text
stringlengths
14
6.51M
Unit AdvClassLists; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses StringSupport, AdvObjects, AdvPointers, AdvIterators; Type TAdvClassList = Class(TAdvPointerList) Private Function GetClassByIndex(Const iIndex : Integer): TClass; Procedure SetClassByIndex(Const iIndex : Integer; Const Value : TClass); Protected Function ItemClass : TAdvObjectClass; Virtual; Public Function Iterator : TAdvIterator; Override; Function Add(Const aClass : TClass) : Integer; Procedure AddAll(Const oClassList : TAdvClassList); Procedure AddArray(Const aClasses : Array Of TClass); Function IndexByClassType(aClass : TClass) : Integer; Function ExistsByClassType(aClass : TClass) : Boolean; Function Find(Const aClass : TClass; Out iIndex : Integer) : Boolean; Property ClassByIndex[Const iIndex : Integer] : TClass Read GetClassByIndex Write SetClassByIndex; Default; End; TAdvClassListIterator = Class(TAdvObjectClassIterator) Private FClassList : TAdvClassList; FIndex : Integer; Procedure SetClassList(Const Value : TAdvClassList); Public Constructor Create; Override; Destructor Destroy; Override; Procedure First; Override; Procedure Last; Override; Procedure Next; Override; Procedure Back; Override; Function More : Boolean; Override; Function Current : TClass; Override; Property ClassList : TAdvClassList Read FClassList Write SetClassList; End; Implementation Procedure TAdvClassList.AddArray(Const aClasses: Array Of TClass); Var iLoop : Integer; Begin For iLoop := Low(aClasses) To High(aClasses) Do Inherited Add(aClasses[iLoop]); End; Function TAdvClassList.IndexByClassType(aClass: TClass): Integer; Begin If Not Find(aClass, Result) Then Result := -1; End; Function TAdvClassList.ExistsByClassType(aClass : TClass) : Boolean; Begin Result := ExistsByIndex(IndexByClassType(aClass)); End; Function TAdvClassList.Iterator : TAdvIterator; Begin Result := TAdvClassListIterator.Create; TAdvClassListIterator(Result).ClassList := TAdvClassList(Self.Link); End; Function TAdvClassList.Add(Const aClass: TClass): Integer; Begin Result := Inherited Add(Pointer(aClass)); End; Procedure TAdvClassList.AddAll(Const oClassList : TAdvClassList); Var iClassIndex : Integer; Begin For iClassIndex := 0 To oClassList.Count - 1 Do Add(oClassList[iClassIndex]); End; Function TAdvClassList.ItemClass : TAdvObjectClass; Begin // TODO: have to constrain this class to lists of TAdvObjectClass's only to enforce this Result := TAdvObject; End; Function TAdvClassList.GetClassByIndex(Const iIndex : Integer) : TClass; Begin Result := TClass(PointerByIndex[iIndex]); End; Procedure TAdvClassList.SetClassByIndex(Const iIndex : Integer; Const Value : TClass); Begin PointerByIndex[iIndex] := Value; End; Function TAdvClassList.Find(Const aClass: TClass; Out iIndex: Integer): Boolean; Begin Result := Inherited Find(aClass, iIndex) End; Constructor TAdvClassListIterator.Create; Begin Inherited; FClassList := Nil; End; Destructor TAdvClassListIterator.Destroy; Begin FClassList.Free; Inherited; End; Procedure TAdvClassListIterator.First; Begin Inherited; FIndex := 0; End; Procedure TAdvClassListIterator.Last; Begin Inherited; FIndex := FClassList.Count - 1; End; Procedure TAdvClassListIterator.Next; Begin Inherited; Inc(FIndex); End; Procedure TAdvClassListIterator.Back; Begin Inherited; Dec(FIndex); End; Function TAdvClassListIterator.Current : TClass; Begin Result := FClassList[FIndex]; End; Function TAdvClassListIterator.More : Boolean; Begin Result := FClassList.ExistsByIndex(FIndex); End; Procedure TAdvClassListIterator.SetClassList(Const Value : TAdvClassList); Begin FClassList.Free; FClassList := Value; End; End. // AdvClassLists //
unit PublicRule; interface uses Windows, SysUtils, Classes, DBClient,DBGrids,Dialogs,ComObj,Graphics,math,StdCtrls; //格式化字段名称 procedure FormatDisplaylable(vDataSet: Tclientdataset; vFields: string); //导出Excel方法 procedure DBGridExport(GRID:TDBGRID;vFileName:string=''); //返回记录数据网格列显示最大宽度是否成功 function DBGridRecordSize(mColumn: TColumn): Boolean; //返回数据网格自动适应宽度是否成功 function DBGridAutoSize(mDBGrid: TDBGrid;mOffset: Integer = 10): Boolean; //初始化表格的font style procedure InitDBGrid(mDBGrid: TDBGrid; vFields: string=''); //初始化科室列表 procedure InitDeptComboxList(vCode,vName,vTabelName: string; vCombox: TComboBox;vSortField: string=''); function GetComboxItemNo(vCombox: TComboBox): string; //格式化时间格式 function DataFormatSet():TFormatSettings; implementation uses dm,Variants; function DataFormatSet():TFormatSettings; var settings: TFormatSettings; begin //解决不同系统时间格式不一致的问题 GetLocaleFormatSettings(GetUserDefaultLCID, settings); settings.DateSeparator := '-'; settings.TimeSeparator := ':'; settings.ShortDateFormat := 'yyyy-mm-dd'; settings.ShortTimeFormat := 'hh:nn:ss'; result := settings; end; function GetComboxItemNo(vCombox: TComboBox): string; begin result := inttostr(Integer(vCombox.Items.Objects[vCombox.ItemIndex])); end; procedure InitDeptComboxList(vCode,vName,vTabelName: string; vCombox: TComboBox;vSortField: string=''); var aitemname: string; aitemno: integer; alist: Tstringlist; asql: string; begin if vSortField='' then vSortField := vCode; vCombox.Items.Clear; asql := format('select %s,%s from %s order by %s',[vCode,vName,vTabelName,vSortField]); with dm.GetDataSet(asql) do begin if recordcount = 0 then exit; while not eof do begin aitemno := fields[0].AsInteger; aitemname := fields[1].AsString; vCombox.Items.AddObject(aitemname,TObject(aitemno)); next; end; vCombox.ItemIndex := 0; end; end; function DBGridRecordSize(mColumn: TColumn): Boolean; { 返回记录数据网格列显示最大宽度是否成功 } begin Result := False; if not Assigned(mColumn.Field) then Exit; mColumn.Field.Tag := Max(mColumn.Field.Tag, TDBGrid(mColumn.Grid).Canvas.TextWidth(mColumn.Field.DisplayText)); Result := True; end; { DBGridRecordSize } function DBGridAutoSize(mDBGrid: TDBGrid;mOffset: Integer = 10): Boolean; { 返回数据网格自动适应宽度是否成功 } var I: Integer; begin Result := False; if not Assigned(mDBGrid) then Exit; if not Assigned(mDBGrid.DataSource) then Exit; if not Assigned(mDBGrid.DataSource.DataSet) then Exit; if not mDBGrid.DataSource.DataSet.Active then Exit; for I := 0 to mDBGrid.Columns.Count - 1 do begin if not mDBGrid.Columns[I].Visible then Continue; if Assigned(mDBGrid.Columns[I].Field) then mDBGrid.Columns[I].Width := Max(mDBGrid.Columns[I].Field.Tag, mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption)) + mOffset else mDBGrid.Columns[I].Width := mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption) + mOffset; mDBGrid.Refresh; end; Result := True; end; { DBGridAutoSize } procedure InitDBGrid(mDBGrid: TDBGrid; vFields: string=''); begin //字体格式 mDBGrid.Font.Size := 12; mDBGrid.TitleFont.Size := 12; mDBGrid.Options := [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgRowSelect, dgConfirmDelete, dgCancelOnExit]; //mDBGrid.TitleFont.Style := [fsBold]; //标题格式化显示 FormatDisplaylable(Tclientdataset(mDBGrid.datasource.dataset),vFields); //自适应列宽 DBGridAutoSize(mDBGrid,20); end; procedure FormatDisplaylable(vDataSet: Tclientdataset; vFields: string); var alist: Tstringlist; i: integer; begin if vFields = '' then exit; alist := tstringlist.Create; alist.CommaText := vFields; for i := 0 to alist.Count - 1 do vDataSet.Fields[i].DisplayLabel := alist[i]; end; procedure DBGridExport(GRID:TDBGRID;vFileName:string=''); var //DBGRID控件内容存储到EXCEL 只有第一行有标题 EclApp:Variant; XlsFileName:String; sh:olevariant; i,j:integer; s:string; savedailog:TSaveDialog; begin savedailog:=TSaveDialog.Create(nil); savedailog.Filter:='Excel files (*.xls)|*.XlS'; savedailog.FileName := vFileName; if savedailog.Execute then begin xlsfilename:=savedailog.FileName; savedailog.Free; end else begin savedailog.Free; exit; end; try eclapp:=createOleObject('Excel.Application'); sh:=CreateOleObject('Excel.Sheet'); except showmessage('您的机器里未安装Microsoft Excel。'); exit; end; try sh:=eclapp.workBooks.add; With Grid.DataSource.DataSet do begin First; i:=GRID.FieldCount-1; j:=i div 26; s:=''; if j>0 then s:=s+chr(64+j); for i:=0 to grid.FieldCount-1 do begin if grid.Fields[i].Visible then begin eclapp.cells[2,i+1]:=grid.Fields[i].DisplayName; if GRID.Fields[i].DisplayWidth>80 then eclapp.columns[i+1].Columnwidth:=80 else eclapp.columns[i+1].Columnwidth:=GRID.Fields[i].DisplayWidth+0.3; eclapp.cells[2,i+1].Font.Color:=clRed; //转EXCEL时过长的数字有截取现象。已改为用‘来解决,所以下面不需要了。 // if (grid.Fields[i].DisplayName='身份证号') or (grid.Fields[i].DisplayName='银行帐号') then begin // eclapp.columns[i+1].NumberFormat:='@'; // end; end; end; for i:=1 to RecordCount do begin for j:=0 to grid.FieldCount-1 do if grid.Fields[j].Visible then if GRID.Fields[j].DisplayText>'' then begin // if length(grid.Fields[j].DisplayText)>=15 then // eclapp.cells[i*2+1,j+1].NumberFormatLocal:='@'; eclapp.cells[i+2,j+1]:=grid.Fields[j].DisplayText; end; Next; end; end; sh.saveas(xlsfilename); sh.close; eclapp.quit; ShowMessage('输出 Excel 文件已完成...'); except showmessage('Excel系统出错!!!'); sh.close; eclapp.quit; exit; end; end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT types } unit dhttypes; interface uses classes,classes2,sysutils,windows,keywfunc,blcksock; type precord_DHT_keywordFilePublishReq=^record_DHT_keywordFilePublishReq; record_DHT_keywordFilePublishReq=record keyW:string; crc:word; // last two bytes of 20 byte sha1 fileHashes:tmystringlist; end; type precord_dht_source=^record_dht_source; record_dht_source=record ip:cardinal; raw:string; lastSeen:cardinal; prev,next:precord_dht_source; end; type precord_dht_outpacket=^record_dht_outpacket; record_dht_outpacket=record destIP:cardinal; destPort:word; buffer:string; end; type precord_DHT_firewallcheck=^record_DHT_firewallcheck; record_DHT_firewallcheck=record RemoteIp:cardinal; RemoteUDPPort:word; RemoteTCPPort:word; started:cardinal; sockt:HSocket; end; type precord_DHT_hash=^record_dht_hash; record_dht_hash=record hashValue:array[0..19] of byte; crc:word; count:word; // number of items lastSeen:cardinal; firstSource:precord_dht_source; prev,next:precord_dht_hash; end; type precord_DHT_hashfile=^record_DHT_hashfile; record_DHT_hashfile=record HashValue:array[0..19] of byte; end; type precord_dht_storedfile=^record_dht_storedfile; record_dht_storedfile=record hashValue:array[0..19] of byte; crc:word; amime:byte; ip:cardinal; //last publish source is available immediately port:word; count:word; lastSeen:cardinal; fsize:int64; param1,param3:cardinal; info:string; numKeywords:byte; keywords:PWordsArray; prev,next:precord_dht_storedfile; end; type PDHTKeyWordItem=^TDHTKeyWordItem; TDHTKeywordItem = packed record share : precord_dht_storedfile; prev, next : PDHTKeywordItem; end; PDHTKeyword = ^TDHTKeyword; TDHTKeyword = packed record // structure that manages one keyword keyword : array of char; // keyword count : cardinal; crc : word; firstitem : PDHTKeywordItem; // pointer to first full item prev, next : PDHTKeyword; // pointer to previous and next PKeyword items in global list end; type tdhtsearchtype=( UNDEFINED, NODE, NODECOMPLETE, KEYWORD, STOREFILE, STOREKEYWORD, FINDSOURCE ); implementation end.
unit BaseFacades; interface uses Classes, BaseObjects, Registrator, Options, DBGate, BaseDicts, ClientDicts, BaseActions, ActnList, Version, Organization, BaseObjectType, CommonReport, ClientType, PasswordForm, Controls, StdCtrls, Variants, Windows; type TVersionChanged = procedure (OldVersion, NewVersion: TVersion) of object; TBaseFacade = class(TComponent) private FDataPosters: TDataPosters; FActionList: TBaseActionList; FSystemSettings: TSystemSettings; FDBGates: TDBGates; FSettingsFileName: string; FClientAppTypeID: integer; FAllVersions: TVersions; FAllReports: TBaseReports; FActiveVersion: TVersion; FClientAppTypeName: string; FClientAppTypes: TClientTypes; FOnAfterSettingsLoaded: TNotifyEvent; FOnActiveVersionChanged: TVersionChanged; FUserName: string; FPwd: string; FAuthorizationError: string; function GetDBGates: TDBGates; function GetSystemSettings: TSystemSettings; procedure SetClientAppTypeID(const Value: integer); function GetActionByClassType( ABaseActionClass: TBaseActionClass): TAction; function GetAllVersions: TVersions; function GetAllOrganizations: TOrganizations; function GetAllReports: TBaseReports; function GetClientAppTypes: TClientTypes; function GetActiveVersion: TVersion; protected FRegistrator: TRegistrator; FAllDicts: TDicts; FAllOrganizations: TOrganizations; FAllObjectsTypes: TObjectTypes; FObjectTypeMapper: TObjectTypeMapper; function GetRegistrator: TRegistrator; virtual; function GetDataPosterByClassType( ADataPosterClass: TDataPosterClass): TDataPoster; virtual; function GetAllDicts: TDicts; virtual; function GetAllObjectTypes: TObjectTypes; virtual; function getObjectTypeMapper: TObjectTypeMapper; virtual; procedure SetActiveVersion(const Value: TVersion); virtual; procedure DoVersionChanged(AOldVersion, ANewVersion: TVersion); virtual; public property UserName: string read FUserName; property Pwd: string read FPwd; property DataPosterByClassType[ADataPosterClass: TDataPosterClass]: TDataPoster read GetDataPosterByClassType; property ActionByClassType[ABaseActionClass: TBaseActionClass]: TAction read GetActionByClassType; property Registrator: TRegistrator read GetRegistrator; property SystemSettings: TSystemSettings read GetSystemSettings; // где сохранять настройки - переопределяется в потомках фасада property SettingsFileName: string read FSettingsFileName write FSettingsFileName; procedure SaveSettings; virtual; procedure LoadSettings; virtual; property OnAfterSettingsLoaded: TNotifyEvent read FOnAfterSettingsLoaded write FOnAfterSettingsLoaded; property DBGates: TDBGates read GetDBGates; function ExecuteQuery(const ASQL: string; var AResult: OleVariant): integer; overload; function ExecuteQuery(const ASQL: string): integer; overload; // идентификатор типа клиента property ClientAppTypeID: integer read FClientAppTypeID write SetClientAppTypeID; // наименование типа клиента property ClientAppTypeName: string read FClientAppTypeName write FClientAppTypeName; // все справочники property AllDicts: TDicts read GetAllDicts; // все организации property AllOrganizations: TOrganizations read GetAllOrganizations; // список типов объектов property AllObjectTypes: TObjectTypes read GetAllObjectTypes; // property AllVersions: TVersions read GetAllVersions; // версия property ActiveVersion: TVersion read GetActiveVersion write SetActiveVersion; property OnActiveVersionChanged: TVersionChanged read FOnActiveVersionChanged write FOnActiveVersionChanged; // все отчеты property AllReports: TBaseReports read GetAllReports; // все типы клиентов property AllClientTypes: TClientTypes read GetClientAppTypes; // связыватель объектов со всякими их характеристиками в БД property ObjectTypeMapper: TObjectTypeMapper read getObjectTypeMapper; function Authorize: boolean; property AuthorizationError: string read FAuthorizationError write FAuthorizationError; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses SysUtils, ReadCommandLine; { TBaseFacade } function TBaseFacade.GetRegistrator: TRegistrator; begin if not Assigned(FRegistrator) then FRegistrator := TRegistrator.Create; Result := FRegistrator; end; destructor TBaseFacade.Destroy; begin FreeAndNil(FObjectTypeMapper); FreeAndNil(FDataPosters); FreeAndNil(FActionList); FreeAndNil(FSystemSettings); FreeAndNil(FDBGates); FreeAndNil(FRegistrator); FreeAndNil(FClientAppTypes); inherited; end; function TBaseFacade.GetDBGates: TDBGates; begin if not Assigned(FDBGates) then FDBGates := TDBGates.Create(Self); Result := FDBGates; end; function TBaseFacade.GetSystemSettings: TSystemSettings; begin if not Assigned(FSystemSettings) then FSystemSettings := TSystemSettings.Create(SettingsFileName); Result := FSystemSettings; end; procedure TBaseFacade.SetClientAppTypeID(const Value: integer); begin FClientAppTypeID := Value; DBGates.ClientAppTypeID := FClientAppTypeID; end; function TBaseFacade.GetAllDicts: TDicts; begin if not Assigned(FAllDicts) then FAllDicts := TClientDicts.Create; Result := FAllDicts; end; function TBaseFacade.GetDataPosterByClassType( ADataPosterClass: TDataPosterClass): TDataPoster; begin if not Assigned(FDataPosters) then FDataPosters := TDataPosters.Create; Result := FDataPosters.DataPosterByClassType[ADataPosterClass]; end; function TBaseFacade.GetActionByClassType( ABaseActionClass: TBaseActionClass): TAction; begin if not Assigned(FActionList) then FActionList := TBaseActionList.Create(Self); Result := FActionList.ActionByClassType[ABaseActionClass]; end; function TBaseFacade.GetAllVersions: TVersions; begin if not Assigned(FAllVersions) then begin FAllVersions := TVersions.Create; FAllVersions.Reload('', true); end; Result := FAllVersions; end; function TBaseFacade.GetAllOrganizations: TOrganizations; begin if not Assigned (FAllOrganizations) then begin FAllOrganizations := TOrganizations.Create; FAllOrganizations.Reload('', true); end; Result := FAllOrganizations; end; function TBaseFacade.GetAllObjectTypes: TObjectTypes; begin if not Assigned (FAllObjectsTypes) then begin FAllObjectsTypes := TObjectTypes.Create; FAllObjectsTypes.Reload('', true); end; Result := FAllObjectsTypes; end; function TBaseFacade.ExecuteQuery(const ASQL: string; var AResult: OleVariant): integer; begin Result := DBGates.ExecuteQuery(ASQL, AResult); end; function TBaseFacade.GetAllReports: TBaseReports; begin if not Assigned(FAllReports) then FAllReports := TBaseReports.Create(Self); Result := FAllReports; end; function TBaseFacade.GetClientAppTypes: TClientTypes; begin if not Assigned(FClientAppTypes) then begin FClientAppTypes := TClientTypes.Create; FClientAppTypes.Reload('', true); end; Result := FClientAppTypes; end; function TBaseFacade.getObjectTypeMapper: TObjectTypeMapper; begin if not Assigned(FObjectTypeMapper) then FObjectTypeMapper := TDefaultObjectTypeMapper.Create; Result := FObjectTypeMapper; end; procedure TBaseFacade.SetActiveVersion(const Value: TVersion); var old: TVersion; begin if FActiveVersion <> Value then begin old := FActiveVersion; FActiveVersion := Value; DoVersionChanged(old, FActiveVersion); if Assigned(OnActiveVersionChanged) then OnActiveVersionChanged(old, FActiveVersion); end; end; procedure TBaseFacade.SaveSettings; begin SystemSettings.SaveAllToFile; end; procedure TBaseFacade.LoadSettings; begin if Assigned(FOnAfterSettingsLoaded) then FOnAfterSettingsLoaded(Self); end; function TBaseFacade.ExecuteQuery(const ASQL: string): integer; begin Result := DBGates.ExecuteQuery(ASQL); end; function TBaseFacade.GetActiveVersion: TVersion; begin if not Assigned(FActiveVersion) then FActiveVersion := AllVersions.ItemsById[0] as TVersion; Result := FActiveVersion; end; procedure TBaseFacade.DoVersionChanged(AOldVersion, ANewVersion: TVersion); begin end; function TBaseFacade.Authorize: Boolean; const cnMaxUserNameLen = 254; var bWithForm: Boolean; sUserName: string; dwUserNameLen: DWORD; begin Result := false; bWithForm := false; FUserName := ''; FPwd := ''; {$IFOPT D+} // получаем имя пользователя и пароль if Assigned(TCommandLineParams.GetInstance.FindParam('-u')) then begin FUserName := TCommandLineParams.GetInstance.ParamValues['-u']; end else begin dwUserNameLen := cnMaxUserNameLen - 1; SetLength(sUserName, cnMaxUserNameLen); GetUserName(PChar(sUserName), dwUserNameLen); SetLength(sUserName, dwUserNameLen); FUserName:=sUserName; end; {$ELSE} if not Assigned(TCommandLineParams.GetInstance.FindParam('-a')) then begin dwUserNameLen := cnMaxUserNameLen - 1; SetLength(sUserName, cnMaxUserNameLen); GetUserName(PChar(sUserName), dwUserNameLen); SetLength(sUserName, dwUserNameLen); FUserName:=sUserName; end else begin frmPassword := TfrmPassword.Create(Self); bWithForm := true; if frmPassword.ShowModal = mrOk then begin FUserName := frmPassword.UserName; FPwd := frmPassword.Pwd; end; end; {$ENDIF} if (trim(FUserName) = '') {and (Trim(FPwd) = '')} then Exit; try DBGates.InitializeServer(UserName, ''); DBGates.EmployeeTabNumber := UserName; if DBGates.Autorized then if DBGates.EmployeePriority > 0 then begin Result := true; if bWithForm then begin frmPassword.Status := 'Здравствуйте, ' + DBGates.EmployeeName; Sleep(100); frmPassword.Close; end; end else if bWithForm then begin frmPassword.Status := 'Авторизация завершилась неудачей. Обратитесь в к.320'; Result := Authorize; end; except on E: Exception do begin FAuthorizationError := e.Message; if bWithForm then frmPassword.Status := FAuthorizationError; Result := false; end; end; end; constructor TBaseFacade.Create(AOwner: TComponent); begin inherited; {$IFOPT D+} if (Assigned(TCommandLineParams.GetInstance.FindParam('-test'))) then DBGates.ServerClassString := 'RiccServerTest.CommonServerTest' else DBGates.ServerClassString := 'RiccServer.CommonServer'; {$ELSE} DBGates.ServerClassString := 'RiccServer.CommonServer'; {$ENDIF} DBGates.AutorizationMethod := amEnum; DBGates.NewAutorizationMode := false; end; end.
unit UProcess; interface uses System.Classes, Vcl.Graphics, UDefinitions; type TProcess = class(TThread) public constructor Create(D: TDefinitions; const InternalDelphiVersionKey: string; Flag64bit: Boolean); protected procedure Execute; override; private D: TDefinitions; InternalDelphiVersionKey: string; Flag64bit: Boolean; MSBuildExe: string; procedure Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); procedure FindMSBuild; procedure Compile; procedure CompilePackage(P: TPackage; const aBat, aPlatform: string); procedure AddLibrary; procedure PublishFiles(P: TPackage; const aPlatform: string); procedure RegisterBPL(const aPackage: string); procedure OnLine(const Text: string); end; implementation uses System.Win.Registry, Winapi.Windows, System.SysUtils, UCommon, UCmdExecBuffer, System.IOUtils, Winapi.ShlObj, UFrm; constructor TProcess.Create(D: TDefinitions; const InternalDelphiVersionKey: string; Flag64bit: Boolean); begin inherited Create(True); FreeOnTerminate := True; Self.D := D; Self.InternalDelphiVersionKey := InternalDelphiVersionKey; Self.Flag64bit := Flag64bit; end; procedure TProcess.Execute; begin try FindMSBuild; //find MSBUILD.EXE to use for compilation Log('COMPILE COMPONENT...'); Compile; if D.AddLibrary then AddLibrary; //add library paths to Delphi Log('COMPONENT INSTALLED!', True, clGreen); except on E: Exception do Log('ERROR: '+E.Message, True, clRed); end; Synchronize( procedure begin Frm.SetButtons(True); end); end; procedure TProcess.Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); begin Synchronize( procedure begin Frm.Log(A, bBold, Color); end); end; procedure TProcess.Compile; var R: TRegistry; aRootDir: string; aBat: string; P: TPackage; begin R := TRegistry.Create; try R.RootKey := HKEY_CURRENT_USER; if not R.OpenKeyReadOnly(BDS_KEY+'\'+InternalDelphiVersionKey) then raise Exception.Create('Main registry of Delphi version not found'); aRootDir := R.ReadString('RootDir'); if aRootDir='' then raise Exception.Create('Unable to get Delphi root folder'); finally R.Free; end; if not DirectoryExists(aRootDir) then raise Exception.Create('Delphi root folder does not exist'); aBat := TPath.Combine(aRootDir, 'bin\rsvars.bat'); if not FileExists(aBat) then raise Exception.Create('Internal Delphi batch file "rsvars" not found'); if Flag64bit and not FileExists(TPath.Combine(aRootDir, 'bin\dcc64.exe')) then raise Exception.Create('Delphi 64 bit compiler not found'); for P in D.Packages do begin CompilePackage(P, aBat, 'Win32'); if Flag64bit and P.Allow64bit then CompilePackage(P, aBat, 'Win64'); if P.Install then RegisterBPL(P.Name); end; end; procedure TProcess.CompilePackage(P: TPackage; const aBat, aPlatform: string); var C: TCmdExecBuffer; begin Log('Compile package '+P.Name+' ('+aPlatform+')'); C := TCmdExecBuffer.Create; try C.OnLine := OnLine; C.CommandLine := Format('""%s" & "%s" "%s.dproj" /t:build /p:config=Release /p:platform=%s"', [aBat, MSBuildExe, AppDir+P.Name, aPlatform]); C.WorkDir := AppDir; if not C.Exec then raise Exception.Create('Could not execute MSBUILD'); if C.ExitCode<>0 then raise Exception.CreateFmt('Error compiling package %s (Exit Code %d)', [P.Name, C.ExitCode]); finally C.Free; end; //publish files PublishFiles(P, aPlatform); Log(''); end; procedure TProcess.OnLine(const Text: string); begin //event for command line execution (line-by-line) Log(TrimRight(Text), False); end; procedure TProcess.PublishFiles(P: TPackage; const aPlatform: string); var A, aSource, aDest: string; begin for A in P.PublishFiles do begin aSource := AppDir+A; aDest := AppDir+aPlatform+'\Release\'+A; Log(Format('Copy file %s to %s', [A{aSource}, aDest]), False, clPurple); TFile.Copy(aSource, aDest, True); end; end; procedure TProcess.AddLibrary; procedure AddKey(const aPlatform: string); var Key, A, Dir: string; R: TRegistry; const SEARCH_KEY = 'Search Path'; begin Log('Add library path to '+aPlatform); Key := BDS_KEY+'\'+InternalDelphiVersionKey+'\Library\'+aPlatform; Dir := AppDir+aPlatform+'\Release'; R := TRegistry.Create; try R.RootKey := HKEY_CURRENT_USER; if not R.OpenKey(Key, False) then raise Exception.Create('Registry key for library '+aPlatform+' not found'); A := R.ReadString(SEARCH_KEY); if not HasInList(Dir, A) then R.WriteString(SEARCH_KEY, A+';'+Dir); finally R.Free; end; end; begin AddKey('Win32'); if Flag64bit then AddKey('Win64'); end; function GetPublicDocs: string; var Path: array[0..MAX_PATH] of Char; begin if not ShGetSpecialFolderPath(0, Path, CSIDL_COMMON_DOCUMENTS, False) then raise Exception.Create('Could not find Public Documents folder location') ; Result := Path; end; procedure TProcess.RegisterBPL(const aPackage: string); var R: TRegistry; BplDir, PublicPrefix: string; FS: TFormatSettings; begin Log('Install BPL into IDE of '+aPackage); FS := TFormatSettings.Create; FS.DecimalSeparator := '.'; if StrToFloat(InternalDelphiVersionKey, FS)<=12 then //Delphi XE5 or below PublicPrefix := 'RAD Studio' else PublicPrefix := 'Embarcadero\Studio'; BplDir := TPath.Combine(GetPublicDocs, PublicPrefix+'\'+InternalDelphiVersionKey+'\Bpl'); if not DirectoryExists(BplDir) then raise Exception.CreateFmt('Public Delphi folder not found at: %s', [BplDir]); R := TRegistry.Create; try R.RootKey := HKEY_CURRENT_USER; if not R.OpenKey(BDS_KEY+'\'+InternalDelphiVersionKey+'\Known Packages', False) then raise Exception.Create('Know Packages registry section not found'); R.WriteString(TPath.Combine(BplDir, aPackage+'.bpl'), D.CompName); finally R.Free; end; end; procedure TProcess.FindMSBuild; var R: TRegistry; S: TStringList; I: Integer; Dir, aFile: string; Found: Boolean; const TOOLS_KEY = 'Software\Microsoft\MSBUILD\ToolsVersions'; begin R := TRegistry.Create; try R.RootKey := HKEY_LOCAL_MACHINE; if not R.OpenKeyReadOnly(TOOLS_KEY) then raise Exception.Create('MSBUILD not found'); S := TStringList.Create; try R.GetKeyNames(S); R.CloseKey; if S.Count=0 then raise Exception.Create('There is no .NET Framework version available'); S.Sort; //sort msbuild versions Found := False; for I := S.Count-1 downto 0 do //iterate versions from last to first begin if not R.OpenKeyReadOnly(TOOLS_KEY+'\'+S[I]) then raise Exception.Create('Internal error on reading .NET version key'); Dir := R.ReadString('MSBuildToolsPath'); R.CloseKey; if Dir<>'' then begin aFile := TPath.Combine(Dir, 'MSBUILD.EXE'); if FileExists(aFile) then begin //msbuild found Found := True; Break; end; end; end; finally S.Free; end; finally R.Free; end; if not Found then raise Exception.Create('MSBUILD not found in any .NET Framework version'); MSBuildExe := aFile; end; end.
unit MailMan; interface type HCkEmailBundle = Pointer; HCkSshKey = Pointer; HCkCsp = Pointer; HCkStringBuilder = Pointer; HCkCert = Pointer; HCkSocket = Pointer; HCkSecureString = Pointer; HCkString = Pointer; HCkMailMan = Pointer; HCkByteData = Pointer; HCkXmlCertVault = Pointer; HCkPrivateKey = Pointer; HCkSsh = Pointer; HCkEmail = Pointer; HCkStringArray = Pointer; HCkTask = Pointer; HCkJsonObject = Pointer; HCkBinData = Pointer; function CkMailMan_Create: HCkMailMan; stdcall; procedure CkMailMan_Dispose(handle: HCkMailMan); stdcall; function CkMailMan_getAbortCurrent(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAbortCurrent(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getAllOrNone(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAllOrNone(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getAutoFix(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAutoFix(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getAutoGenMessageId(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAutoGenMessageId(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getAutoSmtpRset(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAutoSmtpRset(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getAutoUnwrapSecurity(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putAutoUnwrapSecurity(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getClientIpAddress(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putClientIpAddress(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__clientIpAddress(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getConnectFailReason(objHandle: HCkMailMan): Integer; stdcall; function CkMailMan_getConnectTimeout(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putConnectTimeout(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getDebugLogFilePath(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putDebugLogFilePath(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__debugLogFilePath(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getDsnEnvid(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putDsnEnvid(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__dsnEnvid(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getDsnNotify(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putDsnNotify(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__dsnNotify(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getDsnRet(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putDsnRet(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__dsnRet(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getEmbedCertChain(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putEmbedCertChain(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getFilter(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putFilter(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__filter(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getHeartbeatMs(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putHeartbeatMs(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getHeloHostname(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHeloHostname(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__heloHostname(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getHttpProxyAuthMethod(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHttpProxyAuthMethod(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__httpProxyAuthMethod(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getHttpProxyDomain(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHttpProxyDomain(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__httpProxyDomain(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getHttpProxyHostname(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHttpProxyHostname(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__httpProxyHostname(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getHttpProxyPassword(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHttpProxyPassword(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__httpProxyPassword(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getHttpProxyPort(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putHttpProxyPort(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getHttpProxyUsername(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putHttpProxyUsername(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__httpProxyUsername(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getImmediateDelete(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putImmediateDelete(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getIncludeRootCert(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putIncludeRootCert(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getIsPop3Connected(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_getIsSmtpConnected(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_getLastErrorHtml(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__lastErrorHtml(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getLastErrorText(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__lastErrorText(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getLastErrorXml(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__lastErrorXml(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getLastMethodSuccess(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putLastMethodSuccess(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getLastSendQFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__lastSendQFilename(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getLastSmtpStatus(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_getLogMailReceivedFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putLogMailReceivedFilename(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__logMailReceivedFilename(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getLogMailSentFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putLogMailSentFilename(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__logMailSentFilename(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getMailHost(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putMailHost(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__mailHost(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getMailPort(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putMailPort(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getMaxCount(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putMaxCount(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getOAuth2AccessToken(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putOAuth2AccessToken(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__oAuth2AccessToken(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getOpaqueSigning(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putOpaqueSigning(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getP7mEncryptAttachFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putP7mEncryptAttachFilename(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__p7mEncryptAttachFilename(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getP7mSigAttachFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putP7mSigAttachFilename(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__p7mSigAttachFilename(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getP7sSigAttachFilename(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putP7sSigAttachFilename(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__p7sSigAttachFilename(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getPercentDoneScale(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putPercentDoneScale(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getPop3SessionId(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_getPop3SessionLog(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__pop3SessionLog(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getPop3SPA(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putPop3SPA(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getPop3SslServerCertVerified(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_getPop3Stls(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putPop3Stls(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getPopPassword(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putPopPassword(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__popPassword(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getPopPasswordBase64(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putPopPasswordBase64(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__popPasswordBase64(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getPopSsl(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putPopSsl(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getPopUsername(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putPopUsername(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__popUsername(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getPreferIpv6(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putPreferIpv6(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getReadTimeout(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putReadTimeout(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getRequireSslCertVerify(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putRequireSslCertVerify(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getResetDateOnLoad(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putResetDateOnLoad(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getSendBufferSize(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSendBufferSize(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getSendIndividual(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putSendIndividual(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getSizeLimit(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSizeLimit(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getSmtpAuthMethod(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSmtpAuthMethod(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__smtpAuthMethod(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSmtpFailReason(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__smtpFailReason(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSmtpHost(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSmtpHost(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__smtpHost(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSmtpLoginDomain(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSmtpLoginDomain(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__smtpLoginDomain(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSmtpPassword(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSmtpPassword(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__smtpPassword(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getSmtpPipelining(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putSmtpPipelining(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getSmtpPort(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSmtpPort(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getSmtpSessionLog(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__smtpSessionLog(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getSmtpSsl(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putSmtpSsl(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getSmtpSslServerCertVerified(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_getSmtpUsername(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSmtpUsername(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__smtpUsername(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSocksHostname(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSocksHostname(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__socksHostname(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSocksPassword(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSocksPassword(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__socksPassword(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getSocksPort(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSocksPort(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getSocksUsername(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSocksUsername(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__socksUsername(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getSocksVersion(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSocksVersion(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getSoRcvBuf(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSoRcvBuf(objHandle: HCkMailMan; newPropVal: Integer); stdcall; function CkMailMan_getSoSndBuf(objHandle: HCkMailMan): Integer; stdcall; procedure CkMailMan_putSoSndBuf(objHandle: HCkMailMan; newPropVal: Integer); stdcall; procedure CkMailMan_getSslAllowedCiphers(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSslAllowedCiphers(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__sslAllowedCiphers(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getSslProtocol(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putSslProtocol(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__sslProtocol(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getStartTLS(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putStartTLS(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getStartTLSifPossible(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putStartTLSifPossible(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getTlsCipherSuite(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__tlsCipherSuite(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getTlsPinSet(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; procedure CkMailMan_putTlsPinSet(objHandle: HCkMailMan; newPropVal: PWideChar); stdcall; function CkMailMan__tlsPinSet(objHandle: HCkMailMan): PWideChar; stdcall; procedure CkMailMan_getTlsVersion(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__tlsVersion(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_getUseApop(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putUseApop(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; function CkMailMan_getVerboseLogging(objHandle: HCkMailMan): wordbool; stdcall; procedure CkMailMan_putVerboseLogging(objHandle: HCkMailMan; newPropVal: wordbool); stdcall; procedure CkMailMan_getVersion(objHandle: HCkMailMan; outPropVal: HCkString); stdcall; function CkMailMan__version(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_AddPfxSourceData(objHandle: HCkMailMan; pfxData: HCkByteData; password: PWideChar): wordbool; stdcall; function CkMailMan_AddPfxSourceFile(objHandle: HCkMailMan; pfxFilePath: PWideChar; password: PWideChar): wordbool; stdcall; function CkMailMan_CheckMail(objHandle: HCkMailMan): Integer; stdcall; function CkMailMan_CheckMailAsync(objHandle: HCkMailMan): HCkTask; stdcall; procedure CkMailMan_ClearBadEmailAddresses(objHandle: HCkMailMan); stdcall; procedure CkMailMan_ClearPop3SessionLog(objHandle: HCkMailMan); stdcall; procedure CkMailMan_ClearSmtpSessionLog(objHandle: HCkMailMan); stdcall; function CkMailMan_CloseSmtpConnection(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_CloseSmtpConnectionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_CopyMail(objHandle: HCkMailMan): HCkEmailBundle; stdcall; function CkMailMan_CopyMailAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_DeleteBundle(objHandle: HCkMailMan; emailBundle: HCkEmailBundle): wordbool; stdcall; function CkMailMan_DeleteBundleAsync(objHandle: HCkMailMan; emailBundle: HCkEmailBundle): HCkTask; stdcall; function CkMailMan_DeleteByMsgnum(objHandle: HCkMailMan; msgnum: Integer): wordbool; stdcall; function CkMailMan_DeleteByMsgnumAsync(objHandle: HCkMailMan; msgnum: Integer): HCkTask; stdcall; function CkMailMan_DeleteByUidl(objHandle: HCkMailMan; uidl: PWideChar): wordbool; stdcall; function CkMailMan_DeleteByUidlAsync(objHandle: HCkMailMan; uidl: PWideChar): HCkTask; stdcall; function CkMailMan_DeleteEmail(objHandle: HCkMailMan; email: HCkEmail): wordbool; stdcall; function CkMailMan_DeleteEmailAsync(objHandle: HCkMailMan; email: HCkEmail): HCkTask; stdcall; function CkMailMan_DeleteMultiple(objHandle: HCkMailMan; uidlArray: HCkStringArray): wordbool; stdcall; function CkMailMan_DeleteMultipleAsync(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkTask; stdcall; function CkMailMan_FetchByMsgnum(objHandle: HCkMailMan; msgnum: Integer): HCkEmail; stdcall; function CkMailMan_FetchByMsgnumAsync(objHandle: HCkMailMan; msgnum: Integer): HCkTask; stdcall; function CkMailMan_FetchEmail(objHandle: HCkMailMan; uidl: PWideChar): HCkEmail; stdcall; function CkMailMan_FetchEmailAsync(objHandle: HCkMailMan; uidl: PWideChar): HCkTask; stdcall; function CkMailMan_FetchMime(objHandle: HCkMailMan; uidl: PWideChar; outData: HCkByteData): wordbool; stdcall; function CkMailMan_FetchMimeAsync(objHandle: HCkMailMan; uidl: PWideChar): HCkTask; stdcall; function CkMailMan_FetchMimeBd(objHandle: HCkMailMan; uidl: PWideChar; mimeData: HCkBinData): wordbool; stdcall; function CkMailMan_FetchMimeBdAsync(objHandle: HCkMailMan; uidl: PWideChar; mimeData: HCkBinData): HCkTask; stdcall; function CkMailMan_FetchMimeByMsgnum(objHandle: HCkMailMan; msgnum: Integer; outData: HCkByteData): wordbool; stdcall; function CkMailMan_FetchMimeByMsgnumAsync(objHandle: HCkMailMan; msgnum: Integer): HCkTask; stdcall; function CkMailMan_FetchMultiple(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkEmailBundle; stdcall; function CkMailMan_FetchMultipleAsync(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkTask; stdcall; function CkMailMan_FetchMultipleHeaders(objHandle: HCkMailMan; uidlArray: HCkStringArray; numBodyLines: Integer): HCkEmailBundle; stdcall; function CkMailMan_FetchMultipleHeadersAsync(objHandle: HCkMailMan; uidlArray: HCkStringArray; numBodyLines: Integer): HCkTask; stdcall; function CkMailMan_FetchMultipleMime(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkStringArray; stdcall; function CkMailMan_FetchMultipleMimeAsync(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkTask; stdcall; function CkMailMan_FetchSingleHeader(objHandle: HCkMailMan; numBodyLines: Integer; messageNumber: Integer): HCkEmail; stdcall; function CkMailMan_FetchSingleHeaderAsync(objHandle: HCkMailMan; numBodyLines: Integer; messageNumber: Integer): HCkTask; stdcall; function CkMailMan_FetchSingleHeaderByUidl(objHandle: HCkMailMan; numBodyLines: Integer; uidl: PWideChar): HCkEmail; stdcall; function CkMailMan_FetchSingleHeaderByUidlAsync(objHandle: HCkMailMan; numBodyLines: Integer; uidl: PWideChar): HCkTask; stdcall; function CkMailMan_GetAllHeaders(objHandle: HCkMailMan; numBodyLines: Integer): HCkEmailBundle; stdcall; function CkMailMan_GetAllHeadersAsync(objHandle: HCkMailMan; numBodyLines: Integer): HCkTask; stdcall; function CkMailMan_GetBadEmailAddrs(objHandle: HCkMailMan): HCkStringArray; stdcall; function CkMailMan_GetFullEmail(objHandle: HCkMailMan; email: HCkEmail): HCkEmail; stdcall; function CkMailMan_GetFullEmailAsync(objHandle: HCkMailMan; email: HCkEmail): HCkTask; stdcall; function CkMailMan_GetHeaders(objHandle: HCkMailMan; numBodyLines: Integer; fromIndex: Integer; toIndex: Integer): HCkEmailBundle; stdcall; function CkMailMan_GetHeadersAsync(objHandle: HCkMailMan; numBodyLines: Integer; fromIndex: Integer; toIndex: Integer): HCkTask; stdcall; function CkMailMan_GetMailboxCount(objHandle: HCkMailMan): Integer; stdcall; function CkMailMan_GetMailboxCountAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_GetMailboxInfoXml(objHandle: HCkMailMan; outStr: HCkString): wordbool; stdcall; function CkMailMan__getMailboxInfoXml(objHandle: HCkMailMan): PWideChar; stdcall; function CkMailMan_GetMailboxInfoXmlAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_GetMailboxSize(objHandle: HCkMailMan): LongWord; stdcall; function CkMailMan_GetMailboxSizeAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_GetPop3SslServerCert(objHandle: HCkMailMan): HCkCert; stdcall; function CkMailMan_GetSentToEmailAddrs(objHandle: HCkMailMan): HCkStringArray; stdcall; function CkMailMan_GetSizeByUidl(objHandle: HCkMailMan; uidl: PWideChar): Integer; stdcall; function CkMailMan_GetSizeByUidlAsync(objHandle: HCkMailMan; uidl: PWideChar): HCkTask; stdcall; function CkMailMan_GetSmtpSslServerCert(objHandle: HCkMailMan): HCkCert; stdcall; function CkMailMan_GetUidls(objHandle: HCkMailMan): HCkStringArray; stdcall; function CkMailMan_GetUidlsAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_IsSmtpDsnCapable(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_IsSmtpDsnCapableAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_IsUnlocked(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_LastJsonData(objHandle: HCkMailMan): HCkJsonObject; stdcall; function CkMailMan_LoadEml(objHandle: HCkMailMan; emlFilename: PWideChar): HCkEmail; stdcall; function CkMailMan_LoadMbx(objHandle: HCkMailMan; mbxFileName: PWideChar): HCkEmailBundle; stdcall; function CkMailMan_LoadMime(objHandle: HCkMailMan; mimeText: PWideChar): HCkEmail; stdcall; function CkMailMan_LoadQueuedEmail(objHandle: HCkMailMan; path: PWideChar): HCkEmail; stdcall; function CkMailMan_LoadXmlEmail(objHandle: HCkMailMan; filename: PWideChar): HCkEmail; stdcall; function CkMailMan_LoadXmlEmailString(objHandle: HCkMailMan; xmlString: PWideChar): HCkEmail; stdcall; function CkMailMan_LoadXmlFile(objHandle: HCkMailMan; filename: PWideChar): HCkEmailBundle; stdcall; function CkMailMan_LoadXmlString(objHandle: HCkMailMan; xmlString: PWideChar): HCkEmailBundle; stdcall; function CkMailMan_MxLookup(objHandle: HCkMailMan; emailAddress: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMailMan__mxLookup(objHandle: HCkMailMan; emailAddress: PWideChar): PWideChar; stdcall; function CkMailMan_MxLookupAll(objHandle: HCkMailMan; emailAddress: PWideChar): HCkStringArray; stdcall; function CkMailMan_OpenSmtpConnection(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_OpenSmtpConnectionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3Authenticate(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3AuthenticateAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3BeginSession(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3BeginSessionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3Connect(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3ConnectAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3EndSession(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3EndSessionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3EndSessionNoQuit(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3EndSessionNoQuitAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3Noop(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3NoopAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3Reset(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_Pop3ResetAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_Pop3SendRawCommand(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMailMan__pop3SendRawCommand(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar): PWideChar; stdcall; function CkMailMan_Pop3SendRawCommandAsync(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar): HCkTask; stdcall; function CkMailMan_QuickSend(objHandle: HCkMailMan; fromAddr: PWideChar; toAddr: PWideChar; subject: PWideChar; body: PWideChar; smtpServer: PWideChar): wordbool; stdcall; function CkMailMan_QuickSendAsync(objHandle: HCkMailMan; fromAddr: PWideChar; toAddr: PWideChar; subject: PWideChar; body: PWideChar; smtpServer: PWideChar): HCkTask; stdcall; function CkMailMan_RenderToMime(objHandle: HCkMailMan; email: HCkEmail; outStr: HCkString): wordbool; stdcall; function CkMailMan__renderToMime(objHandle: HCkMailMan; email: HCkEmail): PWideChar; stdcall; function CkMailMan_RenderToMimeBd(objHandle: HCkMailMan; email: HCkEmail; renderedMime: HCkBinData): wordbool; stdcall; function CkMailMan_RenderToMimeBytes(objHandle: HCkMailMan; email: HCkEmail; outData: HCkByteData): wordbool; stdcall; function CkMailMan_RenderToMimeSb(objHandle: HCkMailMan; email: HCkEmail; renderedMime: HCkStringBuilder): wordbool; stdcall; function CkMailMan_SaveLastError(objHandle: HCkMailMan; path: PWideChar): wordbool; stdcall; function CkMailMan_SendBundle(objHandle: HCkMailMan; bundle: HCkEmailBundle): wordbool; stdcall; function CkMailMan_SendBundleAsync(objHandle: HCkMailMan; bundle: HCkEmailBundle): HCkTask; stdcall; function CkMailMan_SendEmail(objHandle: HCkMailMan; email: HCkEmail): wordbool; stdcall; function CkMailMan_SendEmailAsync(objHandle: HCkMailMan; email: HCkEmail): HCkTask; stdcall; function CkMailMan_SendMime(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeSource: PWideChar): wordbool; stdcall; function CkMailMan_SendMimeAsync(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeSource: PWideChar): HCkTask; stdcall; function CkMailMan_SendMimeBd(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeData: HCkBinData): wordbool; stdcall; function CkMailMan_SendMimeBdAsync(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeData: HCkBinData): HCkTask; stdcall; function CkMailMan_SendMimeBytes(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeSource: HCkByteData): wordbool; stdcall; function CkMailMan_SendMimeBytesAsync(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeSource: HCkByteData): HCkTask; stdcall; function CkMailMan_SendMimeBytesQ(objHandle: HCkMailMan; from: PWideChar; recipients: PWideChar; mimeData: HCkByteData): wordbool; stdcall; function CkMailMan_SendMimeQ(objHandle: HCkMailMan; fromAddr: PWideChar; recipients: PWideChar; mimeSource: PWideChar): wordbool; stdcall; function CkMailMan_SendMimeToList(objHandle: HCkMailMan; fromAddr: PWideChar; distListFilename: PWideChar; mimeSource: PWideChar): wordbool; stdcall; function CkMailMan_SendMimeToListAsync(objHandle: HCkMailMan; fromAddr: PWideChar; distListFilename: PWideChar; mimeSource: PWideChar): HCkTask; stdcall; function CkMailMan_SendQ(objHandle: HCkMailMan; email: HCkEmail): wordbool; stdcall; function CkMailMan_SendQ2(objHandle: HCkMailMan; email: HCkEmail; queueDir: PWideChar): wordbool; stdcall; function CkMailMan_SendToDistributionList(objHandle: HCkMailMan; emailObj: HCkEmail; recipientList: HCkStringArray): wordbool; stdcall; function CkMailMan_SendToDistributionListAsync(objHandle: HCkMailMan; emailObj: HCkEmail; recipientList: HCkStringArray): HCkTask; stdcall; function CkMailMan_SetCSP(objHandle: HCkMailMan; csp: HCkCsp): wordbool; stdcall; function CkMailMan_SetDecryptCert(objHandle: HCkMailMan; cert: HCkCert): wordbool; stdcall; function CkMailMan_SetDecryptCert2(objHandle: HCkMailMan; cert: HCkCert; privateKey: HCkPrivateKey): wordbool; stdcall; function CkMailMan_SetPassword(objHandle: HCkMailMan; protocol: PWideChar; password: HCkSecureString): wordbool; stdcall; function CkMailMan_SetSslClientCert(objHandle: HCkMailMan; cert: HCkCert): wordbool; stdcall; function CkMailMan_SetSslClientCertPem(objHandle: HCkMailMan; pemDataOrFilename: PWideChar; pemPassword: PWideChar): wordbool; stdcall; function CkMailMan_SetSslClientCertPfx(objHandle: HCkMailMan; pfxFilename: PWideChar; pfxPassword: PWideChar): wordbool; stdcall; function CkMailMan_SmtpAuthenticate(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_SmtpAuthenticateAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_SmtpConnect(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_SmtpConnectAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_SmtpNoop(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_SmtpNoopAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_SmtpReset(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_SmtpResetAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_SmtpSendRawCommand(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar; bEncodeBase64: wordbool; outStr: HCkString): wordbool; stdcall; function CkMailMan__smtpSendRawCommand(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar; bEncodeBase64: wordbool): PWideChar; stdcall; function CkMailMan_SmtpSendRawCommandAsync(objHandle: HCkMailMan; command: PWideChar; charset: PWideChar; bEncodeBase64: wordbool): HCkTask; stdcall; function CkMailMan_SshAuthenticatePk(objHandle: HCkMailMan; sshLogin: PWideChar; sshUsername: HCkSshKey): wordbool; stdcall; function CkMailMan_SshAuthenticatePkAsync(objHandle: HCkMailMan; sshLogin: PWideChar; sshUsername: HCkSshKey): HCkTask; stdcall; function CkMailMan_SshAuthenticatePw(objHandle: HCkMailMan; sshLogin: PWideChar; sshPassword: PWideChar): wordbool; stdcall; function CkMailMan_SshAuthenticatePwAsync(objHandle: HCkMailMan; sshLogin: PWideChar; sshPassword: PWideChar): HCkTask; stdcall; function CkMailMan_SshCloseTunnel(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_SshCloseTunnelAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_SshOpenTunnel(objHandle: HCkMailMan; sshHostname: PWideChar; sshPort: Integer): wordbool; stdcall; function CkMailMan_SshOpenTunnelAsync(objHandle: HCkMailMan; sshHostname: PWideChar; sshPort: Integer): HCkTask; stdcall; function CkMailMan_TransferMail(objHandle: HCkMailMan): HCkEmailBundle; stdcall; function CkMailMan_TransferMailAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_TransferMultipleMime(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkStringArray; stdcall; function CkMailMan_TransferMultipleMimeAsync(objHandle: HCkMailMan; uidlArray: HCkStringArray): HCkTask; stdcall; function CkMailMan_UnlockComponent(objHandle: HCkMailMan; code: PWideChar): wordbool; stdcall; function CkMailMan_UseCertVault(objHandle: HCkMailMan; vault: HCkXmlCertVault): wordbool; stdcall; function CkMailMan_UseSsh(objHandle: HCkMailMan; ssh: HCkSsh): wordbool; stdcall; function CkMailMan_UseSshTunnel(objHandle: HCkMailMan; tunnel: HCkSocket): wordbool; stdcall; function CkMailMan_VerifyPopConnection(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_VerifyPopConnectionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_VerifyPopLogin(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_VerifyPopLoginAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_VerifyRecips(objHandle: HCkMailMan; email: HCkEmail; badAddrs: HCkStringArray): wordbool; stdcall; function CkMailMan_VerifyRecipsAsync(objHandle: HCkMailMan; email: HCkEmail; badAddrs: HCkStringArray): HCkTask; stdcall; function CkMailMan_VerifySmtpConnection(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_VerifySmtpConnectionAsync(objHandle: HCkMailMan): HCkTask; stdcall; function CkMailMan_VerifySmtpLogin(objHandle: HCkMailMan): wordbool; stdcall; function CkMailMan_VerifySmtpLoginAsync(objHandle: HCkMailMan): HCkTask; stdcall; implementation {$Include chilkatDllPath.inc} function CkMailMan_Create; external DLLName; procedure CkMailMan_Dispose; external DLLName; function CkMailMan_getAbortCurrent; external DLLName; procedure CkMailMan_putAbortCurrent; external DLLName; function CkMailMan_getAllOrNone; external DLLName; procedure CkMailMan_putAllOrNone; external DLLName; function CkMailMan_getAutoFix; external DLLName; procedure CkMailMan_putAutoFix; external DLLName; function CkMailMan_getAutoGenMessageId; external DLLName; procedure CkMailMan_putAutoGenMessageId; external DLLName; function CkMailMan_getAutoSmtpRset; external DLLName; procedure CkMailMan_putAutoSmtpRset; external DLLName; function CkMailMan_getAutoUnwrapSecurity; external DLLName; procedure CkMailMan_putAutoUnwrapSecurity; external DLLName; procedure CkMailMan_getClientIpAddress; external DLLName; procedure CkMailMan_putClientIpAddress; external DLLName; function CkMailMan__clientIpAddress; external DLLName; function CkMailMan_getConnectFailReason; external DLLName; function CkMailMan_getConnectTimeout; external DLLName; procedure CkMailMan_putConnectTimeout; external DLLName; procedure CkMailMan_getDebugLogFilePath; external DLLName; procedure CkMailMan_putDebugLogFilePath; external DLLName; function CkMailMan__debugLogFilePath; external DLLName; procedure CkMailMan_getDsnEnvid; external DLLName; procedure CkMailMan_putDsnEnvid; external DLLName; function CkMailMan__dsnEnvid; external DLLName; procedure CkMailMan_getDsnNotify; external DLLName; procedure CkMailMan_putDsnNotify; external DLLName; function CkMailMan__dsnNotify; external DLLName; procedure CkMailMan_getDsnRet; external DLLName; procedure CkMailMan_putDsnRet; external DLLName; function CkMailMan__dsnRet; external DLLName; function CkMailMan_getEmbedCertChain; external DLLName; procedure CkMailMan_putEmbedCertChain; external DLLName; procedure CkMailMan_getFilter; external DLLName; procedure CkMailMan_putFilter; external DLLName; function CkMailMan__filter; external DLLName; function CkMailMan_getHeartbeatMs; external DLLName; procedure CkMailMan_putHeartbeatMs; external DLLName; procedure CkMailMan_getHeloHostname; external DLLName; procedure CkMailMan_putHeloHostname; external DLLName; function CkMailMan__heloHostname; external DLLName; procedure CkMailMan_getHttpProxyAuthMethod; external DLLName; procedure CkMailMan_putHttpProxyAuthMethod; external DLLName; function CkMailMan__httpProxyAuthMethod; external DLLName; procedure CkMailMan_getHttpProxyDomain; external DLLName; procedure CkMailMan_putHttpProxyDomain; external DLLName; function CkMailMan__httpProxyDomain; external DLLName; procedure CkMailMan_getHttpProxyHostname; external DLLName; procedure CkMailMan_putHttpProxyHostname; external DLLName; function CkMailMan__httpProxyHostname; external DLLName; procedure CkMailMan_getHttpProxyPassword; external DLLName; procedure CkMailMan_putHttpProxyPassword; external DLLName; function CkMailMan__httpProxyPassword; external DLLName; function CkMailMan_getHttpProxyPort; external DLLName; procedure CkMailMan_putHttpProxyPort; external DLLName; procedure CkMailMan_getHttpProxyUsername; external DLLName; procedure CkMailMan_putHttpProxyUsername; external DLLName; function CkMailMan__httpProxyUsername; external DLLName; function CkMailMan_getImmediateDelete; external DLLName; procedure CkMailMan_putImmediateDelete; external DLLName; function CkMailMan_getIncludeRootCert; external DLLName; procedure CkMailMan_putIncludeRootCert; external DLLName; function CkMailMan_getIsPop3Connected; external DLLName; function CkMailMan_getIsSmtpConnected; external DLLName; procedure CkMailMan_getLastErrorHtml; external DLLName; function CkMailMan__lastErrorHtml; external DLLName; procedure CkMailMan_getLastErrorText; external DLLName; function CkMailMan__lastErrorText; external DLLName; procedure CkMailMan_getLastErrorXml; external DLLName; function CkMailMan__lastErrorXml; external DLLName; function CkMailMan_getLastMethodSuccess; external DLLName; procedure CkMailMan_putLastMethodSuccess; external DLLName; procedure CkMailMan_getLastSendQFilename; external DLLName; function CkMailMan__lastSendQFilename; external DLLName; function CkMailMan_getLastSmtpStatus; external DLLName; procedure CkMailMan_getLogMailReceivedFilename; external DLLName; procedure CkMailMan_putLogMailReceivedFilename; external DLLName; function CkMailMan__logMailReceivedFilename; external DLLName; procedure CkMailMan_getLogMailSentFilename; external DLLName; procedure CkMailMan_putLogMailSentFilename; external DLLName; function CkMailMan__logMailSentFilename; external DLLName; procedure CkMailMan_getMailHost; external DLLName; procedure CkMailMan_putMailHost; external DLLName; function CkMailMan__mailHost; external DLLName; function CkMailMan_getMailPort; external DLLName; procedure CkMailMan_putMailPort; external DLLName; function CkMailMan_getMaxCount; external DLLName; procedure CkMailMan_putMaxCount; external DLLName; procedure CkMailMan_getOAuth2AccessToken; external DLLName; procedure CkMailMan_putOAuth2AccessToken; external DLLName; function CkMailMan__oAuth2AccessToken; external DLLName; function CkMailMan_getOpaqueSigning; external DLLName; procedure CkMailMan_putOpaqueSigning; external DLLName; procedure CkMailMan_getP7mEncryptAttachFilename; external DLLName; procedure CkMailMan_putP7mEncryptAttachFilename; external DLLName; function CkMailMan__p7mEncryptAttachFilename; external DLLName; procedure CkMailMan_getP7mSigAttachFilename; external DLLName; procedure CkMailMan_putP7mSigAttachFilename; external DLLName; function CkMailMan__p7mSigAttachFilename; external DLLName; procedure CkMailMan_getP7sSigAttachFilename; external DLLName; procedure CkMailMan_putP7sSigAttachFilename; external DLLName; function CkMailMan__p7sSigAttachFilename; external DLLName; function CkMailMan_getPercentDoneScale; external DLLName; procedure CkMailMan_putPercentDoneScale; external DLLName; function CkMailMan_getPop3SessionId; external DLLName; procedure CkMailMan_getPop3SessionLog; external DLLName; function CkMailMan__pop3SessionLog; external DLLName; function CkMailMan_getPop3SPA; external DLLName; procedure CkMailMan_putPop3SPA; external DLLName; function CkMailMan_getPop3SslServerCertVerified; external DLLName; function CkMailMan_getPop3Stls; external DLLName; procedure CkMailMan_putPop3Stls; external DLLName; procedure CkMailMan_getPopPassword; external DLLName; procedure CkMailMan_putPopPassword; external DLLName; function CkMailMan__popPassword; external DLLName; procedure CkMailMan_getPopPasswordBase64; external DLLName; procedure CkMailMan_putPopPasswordBase64; external DLLName; function CkMailMan__popPasswordBase64; external DLLName; function CkMailMan_getPopSsl; external DLLName; procedure CkMailMan_putPopSsl; external DLLName; procedure CkMailMan_getPopUsername; external DLLName; procedure CkMailMan_putPopUsername; external DLLName; function CkMailMan__popUsername; external DLLName; function CkMailMan_getPreferIpv6; external DLLName; procedure CkMailMan_putPreferIpv6; external DLLName; function CkMailMan_getReadTimeout; external DLLName; procedure CkMailMan_putReadTimeout; external DLLName; function CkMailMan_getRequireSslCertVerify; external DLLName; procedure CkMailMan_putRequireSslCertVerify; external DLLName; function CkMailMan_getResetDateOnLoad; external DLLName; procedure CkMailMan_putResetDateOnLoad; external DLLName; function CkMailMan_getSendBufferSize; external DLLName; procedure CkMailMan_putSendBufferSize; external DLLName; function CkMailMan_getSendIndividual; external DLLName; procedure CkMailMan_putSendIndividual; external DLLName; function CkMailMan_getSizeLimit; external DLLName; procedure CkMailMan_putSizeLimit; external DLLName; procedure CkMailMan_getSmtpAuthMethod; external DLLName; procedure CkMailMan_putSmtpAuthMethod; external DLLName; function CkMailMan__smtpAuthMethod; external DLLName; procedure CkMailMan_getSmtpFailReason; external DLLName; function CkMailMan__smtpFailReason; external DLLName; procedure CkMailMan_getSmtpHost; external DLLName; procedure CkMailMan_putSmtpHost; external DLLName; function CkMailMan__smtpHost; external DLLName; procedure CkMailMan_getSmtpLoginDomain; external DLLName; procedure CkMailMan_putSmtpLoginDomain; external DLLName; function CkMailMan__smtpLoginDomain; external DLLName; procedure CkMailMan_getSmtpPassword; external DLLName; procedure CkMailMan_putSmtpPassword; external DLLName; function CkMailMan__smtpPassword; external DLLName; function CkMailMan_getSmtpPipelining; external DLLName; procedure CkMailMan_putSmtpPipelining; external DLLName; function CkMailMan_getSmtpPort; external DLLName; procedure CkMailMan_putSmtpPort; external DLLName; procedure CkMailMan_getSmtpSessionLog; external DLLName; function CkMailMan__smtpSessionLog; external DLLName; function CkMailMan_getSmtpSsl; external DLLName; procedure CkMailMan_putSmtpSsl; external DLLName; function CkMailMan_getSmtpSslServerCertVerified; external DLLName; procedure CkMailMan_getSmtpUsername; external DLLName; procedure CkMailMan_putSmtpUsername; external DLLName; function CkMailMan__smtpUsername; external DLLName; procedure CkMailMan_getSocksHostname; external DLLName; procedure CkMailMan_putSocksHostname; external DLLName; function CkMailMan__socksHostname; external DLLName; procedure CkMailMan_getSocksPassword; external DLLName; procedure CkMailMan_putSocksPassword; external DLLName; function CkMailMan__socksPassword; external DLLName; function CkMailMan_getSocksPort; external DLLName; procedure CkMailMan_putSocksPort; external DLLName; procedure CkMailMan_getSocksUsername; external DLLName; procedure CkMailMan_putSocksUsername; external DLLName; function CkMailMan__socksUsername; external DLLName; function CkMailMan_getSocksVersion; external DLLName; procedure CkMailMan_putSocksVersion; external DLLName; function CkMailMan_getSoRcvBuf; external DLLName; procedure CkMailMan_putSoRcvBuf; external DLLName; function CkMailMan_getSoSndBuf; external DLLName; procedure CkMailMan_putSoSndBuf; external DLLName; procedure CkMailMan_getSslAllowedCiphers; external DLLName; procedure CkMailMan_putSslAllowedCiphers; external DLLName; function CkMailMan__sslAllowedCiphers; external DLLName; procedure CkMailMan_getSslProtocol; external DLLName; procedure CkMailMan_putSslProtocol; external DLLName; function CkMailMan__sslProtocol; external DLLName; function CkMailMan_getStartTLS; external DLLName; procedure CkMailMan_putStartTLS; external DLLName; function CkMailMan_getStartTLSifPossible; external DLLName; procedure CkMailMan_putStartTLSifPossible; external DLLName; procedure CkMailMan_getTlsCipherSuite; external DLLName; function CkMailMan__tlsCipherSuite; external DLLName; procedure CkMailMan_getTlsPinSet; external DLLName; procedure CkMailMan_putTlsPinSet; external DLLName; function CkMailMan__tlsPinSet; external DLLName; procedure CkMailMan_getTlsVersion; external DLLName; function CkMailMan__tlsVersion; external DLLName; function CkMailMan_getUseApop; external DLLName; procedure CkMailMan_putUseApop; external DLLName; function CkMailMan_getVerboseLogging; external DLLName; procedure CkMailMan_putVerboseLogging; external DLLName; procedure CkMailMan_getVersion; external DLLName; function CkMailMan__version; external DLLName; function CkMailMan_AddPfxSourceData; external DLLName; function CkMailMan_AddPfxSourceFile; external DLLName; function CkMailMan_CheckMail; external DLLName; function CkMailMan_CheckMailAsync; external DLLName; procedure CkMailMan_ClearBadEmailAddresses; external DLLName; procedure CkMailMan_ClearPop3SessionLog; external DLLName; procedure CkMailMan_ClearSmtpSessionLog; external DLLName; function CkMailMan_CloseSmtpConnection; external DLLName; function CkMailMan_CloseSmtpConnectionAsync; external DLLName; function CkMailMan_CopyMail; external DLLName; function CkMailMan_CopyMailAsync; external DLLName; function CkMailMan_DeleteBundle; external DLLName; function CkMailMan_DeleteBundleAsync; external DLLName; function CkMailMan_DeleteByMsgnum; external DLLName; function CkMailMan_DeleteByMsgnumAsync; external DLLName; function CkMailMan_DeleteByUidl; external DLLName; function CkMailMan_DeleteByUidlAsync; external DLLName; function CkMailMan_DeleteEmail; external DLLName; function CkMailMan_DeleteEmailAsync; external DLLName; function CkMailMan_DeleteMultiple; external DLLName; function CkMailMan_DeleteMultipleAsync; external DLLName; function CkMailMan_FetchByMsgnum; external DLLName; function CkMailMan_FetchByMsgnumAsync; external DLLName; function CkMailMan_FetchEmail; external DLLName; function CkMailMan_FetchEmailAsync; external DLLName; function CkMailMan_FetchMime; external DLLName; function CkMailMan_FetchMimeAsync; external DLLName; function CkMailMan_FetchMimeBd; external DLLName; function CkMailMan_FetchMimeBdAsync; external DLLName; function CkMailMan_FetchMimeByMsgnum; external DLLName; function CkMailMan_FetchMimeByMsgnumAsync; external DLLName; function CkMailMan_FetchMultiple; external DLLName; function CkMailMan_FetchMultipleAsync; external DLLName; function CkMailMan_FetchMultipleHeaders; external DLLName; function CkMailMan_FetchMultipleHeadersAsync; external DLLName; function CkMailMan_FetchMultipleMime; external DLLName; function CkMailMan_FetchMultipleMimeAsync; external DLLName; function CkMailMan_FetchSingleHeader; external DLLName; function CkMailMan_FetchSingleHeaderAsync; external DLLName; function CkMailMan_FetchSingleHeaderByUidl; external DLLName; function CkMailMan_FetchSingleHeaderByUidlAsync; external DLLName; function CkMailMan_GetAllHeaders; external DLLName; function CkMailMan_GetAllHeadersAsync; external DLLName; function CkMailMan_GetBadEmailAddrs; external DLLName; function CkMailMan_GetFullEmail; external DLLName; function CkMailMan_GetFullEmailAsync; external DLLName; function CkMailMan_GetHeaders; external DLLName; function CkMailMan_GetHeadersAsync; external DLLName; function CkMailMan_GetMailboxCount; external DLLName; function CkMailMan_GetMailboxCountAsync; external DLLName; function CkMailMan_GetMailboxInfoXml; external DLLName; function CkMailMan__getMailboxInfoXml; external DLLName; function CkMailMan_GetMailboxInfoXmlAsync; external DLLName; function CkMailMan_GetMailboxSize; external DLLName; function CkMailMan_GetMailboxSizeAsync; external DLLName; function CkMailMan_GetPop3SslServerCert; external DLLName; function CkMailMan_GetSentToEmailAddrs; external DLLName; function CkMailMan_GetSizeByUidl; external DLLName; function CkMailMan_GetSizeByUidlAsync; external DLLName; function CkMailMan_GetSmtpSslServerCert; external DLLName; function CkMailMan_GetUidls; external DLLName; function CkMailMan_GetUidlsAsync; external DLLName; function CkMailMan_IsSmtpDsnCapable; external DLLName; function CkMailMan_IsSmtpDsnCapableAsync; external DLLName; function CkMailMan_IsUnlocked; external DLLName; function CkMailMan_LastJsonData; external DLLName; function CkMailMan_LoadEml; external DLLName; function CkMailMan_LoadMbx; external DLLName; function CkMailMan_LoadMime; external DLLName; function CkMailMan_LoadQueuedEmail; external DLLName; function CkMailMan_LoadXmlEmail; external DLLName; function CkMailMan_LoadXmlEmailString; external DLLName; function CkMailMan_LoadXmlFile; external DLLName; function CkMailMan_LoadXmlString; external DLLName; function CkMailMan_MxLookup; external DLLName; function CkMailMan__mxLookup; external DLLName; function CkMailMan_MxLookupAll; external DLLName; function CkMailMan_OpenSmtpConnection; external DLLName; function CkMailMan_OpenSmtpConnectionAsync; external DLLName; function CkMailMan_Pop3Authenticate; external DLLName; function CkMailMan_Pop3AuthenticateAsync; external DLLName; function CkMailMan_Pop3BeginSession; external DLLName; function CkMailMan_Pop3BeginSessionAsync; external DLLName; function CkMailMan_Pop3Connect; external DLLName; function CkMailMan_Pop3ConnectAsync; external DLLName; function CkMailMan_Pop3EndSession; external DLLName; function CkMailMan_Pop3EndSessionAsync; external DLLName; function CkMailMan_Pop3EndSessionNoQuit; external DLLName; function CkMailMan_Pop3EndSessionNoQuitAsync; external DLLName; function CkMailMan_Pop3Noop; external DLLName; function CkMailMan_Pop3NoopAsync; external DLLName; function CkMailMan_Pop3Reset; external DLLName; function CkMailMan_Pop3ResetAsync; external DLLName; function CkMailMan_Pop3SendRawCommand; external DLLName; function CkMailMan__pop3SendRawCommand; external DLLName; function CkMailMan_Pop3SendRawCommandAsync; external DLLName; function CkMailMan_QuickSend; external DLLName; function CkMailMan_QuickSendAsync; external DLLName; function CkMailMan_RenderToMime; external DLLName; function CkMailMan__renderToMime; external DLLName; function CkMailMan_RenderToMimeBd; external DLLName; function CkMailMan_RenderToMimeBytes; external DLLName; function CkMailMan_RenderToMimeSb; external DLLName; function CkMailMan_SaveLastError; external DLLName; function CkMailMan_SendBundle; external DLLName; function CkMailMan_SendBundleAsync; external DLLName; function CkMailMan_SendEmail; external DLLName; function CkMailMan_SendEmailAsync; external DLLName; function CkMailMan_SendMime; external DLLName; function CkMailMan_SendMimeAsync; external DLLName; function CkMailMan_SendMimeBd; external DLLName; function CkMailMan_SendMimeBdAsync; external DLLName; function CkMailMan_SendMimeBytes; external DLLName; function CkMailMan_SendMimeBytesAsync; external DLLName; function CkMailMan_SendMimeBytesQ; external DLLName; function CkMailMan_SendMimeQ; external DLLName; function CkMailMan_SendMimeToList; external DLLName; function CkMailMan_SendMimeToListAsync; external DLLName; function CkMailMan_SendQ; external DLLName; function CkMailMan_SendQ2; external DLLName; function CkMailMan_SendToDistributionList; external DLLName; function CkMailMan_SendToDistributionListAsync; external DLLName; function CkMailMan_SetCSP; external DLLName; function CkMailMan_SetDecryptCert; external DLLName; function CkMailMan_SetDecryptCert2; external DLLName; function CkMailMan_SetPassword; external DLLName; function CkMailMan_SetSslClientCert; external DLLName; function CkMailMan_SetSslClientCertPem; external DLLName; function CkMailMan_SetSslClientCertPfx; external DLLName; function CkMailMan_SmtpAuthenticate; external DLLName; function CkMailMan_SmtpAuthenticateAsync; external DLLName; function CkMailMan_SmtpConnect; external DLLName; function CkMailMan_SmtpConnectAsync; external DLLName; function CkMailMan_SmtpNoop; external DLLName; function CkMailMan_SmtpNoopAsync; external DLLName; function CkMailMan_SmtpReset; external DLLName; function CkMailMan_SmtpResetAsync; external DLLName; function CkMailMan_SmtpSendRawCommand; external DLLName; function CkMailMan__smtpSendRawCommand; external DLLName; function CkMailMan_SmtpSendRawCommandAsync; external DLLName; function CkMailMan_SshAuthenticatePk; external DLLName; function CkMailMan_SshAuthenticatePkAsync; external DLLName; function CkMailMan_SshAuthenticatePw; external DLLName; function CkMailMan_SshAuthenticatePwAsync; external DLLName; function CkMailMan_SshCloseTunnel; external DLLName; function CkMailMan_SshCloseTunnelAsync; external DLLName; function CkMailMan_SshOpenTunnel; external DLLName; function CkMailMan_SshOpenTunnelAsync; external DLLName; function CkMailMan_TransferMail; external DLLName; function CkMailMan_TransferMailAsync; external DLLName; function CkMailMan_TransferMultipleMime; external DLLName; function CkMailMan_TransferMultipleMimeAsync; external DLLName; function CkMailMan_UnlockComponent; external DLLName; function CkMailMan_UseCertVault; external DLLName; function CkMailMan_UseSsh; external DLLName; function CkMailMan_UseSshTunnel; external DLLName; function CkMailMan_VerifyPopConnection; external DLLName; function CkMailMan_VerifyPopConnectionAsync; external DLLName; function CkMailMan_VerifyPopLogin; external DLLName; function CkMailMan_VerifyPopLoginAsync; external DLLName; function CkMailMan_VerifyRecips; external DLLName; function CkMailMan_VerifyRecipsAsync; external DLLName; function CkMailMan_VerifySmtpConnection; external DLLName; function CkMailMan_VerifySmtpConnectionAsync; external DLLName; function CkMailMan_VerifySmtpLogin; external DLLName; function CkMailMan_VerifySmtpLoginAsync; external DLLName; end.
unit UfrmPictureDescription; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GR32_Image, Vcl.AppEvnts; type TfrmPictureDescription = class(TForm) ImgView321: TImgView32; edtDescription: TEdit; btnOK: TButton; btnCancel: TButton; ApplicationEvents1: TApplicationEvents; edtRemark: TEdit; Label1: TLabel; Label2: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); private FOtherDescriptions: TStringList; function GetDescription: string; procedure SetDescription(const Value: string); function GetRemark: string; procedure SetRemark(const Value: string); { Private declarations } public property OtherDescriptions: TStringList read FOtherDescriptions; property Description: string read GetDescription write SetDescription; property Remark: string read GetRemark write SetRemark; { Public declarations } end; implementation uses GnuGetText; {$R *.dfm} { TfrmPictureDescription } procedure TfrmPictureDescription.ApplicationEvents1Idle(Sender: TObject; var Done: Boolean); begin btnOK.Enabled := (FOtherDescriptions.IndexOf(edtDescription.Text) = -1) and (edtDescription.Text <> ''); if btnOK.Enabled then begin edtDescription.Color := clWindow; end else begin edtDescription.Color := clRed; end; end; procedure TfrmPictureDescription.FormCreate(Sender: TObject); begin TranslateComponent(self); FOtherDescriptions := TStringList.Create; end; procedure TfrmPictureDescription.FormDestroy(Sender: TObject); begin FOtherDescriptions.Free; end; procedure TfrmPictureDescription.FormShow(Sender: TObject); begin edtDescription.SetFocus; edtDescription.SelStart := Length(edtDescription.Text); end; function TfrmPictureDescription.GetDescription: string; begin Result := edtDescription.Text; end; function TfrmPictureDescription.GetRemark: string; begin Result := edtRemark.Text; end; procedure TfrmPictureDescription.SetDescription(const Value: string); begin edtDescription.Text := Value; end; procedure TfrmPictureDescription.SetRemark(const Value: string); begin edtRemark.Text := Value; end; end.
unit uTestHttpCodes; interface uses URL, HttpClient, Response, DUnitX.TestFramework; type [TestFixture] TMyTestObject = class(TObject) private client :THttpClient; response :TResponse; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure Test200; [Test] procedure Test500; end; implementation procedure TMyTestObject.Setup; begin //client := THttpClient.Create( TURL.Create(8204, 'profissionais') , '', nil ); //response := client.Send(); end; procedure TMyTestObject.TearDown; begin response.Free; client.Free; end; procedure TMyTestObject.Test200; begin response := THttpClient.Create( TURL.Create(8204, 'profissionais') , '', nil ).Get(); Assert.AreEqual(200, response.code); end; procedure TMyTestObject.Test500; begin response := THttpClient.Create( TURL.Create(8204, 'url_invalida') , '', nil ).Get(); Assert.AreEqual(500, response.code); end; initialization TDUnitX.RegisterTestFixture(TMyTestObject); end.
unit ContextTestCase; interface uses TestFramework, Classes, Windows, ZmqIntf; type TContextTestCase = class(TTestCase) private context: IZMQContext; public procedure SetUp; override; procedure TearDown; override; published procedure ContextTerminate; procedure ContextDefaults; procedure SetIOThreads; procedure SetMaxSockets; procedure CreateReqSocket; procedure lazyPirateBugTest; end; implementation uses SysUtils; { TContextTestCase } procedure TContextTestCase.ContextTerminate; var st: TZMQSocketType; FZMQsocket: PZMQSocket; begin for st := Low( TZMQSocketType ) to High( TZMQSocketType ) do begin if context = nil then context := ZMQ.CreateContext; FZMQSocket := context.Socket( st ); try FZMQSocket.bind('tcp://127.0.0.1:5555'); context.Linger := 10; //CheckEquals( True, FZMQSocket.Terminated, 'Socket has not terminated! socket type: ' + IntToStr( Ord( st ) ) ); finally FZMQsocket.Free; context := nil; end; end; end; procedure TContextTestCase.CreateReqSocket; var s: PZMQSocket; p: IZMQPoller; begin s := context.Socket( stRequest ); try p := ZMQ.CreatePoller( true ); s.connect( 'tcp://127.0.0.1:5555' ); s.SendString('hhhh'); p.Register( s , [pepollin] ); p.poll(1000); p := nil; s.SetLinger(0); finally s.Free; end; context := nil; end; procedure TContextTestCase.lazyPirateBugTest; var sclient, sserver: PZMQSocket; begin sserver := context.Socket( stResponse ); try sserver.bind( 'tcp://*:5555' ); sclient := context.Socket( stRequest ); try sclient.connect( 'tcp://localhost:5555' ); sclient.SendString('request1'); sleep(500); finally sclient.Free; end; sclient := context.Socket( stRequest ); try sclient.connect( 'tcp://localhost:5555' ); sclient.SendString('request1'); sleep(500); finally sclient.Free; end; finally sserver.Free; sleep(500); end; context := nil; end; procedure TContextTestCase.SetUp; begin context := ZMQ.CreateContext; end; procedure TContextTestCase.TearDown; begin context := nil; end; procedure TContextTestCase.ContextDefaults; begin CheckEquals( ZMQ_IO_THREADS_DFLT, context.IOThreads ); CheckEquals( ZMQ_MAX_SOCKETS_DFLT, context.MaxSockets ); end; procedure TContextTestCase.SetIOThreads; begin CheckEquals( ZMQ_IO_THREADS_DFLT, context.IOThreads ); context.IOThreads := 0; CheckEquals( 0, context.IOThreads ); context.IOThreads := 2; CheckEquals( 2, context.IOThreads ); end; procedure TContextTestCase.SetMaxSockets; begin CheckEquals( ZMQ_MAX_SOCKETS_DFLT, context.MaxSockets ); context.MaxSockets := 16; CheckEquals( 16, context.MaxSockets ); end; initialization RegisterTest(TContextTestCase.Suite); end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.ConnectionViewManager; interface uses System.SysUtils, System.Classes, System.Diagnostics, System.Actions, System.ImageList, Vcl.ActnList, Vcl.Menus, Vcl.ImgList, Vcl.Controls, Spring.Collections, DataGrabber.DataInspector, DataGrabber.FieldInspector, DataGrabber.Interfaces, DataGrabber.ConnectionProfiles, DDuce.Logger; {$REGION 'documentation'} { The ConnectionViewManager is a singleton instance which manages: - the application settings (TDGSettings) - the ConnectionView instances (ConnectionViews) - the active connection view (ActiveConnectionView) - all actions that can be executed on the active connectionview } {$ENDREGION} type TdmConnectionViewManager = class(TDataModule, IConnectionViewManager) {$REGION 'designer controls'} aclActions : TActionList; actAddConnectionView : TAction; actAutoSizeCols : TAction; actChinookExampleQuery : TAction; actClearGrouping : TAction; actCollapseAll : TAction; actCopy : TAction; actDataInspector : TAction; actDebug : TAction; actDesigner : TAction; actExecute : TAction; actExecuteLiveResultSet : TAction; actExpandAll : TAction; actFireDACInfo : TAction; actFormatSQL : TAction; actGroupByBoxVisible : TAction; actGroupBySelection : TAction; actHideConstantColumns : TAction; actHideEmptyColumns : TAction; actHideSelectedColumns : TAction; actInspect : TAction; actInspectConnection : TAction; actInspectDataSet : TAction; actInspectFDManager : TAction; actInspectFields : TAction; actInspectGrid : TAction; actMergeColumnCells : TAction; actPreview : TAction; actPrint : TAction; actRtti : TAction; actSelectionAsCommaText : TAction; actSelectionAsFields : TAction; actSelectionAsQuotedCommaText : TAction; actSelectionAsQuotedFields : TAction; actSelectionAsText : TAction; actSelectionAsTextTable : TAction; actSelectionAsWhereIn : TAction; actSelectionAsWiki : TAction; actSettings : TAction; actShowAllColumns : TAction; actShowMetaData : TAction; actToggleFullScreen : TAction; actToggleStayOnTop : TAction; imlMain : TImageList; mniAutoSizeCols : TMenuItem; mniClearGrouping : TMenuItem; mniCollapseAll : TMenuItem; mniCopy : TMenuItem; mniCopyTextTable : TMenuItem; mniCopyWikiTable : TMenuItem; mniExecute : TMenuItem; mniExpandAll : TMenuItem; mniFormatSQL1 : TMenuItem; mniGroupByBoxVisible : TMenuItem; mniGroupBySelection : TMenuItem; mniHideConstantColumns : TMenuItem; mniHideEmptyColumns : TMenuItem; mniHideSelectedColumns : TMenuItem; mniInspect : TMenuItem; mniInspectConnection : TMenuItem; mniInspectConnectionManager : TMenuItem; mniInspectDataSet : TMenuItem; mniInspectFields : TMenuItem; mniInspectGrid : TMenuItem; mniMergeColumns : TMenuItem; mniN1 : TMenuItem; mniN3 : TMenuItem; mniSelection : TMenuItem; mniSelectionAsCommaText : TMenuItem; mniSelectionAsFields : TMenuItem; mniSelectionAsQuotedCommaText : TMenuItem; mniSelectionAsQuotedFields : TMenuItem; mniSelectionAsTextTable : TMenuItem; mniSettings : TMenuItem; mniShowAllColumns : TMenuItem; N1 : TMenuItem; N2 : TMenuItem; N3 : TMenuItem; N4 : TMenuItem; N5 : TMenuItem; N6 : TMenuItem; ppmConnectionView : TPopupMenu; ppmEditorView : TPopupMenu; Liveresults1: TMenuItem; actResultsAsWiki: TAction; mniCopyResults: TMenuItem; ResultsasWiki1: TMenuItem; actCopyConnectionViewAsWiki: TAction; actAbout: TAction; {$ENDREGION} {$REGION 'action handlers'} procedure actAddConnectionViewExecute(Sender: TObject); procedure actAutoSizeColsExecute(Sender: TObject); procedure actChinookExampleQueryExecute(Sender: TObject); procedure actClearGroupingExecute(Sender: TObject); procedure actCollapseAllExecute(Sender: TObject); procedure actCopyExecute(Sender: TObject); procedure actDataInspectorExecute(Sender: TObject); procedure actDesignerExecute(Sender: TObject); procedure actExecuteExecute(Sender: TObject); procedure actExecuteLiveResultSetExecute(Sender: TObject); procedure actExpandAllExecute(Sender: TObject); procedure actFireDACInfoExecute(Sender: TObject); procedure actGroupByBoxVisibleExecute(Sender: TObject); procedure actGroupBySelectionExecute(Sender: TObject); procedure actHideConstantColumnsExecute(Sender: TObject); procedure actHideEmptyColumnsExecute(Sender: TObject); procedure actHideSelectedColumnsExecute(Sender: TObject); procedure actInspectConnectionExecute(Sender: TObject); procedure actInspectDataSetExecute(Sender: TObject); procedure actInspectExecute(Sender: TObject); procedure actInspectFDManagerExecute(Sender: TObject); procedure actInspectFieldsExecute(Sender: TObject); procedure actInspectGridExecute(Sender: TObject); procedure actMergeColumnCellsExecute(Sender: TObject); procedure actPreviewExecute(Sender: TObject); procedure actPrintExecute(Sender: TObject); procedure actSelectionAsCommaTextExecute(Sender: TObject); procedure actSelectionAsFieldsExecute(Sender: TObject); procedure actSelectionAsQuotedCommaTextExecute(Sender: TObject); procedure actSelectionAsQuotedFieldsExecute(Sender: TObject); procedure actSelectionAsTextExecute(Sender: TObject); procedure actSelectionAsTextTableExecute(Sender: TObject); procedure actSelectionAsWhereInExecute(Sender: TObject); procedure actSelectionAsWikiExecute(Sender: TObject); procedure actSettingsExecute(Sender: TObject); procedure actShowAllColumnsExecute(Sender: TObject); procedure actShowMetaDataExecute(Sender: TObject); procedure actToggleFullScreenExecute(Sender: TObject); procedure actToggleStayOnTopExecute(Sender: TObject); procedure actResultsAsWikiExecute(Sender: TObject); procedure actCopyConnectionViewAsWikiExecute(Sender: TObject); procedure actAboutExecute(Sender: TObject); {$ENDREGION} private FSettings : ISettings; FConnectionViewList : IList<IConnectionView>; FActiveConnectionView : IConnectionView; FStopWatch : TStopwatch; FDataInspector : TfrmDataInspector; FFieldInspector : TfrmFieldInspector; procedure SettingsChanged(Sender: TObject); {$REGION 'property access methods'} function GetSettings: ISettings; function GetActiveConnectionView: IConnectionView; procedure SetActiveConnectionView(const Value: IConnectionView); function GetActiveDataView: IDataView; function GetActiveData: IData; function GetActionList: TActionList; function GetAction(AName: string): TCustomAction; function GetConnectionViewPopupMenu: TPopupMenu; function GetDefaultConnectionProfile: TConnectionProfile; function GetItem(AIndex: Integer): IConnectionView; function GetCount: Integer; {$ENDREGION} protected procedure Execute(const ASQL: string); procedure ApplySettings; procedure UpdateActions; procedure UpdateConnectionViewCaptions; public procedure AfterConstruction; override; procedure BeforeDestruction; override; constructor Create( AOwner : TComponent; ASettings : ISettings ); reintroduce; virtual; function AddConnectionView: IConnectionView; function DeleteConnectionView(AIndex: Integer): Boolean; overload; function DeleteConnectionView(AConnectionView: IConnectionView): Boolean; overload; property ActiveConnectionView: IConnectionView read GetActiveConnectionView write SetActiveConnectionView; property ActiveDataView: IDataView read GetActiveDataView; property ActiveData: IData read GetActiveData; property Settings: ISettings read GetSettings; property ActionList: TActionList read GetActionList; property Items[AIndex: Integer]: IConnectionView read GetItem; default; property Count: Integer read GetCount; property Actions[AName: string]: TCustomAction read GetAction; property ConnectionViewPopupMenu: TPopupMenu read GetConnectionViewPopupMenu; property DefaultConnectionProfile: TConnectionProfile read GetDefaultConnectionProfile; end; implementation {$R *.dfm} uses Vcl.Forms, Vcl.Clipbrd, Vcl.Dialogs, FireDAC.Comp.Client, FireDAC.Stan.Consts, Spring, DDuce.ObjectInspector.zObjectInspector, DDuce.AboutDialog, DataGrabber.Settings.Dialog, DataGrabber.Factories, DataGrabber.Resources, DataGrabber.MetaData.Dialog; {$REGION 'construction and destruction'} constructor TdmConnectionViewManager.Create(AOwner: TComponent; ASettings: ISettings); begin inherited Create(AOwner); FSettings := ASettings; end; procedure TdmConnectionViewManager.AfterConstruction; begin inherited AfterConstruction; FSettings.Load; FSettings.OnChanged.Add(SettingsChanged); FConnectionViewList := TCollections.CreateInterfaceList<IConnectionView>; FDataInspector := TfrmDataInspector.Create(Self); FFieldInspector := TfrmFieldInspector.Create(Self); // disable actions that are not fully implemented yet actPreview.Visible := False; actPrint.Visible := False; actDesigner.Visible := False; actRtti.Visible := False; actDataInspector.Visible := False; end; procedure TdmConnectionViewManager.BeforeDestruction; begin FSettings.Save; FConnectionViewList := nil; FreeAndNil(FDataInspector); FreeAndNil(FFieldInspector); inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'action handlers'} // editor procedure TdmConnectionViewManager.actSettingsExecute(Sender: TObject); begin ExecuteSettingsDialog(Settings, procedure begin ApplySettings; UpdateActions; end ); end; procedure TdmConnectionViewManager.actCollapseAllExecute(Sender: TObject); begin (ActiveDataView as IGroupable).CollapseAll; end; procedure TdmConnectionViewManager.actCopyConnectionViewAsWikiExecute( Sender: TObject); begin Clipboard.AsText := ActiveConnectionView.ExportAsWiki; end; procedure TdmConnectionViewManager.actCopyExecute(Sender: TObject); begin ActiveConnectionView.Copy; end; // grid {$REGION 'DataView actions'} procedure TdmConnectionViewManager.actGroupByBoxVisibleExecute(Sender: TObject); begin Settings.GroupByBoxVisible := (Sender as TAction).Checked; end; procedure TdmConnectionViewManager.actGroupBySelectionExecute(Sender: TObject); begin (ActiveDataView as IGroupable).GroupBySelectedColumns; end; procedure TdmConnectionViewManager.actShowAllColumnsExecute(Sender: TObject); begin if ActiveDataView.ResultSet.ShowAllFields then ActiveDataView.UpdateView; end; procedure TdmConnectionViewManager.actShowMetaDataExecute(Sender: TObject); var F: TfrmMetaData; begin F := TfrmMetaData.Create(Self, ActiveData.Connection); F.ShowModal; end; procedure TdmConnectionViewManager.actToggleFullScreenExecute(Sender: TObject); var A : TAction; begin A := Sender as TAction; if A.Checked then Settings.FormSettings.WindowState := wsMaximized else Settings.FormSettings.WindowState := wsNormal; end; procedure TdmConnectionViewManager.actToggleStayOnTopExecute(Sender: TObject); var A : TAction; begin A := Sender as TAction; if A.Checked then Settings.FormSettings.FormStyle := fsStayOnTop else Settings.FormSettings.FormStyle := fsNormal; end; procedure TdmConnectionViewManager.actSelectionAsCommaTextExecute( Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToCommaText(False); end; procedure TdmConnectionViewManager.actSelectionAsFieldsExecute(Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToFields(False); end; procedure TdmConnectionViewManager.actSelectionAsQuotedCommaTextExecute( Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToCommaText(True); end; procedure TdmConnectionViewManager.actSelectionAsQuotedFieldsExecute( Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToFields; end; procedure TdmConnectionViewManager.actSelectionAsTextExecute(Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToDelimitedTable; end; procedure TdmConnectionViewManager.actSelectionAsTextTableExecute( Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToTextTable(True); end; procedure TdmConnectionViewManager.actSelectionAsWhereInExecute( Sender: TObject); begin ShowMessage('Not supported yet.'); end; procedure TdmConnectionViewManager.actSelectionAsWikiExecute(Sender: TObject); begin Clipboard.AsText := ActiveDataView.SelectionToWikiTable(True); end; procedure TdmConnectionViewManager.actHideConstantColumnsExecute( Sender: TObject); begin ActiveDataView.ResultSet.ConstantFieldsVisible := not ActiveDataView.ResultSet.ConstantFieldsVisible; ActiveDataView.UpdateView; end; procedure TdmConnectionViewManager.actHideEmptyColumnsExecute(Sender: TObject); begin ActiveDataView.ResultSet.EmptyFieldsVisible := not ActiveDataView.ResultSet.EmptyFieldsVisible; ActiveDataView.UpdateView; end; procedure TdmConnectionViewManager.actHideSelectedColumnsExecute( Sender: TObject); begin ActiveDataView.HideSelectedColumns; end; procedure TdmConnectionViewManager.actInspectConnectionExecute(Sender: TObject); begin InspectComponent(ActiveData.Connection); end; procedure TdmConnectionViewManager.actInspectDataSetExecute(Sender: TObject); begin InspectComponent(ActiveDataView.DataSet); end; procedure TdmConnectionViewManager.actInspectExecute(Sender: TObject); begin ShowMessage('Not supported yet.'); end; procedure TdmConnectionViewManager.actInspectFDManagerExecute(Sender: TObject); begin InspectObject(FDManager); end; procedure TdmConnectionViewManager.actInspectFieldsExecute(Sender: TObject); begin if Assigned(FFieldInspector) then begin FFieldInspector.DataSet := ActiveDataView.DataSet; FFieldInspector.Show; end; end; procedure TdmConnectionViewManager.actInspectGridExecute(Sender: TObject); begin if Assigned(ActiveDataView) then ActiveDataView.Inspect; end; procedure TdmConnectionViewManager.actMergeColumnCellsExecute( Sender: TObject); begin Settings.MergeColumnCells := (Sender as TAction).Checked; end; procedure TdmConnectionViewManager.actAboutExecute(Sender: TObject); var F : TfrmAboutDialog; begin F := TfrmAboutDialog.Create(Self); try F.ShowModal; finally F.Free; end; end; procedure TdmConnectionViewManager.actAddConnectionViewExecute(Sender: TObject); begin AddConnectionView; end; procedure TdmConnectionViewManager.actAutoSizeColsExecute(Sender: TObject); begin if Assigned(ActiveDataView) then ActiveDataView.AutoSizeColumns; end; {$ENDREGION} // data {$REGION 'ActiveData actions'} procedure TdmConnectionViewManager.actDataInspectorExecute(Sender: TObject); begin FSettings.DataInspectorVisible := actDataInspector.Checked; FDataInspector.ResultSet := ActiveDataView.ResultSet; if actDataInspector.Checked then FDataInspector.Show; end; procedure TdmConnectionViewManager.actChinookExampleQueryExecute(Sender: TObject); begin ActiveConnectionView.EditorView.Text := CHINOOK_EXAMPLE_QUERY; end; procedure TdmConnectionViewManager.actClearGroupingExecute(Sender: TObject); begin (ActiveDataView as IGroupable).ClearGrouping; end; procedure TdmConnectionViewManager.actExecuteExecute(Sender: TObject); begin ActiveData.DataEditMode := False; Execute(ActiveConnectionView.EditorView.Text); end; procedure TdmConnectionViewManager.actExecuteLiveResultSetExecute( Sender: TObject); begin ActiveData.DataEditMode := True; Execute(ActiveConnectionView.EditorView.Text); end; procedure TdmConnectionViewManager.actExpandAllExecute(Sender: TObject); begin (ActiveDataView as IGroupable).ExpandAll; end; procedure TdmConnectionViewManager.actFireDACInfoExecute(Sender: TObject); begin ShowMessageFmt('FireDAC version %s', [C_FD_Version]); end; procedure TdmConnectionViewManager.actPrintExecute(Sender: TObject); begin //(ActiveData as IDataReport).PrintReport; end; procedure TdmConnectionViewManager.actResultsAsWikiExecute(Sender: TObject); begin Clipboard.AsText := ActiveConnectionView.ExportAsWiki; end; procedure TdmConnectionViewManager.actDesignerExecute(Sender: TObject); begin // (ActiveData as IDataReport).DesignReport; // (ActiveData as IDataReport).EditProperties; end; procedure TdmConnectionViewManager.actPreviewExecute(Sender: TObject); begin // (ActiveData as IDataReport).ReportTitle := 'DataGrabber'; // (ActiveData as IDataReport).PreviewReport; end; {$ENDREGION} {$ENDREGION} {$REGION 'property access methods'} function TdmConnectionViewManager.GetActionList: TActionList; begin Result := aclActions; end; function TdmConnectionViewManager.GetActiveConnectionView: IConnectionView; begin Result := FActiveConnectionView; end; procedure TdmConnectionViewManager.SetActiveConnectionView( const Value: IConnectionView); begin FActiveConnectionView := Value; end; procedure TdmConnectionViewManager.SettingsChanged(Sender: TObject); begin actToggleFullScreen.Checked := Settings.FormSettings.WindowState = wsMaximized; end; function TdmConnectionViewManager.GetActiveData: IData; begin if Assigned(FActiveConnectionView) then Result := FActiveConnectionView.Data else Result := nil; end; function TdmConnectionViewManager.GetActiveDataView: IDataView; begin if Assigned(FActiveConnectionView) then Result := FActiveConnectionView.ActiveDataView else Result := nil; end; function TdmConnectionViewManager.GetConnectionViewPopupMenu: TPopupMenu; begin Result := ppmConnectionView; end; function TdmConnectionViewManager.GetCount: Integer; begin Result := FConnectionViewList.Count; end; function TdmConnectionViewManager.GetDefaultConnectionProfile: TConnectionProfile; begin Result := FSettings.ConnectionProfiles.Find(FSettings.DefaultConnectionProfile); end; function TdmConnectionViewManager.GetItem(AIndex: Integer): IConnectionView; begin Result := FConnectionViewList[AIndex]; end; function TdmConnectionViewManager.GetAction(AName: string): TCustomAction; var I: Integer; begin I := ActionList.ActionCount - 1; while (I >= 0) and (CompareText(TAction(ActionList[I]).Name, AName) <> 0) do Dec(I); if I >= 0 then Result := ActionList[I] as TCustomAction else Result := nil; end; function TdmConnectionViewManager.GetSettings: ISettings; begin Result := FSettings; end; {$ENDREGION} {$REGION 'protected methods'} procedure TdmConnectionViewManager.ApplySettings; begin ActiveConnectionView.ApplySettings; end; function TdmConnectionViewManager.DeleteConnectionView( AIndex: Integer): Boolean; begin if AIndex < Count then begin FConnectionViewList.Delete(AIndex); Result := True; end else Result := False; end; function TdmConnectionViewManager.DeleteConnectionView( AConnectionView: IConnectionView): Boolean; var N : Integer; begin Guard.CheckNotNull(AConnectionView, 'AConnectionView'); N := FConnectionViewList.IndexOf(AConnectionView); if N <> -1 then begin FConnectionViewList.Delete(N); Result := True; end else Result := False; end; procedure TdmConnectionViewManager.Execute(const ASQL: string); begin FStopWatch.Reset; ActiveData.SQL := ASQL; FStopWatch.Start; ActiveData.Execute; FStopWatch.Stop; // if Assigned(FDataInspector) and FDataInspector.Visible then // begin // FDataInspector.Data := ActiveData; // end; if Assigned(FFieldInspector) and FFieldInspector.Visible then begin FFieldInspector.DataSet := ActiveDataView.DataSet; end; end; procedure TdmConnectionViewManager.UpdateActions; var B: Boolean; begin if Assigned(FSettings) then begin actToggleStayOnTop.Checked := FSettings.FormSettings.FormStyle = fsStayOnTop; actDataInspector.Checked := FSettings.DataInspectorVisible; end; if Assigned(ActiveData) and Assigned(ActiveConnectionView) then begin actExecute.Enabled := not ActiveConnectionView.EditorView.Text.Trim.IsEmpty; actExecuteLiveResultSet.Enabled := actExecute.Enabled; B := ActiveData.Active; actPreview.Enabled := B; actPrint.Enabled := B; actDesigner.Enabled := B; B := Assigned(ActiveDataView); actHideEmptyColumns.Checked := B and not ActiveDataView.ResultSet.EmptyFieldsVisible; actHideConstantColumns.Checked := B and not ActiveDataView.ResultSet.ConstantFieldsVisible; actAutoSizeCols.Visible := B; actAutoSizeCols.Enabled := actAutoSizeCols.Visible; actGroupBySelection.Visible := B and Supports(ActiveDataView, IGroupable); actGroupBySelection.Enabled := actGroupBySelection.Visible; actGroupByBoxVisible.Visible := B and Supports(ActiveDataView, IGroupable); actGroupByBoxVisible.Checked := Settings.GroupByBoxVisible; actExpandAll.Visible := B and Supports(ActiveDataView, IGroupable); actCollapseAll.Visible := B and Supports(ActiveDataView, IGroupable); actClearGrouping.Visible := B and Supports(ActiveDataView, IGroupable); actMergeColumnCells.Visible := B and Supports(ActiveDataView, IMergable); actMergeColumnCells.Enabled := actMergeColumnCells.Visible; actMergeColumnCells.Checked := Settings.MergeColumnCells; end; Logger.Watch('ActiveConnectionView', ActiveConnectionView.EditorView.Text); end; procedure TdmConnectionViewManager.UpdateConnectionViewCaptions; var CV : IConnectionView; I : Integer; begin for I := 0 to FConnectionViewList.Count - 1 do begin CV := FConnectionViewList[I] as IConnectionView; if Assigned(CV.ActiveConnectionProfile) then CV.Form.Caption := Format('(%d) %s', [I + 1, CV.ActiveConnectionProfile.Name]); end; end; {$ENDREGION} {$REGION 'public methods'} function TdmConnectionViewManager.AddConnectionView: IConnectionView; var CP : TConnectionProfile; CV : IConnectionView; D : IData; begin if Assigned(FActiveConnectionView) then CP := FActiveConnectionView.ActiveConnectionProfile else CP := DefaultConnectionProfile; D := TDataGrabberFactories.CreateData(Self, CP.ConnectionSettings); CV := TDataGrabberFactories.CreateConnectionView(Self, Self, D); FConnectionViewList.Add(CV); ActiveConnectionView := CV; UpdateConnectionViewCaptions; Result := CV; end; {$ENDREGION} end.
unit DmMain; interface uses System.SysUtils, System.Classes, CommonInterface, fbapidatabase, SettingsStorage, FB30Statement, fbapiquery, SQLTableProperties, FBSQLData, Variants, RtcInfo, System.Generics.Collections, VkVariable, IB, RtcLog, ServerDocSQLManager, Dialogs, QueryUtils,rtcHttpSrv; type TMainDm = class(TDataModule) procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private FCurrentUser: RUserInfo; { Private declarations } FStorage: TSettingsStorage; // FQuerySelect: TFbApiQuery; // FCommand: TFbApiQuery; // FReadTransaction: TFbApiTransaction; // FReadCommitedTransaction: TFbApiTransaction; // FSnapshotTransaction: TFbApiTransaction; // FTableStabilityTransaction: TFbApiTransaction; FReadOnlyTransactionOptions: TStringList; FSnapshotTransactionOptions: TStringList; FStabilityTransactionOptions: TStringList; FReadCommitedTransactionOptions: TStringList; FServerDocSqlManagerList: TDictionary<String, TServerDocSqlManager>; FEventLogSqlManager: TServerDocSqlManager; FUserAccessTypes: TVkVariableCollection; FUserAccessValues: TVkVariableCollection; //FServerDocSqlManager: TServerDocSqlManager; function CheckValidPassword(const aPassword: String): boolean; procedure SetReadCommitedTransactionOptions(const Value: TStringList); procedure SetReadOnlyTransactionOptions(const Value: TStringList); procedure SetSnapshotTransactionOptions(const Value: TStringList); procedure SetStabilityTransactionOptions(const Value: TStringList); // procedure SetServerDocSqlManager(const Value: TServerDocSqlManager); public { Public declarations } FbDatabase: TFbApiDatabase; function Connected: boolean; function CreateServerDocSQLManager(const key: String):TServerDocSqlManager; procedure Login(const UserName, Password: String); function Gen_ID(const key:String):Int64; function GetNewQuery: TFbApiQuery; overload; function GetNewQuery(const ATransaction: TFbApiTransaction) : TFbApiQuery; overload; function GetServerDocSqlManager(const key: String): TServerDocSqlManager; function GetSQLTableProperties(const ATableName: String;const AConsumer:TSQLTableProperties ): TSQLTableProperties; function GetNewTransaction(const AParams: TStrings; AOwner:TComponent = nil): TFbApiTransaction; property CurrentUser: RUserInfo read FCurrentUser; procedure RegisterAdmin; procedure registerError(const ASQLText, ErrorMessage :String); function ValidUser(const AUserName, aPassword: String): boolean; // property QuerySelect: TFbApiQuery read FQuerySelect; // property CommandQuery: TFbApiQuery read FCommand; procedure TestQuery; procedure QueryValue(query: TFbApiQuery; AParams: TVkVariableCollection; Result: TVkVariableCollection); procedure WriteEventLog(sqlManager: TServerDocSqlManager; ATr: TFbApiTransaction; operation: TDocOperation; new, old, key: TRtcRecord); procedure WriteErrorLog(const ErrorText:String); procedure InitConstsList(var AVarList: TVkVariableCollection; const ATableName, AIdName: String); procedure SetRtcHttpServer(const AServer:TRtcHttpServer); property UserAccessTypes: TVkVariableCollection read FUserAccessTypes; property UsersAccessValues: TVkVariableCollection read FUserAccessValues; property ReadOnlyTransactionOptions: TStringList read FReadOnlyTransactionOptions write SetReadOnlyTransactionOptions; property SnapshotTransactionOptions: TStringList read FSnapshotTransactionOptions write SetSnapshotTransactionOptions; property StabilityTransactionOptions: TStringList read FStabilityTransactionOptions write SetStabilityTransactionOptions; property ReadCommitedTransactionOptions: TStringList read FReadCommitedTransactionOptions write SetReadCommitedTransactionOptions; //property ServerDocSqlManager[const key: String]: TServerDocSqlManager // read GetServerDocSqlManager; end; var MainDm_unused1: TMainDm; implementation { %CLASSGROUP 'Vcl.Controls.TControl' } uses Forms; {$R *.dfm} { TMainDm } function TMainDm.Connected; begin Result := FbDatabase.IsConnected; end; function TMainDm.CreateServerDocSQLManager(const key: String): TServerDocSqlManager; begin Result := TServerDocSqlManager.Create; GetSQLTableProperties(key, Result.SQLTableProperties); end; procedure TMainDm.DataModuleCreate(Sender: TObject); //var // dbParams: TFBApiDatabaseParams; begin FServerDocSqlManagerList := TDictionary<String, TServerDocSqlManager>.Create; FReadOnlyTransactionOptions := TStringList.Create; FReadOnlyTransactionOptions.Add('read'); FReadOnlyTransactionOptions.Add('nowait'); FSnapshotTransactionOptions := TStringList.Create; FSnapshotTransactionOptions.Add('concurrency'); FSnapshotTransactionOptions.Add('nowait'); FStabilityTransactionOptions := TStringList.Create; FStabilityTransactionOptions.Add('consistency'); FStabilityTransactionOptions.Add('nowait'); FReadCommitedTransactionOptions := TStringList.Create; FReadCommitedTransactionOptions.Add('read_commited'); FReadCommitedTransactionOptions.Add('nowait'); FReadCommitedTransactionOptions.Add('no_rec_version'); FStorage := TSettingsStorage.Create (ChangeFileExt(Application.ExeName, '.ini')); FStorage.Read; // dbParams := TFBApiDatabaseParams.Create(self); FbDatabase := TFbApiDatabase.Create(self); FbDatabase.Params.DbName := FStorage.GetVariable('dbParams', 'DbName', '') .AsString; // 'inet://localhost:3050/d:\FBDATA\VERA_PRO\ledapravo.fdb'); FbDatabase.Params.UserName := FStorage.GetVariable('dbParams', 'UserName', 'sysdba').AsString; FbDatabase.Params.Password := FStorage.GetVariable('dbParams', 'password', 'masterkey').AsString; FbDatabase.Params.LibPath := FStorage.GetVariable('dbParams', 'LibPath', 'C:\FIREBIRD-4-32\fbclient.dll').AsString; FbDatabase.connect; { FReadTransaction := TFbApiTransaction.Create(self); FReadTransaction.DefaultDatabase := FbDatabase; FReadTransaction.Params.Add('read'); FReadTransaction.Params.Add('nowait'); FReadCommitedTransaction := TFbApiTransaction.Create(self); FReadCommitedTransaction.DefaultDatabase := FbDatabase; FReadCommitedTransaction.Params.Add('read_commited'); FReadCommitedTransaction.Params.Add('nowait'); FReadCommitedTransaction.Params.Add('no_rec_version'); FSnapshotTransaction := TFbApiTransaction.Create(self); FSnapshotTransaction.DefaultDatabase := FbDatabase; FSnapshotTransaction.Params.Add('concurency'); FSnapshotTransaction.Params.Add('nowait'); FTableStabilityTransaction := TFbApiTransaction.Create(self); FTableStabilityTransaction.DefaultDatabase := FbDatabase; FTableStabilityTransaction.Params.Add('consistency'); FTableStabilityTransaction.Params.Add('nowait'); FQuerySelect := TFbApiQuery.Create(self); FQuerySelect.Database := FbDatabase; FQuerySelect.Transaction := FReadTransaction; FCommand := TFbApiQuery.Create(self); FCommand.Database := FbDatabase; FCommand.Transaction := FSnapshotTransaction; } FEventLogSqlManager := GetServerDocSqlManager('EVENTLOG'); end; procedure TMainDm.DataModuleDestroy(Sender: TObject); begin FServerDocSqlManagerList.Free; end; function TMainDm.Gen_ID(const key: String): Int64; begin Result := FbDatabase.QueryValue(Format('SELECT NEXT VALUE FOR %s FROM RDB$DATABASE',[key]),[]); end; function TMainDm.GetNewQuery(const ATransaction: TFbApiTransaction) : TFbApiQuery; begin Result := TFbApiQuery.Create(self); Result.Database := FbDatabase; Result.Transaction := ATransaction; end; function TMainDm.GetNewQuery: TFbApiQuery; begin Result := TFbApiQuery.Create(self); Result.Database := FbDatabase; Result.IsTransactionOwner := True; Result.Transaction := GetNewTransaction(FReadOnlyTransactionOptions, Result); end; function TMainDm.GetNewTransaction(const AParams: TStrings; AOwner:TComponent): TFbApiTransaction; begin if not Assigned(AOwner) then AOwner := self; Result := TFbApiTransaction.Create(AOwner); Result.DefaultDatabase := FbDatabase; Result.Params := AParams; end; function TMainDm.GetServerDocSqlManager(const key: String) : TServerDocSqlManager; var realKey: String; begin realKey := key.ToUpper; {if FServerDocSqlManagerList.ContainsKey(realKey) then Result := FServerDocSqlManagerList[realKey] else begin} Result := CreateServerDocSQLManager(realKey); { FServerDocSqlManagerList.Add(realKey, Result); end; } end; procedure TMainDm.Login(const UserName, Password: String); begin ValidUser(UserName, Password); end; function TMainDm.ValidUser(const AUserName, aPassword: String): boolean; var query: TFbApiQuery; begin Result := False; if Trim(AUserName) = '' then begin Raise Exception.Create('Не определенный пользователь!'); Exit; end; query := GetNewQuery; try with query do begin Close; SQL.Clear; SQL.Add('SELECT ul.*,ug.id_menu FROM userslist ul '); SQL.Add(' INNER JOIN usersgroup ug ON ug.idgroup= ul.idgroup '); SQL.Add(' WHERE UPPER(ul.username)=:username '); ParamByName('username').AsString := AnsiString(UpperCase(AUserName)); // ParamByName('password').AsString := UpperCase(APassword); ExecQuery; if not Eof then begin FCurrentUser.id_group := FieldByName('idgroup').AsInt64; FCurrentUser.id_user := FieldByName('iduser').AsInt64; FCurrentUser.user_name := String(FieldByName('username').AsString); FCurrentUser.user_password := String(FieldByName('userpassword').AsString); FCurrentUser.id_menu := FieldByName('id_menu').AsInt64; Result := CheckValidPassword(aPassword); end; if (FCurrentUser.id_user > 0) and Result then begin Close; SQL.Clear; SQL.Add(' SELECT rdb$set_context(:nmsp,:varname,:varval) FROM rdb$database'); ParamByName('nmsp').AsString := 'USER_SESSION'; ParamByName('varname').AsString := 'iduser'; ParamByName('varval').AsString := AnsiString(IntToStr(FCurrentUser.id_user)); ExecQuery; Close; end; end; finally FreeAndNil(query); end; // on Exception ex do // begin // finally if not Result then Raise Exception.Create('Неверное имя пользователя или пароль.') else begin InitConstsList(FUserAccessTypes,'USERSACCESSTYPE','IDUATYPE'); InitConstsList(FUserAccessValues,'USERSACCESSVALUES','IDUAVALUE'); end; // end; end; procedure TMainDm.WriteErrorLog(const ErrorText: String); var qr: TFbApiQuery; tr: TFbApiTransaction; begin tr := GetNewTransaction(FStabilityTransactionOptions); qr := GetNewQuery(tr); try qr.SQL.Add('INSERT INTO ERRORLOG(description) VALUES(:description)'); qr.ParamByName('description').Value := ErrorText; qr.ExecQuery; tr.Commit; finally tr.Rollback; FreeAndNil(qr); FreeAndNil(tr); end; end; procedure TMainDm.WriteEventLog(sqlManager: TServerDocSqlManager; ATr: TFbApiTransaction; operation: TDocOperation; new, old, key: TRtcRecord); var fbQuery: TFbApiQuery; insVars: TVkVariableCollection; i: Integer; content: TRtcRecord; _arr: TRtcArray; begin // FEventLogSqlManager.GenerateDinamicSQLInsert fbQuery := GetNewQuery(ATr); insVars:= TVkVariableCollection.Create(nil); content := TRtcRecord.Create; _arr := TRtcArray.Create; try insVars.CreateVkVariable('tablename', sqlManager.SQLTableProperties.TableName); insVars.CreateVkVariable('tablekey', key.toJSON); insVars.CreateVkVariable('iduser', CurrentUser.id_user); insVars.CreateVkVariable('datetime', now); if operation = TDocOperation.docUpdate then begin insVars.CreateVkVariable('idevent', 2); for i:=0 to new.Count-1 do begin _arr.NewRecord(i); _arr.asRecord[i].asString['name'] := new.FieldName[i]; _arr.asRecord[i].asValue['new'] := new.Value[new.FieldName[i]]; _arr.asRecord[i].asValue['old'] := old.asValue[new.FieldName[i]]; end; insVars.CreateVkVariable('content', _arr.toJSON); end else if operation = TDocOperation.docInsert then begin insVars.CreateVkVariable('idevent', 1); insVars.CreateVkVariable('content', key.toJSON); end else if operation = TDocOperation.docDelete then begin insVars.CreateVkVariable('idevent', 3); insVars.CreateVkVariable('content', key.toJSON); end; fbQuery.SQL.Add(FEventLogSqlManager.GenerateSQL(docInsert, insVars)); TQueryUtils.SetQueryParams(fbQuery, insVars); fbQuery.ExecQuery; finally insVars.Free; fbQuery.Free; content.Free; _arr.Free; end; end; procedure TMainDm.RegisterAdmin(); //var // qr: TFbApiQuery; begin // qr := TFbApiQuery.Create(self); // qr.Database := { FCommand.Active := False; FCommand.SQL.Clear; FCommand.SQL.Add('UPDATE userslist SET userpasword=:userpasword WHERE id=:id'); FCommand.Transaction.StartTransaction; FCommand.ParamByName('id').AsInt64 := 1; FCommand.ParamByName('userpassword').AsString := '111'; FCommand.ExecQuery; FCommand.Transaction.Commit; } end; procedure TMainDm.registerError(const ASQLText, ErrorMessage: String); var v: TRtcRecord; begin v := TRtcRecord.Create; try v.asString['SQL_QUERY'] := ASQLText; v.asString['ERROR_MESSAGE'] := ErrorMessage; WriteErrorLog(v.toJSON); finally v.Free; end; end; procedure TMainDm.SetReadCommitedTransactionOptions(const Value: TStringList); begin FReadCommitedTransactionOptions := Value; end; procedure TMainDm.SetReadOnlyTransactionOptions(const Value: TStringList); begin FReadOnlyTransactionOptions := Value; end; procedure TMainDm.SetRtcHttpServer(const AServer: TRtcHttpServer); begin AServer.ServerAddr:=FStorage.GetVariable('RtcHttpServer','host','192.168.1.69').AsString; AServer.ServerPort:=FStorage.GetVariable('RtcHttpServer','port','6476').AsString; end; {procedure TMainDm.SetServerDocSqlManager(const Value: TServerDocSqlManager); begin FServerDocSqlManager := Value; end;} procedure TMainDm.SetSnapshotTransactionOptions(const Value: TStringList); begin FSnapshotTransactionOptions := Value; end; procedure TMainDm.SetStabilityTransactionOptions(const Value: TStringList); begin FStabilityTransactionOptions := Value; end; procedure TMainDm.TestQuery; const qr ='EXECUTE BLOCK(NAME VARCHAR(255) = :NAME) RETURNS (IDDOC BIGINT) ' + ' AS ' + ' BEGIN ' + ' INSERT INTO TESTDOC(NAME) VALUES(:NAME)' + ' RETURNING IDDOC INTO :IDDOC;' + ' SUSPEND; ' + ' END'; qr2 = ' INSERT INTO TESTDOC(NAME) VALUES(:NAME)' + ' RETURNING IDDOC ;'; var query: TFbApiQuery; AParams: TVkVariableCollection; tr: TFbApiTransaction; begin tr := GetNewTransaction(FStabilityTransactionOptions, nil); query := GetNewQuery(tr); query.SQL.Text := qr2; AParams := TVkVariableCollection.Create(self); try AParams.CreateVkVariable('NAME','ТЕСТ3'); TQueryUtils.SetQueryParams(query, AParams); query.ExecQuery; if Assigned(query.Current) then ShowMessage(IntToStr(query.Current.ByName('IDDOC').AsInt64)); // if not query.Eof then // ShowMessage(IntToStr(query.FieldByName('IDDOC').AsInt64)); finally query.Free; tr.Free; AParams.Free; end; end; function TMainDm.CheckValidPassword(const aPassword: String): boolean; //var // sHashPassword: String; begin // sHashPassword := FbDatabase.QueryValue(' SELECT CAST(HASH(CAST('''+IntToStr(FCurrentUser.id_user )+aPassword+''' as CHAR(20))) as CHAR(20)) as pwd FROM rdb$database',[]); Result := aPassword.Trim() = FCurrentUser.user_password.Trim(); end; function TMainDm.GetSQLTableProperties(const ATableName: String; const AConsumer: TSQLTableProperties): TSQLTableProperties; const QR_TABLEFIELDS = 'select ' + ' FLD.RDB$FIELD_TYPE' + ', FLD.RDB$FIELD_SCALE' + ', FLD.RDB$FIELD_LENGTH' + ', FLD.RDB$FIELD_PRECISION' + ', FLD.RDB$CHARACTER_SET_ID' + // CHARACTER SET ', RFR.RDB$COLLATION_ID' + ', COL.RDB$COLLATION_NAME' + // COLLATE ', FLD.RDB$FIELD_SUB_TYPE' + ', RFR.RDB$DEFAULT_SOURCE' + // DEFAULT ', RFR.RDB$FIELD_NAME' + ', FLD.RDB$SEGMENT_LENGTH' + ', FLD.RDB$SYSTEM_FLAG' + ', RFR.RDB$FIELD_SOURCE' + // DOMAIN ', RFR.RDB$NULL_FLAG' + // NULLABLE ', FLD.RDB$VALIDATION_SOURCE' + // CHECK ', FLD.RDB$DIMENSIONS' + ', FLD.RDB$COMPUTED_SOURCE' + // COMPUTED BY ', RDB$VALIDATION_SOURCE ' + 'from ' + ' RDB$RELATIONS REL ' + 'join RDB$RELATION_FIELDS RFR on (RFR.RDB$RELATION_NAME = REL.RDB$RELATION_NAME) ' + 'join RDB$FIELDS FLD on (RFR.RDB$FIELD_SOURCE = FLD.RDB$FIELD_NAME) ' + 'left outer join RDB$COLLATIONS COL on (COL.RDB$COLLATION_ID = RFR.RDB$COLLATION_ID and COL.RDB$CHARACTER_SET_ID = FLD.RDB$CHARACTER_SET_ID) ' + 'where ' + ' (REL.RDB$RELATION_NAME = :tablename) ' + 'order by ' + ' RFR.RDB$FIELD_POSITION, RFR.RDB$FIELD_NAME'; QR_PKFIELDS = 'select ' + ' ix.rdb$index_name as index_name, ' + ' sg.rdb$field_name as field_name, ' + ' rc.rdb$relation_name as table_name ' + ' from ' + ' rdb$indices ix ' + ' left join rdb$index_segments sg on ix.rdb$index_name = sg.rdb$index_name ' + ' left join rdb$relation_constraints rc on rc.rdb$index_name = ix.rdb$index_name ' + ' where ' + ' rc.rdb$constraint_type = :cons and rc.rdb$relation_name= :tablename '; var query: TFbApiQuery; begin query := GetNewQuery; if Assigned(AConsumer) then begin Result := AConsumer; Result.Clear; end else Result := TSQLTableProperties.Create; Result.TableName := ATableName; try query.SQL.Add(QR_TABLEFIELDS); query.ParamByName('tablename').AsString := AnsiString(ATableName.ToUpper); query.ExecQuery; while not query.Eof do begin Result.FieldNameList.Add(String(query.FieldByName('RDB$FIELD_NAME').AsString)); query.next; end; query.Close; query.SQL.Clear; query.SQL.Add(QR_PKFIELDS); query.ParamByName('tablename').AsString := AnsiString(ATableName.ToUpper); query.ParamByName('cons').AsString := 'PRIMARY KEY'; query.ExecQuery; while not query.Eof do begin Result.KeyFieldsList.Add(String(query.FieldByName('FIELD_NAME').AsString)); query.next; end; finally query.Free; end; end; procedure TMainDm.QueryValue(query: TFbApiQuery; AParams: TVkVariableCollection; Result: TVkVariableCollection); var i: Integer; begin with query do begin try for i := 0 to AParams.Count - 1 do begin Params[i].AsVariant := AParams.VarByName(String(Params[i].Name)).Value; end; ExecQuery; if SQLStatementType = SQLSelect then begin end; except on E: Exception do begin // Result.asException := E.Message; XLog(E.Message); Close; raise; end; // finally end; end; end; procedure TMainDm.InitConstsList(var AVarList: TVkVariableCollection; const ATableName, AIdName: String); var query: TFbApiQuery; begin if Assigned(AVarList) then AVarList.Clear else AVarList := TVkVariableCollection.Create(self); query := GetNewQuery; with query do begin SQL.Add('SELECT * FROM '+ATableName); ExecQuery; try while not Eof do begin AVarList.CreateVkVariable(FieldByName('CONSTNAME').AsString,FieldByName(AIdName).Value); Next; end; finally Close; end; end; end; end.
unit DTT_Sound; // Gestion du son // -------------- // Utilise FMod (http://www.fmod.org) interface uses fmod; type TMusic = class private Module: PFMusicModule; public constructor Create(FileName: String); procedure Play; procedure Pause; procedure Stop; destructor Destroy; override; end; TSample = class private Sample: PFSoundSample; public constructor Create(FileName: String); procedure Play; procedure Pause( Channel : Integer = 0 ); destructor Destroy; override; end; TSoundStream = class private Stream: PFSoundStream; public constructor Create(FileName: String); procedure Play; procedure Stop; destructor Destroy; override; end; function SoundInit: Boolean; procedure SoundClose; implementation const SOUND_DIR = 'sound/'; function SoundInit: Boolean; begin {$IFDEF LINUX} FSOUND_SetOutput(FSOUND_OUTPUT_OSS); {$ELSE} FSOUND_SetOutput(FSOUND_OUTPUT_DSOUND); {$ENDIF} FSOUND_SetDriver(0); FSOUND_SetMixer(FSOUND_MIXER_QUALITY_AUTODETECT); Result := FSOUND_Init(44100, 64, 0); end; constructor TMusic.Create(FileName: String); begin inherited Create; Module := FMUSIC_LoadSong(PChar(SOUND_DIR + FileName)); FMUSIC_SetPanSeperation(Module, 0.15); if Module = nil then Halt; end; procedure TMusic.Play; begin FMUSIC_PlaySong(Module); end; procedure TMusic.Pause; begin FMUSIC_SetPaused(Module, not FMUSIC_GetPaused(Module)); end; procedure TMusic.Stop; begin FMUSIC_StopSong(Module); end; destructor TMusic.Destroy; begin FMUSIC_FreeSong(Module); inherited Destroy; end; constructor TSample.Create(FileName: String); begin inherited Create; Sample := FSOUND_Sample_Load(FSOUND_FREE, PChar(SOUND_DIR + FileName), FSOUND_2D, 0); end; procedure TSample.Play; begin FSOUND_PlaySound(FSOUND_FREE, Sample); end; destructor TSample.Destroy; begin FSOUND_Sample_Free(Sample); inherited Destroy; end; constructor TSoundStream.Create(FileName: String); begin Stream := FSOUND_Stream_OpenFile(PChar(SOUND_DIR + FileName), FSOUND_LOOP_NORMAL or FSOUND_NORMAL, 0); end; procedure TSoundStream.Play; begin FSOUND_Stream_Play(FSOUND_FREE, Stream); end; procedure TSoundStream.Stop; begin FSOUND_Stream_Stop(Stream); end; destructor TSoundStream.Destroy; begin FSOUND_Stream_Close(Stream); inherited Destroy; end; procedure SoundClose; begin FSOUND_Close; end; procedure TSample.Pause( Channel : Integer ); begin FSOUND_SetPaused( Channel, not FSOUND_GetPaused( Channel ) ); end; end.
unit VideoFormat; interface uses Aurelius.Mapping.Attributes; type [Entity] [Table('VIDEO_FORMATS')] [Sequence('SEQ_VIDEO_FORMATS')] [Id('FId', TIdGenerator.IdentityOrSequence)] TVideoFormat = class private [Column('ID', [TColumnProp.Unique, TColumnProp.Required, TColumnProp.NoUpdate])] FId: Integer; FFormatName: string; public property Id: integer read FId; [Column('FORMAT_NAME', [TColumnProp.Required], 100)] property FormatName: string read FFormatName write FFormatName; end; implementation end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CONTABIL_LANCAMENTO_CABECALHO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ContabilLancamentoCabecalhoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ContabilLoteVO, ContabilLancamentoDetalheVO; type [TEntity] [TTable('CONTABIL_LANCAMENTO_CABECALHO')] TContabilLancamentoCabecalhoVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FID_CONTABIL_LOTE: Integer; FDATA_LANCAMENTO: TDateTime; FDATA_INCLUSAO: TDateTime; FTIPO: String; FLIBERADO: String; FVALOR: Extended; //Transientes FLoteDescricao: String; FContabilLoteVO: TContabilLoteVO; FListaContabilLancamentoDetalheVO: TObjectList<TContabilLancamentoDetalheVO>; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('ID_CONTABIL_LOTE', 'Id Contabil Lote', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContabilLote: Integer read FID_CONTABIL_LOTE write FID_CONTABIL_LOTE; [TColumnDisplay('CONTABIL_LOTE.DESCRICAO', 'Lote Descrição', 300, [ldGrid, ldLookup], ftString, 'ContabilLoteVO.TContabilLoteVO', True)] property LoteDescricao: String read FLoteDescricao write FLoteDescricao; [TColumn('DATA_LANCAMENTO', 'Data Lancamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataLancamento: TDateTime read FDATA_LANCAMENTO write FDATA_LANCAMENTO; [TColumn('DATA_INCLUSAO', 'Data Inclusao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInclusao: TDateTime read FDATA_INCLUSAO write FDATA_INCLUSAO; [TColumn('TIPO', 'Tipo', 32, [ldGrid, ldLookup, ldCombobox], False)] property Tipo: String read FTIPO write FTIPO; [TColumn('LIBERADO', 'Liberado', 8, [ldGrid, ldLookup, ldCombobox], False)] property Liberado: String read FLIBERADO write FLIBERADO; [TColumn('VALOR', 'Valor', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Valor: Extended read FVALOR write FVALOR; //Transientes [TAssociation('ID', 'ID_CONTABIL_LOTE')] property ContabilLoteVO: TContabilLoteVO read FContabilLoteVO write FContabilLoteVO; [TManyValuedAssociation('ID_CONTABIL_LANCAMENTO_CAB', 'ID')] property ListaContabilLancamentoDetalheVO: TObjectList<TContabilLancamentoDetalheVO> read FListaContabilLancamentoDetalheVO write FListaContabilLancamentoDetalheVO; end; implementation constructor TContabilLancamentoCabecalhoVO.Create; begin inherited; FContabilLoteVO := TContabilLoteVO.Create; FListaContabilLancamentoDetalheVO := TObjectList<TContabilLancamentoDetalheVO>.Create; end; destructor TContabilLancamentoCabecalhoVO.Destroy; begin FreeAndNil(FContabilLoteVO); FreeAndNil(FListaContabilLancamentoDetalheVO); inherited; end; initialization Classes.RegisterClass(TContabilLancamentoCabecalhoVO); finalization Classes.UnRegisterClass(TContabilLancamentoCabecalhoVO); end.
(* compiler...Turbo-Pascal 7.0. source.....Enhanced CD-ROM Audio control unit. requires...CD-ROM w/ MSCDEX.EXE v2.10+ loaded, 386+. coded by...Yuval Melamed (Email: variance@inter.net.il) credits....Ralf Brown's Interrupt List 48. modified...03-Mar-1997, 17:58. *) {$A-,D-,G+,I-,L-,S-,R-,T-} unit CDAudio; interface type (* User interface basic type - time representor: *) TMSF = record {<T>rack, <M>inutes, <S>econds, <F>rames} (* Order was reversed (FSMT) to match the Red book format: *) Frm, {frame, 1/75 of a second} Sec, Min, {seconds, minutes} Trk : Byte; {track, or 0 to represent disc time, or 0/1 as audio/data} end; (* the TrkArr is actually used only as a pointer in DiscRec record. the MSF part - location of track on disc. the T (Trk field) is 1 for data track track, 0 for audio. *) TrkArr = array[01..99] of TMSF; (* Use this type to represent a whole disc, and compare between discs: *) DiscRec = record Length : TMSF; {disc's length in [MSF], number of tracks in Trk field} Track : ^TrkArr; {TMSF(s), track length [MSF]/data-flags [T]} end; var (* System variables, initialized when unit starts: *) NumCDDrv : Byte; {number of CD-ROM drives} DrvList : array[1..8] of Char; {drive letters list} FstCDDrv : Char absolute DrvList; {first CD-ROM drive letter} MSCDEXVer : Real; {MSCDEX.EXE version, 0 for none} (* The following const actually points to the first byte of the real- typed MSCDEXVer - if none (0.00), than the boolean is considered to be false. Else (even if major or minor are zero), it returns true. *) MSCDEXLoaded : Boolean absolute MSCDEXVer; const (* Current-drive parameter (change drive only by ChangeCDROMDrv): *) CurCDDrv : 0..9 = 0; {current cd-rom drive to work with (user variable)} (* Returned values for comparison of two TMSF's: *) SameTime = 0; {means that the TMSF's are equal} SuccTime = 1; {means that the first TMSF is bigger than the first} PredTime = 2; {means that the first is smaller} (* Drive status/capabilities functions: *) function DoorOpen : Boolean; {is door open?} function Locked : Boolean; {is door locked?} function NoDisc : Boolean; {is drive empty?} function DrvBusy : Boolean; {is drive busy? (mostly playing)} function InPause : Boolean; {is audio in pause?} function AudVolume : Byte; {what's the audio channels' volume?} function Writable : Boolean; {does the drive writable?} function SuppAudVid : Boolean; {does it support audio/video tracks?} function SuppAudChn : Boolean; {does it support audio channels? (volume)} (* Disc/audio current information: *) procedure GetDiscInfo(var Info : DiscRec); {not neccessary!, user's} procedure GetDiscLen(var DLen {: TMSF}); {get disc length/tracks} procedure GetTrkLoc(var TLoc {: TMSF}; Trk : Byte); {get track's location} procedure GetTrkLen(var TLen : TMSF; Trk : Byte); {get length of track} procedure CurDiscPos(var DPos {: TMSF}); {get disc position} procedure CurTrkPos(var TPos {: TMSF}); {get track position} procedure GetDiscRem(var DRem : TMSF); {get disc remaining time} procedure GetTrkRem(var TRem : TMSF); {get track remain. time} (* CD-ROM drive commands: *) procedure EjectDoor; {eject tray out, if not locked} procedure InsertDoor; {insert tray inside} procedure LockDoor; {lock tray (no eject till reboot/unlock)} procedure UnlockDoor; {unlock the tray} procedure SetVolume(Vol : Byte); {set all audio channel's volume} (* Play/pause/resume procedures: *) procedure PlayFrom(From : TMSF); {play from specified till end} procedure PlayRange(From, Till : TMSF); {play specified range} procedure PlayAmount(From, Amount : TMSF); {play from spec., amount spec.} procedure PlayTrack(TrkNum : Byte); {play spec. track, till disc end} procedure PlaySingle(TrkNum : Byte); {play spec. track, till track end} procedure PlayPrevTrk; {play pervious track to current} procedure PlayNextTrk; {play next track to current} procedure PlayReverse(Skip : TMSF); {play from current - specified} procedure PlayForward(Skip : TMSF); {play from current + specified} procedure PauseAudio; {pause current audio if playing} procedure ResumeAudio; {resume audio, only if paused} (* Utility functions, for both user, and other procedures: *) procedure SetTMSF(var Dest {: TMSF}; T, M, S, F : Byte); {generate TMSF} procedure AddTMSF(var Dest {: TMSF}; Src : TMSF); {2 TMSF's sum} procedure SubTMSF(var Dest {: TMSF}; Src : TMSF); {2 TMSF's diff.} function CompTMSF(FstTime, SndTime : TMSF) : Byte; {2 TMSF's relation} procedure DiscTime(var Dest : TMSF); {track to disc time} procedure TrkTime(var Dest : TMSF); {disc to track time} procedure ChangeCDROMDrv(Drv : Byte); {change cur. drive} function SameDisc(var Dest, Src {: DiscRec}) : Boolean; {compare 2 DiscRec} implementation (* --- Internal variables, procedures and functions (hidden to user): --- *) var (* Device request header (at maximum used size): (although the size is different every call, this variable wasn't programmed to be local, in order to gain speed when using calls, and overall, it also saves memory. ofs / size / description --- ---- ----------- 00h byte length of block (unused for CD-ROM). 01h byte subunit within device driver (set automaticly). 02h byte command code (request specifier). 03h word status (filled by device driver). 05h 8byte unused/reserved by DOS. ---case command codes: 03h, 0Ch (IOCTL input/output)--- 0Dh byte media descriptor (unused for CD-ROM). 0Eh dword transfer address (of IOCTL block). 12h word (call) number of bytes to read/write (unused). (ret.) actuall number read/written. ---case command code: 84h (CD-ROM play)--- 0Dh byte addressing mode (see above). 0Eh dword starting sector number. 12h dword number of sectors to play. ---case command codes: 85h, 88h (CD-ROM pause/resume)--- no further fields. *) Request : array[$00..$15] of Byte; {multi-porpose block (see above)} (* Transfer buffer (holds information of IOCTL input/output): first byte is always function, rest is data. see at the procedures and functions for more details. *) TBuff : array[$00..$0A] of Byte; {multi-porpose buffer} (* This drive letter, is the actuall number of default CD-ROM drive, in word format, to make interrupt calls faster. *) CurDrive : Word; {drive's letter (0=A, 1=B, ...)} (* Play start-address and number of sectors to play. these are - temporary variables to PFrom^ & PCount^ (see const below), because the 'Request' fields may not be ready to use directly before the actuall play request. *) PFromT, PCountT : TMSF; {play from, play count} const (* Play start-address and number of sectors to play. declared as pointers, to be addressed at Request's offsets - 0Eh and 10h when using command code 84h (see above). this method saves some code, and makes code easily readable: *) PFrom : ^Longint = @Request[$0E]; {play from} PCount : ^Longint = @Request[$12]; {play count} (* Red book format: frame/second/minute/unused, and TMSF format : frame/second/minute/track - convertor to: HSG format: minute * 4500 + seconds * 75 + frame - 150. the "- 150" was dropped in the procedure, because all the unit automaticly handles the 150 frames difference (2sec). *) function HSG(RedBook : TMSF) : Longint; assembler; asm mov cl,byte ptr RedBook {get frames field} xor ch,ch {clear high byte - CX=CL} mov ah,byte ptr RedBook+1 {get seconds field} mov dl,byte ptr RedBook+2 {get minutes field} xor dh,dh {clear high byte - DX=DL} mov al,75 {multiply seconds by 75} mul ah {place result in AX} add cx,ax {add seconds*75 to frames} mov ax,4500 {multiply minutes by 4500} mul dx {place result at DX:AX} add ax,cx {add seconds*75+frames to result} adc dx,0 {make sure result stays dword} end; (* IOCTL input call procedure. It is used only within the code of other procedures, to minimize the generated code. Speed lost due to the - 'call' command is absolutely superflouos for that case. *) procedure InputRequest; assembler; asm mov ax,1510h {mscdex service} mov bx,seg Request {request segment} mov es,bx {segreg assignment} mov bx,offset Request {request offset} mov byte ptr es:[bx+2],03h {command code} mov cx,CurDrive {drive letter} mov word ptr es:[bx+0Eh],offset TBuff {transfer offset} mov word ptr es:[bx+10h],seg TBuff {transfer segment} int 2Fh {send device driver request} end; (* IOCTL output command procedure, to use inside unit's procedures. *) procedure OutputRequest; assembler; asm mov ax,1510h {mscdex service} mov bx,seg Request {request segment} mov es,bx {segreg assignment} mov bx,offset Request {request offset} mov byte ptr es:[bx+2],0Ch {command code} mov cx,CurDrive {drive letter} mov word ptr es:[bx+0Eh],offset TBuff {transfer offset} mov word ptr es:[bx+10h],seg TBuff {transfer segment} int 2Fh {send device driver request} end; (* Control-Block command for the MSCDEX driver. This procedure is also used within other procedures, to minimize the total unit's code. *) procedure PlayRequest; assembler; asm mov ax,1510h {mscdex service} mov bx,seg Request {request segment} mov es,bx {segreg assignment} mov bx,offset Request {request offset} mov byte ptr es:[bx+2],84h {command code} mov byte ptr es:[di+0Dh],0 {HSG addressing mode} mov cx,CurDrive {drive letter} int 2Fh {send device request} end; (* Device status (door state/drive capabilities/etc...). *) function DeviceStatus : Word; assembler; asm mov byte ptr TBuff,06h {function} call InputRequest {make IOCTL input call} mov ax,word ptr TBuff+1 {result - low status word} end; (* Q-Sub audio channels information (current track-time, and disc-time). *) procedure ReqQSubAudChnInfo; assembler; asm mov byte ptr TBuff,0Ch {function} call InputRequest {make IOCTL input call} mov bh,byte ptr TBuff+2 {get track} mov cl,bh {save (temp)} and bh,0Fh {get units digit} shr cl,4 {get decimals digit} mov al,10 {multiply decimals by 10} mul cl {get result} add bh,al {add units to decimals*10} end; (* ----- Interface-declared procedures and functions: ----- *) (* True - door is open, false - door is closed. *) function DoorOpen : Boolean; assembler; asm call DeviceStatus {get current device status} and al,1 shl 0 {check bit 0 of status} end; (* True - door is locked, false - door is unlocked. *) function Locked : Boolean; assembler; asm call DeviceStatus {get current device status} not al {reverse bits values - opposite of unlocked} and al,1 shl 1 {check bit 1 of status} end; (* True - drive is empty, false - disc present. *) function NoDisc : Boolean; assembler; asm call DeviceStatus {get current device status} mov al,ah {transfer high byte of status to function result} and al,1 shl 3 {check bit 11 of status (bit 3 of high byte)} end; (* True - drive is busy (mostly playing), false - drive's busy-led is off. *) function DrvBusy : Boolean; assembler; asm call DeviceStatus {only to update status word of Request} mov al,byte ptr Request+4 {status word's high byte} and al,1 shl 1 {check bit 9 of status (1 of high byte)} end; (* True - audio is paused, false - unpaused (unneccessarily playing!). *) function InPause : Boolean; assembler; asm mov byte ptr TBuff,0Fh {function} call InputRequest {make IOCTL input request} mov al,byte ptr TBuff+1 {result - low status word} end; (* Drive's volume (left audio channel's volume, presuming rest are same). *) function AudVolume : Byte; assembler; asm mov byte ptr TBuff,04h {function} call InputRequest {make IOCTL input request} mov al,byte ptr TBuff+2 {result - left chn's volume} end; (* True - drive can write discs, false - read only (CDROM). *) function Writable : Boolean; assembler; asm call DeviceStatus {get current device status} and al,1 shl 3 {check bit 3 of status} end; (* True - drive can play audio/video tracks, false - can't. *) function SuppAudVid : Boolean; assembler; asm call DeviceStatus {get current device status} and al,1 shl 4 {check bit 4 of status} end; (* True - drive supports audio channels control, false - doesn't. *) function SuppAudChn : Boolean; assembler; asm call DeviceStatus {get current device status} mov al,ah {transfer high byte of status to function result} and al,1 shl 0 {check bit 8 of status (0 of low byte)} end; (* Disposes old tracks data field, if any, get disc tracks count & length, allocate new tracks field, and fill with tracks' parameters. *) procedure GetDiscInfo(var Info : DiscRec); var Trk : Byte; {track index} begin if Info.Track <> nil then {if DiscRec defined -} FreeMem(Info.Track, Info.Length.Trk shl 2); {- then free occupied memory} GetDiscLen(Info.Length); {get disc length} GetMem(Info.Track, Info.Length.Trk shl 2); {allocate memory} for Trk := 1 to Info.Length.Trk do {cycle through all tracks} GetTrkLen(Info.Track^[Trk], Trk); {get track's length} end; (* Disc length in global TMSF variable (actually: leadout-2sec), number of tracks, in TMSF's Trk field. *) procedure GetDiscLen(var DLen {: TMSF} ); assembler; asm mov byte ptr TBuff,0Ah {function} call InputRequest {make IOCTL input call} mov bh,byte ptr TBuff+2 {get last track (=count)} mov ax,word ptr TBuff+3 {get farames & seconds} mov bl,byte ptr TBuff+5 {get minutes} sub ah,2 {subtract 2sec to get length} jns @Return {adjust if < 0} add ah,60 {make Sec field to 59, or 58} dec bl {decrease Min} @Return: les di,DLen {address of global variable} mov es:[di],ax {copy: Frm, Sec} mov es:[di+2],bx {copy: Min, Trk} end; (* Get track's starting address on disc into global TMSF, and sets Trk field to 1 if data track, or to 0 if audio track. *) procedure GetTrkLoc(var TLoc {: TMSF}; Trk : Byte); assembler; asm mov byte ptr TBuff,0Bh {function} mov al,Trk {get track} mov byte ptr TBuff+1,al {requested track} call InputRequest {make IOCTL input call} mov ax,word ptr TBuff+2 {get farames & seconds} mov bl,byte ptr TBuff+4 {get minutes} mov bh,byte ptr TBuff+6 {get control info} and bh,1 shl 6 {check bit 6 - data track?} shr bh,6 {make 0 or 1, acco. to bit} sub ah,2 {subtract 2sec to adj. loc.} jns @Return {adjust if < 0} add ah,60 {make Sec field to 59, or 58} dec bl {decrease Min} @Return: les di,TLoc {address of global variable} mov es:[di],ax {copy: Frm, Sec} mov es:[di+2],bx {copy: Min, Trk} end; (* Track's length in a global TMSF variable. Trk field, is set then to 1 if data track, 0 if audio. *) procedure GetTrkLen(var TLen : TMSF; Trk : Byte); var TLoc : TMSF; {track location} begin GetTrkLoc(TLen, Trk); {start address of track} GetDiscLen(TLoc); {get disc length} if Trk < TLoc.Trk then {if track is last, location=disc length} GetTrkLoc(TLoc, Trk+1); {get successor's location} SubTMSF(TLen, TLoc); {place diff. (length) in result} end; (* Get current disc time, and current track (at Trk field). note: device returns track number at hexa-view, means that track - 10 for example, won't be 0Ah (10d), but 10h. that is why this proc. - has a code to make it the correct track number. [ track := (track shr 4) * 10 + (track and 0Fh) ]. *) procedure CurDiscPos(var DPos {: TMSF} ); assembler; asm call ReqQSubAudChnInfo {get current positions} mov bl,byte ptr TBuff+8 {get minutes} mov ah,byte ptr TBuff+9 {get seconds} mov al,byte ptr TBuff+0Ah {get frames} sub ah,2 {subtract 2sec to adj. pos.} jns @Return {adjust if < 0} add ah,60 {make Sec field to 59, or 58} dec bl {decrease Min} @Return: les di,DPos {address of global variable} mov es:[di],ax {copy: Frm, Sec} mov es:[di+2],bx {copy: Min, Trk} end; (* Get current track time, and current track (at Trk field). (same manner as CurDiscTime). *) procedure CurTrkPos(var TPos {: TMSF} ); assembler; asm call ReqQSubAudChnInfo {get current positions} mov bl,byte ptr TBuff+4 {get minutes} mov ah,byte ptr TBuff+5 {get seconds} mov al,byte ptr TBuff+6 {get frames} les di,TPos {address of global variable} mov es:[di],ax {copy: Frm, Sec} mov es:[di+2],bx {copy: Min, Trk} end; (* Get current disc remaining time, and current track (at Trk field). *) procedure GetDiscRem(var DRem : TMSF); var DLen : TMSF; {disc length} begin GetDiscLen(DLen); {get disc length} CurDiscPos(DRem); {get current disc position} SubTMSF(DRem, DLen); {find difference (= remaining disc time)} end; (* Get current track remaining time, and current track (at Trk field). *) procedure GetTrkRem(var TRem : TMSF); var TLen : TMSF; {track length} begin GetTrkLen(TLen, TRem.Trk); {get current track's length} CurTrkPos(TRem); {get current track position} SubTMSF(TRem, TLen); {find difference (= remaining track time)} end; (* If door is unlocked, pause audio if playing, and eject tray out. *) procedure EjectDoor; assembler; asm call PauseAudio {pause audio} mov byte ptr TBuff,00h {function} call OutputRequest {make IOCTL output call} end; (* Insert tray inside drive. *) procedure InsertDoor; assembler; asm mov byte ptr TBuff,05h {function} call OutputRequest {make IOCTL output call} end; (* Locks the door inside the drive (no eject, even with external button). Door remains locked until cold boot/unlock function call/device reset. *) procedure LockDoor; assembler; asm mov word ptr TBuff,0101h {function} call OutputRequest {make IOCTL output call} end; (* This call unlocks locked door. *) procedure UnlockDoor; assembler; asm mov word ptr TBuff,0001h {function} call OutputRequest {make IOCTL output call} end; procedure SetVolume(Vol : Byte); assembler; asm mov byte ptr TBuff,03h {function} xor al,al {start at channel 0} mov ah,Vol {volume - user input} mov word ptr TBuff+1,ax {left} inc al {next channel} mov word ptr TBuff+3,ax {right} inc al {next channel} mov word ptr TBuff+5,ax {left prime} inc al {next channel} mov word ptr TBuff+7,ax {right prime} call OutputRequest {make IOCTL output call} end; (* Plays regardless of current audio status (playing or not), from specified location until end of disc. user can input the start address by disc time, or by track time as he wishes, representing disc time by a zero Trk field. *) procedure PlayFrom(From : TMSF); begin PauseAudio; {interrupt playing} GetDiscLen(PCountT); {disc length} if From.Trk <> 0 then DiscTime(From); {make disc timing} PFrom^ := HSG(From); {start address} PCount^ := HSG(PCountT) - PFrom^; {count of sectors} PlayRequest; {make play request} end; (* Play specified range, interrupts current playing if needed. same manner of input as previous procedure (see above). *) procedure PlayRange(From, Till : TMSF); begin PauseAudio; {interrupt playing} if From.Trk <> 0 then DiscTime(From); {make disc timing} if Till.Trk <> 0 then DiscTime(Till); {make disc timing} PFrom^ := HSG(From); {start address} PCount^ := HSG(Till) - PFrom^; {count of sectors} PlayRequest; {make play request} end; (* Plays specified amount of sectors from specified start address. only start address can be either travk time or disc time, but amount must be [MSF] value (Trk field ignored). *) procedure PlayAmount(From, Amount : TMSF); begin PauseAudio; {interrupt playing} if From.Trk <> 0 then DiscTime(From); {make disc timing} PFrom^ := HSG(From); {start address} PCount^ := HSG(Amount); {count of sectors} PlayRequest; {make play request} end; (* Interrupt current playing and play specified track, until end of disc. request will be ignored if track is data track, and if audio was - playing, it won't be stopped. *) procedure PlayTrack(TrkNum : Byte); begin GetTrkLoc(PFromT, TrkNum); {get track location} if PFromT.Trk = 0 then PlayFrom(PFromT); {play if audio track} end; (* Same as above procedure, but plays until end of track. *) procedure PlaySingle(TrkNum : Byte); begin GetTrkLoc(PFromT, TrkNum); {get track location} GetTrkLen(PCountT, TrkNum); {get track length} if PFromT.Trk = 0 then PlayAmount(PFromT, PCountT); {play if audio track} end; (* Plays the predecessor track to current, or last track if current track is the first track. *) procedure PlayPrevTrk; begin CurTrkPos(PFromT); {get current track} if PFromT.Trk = 1 then {check current} begin {if first track -} GetDiscLen(PCount^); {get disc length} PFromT.Trk := PCountT.Trk; {play last} end else {if not -} Dec(PFromT.Trk); {previous track} GetTrkLoc(PFromT, PFromT.Trk); {get new track loc.} if PFromT.Trk = 0 then PlayFrom(PFromT); {play if audio track} end; (* Plays the successor track to current, or first track if current track is the last track. *) procedure PlayNextTrk; begin GetDiscLen(PCountT); {get disc length} CurTrkPos(PFromT); {get current track} if PFromT.Trk = PCountT.Trk then {check current} PFromT.Trk := 1 {first if was last} else {if not -} Inc(PFromT.Trk); {next track} GetTrkLoc(PFromT, PFromT.Trk); {get new track loc.} if PFromT.Trk = 0 then PlayFrom(PFromT); {play if audio track} end; (* Use [MSF] input to force playing from current location minus the amount given, till end of disc. *) procedure PlayReverse(Skip : TMSF); begin CurDiscPos(PFromT); {get current position} SubTMSF(PFromT, Skip); {subtract requested amount} PFromT.Trk := 0; {make disc time} PlayFrom(PFromT); {play from new location} end; (* Use [MSF] input to force playing from current location plus the amount given, till end of disc. *) procedure PlayForward(Skip : TMSF); begin CurDiscPos(PFromT); {get current position} AddTMSF(PFromT, Skip); {add requested amount} PFromT.Trk := 0; {make disc time} PlayFrom(PFromT); {play from new location} end; (* Pauses current audio if playing, if not playing - ignored. This is actually the STOP command, as it has the same effect. *) procedure PauseAudio; assembler; asm mov ax,1510h {mscdex service} mov bx,seg Request {request segment} mov es,bx {segreg assignment} mov bx,offset Request {request offset} mov byte ptr es:[bx+2],85h {command code} mov cx,CurDrive {drive letter} int 2Fh {send device driver request} end; (* Resumes paused audio only (faster than PlayAudio). *) procedure ResumeAudio; assembler; asm mov ax,1510h {mscdex service} mov bx,seg Request {request segment} mov es,bx {segreg assignment} mov bx,offset Request {request offset} mov byte ptr es:[bx+2],88h {command code} mov cx,CurDrive {drive letter} int 2Fh {send device driver request} end; (* This procedure makes easier when trying to assign a full time into TMSF variable. that way, your code will consume one text line, instead of four record-field assignment clauses. *) procedure SetTMSF(var Dest {: TMSF}; T, M, S, F : Byte); assembler; asm mov al,F {get frames} mov ah,S {get seconds} mov bl,M {get minutes} mov bh,T {get track} les di,Dest {get global variable's address} mov es:[di],ax {copy: Frm, Sec} mov es:[di+2],bx {copy: Min, Trk} end; (* Adds source TMSF value to destination, ignoring Trk field. *) procedure AddTMSF(var Dest {: TMSF}; Src : TMSF); assembler; asm les di,Dest {get global address} mov al,byte ptr Src {get source frames} add al,es:[di] {add destination frames to source's} cmp al,75 {compare with maximum frames value} jb @Frames {jump if below} sub al,75 {subtract 75 frames} inc byte ptr es:[di+1] {add 1 second to "pay" the 75 frames} @Frames: mov es:[di],al {copy: Frm} mov al,byte ptr Src+1 {get source seconds} add al,es:[di+1] {add destination seconds to source's} cmp al,60 {compare with maximum seconds value} jb @Seconds {jump if below} sub al,60 {subtract 60 seconds} inc byte ptr es:[di+2] {add 1 minute to "pay" the 60 seconds} @Seconds: mov es:[di+1],al {copy: Sec} mov al,byte ptr Src+2 {get source's minutes} add es:[di+2],al {copy: Min (sum of destination+source)} end; (* Subtracts source TMSF value from destination, ignoring Trk field. returned value is difference, no sign is assigned. *) procedure SubTMSF(var Dest {: TMSF}; Src : TMSF); assembler; asm les di,Dest {get global destination address} mov al,es:[di] {get destination's frames} mov bx,es:[di+1] {get destination's seconds & minutes} mov cl,byte ptr Src {get source's frames} mov dx,word ptr Src+1 {get source's seconds & minutes} cmp bx,dx {compare dest's minutes to src's} ja @SubMin {below/above/equal: jump if above} jb @XchgTMSF {below/equal: jump if below} cmp al,cl {equal: compare dest's frames to src's} ja @SubMin {below/above/equal: jump if above} jb @XchgTMSF {below/equal: jump if below} xor al,al {equal: make frames zero} xor bx,bx {equal: make seconds & minutes zero} jmp @Return {return result} @XchgTMSF: xchg al,cl {exchange frames} xchg bx,dx {exchange seconds & minutes} @SubMin: sub bh,dh {subtract src's minutes from dest's, ò 0} cmp bl,dl {compare dest's seconds to src's} jae @SubSec {below/above/equal: jump if above or equal} add bl,60 {below: add 1 minute by 60 seconds} dec bh {below: subtract 1 minute (minutes were > 0)} @SubSec: sub bl,dl {subtract src's seconds from dest's, ò 0} cmp al,cl {compare dest's minutes to src's} jae @SubFrm {below/above/equal: jump if above or equal} add al,75 {below: add 1 second by 75 frames} dec bl {below: subtract 1 sec., and check its sign} jns @SubFrm {positive/negative/zero: jump if not neg.} mov bl,59 {negative (-1): make 59 seconds} dec bh {negative (-1): subtract 1 minute (were > 0)} @SubFrm: sub al,cl {subtract src's frames from dest's, ò 0} @Return: mov es:[di],al {copy: Frm} mov es:[di+1],bx {copy: Sec, Min (never touch the Trk field)} end; (* Compares two TMSF records, and return their relation: If both represent the same time, it returns 0, which has a const named 'SameTime', 1 means that the first TMSF is successor, and the const is 'SuccTime', 2 means that the second record is bigger, therefore the fisrt is - predecessor to the second, and the const is: 'PredTime'. The procedure handles all combination of disc-time and track-time. *) function CompTMSF(FstTime, SndTime : TMSF) : Byte; begin if FstTime.Trk <> 0 then DiscTime(FstTime); {deal with absolute time} if SndTime.Trk <> 0 then DiscTime(SndTime); {make sure both are abs.} if Longint(FstTime) > Longint(SndTime) then {check if first is bigger} CompTMSF := SuccTime; {if so, return const value} if Longint(FstTime) < Longint(SndTime) then {check if first is smaller} CompTMSF := PredTime; {if so, report by const} if Longint(FstTime) = Longint(SndTime) then {same? (least chances)} CompTMSF := SameTime; {report by const value 0} end; (* Converts given track time (including the track number in Trk field), to postion in global disc timing. *) procedure DiscTime(var Dest : TMSF); var TLoc : TMSF; {track location} begin GetTrkLoc(TLoc, Dest.Trk); {get given track location} AddTMSF(Dest, TLoc); {add track location to time into track} Dest.Trk := 0; {indicate 'disc-time'} end; (* Converts given disc time (ignoring Trk field), into track time, placing the track number which falls in that given position, and the time into the track, when being at this position on disc. *) procedure TrkTime(var Dest : TMSF); var Upper, Lower, Middle : Byte; {for binary search} Disc, Trk : TMSF; {disc & track times} begin Dest.Trk := 0; {clear highest byte} GetDiscLen(Disc); {get disc length} GetTrkLoc(Trk, Disc.Trk); {get last trk' loc.} if Longint(Dest) >= (Longint(Trk) and $FFFFFF) then {lower than given?} Dest.Trk := Disc.Trk; {if so - last track} if (Disc.Trk > 1) and (Dest.Trk = 0) then {is there track 2?} begin GetTrkLoc(Trk, 2); {get track location} if Longint(Dest) < (Longint(Trk) and $FFFFFF) then {higher than given?} begin Dest.Trk := 1; {if so - 1st track} GetTrkLoc(Trk, 1); {get its location} end; end; if Dest.Trk = 0 then {if still not found} begin Lower := 2; {lower search bound} Upper := Disc.Trk - 1; {upper search bound} while Dest.Trk <> Middle do {binary search loop} begin Middle := (Lower + Upper) shr 1; {check the middle} GetTrkLoc(Trk, Middle + 1); {get next location} if Longint(Dest) > (Longint(Trk) and $FFFFFF) then {lower than given?} begin Lower := Middle + 1; {check the highers} Continue; {jump to 'while'} end; GetTrkLoc(Trk, Middle); {get middle loc.} if Longint(Dest) < (Longint(Trk) and $FFFFFF) then {higher than given?} Upper := Middle - 1 {check the lowers} else {else -} Dest.Trk := Middle; {given falls here} end; end; SubTMSF(Dest, Trk); {time into track} end; (* This procedures changes the default drive we're working with. it can handle a maximum of 10 CD-ROM drives, from 0 (first, unit default), to 9 (10th drive, last). All procedures, also drive capabilities, refer to the new drive. *) procedure ChangeCDROMDrv(Drv : Byte); begin CurCDDrv := Drv; {interface drive index} CurDrive := Byte(DrvList[Drv]) - 65; {unit's drive letter (char-ascii(A)} end; (* Compare two DiscRec's, and return true if equal, false for unidentical. the compare service, can provide a tool to examine two different discs, and decide whether one disc is actually the same as another disc. the compare consist of the disc length, and the track array, rather than just the pointer address values (compares Track^, not Track). True that there's an UPC/EAN code check, but it is unsupported for most drives, so this procedure is more reliable. *) function SameDisc(var Dest, Src {: DiscRec}) : Boolean; assembler; asm cld {move forward} les di,Dest {load destination} push ds {save data segment} lds si,Src {load source} dw 0A766h {=386's CMPSD; compare TMSF's} jne @Return {if not equal - return false} mov cl,[si-1] {get track count (same for both if reached here)} xor ch,ch {make word} les di,es:[di] {load destination's tracks} lds si,[si] {load source's tracks} db 0F3h,66h,0A7h {=REPE CMPSD; compare all tracks until not equal} @Return: db 0Fh,94h,0C0h {=SETE AL; set SameDisc to False or True} pop ds {restore data segment} end; (* Main, issued automaticly at unit's startup: *) begin asm mov ax,1500h {CD-ROM information function} xor bx,bx {bx must be zero} int 2Fh {execute interrupt} mov NumCDDrv,bl {number of cd-rom drives on system} mov ax,1100h {mscdex installation check} mov dx,sp {save stack} push 0DADAh {subfunction of installation check} int 2Fh {execute interrupt} mov sp,dx {restore interrupt} cmp al,0FFh {must be equal, to indicate installed} jne @AfterVer {jump to end if uninstalled} mov ax,150Ch {version check function} int 2Fh {execute interrupt} mov CurDrive,bx {store version in plain memory} mov ax,150Dh {get drive letters func.} mov bx,seg DrvList {segment of drive letter list} mov es,bx {assign to extra segment} mov bx,offset DrvList {offset of array to hold letters} int 2Fh {execute interrupt} @AfterVer: end; (* Places resident's MSCDEX.EXE version. if none - then MSCDEXVer = 0.00. the earliest version for this unit, must be 2.10+ : *) MSCDEXVer := Hi(CurDrive) + Lo(CurDrive) / 100; {format: n.nn} CurDrive := Byte(FstCDDrv); {produce word-type digit} for CurCDDrv := 1 to NumCDDrv do {convert array to letters} Inc(Byte(DrvList[CurCDDrv]), Byte('A')); {add 65 to the ascii value} end.
program Exercicio_8; var a, b, c : integer; procedure TipoTriangulo(var a, b, c : integer); begin if (a < b + c) and (b < c + a) and (c < b + a) then begin if (a = b) and (b = c) then begin writeln('Triangulo equilatero e isoceles'); end else if (a = b) or (a = c) or (c = b) then begin writeln('Triangulo isoceles'); end else if (a <> b) and (b <> c) and (a <> c) then begin writeln('Triangulo escaleno'); end; end else begin writeln('Nao forma um triangulo!'); end; end; begin write('Digite A: '); readln(a); write('Digite B: '); readln(b); write('Digite C: '); readln(c); TipoTriangulo(a, b, c); end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Servidor relacionado ao Sintegra The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit SintegraController; interface uses Forms, Classes, SQLExpr, SysUtils, Generics.Collections, Controller, DBXJSON, DBXCommon, Biblioteca, Constantes, ACBrSintegra; type TSintegraController = class(TController) private class procedure GerarRegistro10; class procedure GerarRegistro11; class procedure GerarRegistro50; class procedure GerarRegistro60; class procedure GerarRegistro61; class function GerarArquivoSintegra: Boolean; protected public // consultar class function GerarSintegra(pFiltro: String): String; end; implementation uses T2TiORM, UDataModule, EmpresaController, // VOs EmpresaVO, ProdutoVO, EcfImpressoraVO, NfeCabecalhoVO, ViewSpedNfeDetalheVO, EcfSintegra60mVO, EcfSintegra60aVO, ViewSintegra60dVO, ViewSintegra60rVO, EcfNotaFiscalCabecalhoVO, ViewSintegra61rVO; { TSintegraController } var Empresa: TEmpresaVO; CodigoConvenio, FinalidadeArquivo, NaturezaInformacao, IdEmpresa, IdContador, Inventario: Integer; DataInicial, DataFinal, Arquivo, FiltroLocal: String; {$REGION 'Infra'} class function TSintegraController.GerarSintegra(pFiltro: String): String; var ConteudoFiltro: TStringList; begin try ConteudoFiltro := TStringList.Create; Split('|', pFiltro, ConteudoFiltro); { 0 - Periodo Inicial 1 - Periodo Final 2 - Código Convênio 3 - Finalidade Arquivo 4 - Natureza das Informações 5 - IdEmpresa 6 - Inventario 7 - IdContador } DataInicial := ConteudoFiltro[0]; DataFinal := ConteudoFiltro[1]; CodigoConvenio := StrToInt(ConteudoFiltro[2]); FinalidadeArquivo := StrToInt(ConteudoFiltro[3]); NaturezaInformacao := StrToInt(ConteudoFiltro[4]); IdEmpresa := StrToInt(ConteudoFiltro[5]); Inventario := StrToInt(ConteudoFiltro[6]); IdContador := StrToInt(ConteudoFiltro[7]); // GerarArquivoSintegra; Result := Arquivo; finally FreeAndNil(ConteudoFiltro); end; end; {$ENDREGION} {$REGION 'Geração Arquivo'} {$REGION 'REGISTRO TIPO 10 - MESTRE DO ESTABELECIMENTO'} class procedure TSintegraController.GerarRegistro10; begin try Empresa := TEmpresaController.ConsultaObjeto('ID=' + IntToStr(IdEmpresa)); with FDataModule.ACBrSintegra do begin Registro10.CNPJ := Empresa.CNPJ; Registro10.Inscricao := Empresa.InscricaoEstadual; Registro10.RazaoSocial := Empresa.RazaoSocial; Registro10.Cidade := Empresa.EnderecoPrincipal.Cidade; Registro10.Estado := Empresa.EnderecoPrincipal.Uf; Registro10.Telefone := Empresa.EnderecoPrincipal.Fone; Registro10.DataInicial := TextoParaData(DataInicial); Registro10.DataFinal := TextoParaData(DataFinal); Registro10.CodigoConvenio := IntToStr(CodigoConvenio); Registro10.NaturezaInformacoes := IntToStr(NaturezaInformacao); Registro10.FinalidadeArquivo := IntToStr(FinalidadeArquivo); end; finally end; end; {$ENDREGION} {$REGION 'Registro Tipo 11 - Dados Complementares do Informante'} class procedure TSintegraController.GerarRegistro11; begin with FDataModule.ACBrSintegra do begin Registro11.Endereco := Empresa.EnderecoPrincipal.Logradouro; Registro11.Numero := Empresa.EnderecoPrincipal.Numero; Registro11.Bairro := Empresa.EnderecoPrincipal.Bairro; Registro11.Cep := Empresa.EnderecoPrincipal.CEP; Registro11.Responsavel := Empresa.Contato; Registro11.Telefone := Empresa.EnderecoPrincipal.Fone; end; end; {$ENDREGION} {$REGION 'REGISTRO TIPO 50 - Nota Fiscal, modelo 1 ou 1-A (código 01), quanto ao ICMS, a critério de cada UF, Nota Fiscal do Produtor, modelo 4 (código 04), Nota Fiscal/Conta de Energia Elétrica, modelo 6 (código 06), Nota Fiscal de Serviço de Comunicação, modelo 21 (código 21), Nota Fiscal de Serviços de Telecomunicações, modelo 22 (código 22), Nota Fiscal Eletrônica, modelo 55 (código 55).'} class procedure TSintegraController.GerarRegistro50; var ListaNFeCabecalho: TObjectList<TNfeCabecalhoVO>; ListaNFeDetalhe: TObjectList<TViewSpedNfeDetalheVO>; Registro50: TRegistro50; Registro54: TRegistro54; Registro75: TRegistro75; i, j: Integer; begin try ListaNFeCabecalho := TT2TiORM.Consultar<TNfeCabecalhoVO>('DATA_HORA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); if assigned(ListaNFeCabecalho) then begin for i := 0 to ListaNFeCabecalho.Count - 1 do begin Registro50 := TRegistro50.Create; Registro50.CPFCNPJ := Empresa.Cnpj; Registro50.Inscricao := Empresa.InscricaoEstadual; Registro50.DataDocumento := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).DataHoraEmissao; Registro50.UF := Empresa.EnderecoPrincipal.UF; Registro50.ValorContabil := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorTotal; Registro50.Modelo := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).CodigoModelo; Registro50.Serie := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Serie; Registro50.Numero := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Numero; Registro50.EmissorDocumento := 'P'; Registro50.BasedeCalculo := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).BaseCalculoIcms; Registro50.Icms := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorIcms; Registro50.Outras := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorDespesasAcessorias; Registro50.Situacao := 'N'; FDataModule.ACBrSintegra.Registros50.Add(Registro50); // REGISTRO TIPO 51 - TOTAL DE NOTA FISCAL QUANTO AO IPI // REGISTRO TIPO 53 - SUBSTITUIÇÃO TRIBUTÁRIA { Não Implementado } // REGISTRO TIPO 54 - PRODUTO try ListaNFeDetalhe := TT2TiORM.Consultar<TViewSpedNfeDetalheVO>('ID_NFE_CABECALHO=' + IntToStr(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Id), '-1', False); if assigned(ListaNFeDetalhe) then begin for j := 0 to ListaNFeDetalhe.Count - 1 do begin Registro54 := TRegistro54.Create; Registro54.CPFCNPJ := Empresa.Cnpj; Registro54.Modelo := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).CodigoModelo; Registro54.Serie := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Serie; Registro54.Numero := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Numero; Registro54.Cfop := IntToStr(TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).Cfop); Registro54.CST := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CstIcms; Registro54.NumeroItem := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).NumeroItem; Registro54.Codigo := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).Gtin; Registro54.Descricao := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).NomeProduto; Registro54.Quantidade := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).QuantidadeComercial; Registro54.Valor := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorTotal; Registro54.ValorDescontoDespesa := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorDesconto; Registro54.BasedeCalculo := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).BaseCalculoIcms; Registro54.BaseST := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorBaseCalculoIcmsSt; Registro54.ValorIpi := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorIpi; Registro54.Aliquota := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIcms; FDataModule.ACBrSintegra.Registros54.Add(Registro54); // REGISTRO TIPO 75 - CÓDIGO DE PRODUTO OU SERVIÇO Registro75 := TRegistro75.Create; Registro75.DataInicial := TextoParaData(DataInicial); Registro75.DataFinal := TextoParaData(DataFinal); Registro75.Codigo := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).Gtin; Registro75.NCM := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).Ncm; Registro75.Descricao := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).NomeProduto; Registro75.Unidade := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).UnidadeComercial; Registro75.AliquotaIpi := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIpi; Registro75.AliquotaICMS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIcms; FDataModule.ACBrSintegra.Registros75.Add(Registro75); end; end; finally FreeAndNil(ListaNFeDetalhe); end; // REGISTRO TIPO 55 - GUIA NACIONAL DE RECOLHIMENTO DE TRIBUTOS ESTADUAIS // REGISTRO TIPO 56 - OPERAÇÕES COM VEÍCULOS AUTOMOTORES NOVOS // REGISTRO TIPO 57 - NÚMERO DE LOTE DE FABRICAÇÃO DE PRODUTO { Não Implementado } end; end; finally FreeAndNil(ListaNFeCabecalho); end; end; {$ENDREGION} {$REGION 'Registro Tipo 60 - Cupom Fiscal, Cupom Fiscal - PDV ,e os seguintes Documentos Fiscais quando emitidos por Equipamento Emissor de Cupom Fiscal: Bilhete de Passagem Rodoviário (modelo 13), Bilhete de Passagem Aquaviário (modelo 14), Bilhete de Passagem e Nota de Bagagem (modelo 15), Bilhete de Passagem Ferroviário (modelo 16), e Nota Fiscal de Venda a Consumidor (modelo 2)'} class procedure TSintegraController.GerarRegistro60; var Registro60M: TRegistro60M; Registro60A: TRegistro60A; Registro60D: TRegistro60D; Registro60R: TRegistro60R; Registro75: TRegistro75; Lista60M: TObjectList<TEcfSintegra60mVO>; Lista60A: TObjectList<TEcfSintegra60aVO>; Lista60D: TObjectList<TViewSintegra60dVO>; Lista60R: TObjectList<TViewSintegra60rVO>; Produto: TProdutoVO; i,j: Integer; begin try // Registro Tipo 60 - Mestre (60M): Identificador do equipamento Lista60M := TT2TiORM.Consultar<TEcfSintegra60mVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); if Assigned(Lista60M) then begin for i := 0 to Lista60M.Count - 1 do begin Registro60M := TRegistro60M.Create; Registro60M.Emissao := TEcfSintegra60mVO(Lista60M.Items[i]).DataEmissao; Registro60M.NumSerie := TEcfSintegra60mVO(Lista60M.Items[i]).NumeroSerieEcf; Registro60M.NumOrdem := TEcfSintegra60mVO(Lista60M.Items[i]).NumeroEquipamento; if (TEcfSintegra60mVO(Lista60M.Items[i]).ModeloDocumentoFiscal) = '' then Registro60M.ModeloDoc := '2D' else Registro60M.ModeloDoc := TEcfSintegra60mVO(Lista60M.Items[i]).ModeloDocumentoFiscal; Registro60M.CooInicial := TEcfSintegra60mVO(Lista60M.Items[i]).COOInicial; Registro60M.CooFinal := TEcfSintegra60mVO(Lista60M.Items[i]).COOFinal; Registro60M.CRZ := TEcfSintegra60mVO(Lista60M.Items[i]).CRZ; Registro60M.CRO := TEcfSintegra60mVO(Lista60M.Items[i]).CRO; Registro60M.VendaBruta := TEcfSintegra60mVO(Lista60M.Items[i]).ValorVendaBruta; Registro60M.ValorGT := TEcfSintegra60mVO(Lista60M.Items[i]).ValorGrandeTotal; FDataModule.ACBrSintegra.Registros60M.Add(Registro60M); try // Registro Tipo 60 - Analítico (60A): Identificador de cada Situação Tributária no final do dia de cada equipamento emissor de cupom fiscal Lista60A := TT2TiORM.Consultar<TEcfSintegra60aVO>('ID_SINTEGRA_60M = ' + IntToStr(Lista60M.Items[i].Id), '-1', False); if Assigned(Lista60A) then begin for j := 0 to Lista60A.Count - 1 do begin Registro60A := TRegistro60A.Create; Registro60A.Emissao := Registro60M.Emissao; Registro60A.NumSerie := TEcfSintegra60mVO(Lista60M.Items[i]).NumeroSerieEcf; Registro60A.StAliquota := TEcfSintegra60aVO(Lista60A.Items[j]).SituacaoTributaria; Registro60A.Valor := TEcfSintegra60aVO(Lista60A.Items[j]).Valor; FDataModule.ACBrSintegra.Registros60A.Add(Registro60A); end; end; finally FreeAndNil(Lista60A); end; end; end; // Registro Tipo 60 - Resumo Diário (60D): Registro de mercadoria/produto ou serviço constante em documento fiscal emitido por Terminal Ponto de Venda (PDV) ou equipamento Emissor de Cupom Fiscal (ECF) Lista60D := TT2TiORM.Consultar<TViewSintegra60dVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); for i := 0 to Lista60D.Count - 1 do begin Registro60D := TRegistro60D.Create; Registro60D.Emissao := TViewSintegra60dVO(Lista60D.Items[i]).DataEmissao; Registro60D.NumSerie := TViewSintegra60dVO(Lista60D.Items[i]).Serie; Registro60D.Codigo := TViewSintegra60dVO(Lista60D.Items[i]).Gtin; Registro60D.Quantidade := TViewSintegra60dVO(Lista60D.Items[i]).SomaQuantidade; Registro60D.Valor := TViewSintegra60dVO(Lista60D.Items[i]).SomaItem; Registro60D.BaseDeCalculo := TViewSintegra60dVO(Lista60D.Items[i]).SomaBaseIcms; Registro60D.StAliquota := TViewSintegra60dVO(Lista60D.Items[i]).EcfIcmsSt; Registro60D.ValorIcms := TViewSintegra60dVO(Lista60D.Items[i]).SomaIcms; FDataModule.ACBrSintegra.Registros60D.Add(Registro60D); // REGISTRO TIPO 75 - CÓDIGO DE PRODUTO OU SERVIÇO Produto := TT2TiORM.ConsultarUmObjeto<TProdutoVO>('GTIN=' + QuotedStr(Registro60D.Codigo), False); Registro75 := TRegistro75.Create; Registro75.DataInicial := FDataModule.ACBrSintegra.Registro10.DataInicial; Registro75.DataFinal := FDataModule.ACBrSintegra.Registro10.DataFinal; Registro75.Codigo := Registro60D.Codigo; Registro75.NCM := Produto.NCM; Registro75.Descricao := Produto.DescricaoPDV; Registro75.Unidade := Produto.UnidadeProdutoSigla; Registro75.AliquotaIPI := 0; Registro75.AliquotaICMS := 0; FDataModule.ACBrSintegra.Registros75.Add(Registro75); FreeAndNil(Produto); end; // Registro Tipo 60 - Resumo Mensal (60R): Registro de mercadoria/produto ou serviço processado em equipamento Emissor de Cupom Fiscal Lista60R := TT2TiORM.Consultar<TViewSintegra60rVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); for i := 0 to Lista60R.Count - 1 do begin Registro60R := TRegistro60R.Create; Registro60R.MesAno := IntToStr(TViewSintegra60rVO(Lista60R.Items[i]).MesEmissao) + IntToStr(TViewSintegra60rVO(Lista60R.Items[i]).AnoEmissao); Registro60R.Codigo := TViewSintegra60rVO(Lista60R.Items[i]).GTIN; Registro60R.Qtd := TViewSintegra60rVO(Lista60R.Items[i]).SomaQuantidade; Registro60R.Valor := TViewSintegra60rVO(Lista60R.Items[i]).SomaItem; Registro60R.BaseDeCalculo := TViewSintegra60rVO(Lista60R.Items[i]).SomaBaseICMS; Registro60R.Aliquota := TViewSintegra60rVO(Lista60R.Items[i]).EcfIcmsSt; FDataModule.ACBrSintegra.Registros60R.Add(Registro60R); // REGISTRO TIPO 75 - CÓDIGO DE PRODUTO OU SERVIÇO Produto := TT2TiORM.ConsultarUmObjeto<TProdutoVO>('GTIN=' + QuotedStr(Registro60R.Codigo), False); Registro75 := TRegistro75.Create; Registro75.DataInicial := FDataModule.ACBrSintegra.Registro10.DataInicial; Registro75.DataFinal := FDataModule.ACBrSintegra.Registro10.DataFinal; Registro75.Codigo := Registro60R.Codigo; Registro75.NCM := Produto.NCM; Registro75.Descricao := Produto.Descricao; Registro75.Unidade := Produto.UnidadeProdutoSigla; Registro75.AliquotaIPI := 0; Registro75.AliquotaICMS := 0; FDataModule.ACBrSintegra.Registros75.Add(Registro75); end; // Registro Tipo 60 - Item (60I): Item do documento fiscal emitido por Terminal Ponto de Venda (PDV) ou equipamento Emissor de Cupom Fiscal (ECF) { Não Implementado } finally FreeAndNil(Lista60M); FreeAndNil(Lista60D); FreeAndNil(Lista60R); end; end; {$ENDREGION} {$REGION 'Registro Tipo 61 - REGISTRO TIPO 61: Para os documentos fiscais descritos a seguir, quando não emitidos por equipamento emissor de cupom fiscal : Bilhete de Passagem Aquaviário (modelo 14), Bilhete de Passagem e Nota de Bagagem (modelo 15), Bilhete de Passagem Ferroviário (modelo 16), Bilhete de Passagem Rodoviário (modelo 13) e Nota Fiscal de Venda a Consumidor (modelo 2), Nota Fiscal de Produtor (modelo 4), para as unidades da Federação que não o exigirem na forma prevista no item 11'} class procedure TSintegraController.GerarRegistro61; var Registro61: TRegistro61; Registro61R: TRegistro61R; Registro75: TRegistro75; ListaNF2Cabecalho: TObjectList<TEcfNotaFiscalCabecalhoVO>; Lista61R: TObjectList<TViewSintegra61rVO>; Produto: TProdutoVO; i: Integer; begin try ListaNF2Cabecalho := TT2TiORM.Consultar<TEcfNotaFiscalCabecalhoVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); if assigned(ListaNF2Cabecalho) then begin for i := 0 to ListaNF2Cabecalho.Count - 1 do begin Registro61 := TRegistro61.Create; Registro61.Emissao := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).DataEmissao; Registro61.Modelo := '02'; Registro61.NumOrdemInicial := StrToInt(TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).Numero); Registro61.NumOrdemFinal := StrToInt(TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).Numero); Registro61.Serie := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).Serie; Registro61.SubSerie := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).SubSerie; Registro61.Valor := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).TotalNF; Registro61.BaseDeCalculo := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).BaseICMS; Registro61.ValorIcms := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).ICMS; Registro61.Outras := TEcfNotaFiscalCabecalhoVO(ListaNF2Cabecalho.Items[i]).ICMSOutras; FDataModule.ACBrSintegra.Registros61.Add(Registro61); end; end; // Registro Tipo 61 - Resumo Mensal por Item (61R): Registro de mercadoria/produto ou serviço comercializados através de Nota Fiscal de Produtor ou Nota Fiscal de Venda a Consumidor não emitida por ECF Lista61R := TT2TiORM.Consultar<TViewSintegra61rVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); if Assigned(Lista61R) then begin for i := 0 to Lista61R.Count - 1 do begin Registro61R := TRegistro61R.Create; Registro61R.MesAno := IntToStr(TViewSintegra61rVO(Lista61R.Items[i]).MesEmissao) + IntToStr(TViewSintegra61rVO(Lista61R.Items[i]).AnoEmissao); Registro61R.Codigo := TViewSintegra61rVO(Lista61R.Items[i]).GTIN; Registro61R.Qtd := TViewSintegra61rVO(Lista61R.Items[i]).SomaQuantidade; Registro61R.Valor := TViewSintegra61rVO(Lista61R.Items[i]).SomaItem; Registro61R.BaseDeCalculo := TViewSintegra61rVO(Lista61R.Items[i]).SomaBaseICMS; try Registro61R.Aliquota := StrToFloat(TViewSintegra61rVO(Lista61R.Items[i]).EcfIcmsSt)/100; except Registro61R.Aliquota := 0; end; FDataModule.ACBrSintegra.Registros61R.Add(Registro61R); // REGISTRO TIPO 75 - CÓDIGO DE PRODUTO OU SERVIÇO Produto := TT2TiORM.ConsultarUmObjeto<TProdutoVO>('GTIN=' + QuotedStr(Registro61R.Codigo), False); Registro75 := TRegistro75.Create; Registro75.DataInicial := FDataModule.ACBrSintegra.Registro10.DataInicial; Registro75.DataFinal := FDataModule.ACBrSintegra.Registro10.DataFinal; Registro75.Codigo := Registro61R.Codigo; Registro75.NCM := Produto.NCM; Registro75.Descricao := Produto.Descricao; Registro75.Unidade := Produto.UnidadeProdutoSigla; Registro75.AliquotaIPI := 0; Registro75.AliquotaICMS := 0; FDataModule.ACBrSintegra.Registros75.Add(Registro75); end; end; finally FreeAndNil(ListaNF2Cabecalho); FreeAndNil(Lista61R); end; end; {$ENDREGION} {$REGION 'Gerar Arquivo'} class function TSintegraController.GerarArquivoSintegra: Boolean; begin Result := False; try try GerarRegistro10; GerarRegistro11; GerarRegistro50; GerarRegistro60; GerarRegistro61; // REGISTRO TIPO 70 - Nota Fiscal de Serviço de Transporte E OUTRAS // REGISTRO TIPO 71 - Informações da Carga Transportada // REGISTRO TIPO 74 - REGISTRO DE INVENTÁRIO // REGISTRO TIPO 76 - NOTA FISCAL DE SERVIÇOS DE COMUNICAÇÃO E OUTRAS // REGISTRO TIPO 77 - SERVIÇOS DE COMUNICAÇÃO E TELECOMUNICAÇÃO // REGISTRO TIPO 85 - Informações de Exportações // REGISTRO TIPO 86 - Informações Complementares de Exportações { Não Implementado } Arquivo := ExtractFilePath(Application.ExeName) + 'Arquivos\Sintegra\Sintegra' + FormatDateTime('DDMMYYYYhhmmss', Now) + '.txt'; if not DirectoryExists(ExtractFilePath(Application.ExeName) + '\Arquivos\Sintegra\') then ForceDirectories(ExtractFilePath(Application.ExeName) + '\Arquivos\Sintegra\'); FDataModule.ACBrSintegra.FileName := Arquivo; FDataModule.ACBrSintegra.VersaoValidador := TVersaoValidador(1); FDataModule.ACBrSintegra.GeraArquivo; Result := True; except Result := False; end; finally FreeAndNil(Empresa); end; end; {$ENDREGION} {$ENDREGION} initialization Classes.RegisterClass(TSintegraController); finalization Classes.UnRegisterClass(TSintegraController); end.
unit TNT_Texture; // Gestion des textures // -------------------- // TTexture.Create: // TexWrap: GL_REPEAT or GL_CLAMP // TexFilter: GL_NEAREST or GL_LINEAR // Mipmap: True or False // TTexture.Use: // TexEnv: GL_MODULATE, GL_DECAL, or GL_REPLACE // .TEX: // // Width: Integer // Height: Integer // Bpp(BytesPerPixel): Integer // NumFrames: Integer // Speed: Integer (images/sec) // Frame0 data // Frame1 data // Frame2 data // ... interface uses OpenGL12, TNT_Timer; type TTexture = class private CurrFrame: Cardinal; Name: array of GLuint; Time: TTime; Freq: Single; public Frames, Width, Height, Bpp: Cardinal; Loop: Boolean; constructor Create(FileName: String; TexWrap, TexFilter: GLint; Mipmap: Boolean); procedure Use(TexEnv: GLint); procedure UseFrame(n: Cardinal; TexEnv: GLint); destructor Destroy; override; end; implementation uses SysUtils, TNT_3D, TNT_File; var Current: GLuint; CurrTexEnv: GLint; constructor TTexture.Create(FileName: String; TexWrap, TexFilter: GLint; Mipmap: Boolean); var TexFile: TFile; ImageData: PChar; Size, i: Integer; glType: GLuint; begin inherited Create; TexFile := TFile.Open(FileName); Width := TexFile.ReadInt; Height := TexFile.ReadInt; Bpp := TexFile.ReadInt; glType := 0; case Bpp of 1: glType := GL_LUMINANCE; 3: glType := GL_RGB; 4: glType := GL_RGBA; end; Size := Width*Height*Bpp; Frames := TexFile.ReadInt; SetLength(Name, Frames); glGenTextures(Frames, @Name[0]); // Crashes here in Delphi 4 Freq := 1/TexFile.ReadInt; GetMem(ImageData, Size); for i:=0 to Frames-1 do begin TexFile.Read(ImageData^, Size); glBindTexture(GL_TEXTURE_2D, Name[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, TexWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, TexWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, TexFilter); if Mipmap then begin if TexFilter = GL_NEAREST then glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST) else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, Bpp, Width, Height, glType, GL_UNSIGNED_BYTE, ImageData); end else begin glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, TexFilter); glTexImage2D(GL_TEXTURE_2D, 0, Bpp, Width, Height, 0, glType, GL_UNSIGNED_BYTE, ImageData); end; end; FreeMem(ImageData); TexFile.Close; Console.Log('Load texture: ' + FileName + ' ID: ' + IntToStr(Name[0])); Current := Frames-1; CurrTexEnv := 0; Time := TTime.Create; CurrFrame := 0; end; procedure TTexture.Use(TexEnv: GLint); begin UseFrame(CurrFrame, TexEnv); if Time.Diff(Freq) then Inc(CurrFrame); if CurrFrame=Frames then begin CurrFrame := 0; Loop := True; end; end; procedure TTexture.UseFrame(n: Cardinal; TexEnv: GLint); begin if Name[n] <> Current then begin if TexEnv <> CurrTexEnv then begin CurrTexEnv := TexEnv; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, TexEnv); end; glBindTexture(GL_TEXTURE_2D, Name[n]); Current := Name[n]; end; end; destructor TTexture.Destroy; begin Console.Log('Unload texture ' + IntToStr(Name[0])); glDeleteTextures(Frames, @Name[0]); Time.Free; Name := nil; inherited Destroy; end; end.
unit ULinkedLists; {$mode objfpc}{$H+}{$J-} interface uses Classes, SysUtils; type TListElement = record Prev: ^TListElement; Next: ^TListElement; Data: Pointer; end; PListElement = ^TListElement; TSinglyLinkedList = record Head: PListElement; Tail: PListElement; Size: Cardinal; end; PSinglyLinkedList = ^TSinglyLinkedList; function NewSinglyLinkedList(): PSinglyLinkedList; procedure DestroySinglyLinkedList(List: PSinglyLinkedList); function SinglyLinkedListInsertInFront(List: PSinglyLinkedList; data: Pointer): PListElement; function SinglyLinkedListFind(List: PSinglyLinkedList; data: Pointer): PListElement; function SinglyLinkedListDeleteElement(List: PSinglyLinkedList; DeleteMe: PListElement): Boolean; function SinglyLinkedListInsertBefore(List: PSinglyLinkedList; InsertBeforeMe: PListElement; data: Pointer): PListElement; procedure PrintList(List: PSinglyLinkedList); implementation function NewSinglyLinkedList: PSinglyLinkedList; begin New(Result); Result^.Head := nil; Result^.Tail := nil; Result^.Size := 0; end; procedure DestroySinglyLinkedList(List: PSinglyLinkedList); var CurrentElement, NextElement: PListElement; begin CurrentElement := List^.Head; while CurrentElement <> nil do begin NextElement := CurrentElement^.Next; Dispose(CurrentElement); CurrentElement := NextElement; end; Dispose(List); end; function SinglyLinkedListInsertInFront(List: PSinglyLinkedList; data: Pointer): PListElement; begin New(Result); Result^.Data := data; Result^.Next := List^.Head; List^.Head := Result; if List^.Size = 0 then List^.Tail := Result; Inc(List^.Size); end; function SinglyLinkedListFind(List: PSinglyLinkedList; data: Pointer): PListElement; begin Result := List^.Head; while (Result <> nil) and (Result^.Data <> data) do begin Result := Result^.Next; end; end; function SinglyLinkedListDeleteElement(List: PSinglyLinkedList; DeleteMe: PListElement): Boolean; var CurrentElement: PListElement; begin if (List^.Size < 1) or (DeleteMe = nil) then Exit(False); if DeleteMe = List^.Head then begin List^.Head := List^.Head^.Next; Dispose(DeleteMe); Exit(True); end; CurrentElement := List^.Head; while CurrentElement <> nil do begin if CurrentElement^.Next = DeleteMe then begin CurrentElement^.Next := DeleteMe^.Next; if List^.Tail = DeleteMe then List^.Tail := CurrentElement; Dispose(DeleteMe); Exit(True); end; CurrentElement := CurrentElement^.Next; end; Result := False; end; function SinglyLinkedListInsertBefore(List: PSinglyLinkedList; InsertBeforeMe: PListElement; data: Pointer): PListElement; var CurrentElement: PListElement; function NewListElement(Data: Pointer): PListElement; begin New(Result); if Result = nil then Exit; Result^.Data := Data; end; begin Result := nil; if List^.Head = InsertBeforeMe then begin Result := SinglyLinkedListInsertInFront(List, data); Exit(Result); end; CurrentElement := List^.Head; while CurrentElement <> nil do begin if CurrentElement^.Next = InsertBeforeMe then begin Result := NewListElement(Data); if not Assigned(Result) then Exit(Result); Result^.Next := CurrentElement^.Next; CurrentElement^.Next := Result; if List^.Tail = CurrentElement then begin List^.Tail := Result; end; Inc(List^.Size); Exit(Result); end; CurrentElement := CurrentElement^.Next; end; end; procedure PrintList(List: PSinglyLinkedList); var Element: PListElement; Value: PInteger; begin WriteLn(Format('===Printing List size:%d===', [List^.Size])); Element := List^.Head; while Element <> nil do begin Value := PInteger(Element^.Data); WriteLn('Value:', Value^); Element := Element^.next; end; WriteLn(Format('===End Of List===', [List^.Size])); end; end.
Program SL2; Uses crt; Var x, y:real; Begin Clrscr; WriteLn('Привет, я могу считать значение Y по формуле: x^2 + |x - 8|'); Write('Введи значение x: '); ReadLn(x); y:= exp(2 * Ln(x)) + abs(x - 8); Writeln('Y = ', y:8:4); Repeat until keypressed; End.
unit uEditAlarmTemplate; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Grids, Menus, uCustomTypes,uEventClassifier, math, uStrUtils, uEditAlarmElement; type { TfEditAlarmTemplate } TfEditAlarmTemplate = class(TForm) bCancel: TButton; bOK: TButton; eATName: TEdit; Label1: TLabel; pmiCopyAlarmTask: TMenuItem; miCopyAlarmTask: TMenuItem; miActions: TMenuItem; miAddAlarmTask: TMenuItem; miDelAlarmTask: TMenuItem; miEditAlarmTask: TMenuItem; mmEditAlarmMenu: TMainMenu; pmEditBatchMenu: TPopupMenu; pmiAddAlarmTask: TMenuItem; pmiDelAlarmTask: TMenuItem; pmiEditAlarmTask: TMenuItem; sgATEdit: TStringGrid; procedure bCancelClick(Sender: TObject); procedure bOKClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure miAddAlarmTaskClick(Sender: TObject); procedure miCopyAlarmTaskClick(Sender: TObject); procedure miDelAlarmTaskClick(Sender: TObject); procedure miEditAlarmTaskClick(Sender: TObject); procedure pmiAddAlarmTaskClick(Sender: TObject); procedure pmiCopyAlarmTaskClick(Sender: TObject); procedure pmiDelAlarmTaskClick(Sender: TObject); procedure pmiEditAlarmTaskClick(Sender: TObject); procedure sgATEditDblClick(Sender: TObject); private { private declarations } public { public declarations } end; var fEditAlarmTemplate: TfEditAlarmTemplate; DecodedAT: tDecodedAlarmTemplate; initATName:string; res: TAlarmTemplateResult; function EditAlarmTemplate(in_atl:TAlarmTemplate;name_read_only:boolean):TAlarmTemplateResult; function DecodeAlarmTemplate(altt:TAlarmTemplate):tDecodedAlarmTemplate; function EncodeAlarmTemplate(a_name:string;tdatt:tDecodedAlarmTemplate):TAlarmTemplate; procedure RefreshList; procedure AddAlarmTemplateEl; procedure CopyAlarmTemplateEl; procedure EditAlarmTemplateEl; procedure DelAlarmTemplateEl; implementation {$R *.lfm} { TfEditAlarmTemplate } uses uAlarmTemplateEditor; function EditAlarmTemplate(in_atl:TAlarmTemplate;name_read_only:boolean):TAlarmTemplateResult; begin Application.CreateForm(TfEditAlarmTemplate, fEditAlarmTemplate); DecodedAT:=DecodeAlarmTemplate(in_atl); if length(DecodedAT)=1 then begin if DecodedAT[0].ate_param='err' then begin showmessage('Error decoding alarm template!'); Setlength(DecodedAT,0); end; end; fEditAlarmTemplate.eATName.Text:=in_atl.alarm_template_name; if name_read_only then begin fEditAlarmTemplate.eATName.Enabled:=false; end; RefreshList; res.res:=false; initATName:=in_atl.alarm_template_name; fEditAlarmTemplate.ShowModal; result:=res; end; procedure RefreshList; var x,l:integer; begin l:=length(DecodedAT); fEditAlarmTemplate.sgATEdit.RowCount:=max(l+1,2); if l=0 then begin fEditAlarmTemplate.sgATEdit.Cells[0,1]:=''; end; for x:=1 to l do begin fEditAlarmTemplate.sgATEdit.Cells[0,x]:=uEventClassifier.GetAlarmTypeStr(DecodedAT[x-1].ate_type,DecodedAT[x-1].ate_param); end; end; procedure TfEditAlarmTemplate.bCancelClick(Sender: TObject); begin Close; end; procedure TfEditAlarmTemplate.bOKClick(Sender: TObject); begin if length(DecodedAT)=0 then begin ShowMessage('Empty alarm template!'); Exit; end; if trim(eATName.Text)='' then begin ShowMessage('Empty alarm template name!'); Exit; end; if not ValidName(eATName.Text) then begin ShowMessage('Alarm template name contains invalid symbols!'); Exit; end; if uAlarmTemplateEditor.AlarmNameUsed(trim(eATName.Text),initATName) then begin ShowMessage('Alarm template name "'+trim(eATName.Text)+'" already used!'); Exit; end; res.atr_alarm_template:=EncodeAlarmTemplate(trim(eATName.Text),DecodedAT); res.res:=true; Close; end; procedure TfEditAlarmTemplate.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction:=caFree; end; procedure TfEditAlarmTemplate.miAddAlarmTaskClick(Sender: TObject); begin AddAlarmTemplateEl; end; procedure TfEditAlarmTemplate.miCopyAlarmTaskClick(Sender: TObject); begin CopyAlarmTemplateEl; end; procedure TfEditAlarmTemplate.miDelAlarmTaskClick(Sender: TObject); begin DelAlarmTemplateEl; end; procedure TfEditAlarmTemplate.miEditAlarmTaskClick(Sender: TObject); begin EditAlarmTemplateEl; end; procedure TfEditAlarmTemplate.pmiAddAlarmTaskClick(Sender: TObject); begin AddAlarmTemplateEl; end; procedure TfEditAlarmTemplate.pmiCopyAlarmTaskClick(Sender: TObject); begin CopyAlarmTemplateEl; end; procedure TfEditAlarmTemplate.pmiDelAlarmTaskClick(Sender: TObject); begin DelAlarmTemplateEl; end; procedure TfEditAlarmTemplate.pmiEditAlarmTaskClick(Sender: TObject); begin EditAlarmTemplateEl; end; procedure TfEditAlarmTemplate.sgATEditDblClick(Sender: TObject); begin EditAlarmTemplateEl; end; function DecodeAlarmTemplate(altt:TAlarmTemplate):tDecodedAlarmTemplate; var count:integer; x:integer; tmp:string; begin setlength(result,0); try count:=strtoint(uStrUtils.GetFieldFromString(altt.alarm_template_str, ParamLimiter, 1)); setlength(result,count); for x:=1 to count do begin result[x-1].ate_param:=uStrUtils.GetFieldFromString(altt.alarm_template_params,ParamLimiter,x); result[x-1].ate_type:=strtoint(uStrUtils.GetFieldFromString(altt.alarm_template_str,ParamLimiter,x+1)); end; except setlength(result,1); Result[0].ate_param:='err'; end; end; function EncodeAlarmTemplate(a_name:string;tdatt:tDecodedAlarmTemplate):TAlarmTemplate; var x,l:integer; begin l:=Length(tdatt); Result.alarm_template_name:=a_name; Result.alarm_template_str:=inttostr(l)+ParamLimiter; Result.alarm_template_params:=''; for x:=1 to l do begin Result.alarm_template_str:=Result.alarm_template_str+inttostr(tdatt[x-1].ate_type)+ParamLimiter; Result.alarm_template_params:=Result.alarm_template_params+tdatt[x-1].ate_param+ParamLimiter; end; end; procedure EditAlarmTemplateEl; var r:integer; aer:TDecodedAlarmTemplateElementResult; begin r:=fEditAlarmTemplate.sgATEdit.Row; if r<1 then begin ShowMessage('Select alarm template element first!'); exit; end; if r>Length(DecodedAT) then begin ShowMessage('Select alarm template element first!'); exit; end; aer:=uEditAlarmElement.EditAlarmElement(DecodedAT[r-1]); if aer.res then begin DecodedAT[r-1]:=aer.daer_alarm_element; RefreshList; end; end; procedure CopyAlarmTemplateEl; var r:integer; aer:TDecodedAlarmTemplateElementResult; begin r:=fEditAlarmTemplate.sgATEdit.Row; if r<1 then begin ShowMessage('Select alarm template element first!'); exit; end; if r>Length(DecodedAT) then begin ShowMessage('Select alarm template element first!'); exit; end; aer:=uEditAlarmElement.EditAlarmElement(DecodedAT[r-1]); if aer.res then begin SetLength(DecodedAT,length(DecodedAT)+1); DecodedAT[length(DecodedAT)-1]:=aer.daer_alarm_element; RefreshList; end; end; procedure AddAlarmTemplateEl; var aer:TDecodedAlarmTemplateElementResult; dat:TDecodedAlarmTemplateElement; begin dat.ate_type:=1; dat.ate_param:=''; aer:=uEditAlarmElement.EditAlarmElement(dat); if aer.res then begin SetLength(DecodedAT,length(DecodedAT)+1); DecodedAT[length(DecodedAT)-1]:=aer.daer_alarm_element; RefreshList; end; end; procedure DelAlarmTemplateEl; var r,x:integer; begin r:=fEditAlarmTemplate.sgATEdit.Row; if r<1 then begin ShowMessage('Select alarm template element first!'); exit; end; if r>Length(DecodedAT) then begin ShowMessage('Select alarm template element first!'); exit; end; if MessageDlg('Are you sure?','Delete alarm?',mtConfirmation,[mbYes, mbNo],0)=mrYes then begin for x:=r to Length(DecodedAT)-1 do begin DecodedAT[x-1]:=DecodedAT[x]; end; SetLength(DecodedAT,Length(DecodedAT)-1); RefreshList; end; end; end.
unit View.Base; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.StdCtrls, Vcl.ComCtrls, DwmApi, JvComponentBase, JvWndProcHook, Method.Colors; type TProc = procedure of Object; TBorda = (bLeft, bTop, bRight, bBottom, bBottomLeft, bBottomRight); TfrmBase = class(TForm) pnlActionBar: TPanel; pnlClose: TPanel; imgClose: TImage; pnlMinimize: TPanel; imgMinimize: TImage; pnlPrincipal: TPanel; pnlMaximize: TPanel; imgMaximize: TImage; lblCaption: TLabel; pnlTop: TPanel; pnlSubCaption: TPanel; lblSubCaption: TLabel; imgIcon: TImage; procedure pnlActionBarMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgCloseClick(Sender: TObject); procedure imgMinimizeClick(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgMaximizeClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private FControleForm: Boolean; FSubCaption: String; FCaption: String; FFormColor: TColor; FWndFrameSize: Integer; function TipoMouse(ABorda: TBorda): TCursor; procedure setControleForm(const Value: Boolean); procedure setCaption(const Value: String); procedure setSubCaption(const Value: String); procedure setFormColor(const Value: TColor); public constructor Create(AOwner: TComponent; AControlarForm: Boolean = True); property ControleForm: Boolean read FControleForm write setControleForm; property FormColor: TColor read FFormColor write setFormColor; protected procedure WmNCCalcSize(var Msg: TWMNCCalcSize); message WM_NCCALCSIZE; property Caption: String read FCaption write setCaption; property SubCaption: String read FSubCaption write setSubCaption; end; var frmBase: TfrmBase; implementation {$R *.dfm} procedure TfrmBase.WmNCCalcSize(var Msg: TWMNCCalcSize); begin Msg.Result := 0; end; procedure TfrmBase.FormCreate(Sender: TObject); begin BorderStyle := bsNone; SetWindowLong(Handle ,GWL_STYLE ,WS_CLIPCHILDREN or WS_OVERLAPPEDWINDOW ); FormColor := clPurple; end; procedure TfrmBase.FormShow(Sender: TObject); begin Width := (Width - 1); end; constructor TfrmBase.Create(AOwner: TComponent; AControlarForm: Boolean = True); begin inherited Create(AOwner); ControleForm := AControlarForm; end; function TfrmBase.TipoMouse(ABorda: TBorda): TCursor; begin case(ABorda)of bLeft, bRight: Result := crSizeWE; bTop, bBottom: Result := crSizeNS; bBottomLeft: Result := crSizeNESW; bBottomRight: Result := crSizeNWSE; end; end; procedure TfrmBase.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if((Button = mbLeft)and(FControleForm))then begin ReleaseCapture; {Left Bottom} if(((X >= 0)and(X <= 8)) and ((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight)))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_BOTTOMLEFT, 0); Exit; end; {Right Bottom} if(((X >= (Self.ClientWidth -8))and(X <= Self.ClientWidth)) and ((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight)))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_BOTTOMRIGHT, 0); Exit; end; {Left} if((X >= 0)and(X <= 8))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_LEFT, 0); end; {Right} if((X >= (Self.ClientWidth -8))and(X <= Self.ClientWidth))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_RIGHT, 0); end; {Bottom} if((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_BOTTOM, 0); end; {Top} if((Y >= 0)and(Y <= 10))then begin TForm(Self).Perform(WM_SYSCOMMAND, SC_SIZE + WMSZ_TOP, 0); end; end; end; procedure TfrmBase.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if(FControleForm)then begin {Left} if((X >= 0)and(X <= 8))then begin Self.Cursor := TipoMouse(bLeft); end; {Right} if((X >= (Self.ClientWidth -8))and(X <= Self.ClientWidth))then begin Self.Cursor := TipoMouse(bRight); end; {Bottom} if((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight))then begin Self.Cursor := TipoMouse(bBottom); end; {Top} if((Y >= 0)and(Y <= 10))then begin Self.Cursor := TipoMouse(bTop); end; {Left Bottom} if(((X >= 0)and(X <= 8)) and ((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight)))then begin Self.Cursor := TipoMouse(bBottomLeft); end; {Right Bottom} if(((X >= (Self.ClientWidth -8))and(X <= Self.ClientWidth)) and ((Y >= (Self.ClientHeight -8))and(Y <= Self.ClientHeight)))then begin Self.Cursor := TipoMouse(bBottomRight); end; end; end; procedure TfrmBase.imgCloseClick(Sender: TObject); begin Close; end; procedure TfrmBase.imgMaximizeClick(Sender: TObject); begin if(Self.Parent = Nil)then begin if(WindowState = wsNormal)then WindowState := TWindowState.wsMaximized else WindowState := TWindowState.wsNormal; end else begin Self.Parent := Nil; Self.Align := alNone; Self.WindowState := wsMaximized; end; end; procedure TfrmBase.imgMinimizeClick(Sender: TObject); begin WindowState := TWindowState.wsMinimized; end; procedure TfrmBase.pnlActionBarMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); const sc_DragMove = $f012; begin ReleaseCapture; Perform(wm_SysCommand, sc_DragMove, 0); end; procedure TfrmBase.setCaption(const Value: String); begin FCaption := Value; lblCaption.Caption := FCaption; lblCaption.Hint := FCaption; end; procedure TfrmBase.setSubCaption(const Value: String); begin FSubCaption := Value; lblSubCaption.Caption := FSubCaption; lblSubCaption.Hint := FSubCaption; end; procedure TfrmBase.setControleForm(const Value: Boolean); begin FControleForm := Value; pnlActionBar.Visible := FControleForm; pnlPrincipal.AlignWithMargins := FControleForm; end; procedure TfrmBase.setFormColor(const Value: TColor); begin FFormColor := Value; Self.Color := FFormColor; pnlActionBar.Color := FFormColor; pnlSubCaption.Color := CorEscura(FFormColor); lblCaption.Color := FFormColor; lblSubCaption.Color := FFormColor; pnlMinimize.Color := FFormColor; pnlMaximize.Color := FFormColor; pnlMaximize.Color := FFormColor; end; end.
{ Script generates 31 enchanted copies of selected weapons per each, adds enchantment, alters new records value, and adds respected Suffixes for easy parsing and replace. For armors script will make only one enchanted copy per each, for now. All enchanted versions will have it's proper Temper COBJ records as well. Also, for each selected WEAP/ARMO record, will be created a Leveled List, with Base item + all it's enchanted versions. Each with count of 1, and based on enchantment level requirement NOTE: Should be applied on records inside WEAPON/ARMOR (WEAP/ARMO) category of plugin you want to edit (script will not create new plugin) NOTE: So script works with Weapons/Shields/Bags/Bandanas/Armor/Clothing/Amulets/Wigs... every thing, but script won't find right item requirements for tempering wig or amulet... probably... However it will make a recipe, and it will log a message with link on that recipe, in this case, you can simply delete Tempering record or edit it... that is your Skyrim after all :O) } unit GenerateEnchantedVersions; uses SkyrimUtils; // =Settings const // should generator add MagicDisallowEnchanting keyword to the enchanted versions? (boolean) setMagicDisallowEnchanting = false; // on how much the enchanted versions value should be multiplied (integer or real (aka float)) enchantedValueMultiplier = 1; // creates an enchanted copy of the weapon record and returns it function createEnchantedVersion(baseRecord: IInterface; objEffect: string; suffix: string; enchantmentAmount: integer): IInterface; var enchRecord, enchantment, keyword: IInterface; begin enchRecord := wbCopyElementToFile(baseRecord, GetFile(baseRecord), true, true); // find record for Object Effect ID enchantment := getRecordByFormID(objEffect); // add object effect SetElementEditValues(enchRecord, 'EITM', GetEditValue(enchantment)); // set enchantment amount SetElementEditValues(enchRecord, 'EAMT', enchantmentAmount); // set it's value, cause enchantments are more expensive // Vanilla formula [Total Value] = [Base Item Value] + 0.12*[Charge] + [Enchantment Value] // credits: http://www.uesp.net/wiki/Skyrim_talk:Generic_Magic_Weapons // don't know how to make [Enchantment Value] without hardcoding every thing, so made it just for similar results, suggestions are welcome :O) SetElementEditValues( enchRecord, 'DATA\Value', round( getPrice(baseRecord) + (0.12 * enchantmentAmount) + (1.4 * (enchantmentAmount / GetElementEditValues(enchantment, 'ENIT\Enchantment Cost'))) // 1.4 * <number of uses> * enchantedValueMultiplier ) ); // change name by adding suffix SetElementEditValues(enchRecord, 'EDID', GetElementEditValues(baseRecord, 'EDID') + 'Ench' + suffix); // suffix the FULL, for easy finding and manual editing SetElementEditValues(enchRecord, 'FULL', GetElementEditValues(baseRecord, 'FULL') + ' ( ' + suffix + ' )'); makeTemperable(enchRecord); if setMagicDisallowEnchanting = true then begin // add MagicDisallowEnchanting [KYWD:000C27BD] keyword if not present addKeyword(enchRecord, getRecordByFormID('000C27BD')); end; // return it Result := enchRecord; end; // runs on script start function Initialize: integer; begin AddMessage('---Starting Generator---'); Result := 0; end; // for every record selected in xEdit function Process(selectedRecord: IInterface): integer; var newRecord: IInterface; enchLevelList, enchLevelListGroup: IInterface; workingFile: IwbFile; recordSignature: string; begin recordSignature := Signature(selectedRecord); // filter selected records, which are invalid for script if not ((recordSignature = 'WEAP') or (recordSignature = 'ARMO')) then Exit; // create Leveled List for proper distribution enchLevelList := createRecord( GetFile(selectedRecord), // plugin 'LVLI' // category ); // set the flags SetElementEditValues(enchLevelList, 'LVLF', 11); // 11 => Calculate from all levels, and for each item in count // define items group inside the Leveled List Add(enchLevelList, 'Leveled List Entries', true); enchLevelListGroup := ElementByPath(enchLevelList, 'Leveled List Entries'); // add selected record for vanillish style of rare stuff addToLeveledList(enchLevelList, selectedRecord, 1); // remove automatic zero entry removeInvalidEntries(enchLevelList); //------------------------ // =SKYRIM OBJECT EFFECTS //------------------------ if recordSignature = 'WEAP' then begin SetElementEditValues(enchLevelList, 'EDID', 'LItemWeaponsEnch' + GetElementEditValues(selectedRecord, 'EDID')); // FireEffects addToLeveledList( enchLevelList, createEnchantedVersion( selectedRecord, // baseRecord, '00049BB7', // EnchWeaponFireDamage01 'Fire01', // suffix 800 // enchantmentAmount ), 1 // required level ); addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C2A', 'Fire02', 900), 3); // EnchWeaponFireDamage02 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C2C', 'Fire03', 1000), 5); // EnchWeaponFireDamage03 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C2D', 'Fire04', 1200), 10); // EnchWeaponFireDamage04 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C30', 'Fire05', 1500), 15); // EnchWeaponFireDamage05 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C35', 'Fire06', 2000), 20); // EnchWeaponFireDamage06 // Frost addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C36', 'Frost01', 800), 1); // EnchWeaponFrostDamage01 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C37', 'Frost02', 900), 3); // EnchWeaponFrostDamage02 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045C39', 'Frost03', 1000), 5); // EnchWeaponFrostDamage03 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045D4B', 'Frost04', 1200), 10); // EnchWeaponFrostDamage04 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045D56', 'Frost05', 1500), 15); // EnchWeaponFrostDamage05 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '00045D58', 'Frost06', 2000), 20); // EnchWeaponFrostDamage06 // Magicka addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B453', 'Magicka01', 800), 1); // EnchWeaponMagickaDamage01 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B454', 'Magicka02', 900), 3); // EnchWeaponMagickaDamage02 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B455', 'Magicka03', 1000), 5); // EnchWeaponMagickaDamage03 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B456', 'Magicka04', 1200), 10); // EnchWeaponMagickaDamage04 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B457', 'Magicka05', 1500), 15); // EnchWeaponMagickaDamage05 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B458', 'Magicka06', 2000), 20); // EnchWeaponMagickaDamage06 // Fear addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '000FBFF7', 'Fear01', 800), 1); // EnchWeaponFear01 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B466', 'Fear02', 900), 5); // EnchWeaponFear02 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B467', 'Fear03', 1000), 10); // EnchWeaponFear03 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B468', 'Fear04', 1200), 15); // EnchWeaponFear04 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B469', 'Fear05', 1500), 20); // EnchWeaponFear05 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B46A', 'Fear06', 2000), 25); // EnchWeaponFear06 // Soul Trap addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B45F', 'SoulTrap01', 800), 1); // EnchWeaponSoulTrap01 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B460', 'SoulTrap02', 900), 5); // EnchWeaponSoulTrap02 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B461', 'SoulTrap03', 1000), 10); // EnchWeaponSoulTrap03 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B462', 'SoulTrap04', 1200), 15); // EnchWeaponSoulTrap04 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B463', 'SoulTrap05', 1500), 20); // EnchWeaponSoulTrap05 addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '0005B464', 'SoulTrap06', 2000), 25); // EnchWeaponSoulTrap06 // Absorb Health addToLeveledList(enchLevelList, createEnchantedVersion(selectedRecord, '000AA145', 'AbsorbHealth02', 1000), 4); // EnchWeaponAbsorbHealth02 // Misc enchantments // =Adding enchantments for WEAP records end else if recordSignature = 'ARMO' then begin SetElementEditValues(enchLevelList, 'EDID', 'LItemArmorEnch' + GetElementEditValues(selectedRecord, 'EDID')); // Fire Resistence Effects addToLeveledList( enchLevelList, createEnchantedVersion( selectedRecord, // baseRecord, '0004950B', // EnchArmorResistFire01 'Fire01', // suffix 800 // enchantmentAmount ), 1 // required level ); // =Adding enchantments for ARMO records end; Result := 0; end; // runs in the end function Finalize: integer; begin FinalizeUtils(); AddMessage('---Ending Generator---'); Result := 0; end; end.
unit resources; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, SQLiteWrap; function MyMessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; Captions: array of string): Integer; function ConvertDate(datum:string):string; function getParcela_godina_id(godina_id:integer;parcela_id:integer):integer; implementation function MyMessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; Captions: array of string): Integer; var aMsgDlg: TForm; i: Integer; dlgButton: TButton; CaptionIndex: Integer; begin { Create the Dialog } { Dialog erzeugen } aMsgDlg := CreateMessageDialog(Msg, DlgType, Buttons); captionIndex := 0; { Loop through Objects in Dialog } { Über alle Objekte auf dem Dialog iterieren} for i := 0 to aMsgDlg.ComponentCount - 1 do begin { If the object is of type TButton, then } { Wenn es ein Button ist, dann...} //ShowMessage(Captions[CaptionIndex]); if (aMsgDlg.Components[i] is TCustomButton) then begin dlgButton := TButton(aMsgDlg.Components[i]); if CaptionIndex > High(Captions) then Break; { Give a new caption from our Captions array} { Schreibe Beschriftung entsprechend Captions array} dlgButton.Caption := Captions[CaptionIndex]; Inc(CaptionIndex); end; end; Result := aMsgDlg.ShowModal; end; function ConvertDate(datum:string):string; var Y, M, D: Word; datum_datum:TDateTime; begin Y := StrToInt(Copy(datum,1,4)); M := StrToInt(Copy(datum,6,2)); D := StrToInt(Copy(datum,9,2)); datum_datum := EncodeDate(Y,M,D); Result:=FormatDateTime('DD.MM.YYYY',datum_datum); end; function getParcela_godina_id(godina_id:integer;parcela_id:integer):integer; var Database : TsqliteDatabase; Table : TSQLiteTable; begin Database := TsqliteDatabase.Create('Data/gazdinstvo.db3'); Database.AddParamInt(':godina', godina_id); Database.AddParamInt(':parcela', parcela_id); Table := Database.GetTable('SELECT id FROM godina_parcela WHERE godina=:godina AND parcela=:parcela'); if Table.EOF then begin Result := 0; end else begin Result := Table.FieldAsInteger(Table.FieldIndex['id']); end; Table.Free; Database.Free; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 250 of 298 From : David Solly 1:163/215.0 12 Apr 93 11:20 To : Moshe Harel Subj : Letrix to Q-Text file 1/ ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ Moshe... Please find below the Turbo Pascal source code for the conversion program for making Letrix Hebrew files into Q-Text 2.10 files. I could not find a way to make this conversion program convert embedded Roman text without making it into a monster. If you have any suggestions, I would be thankful to the input. ========================= Cut Here ======================== } Program LetrixQText; {$D-} Uses CRT, DOS; VAR Infile, Transfile : Text; Infilenm, Transfilenm : PathStr; Letter, Ans : Char; Printable, HiASCII : Set of Char; { "UpItsCase" is a function that takes a sting of any length and sets all of the characters in the string to upper case. It is handy for comparing strings. } function UpItsCase (SourceStr : PathStr): PathStr; var i : integer; begin for i := 1 to length(SourceStr) do SourceStr[i] := UpCase(SourceStr[i]); UpItsCase := SourceStr end; {function UpItsCase} Function Exist(fname : PathStr) : Boolean; Var f : File; BEGIN {$F-,I-} Assign(f, fname); Reset(f); Close(f); {$I+} Exist := (IOResult = 0) AND (fname <> '') END; {Function exist} Procedure Help; Begin Writeln; Writeln ('LTQT (Version 1.0)'); Writeln ('Hebrew Text File Conversion'); Writeln ('Letrix(R) 3.6 file to Q-Text 2.10 file'); Writeln; Writeln; Writeln ('LTQT converts Letrix Hebrew format files to Q-Text format files.'); Writeln; Writeln ('LTQT expects two parameters on the command line.'); Writeln ('The first parameter is the name of the file to convert,'); Writeln ('the second is the name of the new file.'); Writeln; Writeln ('Example: LTQT HKVTL.TXT HKVTL.HEB'); Writeln; Writeln ('If no parameters are found, LTQT will display this message.'); Writeln; Halt; End; {Procedure Help} { "ParseCommandLine" is a procedure that checks if any data was input at the DOS command line. If no data is there, then the "Help" procedure is executed and the program is halted. Otherwise, the Mode strig variable is set equal to the text on the command line. } procedure ParseCommandLine; begin if (ParamCount = 0) or (ParamCount <> 2) then Help else begin Infilenm := ParamStr(1); Infilenm := UpItsCase(Infilenm); Transfilenm := ParamStr(2); Transfilenm := UpItsCase(Transfilenm); end; end; {procedure ParseCommandLine} Procedure OpenFiles; BEGIN {Open input/output files} If not exist(Infilenm) then Begin Writeln; Writeln (Infilenm, ' not found'); Halt; End Else Begin Assign (Infile, Infilenm); Reset (Infile); End; If exist (Transfilenm) then Begin Writeln; Writeln (Transfilenm, ' already exists!'); Write ('Overwrite it? (Y/N) > '); Repeat Ans := Readkey; Ans := Upcase(Ans); If Ans = 'N' then Halt; Until Ans = 'Y'; End; Assign (Transfile, Transfilenm); Rewrite (Transfile); Writeln; End; {Procedure OpenFiles} Procedure LT_Table (VAR Letter : Char); { This section reviews each Letrix letter and matches it with a Q-Text equivalent where possible } BEGIN CASE Letter of 'a' : Write (Transfile, #128); 'b', 'B','v' : Write (Transfile, #129); {Vet, Bet} 'g' : Write (Transfile, #130); 'd' : Write (Transfile, #131); 'h' : Write (Transfile, #132); 'V', 'o', 'u', 'w' : Write (Transfile, #133); {Vav, Holem male, Shuruq} 'z' : Write (Transfile, #134); 'H' : Write (Transfile, #135); 'T' : Write (Transfile, #136); 'y', 'e' : Write (Transfile, #137); {Yod} 'C', 'Q', 'W' : Write (Transfile, #138); {Khaf-Sofit} 'c', 'K' : Write (Transfile, #139); {Khaf, Kaf} 'l' : Write (Transfile, #140); 'M' : Write (Transfile, #141); 'm' : Write (Transfile, #142); 'N' : Write (Transfile, #143); 'n' : Write (Transfile, #144); 'S' : Write (Transfile, #145); 'i' : Write (Transfile, #146); 'F' : Write (Transfile, #147); 'p', 'P', 'f' : Write (Transfile, #148); {Fe, Pe} 'X' : Write (Transfile, #149); 'x' : Write (Transfile, #150); 'k' : Write (Transfile, #151); 'r' : Write (Transfile, #152); 's' : Write (Transfile, #153); 't' : Write (Transfile, #154); 'A' : Write (Transfile, '-'); {Niqudim and unused letters} 'D','E', 'G', 'I', 'J', 'j', 'O', 'q', 'R', 'U', 'Y', 'Z' : Write(Transfile, ''); else Write(Transfile, Letter); End; {Case of} End; {Procedure LT_Table} Procedure DoIt; BEGIN {Transcription loop} While not eof(Infile) do Begin Read(Infile, Letter); If (Letter in Printable) then LT_Table(Letter); If (Letter in HiASCII) then Write(Transfile, Letter); End; {while} {Close files} Close (Transfile); Close (Infile); {Final message} Writeln; Writeln; Writeln('LTQT Version 1.0'); Writeln('Hebrew Text File Conversion'); Writeln('Letrix(R) 3.6 file to Q-Text 2.10 file'); Writeln; Writeln; Writeln ('Letrix Hebrew file to Q-Text file conversion complete.'); Writeln; Writeln('Special Note:'); Writeln; Writeln ('Q-Text does not support either dagesh or niqudim (vowels).'); Writeln ('Letters containing a dagesh-qol are reduced to their simple form.'); Writeln ('Holam male and shuruq are transcribed as vav. Roman letters used'); Writeln ('to represent niqudim are ignored. All other symbols are transcribed'); Writeln ('without change.'); Writeln; Writeln ('There is no foreign language check -- Anything that can be transcribed'); Writeln ('into Hebrew characters will be.'); Writeln; Writeln ('LTQT was written and released to the public domain by David Solly'); Writeln ('Bibliotheca Sagittarii, Ottawa, Canada (8 December 1992).'); Writeln; End; {Procedure DoIt} BEGIN {Initialize Variables} Printable := [#10,#12,#13,#32..#127]; HiASCII := [#128..#154]; ParseCommandLine; OpenFiles; DoIt; End.
unit TBGRestDWDriver.Model.Query; interface uses TBGConnection.Model.Interfaces, Data.DB, System.Classes, System.SysUtils, uRESTDWPoolerDB, TBGConnection.Model.DataSet.Interfaces, TBGConnection.Model.DataSet.Proxy, FireDAC.Comp.Client, TBGConnection.Model.DataSet.Observer, System.Generics.Collections, TBGConnection.Model.Helper; Type TRestDWModelQuery = class(TInterfacedObject, iQuery) private FConexao: TRESTDWDataBase; vUpdateTableName : String; FKey : Integer; FDriver : iDriver; FQuery: TList<TRESTDWClientSQL>; FDataSource: TDataSource; FDataSet: TDictionary<integer, iDataSet>; FChangeDataSet: TChangeDataSet; FSQL : String; FGetDataSet: iDataSet; FParams : TParams; procedure InstanciaQuery; function GetDataSet : iDataSet; function GetQuery : TRESTDWClientSQL; procedure SetQuery(Value: TRESTDWClientSQL); public constructor Create(Conexao: TRESTDWDataBase; Driver : iDriver); destructor Destroy; override; class function New(Conexao: TRESTDWDataBase; Driver : iDriver): iQuery; //iObserver procedure ApplyUpdates(DataSet : TDataSet); // iQuery function Open(aSQL: String): iQuery; function ExecSQL(aSQL: String): iQuery; overload; function DataSet(Value: TDataset): iQuery; overload; function DataSet: Tdataset; overload; function DataSource(Value: TDataSource): iQuery; function Fields: TFields; function ChangeDataSet(Value: TChangeDataSet): iQuery; function &End: TComponent; function Tag(Value: Integer): iQuery; function LocalSQL(Value: TComponent): iQuery; function Close : iQuery; function SQL : TStrings; function Params : TParams; function ExecSQL : iQuery; overload; function ParamByName(Value : String) : TParam; function UpdateTableName(Tabela : String) : iQuery; end; implementation { TRestDWModelQuery } function TRestDWModelQuery.&End: TComponent; begin Result := GetQuery; end; function TRestDWModelQuery.ExecSQL: iQuery; var VError : String; begin Result := Self; if not GetQuery.ExecSQL(VError) Then raise Exception.Create('Erro: ' + vError + sLineBreak + 'Ao executar o comando: ' + GetQuery.SQL.Text); FDriver.Cache.ReloadCache(''); // ApplyUpdates(nil); end; function TRestDWModelQuery.ExecSQL(aSQL: String): iQuery; var VError : String; begin GetQuery.SQL.Text := aSQL; if not GetQuery.ExecSQL(VError) Then raise Exception.Create('Erro: ' + vError + sLineBreak + 'Ao executar o comando: ' + GetQuery.SQL.Text); FDriver.Cache.ReloadCache(''); // ApplyUpdates(nil); end; function TRestDWModelQuery.Fields: TFields; begin Result := GetQuery.Fields; end; function TRestDWModelQuery.GetDataSet : iDataSet; begin Result := FDataSet.Items[FKey]; end; function TRestDWModelQuery.GetQuery: TRESTDWClientSQL; begin Result := FQuery.Items[Pred(FQuery.Count)]; end; procedure TRestDWModelQuery.InstanciaQuery; var Query : TRESTDWClientSQL; begin Query := TRESTDWClientSQL.Create(nil); Query.DataBase := FConexao; Query.AfterPost := ApplyUpdates; Query.AfterDelete := ApplyUpdates; Query.AutoCommitData := False; Query.AutoRefreshAfterCommit := True; Query.InBlockEvents := false; FQuery.Add(Query); end; function TRestDWModelQuery.LocalSQL(Value: TComponent): iQuery; begin Result := Self; GetQuery.LocalSQL := TFDCustomLocalSQL(Value); end; procedure TRestDWModelQuery.ApplyUpdates(DataSet: TDataSet); var vError : String; begin if Not GetQuery.ApplyUpdates(vError) then raise Exception.Create(vError); FDriver.Cache.ReloadCache(''); end; function TRestDWModelQuery.ChangeDataSet(Value: TChangeDataSet): iQuery; begin Result := Self; FChangeDataSet := Value; end; function TRestDWModelQuery.Close: iQuery; begin Result := Self; GetQuery.Close; end; constructor TRestDWModelQuery.Create(Conexao: TRESTDWDataBase; Driver : iDriver); begin FDriver := Driver; FConexao := Conexao; FQuery := TList<TRESTDWClientSQL>.Create; FDataSet := TDictionary<integer, iDataSet>.Create; InstanciaQuery; end; function TRestDWModelQuery.DataSet: Tdataset; begin Result := GetQuery; end; function TRestDWModelQuery.DataSet(Value: Tdataset): iQuery; begin Result := Self; GetDataSet.DataSet(TRESTDWClientSQL(Value)); end; function TRestDWModelQuery.DataSource(Value: TDataSource): iQuery; begin Result := Self; FDataSource := Value; end; destructor TRestDWModelQuery.Destroy; begin FreeAndNil(FQuery); FreeAndNil(FDataSet); inherited; end; class function TRestDWModelQuery.New(Conexao: TRESTDWDataBase; Driver : iDriver): iQuery; begin Result := Self.Create(Conexao, Driver); end; function TRestDWModelQuery.Open(aSQL: String): iQuery; var Query : TRESTDWClientSQL; DataSet : iDataSet; begin Result := Self; FSQL := aSQL; if not FDriver.Cache.CacheDataSet(FSQL, DataSet) then begin InstanciaQuery; DataSet.SQL(FSQL); DataSet.DataSet(GetQuery); GetQuery.Close; GetQuery.UpdateTableName := vUpdateTableName; GetQuery.SQL.Text := FSQL; GetQuery.Open; FDriver.Cache.AddCacheDataSet(DataSet.GUUID, DataSet); end else SetQuery(TRESTDWClientSQL(DataSet.DataSet)); FDataSource.DataSet := DataSet.DataSet; Inc(FKey); FDataSet.Add(FKey, DataSet); end; function TRestDWModelQuery.ParamByName(Value: String): TParam; begin Result := GetQuery.ParamByName(Value); end; function TRestDWModelQuery.Params: TParams; begin Result := GetQuery.Params; end; procedure TRestDWModelQuery.SetQuery(Value: TRESTDWClientSQL); begin FQuery.Items[Pred(FQuery.Count)] := Value; end; function TRestDWModelQuery.SQL: TStrings; begin Result := GetQuery.SQL; end; function TRestDWModelQuery.Tag(Value: Integer): iQuery; begin Result := Self; GetQuery.Tag := Value; end; function TRestDWModelQuery.UpdateTableName(Tabela : String) : iQuery; begin Result := Self; vUpdateTableName := Tabela; end; end.
unit AutoFree; interface type TAutoFree = record private FInstance: TObject; // Reference public constructor Create(const AInstance: TObject); class operator Initialize(out ADest: TAutoFree); class operator Finalize(var ADest: TAutoFree); class operator Assign(var ADest: TAutoFree; const [ref] ASrc: TAutoFree); end; implementation uses System.Classes; { TAutoFree } constructor TAutoFree.Create(const AInstance: TObject); begin Assert(Assigned(AInstance)); FInstance := AInstance; end; class operator TAutoFree.Initialize(out ADest: TAutoFree); begin ADest.FInstance := nil; end; class operator TAutoFree.Finalize(var ADest: TAutoFree); begin ADest.FInstance.Free; end; class operator TAutoFree.Assign(var ADest: TAutoFree; const [ref] ASrc: TAutoFree); begin raise EInvalidOperation.Create( 'TAutoFree records cannot be copied') end; end.
{----------------------------------------------------------------------------- Unit Name: RbStyleManagerReg Purpose: Component Editor for RbStyleManager Author/Copyright: NathanaŽl VERON - r.b.a.g@free.fr - http://r.b.a.g.free.fr Feel free to modify and improve source code, mail me (r.b.a.g@free.fr) if you make any big fix or improvement that can be included in the next versions. If you use the RbControls in your project please mention it or make a link to my website. =============================================== /* 14/10/2003 */ Creation -----------------------------------------------------------------------------} unit RbStyleManagerReg; interface uses {$IFDEF VER130} DsgnIntf, {$ELSE} DesignEditors, DesignIntf, {$ENDIF} Menus, RbDrawCore, Forms, Controls, Dialogs, windows; type TRbStyleManagerEditor = class(TComponentEditor) public { Public declarations } procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; procedure Register; implementation uses RbStyleEditor; procedure Register; begin RegisterComponentEditor( TRbStyleManager, TRbStyleManagerEditor); end; {--------------------------------------------- TRbStyleManagerEditor ---------------------------------------------} procedure TRbStyleManagerEditor.Edit; begin inherited; end; procedure TRbStyleManagerEditor.ExecuteVerb(Index: Integer); begin case Index of 0: begin with TFStyleEditor.Create(Application) do try Loading := true; TRbStyleManager(Component).AssignTo(Smgr); UpdateComps; Loading := false; if ShowModal <> mrOk then Exit; SMgr.AssignTo(TRbStyleManager(Component)); TRbStyleManager(Component).UpdateStyle; if Designer <> nil then Designer.Modified; finally Free; end; end; 1: TRbStyleManager(Component).UpdateStyle; end; end; function TRbStyleManagerEditor.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Style Manager...'; 1: Result := 'Apply Style'; end; end; function TRbStyleManagerEditor.GetVerbCount: Integer; begin Result := 2; end; end.
unit uTherapyHistory; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, StdCtrls, cxButtons, uDB, uGlobal, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinCaramel, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, ExtCtrls, cxGridLevel, cxGridBandedTableView, cxGridDBBandedTableView, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxGroupBox, ADODB, DBCtrls, cxCheckBox, dxSkinBlack, dxSkinBlue, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinFoggy, dxSkinGlassOceans, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinPumpkin, dxSkinSeven, dxSkinSharp, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinsDefaultPainters, dxSkinValentine, dxSkinXmas2008Blue, dxSkinBlueprint, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinHighContrast, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinSevenClassic, dxSkinSharpPlus, dxSkinTheAsphaltWorld, dxSkinVS2010, dxSkinWhiteprint, dxSkinscxPCPainter, cxNavigator; type TfrmTherapyHistory = class(TForm) btnOK: TcxButton; btnClose: TcxButton; adoSchedule: TADOQuery; cxGroupBox1: TcxGroupBox; cxGrid: TcxGrid; cxGList: TcxGridDBTableView; cxGridDBBandedTableView1: TcxGridDBBandedTableView; cxGridDBTableView2: TcxGridDBTableView; cxGridLevel1: TcxGridLevel; dsSchedule: TDataSource; cxGroupBox22: TcxGroupBox; cxGroupBox10: TcxGroupBox; cxGroupBox11: TcxGroupBox; TimerShow: TTimer; cxGListContent: TcxGridDBColumn; cxGListSDate: TcxGridDBColumn; DBMemo1: TDBMemo; DBMemo2: TDBMemo; DBMemo3: TDBMemo; chkContent: TcxCheckBox; chkChairmanOpinion: TcxCheckBox; chkWorkerOpinion: TcxCheckBox; chkDoctorOpinion: TcxCheckBox; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure TimerShowTimer(Sender: TObject); procedure btnOKClick(Sender: TObject); private { Private declarations } public { Public declarations } HospitalID: string; ProgramID: string; procedure CloseAll; end; var frmTherapyHistory: TfrmTherapyHistory; implementation {$R *.dfm} procedure TfrmTherapyHistory.btnOKClick(Sender: TObject); begin if adoSchedule.IsEmpty then begin oGlobal.Msg('복사할 내용이 없습니다!'); Exit; end; if oGlobal.YesNo('복사하시겠습니까?') = mrYes then ModalResult := mrOK; end; procedure TfrmTherapyHistory.CloseAll; begin adoSchedule.Close; end; procedure TfrmTherapyHistory.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmTherapyHistory.FormShow(Sender: TObject); begin TimerShow.Enabled := True; end; procedure TfrmTherapyHistory.TimerShowTimer(Sender: TObject); begin TimerShow.Enabled := False; adoSchedule.SQL.Text := 'SELECT *' + ' FROM Schedule' + ' WHERE ProgramID=' + ProgramID + ' AND HospitalID=' + HospitalID + ' ORDER BY SDate DESC'; try adoSchedule.Open; except oGlobal.Msg('내역 가져오기에 실패했습니다!'); Close; end; end; end.
unit AsyncIO.Coroutine.Detail; interface uses AsyncIO, AsyncIO.OpResults; type CoroutineFiber = interface ['{EDF6A454-9887-4605-A84C-CFB6F07E7F4D}'] procedure SwitchTo; end; IYieldContext = interface procedure Wait; procedure SetServiceHandlerCoroutine; end; implementation end.
unit uGLParticleEngine; {$mode objfpc}{$H+} interface uses Classes, SysUtils, gl; type TParticle = class x, y, z: GLfloat; vx, vy, vz: GLfloat; life: single; end; { TParticleEngine } TParticleEngine = class xspawn: GLfloat; Particle: array [1..2001] of TParticle; procedure MoveParticles(const atimer : single); procedure DrawParticles; procedure Start; private FListNumber: GLuint; Fdirection : boolean; FTimer: single; public constructor Create; destructor Destroy; override; property ParticleList : GLuint read FListNumber write FListNumber; property Timer : single read FTimer write FTimer; private procedure RespawnParticle(i: integer); end; implementation constructor TParticleEngine.Create; var i: integer; begin for i:=1 to 2001 do Particle[i]:=TParticle.Create; xspawn:=0; end; destructor TParticleEngine.Destroy; var i: integer; begin for i:=1 to 2001 do FreeAndNil(Particle[i]); inherited Destroy; end; procedure TParticleEngine.DrawParticles; var i: integer; begin for i:=1 to 2001 do begin glPushMatrix; glTranslatef(Particle[i].x, Particle[i].y, Particle[i].z); glCallList(ParticleList); glPopMatrix; end; end; procedure TParticleEngine.RespawnParticle(i: integer); begin if (xspawn>2) and (Fdirection=true) then Fdirection:=false; if (xspawn<-2) and (Fdirection=false) then Fdirection:=true; if Fdirection then xspawn:=xspawn+0.0002*(timer/10) else xspawn:=xspawn-0.0002*(timer/10); Particle[i].x:=xspawn; Particle[i].y:=-0.5; Particle[i].z:=0; Particle[i].vx:=-0.005+GLFloat(random(2000))/200000; Particle[i].vy:=0.035+GLFloat(random(750))/100000; Particle[i].vz:=-0.005+GLFloat(random(2000))/200000; Particle[i].life:=GLFloat(random(1250))/1000+1; end; procedure TParticleEngine.MoveParticles(const atimer: single); var i: integer; begin FTimer:=atimer; for i:=1 to 2001 do begin if Particle[i].life>0 then begin Particle[i].life:=Particle[i].life-0.01*(timer/10); Particle[i].x:=Particle[i].x+Particle[i].vx*(timer/10); Particle[i].vy:=Particle[i].vy-0.00035*(timer/10); // gravity Particle[i].y:=Particle[i].y+Particle[i].vy*(timer/10); Particle[i].z:=Particle[i].z+Particle[i].vz*(timer/10); end else begin RespawnParticle(i); end; end; end; procedure TParticleEngine.Start; var i: integer; begin for i:=1 to 2001 do begin RespawnParticle(i); end; end; end.
unit LanguageInstance; // 为了方便多语言的支持, 程序界面中使用文字的地方一律使 // 用 MLIGetText(const wchar_t* lpTextID)函数获取 interface uses Windows; type HLANGUAGE = pointer; //HLANGUAGE _stdcall MLIInit(LPCTSTR lpPrefix); // lpPrefix - 语言文件名前缀 扩展名为dat 返回可用语言数目 function MLIInit(lpPrefix : PWideChar) : HLANGUAGE; stdcall; //void _stdcall MLIClose(HLANGUAGE hLang); procedure MLIClose(hLang : HLANGUAGE); stdcall; //int _stdcall MLIGetLanguageCount(HLANGUAGE hLang); function MLIGetLanguageCount(hLang : HLANGUAGE) : Integer; stdcall; //const wchar_t* _stdcall MLIGetLanguageName(HLANGUAGE hLang, int nLanguageIndex); function MLIGetLanguageName(hLang : HLANGUAGE; nLanguageIndex : Integer) : PWideChar; stdcall; //BOOL _stdcall MLILoadLanguageRes(HLANGUAGE hLang, int nLanguageIndex); function MLILoadLanguageRes(hLang : HLANGUAGE; nLanguageIndex : Integer) : BOOL; stdcall; //BOOL __stdcall MLILoadLanguageResByName(HLANGUAGE hLang, LPCTSTR lpName); function MLILoadLanguageResByName(hLang : HLANGUAGE; lpName : PWideChar) : BOOL; stdcall; //const wchar_t* __stdcall MLIGetText(HLANGUAGE hLang, LPCTSTR lpTextID); function MLIGetText(hLang : HLANGUAGE; lpTextID: PWideChar) : PWideChar; stdcall; //const wchar_t* __stdcall MLIGetImage(HLANGUAGE hLang, LPCTSTR lpImageID); function MLIGetImage(hLang : HLANGUAGE; lpImageID: PWideChar) : PWideChar; stdcall; //const wchar_t* __stdcall MLIGetTextEx(HLANGUAGE hLang, LPCTSTR lpDir, LPCTSTR lpTextID); // 指定Text目录下的相对路径 如果lpTextID或lpDir不存在, 返回0 function MLIGetTextEx(hLang : HLANGUAGE; lpDir: PWideChar; lpTextID: PWideChar) : PWideChar; stdcall; //const wchar_t* __stdcall MLGetAttribute(LPCTSTR lpTextID, LPCTSTR lpAttribName); function MLIGetAttribute(hLang : HLANGUAGE; lpTextID: PWideChar; lpAttribName: PWideChar) : PWideChar; stdcall; //const wchar_t* __stdcall MLGetAttributeEx(LPCTSTR lpDir, LPCTSTR lpTextID, LPCTSTR lpAttribName); // 指定Text目录下的相对路径 如果lpTextID或lpDir不存在, 返回0 function MLIGetAttributeEx(hLang : HLANGUAGE; lpDir: PWideChar; lpTextID: PWideChar; lpAttribName: PWideChar) : PWideChar; stdcall; implementation const DLLNAME = 'WS_Language.dll'; function MLIInit ; external DLLNAME Name 'MLIInit'; procedure MLIClose ; external DLLNAME Name 'MLIClose'; function MLIGetLanguageCount ; external DLLNAME Name 'MLIGetLanguageCount'; function MLIGetLanguageName ; external DLLNAME Name 'MLIGetLanguageName'; function MLILoadLanguageRes ; external DLLNAME Name 'MLILoadLanguageRes'; function MLILoadLanguageResByName ; external DLLNAME Name 'MLILoadLanguageResByName'; function MLIGetText ; external DLLNAME Name 'MLIGetText'; function MLIGetImage ; external DLLNAME Name 'MLIGetImage'; function MLIGetTextEx ; external DLLNAME Name 'MLIGetTextEx'; function MLIGetAttribute ; external DLLNAME Name 'MLIGetAttribute'; function MLIGetAttributeEx ; external DLLNAME Name 'MLIGetAttributeEx'; end.
unit rs_world; {$mode objfpc}{$H+} interface uses Classes, SysUtils; const TEX_WIDTH = 64; TEX_HEIGHT = 64; TEXTURE_FNAME = 'level_tex.pnm'; type TRGB = array[0..2] of byte; PRGB = ^TRGB; TPalette_4bit = array[0..15] of TRGB; TTile = packed record texture_index: word; unknown_attrib: byte; unknown_lo: byte; unknown_hi: byte; unknown: array[0..24] of byte; end; PTile = ^TTile; THeightmap = record width, height: word; blk: pword; tile_count: integer; tiles: PTile; texture_count: integer; textures: array of pbyte; texture_index_map: array of integer; end; TVertex3f = record x, y, z: single; u, v: single end; PVertex3f = ^TVertex3f; { TWorld } TWorld = class private heightmap: THeightmap; world_texture: pbyte; height_texture: pbyte; vertex_array: PVertex3f; vertex_count: integer; procedure LoadTextures(const tex_fname, texidx_fname: string); procedure LoadHeightmap(fname: string); procedure GenerateCompositeTexture; procedure HeightmapToTexture; procedure GenerateVertices; procedure WriteToObj(const objFname: string); public property TileWidth: word read heightmap.width; property TileHeight: word read heightmap.height; procedure LoadFromFiles(const hmp, tex, texmap: string); procedure ExportToObj(const objfname: string); procedure ExportToRaw(const rawfname: string); constructor Create; destructor Destroy; override; end; //************************************************************************************************** implementation procedure pnm_save(const fname: string; const p: pbyte; const w, h: integer); var f: file; c: PChar; Begin c := PChar(format('P6'#10'%d %d'#10'255'#10, [w, h])); AssignFile (f, fname); Rewrite (f, 1); BlockWrite (f, c^, strlen(c)); BlockWrite (f, p^, w * h * 3); CloseFile (f); end; procedure pgm_save(fname: string; p: pbyte; w, h: integer) ; var f: file; c: PChar; Begin c := PChar(format('P5'#10'%d %d'#10'255'#10, [w, h])); AssignFile (f, fname); Rewrite (f, 1); BlockWrite (f, c^, strlen(c)); BlockWrite (f, p^, w * h); CloseFile (f); end; procedure convert_4bit_to_32bit(const indices: PByte; const w, h: Word; const image: PByte; const pal: TPalette_4bit); var i: Integer; index: integer; dst: PRGB; begin dst := PRGB(image); for i := 0 to w * h div 2 - 1 do begin index := indices[i]; dst[i * 2 ] := pal[(index shr 4) and 15]; dst[i * 2 + 1] := pal[index and 15]; end; end; procedure CopyTexToXY(image: PByte; texture: PByte; const x, y, stride: integer); var i: integer; src, dst: pbyte; begin src := texture; dst := image + y * stride + x * 3; for i := 0 to TEX_HEIGHT - 1 do begin move(src^, dst^, TEX_WIDTH * 3); dst += stride; src += TEX_WIDTH * 3; end; end; procedure CopyTileToXY(image: PByte; tile: PByte; const x, y, stride: integer); var i: integer; src, dst: pbyte; begin src := tile + 5 * 4; dst := image + y * stride + x; for i := 0 to 3 do begin move(src^, dst^, 4); dst += stride; src -= 5; end; end; { TWorld } procedure TWorld.LoadTextures(const tex_fname, texidx_fname: string); var f: file; buf: pbyte; tex_size: integer; i: Integer; palette: TPalette_4bit; image: pbyte; palette_size: Integer; texture_count: integer; begin AssignFile(f, tex_fname); reset(f, 1); palette_size := 48; //16x RGB tex_size := TEX_WIDTH * TEX_HEIGHT div 2; texture_count := filesize(f) div (tex_size + palette_size); //writeln('texture_count: ', texture_count); SetLength(heightmap.textures, texture_count); heightmap.texture_count := texture_count; buf := getmem(tex_size); for i := 0 to texture_count - 1 do begin image := getmem(TEX_WIDTH * TEX_HEIGHT * 3); Blockread(f, buf^, tex_size); Blockread(f, palette, palette_size); convert_4bit_to_32bit(buf, TEX_WIDTH, TEX_HEIGHT, image, palette); heightmap.textures[i] := image; end; freemem(buf); CloseFile(f); AssignFile(f, texidx_fname); Reset(f, 1); texture_count := filesize(f) div 4 - 1; SetLength(heightmap.texture_index_map, texture_count); Blockread(f, heightmap.texture_index_map[0], texture_count * 4); CloseFile(f); end; procedure TWorld.LoadHeightmap(fname: string); var f: file; buffer: array[0..15] of byte; tile_offset: integer; blk: pword; blk_size: integer; tile_count: word; i: integer; begin AssignFile(f, fname); reset(f, 1); //header Blockread(f, buffer, 16); //15xB + 0x3f Blockread(f, buffer, 4); Blockread(f, buffer, 4); //0x3f Blockread(f, tile_count, 2); //tile count Blockread(f, buffer, 2); //2B? Blockread(f, tile_offset, 4); //tile offset Blockread(f, buffer, 4); //offset? Blockread(f, heightmap.width, 2); Blockread(f, heightmap.height, 2); //blocks / tile indices blk_size := heightmap.width * heightmap.height * 2; blk := getmem(blk_size); Blockread(f, blk^, blk_size); heightmap.blk := blk; //tiles //writeln('tiles: ', tile_count); Seek(f, tile_offset); heightmap.tile_count := tile_count; heightmap.tiles := getmem(tile_count * 30); for i := 0 to tile_count - 1 do Blockread(f, heightmap.tiles[i], 30); CloseFile(f); end; procedure TWorld.GenerateCompositeTexture; var image: pbyte; image_size: integer; x, y, stride: integer; tile_idx, texture_idx, texmap_idx: integer; texture: pbyte; begin image_size := heightmap.width * heightmap.height * TEX_WIDTH * TEX_HEIGHT * 3; image := GetMem(image_size); stride := heightmap.width * TEX_WIDTH * 3; for y := 0 to heightmap.height - 1 do for x := 0 to heightmap.width - 1 do begin tile_idx := heightmap.blk[y * heightmap.width + x]; texmap_idx := heightmap.tiles[tile_idx].texture_index; if texmap_idx > Length(heightmap.texture_index_map) - 1 then texmap_idx := 0; texture_idx := heightmap.texture_index_map[texmap_idx]; texture := heightmap.textures[texture_idx]; CopyTexToXY(image, texture, x * TEX_WIDTH, (heightmap.height - y - 1) * TEX_HEIGHT, stride); end; world_texture := image; pnm_save(TEXTURE_FNAME, image, heightmap.width * TEX_WIDTH, heightmap.height * TEX_HEIGHT); end; procedure TWorld.HeightmapToTexture; const TILE_WIDTH = 4; SCALE = 128; var x, y: integer; tile_idx: integer; i: integer; image_size: integer; image: pbyte; begin image_size := heightmap.width * heightmap.height * TILE_WIDTH * TILE_WIDTH; image := GetMem(image_size); for y := 0 to heightmap.height - 1 do begin for x := 0 to heightmap.width - 1 do begin tile_idx := heightmap.blk[y * heightmap.width + x]; CopyTileToXY(image, @(heightmap.tiles[tile_idx].unknown), x * TILE_WIDTH, (heightmap.height - y - 1) * TILE_WIDTH, heightmap.width * TILE_WIDTH); end; end; //scale for i := 0 to image_size - 1 do image[i] := byte(image[i] + SCALE); height_texture := image; //pgm_save('map_height.pgm', image, heightmap.width * TILE_WIDTH, heightmap.height * TILE_WIDTH); end; procedure TWorld.GenerateVertices; const scale = 0.1; var va_size: integer; x, y: integer; vert: TVertex3f; width_half, height_half: integer; i: integer; begin vertex_count := heightmap.width * 4 * heightmap.height * 4; va_size := vertex_count * SizeOf(TVertex3f); vertex_array := getmem(va_size); width_half := heightmap.width * 2; height_half := heightmap.height * 2; for y := 0 to heightmap.height * 4 - 1 do for x := 0 to heightmap.width * 4 - 1 do begin vert.x := (-width_half + x) * scale; vert.z := (-height_half + y) * scale; vert.u := x / (heightmap.width * 4); vert.v := y / (heightmap.height * 4); i := y * heightmap.width * 4 + x; vert.y := (255 - height_texture[i]) * 0.01; //inverse for mos eisley / lv0 vertex_array[i] := vert; end; end; procedure SaveMaterialFile(const obj_fname, mtl_name, texture_fname: string); var f: TextFile; begin AssignFile(f, obj_fname + '.mtl'); Rewrite(f); writeln(f, '# RS heightmap'); writeln(f, 'newmtl ', mtl_name); //begin new material writeln(f, 'map_Kd ', texture_fname); //texture writeln(f, 'Ka 1.000 1.000 1.000'); //ambient color writeln(f, 'Kd 1.000 1.000 1.000'); //diffuse color writeln(f, 'Ks 1.000 1.000 1.000'); //specular color writeln(f, 'Ns 100.0'); //specular weight writeln(f, 'illum 2'); //Color on and Ambient on, Highlight on CloseFile(f); end; procedure TWorld.WriteToObj(const objFname: string); const MAT_NAME = 'default'; var f: textfile; i: integer; v: TVertex3f; x, y, stride: integer; i2, i3: integer; begin AssignFile(f, objFname); Rewrite(f); writeln(f, '# RS heightmap'); writeln(f, 'mtllib ', objFname + '.mtl'); //vertices for i := 0 to vertex_count - 1 do begin v := vertex_array[i]; writeln(f, 'v ', v.x:10:6, ' ', v.y:10:6, ' ', v.z:10:6); end; //uv-s for i := 0 to vertex_count - 1 do begin v := vertex_array[i]; writeln(f, 'vt ', v.u:10:6, ' ', v.v:10:6); end; //select material writeln(f, 'usemtl ' + MAT_NAME); //faces { 12 2 3 34 } stride := heightmap.width * 4; for y := 0 to heightmap.height * 4 - 2 do for x := 0 to heightmap.width * 4 - 2 do begin i := y * stride + x + 1; i2 := i + 1; i3 := i + stride; writeln(f, Format('f %d/%d %d/%d %d/%d', [i, i, i2, i2, i3, i3])); i := i3 + 1; writeln(f, Format('f %d/%d %d/%d %d/%d', [i2, i2, i, i, i3, i3])); end; CloseFile(f); SaveMaterialFile(objFname, MAT_NAME, TEXTURE_FNAME); end; procedure TWorld.LoadFromFiles(const hmp, tex, texmap: string); begin LoadHeightmap(hmp); LoadTextures(tex, texmap); end; procedure TWorld.ExportToObj(const objfname: string); begin GenerateCompositeTexture; HeightmapToTexture; GenerateVertices; WriteToObj(objfname); end; procedure TWorld.ExportToRaw(const rawfname: string); var f: file; image_size, i: integer; y: Byte; begin AssignFile(f, rawfname); Rewrite(f,1); image_size := heightmap.width * heightmap.height; for i := 0 to image_size - 1 do begin y := 255 - height_texture[i]; //negative scale - Unity uses it like this, for example BlockWrite(f, y, 1); end; CloseFile(f); end; constructor TWorld.Create; begin height_texture := nil; vertex_array := nil; end; destructor TWorld.Destroy; begin if height_texture <> nil then Freemem(height_texture); if vertex_array <> nil then Freemem(vertex_array); inherited Destroy; end; end.
unit qplugins_proxy; interface {$I 'qdac.inc'} uses classes, sysutils, qstring, qplugins, qplugins_base,qplugins_params, windows, messages, syncobjs{$IF RTLVersion>21}, Generics.collections{$IFEND}, qsimplepool; {$HPPEMIT '#pragma link "qplugins_proxy"'} type TQPendingCallback = procedure(ASerivce: IQService; AParams, AResult: IQParams; ATag: Pointer) of object; TQPendingRPC = class private FParams: IQParams; FResult: IQParams; FTag: Pointer; FService: IQService; FEvent: TEvent; FErrorCode: Cardinal; FErrorMsg: QStringW; FCallback: TQPendingCallback; public constructor Create(AService: IQService; AParams, AResult: IQParams; ATag: Pointer); overload; destructor Destroy; override; function WaitFor(ATimeout: Cardinal): TWaitResult; procedure SetEvent; property Params: IQParams read FParams; property Result: IQParams read FResult; property Tag: Pointer read FTag; property Callback: TQPendingCallback read FCallback write FCallback; property ErrorCode: Cardinal read FErrorCode write FErrorCode; property ErrorMsg: QStringW read FErrorMsg write FErrorMsg; end; // 远程过程进程 TQRPCProcess = class protected FPath, FWorkDir: QStringW; // 服务提供进程路径,使用URI方式来定位,本地为:file:///xxxx? FLocker: TCriticalSection; function InternalSend(ACall: TQPendingRPC): Boolean; virtual; abstract; property Path: QStringW read FPath; public constructor Create(APath: String); overload; virtual; procedure Lock; procedure Unlock; end; {$IF RTLVersion>21} TQProcessList = TList<TQRPCProcess>; {$ELSE} TQProcessList = TList; {$IFEND} TQProxyService = class; TQRPCProcesses = class(TCriticalSection) private function GetCount: Integer; function GetItems(AIndex: Integer): TQRPCProcess; protected FItems: TQProcessList; FEvents: TQSimplePool; function InternalPost(ACall: TQPendingRPC): Boolean; virtual; procedure DoNewEvent(ASender: TQSimplePool; var AData: Pointer); procedure DoFreeEvent(ASender: TQSimplePool; AData: Pointer); public constructor Create; overload; destructor Destroy; override; procedure Clear; // 投寄一个不关心返回结果的请求 function Post(AService: IQService; AParams, AResult: IQParams; ATag: Pointer): TQPendingRPC; overload; function Post(AService: IQService; AParams, AResult: IQParams; ATag: Pointer; ACallback: TQPendingCallback): Boolean; overload; function Send(AService: IQService; AParams, AResult: IQParams): Boolean; property Count: Integer read GetCount; property Items[AIndex: Integer]: TQRPCProcess read GetItems; default; end; TQProxyService = class(TQService) protected FProcess: TQRPCProcess; public function Execute(AParams: IQParams; AResult: IQParams): Boolean; override; stdcall; property Process: TQRPCProcess read FProcess; // 服务所隶属的进程 end; var RemoteProcesses: TQRPCProcesses; implementation { TQRPCProcesses } procedure TQRPCProcesses.Clear; var I: Integer; begin Enter; try for I := 0 to FItems.Count - 1 do FreeObject(FItems[I]); FItems.Clear; finally Leave; end; end; constructor TQRPCProcesses.Create; begin inherited Create; FItems := TQProcessList.Create; FEvents := TQSimplePool.Create(100, SizeOf(Pointer)); FEvents.OnNewItem := DoNewEvent; FEvents.OnFree := DoFreeEvent; end; destructor TQRPCProcesses.Destroy; begin Clear; FreeAndNil(FItems); FreeAndNil(FEvents); inherited; end; procedure TQRPCProcesses.DoFreeEvent(ASender: TQSimplePool; AData: Pointer); begin FreeAndNil(AData); end; procedure TQRPCProcesses.DoNewEvent(ASender: TQSimplePool; var AData: Pointer); begin AData := TEvent.Create(nil, false, false, ''); end; function TQRPCProcesses.GetCount: Integer; begin Result := FItems.Count; end; function TQRPCProcesses.GetItems(AIndex: Integer): TQRPCProcess; begin Result := FItems[AIndex]; end; function TQRPCProcesses.InternalPost(ACall: TQPendingRPC): Boolean; begin Result := TQProxyService(ACall.FService.GetOriginObject) .FProcess.InternalSend(ACall); end; function TQRPCProcesses.Post(AService: IQService; AParams, AResult: IQParams; ATag: Pointer): TQPendingRPC; begin Result := TQPendingRPC.Create(AService, AParams, AResult, ATag); try if not InternalPost(Result) then FreeAndNil(Result); except FreeAndNil(Result); end; end; function TQRPCProcesses.Post(AService: IQService; AParams, AResult: IQParams; ATag: Pointer; ACallback: TQPendingCallback): Boolean; var ACall: TQPendingRPC; begin ACall := TQPendingRPC.Create(AService, AParams, AResult, ATag); try ACall.Callback := ACallback; Result := InternalPost(ACall); if not Result then FreeAndNil(ACall); except FreeAndNil(ACall); end; end; function TQRPCProcesses.Send(AService: IQService; AParams, AResult: IQParams): Boolean; var ACall: TQPendingRPC; begin ACall := TQPendingRPC.Create(AService, AParams, AResult, nil); try Result := InternalPost(ACall); if Result then begin if ACall.FEvent.WaitFor(INFINITE) = wrSignaled then Result := True; end; finally FreeAndNil(ACall); end; end; { TQProxyService } function TQProxyService.Execute(AParams, AResult: IQParams): Boolean; begin Result := RemoteProcesses.Send(Self, AParams, AResult); end; { TQPendingRPC } constructor TQPendingRPC.Create(AService: IQService; AParams, AResult: IQParams; ATag: Pointer); begin inherited Create; FService := AService; FParams := AParams; FResult := AResult; FTag := ATag; FEvent := RemoteProcesses.FEvents.Pop; end; destructor TQPendingRPC.Destroy; begin RemoteProcesses.FEvents.Push(FEvent); inherited; end; procedure TQPendingRPC.SetEvent; begin FEvent.SetEvent; end; function TQPendingRPC.WaitFor(ATimeout: Cardinal): TWaitResult; begin Result := FEvent.WaitFor(ATimeout); end; { TQRPCProcess } constructor TQRPCProcess.Create(APath: String); begin inherited Create; FPath := APath; FLocker := TCriticalSection.Create; end; procedure TQRPCProcess.Lock; begin FLocker.Enter; end; procedure TQRPCProcess.Unlock; begin FLocker.Leave; end; initialization RemoteProcesses := TQRPCProcesses.Create(); end.
{ //***************************************************************************************************************// Unit Name: uPatcher Author: Glen Vlotman Date: 31 December 2011 Version: 0.0.0.1 Changed: N/A TO DO: Implement symbol file loading functionality. Requires: PatchAPI.pas (the raw API definitions for the PatchAPI interface) for creating patches - mspatchc.dll (should ideally be located in application directory) for applying patches - mspatcha.dll (should already be on the destination pc in <windows directory>\system32) Description: This unit provides the functionality to create and apply binary patches (also known as deltas) using the Delta Compression Application Programming Interfaces provided by Microsoft (for more information on how binary patching works, go to this URL: http://msdn.microsoft.com/en-us/library/bb267312(VS.85).aspx). It hides the raw PatchAPI interface from the user and in effect makes it easier to create and apply binary patches. Technical Stuff: Types: TPatchCreateOption - Valid create patch flags. TPatchApplyOptions - Set of TPatchCreateOption. TPatchCreateOptions_Compression - Valid compression option flags for creating patches. This is a subset of TPatchCreateOption. TPatchCreateOptions_Additional - Additional create patch option flags for creating patches. This is a subset of TPatchCreateOption. TPatchApplyOption - Valid apply patch flags. TPatchApplyOptions - Set of TPatchApplyOption. TPatchCreateErrorCode - Error codes when creating patch files. TPatchApplyErrorCode - Error codes when applying patch files. TPatcherFileMode - Patcher file mode (use AnsiString, Widestring or THandle). Constants: Descriptions_TPatchCreateOption - Descriptions for the TPatchCreateOption flags. Descriptions_TPatchApplyOption - Descriptions for the TPatchApplyOption flags. Descriptions_TPatchCreateErrorCode - Descriptions for TPatchCreateErrorCode. Descriptions_TPatchApplyOption - Descriptions for TPatchApplyErrorCode. Object Events: TOnPatchProgress - Fires when part of an apply or create patch operation has completed Parameters ASender - The (TPatcher) object which fired this event. ACurrentPosition - CONSTANT - The current position of the patching process. AMaximumPosition - CONSTANT - The maximum position of the patching process. ACanContinue - VARIABLE - Should the process continue. TOnPatchesComplete - Fires when TPatchItem object(s) have been processed, irrespective of whether the patch operation(s) were successful or not Parameters ASender - The (TPatcher) object which fired this event. AStatusCode - CONSTANT - Status code indicating whether the patch operation(s) were a success ( 0 ) or not ( > 0 ) AStatusMessage - CONSTANT - Status message (blank if AStatusCode = 0). TOnPatchFileBegin - Fires when a TPatchItem is about to have a patch operation applied to it. Parameters ASender - The (TPatcher) object which fired this event. APatchItem - The TPatchItem object which is going to be used. APatchItemNumber - CONSTANT - The current position in the list of TPatchItem objects of the APatchItem parameter. APatchItemCount - CONSTANT - The total number of TPatchItem objects that will be processed. AContinueIfError - VARIABLE - Indicates whether the patching operation(s) should continue if there is an error. TOnPatchFileEnd - Fires after a TPatchItem has had a patch operation applied to it. Parameters ASender - The (TPatcher) object which fired this event. APatchItem - The TPatchItem object which is going to be used. APatchItemNumber - CONSTANT - The current position in the list of TPatchItem objects of the APatchItem parameter. APatchItemCount - CONSTANT - The total number of TPatchItem objects that will be processed. Exceptions: EPatcherException Helper Classes: PatcherHelper - Miscellaneous helper functions pertaining to the TPatcher object and PatchAPI interface Objects: TPatchItem - Holds information about a file which is going to be patched. Constructor(s) Create(<PatchFileExtension>, <PatchFilePath>) Create(<PatchFileExtension>, <PatchFilePath>, <OldFileVersion>, <NewFileVersion>, <PatchFileName>) Properties OldFileVersion (Read/Write) - The old file version NewFileVersion (Read/Write) - The new file version PatchFileName (Read/Write) - The name of the patch file TPatcher - Allows for creating and applying binary patches. Methods AddFileToPatch - Adds a file to be operated on. Parameters AOldFileVersion - string ANewFileVersion - string APatchFileName - string AddAdditionalCreatePatchFlag - Add a create patch flag. Parameters OVERLOAD ONE ACreatePatchFlag - TPatchCreateOption ARaiseOnDuplicateFlag - Boolean Parameters OVERLOAD TWO ACreatePatchFlag - TPatchCreateOption AddApplyPatchOptionFlag - Add an apply patch flag. Parameters OVERLOAD ONE AApplyPatchOptionFlag - TPatchApplyOption ARaiseOnDuplicateFlag - Boolean Parameters OVERLOAD TWO AApplyPatchOptionFlag - TPatchApplyOption SetCompressionMode - Change the compression mode of the patch action. Parameters ACompressionMode - TPatchCreateOptions_Compression CreatePatches - Create the patch files for the list of TPatchItem objects. Parameters None ApplyPatches - Applies the patch files for the list of TPatchItem objects. Parameters None TestApplyPatches [NOT YET IMPLEMENTED!!!!!]- Test the patch files against the list of TPatchItem objects. Parameters None ResetPatchData - Reset the TPatcher object's properties. Parameters AClearEventsAsWell - Boolean RemovePatchItemAtIndex - Removes a TPatchItem from the list of items at the specified index. Parameters AIndex - Integer Properties AlwaysRaiseExceptions - Boolean FileMode (Read/Write) - TPatcherFileMode PatchFileExtension (Read/Write) - string PatchFilePath (Read/Write) - string Items[Index] (Readonly ) - TPatchItem CreatePatchCompressionMode (Readonly) - TPatchCreateOptions_Compression CreatePatchAdditionalFlags (Readonly) - TPatchCreateOptions_Additional ApplyPatchOptions (Readonly) - TPatchApplyOptions PatchItemCount (Readonly) - Integer OnPatchProgress (Read/Write) - TOnPatchProgress OnPatchesComplete (Read/Write) - TOnPatchesComplete OnPatchFileBegin (Read/Write) - TOnPatchFileBegin OnPatchFileEnd (Read/Write) - TOnPatchFileBegin //***************************************************************************************************************// } unit uPatcher; interface uses Windows, SysUtils, Classes, TypInfo, Contnrs, PatchAPI; type TPatchCreateOption = ( pcoUseBest, // = PATCH_OPTION_USE_BEST pcoUseLZX_A, // = PATCH_OPTION_USE_LZX_A pcoUseLZX_B, // = PATCH_OPTION_USE_LZX_B pcoUseBestLZX, // = PATCH_OPTION_USE_LZX_BEST pcoUseLZX_Large, // = PATCH_OPTION_USE_LZX_LARGE pcoNoBindFix, // = PATCH_OPTION_NO_BINDFIX pcoNoLockFix, // = PATCH_OPTION_NO_LOCKFIX pcoNoRebase, // = PATCH_OPTION_NO_REBASE pcoFailIfSameFile, // = PATCH_OPTION_FAIL_IF_SAME_FILE pcoFailIfBigger, // = PATCH_OPTION_FAIL_IF_BIGGER pcoNoChecksum, // = PATCH_OPTION_NO_CHECKSUM, pcoNoResourceTimeStampFix, // = PATCH_OPTION_NO_RESTIMEFIX pcoNoTimeStamp, // = PATCH_OPTION_NO_TIMESTAMP pcoUseSignatureMD5, // = PATCH_OPTION_SIGNATURE_MD5 pcoReserved1, // = PATCH_OPTION_RESERVED1 pcoValidFlags // = PATCH_OPTION_VALID_FLAGS ); TPatchCreateOptions_Compression = pcoUseBest..pcoUseLZX_Large; TPatchCreateOptions_Additional = set of pcoNoBindFix..pcoValidFlags; const Descriptions_TPatchCreateOption : array[Low(TPatchCreateOption)..High(TPatchCreateOption)] of string = ( 'Auto-choose best of LZX_A or LZX_B (slower). Equivalent to pcoUseBestLZX.', 'Use standard LZX compression.', 'Use alternate LZX compression. Better on some x86 binaries.', 'Auto-choose best of LZX_A or LZX_B (slower). Equivalent to pcoUseBest.', 'Better support for files larger than 8 MB.', 'Don'#39't pre-process PE bound imports.', 'Don'#39't repair disabled lock prefixes in source PE file.', 'Don'#39't pre-process PE rebase information.', 'Don'#39't create a delta if source file and target are the same or differ only by normalization.', 'Fail if delta is larger than simply compressing the target without comparison to the source file. Setting this flag makes the Create process slower.', 'Set PE checksum to zero.', 'Don'#39't pre-process PE resource timestamps.', 'Don'#39't store a timestamp in delta.', 'Use MD5 instead of CRC32 in signature. (reserved for future use)', 'Reserved.', 'The logical OR of all valid delta creation flags.' ); type TPatchApplyOption = ( paoFailIfExact, // = APPLY_OPTION_FAIL_IF_EXACT paoFailIfClose, // = APPLY_OPTION_FAIL_IF_CLOSE paoTestOnly, // = APPLY_OPTION_TEST_ONLY paoValidFlags // = APPLY_OPTION_VALID_FLAGS ); TPatchApplyOptions = set of TPatchApplyOption; const Descriptions_TPatchApplyOption : array[Low(TPatchApplyOption)..High(TPatchApplyOption)] of string = ( 'If the source file and the target are the same, return a failure and don'#39't create the target.', 'If the source file and the target differ by only rebase and bind information (that is, they have the same normalized signature), return a failure and don'#39't create the target.', 'Don'#39't create the target.', 'The logical OR of all valid patch apply flags.' ); type TPatchCreateErrorCode = ( pcecEncodeFailure, // = ERROR_PATCH_ENCODE_FAILURE pcecInvalidOptions, // = ERROR_PATCH_INVALID_OPTIONS pcecSameFile, // = ERROR_PATCH_SAME_FILE pcecRetainRangesDiffer, // = ERROR_PATCH_RETAIN_RANGES_DIFFER pcecBiggerThanCompressed, // = ERROR_PATCH_BIGGER_THAN_COMPRESSED pcecImageHlpFailure, // = ERROR_PATCH_IMAGEHLP_FAILURE pcecUnknown ); const Descriptions_TPatchCreateErrorCode : array[Low(TPatchCreateErrorCode)..High(TPatchCreateErrorCode)] of string = ( 'Generic encoding failure. Could not create delta.', 'Invalid options were specified.', 'The source file and target are the same.', 'Retain ranges specified in multiple source files are different.', 'The delta is larger than simply compressing the target without comparison to the source file. This error is returned only if the pcoFailIfBigger flag is set.', 'Could not obtain symbols.', '' ); type TPatchApplyErrorCode = ( paecDecodeFailure, // = ERROR_PATCH_DECODE_FAILURE paecCorrupt, // = ERROR_PATCH_CORRUPT paecNewerFormat, // = ERROR_PATCH_NEWER_FORMAT paecWrongFile, // = ERROR_PATCH_WRONG_FILE paecNotNecessary, // = ERROR_PATCH_NOT_NECESSARY paecNotAvailable, // = ERROR_PATCH_NOT_AVAILABLE paecUnknown // Unknown exception ); const Descriptions_TPatchApplyErrorCode : array[Low(TPatchApplyErrorCode)..High(TPatchApplyErrorCode)] of string = ( 'Decode failure of the delta.', 'The delta is corrupt.', 'The delta was created using a compression algorithm that is not compatible with the source file.', 'The delta is not applicable to the source file.', 'The source file and target are the same, or they differ only by normalization. This error is returned only if the pcoFailIfSameFile flag is set.', 'Delta consists of only an extracted header and an ApplyPatchToFile function is called instead of a TestApplyPatchToFile function.', '' ); // Patcher file mode... type TPatcherFileMode = ( psmAnsi, psmUnicode, psmHandle); // Patcher Exceptions... type EPatcherException = class(Exception) end; type TPatchItem = class; TOnPatchProgress = procedure( ASender : TObject; const ACurrentPosition : LongWord; const AMaximumPosition : LongWord; var ACanContinue : LongBool) of object; TOnPatchesComplete = procedure( ASender : TObject; const AStatusCode : LongWord; const AStatusMessage : string) of object; TOnPatchFileBegin = procedure( ASender : TObject; APatchItem : TPatchItem; const APatchItemNumber : Integer; const APatchItemCount : Integer; var AContinueIfError : Boolean) of object; TOnPatchFileEnd = procedure( ASender : TObject; APatchItem : TPatchItem; const APatchItemNumber : Integer; const APatchItemCount : Integer) of object; TPatchItem = class(TObject) private FPatchFileExtension : string; FPatchFilePath : string; FOldFileName : string; FNewFileName : string; FPatchFileName : string; function GetPatchFileName : string; protected constructor Create; overload; public constructor Create( const APatchFileExtension : string; const APatchFilePath : string); overload; constructor Create( const APatchFileExtension : string; const APatchFilePath : string; const AOldFileName : string; const ANewFileName : string; const APatchFilename : string); overload; property OldFileName : string read FOldFileName write FOldFileName; property NewFileName : string read FNewFileName write FNewFileName; property PatchFileName : string read FPatchFileName write FNewFileName; end; TPatcher = class(TObject) private FOnPatchProgress : TOnPatchProgress; FOnPatchesComplete : TOnPatchesComplete; FOnPatchFileBegin : TOnPatchFileBegin; FOnPatchFileEnd : TOnPatchFileEnd; private FAlwaysRaiseExceptions : Boolean; FPatchFileExtension : string; FPatchFilePath : string; FPatchList : TObjectList; FFileMode : TPatcherFileMode; FCreatePatchCompressionMode : TPatchCreateOptions_Compression; FCreatePatchAdditionalFlags : TPatchCreateOptions_Additional; FApplyPatchOptions : TPatchApplyOptions; function GetPatchItemCount : Integer; function GetItem(AIndex : Integer) : TPatchItem; procedure CreatePatchesAnsi; procedure CreatePatchesWide; procedure ApplyPatchesAnsi; procedure ApplyPatchesWide; public constructor Create; destructor Destroy; override; procedure AddFileToPatch( const AOldFileVersion : string; const ANewFileVersion : string; const APatchFilename : string); procedure AddAdditionalCreatePatchFlag( const ACreatePatchFlag : TPatchCreateOption; const ARaiseOnDuplicateFlag : Boolean); overload; procedure AddAdditionalCreatePatchFlag( const ACreatePatchFlag : TPatchCreateOption); overload; procedure AddApplyPatchOptionFlag( const AApplyPatchOptionFlag : TPatchApplyOption); overload; procedure AddApplyPatchOptionFlag( const AApplyPatchOptionFlag : TPatchApplyOption; const ARaiseOnDuplicateFlag : Boolean); overload; procedure SetCompressionMode(const ACompressionMode : TPatchCreateOptions_Compression); procedure CreatePatches; procedure ApplyPatches; procedure TestApplyPatches; procedure ResetPatchData(const AClearEventsAsWell : Boolean); procedure RemovePatchItemAtIndex(const AIndex : Integer); property AlwaysRaiseExceptions : Boolean read FAlwaysRaiseExceptions write FAlwaysRaiseExceptions; property FileMode : TPatcherFileMode read FFileMode write FFileMode; property PatchFileExtension : string read FPatchFileExtension write FPatchFileExtension; property PatchFilePath : string read FPatchFilePath write FPatchFilePath; property Items[Index : Integer] : TPatchItem read GetItem; property CreatePatchCompressionMode : TPatchCreateOptions_Compression read FCreatePatchCompressionMode; property CreatePatchAdditionalFlags : TPatchCreateOptions_Additional read FCreatePatchAdditionalFlags; property ApplyPatchOptions : TPatchApplyOptions read FApplyPatchOptions; property PatchItemCount : Integer read GetPatchItemCount; property OnPatchProgress : TOnPatchProgress read FOnPatchProgress write FOnPatchProgress; property OnPatchesComplete : TOnPatchesComplete read FOnPatchesComplete write FOnPatchesComplete; property OnPatchFileBegin : TOnPatchFileBegin read FOnPatchFileBegin write FOnPatchFileBegin; property OnPatchFileEnd : TOnPatchFileEnd read FOnPatchFileEnd write FOnPatchFileEnd; end; PatcherHelper = class public class function EnumTypeToString( const ATypeInfoPointer : PTypeInfo; const AIntegerOfEnum : Integer) : string; class function PatchCreateFlagToString( const APatchCreateFlag : TPatchCreateOption) : string; class function StringToPatchCreateFlag( const APatchCreateFlagString : string) : TPatchCreateOption; class function PatchFileModeToString( const APatcherFileMode : TPatcherFileMode) : string; class function StringToPatchFileMode( const APatcherFileModeString : string) : TPatcherFileMode; class function PatchApplyOptionFlagToString( const APatchApplyOptionFlag : TPatchApplyOption) : string; class function StringToPatchApplyOptionFlag( const APatchApplyOptionFlagString : string) : TPatchApplyOption; class function PatchCreateFlagToAPICode( const APatchCreateFlag : TPatchCreateOption) : ULONG; class function PatchCreateOptionsToULONG( const APatchCreateCompression : TPatchCreateOptions_Compression = pcoUseBest; const APatchCreateAdditional : TPatchCreateOptions_Additional = []) : ULONG; class function PatchApplyFlagToAPICode( const APatchApplyFlag : TPatchApplyOption) : ULONG; class function APICodeToPatchApplyErrorCode( const AAPICode : ULONG) : TPatchApplyErrorCode; class function APICodeToPatchCreateErrorCode( const AAPICode : ULONG) : TPatchCreateErrorCode; class function PatchApplyOptionsToULONG( const APatchApplyOptions : TPatchApplyOptions = []) : ULONG; end; implementation uses Forms, Math; function MyPatchCreateApplyCallback( CallbackContext : Pointer; CurrentPosition : LongWord; MaximumPosition : LongWord) : LongBool; stdcall; var LPatcher : TPatcher; LCanContinue : LongBool; begin LCanContinue := True; LPatcher := TPatcher(CallbackContext); if Assigned(LPatcher.OnPatchProgress) then begin LPatcher.OnPatchProgress( LPatcher, CurrentPosition, MaximumPosition, LCanContinue); end; Result := LCanContinue; end; { TPatcher } procedure TPatcher.AddAdditionalCreatePatchFlag( const ACreatePatchFlag : TPatchCreateOption; const ARaiseOnDuplicateFlag : Boolean); begin if (ACreatePatchFlag in CreatePatchAdditionalFlags) then begin if ARaiseOnDuplicateFlag then raise EPatcherException.Create( Format('Flag [%s] already exists in the CreatePatchAdditionalFlags property.', [PatcherHelper.PatchCreateFlagToString(ACreatePatchFlag)])); end else begin FCreatePatchAdditionalFlags := FCreatePatchAdditionalFlags + [ACreatePatchFlag]; end; end; procedure TPatcher.AddAdditionalCreatePatchFlag( const ACreatePatchFlag : TPatchCreateOption); begin AddAdditionalCreatePatchFlag(ACreatePatchFlag, AlwaysRaiseExceptions); end; procedure TPatcher.AddApplyPatchOptionFlag( const AApplyPatchOptionFlag : TPatchApplyOption); begin AddApplyPatchOptionFlag(AApplyPatchOptionFlag, AlwaysRaiseExceptions); end; procedure TPatcher.AddApplyPatchOptionFlag( const AApplyPatchOptionFlag : TPatchApplyOption; const ARaiseOnDuplicateFlag : Boolean); begin if (AApplyPatchOptionFlag in ApplyPatchOptions) then begin if ARaiseOnDuplicateFlag then raise EPatcherException.Create( Format('Flag [%s] already exists in the ApplyPatchOptions property.', [PatcherHelper.PatchApplyOptionFlagToString(AApplyPatchOptionFlag)])); end else begin FApplyPatchOptions := FApplyPatchOptions + [AApplyPatchOptionFlag]; end; end; procedure TPatcher.AddFileToPatch( const AOldFileVersion : string; const ANewFileVersion : string; const APatchFilename : string); begin FPatchList.Add( TPatchItem.Create( PatchFileExtension, PatchFilePath, AOldFileVersion, ANewFileVersion, APatchFilename)); end; procedure TPatcher.ApplyPatches; begin case FileMode of psmAnsi : ApplyPatchesAnsi; psmUnicode : ApplyPatchesWide; else begin raise EPatcherException.Create('Apply Patch To File mode not implemented yet [' + PatcherHelper.EnumTypeToString( TypeInfo(TPatcherFileMode), Integer(FileMode)) + ']'); end; end; end; procedure TPatcher.ApplyPatchesAnsi; var LOldFile : AnsiString; LNewFile : AnsiString; LPatchFile : AnsiString; LApplyPatchOptions : ULONG; LOld : TPatchOldFileInfoA; LIdx : Integer; LPatchItem : TPatchItem; LApplyPatchResult : LongBool; LContinueIfError : Boolean; LError : Cardinal; LErrorMessage : string; begin LError := 0; LErrorMessage := ''; try try LContinueIfError := not AlwaysRaiseExceptions; LApplyPatchOptions := PatcherHelper.PatchApplyOptionsToULONG(ApplyPatchOptions); if PatchItemCount = 0 then raise EPatcherException.Create('No patch items to patch.'); for LIdx := 0 to PatchItemCount - 1 do begin LOld.SizeOfThisStruct := 0; LOld.OldFileName := nil; LOld.IgnoreRangeCount := 0; LOld.IgnoreRangeArray := nil; LOld.RetainRangeCount := 0; LOld.RetainRangeArray := nil; LPatchItem := TPatchItem(FPatchList.Items[LIdx]); if Assigned(OnPatchFileBegin) then begin OnPatchFileBegin( Self, LPatchItem, LIdx + 1, PatchItemCount, LContinueIfError); end; LPatchFile := LPatchItem.PatchFileName; LOldFile := LPatchItem.OldFileName; LNewFile := LPatchItem.NewFileName; LApplyPatchResult := ApplyPatchToFileExA( Pointer(LPatchFile), Pointer(LOldFile), Pointer(LNewFile), LApplyPatchOptions, @MyPatchCreateApplyCallback, Self); if LApplyPatchResult <> True then begin LError := GetLastError; LErrorMessage := Descriptions_TPatchApplyErrorCode[PatcherHelper.APICodeToPatchApplyErrorCode(LError)]; if LErrorMessage = '' then LErrorMessage := SysErrorMessage(LError); if not (LContinueIfError) then raise EPatcherException.Create(LErrorMessage); end; if Assigned(OnPatchFileEnd) then begin OnPatchFileEnd( Self, LPatchItem, LIdx + 1, PatchItemCount); end; end; except on E : Exception do begin LError := 1; LErrorMessage := E.ClassName + ' caught with message: ' + E.Message; if AlwaysRaiseExceptions then begin raise EPatcherException.Create(LErrorMessage); end; end; end; finally if Assigned(OnPatchesComplete) then begin OnPatchesComplete( Self, LError, LErrorMessage); end; end; end; procedure TPatcher.ApplyPatchesWide; var LOldFile : WideString; LNewFile : WideString; LPatchFile : WideString; LApplyPatchOptions : ULONG; LIdx : Integer; LPatchItem : TPatchItem; LApplyPatchResult : LongBool; LContinueIfError : Boolean; LError : Cardinal; LErrorMessage : string; begin LError := 0; LErrorMessage := ''; try try LContinueIfError := not AlwaysRaiseExceptions; LApplyPatchOptions := PatcherHelper.PatchApplyOptionsToULONG(ApplyPatchOptions); if PatchItemCount = 0 then raise EPatcherException.Create('No patch items to patch.'); for LIdx := 0 to PatchItemCount - 1 do begin LPatchItem := TPatchItem(FPatchList.Items[LIdx]); if Assigned(OnPatchFileBegin) then begin OnPatchFileBegin( Self, LPatchItem, LIdx + 1, PatchItemCount, LContinueIfError); end; LPatchFile := LPatchItem.PatchFileName; LOldFile := LPatchItem.OldFileName; LNewFile := LPatchItem.NewFileName; LApplyPatchResult := ApplyPatchToFileExW( Pointer(LPatchFile), Pointer(LOldFile), Pointer(LNewFile), LApplyPatchOptions, @MyPatchCreateApplyCallback, Self); if LApplyPatchResult <> True then begin LError := GetLastError; LErrorMessage := Descriptions_TPatchApplyErrorCode[PatcherHelper.APICodeToPatchApplyErrorCode(LError)]; if LErrorMessage = '' then LErrorMessage := SysErrorMessage(LError); if not (LContinueIfError) then raise EPatcherException.Create(LErrorMessage); end; if Assigned(OnPatchFileEnd) then begin OnPatchFileEnd( Self, LPatchItem, LIdx + 1, PatchItemCount); end; end; except on E : Exception do begin LError := 1; LErrorMessage := E.ClassName + ' caught with message: ' + E.Message; if AlwaysRaiseExceptions then begin raise EPatcherException.Create(LErrorMessage); end; end; end; finally if Assigned(OnPatchesComplete) then begin OnPatchesComplete( Self, LError, LErrorMessage); end; end; end; constructor TPatcher.Create; begin inherited Create; FPatchList := TObjectList.Create; ResetPatchData(True); end; procedure TPatcher.CreatePatches; begin case FileMode of psmAnsi : CreatePatchesAnsi; psmUnicode : CreatePatchesWide; else begin raise EPatcherException.Create('Create Patch File mode not implemented yet [' + PatcherHelper.EnumTypeToString( TypeInfo(TPatcherFileMode), Integer(FileMode)) + ']'); end; end; end; procedure TPatcher.CreatePatchesAnsi; var LOldFile : AnsiString; LNewFile : AnsiString; LPatchFile : AnsiString; LError : Integer; LErrorMessage : string; LFile : file of byte; LOld : TPatchOldFileInfoA; LCreatePatchOptions : ULONG; LIdx : Integer; LPatchItem : TPatchItem; LCreatePatchResult : LongBool; LContinueIfError : Boolean; begin LError := 0; LErrorMessage := ''; try try LContinueIfError := AlwaysRaiseExceptions; LCreatePatchOptions := PatcherHelper.PatchCreateOptionsToULONG(CreatePatchCompressionMode, CreatePatchAdditionalFlags); if PatchItemCount = 0 then raise EPatcherException.Create('No patch items to patch.'); for LIdx := 0 to PatchItemCount - 1 do begin LPatchItem := TPatchItem(FPatchList.Items[LIdx]); if Assigned(OnPatchFileBegin) then begin OnPatchFileBegin( Self, LPatchItem, LIdx + 1, PatchItemCount, LContinueIfError); end; LPatchFile := LPatchItem.PatchFileName; LOldFile := LPatchItem.OldFileName; LNewFile := LPatchItem.NewFileName; LOld.SizeOfThisStruct := SizeOf(LOld); LOld.OldFileName := Pointer(LOldFile); LOld.IgnoreRangeCount := 0; LOld.RetainRangeCount := 0; AssignFile(LFile, LPatchFile); Rewrite(LFile); CloseFile(LFile); LCreatePatchResult := CreatePatchFileExA( 1, @LOld, Pointer(LNewFile), Pointer(LPatchFile), LCreatePatchOptions, nil, @MyPatchCreateApplyCallback, Self); if LCreatePatchResult <> True then begin LError := GetLastError; LErrorMessage := Descriptions_TPatchCreateErrorCode[PatcherHelper.APICodeToPatchCreateErrorCode(LError)]; if LErrorMessage = '' then LErrorMessage := SysErrorMessage(LError); if not (LContinueIfError) then Break; end; if Assigned(OnPatchFileEnd) then begin OnPatchFileEnd( Self, LPatchItem, LIdx + 1, PatchItemCount); end; end; except on E : Exception do begin LError := 1; LErrorMessage := E.ClassName + ' caught with message: ' + E.Message; if AlwaysRaiseExceptions then begin raise; end; end; end; finally if Assigned(OnPatchesComplete) then begin OnPatchesComplete( Self, LError, LErrorMessage); end; end; end; procedure TPatcher.CreatePatchesWide; var LOldFile : WideString; LNewFile : WideString; LPatchFile : WideString; LError : Integer; LErrorMessage : string; LFile : file of byte; LOld : TPatchOldFileInfoW; LCreatePatchOptions : ULONG; LIdx : Integer; LPatchItem : TPatchItem; LCreatePatchResult : LongBool; LContinueIfError : Boolean; begin LError := 0; LErrorMessage := ''; try try LContinueIfError := AlwaysRaiseExceptions; LCreatePatchOptions := PatcherHelper.PatchCreateOptionsToULONG(CreatePatchCompressionMode, CreatePatchAdditionalFlags); if PatchItemCount = 0 then raise EPatcherException.Create('No patch items to patch.'); for LIdx := 0 to PatchItemCount - 1 do begin LPatchItem := TPatchItem(FPatchList.Items[LIdx]); if Assigned(OnPatchFileBegin) then begin OnPatchFileBegin( Self, LPatchItem, LIdx + 1, PatchItemCount, LContinueIfError); end; LPatchFile := LPatchItem.PatchFileName; LOldFile := LPatchItem.OldFileName; LNewFile := LPatchItem.NewFileName; LOld.SizeOfThisStruct := SizeOf(LOld); LOld.OldFileName := Pointer(LOldFile); LOld.IgnoreRangeCount := 0; LOld.RetainRangeCount := 0; // We need to rewrite/create the patch file... or else the patch will fail... AssignFile(LFile, LPatchFile); Rewrite(LFile); CloseFile(LFile); LCreatePatchResult := CreatePatchFileExW( 1, @LOld, Pointer(LNewFile), Pointer(LPatchFile), LCreatePatchOptions, nil, @MyPatchCreateApplyCallback, Self); if LCreatePatchResult <> True then begin LError := GetLastError; LErrorMessage := Descriptions_TPatchCreateErrorCode[PatcherHelper.APICodeToPatchCreateErrorCode(LError)]; if LErrorMessage = '' then LErrorMessage := SysErrorMessage(LError); if not (LContinueIfError) then Break; end; if Assigned(OnPatchFileEnd) then begin OnPatchFileEnd( Self, LPatchItem, LIdx + 1, PatchItemCount); end; end; except on E : Exception do begin LError := 1; LErrorMessage := E.ClassName + ' caught with message: ' + E.Message; if AlwaysRaiseExceptions then begin raise EPatcherException.Create(LErrorMessage); end; end; end; finally if Assigned(OnPatchesComplete) then begin OnPatchesComplete( Self, LError, LErrorMessage); end; end; end; destructor TPatcher.Destroy; begin ResetPatchData(True); FreeAndNil(FPatchList); inherited Destroy; end; function TPatcher.GetItem(AIndex : Integer) : TPatchItem; begin if (PatchItemCount = 0) then begin raise EPatcherException.Create('Patch item count is zero.'); end; if ((AIndex < 0) and (AIndex >= PatchItemCount)) then begin raise EPatcherException.Create('Index for retrieving patch item must be between 0 and ' + IntToStr(PatchItemCount) + '.'); end; Result := TPatchItem(FPatchList.Items[AIndex]); end; function TPatcher.GetPatchItemCount : Integer; begin Result := FPatchList.Count; end; procedure TPatcher.RemovePatchItemAtIndex(const AIndex : Integer); begin if (PatchItemCount = 0) then begin raise EPatcherException.Create('Patch item count is zero.'); end; if ((AIndex < 0) and (AIndex >= PatchItemCount)) then begin raise EPatcherException.Create('Index for retrieving patch item must be between 0 and ' + IntToStr(PatchItemCount) + '.'); end; FPatchList.Delete(AIndex); FPatchList.Capacity := FPatchList.Count; end; procedure TPatcher.ResetPatchData( const AClearEventsAsWell : Boolean); begin FPatchList.Clear; FPatchList.Capacity := FPatchList.Count; FPatchFileExtension := '.pth'; FPatchFilePath := ExtractFilePath(Application.ExeName); FFileMode := psmAnsi; FPatchList := TObjectList.Create(True); FCreatePatchCompressionMode := pcoUseBest; FCreatePatchAdditionalFlags := []; FAlwaysRaiseExceptions := True; if AClearEventsAsWell then begin FOnPatchProgress := nil; FOnPatchesComplete := nil; FOnPatchFileBegin := nil; FOnPatchFileEnd := nil; end; end; procedure TPatcher.SetCompressionMode( const ACompressionMode : TPatchCreateOptions_Compression); begin FCreatePatchCompressionMode := ACompressionMode; end; procedure TPatcher.TestApplyPatches; begin raise EPatcherException.Create('Test Apply Patch To File mode not implemented yet [' + PatcherHelper.EnumTypeToString( TypeInfo(TPatcherFileMode), Integer(FileMode)) + ']'); end; { TPatchItem } constructor TPatchItem.Create(const APatchFileExtension, APatchFilePath : string); begin inherited Create; FPatchFileExtension := APatchFileExtension; FPatchFilePath := APatchFilePath; end; constructor TPatchItem.Create( const APatchFileExtension : string; const APatchFilePath : string; const AOldFileName : string; const ANewFileName : string; const APatchFilename : string); begin Create( APatchFileExtension, APatchFilePath); FOldFileName := AOldFileName; if Trim(ANewFileName) = '' then FNewFileName := FOldFileName else FNewFileName := ANewFileName; if Trim(APatchFileName) = '' then FPatchFileName := GetPatchFileName else FPatchFileName := APatchFilename; end; constructor TPatchItem.Create; begin raise EPatcherException.Create('You cannot instantiate this object using the constructor.'); end; function TPatchItem.GetPatchFileName : string; begin Result := FPatchFilePath + ChangeFileExt(ExtractFileName(NewFileName), FPatchFileExtension); end; { PatcherHelper } class function PatcherHelper.APICodeToPatchApplyErrorCode( const AAPICode : ULONG) : TPatchApplyErrorCode; begin Result := paecUnknown; case AAPICode of ERROR_PATCH_DECODE_FAILURE : Result := paecDecodeFailure; ERROR_PATCH_CORRUPT : Result := paecCorrupt; ERROR_PATCH_NEWER_FORMAT : Result := paecNewerFormat; ERROR_PATCH_WRONG_FILE : Result := paecWrongFile; ERROR_PATCH_NOT_NECESSARY : Result := paecNotNecessary; ERROR_PATCH_NOT_AVAILABLE : Result := paecNotAvailable; end; end; class function PatcherHelper.APICodeToPatchCreateErrorCode( const AAPICode : ULONG) : TPatchCreateErrorCode; begin Result := pcecUnknown; case AAPICode of ERROR_PATCH_ENCODE_FAILURE : Result := pcecEncodeFailure; ERROR_PATCH_INVALID_OPTIONS : Result := pcecInvalidOptions; ERROR_PATCH_SAME_FILE : Result := pcecSameFile; ERROR_PATCH_RETAIN_RANGES_DIFFER : Result := pcecRetainRangesDiffer; ERROR_PATCH_BIGGER_THAN_COMPRESSED : Result := pcecBiggerThanCompressed; ERROR_PATCH_IMAGEHLP_FAILURE : Result := pcecImageHlpFailure; end; end; class function PatcherHelper.EnumTypeToString( const ATypeInfoPointer : PTypeInfo; const AIntegerOfEnum : Integer) : string; begin Result := GetEnumName( ATypeInfoPointer, AIntegerOfEnum); end; class function PatcherHelper.PatchApplyFlagToAPICode( const APatchApplyFlag : TPatchApplyOption) : ULONG; begin Result := 0; case APatchApplyFlag of paoFailIfExact : Result := APPLY_OPTION_FAIL_IF_EXACT; paoFailIfClose : Result := APPLY_OPTION_FAIL_IF_CLOSE; paoTestOnly : Result := APPLY_OPTION_TEST_ONLY; paoValidFlags : Result := APPLY_OPTION_VALID_FLAGS; end; end; class function PatcherHelper.PatchApplyOptionFlagToString( const APatchApplyOptionFlag : TPatchApplyOption) : string; begin Result := EnumTypeToString( TypeInfo(TPatchApplyOption), Integer(APatchApplyOptionFlag)); end; class function PatcherHelper.PatchApplyOptionsToULONG( const APatchApplyOptions : TPatchApplyOptions) : ULONG; var LFlags : ULONG; LAdditional : TPatchApplyOption; begin LFlags := 0; if APatchApplyOptions <> [] then begin for LAdditional := Low(TPatchApplyOption) to High(TPatchApplyOption) do begin if LAdditional in APatchApplyOptions then begin LFlags := LFlags or PatcherHelper.PatchApplyFlagToAPICode(LAdditional); end; end; end; Result := LFlags; end; class function PatcherHelper.PatchCreateFlagToAPICode( const APatchCreateFlag : TPatchCreateOption) : ULONG; begin Result := PATCH_OPTION_USE_BEST; case APatchCreateFlag of pcoUseBest : Result := PATCH_OPTION_USE_BEST; pcoUseLZX_A : Result := PATCH_OPTION_USE_LZX_A; pcoUseLZX_B : Result := PATCH_OPTION_USE_LZX_B; pcoUseBestLZX : Result := PATCH_OPTION_USE_LZX_BEST; pcoUseLZX_Large : Result := PATCH_OPTION_USE_LZX_LARGE; pcoNoBindFix : Result := PATCH_OPTION_NO_BINDFIX; pcoNoLockFix : Result := PATCH_OPTION_NO_LOCKFIX; pcoNoRebase : Result := PATCH_OPTION_NO_REBASE; pcoFailIfSameFile : Result := PATCH_OPTION_FAIL_IF_SAME_FILE; pcoFailIfBigger : Result := PATCH_OPTION_FAIL_IF_BIGGER; pcoNoChecksum : Result := PATCH_OPTION_NO_CHECKSUM; pcoNoResourceTimeStampFix : Result := PATCH_OPTION_NO_RESTIMEFIX; pcoNoTimeStamp : Result := PATCH_OPTION_NO_TIMESTAMP; pcoUseSignatureMD5 : Result := PATCH_OPTION_SIGNATURE_MD5; pcoReserved1 : Result := PATCH_OPTION_RESERVED1; pcoValidFlags : Result := PATCH_OPTION_VALID_FLAGS; end; end; class function PatcherHelper.PatchCreateFlagToString( const APatchCreateFlag : TPatchCreateOption) : string; begin Result := EnumTypeToString( TypeInfo(TPatchCreateOption), Integer(APatchCreateFlag)); end; class function PatcherHelper.PatchCreateOptionsToULONG( const APatchCreateCompression : TPatchCreateOptions_Compression; const APatchCreateAdditional : TPatchCreateOptions_Additional) : ULONG; var LFlags : ULONG; LAdditional : TPatchCreateOption; begin LFlags := PatcherHelper.PatchCreateFlagToAPICode(APatchCreateCompression); if APatchCreateAdditional <> [] then begin for LAdditional := Low(TPatchCreateOption) to High(TPatchCreateOption) do begin if LAdditional in APatchCreateAdditional then begin LFlags := LFlags or PatcherHelper.PatchCreateFlagToAPICode(LAdditional); end; end; end; Result := LFlags; end; class function PatcherHelper.PatchFileModeToString( const APatcherFileMode : TPatcherFileMode) : string; begin Result := EnumTypeToString( TypeInfo(TPatcherFileMode), Integer(APatcherFileMode)); end; class function PatcherHelper.StringToPatchApplyOptionFlag( const APatchApplyOptionFlagString : string) : TPatchApplyOption; begin Result := TPatchApplyOption( GetEnumValue( TypeInfo(TPatchApplyOption), APatchApplyOptionFlagString)); end; class function PatcherHelper.StringToPatchCreateFlag( const APatchCreateFlagString : string) : TPatchCreateOption; begin Result := TPatchCreateOption( GetEnumValue( TypeInfo(TPatchCreateOption), APatchCreateFlagString)); end; class function PatcherHelper.StringToPatchFileMode( const APatcherFileModeString : string) : TPatcherFileMode; begin Result := TPatcherFileMode( GetEnumValue( TypeInfo(TPatcherFileMode), APatcherFileModeString)); end; end.
unit View.EstoqueVA; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DAO.EstoqueVA, DAO.ProdutosVA, Model.EstoqueVA, Model.ProdutosVA, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, cxLabel, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, dxmdaset, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid; type Tview_EstoqueVA = class(TForm) dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; dxLayoutItem1: TdxLayoutItem; mtbEstoque: TdxMemData; mtbEstoqueID_ESTOQUE: TIntegerField; mtbEstoqueID_PRODUTO: TIntegerField; mtbEstoqueDAT_ESTOQUE: TDateField; mtbEstoqueQTD_ESTOQUE: TFloatField; mtbEstoqueVAL_UNITARIO: TFloatField; mtbEstoqueVAL_ESTOQUE: TFloatField; mtbEstoqueDES_LOG: TMemoField; dsEstoque: TDataSource; private { Private declarations } public { Public declarations } end; var view_EstoqueVA: Tview_EstoqueVA; implementation {$R *.dfm} uses udm, uGlobais; end.
// stack buku program stack_buku; uses crt; const max = 10; type stack=record judul,pengarang: array[1..max] of string; tos,bos:0..max; // tos : top of stack ; bos : bottom of stack end; var stackbuku : stack; pil,i:byte; function isFull(S:stack):Boolean; begin if S.tos=max then isFull:=true else isFull:=false; end; function isEmpty(S:stack):Boolean; begin if S.tos=0 then isEmpty:=true else isEmpty:=false; end; procedure PushBuku(var S:stack); begin WriteLn('Menambahkan buku baru ke dalam tumpukan'); Inc(S.tos);//menaikkan posisii tos of stack kr ada data baru akan masuk Write('masukkan judul buku yang baru : ');ReadLn(S.judul[S.tos]);//perhatikan posisi index milik atribut bukan milik variabel Write('masukkan nama pengarang : ');ReadLn(S.pengarang[S.tos]);//idem WriteLn('Buku sudah berhasil ditambahkan ke dalam stack '); end; procedure PopBuku(var S:stack); var ya:char; begin WriteLn('Mengambil data dari stack buku'); WriteLn('Berikut adalah buku di posisi teratas stack buku : '); WriteLn('Judul Buku : ',S.judul[S.tos]); WriteLn('Pengarang : ',S.pengarang[S.tos]); WriteLn('yakin akan diambil buku tsb <y/t> ? ');ReadLn(ya); if (ya='Y') or (ya='y') then begin dec(S.tos); WriteLn('Buku sudah diambil dari tumpukan '); end else WriteLn('buku tidak jadi diambil dari stack '); end; procedure PrintBuku(var S:stack); begin WriteLn('Daftar Buku di tumpukan saat ini dan posisiya '); WriteLn('-----------------------------------------------'); WriteLn('Posisi judul Pengarang '); WriteLn('-----------------------------------------------'); for i:=S.tos downto S.bos do WriteLn(i:3,' ',S.judul[i]:15,' ',S.pengarang[i]:10); WriteLn('-----------------------------------------------'); WriteLn('Saat ini ada ',S.tos,' buku di dalam stack'); end; begin // inisialisasi stackbuku.tos:= 0; stackbuku.bos:=1; repeat clrscr; WriteLn('Manipulasi Stack Buku'); WriteLn('1. Push Data ke Stack Buku'); WriteLn('2. Pop Data ke Stack Buku'); WriteLn('3. Cetak Stack Buku'); WriteLn('0. selesai'); Write('pilih menu 0-3 : ');ReadLn(pil); case pil of 1:if isFull(stackbuku)=true then WriteLn('Stcak buku sudah penuh') else PushBuku(stackbuku); 2:if isEmpty(stackbuku)=true then WriteLn('Stcak buku kosong') else PopBuku(stackbuku); 3:if isEmpty(stackbuku)=true then WriteLn('Stcak buku kosong') else PrintBuku(stackbuku); 0:WriteLn('terimakasih') else WriteLn('Anda '); end; ReadLn; until pil = 0; end.
UNIT SortedCollection; INTERFACE USES Lexer; PROCEDURE PrintCollection(); PROCEDURE Insert(Lexem: LexemType); IMPLEMENTATION TYPE Tree = ^NodeType; NodeType = RECORD Lexem: LexemType; LLink, RLink: Tree; Count: INTEGER; END; VAR Root: Tree; PROCEDURE LocalInsert(VAR Ptr: Tree; VAR Lexem: LexemType); BEGIN {LocalInsert} IF Ptr = NIL THEN{Add new leaf to tree with Lexem value} BEGIN New(Ptr); Ptr^.Lexem := Lexem; Ptr^.LLink := NIL; Ptr^.RLink := NIL; Ptr^.Count := 1; END ELSE IF Ptr^.Lexem > Lexem THEN LocalInsert(Ptr^.LLink, Lexem) ELSE BEGIN IF Ptr^.Lexem < Lexem THEN LocalInsert(Ptr^.RLink, Lexem) ELSE Ptr^.Count := Ptr^.Count + 1 END END; {LocalInsert} PROCEDURE Insert(Lexem: LexemType); BEGIN{Insert} LocalInsert(Root, Lexem) END;{Insert} PROCEDURE LocalPrintTree(Ptr: Tree); BEGIN {LocalPrintTree} IF Ptr <> NIL THEN BEGIN LocalPrintTree(Ptr^.LLink); WRITE(Ptr^.Lexem, ' ', Ptr^.Count); WRITELN; LocalPrintTree(Ptr^.RLink) END END; {LocalPrintTree} PROCEDURE PrintCollection(); BEGIN{PrintCollection} LocalPrintTree(Root) END;{PrintCollection} BEGIN{SortedCollection} Root := NIL END.{SortedCollection}
unit OptionsConfigImpl; interface uses Classes,Windows,SysUtils,AdoDb,Forms,Registry,ActiveX,DB,WinSock; type EUnSupportException=class(Exception); TFTPUseMode=(umWindow,umFTP); TTransmitStyle=(tsFTP,tsDTS); TTransmitStyles=set of TTransmitStyle; TConnectStringBulider=class(TPersistent) private FUser: string; FPassword: string; FDatabase: string; FDataSource: string; FDbType: Integer; FConnStr:string; FInterfaceDatabase: string; FInterfacePath: string; FInterfaceMappingPath: string; FLocalImportPath: string; FCommandTimeOut: integer; FLocalExportPath: string; function GetConnectionString: string; function GetWorkStation: string; procedure SetConnectionString(const Value: string); procedure SetDatabaseType(const Value: Integer); function GetDBMSDescription: string; function GetDBMSID: string; procedure SetDataSource(const Value: string); function GetDatabase: string; function GetConnectName: string; function GetInterfaceDatabase: string; protected procedure Parser; public procedure Assign(Source: TPersistent);override; property User:string read FUser write FUser; property Password:string read FPassword write FPassword; property Database:string read GetDatabase write FDatabase; property InterfaceDatabase:string read GetInterfaceDatabase write FInterfaceDatabase; property CommandTimeOut:integer read FCommandTimeOut write FCommandTimeOut; //本地导入文件 property LocalImportPath:string read FLocalImportPath write FLocalImportPath; property LocalExportPath:string read FLocalExportPath write FLocalExportPath; property InterfacePath:string read FInterfacePath write FInterfacePath; property InterfaceMappingPath:string read fInterfaceMappingPath write FInterfaceMappingPath; property DataSource:string read FDataSource write SetDataSource; property DbType:Integer read FDbType write SetDatabaseType; property WorkStation:string read GetWorkStation; property ConnectionString:string read GetConnectionString write SetConnectionString; property DBMSID:string read GetDBMSID; property DBMSDescription:string read GetDBMSDescription; property ConnectName:string read GetConnectName; end; TFTPConfigOption=class(TComponent) private FRetry: Integer; FPort: Integer; FTimeOut: Integer; FProxyPort: Integer; FPassword: string; FHost: string; FUser: string; FProxyServer: string; FRootDir: string; FZipPassword: String; FUseMode: TFTPUseMode; function GetPort: Integer; function GetTimeOut: Integer; public procedure Assign(Source: TPersistent);override; destructor Destroy;override; property RootDir:string read FRootDir write FRootDir; property User:string read FUser write FUser; property Password:string read FPassword write FPassword; property Host:string read FHost write FHost; property Port:Integer read GetPort write FPort; property Retry:Integer read FRetry write FRetry; property TimeOut:Integer read GetTimeOut write FTimeOut; property ProxyServer:string read FProxyServer write FProxyServer; property ProxyPort:Integer read FProxyPort write FProxyPort; property UseMode:TFTPUseMode read FUseMode write FUseMode; property ZipPassword:String read FZipPassword write FZipPassword; end; TDataProcessOption=class(TComponent) private FAutoReveive: Boolean; FAutoSend: Boolean; FSendFrequency: Integer; FReveiveFrquency: Integer; FTriggerFileDir: String; FFileLogDir: String; FDefaultTrigger: String; FProcedureFileDir: String; FDefaultProcedure: String; FTransmitStyles: TTransmitStyles; function GetAutoReveive: Boolean; function GetAutoSend: Boolean; function GetReveiveFrquency: Integer; function GetSendFrequency: Integer; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Assign(Source: TPersistent);override; property AutoSend:Boolean read GetAutoSend write FAutoSend; property SendFrequency:Integer read GetSendFrequency write FSendFrequency; property AutoReveive:Boolean read GetAutoReveive write FAutoReveive; property ReveiveFrquency:Integer read GetReveiveFrquency write FReveiveFrquency; property FileLogDir:String read FFileLogDir write FFileLogDir; property DefaultTrigger:String read FDefaultTrigger write FDefaultTrigger; property TriggerFileDir:String read FTriggerFileDir write FTriggerFileDir; property DefaultProcedure:String read FDefaultProcedure write FDefaultProcedure; property ProcedureFileDir:String read FProcedureFileDir write FProcedureFileDir; property TransmitStyles:TTransmitStyles read FTransmitStyles write FTransmitStyles; end; TServerConfigOption=class(TComponent) private FIsCompress: Boolean; FListenQueue: Integer; FTerminateWaitTime: Longint; FPort: Longint; FIPAdress: String; FSvrGuid: string; FConnectMode: integer; public constructor Create(AOwner:TComponent);override; procedure Assign(Source: TPersistent);override; property IsCompress:Boolean read FIsCompress write FIsCompress; property Port:Longint read FPort write FPort; property IPAdress:String read FIPAdress write FIPAdress; property ListenQueue:Integer read FListenQueue write FListenQueue; property SvrGuid:string read FSvrGuid write FSvrGuid ; property ConnectMode:integer read FConnectMode write FConnectMode; property TerminateWaitTime:Longint read FTerminateWaitTime write FTerminateWaitTime; end; TConfigSettings=class(TComponent) private FConnStrBulider: TConnectStringBulider; FFTPOption: TFTPConfigOption; FProcessOption: TDataProcessOption; FServerOption: TServerConfigOption; FStoreId: string; FOnline: Boolean; function GetFileName: string; function GetStoreId: string; function GetFTPOption: TFTPConfigOption; function GetProcessOption: TDataProcessOption; function GetServerOption: TServerConfigOption; function GetConnStrBulider: TConnectStringBulider; protected function ConvertTransmitStylesSetToInteger(AStyles:TTransmitStyles):Integer; function ConvertIntegerToTransmitStyles(Value:Integer):TTransmitStyles; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure LoadFromStream; procedure SaveToStream; property ConnStrBulider:TConnectStringBulider read GetConnStrBulider; property FTPOption:TFTPConfigOption read GetFTPOption ; property ProcessOption:TDataProcessOption read GetProcessOption ; property ServerOption:TServerConfigOption read GetServerOption ; property StoreId:string read GetStoreId write FStoreId; property Online:Boolean read FOnline write FOnline; property FileName:string read GetFileName; end; TRemoteServerConfig=class(TCollectionItem) private FServerId: string; FFTPOption: TFTPConfigOption; FServerOption: TServerConfigOption; FServerName: string; procedure SetFTPOption(const Value: TFTPConfigOption); procedure SetServerOption(const Value: TServerConfigOption); protected public constructor Create(Collection: TCollection);override; destructor Destroy;override; property FTPOption:TFTPConfigOption read FFTPOption write SetFTPOption; property ServerOption:TServerConfigOption read FServerOption write SetServerOption; property ServerId:string read FServerId write FServerId; property ServerName:string read FServerName write FServerName; end; TRemoteServerConfigItems=class(TCollection) private function GetItems(Index: Integer): TRemoteServerConfig; public constructor Create; procedure Fill(ADataSet:TDataSet); function Add:TRemoteServerConfig; property Items[Index:Integer]:TRemoteServerConfig read GetItems;default; end; implementation uses IniFiles,ShareLib; const dbtAccess = $00000000; dbtSqlServer = $00000001; dbtOracle = $00000002; dbtInterbase = $00000003; dbtDb2 = $00000004; dbtMySql = $00000005; dbtMsOdbcSql = $00000006; {DBMS_ID} SQLSERVER_DBMS_ID ='SqlServer'; ACCESS_DBMS_ID ='Access'; ORACLE_DBMS_ID ='Oracle'; INTERBASE_DBMS_ID ='Interbase'; DB2_DBMS_ID ='Db2'; MYSQL_DBMS_ID ='MySql'; MSODBC_DBMS_ID ='MsOdbc'; const ServerConfigFileName='ServerConfig.Ini'; DBConnectSection ='DBConfig'; DBConnectUserIdent ='User'; DBConnectPasswordIdent ='Password'; DBConnectDatabaseIdent ='Database'; DBConnectDataSourceIdent ='DataSource'; DBConnectDbTypeIdent ='DbType'; DBConnectInterfaceDatabaseIdent ='InterfaceDatabase'; DBConnectInterfacePath ='InterfacePath'; DBConnectInterfaceMappingPath ='InterfaceMappingPath'; DBConnectLocalImportPath ='LocalImportPath'; DBConnectLocalExportPath ='LocalExportPath'; DBConnectCommandTimeOut='CommandTimeOut'; { TConnectStringBulider } procedure TConnectStringBulider.Assign(Source: TPersistent); var Conn:TConnectStringBulider; begin if Source is TConnectStringBulider then begin Conn:=Source as TConnectStringBulider; FUser:=Conn.User; FPassword:=Conn.Password; FDatabase:=Conn.Database; FDataSource:=Conn.DataSource; FDbType:=Conn.DbType; end; end; function TConnectStringBulider.GetConnectionString: string; const MySqlConntion='DRIVER={MySQL ODBC 3.51 Driver};DESC=;' +'DATABASE=%s;SERVER=%s;UID=%s;PASSWORD=%s;PORT=3306;OPTION=;STMT=;'; DB2Connection='Provider=IBMDADB2.1;Password=%s;Persist Security Info=True;' +'User ID=%s;Data Source=%s;Location=%s'; AccessConnection ='Provider=Microsoft.Jet.OLEDB.4.0;User ID=%s;' +'Data Source=%s;Persist Security Info=True;Jet OLEDB:Database Password=%s'; SqlServerConnection='Provider=SQLOLEDB.1;Password=%s' +';Persist Security Info=True;User ID=%s' +';Initial Catalog=%s;Data Source=%S' +';Use Encryption for Data=False;' +'Tag with column collation when possible=False;' +'Use Procedure for Prepare=1;' +'Auto Translate=True;' +'Packet Size=4096;' +'Workstation ID=%s'; OracleConnection='Provider=MSDAORA.1;Password=%S;' +'User ID=%S;Data Source=%S;Persist Security Info=True'; MSDASQLConnection='Provider=MSDASQL.1;Password=%s;Persist Security Info=True;User ID=%s;Data Source=%s'; begin Result:=''; case DbType of dbtAccess:Result:=Format(AccessConnection,[User,DataSource,Password]); dbtSqlServer: Result:=Format(SqlServerConnection,[Password,User,Database,DAtaSource,WorkStation]); dbtOracle:Result:=Format(OracleConnection,[Password,User,Database]); dbtInterbase:raise EUnSupportException.Create('不支持的数据库类型'); dbtDB2:Result:=Format(DB2Connection,[Password,User,Database,DataSource]); dbtMySql:Result:=Format(MySqlConntion,[Database,DataSource,User,Password]); dbtMsOdbcSql:Result:=Format(MSDASQLConnection,[Password,User,DataSource]); else raise EUnSupportException.Create('不支持的数据库类型'); end; FConnStr:=Result; end; function TConnectStringBulider.GetConnectName: string; begin Result:=WorkStation+'.'+DBMSID+'.'+Database; end; function TConnectStringBulider.GetDatabase: string; var FileName:string; I:Integer; begin if DbType=dbtAccess then begin FileName:=ExtractFileName(DataSource); I:=Pos('.',FileName); if I>0 then Result:=Copy(FileName,1,I-1) else Result:=FileName; end else Result := FDatabase; end; function TConnectStringBulider.GetDBMSDescription: string; begin case DbType of dbtAccess:Result:=ACCESS_DBMS_ID; dbtSqlServer:Result:=SQLSERVER_DBMS_ID; dbtOracle:Result:=ORACLE_DBMS_ID; dbtInterbase:Result:=INTERBASE_DBMS_ID; dbtDb2:Result:=DB2_DBMS_ID; dbtMySql:Result:=MYSQL_DBMS_ID; else Result:='UnKnown'; end; end; function TConnectStringBulider.GetDBMSID: string; begin case DbType of dbtAccess:Result:=ACCESS_DBMS_ID; dbtSqlServer:Result:=SQLSERVER_DBMS_ID; dbtOracle:Result:=ORACLE_DBMS_ID; dbtInterbase:Result:=INTERBASE_DBMS_ID; dbtDb2:Result:=DB2_DBMS_ID; dbtMySql:Result:=MYSQL_DBMS_ID; else Result:='UnKnown'; end; end; function TConnectStringBulider.GetInterfaceDatabase: string; var FileName:string; I:Integer; begin if DbType=dbtAccess then begin FileName:=ExtractFileName(DataSource); I:=Pos('.',FileName); if I>0 then Result:=Copy(FileName,1,I-1) else Result:=FileName; end else Result := FInterfaceDatabase; end; function TConnectStringBulider.GetWorkStation: string; const Len=200; var Data:TWSAData; Buffer:PChar; begin GetMem(Buffer,Len); try try Winsock.WSAStartup($101,Data); Winsock.gethostname(Buffer,Len); Result:=Buffer; Winsock.WSACleanup; except end; finally FreeMem(Buffer,Len); end; end; procedure TConnectStringBulider.Parser; var List:TStringList; procedure ParserString; var I,Len:Integer; Value:string; C:Char; begin Len:=Length(FConnStr); I:=1; while (I<=Len) do begin C:=FConnStr[I]; if (C<>';') then Value:=Value+C else if (C=';') then begin List.Add(Value); Value:=''; end; Inc(I); end; if Value<>'' then List.Add(Value); end; procedure ParserSqlServer; var Value:string; begin ParserString; User:=List.Values['User ID']; Database:=List.Values['Initial Catalog']; DataSource:=List.Values['Data Source']; Password:=List.Values['Password']; Value:=List.Values['Persist Security Info']; end; procedure ParserMySql; begin ParserString; User:=List.Values['UID']; Database:=List.Values['DATABASE']; DataSource:=List.Values['SERVER']; Password:=List.Values['PASSWORD']; end; procedure ParserAccess; begin ParserString; User:=List.Values['User ID']; DataSource:=List.Values['Data Source']; Password:=List.Values['Jet OLEDB:Database Password']; end; procedure ParserDB2; begin ParserString; User:=List.Values['User ID']; Database:=List.Values['Data Source']; DataSource:=List.Values['Location=']; Password:=List.Values['Password']; end; procedure ParserOracle; begin ParserString; User:=List.Values['User ID']; Database:=List.Values['Data Source']; DataSource:=List.Values['Location=']; Password:=List.Values['Password']; end; begin if(FConnStr='')then Exit; List:=TStringList.Create; try case DbType of dbtAccess: ParserAccess; dbtSqlServer:ParserSqlServer; dbtOracle:ParserOracle; dbtInterbase:; dbtDB2:ParserDB2; dbtMySql:ParserMySql; end; finally List.Free; end; end; procedure TConnectStringBulider.SetConnectionString(const Value: string); begin if ConnectionString<>Value then FConnStr:=Value; Parser; end; procedure TConnectStringBulider.SetDatabaseType(const Value: Integer); begin if FDbType<>Value then FDbType := Value; Parser; end; procedure TConnectStringBulider.SetDataSource(const Value: string); begin FDataSource := Value; end; { TMQConfigEnvironment } function TConfigSettings.ConvertIntegerToTransmitStyles( Value: Integer): TTransmitStyles; begin case Value of 1:Result:=[tsDTS]; 2:Result:=[tsFTP]; 3:Result:=[tsFTP,tsDTS]; else Result:=[]; end; end; function TConfigSettings.ConvertTransmitStylesSetToInteger( AStyles: TTransmitStyles): Integer; begin if AStyles=[tsFTP,tsDTS]then begin Result:=3; end else if AStyles=[tsFTP]then begin Result:=2; end else if AStyles=[tsDTS]then begin REsult:=1; end else Result:=0; end; constructor TConfigSettings.Create(AOwner: TComponent); begin inherited Create(AOwner); FConnStrBulider:=TConnectStringBulider.Create; FConnStrBulider.DbType:=dbtSqlServer; FFTPOption:=TFTPConfigOption.Create(AOwner); FProcessOption:=TDataProcessOption.Create(AOwner); FServerOption:=TServerConfigOption.Create(AOwner) ; FOnline:=True; end; destructor TConfigSettings.Destroy; begin //FConnStrBulider.Free; inherited; end; function TConfigSettings.GetConnStrBulider: TConnectStringBulider; begin result:=FConnStrBulider ; end; function TConfigSettings.GetFileName: string; begin Result:=IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))+ServerConfigFileName; end; function TConfigSettings.GetFTPOption: TFTPConfigOption; begin result:=FFTPOption ; end; function TConfigSettings.GetProcessOption: TDataProcessOption; begin result:=FProcessOption ; end; function TConfigSettings.GetServerOption: TServerConfigOption; begin result:=FServerOption ; end; function TConfigSettings.GetStoreId: string; const StoreKey='\SOFTWARE\Remote\Session'; var Buffer,strCash:string; function ReadDatabaseStoreCode(AStoreId:string):string; var Conn:TADOConnection; begin REsult:=EmptyStr; CoInitialize(nil) ; try Conn:=TADOConnection.Create(nil); except exit ; end ; try try Conn.LoginPrompt:=False; Conn.ConnectionString:=ConnStrBulider.ConnectionString; Conn.Connected:=True; with TADOQuery.Create(nil) do try Connection:=Conn; Sql.Text:=Format('select store_code from store where store_code_id=%s',[AStoreId]); Active:=True; if not IsEmpty then Result:=FieldByName('store_code').AsString; finally Free; end; except on E:Exception do begin end; end; finally Conn.Free; end; if REsult=EmptyStr then Result:=AStoreId; end; begin Buffer:=EmptyStr ; if FStoreId<>EmptyStr then begin Result:=FStoreId; end else begin with TRegistry.Create do try Buffer:=EmptyStr; RootKey:=HKEY_LOCAL_MACHINE; if KeyExists(StoreKey)then begin if OpenKey(StoreKey,False)then begin Buffer:=ReadString('Code'); strCash :=ReadString('Cash'); CloseKey; end; end; finally Free; end; if Buffer<>EmptyStr then begin FStoreId:=Buffer ; if (Trim(strCash)<>'') and (Uppercase(Trim(strCash))<>'NULL') and (Trim(strCash)<>'1') then begin FStoreId:=Buffer+'_'+strCash ; end ; end ; Result:=Buffer ; //Result:=ReadDatabaseStoreCode(Buffer); end; end; procedure TConfigSettings.LoadFromStream; var SuperIni:TIniFile; begin if FileExists(FileName)then begin SuperIni:=TIniFile.Create(FileName); try //Summary: // 总部数据库连接配置 ConnStrBulider.User:=SuperIni.ReadString(DBConnectSection,DBConnectUserIdent,EmptyStr); //ConnStrBulider.Password:=DecodeString(SuperIni.ReadString(DBConnectSection,DBConnectPasswordIdent,EmptyStr)); ConnStrBulider.Password:=SuperIni.ReadString(DBConnectSection,DBConnectPasswordIdent,EmptyStr); ConnStrBulider.Database:=SuperIni.ReadString(DBConnectSection,DBConnectDatabaseIdent,EmptyStr); ConnStrBulider.DataSource:=SuperIni.ReadString(DBConnectSection,DBConnectDataSourceIdent,EmptyStr); ConnStrBulider.DbType:=SuperIni.ReadInteger(DBConnectSection,DBConnectDbTypeIdent,1); ConnStrBulider.InterfaceDatabase:=SuperIni.ReadString(DBConnectSection,DBConnectInterfaceDatabaseIdent,EmptyStr); ConnStrBulider.InterfacePath:=SuperIni.ReadString(DBConnectSection,DBConnectInterfacePath,EmptyStr); ConnStrBulider.InterfaceMappingPath:=SuperIni.ReadString(DBConnectSection,DBConnectInterfaceMappingPath,EmptyStr); ConnStrBulider.LocalImportPath :=SuperIni.ReadString(DBConnectSection,DBConnectLocalImportPath,EmptyStr); ConnStrBulider.LocalExportPath :=SuperIni.ReadString(DBConnectSection,DBConnectLocalExportPath,EmptyStr); ConnStrBulider.CommandTimeOut:=SuperIni.ReadInteger(DBConnectSection,DBConnectCommandTimeOut,120); finally SuperIni.Free; end; end; end; procedure TConfigSettings.SaveToStream; var SuperIni:TIniFile; begin SuperIni:=TIniFile.Create(FileName); try //Summary: // 总部数据库连接配置 SuperIni.WriteString(DBConnectSection,DBConnectUserIdent,ConnStrBulider.User); SuperIni.WriteString(DBConnectSection,DBConnectPasswordIdent,EncodeString(ConnStrBulider.Password)); SuperIni.WriteString(DBConnectSection,DBConnectDatabaseIdent,ConnStrBulider.Database); SuperIni.WriteString(DBConnectSection,DBConnectDataSourceIdent,ConnStrBulider.DataSource); SuperIni.WriteInteger(DBConnectSection,DBConnectDbTypeIdent,Integer(ConnStrBulider.DbType)); SuperIni.WriteInteger(DBConnectSection,DBConnectCommandTimeOut,Integer(ConnStrBulider.CommandTimeOut)); SuperIni.WriteString(DBConnectSection,DBConnectLocalImportPath,ConnStrBulider.LocalImportPath); SuperIni.WriteString(DBConnectSection,DBConnectLocalExportPath,ConnStrBulider.LocalExportPath); SuperIni.WriteString(DBConnectSection,DBConnectInterfaceDatabaseIdent,ConnStrBulider.InterfaceDatabase); SuperIni.WriteString(DBConnectSection,DBConnectInterfacePath,ConnStrBulider.InterfacePath); SuperIni.WriteString(DBConnectSection,DBConnectInterfaceMappingPath,ConnStrBulider.InterfaceMappingPath); finally SuperIni.Free; end; end; { TFTPConfigOption } procedure TFTPConfigOption.Assign(Source: TPersistent); begin if Source is TFTPConfigOption then begin RootDir:=TFTPConfigOption(Source).RootDir; User:=TFTPConfigOption(Source).User; Password:=TFTPConfigOption(Source).Password; Host:=TFTPConfigOption(Source).Host; Port:=TFTPConfigOption(Source).Port; Retry:=TFTPConfigOption(Source).Retry; TimeOut:=TFTPConfigOption(Source).TimeOut; ProxyServer:=TFTPConfigOption(Source).ProxyServer; ProxyPort:=TFTPConfigOption(Source).ProxyPort; UseMode:=TFTPConfigOption(Source).UseMode; ZipPassword:=TFTPConfigOption(Source).ZipPassword; end; end; destructor TFTPConfigOption.Destroy; begin inherited; end; function TFTPConfigOption.GetPort: Integer; begin if FPort<=0 then FPort:=21; Result := FPort; end; function TFTPConfigOption.GetTimeOut: Integer; begin if FTimeOut<0 then FTimeOut:=30000; Result := FTimeOut; end; { TDataProcessOption } procedure TDataProcessOption.Assign(Source: TPersistent); begin if Source is TDataProcessOption then begin AutoSend:=TDataProcessOption(Source).AutoSend; SendFrequency:=TDataProcessOption(Source).SendFrequency; AutoReveive:=TDataProcessOption(Source).AutoReveive; ReveiveFrquency:=TDataProcessOption(Source).ReveiveFrquency; FileLogDir:=TDataProcessOption(Source).FileLogDir; DefaultTrigger:=TDataProcessOption(Source).DefaultTrigger; TriggerFileDir:=TDataProcessOption(Source).TriggerFileDir; DefaultProcedure:=TDataProcessOption(Source).DefaultProcedure; ProcedureFileDir:=TDataProcessOption(Source).ProcedureFileDir; TransmitStyles:=TDataProcessOption(Source).TransmitStyles; end; end; constructor TDataProcessOption.Create(AOwner:TComponent); begin inherited Create(Aowner); TransmitStyles:=[tsFTP]; end; destructor TDataProcessOption.Destroy; begin inherited; end; function TDataProcessOption.GetAutoReveive: Boolean; begin Result := FAutoReveive and (ReveiveFrquency>0); end; function TDataProcessOption.GetAutoSend: Boolean; begin Result := FAutoSend and(SendFrequency>0); end; function TDataProcessOption.GetReveiveFrquency: Integer; begin Result := FReveiveFrquency; if FReveiveFrquency<=0 then Result:=30; end; function TDataProcessOption.GetSendFrequency: Integer; begin Result := FSendFrequency; if FSendFrequency<=0 then Result:=30; end; { TServerConfigOption } procedure TServerConfigOption.Assign(Source: TPersistent); begin if Source is TServerConfigOption then begin FTerminateWaitTime:=TServerConfigOption(Source).TerminateWaitTime; FPort:=TServerConfigOption(Source).Port; FIsCompress:=TServerConfigOption(Source).IsCompress; FListenQueue:=TServerConfigOption(Source).ListenQueue; FIPAdress:=TServerConfigOption(Source).IPAdress; FSvrGuid:=TServerConfigOption(Source).SvrGuid; FConnectMode:=TServerConfigOption(Source).ConnectMode; end; end; constructor TServerConfigOption.Create(AOwner:TComponent); begin inherited Create(AOwner); FTerminateWaitTime:=5000; FPort:=211; FIsCompress:=False; FListenQueue:=15; FIPAdress:='127.0.0.1'; end; { TRemoteServerConfig } constructor TRemoteServerConfig.Create(Collection: TCollection); begin inherited; FFTPOption:= TFTPConfigOption.Create(nil); FServerOption:= TServerConfigOption.Create(nil); end; destructor TRemoteServerConfig.Destroy; begin FFTPOption.Free ; FServerOption.Free ; inherited; end; procedure TRemoteServerConfig.SetFTPOption(const Value: TFTPConfigOption); begin FFTPOption.Assign(Value) ; end; procedure TRemoteServerConfig.SetServerOption( const Value: TServerConfigOption); begin FServerOption.Assign(Value) ; end; { TRemoteServerConfigItems } function TRemoteServerConfigItems.Add: TRemoteServerConfig; begin Result:=TRemoteServerConfig(inherited Add); end; constructor TRemoteServerConfigItems.Create; begin inherited Create(TRemoteServerConfig); end; procedure TRemoteServerConfigItems.Fill(ADataSet: TDataSet); var Item:TRemoteServerConfig; begin ADataSet.First; while not ADataSet.Eof do begin Item:=Add; Item.ServerId :=ADataSet.FieldByName('SERVERID').AsString; Item.ServerName :=ADataSet.FieldByName('SERVERNAME').AsString; Item.ServerOption.IPAdress :=ADataSet.FieldByName('SEV_HOST').AsString; Item.ServerOption.Port :=ADataSet.FieldByName('SEV_PORT').AsInteger; Item.ServerOption.SvrGuid :=ADataSet.FieldByName('SEV_GUID').AsString; Item.ServerOption.ConnectMode :=ADataSet.FieldByName('SEV_CONNECTMODE').AsInteger; Item.FTPOption.RootDir :=ADataSet.FieldByName('FTP_ROOT').AsString; Item.FTPOption.Host :=ADataSet.FieldByName('FTP_HOST').AsString; Item.FTPOption.Port :=ADataSet.FieldByName('FTP_PORT').AsInteger; Item.FTPOption.User :=ADataSet.FieldByName('FTP_USER').AsString; Item.FTPOption.Password :=DecodeString(ADataSet.FieldByName('FTP_PASSWORD').AsString); Item.FTPOption.Retry :=ADataSet.FieldByName('FTP_RETRY').AsInteger; Item.FTPOption.TimeOut :=ADataSet.FieldByName('FTP_RETRY').AsInteger; Item.FTPOption.ProxyServer :=ADataSet.FieldByName('FTP_PROXYHOST').AsString; Item.FTPOption.ProxyPort :=ADataSet.FieldByName('FTP_PROXYPORT').AsInteger; ADataSet.Next; end; end; function TRemoteServerConfigItems.GetItems( Index: Integer): TRemoteServerConfig; begin Result:=TRemoteServerConfig(inherited Items[Index]); end; end.
unit InsertTableFrm; interface uses Forms, cxLookAndFeelPainters, cxCheckBox, cxDropDownEdit, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit, Controls, StdCtrls, ExtCtrls, Classes, cxButtons; type TInsertTableForm = class(TForm) OK: TcxButton; Cancel: TcxButton; Panel1: TPanel; Panel2: TPanel; Label1: TLabel; Label2: TLabel; rows: TcxSpinEdit; cols: TcxSpinEdit; Panel3: TPanel; align: TcxComboBox; border: TcxSpinEdit; cellpadding: TcxSpinEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; cellspacing: TcxSpinEdit; Panel4: TPanel; UseWidth: TcxCheckBox; PercentWidth: TcxCheckBox; _width: TcxSpinEdit; private function GetTableAttrs: String; public property TableAttrs: String read GetTableAttrs; end; function GetInsertTableForm(var NumRows, NumCols: Integer; var _TableAttrs: String): Integer; implementation {$R *.dfm} uses SysUtils, AlignUtils; function GetInsertTableForm; var Form: TInsertTableForm; begin Form := TInsertTableForm.Create(Application); try with Form do begin Result := ShowModal; if Result = mrOK then begin NumRows := rows.Value; NumCols := cols.Value; _TableAttrs := TableAttrs; end; end; finally Form.Free; end; end; function TInsertTableForm.GetTableAttrs: String; var p, w: String; begin if UseWidth.Checked then begin p := ''; if PercentWidth.Checked then p := '%'; w := Format(' width="%s%s"', [_width.Value, p]); end; Result := Format('border="%s" cellpadding="%s" cellspacing="%s"', [border.Value, cellpadding.Value, cellspacing.Value]) + w; end; end.
unit myADO; interface uses ActiveX, Variants, IniFiles, SysUtils, Classes, ADODB; type TMyADO=class ADO: variant; pathINIFile: string; ConnectionString: string; strSQL: string; bADOError: boolean; bADOErrDescript: string; constructor Create(MyADO: variant); overload; destructor CloseADO; overload; function OpenADO:boolean; end; implementation uses main; constructor TMyADO.Create(MyADO: variant); var Ini: TiniFile; begin inherited Create; pathINIFile:='cgicfg.ini'; Ini:=TiniFile.Create(pathINIFile); ConnectionString:=Ini.ReadString('NewsDir','ConnectionString',''); Ini.Free; CoInitialize(nil); ADO:=MyADO; if VarType(ADO)<> VarDispatch then begin bADOError:=true; //невозможно создать ADO bADOErrDescript:='Невозможно подключиться к базе новостей'; end; end; destructor TMyADO.CloseADO; begin ADO.Close; inherited; end; function TMyADO.OpenADO: boolean; begin Result:=True; if (not bADOError) then begin try ADO.Open(strSQL,ConnectionString,2,2) except on E:Exception do begin bADOError:=true; bADOErrDescript:=E.Message; Result:=False; end; end; end; end; end.
unit Common; interface uses cxGridCustomTableView, cxGridDBTableView, cxGraphics, Graphics, cxRichEdit, Controls, SysUtils, ShellAPI, Windows; type RecordLights = record // структура для подсветки строки в таблице на insert/edit ErrorState: Boolean; ErrorControl: Boolean; RecordControlID: Integer; end; procedure ColorRecordByState(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; RL: RecordLights); procedure LogError(RichEdit: TcxRichEdit; Text: string); procedure LogWarning(RichEdit: TcxRichEdit; Text: string); procedure LogInfo(RichEdit: TcxRichEdit; Text: string); function GetMonthName(MonthNumber: Byte): string; function DelDir(dir: string): Boolean; implementation function DelDir(dir: string): Boolean; var fos: TSHFileOpStruct; begin ZeroMemory(@fos, SizeOf(fos)); with fos do begin wFunc := FO_DELETE; fFlags := FOF_SILENT or FOF_NOCONFIRMATION; pFrom := PChar(dir + #0); end; Result := (0 = ShFileOperation(fos)); end; procedure ColorRecordByState(Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; RL: RecordLights); begin if RL.ErrorControl then begin if AViewInfo.GridRecord.Values[TcxGridDBTableView(Sender).GetColumnByFieldName('ID').Index] = RL.RecordControlID then begin if not RL.ErrorState then begin if AViewInfo.Item.VisibleIndex <> TcxGridDBTableView(Sender).Controller.FocusedColumnIndex then begin ACanvas.Brush.Color := clLime; ACanvas.Font.Color := clBlack; end else begin if AViewInfo.GridRecord.Focused then begin ACanvas.Brush.Color := clYellow; ACanvas.Font.Color := clBlack; end else begin ACanvas.Brush.Color := clLime; ACanvas.Font.Color := clBlack; end; end; end else begin ACanvas.Brush.Color := clRed; ACanvas.Font.Color := clBlack; end; end; end; ACanvas.FillRect(AViewInfo.Bounds); end; procedure LogError(RichEdit: TcxRichEdit; Text: string); begin RichEdit.SelAttributes.Color := clRed; RichEdit.Lines.Add(Text); RichEdit.SetSelection(Length(RichEdit.Text),Length(Text)); RichEdit.SelAttributes.Color := clRed; end; procedure LogWarning(RichEdit: TcxRichEdit; Text: string); begin RichEdit.SelAttributes.Color := $008CFF; RichEdit.Lines.Add(Text); RichEdit.SetSelection(Length(RichEdit.Text),Length(Text)); RichEdit.SelAttributes.Color := $008CFF; end; procedure LogInfo(RichEdit: TcxRichEdit; Text: string); begin RichEdit.SelAttributes.Color := clBlue; RichEdit.Lines.Add(Text); RichEdit.SetSelection(Length(RichEdit.Text),Length(Text)); RichEdit.SelAttributes.Color := clBlue; end; function GetMonthName(MonthNumber: Byte): string; begin case MonthNumber of 1: Result := 'январь'; 2: Result := 'февраль'; 3: Result := 'март'; 4: Result := 'апрель'; 5: Result := 'май'; 6: Result := 'июнь'; 7: Result := 'июль'; 8: Result := 'август'; 9: Result := 'сентябрь'; 10: Result := 'октябрь'; 11: Result := 'ноябрь'; 12: Result := 'декабрь'; end; end; end.
unit UEvent; interface uses generics.collections, UChannel; type IEventMsg = Interface ['{662FBC7A-CA8A-41CC-A165-30E32D930843}'] function GetChannelCount: Integer; procedure AddChannel(AChannel: TChannel); function GetChannelByIndex(AIndex: Integer): TChannel; function GetDescription: string; end; TEventMsg = class(TInterfacedObject, IEventMsg) strict private FEventDescr: string; FChannels: TObjectList<TChannel>; private function GetDescription: string; public constructor Create(AChannel: TChannel); destructor Destroy; override; function GetChannelCount: Integer; procedure AddChannel(AChannel: TChannel); function GetChannelByIndex(AIndex: Integer): TChannel; property Descrition: string read GetDescription write FEventDescr; end; implementation { TEventMsg } procedure TEventMsg.AddChannel(AChannel: TChannel); begin FChannels.Add(AChannel); end; constructor TEventMsg.Create(AChannel: TChannel); begin FChannels := TObjectList<TChannel>.Create(False); FChannels.Add(AChannel); end; destructor TEventMsg.Destroy; begin FChannels.Free; inherited; end; function TEventMsg.GetChannelByIndex(AIndex: Integer): TChannel; begin Result := nil; if (AIndex >= 0) and (AIndex < GetChannelCount) then Result := FChannels[AIndex]; end; function TEventMsg.GetChannelCount: Integer; begin Result := FChannels.Count; end; function TEventMsg.GetDescription: string; begin Result := FEventDescr; end; end.
unit RRManagerWaitForArchiveFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerBaseGUI, RRManagerObjects, RRManagerBaseObjects, StdCtrls, ComCtrls, Gauges, RRManagerLoaderCommands; type // TfrmWaitForArchive = class(TFrame) TfrmWaitForArchive = class(TBaseFrame) gbxWaitForArchive: TGroupBox; ggStructure: TGauge; mmStructuresState: TRichEdit; lblStructure: TLabel; Label2: TLabel; prgStructure: TProgressBar; private { Private declarations } FArchivingStructures: TOldStructures; FStructureLoadAction: TStructureBaseLoadAction; function GetVersion: TOldVersion; procedure DoPercentProgress(Sender: TObject); procedure DoProgress(Sender: TObject); procedure DoGaugeProgress(Sender: TObject); protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; public { Public declarations } property Version: TOldVersion read GetVersion; procedure Save; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses RRManagerCommon, RRManagerEditCommands, Facade; {$R *.dfm} type TArchivingStructureLoadAction = class(TStructureBaseLoadAction) private FOnProgress: TNotifyEvent; FSubObjectsCountList: TList; FOnSubprogress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; property OnSubprogress: TNotifyEvent read FOnSubprogress write FOnSubprogress; function Execute(AFilter: string): boolean; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TArchivingStructurePreEditAction = class(TStructureBasePreEditAction) public constructor Create(AOwner: TComponent); override; end; TArchivingHorizonLoadAction = class(THorizonBaseLoadAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingSubstructureLoadAction = class(TSubstructureBaseLoadAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingLayerLoadAction = class(TLayerBaseLoadAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingBedLoadAction = class(TBedBaseLoadAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingBedLayerLoadAction = class(TBedLayerBaseLoadAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingPropertiesLoadAction = class(TVersionBaseLoadAction) public function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingVersionSaveAction = class(TVersionBaseSaveAction) public function Execute(ABaseObject: TBaseObject): boolean; override; end; TArchivingStructureSaveAction = class(TStructureBaseSaveAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingHorizonSaveAction = class(THorizonBaseSaveAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingSubstructureSaveAction = class(TSubstructureBaseSaveAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingLayerSaveAction = class(TLayerBaseSaveAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; TArchivingBedSaveAction = class(TBedBaseSaveAction) private FOnProgress: TNotifyEvent; public property OnProgress: TNotifyEvent read FOnProgress write FOnProgress; function Execute(ABaseObject: TBaseObject): boolean; override; constructor Create(AOwner: TComponent); override; end; const sSuccess: string = 'Успешно'; sUnSuccess: string = 'Неудачно'; procedure ReportStatus(AControl: TRichEdit; S: string; State: boolean; AColor: TColor); var iLen: integer; sState: string; StateColor: TColor; StateStyles: TFontStyles; begin iLen := Length(AControl.Text); if State then begin sState := '[' + DateTimeToStr(Now) + ']' + S + '...' + sSuccess; StateColor := AColor; AControl.Lines.AddObject(sState, TObject(1)); StateStyles := []; end else begin sState := '[' + DateTimeToStr(Now) + ']' +S + '...' + sUnSuccess; StateColor := AColor; AControl.Lines.AddObject(sState, nil); StateStyles := [fsBold]; end; AControl.SelStart := iLen; AControl.SelLength := Length(sState); AControl.SelAttributes.Color := StateColor; AControl.SelAttributes.Style := StateStyles; end; { TfrmWaitForArchive } procedure TfrmWaitForArchive.ClearControls; begin FArchivingStructures.Clear; prgStructure.Min := 0; prgStructure.Max := 200; prgStructure.Position := 0; ggStructure.MinValue := 0; ggStructure.MaxValue := 100; ggStructure.Progress := 0; // mmStructuresState.Clear; end; constructor TfrmWaitForArchive.Create(AOwner: TComponent); begin inherited; NeedCopyState := true; FArchivingStructures := TOldStructures.Create(nil); FStructureLoadAction := TArchivingStructureLoadAction.Create(Self); FStructureLoadAction.LastCollection := FArchivingStructures; end; destructor TfrmWaitForArchive.Destroy; begin FArchivingStructures.Free; inherited; end; procedure TfrmWaitForArchive.DoGaugeProgress(Sender: TObject); begin ggStructure.AddProgress(1); if ggStructure.Progress = ggStructure.MaxValue then ggStructure.Progress := 0; end; procedure TfrmWaitForArchive.DoPercentProgress(Sender: TObject); begin prgStructure.StepBy(Round((prgStructure.Max - prgStructure.Min)/FArchivingStructures.Count)); Update; end; procedure TfrmWaitForArchive.DoProgress(Sender: TObject); begin prgStructure.StepIt; Update; end; procedure TfrmWaitForArchive.FillControls(ABaseObject: TBaseObject); begin inherited; end; procedure TfrmWaitForArchive.FillParentControls; begin inherited; end; function TfrmWaitForArchive.GetVersion: TOldVersion; begin Result := EditingObject as TOldVersion; end; procedure TfrmWaitForArchive.Save; var i: integer; actn: TArchivingStructureSaveAction; actnLoad: TArchivingStructureLoadAction; actnSaveVersion: TArchivingVersionSaveAction; begin inherited; mmStructuresState.Clear; if not Assigned(EditingObject) then // если что берем последнюю добавленную версию FEditingObject := (TMainFacade.GetInstance as TMainFacade).AllVersions.Items[(TMainFacade.GetInstance as TMainFacade).AllVersions.Count - 1]; lblStructure.Caption := 'Сохраняем версию'; // сохраняем версию actnSaveVersion := TArchivingVersionSaveAction.Create(Self); actnSaveVersion.Execute(FEditingObject); actnSaveVersion.Free; lblStructure.Caption := 'Загружаем структуры для сохранения'; // грузим структуры prgStructure.Min := 0; prgStructure.Max := 1000; ggStructure.MinValue := 0; ggStructure.MaxValue := 4; actnLoad := (FStructureLoadAction as TArchivingStructureLoadAction); actnLoad.OnProgress := DoPercentProgress; actnLoad.OnSubprogress := DoGaugeProgress; FStructureLoadAction.LastCollection := FArchivingStructures; if FStructureLoadAction.Execute('Structure_ID > 0 and Version_ID = ' + IntToStr((TMainFacade.GetInstance as TMainFacade).ActiveVersion.ID)) then begin lblStructure.Caption := 'Начинаем сохранение структур'; // делаем активным новй архив //(TMainFacade.GetInstance as TMainFacade).ActiveVersion := Version; // параметризуем прогресс prgStructure.Min := 0; prgStructure.Max := FArchivingStructures.Count; // проходим циклом по всем загруженным структурам actn := TArchivingStructureSaveAction.Create(Self); actn.OnProgress := DoGaugeProgress; for i := 0 to FArchivingStructures.Count - 1 do // for i := 0 to 25 do begin ggStructure.MinValue := 0; ggStructure.MaxValue := Integer(actnLoad.FSubObjectsCountList.Items[i]); ggStructure.Progress := 0; lblStructure.Caption := 'Сохраняем структуру ' + FArchivingStructures.Items[i].List(AllOpts.Current.ListOption, false, false); DoProgress(Self); actn.Execute(FArchivingStructures.Items[i]); end; actn.Free; ggStructure.Progress := ggStructure.MaxValue; lblStructure.Caption := 'Сохранение структур завершено. Повторное нажатие кнопки "Готово" приведёт к пересохранению структур в эту же версию архива. Если хотите новую версию - закончите этот сеанс архивирования (кнопка "Закрыть") и начните новый.'; end; end; { TArchivingStructureLoadAction } constructor TArchivingStructureLoadAction.Create(AOwner: TComponent); begin inherited; Caption := 'Загрузить структуры'; FSubObjectsCountList := TList.Create; DestroyCollection := false; end; destructor TArchivingStructureLoadAction.Destroy; begin FSubObjectsCountList.Free; inherited; end; function TArchivingStructureLoadAction.Execute(AFilter: string): boolean; var i: integer; actn: TArchivingHorizonLoadAction; actnPreEdit: TStructureBasePreEditAction; actnProperties: TArchivingPropertiesLoadAction; actnDrilledWells: TDrilledStructureWellsBaseLoadAction; actnHistory: TStructureHistoryBaseLoadAction; actnBed: TArchivingBedLoadAction; s: TOLdStructure; LastAction: TBaseAction; LastUsedObject: TBaseObject; begin Result := true; try LastAction := Self; LastUsedObject := nil; Result := inherited Execute(AFilter); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Caption, true, clGray); actn := TArchivingHorizonLoadAction.Create(Owner); actnPreEdit := TArchivingStructurePreEditAction.Create(Owner); actnProperties := TArchivingPropertiesLoadAction.Create(Owner); actnDrilledWells := TDrilledStructureWellsBaseLoadAction.Create(Owner); actnHistory := TStructureHistoryBaseLoadAction.Create(Owner); actnBed := TArchivingBedLoadAction.Create(Owner); for i := 0 to LastCollection.Count - 1 do // for i := 0 to 25 do begin s := LastCollection.Items[i] as TOLdStructure; LastAction := actnPreEdit; LastUsedObject := S; actnPreEdit.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); if Assigned(FOnSubprogress) then FOnSubprogress(Self); LastAction := actn; LastUsedObject := S; actn.LastCollection := s.Horizons; actn.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); if Assigned(FOnSubprogress) then FOnSubprogress(Self); LastAction := actnProperties; LastUsedObject := S; actnProperties.LastCollection := s.Versions; actnProperties.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); if Assigned(FOnSubprogress) then FOnSubprogress(Self); if s is TOldDrilledStructure then begin LastAction := actnDrilledWells; LastUsedObject := S; actnDrilledWells.LastCollection := (s as TOldDrilledStructure).Wells; actnDrilledWells.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); end else if s is TOldField then begin LastAction := actnBed; LastUsedObject := S; actnBed.LastCollection := (s as TOldField).Beds; actnBed.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); end; LastAction := actnHistory; LastUsedObject := S; actnHistory.LastCollection := s.History; actnHistory.Execute(s); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGray); if Assigned(FOnSubprogress) then FOnSubprogress(Self); if Assigned(FOnProgress) then FOnProgress(Self); FSubObjectsCountList.Add(Pointer(s.SubObjectsCount)); end; actnPreEdit.Free; actn.Free; actnProperties.Free; actnDrilledWells.Free; actnBed.Free; except Result := false; if Assigned(LastUsedObject) then ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption + '(' + LastUsedObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed) else ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, LastAction.Caption, false, clRed) end; end; { TArchivingPropertiesByVersionLoadAction } constructor TArchivingPropertiesLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; Caption := 'Загрузить свойства структуры'; end; function TArchivingPropertiesLoadAction.Execute( ABaseObject: TBaseObject): boolean; var v: TOldAccountVersion; i: integer; actnParams, actnResources, actnReserves, actnDocs: TBaseAction; begin Result := inherited Execute(ABaseObject); actnParams := TParamByVersionBaseLoadAction.Create(nil); actnResources := TResourceByVersionBaseLoadAction.Create(nil); actnReserves := TReserveByVersionBaseLoadAction.Create(nil); actnDocs := TDocumentByVersionBaseLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin v := LastCollection.Items[i] as TOldAccountVersion; actnParams.LastCollection := v.Parameters; actnParams.Execute(v); actnDocs.LastCollection := v.Documents; actnDocs.Execute(v); if ABaseObject is TOldLayer then begin actnResources.LastCollection := v.Resources; actnResources.Execute(v); actnReserves.LastCollection := v.Reserves; actnReserves.Execute(v); end; end; actnParams.Free; actnResources.Free; actnReserves.Free; actnDocs.Free; end; { TArchivingHorizonLoadAction } constructor TArchivingHorizonLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; Caption := 'Загрузить состав структуры' end; function TArchivingHorizonLoadAction.Execute( ABaseObject: TBaseObject): boolean; var i: integer; actn: TArchivingSubstructureLoadAction; actnProperties: TArchivingPropertiesLoadAction; h: TOldHorizon; begin Result := inherited Execute(ABaseObject); actn := TArchivingSubstructureLoadAction.Create(nil); actnProperties := TArchivingPropertiesLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin h := LastCollection.Items[i] as TOldHorizon; actn.LastCollection := h.Substructures; actn.Execute(h); actnProperties.LastCollection := h.Versions; actnProperties.Execute(h); if Assigned(FOnProgress) then FOnProgress(Self); end; actn.Free; actnProperties.Free; end; { TArchivingSubstructureLoadAction } constructor TArchivingSubstructureLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; end; function TArchivingSubstructureLoadAction.Execute( ABaseObject: TBaseObject): boolean; var i: integer; actn: TArchivingLayerLoadAction; actnProperties: TArchivingPropertiesLoadAction; s: TOldSubstructure; begin Result := inherited Execute(ABaseObject); actn := TArchivingLayerLoadAction.Create(nil); actnProperties := TArchivingPropertiesLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin s := LastCollection.Items[i] as TOldSubstructure; actn.LastCollection := s.Layers; actn.Execute(s); actnProperties.LastCollection := s.Versions; actnProperties.Execute(s); if Assigned(FOnProgress) then FOnProgress(Self); end; actn.Free; actnProperties.Free; end; { TArchivingLayerLoadAction } constructor TArchivingLayerLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; end; function TArchivingLayerLoadAction.Execute( ABaseObject: TBaseObject): boolean; var i: integer; actnProperties: TArchivingPropertiesLoadAction; l: TOldLayer; begin Result := inherited Execute(ABaseObject); actnProperties := TArchivingPropertiesLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin l := LastCollection.Items[i] as TOldLayer; actnProperties.LastCollection := l.Versions; actnProperties.Execute(l); if Assigned(FOnProgress) then FOnProgress(Self); end; actnProperties.Free; end; { TArchivingBedLoadAction } constructor TArchivingBedLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; Caption := 'Загрузить состав месторождения'; end; function TArchivingBedLoadAction.Execute( ABaseObject: TBaseObject): boolean; var i: integer; actn: TArchivingBedLayerLoadAction; actnProperties: TArchivingPropertiesLoadAction; b: TOldBed; begin Result := inherited Execute(ABaseObject); actn := TArchivingBedLayerLoadAction.Create(nil); actnProperties := TArchivingPropertiesLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin b := LastCollection.Items[i] as TOldBed; actn.LastCollection := b.Layers; actn.Execute(b); actnProperties.LastCollection := b.Versions; actnProperties.Execute(b); if Assigned(FOnProgress) then FOnProgress(Self); end; actn.Free; actnProperties.Free; end; { TArchivingBedLayerLoadAction } constructor TArchivingBedLayerLoadAction.Create(AOwner: TComponent); begin inherited; DestroyCollection := false; end; { TArchivingStructureEditAction } constructor TArchivingStructureSaveAction.Create(AOwner: TComponent); begin inherited; Caption := 'Сохранить структуру'; end; function TArchivingStructureSaveAction.Execute( ABaseObject: TBaseObject): boolean; var s: TOLdStructure; f: TOldField; i: integer; actn: TArchivingHorizonSaveAction; actnBed: TArchivingBedSaveAction; begin try Result := inherited Execute(ABaseObject); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGreen); actn := TArchivingHorizonSaveAction.Create(Owner); actn.OnProgress := OnProgress; if Result then begin s := ABaseObject as TOLdStructure; for i := 0 to s.Horizons.Count - 1 do begin actn.Execute(s.Horizons.Items[i]); if Assigned(FOnProgress) then FOnProgress(Self); end; if ABaseObject is TOldField then begin actnBed := TArchivingBedSaveAction.Create(Owner); actnBed.OnProgress := OnProgress; f := s as TOldField; for i := 0 to f.Beds.Count - 1 do begin actnBed.Execute(f.Beds.Items[i]); if Assigned(FOnProgress) then FOnProgress(Self); end; actnBed.Free; end; end; actn.Free; except ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed); end; end; function TArchivingBedLayerLoadAction.Execute( ABaseObject: TBaseObject): boolean; var i: integer; actnProperties: TArchivingPropertiesLoadAction; l: TOldLayer; begin Result := inherited Execute(ABaseObject); actnProperties := TArchivingPropertiesLoadAction.Create(nil); for i := 0 to LastCollection.Count - 1 do begin l := LastCollection.Items[i] as TOldLayer; actnProperties.LastCollection := l.Versions; actnProperties.Execute(l); if Assigned(FOnProgress) then FOnProgress(Self); end; actnProperties.Free; end; { TArchivingHorizonSaveAction } constructor TArchivingHorizonSaveAction.Create(AOwner: TComponent); begin inherited; Caption := 'Сохранить горизонт'; end; function TArchivingHorizonSaveAction.Execute( ABaseObject: TBaseObject): boolean; var h: TOldHorizon; i: integer; actn: TArchivingSubstructureSaveAction; begin try Result := inherited Execute(ABaseObject); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGreen); actn := TArchivingSubstructureSaveAction.Create(Owner); actn.FOnProgress := OnProgress; if Result then begin h := ABaseObject as TOldHorizon; for i := 0 to h.Substructures.Count - 1 do begin actn.Execute(h.Substructures.Items[i]); if Assigned(FOnProgress) then FOnProgress(Self); end; end; actn.Free; except ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed); end; end; { TArchivingSubstructureSaveAction } constructor TArchivingSubstructureSaveAction.Create(AOwner: TComponent); begin inherited; Caption := 'Сохранить подструктуру'; end; function TArchivingSubstructureSaveAction.Execute( ABaseObject: TBaseObject): boolean; var s: TOldSubstructure; i: integer; actn: TArchivingLayerSaveAction; begin try Result := inherited Execute(ABaseObject); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGreen); actn := TArchivingLayerSaveAction.Create(Owner); actn.OnProgress := FOnProgress; if Result then begin s := ABaseObject as TOldSubstructure; for i := 0 to s.Layers.Count - 1 do begin actn.Execute(s.Layers.Items[i]); if Assigned(FOnProgress) then FOnProgress(Self); end; end; actn.Free; except ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed); end; end; { TArchivingLayerSaveAction } constructor TArchivingLayerSaveAction.Create(AOwner: TComponent); begin inherited; Caption := 'Сохранить продуктивный пласт'; end; function TArchivingLayerSaveAction.Execute( ABaseObject: TBaseObject): boolean; begin try Result := inherited Execute(ABaseObject); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGreen); except ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed); end; end; { TArchivingBedSaveAction } constructor TArchivingBedSaveAction.Create(AOwner: TComponent); begin inherited; Caption := 'Сохранить залежь'; end; function TArchivingBedSaveAction.Execute( ABaseObject: TBaseObject): boolean; var b: TOldBed; i: integer; actn: TArchivingBedSaveAction; begin try Result := inherited Execute(ABaseObject); ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', true, clGreen); actn := TArchivingBedSaveAction.Create(Owner); actn.OnProgress := FOnProgress; if Result then begin b := ABaseObject as TOldBed; for i := 0 to b.Layers.Count - 1 do begin actn.Execute(b.Layers.Items[i]); if Assigned(FOnProgress) then FOnProgress(Self); end; end; actn.Free; except ReportStatus((Owner as TfrmWaitForArchive).mmStructuresState, Self.Caption + '(' + ABaseObject.List(AllOpts.Current.ListOption, true, true) + ')', false, clRed); end; end; { TArchivingVersionSaveAction } function TArchivingVersionSaveAction.Execute( ABaseObject: TBaseObject): boolean; begin Result := inherited Execute(ABaseObject); end; { TArchivingStructurePreEditAction } constructor TArchivingStructurePreEditAction.Create(AOwner: TComponent); begin inherited; Caption := 'Загрузить свойства структуры, определяемые видом фонда'; end; end.
unit Marvin.Console.Utils; interface uses System.Classes, System.Generics.Collections, System.Generics.Defaults; type { controle de cores } TConsoleColor = (ccBlack = 0, ccBlueDark = 1, ccGreenDark = 2, ccCyanDark = 3, ccRedDark = 4, ccMagentaDark = 5, ccYellowDark = 6, ccGray = 7, ccGrayDark = 8, ccBlue = 9, ccGreen = 10, ccCyan = 11, ccRed = 12, ccMagenta = 13, ccYellow = 14, ccWhite = 15); { controle de cor } TDefaultColor = class(TPersistent) strict private FName: string; FForegroundColor: TConsoleColor; FBackgroundColor: TConsoleColor; public procedure Assign(ASource: TPersistent); override; procedure Clear; property Name: string read FName write FName; property ForegroundColor: TConsoleColor read FForegroundColor write FForegroundColor; property BackgroundColor: TConsoleColor read FBackgroundColor write FBackgroundColor; end; { busca na ObjectList } TDefaultColorComparer = class(TComparer<TDefaultColor>) public function Compare(const Left, Right: TDefaultColor): Integer; override; end; { funções de ajuda } TConsoleUtils = class(TObject) public const C_GERAL: string = 'geral'; const C_GERAL_TEXTO: string = 'geral_texto'; const C_CABECALHO_TEXTO: string = 'cabecalho_texto'; const C_TEXTO: string = 'texto'; const C_TEXTO_ENFASE: string = 'texto_enfase'; const C_TITULO_TABELA: string = 'titulo_tabela'; const C_MENSAGEM_ERRO: string = 'mensagem_erro'; public class var FCores: TObjectList<TDefaultColor>; class procedure ClearScreen; class procedure SetConsoleColor(ABackgroundColor: TConsoleColor; AForegroundColor: TConsoleColor); overload; class procedure SetConsoleColor(ADefaultColorName: string); overload; class procedure WriteWithColor(AText: string; ABackgroundColor: TConsoleColor; AForegroundColor: TConsoleColor); overload; class procedure WritelnWithColor(AText: string; ABackgroundColor: TConsoleColor; AForegroundColor: TConsoleColor); overload; class procedure WriteWithColor(AText: string; ADefaultColorName: string); overload; class procedure WritelnWithColor(AText: string; ADefaultColorName: string); overload; class procedure SetDefaultColor(ADefaultColorName: string); end; { tipo para configurar o estado da página } TPaginaStatus = (psNone, psNovo, psAlterar); implementation uses Winapi.Windows, System.SysUtils; { TConsoleUtils } class procedure TConsoleUtils.ClearScreen; var LSdtOut: THandle; LConsoleBuffer: TConsoleScreenBufferInfo; LConsoleSize: DWORD; LNumWritten: DWORD; LOrigin: TCoord; begin { informa a cor padrão } Self.SetConsoleColor(TConsoleUtils.C_GERAL); {$WARNINGS OFF} LSdtOut := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(LSdtOut <> INVALID_HANDLE_VALUE); Win32Check(GetConsoleScreenBufferInfo(LSdtOut, LConsoleBuffer)); LConsoleSize := LConsoleBuffer.dwSize.X * LConsoleBuffer.dwSize.Y; LOrigin.X := 0; LOrigin.Y := 0; Win32Check(FillConsoleOutputCharacter(LSdtOut, ' ', LConsoleSize, LOrigin, LNumWritten)); Win32Check(FillConsoleOutputAttribute(LSdtOut, LConsoleBuffer.wAttributes, LConsoleSize, LOrigin, LNumWritten)); Win32Check(SetConsoleCursorPosition(LSdtOut, LOrigin)); {$WARNINGS ON} end; class procedure TConsoleUtils.SetConsoleColor(ABackgroundColor, AForegroundColor: TConsoleColor); var LColor: Word; begin { calcula a cor } LColor := 16 * Word(ABackgroundColor) + Word(AForegroundColor); { configura a cor } SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), LColor); end; class procedure TConsoleUtils.SetConsoleColor(ADefaultColorName: string); begin { configura a cor } Self.SetDefaultColor(ADefaultColorName); end; class procedure TConsoleUtils.SetDefaultColor(ADefaultColorName: string); var LSearchDefaultColor, LDefaultColor: TDefaultColor; LPosition: Integer; begin LSearchDefaultColor := TDefaultColor.Create; try LSearchDefaultColor.Name := ADefaultColorName; LPosition := FCores.IndexOf(LSearchDefaultColor); { ajusta a cor padrão } TConsoleUtils.SetConsoleColor(ccBlack, ccGray); if LPosition > -1 then begin LDefaultColor := FCores.Items[LPosition]; { ajusta a cor } TConsoleUtils.SetConsoleColor(LDefaultColor.BackgroundColor, LDefaultColor.ForegroundColor); end; finally LSearchDefaultColor.Free; end; end; class procedure TConsoleUtils.WritelnWithColor(AText: string; ABackgroundColor, AForegroundColor: TConsoleColor); begin { ajusta a cor } TConsoleUtils.SetConsoleColor(ABackgroundColor, AForegroundColor); { imprime } Writeln(AText); end; class procedure TConsoleUtils.WriteWithColor(AText: string; ABackgroundColor, AForegroundColor: TConsoleColor); begin { ajusta a cor } TConsoleUtils.SetConsoleColor(ABackgroundColor, AForegroundColor); { imprime } Write(AText); end; class procedure TConsoleUtils.WritelnWithColor(AText, ADefaultColorName: string); begin { configura a cor } Self.SetDefaultColor(ADefaultColorName); { imprime } Writeln(AText); end; class procedure TConsoleUtils.WriteWithColor(AText, ADefaultColorName: string); begin { configura a cor } Self.SetDefaultColor(ADefaultColorName); { imprime } Write(AText); end; { TDefaultColor } procedure TDefaultColor.Assign(ASource: TPersistent); var LDefaultColor: TDefaultColor; begin inherited; LDefaultColor := ASource as TDefaultColor; { recupera os dados } FName := LDefaultColor.Name; FForegroundColor := LDefaultColor.ForegroundColor; FBackgroundColor := LDefaultColor.BackgroundColor; end; procedure TDefaultColor.Clear; begin FName := EmptyStr; FForegroundColor := ccWhite; FBackgroundColor := ccBlack; end; { TDefaultColorComparer } function TDefaultColorComparer.Compare(const Left, Right: TDefaultColor): Integer; begin Result := -1; { verifica se os métodos são os mesmos } if (TDefaultColor(Left).Name = TDefaultColor(Right).Name) then begin Result := 0; end; end; end.
unit uJxdUdpHashServer; interface uses Windows, SysUtils, WinSock2, uJxdDataStream, uJxdUdpBasic, uJxdUdpsynchroBasic, uJxdServerCommon, uJxdUdpDefine, uJxdHashTableManage; type TxdUdpHashServer = class(TxdServerCommon) public constructor Create; override; protected function DoBeforOpenUDP: Boolean; override; procedure DoAfterCloseUDP; override; procedure DoHandleCmd(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Integer; const AIsSynchroCmd: Boolean; const ASynchroID: Word); override; private FHashManage: TxdHashTableManage; procedure SetHashManage(const Value: TxdHashTableManage); public property HashManage: TxdHashTableManage read FHashManage write SetHashManage; end; implementation { TxdUdpHashServer } constructor TxdUdpHashServer.Create; begin inherited; FServerStyle := srvHash; //设置服务器类型,不可改变 FSelfID := CtHashServerID; FOnlineServerIP := inet_addr('192.168.1.100'); FOnlineServerPort := 8989; end; procedure TxdUdpHashServer.DoAfterCloseUDP; begin inherited; FHashManage.Active := False; end; function TxdUdpHashServer.DoBeforOpenUDP: Boolean; begin if not Assigned(FHashManage) then raise Exception.Create( 'must set the hash manage' ); Result := inherited DoBeforOpenUDP; FHashManage.Active := Result; end; procedure TxdUdpHashServer.DoHandleCmd(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Integer; const AIsSynchroCmd: Boolean; const ASynchroID: Word); var pCmd: PCmdHead; begin pCmd := PCmdHead(ABuffer); case pCmd^.FCmdID of CtCmd_UpdateFileHashTable: FHashManage.DoHandleCmd_UpdateFileHashTable( AIP, APort, ABuffer, ABufLen, AIsSynchroCmd, ASynchroID ); CtCmd_SearchFileUser: FHashManage.DoHandleCmd_SearchFileUser( AIP, APort, ABuffer, ABufLen, AIsSynchroCmd, ASynchroID ); CtCmd_ClientShutDown: FHashManage.DoHandleCmd_ClientShutdown( AIP, APort, ABuffer, ABufLen, AIsSynchroCmd, ASynchroID ); end; end; procedure TxdUdpHashServer.SetHashManage(const Value: TxdHashTableManage); begin if not Active then FHashManage := Value; end; end.
unit InfraCommon; interface {$I InfraCommon.Inc} uses {$IFDEF USE_GXDEBUG}DBugIntf, {$ENDIF} InfraBase, InfraCommonIntf; type TBaseElement = class(TInfraBaseObject, IInterface, IBaseElement, IInfraReferenceKeeper, IInfraInstance) private FInjectedList: IInjectedList; protected function GetInjectedList: IInjectedList; function GetInstance: TObject; procedure InfraInitInstance; virtual; function Inject(const pID: TGUID; const pItem: IInterface): IInjectedItem; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; property InjectedList: IInjectedList read GetInjectedList; {$IFDEF SEE_REFCOUNT} function GetRefCount: integer; {$ENDIF} {$IFDEF TEST_REFCOUNT} function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; {$ENDIF} public procedure SetReference(var Ref: IInterface; const Value: IInterface); procedure AfterConstruction; override; procedure BeforeDestruction; override; destructor Destroy; override; end; TBaseElementClass = class of TBaseElement; TElement = class(TBaseElement, IElement, IInfraPublisher, ISubscriber, IInfraFilter) private FPublisher: IInfraPublisher; FTypeInfo: IClassInfo; protected function Apply(const Event: IInfraEvent): Boolean; virtual; function GetPublisher: IInfraPublisher; function GetTypeInfo: IClassInfo; procedure InitTypeInfo; virtual; procedure Inform(const Event: IInfraEvent); virtual; procedure SetTypeInfo(const Value: IClassInfo); property TypeInfo: IClassInfo read GetTypeInfo write SetTypeInfo; public procedure InfraInitInstance; override; destructor Destroy; override; property Publisher: IInfraPublisher read GetPublisher implements IInfraPublisher; end; TElementClass = Class of TElement; {$IFDEF INFRA_LEAKOBJECTS} var _InfraObjectsInfras: TObjectList; function InfraLeakObjects: TObjectList; {$ENDIF} implementation uses SysUtils, List_InjectedItem, InfraNotify, InfraInjected; {$IFDEF INFRA_LEAKOBJECTS} function InfraLeakObjects: TObjectList; begin if not Assigned(_InfraObjectsInfras) then begin _InfraObjectsInfras := TObjectList.Create; _InfraObjectsInfras.OwnsObjects := False; end; Result := _InfraObjectsInfras; end; {$ENDIF} { TBaseElement } procedure TBaseElement.AfterConstruction; begin {$IFDEF INFRA_LEAKOBJECTS} InfraLeakObjects.Add(Self); {$ENDIF} // Obs: Explicity change the refcount to make sure that cast inside the // construction process dont trigger refcouting which is // still zero to avoid the object being destroyied FRefCount := Low(Integer); InfraInitInstance; FRefCount := 0; end; procedure TBaseElement.InfraInitInstance; begin // nothing. inplemented on descedents. end; procedure TBaseElement.BeforeDestruction; begin inherited; // Obs: See coments on AfterConstruction FRefCount := Low(Integer); end; destructor TBaseElement.Destroy; begin {$IFDEF INFRA_CLASSNAMEDESTROYED} SendDebug('<<< '+Self.ClassName); {$ENDIF} {$IFDEF INFRA_LEAKOBJECTS} if Assigned(_InfraObjectsInfras) and (_InfraObjectsInfras.Count <> 0) then _InfraObjectsInfras.Remove(Self); {$ENDIF} ReferenceService.NotifyDestruction(Self); inherited; end; {$IFDEF TEST_REFCOUNT} function TBaseElement._AddRef: Integer; begin Result := inherited _AddRef; SendDebug(Format('ADDREF: %s.RefCount = %d', [ClassName, RefCount])); end; function TBaseElement._Release: Integer; begin SendDebug(Format('RELEASE: %s.RefCount = %d', [ClassName, RefCount-1])); Result := inherited _Release; end; {$ENDIF} function TBaseElement.GetInjectedList: IInjectedList; begin if not Assigned(FInjectedList) then FInjectedList := TInjectedList.Create(Self); Result := FInjectedList; end; { Qualquer objeto infra aceita interfaces injetadas (sejam anotações ou não) Quando o programa verifica se o objeto atual suporta uma interface ou faz-se cast com "As" o delphi chama este método. Aqui primeiro verificamos se existe uma injeção da interface passada, se houver, testamos ainda se ela está instanciada e a retorna. Se nao está instanciada devemos verificar se é uma anotação por instancia e então instanciamos a mesma e a retornamos. Caso contrário chamamos este mesmo método no pai. } function TBaseElement.QueryInterface(const IID: TGUID; out Obj): HResult; var i: integer; begin if not Assigned(FInjectedList) then Result := inherited Queryinterface(IID, Obj) else begin i := FInjectedList.IndexByGUID(IID); if (i <> -1) then begin if Assigned(FInjectedList.Item[i].InjectedInterface) then begin IInterface(Obj) := FInjectedList.Item[i].InjectedInterface; Result := 0; end else Result := inherited Queryinterface(IID, Obj); end else Result := inherited Queryinterface(IID, Obj); end; end; function TBaseElement.GetInstance: TObject; begin Result := Self; end; procedure TBaseElement.SetReference(var Ref: IInterface; const Value: IInterface); begin ReferenceService.SetReference(Self, Ref, Value); end; {$IFDEF SEE_REFCOUNT} function TBaseElement.GetRefCount: integer; begin Result := FRefCount; end; {$ENDIF} function TBaseElement.Inject(const pID: TGUID; const pItem: IInterface): IInjectedItem; var Index: integer; vItem: IInterface; begin Supports(pItem, pId, vItem); Index := InjectedList.Add(pID, vItem); Result := FInjectedList.Item[Index]; Result.IsAnnotation := False; end; { TElement } procedure TElement.InfraInitInstance; begin inherited; InitTypeInfo; end; function TElement.Apply(const Event: IInfraEvent): Boolean; begin Result := False; end; destructor TElement.Destroy; begin EventService.UnSubscribeAll(Self as ISubscriber); inherited; end; function TElement.GetTypeInfo: IClassInfo; begin Result := FTypeInfo; end; // Im not sure about this, but probably we need that function TElement.GetPublisher: IInfraPublisher; begin if not Assigned(FPublisher) then FPublisher := TInfraPublisher.Create(Self); Result := FPublisher; end; procedure TElement.Inform(const Event: IInfraEvent); begin // nothing. inplemented on descedents. end; procedure TElement.InitTypeInfo; begin FTypeInfo := TypeService.GetType(TInfraBaseObjectClass(Self.ClassType)); end; procedure TElement.SetTypeInfo(const Value: IClassInfo); begin if Value <> FTypeInfo then FTypeInfo := Value; end; initialization finalization {$IFDEF INFRA_LEAKOBJECTS} if Assigned(_InfraObjectsInfras) then FreeAndNil(_InfraObjectsInfras); {$ENDIF} end.
unit Mail; interface uses Windows, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, IniFiles, IdSMTP, IdMessage, ComCtrls, ToolCtrlsEh, DBGridEhToolCtrls, GridsEh, DBAxisGridsEh, DBGridEh, DBGridEhGrouping; type TMailForm = class(TForm) PBSend: TProgressBar; Panel1: TPanel; lblMemo: TLabel; BtnSend: TBitBtn; LEUser: TLabeledEdit; LEPass: TLabeledEdit; LEReceive: TLabeledEdit; LETitle: TLabeledEdit; MemoBody: TMemo; TSend: TTimer; BtnSave: TBitBtn; TMail: TTimer; Label1: TLabel; LEHost: TComboBox; GBSendOption: TGroupBox; RBEveryDay: TRadioButton; DTPSend: TDateTimePicker; RBEveryHour: TRadioButton; CBAutoSend: TCheckBox; CBReportType: TComboBox; lblReportType: TLabel; DBGridEhMail: TDBGridEh; procedure BtnSendClick(Sender: TObject); procedure TSendTimer(Sender: TObject); procedure BtnSaveClick(Sender: TObject); procedure TMailTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure loadDBGrid(); public { Public declarations } function sendMail(host, username, password, receiver, title, body, attachment: string): Boolean; end; var MailForm: TMailForm; implementation uses CommonUtil, DBGridEhImpExp, OtherUtil, QueryDM, Main; {$R *.dfm} function TMailForm.sendMail(host, username, password, receiver, title, body, attachment: string): Boolean; var smtp: TIdSMTP; msgsend: TIdMessage; begin smtp := TIdSMTP.Create(nil); msgsend := TIdMessage.Create(nil); try smtp.AuthenticationType := atLogin; smtp.Host := host; smtp.Username := username; //用户名 smtp.Password := password; msgsend.Recipients.EMailAddresses := receiver; //收 件人地址(多于一个的话用逗号隔开) msgsend.From.Text := username; //自己的邮箱地址 msgsend.Subject := title; //邮件标题 msgsend.Body.Text := body; //邮件内容 //添加附件 msgsend.MessageParts.Clear; if FileExists(attachment) then TIdAttachment.Create(msgsend.MessageParts, attachment); try smtp.Connect(); try smtp.Authenticate; smtp.Send(msgsend); Result := True; except on E: Exception do begin ShowMessage(E.Message); Result := False; end; end; except Result := False; end; finally smtp.Disconnect; msgsend.Free; smtp.Free; end; end; procedure TMailForm.BtnSendClick(Sender: TObject); var ret: Integer; attatchment: string; ExpClass: TDBGridEhExportClass; begin TSend.Enabled := True; try case CBReportType.ItemIndex of 0: TMailUtil.showTodayRecord(); 1: TMailUtil.showToWeekRecord(); 2: TMailUtil.showToMonthRecord(); 3: TMailUtil.showToYearRecord(); end; attatchment := ExtractFilePath(ParamStr(0)) + 'dataReport.xls'; ExpClass := TDBGridEhExportAsXLS; if ExpClass <> nil then begin SaveDBGridEhToExportFile(ExpClass, DBGridEhMail, attatchment, True); end; if sendMail(LEHost.Text, LEUser.Text, LEPass.Text, LEReceive.Text, LETitle.Text, MemoBody.Text, attatchment) then MessageBox(Handle, '邮件发送成功', '提示', MB_OK + MB_ICONINFORMATION + MB_DEFBUTTON2 + MB_TOPMOST) else MessageBox(Handle, '邮件发送失败,请检查用户名,密码及网络连接', '提示', MB_OK + MB_ICONSTOP + MB_DEFBUTTON2 + MB_TOPMOST); if FileExists(attatchment) then DeleteFile(attatchment); finally TSend.Enabled := False; PBSend.Position := 0; end; end; procedure TMailForm.TSendTimer(Sender: TObject); begin PBSend.StepIt; end; procedure TMailForm.BtnSaveClick(Sender: TObject); var myini: TIniFile; begin myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'setup.ini'); try myini.WriteString('mail', 'host', LEHost.Text); myini.WriteString('mail', 'username', LEUser.Text); myini.WriteString('mail', 'pass', TCommonUtil.Base64(LEPass.Text)); myini.WriteString('mail', 'receiver', LEReceive.Text); myini.WriteString('mail', 'title', LETitle.Text); myini.WriteString('mail', 'body', MemoBody.Text); myini.WriteInteger('mail', 'report_type', CBReportType.ItemIndex); myini.WriteBool('mail', 'auto_send', CBAutoSend.Checked); myini.WriteBool('mail', 'everyday', RBEveryDay.Checked); myini.WriteTime('mail', 'sendTime', DTPSend.Time); myini.WriteBool('mail', 'everyhour', RBEveryHour.Checked); Application.MessageBox('参数保存成功', '提示', MB_OK + MB_ICONINFORMATION + MB_TOPMOST); finally myini.Free; end; end; procedure TMailForm.TMailTimer(Sender: TObject); var ExpClass: TDBGridEhExportClass; fileName: string; begin if RBEveryDay.Checked then begin if FormatDateTime('hhnnss', Time) = FormatDateTime('hhnnss', DTPSend.Time) then begin case CBReportType.ItemIndex of 0: TMailUtil.showTodayRecord(); 1: TMailUtil.showToWeekRecord(); 2: TMailUtil.showToMonthRecord(); 3: TMailUtil.showToYearRecord(); end; try fileName := ExtractFilePath(ParamStr(0)) + 'dataReport.xls'; ExpClass := TDBGridEhExportAsXLS; if ExpClass <> nil then begin SaveDBGridEhToExportFile(ExpClass, DBGridEhMail, fileName, True); end; sendMail(LEHost.Text, LEUser.Text, LEPass.Text, LEReceive.Text, FormatDateTime('yyyy-mm-dd', Date) + LETitle.Text, MemoBody.Text, filename); finally if FileExists(fileName) then DeleteFile(fileName); end; end; end else begin if FormatDateTime('nnss', Now) = '0000' then begin case CBReportType.ItemIndex of 0: TMailUtil.showTodayRecord(); 1: TMailUtil.showToWeekRecord(); 2: TMailUtil.showToMonthRecord(); 3: TMailUtil.showToYearRecord(); end; try fileName := ExtractFilePath(ParamStr(0)) + 'dataReport.xls'; ExpClass := TDBGridEhExportAsXLS; if ExpClass <> nil then begin SaveDBGridEhToExportFile(ExpClass, DBGridEhMail, fileName, True); end; sendMail(LEHost.Text, LEUser.Text, LEPass.Text, LEReceive.Text, FormatDateTime('yyyy-mm-dd', Date) + LETitle.Text, MemoBody.Text, filename); finally if FileExists(fileName) then DeleteFile(fileName); end; end; end; end; procedure TMailForm.FormCreate(Sender: TObject); var myini: TIniFile; begin myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'setup.ini'); try LEHost.Text := myini.ReadString('mail', 'host', 'smtp.qq.com'); LEUser.Text := myini.ReadString('mail', 'username', ''); LEPass.Text := TCommonUtil.deBase64(myini.ReadString('mail', 'pass', '')); LEReceive.Text := myini.ReadString('mail', 'receiver', ''); LETitle.Text := myini.ReadString('mail', 'title', ''); MemoBody.Text := myini.ReadString('mail', 'body', ''); CBReportType.ItemIndex := myini.ReadInteger('mail', 'report_type', 0); CBAutoSend.Checked := myini.ReadBool('mail', 'auto_send', False); RBEveryDay.Checked := myini.ReadBool('mail', 'everyday', True); DTPSend.Time := myini.ReadTime('mail', 'sendTime', StrToTime('00:00:00')); RBEveryHour.Checked := myini.ReadBool('mail', 'everyhour', False); TMail.Enabled := CBAutoSend.Checked; finally myini.Free; end; DBGridEhMail.DataSource := QueryDataModule.DSMail; end; procedure TMailForm.loadDBGrid; var i: Integer; fn: string; begin for i := 0 to MainForm.DBGridEh1.FieldCount - 1 do begin fn := MainForm.DBGridEh1.Fields[i].FieldName; DBGridEhMail.FieldColumns[fn].Title.Caption := MainForm.DBGridEh1.FieldColumns[fn].Title.Caption; DBGridEhMail.FieldColumns[fn].Visible := MainForm.DBGridEh1.FieldColumns[fn].Visible; end; for i := 0 to DBGridEhMail.Columns.Count - 1 do begin DBGridEhMail.Columns[i].Width := MainForm.DBGridEh1.Columns[i].Width; end; end; end.
unit Grijjy.MongoDB.Queries; (*< Tools for building MongoDB queries. @bold(Quick Start) <source> var Filter: TgoMongoFilter; Projection: TgoMongoProjection; Sort: TgoMongoSort; Update: TgoMongoUpdate; begin Filter := TgoMongoFilter.Gte('age', 21) and TgoMongoFilter.Lt('age', 65'); WriteLn(Filter.ToJson); // outputs: {age: {$gte: 21, $lt: 65}} Projection := TgoMongoProjection.Include('name') + TgoMongoProjection.Exclude('_id'); WriteLn(Projection.ToJson); // outputs: {name: 1, _id: 0} Sort := TgoMongoSort.Decending('age') + TgoMongoSort.Ascending('posts'); WriteLn(Sort.ToJson); // outputs: {age: -1, posts: 1} Update := TgoMongoUpdate.Init.&Set('age', 42).&Set('name', 'Joe'); WriteLn(Update.ToJson); // outputs {$set: {age: 42, name: "Joe"}} end; </source> @bold(Query Tools) Filters (TgoMongoFilter), projections (TgoMongoProjection), sort modifiers (TgrMongoSort) and update definitions (TgrMongoUpdate) can be implictly converted from JSON strings and documents, or they can be created using static helper functions. The following 3 statements all have the same result: <source> MyFilter := '{age: {$gt: 18}}'; MyFilter := TgoBsonDocument.Create('age', TgoBsonDocument.Create('$gt', 18)); MyFilter := TgoMongoFilter.Gt('age', 18); </source> They can be converted to BSON documents using the Render method, or to JSON and BSON using to ToJson and ToBson methods. @bold(TgoMongoFilter) Comparision: * TgoMongoFilter.Eq * TgoMongoFilter.Ne * TgoMongoFilter.Lt * TgoMongoFilter.Lte * TgoMongoFilter.Gt * TgoMongoFilter.Gte Logical: * TgoMongoFilter.LogicalAnd * TgoMongoFilter.LogicalOr * TgoMongoFilter.LogicalNot * TgoMongoFilter.And * TgoMongoFilter.Or * TgoMongoFilter.Not Element: * TgoMongoFilter.Exists * TgoMongoFilter.Type Evaluation: * TgoMongoFilter.Mod * TgoMongoFilter.Regex * TgoMongoFilter.Text Array: * TgoMongoFilter.AnyEq * TgoMongoFilter.AnyNe * TgoMongoFilter.AnyLt * TgoMongoFilter.AnyLte * TgoMongoFilter.AnyGt * TgoMongoFilter.AnyGte * TgoMongoFilter.All * TgoMongoFilter.In * TgoMongoFilter.Nin * TgoMongoFilter.ElemMatch * TgoMongoFilter.Size * TgoMongoFilter.SizeGt * TgoMongoFilter.SizeGte * TgoMongoFilter.SizeLt * TgoMongoFilter.SizeLte Bitwise: * TgoMongoFilter.BitsAllClear * TgoMongoFilter.BitsAllSet * TgoMongoFilter.BitsAnyClear * TgoMongoFilter.BitsAnySet @bold(TgoMongoProjection) * TgoMongoProjection.Include * TgoMongoProjection.Exclude * TgoMongoProjection.ElemMatch * TgoMongoProjection.MetaTextScore * TgoMongoProjection.Slice * TgoMongoProjection.Add * TgoMongoProjection.Combine @bold(TgrMongoSort) * TgoMongoSort.Ascending * TgoMongoSort.Descending * TgoMongoSort.MetaTextScore * TgoMongoSort.Add * TgoMongoSort.Combine @bold(TgrMongoUpdate) Fields: * TgoMongoUpdate.Set * TgoMongoUpdate.SetOnInsert * TgoMongoUpdate.Unset * TgoMongoUpdate.Inc * TgoMongoUpdate.Mul * TgoMongoUpdate.Max * TgoMongoUpdate.Min * TgoMongoUpdate.CurrentDate * TgoMongoUpdate.Rename Array: * TgoMongoUpdate.AddToSet * TgoMongoUpdate.AddToSetEach * TgoMongoUpdate.PopFirst * TgoMongoUpdate.PopLast * TgoMongoUpdate.Pull * TgoMongoUpdate.PullFilter * TgoMongoUpdate.PullAll * TgoMongoUpdate.Push * TgoMongoUpdate.PushEach Bitwise: * TgoMongoUpdate.BitwiseAnd * TgoMongoUpdate.BitwiseOr * TgoMongoUpdate.BitwiseXor *) {$INCLUDE 'Grijjy.inc'} interface uses System.SysUtils, Grijjy.Bson; type { Text searching options for TgoMongoFilter.Text } TgoMongoTextSearchOption = ( { The enable case sensitive search } CaseSensitive, { The enable diacritic sensitive search } DiacriticSensitive); type { Set of text search options } TgoMongoTextSearchOptions = set of TgoMongoTextSearchOption; type (* A MongoDB filter. A filter defines a query criterion. For example, the filter <tt>{ age : { $gt: 18 } }</tt> can be used to query persons more than 18 years old. Filters can be implictly converted from JSON strings and documents, or they can be created using static helper functions. The following 3 statements all have the same result: <source> MyFilter := '{age: {$gt: 18}}'; MyFilter := TgoBsonDocument.Create('age', TgoBsonDocument.Create('$gt', 18)); MyFilter := TgoMongoFilter.Gt('age', 18); </source> You can use the logical "and", "or" and "not" operators to combine multiple filters into one: <source> MyFilter := TgoMongoFilter.Gt('a', 1) and TgoMongoFilter.Lt('a', 10); </source> This results in: <tt>{a: {$gt: 1, $lt: 10}}</tt> *) TgoMongoFilter = record {$REGION 'Internal Declarations'} private type IFilter = interface ['{BAE9502F-7FC3-4AB4-B35F-AEA09F8BC0DB}'] function Render: TgoBsonDocument; function ToBson: TBytes; function ToJson(const ASettings: TgoJsonWriterSettings): String; end; private class var FEmpty: TgoMongoFilter; private FImpl: IFilter; public class constructor Create; {$ENDREGION 'Internal Declarations'} public (* Implicitly converts a Json string to a filter. Use this converter if you have manually created a query criterion in Json (such as <tt>{ age : { $gt: 18 } }</tt>) and want to use it as a filter. The Json string must be parseable to a BSON document. Raises: EgrJsonParserError or EInvalidOperation on parse errors *) class operator Implicit(const AJson: String): TgoMongoFilter; static; (* Implicitly converts a BSON Document to a filter. Use this converter if you have manually created a BSON document for a query criterion, and want to use it as a filter. *) class operator Implicit(const ADocument: TgoBsonDocument): TgoMongoFilter; static; (* Checks if the filter has been assigned. Returns: True if the filter hasn't been assigned yet. *) function IsNil: Boolean; inline; { Unassigns the filter (like setting an object to nil). IsNil will return True afterwards. } procedure SetNil; inline; (* Renders the filter to a BSON Document. Returns: The BSON Document that represents this filter. *) function Render: TgoBsonDocument; inline; (* Converts the filter to binary BSON. Returns: The BSON byte stream that represents this filter. *) function ToBson: TBytes; inline; (* Converts the filter to a JSON string. Returns: This filter in JSON format. @bold(Note): the filter is converted using the default writer settings. That is, without any pretty printing, and in Strict mode. Use the other overload of this function to specify output settings. *) function ToJson: String; overload; inline; (* Converts the filter to a JSON string, using specified settings. Parameters: ASettings: the output settings to use, such as pretty-printing and Strict vs Shell mode. Returns: This filter in JSON format. *) function ToJson(const ASettings: TgoJsonWriterSettings): String; overload; inline; { Empty filter. An empty filter matches everything. } class property Empty: TgoMongoFilter read FEmpty; public {=================================== Comparison ===================================} (* Matches values that are equal to a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Eq('x', 1)</code> results in <tt>{x: 1}</tt> See https://docs.mongodb.org/manual/reference/operator/query/eq/#op._S_eq *) class function Eq(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values that are @bold(not) equal to a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Ne('x', 1)</code> results in <tt>{x: {$ne: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/ne/#op._S_ne *) class function Ne(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values that are less than a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Lt('x', 1)</code> results in <tt>{x: {$lt: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/lt/#op._S_lt *) class function Lt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values that are less than or equal to a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Lte('x', 1)</code> results in <tt>{x: {$lte: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/lte/#op._S_lte *) class function Lte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values that are greater than a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Gt('x', 1)</code> results in <tt>{x: {$gt: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/gt/#op._S_gt *) class function Gt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values that are greater than or equal to a specified value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Gte('x', 1)</code> results in <tt>{x: {$gte: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/gte/#op._S_gte *) class function Gte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; public {=================================== Logical ===================================} (* Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. For example: <source> Filter := TgoMongoFilter.Eq('x', 1) and TgoMongoFilter.Eq('y', 2); </source> will result in <tt>{x: 1, y: 2}</tt>. Depending on the source filters, the output may be different. For example: <source> Filter := TgoMongoFilter.Gt('x', 1) and TgoMongoFilter.Lt('x', 10); </source> will result in <tt>{x: {$gt: 1, $lt: 10}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/and/#op._S_and *) class operator LogicalAnd(const ALeft, ARight: TgoMongoFilter): TgoMongoFilter; static; (* Joins query clauses with a logical OR returns all documents that match the conditions of either clause. For example: <source> Filter := TgoMongoFilter.Eq('x', 1) or TgoMongoFilter.Eq('y', 2); </source> will result in <tt>{$or: [{x: 1}, {y: 2}]}</tt>. See https://docs.mongodb.org/manual/reference/operator/query/or/#op._S_or *) class operator LogicalOr(const ALeft, ARight: TgoMongoFilter): TgoMongoFilter; static; (* Inverts the effect of a query expression and returns documents that do not match the query expression. For example: <source> Filter := not TgoMongoFilter.Eq('x', 1); </source> will result in <tt>{x: {$ne: 1}}</tt>. See https://docs.mongodb.org/manual/reference/operator/query/not/#op._S_not *) class operator LogicalNot(const AOperand: TgoMongoFilter): TgoMongoFilter; static; (* Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. For example: Parameters: AFilter1: the first filter. AFilter2: the second filter. Returns: The AND filter. <source> Filter := TgoMongoFilter.&And( TgoMongoFilter.Eq('x', 1), TgoMongoFilter.Eq('y', 2)); </source> will result in <tt>{x: 1, y: 2}</tt>. Depending on the source filters, the output may be different. For example: <source> Filter := TgoMongoFilter.&And( TgoMongoFilter.Gt('x', 1), TgoMongoFilter.Lt('x', 10)); </source> will result in <tt>{x: {$gt: 1, $lt: 10}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/and/#op._S_and *) class function &And(const AFilter1, AFilter2: TgoMongoFilter): TgoMongoFilter; overload; static; (* Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. For example: Parameters: AFilters: the filters to combine. Returns: The AND filter. <source> Filter := TgoMongoFilter.&And([ TgoMongoFilter.Eq('x', 1), TgoMongoFilter.Eq('y', 2), TgoMongoFilter.Eq('z', 3)]); </source> will result in <tt>{x: 1, y: 2, z: 3}</tt>. Depending on the source filter, the output may be different. For example: <source> Filter := TgoMongoFilter.&And([ TgoMongoFilter.Eq('x', 1), TgoMongoFilter.Eq('x', 2), TgoMongoFilter.Eq('z', 3)]); </source> will result in <tt>{$and: [{x: 1}, {x: 2}, {z: 3}]}</tt> See https://docs.mongodb.org/manual/reference/operator/query/and/#op._S_and *) class function &And( const AFilters: array of TgoMongoFilter): TgoMongoFilter; overload; static; (* Joins query clauses with a logical OR returns all documents that match the conditions of either clause. For example: Parameters: AFilter1: the first filter. AFilter2: the second filter. Returns: The OR filter. <source> Filter := TgoMongoFilter.Eq('x', 1) or TgoMongoFilter.Eq('y', 2); </source> will result in <tt>{$or: [{x: 1}, {y: 2}]}</tt>. See https://docs.mongodb.org/manual/reference/operator/query/or/#op._S_or *) class function &Or(const AFilter1, AFilter2: TgoMongoFilter): TgoMongoFilter; overload; static; (* Joins query clauses with a logical OR returns all documents that match the conditions of either clause. For example: Parameters: AFilters: the filters to combine. Returns: The OR filter. <source> Filter := TgoMongoFilter.Eq('x', 1) or TgoMongoFilter.Eq('y', 2); </source> will result in <tt>{$or: [{x: 1}, {y: 2}]}</tt>. See https://docs.mongodb.org/manual/reference/operator/query/or/#op._S_or *) class function &Or( const AFilters: array of TgoMongoFilter): TgoMongoFilter; overload; static; (* Inverts the effect of a query expression and returns documents that do not match the query expression. For example: Parameters: AOperand: the filter to negate. Returns: The NOT filter. <source> Filter := TgoMongoFilter.&Not(TgoMongoFilter.Eq('x', 1)); </source> will result in <tt>{x: {$ne: 1}}</tt>. See https://docs.mongodb.org/manual/reference/operator/query/not/#op._S_not *) class function &Not(const AOperand: TgoMongoFilter): TgoMongoFilter; static; public {=================================== Element ===================================} (* Matches documents that have (or have not) the specified field. Parameters: AFieldName: the name of the field (left operand). AExists: (optional) whether the field must exist or not (right operand). Defaults to True. Returns: The filter. Example: <code>TgoMongoFilter.Exists('x')</code> results in <tt>{x: {$exists: true}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/exists/#op._S_exists *) class function Exists(const AFieldName: String; const AExists: Boolean = True): TgoMongoFilter; static; (* Selects documents if a field is of the specified type. Parameters: AFieldName: the name of the field (left operand). AType: the BSON type to match (right operand). Returns: The filter. Example: <code>TgoMongoFilter.&Type('x', TgtBsonType.&String)</code> results in <tt>{x: {$type: 2}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type *) class function &Type(const AFieldName: String; const AType: TgoBsonType): TgoMongoFilter; overload; static; (* Selects documents if a field is of the specified type. Parameters: AFieldName: the name of the field (left operand). AType: the string alias for the BSON type to match (right operand). Returns: The filter. Example: <code>TgoMongoFilter.&Type('x', 'string')</code> results in <tt>{x: {$type: "string"}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type *) class function &Type(const AFieldName, AType: String): TgoMongoFilter; overload; static; public {=================================== Evaluation ===================================} (* Select documents where the value of a field divided by a divisor has the specified remainder (i.e. perform a modulo operation to select documents). Parameters: AFieldName: the name of the field (left operand). ADivisor: the divisor. ARemainder: the remainder. Returns: The filter. Example: <code>TgoMongoFilter.&Mod('x', 10, 4)</code> results in <tt>{x: {$mod: [NumberLong(10), NumberLong(4)]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/mod/#op._S_mod *) class function &Mod(const AFieldName: String; const ADivisor, ARemainder: Int64): TgoMongoFilter; static; (* Selects documents where values match a specified regular expression. Parameters: AFieldName: the name of the field (left operand). ARegex: the regular expression. Returns: The filter. Example: <code>TgoMongoFilter.Regex('x', '/abc/')</code> results in <tt>{x: /abc/}</tt> See https://docs.mongodb.org/manual/reference/operator/query/regex/#op._S_regex *) class function Regex(const AFieldName: String; const ARegex: TgoBsonRegularExpression): TgoMongoFilter; static; (* Performs a text search. Parameters: AText: a string of terms that MongoDB parses and uses to query the text index. MongoDB performs a logical OR search of the terms unless specified as a phrase. AOptions: (optional) text search options. Defaults to none. ALanguage: (optional) language that determines the list of stop words for the search and the rules for the stemmer and tokenizer. If not specified, the search uses the default language of the index. Returns: The filter. Example: <code>TgoMongoFilter.Text('funny', [TgrMongoTextSearchOption.CaseSensitive])</code> results in <tt>{$text: {$search: "funny", $caseSensitive: true}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/text/#op._S_text *) class function Text(const AText: String; const AOptions: TgoMongoTextSearchOptions = []; const ALanguage: String = ''): TgoMongoFilter; static; public {=================================== Array ===================================} (* Matches values where an array field contains any element with a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyEq('x', 1)</code> results in <tt>{x: 1}</tt> See https://docs.mongodb.org/manual/reference/operator/query/eq/#op._S_eq *) class function AnyEq(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values where an array field contains any element not qual to a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyNe('x', 1)</code> results in <tt>{x: {$ne: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/ne/#op._S_ne *) class function AnyNe(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values where an array field contains any element with a value less than a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyLt('x', 1)</code> results in <tt>{x: {$lt: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/lt/#op._S_lt *) class function AnyLt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values where an array field contains any element with a value less than or equal to a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyLte('x', 1)</code> results in <tt>{x: {$lte: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/lte/#op._S_lte *) class function AnyLte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values where an array field contains any element with a value greater than a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyGt('x', 1)</code> results in <tt>{x: {$gt: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/gt/#op._S_gt *) class function AnyGt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Matches values where an array field contains any element with a value greater than or equal to a specific value. Parameters: AFieldName: the name of the field (left operand). AValue: the value (right operand). Returns: The filter. Example: <code>TgoMongoFilter.AnyGte('x', 1)</code> results in <tt>{x: {$gte: 1}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/gte/#op._S_gte *) class function AnyGte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; static; (* Creates an All filter for an array field. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.All('x', [1, 2])</code> results in <tt>{x: {$all: [1, 2]}}</tt> *) class function All(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; overload; static; (* Matches arrays that contain all elements specified in the query. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.All('x', [1, 2])</code> results in <tt>{x: {$all: [1, 2]}}</tt> *) class function All(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; overload; static; (* Matches arrays that contain all elements specified in the query. Parameters: AFieldName: the name of the field (left operand). AValues: the BSON Array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.All('x', TgoBsonArray.Create([1, 2]))</code> results in <tt>{x: {$all: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/all/#op._S_all *) class function All(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; overload; static; (* Matches any of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.In('x', [1, 2])</code> results in <tt>{x: {$in: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in *) class function &In(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; overload; static; (* Matches any of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.In('x', [1, 2])</code> results in <tt>{x: {$in: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in *) class function &In(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; overload; static; (* Matches any of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the BSON Array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.In('x', TgoBsonArray.Create([1, 2]))</code> results in <tt>{x: {$in: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in *) class function &In(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; overload; static; (* Matches none of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Nin('x', [1, 2])</code> results in <tt>{x: {$nin: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin *) class function Nin(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; overload; static; (* Matches none of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the array values (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Nin('x', [1, 2])</code> results in <tt>{x: {$nin: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin *) class function Nin(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; overload; static; (* Matches none of the values specified in an array. Parameters: AFieldName: the name of the field (left operand). AValues: the BSON Array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Nin('x', TgoBsonArray.Create([1, 2]))</code> results in <tt>{x: {$nin: [1, 2]}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/nin/#op._S_nin *) class function Nin(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; overload; static; (* Selects documents if element in the array field matches all the specified conditions. Parameters: AFieldName: the name of the field (left operand). AFilter: the filter specifying the conditions (right operand). Returns: The filter. Example: <code>TgoMongoFilter.ElemMatch('Enabled', TgoMongoFilter.Eq('k', 0) and TgoMongoFilter.Eq('v', True))</code> results in <tt>{Enabled: {$elemMatch: { k: 0, v: true}}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/elemMatch/#op._S_elemMatch *) class function ElemMatch(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoFilter; overload; static; (* Selects documents if the array field is a specified size. Parameters: AFieldName: the name of the field (left operand). ASize: the size (aka length or count) of the array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.Size('x', 10)</code> results in <tt>{x: {$size: 10}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/size/#op._S_size *) class function Size(const AFieldName: String; const ASize: Integer): TgoMongoFilter; overload; static; (* Selects documents if the array field is greater than a specified size. Parameters: AFieldName: the name of the field (left operand). ASize: the size (aka length or count) of the array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.SizeGt('x', 10)</code> results in <tt>{"x.10": {$exists: true}}</tt> *) class function SizeGt(const AFieldName: String; const ASize: Integer): TgoMongoFilter; overload; static; (* Selects documents if the array field is greater than or equal to a specified size. Parameters: AFieldName: the name of the field (left operand). ASize: the size (aka length or count) of the array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.SizeGt('x', 10)</code> results in <tt>{"x.9": {$exists: true}}</tt> *) class function SizeGte(const AFieldName: String; const ASize: Integer): TgoMongoFilter; overload; static; (* Selects documents if the array field is less than a specified size. Parameters: AFieldName: the name of the field (left operand). ASize: the size (aka length or count) of the array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.SizeLt('x', 10)</code> results in <tt>{"x.9": {$exists: false}}</tt> *) class function SizeLt(const AFieldName: String; const ASize: Integer): TgoMongoFilter; overload; static; (* Selects documents if the array field is less than or equal to a specified size. Parameters: AFieldName: the name of the field (left operand). ASize: the size (aka length or count) of the array (right operand). Returns: The filter. Example: <code>TgoMongoFilter.SizeLte('x', 10)</code> results in <tt>{"x.10": {$exists: false}}</tt> *) class function SizeLte(const AFieldName: String; const ASize: Integer): TgoMongoFilter; overload; static; public {=================================== Bitwise ===================================} (* Matches numeric or binary values in which a set of bit positions @bold(all) have a value of 0. Parameters: AFieldName: the name of the field (left operand). ABitMask: the set of bit positions (right operand). Returns: The filter. Example: <code>TgoMongoFilter.BitsAllClear('x', 43)</code> results in <tt>{x: {$bitsAllClear: 43}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/bitsAllClear/#op._S_bitsAllClear *) class function BitsAllClear(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; static; (* Matches numeric or binary values in which a set of bit positions @bold(all) have a value of 1. Parameters: AFieldName: the name of the field (left operand). ABitMask: the set of bit positions (right operand). Returns: The filter. Example: <code>TgoMongoFilter.BitsAllSet('x', 43)</code> results in <tt>{x: {$bitsAllSet: 43}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/bitsAllSet/#op._S_bitsAllSet *) class function BitsAllSet(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; static; (* Matches numeric or binary values in which @bold(any) bit from a set of bit positions has a value of 0. Parameters: AFieldName: the name of the field (left operand). ABitMask: the set of bit positions (right operand). Returns: The filter. Example: <code>TgoMongoFilter.BitsAnyClear('x', 43)</code> results in <tt>{x: {$bitsAnyClear: 43}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/bitsAnyClear/#op._S_bitsAnyClear *) class function BitsAnyClear(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; static; (* Matches numeric or binary values in which @bold(any) bit from a set of bit positions has a value of 1. Parameters: AFieldName: the name of the field (left operand). ABitMask: the set of bit positions (right operand). Returns: The filter. Example: <code>TgoMongoFilter.BitsAnyClear('x', 43)</code> results in <tt>{x: {$bitsAnyClear: 43}}</tt> See https://docs.mongodb.org/manual/reference/operator/query/bitsAnySet/#op._S_bitsAnySet *) class function BitsAnySet(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; static; end; type (* A MongoDB projection. A projection limits the amount of data that MongoDB sends to application. For example, the projection <tt>{ _id: 0 }</tt> excludes the _id field from result sets. Projections can be implictly converted from JSON strings and documents, or they can be created using static helper functions. The following 3 statements all have the same result: <source> MyProjection := '{_id: 0}'; MyProjection := TgoBsonDocument.Create('_id', 0); MyProjection := TgoMongoProjection.Exclude('_id'); </source> You can use the add (+) operator to combine multiple projections into one: <source> MyProjection := TgoMongoProjection.Include('name') + TgoMongoProjection.Exclude('_id'); </source> This results in: <tt>{name: 1, _id: 0}</tt> *) TgoMongoProjection = record {$REGION 'Internal Declarations'} private type IProjection = interface ['{060E413F-6B4E-4FFE-83EF-5A124BC914DB}'] function Render: TgoBsonDocument; function ToBson: TBytes; function ToJson(const ASettings: TgoJsonWriterSettings): String; end; private FImpl: IProjection; class function GetEmpty: TgoMongoProjection; static; inline; {$ENDREGION 'Internal Declarations'} public (* Implicitly converts a Json string to a projection. Use this converter if you have manually created a projection Json (such as <tt>{ _id: 0 }</tt>) and want to use it as a filter. The Json string must be parseable to a BSON document. Raises: EgrJsonParserError or EInvalidOperation on parse errors *) class operator Implicit(const AJson: String): TgoMongoProjection; static; (* Implicitly converts a BSON Document to a projection. Use this converter if you have manually created a BSON document, and want to use it as a projection. *) class operator Implicit(const ADocument: TgoBsonDocument): TgoMongoProjection; static; (* Combines two projections into a single projection. *) class operator Add(const ALeft, ARight: TgoMongoProjection): TgoMongoProjection; static; (* Checks if the projection has been assigned. Returns: True if the projection hasn't been assigned yet. *) function IsNil: Boolean; inline; { Unassigns the projection (like setting an object to nil). IsNil will return True afterwards. } procedure SetNil; inline; (* Renders the projection to a BSON Document. Returns: The BSON Document that represents this projection. *) function Render: TgoBsonDocument; inline; (* Converts the projection to binary BSON. Returns: The BSON byte stream that represents this projection. *) function ToBson: TBytes; inline; (* Converts the projection to a JSON string. Returns: This projection in JSON format. @bold(Note): the projection is converted using the default writer settings. That is, without any pretty printing, and in Strict mode. Use the other overload of this function to specify output settings. *) function ToJson: String; overload; inline; (* Converts the projection to a JSON string, using specified settings. Parameters: ASettings: the output settings to use, such as pretty-printing and Strict vs Shell mode. Returns: This projection in JSON format. *) function ToJson(const ASettings: TgoJsonWriterSettings): String; overload; inline; (* Empty projection. This is a null-projection (IsNil returns True) *) class property Empty: TgoMongoProjection read GetEmpty; public (* Combines two projections into a single projection. Parameters: AProjection1: the first projection. AProjection2: the second projection. Returns: The combined projection. Example: <code>TgoMongoProjection.Combine(TgoMongoProjection.Include('x'), TgoMongoProjection.Exclude('y'))</code> results in <tt>{x: 1, y: 0}</tt> *) class function Combine(const AProjection1, AProjection2: TgoMongoProjection): TgoMongoProjection; overload; static; (* Combines multiple projections into a single projection. Parameters: AProjections: the projections to combine. Returns: The combined projection. Example: <source>TgoMongoProjection.Combine([ TgoMongoProjection.Include('x'), TgoMongoProjection.Include('y'), TgoMongoProjection.Exclude('z')]) </source> results in <tt>{x: 1, y: 1, z: 0}</tt> *) class function Combine(const AProjections: array of TgoMongoProjection): TgoMongoProjection; overload; static; (* Includes a field in a projection. Parameters: AFieldName: the name of the field to include Returns: The projection. Example: <code>TgoMongoProjection.Include('x')</code> results in <tt>{x: 1}</tt> *) class function Include(const AFieldName: String): TgoMongoProjection; overload; static; (* Includes an array of fields in a projection. Parameters: AFieldNames: the names of the fields to include Returns: The projection. Example: <code>TgoMongoProjection.Include(['x', 'y'])</code> results in <tt>{x: 1, y: 1}</tt> *) class function Include(const AFieldNames: array of String): TgoMongoProjection; overload; static; (* Excludes a field from a projection. Parameters: AFieldName: the name of the field to exclude Returns: The projection. Example: <code>TgoMongoProjection.Exclude('x')</code> results in <tt>{x: 0}</tt> *) class function Exclude(const AFieldName: String): TgoMongoProjection; overload; static; (* Excludes an array of fields from a projection. Parameters: AFieldNames: the names of the fields to exclude Returns: The projection. Example: <code>TgoMongoProjection.Exclude(['x', 'y'])</code> results in <tt>{x: 0, y: 0}</tt> *) class function Exclude(const AFieldNames: array of String): TgoMongoProjection; overload; static; (* Projects the first element in an array that matches the specified condition (filter). Parameters: AFieldName: the name of the field (left operand). AFilter: the filter specifying the conditions (right operand). Returns: The projection. Example: <code>TgoMongoProjection.ElemMatch('a', TgoMongoFilter.Eq('b', 1))</code> results in <tt>{a: {$elemMatch: { b: 1}}}</tt> See https://docs.mongodb.org/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch *) class function ElemMatch(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoProjection; static; (* Projects the documentís score assigned during $text operation. Parameters: AFieldName: the name of the field. Returns: The projection. Example: <code>TgoMongoProjection.MetaTextScore('a')</code> results in <tt>{a: {$meta: "textScore"}}</tt> See https://docs.mongodb.org/manual/reference/operator/projection/meta/#proj._S_meta *) class function MetaTextScore(const AFieldName: String): TgoMongoProjection; static; (* Limits the number of elements projected from an array. Parameters: AFieldName: the name of the field. ALimit: the maximum number of array elements to return. When positive, it selects at most the first ALimit elements. When negative, it selects at most the last -ALimit elements. Returns: The projection. Example: <code>TgoMongoProjection.Slice('a', 10)</code> results in <tt>{a: {$slice: 10}}</tt> See https://docs.mongodb.org/manual/reference/operator/projection/slice/#proj._S_slice *) class function Slice(const AFieldName: String; const ALimit: Integer): TgoMongoProjection; overload; static; (* Limits the number of elements projected from an array. Parameters: AFieldName: the name of the field. ASkip: the number of items in the array to skip. When positive, it skips the first ASkip items. When negative, it starts with the item that is -ASkip from the last item. ALimit: the maximum number of array elements to return. Returns: The projection. Example: <code>TgoMongoProjection.Slice('a', 10, 20)</code> results in <tt>{a: {$slice: [10, 20]}}</tt> See https://docs.mongodb.org/manual/reference/operator/projection/slice/#proj._S_slice *) class function Slice(const AFieldName: String; const ASkip, ALimit: Integer): TgoMongoProjection; overload; static; end; type { Direction of a sort } TgoMongoSortDirection = ( { Sort in ascending order } Ascending, { Sort in descending order } Descending); type (* A MongoDB sort modifier, used to sort the results from a MongoDB query by some criteria. For example, the sort modifier <tt>{ age: 1 }</tt> sorts the result set by age in ascending order. Sort modifiers can be implictly converted from JSON strings and documents, or they can be created using static helper functions. The following 3 statements all have the same result: <source> MySort := '{age: 1}'; MySort := TgoBsonDocument.Create('age', 1); MySort := TgoMongoSort.Ascending('age'); </source> You can use the add (+) operator to combine multiple sort modifiers into one: <source> MySort := TgoMongoSort.Decending('age') + TgoMongoSort.Ascending('posts'); </source> This results in: <tt>{age: -1, posts: 1}</tt>. This specifies a descending sort by age first, and then an ascending sort by posts (in case ages are equal). *) TgoMongoSort = record {$REGION 'Internal Declarations'} private type ISort = interface ['{FB526276-76F3-4F67-90C9-F09010FE8F37}'] function Render: TgoBsonDocument; function ToBson: TBytes; function ToJson(const ASettings: TgoJsonWriterSettings): String; end; private FImpl: ISort; {$ENDREGION 'Internal Declarations'} public (* Implicitly converts a Json string to a sort modifier. Use this converter if you have manually created a sort modifier in Json (such as <tt>{age: 1}</tt>) and want to use it as a sort modifier. The Json string must be parseable to a BSON document. Raises: EgrJsonParserError or EInvalidOperation on parse errors *) class operator Implicit(const AJson: String): TgoMongoSort; static; (* Implicitly converts a BSON Document to a sort modifier. Use this converter if you have manually created a BSON document, and want to use it as a sort modifier. *) class operator Implicit(const ADocument: TgoBsonDocument): TgoMongoSort; static; (* Combines two sort modifiers into a single sort modifier. *) class operator Add(const ALeft, ARight: TgoMongoSort): TgoMongoSort; static; (* Checks if the sort modifier has been assigned. Returns: True if the sort modifier hasn't been assigned yet. *) function IsNil: Boolean; inline; { Unassigns the sort modifier (like setting an object to nil). IsNil will return True afterwards. } procedure SetNil; inline; (* Renders the sort modifier to a BSON Document. Returns: The BSON Document that represents this sort modifier. *) function Render: TgoBsonDocument; inline; (* Converts the sort modifier to binary BSON. Returns: The BSON byte stream that represents this sort modifier. *) function ToBson: TBytes; inline; (* Converts the sort modifier to a JSON string. Returns: This sort modifier in JSON format. @bold(Note): the sort modifier is converted using the default writer settings. That is, without any pretty printing, and in Strict mode. Use the other overload of this function to specify output settings. *) function ToJson: String; overload; inline; (* Converts the sort modifier to a JSON string, using specified settings. Parameters: ASettings: the output settings to use, such as pretty-printing and Strict vs Shell mode. Returns: This sort modifier in JSON format. *) function ToJson(const ASettings: TgoJsonWriterSettings): String; overload; inline; public (* Combines two sort modifiers into a single sort modifier. Parameters: ASort1: the first sort modifier. ASort2: the second sort modifier. Returns: The combined sort modifier. Example: <code>TgrMongoSort.Combine(TgrMongoSort.Descending('age'), TgoMongoSort.Ascending('posts'))</code> results in <tt>{age: -1, posts: 1}</tt> *) class function Combine(const ASort1, ASort2: TgoMongoSort): TgoMongoSort; overload; static; (* Combines multiple sort modifiers into a single sort modifier. Parameters: ASorts: the sort modifiers to combine. Returns: The combined sort modifier. Example: <source>TgrMongoSort.Combine([ TgoMongoSort.Ascending('x'), TgoMongoSort.Descending('y'), TgoMongoSort.Ascending('z')]) </source> results in <tt>{x: 1, y: -1, z: 1}</tt> *) class function Combine(const ASorts: array of TgoMongoSort): TgoMongoSort; overload; static; (* Sorts a result set by a specific field in ascending order. Parameters: AFieldName: the name of the field to sort by Returns: The sort modifier. Example: <code>TgrMongoSort.Ascending('x')</code> results in <tt>{x: 1}</tt> *) class function Ascending(const AFieldName: String): TgoMongoSort; static; (* Sorts a result set by a specific field in descending order. Parameters: AFieldName: the name of the field to sort by Returns: The sort modifier. Example: <code>TgrMongoSort.Descending('x')</code> results in <tt>{x: -1}</tt> *) class function Descending(const AFieldName: String): TgoMongoSort; static; (* Creates a descending sort on the computed relevance score of a text search. The name of the key should be the name of the projected relevence score field. Parameters: AFieldName: the name of the field. Returns: The sort modifier. Example: <code>TgrMongoSort.MetaTextScore('awesome')</code> results in <tt>{awesome: {$meta: "textScore"}}</tt> *) class function MetaTextScore(const AFieldName: String): TgoMongoSort; static; end; type { Used with TgoMongoUpdate.CurrentDate } TgoMongoCurrentDateType = (Default, Date, Timestamp); type (* A MongoDB update definition, used the specify how to update a document in the database. For example, {$set: {age: 42}} sets the "age" field in the document to 42. Update definitions can be implictly converted from JSON strings and documents, or they can be created using static helper functions. The following 3 statements all have the same result: <source> MyUpdate := '{$set: {age: 42}}'; MyUpdate := TgoBsonDocument.Create('$set', TgoBsonDocument.Create('age', 42)); MyUpdate := TgoMongoUpdate.Init.&Set('age', 42); </source> To create an update definition, you always start by calling the static <tt>Init</tt> function. This returns a new update definition that you can then define further by calling methods such as &Set, Push and Inc. All those methods return the update definition itself, so you can chain them for a fluent interface. For example, this fluent statement: <source> MyUpdate := TgoMongoUpdate.Init.&Set('a', 1).&Set('b', 2); </source> is identical to: <source> MyUpdate := TgoMongoUpdate.Init; MyUpdate.&Set('a', 1); MyUpdate.&Set('b', 2); </source> You can also write it like this for a readable, but short statement: <source> MyUpdate := TgoMongoUpdate.Init .&Set('a', 1) .&Set('b', 2); </source> In all these cases, the following JSON will be generated: <tt>{$set: {a: 1, b: 2}}</tt> As you can see, multiple <tt>&Set</tt> calls are merged into a single <tt>$set</tt> operator. *) TgoMongoUpdate = record public const { Used with PushEach } NO_SLICE = Integer.MaxValue; { Used with PushEach } NO_POSITION = Integer.MaxValue; {$REGION 'Internal Declarations'} private type IUpdate = interface ['{9FC6C8B5-B4BA-445F-A960-67FBDF8613F4}'] function Render: TgoBsonDocument; function ToBson: TBytes; function ToJson(const ASettings: TgoJsonWriterSettings): String; function IsCombine: Boolean; end; private FImpl: IUpdate; private function SetOrCombine(const AUpdate: IUpdate): IUpdate; {$ENDREGION 'Internal Declarations'} public (* Initializes a new update definition. This is like a constructor and should be the first call you make before calling any other methods. Returns: A new update definition, ready to be used for chaining other methods. *) class function Init: TgoMongoUpdate; inline; static; (* Implicitly converts a Json string to an update definition. Use this converter if you have manually created an update definition in Json (such as <tt>{$set: {age: 42}}</tt>) and want to use it as an update definition. The Json string must be parseable to a BSON document. Raises: EgrJsonParserError or EInvalidOperation on parse errors *) class operator Implicit(const AJson: String): TgoMongoUpdate; static; (* Implicitly converts a BSON Document to an update definition. Use this converter if you have manually created a BSON document, and want to use it as an update definition. *) class operator Implicit(const ADocument: TgoBsonDocument): TgoMongoUpdate; static; (* Checks if the update definition has been assigned. Returns: True if the update definition hasn't been assigned yet. *) function IsNil: Boolean; inline; { Unassigns the update definition (like setting an object to nil). IsNil will return True afterwards. } procedure SetNil; inline; (* Renders the update definition to a BSON Document. Returns: The BSON Document that represents this update definition. *) function Render: TgoBsonDocument; inline; (* Converts the update definition to binary BSON. Returns: The BSON byte stream that represents this update definition. *) function ToBson: TBytes; inline; (* Converts the update definition to a JSON string. Returns: This update definition in JSON format. @bold(Note): the update definition is converted using the default writer settings. That is, without any pretty printing, and in Strict mode. Use the other overload of this function to specify output settings. *) function ToJson: String; overload; inline; (* Converts the update definition to a JSON string, using specified settings. Parameters: ASettings: the output settings to use, such as pretty-printing and Strict vs Shell mode. Returns: This update definition in JSON format. *) function ToJson(const ASettings: TgoJsonWriterSettings): String; overload; inline; public {=================================== Fields ===================================} (* Sets the value of a field in a document. Parameters: AFieldname: the name of the field to set. AValue: the value to set the field to. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.&Set('a', 10)</code> results in <tt>{$set: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/set/#up._S_set *) function &Set(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents. Parameters: AFieldname: the name of the field to set. AValue: the value to set the field to. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.SetOnInsert('a', 10)</code> results in <tt>{$setOnInsert: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#up._S_setOnInsert *) function SetOnInsert(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Removes the specified field from a document. Parameters: AFieldname: the name of the field to remove. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Unset('a')</code> results in <tt>{$unset: {a: 1}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/set/#up._S_set *) function Unset(const AFieldName: String): TgoMongoUpdate; (* Increments the value of the field by the specified amount. Parameters: AFieldname: the name of the field to increment. AAmount: the amount to increment the field by. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Inc('a', 10)</code> results in <tt>{$inc: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/inc/#up._S_inc *) function Inc(const AFieldName: String; const AAmount: TgoBsonValue): TgoMongoUpdate; overload; (* Increments the value of the field by 1. Parameters: AFieldname: the name of the field to increment. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Inc('a')</code> results in <tt>{$inc: {a: 1}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/inc/#up._S_inc *) function Inc(const AFieldName: String): TgoMongoUpdate; overload; (* Multiplies the value of the field by the specified amount. Parameters: AFieldname: the name of the field to set. AAmount: the amount to multiply the field by. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Mul('a', 10)</code> results in <tt>{$mul: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/mul/#up._S_mul *) function Mul(const AFieldName: String; const AAmount: TgoBsonValue): TgoMongoUpdate; (* Only updates the field if the specified value is greater than the existing field value. Parameters: AFieldname: the name of the field to set. AValue: the value to set the field to if its current value is greater than this value. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Max('a', 10)</code> results in <tt>{$max: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/max/#up._S_max *) function Max(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Only updates the field if the specified value is less than the existing field value. Parameters: AFieldname: the name of the field to set. AValue: the value to set the field to if its current value is less than this value. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Min('a', 10)</code> results in <tt>{$min: {a: 10}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/min/#up._S_min *) function Min(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Sets the value of a field to current date, either as a Date or a Timestamp. Parameters: AFieldname: the name of the field to set to the current date. AType: (optional) type of the field to set. By default, it sets the current data as a Date. You can also explicitly set to Date or Timestamp. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.CurrentDate('a', TgoMongoCurrentDateType.Timestamp)</code> results in <tt>{$currentDate: {a: {$type: 'timestamp'}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/currentDate/#up._S_currentDate *) function CurrentDate(const AFieldName: String; const AType: TgoMongoCurrentDateType = TgoMongoCurrentDateType.Default): TgoMongoUpdate; (* Renames a field. Parameters: AFieldname: the name of the field to set. ANewName: the new name of the field. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Rename('a', 'b')</code> results in <tt>{$rename: {a: "b"}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/rename/#up._S_rename *) function Rename(const AFieldName, ANewName: String): TgoMongoUpdate; public {=================================== Array ===================================} (* Adds an element to an array only if it does not already exist in the set. Parameters: AFieldname: the name of array field. AValue: the value to add to the array. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.AddToSet('a', 1)</code> results in <tt>{$addToSet: {a: 1}}</tt> If AValue is a BSON array, then that array is added as a single value. For example, consider the following document: <tt>{ letters: ["a", "b"] }</tt> The following operation appends the array ["c", "d"] to the "letters" field: <code>TgrMongoUpdate.Init.AddToSet('letters', TgoBsonArray.Create('c', 'd'))</code> so the result becomes: <tt>{ letters: ["a", "b", ["c", "d"] ] }</tt> If you intent to add the letters "c" and "d" separately, the use AddToSetEach instead. See https://docs.mongodb.com/manual/reference/operator/update/addToSet/#up._S_addToSet *) function AddToSet(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* As AddToSet, but adds each element separately. Parameters: AFieldname: the name of array field. AValues: the values to add to the array. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.AddToSetEach('a', [1, 2])</code> results in <tt>{$addToSet: {a: {$each: [1, 2]}}}</tt> For example, consider the following document: <tt>{ letters: ["a", "b"] }</tt> The following operation appends the values "c" and "d" to the "letters" field: <code>TgrMongoUpdate.Init.AddToSetEach('letters', ['c', 'd'])</code> so the result becomes: <tt>{ letters: ["a", "b", "c", "d"] }</tt> See https://docs.mongodb.com/manual/reference/operator/update/addToSet/#up._S_addToSet See https://docs.mongodb.com/manual/reference/operator/update/each/#up._S_each *) function AddToSetEach(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoUpdate; (* Removes the first item of an array. Parameters: AFieldname: the name of array field. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PopFirst('a')</code> results in <tt>{$pop: {a: -1}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/pop/#up._S_pop *) function PopFirst(const AFieldName: String): TgoMongoUpdate; (* Removes the last item of an array. Parameters: AFieldname: the name of array field. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PopFirst('a')</code> results in <tt>{$pop: {a: 1}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/pop/#up._S_pop *) function PopLast(const AFieldName: String): TgoMongoUpdate; (* Removes all array elements that have a specific value. Parameters: AFieldname: the name of array field. AValue: the value to remove from the array. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Pull('a', 1)</code> results in <tt>{$pull: {a: 1}}</tt> @bold(Note): If AValue is a TgoBsonArray, Pull removes only the elements in the array that match the specified AValue exactly, including order. @bold(Note): If AValue is a TgoBsonDocument, Pull removes only the elements in the array that have the exact same fields and values. The ordering of the fields can differ. See https://docs.mongodb.com/manual/reference/operator/update/pull/#up._S_pull *) function Pull(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Removes all array elements that match a specified query. Parameters: AFieldname: the name of array field. AFilter: the query filter. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PullFilter('a', TgoMongoFilter.Gt('b', 1))</code> results in <tt>{$pull: {a: {b: {$gt: 1}}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/pull/#up._S_pull *) function PullFilter(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoUpdate; (* Removes all matching values from an array. Parameters: AFieldname: the name of array field. AValues: the values to remove from the array. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PullAll('a', [1, 2])</code> results in <tt>{$pullAll: {a: [1, 2]}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/pullAll/#up._S_pullAll *) function PullAll(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoUpdate; (* Adds an item to an array. Parameters: AFieldname: the name of array field. AValue: the value to add to the array. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.Push('a', 1)</code> results in <tt>{$push: {a: 1}}</tt> @bold(Note): If AValue is a TgoBsonArray, Push appends the whole array as a <i>single</i> element. See https://docs.mongodb.com/manual/reference/operator/update/push/#up._S_push *) function Push(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* As Push, but adds each item separately. Parameters: AFieldname: the name of array field. AValues: the values to add to the array. ASlice: (optional) slice modifier. If 0, the array will be emptied. If negative, the array is updated to contain only the last ASlice elements. If positive, the array is updated to contain only the first ASlice elements. Set the NO_SLICE (default) to disable this modifier. APosition: (optional) position modifier. Specifies the location in the array at which to insert the new elements. Set to NO_POSITION (default) to disable this modifier. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PushEach('a', [1, 2], 3)</code> results in <tt>{$push: {a: {$each: [1, 2], $slice: 3}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/push/#up._S_push *) function PushEach(const AFieldName: String; const AValues: array of TgoBsonValue; const ASlice: Integer = NO_SLICE; const APosition: Integer = NO_POSITION): TgoMongoUpdate; overload; (* As Push, but adds each item separately. Parameters: AFieldname: the name of array field. AValues: the values to add to the array. ASort: orders the elements of the array using this sort modifier. ASlice: (optional) slice modifier. If 0, the array will be emptied. If negative, the array is updated to contain only the last ASlice elements. If positive, the array is updated to contain only the first ASlice elements. Set the NO_SLICE (default) to disable this modifier. APosition: (optional) position modifier. Specifies the location in the array at which to insert the new elements. Set to NO_POSITION (default) to disable this modifier. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.PushEach('a', [1, 2], TgoMongoSort.Ascending('b')</code> results in <tt>{$push: {a: {$each: [1, 2], $sort: {b: 1}}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/push/#up._S_push *) function PushEach(const AFieldName: String; const AValues: array of TgoBsonValue; const ASort: TgoMongoSort; const ASlice: Integer = NO_SLICE; const APosition: Integer = NO_POSITION): TgoMongoUpdate; overload; public {=================================== Bitwise ===================================} (* Performs a bitwise AND update of integer values. Parameters: AFieldname: the name of the field to update. AValue: the operand of the bitwise AND. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.BitwiseAnd('a', 10)</code> results in <tt>{$bit: {a: {and: 10}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/bit/#up._S_bit *) function BitwiseAnd(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Performs a bitwise OR update of integer values. Parameters: AFieldname: the name of the field to update. AValue: the operand of the bitwise OR. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.BitwiseXor('a', 10)</code> results in <tt>{$bit: {a: {or: 10}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/bit/#up._S_bit *) function BitwiseOr(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; (* Performs a bitwise XOR update of integer values. Parameters: AFieldname: the name of the field to update. AValue: the operand of the bitwise XOR. Returns: This update definition, so you can use it for chaining. Example: <code>TgrMongoUpdate.Init.BitwiseXor('a', 10)</code> results in <tt>{$bit: {a: {xor: 10}}}</tt> See https://docs.mongodb.com/manual/reference/operator/update/bit/#up._S_bit *) function BitwiseXor(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; end; implementation uses Grijjy.Bson.IO; type TBuilder = class abstract(TInterfacedObject) protected class function SupportsWriter: Boolean; virtual; procedure Write(const AWriter: IgoBsonBaseWriter); virtual; function Build: TgoBsonDocument; virtual; protected { TgoMongoFilter.IFilter } { TgoMongoProjection.IProjection } { TgoMongoSort.ISort } { TgoMongoUpdate.IUpdate } function Render: TgoBsonDocument; function ToBson: TBytes; function ToJson(const ASettings: TgoJsonWriterSettings): String; end; type TFilter = class abstract(TBuilder, TgoMongoFilter.IFilter) end; type TFilterEmpty = class(TFilter) protected function Build: TgoBsonDocument; override; end; type TFilterJson = class(TFilter) private FJson: String; protected function Build: TgoBsonDocument; override; public constructor Create(const AJson: String); end; type TFilterBsonDocument = class(TFilter) private FDocument: TgoBsonDocument; protected function Build: TgoBsonDocument; override; public constructor Create(const ADocument: TgoBsonDocument); end; type TFilterSimple = class(TFilter) private FFieldName: String; FValue: TgoBsonValue; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AValue: TgoBsonValue); end; type TFilterOperator = class(TFilter) private FFieldName: String; FOperator: String; FValue: TgoBsonValue; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName, AOperator: String; const AValue: TgoBsonValue); end; type TFilterArrayOperator = class(TFilter) private FFieldName: String; FOperator: String; FValues: TgoBsonArray; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName, AOperator: String; const AValues: TgoBsonArray); end; type TFilterArrayIndexExists = class(TFilter) private FFieldName: String; FIndex: Integer; FExists: Boolean; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AIndex: Integer; const AExists: Boolean); end; type TFilterAnd = class(TFilter) private FFilters: TArray<TgoMongoFilter.IFilter>; private class procedure AddClause(const ADocument: TgoBsonDocument; const AClause: TgoBsonElement); static; class procedure PromoteFilterToDollarForm(const ADocument: TgoBsonDocument; const AClause: TgoBsonElement); static; protected function Build: TgoBsonDocument; override; public constructor Create(const AFilter1, AFilter2: TgoMongoFilter); overload; constructor Create(const AFilters: array of TgoMongoFilter); overload; end; type TFilterOr = class(TFilter) private FFilters: TArray<TgoMongoFilter.IFilter>; private class procedure AddClause(const AClauses: TgoBsonArray; const AFilter: TgoBsonDocument); static; protected function Build: TgoBsonDocument; override; public constructor Create(const AFilter1, AFilter2: TgoMongoFilter); overload; constructor Create(const AFilters: array of TgoMongoFilter); overload; end; type TFilterNot = class(TFilter) private FFilter: TgoMongoFilter.IFilter; private class function NegateArbitraryFilter(const AFilter: TgoBsonDocument): TgoBsonDocument; static; class function NegateSingleElementFilter(const AFilter: TgoBsonDocument; const AElement: TgoBsonElement): TgoBsonDocument; static; class function NegateSingleElementTopLevelOperatorFilter( const AFilter: TgoBsonDocument; const AElement: TgoBsonElement): TgoBsonDocument; static; class function NegateSingleFieldOperatorFilter(const AFieldName: String; const AElement: TgoBsonElement): TgoBsonDocument; static; protected function Build: TgoBsonDocument; override; public constructor Create(const AOperand: TgoMongoFilter); end; type TFilterElementMatch = class(TFilter) private FFieldName: String; FFilter: TgoMongoFilter.IFilter; protected function Build: TgoBsonDocument; override; public constructor Create(const AFieldName: String; const AFilter: TgoMongoFilter); end; type TProjection = class abstract(TBuilder, TgoMongoProjection.IProjection) end; type TProjectionJson = class(TProjection) private FJson: String; protected function Build: TgoBsonDocument; override; public constructor Create(const AJson: String); end; type TProjectionBsonDocument = class(TProjection) private FDocument: TgoBsonDocument; protected function Build: TgoBsonDocument; override; public constructor Create(const ADocument: TgoBsonDocument); end; type TProjectionSingleField = class(TProjection) private FFieldName: String; FValue: TgoBsonValue; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AValue: TgoBsonValue); end; type TProjectionMultipleFields = class(TProjection) private FFieldNames: TArray<String>; FValue: Integer; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldNames: array of String; const AValue: Integer); end; type TProjectionCombine = class(TProjection) private FProjections: TArray<TgoMongoProjection.IProjection>; protected function Build: TgoBsonDocument; override; public constructor Create(const AProjection1, AProjection2: TgoMongoProjection); overload; constructor Create(const AProjections: array of TgoMongoProjection); overload; end; type TProjectionElementMatch = class(TProjection) private FFieldName: String; FFilter: TgoMongoFilter.IFilter; protected function Build: TgoBsonDocument; override; public constructor Create(const AFieldName: String; const AFilter: TgoMongoFilter); end; type TSort = class abstract(TBuilder, TgoMongoSort.ISort) end; type TSortJson = class(TSort) private FJson: String; protected function Build: TgoBsonDocument; override; public constructor Create(const AJson: String); end; type TSortBsonDocument = class(TSort) private FDocument: TgoBsonDocument; protected function Build: TgoBsonDocument; override; public constructor Create(const ADocument: TgoBsonDocument); end; type TSortCombine = class(TSort) private FSorts: TArray<TgoMongoSort.ISort>; protected function Build: TgoBsonDocument; override; public constructor Create(const ASort1, ASort2: TgoMongoSort); overload; constructor Create(const ASorts: array of TgoMongoSort); overload; end; type TSortDirectional = class(TSort) private FFieldName: String; FDirection: TgoMongoSortDirection; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const ADirection: TgoMongoSortDirection); end; type TUpdate = class abstract(TBuilder, TgoMongoUpdate.IUpdate) protected { TgoMongoUpdate.IUpdate } function IsCombine: Boolean; virtual; end; type TUpdateJson = class(TUpdate) private FJson: String; protected function Build: TgoBsonDocument; override; public constructor Create(const AJson: String); end; type TUpdateBsonDocument = class(TUpdate) private FDocument: TgoBsonDocument; protected function Build: TgoBsonDocument; override; public constructor Create(const ADocument: TgoBsonDocument); end; type TUpdateOperator = class(TUpdate) private FOperator: String; FFieldName: String; FValue: TgoBsonValue; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AOperator, AFieldName: String; const AValue: TgoBsonValue); end; type TUpdateBitwiseOperator = class(TUpdate) private FOperator: String; FFieldName: String; FValue: TgoBsonValue; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AOperator, AFieldName: String; const AValue: TgoBsonValue); end; type TUpdateAddToSet = class(TUpdate) private FFieldName: String; FValues: TArray<TgoBsonValue>; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AValue: TgoBsonValue); overload; constructor Create(const AFieldName: String; const AValues: array of TgoBsonValue); overload; end; type TUpdatePull = class(TUpdate) private FFieldName: String; FFilter: TgoMongoFilter; FValues: TArray<TgoBsonValue>; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AValue: TgoBsonValue); overload; constructor Create(const AFieldName: String; const AValues: array of TgoBsonValue); overload; constructor Create(const AFieldName: String; const AFilter: TgoMongoFilter); overload; end; type TUpdatePush = class(TUpdate) private FFieldName: String; FValues: TArray<TgoBsonValue>; FSlice: Integer; FPosition: Integer; FSort: TgoMongoSort; protected class function SupportsWriter: Boolean; override; procedure Write(const AWriter: IgoBsonBaseWriter); override; public constructor Create(const AFieldName: String; const AValue: TgoBsonValue); overload; constructor Create(const AFieldName: String; const AValues: array of TgoBsonValue; const ASlice, APosition: Integer; const ASort: TgoMongoSort); overload; end; type TUpdateCombine = class(TUpdate) private FUpdates: TArray<TgoMongoUpdate.IUpdate>; FCount: Integer; protected { TgoMongoUpdate.IUpdate } function IsCombine: Boolean; override; protected function Build: TgoBsonDocument; override; public constructor Create(const AUpdate1, AUpdate2: TgoMongoUpdate.IUpdate); overload; constructor Create(const AUpdate1, AUpdate2: TgoMongoUpdate); overload; constructor Create(const AUpdates: array of TgoMongoUpdate); overload; procedure Add(const AUpdate: TgoMongoUpdate.IUpdate); end; { TgoMongoFilter } class function TgoMongoFilter.All(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$all', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.All(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$all', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.&Mod(const AFieldName: String; const ADivisor, ARemainder: Int64): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$mod', TgoBsonArray.Create([ADivisor, ARemainder])); end; class function TgoMongoFilter.Ne(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$ne', AValue); end; class function TgoMongoFilter.Nin(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$nin', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.Nin(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$nin', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.Nin(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$nin', AValues); end; class function TgoMongoFilter.&Not( const AOperand: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterNot.Create(AOperand); end; class function TgoMongoFilter.&Or(const AFilter1, AFilter2: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterOr.Create(AFilter1, AFilter2); end; class function TgoMongoFilter.&Or( const AFilters: array of TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterOr.Create(AFilters); end; class function TgoMongoFilter.&Type(const AFieldName: String; const AType: TgoBsonType): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$type', Ord(AType)); end; class function TgoMongoFilter.&Type(const AFieldName, AType: String): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$type', AType); end; class function TgoMongoFilter.All(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$all', AValues); end; class function TgoMongoFilter.&And(const AFilter1, AFilter2: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterAnd.Create(AFilter1, AFilter2); end; class function TgoMongoFilter.&And( const AFilters: array of TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterAnd.Create(AFilters); end; class function TgoMongoFilter.AnyEq(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterSimple.Create(AFieldName, AValue); end; class function TgoMongoFilter.AnyGt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$gt', AValue); end; class function TgoMongoFilter.AnyGte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$gte', AValue); end; class function TgoMongoFilter.AnyLt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$lt', AValue); end; class function TgoMongoFilter.AnyLte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$lte', AValue); end; class function TgoMongoFilter.AnyNe(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$ne', AValue); end; class function TgoMongoFilter.BitsAllClear(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$bitsAllClear', ABitMask); end; class function TgoMongoFilter.BitsAllSet(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$bitsAllSet', ABitMask); end; class function TgoMongoFilter.BitsAnyClear(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$bitsAnyClear', ABitMask); end; class function TgoMongoFilter.BitsAnySet(const AFieldName: String; const ABitMask: UInt64): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$bitsAnySet', ABitMask); end; class constructor TgoMongoFilter.Create; begin FEmpty.FImpl := TFilterEmpty.Create; end; class function TgoMongoFilter.ElemMatch(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterElementMatch.Create(AFieldName, AFilter); end; class function TgoMongoFilter.Eq(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterSimple.Create(AFieldName, AValue); end; class function TgoMongoFilter.Exists(const AFieldName: String; const AExists: Boolean): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$exists', AExists); end; class function TgoMongoFilter.Gt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$gt', AValue); end; class function TgoMongoFilter.Gte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$gte', AValue); end; class operator TgoMongoFilter.Implicit(const AJson: String): TgoMongoFilter; begin Result.FImpl := TFilterJson.Create(AJson); end; class operator TgoMongoFilter.Implicit( const ADocument: TgoBsonDocument): TgoMongoFilter; begin if (ADocument.IsNil) then Result.FImpl := nil else Result.FImpl := TFilterBsonDocument.Create(ADocument); end; class function TgoMongoFilter.&In(const AFieldName: String; const AValues: TArray<TgoBsonValue>): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$in', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.&In(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$in', TgoBsonArray.Create(AValues)); end; class function TgoMongoFilter.&In(const AFieldName: String; const AValues: TgoBsonArray): TgoMongoFilter; begin Result.FImpl := TFilterArrayOperator.Create(AFieldName, '$in', AValues); end; function TgoMongoFilter.IsNil: Boolean; begin Result := (FImpl = nil); end; class operator TgoMongoFilter.LogicalAnd(const ALeft, ARight: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterAnd.Create(ALeft, ARight); end; class operator TgoMongoFilter.LogicalNot( const AOperand: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterNot.Create(AOperand); end; class operator TgoMongoFilter.LogicalOr(const ALeft, ARight: TgoMongoFilter): TgoMongoFilter; begin Result.FImpl := TFilterOr.Create(ALeft, ARight); end; class function TgoMongoFilter.Lt(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$lt', AValue); end; class function TgoMongoFilter.Lte(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$lte', AValue); end; class function TgoMongoFilter.Regex(const AFieldName: String; const ARegex: TgoBsonRegularExpression): TgoMongoFilter; begin Result.FImpl := TFilterSimple.Create(AFieldName, ARegex); end; function TgoMongoFilter.Render: TgoBsonDocument; begin Assert(Assigned(FImpl)); Result := FImpl.Render; end; procedure TgoMongoFilter.SetNil; begin FImpl := nil; end; class function TgoMongoFilter.Size(const AFieldName: String; const ASize: Integer): TgoMongoFilter; begin Result.FImpl := TFilterOperator.Create(AFieldName, '$size', ASize); end; class function TgoMongoFilter.SizeGt(const AFieldName: String; const ASize: Integer): TgoMongoFilter; begin Result.FImpl := TFilterArrayIndexExists.Create(AFieldName, ASize, True); end; class function TgoMongoFilter.SizeGte(const AFieldName: String; const ASize: Integer): TgoMongoFilter; begin Result.FImpl := TFilterArrayIndexExists.Create(AFieldName, ASize - 1, True); end; class function TgoMongoFilter.SizeLt(const AFieldName: String; const ASize: Integer): TgoMongoFilter; begin Result.FImpl := TFilterArrayIndexExists.Create(AFieldName, ASize - 1, False); end; class function TgoMongoFilter.SizeLte(const AFieldName: String; const ASize: Integer): TgoMongoFilter; begin Result.FImpl := TFilterArrayIndexExists.Create(AFieldName, ASize, False); end; class function TgoMongoFilter.Text(const AText: String; const AOptions: TgoMongoTextSearchOptions; const ALanguage: String): TgoMongoFilter; var Settings: TgoBsonDocument; begin Settings := TgoBsonDocument.Create; Settings.Add('$search', AText); if (ALanguage <> '') then Settings.Add('$language', ALanguage); if (TgoMongoTextSearchOption.CaseSensitive in AOptions) then Settings.Add('$caseSensitive', True); if (TgoMongoTextSearchOption.DiacriticSensitive in AOptions) then Settings.Add('$diacriticSensitive', True); Result.FImpl := TFilterBsonDocument.Create(TgoBsonDocument.Create('$text', Settings)); end; function TgoMongoFilter.ToJson: String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(TgoJsonWriterSettings.Default); end; function TgoMongoFilter.ToBson: TBytes; begin Assert(Assigned(FImpl)); Result := FImpl.ToBson; end; function TgoMongoFilter.ToJson(const ASettings: TgoJsonWriterSettings): String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(ASettings); end; { TgoMongoProjection } class operator TgoMongoProjection.Implicit(const AJson: String): TgoMongoProjection; begin Result.FImpl := TProjectionJson.Create(AJson); end; class function TgoMongoProjection.Combine(const AProjection1, AProjection2: TgoMongoProjection): TgoMongoProjection; begin Result.FImpl := TProjectionCombine.Create(AProjection1, AProjection2); end; class function TgoMongoProjection.Combine( const AProjections: array of TgoMongoProjection): TgoMongoProjection; begin Result.FImpl := TProjectionCombine.Create(AProjections); end; class function TgoMongoProjection.ElemMatch(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoProjection; begin Result.FImpl := TProjectionElementMatch.Create(AFieldName, AFilter); end; class function TgoMongoProjection.Exclude( const AFieldNames: array of String): TgoMongoProjection; begin Result.FImpl := TProjectionMultipleFields.Create(AFieldNames, 0); end; class function TgoMongoProjection.Exclude( const AFieldName: String): TgoMongoProjection; begin Result.FImpl := TProjectionSingleField.Create(AFieldName, 0); end; class function TgoMongoProjection.GetEmpty: TgoMongoProjection; begin Result.FImpl := nil; end; class operator TgoMongoProjection.Implicit(const ADocument: TgoBsonDocument): TgoMongoProjection; begin if (ADocument.IsNil) then Result.FImpl := nil else Result.FImpl := TProjectionBsonDocument.Create(ADocument); end; class operator TgoMongoProjection.Add(const ALeft, ARight: TgoMongoProjection): TgoMongoProjection; begin Result.FImpl := TProjectionCombine.Create(ALeft, ARight); end; class function TgoMongoProjection.Include( const AFieldName: String): TgoMongoProjection; begin Result.FImpl := TProjectionSingleField.Create(AFieldName, 1); end; class function TgoMongoProjection.Include( const AFieldNames: array of String): TgoMongoProjection; begin Result.FImpl := TProjectionMultipleFields.Create(AFieldNames, 1); end; function TgoMongoProjection.IsNil: Boolean; begin Result := (FImpl = nil); end; class function TgoMongoProjection.MetaTextScore( const AFieldName: String): TgoMongoProjection; begin Result.FImpl := TProjectionSingleField.Create(AFieldName, TgoBsonDocument.Create('$meta', 'textScore')); end; function TgoMongoProjection.Render: TgoBsonDocument; begin Assert(Assigned(FImpl)); Result := FImpl.Render; end; class function TgoMongoProjection.Slice(const AFieldName: String; const ALimit: Integer): TgoMongoProjection; begin Result.FImpl := TProjectionSingleField.Create(AFieldName, TgoBsonDocument.Create('$slice', ALimit)); end; procedure TgoMongoProjection.SetNil; begin FImpl := nil; end; class function TgoMongoProjection.Slice(const AFieldName: String; const ASkip, ALimit: Integer): TgoMongoProjection; begin Result.FImpl := TProjectionSingleField.Create(AFieldName, TgoBsonDocument.Create('$slice', TgoBsonArray.Create([ASkip, ALimit]))); end; function TgoMongoProjection.ToBson: TBytes; begin Assert(Assigned(FImpl)); Result := FImpl.ToBson; end; function TgoMongoProjection.ToJson: String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(TgoJsonWriterSettings.Default); end; function TgoMongoProjection.ToJson( const ASettings: TgoJsonWriterSettings): String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(ASettings); end; { TgoMongoSort } class operator TgoMongoSort.Add(const ALeft, ARight: TgoMongoSort): TgoMongoSort; begin Result.FImpl := TSortCombine.Create(ALeft, ARight); end; class function TgoMongoSort.Ascending(const AFieldName: String): TgoMongoSort; begin Result.FImpl := TSortDirectional.Create(AFieldName, TgoMongoSortDirection.Ascending); end; class function TgoMongoSort.Combine( const ASorts: array of TgoMongoSort): TgoMongoSort; begin Result.FImpl := TSortCombine.Create(ASorts); end; class function TgoMongoSort.Descending(const AFieldName: String): TgoMongoSort; begin Result.FImpl := TSortDirectional.Create(AFieldName, TgoMongoSortDirection.Descending); end; class function TgoMongoSort.Combine(const ASort1, ASort2: TgoMongoSort): TgoMongoSort; begin Result.FImpl := TSortCombine.Create(ASort1, ASort2); end; class operator TgoMongoSort.Implicit( const ADocument: TgoBsonDocument): TgoMongoSort; begin if (ADocument.IsNil) then Result.FImpl := nil else Result.FImpl := TSortBsonDocument.Create(ADocument); end; class operator TgoMongoSort.Implicit(const AJson: String): TgoMongoSort; begin Result.FImpl := TSortJson.Create(AJson); end; function TgoMongoSort.IsNil: Boolean; begin Result := (FImpl = nil); end; class function TgoMongoSort.MetaTextScore( const AFieldName: String): TgoMongoSort; begin Result.FImpl := TSortBsonDocument.Create( TgoBsonDocument.Create(AFieldName, TgoBsonDocument.Create('$meta', 'textScore'))); end; function TgoMongoSort.Render: TgoBsonDocument; begin Assert(Assigned(FImpl)); Result := FImpl.Render; end; procedure TgoMongoSort.SetNil; begin FImpl := nil; end; function TgoMongoSort.ToBson: TBytes; begin Assert(Assigned(FImpl)); Result := FImpl.ToBson; end; function TgoMongoSort.ToJson: String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(TgoJsonWriterSettings.Default); end; function TgoMongoSort.ToJson(const ASettings: TgoJsonWriterSettings): String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(ASettings); end; { TgoMongoUpdate } function TgoMongoUpdate.&Set(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$set', AFieldName, AValue)); end; procedure TgoMongoUpdate.SetNil; begin FImpl := nil; end; function TgoMongoUpdate.SetOnInsert(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$setOnInsert', AFieldName, AValue)); end; function TgoMongoUpdate.SetOrCombine(const AUpdate: IUpdate): IUpdate; begin if (FImpl = nil) then FImpl := AUpdate else if (FImpl.IsCombine) then TUpdateCombine(FImpl).Add(AUpdate) else FImpl := TUpdateCombine.Create(FImpl, AUpdate); Result := FImpl; end; function TgoMongoUpdate.AddToSet(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateAddToSet.Create(AFieldName, AValue)); end; function TgoMongoUpdate.AddToSetEach(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateAddToSet.Create(AFieldName, AValues)); end; function TgoMongoUpdate.BitwiseAnd(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateBitwiseOperator.Create('and', AFieldName, AValue)); end; function TgoMongoUpdate.BitwiseOr(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateBitwiseOperator.Create('or', AFieldName, AValue)); end; function TgoMongoUpdate.BitwiseXor(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateBitwiseOperator.Create('xor', AFieldName, AValue)); end; function TgoMongoUpdate.CurrentDate(const AFieldName: String; const AType: TgoMongoCurrentDateType): TgoMongoUpdate; var Value: TgoBsonValue; begin case AType of TgoMongoCurrentDateType.Date: Value := TgoBsonDocument.Create('$type', 'date'); TgoMongoCurrentDateType.Timestamp: Value := TgoBsonDocument.Create('$type', 'timestamp'); else Value := True; end; Result.FImpl := SetOrCombine(TUpdateOperator.Create('$currentDate', AFieldName, Value)); end; class operator TgoMongoUpdate.Implicit( const ADocument: TgoBsonDocument): TgoMongoUpdate; begin if (ADocument.IsNil) then Result.FImpl := nil else Result.FImpl := TUpdateBsonDocument.Create(ADocument); end; function TgoMongoUpdate.Inc(const AFieldName: String; const AAmount: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$inc', AFieldName, AAmount)); end; function TgoMongoUpdate.Inc(const AFieldName: String): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$inc', AFieldName, 1)); end; class function TgoMongoUpdate.Init: TgoMongoUpdate; begin Result.FImpl := nil; end; class operator TgoMongoUpdate.Implicit(const AJson: String): TgoMongoUpdate; begin Result.FImpl := TUpdateJson.Create(AJson); end; function TgoMongoUpdate.IsNil: Boolean; begin Result := (FImpl = nil); end; function TgoMongoUpdate.Max(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$max', AFieldName, AValue)); end; function TgoMongoUpdate.Min(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$min', AFieldName, AValue)); end; function TgoMongoUpdate.Mul(const AFieldName: String; const AAmount: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$mul', AFieldName, AAmount)); end; function TgoMongoUpdate.PopFirst(const AFieldName: String): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$pop', AFieldName, -1)); end; function TgoMongoUpdate.PopLast(const AFieldName: String): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$pop', AFieldName, 1)); end; function TgoMongoUpdate.Pull(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdatePull.Create(AFieldName, AValue)); end; function TgoMongoUpdate.PullAll(const AFieldName: String; const AValues: array of TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdatePull.Create(AFieldName, AValues)); end; function TgoMongoUpdate.PullFilter(const AFieldName: String; const AFilter: TgoMongoFilter): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdatePull.Create(AFieldName, AFilter)); end; function TgoMongoUpdate.Push(const AFieldName: String; const AValue: TgoBsonValue): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdatePush.Create(AFieldName, AValue)); end; function TgoMongoUpdate.PushEach(const AFieldName: String; const AValues: array of TgoBsonValue; const ASlice, APosition: Integer): TgoMongoUpdate; var Sort: TgoMongoSort; begin Sort.SetNil; Result := PushEach(AFieldName, AValues, Sort, ASlice, APosition); end; function TgoMongoUpdate.PushEach(const AFieldName: String; const AValues: array of TgoBsonValue; const ASort: TgoMongoSort; const ASlice, APosition: Integer): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdatePush.Create(AFieldName, AValues, ASlice, APosition, ASort)); end; function TgoMongoUpdate.Rename(const AFieldName, ANewName: String): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$rename', AFieldName, ANewName)); end; function TgoMongoUpdate.Render: TgoBsonDocument; begin Assert(Assigned(FImpl)); Result := FImpl.Render; end; function TgoMongoUpdate.ToBson: TBytes; begin Assert(Assigned(FImpl)); Result := FImpl.ToBson; end; function TgoMongoUpdate.ToJson: String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(TgoJsonWriterSettings.Default); end; function TgoMongoUpdate.ToJson(const ASettings: TgoJsonWriterSettings): String; begin Assert(Assigned(FImpl)); Result := FImpl.ToJson(ASettings); end; function TgoMongoUpdate.Unset(const AFieldName: String): TgoMongoUpdate; begin Result.FImpl := SetOrCombine(TUpdateOperator.Create('$unset', AFieldName, 1)); end; { TBuilder } function TBuilder.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Create; end; function TBuilder.Render: TgoBsonDocument; var Writer: IgoBsonDocumentWriter; begin if (SupportsWriter) then begin Result := TgoBsonDocument.Create; Writer := TgoBsonDocumentWriter.Create(Result); Write(Writer); end else Result := Build(); end; class function TBuilder.SupportsWriter: Boolean; begin Result := False; end; function TBuilder.ToBson: TBytes; var Writer: IgoBsonWriter; begin if (SupportsWriter) then begin Writer := TgoBsonWriter.Create; Write(Writer); Result := Writer.ToBson; end else Result := Build().ToBson; end; function TBuilder.ToJson(const ASettings: TgoJsonWriterSettings): String; var Writer: IgoJsonWriter; begin if (SupportsWriter) then begin Writer := TgoJsonWriter.Create(ASettings); Write(Writer); Result := Writer.ToJson; end else Result := Build().ToJson(ASettings); end; procedure TBuilder.Write(const AWriter: IgoBsonBaseWriter); begin { No default implementation } end; { TFilterEmpty } function TFilterEmpty.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Create; end; { TFilterJson } function TFilterJson.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Parse(FJson); end; constructor TFilterJson.Create(const AJson: String); begin inherited Create; FJson := AJson; end; { TFilterBsonDocument } function TFilterBsonDocument.Build: TgoBsonDocument; begin Result := FDocument; end; constructor TFilterBsonDocument.Create(const ADocument: TgoBsonDocument); begin inherited Create; FDocument := ADocument; end; { TFilterSimple } constructor TFilterSimple.Create(const AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; FValue := AValue; end; class function TFilterSimple.SupportsWriter: Boolean; begin Result := True; end; procedure TFilterSimple.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteValue(FValue); AWriter.WriteEndDocument; end; { TFilterOperator } constructor TFilterOperator.Create(const AFieldName, AOperator: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; FOperator := AOperator; FValue := AValue; end; class function TFilterOperator.SupportsWriter: Boolean; begin Result := True; end; procedure TFilterOperator.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteStartDocument; AWriter.WriteName(FOperator); AWriter.WriteValue(FValue); AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TFilterArrayOperator } constructor TFilterArrayOperator.Create(const AFieldName, AOperator: String; const AValues: TgoBsonArray); begin inherited Create; FFieldName := AFieldName; FOperator := AOperator; FValues := AValues; end; class function TFilterArrayOperator.SupportsWriter: Boolean; begin Result := True; end; procedure TFilterArrayOperator.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteStartDocument; AWriter.WriteName(FOperator); AWriter.WriteValue(FValues); AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TFilterAnd } class procedure TFilterAnd.AddClause(const ADocument: TgoBsonDocument; const AClause: TgoBsonElement); var Item, Value: TgoBsonValue; ExistingClauseValue, ClauseValue: TgoBsonDocument; Element: TgoBsonElement; I: Integer; begin if (AClause.Name = '$and') then begin { Flatten out nested $and } for Item in AClause.Value.AsBsonArray do begin for Element in Item.AsBsonDocument do AddClause(ADocument, Element); end; end else if (ADocument.Count = 1) and (ADocument.Elements[0].Name = '$and') then ADocument.Values[0].AsBsonArray.Add(TgoBsonDocument.Create(AClause)) else if (ADocument.TryGetValue(AClause.Name, Value)) then begin if (Value.IsBsonDocument) and (AClause.Value.IsBsonDocument) then begin ClauseValue := AClause.Value.AsBsonDocument; ExistingClauseValue := Value.AsBsonDocument; for I := 0 to ExistingClauseValue.Count - 1 do begin if (ClauseValue.Contains(ExistingClauseValue.Elements[I].Name)) then begin PromoteFilterToDollarForm(ADocument, AClause); Exit; end; end; for Element in ClauseValue do ExistingClauseValue.Add(Element); end else PromoteFilterToDollarForm(ADocument, AClause); end else ADocument.Add(AClause); end; function TFilterAnd.Build: TgoBsonDocument; var I, J: Integer; RenderedFilter: TgoBsonDocument; begin Result := TgoBsonDocument.Create; for I := 0 to Length(FFilters) - 1 do begin RenderedFilter := FFilters[I].Render; for J := 0 to RenderedFilter.Count - 1 do AddClause(Result, RenderedFilter.Elements[J]); end; end; constructor TFilterAnd.Create(const AFilter1, AFilter2: TgoMongoFilter); begin Assert(not AFilter1.IsNil); Assert(not AFilter2.IsNil); inherited Create; SetLength(FFilters, 2); FFilters[0] := AFilter1.FImpl; FFilters[1] := AFilter2.FImpl; end; constructor TFilterAnd.Create(const AFilters: array of TgoMongoFilter); var I: Integer; begin inherited Create; SetLength(FFilters, Length(AFilters)); for I := 0 to Length(AFilters) - 1 do begin Assert(not AFilters[I].IsNil); FFilters[I] := AFilters[I].FImpl; end; end; class procedure TFilterAnd.PromoteFilterToDollarForm(const ADocument: TgoBsonDocument; const AClause: TgoBsonElement); var Clauses: TgoBsonArray; QueryElement: TgoBsonElement; begin Clauses := TgoBsonArray.Create(ADocument.Count); for QueryElement in ADocument do Clauses.Add(TgoBsonDocument.Create(QueryElement)); Clauses.Add(TgoBsonDocument.Create(AClause)); ADocument.Clear; ADocument.Add('$and', Clauses) end; { TFilterOr } class procedure TFilterOr.AddClause(const AClauses: TgoBsonArray; const AFilter: TgoBsonDocument); begin if (AFilter.Count = 1) and (AFilter.Elements[0].Name = '$or') then { Flatten nested $or } AClauses.AddRange(AFilter.Values[0].AsBsonArray) else { We could shortcut the user's query if there are no elements in the filter, but I'd rather be literal and let them discover the problem on their own. } AClauses.Add(AFilter); end; function TFilterOr.Build: TgoBsonDocument; var I: Integer; Clauses: TgoBsonArray; RenderedFilter: TgoBsonDocument; begin Clauses := TgoBsonArray.Create; for I := 0 to Length(FFilters) - 1 do begin RenderedFilter := FFilters[I].Render; AddClause(Clauses, RenderedFilter); end; Result := TgoBsonDocument.Create('$or', Clauses); end; constructor TFilterOr.Create(const AFilter1, AFilter2: TgoMongoFilter); begin Assert(not AFilter1.IsNil); Assert(not AFilter2.IsNil); inherited Create; SetLength(FFilters, 2); FFilters[0] := AFilter1.FImpl; FFilters[1] := AFilter2.FImpl; end; constructor TFilterOr.Create(const AFilters: array of TgoMongoFilter); var I: Integer; begin inherited Create; SetLength(FFilters, Length(AFilters)); for I := 0 to Length(AFilters) - 1 do begin Assert(not AFilters[I].IsNil); FFilters[I] := AFilters[I].FImpl; end; end; { TFilterNot } function TFilterNot.Build: TgoBsonDocument; var RenderedFilter: TgoBsonDocument; begin RenderedFilter := FFilter.Render; if (RenderedFilter.Count = 1) then Result := NegateSingleElementFilter(RenderedFilter, RenderedFilter.Elements[0]) else Result := NegateArbitraryFilter(RenderedFilter); end; constructor TFilterNot.Create(const AOperand: TgoMongoFilter); begin Assert(not AOperand.IsNil); inherited Create; FFilter := AOperand.FImpl; end; class function TFilterNot.NegateArbitraryFilter( const AFilter: TgoBsonDocument): TgoBsonDocument; begin // $not only works as a meta operator on a single operator so simulate Not using $nor Result := TgoBsonDocument.Create('$nor', TgoBsonArray.Create([AFilter])); end; class function TFilterNot.NegateSingleElementFilter( const AFilter: TgoBsonDocument; const AElement: TgoBsonElement): TgoBsonDocument; var Selector: TgoBsonDocument; OperatorName: String; begin if (AElement.Name.Chars[0] = '$') then Exit(NegateSingleElementTopLevelOperatorFilter(AFilter, AElement)); if (AElement.Value.IsBsonDocument) then begin Selector := AElement.Value.AsBsonDocument; if (Selector.Count > 0) then begin OperatorName := Selector.Elements[0].Name; Assert(OperatorName <> ''); if (OperatorName.Chars[0] = '$') and (OperatorName <> '$ref') then begin if (Selector.Count = 1) then Exit(NegateSingleFieldOperatorFilter(AElement.Name, Selector.Elements[0])) else Exit(NegateArbitraryFilter(AFilter)); end; end; end; if (AElement.Value.IsBsonRegularExpression) then Exit(TgoBsonDocument.Create(AElement.Name, TgoBsonDocument.Create('$not', AElement.Value))); Result := TgoBsonDocument.Create(AElement.Name, TgoBsonDocument.Create('$ne', AElement.Value)); end; class function TFilterNot.NegateSingleElementTopLevelOperatorFilter( const AFilter: TgoBsonDocument; const AElement: TgoBsonElement): TgoBsonDocument; begin if (AElement.Name = '$or') then Result := TgoBsonDocument.Create('$nor', AElement.Value) else if (AElement.Name = '$nor') then Result := TgoBsonDocument.Create('$or', AElement.Value) else Result := NegateArbitraryFilter(AFilter); end; class function TFilterNot.NegateSingleFieldOperatorFilter( const AFieldName: String; const AElement: TgoBsonElement): TgoBsonDocument; var S: String; begin S := AElement.Name; if (S = '$exists') then Result := TgoBsonDocument.Create(AFieldName, TgoBsonDocument.Create('$exists', not AElement.Value.AsBoolean)) else if (S = '$in') then Result := TgoBsonDocument.Create(AFieldName, TgoBsonDocument.Create('$nin', AElement.Value.AsBsonArray)) else if (S = '$ne') or (S = '$not') then Result := TgoBsonDocument.Create(AFieldName, AElement.Value) else if (S = '$nin') then Result := TgoBsonDocument.Create(AFieldName, TgoBsonDocument.Create('$in', AElement.Value.AsBsonArray)) else Result := TgoBsonDocument.Create(AFieldName, TgoBsonDocument.Create('$not', TgoBsonDocument.Create(AElement))); end; { TFilterElementMatch } function TFilterElementMatch.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Create(FFieldName, TgoBsonDocument.Create('$elemMatch', FFilter.Render)); end; constructor TFilterElementMatch.Create(const AFieldName: String; const AFilter: TgoMongoFilter); begin Assert(not AFilter.IsNil); inherited Create; FFieldName := AFieldName; FFilter := AFilter.FImpl; end; { TFilterArrayIndexExists } constructor TFilterArrayIndexExists.Create(const AFieldName: String; const AIndex: Integer; const AExists: Boolean); begin inherited Create; FFieldName := AFieldName; FIndex := AIndex; FExists := AExists; end; class function TFilterArrayIndexExists.SupportsWriter: Boolean; begin Result := True; end; procedure TFilterArrayIndexExists.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName + '.' + FIndex.ToString); AWriter.WriteStartDocument; AWriter.WriteName('$exists'); AWriter.WriteBoolean(FExists); AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TProjectionJson } function TProjectionJson.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Parse(FJson); end; constructor TProjectionJson.Create(const AJson: String); begin inherited Create; FJson := AJson; end; { TProjectionBsonDocument } function TProjectionBsonDocument.Build: TgoBsonDocument; begin Result := FDocument; end; constructor TProjectionBsonDocument.Create(const ADocument: TgoBsonDocument); begin inherited Create; FDocument := ADocument; end; { TProjectionCombine } function TProjectionCombine.Build: TgoBsonDocument; var Projection: TgoMongoProjection.IProjection; RenderedProjection: TgoBsonDocument; Element: TgoBsonElement; begin Result := TgoBsonDocument.Create; for Projection in FProjections do begin RenderedProjection := Projection.Render; for Element in RenderedProjection do begin Result.Remove(Element.Name); Result.Add(Element) end; end; end; constructor TProjectionCombine.Create(const AProjection1, AProjection2: TgoMongoProjection); begin Assert(not AProjection1.IsNil); Assert(not AProjection2.IsNil); inherited Create; SetLength(FProjections, 2); FProjections[0] := AProjection1.FImpl; FProjections[1] := AProjection2.FImpl; end; constructor TProjectionCombine.Create( const AProjections: array of TgoMongoProjection); var I: Integer; begin inherited Create; SetLength(FProjections, Length(AProjections)); for I := 0 to Length(AProjections) - 1 do begin Assert(not AProjections[I].IsNil); FProjections[I] := AProjections[I].FImpl; end; end; { TProjectionSingleField } constructor TProjectionSingleField.Create(const AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; FValue := AValue; end; class function TProjectionSingleField.SupportsWriter: Boolean; begin Result := True; end; procedure TProjectionSingleField.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteValue(FValue); AWriter.WriteEndDocument; end; { TProjectionMultipleFields } constructor TProjectionMultipleFields.Create(const AFieldNames: array of String; const AValue: Integer); var I: Integer; begin inherited Create; FValue := AValue; SetLength(FFieldNames, Length(AFieldNames)); for I := 0 to Length(AFieldNames) - 1 do FFieldNames[I] := AFieldNames[I]; end; class function TProjectionMultipleFields.SupportsWriter: Boolean; begin Result := True; end; procedure TProjectionMultipleFields.Write(const AWriter: IgoBsonBaseWriter); var I: Integer; begin AWriter.WriteStartDocument; for I := 0 to Length(FFieldNames) - 1 do begin AWriter.WriteName(FFieldNames[I]); AWriter.WriteInt32(FValue); end; AWriter.WriteEndDocument; end; { TProjectionElementMatch } function TProjectionElementMatch.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Create(FFieldName, TgoBsonDocument.Create('$elemMatch', FFilter.Render)); end; constructor TProjectionElementMatch.Create(const AFieldName: String; const AFilter: TgoMongoFilter); begin Assert(not AFilter.IsNil); inherited Create; FFieldName := AFieldName; FFilter := AFilter.FImpl; end; { TSortJson } function TSortJson.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Parse(FJson); end; constructor TSortJson.Create(const AJson: String); begin inherited Create; FJson := AJson; end; { TSortBsonDocument } function TSortBsonDocument.Build: TgoBsonDocument; begin Result := FDocument; end; constructor TSortBsonDocument.Create(const ADocument: TgoBsonDocument); begin inherited Create; FDocument := ADocument; end; { TSortCombine } function TSortCombine.Build: TgoBsonDocument; var Sort: TgoMongoSort.ISort; RenderedSort: TgoBsonDocument; Element: TgoBsonElement; begin Result := TgoBsonDocument.Create; for Sort in FSorts do begin RenderedSort := Sort.Render; for Element in RenderedSort do begin Result.Remove(Element.Name); Result.Add(Element) end; end; end; constructor TSortCombine.Create(const ASort1, ASort2: TgoMongoSort); begin Assert(not ASort1.IsNil); Assert(not ASort2.IsNil); inherited Create; SetLength(FSorts, 2); FSorts[0] := ASort1.FImpl; FSorts[1] := ASort2.FImpl; end; constructor TSortCombine.Create(const ASorts: array of TgoMongoSort); var I: Integer; begin inherited Create; SetLength(FSorts, Length(ASorts)); for I := 0 to Length(ASorts) - 1 do begin Assert(not ASorts[I].IsNil); FSorts[I] := ASorts[I].FImpl; end; end; { TSortDirectional } constructor TSortDirectional.Create(const AFieldName: String; const ADirection: TgoMongoSortDirection); begin inherited Create; FFieldName := AFieldName; FDirection := ADirection; end; class function TSortDirectional.SupportsWriter: Boolean; begin Result := True; end; procedure TSortDirectional.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); case FDirection of TgoMongoSortDirection.Ascending: AWriter.WriteInt32(1); TgoMongoSortDirection.Descending: AWriter.WriteInt32(-1); else Assert(False); end; AWriter.WriteEndDocument; end; { TUpdate } function TUpdate.IsCombine: Boolean; begin Result := False; end; { TUpdateJson } function TUpdateJson.Build: TgoBsonDocument; begin Result := TgoBsonDocument.Parse(FJson); end; constructor TUpdateJson.Create(const AJson: String); begin inherited Create; FJson := AJson; end; { TUpdateBsonDocument } function TUpdateBsonDocument.Build: TgoBsonDocument; begin Result := FDocument; end; constructor TUpdateBsonDocument.Create(const ADocument: TgoBsonDocument); begin inherited Create; FDocument := ADocument; end; { TUpdateOperator } constructor TUpdateOperator.Create(const AOperator, AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FOperator := AOperator; FFieldName := AFieldName; FValue := AValue; end; class function TUpdateOperator.SupportsWriter: Boolean; begin Result := True; end; procedure TUpdateOperator.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName(FOperator); AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteValue(FValue); AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TUpdateBitwiseOperator } constructor TUpdateBitwiseOperator.Create(const AOperator, AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FOperator := AOperator; FFieldName := AFieldName; FValue := AValue; end; class function TUpdateBitwiseOperator.SupportsWriter: Boolean; begin Result := True; end; procedure TUpdateBitwiseOperator.Write(const AWriter: IgoBsonBaseWriter); begin AWriter.WriteStartDocument; AWriter.WriteName('$bit'); AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); AWriter.WriteStartDocument; AWriter.WriteName(FOperator); AWriter.WriteValue(FValue); AWriter.WriteEndDocument; AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TUpdateAddToSet } constructor TUpdateAddToSet.Create(const AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; SetLength(FValues, 1); FValues[0] := AValue; end; constructor TUpdateAddToSet.Create(const AFieldName: String; const AValues: array of TgoBsonValue); var I: Integer; begin inherited Create; FFieldName := AFieldName; SetLength(FValues, Length(AValues)); for I := 0 to Length(AValues) - 1 do FValues[I] := AValues[I]; end; class function TUpdateAddToSet.SupportsWriter: Boolean; begin Result := True; end; procedure TUpdateAddToSet.Write(const AWriter: IgoBsonBaseWriter); var I: Integer; begin AWriter.WriteStartDocument; AWriter.WriteName('$addToSet'); AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); if (Length(FValues) = 1) then AWriter.WriteValue(FValues[0]) else begin AWriter.WriteStartDocument; AWriter.WriteName('$each'); AWriter.WriteStartArray; for I := 0 to Length(FValues) - 1 do AWriter.WriteValue(FValues[I]); AWriter.WriteEndArray; AWriter.WriteEndDocument; end; AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TUpdatePull } constructor TUpdatePull.Create(const AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; SetLength(FValues, 1); FValues[0] := AValue; end; constructor TUpdatePull.Create(const AFieldName: String; const AValues: array of TgoBsonValue); var I: Integer; begin inherited Create; FFieldName := AFieldName; SetLength(FValues, Length(AValues)); for I := 0 to Length(AValues) - 1 do FValues[I] := AValues[I]; end; constructor TUpdatePull.Create(const AFieldName: String; const AFilter: TgoMongoFilter); begin inherited Create; FFieldName := AFieldName; FFilter := AFilter; end; class function TUpdatePull.SupportsWriter: Boolean; begin Result := True; end; procedure TUpdatePull.Write(const AWriter: IgoBsonBaseWriter); var RenderedFilter: TgoBsonDocument; I: Integer; begin AWriter.WriteStartDocument; if (FFilter.IsNil) then begin if (Length(FValues) = 1) then AWriter.WriteName('$pull') else AWriter.WriteName('$pullAll'); AWriter.WriteStartDocument; AWriter.WriteName(FFieldName); if (Length(FValues) = 1) then AWriter.WriteValue(FValues[0]) else begin AWriter.WriteStartArray; for I := 0 to Length(FValues) - 1 do AWriter.WriteValue(FValues[I]); AWriter.WriteEndArray; end; AWriter.WriteEndDocument; end else begin RenderedFilter := FFilter.Render; AWriter.WriteStartDocument('$pull'); AWriter.WriteName(FFieldName); AWriter.WriteValue(RenderedFilter); AWriter.WriteEndDocument; end; AWriter.WriteEndDocument; end; { TUpdatePush } constructor TUpdatePush.Create(const AFieldName: String; const AValue: TgoBsonValue); begin inherited Create; FFieldName := AFieldName; SetLength(FValues, 1); FValues[0] := AValue; FSlice := TgoMongoUpdate.NO_SLICE; FPosition := TgoMongoUpdate.NO_POSITION; end; constructor TUpdatePush.Create(const AFieldName: String; const AValues: array of TgoBsonValue; const ASlice, APosition: Integer; const ASort: TgoMongoSort); var I: Integer; begin inherited Create; FFieldName := AFieldName; SetLength(FValues, Length(AValues)); for I := 0 to Length(AValues) - 1 do FValues[I] := AValues[I]; FSlice := ASlice; FPosition := APosition; FSort := ASort; end; class function TUpdatePush.SupportsWriter: Boolean; begin Result := True; end; procedure TUpdatePush.Write(const AWriter: IgoBsonBaseWriter); var I: Integer; RenderedSort: TgoBsonDocument; begin AWriter.WriteStartDocument; AWriter.WriteStartDocument('$push'); AWriter.WriteName(FFieldName); if (FSlice = TgoMongoUpdate.NO_SLICE) and (FPosition = TgoMongoUpdate.NO_POSITION) and (FSort.IsNil) and (Length(FValues) = 1) then AWriter.WriteValue(FValues[0]) else begin AWriter.WriteStartDocument; AWriter.WriteStartArray('$each'); for I := 0 to Length(FValues) - 1 do AWriter.WriteValue(FValues[I]); AWriter.WriteEndArray; if (FSlice <> TgoMongoUpdate.NO_SLICE) then AWriter.WriteInt32('$slice', FSlice); if (FPosition <> TgoMongoUpdate.NO_POSITION) then AWriter.WriteInt32('$position', FPosition); if (not FSort.IsNil) then begin RenderedSort := FSort.Render; AWriter.WriteName('$sort'); AWriter.WriteValue(RenderedSort); end; AWriter.WriteEndDocument; end; AWriter.WriteEndDocument; AWriter.WriteEndDocument; end; { TUpdateCombine } procedure TUpdateCombine.Add(const AUpdate: TgoMongoUpdate.IUpdate); var NewCapacity: Integer; begin if (FCount >= Length(FUpdates)) then begin if (FCount = 0) then NewCapacity := 2 else NewCapacity := FCount * 2; SetLength(FUpdates, NewCapacity); end; FUpdates[FCount] := AUpdate; Inc(FCount); end; function TUpdateCombine.Build: TgoBsonDocument; var I: Integer; Update: TgoMongoUpdate.IUpdate; RenderedUpdate: TgoBsonDocument; Element: TgoBsonElement; CurrentOperatorValue: TgoBsonValue; begin Result := TgoBsonDocument.Create; for I := 0 to FCount - 1 do begin Update := FUpdates[I]; RenderedUpdate := Update.Render; for Element in RenderedUpdate do begin if (Result.TryGetValue(Element.Name, CurrentOperatorValue)) then Result[Element.Name] := CurrentOperatorValue.AsBsonDocument.Merge( Element.Value.AsBsonDocument, True) else Result.Add(Element); end; end; end; constructor TUpdateCombine.Create(const AUpdate1, AUpdate2: TgoMongoUpdate.IUpdate); begin Assert(Assigned(AUpdate1)); Assert(Assigned(AUpdate2)); inherited Create; FCount := 2; SetLength(FUpdates, 2); FUpdates[0] := AUpdate1; FUpdates[1] := AUpdate2; end; constructor TUpdateCombine.Create(const AUpdate1, AUpdate2: TgoMongoUpdate); begin Assert(not AUpdate1.IsNil); Assert(not AUpdate2.IsNil); inherited Create; FCount := 2; SetLength(FUpdates, 2); FUpdates[0] := AUpdate1.FImpl; FUpdates[1] := AUpdate2.FImpl; end; constructor TUpdateCombine.Create(const AUpdates: array of TgoMongoUpdate); var I: Integer; begin inherited Create; FCount := Length(AUpdates); SetLength(FUpdates, FCount); for I := 0 to FCount - 1 do begin Assert(not AUpdates[I].IsNil); FUpdates[I] := AUpdates[I].FImpl; end; end; function TUpdateCombine.IsCombine: Boolean; begin Result := True; end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [CST_ICMS] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit CstIcmsService; interface uses CstIcms, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TCstIcmsService = class(TServiceBase) private public class function ConsultarLista: TObjectList<TCstIcms>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TCstIcms>; class function ConsultarObjeto(AId: Integer): TCstIcms; class procedure Inserir(ACstIcms: TCstIcms); class function Alterar(ACstIcms: TCstIcms): Integer; class function Excluir(ACstIcms: TCstIcms): Integer; end; var sql: string; implementation { TCstIcmsService } class function TCstIcmsService.ConsultarLista: TObjectList<TCstIcms>; begin sql := 'SELECT * FROM CST_ICMS ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TCstIcms>; finally Query.Close; Query.Free; end; end; class function TCstIcmsService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TCstIcms>; begin sql := 'SELECT * FROM CST_ICMS where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TCstIcms>; finally Query.Close; Query.Free; end; end; class function TCstIcmsService.ConsultarObjeto(AId: Integer): TCstIcms; begin sql := 'SELECT * FROM CST_ICMS WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TCstIcms>; end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TCstIcmsService.Inserir(ACstIcms: TCstIcms); begin ACstIcms.ValidarInsercao; ACstIcms.Id := InserirBase(ACstIcms, 'CST_ICMS'); end; class function TCstIcmsService.Alterar(ACstIcms: TCstIcms): Integer; begin ACstIcms.ValidarAlteracao; Result := AlterarBase(ACstIcms, 'CST_ICMS'); end; class function TCstIcmsService.Excluir(ACstIcms: TCstIcms): Integer; begin ACstIcms.ValidarExclusao; Result := ExcluirBase(ACstIcms.Id, 'CST_ICMS'); end; end.
unit AlbumsController; interface uses MediaFile, Generics.Collections, Aurelius.Engine.ObjectManager; type TAlbumsController = class private FManager: TObjectManager; public constructor Create; destructor Destroy; override; procedure DeleteAlbum(Album: TAlbum); function GetAllAlbums: TList<TAlbum>; end; implementation uses DBConnection; { TAlbunsController } constructor TAlbumsController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TAlbumsController.DeleteAlbum(Album: TAlbum); begin if not FManager.IsAttached(Album) then Album := FManager.Find<TAlbum>(Album.Id); FManager.Remove(Album); end; destructor TAlbumsController.Destroy; begin FManager.Free; inherited; end; function TAlbumsController.GetAllAlbums: TList<TAlbum>; begin FManager.Clear; Result := FManager.FindAll<TAlbum>; end; end.
unit HackingHealthLogic; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses FHIRResources, CDSHooksServer; type THackingHealthBNPLogic = class (TCDSHooksProcessor) private function aTestIsBNP : boolean; function clinicIsED : boolean; function hasDyspnoea : boolean; function isDyspnoea(cond : TFhirCondition) : boolean; public function execute : boolean; override; end; implementation { THackingHealthBNPLogic } function THackingHealthBNPLogic.aTestIsBNP: boolean; var res : TFHIRResource; req : TFhirProcedureRequest; begin result := false; for res in request.context do if res is TFhirProcedureRequest then begin req := res as TFhirProcedureRequest; if req.code.text = 'BNP' then exit(true); end; end; function THackingHealthBNPLogic.clinicIsED: boolean; var enc : TFhirEncounter; begin if not request.preFetch.ContainsKey('encounter') then result := false else begin enc := request.preFetch['encounter'].resource as TFhirEncounter; result := (enc.class_ <> nil) and (enc.class_.code = 'emergency'); end; end; function THackingHealthBNPLogic.execute: boolean; begin result := false; if (aTestIsBNP) then begin if not clinicIsED then addCard('BNP will not be paid by Medicare because this is not an emergency presentation', '', 'warning', 'MBS rules', '') else if not hasDyspnoea then addCard('BNP will not be paid by Medicare if the patient does not have Dyspnoea', '', 'warning', 'MBS rules', ''); end; end; function THackingHealthBNPLogic.hasDyspnoea: boolean; var bnd : TFhirBundle; be : TFhirBundleEntry; begin bnd := request.preFetch['problems'].resource as TFhirBundle; result := false; for be in bnd.entryList do if (be.resource <> nil) and (be.resource is TFhirCondition) then if isDyspnoea(be.resource as TFhirCondition) then exit(true); end; function THackingHealthBNPLogic.isDyspnoea(cond: TFhirCondition): boolean; begin result := cond.code.text = 'Dyspnoea'; end; end.
unit uDocument; interface uses SysUtils, Windows, Classes, XMLIntf, XMLDoc, uTypes, Generics.Collections, Generics.Defaults; type eEgaisDocumentType = (edtUnknown, edtInbox, edtOutbox); const eWayBillTTNTypes: array[0..3] of String = ('WBInvoiceFromMe', 'WBInvoiceToMe', 'WBReturnFromMe', 'WBReturnToMe'); const eWayBillUnitTypes: array[0..1] of String = ('Packed','Unpacked'); type eEgaisDocumentDirectionType =(WBInvoiceFromMe, WBInvoiceToMe, WBReturnFromMe, WBReturnToMe); type eEgaisDocumentStatus =(edsUnknown, edsNew, edsLoaded, edsActUploaded, edsActAccepted, edsClosed, edsRejected, edsUploaded, edsUploadedChecked, edsPosted, edsError); type eEgaisDocumentResult =(edrNone, edrActAccept, edrActEdit, edrActReject, edrAccepted, edrChipperReject); type TEgaisDocument = class type TRegInfo = class Identity: String; WBRegId: String; FixNumber: String; FixDate: TDate; WBNUMBER: String; WBDate: TDate; end; public DocumentType: eEgaisDocumentType; DocumentStatus: eEgaisDocumentStatus; DocumentResult: eEgaisDocumentResult; SystemComment: String; Identity: String; ClientNumber: String; DocumentDate: TDate; ShippingDate: TDate; TTNType: Integer; UnitType: Integer; Shipper: TContragent; Consignee: TContragent; Content: TList<TPositionType>; Transport: TTransport; ReplyID: String; REGINFO: TRegInfo; class function GetHumanityStatusName(EnumIndex:Integer): String; class function GetHumanityDocTypeName(EnumIndex:Integer): String; class function GetHumanityeDocResultName(EnumIndex:Integer): String; private docPassword: String; fileStream: TFileStream; published constructor Create; overload; end; type TTicket = class type TTicketResultType = class Conclusion: string; ConclusionDate: string; Comments: string; end; type TOperationResultType = class OperationName: string; OperationResult: string; OperationDate: string; OperationComment: string; end; public Owner: string; TicketDate: String; Identity: String; DocId: String; TransportId: String; RegID: string; DocHash: string; DocType: string; Result: TTicketResultType; OperationResult: TOperationResultType; end; type TAct = class type TActType = (artNone, artAccepted, artRejected, artEdit); public Owner: string; ActType: TActType; Date: TDate; Number: string; WBRegId: String; Note: String; Content: TList<TPositionType>; end; implementation uses uLog, uCrypt; constructor TEgaisDocument.Create; begin REGINFO:= TRegInfo.Create; Content:= TList<TPositionType>.Create; end; class function TEgaisDocument.GetHumanityStatusName(EnumIndex:Integer): String; begin case EnumIndex of 0: Result:= 'Неизвестно'; 1: Result:= 'Новый'; 2: Result:= 'Загружен'; 3: Result:= 'Акт отправлен'; 4: Result:= 'Акт подтвержден'; 5: Result:= 'Закрыт'; 6: Result:= 'Отказан'; 7: Result:= 'Отправлен'; 8: Result:= 'Проверен'; 9: Result:= 'Проведен'; 10:Result:= 'Ошибка'; end; end; class function TEgaisDocument.GetHumanityDocTypeName(EnumIndex:Integer): String; begin case EnumIndex of 0: Result:= 'Неизвестно'; 1: Result:= 'Входящий'; 2: Result:= 'Исходящий'; end; end; class function TEgaisDocument.GetHumanityeDocResultName(EnumIndex:Integer): String; begin case EnumIndex of 0: Result:= 'Нет'; 1: Result:= 'Подтвержден'; 2: Result:= 'Расхождение'; 3: Result:= 'Отказ'; 4: Result:= 'Одобрен'; 5: Result:= 'Отказ пост.'; end; end; end.
unit ParseError; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is ParseError, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2000 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"). you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/NPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. ------------------------------------------------------------------------------*) {*)} interface uses {delphi } SysUtils, { local } SourceToken; type TEParseError = class(Exception) private fcToken: TSourceToken; fiXPosition, fiYPosition: integer; fsFileName: string; function GetTokenMessage: string; public constructor Create(const psMessage: string; const pcToken: TSourceToken); property FileName: string Read fsFileName Write fsFileName; property TokenMessage: string Read GetTokenMessage; property XPosition: integer Read fiXPosition; property YPosition: integer Read fiYPosition; end; implementation { TEParseError } constructor TEParseError.Create(const psMessage: string; const pcToken: TSourceToken); begin inherited Create(psMessage); fcToken := pcToken; if pcToken <> nil then begin fiXPosition := pcToken.XPosition; fiYPosition := pcToken.YPosition; end else begin fiXPosition := -1; fiYPosition := -1; end; end; function TEParseError.GetTokenMessage: string; begin if fcToken = nil then Result := '' else Result := fcToken.Describe; end; end.
{$mode TP} {$R+,B+,X-} {$codepage UTF-8} program T_11_55(input, output); var i, n, pr: integer; function prime(x: integer): boolean; var i: integer; p: boolean; begin i := 2; p := true; while (i * i <= x) and p do begin p := x mod i <> 0; i := i + 1 end; prime := p end; begin writeln('Зянчурин Игорь, 110, 11.55'); writeln('Введите число n: '); readln(n); writeln('Простые числа "близнецы" из [2,n]: '); pr := -10; for i := 2 to n - 2 do if prime(i) then begin if i = pr + 2 then writeln(pr, ' ', i); pr := i; end; end.
{******************************************************************************* * * * PentireFMX * * * * https://github.com/gmurt/PentireFMX * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksInputList; interface uses System.Classes, FMX.Controls, FMX.InertialMovement, System.Types, System.Generics.Collections, FMX.Graphics, System.UITypes, FMX.Layouts, FMX.Types, FMX.Objects, FMX.Edit, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ListBox, Json, FMX.Pickers, System.UIConsts, FMX.TextLayout, FMX.Forms; {.$DEFINE DEBUG_BOXES} const C_DEFAULT_SEPERATOR_HEIGHT = 44; type TksInputList = class; TksBaseInputListItem = class; TksInputListSelectorItem = class; TksInputListEditItem = class; TksInputListSwitchItem = class; TksInputListCheckBoxItem = class; TksInputListButtonItem = class; TksInputListTrackBarItem = class; TksInputListDateTimeSelectorItem = class; TksInputAccessoryType = (atNone, atMore, atCheckmark, atDetail); TksInputListItemClickEvent = procedure(Sender: TObject; AItem: TksBaseInputListItem; AID: string) of object; TksInputListItemLongTapEvent = procedure(Sender: TObject; AItem: TksBaseInputListItem; AID: string) of object; TksInputListSelectorItemChangeEvent = procedure(Sender: TObject; AItem: TksInputListSelectorItem; AID, AValue: string) of object; TksInputListDateTimeSelectedEvent = procedure(Sender: TObject; AItem: TksInputListDateTimeSelectorItem; AID: string; ADateTime: TDateTime) of object; TksInputListEditTextChangeEvent = procedure(Sender: TObject; AItem: TksInputListEditItem; AID, AText: string) of object; TksInputListSwitchChangeEvent = procedure(Sender: TObject; AItem: TksInputListSwitchItem; AID: string; AIsChecked: Boolean) of object; TksInputListCheckBoxChangeEvent = procedure(Sender: TObject; AItem: TksInputListCheckBoxItem; AID: string; AIsChecked: Boolean) of object; TksInputListButtonClickEvent = procedure(Sender: TObject; AItem: TksInputListButtonItem; AID: string) of object; TksInputListTrackBarItemEvent = procedure(Sender: TObject; AItem: TksInputListTrackBarItem; AID: string; AValue: single) of object; TksInputListPaintItemEvent = procedure(Sender: TObject; ACanvas: TCanvas; AItemRect: TRectF; AIndex: integer) of object; TksBaseInputListItem = class private FksInputList: TksInputList; FEnabled: Boolean; FItemID: string; FFont: TFont; FItemRect: TRectF; FImageRect: TRectF; FContentRect: TRectF; FAccessoryRect: TRectF; FAccessory: TksInputAccessoryType; FBackground: TAlphaColor; FHeight: single; FIndex: integer; FTitle: string; FDetail: string; FImage: TBitmap; FMouseDown: Boolean; FOnChange: TNotifyEvent; FSelected: Boolean; FShowSelection: Boolean; FSelectedColor: TAlphaColor; FTagStr: string; FTagInt: integer; FReadOnly: Boolean; FTextColor: TAlphaColor; FDetailTextColor: TAlphaColor; FSlideButtonWidth: integer; function GetItemRect: TRectF; function GetAccessoryWidth(const AAddPadding: Boolean = False): single; procedure SetTitle(const Value: string); procedure SetHeight(const Value: Single); procedure SetBackgroundColor(const Value: TAlphaColor); procedure SetSelected(const Value: Boolean); procedure SetShowSelection(const Value: Boolean); procedure SetAccessory(const Value: TksInputAccessoryType); procedure SetDetail(const Value: string); procedure SetEnabled(const Value: Boolean); procedure DrawDisabledRect(ACanvas: TCanvas); procedure SetTextColor(const Value: TAlphaColor); procedure SetSelectedColor(const Value: TAlphaColor); procedure SetDetailTextColor(const Value: TAlphaColor); protected class function GetClassID: string; virtual; abstract; function GetHeight: Single; virtual; function GetDetailTextColor: TAlphaColor; virtual; function GetValue: string; virtual; procedure SetValue(const AValue: string); virtual; procedure SaveStructure(AJson: TJsonObject); virtual; procedure LoadStructure(AJson: TJSONObject); virtual; procedure UpdateRects; virtual; procedure MouseDown; virtual; procedure ItemClick; virtual; procedure MouseUp(ATapEvent: Boolean); virtual; procedure Changed; virtual; procedure Reset; virtual; procedure DoCustomDraw(ACanvas: TCanvas); virtual; property ItemRect: TRectF read GetItemRect; procedure SetReadOnly(const Value: Boolean); virtual; property OnChange: TNotifyEvent read FOnChange write FOnChange; procedure ShowSwipeButtons; procedure HideSwipeButtons; public constructor Create(AInputList: TksInputList); virtual; destructor Destroy; override; procedure DrawToCanvas(ACanvas: TCanvas); virtual; procedure DrawSeparators(ACanvas: TCanvas; ATop, ABottom: Boolean); procedure SaveToJson(AJson: TJsonObject; AStructure, AData: Boolean); procedure LoadFromJson(AJson: TJsonObject; AStructure, AData: Boolean); property Accessory: TksInputAccessoryType read FAccessory write SetAccessory; property BackgroundColor: TAlphaColor read FBackground write SetBackgroundColor; property TextColor: TAlphaColor read FTextColor write SetTextColor; property DetailTextColor: TAlphaColor read FDetailTextColor write SetDetailTextColor; property Image: TBitmap read FImage; property Height: Single read GetHeight write SetHeight; property Title: string read FTitle write SetTitle; property Detail: string read FDetail write SetDetail; property ClassID: string read GetClassID; property ID: string read FItemID write FItemID; property Value: string read GetValue write SetValue; property TagStr: string read FTagStr write FTagStr; property TagInt: integer read FTagInt write FTagInt; property Selected: Boolean read FSelected write SetSelected default False; property ShowSelection: Boolean read FShowSelection write SetShowSelection default False; property SelectedColor: TAlphaColor read FSelectedColor write SetSelectedColor; property Enabled: Boolean read FEnabled write SetEnabled default True; property ReadOnly: Boolean read FReadOnly write SetReadOnly default False; end; TksInputListSeperator = class(TksBaseInputListItem) private FHorzAlign: TTextAlign; procedure SetHorzAlign(const Value: TTextAlign); protected class function GetClassID: string; override; function GetValue: string; override; public constructor Create(AInputList: TksInputList); override; procedure DrawToCanvas(ACanvas: TCanvas); override; property HorzAlign: TTextAlign read FHorzAlign write SetHorzAlign default TTextAlign.Leading; end; TksInputListItem = class(TksBaseInputListItem) protected class function GetClassID: string; override; procedure UpdateRects; override; public procedure DrawToCanvas(ACanvas: TCanvas); override; property Accessory; property BackgroundColor; property ItemRect; property Selected; property ShowSelection; end; TksInputListBadgeItem = class(TksInputListItem) private FBadgeColor: TAlphaColor; FBadgeTextColor: TAlphaColor; procedure SetBadgeColor(const Value: TAlphaColor); protected class function GetClassID: string; override; function GetDetailTextColor: TAlphaColor; override; public constructor Create(AInputList: TksInputList); override; procedure DrawToCanvas(ACanvas: TCanvas); override; property BadgeColor: TAlphaColor read FBadgeColor write SetBadgeColor default claDodgerBlue; property BadgeTextColor: TAlphaColor read FBadgeTextColor write FBadgeTextColor default claWhite; end; TksInputListChatItem = class(TksInputListItem) private FColor: TAlphaColor; FTextColor: TAlphaColor; FSender: string; FBody: string; FDateTime: TDateTime; FCached: TBitmap; FAlignment: TTextAlign; FUse24HourTime: Boolean; function IsEmojiOnly: Boolean; procedure SetSender(const Value: string); procedure SetDateTime(const Value: TDateTime); procedure SetBody(const Value: string); function CalculateHeight: single; procedure SetAlignment(const Value: TTextAlign); procedure SetUse24HourTime(const Value: Boolean); protected class function GetClassID: string; override; procedure UpdateRects; override; function GetHeight: Single; override; procedure MouseDown; override; public constructor Create(AInputList: TksInputList); override; destructor Destroy; override; procedure DrawToCanvas(ACanvas: TCanvas); override; property Color: TAlphaColor read FColor write FColor default claDodgerBlue; property TextColor: TAlphaColor read FTextColor write FTextColor default claWhite; property DateTime: TDateTime read FDateTime write SetDateTime; property Sender: string read FSender write SetSender; property Body: string read FBody write SetBody; property Alignment: TTextAlign read FAlignment write SetAlignment default TTextAlign.Leading; property Use24HourTime: Boolean read FUse24HourTime write SetUse24HourTime default True; end; TksInputListItemWithControl = class(TksInputListItem) private FControl: TPresentedControl; FCached: TBitmap; FControlRect: TRectF; FFullWidthSelect: Boolean; protected procedure UpdateRects; override; function CreateControl: TPresentedControl; virtual; abstract; procedure PaintControl(ACanvas: TCanvas); virtual; procedure UpdateControlPosition; procedure ClickControl; virtual; procedure Changed; override; procedure Reset; override; procedure ItemClick; override; public constructor Create(AInputList: TksInputList); override; destructor Destroy; override; procedure ClearCache; procedure DrawToCanvas(ACanvas: TCanvas); override; end; // inherited to allow access to protected methods. TksEdit = class(TEdit); TksInputListEditItem = class(TksInputListItemWithControl) private function GetEdit: TksEdit; procedure TextChange(Sender: TObject); protected class function GetClassID: string; override; procedure SetReadOnly(const Value: Boolean); override; procedure SaveStructure(AJson: TJsonObject); override; procedure LoadStructure(AJson: TJSONObject); override; function GetValue: string; override; procedure SetValue(const AValue: string); override; function CreateControl: TPresentedControl; override; procedure Reset; override; procedure ClickControl; override; procedure MouseDown; override; public procedure DrawToCanvas(ACanvas: TCanvas); override; property Edit: TksEdit read GetEdit; end; TksInputListSwitchItem = class(TksInputListItemWithControl) private function GetSwitch: TSwitch; procedure SwitchChange(Sender: TObject); function GetIsChecked: Boolean; procedure SetIsChecked(const Value: Boolean); protected function GetValue: string; override; procedure SetValue(const AValue: string); override; function CreateControl: TPresentedControl; override; class function GetClassID: string; override; procedure Reset; override; public constructor Create(AInputList: TksInputList); override; property IsChecked: Boolean read GetIsChecked write SetIsChecked; end; TksInputListCheckBoxItem = class(TksInputListItemWithControl) private FRadioGroupID: string; function GetCheckBox: TCheckBox; procedure CheckBoxChange(Sender: TObject); procedure SetRadioGroupID(const Value: string); protected function CreateControl: TPresentedControl; override; class function GetClassID: string; override; function GetValue: string; override; procedure SetValue(const AValue: string); override; procedure ClickControl; override; procedure Reset; override; public constructor Create(AInputList: TksInputList); override; property CheckBox: TCheckBox read GetCheckBox; property RadioGroupID: string read FRadioGroupID write SetRadioGroupID; end; TksInputListButtonItem = class(TksInputListItemWithControl) private function GetButton: TButton; procedure DoButtonClick(Sender: TObject); protected function CreateControl: TPresentedControl; override; procedure SaveStructure(AJson: TJsonObject); override; procedure LoadStructure(AJson: TJSONObject); override; class function GetClassID: string; override; procedure ClickControl; override; public property Button: TButton read GetButton; end; // inherited to allow access to protected methods. TksTrackBar = class(TTrackBar); TksInputListTrackBarItem = class(TksInputListItemWithControl) private function GetTrackBar: TksTrackBar; procedure TrackBarChange(Sender: TObject); protected function CreateControl: TPresentedControl; override; class function GetClassID: string; override; function GetValue: string; override; procedure SetValue(const AValue: string); override; procedure PaintControl(ACanvas: TCanvas); override; procedure Reset; override; public constructor Create(AInputList: TksInputList); override; property TrackBar: TksTrackBar read GetTrackBar; end; TksInputListImageItem = class(TksInputListItem) protected class function GetClassID: string; override; procedure UpdateRects; override; procedure DoCustomDraw(ACanvas: TCanvas); override; public constructor Create(AInputList: TksInputList); override; destructor Destroy; override; procedure DrawToCanvas(ACanvas: TCanvas); override; end; TksInputListSelectorItem = class(TksBaseInputListItem) private FItems: TStrings; FCombo: TComboBox; FValue: string; procedure DoSelectorChanged(Sender: TObject); procedure SetItems(const Value: TStrings); protected function GetValue: string; override; procedure SetValue(const Value: string); override; procedure SaveStructure(AJson: TJsonObject); override; procedure LoadStructure(AJson: TJSONObject); override; procedure MouseUp(ATapEvent: Boolean); override; class function GetClassID: string; override; procedure Reset; override; public constructor Create(AInputList: TksInputList); override; destructor Destroy; override; property Items: TStrings read FItems write SetItems; property Value: string read GetValue write SetValue; end; TksDateTimeSelectorKind = (ksDateSelector, ksTimeSelector); TksInputListDateTimeSelectorItem = class(TksBaseInputListItem) private FPickerService: IFMXPickerService; FDateTimePicker: TCustomDateTimePicker; FDateTime: TDateTime; FKind: TksDateTimeSelectorKind; function GetDateTime: TDateTime; procedure SetDateTime(const AValue: TDateTime); procedure DoSelectDateTime(Sender: TObject; const ADateTime: TDateTime); procedure SetKind(const Value: TksDateTimeSelectorKind); protected function GetValue: string; override; procedure SetValue(const Value: string); override; procedure SaveStructure(AJson: TJsonObject); override; procedure LoadStructure(AJson: TJSONObject); override; procedure MouseUp(ATapEvent: Boolean); override; class function GetClassID: string; override; procedure Reset; override; public constructor Create(AInputList: TksInputList); override; destructor Destroy; override; property DateTime: TDateTime read GetDateTime write SetDateTime; property Kind: TksDateTimeSelectorKind read FKind write SetKind; end; TksInputListItems = class(TObjectList<TksBaseInputListItem>) private FksInputList: TksInputList; function GetItemByID(AID: string): TksBaseInputListItem; function GetCheckedCount: integer; public constructor Create(AForm: TksInputList); virtual; procedure ItemChange(Sender: TObject); procedure DrawToCanvas(ACanvas: TCanvas; AViewPort: TRectF); procedure DeselectAll; function AddSeperator(ATitle: string; const AHeight: integer = C_DEFAULT_SEPERATOR_HEIGHT): TksInputListSeperator; function AddItem(AID: string; AImg: TBitmap; ATitle: string; const AAccessory: TksInputAccessoryType = atNone): TksInputListItem; procedure Insert(Index: Integer; const Value: TksBaseInputListItem); overload; function AddEditBoxItem(AID: string; AImg: TBitmap; ATitle: string; AValue: string; APlaceholder: string; const AKeyboard: TVirtualKeyboardType = TVirtualKeyboardType.Default): TksInputListEditItem; function AddSwitchItem(AID: string; AImg: TBitmap; ATitle: string; AState: Boolean): TksInputListSwitchItem; function AddCheckBoxItem(AID: string; AImg: TBitmap; ATitle: string; AState: Boolean): TksInputListCheckBoxItem; procedure AddButtonItem(AID: string; AImg: TBitmap; ATitle, AButtonTitle: string); procedure AddTrackBar(AID: string; AImg: TBitmap; ATitle: string; APos, AMax: integer); function AddImageItem(AID: string; AImg: TBitmap): TksInputListImageItem; function AddItemSelector(AID: string; AImg: TBitmap; ATitle, ASelected: string; AItems: array of string): TksInputListSelectorItem overload; function AddItemSelector(AID: string; AImg: TBitmap; ATitle, ASelected: string; AItems: TStrings): TksInputListSelectorItem overload; function AddDateSelector(AID: string; AImg: TBitmap; ATitle: string; ASelected: TDateTime): TksInputListDateTimeSelectorItem overload; function AddTimeSelector(AID: string; AImg: TBitmap; ATitle: string; ASelected: TDateTime): TksInputListDateTimeSelectorItem overload; function AddRadioItem(AID: string; AImage: TBitmap; AGroupID, ATitle: string; AChecked: Boolean): TksInputListCheckBoxItem; function AddBadgeItem(AID: string; AImage: TBitmap; ATitle, AValue: string; ABadgeColor, ABadgeTextColor: TAlphaColor; const AAccessory: TksInputAccessoryType = atNone): TksInputListBadgeItem; function AddChatItem(AID, ASender, AText: string; ADateTime: TDateTime; AAlign: TTextAlign; AColor, ATextColor: TAlphaColor; const AUse24HourTime: Boolean = True): TksInputListChatItem; function ItemExists(AID: string): Boolean; property CheckedCount: integer read GetCheckedCount; property ItemByID[AID: string]: TksBaseInputListItem read GetItemByID; end; TksInputListCanvas = class(TPaintBox) protected procedure Paint; override; end; [ComponentPlatformsAttribute(pidAllPlatforms)] TksInputList = class(TVertScrollBox) private FBuffer: TForm; FScrollMonitor: TThread; FPickerService: IFMXPickerService; FCanvas: TksInputListCanvas; FItems: TksInputListItems; FLastScrollPos: single; FControlsVisible: Boolean; FUpdateCount: integer; FLastScrollChange: TDateTime; FMouseDownTime: Cardinal; FMouseDownPos: TPointF; FMousePos: TPointF; FMouseDownItem: TksBaseInputListItem; FOnSelectorItemSelected: TksInputListSelectorItemChangeEvent; FOnDateTimeSelected: TksInputListDateTimeSelectedEvent; FOnEditItemTextChange: TksInputListEditTextChangeEvent; FOnItemClick: TksInputListItemClickEvent; FOnItemLongTap: TksInputListItemLongTapEvent; FOnSwitchChange: TksInputListSwitchChangeEvent; FOnCheckBoxChange: TksInputListCheckBoxChangeEvent; FOnItemButtonClick: TksInputListButtonClickEvent; FOnItemTrackBarChange: TksInputListTrackBarItemEvent; FItemHeight: single; FShowDividers: Boolean; FBackgroundColor: TAlphaColor; FMouseDown: Boolean; FOnPaintItem: TksInputListPaintItemEvent; procedure UpdateItemRects; procedure RedrawItems; procedure CreateScrollMonitor; function GetIsScrolling: Boolean; procedure HidePickers; function GetValue(AName: string): string; procedure SetItemHeight(const Value: single); function GetAsJson(AStructure, AData: Boolean): string; procedure SetValue(AName: string; const Value: string); procedure SetShowDividers(const Value: Boolean); procedure SetBackgroundColor(const Value: TAlphaColor); procedure SwipeLeft(AEventInfo: TGestureEventInfo); procedure SwipeRight(AEventInfo: TGestureEventInfo); //function ItemAtPos(x, y: Extended): TksBaseInputListItem; procedure HideAllSwipeButtons(AIgnoreItem: TksBaseInputListItem); protected procedure Paint; override; procedure Resize; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure ViewportPositionChange(const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: boolean); override; procedure CMGesture(var EventInfo: TGestureEventInfo); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowOnScreenControls; procedure HideAllControls; procedure BeginUpdate; override; procedure EndUpdate; override; procedure ClearItems; procedure Reset; procedure EnableAll; procedure DisableAll; procedure LoadFromJson(AJsonData: string; AStructure: Boolean; AData: Boolean); overload; procedure LoadFromJson(AJson: TJsonObject; AStructure: Boolean; AData: Boolean); overload; procedure SaveToJson(AJson: TJsonObject; AStructure: Boolean; AData: Boolean); overload; procedure ScrollToTop(const AAnimated: Boolean = False); procedure ScrollToBottom(const AAnimated: Boolean = False); property IsScrolling: Boolean read GetIsScrolling; property Items: TksInputListItems read FItems; property Value[AName: string]: string read GetValue write SetValue; property AsJson[AStructure, AData: Boolean]: string read GetAsJson; published property VScrollBar; property BackgroundColor: TAlphaColor read FBackgroundColor write SetBackgroundColor default claNull; property ShowDividers: Boolean read FShowDividers write SetShowDividers default True; property ItemHeight: single read FItemHeight write SetItemHeight; property OnItemClick: TksInputListItemClickEvent read FOnItemClick write FOnItemClick; property OnItemLongTapClick: TksInputListItemLongTapEvent read FOnItemLongTap write FOnItemLongTap; property OnSelectorItemSelected: TksInputListSelectorItemChangeEvent read FOnSelectorItemSelected write FOnSelectorItemSelected; property OnDateTimeSelected: TksInputListDateTimeSelectedEvent read FOnDateTimeSelected write FOnDateTimeSelected; property OnEditItemTextChange: TksInputListEditTextChangeEvent read FOnEditItemTextChange write FOnEditItemTextChange; property OnItemSwitchChanged: TksInputListSwitchChangeEvent read FOnSwitchChange write FOnSwitchChange; property OnItemCheckBoxChanged: TksInputListCheckBoxChangeEvent read FOnCheckBoxChange write FOnCheckBoxChange; property OnItemButtonClick: TksInputListButtonClickEvent read FOnItemButtonClick write FOnItemButtonClick; property OnItemTrackBarChange: TksInputListTrackBarItemEvent read FOnItemTrackBarChange write FOnItemTrackBarChange; property OnPaintItem: TksInputListPaintItemEvent read FOnPaintItem write FOnPaintItem; end; procedure Register; implementation uses SysUtils, FMX.DialogService, DateUtils, FMX.Ani, Math, FMX.Styles, FMX.Styles.Objects, System.NetEncoding, FMX.Platform, System.Character; const C_CORNER_RADIUS = 12; C_DEFAULT_ITEM_HEIGHT = 44; {$IFDEF MSWINDOWS} C_RIGHT_MARGIN = 20; {$ELSE} C_RIGHT_MARGIN = 8; {$ENDIF} type TInputListAccessoryImage = class private FAccessoryType: TksInputAccessoryType; FBitmap: TBitmap; private constructor Create(AType: TksInputAccessoryType; ABmp: TBitmap); virtual; destructor Destroy; override; property AccessoryType: TksInputAccessoryType read FAccessoryType; property Bitmap: TBitmap read FBitmap; end; TInputListAccessoryImages = class(TObjectList<TInputListAccessoryImage>) private function GetItemByAccessory(AType: TksInputAccessoryType): TInputListAccessoryImage; public constructor Create; virtual; property ItemByAccessory[AType: TksInputAccessoryType]: TInputListAccessoryImage read GetItemByAccessory; end; var //TempForm: TForm; AAccessoriesList: TInputListAccessoryImages; ATextLayout: TTextLayout; AScreenScale: single; procedure Register; begin RegisterComponents('Pentire FMX', [TksInputList]); end; function GetScreenScale: single; var Service: IFMXScreenService; begin if AScreenScale > 0 then begin Result := AScreenScale; Exit; end else begin Service := IFMXScreenService(TPlatformServices.Current.GetPlatformService(IFMXScreenService)); Result := Service.GetScreenScale; {$IFDEF IOS} if Result < 2 then Result := 2; AScreenScale := Result; {$ENDIF} end; {$IFDEF ANDROID} AScreenScale := Result; {$ENDIF} end; function AccessoryToStr(AAcc: TksInputAccessoryType): string; begin Result := ''; case AAcc of atMore: Result := 'more'; atCheckmark: Result := 'checkmark'; atDetail: Result := 'detail'; end; end; function StrToAccessory(AAcc: string): TksInputAccessoryType; begin AAcc := Trim(AAcc.ToLower); Result := atNone; if AAcc = 'more' then Result := atMore; if AAcc = 'checkmark' then Result := atCheckmark; if AAcc = 'detail' then Result := atDetail; end; function CreateListItem(AInputList: TksInputList; AClassID: string): TksBaseInputListItem; begin Result := nil; if AClassID = TksInputListSeperator.GetClassID then Result := TksInputListSeperator.Create(AInputList); if AClassID = TksInputListItem.GetClassID then Result := TksInputListItem.Create(AInputList); if AClassID = TksInputListEditItem.GetClassID then Result := TksInputListEditItem.Create(AInputList); if AClassID = TksInputListSwitchItem.GetClassID then Result := TksInputListSwitchItem.Create(AInputList); if AClassID = TksInputListCheckBoxItem.GetClassID then Result := TksInputListCheckBoxItem.Create(AInputList); if AClassID = TksInputListButtonItem.GetClassID then Result := TksInputListButtonItem.Create(AInputList); if AClassID = TksInputListTrackBarItem.GetClassID then Result := TksInputListTrackBarItem.Create(AInputList); if AClassID = TksInputListSelectorItem.GetClassID then Result := TksInputListSelectorItem.Create(AInputList); end; function BmpToBase64(AImg: TBitmap): string; var AStream: TMemoryStream; AEncoded: TStringStream; begin AStream := TMemoryStream.Create; AEncoded := TStringStream.Create; try if AImg <> nil then AImg.SaveToStream(AStream); AStream.Position := 0; TNetEncoding.Base64.Encode(AStream, AEncoded); Result := AEncoded.DataString; finally AStream.Free; AEncoded.Free; end; end; procedure Base64ToBmp(AData: string; AImg: TBitmap); var AStream: TMemoryStream; AEncoded: TStringStream; begin AEncoded := TStringStream.Create(AData); AStream := TMemoryStream.Create; try AEncoded.Position := 0; TNetEncoding.Base64.Decode(AEncoded, AStream); AStream.Position := 0; AImg.LoadFromStream(AStream); finally AStream.Free; AEncoded.Free; end; end; function TryGetBoolFromString(AValue: string): Boolean; var AStrings: TStrings; begin AValue := AValue.ToLower; AStrings := TStringList.Create; try AStrings.CommaText := 'y,yes,t,true,1,on,checked'; Result := AStrings.IndexOf(AValue) > -1; finally AStrings.Free; end; end; function GetAccessoryFromResource(AStyleName: array of string; const AState: string = ''): TBitmap; var AStyleObj: TStyleObject; AImgRect: TBounds; r: TRectF; ABitmapLink: TBitmapLinks; AImageMap: TBitmap; I: integer; AScale: single; ICount: integer; AMap: TBitmap; begin AMap := TBitmap.Create; Result := TBitmap.Create; AScale := GetScreenScale; AStyleObj := TStyleObject(TStyleManager.ActiveStyle(nil)); for ICount := Low(AStyleName) to High(AStyleName) do AStyleObj := TStyleObject(AStyleObj.FindStyleResource(AStyleName[ICount])); if AStyleObj <> nil then begin if AMap.IsEmpty then begin for i := 0 to (AStyleObj as TStyleObject).Source.MultiResBitmap.Count-1 do begin AScale := (AStyleObj as TStyleObject).Source.MultiResBitmap[i].Scale; if Round(AScale) <= AScale then begin AScale := Round(AScale); Break; end; end; AImageMap := ((AStyleObj as TStyleObject).Source.MultiResBitmap.Bitmaps[AScale]); AMap.SetSize(Round(AImageMap.Width), Round(AImageMap.Height)); AMap.Clear(claNull); AMap.Canvas.BeginScene; try AMap.Canvas.DrawBitmap(AImageMap, RectF(0, 0, AImageMap.Width, AImageMap.Height), RectF(0, 0, AMap.Width, AMap.Height), 1, True); finally AMap.Canvas.EndScene; end; end; ABitmapLink := nil; if AStyleObj = nil then Exit; if (AStyleObj.ClassType = TCheckStyleObject) then begin if AState = 'checked' then ABitmapLink := TCheckStyleObject(AStyleObj).ActiveLink else ABitmapLink := TCheckStyleObject(AStyleObj).SourceLink end; if ABitmapLink = nil then ABitmapLink := AStyleObj.SourceLink; AImgRect := ABitmapLink.LinkByScale(AScale, True).SourceRect; Result.SetSize(Round(AImgRect.Width), Round(AImgRect.Height)); Result.Clear(claNull); Result.Canvas.BeginScene; r := AImgRect.Rect; Result.Canvas.DrawBitmap(AMap, r, RectF(0, 0, Result.Width, Result.Height), 1, True); Result.Canvas.EndScene; end; AMap.Free; end; { TksInputList } procedure TksInputList.BeginUpdate; begin //inherited; Inc(FUpdateCount); end; procedure TksInputList.ClearItems; begin HideAllControls; BeginUpdate; try FItems.Clear; finally EndUpdate; end; end; procedure TksInputList.CMGesture(var EventInfo: TGestureEventInfo); begin inherited; if EventInfo.GestureID = 1 then SwipeLeft(EventInfo); if EventInfo.GestureID = 2 then SwipeRight(EventInfo); end; constructor TksInputList.Create(AOwner: TComponent); begin inherited; FBuffer := TForm.CreateNew(nil); FPickerService := nil; TPlatformServices.Current.SupportsPlatformService(IFMXPickerService, FPickerService); FControlsVisible := False; FItemHeight := C_DEFAULT_ITEM_HEIGHT; FLastScrollPos := 0; FLastScrollChange := Now; FItems := TksInputListItems.Create(Self); FCanvas := TksInputListCanvas.Create(Self); FCanvas.Align := TAlignLayout.Top; FShowDividers := True; FCanvas.HitTest := False; FCanvas.Stored := False; AddObject(FCanvas); UpdateItemRects; FMouseDown := False; CreateScrollMonitor; AniCalculations.BoundsAnimation := True; end; procedure TksInputList.CreateScrollMonitor; begin FScrollMonitor := TThread.CreateAnonymousThread( procedure begin while not Application.Terminated do begin sleep (200); try if Application = nil then Exit; if FItems = nil then Exit; if (FItems.Count > 0) then begin if (FLastScrollPos = VScrollBarValue) and (FControlsVisible = False) then begin TThread.Synchronize(TThread.CurrentThread, procedure begin ShowOnScreenControls; end); end end; FLastScrollPos := VScrollBarValue; except end; end; end ); FScrollMonitor.Start; end; destructor TksInputList.Destroy; var AItem: TksBaseInputListItem; c: TPresentedControl; begin FScrollMonitor.Terminate; //if FScrollMonitor <> nil then // FScrollMonitor.Free; //Application.ProcessMessages; for AItem in FItems do begin if AItem is TksInputListItemWithControl then begin c := (AItem as TksInputListItemWithControl).FControl; c.parent := nil; end; end; FItems.Free; FCanvas.Free; FBuffer.Free; inherited; end; procedure TksInputList.DisableAll; var AItem: TksBaseInputListItem; begin BeginUpdate; for AItem in FItems do AItem.Enabled := False; EndUpdate; end; procedure TksInputList.EnableAll; var AItem: TksBaseInputListItem; begin BeginUpdate; for AItem in FItems do AItem.Enabled := True; EndUpdate; end; procedure TksInputList.EndUpdate; begin if FUpdateCount > 0 then Dec(FUpdateCount); if FUpdateCount = 0 then begin UpdateItemRects; {$IFNDEF MSWINDOWS} RedrawItems; {$ENDIF} //HideAllControls; HidePickers; InvalidateRect(ClipRect); FControlsVisible := False; ShowOnScreenControls; end; end; function TksInputList.GetAsJson(AStructure, AData: Boolean): string; var AJson: TJSONObject; begin AJson := TJSONObject.Create; try SaveToJson(AJson, AStructure, AData); Result := AJson.ToJSON; finally AJson.Free; end; end; function TksInputList.GetIsScrolling: Boolean; begin Result := ((FMousePos.Y) < (FMouseDownPos.Y - 4)) or ((FMousePos.Y) > (FMouseDownPos.Y + 4)); end; function TksInputList.GetValue(AName: string): string; var AItem: TksBaseInputListItem; begin Result := ''; AItem := FItems.ItemByID[AName]; if AItem <> nil then begin Result := AItem.Value; end; end; procedure TksInputList.HideAllControls; var AItem: TksBaseInputListItem; c: TFMXObject; begin inherited; if (FUpdateCount > 0) or (FControlsVisible = False) then Exit; for AItem in FItems do begin if AItem is TksInputListItemWithControl then begin c := (AItem as TksInputListItemWithControl).FControl; if (c is TksEdit) then begin (c as TksEdit).ControlType := TControlType.Styled; (AItem as TksInputListItemWithControl).ClearCache; end; if c.Parent <> FBuffer then begin FBuffer.AddObject(c); (AItem as TksInputListItemWithControl).FControl.ApplyStyleLookup; //FBuffer.RemoveObject(c); end; end; end; FControlsVisible := False; end; procedure TksInputList.HideAllSwipeButtons(AIgnoreItem: TksBaseInputListItem); var AItem: TksBaseInputListItem; begin for AItem in FItems do begin if AItem <> AIgnoreItem then AItem.HideSwipeButtons; end; end; procedure TksInputList.HidePickers; begin if FPickerService <> nil then FPickerService.CloseAllPickers; end; { function TksInputList.ItemAtPos(x, y: Extended): TksBaseInputListItem; var AItem: TksBaseInputListItem; begin Result := nil; for AItem in FItems do begin if PtInRect(AItem.ItemRect, PointF(x, y+FLastScrollPos)) then begin Result := AItem; Exit; end; end; end; } procedure TksInputList.LoadFromJson(AJsonData: string; AStructure, AData: Boolean); var AJson: TJSONObject; begin AJson := TJSONObject.ParseJSONValue(AJsonData) as TJSONObject; try LoadFromJson(AJson, AStructure, AData); finally AJson.Free; end; end; procedure TksInputList.LoadFromJson(AJson: TJsonObject; AStructure, AData: Boolean); var AObj: TJSONObject; AArray: TJSONArray; ICount: integer; AItem: TksBaseInputListItem; begin BeginUpdate; try if AStructure then ClearItems; AArray := (AJson.Values['items'] as TJSONArray); begin for ICount := 0 to AArray.Count-1 do begin AObj := AArray.Items[ICount] as TJSONObject; if AStructure then begin AItem := CreateListItem(Self, AObj.Values['class_id'].Value); FItems.Add(AItem); end else AItem := FItems.ItemByID[AObj.Values['id'].Value]; if AItem <> nil then AItem.LoadFromJson(AObj, AStructure, AData); end; end; finally EndUpdate; end; end; procedure TksInputList.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var AItem: TksBaseInputListItem; ATapEvent: Boolean; begin inherited; FMouseDown := True; HidePickers; y := y + VScrollBarValue; Root.SetFocused(nil); FMouseDownPos := PointF(X, Y); FMousePos := FMouseDownPos; FMouseDownItem := nil; for AItem in FItems do begin if PtInRect(AItem.ItemRect, PointF(x, y)) then begin if AItem.Enabled then begin FMouseDownItem := AItem; FMouseDownTime := MilliSecondOfTheDay(Now); TThread.CreateAnonymousThread( procedure begin Sleep(100); ATapEvent := ((FMousePos.Y) > (FMouseDownPos.Y - 10)) and ((FMousePos.Y) < (FMouseDownPos.Y + 10)); TThread.Synchronize(TThread.CurrentThread, procedure var AItem: TksBaseInputListItem; begin if FMouseDown then begin for AItem in FItems do begin if AItem.FMouseDown then AItem.MouseUp(False); end; FMouseDownItem.MouseDown; end; Application.ProcessMessages; end ); end ).Start; end; end; end; end; procedure TksInputList.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; y := y + VScrollBarValue; FMousePos := PointF(X, Y); end; procedure TksInputList.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var ATapEvent: Boolean; ADelay: cardinal; AQuckTap: Boolean; AItem: TksBaseInputListItem; ALongTap: Boolean; begin inherited; FMouseDown := False; y := y + VScrollBarValue; ADelay := MilliSecondOfTheDay(Now) - FMouseDownTime; AQuckTap := ADelay < 200; ALongTap := ADelay > 500; //form11.memo1.lines.add(FMouseDownPos.Y.ToString+' '+y.ToString); ATapEvent := ((Y) > (FMouseDownPos.Y - 5)) and ((Y) < (FMouseDownPos.Y + 5)); if FMouseDownItem <> nil then begin if FMouseDownItem.Enabled = False then Exit; //ADelay := (MilliSecondOfTheDay(Now) - FMouseDownTime); if ATapEvent then begin if AQuckTap then begin for AItem in FItems do begin if AItem.FMouseDown then AItem.MouseUp(False); end; FMouseDownItem.MouseDown; Application.ProcessMessages; Sleep(50); end; FMouseDownItem.MouseUp(ATapEvent); Application.ProcessMessages; if ALongTap then begin if Assigned(FOnItemLongTap) then FOnItemLongTap(Self, FMouseDownItem, FMouseDownItem.ID); end else begin FMouseDownItem.ItemClick; if Assigned(OnItemClick) then OnItemClick(Self, FMouseDownItem, FMouseDownItem.ID); end; end else FMouseDownItem.MouseUp(ATapEvent); end; end; procedure TksInputList.Paint; begin if BackgroundColor = claNull then Canvas.ClearRect(ClipRect, claWhitesmoke) else Canvas.ClearRect(ClipRect, BackgroundColor); inherited; end; procedure TksInputList.UpdateItemRects; var ICount: integer; AItem: TksBaseInputListItem; ATop: single; AHeight: single; begin ATop := 0; AHeight := 0; for ICount := 0 to FItems.Count-1 do begin AItem := FItems[ICount]; AItem.FItemRect := RectF(0, ATop, Width, ATop + AItem.Height); AItem.FIndex := ICount; ATop := AItem.FItemRect.Bottom; AHeight := AHeight + AItem.FItemRect.Height; end; FCanvas.Height := AHeight; end; procedure TksInputList.ViewportPositionChange(const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: boolean); begin inherited; FLastScrollChange := Now; HideAllControls; HidePickers; end; procedure TksInputList.RedrawItems; var r: TRectF; begin r := ClipRect; OffsetRect(r, 0, VScrollBarValue); FItems.DrawToCanvas(FCanvas.Canvas, r); end; procedure TksInputList.Reset; var AItem: TksBaseInputListItem; begin BeginUpdate; try for AItem in FItems do begin AItem.Reset; end; finally EndUpdate; end; end; procedure TksInputList.Resize; begin inherited; UpdateItemRects; ShowOnScreenControls; end; procedure TksInputList.SaveToJson(AJson: TJsonObject; AStructure, AData: Boolean); var AArray: TJSONArray; AObj: TJSONObject; AItem: TksBaseInputListItem; begin AArray := TJSONArray.Create; AJson.AddPair('items', AArray); for AItem in FItems do begin if (AStructure) or (not (AItem is TksInputListSeperator)) then begin AObj := TJSONObject.Create; AItem.SaveToJson(AObj, AStructure, AData); AArray.Add(AObj); end; end; end; procedure TksInputList.ScrollToBottom(const AAnimated: Boolean = False); var ATime: Single; begin AniCalculations.UpdatePosImmediately(True); case AAnimated of True: ATime := 0.4; False: ATime := 0; end; if VScrollBar <> nil then begin case AAnimated of False: VScrollBar.Value := VScrollBar.Max; True: TAnimator.AnimateFloat(Self, 'VScrollBar.Value', {FCanvas.Height-Height} VScrollBar.Max, ATime, TAnimationType.InOut, TInterpolationType.Quadratic); end; end; end; procedure TksInputList.ScrollToTop(const AAnimated: Boolean = False); var ATime: Single; begin case AAnimated of True: ATime := 1; False: ATime := 0; end; if VScrollBar <> nil then TAnimator.AnimateFloat(Self, 'VScrollBar.Value', 0, ATime, TAnimationType.InOut, TInterpolationType.Quadratic); end; procedure TksInputList.SetBackgroundColor(const Value: TAlphaColor); begin if FBackgroundColor <> Value then begin FBackgroundColor := Value; Repaint; end; end; procedure TksInputList.SetItemHeight(const Value: single); begin if FItemHeight <> Value then begin FItemHeight := Value; UpdateItemRects; ShowOnScreenControls; end; end; procedure TksInputList.SetShowDividers(const Value: Boolean); begin if FShowDividers <> Value then begin FShowDividers := Value; RedrawItems; end; end; procedure TksInputList.SetValue(AName: string; const Value: string); var AItem: TksBaseInputListItem; begin; AItem := FItems.ItemByID[AName]; if AItem <> nil then begin AItem.Value := Value; end; end; procedure TksInputList.ShowOnScreenControls; var AItem: TksBaseInputListItem; ACtrlItem: TksInputListItemWithControl; r: TRectF; begin if FUpdateCount > 0 then Exit; r := ContentRect; OffsetRect(r, 0, VScrollBarValue); for AItem in FItems do begin if (AItem is TksInputListItemWithControl) then begin ACtrlItem := (AItem as TksInputListItemWithControl); if (ACtrlItem is TksInputListEditItem) then (ACtrlItem as TksInputListEditItem).Edit.Width := Width/2; if ACtrlItem.Enabled then begin if IntersectRect(r, ACtrlItem.FItemRect) then begin if ACtrlItem.FControl.Parent = FBuffer then begin ACtrlItem.UpdateControlPosition; if (ACtrlItem.FControl is TksEdit) then (ACtrlItem.FControl as TksEdit).ControlType := TControlType.Platform; Self.AddObject(ACtrlItem.FControl); end; end; end; end; end; FControlsVisible := True; end; procedure TksInputList.SwipeLeft(AEventInfo: TGestureEventInfo); var //AItem: TksBaseInputListItem; AWidth: integer; ICount: integer; begin for AWidth := 0 to 10 do begin for ICount := 0 to FItems.Count-1 do begin FItems[ICount].FSlideButtonWidth := (AWidth * 10); FItems[Icount].Changed; end; //InvalidateRect(ClipRect); Repaint; end; {AItem := ItemAtPos(AEventInfo.Location.X, AEventInfo.Location.Y); if AItem <> nil then begin HideAllSwipeButtons(AItem); AItem.ShowSwipeButtons; end;} end; procedure TksInputList.SwipeRight(AEventInfo: TGestureEventInfo); //var //AItem: TksBaseInputListItem; begin HideAllSwipeButtons(nil); {AItem := ItemAtPos(AEventInfo.TapLocation.X, AEventInfo.TapLocation.Y); if AItem <> nil then begin AItem.HideSwipeButtons; end;} end; { TksBaseInputListItem } procedure TksBaseInputListItem.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TksBaseInputListItem.Create(AInputList: TksInputList); begin inherited Create; FksInputList := AInputList; FImage := TBitmap.Create; FFont := TFont.Create; FHeight := FksInputList.ItemHeight; FItemID := ''; FBackground := claWhite; FTextColor := claBlack; FDetailTextColor := claBlack; FSelected := False; FShowSelection := False; FReadOnly := False; FEnabled := True; FSelectedColor := $FFEAEAEA; FSlideButtonWidth := 0; end; destructor TksBaseInputListItem.Destroy; begin FImage.Free; FFont.Free; inherited; end; procedure TksBaseInputListItem.DoCustomDraw(ACanvas: TCanvas); begin // end; procedure TksBaseInputListItem.DrawDisabledRect(ACanvas: TCanvas); begin ACanvas.Fill.Color := claWhite; ACanvas.Fill.Kind := TBrushKind.Solid; ACanvas.FillRect(FItemRect, 0, 0, AllCorners, 0.5); end; procedure TksBaseInputListItem.DrawSeparators(ACanvas: TCanvas; ATop, ABottom: Boolean); var r: TRectF; begin ACanvas.Stroke.Color := claGray; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Thickness := 0.5; r := FItemRect; InflateRect(r, 0, (ACanvas.Stroke.Thickness / GetScreenScale())); if ATop then ACanvas.DrawLine(r.TopLeft, PointF(r.Right, r.Top), 1); if ABottom then ACanvas.DrawLine(PointF(r.Left, r.Bottom), r.BottomRight, 1); end; procedure TksBaseInputListItem.DrawToCanvas(ACanvas: TCanvas); var AState: TCanvasSaveState; AAccRect: TRectF; AAcc: TBitmap; r: TRectF; AButtonRect: TRectF; begin UpdateRects; AState := ACanvas.SaveState; try ACanvas.IntersectClipRect(FItemRect); ACanvas.Fill.Color := FBackground; ACanvas.Font.Assign(FFont); if ((FSelected) and (FShowSelection)) and (not FReadOnly) and (FEnabled) then ACanvas.Fill.Color := FSelectedColor; r := FItemRect; InflateRect(r, 0, 0.5); ACanvas.FillRect(r, 0, 0, AllCorners, 1); {$IFDEF DEBUG_BOXES} ACanvas.Stroke.Color := claRed; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Thickness := GetScreenScale; ACanvas.DrawRect(FContentRect, C_CORNER_RADIUS, C_CORNER_RADIUS, AllCorners, 1); ACanvas.Stroke.Color := claGreen; ACanvas.DrawRect(FContentRect, C_CORNER_RADIUS, C_CORNER_RADIUS, AllCorners, 1); ACanvas.Stroke.Color := claBlue; ACanvas.DrawRect(FAccessoryRect, C_CORNER_RADIUS, C_CORNER_RADIUS, AllCorners, 1); ACanvas.Stroke.Color := claPink; ACanvas.DrawRect(FImageRect, C_CORNER_RADIUS, C_CORNER_RADIUS, AllCorners, 1); {$ENDIF} if Assigned(FksInputList.OnPaintItem) then FksInputList.OnPaintItem(Self, ACanvas, r, FksInputList.Items.IndexOf(Self)); if (FAccessory <> atNone) and (FReadOnly = False) then begin AAcc := AAccessoriesList.ItemByAccessory[FAccessory].Bitmap; if AAcc <> nil then begin AAccRect := RectF(0, 0, AAcc.Width, AAcc.Height); ACanvas.DrawBitmap(AAcc, AAccRect, RectF(0, 0, AAccRect.Width/GetScreenScale, AAccRect.Height/GetScreenScale).PlaceInto(FAccessoryRect), 1, True); {$IFDEF DEBUG_BOXES} ACanvas.Stroke.Color := claBlack; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Thickness := 1; ACanvas.DrawRect(FAccessoryRect, 0, 0, AllCorners, 1); {$ENDIF} end; end; if FImage.IsEmpty = False then begin FImageRect.Inflate(-4, -4); ACanvas.DrawBitmap(FImage, FImage.BoundsF, FImage.BoundsF.PlaceInto(FImageRect),1, True); end; ACanvas.Fill.Color := FTextColor; if Trim(FTitle) <> '' then begin ACanvas.FillText(FContentRect, FTitle, False, 1, [], TTextAlign.Leading, TTextAlign.Center); end; if Trim(FDetail) <> '' then begin ACanvas.Fill.Color := GetDetailTextColor; ACanvas.FillText(FContentRect, FDetail, False, 1, [], TTextAlign.Trailing, TTextAlign.Center); end; DoCustomDraw(ACanvas); // draw the button... if FSlideButtonWidth > 0 then begin ACanvas.Fill.Color := claRed; AButtonRect := FItemRect; AButtonRect.Left := AButtonRect.Right-FSlideButtonWidth; ACanvas.FillRect(AButtonRect, 0, 0, AllCorners, 1); end; finally ACanvas.RestoreState(AState); end; end; function TksBaseInputListItem.GetAccessoryWidth(const AAddPadding: Boolean = False): single; begin Result := 0; if FAccessory <> atNone then begin Result := 20; if AAddPadding then Result := Result + 4; end; end; function TksBaseInputListItem.GetDetailTextColor: TAlphaColor; begin Result := FDetailTextColor; end; function TksBaseInputListItem.GetHeight: Single; begin Result := FHeight; end; function TksBaseInputListItem.GetItemRect: TRectF; begin Result := FItemRect; end; function TksBaseInputListItem.GetValue: string; begin Result := ''; end; procedure TksBaseInputListItem.HideSwipeButtons; var ICount: integer; begin if FSlideButtonWidth > 0 then begin for ICount := 20 downto 0 do begin FSlideButtonWidth := ICount*5; Changed; end; end; end; procedure TksBaseInputListItem.ItemClick; begin // end; procedure TksBaseInputListItem.LoadFromJson(AJson: TJsonObject; AStructure, AData: Boolean); begin if AStructure then LoadStructure(AJson); if AData then Value := AJson.Values['value'].Value; end; procedure TksBaseInputListItem.LoadStructure(AJson: TJSONObject); begin if AJson.Values['image'] <> nil then Base64ToBmp(AJson.Values['image'].Value, FImage); FItemID := AJson.Values['id'].Value; FAccessory := StrToAccessory(AJson.Values['acc'].Value); FBackground := StringToAlphaColor(AJson.Values['background'].Value); FHeight := StrToFloat(AJson.Values['height'].Value); FIndex := StrToInt(AJson.Values['index'].Value); FTitle := AJson.Values['title'].Value; FDetail := AJson.Values['detail'].Value; FShowSelection := StrToBool(AJson.Values['show_selection'].Value); end; procedure TksBaseInputListItem.MouseDown; begin if not FEnabled then Exit; if FksInputList.IsScrolling then Exit; FMouseDown := True; if FShowSelection then Selected := True; end; procedure TksBaseInputListItem.MouseUp(ATapEvent: Boolean); begin if FEnabled = False then Exit; if FMouseDown then begin FMouseDown := False; if (FSelected) then Selected := False; end; end; procedure TksBaseInputListItem.Reset; begin // end; procedure TksBaseInputListItem.SaveStructure(AJson: TJsonObject); begin AJson.AddPair('class_id', GetClassID); if not FImage.IsEmpty then AJson.AddPair('image', BmpToBase64(FImage)); AJson.AddPair('acc', AccessoryToStr(FAccessory)); AJson.AddPair('background', AlphaColorToString(FBackground)); AJson.AddPair('height', FloatToStr(FHeight)); AJson.AddPair('index', IntToStr(FIndex)); AJson.AddPair('title', FTitle); AJson.AddPair('detail', FDetail); AJson.AddPair('show_selection', BoolToStr(FShowSelection, True)); end; procedure TksBaseInputListItem.SaveToJson(AJson: TJsonObject; AStructure, AData: Boolean); begin AJson.AddPair('id', FItemID); if AStructure then SaveStructure(AJson); if AData then AJson.AddPair('value', Value); end; procedure TksBaseInputListItem.SetAccessory(const Value: TksInputAccessoryType); begin if FAccessory <> Value then begin FAccessory := Value; if FAccessory = atMore then FShowSelection := True; Changed; end; end; procedure TksBaseInputListItem.SetBackgroundColor(const Value: TAlphaColor); begin if FBackground <> Value then begin FBackground := Value; Changed; end; end; procedure TksBaseInputListItem.SetDetail(const Value: string); begin if FDetail <> Value then begin FDetail := Value; Changed; end; end; procedure TksBaseInputListItem.SetDetailTextColor(const Value: TAlphaColor); begin if FDetailTextColor <> Value then begin FDetailTextColor := Value; Changed; end; end; procedure TksBaseInputListItem.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; Changed; end; end; procedure TksBaseInputListItem.SetHeight(const Value: Single); begin FHeight := Value; Changed; end; procedure TksBaseInputListItem.SetReadOnly(const Value: Boolean); begin if FReadOnly <> Value then begin if Value then FShowSelection := False; FReadOnly := Value; Changed; end; end; procedure TksBaseInputListItem.SetSelected(const Value: Boolean); begin if FSelected <> Value then begin FSelected := Value; Changed; end; end; procedure TksBaseInputListItem.SetSelectedColor(const Value: TAlphaColor); begin if FSelectedColor <> Value then begin FSelectedColor := Value; Changed; end; end; procedure TksBaseInputListItem.SetShowSelection(const Value: Boolean); begin FShowSelection := Value; end; procedure TksBaseInputListItem.SetTextColor(const Value: TAlphaColor); begin if FTextColor <> Value then begin FTextColor := Value; Changed; end; end; procedure TksBaseInputListItem.SetTitle(const Value: string); begin FTitle := Value; Changed; end; procedure TksBaseInputListItem.SetValue(const AValue: string); begin // overridden in descendant classes. end; procedure TksBaseInputListItem.ShowSwipeButtons; var ICount: integer; begin for ICount := 0 to 20 do begin FSlideButtonWidth := ICount*5; Changed; end; end; procedure TksBaseInputListItem.UpdateRects; var AAccessoryWidth: single; begin FAccessoryRect := FAccessoryRect.Empty; FImageRect := FImageRect.Empty; FContentRect := FItemRect; FContentRect.Left := FContentRect.Left + 10; FContentRect.Right := FContentRect.Right - C_RIGHT_MARGIN; // add image rect... if not FImage.IsEmpty then begin FImageRect := FContentRect; FImageRect.Right := FContentRect.Left+36; FContentRect.Left := FImageRect.Right+8; end; if (FAccessory <> atNone) and (not ((FAccessory = atMore) and (FReadOnly))) then begin // add accessory rect AAccessoryWidth := GetAccessoryWidth(False); FAccessoryRect := FContentRect; FAccessoryRect.Left := FContentRect.Right-AAccessoryWidth; FContentRect.Right := FAccessoryRect.Left; end {$IFNDEF MSWINDOWS} else FContentRect.Right := FContentRect.Right - 6; {$ENDIF} end; { TksInputListItems } function TksInputListItems.AddBadgeItem(AID: string; AImage: TBitmap; ATitle, AValue: string; ABadgeColor, ABadgeTextColor: TAlphaColor; const AAccessory: TksInputAccessoryType = atNone): TksInputListBadgeItem; begin Result := TksInputListBadgeItem.Create(FksInputList); Result.FItemID := AID; Result.FImage.Assign(AImage); Result.Title := ATitle; Result.Detail := AValue; Result.BadgeColor := ABadgeColor; Result.BadgeTextColor := ABadgeTextColor; Result.Accessory := AAccessory; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; procedure TksInputListItems.AddButtonItem(AID: string; AImg: TBitmap; ATitle, AButtonTitle: string); var AItem: TksInputListButtonItem; begin AItem := TksInputListButtonItem.Create(FksInputList); AItem.FItemID := AID; AItem.FImage.Assign(AImg); AItem.Title := ATitle; AItem.Button.Text := AButtonTitle; AItem.Button.DisableFocusEffect := True; AItem.Button.CanFocus := False; AItem.OnChange := ItemChange; Add(AItem); ItemChange(Self); end; function TksInputListItems.AddChatItem(AID, ASender, AText: string; ADateTime: TDateTime; AAlign: TTextAlign; AColor, ATextColor: TAlphaColor; const AUse24HourTime: Boolean = True): TksInputListChatItem; var AStr: string; ATone: integer; begin Result := TksInputListChatItem.Create(FksInputList); Result.FItemID := AID; Result.Color := AColor; AStr := AText; for ATone := 57339 to 57344 do if Pos(Chr(ATone), AStr) > 0 then System.Delete(AStr, Pos(Chr(ATone), AStr)-1, 2); //StringReplace(s, Chr(57339), '', [rfReplaceAll]); if Pos(Chr(8205), AStr) > 0 then System.Delete(AStr, Pos(Chr(8205), AStr), 3); //StringReplace(s, Chr(57339), '', [rfReplaceAll]); AStr := StringReplace(AStr, '‍♂️', '', [rfReplaceAll]); AStr := StringReplace(AStr, '♀️', '', [rfReplaceAll]); AStr := Trim(AStr); Result.TextColor := ATextColor; Result.Body := AStr; Result.DateTime := ADateTime; Result.Sender := ASender; Result.Alignment := AAlign; Result.Use24HourTime := AUse24HourTime; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddCheckBoxItem(AID: string; AImg: TBitmap; ATitle: string; AState: Boolean): TksInputListCheckBoxItem; begin Result := TksInputListCheckBoxItem.Create(FksInputList); Result.FImage.Assign(AImg); Result.FItemID := AID; Result.Title := ATitle; Result.CheckBox.IsChecked := AState; Result.CheckBox.OnChange := Result.CheckBoxChange; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddEditBoxItem(AID: string; AImg: TBitmap; ATitle: string; AValue: string; APlaceholder: string; const AKeyboard: TVirtualKeyboardType = TVirtualKeyboardType.Default): TksInputListEditItem; begin Result := TksInputListEditItem.Create(FksInputList); Result.FItemID := AID; Result.Edit.KeyboardType := AKeyboard; Result.FImage.Assign(AImg); Result.Title := ATitle; Result.Edit.TextPrompt := APlaceholder; Result.Edit.Text := AValue; Result.OnChange := ItemChange; Result.Edit.OnChangeTracking := Result.TextChange; Result.Edit.ApplyStyleLookup; Add(Result); ItemChange(Self); end; function TksInputListItems.AddSeperator(ATitle: string; const AHeight: integer = C_DEFAULT_SEPERATOR_HEIGHT): TksInputListSeperator; begin Result := TksInputListSeperator.Create(FksInputList); Result.Height := AHeight; Result.FItemID := GuidToString(TGUID.NewGuid); Result.Title := ATitle; Add(Result); ItemChange(Self); end; function TksInputListItems.AddSwitchItem(AID: string; AImg: TBitmap; ATitle: string; AState: Boolean): TksInputListSwitchItem; begin Result := TksInputListSwitchItem.Create(FksInputList); Result.FItemID := AID; Result.FImage.Assign(AImg); Result.Title := ATitle; Result.GetSwitch.IsChecked := AState; Result.GetSwitch.OnSwitch := Result.SwitchChange; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; procedure TksInputListItems.AddTrackBar(AID: string; AImg: TBitmap; ATitle: string; APos, AMax: integer); var AItem: TksInputListTrackBarItem; begin AItem := TksInputListTrackBarItem.Create(FksInputList); AItem.FItemID := AID; AItem.FImage.Assign(AImg); AItem.Title := ATitle; AItem.TrackBar.Max := AMax; AItem.TrackBar.Value := AMax; AItem.OnChange := ItemChange; AItem.TrackBar.OnTracking := AItem.TrackBarChange; Add(AItem); ItemChange(Self); end; function TksInputListItems.AddImageItem(AID: string; AImg: TBitmap): TksInputListImageItem; begin Result := TksInputListImageItem.Create(FksInputList); Result.FItemID := AID; Result.FImage.Assign(AImg); Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddItem(AID: string; AImg: TBitmap; ATitle: string; const AAccessory: TksInputAccessoryType = atNone): TksInputListItem; begin Result := TksInputListItem.Create(FksInputList); Result.FItemID := AID; Result.FImage.Assign(AImg); Result.Title := ATitle; if AAccessory <> atNone then Result.ShowSelection := True; Result.Accessory := AAccessory; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddItemSelector(AID: string; AImg: TBitmap; ATitle, ASelected: string; AItems: TStrings): TksInputListSelectorItem; begin Result := TksInputListSelectorItem.Create(FksInputList); Result.FItemID := AID; Result.Items.Assign(AItems); Result.FImage.Assign(AImg); Result.Title := ATitle; Result.Accessory := atMore; Result.Value := ASelected; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddDateSelector(AID: string; AImg: TBitmap; ATitle: string; ASelected: TDateTime): TksInputListDateTimeSelectorItem overload; begin Result := TksInputListDateTimeSelectorItem.Create(FksInputList); Result.FItemID := AID; Result.DateTime := ASelected; Result.FImage.Assign(AImg); Result.Title := ATitle; Result.Accessory := atMore; Result.OnChange := ItemChange; Result.Kind := ksDateSelector; Add(Result); ItemChange(Self); end; function TksInputListItems.AddTimeSelector(AID: string; AImg: TBitmap; ATitle: string; ASelected: TDateTime): TksInputListDateTimeSelectorItem overload; begin Result := TksInputListDateTimeSelectorItem.Create(FksInputList); Result.FItemID := AID; Result.Kind := ksTimeSelector; Result.DateTime := ASelected; Result.FImage.Assign(AImg); Result.Title := ATitle; Result.Accessory := atMore; Result.OnChange := ItemChange; Add(Result); ItemChange(Self); end; function TksInputListItems.AddRadioItem(AID: string; AImage: TBitmap; AGroupID, ATitle: string; AChecked: Boolean): TksInputListCheckBoxItem; begin Result := AddCheckBoxItem(AID, AImage, ATitle, AChecked); Result.RadioGroupID := AGroupID; end; function TksInputListItems.AddItemSelector(AID: string; AImg: TBitmap; ATitle, ASelected: string; AItems: array of string): TksInputListSelectorItem; var AStrings: TStrings; s: string; begin AStrings := TStringList.Create; try for s in AItems do AStrings.Add(s); Result := AddItemSelector(AId, AImg, ATitle, ASelected, AStrings); finally AStrings.Free; end; end; constructor TksInputListItems.Create(AForm: TksInputList); begin inherited Create(True); FksInputList := AForm; end; procedure TksInputListItems.DeselectAll; var AItem: TksBaseInputListItem; begin for AItem in Self do AItem.Selected := False; end; procedure TksInputListItems.DrawToCanvas(ACanvas: TCanvas; AViewPort: TRectF); var AItem: TksBaseInputListItem; ICount: integer; begin for AItem in Self do begin if IntersectRect(AViewPort, AItem.FItemRect) then AItem.DrawToCanvas(ACanvas); if AItem.Enabled = False then AItem.DrawDisabledRect(ACanvas); end; if FksInputList.ShowDividers then begin for ICount := 0 to Count-1 do begin AItem := Items[ICount]; if IntersectRect(AViewPort, AItem.FItemRect) then if (not ((AItem is TksInputListSeperator) and (ICount = 0))) then AItem.DrawSeparators(ACanvas, True, (ICount = Count-1) and (not(AItem is TksInputListSeperator))); end; end; end; function TksInputListItems.GetCheckedCount: integer; var AItem: TksBaseInputListItem; begin Result := 0; for AItem in Self do begin if (AItem is TksInputListCheckBoxItem) then if (AItem as TksInputListCheckBoxItem).CheckBox.IsChecked then Result := Result +1; end; end; function TksInputListItems.GetItemByID(AID: string): TksBaseInputListItem; var AItem: TksBaseInputListItem; begin Result := nil; for AItem in Self do begin if UpperCase(AItem.ID) = UpperCase(AID) then begin Result := AItem; Exit; end; end; end; procedure TksInputListItems.Insert(Index: Integer; const Value: TksBaseInputListItem); begin Value.OnChange := ItemChange; inherited Insert(Index, Value); ItemChange(Self); end; procedure TksInputListItems.ItemChange(Sender: TObject); begin if FksInputList.FUpdateCount > 0 then Exit; FksInputList.UpdateItemRects; FksInputList.InvalidateRect(FksInputList.ClipRect); FksInputList.ShowOnScreenControls; end; function TksInputListItems.ItemExists(AID: string): Boolean; begin Result := ItemByID[AID] <> nil; end; { TksInputListCanvas } procedure TksInputListCanvas.Paint; begin inherited; if (Owner as TksInputList).BackgroundColor <> claNull then Canvas.Clear((Owner as TksInputList).BackgroundColor); (Owner as TksInputList).RedrawItems; end; { TksInputListEditItem } procedure TksInputListEditItem.ClickControl; begin //FControl.ControlType := TControlType.Platform; inherited ClickControl; end; function TksInputListEditItem.CreateControl: TPresentedControl; begin Result := TksEdit.Create(nil); (Result as TksEdit).ApplyStyle; (Result as TksEdit).Width := FksInputList.Width / 2; (Result as TksEdit).TextSettings.HorzAlign := TTextAlign.Trailing; (Result as TksEdit).CanFocus := True; (Result as TksEdit).DisableFocusEffect := False; // end; procedure TksInputListEditItem.DrawToCanvas(ACanvas: TCanvas); begin //FControl.ControlType := TControlType.Styled; inherited DrawToCanvas(ACanvas); end; class function TksInputListEditItem.GetClassID: string; begin Result := '{099048A9-EC3B-4931-89DF-61C938B3F571}'; end; function TksInputListEditItem.GetEdit: TksEdit; begin Result := (FControl as TksEdit); end; function TksInputListEditItem.GetValue: string; begin Result := Edit.Text; end; procedure TksInputListEditItem.MouseDown; begin inherited; end; procedure TksInputListEditItem.LoadStructure(AJson: TJSONObject); begin inherited; Edit.KeyboardType := TVirtualKeyboardType(StrToIntDef(AJson.Values['keyboard'].Value, 0)); end; procedure TksInputListEditItem.Reset; begin inherited; Edit.Text := ''; end; procedure TksInputListEditItem.SaveStructure(AJson: TJsonObject); begin inherited; AJson.AddPair('keyboard', IntToStr(Ord(Edit.KeyboardType))); end; procedure TksInputListEditItem.SetReadOnly(const Value: Boolean); begin if Value <> FReadOnly then begin FReadOnly := Value; Edit.CanFocus := not ReadOnly; Edit.HitTest := not ReadOnly; Edit.ReadOnly := ReadOnly; Changed; end; end; procedure TksInputListEditItem.SetValue(const AValue: string); begin Edit.Text := AValue; end; procedure TksInputListEditItem.TextChange(Sender: TObject); begin if Assigned(FksInputList.OnEditItemTextChange) then FksInputList.OnEditItemTextChange(FksInputList, Self, ID, Value); end; { TksInputListItemWithControl } procedure TksInputListItemWithControl.Changed; begin inherited; UpdateRects; UpdateControlPosition; end; procedure TksInputListItemWithControl.ClearCache; begin FCached.SetSize(0,0); end; procedure TksInputListItemWithControl.ClickControl; begin ClearCache; //FksInputList.HidePickers; end; constructor TksInputListItemWithControl.Create(AInputList: TksInputList); begin inherited; FControl := CreateControl; FControl.Visible := True; FControl.ApplyStyleLookup; FCached := TBitmap.Create; FFullWidthSelect := False; end; destructor TksInputListItemWithControl.Destroy; begin FControl.DisposeOf; FCached.Free; inherited; end; procedure TksInputListItemWithControl.DrawToCanvas(ACanvas: TCanvas); var AScreenScale: single; begin inherited; {$IFDEF DEBUG_BOXES} ACanvas.Stroke.Color := claBlack; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Thickness := GetScreenScale; ACanvas.DrawRect(FControl.BoundsRect, C_CORNER_RADIUS, C_CORNER_RADIUS, AllCorners, 1); {$ENDIF} if FControl.Parent <> FksInputList.FBuffer then Exit; AScreenScale := GetScreenScale; ACanvas.Stroke.Kind := TBrushKind.Solid; ACanvas.Stroke.Thickness := 0.5; if FCached.IsEmpty then begin FCached.BitmapScale := AScreenScale; FCached.SetSize(Round(FControl.Width*AScreenScale), Round(FControl.Height*AScreenScale)); FCached.Canvas.BeginScene; FCached.Clear(claNull); PaintControl(FCached.Canvas); FCached.Canvas.EndScene; end; ACanvas.DrawBitmap(FCached, Rect(0, 0, FCached.Width, FCached.Height), FControl.BoundsRect.PlaceInto(FControlRect, THorzRectAlign.Right), 1); end; procedure TksInputListItemWithControl.ItemClick; begin if (FFullWidthSelect) and (not ReadOnly) and (FEnabled) then ClickControl; end; procedure TksInputListItemWithControl.PaintControl(ACanvas: TCanvas); begin if FControl.Parent <> FksInputList then FControl.PaintTo(ACanvas, RectF(0, 0, FControl.Width, FControl.Height)); end; procedure TksInputListItemWithControl.Reset; begin inherited; FCached.SetSize(0, 0); end; procedure TksInputListItemWithControl.UpdateControlPosition; begin UpdateRects; FControl.BoundsRect := FControl.BoundsRect.PlaceInto(FControlRect, THorzRectAlign.Right); end; procedure TksInputListItemWithControl.UpdateRects; begin inherited; FControlRect := FContentRect; FControlRect.Left := FControlRect.Right - FControl.Width; FContentRect.Right := FControlRect.Left; end; { TksInputListSwitchItem } constructor TksInputListSwitchItem.Create(AInputList: TksInputList); begin inherited; end; function TksInputListSwitchItem.CreateControl: TPresentedControl; begin Result := TSwitch.Create(nil); end; class function TksInputListSwitchItem.GetClassID: string; begin Result := '{C9533F62-6097-4AB2-B353-C54F83B29EEF}'; end; function TksInputListSwitchItem.GetIsChecked: Boolean; begin Result := GetSwitch.IsChecked; end; function TksInputListSwitchItem.GetSwitch: TSwitch; begin Result := FControl as TSwitch; end; function TksInputListSwitchItem.GetValue: string; begin Result := BoolToStr(GetSwitch.IsChecked, True); end; procedure TksInputListSwitchItem.Reset; begin inherited; IsChecked := False; end; procedure TksInputListSwitchItem.SetIsChecked(const Value: Boolean); begin GetSwitch.IsChecked := Value; end; procedure TksInputListSwitchItem.SetValue(const AValue: string); begin inherited; IsChecked := TryGetBoolFromString(AValue); end; procedure TksInputListSwitchItem.SwitchChange(Sender: TObject); var Thread: TThread; begin FCached.Clear(claNull); Thread := TThread.CreateAnonymousThread( procedure begin Sleep(250); TThread.Synchronize(TThread.CurrentThread,procedure begin if Assigned(FksInputList.OnItemSwitchChanged) then begin FksInputList.OnItemSwitchChanged(FksInputList, Self, ID, GetSwitch.IsChecked); end; end); end); Thread.Start; end; { TksInputListCheckBoxItem } procedure TksInputListCheckBoxItem.CheckBoxChange(Sender: TObject); begin if Assigned(FksInputList.OnItemCheckBoxChanged) then begin FksInputList.OnItemCheckBoxChanged(FksInputList, Self, ID, CheckBox.IsChecked); end; end; procedure TksInputListCheckBoxItem.ClickControl; var AItem: TksBaseInputListItem; cb: TksInputListCheckBoxItem; begin inherited; if FRadioGroupID <> '' then begin for AItem in FksInputList.Items do begin if AItem is TksInputListCheckBoxItem then begin cb := (AItem as TksInputListCheckBoxItem); cb.CheckBox.IsChecked := False; end; end; end; if (CheckBox.IsChecked) and (FRadioGroupID <> '') then Exit; CheckBox.IsChecked := not CheckBox.IsChecked; end; constructor TksInputListCheckBoxItem.Create(AInputList: TksInputList); begin inherited; FShowSelection := True; FFullWidthSelect := True; end; function TksInputListCheckBoxItem.CreateControl: TPresentedControl; begin Result := TCheckBox.Create(nil); end; function TksInputListCheckBoxItem.GetCheckBox: TCheckBox; begin Result := (FControl as TCheckBox); (Result as TCheckBox).Width := 24; (Result as TCheckBox).Height := 24; end; class function TksInputListCheckBoxItem.GetClassID: string; begin Result := '{07EC5B74-F220-45DD-BDC0-D4D686058C7C}'; end; function TksInputListCheckBoxItem.GetValue: string; begin Result := BoolToStr(CheckBox.IsChecked, True); end; procedure TksInputListCheckBoxItem.Reset; begin inherited; CheckBox.IsChecked := False; end; procedure TksInputListCheckBoxItem.SetRadioGroupID(const Value: string); begin if FRadioGroupID <> Value then begin FRadioGroupID := Value; end; end; procedure TksInputListCheckBoxItem.SetValue(const AValue: string); begin inherited; CheckBox.IsChecked := TryGetBoolFromString(AValue); end; { TksInputListButtonItem } procedure TksInputListButtonItem.ClickControl; begin inherited; (FControl as TButton).IsPressed := True; end; function TksInputListButtonItem.CreateControl: TPresentedControl; begin Result := TButton.Create(nil); (Result as TButton).StyleLookup := 'listitembutton'; (Result as TButton).Height := 32; (Result as TButton).OnClick := DoButtonClick; end; procedure TksInputListButtonItem.DoButtonClick(Sender: TObject); begin if Assigned(FksInputList.OnItemButtonClick) then FksInputList.OnItemButtonClick(FksInputList, Self, ID); end; function TksInputListButtonItem.GetButton: TButton; begin Result := (FControl as TButton); end; class function TksInputListButtonItem.GetClassID: string; begin Result := '{D7E87C25-E018-41F0-B85D-AA6B690C36CB}'; end; procedure TksInputListButtonItem.LoadStructure(AJson: TJSONObject); begin inherited; Button.Text := AJson.Values['button_text'].Value; Button.Width := StrToFloat(AJson.Values['button_width'].Value); end; procedure TksInputListButtonItem.SaveStructure(AJson: TJsonObject); begin inherited; AJson.AddPair('button_text', Button.Text); AJson.AddPair('button_width', FloatToStr(Button.Width)); end; { TksInputListTrackBarItem } constructor TksInputListTrackBarItem.Create(AInputList: TksInputList); begin inherited; TrackBar.Width := 200; end; function TksInputListTrackBarItem.CreateControl: TPresentedControl; begin Result := TksTrackBar.Create(nil); (Result as TksTrackBar).ApplyStyle; end; class function TksInputListTrackBarItem.GetClassID: string; begin Result := '{CBBF6D98-CCBD-4FCF-9AF4-6DE99E9E2362}' end; function TksInputListTrackBarItem.GetTrackBar: TksTrackBar; begin Result := (FControl as TksTrackBar); end; function TksInputListTrackBarItem.GetValue: string; begin Result := FloatToStr(TrackBar.Value); end; procedure TksInputListTrackBarItem.PaintControl(ACanvas: TCanvas); var AThumbRect: TRectF; begin inherited; AThumbRect := TrackBar.GetThumbRect; if TrackBar.Thumb <> nil then begin if TrackBar.Thumb.StyleState <> TStyleState.Applied then TrackBar.Thumb.ApplyStyleLookup; TrackBar.Thumb.PaintTo(ACanvas, AThumbRect); end; end; procedure TksInputListTrackBarItem.Reset; begin inherited; TrackBar.Value := 0; end; procedure TksInputListTrackBarItem.SetValue(const AValue: string); begin inherited; TrackBar.Value := StrToFloatDef(AValue, 0); end; procedure TksInputListTrackBarItem.TrackBarChange(Sender: TObject); begin if Assigned(FksInputList.OnItemTrackBarChange) then FksInputList.OnItemTrackBarChange(FksInputList, Self, ID, StrToFloatDef(Value, 0)); end; { TksInputListSelectorItem } constructor TksInputListSelectorItem.Create(AInputList: TksInputList); begin inherited; FCombo := TComboBox.Create(nil); FItems := TStringList.Create; FShowSelection := True; FCombo.OnChange := DoSelectorChanged; end; destructor TksInputListSelectorItem.Destroy; begin FItems.Free; FCombo.Free; inherited; end; procedure TksInputListSelectorItem.DoSelectorChanged(Sender: TObject); var Thread: TThread; begin if FCombo.ItemIndex > -1 then Value := FCombo.Items[FCombo.ItemIndex]; Thread := TThread.CreateAnonymousThread( procedure begin Sleep(200); // Copy files here TThread.Synchronize(TThread.CurrentThread, procedure begin if Assigned(FksInputList.OnSelectorItemSelected) then FksInputList.OnSelectorItemSelected(FksInputList, Self, ID, Value); end ); end ); Thread.Start; end; class function TksInputListSelectorItem.GetClassID: string; begin Result := '{D5BB3373-99AB-4BB4-A478-96EAAC0AD091}'; end; function TksInputListSelectorItem.GetValue: string; begin Result := FValue; end; procedure TksInputListSelectorItem.LoadStructure(AJson: TJSONObject); begin inherited; FItems.CommaText := AJson.Values['items'].Value; end; procedure TksInputListSelectorItem.MouseUp(ATapEvent: Boolean); begin if (FMouseDown) and (ATapEvent) then begin FCombo.OnChange := nil; FCombo.Items.Assign(FItems); FCombo.ItemIndex := FCombo.Items.IndexOf(FValue); FCombo.DropDown; FCombo.OnChange := DoSelectorChanged; end; inherited; end; procedure TksInputListSelectorItem.Reset; begin inherited; Value := ''; end; procedure TksInputListSelectorItem.SaveStructure(AJson: TJsonObject); begin inherited; AJson.AddPair('items', FItems.CommaText); end; procedure TksInputListSelectorItem.SetItems(const Value: TStrings); begin FItems.Assign(Value); end; procedure TksInputListSelectorItem.SetValue(const Value: string); begin if FValue <> Value then begin FDetail := Value; FValue := Value; Changed; end; end; { TInputListAccessoryImages } constructor TInputListAccessoryImages.Create; begin inherited Create(True); Add(TInputListAccessoryImage.Create(atMore, GetAccessoryFromResource(['listviewstyle','accessorymore']))); Add(TInputListAccessoryImage.Create(atCheckmark, GetAccessoryFromResource(['listviewstyle','accessorycheckmark']))); Add(TInputListAccessoryImage.Create(atDetail, GetAccessoryFromResource(['listviewstyle','accessorydetail']))); end; function TInputListAccessoryImages.GetItemByAccessory(AType: TksInputAccessoryType): TInputListAccessoryImage; var AItem: TInputListAccessoryImage; begin Result := nil; for AItem in Self do begin if AItem.AccessoryType = AType then begin Result := AItem; Exit; end; end; end; { TInputListAccessoryImage } constructor TInputListAccessoryImage.Create(AType: TksInputAccessoryType; ABmp: TBitmap); begin inherited Create; FAccessoryType := AType; FBitmap := ABmp; end; destructor TInputListAccessoryImage.Destroy; begin FBitmap.Free; inherited; end; { TksInputListSeperator } constructor TksInputListSeperator.Create(AInputList: TksInputList); begin inherited; FHeight := C_DEFAULT_SEPERATOR_HEIGHT; FFont.Size := 11; FHorzAlign := TTextAlign.Leading; end; procedure TksInputListSeperator.DrawToCanvas(ACanvas: TCanvas); var AText: string; begin AText := FTitle; FTitle := ''; FBackground := claNull; inherited DrawToCanvas(ACanvas); FTitle := AText; FBackground := claNull; ACanvas.Fill.Color := claDimgray; ACanvas.Font.Size := 12; FContentRect.Inflate(0, -4); ACanvas.FillText(FContentRect, FTitle, False, 1, [], FHorzAlign, TTextAlign.Trailing); FContentRect.Inflate(0, 4); end; class function TksInputListSeperator.GetClassID: string; begin Result := '{7DAC9C9A-3222-418B-A4B1-2EB33EC99466}'; end; function TksInputListSeperator.GetValue: string; begin Result := ''; end; procedure TksInputListSeperator.SetHorzAlign(const Value: TTextAlign); begin if FHorzAlign <> Value then begin FHorzAlign := Value; Changed; end; end; { TksInputListItem } procedure TksInputListItem.DrawToCanvas(ACanvas: TCanvas); begin inherited DrawToCanvas(ACanvas); end; class function TksInputListItem.GetClassID: string; begin Result := '{4457C117-E5E0-41F3-9EC9-71BBB30C198D}'; end; procedure TksInputListItem.UpdateRects; begin inherited UpdateRects; end; { TksInputListImageItem } constructor TksInputListImageItem.Create(AInputList: TksInputList); begin inherited; FImage := TBitmap.Create; end; destructor TksInputListImageItem.Destroy; begin FreeAndNil(FImage); inherited; end; procedure TksInputListImageItem.DoCustomDraw(ACanvas: TCanvas); begin inherited; ACanvas.DrawBitmap(FImage, FImage.BoundsF, FItemRect, 1, True); end; procedure TksInputListImageItem.DrawToCanvas(ACanvas: TCanvas); begin inherited DrawToCanvas(ACanvas); end; class function TksInputListImageItem.GetClassID: string; begin Result := '{E5E6CA88-3228-46BD-8A66-41E0EB674115}'; end; procedure TksInputListImageItem.UpdateRects; begin inherited UpdateRects; FImageRect.Left := 0; FImageRect.Width := FksInputList.Width; end; { TksInputListDateTimeSelectorItem } constructor TksInputListDateTimeSelectorItem.Create(AInputList: TksInputList); begin inherited; if TPlatformServices.Current.SupportsPlatformService(IFMXPickerService, FPickerService) then begin FDateTimePicker := FPickerService.CreateDateTimePicker; end; end; destructor TksInputListDateTimeSelectorItem.Destroy; begin inherited; end; procedure TksInputListDateTimeSelectorItem.DoSelectDateTime(Sender: TObject; const ADateTime: TDateTime); begin DateTime := ADateTime; if Assigned(FksInputList.OnDateTimeSelected) then FksInputList.OnDateTimeSelected(FksInputList, Self, FItemID, ADateTime); end; class function TksInputListDateTimeSelectorItem.GetClassID: string; begin Result := '{E4F2A9C8-FDBC-4E99-B434-66B444F5A3B3}'; end; function TksInputListDateTimeSelectorItem.GetDateTime: TDateTime; begin Result := FDateTime; end; function TksInputListDateTimeSelectorItem.GetValue: string; begin Result := DateToISO8601(FDateTime); end; procedure TksInputListDateTimeSelectorItem.LoadStructure(AJson: TJSONObject); begin inherited; end; procedure TksInputListDateTimeSelectorItem.MouseUp(ATapEvent: Boolean); begin if ((FMouseDown) and (ATapEvent)) and (not ReadOnly) and (FEnabled) then begin case FKind of ksDateSelector: FDateTimePicker.ShowMode := TDatePickerShowMode.Date; ksTimeSelector: FDateTimePicker.ShowMode := TDatePickerShowMode.Time; end; FDateTimePicker.Date := FDateTime; FDateTimePicker.OnDateChanged := DoSelectDateTime; FDateTimePicker.Show; end; inherited; end; procedure TksInputListDateTimeSelectorItem.Reset; begin inherited; DateTime := 0; end; procedure TksInputListDateTimeSelectorItem.SaveStructure(AJson: TJsonObject); begin inherited; end; procedure TksInputListDateTimeSelectorItem.SetDateTime(const AValue: TDateTime); begin FDateTime := AValue; case FKind of ksDateSelector: Detail := FormatDateTime('ddd, d mmmm, yyyy', FDateTime); ksTimeSelector: Detail := FormatDateTime('hh:nn', FDateTime); end; end; procedure TksInputListDateTimeSelectorItem.SetKind(const Value: TksDateTimeSelectorKind); begin FKind := Value; SetDateTime(FDateTime); end; procedure TksInputListDateTimeSelectorItem.SetValue(const Value: string); begin try FDateTime := ISO8601ToDate(Value) except // invalid date/time? end; end; { TksInputListBadgeItem } constructor TksInputListBadgeItem.Create(AInputList: TksInputList); begin inherited; FBadgeColor := claDodgerblue; FBadgeTextColor := claWhite; end; procedure TksInputListBadgeItem.DrawToCanvas(ACanvas: TCanvas); var r: TRectF; ADetail: string; ACenter: TPointF; begin ADetail := FDetail; FDetail := ''; inherited DrawToCanvas(ACanvas); FDetail := ADetail; if Trim(FDetail) = '' then Exit; ACanvas.Fill.Color := FBadgeColor; ACanvas.Fill.Kind := TBrushKind.Solid; ACanvas.Font.Size := 13; r := FContentRect; r.Left := r.Right - (ACanvas.TextWidth(FDetail)+14); ACenter := r.CenterPoint; r.Top := ACenter.Y-13; r.Bottom := ACenter.Y+13; ACanvas.FillRect(r, 6, 6, AllCorners, 1); ACanvas.Fill.Color := FBadgeTextColor; ACanvas.FillText(r, FDetail, False, 1, [], TTextAlign.Center, TTextAlign.Center); end; class function TksInputListBadgeItem.GetClassID: string; begin Result := '{5CE55631-0B72-4BDA-8805-D2EDF5E639FF}'; end; function TksInputListBadgeItem.GetDetailTextColor: TAlphaColor; begin Result := FBadgeTextColor; end; procedure TksInputListBadgeItem.SetBadgeColor(const Value: TAlphaColor); begin if FBadgeColor <> Value then begin FBadgeColor := Value; Changed; end; end; { TksInputListChatItem } constructor TksInputListChatItem.Create(AInputList: TksInputList); begin inherited; FColor := claDodgerblue; FTextColor := claWhite; FCached := TBitmap.Create; FCached.BitmapScale := GetScreenScale; FUse24HourTime := True; end; function TksInputListChatItem.CalculateHeight: single; var AEmojiOnly: Boolean; begin AEmojiOnly := IsEmojiOnly; ATextLayout.Font.Size := 16; if AEmojiOnly then ATextLayout.Font.Size := 36; ATextLayout.BeginUpdate; ATextLayout.Text := FBody; ATextLayout.WordWrap := True; ATextLayout.Color := FTextColor; ATextLayout.HorizontalAlign := TTextAlign.Leading; ATextLayout.Padding.Rect := RectF(0, 0, 0, 0); ATextLayout.Trimming := TTextTrimming.None; ATextLayout.TopLeft := PointF(0,0); ATextLayout.MaxSize := PointF(FksInputList.Width * 0.7, MaxSingle); ATextLayout.EndUpdate; //Result := ATextLayout.TextRect.Height+20; //if FSender <> '' then if AEmojiOnly then Result := ATextLayout.TextRect.Height+40 else Result := ATextLayout.TextRect.Height+40; end; destructor TksInputListChatItem.Destroy; begin FCached.Free; inherited; end; procedure TksInputListChatItem.DrawToCanvas(ACanvas: TCanvas); var r: TRectF; AEmojiOnly: Boolean; AStr: string; APadding: single; begin inherited; APadding := 8; if FCached.IsEmpty then begin AEmojiOnly := IsEmojiOnly; ATextLayout.Font.Size := 16; if AEmojiOnly then ATextLayout.Font.Size := 36; ATextLayout.BeginUpdate; AStr := FBody; ATextLayout.Text := Trim(AStr); ATextLayout.WordWrap := True; ATextLayout.Color := FTextColor; ATextLayout.HorizontalAlign := TTextAlign.Leading; ATextLayout.Padding.Rect := RectF(0, 0, 0, 0); ATextLayout.Trimming := TTextTrimming.None; ATextLayout.TopLeft := PointF(APadding, APadding); ATextLayout.MaxSize := PointF(FksInputList.Width * 0.7, MaxSingle); ATextLayout.EndUpdate; APadding := (8); FCached.SetSize(Round(GetScreenScale*(ATextLayout.Width+(APadding*2))), Round(GetScreenScale*((ATextLayout.Height+(APadding*2))))); FCached.Canvas.BeginScene(nil); try FCached.Clear(claNull); if AEmojiOnly = False then begin FCached.Canvas.Fill.Kind := TBrushKind.Solid; FCached.Canvas.Fill.Color := FColor; FCached.Canvas.FillRect(RectF(0, 0, Round(FCached.Width/GetScreenScale), Round(FCached.Height/GetScreenScale)), 8, 8, AllCorners, 1); end; FCached.Canvas.Fill.Color := FColor; ATextLayout.RenderLayout(FCached.Canvas); finally FCached.Canvas.EndScene; end; end; AStr := Trim(FSender); if AStr <> '' then AStr := AStr + ' - '; if FUse24HourTime then AStr := AStr + FormatDateTime('hh:nn', FDateTime) else AStr := AStr + FormatDateTime('h:nn am/pm', FDateTime); ACanvas.Fill.Color := claSilver; ACanvas.Font.Size := 12; r := FContentRect; r.Inflate(-4, -6); ACanvas.FillText(r, AStr, False, 1, [], FAlignment, TTextAlign.Leading); r := FCached.BoundsF; r.Width := r.Width/GetScreenScale; r.Height := r.Height/GetScreenScale; case FAlignment of TTextAlign.Leading: OffsetRect(r, (4), FContentRect.Top+(24)); TTextAlign.Center: OffsetRect(r, (4), FContentRect.Top+(24)); TTextAlign.Trailing: OffsetRect(r, FContentRect.Right-r.Width, FContentRect.Top+(24)); end; ACanvas.DrawBitmap(FCached, FCached.BoundsF, r, 1, True); end; class function TksInputListChatItem.GetClassID: string; begin Result := '{FD931C67-7C01-4C78-B3D4-EF66A94C2593}'; end; function TksInputListChatItem.GetHeight: Single; begin Result := CalculateHeight; end; function TksInputListChatItem.IsEmojiOnly: Boolean; var c: Char; begin Result := True; for c in FBody do begin if Ord(c) < 5000 then begin Result := False; Exit; end; end; end; procedure TksInputListChatItem.MouseDown; begin inherited; end; procedure TksInputListChatItem.SetAlignment(const Value: TTextAlign); begin if FAlignment <> Value then begin FAlignment := Value; Changed; end; end; procedure TksInputListChatItem.SetBody(const Value: string); begin if FBody <> Value then begin FBody := Value; Changed; end; end; procedure TksInputListChatItem.SetDateTime(const Value: TDateTime); begin if CompareDateTime(FDateTime, Value) <> 0 then begin FDateTime := Value; Changed; end; end; procedure TksInputListChatItem.SetSender(const Value: string); begin IF FSender <> Value then begin FSender := Value; Changed; end; end; procedure TksInputListChatItem.SetUse24HourTime(const Value: Boolean); begin if FUse24HourTime <> Value then begin FUse24HourTime := Value; Changed; end; end; procedure TksInputListChatItem.UpdateRects; begin inherited UpdateRects; end; initialization AAccessoriesList := TInputListAccessoryImages.Create; ATextLayout := TTextLayoutManager.DefaultTextLayout.Create; AScreenScale := 0; finalization AAccessoriesList.Free; ATextLayout.Free; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ORCAMENTO_FLUXO_CAIXA_PERIODO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit OrcamentoFluxoCaixaPeriodoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ContaCaixaVO; type [TEntity] [TTable('ORCAMENTO_FLUXO_CAIXA_PERIODO')] TOrcamentoFluxoCaixaPeriodoVO = class(TVO) private FID: Integer; FID_CONTA_CAIXA: Integer; FPERIODO: String; FNOME: String; //Transientes FContaCaixaNome: String; FContaCaixaVO: TContaCaixaVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CONTA_CAIXA', 'Id Conta Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA; [TColumnDisplay('CONTA_CAIXA.NOME', 'Conta Caixa Nome', 100, [ldGrid, ldLookup], ftString, 'ContaCaixaVO.TContaCaixaVO', True)] property ContaCaixaNome: String read FContaCaixaNome write FContaCaixaNome; [TColumn('PERIODO', 'Periodo', 16, [ldGrid, ldLookup, ldCombobox], False)] property Periodo: String read FPERIODO write FPERIODO; [TColumn('NOME', 'Nome', 240, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; //Transientes [TAssociation('ID', 'ID_CONTA_CAIXA')] property ContaCaixaVO: TContaCaixaVO read FContaCaixaVO write FContaCaixaVO; end; implementation constructor TOrcamentoFluxoCaixaPeriodoVO.Create; begin inherited; FContaCaixaVO := TContaCaixaVO.Create; end; destructor TOrcamentoFluxoCaixaPeriodoVO.Destroy; begin FreeAndNil(FContaCaixaVO); inherited; end; initialization Classes.RegisterClass(TOrcamentoFluxoCaixaPeriodoVO); finalization Classes.UnRegisterClass(TOrcamentoFluxoCaixaPeriodoVO); end.
{ NIM/NAMA : 16518305/QURRATA A'YUNI TANGGAL : JUMAT, 5 APRIL 2019 DEKSRIPSI : OLAH NILAI } Program nilai; {Program input nilai dan berhenti saat input -9999. Data divalidasi dari range 0-100. Ada yang salah diabaikan. Tulis berapa banyak mahasiswa. Berapa yang lulus, yang tidak lulus, dan yang tidak valid. bila tidak ada data valid tulis 0. Jika input pertama -9999 tuliskan "Data nilai kosong"} { Kamus } const NMin = 0; NMax = 100; var i, hitung, hitungLulus : integer; {indeks -_-} T : array [NMin..NMax] of real; {memori untuk input} N : integer; {indeks efektif} x, jumlah, rata : real; {nilai yang akan dibaca} { Algoritma } function IsWithinRange (X : real; min, max : real) : boolean; { Menghasilkan true jika min <= X <= max, menghasilkan false jika tidak } begin if (X>=min) and (X<=max) then IsWithinRange := true else IsWithinRange := false end; begin {mengisi array} i := NMin; read(x); if (x<>-9999) then begin while (x<>-9999) and (i<=NMax) do begin T[i] := x; i := i+1; read(x); end; N := i-1; {array yang diisi} {menghitung array yang valid} hitung := 0; jumlah := 0; for i:=0 to N do begin if ((IsWithinRange (T[i],0,100)) = true) then begin hitung := hitung+1; jumlah := jumlah+T[i]; end end; {hitung lulus} hitungLulus := 0; for i:=0 to N do begin if ((IsWithinRange (T[i],40,100)) = true) then begin hitungLulus := hitungLulus+1; end; end; {tampilan menu} writeln(hitung); if (hitung<>0) then begin writeln(hitungLulus); writeln(hitung-hitungLulus); rata := jumlah/hitung; {rata-rata} writeln(rata:0:2); end end else begin writeln('Data nilai kosong'); end end.
{ Copyright 2009-2011 10gen Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } { GridFS Unit - The classes in this unit are used to store and/or access a "Grid File System" (GridFS) on a MongoDB server. While primarily intended to store large documents that won't fit on the server as a single BSON object, GridFS may also be used to store large numbers of smaller files. See http://www.mongodb.org/display/DOCS/GridFS and http://www.mongodb.org/display/DOCS/When+to+use+GridFS. Objects of class TGridFS represent the interface to the GridFS. Objects of class TGridfile are used to access gridfiles and read from them. Objects of class TGridfileWriter are used to write buffered data to the GridFS. } unit GridFS; interface uses MongoDB, MongoBson, MongoApi; const GRIDFILE_DEFAULT = 0; GRIDFILE_NOMD5 = 1; GRIDFILE_COMPRESS = 2; GRIDFILE_ENCRYPT = 4; E_GridFSHandleIsNil = 90200; E_GridFileHandleIsNil = 90201; E_InternalErrorOIDDescriptorOfFile = 90202; E_UnableToCreateGridFS = 90203; type IGridfile = interface; IGridfileWriter = interface; TGridFS = class(TMongoObject) private { Pointer to externally managed data representing the GridFS } Handle: Pointer; { Holds a reference to the TMongo object used in construction. Prevents release until the TGridFS is destroyed. } conn: TMongo; fdb : UTF8String; FPrefix: UTF8String; procedure CheckHandle; procedure setAutoCheckLastError(value : Boolean); function getAutoCheckLastError : Boolean; function GetCaseInsensitiveFileNames: Boolean; procedure SetCaseInsensitiveFileNames(const Value: Boolean); public { Create a TGridFS object for accessing the GridFS on the MongoDB server. Parameter mongo is an already established connection object to the server; db is the name of the database in which to construct the GridFS. The prefix defaults to 'fs'.} constructor Create(mongo: TMongo; const db: UTF8String); overload; { Create a TGridFS object for accessing the GridFS on the MongoDB server. Parameter mongo is an already established connection object to the server; db is the name of the database in which to construct the GridFS. prefix is appended to the database name for the collections that represent the GridFS: 'db.prefix.files' & 'db.prefix.chunks'. } constructor Create(mongo: TMongo; const db, prefix: UTF8String); overload; { Store a file on the GridFS. filename is the path to the file. Returns True if successful; otherwise, False. } function storeFile(const FileName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; overload; { Store a file on the GridFS. filename is the path to the file. remoteName is the name that the file will be known as within the GridFS. Returns True if successful; otherwise, False. } function storeFile(const FileName, remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; overload; { Store a file on the GridFS. filename is the path to the file. remoteName is the name that the file will be known as within the GridFS. contentType is the MIME-type content type of the file. Returns True if successful; otherwise, False. } function storeFile(const FileName, remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; overload; { Remove a file from the GridFS. } procedure removeFile(const remoteName: UTF8String); { Store data as a GridFS file. Pointer is the address of the data and length is its size. remoteName is the name that the file will be known as within the GridFS. Returns True if successful; otherwise, False. } function store(p: Pointer; Length: Int64; const remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; overload; { Store data as a GridFS file. Pointer is the address of the data and length is its size. remoteName is the name that the file will be known as within the GridFS. contentType is the MIME-type content type of the file. Returns True if successful; otherwise, False. } function store(p: Pointer; Length: Int64; const remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; overload; { Create a TGridfileWriter object for writing buffered data to a GridFS file. remoteName is the name that the file will be known as within the GridFS. } function writerCreate(const remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): IGridfileWriter; overload; { Create a TGridfileWriter object for writing buffered data to a GridFS file. remoteName is the name that the file will be known as within the GridFS. contentType is the MIME-type content type of the file. } function writerCreate(const remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): IGridfileWriter; overload; { Locate a GridFS file by its remoteName and return a TGridfile object for accessing it. } function find(const remoteName: UTF8String; AWriteMode: Boolean): IGridfile; overload; { Locate a GridFS file by an TBson query document on the GridFS file descriptors. Returns a TGridfile object for accessing it. } function find(query: IBson; AWriteMode: Boolean): IGridfile; overload; { Destroy this GridFS object. Releases external resources. } function createGridFile: IGridFile; destructor Destroy; override; procedure removeFS; property AutoCheckLastError: Boolean read getAutoCheckLastError write setAutoCheckLastError; property CaseInsensitiveFileNames: Boolean read GetCaseInsensitiveFileNames write SetCaseInsensitiveFileNames; property Mongo: TMongo read conn; end; IGridFile = interface ['{DA93414C-1D0B-4F08-A78A-F1914A2E214C}'] { Get the Ith chunk of this gridfile. The content of the chunk is in the 'data' field of the returned TBson document. Returns nil if i is not in the range 0 to getChunkCount() - 1. } function getChunk(i: Integer): IBson; { Get the number of chunks into which the file is divided. } function getChunkCount: Integer; { Get the number of chunks into which the file is divided. } function getStoredChunkCount: UInt64; { Get a cursor for stepping through a range of chunks of this gridfile. i is the index of the first chunk to be returned. count is the number of chunks to return. Returns nil if there are no chunks in the specified range. } function getChunks(i: Integer; Count: Integer): IMongoCursor; { Get the size of the chunks into which the file is divided. } function getChunkSize: Integer; { Get the content type of this gridfile. } function getContentType: UTF8String; { Get the descriptor of this gridfile as a TBson document. } function getDescriptor: IBson; { Get the filename (remoteName) of this gridfile. } function getFilename: UTF8String; { Get the length of this gridfile. } function getLength: UInt64; { Get the MD5 hash of this gridfile. This is a 16-digit hex string. } function getMD5: UTF8String; { Get any metadata associated with this gridfile as a TBson document. Returns nil if there is none. } function getMetadata: IBson; { Get the upload date of this gridfile. } function getUploadDate: TDateTime; { read data from this gridfile. The gridfile maintains a current position so that successive reads will return consecutive data. The data is read to the address indicated by p and length bytes are read. The size of the data read is returned and can be less than length if there was not enough data remaining to be read. } function read(p: Pointer; Length: UInt64): UInt64; { seek to a specified offset within the gridfile. read() will then return data starting at that location. Returns the position that was set. This can be at the end of the gridfile if offset is greater the length of this gridfile. } function seek(offset: UInt64): UInt64; function getID : IBsonOID; function Handle : Pointer; end; IGridfileWriter = interface(IGridFile) ['{1BD1F2BA-C045-47CD-B1C7-611A77BCB590}'] { Finish with this IGridfileWriter. Flushes any data remaining to be written to a chunk and posts the 'directory' information of the gridfile to the GridFS. Returns True if successful; otherwise, False. } function finish: Boolean; { Write data to this IGridfileWriter. p is the address of the data and length is its size. Multiple calls to write() may be made to append successive data. } function Write(p: Pointer; Length: UInt64): UInt64; function truncate(newSize: UInt64): UInt64; function expand(bytesToExpand: UInt64): UInt64; function setSize(newSize: UInt64): UInt64; end; implementation uses SysUtils; // START resource string wizard section const SFiles_id = 'files_id'; SChunks = '.chunks'; SFs = 'fs'; SFilename = 'filename'; // END resource string wizard section // START resource string wizard section resourcestring SGridFSHandleIsNil = 'GridFS Handle is nil (D%d)'; SGridFileHandleIsNil = 'GridFile Handle is nil (D%d)'; SUnableToCreateGridFS = 'Unable to create GridFS (D%d)'; // END resource string wizard section type { Objects of class TGridfile are used to access gridfiles and read from them. } TGridfile = class(TMongoInterfacedObject, IGridFile) private procedure CheckHandle; protected { Pointer to externally managed data representing the gridfile } FHandle: Pointer; { Hold a reference to the TGridFS object used in construction of this TGridfile. Prevents release until this TGridfile is destroyed. } gfs: TGridFS; { Create a TGridfile object. Internal use only by TGridFS.find(). } constructor Create(gridfs: TGridFS); procedure DestroyGridFile; public function getStoredChunkCount: UInt64; { Get the filename (remoteName) of this gridfile. } function getFilename: UTF8String; { Get the size of the chunks into which the file is divided. } function getChunkSize: Integer; { Get the length of this gridfile. } function getLength: UInt64; { Get the content type of this gridfile. } function getContentType: UTF8String; { Get the upload date of this gridfile. } function getUploadDate: TDateTime; { Get the MD5 hash of this gridfile. This is a 16-digit hex string. } function getMD5: UTF8String; { Get any metadata associated with this gridfile as a TBson document. Returns nil if there is none. } function getMetadata: IBson; { Get the number of chunks into which the file is divided. } function getChunkCount: Integer; { Get the descriptor of this gridfile as a TBson document. } function getDescriptor: IBson; { Get the Ith chunk of this gridfile. The content of the chunk is in the 'data' field of the returned TBson document. Returns nil if i is not in the range 0 to getChunkCount() - 1. } function getChunk(i: Integer): IBson; { Get a cursor for stepping through a range of chunks of this gridfile. i is the index of the first chunk to be returned. count is the number of chunks to return. Returns nil if there are no chunks in the specified range. } function getChunks(i: Integer; Count: Integer): IMongoCursor; { read data from this gridfile. The gridfile maintains a current position so that successive reads will return consecutive data. The data is read to the address indicated by p and length bytes are read. The size of the data read is returned and can be less than length if there was not enough data remaining to be read. } function read(p: Pointer; Length: UInt64): UInt64; { seek to a specified offset within the gridfile. read() will then return data starting at that location. Returns the position that was set. This can be at the end of the gridfile if offset is greater the length of this gridfile. } function seek(offset: UInt64): UInt64; function Handle: Pointer; function getID: IBsonOID; { Destroy this TGridfile object. Releases external resources. } destructor Destroy; override; end; type { Objects of class TGridfileWriter are used to write buffered data to the GridFS. } TGridfileWriter = class(TGridFile, IGridfileWriter) private FInited: Boolean; public { Create a TGridfile writer on the given TGridFS that will write data to the given remoteName. } constructor Create(gridfs: TGridFS; remoteName: UTF8String; AInit: Boolean; AMeta: Pointer; Flags: Integer); overload; { Create a TGridfile writer on the given TGridFS that will write data to the given remoteName. contentType is the MIME-type content type of the gridfile to be written. } constructor Create(gridfs: TGridFS; const remoteName, contentType: UTF8String; AInit: Boolean; AMeta: Pointer; Flags: Integer); overload; { write data to this TGridfileWriter. p is the address of the data and length is its size. Multiple calls to write() may be made to append successive data. } function write(p: Pointer; Length: UInt64): UInt64; { Finish with this TGridfileWriter. Flushes any data remaining to be written to a chunk and posts the 'directory' information of the gridfile to the GridFS. Returns True if successful; otherwise, False. } function truncate(newSize: UInt64): UInt64; function expand(bytesToExpand: UInt64): UInt64; { setSize supercedes truncate in the sense it can change the file size up or down. If making file size larger, file will be zero filled } function setSize(newSize: UInt64): UInt64; function finish: Boolean; { Destroy this TGridfileWriter. Calls finish() if necessary and releases external resources. } destructor Destroy; override; end; { TGridFS } constructor TGridFS.Create(mongo: TMongo; const db, prefix: UTF8String); begin inherited Create; {$IFDEF OnDemandMongoCLoad} InitMongoDBLibrary; {$ENDIF} FPrefix := prefix; fdb := db; conn := mongo; Handle := gridfs_alloc; if gridfs_init(mongo.Handle, PAnsiChar(fdb), PAnsiChar(prefix), Handle) <> 0 then begin gridfs_dealloc(Handle); raise EMongo.Create(SUnableToCreateGridFS, E_UnableToCreateGridFS); end; AutoCheckLastError := True; end; constructor TGridFS.Create(mongo: TMongo; const db: UTF8String); begin inherited Create; Create(mongo, db, SFs); end; destructor TGridFS.Destroy; begin if Handle <> nil then begin gridfs_destroy(Handle); gridfs_dealloc(Handle); Handle := nil; end; inherited; end; procedure TGridFS.CheckHandle; begin if Handle = nil then raise EMongo.Create(SGridFSHandleIsNil, E_GridFSHandleIsNil); end; function TGridFS.storeFile(const FileName, remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; var RetVal : Integer; begin CheckHandle; conn.autoCmdResetLastError(fdb, False); RetVal := gridfs_store_file(Handle, PAnsiChar(FileName), PAnsiChar(remoteName), PAnsiChar(contentType), Flags); Result := RetVal = 0; conn.autoCheckCmdLastError(fdb, False); end; function TGridFS.storeFile(const FileName, remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; begin Result := storeFile(FileName, remoteName, '', Flags); end; function TGridFS.storeFile(const FileName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; begin Result := storeFile(FileName, FileName, '', Flags); end; procedure TGridFS.removeFile(const remoteName: UTF8String); begin CheckHandle; gridfs_remove_filename(Handle, PAnsiChar(remoteName)); end; procedure TGridFS.setAutoCheckLastError(value: Boolean); begin conn.AutoCheckLastError := Value; end; function TGridFS.store(p: Pointer; Length: Int64; const remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; begin CheckHandle; Result := (gridfs_store_buffer(Handle, p, Length, PAnsiChar(remoteName), PAnsiChar(contentType), Flags) = 0); end; function TGridFS.store(p: Pointer; Length: Int64; const remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): Boolean; begin Result := store(p, Length, remoteName, '', Flags); end; function TGridFS.writerCreate(const remoteName, contentType: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): IGridfileWriter; begin CheckHandle; Result := TGridfileWriter.Create(Self, remoteName, contentType, True, bsonEmpty.Handle, Flags); end; function TGridFS.writerCreate(const remoteName: UTF8String; Flags: Integer = GRIDFILE_DEFAULT): IGridfileWriter; begin Result := writerCreate(remoteName, '', Flags); end; function TGridFS.createGridFile: IGridFile; begin CheckHandle; Result := TGridFile.Create(Self); end; function TGridFS.find(query: IBson; AWriteMode: Boolean): IGridfile; var gf: IGridfile; AHandle : Pointer; meta : Pointer; begin CheckHandle; gf := nil; if not AWriteMode then begin gf := TGridfile.Create(Self); AHandle := gf.Handle; end else AHandle := gridfile_create; try if gridfs_find_query(Handle, query.Handle, AHandle) = 0 then begin if AWriteMode then begin meta := bson_create; try gridfile_get_descriptor( AHandle, meta ); gf := TGridfileWriter.Create(Self, gridfile_get_filename(AHandle), True, Meta, GRIDFILE_DEFAULT); gridfile_destroy(AHandle); finally bson_dealloc(meta); // Dont' call Destroy for this object, data is owned by gridfile end; end; Result := gf; end else Result := nil; finally if AWriteMode then gridfile_dealloc(AHandle); end; end; function TGridFS.getAutoCheckLastError: Boolean; begin Result := conn.AutoCheckLastError; end; function TGridFS.find(const remoteName: UTF8String; AWriteMode: Boolean): IGridfile; begin if CaseInsensitiveFileNames then Result := find(BSON([SFilename, UpperCase(remoteName)]), AWriteMode) else Result := find(BSON([SFilename, remoteName]), AWriteMode); end; function TGridFS.GetCaseInsensitiveFileNames: Boolean; begin CheckHandle; Result := gridfs_get_caseInsensitive(Handle); end; procedure TGridFS.removeFS; begin conn.drop(fdb + '.' + FPrefix + '.files'); conn.drop(fdb + '.' + FPrefix + '.chunks'); end; procedure TGridFS.SetCaseInsensitiveFileNames(const Value: Boolean); begin CheckHandle; gridfs_set_caseInsensitive(Handle, Value); end; { TGridfileWriter } constructor TGridfileWriter.Create(gridfs: TGridFS; const remoteName, contentType: UTF8String; AInit: Boolean; AMeta: Pointer; Flags: Integer); begin inherited Create(gridfs); if AInit then begin gridfile_init(gfs.Handle, AMeta, Handle); FInited := True; end; gridfile_writer_init(Handle, gridfs.Handle, PAnsiChar(remoteName), PAnsiChar(contentType), Flags); end; constructor TGridfileWriter.Create(gridfs: TGridFS; remoteName: UTF8String; AInit: Boolean; AMeta: Pointer; Flags: Integer); begin Create(gridfs, remoteName, '', AInit, AMeta, Flags); end; function TGridfileWriter.write(p: Pointer; Length: UInt64): UInt64; begin CheckHandle; Result := gridfile_write_buffer(Handle, p, Length); end; function TGridfileWriter.finish: Boolean; begin if Handle = nil then Result := true else begin Result := (gridfile_writer_done(Handle) = 0); if FInited then DestroyGridFile else begin gridfile_dealloc(Handle); FHandle := nil; end; end; end; destructor TGridfileWriter.Destroy; begin finish; inherited; end; function TGridfileWriter.expand(bytesToExpand: UInt64): UInt64; begin CheckHandle; Result := gridfile_expand(Handle, bytesToExpand); end; function TGridfileWriter.setSize(newSize: UInt64): UInt64; begin CheckHandle; Result := gridfile_set_size(Handle, newSize); end; function TGridfileWriter.truncate(newSize: UInt64): UInt64; begin CheckHandle; Result := gridfile_truncate(Handle, newSize); end; { TGridfile } constructor TGridfile.Create(gridfs: TGridFS); begin inherited Create; gfs := gridfs; FHandle := gridfile_create; end; destructor TGridfile.Destroy; begin DestroyGridFile; inherited; end; procedure TGridfile.CheckHandle; begin if FHandle = nil then raise EMongo.Create(SGridFileHandleIsNil, E_GridFileHandleIsNil); end; procedure TGridfile.DestroyGridFile; begin if FHandle <> nil then begin gridfile_destroy(FHandle); gridfile_dealloc(FHandle); FHandle := nil; end; end; function TGridfile.getFilename: UTF8String; begin CheckHandle; Result := UTF8String(gridfile_get_filename(FHandle)); end; function TGridfile.getChunkSize: Integer; begin CheckHandle; Result := gridfile_get_chunksize(FHandle); end; function TGridfile.getLength: UInt64; begin CheckHandle; Result := gridfile_get_contentlength(FHandle); end; function TGridfile.getContentType: UTF8String; begin CheckHandle; Result := UTF8String(gridfile_get_contenttype(FHandle)); end; function TGridfile.getUploadDate: TDateTime; begin CheckHandle; Result := Int64toDouble(gridfile_get_uploaddate(FHandle)) / (1000 * 24 * 60 * 60) + 25569; end; function TGridfile.getMD5: UTF8String; begin CheckHandle; Result := UTF8String(gridfile_get_md5(FHandle)); end; function TGridfile.getMetadata: IBson; var b: Pointer; begin CheckHandle; b := bson_create; try gridfile_get_metadata(FHandle, b, True); if bson_size(b) <= 5 then Result := nil else Result := NewBsonCopy(b); finally bson_dealloc(b); // Dont' call Destroy for this object, data is owned by gridfile end; end; function TGridfile.getChunkCount: Integer; begin CheckHandle; Result := gridfile_get_numchunks(FHandle); end; function TGridfile.getDescriptor: IBson; var b : Pointer; begin CheckHandle; b := bson_create; try gridfile_get_descriptor(FHandle, b); Result := NewBsonCopy(b); finally bson_dealloc(b); // Dont' call Destroy for this object, data is owned by gridfile end; end; function TGridfile.getChunk(i: Integer): IBson; var b: IBson; h : Pointer; begin CheckHandle; h := bson_create; try b := NewBson(h); except bson_dealloc_and_destroy(h); raise; end; gridfile_get_chunk(FHandle, i, b.Handle); if b.size <= 5 then Result := nil else Result := b; end; function TGridfile.getChunks(i: Integer; Count: Integer): IMongoCursor; var Cursor: IMongoCursor; begin CheckHandle; Cursor := NewMongoCursor; Cursor.Handle := gridfile_get_chunks(FHandle, i, Count); if Cursor.Handle = nil then Result := nil else begin Cursor.FindCalled; Result := Cursor; end; end; function TGridfile.getID: IBsonOID; var oid : TBsonOIDValue; begin CheckHandle; oid := gridfile_get_id(FHandle); Result := NewBsonOID; Result.setValue(oid); end; function TGridfile.getStoredChunkCount: UInt64; var buf : IBsonBuffer; q : IBson; id : TBsonOIDValue; oid : IBsonOID; begin CheckHandle; id := gridfile_get_id(FHandle); oid := NewBsonOID; oid.setValue(id); buf := NewBsonBuffer; buf.Append(SFiles_id, oid); q := buf.finish; Result := Trunc(gfs.conn.count(gfs.fdb + '.' + gfs.FPrefix + SChunks, q)); end; function TGridfile.Handle: Pointer; begin Result := FHandle; end; function TGridfile.read(p: Pointer; Length: UInt64): UInt64; begin CheckHandle; Result := gridfile_read_buffer(FHandle, p, Length); end; function TGridfile.seek(offset: UInt64): UInt64; begin CheckHandle; Result := gridfile_seek(FHandle, offset); end; end.
{ *********************************************************************** } { } { Модуль реализации класса TProcessTimer - инструмент } { } { проверки времени выполнения алгоритмов } { } { Copyright © 2003, 2007 UzySoft } { } { Пожелания и предложения - jack@uzl.tula.net } { *********************************************************************** } unit ProcTime; interface uses SysUtils; type TProcessTimer = class private FBeginTime: TDateTime; FEndTime: TDateTime; FProcessing: Boolean; function GetTextTime: string; function GetTime: Extended; public constructor Create; procedure BeginProcess; // Запускает таймер function EndProcess: string; // Останавливает таймер property Processing: Boolean read FProcessing; // Индикатор работы таймера property TextTime: string read GetTextTime; // Время как текст (сек.) property Time: Extended read GetTime; // Время как число (сек.) end; implementation { TProcessTimer } // Вычисляет количество миллисекунд между двумя датами function MilliSecondsBetween(const ANow, AThen: TDateTime): Int64; begin if ANow < AThen then Result := Trunc(MSecsPerDay * (AThen - ANow)) else Result := Trunc(MSecsPerDay * (ANow - AThen)); end; constructor TProcessTimer.Create; begin FBeginTime := Now; FEndTime := FBeginTime; FProcessing := False; end; procedure TProcessTimer.BeginProcess; begin if not Processing then begin FBeginTime := Now; FProcessing := True end; end; function TProcessTimer.EndProcess: string; begin if Processing then begin FEndTime := Now; FProcessing := False; Result := TextTime; Beep end; end; function TProcessTimer.GetTextTime: string; begin Result := FloatToStr(Round(Time) / 1000) end; function TProcessTimer.GetTime: Extended; begin if Processing then Result := MilliSecondsBetween(FBeginTime, Now) else Result := MilliSecondsBetween(FBeginTime, FEndTime) end; end.
unit BlockProperties; {$mode objfpc}{$H+} interface uses Buttons, Classes, Grids, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, GraphComponents, StdCtrls; type { TBlockPropertiesDialog } TBlockPropertiesDialog = class(TForm) ApplyButton: TButton; CancelButton: TButton; StringGrid1: TStringGrid; procedure ApplyButtonClick(Sender: TObject); procedure CancelButtonClick(Sender: TObject); procedure StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); procedure ValidateInput(Sender: TObject); private FDevice: TBlock; protected procedure SetDevice(ADevice: TBlock); public { public declarations } property Device: TBlock write SetDevice; end; var BlockPropertiesDialog: TBlockPropertiesDialog; implementation { TBlockPropertiesDialog } procedure TBlockPropertiesDialog.StringGrid1SelectCell(Sender: TObject; aCol, aRow: Integer; var CanSelect: Boolean); begin CanSelect := (aRow > 0) and (aCol > 1); end; procedure TBlockPropertiesDialog.ValidateInput(Sender: TObject); var PropIdx: Integer; PropTyp, PropVal: string; v, e: Integer; f: Real; begin with StringGrid1 do begin PropIdx := Row; PropTyp := Rows[PropIdx].Strings[1]; PropVal := Rows[PropIdx].Strings[2]; if PropTyp = 'Integer' then begin Val(PropVal, v, e); end else if PropTyp = 'Real' then begin {end else if PropTyp = 'Symbol' then begin end else if PropTyp = 'Set' then begin end else if PropTyp = 'List' then begin end else if PropTyp = 'Collection' then begin end else if PropTyp = 'Binary' then begin} Val(PropVal, f, e); end else begin e := 0; end; if e <> 0 then begin ShowMessage('Invalid input "' + PropVal + '" for property type ' + PropTyp); end; end; end; procedure TBlockPropertiesDialog.ApplyButtonClick(Sender: TObject); var DevicePropQty: Integer; i: Integer; begin Visible := not Assigned(FDevice); with FDevice, StringGrid1 do begin DevicePropQty := PropQty; for i := 0 to DevicePropQty - 1 do with Rows[i + 1] do begin PropVal[i] := Strings[2]; end; end; end; procedure TBlockPropertiesDialog.CancelButtonClick(Sender: TObject); begin Visible := False; end; procedure TBlockPropertiesDialog.SetDevice(ADevice: TBlock); var DevicePropQty: Integer; i: Integer; begin FDevice := ADevice; with FDevice, StringGrid1 do begin DevicePropQty := PropQty; RowCount := DevicePropQty + 1; for i := 0 to DevicePropQty - 1 do with Rows[i + 1] do begin Strings[0] := PropName[i]; Strings[1] := PropType[i]; Strings[2] := PropVal[i]; end; end; end; initialization {$R blockproperties.lfm} end.
{: GLMisc<p> Object with support for complex polygons.<p> <b>Historique : </b><font size=-1><ul> <li>21/02/01 - Egg - Now XOpenGL based (multitexture) <li>08/01/01 - Egg - Compatibility fix (TGLLineNodes change), Delphi 4 compatibility (removed TVectorPool) and added/renamed some properties, various fixes <li>08/10/00 - Egg - Added header, code contributed by Uwe Raabe </ul> } unit GLMultiPolygon; interface uses Classes, OpenGL12, Geometry, GLScene, GLObjects, GLMisc, GLTexture; type // TMultiPolygon // {: A polygon that can have holes and multiple contours.<p> Use the Contour property to access a contour or one of the AddNode methods to add a node to a contour (contours are allocated automatically). } TMultiPolygon = class (TGLSceneObject) private { Private Declarations } FParts: TPolygonParts; FContours : array of TGLNodes; protected { Protected Declarations } function GetContour(i : Integer): TGLNodes; procedure SetContour(i : Integer; const Value: TGLNodes); procedure SetParts(const value : TPolygonParts); procedure RenderTesselatedPolygon(textured : Boolean; normal : PAffineVector; invertNormals: Boolean); function GetContourCount : Integer; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure BuildList(var rci : TRenderContextInfo); override; procedure AddNode(const i : Integer; const coords : TGLCoordinates); overload; procedure AddNode(const i : Integer; const X, Y, Z: TGLfloat); overload; procedure AddNode(const i : Integer; const value : TVector); overload; procedure AddNode(const i : Integer; const value : TAffineVector); overload; property Contours[i : Integer] : TGLNodes read GetContour write SetContour; property ContourCount : Integer read GetContourCount; procedure Clear; published { Published Declarations } property Parts : TPolygonParts read FParts write SetParts default [ppTop, ppBottom]; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- uses SysUtils, VectorLists, XOpenGL; // ------------------ // ------------------ TMultiPolygon ------------------ // ------------------ // Create // constructor TMultiPolygon.Create(AOwner: TComponent); begin inherited; FParts:=[ppTop, ppBottom]; end; // Destroy // destructor TMultiPolygon.Destroy; begin Clear; inherited; end; // Assign // procedure TMultiPolygon.Assign(Source: TPersistent); var i : Integer; begin if Source is TMultiPolygon then begin Clear; for i:=Low(TMultiPolygon(Source).FContours) to High(TMultiPolygon(Source).FContours) do Contours[i]:=TMultiPolygon(Source).FContours[i]; FParts:=TMultiPolygon(Source).FParts; end; inherited; end; // AddNode (vector) // procedure TMultiPolygon.AddNode(const i : Integer; const value : TVector); begin Contours[i].Add.AsVector:=value; end; // AddNode (float) // procedure TMultiPolygon.AddNode(const i : Integer; const x, y, z : TGLfloat); begin Contours[i].Add.AsVector:=PointMake(x, y, z); end; // AddNode (coords) // procedure TMultiPolygon.AddNode(const i : Integer; const coords : TGLCoordinates); begin Contours[i].Add.AsVector:=coords.AsVector; end; // AddNode (affine vector) // procedure TMultiPolygon.AddNode(const I: Integer; const value: TAffineVector); begin Contours[i].Add.AsVector:=VectorMake(value); end; // Clear // procedure TMultiPolygon.Clear; var i : Integer; begin if Assigned(FContours) then for i:=Low(FContours) to High(FContours) do FContours[i].Free; end; // BuildList // procedure TMultiPolygon.BuildList(var rci: TRenderContextInfo); var normal : TAffineVector; p : PAffineVector; n : Integer; begin if ContourCount<1 then Exit; // find normal vector to contour[0] p:=nil; for n:=2 to Contours[0].Count-1 do begin CalcPlaneNormal(Contours[0].Vector(0), Contours[0].Vector(1), Contours[0].Vector(N), normal); if VectorNorm(normal)>0 then begin NormalizeVector(normal); p:=@normal; Break; end; end; // Render if Assigned(p) then begin // tessellate top polygon if ppTop in FParts then RenderTesselatedPolygon(True, p, False); // tessellate bottom polygon if ppBottom in FParts then begin ScaleVector(normal, -1); RenderTesselatedPolygon(True, p, True) end; end; end; // GetContourCount // function TMultiPolygon.GetContourCount : Integer; begin if Assigned(FContours) then Result:=High(FContours)+1 else Result:=0; end; // GetContour // function TMultiPolygon.GetContour(i : Integer): TGLNodes; var k : Integer; begin Assert(i>=0); if (not Assigned(FContours)) or (i>High(FContours)) then begin k:=High(FContours)+1; SetLength(FContours, i+1); while k<=i do begin FContours[k]:=TGLNodes.Create(Self); Inc(k); end; end; Result:=FContours[i]; end; // SetContour // procedure TMultiPolygon.SetContour(i : Integer; const value: TGLNodes); begin Contours[i].Assign(value); end; // SetParts // procedure TMultiPolygon.SetParts(const value : TPolygonParts); begin if FParts<>value then begin FParts:=value; StructureChanged; end; end; // // Tessellation routines (OpenGL callbacks) // var vVertexPool : TAffineVectorList; procedure tessError(errno : TGLEnum); stdcall; begin Assert(False, IntToStr(errno)+' : '+gluErrorString(errno)); end; procedure tessIssueVertex(vertexData : Pointer); stdcall; begin xglTexCoord2fv(vertexData); glVertex3fv(vertexData); end; procedure tessCombine(coords : PDoubleVector; vertex_data : Pointer; weight : PGLFloat; var outData : Pointer); stdcall; var i : Integer; begin i:=vVertexPool.Add(coords[0], coords[1], coords[2]); outData:=@vVertexPool.List[i]; end; // RenderTesselatedPolygon // procedure TMultiPolygon.RenderTesselatedPolygon(textured : Boolean; normal : PAffineVector; invertNormals : Boolean); var i,n : Integer; tess : PGLUTesselator; dblVector : TAffineDblVector; begin if (ContourCount>0) and (FContours[0].Count>2) then begin // Vertex count n:=0; for i:=Low(FContours) to High(FContours) do n:=n+FContours[i].Count; // Create and initialize the GLU tesselator vVertexPool:=TAffineVectorList.Create; vVertexPool.Capacity:=4*n; tess:=gluNewTess; try gluTessCallback(tess, GLU_TESS_BEGIN, @glBegin); if textured then gluTessCallback(tess, GLU_TESS_VERTEX, @tessIssueVertex) else gluTessCallback(tess, GLU_TESS_VERTEX, @glVertex3fv); gluTessCallback(tess, GLU_TESS_END, @glEnd); gluTessCallback(tess, GLU_TESS_ERROR, @tessError); gluTessCallback(tess, GLU_TESS_COMBINE, @tessCombine); // Issue normal if Assigned(normal) then begin glNormal3fv(PGLFloat(normal)); gluTessNormal(tess, normal[0], normal[1], normal[2]); end; gluTessProperty(Tess,GLU_TESS_WINDING_RULE,GLU_TESS_WINDING_POSITIVE); // Issue polygon gluTessBeginPolygon(tess, nil); for n:=Low(FContours) to High(FContours) do begin gluTessBeginContour(tess); if invertNormals xor (n>0) then begin for i:=FContours[n].Count-1 downto 0 do begin SetVector(dblVector, PAffineVector(FContours[n].Items[i].AsAddress)^); gluTessVertex(tess, dblVector, FContours[n].Items[i].AsAddress); end; end else begin for i:=0 to FContours[n].Count-1 do begin SetVector(dblVector, PAffineVector(FContours[n].Items[i].AsAddress)^); gluTessVertex(tess, dblVector, FContours[n].Items[i].AsAddress); end; end; gluTessEndContour(tess); end; gluTessEndPolygon(tess); finally gluDeleteTess(tess); vVertexPool.Free; vVertexPool:=nil; end; end; end; end.
program SimplePolitics; uses TerminalUserInput; const YEAR_TRUMP_ELECTED = 2016; (* Function Definition *) function calculateAgeWhenTrumpElected(birthYear: Integer): Integer; var temp: Integer; begin temp := YEAR_TRUMP_ELECTED - birthYear; result := temp; end; (* Main Procedure *) procedure Main(); var name: String; ageWhenTrumpElected, birthYear: Integer; answer: Boolean; begin WriteLn('Please enter your name: '); ReadLn(name); WriteLn('What year were you born?: '); ReadLn(birthYear); ageWhenTrumpElected := calculateAgeWhenTrumpElected(birthYear); WriteLn('You were ', ageWhenTrumpElected, ' years old when Trump was elected.'); answer := ReadBoolean('Did you support Brexit? '); if answer = true then WriteLn(name, ' is a Brexit supporter.') else WriteLn(name, ' is NOT a Brexit supporter.'); WriteLn('Press Enter to Continue.'); ReadLn(); end; begin Main(); end.
unit CommonListFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, BaseObjects, StdCtrls, ExtCtrls, ToolWin, ComCtrls, ActnList, Registrator, TreeNodeFrame; type TCommonListEditState = (clsInitialState, clsObjectAdded, clsObjectEdited); TAllowedAction = (actnAdd, actnEdit, actnDelete); TAllowedActions = set of TAllowedAction; TfrmCommonList = class(TfrmCommonFrame) //TfrmCommonList = class(TFrame) tlbrEditList: TToolBar; pnlProperties: TPanel; Splitter1: TSplitter; actnCommonList: TActionList; actnAddObject: TAction; actnStartEdit: TAction; actnFinishEdit: TAction; actnCancelEdit: TAction; actnDeleteObject: TAction; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; pnlList: TPanel; lbxObjects: TListBox; sbReport: TStatusBar; procedure lbxObjectsClick(Sender: TObject); procedure actnAddObjectExecute(Sender: TObject); procedure actnStartEditExecute(Sender: TObject); procedure actnFinishEditExecute(Sender: TObject); procedure actnCancelEditExecute(Sender: TObject); procedure actnDeleteObjectExecute(Sender: TObject); procedure actnAddObjectUpdate(Sender: TObject); procedure actnStartEditUpdate(Sender: TObject); procedure actnFinishEditUpdate(Sender: TObject); procedure actnCancelEditUpdate(Sender: TObject); procedure actnDeleteObjectUpdate(Sender: TObject); private { Private declarations } FObjectList, FSelectedObjects: TRegisteredIDObjects; FObjectEditFrameClass: TCommonFrameClass; FObjectEditFrame: TfrmCommonFrame; FRegistrator: TRegistrator; FEditingObjectClass: TIDObjectClass; FAllowedActions: TAllowedActions; FOnLoadList: TNotifyEvent; FOnObjectEditFinished: TNotifyEvent; FStatusString: string; procedure SetObjectList(const Value: TRegisteredIDObjects); procedure SetObjectEditFrameClass(const Value: TCommonFrameClass); procedure ClearSelection; procedure AddItem(AObject: TIDObject); //procedure UpdateItem(AObject: TIDObject); procedure DeleteItem(AObject: TIDObject); function FindItem(AObject: TIDObject): integer; procedure SetEditingObjectClass(const Value: TIDObjectClass); function GetActiveObject: TIDObject; procedure CloseForm(Sender: TObject; var CanClose: Boolean); procedure SetStatusString(const Value: string); function GetSelectedObjects: TIDObjects; procedure ReportStatus(S: string); protected FActiveObject: TIDObject; FCommonListEditState: TCommonListEditState; procedure SetRegistrator(const Value: TRegistrator); virtual; procedure AddObject; virtual; procedure EditObject; virtual; procedure FinishEditObject; virtual; procedure CancelEditObject; virtual; procedure DeleteObject; virtual; public { Public declarations } property ObjectEditFrame: TfrmCommonFrame read FObjectEditFrame; property ObjectEditFrameClass: TCommonFrameClass read FObjectEditFrameClass write SetObjectEditFrameClass; property ObjectList: TRegisteredIDObjects read FObjectList write SetObjectList; property ActiveObject: TIDObject read GetActiveObject; property SelectedObjects: TIDObjects read GetSelectedObjects; property Registrator: TRegistrator read FRegistrator write SetRegistrator; property EditingObjectClass: TIDObjectClass read FEditingObjectClass write SetEditingObjectClass; procedure Clear; override; function CheckInput: boolean; virtual; property AllowedActions: TAllowedActions read FAllowedActions write FAllowedActions; property OnLoadList: TNotifyEvent read FOnLoadList write FOnLoadList; property OnObjectEditFinished: TNotifyEvent read FOnObjectEditFinished write FOnObjectEditFinished; property StatusString: string read FStatusString write SetStatusString; property EditState: TCommonListEditState read FCommonListEditState; procedure Finish; virtual; procedure Cancel; virtual; procedure MakeList; virtual; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmCommonList: TfrmCommonList; implementation {$R *.dfm} { TfrmCommonList } procedure TfrmCommonList.SetObjectEditFrameClass( const Value: TCommonFrameClass); begin if FObjectEditFrameClass <> Value then begin FObjectEditFrameClass := Value; if Assigned(FObjectEditFrame) then FObjectEditFrame.Free; if Assigned(FObjectEditFrameClass) then begin FObjectEditFrame := FObjectEditFrameClass.Create(Self.Owner); FObjectEditFrame.Parent := pnlProperties; FObjectEditFrame.Align := alClient; end else FObjectEditFrame := nil; end; end; procedure TfrmCommonList.SetObjectList(const Value: TRegisteredIDObjects); begin //if FObjectList <> Value then begin FObjectList := Value; if Assigned(FObjectList) then if not Assigned(FOnLoadList) then MakeList else FOnLoadList(lbxObjects); end; end; procedure TfrmCommonList.lbxObjectsClick(Sender: TObject); begin inherited; FActiveObject := TIDObject(lbxObjects.Items.Objects[lbxObjects.ItemIndex]); if Assigned(FObjectEditFrame) then if lbxObjects.ItemIndex > -1 then FObjectEditFrame.EditingObject := TIDObject(lbxObjects.Items.Objects[lbxObjects.ItemIndex]) else FObjectEditFrame.Clear; end; procedure TfrmCommonList.MakeList; begin FObjectList.MakeList(lbxObjects.Items, true) end; constructor TfrmCommonList.Create(AOwner: TComponent); begin inherited; FCommonListEditState := clsInitialState; FObjectEditFrameClass := nil; if (Owner is TForm) then (Owner as TForm).OnCloseQuery := CloseForm; AllowedActions := [actnAdd, actnEdit, actnDelete]; end; procedure TfrmCommonList.actnAddObjectExecute(Sender: TObject); begin inherited; AddObject; end; procedure TfrmCommonList.actnStartEditExecute(Sender: TObject); begin inherited; EditObject; end; procedure TfrmCommonList.actnFinishEditExecute(Sender: TObject); begin inherited; FinishEditObject; end; procedure TfrmCommonList.actnCancelEditExecute(Sender: TObject); begin inherited; CancelEditObject; end; procedure TfrmCommonList.actnDeleteObjectExecute(Sender: TObject); begin inherited; DeleteObject; end; procedure TfrmCommonList.AddItem(AObject: TIDObject); var iIndex: integer; begin iIndex := FindItem(AObject); ClearSelection; if iIndex = -1 then begin iIndex := lbxObjects.Items.AddObject(AObject.List, AObject); lbxObjects.Selected[iIndex] := true; end else begin lbxObjects.Items[iIndex] := AObject.List; lbxObjects.Items.Objects[iIndex] := AObject; lbxObjects.Selected[iIndex] := true; end; end; procedure TfrmCommonList.AddObject; begin FActiveObject := ObjectList.Add; lbxObjects.ItemIndex := lbxObjects.Count - 1; FObjectEditFrame.EditingObject := FActiveObject; lbxObjects.Enabled := false; FCommonListEditState := clsObjectAdded; FObjectEditFrame.ViewOnly := false; FObjectEditFrame.Edited := not (FCommonListEditState = clsInitialState); end; procedure TfrmCommonList.DeleteItem(AObject: TIDObject); var iIndex: integer; begin iIndex := FindItem(AObject); if iIndex > -1 then lbxObjects.Items.Delete(iIndex); end; procedure TfrmCommonList.DeleteObject; var i: integer; begin if SelectedObjects.Count = 1 then begin FActiveObject := lbxObjects.Items.Objects[lbxObjects.ItemIndex] as TIDObject; if MessageBox(Handle, PChar('Вопрос'), PChar('Вы действительно хотите удалить ' + PChar(FActiveObject.List) + '?'), MB_APPLMODAL + MB_YESNO + MB_DEFBUTTON3) = mrYes then begin FActiveObject.Collection.Remove(FActiveObject); FActiveObject := nil; end; end else begin if MessageBox(Handle, PChar('Вопрос'), PChar('Вы действительно хотите удалить выделенные объекты (' + IntToStr(SelectedObjects.Count) + ')?'), MB_APPLMODAL + MB_YESNO + MB_DEFBUTTON3) = mrYes then begin for i := SelectedObjects.Count - 1 downto 0 do ObjectList.Remove(SelectedObjects.Items[i]); FActiveObject := nil; end; end; if Assigned(FObjectEditFrame) then begin FObjectEditFrame.Clear; FObjectEditFrame.ViewOnly := true; FObjectEditFrame.Clear; FObjectEditFrame.Edited := not (FCommonListEditState = clsInitialState); end; FActiveObject := nil; CheckInput; FActiveObject := nil; { if Assigned(NodeObject) then begin bExpanded := NodeObject.Node.Expanded; NodeObject.Refresh; if bExpanded then NodeObject.Node.Expand(false); end; } end; function TfrmCommonList.FindItem(AObject: TIDObject): integer; begin Result := lbxObjects.Items.IndexOfObject(AObject); end; procedure TfrmCommonList.Finish; begin if actnFinishEdit.Enabled then actnFinishEdit.Execute; end; procedure TfrmCommonList.FinishEditObject; var iIndex: integer; begin iIndex := lbxObjects.ItemIndex; FObjectEditFrame.Save; FCommonListEditState := clsInitialState; lbxObjects.Enabled := true; FObjectEditFrame.ViewOnly := true; {if Assigned(NodeObject) then begin bExpanded := NodeObject.Node.Expanded; NodeObject.Refresh; if bExpanded then NodeObject.Node.Expand(false); end;} if Assigned(FOnObjectEditFinished) then FOnObjectEditFinished(Self); FObjectEditFrame.Edited := not (FCommonListEditState = clsInitialState); lbxObjects.SetFocus; lbxObjects.ItemIndex := -1; lbxObjects.ItemIndex := iIndex; lbxObjects.Invalidate; lbxObjects.Refresh; end; {procedure TfrmCommonList.UpdateItem(AObject: TIDObject); var iIndex: integer; begin iIndex := FindItem(AObject); if iIndex > -1 then begin lbxObjects.Items[iIndex] := AObject.List; lbxObjects.Items.Objects[iIndex] := AObject; end; end;} { TListBoxRegistrator } procedure TfrmCommonList.SetRegistrator(const Value: TRegistrator); begin if FRegistrator <> Value then begin FRegistrator := Value; end; end; procedure TfrmCommonList.SetStatusString(const Value: string); begin FStatusString := Value; sbReport.SimpleText := FStatusString; end; procedure TfrmCommonList.SetEditingObjectClass( const Value: TIDObjectClass); begin if FEditingObjectClass <> Value then FEditingObjectClass := Value; end; procedure TfrmCommonList.actnAddObjectUpdate(Sender: TObject); begin inherited; actnAddObject.Enabled := (EditState = clsInitialState) and Assigned(ObjectList) and (actnAdd in AllowedActions); end; procedure TfrmCommonList.actnStartEditUpdate(Sender: TObject); begin inherited; actnStartEdit.Enabled := (EditState = clsInitialState) and (lbxObjects.SelCount = 1) and (lbxObjects.ItemIndex > -1) and (actnEdit in AllowedActions); end; procedure TfrmCommonList.actnFinishEditUpdate(Sender: TObject); begin inherited; actnFinishEdit.Enabled := (EditState in [clsObjectAdded, clsObjectEdited]) and ((not Assigned(ObjectEditFrame)) or (Assigned(ObjectEditFrame) and ObjectEditFrame.Edited and ObjectEditFrame.Check)); end; procedure TfrmCommonList.actnCancelEditUpdate(Sender: TObject); begin inherited; actnCancelEdit.Enabled := EditState in [clsObjectAdded, clsObjectEdited]; end; procedure TfrmCommonList.actnDeleteObjectUpdate(Sender: TObject); begin inherited; actnDeleteObject.Enabled := (EditState = clsInitialState) and (lbxObjects.SelCount > 0) and (lbxObjects.ItemIndex > -1) and (actnDelete in AllowedActions); end; function TfrmCommonList.GetActiveObject: TIDObject; begin Result := FActiveObject; end; function TfrmCommonList.GetSelectedObjects: TIDObjects; var i: integer; begin if not Assigned(FSelectedObjects) then begin FSelectedObjects := TRegisteredIDObjects.Create; FSelectedObjects.OwnsObjects := false; end else FSelectedObjects.Clear; for i := 0 to lbxObjects.Items.Count - 1 do if lbxObjects.Selected[i] then FSelectedObjects.Add(TIDObject(lbxObjects.Items.Objects[i]), false, false); Result := FSelectedObjects; end; procedure TfrmCommonList.Clear; begin inherited; if Assigned(ObjectEditFrame) then ObjectEditFrame.Clear; lbxObjects.Clear; end; procedure TfrmCommonList.ClearSelection; var i: integer; begin lbxObjects.ItemIndex := -1; for i := 0 to lbxObjects.Count - 1 do lbxObjects.Selected[i] := false; end; procedure TfrmCommonList.Cancel; begin actnCancelEdit.Execute; end; procedure TfrmCommonList.CancelEditObject; begin if FCommonListEditState = clsObjectAdded then begin FActiveObject.Collection.Remove(FActiveObject); FActiveObject := nil; FObjectEditFrame.Clear; end else FObjectEditFrame.EditingObject := FActiveObject; FCommonListEditState := clsInitialState; lbxObjects.Enabled := true; FObjectEditFrame.ViewOnly := true; FObjectEditFrame.Clear; FObjectEditFrame.Edited := not (FCommonListEditState = clsInitialState); end; function TfrmCommonList.CheckInput: boolean; begin if (EditState <> clsInitialState) and Assigned(ObjectEditFrame) then begin Result := ObjectEditFrame.Check; if not Result then begin //ReportStatus(ObjectEditFrame.L); exit; end; end; Result := EditState = clsInitialState; if not Result then begin ReportStatus('Завершите операцию добавления или редакции'); exit; end; ReportStatus(''); end; procedure TfrmCommonList.CloseForm(Sender: TObject; var CanClose: Boolean); begin CanClose := (EditState = clsInitialState); if not CanClose then ShowMessage('Сначала завершите или отмените редакцию элемента'); end; destructor TfrmCommonList.Destroy; begin if Assigned(FSelectedObjects) then FreeAndNil(FSelectedObjects); inherited; end; procedure TfrmCommonList.EditObject; begin FActiveObject := lbxObjects.Items.Objects[lbxObjects.ItemIndex] as TIDObject; FObjectEditFrame.EditingObject := FActiveObject; lbxObjects.Enabled := false; FObjectEditFrame.Edited := not (FCommonListEditState = clsInitialState); FCommonListEditState := clsObjectEdited; FObjectEditFrame.ViewOnly := false; end; procedure TfrmCommonList.ReportStatus(S: string); begin end; end.
unit ClassStructList; {$mode objfpc}{$H+} interface type t_value = integer; t_size = dword; //Указатель на узел в списке p_stack = ^t_stack; //Структура узла односвязного списка t_stack = record Data: t_value; //Значение в узле Next: p_stack; //Указатель на следующий узел end; //Класс стека [на основе связных списков] StackList = class private pStart: p_stack; currentsize: t_size; maxsize: t_size; public function add_head(const Value: t_value): boolean; function del_head(): boolean; function get_head(var Value: t_value): boolean; function get_size(): t_size; procedure print(); constructor Create(size: t_size); destructor Destroy(); override; end; //Указатель на узел в списке p_queue = ^t_queue; //Структура узла двусвязного списка t_queue = record Data: t_value; //Значение в узле Next: p_queue; //Указатель на следующий узел prev: p_queue; //Указатель на предыдущий узел end; //Класс очереди [на основе связных списков] QueueList = class protected pStart: p_queue; pEnd: p_queue; currentsize: t_size; maxsize: t_size; public function add_head(const Value: t_value): boolean; function del_tail(): boolean; function get_tail(var Value: t_value): boolean; function get_size(): t_size; procedure print(); constructor Create(size: t_size); destructor Destroy(); override; end; //Класс ДЕКА [на основе связных списков] DQueueList = class(QueueList) public function add_tail(const Value: t_value): boolean; function del_head(): boolean; function get_head(var Value: t_value): boolean; end; implementation { StackList methods ================= } constructor StackList.Create(size: t_size); begin self.pStart := nil; self.currentsize := 0; self.maxsize := size; end; destructor StackList.Destroy(); var nextelem: p_stack; begin nextelem := self.pStart; while self.get_size() <> 0 do begin self.del_head(); end; dispose(nextelem); nextelem := nil; end; function StackList.add_head(const Value: t_value): boolean; var new_elem: p_stack; begin if (self.get_size() >= self.maxsize) then begin Result := False; exit; end; new(new_elem); if (self.pStart = nil) then begin self.pStart := new_elem; new_elem^.Data := Value; new_elem^.Next := nil; end else begin new_elem^.Next := self.pStart; self.pStart := new_elem; new_elem^.Data := Value; end; Inc(self.currentsize); Result := True; end; function StackList.del_head(): boolean; var tempelem: p_stack; begin if (self.get_size() = 0) then begin Result := False; exit; end; tempelem := self.pStart; if (self.pStart <> nil) then self.pStart := self.pStart^.Next^.Next else self.pStart := nil; dispose(tempelem); Dec(self.currentsize); Result := True; end; function StackList.get_head(var Value: t_value): boolean; var new_elem: p_stack; begin if (self.get_size() = 0) then begin Result := False; exit; end; Value := pStart^.Data; new_elem := pStart; if (new_elem^.Next = nil) then begin pStart := nil; dispose(new_elem); end else begin pStart := new_elem^.Next; dispose(new_elem); end; Dec(self.currentsize); Result := True; end; function StackList.get_size(): t_size; begin Result := self.currentsize; end; procedure StackList.print(); var tempelem: p_stack; begin if (self.get_size() = 0) then exit; tempelem := pStart; while tempelem^.Next <> nil do begin Write(tempelem^.Data, ' '); tempelem := tempelem^.Next; end; Write(tempelem^.Data, ' '); end; { QueueList methods ================= } constructor QueueList.Create(size: t_size); begin self.pStart := nil; self.pEnd := nil; self.currentsize := 0; self.maxsize := size; end; destructor QueueList.Destroy(); var nextelem: p_queue; begin nextelem := self.pStart; while self.get_size() <> 0 do begin self.del_tail(); end; dispose(nextelem); nextelem := nil; end; function QueueList.add_head(const Value: t_value): boolean; var new_elem: p_queue; begin if (self.get_size() >= self.maxsize) then begin Result := False; exit; end; new(new_elem); new_elem^.Data := Value; if (self.pStart = nil) then begin self.pStart := new_elem; self.pEnd := new_elem; new_elem^.Next := nil; new_elem^.prev := nil; end else begin self.pStart^.prev := new_elem; new_elem^.Next := self.pStart; new_elem^.prev := nil; self.pStart := new_elem; end; Inc(self.currentsize); Result := True; end; function QueueList.del_tail(): boolean; var tempelem: p_queue; begin if (self.get_size() = 0) then begin Result := False; exit; end; tempelem := self.pEnd; if (self.get_size() = 1) then begin self.pEnd := nil; self.pStart := nil; dispose(tempelem); Dec(self.currentsize); Result := True; exit; end; self.pEnd^.prev^.Next := nil; self.pEnd := self.pEnd^.prev; dispose(tempelem); Dec(self.currentsize); Result := True; end; function QueueList.get_tail(var Value: t_value): boolean; begin if (self.get_size() = 0) then begin Result := False; exit; end; Value := self.pEnd^.Data; Result := self.del_tail(); end; function QueueList.get_size(): t_size; begin Result := self.currentsize; end; procedure QueueList.print(); var tempelem: p_queue; begin if (self.get_size() = 0) then exit; tempelem := self.pStart; while tempelem^.Next <> nil do begin Write(tempelem^.Data, ' '); tempelem := tempelem^.Next; end; Write(tempelem^.Data, ' '); end; { DQueueList methods (inherits QueueList methods) =============================================== } function DQueueList.add_tail(const Value: t_value): boolean; var new_elem: p_queue; begin if (self.get_size() >= self.maxsize) then begin Result := False; exit; end; if (self.get_size() = 0) then begin self.add_head(Value); exit; end; new(new_elem); new_elem^.Data := Value; new_elem^.prev := self.pEnd; new_elem^.Next := nil; self.pEnd^.Next := new_elem; self.pEnd := new_elem; Inc(self.currentsize); Result := True; end; function DQueueList.del_head(): boolean; var tempelem: p_queue; begin if (get_size() = 0) then begin Result := False; exit; end; tempelem := self.pStart; if (self.pStart^.Next <> nil) then begin self.pStart^.Next^.prev := nil; self.pStart := self.pStart^.Next; end else begin self.pStart := nil; self.pEnd := nil; end; dispose(tempelem); Dec(self.currentsize); Result := True; end; function DQueueList.get_head(var Value: t_value): boolean; begin if (get_size() = 0) then begin Result := False; exit; end; Value := self.pStart^.Data; Result := self.del_head(); end; end.
unit JPL.Strings.Ext; { Jacek Pazera http://www.pazera-software.com } {$IFDEF FPC} {$mode objfpc}{$H+} {$ENDIF} interface uses SysUtils, Classes; procedure SplitStrToList(LineToParse: string; var List: TStringList; DataSeparator: string = ','); function SaveStringToFile(const FileName, FileContent: string; Encoding: TEncoding): Boolean; implementation function SaveStringToFile(const FileName, FileContent: string; Encoding: TEncoding): Boolean; var sl: TStringList; begin sl := TStringList.Create; try sl.Text := FileContent; try sl.SaveToFile(FileName, Encoding); Result := True; except Result := False; end; finally sl.Free; end; end; procedure SplitStrToList(LineToParse: string; var List: TStringList; DataSeparator: string = ','); var xp: integer; s: string; begin if not Assigned(List) then Exit; xp := Pos(DataSeparator, LineToParse); while xp > 0 do begin s := Trim(Copy(LineToParse, 1, xp - 1)); List.Add(s); Delete(LineToParse, 1, xp + Length(DataSeparator) - 1); LineToParse := Trim(LineToParse); xp := Pos(DataSeparator, LineToParse); end; if LineToParse <> '' then begin LineToParse := Trim(LineToParse); if LineToParse <> '' then List.Add(LineToParse); end; end; end.
{ Puzzle! is a puzzle game using BGRABitmap Copyright (C) 2012 lainz http://sourceforge.net/users/lainz Thanks to circular and eny from the Lazarus forum for their contributions. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, BGRAVirtualScreen, BGRABitmap, BGRABitmapTypes, ugame, LCLType, ExtCtrls{$IFDEF WINDOWS}, mmsystem{$ENDIF}; const // controls L1 = VK_LEFT; R1 = VK_RIGHT; U1 = VK_UP; D1 = VK_DOWN; L2 = VK_A; R2 = VK_D; U2 = VK_W; D2 = VK_S; type TArrayOfString = array of string; TGameKey = (gkLeft, gkUp, gkRight, gkDown); PGameMap = ^TGameMap; TGameMap = record map, solve: string; mapW: integer; mapH: integer; blockW: integer; blockH: integer; background: TBGRABitmap; end; var Game: array [1..12] of TGameMap; GameOver: TGameMap = (map: 'Game-Over'; solve: 'GameOver-'; mapW: 3; mapH: 3; blockW: 85; blockH: 85; background: nil); procedure DrawMap(var map: TGameMap; bitmap: TBGRABitmap; texture: TBGRABitmap); function ClickMap(var map: TGameMap; pos: TPoint): boolean; function KeyPressMap(var map: TGameMap; var Key: word): boolean; function IsMapSolved(var map: TGameMap): boolean; function CalcularPosibles(str: string; showDebug: boolean = False): TarrayOfString; type { TForm1 } TForm1 = class(TForm) BGRAVirtualScreen1: TBGRAVirtualScreen; Timer1: TTimer; procedure BGRAVirtualScreen1Click(Sender: TObject); procedure BGRAVirtualScreen1Redraw(Sender: TObject; Bitmap: TBGRABitmap); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure FormResize(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } public { public declarations } Size: TRect; map: PGameMap; current: integer; texture: TBGRABitmap; procedure OpenMap(num: integer); procedure CloseMap; procedure ScaleBlocks; procedure GenerateTexture; procedure PlayBlockSound; end; var Form1: TForm1; implementation uses BGRAGradients, ugraph; { DRAWMAP } procedure DrawMap(var map: TGameMap; bitmap: TBGRABitmap; texture: TBGRABitmap); var r: TRect; n, n1, n2: integer; phong: TPhongShading; tile3D, empty3D: TBGRABitmap; h: integer; begin if (bitmap = nil) or (texture = nil) then exit; phong := TPhongShading.Create; if map.background = nil then begin map.background := TBGRABitmap.Create(map.BlockW * map.mapW, map.BlockH * map.mapH); empty3D := TBGRABitmap.Create(texture.Width, texture.Height, BGRABlack); for n1 := 1 to (map.background.Width + texture.Width - 1) div texture.Width do for n2 := 1 to (map.background.Height + texture.Height - 1) div texture.Height do phong.Draw(map.background, empty3D, 0, (n1 - 1) * texture.Width, (n2 - 1) * texture.Height, texture); empty3D.Free; end; h := (map.blockW + map.blockH) div 16; tile3D := CreateRectanglePreciseMap(map.BlockW, map.BlockH, h, []); bitmap.PutImage(0, 0, map.background, dmDrawWithTransparency); n1 := 0; n2 := 0; for n := 1 to length(map.map) do begin r.Left := map.blockW * n1; r.Top := map.blockH * n2; r.Right := r.Left + map.blockW; r.Bottom := r.Top + map.blockH; // begin to draw here // if map.map[n] <> '0' then begin phong.Draw(bitmap, tile3D, h, r.left, r.top, texture); if map.blockH > map.blockW then bitmap.FontHeight := round(map.blockW * 0.75) else bitmap.FontHeight := round(map.blockH * 0.75); bitmap.TextRect(Rect(r.Left + 10, r.Top + 10, r.Right, r.Bottom), map.map[n], taCenter, tlCenter, BGRA(0, 0, 0, 175)); bitmap.TextRect(r, map.map[n], taCenter, tlCenter, BGRABlack); end; { if map.map[n] = '0' then begin bitmap.FontHeight := map.blockH div 4; if (n1 <> 0) then bitmap.TextRect(r, '►', taLeftJustify, tlCenter, BGRA(192, 192, 192)); if (n1 <> map.mapW - 1) then bitmap.TextRect(r, '◄', taRightJustify, tlCenter, BGRA(192, 192, 192)); if (n2 <> 0) then bitmap.TextRect(r, '▼', taCenter, tlTop, BGRA(192, 192, 192)); if (n2 <> map.mapH - 1) then bitmap.TextRect(r, '▲', taCenter, tlBottom, BGRA(192, 192, 192)); end; } // end to draw here // if n1 = map.mapW - 1 then begin n1 := -1; Inc(n2); end; Inc(n1); end; tile3D.Free; phong.Free; end; function ClickMap(var map: TGameMap; pos: TPoint): boolean; var n, n1, n2: integer; r: TRect; begin Result := False; n1 := 0; n2 := 0; for n := 1 to length(map.map) do begin r.Left := map.blockW * n1; r.Top := map.blockH * n2; r.Right := r.Left + map.blockW; r.Bottom := r.Top + map.blockH; { SCALING } r.Left += Form1.BGRAVirtualScreen1.Left; r.Top += Form1.BGRAVirtualScreen1.Top; r.Right += Form1.BGRAVirtualScreen1.Left; r.Bottom += Form1.BGRAVirtualScreen1.Top; if (pos.x >= r.Left) and (pos.x <= r.Right) and (pos.y >= r.Top) and (pos.y <= r.Bottom) then begin // vacio if map.map[n] = '0' then exit; // el vacio esta a la izquierda if (n1 <> 0) then if map.map[n - 1] = '0' then begin map.map[n - 1] := map.map[n]; map.map[n] := '0'; end; // el vacio esta a la derecha if (n1 <> map.mapW - 1) then if map.map[n + 1] = '0' then begin map.map[n + 1] := map.map[n]; map.map[n] := '0'; end; // el vacio esta arriba if map.map[n - map.mapW] = '0' then begin map.map[n - map.mapW] := map.map[n]; map.map[n] := '0'; end; // el vacio esta abajo if map.map[n + map.mapW] = '0' then begin map.map[n + map.mapW] := map.map[n]; map.map[n] := '0'; end; Result := True; exit; end; if n1 = map.mapW - 1 then begin n1 := -1; Inc(n2); end; Inc(n1); end; end; function KeyPressMap(var map: TGameMap; var Key: word): boolean; function GetGameKey(var Key: word; invertLR, invertUD: boolean): TGameKey; begin if (Key = L1) or (Key = L2) then Result := gkLeft; if (Key = R1) or (Key = R2) then Result := gkRight; if (Key = U1) or (Key = U2) then Result := gkUp; if (Key = D1) or (Key = D2) then Result := gkDown; if invertLR then case Result of gkLeft: Result := gkRight; gkRight: Result := gkLeft; end; if invertUD then case Result of gkUp: Result := gkDown; gkDown: Result := gkUp; end; end; var n, n1, n2: integer; begin n1 := 0; n2 := 0; Result := False; for n := 1 to length(map.map) do begin if map.map[n] = '0' then begin case GetGameKey(Key, True, True) of gkLeft: // el de la izquierda if (n1 <> 0) then begin map.map[n] := map.map[n - 1]; map.map[n - 1] := '0'; Result := True; Key := 0; end; gkRight: // el de la derecha if (n1 <> map.mapW - 1) then begin map.map[n] := map.map[n + 1]; map.map[n + 1] := '0'; Result := True; Key := 0; end; gkUp: // el de arriba if (n2 <> 0) then begin map.map[n] := map.map[n - map.mapW]; map.map[n - map.mapW] := '0'; Result := True; Key := 0; end; gkDown: // el de abajo if (n2 <> map.mapH - 1) then begin map.map[n] := map.map[n + map.mapW]; map.map[n + map.mapW] := '0'; Result := True; Key := 0; end; end; if Result then exit; end; if n1 = map.mapW - 1 then begin n1 := -1; Inc(n2); end; Inc(n1); end; end; function IsMapSolved(var map: TGameMap): boolean; begin Result := map.map = map.solve; end; function CalcularPosibles(str: string; showDebug: boolean = False): TarrayOfString; function Factorial(number: integer): integer; var i: integer; begin Result := number; for i := number - 1 downto 1 do begin Result := Result * i; end; end; function MoverIzq(str: string; pos: integer): string; var s1, s2: char; begin Result := str; s1 := Result[pos]; s2 := Result[pos - 1]; Result[pos] := s2; Result[pos - 1] := s1; end; function MoverIni(str: string; pos: integer): string; var s1, s2: char; begin Result := str; s1 := Result[pos]; s2 := Result[1]; Result[pos] := s2; Result[1] := s1; end; var nLargo, // numero de char en la string nFactorial, // numero de combinaciones nFactorialDivLargo, // primer char veces repetido nFactorialm1DivLargom1, // segundo char veces repetido nPosibles: integer; // numero de combinaciones jugables n: integer; rstr: string; begin // Los comentarios de los numeros son para str:=1230; nLargo := length(str); // 4 if nLargo <= 1 then exit; nFactorial := Factorial(nLargo); // 24 //nFactorialDivLargo := nFactorial div nLargo; // 6 //nFactorialm1DivLargom1 := Factorial(nLargo - 1) div (nLargo - 1); // 2 nPosibles := nFactorial div 2; // 12 SetLength(Result, nPosibles); //0 to 11 for n := 0 to nPosibles - 1 do begin // create a function here ;) // start with '1' if n = 0 then Result[n] := str // 1230 (no clic) else if n = 1 then // 1203 (clic 3) Result[n] := MoverIzq(Result[n - 1], nLargo); // 1203 if n = 2 then // 1032 (clic 2) begin Result[n] := MoverIzq(Result[n - 1], nLargo - 1); // 1023 Result[n] := MoverIzq(Result[n], nLargo); // 1032 end; // start with '2' (the 2 positioned char) if n = 3 then // 2310 (clic 3 2 1 3) begin Result[n] := MoverIni(Result[0], 2); // 2130 Result[n] := MoverIzq(Result[n], nLargo - 1); // 2310 end; if n = 4 then // 2301 begin Result[n] := MoverIzq(Result[n - 1], nLargo); // 2301 end; if n = 5 then // 2013 begin Result[n] := MoverIzq(Result[n - 1], nLargo - 1); // 2031 Result[n] := MoverIzq(Result[n], nLargo); // 2013 end; // start with '3' (the 3 positioned char) if n = 6 then // 3120 begin Result[n] := MoverIni(Result[0], 3); Result[n] := MoverIzq(Result[n], nLargo - 1); // 3120 end; if n = 7 then // 3102 begin Result[n] := MoverIzq(Result[n - 1], nLargo); // 3102 end; if n = 8 then // 3021 begin Result[n] := MoverIzq(Result[n - 1], nLargo - 1); Result[n] := MoverIzq(Result[n], nLargo); // 3021 end; // start with '0' (the 4 positioned char) if n = 9 then // 0321 begin Result[n] := MoverIni(Result[0], 4); Result[n] := MoverIzq(Result[n], nLargo - 1); // 0321 end; if n = 10 then // 0213 begin Result[n] := MoverIzq(Result[n - 1], nLargo - 1); Result[n] := MoverIzq(Result[n], nLargo); // 0213 end; if n = 11 then // 0132 begin Result[n] := MoverIzq(Result[n - 1], nLargo - 1); Result[n] := MoverIzq(Result[n], nLargo); // 0232 end; end; // Debug if showDebug then begin rstr := ''; for n := 0 to nPosibles - 1 do begin rstr := concat(rstr, LineEnding, Result[n]); end; ShowMessage(rstr); ShowMessage( concat('numero de char en la string: ', IntToStr(nLargo), LineEnding, 'numero de combinaciones: ', IntToStr(nFactorial), LineEnding, //'primer char veces repetido: ', IntToStr(nFactorialDivLargo), //LineEnding, 'segundo char veces repetido: ', IntToStr(nFactorialm1DivLargom1), LineEnding, 'numero de combinaciones jugables: ', IntToStr(nPosibles)) ); end; end; {$R *.lfm} { TForm1 } procedure TForm1.BGRAVirtualScreen1Redraw(Sender: TObject; Bitmap: TBGRABitmap); begin DrawMap(map^, bitmap, texture); end; { MOUSE } procedure TForm1.BGRAVirtualScreen1Click(Sender: TObject); var pos: TPoint; begin pos := ScreenToClient(Mouse.CursorPos); if ClickMap(map^, pos) then begin PlayBlockSound; BGRAVirtualScreen1.DiscardBitmap; end; end; { CREATE } procedure TForm1.FormCreate(Sender: TObject); var a: TArrayOfString; i: integer; begin a := CalcularPosibles('1230'{, True}); // 0 is 1230 the solve // 1 to 11 for i := 1 to length(a) - 1 do begin Game[i].map := a[i]; Game[i].solve := a[0]; Game[i].mapW := length(a[0]) div 2; Game[i].mapH := length(a[0]) div 2; Game[i].blockW := 128; Game[i].blockH := 128; end; Game[length(Game)] := GameOver; { SCALING } // FullScreen with current screen resolution //Size := Rect(0, 0, Screen.Width, Screen.Height); Size := Rect(0, 0, 640, 480); SetBounds(Size.Left, Size.Top, Size.Right, Size.Bottom); ScaleAspectRatio(BGRAVirtualScreen1, Size.Right, Size.Bottom, True, True, True); ToggleFullScreen(Self, Size); ScaleBlocks; { OPEN } randomize; // to randomize the skin OpenMap(1); current := 1; end; procedure TForm1.FormDestroy(Sender: TObject); begin CloseMap; end; { KEYBOARD } procedure TForm1.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if (Key = VK_ESCAPE) then Application.Terminate; if (Key = VK_F11) then ToggleFullScreen(Self, Size); if KeyPressMap(map^, Key) then begin PlayBlockSound; BGRAVirtualScreen1.DiscardBitmap; end; end; procedure TForm1.FormResize(Sender: TObject); begin CenterControl(BGRAVirtualScreen1); end; { TIMER } procedure TForm1.Timer1Timer(Sender: TObject); {$IFDEF WINDOWS} procedure JoyDown(const pKey: word); var Key: word; begin Key := pKey; FormKeyDown(nil, Key, []); end; {$ENDIF} var nextGame: boolean; {$IFDEF WINDOWS} myJoy: TJoyInfoEx; myJoyCaps: TJoyCaps; ErrorResultC, ErrorResultP: MMRESULT; {$ENDIF} begin if map <> nil then begin Caption := 'Level ' + IntToStr(current); nextGame := IsMapSolved(map^); if (current = length(Game)) and nextGame then begin Timer1.Enabled := False; //ShowMessage('Game Win!'); exit; end; if nextGame then begin Timer1.Enabled := False; OpenMap(current + 1); //ShowMessage('Next: Level ' + IntToStr(current)); BGRAVirtualScreen1.DiscardBitmap; Timer1.Enabled := True; end; {$IFDEF WINDOWS} ErrorResultC := joyGetDevCaps(joystickid1, @myJoyCaps, sizeof(myJoyCaps)); ErrorResultP := joyGetPosEx(joystickid1, @MyJoy); if (ErrorResultC = JOYERR_NOERROR) and (ErrorResultP = JOYERR_NOERROR) then begin if (myJoy.dwPOV = JOY_POVFORWARD) or (myJoy.wYpos = myJoyCaps.wYmin) then JoyDown(U1) else if (myJoy.dwPOV = JOY_POVBACKWARD) or (myJoy.wYpos = myJoyCaps.wYmax) then JoyDown(D1) else if (myJoy.dwPOV = JOY_POVLEFT) or (myJoy.wXpos = myJoyCaps.wXmin) then JoyDown(L1) else if (myJoy.dwPOV = JOY_POVRIGHT) or (myJoy.wXpos = myJoyCaps.wXmax) then JoyDown(R1); end; {$ENDIF} end; end; procedure TForm1.OpenMap(num: integer); begin CloseMap; if (num < low(Game)) or (num > high(Game)) then halt; current := num; map := @Game[current]; GenerateTexture; end; procedure TForm1.CloseMap; begin if map <> nil then FreeAndNil(map^.background); FreeAndNil(texture); map := nil; end; procedure TForm1.ScaleBlocks; var i: integer; begin for i := low(game) to high(game) do begin Game[i].blockW := BGRAVirtualScreen1.Width div Game[i].mapW; Game[i].blockH := BGRAVirtualScreen1.Height div Game[i].mapH; end; end; procedure TForm1.GenerateTexture; begin if texture <> nil then raise Exception.Create('Texture not freed'); case random(9) of 0: texture := CreatePlastikTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 1: texture := CreateCamouflageTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 2: texture := CreateSnowPrintTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 3: texture := CreateRoundStoneTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 4: texture := CreateStoneTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 5: texture := CreateWaterTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 6: texture := CreateMarbleTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 7: texture := CreateWoodTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); 8: texture := CreateVerticalWoodTexture(BGRAVirtualScreen1.Width, BGRAVirtualScreen1.Height); end; end; procedure TForm1.PlayBlockSound; begin {$IFDEF WINDOWS} PlaySound(PChar('move.wav'), 0, SND_ASYNC); {$ENDIF} end; end.
unit XYcurve; { ---------------------------------------------------------- Copyright (c) 2011-2015, Electric Power Research Institute, Inc. All rights reserved. ---------------------------------------------------------- } { 2-15-2011 Converted from TempShape. General X-Y Curve Data Support Class } Interface { The XYcurve object is a general DSS object used by all circuit elements as a reference for obtaining yearly, daily, and other Temperature shapes. The values are set by the normal New and Edit PROCEDUREs for any DSS object. The values may be retrieved by setting the Code Property in the XYCurve Class. This sets the active XYCurve object to be the one referenced by the Code Property; Then the values of that code can be retrieved via the public variables. Or you can pick up the ActiveTXYcurveObj object and save the direct reference to the object. The user may place the curve data in CSV or binary files as well as passing through the command interface. Obviously, for large amounts of data such as 8760 load curves, the command interface is cumbersome. CSV files are text separated by commas, or white space one point to a line. There are two binary formats permitted: 1) a file of Singles; 2) a file of Doubles. } USES Command, DSSClass, DSSObject, Arraydef; TYPE TXYcurve = class(TDSSClass) private TempPointsBuffer:pDoubleArray; FUNCTION Get_Code:String; // Returns active TShape string PROCEDURE Set_Code(const Value:String); // sets the active TShape PROCEDURE DoCSVFile(Const FileName:String); PROCEDURE DoSngFile(Const FileName:String); PROCEDURE DoDblFile(Const FileName:String); protected PROCEDURE DefineProperties; FUNCTION MakeLike(Const CurveName:String):Integer; Override; public constructor Create; destructor Destroy; override; FUNCTION Edit:Integer; override; // uses global parser FUNCTION Init(Handle:Integer):Integer; override; FUNCTION NewObject(const ObjName:String):Integer; override; FUNCTION Find(const ObjName:String):Pointer; override; // Find an obj of this class by name // Set this property to point ActiveTShapeObj to the right value Property Code:String Read Get_Code Write Set_Code; End; TXYcurveObj = class(TDSSObject) private LastValueAccessed, FNumPoints :Integer; // Number of points in curve ArrayPropertyIndex:Integer; FX, FY : Double; XValues, YValues :pDoubleArray; PROCEDURE Set_NumPoints(const Value: Integer); FUNCTION InterpolatePoints(i,j:Integer; X:double; Xarray, Yarray:pDoubleArray):Double; // PROCEDURE SaveToDblFile; // PROCEDURE SaveToSngFile; FUNCTION Get_YValue(i:Integer):Double; // get Y Value by index FUNCTION Get_XValue(i:Integer):Double; // get X Value corresponding to point index PROCEDURE Set_XValue(Index:Integer; Value: Double); PROCEDURE Set_YValue(Index:Integer; Value: Double); FUNCTION Get_X:Double; FUNCTION Get_Y:Double; PROCEDURE Set_X(Value:Double); PROCEDURE Set_Y(Value:Double); public // Make these vars available to COM interface FXshift, FYshift, FXscale, FYscale : Double; constructor Create(ParClass:TDSSClass; const XYCurveName:String); destructor Destroy; override; FUNCTION GetYValue(X:double):Double; // Get Y value at specified X Value FUNCTION GetXValue(Y:double):Double; // Get X value at specified Y Value FUNCTION GetPropertyValue(Index:Integer):String;Override; PROCEDURE InitPropertyValues(ArrayOffset:Integer);Override; PROCEDURE DumpProperties(Var F:TextFile; Complete:Boolean);Override; PROCEDURE SaveWrite(Var F:TextFile);Override; Property NumPoints :Integer Read FNumPoints Write Set_NumPoints; Property XValue_pt[Index:Integer]:Double Read Get_XValue Write Set_XValue; Property YValue_pt[Index:Integer]:Double Read Get_YValue Write Set_YValue; Property X:double Read Get_X Write Set_X; Property Y:double Read Get_Y Write Set_Y; End; VAR ActiveXYcurveObj:TXYcurveObj; implementation USES ParserDel, DSSClassDefs, DSSGlobals, Sysutils, MathUtil, Utilities, Classes, Math, PointerList; Const NumPropsThisClass = 13; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - constructor TXYcurve.Create; // Creates superstructure for all Line objects Begin Inherited Create; Class_Name := 'XYcurve'; DSSClassType := DSS_OBJECT; ActiveElement := 0; TempPointsBuffer := Nil; // Has to start off Nil for Reallocmem call DefineProperties; CommandList := TCommandList.Create(Slice(PropertyName^, NumProperties)); CommandList.Abbrev := TRUE; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Destructor TXYcurve.Destroy; Begin // ElementList and CommandList freed in inherited destroy Inherited Destroy; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROCEDURE TXYcurve.DefineProperties; Begin Numproperties := NumPropsThisClass; CountProperties; // Get inherited property count AllocatePropertyArrays; // Define Property names PropertyName[1] := 'npts'; // Number of points to expect PropertyName[2] := 'Points'; PropertyName[3] := 'Yarray'; // vector of Y values PropertyName[4] := 'Xarray'; // vector of X values corresponding to Y values PropertyName[5] := 'csvfile'; // Switch input to a csvfile PropertyName[6] := 'sngfile'; // switch input to a binary file of singles PropertyName[7] := 'dblfile'; // switch input to a binary file of singles PropertyName[8] := 'x'; PropertyName[9] := 'y'; PropertyName[10] := 'Xshift'; PropertyName[11] := 'Yshift'; PropertyName[12] := 'Xscale'; PropertyName[13] := 'Yscale'; // define Property help values PropertyHelp[1] := 'Max number of points to expect in curve. This could get reset to the actual number of points defined ' + 'if less than specified.'; // Number of points to expect PropertyHelp[2] := 'One way to enter the points in a curve. Enter x and y values as one array '+ 'in the order [x1, y1, x2, y2, ...]. For example:'+CRLF+CRLF+ 'Points=[1,100 2,200 3, 300] '+CRLF+CRLF+ 'Values separated by commas or white space. Zero fills arrays if insufficient number of values.'; PropertyHelp[3] := 'Alternate way to enter Y values. Enter an array of Y values corresponding to the X values. '+ 'You can also use the syntax: '+CRLF+ 'Yarray = (file=filename) !for text file one value per line'+CRLF+ 'Yarray = (dblfile=filename) !for packed file of doubles'+CRLF+ 'Yarray = (sngfile=filename) !for packed file of singles '+CRLF+CRLF+ 'Note: this property will reset Npts to a smaller value if the number of values in the files are fewer.'; // vextor of hour values PropertyHelp[4] := 'Alternate way to enter X values. Enter an array of X values corresponding to the Y values. '+ 'You can also use the syntax: '+CRLF+ 'Xarray = (file=filename) !for text file one value per line'+CRLF+ 'Xarray = (dblfile=filename) !for packed file of doubles'+CRLF+ 'Xarray = (sngfile=filename) !for packed file of singles '+CRLF+CRLF+ 'Note: this property will reset Npts to a smaller value if the number of values in the files are fewer.'; // vextor of hour values PropertyHelp[5] := 'Switch input of X-Y curve data to a CSV file '+ 'containing X, Y points one per line. ' + 'NOTE: This action may reset the number of points to a lower value.'; // Switch input to a csvfile PropertyHelp[6] := 'Switch input of X-Y curve data to a binary file of SINGLES '+ 'containing X, Y points packed one after another. ' + 'NOTE: This action may reset the number of points to a lower value.'; // switch input to a binary file of singles PropertyHelp[7] := 'Switch input of X-Y curve data to a binary file of DOUBLES '+ 'containing X, Y points packed one after another. ' + 'NOTE: This action may reset the number of points to a lower value.'; // switch input to a binary file of singles PropertyHelp[8] := 'Enter a value and then retrieve the interpolated Y value from the Y property. On input shifted then scaled to original curve. Scaled then shifted on output.'; PropertyHelp[9] := 'Enter a value and then retrieve the interpolated X value from the X property. On input shifted then scaled to original curve. Scaled then shifted on output.'; PropertyHelp[10] := 'Shift X property values (in/out) by this amount of offset. Default = 0. Does not change original definition of arrays.'; PropertyHelp[11] := 'Shift Y property values (in/out) by this amount of offset. Default = 0. Does not change original definition of arrays.'; PropertyHelp[12] := 'Scale X property values (in/out) by this factor. Default = 1.0. Does not change original definition of arrays.'; PropertyHelp[13] := 'Scale Y property values (in/out) by this factor. Default = 1.0. Does not change original definition of arrays.'; ActiveProperty := NumPropsThisClass; inherited DefineProperties; // Add defs of inherited properties to bottom of list End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurve.NewObject(const ObjName:String):Integer; Begin // create a new object of this class and add to list With ActiveCircuit Do Begin ActiveDSSObject := TXYcurveObj.Create(Self, ObjName); Result := AddObjectToList(ActiveDSSObject); End; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurve.Edit:Integer; VAR ParamPointer :Integer; ParamName :String; Param :String; i :Integer; Begin Result := 0; // continue parsing with contents of Parser ActiveXYcurveObj := ElementList.Active; ActiveDSSObject := ActiveXYcurveObj; WITH ActiveXYcurveObj DO Begin ParamPointer := 0; ParamName := Parser.NextParam; Param := Parser.StrValue; While Length(Param)>0 DO Begin IF Length(ParamName) = 0 Then Inc(ParamPointer) ELSE ParamPointer := CommandList.GetCommand(ParamName); If (ParamPointer>0) and (ParamPointer<=NumProperties) Then PropertyValue[ParamPointer] := Param; CASE ParamPointer OF 0: DoSimpleMsg('Unknown parameter "' + ParamName + '" for Object "' + Class_Name +'.'+ Name + '"', 610); 1: NumPoints := Parser.Intvalue; 2: Begin ReAllocmem(TempPointsBuffer, Sizeof(TempPointsBuffer^[1]) * FNumPoints * 2); // Allow possible Resetting (to a lower value) of num points when specifying temperatures not Hours NumPoints := InterpretDblArray(Param, (FNumPoints * 2), TempPointsBuffer) div 2; // Parser.ParseAsVector(Npts, Temperatures); ReAllocmem(YValues, Sizeof(YValues^[1]) * FNumPoints); ReAllocmem(XValues, Sizeof(XValues^[1]) * FNumPoints); FOR i := 1 to FNumPoints Do Begin XValues^[i] := TempPointsBuffer^[2*i-1]; YValues^[i] := TempPointsBuffer^[2*i]; End; X := Xvalues^[1]; Y := Yvalues^[1]; ReAllocmem(TempPointsBuffer, 0); // Throw away temp array End; 3: Begin ReAllocmem(YValues, Sizeof(YValues^[1]) * NumPoints); NumPoints := InterpretDblArray(Param, NumPoints, YValues); Y := Yvalues^[1]; End; 4: Begin ReAllocmem(XValues, Sizeof(XValues^[1]) * NumPoints); NumPoints := InterpretDblArray(Param, NumPoints, XValues); X := Xvalues^[1]; End; 5: DoCSVFile(Param); // file of x,y points, one to a line 6: DoSngFile(Param); 7: DoDblFile(Param); 8: X := Parser.dblvalue; 9: Y := Parser.dblvalue; 10: FXshift := Parser.dblvalue; 11: FYshift := Parser.dblvalue; 12: FXscale := Parser.dblvalue; 13: FYscale := Parser.dblvalue; ELSE // Inherited parameters ClassEdit( ActiveXYcurveObj, ParamPointer - NumPropsThisClass) End; CASE ParamPointer OF 5..7: Begin X := Xvalues^[1]; Y := Yvalues^[1]; End; End; CASE ParamPointer OF 2..7: Begin ArrayPropertyIndex := ParamPointer; NumPoints := FNumPoints; // Keep Properties in order for save command LastValueAccessed := 1; End; End; ParamName := Parser.NextParam; Param := Parser.StrValue; End; {While} End; {WITH} End; FUNCTION TXYcurve.Find(const ObjName: String): Pointer; Begin If (Length(ObjName)=0) or (CompareText(ObjName, 'none')=0) Then Result := Nil ELSE Result := Inherited Find(ObjName); End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurve.MakeLike(Const CurveName:String):Integer; VAR OtherXYCurve:TXYcurveObj; i:Integer; Begin Result := 0; {See if we can find this curve in the present collection} OtherXYCurve := Find(CurveName); IF OtherXYCurve <> Nil Then WITH ActiveXYcurveObj DO Begin NumPoints := OtherXYCurve.NumPoints; ReAllocmem(XValues, Sizeof(XValues^[1]) * NumPoints); ReAllocmem(YValues, Sizeof(YValues^[1]) * NumPoints); FOR i := 1 To NumPoints DO XValues^[i] := OtherXYCurve.XValues^[i]; FOR i := 1 To NumPoints DO YValues^[i] := OtherXYCurve.YValues^[i]; FXshift := OtherXYCurve.FXshift; FYshift := OtherXYCurve.FYshift; FXscale := OtherXYCurve.FXscale; FYscale := OtherXYCurve.FYscale; FOR i := 1 to ParentClass.NumProperties Do PropertyValue[i] := OtherXYCurve.PropertyValue[i]; End ELSE DoSimpleMsg('Error in XYCurve MakeLike: "' + CurveName + '" Not Found.', 611); End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurve.Init(Handle:Integer):Integer; Begin DoSimpleMsg('Need to implement TXYcurve.Init', -1); Result := 0; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurve.Get_Code:String; // Returns active line code string VAR XYCurveObj:TXYcurveObj; Begin XYCurveObj := ElementList.Active; Result := XYCurveObj.Name; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROCEDURE TXYcurve.Set_Code(const Value:String); // sets the active TShape VAR XYCurveObj:TXYcurveObj; Begin ActiveXYcurveObj := Nil; XYCurveObj := ElementList.First; While XYCurveObj<>Nil DO Begin IF CompareText(XYCurveObj.Name, Value)=0 Then Begin ActiveXYcurveObj := XYCurveObj; Exit; End; XYCurveObj := ElementList.Next; End; DoSimpleMsg('XYCurve: "' + Value + '" not Found.', 612); End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROCEDURE TXYcurve.DoCSVFile(Const FileName:String); VAR F:Textfile; i:Integer; s:String; Begin TRY AssignFile(F,FileName); Reset(F); EXCEPT DoSimpleMsg('Error Opening File: "' + FileName, 613); CloseFile(F); Exit; End; TRY WITH ActiveXYcurveObj DO Begin ReAllocmem(XValues, Sizeof(XValues^[1])*NumPoints); ReAllocmem(YValues, Sizeof(YValues^[1])*NumPoints); i := 0; While (NOT EOF(F)) AND (i < FNumPoints) DO Begin Inc(i); Readln(F, s); // read entire line and parse with AuxParser {AuxParser allows commas or white space} WITH AuxParser Do Begin CmdString := s; NextParam; XValues^[i] := DblValue; NextParam; YValues^[i] := DblValue; End; End; CloseFile(F); If i <> FNumPoints Then NumPoints := i; End; EXCEPT On E:Exception Do Begin DoSimpleMsg('Error Processing XYCurve CSV File: "' + FileName + '. ' + E.Message , 614); CloseFile(F); Exit; End; End; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROCEDURE TXYcurve.DoSngFile(Const FileName:String); VAR F :File of Single; sX, sY :Single; i :Integer; Begin TRY AssignFile(F,FileName); Reset(F); EXCEPT DoSimpleMsg('Error Opening File: "' + FileName, 615); CloseFile(F); Exit; End; TRY WITH ActiveXYcurveObj DO Begin ReAllocmem(XValues, Sizeof(XValues^[1])*NumPoints); ReAllocmem(YValues, Sizeof(YValues^[1])*NumPoints); i := 0; While (NOT EOF(F)) AND (i < FNumPoints) DO Begin Inc(i); Read(F, sX); XValues^[i] := sX; Read(F, sY); YValues^[i] := sY; End; CloseFile(F); If i <> FNumPoints Then NumPoints := i; End; EXCEPT DoSimpleMsg('Error Processing binary (single) XYCurve File: "' + FileName, 616); CloseFile(F); Exit; End; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PROCEDURE TXYcurve.DoDblFile(Const FileName:String); VAR F :File of double; i :Integer; Begin TRY AssignFile(F,FileName); Reset(F); EXCEPT DoSimpleMsg('Error Opening File: "' + FileName, 617); CloseFile(F); Exit; End; TRY WITH ActiveXYcurveObj DO Begin ReAllocmem(XValues, Sizeof(XValues^[1])*NumPoints); ReAllocmem(YValues, Sizeof(YValues^[1])*NumPoints); i := 0; While (NOT EOF(F)) AND (i < FNumPoints) DO Begin Inc(i); Read(F, XValues^[i]); Read(F, YValues^[i]); End; CloseFile(F); If i <> FNumPoints Then NumPoints := i; End; EXCEPT DoSimpleMsg('Error Processing binary (double) XYCurve File: "' + FileName, 618); CloseFile(F); Exit; End; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TTShape Obj //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CONSTRUCTOR TXYcurveObj.Create(ParClass:TDSSClass; const XYCurveName:String); Begin Inherited Create(ParClass); Name := LowerCase(XYCurveName); DSSObjType := ParClass.DSSClassType; LastValueAccessed := 1; FNumPoints := 0; XValues := Nil; YValues := Nil; FX := 0.0; FY := 0.0; FXshift := 0.0; FYshift := 0.0; FXscale := 1.0; FYscale := 1.0; ArrayPropertyIndex := 0; InitPropertyValues(0); End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - DESTRUCTOR TXYcurveObj.Destroy; Begin IF Assigned(XValues) Then ReallocMem(XValues, 0); IF Assigned(YValues) Then ReallocMem(YValues, 0); Inherited destroy; End; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FUNCTION TXYcurveObj.GetYValue(X:double):Double; // This function returns the interpolated Y value for the given X. // If no points exist in the curve, the result is 0.0 // If Xvalue is outside the range of defined X values, // the curve is extrapolated from the Ends. Var i:Integer; Begin Result := 0.0; // default return value if no points in curve IF FNumPoints>0 Then // Handle Exceptional cases IF FNumPoints=1 Then Result := YValues^[1] ELSE Begin { Start with previous value accessed under the assumption that most of the time, the values won't change much} IF (XValues^[LastValueAccessed] > X) Then LastValueAccessed := 1; // Start over from Beginning // if off the curve for the first point, extrapolate from the first two points IF (LastValueAccessed = 1) AND (XValues[1] > X) Then Begin Result := InterpolatePoints(1, 2, X, XValues, YValues); Exit; End; // In the middle of the arrays FOR i := LastValueAccessed+1 TO FNumPoints do Begin IF (Abs(XValues^[i]-X) < 0.00001) Then // If close to an actual point, just use it. Begin Result := YValues^[i]; LastValueAccessed := i; Exit; End ELSE IF (XValues^[i] > X) Then // INTERPOLATE between two values Begin LastValueAccessed := i-1; Result := InterpolatePoints(i, LastValueAccessed, X, XValues, YValues); Exit ; End; End; // If we fall through the loop, Extrapolate from last two points LastValueAccessed := FNumPoints-1; Result := InterpolatePoints(FNumPoints, LastValueAccessed, X, XValues, YValues); End; End; function TXYcurveObj.Get_Y: Double; begin Result := FY * FYscale + FYshift; end; FUNCTION TXYcurveObj.Get_YValue(i:Integer) :Double; Begin If (i <= FNumPoints) and (i > 0) Then Begin Result := YValues^[i]; LastValueAccessed := i; End ELSE Result := 0.0; End; function TXYcurveObj.Get_X: Double; begin Result := FX * FXscale + FXshift; end; FUNCTION TXYcurveObj.Get_XValue(i:Integer) :Double; Begin If (i <= FNumPoints) and (i > 0) Then Begin Result := XValues^[i]; LastValueAccessed := i; End ELSE Result := 0.0; End; PROCEDURE TXYcurveObj.DumpProperties(var F: TextFile; Complete: Boolean); Var i :Integer; Begin Inherited DumpProperties(F, Complete); WITH ParentClass Do FOR i := 1 to NumProperties Do Begin CASE i of 3, 4: Writeln(F,'~ ',PropertyName^[i],'=(',PropertyValue[i],')'); ELSE Writeln(F,'~ ',PropertyName^[i],'=',PropertyValue[i]); End; End; End; FUNCTION TXYcurveObj.GetPropertyValue(Index: Integer): String; VAR i: Integer; Begin CASE Index of 2..4: Result := '['; ELSE Result := ''; End; CASE Index of 2: IF (XValues<>Nil) AND (YValues <> Nil) Then FOR i := 1 to FNumPoints Do Result := Result + Format('%.8g, %.8g ', [XValues^[i], YValues^[i] ]) ELSE Result := '0, 0'; 3: If (YValues <> Nil) Then FOR i := 1 to FNumPoints Do Result := Result + Format('%-g, ' , [YValues^[i]]) ELSE Result := '0'; 4: If (XValues <> Nil) Then FOR i := 1 to FNumPoints Do Result := Result + Format('%-g, ' , [XValues^[i]]) ELSE Result := '0'; 8: Result := Format('%.8g',[Get_X]); 9: Result := Format('%.8g',[Get_Y]); 10: Result := Format('%.8g',[FXshift]); 11: Result := Format('%.8g',[FYshift]); 12: Result := Format('%.8g',[FXscale]); 13: Result := Format('%.8g',[FYscale]); ELSE Result := Inherited GetPropertyValue(index); End; CASE Index of 2..4: Result := Result + ']'; ELSE End; End; FUNCTION TXYcurveObj.GetXValue(Y: double): Double; // This FUNCTION returns the interpolated X value for the given Y. // If no points exist in the curve, the result is 0.0 // If Xvalue is outside the range of defined X values, // the curve is extrapolated from the Ends. Var i:Integer; Begin Result := 0.0; // default return value if no points in curve IF FNumPoints>0 Then // Handle Exceptional cases IF FNumPoints=1 Then Result := XValues^[1] ELSE Begin { Start with previous value accessed under the assumption that most of the time, this FUNCTION will be called sequentially} IF (YValues^[LastValueAccessed] > Y) Then LastValueAccessed := 1; // Start over from Beginning // if off the curve for the first point, extrapolate from the first two points IF (LastValueAccessed = 1) AND (YValues[1] > Y) Then Begin Result := InterpolatePoints(1, 2, Y, YValues, XValues); Exit; End; FOR i := LastValueAccessed+1 TO FNumPoints do Begin IF (Abs(YValues^[i]-Y) < 0.00001) Then // If close to an actual point, just use it. Begin Result := XValues^[i]; LastValueAccessed := i; Exit; End ELSE IF (YValues^[i] > Y) Then // INTERPOLATE Begin LastValueAccessed := i-1; Result := InterpolatePoints(i, LastValueAccessed, Y, YValues, XValues); Exit ; End; End; // If we fall through the loop, Extrapolate from last two points LastValueAccessed := FNumPoints-1; Result := InterpolatePoints(FNumPoints, LastValueAccessed, Y, YValues, XValues); End; End; PROCEDURE TXYcurveObj.InitPropertyValues(ArrayOffset: Integer); Begin PropertyValue[1] := '0'; // Number of points to expect PropertyValue[2] := ''; PropertyValue[3] := ''; PropertyValue[4] := ''; PropertyValue[5] := ''; PropertyValue[6] := ''; PropertyValue[7] := ''; PropertyValue[8] := ''; PropertyValue[9] := ''; PropertyValue[10] := '0'; PropertyValue[11] := '0'; PropertyValue[12] := '1'; PropertyValue[13] := '1'; inherited InitPropertyValues(NumPropsThisClass); End; FUNCTION TXYcurveObj.InterpolatePoints(i, j:Integer; X: double; Xarray, Yarray: pDoubleArray): Double; Var Den :Double; Begin Den := (Xarray^[i] - Xarray^[j]); IF Den<>0.0 Then Result := Yarray^[j] + (X - Xarray^[j]) / Den * (Yarray^[i] - Yarray^[j]) ELSE Result := Yarray^[i]; // Y is undefined, return ith value End; (************************************************* PROCEDURE TXYcurveObj.SaveToDblFile; Var F:File of Double; i:Integer; Fname :String; Begin If Assigned(TValues) then Begin TRY FName := Format('%s.dbl',[Name]); AssignFile(F, Fname); Rewrite(F); FOR i := 1 to NumPoints Do Write(F, TValues^[i]); GlobalResult := 'Temp=[dblfile='+FName+']'; FINALLY CloseFile(F); End; End ELSE DoSimpleMsg('Tshape.'+Name + ' Temperatures not defined.', 622); End; PROCEDURE TXYcurveObj.SaveToSngFile; Var F:File of Single; i:Integer; Fname :String; Temp :Single; Begin If Assigned(TValues) then Begin TRY FName := Format('%s.sng',[Name]); AssignFile(F, Fname); Rewrite(F); FOR i := 1 to NumPoints Do Begin Temp := TValues^[i] ; Write(F, Temp); End; GlobalResult := 'Temp=[sngfile='+FName+']'; FINALLY CloseFile(F); End; End ELSE DoSimpleMsg('Tshape.'+Name + ' Temperatures not defined.', 623); End; ****************************************************) procedure TXYcurveObj.Set_X(Value: Double); begin FX := (Value - FXshift) / FXscale; FY := GetYValue(FX); //Keep In synch end; PROCEDURE TXYCurveObj.Set_XValue(Index:Integer; Value: Double); Begin If Index <= FNumPoints Then XValues^[Index] := Value; End; procedure TXYcurveObj.Set_Y(Value: Double); begin FY := (Value - FYshift) / FYscale; FX := GetXValue(FY); //Keep In synch end; PROCEDURE TXYCurveObj.Set_YValue(Index:Integer; Value: Double); Begin If Index <= FNumPoints Then YValues^[Index] := Value; End; procedure TXYcurveObj.SaveWrite(var F: TextFile); {Override standard SaveWrite} {Transformer structure not conducive to standard means of saving} var iprop : Integer; begin {Write only properties that were explicitly set in the final order they were actually set} {Write Npts out first so that arrays get allocated properly} Write(F, Format(' Npts=%d',[NumPoints])); iProp := GetNextPropertySet(0); // Works on ActiveDSSObject While iProp > 0 Do Begin With ParentClass Do {Trap npts= and write out array properties instead} CASE RevPropertyIdxMap[iProp] of 1: {Ignore Npts}; ELSE Write(F,Format(' %s=%s', [PropertyName^[RevPropertyIdxMap[iProp]],CheckForBlanks(PropertyValue[iProp])] )); END; iProp := GetNextPropertySet(iProp); End; end; PROCEDURE TXYcurveObj.Set_NumPoints(const Value: Integer); Begin PropertyValue[1] := IntToStr(Value); // Update property list variable // Reset array property values to keep them in propoer order in Save If ArrayPropertyIndex>0 Then PropertyValue[ArrayPropertyIndex] := PropertyValue[ArrayPropertyIndex]; FNumPoints := Value; // Now assign the value // reallocate the curve memory ReAllocmem(YValues, Sizeof(YValues^[1]) * FNumPoints); ReAllocmem(XValues, Sizeof(XValues^[1]) * FNumPoints); End; End.
(****************************************************************) (* Programmname : KEYMOUSE.PAS V1.7 *) (* Programmautor : Michael Rippl *) (* Compiler : Quick Pascal V1.0 *) (* Inhalt : Routinen fr Abfrage von Maus und Tastatur *) (* Bemerkung : Erkennt automatisch, ob Maus vorhanden *) (* Letzte Žnderung : 13-Jul-1990 *) (****************************************************************) UNIT KeyMouse; INTERFACE USES Dos; (* Units einbinden *) CONST EventMouseMove = 1; (* Bewegung der Maus *) EventLeftDown = 2; (* Linke Taste drcken *) EventLeftUp = 4; (* Linke Taste loslassen *) EventRightDown = 8; (* Rechte Taste drcken *) EventRightUp = 16; (* Rechte Taste loslassen *) EventMiddleDown = 32; (* Mittlere Taste drcken *) EventMiddleUp = 64; (* Mittlere Taste loslass. *) EventASCIICode = 1; (* Taste liefert ASCII *) EventStatusChange = 2; (* Neuer Tastaturstatus *) EventMakeCode = 4; (* Make Code von Port 60h *) EventReleaseCode = 8; (* Release Code Port 60h *) CONST NoUserId = 0; (* Keine Benutzernummer *) CONST LeftButton = 1; (* Linke Maustaste *) RightButton = 2; (* Rechte Maustaste *) MiddleButton = 4; (* Mittlere Maustaste *) RightShiftKey = 1; (* Rechte Shift Taste *) LeftShiftKey = 2; (* Linke Shift Taste *) CtrlKey = 4; (* Control (Strg) Taste *) AltKey = 8; (* Alternate Taste *) ScrollLockKey = 16; (* Scroll Lock Taste *) NumLockKey = 32; (* Number Lock Taste *) CapsLockKey = 64; (* Caps Lock Taste *) InsertKey = 128; (* Insert (Einfg) Taste *) CONST ShiftTab = 15; AltQ = 16; (* Erweiterte Tastencodes *) AltW = 17; AltE = 18; AltR = 19; AltT = 20; AltY = 21; AltU = 22; AltI = 23; AltO = 24; AltP = 25; AltA = 30; AltS = 31; AltD = 32; AltF = 33; AltG = 34; AltH = 35; AltJ = 36; AltK = 37; AltL = 38; AltZ = 44; AltX = 45; AltC = 46; AltV = 47; AltB = 48; AltN = 49; AltM = 50; F1 = 59; F2 = 60; F3 = 61; F4 = 62; F5 = 63; F6 = 64; F7 = 65; F8 = 66; F9 = 67; F10 = 68; Home = 71; CursorUp = 72; PageUp = 73; CursorLeft = 75; CursorRight = 77; EndKey = 79; CursorDown = 80; PageDown = 81; Insert = 82; DelKey = 83; ShiftF1 = 84; ShiftF2 = 85; ShiftF3 = 86; ShiftF4 = 87; ShiftF5 = 88; ShiftF6 = 89; ShiftF7 = 90; ShiftF8 = 91; ShiftF9 = 92; ShiftF10 = 93; CtrlF1 = 94; CtrlF2 = 95; CtrlF3 = 96; CtrlF4 = 97; CtrlF5 = 98; CtrlF6 = 99; CtrlF7 = 100; CtrlF8 = 101; CtrlF9 = 102; CtrlF10 = 103; AltF1 = 104; AltF2 = 105; AltF3 = 106; AltF4 = 107; AltF5 = 108; AltF6 = 109; AltF7 = 110; AltF8 = 111; AltF9 = 112; AltF10 = 113; CtrlCursorLeft = 115; CtrlCursorRight = 116; CtrlEnd = 117; CtrlPageDown = 118; CtrlHome = 119; Alt1 = 120; Alt2 = 121; Alt3 = 122; Alt4 = 123; Alt5 = 124; Alt6 = 125; Alt7 = 126; Alt8 = 127; Alt9 = 128; Alt0 = 129; CtrlPageUp = 132; CONST Bel = 7; BackSpace = 8; (* Normale Tastaturcodes *) Tab = 9; LineFeed = 10; CarriageReturn = 13; Esc = 27; Space = 32; CtrlA = 1; CtrlB = 2; CtrlC = 3; CtrlD = 4; CtrlE = 5; CtrlF = 6; CtrlG = 7; CtrlH = 8; CtrlI = 9; CtrlJ = 10; CtrlK = 11; CtrlL = 12; CtrlM = 13; CtrlN = 14; CtrlO = 15; CtrlP = 16; CtrlQ = 17; CtrlR = 18; CtrlS = 19; CtrlT = 20; CtrlU = 21; CtrlV = 22; CtrlW = 23; CtrlX = 24; CtrlY = 25; CtrlZ = 26; TYPE Event = RECORD (* Maus, Tasten Ereignis *) BiosTick : LONGINT; (* Zeitpunkt vom Ereignis *) CASE Mouse : BOOLEAN OF (* Maus oder Tastatur *) TRUE : (* Maus Ereignis *) (mEvent, (* Grund des Ereignisses *) Buttons : WORD; (* Status der Mauskn”pfe *) Column, (* Mausposition Spalte *) Line, (* Mausposition Zeile *) AreaId, (* Nummer eines Bereichs *) RelativX, (* Relativ X zum Bereich *) RelativY : BYTE); (* Relativ Y zum Bereich *) FALSE : (* Tastatur Ereignis *) (tEvent, (* Grund des Ereignisses *) KeyCode, (* ASCII Code der Taste *) ExtCode, (* Erweiterter Tastencode *) ScanCode : BYTE); (* Scan Code der Taste *) END; TYPE UserId = 1..128; (* Identifikation Bereich *) MouseType = (Bus, Serial, InPort, PS2, HP);(* Typ der Maus *) EventHandler = PROCEDURE (NewEvent : Event); (* Handler fr Ereignis *) Handlers = (HandlerMouseMove, HandlerLeftDown, HandlerLeftUp, HandlerRightDown, HandlerRightUp, HandlerMiddleDown, HandlerMiddleUp, HandlerASCIICode, HandlerStatusChange, HandlerMakeCode, HandlerReleaseCode); (* M”gliche Handlertypen *) HandlerSet = SET OF Handlers; (* Menge von Handlern *) VAR MouseAvail : BOOLEAN; (* Maus vorhanden *) MouseX, (* Aktuelle X Position *) MouseY, (* Aktuelle Y Position *) NrOfButtons : BYTE; (* Anzahl der Mauskn”pfe *) (* Diese Prozedur ermittelt den Maustyp und die Versionsnummer der Maus *) PROCEDURE GetMouseType(VAR VerHigh, VerLow : BYTE; VAR MouseTyp : MouseType); (* Diese Prozedur schaltet den Cursor der Maus an *) PROCEDURE MouseOn; (* Diese Prozedur schaltet den Cursor der Maus aus *) PROCEDURE MouseOff; (* Diese Prozedur legt das Erscheinungsbild des Maus-Cursors fest *) PROCEDURE DefineMouseCursor(ScreenMask, CursorMask : WORD); (* Es wird die Geschwindigkeit der Maus in Mickeys = 1/200 Zoll festgelegt *) PROCEDURE SetMouseSpeed(Horizontal, Vertical : WORD); (* Diese Prozedur holt ein Ereignis von den Warteschlangen *) PROCEDURE GetEvent(VAR NewEvent : Event); (* N„chstes Ereignis holen ohne es aus der Warteschlange zu nehmen *) PROCEDURE LookEvent(VAR NewEvent : Event); (* Diese Prozedur prft ob ein Maus Ereignis vorliegt *) FUNCTION IsMouseEvent : BOOLEAN; (* Diese Prozedur prft ob ein Tastatur Ereignis vorliegt *) FUNCTION IsKeyEvent : BOOLEAN; (* Diese Prozedur prft ob ein Tastatur oder Maus Ereignis vorliegt *) FUNCTION IsEvent : BOOLEAN; (* Diese Prozedur setzt den Maus Cursor an eine bestimmte Position *) PROCEDURE SetMouseXY(LeftEdge, TopEdge : WORD); (* Diese Prozedur schr„nkt den Bewegungsbereich des Maus Cursors ein *) PROCEDURE SetMouseArea(LeftEdge, TopEdge, Width, Height : WORD); (* Diese Prozedur ordnet einem Bildschirmbereich eine Benutzernummer zu *) PROCEDURE CreateArea(LeftEdge, TopEdge, Width, Height : BYTE; AreaNr : UserId); (* Diese Prozedur entfernt die Zuordnung zu einem Bildschirmbereich *) PROCEDURE DeleteArea(AreaNr : UserId); (* Diese Prozedur installiert einen Handler fr ein bestimmtes Ereignis *) PROCEDURE InstallHandler(HandlerProc : EventHandler; OneEvent : Handlers); (* Diese Prozedur entfernt einen Handler fr ein bestimmtes Ereignis *) PROCEDURE RemoveHandler(OneEvent : Handlers); (* Diese Prozedur wartet auf ein Ereignis und ruft dessen Handler auf *) PROCEDURE WaitEvent(StopEvents : HandlerSet); (* Fr den Release Code der Tasten wird ein Ereignis erzeugt *) PROCEDURE ReleaseCodeOn; (* Fr den Release Code der Tasten wird kein Ereignis erzeugt *) PROCEDURE ReleaseCodeOff; (* Fr den Make Code der Tasten wird ein Ereignis erzeugt *) PROCEDURE MakeCodeOn; (* Fr den Make Code der Tasten wird kein Ereignis erzeugt *) PROCEDURE MakeCodeOff; (* Diese Funktion liefert den Tastaturstatus *) FUNCTION GetKeyStatus : BYTE; (* Diese Prozedur legt den Tastaturstatus fest *) PROCEDURE SetKeyStatus(Status : BYTE); (* Diese Prozedur l”scht Statusinformationen *) PROCEDURE DelKeyStatus(Status : BYTE); (* Diese Prozedur setzt die Typematic-Rate und die Delay-Rate der Tastatur *) PROCEDURE SetKeySpeed(DelayRate, TypematicRate : BYTE); (* Diese Prozedur entfernt die Interrupt Routine fr die Tastatur *) PROCEDURE ReInstallKeyInterrupt; (* Diese Prozedur installiert die Interrupt Routine fr die Tastatur *) PROCEDURE InstallKeyInterrupt; IMPLEMENTATION CONST AllMouseEvents = 127; (* Alle Maus-Ereignisse *) MaxEvents = 100; (* Maximale Event-Anzahl *) TYPE Area = ARRAY [0..24768] OF BYTE; (* Typ vom Benutzerbereich *) pEventTable = ^EventTable; (* Zeiger auf Eventtabelle *) Handler = RECORD (* Typ eines Handlers *) Call : BOOLEAN; (* Handler installiert *) CallProc : EventHandler; (* Prozedur fr Handler *) END; Coordinates = RECORD (* Koordinaten vom Bereich *) Column, (* Linke Spalte *) Line, (* Obere Zeile *) SizeX, (* Anzahl der Spalten *) SizeY : BYTE; (* Anzahl der Zeilen *) END; EventTable = RECORD (* Tabelle der Ereignisse *) Last, (* Letztes Ereignis *) Next : 0..MaxEvents; (* N„chstes Ereignis *) Fifo : ARRAY [0..MaxEvents] OF Event; END; (* Ereignisse, Fifo-Liste *) VAR NrOfLines, (* Anzahl der Zeilen *) NrOfColumns, (* Anzahl der Spalten *) OldMouseX, (* Alte Maus X Position *) OldMouseY : BYTE; (* Alte Maus Y Position *) Interrupt09, (* Interrupt $09 Routine *) OldExitProc : POINTER; (* Alte Exit-Prozedur *) MakeKey, (* Make Code erzeugen *) ReleaseKey : BOOLEAN; (* Release Code erzeugen *) MouseRing, (* Warteschlange fr Maus *) KeyRing : pEventTable; (* Warteschlange fr Taste *) UserArea : ^Area; (* Benutzer Bereiche *) Time : LONGINT ABSOLUTE $40:$6C; (* Tick-Z„hler vom BIOS *) KeyStatus : BYTE ABSOLUTE $40:$17; (* Statusbyte vom BIOS *) ActKeyStatus : BYTE; (* Aktueller Tastenstatus *) DefinedId : ARRAY [UserId] OF Coordinates; (* Definierte Nummern *) HandlerTable : ARRAY [Handlers] OF Handler; (* Tabelle aller Handler *) (*$F+ Diese Assembler-Prozedur dient als Handler fr den Maustreiber *) PROCEDURE MouseHandler; EXTERNAL; (*$F-*) (*$L Mouse.Obj *) (*$F+ Diese Assembler-Prozedur dient als Erg„nzung fr den Interrupt $09 *) PROCEDURE KeyboardHandler; EXTERNAL; (*$F-*) (*$L Keyboard.Obj *) (* Diese Prozedur fgt ein Event in eine Liste ein *) PROCEDURE Push(EventQueue : pEventTable; Item : Event); BEGIN WITH EventQueue^ DO BEGIN IF Last + 1 <> Next THEN (* Ring ist nicht voll *) BEGIN Fifo[Last] := Item; (* Ereignis eintragen *) Last := (Last + 1) MOD (MaxEvents + 1); (* Falls Ende, dann Anfang *) END; END; END; (* Push *) (* Diese Prozedur entfernt ein Element aus einer Liste *) PROCEDURE Pop(EventQueue : pEventTable; VAR Item : Event); BEGIN WITH EventQueue^ DO BEGIN IF Last <> Next THEN (* Ring ist nicht leer *) BEGIN Item := Fifo[Next]; Next := (Next + 1) MOD (MaxEvents + 1); (* Falls Ende, dann Anfang *) END ELSE Item.BiosTick := MaxLongInt; (* Ring ist leer *) END; END; (* Pop *) (* Diese Prozedur wird vom Handler des Maustreibers aufgerufen *) PROCEDURE MouseEvent(MouseEvents, MouseButtons : WORD); VAR ActualTime : LONGINT; Item : Event; EventMask : WORD; i : BYTE; BEGIN ActualTime := Time; (* Zeitpunkt merken *) EventMask := 1; (* Zum Auslesen von Bits *) FOR i := 1 TO 7 DO (* Alle Events durchgehen *) BEGIN IF (MouseEvents AND EventMask) = EventMask THEN BEGIN IF NOT ((EventMask = EventMouseMove) AND (OldMouseX = MouseX) AND (OldMouseY = MouseY)) THEN (* Position nicht doppelt *) BEGIN WITH Item DO BEGIN BiosTick := ActualTime; (* Zeitpunkt eintragen *) Mouse := TRUE; (* Ereignis von der Maus *) Buttons := MouseButtons; Line := MouseY; Column := MouseX; OldMouseY := Line; (* Doppeleintrag vermeiden *) OldMouseX := Column; AreaId := UserArea^[Line * NrOfColumns + Column]; mEvent := EventMask; IF AreaId = NoUserId THEN (* Auf keinem Bereich *) BEGIN RelativX := Column; RelativY := Line; END ELSE (* Ereignis auf Bereich *) BEGIN RelativX := Column - DefinedId[AreaId].Column; RelativY := Line - DefinedId[AreaId].Line; END; END; Push(MouseRing, Item); (* In Warteschlange setzen *) END; END; EventMask := EventMask SHL 1; (* N„chstes Event-Bit *) END; END; (* MouseEvent *) (* Diese Prozedur wird vom neuen Interrupt $09 Handler aufgerufen *) PROCEDURE KeyboardEvent(KeyPort : BYTE); VAR ActualTime : LONGINT; Item : Event; Regs : REGISTERS; NewKeyStatus : BYTE; BEGIN ActualTime := Time; (* Zeitpunkt merken *) NewKeyStatus := KeyStatus; (* Neuen Status merken *) Item.BiosTick := MaxLongInt; (* Kein Ereignis vorhanden *) Regs.AH := $01; (* Tastaturpuffer prfen *) Intr($16, Regs); (* Tasten Interrupt *) IF (Regs.Flags AND FZero) = 0 THEN (* Code im Tastaturpuffer *) BEGIN WITH Item DO BEGIN tEvent := EventASCIICode; (* Taste liefert ASCII *) BiosTick := ActualTime; (* Zeitpunkt vom Ereignis *) Regs.AH := $00; (* Code aus Puffer lesen *) Intr($16, Regs); (* Tasten Interrupt *) KeyCode := Regs.AL; (* ASCII Code der Taste *) ExtCode := Regs.AH; (* Erweiterter Tastencode *) END; END ELSE (* Kein Tastencode erzeugt *) BEGIN IF ActKeyStatus <> NewKeyStatus THEN (* Status„nderung *) BEGIN IF NewKeyStatus > ActKeyStatus THEN (* Ein Bit wurde gesetzt *) BEGIN IF (NewKeyStatus XOR ActKeyStatus) <> InsertKey THEN BEGIN (* Keine Insert Taste *) WITH Item DO BEGIN tEvent := EventStatusChange; BiosTick := ActualTime; (* Zeitpunkt vom Ereignis *) KeyCode := NewKeyStatus XOR ActKeyStatus; END; END; END ELSE IF ReleaseKey THEN (* Release Code der Taste *) BEGIN Item.tEvent := EventReleaseCode; Item.BiosTick := ActualTime; (* Zeitpunkt vom Ereignis *) END; ActKeyStatus := NewKeyStatus; END ELSE IF KeyPort < 128 THEN (* Make Code der Taste *) BEGIN IF MakeKey THEN (* Make Code erzeugen *) BEGIN Item.tEvent := EventMakeCode; Item.BiosTick := ActualTime; (* Zeitpunkt vom Ereignis *) END; END ELSE IF ReleaseKey THEN (* Release Code der Taste *) BEGIN Item.tEvent := EventReleaseCode; Item.BiosTick := ActualTime; (* Zeitpunkt vom Ereignis *) END; END; IF Item.BiosTick <> MaxLongInt THEN (* Ereignis vorhanden *) BEGIN Item.Mouse := FALSE; (* Ereignis von Tastatur *) Item.ScanCode := KeyPort; (* Scan Code der Taste *) Push(KeyRing, Item); (* In Warteschlange setzen *) END; END; (* KeyboardEvent *) (* Diese Prozedur ermittelt den Maustyp und die Versionsnummer der Maus *) PROCEDURE GetMouseType(VAR VerHigh, VerLow : BYTE; VAR MouseTyp : MouseType); VAR Regs : REGISTERS; BEGIN Regs.AX := $0024; (* Maustyp ermitteln *) Intr($33, Regs); (* Maus Interrupt *) VerHigh := Regs.BH; VerLow := Regs.BL; CASE Regs.CH OF (* Unterschiedliche Typen *) 1 : MouseTyp := Bus; 2 : MouseTyp := Serial; 3 : MouseTyp := InPort; 4 : MouseTyp := PS2; 5 : MouseTyp := HP; END; END; (* GetMouseType *) (* Diese Prozedur schaltet den Cursor der Maus an *) PROCEDURE MouseOn; VAR Regs : REGISTERS; BEGIN Regs.AX := $0001; (* Maus Cursor anschalten *) Intr($33, Regs); (* Maus Interrupt *) END; (* MouseOn *) (* Diese Prozedur schaltet den Cursor der Maus aus *) PROCEDURE MouseOff; VAR Regs : REGISTERS; BEGIN Regs.AX := $0002; (* Maus Cursor ausschalten *) Intr($33, Regs); (* Maus Interrupt *) END; (* MouseOff *) (* Diese Prozedur legt das Erscheinungsbild des Maus-Cursors fest *) PROCEDURE DefineMouseCursor(ScreenMask, CursorMask : WORD); VAR Regs : REGISTERS; BEGIN Regs.AX := $000A; (* Maus Cursor definieren *) Regs.BX := $0000; (* Software Cursor *) Regs.CX := ScreenMask; Regs.DX := CursorMask; Intr($33, Regs); (* Maus Interrupt *) END; (* DefineMouseCursor *) (* Es wird die Geschwindigkeit der Maus in Mickeys = 1/200 Zoll festgelegt *) PROCEDURE SetMouseSpeed(Horizontal, Vertical : WORD); VAR Regs : REGISTERS; BEGIN Regs.AX := $000F; (* Maus Geschwindigkeit *) Regs.CX := Horizontal; Regs.DX := Vertical; Intr($33, Regs); (* Maus Interrupt *) END; (* SetMouseSpeed *) (* Diese Prozedur prft ob ein Maus Ereignis vorliegt *) FUNCTION IsMouseEvent : BOOLEAN; BEGIN IsMouseEvent := MouseRing^.Last <> MouseRing^.Next; END; (* IsMouseEvent *) (* Diese Prozedur prft ob ein Tastatur Ereignis vorliegt *) FUNCTION IsKeyEvent : BOOLEAN; BEGIN IsKeyEvent := KeyRing^.Last <> KeyRing^.Next; END; (* IsKeyEvent *) (* Diese Prozedur prft ob ein Tastatur oder Maus Ereignis vorliegt *) FUNCTION IsEvent : BOOLEAN; BEGIN IsEvent := (KeyRing^.Last <> KeyRing^.Next) OR (MouseRing^.Last <> MouseRing^.Next); END; (* IsEvent *) (* Diese Prozedur setzt den Maus Cursor an eine bestimmte Position *) PROCEDURE SetMouseXY(LeftEdge, TopEdge : WORD); VAR Regs : REGISTERS; BEGIN MouseX := LeftEdge; (* Neue Positionen merken *) MouseY := TopEdge; Regs.AX := $0004; (* Maus Cursor setzen *) Regs.CX := LeftEdge SHL 3; Regs.DX := TopEdge SHL 3; Intr($33, Regs); (* Maus Interrupt *) END; (* SetMouseXY *) (* Diese Prozedur schr„nkt den Bewegungsbereich des Maus Cursors ein *) PROCEDURE SetMouseArea(LeftEdge, TopEdge, Width, Height : WORD); VAR Regs : REGISTERS; BEGIN Regs.AX := $0007; (* Horizontale Grenzen *) Regs.CX := LeftEdge SHL 3; Regs.DX := (LeftEdge + Width - 1) SHL 3; Intr($33, Regs); (* Maus Interrupt *) Regs.AX := $0008; (* Vertikale Grenzen *) Regs.CX := TopEdge SHL 3; Regs.DX := (TopEdge + Height - 1) SHL 3; Intr($33, Regs); END; (* SetMouseArea *) (* Diese Prozedur ordnet einem Bildschirmbereich eine Benutzernummer zu *) PROCEDURE CreateArea(LeftEdge, TopEdge, Width, Height : BYTE; AreaNr : UserId); VAR i : BYTE; BEGIN IF (Width > 0) AND (Height > 0) AND (* Bereichsprfung *) (LeftEdge + Width <= NrOfColumns) AND (TopEdge + Height <= NrOfLines) AND (DefinedId[AreaNr].SizeX = 0) THEN (* Bereich nicht belegt *) BEGIN FOR i := 0 TO Height - 1 DO (* Bereich erzeugen *) FillChar(UserArea^[(TopEdge + i) * NrOfColumns + LeftEdge], Width, AreaNr); WITH DefinedId[AreaNr] DO (* Bereichsdaten merken *) BEGIN Column := LeftEdge; Line := TopEdge; SizeX := Width; SizeY := Height; END; END; END; (* CreateArea *) (* Diese Prozedur entfernt die Zuordnung zu einem Bildschirmbereich *) PROCEDURE DeleteArea(AreaNr : UserId); VAR i : BYTE; BEGIN WITH DefinedId[AreaNr] DO (* Bereichsdaten berechnen *) BEGIN IF SizeX > 0 THEN (* Gltige Benutzernummer *) BEGIN FOR i := 0 TO SizeY - 1 DO (* Bereich l”schen *) FillChar(UserArea^[(Line + i) * NrOfColumns + Column], SizeX, NoUserId); Line := 0; (* Defaultwerte eintragen *) Column := 0; SizeX := 0; SizeY := 0; END; END; END; (* DeleteArea *) (* Diese Prozedur holt ein Ereignis von den Warteschlangen *) PROCEDURE GetEvent(VAR NewEvent : Event); BEGIN REPEAT UNTIL IsEvent; (* Warte auf Ereignis *) IF IsMouseEvent AND IsKeyEvent THEN (* Tastatur, Maus Ereignis *) BEGIN IF KeyRing^.Fifo[KeyRing^.Next].BiosTick < (* Zeiten vergleichen *) MouseRing^.Fifo[MouseRing^.Next].BiosTick THEN Pop(KeyRing, NewEvent) (* Tastatur Ereignis *) ELSE Pop(MouseRing, NewEvent); (* Maus Ereignis *) END ELSE IF IsKeyEvent THEN Pop(KeyRing, NewEvent) (* Tastatur Ereignis *) ELSE Pop(MouseRing, NewEvent); (* Maus Ereignis *) END; (* GetEvent *) (* N„chstes Ereignis holen ohne es aus der Warteschlange zu nehmen *) PROCEDURE LookEvent(VAR NewEvent : Event); BEGIN IF NOT IsEvent THEN (* Kein Ereignis vorhanden *) NewEvent.BiosTick := MaxLongInt ELSE IF IsMouseEvent AND IsKeyEvent THEN (* Tastatur, Maus Ereignis *) BEGIN IF KeyRing^.Fifo[KeyRing^.Next].BiosTick < (* Zeiten vergleichen *) MouseRing^.Fifo[MouseRing^.Next].BiosTick THEN NewEvent := KeyRing^.Fifo[KeyRing^.Next] (* Tastatur Ereignis *) ELSE NewEvent := MouseRing^.Fifo[MouseRing^.Next]; (* Maus Ereignis *) END ELSE IF IsKeyEvent THEN (* Tastatur Ereignis *) NewEvent := KeyRing^.Fifo[KeyRing^.Next] ELSE NewEvent := MouseRing^.Fifo[MouseRing^.Next]; (* Maus Ereignis *) END; (* LookEvent *) (* Diese Prozedur installiert einen Handler fr ein bestimmtes Ereignis *) PROCEDURE InstallHandler(HandlerProc : EventHandler; OneEvent : Handlers); BEGIN HandlerTable[OneEvent].Call := TRUE; (* Handler ist installiert *) HandlerTable[OneEvent].CallProc := HandlerProc; (* Prozedur fr Ereignis *) END; (* InstallHandler *) (* Diese Prozedur entfernt einen Handler fr ein bestimmtes Ereignis *) PROCEDURE RemoveHandler(OneEvent : Handlers); BEGIN HandlerTable[OneEvent].Call := FALSE; (* Handler nicht vorhanden *) END; (* RemoveHandler *) (* Diese Prozedur wartet auf ein Ereignis und ruft dessen Handler auf *) PROCEDURE WaitEvent(StopEvents : HandlerSet); VAR NewEvent : Event; CallHandler : Handlers; BEGIN REPEAT (* Schleife bis Stop Event *) GetEvent(NewEvent); (* Warte auf Ereignis *) IF NewEvent.Mouse THEN (* Maus Ereignis *) BEGIN CASE NewEvent.mEvent OF EventMouseMove : CallHandler := HandlerMouseMove; EventLeftDown : CallHandler := HandlerLeftDown; EventLeftUp : CallHandler := HandlerLeftUp; EventMiddleDown : CallHandler := HandlerMiddleDown; EventMiddleUp : CallHandler := HandlerMiddleUp; EventRightDown : CallHandler := HandlerRightDown; EventRightUp : CallHandler := HandlerRightUp; END; END ELSE (* Tastatur Ereignis *) BEGIN CASE NewEvent.tEvent OF EventASCIICode : CallHandler := HandlerASCIICode; EventStatusChange : CallHandler := HandlerStatusChange; EventMakeCode : CallHandler := HandlerMakeCode; EventReleaseCode : CallHandler := HandlerReleaseCode; END; END; IF HandlerTable[CallHandler].Call THEN (* Handler ist installiert *) HandlerTable[CallHandler].CallProc(NewEvent); UNTIL CallHandler IN StopEvents; END; (* WaitEvent *) (* Es wird auch beim Loslassen einer Taste ein Ereignis erzeugt *) PROCEDURE ReleaseCodeOn; BEGIN ReleaseKey := TRUE; (* Release Code erzeugen *) END; (* ReleaseCodeOn *) (* Beim Loslassen einer Taste wird kein Ereignis erzeugt *) PROCEDURE ReleaseCodeOff; BEGIN ReleaseKey := FALSE; (* Release Code ignorieren *) END; (* ReleaseCodeOff *) (* Fr den Make Code der Tasten wird ein Ereignis erzeugt *) PROCEDURE MakeCodeOn; BEGIN MakeKey := TRUE; (* Make Code erzeugen *) END; (* MakeCodeOn *) (* Fr den Make Code der Tasten wird kein Ereignis erzeugt *) PROCEDURE MakeCodeOff; BEGIN MakeKey := FALSE; (* Make Code ignorieren *) END; (* MakeCodeOff *) (* Diese Funktion liefert den Tastaturstatus *) FUNCTION GetKeyStatus : BYTE; BEGIN GetKeyStatus := KeyStatus; (* Status auslesen *) END; (* GetKeyStatus *) (* Diese Prozedur entfernt die Interrupt Routine fr die Tastatur *) PROCEDURE ReInstallKeyInterrupt; BEGIN SetIntVec($09, Interrupt09); (* Interrupt $09 setzen *) END; (* ReInstallKeyInterrupt *) (* Diese Prozedur installiert die Interrupt Routine fr die Tastatur *) PROCEDURE InstallKeyInterrupt; BEGIN SetIntVec($09, Addr(KeyboardHandler)); (* Neuer Tastaturhandler *) END; (* InstallKeyInterrupt *) (* Diese Prozedur legt den Tastaturstatus fest *) PROCEDURE SetKeyStatus(Status : BYTE); VAR Regs : REGISTERS; BEGIN KeyStatus := KeyStatus OR Status; (* Statusbits setzen *) ActKeyStatus := KeyStatus; (* Status aktualisieren *) Regs.AH := $02; (* Bios informieren *) Intr($16, Regs); (* Tastatur Interrupt *) Regs.AH := $01; (* LED's anschalten *) Intr($16, Regs); (* Tastatur Interrupt *) END; (* SetKeyStatus *) (* Diese Prozedur l”scht Statusinformationen *) PROCEDURE DelKeyStatus(Status : BYTE); VAR Regs : REGISTERS; BEGIN KeyStatus := KeyStatus AND (Status XOR $FF); (* Statusbits l”schen *) ActKeyStatus := KeyStatus; (* Status aktualisieren *) Regs.AH := $02; (* Bios informieren *) Intr($16, Regs); (* Tastatur Interrupt *) Regs.AH := $01; (* LED's ausschalten *) Intr($16, Regs); (* Tastatur Interrupt *) END; (* DelKeyStatus *) (* Diese Prozedur setzt die Typematic-Rate und die Delay-Rate der Tastatur *) PROCEDURE SetKeySpeed(DelayRate, TypematicRate : BYTE); VAR Regs : REGISTERS; BEGIN Regs.AX := $0305; (* Tastengeschwindigkeit *) Regs.BH := DelayRate AND $03; (* Nur Bits 0, 1 belassen *) Regs.BL := TypematicRate AND $1F; (* Nur Bits 0 - 4 belassen *) Intr($16, Regs); (* Tastatur Interrupt *) END; (*$F+ Diese Prozedur beendet die Arbeit mit der KeyMouse Unit *) PROCEDURE DelKeyMouse; VAR Regs : REGISTERS; BEGIN SetIntVec($09, Interrupt09); (* Interrupt $09 setzen *) IF MouseAvail THEN (* Maus vorhanden *) BEGIN MouseOff; (* Maus Cursor ausschalten *) Regs.AX := $0000; (* Reset des Maustreibers *) Intr($33, Regs); (* Maus Interrupt *) END; Dispose(KeyRing); (* Speicher freigeben *) Dispose(MouseRing); FreeMem(UserArea, NrOfLines * NrOfColumns); ExitProc := OldExitProc; (* Mehrere Exit-Prozeduren *) END; (*$F- DelKeyMouse *) (* Diese Prozedur initialisiert die KeyMouse Unit *) PROCEDURE InitKeyMouse; TYPE pBYTE = ^BYTE; (* Zeiger auf ein Byte *) VAR Regs : REGISTERS; BEGIN NrOfLines := pBYTE(Ptr($40, $84))^ + 1; (* Anzahl der Zeilen *) NrOfColumns := pBYTE(Ptr($40, $4A))^; (* Anzahl der Spalten *) ActKeyStatus := KeyStatus; (* Aktueller Tastenstatus *) ReleaseCodeOff; (* Release Code ignorieren *) MakeCodeOff; (* Make Code ignorieren *) GetIntVec($09, Interrupt09); (* Tastaturinterrupt *) SetIntVec($09, Addr(KeyboardHandler)); (* Neuer Tastaturhandler *) OldExitProc := ExitProc; (* Exit-Prozedur merken *) ExitProc := Addr(DelKeyMouse); (* Neue Exit-Prozedur *) New(KeyRing); (* Speicher fr Ereignisse *) KeyRing^.Last := 0; (* Kein Ereignis enthalten *) KeyRing^.Next := 0; (* Kein Ereignis enthalten *) New(MouseRing); (* Speicher fr Ereignisse *) MouseRing^.Last := 0; (* Kein Ereignis enthalten *) MouseRing^.Next := 0; (* Kein Ereignis enthalten *) GetMem(UserArea, NrOfLines * NrOfColumns); (* Speicher fr Bereiche *) FillChar(UserArea^, NrOfLines * NrOfColumns, NoUserId); FillChar(DefinedId, SizeOf(DefinedId), 0); (* Kein Bereich definiert *) FillChar(HandlerTable, SizeOf(HandlerTable), 0);(* Kein Handler vorhanden *) Regs.AX := $0000; (* Reset des Maustreibers *) Intr($33, Regs); (* Maus Interrupt *) MouseAvail := Regs.AX = $FFFF; IF MouseAvail THEN (* Maus vorhanden *) BEGIN NrOfButtons := Regs.BL; (* Anzahl der Mauskn”pfe *) Regs.AX := $000C; (* Maus-Handler festlegen *) Regs.ES := Seg(MouseHandler); (* Adresse als Far-Call *) Regs.DX := Ofs(MouseHandler); Regs.CX := AllMouseEvents; (* Alle Events erkennen *) Intr($33, Regs); (* Maus Interrupt *) OldMouseX := 0; (* Defaultwerte *) OldMouseY := 0; END ELSE NrOfButtons := 0; (* Maus nicht vorhanden *) END; (* InitKeyMouse *) BEGIN (* Initialisierung *) InitKeyMouse; END. (* KeyMouse *)
unit Game; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CustApp, SnakeUnit, Coords, Crt, VidUtils; const DELAY_SPEED = 150; MIN_DELAY = 75; VK_UP = #72; VK_DOWN = #80; VK_RIGHT = #77; VK_LEFT = #75; VK_ESC = #27; VK_ENTER = #13; type TGameState = (gsLoading, gsWelcome, gsStartGame, gsPlaying, gsGameOver, gsTerminate); { TSnakeApplication } TSnakeApplication = class(TCustomApplication) private State: TGameState; Snake: TSnake; Apple: TPosition; procedure DoLoadingScreen; procedure DoWelcomeScreen; procedure DoPlayingScreen; procedure DoGameOverScreen; procedure Draw; procedure DrawApple; procedure GameCheckCollitions; procedure HandleGameKeyEvents; procedure MoveAppleToRandomPosition; procedure StartGame; protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; end; implementation procedure TSnakeApplication.DoLoadingScreen; begin State := gsWelcome; TextBackground(Black); ClearScreen; Sleep(150); end; procedure TSnakeApplication.DoWelcomeScreen; begin State := gsStartGame; TextBackground(Green); ClearScreen; TextColor(Black); TextOutCentered([ 'Snake!', '-----------', 'Use arrow keys to move', 'Press any key to start' ]); ReadKey; end; procedure TSnakeApplication.DoGameOverScreen; var C: Char; begin TextBackground(Red); TextColor(White); ClearScreen; TextOutCentered([ 'Game over! :-(', '--------------', 'Press ENTER to play again, or ESC to exit' ]); repeat C := ReadKey; case C of VK_ESC: State := gsTerminate; VK_ENTER: State := gsStartGame; end; until State <> gsGameOver; end; procedure TSnakeApplication.DoPlayingScreen; var CalculatedDelay: integer; begin HandleGameKeyEvents; Snake.Move; GameCheckCollitions; if State = gsGameOver then Exit; Draw; CalculatedDelay := DELAY_SPEED - (Length(Snake.Tail) * 2); if CalculatedDelay < MIN_DELAY then CalculatedDelay := MIN_DELAY; Delay(CalculatedDelay); end; procedure TSnakeApplication.Draw; begin TextBackground(Green); TextColor(Green); CursorOff; ClearScreen; Snake.Draw; DrawApple; GotoXY(1, ScreenHeight); end; procedure TSnakeApplication.DrawApple; begin TextColor(Red); TextBackground(Green); TextOut(Apple.X, Apple.Y, '@'); end; procedure TSnakeApplication.GameCheckCollitions; var Position: TPosition; begin if (Snake.Position.X <= 0) or (Snake.Position.X > ScreenWidth) or (Snake.Position.Y <= 0) or (Snake.Position.Y > ScreenHeight) then State := gsGameOver; for Position in Snake.Tail do if (Snake.Position.X = Position.X) and (Snake.Position.Y = Position.Y) then State := gsGameOver; if (Snake.Position.X = Apple.X) and (Snake.Position.Y = Apple.Y) then begin Snake.Grow; MoveAppleToRandomPosition; end; end; procedure TSnakeApplication.HandleGameKeyEvents; var PressedKey: char; Direction: TDirection; begin if not KeyPressed then Exit; Direction := Snake.Direction; while KeyPressed do begin PressedKey := ReadKey; case PressedKey of VK_UP: if Direction <> drSouth then Snake.Direction := drNorth; VK_DOWN: if Direction <> drNorth then Snake.Direction := drSouth; VK_RIGHT: if Direction <> drWest then Snake.Direction := drEast; VK_LEFT: if Direction <> drEast then Snake.Direction := drWest; VK_ESC: Terminate; end; end; end; procedure TSnakeApplication.MoveAppleToRandomPosition; const PADDING = 5; begin Apple.X := PADDING + Random(ScreenWidth - PADDING); Apple.Y := PADDING + Random(ScreenHeight - PADDING); end; procedure TSnakeApplication.StartGame; begin State := gsPlaying; MoveAppleToRandomPosition; Snake.Direction := drEast; Snake.Position.X := Round(ScreenWidth / 2); Snake.Position.Y := Round(ScreenHeight / 2); Snake.CleanTail; end; procedure TSnakeApplication.DoRun; begin RefreshWindowSize; case State of gsLoading: DoLoadingScreen; gsWelcome: DoWelcomeScreen; gsStartGame: StartGame; gsPlaying: DoPlayingScreen; gsGameOver: DoGameOverScreen; else Terminate; end; end; constructor TSnakeApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); Randomize; StopOnException := True; Snake := TSnake.Create; State := gsLoading; end; destructor TSnakeApplication.Destroy; begin NormVideo; CursorOn; ClearScreen; Snake.Free; inherited Destroy; end; end.
unit CatHighlighters; { Catarinka - Multiple Code Highlighters Copyright (c) 2011-2015 Syhunt Informatica License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details Color scheme adapted from the CodeRay project (MIT-licensed) https://github.com/rubychan/coderay Copyright (C) 2005-2012 Kornelius Kalnbach <murphy@rubychan.de> (@murphy_karasu) } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.Classes, System.SysUtils, System.TypInfo, Vcl.Graphics, {$ELSE} Classes, SysUtils, TypInfo, Graphics, {$ENDIF} SynUnicode, SynExportHTML, SynEditHighlighter, SynHighlighterRuby, SynHighlighterPerl, SynHighlighterPython, SynHighlighterPas, SynHighlighterVBScript, SynHighlighterSQL, SynHighlighterWeb, SynHighlighterWebData, SynHighlighterWebMisc; type TCatHighlighters = class private fSynWebEngine: TSynWebEngine; WebJS: TSynWebESSyn; WebCSS: TSynWebCSSSyn; WebXML: TSynWebXMLSyn; WebPHP: TSynWebPHPPlainSyn; Ruby: TSynRubySyn; Pascal: TSynPasSyn; Perl: TSynPerlSyn; Python: TSynPythonSyn; SQLSyn: TSynSQLSyn; VBScript: TSynVBScriptSyn; function GetSynExport(HL: TSynCustomHighlighter; Source: string): string; public WebHTML: TSynWebHtmlSyn; function GetByFileExtension(const fileext: string): TSynCustomHighlighter; function GetByContentType(const contenttype: string): TSynCustomHighlighter; function HighlightSourceByFileExt(const Source, fileext: string): string; procedure SetCodeRayColors(const e: TSynWebEngine); constructor Create(AOwner: TObject); destructor Destroy; override; end; implementation uses CatStrings; function TCatHighlighters.GetByContentType(const contenttype: string) : TSynCustomHighlighter; var ct: string; begin result := nil; ct := lowercase(contenttype); if pos('html', ct) <> 0 then result := WebHTML; if pos('javascript', ct) <> 0 then result := WebJS; if pos('xml', ct) <> 0 then result := WebXML; if pos('css', ct) <> 0 then result := WebCSS; end; type TWebExts = (css, dpr, htm, html, js, json, jsie, lua, lp, pas, pasrem, php, pl, py, rb, sql, tis, vbs, xml); function TCatHighlighters.GetByFileExtension(const fileext: string) : TSynCustomHighlighter; var ext: string; begin result := WebHTML; ext := lowercase(fileext); if beginswith(ext, '.') then ext := after(ext, '.'); if ext = emptystr then exit; case TWebExts(GetEnumValue(TypeInfo(TWebExts), ext)) of htm, html: result := WebHTML; lua, lp: result := nil; js, json, jsie, tis: result := WebJS; css: result := WebCSS; php: result := WebPHP; rb: result := Ruby; pas, dpr, pasrem: result := Pascal; pl: result := Perl; py: result := Python; sql: result := SQLSyn; vbs: result := VBScript; xml: result := WebXML; end; end; function TCatHighlighters.GetSynExport(HL: TSynCustomHighlighter; Source: string): string; var codestream: TMemoryStream; Code: TUnicodeStringList; SynExp: TSynExporterHTML; begin result := emptystr; if Source = emptystr then exit; codestream := TMemoryStream.Create; Code := TUnicodeStringList.Create; Code.Text := Source; SynExp := TSynExporterHTML.Create(nil); SynExp.Highlighter := HL; SynExp.ExportAsText := TRUE; SynExp.ExportAll(Code); SynExp.SaveToStream(codestream); SynExp.free; codestream.Position := 0; Code.LoadFromStream(codestream); // code.SaveToFile('D:\debug.txt'); result := Code.Text; Code.free; codestream.free; end; function TCatHighlighters.HighlightSourceByFileExt(const Source, fileext: string): string; var HL: TSynCustomHighlighter; begin result := emptystr; if Source = emptystr then exit; HL := GetByFileExtension(fileext); if HL <> nil then result := GetSynExport(HL, Source); end; procedure TCatHighlighters.SetCodeRayColors(const e: TSynWebEngine); begin e.mltagnameattri.foreground := $00007700; e.mltagnameundefattri.foreground := $00007700; e.mltagattri.foreground := $00007700; e.mltagkeyattri.foreground := $008844BB; e.mltagkeyundefattri.foreground := $008844BB; e.mltagkeyundefattri.Style := e.mltagkeyundefattri.Style - [fsUnderline]; e.mltagkeyvalueattri.foreground := $000022DD; e.mltagkeyvaluequotedattri.foreground := $000022DD; e.mlerrorattri.Style := e.mlerrorattri.Style - [fsUnderline]; e.mlerrorattri.foreground := $00007700; e.eskeyattri.foreground := $00008800; e.esidentifierattri.foreground := clBlack; e.esnumberattri.foreground := $00DD0000; e.escommentattri.foreground := $00777777; e.eswhitespaceattri.background := $00E0E0E0; e.cssselectorattri.foreground := $00993333; e.csspropattri.foreground := $00660066; e.csspropundefattri.foreground := $00660066; e.cssselectorclassattri.foreground := $006600BB; e.cssselectoridattri.foreground := $0000AA00; e.cssrulesetwhitespaceattri.background := clNone; e.csswhitespaceattri.background := clNone; e.csscommentattri.foreground := $00777777; e.cssvalattri.foreground := $00888800; e.cssvalundefattri.foreground := $00888800; e.cssvalundefattri.Style := e.cssvalundefattri.Style - [fsUnderline]; e.csserrorattri.foreground := $000000FF; e.csserrorattri.Style := e.csserrorattri.Style - [fsUnderline]; e.cssvalnumberattri.foreground := $0000AA00; e.CssValStringAttri.foreground := $000022DD; e.phpstringattri.foreground := $000022DD; e.phpstringspecialattri.foreground := $000022DD; e.phpvariableattri.foreground := $00008800; e.phpfunctionattri.foreground := $00996633; e.phpfunctionattri.Style := e.phpfunctionattri.Style + [fsBold]; e.phpkeyattri.foreground := $00008800; e.specialattri.phpmarker.foreground := $00666666; e.phpcommentattri.foreground := $00777777; e.phpdoccommentattri.foreground := $00777777; e.phpidentifierattri.foreground := $00BB6600; e.phpidentifierattri.Style := e.phpidentifierattri.Style + [fsBold]; e.PhpNumberAttri.foreground := $00DD0000; end; constructor TCatHighlighters.Create(AOwner: TObject); begin inherited Create; Ruby := TSynRubySyn.Create(nil); Pascal := TSynPasSyn.Create(nil); Perl := TSynPerlSyn.Create(nil); Python := TSynPythonSyn.Create(nil); VBScript := TSynVBScriptSyn.Create(nil); SQLSyn := TSynSQLSyn.Create(nil); fSynWebEngine := TSynWebEngine.Create(nil); fSynWebEngine.Options.CssVersion := scvCSS3; WebHTML := TSynWebHtmlSyn.Create(nil); WebHTML.Engine := fSynWebEngine; WebHTML.Options.PhpEmbeded := false; WebPHP := TSynWebPHPPlainSyn.Create(nil); WebPHP.Engine := fSynWebEngine; WebJS := TSynWebESSyn.Create(nil); WebJS.Engine := fSynWebEngine; WebCSS := TSynWebCSSSyn.Create(nil); WebCSS.Engine := fSynWebEngine; WebCSS.Options.CssVersion := scvCSS3; WebXML := TSynWebXMLSyn.Create(nil); WebXML.Engine := fSynWebEngine; SetCodeRayColors(fSynWebEngine); end; destructor TCatHighlighters.Destroy; begin inherited; end; end.
unit ConnectList; interface uses System.SysUtils, System.Classes, Vcl.Graphics, BCDialogs.Dlg, Vcl.Controls, Vcl.Forms, OdacVcl, Vcl.Dialogs, Vcl.Grids, JvExGrids, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ActnList, Vcl.ImgList, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, Winapi.Windows, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ComCtrls, BCControls.ImageList, System.Actions, VirtualTrees, Vcl.AppEvnts, Ora; type PConnectData = ^TConnectData; TConnectData = record Profile: string; Username: string; Password: string; Database: string; HomeName: string; Host: string; Port: string; SID: string; ServiceName: string; ClientMode: Boolean; end; TConnectListDialog = class(TDialog) ActionManager: TActionManager; ActionToolBar1: TActionToolBar; AddConnectionAction: TAction; BottomPanel: TPanel; CancelButton: TButton; ClientModeRadioButton: TRadioButton; ConnectAction: TAction; ConnectButton: TButton; DirectModeRadioButton: TRadioButton; EditConnectionAction: TAction; ImageList: TBCImageList; Label1: TLabel; ModeClickAction: TAction; RemoveConnectionAction: TAction; Separator1Panel: TPanel; StringGridPanel: TPanel; TopPanel: TPanel; VirtualDrawTree: TVirtualDrawTree; ApplicationEvents: TApplicationEvents; procedure AddConnectionActionExecute(Sender: TObject); procedure ConnectActionExecute(Sender: TObject); procedure EditConnectionActionExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RemoveConnectionActionExecute(Sender: TObject); procedure ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); procedure VirtualDrawTreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); procedure VirtualDrawTreeDblClick(Sender: TObject); procedure VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo); procedure VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); procedure VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer); procedure FormCreate(Sender: TObject); procedure RadioButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FOraSession: TOraSession; function GetConnectString(Data: PConnectData; IncludeHome: Boolean = False): string; procedure ReadIniFile; procedure SetNodeVisibility; procedure WriteConnectionsToIniFile; procedure WriteIniFile; public function Open(OraSession: TOraSession): Boolean; end; function ConnectListDialog(AOwner: TComponent): TConnectListDialog; implementation {$R *.dfm} uses OraError, BigIni, ConnectClient, ConnectDirect, BCCommon.FileUtils, BCCommon.Messages, BCCommon.StringUtils, BCCommon.Lib, Vcl.Themes, System.Types, BCCommon.StyleUtils; const SECTION_CONNECTIONS = 'Connections'; SECTION_CONNECTIONPROFILES = 'ConnectionProfiles'; var FConnectListDialog: TConnectListDialog; function ConnectListDialog(AOwner: TComponent): TConnectListDialog; begin if not Assigned(FConnectListDialog) then FConnectListDialog := TConnectListDialog.Create(AOwner); Result := FConnectListDialog; SetStyledFormSize(Result); end; procedure TConnectListDialog.AddConnectionActionExecute(Sender: TObject); var Node: PVirtualNode; Data: PConnectData; begin if ClientModeRadioButton.Checked then with ConnectClientDialog(Self) do try if Open(True) then begin Node := VirtualDrawTree.AddChild(nil); Data := VirtualDrawTree.GetNodeData(Node); Data.Profile := Profile; Data.Username := Username; Data.Password := Password; Data.Database := Database; Data.HomeName := HomeName; Data.ClientMode := True; end; finally Free; end; if DirectModeRadioButton.Checked then with ConnectDirectDialog(Self) do try if Open(True) then begin Node := VirtualDrawTree.AddChild(nil); Data := VirtualDrawTree.GetNodeData(Node); Data.Profile := Profile; Data.Username := Username; Data.Password := Password; Data.Host := Host; Data.Port := Port; if SID <> '' then Data.SID := SID else Data.ServiceName := ServiceName; Data.ClientMode := False; end; finally Free; end; end; function TConnectListDialog.GetConnectString(Data: PConnectData; IncludeHome: Boolean): string; begin { Direct: Username/password@host:port:sid=sid/sn=service name Client: Username/password@database } Result := System.SysUtils.Format('%s/%s@', [Data.Username, Data.Password]); if Data.ClientMode then begin Result := Result + Data.Database; if IncludeHome then Result := Result + System.SysUtils.Format('^%s', [Data.HomeName]); end else begin Result := Result + System.SysUtils.Format('%s:%s:', [Data.Host, Data.Port]); if Data.SID <> '' then Result := Result + System.SysUtils.Format('sid=%s', [Data.SID]); if Data.ServiceName <> '' then Result := Result + System.SysUtils.Format('sn=%s', [Data.ServiceName]); end; end; procedure TConnectListDialog.ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); var Node: PVirtualNode; begin Node := VirtualDrawTree.GetFirstSelected; ConnectAction.Enabled := Assigned(Node); RemoveConnectionAction.Enabled := ConnectAction.Enabled; EditConnectionAction.Enabled := ConnectAction.Enabled; end; procedure TConnectListDialog.SetNodeVisibility; var i: Integer; Node: PVirtualNode; Data: PConnectData; begin Node := VirtualDrawTree.GetFirst; while Assigned(Node) do begin Data := VirtualDrawTree.GetNodeData(Node); VirtualDrawTree.IsVisible[Node] := ClientModeRadioButton.Checked and Data.ClientMode or DirectModeRadioButton.Checked and not Data.ClientMode; Node := VirtualDrawTree.GetNext(Node); end; if ClientModeRadioButton.Checked then begin for i := 0 to 3 do VirtualDrawTree.Header.Columns[i].Width := VirtualDrawTree.Width div 4; VirtualDrawTree.Header.Columns[3].Options := VirtualDrawTree.Header.Columns[3].Options + [coVisible] end else begin for i := 0 to 2 do VirtualDrawTree.Header.Columns[i].Width := VirtualDrawTree.Width div 3; VirtualDrawTree.Header.Columns[3].Options := VirtualDrawTree.Header.Columns[3].Options - [coVisible]; end; end; procedure TConnectListDialog.RadioButtonClick(Sender: TObject); begin SetNodeVisibility; end; procedure TConnectListDialog.ConnectActionExecute(Sender: TObject); var ConnectString: string; Node: PVirtualNode; Data: PConnectData; begin Node := VirtualDrawTree.GetFirstSelected; Data := VirtualDrawTree.GetNodeData(Node); ConnectString := GetConnectString(Data); if ConnectString <> '' then begin FOraSession.ConnectString := ConnectString; FOraSession.Schema := Data.Username; { What the fuck, Devart?!?!? } FOraSession.Options.Direct := not Data.ClientMode; {FConnectDialog.Session.HomeName := Data.HomeName; FConnectDialog.Session.Username := Data.Username; FConnectDialog.Session.Password := Data.Password; if Data.ClientMode then FConnectDialog.Session.Server := Data.Database else begin FConnectDialog.Session.Server := System.SysUtils.Format('%s:%s:', [Data.Host, Data.Port]); if Data.SID <> '' then FConnectDialog.Session.Server := FConnectDialog.Connection.Server + System.SysUtils.Format('sid=%s', [Data.SID]); if Data.ServiceName <> '' then FConnectDialog.Session.Server := FConnectDialog.Connection.Server + System.SysUtils.Format('sn=%s', [Data.ServiceName]); end; } //try //FOraSession.Connect; //ConnectDialog.Connection.PerformConnect(False); ModalResult := mrOk; {except on E: EOraError do Raise; end;} end; end; procedure TConnectListDialog.ReadIniFile; var i: Integer; s, Temp: string; Connections, ConnectionProfiles: TStrings; Node: PVirtualNode; Data: PConnectData; begin Connections := TStringList.Create; ConnectionProfiles := TStringList.Create; with TBigIniFile.Create(GetINIFilename) do try { Size } Width := ReadInteger('ConnectListSize', 'Width', 444); Height := ReadInteger('ConnectListSize', 'Height', 456); { Position } Left := ReadInteger('ConnectListPosition', 'Left', (Screen.Width - Width) div 2); Top := ReadInteger('ConnectListPosition', 'Top', (Screen.Height - Height) div 2); { Check if the form is outside the workarea } Left := SetFormInsideWorkArea(Left, Width); ReadSectionValues(SECTION_CONNECTIONS, Connections); ReadSectionValues(SECTION_CONNECTIONPROFILES, ConnectionProfiles); {} Node := VirtualDrawTree.GetFirst; while Assigned(Node) do begin VirtualDrawTree.DeleteNode(Node); Node := VirtualDrawTree.GetFirst; end; for i := 0 to Connections.Count - 1 do begin Node := VirtualDrawTree.AddChild(nil); Data := VirtualDrawTree.GetNodeData(Node); s := DecryptString(System.Copy(Connections.Strings[i], Pos('=', Connections.Strings[i]) + 1, Length(Connections.Strings[i]))); { Direct: Username/password@host:port:sid=sid/sn=service name Client: Username/password@database^homename } if i < ConnectionProfiles.Count then Data.Profile := System.Copy(ConnectionProfiles.Strings[i], Pos('=', ConnectionProfiles.Strings[i]) + 1, Length(ConnectionProfiles.Strings[i])); Data.Username := Copy(s, 0, Pos('/', s) - 1); Temp := Copy(s, 0, Pos('@', s) - 1); Data.Password := Copy(Temp, Pos('/', Temp) + 1, Length(Temp)); Data.Database := Copy(s, Pos('@', s) + 1, Length(s)); Data.ClientMode := Pos(':', s) = 0; if Pos('^', Data.Database) <> 0 then // client mode begin Data.HomeName := Copy(Data.Database, Pos('^', Data.Database) + 1, Length(Data.Database)); Data.Database := Copy(Data.Database, 0, Pos('^', Data.Database) - 1); end; if not Data.ClientMode then // direct mode begin Temp := Data.Database; // host:port:sid=sid/sn=service name Data.Host := Copy(Temp, 0, Pos(':', Temp) - 1); Temp := Copy(Temp, Pos(':', Temp) + 1, Length(Temp)); Data.Port := Copy(Temp, 0, Pos(':', Temp) - 1); Temp := Copy(Temp, Pos(':', Temp) + 1, Length(Temp)); if Pos('sid=', Temp) <> 0 then Data.Sid := Copy(Temp, Pos('sid=', Temp) + 4, Length(Temp)); if Pos('sn=', Temp) <> 0 then Data.ServiceName := Copy(Temp, Pos('sn=', Temp) + 3, Length(Temp)); Data.Database := ''; end; end; finally Connections.Free; ConnectionProfiles.Free; Free; end; end; procedure TConnectListDialog.RemoveConnectionActionExecute(Sender: TObject); var Node: PVirtualNode; Data: PConnectData; ConnectionProfile: string; begin Node := VirtualDrawTree.GetFirstSelected; Data := VirtualDrawTree.GetNodeData(Node); ConnectionProfile := ''; if Trim(Data.Profile) <> '' then ConnectionProfile := System.SysUtils.Format(' ''%s''', [Data.Profile]); if AskYesOrNo(System.SysUtils.Format('Remove selected connection%s, are you sure?', [ConnectionProfile])) then VirtualDrawTree.DeleteNode(Node); end; procedure TConnectListDialog.WriteConnectionsToIniFile; var i: Integer; BigIniFile: TBigIniFile; Node: PVirtualNode; Data: PConnectData; begin Node := VirtualDrawTree.GetFirst; BigIniFile := TBigIniFile.Create(GetINIFilename); with BigIniFile do try EraseSection(SECTION_CONNECTIONS); EraseSection(SECTION_CONNECTIONPROFILES); i := 0; while Assigned(Node) do begin Data := VirtualDrawTree.GetNodeData(Node); BigIniFile.WriteString(SECTION_CONNECTIONS, IntToStr(i), EncryptString(GetConnectString(Data, True))); BigIniFile.WriteString(SECTION_CONNECTIONPROFILES, IntToStr(i), Data.Profile); Node := VirtualDrawTree.GetNext(Node); Inc(i); end; finally BigIniFile.Free; end; end; procedure TConnectListDialog.WriteIniFile; var BigIniFile: TBigIniFile; begin BigIniFile := TBigIniFile.Create(GetINIFilename); with BigIniFile do try if Windowstate = wsNormal then begin { Position } WriteInteger('ConnectListPosition', 'Left', Left); WriteInteger('ConnectListPosition', 'Top', Top); { Size } WriteInteger('ConnectListSize', 'Width', Width); WriteInteger('ConnectListSize', 'Height', Height); end; finally BigIniFile.Free; end; end; procedure TConnectListDialog.EditConnectionActionExecute(Sender: TObject); var Node: PVirtualNode; Data: PConnectData; begin Node := VirtualDrawTree.GetFirstSelected; Data := VirtualDrawTree.GetNodeData(Node); if ClientModeRadioButton.Checked then with ConnectClientDialog(Self) do try Profile := Data.Profile; Username := Data.Username; Password := Data.Password; Database := StringReplace(Data.Database, '.WORLD', '', [rfIgnoreCase]); HomeName := Data.HomeName; if Open(False) then begin Data.Profile := Profile; Data.Username := Username; Data.Password := Password; Data.Database := Database; Data.HomeName := HomeName; end; finally Free; end; if DirectModeRadioButton.Checked then with ConnectDirectDialog(Self) do try Profile := Data.Profile; Username := Data.Username; Password := Data.Password; Host := Data.Host; Port := Data.Port; SID := Data.SID; ServiceName := Data.ServiceName; if Open(False) then begin Data.Profile := Profile; Data.Username := Username; Data.Password := Password; Data.Host := Host; Data.Port := Port; Data.SID := SID; Data.ServiceName := ServiceName; end; finally Free; end; end; procedure TConnectListDialog.FormClose(Sender: TObject; var Action: TCloseAction); begin WriteConnectionsToIniFile; WriteIniFile; end; procedure TConnectListDialog.FormCreate(Sender: TObject); begin VirtualDrawTree.NodeDataSize := SizeOf(TConnectData); end; procedure TConnectListDialog.FormDestroy(Sender: TObject); begin FConnectListDialog := nil; end; procedure TConnectListDialog.FormShow(Sender: TObject); begin SetNodeVisibility; end; function TConnectListDialog.Open(OraSession: TOraSession): Boolean; begin FOraSession := OraSession; ReadIniFile; Result := ShowModal = mrOk; end; procedure TConnectListDialog.VirtualDrawTreeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PConnectData; Value1, Value2: string; begin { begin Data1 := VirtualDrawTree.GetNodeData(Node1); Data2 := VirtualDrawTree.GetNodeData(Node2); Result := -1; if not Assigned(Data1) or not Assigned(Data2) then Exit; Result := AnsiCompareText(string(Data1.Profile), string(Data2.Profile)) + AnsiCompareText(string(Data1.Username), string(Data2.Username)); end; } Data1 := VirtualDrawTree.GetNodeData(Node1); Data2 := VirtualDrawTree.GetNodeData(Node2); case Column of 0: begin Value1 := Data1.Profile; Value2 := Data2.Profile; end; 1: begin Value1 := Data1.Username; Value2 := Data2.Username; end; 2: begin Value1 := Data1.Database; Value2 := Data2.Database; end; 3: begin Value1 := Data1.HomeName; Value2 := Data2.HomeName; end; end; if (Value1 = '') or (Value2 = '') then Exit; Result := AnsiCompareText(Value1, Value2); end; procedure TConnectListDialog.VirtualDrawTreeDblClick(Sender: TObject); begin ConnectAction.Execute end; procedure TConnectListDialog.VirtualDrawTreeDrawNode(Sender: TBaseVirtualTree; const PaintInfo: TVTPaintInfo); var Data: PConnectData; S: string; R: TRect; Format: Cardinal; LStyles: TCustomStyleServices; LColor: TColor; begin LStyles := StyleServices; with Sender as TVirtualDrawTree, PaintInfo do begin Data := Sender.GetNodeData(Node); if not Assigned(Data) then Exit; if not LStyles.GetElementColor(LStyles.GetElementDetails(tgCellNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); //get and set the background color Canvas.Brush.Color := LStyles.GetStyleColor(scEdit); Canvas.Font.Color := LColor; if LStyles.Enabled and (vsSelected in PaintInfo.Node.States) then begin Colors.FocusedSelectionColor := LStyles.GetSystemColor(clHighlight); Colors.FocusedSelectionBorderColor := LStyles.GetSystemColor(clHighlight); Colors.UnfocusedSelectionColor := LStyles.GetSystemColor(clHighlight); Colors.UnfocusedSelectionBorderColor := LStyles.GetSystemColor(clHighlight); Canvas.Brush.Color := LStyles.GetSystemColor(clHighlight); Canvas.Font.Color := LStyles.GetStyleFontColor(sfMenuItemTextSelected); end else if not LStyles.Enabled and (vsSelected in PaintInfo.Node.States) then begin Canvas.Brush.Color := clHighlight; Canvas.Font.Color := clHighlightText; end; SetBKMode(Canvas.Handle, TRANSPARENT); R := ContentRect; InflateRect(R, -TextMargin, 0); Dec(R.Right); Dec(R.Bottom); case Column of 0: S := Data.Profile; 1: S := Data.Username; 2: begin if Data.ClientMode then S := Data.Database else begin // host:port:sid=sid/sn=service name S := System.SysUtils.Format('%s:%s:', [Data.Host, Data.Port]); if Data.SID <> '' then S := S + System.SysUtils.Format('sid=%s', [Data.SID]); if Data.ServiceName <> '' then S := S + System.SysUtils.Format('sn=%s', [Data.ServiceName]); end; end; 3: S := Data.Homename; end; if Length(S) > 0 then begin Format := DT_TOP or DT_LEFT or DT_VCENTER or DT_SINGLELINE; DrawText(Canvas.Handle, S, Length(S), R, Format); end; end; end; procedure TConnectListDialog.VirtualDrawTreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode); var Data: PConnectData; begin Data := VirtualDrawTree.GetNodeData(Node); Finalize(Data^); inherited; end; procedure TConnectListDialog.VirtualDrawTreeGetNodeWidth(Sender: TBaseVirtualTree; HintCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; var NodeWidth: Integer); begin NodeWidth := VirtualDrawTree.Width end; initialization if not Assigned(GetClass('TConnectListDialog')) then System.Classes.RegisterClass(TConnectListDialog); end.
unit ClipperMisc; (******************************************************************************* * * * Author : Angus Johnson * * Version : 10.0 (alpha) * * Date : 15 September 2017 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2010-2017 * * * * License: * * Use, modification & distribution is subject to Boost Software License Ver 1. * * http://www.boost.org/LICENSE_1_0.txt * * * *******************************************************************************) {$IFDEF FPC} {$DEFINE INLINING} {$ELSE} {$IF CompilerVersion < 14} Requires Delphi version 6 or above. {$IFEND} {$IF CompilerVersion >= 18} //Delphi 2007 //While Inlining has been supported since D2005, both D2005 and D2006 //have an Inline codegen bug (QC41166) so ignore Inline until D2007. {$DEFINE INLINING} {$IF CompilerVersion >= 25.0} //Delphi XE4+ {$LEGACYIFEND ON} {$IFEND} {$IFEND} {$ENDIF} interface uses SysUtils, Types, Classes, Math, Clipper; function Orientation(const path: TPath): Boolean; overload; function Area(const path: TPath): Double; //PointInPolygon: 0=false; +1=true; -1 when 'pt' is on a polygon edge function PointInPolygon(const pt: TPoint64; const path: TPath): Integer; function Path1ContainsPath2(const Path1, Path2: TPath): Boolean; function PolyTreeToPaths(PolyTree: TPolyTree): TPaths; function GetBounds(const paths: TPaths): TRect64; function ReversePath(const path: TPath): TPath; function ReversePaths(const paths: TPaths): TPaths; implementation //OVERFLOWCHECKS OFF is a necessary workaround for a Delphi compiler bug that very //occasionally reports overflow errors while still returning correct values //eg var A, B: Int64; begin A := -$13456780; B := -$73456789; A := A * B; end; //see https://forums.embarcadero.com/message.jspa?messageID=871444 //nb: this issue was resolved in Delphi 10.2 {$OVERFLOWCHECKS OFF} function Area(const path: TPath): Double; var i, j, cnt: Integer; d: Double; begin Result := 0.0; cnt := Length(path); if (cnt < 3) then Exit; j := cnt - 1; for i := 0 to cnt -1 do begin d := (path[j].X + path[i].X); Result := Result + d * (path[j].Y - path[i].Y); j := i; end; Result := -Result * 0.5; end; //------------------------------------------------------------------------------ function Orientation(const path: TPath): Boolean; begin Result := Area(path) >= 0; end; //------------------------------------------------------------------------------ function ReversePath(const path: TPath): TPath; var i, highI: Integer; begin highI := high(path); SetLength(Result, highI +1); for i := 0 to highI do Result[i] := path[highI - i]; end; //------------------------------------------------------------------------------ function ReversePaths(const paths: TPaths): TPaths; var i, j, highJ: Integer; begin i := length(paths); SetLength(Result, i); for i := 0 to i -1 do begin highJ := high(paths[i]); SetLength(Result[i], highJ+1); for j := 0 to highJ do Result[i][j] := paths[i][highJ - j]; end; end; //------------------------------------------------------------------------------ function GetBounds(const paths: TPaths): TRect64; var i,j: Integer; begin Result := Rect64(High(Int64), High(Int64), Low(Int64), Low(Int64)); for i := 0 to High(paths) do for j := 0 to High(paths[i]) do begin if paths[i][j].X < Result.Left then Result.Left := paths[i][j].X; if paths[i][j].X > Result.Right then Result.Right := paths[i][j].X; if paths[i][j].Y < Result.Top then Result.Top := paths[i][j].Y; if paths[i][j].Y > Result.Bottom then Result.Bottom := paths[i][j].Y; end; if Result.Left > Result.Right then Result := EmptyRect; end; //------------------------------------------------------------------------------ function PointInPolygon(const pt: TPoint64; const path: TPath): Integer; var i, cnt: Integer; d, d2, d3: Double; //nb: Double not cInt to avoid potential overflow errors ip, ipNext: TPoint64; begin Result := 0; cnt := Length(path); if cnt < 3 then Exit; ip := path[0]; for i := 1 to cnt do begin if i < cnt then ipNext := path[i] else ipNext := path[0]; if (ipNext.Y = pt.Y) then begin if (ipNext.X = pt.X) or ((ip.Y = pt.Y) and ((ipNext.X > pt.X) = (ip.X < pt.X))) then begin Result := -1; Exit; end; end; if ((ip.Y < pt.Y) <> (ipNext.Y < pt.Y)) then begin if (ip.X >= pt.X) then begin if (ipNext.X > pt.X) then Result := 1 - Result else begin d2 := (ip.X - pt.X); d3 := (ipNext.X - pt.X); d := d2 * (ipNext.Y - pt.Y) - d3 * (ip.Y - pt.Y); if (d = 0) then begin Result := -1; Exit; end; if ((d > 0) = (ipNext.Y > ip.Y)) then Result := 1 - Result; end; end else begin if (ipNext.X > pt.X) then begin d2 := (ip.X - pt.X); d3 := (ipNext.X - pt.X); d := d2 * (ipNext.Y - pt.Y) - d3 * (ip.Y - pt.Y); if (d = 0) then begin Result := -1; Exit; end; if ((d > 0) = (ipNext.Y > ip.Y)) then Result := 1 - Result; end; end; end; ip := ipNext; end; end; //--------------------------------------------------------------------------- function Path1ContainsPath2(const Path1, Path2: TPath): Boolean; var i: Integer; pt: TPoint64; begin //precondition: Path2 may touch but not intersect Path1. Result := false; if (length(Path1) < 3) or (length(Path2) = 0) then Exit; for i := 0 to high(Path2) do begin pt := Path2[i]; //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon case PointInPolygon(pt, Path1) of 0: Exit; 1: begin Result := true; Exit; end; //else point on line end; end; Result := true; //ie no vertex in Path2 is outside Path1. end; //--------------------------------------------------------------------------- procedure AddPolyNodeToPaths(Poly: TPolyPath; var Paths: TPaths); var i: Integer; begin if (Length(Poly.Path) > 0) then begin i := Length(Paths); SetLength(Paths, i +1); Paths[i] := Poly.Path; end; for i := 0 to Poly.ChildCount - 1 do AddPolyNodeToPaths(Poly.Child[i], Paths); end; //------------------------------------------------------------------------------ function PolyTreeToPaths(PolyTree: TPolyTree): TPaths; begin Result := nil; AddPolyNodeToPaths(PolyTree, Result); end; //------------------------------------------------------------------------------ end.
// // Created by the DataSnap proxy generator. // 15/03/2018 03:22:33 // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminRestClient) private FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; FRelatorioEmpregadosCommand: TDSRestCommand; FRelatorioEmpregadosCommand_Cache: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string; const ARequestFilter: string = ''): string; function ReverseString(Value: string; const ARequestFilter: string = ''): string; function RelatorioEmpregados(out size: Int64; const ARequestFilter: string = ''): TStream; function RelatorioEmpregados_Cache(out size: Int64; const ARequestFilter: string = ''): IDSRestCachedStream; end; const TServerMethods1_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_RelatorioEmpregados: array [0..1] of TDSRestParameterMetaData = ( (Name: 'size'; Direction: 2; DBXType: 18; TypeName: 'Int64'), (Name: ''; Direction: 4; DBXType: 33; TypeName: 'TStream') ); TServerMethods1_RelatorioEmpregados_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'size'; Direction: 2; DBXType: 18; TypeName: 'Int64'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); implementation function TServerMethods1Client.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare(TServerMethods1_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare(TServerMethods1_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.RelatorioEmpregados(out size: Int64; const ARequestFilter: string): TStream; begin if FRelatorioEmpregadosCommand = nil then begin FRelatorioEmpregadosCommand := FConnection.CreateCommand; FRelatorioEmpregadosCommand.RequestType := 'GET'; FRelatorioEmpregadosCommand.Text := 'TServerMethods1.RelatorioEmpregados'; FRelatorioEmpregadosCommand.Prepare(TServerMethods1_RelatorioEmpregados); end; FRelatorioEmpregadosCommand.Execute(ARequestFilter); size := FRelatorioEmpregadosCommand.Parameters[0].Value.GetInt64; Result := FRelatorioEmpregadosCommand.Parameters[1].Value.GetStream(FInstanceOwner); end; function TServerMethods1Client.RelatorioEmpregados_Cache(out size: Int64; const ARequestFilter: string): IDSRestCachedStream; begin if FRelatorioEmpregadosCommand_Cache = nil then begin FRelatorioEmpregadosCommand_Cache := FConnection.CreateCommand; FRelatorioEmpregadosCommand_Cache.RequestType := 'GET'; FRelatorioEmpregadosCommand_Cache.Text := 'TServerMethods1.RelatorioEmpregados'; FRelatorioEmpregadosCommand_Cache.Prepare(TServerMethods1_RelatorioEmpregados_Cache); end; FRelatorioEmpregadosCommand_Cache.ExecuteCache(ARequestFilter); size := FRelatorioEmpregadosCommand_Cache.Parameters[0].Value.GetInt64; Result := TDSRestCachedStream.Create(FRelatorioEmpregadosCommand_Cache.Parameters[1].Value.GetString); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FRelatorioEmpregadosCommand.DisposeOf; FRelatorioEmpregadosCommand_Cache.DisposeOf; inherited; end; end.
unit MD.ColorPalette; interface uses System.SysUtils, System.Classes, FMX.Types, System.UIConsts, FMX.Ani; const MaterialColors: array [0 .. 241] of TIdentMapEntry = ( (Value: Integer($FFFFEBEE); Name: 'claRed50'), (Value: Integer($FFFFCDD2); Name: 'claRed100'), (Value: Integer($FFEF9A9A); Name: 'claRed200'), (Value: Integer($FFE57373); Name: 'claRed300'), (Value: Integer($FFEF5350); Name: 'claRed400'), (Value: Integer($FFF44336); Name: 'claRed500'), (Value: Integer($FFE53935); Name: 'claRed600'), (Value: Integer($FFD32F2F); Name: 'claRed700'), (Value: Integer($FFC62828); Name: 'claRed800'), (Value: Integer($FFB71C1C); Name: 'claRed900'), (Value: Integer($FFFF8A80); Name: 'claRedA100'), (Value: Integer($FFFF5252); Name: 'claRedA200'), (Value: Integer($FFFF1744); Name: 'claRedA400'), (Value: Integer($FFD50000); Name: 'claRedA700'), (Value: Integer($FFFCE4EC); Name: 'claPink50'), (Value: Integer($FFF8BBD0); Name: 'claPink100'), (Value: Integer($FFF48FB1); Name: 'claPink200'), (Value: Integer($FFF06292); Name: 'claPink300'), (Value: Integer($FFEC407A); Name: 'claPink400'), (Value: Integer($FFE91E63); Name: 'claPink500'), (Value: Integer($FFD81B60); Name: 'claPink600'), (Value: Integer($FFC2185B); Name: 'claPink700'), (Value: Integer($FFAD1457); Name: 'claPink800'), (Value: Integer($FF880E4F); Name: 'claPink900'), (Value: Integer($FFFF80AB); Name: 'claPinkA100'), (Value: Integer($FFFF4081); Name: 'claPinkA200'), (Value: Integer($FFF50057); Name: 'claPinkA400'), (Value: Integer($FFC51162); Name: 'claPinkA700'), (Value: Integer($FFF3E5F5); Name: 'claPurple50'), (Value: Integer($FFE1BEE7); Name: 'claPurple100'), (Value: Integer($FFCE93D8); Name: 'claPurple200'), (Value: Integer($FFBA68C8); Name: 'claPurple300'), (Value: Integer($FFAB47BC); Name: 'claPurple400'), (Value: Integer($FF9C27B0); Name: 'claPurple500'), (Value: Integer($FF8E24AA); Name: 'claPurple600'), (Value: Integer($FF7B1FA2); Name: 'claPurple700'), (Value: Integer($FF6A1B9A); Name: 'claPurple800'), (Value: Integer($FF4A148C); Name: 'claPurple900'), (Value: Integer($FFEA80FC); Name: 'claPurpleA100'), (Value: Integer($FFE040FB); Name: 'claPurpleA200'), (Value: Integer($FFD500F9); Name: 'claPurpleA400'), (Value: Integer($FFAA00FF); Name: 'claPurpleA700'), (Value: Integer($FFEDE7F6); Name: 'claDeepPurple50'), (Value: Integer($FFD1C4E9); Name: 'claDeepPurple100'), (Value: Integer($FFB39DDB); Name: 'claDeepPurple200'), (Value: Integer($FF9575CD); Name: 'claDeepPurple300'), (Value: Integer($FF7E57C2); Name: 'claDeepPurple400'), (Value: Integer($FF673AB7); Name: 'claDeepPurple500'), (Value: Integer($FF5E35B1); Name: 'claDeepPurple600'), (Value: Integer($FF512DA8); Name: 'claDeepPurple700'), (Value: Integer($FF4527A0); Name: 'claDeepPurple800'), (Value: Integer($FF311B92); Name: 'claDeepPurple900'), (Value: Integer($FFB388FF); Name: 'claDeepPurpleA100'), (Value: Integer($FF7C4DFF); Name: 'claDeepPurpleA200'), (Value: Integer($FF651FFF); Name: 'claDeepPurpleA400'), (Value: Integer($FF6200EA); Name: 'claDeepPurpleA700'), (Value: Integer($FFE8EAF6); Name: 'claIndigo50'), (Value: Integer($FFC5CAE9); Name: 'claIndigo100'), (Value: Integer($FF9FA8DA); Name: 'claIndigo200'), (Value: Integer($FF7986CB); Name: 'claIndigo300'), (Value: Integer($FF5C6BC0); Name: 'claIndigo400'), (Value: Integer($FF3F51B5); Name: 'claIndigo500'), (Value: Integer($FF3949AB); Name: 'claIndigo600'), (Value: Integer($FF303F9F); Name: 'claIndigo700'), (Value: Integer($FF283593); Name: 'claIndigo800'), (Value: Integer($FF1A237E); Name: 'claIndigo900'), (Value: Integer($FF8C9EFF); Name: 'claIndigoA100'), (Value: Integer($FF536DFE); Name: 'claIndigoA200'), (Value: Integer($FF3D5AFE); Name: 'claIndigoA400'), (Value: Integer($FF304FFE); Name: 'claIndigoA700'), (Value: Integer($FFE3F2FD); Name: 'claBlue50'), (Value: Integer($FFBBDEFB); Name: 'claBlue100'), (Value: Integer($FF90CAF9); Name: 'claBlue200'), (Value: Integer($FF64B5F6); Name: 'claBlue300'), (Value: Integer($FF42A5F5); Name: 'claBlue400'), (Value: Integer($FF2196F3); Name: 'claBlue500'), (Value: Integer($FF1E88E5); Name: 'claBlue600'), (Value: Integer($FF1976D2); Name: 'claBlue700'), (Value: Integer($FF1565C0); Name: 'claBlue800'), (Value: Integer($FF0D47A1); Name: 'claBlue900'), (Value: Integer($FF82B1FF); Name: 'claBlueA100'), (Value: Integer($FF448AFF); Name: 'claBlueA200'), (Value: Integer($FF2979FF); Name: 'claBlueA400'), (Value: Integer($FF2962FF); Name: 'claBlueA700'), (Value: Integer($FFE1F5FE); Name: 'claLightBlue50'), (Value: Integer($FFB3E5FC); Name: 'claLightBlue100'), (Value: Integer($FF81D4FA); Name: 'claLightBlue200'), (Value: Integer($FF4FC3F7); Name: 'claLightBlue300'), (Value: Integer($FF29B6F6); Name: 'claLightBlue400'), (Value: Integer($FF03A9F4); Name: 'claLightBlue500'), (Value: Integer($FF039BE5); Name: 'claLightBlue600'), (Value: Integer($FF0288D1); Name: 'claLightBlue700'), (Value: Integer($FF0277BD); Name: 'claLightBlue800'), (Value: Integer($FF01579B); Name: 'claLightBlue900'), (Value: Integer($FF80D8FF); Name: 'claLightBlueA100'), (Value: Integer($FF40C4FF); Name: 'claLightBlueA200'), (Value: Integer($FF00B0FF); Name: 'claLightBlueA400'), (Value: Integer($FF0091EA); Name: 'claLightBlueA700'), (Value: Integer($FFE0F7FA); Name: 'claCyan50'), (Value: Integer($FFB2EBF2); Name: 'claCyan100'), (Value: Integer($FF80DEEA); Name: 'claCyan200'), (Value: Integer($FF4DD0E1); Name: 'claCyan300'), (Value: Integer($FF26C6DA); Name: 'claCyan400'), (Value: Integer($FF00BCD4); Name: 'claCyan500'), (Value: Integer($FF00ACC1); Name: 'claCyan600'), (Value: Integer($FF0097A7); Name: 'claCyan700'), (Value: Integer($FF00838F); Name: 'claCyan800'), (Value: Integer($FF006064); Name: 'claCyan900'), (Value: Integer($FF84FFFF); Name: 'claCyanA100'), (Value: Integer($FF18FFFF); Name: 'claCyanA200'), (Value: Integer($FF00E5FF); Name: 'claCyanA400'), (Value: Integer($FF00B8D4); Name: 'claCyanA700'), (Value: Integer($FFE0F2F1); Name: 'claTeal50'), (Value: Integer($FFB2DFDB); Name: 'claTeal100'), (Value: Integer($FF80CBC4); Name: 'claTeal200'), (Value: Integer($FF4DB6AC); Name: 'claTeal300'), (Value: Integer($FF26A69A); Name: 'claTeal400'), (Value: Integer($FF009688); Name: 'claTeal500'), (Value: Integer($FF00897B); Name: 'claTeal600'), (Value: Integer($FF00796B); Name: 'claTeal700'), (Value: Integer($FF00695C); Name: 'claTeal800'), (Value: Integer($FF004D40); Name: 'claTeal900'), (Value: Integer($FFA7FFEB); Name: 'claTealA100'), (Value: Integer($FF64FFDA); Name: 'claTealA200'), (Value: Integer($FF1DE9B6); Name: 'claTealA400'), (Value: Integer($FF00BFA5); Name: 'claTealA700'), (Value: Integer($FFE8F5E9); Name: 'claGreen50'), (Value: Integer($FFC8E6C9); Name: 'claGreen100'), (Value: Integer($FFA5D6A7); Name: 'claGreen200'), (Value: Integer($FF81C784); Name: 'claGreen300'), (Value: Integer($FF66BB6A); Name: 'claGreen400'), (Value: Integer($FF4CAF50); Name: 'claGreen500'), (Value: Integer($FF43A047); Name: 'claGreen600'), (Value: Integer($FF388E3C); Name: 'claGreen700'), (Value: Integer($FF2E7D32); Name: 'claGreen800'), (Value: Integer($FF1B5E20); Name: 'claGreen900'), (Value: Integer($FFB9F6CA); Name: 'claGreenA100'), (Value: Integer($FF69F0AE); Name: 'claGreenA200'), (Value: Integer($FF00E676); Name: 'claGreenA400'), (Value: Integer($FF00C853); Name: 'claGreenA700'), (Value: Integer($FFF1F8E9); Name: 'claLightGreen50'), (Value: Integer($FFDCEDC8); Name: 'claLightGreen100'), (Value: Integer($FFC5E1A5); Name: 'claLightGreen200'), (Value: Integer($FFAED581); Name: 'claLightGreen300'), (Value: Integer($FF9CCC65); Name: 'claLightGreen400'), (Value: Integer($FF8BC34A); Name: 'claLightGreen500'), (Value: Integer($FF7CB342); Name: 'claLightGreen600'), (Value: Integer($FF689F38); Name: 'claLightGreen700'), (Value: Integer($FF558B2F); Name: 'claLightGreen800'), (Value: Integer($FF33691E); Name: 'claLightGreen900'), (Value: Integer($FFCCFF90); Name: 'claLightGreenA100'), (Value: Integer($FFB2FF59); Name: 'claLightGreenA200'), (Value: Integer($FF76FF03); Name: 'claLightGreenA400'), (Value: Integer($FF64DD17); Name: 'claLightGreenA700'), (Value: Integer($FFF9FBE7); Name: 'claLime50'), (Value: Integer($FFF0F4C3); Name: 'claLime100'), (Value: Integer($FFE6EE9C); Name: 'claLime200'), (Value: Integer($FFDCE775); Name: 'claLime300'), (Value: Integer($FFD4E157); Name: 'claLime400'), (Value: Integer($FFCDDC39); Name: 'claLime500'), (Value: Integer($FFC0CA33); Name: 'claLime600'), (Value: Integer($FFAFB42B); Name: 'claLime700'), (Value: Integer($FF9E9D24); Name: 'claLime800'), (Value: Integer($FF827717); Name: 'claLime900'), (Value: Integer($FFF4FF81); Name: 'claLimeA100'), (Value: Integer($FFEEFF41); Name: 'claLimeA200'), (Value: Integer($FFC6FF00); Name: 'claLimeA400'), (Value: Integer($FFAEEA00); Name: 'claLimeA700'), (Value: Integer($FFFFFDE7); Name: 'claYellow50'), (Value: Integer($FFFFF9C4); Name: 'claYellow100'), (Value: Integer($FFFFF59D); Name: 'claYellow200'), (Value: Integer($FFFFF176); Name: 'claYellow300'), (Value: Integer($FFFFEE58); Name: 'claYellow400'), (Value: Integer($FFFFEB3B); Name: 'claYellow500'), (Value: Integer($FFFDD835); Name: 'claYellow600'), (Value: Integer($FFFBC02D); Name: 'claYellow700'), (Value: Integer($FFF9A825); Name: 'claYellow800'), (Value: Integer($FFF57F17); Name: 'claYellow900'), (Value: Integer($FFFFFF8D); Name: 'claYellowA100'), (Value: Integer($FFFFFF00); Name: 'claYellowA200'), (Value: Integer($FFFFEA00); Name: 'claYellowA400'), (Value: Integer($FFFFD600); Name: 'claYellowA700'), (Value: Integer($FFFFF8E1); Name: 'claAmber50'), (Value: Integer($FFFFECB3); Name: 'claAmber100'), (Value: Integer($FFFFE082); Name: 'claAmber200'), (Value: Integer($FFFFD54F); Name: 'claAmber300'), (Value: Integer($FFFFCA28); Name: 'claAmber400'), (Value: Integer($FFFFC107); Name: 'claAmber500'), (Value: Integer($FFFFB300); Name: 'claAmber600'), (Value: Integer($FFFFA000); Name: 'claAmber700'), (Value: Integer($FFFF8F00); Name: 'claAmber800'), (Value: Integer($FFFF6F00); Name: 'claAmber900'), (Value: Integer($FFFFE57F); Name: 'claAmberA100'), (Value: Integer($FFFFD740); Name: 'claAmberA200'), (Value: Integer($FFFFC400); Name: 'claAmberA400'), (Value: Integer($FFFFAB00); Name: 'claAmberA700'), (Value: Integer($FFFFF3E0); Name: 'claOrange50'), (Value: Integer($FFFFE0B2); Name: 'claOrange100'), (Value: Integer($FFFFCC80); Name: 'claOrange200'), (Value: Integer($FFFFB74D); Name: 'claOrange300'), (Value: Integer($FFFFA726); Name: 'claOrange400'), (Value: Integer($FFFF9800); Name: 'claOrange500'), (Value: Integer($FFFB8C00); Name: 'claOrange600'), (Value: Integer($FFF57C00); Name: 'claOrange700'), (Value: Integer($FFEF6C00); Name: 'claOrange800'), (Value: Integer($FFE65100); Name: 'claOrange900'), (Value: Integer($FFFFD180); Name: 'claOrangeA100'), (Value: Integer($FFFFAB40); Name: 'claOrangeA200'), (Value: Integer($FFFF9100); Name: 'claOrangeA400'), (Value: Integer($FFFF6D00); Name: 'claOrangeA700'), (Value: Integer($FFEFEBE9); Name: 'claBrown50'), (Value: Integer($FFD7CCC8); Name: 'claBrown100'), (Value: Integer($FFBCAAA4); Name: 'claBrown200'), (Value: Integer($FFA1887F); Name: 'claBrown300'), (Value: Integer($FF8D6E63); Name: 'claBrown400'), (Value: Integer($FF795548); Name: 'claBrown500'), (Value: Integer($FF6D4C41); Name: 'claBrown600'), (Value: Integer($FF5D4037); Name: 'claBrown700'), (Value: Integer($FF4E342E); Name: 'claBrown800'), (Value: Integer($FF3E2723); Name: 'claBrown900'), (Value: Integer($FFFAFAFA); Name: 'claGrey50'), (Value: Integer($FFF5F5F5); Name: 'claGrey100'), (Value: Integer($FFEEEEEE); Name: 'claGrey200'), (Value: Integer($FFE0E0E0); Name: 'claGrey300'), (Value: Integer($FFBDBDBD); Name: 'claGrey400'), (Value: Integer($FF9E9E9E); Name: 'claGrey500'), (Value: Integer($FF757575); Name: 'claGrey600'), (Value: Integer($FF616161); Name: 'claGrey700'), (Value: Integer($FF424242); Name: 'claGrey800'), (Value: Integer($FF212121); Name: 'claGrey900'), (Value: Integer($FFECEFF1); Name: 'claBlueGrey50'), (Value: Integer($FFCFD8DC); Name: 'claBlueGrey100'), (Value: Integer($FFB0BEC5); Name: 'claBlueGrey200'), (Value: Integer($FF90A4AE); Name: 'claBlueGrey300'), (Value: Integer($FF78909C); Name: 'claBlueGrey400'), (Value: Integer($FF607D8B); Name: 'claBlueGrey500'), (Value: Integer($FF546E7A); Name: 'claBlueGrey600'), (Value: Integer($FF455A64); Name: 'claBlueGrey700'), (Value: Integer($FF37474F); Name: 'claBlueGrey800'), (Value: Integer($FF263238); Name: 'claBlueGrey900'), (Value: Integer($FF000000); Name: 'claBlack'), (Value: Integer($FFFFFFFF); Name: 'claWhite') ); type PMaterialColor = ^TMaterialColor; TMaterialColor = type Cardinal; PMaterialColorRec = ^TMaterialColorRec; TMaterialColorMapEntry = record Value: TMaterialColor; Name: string; end; TRTLMaterialColors = class strict private FMaterialColors: array of TMaterialColorMapEntry; procedure GetMaterialColorValuesProc(const AMaterialColorName: string); function GetMaterialColor(AIndex: Integer): TMaterialColorMapEntry; public constructor Create; function Count: Integer; property MaterialColor[Index: Integer]: TMaterialColorMapEntry read GetMaterialColor; end; TMaterialColorRec = record const Alpha = TMaterialColor($FF000000); Red50 = Alpha or TMaterialColor($FFFFEBEE); Red100 = Alpha or TMaterialColor($FFFFCDD2); Red200 = Alpha or TMaterialColor($FFEF9A9A); Red300 = Alpha or TMaterialColor($FFE57373); Red400 = Alpha or TMaterialColor($FFEF5350); Red500 = Alpha or TMaterialColor($FFF44336); Red600 = Alpha or TMaterialColor($FFE53935); Red700 = Alpha or TMaterialColor($FFD32F2F); Red800 = Alpha or TMaterialColor($FFC62828); Red900 = Alpha or TMaterialColor($FFB71C1C); RedA100 = Alpha or TMaterialColor($FFFF8A80); RedA200 = Alpha or TMaterialColor($FFFF5252); RedA400 = Alpha or TMaterialColor($FFFF1744); RedA700 = Alpha or TMaterialColor($FFD50000); Pink50 = Alpha or TMaterialColor($FFFCE4EC); Pink100 = Alpha or TMaterialColor($FFF8BBD0); Pink200 = Alpha or TMaterialColor($FFF48FB1); Pink300 = Alpha or TMaterialColor($FFF06292); Pink400 = Alpha or TMaterialColor($FFEC407A); Pink500 = Alpha or TMaterialColor($FFE91E63); Pink600 = Alpha or TMaterialColor($FFD81B60); Pink700 = Alpha or TMaterialColor($FFC2185B); Pink800 = Alpha or TMaterialColor($FFAD1457); Pink900 = Alpha or TMaterialColor($FF880E4F); PinkA100 = Alpha or TMaterialColor($FFFF80AB); PinkA200 = Alpha or TMaterialColor($FFFF4081); PinkA400 = Alpha or TMaterialColor($FFF50057); PinkA700 = Alpha or TMaterialColor($FFC51162); Purple50 = Alpha or TMaterialColor($FFF3E5F5); Purple100 = Alpha or TMaterialColor($FFE1BEE7); Purple200 = Alpha or TMaterialColor($FFCE93D8); Purple300 = Alpha or TMaterialColor($FFBA68C8); Purple400 = Alpha or TMaterialColor($FFAB47BC); Purple500 = Alpha or TMaterialColor($FF9C27B0); Purple600 = Alpha or TMaterialColor($FF8E24AA); Purple700 = Alpha or TMaterialColor($FF7B1FA2); Purple800 = Alpha or TMaterialColor($FF6A1B9A); Purple900 = Alpha or TMaterialColor($FF4A148C); PurpleA100 = Alpha or TMaterialColor($FFEA80FC); PurpleA200 = Alpha or TMaterialColor($FFE040FB); PurpleA400 = Alpha or TMaterialColor($FFD500F9); PurpleA700 = Alpha or TMaterialColor($FFAA00FF); DeepPurple50 = Alpha or TMaterialColor($FFEDE7F6); DeepPurple100 = Alpha or TMaterialColor($FFD1C4E9); DeepPurple200 = Alpha or TMaterialColor($FFB39DDB); DeepPurple300 = Alpha or TMaterialColor($FF9575CD); DeepPurple400 = Alpha or TMaterialColor($FF7E57C2); DeepPurple500 = Alpha or TMaterialColor($FF673AB7); DeepPurple600 = Alpha or TMaterialColor($FF5E35B1); DeepPurple700 = Alpha or TMaterialColor($FF512DA8); DeepPurple800 = Alpha or TMaterialColor($FF4527A0); DeepPurple900 = Alpha or TMaterialColor($FF311B92); DeepPurpleA100 = Alpha or TMaterialColor($FFB388FF); DeepPurpleA200 = Alpha or TMaterialColor($FF7C4DFF); DeepPurpleA400 = Alpha or TMaterialColor($FF651FFF); DeepPurpleA700 = Alpha or TMaterialColor($FF6200EA); Indigo50 = Alpha or TMaterialColor($FFE8EAF6); Indigo100 = Alpha or TMaterialColor($FFC5CAE9); Indigo200 = Alpha or TMaterialColor($FF9FA8DA); Indigo300 = Alpha or TMaterialColor($FF7986CB); Indigo400 = Alpha or TMaterialColor($FF5C6BC0); Indigo500 = Alpha or TMaterialColor($FF3F51B5); Indigo600 = Alpha or TMaterialColor($FF3949AB); Indigo700 = Alpha or TMaterialColor($FF303F9F); Indigo800 = Alpha or TMaterialColor($FF283593); Indigo900 = Alpha or TMaterialColor($FF1A237E); IndigoA100 = Alpha or TMaterialColor($FF8C9EFF); IndigoA200 = Alpha or TMaterialColor($FF536DFE); IndigoA400 = Alpha or TMaterialColor($FF3D5AFE); IndigoA700 = Alpha or TMaterialColor($FF304FFE); Blue50 = Alpha or TMaterialColor($FFE3F2FD); Blue100 = Alpha or TMaterialColor($FFBBDEFB); Blue200 = Alpha or TMaterialColor($FF90CAF9); Blue300 = Alpha or TMaterialColor($FF64B5F6); Blue400 = Alpha or TMaterialColor($FF42A5F5); Blue500 = Alpha or TMaterialColor($FF2196F3); Blue600 = Alpha or TMaterialColor($FF1E88E5); Blue700 = Alpha or TMaterialColor($FF1976D2); Blue800 = Alpha or TMaterialColor($FF1565C0); Blue900 = Alpha or TMaterialColor($FF0D47A1); BlueA100 = Alpha or TMaterialColor($FF82B1FF); BlueA200 = Alpha or TMaterialColor($FF448AFF); BlueA400 = Alpha or TMaterialColor($FF2979FF); BlueA700 = Alpha or TMaterialColor($FF2962FF); LightBlue50 = Alpha or TMaterialColor($FFE1F5FE); LightBlue100 = Alpha or TMaterialColor($FFB3E5FC); LightBlue200 = Alpha or TMaterialColor($FF81D4FA); LightBlue300 = Alpha or TMaterialColor($FF4FC3F7); LightBlue400 = Alpha or TMaterialColor($FF29B6F6); LightBlue500 = Alpha or TMaterialColor($FF03A9F4); LightBlue600 = Alpha or TMaterialColor($FF039BE5); LightBlue700 = Alpha or TMaterialColor($FF0288D1); LightBlue800 = Alpha or TMaterialColor($FF0277BD); LightBlue900 = Alpha or TMaterialColor($FF01579B); LightBlueA100 = Alpha or TMaterialColor($FF80D8FF); LightBlueA200 = Alpha or TMaterialColor($FF40C4FF); LightBlueA400 = Alpha or TMaterialColor($FF00B0FF); LightBlueA700 = Alpha or TMaterialColor($FF0091EA); Cyan50 = Alpha or TMaterialColor($FFE0F7FA); Cyan100 = Alpha or TMaterialColor($FFB2EBF2); Cyan200 = Alpha or TMaterialColor($FF80DEEA); Cyan300 = Alpha or TMaterialColor($FF4DD0E1); Cyan400 = Alpha or TMaterialColor($FF26C6DA); Cyan500 = Alpha or TMaterialColor($FF00BCD4); Cyan600 = Alpha or TMaterialColor($FF00ACC1); Cyan700 = Alpha or TMaterialColor($FF0097A7); Cyan800 = Alpha or TMaterialColor($FF00838F); Cyan900 = Alpha or TMaterialColor($FF006064); CyanA100 = Alpha or TMaterialColor($FF84FFFF); CyanA200 = Alpha or TMaterialColor($FF18FFFF); CyanA400 = Alpha or TMaterialColor($FF00E5FF); CyanA700 = Alpha or TMaterialColor($FF00B8D4); Teal50 = Alpha or TMaterialColor($FFE0F2F1); Teal100 = Alpha or TMaterialColor($FFB2DFDB); Teal200 = Alpha or TMaterialColor($FF80CBC4); Teal300 = Alpha or TMaterialColor($FF4DB6AC); Teal400 = Alpha or TMaterialColor($FF26A69A); Teal500 = Alpha or TMaterialColor($FF009688); Teal600 = Alpha or TMaterialColor($FF00897B); Teal700 = Alpha or TMaterialColor($FF00796B); Teal800 = Alpha or TMaterialColor($FF00695C); Teal900 = Alpha or TMaterialColor($FF004D40); TealA100 = Alpha or TMaterialColor($FFA7FFEB); TealA200 = Alpha or TMaterialColor($FF64FFDA); TealA400 = Alpha or TMaterialColor($FF1DE9B6); TealA700 = Alpha or TMaterialColor($FF00BFA5); Green50 = Alpha or TMaterialColor($FFE8F5E9); Green100 = Alpha or TMaterialColor($FFC8E6C9); Green200 = Alpha or TMaterialColor($FFA5D6A7); Green300 = Alpha or TMaterialColor($FF81C784); Green400 = Alpha or TMaterialColor($FF66BB6A); Green500 = Alpha or TMaterialColor($FF4CAF50); Green600 = Alpha or TMaterialColor($FF43A047); Green700 = Alpha or TMaterialColor($FF388E3C); Green800 = Alpha or TMaterialColor($FF2E7D32); Green900 = Alpha or TMaterialColor($FF1B5E20); GreenA100 = Alpha or TMaterialColor($FFB9F6CA); GreenA200 = Alpha or TMaterialColor($FF69F0AE); GreenA400 = Alpha or TMaterialColor($FF00E676); GreenA700 = Alpha or TMaterialColor($FF00C853); LightGreen50 = Alpha or TMaterialColor($FFF1F8E9); LightGreen100 = Alpha or TMaterialColor($FFDCEDC8); LightGreen200 = Alpha or TMaterialColor($FFC5E1A5); LightGreen300 = Alpha or TMaterialColor($FFAED581); LightGreen400 = Alpha or TMaterialColor($FF9CCC65); LightGreen500 = Alpha or TMaterialColor($FF8BC34A); LightGreen600 = Alpha or TMaterialColor($FF7CB342); LightGreen700 = Alpha or TMaterialColor($FF689F38); LightGreen800 = Alpha or TMaterialColor($FF558B2F); LightGreen900 = Alpha or TMaterialColor($FF33691E); LightGreenA100 = Alpha or TMaterialColor($FFCCFF90); LightGreenA200 = Alpha or TMaterialColor($FFB2FF59); LightGreenA400 = Alpha or TMaterialColor($FF76FF03); LightGreenA700 = Alpha or TMaterialColor($FF64DD17); Lime50 = Alpha or TMaterialColor($FFF9FBE7); Lime100 = Alpha or TMaterialColor($FFF0F4C3); Lime200 = Alpha or TMaterialColor($FFE6EE9C); Lime300 = Alpha or TMaterialColor($FFDCE775); Lime400 = Alpha or TMaterialColor($FFD4E157); Lime500 = Alpha or TMaterialColor($FFCDDC39); Lime600 = Alpha or TMaterialColor($FFC0CA33); Lime700 = Alpha or TMaterialColor($FFAFB42B); Lime800 = Alpha or TMaterialColor($FF9E9D24); Lime900 = Alpha or TMaterialColor($FF827717); LimeA100 = Alpha or TMaterialColor($FFF4FF81); LimeA200 = Alpha or TMaterialColor($FFEEFF41); LimeA400 = Alpha or TMaterialColor($FFC6FF00); LimeA700 = Alpha or TMaterialColor($FFAEEA00); Yellow50 = Alpha or TMaterialColor($FFFFFDE7); Yellow100 = Alpha or TMaterialColor($FFFFF9C4); Yellow200 = Alpha or TMaterialColor($FFFFF59D); Yellow300 = Alpha or TMaterialColor($FFFFF176); Yellow400 = Alpha or TMaterialColor($FFFFEE58); Yellow500 = Alpha or TMaterialColor($FFFFEB3B); Yellow600 = Alpha or TMaterialColor($FFFDD835); Yellow700 = Alpha or TMaterialColor($FFFBC02D); Yellow800 = Alpha or TMaterialColor($FFF9A825); Yellow900 = Alpha or TMaterialColor($FFF57F17); YellowA100 = Alpha or TMaterialColor($FFFFFF8D); YellowA200 = Alpha or TMaterialColor($FFFFFF00); YellowA400 = Alpha or TMaterialColor($FFFFEA00); YellowA700 = Alpha or TMaterialColor($FFFFD600); Amber50 = Alpha or TMaterialColor($FFFFF8E1); Amber100 = Alpha or TMaterialColor($FFFFECB3); Amber200 = Alpha or TMaterialColor($FFFFE082); Amber300 = Alpha or TMaterialColor($FFFFD54F); Amber400 = Alpha or TMaterialColor($FFFFCA28); Amber500 = Alpha or TMaterialColor($FFFFC107); Amber600 = Alpha or TMaterialColor($FFFFB300); Amber700 = Alpha or TMaterialColor($FFFFA000); Amber800 = Alpha or TMaterialColor($FFFF8F00); Amber900 = Alpha or TMaterialColor($FFFF6F00); AmberA100 = Alpha or TMaterialColor($FFFFE57F); AmberA200 = Alpha or TMaterialColor($FFFFD740); AmberA400 = Alpha or TMaterialColor($FFFFC400); AmberA700 = Alpha or TMaterialColor($FFFFAB00); Orange50 = Alpha or TMaterialColor($FFFFF3E0); Orange100 = Alpha or TMaterialColor($FFFFE0B2); Orange200 = Alpha or TMaterialColor($FFFFCC80); Orange300 = Alpha or TMaterialColor($FFFFB74D); Orange400 = Alpha or TMaterialColor($FFFFA726); Orange500 = Alpha or TMaterialColor($FFFF9800); Orange600 = Alpha or TMaterialColor($FFFB8C00); Orange700 = Alpha or TMaterialColor($FFF57C00); Orange800 = Alpha or TMaterialColor($FFEF6C00); Orange900 = Alpha or TMaterialColor($FFE65100); OrangeA100 = Alpha or TMaterialColor($FFFFD180); OrangeA200 = Alpha or TMaterialColor($FFFFAB40); OrangeA400 = Alpha or TMaterialColor($FFFF9100); OrangeA700 = Alpha or TMaterialColor($FFFF6D00); Brown50 = Alpha or TMaterialColor($FFEFEBE9); Brown100 = Alpha or TMaterialColor($FFD7CCC8); Brown200 = Alpha or TMaterialColor($FFBCAAA4); Brown300 = Alpha or TMaterialColor($FFA1887F); Brown400 = Alpha or TMaterialColor($FF8D6E63); Brown500 = Alpha or TMaterialColor($FF795548); Brown600 = Alpha or TMaterialColor($FF6D4C41); Brown700 = Alpha or TMaterialColor($FF5D4037); Brown800 = Alpha or TMaterialColor($FF4E342E); Brown900 = Alpha or TMaterialColor($FF3E2723); Grey50 = Alpha or TMaterialColor($FFFAFAFA); Grey100 = Alpha or TMaterialColor($FFF5F5F5); Grey200 = Alpha or TMaterialColor($FFEEEEEE); Grey300 = Alpha or TMaterialColor($FFE0E0E0); Grey400 = Alpha or TMaterialColor($FFBDBDBD); Grey500 = Alpha or TMaterialColor($FF9E9E9E); Grey600 = Alpha or TMaterialColor($FF757575); Grey700 = Alpha or TMaterialColor($FF616161); Grey800 = Alpha or TMaterialColor($FF424242); Grey900 = Alpha or TMaterialColor($FF212121); BlueGrey50 = Alpha or TMaterialColor($FFECEFF1); BlueGrey100 = Alpha or TMaterialColor($FFCFD8DC); BlueGrey200 = Alpha or TMaterialColor($FFB0BEC5); BlueGrey300 = Alpha or TMaterialColor($FF90A4AE); BlueGrey400 = Alpha or TMaterialColor($FF78909C); BlueGrey500 = Alpha or TMaterialColor($FF607D8B); BlueGrey600 = Alpha or TMaterialColor($FF546E7A); BlueGrey700 = Alpha or TMaterialColor($FF455A64); BlueGrey800 = Alpha or TMaterialColor($FF37474F); BlueGrey900 = Alpha or TMaterialColor($FF263238); Black = Alpha or TMaterialColor($FF000000); White = Alpha or TMaterialColor($FFFFFFFF); Null = TMaterialColor($00000000); constructor Create(const Color: TMaterialColor); class var ColorToRGB: function(Color: TMaterialColor): Longint; case LongWord of 0: (Color: TMaterialColor); 2: (HiWord, LoWord: Word); 3: {$IFDEF BIGENDIAN} (A, R, G, B: System.Byte); {$ELSE} (B, G, R, A: System.Byte); {$ENDIF} end; TMaterialColors = TMaterialColorRec; var MaterialColorsMap: TRTLMaterialColors; procedure GetMaterialColorValues(Proc: TGetStrProc); function StringToMaterialColor(const Value: string): TMaterialColor; function IdentToMaterialColor(const Ident: string; var MaterialColor: Integer): Boolean; function MaterialColorToIdent(MaterialColor: Integer; var Ident: string): Boolean; function MaterialColorToString(Value: TMaterialColor): string; implementation { TMaterialColorRec } procedure GetMaterialColorValues(Proc: TGetStrProc); var I: Integer; begin for I := Low(MaterialColors) to High(MaterialColors) do Proc(MaterialColorToString(TMaterialColor(MaterialColors[I].Value))); end; function StringToMaterialColor(const Value: string): TMaterialColor; var LValue: string; LMaterialColor: Integer; begin LValue := Value; if LValue = #0 then LValue := '$0' else if (LValue <> '') and ((LValue.Chars[0] = '#') or (LValue.Chars[0] = 'x')) then LValue := '$' + LValue.SubString(1); if (not IdentToMaterialColor('cla' + LValue, LMaterialColor)) and (not IdentToMaterialColor(LValue, LMaterialColor)) then Result := TMaterialColor(StrToInt64(LValue)) else Result := TMaterialColor(LMaterialColor); end; function IdentToMaterialColor(const Ident: string; var MaterialColor: Integer): Boolean; var LIdent: string; begin LIdent := Ident; if (LIdent.Length > 0) and (LIdent.Chars[0] = 'x') then begin MaterialColor := Integer(StringToMaterialColor(LIdent)); Result := True; end else Result := IdentToInt(LIdent, MaterialColor, MaterialColors); // Allow "clXXXX" constants and convert it to TMaterialColor if not Result and (LIdent.Length > 3) then begin LIdent := LIdent.Insert(2, 'a'); Result := IdentToInt(LIdent, Integer(MaterialColor), MaterialColors); end; end; function MaterialColorToIdent(MaterialColor: Integer; var Ident: string): Boolean; begin Result := IntToIdent(MaterialColor, Ident, MaterialColors); if not Result then begin Ident := 'x' + IntToHex(MaterialColor, 8); Result := True; end; end; function MaterialColorToString(Value: TMaterialColor): string; begin MaterialColorToIdent(Integer(Value), Result); if Result.Chars[0] = 'x' then Result := '#' + Result.SubString(1) else Result := Result.Remove(0, 3); end; constructor TMaterialColorRec.Create(const Color: TMaterialColor); begin Self := TMaterialColorRec(Color); end; { TRTLMaterialColors } function TRTLMaterialColors.Count: Integer; begin Result := Length(FMaterialColors); end; constructor TRTLMaterialColors.Create; begin GetMaterialColorValues(GetMaterialColorValuesProc); end; function TRTLMaterialColors.GetMaterialColor(AIndex: Integer): TMaterialColorMapEntry; begin Result := FMaterialColors[AIndex]; end; procedure TRTLMaterialColors.GetMaterialColorValuesProc(const AMaterialColorName: string); var LNewIndex: Integer; begin LNewIndex := Count; SetLength(FMaterialColors, LNewIndex + 1); FMaterialColors[LNewIndex].Name := AMaterialColorName; FMaterialColors[LNewIndex].Value := StringToMaterialColor(AMaterialColorName); end; end.
unit uHtml2MIME; interface uses Classes, SysUtils, uStringHandle, uRandomInfo; type //HTML×ÊÔ´ pHtmlRes = ^THtmlRes; THtmlRes = record FID: string; FFileName: string; end; {$M+} THtml2MIME = class private FText: string; FResList: TList; FFileName: string; FResIndex: Integer; procedure FreeResList; procedure SetText(const Value: string); procedure SetFileName(const Value: string); function GetHtmlText: string; function GetSimpleText: string; procedure AddHtmlRes(const AID, AFileName: string); function NewResID: string; function NewCid(const AResID: string): string; function GetResCount: Integer; function GetHtmlRes(index: Integer): pHtmlRes; public constructor Create; destructor Destroy; override; property ResItem[index: Integer]: pHtmlRes read GetHtmlRes; published property Text: string read FText write SetText; property FileName: string read FFileName write SetFileName; property SimpleText: string read GetSimpleText; property HtmlText: string read GetHtmlText; property ResCount: Integer read GetResCount; end; implementation { THtml2MIME } const CtImageSign = '<Img'; CtImageSrc = 'src="'; CtImgSrcLen = 5; CtEndSrc = '"'; procedure THtml2MIME.AddHtmlRes(const AID, AFileName: string); var p: pHtmlRes; begin New(p); p^.FID := AID; p^.FFileName := AFileName; FResList.Add( p ); end; constructor THtml2MIME.Create; begin Text := ''; FileName := ''; FResList := TList.Create; FResIndex := GetRandomNum(100, 9999); end; destructor THtml2MIME.Destroy; begin FreeResList; FResList.Free; inherited; end; procedure THtml2MIME.FreeResList; var i: integer; begin for i := 0 to FResList.Count - 1 do if Assigned(FResList[i]) then Dispose(FResList[i]); FResList.Clear; end; function THtml2MIME.GetHtmlRes(index: Integer): pHtmlRes; begin if (index < 0) or (index > ResCount) then Result := nil else Result := FResList[index]; end; function THtml2MIME.GetHtmlText: string; var S: string; nImagePos, nImgSrcPos, nEndSrcPos: Integer; strID, strImagePath: string; begin FreeResList; s := Text; nImagePos := SearchSignPositon(S, CtImageSign); while nImagePos > 0 do begin nImgSrcPos := SearchSignPositon(S, CtImageSrc, swFromLeft, nImagePos + 4); if nImgSrcPos <= 0 then Break; nImgSrcPos := nImgSrcPos + CtImgSrcLen; nEndSrcPos := SearchSignPositon(S, CtEndSrc, swFromLeft, nImgSrcPos + 1); if nEndSrcPos <= 0 then Break; strImagePath := Copy(S, nImgSrcPos, nEndSrcPos - nImgSrcPos); if strImagePath = '' then Continue; strID := NewResID; AddHtmlRes( strID, strImagePath ); StringReplace(S, strImagePath, NewCid(strID), swFromLeft, 1); nImagePos := SearchSignPositon(S, CtImageSign, swFromLeft, nImagePos + nEndSrcPos + 1); end; Result := S; end; function THtml2MIME.GetResCount: Integer; begin Result := FResList.Count; end; function THtml2MIME.GetSimpleText: string; begin Result := Text; Result := LoopDeleteString(Result, '<style', '</style>'); Result := LoopDeleteString(Result, '<script', '</script>'); Result := LoopDeleteString(Result, '<', '>'); StringReplace( Result, '&nbsp;', ' '); end; function THtml2MIME.NewCid(const AResID: string): string; begin Result := 'cid: ' + AResID; end; function THtml2MIME.NewResID: string; begin Result := GetRandokmString(8, 15) + IntToStr(FResIndex) + GetRandokmString(5, 12); Inc(FResIndex); end; procedure THtml2MIME.SetFileName(const Value: string); var lt: TStringList; begin if FileExists(Value) and ( CompareText(FFileName, Value) <> 0 ) then begin FFileName := Value; lt := TStringList.Create; try lt.LoadFromFile( FFileName ); Text := lt.Text; finally lt.Free; end; end; end; procedure THtml2MIME.SetText(const Value: string); begin FText := Value; end; end.
unit PageTreeForm; interface uses Forms, PluginManagerIntf, Controls, ExtCtrls, Classes, ComCtrls, cxLookAndFeelPainters, StdCtrls, cxButtons, ActnList, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, ImgList; type TTreeForm = class(TForm) PagesTree: TTreeView; Panel1: TPanel; Panel4: TPanel; OK: TcxButton; Cancel: TcxButton; ActionList: TActionList; ActionOK: TAction; Lang: TcxComboBox; ImageList16: TImageList; StaticText1: TStaticText; cxButton1: TcxButton; procedure ActionOKExecute(Sender: TObject); procedure PagesTreeCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); procedure FormDestroy(Sender: TObject); procedure PagesTreeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); procedure PagesTreeCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); procedure PagesTreeDblClick(Sender: TObject); procedure LangPropertiesChange(Sender: TObject); procedure cxButton1Click(Sender: TObject); private FPluginManager: IPluginManager; FDataPath: String; FOpenDM: Boolean; procedure SetPluginManager(const Value: IPluginManager); function FindNode(AID: Integer): TTreeNode; function IntToStr2(Value, Len: Integer): String; procedure FillTree; procedure FillLanguages; function GetLink: string; public property PluginManager: IPluginManager read FPluginManager write SetPluginManager; property DataPath: String read FDataPath write FDataPath; property Link: string read GetLink; end; function GetTreeForm(const PluginManager: IPluginManager; const DataPath: String; var S: String): Integer; implementation uses PageMangerLib, PageMangerDM, SysUtils, Dialogs, StrUtils; {$R *.dfm} function GetTreeForm; var Form: TTreeForm; begin Form := TTreeForm.Create(Application); try Form.DataPath := DataPath; Form.PluginManager := PluginManager; Result := Form.ShowModal; if Result = mrOK then S := Form.Link; finally Form.Free; end; end; procedure TTreeForm.ActionOKExecute(Sender: TObject); begin OK.SetFocus; ModalResult := mrOK; end; procedure TTreeForm.FillTree; var Node: TNC; PNode: TTreeNode; SaveID, i: Integer; begin SaveID := -1; with PagesTree, Dm.Pages do begin // Сохранение местоположения if Assigned(Selected) then SaveID := TNC(Selected).ID; DisableControls; Items.BeginUpdate; Items.Clear; First; while not EOF do begin // добавление элемента Node := TNC(Items.AddChild(nil, FieldValues['title'])); Node.ID := FieldValues['id']; Node.ParentID := FieldValues['parent_id']; Node.SortOrder := FieldValues['sort_order']; Node.IsDefault := FieldValues['is_default']; Node.DontClick := FieldValues['dont_click']; Node.IsDynamic := FieldValues['is_dynamic']; Node.DontVisible := FieldValues['dont_visible']; Node.Folder := (FieldValues['folder'] = 1); if Node.Folder then begin if Node.ParentID = 0 then Node.ImageIndex := 121 else Node.ImageIndex := 20; end else Node.ImageIndex := 40; Node.SelectedIndex := Node.ImageIndex; Next; end; // пересортировка дерева i := 0; while i < Items.Count do begin Node := TNC(Items[i]); // поиск в дереве родителя PNode := FindNode(Node.ParentID); if (PNode <> nil) and (Node.Parent <> PNode) then begin // сделать детёнком Node.MoveTo(PNode, naAddChild); i := -1; end; Inc(i); end; // конец пересортировки Items.EndUpdate; EnableControls; // возврат на то что было if SaveID > -1 then begin PNode := FindNode(SaveID); if PNode <> nil then begin Selected := PNode; PNode.MakeVisible; end else Selected := Items[0]; end; AlphaSort; end; PagesTree.Refresh; end; procedure TTreeForm.SetPluginManager(const Value: IPluginManager); begin FPluginManager := Value; FOpenDM := not Assigned(DM); if FOpenDM then begin DM := TDM.Create(Self); DM.PluginManager := FPluginManager; DM.DataPath := FDataPath; DM.Open; end; FillLanguages; FillTree; end; procedure TTreeForm.PagesTreeCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); begin NodeClass := TNC; end; function TTreeForm.FindNode(AID: Integer): TTreeNode; var i: Integer; begin Result := nil; for i := 0 to PagesTree.Items.Count - 1 do begin if TNC(PagesTree.Items[i]).ID = AID then begin Result := PagesTree.Items[i]; Exit; end; end; end; procedure TTreeForm.FormDestroy(Sender: TObject); begin if FOpenDM then DM.Free; end; procedure TTreeForm.PagesTreeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean); begin AllowCollapse := Assigned(Node.Parent); end; procedure TTreeForm.PagesTreeCompare(Sender: TObject; Node1, Node2: TTreeNode; Data: Integer; var Compare: Integer); var s1, s2: String; function SortStr(ANode: TTreeNode): String; var Node: TNC; begin Node := TNC(ANode); repeat Result := IntToStr(Integer(not Node.Folder)) + IntToStr2(Node.SortOrder, 4) + Result; Node := TNC(Node.Parent); until Node = nil; end; begin s1 := SortStr(Node1); s2 := SortStr(Node2); Compare := AnsiCompareText(S1, S2); end; function TTreeForm.IntToStr2(Value, Len: Integer): String; var s: String; begin s := IntToStr(Value); Result := StringOfChar('0', Len - Length(s)) + s; end; procedure TTreeForm.PagesTreeDblClick(Sender: TObject); begin ActionOK.Execute; end; procedure TTreeForm.FillLanguages; begin with DM.Languages do begin Lang.Properties.Items.BeginUpdate; Lang.Properties.Items.Clear; First; while not EOF do begin Lang.Properties.Items.Add(FieldValues['title']); Next; end; Lang.Properties.Items.EndUpdate; end; end; procedure TTreeForm.LangPropertiesChange(Sender: TObject); begin DM.SetLanguage(Lang.Text); FillTree; end; procedure TTreeForm.cxButton1Click(Sender: TObject); var s: String; sl: TStringList; i: Integer; begin DM.Pages.Locate('id', TNC(PagesTree.Selected).ID, []); s := DM.GetLocalPath(DM.Pages); s := DM.GetRemotePath(s); sl := TStringList.Create; try sl.Delimiter := '/'; sl.DelimitedText := s; // складываем путь заново for i := 1 to 4 do sl.Delete(0); // первые три элемента sl.Insert(0, 'ru'); if not TNC(PagesTree.Selected).Folder then sl[sl.Count-1] := sl[sl.Count-1] + '.html'; s := '/' + sl.DelimitedText; { if TNC(PagesTree.Selected).Folder then s := s + '/' else s := s + '.html'; } finally sl.Free; end; ShowMessage(s); end; function TTreeForm.GetLink: string; var sl: TStringList; i: Integer; begin DM.Pages.Locate('id', TNC(PagesTree.Selected).ID, []); Result := DM.GetLocalPath(DM.Pages); Result := DM.GetRemotePath(Result); sl := TStringList.Create; try sl.Delimiter := '/'; sl.DelimitedText := Result; // складываем путь заново for i := 1 to 4 do sl.Delete(0); // первые три элемента // sl.Insert(0, 'ru'); Result := '/' + sl.DelimitedText; if not TNC(PagesTree.Selected).Folder then begin Result := Copy(Result, 1, Length(Result) - 1); Result := Result + '.html'; end; finally sl.Free; end; end; end.
unit ConsoleCrt; (* This unit only work with: +Os : Windows +Compiler: Delphi Language that written in: Delphi (RAD studio) +Version: SYdney 10.4 Hope you enjoy <3 *) interface uses System.SysUtils, WinAPI.Windows; //This is constant color code const MedGray=0; LightRed=1; LightGreen=2; LightBlue=3; Yellow=4; Purple=5; Aqua=6; Gray=7; Green=8; Blue=9; Red=10; DarkYellow=11; DarkPurple=12; DarkAqua=13; White=14; Default=15; Black=16; procedure WaitAnyKeyPressed(const TextMessage: string = ''); overload; inline; procedure WaitAnyKeyPressed(TimeDelay: Cardinal; const TextMessage: string = ''); overload; inline; procedure WaitForKeyPressed(KeyCode: Word; const TextMessage: string = ''); overload; inline; procedure WaitForKeyPressed(KeyCode: Word; TimeDelay: Cardinal; const TextMessage: string = ''); overload; procedure TextCl(Code:Byte); procedure TextBk(Code:Byte); procedure GotoXY(x,y: Integer); function WhereY: Integer; function WhereX: Integer; function MaxTermiSize:TCoord; procedure Cls(OptionalCharFill:Char=' '); function TermiSize:_COORD; procedure ResetCl; implementation type TTimer = record Started: TLargeInteger; Frequency: Cardinal; end; var IsElapsed: function(const Timer: TTimer; Interval: Cardinal): Boolean; StartTimer: procedure(var Timer: TTimer); Buffer: _Console_Screen_Buffer_Info; hStdOut:THandle; ConOut: THandle; BufInfo: TConsoleScreenBufferInfo; procedure ResetCl; begin TextCl(Default); end; procedure TextCl(Code:Byte); begin case Code of 0: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE); 1: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_RED or FOREGROUND_INTENSITY); 2: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_GREEN or FOREGROUND_INTENSITY); 3: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_BLUE or FOREGROUND_INTENSITY); 4: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY); 5: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_RED or FOREGROUND_BLUE or FOREGROUND_INTENSITY); 6: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY); 7: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY); 8: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN); 9: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE); 10: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED); 11: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_GREEN or FOREGROUND_RED); 12: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_BLUE or FOREGROUND_RED); 13: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_GREEN or FOREGROUND_BLUE); 14: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY); 15: SetConsoleTextAttribute(ConOut, BufInfo.wAttributes); 16: begin { this is optional so u cant uncomment this } //raise Exception.Create('COLOR CODE FOR BLACK CANNOT APPLIED HERE [0..15], ALL THE COLOR WILL AUTO RESET TO DEFAULT'); ResetCl; end else begin { this is optional so u cant uncomment this } //raise Exception.Create('COLOR CODE OVER THE RANGE [0..15], ALL THE COLOR WILL AUTO RESET TO DEFAULT'); ResetCl; end; end; end; procedure TextBk(Code:Byte); begin case Code of 0: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_RED or BACKGROUND_GREEN or BACKGROUND_BLUE); 1: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_RED or BACKGROUND_INTENSITY); 2: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN or BACKGROUND_INTENSITY); 3: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE or BACKGROUND_INTENSITY); 4: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY); 5: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_RED or BACKGROUND_BLUE or BACKGROUND_INTENSITY); 6: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN or BACKGROUND_BLUE or BACKGROUND_INTENSITY); 7: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY); 8: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_GREEN); 9: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE); 10: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_RED); 11: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN or BACKGROUND_RED); 12: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_BLUE or BACKGROUND_RED); 13: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN or BACKGROUND_BLUE); 14: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),FOREGROUND_RED or FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY); 15: SetConsoleTextAttribute(ConOut, BufInfo.wAttributes); 16: SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),0); else begin { this is optional so u cant uncomment this } //raise Exception.Create('COLOR CODE OVER THE RANGE [0..15], ALL THE COLOR WILL AUTO RESET TO DEFAULT '); ResetCl; end; end; end; function MaxTermiSize:TCoord; var Con: THandle; begin Con := GetStdHandle(STD_OUTPUT_HANDLE); Exit(GetLargestConsoleWindowSize(Con)); end; function WhereX: Integer; begin hStdOut:= GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hStdOut,Buffer); // Result:=Buffer.dwCursorPosition.X; end; function WhereY: Integer; begin hStdOut:= GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hStdOut,Buffer); // Result:=Buffer.dwCursorPosition.Y; end; procedure GotoXY(x,y: Integer); var CursorCoord: _COORD; begin CursorCoord.x := x; CursorCoord.y := y; hStdOut:= GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hStdOut, CursorCoord); end; procedure WaitAnyKeyPressed(const TextMessage: string); begin WaitForKeyPressed(0, 0, TextMessage) end; procedure WaitAnyKeyPressed(TimeDelay: Cardinal; const TextMessage: string); begin WaitForKeyPressed(0, TimeDelay, TextMessage) end; procedure WaitForKeyPressed(KeyCode: Word; const TextMessage: string); begin WaitForKeyPressed(KeyCode, 0, TextMessage) end; function TermiSize:_COORD; var csbi: TConsoleScreenBufferInfo; StdOut:THandle; begin stdout := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(GetConsoleScreenBufferInfo(stdout, csbi)); Exit(csbi.dwSize); end; procedure WaitForKeyPressed(KeyCode: Word; TimeDelay: Cardinal; const TextMessage: string); var Handle: THandle; Buffer: TInputRecord; Counter: Cardinal; Timer: TTimer; begin Handle := GetStdHandle(STD_INPUT_HANDLE); if Handle = 0 then RaiseLastOSError; if not (TextMessage = '') then Write(TextMessage); if not (TimeDelay = 0) then StartTimer(Timer); while True do begin Sleep(0); if not GetNumberOfConsoleInputEvents(Handle, Counter) then RaiseLastOSError; if not (Counter = 0) then begin if not ReadConsoleInput(Handle, Buffer, 1, Counter) then RaiseLastOSError; if (Buffer.EventType = KEY_EVENT) and Buffer.Event.KeyEvent.bKeyDown then if (KeyCode = 0) or (KeyCode = Buffer.Event.KeyEvent.wVirtualKeyCode) then Break end; if not (TimeDelay = 0) and IsElapsed(Timer, TimeDelay) then Break end end; function HardwareIsElapsed(const Timer: TTimer; Interval: Cardinal): Boolean; var Passed: TLargeInteger; begin QueryPerformanceCounter(Passed); Result := (Passed - Timer.Started) div Timer.Frequency > Interval end; procedure HardwareStartTimer(var Timer: TTimer); var Frequency: TLargeInteger; begin QueryPerformanceCounter(Timer.Started); QueryPerformanceFrequency(Frequency); Timer.Frequency := Frequency div 1000 end; function SoftwareIsElapsed(const Timer: TTimer; Interval: Cardinal): Boolean; begin Result := (GetCurrentTime - Cardinal(Timer.Started)) > Interval end; procedure SoftwareStartTimer(var Timer: TTimer); begin PCardinal(@Timer.Started)^ := GetCurrentTime end; procedure Cls(OptionalCharFill:Char=' '); var stdout: THandle; csbi: TConsoleScreenBufferInfo; ConsoleSize: DWORD; NumWritten: DWORD; Origin: TCoord; begin stdout := GetStdHandle(STD_OUTPUT_HANDLE); Win32Check(stdout<>INVALID_HANDLE_VALUE); Win32Check(GetConsoleScreenBufferInfo(stdout, csbi)); ConsoleSize := csbi.dwSize.X * csbi.dwSize.Y; Origin.X := 0; Origin.Y := 0; Win32Check(FillConsoleOutputCharacter(stdout, OptionalCharFill, ConsoleSize, Origin, NumWritten)); Win32Check(FillConsoleOutputAttribute(stdout, csbi.wAttributes, ConsoleSize, Origin, NumWritten)); Win32Check(SetConsoleCursorPosition(stdout, Origin)); end; initialization if QueryPerformanceCounter(PLargeInteger(@@IsElapsed)^) and QueryPerformanceFrequency(PLargeInteger(@@IsElapsed)^) then begin StartTimer := HardwareStartTimer; IsElapsed := HardwareIsElapsed end else begin StartTimer := SoftwareStartTimer; IsElapsed := SoftwareIsElapsed end; //begin init variables ConOut := TTextRec(Output).Handle; GetConsoleScreenBufferInfo(ConOut, BufInfo); end.
unit LogFactory; {$mode objfpc}{$H+} interface uses LogItf; type TLoggerType = (ltFile,ltStream); TLogSingletonFactory = class protected constructor Create; // Заглушка destructor Destroy; override; // Заглушка public class function GetLoggerTypeStr(AType: TLoggerType): string; class function ActivateLog(LogDirPath : String; LogMaxLen : Cardinal =1048576; SaveInterval : Cardinal=1000): ILog; class function GetLoItf : ILog; class procedure SetLogHeader(Header : String); // устанавливает заголовок для каждого файла лога class function SetLoggerType(lgType : TLoggerType): ILog; // изменяет тип логера и возвращает новый интерфейс если логер был ранее активирован class procedure SetLogFormItf(LogFormItf : TLogProc); class procedure DeActivateLog; end; implementation uses LogTools, DateUtils, SysUtils, LogResStrings; var Log : TCustomLogObject; LogHeader : String; LoggerType : TLoggerType; { TLogSingletonFactory } class function TLogSingletonFactory.GetLoggerTypeStr(AType: TLoggerType): string; begin case AType of ltFile: Result:= rsLogFileType; ltStream: Result:= rsLogSteramType; else Result:= rsUnknownType; end; end; class function TLogSingletonFactory.ActivateLog(LogDirPath: String; LogMaxLen : Cardinal; SaveInterval : Cardinal): ILog; begin if not Assigned(Log) then begin case LoggerType of ltFile : Log:= TFileLogObject.Create(nil); ltStream : Log:= TStreamLogObject.Create(nil); end; end; Result:=Log; if Result <> nil then begin Log.LogPath:=LogDirPath; Log.SaveInterval:=SaveInterval; Log.LogMaxLen:=LogMaxLen; // Log.FileHeader:=format(rsHeader, [LogHeader, GetLoggerTypeStr(LoggerType)]); Log.FileHeader:=LogHeader; Log.Active:=True; end; end; class procedure TLogSingletonFactory.DeActivateLog; begin Log.Active:=False; Log:=nil; end; constructor TLogSingletonFactory.Create; begin // заглушка end; destructor TLogSingletonFactory.Destroy; begin // заглушка inherited; end; class procedure TLogSingletonFactory.SetLogFormItf(LogFormItf: TLogProc); begin if not Assigned(Log) then Log:=TFileLogObject.Create(nil); Log.LogFormItf:=LogFormItf; end; class function TLogSingletonFactory.GetLoItf: ILog; begin Result:=Log; end; class procedure TLogSingletonFactory.SetLogHeader(Header: String); begin LogHeader:=Header; if Assigned(Log) then Log.FileHeader:=LogHeader; end; class function TLogSingletonFactory.SetLoggerType(lgType: TLoggerType): ILog; var TempLogDirPath : String; TempSaveInterval : Cardinal; TempLogMaxLen : Cardinal; begin Result:=nil; LoggerType:=lgType; if Log=nil then Exit; TempLogDirPath := Log.LogPath; TempSaveInterval := Log.SaveInterval; TempLogMaxLen := Log.LogMaxLen; DeActivateLog; Result:=ActivateLog(TempLogDirPath,TempLogMaxLen,TempSaveInterval); end; initialization LoggerType:=ltFile; end.
unit uthrImportarDevolucao; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil, clEntregador, clAgentes, clCEPAgentes, Messages, Controls, System.DateUtils; type TCSVDevolucao = record _nossonumero: String; _volumes: String; _cep3: String; _cep: String; end; type thrImportarDevolucao = class(TThread) private { Private declarations } entregador: TEntregador; agentes: TAgente; cep: TCEPAgentes; CSVDevolucao: TCSVDevolucao; protected procedure Execute; override; procedure AtualizaProgress; procedure TerminaProcesso; function TrataLinha(sLinha: String): String; end; implementation { thrImportarDevolucao } uses ufrmDevolucoes, uGlobais, udm; function thrImportarDevolucao.TrataLinha(sLinha: String): String; var iConta: Integer; sLin: String; bFlag: Boolean; begin if Pos('"', sLinha) = 0 then begin Result := sLinha; Exit; end; iConta := 1; bFlag := False; sLin := ''; while sLinha[iConta] >= ' ' do begin if sLinha[iConta] = '"' then begin if bFlag then bFlag := False else bFlag := True; end; if bFlag then begin if sLinha[iConta] = ';' then sLin := sLin + ' ' else sLin := sLin + sLinha[iConta]; end else sLin := sLin + sLinha[iConta]; Inc(iConta); end; Result := sLin; end; procedure thrImportarDevolucao.Execute; var ArquivoCSV: TextFile; Contador, I, LinhasTotal, iRet: Integer; Linha, campo, codigo, sMess, sData: String; d: Real; // Lê Linha e Monta os valores function MontaValor: String; var ValorMontado: String; begin ValorMontado := ''; Inc(I); While Linha[I] >= ' ' do begin If Linha[I] = ';' then // vc pode usar qualquer delimitador ... eu // estou usando o ";" break; ValorMontado := ValorMontado + Linha[I]; Inc(I); end; Result := ValorMontado; end; begin entregador := TEntregador.Create; agentes := TAgente.Create; cep := TCEPAgentes.Create; LinhasTotal := TUtil.NumeroDeLinhasTXT(frmDevolucoes.cxArquivo.Text); // Carregando o arquivo ... AssignFile(ArquivoCSV, frmDevolucoes.cxArquivo.Text); sData := frmDevolucoes.cxData.Text; try Reset(ArquivoCSV); Readln(ArquivoCSV, Linha); if Copy(Linha, 0, 15) <> 'GRADE DE DEVOLU' then begin MessageDlg('Arquivo informado não é da GRADE DE DEVOLUÇÕES PENDENTES.', mtWarning, [mbOK], 0); Abort; end; Readln(ArquivoCSV, Linha); Readln(ArquivoCSV, Linha); Contador := 3; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, Linha); Linha := TrataLinha(Linha); with CSVDevolucao do begin campo := MontaValor; _nossonumero := MontaValor; campo := MontaValor; campo := MontaValor; campo := MontaValor; campo := MontaValor; campo := MontaValor; campo := MontaValor; campo := MontaValor; _volumes := MontaValor; campo := MontaValor; _cep := campo; _cep3 := Copy(campo, 1, 3); end; if cep.getObject(CSVDevolucao._cep3, 'CEP') then begin if (not dm.tbDevolucao.Locate('NUM_NOSSONUMERO', CSVDevolucao._nossonumero, [])) then begin dm.tbDevolucao.Insert; dm.tbDevolucaoCOD_BASE.Value := cep.Agente; if Agente.getObject(IntToStr(cep.Agente), 'CODIGO') then begin dm.tbDevolucaoDES_BASE.Value := Agente.Fantasia; end else begin dm.tbDevolucaoDES_BASE.Value := 'BASE NÃO CADASTRADA'; end; dm.tbDevolucaoDAT_EXPEDICAO.Value := StrToDate(sData); dm.tbDevolucaoNUM_NOSSONUMERO.Value := FormatFloat('00000000000', StrToFloat(CSVDevolucao._nossonumero)); dm.tbDevolucaoNUM_VOLUME.Value := StrToInt(CSVDevolucao._volumes); dm.tbDevolucaoCOD_STATUS.Value := 0; dm.tbDevolucaoDES_CEP.Value := Copy(CSVDevolucao._cep, 1, 5) + '-' + Copy(CSVDevolucao._cep, 6, 3); dm.tbDevolucaoDOM_MARCA.Value := 'S'; dm.tbDevolucao.Post; end; end else begin if (not dm.tbDevolucao.Locate('NUM_NOSSONUMERO', CSVDevolucao._nossonumero, [])) then begin dm.tbDevolucao.Insert; dm.tbDevolucaoCOD_BASE.Value := 0; dm.tbDevolucaoDES_BASE.Value := 'BASE IGNORADA'; dm.tbDevolucaoDAT_EXPEDICAO.Value := StrToDate(sData); dm.tbDevolucaoNUM_NOSSONUMERO.Value := FormatFloat('00000000000', StrToFloat(CSVDevolucao._nossonumero)); dm.tbDevolucaoNUM_VOLUME.Value := StrToInt(CSVDevolucao._volumes); dm.tbDevolucaoCOD_STATUS.Value := 0; dm.tbDevolucaoDES_CEP.Value := Copy(CSVDevolucao._cep, 1, 5) + '-' + Copy(CSVDevolucao._cep, 6, 3); dm.tbDevolucaoDOM_MARCA.Value := 'S'; dm.tbDevolucao.Post; end; end; I := 0; iConta := Contador; iTotal := LinhasTotal; dPosicao := (iConta / iTotal) * 100; Inc(Contador, 1); if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin entregador.Free; cep.Free; agentes.Free; Abort; end; end; finally CloseFile(ArquivoCSV); Synchronize(TerminaProcesso); entregador.Free; cep.Free; agentes.Free; end; end; procedure thrImportarDevolucao.AtualizaProgress; begin frmDevolucoes.cxProgressBar1.Position := dPosicao; frmDevolucoes.cxProgressBar1.Properties.Text := 'Registro ' + IntToStr(iConta) + ' de ' + IntToStr(iTotal); frmDevolucoes.cxProgressBar1.Refresh; end; procedure thrImportarDevolucao.TerminaProcesso; begin frmDevolucoes.cxArquivo.Clear; frmDevolucoes.cxProgressBar1.Properties.Text := ''; frmDevolucoes.cxProgressBar1.Position := 0; frmDevolucoes.cxProgressBar1.Clear; frmDevolucoes.cxProgressBar1.Visible := False; frmDevolucoes.ds3.Enabled := True; frmDevolucoes.actDevolucaoSalvarImportacao.Enabled := True; frmDevolucoes.cxGrid3DBTableView1.ViewData.Expand(True); end; end.
unit PedidosConsulta; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IBDatabase, DB, DBClient, Menus, DBXpress, FMTBcd, SqlExpr, ConsultaSql, Provider, Grids, DBGrids, UDMConexaoDB, Buttons, ExtCtrls, StdCtrls, Mask, PedidosCadastro, ORMUtils, PedidosORM, ConexaoDB; type TFPedidosConsulta = class(TForm) dsPedidos: TDataSource; dspPedidos: TDataSetProvider; sdsPedidos: TSQLDataSet; gridPedidos: TDBGrid; cdsPedidos: TClientDataSet; Panel1: TPanel; btAdicionar: TSpeedButton; btExcluir: TSpeedButton; btRefresh: TSpeedButton; btEditar: TSpeedButton; pnlDivisor: TPanel; grbFiltro: TGroupBox; lbCliente: TLabel; edClienteNome: TEdit; btnFiltrar: TButton; sdsPedidosPEDIDO_ID: TIntegerField; sdsPedidosTIPO_OPERACAO: TStringField; sdsPedidosREFERENCIA: TStringField; sdsPedidosNUMERO_PEDIDO: TStringField; sdsPedidosDATA_EMISSAO: TSQLTimeStampField; sdsPedidosCLIENTE_ID: TIntegerField; sdsPedidosCLIENTE_NOME: TStringField; sdsPedidosVALOR_TOTAL: TFloatField; cdsPedidosPEDIDO_ID: TIntegerField; cdsPedidosTIPO_OPERACAO: TStringField; cdsPedidosREFERENCIA: TStringField; cdsPedidosNUMERO_PEDIDO: TStringField; cdsPedidosDATA_EMISSAO: TSQLTimeStampField; cdsPedidosCLIENTE_ID: TIntegerField; cdsPedidosCLIENTE_NOME: TStringField; cdsPedidosVALOR_TOTAL: TFloatField; cbTipoOperacao: TComboBox; lbTipoOperacao: TLabel; edEmissaoInicial: TMaskEdit; lbEmissaoInicial: TLabel; lbEmissaoFinal: TLabel; edEmissaoFinal: TMaskEdit; edClienteID: TEdit; btBuscaCep: TSpeedButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnFiltrarClick(Sender: TObject); procedure btRefreshClick(Sender: TObject); procedure edClienteIDKeyPress(Sender: TObject; var Key: Char); procedure DateKeyPress(Sender: TObject; var Key: Char); procedure KeyUpPadrao(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btEditarClick(Sender: TObject); procedure btAdicionarClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); procedure btBuscaCepClick(Sender: TObject); procedure edClienteIDExit(Sender: TObject); procedure gridPedidosDblClick(Sender: TObject); private { Private declarations } FiltroSql: TLayoutQuery; procedure CriaSqlQuery; procedure CarregaSql; procedure AplicaFiltro; procedure AtualizaLinhaGrid(pedido: TPedido; acao: TAcao); procedure ValidaCliente(clienteID: Integer); public { Public declarations } end; var FPedidosConsulta: TFPedidosConsulta; implementation uses MyStrUtils, MyDateUtils, Constantes, BuscaRapida; {$R *.dfm} procedure TFPedidosConsulta.FormCreate(Sender: TObject); procedure MontaFiltroPadrao; const tpTodos = 0; begin cbTipoOperacao.ItemIndex := tpTodos; edEmissaoInicial.Text := MaskDate(PrimeiroDiaMes(Now)); edEmissaoFinal.Text := MaskDate(UltimoDiaMes(Now)); end; begin CriaSqlQuery; MontaFiltroPadrao; AplicaFiltro; CarregaSql; end; procedure TFPedidosConsulta.FormClose(Sender: TObject; var Action: TCloseAction); begin Free; end; procedure TFPedidosConsulta.btnFiltrarClick(Sender: TObject); begin AplicaFiltro; CarregaSql; end; procedure TFPedidosConsulta.CriaSqlQuery; begin FiltroSql := TLayoutQuery.Create; FiltroSql.Query := 'SELECT PEDIDO.PEDIDO_ID, ' + 'CASE PEDIDO.TIPO_OPERACAO ' + 'WHEN ''E'' THEN ''Entrada'' ' + 'WHEN ''S'' THEN ''Saída'' ' + 'END TIPO_OPERACAO, ' + 'PEDIDO.REFERENCIA, ' + 'PEDIDO.NUMERO_PEDIDO, ' + 'PEDIDO.DATA_EMISSAO, ' + 'PEDIDO.CLIENTE_ID, ' + 'CLIENTE.NOME CLIENTE_NOME, ' + 'PEDIDO.VALOR_TOTAL ' + 'FROM PEDIDOS PEDIDO ' + 'LEFT JOIN CLIENTES CLIENTE ' + 'ON CLIENTE.CLIENTE_ID = PEDIDO.CLIENTE_ID'; FiltroSql.OrderBy := 'PEDIDO.DATA_EMISSAO, PEDIDO.NUMERO_PEDIDO'; end; procedure TFPedidosConsulta.CarregaSql; begin cdsPedidos.Close; sdsPedidos.CommandText := FiltroSql.SqlQuery; cdsPedidos.Open; TNumericField(cdsPedidos.FieldByName('VALOR_TOTAL')).DisplayFormat := ',0.00;-,0.00'; end; procedure TFPedidosConsulta.AplicaFiltro; const tipoOperacao : array[1..2] of string = ('E','S'); dataVazia = ' / / '; var sqlFiltro: string; begin sqlFiltro := ''; // Filtro por Tipo de Operacao if (cbTipoOperacao.ItemIndex > 0) then sqlFiltro := sqlFiltro + format(' AND PEDIDO.TIPO_OPERACAO = %s', [QuotedStr(tipoOperacao[cbTipoOperacao.ItemIndex])]); // Filtro por Periodo de Emissao if ((edEmissaoInicial.Text <> dataVazia) and (edEmissaoFinal.Text = dataVazia)) then sqlFiltro := sqlFiltro + format(' AND PEDIDO.DATA_EMISSAO > %s', [QuotedStr(AsStrDate(edEmissaoInicial.Text))]) else if ((edEmissaoInicial.Text <> dataVazia) and (edEmissaoFinal.Text <> dataVazia)) then sqlFiltro := sqlFiltro + format(' AND PEDIDO.DATA_EMISSAO BETWEEN %s AND %s', [QuotedStr(AsStrDate(edEmissaoInicial.Text)), QuotedStr(AsStrDate(edEmissaoFinal.Text))]); // Filtro por Cliente if (edClienteID.Text <> '0') then sqlFiltro := sqlFiltro + format(' AND PEDIDO.CLIENTE_ID = %s)', [QuotedStr(edClienteID.Text)]); // Setando Filtro FiltroSql.Conditions := Copy(sqlFiltro, 6, Length(sqlFiltro)); end; procedure TFPedidosConsulta.btRefreshClick(Sender: TObject); begin cdsPedidos.Close; cdsPedidos.Open; end; procedure TFPedidosConsulta.AtualizaLinhaGrid(pedido: TPedido; acao: TAcao); begin if (acao = paInclusao) then begin cdsPedidos.Append; cdsPedidos.FieldByName('PEDIDO_ID').AsInteger := Pedido.PedidoID; end else cdsPedidos.Edit; cdsPedidos.FieldByName('TIPO_OPERACAO').AsString := iif(Pedido.TipoOperacao = 'S', 'Saída', 'Entrada'); cdsPedidos.FieldByName('NUMERO_PEDIDO').AsString := Pedido.NumeroPedido; cdsPedidos.FieldByName('DATA_EMISSAO').AsDateTime := Pedido.DataEmissao; cdsPedidos.FieldByName('REFERENCIA').AsString := Pedido.Referencia; cdsPedidos.FieldByName('CLIENTE_ID').AsInteger := Pedido.ClienteID; cdsPedidos.FieldByName('VALOR_TOTAL').AsFloat := Pedido.ValorTotal; end; procedure TFPedidosConsulta.btEditarClick(Sender: TObject); var pedido: TPedido; begin if PedidosCadastro.AbreCadastro(cdsPedidosPEDIDO_ID.Value, paEdicao, pedido) then AtualizaLinhaGrid(pedido, paEdicao); end; procedure TFPedidosConsulta.btAdicionarClick(Sender: TObject); var pedido: TPedido; begin if PedidosCadastro.AbreCadastro(0, paInclusao, pedido) then AtualizaLinhaGrid(pedido, paInclusao); end; procedure TFPedidosConsulta.btExcluirClick(Sender: TObject); var pedido : TPedido; begin if Application.MessageBox(mensagemConfirmacaoDeExclusao, 'Application.Title', MB_YESNO) = IDYES then begin pedido := TPedido.Create(cdsPedidosPEDIDO_ID.Value); if pedido.Excluir then cdsPedidos.Delete else raise Exception.Create('Não foi possível excluir o registro'); end; end; procedure TFPedidosConsulta.edClienteIDKeyPress(Sender: TObject; var Key: Char); begin if not (Key in [#8, '0'..'9']) then begin Key := #0; end; end; procedure TFPedidosConsulta.DateKeyPress(Sender: TObject; var Key: Char); begin if (Key = #32) then TMaskEdit(Sender).Text := MaskDate(now); end; procedure TFPedidosConsulta.KeyUpPadrao(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_RETURN) then begin Perform(CM_DIALOGKEY, VK_TAB, 0); Key := 0; end; end; procedure TFPedidosConsulta.btBuscaCepClick(Sender: TObject); var buscaRapida: TBuscaRapida; begin buscaRapida := TBuscaRapida.Create; buscaRapida.tabela := 'CLIENTES'; buscaRapida.ColunaCodigoNome := 'CLIENTE_ID'; buscaRapida.colunaCodigoTitulo := 'Código'; buscaRapida.colunaDescricaoNome := 'NOME'; buscaRapida.colunaDescricaoTitulo := 'Nome'; if buscaRapida.Execute then begin edClienteID.Text := IntToStr(buscaRapida.ValorID); edClienteNome.Text := buscaRapida.ValorDescricao; end; end; procedure TFPedidosConsulta.ValidaCliente(clienteID: Integer); begin with TSQLQuery.Create(nil) do begin SQLConnection := SimpleCrudSQLConnection; try SQL.Clear; SQL.Add('SELECT CLIENTES.NOME'); SQL.Add('FROM CLIENTES'); SQL.Add('WHERE CLIENTES.CLIENTE_ID = :CLIENTE_ID '); ParamByName('CLIENTE_ID').AsInteger := clienteID; Open; if (not eof) then edClienteNome.Text := FieldByName('NOME').AsString else edClienteNome.Text := 'Cliente não encontrado' finally Free; end; end; end; procedure TFPedidosConsulta.edClienteIDExit(Sender: TObject); begin ValidaCliente(StrToInt(edClienteID.Text)); end; procedure TFPedidosConsulta.gridPedidosDblClick(Sender: TObject); begin btEditar.Click; end; end.
unit U_IOManager; interface type IOManager = class(TObject) private public function readFromFile(filePath: string): string; function writeToFile(filePath: string; outText: string): boolean; end; implementation uses SysUtils; { IOManager } { IOManager } function IOManager.readFromFile(filePath: string): string; var input: TextFile; text: string; begin AssignFile(input, filePath); reset(input); Result := ''; while not Eof(input) do begin ReadLn(input, text); Result := Result + ' ' + text; end; CloseFile(input); end; function IOManager.writeToFile(filePath: string; outText: string): boolean; var output: TextFile; begin try AssignFile(output, filePath); rewrite(output); writeln(output, outText); CloseFile(output); Result := true; except Result := false; end; end; end.
unit WeightRecord; interface uses SysUtils, Variants, Dialogs, ADODB, IdURI; type TWeightRecord = class private public id: Integer; glideNo: string; carNo: string; weightType: string; faHuo: string; shouHuo: string; goods: string; spec: string; gross: Double; tare: Double; net: Double; bundle: Double; real: Double; price: Double; sum: Double; scale: Double; quanter: Double; cost: Double; grossMan: string; tareMan: string; grossAddr: string; tareAddr: string; grossTime: TDateTime; tareTime: TDateTime; firstTime: TDateTime; secondTime: TDateTime; updateUser: string; updateTime: TDateTime; memo: string; printCount: Integer; upload: Boolean; backup1: string; backup2: string; backup3: string; backup4: string; backup5: string; backup6: Double; backup7: Double; backup8: Double; backup9: Double; backup10: string; backup11: string; backup12: string; backup13: string; backup14: string; backup15: Double; backup16: Double; backup17: Double; backup18: Double; function toString(): string; function toJsonString(): string; function toEncodeJsonString(): string; end; TWeightRecordUtil = class private public class function get(glideNo: string; var w: TWeightRecord): Boolean; end; implementation uses Classes, CommonUtil, UploadCloud, superobject; { TWeightUtil } class function TWeightRecordUtil.get(glideNo: string; var w: TWeightRecord): Boolean; var adoq: TADOQuery; begin Result := False; adoq := TADOQuery.Create(nil); try adoq.Connection := UploadCloudForm.ADOCLocal; with adoq do begin Close; SQL.Text := 'select * from 称重信息 where 流水号=:glideNo'; Parameters.ParamByName('glideNo').Value := glideNo; Open; if not IsEmpty then begin w.id := FieldByName('序号').AsInteger; w.glideNo := FieldByName('流水号').AsString; w.carNo := FieldByName('车号').AsString; w.weightType := FieldByName('过磅类型').AsString; w.faHuo := FieldByName('发货单位').AsString; w.shouHuo := FieldByName('收货单位').AsString; w.goods := FieldByName('货名').AsString; w.spec := FieldByName('规格').AsString; w.grossMan := FieldByName('毛重司磅员').AsString; w.tareMan := FieldByName('皮重司磅员').AsString; w.grossAddr := FieldByName('毛重磅号').AsString; w.tareAddr := FieldByName('皮重磅号').AsString; if not FieldByName('毛重时间').IsNull then w.grossTime := FieldByName('毛重时间').AsDateTime; if not FieldByName('皮重时间').IsNull then w.tareTime := FieldByName('皮重时间').AsDateTime; w.gross := FieldByName('毛重').AsFloat; w.tare := FieldByName('皮重').AsFloat; w.net := FieldByName('净重').AsFloat; w.bundle := FieldByName('扣重').AsFloat; w.real := FieldByName('实重').AsFloat; w.price := FieldByName('单价').AsFloat; w.sum := FieldByName('金额').AsFloat; w.scale := FieldByName('折方系数').AsFloat; w.quanter := FieldByName('方量').AsFloat; w.cost := FieldByName('过磅费').AsFloat; w.firstTime := FieldByName('一次过磅时间').AsDateTime; w.secondTime := FieldByName('二次过磅时间').AsDateTime; w.updateUser := FieldByName('更新人').AsString; w.updateTime := FieldByName('更新时间').AsDateTime; w.memo := FieldByName('备注').AsString; w.printCount := FieldByName('打印次数').AsInteger; w.upload := FieldByName('上传否').AsBoolean; w.backup1 := FieldByName('备用1').AsString; w.backup2 := FieldByName('备用2').AsString; w.backup3 := FieldByName('备用3').AsString; w.backup4 := FieldByName('备用4').AsString; w.backup5 := FieldByName('备用5').AsString; w.backup6 := FieldByName('备用6').AsFloat; w.backup7 := FieldByName('备用7').AsFloat; w.backup8 := FieldByName('备用8').AsFloat; w.backup9 := FieldByName('备用9').AsFloat; w.backup10 := FieldByName('备用10').AsString; w.backup11 := FieldByName('备用11').AsString; w.backup12 := FieldByName('备用12').AsString; w.backup13 := FieldByName('备用13').AsString; w.backup14 := FieldByName('备用14').AsString; w.backup15 := FieldByName('备用15').AsFloat; w.backup16 := FieldByName('备用16').AsFloat; w.backup17 := FieldByName('备用17').AsFloat; w.backup18 := FieldByName('备用18').AsFloat; Result := True; end; end; finally adoq.Free; end; end; { TWeightRecord } function TWeightRecord.toEncodeJsonString: string; begin Result := TCommonUtil.base64(toJsonString); end; function TWeightRecord.toJsonString: string; var jo: ISuperObject; begin jo := TSuperObject.Create(); jo.I['id'] := id; jo.S['glideNo'] := glideNo; jo.S['carNo'] := carNo; jo.S['weightType'] := weightType; jo.S['faHuo'] := faHuo; jo.S['shouHuo'] := shouHuo; jo.S['goods'] := goods; jo.S['spec'] := spec; jo.S['gross'] := FloatToStr(gross); jo.S['tare'] := FloatToStr(tare); jo.S['net'] := FloatToStr(net); jo.S['bundle'] := FloatToStr(bundle); jo.S['real'] := FloatToStr(real); jo.S['price'] := FloatToStr(price); jo.S['sum'] := FloatToStr(sum); jo.S['scale'] := FloatToStr(scale); jo.S['quanter'] := FloatToStr(quanter); jo.S['cost'] := FloatToStr(cost); jo.S['grossMan'] := grossMan; jo.S['tareMan'] := tareMan; jo.S['grossAddr'] := grossAddr; jo.S['tareAddr'] := tareAddr; jo.S['grossTime'] := FormatDateTime('yyyy-MM-dd HH:mm:ss',grossTime); jo.S['tareTime'] := FormatDateTime('yyyy-MM-dd HH:mm:ss',tareTime); jo.S['firstTime'] := FormatDateTime('yyyy-MM-dd HH:mm:ss',firstTime); jo.S['secondTime'] := FormatDateTime('yyyy-MM-dd HH:mm:ss',secondTime); jo.S['updateUser'] := updateUser; jo.S['updateTime'] := FormatDateTime('yyyy-MM-dd HH:mm:ss',updateTime); jo.S['memo'] := memo; jo.I['printCount'] := printCount; jo.B['upload'] := upload; jo.S['backup1'] := backup1; jo.S['backup2'] := backup2; jo.S['backup3'] := backup3; jo.S['backup4'] := backup4; jo.S['backup5'] := backup5; jo.S['backup6'] := FloatToStr(backup6); jo.S['backup7'] := FloatToStr(backup7); jo.S['backup8'] := FloatToStr(backup8); jo.S['backup9'] := FloatToStr(backup9); jo.S['backup10'] := backup10; jo.S['backup11'] := backup11; jo.S['backup12'] := backup12; jo.S['backup13'] := backup13; jo.S['backup14'] := backup14; jo.S['backup15'] := FloatToStr(backup15); jo.S['backup16'] := FloatToStr(backup16); jo.S['backup17'] := FloatToStr(backup17); jo.S['backup18'] := FloatToStr(backup18); Result := jo.AsJSon(True); {Result := '{' + Format('''id'':%d,', [id]) + Format('''glideNo'':''%s'',', [glideNo]) + Format('''carNo'':''%s'',', [carNo]) + Format('''weightType'':''%s'',', [weightType]) + Format('''faHuo'':''%s'',', [faHuo]) + Format('''shouHuo'':''%s'',', [shouHuo]) + Format('''goods'':''%s'',', [goods]) + Format('''spec'':''%s'',', [spec]) + Format('''gross'':%f,', [gross]) + Format('''tare'':%f,', [tare]) + Format('''net'':%f,', [net]) + Format('''bundle'':%f,', [bundle]) + Format('''real'':%f,', [real]) + Format('''price'':%f,', [price]) + Format('''sum'':%f,', [sum]) + Format('''scale'':%f,', [scale]) + Format('''quanter'':%f,', [quanter]) + Format('''cost'':%f,', [cost]) + Format('''grossMan'':''%s'',', [grossMan]) + Format('''tareMan'':''%s'',', [tareMan]) + Format('''grossAddr'':''%s'',', [grossAddr]) + Format('''tareAddr'':''%s'',', [tareAddr]) + Format('''grossTime'':''%s'',', [FormatDateTime('yyyy-MM-dd HH:mm:ss', grossTime)]) + Format('''tareTime'':''%s'',', [FormatDateTime('yyyy-MM-dd HH:mm:ss', tareTime)]) + Format('''firstTime'':''%s'',', [FormatDateTime('yyyy-MM-dd HH:mm:ss', firstTime)]) + Format('''secondTime'':''%s'',', [FormatDateTime('yyyy-MM-dd HH:mm:ss', secondTime)]) + Format('''updateUser'':''%s'',', [updateUser]) + Format('''updateTime'':''%s'',', [FormatDateTime('yyyy-MM-dd HH:mm:ss', updateTime)]) + Format('''memo'':''%s'',', [memo]) + Format('''printCount'':%d,', [printCount]) + Format('''upload'':%s,', [LowerCase(BoolToStr(upload, True))]) + Format('''backup1'':''%s'',', [backup1]) + Format('''backup2'':''%s'',', [backup2]) + Format('''backup3'':''%s'',', [backup3]) + Format('''backup4'':''%s'',', [backup4]) + Format('''backup5'':''%s'',', [backup5]) + Format('''backup6'':%f,', [backup6]) + Format('''backup7'':%f,', [backup7]) + Format('''backup8'':%f,', [backup8]) + Format('''backup9'':%f,', [backup9]) + Format('''backup10'':''%s'',', [backup10]) + Format('''backup11'':''%s'',', [backup11]) + Format('''backup12'':''%s'',', [backup12]) + Format('''backup13'':''%s'',', [backup13]) + Format('''backup14'':''%s'',', [backup14]) + Format('''backup15'':%f,', [backup15]) + Format('''backup16'':%f,', [backup16]) + Format('''backup17'':%f,', [backup17]) + Format('''backup18'':%f', [backup18]) }// + '}'; end; function TWeightRecord.toString: string; var s: string; begin s := s + glideNo + ',' + carNo + ',' + faHuo + ',' + shouHuo + ',' + goods + ',' + spec + ',' + FloatToStr(gross) + ',' + FloatToStr(tare) + ',' + FloatToStr(net) + ',' + FloatToStr(bundle) + ',' + FloatToStr(real) + ',' + FloatToStr(price) + ',' + FloatToStr(sum) + ',' + FloatToStr(scale) + ',' + FloatToStr(quanter) + ',' + FloatToStr(cost) + ',' + grossMan + ',' + tareMan + ',' + grossAddr + ',' + tareAddr + ',' + memo + ',' + backup1 + ',' + backup2 + ',' + backup3 + ',' + backup4 + ',' + backup5 + ',' + FloatToStr(backup6) + ',' + FloatToStr(backup7) + ',' + FloatToStr(backup8) + ',' + FloatToStr(backup9) + ',' + backup10 + ',' + backup11 + ',' + backup12 + ',' + backup13 + ',' + backup14 + ',' + FloatToStr(backup15) + ',' + FloatToStr(backup16) + ',' + FloatToStr(backup17) + ',' + FloatToStr(backup18); Result := s; end; end.
unit ucLogFileAnsi; (* Permission is hereby granted, on 18-Jul-2017, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) interface {$I hrefdefines.inc} uses {$IFDEF MSWINDOWS} Windows, {$ELSE} !! requires Windows API !! {$ENDIF} SysUtils, Classes, ucString; // ---- replace/output to a file // AnsiString variations procedure StringAnsiWriteToFile(const AFileName: string; const AText: AnsiString); procedure StringAnsiAppendToFile(const AFileName: string; const AText: AnsiString); procedure AppendLine(const AFileName: string; const AText: AnsiString); procedure StringWriteToStream(AStream: TStream; const AText: AnsiString); function StringLoadFromStream(AStream: TStream): AnsiString; function StringAnsiLoadFromFile(const AFilespec: string): AnsiString; implementation uses WideStrUtils, // NB: IOUtils with TFile.OpenRead is NOT used because it does not read files // when they are open in any other process, even readonly in another text editor ZM_CodeSiteInterface, ZM_LoggingBase, ZM_UTF8StringUtils; procedure AppendLine(const AFileName: string; const AText: AnsiString); //const cFn = 'AppendLine_w_AnsiString'; begin //CSEnterMethod(nil, cFn); StringAnsiAppendToFile(AFileName, AText + sLineBreak); //CSExitMethod(nil, cFn); end; procedure StringAnsiAppendToFile(const AFileName: string; const AText: AnsiString); overload; {$IFDEF LogUcLog}const cFn = 'StringAnsiAppendToFile';{$ENDIF} var AStream: TStream; begin {$IFDEF LogUcLog}CSEnterMethod(nil, cFn); CSSend('AText', ConvAto16(AText));{$ENDIF} AStream := nil; try if FileExists(AFileName) then AStream := TFileStream.Create(AFileName, fmOpenWrite or fmShareDenyWrite) else begin AStream := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite); end; AStream.Seek(0, soEnd); AStream.Write(AText[1], Length(AText)); finally FreeAndNil(AStream); end; {$IFDEF LogUcLog}CSExitMethod(nil, cFn);{$ENDIF} end; procedure StringAppendToFile(const AFileName: string; const AText: UnicodeString); overload; {$IFDEF LogUcLog}const cFn = 'StringAppendToFile_UnicodeString';{$ENDIF} var AStream: TStream; begin {$IFDEF LogUcLog}CSEnterMethod(nil, cFn); CSSend('AText', AText); {$ENDIF} {Alternative syntax in recent Delphi: TFile.AppendAllText(AFileName, AText, TEncoding.Ansi); // uses IOUtils } AStream := nil; try if FileExists(AFileName) then AStream := TFileStream.Create(AFileName, fmOpenWrite or fmShareDenyWrite) else begin AStream := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite); AStream.WriteBuffer(UTF16BOM, Length(UTF16BOM)); end; AStream.Seek(0, soEnd); AStream.Write(AText[1], Length(AText) * SizeOf(WideChar)); finally FreeAndNil(AStream); end; {$IFDEF LogUcLog}CSExitMethod(nil, cFn);{$ENDIF} end; procedure StringAnsiWriteToFile(const AFileName: string; const AText: AnsiString); begin DeleteFile(AFileName); StringAnsiAppendToFile(AFileName, AText); end; function StringLoadFromStream(AStream: TStream): AnsiString; // const cFn = StringLoadFromStream; var ASize: Integer; begin ASize := AStream.Size - AStream.Position; SetLength(Result, ASize); AStream.Read(Result[1], Integer(ASize)); end; function StringAnsiLoadFromFile(const AFilespec: string): AnsiString; var AStream: TFileStream; begin AStream := nil; try AStream := TFileStream.Create(AFilespec, fmOpenRead or fmShareDenyWrite); Result := StringLoadFromStream(AStream); finally FreeAndNil(AStream); end; end; procedure StringWriteToStream(AStream: TStream; const AText: AnsiString); begin AStream.WriteBuffer(AText[1], Length(AText)); end; // initialization // finalization {none} end.
{$include kode.inc} unit syn_simple_voice; { control: 0 - waveform 1 - amplitude 2 - attack 3 - release 4 - pitch } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_phase, kode_osc_naive, kode_osc_druttis, kode_filter_rc, kode_voice; const o1_ampl_start = 0; type KVoiceSimple1 = class(KVoice) private //o1_wave : LongInt; wave_type1 : LongInt; o1_ampl : Single; o1_att : Single; o1_rel : Single; o1_pitch : Single; //osc1 : KOsc_Naive; ph1 : KPhase; att1 : KFilter_RC; rel1 : KFilter_RC; public constructor create; destructor destroy; override; procedure on_setSampleRate(ARate: Single); override; procedure on_noteOn(ANote, AVel: Single); override; procedure on_noteOff(ANote, AVel: Single); override; //procedure on_control(AIndex: LongInt; AVal: Single); override; procedure on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); override; procedure on_process(outs: PSingle); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses Math, kode_const, kode_debug, kode_flags, kode_math; //---------- constructor KVoiceSimple1.create; begin inherited; ph1 := KPhase.create; att1 := KFilter_RC.create; rel1 := KFilter_RC.create; //osc1.setup(osc_type_ramp ,0,0); ph1.setPhase(0); ph1.setPhaseAdd(0); //att1.setup(0,1,0); att1.setValue(0); att1.setTarget(1); att1.setWeight(0); //rel1.setup(0,0,0); rel1.setValue(0); rel1.setTarget(0); rel1.setWeight(0); end; //---------- destructor KVoiceSimple1.destroy; begin ph1.destroy; att1.destroy; rel1.destroy; inherited; end; //---------- procedure KVoiceSimple1.on_setSampleRate(ARate: Single); begin ph1.setSampleRate(ARate); KOsc_Druttis_setSampleRate(ARate); end; //---------- procedure KVoiceSimple1.on_noteOn(ANote, AVel: Single); var vel : Single; fr1 : single; begin fr1 := 440 * power(2.0,(ANote-69.0+o1_pitch) / 12); //osc1._type := wave_type1; ph1.setFrequency(fr1); vel := Single(AVel) * KODE_INV127; att1.setValue(o1_ampl_start); att1.setTarget(vel);; att1.setWeight(o1_att); // fade up rel1.setValue(1); // initially, set to full on rel1.setWeight(0); // fade speed = 0 (until note off) end; //---------- procedure KVoiceSimple1.on_noteOff(ANote, AVel: Single); begin rel1.setValue(att1.getValue); // start from current amplitude rel1.setWeight(o1_rel); // and let it fade down end; //---------- //procedure KVoiceSimple1.on_control(AIndex: LongInt; AVal: Single); procedure KVoiceSimple1.on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); begin case AIndex of 0: wave_type1 := trunc(AVal); 1: o1_ampl := AVal*AVal*AVal; 2: o1_att := 1 / ((AVal*AVal*AVal)+KODE_TINY); 3: o1_rel := 1 / ((AVal*AVal*AVal)+KODE_TINY); 4: o1_pitch := AVal; end; end; //---------- procedure KVoiceSimple1.on_process(outs: PSingle); var ph : single; o1 : single; a1 : Single; r1 : single; begin //KTrace('.'); o1 := ph1.process; o1 := KOsc_Pulse_Druttis( o1, 1, 0 {ps}, 0 {fm}, 0 {fb}, 0 {pm}, 0.3 {pw} ); a1 := att1.process; r1 := rel1.process; if r1 < KODE_TINY then FState := kvs_off; outs[0] := o1*a1*r1*o1_ampl; outs[1] := o1*a1*r1*o1_ampl; end; //---------------------------------------------------------------------- end.
Program CubeRot; { Testing 2D/3D Demo -- Cube Rotation } { The Original Code was made by fh94.3 (C) 12/23/1995 } { I just modified and optimized it to work in all Vesa modes. The final use } { of this code is just to demonstrate my VESA unit. } { Fernando J.A. Silva ( ^Magico^ ) 13/Oct/1997 } Uses Crt, Vbe20; Const Cube : Array [0..23] OF Real = { 8 points * 3 coords(X,Y,Z) = 24 numbers } (-1,-1,-1, -1,-1, 1, -1, 1,-1, -1, 1, 1, 1,-1,-1, 1,-1, 1, 1, 1,-1, 1, 1, 1); { Coords of the objects (like } { point1_x, point1_y, point1_z, point2_x, point2_y, ...) } LineIndex : Array [0..23] OF Integer = { 12 lines * 2 points per line = } { = 24 numbers } (0,1, 0,4, 0,2, 1,3, 1,5, 2,3, 2,6, 3,7, 4,5, 4,6, 5,7, 6,7); { Index of the lines, it } { sets how the points are connected together (point #0 to point #1, ...) } Var Xt, Yt, Zt : Real; { Temp Points } Xan, Yan, Zan : Real; { Angles for axis X,Y,Z } sX,sY,sX1,sY1, P, Zoom : Integer; { Screen coords X,Y } MaxX, MaxY : Integer; { Screen resolution } Ticks : Longint; Seconds : Integer; PROCEDURE Draw(Color : Longint); { Procedure to draw a cube } Begin FOR P := 0 TO 11 DO Begin { Loops for all 12 lines } sX := Round(Zoom * Cube[LineIndex[P * 2] * 3]) + (MaxX DIV 2); { X coord for point #1 } sY := Round(Zoom * Cube[LineIndex[P * 2] * 3 + 1]) + (MaxY DIV 2); { Y coord for point #1 } sX1 := Round(Zoom * Cube[LineIndex[P * 2 + 1] * 3]) + (MaxX DIV 2); { X coord for point #2 } sY1 := Round(Zoom * Cube[LineIndex[P * 2 + 1] * 3 + 1]) + (MaxY DIV 2); { Y coord for point #2 } DrawLine(sX,sY,sX1,sY1,Color); { Draw it in current color } End; End; { Draw } PROCEDURE Calc; { Calculates new values after rotate step } Begin FOR P := 0 TO 7 DO Begin { Repeats for all 8 points } Yt := Cube[P * 3 + 1] * COS(Xan) - cube[P * 3 + 2] * SIN(Xan); { Read old values from the table of coord, } Zt := Cube[P * 3 + 1] * SIN(Xan) + cube[P * 3 + 2] * COS(Xan); { Rotating about x axis } Cube[P * 3 + 1] := Yt; { Writes the new values back to the table } Cube[P * 3 + 2] := Zt; Xt := Cube[P * 3] * COS(Yan) - Cube[P * 3 + 2] * SIN(Yan); { Same as above, for Y axis } Zt := Cube[P * 3] * SIN(Yan) + Cube[P * 3 + 2] * COS(Yan); Cube[P * 3] := Xt; Cube[P * 3 + 2] := Zt; Xt := Cube[P * 3] * COS(Zan) - Cube[P * 3 + 1] * SIN(Zan); { About Z axis } Yt := Cube[P * 3] * SIN(Zan) + Cube[P * 3 + 1] * COS(Zan); Cube[P * 3] := Xt; Cube[P * 3 + 1] := Yt; End; End; { Calc } Begin VBEInit(800,600,8); MaxX := ModeInfo.XResolution; MaxY := ModeInfo.YResolution; Zan := 0.1; { Rotation about Z axis by this angle } Yan := 0.02; { Rotation about Y axis by this angle } Xan := 0.02; { Rotation about X axis by this angle } Zoom := 60; { Size of the cube } Draw(100); { Draws the cube } InitFramesCounter; Repeat { Loops ... } Draw(0); { Undraws the cube } Retrace; Calc; { Calculates the new coords } Delay(10); { Wait a sec! } Draw(100); { Draws it again } Retrace; Delay(10); { Wait a sec! } CheckFramesCounter; Until KeyPressed; { ... 'till you press something } CloseVbeMode; WriteLn('Frames/sec : ',StopFramesCounter(Ticks,Seconds):3:2); End.
unit TPaintBoxX_IMP; interface uses ComServ, TPaintBoxX_TLB, SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, StdCtrls, ExtCtrls, ActiveX, AXCtrls, FadeEffect, RzPanel; type TTPaintBoxX = class(TActiveXControl, ITPaintBoxX) private FDelphiControl: TRzPanel; PaintBox: TPaintBox; FEvents: ITPaintBoxXEvents; FFontColor: TColor; LastTextRect: TRect; LastPicRect: TRect; FadeEffect: TFadeEffect; procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); procedure ResizeEvent(Sender: TObject); procedure PaintEvent(Sender: TObject); protected procedure InitializeControl; override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; function Get_Alignment: TxAlignment; safecall; function Get_BevelInner: TxPanelBevel; safecall; function Get_BevelOuter: TxPanelBevel; safecall; function Get_BevelWidth: Integer; safecall; function Get_BorderColor: TColor; safecall; function Get_BorderWidth: Integer; safecall; function Get_Caption: WideString; safecall; function Get_Color: TColor; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: Font; safecall; function Get_Locked: WordBool; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_VerticalAlignment: TxVerticalAlignment; safecall; function Get_Visible: WordBool; safecall; procedure Set_Alignment(Value: TxAlignment); safecall; procedure Set_BevelInner(Value: TxPanelBevel); safecall; procedure Set_BevelOuter(Value: TxPanelBevel); safecall; procedure Set_BevelWidth(Value: Integer); safecall; procedure Set_BorderColor(Value: TColor); safecall; procedure Set_BorderWidth(Value: Integer); safecall; procedure Set_Caption(const Value: WideString); safecall; procedure Set_Color(Value: TColor); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: Font); safecall; procedure Set_Locked(Value: WordBool); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_VerticalAlignment(Value: TxVerticalAlignment); safecall; procedure Set_Visible(Value: WordBool); safecall; procedure FadeInto(X, Y, PictureHDC: Integer); safecall; procedure FadeInText(X, Y: Integer; const Text: WideString); safecall; procedure FadeOutText(Left, Top, Right, Bottom, PictureHDC: Integer); safecall; function Get_LastTextBottom: Integer; safecall; function Get_LastTextLeft: Integer; safecall; function Get_LastTextRight: Integer; safecall; function Get_LastTextTop: Integer; safecall; procedure Set_LastTextBottom(Value: Integer); safecall; procedure Set_LastTextLeft(Value: Integer); safecall; procedure Set_LastTextRight(Value: Integer); safecall; procedure Set_LastTextTop(Value: Integer); safecall; function Get_OriginalCanvas: Integer; safecall; function Get_FontColor: TColor; safecall; procedure Set_FontColor(Value: TColor); safecall; procedure FadeOut(Left, Top, Right, Bottom, PictureHDC: Integer); safecall; function Get_LastPicBottom: Integer; safecall; function Get_LastPicLeft: Integer; safecall; function Get_LastPicRight: Integer; safecall; function Get_LastPicTop: Integer; safecall; procedure Set_LastPicBottom(Value: Integer); safecall; procedure Set_LastPicLeft(Value: Integer); safecall; procedure Set_LastPicRight(Value: Integer); safecall; procedure Set_LastPicTop(Value: Integer); safecall; procedure Refresh; safecall; end; implementation { TTPaintBoxX } Procedure TTPaintBoxX.InitializeControl; Begin FDelphiControl := Control As TRzPanel; PaintBox := TPaintBox.Create(FDelphiControl); PaintBox.Parent := FDelphiControl; PaintBox.Align := alClient; PaintBox.Visible := True; PaintBox.ParentFont := False; PaintBox.ParentColor := False; FFontColor := clBlack; LastTextRect := Rect(0, 0, 0, 0); LastPicRect := Rect(0, 0, 0, 0); FadeEffect := TFadeEffect.Create; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; FDelphiControl.OnResize := ResizeEvent; PaintBox.OnPaint := PaintEvent; End; procedure TTPaintBoxX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as ITPaintBoxXEvents; end; procedure TTPaintBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin {Define property pages here. Property pages are defined by calling} {DefinePropertyPage with the class id of the page. For example,} {DefinePropertyPage(Class_TPaintBoxXPage);} end; function TTPaintBoxX.Get_Alignment: TxAlignment; begin Result := Ord(FDelphiControl.Alignment); end; function TTPaintBoxX.Get_BevelInner: TxPanelBevel; begin Result := Ord(FDelphiControl.BevelInner); end; function TTPaintBoxX.Get_BevelOuter: TxPanelBevel; begin Result := Ord(FDelphiControl.BevelOuter); end; function TTPaintBoxX.Get_BevelWidth: Integer; begin Result := Integer(FDelphiControl.BevelWidth); end; function TTPaintBoxX.Get_BorderColor: TColor; begin Result := FDelphiControl.BorderColor; end; function TTPaintBoxX.Get_BorderWidth: Integer; begin Result := Integer(FDelphiControl.BorderWidth); end; function TTPaintBoxX.Get_Caption: WideString; begin Result := WideString(FDelphiControl.Caption); end; function TTPaintBoxX.Get_Color: TColor; begin Result := FDelphiControl.Color; end; function TTPaintBoxX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TTPaintBoxX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TTPaintBoxX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TTPaintBoxX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TTPaintBoxX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TTPaintBoxX.Get_Font: Font; begin GetOleFont(PaintBox.Canvas.Font, Result); end; function TTPaintBoxX.Get_Locked: WordBool; begin Result := FDelphiControl.Locked; end; function TTPaintBoxX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TTPaintBoxX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TTPaintBoxX.Get_VerticalAlignment: TxVerticalAlignment; begin Result := Ord(FDelphiControl.VerticalAlignment); end; function TTPaintBoxX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; procedure TTPaintBoxX.Set_Alignment(Value: TxAlignment); begin FDelphiControl.Alignment := TAlignment(Value); end; procedure TTPaintBoxX.Set_BevelInner(Value: TxPanelBevel); begin FDelphiControl.BevelInner := TPanelBevel(Value); end; procedure TTPaintBoxX.Set_BevelOuter(Value: TxPanelBevel); begin FDelphiControl.BevelOuter := TPanelBevel(Value); end; procedure TTPaintBoxX.Set_BevelWidth(Value: Integer); begin FDelphiControl.BevelWidth := TBevelWidth(Value); end; procedure TTPaintBoxX.Set_BorderColor(Value: TColor); begin FDelphiControl.BorderColor := Value; end; procedure TTPaintBoxX.Set_BorderWidth(Value: Integer); begin FDelphiControl.BorderWidth := TBorderWidth(Value); end; procedure TTPaintBoxX.Set_Caption(const Value: WideString); begin FDelphiControl.Caption := TCaption(Value); end; procedure TTPaintBoxX.Set_Color(Value: TColor); begin FDelphiControl.Color := Value; end; procedure TTPaintBoxX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TTPaintBoxX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TTPaintBoxX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TTPaintBoxX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TTPaintBoxX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TTPaintBoxX.Set_Font(const Value: Font); begin SetOleFont(PaintBox.Canvas.Font, Value); end; procedure TTPaintBoxX.Set_Locked(Value: WordBool); begin FDelphiControl.Locked := Value; end; procedure TTPaintBoxX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TTPaintBoxX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TTPaintBoxX.Set_VerticalAlignment(Value: TxVerticalAlignment); begin FDelphiControl.VerticalAlignment := TVerticalAlignment(Value); end; procedure TTPaintBoxX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TTPaintBoxX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TTPaintBoxX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; procedure TTPaintBoxX.ResizeEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnResize; end; procedure TTPaintBoxX.PaintEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnPaint; end; procedure TTPaintBoxX.FadeInto(X, Y, PictureHDC: Integer); var Picture : TBitmap; begin Picture := TBitmap.Create; Picture.Handle := PictureHDC; FadeEffect.FadeInTo(PaintBox.Canvas, X, Y, Picture); LastPicRect.Left := X; LastPicRect.Top := Y; LastPicRect.Right := X + Picture.Width; LastPicRect.Bottom := Y + Picture.Height; Picture.ReleaseHandle; Picture.Free; end; procedure TTPaintBoxX.FadeInText(X, Y: Integer; const Text: WideString); begin PaintBox.Canvas.Font.Color := FFontColor; LastTextRect := FadeEffect.FadeInText(PaintBox.Canvas, X, Y, Text); end; procedure TTPaintBoxX.FadeOutText(Left, Top, Right, Bottom, PictureHDC: Integer); var Picture: TBitmap; NewRect: TRect; PicRect: TRect; begin Picture := TBitmap.Create; NewRect := Rect(Left, Top, Right, Bottom); If PictureHDC = -1 Then begin PicRect := Rect(0, 0, Right - Left, Top - Bottom); PaintBox.Color := FDelphiControl.Color; Picture.Canvas.CopyRect(PicRect, PaintBox.Canvas, NewRect); Picture.Canvas.Brush.Color := FDelphiControl.Color; Picture.Canvas.Brush.Style := bsSolid; Picture.Canvas.FillRect(PicRect); Picture.Canvas.Refresh; end Else begin Picture.Handle := PictureHDC; end; FadeEffect.FadeOutText(PaintBox.Canvas, NewRect, Picture); Picture.ReleaseHandle; Picture.Free; end; procedure TTPaintBoxX.FadeOut(Left, Top, Right, Bottom, PictureHDC: Integer); var Picture: TBitmap; NewRect: TRect; PicRect: TRect; begin Picture := TBitmap.Create; NewRect := Rect(Left, Top, Right, Bottom); If PictureHDC = -1 Then begin PicRect := Rect(0, 0, Right - Left, Top - Bottom); PaintBox.Color := FDelphiControl.Color; Picture.Canvas.CopyRect(PicRect, PaintBox.Canvas, NewRect); Picture.Canvas.Brush.Color := FDelphiControl.Color; Picture.Canvas.Brush.Style := bsSolid; Picture.Canvas.FillRect(PicRect); Picture.Canvas.Refresh; end Else begin Picture.Handle := PictureHDC; end; FadeEffect.FadeOut(PaintBox.Canvas, NewRect, Picture); Picture.ReleaseHandle; Picture.Free; end; function TTPaintBoxX.Get_LastTextBottom: Integer; begin Result := LastTextRect.Bottom; end; function TTPaintBoxX.Get_LastTextLeft: Integer; begin Result := LastTextRect.Left; end; function TTPaintBoxX.Get_LastTextRight: Integer; begin Result := LastTextRect.Right; end; function TTPaintBoxX.Get_LastTextTop: Integer; begin Result := LastTextRect.Top; end; procedure TTPaintBoxX.Set_LastTextBottom(Value: Integer); begin LastTextRect.Bottom := Value; end; procedure TTPaintBoxX.Set_LastTextLeft(Value: Integer); begin LastTextRect.Left := Value; end; procedure TTPaintBoxX.Set_LastTextRight(Value: Integer); begin LastTextRect.Right := Value; end; procedure TTPaintBoxX.Set_LastTextTop(Value: Integer); begin LastTextRect.Top := Value; end; function TTPaintBoxX.Get_OriginalCanvas: Integer; begin Result := -1; end; function TTPaintBoxX.Get_FontColor: TColor; begin Result := FFontColor; end; procedure TTPaintBoxX.Set_FontColor(Value: TColor); begin FFontColor := Value; end; function TTPaintBoxX.Get_LastPicBottom: Integer; begin Result := LastPicRect.Bottom; end; function TTPaintBoxX.Get_LastPicLeft: Integer; begin Result := LastPicRect.Left; end; function TTPaintBoxX.Get_LastPicRight: Integer; begin Result := LastPicRect.Right; end; function TTPaintBoxX.Get_LastPicTop: Integer; begin Result := LastPicRect.Top; end; procedure TTPaintBoxX.Set_LastPicBottom(Value: Integer); begin LastPicRect.Bottom := Value; end; procedure TTPaintBoxX.Set_LastPicLeft(Value: Integer); begin LastPicRect.Left := Value; end; procedure TTPaintBoxX.Set_LastPicRight(Value: Integer); begin LastPicRect.Right := Value; end; procedure TTPaintBoxX.Set_LastPicTop(Value: Integer); begin LastPicRect.Top := Value; end; procedure TTPaintBoxX.Refresh; begin PaintBox.Refresh; end; initialization TActiveXControlFactory.Create( ComServer, TTPaintBoxX, TRzPanel, Class_TPaintBoxX, 1, '', OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL); end.
(****************************************************************************** * * * Settings.pas -- TSettings class, class for saving and loading program * * settings from the registry * * * * Copyright (c) 2006 Michael Puff http://www.michael-puff.de * * * ******************************************************************************) (***************************************************************************** * * * COPYRIGHT NOTICE * * * * Copyright (c) 2001-2006, Michael Puff ["copyright holder(s)"] * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in * * the documentation and/or other materials provided with the * * distribution. * * 3. The name(s) of the copyright holder(s) may not be used to endorse * * or promote products derived from this software without specific * * prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FORA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * * LIABILITY, OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ******************************************************************************) {$I CompilerSwitches.inc} unit Settings; interface uses Windows, MpuRegistry, MpuTools, Exceptions; type TSettings = class(TObject) private FReg: TMpuRegistry; function GetShowUsers: Boolean; procedure SetShowUsers(ShowUsers: Boolean); function GetExpandAll: Boolean; procedure SetExpandAll(ExpandAll: Boolean); public constructor Create(const Machine: WideString; hKey: HKEY); destructor Destroy; override; property ShowUsers: Boolean read GetShowUsers write SetShowUsers; property ExpandAll: Boolean read GetExpandAll write SetExpandAll; end; const REGKEY = 'Software\MichaelPuff\XPUsermanager'; REGEXPANDALL = 'Expand'; REGSHOWTYPE = 'ShowType'; implementation { TSettings } constructor TSettings.Create(const Machine: WideString; hKey: HKEY); begin FReg := TMpuRegistry.CreateW(Machine, hKey); end; destructor TSettings.Destroy; begin FReg.Free; end; function TSettings.GetExpandAll: Boolean; var err: DWORD; begin result := False; err := FReg.Connect; if err <> 0 then raise Exception.Create(SysErrorMessage(err), err); err := FReg.OpenKeyW(REGKEY, KEY_READ); if err = 0 then FReg.ReadBoolW(REGEXPANDALL, result, False); end; function TSettings.GetShowUsers: Boolean; var err: DWORD; begin result := True; err := FReg.Connect; if err <> 0 then raise Exception.Create(SysErrorMessage(err), err); err := FReg.OpenKeyW(REGKEY, KEY_READ); if err = 0 then FReg.ReadBoolW(REGSHOWTYPE, result, True); end; procedure TSettings.SetExpandAll(ExpandAll: Boolean); var err: DWORD; begin err := FReg.Connect; if err <> 0 then raise Exception.Create(SysErrorMessage(err), err); err := FReg.CreateKeyW(REGKEY); if err = 0 then FReg.WriteBoolW(REGEXPANDALL, ExpandAll) else raise Exception.Create(SysErrorMessage(err), err); end; procedure TSettings.SetShowUsers(ShowUsers: Boolean); var err: DWORD; begin err := FReg.Connect; if err <> 0 then raise Exception.Create(SysErrorMessage(err), err); err := FReg.CreateKeyW(REGKEY); if err = 0 then FReg.WriteBoolW(REGSHOWTYPE, ShowUsers) else raise Exception.Create(SysErrorMessage(err), err); end; end.
unit acRootEdit; {$I sDefs.inc} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, acShellCtrls, {$IFDEF DELPHI6UP}DesignEditors, DesignIntf, VCLEditors,{$ELSE}dsgnintf,{$ENDIF} sSkinProvider, sDialogs, sEdit, sRadioButton, sComboBox, sGroupBox, sButton, Buttons, sBitBtn, Mask, sMaskEdit, sCustomComboEdit, sTooledit; type TacRootPathEditDlg = class(TForm) Button1: TsBitBtn; Button2: TsBitBtn; rbUseFolder: TsRadioButton; GroupBox1: TsGroupBox; cbFolderType: TsComboBox; GroupBox2: TsGroupBox; OpenDialog1: TsOpenDialog; sSkinProvider1: TsSkinProvider; rbUsePath: TsRadioButton; ePath: TsDirectoryEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button2Click(Sender: TObject); procedure rbUseFolderClick(Sender: TObject); procedure rbUsePathClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnBrowseClick(Sender: TObject); private procedure UpdateState; public end; TacRootProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; TacRootEditor = class(TComponentEditor) public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): String; override; function GetVerbCount: Integer; override; end; implementation {$R *.dfm} uses TypInfo, FileCtrl, sStyleSimply; resourcestring SEdiTacRoot = 'E&dit Root'; function PathIsCSIDL(Value: string): Boolean; begin Result := GetEnumValue(TypeInfo(TacRootFolder), Value) >= 0; end; function RootPathEditor(const Value : string): string; var rpe : TacRootPathEditDlg; begin Result := Value; rpe := TacRootPathEditDlg.Create(Application); with rpe do try rbUseFolder.Checked := PathIsCSIDL(Result); rbUsePath.Checked := not rbUseFolder.Checked; if not PathIsCSIDL(Result) then begin cbFolderType.ItemIndex := 0; ePath.Text := Result; end else cbFolderType.ItemIndex := cbFolderType.Items.IndexOf(Result); UpdateState; ShowModal; if ModalResult = mrOK then begin if rbUsePath.Checked then Result := ePath.Text else Result := cbFolderType.Items[cbFolderType.ItemIndex]; end; finally Free; end; end; procedure TacRootProperty.Edit; begin SetStrValue(RootPathEditor(GetStrValue)); end; function TacRootProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog]; end; procedure TacRootPathEditDlg.FormCreate(Sender: TObject); var FT: TacRootFolder; begin for FT := Low(TacRootFolder) to High(TacRootFolder) do if not ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and (FT in NTFolders)) then cbFolderType.Items.Add(GetEnumName(TypeInfo(TacRootFolder), Ord(FT))); cbFolderType.ItemIndex := 0; end; procedure TacRootPathEditDlg.UpdateState; begin cbFolderType.Enabled := rbUseFolder.Checked; ePath.Enabled := not rbUseFolder.Checked; // btnBrowse.Enabled := ePath.Enabled; end; procedure TacRootPathEditDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TacRootPathEditDlg.Button2Click(Sender: TObject); begin ModalResult := mrCancel; Close; end; procedure TacRootPathEditDlg.rbUseFolderClick(Sender: TObject); begin rbUsePath.Checked := not rbUseFolder.Checked; UpdateState; end; procedure TacRootPathEditDlg.rbUsePathClick(Sender: TObject); begin rbUseFolder.Checked := not rbUsePath.Checked; UpdateState; end; procedure TacRootPathEditDlg.Button1Click(Sender: TObject); begin ModalResult := mrOK; end; procedure TacRootPathEditDlg.btnBrowseClick(Sender: TObject); begin end; { TacRootEditor } procedure TacRootEditor.ExecuteVerb(Index: Integer); procedure EdiTacRoot; const SRoot = 'root'; var Path : string; begin Path := RootPathEditor(GetPropValue(Component, SRoot, True)); SetPropValue(Component, SRoot, Path); Designer.Modified; end; begin case Index of 0 : EdiTacRoot; end; end; function TacRootEditor.GetVerb(Index: Integer): String; begin case Index of 0 : Result := SEdiTacRoot; end; end; function TacRootEditor.GetVerbCount: Integer; begin Result := 1; end; end.
unit EasyUDP; interface uses System.Net, System.Text, System.Threading, System.Windows; Var Client: System.Net.Sockets.UdpClient; IP: System.Net.IPAddress; EP: IPEndPoint; ///Функция отправки датаграммы. Возвращает количество отправленных байт. Function Send(Datagram: array of byte): integer; ///Инициализация подключения Procedure Connect(HostName: string; Port: integer); ///Инициализация подключения Procedure Connect(IP: IPAddress; Port: integer); ///Закрытие подключения Procedure Close; ///Функция, возвращающая полученные из заданного в Connect EndPoint данные. ///Важно: останавливает ход программы до получения. Function Receive: array of byte; ///Функция, возвращающая полученные из заданного EndPoint данные. ///Важно: останавливает ход программы до получения. Function Receive(Point: IPEndPoint): array of byte; implementation Procedure Close; BEGIN Client.Close; End; Function Send(Datagram: array of byte): integer; BEGIN Result := Client.Send(Datagram, Datagram.Length); End; Procedure Connect(HostName: string; Port: integer); BEGIN IP := Dns.GetHostAddresses(HostName)[0]; EP := new IpEndPoint(IP, Port); Client.Connect(EP); End; Procedure Connect(IP: IPAddress; Port: integer); BEGIN EP := new IpEndPoint(IP, Port); Client.Connect(EP); End; Function Receive: array of byte; BEGIN Result := Client.Receive(EP); End; Function Receive(Point: IPEndPoint): array of byte; BEGIN Result := Client.Receive(Point); End; end.
{-----------------------------------} program Cradle; {-----------------------------------} { Constant Declarations} const TAB = ^I; {-----------------------------------} { Variable Declarations} var Look: char; { Lookahead Character} {-----------------------------------} { Read New Character From Input Stream} procedure GetChar; begin Read(Look); end; {-----------------------------------} procedure Error (s: string); begin WriteLn; WriteLn(^G, 'Error: ', s, '.'); end; {-----------------------------------} procedure Abort(s: string); begin Error(s); Halt; end; {-----------------------------------} {Report what was expected} procedure Expected (s: string); begin Abort (s + 'Expected'); end; {-----------------------------------} {Match a Specific Input Character} procedure Match(x: char); begin if Look = x then GetChar else Expected('''' + x + ''''); end; {-----------------------------------} {Recognize an Alpha Characters} function IsAlpha(c: char): boolean; begin IsAlpha := upcase(c) in ['A'..'Z']; end; {-----------------------------------} { Recognize a Decimal Digit } function IsDigit(c: char): boolean; begin IsDigit := c in ['0'..'9']; end; {-----------------------------------} { Get an Identifier} function GetName: char; begin if not IsAlpha(Look) then Expected('Name'); GetName := UpCase(Look); GetChar; end; {-----------------------------------} {Get a Number} function GetNum: char; begin if not IsDigit(Look) then Expected('Integer'); GetNum := Look; GetChar; end; {-----------------------------------} {Output a String with Tab} procedure Emit(s: string); begin Write(TAB, s); end; {-----------------------------------} {Output a String with Tab and CRLF} procedure EmitLn(s: string); begin Emit(s); WriteLn; end; {-----------------------------------} {Parse and Translate a Math Factor} {Parse and Translate a Math Factor} procedure Expression; Forward; procedure Factor; begin if Look = '(' then begin Match('('); Expression; Match(')'); end else EmitLn('MOVE #' + GetNum + ',D0'); end; {-----------------------------------} {Recognize and Translate a Subtract} procedure Multiply; begin Match('*'); Factor; EmitLn('MULT (SP)+, D0'); end; {-----------------------------------} {Recognize and Translate a Divide} procedure Divide; begin Match('/'); Factor; EmitLn('MOVE (SP)+, D0'); EmitLn('DIV D1, D0'); end; {-----------------------------------} {Parse and Translate a Math Expression} procedure Term; begin Factor; while Look in ['*', '/'] do begin EmitLn('MOVE D0, -(SP)'); case Look of '*': Multiply; '/': Divide; else Expected('Mulop'); end; end; end; {-----------------------------------} {Recognize and Translate an Add} procedure Add; begin Match('+'); Term; EmitLn('ADD (SP)+, D0'); end; {-----------------------------------} {Recognize and Translate an Subtract} procedure Subtract; begin Match('-'); Term; EmitLn('SUB (SP)+, D0'); EmitLn('NEG D0'); end; {-----------------------------------} {Parse and Translate a Math Expression} procedure Expression; begin Term; while Look in ['+', '-'] do begin EmitLn('MOVE D0, -(SP)'); case Look of '+': Add; '-': Subtract; else Expected('Addop'); end; end; end; {-----------------------------------} {Initialize} procedure init; begin GetChar; end; {-----------------------------------} {Main Program} begin Init; Expression; end. {-----------------------------------}
Program Shrinker; {$M 10240, 0, 0} {$F+} { Shrink.Pas version 1.2 (C) Copyright 1989 by R. P. Byrne } { } { Compress a set of input files into a Zip file using Lempel-Ziv-Welch } { (LZW) compression techniques (the "shrink" method). } Uses Dos, Crt, MemAlloc, StrProcs; Const CopyRight = 'Shrink (C) Copyright 1989 by R. P. Byrne'; Version = 'Version 1.2 - Compiled on March 11, 1989'; Const BUFSIZE = 10240; { Use 10K file buffers } MINBITS = 9; { Starting code size of 9 bits } MAXBITS = 13; { Maximum code size of 13 bits } TABLESIZE = 8191; { We'll need 4K entries in table } SPECIAL = 256; { Special function code } INCSIZE = 1; { Code indicating a jump in code size } CLEARCODE = 2; { Code indicating code table has been cleared } FIRSTENTRY = 257; { First available table entry } UNUSED = -1; { Prefix indicating an unused code table entry } STDATTR = $23; { Standard file attribute for DOS Find First/Next } Const LOCAL_FILE_HEADER_SIGNATURE = $04034B50; Type Local_File_Header_Type = Record Signature : LongInt; Extract_Version_Reqd : Word; Bit_Flag : Word; Compress_Method : Word; Last_Mod_Time : Word; Last_Mod_Date : Word; Crc32 : LongInt; Compressed_Size : LongInt; Uncompressed_Size : LongInt; Filename_Length : Word; Extra_Field_Length : Word; end; { Define the Central Directory record types } Const CENTRAL_FILE_HEADER_SIGNATURE = $02014B50; Type Central_File_Header_Type = Record Signature : LongInt; MadeBy_Version : Word; Extract_Version_Reqd : Word; Bit_Flag : Word; Compress_Method : Word; Last_Mod_Time : Word; Last_Mod_Date : Word; Crc32 : LongInt; Compressed_Size : LongInt; Uncompressed_Size : LongInt; Filename_Length : Word; Extra_Field_Length : Word; File_Comment_Length : Word; Starting_Disk_Num : Word; Internal_Attributes : Word; External_Attributes : LongInt; Local_Header_Offset : LongInt; End; Const END_OF_CENTRAL_DIR_SIGNATURE = $06054B50; Type End_of_Central_Dir_Type = Record Signature : LongInt; Disk_Number : Word; Central_Dir_Start_Disk : Word; Entries_This_Disk : Word; Total_Entries : Word; Central_Dir_Size : LongInt; Start_Disk_Offset : LongInt; ZipFile_Comment_Length : Word; end; Const Crc_32_Tab : Array[0..255] of LongInt = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d ); Type { Define data types needed to implement a code table for LZW compression } CodeRec = Record { Code Table record format... } Child : Integer; { Addr of 1st suffix for this prefix } Sibling : Integer; { Addr of next suffix in chain } Suffix : Byte; { Suffix character } end {CodeRec}; CodeArray = Array[0..TABLESIZE] of CodeRec; { Define the code table } TablePtr = ^CodeArray; { Allocate dynamically } { Define data types needed to implement a free node list } FreeListPtr = ^FreeListArray; FreeListArray = Array[FIRSTENTRY..TABLESIZE] of Word; { Define data types needed to implement input and output file buffers } BufArray = Array[1..BUFSIZE] of byte; BufPtr = ^BufArray; { Define the structure of a DOS Disk Transfer Area (DTA) } DTARec = Record Filler : Array[1..21] of Byte; Attr : Byte; Time : Word; Date : Word; Size : LongInt; Name : String[12]; end {DtaRec}; { Define data types needed to implement a sorted singly linked list to } { hold the names of all files to be compressed } NameStr = String[12]; PathStr = String[64]; NodePtr = ^NameList; NameList = Record { Linked list node structure... } Path : PathStr; { Path of input file } Name : NameStr; { Name of input file } Size : LongInt; { Size in bytes of input file } Date : Word; { Date stamp of input file } Time : Word; { Time stamp of input file } Next : NodePtr; { Next node in linked list } end {NameList}; Var InFileSpecs : Array[1..20] of String; { Input file specifications } MaxSpecs : Word; { Total number of filespecs to be Zipped } OutFileName : String; { Name of resulting Zip file } InFile, { I/O file variables } OutFile : File; InBuf, { I/O buffers } OutBuf : BufPtr; InBufIdx, { Points to next char in buffer to be read } OutBufIdx : Word; { Points to next free space in output buffer } MaxInBufIdx : Word; { Count of valid chars in input buffer } InputEof : Boolean; { End of file indicator } Crc32Val : LongInt; { CRC calculation variable } CodeTable : TablePtr; { Points to code table for LZW compression } FreeList : FreeListPtr; { Table of free code table entries } NextFree : Word; { Index into free list table } ClearList : Array[0..1023] of Byte; { Bit mapped structure used in } { during adaptive resets } CodeSize : Byte; { Size of codes (in bits) currently being written } MaxCode : Word; { Largest code that can be written in CodeSize bits } LocalHdr : Local_File_Header_Type; LocalHdrOfs : LongInt; { Offset within output file of the local header } CentralHdr : Central_File_Header_Type; EndHdr : End_of_Central_Dir_Type; FirstCh : Boolean; { Flag indicating the START of a shrink operation } TableFull : Boolean; { Flag indicating a full symbol table } SaveByte : Byte; { Output code buffer } BitsUsed : Byte; { Index into output code buffer } BytesIn : LongInt; { Count of input file bytes processed } BytesOut : LongInt; { Count of output bytes } ListHead : NodePtr; { Pointer to head of linked list } TenPercent : LongInt; { --------------------------------------------------------------------------- } { Houskeeping stuff (error routines and initialization of program variables) } { --------------------------------------------------------------------------- } Procedure Syntax; Begin Writeln('Shrink.Exe'); Writeln(' Usage: Shrink zipfilename [filespec [...]]'); Writeln; Writeln(' A filespec is defined as [d:][\path\]name'); Writeln(' where ''name'' may contain DOS wildcard characters.'); Writeln; Writeln(' Multiple filespecs may be entered up to a maximum of 20.'); Writeln; Writeln(' If no filespecs are entered, *.* is assumed.'); Writeln; Halt(255); end {Syntax}; { --------------------------------------------------------------------------- } Procedure Fatal(Msg : String); Begin Writeln; Writeln; Writeln('Shrink.Exe'); Writeln(' Error: ', Msg); Writeln(' Program halted'); Writeln; Writeln; Halt(128); end {Fatal}; { --------------------------------------------------------------------------- } Procedure AddToList(PathSpec : PathStr; DTA : DTARec); { Add an entry to a linked list of filenames to be crunched. Maintain } { sorted order (standard ASCII collating sequence) by filename } Var MemError : Word; NewNode : NodePtr; Done : Boolean; ListNode : NodePtr; Begin { Allocate a new node } MemError := Malloc(NewNode, SizeOf(NewNode^)); If MemError <> 0 then Fatal('Not enough memory to process all filenames!'); { Populate the fields of the new node } NewNode^.Path := PathSpec; NewNode^.Name := DTA.Name; NewNode^.Size := DTA.Size; NewNode^.Date := DTA.Date; NewNode^.Time := DTA.Time; NewNode^.Next := NIL; { Find the proper location in the list at which to insert the new node } If ListHead = NIL then ListHead := NewNode else If DTA.Name < ListHead^.Name then begin NewNode^.Next := ListHead; ListHead := NewNode; end {then} else begin Done := FALSE; ListNode := ListHead; While NOT Done do begin If ListNode^.Name = DTA.Name then begin ListNode^.Path := PathSpec; MemError := Dalloc(NewNode); Done := TRUE; end {then} else If ListNode^.Next = NIL then begin ListNode^.Next := NewNode; Done := TRUE; end {then} else If ListNode^.Next^.Name > DTA.Name then begin NewNode^.Next := ListNode^.Next; ListNode^.Next := NewNode; Done := TRUE; end {then} else ListNode := ListNode^.Next; end {while}; end {if}; end {AddToList}; { --------------------------------------------------------------------------- } Procedure GetNames; { Expand input file specifications. Store the name of each file to be } { compressed in a sorted, singly linked list } Var DosDTA : DTARec; I : Word; InPath : String; Begin ListHead := NIL; For I := 1 to MaxSpecs do begin { Loop through all input file specs } InPath := Upper(PathOnly(InFileSpecs[I])); FindFirst(InFileSpecs[I], STDATTR, SearchRec(DosDTA)); While DosError = 0 do begin { Loop through all matching files } If (NOT SameFile(InPath + DosDTA.Name, OutFileName)) then AddToList(InPath, DosDTA); FindNext(SearchRec(DosDTA)); end {while}; end {for}; end {GetNames}; { --------------------------------------------------------------------------- } Function ParamCheck : Boolean; { Verify all command line parameters } Var SearchBuf : SearchRec; OutPath : String; Ch : Char; I : Word; Begin If ParamCount < 1 then Syntax; If ParamCount > 21 then begin Writeln('Too many command line parameters entered!'); Syntax; end {if}; OutFileName := Upper(ParamStr(1)); If Pos('.', OutFileName) = 0 then OutFileName := Concat(OutFileName, '.ZIP'); FindFirst(OutFileName, STDATTR, SearchBuf); If DosError = 0 then begin Write(OutFileName, ' already exists! Overwrite it (Y/N, Enter=N)? '); Ch := ReadKey; Writeln(Ch); Writeln; If UpCase(Ch) <> 'Y' then begin Writeln; Writeln('Program aborted!'); Halt; end {if}; end {if}; If ParamCount = 1 then begin InFileSpecs[1] := '*.*'; MaxSpecs := 1; end {then} else For I := 2 to ParamCount do begin InFilespecs[Pred(I)] := ParamStr(I); MaxSpecs := Pred(I); end {for}; GetNames; End {ParamCheck}; { --------------------------------------------------------------------------- } { Running 32 Bit CRC update function } { --------------------------------------------------------------------------- } Function UpdC32(Octet: Byte; Crc: LongInt) : LongInt; Var L : LongInt; W : Array[1..4] of Byte Absolute L; Begin UpdC32 := Crc_32_Tab[Byte(Crc XOR LongInt(Octet))] XOR ((Crc SHR 8) AND $00FFFFFF); end {UpdC32}; { --------------------------------------------------------------------------- } { I/O Support routines } { --------------------------------------------------------------------------- } Procedure GetBuffers; { Allocate Input and Output buffers } Var MemError : Word; Begin MemError := Malloc(InBuf, Sizeof(InBuf^)); If MemError <> 0 then Fatal(Concat('Cannot allocate Input buffer', #13#10, ' DOS Return Code on allocation request was ', IntStr(MemError, 0))); MemError := Malloc(OutBuf, Sizeof(OutBuf^)); If MemError <> 0 then Fatal(Concat('Cannot allocate Output buffer', #13#10, ' DOS Return Code on allocation request was ', IntStr(MemError, 0))); End {GetBuffers}; { --------------------------------------------------------------------------- } Procedure DropBuffers; { Deallocate input and output buffers } Var MemError : Word; Begin MemError := Dalloc(InBuf); MemError := Dalloc(OutBuf); end {DropBuffers}; { --------------------------------------------------------------------------- } Procedure OpenOutput; Var RC : Integer; Begin Assign(OutFile, OutFileName); FileMode := 66; {$I-} ReWrite(OutFile, 1); {$I+} RC := IOResult; If RC <> 0 then Fatal(Concat('Cannot open output file', #13#10, ' Return Code was ', IntStr(RC, 0))); End {OpenOutput}; { --------------------------------------------------------------------------- } Function OpenInput(InFileName : String) : Boolean; Var RC : Integer; Begin Assign(InFile, InFileName); FileMode := 64; {$I-} Reset(InFile, 1); {$I+} OpenInput := (IOResult = 0); End {OpenInput}; { --------------------------------------------------------------------------- } Procedure CloseOutput; Var RC : Integer; Begin {$I-} Close(OutFile) {$I+}; RC := IOResult; end {CloseOutput}; { --------------------------------------------------------------------------- } Procedure CloseInput; Var RC : Integer; Begin {$I-} Close(InFile) {$I+}; RC := IOResult; end {CloseInput}; { --------------------------------------------------------------------------- } Procedure Read_Block; { Read a "block" of data into our our input buffer } Begin BlockRead(InFile, InBuf^[1], SizeOf(InBuf^), MaxInBufIdx); If MaxInBufIdx = 0 then InputEof := TRUE else InputEOF := FALSE; InBufIdx := 1; end {Read_Block}; { --------------------------------------------------------------------------- } Procedure Write_Block; { Write a block of data from the output buffer to our output file } Begin BlockWrite(OutFile, OutBuf^[1], Pred(OutBufIdx)); OutBufIdx := 1; end {Write_Block}; { --------------------------------------------------------------------------- } Procedure PutChar(B : Byte); { Put one character into our output buffer } Begin OutBuf^[OutBufIdx] := B; Inc(OutBufIdx); If OutBufIdx > SizeOf(OutBuf^) then Write_Block; Inc(BytesOut); end {PutChar}; { --------------------------------------------------------------------------- } Procedure FlushOutput; { Write any data sitting in our output buffer to the output file } Begin If OutBufIdx > 1 then Write_Block; End {FlushOutput}; { --------------------------------------------------------------------------- } Procedure PutCode(Code : Integer); { Assemble coded bytes for output } Var PutCharAddr : Pointer; Begin PutCharAddr := @PutChar; Inline( {; Register useage:} {;} {; AX - holds Code} {; BX - BH is a work register, BL holds SaveByte} {; CX - holds our loop counter CodeSize} {; DX - holds BitsUsed} {;} $8B/$46/<Code/ { mov ax,[bp+<Code]} $31/$DB/ { xor bx,bx} $89/$D9/ { mov cx,bx} $89/$DA/ { mov dx,bx} $8A/$1E/>SaveByte/ { mov bl,[>SaveByte]} $8A/$0E/>CodeSize/ { mov cl,[>CodeSize]} $8A/$16/>BitsUsed/ { mov dl,[>BitsUsed]} $3D/$FF/$FF/ { cmp ax,-1 ;Any work to do?} $75/$0D/ { jnz Repeat ;Yup, go do it} $80/$FA/$00/ { cmp dl,0 ;Any leftovers?} $74/$3A/ { jz AllDone ;Nope, we're done} $53/ { push bx ;Yup...push leftovers} $0E/ { push cs} $FF/$96/>PutCharAddr/ { call [bp+>PutCharAddr] ; and send to output} $EB/$32/ { jmp short AllDone} {;} $30/$FF/ {Repeat: xor bh,bh ;Zero out BH} $D1/$D8/ { rcr ax,1 ;Get low order bit into CY flag} $73/$02/ { jnc SkipBit ;Was the bit set?} $FE/$C7/ { inc bh ;Yes, xfer to BH} $87/$D1/ {SkipBit: xchg cx,dx ;Swap CX & DX} $D2/$E7/ { shl bh,cl ;Shift bit over} $87/$D1/ { xchg cx,dx ;Put CX & DX back where they were} $42/ { inc dx ;Bump count of bit positions used} $08/$FB/ { or bl,bh ;Transfer bit to output byte (SaveByte)} $83/$FA/$08/ { cmp dx,8 ;Full byte yet?} $72/$12/ { jb GetNext ;Nope, go get more code bits} $50/ { push ax ;Yup, save regs in preparation} $53/ { push bx ; for call to output routine} $51/ { push cx} $52/ { push dx} $53/ { push bx ;Push byte to output onto stack} $0E/ { push cs} $FF/$96/>PutCharAddr/ { call [bp+>PutCharAddr] ; and call the output routine} $5A/ { pop dx} $59/ { pop cx} $5B/ { pop bx} $58/ { pop ax} $31/$DB/ { xor bx,bx ;Prepare SaveByte for next byte} $89/$DA/ { mov dx,bx ;Set BitsUsed to zero} $E2/$D6/ {GetNext: loop Repeat ;Repeat for all code bits} {;} $88/$1E/>SaveByte/ { mov [>SaveByte],bl ;Put SaveByte and BitsUsed} $88/$16/>BitsUsed); { mov [>BitsUsed],dl ; back in memory} {;} {AllDone:} end {Putcode}; { --------------------------------------------------------------------------- } { The following routines are used to allocate, initialize, and de-allocate } { various dynamic memory structures used by the LZW compression algorithm } { --------------------------------------------------------------------------- } Procedure Build_Data_Structures; Var Code : Word; Begin Code := Malloc(CodeTable, SizeOf(CodeTable^)) OR Malloc(FreeList, SizeOf(FreeList^ )); If Code <> 0 then Fatal('Not enough memory to allocate LZW data structures!'); end {Build_Data_Structures}; { --------------------------------------------------------------------------- } Procedure Destroy_Data_Structures; Var Code : Word; Begin Code := Dalloc(CodeTable); Code := Dalloc(FreeList); end {Destroy_Data_Structures}; { --------------------------------------------------------------------------- } Procedure Initialize_Data_Structures; Var I : Word; Begin For I := 0 to TableSize do begin With CodeTable^[I] do begin Child := -1; Sibling := -1; If I <= 255 then Suffix := I; end {with}; If I >= 257 then FreeList^[I] := I; end {for}; NextFree := FIRSTENTRY; TableFull := FALSE; end {Initialize_Data_Structures}; { --------------------------------------------------------------------------- } { The following routines handle manipulation of the LZW Code Table } { --------------------------------------------------------------------------- } Procedure Prune(Parent : Word); { Prune leaves from a subtree - Note: this is a recursive procedure } Var CurrChild : Integer; NextSibling : Integer; Begin CurrChild := CodeTable^[Parent].Child; { Find first Child that has descendants .. clear any that don't } While (CurrChild <> -1) AND (CodeTable^[CurrChild].Child = -1) do begin CodeTable^[Parent].Child := CodeTable^[CurrChild].Sibling; CodeTable^[CurrChild].Sibling := -1; { Turn on ClearList bit to indicate a cleared entry } ClearList[CurrChild DIV 8] := (ClearList[CurrChild DIV 8] OR (1 SHL (CurrChild MOD 8))); CurrChild := CodeTable^[Parent].Child; end {while}; If CurrChild <> -1 then begin { If there are any children left ...} Prune(CurrChild); NextSibling := CodeTable^[CurrChild].Sibling; While NextSibling <> -1 do begin If CodeTable^[NextSibling].Child = -1 then begin CodeTable^[CurrChild].Sibling := CodeTable^[NextSibling].Sibling; CodeTable^[NextSibling].Sibling := -1; { Turn on ClearList bit to indicate a cleared entry } ClearList[NextSibling DIV 8] := (ClearList[NextSibling DIV 8] OR (1 SHL (NextSibling MOD 8))); NextSibling := CodeTable^[CurrChild].Sibling; end {then} else begin CurrChild := NextSibling; Prune(CurrChild); NextSibling := CodeTable^[CurrChild].Sibling; end {if}; end {while}; end {if}; end {Prune}; { --------------------------------------------------------------------------- } Procedure Clear_Table; Var Node : Word; Begin FillChar(ClearList, SizeOf(ClearList), $00); { Remove all leaf nodes by recursively pruning subtrees} For Node := 0 to 255 do Prune(Node); { Next, re-initialize our list of free table entries } NextFree := Succ(TABLESIZE); For Node := TABLESIZE downto FIRSTENTRY do begin If (ClearList[Node DIV 8] AND (1 SHL (Node MOD 8))) <> 0 then begin Dec(NextFree); FreeList^[NextFree] := Node; end {if}; end {for}; If NextFree <= TABLESIZE then TableFull := FALSE; end {Clear_Table}; { --------------------------------------------------------------------------- } Procedure Table_Add(Prefix : Word; Suffix : Byte); Var FreeNode : Word; Begin If NextFree <= TABLESIZE then begin FreeNode := FreeList^[NextFree]; Inc(NextFree); CodeTable^[FreeNode].Child := -1; CodeTable^[FreeNode].Sibling := -1; CodeTable^[FreeNode].Suffix := Suffix; If CodeTable^[Prefix].Child = -1 then CodeTable^[Prefix].Child := FreeNode else begin Prefix := CodeTable^[Prefix].Child; While CodeTable^[Prefix].Sibling <> -1 do Prefix := CodeTable^[Prefix].Sibling; CodeTable^[Prefix].Sibling := FreeNode; end {if}; end {if}; If NextFree > TABLESIZE then TableFull := TRUE; end {Table_Add}; { --------------------------------------------------------------------------- } Function Table_Lookup( TargetPrefix : Integer; TargetSuffix : Byte; Var FoundAt : Integer ) : Boolean; { --------------------------------------------------------------------------- } { Search for a Prefix:Suffix pair in our Symbol table. If found, return the } { index value where found. If not found, return FALSE and set the VAR parm } { FoundAt to -1. } { --------------------------------------------------------------------------- } Begin Inline( {;} {; Lookup an entry in the Hash Table. If found, return TRUE and set the VAR} {; parameter FoundAt with the index of the entry at which the match was found.} {; If not found, return FALSE and plug a -1 into the FoundAt var.} {;} {;} {; Register usage:} {; AX - varies BL - holds target suffix character} {; BH - If search fails, determines how to} {; add the new entry} {; CX - not used DX - holds size of 1 table entry (5)} {; DI - varies SI - holds offset of 1st table entry} {; ES - seg addr of hash table DS - program's data segment} {;} {;} $8A/$5E/<TargetSuffix/ { mov byte bl,[bp+<TargetSuffix] ;Target Suffix character} $8B/$46/<TargetPrefix/ { mov word ax,[bp+<TargetPrefix] ;Index into table} $BA/$05/$00/ { mov dx,5 ;5 byte table entries} $F7/$E2/ { mul dx ;AX now an offset into table} $C4/$3E/>CodeTable/ { les di,[>CodeTable] ;Hash table address} $89/$FE/ { mov si,di ;save offset in SI} $01/$C7/ { add di,ax ;es:di points to table entry} {;} $B7/$00/ { mov bh,0 ;Chain empty flag (0=empty)} $26/$83/$3D/$FF/ { es: cmp word [di],-1 ;Anything on the chain?} $74/$33/ { jz NotFound ;Nope, search fails} $B7/$01/ { mov bh,1 ;Chain empty flag (1=not empty)} {;} $26/$8B/$05/ { es: mov word ax,[di] ;Get index of 1st entry in chain} $89/$46/<TargetPrefix/ {Loop: mov word [bp+<TargetPrefix],ax ;Save index for later} $BA/$05/$00/ { mov dx,5} $F7/$E2/ { mul dx ;convert index to offset} $89/$F7/ { mov di,si ;es:di points to start of table} $01/$C7/ { add di,ax ;es:di points to table entry} {;} $26/$3A/$5D/$04/ { es: cmp byte bl,[di+4] ;match on suffix?} $74/$0D/ { jz Found ;Yup, search succeeds} {;} $26/$83/$7D/$02/$FF/ { es: cmp word [di+2],-1 ;any more entries in chain?} $74/$15/ { jz NotFound ;nope, search fails} {;} $26/$8B/$45/$02/ { es: mov word ax,[di+2] ;get index of next chain entry} $EB/$E1/ { jmp short Loop ; and keep searching} {;} $C6/$46/$FF/$01/ {Found: mov byte [bp-1],1 ;return TRUE} $C4/$7E/<FoundAt/ { les di,[bp+<FoundAt] ;get address of Var parameter} $8B/$46/<TargetPrefix/ { mov word ax,[bp+<TargetPrefix] ;get index of entry where found} $26/$89/$05/ { es: mov [di],ax ;and store it} $EB/$0C/ { jmp short Done} {;} $C6/$46/$FF/$00/ {NotFound: mov byte [bp-1],0 ;return FALSE} $C4/$7E/<FoundAt/ { les di,[bp+<FoundAt] ;get address of Var parameter} $26/$C7/$05/$FF/$FF); { es: mov word [di],-1 ;and store a -1 in it} {;} {Done:} {;} end {Table_Lookup}; { --------------------------------------------------------------------------- } { These routines build the Header structures for the ZIP file } { --------------------------------------------------------------------------- } Procedure Begin_ZIP(ListPtr : NodePtr); { Write a dummy header to the zip. Include as much info as is currently } { known (we'll come back and fill in the rest later...) } Begin LocalHdrOfs := FilePos(OutFile); { Save file position for later use } With LocalHdr do begin Signature := LOCAL_FILE_HEADER_SIGNATURE; Extract_Version_Reqd := 10; Bit_Flag := 0; Compress_Method := 1; Last_Mod_Time := ListPtr^.Time; Last_Mod_Date := ListPtr^.Date; Crc32 := 0; Compressed_Size := 0; Uncompressed_Size := ListPtr^.Size; FileName_Length := Length(ListPtr^.Name); Extra_Field_Length := 0; end {with}; Move(LocalHdr, OutBuf^, SizeOf(LocalHdr)); { Put header into output buffer } OutBufIdx := Succ(SizeOf(LocalHdr)); {...adjust buffer index accordingly } Move(ListPtr^.Name[1], OutBuf^[OutBufIdx], Length(ListPtr^.Name)); Inc(OutBufIdx, Length(ListPtr^.Name)); FlushOutput; { Write it now } End {Begin_ZIP}; { --------------------------------------------------------------------------- } Procedure Update_ZIP_Header(ListPtr : NodePtr); { Update the zip's local header with information that we now possess. Check } { to make sure that our shrinker actually produced a smaller file. If not, } { scrap the shrunk data, modify the local header accordingly, and just copy } { the input file to the output file (compress method 0 - Storing). } Var EndPos : LongInt; Redo : Boolean; Begin Redo := FALSE; { Set REDO flag to false } EndPos := FilePos(OutFile); { Save current file position } Seek(OutFile, LocalHdrOfs); { Rewind back to file header } With LocalHdr do begin { Update compressed size field } Compressed_Size := EndPos - LocalHdrOfs - SizeOf(LocalHdr) - Filename_Length; Crc32 := Crc32Val; { Update CRC value } { Have we compressed the file? } Redo := (Compressed_Size >= Uncompressed_Size); If Redo then begin { No... } Compress_Method := 0; { ...change stowage type } Compressed_Size := Uncompressed_Size; { ...update compressed size } end {if}; end {with}; Move(LocalHdr, OutBuf^, SizeOf(LocalHdr)); { Put header into output buffer } OutBufIdx := Succ(SizeOf(LocalHdr)); {...adjust buffer index accordingly } Move(ListPtr^.Name[1], OutBuf^[OutBufIdx], Length(ListPtr^.Name)); Inc(OutBufIdx, Length(ListPtr^.Name)); FlushOutput; { Write it now } If Redo then begin { If compression didn't make a smaller file, then ... } Seek(InFile, 0); { Rewind the input file } InputEof := FALSE; { Reset EOF indicator } Read_Block; { Prime the input buffer } While NOT InputEof do begin { Copy input to output } BlockWrite(OutFile, InBuf^, MaxInBufIdx); Read_Block; end {while}; Truncate(Outfile); { Truncate output file } end {then} else begin { Compression DID make a smaller file ... } Seek(OutFile, FileSize(OutFile)); { Move output file pos back to eof } end {if}; End {Update_ZIP_Header}; { --------------------------------------------------------------------------- } Procedure Build_Central_Dir; { Revisit each local file header to build the Central Directory. When done, } { build the End of Central Directory record. } Var BytesRead : Word; SavePos : LongInt; HdrPos : LongInt; CenDirPos : LongInt; Entries : Word; FileName : String; Begin Entries := 0; CenDirPos := FilePos(Outfile); Seek(OutFile, 0); { Rewind output file } HdrPos := FilePos(OutFile); BlockRead(OutFile, LocalHdr, SizeOf(LocalHdr), BytesRead); Repeat BlockRead(OutFile, FileName[1], LocalHdr.FileName_Length, BytesRead); FileName[0] := Chr(LocalHdr.FileName_Length); SavePos := FilePos(OutFile); With CentralHdr do begin Signature := CENTRAL_FILE_HEADER_SIGNATURE; MadeBy_Version := LocalHdr.Extract_Version_Reqd; Move(LocalHdr.Extract_Version_Reqd, Extract_Version_Reqd, 26); File_Comment_Length := 0; Starting_Disk_Num := 0; Internal_Attributes := 0; External_Attributes := ARCHIVE; Local_Header_Offset := HdrPos; Seek(OutFile, FileSize(OutFile)); BlockWrite(Outfile, CentralHdr, SizeOf(CentralHdr)); BlockWrite(OutFile, FileName[1], Length(FileName)); Inc(Entries); end {with}; Seek(OutFile, SavePos + LocalHdr.Compressed_Size); HdrPos := FilePos(OutFile); BlockRead(OutFile, LocalHdr, SizeOf(LocalHdr), BytesRead); Until LocalHdr.Signature = CENTRAL_FILE_HEADER_SIGNATURE; Seek(OutFile, FileSize(OutFile)); With EndHdr do begin Signature := END_OF_CENTRAL_DIR_SIGNATURE; Disk_Number := 0; Central_Dir_Start_Disk := 0; Entries_This_Disk := Entries; Total_Entries := Entries; Central_Dir_Size := CenDirPos - FileSize(OutFile); Start_Disk_Offset := CenDirPos; ZipFile_Comment_Length := 0; BlockWrite(Outfile, EndHdr, SizeOf(EndHdr)); end {with}; end {Build_Central_Dir}; { --------------------------------------------------------------------------- } { The actual Crunching algorithm } { --------------------------------------------------------------------------- } Procedure Shrink(Suffix : Integer); Const LastCode : Integer = 0; { Typed constant, so value retained across calls } Var WhereFound : Integer; CrunchRatio : LongInt; Begin If FirstCh then begin { If just getting started ... } SaveByte := $00; { Initialize our output code buffer } BitsUsed := 0; CodeSize := MINBITS; { Initialize code size to minimum } MaxCode := (1 SHL CodeSize) - 1; LastCode := Suffix; { get first character from input, } FirstCh := FALSE; { and reset the first char flag. } end {then} else begin If Suffix <> -1 then begin { If there's work to do ... } If TableFull then begin { Ok, lets clear the code table (adaptive reset) } Putcode(LastCode); PutCode(SPECIAL); Putcode(CLEARCODE); Clear_Table; Table_Add(LastCode, Suffix); LastCode := Suffix; end {then} else begin If Table_Lookup(LastCode, Suffix, WhereFound) then begin { If LastCode:Suffix pair is found in the code table, then ... } { ... set LastCode to the entry where the pair is located } LastCode := WhereFound; end {then} else begin { Not in table } PutCode(LastCode); { Write current LastCode code } Table_Add(LastCode, Suffix); { Attempt to add to code table } LastCode := Suffix; { Reset LastCode code for new char } If (FreeList^[NextFree] > MaxCode) and (CodeSize < MaxBits) then begin { Time to increase the code size and change the max. code } PutCode(SPECIAL); PutCode(INCSIZE); Inc(CodeSize); MaxCode := (1 SHL CodeSize) -1; end {if}; end {if}; end {if}; end {then} else begin { Nothing to crunch...must be EOF on input } PutCode(LastCode); { Write last prefix code } PutCode(-1); { Tell putcode to flush remaining bits } FlushOutput; { Flush our output buffer } end {if}; end {if}; end {Crunch}; { --------------------------------------------------------------------------- } Procedure Process_Input(Source : String); Var I : Word; PctDone : Integer; Begin If Source = '' then Shrink(-1) else For I := 1 to Length(Source) do begin Inc(BytesIn); If (Pred(BytesIn) MOD TenPercent) = 0 then begin PctDone := Round( 100 * ( BytesIn / FileSize(InFile))); GotoXY(WhereX - 4, WhereY); Write(PctDone:3, '%'); end {if}; CRC32Val := UpdC32(Ord(Source[I]), CRC32Val); Shrink(Ord(Source[I])); end {for}; end {Process_Input}; { --------------------------------------------------------------------------- } { This routine handles processing for one input file } { --------------------------------------------------------------------------- } Procedure Process_One_File; Var OneString : String; Remaining : Word; Begin Read_Block; { Prime the input buffer } FirstCh := TRUE; { 1st character flag for Crunch procedure } Crc32Val := $FFFFFFFF; TenPercent := FileSize(InFile) DIV 10; While NOT InputEof do begin Remaining := Succ(MaxInBufIdx - InBufIdx); If Remaining > 255 then Remaining := 255; If Remaining = 0 then Read_Block else begin Move(InBuf^[InBufIdx], OneString[1], Remaining); OneString[0] := Chr(Remaining); Inc(InBufIdx, Remaining); Process_Input(OneString); end {if}; end {while}; Crc32Val := NOT Crc32Val; Process_Input(''); { This forces EOF processing } end {Process_One_File}; { --------------------------------------------------------------------------- } Procedure Process_All_Files; Var InPath : String; ComprPct : Word; ListNode : NodePtr; Begin If ListHead = NIL then begin Writeln; Writeln('There are no files to shrink!'); Writeln; Halt; end {if}; OpenOutput; ListNode := ListHead; While ListNode <> NIL do begin If OpenInput(Concat(ListNode^.Path, ListNode^.Name)) then begin Write('Processing ', ListNode^.Name, ' '); While WhereX < 28 do Write('.'); Write(' '); BytesIn := 1; BytesOut := 1; TenPercent := FileSize(InFile) DIV 10; Initialize_Data_Structures; Begin_ZIP(ListNode); Process_One_File; Update_ZIP_Header(ListNode); CloseInput; If LocalHdr.Uncompressed_Size > 0 then ComprPct := Round((100.0 * (LocalHdr.Uncompressed_Size - LocalHdr.Compressed_Size)) / LocalHdr.Uncompressed_Size) else ComprPct := 0; GotoXY(WhereX - 4, WhereY); ClrEol; Writeln(' done (compression = ', ComprPct:2, '%)'); end {then} else Writeln('Could not open ', ListNode^.Name, '. Skipping this file ...'); ListNode := ListNode^.Next; end {while}; Build_Central_Dir; CloseOutput; End {Process_All_Files}; { --------------------------------------------------------------------------- } { Main Program (driver) } { --------------------------------------------------------------------------- } Begin Assign(Output, ''); { Reset output to DOS stdout device } Rewrite(Output); Writeln; Writeln(Copyright); Writeln(Version); Writeln; If ParamCheck then begin GetBuffers; { Allocate input and output buffers ... } Build_Data_Structures; { ... and other data structures required } Process_All_Files; { Crunch the file } DropBuffers; { Be polite and de-allocate Buffer memory and } Destroy_Data_Structures; { other allocated data structures } end {if}; End.
unit USlideVariables; interface uses Classes, UFastKeysSS; procedure DetectSlideVariables(strText: string; slVariables: TStringList); procedure CleanupSlideVariables(vars: TFastKeyValuesSS; slVariables: TStringList); function EditSlideVariables(vars, options: TFastKeyValuesSS): boolean; implementation uses RegularExpressionsCore, Dialogs, UfrmEditVariables; procedure DetectSlideVariables(strText: string; slVariables: TStringList); var regex: TPerlRegEx; strKey: string; begin regex := TPerlRegEx.Create; try regex.RegEx := '%([^<>]+)%'; regex.Options := [preUnGreedy]; regex.Subject := strText; regex.Start := 1; while regex.MatchAgain do begin strKey := copy(regex.MatchedText, 2, Length(regex.MatchedText) -2); slVariables.Add(strKey); end; finally regex.Free; end; end; procedure CleanupSlideVariables(vars: TFastKeyValuesSS; slVariables: TStringList); var index, iFound: integer; begin index := 0; while index < vars.Count do begin iFound := slVariables.IndexOf(vars.KeyOfIndex[index]); if iFound <> -1 then begin slVariables.Delete(iFound); inc(index); end else begin vars.Delete(index); end; end; for index := 0 to slVariables.Count -1 do begin vars[slVariables[index]] := ''; end; end; function EditSlideVariables(vars, options: TFastKeyValuesSS): boolean; begin Result := EditFastKeySSVariables(vars, options); end; end.
(*********************************************************************) (* Programmname : VENCOLOR.PAS V1.6 *) (* Programmautor : Michael Rippl *) (* Compiler : Quick Pascal V1.0 *) (* Inhalt : Farbenverwaltung des Kopierprogramms Venus V2.1 *) (* Bemerkung : - *) (* Letzte Žnderung : 01-Mar-1991 *) (*********************************************************************) UNIT VenColor; INTERFACE USES Primitiv; (* Units einbinden *) VAR cBlack, (* Farbe Schwarz *) cBlue, (* Farbe Blau *) cCyan, (* Farbe Cyan *) cRed, (* Farbe Rot *) cMagenta, (* Farbe Magenta *) cLightGrey, (* Farbe Hell-Grau *) cLightGreen, (* Farbe Hell-Grn *) cLightCyan, (* Farbe Hell-Cyan *) cYellow, (* Farbe Gelb *) cWhite, (* Farbe Weiá *) cLightRed, (* Farbe Hell-Rot *) cLightMagenta : Colors; (* Farbe Hell-Magenta *) (* Diese Prozedur setzt die Farben fr eine Farbgrafikkarte *) PROCEDURE SetColorGraphics; (* Diese Prozedur setzt die Farben fr eine Monochromgrafikkarte *) PROCEDURE SetMonochromGraphics; (* Diese Prozedur modifiziert die Farbpalette *) PROCEDURE ModifyColors(VAR ColBlack, ColBlue, ColCyan, ColRed, ColMag, ColLiGrey, ColLiGrn, ColLiCyan, ColYel, ColWh, ColLiRed, ColLiMag : Colors); IMPLEMENTATION (* Diese Prozedur setzt die Farben fr eine Farbgrafikkarte *) PROCEDURE SetColorGraphics; BEGIN cBlack := Black; (* Farbwerte eintragen *) cBlue := Blue; cCyan := Cyan; cRed := Red; cMagenta := Magenta; cLightGrey := LightGrey; cLightGreen := LightGreen; cLightCyan := LightCyan; cYellow := Yellow; cWhite := White; cLightRed := LightRed; cLightMagenta := LightMagenta; END; (* SetColorGraphics *) (* Diese Prozedur setzt die Farben fr eine Monochromgrafikkarte *) PROCEDURE SetMonochromGraphics; BEGIN cBlack := Black; (* Farbwerte eintragen *) cBlue := Black; cCyan := LightGrey; cRed := LightGrey; cMagenta := LightGrey; cLightGrey := LightGrey; cLightGreen := White; cLightCyan := White; cYellow := White; cWhite := White; cLightRed := White; cLightMagenta := White; END; (* SetMonochromGraphics *) (* Diese Prozedur modifiziert die Farbpalette *) PROCEDURE ModifyColors(VAR ColBlack, ColBlue, ColCyan, ColRed, ColMag, ColLiGrey, ColLiGrn, ColLiCyan, ColYel, ColWh, ColLiRed, ColLiMag : Colors); BEGIN cBlack := ColBlack; (* Farbwerte ver„ndern *) cBlue := ColBlue; cCyan := ColCyan; cRed := ColRed; cMagenta := ColMag; cLightGrey := ColLiGrey; cLightGreen := ColLiGrn; cLightCyan := ColLiCyan; cYellow := ColYel; cWhite := ColWh; cLightRed := ColLiRed; cLightMagenta := ColLiMag; END; (* ModifyColors *) END. (* VenColor *)
unit UfrmPesquisaBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls; type TfrmPesquisaBase = class(TForm) pnTop: TPanel; DBGrid: TDBGrid; dsTabela: TDataSource; lblOpcao: TLabel; lblPesquisa: TLabel; cbCampo: TComboBox; edtPesquisa: TEdit; btnPesquisa: TButton; Panel1: TPanel; btnConfirmar: TButton; btnCancelar: TButton; fdqTabela2: TFDQuery; procedure btnCancelarClick(Sender: TObject); procedure btnConfirmarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnPesquisaClick(Sender: TObject); procedure DBGridKeyPress(Sender: TObject; var Key: Char); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } blConfirma:Boolean; end; var frmPesquisaBase: TfrmPesquisaBase; implementation {$R *.dfm} uses UfrmConexao; procedure TfrmPesquisaBase.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmPesquisaBase.btnConfirmarClick(Sender: TObject); begin blConfirma:=true; Close; end; procedure TfrmPesquisaBase.btnPesquisaClick(Sender: TObject); begin DBGrid.SetFocus; end; procedure TfrmPesquisaBase.DBGridKeyPress(Sender: TObject; var Key: Char); begin If key = #13 then Begin blConfirma:=true; Close; end; end; procedure TfrmPesquisaBase.FormCreate(Sender: TObject); begin blConfirma:=false; end; procedure TfrmPesquisaBase.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then //tem que verificar o keyPreviw begin case application.MessageBox('Deseja realmente fechar o programa?', 'Confirmação', MB_yesno + MB_iconInformation) of mrNo, mrCancel: Application.MessageBox('retomando os testes.','Continuando...'); mrYes: Close; end; end; if (Key = #13) then begin //Key := #0; Perform(Wm_NextDlgCtl,0,0); end; end; end.
unit DataModule.Conexao; interface uses FMX.Forms, System.SysUtils, System.Classes, System.IOUtils, Data.DB, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.FMXUI.Wait, FireDAC.Comp.Client, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet; type TDMConexao = class(TDataModule) Conn: TFDConnection; Qry: TFDQuery; procedure DataModuleCreate(Sender: TObject); procedure ConnBeforeConnect(Sender: TObject); strict private class var _instance : TDMConexao; private { Private declarations } FFileBase : String; public { Public declarations } class function GetInstance() : TDMConexao; class function Instanciado : Boolean; class function GetLastInsertRowID : Integer; class function GetNexID(aTableName, aFieldName : String) : Integer; end; //var // DMConexao: TDMConexao; // implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TDMConexao } uses System.UITypes; procedure TDMConexao.ConnBeforeConnect(Sender: TObject); begin Conn.Params.Values['DriverID'] := 'SQLite'; Conn.Params.Values['Database'] := FFileBase; end; procedure TDMConexao.DataModuleCreate(Sender: TObject); begin Conn.Connected := False; Conn.Params.BeginUpdate; Conn.Params.Clear; Conn.Params.EndUpdate; {$IFDEF MSWINDOWS} FFileBase := TPath.Combine(System.SysUtils.GetCurrentDir, 'db\financeiro_simples.db'); {$ELSE} FFileBase := TPath.Combine(TPath.GetDocumentsPath, 'financeiro_simples.db'); {$ENDIF} end; class function TDMConexao.GetInstance: TDMConexao; begin if not Assigned(_instance) then _instance := TDMConexao.Create(Application); Result := _instance; end; class function TDMConexao.GetLastInsertRowID: Integer; var aQry : TFDQuery; begin Result := 0; aQry := TFDQuery.Create(nil); try aQry.Connection := TDMConexao.GetInstance().Conn; with aQry, SQL do begin BeginUpdate; Clear; Add('SELECT last_insert_rowid() as ID'); EndUpdate; Open; Result := FieldByName('ID').AsInteger; end; finally aQry.DisposeOf; end; end; class function TDMConexao.GetNexID(aTableName, aFieldName: String): Integer; var aQry : TFDQuery; begin Result := 0; aQry := TFDQuery.Create(nil); try aQry.Connection := TDMConexao.GetInstance().Conn; with aQry, SQL do begin BeginUpdate; Clear; Add('SELECT max(' + aFieldName + ') as ID from ' + aTableName); EndUpdate; Open; if not FieldByName('ID').IsNull then Result := (FieldByName('ID').AsInteger + 1) else Result := 1; end; finally aQry.DisposeOf; end; end; class function TDMConexao.Instanciado: Boolean; begin Result := Assigned(_instance); end; end.
unit HTTPURIElement; interface uses SysUtils, StrUtils, HTTPURIElementField, Generics.Collections; type IHTTPURIElement = interface ['{9191363A-F8FA-414D-9BC4-AA6479BFBB8D}'] function Index: Cardinal; function Content: String; function Fields: THTTPURIElementFieldList; end; THTTPURIElement = class sealed(TInterfacedObject, IHTTPURIElement) strict private _Index: Cardinal; _Content: String; _Fields: THTTPURIElementFieldList; public function Index: Cardinal; function Content: String; function Fields: THTTPURIElementFieldList; constructor Create(const Index: Cardinal; const Content: String); destructor Destroy; override; class function New(const Index: Cardinal; const Content: String): IHTTPURIElement; end; THTTPURIElementList = class sealed(TList<IHTTPURIElement>) strict private procedure ParseURI(const URI: String); public function ItemByName(const Name: String): IHTTPURIElement; class function New: THTTPURIElementList; class function NewByURI(const URI: String): THTTPURIElementList; end; implementation { THTTPURIElement } function THTTPURIElement.Index: Cardinal; begin Result := _Index; end; function THTTPURIElement.Content: String; begin Result := _Content; end; function THTTPURIElement.Fields: THTTPURIElementFieldList; begin Result := _Fields; end; constructor THTTPURIElement.Create(const Index: Cardinal; const Content: String); begin _Index := Index; _Fields := THTTPURIElementFieldList.NewByContent(Content); if _Fields.IsEmpty then _Content := Content else _Content := Copy(Content, 1, Pred(Pos('?', Content))); end; destructor THTTPURIElement.Destroy; begin _Fields.Free; inherited; end; class function THTTPURIElement.New(const Index: Cardinal; const Content: String): IHTTPURIElement; begin Result := THTTPURIElement.Create(Index, Content); end; { THTTPURIElementList } procedure THTTPURIElementList.ParseURI(const URI: String); Var SeparatorPos, PosOffset: Integer; Text: String; begin PosOffset := 1; repeat SeparatorPos := PosEx('/', URI, PosOffset); if SeparatorPos > 0 then begin Text := Copy(URI, PosOffset, SeparatorPos - PosOffset); if Length(Text) > 0 then Add(THTTPURIElement.New(Count, Text)); PosOffset := Succ(SeparatorPos); end; until SeparatorPos < 1; Text := Copy(URI, PosOffset, Succ(Length(URI) - PosOffset)); if Length(Text) > 0 then Add(THTTPURIElement.New(Count, Text)); end; function THTTPURIElementList.ItemByName(const Name: String): IHTTPURIElement; var Item: IHTTPURIElement; begin Result := nil; for Item in Self do if SameText(Name, Item.Content) then Exit(Item); end; class function THTTPURIElementList.New: THTTPURIElementList; begin Result := THTTPURIElementList.Create; end; class function THTTPURIElementList.NewByURI(const URI: String): THTTPURIElementList; begin Result := THTTPURIElementList.New; Result.ParseURI(URI); end; end.
unit FramePriCone; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PMBuild, StdCtrls, ComCtrls, Spin, FPSpin; type TPriConeFrame = class(TFrame) ConeGroup: TGroupBox; PageControl1: TPageControl; GeomPage: TTabSheet; TexCoordsSidePage: TTabSheet; Slices: TSpinEdit; SlicesSector: TSpinEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; RadiusT: TFPSpinEdit; RadiusB: TFPSpinEdit; SmoothCheck: TCheckBox; OriginLabel: TLabel; SizeLabel: TLabel; SizeV: TSpinEdit; SizeU: TSpinEdit; OrigV: TSpinEdit; OrigU: TSpinEdit; TexCoordsBasePage: TTabSheet; Label7: TLabel; UVCenterUT: TSpinEdit; UVCenterVT: TSpinEdit; UVRadiusT: TSpinEdit; Label8: TLabel; UVCenterUB: TSpinEdit; UVCenterVB: TSpinEdit; UVRadiusB: TSpinEdit; function Fill(Pri: TPMBPrimitive): Boolean; procedure Clear; procedure RadiusBChange(Sender: TObject); procedure RadiusTChange(Sender: TObject); procedure SlicesChange(Sender: TObject); procedure SlicesSectorChange(Sender: TObject); procedure SmoothCheckClick(Sender: TObject); procedure UVBaseBChange(Sender: TObject); procedure UVBaseTChange(Sender: TObject); procedure UVSideChange(Sender: TObject); private FPri: TPMBPrimitiveCone; end; implementation {$R *.dfm} function TPriConeFrame.Fill(Pri: TPMBPrimitive): Boolean; begin Result:=Pri.PriType=PrimitiveCone; if Result then begin FPri:=Pri as TPMBPrimitiveCone; SmoothCheck.Checked:=FPri.Smooth; Slices.Value:=FPri.Slices; SlicesSector.Value:=FPri.SlicesSector; RadiusT.Value:=FPri.RadiusT; RadiusB.Value:=FPri.RadiusB; if FPri.TexGenUV then begin OrigU.Value:=FPri.UVSide.OrigU; OrigV.Value:=FPri.UVSide.OrigV; SizeU.Value:=FPri.UVSide.SizeU; SizeV.Value:=FPri.UVSide.SizeV; UVCenterUT.Value:=FPri.UVBaseT.CenterU; UVCenterVT.Value:=FPri.UVBaseT.CenterV; UVRadiusT.Value:=FPri.UVBaseT.Radius; UVCenterUB.Value:=FPri.UVBaseB.CenterU; UVCenterVB.Value:=FPri.UVBaseB.CenterV; UVRadiusB.Value:=FPri.UVBaseB.Radius; end; end else FPri:=nil; end; procedure TPriConeFrame.Clear; begin FPri:=nil; end; procedure TPriConeFrame.RadiusBChange(Sender: TObject); begin if Assigned(FPri) and ((Sender as TFPSpinEdit).Text<>'') and ((Sender as TFPSpinEdit).Text<>'-') or ((Sender as TFPSpinEdit).Text=DecimalSeparator) then FPri.RadiusB:=RadiusB.Value; end; procedure TPriConeFrame.RadiusTChange(Sender: TObject); begin if Assigned(FPri) and ((Sender as TFPSpinEdit).Text<>'') and ((Sender as TFPSpinEdit).Text<>'-') or ((Sender as TFPSpinEdit).Text=DecimalSeparator) then FPri.RadiusT:=RadiusT.Value; end; procedure TPriConeFrame.SlicesChange(Sender: TObject); begin if Assigned(FPri) and ((Sender as TSpinEdit).Text<>'') and ((Sender as TSpinEdit).Text<>'-') then FPri.Slices:=Slices.Value; end; procedure TPriConeFrame.SlicesSectorChange(Sender: TObject); begin if Assigned(FPri) and ((Sender as TSpinEdit).Text<>'') and ((Sender as TSpinEdit).Text<>'-') then FPri.SlicesSector:=SlicesSector.Value; end; procedure TPriConeFrame.SmoothCheckClick(Sender: TObject); begin if Assigned(FPri) then FPri.Smooth:=SmoothCheck.Checked; end; procedure TPriConeFrame.UVBaseBChange(Sender: TObject); var UVBase: TPMUVCircle; begin if not Assigned(FPri) or ((Sender as TSpinEdit).Text='') or ((Sender as TSpinEdit).Text='-') then Exit; UVBase:=FPri.UVBaseB; if Sender=UVCenterUB then UVBase.CenterU:=UVCenterUB.Value; if Sender=UVCenterVB then UVBase.CenterV:=UVCenterVB.Value; if Sender=UVRadiusB then UVBase.Radius:=UVRadiusB.Value; FPri.UVBaseB:=UVBase; end; procedure TPriConeFrame.UVBaseTChange(Sender: TObject); var UVBase: TPMUVCircle; begin if not Assigned(FPri) or ((Sender as TSpinEdit).Text='') or ((Sender as TSpinEdit).Text='-') then Exit; UVBase:=FPri.UVBaseT; if Sender=UVCenterUT then UVBase.CenterU:=UVCenterUT.Value; if Sender=UVCenterVT then UVBase.CenterV:=UVCenterVT.Value; if Sender=UVRadiusT then UVBase.Radius:=UVRadiusT.Value; FPri.UVBaseT:=UVBase; end; procedure TPriConeFrame.UVSideChange(Sender: TObject); var UVSide: TPMUVRect; begin if not Assigned(FPri) or ((Sender as TSpinEdit).Text='') or ((Sender as TSpinEdit).Text='-') then Exit; UVSide:=FPri.UVSide; if Sender=OrigU then UVSide.OrigU:=OrigU.Value; if Sender=OrigV then UVSide.OrigV:=OrigV.Value; if Sender=SizeU then UVSide.SizeU:=SizeU.Value; if Sender=SizeV then UVSide.SizeV:=SizeV.Value; FPri.UVSide:=UVSide; end; end.
unit U3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IniFiles; type TNP01VN01Form3 = class(TForm) lst1: TListBox; btn1: TButton; btn2: TButton; edt1: TEdit; btn3: TButton; btn4: TButton; procedure FormCreate(Sender: TObject); procedure btn3Click(Sender: TObject); procedure btn4Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lst1DblClick(Sender: TObject); procedure btn1Click(Sender: TObject); procedure btn2Click(Sender: TObject); private FFilterList: TMemIniFile; FFilterChange: Boolean; procedure SetFilterList(const Value: TMemIniFile); procedure SetFilterChange(const Value: Boolean); public property FilterList: TMemIniFile read FFilterList write SetFilterList; property FilterChange: Boolean read FFilterChange write SetFilterChange; procedure SetFilter; end; implementation uses U1; const FilterFile = 'filter.ini'; {$R *.dfm} procedure TNP01VN01Form3.FormCreate(Sender: TObject); var s: string; begin FFilterChange := False; s := U1.LocalStorage + FilterFile; FFilterList := TMemIniFile.Create(s); if FileExists(s) then begin FFilterList.ReadSections(lst1.Items); end; end; procedure TNP01VN01Form3.SetFilterChange(const Value: Boolean); begin FFilterChange := Value; end; procedure TNP01VN01Form3.SetFilterList(const Value: TMemIniFile); begin FFilterList := Value; end; procedure TNP01VN01Form3.btn3Click(Sender: TObject); var i: Integer; begin i := 0; if lst1.Items.Count > 0 then while (i < lst1.Items.Count) and (lst1.Items[i] <> edt1.Text) do Inc(i); if i = lst1.Items.Count then begin FFilterChange := True; lst1.Items.Add(edt1.Text); FFilterList.WriteString(edt1.Text, 'ki', U1.NP01VN01Form1.medtKI.Text); FFilterList.WriteString(edt1.Text, 'shifr', U1.NP01VN01Form1.medtShifr.Text); FFilterList.WriteString(edt1.Text, 'cp', U1.NP01VN01Form1.medtCP.Text); FFilterList.WriteString(edt1.Text, 'docnum', U1.NP01VN01Form1.medt1.Text); FFilterList.WriteString(edt1.Text, 'docdate', U1.NP01VN01Form1.medt2.Text); FFilterList.WriteInteger(edt1.Text, 'dategr', U1.NP01VN01Form1.rg1.ItemIndex); FFilterList.WriteString(edt1.Text, 'date1', U1.NP01VN01Form1.medtDate1.Text); FFilterList.WriteString(edt1.Text, 'date2', U1.NP01VN01Form1.medtDate2.Text); FFilterList.WriteBool(edt1.Text, 'q1', U1.NP01VN01Form1.btnQ1.Down); FFilterList.WriteBool(edt1.Text, 'q2', U1.NP01VN01Form1.btnQ2.Down); FFilterList.WriteBool(edt1.Text, 'q3', U1.NP01VN01Form1.btnQ3.Down); FFilterList.WriteBool(edt1.Text, 'q4', U1.NP01VN01Form1.btnQ4.Down); FFilterList.WriteBool(edt1.Text, 'table', U1.NP01VN01Form1.btnTable.Down); FFilterList.WriteBool(edt1.Text, 'doc', U1.NP01VN01Form1.btnDoc.Down); end else begin ShowMessage('Фильтр с таким именем уже существует!'); lst1.Selected[i] := True; edt1.SetFocus; edt1.SelectAll; end; end; procedure TNP01VN01Form3.btn4Click(Sender: TObject); begin if lst1.ItemIndex > -1 then begin FilterChange := True; FilterList.EraseSection(lst1.Items[lst1.itemIndex]); lst1.DeleteSelected; end; end; procedure TNP01VN01Form3.FormDestroy(Sender: TObject); begin try if FFilterChange then FFilterList.UpdateFile; finally FreeAndNil(FFilterList); end; end; procedure TNP01VN01Form3.SetFilter; begin if lst1.ItemIndex > -1 then begin U1.NP01VN01Form1.medtKI.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'ki', ''); U1.NP01VN01Form1.medtShifr.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'shifr', ''); U1.NP01VN01Form1.medtCP.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'cp', ''); U1.NP01VN01Form1.medt1.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'docnum', ''); U1.NP01VN01Form1.medt2.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'docdate', ''); U1.NP01VN01Form1.rg1.ItemIndex := FFilterList.ReadInteger(lst1.Items[lst1.itemIndex], 'dategr', -1); U1.NP01VN01Form1.medtDate1.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'date1', ''); U1.NP01VN01Form1.medtDate2.Text := FFilterList.ReadString(lst1.Items[lst1.itemIndex], 'date2', ''); U1.NP01VN01Form1.btnQ1.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'q1', False); U1.NP01VN01Form1.btnQ2.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'q2', False); U1.NP01VN01Form1.btnQ3.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'q3', False); U1.NP01VN01Form1.btnQ4.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'q4', False); U1.NP01VN01Form1.btnTable.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'table', False); U1.NP01VN01Form1.btnDoc.Down := FFilterList.ReadBool(lst1.Items[lst1.itemIndex], 'doc', False); end; end; procedure TNP01VN01Form3.lst1DblClick(Sender: TObject); begin SetFilter; Self.Close; end; procedure TNP01VN01Form3.btn1Click(Sender: TObject); begin SetFilter; Self.Close; end; procedure TNP01VN01Form3.btn2Click(Sender: TObject); begin Self.Close; end; end.
unit controller.registration; {$mode delphi}{$H+} {$ModeSwitch nestedprocvars} interface uses SysUtils, Classes, httpdefs, fpHTTP, fpWeb, FPImage, BGRABitmap, BGRABitmapTypes, controller.base, controller.registration.dto, controller.image.dto; type TRegistrationValidateCallback = function(Const AURL : String) : Boolean; var //to add validations rules for url's, add them to this array VALIDATE_CALLBACKS : TArray<TRegistrationValidateCallback>; MAX_IMAGE_WIDTH : Integer; MAX_IMAGE_HEIGHT : Integer; type { TRegistrationController } (* controller that handles the starting step of processing image requests. endpoints will allow image client to validate whether or not a URL is acceptable, begin process, as well as cancelling a a request *) TRegistrationController = class(TBaseController) private //action for handling validating urls procedure ValidateAction(Sender : TObject; ARequest : TRequest; AResponse : TResponse; var Handled : Boolean); //action for handling registering an image to be processed procedure RegisterAction(Sender : TObject; ARequest : TRequest; AResponse : TResponse; var Handled : Boolean); //action to attempt to cancel an in progress image request procedure CancelAction(Sender : TObject; ARequest : TRequest; AResponse : TResponse; var Handled : Boolean); procedure InitRegistrationTable; strict protected procedure DoInitialize(); override; function DoInitializeActions(): TActions; override; //async processing for a url class procedure StartProcessing(Constref ARequest : TRegisterURLRequest; Constref AResponse : TRegisterURLResponse); static; public (* uses validation rules to determine whether or not a particular url is valid for processing. this could be as simple as domain checking, or could do text analysis on the resource, etc... note: by default all images that *can* be processed will be accepted. it's up to individual land owners who use this service to implement the custom validation rules *) function ValidateURL(Constref AValidation : TValidateURLRequest) : Boolean; //begins the processing step as long as the URL is valid function RegisterImage(Constref ARequest : TRegisterURLRequest; out Response : TRegisterURLResponse) : Boolean; //will cancel the request as long as the process is in-progress function CancelRequest() : Boolean; //provided an external image id, will return the internal primary key function LookupImageID(Const AImageToken : String; Out ID : Integer) : Boolean; end; function DitherImageStream(Const AImage : TStream; Const AURL : String; Const ABitmap : TBGRABitmap; Out Error : String) : Boolean; function ConstructDCLImageResponse(Const AImage : TBGRABitmap; Out Response : TImageResponse; Out Error : String) : Boolean; var RegistrationController: TRegistrationController; implementation uses Interfaces, Graphics, bgradithering, BGRAPalette, BGRAColorQuantization, fphttpclient, controller.status, controller.dto, ezthreads, ezthreads.collection, controller.image, opensslsockets, fgl, fpjson, jsonparser; var Collection : IEZCollection; Palette : TBGRAApproxPalette; {$R *.lfm} procedure InitializePalette; begin //for now we initialize this in here rather than exposing the //palette to a config, since we don't want to overload dcl Palette := TBGRAApproxPalette.Create( [ TBGRAPixel.New(255, 0, 0), //red TBGRAPixel.New(188, 143, 143), //pink TBGRAPixel.New(0, 255, 0), //green TBGRAPixel.New(0, 0, 255), //blue TBGRAPixel.New(0, 0, 0), //black TBGRAPixel.New(166, 42, 42), //brown TBGRAPixel.New(128, 128, 128), //grey TBGRAPixel.New(255, 255, 255), //white TBGRAPixel.New(255, 255, 0), //yellow TBGRAPixel.New(255, 128, 0), //orange TBGRAPixel.New(128, 0, 255) //purple ] ); end; function DitherImageStream(Const AImage : TStream; Const AURL : String; Const ABitmap : TBGRABitmap; Out Error : String) : Boolean; var LTask: TDitheringTask; LReader: TFPCustomImageReader; LBitmap , LResampled, LDithered: TBGRACustomBitmap; LExt: String; LFormat: TBGRAImageFormat; begin Result := False; try AImage.Position := 0; LExt := AURL.Substring(AURL.LastIndexOf('.')); if LExt.IsEmpty then begin Error := 'DitherImageStream::invalid/empty extension'; Exit; end; //initialize reader objects LFormat := SuggestImageFormat(LExt); LReader := DefaultBGRAImageReader[LFormat].Create; LBitmap := TBGRABitmap.Create; try //try to load LBitmap.LoadFromStream(AImage, LReader, []); //resize the image to the configured dimensions LResampled := LBitmap.Resample(MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT); //initialize the dither task LTask := CreateDitheringTask( daNearestNeighbor, //algorithm for dithering LResampled, //source image Palette, //use the reduced color palette True, //ignore alpha for now LResampled.GetImageBounds() ); LTask.DrawMode := dmSet; try //begin dithering LDithered := LTask.Execute; //update result with the dithered result ABitmap.Assign(LDithered); //cleanup LDithered.Free; //success Result := True; finally LResampled.Free; LTask.Free; end; finally LBitmap.Free; LReader.Free; end; except on E : Exception do Error := E.Message; end; end; function ConstructDCLImageResponse(Const AImage : TBGRABitmap; Out Response : TImageResponse; Out Error : String) : Boolean; type TRectangle = packed record TopLeft, TopRight, BottomLeft, BottomRight: TPoint; end; TColorRect = packed record Rect : TRectangle; Red : Byte; Green : Byte; Blue : Byte; end; TColorRectArray = TArray<TColorRect>; TLookupArray = packed array of array of Boolean; //key is int value of color TColorMap = TFPGMap<Integer, TColorRectArray>; var W, H, BR, LCurrentRow, TL, TR, BL, J, K, I, Top, Bottom: Integer; LPoints : TRectangle; LRect : TColorRect; LRects : TColorRectArray; LLookup : TLookupArray; LColor: TBGRAPixel; LCurPixel: TBGRAPixel; LAreaCalc, LFound, LCloseRect: Boolean; LCommands : TDrawCommands; LCommand : TDrawCommand; begin (* essentially the below algorithm will attempt to "vectorize" an input raster image into a series of draw rect Response (color/rect). this won't be perfect, and isn't a trivial problem to solve, but due to the fact that dcl doesn't have native canvas commands or support to load a damn web image, it's the best stab I have at the problem right now... the upside to this, is that it should be renderable to any client that can draw to a canvas and who needs to dithered scaleable image (which may be useful for other things...) *) Result := False; SetLength(LRects, 0); try W := AImage.Width; H := AImage.Height; if (W <= 0) or (H <= 0) then raise Exception.Create('ConstructDCLImageJSON::invalid dimensions'); //for every color in the palette, we need to construct rects to draw SetLength(LLookup, W, H); //define to the size of our image for I := 0 to Pred(Palette.Count) do begin //get the color we're searching for from the palette LColor := Palette.Color[I]; LFound := False; //iterate the pixels of the image to populate the lookup array for J := 0 to Pred(W) do for K := 0 to Pred(H) do begin LCurPixel := AImage.GetPixel(J, K); if (LCurPixel.red = LColor.red) and (LCurPixel.green = LColor.green) and (LCurPixel.blue = LColor.blue) then begin LLookup[J][K] := True; LFound := True; end else LLookup[J][K] := False; end; //didn't find this color, move to the next if not LFound then Continue; //current working column in the array LCurrentRow := 0; //continue as long as we have un-filled areas while True do begin //covered this entire color if LCurrentRow >= H then Break; //initialize positional markers for the rect Top := LCurrentRow; //row marker for top corners TL := -1; //top-left corner TR := -1; //top-right corner BL := -1; //bottom-left corner BR := -1; //bottom-right corner Bottom := LCurrentRow; //row marker for bottom corners LCloseRect := False; while True do begin //first we find the top corners if TL < 0 then begin for J := 0 to Pred(W) do begin if (TL < 0) and LLookup[J][Top] then TL := J //break in color else if not LLookup[J][Top] then begin //continue scanning for a top left if we still have pixels if (TL < 0) and (J < Pred(W)) then Continue else begin //if right corner hasn't been set yet, then it equals the top-left if TR < 0 then TR := TL; //this row is no longer valid Break; end; end else TR := J; end; if TR <= TL then TR := TL; end //otherwise we have the top, need to find the bottom else begin //move the bottom further than top Bottom := Succ(Bottom); //exceeded bounds if Bottom >= H then begin if BL < 0 then BL := TL; if BR < 0 then BR := TR; Bottom := Pred(Bottom); LCloseRect := True; end else begin //flag for area calculation LAreaCalc := False; for J := TL to TR do begin (* since we already know the top left, make sure we can anchor the bottom left at the current row aligned to top otherwise we will need to perform area calculations to find if adjusting the top will be beneficial (largest rect possible) *) if (BL < 0) and LLookup[TL][Bottom] then BL := J //found color, but bottom-left is different than top-left else if (BL < 0) and LLookup[J][Bottom] then begin BL := J; LAreaCalc := True; end //break in color else if not LLookup[J][Bottom] then begin //continue scanning for a bottom left if we still have pixels if (BL < 0) and (J < Pred(TR)) then Continue //invalid row else if BL < 0 then begin Dec(Bottom); LCloseRect := True; Break; end //valid row, but possible area recalc else begin //if right corner hasn't been set yet, then it equals the bottom-left if BR < 0 then BR := BL; //we've broken earlier than the previous rows if BR < TR then LAreaCalc := True //finished this rect else begin //discard this bottom Dec(Bottom); LCloseRect := True; Break; end; end; end else BR := J; if LAreaCalc then begin //check if the previous area is greater than the new if (Succ(TR) - TL) * (Bottom - Top) //previous > (Succ(BR) - BL) * (Succ(Bottom) - Top) //new then begin Dec(Bottom); BL := TL; BR := TR; LCloseRect := True; Break; end //reduced corners but having new row was greater area else begin //shrink top to fit bottom TL := BL; TR := BR; end; end; end; end; end; //found a rect or failed to find one if LCloseRect or (TL < 0) then Break; end; //when building the rect, we exhausted this rows pixels if TL < 0 then begin Inc(LCurrentRow); Continue; end //add the rect else begin //update the color LRect.Red := LColor.red; LRect.Green := LColor.green; LRect.Blue := LColor.blue; //update the rectangle portion with LPoints do begin TopLeft.X := TL; TopLeft.Y := Top; TopRight.X := TR; TopRight.Y := Top; BottomLeft.X := BL; BottomLeft.Y := Bottom; BottomRight.X := BR; BottomRight.Y := Bottom; end; LRect.Rect := LPoints; //increase size and add to result SetLength(LRects, Succ(Length(LRects))); LRects[High(LRects)] := LRect; //clear the lookup for this rect for J := TL to TR do for K := Top to Bottom do LLookup[J][K] := False; end; //right corner went to bounds if TR >= Pred(W) then Inc(LCurrentRow); end; end; SetLength(LCommands, Length(LRects)); for J := 0 to High(LCommands) do begin //translate rect to command LRect := LRects[J]; LCommand.Red := LRect.Red; LCommand.Green := LRect.Green; LCommand.Blue := LRect.Blue; LCommand.Alpha := 255; //no alpha support right now //translate x's LCommand.TopLeftX := LRect.Rect.TopLeft.X; LCommand.TopRightX := LRect.Rect.TopRight.X; LCommand.BottomLeftX := LRect.Rect.BottomLeft.X; LCommand.BottomRightX := LRect.Rect.BottomRight.X; //translate y's LCommand.TopLeftY := LRect.Rect.TopLeft.Y; LCommand.TopRightY := LRect.Rect.TopRight.Y; LCommand.BottomLeftY := LRect.Rect.BottomLeft.Y; LCommand.BottomRightY := LRect.Rect.BottomRight.Y; //update the command LCommands[J] := LCommand; end; //now set the commands in the response Response.Commands := LCommands; //success Result := True; except on E : Exception do Error := E.Message; end; end; { TRegistrationController } procedure TRegistrationController.ValidateAction(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean); var LValidate : TValidateURLRequest; LResult : TBoolResponse; begin try LResult.Success := False; AResponse.ContentType := 'application/json'; AResponse.SetCustomHeader('Access-Control-Allow-Origin', '*'); Handled := True; LogRequester('ValidateAction::', ARequest); //try and parse the token LValidate.FromJSON(ARequest.Content); //try to validate if not ValidateURL(LValidate) then AResponse.Content := LResult.ToJSON else begin LResult.Success := True; AResponse.Content := LResult.ToJSON; end; except on E : Exception do begin LogError(E.Message); AResponse.Content := GetErrorJSON('unable to validate - server error'); end end; end; procedure TRegistrationController.RegisterAction(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean); var LRequest : TRegisterURLRequest; LResult : TRegisterURLResponse; LGuid, LError: String; begin try AResponse.ContentType := 'application/json'; AResponse.SetCustomHeader('Access-Control-Allow-Origin', '*'); Handled := True; LogRequester('RegisterAction::', ARequest); //try and parse the request LRequest.FromJSON(ARequest.Content); //perform registrations if not RegisterImage(LRequest, LResult) then begin AResponse.Content := GetErrorJSON('unable to register image'); Exit; end; //success AResponse.Content := LResult.ToJSON; except on E : Exception do begin LogError(E.Message); AResponse.Content := GetErrorJSON('unable to register image - server error'); end end; end; procedure TRegistrationController.CancelAction(Sender: TObject; ARequest: TRequest; AResponse: TResponse; var Handled: Boolean); begin end; procedure TRegistrationController.InitRegistrationTable; var LError: String; begin //initialize our table if it doesn't exist if not ExecuteSQL( 'CREATE TABLE IF NOT EXISTS registration(' + ' "id" Integer NOT NULL PRIMARY KEY AUTOINCREMENT,' + ' "token" varchar(128) NOT NULL,' + ' "user_key" varchar(50) NOT NULL,' + ' "parcel_identity" varchar(25) NOT NULL,' + ' "url" varchar(2000) NOT NULL,' + ' "create_date" datetime NOT NULL DEFAULT (datetime(''now'')));', LError ) then LogError(LError); end; procedure TRegistrationController.DoInitialize(); begin inherited DoInitialize(); InitRegistrationTable; end; function TRegistrationController.DoInitializeActions(): TActions; var I : Integer; LAction : TAction; begin Result := inherited DoInitializeActions(); //set the starting index to the last index of result I := High(Result); //if base added some default actions, then increment the index if I >= 0 then Inc(I); //initialize the registration route actions SetLength(Result, Length(Result) + 3); LAction.Name := 'validate'; LAction.Action := ValidateAction; Result[I] := LAction; LAction.Name := 'register'; LAction.Action := RegisterAction; Result[I + 1] := LAction; LAction.Name := 'cancel'; LAction.Action := CancelAction; Result[I + 2] := LAction; end; function TRegistrationController.ValidateURL(Constref AValidation: TValidateURLRequest): Boolean; var I: Integer; begin Result := True; for I := 0 to High(VALIDATE_CALLBACKS) do if not VALIDATE_CALLBACKS[I](AValidation.URL) then Exit(False); end; function TRegistrationController.RegisterImage(Constref ARequest: TRegisterURLRequest; out Response: TRegisterURLResponse): Boolean; var LGuid, LError: String; begin Result := False; try //make a call to make sure the requested token matches the details //... //try to validate the url if not ValidateURL(ARequest.Validation) then begin LogError('RegisterImage::validation failed for ' + ARequest.ToJSON); Exit; end; //save the job to db with the generated token LGuid := TGuid.NewGuid.ToString(); if not ExecuteSQL( 'INSERT INTO registration(token, user_key, parcel_identity, url)' + ' SELECT ' + QuotedStr(LGuid) + ',' + ' ' + QuotedStr(ARequest.Authentication.UserKey) + ',' + ' ' + QuotedStr(ARequest.Authentication.ParcelID) + ',' + ' ' + QuotedStr(ARequest.Validation.URL) + ';', LError ) then begin LogError('RegisterImage::' + LError); Exit; end; Response.Token := LGuid; //kick off the background process to perform the actual image deconstruction StartProcessing(ARequest, Response); Result := True; except on E : Exception do LogError('RegisterImage::' + E.Message); end; end; function TRegistrationController.CancelRequest(): Boolean; begin //not implemented, but need to look in collection and //then add some kind of flag to the thread (if found) to stop processing Result := False; end; function TRegistrationController.LookupImageID(const AImageToken: String; out ID: Integer): Boolean; var LData: TDatasetResponse; LError: String; LRow: TJSONData; begin Result := False; try //try to fetch the id if not GetSQLResultsJSON( 'SELECT id as id FROM registration WHERE token = ' + QuotedStr(AImageToken) + ' LIMIT 1;', LData, LError ) then begin LogError('LookupImageID::' + LError); Exit; end; //if the caller provided an invalid token, warn and bail if LData.Count < 1 then begin LogWarn('LookupImageID::[' + AImageToken + '] is not a valid token'); Exit; end; LRow := GetJSON(LData[0]); try if not Assigned(LRow) or (LRow.JSONType <> jtObject) then begin LogError('LookupImageID::malformed json for token [' + AImageToken + ']'); Exit; end; //assign the id ID := TJSONObject(LRow).Get('id'); finally LRow.Free; end; //success Result := True; except on E : Exception do LogError('LookupImageID::' + E.Message); end; end; class procedure TRegistrationController.StartProcessing(Constref ARequest: TRegisterURLRequest; Constref AResponse: TRegisterURLResponse); var LThread : IEZThread; procedure Start(Const AThread : IEZThread); var LStatus : TStatusController; LImage : TImageController; LData : TMemoryStream; LClient : TFPHTTPClient; LError : String; LResp : TImageResponse; LBitmap : TBGRABitmap; begin LStatus := TStatusController.Create(nil); LImage := TImageController.Create(nil); LClient := TFPHTTPClient.Create(nil); LData := TMemoryStream.Create; LBitmap := TBGRABitmap.Create; try try //update status to in-progress if not LStatus.UpdateStatus(AThread['token'], isInProgress, LError) then raise Exception.Create(LError); //attempt to download the image LClient.Get(AThread['url'], LData); //we need to dither the image to a reduced color space so our //dcl client can draw it in some reasonable amount of time //(currently uses color components to draw, this may change later...) if not DitherImageStream(LData, AThread['url'], LBitmap, LError) then begin AThread.AddArg('error', LError); Exit; end; //after dithering has been completed, we can construct to a //dcl readable format if not ConstructDCLImageResponse(LBitmap, LResp, LError) then begin AThread.AddArg('error', LError); Exit; end; //write the image response to the database if not LImage.UpdateImage(AThread['token'], LResp, LError) then AThread.AddArg('error', LError); finally LBitmap.Free; LData.Free; LClient.Free; LStatus.Free; LImage.Free; end; except on E : Exception do AThread.AddArg('error', E.Message); end; end; procedure Finish(Const AThread : IEZThread); var LStatus : TStatusController; LError: String; begin LStatus := TStatusController.Create(nil); try if not AThread.Exists['error'] then begin //mark the status as complete if not LStatus.UpdateStatus(AThread['token'], isCompleted, LError) then if not LStatus.UpdateStatus(AThread['token'], isFailed, LError) then Exit; end //mark the status as failure else LStatus.UpdateStatus(AThread['token'], isFailed, LError); finally //remove from collection Collection.Remove(AThread); end; end; begin //setup a processing thread LThread := TEZThreadImpl.Create; LThread .Setup( Start, //handles initialize of status and processing nil, Finish //updates the status to finished/failed and saves the result ) .AddArg('url', ARequest.Validation.URL) .AddArg('token', AResponse.Token) .Settings .Await (* update the group id to be the thread id since we won't have access to the thread from the controller (gets freed after the request) and we may need to index back into the collection. alternatively, could use a different collection type (map<token,thread> for example) *) .UpdateGroupID(LThread.Settings.Await.ThreadID); //before starting the thread, add it to the monitor collection Collection.Add(LThread); //good to start now LThread.Start; end; initialization MAX_IMAGE_HEIGHT := 64; MAX_IMAGE_WIDTH := 64; Collection := TEZCollectionImpl.Create; InitializePalette; RegisterHTTPModule(GetControllerRoute('registration'), TRegistrationController); finalization Collection := nil; Palette.Free; end.