text
stringlengths
14
6.51M
unit akStream; interface uses Classes; type // ============================================================================= // Элемент коллекции, поддерживающий сохранение/чтение разных версий TVersionedCollectionItem = class(TCollectionItem) private fSecVersion: WORD; protected property SecVersion: WORD read fSecVersion write fSecVersion; public procedure SaveToStreamVer(Stream: TStream; const ver:Integer); virtual; abstract; procedure LoadFromStreamVer(Stream: TStream; const ver:Integer); virtual; abstract; constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Clear; virtual; abstract; procedure LoadFromStream(Stream: TStream); virtual; procedure SaveToStream(Stream: TStream); virtual; end; TVersionedCollectionItemClass = class of TVersionedCollectionItem; // ============================================================================= // Rоллекциz, поддерживающая сохранение/чтение разных версий TVersionedCollection = class(TCollection) private fSecVersion: WORD; protected property SecVersion: WORD read fSecVersion write fSecVersion; public procedure SaveToStreamVer(Stream: TStream; const ver:Integer); virtual; abstract; procedure LoadFromStreamVer(Stream: TStream; const ver:Integer); virtual; abstract; constructor Create(ItemClass: TVersionedCollectionItemClass); destructor Destroy; override; procedure Clear; virtual; procedure LoadFromStream(Stream: TStream); procedure SaveToStream(Stream: TStream); end; // ============================================================================= // Измененный TCollectionItem : умеет сохранять ссылки с элемента на элемент // с помощью GUID'ов и восстанавливать их : TSafeCollectionItem = class(TCollectionItem) private fParentGUID: TGUID; fGUID: TGUID; fParentPtr: TSafeCollectionItem; // содержит указатель на Parent, если PtrValid fParentPtrValid: Boolean; procedure AssignGUID; procedure SetParent(const Value: TSafeCollectionItem); function GetParent: TSafeCollectionItem; protected property GUID: TGUID read fGUID; property ParentGUID: TGUID read fParentGUID; procedure Clear; virtual; // Сохраняет/загружает информацию о парентах из стрима procedure SaveToStream(stream: TStream); virtual; procedure LoadFromStream(stream: TStream); virtual; public constructor Create(Collection: TCollection); override; destructor Destroy; override; // Сбрасывает информацию о всех прямых ссылках на элементы парент-элементы. // Следует сбрасывать при любых операциях, изменяющих структуру иерархии. procedure ClearPointers; // Interface property Parent: TSafeCollectionItem read GetParent write SetParent; end; // Сохраняет и читает строку из стрима. // формат записи таков : [длина строки (2 байта)]строка. procedure SaveStringToStream(St: string; Stream: TStream); function ReadStringFromStream(Stream: TStream): string; implementation uses akComUtils, ActiveX, Windows; procedure SaveStringToStream(St: string; Stream: TStream); var len: Word; leng, dlen: DWORD; begin with Stream do if Length(st) > (High(Word) - 1) then begin len := High(Word); WriteBuffer(len, SizeOf(Word)); // если длина строки больше 65k, то dlen := Length(st); // пишем первыми двумя байтами $FFFF, а WriteBuffer(dlen, SizeOf(DWORD)); // следующими четыеремя - длину end else begin len := Length(St); WriteBuffer(len, SizeOf(len)); end; leng := Length(st); if leng <> 0 then Stream.WriteBuffer(St[1], leng); end; function ReadStringFromStream(Stream: TStream): string; var len: Word; leng, dlen: DWORD; begin Stream.ReadBuffer(len, SizeOf(len)); with Stream do if len = High(Word) then begin ReadBuffer(dlen, SizeOf(DWORD)); leng := dlen; end else leng := len; SetLength(Result, leng); Stream.ReadBuffer(Result[1], leng); end; { TVersionedCollectionItem } constructor TVersionedCollectionItem.Create(Collection: TCollection); begin inherited; end; destructor TVersionedCollectionItem.Destroy; begin inherited; end; procedure TVersionedCollectionItem.LoadFromStream(Stream: TStream); begin Clear; with Stream do begin ReadBuffer(fSecVersion, SizeOf(fSecVersion)); LoadFromStreamVer(stream, fSecVersion); end; end; procedure TVersionedCollectionItem.SaveToStream(Stream: TStream); begin with Stream do begin WriteBuffer(fSecVersion, SizeOf(fSecVersion)); SaveToStreamVer(stream, fSecVersion); end; end; { TVersionedCollection } procedure TVersionedCollection.Clear; var i : Integer; begin for i := 0 to Count-1 do begin TVersionedCollectionItem(Items[i]).Clear; end; end; constructor TVersionedCollection.Create(ItemClass: TVersionedCollectionItemClass); begin inherited Create(ItemClass); Clear; end; destructor TVersionedCollection.Destroy; begin inherited; end; procedure TVersionedCollection.LoadFromStream(Stream: TStream); var i : Integer; begin Clear; with Stream do begin ReadBuffer(fSecVersion, SizeOf(fSecVersion)); LoadFromStreamVer(Stream, fSecVersion); for i := 0 to Count-1 do TVersionedCollectionItem(Items[i]).LoadFromStreamVer(Stream, fSecVersion); end; end; procedure TVersionedCollection.SaveToStream(Stream: TStream); var i : Integer; begin with Stream do begin WriteBuffer(fSecVersion, SizeOf(fSecVersion)); SaveToStreamVer(Stream, fSecVersion); for i := 0 to Count-1 do TVersionedCollectionItem(Items[i]).SaveToStreamVer(Stream, fSecVersion); end; end; { TSafeCollectionItem } procedure TSafeCollectionItem.AssignGUID; begin if IsGUIDEmpty(fGUID) then CoCreateGUID(fGUID); end; procedure TSafeCollectionItem.Clear; begin EmptyGUID(fParentGUID); EmptyGUID(fGUID); ClearPointers; AssignGUID; end; procedure TSafeCollectionItem.ClearPointers; begin fParentPtrValid := false; fParentPtr := nil; end; constructor TSafeCollectionItem.Create(Collection: TCollection); begin inherited; Clear; end; destructor TSafeCollectionItem.Destroy; begin inherited; end; function TSafeCollectionItem.GetParent: TSafeCollectionItem; var i: Integer; ti: TSafeCollectionItem; begin if fParentPtrValid then Result := fParentPtr else begin Result := nil; fParentPtrValid := true; for i := 0 to Collection.Count - 1 do begin ti := TSafeCollectionItem(Collection.Items[i]); if IsEqualGUID(ParentGUID, ti.GUID) then begin fParentPtr := ti; Result := ti; Break; end; end; end; end; procedure TSafeCollectionItem.LoadFromStream(stream: TStream); begin Stream.ReadBuffer(fGUID, SizeOf(fGUID)); Stream.ReadBuffer(fParentGUID, SizeOf(fParentGUID)); ClearPointers; end; procedure TSafeCollectionItem.SaveToStream(stream: TStream); begin Stream.WriteBuffer(fGUID, SizeOf(fGUID)); Stream.WriteBuffer(fParentGUID, SizeOf(fParentGUID)); end; procedure TSafeCollectionItem.SetParent(const Value: TSafeCollectionItem); begin Value.AssignGUID; fParentGUID := Value.GUID; ClearPointers; end; end.
unit atAdapterTest; {* Класс, через который пускается приложение } // Модуль: "w:\quality\test\garant6x\AdapterTest\Runner\atAdapterTest.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatAdapterTest" MUID: (4AC3488802F7) interface uses l3IntfUses , atAdapterTestCommandLine , atScenario , SysUtils ; type ECantCreateScenario = class(Exception) end;//ECantCreateScenario TatAdapterTest = class(TObject) {* Класс, через который пускается приложение } private f_UserName: AnsiString; {* имя пользователя } f_Password: AnsiString; {* пароль пользователя } f_CommandLine: TatAdapterTestCommandLine; f_Scenario: TatScenario; {* выполняемый сценарий (последовательность операций) } private function Init: Boolean; virtual; procedure CreateScenario; virtual; procedure PlayScenario; virtual; public procedure Start; virtual; constructor Create; reintroduce; destructor Destroy; override; end;//TatAdapterTest implementation uses l3ImplUses , atLogger , atXMLScenarioGenerator , atScenarioPlayer {$If NOT Defined(NoScripts)} , TtfwTypeRegistrator_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *4AC3488802F7impl_uses* //#UC END# *4AC3488802F7impl_uses* ; function TatAdapterTest.Init: Boolean; //#UC START# *4AC3492402F9_4AC3488802F7_var* //#UC END# *4AC3492402F9_4AC3488802F7_var* begin //#UC START# *4AC3492402F9_4AC3488802F7_impl* // проверяем, все ли необходимые параметры командной строки переданы if NOT f_CommandLine.IsAllRequiredSet then begin // ругаемся, если нет Logger.Error('Заданы не все необходимые параметры командной строки!'); f_CommandLine.PrintUsageInfo; Result := false; Exit; end; // // считываем параметры логина f_UserName := f_CommandLine.Parameters[CLP_LOGIN].AsStr; f_Password := f_CommandLine.Parameters[CLP_PASSWORD].AsStr; // // перенаправляем вывод в лог файл, если он задан with f_CommandLine.Parameters[CLP_LOGFILENAME] do if IsSet then Logger := TatFileLogger.Create(AsStr); Result := true; //#UC END# *4AC3492402F9_4AC3488802F7_impl* end;//TatAdapterTest.Init procedure TatAdapterTest.CreateScenario; //#UC START# *4AC349310110_4AC3488802F7_var* var scenarioFileName : String; generator : TatXMLScenarioGenerator; //#UC END# *4AC349310110_4AC3488802F7_var* begin //#UC START# *4AC349310110_4AC3488802F7_impl* scenarioFileName := f_CommandLine.Parameters[CLP_SCENARIOFILENAME].AsStr; if NOT FileExists(scenarioFileName) then Raise ECantCreateScenario.Create(Logger.Error('Файл сценария не найден!')); // generator := TatXMLScenarioGenerator.Create; f_Scenario := TatScenario.Create; try generator.FillScenario(f_Scenario, scenarioFileName); finally FreeAndNil(generator); end; //#UC END# *4AC349310110_4AC3488802F7_impl* end;//TatAdapterTest.CreateScenario procedure TatAdapterTest.PlayScenario; //#UC START# *4AC3494000AA_4AC3488802F7_var* var player : TatScenarioPlayer; //#UC END# *4AC3494000AA_4AC3488802F7_var* begin //#UC START# *4AC3494000AA_4AC3488802F7_impl* player := TatScenarioPlayer.Create(f_Scenario); try // инициализируем контекст выполнения with player.F_ExecutionContext do begin F_LoginData.Login := f_UserName; F_LoginData.Password := f_Password; //GblAdapterWorker := TatGblAdapterWorker.Instance; end; // выполняем player.Execute; finally FreeAndNil(player); end; //#UC END# *4AC3494000AA_4AC3488802F7_impl* end;//TatAdapterTest.PlayScenario procedure TatAdapterTest.Start; //#UC START# *4AC3494903C7_4AC3488802F7_var* //#UC END# *4AC3494903C7_4AC3488802F7_var* begin //#UC START# *4AC3494903C7_4AC3488802F7_impl* if NOT Init then Exit; // CreateScenario; // PlayScenario; //#UC END# *4AC3494903C7_4AC3488802F7_impl* end;//TatAdapterTest.Start constructor TatAdapterTest.Create; //#UC START# *4AC3495102C1_4AC3488802F7_var* //#UC END# *4AC3495102C1_4AC3488802F7_var* begin //#UC START# *4AC3495102C1_4AC3488802F7_impl* inherited; // f_CommandLine := TatAdapterTestCommandLine.Create; //#UC END# *4AC3495102C1_4AC3488802F7_impl* end;//TatAdapterTest.Create destructor TatAdapterTest.Destroy; //#UC START# *48077504027E_4AC3488802F7_var* //#UC END# *48077504027E_4AC3488802F7_var* begin //#UC START# *48077504027E_4AC3488802F7_impl* FreeAndNil(f_CommandLine); FreeAndNil(f_Scenario); inherited; //#UC END# *48077504027E_4AC3488802F7_impl* end;//TatAdapterTest.Destroy initialization {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(ECantCreateScenario)); {* Регистрация типа ECantCreateScenario } {$IfEnd} // NOT Defined(NoScripts) end.
unit UnitDemo3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) btnRead: TButton; mmoDisplay: TMemo; procedure btnReadClick(Sender: TObject); private { Private declarations } public { Public declarations } end; // 函数声明 function MyFileRead(Path:string;Num:Integer;readPos:Integer): TBytes; function MyFileWrite(Path:string;Num:Integer;writePos:Integer): TBytes; function MyEcgCaculation(ecgBuff:TBytes): Integer; var Form1: TForm1; const SOURCE_PATH = 'D:\ecgTest.txt'; NUM_READ:Integer = 10000; implementation // 函数实现 function MyFileWrite(Path:string;Num:Integer;writePos:Integer): TBytes; var WriteFileStream:TFileStream; begin try // 只读方式打开 WriteFileStream := TFileStream.Create(path, fmOpenWrite); WriteFileStream.Seek(writePos,soFromBeginning); finally // 释放资源 FreeAndNil(WriteFileStream); end; end; function MyFileRead(path:string;num:Integer;readPos:Integer): TBytes; var ReadFileStream:TFileStream; begin Result := nil; // 文件不存在则结束读取 if (not FileExists(path)) then Exit; try // 只读方式打开 ReadFileStream := TFileStream.Create(path, fmOpenRead); // 判断剩下的字节数目是否足够 if( ReadFileStream.Size-readPos < NUM_READ ) then begin Num := ReadFileStream.Size-readPos; end; // 设定TBytes数组长度 SetLength(Result, Num); ReadFileStream.Seek(readPos,soFromBeginning); // 读num个字节 ReadFileStream.Read(Result, num); finally // 释放资源 FreeAndNil(ReadFileStream); end; end; function MyEcgCaculation(ecgBuff:TBytes): Integer; var EcgReadPosition:Integer; // ecg数据读取位置 EcgReadPositionOld:Integer; // ecg数据读取位置 tmpReadPosition:Integer; datPackSize:Integer; // 从包中取得的长度 ecgNumSize:Integer; // 根据标志计算得到ECG包长 kk:Byte; // 通道数码 begin EcgReadPosition :=0; EcgReadPositionOld :=0; tmpReadPosition:=0; datPackSize:=0; ecgNumSize:=0; // 最小的包FMT21为17个字节 while EcgReadPosition < ( Length(ecgBuff)-17 + 1 ) do begin { 判断数据 } ShowMessage('1:EcgReadPosition='+IntToStr(EcgReadPosition)); if (ecgBuff[EcgReadPosition+0]=$7f) and (ecgBuff[EcgReadPosition+1]=$7f) then begin EcgReadPositionOld := EcgReadPosition; // 保存当前读取位置 datPackSize:=ecgBuff[EcgReadPosition+2]+ecgBuff[EcgReadPosition+3]*256; // 数据已不足 if( Length(ecgBuff)- EcgReadPosition)< datPackSize then begin Result := EcgReadPositionOld; Exit; end; // 判断格式 FMT22 if ecgBuff[EcgReadPosition+5]=22 then // 判断FMT格式 22数据包 begin for kk := 1 to ecgBuff[EcgReadPosition+7+4] do begin tmpReadPosition:= ecgNumSize+EcgReadPosition+13; // 防止超界 if( tmpReadPosition >= Length(ecgBuff) ) then begin Result:= EcgReadPositionOld; Exit; end; // and两边是整数型,则是按位与 if ecgBuff[tmpReadPosition] and $07 = 0 then begin Inc(ecgNumSize,101); end else begin Inc(ecgNumSize,52); end; end; // 数据总长度+头部长度 Inc(ecgNumSize,13); // 判断计算得到的长度和包内给定长度是否一致 if(ecgNumSize<>datPackSize) then begin // 输出提示 Form1.mmoDisplay.Lines.Add('ecgNumSize='+IntToStr(ecgNumSize)); Form1.mmoDisplay.Lines.Add('datPackSize='+IntToStr(datPackSize)); Form1.mmoDisplay.Lines.Add('FMT22 Lost'); // 重新查找开始的头部7f 7f while ( EcgReadPosition < ( Length(ecgBuff)-1 ) ) do begin Inc(EcgReadPosition,1); if ( ecgBuff[EcgReadPosition]= $7f )and(ecgBuff[EcgReadPosition+1]= $7f) then begin Break; end; end; // 数据部分丢失 {if (EcgReadPosition-EcgReadPositionOld)<datPackSize then begin Form1.mmoDisplay.Lines.Add('FMT22 error from lost data.'); end; } // 数据已全部读完,没有头部 if(EcgReadPosition>=Length(ecgBuff)-1) then begin Result:= EcgReadPositionOld; Exit; end; end else begin Inc(EcgReadPosition,ecgNumSize); end; end else if ecgBuff[EcgReadPosition+5]=20 then // 判断FMT格式 20空闲包 begin ecgNumSize:=datPackSize; if ecgNumSize<>24 then begin Form1.mmoDisplay.Lines.Add('FMT20 Dat Error.datPackSize='+IntToStr(datPackSize)); end; tmpReadPosition:= EcgReadPosition+24+2; // 需要判断后面的字节是否为7f 7f来判断数据是否完整 // 防止超界 if( tmpReadPosition >= Length(ecgBuff) ) then begin Result:= EcgReadPositionOld; Exit; end; if ( ecgBuff[EcgReadPosition] <> $7f )or(ecgBuff[EcgReadPosition+1]<> $7f) then begin Form1.mmoDisplay.Lines.Add('FMT20 Dat Lost.'); // 重新查找开始的头部7f 7f while ( EcgReadPosition < ( Length(ecgBuff)-1 ) ) do begin Inc(EcgReadPosition,1); if ( ecgBuff[EcgReadPosition]= $7f )and(ecgBuff[EcgReadPosition+1]= $7f) then begin Break; end; end; // 数据已全部读完,没有头部 if(EcgReadPosition>=Length(ecgBuff)-1) then begin Result:= EcgReadPositionOld; Exit; end; end else begin Inc(EcgReadPosition,ecgNumSize); end; end else if ecgBuff[EcgReadPosition+5]=21 then // 判断FMT格式 21信息包 begin ecgNumSize:=datPackSize; if ecgNumSize<>17 then begin Form1.mmoDisplay.Lines.Add('FMT21 Dat Error.datPackSize='+IntToStr(datPackSize)); end; tmpReadPosition:= EcgReadPosition+17+2; // 需要判断后面的字节是否为7f 7f来判断数据是否完整 // 防止超界 if( tmpReadPosition >= Length(ecgBuff) ) then begin Result:= EcgReadPositionOld; Exit; end; if ( ecgBuff[EcgReadPosition] <> $7f )or(ecgBuff[EcgReadPosition+1]<> $7f) then begin Form1.mmoDisplay.Lines.Add('FMT20 Dat Lost.'); // 重新查找开始的头部7f 7f while ( EcgReadPosition < ( Length(ecgBuff)-1 ) ) do begin Inc(EcgReadPosition,1); if ( ecgBuff[EcgReadPosition]= $7f )and(ecgBuff[EcgReadPosition+1]= $7f) then begin Break; end; end; // 数据已全部读完,没有头部 if(EcgReadPosition>=Length(ecgBuff)-1) then begin Result:= EcgReadPositionOld; Exit; end; end else begin Inc(EcgReadPosition,ecgNumSize); end; end; end else begin Form1.mmoDisplay.Lines.Add('Head Error.'); // 重新查找开始的头部7f 7f while ( EcgReadPosition < ( Length(ecgBuff)-1 ) ) do begin Inc( EcgReadPosition,1 ); if ( ecgBuff[EcgReadPosition]= $7f )and(ecgBuff[EcgReadPosition+1]= $7f) then begin Break; end; end; // 数据已全部读完,没有头部 if(EcgReadPosition>=Length(ecgBuff)-1) then begin Result:= EcgReadPositionOld; Exit; end; end; end; end; {$R *.dfm} procedure TForm1.btnReadClick(Sender: TObject); var ReadPosition:Integer; // 读取位置 EcgReadPosition:Integer;// ecg数据读取位置 ReadNum:Integer; // 读取个数 ecgBuf:TBytes; // Byte数组 cnt:Integer; SourEncoding, DestEncoding: TEncoding; WriteFile:TextFile; ecgWriteBuf:TBytes; begin ReadPosition:=0; // 初始化读取初始位置 EcgReadPosition:=0; // 初始化Ecg读取初始位置 readNum:=NUM_READ; // 初始化初始读取个数 DestEncoding:= TEncoding.UTF8; try // 只读方式打开 // 将磁盘上的文件跟我们的变量关联绑定 AssignFile(WriteFile,'D:\ecgDataTestxx.txt'); // 打开文件 rewirte方式打开,如果该文件已存在,将被覆盖 Rewrite(WriteFile); while True do begin // 读出数据到ecgBuf ecgBuf:=MyFileRead(SOURCE_PATH,ReadNum,ReadPosition); for cnt := 0 to Length(ecgBuf)-1 do begin Write(WriteFile,IntToHex(ecgBuf[cnt])); write(WriteFile,' '); end; // 更新读取位置 //Inc(ReadPosition,MyEcgCaculation(ecgBuf)); Inc(ReadPosition,Length(ecgBuf)); //ShowMessage(IntToStr(ReadPosition)); // 判断数据已全部读取完成 if Length(ecgBuf) < NUM_READ then begin Break; end; end; finally end; // DEBUG Message ShowMessage(IntToStr(ReadPosition)); end; end.
unit ZMOprFile; // ZMFileOpr.pas - file operations (* Derived from * SFX for DelZip v1.7 * Copyright 2002-2005 * written by Markus Stephany *) (* *************************************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2014, 2015 delphizip 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. contact: problems AT delphizip DOT org updates: http://www.delphizip.org *************************************************************************** *) // modified 2015-04-07 {$I '.\ZipVers.inc'} interface uses {$IFDEF VERDXE2up} System.Classes, {$ELSE} Classes, {$ENDIF} ZMHandler; type TZMOpConvertToSFX = class(TZMOperationRoot) private FOutName: string; FSpan: Boolean; public constructor Create(const OutName: string; Span: Boolean); function Execute(TheBody: TZMHandler): Integer; override; function Name: string; override; end; type TZMOpConvertToZip = class(TZMOperationRoot) public constructor Create; function Execute(TheBody: TZMHandler): Integer; override; function Name: string; override; end; type TZMOpReadSpan = class(TZMOperationRoot) private FInFileName: string; FOutFilePath: string; FUseXProgress: Boolean; public constructor Create(const InFileName: string; var OutFilePath: string; UseXProgress: Boolean); function Execute(TheBody: TZMHandler): Integer; override; function Name: string; override; end; type TZMOpWriteSpan = class(TZMOperationRoot) private FInFileName: string; FOutFileName: string; FUseXProgress: Boolean; public constructor Create(const InFileName, OutFileName: string; UseXProgress: Boolean); function Execute(TheBody: TZMHandler): Integer; override; function Name: string; override; end; implementation uses ZMLister, ZMFileOpr; { TZMOpConvertToSFX } constructor TZMOpConvertToSFX.Create(const OutName: string; Span: Boolean); begin inherited Create; FOutName := OutName; FSpan := Span; end; function TZMOpConvertToSFX.Execute(TheBody: TZMHandler): Integer; var FOper: TZMFileOpr; begin FOper := TZMFileOpr.Create(TheBody as TZMLister); AnOperation := FOper; if FSpan then Result := FOper.ConvertToSpanSFX(FOutName, nil) else Result := FOper.ConvertToSFX(FOutName, nil); end; function TZMOpConvertToSFX.Name: string; begin if FSpan then Result := 'ConvertToSpanSFX' else Result := 'ConvertToSFX'; end; { TZMOpConvertToZip } constructor TZMOpConvertToZip.Create; begin inherited; end; function TZMOpConvertToZip.Execute(TheBody: TZMHandler): Integer; var FOper: TZMFileOpr; begin FOper := TZMFileOpr.Create(TheBody as TZMLister); AnOperation := FOper; Result := FOper.ConvertToZIP; end; function TZMOpConvertToZip.Name: string; begin Result := 'ConvertToZip'; end; { TZMOpReadSpan } constructor TZMOpReadSpan.Create(const InFileName: string; var OutFilePath: string; UseXProgress: Boolean); begin inherited Create; FInFileName := InFileName; FOutFilePath := OutFilePath; FUseXProgress := UseXProgress; end; function TZMOpReadSpan.Execute(TheBody: TZMHandler): Integer; var FOper: TZMFileOpr; begin FOper := TZMFileOpr.Create(TheBody as TZMLister); AnOperation := FOper; Result := FOper.ReadSpan(FInFileName, FOutFilePath, FUseXProgress); end; function TZMOpReadSpan.Name: string; begin Result := 'ReadSpan'; end; { TZMOpWriteSpan } constructor TZMOpWriteSpan.Create(const InFileName, OutFileName: string; UseXProgress: Boolean); begin inherited Create; FInFileName := InFileName; FOutFileName := OutFileName; FUseXProgress := UseXProgress; end; function TZMOpWriteSpan.Execute(TheBody: TZMHandler): Integer; var FOper: TZMFileOpr; begin FOper := TZMFileOpr.Create(TheBody as TZMLister); AnOperation := FOper; Result := FOper.WriteSpan(FInFileName, FOutFileName, FUseXProgress); end; function TZMOpWriteSpan.Name: string; begin Result := 'WriteSpan'; end; end.
unit UProperties; interface uses SysUtils, Classes; type // Stores the selected properties of a component TNLDComponentItem = class(TCollectionItem) private FComponent: TComponent; FSelProperties: TStringList; function GetName(): String; function GetSelected(Name: String): Boolean; procedure SetSelected(Name: String; const Value: Boolean); function GetProperties: String; procedure SetName(const Value: String); procedure SetProperties(const Value: String); public constructor Create(Collection: TCollection); override; destructor Destroy(); override; property Component: TComponent read FComponent write FComponent; property Selected[Name: String]: Boolean read GetSelected write SetSelected; published // Used for writing to file property Name: String read GetName write SetName; property Properties: String read GetProperties write SetProperties; end; // Stores the components on a form TNLDGetComponentEvent = procedure(Sender: TObject; const Name: String; out Component: TComponent) of object; TNLDComponents = class(TCollection) private FOnGetComponent: TNLDGetComponentEvent; function GetItem(Index: Integer): TNLDComponentItem; procedure SetItem(Index: Integer; const Value: TNLDComponentItem); protected procedure DoGetComponent(const Name: String; out Component: TComponent); public constructor Create(); procedure LoadFromFile(const AFilename: String); procedure SaveToFile(const AFilename: String); function Add(): TNLDComponentItem; function GetFromComponent(const AComponent: TComponent): TNLDComponentItem; property Items[Index: Integer]: TNLDComponentItem read GetItem write SetItem; default; property OnGetComponent: TNLDGetComponentEvent read FOnGetComponent write FOnGetComponent; end; // Wrapper to allow easy storage of the collection TNLDComponentsWrapper = class(TComponent) private FCollection: TCollection; published property Collection: TCollection read FCollection write FCollection; end; implementation uses Dialogs; { :: TNLDComponentItem } constructor TNLDComponentItem.Create; begin inherited; FSelProperties := TStringList.Create(); end; destructor TNLDComponentItem.Destroy; begin FreeAndNil(FSelProperties); inherited; end; function TNLDComponentItem.GetName; begin if Assigned(FComponent) then Result := FComponent.Name else Result := ''; end; function TNLDComponentItem.GetProperties; begin Result := FSelProperties.Text; end; function TNLDComponentItem.GetSelected; begin Result := (FSelProperties.IndexOf(Name) > -1); end; procedure TNLDComponentItem.SetName; begin if (Assigned(Collection)) and (Collection is TNLDComponents) then TNLDComponents(Collection).DoGetComponent(Value, FComponent); end; procedure TNLDComponentItem.SetProperties; begin FSelProperties.Text := Value; end; procedure TNLDComponentItem.SetSelected; var iIndex: Integer; begin iIndex := FSelProperties.IndexOf(Name); if Value then begin if iIndex = -1 then FSelProperties.Add(Name); end else if iIndex > -1 then FSelProperties.Delete(iIndex); end; { :: TNLDComponents } constructor TNLDComponents.Create; begin inherited Create(TNLDComponentItem); end; function TNLDComponents.Add; begin Result := TNLDComponentItem(inherited Add()); end; procedure TNLDComponents.LoadFromFile; var pSource: TFileStream; pWrapper: TNLDComponentsWrapper; begin Clear(); // Load from file pSource := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite); try pWrapper := TNLDComponentsWrapper.Create(nil); try pWrapper.Collection := Self; pSource.ReadComponent(pWrapper); finally FreeAndNil(pWrapper); end; finally FreeAndNil(pSource); end; end; procedure TNLDComponents.SaveToFile; var pDest: TFileStream; pWrapper: TNLDComponentsWrapper; iItem: Integer; begin // Filter unused components for iItem := Count - 1 downto 0 do if Items[iItem].FSelProperties.Count = 0 then Delete(iItem); if Count = 0 then if FileExists(AFilename) then begin DeleteFile(AFilename); exit; end; // Save to file pDest := TFileStream.Create(AFilename, fmCreate or fmShareExclusive); try pWrapper := TNLDComponentsWrapper.Create(nil); try pWrapper.Collection := Self; pDest.WriteComponent(pWrapper); finally FreeAndNil(pWrapper); end; finally FreeAndNil(pDest); end; end; function TNLDComponents.GetItem; begin Result := TNLDComponentItem(inherited GetItem(Index)); end; procedure TNLDComponents.SetItem; begin inherited SetItem(Index, Value); end; function TNLDComponents.GetFromComponent; var iItem: Integer; begin for iItem := Count - 1 downto 0 do if Items[iItem].Component = AComponent then begin Result := Items[iItem]; exit; end; Result := Add(); Result.Component := AComponent; end; procedure TNLDComponents.DoGetComponent; begin if Assigned(FOnGetComponent) then FOnGetComponent(Self, Name, Component); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 11/15/04 11:32:50 AM RLebeau Bug fix for OutboundConnect() assigning the IOHandler.ConnectTimeout property before the IOHandler has been assigned. Rev 1.3 11/14/04 11:40:00 AM RLebeau Removed typecast in OutboundConnect() Rev 1.2 2004.02.03 5:45:52 PM czhower Name changes Rev 1.1 2/2/2004 4:12:02 PM JPMugaas Should now compile in DotNET. Rev 1.0 2/1/2004 4:22:50 AM JPMugaas Components from IdMappedPort are now in their own units. } unit IdMappedTelnet; interface {$i IdCompilerDefines.inc} uses IdAssignedNumbers, IdMappedPortTCP, IdTCPServer; type TIdMappedTelnetContext = class(TIdMappedPortContext) protected FAllowedConnectAttempts: Integer; FErrorMsg: String; // procedure OutboundConnect; override; public property AllowedConnectAttempts: Integer read FAllowedConnectAttempts; property ErrorMsg: String read FErrorMsg; end; TIdMappedTelnetCheckHostPort = procedure (AContext: TIdMappedPortContext; const AHostPort: String; var VHost, VPort: String) of object; TIdCustomMappedTelnet = class (TIdMappedPortTCP) protected FAllowedConnectAttempts: Integer; FOnCheckHostPort: TIdMappedTelnetCheckHostPort; procedure DoCheckHostPort (AContext: TIdMappedPortContext; const AHostPort: String; var VHost, VPort: String); virtual; procedure SetAllowedConnectAttempts(const Value: Integer); procedure ExtractHostAndPortFromLine(AContext: TIdMappedPortContext; const AHostPort: String); procedure InitComponent; override; public // property AllowedConnectAttempts: Integer read FAllowedConnectAttempts write SetAllowedConnectAttempts default -1; // property OnCheckHostPort: TIdMappedTelnetCheckHostPort read FOnCheckHostPort write FOnCheckHostPort; published property DefaultPort default IdPORT_TELNET; property MappedPort default IdPORT_TELNET; end; TIdMappedTelnet = class (TIdCustomMappedTelnet) published property AllowedConnectAttempts: Integer read FAllowedConnectAttempts write SetAllowedConnectAttempts default -1; // property OnCheckHostPort: TIdMappedTelnetCheckHostPort read FOnCheckHostPort write FOnCheckHostPort; end; implementation uses IdGlobal, IdException, IdResourceStringsProtocols, IdIOHandlerSocket, IdTCPClient, SysUtils; const NAMESEP = #0+#9+' :'; {do not localize} { TIdCustomMappedTelnet } procedure TIdCustomMappedTelnet.InitComponent; begin inherited InitComponent; FAllowedConnectAttempts := -1; FContextClass := TIdMappedTelnetContext; DefaultPort := IdPORT_TELNET; MappedPort := IdPORT_TELNET; end; procedure TIdCustomMappedTelnet.DoCheckHostPort(AContext: TIdMappedPortContext; const AHostPort: String; var VHost, VPort: String); Begin if Assigned(FOnCheckHostPort) then begin FOnCheckHostPort(AContext, AHostPort, VHost, VPort); end; end; procedure TIdCustomMappedTelnet.ExtractHostAndPortFromLine(AContext: TIdMappedPortContext; const AHostPort: String); var LHost, LPort: String; i : Integer; Begin LHost := ''; {Do not Localize} LPort := ''; {Do not Localize} if Length(AHostPort) > 0 then begin i := 1; while (i <= Length(AHostPort)) and (not CharIsInSet(AHostPort, i, NAMESEP)) do begin LHost := LHost + AHostPort[i]; Inc(i); end; Inc(i); while (i <= Length(AHostPort)) and (not CharIsInSet(AHostPort, i, NAMESEP)) do begin LPort := LPort + AHostPort[i]; Inc(i); end; LHost := TrimRight(LHost); LPort := TrimLeft(LPort); end; DoCheckHostPort(AContext, AHostPort, LHost, LPort); if Length(LHost) > 0 then begin TIdTcpClient(AContext.OutboundClient).Host := LHost; end; if Length(LPort) > 0 then begin TIdTcpClient(AContext.OutboundClient).Port := IndyStrToInt(LPort, TIdTcpClient(AContext.OutboundClient).Port); end; end; procedure TIdMappedTelnetContext.OutboundConnect; var LHostPort: String; Begin //don`t call inherited, NEW behavior FOutboundClient := TIdTCPClient.Create(nil); with TIdCustomMappedTelnet(Server) do begin with TIdTcpClient(FOutboundClient) do begin Port := MappedPort; Host := MappedHost; end;//with Self.FAllowedConnectAttempts := AllowedConnectAttempts; DoLocalClientConnect(Self); repeat if FAllowedConnectAttempts > 0 then begin Dec(FAllowedConnectAttempts); end; try LHostPort := Trim(Connection.IOHandler.InputLn); //~telnet input ExtractHostAndPortFromLine(Self, LHostPort); if Length(TIdTcpClient(FOutboundClient).Host) < 1 then begin raise EIdException.Create(RSEmptyHost); end; with TIdTcpClient(FOutboundClient) do begin ConnectTimeout := Self.FConnectTimeOut; Connect; end; except on E: Exception do // DONE: Handle connect failures begin FErrorMsg := 'ERROR: ['+E.ClassName+'] ' + E.Message; {Do not Localize} Self.DoException(E); Connection.IOHandler.WriteLn(FErrorMsg); end; end;//trye until FOutboundClient.Connected or (FAllowedConnectAttempts = 0); if FOutboundClient.Connected then begin DoOutboundClientConnect(Self); end else begin Connection.Disconnect; //prevent all next work end; end;//with end; procedure TIdCustomMappedTelnet.SetAllowedConnectAttempts(const Value: Integer); Begin if Value >= 0 then begin FAllowedConnectAttempts := Value; end else begin FAllowedConnectAttempts := -1; //unlimited end; end; end.
unit missing_param_error; interface uses System.Json, error; type TMissingParamError = class(TInterfacedObject, IError) private FBody: TJSONObject; function Body: TJSONObject; constructor Create(Const AParamName: String); public class function New(Const AParamName: String): IError; end; implementation uses System.SysUtils; constructor TMissingParamError.Create(const AParamName: String); begin FBody := TJSONObject.Create.AddPair('error', format('Missing param: %s', [AParamName])); end; function TMissingParamError.Body: TJSONObject; begin result := FBody; end; class function TMissingParamError.New(Const AParamName: String): IError; begin result := self.Create(AParamName); end; end.
unit senCille.XPlatformTools; interface {$INCLUDE PRODUCT_CONSTS.INC} type TXPlatform = class private {$IF DEFINED(IOS)} class function prvOpenURL(const URL: string; const DisplayError: Boolean = False):Integer; {$ELSEIF DEFINED(ANDROID)} class function prvOpenURL(const URL: string; const DisplayError: Boolean = False):Integer; {$ENDIF} public class function OpenURL(sCommand: string):Integer; class procedure CallWebHelp(aHelpPath :string); class procedure CallWebPage(aHelpPath :string); end; implementation uses {$IFDEF ANDROID} FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, Androidapi.JNI.JavaTypes, {$ELSE} {$IFDEF IOS} iOSapi.Foundation, FMX.Helpers.iOS, {$ENDIF IOS} {$ENDIF ANDROID} {$IFDEF MSWINDOWS} Winapi.ShellAPI, Winapi.Windows, {$ELSEIF DEFINED(MACOS)} Posix.Stdlib, {$ENDIF} {IdURI,} System.SysUtils, Classes, FMX.Dialogs; class function TXPlatform.OpenURL(sCommand: string):Integer; begin {$IF DEFINED(MACOS)} _system(PAnsiChar('open ' + '"' + AnsiString(sCommand) + '"')); {$ELSEIF DEFINED(MSWINDOWS)} Result := ShellExecute(0, 'OPEN', PChar(sCommand), '', '', SW_SHOWNORMAL); {$ELSEIF DEFINED(IOS)} Result := prvOpenURL(sCommand); {$ELSEIF DEFINED(ANDROID)} Result := prvOpenURL(sCommand); {$ENDIF} end; {$IFDEF IOS} class function TXPlatform.prvOpenURL(const URL: string; const DisplayError: Boolean = False):Integer; var NSU :NSUrl; begin // iOS doesn't like spaces, so URL encode is important. NSU := StrToNSUrl(TIdURI.URLEncode(URL)); if SharedApplication.canOpenURL(NSU) then begin exit(SharedApplication.openUrl(NSU)); end else begin if DisplayError then begin ShowMessage('Error: Opening "' + URL + '" not supported.'); end; Exit(False); end; end; {$ENDIF} {$IFDEF ANDROID} class function TXPlatform.prvOpenURL(const URL: string; const DisplayError: Boolean = False):Integer; var Intent :JIntent; begin // There may be an issue with the geo: prefix and URLEncode. // will need to research Intent := TJIntent.JavaClass.Init(TJIntent.JavaClass.ACTION_VIEW, TJnet_Uri.JavaClass.Parse(StringToJString(TIdURI.URLEncode(URL)))); try SharedActivity.StartActivity(Intent); Exit(True); except on e: Exception do begin if DisplayError then ShowMessage('Error: ' + e.Message); Exit(False); end; end; end; {$ENDIF} class procedure TXPlatform.CallWebHelp(aHelpPath :string); begin TXPlatform.OpenURL(RootHelpPath + LowerCase(aHelpPath)); end; class procedure TXPlatform.CallWebPage(aHelpPath :string); begin TXPlatform.OpenURL(RootWebPath + LowerCase(aHelpPath)); end; end.
{ CSI 1101-X, Winter 1999 } { Assignment 5, Question 1 } { Identification: Mark Sattolo, student# 428500 } { tutorial group DGD-4, t.a. = Jensen Boire } program a5q1 (input,output) ; label 310 ; const maxMazeSize = 12 ; maxSolutionLength = 78 ; { solutions must be length 77 or less } up = 'u' ; { use the NAMES - up, down, left, and right } down = 'd' ; { throughout your code } left = 'l' ; right = 'r' ; free = '.' ; wall = '#' ; type maze = record size: integer ; { assume the maze is square } map: array[1..maxMazeSize,1..maxMazeSize] of char end ; element_type = string[maxSolutionLength] ; pointer = ^node ; node = record value: element_type ; next: pointer end ; queue = record front: pointer ; rear: pointer ; size: integer end ; { variable for the main program - NOT to be referenced anywhere else } var YESorNO: char ; {* The following global variables are used for memory management. You might find them useful while debugging your code, but the solutions you hand in must not refer to these variables in any way. *} max_memory_count, memory_count: integer ; {******* MEMORY MANAGEMENT PROCEDURES **********} { get_node - Returns a pointer to a new node. } procedure get_node( var P: pointer ); begin memory_count := memory_count + 1 ; if memory_count > max_memory_count then max_memory_count := memory_count ; new( P ) end ; { return_node - Make the node pointed at by P "free" (available to get_node). } procedure return_node(var P: pointer) ; begin memory_count := memory_count - 1 ; { "scrub" memory to aid debugging } P^.value := 'I am free' ; P^.next := P ; dispose( P ) end ; { ================= QUEUE OPERATIONS ============================== } procedure create_empty( var q:queue ) ; begin q.front := nil ; q.rear := nil ; q.size := 0 ; end; { proc create_empty } function is_empty(q:queue): boolean ; begin if q.front = nil then is_empty := true else is_empty := false end; { fxn is_empty } procedure destroy( var q:queue ); var temp: queue ; begin if not is_empty(q) then begin temp := q ; temp.front := temp.front^.next ; destroy(temp) ; return_node(q.front) ; q.size := q.size - 1 ; end { if }; end; { proc destroy } procedure enqueue( v:element_type; var q:queue ) ; var p: pointer ; begin get_node(p) ; p^.value := v ; p^.next := nil ; if is_empty(q) then begin q.front := p ; q.rear := p ; end { if } else begin q.rear^.next := p ; q.rear := p ; end ; { else } inc(q.size) end; { proc enqueue } procedure serve( var q:queue ; var v:element_type ); var p: pointer ; begin if is_empty(q) then begin writeln('Error: attempting to serve from an empty queue.') ; goto 310 ; { halt } end { if } else begin v := q.front^.value ; p := q.front ; q.front := q.front^.next ; return_node(p) ; if q.front = nil then q.rear := nil ; q.size := q.size - 1 ; end { else } end; { proc serve } { ================= MAZE OPERATIONS ============================== } procedure read_maze( var M:maze ); var row,col: integer ; begin writeln('How many rows are in your maze (# columns must be the same) ?'); readln(M.size); if (M.size < 1) or (M.size > maxMazeSize) then begin writeln('error - bad maze size'); M.size := 0 end else begin writeln('enter each row of your maze on one line.'); writeln('each position should be either . (empty) or # (wall)'); for row := 1 to M.size do begin for col := 1 to M.size do read(M.map[row,col]) ; readln end end end; procedure check_path ( var path:element_type; var M:maze; var ok: boolean; var is_solution: boolean ); var len, i, row, col: integer ; tempM: maze ; { mark the positions visited to detect cycles } begin row := 1 ; col := 1 ; i := 1 ; len := length(path); ok := len < maxSolutionLength ; tempM := M ; while (i <= len) and ok do if not (path[i] in [left,right,up,down]) then ok := false else begin tempM.map[row,col] := wall ; case path[i] of left : begin col := col - 1 ; if (col < 1) or (tempM.map[row,col]<>free) then ok := false end; right: begin col := col + 1 ; if (col > M.size) or (tempM.map[row,col]<>free) then ok := false end; up : begin row := row - 1 ; if (row < 1) or (tempM.map[row,col]<>free) then ok := false end; down : begin row := row + 1 ; if (row > M.size) or (tempM.map[row,col]<>free) then ok := false end end ; i := i + 1 end ; is_solution := ok and (row = M.size) and (col = M.size) end; procedure write_path( var path:element_type; var M:maze ); var i,row,col: integer ; tempM: maze ; ok,is_solution: boolean ; begin write('The path <'); for i := 1 to length(path) do write(path[i]); write('>'); check_path(path,M,ok,is_solution) ; if not ok then begin writeln(' is not ok') end else begin row := 1 ; col := 1 ; tempM := M ; for i := 1 to length(path) do begin tempM.map[row,col] := path[i]; case path[i] of left : col := col - 1 ; right: col := col + 1 ; up : row := row - 1 ; down : row := row + 1 ; end end ; tempM.map[row,col] := '+' ; writeln(' looks as follows in the maze (it ends at ''+'').') ; for row := 1 to M.size do begin for col := 1 to M.size do write(tempM.map[row,col]); writeln end ; if is_solution then writeln('**** This path leads to the goal.') ; writeln end end; { ========================================================================= } procedure breadth_first_search(var M:maze; var path: element_type; var is_solution:boolean); var q: queue ; val : element_type ; good: boolean ; begin path := '' ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin create_empty(q) ; path := right ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if good then enqueue(path, q) ; path := down ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if good then enqueue(path, q) ; while (not is_solution) and (not is_empty(q) ) do begin serve(q, val) ; path := val + right ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + down ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + left ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if not is_solution then begin if good then enqueue(path, q) ; path := val + up ; check_path(path, M, good, is_solution) ; write_path(path,M) ; if (not is_solution) and good then enqueue(path, q) ; end ; writeln ; writeln('>> q.size is ', q.size) ; writeln ; end end end ; destroy(q) ; end; end ; procedure assignment5q1 ; var M: maze ; path: element_type ; is_solution: boolean ; begin read_maze(M); writeln ; breadth_first_search(M,path,is_solution); if is_solution then write_path(path,M) else writeln('there is no solution for this maze') end; {***** YOU MUST CHANGE THIS PROCEDURE TO DESCRIBE YOURSELF *****} procedure identify_myself ; { Writes who you are to the screen } begin writeln ; writeln('CSI 1101-X (winter, 1999). Assignment 5, Question 1.') ; writeln('Mark Sattolo, student# 428500.') ; writeln('tutorial section DGD-4, t.a. = Jensen Boire') ; writeln end ; begin { main program } identify_myself ; repeat max_memory_count := 0 ; memory_count := 0 ; assignment5q1 ; 310: writeln('Amount of dynamic memory allocated but not returned (should be 0) ', memory_count:0) ; writeln('Maximum dynamic memory allocated at one time in that run was ', max_memory_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(YESorNO); until (YESorNO <> 'y') end.
unit SimMLS; interface uses Languages; function GetLanguagePath( LangId : TLanguageId ) : string; procedure LoadMLS; implementation uses SysUtils; function GetLanguagePath( LangId : TLanguageId ) : string; begin result := ExtractFilePath(paramstr(0)) + 'Languages\ms\' + LangId + '\sim.lang'; end; procedure LoadMLS; var Dict : TDictionary; i : integer; root : string; begin root := ExtractFilePath(paramstr(0)) + 'languages\ms\'; Languages.LoadMLSFrom(root); for i := 0 to pred(LangList.Count) do begin Dict := TDictionary.Create(GetLanguagePath(LangList[i])); try Languages.ApplyDictionary( Dict, LangList[i] ); finally Dict.Free; end; end; end; { procedure LoadMLS; var Dict : TDictionary; i : integer; begin Languages.RequestLanguage( '0' ); Languages.RequestLanguage( '1' ); for i := 0 to pred(LangList.Count) do begin Dict := TDictionary.Create( GetLanguagePath( LangList[i] )); try Languages.ApplyDictionary( Dict, LangList[i] ); finally Dict.Free; end; end; end; } end.
unit GX_GrepPrinting; interface {$I GX_CondDefine.inc} uses Classes, Controls, GX_GrepBackend; type TGrepOutputMode = (grPrint, grCopy, grFile); TSaveToFileMode = (sfPrintToFile, sfSaveToLoadable, sfBoth); procedure SaveGrepResultsToFile(Owner: TWinControl; Results: TGrepHistoryList; AIniVersion: Integer; ASaveAll: Boolean; AMode: TSaveToFileMode; Where: TGrepOutputMode = grFile; AFileName: String = ''; ASplitCount: Integer = -1); implementation uses GX_GenericUtils, SysUtils, Graphics, ComCtrls, Dialogs, IniFiles, StrUtils, GX_GrepProgress; function OpenSaveDialog(var AFileName: String): Boolean; var SaveDlg: TSaveDialog; begin SaveDlg := TSaveDialog.Create(nil); try SaveDlg.DefaultExt := 'txt'; if Trim(AFileName) <> '' then begin if Trim(SaveDlg.FileName) <> '' then SaveDlg.InitialDir := ExtractFilePath(SaveDlg.FileName); SaveDlg.FileName := AFileName + '.' + SaveDlg.DefaultExt; end; SaveDlg.Filter := 'Text Files (*.txt, *.log)|*.txt;*.log|All Files (' +AllFilesWildCard+ ')|' + AllFilesWildCard; SaveDlg.Options := SaveDlg.Options + [ofOverwritePrompt]; Result := GetOpenSaveDialogExecute(SaveDlg); if Result then AFileName := SaveDlg.FileName; finally FreeAndNil(SaveDlg); end; end; procedure SaveResults(RichEdit: TRichEdit; AFileName: string; DoSaveDialog: Boolean); begin RichEdit.PlainText := True; if not DoSaveDialog or OpenSaveDialog(AFileName) then RichEdit.Lines.SaveToFile(AFileName); end; procedure PrintGeneric(Owner: TWinControl; Results: TGrepHistorySortableList; Where: TGrepOutputMode; const AFileName: string; DoSaveDialog, ASaveAll: Boolean; ASplitCount: Integer); var RichEdit: TRichEdit; procedure PrintResults(AResults: TStrings); var FileResult: TFileResult; Line: string; LinePos: Integer; i, j, c: Integer; AMatchResult: TMatchResult; MIndx: Integer; begin for i := 0 to AResults.Count - 1 do begin if AResults.Objects[i] is TFileResult then begin if RichEdit.Lines.Count > 0 then RichEdit.Lines.Add(''); // space between file AResults FileResult := TFileResult(AResults.Objects[i]); RichEdit.SelAttributes.Style := [fsBold]; RichEdit.Lines.Add(FileResult.FileName); RichEdit.SelAttributes.Style := []; for j := 0 to FileResult.Count - 1 do begin LinePos := RichEdit.GetTextLen; Line := FileResult.Items[j].Line; c := LeftTrimChars(Line); RichEdit.Lines.Add(Format(' %5d'#9, [FileResult.Items[j].LineNo]) + Line); // Now make the found Text bold for MIndx := 0 to FileResult.Items[j].Matches.Count-1 do begin AMatchResult := FileResult.Items[j].Matches[MIndx]; RichEdit.SelStart := LinePos + 7 - c + AMatchResult.SPos; RichEdit.SelLength := AMatchResult.EPos - AMatchResult.SPos + 1; RichEdit.SelAttributes.Style := [fsBold]; RichEdit.SelLength := 0; RichEdit.SelAttributes.Style := []; end; end; end; end; end; var HistoryItem: TGrepHistoryListItem; I: Integer; begin if Results.Count = 0 then Exit; RichEdit := TRichEdit.Create(Owner); try RichEdit.Visible := False; RichEdit.Parent := Owner; RichEdit.Font.Name := 'Arial'; RichEdit.Font.Size := 10; RichEdit.Clear; RichEdit.Lines.BeginUpdate; try for I := 0 to Results.Count-1 do begin HistoryItem := Results.Items[I]; if not ASaveAll and not HistoryItem.Checked then Continue; if RichEdit.Lines.Count > 0 then begin RichEdit.Lines.Add(''); // space between file AResults RichEdit.Lines.Add(''); end ; RichEdit.SelAttributes.Style := [fsBold, fsUnderline]; RichEdit.Lines.Add(HistoryItem.SearchText); RichEdit.SelAttributes.Style := []; PrintResults(HistoryItem.ResultList); if ASplitCount > 0 then begin Dec(ASplitCount); if ASplitCount = 0 then Break; end ; end; finally RichEdit.Lines.EndUpdate; end; case Where of grPrint: RichEdit.Print('GExperts - Grep Search Results'); grCopy: begin RichEdit.SelectAll; RichEdit.CopyToClipboard; end; grFile: SaveResults(RichEdit, AFileName, DoSaveDialog); end; finally FreeAndNil(RichEdit); end; end; procedure SaveGrepResultsToFile(Owner: TWinControl; Results: TGrepHistoryList; AIniVersion: Integer; ASaveAll: Boolean; AMode: TSaveToFileMode; Where: TGrepOutputMode; AFileName: String; ASplitCount: Integer); var AIni: TGrepIniFile; AFileNameExt, AFileNameForSave: String; AFileIndex: Integer; begin if (Where = grFile) and not OpenSaveDialog(AFileName) then Exit; TfmGrepProgress.Start; AFileNameExt := ExtractFileExt(AFileName); AFileName := ChangeFileExt(AFileName, ''); AFileIndex := 0; repeat AFileNameForSave := AFileName + IfThen(AFileIndex > 0, IntToStr(AFileIndex), '') + AFileNameExt; TfmGrepProgress.Progressing(AFileNameForSave); if AMode <> sfSaveToLoadable then PrintGeneric(Owner, Results.HistoryList, Where, AFileName, False, ASaveAll, ASplitCount); if AMode <> sfSaveToLoadable then TfmGrepProgress.Progressed; if AMode = sfPrintToFile then Exit; if (AMode <> sfBoth) and FileExists(AFileNameForSave) then DeleteFile(AFileNameForSave); AIni := TGrepIniFile.Create(AFileNameForSave); try Results.SaveToSettings(AIni, AIniVersion, ifmSingle, '', ASaveAll, False, False, 0, ASplitCount); finally AIni.Free; end; TfmGrepProgress.Progressed; Inc(AFileIndex); until not Results.AnyChecked; end; end.
unit MFichas.Model.Pagamento.Formas.Debito; interface uses System.SysUtils, MFichas.Model.Pagamento.Interfaces, MFichas.Model.Pagamento.Formas.Debito.Processar; type TModelPagamentoFormasDebito = class(TInterfacedObject, iModelPagamentoMetodos) private [weak] FParent: iModelPagamento; constructor Create(AParent: iModelPagamento); public destructor Destroy; override; class function New(AParent: iModelPagamento): iModelPagamentoMetodos; function Processar: iModelPagamentoMetodosProcessar; function Estornar : iModelPagamentoMetodosEstornar; function &End : iModelPagamento; end; implementation { TModelPagamentoFormasDebito } function TModelPagamentoFormasDebito.&End: iModelPagamento; begin Result := FParent; end; constructor TModelPagamentoFormasDebito.Create(AParent: iModelPagamento); begin FParent := AParent; end; destructor TModelPagamentoFormasDebito.Destroy; begin inherited; end; function TModelPagamentoFormasDebito.Estornar: iModelPagamentoMetodosEstornar; begin raise Exception.Create( 'Este método de pagamento ainda não está validado no sistema.' + sLineBreak + 'Por favor, utilize outro método.' ); end; class function TModelPagamentoFormasDebito.New(AParent: iModelPagamento): iModelPagamentoMetodos; begin Result := Self.Create(AParent); end; function TModelPagamentoFormasDebito.Processar: iModelPagamentoMetodosProcessar; begin Result := TModelPagamentoFormasDebitoProcessar.New(FParent); end; end.
unit DataStorage; interface uses Classes, SysUtils, math, supportptr; type PMemBlock=^TMemBlock; TMemBlock=record Count, MaxCount:integer; Addr:array[0..maxint shr PtrShiftCNT-100] of pointer; end; TListEx = class private FCount:integer; Mem:PMemBlock; Cache:record index, i, offset:integer; end; procedure GetCache(index:integer; var i, offset:integer); procedure SetCache(index, i, offset:integer); procedure CreateBlockMem(var mem:PMemBlock; size:integer); procedure FreeBlockMem(mem:PMemBlock); procedure ExtendBlockMem(var mem:PMemBlock; size:integer); function GetBlockMemItem(mem:PMemBlock; index:integer):pointer; procedure AddBlockItem(mem:PMemBlock; Item:pointer); procedure InsertBlockItem(mem:PMemBlock; index:integer; Item:pointer); procedure DeleteBlockItem(mem:PMemBlock; index:integer); procedure SplitBlockMemItem(source:PMemBlock; var destination:PMemBlock); function GetMemoryAddr(index:integer):pointer; protected function Get(index:integer):pointer; procedure Put(index:integer; item:pointer); public constructor Create; virtual; destructor Destroy; override; procedure Clear; function Add(Item:pointer):integer; procedure Delete(index:integer); procedure Insert(Index: Integer; Item: pointer); property Count:integer read FCount; property Items[index:integer]:pointer read Get write Put; default; end; TStringListEx=class private ItemList, MemList:TListEx; MemVolume:integer; MemPointer:pointer; function Get(Index:integer):string; procedure Put(Index:integer; const Value:string); procedure ClearValue(Index:integer); function GetCount:integer; public constructor Create; virtual; destructor Destroy; override; procedure Clear; function Add(value:string):integer; procedure Delete(Index:integer); procedure Insert(Index:integer; value:string); procedure Assign(List:TStringListEx); property Count:integer read GetCount; property Strings[index:integer]:string read Get write Put; default; end; TDataStorage=class private FColCount:integer; ItemList:TStringListEx; function GetValue(row, col:integer):string; procedure SetValue(row, col:integer; const ItemValue:string); function GetRowCount:integer; public constructor Create; virtual; destructor Destroy; override; procedure Clear; procedure AddRow; procedure DeleteRow(row:integer); procedure InsertRow(row:integer); property ColCount:integer read FColCount write FColCount; property Value[row, col:integer]:string read GetValue write SetValue; property RowCount:integer read GetRowCount; end; implementation Const MemBlockInc=1024; MemBlockMaxInc=256*1024; BlockSize=1024*1024; MaxSize=255; // byte+string or getmem(byte+integer+string) {TListEx} constructor TListEx.Create; begin inherited; Cache.index:=-1; CreateBlockMem(mem, MemBlockInc); FCount:=0; end; destructor TListEx.Destroy; begin Clear; FreeBlockMem(mem); inherited end; procedure TListEx.CreateBlockMem(var mem:PMemBlock; size:integer); begin GetMem(mem, sizeof(integer) shl 1 + size shl PtrShiftCNT); mem.Count:=0; mem.MaxCount:=size; end; procedure TListEx.FreeBlockMem(mem:PMemBlock); begin FreeMem(mem); end; procedure TListEx.ExtendBlockMem(var mem:PMemBlock; size:integer); var m:PMemBlock; begin m:=mem; CreateBlockMem(mem, size); movememory(@mem.Addr[0], @m.Addr[0], m.Count shl PtrShiftCNT); mem.Count:=m.Count; FreeBlockMem(m) end; procedure TListEx.AddBlockItem(mem:PMemBlock; Item:pointer); begin if mem.count<mem.maxcount then begin mem.Addr[mem.count]:=Item; inc(mem.count) end end; procedure TListEx.InsertBlockItem(mem:PMemBlock; index:integer; Item:pointer); begin if (index>=0)and(mem.count<mem.maxcount) then begin if index<mem.count then movememory(@mem.Addr[index+1], @mem.Addr[index], (mem.Count-index) shl PtrShiftCNT); mem.Addr[index]:=Item; inc(mem.count) end end; procedure TListEx.DeleteBlockItem(mem:PMemBlock; index:integer); begin if (index>=0)and(index<mem.count) then begin if index<mem.Count-1 then movememory(@mem.Addr[index], @mem.Addr[index+1], (mem.Count-index) shl PtrShiftCNT); dec(mem.count) end end; procedure TListEx.SplitBlockMemItem(source:PMemBlock; var destination:PMemBlock); var cnt:integer; begin cnt:=source.Count div 2; CreateBlockMem(destination, source.MaxCount); movememory(@destination.Addr[0], @source.Addr[cnt+1], cnt shl PtrShiftCNT); dec(source.Count, cnt); destination.Count:=cnt; end; function TListEx.GetBlockMemItem(mem:PMemBlock; index:integer):pointer; begin if (index>=0)and(index<mem.Count) then result:=mem.Addr[index] else result:=nil end; procedure TListEx.GetCache(index:integer; var i, offset:integer); begin if (Cache.index=-1) or (Cache.index>index) then begin i:=0; offset:=0 end else begin i:=Cache.i; offset:=Cache.offset end end; procedure TListEx.SetCache(index, i, offset:integer); begin Cache.index:=index; Cache.i:=i; Cache.offset:=offset end; function TListEx.GetMemoryAddr(index:integer):pointer; var m:PMemBlock; i,offset:integer; begin GetCache(index, i, offset); while i<mem.Count do begin m:=GetBlockMemItem(mem, i); if (index>=offset)and(index<offset+m.Count) then begin SetCache(index, i, offset); result:=@m.Addr[index-offset]; exit end; inc(offset, m.count); inc(i); end; result:=nil end; procedure TListEx.Clear; var i:integer; m:PMemBlock; begin for i:=0 to mem.Count-1 do begin m:=GetBlockMemItem(mem, i); FreeBlockMem(m); end; Cache.index:=-1; mem.Count:=0; FCount:=0; end; function TListEx.Get(index:integer):pointer; var p:pointer; begin p:=GetMemoryAddr(index); if p<>nil then result:=ppointer(p)^ end; procedure TListEx.Put(index:integer; item:pointer); var p:pointer; begin p:=GetMemoryAddr(index); if p<>nil then ppointer(p)^:=item end; function TListEx.Add(Item:pointer):integer; var m:PMemBlock; begin m:=GetBlockMemItem(mem, mem.Count-1); if m=nil then begin CreateBlockMem(m, MemBlockInc); AddBlockItem(mem, m); end else if m.Count>m.MaxCount-64 then begin CreateBlockMem(m, min(m.MaxCount shl 1, MemBlockMaxInc)); if mem.Count=mem.MaxCount then ExtendBlockMem(mem, mem.MaxCount+MemBlockInc); AddBlockItem(mem, m); end; AddBlockItem(m, Item); result:=FCount; inc(FCount); end; procedure TListEx.Insert(Index: Integer; Item: Pointer); var m,ms:PMemBlock; i,offset:integer; begin GetCache(index, i, offset); while i<mem.Count do begin m:=GetBlockMemItem(mem, i); if (index>=offset)and(index<offset+m.Count) then begin if m.Count<m.MaxCount then InsertBlockItem(m, index-offset, Item) else begin SplitBlockMemItem(m, ms); if mem.Count=mem.MaxCount then ExtendBlockMem(mem, mem.MaxCount+MemBlockInc); InsertBlockItem(mem, i+1, ms); continue end; SetCache(index, i, offset); inc(FCount); exit end; inc(offset, m.count); inc(i); end; Add(Item) end; procedure TListEx.Delete(index:integer); var m:PMemBlock; i,offset:integer; begin GetCache(index, i, offset); while i<mem.Count do begin m:=GetBlockMemItem(mem, i); if (index>=offset)and(index<offset+m.Count) then begin SetCache(index, i, offset); DeleteBlockItem(m, index-offset); dec(FCount); exit end; inc(offset, m.count); inc(i); end; end; {TStringListEx} constructor TStringListEx.Create; begin inherited; ItemList:=TListEx.Create; MemList:=TListEx.Create; MemVolume:=0; end; destructor TStringListEx.Destroy; begin Clear; ItemList.Free; MemList.Free; inherited end; function TStringListEx.Get(index:integer):string; var p:pointer; len:integer; begin p:=ItemList[index]; if p=nil then result:='' else begin if pbyte(p)^ = MaxSize then begin len:=pint(PtrINC(p, sizeof(byte)))^; SetLength(result, len); CopyMemory(pchar(result), PtrINC(p, sizeof(byte)+sizeof(integer)), len); end else begin len:=pbyte(p)^; SetLength(result, len); CopyMemory(pchar(result), PtrINC(p, sizeof(byte)), len); end end end; procedure TStringListEx.ClearValue(Index:integer); var p:pointer; begin p:=ItemList[Index]; if (p <> nil) and (pbyte(p)^ = MaxSize) then freemem(p) end; procedure TStringListEx.Put(index:integer; const Value:string); var p:pointer; len:integer; begin ClearValue(index); len:=length(Value); if len=0 then ItemList[index]:=nil else begin if len>=MaxSize then begin getmem(p, sizeof(byte)+sizeof(integer)+len); pbyte(p)^:=MaxSize; pint(PtrINC(p, sizeof(byte)))^:=len; CopyMemory(PtrINC(p, sizeof(byte)+sizeof(integer)), pchar(Value), len); end else begin if len+sizeof(byte) > MemVolume then begin getmem(MemPointer, BlockSize); MemList.Add(MemPointer); MemVolume:=BlockSize; end; p:=MemPointer; MemPointer:=PtrINC(MemPointer, sizeof(byte)+len); MemVolume:=MemVolume-(sizeof(byte)+len); pbyte(p)^:=len; CopyMemory(PtrINC(p, sizeof(byte)), pchar(Value), len); end; ItemList[index]:=p; end end; procedure TStringListEx.Clear; var i:integer; begin for i:=0 to ItemList.Count-1 do ClearValue(i); ItemList.Clear; for i:=0 to MemList.Count-1 do freemem(MemList[i]); MemList.Clear; MemVolume:=0; end; function TStringListEx.Add(value:string):integer; begin result:=ItemList.Add(nil); Put(result, value) end; procedure TStringListEx.Delete(index:integer); begin ClearValue(index); ItemList.Delete(index) end; procedure TStringListEx.Insert(index:integer; value:string); begin ItemList.Insert(index, nil); Put(index, value); end; procedure TStringListEx.Assign(List:TStringListEx); var i:integer; begin Clear; for i:=0 to List.Count-1 do Add(List[i]); end; function TStringListEx.GetCount:integer; begin result:=ItemList.Count end; {TDataStorage} constructor TDataStorage.Create; begin inherited; ItemList:=TStringListEx.Create; end; destructor TDataStorage.Destroy; begin ItemList.Free; inherited end; function TDataStorage.GetValue(row, col:integer):string; begin result:=ItemList[row*FColCount+col]; end; procedure TDataStorage.SetValue(row, col:integer; const ItemValue:string); begin ItemList[row*FColCount+col]:=ItemValue; end; procedure TDataStorage.Clear; begin ItemList.Clear; end; procedure TDataStorage.AddRow; var i:integer; begin for i:=0 to FColCount-1 do ItemList.Add('') end; procedure TDataStorage.DeleteRow(row:integer); var i:integer; begin for i:=0 to FColCount-1 do ItemList.Delete(row*FColCount) end; procedure TDataStorage.InsertRow(row:integer); var i:integer; begin for i:=0 to FColCount-1 do ItemList.Insert(row*FColCount+i, '') end; function TDataStorage.GetRowCount:integer; begin result:=ItemList.Count div FColCount end; end.
unit GX_eComment; {$I GX_CondDefine.inc} interface uses GX_eSelectionEditorExpert, GX_ConfigurationInfo, Classes, StdCtrls, Controls, Forms, GX_BaseForm, ExtCtrls, ComCtrls; type // // ctSlash // (* *) ctC // { } ctPascal // /* */ ctCpp // -- (SQL) ctSQL TCommentType = (ctSlash, ctC, ctPascal, ctCpp, ctSQL); TExtensionStyle = class(TObject) private FExtensions: String; FCommentType: TCommentType; FInsertRemoveSpace: Boolean; FIsDefault: Boolean; protected public constructor Create; property Extensions: String read FExtensions write FExtensions; property CommentType: TCommentType read FCommentType write FCommentType; property InsertRemoveSpace: Boolean read FInsertRemoveSpace write FInsertRemoveSpace; property IsDefault: Boolean read FIsDefault write FIsDefault; end; TCommentStyles = class(TStringList) private procedure ClearStyles; protected public destructor Destroy; override; procedure Clear; override; function GetStyle(const AFileName: String): TExtensionStyle; procedure CopyStyles(AFromStyles: TCommentStyles); end; TCommentExpert = class(TSelectionEditorExpert) protected procedure InternalSaveSettings(Settings: TExpertSettings); override; procedure InternalLoadSettings(Settings: TExpertSettings); override; function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; procedure Configure; override; function GetHelpString: string; override; end; TUnCommentExpert = class(TSelectionEditorExpert) protected function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; TfmCommentConfig = class(TfmBaseForm) gbStyles: TGroupBox; lvStyles: TListView; gbStyle: TGroupBox; lblExtensions: TLabel; eExtensions: TEdit; rgStyle: TRadioGroup; chkInsertSpace: TCheckBox; btnAdd: TButton; btnDelete: TButton; btnOK: TButton; btnCancel: TButton; procedure lvStylesData(Sender: TObject; Item: TListItem); procedure lvStylesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure eExtensionsChange(Sender: TObject); procedure rgStyleClick(Sender: TObject); procedure chkInsertSpaceClick(Sender: TObject); private FStyles: TCommentStyles; FCurrStyle: TExtensionStyle; FCurrIndex: Integer; function ConvertStyleTypeToViewedType(AStyleType: TCommentType): Integer; function ConvertViewedTypeToStyleType(AViewedType: Integer): TCommentType; protected procedure Initialize; end; implementation {$R *.dfm} uses SysUtils, StrUtils, Math, GX_EditorExpert, GX_OtaUtils; var // This is *local* and used by both the comment // and the uncomment expert... Styles: TCommentStyles; const cNameDefaultStyle = 'Default style'; cIniStyleCount = 'StyleCount'; cIniExtensions = 'Extensions'; cIniCommentType = 'CommentType'; cIniInsertRemoveSpace = 'InsertRemoveSpace'; { TCommentExpert } procedure TCommentExpert.Configure; var Dlg: TfmCommentConfig; begin Dlg := TfmCommentConfig.Create(nil); try Dlg.Initialize; if Dlg.ShowModal = mrOk then begin Styles.CopyStyles(Dlg.FStyles); SaveSettings; end; finally FreeAndNil(Dlg); end; end; constructor TCommentExpert.Create; begin inherited Create; end; function TCommentExpert.GetDefaultShortCut: TShortCut; const VK_OEM_PERIOD = $BE; // '.' any country begin Result := scCtrl + scAlt + VK_OEM_PERIOD; end; function TCommentExpert.GetDisplayName: string; resourcestring SCommentName = 'Comment Code'; begin Result := SCommentName; end; function TCommentExpert.GetHelpString: string; resourcestring SCommentHelp = ' This expert comments out a selected block of code. ' + 'To use it, select a block in the Delphi editor and ' + 'activate this expert.' + sLineBreak + sLineBreak + ' You can configure this expert to use different comment styles.'; begin Result := SCommentHelp; end; class function TCommentExpert.GetName: string; begin Result := 'Comment'; end; procedure TCommentExpert.InternalLoadSettings(Settings: TExpertSettings); var I, ACount: Integer; AIndexText: String; AStyle: TExtensionStyle; begin inherited InternalLoadSettings(Settings); // Do not localize any of the below items. Styles.Clear; ACount := Settings.ReadInteger(cIniStyleCount, 1); //1= default style is always created for I := 0 to ACount-1 do begin AStyle := TExtensionStyle.Create; AStyle.IsDefault := I = 0; AIndexText := IfThen(not AStyle.IsDefault, IntToStr(I)); AStyle.Extensions := Settings.ReadString(cIniExtensions + AIndexText, cNameDefaultStyle); AStyle.CommentType := TCommentType(Settings.ReadEnumerated(cIniCommentType + AIndexText, TypeInfo(TCommentType), Ord(ctSlash))); AStyle.InsertRemoveSpace := Settings.ReadBool(cIniInsertRemoveSpace + AIndexText, False); Styles.AddObject(AStyle.Extensions, AStyle); end; end; procedure TCommentExpert.InternalSaveSettings(Settings: TExpertSettings); var I, ACount: Integer; AIndexText: String; AStyle: TExtensionStyle; begin inherited InternalSaveSettings(Settings); // Do not localize any of the below items. ACount := Settings.ReadInteger(cIniStyleCount, 0); Settings.WriteInteger(cIniStyleCount, Styles.Count); for I := 0 to Styles.Count-1 do begin AStyle := TExtensionStyle(Styles.Objects[I]); AIndexText := IfThen(not AStyle.IsDefault, IntToStr(I)); if not AStyle.IsDefault then Settings.WriteString(cIniExtensions + AIndexText, AStyle.Extensions); Settings.WriteEnumerated(cIniCommentType + AIndexText, TypeInfo(TCommentType), Ord(AStyle.CommentType)); Settings.WriteBool(cIniInsertRemoveSpace + AIndexText, AStyle.InsertRemoveSpace); end; for I := Styles.Count to ACount-1 do begin AIndexText := IntToStr(I); Settings.DeleteKey(cIniExtensions + AIndexText); Settings.DeleteKey(cIniCommentType + AIndexText); Settings.DeleteKey(cIniInsertRemoveSpace + AIndexText); end; end; function TCommentExpert.ProcessSelected(Lines: TStrings): Boolean; var i: Integer; CommentPrefix: string; AStyle: TExtensionStyle; procedure AddBracketing(const CodeList: TStrings; const LeftBracket, RightBracket: string); begin if AStyle.InsertRemoveSpace then begin CodeList[0] := LeftBracket + ' ' + CodeList[0]; CodeList[CodeList.Count - 1] := CodeList[CodeList.Count - 1] + ' ' + RightBracket; end else begin CodeList[0] := LeftBracket + CodeList[0]; CodeList[CodeList.Count - 1] := CodeList[CodeList.Count - 1] + RightBracket; end; end; begin Assert(Assigned(Lines)); AStyle := Styles.GetStyle(GxOtaGetTopMostEditBufferFileName); // Do not localize any of the below lines. case AStyle.CommentType of ctSlash: begin CommentPrefix := '//' + IfThen(AStyle.InsertRemoveSpace, ' '); for i := 0 to Lines.Count - 1 do Lines[i] := CommentPrefix + Lines[i]; end; ctSQL: begin CommentPrefix := '--' + IfThen(AStyle.InsertRemoveSpace, ' '); for i := 0 to Lines.Count - 1 do Lines[i] := CommentPrefix + Lines[i]; end; ctC: AddBracketing(Lines, '(*', '*)'); ctCpp: AddBracketing(Lines, '/*', '*/'); ctPascal: AddBracketing(Lines, '{', '}'); else Assert(False); end; Result := True; end; { TUncommentExpert } constructor TUnCommentExpert.Create; begin inherited Create; end; function TUnCommentExpert.GetDefaultShortCut: TShortCut; const VK_OEM_COMMA = $BC; // ',' any country begin Result := scCtrl + scAlt + VK_OEM_COMMA; end; function TUnCommentExpert.GetDisplayName: string; resourcestring SUncommentName = 'Uncomment Code'; begin Result := SUncommentName; end; function TUnCommentExpert.GetHelpString: string; resourcestring SUncommentHelp = ' This expert uncomments a selected block of code. ' + 'To use it, select a block in the IDE code editor and ' + 'activate this expert.' + sLineBreak + ' Uncommenting is performed using the comment style that ' + 'you selected for the Comment Code editor expert.'; begin Result := SUncommentHelp; end; class function TUnCommentExpert.GetName: string; begin Result := 'UnComment'; end; function TUnCommentExpert.HasConfigOptions: Boolean; begin Result := False; end; function TUnCommentExpert.ProcessSelected(Lines: TStrings): Boolean; var AStyle: TExtensionStyle; function RemoveFirstString(const SubString, InString: string): string; var Success: Boolean; function RemoveFirstInternal(const SubString, InString: string): string; var SubStringPos: Integer; begin if StrLComp(PChar(Trim(InString)), PChar(SubString), Length(SubString)) = 0 then begin SubStringPos := Pos(SubString, InString); if SubStringPos > 1 then begin Result := Copy(InString, 1, SubStringPos - 1) + Copy(InString, SubStringPos + Length(SubString), MaxInt) end else Result := Copy(InString, Length(SubString) + 1, MaxInt); Success := True; end else Result := InString; end; begin Success := False; // If spaces are to be removed, try to first kill // WITH space, otherwise continue with default // comment removal. if AStyle.InsertRemoveSpace then begin Result := RemoveFirstInternal(SubString + ' ', InString); if Success then Exit; end; Result := RemoveFirstInternal(SubString, InString); end; function RemoveLastString(const SubString, InString: string): string; var Success: Boolean; function RemoveLastInternal(const SubString, InString: string): string; var SubStringStartPos: Integer; TempString: string; begin TempString := TrimRight(InString); SubStringStartPos := Length(TempString) - Length(SubString) + 1; if SubString = Copy(TempString, SubStringStartPos, Length(SubString)) then begin Result := Copy(TempString, 1, SubStringStartPos - 1); Success := True; end else Result := InString; end; begin Success := False; // If spaces are to be removed, try to first kill // WITH space, otherwise continue with default // comment removal. if AStyle.InsertRemoveSpace then begin Result := RemoveLastInternal(' ' + SubString, InString); if Success then Exit; end; Result := RemoveLastInternal(SubString, InString); end; var i: Integer; begin Assert(Assigned(Lines)); AStyle := Styles.GetStyle(GxOtaGetTopMostEditBufferFileName); case AStyle.CommentType of ctSlash: for i := 0 to Lines.Count - 1 do Lines[i] := RemoveFirstString('//', Lines[i]); ctC: begin Lines[0] := RemoveFirstString('(*', Lines[0]); Lines[Lines.Count - 1] := RemoveLastString('*)', Lines[Lines.Count - 1]); end; ctCpp: begin Lines[0] := RemoveFirstString('/*', Lines[0]); Lines[Lines.Count - 1] := RemoveLastString('*/', Lines[Lines.Count - 1]); end; ctPascal: begin Lines[0] := RemoveFirstString('{', Lines[0]); Lines[Lines.Count - 1] := RemoveLastString('}', Lines[Lines.Count - 1]); end; ctSQL: for i := 0 to Lines.Count - 1 do Lines[i] := RemoveFirstString('--', Lines[i]); end; Result := True; end; { TExtensionStyle } constructor TExtensionStyle.Create; begin inherited Create; FExtensions := ''; FCommentType := ctSlash; FInsertRemoveSpace := False; end; { TCommentStyles } destructor TCommentStyles.Destroy; begin ClearStyles; inherited Destroy; end; procedure TCommentStyles.ClearStyles; var I: Integer; begin for I := 0 to Count-1 do Objects[I].Free; end; procedure TCommentStyles.Clear; begin ClearStyles; inherited Clear; end; function TCommentStyles.GetStyle(const AFileName: String): TExtensionStyle; var I: Integer; AExt: String; begin AExt := ExtractFileExt(AFileName); if LeftStr(AExt, 1) = '.' then AExt := Copy(AExt, 2, MaxInt); for I := 1 to Count-1 do if AnsiContainsText(Strings[I], AExt) then begin Result := TExtensionStyle(Objects[I]); Exit; end; Result := TExtensionStyle(Objects[0]); end; procedure TCommentStyles.CopyStyles(AFromStyles: TCommentStyles); var I: Integer; AStyle, AFromStyle: TExtensionStyle; begin Clear; for I := 0 to AFromStyles.Count-1 do begin AFromStyle := TExtensionStyle(AFromStyles.Objects[I]); AStyle := TExtensionStyle.Create; AStyle.Extensions := AFromStyle.Extensions; AStyle.CommentType := AFromStyle.CommentType; AStyle.InsertRemoveSpace := AFromStyle.InsertRemoveSpace; AStyle.IsDefault := AFromStyle.IsDefault; AddObject(AStyle.Extensions, AStyle); end; end; { TfmCommentConfig } procedure TfmCommentConfig.FormCreate(Sender: TObject); begin FStyles := TCommentStyles.Create; FCurrIndex := -1; FCurrStyle := nil; end; procedure TfmCommentConfig.FormDestroy(Sender: TObject); begin FStyles.Free; end; procedure TfmCommentConfig.Initialize; begin FStyles.CopyStyles(Styles); lvStyles.Clear; lvStyles.Items.Count := FStyles.Count; lvStyles.ItemIndex := 0; end; // // ctSlash // { } ctPascal // -- (SQL) ctSQL // /* */ ctCpp // (* *) ctC // TCommentType = (ctSlash, ctC, ctPascal, ctCpp, ctSQL); function TfmCommentConfig.ConvertStyleTypeToViewedType(AStyleType: TCommentType): Integer; const cCommentTypeArray: array[TCommentType] of Integer = (0, 4, 1, 3, 2); begin Result := cCommentTypeArray[AStyleType]; end; function TfmCommentConfig.ConvertViewedTypeToStyleType(AViewedType: Integer): TCommentType; const cViewedArray: array[0..Integer(High(TCommentType))] of TCommentType = (ctSlash, ctPascal, ctSQL, ctCpp, ctC); begin Result := cViewedArray[AViewedType]; end; procedure TfmCommentConfig.lvStylesData(Sender: TObject; Item: TListItem); var AStyle: TExtensionStyle; begin AStyle := TExtensionStyle(FStyles.Objects[Item.Index]); Item.Caption := AStyle.Extensions; Item.SubItems.Add( rgStyle.Items[ ConvertStyleTypeToViewedType(AStyle.CommentType) ] ); Item.SubItems.Add( BoolToStr(AStyle.InsertRemoveSpace, True) ); end; procedure TfmCommentConfig.lvStylesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if not Selected then Exit; FCurrIndex := Item.Index; FCurrStyle := TExtensionStyle(FStyles.Objects[FCurrIndex]); eExtensions.Text := FCurrStyle.Extensions; eExtensions.ReadOnly := FCurrStyle.IsDefault; rgStyle.ItemIndex := ConvertStyleTypeToViewedType(FCurrStyle.CommentType); chkInsertSpace.Checked := FCurrStyle.InsertRemoveSpace; btnDelete.Enabled := not FCurrStyle.IsDefault; end; procedure TfmCommentConfig.btnAddClick(Sender: TObject); begin FStyles.AddObject('Style' + IntToStr(FStyles.Count), TExtensionStyle.Create); lvStyles.Items.Count := FStyles.Count; lvStyles.ItemIndex := FStyles.Count-1; eExtensions.SetFocus; end; procedure TfmCommentConfig.btnDeleteClick(Sender: TObject); begin lvStyles.SetFocus; FCurrStyle.Free; FStyles.Delete(FCurrIndex); lvStyles.Items.Count := FStyles.Count; lvStyles.ItemIndex := Min(FCurrIndex, FStyles.Count-1); end; procedure TfmCommentConfig.eExtensionsChange(Sender: TObject); begin if eExtensions.ReadOnly then Exit; FCurrStyle.Extensions := eExtensions.Text; FStyles[FCurrIndex] := eExtensions.Text; lvStyles.Refresh; end; procedure TfmCommentConfig.rgStyleClick(Sender: TObject); begin FCurrStyle.CommentType := ConvertViewedTypeToStyleType(rgStyle.ItemIndex); lvStyles.Refresh; end; procedure TfmCommentConfig.chkInsertSpaceClick(Sender: TObject); begin FCurrStyle.InsertRemoveSpace := chkInsertSpace.Checked; lvStyles.Refresh; end; initialization Styles := TCommentStyles.Create; RegisterEditorExpert(TCommentExpert); RegisterEditorExpert(TUnCommentExpert); finalization Styles.Free; end.
{Sabine Wolf,5999219,q5999219@bonsai.fernuni-hagen.de} {In dieser Unit stecken nuetzliche kleine Funktionen, die an vielen Stellen gebraucht werden.} unit gomutil; interface {gibt das Vorzeichen einer Zahl als -1,0 oder 1 zurueck} function sgn(x:integer):integer; {Gibt ein integer als string zurueck.} function intstr(i: integer ): string; {Gibt den kleineren wert zurueck.} function min(a,b : integer):integer; {Gibt den kleineren Real-Wert zurueck.} function minr(a,b : real):real; {Gibt den groesseren wert zurueck.} function max(a,b : integer):integer; function maxr(a,b : real):real; implementation function sgn(x:integer):integer; begin if x<0 then sgn:=-1 else if x>0 then sgn:=1 else sgn:=0; end; function intstr(i: integer ): string; var s : string; begin str(i,s); intstr:=s; end; { intstr } function min(a,b : integer):integer; begin if a>b then min:=b else min:=a; end; { min } function minr(a,b : real):real; begin if a>b then minr:=b else minr:=a; end; { minr } function max(a,b : integer):integer; begin if a<b then max:=b else max:=a; end; { max } function maxr(a,b : real):real; begin if a<b then maxr:=b else maxr:=a; end; { maxr } begin end.
unit DataTvary; interface uses VCLTee.TeeProcs, Types, Classes, Controls, Graphics; type //vymenovanie tvarov TDruhTvaru = (tvNeurceny, tvObdlznik, tvOval, tvTrojuholnikP, tvTrojuholnikR, tvSipka); TTvar = class(TObject) private FDlzkaSpice: Integer; FDruhTvaru: TDruhTvaru; FFarba: TColor; FFarbaCiary: TColor; FHore: Integer; FHrubkaCiary: Byte; FHrubkaSpice: Integer; FSirka: Integer; FVlavo: Integer; FVyska: Integer; FZobrazit: Boolean; protected function GetNazov: String; virtual; public constructor Create; function PointInTvar(P: TPoint) : Boolean; virtual; abstract; procedure LoadFromStream (AStream : TFileStream); virtual; procedure Nakreslit(ACanvas: TCanvas); virtual; procedure SaveToStream (AStream : TFileStream); virtual; property DlzkaSpice: Integer read FDlzkaSpice write FDlzkaSpice; property DruhTvaru: TDruhTvaru read FDruhTvaru; property Farba: TColor read FFarba write FFarba; property FarbaCiary: TColor read FFarbaCiary write FFarbaCiary; property Hore: Integer read FHore write FHore; property HrubkaCiary: Byte read FHrubkaCiary write FHrubkaCiary; property HrubkaSpice: Integer read FHrubkaSpice write FHrubkaSpice; property Nazov: String read GetNazov; property Sirka: Integer read FSirka write FSirka; property Vlavo: Integer read FVlavo write FVlavo; property Vyska: Integer read FVyska write FVyska; property Zobrazit: Boolean read FZobrazit write FZobrazit; end; TObdlznik = class(TTvar) protected function GetNazov: String; override; public constructor Create; function PointInTvar(P: TPoint) : Boolean; override; procedure Nakreslit(ACanvas: TCanvas); override; end; TOval = class(TTvar) protected function GetNazov: String; override; public constructor Create; function PointInTvar(P: TPoint) : Boolean; override; procedure Nakreslit(ACanvas: TCanvas); override; end; TTrojuholnikP = class(TTvar) protected function GetNazov: String; override; public constructor Create; function PointInTvar(P: TPoint) : Boolean; override; procedure Nakreslit(ACanvas: TCanvas); override; end; TTrojuholnikR = class(TTvar) protected function GetNazov : String; override; public constructor Create; function PointInTvar(P: TPoint) : Boolean; override; procedure Nakreslit (ACanvas: TCanvas); override; end; TSipka = class(TTvar) protected function GetNazov: String; override; public constructor Create; function PointInTvar(P: TPoint) : Boolean; override; procedure Nakreslit(ACanvas: TCanvas); override; end; TZoznamTvarov = class(TObject) private FList: TList; public constructor Create; destructor Destroy; override; function GetTvar(Index: Integer): TTvar; function GetTvarPoint(P: TPoint) : TTvar; procedure SaveToStream (ANazovSuboru: String); procedure LoadFromStream(ANazovSuboru: String); procedure OdstranitTvar(Index: Integer); function PridatTvar(DruhTvaru: TDruhTvaru): TTvar; procedure Prekreslit(Canvas: TCanvas); procedure ZmazatVsetko; end; implementation uses SysUtils; {$Region ' TTvar '} constructor TTvar.Create; begin inherited Create; FDruhTvaru := tvNeurceny; FVlavo := 10; FHore := 10; FSirka := 100; FVyska := 100; FFarba := clWhite; FFarbaCiary := clBlack; FHrubkaCiary := 2; FZobrazit := True; end; function TTvar.GetNazov: String; begin Result := 'Neurceny'; end; procedure TTvar.Nakreslit(ACanvas: TCanvas); begin with ACanvas do begin Pen.Color := FarbaCiary; Pen.Width := HrubkaCiary; Brush.Color := Farba; end; end; //ukladanie projektu - parametre procedure TTvar.SaveToStream(AStream: TFileStream); begin with AStream do begin Write(FVlavo, SizeOf(FVlavo)); Write(FHore, SizeOf(FHore)); Write(FSirka, SizeOf(FSirka)); Write(FVyska, SizeOf(FVyska)); Write(FFarba, SizeOf(FFarba)); Write(FFarbaCiary, SizeOf(FFarbaCiary)); Write(FHrubkaCiary, SizeOf(FHrubkaCiary)); Write(FZobrazit, SizeOf(FZobrazit)); Write(FDlzkaSpice, SizeOf(FDlzkaSpice)); Write(FHrubkaSpice, SizeOf(FHrubkaSpice)); end; end; //otvaranie projektu - parametre procedure TTvar.LoadFromStream(AStream: TFileStream); begin with AStream do begin Read(FVlavo, SizeOf(FVlavo)); Read(FHore, SizeOf(FHore)); Read(FSirka, SizeOf(FSirka)); Read(FVyska, SizeOf(FVyska)); Read(FFarba, SizeOf(FFarba)); Read(FFarbaCiary, SizeOf(FFarbaCiary)); Read(FHrubkaCiary, SizeOf(FHrubkaCiary)); Read(FZobrazit, SizeOf(FZobrazit)); Read(FDlzkaSpice, SizeOf(FDlzkaSpice)); Read(FHrubkaSpice, SizeOf(FHrubkaSpice)); end; end; {$EndRegion} {$Region ' TObdlznik '} constructor TObdlznik.Create; begin inherited Create; FDruhTvaru := tvObdlznik; end; function TObdlznik.GetNazov: String; begin Result := 'Obdĺžnik'; end; procedure TObdlznik.Nakreslit(ACanvas: TCanvas); begin if Zobrazit then begin inherited Nakreslit(ACanvas); ACanvas.Rectangle(Vlavo, Hore, Vlavo + Sirka, Hore + Vyska); end; end; function TObdlznik.PointInTvar(P: TPoint) : Boolean; var P1, P2, P3, P4: TPoint; begin P1 := Point(Vlavo, Hore); P1 := Point(Vlavo + Sirka, Hore); P1 := Point(Vlavo + Sirka, Hore + Vyska); P1 := Point(Vlavo, Hore + Vyska); Result := PointInPolygon(P, [P1, P2, P3, P4]); end; {$EndRegion} {$Region ' TOval '} constructor TOval.Create; begin inherited Create; FDruhTvaru := tvOval; end; function TOval.GetNazov: String; begin Result := 'Ovál'; end; procedure TOval.Nakreslit(ACanvas: TCanvas); begin if Zobrazit then begin inherited Nakreslit(ACanvas); ACanvas.Ellipse(Vlavo, Hore, Vlavo + Sirka, Hore + Vyska); end; end; function TOval.PointInTvar(P: TPoint): Boolean; var P1, P2, P3, P4 : TPoint; begin P1 := Point(Vlavo, Hore); P1 := Point(Vlavo + Sirka, Hore); P1 := Point(Vlavo + Sirka, Hore + Vyska); P1 := Point(Vlavo, Hore + Vyska); Result := PointInPolygon(P, [P1, P2, P3, P4]); end; {$EndRegion} {$Region ' TTrojuholnikP '} constructor TTrojuholnikP.Create; begin inherited Create; FDruhTvaru := tvTrojuholnikP; end; function TTrojuholnikP.GetNazov: String; begin Result := 'Pravouhlý trojuholník'; end; procedure TTrojuholnikP.Nakreslit(ACanvas: TCanvas); var P1, P2, P3: TPoint; begin if Zobrazit then begin inherited Nakreslit(ACanvas); P1:= Point(Vlavo, Hore); P2:= Point(Vlavo, Hore+Vyska); P3:= Point(Vlavo+Sirka, Hore+Vyska); ACanvas.Polygon([P1, P2, P3]); end; end; function TTrojuholnikP.PointInTvar(P: TPoint): Boolean; var P1, P2, P3 : TPoint; begin P1 := Point(Vlavo, Hore); P2 := Point(Vlavo, Hore + Vyska); P3 := Point(Vlavo + Sirka, Hore + Vyska); Result := PointInPolygon(P, [P1, P2, P3]); end; {$EndRegion} {$Region 'TrojuholnikR '} constructor TTrojuholnikR.Create; begin inherited Create; FDruhTvaru := tvTrojuholnikR; end; function TTrojuholnikR.GetNazov: String; begin Result := 'Rovnostranný trojuholník'; end; procedure TTrojuholnikR.Nakreslit(ACanvas: TCanvas); var P1, P2, P3: TPoint; begin if Zobrazit then begin inherited Nakreslit(ACanvas); P1 := Point(Vlavo, Hore + Vyska); P2 := Point (Vlavo + Sirka, Hore + Vyska); P3 := Point (Vlavo + Sirka div 2, Hore); Acanvas.Polygon([P1, P2, P3]); end; end; function TTrojuholnikR.PointInTvar(P: TPoint): Boolean; var P1, P2, P3 : TPoint; begin P1 := Point(Vlavo, Hore + Vyska); P2 := Point (Vlavo + Sirka, Hore + Vyska); P3 := Point (Vlavo + Sirka div 2, Hore); Result := PointInPolygon(P, [P1, P2, P3]); end; {$EndRegion} {$Region ' TSipka '} constructor TSipka.Create; begin inherited Create; FDruhTvaru := tvSipka; end; function TSipka.GetNazov: String; begin Result := 'Šípka'; end; procedure TSipka.Nakreslit(ACanvas: TCanvas); var P1, P2, P3, P4, P5, P6, P7: TPoint; begin if Zobrazit then begin inherited Nakreslit(ACanvas); P1:= Point(Vlavo, Hore); P2:= Point(Vlavo + Sirka, Hore); P3:= Point(Vlavo + Sirka, Hore - HrubkaSpice); P4:= Point(Vlavo + Sirka + DlzkaSpice, Hore + Vyska div 2); P5:= Point(Vlavo + Sirka, Hore + Vyska + HrubkaSpice); P6:= Point(Vlavo + Sirka, Hore + Vyska); P7:= Point(Vlavo, Hore + Vyska); ACanvas.Polygon([P1, P2, P3, P4, P5, P6, P7]); end; end; function TSipka.PointInTvar(P: TPoint) : Boolean; var P1, P2, P3, P4, P5, P6, P7: TPoint; begin P1:= Point(Vlavo, Hore); P2:= Point(Vlavo + Sirka, Hore); P3:= Point(Vlavo + Sirka, Hore - HrubkaSpice); P4:= Point(Vlavo + Sirka + DlzkaSpice, Hore + Vyska div 2); P5:= Point(Vlavo + Sirka, Hore + Vyska + HrubkaSpice); P6:= Point(Vlavo + Sirka, Hore + Vyska); P7:= Point(Vlavo, Hore + Vyska); Result := PointInPolygon(P, [P1, P2, P3, P4, P5, P6, P7]); end; {$EndRegion} {$Region ' TZoznamTvarov '} constructor TZoznamTvarov.Create; begin inherited Create; FList := TList.Create; end; destructor TZoznamTvarov.Destroy; begin ZmazatVsetko; FList.Free; inherited Destroy; end; function TZoznamTvarov.GetTvar(Index: Integer): TTvar; begin //kontrola umiestnenia tvarov, priradi mu adresu, na ktoru ukazujeme v procedure Prekreslit if (Index >= 0) AND (Index < FList.Count) then Result := FList.Items[Index] else Result := nil; end; procedure TZoznamTvarov.OdstranitTvar(Index: Integer); begin end; function TZoznamTvarov.PridatTvar(DruhTvaru: TDruhTvaru): TTvar; begin //funkcia na vytvorenie jednotlivych tvarov(objektov) case DruhTvaru of tvNeurceny: Result:= TTvar.Create; tvObdlznik: Result:= TObdlznik.Create; tvOval: Result:= TOval.Create; tvTrojuholnikP: Result:= TTrojuholnikP.Create; tvTrojuholnikR: Result:= TTrojuholnikR.Create; tvSipka: Result:= TSipka.Create; end; FList.Add(Result); end; procedure TZoznamTvarov.Prekreslit(Canvas: TCanvas); var i: Integer; Tvar: TTvar; begin for i := 0 to FList.Count-1 do begin Tvar := FList.Items[i]; Tvar.Nakreslit(Canvas); end; end; procedure TZoznamTvarov.ZmazatVsetko; begin end; //ukladanie projektu procedure TZoznamTvarov.SaveToStream (ANazovSuboru: String); var AStream : TFileStream; ATvar: TTvar; APocet: Integer; i: Integer; begin AStream :=TFileStream.Create(ANazovSuboru, fmCreate); APocet:=FList.Count; AStream.Write(APocet, SizeOf(APocet)); for i := 0 to APocet -1 do begin ATvar := GetTvar(i); AStream.Write(ATvar.FDruhTvaru, SizeOf(ATvar.FDruhTvaru)); ATvar.SaveToStream(AStream); end; AStream.Free; end; //otvaranie projektu procedure TZoznamTvarov.LoadFromStream(ANazovSuboru: String); var AStream : TFileStream; ATvar: TTvar; APocet: Integer; i: Integer; DruhTvaru: TDruhTvaru; begin ZmazatVsetko; AStream :=TFileStream.Create(ANazovSuboru, fmOpenRead); APocet:=FList.Count; AStream.Read(APocet, SizeOf(APocet)); for i := 0 to APocet -1 do begin AStream.Read(DruhTvaru, SizeOf(DruhTvaru)); ATvar := PridatTvar(DruhTvaru); ATvar.LoadFromStream(AStream); end; AStream.Free; end; function TZoznamTvarov.GetTvarPoint(P: TPoint) : TTvar; var I : Integer; Tvar : TTvar; begin Result := nil; //vysledok od zaciatku prazdny for I := FList.Count - 1 downto 0 do //prejdi vsetky tvary od posledneho k prvemu begin Tvar := FList.Items[i]; //prirad premennej Tvar zoznam tvarov s parametrom i if Tvar.FZobrazit and Tvar.PointInTvar(P) then // ak je tvar zobrazeny a bod P patri tvaru begin Result:= Tvar; //potom ukaz na tvar Exit; end; end; end; {$EndRegion} end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { HMAC specification on the NIST website http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf } unit IdHMACSHA1; interface uses IdHash, IdHashSHA1, IdHMAC, IdGlobal, IdObjs, IdSys; type TIdHMACSHA1 = class(TIdHMAC) private FHashSHA1: TIdHashSHA1; protected procedure InitHash; override; function InternalHashValue(const ABuffer: TIdBytes) : TIdBytes; override; end; implementation { TIdHMACSHA1 } procedure TIdHMACSHA1.InitHash; begin inherited; FHashSHA1 := TIdHashSHA1.Create; FHash := FHashSHA1; FHashSize := 20; FBlockSize := 64; FHashName := 'SHA1'; end; function TIdHMACSHA1.InternalHashValue(const ABuffer: TIdBytes): TIdBytes; var TempStream: TIdMemoryStream; TempResult: T5x4LongWordRecord; TempBuff: TIdBytes; begin TempStream := TIdMemoryStream.Create; try WriteTIdBytesToStream(TempStream, ABuffer); TempStream.Position := 0; TempResult := FHashSHA1.HashValue(TempStream); SetLength(TempBuff, 4); SetLength(Result, FHashSize); TempBuff := ToBytes(TempResult[0]); CopyTIdBytes(TempBuff, 0, Result, 0, 4); TempBuff := ToBytes(TempResult[1]); CopyTIdBytes(TempBuff, 0, Result, 4, 4); TempBuff := ToBytes(TempResult[2]); CopyTIdBytes(TempBuff, 0, Result, 8, 4); TempBuff := ToBytes(TempResult[3]); CopyTIdBytes(TempBuff, 0, Result, 12, 4); TempBuff := ToBytes(TempResult[4]); CopyTIdBytes(TempBuff, 0, Result, 16, 4); finally Sys.FreeAndNil(TempStream); end; end; initialization TIdHMACSHA1.Create.Destroy; end.
unit kwDefault; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwDefault.pas" // Начат: 29.04.2011 21:23 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::Scripting::TkwDefault // // Внутреннее слово для определения ветки по умолчанию в скомпилированном Case. Не предназначено // для прямого вызова. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses tfwScriptingInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} TkwDefault = class(_tfwAutoregisteringWord_) {* Внутреннее слово для определения ветки по умолчанию в скомпилированном Case. Не предназначено для прямого вызова. } protected // realized methods procedure DoDoIt(const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; function IsDefaultBranch: Boolean; override; end;//TkwDefault {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwDefault; {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} // start class TkwDefault procedure TkwDefault.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4DBAF3D60039_var* //#UC END# *4DAEEDE10285_4DBAF3D60039_var* begin //#UC START# *4DAEEDE10285_4DBAF3D60039_impl* RunnerAssert(false, 'Слово DEFAULT не должно вызываться', aCtx); //#UC END# *4DAEEDE10285_4DBAF3D60039_impl* end;//TkwDefault.DoDoIt class function TkwDefault.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4DBAF3D60039_var* //#UC END# *4DB0614603C8_4DBAF3D60039_var* begin //#UC START# *4DB0614603C8_4DBAF3D60039_impl* Result := 'DEFAULT'; //#UC END# *4DB0614603C8_4DBAF3D60039_impl* end;//TkwDefault.GetWordNameForRegister function TkwDefault.IsDefaultBranch: Boolean; //#UC START# *4DBAF4630154_4DBAF3D60039_var* //#UC END# *4DBAF4630154_4DBAF3D60039_var* begin //#UC START# *4DBAF4630154_4DBAF3D60039_impl* Result := true; //#UC END# *4DBAF4630154_4DBAF3D60039_impl* end;//TkwDefault.IsDefaultBranch {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwAutoregisteringWord.imp.pas} {$IfEnd} //not NoScripts end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.0 11/13/2002 08:03:48 AM JPMugaas } unit IdTunnelCommon; {* Indy Tunnel components module Copyright (C) 1999, 2000, 2001 Gregor Ibic (gregor.ibic@intelicom.si) Intelicom d.o.o., www.intelicom.si This component is published under same license like Indy package. This package is a TCP Tunnel implementation written by Gregor Ibic (gregor.ibic@intelicom.si). This notice may not be removed or altered from any source distribution. // MAJOR CHANGES 05-January-20001 GI: Major code reorganization and polishing 31-May-2000 GI TunnelHeaders eliminated. Some other code jugling. 29-May-2000 GI Components split in several files to be more compliant with Indy coding standards. It consists of: - IdTunnelHeaders - IdTunnelCommon - IdTunnelMaster - IdTunnelSlave 24-May-2000 GI: Turbo translation mode finished (01:24). It works! Will draw icons in the morning. 23-May-2000 GI: Turbo translation mode to Indy standard started by Gregor Ibic (hehe) (now is 23:15) *} interface {$i IdCompilerDefines.inc} uses SysUtils, Classes, SyncObjs, IdException, IdHashCRC, IdStack, IdCoder, IdResourceStrings, IdTCPServer; const BUFFERLEN = $4000; // Statistics constants NumberOfConnectionsType = 1; NumberOfPacketsType = 2; CompressionRatioType = 3; CompressedBytesType = 4; BytesReadType = 5; BytesWriteType = 6; NumberOfClientsType = 7; NumberOfSlavesType = 8; NumberOfServicesType = 9; // Message types tmError = 0; tmData = 1; tmDisconnect = 2; tmConnect = 3; tmCustom = 99; type TIdStatisticsOperation = (soIncrease, soDecrease ); TIdHeader = record CRC16: Word; MsgType: Word; MsgLen: Word; UserId: Word; Port: Word; IpAddr: TIdInAddr; end; TReceiver = class(TObject) private fiPrenosLen: LongInt; fiMsgLen: LongInt; fsData: String; fbNewMessage: Boolean; fCRCFailed: Boolean; Locker: TCriticalSection; CRC16Calculator: TIdHashCRC16; function FNewMessage: Boolean; procedure SetData(const Value: string); public pBuffer: PChar; HeaderLen: Integer; Header: TIdHeader; MsgLen: Word; TypeDetected: Boolean; Msg: PChar; property Data: String read fsData write SetData; property NewMessage: Boolean read FNewMessage; property CRCFailed: Boolean read fCRCFailed; procedure ShiftData; constructor Create; destructor Destroy; override; end; TSender = class(TObject) public Header: TIdHeader; DataLen: Word; HeaderLen: Integer; pMsg: PChar; Locker: TCriticalSection; CRC16Calculator: TIdHashCRC16; public Msg: String; procedure PrepareMsg(var Header: TIdHeader; buffer: PChar; buflen: Integer); constructor Create; destructor Destroy; override; end; // // END Communication classes /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Logging class // TLogger = class(TObject) private OnlyOneThread: TCriticalSection; // Some locking code fLogFile: TextFile; // Debug Log File fbActive: Boolean; public property Active: Boolean read fbActive Default False; procedure LogEvent(Msg: String); constructor Create(LogFileName: String); destructor Destroy; override; end; // // Logging class /////////////////////////////////////////////////////////////////////////////// TSendMsgEvent = procedure(Thread: TIdPeerThread; var CustomMsg: String) of object; TSendTrnEvent = procedure(Thread: TIdPeerThread; var Header: TIdHeader; var CustomMsg: String) of object; TSendTrnEventC = procedure(var Header: TIdHeader; var CustomMsg: String) of object; TTunnelEventC = procedure(Receiver: TReceiver) of object; TSendMsgEventC = procedure(var CustomMsg: String) of object; // TTunnelEvent = procedure(Thread: TSlaveThread) of object; EIdTunnelException = class(EIdException); EIdTunnelTransformErrorBeforeSend = class(EIdTunnelException); EIdTunnelTransformError = class(EIdTunnelException); EIdTunnelConnectToMasterFailed = class(EIdTunnelException); EIdTunnelDontAllowConnections = class(EIdTunnelException); EIdTunnelCRCFailed = class(EIdTunnelException); EIdTunnelMessageTypeRecognitionError = class(EIdTunnelException); EIdTunnelMessageHandlingFailed = class(EIdTunnelException); EIdTunnelInterpretationOfMessageFailed = class(EIdTunnelException); EIdTunnelCustomMessageInterpretationFailure = class(EIdTunnelException); implementation /////////////////////////////////////////////////////////////////////////////// // Communication classes // constructor TSender.Create; begin inherited; Locker := TCriticalSection.Create; CRC16Calculator := TIdHashCRC16.Create; HeaderLen := SizeOf(TIdHeader); GetMem(pMsg, BUFFERLEN); end; destructor TSender.Destroy; begin FreeMem(pMsg, BUFFERLEN); Locker.Free; CRC16Calculator.Free; inherited; end; procedure TSender.PrepareMsg(var Header: TIdHeader; buffer: PChar; buflen: Integer); begin Locker.Enter; try //Header.MsgType := mType; Header.CRC16 := CRC16Calculator.HashValue(buffer^); Header.MsgLen := Headerlen + bufLen; //Header.UserId := mUser; //Header.Port := Port; //Header.IpAddr := IPAddr; Move(Header, pMsg^, Headerlen); Move(buffer^, (pMsg + Headerlen)^, bufLen); SetLength(Msg, Header.MsgLen); SetString(Msg, pMsg, Header.MsgLen); finally Locker.Leave; end; end; constructor TReceiver.Create; begin inherited; Locker := TCriticalSection.Create; CRC16Calculator := TIdHashCRC16.Create; fiPrenosLen := 0; fsData := ''; {Do not Localize} fiMsgLen := 0; HeaderLen := SizeOf(TIdHeader); GetMem(pBuffer, BUFFERLEN); GetMem(Msg, BUFFERLEN); end; destructor TReceiver.Destroy; begin FreeMem(pBuffer, BUFFERLEN); FreeMem(Msg, BUFFERLEN); Locker.Free; CRC16Calculator.Free; inherited; end; function TReceiver.FNewMessage: Boolean; begin Result := fbNewMessage; end; procedure TReceiver.SetData(const Value: string); var CRC16: Word; begin Locker.Enter; try try fsData := Value; fiMsgLen := Length(fsData); if fiMsgLen > 0 then begin Move(fsData[1], (pBuffer + fiPrenosLen)^, fiMsgLen); fiPrenosLen := fiPrenosLen + fiMsgLen; if (fiPrenosLen >= HeaderLen) then begin // copy the header Move(pBuffer^, Header, HeaderLen); TypeDetected := True; // do we have enough data for the entire message if Header.MsgLen <= fiPrenosLen then begin MsgLen := Header.MsgLen - HeaderLen; Move((pBuffer+HeaderLen)^, Msg^, MsgLen); // Calculate the crc code CRC16 := CRC16Calculator.HashValue(Msg^); if CRC16 <> Header.CRC16 then begin fCRCFailed := True; end else begin fCRCFailed := False; end; fbNewMessage := True; end else begin fbNewMessage := False; end; end else begin TypeDetected := False; end; end else begin fbNewMessage := False; TypeDetected := False; end; except raise; end; finally Locker.Leave; end; end; procedure TReceiver.ShiftData; var CRC16: Word; begin Locker.Enter; try fiPrenosLen := fiPrenosLen - Header.MsgLen; // check if we have another entire message if fiPrenosLen > 0 then begin Move((pBuffer + Header.MsgLen)^, pBuffer^, fiPrenosLen); end; // check if we have another entire message if (fiPrenosLen >= HeaderLen) then begin // copy the header Move(pBuffer^, Header, HeaderLen); TypeDetected := True; // do we have enough data for the entire message if Header.MsgLen <= fiPrenosLen then begin MsgLen := Header.MsgLen - HeaderLen; Move((pBuffer+HeaderLen)^, Msg^, MsgLen); // Calculate the crc code CRC16 := CRC16Calculator.HashValue(Msg^); if CRC16 <> Header.CRC16 then begin fCRCFailed := True; end else begin fCRCFailed := False; end; fbNewMessage := True; end else begin fbNewMessage := False; end; end else begin TypeDetected := False; end; finally Locker.Leave; end; end; // // END Communication classes /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Logging class // constructor TLogger.Create(LogFileName: String); begin fbActive := False; OnlyOneThread := TCriticalSection.Create; try AssignFile(fLogFile, LogFileName); Rewrite(fLogFile); fbActive := True; except fbActive := False; //self.Destroy; // catch file i/o errors, double create file end; end; destructor TLogger.Destroy; begin if fbActive then CloseFile(fLogFile); OnlyOneThread.Free; inherited; end; procedure TLogger.LogEvent(Msg: String); begin OnlyOneThread.Enter; try WriteLn(fLogFile, Msg); Flush(fLogFile); finally OnlyOneThread.Leave; end; end; // // Logging class /////////////////////////////////////////////////////////////////////////////// end.
program caseStatement; var grade: char; begin // Example from: http://www.tutorialspoint.com/pascal/pascal_case_statement.htm grade := 'A'; case (grade) of 'A': writeln('your grade is', 100); 'B': writeln('your grade is', 85); 'C': writeln('your grade is', 75); 'D': writeln('your grade is', 60); 'F': writeln('your grade is', 0); end; end.
unit Data; interface uses System.StrUtils, Classes, SysUtils, System.Generics.Collections, System.Generics.Defaults, System.RegularExpressions, Math, Interfaces, Rtti; var FormatSettings : TFormatSettings; type // <summary>Smart Pointer</summary> Ref<T> = reference to function : T; TSymbol = class; /// <summary> /// Implementation of a smart pointer (interface Ref<T>). /// </summary> TRef<T : class, constructor> = class(TInterfacedObject, Ref<T>) private FValue : T; public /// <summary>Creates a new reference pointing to a new instance of T.</summary> constructor Create(); overload; /// <summary>Creates a new reference pointing to val.</summary> constructor Create(val : T); overload; destructor Destroy(); override; function Invoke : T; function AsSymbol : TSymbol; end; ISomething = interface(IInterface) function ToQualifiedString() : string; end; TData = class abstract(TInterfacedObject, ISomething) public Value : string; ConsumedCharacters : Integer; constructor Create(); destructor Destroy(); override; function ValueEquals(b : TData) : Boolean; virtual; function Copy() : TData; virtual; abstract; procedure Release(); function ToQualifiedString() : string; function ToTValue() : TValue; virtual; abstract; end; TNothing = class(TData) private class var FInstance : TNothing; class var FReference : Ref<TData>; class function GetInstance() : TNothing; static; class function GetReference() : Ref<TData>; static; public constructor Create(); function Copy() : TData; override; function ToString : string; override; class property Instance : Ref<TData> read GetReference; end; TAtom = class(TData) public constructor Create(v : string); function Copy() : TData; override; function ToString : string; override; end; DataRef = Ref<TData>; TValueType = class(TAtom) public function GetHashCode : Integer; override; end; TSymbol = class(TValueType) public function Copy() : TData; override; class function Match(v : string) : Boolean; function ToTValue() : TValue; override; end; TString = class(TValueType) public function Copy() : TData; override; function ToString : string; override; function ToTValue() : TValue; override; end; TBoolean = class(TValueType) public BoolValue : Boolean; constructor Create(v : string); overload; constructor Create(v : Boolean); overload; function Copy() : TData; override; class function Match(v : string) : Boolean; function ToString() : string; override; function ToTValue() : TValue; override; end; TNumber = class(TValueType) public function ToInteger() : Integer; virtual; abstract; function ToSingle() : Single; virtual; abstract; function Plus(b : TNumber) : TNumber; virtual; abstract; function Minus(b : TNumber) : TNumber; virtual; abstract; function Multiply(b : TNumber) : TNumber; virtual; abstract; function Divide(b : TNumber) : TNumber; virtual; abstract; function Compare(b : TNumber) : TNumber; virtual; abstract; end; TInteger = class(TNumber) public IntValue : Integer; constructor Create(v : string); overload; constructor Create(v : Integer); overload; function ToInteger() : Integer; override; function ToSingle() : Single; override; function Copy() : TData; override; function Plus(b : TNumber) : TNumber; override; function Minus(b : TNumber) : TNumber; override; function Multiply(b : TNumber) : TNumber; override; function Divide(b : TNumber) : TNumber; override; function Compare(b : TNumber) : TNumber; override; class function Match(v : string) : Boolean; function ToTValue() : TValue; override; end; TFloat = class(TNumber) public FloatValue : Single; constructor Create(v : string); overload; constructor Create(v : Single); overload; function ToInteger() : Integer; override; function ToSingle() : Single; override; function Copy() : TData; override; function Plus(b : TNumber) : TNumber; override; function Minus(b : TNumber) : TNumber; override; function Multiply(b : TNumber) : TNumber; override; function Divide(b : TNumber) : TNumber; override; function Compare(b : TNumber) : TNumber; override; class function Match(v : string) : Boolean; function ToTValue() : TValue; override; end; TAbstractObject = class abstract(TAtom) end; /// <summary> /// An abstract object implementation wrapping a native Delphi class instance. /// </summary> TDelphiObject = class(TAbstractObject) protected FValue : TValue; FObject : TObject; FOwned : Boolean; FContext : TRttiContext; FType : TRttiInstanceType; procedure Init(); public /// <summary>Creates a Lisp object that owns the contained delphi object /// </summary> constructor CreateOwned(obj : TObject); overload; /// <summary>Creates a new Lisp object wrapping a new instance of the type /// denoted by the qualified name. Ownership is taken for that instance.</summary> constructor CreateOwned(qualifiedName : string; const args : array of TValue); overload; /// <summary>Creates a lisp object wrapping obj but not taking ownership</summary> constructor Create(obj : TObject); destructor Destroy(); override; property Content : TObject read FObject; function ToTValue() : TValue; override; function ToString() : string; override; end; /// <summary> /// Hierarchical program execution context. Contains a symbol reference table /// and an optional reference to a parent context. Reads will search the tree /// upwards. Writes always only apply the current context. /// </summary> TContext = class protected FParent : TContext; FSymbols : TDictionary<string, DataRef>; function GetSymbol(name : string) : Ref<TData>; virtual; procedure SetSymbol(name : string; Data : Ref<TData>); virtual; public /// <summary>Creates a new context optionally chained to given parent context.</summary> constructor Create(parent : TContext); destructor Destroy(); override; /// <summary>Symbols defined in this context. Can be used for reading /// symbols in this and parent contexts, and writing into this context. /// </summary> property Symbols[name : string] : Ref<TData> read GetSymbol write SetSymbol; default; property parent : TContext read FParent; /// <summary>Return true if the symbol is defined in this context or /// in one of its ancestors.</summary> function IsDefined(name : string) : Boolean; virtual; /// <summary>Looks up a TDelphiObject wrapper and returns the contained /// native delphi object.</summary> function GetObject<T : class>(name : string) : T; function GetInteger(name : string) : Integer; function GetSingle(name : string) : Single; function GetBoolean(name : string) : Boolean; function GetString(name : string) : string; procedure Define(name : string; obj : TObject); overload; procedure Define(name : string; num : Integer); overload; procedure Define(name : string; num : Single); overload; procedure Define(name : string; bool : Boolean); overload; procedure Define(name : string; str : String); overload; /// <summary>Imports all symbols from another context into this context. /// All symbol names will be prefixed with <prefix>.</summary> procedure Import(context : TContext; prefix : string); virtual; /// <summary>Removes a symbol reference from this context.</summary> procedure Remove(name : string); virtual; function ToString : string; override; end; /// <summary> /// Dual context that uses an external primary and secondary context for /// looking up symbols. This context is read-only. /// </summary> TDualLookupContext = class(TContext) protected FSecondary : TContext; FPrimary : TContext; procedure SetSymbol(name : string; Data : Ref<TData>); override; public constructor Create(primary : TContext; secondary : TContext); function GetSymbol(name : string) : Ref<TData>; override; function IsDefined(name : string) : Boolean; override; procedure Import(context : TContext; prefix : string); override; procedure Remove(name : string); override; end; /// <summary>An abstract function</summary> TFunction = class abstract(TAtom) protected FContext : TContext; public end; function CreateRef(Data : TData) : DataRef; implementation function CreateRef(Data : TData) : DataRef; begin Result := TRef<TData>.Create(Data); end; { TRef<T> } constructor TRef<T>.Create; begin inherited; FValue := T.Create(); end; function TRef<T>.AsSymbol: TSymbol; begin Result := FValue as TSymbol; end; constructor TRef<T>.Create(val : T); begin inherited Create(); if val <> nil then FValue := val else FValue := T.Create(); end; destructor TRef<T>.Destroy; begin FValue.Free; inherited; end; function TRef<T>.Invoke : T; begin Result := FValue; end; { TParseString } function TAtom.Copy : TData; begin Result := TAtom.Create(Value); end; constructor TAtom.Create(v : string); begin inherited Create(); Value := v; end; function TAtom.ToString : string; begin Result := Value; end; { TContext } constructor TContext.Create(parent : TContext); begin FParent := parent; FSymbols := TDictionary<string, DataRef>.Create(); end; procedure TContext.Define(name: string; num: Integer); begin SetSymbol(name, CreateRef(TInteger.Create(num))); end; procedure TContext.Define(name: string; obj: TObject); begin SetSymbol(name, CreateRef(TDelphiObject.Create(obj))); end; procedure TContext.Define(name: string; num: Single); begin SetSymbol(name, CreateRef(TFloat.Create(num))); end; procedure TContext.Define(name, str: String); begin SetSymbol(name, CreateRef(TString.Create(str))); end; procedure TContext.Define(name: string; bool: Boolean); begin SetSymbol(name, CreateRef(TBoolean.Create(bool))); end; destructor TContext.Destroy; begin inherited; FSymbols.Free; end; function TContext.GetBoolean(name: string): Boolean; begin Result := (GetSymbol(name) as TBoolean).BoolValue; end; function TContext.GetInteger(name: string): Integer; begin Result := (GetSymbol(name) as TInteger).IntValue; end; function TContext.GetObject<T>(name : string) : T; begin Result := (GetSymbol(name)() as TDelphiObject).Content as T; end; function TContext.GetSingle(name: string): Single; begin Result := (GetSymbol(name) as TFloat).FloatValue; end; function TContext.GetString(name: string): String; begin Result := (GetSymbol(name) as TString).Value; end; function TContext.GetSymbol(name : string) : Ref<TData>; begin if FSymbols.ContainsKey(name) then begin Result := FSymbols[name]; end else if FParent <> nil then begin Result := FParent.GetSymbol(name); end else begin raise Exception.Create('Symbol "' + name + '" unknown'); end; end; procedure TContext.Import(context : TContext; prefix : string); var symbol : string; begin for symbol in context.FSymbols.Keys do begin SetSymbol(prefix + symbol, context[symbol]); end; end; function TContext.IsDefined(name : string) : Boolean; begin Result := FSymbols.ContainsKey(name); if (not Result) and (FParent <> nil) then Result := FParent.IsDefined(name); end; procedure TContext.Remove(name : string); begin FSymbols.Remove(name); end; procedure TContext.SetSymbol(name : string; Data : Ref<TData>); begin if FSymbols.ContainsKey(name) then begin FSymbols[name] := DataRef(Data); end else begin FSymbols.Add(name, DataRef(Data)); end; end; function TContext.ToString: string; var pair: TPair<string,DataRef>; begin Result := 'TContext { '; for pair in FSymbols do begin Result := Result + pair.Key + ' => ' + pair.Value().ToString + ', '; end; Result := Result + ' }'; end; { TInteger } constructor TInteger.Create(v : string); begin inherited; IntValue := StrToInt(v); end; function TInteger.Compare(b : TNumber) : TNumber; var I : Integer; begin if b is TInteger then I := Sign(IntValue - (b as TInteger).IntValue) else if b is TFloat then I := Sign(IntValue - (b as TFloat).FloatValue) else raise Exception.Create('unsupported operand'); Result := TInteger.Create(I); end; function TInteger.Copy : TData; begin Result := TInteger.Create(IntValue); end; constructor TInteger.Create(v : Integer); begin IntValue := v; Value := IntToStr(v); end; function TInteger.Divide(b : TNumber) : TNumber; begin if b is TFloat then Result := TFloat.Create(IntValue / (b as TFloat).FloatValue) else if b is TInteger then Result := TInteger.Create(IntValue div (b as TInteger).IntValue) else raise Exception.Create('Unsupported operand'); end; class function TInteger.Match(v : string) : Boolean; begin Result := TRegEx.IsMatch(v, '^[-]?\d+$'); end; function TInteger.Minus(b : TNumber) : TNumber; begin if b is TFloat then Result := TFloat.Create(IntValue - (b as TFloat).FloatValue) else if b is TInteger then Result := TInteger.Create(IntValue - (b as TInteger).IntValue) else raise Exception.Create('Unsupported operand'); end; function TInteger.Multiply(b : TNumber) : TNumber; begin if b is TFloat then Result := TFloat.Create(IntValue * (b as TFloat).FloatValue) else if b is TInteger then Result := TInteger.Create(IntValue * (b as TInteger).IntValue) else raise Exception.Create('Unsupported operand'); end; function TInteger.Plus(b : TNumber) : TNumber; begin if b is TFloat then Result := TFloat.Create(IntValue + (b as TFloat).FloatValue) else if b is TInteger then Result := TInteger.Create(IntValue + (b as TInteger).IntValue) else raise Exception.Create('Unsupported operand'); end; function TInteger.ToInteger : Integer; begin Result := IntValue; end; function TInteger.ToSingle : Single; begin Result := IntValue; end; function TInteger.ToTValue: TValue; begin Result := TValue.From(Self.IntValue); end; { TSingle } constructor TFloat.Create(v : string); begin inherited; FloatValue := StrToFloat(v, FormatSettings); end; function TFloat.Compare(b : TNumber) : TNumber; var I : Integer; begin if b is TInteger then I := Sign(FloatValue - (b as TInteger).IntValue) else if b is TFloat then I := Sign(FloatValue - (b as TFloat).FloatValue) else raise Exception.Create('unsupported operand'); Result := TInteger.Create(I); end; function TFloat.Copy : TData; begin Result := TFloat.Create(FloatValue); end; constructor TFloat.Create(v : Single); begin FloatValue := v; Value := FloatToStr(v, FormatSettings); end; function TFloat.Divide(b : TNumber) : TNumber; begin if b is TInteger then Result := TFloat.Create(FloatValue / ((b as TInteger).IntValue)) else if b is TFloat then Result := TFloat.Create(FloatValue / (b as TFloat).FloatValue) else raise Exception.Create('Unsupported operand'); end; class function TFloat.Match(v : string) : Boolean; begin Result := TRegEx.IsMatch(v, '^[-]?\d+\.\d+'); end; function TFloat.Minus(b : TNumber) : TNumber; begin if b is TInteger then Result := TFloat.Create(FloatValue - (b as TInteger).IntValue) else if b is TFloat then Result := TFloat.Create(FloatValue - (b as TFloat).FloatValue) else raise Exception.Create('Unsupported operand'); end; function TFloat.Multiply(b : TNumber) : TNumber; begin if b is TInteger then Result := TFloat.Create(FloatValue * (b as TInteger).IntValue) else if b is TFloat then Result := TFloat.Create(FloatValue * (b as TFloat).FloatValue) else raise Exception.Create('Unsupported operand'); end; function TFloat.Plus(b : TNumber) : TNumber; begin if b is TInteger then Result := TFloat.Create(FloatValue + (b as TInteger).IntValue) else if b is TFloat then Result := TFloat.Create(FloatValue + (b as TFloat).FloatValue) else raise Exception.Create('Unsupported operand'); end; function TFloat.ToInteger : Integer; begin Result := Round(FloatValue); end; function TFloat.ToSingle : Single; begin Result := FloatValue; end; function TFloat.ToTValue: TValue; begin Result := TValue.From(Self.FloatValue); end; { TSymbol } function TSymbol.Copy : TData; begin Result := TSymbol.Create(Value); end; class function TSymbol.Match(v : string) : Boolean; begin Result := TRegEx.IsMatch(v, '^[\D][\S]*$'); end; function TSymbol.ToTValue : TValue; begin Result := TValue.From(Self.Value); end; { TBoolean } function TBoolean.Copy : TData; begin Result := TBoolean.Create(Value); end; constructor TBoolean.Create(v : string); begin inherited; BoolValue := StrToBool(v); end; constructor TBoolean.Create(v : Boolean); begin BoolValue := v; Value := BoolToStr(v); end; class function TBoolean.Match(v : string) : Boolean; var lower : string; begin lower := v.ToLower; Result := lower.Equals('true') or lower.Equals('false'); end; function TBoolean.ToString : string; begin if BoolValue then Result := 'True' else Result := 'False' end; function TBoolean.ToTValue: TValue; begin Result := TValue.From(Self.BoolValue); end; { TData } constructor TData.Create; begin Value := '()'; end; destructor TData.Destroy; begin inherited; end; procedure TData.Release; begin Self._Release; end; function TData.ToQualifiedString : string; begin Result := Self.ClassName + '[' + Self.ToString + ']'; end; function TData.ValueEquals(b : TData) : Boolean; begin Result := Self.Value.Equals(b.Value); end; { TNothing } function TNothing.Copy : TData; begin Result := TNothing.Create(); end; constructor TNothing.Create; begin Value := ''; end; class function TNothing.GetInstance: TNothing; begin if FInstance = nil then FInstance := TNothing.Create(); Result := FInstance; end; class function TNothing.GetReference: Ref<TData>; begin if FReference = Nil then FReference := CreateRef(GetInstance()); Result := FReference; end; function TNothing.ToString : string; begin Result := 'TNothing'; end; { TString } function TString.Copy : TData; begin Result := TString.Create(Value); end; function TString.ToString : string; begin Result := '"' + Value + '"'; end; function TString.ToTValue: TValue; begin Result := TValue.From(Value); end; { TObject } constructor TDelphiObject.Create(obj : TObject); begin FObject := obj; FOwned := False; FValue := TValue.From(FObject); Init; FType := FContext.GetType(obj.ClassInfo) as TRttiInstanceType; end; constructor TDelphiObject.CreateOwned(qualifiedName : string; const args : array of TValue); begin Init; FType := FContext.FindType(qualifiedName) as TRttiInstanceType; FValue := FType.GetMethod('Create').Invoke(FType.MetaclassType, args); if FValue.IsObject then FObject := FValue.AsObject else FObject := nil end; constructor TDelphiObject.CreateOwned(obj : TObject); begin FObject := obj; FValue := TValue.From(FObject); FOwned := True; Init; FType := FContext.GetType(obj.ClassInfo) as TRttiInstanceType; end; destructor TDelphiObject.Destroy; begin if (FObject <> nil) and FOwned then FObject.Free; inherited; end; procedure TDelphiObject.Init; begin FContext := TRttiContext.Create(); end; function TDelphiObject.ToString: string; begin if FObject <> Nil then Result := FType.QualifiedName + '(' + FObject.ToString + ')' else Result := FType.QualifiedName + '(' + FValue.ToString + ')'; end; function TDelphiObject.ToTValue: TValue; begin Result := FValue; end; { TScopedContext } constructor TDualLookupContext.Create(primary, secondary : TContext); begin inherited Create(nil); FSecondary := secondary; FPrimary := primary; end; function TDualLookupContext.GetSymbol(name : string) : Ref<TData>; begin if FPrimary.IsDefined(name) then Result := FPrimary[name] else Result := FSecondary[name]; end; procedure TDualLookupContext.Import(context : TContext; prefix : string); begin raise Exception.Create('read-only'); end; function TDualLookupContext.IsDefined(name : string) : Boolean; begin Result := FPrimary.IsDefined(name) or FSecondary.IsDefined(name); end; procedure TDualLookupContext.Remove(name : string); begin raise Exception.Create('read-only'); end; procedure TDualLookupContext.SetSymbol(name : string; Data : Ref<TData>); begin raise Exception.Create('read-only'); end; { TValueType } function TValueType.GetHashCode: Integer; begin Result := Self.Value.GetHashCode; end; initialization TNothing.FInstance := TNothing.Create(); TNothing.FReference := CreateRef(TNothing.FInstance); FormatSettings := TFormatSettings.Create('en_US'); finalization end.
{*******************************************************************} { } { Delphi XML Data Binding } { } { Generated on: 5-10-2003 17:46:58 } { Generated from: D:\NLDelphi\Projects\DeX2\TemplateDeX.xml } { Settings stored in: D:\NLDelphi\Projects\DeX2\TemplateDeX.xdb } { } {*******************************************************************} unit NLDXMLIntf; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLNLDelphiDataType = interface; IXMLErrorType = interface; IXMLPMType = interface; IXMLPMTypeList = interface; IXMLMemberType = interface; IXMLPMReadType = interface; IXMLPMReadTypeList = interface; IXMLForumType = interface; IXMLForumTypeList = interface; IXMLThreadType = interface; IXMLThreadTypeList = interface; IXMLPostType = interface; IXMLPostTypeList = interface; IXMLEventType = interface; IXMLEventTypeList = interface; IXMLLinkType = interface; IXMLLinkTypeList = interface; IXMLNewsType = interface; IXMLNewsTypeList = interface; IXMLForumInfoType = interface; IXMLForumInfoTypeList = interface; IXMLString_List = interface; { IXMLNLDelphiDataType } IXMLNLDelphiDataType = interface(IXMLNode) ['{8F530BEF-B012-44B2-8FF0-6D6084CB96CB}'] { Property Accessors } function Get_SessionID: WideString; function Get_RowCount: Integer; function Get_Error: IXMLErrorType; function Get_PM: IXMLPMTypeList; function Get_PMRead: IXMLPMReadTypeList; function Get_Forum: IXMLForumTypeList; function Get_Event: IXMLEventTypeList; function Get_Link: IXMLLinkTypeList; function Get_News: IXMLNewsTypeList; function Get_ForumInfo: IXMLForumInfoTypeList; procedure Set_SessionID(Value: WideString); procedure Set_RowCount(Value: Integer); { Methods & Properties } property SessionID: WideString read Get_SessionID write Set_SessionID; property RowCount: Integer read Get_RowCount write Set_RowCount; property Error: IXMLErrorType read Get_Error; property PM: IXMLPMTypeList read Get_PM; property PMRead: IXMLPMReadTypeList read Get_PMRead; property Forum: IXMLForumTypeList read Get_Forum; property Event: IXMLEventTypeList read Get_Event; property Link: IXMLLinkTypeList read Get_Link; property News: IXMLNewsTypeList read Get_News; property ForumInfo: IXMLForumInfoTypeList read Get_ForumInfo; end; { IXMLErrorType } IXMLErrorType = interface(IXMLNode) ['{9E7B19B9-7E10-4AEE-A2A2-D5E909AE2DFD}'] { Property Accessors } function Get_Text: WideString; procedure Set_Text(Value: WideString); { Methods & Properties } property Text: WideString read Get_Text write Set_Text; end; { IXMLPMType } IXMLPMType = interface(IXMLNode) ['{8754A362-4509-49F3-8B08-F76E7BA37196}'] { Property Accessors } function Get_ID: Integer; function Get_Title: WideString; function Get_Member: IXMLMemberType; function Get_DateTime: Integer; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Title: WideString read Get_Title write Set_Title; property Member: IXMLMemberType read Get_Member; property DateTime: Integer read Get_DateTime write Set_DateTime; end; { IXMLPMTypeList } IXMLPMTypeList = interface(IXMLNodeCollection) ['{7E5B8A1C-B845-44BF-90FD-8AD0BA512B16}'] { Methods & Properties } function Add: IXMLPMType; function Insert(const Index: Integer): IXMLPMType; function Get_Item(Index: Integer): IXMLPMType; property Items[Index: Integer]: IXMLPMType read Get_Item; default; end; { IXMLMemberType } IXMLMemberType = interface(IXMLNode) ['{14F50029-70C9-42E3-B553-54BCE339D848}'] { Property Accessors } function Get_ID: Integer; function Get_Name: WideString; procedure Set_ID(Value: Integer); procedure Set_Name(Value: WideString); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Name: WideString read Get_Name write Set_Name; end; { IXMLPMReadType } IXMLPMReadType = interface(IXMLNode) ['{1D823C08-6E5C-40C4-ACF8-A52544B73756}'] { Property Accessors } function Get_ID: Integer; function Get_Title: WideString; function Get_Member: IXMLMemberType; function Get_DateTime: Integer; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Title: WideString read Get_Title write Set_Title; property Member: IXMLMemberType read Get_Member; property DateTime: Integer read Get_DateTime write Set_DateTime; end; { IXMLPMReadTypeList } IXMLPMReadTypeList = interface(IXMLNodeCollection) ['{46BA1C7A-050A-4073-A81C-3BD48837C690}'] { Methods & Properties } function Add: IXMLPMReadType; function Insert(const Index: Integer): IXMLPMReadType; function Get_Item(Index: Integer): IXMLPMReadType; property Items[Index: Integer]: IXMLPMReadType read Get_Item; default; end; { IXMLForumType } IXMLForumType = interface(IXMLNode) ['{A08548DF-EDF3-4978-9DB9-944AF5B8CF19}'] { Property Accessors } function Get_ID: Integer; function Get_Title: WideString; function Get_Thread: IXMLThreadTypeList; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Title: WideString read Get_Title write Set_Title; property Thread: IXMLThreadTypeList read Get_Thread; end; { IXMLForumTypeList } IXMLForumTypeList = interface(IXMLNodeCollection) ['{A6500BF3-9F56-4EFF-B979-057D3E47EA05}'] { Methods & Properties } function Add: IXMLForumType; function Insert(const Index: Integer): IXMLForumType; function Get_Item(Index: Integer): IXMLForumType; property Items[Index: Integer]: IXMLForumType read Get_Item; default; end; { IXMLThreadType } IXMLThreadType = interface(IXMLNode) ['{ACCB85A5-A7D6-4FBC-9810-8A3A3F40257B}'] { Property Accessors } function Get_ID: Integer; function Get_Title: WideString; function Get_Part: Integer; function Get_IconID: Integer; function Get_Member: IXMLMemberType; function Get_Post: IXMLPostTypeList; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_Part(Value: Integer); procedure Set_IconID(Value: Integer); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Title: WideString read Get_Title write Set_Title; property Part: Integer read Get_Part write Set_Part; property IconID: Integer read Get_IconID write Set_IconID; property Member: IXMLMemberType read Get_Member; property Post: IXMLPostTypeList read Get_Post; end; { IXMLThreadTypeList } IXMLThreadTypeList = interface(IXMLNodeCollection) ['{76C27AEC-59C2-4F3C-8D62-EB7B843DE93D}'] { Methods & Properties } function Add: IXMLThreadType; function Insert(const Index: Integer): IXMLThreadType; function Get_Item(Index: Integer): IXMLThreadType; property Items[Index: Integer]: IXMLThreadType read Get_Item; default; end; { IXMLPostType } IXMLPostType = interface(IXMLNode) ['{71E9901D-FE48-4248-87CF-29842BA43BE2}'] { Property Accessors } function Get_ID: Integer; function Get_DateTime: Integer; function Get_IconID: Integer; function Get_Member: IXMLMemberType; procedure Set_ID(Value: Integer); procedure Set_DateTime(Value: Integer); procedure Set_IconID(Value: Integer); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property DateTime: Integer read Get_DateTime write Set_DateTime; property IconID: Integer read Get_IconID write Set_IconID; property Member: IXMLMemberType read Get_Member; end; { IXMLPostTypeList } IXMLPostTypeList = interface(IXMLNodeCollection) ['{D946D12E-317B-4C4F-BCE8-D15B2689F357}'] { Methods & Properties } function Add: IXMLPostType; function Insert(const Index: Integer): IXMLPostType; function Get_Item(Index: Integer): IXMLPostType; property Items[Index: Integer]: IXMLPostType read Get_Item; default; end; { IXMLEventType } IXMLEventType = interface(IXMLNode) ['{D08E764E-EA95-4B72-8304-B8F047E1D51E}'] { Property Accessors } function Get_Title: IXMLString_List; function Get_Date: Integer; procedure Set_Date(Value: Integer); { Methods & Properties } property Title: IXMLString_List read Get_Title; property Date: Integer read Get_Date write Set_Date; end; { IXMLEventTypeList } IXMLEventTypeList = interface(IXMLNodeCollection) ['{622014BF-8C9C-486B-8C20-C7C309BE3F94}'] { Methods & Properties } function Add: IXMLEventType; function Insert(const Index: Integer): IXMLEventType; function Get_Item(Index: Integer): IXMLEventType; property Items[Index: Integer]: IXMLEventType read Get_Item; default; end; { IXMLLinkType } IXMLLinkType = interface(IXMLNode) ['{3A123D99-4B8F-4308-BFC8-557D13005DF3}'] { Property Accessors } function Get_ID: Integer; function Get_Title: WideString; function Get_DateTime: Integer; function Get_Forum: IXMLForumType; function Get_Member: IXMLMemberType; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property Title: WideString read Get_Title write Set_Title; property DateTime: Integer read Get_DateTime write Set_DateTime; property Forum: IXMLForumType read Get_Forum; property Member: IXMLMemberType read Get_Member; end; { IXMLLinkTypeList } IXMLLinkTypeList = interface(IXMLNodeCollection) ['{182B7753-34CB-4F22-8FC6-F1B0E1E686DD}'] { Methods & Properties } function Add: IXMLLinkType; function Insert(const Index: Integer): IXMLLinkType; function Get_Item(Index: Integer): IXMLLinkType; property Items[Index: Integer]: IXMLLinkType read Get_Item; default; end; { IXMLNewsType } IXMLNewsType = interface(IXMLNode) ['{28F5CCE0-132E-43DE-9069-2768B5123487}'] { Property Accessors } function Get_ID: Integer; function Get_DateTime: Integer; function Get_Title: WideString; procedure Set_ID(Value: Integer); procedure Set_DateTime(Value: Integer); procedure Set_Title(Value: WideString); { Methods & Properties } property ID: Integer read Get_ID write Set_ID; property DateTime: Integer read Get_DateTime write Set_DateTime; property Title: WideString read Get_Title write Set_Title; end; { IXMLNewsTypeList } IXMLNewsTypeList = interface(IXMLNodeCollection) ['{A17969B0-938B-4168-9882-E23841012FFA}'] { Methods & Properties } function Add: IXMLNewsType; function Insert(const Index: Integer): IXMLNewsType; function Get_Item(Index: Integer): IXMLNewsType; property Items[Index: Integer]: IXMLNewsType read Get_Item; default; end; { IXMLForumInfoType } IXMLForumInfoType = interface(IXMLNode) ['{E4CB7946-BD04-4CBF-AD62-52ADD042C51F}'] { Property Accessors } function Get_Name: WideString; function Get_ID: Integer; function Get_ParentID: Integer; procedure Set_Name(Value: WideString); procedure Set_ID(Value: Integer); procedure Set_ParentID(Value: Integer); { Methods & Properties } property Name: WideString read Get_Name write Set_Name; property ID: Integer read Get_ID write Set_ID; property ParentID: Integer read Get_ParentID write Set_ParentID; end; { IXMLForumInfoTypeList } IXMLForumInfoTypeList = interface(IXMLNodeCollection) ['{E27422D4-9E6B-43C7-8F1E-F26E935F09CA}'] { Methods & Properties } function Add: IXMLForumInfoType; function Insert(const Index: Integer): IXMLForumInfoType; function Get_Item(Index: Integer): IXMLForumInfoType; property Items[Index: Integer]: IXMLForumInfoType read Get_Item; default; end; { IXMLString_List } IXMLString_List = interface(IXMLNodeCollection) ['{07FBE96B-9FE8-4475-AA22-FF44B8797CE6}'] { Methods & Properties } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; property Items[Index: Integer]: WideString read Get_Item; default; end; { Forward Decls } TXMLNLDelphiDataType = class; TXMLErrorType = class; TXMLPMType = class; TXMLPMTypeList = class; TXMLMemberType = class; TXMLPMReadType = class; TXMLPMReadTypeList = class; TXMLForumType = class; TXMLForumTypeList = class; TXMLThreadType = class; TXMLThreadTypeList = class; TXMLPostType = class; TXMLPostTypeList = class; TXMLEventType = class; TXMLEventTypeList = class; TXMLLinkType = class; TXMLLinkTypeList = class; TXMLNewsType = class; TXMLNewsTypeList = class; TXMLForumInfoType = class; TXMLForumInfoTypeList = class; TXMLString_List = class; { TXMLNLDelphiDataType } TXMLNLDelphiDataType = class(TXMLNode, IXMLNLDelphiDataType) private FPM: IXMLPMTypeList; FPMRead: IXMLPMReadTypeList; FForum: IXMLForumTypeList; FEvent: IXMLEventTypeList; FLink: IXMLLinkTypeList; FNews: IXMLNewsTypeList; FForumInfo: IXMLForumInfoTypeList; protected { IXMLNLDelphiDataType } function Get_SessionID: WideString; function Get_RowCount: Integer; function Get_Error: IXMLErrorType; function Get_PM: IXMLPMTypeList; function Get_PMRead: IXMLPMReadTypeList; function Get_Forum: IXMLForumTypeList; function Get_Event: IXMLEventTypeList; function Get_Link: IXMLLinkTypeList; function Get_News: IXMLNewsTypeList; function Get_ForumInfo: IXMLForumInfoTypeList; procedure Set_SessionID(Value: WideString); procedure Set_RowCount(Value: Integer); public procedure AfterConstruction; override; end; { TXMLErrorType } TXMLErrorType = class(TXMLNode, IXMLErrorType) protected { IXMLErrorType } function Get_Text: WideString; procedure Set_Text(Value: WideString); end; { TXMLPMType } TXMLPMType = class(TXMLNode, IXMLPMType) protected { IXMLPMType } function Get_ID: Integer; function Get_Title: WideString; function Get_Member: IXMLMemberType; function Get_DateTime: Integer; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); public procedure AfterConstruction; override; end; { TXMLPMTypeList } TXMLPMTypeList = class(TXMLNodeCollection, IXMLPMTypeList) protected { IXMLPMTypeList } function Add: IXMLPMType; function Insert(const Index: Integer): IXMLPMType; function Get_Item(Index: Integer): IXMLPMType; end; { TXMLMemberType } TXMLMemberType = class(TXMLNode, IXMLMemberType) protected { IXMLMemberType } function Get_ID: Integer; function Get_Name: WideString; procedure Set_ID(Value: Integer); procedure Set_Name(Value: WideString); end; { TXMLPMReadType } TXMLPMReadType = class(TXMLNode, IXMLPMReadType) protected { IXMLPMReadType } function Get_ID: Integer; function Get_Title: WideString; function Get_Member: IXMLMemberType; function Get_DateTime: Integer; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); public procedure AfterConstruction; override; end; { TXMLPMReadTypeList } TXMLPMReadTypeList = class(TXMLNodeCollection, IXMLPMReadTypeList) protected { IXMLPMReadTypeList } function Add: IXMLPMReadType; function Insert(const Index: Integer): IXMLPMReadType; function Get_Item(Index: Integer): IXMLPMReadType; end; { TXMLForumType } TXMLForumType = class(TXMLNode, IXMLForumType) private FThread: IXMLThreadTypeList; protected { IXMLForumType } function Get_ID: Integer; function Get_Title: WideString; function Get_Thread: IXMLThreadTypeList; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); public procedure AfterConstruction; override; end; { TXMLForumTypeList } TXMLForumTypeList = class(TXMLNodeCollection, IXMLForumTypeList) protected { IXMLForumTypeList } function Add: IXMLForumType; function Insert(const Index: Integer): IXMLForumType; function Get_Item(Index: Integer): IXMLForumType; end; { TXMLThreadType } TXMLThreadType = class(TXMLNode, IXMLThreadType) private FPost: IXMLPostTypeList; protected { IXMLThreadType } function Get_ID: Integer; function Get_Title: WideString; function Get_Part: Integer; function Get_IconID: Integer; function Get_Member: IXMLMemberType; function Get_Post: IXMLPostTypeList; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_Part(Value: Integer); procedure Set_IconID(Value: Integer); public procedure AfterConstruction; override; end; { TXMLThreadTypeList } TXMLThreadTypeList = class(TXMLNodeCollection, IXMLThreadTypeList) protected { IXMLThreadTypeList } function Add: IXMLThreadType; function Insert(const Index: Integer): IXMLThreadType; function Get_Item(Index: Integer): IXMLThreadType; end; { TXMLPostType } TXMLPostType = class(TXMLNode, IXMLPostType) protected { IXMLPostType } function Get_ID: Integer; function Get_DateTime: Integer; function Get_IconID: Integer; function Get_Member: IXMLMemberType; procedure Set_ID(Value: Integer); procedure Set_DateTime(Value: Integer); procedure Set_IconID(Value: Integer); public procedure AfterConstruction; override; end; { TXMLPostTypeList } TXMLPostTypeList = class(TXMLNodeCollection, IXMLPostTypeList) protected { IXMLPostTypeList } function Add: IXMLPostType; function Insert(const Index: Integer): IXMLPostType; function Get_Item(Index: Integer): IXMLPostType; end; { TXMLEventType } TXMLEventType = class(TXMLNode, IXMLEventType) private FTitle: IXMLString_List; protected { IXMLEventType } function Get_Title: IXMLString_List; function Get_Date: Integer; procedure Set_Date(Value: Integer); public procedure AfterConstruction; override; end; { TXMLEventTypeList } TXMLEventTypeList = class(TXMLNodeCollection, IXMLEventTypeList) protected { IXMLEventTypeList } function Add: IXMLEventType; function Insert(const Index: Integer): IXMLEventType; function Get_Item(Index: Integer): IXMLEventType; end; { TXMLLinkType } TXMLLinkType = class(TXMLNode, IXMLLinkType) protected { IXMLLinkType } function Get_ID: Integer; function Get_Title: WideString; function Get_DateTime: Integer; function Get_Forum: IXMLForumType; function Get_Member: IXMLMemberType; procedure Set_ID(Value: Integer); procedure Set_Title(Value: WideString); procedure Set_DateTime(Value: Integer); public procedure AfterConstruction; override; end; { TXMLLinkTypeList } TXMLLinkTypeList = class(TXMLNodeCollection, IXMLLinkTypeList) protected { IXMLLinkTypeList } function Add: IXMLLinkType; function Insert(const Index: Integer): IXMLLinkType; function Get_Item(Index: Integer): IXMLLinkType; end; { TXMLNewsType } TXMLNewsType = class(TXMLNode, IXMLNewsType) protected { IXMLNewsType } function Get_ID: Integer; function Get_DateTime: Integer; function Get_Title: WideString; procedure Set_ID(Value: Integer); procedure Set_DateTime(Value: Integer); procedure Set_Title(Value: WideString); end; { TXMLNewsTypeList } TXMLNewsTypeList = class(TXMLNodeCollection, IXMLNewsTypeList) protected { IXMLNewsTypeList } function Add: IXMLNewsType; function Insert(const Index: Integer): IXMLNewsType; function Get_Item(Index: Integer): IXMLNewsType; end; { TXMLForumInfoType } TXMLForumInfoType = class(TXMLNode, IXMLForumInfoType) protected { IXMLForumInfoType } function Get_Name: WideString; function Get_ID: Integer; function Get_ParentID: Integer; procedure Set_Name(Value: WideString); procedure Set_ID(Value: Integer); procedure Set_ParentID(Value: Integer); end; { TXMLForumInfoTypeList } TXMLForumInfoTypeList = class(TXMLNodeCollection, IXMLForumInfoTypeList) protected { IXMLForumInfoTypeList } function Add: IXMLForumInfoType; function Insert(const Index: Integer): IXMLForumInfoType; function Get_Item(Index: Integer): IXMLForumInfoType; end; { TXMLString_List } TXMLString_List = class(TXMLNodeCollection, IXMLString_List) protected { IXMLString_List } function Add(const Value: WideString): IXMLNode; function Insert(const Index: Integer; const Value: WideString): IXMLNode; function Get_Item(Index: Integer): WideString; end; { Global Functions } function GetNLDelphiData(Doc: IXMLDocument): IXMLNLDelphiDataType; function LoadNLDelphiData(const FileName: WideString): IXMLNLDelphiDataType; function NewNLDelphiData: IXMLNLDelphiDataType; implementation { Global Functions } function GetNLDelphiData(Doc: IXMLDocument): IXMLNLDelphiDataType; begin Result := Doc.GetDocBinding('NLDelphiData', TXMLNLDelphiDataType) as IXMLNLDelphiDataType; end; function LoadNLDelphiData(const FileName: WideString): IXMLNLDelphiDataType; begin Result := LoadXMLDocument(FileName).GetDocBinding('NLDelphiData', TXMLNLDelphiDataType) as IXMLNLDelphiDataType; end; function NewNLDelphiData: IXMLNLDelphiDataType; begin Result := NewXMLDocument.GetDocBinding('NLDelphiData', TXMLNLDelphiDataType) as IXMLNLDelphiDataType; end; { TXMLNLDelphiDataType } procedure TXMLNLDelphiDataType.AfterConstruction; begin RegisterChildNode('error', TXMLErrorType); RegisterChildNode('PM', TXMLPMType); RegisterChildNode('PMRead', TXMLPMReadType); RegisterChildNode('Forum', TXMLForumType); RegisterChildNode('Event', TXMLEventType); RegisterChildNode('Link', TXMLLinkType); RegisterChildNode('News', TXMLNewsType); RegisterChildNode('ForumInfo', TXMLForumInfoType); FPM := CreateCollection(TXMLPMTypeList, IXMLPMType, 'PM') as IXMLPMTypeList; FPMRead := CreateCollection(TXMLPMReadTypeList, IXMLPMReadType, 'PMRead') as IXMLPMReadTypeList; FForum := CreateCollection(TXMLForumTypeList, IXMLForumType, 'Forum') as IXMLForumTypeList; FEvent := CreateCollection(TXMLEventTypeList, IXMLEventType, 'Event') as IXMLEventTypeList; FLink := CreateCollection(TXMLLinkTypeList, IXMLLinkType, 'Link') as IXMLLinkTypeList; FNews := CreateCollection(TXMLNewsTypeList, IXMLNewsType, 'News') as IXMLNewsTypeList; FForumInfo := CreateCollection(TXMLForumInfoTypeList, IXMLForumInfoType, 'ForumInfo') as IXMLForumInfoTypeList; inherited; end; function TXMLNLDelphiDataType.Get_SessionID: WideString; begin Result := ChildNodes['SessionID'].Text; end; procedure TXMLNLDelphiDataType.Set_SessionID(Value: WideString); begin ChildNodes['SessionID'].NodeValue := Value; end; function TXMLNLDelphiDataType.Get_RowCount: Integer; begin Result := ChildNodes['RowCount'].NodeValue; end; procedure TXMLNLDelphiDataType.Set_RowCount(Value: Integer); begin ChildNodes['RowCount'].NodeValue := Value; end; function TXMLNLDelphiDataType.Get_Error: IXMLErrorType; begin Result := ChildNodes['error'] as IXMLErrorType; end; function TXMLNLDelphiDataType.Get_PM: IXMLPMTypeList; begin Result := FPM; end; function TXMLNLDelphiDataType.Get_PMRead: IXMLPMReadTypeList; begin Result := FPMRead; end; function TXMLNLDelphiDataType.Get_Forum: IXMLForumTypeList; begin Result := FForum; end; function TXMLNLDelphiDataType.Get_Event: IXMLEventTypeList; begin Result := FEvent; end; function TXMLNLDelphiDataType.Get_Link: IXMLLinkTypeList; begin Result := FLink; end; function TXMLNLDelphiDataType.Get_News: IXMLNewsTypeList; begin Result := FNews; end; function TXMLNLDelphiDataType.Get_ForumInfo: IXMLForumInfoTypeList; begin Result := FForumInfo; end; { TXMLErrorType } function TXMLErrorType.Get_Text: WideString; begin Result := ChildNodes['text'].Text; end; procedure TXMLErrorType.Set_Text(Value: WideString); begin ChildNodes['text'].NodeValue := Value; end; { TXMLPMType } procedure TXMLPMType.AfterConstruction; begin RegisterChildNode('Member', TXMLMemberType); inherited; end; function TXMLPMType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLPMType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLPMType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLPMType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; function TXMLPMType.Get_Member: IXMLMemberType; begin Result := ChildNodes['Member'] as IXMLMemberType; end; function TXMLPMType.Get_DateTime: Integer; begin Result := ChildNodes['DateTime'].NodeValue; end; procedure TXMLPMType.Set_DateTime(Value: Integer); begin ChildNodes['DateTime'].NodeValue := Value; end; { TXMLPMTypeList } function TXMLPMTypeList.Add: IXMLPMType; begin Result := AddItem(-1) as IXMLPMType; end; function TXMLPMTypeList.Insert(const Index: Integer): IXMLPMType; begin Result := AddItem(Index) as IXMLPMType; end; function TXMLPMTypeList.Get_Item(Index: Integer): IXMLPMType; begin Result := List[Index] as IXMLPMType; end; { TXMLMemberType } function TXMLMemberType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLMemberType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLMemberType.Get_Name: WideString; begin Result := ChildNodes['Name'].Text; end; procedure TXMLMemberType.Set_Name(Value: WideString); begin ChildNodes['Name'].NodeValue := Value; end; { TXMLPMReadType } procedure TXMLPMReadType.AfterConstruction; begin RegisterChildNode('Member', TXMLMemberType); inherited; end; function TXMLPMReadType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLPMReadType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLPMReadType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLPMReadType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; function TXMLPMReadType.Get_Member: IXMLMemberType; begin Result := ChildNodes['Member'] as IXMLMemberType; end; function TXMLPMReadType.Get_DateTime: Integer; begin Result := ChildNodes['DateTime'].NodeValue; end; procedure TXMLPMReadType.Set_DateTime(Value: Integer); begin ChildNodes['DateTime'].NodeValue := Value; end; { TXMLPMReadTypeList } function TXMLPMReadTypeList.Add: IXMLPMReadType; begin Result := AddItem(-1) as IXMLPMReadType; end; function TXMLPMReadTypeList.Insert(const Index: Integer): IXMLPMReadType; begin Result := AddItem(Index) as IXMLPMReadType; end; function TXMLPMReadTypeList.Get_Item(Index: Integer): IXMLPMReadType; begin Result := List[Index] as IXMLPMReadType; end; { TXMLForumType } procedure TXMLForumType.AfterConstruction; begin RegisterChildNode('Thread', TXMLThreadType); FThread := CreateCollection(TXMLThreadTypeList, IXMLThreadType, 'Thread') as IXMLThreadTypeList; inherited; end; function TXMLForumType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLForumType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLForumType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLForumType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; function TXMLForumType.Get_Thread: IXMLThreadTypeList; begin Result := FThread; end; { TXMLForumTypeList } function TXMLForumTypeList.Add: IXMLForumType; begin Result := AddItem(-1) as IXMLForumType; end; function TXMLForumTypeList.Insert(const Index: Integer): IXMLForumType; begin Result := AddItem(Index) as IXMLForumType; end; function TXMLForumTypeList.Get_Item(Index: Integer): IXMLForumType; begin Result := List[Index] as IXMLForumType; end; { TXMLThreadType } procedure TXMLThreadType.AfterConstruction; begin RegisterChildNode('Member', TXMLMemberType); RegisterChildNode('Post', TXMLPostType); FPost := CreateCollection(TXMLPostTypeList, IXMLPostType, 'Post') as IXMLPostTypeList; inherited; end; function TXMLThreadType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLThreadType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLThreadType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLThreadType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; function TXMLThreadType.Get_Part: Integer; begin Result := ChildNodes['Part'].NodeValue; end; procedure TXMLThreadType.Set_Part(Value: Integer); begin ChildNodes['Part'].NodeValue := Value; end; function TXMLThreadType.Get_IconID: Integer; begin Result := ChildNodes['IconID'].NodeValue; end; procedure TXMLThreadType.Set_IconID(Value: Integer); begin ChildNodes['IconID'].NodeValue := Value; end; function TXMLThreadType.Get_Member: IXMLMemberType; begin Result := ChildNodes['Member'] as IXMLMemberType; end; function TXMLThreadType.Get_Post: IXMLPostTypeList; begin Result := FPost; end; { TXMLThreadTypeList } function TXMLThreadTypeList.Add: IXMLThreadType; begin Result := AddItem(-1) as IXMLThreadType; end; function TXMLThreadTypeList.Insert(const Index: Integer): IXMLThreadType; begin Result := AddItem(Index) as IXMLThreadType; end; function TXMLThreadTypeList.Get_Item(Index: Integer): IXMLThreadType; begin Result := List[Index] as IXMLThreadType; end; { TXMLPostType } procedure TXMLPostType.AfterConstruction; begin RegisterChildNode('Member', TXMLMemberType); inherited; end; function TXMLPostType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLPostType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLPostType.Get_DateTime: Integer; begin Result := ChildNodes['DateTime'].NodeValue; end; procedure TXMLPostType.Set_DateTime(Value: Integer); begin ChildNodes['DateTime'].NodeValue := Value; end; function TXMLPostType.Get_IconID: Integer; begin Result := ChildNodes['IconID'].NodeValue; end; procedure TXMLPostType.Set_IconID(Value: Integer); begin ChildNodes['IconID'].NodeValue := Value; end; function TXMLPostType.Get_Member: IXMLMemberType; begin Result := ChildNodes['Member'] as IXMLMemberType; end; { TXMLPostTypeList } function TXMLPostTypeList.Add: IXMLPostType; begin Result := AddItem(-1) as IXMLPostType; end; function TXMLPostTypeList.Insert(const Index: Integer): IXMLPostType; begin Result := AddItem(Index) as IXMLPostType; end; function TXMLPostTypeList.Get_Item(Index: Integer): IXMLPostType; begin Result := List[Index] as IXMLPostType; end; { TXMLEventType } procedure TXMLEventType.AfterConstruction; begin FTitle := CreateCollection(TXMLString_List, IXMLNode, 'Title') as IXMLString_List; inherited; end; function TXMLEventType.Get_Title: IXMLString_List; begin Result := FTitle; end; function TXMLEventType.Get_Date: Integer; begin Result := ChildNodes['Date'].NodeValue; end; procedure TXMLEventType.Set_Date(Value: Integer); begin ChildNodes['Date'].NodeValue := Value; end; { TXMLEventTypeList } function TXMLEventTypeList.Add: IXMLEventType; begin Result := AddItem(-1) as IXMLEventType; end; function TXMLEventTypeList.Insert(const Index: Integer): IXMLEventType; begin Result := AddItem(Index) as IXMLEventType; end; function TXMLEventTypeList.Get_Item(Index: Integer): IXMLEventType; begin Result := List[Index] as IXMLEventType; end; { TXMLLinkType } procedure TXMLLinkType.AfterConstruction; begin RegisterChildNode('Forum', TXMLForumType); RegisterChildNode('Member', TXMLMemberType); inherited; end; function TXMLLinkType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLLinkType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLLinkType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLLinkType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; function TXMLLinkType.Get_DateTime: Integer; begin Result := ChildNodes['DateTime'].NodeValue; end; procedure TXMLLinkType.Set_DateTime(Value: Integer); begin ChildNodes['DateTime'].NodeValue := Value; end; function TXMLLinkType.Get_Forum: IXMLForumType; begin Result := ChildNodes['Forum'] as IXMLForumType; end; function TXMLLinkType.Get_Member: IXMLMemberType; begin Result := ChildNodes['Member'] as IXMLMemberType; end; { TXMLLinkTypeList } function TXMLLinkTypeList.Add: IXMLLinkType; begin Result := AddItem(-1) as IXMLLinkType; end; function TXMLLinkTypeList.Insert(const Index: Integer): IXMLLinkType; begin Result := AddItem(Index) as IXMLLinkType; end; function TXMLLinkTypeList.Get_Item(Index: Integer): IXMLLinkType; begin Result := List[Index] as IXMLLinkType; end; { TXMLNewsType } function TXMLNewsType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLNewsType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLNewsType.Get_DateTime: Integer; begin Result := ChildNodes['DateTime'].NodeValue; end; procedure TXMLNewsType.Set_DateTime(Value: Integer); begin ChildNodes['DateTime'].NodeValue := Value; end; function TXMLNewsType.Get_Title: WideString; begin Result := ChildNodes['Title'].Text; end; procedure TXMLNewsType.Set_Title(Value: WideString); begin ChildNodes['Title'].NodeValue := Value; end; { TXMLNewsTypeList } function TXMLNewsTypeList.Add: IXMLNewsType; begin Result := AddItem(-1) as IXMLNewsType; end; function TXMLNewsTypeList.Insert(const Index: Integer): IXMLNewsType; begin Result := AddItem(Index) as IXMLNewsType; end; function TXMLNewsTypeList.Get_Item(Index: Integer): IXMLNewsType; begin Result := List[Index] as IXMLNewsType; end; { TXMLForumInfoType } function TXMLForumInfoType.Get_Name: WideString; begin Result := ChildNodes['Name'].Text; end; procedure TXMLForumInfoType.Set_Name(Value: WideString); begin ChildNodes['Name'].NodeValue := Value; end; function TXMLForumInfoType.Get_ID: Integer; begin Result := ChildNodes['ID'].NodeValue; end; procedure TXMLForumInfoType.Set_ID(Value: Integer); begin ChildNodes['ID'].NodeValue := Value; end; function TXMLForumInfoType.Get_ParentID: Integer; begin Result := ChildNodes['ParentID'].NodeValue; end; procedure TXMLForumInfoType.Set_ParentID(Value: Integer); begin ChildNodes['ParentID'].NodeValue := Value; end; { TXMLForumInfoTypeList } function TXMLForumInfoTypeList.Add: IXMLForumInfoType; begin Result := AddItem(-1) as IXMLForumInfoType; end; function TXMLForumInfoTypeList.Insert(const Index: Integer): IXMLForumInfoType; begin Result := AddItem(Index) as IXMLForumInfoType; end; function TXMLForumInfoTypeList.Get_Item(Index: Integer): IXMLForumInfoType; begin Result := List[Index] as IXMLForumInfoType; end; { TXMLString_List } function TXMLString_List.Add(const Value: WideString): IXMLNode; begin Result := AddItem(-1); Result.NodeValue := Value; end; function TXMLString_List.Insert(const Index: Integer; const Value: WideString): IXMLNode; begin Result := AddItem(Index); Result.NodeValue := Value; end; function TXMLString_List.Get_Item(Index: Integer): WideString; begin Result := List[Index].NodeValue; end; end.
unit tappydrawer; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, LCLType, IntfGraphics, fpimage, Math, LCLIntf, tappyconfig, tappymodules; type { TTappyTuxAnimation } TTappyTuxAnimation = class public StartPoint, EndPoint: TPoint; Position: TPoint; CurrentStep: Integer; StepCount: Integer; // In miliseconds IsInfinite: Boolean; // if True the animation will never end Stopped: Boolean; // User data UserData: TObject; UserPosition: TPoint; constructor Create; virtual; procedure DrawToIntfImg(AIntfImage: TLazIntfImage); virtual; procedure DrawToCanvas(ACanvas: TCanvas); virtual; procedure CalculatePosition; procedure ExecuteFinal; virtual; end; { TTappySpriteAnimation } TTappySpriteAnimation = class(TTappyTuxAnimation) public Images: array of TLazIntfImage; SpriteChangeInterval: Integer; constructor Create; override; destructor Destroy; override; procedure DrawToIntfImg(AIntfImage: TLazIntfImage); override; procedure ExecuteFinal; override; procedure LoadImageFromPng(AIndex: Integer; APath: string); end; { TFallingText } TFallingText = class(TTappyTuxAnimation) public Caption: String; Value: Integer; ProcessOnEnd: Boolean; Image: TLazIntfImage; constructor Create; override; destructor Destroy; override; procedure DrawToIntfImg(AIntfImage: TLazIntfImage); override; procedure DrawToCanvas(ACanvas: TCanvas); override; procedure ExecuteFinal; override; procedure LoadImageFromPng(APath: string); end; { TTappyTuxDrawer } TTappyTuxDrawer = class(TCustomControl) private imgSomething: TPortableNetworkGraphic; FAnimationList: TFPList; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure EraseBackground(DC: HDC); override; procedure Paint; override; procedure DrawToCanvas(ACanvas: TCanvas); class procedure DrawImageWithTransparentColor( ADest: TLazIntfImage; const ADestX, ADestY: Integer; AColor: TFPColor; AImage: TLazIntfImage); class function DateTimeToMilliseconds(aDateTime: TDateTime): Int64; //function GetImage(ATile: TChessTile): TPortableNetworkGraphic; procedure HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure HandleMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HandleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure HandleOnTimer(Sender: TObject); function AddAnimation(AAnimation: TTappyTuxAnimation): Integer; function GetAnimation(AIndex: Integer): TTappyTuxAnimation; function GetAnimationIndex(AAnimation: TTappyTuxAnimation): Integer; function GetAnimationCount: Integer; procedure RemoveAnimation(AIndex: Integer); procedure HandleAnimationOnTimer(AInterval: Integer); end; var vTappyTuxDrawer: TTappyTuxDrawer; implementation { TTappySpriteAnimation } constructor TTappySpriteAnimation.Create; begin inherited Create; SpriteChangeInterval := 1000; end; destructor TTappySpriteAnimation.Destroy; var i: Integer; begin for i := 0 to Length(Images)-1 do if Assigned(Images[i]) then Images[i].Free; inherited Destroy; end; procedure TTappySpriteAnimation.DrawToIntfImg(AIntfImage: TLazIntfImage); var lNumBitmaps, lCurBmpIndex: Integer; begin lNumBitmaps := Length(Images); if lNumBitmaps = 0 then Exit; lCurBmpIndex := (CurrentStep div SpriteChangeInterval) mod lNumBitmaps; TTappyTuxDrawer.DrawImageWithTransparentColor(AIntfImage, Position.X, Position.Y, colFuchsia, Images[lCurBmpIndex]); end; procedure TTappySpriteAnimation.ExecuteFinal; begin GetCurrentModule().ProcessSpriteEnd(UserData, UserPosition); end; procedure TTappySpriteAnimation.LoadImageFromPng(AIndex: Integer; APath: string); var lBitmap: TPortableNetworkGraphic; begin lBitmap := TPortableNetworkGraphic.Create; try lBitmap.LoadFromFile(APath); Images[AIndex] := TLazIntfImage.Create(0, 0); Images[AIndex].LoadFromBitmap(lBitmap.Handle, 0); finally lBitmap.Free; end; end; {TFallingText} constructor TFallingText.Create; begin inherited Create; ProcessOnEnd := True; end; destructor TFallingText.Destroy; begin if Assigned(Image) then Image.Free; inherited Destroy; end; procedure TFallingText.DrawToIntfImg(AIntfImage: TLazIntfImage); begin TTappyTuxDrawer.DrawImageWithTransparentColor(AIntfImage, Position.X, Position.Y, colFuchsia, Image); end; procedure TFallingText.DrawToCanvas(ACanvas: TCanvas); begin ACanvas.Brush.Style := bsSolid; ACanvas.Brush.Color := clWhite; ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := clBlack; ACanvas.Rectangle(Position.X + 25, Position.Y + 45, Position.X + 30 + ACanvas.TextWidth(Caption)+5, Position.Y + 50 + ACanvas.TextHeight(Caption)+5); ACanvas.TextOut(Position.X + 30, Position.Y + 50, caption); end; procedure TFallingText.ExecuteFinal; var snowmanWrong: TFallingText; begin if ProcessOnEnd then begin snowmanWrong := TFallingText.Create; snowmanWrong.IsInfinite := False; snowmanWrong.StartPoint := Position; snowmanWrong.EndPoint := Position; snowmanWrong.Position := Position; snowmanWrong.caption:= 'Oh-oh!'; snowmanWrong.ProcessOnEnd := False; snowmanWrong.StepCount := 2000; snowmanWrong.LoadImageFromPng(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'snowmanwrong.png'); vTappyTuxDrawer.AddAnimation(snowmanWrong); GetCurrentModule().ProcessFallingTextEnd(); end; end; procedure TFallingText.LoadImageFromPng(APath: string); var lBitmap: TPortableNetworkGraphic; begin lBitmap := TPortableNetworkGraphic.Create; try lBitmap.LoadFromFile(APath); Image := TLazIntfImage.Create(0, 0); Image.LoadFromBitmap(lBitmap.Handle, 0); finally lBitmap.Free; end; end; { TTappyTuxAnimation } constructor TTappyTuxAnimation.Create; begin inherited Create; CurrentStep := 0; StepCount := 20000; end; procedure TTappyTuxAnimation.DrawToIntfImg(AIntfImage: TLazIntfImage); begin end; procedure TTappyTuxAnimation.DrawToCanvas(ACanvas: TCanvas); begin end; procedure TTappyTuxAnimation.CalculatePosition; var t: Double; begin t := CurrentStep / StepCount; Position.X := Round(StartPoint.X + t * (EndPoint.X - StartPoint.X)); Position.Y := Round(StartPoint.Y + t * (EndPoint.Y - StartPoint.Y)); end; procedure TTappyTuxAnimation.ExecuteFinal; begin // inherit from this class and add something to ExecuteFinal end; constructor TTappyTuxDrawer.Create(AOwner: TComponent); begin inherited Create(AOwner); FAnimationList := TFPList.Create; // Events OnMouseMove := @HandleMouseMove; OnMouseUp := @HandleMouseUp; OnMouseDown := @HandleMouseDown; end; destructor TTappyTuxDrawer.Destroy; begin FAnimationList.Free; inherited Destroy; end; procedure TTappyTuxDrawer.EraseBackground(DC: HDC); begin // Don't erase the background end; procedure TTappyTuxDrawer.Paint; var x, y: integer; Bitmap: TBitmap; begin Bitmap := TBitmap.Create; try // Initializes the Bitmap Size Bitmap.Height := Height; Bitmap.Width := Width; DrawToCanvas(Bitmap.Canvas); Canvas.Draw(0, 0, Bitmap); finally Bitmap.Free; end; end; procedure TTappyTuxDrawer.DrawToCanvas(ACanvas: TCanvas); var col, row: integer; lIntfImage: TLazIntfImage; lTmpBmp: TBitmap; X, Y: integer; i: Integer; lAnimation: TTappyTuxAnimation; lStartTime, lAnimTime, lTimeDiff: TDateTime; begin {$IFDEF TAPPY_PROFILER} lStartTime := Now; {$ENDIF} lIntfImage := TLazIntfImage.Create(0, 0); lTmpBmp := TBitmap.Create; try // First draw the background lIntfImage.LoadFromBitmap(GetCurrentModule().GetBackgroundImage(2).Handle, 0{bmpBoard.MaskHandle}); // Draw all animations via TLazIntfImage for i := 0 to FAnimationList.Count - 1 do begin lAnimation := TTappyTuxAnimation(FAnimationList.Items[i]); lAnimation.CalculatePosition(); {$IFDEF TAPPY_PROFILER} lAnimTime := Now; {$ENDIF} lAnimation.DrawToIntfImg(lIntfImage); {$IFDEF TAPPY_PROFILER} lTimeDiff := Now - lAnimTime; WriteLn(Format('[TTappyTuxDrawer.DrawToCanvas] %s %d DrawToIntfImage Performance: %7d ms', [lAnimation.ClassName, i, DateTimeToMilliseconds(lTimeDiff)])); {$ENDIF} end; lTmpBmp.LoadFromIntfImage(lIntfImage); ACanvas.Draw(0, 0, lTmpBmp); // ------------------------- // Now TCanvas drawings // ------------------------- // Second pass of animation drawings, now draw via TCanvas for using fonts for i := 0 to FAnimationList.Count - 1 do begin lAnimation := TTappyTuxAnimation(FAnimationList.Items[i]); lAnimation.DrawToCanvas(ACanvas); end; finally lTmpBmp.Free; lIntfImage.Free; end; {$IFDEF TAPPY_PROFILER} lTimeDiff := Now - lStartTime; WriteLn(Format('[TTappyTuxDrawer.DrawToCanvas] Performance: %7d ms', [DateTimeToMilliseconds(lTimeDiff)])); {$ENDIF} end; class procedure TTappyTuxDrawer.DrawImageWithTransparentColor(ADest: TLazIntfImage; const ADestX, ADestY: Integer; AColor: TFPColor; AImage: TLazIntfImage); var x, y, CurX, CurY: Integer; lDrawWidth, lDrawHeight: Integer; CurColor: TFPColor; begin // Take care not to draw outside the destination area lDrawWidth := Min(ADest.Width - ADestX, AImage.Width); lDrawHeight := Min(ADest.Height - ADestY, AImage.Height); for y := 0 to lDrawHeight - 1 do begin for x := 0 to lDrawWidth - 1 do begin CurX := ADestX + x; CurY := ADestY + y; // Never draw outside the destination if (CurX < 0) or (CurY < 0) then Continue; CurColor := AImage.Colors[x, y]; if (AColor.Green <> CurColor.Green) or (AColor.Red <> CurColor.Red) or (AColor.Blue <> CurColor.Blue) then ADest.Colors[CurX, CurY] := CurColor; end; end; end; class function TTappyTuxDrawer.DateTimeToMilliseconds(aDateTime: TDateTime ): Int64; var TimeStamp: TTimeStamp; begin {Call DateTimeToTimeStamp to convert DateTime to TimeStamp:} TimeStamp:= DateTimeToTimeStamp (aDateTime); {Multiply and add to complete the conversion:} Result:= TimeStamp.Time; end; procedure TTappyTuxDrawer.HandleMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin { if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseMove(Sender, Shift, X, Y);} end; procedure TTappyTuxDrawer.HandleMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin { if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseUp(Sender, Button, Shift, X, Y);} end; procedure TTappyTuxDrawer.HandleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin { if Assigned(FDelegate) and (FDrawerState in [dsIdle, dsDragging]) then FDelegate.HandleMouseDown(Sender, Button, Shift, X, Y);} end; procedure TTappyTuxDrawer.HandleOnTimer(Sender: TObject); begin { if FDrawerState = dsRunningAnimation then begin Inc(FAnimation.CurrentStep); if FAnimation.CurrentStep >= FAnimation.FinalStep then begin FAnimation.ExecuteFinal; FAnimation.Free; FAnimation := nil; FDrawerState := dsIdle; end; Invalidate(); end;} end; function TTappyTuxDrawer.AddAnimation(AAnimation: TTappyTuxAnimation): Integer; begin Result := FAnimationList.Add(AAnimation); end; function TTappyTuxDrawer.GetAnimation(AIndex: Integer): TTappyTuxAnimation; begin Result := TTappyTuxAnimation(FAnimationList.Items[AIndex]); end; function TTappyTuxDrawer.GetAnimationIndex(AAnimation: TTappyTuxAnimation ): Integer; begin Result := FAnimationList.IndexOf(AAnimation); end; function TTappyTuxDrawer.GetAnimationCount: Integer; begin Result := FAnimationList.Count; end; procedure TTappyTuxDrawer.RemoveAnimation(AIndex: Integer); begin FAnimationList.Delete(AIndex); end; procedure TTappyTuxDrawer.HandleAnimationOnTimer(AInterval: Integer); var i: Integer; lAnimation: TTappyTuxAnimation; begin i := 0; while i < FAnimationList.Count do begin lAnimation := GetAnimation(i); if (not lAnimation.Stopped) then Inc(lAnimation.CurrentStep, AInterval); if (not lAnimation.IsInfinite) and (lAnimation.CurrentStep >= lAnimation.StepCount) and (not lAnimation.Stopped) then begin lAnimation.ExecuteFinal(); RemoveAnimation(i); Continue; end; Inc(i); end; Self.Invalidate; end; end.
unit Model.CadastroContatos; interface uses Common.ENum, FireDAC.Comp.Client, System.SysUtils, DAO.Conexao; type TCadastroContatos = class private FID: Integer; FSequencia: Integer; FDescricao: String; FTelefone: String; FEMail: String; FAcao: TAcao; FConexao : TConexao; FQuery: TFDQuery; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public property ID: Integer read FID write FID; property Sequencia: Integer read FSequencia write FSequencia; property Descricao: String read FDescricao write FDescricao; property Telefone: String read FTelefone write FTelefone; property EMail: String read FEMail write FEMail; property Query: TFDQuery read FQuery write FQuery; property Acao: TAcao read FAcao write FAcao; constructor Create(); function GetID(iID: Integer): Integer; function Localizar(aParam: array of variant): Boolean; function Gravar(): Boolean; function SaveBatch(memTable: TFDMemTable): Boolean; function SetupClass(FDQuery: TFDQuery): Boolean; function ClearClass(): Boolean; end; const TABLENAME = 'tbcontatosentregadores'; implementation { TCadastroContatos } function TCadastroContatos.ClearClass: Boolean; begin Result := False; FID := 0; FSequencia := 0; FDescricao := ''; FTelefone := ''; FEMail := ''; Result := True; end; constructor TCadastroContatos.Create; begin FConexao := TConexao.Create; end; function TCadastroContatos.Delete: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; if Self.Sequencia = -1 then begin sSQL := 'delete drom ' + TABLENAME + ' ' + 'where cod_cadastro = :pcod_cadastro;'; FDQuery.ExecSQL(sSQL,[Self.ID]); end else begin sSQL := 'delete from ' + TABLENAME + ' ' + 'where cod_cadastro = :pcod_cadastro and seq_contato = :seq_contato;'; FDQuery.ExecSQL(sSQL,[Self.ID, Self.Sequencia]); end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroContatos.GetID(iID: Integer): Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.Open('select coalesce(max(seq_contato),0) + 1 from ' + TABLENAME + ' where cod_entregador = ' + iID.toString); Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroContatos.Gravar: Boolean; begin case FAcao of tacIncluir: Result := Self.Insert(); tacAlterar: Result := Self.Update(); tacExcluir: Result := Self.Delete(); end; end; function TCadastroContatos.Insert: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; Self.Sequencia := GetID(Self.ID); sSQL := 'insert into ' + TABLENAME + '(' + 'cod_entregador, seq_contato, des_contato, num_telefone, des_email) ' + 'values (' + ':cod_entregador, :seq_contato, :des_contato, :num_telefone, :des_email);'; FDQuery.ExecSQL(sSQL,[Self.ID, Self.Sequencia, Self.Descricao, Self.Telefone, Self.EMail]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TCadastroContatos.Localizar(aParam: array of variant): Boolean; begin Result := False; FQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FQuery.SQL.Clear; FQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FQuery.SQL.Add('whew cod_entregador = :cod_entregador'); FQuery.ParamByName('cod_entregador').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FQuery.SQL.Add('where cod_entregador = :cod_entregador and seq_contato = :seq_contato'); FQuery.ParamByName('id_cadastro').AsInteger := aParam[1]; FQuery.ParamByName('seq_contato').AsInteger := aParam[2]; end; if aParam[0] = 'DESCRICAO' then begin FQuery.SQL.Add('where des_contato like :des_contato'); FQuery.ParamByName('des_contato').AsString := aParam[1]; end; if aParam[0] = 'TELEFONE' then begin FQuery.SQL.Add('where num_telefone like :num_telefone'); FQuery.ParamByName('num_telefone').AsString := aParam[1]; end; if aParam[0] = 'EMAIL' then begin FQuery.SQL.Add('where des_email like :des_email'); FQuery.ParamByName('des_email').AsString := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FQuery.SQL.Clear; FQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FQuery.Open(); if Fquery.IsEmpty then begin Exit; end; Result := True; end; function TCadastroContatos.SaveBatch(memTable: TFDMemTable): Boolean; begin Result := False; Self.Acao := tacExcluir; if not Self.Gravar then begin Exit; end; memTable.First; while not memTable.Eof do begin Self.ID := memTable.FieldByName('cod_entregador').AsInteger; Self.Sequencia := GetID(Self.ID); Self.Descricao := memTable.FieldByName('des_contato').AsString; Self.Telefone := memTable.FieldByName('num_telefone').AsString; Self.EMail := memTable.FieldByName('des_logradouro').AsString; Self.Acao := tacIncluir; if not Self.Gravar then begin Exit; end; memTable.Next; end; Result := True; end; function TCadastroContatos.SetupClass(FDQuery: TFDQuery): Boolean; begin Result := False; FID := FDQuery.FieldByName('cod_cadastro').AsInteger; FSequencia := FDQuery.FieldByName('seq_contato').AsInteger; FDescricao := FDQuery.FieldByName('des_contato').AsString; FTelefone := FDQuery.FieldByName('des_telefone').AsString; FEMail := FDQuery.FieldByName('des_email').AsString; Result := True; end; function TCadastroContatos.Update: Boolean; var sSQL: String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; sSQL := 'update ' + TABLENAME + ' set ' + 'des_contato = :pdes_contato,num_telefone = :pnum_telefone, des_email = :pdes_email ' + 'where cod_cadastro = :pcod_cadastro and seq_contato = :pseq_contato;'; FDQuery.ExecSQL(sSQL,[Self.Descricao, Self.Telefone, Self.EMail, Self.ID,Self.Sequencia]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit vcmFormSetRefreshParams; {* Параметры обновления представления сборки. } // Библиотека : "vcm" // Автор : Морозов. М.А. // Модуль : vcmInterfaces - // Начат : 21.06.2007 // Версия : $Id: vcmFormSetRefreshParams.pas,v 1.5 2015/08/19 07:03:52 morozov Exp $ } (*------------------------------------------------------------------------------- $Log: vcmFormSetRefreshParams.pas,v $ Revision 1.5 2015/08/19 07:03:52 morozov {RequestLink: 604494984} Revision 1.4 2014/09/16 15:33:24 kostitsin {requestlink: 555385722 } Revision 1.3 2014/09/16 15:24:48 kostitsin {requestlink: 564993742 } Revision 1.2 2008/11/28 19:38:40 lulin - избавляемся от "прокидывания данных". Revision 1.1 2007/06/22 08:56:23 mmorozov - new: параметры обновления представления сборки оформлены интерфейсом; -------------------------------------------------------------------------------*) interface uses vcmInterfaces ; function vcmMakeDataRefreshParams(const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil; aLockSetFocusToMainObjectForm: Boolean = True; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshDataParams; {-} function vcmMakeRefreshParams(const aParams : IvcmFormSetRefreshDataParams; const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshParams; {-} implementation uses SysUtils, vcmBase ; type TvcmFormSetRefreshParams = class(TvcmBase, IvcmFormSetRefreshParams) {* Элемент стека обновления. } private // internal methods f_DataSource : IvcmFormSetDataSource; f_FormSet : IvcmFormSet; f_SaveToHistory : TvcmSaveFormSetToHistory; f_DataForHistory : IvcmData; f_LockSetFocusToMainObjectForm: Boolean; f_FormSetToClone : IvcmFormSet; private // IvcmFormSetRefreshParams function pm_GetLockSetFocusToMainObjectForm: Boolean; procedure pm_SetLockSetFocusToMainObjectForm(aValue: Boolean); function pm_GetDataForHistory: IvcmData; {-} function pm_GetDataSource: IvcmFormSetDataSource; procedure pm_SetDataSource(const aValue: IvcmFormSetDataSource); {-} function pm_GetFormSet: IvcmFormSet; procedure pm_SetFormSet(const aValue: IvcmFormSet); {-} function pm_GetSaveToHistory: TvcmSaveFormSetToHistory; {-} function pm_GetFormSetToClone: IvcmFormSet; {-} protected // protected methods procedure Cleanup; override; {-} public // public methods constructor Create(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory; const aDataForHistory : IvcmData; aLockSetFocusToMainObjectForm: Boolean; const aFormSetToClone : IvcmFormSet = nil); reintroduce; {-} class function Make(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil; aLockSetFocusToMainObjectForm: Boolean = True; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshParams; {-} public // public properties property DataSource: IvcmFormSetDataSource read pm_GetDataSource; {-} property FormSet: IvcmFormSet read pm_GetFormSet; {-} property SaveToHistory: TvcmSaveFormSetToHistory read pm_GetSaveToHistory; {-} property DataForHistory: IvcmData read pm_GetDataForHistory; {-} property FormSetToClone: IvcmFormSet read pm_GetFormSetToClone; end;//TvcmFormSetRefreshParams function vcmMakeRefreshParams(const aParams : IvcmFormSetRefreshDataParams; const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshParams; {-} begin if Supports(aParams, IvcmFormSetRefreshParams, Result) then with Result do begin DataSource := aDataSource; FormSet := aFormSet end//with Result do else if aParams <> nil then Result := TvcmFormSetRefreshParams.Make(aDataSource, aFormSet, aParams.SaveToHistory, aParams.DataForHistory, aParams.LockSetFocusToMainObjectForm, aParams.FormSetToClone) else Result := TvcmFormSetRefreshParams.Make(aDataSource, aFormSet); end; function vcmMakeDataRefreshParams(const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil; aLockSetFocusToMainObjectForm: Boolean = True; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshDataParams; {-} begin Result := TvcmFormSetRefreshParams.Make(nil, nil, aSaveToHistory, aDataForHistory, aLockSetFocusToMainObjectForm, aFormSetToClone); end; { TvcmFormSetRefreshParams } procedure TvcmFormSetRefreshParams.Cleanup; // override; {-} begin f_DataForHistory := nil; f_DataSource := nil; f_FormSet := nil; inherited; end;//Cleanup constructor TvcmFormSetRefreshParams.Create(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory; const aDataForHistory : IvcmData; aLockSetFocusToMainObjectForm: Boolean; const aFormSetToClone : IvcmFormSet); // reintroduce; {-} begin inherited Create; f_DataSource := aDataSource; f_FormSet := aFormSet; f_SaveToHistory := aSaveToHistory; f_DataForHistory := aDataForHistory; f_LockSetFocusToMainObjectForm := aLockSetFocusToMainObjectForm; f_FormSetToClone := aFormSetToClone; end;//Create class function TvcmFormSetRefreshParams.Make(const aDataSource : IvcmFormSetDataSource; const aFormSet : IvcmFormSet; const aSaveToHistory : TvcmSaveFormSetToHistory = sfsNone; const aDataForHistory : IvcmData = nil; aLockSetFocusToMainObjectForm: Boolean = True; const aFormSetToClone : IvcmFormSet = nil): IvcmFormSetRefreshParams; {-} var l_Class: TvcmFormSetRefreshParams; begin l_Class := Create(aDataSource, aFormSet, aSaveToHistory, aDataForHistory, aLockSetFocusToMainObjectForm, aFormSetToClone); try Result := l_Class; finally FreeAndNil(l_Class); end;{try..finally} end;//Make function TvcmFormSetRefreshParams.pm_GetDataForHistory: IvcmData; begin Result := f_DataForHistory; end;//pm_GetDataForHistory function TvcmFormSetRefreshParams.pm_GetDataSource: IvcmFormSetDataSource; begin Result := f_DataSource; end;//pm_GetDataSource function TvcmFormSetRefreshParams.pm_GetFormSet: IvcmFormSet; begin Result := f_FormSet; end;//pm_GetFormSet function TvcmFormSetRefreshParams.pm_GetLockSetFocusToMainObjectForm: Boolean; begin Result := f_LockSetFocusToMainObjectForm end; procedure TvcmFormSetRefreshParams.pm_SetLockSetFocusToMainObjectForm( aValue: Boolean); begin f_LockSetFocusToMainObjectForm := aValue; end; function TvcmFormSetRefreshParams.pm_GetSaveToHistory: TvcmSaveFormSetToHistory; begin Result := f_SaveToHistory; end;//pm_GetSaveToHistory function TvcmFormSetRefreshParams.pm_GetFormSetToClone: IvcmFormSet; begin Result := f_FormSetToClone; end; procedure TvcmFormSetRefreshParams.pm_SetDataSource(const aValue: IvcmFormSetDataSource); begin f_DataSource := aValue; end;//pm_SetDataSource procedure TvcmFormSetRefreshParams.pm_SetFormSet(const aValue: IvcmFormSet); begin f_FormSet := aValue; end;//pm_SetFormSet end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit frmSequenceProperties; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmBaseForm, OraBarConn, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxMemo, cxRichEdit, cxSplitter, dxStatusBar, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxLabel, cxContainer, cxTextEdit, dxBar, jpeg, cxPC, StdCtrls, ExtCtrls, ora, MemDS, DBAccess, GenelDM, OraSequence, VirtualTable; type TSequencePropertiesFrm = class(TBaseform) Panel1: TPanel; imgToolBar: TImage; lblDescription: TLabel; pcSequenceProperties: TcxPageControl; tsSequenceDetails: TcxTabSheet; dxBarDockControl1: TdxBarDockControl; edtIncrementBy: TcxTextEdit; cxLabel1: TcxLabel; cxLabel2: TcxLabel; edtLastValue: TcxTextEdit; cxLabel3: TcxLabel; edtMinValue: TcxTextEdit; cxLabel4: TcxLabel; edtMaxValue: TcxTextEdit; cxLabel5: TcxLabel; edtCacheSize: TcxTextEdit; tsSequenceGrants: TcxTabSheet; dxBarDockControl4: TdxBarDockControl; GridGrants: TcxGrid; GridGrantsDBTableView1: TcxGridDBTableView; GridGrantsDBTableView1Column1: TcxGridDBColumn; GridGrantsDBTableView1Column2: TcxGridDBColumn; GridGrantsDBTableView1Column3: TcxGridDBColumn; GridGrantsDBTableView1Column4: TcxGridDBColumn; cxGridLevel5: TcxGridLevel; tsSequenceSynonyms: TcxTabSheet; dxBarDockControl6: TdxBarDockControl; GridSynonyms: TcxGrid; GridSynonymsDBTableView1: TcxGridDBTableView; GridSynonymsDBTableView1Column1: TcxGridDBColumn; GridSynonymsDBTableView1Column2: TcxGridDBColumn; cxGridLevel6: TcxGridLevel; tsSequenceUsedBy: TcxTabSheet; GridUsed: TcxGrid; GridUsedDBTableView1: TcxGridDBTableView; GridUsedDBTableView1Column1: TcxGridDBColumn; GridUsedDBTableView1Column2: TcxGridDBColumn; GridUsedDBTableView1Column3: TcxGridDBColumn; GridUsedDBTableView1Column4: TcxGridDBColumn; GridUsedDBTableView1Column5: TcxGridDBColumn; cxGridLevel7: TcxGridLevel; tsSequenceScripts: TcxTabSheet; redtDDL: TcxRichEdit; cxLabel6: TcxLabel; cxLabel7: TcxLabel; edtCycleFlag: TcxTextEdit; edtOrderFlag: TcxTextEdit; cxLabel8: TcxLabel; edtName: TcxTextEdit; dxBarManager1: TdxBarManager; bbtnCreateSequence: TdxBarButton; bbtnDropSequence: TdxBarButton; bbtnAlterSequence: TdxBarButton; bbtnRefreshSequence: TdxBarButton; dsGrants: TDataSource; bbtnGrantPrivileges: TdxBarButton; bbtnRefreshGrant: TdxBarButton; dsSynonyms: TDataSource; bbtnCreateSynonym: TdxBarButton; bbtnDropSynonym: TdxBarButton; bbtnRefreshSynonym: TdxBarButton; dsUsed: TDataSource; vtSynonyms: TVirtualTable; vtGrants: TVirtualTable; vtUsedBy: TVirtualTable; procedure bbtnGrantPrivilegesClick(Sender: TObject); procedure bbtnRefreshGrantClick(Sender: TObject); procedure bbtnCreateSynonymClick(Sender: TObject); procedure bbtnDropSynonymClick(Sender: TObject); procedure bbtnRefreshSynonymClick(Sender: TObject); procedure bbtnCreateSequenceClick(Sender: TObject); procedure bbtnAlterSequenceClick(Sender: TObject); procedure bbtnDropSequenceClick(Sender: TObject); procedure bbtnRefreshSequenceClick(Sender: TObject); procedure pcSequencePropertiesPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); private { Private declarations } FSequenceName, FOwner: string; Sequence: TSequence; procedure GetSequence; procedure GetSequenceDetail; procedure GetUsed; public { Public declarations } procedure Init(ObjName, OwnerName: string); override; end; var SequencePropertiesFrm: TSequencePropertiesFrm; implementation {$R *.dfm} uses frmSchemaBrowser, Util, OraStorage, OraGrants, frmGrants, OraSynonym, frmSynonyms, frmSchemaPublicEvent, frmSequenceDetail, VisualOptions; procedure TSequencePropertiesFrm.Init(ObjName, OwnerName: string); var a: boolean; begin inherited Show; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); top := 0; left := 0; FSequenceName := ObjName; FOwner := OwnerName; GetSequence; pcSequencePropertiesPageChanging(self, pcSequenceProperties.ActivePage ,a); end; procedure TSequencePropertiesFrm.GetSequence; begin if Sequence <> nil then FreeAndNil(Sequence); Sequence := TSequence.Create; Sequence.OraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession; Sequence.SEQUENCE_NAME := FSequenceName; Sequence.OWNER := FOwner; Sequence.SetDDL; lblDescription.Caption := Sequence.Status; redtDDL.Text := Sequence.GetDDL; CodeColors(self, 'Default', redtDDL, false); GetSequenceDetail; vtSynonyms.close; vtSynonyms.Assign(Sequence.SynonymList.DSSynonymList); vtSynonyms.Open; vtGrants.close; vtGrants.Assign(Sequence.GrantList.DSGrantList); vtGrants.Open; end; procedure TSequencePropertiesFrm.pcSequencePropertiesPageChanging( Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin inherited; if NewPage = tsSequenceUsedBy then GetUsed; end; procedure TSequencePropertiesFrm.GetSequenceDetail; begin edtName.Text := Sequence.SEQUENCE_NAME; edtIncrementBy.Text := Sequence.INCREMENT_BY; edtLastValue.Text := Sequence.LAST_NUMBER; edtMinValue.Text := Sequence.MIN_VALUE; edtMaxValue.Text := Sequence.MAX_VALUE; edtCacheSize.Text := Sequence.CACHE_SIZE; edtCycleFlag.Text := BoolToStr(Sequence.CYCLE_FLAG, 'YN'); edtOrderFlag.Text := BoolToStr(Sequence.ORDER_FLAG, 'YN'); end; procedure TSequencePropertiesFrm.bbtnRefreshSequenceClick(Sender: TObject); begin inherited; GetSequence; end; procedure TSequencePropertiesFrm.bbtnCreateSequenceClick(Sender: TObject); var s: TSequence; begin inherited; s := TSequence.Create; s.OWNER := Sequence.OWNER; s.SEQUENCE_NAME := ''; s.OraSession := Sequence.OraSession; if SequenceDetailFrm.Init(s) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbSequences); end; procedure TSequencePropertiesFrm.bbtnAlterSequenceClick(Sender: TObject); begin inherited; if Sequence = nil then exit; if Sequence.SEQUENCE_NAME = '' then exit; if SequenceDetailFrm.Init(Sequence) then GetSequence; end; procedure TSequencePropertiesFrm.bbtnDropSequenceClick(Sender: TObject); begin inherited; if Sequence.SEQUENCE_NAME = '' then exit; if Sequence = nil then exit; if SchemaPublicEventFrm.Init(Sequence, oeDrop) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbSequences); end; {*******************************************************************************} { G R A N T S } {*******************************************************************************} procedure TSequencePropertiesFrm.bbtnGrantPrivilegesClick(Sender: TObject); begin inherited; if GrantsFrm.Init(Sequence.GrantList) then GetSequence; end; procedure TSequencePropertiesFrm.bbtnRefreshGrantClick(Sender: TObject); begin inherited; Sequence.GrantList.SetDDL; vtGrants.close; vtGrants.Assign(Sequence.GrantList.DSGrantList); vtGrants.Open; end; {*******************************************************************************} { S Y N O N Y M S } {*******************************************************************************} procedure TSequencePropertiesFrm.bbtnCreateSynonymClick(Sender: TObject); begin inherited; if SynonymsFrm.Init(Sequence.SynonymList) then GetSequence; end; procedure TSequencePropertiesFrm.bbtnDropSynonymClick(Sender: TObject); var SynonymList: TSynonymList; FSynonym: TSynonym; begin inherited; if not vtSynonyms.Active then exit; new(FSynonym); FSynonym^.Owner := Sequence.OWNER; FSynonym^.SynonymName := vtSynonyms.FieldByName('SYNONYM_NAME').AsString; FSynonym^.TableOwner := vtSynonyms.FieldByName('TABLE_OWNER').AsString; FSynonym^.TableName := vtSynonyms.FieldByName('TABLE_NAME').AsString; SynonymList := TSynonymList.Create; SynonymList.OraSession := Sequence.OraSession; SynonymList.TableOwner := Sequence.OWNER; SynonymList.TableName := Sequence.SEQUENCE_NAME; SynonymList.SynonymAdd(FSynonym); if SchemaPublicEventFrm.Init(SynonymList, oeDrop) then GetSequence; end; procedure TSequencePropertiesFrm.bbtnRefreshSynonymClick(Sender: TObject); begin inherited; Sequence.SynonymList.SetDDL; vtSynonyms.close; vtSynonyms.Assign(Sequence.SynonymList.DSSynonymList); vtSynonyms.Open; end; {*******************************************************************************} { U S E D } {*******************************************************************************} procedure TSequencePropertiesFrm.GetUsed; begin vtUsedBy.close; vtUsedBy.Assign(Sequence.DSUsedByList); vtUsedBy.Open; end; end.
unit uItemDetailsDownloadThread; interface uses Classes, SysUtils, TypInfo, Variants, DB, nxdb, ShoppingServiceXMLClasses, EbayConnect, CommonTypes, uTypes, Forms, IdThread, IdSync, uThreadSync, IdComponent; type TDownloadItemDetailsThread = class(TidThread) private // Private declarations FForm : TForm; FOperationResult : AckCodeType; FErrorRecord : eBayAPIError; FEItemId : string; RecAdded : Integer; FSyncObj : TFTSync; FRxDelta : Integer; FTxDelta : Integer; FItemsToGet : TStringList; FEbayShoppingConnect : TEbayShoppingConnect; FGetMultipleItems : TGetMultipleItems; FQuery : TnxQuery; FQueryItems : TnxQuery; FAppID : string; FSiteID : SiteCodeType; FGlobalID : Global_ID; FUpdateRec : TDownloadImageThreadStatus; FCounter : Integer; FCounterAll : Integer; FBasePath : string; FMultiThread : Boolean; FFirsImage : string; FFirstURL : string; FDetailDC : TObject; FDebug : Boolean; FUpdate : Boolean; FDescription : Boolean; Fdc : Char; protected // Protected declarations procedure GetMultipleItemsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); procedure GetMultipleItemsEndRequest(Sender: TObject); procedure GetMultipleItemsStartRequest(Sender: TObject); procedure WriteEbayApiExceptionLog(E : Exception); procedure SetItemsToGet(Value : TStringList); procedure SetGlobalID(Value : Global_ID); procedure EbayShoppingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); public // Public declarations TID : Integer; // Objects visible outside threads property SiteID : SiteCodeType read FSiteID; property AppID : string read FAppID write FAppID; property GlobalID : Global_ID read FGlobalID write SetGlobalID; property ItemsToGet : TStringList read FItemsToGet write SetItemsToGet; property MultiThread : Boolean read FMultiThread write FMultiThread; property FirstImageID : string read FFirsImage write FFirsImage; property FirstImageUrl : string read FFirstURL write FFirstURL; property IDetailDC : TObject read FDetailDC write FDetailDC; property Debug : Boolean read FDebug write FDebug; property Update : Boolean read FUpdate write FUpdate; property IncludeDescription : Boolean read FDescription write FDescription; property DecimalSeparator : Char read Fdc write Fdc; // methods constructor Create; destructor Destroy; override; procedure Run; override; procedure WriteToDB; procedure UpdateDetails; end; implementation uses functions, ActiveX, IdHTTP, uMain, HotLog, Math; { TCompleteCheckThread } constructor TDownloadItemDetailsThread.Create; begin inherited Create; FEbayShoppingConnect := TEbayShoppingConnect.Create(nil); FEbayShoppingConnect.OnWork := EbayShoppingConnectWork; FEbayShoppingConnect.AppID := FAppID; FGlobalID := EBAY_US; FSiteID := GlobalID2SiteCode(FGlobalID); FEbayShoppingConnect.SiteID := FSiteID; FQueryItems := TnxQuery.Create(nil); FQueryItems.Database := fmMain.nxdtbs1; FItemsToGet := TStringList.Create; FSyncObj := TFTSync.Create; FSyncObj.FThread := Self; FBasePath := fmMain.BasePath; FreeOnTerminate := True; FMultiThread := True; FFirsImage := ''; IDetailDC := nil; FDebug := False; FUpdate := False; FDescription := False; Fdc := '.'; end; destructor TDownloadItemDetailsThread.Destroy; begin FreeAndNil(FEbayShoppingConnect); FreeAndNil(FItemsToGet); FreeAndNil(FSyncObj); FreeAndNil(FQueryItems); inherited; end; procedure TDownloadItemDetailsThread.EbayShoppingConnectWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin case AWorkMode of wmRead : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FRxDelta); FRxDelta := AWorkCount; end; wmWrite : begin FSyncObj.OnHttpWork(AWorkMode,AWorkCount-FTxDelta); FTxDelta := AWorkCount; end; end; end; procedure TDownloadItemDetailsThread.GetMultipleItemsAPIError(Sender: TObject; ErrorRecord: eBayAPIError); var i : Integer; begin with ErrorRecord do begin hLog.AddError(0,'ApiCall: GetMultipleItems. API Error',[ShortMessage, LongMessage,ErrorCode,SeverityCode,ErrorClassification,index]); end; if FDebug then begin hLog.Add('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.RequestXMLText.Strings[i]); hLog.Add('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.ResponseXMLText.Strings[i]); end; end; procedure TDownloadItemDetailsThread.GetMultipleItemsEndRequest(Sender: TObject); begin hLog.Add(Format('{hms} ApiCall: GetMultipleItems. Result %s',[GetEnumName(TypeInfo(AckCodeType),ord(FGetMultipleItems.Ack))])); if FDebug then FGetMultipleItems.ResponseXMLDoc.SaveToFile('GetMultipleItemsResponse.xml'); FSyncObj.IncApiUsage; end; procedure TDownloadItemDetailsThread.GetMultipleItemsStartRequest( Sender: TObject); begin hLog.Add('{hms} ApiCall: GetMultipleItems. Starting'); if FDebug then FGetMultipleItems.RequestXMLDoc.SaveToFile('GetMultipleItemsRequest.xml'); end; procedure TDownloadItemDetailsThread.Run; var i : Integer; hr: HRESULT; cnt : Integer; begin inherited; try hr := CoInitializeEx(nil, COINIT_APARTMENTTHREADED); if hr <> S_OK then Exception.Create('Error occurs: ' + IntToHex(hr, 2)); FGetMultipleItems := TGetMultipleItems.Create(nil); FGetMultipleItems.OnAPIError := GetMultipleItemsAPIError; FGetMultipleItems.OnStartRequest := GetMultipleItemsStartRequest; FGetMultipleItems.OnEndRequest := GetMultipleItemsEndRequest; FGetMultipleItems.Connector := FEbayShoppingConnect; if FDescription then FGetMultipleItems.IncludeSelector := [Details,ItemSpecifics,Description] else FGetMultipleItems.IncludeSelector := [Details,ItemSpecifics]; if FUpdate then begin FQueryItems.SQL.Add('SELECT Items.ItemID'); FQueryItems.SQL.Add('FROM Items'); FQueryItems.SQL.Add('WHERE Items.Enabled = true'); end else begin FQueryItems.SQL.Add('SELECT TOP 19 Items.ItemID'); FQueryItems.SQL.Add('FROM Items'); FQueryItems.SQL.Add('WHERE Items.PictureURL Is Null'); end; try FItemsToGet.Clear; if not FUpdate then FItemsToGet.Add(FFirsImage); FQueryItems.Open; if FQueryItems.RecordCount >0 then begin while not FQueryItems.Eof do begin FItemsToGet.Add(FQueryItems.FieldValues['ItemID']); FQueryItems.Next; end; FEbayShoppingConnect.AppID := FAppID; FEbayShoppingConnect.SiteID := FSiteID; repeat cnt := min(19,FItemsToGet.Count-1); FGetMultipleItems.ItemID.Clear; for i := 0 to cnt do FGetMultipleItems.ItemID.Add(FItemsToGet.Strings[i]); try FRxDelta := 0; FTxDelta := 0; FOperationResult := FGetMultipleItems.DoRequestEx; if (FOperationResult in [Failure, PartialFailure]) then begin Exception.Create('Request Failure'); end; //FSyncObj.WriteLog('GetMultipleItems request done. Result: '+GetEnumName(TypeInfo(AckCodeType),ord(FOperationResult))); hLog.Add('{hms} GetMultipleItems request done. Result: '+GetEnumName(TypeInfo(AckCodeType),ord(FOperationResult))); if Terminated then Exit; if FOperationResult in [Success, Warning, PartialFailure] then begin FCounterAll := 0; FCounter := 0; if FUpdate then UpdateDetails else WriteToDB; FUpdateRec.TotalItems := FCounterAll; FUpdateRec.SavedPhotos := FCounter; FSyncObj.UpdDThreadStatus(FUpdateRec); end; if (FOperationResult in [Failure, Warning, PartialFailure]) then begin hLog.AddError(0,'GetMultipleItems Request failure',[GetEnumName(TypeInfo(AckCodeType),ord(FOperationResult))]); if FDebug then begin hLog.Add('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.RequestXMLText.Strings[i]); hLog.Add('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.ResponseXMLText.Strings[i]); end; end; except on E : Exception do WriteEbayApiExceptionLog(E); end; if Terminated then Stop; for i := 0 to cnt do begin FItemsToGet.Delete(0); end; until FItemsToGet.Count = 0; end else Stop; finally FQueryItems.Close; end; finally CoUninitialize; FreeAndNil(FGetMultipleItems); Stop; end; end; procedure TDownloadItemDetailsThread.WriteEbayApiExceptionLog(E: Exception); var i : Integer; begin hLog.AddException(E,'GetMultipleItems',[]); if FDebug then begin hLog.Add('Request XML'); for i := 0 to FEbayShoppingConnect.RequestXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.RequestXMLText.Strings[i]); hLog.Add('Response XML'); for i := 0 to FEbayShoppingConnect.ResponseXMLText.Count -1 do hLog.Add(FEbayShoppingConnect.ResponseXMLText.Strings[i]); end; end; procedure TDownloadItemDetailsThread.WriteToDB; var i,j: Integer; ItemDetails : TItemDetails; begin try for i:=0 to FGetMultipleItems.Items.Count-1 do with FGetMultipleItems.Items.Items[i] do begin inc(FCounterAll); ItemDetails.PaymentMethods := ''; ItemDetails.ShipToLocations := ''; ItemDetails.PictureURL := No_Photo; ItemDetails.ItemID := ItemID; ItemDetails.Description := Description; for j:=0 to PaymentMethods.Count-1 do ItemDetails.PaymentMethods := ItemDetails.PaymentMethods + ',' + PaymentMethods[j]; if Length(ItemDetails.PaymentMethods)>0 then ItemDetails.PaymentMethods := Copy(ItemDetails.PaymentMethods,2,Length(ItemDetails.PaymentMethods)-1); for j:=0 to ShipToLocations.Count-1 do ItemDetails.ShipToLocations := ItemDetails.ShipToLocations + ',' + ShipToLocations[j]; if Length(ItemDetails.ShipToLocations)>0 then ItemDetails.ShipToLocations := Copy(ItemDetails.ShipToLocations,2,Length(ItemDetails.ShipToLocations)-1); if ChildNodes.FindNode('PictureURL') <> nil then begin //if PictureURL <> nil then begin try ItemDetails.PictureURL := PictureURL[0]; except ItemDetails.PictureURL := No_Photo; end; end; ItemDetails.BidCount := BidCount; ItemDetails.ListingStatus := ListingStatus; ItemDetails.QuantitySold := QuantitySold; //if not VarIsNull(ReserveMet) then ItemDetails.ReserveMet := ReserveMet; if Fdc = '.' then ItemDetails.Price := StrToFloat(CurrentPrice.NodeValue) else ItemDetails.Price := StrToFloat( StringReplace(CurrentPrice.NodeValue,'.',Fdc,[])); ItemDetails.PriceCurrency := CurrentPrice.CurrencyID; // try save photo url if FFirsImage = ItemID then FFirstURL := ItemDetails.PictureURL; FSyncObj.SavePictureDetails(ItemDetails); inc(FCounter); //************** // end try download photos end; except on E : Exception do begin hLog.AddException(E,'Save database GetMultipleItems',[ItemDetails.ItemID]); end; end; end; procedure TDownloadItemDetailsThread.UpdateDetails; var i: Integer; ItemDetails : TItemDetails; begin try for i:=0 to FGetMultipleItems.Items.Count-1 do with FGetMultipleItems.Items.Items[i] do begin inc(FCounterAll); ItemDetails.BidCount := BidCount; ItemDetails.ItemID := ItemID; ItemDetails.ListingStatus := ListingStatus; ItemDetails.QuantitySold := QuantitySold; //if not VarIsNull(ReserveMet) then ItemDetails.ReserveMet := ReserveMet; if Fdc = '.' then ItemDetails.Price := StrToFloat(CurrentPrice.NodeValue) else ItemDetails.Price := StrToFloat( StringReplace(CurrentPrice.NodeValue,'.',Fdc,[])); ItemDetails.PriceCurrency := CurrentPrice.CurrencyID; FSyncObj.UpdateItemDetails(ItemDetails); inc(FCounter); //************** // end try update details end; except on E : Exception do begin hLog.AddException(E,'Save database GetMultipleItems',[ItemDetails.ItemID]); end; end; end; procedure TDownloadItemDetailsThread.SetItemsToGet(Value : TStringList); begin if Value <> nil then FItemsToGet.Assign(Value); end; procedure TDownloadItemDetailsThread.SetGlobalID(Value : Global_ID); begin FGlobalID := Value; FSiteID := GlobalID2SiteCode(FGlobalID); FEbayShoppingConnect.SiteID := FSiteID; end; initialization Randomize; end.
// Image loading queue for multithreading preload of images // PNG/JPG/TGA/DDS/PVR only // JPEG with external RAW alpha channel NOT SUPPORTED! // // Copyright (C) 2019 Ivan Polyacov, Apus Software (ivan@apus-software.com) // This file is licensed under the terms of BSD-3 license (see license.txt) // This file is a part of the Apus Game Engine (http://apus-software.com/engine/) unit ImgLoadQueue; interface uses MyServis,Images; type // What happens when requested image is queued, but not ready TQueueRequestMode=( qrmWait, // block and wait until image is ready (requested image get highest priority) qrmReturnSource, // if file is loaded but not yet unpacked - return its content in imageSource and abort task qrmAbort, // abort task qrmIgnore); // do nothing, return nothing threadvar imageSource:ByteArray; // Queue file for loading, name must be with extension procedure QueueFileLoad(fname:string); // Starts one loading thread and 1..4 unpacking threads procedure StartLoadingThreads(unpackThreadsNum:integer=2); // Get raw image from queue if exists or nil elsewere // Waits if image is queued, but not yet processed function GetImageFromQueue(fname:string;mode:TQueueRequestMode=qrmWait):TRawImage; implementation uses SysUtils,Classes,gfxFormats; // Queue type TLoadQueueStatus=(lqsNone, // No entry lqsWaiting, // Load operation queued lqsLoading, // File is loading lqsLoaded, // Loading done, waiting for unpack lqsUnpacking, // Processing by an unpacking thread lqsReady, // All done! Final RAW image data is ready lqsError); // Failed to load the image PQueueEntry=^TQueueEntry; TQueueEntry=record status:TLoadQueueStatus; fname:string; srcData:ByteArray; img:TRawImage; format:TImageFormat; info:TImageInfo; next:PQueueEntry; end; var cSect:TMyCriticalSection; firstItem,lastItem:PQueueEntry; // Threads type TLoadingThread=class(TThread) procedure Execute; override; end; TUnpackThread=class(TThread) procedure Execute; override; end; var // This thread load image files loadingThread:TLoadingThread; // These threads are unpacking compressed images (JPG/PNG) unpackThreads:array[1..4] of TUnpackThread; function GetImageFromQueue(fname:string;mode:TQueueRequestMode=qrmWait):TRawImage; var item,prev:PQueueEntry; found:boolean; begin result:=nil; if firstItem=nil then exit; cSect.Enter; try item:=firstItem; prev:=nil; found:=false; while item<>nil do begin if (item.status<>lqsNone) and SameText(fname,item.fname) then begin found:=true; break; end; prev:=item; item:=item.next; end; if not found then exit; if item.status=lqsReady then exit(item.img); // success case mode of qrmIgnore:exit; qrmAbort:begin item.status:=lqsNone; exit; end; qrmReturnSource: if (item.status in [lqsLoaded,lqsUnpacking]) then begin if item.status=lqsLoaded then item.status:=lqsNone; imageSource:=item.srcData; exit; end; qrmWait:begin LogMessage('Waiting for %s, status %d',[fname,ord(item.status)]); // try to handle this earlier -> move on top if (prev<>nil) and (item.status in [lqsWaiting,lqsLoaded]) then begin prev.next:=item.next; item.next:=firstItem; MemoryBarrier; firstItem:=item; end; end; end; finally cSect.Leave; end; // Wait for result while not (item.status in [lqsNone,lqsReady,lqsError]) do sleep(0); if item.status=lqsReady then result:=item.img; end; procedure QueueFileLoad(fname:string); var item:PQueueEntry; begin fname:=FileName(fname); cSect.Enter; try New(item); item.status:=lqsWaiting; item.fname:=fname; item.next:=nil; if lastItem<>nil then lastItem.next:=item; MemoryBarrier; lastItem:=item; if firstItem=nil then firstItem:=item; finally cSect.Leave; end; end; procedure LockImgQueue; begin cSect.Enter; end; procedure UnlockImgQueue; begin cSect.Leave; end; procedure StartLoadingThreads(unpackThreadsNum:integer=2); var i:integer; begin loadingThread:=TLoadingThread.Create(false); for i:=1 to min2(unpackThreadsNum,high(unpackThreads)) do unpackThreads[i]:=TUnpackThread.Create(false); end; { TLoadingThread } procedure TLoadingThread.Execute; var i,n:integer; item,start:PQueueEntry; procedure Restart; begin // Wait until queue not empty while firstItem=nil do sleep(10); start:=firstItem; item:=start; end; begin RegisterThread('QLoading'); try Restart; repeat while (item<>nil) and (item.status<>lqsWaiting) do item:=item.next; if item=nil then begin Sleep(10); Restart; continue; end; if item.status=lqsWaiting then with item^ do begin LogMessage('Preloading '+fname); try srcData:=LoadFileAsBytes(fname); except on e:Exception do ForceLogMessage('Loader error; '+ExceptionMsg(e)); end; if length(srcData)<30 then begin ForceLogMessage('Failed to load file: '+fname); status:=lqsError; end; format:=CheckImageFormat(srcData); info:=imgInfo; status:=lqsLoaded; // ready for processing end; if firstItem<>start then begin Restart; continue; end; item:=item.next; until terminated; except on e:Exception do ErrorMessage('Error in LoadingThread: '+ExceptionMsg(e)); end; UnregisterThread; end; { TUnpackThread } procedure TUnpackThread.Execute; var item:PQueueEntry; t:int64; begin RegisterThread('QUnpack'); try repeat sleep(1); // Never wait inside CS! item:=firstItem; // Find the first waiting entry cSect.Enter; try while (item<>nil) and (item.status<>lqsLoaded) do item:=item.next; if item<>nil then item.status:=lqsUnpacking; finally cSect.Leave; end; if item<>nil then begin // Unpack image t:=MyTickCount; with item^ do try img:=nil; if format=ifTGA then LoadTGA(srcData,img,true) else if format=ifJPEG then LoadJPEG(srcData,img) else if format=ifPNG then LoadPNG(srcData,img) else if format=ifPVR then LoadPVR(srcData,img,true) else if format=ifDDS then LoadDDS(srcData,img,true) else begin ForceLogMessage('Image format not supported for async load: '+fname); Setlength(srcData,0); status:=lqsError; continue; end; LogMessage('Preloaded: '+fname+', time='+IntToStr(MyTickCount-t)); Setlength(srcData,0); status:=lqsReady; sleep(0); except on e:exception do begin ForceLogMessage('Error unpacking '+fname+': '+ExceptionMsg(e)); Setlength(srcData,0); status:=lqsError; end; end; end; until terminated; except on e:Exception do ErrorMessage('Error in UnpackingThread: '+ExceptionMsg(e)); end; UnregisterThread; end; procedure TerminateThreads; var i:integer; begin if (loadingThread<>nil) and not loadingThread.Terminated then begin loadingThread.Terminate; loadingThread.WaitFor; end; for i:=1 to high(unpackThreads) do if (unpackThreads[i]<>nil) and not unpackThreads[i].Terminated then begin unpackThreads[i].Terminate; unpackThreads[i].WaitFor; end; end; initialization InitCritSect(cSect,'ImgloadQueue'); finalization TerminateThreads; DeleteCritSect(cSect); end.
unit fRoomOrderEditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GR32_Image, GR32, Buttons, cMegaROM, cConfiguration; type TfrmRoomOrder = class(TForm) lstRooms: TListBox; imgRoomPreview: TImage32; cmdOK: TButton; cmdCancel: TButton; cmdSetRoomStart: TSpeedButton; cmdSetCheckPoint1: TSpeedButton; cmdSetCheckPoint2: TSpeedButton; cmdChk1Activate: TSpeedButton; cmdChk2Activate: TSpeedButton; cmdRoomOrderKey: TButton; procedure FormShow(Sender: TObject); procedure lstRoomsClick(Sender: TObject); procedure lstRoomsDblClick(Sender: TObject); procedure lstRoomsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cmdSetRoomOrderStartClick(Sender: TObject); procedure cmdSetRoomCheckpoint1Click(Sender: TObject); procedure cmdSetRoomCheckpoint2Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cmdChk1ActivateClick(Sender: TObject); procedure cmdChk2ActivateClick(Sender: TObject); procedure cmdRoomOrderKeyClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; _RoomOrderStart, _RoomOrderChk1, _RoomOrderChk2, _Chk1Activate,_Chk2Activate : Byte; Chk1Respawn,Chk2Respawn,Chk1Act,Chk2Act : TBitmap; procedure LoadRoomOrder(); procedure DisplayRoom(); { Private declarations } public property RoomOrderStart : Byte read _RoomOrderStart write _RoomOrderStart; property RoomOrderChk1 : Byte read _RoomOrderChk1 write _RoomOrderChk1; property RoomOrderChk2 : Byte read _RoomOrderChk2 write _RoomOrderChk2; property Chk1Activate : Byte read _Chk1Activate write _Chk1Activate; property Chk2Activate : Byte read _Chk2Activate write _Chk2Activate; property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmRoomOrder: TfrmRoomOrder; implementation {$R *.dfm} uses uglobal, fHexadecimalEntry, fRoomOrderKey; procedure TfrmRoomOrder.LoadRoomOrder(); var i : Integer; begin // Cease the drawing on the listbox. This means that // the listbox doesn't redraw every time we add a new entry, // which is probably one of the major causes of slow applications. lstRooms.Items.BeginUpdate; // Clear the listbox, if it has any contents. lstRooms.Items.Clear; // Loop through all the room order data and load it into the listbox. for i := 0 to _ROMData.RoomOrder.Count - 1 do lstRooms.Items.Add(IntToHex(_ROMData.RoomOrder[i],2)); // Resume painting of the listbox. lstRooms.Items.EndUpdate; end; procedure TfrmRoomOrder.FormShow(Sender: TObject); begin Chk1Respawn := TBitmap.Create; Chk1Respawn.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\chk1.bmp'); Chk1Respawn.TransparentMode := tmFixed; Chk1Respawn.TransparentColor := Chk1Respawn.Canvas.Pixels[0,0]; Chk1Respawn.Transparent := True; Chk2Respawn := TBitmap.Create; Chk2Respawn.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\chk2.bmp'); Chk2Respawn.TransparentMode := tmFixed; Chk2Respawn.TransparentColor := Chk2Respawn.Canvas.Pixels[0,0]; Chk2Respawn.Transparent := True; Chk1Act := TBitmap.Create; Chk1Act.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\chk1-2.bmp'); Chk1Act.TransparentMode := tmFixed; Chk1Act.TransparentColor := Chk1Respawn.Canvas.Pixels[0,0]; Chk1Act.Transparent := True; Chk2Act := TBitmap.Create; Chk2Act.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\chk2-2.bmp'); Chk2Act.TransparentMode := tmFixed; Chk2Act.TransparentColor := Chk2Respawn.Canvas.Pixels[0,0]; Chk2Act.Transparent := True; // Initialise the various variables that this screen can // edit in relation to the room order list. Mostly where to load the // data from. _RoomOrderStart := _ROMData.CurrLevel.Properties['ScreenStartCheck1'].Value; _RoomOrderChk1 := _ROMData.CurrLevel.Properties['ScreenStartCheck2'].Value; _RoomOrderChk2 := _ROMData.CurrLevel.Properties['ScreenStartCheck3'].Value; _Chk1Activate := _ROMData.CurrLevel.Properties['ScreenStartChk2Trig'].Value; _Chk2Activate := _ROMData.CurrLevel.Properties['ScreenStartChk3Trig'].Value; // Load in the room order into the listbox. (Perhaps this procedure should // be changed in name, as it could potentially confuse people with the // MegamanROM.LoadRoomOrder procedure) LoadRoomOrder(); // Set the initial item index to the current room. // Maybe this should be the first room in the level? I don't // know. lstRooms.ItemIndex := _RoomOrderStart; // Display the room in the preview image. DisplayRoom; end; procedure TfrmRoomOrder.lstRoomsClick(Sender: TObject); begin // Change the room that is currently displayed. DisplayRoom; end; // This function draws the screen preview that is displayed on the right. procedure TfrmRoomOrder.DisplayRoom(); var TempBitmap : TBitmap32; begin TempBitmap := TBitmap32.create; try TempBitmap.Width := 256; TempBitmap.Height := 256; _ROMData.DrawScreenIndex(TempBitmap,lstRooms.ItemIndex); imgRoomPreview.Bitmap := TempBitmap; finally FreeAndNil(TempBitmap); end; end; procedure TfrmRoomOrder.lstRoomsDblClick(Sender: TObject); var // NewVal : String; Hex : TfrmHex; OldItemIndex : Integer; begin // If there is not any rooms selected, then do not bother // to edit. if lstRooms.ItemIndex > -1 then begin Hex := TfrmHex.Create(self); try Hex.Caption := 'Room Order Byte Entry'; Hex.Description := 'Please enter the room ID:'; Hex.InitValue := lstRooms.Items[lstRooms.ItemIndex]; if Hex.ShowModal = mrOk then begin // Store the selected item, because when the list is reloaded, the item // index is set to -1. OldItemIndex := lstRooms.ItemIndex; // Now we set the room order to be the new value. _ROMData.RoomOrder[lstRooms.ItemIndex] := Hex.ReturnValue; // Repopulate the listbox, to make it look like we are updating the // listbox, not the stored byte array. LoadRoomOrder(); // Reset the itemindex (which is now -1) to the last selected item. lstRooms.ItemIndex := OldItemIndex; // Display the currently selected room, again. DisplayRoom; end; finally FreeAndNil(Hex); end; end; end; procedure TfrmRoomOrder.lstRoomsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin // First, fill the current area with the colour of the window. lstRooms.Canvas.Brush.Color := clWindow; lstRooms.Canvas.FillRect(Rect); if (Index >= _RoomOrderStart) and (Index <= _RoomOrderStart + _ROMData.CurrLevel.RoomAmount) then begin lstRooms.Canvas.Brush.Color := clSkyBlue; lstRooms.Canvas.FillRect(Rect); lstRooms.Canvas.Font.Color := clBlack; lstRooms.Canvas.TextOut(Rect.Left + 1,Rect.Top + 1,lstRooms.Items[index]); end else begin lstRooms.Canvas.Brush.Color := clWindow; lstRooms.Canvas.FillRect(Rect); lstRooms.Canvas.Font.Color := clBlack; lstRooms.Canvas.TextOut(Rect.Left + 1,Rect.Top + 1,lstRooms.Items[index]); end; if (Index = _RoomOrderChk1) then begin lstRooms.Canvas.Draw(60,Rect.Top,Chk1Respawn); end; if (Index = _RoomOrderChk2) then begin lstRooms.Canvas.Draw(76,Rect.Top,Chk2Respawn); end; if (Index = _Chk1Activate) then begin lstRooms.Canvas.Draw(92,Rect.Top,Chk1Act); end; if (Index = _Chk2Activate) then begin lstRooms.Canvas.Draw(108,Rect.Top,Chk2Act); end; if odSelected in State then begin lstRooms.Canvas.FrameRect(Rect); lstRooms.Font.Color := clBlack; end; end; procedure TfrmRoomOrder.cmdSetRoomOrderStartClick(Sender: TObject); begin if lstRooms.ItemIndex > -1 then begin _RoomOrderStart := lstRooms.ItemIndex; lstRooms.Refresh; end; end; procedure TfrmRoomOrder.cmdSetRoomCheckpoint1Click(Sender: TObject); begin if lstRooms.ItemIndex > -1 then begin _RoomOrderChk1 := lstRooms.ItemIndex; lstRooms.Refresh; end; end; procedure TfrmRoomOrder.cmdSetRoomCheckpoint2Click(Sender: TObject); begin if lstRooms.ItemIndex > -1 then begin _RoomOrderChk2 := lstRooms.ItemIndex; lstRooms.Refresh; end; end; procedure TfrmRoomOrder.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(Chk1Respawn); FreeAndNil(Chk2Respawn); FreeAndNil(Chk1Act); FreeAndNil(Chk2Act); end; procedure TfrmRoomOrder.cmdChk1ActivateClick(Sender: TObject); begin if lstRooms.ItemIndex > -1 then begin _Chk1Activate := lstRooms.ItemIndex; lstRooms.Refresh; end; end; procedure TfrmRoomOrder.cmdChk2ActivateClick(Sender: TObject); begin if lstRooms.ItemIndex > -1 then begin _Chk2Activate := lstRooms.ItemIndex; lstRooms.Refresh; end; end; procedure TfrmRoomOrder.cmdRoomOrderKeyClick(Sender: TObject); var RoomOrderKey : TfrmRoomOrderKey; begin RoomOrderKey := TfrmRoomOrderKey.Create(self); try RoomOrderKey.ShowModal; finally FreeAndNil(RoomOrderKey); end; end; end.
unit AddressParametersUnit; interface uses HttpQueryMemberAttributeUnit, JSONNullableAttributeUnit, NullableBasicTypesUnit, GenericParametersUnit; type TAddressParameters = class(TGenericParameters) private [HttpQueryMember('route_id')] [Nullable] FRouteId: NullableString; [HttpQueryMember('route_destination_id')] [Nullable] FRouteDestinationId: NullableInteger; [HttpQueryMember('notes')] FNotes: boolean; public constructor Create; override; property RouteId: NullableString read FRouteId write FRouteId; property RouteDestinationId: NullableInteger read FRouteDestinationId write FRouteDestinationId; property Notes: Boolean read FNotes write FNotes; end; implementation { TAddressParameters } constructor TAddressParameters.Create; begin Inherited Create; FNotes := False; FRouteId := NullableString.Null; FRouteDestinationId := NullableInteger.Null; end; end.
unit GetOrdersWithCustomFieldsUnit; interface uses SysUtils, BaseExampleUnit; type TGetOrdersWithCustomFields = class(TBaseExample) public procedure Execute(Fields: TArray<String>); end; implementation uses CommonTypesUnit, OrderActionsUnit; procedure TGetOrdersWithCustomFields.Execute(Fields: TArray<String>); var ErrorString: String; Orders: TOrdersCustomFields; Offset, Limit: integer; Total: integer; begin Limit := 10; Offset := 0; Orders := Route4MeManager.Order.GetOrdersWithCustomFields( Fields, Limit, Offset, Total, ErrorString); try WriteLn(''); if (Orders.Count > 0) then WriteLn(Format( 'GetOrdersWithCustomFields executed successfully, %d orders returned, %d total', [Orders.Count, Total])) else WriteLn(Format('GetOrdersWithCustomFields error: "%s"', [ErrorString])); finally FreeAndNil(Orders); end; end; end.
unit arkanoid_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,m6805,rom_engine,pal_engine, sound_engine,ay_8910; function iniciar_arkanoid:boolean; implementation const arkanoid_rom:array[0..1] of tipo_roms=( (n:'a75-01-1.ic17';l:$8000;p:$0;crc:$5bcda3b0),(n:'a75-11.ic16';l:$8000;p:$8000;crc:$eafd7191)); arkanoid_mcu:tipo_roms=(n:'a75__06.ic14';l:$800;p:$0;crc:$0be83647); arkanoid_tiles:array[0..2] of tipo_roms=( (n:'a75-03.ic64';l:$8000;p:0;crc:$038b74ba),(n:'a75-04.ic63';l:$8000;p:$8000;crc:$71fae199), (n:'a75-05.ic62';l:$8000;p:$10000;crc:$c76374e2)); arkanoid_proms:array[0..2] of tipo_roms=( (n:'a75-07.ic24';l:$200;p:$0;crc:$0af8b289),(n:'a75-08.ic23';l:$200;p:$200;crc:$abb002fb), (n:'a75-09.ic22';l:$200;p:$400;crc:$a7c6c277)); //Dip arkanoid_dip_a:array [0..6] of def_dip=( (mask:$1;name:'Allow Continue';number:2;dip:((dip_val:$1;dip_name:'No'),(dip_val:$0;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Flip Screen';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Difficulty';number:2;dip:((dip_val:$8;dip_name:'Easy'),(dip_val:$0;dip_name:'Hard'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$10;name:'Bonus Life';number:2;dip:((dip_val:$10;dip_name:'20K 60K 60K+'),(dip_val:$0;dip_name:'20K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$20;name:'Lives';number:2;dip:((dip_val:$20;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coinage';number:4;dip:((dip_val:$40;dip_name:'2C 1C'),(dip_val:$c0;dip_name:'1C 1C'),(dip_val:$80;dip_name:'1C 2C'),(dip_val:$0;dip_name:'1C 6C'),(),(),(),(),(),(),(),(),(),(),(),())),()); var mcu_mem:array[0..$7ff] of byte; paddle_select,palettebank,gfxbank:byte; port_a_in,port_a_out,port_c_in,port_c_out,ddr_a,ddr_c,from_main,from_mcu:byte; main_sent,mcu_sent:boolean; procedure update_video_arkanoid; var f,nchar:word; color,x,y,atrib:byte; begin for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=31-(f shr 5); y:=f and $1f; atrib:=memoria[$e000+(f*2)]; color:=((atrib and $f8) shr 3)+palettebank; nchar:=memoria[$e001+(f*2)]+((atrib and $07) shl 8)+2048*gfxbank; put_gfx(x*8,y*8,nchar,color shl 3,1,0); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,0,256,256,1,0,0,256,256,2); //Sprites for f:=0 to $f do begin atrib:=memoria[$e802+(f*4)]; nchar:=memoria[$e803+(f*4)]+((atrib and $03) shl 8)+1024*gfxbank; color:=((atrib and $f8) shr 3)+palettebank; x:=memoria[$e801+(f*4)]; y:=memoria[$e800+(f*4)]; put_gfx_sprite_diff(2*nchar,color shl 3,false,false,0,8,0); put_gfx_sprite_diff(2*nchar+1,color shl 3,false,false,0,0,0); actualiza_gfx_sprite_size(x,y,2,16,8); end; actualiza_trozo_final(16,0,224,256,2); end; procedure eventos_arkanoid; begin if event.arcade then begin //P1 if arcade_input.start[0] then marcade.in0:=marcade.in0 and $fe else marcade.in0:=marcade.in0 or 1; if arcade_input.start[1] then marcade.in0:=marcade.in0 and $fd else marcade.in0:=marcade.in0 or 2; if arcade_input.coin[0] then marcade.in0:=marcade.in0 or $10 else marcade.in0:=marcade.in0 and $ef; if arcade_input.coin[1] then marcade.in0:=marcade.in0 or $20 else marcade.in0:=marcade.in0 and $df; //p2 if arcade_input.but0[0] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or 1; if arcade_input.but0[1] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or 2; end; end; procedure principal_arkanoid; var frame_m,frame_mcu:single; f:word; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; frame_mcu:=m6805_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //mcu m6805_0.run(frame_mcu); frame_mcu:=frame_mcu+m6805_0.tframes-m6805_0.contador; if f=239 then z80_0.change_irq(HOLD_LINE); end; update_video_arkanoid; eventos_arkanoid; video_sync; end; end; function getbyte_arkanoid(direccion:word):byte; begin case direccion of 0..$bfff,$e000..$efff:getbyte_arkanoid:=memoria[direccion]; $c000..$cfff:getbyte_arkanoid:=memoria[$c000+(direccion and $7ff)]; $d000..$dfff:case (direccion and $1f) of $1,$3,$5,$7:getbyte_arkanoid:=ay8910_0.read; $8..$b:getbyte_arkanoid:=$ff; $c..$f:getbyte_arkanoid:=byte(not(mcu_sent))*$80 or byte(not(main_sent))*$40 or marcade.in0; $10..$17:getbyte_arkanoid:=marcade.in1; $18..$1f:begin getbyte_arkanoid:=from_mcu; mcu_sent:=false; end; end; $f000..$ffff:getbyte_arkanoid:=0; end; end; procedure putbyte_arkanoid(direccion:word;valor:byte); begin case direccion of 0..$bfff:; //ROM $c000..$cfff:memoria[$c000+(direccion and $7ff)]:=valor; $d000..$dfff:case (direccion and $1f) of $0,$2,$4,$6:ay8910_0.control(valor); $1,$3,$5,$7:ay8910_0.write(valor); $8..$f:begin paddle_select:=(valor and $4) shr 2; if gfxbank<>((valor and $20) shr 5) then begin fillchar(gfx[0].buffer,$400,1); gfxbank:=(valor and $20) shr 5; end; if palettebank<>((valor and $40) shr 1) then begin fillchar(gfx[0].buffer,$400,1); palettebank:=(valor and $40) shr 1; end; if (valor and $80)=0 then m6805_0.change_reset(ASSERT_LINE) else m6805_0.change_reset(CLEAR_LINE); end; $18..$1f:begin main_sent:=true; from_main:=valor; m6805_0.irq_request(0,ASSERT_LINE); end; end; $e000..$e7ff:if memoria[direccion]<>valor then begin gfx[0].buffer[(direccion and $7ff) shr 1]:=true; memoria[direccion]:=valor; end; $e800..$ffff:memoria[direccion]:=valor; end; end; function arkanoid_mcu_getbyte(direccion:word):byte; var res:byte; begin direccion:=direccion and $7ff; case direccion of 0:arkanoid_mcu_getbyte:=(port_a_out and ddr_a) or (port_a_in and not(ddr_a)); 1:arkanoid_mcu_getbyte:=analog.c[0].x[paddle_select]; 2:begin res:=byte(main_sent) or (byte(not(mcu_sent)) shl 1); arkanoid_mcu_getbyte:=(port_c_out and ddr_c) or (res and not(ddr_c)); end; $10..$7ff:arkanoid_mcu_getbyte:=mcu_mem[direccion]; end; end; procedure arkanoid_mcu_putbyte(direccion:word;valor:byte); begin direccion:=direccion and $7ff; case direccion of 0:port_a_out:=valor; 2:begin if (((ddr_c and $4)<>0) and ((not(valor) and $4)<>0) and ((port_c_out and $4)<>0)) then begin port_a_in:=from_main; main_sent:=false; m6805_0.irq_request(0,CLEAR_LINE); end; if (((ddr_c and $8)<>0) and ((not(valor) and $8)<>0) and ((port_c_out and $8)<>0)) then begin from_mcu:=port_a_out; mcu_sent:=true; end; port_c_out:=valor; end; 4:ddr_a:=valor; 6:ddr_c:=valor; $10..$7f:mcu_mem[direccion]:=valor; $80..$7ff:; //ROM end; end; procedure arkanoid_sound_update; begin ay8910_0.update; end; function arkanoid_porta_r:byte; begin arkanoid_porta_r:=$ff; end; function arkanoid_portb_r:byte; begin arkanoid_portb_r:=marcade.dswa; end; //Main procedure reset_arkanoid; begin z80_0.reset; m6805_0.reset; ay8910_0.reset; marcade.in0:=$f; marcade.in1:=$ff; port_a_in:=0; port_a_out:=0; port_c_in:=0; port_c_out:=0; ddr_a:=0; ddr_c:=0; from_main:=0; from_mcu:=0; palettebank:=0; gfxbank:=0; paddle_select:=0; main_sent:=false; mcu_sent:=false; end; function iniciar_arkanoid:boolean; const pc_x:array[0..7] of dword=(0, 1, 2, 3, 4, 5, 6, 7); pc_y:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); var colores:tpaleta; f:word; memoria_temp:array[0..$17fff] of byte; begin llamadas_maquina.bucle_general:=principal_arkanoid; llamadas_maquina.reset:=reset_arkanoid; llamadas_maquina.fps_max:=59.185608; iniciar_arkanoid:=false; iniciar_audio(false); screen_init(1,256,256); screen_init(2,256,256,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(12000000 div 2,264); z80_0.change_ram_calls(getbyte_arkanoid,putbyte_arkanoid); z80_0.init_sound(arkanoid_sound_update); //MCU CPU m6805_0:=cpu_m6805.create(12000000 div 4,264,tipo_m68705); m6805_0.change_ram_calls(arkanoid_mcu_getbyte,arkanoid_mcu_putbyte); //Sound Chip ay8910_0:=ay8910_chip.create(3000000,AY8910,0.5); ay8910_0.change_io_calls(arkanoid_porta_r,arkanoid_portb_r,nil,nil); //analog init_analog(z80_0.numero_cpu,z80_0.clock); analog_0(30,15,$7f,$ff,0,false,true,true); //cargar roms if not(roms_load(@memoria,arkanoid_rom)) then exit; if not(roms_load(@mcu_mem,arkanoid_mcu)) then exit; //Cargar tiles if not(roms_load(@memoria_temp,arkanoid_tiles)) then exit; init_gfx(0,8,8,$1000); gfx[0].trans[0]:=true; gfx_set_desc_data(3,0,8*8,2*4096*8*8,4096*8*8,0); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,true,false); //pal if not(roms_load(@memoria_temp,arkanoid_proms)) then exit; for f:=0 to $1ff do begin colores[f].r:=pal4bit(memoria_temp[f+$000]); colores[f].g:=pal4bit(memoria_temp[f+$200]); colores[f].b:=pal4bit(memoria_temp[f+$400]); end; set_pal(colores,$200); //Dip marcade.dswa:=$fe; marcade.dswa_val:=@arkanoid_dip_a; //final reset_arkanoid; iniciar_arkanoid:=true; end; end.
unit DcefB_Options; interface uses Classes, StrUtils, SysUtils, Windows; type TDcefBrowserOptions = class(TPersistent) private FDftDownPath: string; // 值为 APP路径\Download\ FExitPagesClosed: Boolean; // 所有标签关闭后是否终止APP 默认True { FExitDownloading: Boolean; // 正在执行下载时是否终止APP并退出下载 只有FTerminateAppWhenAllPageClosed为True时这个设置才有效 默认为False } FPopupNewWin: Boolean; // 是否弹出新窗口 这样就和TChromium没区别了 这个新窗口将不受TDcefBrowser控制 默认为False FDevToolsEnable: Boolean; //是否允许使用F12 DebugTool 默认为True // --------------------------------------------------------------------------- FAutoDown: Boolean; // 是否自动下载至默认文件夹 默认False FDownLoadPath: string; // 下载路径 默认为FDefaultDownLoadPath procedure SetDownLoadPath(const value: string); procedure SetDevToolsEnable(const Value: Boolean); public constructor Create; published property ExitPagesClosed: Boolean read FExitPagesClosed write FExitPagesClosed; {property ExitDownloading: Boolean read FExitDownloading write FExitDownloading; } property PopupNewWin: Boolean read FPopupNewWin write FPopupNewWin; property DevToolsEnable: Boolean read FDevToolsEnable write SetDevToolsEnable; property AutoDown: Boolean read FAutoDown write FAutoDown; property DownLoadPath: string read FDownLoadPath write SetDownLoadPath; end; implementation { TDcefBrowserOptions } constructor TDcefBrowserOptions.Create; begin FExitPagesClosed := True; //FExitDownloading := False; FDevToolsEnable := True; FPopupNewWin := False; FAutoDown := False; FDftDownPath := ExtractFilePath(Paramstr(0)) + 'Download\'; FDownLoadPath := FDftDownPath; end; procedure TDcefBrowserOptions.SetDevToolsEnable(const Value: Boolean); begin FDevToolsEnable := Value; end; procedure TDcefBrowserOptions.SetDownLoadPath(const value: string); begin if DirectoryExists(value) then FDownLoadPath := IfThen(SameText(Copy(value, Length(value), 1), '\'), value, value + '\') else FDownLoadPath := FDftDownPath; end; end.
unit Room; {$mode objfpc}{$H+} interface Type TRoom=object; length,width:real; {поля: длина и ширина комнаты} function Square:real; {метод определения площади} procedure Init(l,w:real); {инициализирующий метод} end; implementation Function TRoom.Square; {метод определения площади} begin Square:=length*width; end; Procedure TRoom.Init; {инициализирующий метод} begin length:=l; width:=w; end; end.
unit uOrcamentoItemModuloVO; interface uses System.Generics.Collections, uTableName, uKeyField; type [TableName('Orcamento_Item_Modulo')] TOrcamentoItemModuloVO = class private FIdOrcamentoItem: Integer; FDescricao: string; FIdModulo: Integer; FId: Integer; procedure SetDescricao(const Value: string); procedure SetId(const Value: Integer); procedure SetIdModulo(const Value: Integer); procedure SetIdOrcamentoItem(const Value: Integer); public [KeyField('OrcIteMod_Id')] property Id: Integer read FId write SetId; [FieldName('OrcIteMod_OrcamentoItem')] property IdOrcamentoItem: Integer read FIdOrcamentoItem write SetIdOrcamentoItem; [FieldName('OrcIteMod_Modulo')] property IdModulo: Integer read FIdModulo write SetIdModulo; [FieldName('OrcIteMod_Descricao')] property Descricao: string read FDescricao write SetDescricao; end; TListaOrcamentoItemModulo = TObjectList<TOrcamentoItemModuloVO>; implementation { TOrcamentoItemModuloVO } procedure TOrcamentoItemModuloVO.SetDescricao(const Value: string); begin FDescricao := Value; end; procedure TOrcamentoItemModuloVO.SetId(const Value: Integer); begin FId := Value; end; procedure TOrcamentoItemModuloVO.SetIdModulo(const Value: Integer); begin FIdModulo := Value; end; procedure TOrcamentoItemModuloVO.SetIdOrcamentoItem(const Value: Integer); begin FIdOrcamentoItem := Value; end; end.
unit Eagle.ERP.{ModuleName}.ViewModel.Impl.{ModelName}ViewModel; interface uses System.SysUtils, Spring.Container, Spring.Container.Common, EventBus.Attributes, DSharp.Core.Validations, Eagle.ERP.Common.Bind.Attributes, Eagle.ERP.Common.ViewModel.CrudNavigateViewModel, Eagle.ERP.Common.ViewModel.Utils.SearchUtils, Eagle.ERP.Common.Exception.WrongValueException, Eagle.ERP.Common.Exception.WrongValuesException, Eagle.ERP.{ModuleName}.ViewModel.{ModelName}ViewModel, Eagle.ERP.{ModuleName}.Model.Repository.{ModelName}Repository, Eagle.ERP.{ModuleName}.Model.Entity.{ModelName}, Eagle.ERP.{ModuleName}.Model.Entity.Impl.{ModelName}; type T{ModelName}SearchResponse = class(TSearchResponse<T{ModelName}>); T{ModelName}ViewModel = class(TCrudNavigateViewModel<I{ModelName}, I{ModelName}Repository>, I{ModelName}ViewModel, IDataErrorInfo) private procedure NotifyOfEntityChange; override; public [NotifyChange('CanSalvar, CanEdit, CanDelete, Editable, CanPrior, CanNext')] procedure OnSave(Sender: TObject); override; procedure OnSearch(Sender: TObject); [Subscribe, NotifyChange('CanPrior, CanNext')] procedure OnSearchResponse(Event: T{ModelName}SearchResponse); virtual; function GetError: string; function GetItem(const Name: string): string; function GetCodigo: Integer; function GetNome: string; procedure SetNome(const Value: string); function GetIsInativo: Boolean; procedure SetIsInativo(const Value: Boolean); property Codigo: Integer read GetCodigo; property Nome: string read GetNome write SetNome; property IsInativo: Boolean read GetIsInativo write SetIsInativo; end; implementation { T{ModelName}ViewModel } function T{ModelName}ViewModel.GetCodigo: Integer; begin if not Assigned(FEntity) then Exit; Result := FEntity.Id; end; function T{ModelName}ViewModel.GetError: string; begin end; function T{ModelName}ViewModel.GetIsInativo: Boolean; begin if not Assigned(FEntity) then Exit; Result := FEntity.Inativo; end; function T{ModelName}ViewModel.GetItem(const Name: string): string; begin end; function T{ModelName}ViewModel.GetNome: string; begin if not Assigned(FEntity) then Exit; Result := FEntity.Nome; end; procedure T{ModelName}ViewModel.NotifyOfEntityChange; begin inherited; NotifyOfPropertyChange('Codigo'); NotifyOfPropertyChange('Nome'); NotifyOfPropertyChange('IsInativo'); end; procedure T{ModelName}ViewModel.OnSearch(Sender: TObject); begin FDialogService.ShowSearch('C{ModelName}S', T{ModelName}SearchResponse); end; procedure T{ModelName}ViewModel.OnSave(Sender: TObject); begin if FEntity.Nome.IsEmpty then raise EWrongValueException.Create('Nome', 'Campo requerido!'); inherited; end; procedure T{ModelName}ViewModel.OnSearchResponse(Event: T{ModelName}SearchResponse); begin FEntity := Event.Records.First; FCanPrior := not FRepository.IsFirst(FEntity); FCanNext := not FRepository.IsLast(FEntity); NotifyOfEntityChange; end; procedure T{ModelName}ViewModel.SetIsInativo(const Value: Boolean); begin FEntity.Inativo := Value; end; procedure T{ModelName}ViewModel.SetNome(const Value: string); begin FEntity.Nome := Value.Trim; end; initialization GlobalContainer.RegisterType<T{ModelName}ViewModel>('{ModelName}ViewModel').Implements<I{ModelName}ViewModel>; end.
unit DelphiUp.View.Services.Routers; interface type TRouters = class private public constructor Create; destructor Destroy; override; end; var Routers : TRouters; implementation uses Router4D, DelphiUp.View.Layouts.Principal, DelphiUp.View.Pages.Main, DelphiUp.View.Pages.Produtos, DelphiUp.View.Pages.Financeiro.ContasPagar, DelphiUp.View.Pages.Estoque.ReporEstoque; { TRouters } constructor TRouters.Create; begin TRouter4D .Switch .Router('Index', TPageMain) .Router('Produto', TPageProdutos) .Router('ContasPagar', TPageFinanceiroContasPagar) .Router('ReporEstoque', TPageReporEstoque) .Router('Principal', TLayoutPrincipal); end; destructor TRouters.Destroy; begin inherited; end; initialization Routers := TRouters.Create; finalization Routers.Free; end.
unit Thread.ImportaCEPRoteiro; interface uses System.Classes, Control.Bases, System.SysUtils, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Control.RoteirosExpressas, Control.PlanilhaRoteirosExpressas; type Thread_ImportaCEPRoteiro = class(TThread) private FPlanilha : TPlanilhaRoteirosExpressasControl; FArquivo: String; FProcesso: Boolean; FLog: String; FTotalRegistros: Integer; FProgresso: Double; FCancelar: Boolean; procedure UpdateLOG(sMensagem: String); { Private declarations } protected procedure Execute; override; public property Arquivo: String read FArquivo write FArquivo; property Processo: Boolean read FProcesso write FProcesso; property Log: String read FLog write FLog; property Progresso: Double read FProgresso write FProgresso; property TotalRegistros: Integer read FTotalRegistros write FTotalRegistros; property Cancelar: Boolean read FCancelar write FCancelar; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_ImportaCEPRoteiro.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.ENum; { Thread_ImportaCEPRoteiro } procedure Thread_ImportaCEPRoteiro.Execute; var aParam: Array of variant; iPos, i: Integer; sMensagem: String; FRoteiros : TRoteirosExpressasControl; begin { Place thread code here } try FProcesso := True; FCancelar := False; FPlanilha := TPlanilhaRoteirosExpressasControl.Create; FRoteiros := TRoteirosExpressasControl.Create; if FPlanilha.GetPlanilha(FArquivo) then begin iPos := 0; FTotalRegistros := FPlanilha.Planilha.Planilha.Count; FProgresso := 0; for i := 0 to Pred(FTotalRegistros) do begin SetLength(aParam,3); aParam := ['CEP', FPlanilha.Planilha.Planilha[i].CEPInicial,FPlanilha.Planilha.Planilha[i].CEPFinal]; if FRoteiros.Localizar(aParam).IsEmpty then begin FRoteiros.Roteiros.ID := 0; FRoteiros.Roteiros.CCEP5 := FPlanilha.Planilha.Planilha[i].CCEP5; FRoteiros.Roteiros.Descricao := ''; FRoteiros.Roteiros.CEPInicial := FPlanilha.Planilha.Planilha[i].CEPInicial; if FPlanilha.Planilha.Planilha[i].CEPFinal.IsEmpty then FRoteiros.Roteiros.CEPFinal := FPlanilha.Planilha.Planilha[i].CEPInicial else FRoteiros.Roteiros.CEPFinal := FPlanilha.Planilha.Planilha[i].CEPFinal; FRoteiros.Roteiros.Prazo := FPlanilha.Planilha.Planilha[i].Prazo; FRoteiros.Roteiros.Zona := FPlanilha.Planilha.Planilha[i].Zona; FRoteiros.Roteiros.Tipo := FPlanilha.Planilha.Planilha[i].Tipo; FRoteiros.Roteiros.Logradouro := FPlanilha.Planilha.Planilha[i].Logradouro; FRoteiros.Roteiros.Bairro := FPlanilha.Planilha.Planilha[i].Bairro; FRoteiros.Roteiros.Acao := tacIncluir; if not FRoteiros.Gravar() then begin sMensagem := 'Erro ao gravar;' + FPlanilha.Planilha.Planilha[i].CEPInicial; UpdateLOG(sMensagem); end; end; Finalize(aParam); iPos := i; FProgresso := (iPos / FTotalRegistros) * 100; if Self.Terminated then Abort; end; FProcesso := False; end else begin UpdateLOG(FPlanilha.Planilha.Mensagem); end; FRoteiros.Free; FPlanilha.Free; Except on E: Exception do begin sMensagem := '** ERROR **' + 'Classe:' + E.ClassName + chr(13) + 'Mensagem:' + E.Message; UpdateLOG(sMensagem); FProcesso := False; end; end; end; procedure Thread_ImportaCEPRoteiro.UpdateLOG(sMensagem: String); begin FLog := FLOG + #13 + sMensagem; end; end.
{ Version 11.7 Copyright (c) 1995-2008 by L. David Baldwin Copyright (c) 2008-2015 by HtmlViewer Team 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. Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } unit ImgForm; {$include ..\..\source\htmlcons.inc} interface uses SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Math, HtmlImages; type TImageForm = class(TForm) published Image1: TImage; private procedure SetGraphic(const Value: TGraphic); procedure SetImage(const Value: ThtImage); public property Graphic: TGraphic write SetGraphic; property Image: ThtImage write SetImage; end; implementation {$ifdef LCL} {$R *.lfm} {$else} {$R *.dfm} {$endif} procedure TImageForm.SetGraphic(const Value: TGraphic); var OldWidth, OldHeight: Integer; begin OldWidth := Image1.Width; OldHeight := Image1.Height; Image1.Picture.Graphic := Value; Left := Max(Left + (OldWidth - Image1.Width) div 2, 0); Top := Max(Top + (OldHeight - Image1.Height) div 2, 0); end; procedure TImageForm.SetImage(const Value: ThtImage); begin if Value <> nil then begin SetGraphic(Value.Graphic); Image1.Transparent := Value.Transp <> itrNone; end else SetGraphic(nil); end; end.
//Exercicio 46: Faça um algoritmo para ler um valor X e um valor N e calcular a soma: // Y = X - 2X + 4X - 6X + 8X - 10X + ... NX. //Obs. Considere N um número inteiro e par. { Solução em Portugol Algoritmo Exercicio ; Var N, X, contador,alternador_sinal,soma: inteiro; Inicio exiba("Programa que calcula uma soma maluca."); exiba("Digite um número par de termos da soma: "); leia(N); enquanto(resto(N,2) = 1)faça // Consistência exiba("Digite um número par de termos da soma: "); leia(N); fimenquanto; exiba("Digite um número inteiro X: "); leia(X); alternador_sinal <- -1; soma <- X; para contador <- 0 até N -1 faça soma <- soma + 2 * contador * alternador_sinal * X; alternador_sinal <- alternador_sinal * (-1); fimpara; exiba("A soma é: ", soma); Fim. } // Solução em Pascal Program Exercicio; uses crt; var N, X, contador,alternador_sinal,soma: integer; begin clrscr; writeln('Programa que calcula uma soma maluca.'); writeln('Digite um número par de termos da soma: '); readln(N); while((N mod 2) = 1)do Begin writeln('Digite um número par de termos da soma: '); readln(N); end; writeln('Digite um número inteiro X: '); readln(X); alternador_sinal := 1; soma := X; for contador := 0 to N-1 do Begin soma := soma + 2 * contador * alternador_sinal * X; alternador_sinal := alternador_sinal * (-1); End; writeln('A soma é: ', soma); repeat until keypressed; end.
unit ltelnetex; {$mode objfpc}{$H+} interface uses Classes, SysUtils, lTelnet, lnet, sorokinregexpr, Forms; type TLTelnetDebugOutProc = procedure (AStr: string) of object; { TLTelnetClientEx } TLTelnetClientEx = class(TLTelnetClient) private FOnDebugOut: TLTelnetDebugOutProc; RegexObj: TRegExpr; public LastMsg: string; constructor Create(aOwner: TComponent); override; destructor Destroy; override; function WaitFor(FirstMatch, SecondMatch: string; ATimeOut: Cardinal): Integer; property OnDebugOut: TLTelnetDebugOutProc read FOnDebugOut write FOnDebugOut; end; implementation { TLTelnetClientEx } constructor TLTelnetClientEx.Create(aOwner: TComponent); begin inherited Create(aOwner); RegexObj := TRegExpr.Create; end; destructor TLTelnetClientEx.Destroy; begin RegexObj.Free; inherited Destroy; end; { Returns a zero-based index to which regular expression was found or -1 if none was found } function TLTelnetClientEx.WaitFor(FirstMatch, SecondMatch: string; ATimeOut: Cardinal): Integer; var lMsg: string; lRemaining: Integer; begin lRemaining := ATimeOut; Result := -1; if (FirstMatch = '') and (SecondMatch = '') then Exit; repeat if GetMessage(lMsg) > 0 then if Assigned(OnDebugOut) then OnDebugOut(lMsg); LastMsg := lMsg; if FirstMatch <> '' then begin RegexObj.Expression := FirstMatch; if RegexObj.Exec(lMsg) then Exit(0); end; if SecondMatch <> '' then begin RegexObj.Expression := SecondMatch; if RegexObj.Exec(lMsg) then Exit(1); end; CallAction; // don't forget to make the clock tick :) if lRemaining > 0 then // Don't sleep if the routine was called with ATimeOut=0 begin Application.ProcessMessages; Sleep(100); end; Dec(lRemaining, 100); until lRemaining <= 0; end; end.
// Copyright (C) 2011 // GSI Helmholtzzentrum für Schwerionenforschung GmbH // // Author: M.Zweig // unit device_setup; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,etherbone, Global; type TDevSet_Form = class(TForm) Panel1: TPanel; DevAdr_Edit: TEdit; Label1: TLabel; Label2: TLabel; PortNr_Edit: TEdit; OK: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKClick(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var DevSet_Form: TDevSet_Form; implementation {$R *.dfm} procedure TDevSet_Form.OKClick(Sender: TObject); var error:boolean; begin error:= false; myDNSAdress:= DevAdr_Edit.Text; try myAddress := StrToInt('$'+ PortNr_Edit.Text); except Application.MessageBox('This is not a valid hex-adress', 'So What ?', 16); error:= true; end; if not (error) then DevSet_Form.Close; end; procedure TDevSet_Form.FormShow(Sender: TObject); begin DevAdr_Edit.Text:= myDNSAdress; PortNr_Edit.Text:= IntToHex(myAddress, 4); end; procedure TDevSet_Form.FormCreate(Sender: TObject); begin DevAdr_Edit.Text:= First_DNSAdress; PortNr_Edit.Text:= First_PortNumber; myDNSAdress:= First_DNSAdress; myAddress := StrToInt('$'+ First_PortNumber); end; end.
{ This file is part of the Free Component Library (FCL) Copyright (c) 2014 by Michael Van Canneyt Unit tests for Pascal-to-Javascript source map. See the file COPYING.FPC, included in this distribution, for details about the copyright. 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. ********************************************************************** Examples: ./testpas2js --suite=TTestSrcMap.TestEmptyProgram } unit tcsrcmap; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, jstree, jswriter, JSSrcMap, FPPas2Js, FPPJsSrcMap, tcmodules, PasResolveEval; type { TCustomTestSrcMap } TCustomTestSrcMap = class(TCustomTestModule) private FJS_Writer: TJSWriter; FPas2JSMapper: TPas2JSMapper; FSrcMap: TPas2JSSrcMap; protected procedure SetUp; override; procedure TearDown; override; function ConvertJSModuleToString(El: TJSElement): string; override; procedure CheckSrcMap(const aTitle: string; const JSLines: array of string); virtual; procedure WriteSrcMapLine(GeneratedLine: integer); public property Pas2JSMapper: TPas2JSMapper read FPas2JSMapper; // fills SrcMap property SrcMap: TPas2JSSrcMap read FSrcMap; // map container property JS_Writer: TJSWriter read FJS_Writer; // JS element to text end; { TTestSrcMap } TTestSrcMap = class(TCustomTestSrcMap) published procedure TestEmptyProgram; procedure TestEmptyUnit; procedure TestIf; procedure TestIfBegin; procedure TestForConstRange; procedure TestFunction; procedure TestExternalObjCall; procedure TestBracketAccessor; end; implementation { TCustomTestSrcMap } procedure TCustomTestSrcMap.SetUp; begin FSrcMap:=TPas2JSSrcMap.Create('test1.js.map'); FPas2JSMapper:=TPas2JSMapper.Create(4096); FPas2JSMapper.SrcMap:=SrcMap; SrcMap.Release;// release the refcount from the Create //SrcMap.SourceRoot:=''; //SrcMap.LocalFilename:=''; fJS_Writer:=TJSWriter.Create(Pas2JSMapper); JS_Writer.IndentSize:=2; inherited SetUp; end; procedure TCustomTestSrcMap.TearDown; begin // Note: SrcMap is freed by freeing Pas2JSMapper FreeAndNil(FJS_Writer); FreeAndNil(FPas2JSMapper); inherited TearDown; end; function TCustomTestSrcMap.ConvertJSModuleToString(El: TJSElement): string; begin writeln('TCustomTestSrcMap.JSToStr ',GetObjName(El)); JS_Writer.WriteJS(El); Result:=Pas2JSMapper.AsString; end; procedure TCustomTestSrcMap.CheckSrcMap(const aTitle: string; const JSLines: array of string); type TMarker = record Name: string; PasLine: integer; // 1-based PasColMin,PasColMax: integer; // 0-based end; PMarker = ^TMarker; var Markers: array of TMarker; PasSrc: TStringList; function IndexOfMarker(const aName: String): integer; var i: Integer; begin for i:=0 to length(Markers)-1 do if CompareText(Markers[i].Name,aName)=0 then exit(i); Result:=-1; end; procedure AddMarker(const aName: String; PasLine, PasColMin, PasColMax: integer); var i, l: Integer; p: PMarker; begin if IndexOfMarker(aName)>0 then begin writeln('AddMarker duplicate marker "',aName,'"'); for i:=1 to PasLine do writeln(PasSrc[i-1]); Fail('duplicate marker "'+aName+'"'); end; l:=length(Markers); SetLength(Markers,l+1); p:=@Markers[l]; p^.Name:=aName; p^.PasLine:=PasLine; p^.PasColMin:=PasColMin; p^.PasColMax:=PasColMax; end; procedure JSMarkerError(Line, Col: integer; Msg: string); var i: Integer; begin for i:=0 to Line-1 do writeln(JSSource[i]); for i:=1 to Col do write('-'); writeln('^'); Fail(Msg+' at '+IntToStr(Line)+','+IntToStr(Col)); end; var i, j, ColMin, ColMax: integer; Line, aName, SegFile, ActLine: String; p, StartP, ActP: PChar; m: PMarker; aSeg: TSourceMapSegment; begin {$IFDEF VerbosePas2JS} writeln('TCustomTestSrcMap.CheckSrcMap ',aTitle); {for i:=0 to SrcMap.Count-1 do begin write('TCustomTestSrcMap.CheckSrcMap i=',i,' Gen=', SrcMap[i].GeneratedLine,',',SrcMap[i].GeneratedColumn); write(' Src='); if SrcMap[i].SrcFileIndex>0 then write(SrcMap.SourceFiles[SrcMap[i].SrcFileIndex],','); writeln(SrcMap[i].SrcLine,',',SrcMap[i].SrcColumn); end;} for i:=1 to JSSource.Count do WriteSrcMapLine(i); WriteSources(Filename,1,1); writeln('......012345678901234567890123456789012345678901234567890123456789'); {$ENDIF} if Low(JSLines)<>0 then {%H-}Fail('inconsistency'); AssertEquals('expected JavaScript lines',High(JSLines)+1,JSSource.Count); // collect markers in Pascal PasSrc:=TStringList.Create; try PasSrc.Text:=Engine.Source; for i:=1 to PasSrc.Count do begin Line:=PasSrc[i-1]; p:=PChar(Line); repeat case p^ of #0: break; '(': if (p[1]='*') and (p[2] in ['a'..'z','A'..'Z','_']) then begin ColMin:=p-PChar(Line); inc(p,2); StartP:=p; while p^ in ['a'..'z','A'..'Z','0'..'9','_'] do inc(p); aName:=copy(Line,StartP-PChar(Line)+1,p-StartP); if (p^<>'*') or (p[1]<>')') then begin for j:=1 to i do writeln(PasSrc[j-1]); Fail('missing closing bracket of Pascal marker at '+IntToStr(i)+','+IntToStr(p-PChar(Line))); end; inc(p,2); ColMax:=p-PChar(Line); AddMarker(aName,i,ColMin,ColMax); continue; end; end; inc(p); until false; end; // check JavaScript markers for i:=1 to JSSource.Count do begin ActLine:=JSSource[i-1]; if i>High(JSLines)+1 then begin writeln('TCustomTestSrcMap.CheckSrcMap unexpected JS line ',i,': ',ActLine); Fail('created JS has more lines than expected JS'); end; ActP:=PChar(ActLine); Line:=JSLines[i-1]; p:=PChar(Line); repeat case p^ of #0: break; '(': if (p[1]='*') and (p[2] in ['a'..'z','A'..'Z','_']) then begin ColMin:=ActP-PChar(ActLine); inc(p,2); StartP:=p; while p^ in ['a'..'z','A'..'Z','0'..'9','_'] do inc(p); aName:=copy(Line,StartP-PChar(Line)+1,p-StartP); if (p^<>'*') or (p[1]<>')') then begin for j:=1 to i do writeln(JSSource[j-1]); Fail('missing closing bracket of JS marker at '+IntToStr(i)+','+IntToStr(ColMin)); end; inc(p,2); j:=IndexOfMarker(aName); if j<0 then JSMarkerError(i,ColMin,'JS marker "'+aName+'" not found in Pascal'); m:=@Markers[j]; j:=SrcMap.IndexOfSegmentAt(i,ColMin); if j<0 then JSMarkerError(i,ColMin,'JS marker "'+aName+'" has no segment in SrcMap'); aSeg:=SrcMap[j]; SegFile:=SrcMap.SourceFiles[aSeg.SrcFileIndex]; if SegFile<>Filename then JSMarkerError(i,ColMin,'JS marker "'+aName+'" maps to file "'+SegFile+'" instead of "'+Filename+'"'); if aSeg.SrcLine<>m^.PasLine then JSMarkerError(i,ColMin,'JS marker "'+aName+'" maps to Pascal line "'+IntToStr(aSeg.SrcLine)+'" instead of "'+IntToStr(m^.PasLine)+'"'); if (aSeg.SrcColumn<m^.PasColMin) or (aSeg.SrcColumn>m^.PasColMax) then JSMarkerError(i,ColMin,'JS marker "'+aName+'" maps to Pascal col "'+IntToStr(aSeg.SrcColumn)+'" instead of "'+IntToStr(m^.PasColMin)+'-'+IntToStr(m^.PasColMax)+'"'); continue; end; end; if p^<>ActP^ then begin writeln('JavaScript: '); for j:=0 to i-1 do writeln(JSSource[j]); for j:=1 to P-PChar(Line) do write('-'); writeln('^'); writeln('Expected JS:<',Line,'>'); AssertEquals('Expected JavaScript differs',p^,ActP^); end; inc(p); inc(ActP); until false; end; finally PasSrc.Free; end; end; procedure TCustomTestSrcMap.WriteSrcMapLine(GeneratedLine: integer); var JS, Origins: String; begin JS:=JSSource[GeneratedLine-1]; DebugSrcMapLine(GeneratedLine,JS,SrcMap,Origins); writeln(JS); writeln(Origins); end; { TTestSrcMap } procedure TTestSrcMap.TestEmptyProgram; begin StartProgram(false); Add('(*b*)begin'); ConvertProgram; CheckSrcMap('TestEmptyProgram',[ 'rtl.module("program", [], function () {', ' var $mod = this;', '(*b*) $mod.$main = function () {', ' };', '});']); end; procedure TTestSrcMap.TestEmptyUnit; begin StartUnit(false); Add([ 'interface', 'implementation' ]); ConvertUnit; CheckSrcMap('TestEmptyUnit',[ 'rtl.module("Test1", [], function () {', ' var $mod = this;', '});']); end; procedure TTestSrcMap.TestIf; begin StartProgram(false); Add([ 'var (*i*)i: longint;', 'begin', ' if true then', ' (*a*)i:=(*b*)1234 (*c*)+ (*d*)2222', ' else', ' i:=3456;']); ConvertProgram; CheckSrcMap('TestIf',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.(*i*)i = 0;', ' $mod.$main = function () {', ' if (true) {', ' (*a*)$mod.i = (*b*)1234 (*c*)+ (*d*)2222}', ' else $mod.i = 3456;', ' };', '});']); end; procedure TTestSrcMap.TestIfBegin; begin StartProgram(false); Add([ 'var', ' (*E*)E, (*P*)P: String;', 'begin', ' (*E2*)E:=(*bla*)''bla'';', ' (*if1*)if E=P then', ' begin', ' (*then*)E:=''active'';', ' end', ' else', ' begin', ' (*else*)E:=''inactive'';', ' end;']); ConvertProgram; CheckSrcMap('TestIfBegin',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.(*E*)E = "";', ' this.(*P*)P = "";', ' $mod.$main = function () {', '(*E2*) $mod.E = (*bla*)"bla";(*bla*)', ' (*if1*)if ($mod.E === $mod.P) {(*if1*)', '(*then*) $mod.E = "active";', ' } else {', '(*else*) $mod.E = "inactive";', ' };', ' };', '});']); end; procedure TTestSrcMap.TestForConstRange; begin StartProgram(false); Add([ 'var Runner, i: longint;', 'begin', ' (*for*)for (*r*)Runner := (*start*)1000 to (*end*)3000 do', ' (*inc*)inc(i);']); ConvertProgram; CheckSrcMap('TestForConstRange',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.Runner = 0;', ' this.i = 0;', ' $mod.$main = function () {', '(*for*) for ((*r*)$mod.Runner = (*start*)1000; (*r*)$mod.Runner (*end*)<= 3000; (*r*)$mod.Runner++) $mod.i (*inc*)+= 1;', ' };', '});' ]); end; procedure TTestSrcMap.TestFunction; begin StartProgram(false); Add([ 'function DoIt(i: longint): longint; forward;', 'const p = 3;', 'function (*ResultInit*)DoIt(*DoIt*)(i: longint): longint;', 'var Runner, j: longint;', 'begin', ' j:=0;', ' (*for*)for (*r*)Runner := (*start*)p to (*end*)j do', ' (*inc*)inc(j);', ' Result:=j;', 'end;', 'begin', ' (*CallDoIt*)DoIt(2);']); ConvertProgram; CheckSrcMap('TestFunction',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.p = 3;', '(*DoIt*) this.DoIt = function (i) {', '(*ResultInit*) var Result = 0;', ' var Runner = 0;', ' var j = 0;', ' j = 0;', ' for (var $l1 = 3, $end2 = j; $l1 <= $end2; $l1++) {', ' Runner = $l1;', ' j += 1;', ' };', ' Result = j;', ' return Result;', ' };', ' $mod.$main = function () {', '(*CallDoIt*) $mod.DoIt(2);', ' };', '});' ]); end; procedure TTestSrcMap.TestExternalObjCall; begin StartProgram(false); Add([ '{$modeswitch externalclass}', 'type', ' TJSConsole = class external name ''Console''', ' Public', ' procedure log(Obj1 : JSValue); varargs;', ' end;', 'var console : TJSConsole; external name ''window.console'';', ' xhrstatus: longint;', 'begin', ' (*w*)console(*log*).log (''state'');', ' if xhrstatus=200 then', ' begin', ' xhrstatus:=3;', ' xhrstatus:=4;', ' end;']); ConvertProgram; CheckSrcMap('TestExternalObjCall',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.xhrstatus = 0;', ' $mod.$main = function () {', ' (*w*)window.console(*log*).log("state");', ' if ($mod.xhrstatus === 200) {', ' $mod.xhrstatus = 3;', ' $mod.xhrstatus = 4;', ' };', ' };', '});' ]); end; procedure TTestSrcMap.TestBracketAccessor; begin StartProgram(false); Add([ '{$modeswitch externalclass}', 'type', ' TJSObject = class external name ''Object''', ' private', ' function GetProperties(Name: String): JSValue; external name ''[]'';', ' Public', ' property Properties[Name: string]: JSValue read GetProperties;', ' end;', 'var Obj : TJSObject;', ' j: JSValue;', 'begin', ' (*j*)j:=(*Obj*)Obj.Properties[(*bracket*)''state''];', ' ']); ConvertProgram; CheckSrcMap('TestExternalObjCall',[ 'rtl.module("program", [], function () {', ' var $mod = this;', ' this.Obj = null;', ' this.j = undefined;', ' $mod.$main = function () {', '(*j*) $mod.j = (*Obj*)$mod.Obj(*bracket*)["state"];', ' };', '});']); end; Initialization RegisterTests([TTestSrcMap]); end.
unit untMDIImage; interface uses Classes, Forms, Controls, ExtCtrls, Menus, StdCtrls, Windows, Graphics, untCalcImage; type TfrmMDIImage = class(TForm) imgImage: TImage; PopupMenu: TPopupMenu; mnuEnregistrerImage: TMenuItem; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure imgImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Déclarations privées } public { Déclarations publiques } CalcImage : TCalcImage; procedure OuvrirImage(NomFichier : string); procedure EnregistrerImage(NomFichier : string); procedure AnalyseImage; procedure AfficheImage; procedure ChangerDimensionsImage(X, Y : Integer); end; function LimiteCouleur(Couleur : Double) : Byte; function CouleurToColor(Couleur : TCouleur) : TColor; var frmMDIImage: TfrmMDIImage; implementation uses SysUtils, Math, untPrincipale; {$R *.DFM} { TfrmMDIImage } function CouleurToColor(Couleur : TCouleur) : TColor; begin Result := LimiteCouleur(Couleur.Rouge) or (LimiteCouleur(Couleur.Vert) shl 8) or (LimiteCouleur(Couleur.Bleu) shl 16); // Calcul la couleur du pixel end; procedure TfrmMDIImage.AnalyseImage; var X, Y : Integer; Couleur : TColor; begin frmPrincipale.ChangeStatus('Analyse de l''image'); frmPrincipale.ProgressBar.Max := CalcImage.TailleX - 1; for X := 0 to CalcImage.TailleX - 1 do // On parcourt tous begin frmPrincipale.ProgressBar.Position := X; for Y := 0 to CalcImage.TailleY - 1 do // les pixels de l'image with CalcImage.Image[X, Y] do begin Couleur := imgImage.Canvas.Pixels[X, Y]; Rouge := (Couleur and $000000FF); // Calcul les différents Vert := (Couleur and $0000FF00) shr 8; // composants de la couleur Bleu := (Couleur and $00FF0000) shr 16; // à partir d'un pixel end; end; end; procedure TfrmMDIImage.EnregistrerImage(NomFichier: string); begin imgImage.Picture.SaveToFile(NomFichier); // Enregistre l'image end; procedure TfrmMDIImage.OuvrirImage(NomFichier: string); begin imgImage.Picture.LoadFromFile(NomFichier); // Ouvre et affiche l'image dans la fiche ChangerDimensionsImage(imgImage.Picture.Width, imgImage.Picture.Height); // Redimension le tableau de données à la taille de l'image AnalyseImage; // Procédure qui va analyser tous les pixels de l'images et va les mettres dans le tableau Image du CalcImage CalcImage.CalculerHistogramme; // Calcul l'histogramme pour chaque couleur frmPrincipale.ChangeStatus('Prêt'); frmPrincipale.ProgressBar.Position := 0; end; procedure TfrmMDIImage.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; // Ferme la fiche et libère l'espace alloué par celle-ci end; procedure TfrmMDIImage.AfficheImage; var X, Y : Integer; begin imgImage.Picture.Bitmap.Width := CalcImage.TailleX; // Met l'image imgImage.Picture.Bitmap.Height := CalcImage.TailleY; // aux bonnes dimensions frmPrincipale.ChangeStatus('Affichage de l''image'); frmPrincipale.ProgressBar.Max := CalcImage.TailleX - 1; for X := 0 to CalcImage.TailleX - 1 do // Parcourt tous les begin frmPrincipale.ProgressBar.Position := X; for Y := 0 to CalcImage.TailleY - 1 do // pixels de l'images imgImage.Canvas.Pixels[X, Y] := CouleurToColor(CalcImage.Image[X, Y]); end; CalcImage.CalculerHistogramme; frmPrincipale.FinCalcul; end; function LimiteCouleur(Couleur: Double): Byte; begin Result := Round(Max(Min(255, Couleur), 0)); // Met la couleur de type Double sous forme d'un Byte; end; procedure TfrmMDIImage.FormDestroy(Sender: TObject); begin CalcImage.Destroy; ListeImages.Extract(Self); // Supprime la fiche de la liste des images (ici je n'utilise pas la procédure Delete car celle-ci appelle l'évènement OnDestroy et créerait donc une référence circulaire) end; procedure TfrmMDIImage.FormCreate(Sender: TObject); begin DoubleBuffered := True; CalcImage := TCalcImage.Create; // Crée le composant qui contient l'image sous forme de tableau end; procedure TfrmMDIImage.ChangerDimensionsImage(X, Y: Integer); begin imgImage.Picture.Bitmap.Width := X; imgImage.Picture.Bitmap.Height := Y; CalcImage.ChangeDimensions(X, Y); { TODO : Barres de défilement } end; procedure TfrmMDIImage.imgImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin X := X - (imgImage.Width - imgImage.Picture.Width) div 2; // Calcul la position du curseur sur l'image if (X < 0) or (X > imgImage.Picture.Width) then // Verifie si le curseur est sur l'image X := -1; Y := Y - (imgImage.Height - imgImage.Picture.Height) div 2; // Calcul la position du curseur sur l'image if (Y < 0) or (Y > imgImage.Picture.Height) then // Verifie si le curseur est sur l'image Y := -1; frmPrincipale.ChangeCoordonneesCurseur(X, Y); end; end.
unit OS.WriteBufferSettingVerifier; interface uses Classes, SysUtils, Support, Support.Sandforce, Support.Factory, Registry.Helper.Internal, Registry.Helper; type TWriteBufferSettingVerifier = class {$IfNDef UNITTEST} private {$EndIf} function SplitIntoModelAndFirmware( ModelAndFirmware: String; out Model, Firmware: String): Boolean; private ModelList: TStringList; DeviceList: TStringList; function CheckAndCorrectByInterface(const InterfaceName: String): TStringList; function CheckAndCorrectByDevice(ModelPathInRegistry: TRegistryPath; const CurrentDevice: String): String; function CheckAndCorrectByModel(InterfacePathInRegistry: TRegistryPath; const ModelAndFirmware: String): TStringList; function CheckDevice(DevicePathInRegistry: TRegistryPath): Boolean; function CheckSupportStatus(const ModelAndFirmware: String): Boolean; function CorrectDevice(DevicePathInRegistry: TRegistryPath): Boolean; function UnderbarToSpace(const ModelAndFirmware: String): String; function GetDeviceFriendlyName(DevicePathInRegistry: TRegistryPath): String; public function CheckAndCorrect: TStringList; end; implementation { TWriteBufferSettingVerifier } function TWriteBufferSettingVerifier.UnderbarToSpace( const ModelAndFirmware: String): String; var CurrentPoint: Integer; begin result := ModelAndFirmware; for CurrentPoint := 1 to Length(result) do if result[CurrentPoint] = '_' then result[CurrentPoint] := ' '; end; function TWriteBufferSettingVerifier.SplitIntoModelAndFirmware( ModelAndFirmware: String; out Model, Firmware: String): Boolean; const IdeDiskString = 'Disk'; FirmwareLength = 8; var ModelLength: Integer; begin if Copy(ModelAndFirmware, 1, Length(IdeDiskString)) <> IdeDiskString then exit(false); ModelAndFirmware := UnderbarToSpace(ModelAndFirmware); ModelLength := Length(ModelAndFirmware) - (Length(IdeDiskString) + FirmwareLength); Model := Trim(Copy(ModelAndFirmware, Length(IdeDiskString) + 1, ModelLength)); Firmware := Trim(Copy(ModelAndFirmware, ModelLength + Length(IdeDiskString) + 1, FirmwareLength)); result := true; end; function TWriteBufferSettingVerifier.CheckSupportStatus( const ModelAndFirmware: String): Boolean; var SupportFactory: TNSTSupportFactory; NSTSupport: TNSTSupport; Model, Firmware: String; begin if not SplitIntoModelAndFirmware(ModelAndFirmware, Model, Firmware) then exit(false); SupportFactory := TNSTSupportFactory.Create; try NSTSupport := SupportFactory.GetSuitableNSTSupport(Model, Firmware); result := (NSTSupport <> nil) and (NSTSupport.GetSupportStatus.Supported) and (not (NSTSupport is TSandforceNSTSupport)); FreeAndNil(NSTSupport); finally FreeAndNil(SupportFactory); end; end; function TWriteBufferSettingVerifier.CheckDevice( DevicePathInRegistry: TRegistryPath): Boolean; const WriteBufferIsDisabled = 0; begin try result := NSTRegistry.GetRegInt(DevicePathInRegistry) = WriteBufferIsDisabled; except result := false; end; end; function TWriteBufferSettingVerifier.CorrectDevice( DevicePathInRegistry: TRegistryPath): Boolean; const WriteBufferIsEnabled = 1; begin result := NSTRegistry.SetRegInt(DevicePathInRegistry, WriteBufferIsEnabled); end; function TWriteBufferSettingVerifier.GetDeviceFriendlyName( DevicePathInRegistry: TRegistryPath): String; begin DevicePathInRegistry.ValueName := 'FriendlyName'; result := NSTRegistry.GetRegStr(DevicePathInRegistry); end; function TWriteBufferSettingVerifier.CheckAndCorrectByDevice( ModelPathInRegistry: TRegistryPath; const CurrentDevice: String): String; var IsDeviceNeedCorrection: Boolean; DevicePath: String; begin result := ''; DevicePath := ModelPathInRegistry.PathUnderHKEY + '\' + CurrentDevice; ModelPathInRegistry.PathUnderHKEY := DevicePath + '\Device Parameters\Disk'; ModelPathInRegistry.ValueName := 'UserWriteCacheSetting'; IsDeviceNeedCorrection := CheckDevice(ModelPathInRegistry); if IsDeviceNeedCorrection then begin CorrectDevice(ModelPathInRegistry); ModelPathInRegistry.PathUnderHKEY := DevicePath; result := GetDeviceFriendlyName(ModelPathInRegistry); end; end; function TWriteBufferSettingVerifier.CheckAndCorrectByModel( InterfacePathInRegistry: TRegistryPath; const ModelAndFirmware: String): TStringList; var CurrentDevice: String; CurrentDeviceResult: String; begin result := TStringList.Create; if not CheckSupportStatus(ModelAndFirmware) then exit; InterfacePathInRegistry.PathUnderHKEY := InterfacePathInRegistry.PathUnderHKEY + '\' + ModelAndFirmware; NSTRegistry.GetKeyList(InterfacePathInRegistry, DeviceList); for CurrentDevice in DeviceList do begin CurrentDeviceResult := CheckAndCorrectByDevice(InterfacePathInRegistry, CurrentDevice); if CurrentDeviceResult <> '' then result.Add(CurrentDeviceResult); end; end; function TWriteBufferSettingVerifier.CheckAndCorrectByInterface( const InterfaceName: String): TStringList; const DeviceBasePath: TRegistryPath = (Root: LocalMachine; PathUnderHKEY: 'SYSTEM\CurrentControlSet\Enum\'; ValueName: ''); var BasePathWithInterfaceName: TRegistryPath; ModelAndFirmware: String; ResultInModel: TStringList; begin result := TStringList.Create; BasePathWithInterfaceName := DeviceBasePath; BasePathWithInterfaceName.PathUnderHKEY := BasePathWithInterfaceName.PathUnderHKEY + InterfaceName; NSTRegistry.GetKeyList(BasePathWithInterfaceName, ModelList); for ModelAndFirmware in ModelList do begin ResultInModel := CheckAndCorrectByModel( BasePathWithInterfaceName, ModelAndFirmware); if ResultInModel.Count > 0 then result.AddStrings(ResultInModel); FreeAndNil(ResultInModel); end; end; function TWriteBufferSettingVerifier.CheckAndCorrect: TStringList; const InterfaceSet: Array[0..1] of String = ('IDE', 'SCSI'); var CurrentInterfaceName: String; ResultInSpecificInterface: TStringList; begin result := TStringList.Create; ModelList := TStringList.Create; DeviceList := TStringList.Create; for CurrentInterfaceName in InterfaceSet do begin ResultInSpecificInterface := CheckAndCorrectByInterface(CurrentInterfaceName); result.AddStrings(ResultInSpecificInterface); FreeAndNil(ResultInSpecificInterface); end; FreeAndNil(ModelList); FreeAndNil(DeviceList); end; end.
{ *************************************************************************** } { } { This file is part of the XPde project } { } { Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> } { } { 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; see the file COPYING. If not, write to } { the Free Software Foundation, Inc., 59 Temple Place - Suite 330, } { Boston, MA 02111-1307, USA. } { } { *************************************************************************** } unit uActiveTasks; interface uses SysUtils, Types, Classes,XLib, Variants, QTypes, QGraphics, Qt, QControls, QForms, uGraphics, QDialogs, QStdCtrls, QExtCtrls; type TActiveTasksDlg = class(TForm) Label1: TLabel; Timer1: TTimer; procedure FormPaint(Sender: TObject); procedure FormShow(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } activetask: integer; function getDottedText(const text: string; maxwidth: integer): string; public { Public declarations } procedure incActiveTask; end; var ActiveTasksDlg: TActiveTasksDlg=nil; implementation uses uWindowManager; {$R *.xfm} procedure TActiveTasksDlg.FormPaint(Sender: TObject); var x,y: integer; w: integer; c: integer; cli: TWMClient; b: TBitmap; nc: integer; ox: integer; begin y:=19; nc:=xpwindowmanager.framedclients.count; if (nc>7) then nc:=7; w:=nc*43; ox:=(width-w) div 2; x:=ox; canvas.pen.width:=1; R3D(canvas,clientrect); R3D(canvas,rect(14,height-35,315,height-10),false,false,true); c:=0; canvas.pen.color:=clHighlight; canvas.pen.width:=2; while (c<xpwindowmanager.framedclients.count) do begin cli:=xpwindowmanager.framedclients[c]; if c=activetask then begin canvas.rectangle(rect(x,y,x+43,y+43)); end; b:=cli.geticon; if assigned(b) then begin b.transparent:=true; canvas.draw(x+5,y+5,b); x:=x+43; if ((c+1) mod 7)=0 then begin x:=ox; y:=y+43; end; end; inc(c); end; end; procedure TActiveTasksDlg.FormShow(Sender: TObject); var rows: integer; begin width:=330; height:=107; rows:=((xpwindowmanager.framedclients.count-1) div 7)+1; height:=height+(43*(rows-1)); activetask:=0; incActiveTask; left:=(screen.Width-width) div 2; top:=((screen.height-height) div 2)-107; end; procedure TActiveTasksDlg.Timer1Timer(Sender: TObject); var keymap: TXQueryKeymap; c: TWMClient; begin //This is shit! xquerykeymap(qtdisplay,keymap); if keymap[8]=#0 then begin timer1.enabled:=false; c:=xpwindowmanager.framedclients[activetask]; if assigned(c) then begin c.activate; activetasksdlg:=nil; close; end; end; end; procedure TActiveTasksDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin action:=caFree; end; function TActiveTasksDlg.getDottedText(const text:string;maxwidth:integer):string; var w: integer; wc: widestring; k: integer; begin wc:=text; k:=1; canvas.Font.assign(label1.font); w:=canvas.TextWidth(wc); while w>maxwidth do begin wc:=copy(text,1,length(text)-k)+'...'; w:=canvas.TextWidth(wc); inc(k); end; result:=wc; end; procedure TActiveTasksDlg.incActiveTask; var c: TWMClient; begin inc(activetask); if activetask>=xpwindowmanager.framedclients.count then begin activetask:=0; end; invalidate; c:=xpwindowmanager.framedclients[activetask]; label1.caption:=getdottedText(c.gettitle,label1.width); end; end.
(*** CSI 1101, Winter, 1999 ***) (*** Assignment 8, Simulator program ***) (*** author: Dr. R. Holte ***) program a8sim (input,output) ; (* the following constants give symbolic names for the opcodes *) const LDA = 91 ; (* Load Accumulator from memory *) STA = 39 ; (* Store Accumulator into memory *) CLA = 08 ; (* Clear (set to zero) the Accumulator *) INC = 10 ; (* Increment (add 1 to) the Accumulator *) ADD = 99 ; (* Add to Accumulator *) SUB = 61 ; (* Subtract from Accumulator *) JMP = 15 ; (* Jump ("go to ") *) JZ = 17 ; (* Jump if the Zero status bit is TRUE *) JN = 19 ; (* Jump if the Negative status bit is TRUE *) DSP = 01 ; (* Display (write on the screen) *) HLT = 64 ; (* Halt *) type byte = -99..99 ; word = 0000..9999 ; bit = boolean ; var memory: array[word] of byte ; (* the following are the registers in the CPU *) pc: word ; (* program counter *) a: byte ; (* accumulator *) opCode: byte ; (* the opcode of the current instruction *) opAddr: word ; (* the ADDRESS of the operand of the current instruction *) z: bit ; (* "Zero" status bit *) n: bit ; (* "Negative" status bit *) h: bit ; (* "Halt" status bit *) mar: word ; (* Memory Address register *) mdr: byte ; (* Memory Data register *) rw: bit ; (* Read/Write bit. Read = True; Write = False *) procedure load ;(* Loads a machine language program into memory *) var address: word ; first_character, ch: char ; begin address := 0 ; while (not eof) do begin if not eoln then begin read(first_character); if first_character <> ' ' (* non-blank indicates a comment *) then repeat (* skip over comment *) read(ch) until ch = first_character ; while (not eoln) do begin read(memory[address]) ; address := address + 1 end end ; readln end end ; procedure access_memory ; begin if rw then mdr := memory[mar] (* TRUE = read = copy a value from memory into the CPU *) else memory[mar] := mdr (* FALSE = write = copy a value into memory from the CPU *) end ; procedure run ; (* This implements the Fetch-Execute cycle *) begin pc := 0 ; (* always start execution at location 0 *) h := false ; (* reset the Halt status bit *) repeat (* FETCH OPCODE *) mar := pc ; pc := pc + 1 ; (* NOTE that pc is incremented immediately *) rw := true ; access_memory ; opCode := mdr ; (* If the opcode is odd, it needs an operand. FETCH THE ADDRESS OF THE OPERAND *) if (opCode mod 2) = 1 then begin mar := pc ; pc := pc + 1 ; (* NOTE that pc is incremented immediately *) rw := true ; access_memory ; opAddr := mdr ; (* this is just the HIGH byte of the opAddr *) mar := pc ; pc := pc + 1 ; (* NOTE that pc is incremented immediately *) rw := true ; access_memory ; (* this gets the LOW byte *) opAddr := 100*opAddr + mdr (* put the two bytes together *) end ; (* EXECUTE THE OPERATION *) case opCode of LDA: begin mar := opAddr ; (* Get the Operand's value from memory *) rw := true ; access_memory ; a := mdr (* and store it in the Accumulator *) end; STA: begin mdr := a ; (* Store the Accumulator *) mar := opAddr ; (* into the Operand's address *) rw := false ; (* False means "write" *) access_memory end; CLA: begin a := 0 ; (* Clear = set the Accumulator to zero *) z := true ; (* set the Status Bits appropriately *) n := false end; INC: begin a := (a + 1) mod 100;(* Increment = add 1 to the Accumulator *) z := (a = 0); (* set the Status Bits appropriately *) n := (a < 0) end; ADD: begin mar := opAddr ; (* Get the Operand's value from memory *) rw := true ; access_memory ; a := (a + mdr) mod 100; (* and add it to the Accumulator *) z := (a = 0); (* set the Status Bits appropriately *) n := (a < 0) end; SUB: begin mar := opAddr ; (* Get the Operand's value from memory *) rw := true ; access_memory ; a := (a - mdr) mod 100;(* and subtract it from the Accumulator *) z := (a = 0); (* set the Status Bits appropriately *) n := (a < 0) end; JMP: pc := opAddr ; (* opAddr is the address of the next instruction to execute *) JZ : if z then pc := opAddr ;(* Jump if the Z status bit is true *) JN : if n then pc := opAddr ;(* Jump if the N status bit is true *) HLT: h := true ; (* set the Halt status bit *) DSP: begin mar := opAddr ; (* Get the Operand's value from memory *) rw := true ; access_memory ; writeln('memory location',mar:5,' contains the value',mdr:3) end end until h (* continue the Fetch-Execute cycle until Halt bit is set *) end ; procedure identify_myself ; (* Writes who you are to the screen *) begin writeln ; writeln('CSI 1101 (winter,1999). Assignment #8, simulator program.') ; writeln end ; begin (* main program *) identify_myself ; load ; run end.
unit GroupOptionPart; interface uses Classes, SearchOption_Intf, FMX.ListBox, FMX.Controls, UIWappedPartUnit; type TGroupOptionPart = class(TAbsUIWrappedPart) private FCmbTimeUnit: TComboBox; FCmbFunction: TComboBox; public constructor Create(owner: TExpander; cmbTimeUnit, cmbFunction: TComboBox); function GetValues(key: String): String; override; procedure SetValues(key, val: String); override; end; implementation uses Const_SearchOptionUnit, System.SysUtils; { TGruopOptionPart } constructor TGroupOptionPart.Create(owner: TExpander; cmbTimeUnit, cmbFunction: TComboBox); var sList_TimeUnit, sList_Function: TStringList; begin Init( owner ); FCmbTimeUnit := cmbTimeUnit; FCmbFunction := cmbFunction; sList_TimeUnit := StrArrayToStrList( ITEM_LIST_GROUP_TIMEUNIT_VIEW ); sList_Function := StrArrayToStrList( ITEM_LIST_GROUP_FUNCTION ); FCmbTimeUnit.Items := sList_TimeUnit; FCmbTimeUnit.ItemIndex := sList_TimeUnit.IndexOf( ITEM_DEFAULT_GROUP_TIMEUNIT ); //Default: 1 min FCmbFunction.Items := sList_Function; FCmbFunction.ItemIndex := sList_Function.IndexOf( ITEM_DEFAULT_GROUP_FUNCTION ); //Default: AVG end; function TGroupOptionPart.GetValues(key: String): String; begin if key = 'group.use' then result := IsUseToString else if key = 'group.timeunit' then result := IntToStr( ITEM_LIST_GROUP_TIMEUNIT_FACT[ FCmbTimeUnit.ItemIndex ] ) else begin if IsUse = true then begin if key = 'group.func' then result := FCmbFunction.Selected.Text; end else begin result := ''; end; end; end; procedure TGroupOptionPart.SetValues(key, val: String); begin if key = 'group.use' then SetUse( StrToBool( val ) ) else if key = 'group.timeunit' then FCmbTimeUnit.ItemIndex := FCmbTimeUnit.Items.IndexOf( val ) else if key = 'group.func' then FCmbFunction.ItemIndex := FCmbFunction.Items.IndexOf( val ); end; end.
unit AceImg; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2005 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses windows, sysutils, classes, graphics; type TAceImage = class(TObject) end; TAceBitmapType = (abtNone, abtWindows, abtPresMan); TAceBitmap = class(TAceImage) private FPalette: HBITMAP; FDIBBits: Pointer; FMonochrome: Boolean; FBitmapType: TAceBitmapType; FBitmapFileHeader: TBitmapFileHeader; FBitmapStream: TMemoryStream; FCoreHeader: TBitmapCoreHeader; FInfoHeader: TBitmapInfoHeader; FColorSize: Word; FBitsSize: LongInt; FBitmapInfo: PBitmapInfo; FBitmapCoreInfo: PBitmapCoreInfo; FDC: THandle; FWidth, FHeight: LongInt; FPixelsPerInch: Integer; procedure InitBitmap; procedure MakePalette; procedure CreateWinPalette; procedure CreatePMPalette; procedure CreateBitmapInfo; protected function GetHeight(Handle: THandle): Integer; function GetWidth(Handle: THandle): Integer; public constructor Create; virtual; destructor Destroy; override; procedure Clear; procedure LoadFromStream(Stream: TStream); procedure StretchDraw(hnd: THandle; Rect: TRect); procedure Draw(hnd: THandle; x,y: Integer); property Width: LongInt read FWidth write FWidth; property Height: LongInt read FHeight write FHeight; property PixelsPerInch: Integer read FPixelsPerInch write FPixelsPerInch; end; function AceGetGraphic(Stream: TStream): TGraphic; function AceIsBlob(Stream: TStream): Boolean; function AceIsIcon(Stream: TStream): Boolean; function AceIsBitmap(Stream: TStream): Boolean; function AceIsEMF(Stream: TStream): Boolean; function AceIsPlaceWMF(Stream: TStream): Boolean; implementation uses acetypes, forms {$ifdef AceJpeg} ,jpeg {$endif} {$ifdef AcePNG} ,pngimage {$endif} {$ifdef AceGIF} , gifimg {$endif} ; function IsJPegVersion: Boolean; begin {$ifdef AceJpeg} Result := True; {$else} Result := False; {$endif} end; function AceGetGraphic(Stream: TStream): TGraphic; var Spot: Integer; Graphic: TGraphic; procedure LoadImage; begin if Graphic <> nil then begin try Graphic.LoadFromStream(Stream); except Stream.Position := Spot; Graphic.Free; Graphic := nil; end; end; end; begin Graphic := nil; { Stip out any blob header info } AceIsBlob(Stream); { Save position } Spot := Stream.Position; if AceIsBitmap(Stream) then begin Graphic := TBitMap.Create; LoadImage; end; if Graphic = nil then begin if (AceIsEMF(Stream) or AceIsPlaceWMF(Stream)) then begin Graphic := TMetaFile.Create; LoadImage; end; end; if Graphic = nil then begin if AceIsIcon(Stream) then begin Graphic := TIcon.Create; LoadImage; end; end; {$ifdef AcePNG} if Graphic = nil then begin Graphic := TPNGImage.Create; LoadImage; end; {$endif} {$ifdef AceGIF} if Graphic = nil then begin Graphic := TGIFImage.Create; LoadImage; end; {$endif} {$ifdef AceJpeg} if Graphic = nil then begin Graphic := TJPegImage.Create; LoadImage; end; {$endif} {$ifdef AceWIC} if Graphic = nil then begin Graphic := TWICImage.Create; LoadImage; end; {$endif} Result := Graphic; end; function AceIsBlob(Stream: TStream): Boolean; type TGraphicHeader = record Count: Word; { Fixed at 1 } HType: Word; { Fixed at $0100 } Size: Longint; { Size not including header } end; var Size: LongInt; Header: TGraphicHeader; begin Result := False; Stream.Position := 0; Size := Stream.Size; if Size >= Sizeof(TGraphicHeader) Then begin Stream.Read(Header, Sizeof(Header)); if (Header.Count <> 1) or (Header.HType <> $0100) or (Header.Size <> Size - SizeOf(Header)) then Stream.Position := 0 else Result := True; end; end; function AceIsIcon(Stream: TStream): Boolean; const rc3_StockIcon = 0; rc3_Icon = 1; rc3_Cursor = 2; type TCursorOrIcon = packed record Reserved: Word; wType: Word; Count: Word; end; var Header: TCursorOrIcon; Spot: LongInt; begin Result := False; if Stream <> nil then begin if Stream.Size > Stream.Position then begin Spot := Stream.Position; { See if valid cursor } Stream.Read(Header, Sizeof(Header)); Result := (Header.wType in [RC3_STOCKICON, RC3_ICON]); Stream.Position := Spot; end; end; end; { AceIsBitmap } function AceIsBitmap(Stream: TStream): Boolean; var Header: TBitmapFileHeader; Spot: LongInt; begin Result := False; if Stream <> nil then begin if Stream.Size > Stream.Position then begin Spot := Stream.Position; { See if valid bitmap header } Stream.Read(Header, Sizeof(Header)); Result := (Header.bfType = $4D42); Stream.Position := Spot; end; end; end; { AceIsEMF } function AceIsEMF(Stream: TStream): Boolean; var Size, Spot: Longint; Header: TEnhMetaHeader; begin Result := False; if Stream <> nil then begin Size := Stream.Size - Stream.Position; if Size > Sizeof(Header) then begin Spot := Stream.Position; Stream.Read(Header, Sizeof(Header)); Stream.Position := Spot; Result := (Header.iType = EMR_HEADER) and (Header.dSignature = ENHMETA_SIGNATURE); end; end; end; { AceIsPlaceWMF } function AceIsPlaceWMF(Stream: TStream): Boolean; var Size, Spot: Longint; Header: TAcePlaceMetaHeader; Sum: array[0..9] of Word absolute Header; CheckSum: Word; { w,h: Integer;} begin Result := False; if Stream <> nil then begin Size := Stream.Size - Stream.Position; if Size > Sizeof(Header) then begin Spot := Stream.Position; Stream.Read(Header, Sizeof(Header)); Stream.Position := Spot; { w := MulDiv(Header.BBox.Right - Header.BBox.Left,25400,Header.Inch); h := MulDiv(Header.BBox.Bottom - Header.BBox.Top,25400,Header.Inch); } if (Header.Key = AcePlaceHeadKey) then begin Spot := 0; CheckSum := 0; while Spot < 10 do begin CheckSum := CheckSum xor Sum[Spot]; Inc(Spot); end; Result := (CheckSum = Header.CheckSum); end; end; end; end; { TAceBitmap } constructor TAceBitmap.Create; begin FBitmapStream := TMemoryStream.Create; FBitmapInfo := nil; FBitmapCoreInfo := nil; FPalette := 0; FDC := 0; FPixelsPerInch := Screen.PixelsPerInch; end; destructor TAceBitmap.Destroy; begin Clear; if FBitmapStream <> nil then FBitmapStream.Free; inherited Destroy; end; procedure TAceBitmap.Clear; begin FBitmapStream.Clear; if FBitmapInfo <> nil then begin FreeMem(FBitmapInfo, FColorSize + SizeOf(TBitmapInfoHeader)); FBitmapInfo := nil; end; if FBitmapCoreInfo <> nil then begin FreeMem(FBitmapCoreInfo, FColorSize + SizeOf(TBitmapInfoHeader)); FBitmapInfo := nil; end; if FPalette <> 0 then begin DeleteObject(FPalette); FPalette := 0; end; FDC := 0; end; procedure TAceBitmap.LoadFromStream(Stream: TStream); (*****************************************************************) (*** BIOS - BitmapProblem ***) (*****************************************************************) function InlineCopyFrom(Source: TStream; Count: Int64): Int64; var n: Integer; Buffer: PAnsiChar; //** PChar in D7, PByte in D2010 (otherwise Unicode 2 Bytes) //** I use not PByte, maybe Windows handles MemoryAlloc different? //** But testing BByte also worked fine... //** Seems to be a problem StretchDIBits //** with fragmented memory in FDIBBits begin if Count = 0 then //** should not happen... begin Source.Position := 0; Count := Source.Size; end; Result := Count; n := Count; GetMem(Buffer, N); try Source.ReadBuffer(Buffer^, N); FBitmapStream.WriteBuffer(Buffer^, N); finally FreeMem(Buffer, N); end; end; //** function InlineCopyFrom begin Clear; if Stream <> nil then begin if Stream.Size > Stream.Position then begin { See if value bitmap header } Stream.Read(FBitmapFileHeader, Sizeof(FBitmapFileHeader)); if FBitmapFileHeader.bfType = $4D42 then begin { copy entire bitmap } // FBitmapStream.CopyFrom(Stream, Stream.Size - Sizeof(FBitmapFileHeader)); InlineCopyFrom(Stream, Stream.Size - Sizeof(FBitmapFileHeader)); FBitmapStream.Position := 0; InitBitmap; end; end; end; end; function GetDInColors(BitCount: Word): Integer; begin case BitCount of 1, 4, 8: Result := 1 shl BitCount; else Result := 0; end; end; procedure TAceBitmap.InitBitmap; var Size: LongInt; begin FBitmapStream.Read(Size, SizeOf(Size)); FBitmapStream.Position := 0; if Size = SizeOf(FCoreHeader) then begin FBitmapStream.Read(FCoreHeader, SizeOf(FCoreHeader)); FCoreHeader.bcSize := SizeOf(FCoreHeader); FMonochrome := (FCoreHeader.bcPlanes = 1) and (FCoreHeader.bcBitCount = 1); FBitmapType := abtPresMan; FColorSize := GetDInColors(FCoreHeader.bcBitCount) * SizeOf(TRGBTriple); FDIBBits := Pointer(Longint(FBitmapStream.Memory) + Sizeof(FCoreHeader) + FColorSize); FWidth := FCoreHeader.bcWidth; FHeight := FCoreHeader.bcHeight; CreateBitmapInfo; end else if Size = SizeOf(TBitmapInfoHeader) then begin FBitmapStream.Read(FInfoHeader, SizeOf(FInfoHeader)); FInfoHeader.biSize := SizeOf(FInfoHeader); FMonochrome := (FInfoHeader.biPlanes = 1) and (FInfoHeader.biBitCount = 1); FBitmapType := abtWindows; if FInfoHeader.biClrUsed = 0 then FInfoHeader.biClrUsed := GetDInColors(FInfoHeader.biBitCount); FColorSize := FInfoHeader.biClrUsed * SizeOf(TRgbQuad); if ((FInfoHeader.biBitCount = 16) or (FInfoHeader.biBitCount = 32)) then begin if FInfoHeader.biCompression = BI_BITFIELDS then begin Inc(FColorSize, 3 * SizeOf(DWord)); end; end; {$IFDEF WIN64} FDIBBits := Pointer(Int64(FBitmapStream.Memory) + sizeof(FInfoHeader) + FColorSize); {$ELSE} FDIBBits := Pointer(Longint(FBitmapStream.Memory) + sizeof(FInfoHeader) + FColorSize); {$ENDIF} FWidth := FInfoHeader.biWidth; FHeight := FInfoHeader.biHeight; CreateBitmapInfo; end else Clear; FBitmapStream.Position := 0; end; procedure TAceBitmap.CreateBitmapInfo; begin if FBitmapType = abtWindows then begin FBitmapInfo := AllocMem(FColorSize + SizeOf(TBitmapInfoHeader)); with FBitmapInfo^ do begin bmiHeader := FInfoHeader; FBitmapStream.Read(bmiColors, FColorSize); with bmiHeader do begin FBitsSize := FBitmapStream.Size - (Sizeof(TBitmapInfoHeader)+FColorSize); if biSizeImage <> 0 then {if biSizeImage < FBitsSize then FBitsSize := biSizeImage;} if Int64(biSizeImage) < int64(FBitsSize) then FBitsSize := biSizeImage; end; end; end else if FBitmapType = abtPresMan then begin FBitmapCoreInfo := AllocMem(FColorSize + SizeOf(TBitmapCoreHeader)); with FBitmapCoreInfo^ do begin bmciHeader := FCoreHeader; FBitmapStream.Read(bmciColors, FColorSize); with bmciHeader do FBitsSize := ((((bcWidth * bcBitCount) + 31) div 32) * 4) * bcHeight; end; end; end; procedure TAceBitmap.MakePalette; begin case FBitmapType of abtWindows: CreateWinPalette; abtPresMan: CreatePMPalette; end; end; procedure TAceBitmap.CreateWinPalette; var SysPalSize: LongInt; I: Integer; Size, Colors, Spot: Longint; DstPal: PLogPalette; begin if (FPalette = 0) And (FDC <> 0) then begin Colors := FInfoHeader.biClrUsed; if Colors > 2 then begin Size := SizeOf(TLogPalette) + ((Colors - 1) * SizeOf(TPaletteEntry)); DstPal := AllocMem(Size); try FillChar(DstPal^, Size, 0); with DstPal^ do begin palNumEntries := Colors; palVersion := $300; SysPalSize := GetDeviceCaps(FDC, SIZEPALETTE); if (Colors = 16) and (SysPalSize >= 16) then begin GetSystemPaletteEntries(FDC, 0, 8, palPalEntry); I := 8; GetSystemPaletteEntries(FDC, SysPalSize - I, I, palPalEntry[I]); end else for Spot := 0 to Colors - 1 do begin palPalEntry[Spot].peRed := FBitmapInfo^.bmiColors[Spot].rgbRed; palPalEntry[Spot].peGreen := FBitmapInfo^.bmiColors[Spot].rgbGreen; palPalEntry[Spot].peBlue := FBitmapInfo^.bmiColors[Spot].rgbBlue; palPalEntry[Spot].peFlags := 0; end; end; FPalette := CreatePalette(DstPal^); finally FreeMem(DstPal, Size); end; end; end; end; procedure TAceBitmap.CreatePMPalette; var DstPal: PLogPalette; Size, Colors, Spot: Longint; begin if (FPalette = 0) And (FDC <> 0) then begin Colors := GetDInColors(FCoreHeader.bcBitCount); if Colors <> 0 then begin Size := SizeOf(TLogPalette) + ((Colors - 1) * SizeOf(TPaletteEntry)); DstPal := AllocMem(Size); FillChar(DstPal^, Size, 0); try with DstPal^ do begin palNumEntries := Colors; palVersion := $300; for Spot := 0 to Colors - 1 do begin palPalEntry[Spot].peRed := FBitmapCoreInfo^.bmciColors[Spot].rgbtRed; palPalEntry[Spot].peGreen := FBitmapCoreInfo^.bmciColors[Spot].rgbtGreen; palPalEntry[Spot].peBlue := FBitmapCoreInfo^.bmciColors[Spot].rgbtBlue; palPalEntry[Spot].peFlags := 0; end; end; FPalette := CreatePalette(DstPal^); finally FreeMem(DstPal, Size); end; end; end; end; procedure TAceBitmap.StretchDraw(hnd: THandle; Rect: TRect); var SDC: THandle; OldPalette: HPalette; begin OldPalette := 0; SDC := SaveDC(hnd); FDC := hnd; MakePalette; if not FMonochrome then SetStretchBltMode(hnd, STRETCH_DELETESCANS); if FPalette <> 0 then begin OldPalette := SelectPalette(hnd, FPalette, True); RealizePalette(hnd); end; if FBitmapType = abtWindows then begin with FBitmapInfo^.bmiHeader do begin StretchDIBits(hnd, rect.left, rect.top, rect.right - rect.left + 1,rect.bottom - rect.top + 1, 0, 0, FInfoHeader.biWidth, FInfoHeader.biHeight, FDIBBits, FBitmapInfo^, DIB_RGB_COLORS, SRCCOPY); end; end else if FBitmapType = abtPresMan then begin with FBitmapCoreInfo^.bmciHeader do begin StretchDIBits(hnd, rect.left, rect.top, rect.right - rect.left + 1,rect.bottom - rect.top + 1, 0, 0, FCoreHeader.bcWidth, FCoreHeader.bcHeight, FDIBBits, PBitmapInfo(FBitmapCoreInfo)^, DIB_RGB_COLORS, SRCCOPY); end; end; if FPalette <> 0 then SelectPalette(hnd, OldPalette, True); RestoreDC(hnd, SDC); end; procedure TAceBitmap.Draw(hnd: THandle; x,y: Integer); begin StretchDraw(hnd, Bounds(x,y,GetWidth(hnd), GetHeight(hnd))); end; function TAceBitmap.GetHeight(Handle: THandle): Integer; var yPixels: Integer; begin Result := 0; yPixels := GetDeviceCaps(Handle, LOGPIXELSY); case FBitmapType of abtWindows: begin { // Convert pixles per meter to pixels per inch} Result := MulDiv(FInfoHeader.biYPelsPerMeter, 254, 10000); if Result = 0 then Result := FPixelsPerInch; Result := MulDiv(FHeight, yPixels, Result); end; abtPresMan: Result := MulDiv(FHeight, yPixels, FPixelsPerInch); end; end; function TAceBitmap.GetWidth(Handle: THandle): Integer; var xPixels: Integer; begin Result := 0; xPixels := GetDeviceCaps(Handle, LOGPIXELSX); case FBitmapType of abtWindows: begin { // Convert pixles per meter to pixels per inch} Result := MulDiv(FInfoHeader.biXPelsPerMeter, 254, 10000); if Result = 0 then Result := FPixelsPerInch; Result := MulDiv(FWidth, xPixels, Result); end; abtPresMan: Result := MulDiv(FWidth, xPixels, FPixelsPerInch); end; end; end.
unit Cliente.model; interface uses System.SysUtils; type TCliente = class private FDocumento: string; FID: Integer; FNome: string; FTipo: string; FTelefone: string; procedure SetNome(const Value: string); public property ID: Integer read FID write FID; property Nome: string read FNome write SetNome; property Tipo: string read FTipo write FTipo; property Documento: string read FDocumento write FDocumento; property Telefone: string read FTelefone write FTelefone; end; implementation { TCliente } { TCliente } procedure TCliente.SetNome(const Value: string); begin if Value = EmptyStr then raise EArgumentException.Create('''Nome'' precisa ser preechido!'); FNome := Value; end; end.
unit evAACContentUtils; {* [$602009846] } // Модуль: "w:\common\components\gui\Garant\Everest\evAACContentUtils.pas" // Стереотип: "UtilityPack" // Элемент модели: "evAACContentUtils" MUID: (55CB06D00354) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface {$If Defined(k2ForEditor)} uses l3IntfUses , nevBase , nevTools ; const cnAACLeftBackColor = $C48B5C; cnAACContentsLeftIndent = 750; cnTopAACItem = nevInch div 16; cnAACSeparatorSpace = 1050; cnAACContentsRigthIndent = 450; cnAACRightBottomSpace = 1350; function evIsAACItem(aSegment: Tl3Variant; aTextLen: Integer; aCheckInternal: Boolean): Boolean; {* Проверяет покрывает ли гиперссылка весь параграф. } procedure evSelectAACHyperlink(const aView: InevControlView; aHyperlink: Tl3Variant; const aOwnerPara: InevObject; aCheckInternal: Boolean); function evIsAACHyperlink(aPara: Tl3Variant; aCheckInternal: Boolean): Boolean; function evAACNeedSpaceBefore(aPara: Tl3Variant): Boolean; {$IfEnd} // Defined(k2ForEditor) implementation {$If Defined(k2ForEditor)} uses l3ImplUses , HyperLink_Const , evdStyles , evdTypes , k2Tags , evSegLst , evParaTools //#UC START# *55CB06D00354impl_uses* //#UC END# *55CB06D00354impl_uses* ; function evIsAACItem(aSegment: Tl3Variant; aTextLen: Integer; aCheckInternal: Boolean): Boolean; {* Проверяет покрывает ли гиперссылка весь параграф. } //#UC START# *502205C20239_55CB06D00354_var* var l_Type : Integer; l_DocID: Integer; //#UC END# *502205C20239_55CB06D00354_var* begin //#UC START# *502205C20239_55CB06D00354_impl* Result := aSegment.IsValid and (aSegment.IsKindOf(k2_typHyperLink) or (aSegment.IntA[k2_tiStyle] = ev_saHyperlink)); if Result then begin Result := (aSegment.IntA[k2_tiStart] <= 1) and (aSegment.IntA[k2_tiFinish] >= aTextLen); if Result and aCheckInternal then begin with aSegment.Child[0] do begin l_Type := IntA[k2_tiType]; l_DocID :=IntA[k2_tiDocID]; end; // with aSegment.Child[0] do Result := (l_Type = CI_TOPIC) and (l_DocID = 0); end; // if Result then end; // if Result then //#UC END# *502205C20239_55CB06D00354_impl* end;//evIsAACItem procedure evSelectAACHyperlink(const aView: InevControlView; aHyperlink: Tl3Variant; const aOwnerPara: InevObject; aCheckInternal: Boolean); //#UC START# *5063E9CC0008_55CB06D00354_var* var l_Start : InevBasePoint; l_Block : InevRange; l_Finish : InevBasePoint; l_IsHyperlinkOnly: Boolean; //#UC END# *5063E9CC0008_55CB06D00354_var* begin //#UC START# *5063E9CC0008_55CB06D00354_impl* if aHyperlink <> nil then begin l_IsHyperlinkOnly := EvIsAACHyperlink(aOwnerPara.AsObject, aCheckInternal); l_Start := aOwnerPara.MakePoint; l_Start.SetEntryPoint(aHyperlink.IntA[k2_tiStart] - 1); if l_IsHyperlinkOnly then l_Start.SetAtStart(aView, True); l_Finish := aOwnerPara.MakePoint; l_Finish.SetEntryPoint(aHyperlink.IntA[k2_tiFinish]); if l_IsHyperlinkOnly then l_Finish.SetAtEnd(aView, True); l_Block := aOwnerPara.Range(l_Start, l_Finish); aView.Control.Selection.Select(l_Block, False); end; // if aHyperlink <> nil then //#UC END# *5063E9CC0008_55CB06D00354_impl* end;//evSelectAACHyperlink function evIsAACHyperlink(aPara: Tl3Variant; aCheckInternal: Boolean): Boolean; //#UC START# *50223AB403B3_55CB06D00354_var* var l_Pos : Integer; l_Len : Integer; l_Seg : Tl3Variant; l_Segments : Tl3Variant; //#UC END# *50223AB403B3_55CB06D00354_var* begin //#UC START# *50223AB403B3_55CB06D00354_impl* Result := False; l_Segments := aPara.Attr[k2_tiSegments]; if l_Segments.IsValid then begin l_Len := aPara.PCharLenA[k2_tiText].SLen; l_Seg := evSegments_GetSegmentOnPos(l_Segments, ev_slHyperlinks, 1, l_Pos); Result := EvIsAACItem(l_Seg.AsObject, l_Len, aCheckInternal); if not Result then begin l_Seg := evSegments_GetSegmentOnPos(l_Segments, ev_slView, 1, l_Pos); Result := EvIsAACItem(l_Seg, l_Len, aCheckInternal); end;{Seg = nil} end; // if l_Segments.IsValid then //#UC END# *50223AB403B3_55CB06D00354_impl* end;//evIsAACHyperlink function evAACNeedSpaceBefore(aPara: Tl3Variant): Boolean; //#UC START# *55CB274E02B4_55CB06D00354_var* var l_Para: InevPara; //#UC END# *55CB274E02B4_55CB06D00354_var* begin //#UC START# *55CB274E02B4_55CB06D00354_impl* Result := aPara.PCharLenA[k2_tiText].SLen > 0; if Result then begin if not aPara.AsObject.QT(InevPara, l_Para) then Assert(false); Result := False; while (l_Para <> nil) and l_Para.IsValid do begin l_Para := evPrevOverallPara(l_Para); if (l_Para <> nil) and l_Para.IsValid then if not l_Para.IsEmpty then if EvIsAACHyperlink(l_Para.AsObject, True) then begin Result := True; Break; end // if not l_Para.IsEmpty and EvIsAACHyperlink(l_Para.AsObject, True) then else Break; end; // while (l_Para <> nil) and l_Para.IsValid do end; // if Result then //#UC END# *55CB274E02B4_55CB06D00354_impl* end;//evAACNeedSpaceBefore {$IfEnd} // Defined(k2ForEditor) end.
unit a0ptConst; interface type TLogOperations = ( lopEdit, lopDelete, lopExport, lopImport, lopBOChange, lopGrOpenAcc, lopGrCloseAcc, lopChangeOwner, lopAdminON, lopAdminOFF, lopCreateUser, lopDeleteUser, lopAddUsGroup, lopDelUsGroup, lopAddUsRole, lopDelUsRole, lopEditRole, lopClearLog, lopChangeLOp, lopBakUpAdm, lopRestoreAdm, lopAddSlGroup, lopDelSlGroup ); const strLogOperations : array [TLogOperations] of string = ( ' 1 Редактирование сметных/системных данных', ' 2 Удаление сметных/системных данных', ' 3 Экспорт (выгрузка) сметных данных', ' 4 Импорт (загрузка) сметных данных', ' 5 Переключение бизнес-этапа для сметных данных', ' 6 Предоставление группе доступа к сметному объекту', ' 7 Запрет доступа к сметному объекту для группы', ' 8 Изменение собственника сметного объекта', ' 9 Включение разделения доступа', '10 Выключение разделения доступа', '11 Создание пользователя', '12 Удаление пользователя', '13 Привязка пользователя к группе', '14 Исключение пользователя из группы', '15 Назначение роли пользователю', '16 Снятие роли с пользователя', '17 Редактирование роли', '18 Очистка протокола (вручную)', '19 Изменение списка протоколируемых операций', '20 Выгрузка данных административного доступа', '21 Загрузка данных административного доступа', '22 Добавление подчиненной группы', '23 Удаление подчиненной группы' ); type TLogObjects = ( lobProj, lobOS, lobLS, lobPS, lobAct, lobUser, lobRole, lobLog, lobAdm, lobRefer, lobGroup, lobSysObj, lobIndRef ); const strLogObjects: array [TLogObjects] of String = ( ' 1 Проект', ' 2 ОС', ' 3 ЛС', ' 4 ПС (проектная смета)', ' 5 Акт', ' 6 Пользователь', ' 7 Роль', ' 8 Операции с протоколом', ' 9 Операции с разделением доступа', '10 Справочник', '11 Группа', '12 Системные объекты', '13 Справочники индексов' ); implementation end.
{$I ACBr.inc} unit pciotVeiculoW; interface uses SysUtils, Classes, pcnConversao, pciotCIOT, ASCIOTUtil; type TGeradorOpcoes = class; TVeiculoW = class(TPersistent) private FGerador: TGerador; FVeiculo: TVeiculo; FOperacao: TpciotOperacao; FOpcoes: TGeradorOpcoes; public constructor Create(AOwner: TVeiculo; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function GerarXML: boolean; published property Gerador: TGerador read FGerador write FGerador; property Veiculo: TVeiculo read FVeiculo write FVeiculo; property Opcoes: TGeradorOpcoes read FOpcoes write FOpcoes; end; TGeradorOpcoes = class(TPersistent) private FAjustarTagNro: boolean; FNormatizarMunicipios: boolean; FGerarTagAssinatura: TpcnTagAssinatura; FPathArquivoMunicipios: string; FValidarInscricoes: boolean; FValidarListaServicos: boolean; published property AjustarTagNro: boolean read FAjustarTagNro write FAjustarTagNro; property NormatizarMunicipios: boolean read FNormatizarMunicipios write FNormatizarMunicipios; property GerarTagAssinatura: TpcnTagAssinatura read FGerarTagAssinatura write FGerarTagAssinatura; property PathArquivoMunicipios: string read FPathArquivoMunicipios write FPathArquivoMunicipios; property ValidarInscricoes: boolean read FValidarInscricoes write FValidarInscricoes; property ValidarListaServicos: boolean read FValidarListaServicos write FValidarListaServicos; end; //////////////////////////////////////////////////////////////////////////////// implementation { TVeiculoW } uses ASCIOT; constructor TVeiculoW.Create(AOwner: TVeiculo; AOperacao: TpciotOperacao); begin FVeiculo := AOwner; FOperacao := AOperacao; FGerador := TGerador.Create; FGerador.FIgnorarTagNivel := '|?xml version|CTe xmlns|infCTe versao|obsCont|obsFisco|'; FOpcoes := TGeradorOpcoes.Create; FOpcoes.FAjustarTagNro := True; FOpcoes.FNormatizarMunicipios := False; FOpcoes.FGerarTagAssinatura := taSomenteSeAssinada; FOpcoes.FValidarInscricoes := False; FOpcoes.FValidarListaServicos := False; end; destructor TVeiculoW.Destroy; begin FGerador.Free; FOpcoes.Free; inherited Destroy; end; function TVeiculoW.GerarXML: boolean; var chave: AnsiString; Gerar: boolean; xProtCTe : String; begin Gerador.Opcoes.IdentarXML := True; Gerador.Opcoes.TagVaziaNoFormatoResumido := False; Gerador.ArquivoFormatoXML := ''; case FOperacao of opObter: begin Gerador.wGrupo('ObterPorPlacaRequest ' + NAME_SPACE_EFRETE_VEICULOS_EFRETE); Gerador.wTexto('<Integrador ' + NAME_SPACE_EFRETE_OBJECTS + '>' + TAmsCIOT( FVeiculo.Owner ).Configuracoes.Integradora.Identificacao + '</Integrador>'); Gerador.wTexto('<Versao ' + NAME_SPACE_EFRETE_OBJECTS + '>1</Versao>'); Gerador.wCampo(tcStr, '', 'Placa', 001, 007, 1, FVeiculo.Placa, ''); Gerador.wCampo(tcStr, '', 'RNTRC', 001, 008, 1, FVeiculo.RNTRC, ''); Gerador.wGrupo('/ObterPorPlacaRequest'); end; opAdicionar: begin Gerador.wGrupo('GravarRequest ' + NAME_SPACE_EFRETE_VEICULOS_EFRETE, 'VP01'); Gerador.wTexto('<Integrador ' + NAME_SPACE_EFRETE_OBJECTS + '>' + TAmsCIOT( FVeiculo.Owner ).Configuracoes.Integradora.Identificacao + '</Integrador>'); Gerador.wTexto('<Versao ' + NAME_SPACE_EFRETE_OBJECTS + '>1</Versao>'); Gerador.wGrupo('Veiculo', 'VP04'); Gerador.wCampo(tcInt, 'VP05', 'AnoFabricacao', 001, 004, 1, FVeiculo.AnoFabricacao, 'De 1930 até o ano atual.'); Gerador.wCampo(tcInt, 'VP06', 'AnoModelo', 001, 004, 1, FVeiculo.AnoModelo, 'De 1930 até o ano atual.'); Gerador.wCampo(tcInt, 'VP07', 'CapacidadeKg', 001, 001, 1, FVeiculo.CapacidadeKg, 'Capacidade do veículo em Kg.'); Gerador.wCampo(tcInt, 'VP08', 'CapacidadeM3', 001, 001, 1, FVeiculo.CapacidadeM3, 'Capacidade do veículo em M3.'); Gerador.wCampo(tcStr, 'VP09', 'Chassi', 001, 001, 1, FVeiculo.Chassi, 'Chassi do veículo.'); Gerador.wCampo(tcStr, 'VP10', 'CodigoMunicipio', 001, 007, 1, FVeiculo.CodigoMunicipio, 'Código do Município segundo IBGE.'); Gerador.wCampo(tcStr, 'VP11', 'Cor', 001, 001, 1, FVeiculo.Cor, 'Cor do veículo.'); Gerador.wCampo(tcStr, 'VP12', 'Marca', 001, 001, 1, FVeiculo.Marca, 'Marca do veículo.'); Gerador.wCampo(tcStr, 'VP13', 'Modelo', 001, 001, 1, FVeiculo.Modelo, 'Modelo do veículo.'); Gerador.wCampo(tcInt, 'VP14', 'NumeroDeEixos', 001, 002, 1, FVeiculo.NumeroDeEixos, 'Numero de eixos do veículo.'); Gerador.wCampo(tcStr, 'VP15', 'Placa', 001, 007, 7, FVeiculo.Placa, 'Exemplo: AAA1234.'); Gerador.wCampo(tcStr, 'VP16', 'RNTRC', 001, 008, 1, FVeiculo.RNTRC, 'RNTRC do veículo.'); Gerador.wCampo(tcStr, 'VP17', 'Renavam', 001, 001, 1, FVeiculo.Renavam, 'RENAVAM do veículo.'); Gerador.wCampo(tcInt, 'VP18', 'Tara', 001, 08, 1, FVeiculo.Tara, 'Peso do veículo.'); Gerador.wCampo(tcStr, 'VP19', 'TipoCarroceria', 001, 001, 1, TpCarroceriaToStrTxt(FVeiculo.TipoCarroceria), 'Restrito aos itens da enum: -NaoAplicavel -Aberta -FechadaOuBau -Graneleira -PortaContainer -Sider'); Gerador.wCampo(tcStr, 'VP20', 'TipoRodado', 001, 001, 1, TpRodadoToStrTxt(FVeiculo.TipoRodado), 'Restrito aos itens da enum: -NaoAplicavel -Truck -Toco'); Gerador.wGrupo('/Veiculo'); Gerador.wGrupo('/GravarRequest'); end; end; Result := (Gerador.ListaDeAlertas.Count = 0); end; end.
unit EquipmentComands; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GridForma, ActnList, DB, ComCtrls, ToolWin, GridsEh, DBGridEh, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, Menus, StdCtrls, DBCtrls, ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh, System.Actions, Vcl.Buttons, Vcl.ExtCtrls, PrjConst, CnErrorProvider, System.UITypes, EhLibVCL, DBGridEhGrouping, DynVarsEh, Vcl.Mask, DBCtrlsEh; type TEquipmentCommandsForm = class(TGridForm) trWrite: TpFIBTransaction; trRead: TpFIBTransaction; dsCGR: TpFIBDataSet; dbmCMD: TDBMemoEh; procedure srcDataSourceStateChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure srcDataSourceDataChange(Sender: TObject; Field: TField); procedure actNewExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure tbCancelClick(Sender: TObject); procedure tbOkClick(Sender: TObject); procedure actDeleteExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var EquipmentCommandsForm: TEquipmentCommandsForm; implementation uses DM, EquipmentCommandForma; {$R *.dfm} procedure TEquipmentCommandsForm.actDeleteExecute(Sender: TObject); begin inherited; if srcDataSource.DataSet.FieldByName('NAME').IsNull then Exit; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Equipment))) then exit; if (MessageDlg(Format( rsDeleteWithName, [srcDataSource.DataSet['NAME']] ), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then srcDataSource.DataSet.Delete; end; procedure TEquipmentCommandsForm.actEditExecute(Sender: TObject); var bm : TBookmark; begin inherited; if srcDataSource.DataSet.FieldByName('EC_ID').IsNull then Exit; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Equipment))) then exit; if EditGroupCommand(dsCGR['EC_ID']) then begin bm := dsCGR.GetBookmark; dsCGR.CloseOpen(true); dsCGR.GotoBookmark(bm); end; end; procedure TEquipmentCommandsForm.actNewExecute(Sender: TObject); var bm : TBookmark; begin inherited; if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Equipment))) then exit; if EditGroupCommand(-1) then begin bm := dsCGR.GetBookmark; dsCGR.CloseOpen(true); dsCGR.GotoBookmark(bm); end; end; procedure TEquipmentCommandsForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; EquipmentCommandsForm := nil; end; procedure TEquipmentCommandsForm.FormShow(Sender: TObject); begin inherited; dsCGR.Open; // права пользователей actNew.Visible := (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Equipment)); actDelete.Visible := actNew.Visible; actEdit.Visible := actNew.Visible; tbOk.Visible := actNew.Visible; tbCancel.Visible := actNew.Visible; end; procedure TEquipmentCommandsForm.srcDataSourceDataChange(Sender: TObject; Field: TField); begin inherited; actEdit.Enabled := ((sender as TDataSource).DataSet.RecordCount>0) and actNew.Enabled; actDelete.Enabled := ((sender as TDataSource).DataSet.RecordCount>0) and actNew.Enabled; end; procedure TEquipmentCommandsForm.srcDataSourceStateChange(Sender: TObject); begin inherited; tbOk.Enabled := not ((sender as TDataSource).DataSet.State = dsBrowse); tbCancel.Enabled := tbOk.Enabled; actNew.Enabled := not tbOk.Enabled; actEdit.Enabled := not tbOk.Enabled; actDelete.Enabled := not tbOk.Enabled; end; procedure TEquipmentCommandsForm.tbCancelClick(Sender: TObject); begin inherited; dsCGR.Cancel; end; procedure TEquipmentCommandsForm.tbOkClick(Sender: TObject); begin inherited; dsCGR.Post; end; end.
unit CoreTypes; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {$mode objfpc}{$H+} {$macro on} {$modeswitch advancedrecords} {$inline on} interface uses SysUtils; type //TPoint of Float TFPoint = packed record X,Y:Double; end; TFPointArray = Array of TFPoint; //Int TIntArray = array of Integer; T2DIntArray = array of TIntArray; T3DIntArray = array of T2DIntArray; //Byte TByteArray = array of Byte; T2DByteArray = array of TByteArray; T3DByteArray = array of T2DByteArray; //Bool TBoolArray = array of Boolean; T2DBoolArray = array of TBoolArray; T3DBoolArray = array of T2DBoolArray; //Extended TExtArray = array of Extended; T2DExtArray = array of TExtArray; T3DExtArray = array of T2DExtArray; //Double TDoubleArray = array of Double; T2DDoubleArray = array of TDoubleArray; T3DDoubleArray = array of T2DDoubleArray; //Float (aka single) TFloatArray = array of Single; T2DFloatArray = array of TFloatArray; T3DFloatArray = array of T2DFloatArray; //String+Char TStringArray = array of String; TStrArray = array of String; TCharArray = array of Char; //TPoint TPoint = packed record X,Y: LongInt; function InBox(x1,y1,x2,y2:Int32): Boolean; end; TPointArray = array of TPoint; T2DPointArray = array of TPointArray; T3DPointArray = array of T2DPointArray; //TBox TBox = packed record X1, Y1, X2, Y2: LongInt; private function GetWidth: Integer; function GetHeight: Integer; public property Width: Integer read GetWidth; property Height: Integer read GetHeight; function Center: TPoint; procedure Expand(const SizeChange: Integer); end; TBoxArray = Array of TBox; T2DBoxArray = Array of TBoxArray; //Regular datatypes w/pointers Float32 = Single; Float64 = Double; Float80 = Extended; PFloat32 = ^Single; PFloat64 = ^Double; PFloat80 = ^Extended; PInt8 = ^Int8; PInt16 = ^Int16; PInt32 = ^Int32; PInt64 = ^Int64; PUInt8 = ^UInt8; PUInt16 = ^UInt16; PUInt32 = ^UInt32; PUInt64 = ^UInt64; // TAlignAlgo = (AA_BOUNDS, AA_CHULL, AA_BBOX); TThreshAlgo = (TA_MEAN, TA_MINMAX); TCenterAlgo = (CA_BOUNDS, CA_BBOX, CA_MEAN, CA_Median); TResizeAlgo = (RA_NEAREST, RA_BILINEAR, RA_BICUBIC); //Color correlation algorithm TCCorrMode = (CC_EUCLID, CC_EUCLID_NORMED, CC_EUCLID_SQUARED, CC_CHEB, CC_CHEB_NORMED); //Comperison operator TComparator = (__LT__, __GT__, __EQ__, __NE__, __GE__, __LE__); TChars = Array of T2DIntArray; TCharsArray = Array of TChars; ColorLAB = packed record L, A, B: Single; end; ColorHSV = packed record H, S, V: Single; end; ColorRGB = packed record R, G, B, A: UInt8; end; PRGB32 = ^TRGB32; TRGB32 = packed record B, G, R, A: UInt8; end; function Box(const x1,y1,x2,y2:Integer): TBox; Inline; function Point(const x,y:Integer): TPoint; Inline; function FPoint(const x,y:Extended):TFPoint; Inline; function TFPAToTPA(TFPA:TFPointArray): TPointArray; function TPAToTFPA(TPA:TPointArray): TFPointArray; //----------------------------------------------------------------------- implementation uses math; function TBox.GetWidth: Integer; begin Result := (X2-X1+1); end; function TBox.GetHeight: Integer; begin Result := (Y2-Y1+1); end; function TBox.Center: TPoint; begin Result.X := Self.X1 + (GetWidth div 2); Result.Y := Self.Y1 + (GetHeight div 2); end; procedure TBox.Expand(const SizeChange: Integer); begin Self.X1 := Self.X1 - SizeChange; Self.Y1 := Self.Y1 - SizeChange; Self.X2 := Self.X2 + SizeChange; Self.Y2 := Self.Y2 + SizeChange; end; function TPoint.InBox(x1,y1,x2,y2:Int32): Boolean; begin Result := InRange(Self.x, x1, x2) and InRange(Self.y, y1, y2); end; function Box(const X1,Y1,X2,Y2:Integer): TBox; Inline; begin Result.x1 := x1; Result.y1 := y1; Result.x2 := x2; Result.y2 := y2; end; function Point(const X, Y: Integer): TPoint; Inline; begin Result.X := X; Result.Y := Y; end; function FPoint(const X,Y:Extended): TFPoint; Inline; begin Result.X := X; Result.Y := Y; end; function TFPAToTPA(TFPA:TFPointArray): TPointArray; var i:Integer; begin SetLength(Result, Length(TFPA)); for i:=0 to High(TFPA) do Result[i] := Point(Round(TFPA[i].x), Round(TFPA[i].y)); end; function TPAToTFPA(TPA:TPointArray): TFPointArray; var i:Integer; begin SetLength(Result, Length(TPA)); for i:=0 to High(TPA) do begin Result[i].x := TPA[i].x; Result[i].y := TPA[i].y; end; end; end.
unit RegSvr; { Inno Setup Copyright (C) 1997-2012 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Registers OLE servers & type libraries after a reboot } interface procedure RunRegSvr; implementation uses Windows, SysUtils, Classes, Forms, PathFunc, CmnFunc2, InstFunc, InstFnc2, FileClass, CmnFunc, Struct, Main, Msgs, MsgIDs, RegDLL, Helper; procedure DeleteOldTempFiles(const Path: String); { Removes any old isRS-???.tmp files from Path. Not strictly necessary, but in case a prior multi-install run left behind multiple .tmp files now is a good time to clean them up. } var H: THandle; FindData: TWin32FindData; Filename: String; begin H := FindFirstFile(PChar(Path + 'isRS-???.tmp'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat { Yes, this StrLIComp is superfluous. When deleting files from potentionally the Windows directory I can't help but be *extra* careful. :) } if (StrLIComp(FindData.cFileName, 'isRS-', Length('isRS-')) = 0) and (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY = 0) then begin Filename := Path + FindData.cFileName; { If the file is read-only, try to strip the attribute } if FindData.dwFileAttributes and FILE_ATTRIBUTE_READONLY <> 0 then SetFileAttributes(PChar(Filename), FindData.dwFileAttributes and not FILE_ATTRIBUTE_READONLY); DeleteFile(Filename); end; until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; end; function RenameToNonRandomTempName(const Filename: String): String; { Renames Filename to a name in the format: isRS-nnn.tmp. Returns the new filename if successful, or '' if not. Note: This is an NT-only function, as it calls MoveFileEx. } var Path, NewFilename: String; Attribs: DWORD; Attempts, I: Integer; begin Result := ''; Path := PathExtractPath(Filename); Attempts := 0; for I := 0 to 999 do begin NewFilename := Path + Format('isRS-%.3u.tmp', [I]); Attribs := GetFileAttributes(PChar(NewFilename)); if Attribs <> $FFFFFFFF then begin { Skip any directories that happen to named NewFilename } if Attribs and FILE_ATTRIBUTE_DIRECTORY <> 0 then Continue; { If the existing file is read-only, try to strip the attribute } if Attribs and FILE_ATTRIBUTE_READONLY <> 0 then SetFileAttributes(PChar(NewFilename), Attribs and not FILE_ATTRIBUTE_READONLY); end; if MoveFileEx(PChar(Filename), PChar(NewFilename), MOVEFILE_REPLACE_EXISTING) then begin Result := NewFilename; Break; end; Inc(Attempts); { Limit MoveFileEx calls to 10 since it can be really slow over network connections when a file is in use } if Attempts = 10 then Break; end; end; procedure DeleteSelf; var SelfFilename, NewFilename: String; begin SelfFilename := NewParamStr(0); if Win32Platform = VER_PLATFORM_WIN32_NT then begin { On NT, RestartReplace will fail if the user doesn't have admin privileges. We don't want to leak temporary files, so try to rename ourself to a non-random name. This way, future runs should just keep overwriting the same temp file. } DeleteOldTempFiles(PathExtractPath(SelfFilename)); NewFilename := RenameToNonRandomTempName(SelfFilename); if NewFilename <> '' then RestartReplace(False, NewFilename, '') else RestartReplace(False, SelfFilename, ''); end else RestartReplace(False, SelfFilename, ''); end; procedure RunRegSvr; var CreatedAsAdmin, NoErrorMessages: Boolean; Mutex: THandle; F: TTextFileReader; MsgFilename, ListFilename, L, RegFilename: String; begin if CompareText(NewParamStr(1), '/REG') = 0 then CreatedAsAdmin := True else if CompareText(NewParamStr(1), '/REGU') = 0 then CreatedAsAdmin := False else Exit; { Set default title; it's set again below after the messages are read } Application.Title := 'Setup'; { This is needed for D3+: Must force the application window visible since we aren't displaying any forms } ShowWindow(Application.Handle, SW_SHOW); InitializeCommonVars; { Try to create and acquire a mutex. In cases where multiple IS installers have each created their own RegSvr RunOnce entries in HKCU, Windows Explorer will execute them asynchronously. This could have undesirable ramifications -- what might happen if the same DLL were registered simultaneously by two RegSvr processes? Could the registry entries be in an incomplete/inconsistent state? I'm not sure, so a mutex is used here to ensure registrations are serialized. } Mutex := CreateMutex(nil, False, 'Inno-Setup-RegSvr-Mutex'); ShowWindow(Application.Handle, SW_HIDE); { hide taskbar button while waiting } if Mutex <> 0 then begin { Even though we have no visible windows, process messages while waiting so Windows doesn't think we're hung } repeat Application.ProcessMessages; until MsgWaitForMultipleObjects(1, Mutex, False, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0+1; end; ShowWindow(Application.Handle, SW_SHOW); try MsgFilename := PathChangeExt(NewParamStr(0), '.msg'); ListFilename := PathChangeExt(NewParamStr(0), '.lst'); { The .lst file may not exist at this point, if we were already run previously, but the RunOnce entry could not be removed due to lack of admin privileges. } if NewFileExists(ListFilename) then begin { Need to load messages in order to display exception messages below. Note: The .msg file only exists when the .lst file does. } LoadSetupMessages(MsgFilename, 0, True); SetMessageBoxRightToLeft(lfRightToLeft in MessagesLangOptions.Flags); Application.Title := SetupMessages[msgSetupAppTitle]; try { Extract the 64-bit helper } CreateTempInstallDir; F := TTextFileReader.Create(ListFilename, fdOpenExisting, faRead, fsRead); try while not F.Eof do begin L := F.ReadLine; if (Length(L) > 4) and (L[1] = '[') and (L[4] = ']') then begin RegFilename := Copy(L, 5, Maxint); NoErrorMessages := (L[3] = 'q') or (CreatedAsAdmin and not IsAdmin); try case L[2] of 's': RegisterServer(False, False, RegFilename, NoErrorMessages); 'S': RegisterServer(False, True, RegFilename, NoErrorMessages); 't': RegisterTypeLibrary(RegFilename); 'T': HelperRegisterTypeLibrary(False, RegFilename); end; except { Display the exception message (with a caption of 'Setup' so people have some clue of what generated it), and keep going. Exception: Don't display the message if the program was installed as an admin (causing the RunOnce entry to be created in HKLM) and the user isn't logged in as an admin now. That's almost certainly going to result in errors; let's not complain about it. The RunOnce entry should survive a logoff (since only admins can write to HKLM's RunOnce); once the user logs back in as an admin the files will get registered for real, and we won't suppress error messages then. } if not NoErrorMessages then AppMessageBox(PChar(RegFilename + SNewLine2 + FmtSetupMessage1(msgErrorRegisterServer, GetExceptMessage)), PChar(SetupMessages[msgSetupAppTitle]), MB_OK or MB_ICONEXCLAMATION); end; end; end; finally F.Free; end; finally RemoveTempInstallDir; end; end; DeleteFile(ListFilename); DeleteFile(MsgFilename); try DeleteSelf; except { ignore exceptions } end; finally if Mutex <> 0 then begin ReleaseMutex(Mutex); CloseHandle(Mutex); end; end; end; end.
{ CSI 1101-X, Winter 1999 } { Mark Sattolo, student# 428500 } program ExpressionEvaluate ; uses EqnTPU ; procedure Precedence(var Subeqn: stack; var Answer: element) ; var nums, ops : stack ; L, R, OP, X : element ; BEGIN create_stack(nums) ; create_stack(ops) ; while (Subeqn.size > 0) do BEGIN pull(X, Subeqn) ; if ((length(X) = 1) & ((X < '0') | (X > '9'))) then BEGIN {TESTING} writeln('X is an operator.'); while ((Ops.size > 0) & (Priority(top(ops)) >= Priority(X))) do BEGIN pull(R, nums) ; pull(L, nums) ; pull(OP, ops) ; push(Eval(L, R, OP[1]), nums) ; write('Eval-1 output is: '); write_stack(nums) ; { TESTING } END; { while } {TESTING} writeln('pushing X onto Ops.') ; push (X, ops) END { if } else push (X, nums) ; END; { while } while (Ops.size > 0) do BEGIN pull(R, nums) ; pull(L, nums) ; pull(OP, ops) ; push(Eval(L, R, OP[1]), nums); write('Eval-2 output is: '); write_stack(nums) ; { TESTING } END; { while } Answer := top(nums) ; destroy(nums) ; destroy(ops) ; END; { proc Precedence } procedure Brackets(var Eqn, Answer: element) ; var S, T: stack ; X, Mid : element ; BEGIN create_stack(S) ; create_stack(T) ; Mid := '' ; while (length(Eqn) > 0) do BEGIN get_X(Eqn, X) ; if ( X <> ')' ) then push (X, S) else BEGIN while ( top(S) <> '(' ) do BEGIN push (top(S), T) ; pop (S) END; { while } pop (S) ; Precedence (T, Mid) ; push (Mid, S) END { else } END; { while } while (S.size > 0) do BEGIN push(top(S), T) ; pop(S) END; { while } Precedence (T, Answer) ; destroy(S) ; destroy(T) END; { proc Brackets } procedure Equation; var eqn, Answer: element ; BEGIN writeln('Enter a numeric expression to be evaluated: '); writeln(' [ div = /, mult = *, power = ^, brackets = () ] ') ; readln(eqn) ; brackets(eqn, Answer) ; writeln('This equation evaluates to: ', Answer) END; { proc Equation } BEGIN { main program } identify_myself ; repeat mem_count := 0 ; Equation ; if ( mem_count <> 0 ) then writeln('Memory Leak! Dynamic memory allocated but not returned: ', mem_count:0) ; writeln('Do you wish to continue (y or n) ?') ; readln(continue) ; until continue in ['n', 'N'] ; writeln('PROGRAM ENDED.') END.
unit uMyThread; interface uses System.Classes, System.SysUtils, Vcl.ComCtrls; type TmyThread = class(TThread) private FIntervalo: Integer; FPosicaoAtual: Integer; FProgressBar: TProgressBar; procedure SetIntervalo(Value: Integer); procedure SetPosicaoAtual(Value: Integer); procedure SetProgressBar(ProgressBar: TProgressBar); protected public property Intervalo: Integer read FIntervalo write setIntervalo; property PosicaoAtual: Integer read FPosicaoAtual; procedure Execute; override; constructor Create(IntervaloExecucao: Integer; ProgressBar: TProgressBar); procedure Sincronizar; end; const LIMITE_CONTAGEM = 100; implementation { TmyThread } constructor TmyThread.Create(IntervaloExecucao: Integer; ProgressBar: TProgressBar); begin SetIntervalo(IntervaloExecucao); SetProgressBar(ProgressBar); FreeOnTerminate := True; inherited Create(True); end; procedure TmyThread.Execute; begin inherited; SetPosicaoAtual(0); repeat Sleep(FIntervalo); Inc(FPosicaoAtual); Self.Queue(Self.Sincronizar); until (FPosicaoAtual > LIMITE_CONTAGEM); end; procedure TmyThread.SetPosicaoAtual(Value: Integer); begin FPosicaoAtual := Value; end; procedure TmyThread.SetIntervalo(Value: Integer); begin if Value <= 0 then raise Exception.Create('TMyThread - O intervalo de execução deve ser maior que zero'); FIntervalo := Value; end; procedure TmyThread.SetProgressBar(ProgressBar: TProgressBar); begin FProgressBar := ProgressBar; end; procedure TmyThread.Sincronizar; begin FProgressBar.Position := FPosicaoAtual; end; end.
unit UGlobalTypes; interface uses Graphics; type TECellType = (ctWall, ctEmpty, ctAinable, ctBox, ctBoxPlace, ctHome); TRMove = record FromI, FormJ, ToI, ToJ: Integer; end; TAMoveList = array of TRMove; TCMap = class private FieldH, FieldW: Integer; Field: array of array of set of TECellType; public procedure SetFieldSize; procedure LoadMapFromFile(FileName: string); procedure CalculateMap; function DrawMap: TBitmap; function GenerateMoves: TAMoveList; function MakeMove(Move: TRMove): TCMap; var isSolved: Boolean; end; TRPosition = record PrevInd: Integer; map: TCMap; end; TCList = class Count: Integer; p: array of TRPosition; public procedure AddMap(Prev: Integer; map: TCMap); procedure Solve; end; implementation uses UColorImages; procedure TCMap.SetFieldSize; var i, j: Integer; begin SetLength(Self.Field, Self.FieldH + 2); for i := 0 to Self.FieldH + 1 do SetLength(Self.Field[i], Self.FieldW + 2); end; procedure TCMap.LoadMapFromFile(FileName: string); var f: TextFile; I: Integer; j: Integer; t: AnsiChar; begin AssignFile(f, FileName); Reset(f); Read(f, Self.FieldH); Readln(f, Self.FieldW); Self.SetFieldSize(); for I := 0 to Self.FieldH + 1 do for j := 0 to Self.FieldW + 1 do if (I < 1) or (I > FieldH) or (j < 1) or (j > FieldW) then Self.Field[I, j] := [ctWall] else Self.Field[I, j] := [ctEmpty]; while not Eof(f) do begin Read(f, I); Read(f, j); Read(f, t); Readln(f, t); case t of 'H': Field[I, j] := Field[I, j] + [ctHome]; 'I': Field[I, j] := Field[I, j] + [ctAinable]; 'W': Field[I, j] := Field[I, j] + [ctWall]; 'B': Field[I, j] := Field[I, j] + [ctBox]; 'P': Field[I, j] := Field[I, j] + [ctBoxPlace]; end; end; CloseFile(f); Self.isSolved := False; Self.CalculateMap; Self.GenerateMoves; end; procedure TCMap.CalculateMap; var fl: Boolean; i: Integer; j: Integer; t: set of TECellType; begin fl := True; t := [ctWall, ctBox, ctAinable]; while fl do begin fl := False; for i := 1 to FieldH do for j := 1 to FieldW do if ctAinable in Field[i, j] then begin if t * Field[i - 1, j] = [] then begin Field[i - 1, j] := Field[i - 1, j] + [ctAinable]; fl := True; end; if t * Field[i + 1, j] = [] then begin Field[i + 1, j] := Field[i + 1, j] + [ctAinable]; fl := True; end; if t * Field[i, j - 1] = [] then begin Field[i, j - 1] := Field[i, j - 1] + [ctAinable]; fl := True; end; if t * Field[i, j + 1] = [] then begin Field[i, j + 1] := Field[i, j + 1] + [ctAinable]; fl := True; end; end; end; end; function TCMap.DrawMap: TBitmap; var CI: UColorImages.TCColorImage; i: Integer; j: Integer; begin CI := TCColorImage.Create; CI.Height := FieldH; CI.Width := FieldW; for i := 1 to FieldH do for j := 1 to FieldW do if ctWall in Field[i, j] then CI.Pixels[i - 1, j - 1].FullColor := clBlack else if ctBox in Field[i, j] then CI.Pixels[i - 1, j - 1].FullColor := clWebBrown else if ctBoxPlace in Field[i, j] then CI.Pixels[i - 1, j - 1].FullColor := clWebSandyBrown else if ctHome in Field[i, j] then CI.Pixels[i - 1, j - 1].FullColor := clRed else if ctAinable in Field[i, j] then CI.Pixels[i - 1, j - 1].FullColor := clGreen else CI.Pixels[i - 1, j - 1].FullColor := clWhite; DrawMap := CI.SaveToBitMap; end; function TCMap.GenerateMoves; var m: TAMoveList; count: Integer; I: Integer; j: Integer; begin count := 0; for I := 1 to FieldH do for j := 1 to FieldW do if ctBox in Field[I, j] then begin if (ctAinable in Field[I - 1, j]) and ((Field[I + 1, j] * [ctBox, ctWall, ctHome]) = []) then begin count := count + 1; SetLength(m, count + 1); m[count].FromI := I; m[count].FormJ := j; m[count].ToI := I + 1; m[count].ToJ := j; end; if (ctAinable in Field[I + 1, j]) and ((Field[I - 1, j] * [ctBox, ctWall, ctHome]) = []) then begin count := count + 1; SetLength(m, count + 1); m[count].FromI := I; m[count].FormJ := j; m[count].ToI := I - 1; m[count].ToJ := j; end; if (ctAinable in Field[I, j - 1]) and ((Field[I, j + 1] * [ctBox, ctWall, ctHome]) = []) then begin count := count + 1; SetLength(m, count + 1); m[count].FromI := I; m[count].FormJ := j; m[count].ToI := I; m[count].ToJ := j + 1; end; if (ctAinable in Field[I, j + 1]) and ((Field[I, j - 1] * [ctBox, ctWall, ctHome]) = []) then begin count := count + 1; SetLength(m, count + 1); m[count].FromI := I; m[count].FormJ := j; m[count].ToI := I; m[count].ToJ := j - 1; end; end; GenerateMoves := m; end; function TCMap.MakeMove(Move: TRMove): TCMap; var nm: TCMap; i, j: Integer; begin nm := TCMap.Create; nm.FieldH := Self.FieldH; nm.FieldW := Self.FieldW; nm.SetFieldSize; for i := 0 to nm.FieldH + 1 do for j := 0 to nm.FieldW + 1 do nm.Field[i, j] := Self.Field[i, j] - [ctAinable]; nm.Field[Move.FromI, Move.FormJ] := nm.Field[Move.FromI, Move.FormJ] - [ctBox]; nm.Field[Move.ToI, Move.ToJ] := nm.Field[Move.ToI, Move.ToJ] + [ctBox]; nm.Field[Move.FromI, Move.FormJ] := nm.Field[Move.FromI, Move.FormJ] + [ctAinable]; nm.CalculateMap; if [ctBoxPlace] * nm.Field[Move.ToI, Move.ToJ] = [] then nm.isSolved := False else begin nm.isSolved := True; for i := 1 to Self.FieldH do for j := 1 to Self.FieldW do begin if (ctHome in nm.Field[i, j]) then if not (ctAinable in nm.Field[i, j]) then nm.isSolved := False; if ctBoxPlace in nm.Field[i, j] then if not (ctBox in nm.Field[i, j]) then nm.isSolved := False; end; end; MakeMove := nm; end; procedure TCList.AddMap(Prev: Integer; Map: TCMap); var NeedAdd: Boolean; fl: Boolean; q: Integer; i: Integer; j: Integer; begin NeedAdd := True; for q := 1 to count do begin fl := True; for i := 1 to Self.p[q].Map.FieldH do for j := 1 to Self.p[q].Map.FieldW do if Map.Field[i, j] <> Self.p[q].Map.Field[i, j] then fl := False; if fl then NeedAdd := False; end; if NeedAdd then begin Self.Count := Self.Count + 1; SetLength(Self.p, count + 1); Self.p[count].PrevInd := Prev; Self.p[count].Map := Map; end; end; procedure TCList.Solve; var p: Integer; m: TAMoveList; mInd: Integer; begin p := 1; while p <= Self.Count do begin if Self.p[p].map.isSolved then Break; m := Self.p[p].map.GenerateMoves; for mInd := 1 to Length(m) - 1 do Self.AddMap(p, Self.p[p].map.MakeMove(m[mInd])); p := p + 1; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpLimitedInputStream; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpBaseInputStream; type TLimitedInputStream = class abstract(TBaseInputStream) strict private var F_limit: Int32; strict protected var F_in: TStream; procedure SetParentEofDetect(&on: Boolean); public constructor Create(inStream: TStream; limit: Int32); function GetRemaining(): Int32; virtual; end; implementation uses // included here to avoid circular dependency :) ClpIndefiniteLengthInputStream; { TLimitedInputStream } constructor TLimitedInputStream.Create(inStream: TStream; limit: Int32); begin Inherited Create(); F_in := inStream; F_limit := limit; end; function TLimitedInputStream.GetRemaining: Int32; begin // TODO: maybe one day this can become more accurate Result := F_limit; end; procedure TLimitedInputStream.SetParentEofDetect(&on: Boolean); var indefiniteLengthInputStream: TIndefiniteLengthInputStream; begin if F_in is TIndefiniteLengthInputStream then begin indefiniteLengthInputStream := F_in as TIndefiniteLengthInputStream; indefiniteLengthInputStream.SetEofOn00(&on); end; end; end.
{ Exercicio 59: Um cinema possui capacidade de 100 lugares e está sempre com ocupação total. Certo dia, cada espectador respondeu a um questionário, no qual constava: sua idade e sua opinião em relação ao filme, segundo as seguintes notas: Nota Significado A Ótimo B Bom C Regular D Ruim E Péssimo Escreva um algoritmo que, lendo estes dados, calcule e exiba: a) a quantidade de respostas: "ótimo"; b) a diferença percentual entre respostas "bom" e "regular"; c) a média de idade das pessoas que responderam: "ruim"; d) a porcentagem de respostas: "péssimo" e a maior idade que utilizou esta opção; e) a diferença de idade entre a maior idade que respondeu: "ótimo" e a maior idade que respondeu: "ruim". } { Solução em Portugol Algoritmo Exercicio 59; Const publico_cinema = 100; Var otimo,bom,regular,ruim,pessimo,maior_idade_pessimo,maior_idade_otimo,maior_idade_ruim,contador,idade: inteiro; nota: caracter; soma_idade_ruim: real; Inicio exiba("Programa de avaliação do cinema."); otimo <- 0; bom <- 0; // Zerando os acumuladores. regular <- 0; ruim <- 0; pessimo <- 0; soma_idade_ruim <- 0; maior_idade_pessimo <- 0; maior_idade_otimo <- 0; maior_idade_ruim <- 0; para contador <- 1 até publico_cinema faça exiba("Digite uma nota para o filme: "); leia(nota); enquanto((nota <> 'A') e (nota <> 'B') e (nota <> 'C') e (nota <> 'D') e (nota <> 'E'))faça exiba('Digite uma nota entre A-E'); leia(nota); fimenquanto; exiba("Digite a sua idade: "); leia(idade); enquanto(idade <= 3)faça exiba('Digite uma idade válida: '); leia(idade); fimenquanto; caso(nota)de "A": Inicio otimo <- otimo + 1; se(idade > maior_idade_otimo) então maior_idade_otimo <- idade; fimse; Fim; "B": bom <- bom + 1; "C": regular <- regular + 1; "D": Inicio ruim <- ruim + 1; soma_idade_ruim <- soma_idade_ruim + idade; se(idade > maior_idade_ruim) então maior_idade_ruim <- idade; fimse; Fim; "E": Inicio pessimo <- pessimo + 1; se(idade > maior_idade_pessimo) então maior_idade_pessimo <- idade; fimse; Fim; fimcaso; fimpara; exiba("A quantidade de respostas Ótimo foi: ",otimo); // Questão (a) se(bom > regular) então exiba("A diferença de respostas Bom e Regular foi: ", bom - regular) // Questão (b) senão exiba("A diferença de respostas Bom e Regular foi: ", regular - bom); fimse; se(ruim <> 0) então exiba("A média da idade de quem respondeu Ruim é: ",soma_idade_ruim) // Questão (c) senão exiba("Ninguém respondeu ruim."); fimse; exiba("A porcentagem de respostas péssimo foi: ", pessimo, " e a pessoa mais velha que deu essa resposta foi: ",maior_idade_pessimo); // Questão (d) se(maior_idade_ruim > maior_idade_otimo) então exiba("A diferença de idade entre as pessoas mais velhas que responderam Ótimo e Ruim foi: ", maior_idade_ruim - maior_idade_otimo); // Questão (e) senão exiba("A diferença de idade entre as pessoas mais velhas que responderam Ótimo e Ruim foi: ", maior_idade_otimo - maior_idade_ruim); fimse; Fim. } // Solução em Pascal Program Exercicio59; uses crt; Const publico_cinema = 100; var otimo,bom,regular,ruim,pessimo,maior_idade_pessimo,maior_idade_otimo,maior_idade_ruim,contador,idade: integer; nota: char; soma_idade_ruim: real; begin clrscr; writeln('Programa de avaliação do cinema.'); otimo := 0; bom := 0; // Zerando os acumuladores. regular := 0; ruim := 0; pessimo := 0; soma_idade_ruim := 0; maior_idade_pessimo := 0; maior_idade_otimo := 0; maior_idade_ruim := 0; for contador := 1 to publico_cinema do Begin writeln('Digite uma nota para o filme: '); readln(nota); while((nota <> 'A') and (nota <> 'B') and (nota <> 'C') and (nota <> 'D') and (nota <> 'E'))do Begin writeln('Digite uma nota entre A-E'); readln(nota); End; writeln('Digite a sua idade: '); readln(idade); while(idade <= 3)do Begin writeln('Digite uma idade válida: '); readln(idade); End; case(nota)of 'A': Begin otimo := otimo + 1; if(idade > maior_idade_otimo) then maior_idade_otimo := idade; End; 'B': bom := bom + 1; 'C': regular := regular + 1; 'D': Begin ruim := ruim + 1; soma_idade_ruim := soma_idade_ruim + idade; if(idade > maior_idade_ruim) then maior_idade_ruim := idade; End; 'E': Begin pessimo := pessimo + 1; if(idade > maior_idade_pessimo) then maior_idade_pessimo := idade; End; End; End; writeln('A quantidade de respostas Ótimo foi: ',otimo); // Questão (a) if(bom > regular) then writeln('A diferença de respostas Bom e Regular foi: ', bom - regular) // Questão (b) else writeln('A diferença de respostas Bom e Regular foi: ', regular - bom); if(ruim <> 0) then writeln('A média da idade de quem respondeu Ruim é: ',(soma_idade_ruim/ruim):0:2) // Questão (c) else writeln('Ninguém respondeu ruim.'); writeln('A porcentagem de respostas péssimo foi: ', pessimo, ' e a pessoa mais velha que deu essa resposta foi: ',maior_idade_pessimo); // Questão (d) if(maior_idade_ruim > maior_idade_otimo) then writeln('A diferença de idade entre as pessoas mais velhas que responderam Ótimo e Ruim foi: ', maior_idade_ruim - maior_idade_otimo) // Questão (e) else writeln('A diferença de idade entre as pessoas mais velhas que responderam Ótimo e Ruim foi: ', maior_idade_otimo - maior_idade_ruim); repeat until keypressed; end.
unit ConsCheRec2013; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cons_2013, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxRibbonSkins, dxSkinsCore, dxSkinsDefaultPainters, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, dxSkinsdxBarPainter, cxLocalization, Datasnap.Provider, Datasnap.DBClient, System.Actions, Vcl.ActnList, JvAppStorage, JvAppIniStorage, JvComponentBase, JvFormPlacement, Vcl.ImgList, dxBar, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, dxStatusBar, dxRibbonStatusBar, dxRibbon, dxSkinsdxRibbonPainter, cxNavigator, Vcl.Menus, Vcl.DBActns; type TFConsCheRec2013 = class(TFCons_2013) vistaNUMERO: TcxGridDBColumn; vistaFECHAING: TcxGridDBColumn; vistaFECHADEP: TcxGridDBColumn; vistaNUMBCO: TcxGridDBColumn; vistaNUMCHE: TcxGridDBColumn; vistaIMPORTE: TcxGridDBColumn; vistaCLIENTE: TcxGridDBColumn; vistaLOCALIDAD: TcxGridDBColumn; vistaCODDEP: TcxGridDBColumn; vistaCODCTE: TcxGridDBColumn; vistaNUMCTE: TcxGridDBColumn; vistaFIRMANTE: TcxGridDBColumn; vistaCODIGO: TcxGridDBColumn; vistaCANCELADO: TcxGridDBColumn; vistaCODBAJA: TcxGridDBColumn; vistaCTEBAJA: TcxGridDBColumn; vistaNUMCTEBAJA: TcxGridDBColumn; vistaFECBAJA: TcxGridDBColumn; vistaENDOSO: TcxGridDBColumn; vistaNOMBAN: TcxGridDBColumn; vistaNOMBRE: TcxGridDBColumn; cdsNUMERO: TWideStringField; cdsFECHAING: TDateTimeField; cdsFECHADEP: TDateTimeField; cdsNUMBCO: TWideStringField; cdsNUMCHE: TWideStringField; cdsIMPORTE: TFloatField; cdsCLIENTE: TWideStringField; cdsLOCALIDAD: TWideStringField; cdsCODDEP: TWideStringField; cdsCODCTE: TWideStringField; cdsNUMCTE: TWideStringField; cdsFIRMANTE: TWideStringField; cdsCODIGO: TWideStringField; cdsCANCELADO: TWideStringField; cdsCODBAJA: TWideStringField; cdsCTEBAJA: TWideStringField; cdsNUMCTEBAJA: TWideStringField; cdsFECBAJA: TDateTimeField; cdsENDOSO: TWideStringField; cdsNOMBAN: TWideStringField; cdsNOMBRE: TWideStringField; cdsIMAGEN: TWideStringField; cdsRUTA: TStringField; private { Private declarations } public { Public declarations } constructor create( AOwner: TComponent; NoAbrir: boolean ); overload; end; var FConsCheRec2013: TFConsCheRec2013; implementation uses dmcons; {$R *.dfm} { TFConsCheRec2013 } constructor TFConsCheRec2013.create(AOwner: TComponent; NoAbrir: boolean); begin inherited create( AOwner ); Abrir_Auto := noAbrir; end; end.
unit kwPopEditorSetCursorByPoint; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorSetCursorByPoint.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_SetCursorByPoint // // editor:SetCursorByPoint // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses nevTools, evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes, l3Units ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} _Para2Point_Parent_ = _kwEditorFromStackWord_; {$Include w:\common\components\rtl\Garant\EditorUsers\Para2Point.imp.pas} TkwPopEditorSetCursorByPoint = class(_Para2Point_) {* editor:SetCursorByPoint } private // private fields f_Point : InevBasePoint; f_DeltaX : Integer; f_DeltaY : Integer; protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; protected // overridden protected methods function GetInnerPara(const aView: InevInputView; const aDocument: InevPara): InevPara; override; {* Возвращает параграф, относительно которого будет рассчитываться точка для выделения } function GetPoint(const aMap: InevMap): Tl3Point; override; {* Возвращает точку, на которую нужно спозиционироваться. } public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorSetCursorByPoint {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses nevGUIInterfaces, l3Base, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorSetCursorByPoint; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$Include w:\common\components\rtl\Garant\EditorUsers\Para2Point.imp.pas} // start class TkwPopEditorSetCursorByPoint procedure TkwPopEditorSetCursorByPoint.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4EA922390373_var* var l_Effect : TevMouseEffect; l_Keys : TevMouseState; l_l3Pt : Tl3Point; l_EditorHotSpot : IevHotSpot; //#UC END# *4F4CB81200CA_4EA922390373_var* begin //#UC START# *4F4CB81200CA_4EA922390373_impl* if aCtx.rEngine.IsTopInt then f_DeltaY := aCtx.rEngine.PopInt else RunnerAssert(False, 'Не задана дельта к координате Y.', aCtx); if aCtx.rEngine.IsTopInt then f_DeltaX := aCtx.rEngine.PopInt else RunnerAssert(False, 'Не задана дельта к координате X.', aCtx); f_Point := anEditor.Selection.Cursor; l_l3Pt := TranslatePara2Point(anEditor); l_EditorHotSpot := anEditor.HotSpotClass.Make(anEditor, nil); try l3FillChar(l_Effect, SizeOf(l_Effect), 0); l_Effect.rNeedAsyncLoop := True; l3FillChar(l_Keys, SizeOf(l_Keys), 0); l_Keys.rKeys := []; l_Keys.rInitialPoint := l_l3Pt; l_Keys.rPoint := l_l3Pt; l_EditorHotSpot.LButtonDown(anEditor.View, l_Keys, l_Effect); l_EditorHotSpot.LButtonUp(anEditor.View, l_Keys); finally l_EditorHotSpot := nil; end; //#UC END# *4F4CB81200CA_4EA922390373_impl* end;//TkwPopEditorSetCursorByPoint.DoWithEditor function TkwPopEditorSetCursorByPoint.GetInnerPara(const aView: InevInputView; const aDocument: InevPara): InevPara; //#UC START# *4BF4E6A00093_4EA922390373_var* //#UC END# *4BF4E6A00093_4EA922390373_var* begin //#UC START# *4BF4E6A00093_4EA922390373_impl* Result := f_Point.MostInner.Obj^.AsPara; f_Point := nil; //#UC END# *4BF4E6A00093_4EA922390373_impl* end;//TkwPopEditorSetCursorByPoint.GetInnerPara function TkwPopEditorSetCursorByPoint.GetPoint(const aMap: InevMap): Tl3Point; //#UC START# *4C3C927B027E_4EA922390373_var* //#UC END# *4C3C927B027E_4EA922390373_var* begin //#UC START# *4C3C927B027E_4EA922390373_impl* Result := l3Point(aMap.Bounds.Right - f_DeltaX, aMap.Bounds.Bottom - f_DeltaY); //#UC END# *4C3C927B027E_4EA922390373_impl* end;//TkwPopEditorSetCursorByPoint.GetPoint class function TkwPopEditorSetCursorByPoint.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:SetCursorByPoint'; end;//TkwPopEditorSetCursorByPoint.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit Impenlet; interface uses Windows, Messages, SysUtils, utiles; type Unidad = array[ 0..9 ] of string; Decena = array[ 0..9 ] of string; Deceuno = array[ 0..9 ] of string; Centena = array[ 0..9 ] of string; Miles = array[ 0..6 ] of string; const aUnidad : Unidad = ( '', 'un ', 'dos ', 'tres ', 'cuatro ', 'cinco ', 'seis ', 'siete ', 'ocho ', 'nueve ' ); aDecena : Decena = ( '', 'diez ', 'veinti', 'treinta y ', 'cuarenta y ', 'cincuenta y ', 'sesenta y ', 'setenta y ', 'ochenta y ', 'noventa y ' ); aDeceuno : Deceuno = ( 'diez ', 'once ', 'doce ', 'trece ', 'catorce ', 'quince ', 'dieciseis ', 'diecisiete ', 'dieciocho ', 'diecinueve ' ); aCentena : Centena = ( '', 'ciento ', 'doscientos ', 'trescientos ', 'cuatrocientos ', 'quinientos ', 'seiscientos ', 'setecientos ', 'ochocientos ', 'novecientos ' ); aMiles : Miles = ( '', 'mil ', 'millones ', 'mil millones ', 'billones ', 'mil billones ', 'trillones ' ); cVeinte = 'veinte '; function ImpEnLetras( nTotDebe :real ) :string; implementation function ImpEnLetras( nTotDebe :real ) :string; var nContador, nContGrupo, nCeroAcum :integer; nNro, nPosComa, nDigito, nDigDec :integer; cValor, cDecimales :string; cNumero: string; begin nCeroAcum := 0; nContGrupo := 0; nContador := 0; nDigDec := 0; cValor := FormatFloat( '###########0.00', nTotDebe ); nPosComa := Pos( Utiles.DecimalSeparator, cValor ); // modificado para emision de recibos // nPosComa := Pos( '.', cValor ); if nPosComa <> 0 then begin cDecimales := Copy( cValor, nPosComa + 1, 2 ); cNumero := 'con ' + cDecimales + '/100'; cValor := Copy( cValor, 1, nPosComa - 1 ); end else cNumero := '.'; nContGrupo := nContGrupo + 1; nNro := Length( cValor ); while nNro > 0 do begin Inc( nContador ); if nContador > 3 then begin nContador := 1; Inc( nContGrupo ); end; nDigito := StrToInt( Copy( cValor, nNro, 1 ) ); if nContador = 1 then begin if nDigito > 0 then begin nCeroAcum := 0; if nNro > 1 then begin nDigDec := StrToInt( Copy( cValor, nNro -1 , 1 ) ); if nDigDec = 1 then begin cNumero := aDeceUno[ nDigito ] + aMiles[ nContGrupo - 1 ] + cNumero; Dec( nNro ); Inc( nContador ); end; end; if ( ( nDigDec <> 1 ) or ( nNro = 1 ) ) and ( nContador = 1 ) then begin if nDigito = 1 then begin if nContGrupo = 1 then cNumero := 'uno ' + cNumero else if nContGrupo = 2 then cNumero := aUnidad[ nDigito ] + aMiles[ nContGrupo - 1] + cNumero else cNumero := aUnidad[ nDigito ]+ Copy( aMiles[ nContGrupo -1 ], 1, Length( aMiles[ nContGrupo -1 ] ) -3 )+ ' ' + cNumero; end else cNumero := aUnidad[ nDigito ] + aMiles[ nContGrupo -1 ] + cNumero; end; end else Inc( nCeroAcum ); end else if nContador = 2 then begin if nDigito > 0 then begin if nCeroAcum > 0 then begin if nDigito = 1 then cNumero := aDecena[ nDigito ] + aMiles[ nContGrupo -1 ] + cNumero else if nDigito = 2 then cNumero := cVeinte + aMiles[ nContGrupo -1 ] + cNumero else cNumero := Copy( aDecena[ nDigito ], 1, Length( aDecena[ nDigito ] ) -3 ) + ' ' + aMiles[ nContGrupo -1 ] + cNumero; end else cNumero := aDecena[ nDigito ] + cNumero; nCeroAcum := 0; end else Inc( nCeroAcum ); end else { nContador = 3 } begin if nDigito > 0 then begin if nCeroAcum >= 2 then begin if nDigito = 1 then cNumero := 'cien ' + aMiles[ nContGrupo -1 ] + cNumero else cNumero := aCentena[ nDigito ] + aMiles[ nContGrupo -1 ] + cNumero; end else cNumero := aCentena[ nDigito ] + cNumero; nCeroAcum := 0; end else Inc( nCeroAcum ); end; Dec( nNro ); { cNumero := aUnidad[ nDigito ] + cNumero; Dec( nNro ); } end; result := cNumero; end; end.
Unit TERRA_VCLApplication; {$I terra.inc} Interface Uses Classes, Forms, ExtCtrls, Graphics, TERRA_String, TERRA_Utils, TERRA_Application, TERRA_GraphicsManager, TERRA_Viewport, TERRA_Image, TERRA_Color, TERRA_OS, TERRA_Renderer; Type VCLCanvasViewport = Class(TERRAObject) Protected _Source:Viewport; _Target:TCanvas; Procedure Update(); Public Constructor Create(Source:Viewport; Target:TCanvas); Procedure Release; Override; End; VCLApplication = Class(Application) Protected _Timer:TTimer; _CurrentWidth:Integer; _CurrentHeight:Integer; _Target:TComponent; _Viewports:Array Of VCLCanvasViewport; _ViewportCount:Integer; Procedure TimerTick(Sender: TObject); Procedure UpdateSize(); Procedure UpdateViewports(); Function InitWindow:Boolean; Override; Procedure CloseWindow; Override; Public Constructor Create(Target:TComponent); Procedure Release; Override; Function GetWidth:Word; Override; Function GetHeight:Word; Override; Function GetTitle:TERRAString; Override; Procedure AddViewport(V:VCLCanvasViewport); End; Implementation { VCLApplication } Constructor VCLApplication.Create(Target:TComponent); Begin _Target := Target; _Timer := TTimer.Create(Target); _Timer.Interval := 15; _Timer.Enabled := True; _Timer.OnTimer := TimerTick; If (_Target Is TForm) Then _Handle := TForm(_Target).Handle Else If (_Target Is TPanel) Then _Handle := TPanel(_Target).Handle Else _Handle := 0; _Managed := True; Inherited Create(); End; Procedure VCLApplication.Release; Begin _Timer.Enabled := False; _Timer.Free(); Inherited; End; Procedure VCLApplication.TimerTick(Sender: TObject); Begin Self.UpdateSize(); Application.Instance.Run(); Self.UpdateViewports(); End; Procedure VCLApplication.UpdateSize; Begin If (_CurrentWidth<>Self.GetWidth()) Or (_CurrentHeight<>Self.GetHeight()) Then Begin _CurrentWidth := GetWidth(); _CurrentHeight := GetHeight(); Application.Instance.AddRectEvent(eventWindowResize, _CurrentWidth, _CurrentHeight, 0, 0); End; End; Procedure VCLApplication.AddViewport(V: VCLCanvasViewport); Begin Inc(_ViewportCount); SetLength(_Viewports, _ViewportCount); _Viewports[Pred(_ViewportCount)] := V; End; Procedure VCLApplication.UpdateViewports; Var I:Integer; Begin For I:=0 To Pred(_ViewportCount) Do _Viewports[I].Update(); End; Function VCLApplication.GetTitle: TERRAString; Begin If (_Target Is TForm) Then Result := TForm(_Target).Caption Else If (_Target Is TPanel) Then Result := TPanel(_Target).Caption Else Result := ''; End; Function VCLApplication.GetWidth: Word; Begin If (_Target Is TForm) Then Result := TForm(_Target).ClientWidth Else If (_Target Is TPanel) Then Result := TPanel(_Target).Width Else Result := 0; End; Function VCLApplication.GetHeight: Word; Begin If (_Target Is TForm) Then Result := TForm(_Target).ClientHeight Else If (_Target Is TPanel) Then Result := TPanel(_Target).Height Else Result := 0; End; Function VCLApplication.InitWindow: Boolean; Begin Result := True; End; Procedure VCLApplication.CloseWindow; Begin // do nothing End; { VCLCanvasViewport } Constructor VCLCanvasViewport.Create(Source:Viewport; Target: TCanvas); Begin Self._Source := Source; Self._Target := Target; End; Procedure VCLCanvasViewport.Release; Begin End; // this is slow!!!! just experimental test Procedure VCLCanvasViewport.Update; Var Temp:Image; I, J:Integer; C:Color; Begin Temp := Self._Source.GetRenderTarget(captureTargetColor).GetImage(); _Target.Lock(); For I:=0 To Pred(Temp.Width) Do For J:=0 To Pred(Temp.Height) Do Begin C := Temp.GetPixel(I, J); _Target.Pixels[I,J] := C.R + C.G Shl 8 + C.B Shl 16; End; _Target.Unlock(); ReleaseObject(Temp); End; End.
{&Use32-} Unit Inflate ; {adapted for e_wise ! } { This code is based on the following: "inflate.c -- Not copyrighted 1992 by Mark Adler" version c10p1, 10 January 1993 Written 1995 by Oliver Fromme <fromme@rz.tu-clausthal.de>. Donated to the public domain. Freely distributable, freely usable. Nobody may claim copyright on this code. Disclaimer: Use it at your own risk. I am not liable for anything. Note that this is not my usual programming style, because of the conversion from C to Pascal. Many things could have been implemented more efficient and in a more natural way if written from scratch in Pascal. Especially the handling of pointers and arrays is awful in C. *** VERY IMPORTANT NOTES: *** 1. This unit assumes that GetMem returns a NIL pointer if there is not enoug memory (no run-time error). This requires a user-defined HeapError function which always returns 1. 2. The application must allocate memory for the slide^[] array! Exactly WSIZE bytes have to be allocated. This is _not_ done by this unit, so the application has to care about that. 3. The application has to provide the InflateFlush function (interface section) which takes the first w bytes of the slide array as output of the inflate process. It returns an error code: 0 = no error, any other value causes inflate to stop and return the same code. 4. The application has to provide the InflateRead function which returns the next byte of the input stream which is fed into the inflate process. } {$A+,B-,I-,Q-,R-,S-,T-,V+,X+} {$D+,L+,Y+} {for debugging only} { The following text (and many of the comments) is from the original inflate code by Mark Adler. Inflate deflated (PKZIP's method 8 compressed) data. The compression method searches for as much of the current string of bytes (up to a length of 258) in the previous 32K bytes. If it doesn't find any matches (of at least length 3), it codes the next byte. Otherwise, it codes the length of the matched string and its distance backwards from the current position. There is a single Huffman code that codes both single bytes (called "literals") and match lengths. A second Huffman code codes the distance information, which follows a length code. Each length or distance code actually represents a base value and a number of "extra" (sometimes zero) bits to get to add to the base value. At the end of each deflated block is a special end-of-block (EOB) literal/ length code. The decoding process is basically: get a literal/length code; if EOB then done; if a literal, emit the decoded byte; if a length then get the distance and emit the referred-to bytes from the sliding window of previously emitted data. There are (currently) three kinds of inflate blocks: stored, fixed, and dynamic. The compressor outputs a chunk of data at a time, and decides which method to use on a chunk-by-chunk basis. A chunk might typically be 32K to 64K, uncompressed. If the chunk is uncompressible, then the "stored" method is used. In this case, the bytes are simply stored as is, eight bits per byte, with none of the above coding. The bytes are preceded by a count, since there is no longer an EOB code. If the data is compressible, then either the fixed or dynamic methods are used. In the dynamic method, the compressed data is preceded by an encoding of the literal/length and distance Huffman codes that are to be used to decode this block. The representation is itself Huffman coded, and so is preceded by a description of that code. These code descriptions take up a little space, and so for small blocks, there is a predefined set of codes, called the fixed codes. The fixed method is used if the block ends up smaller that way (usually for quite small chunks), otherwise the dynamic method is used. In the latter case, the codes are customized to the probabilities in the current block, and so can code it much better than the pre-determined fixed codes can. The Huffman codes themselves are decoded using a mutli-level table lookup, in order to maximize the speed of decoding plus the speed of building the decoding tables. See the comments below that precede the lbits and dbits tuning parameters. Notes beyond the 1.93a appnote.txt: 1. Distance pointers never point before the beginning of the output stream. 2. Distance pointers can point back across blocks, up to 32k away. 3. There is an implied maximum of 7 bits for the bit length table and 15 bits for the actual data. 4. If only one code exists, then it is encoded using one bit. (Zero would be more efficient, but perhaps a little confusing.) If two codes exist, they are coded using one bit each (0 and 1). 5. There is no way of sending zero distance codes--a dummy must be sent if there are none. (History: a pre 2.0 version of PKZIP would store blocks with no distance codes, but this was discovered to be too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one code of zero bits in length. 6. There are up to 286 literal/length codes. Code 256 represents the end-of-block. Note however that the static length tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since there is no length base or extra bits defined for them. Similarily, there are up to 30 distance codes. However, static trees define 32 codes (all 5 bits) to fill out the Huffman codes, but the last two had better not show up in the data. 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be complete (see #4). 8. The five bits following the block type is really the number of literal codes sent minus 257. 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits (1+6+6). Therefore, to output three times the length, you output three codes (1+1+1), whereas to output four times the same length, you only need two codes (1+3). Hmm. 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(i) is not zero. (Pretty obvious.) 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19) 12. Note: length code 284 can represent 227-258, but length code 285 really is 258. The last length deserves its own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the min match length) is 255. 13. The literal/length and distance code bit lengths are read as a single stream of lengths. It is possible (and advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths. } Interface Const WSIZE = $8000 ; {window size--must be a power of two, and at least 32K for zip's deflate} Type InflateWindow = Array [0..Pred(WSIZE)] Of Byte ; pInflateWindow = ^InflateWindow ; Var slide : pInflateWindow ; InflateFlush : Function (w : Word) : Integer ; InflateRead : Function : Byte ; GoBackInSource : Procedure(w : Word); End_of_Input : Function : Boolean; Function InflateRun : Integer ; Implementation { Huffman code lookup table entry--this entry is four bytes for machines that have 16-bit pointers (e.g. PC's in the small or medium model). Valid extra bits are 0..13. e == 15 is EOB (end of block), e == 16 means that v is a literal, 16 < e < 32 means that v is a pointer to the next table, which codes e - 16 bits, and lastly e == 99 indicates an unused code. If a code with e == 99 is looked up, this implies an error in the data. } Type pInteger = ^Integer ; pWord = ^Word ; phuft = ^huft ; huft = Record e : Byte ; {number of extra bits or operation} b : Byte ; {number of bits in this code or subcode} v : Record {this odd Record is just for easier Pas2C} Case Integer Of 0 : (n : Word) ; {literal, length base, or distance base} 1 : (t : phuft) {pointer to next level of table} End End ; pphuft = ^phuft ; { The inflate algorithm uses a sliding 32K byte window on the uncompressed stream to find repeated byte strings. This is implemented here as a circular buffer. The index is updated simply by incrementing and then and'ing with $7fff (32K-1). It is left to other modules to supply the 32K area. It is assumed to be usable as if it were declared "slide : ^Array [0..32767] Of Byte". } Var wp : Word ; {current position in slide} {Tables for deflate from PKZIP's appnote.txt.} Const border : Array [0..18] Of Word {Order of the bit length code lengths} = (16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15) ; cplens : Array [0..30] Of Word {Copy lengths for literal codes 257..285} = (3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31, 35,43,51,59,67,83,99,115,131,163,195,227,258,0,0) ; {note: see note #13 above about the 258 in this list.} cplext : Array [0..30] Of Word {Extra bits for literal codes 257..285} = (0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2, 3,3,3,3,4,4,4,4,5,5,5,5,0,99,99) ; {99=invalid} cpdist : Array [0..29] Of Word {Copy offsets for distance codes 0..29} = (1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145, 8193,12289,16385,24577) ; cpdext : Array [0..29] Of Word {Extra bits for distance codes} = (0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6, 7,7,8,8,9,9,10,10,11,11, 12,12,13,13) ; {NEXTBYTE -> InflateRead} Procedure NEEDBITS (Var b : LongInt ; Var k : Byte ; n : Byte) ; Begin While k<n Do Begin b := b Or (LongInt(InflateRead) Shl k) ; Inc (k,8) End End {NEEDBITS} ; Procedure DUMPBITS (Var b : LongInt ; Var k : Byte ; n : Byte) ; Begin b := b Shr n ; Dec (k,n) End {DUMPBITS} ; (* Macros for inflate() bit peeking and grabbing. #define NEXTBYTE (ReadByte(&bytebuf), bytebuf) #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE)<<k;k+=8;}} #define DUMPBITS(n) {b>>=(n);k-=(n);} The usage is: NEEDBITS(j) x = b & mask_bits[j]; DUMPBITS(j) where NEEDBITS makes sure that b has at least j bits in it, and DUMPBITS removes the bits from b. The macros use the variable k for the number of bits in b. Normally, b and k are register variables for speed, and are initialized at the begining of a routine that uses these macros from a global bit buffer and count. If we assume that EOB will be the longest code, then we will never ask for bits with NEEDBITS that are beyond the end of the stream. So, NEEDBITS should not read any more bytes than are needed to meet the request. Then no bytes need to be "returned" to the buffer at the end of the last block. However, this assumption is not true for fixed blocks--the EOB code is 7 bits, but the other literal/length codes can be 8 or 9 bits. (The EOB code is shorter than other codes becuase fixed blocks are generally short. So, while a block always has an EOB, many other literal/length codes have a significantly lower probability of showing up at all.) However, by making the first table have a lookup of seven bits, the EOB code will be found in that first lookup, and so will not require that too many bits be pulled from the stream. *) Var bb : LongInt ; {bit buffer, unsigned} bk : Byte ; {bits in bit buffer} { Huffman code decoding is performed using a multi-level table lookup. The fastest way to decode is to simply build a lookup table whose size is determined by the longest code. However, the time it takes to build this table can also be a factor if the data being decoded is not very long. The most common codes are necessarily the shortest codes, so those codes dominate the decoding time, and hence the speed. The idea is you can have a shorter table that decodes the shorter, more probable codes, and then point to subsidiary tables for the longer codes. The time it costs to decode the longer codes is then traded against the time it takes to make longer tables. This results of this trade are in the variables lbits and dbits below. lbits is the number of bits the first level table for literal/ length codes can decode in one step, and dbits is the same thing for the distance codes. Subsequent tables are also less than or equal to those sizes. These values may be adjusted either when all of the codes are shorter than that, in which case the longest code length in bits is used, or when the shortest code is *longer* than the requested table size, in which case the length of the shortest code in bits is used. There are two different values for the two tables, since they code a different number of possibilities each. The literal/length table codes 286 possible values, or in a flat code, a little over eight bits. The distance table codes 30 possible values, or a little less than five bits, flat. The optimum values for speed end up being about one bit more than those, so lbits is 8+1 and dbits is 5+1. The optimum values may differ though from machine to machine, and possibly even between compilers. Your mileage may vary. } Const lbits = 9 ; {bits in base literal/length lookup table} dbits = 6 ; {bits in base distance lookup table} {If BMAX needs to be larger than 16, then h and x[] should be LongInts.} Const BMAX = 16 ; {maximum bit length of any code (16 for explode)} N_MAX = 288 ; {maximum number of codes in any set} Var hufts : Word ; {track memory usage} { Free the malloc'ed tables built by huft_build, which makes a linked list of the tables it made, with the links in a dummy first entry of each table. } Procedure huft_free ( t : phuft {table to free} ) ; Var p,q : phuft ; {(register variables)} alloc_tmp : Word ; Begin {Go through linked list, freeing from the malloced (t[-1]) address.} p := t ; While p<>NIL Do BEgin Dec (p) ; q := p^.v.t ; Dec (Word(p),2) ; alloc_tmp := (pWord(p))^ ; FreeMem (p,alloc_tmp) ; p := q End End {huft_free} ; { Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Return zero on success, one if the given code set is incomplete (the tables are still built in this case), two if the input is invalid (all zero length codes or an oversubscribed set of lengths), and three if not enough memory. } Function huft_build ( b : pWord ; {code lengths in bits (all assumed <= BMAX)} n : Word ; {number of codes (assumed <= N_MAX)} s : Word ; {number of simple-valued codes (0..s-1)} d : pWord ; {list of base values for non-simple codes} e : pWord ; {list of extra bits for non-simple codes} t : pphuft ; {result: starting table} m : pInteger {maximum lookup bits, returns actual} ) : Integer ; Var a : Word ; {counter for codes of length k} c : Array [0..BMAX] Of Word ; {bit length count table} f : Word ; {i repeats in table every f entries} g : Integer ; {maximum code length} h : Integer ; {table level} i : Word ; {counter, current code (register variable)} j : Word ; {counter (register variable)} k : Integer ; {number of bits in current code (register variable)} l : Integer ; {bits per table (returned in m)} p : pWord ; {pointer into c[], b[], or v[] (register variable)} q : phuft ; {points to current table (register variable)} r : huft ; {table entry for structure assignment} u : Array [0..BMAX-1] Of phuft ;{table stack} v : Array [0..N_MAX-1] Of Word ;{values in order of bit length} w : Integer ; {bits before this table = (l*h) (register variable)} x : Array [0..BMAX] Of Word ; {bit offsets, then code stack} xp : pWord ; {pointer into x} y : Integer ; {number of dummy codes added} z : Word ; {number of entries in current table} alloc_tmp : Word ; phuft_tmp : phuft ; pword_tmp : pWord ; Begin {Generate counts for each bit length} FillChar (c,SizeOf(c),0) ; p := b ; i := n ; Repeat Inc (c[p^]) ; {assume all entries <= BMAX} Inc (p) ; Dec (i) Until i=0 ; If c[0]=n Then Begin {null input--all zero length codes} t^ := NIL ; m^ := 0 ; huft_build := 0 ; Exit End ; {Find minimum and maximum length, bound m^ by those} l := m^ ; For j:=1 To BMAX Do If c[j]<>0 Then Break ; k := j ; {minimum code length} If l<j Then l := j ; For i:=BMAX DownTo 1 Do If c[i]<>0 Then Break ; g := i ; {maximum code length} If l>i Then l := i ; m^:= l ; {Adjust last length count to fill out codes, if needed} y := 1 Shl j ; While j<i Do Begin Dec (y,c[j]) ; If y<0 Then Begin huft_build := 2 ; {bad input: more codes than bits} Exit End ; Inc (j) ; y := y Shl 1 End ; Dec (y,c[i]) ; If y<0 Then Begin huft_build := 2 ; {bad input: more codes than bits} Exit End ; Inc (c[i],y) ; {Generate starting offsets into the value table for each length} x[1] := 0 ; j := 0 ; p := Addr(c[1]) ; xp := Addr(x[2]) ; Dec (i) ; {note that i=g from above} While i<>0 Do Begin Inc (j,p^) ; Inc (p) ; xp^ := j ; Inc (xp) ; Dec (i) End ; {Make a table of values in order of bit lengths} p := b ; i := 0 ; Repeat j := p^ ; Inc (p) ; If j<>0 Then Begin v[x[j]] := i ; Inc (x[j]) End ; Inc (i) Until i>=n ; {Generate the Huffman codes and for each, make the table entries} x[0] := 0 ; {first Huffman code is zero} i := 0 ; p := Addr(v) ; {grab values in bit order} h := -1 ; {no tables yet--level -1} w := -l ; {bits decoded = (l*h)} u[0] := NIL ; {just to keep compilers happy} q := NIL ; {ditto} z := 0 ; {ditto} {go through the bit lengths (k already is bits in shortest code)} While k<=g Do Begin a := c[k] ; While (a<>0) Do Begin Dec (a) ; {here i is the Huffman code of length k bits for value *p} {make tables up to required level} While k>w+l Do Begin Inc (h) ; Inc (w,l) ; {previous table always l bits} {compute minimum size table less than or equal to l bits} If g-w>l Then {upper limit on table size} z := l Else z := g-w ; j := k-w ; {try a k-w bit table} f := 1 Shl j ; If f>a+1 Then Begin {too few codes for k-w bit table} Dec (f,a+1) ; {deduct codes from patterns left} xp := Addr(c[k]) ; Inc (j) ; While j<z Do Begin {try smaller tables up to z bits} f := f Shl 1 ; Inc (xp) ; If f<=xp^ Then Break ; {enough codes to use up j bits} Dec (f,xp^) ; {else deduct codes from patterns} Inc (j) End ; End ; z := 1 Shl j ; {table entries for j-bit table} {allocate and link in new table} alloc_tmp := 2+(z+1)*SizeOf(huft) ; GetMem (q,alloc_tmp) ; If q=NIL Then Begin If h<>0 Then huft_free (u[0]) ; huft_build := 3 ; {not enough memory} Exit End ; pWord(q)^ := alloc_tmp ; Inc (Word(q),2) ; Inc (hufts,z+1) ; {track memory usage} t^ := q ; Inc (t^) ; {link to list for huft_free()} t := Addr(q^.v.t) ; t^ := NIL ; Inc (q) ; u[h] := q ; {table starts after link} {connect to last table, if there is one} If h<>0 Then Begin x[h] := i ; {save pattern for backing up} r.b := l ; {bits to dump before this table} r.e := 16+j ; {bits in this table} r.v.t := q ; {pointer to this table} j := i Shr (w-l) ; {(get around Turbo C bug)} {u[h-1][j] := r} phuft_tmp := u[h-1] ; Inc (phuft_tmp,j) ; phuft_tmp^ := r {connect to last table} End ; End ; {set up table entry in r} r.b := k-w ; If LongInt(p)>=LongInt(@(v[n])) Then r.e := 99 {out of values--invalid code} Else If p^<s Then Begin If p^<256 Then {256 is end-of-block code} r.e := 16 Else r.e := 15 ; r.v.n := p^ ; {simple code is just the value} Inc (p) End Else Begin pword_tmp := e ; Inc (pword_tmp,p^-s) ; r.e := pword_tmp^ ; {non-simple--look up in lists} pword_tmp := d ; Inc (pword_tmp,p^-s) ; r.v.n := pword_tmp^ ; Inc (p) End ; {fill code-like entries with r} f := 1 Shl (k-w) ; j := i Shr w ; While j<z Do Begin phuft_tmp := q ; Inc (phuft_tmp,j) ; phuft_tmp^ := r ; Inc (j,f) End ; {backwards increment the k-bit code i} j := 1 Shl (k-1) ; While (i And j)<>0 Do Begin i := i XOr j ; j := j Shr 1 End ; i := i XOr j ; {backup over finished tables} While (i And (1 Shl w -1)) <> x[h] Do Begin Dec (h) ; {don't need to update q} Dec (w,l) End ; End ; Dec (a) ; Inc (k) End ; {Return 1 if we were given an incomplete table} If (y<>0) And (g<>1) Then huft_build := 1 Else huft_build := 0 End {huft_build} ; Const mask_bits : Array [0..16] Of Word = (0,1,3,7,15,31,63,127,255,511,1023, 2047,4095,8191,16383,32767,65535) ; { inflate (decompress) the codes in a deflated (compressed) block. Return an error code or zero if it all goes ok. } Function inflate_codes ( tl,td : phuft ; {literal/length and distance decoder tables} bl,bd : Integer {number of bits decoded by tl[] and td[]} ) : Integer ; Var e : Word ; {table entry flag/number of extra bits (register variable)} n,d : Word ; {length and index for copy} w : Word ; {current window position} t : phuft ; {pointer to table entry} ml,md : Word ; {masks for bl and bd bits} b : LongInt ; {bit buffer (unsigned, register variable)} k : Byte ; {number of bits in bit buffer (register variable)} i : Integer ; Begin {make local copies of globals} b := bb ; {initialize bit buffer} k := bk ; w := wp ; {initialize window position} {inflate the coded data} ml := mask_bits[bl] ; {precompute masks for speed} md := mask_bits[bd] ; While {VK::True}not End_of_Input Do Begin {do until end of block} NEEDBITS (b,k,bl) ; t := tl ; Inc (t,b And ml) ; e := t^.e ; If e>16 Then Repeat If e=99 Then Begin inflate_codes := 1 ; Exit End ; DUMPBITS (b,k,t^.b) ; Dec (e,16) ; NEEDBITS (b,k,e) ; t := t^.v.t ; Inc (t,b And mask_bits[e]) ; e := t^.e Until e<=16 ; DUMPBITS (b,k,t^.b) ; If e=16 Then Begin {it's a literal} slide^[w] := t^.v.n ; Inc (w) ; If w=WSIZE Then Begin i := InflateFlush(w) ; If i<>0 Then Begin inflate_codes := i ; Exit End ; w := 0 End End Else Begin {it's an EOB or a length} {exit if end of block} If e=15 Then Break ; {get length of block to copy} NEEDBITS (b,k,e) ; n := t^.v.n+(b And mask_bits[e]) ; DUMPBITS (b,k,e) ; {decode distance of block to copy} NEEDBITS (b,k,bd) ; t := td ; Inc (t,b And md) ; e := t^.e ; If e>16 Then Repeat If e=99 Then Begin inflate_codes := 1 ; Exit End ; DUMPBITS (b,k,t^.b) ; Dec (e,16) ; NEEDBITS (b,k,e) ; t := t^.v.t ; Inc (t,b And mask_bits[e]) ; e := t^.e Until e<=16 ; DUMPBITS (b,k,t^.b) ; NEEDBITS (b,k,e) ; d := w-t^.v.n-Word(b And mask_bits[e]) ; DUMPBITS (b,k,e) ; {do the copy} Repeat d := d And (WSIZE-1) ; If d>w Then e := WSIZE-d Else e := WSIZE-w ; If e>n Then e := n ; Dec (n,e) ; While e>0 Do Begin slide^[w] := slide^[d] ; Inc (w) ; Inc (d) ; Dec (e) End ; If w=WSIZE Then Begin i := InflateFlush(w) ; If i<>0 Then Begin inflate_codes := i ; Exit End ; w := 0 End Until n=0 ; End End ; {restore the globals from the locals} wp := w ; {restore global window pointer} bb := b ; {restore global bit buffer} bk := k ; {done} inflate_codes := 0 End {inflate_codes} ; { "decompress" an inflated type 0 (stored) block. } Function inflate_stored : Integer ; Var n : Word ; {number of bytes in block} w : Word ; {current window position} b : LongInt ; {bit buffer (unsigned, register variable)} k : Byte ; {number of bits in bit buffer (register variable)} i : Integer ; Begin {make local copies of globals} b := bb ; {initialize bit buffer} k := bk ; w := wp ; {initialize window position} {go to byte boundary} n := k And 7 ; DUMPBITS (b,k,n) ; {get the length and its complement} NEEDBITS (b,k,16) ; n := (b And $ffff) ; DUMPBITS (b,k,16) ; NEEDBITS (b,k,16) ; If n<>((Not b) And $ffff) Then Begin inflate_stored := 1 ; {error in compressed data} Exit End ; DUMPBITS (b,k,16) ; {read and output the compressed data} While n<>0 Do Begin Dec (n) ; NEEDBITS (b,k,8) ; slide^[w] := b ; Inc (w) ; If w=WSIZE Then Begin i := InflateFlush(w) ; If i<>0 Then Begin inflate_stored := i ; Exit End ; w := 0 End ; DUMPBITS (b,k,8) End ; {restore the globals from the locals} wp := w ; {restore global window pointer} bb := b ; {restore global bit buffer} bk := k ; inflate_stored := 0 End {inflate_stored} ; { decompress a deflated type 1 (fixed Huffman codes) block. We should either replace this with a custom decoder, or at least precompute the Huffman tables. } Function inflate_fixed : Integer ; Var i : Integer ; {temporary variable} tl : phuft ; {literal/length code table} td : phuft ; {distance code table} bl : Integer ; {lookup bits for tl} bd : Integer ; {lookup bits for td} l : Array [0..287] Of Word ; {length list for huft_build} Begin {set up literal table} For i:=0 To 143 Do l[i] := 8 ; For i:=144 To 255 Do l[i] := 9 ; For i:=256 To 279 Do l[i] := 7 ; For i:=280 To 287 Do {make a complete, but wrong code set} l[i] := 8 ; bl := 7 ; i := huft_build(@l,288,257,@cplens,@cplext,Addr(tl),Addr(bl)) ; If i<>0 Then Begin inflate_fixed := i ; Exit End ; {set up distance table} For i:=0 To 29 Do {make an incomplete code set} l[i] := 5 ; bd := 5 ; i := huft_build(@l,30,0,@cpdist,@cpdext,Addr(td),Addr(bd)) ; If i>1 Then Begin huft_free (tl) ; inflate_fixed := i ; Exit End ; {decompress until an end-of-block code} i := inflate_codes(tl,td,bl,bd) ; If i<>0 Then Begin inflate_fixed := i ; huft_free (tl) ; huft_free (td) ; Exit End ; {free the decoding tables, return} huft_free (tl) ; huft_free (td) ; inflate_fixed := 0 End {inflate_fixed} ; { decompress an inflated type 2 (dynamic Huffman codes) block. } Function inflate_dynamic : Integer ; Var i : Integer ; {temporary variables} j : Word ; l : Word ; {last length} m : Word ; {mask for bit lengths table} n : Word ; {number of lengths to get} tl : phuft ; {literal/length code table} td : phuft ; {distance code table} bl : Integer ; {lookup bits for tl} bd : Integer ; {lookup bits for td} nb : Word ; {number of bit length codes} nl : Word ; {number of literal/length codes} nd : Word ; {number of distance codes} ll : Array [0..286+30-1] Of Word ; {literal/length and distance code lengths} b : LongInt ; {bit buffer (unsigned, register variable)} k : Byte ; {number of bits in bit buffer (register variable)} Begin {make local bit buffer} b := bb ; k := bk ; {read in table lengths} NEEDBITS (b,k,5) ; nl := 257+(b And $1f) ; {number of literal/length codes} DUMPBITS (b,k,5) ; NEEDBITS (b,k,5) ; nd := 1+(b And $1f) ; {number of distance codes} DUMPBITS (b,k,5) ; NEEDBITS (b,k,4) ; nb := 4+(b And $f) ; {number of bit length codes} DUMPBITS (b,k,4) ; If (nl>286) Or (nd>30) Then Begin inflate_dynamic := 1 ; {bad lengths} Exit End ; {read in bit-length-code lengths} For j:=0 To nb-1 Do Begin NEEDBITS (b,k,3) ; ll[border[j]] := b And 7 ; DUMPBITS (b,k,3) End ; For j:=nb To 18 Do ll[border[j]] := 0 ; {build decoding table for trees--single level, 7 bit lookup} bl := 7 ; i := huft_build(@ll,19,19,NIL,NIL,Addr(tl),Addr(bl)) ; If i<>0 Then Begin If i=1 Then huft_free (tl) ; inflate_dynamic := i ; {incomplete code set} Exit End ; {read in literal and distance code lengths} n := nl+nd ; m := mask_bits[bl] ; l := 0 ; i := 0 ; While i<n Do Begin NEEDBITS (b,k,bl) ; td := tl ; Inc (td,b And m) ; j := td^.b ; DUMPBITS (b,k,j) ; j := td^.v.n ; If j<16 Then Begin {length of code in bits (0..15)} l := j ; {save last length in l} ll[i] := j ; Inc (i) End Else If j=16 Then Begin {repeat last length 3 to 6 times} NEEDBITS (b,k,2) ; j := 3+(b And 3) ; DUMPBITS (b,k,2) ; If i+j>n Then Begin inflate_dynamic := 1 ; Exit End ; While j<>0 Do Begin Dec (j) ; ll[i] := l ; Inc (i) End ; Dec (j) End Else If j=17 Then Begin {3 to 10 zero length codes} NEEDBITS (b,k,3) ; j := 3+(b And 7) ; DUMPBITS (b,k,3) ; If i+j>n Then Begin inflate_dynamic := 1 ; Exit End ; While j<>0 Do Begin Dec (j) ; ll[i] := 0 ; Inc (i) End ; Dec (j) ; l := 0 End Else Begin {j=18: 11 to 138 zero length codes} NEEDBITS (b,k,7) ; j := 11+(b And $7f) ; DUMPBITS (b,k,7) ; If i+j>n Then Begin inflate_dynamic := 1 ; Exit End ; While j<>0 Do Begin Dec (j) ; ll[i] := 0 ; Inc (i) End ; Dec (j) ; l := 0 End End ; {free decoding table for trees} huft_free (tl) ; {restore the global bit buffer} bb := b ; bk := k ; {build the decoding tables for literal/length and distance codes} bl := lbits ; i := huft_build(@ll,nl,257,@cplens,@cplext,Addr(tl),Addr(bl)) ; If i<>0 Then Begin if i=1 Then huft_free (tl) ; inflate_dynamic := i ; {incomplete code set} Exit End ; bd := dbits ; i := huft_build(@(ll[nl]),nd,0,@cpdist,@cpdext,Addr(td),Addr(bd)) ; If i<>0 Then Begin if i=1 Then huft_free (td) ; huft_free (tl) ; inflate_dynamic := i ; {incomplete code set} Exit End ; {decompress until an end-of-block code} i := inflate_codes(tl,td,bl,bd) ; If i<>0 Then Begin inflate_dynamic := i ; huft_free (tl) ; huft_free (td) ; Exit End ; {free the decoding tables, return} huft_free (tl) ; huft_free (td) ; inflate_dynamic := 0 End {inflate_dynamic} ; { decompress an inflated block } Function inflate_block ( e : pInteger {last block flag} ) : Integer ; Var t : Word ; {block type} b : LongInt ; {bit buffer (unsigned, register variable)} k : Byte ; {number of bits in bit buffer (register variable)} Begin {make local bit buffer} b := bb ; k := bk ; {read in last block bit} NEEDBITS (b,k,1) ; e^ := b And 1 ; DUMPBITS (b,k,1) ; {read in block type} NEEDBITS (b,k,2) ; t := b And 3 ; DUMPBITS (b,k,2) ; {restore the global bit buffer} bb := b ; bk := k ; {inflate that block type} Case t Of 2 : inflate_block := inflate_dynamic ; 0 : inflate_block := inflate_stored ; 1 : inflate_block := inflate_fixed Else inflate_block := 2 {bad block type} End End {inflate_block} ; { decompress an inflated entry } Function InflateRun : Integer ; Var e : Integer ; {last block flag} r : Integer ; {result code} h : Word ; {maximum struct huft's malloc'ed} Begin {initialize window, bit buffer} wp := 0 ; bk := 0 ; bb := 0 ; {decompress until the last block} h := 0 ; Repeat hufts := 0 ; r := inflate_block(Addr(e)) ; if r<>0 Then Begin InflateRun := r ; Exit End ; If hufts>h Then h := hufts Until e<>0 ; {flush out slide, return error code} InflateRun := InflateFlush(wp); if bk>=8 then GoBackInSource(bk shr 3); End {InflateRun} ; Begin slide := NIL End.
unit signup; interface uses system.json, http_intf, controller_intf, http_helpers, add_account, email_validator_intf, missing_param_error; type TSignupController = class(TInterfacedObject, IController) FEmailValidator: IEmailValidator; FAddAccount: IAddAccount; function handle(const httpRequest: IHttpRequest): IHttpResponse; constructor Create(AEmailValidator: IEmailValidator; AAddAccount: IAddAccount); end; implementation uses system.SysUtils, account, invalid_param_error; constructor TSignupController.Create(AEmailValidator: IEmailValidator; AAddAccount: IAddAccount); begin FEmailValidator := AEmailValidator; FAddAccount := AAddAccount; end; function TSignupController.handle(const httpRequest: IHttpRequest): IHttpResponse; var lAccountModel: IAccountModel; lAddAccountModel: IAddAccountModel; lField: String; isEmailValid: Boolean; lBody: TJSONObject; lName, lEmail, lPassword, lPasswordConfirmation: String; const requiredFields: TArray<String> = ['name', 'email', 'password', 'passwordConfirmation']; begin lBody := httpRequest.body; try for lField in requiredFields do begin if not(Assigned(lBody.GetValue(lField))) then begin result := badRequest(TMissingParamError.New(lField).body); exit; end; end; lName := lBody.GetValue('name').Value; lEmail := lBody.GetValue('email').Value; lPassword := lBody.GetValue('password').Value; lPasswordConfirmation := lBody.GetValue('passwordConfirmation').Value; if not(lPassword.Equals(lPasswordConfirmation)) then begin result := badRequest(TInvalidParamError.New('passwordConfirmation').body); exit; end; isEmailValid := FEmailValidator.isValid(lEmail); if not(isEmailValid) then begin result := badRequest(TInvalidParamError.New('email').body); exit; end; lAddAccountModel := TAddAccountModel.New // .name(lName) // .email(lEmail) // .password(lPassword); lAccountModel := FAddAccount.add(lAddAccountModel); result := ok(TJSONObject.Create // .AddPair('id', lAccountModel.id) // .AddPair('name', lAccountModel.name) // .AddPair('email', lAccountModel.email) // .AddPair('password', lAccountModel.password)); except result := serverError; end; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, {$IF CompilerVersion > 32} System.Permissions, {$ENDIF} Androidapi.JNI.JavaTypes, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdActns, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.ScrollBox, FMX.Memo; type TForm1 = class(TForm) Button1: TButton; Layout1: TLayout; Image1: TImage; Memo1: TMemo; procedure Button1Click(Sender: TObject); private FFileName: JString; procedure GetEXIF(const AFileName: JString); procedure ResultNotificationMessageHandler(const Sender: TObject; const M: TMessage); procedure TakePhoto; {$IF CompilerVersion > 32} procedure TakePhotoPermissionsResultHandler(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); {$ENDIF} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} uses System.IOUtils, Androidapi.Helpers, Androidapi.JNI.Media, Androidapi.JNIBridge, Androidapi.JNI.Provider, Androidapi.JNI.App, Androidapi.JNI.Os, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Net, FMX.Platform.Android, DW.Androidapi.JNI.Os, DW.Consts.Android; {$IF CompilerVersion > 32} type TGrantResults = TArray<TPermissionStatus>; TGrantResultsHelper = record helper for TGrantResults public function AreAllGranted: Boolean; end; { TGrantResultsHelper } function TGrantResultsHelper.AreAllGranted: Boolean; var LStatus: TPermissionStatus; begin for LStatus in Self do begin if LStatus <> TPermissionStatus.Granted then Exit(False); // <====== end; Result := True; end; {$ENDIF} { TForm1 } constructor TForm1.Create(AOwner: TComponent); begin inherited; TMessageManager.DefaultManager.SubscribeToMessage(TMessageResultNotification, ResultNotificationMessageHandler); end; destructor TForm1.Destroy; begin TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification, ResultNotificationMessageHandler); inherited; end; procedure TForm1.GetEXIF(const AFileName: JString); var LEXIF: JExifInterface; LLatLong: TJavaArray<Single>; LStream: JFileInputStream; begin LEXIF := TJExifInterface.JavaClass.init(AFileName); Memo1.Lines.Add('Date Taken: ' + JStringToString(LEXIF.getAttribute(TJExifInterface.JavaClass.TAG_DATETIME))); Memo1.Lines.Add('Camera Make: ' + JStringToString(LEXIF.getAttribute(TJExifInterface.JavaClass.TAG_MAKE))); Memo1.Lines.Add('Camera Model: ' + JStringToString(LEXIF.getAttribute(TJExifInterface.JavaClass.TAG_MODEL))); LLatLong := TJavaArray<Single>.Create(2); try if LEXIF.getLatLong(LLatLong) then begin Memo1.Lines.Add('Latitude: ' + LLatLong.Items[0].ToString); Memo1.Lines.Add('Longitude: ' + LLatLong.Items[1].ToString); end else Memo1.Lines.Add('Unable to obtain location info'); finally LLatLong.Free; end; end; procedure TForm1.ResultNotificationMessageHandler(const Sender: TObject; const M: TMessage); var LMessage: TMessageResultNotification; begin if M is TMessageResultNotification then begin LMessage := TMessageResultNotification(M); if LMessage.RequestCode = 1001 then begin GetEXIF(FFileName); Image1.Bitmap.LoadFromFile(JStringToString(FFileName)); end; end; end; procedure TForm1.TakePhotoPermissionsResultHandler(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>); begin if TGrantResults(AGrantResults).AreAllGranted then TakePhoto else ShowMessage('Not all photo permissions granted!'); end; procedure TForm1.Button1Click(Sender: TObject); begin {$IF CompilerVersion > 32} TPermissionsService.DefaultService.RequestPermissions([cPermissionReadExternalStorage, cPermissionWriteExternalStorage, cPermissionCamera, cPermissionAccessCoarseLocation, cPermissionAccessFineLocation], TakePhotoPermissionsResultHandler); {$ELSE} TakePhoto; {$ENDIF} end; // Based on: https://developer.android.com/training/camera/photobasics#java procedure TForm1.TakePhoto; var LIntent: JIntent; LFile, LDir: JFile; LUri: Jnet_Uri; LFileName: string; begin LIntent := TJIntent.JavaClass.init(TJMediaStore.JavaClass.ACTION_IMAGE_CAPTURE); if LIntent.resolveActivity(TAndroidHelper.Context.getPackageManager) <> nil then begin LFileName := Format('JPEG_%s', [FormatDateTime('yyyymmdd_hhnnss', Now)]); LDir := TAndroidHelper.Context.getExternalFilesDir(TJEnvironment.JavaClass.DIRECTORY_PICTURES); LFile := TJFile.JavaClass.createTempFile(StringToJString(LFileName), StringToJString('.jpg'), LDir); FFileName := LFile.getAbsolutePath; {$IF CompilerVersion > 32} LUri := TAndroidHelper.JFileToJURI(LFile); {$ELSE} LUri := TJnet_Uri.JavaClass.fromFile(TJFile.JavaClass.init(FFileName)); {$ENDIF} LIntent.putExtra(TJMediaStore.JavaClass.EXTRA_OUTPUT, TJParcelable.Wrap((LUri as ILocalObject).GetObjectID)); MainActivity.startActivityForResult(LIntent, 1001); end else ShowMessage('Cannot take a photo!'); end; end.
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient, REST.Backend.PushTypes, System.JSON, REST.Backend.KinveyPushDevice, System.PushNotification, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.PushDevice, REST.Backend.KinveyProvider; type TForm1 = class(TForm) KinveyProvider1: TKinveyProvider; PushEvents1: TPushEvents; Memo1: TMemo; procedure PushEvents1DeviceRegistered(Sender: TObject); procedure PushEvents1DeviceTokenReceived(Sender: TObject); procedure PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.PushEvents1DeviceRegistered(Sender: TObject); begin Memo1.Lines.Add('Device Registered'); Memo1.Lines.Add(''); end; procedure TForm1.PushEvents1DeviceTokenReceived(Sender: TObject); begin Memo1.Lines.Add('Device Token Received'); Memo1.Lines.Add(''); end; procedure TForm1.PushEvents1DeviceTokenRequestFailed(Sender: TObject; const AErrorMessage: string); begin Memo1.Lines.Add('Device Token Request Failed'); Memo1.Lines.Add(''); end; procedure TForm1.PushEvents1PushReceived(Sender: TObject; const AData: TPushData); begin Memo1.Lines.Add('Message: ' + AData.Message); Memo1.Lines.Add(''); end; end.
unit Androidapi.JNI.baidu.location; // ==================================================== // Android Baidu Map SDK interface // Package:com.baidu.location // author:Xubzhlin // email:371889755@qq.com // // date:2017.5.10 // version:4.3.0 // ==================================================== interface uses Androidapi.JNIBridge, Androidapi.JNI.Os, Androidapi.JNI.location, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes; type // ===== Forward declarations ===== JAddress_Builder = interface; // com.baidu.location.Address$Builder JAddress = interface; // com.baidu.location.Address JBDLocation = interface; // com.baidu.location.BDLocation JBDLocationListener = interface; // com.baidu.location.BDLocationListener JJni = interface; // com.baidu.location.Jni JLLSInterface = interface; // com.baidu.location.LLSInterface JLocationClient = interface; // com.baidu.location.LocationClient JLocationClientOption_LocationMode = interface; // com.baidu.location.LocationClientOption$LocationMode JLocationClientOption = interface; // com.baidu.location.LocationClientOption JPoi = interface; // com.baidu.location.Poi // ===== Interface declarations ===== JAddress_BuilderClass = interface(JObjectClass) ['{18C38796-BD09-457B-ABD4-DC4468D4974F}'] { static Property Methods } { static Methods } { class } function init: JAddress_Builder; cdecl; // ()V { static Property } end; [JavaSignature('com/baidu/location/Address$Builder')] JAddress_Builder = interface(JObject) ['{70B013EA-D424-4F39-BBFD-3B06CDFF963C}'] { Property Methods } { methods } function country(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function countryCode(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function province(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function city(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function cityCode(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function district(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function street(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function streetNumber(P1: JString): JAddress_Builder; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/Address$Builder; function build: JAddress; cdecl; // ()Lcom/baidu/location/Address; { Property } end; TJAddress_Builder = class(TJavaGenericImport<JAddress_BuilderClass, JAddress_Builder>) end; JAddressClass = interface(JObjectClass) ['{E5847AB4-6C7B-4DDE-8238-FA00711FAF12}'] { static Property Methods } { static Methods } { static Property } end; [JavaSignature('com/baidu/location/Address')] JAddress = interface(JObject) ['{2F81FF92-5423-47E3-A267-3E932816D510}'] { Property Methods } function _Getcountry: JString; // Ljava/lang/String; procedure _Setcountry(acountry: JString); // (Ljava/lang/String;)V function _GetcountryCode: JString; // Ljava/lang/String; procedure _SetcountryCode(acountryCode: JString); // (Ljava/lang/String;)V function _Getprovince: JString; // Ljava/lang/String; procedure _Setprovince(aprovince: JString); // (Ljava/lang/String;)V function _Getcity: JString; // Ljava/lang/String; procedure _Setcity(acity: JString); // (Ljava/lang/String;)V function _GetcityCode: JString; // Ljava/lang/String; procedure _SetcityCode(acityCode: JString); // (Ljava/lang/String;)V function _Getdistrict: JString; // Ljava/lang/String; procedure _Setdistrict(adistrict: JString); // (Ljava/lang/String;)V function _Getstreet: JString; // Ljava/lang/String; procedure _Setstreet(astreet: JString); // (Ljava/lang/String;)V function _GetstreetNumber: JString; // Ljava/lang/String; procedure _SetstreetNumber(astreetNumber: JString); // (Ljava/lang/String;)V function _Getaddress: JString; // Ljava/lang/String; procedure _Setaddress(aaddress: JString); // (Ljava/lang/String;)V { methods } { Property } property country: JString read _Getcountry write _Setcountry; property countryCode: JString read _GetcountryCode write _SetcountryCode; property province: JString read _Getprovince write _Setprovince; property city: JString read _Getcity write _Setcity; property cityCode: JString read _GetcityCode write _SetcityCode; property district: JString read _Getdistrict write _Setdistrict; property street: JString read _Getstreet write _Setstreet; property streetNumber: JString read _GetstreetNumber write _SetstreetNumber; property address: JString read _Getaddress write _Setaddress; end; TJAddress = class(TJavaGenericImport<JAddressClass, JAddress>) end; JBDLocationClass = interface(JObjectClass) ['{F71DE0A4-CE6E-4662-B884-6507D3ABF8F5}'] { static Property Methods } { class } function _GetTypeNone: Integer; // I { class } function _GetTypeGpsLocation: Integer; // I { class } function _GetTypeCriteriaException: Integer; // I { class } function _GetTypeNetWorkException: Integer; // I { class } function _GetTypeOffLineLocation: Integer; // I { class } function _GetTypeOffLineLocationFail: Integer; // I { class } function _GetTypeOffLineLocationNetworkFail: Integer; // I { class } function _GetTypeNetWorkLocation: Integer; // I { class } function _GetTypeCacheLocation: Integer; // I { class } function _GetTypeServerError: Integer; // I { class } function _GetTypeServerDecryptError: Integer; // I { class } function _GetTypeServerCheckKeyError: Integer; // I { class } function _GetLOCATION_WHERE_UNKNOW: Integer; // I { class } function _GetLOCATION_WHERE_IN_CN: Integer; // I { class } function _GetLOCATION_WHERE_OUT_CN: Integer; // I { class } function _GetUSER_INDOOR_UNKNOW: Integer; // I { class } function _GetUSER_INDDOR_TRUE: Integer; // I { class } function _GetUSER_INDOOR_FALSE: Integer; // I { class } function _GetINDOOR_LOCATION_NEARBY_SURPPORT_TRUE: Integer; // I { class } function _GetINDOOR_LOCATION_SURPPORT_TRUE: Integer; // I { class } function _GetINDOOR_LOCATION_SURPPORT_FALSE: Integer; // I { class } function _GetINDOOR_LOCATION_SOURCE_UNKNOWN: Integer; // I { class } function _GetINDOOR_LOCATION_SOURCE_WIFI: Integer; // I { class } function _GetINDOOR_LOCATION_SOURCE_MAGNETIC: Integer; // I { class } function _GetINDOOR_LOCATION_SOURCE_BLUETOOTH: Integer; // I { class } function _GetINDOOR_LOCATION_SOURCE_SMALLCELLSTATION: Integer; // I { class } function _GetINDOOR_NETWORK_STATE_HIGH: Integer; // I { class } function _GetINDOOR_NETWORK_STATE_MIDDLE: Integer; // I { class } function _GetINDOOR_NETWORK_STATE_LOW: Integer; // I { class } function _GetOPERATORS_TYPE_UNKONW: Integer; // I { class } function _GetOPERATORS_TYPE_MOBILE: Integer; // I { class } function _GetOPERATORS_TYPE_UNICOM: Integer; // I { class } function _GetOPERATORS_TYPE_TELECOMU: Integer; // I { class } function _GetGPS_ACCURACY_GOOD: Integer; // I { class } function _GetGPS_ACCURACY_MID: Integer; // I { class } function _GetGPS_ACCURACY_BAD: Integer; // I { class } function _GetGPS_ACCURACY_UNKNOWN: Integer; // I { class } function _GetBDLOCATION_GCJ02_TO_BD09: JString; // Ljava/lang/String; { class } function _GetBDLOCATION_GCJ02_TO_BD09LL: JString; // Ljava/lang/String; { class } function _GetBDLOCATION_BD09_TO_GCJ02: JString; // Ljava/lang/String; { class } function _GetBDLOCATION_BD09LL_TO_GCJ02: JString; // Ljava/lang/String; { class } function _GetBDLOCATION_WGS84_TO_GCJ02: JString; // Ljava/lang/String; { class } function _GetCREATOR: JParcelable_Creator; // Landroid/os/Parcelable$Creator; { static Methods } { class } function init: JBDLocation; cdecl; overload; // ()V { class } function init(P1: JBDLocation): JBDLocation; cdecl; overload; // (Lcom/baidu/location/BDLocation;)V { class } function init(P1: JString): JBDLocation; cdecl; overload; // (Ljava/lang/String;)V { static Property } { class } property TypeNone: Integer read _GetTypeNone; { class } property TypeGpsLocation: Integer read _GetTypeGpsLocation; { class } property TypeCriteriaException: Integer read _GetTypeCriteriaException; { class } property TypeNetWorkException: Integer read _GetTypeNetWorkException; { class } property TypeOffLineLocation: Integer read _GetTypeOffLineLocation; { class } property TypeOffLineLocationFail: Integer read _GetTypeOffLineLocationFail; { class } property TypeOffLineLocationNetworkFail: Integer read _GetTypeOffLineLocationNetworkFail; { class } property TypeNetWorkLocation: Integer read _GetTypeNetWorkLocation; { class } property TypeCacheLocation: Integer read _GetTypeCacheLocation; { class } property TypeServerError: Integer read _GetTypeServerError; { class } property TypeServerDecryptError: Integer read _GetTypeServerDecryptError; { class } property TypeServerCheckKeyError: Integer read _GetTypeServerCheckKeyError; { class } property LOCATION_WHERE_UNKNOW: Integer read _GetLOCATION_WHERE_UNKNOW; { class } property LOCATION_WHERE_IN_CN: Integer read _GetLOCATION_WHERE_IN_CN; { class } property LOCATION_WHERE_OUT_CN: Integer read _GetLOCATION_WHERE_OUT_CN; { class } property USER_INDOOR_UNKNOW: Integer read _GetUSER_INDOOR_UNKNOW; { class } property USER_INDDOR_TRUE: Integer read _GetUSER_INDDOR_TRUE; { class } property USER_INDOOR_FALSE: Integer read _GetUSER_INDOOR_FALSE; { class } property INDOOR_LOCATION_NEARBY_SURPPORT_TRUE: Integer read _GetINDOOR_LOCATION_NEARBY_SURPPORT_TRUE; { class } property INDOOR_LOCATION_SURPPORT_TRUE: Integer read _GetINDOOR_LOCATION_SURPPORT_TRUE; { class } property INDOOR_LOCATION_SURPPORT_FALSE: Integer read _GetINDOOR_LOCATION_SURPPORT_FALSE; { class } property INDOOR_LOCATION_SOURCE_UNKNOWN: Integer read _GetINDOOR_LOCATION_SOURCE_UNKNOWN; { class } property INDOOR_LOCATION_SOURCE_WIFI: Integer read _GetINDOOR_LOCATION_SOURCE_WIFI; { class } property INDOOR_LOCATION_SOURCE_MAGNETIC: Integer read _GetINDOOR_LOCATION_SOURCE_MAGNETIC; { class } property INDOOR_LOCATION_SOURCE_BLUETOOTH: Integer read _GetINDOOR_LOCATION_SOURCE_BLUETOOTH; { class } property INDOOR_LOCATION_SOURCE_SMALLCELLSTATION: Integer read _GetINDOOR_LOCATION_SOURCE_SMALLCELLSTATION; { class } property INDOOR_NETWORK_STATE_HIGH: Integer read _GetINDOOR_NETWORK_STATE_HIGH; { class } property INDOOR_NETWORK_STATE_MIDDLE: Integer read _GetINDOOR_NETWORK_STATE_MIDDLE; { class } property INDOOR_NETWORK_STATE_LOW: Integer read _GetINDOOR_NETWORK_STATE_LOW; { class } property OPERATORS_TYPE_UNKONW: Integer read _GetOPERATORS_TYPE_UNKONW; { class } property OPERATORS_TYPE_MOBILE: Integer read _GetOPERATORS_TYPE_MOBILE; { class } property OPERATORS_TYPE_UNICOM: Integer read _GetOPERATORS_TYPE_UNICOM; { class } property OPERATORS_TYPE_TELECOMU: Integer read _GetOPERATORS_TYPE_TELECOMU; { class } property GPS_ACCURACY_GOOD: Integer read _GetGPS_ACCURACY_GOOD; { class } property GPS_ACCURACY_MID: Integer read _GetGPS_ACCURACY_MID; { class } property GPS_ACCURACY_BAD: Integer read _GetGPS_ACCURACY_BAD; { class } property GPS_ACCURACY_UNKNOWN: Integer read _GetGPS_ACCURACY_UNKNOWN; { class } property BDLOCATION_GCJ02_TO_BD09: JString read _GetBDLOCATION_GCJ02_TO_BD09; { class } property BDLOCATION_GCJ02_TO_BD09LL: JString read _GetBDLOCATION_GCJ02_TO_BD09LL; { class } property BDLOCATION_BD09_TO_GCJ02: JString read _GetBDLOCATION_BD09_TO_GCJ02; { class } property BDLOCATION_BD09LL_TO_GCJ02: JString read _GetBDLOCATION_BD09LL_TO_GCJ02; { class } property BDLOCATION_WGS84_TO_GCJ02: JString read _GetBDLOCATION_WGS84_TO_GCJ02; { class } property CREATOR: JParcelable_Creator read _GetCREATOR; end; [JavaSignature('com/baidu/location/BDLocation')] JBDLocation = interface(JObject) ['{D0D7B959-E0F6-451C-BEA9-D6A68E693D9E}'] { Property Methods } { methods } function getPoiList: JList; cdecl; // ()Ljava/util/List; procedure setPoiList(P1: JList); cdecl; // (Ljava/util/List;)V function isCellChangeFlag: Boolean; cdecl; // ()Z function getUserIndoorState: Integer; cdecl; // ()I procedure setUserIndoorState(P1: Integer); cdecl; // (I)V function getIndoorLocationSurpport: Integer; cdecl; // ()I function getIndoorLocationSurpportBuidlingName: JString; cdecl; // ()Ljava/lang/String; function getIndoorLocationSurpportBuidlingID: JString; cdecl; // ()Ljava/lang/String; procedure setIndoorLocationSurpport(P1: Integer); cdecl; // (I)V function getIndoorNetworkState: Integer; cdecl; // ()I procedure setIndoorNetworkState(P1: Integer); cdecl; // (I)V function getIndoorLocationSource: Integer; cdecl; // ()I procedure setIndoorLocationSource(P1: Integer); cdecl; // (I)V function getIndoorSurpportPolygon: JString; cdecl; // ()Ljava/lang/String; procedure setIndoorSurpportPolygon(P1: JString); cdecl; // (Ljava/lang/String;)V function getTime: JString; cdecl; // ()Ljava/lang/String; procedure setTime(P1: JString); cdecl; // (Ljava/lang/String;)V function getLatitude: Double; cdecl; // ()D procedure setLatitude(P1: Double); cdecl; // (D)V function getLongitude: Double; cdecl; // ()D procedure setLongitude(P1: Double); cdecl; // (D)V function getAltitude: Double; cdecl; // ()D procedure setAltitude(P1: Double); cdecl; // (D)V function getSpeed: Single; cdecl; // ()F procedure setSpeed(P1: Single); cdecl; // (F)V function getRadius: Single; cdecl; // ()F procedure setRadius(P1: Single); cdecl; // (F)V function getCoorType: JString; cdecl; // ()Ljava/lang/String; procedure setCoorType(P1: JString); cdecl; // (Ljava/lang/String;)V procedure setAddrStr(P1: JString); cdecl; // (Ljava/lang/String;)V function hasAltitude: Boolean; cdecl; // ()Z function hasSpeed: Boolean; cdecl; // ()Z function hasRadius: Boolean; cdecl; // ()Z procedure setLocType(P1: Integer); cdecl; // (I)V function getLocType: Integer; cdecl; // ()I function getLocTypeDescription: JString; cdecl; // ()Ljava/lang/String; procedure setLocTypeDescription(P1: JString); cdecl; // (Ljava/lang/String;)V procedure setSatelliteNumber(P1: Integer); cdecl; // (I)V function getSatelliteNumber: Integer; cdecl; // ()I function getDerect: Single; cdecl; // Deprecated //()F function getDirection: Single; cdecl; // ()F procedure setDirection(P1: Single); cdecl; // (F)V function hasSateNumber: Boolean; cdecl; // ()Z function hasAddr: Boolean; cdecl; // ()Z function getAddress: JAddress; cdecl; // ()Lcom/baidu/location/Address; procedure setAddr(P1: JAddress); cdecl; // (Lcom/baidu/location/Address;)V function getAddrStr: JString; cdecl; // ()Ljava/lang/String; function getProvince: JString; cdecl; // ()Ljava/lang/String; function getCity: JString; cdecl; // ()Ljava/lang/String; function getCityCode: JString; cdecl; // ()Ljava/lang/String; function getCountry: JString; cdecl; // ()Ljava/lang/String; function getCountryCode: JString; cdecl; // ()Ljava/lang/String; function getDistrict: JString; cdecl; // ()Ljava/lang/String; function getStreet: JString; cdecl; // ()Ljava/lang/String; function getStreetNumber: JString; cdecl; // ()Ljava/lang/String; function getLocationDescribe: JString; cdecl; // ()Ljava/lang/String; procedure setLocationDescribe(P1: JString); cdecl; // (Ljava/lang/String;)V function getFloor: JString; cdecl; // ()Ljava/lang/String; procedure setFloor(P1: JString); cdecl; // (Ljava/lang/String;)V function getBuildingID: JString; cdecl; // ()Ljava/lang/String; procedure setBuildingID(P1: JString); cdecl; // (Ljava/lang/String;)V function getBuildingName: JString; cdecl; // ()Ljava/lang/String; procedure setBuildingName(P1: JString); cdecl; // (Ljava/lang/String;)V function isParkAvailable: Integer; cdecl; // ()I procedure setParkAvailable(P1: Integer); cdecl; // (I)V function isIndoorLocMode: Boolean; cdecl; // ()Z procedure setIndoorLocMode(P1: Boolean); cdecl; // (Z)V function getLocationWhere: Integer; cdecl; // ()I procedure setLocationWhere(P1: Integer); cdecl; // (I)V function getGpsAccuracyStatus: Integer; cdecl; // ()I procedure setGpsAccuracyStatus(P1: Integer); cdecl; // (I)V function getSemaAptag: JString; cdecl; // Deprecated //()Ljava/lang/String; function getNetworkLocationType: JString; cdecl; // ()Ljava/lang/String; procedure setNetworkLocationType(P1: JString); cdecl; // (Ljava/lang/String;)V function getOperators: Integer; cdecl; // ()I procedure setOperators(P1: Integer); cdecl; // (I)V function describeContents: Integer; cdecl; // ()I procedure writeToParcel(P1: JParcel; P2: Integer); cdecl; // (Landroid/os/Parcel;I)V { Property } end; TJBDLocation = class(TJavaGenericImport<JBDLocationClass, JBDLocation>) end; JBDLocationListenerClass = interface(JObjectClass) ['{699EB89C-6403-4384-B871-FB32A09D134A}'] { static Property Methods } { static Methods } { static Property } end; [JavaSignature('com/baidu/location/BDLocationListener')] JBDLocationListener = interface(IJavaInstance) ['{5BB0FC2B-60CD-4D91-BCEF-1848C078AFA9}'] { Property Methods } { methods } procedure onReceiveLocation(P1: JBDLocation); cdecl; // (Lcom/baidu/location/BDLocation;)V procedure onConnectHotSpotMessage(P1: JString; P2: Integer); cdecl; // (Ljava/lang/String;I)V { Property } end; TJBDLocationListener = class(TJavaGenericImport<JBDLocationListenerClass, JBDLocationListener>) end; JJniClass = interface(JObjectClass) ['{1007C41F-0982-4EBA-8801-DBC35F98FE41}'] { static Property Methods } { static Methods } { class } function init: JJni; cdecl; // ()V { class } procedure uninstall(P1: JString); cdecl; // (Ljava/lang/String;)V { class } function encode(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { class } function decodeIBeacon(P1: TJavaArray<Byte>; P2: TJavaArray<Byte>) : JString; cdecl; // ([B[B)Ljava/lang/String; { class } procedure removeSoList(P1: Integer; P2: JString); cdecl; // (ILjava/lang/String;)V { class } function en1(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { class } function encode2(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { class } function encode3(P1: JString): JLong; cdecl; // (Ljava/lang/String;)Ljava/lang/Long; { class } function getSkyKey: JString; cdecl; // ()Ljava/lang/String; { class } function encodeOfflineLocationUpdateRequest(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { class } function encodeTp4(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { class } function getGpsSwiftRadius(P1: Single; P2: Double; P3: Double) : Double; cdecl; // (FDD)D { class } function coorEncrypt(P1: Double; P2: Double; P3: JString) : TJavaArray<Double>; cdecl; // (DDLjava/lang/String;)[D { class } procedure tr2(P1: JString; P2: JString); cdecl; // (Ljava/lang/String;Ljava/lang/String;)V { class } function gtr2(P1: JString): JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; { static Property } end; [JavaSignature('com/baidu/location/Jni')] JJni = interface(JObject) ['{F2F6D06F-9553-4C22-B685-1AC1BD3CAE84}'] { Property Methods } { methods } { Property } end; TJJni = class(TJavaGenericImport<JJniClass, JJni>) end; JLLSInterfaceClass = interface(JObjectClass) ['{E940DF44-ED74-424D-9D16-E1A3EA1ECD3C}'] { static Property Methods } { static Methods } { static Property } end; [JavaSignature('com/baidu/location/LLSInterface')] JLLSInterface = interface(IJavaInstance) ['{0B124C93-B804-42A2-BFB0-3914BE42C8C1}'] { Property Methods } { methods } procedure onCreate(P1: JContext); cdecl; // (Landroid/content/Context;)V function onStartCommand(P1: JIntent; P2: Integer; P3: Integer): Integer; cdecl; // (Landroid/content/Intent;II)I function onBind(P1: JIntent): JIBinder; cdecl; // (Landroid/content/Intent;)Landroid/os/IBinder; function onUnBind(P1: JIntent): Boolean; cdecl; // (Landroid/content/Intent;)Z procedure onDestroy; cdecl; // ()V function getVersion: Double; cdecl; // ()D { Property } end; TJLLSInterface = class(TJavaGenericImport<JLLSInterfaceClass, JLLSInterface>) end; JLocationClientClass = interface(JObjectClass) ['{D951C38B-CD0C-4EF6-BE79-D80C0B8B4398}'] { static Property Methods } { class } function _GetCONNECT_HOT_SPOT_TRUE: Integer; // I { class } function _GetCONNECT_HOT_SPOT_FALSE: Integer; // I { class } function _GetCONNECT_HOT_SPOT_UNKNOWN: Integer; // I { static Methods } { class } function init(P1: JContext): JLocationClient; cdecl; overload; // (Landroid/content/Context;)V { class } function init(P1: JContext; P2: JLocationClientOption) : JLocationClient; cdecl; overload; // (Landroid/content/Context;Lcom/baidu/location/LocationClientOption;)V { class } function getBDLocationInCoorType(P1: JBDLocation; P2: JString) : JBDLocation; cdecl; // (Lcom/baidu/location/BDLocation;Ljava/lang/String;)Lcom/baidu/location/BDLocation; { static Property } { class } property CONNECT_HOT_SPOT_TRUE: Integer read _GetCONNECT_HOT_SPOT_TRUE; { class } property CONNECT_HOT_SPOT_FALSE: Integer read _GetCONNECT_HOT_SPOT_FALSE; { class } property CONNECT_HOT_SPOT_UNKNOWN: Integer read _GetCONNECT_HOT_SPOT_UNKNOWN; end; [JavaSignature('com/baidu/location/LocationClient')] JLocationClient = interface(JObject) ['{9803CAEA-1DA3-45BF-90D6-B8671AADA47C}'] { Property Methods } { methods } function getLocOption: JLocationClientOption; cdecl; // ()Lcom/baidu/location/LocationClientOption; procedure setLocOption(P1: JLocationClientOption); cdecl; // (Lcom/baidu/location/LocationClientOption;)V function updateLocation(P1: JLocation): Boolean; cdecl; // (Landroid/location/Location;)Z procedure requestNotifyLocation; cdecl; // ()V function requestOfflineLocation: Integer; cdecl; // ()I function requestLocation: Integer; cdecl; // ()I function isStarted: Boolean; cdecl; // ()Z function getLastKnownLocation: JBDLocation; cdecl; // ()Lcom/baidu/location/BDLocation; function getVersion: JString; cdecl; // ()Ljava/lang/String; procedure start; cdecl; // ()V function requestHotSpotState: Boolean; cdecl; // ()Z procedure stop; cdecl; // ()V procedure registerNotifyLocationListener(P1: JBDLocationListener); cdecl; // (Lcom/baidu/location/BDLocationListener;)V procedure registerLocationListener(P1: JBDLocationListener); cdecl; // (Lcom/baidu/location/BDLocationListener;)V procedure unRegisterLocationListener(P1: JBDLocationListener); cdecl; // (Lcom/baidu/location/BDLocationListener;)V function getAccessKey: JString; cdecl; // ()Ljava/lang/String; procedure onReceiveLocation(P1: JBDLocation); cdecl; // (Lcom/baidu/location/BDLocation;)V { Property } end; TJLocationClient = class(TJavaGenericImport<JLocationClientClass, JLocationClient>) end; JLocationClientOption_LocationModeClass = interface(JEnumClass) // or JObjectClass // SuperSignature: java/lang/Enum ['{5E6934B8-28E2-4ED8-B25B-11C412E765C5}'] { static Property Methods } { class } function _GetHight_Accuracy: JLocationClientOption_LocationMode; // Lcom/baidu/location/LocationClientOption$LocationMode; { class } function _GetBattery_Saving: JLocationClientOption_LocationMode; // Lcom/baidu/location/LocationClientOption$LocationMode; { class } function _GetDevice_Sensors: JLocationClientOption_LocationMode; // Lcom/baidu/location/LocationClientOption$LocationMode; { static Methods } { class } function values : TJavaObjectArray<JLocationClientOption_LocationMode>; cdecl; // ()[Lcom/baidu/location/LocationClientOption$LocationMode; { class } function valueOf(P1: JString): JLocationClientOption_LocationMode; cdecl; // (Ljava/lang/String;)Lcom/baidu/location/LocationClientOption$LocationMode; { static Property } { class } property Hight_Accuracy: JLocationClientOption_LocationMode read _GetHight_Accuracy; { class } property Battery_Saving: JLocationClientOption_LocationMode read _GetBattery_Saving; { class } property Device_Sensors: JLocationClientOption_LocationMode read _GetDevice_Sensors; end; [JavaSignature('com/baidu/location/LocationClientOption$LocationMode')] JLocationClientOption_LocationMode = interface(JEnum) // or JObject // SuperSignature: java/lang/Enum ['{7FC6015A-EDFE-4F2D-8DEE-D25F1E54634D}'] { Property Methods } { methods } { Property } end; TJLocationClientOption_LocationMode = class (TJavaGenericImport<JLocationClientOption_LocationModeClass, JLocationClientOption_LocationMode>) end; JLocationClientOptionClass = interface(JObjectClass) ['{BC1486D6-5A8B-4684-A947-4164B6C29B30}'] { static Property Methods } { class } function _GetMIN_SCAN_SPAN: Integer; // I { class } function _GetGpsFirst: Integer; // I { class } function _GetNetWorkFirst: Integer; // I { class } function _GetGpsOnly: Integer; // I { class } function _GetLOC_SENSITIVITY_HIGHT: Integer; // I { class } function _GetLOC_SENSITIVITY_MIDDLE: Integer; // I { class } function _GetLOC_SENSITIVITY_LOW: Integer; // I { class } function _GetMIN_AUTO_NOTIFY_INTERVAL: Integer; // I { static Methods } { class } function init: JLocationClientOption; cdecl; overload; // ()V { class } function init(P1: JLocationClientOption): JLocationClientOption; cdecl; overload; // (Lcom/baidu/location/LocationClientOption;)V { static Property } { class } property MIN_SCAN_SPAN: Integer read _GetMIN_SCAN_SPAN; { class } property GpsFirst: Integer read _GetGpsFirst; { class } property NetWorkFirst: Integer read _GetNetWorkFirst; { class } property GpsOnly: Integer read _GetGpsOnly; { class } property LOC_SENSITIVITY_HIGHT: Integer read _GetLOC_SENSITIVITY_HIGHT; { class } property LOC_SENSITIVITY_MIDDLE: Integer read _GetLOC_SENSITIVITY_MIDDLE; { class } property LOC_SENSITIVITY_LOW: Integer read _GetLOC_SENSITIVITY_LOW; { class } property MIN_AUTO_NOTIFY_INTERVAL: Integer read _GetMIN_AUTO_NOTIFY_INTERVAL; end; [JavaSignature('com/baidu/location/LocationClientOption')] JLocationClientOption = interface(JObject) ['{34C7E82D-6F40-4B13-936E-992AAC056AF0}'] { Property Methods } function _GetcoorType: JString; // Ljava/lang/String; procedure _SetcoorType(acoorType: JString); // (Ljava/lang/String;)V function _GetaddrType: JString; // Ljava/lang/String; procedure _SetaddrType(aaddrType: JString); // (Ljava/lang/String;)V function _GetopenGps: Boolean; // Z procedure _SetopenGps(aopenGps: Boolean); // (Z)V function _GetscanSpan: Integer; // I procedure _SetscanSpan(ascanSpan: Integer); // (I)V function _GettimeOut: Integer; // I procedure _SettimeOut(atimeOut: Integer); // (I)V function _GetprodName: JString; // Ljava/lang/String; procedure _SetprodName(aprodName: JString); // (Ljava/lang/String;)V function _Getpriority: Integer; // I procedure _Setpriority(apriority: Integer); // (I)V function _Getlocation_change_notify: Boolean; // Z procedure _Setlocation_change_notify(alocation_change_notify: Boolean); // (Z)V function _GetdisableLocCache: Boolean; // Z procedure _SetdisableLocCache(adisableLocCache: Boolean); // (Z)V function _GetenableSimulateGps: Boolean; // Z procedure _SetenableSimulateGps(aenableSimulateGps: Boolean); // (Z)V function _GetserviceName: JString; // Ljava/lang/String; procedure _SetserviceName(aserviceName: JString); // (Ljava/lang/String;)V function _GetisIgnoreCacheException: Boolean; // Z procedure _SetisIgnoreCacheException(aisIgnoreCacheException: Boolean); // (Z)V function _GetisIgnoreKillProcess: Boolean; // Z procedure _SetisIgnoreKillProcess(aisIgnoreKillProcess: Boolean); // (Z)V function _GetmIsNeedDeviceDirect: Boolean; // Z procedure _SetmIsNeedDeviceDirect(amIsNeedDeviceDirect: Boolean); // (Z)V function _GetisNeedAptag: Boolean; // Z procedure _SetisNeedAptag(aisNeedAptag: Boolean); // (Z)V function _GetisNeedAptagd: Boolean; // Z procedure _SetisNeedAptagd(aisNeedAptagd: Boolean); // (Z)V function _GetisNeedPoiRegion: Boolean; // Z procedure _SetisNeedPoiRegion(aisNeedPoiRegion: Boolean); // (Z)V function _GetisNeedRegular: Boolean; // Z procedure _SetisNeedRegular(aisNeedRegular: Boolean); // (Z)V function _GetisNeedAltitude: Boolean; // Z procedure _SetisNeedAltitude(aisNeedAltitude: Boolean); // (Z)V function _GetautoNotifyMaxInterval: Integer; // I procedure _SetautoNotifyMaxInterval(aautoNotifyMaxInterval: Integer); // (I)V function _GetautoNotifyLocSensitivity: Single; // F procedure _SetautoNotifyLocSensitivity(aautoNotifyLocSensitivity: Single); // (F)V function _GetautoNotifyMinTimeInterval: Integer; // I procedure _SetautoNotifyMinTimeInterval(aautoNotifyMinTimeInterval : Integer); // (I)V function _GetautoNotifyMinDistance: Integer; // I procedure _SetautoNotifyMinDistance(aautoNotifyMinDistance: Integer); // (I)V { methods } function optionEquals(P1: JLocationClientOption): Boolean; cdecl; // (Lcom/baidu/location/LocationClientOption;)Z function getCoorType: JString; cdecl; // ()Ljava/lang/String; procedure setCoorType(P1: JString); cdecl; // (Ljava/lang/String;)V function getAddrType: JString; cdecl; // ()Ljava/lang/String; procedure setAddrType(P1: JString); cdecl; // Deprecated //(Ljava/lang/String;)V procedure setIsNeedAddress(P1: Boolean); cdecl; // (Z)V function isOpenGps: Boolean; cdecl; // ()Z procedure setOpenGps(P1: Boolean); cdecl; // (Z)V function isLocationNotify: Boolean; cdecl; // ()Z procedure setLocationNotify(P1: Boolean); cdecl; // (Z)V procedure setOpenAutoNotifyMode; cdecl; overload; // ()V procedure setOpenAutoNotifyMode(P1: Integer; P2: Integer; P3: Integer); cdecl; overload; // (III)V function getAutoNotifyMinTimeInterval: Integer; cdecl; // ()I function getAutoNotifyMinDistance: Integer; cdecl; // ()I function getScanSpan: Integer; cdecl; // ()I procedure setScanSpan(P1: Integer); cdecl; // (I)V function getTimeOut: Integer; cdecl; // ()I procedure setTimeOut(P1: Integer); cdecl; // (I)V function getProdName: JString; cdecl; // ()Ljava/lang/String; procedure setProdName(P1: JString); cdecl; // (Ljava/lang/String;)V function getPriority: Integer; cdecl; // ()I procedure setPriority(P1: Integer); cdecl; // Deprecated //(I)V procedure setLocationMode(P1: JLocationClientOption_LocationMode); cdecl; // (Lcom/baidu/location/LocationClientOption$LocationMode;)V function getLocationMode: JLocationClientOption_LocationMode; cdecl; // ()Lcom/baidu/location/LocationClientOption$LocationMode; procedure setNeedDeviceDirect(P1: Boolean); cdecl; // (Z)V function getServiceName: JString; cdecl; // ()Ljava/lang/String; procedure setServiceName(P1: JString); cdecl; // (Ljava/lang/String;)V procedure setIsNeedLocationDescribe(P1: Boolean); cdecl; // (Z)V procedure setIsNeedAltitude(P1: Boolean); cdecl; // (Z)V procedure setIsNeedLocationPoiList(P1: Boolean); cdecl; // (Z)V procedure setSema(P1: Boolean; P2: Boolean; P3: Boolean); cdecl; // Deprecated //(ZZZ)V procedure disableCache(P1: Boolean); cdecl; // (Z)V function isDisableCache: Boolean; cdecl; // ()Z procedure SetIgnoreCacheException(P1: Boolean); cdecl; // (Z)V procedure setIgnoreKillProcess(P1: Boolean); cdecl; // (Z)V procedure setEnableSimulateGps(P1: Boolean); cdecl; // (Z)V { Property } property coorType: JString read _GetcoorType write _SetcoorType; property addrType: JString read _GetaddrType write _SetaddrType; property openGps: Boolean read _GetopenGps write _SetopenGps; property scanSpan: Integer read _GetscanSpan write _SetscanSpan; property timeOut: Integer read _GettimeOut write _SettimeOut; property prodName: JString read _GetprodName write _SetprodName; property priority: Integer read _Getpriority write _Setpriority; property location_change_notify: Boolean read _Getlocation_change_notify write _Setlocation_change_notify; property disableLocCache: Boolean read _GetdisableLocCache write _SetdisableLocCache; property enableSimulateGps: Boolean read _GetenableSimulateGps write _SetenableSimulateGps; property serviceName: JString read _GetserviceName write _SetserviceName; property isIgnoreCacheException: Boolean read _GetisIgnoreCacheException write _SetisIgnoreCacheException; property isIgnoreKillProcess: Boolean read _GetisIgnoreKillProcess write _SetisIgnoreKillProcess; property mIsNeedDeviceDirect: Boolean read _GetmIsNeedDeviceDirect write _SetmIsNeedDeviceDirect; property isNeedAptag: Boolean read _GetisNeedAptag write _SetisNeedAptag; property isNeedAptagd: Boolean read _GetisNeedAptagd write _SetisNeedAptagd; property isNeedPoiRegion: Boolean read _GetisNeedPoiRegion write _SetisNeedPoiRegion; property isNeedRegular: Boolean read _GetisNeedRegular write _SetisNeedRegular; property isNeedAltitude: Boolean read _GetisNeedAltitude write _SetisNeedAltitude; property autoNotifyMaxInterval: Integer read _GetautoNotifyMaxInterval write _SetautoNotifyMaxInterval; property autoNotifyLocSensitivity: Single read _GetautoNotifyLocSensitivity write _SetautoNotifyLocSensitivity; property autoNotifyMinTimeInterval: Integer read _GetautoNotifyMinTimeInterval write _SetautoNotifyMinTimeInterval; property autoNotifyMinDistance: Integer read _GetautoNotifyMinDistance write _SetautoNotifyMinDistance; end; TJLocationClientOption = class(TJavaGenericImport<JLocationClientOptionClass, JLocationClientOption>) end; JPoiClass = interface(JObjectClass) ['{78EAAB9C-E4B7-4999-8618-3751D1D1FCC3}'] { static Property Methods } { class } function _GetCREATOR: JParcelable_Creator; // Landroid/os/Parcelable$Creator; { static Methods } { class } function init(P1: JString; P2: JString; P3: Double): JPoi; cdecl; // (Ljava/lang/String;Ljava/lang/String;D)V { static Property } { class } property CREATOR: JParcelable_Creator read _GetCREATOR; end; [JavaSignature('com/baidu/location/Poi')] JPoi = interface(JObject) ['{6EF42CC1-250D-4555-8C9A-B0B68F60590E}'] { Property Methods } { methods } function getId: JString; cdecl; // ()Ljava/lang/String; function getRank: Double; cdecl; // ()D function getName: JString; cdecl; // ()Ljava/lang/String; function describeContents: Integer; cdecl; // ()I procedure writeToParcel(P1: JParcel; P2: Integer); cdecl; // (Landroid/os/Parcel;I)V { Property } end; TJPoi = class(TJavaGenericImport<JPoiClass, JPoi>) end; implementation procedure RegisterTypes; begin TRegTypes.RegisterType('Androidapi.JNI.baidu.location.Address_Builder', TypeInfo(Androidapi.JNI.baidu.location.JAddress_Builder)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.Address', TypeInfo(Androidapi.JNI.baidu.location.JAddress)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.BDLocation', TypeInfo(Androidapi.JNI.baidu.location.JBDLocation)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.BDLocationListener', TypeInfo(Androidapi.JNI.baidu.location.JBDLocationListener)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.Jni', TypeInfo(Androidapi.JNI.baidu.location.JJni)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.LLSInterface', TypeInfo(Androidapi.JNI.baidu.location.JLLSInterface)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.LocationClient', TypeInfo(Androidapi.JNI.baidu.location.JLocationClient)); TRegTypes.RegisterType ('Androidapi.JNI.baidu.location.LocationClientOption_LocationMode', TypeInfo(Androidapi.JNI.baidu.location.JLocationClientOption_LocationMode)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.LocationClientOption', TypeInfo(Androidapi.JNI.baidu.location.JLocationClientOption)); TRegTypes.RegisterType('Androidapi.JNI.baidu.location.Poi', TypeInfo(Androidapi.JNI.baidu.location.JPoi)); end; initialization RegisterTypes; end.
unit ship_; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Timer1: TTimer; procedure Timer1Timer(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} var x,y: integer; // координаты корабля (базовой точки) // вычерчивает на поверхности формы кораблик // или стирает его procedure Parohod(x,y: integer; mode: boolean); // x,y - координаты базовой точки кораблика // mode: True - нарисовать, False - стереть const { Базовые точки кораблика находятся в узлах сетки, шаг которой определяет размер кораблика. } dx = 5; // шаг сетки по X dy = 5; // шаг сетки по Y var // корпус и надстройку будем рисовать // при помощи метода Polygon p1: array[1..7]of TPoint; // координаты точек корпуса p2: array[1..8]of TPoint; // координаты точек надстройки pc,bc: TColor; // текущий цвет карандаша и кисти begin if not mode then begin // стереть Form1.Canvas.Brush.Color := clNavy; Form1.Canvas.Pen.Color := clNavy; Form1.Canvas.Rectangle(x,y+1,x+17*dx,y-10*dy); Form1.Canvas.Brush.Color := clNavy; // небо if y-10*dy < 80 then begin // конец мачты на фоне неба Form1.Canvas.Pen.Color := clSkyBlue; Form1.Canvas.Brush.Color := clSkyBlue; Form1.Canvas.Rectangle(x,y-10*dy,x+17*dx,80); end; exit; end; // рисуем with Form1.Canvas do begin pc :=Pen.Color; // сохраним текущий цвет карандаша bc := Brush.Color; // и кисти Pen.Color:=clBlack; // установим нужный цвет Brush.Color := clWhite; // рисуем ... // корпус p1[1].X := x; p1[1].y := y; p1[2].X := x; p1[2].Y := y-2*dy; p1[3].X :=x+10*dx; p1[3].Y := y-2*dy; p1[4].X :=x+11*dx; p1[4].Y := y-3*dy; p1[5].X :=x+17*dx; p1[5].Y :=y-3*dy; p1[6].X :=x+14*dx; p1[6].Y :=y; p1[7].X :=x; p1[7].Y :=y; Polygon(p1); // надстройка p2[1].X := x+3*dx; p2[1].Y := y-2*dy; p2[2].X := x+4*dx; p2[2].Y := y-3*dy; p2[3].X := x+4*dx; p2[3].Y := y-4*dy; p2[4].X := x+13*dx; p2[4].Y := y-4*dy; p2[5].X := x+13*dx; p2[5].Y := y-3*dy; p2[6].X := x+11*dx; p2[6].Y := y-3*dy; p2[7].X := x+10*dx; p2[7].Y := y-2*dy; p2[8].X := x+3*dx; p2[8].Y := y-2*dy; Polygon(p2); MoveTo(x+5*dx,y-3*dy); LineTo(x+9*dx,y-3*dy); // капитанский мостик Rectangle(x+8*dx,y-4*dy,x+11*dx,y-5*dy); // труба Rectangle(x+7*dx,y-4*dy,x+8*dx,y-7*dy); // иллюминаторы Ellipse(x+11*dx,y-2*dy,x+12*dx,y-1*dy); Ellipse(x+13*dx,y-2*dy,x+14*dx,y-1*dy); // мачта MoveTo(x+10*dx,y-5*dy); LineTo(x+10*dx,y-10*dy); // оснастка Pen.Color := clWhite; MoveTo(x+17*dx,y-3*dy); LineTo(x+10*dx,y-10*dy); LineTo(x,y-2*dy); Pen.Color:=pc; // восстановим старый цвет карандаша end; end; // обработка сигнала таймера procedure TForm1.Timer1Timer(Sender: TObject); begin Parohod(x,y, False); // стереть рисунок if x < Form1.ClientWidth then x := x+2 else begin // новый рейс x := 0; y := Random(50) + 100; end; Parohod(x,y,True); // нарисовать в новой точке end; procedure TForm1.FormPaint(Sender: TObject); begin // небо Canvas.Brush.Color := clSkyBlue; Canvas.Pen.Color := clSkyBlue; Canvas.Rectangle(0,0,ClientWidth,80); end; procedure TForm1.FormCreate(Sender: TObject); begin Form1.DoubleBuffered:=true; x:=0; y:=80; // исходное положение парохода Form1.Color:=clNavy; // цвет моря Timer1.Interval := 50; // сигнал таймера каждые 50 мСек end; end.
unit kwPopComboBoxSetIndex; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopComboBoxSetIndex.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::ControlsProcessing::pop_ComboBox_SetIndex // // *Формат:* // {code} // anItemIndex aControlObj pop:ComboBox:SetItemIdex // {code} // *Описание:* Устанавливает значение свойства ItemIndex у контрола TComboBox, заданное в параметре // anItemIndex // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses StdCtrls, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} TkwPopComboBoxSetIndex = {final} class(_kwComboBoxFromStack_) {* *Формат:* [code] anItemIndex aControlObj pop:ComboBox:SetItemIdex [code] *Описание:* Устанавливает значение свойства ItemIndex у контрола TComboBox, заданное в параметре anItemIndex } protected // realized methods procedure DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopComboBoxSetIndex {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopComboBoxSetIndex; {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} // start class TkwPopComboBoxSetIndex procedure TkwPopComboBoxSetIndex.DoWithComboBox(const aCombobox: TCustomCombo; const aCtx: TtfwContext); //#UC START# *5049C8740203_5049C71F002B_var* //#UC END# *5049C8740203_5049C71F002B_var* begin //#UC START# *5049C8740203_5049C71F002B_impl* if aCtx.rEngine.IsTopInt then aCombobox.ItemIndex := aCtx.rEngine.PopInt else Assert(False, 'Не задано значение ItemIndex у CombobBox'); //#UC END# *5049C8740203_5049C71F002B_impl* end;//TkwPopComboBoxSetIndex.DoWithComboBox class function TkwPopComboBoxSetIndex.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:ComboBox:SetIndex'; end;//TkwPopComboBoxSetIndex.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwComboBoxFromStack.imp.pas} {$IfEnd} //not NoScripts end.
unit uFormaPagtoController; interface uses System.SysUtils, uDMFormaPagto, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, Data.DBXJSON, Data.DBXJSONReflect, uFormaPagtoVO; type TFormaPagtoController = class private FModel: TDMFormaPagto; FOperacao: TOperacao; procedure Post; procedure SalvarItens(Obj: TFormaPagtoVO); public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(AIdUsuario: Integer): Integer; procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, Codigo: Integer); function CodigoAtual: Integer; procedure ListarFormaPagto(AIdFormaPagto: Integer); property Model: TDMFormaPagto read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TObservacaoController } uses uFormaPagtoItemVO; procedure TFormaPagtoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TFormaPagtoController.CodigoAtual: Integer; begin Result := FModel.CDSCadastroFpg_Codigo.AsInteger; end; constructor TFormaPagtoController.Create; begin inherited Create; FModel := TDMFormaPagto.Create(nil); end; destructor TFormaPagtoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TFormaPagtoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CFormaPagto, dm.IdUsuario, AId); FModel.CDSCadastro.Open; FModel.CDSItens.Close; Negocio.FormaPagtoFiltroItem(AId); FModel.CDSItens.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CFormaPagto, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.Filtrar(CFormaPagto, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CFormaPagto, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CFormaPagto, AIdUsuario); FModel.Rel.Print; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.ListarFormaPagto(AIdFormaPagto: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSItens.Close; Negocio.FormaPagtoFiltroItem(AIdFormaPagto); FModel.CDSItens.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CFormaPagto, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CFormaPagto, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CFormaPagto, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FModel.CDSItens.Close; Negocio.FormaPagtoFiltroItem(0); FModel.CDSItens.Open; FModel.CDSCadastroFpg_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFormaPagtoController.Pesquisar(AId, Codigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(Codigo); end; procedure TFormaPagtoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TFormaPagtoController.ProximoCodigo: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoCodigo(CFormaPagto).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TFormaPagtoController.ProximoId: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoId(CFormaPagto).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TFormaPagtoController.Salvar(AIdUsuario: Integer): Integer; var Negocio: TServerModule2Client; ObjVO: TFormaPagtoVO; Marshal : TJSONMarshal; oObjetoJSON : TJSONValue; begin ObjVO := TFormaPagtoVO.Create; Marshal := TJSONMarshal.Create; DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try ObjVO.Id := FModel.CDSCadastroFpg_Id.AsInteger; ObjVO.Codigo := FModel.CDSCadastroFpg_Codigo.AsInteger; ObjVO.Nome := FModel.CDSCadastroFpg_Nome.AsString; ObjVO.Ativo := FModel.CDSCadastroFpg_Ativo.AsBoolean; SalvarItens(ObjVO); oObjetoJSON := Marshal.Marshal(ObjVO); Result := StrToIntDef(Negocio.FormaPagtoSalvar(oObjetoJSON).ToString(),0); Post; FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); FreeAndNil(Marshal); FreeAndNil(ObjVO); end; end; procedure TFormaPagtoController.SalvarItens(Obj: TFormaPagtoVO); var ItemVO: TFormaPagtoItemVO; begin FModel.CDSItens.DisableControls; FModel.CDSItens.First; try while not FModel.CDSItens.Eof do begin ItemVO := TFormaPagtoItemVO.Create; ItemVO.Id := FModel.CDSItensFpgIte_Id.AsInteger; ItemVO.IdFormaPagto := FModel.CDSItensFpgIte_FormaPagto.AsInteger; ItemVO.Dias := FModel.CDSItensFpgIte_Dias.AsInteger; ItemVO.Obs := FModel.CDSItensFpgIte_Obs.AsString; Obj.Itens.Add(ItemVO); FModel.CDSItens.Next; end; finally FModel.CDSItens.First; FModel.CDSItens.EnableControls; end; end; end.
unit CacheProperties; //falta manejar cuando no es un par nombre=valor //crearlo sin dicc funciones para activar y desactivar el diccionario interface uses classes, containers; type TStringItem = class(TItem) private fString : string; public property StringData : string read fString write fString; end; TCacheProperties = class(TObject)//TPersistent private fDictionary : TDictionary; fStringList : TStrings; function Get(Index: Integer): string; function GetName(Index: Integer): string; function GetValue(const Name: string): string; procedure Put(Index: Integer; const Value: string); procedure SetValue(const Name, Value: string); procedure PopulateDictionary; public constructor Create; //virtual;//overload; // constructor Create(AStringList: TStringList); overload; destructor Destroy; override; procedure Clear; virtual; //abstract; function IndexOfName(const Name: string): Integer; virtual; procedure SaveToStream(Stream: TStream); virtual; procedure LoadFromStream(Stream: TStream); virtual; function Add(const S: string): Integer; virtual; function ActivateDictionary : boolean; function DeactivateDictionary : boolean; procedure AssignProperties(AStringList: TStrings); virtual; public property StringList : TStrings read fStringList; property Names[Index: Integer]: string read GetName; property Values[const Name: string]: string read GetValue write SetValue; property Strings[Index: Integer]: string read Get write Put; default; end; implementation uses sysutils; { TCacheProperties } procedure TCacheProperties.AssignProperties(AStringList: TStrings); begin if fStringList <> nil then begin fStringList.Free; fStringList := nil; end; fStringList := AStringList; DeactivateDictionary; end; function TCacheProperties.ActivateDictionary: boolean; begin if fDictionary = nil then begin fDictionary := TDictionary.Create(nil,true); PopulateDictionary; Result := true; end else Result := false; end; function TCacheProperties.DeactivateDictionary: boolean; begin if fDictionary <> nil then begin fDictionary.Clear; fDictionary.Free; fDictionary := nil; Result := true; end else Result := false; end; procedure TCacheProperties.PopulateDictionary; var StrItem : TStringItem; i : integer; begin if fDictionary <> nil then begin fDictionary.Clear; for i:= 0 to fStringList.Count-1 do begin StrItem := TStringItem.Create; StrItem.StringData := fStringList[i]; fDictionary.Insert(fStringList.Names[i], StrItem); end; end; end; function TCacheProperties.Add(const S: string): Integer; var StrItem : TStringItem; P : integer; Name : string; begin Result := -1; if fStringList <> nil then Result := fStringList.Add(S); if fDictionary <> nil then begin StrItem := TStringItem.Create; StrItem.StringData := S; P := AnsiPos('=',S); if P <> 0 then begin Name := copy(S,1,P-1); fDictionary.Insert(Name, StrItem); end else StrItem.Free; end; end; procedure TCacheProperties.Clear; begin if fStringList <> nil then fStringList.Clear; if fDictionary <> nil then fDictionary.Clear; end; constructor TCacheProperties.Create; begin // inherited Create; fDictionary := nil;//TDictionary.Create(nil, true); fStringList := TStringList.Create;//TStringList.Create; end; { constructor TCacheProperties.Create(AStringList: TStringList); begin inherited Create; fDictionary := nil;//TDictionary.Create(nil, true); fStringList := AStringList; end;} destructor TCacheProperties.Destroy; begin if fDictionary <> nil then begin fDictionary.Clear; fDictionary.Free; fDictionary := nil; end; if fStringList <> nil then begin fStringList.Clear; fStringList.Free; fStringList := nil; end; inherited Destroy; end; { ojojojo en TCachedObject cambiar/////// property Values : TStrings read fProperties; por////////// property Values : TStrings read fProperties.StringList; en UpdateProperties cambiar procedure TCachedObject.UpdateProperties(Props : TStrings); var i : integer; index : integer; Name : string; s : string; begin for i := 0 to pred(Props.Count) do cambiar esto/////////// begin Name := Props.Names[i]; index := fProperties.IndexOfName(Name); if index <> NoIndex then fProperties[index] := Props[i] else fProperties.Add(Props[i]); end; por esto/////////////// begin Name := Props.Names[i]; if fProperties.Values[Name] <> '' then begin P := AnsiPos('=',Props[i]); fProperties.Values[Name]:= copy(Props[i],P+1,MaxInt); end else begin fProperties.Add(Props[i]); end; end; end;} function TCacheProperties.Get(Index: Integer): string; begin if fStringList <> nil then Result := fStringList[Index] else Result := ''; end; function TCacheProperties.GetName(Index: Integer): string; begin if fStringList <> nil then Result := fStringList.Names[Index] else Result := ''; end; function TCacheProperties.GetValue(const Name: string): string; var StrItem : TStringItem; P : integer; begin if fDictionary <> nil then begin StrItem := TStringItem(fDictionary[Name]); if StrItem <> nil then begin Result := StrItem.StringData;//Get(Index); P := AnsiPos('=', Result); if P <> 0 then Result := copy(Result, P+1, MaxInt) else SetLength(Result, 0); end else Result := ''; end else begin if fStringList <> nil then Result := fStringList.Values[Name] else Result := ''; end; end; function TCacheProperties.IndexOfName(const Name: string): Integer; begin if fStringList <> nil then Result := fStringList.IndexOfName(Name) else Result := -1; end; procedure TCacheProperties.LoadFromStream(Stream: TStream); begin if fStringList <> nil then fStringList.LoadFromStream(Stream); //PopulateDictionary; end; procedure TCacheProperties.Put(Index: Integer; const Value: string); var StrItem : TStringItem; begin //StrItem := fDictionary.Items[fStringList.Names[Index]]; if fDictionary <> nil then begin fDictionary.Remove(fStringList.Names[Index]); fStringList[Index] := Value; StrItem := TStringItem.Create; StrItem.StringData := Value; fDictionary.Insert(fStringList.Names[Index],StrItem); end else begin if fStringList <> nil then fStringList[Index] := Value; end; end; procedure TCacheProperties.SaveToStream(Stream: TStream); begin if fStringList <> nil then fStringList.SaveToStream(Stream); end; procedure TCacheProperties.SetValue(const Name, Value: string); var StrItem : TStringItem; begin if fDictionary <> nil then begin StrItem := TStringItem(fDictionary[Name]); StrItem.StringData := Name + '=' + Value; end else begin if fStringList <> nil then fStringList.Values[Name] := Value; end; end; end.
{7. Realizar un programa que lea desde teclado información de autos de carrera. Para cada uno de los autos se lee el nombre del piloto y el tiempo total que le tomó finalizar la carrera. En la carrera participaron 100 autos. Informar en pantalla: - Los nombres de los dos pilotos que finalizaron en los dos primeros puestos. - Los nombres de los dos pilotos que finalizaron en los dos últimos puestos. } program ejercicio7; const Df= 5; //ejercicio dice 100 pilotos var nombrePiloto, maxNombre1, maxNombre2, minNombre1, minNombre2: String; tiempoTotal: Real; maxPrimero1, maxPrimero2, min1Ultimo1, min1Ultimo2: Real; i: Integer; begin maxPrimero1:= 9999; maxPrimero2:= 9999; maxNombre1:= ''; maxNombre2:= ''; min1Ultimo1:= -1; min1Ultimo2:= -1; minNombre1:= ''; minNombre2:= ''; for i := 1 to Df do begin write('Ingrese el NOMBRE DEL PILOTO: '); readln(nombrePiloto); write('Ingrese TIEMPO TOTAL EN FINALIZAR LA CARRERA: '); readln(tiempoTotal); writeln('-------------------------------------------'); if (tiempoTotal <= maxPrimero1) then begin maxPrimero2:= maxPrimero1; maxNombre2:= maxNombre1; maxPrimero1:= tiempoTotal; maxNombre1:= nombrePiloto; end else if (tiempoTotal <= maxPrimero2) then begin maxPrimero2:= tiempoTotal; maxNombre2:= nombrePiloto; end; if (tiempoTotal >= min1Ultimo1) then begin min1Ultimo2:= min1Ultimo1; minNombre2:= minNombre1; min1Ultimo1:= tiempoTotal; minNombre1:= nombrePiloto; end else if (tiempoTotal >= min1Ultimo2) then begin min1Ultimo2:= tiempoTotal; minNombre2:= nombrePiloto; end; end; writeln('Los nombres de los pilotos que terminaron en primer lugar son: ',maxNombre1, ' y ', maxNombre2 ); writeln('Los nombres de los pilotos en terminar en ultimo lugar la carrera son: ', minNombre1, ' y ', minNombre2); readln(); end.
unit KP_Form; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, FileCtrl, StrUtils, KM_Game, KM_CommonTypes, KM_Consts, ExtAILog, ExtAIInfo, // Detection of IP address Winsock; type //@Krom: This is the main class with GUI for KP, it contains just all necessary functions and connections // GUI of the game (server, lobby, basic interface) TGame_form = class(TForm) btnAddPath: TButton; btnAutoFill: TButton; btnRemove: TButton; btnSendEvent: TButton; btnSendState: TButton; btnServerStartMap: TButton; btnStartServer: TButton; cbLoc00: TComboBox; cbLoc01: TComboBox; cbLoc02: TComboBox; cbLoc03: TComboBox; cbLoc04: TComboBox; cbLoc05: TComboBox; cbLoc06: TComboBox; cbLoc07: TComboBox; cbLoc08: TComboBox; cbLoc09: TComboBox; cbLoc10: TComboBox; cbLoc11: TComboBox; edPingLoc00: TEdit; edPingLoc01: TEdit; edPingLoc02: TEdit; edPingLoc03: TEdit; edPingLoc04: TEdit; edPingLoc05: TEdit; edPingLoc06: TEdit; edPingLoc07: TEdit; edPingLoc08: TEdit; edPingLoc09: TEdit; edPingLoc10: TEdit; edPingLoc11: TEdit; edServerPort: TEdit; gbDLLs: TGroupBox; gbKP: TGroupBox; gbLobby: TGroupBox; gbServer: TGroupBox; gbSimulation: TGroupBox; labLoc00: TLabel; labLoc01: TLabel; labLoc02: TLabel; labLoc03: TLabel; labLoc04: TLabel; labLoc05: TLabel; labLoc06: TLabel; labLoc07: TLabel; labLoc08: TLabel; labLoc09: TLabel; labLoc10: TLabel; labLoc11: TLabel; labPortNumber: TLabel; lbDLLs: TListBox; lbPaths: TListBox; mTutorial: TMemo; prgServer: TProgressBar; reLog: TRichEdit; stDLLs: TStaticText; stExtAIName: TStaticText; stPathsDLL: TStaticText; stPing: TStaticText; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnStartServerClick(Sender: TObject); procedure btnServerStartMapClick(Sender: TObject); procedure btnAutoFillClick(Sender: TObject); procedure cbOnChange(Sender: TObject); procedure btnSendEventClick(Sender: TObject); procedure btnAddPathClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); private // Game class fGame: TKMGame; // Pure GUI of the game and some methods to maintain lobby list, etc. fcbLoc: array[0..MAX_HANDS_COUNT-1] of TComboBox; fedPingLoc: array[0..MAX_HANDS_COUNT-1] of TEdit; procedure RefreshDLLs(); procedure EnableLobbyGUI(aEnable: Boolean); procedure EnableSimulationGUI(aEnable: Boolean); procedure RefreshComboBoxes(aServerClient: TExtAIInfo = nil); procedure UpdateSimStatus(const aLogDLL: String = ''); public procedure Log(const aText: String); end; const CLOSED_LOC = 'Closed'; var Game_form: TGame_form; implementation {$R *.dfm} procedure TGame_form.FormCreate(Sender: TObject); begin // Game log (log every input from Socket) gLog := TExtAILog.Create(Log); gLog.Log('TExtAI_TestBed-Create'); // Game class fGame := TKMGame.Create(UpdateSimStatus); // Game events for GUI fGame.ExtAIMaster.OnAIConfigured := RefreshComboBoxes; fGame.ExtAIMaster.OnAIDisconnect := RefreshComboBoxes; // Define ComboBoxes fedPingLoc[0] := edPingLoc00; fcbLoc[0] := cbLoc00; fedPingLoc[1] := edPingLoc01; fcbLoc[1] := cbLoc01; fedPingLoc[2] := edPingLoc02; fcbLoc[2] := cbLoc02; fedPingLoc[3] := edPingLoc03; fcbLoc[3] := cbLoc03; fedPingLoc[4] := edPingLoc04; fcbLoc[4] := cbLoc04; fedPingLoc[5] := edPingLoc05; fcbLoc[5] := cbLoc05; fedPingLoc[6] := edPingLoc06; fcbLoc[6] := cbLoc06; fedPingLoc[7] := edPingLoc07; fcbLoc[7] := cbLoc07; fedPingLoc[8] := edPingLoc08; fcbLoc[8] := cbLoc08; fedPingLoc[9] := edPingLoc09; fcbLoc[9] := cbLoc09; fedPingLoc[10] := edPingLoc10; fcbLoc[10] := cbLoc10; fedPingLoc[11] := edPingLoc11; fcbLoc[11] := cbLoc11; // Init GUI RefreshDLLs(); // Includes refresh combo boxes EnableLobbyGUI(False); EnableSimulationGUI(False); end; procedure TGame_form.FormDestroy(Sender: TObject); begin gLog.Log('TExtAI_TestBed-Destroy'); fGame.TerminateSimulation(); // Tell thread to properly finish the simulation fGame.WaitFor; // Wait for server to close (this method is called by main thread) fGame.Free; gLog.Free; end; //------------------------------------------------------------------------------ // DLLs //------------------------------------------------------------------------------ // Add new path for scanning DLLs (in game just 1 path with ExtAI folder) procedure TGame_form.btnAddPathClick(Sender: TObject); var K: Integer; Path: String; begin Path := ParamStr(0); if not FileCtrl.SelectDirectory(Path, [sdAllowCreate, sdPerformCreate, sdPrompt],1000) then Exit else for K := 0 to lbPaths.Items.Count - 1 do if (AnsiCompareText(lbPaths.Items[K],Path) = 0) then Exit; lbPaths.Items.Add(Path); RefreshDLLs(); end; // Remove selected path from DLL list procedure TGame_form.btnRemoveClick(Sender: TObject); begin if (lbPaths.ItemIndex >= 0) then lbPaths.Items.Delete(lbPaths.ItemIndex); RefreshDLLs(); end; // Refresh DLL procedure TGame_form.RefreshDLLs(); var K: Integer; Paths: TStringList; begin if (fGame = nil) then Exit; // Get paths Paths := TStringList.Create(); try for K := 0 to lbPaths.Items.Count - 1 do Paths.Add(lbPaths.Items[K]); // Refresh DLLs fGame.ExtAIMaster.DLLs.RefreshList(Paths); finally Paths.Free; end; // Update GUI RefreshComboBoxes(); //lbPaths.Clear; //for K := 0 to fGame.ExtAIMaster.DLLs.Paths.Count - 1 do // lbPaths.Items.Add(fGame.ExtAIMaster.DLLs.Paths[K]); lbDLLs.Clear; for K := 0 to fGame.ExtAIMaster.DLLs.Count - 1 do lbDLLs.Items.Add(fGame.ExtAIMaster.DLLs[K].Name); end; //------------------------------------------------------------------------------ // Server //------------------------------------------------------------------------------ // Start / stop game server via button procedure TGame_form.btnStartServerClick(Sender: TObject); begin // Server is listening => stop listening if fGame.ExtAIMaster.Net.Listening then begin if fGame.GameState <> gsLobby then btnServerStartMapClick(Sender); fGame.ExtAIMaster.Net.StopListening(); prgServer.Style := pbstNormal; EnableLobbyGUI(False); EnableSimulationGUI(False); end // Start server else begin try fGame.ExtAIMaster.Net.StartListening(StrToInt(edServerPort.Text), 'Testing server'); except Log('Invalid port'); Exit; end; // Check if server listen if fGame.ExtAIMaster.Net.Listening then begin prgServer.Style := pbstMarquee; EnableLobbyGUI(True); EnableSimulationGUI(True); end; end; end; //------------------------------------------------------------------------------ // Lobby //------------------------------------------------------------------------------ // Enable lobby GUI procedure TGame_form.EnableLobbyGUI(aEnable: Boolean); var K: Integer; begin btnAutoFill.Enabled := aEnable; for K := Low(fcbLoc) to High(fcbLoc) do fcbLoc[K].Enabled := aEnable; end; // Generic callback for combo boxes procedure TGame_form.cbOnChange(Sender: TObject); begin RefreshComboBoxes(); end; // Refresh list of available ExtAIs in the combo boxes so player can select just 1 instance of the AI for 1 slot procedure TGame_form.RefreshComboBoxes(aServerClient: TExtAIInfo); var ItemFound: Boolean; K,L,Cnt: Integer; AvailableAIs, AvailableDLLs: TStringArray; SelectedAIs: array[0..MAX_HANDS_COUNT-1] of String; begin // Get available ExtAIs and DLLs AvailableAIs := fGame.ExtAIMaster.GetExtAIClientNames(); AvailableDLLs := fGame.ExtAIMaster.GetExtAIDLLNames(); // Filter already selected AI players Cnt := Length(AvailableAIs); for K := Low(fcbLoc) to High(fcbLoc) do begin // Get actual selection (String, name of the ExtAI) SelectedAIs[K] := fcbLoc[K].Items[ fcbLoc[K].ItemIndex ]; // Try to find selection in list of new names ItemFound := False; for L := 0 to Cnt - 1 do if (AnsiCompareText(AvailableAIs[L],SelectedAIs[K]) = 0) then begin // Confirm selection and remove AI from list of possible names ItemFound := True; Cnt := Cnt - 1; AvailableAIs[L] := AvailableAIs[Cnt]; Break; end; for L := Low(AvailableDLLs) to High(AvailableDLLs) do if (AnsiCompareText(AvailableDLLs[L],SelectedAIs[K]) = 0) then ItemFound := True; // Remove selection if not ItemFound then SelectedAIs[K] := ''; end; // Refresh combo boxes [Closed, ActualSelection, PossibleSelection1, PossibleSelection2, ...] for K := Low(fcbLoc) to High(fcbLoc) do begin fcbLoc[K].Items.Clear; fcbLoc[K].Items.Add(CLOSED_LOC); // Closed by default, first index if there is existing already selected AI if (Length(SelectedAIs[K]) > 0) then fcbLoc[K].Items.Add(SelectedAIs[K]); fcbLoc[K].ItemIndex := fcbLoc[K].Items.Count - 1; for L := 0 to Cnt - 1 do fcbLoc[K].Items.Add(AvailableAIs[L]); for L := Low(AvailableDLLs) to High(AvailableDLLs) do if (AnsiCompareText(AvailableDLLs[L],SelectedAIs[K]) <> 0) then fcbLoc[K].Items.Add(AvailableDLLs[L]); end; end; // Auto fill available ExtAIs in the lobby procedure TGame_form.btnAutoFillClick(Sender: TObject); var K: Integer; begin for K := Low(fcbLoc) to High(fcbLoc) do if (fcbLoc[K].ItemIndex = 0) AND (fcbLoc[K].Items.Count > 1) then // Loc is closed and we have available ExtAI begin fcbLoc[K].ItemIndex := 1; RefreshComboBoxes(); // Refresh GUI end; end; //------------------------------------------------------------------------------ // Simulation //------------------------------------------------------------------------------ // Enable simulation GUI procedure TGame_form.EnableSimulationGUI(aEnable: Boolean); begin btnStartServer.Caption := 'Start Server'; if aEnable then btnStartServer.Caption := 'Stop Server'; btnServerStartMap.Enabled := aEnable; btnSendEvent.Enabled := aEnable; btnSendState.Enabled := aEnable; end; // Start the map (simulation of the game) procedure TGame_form.btnServerStartMapClick(Sender: TObject); var K, Cnt: Integer; AIs: TStringArray; begin if (fGame.GameState = gsLobby) then begin // Get AI players in the lobby SetLength(AIs,MAX_HANDS_COUNT); Cnt := 0; for K := Low(fcbLoc) to High(fcbLoc) do begin // Get actual selection AIs[Cnt] := fcbLoc[K].Items[ fcbLoc[K].ItemIndex ]; Cnt := Cnt + Byte((Length(AIs[Cnt]) > 0) AND (AnsiCompareText(AIs[Cnt],CLOSED_LOC) <> 0)); end; SetLength(AIs,Cnt); // Start / stop the simulation with specific AI players fGame.StartGame(AIs); btnServerStartMap.Caption := 'Stop Map'; end else if (fGame.GameState = gsPlay) then begin btnServerStartMap.Caption := 'Start Map'; fGame.EndGame(); end else begin btnServerStartMap.Caption := 'Start Map'; end end; // Test event procedure TGame_form.btnSendEventClick(Sender: TObject); begin fGame.SendEvent; end; // Update simulation status (ping, etc.) procedure TGame_form.UpdateSimStatus(const aLogDLL: String = ''); var K,L: Integer; AvailableAIs: TStringArray; begin // Add log if exists if (Length(aLogDLL) > 0) then Log(Format('DLL: %s',[aLogDLL])); // Get available AI players AvailableAIs := fGame.ExtAIMaster.GetExtAIClientNames(); // Update ping for K := Low(fcbLoc) to High(fcbLoc) do begin fedPingLoc[K].Text := '0'; for L := Low(AvailableAIs) to High(AvailableAIs) do if (AnsiCompareText(AvailableAIs[L], fcbLoc[K].Items[ fcbLoc[K].ItemIndex ]) = 0) then fedPingLoc[K].Text := IntToStr(fGame.ExtAIMaster.AIs[L].ServerClient.NetPing); end; // Update Start simulation button case fGame.GameState of gsLobby, gsEnd: btnServerStartMap.Caption := 'Start Map'; gsLoad, gsPlay: btnServerStartMap.Caption := 'Stop Map'; else begin end; end; end; //------------------------------------------------------------------------------ // Logs //------------------------------------------------------------------------------ // Log to console procedure TGame_form.Log(const aText: String); begin with reLog.SelAttributes do begin if ContainsText(aText, 'Create' ) then Color := clGreen else if ContainsText(aText, 'Destroy' ) then Color := clRed else if ContainsText(aText, 'Server Status' ) then Color := clPurple else if ContainsText(aText, 'ExtAIInfo' ) then Color := clMedGray else if ContainsText(aText, 'TKMGame-Execute') then Color := clNavy; end; reLog.Lines.Add(aText); SendMessage(reLog.handle, WM_VSCROLL, SB_BOTTOM, 0); end; end.
unit VoxelRendererWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FiveControl; type TVoxelRendererForm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } fMapView : TFiveControl; public { Public declarations } end; var VoxelRendererForm: TVoxelRendererForm; implementation {$R *.DFM} uses LocalCacheManager; const CachePath = 'C:\Work\Five\Release\Cache'; procedure TVoxelRendererForm.FormCreate(Sender: TObject); var Agents : TWorldAgents; begin fMapView := TFiveControl.Create(Self); with fMapView do begin Align := alClient; ZoomLevel := 3; // ord(zr32x64); end; GetWorldAgents(Agents); Agents.Manager.Load(CachePath); Agents.Map.InitMap; fMapView.Document := Agents.Document; end; procedure TVoxelRendererForm.FormShow(Sender: TObject); begin fMapView.Parent := Self; end; procedure TVoxelRendererForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ADD: fMapView.ZoomIn; VK_SUBTRACT: fMapView.ZoomOut; end; end; end.
unit UnitDataInterfaces; interface uses System.Generics.Collections, UnitCustomer, UnitOrder, UnitOrderItem, UnitProduct, FireDAC.Comp.Client; type IDataConnection = Interface ['{9281BB97-F337-4765-98BE-62B3737FF7D8}'] function GetFDConn : TFDConnection; function ConnectToDB : Boolean; property FDConn : TFDConnection read GetFDConn; End; ICustomerService = Interface ['{D9537CBD-367D-44A1-907E-16F0EF6F7242}'] function GetCustomers : TList<TCustomer>; function UpdateCustomers : Integer; function DeleteCustomers : Integer; End; IOrderService = Interface ['{C547B6F9-D66A-43D5-8057-26C1B3AD3FA8}'] function GetOrders : Tlist<TOrder>; function UpdateOrders : Integer; function DeleteOrders : Integer; function GetOrderItems : Tlist<TOrderItem>; function UpdateOrderItems : Integer; function DeleteOrderItems : Integer; End; IProductService = Interface ['{00A0F173-9435-43C7-9FD0-D3A6820D4D10}'] function GetProducts : Tlist<TProduct>; function UpdateProducts : Integer; function DeleteProducts : Integer; End; implementation end.
unit BittrexAPI; interface uses Classes, System.generics.collections, REST.Client; type TTicker = class(TObject) public datetime: TDateTime; Bid, Ask, Last, Ant: double; end; TOrderHistory = record OrderUuid: string; Exchange: string; TimeStamp: TDateTime; OrderType: string; Limit: double; Quantity: double; Commision: double; Price: double; PricePerUnit: double; Cost: double; IsConditional: boolean; Condition: string; ConditionTarget: string; InmediateOrCancel: boolean; end; TOrdersHistory = class(Tlist<TOrderHistory>) public // procedure Exchanges(const aExchanges: TStringList); // function GetProfit(const aMarket: string): double; // function GetLastOrderCost(const aMarket: string): double; end; TBalance = record Currency: string; Balance: double; Available: double; Pending: double; CryptoAddress: string; Requested: boolean; end; TBalances = class(Tlist<TBalance>) public function Balance(const aCurrency: string): TBalance; end; TMarket = class(TObject) private fTicker: TTicker; function GetLastValue: double; function GetBump: double; function GetAsk: double; function GetBid: double; function GetAntValue: double; function GetTimer: TDateTime; public MarketCurrency: string; BaseCurrency: string; MarketCurrencyLong: string; BaseCurrencyLong: string; MinTradeSize: string; // cambiar; MarketName: string; IsActive: boolean; Created: TDateTime; Notice: string; IsSponsored: string; LogoUrl: string; // Refresh Ticker information // function RefreshTicker: boolean; constructor Create; destructor Destroy; override; property Timer: TDateTime read GetTimer; property LastValue: double read GetLastValue; property Bid: double read GetBid; property Ask: double read GetAsk; property Bump: double read GetBump; property AntValue: double read GetAntValue; end; TMarkets = class(Tlist<TMarket>) function GetMarket(const aMarket: string): TMarket; end; TBittrexApi = class(TComponent) private fapikey: string; fsecret: string; aRESTClient: TRESTClient; aRESTRequest: TRESTRequest; aRESTResponse: TRESTResponse; public constructor Create(Owner: TComponent); override; function GetMarkets(var aMarkets: TMarkets): boolean; function GetTicker(const aMarket: string; aTicker: TTicker): boolean; function GetBalances(var aBalances: TBalances): boolean; function GetOrderHistory(var aOrdersHistory: TOrdersHistory; aMarket: string = ''): boolean; property APIKEY: string read fapikey write fapikey; property SECRET: string read fsecret write fsecret; end; implementation uses dialogs, IPPeerClient, System.SysUtils, REST.Types, System.Json, REST.Json, flcHash; constructor TBittrexApi.Create(Owner: TComponent); begin aRESTClient := TRESTClient.Create('https://bittrex.com/api/v1.1/public/'); aRESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,'; aRESTClient.AcceptCharset := 'UTF-8, *;q=0.8'; aRESTResponse := TRESTResponse.Create(self); aRESTResponse.ContentType := 'application/json'; aRESTRequest := TRESTRequest.Create(self); aRESTRequest.Client := aRESTClient; aRESTRequest.Response := aRESTResponse; end; constructor TMarket.Create; begin fTicker := TTicker.Create; end; destructor TMarket.Destroy; begin fTicker.Free; inherited; end; function TMarket.GetAntValue: double; begin result := fTicker.Ant; end; function TMarket.GetAsk: double; begin result := fTicker.Ask; end; function TMarket.GetBid: double; begin result := fTicker.Bid; end; function TMarket.GetBump: double; begin result := ((LastValue * 100) / fTicker.Ant) - 100; end; function TMarket.GetLastValue: double; begin result := fTicker.Last; end; function TMarket.GetTimer: TDateTime; begin result := fTicker.datetime; end; function TBittrexApi.GetBalances(var aBalances: TBalances): boolean; var aParam: TRESTRequestParameter; ajsonBalances: TJsonArray; aBalance: TBalance; k: integer; begin aRESTClient.BaseURL := 'https://bittrex.com/api/v1.1/account/getbalances'; aRESTRequest.Params.Clear; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'apikey'; aParam.Value := APIKEY; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'nonce'; aParam.Value := '0'; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkHTTPHEADER; aParam.name := 'apisign'; aParam.Value := SHA512DigestToHexW(CalcHMAC_SHA512(SECRET, format('%s?apikey=%s&nonce=0', [aRESTClient.BaseURL, APIKEY]))); result := false; aRESTRequest.Execute; if aRESTRequest.Response.StatusCode = 200 then begin if aRESTResponse.JSONValue.GetValue<string>('success') = 'true' then begin ajsonBalances := aRESTResponse.JSONValue.GetValue<TJsonArray>('result'); for k := 0 to ajsonBalances.Count - 1 do begin // Aņadimos solo los balances donde tengamos monedas if ajsonBalances.Items[k].GetValue<string>('Available').ToDouble > 0 then begin aBalance.Currency := ajsonBalances.Items[k].GetValue<string> ('Currency'); aBalance.Balance := ajsonBalances.Items[k].GetValue<string> ('Balance').ToDouble; aBalance.Available := ajsonBalances.Items[k].GetValue<string> ('Available').ToDouble; aBalance.Pending := ajsonBalances.Items[k].GetValue<string> ('Pending').ToDouble; aBalance.CryptoAddress := ajsonBalances.Items[k].GetValue<string> ('CryptoAddress'); // aBalance.Requested := ajsonBalances.Items[k].GetValue<string> ('Requested').ToBoolean; aBalances.Add(aBalance); end; end; result := true; end; end; end; function TBittrexApi.GetMarkets(var aMarkets: TMarkets): boolean; var r: TJsonArray; k: integer; aMarket: TMarket; begin result := true; aMarkets.Clear; aRESTClient.BaseURL := 'https://bittrex.com/api/v1.1/public/getmarkets'; aRESTRequest.Params.Clear; aRESTRequest.Execute; if aRESTRequest.Response.StatusCode = 200 then begin if aRESTResponse.JSONValue.GetValue<string>('success') = 'true' then begin result := true; r := aRESTResponse.JSONValue.GetValue<TJsonArray>('result'); for k := 0 to r.Count - 1 do begin aMarket := TMarket.Create; aMarket.BaseCurrency := r.Items[k].GetValue<string>('BaseCurrency'); if aMarket.BaseCurrency = 'BTC' then begin aMarket.MarketCurrency := r.Items[k].GetValue<string> ('MarketCurrency'); aMarket.MarketCurrencyLong := r.Items[k].GetValue<string> ('MarketCurrencyLong'); aMarket.BaseCurrencyLong := r.Items[k].GetValue<string> ('BaseCurrencyLong'); aMarket.MinTradeSize := r.Items[k].GetValue<string>('MinTradeSize'); aMarket.MarketName := r.Items[k].GetValue<string>('MarketName'); aMarket.IsActive := r.Items[k].GetValue<boolean>('IsActive'); // aMarket.Created := r.Items[k].GetValue<tdaatetime>('Created'); aMarket.Notice := r.Items[k].GetValue<string>('Notice'); aMarket.IsSponsored := r.Items[k].GetValue<string>('IsSponsored'); aMarket.LogoUrl := r.Items[k].GetValue<string>('LogoUrl'); aMarket.IsSponsored := r.Items[k].GetValue<string>('IsSponsored'); aMarkets.Add(aMarket); end; end; end; end; end; function TBittrexApi.GetOrderHistory(var aOrdersHistory: TOrdersHistory; aMarket: string = ''): boolean; var aParam: TRESTRequestParameter; ajsonOrdersHistory: TJsonArray; aOrderHistory: TOrderHistory; k: integer; begin aRESTClient.BaseURL := 'https://bittrex.com/api/v1.1/account/getorderhistory'; aRESTRequest.Params.Clear; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'apikey'; aParam.Value := APIKEY; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'nonce'; aParam.Value := '0'; if aMarket <> '' then begin aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'market'; aParam.Value := aMarket; end; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkHTTPHEADER; aParam.name := 'apisign'; if aMarket <> '' then begin aParam.Value := SHA512DigestToHexW(CalcHMAC_SHA512(SECRET, format('https://bittrex.com/api/v1.1/account/getorderhistory?apikey=%s&nonce=0&market=%s', [APIKEY, aMarket]))); end else begin aParam.Value := SHA512DigestToHexW(CalcHMAC_SHA512(SECRET, format('https://bittrex.com/api/v1.1/account/getorderhistory?apikey=%s&nonce=0', [APIKEY]))); end; result := false; aRESTRequest.Execute; if aRESTRequest.Response.StatusCode = 200 then begin if aRESTResponse.JSONValue.GetValue<string>('success') = 'true' then begin ajsonOrdersHistory := aRESTResponse.JSONValue.GetValue<TJsonArray> ('result'); for k := 0 to ajsonOrdersHistory.Count - 1 do begin aOrderHistory.OrderUuid := ajsonOrdersHistory.Items[k].GetValue<string> ('OrderUuid'); aOrderHistory.Exchange := ajsonOrdersHistory.Items[k].GetValue<string> ('Exchange'); aOrderHistory.OrderType := ajsonOrdersHistory.Items[k].GetValue<string> ('OrderType'); aOrderHistory.Quantity := ajsonOrdersHistory.Items[k].GetValue<string> ('Quantity').ToDouble - ajsonOrdersHistory.Items[k].GetValue<string> ('QuantityRemaining').ToDouble; aOrderHistory.Commision := ajsonOrdersHistory.Items[k].GetValue<string> ('Commission').ToDouble; aOrderHistory.Price := ajsonOrdersHistory.Items[k].GetValue<string> ('Price').ToDouble; aOrderHistory.PricePerUnit := ajsonOrdersHistory.Items[k] .GetValue<string>('PricePerUnit').ToDouble; if aOrderHistory.OrderType = 'LIMIT_BUY' then aOrderHistory.Cost := -aOrderHistory.Price - aOrderHistory.Commision else aOrderHistory.Cost := aOrderHistory.Price - aOrderHistory.Commision; aOrdersHistory.Add(aOrderHistory); end; result := true; end; end; end; function TBittrexApi.GetTicker(const aMarket: string; aTicker: TTicker) : boolean; var r: TJsonValue; aParam: TRESTRequestParameter; begin aRESTClient.BaseURL := 'https://bittrex.com/api/v1.1/public/getticker'; aRESTRequest.Params.Clear; aParam := aRESTRequest.Params.AddItem; aParam.Kind := pkGETorPOST; aParam.name := 'market'; aParam.Value := aMarket; result := false; try aRESTRequest.Execute; if aRESTRequest.Response.StatusCode = 200 then begin if aRESTResponse.JSONValue.GetValue<string>('success') = 'true' then begin r := aRESTResponse.JSONValue.GetValue<TJsonValue>('result'); aTicker.datetime := now; aTicker.Bid := r.GetValue<string>('Bid').ToDouble; aTicker.Ask := r.GetValue<string>('Ask').ToDouble; aTicker.Last := r.GetValue<string>('Last').ToDouble; result := true; end; end; except result := false; end; end; function TBalances.Balance(const aCurrency: string): TBalance; var I: integer; begin for I := 0 to Count - 1 do if Items[I].Currency = aCurrency then result := Items[I]; end; { TMarkets } function TMarkets.GetMarket(const aMarket: string): TMarket; var I: integer; begin result := nil; for I := 0 to Count - 1 do if Items[I].MarketName = aMarket then result := Items[I]; end; initialization FormatSettings.DecimalSeparator := '.'; end.
unit GX_Replace; interface uses Classes, GX_GrepBackend; // Replace all matches in all files function ReplaceAll(ResultList: TStrings; GrepSettings: TGrepSettings): Integer; // Replace all matches in a single file function ReplaceAllInFiles(FileResult: TFileResult; GrepSettings: TGrepSettings): Integer; // Replace all matches on a single line function ReplaceLine(LineResult: TLineResult; GrepSettings: TGrepSettings): Integer; implementation uses SysUtils, Controls, Dialogs, ToolsAPI, GX_OtaUtils, GX_GenericUtils, RegExpr; type ESkipFileReplaceException = class(Exception); resourcestring SFileChangedAbort = '%s' + sLineBreak + 'has changed since it was searched. Replacement aborted.' + sLineBreak + 'Expected: %s' + sLineBreak + 'Found: %s'; SUnableToOpen = 'Unable to open '; SNoOpenForms = 'Replacing strings in open forms is not possible. Please close the form first.'; SFileSkipped = 'The following file will be skipped:'; // Replaces the string between SPos and EPos with the replace string from TGrepSettings function ReplacePatternInString(CurrentLine: TLineResult; GrepSettings: TGrepSettings): string; var i: Integer; FindPos: Integer; FindLen: Integer; CurrentMatch: TMatchResult; begin Result := CurrentLine.Line; for i := CurrentLine.Matches.Count - 1 downto 0 do begin CurrentMatch := CurrentLine.Matches.Items[i]; FindPos := CurrentMatch.SPos; FindLen := CurrentMatch.EPos - CurrentMatch.SPos + 1; Delete(Result, FindPos, FindLen); Insert(GrepSettings.Replace, Result, FindPos); CurrentMatch.ShowBold := False; end; end; function ReplacePatternInStringWithRegEx(CurrentLine: TLineResult; GrepSettings: TGrepSettings; RegEx: TRegExpr): string; var i: Integer; begin Result := RegEx.Replace(CurrentLine.Line, GrepSettings.Replace, True); for i := CurrentLine.Matches.Count - 1 downto 0 do CurrentLine.Matches[i].ShowBold := False; end; function ReplaceAll(ResultList: TStrings; GrepSettings: TGrepSettings): Integer; var i: Integer; Replaced: Integer; begin Result := 0; for i := 0 to ResultList.Count - 1 do begin if ResultList.Objects[i] is TFileResult then begin Replaced := ReplaceAllInFiles(ResultList.Objects[i] as TFileResult, GrepSettings); Inc(Result, Replaced); end; end; end; function InternalReplace(LineMode: Boolean; ALineResult: TLineResult; AFileResult: TFileResult; GrepSettings: TGrepSettings): Integer; var InMemory: Boolean; TempString: string; MatchFile: string; TempFile: TGXUnicodeStringList; LineResult : TLineResult; Module: IOTAModule; EditWriter: IOTAEditWriter; SourceEditor: IOTASourceEditor; RegEx: TRegExpr; WasBinary: Boolean; procedure GetFileLines; begin if InMemory then begin if IsForm(MatchFile) then raise ESkipFileReplaceException.Create(SNoOpenForms); Module := GxOtaGetModule(GxOtaGetBaseModuleFileName(MatchFile)); if not Assigned(Module) then raise Exception.Create(SUnableToOpen + MatchFile); SourceEditor := GxOtaGetSourceEditorFromModule(Module, MatchFile); if not Assigned(SourceEditor) then raise Exception.Create(SUnableToOpen + MatchFile); GxOtaLoadFileToUnicodeStrings(SourceEditor.FileName, TempFile, WasBinary); end else GxOtaLoadFileToUnicodeStrings(MatchFile, TempFile, WasBinary); end; procedure DoReplacement; var i: Integer; FileLine: string; begin if LineMode then begin i := ALineResult.LineNo; Assert(TempFile.Count >= (LineResult.LineNo - 1)); FileLine := TempFile.Strings[LineResult.LineNo - 1]; if LineResult.Line <> FileLine then raise Exception.CreateFmt(SFileChangedAbort, [MatchFile, LineResult.Line, FileLine]); if GrepSettings.RegEx then TempString := ReplacePatternInStringWithRegEx(LineResult, GrepSettings, RegEx) else TempString := ReplacePatternInString(LineResult, GrepSettings); TempFile.Strings[i -1] := TempString; Inc(Result, LineResult.Matches.Count); end else begin for i := AFileResult.Count - 1 downto 0 do begin LineResult := AFileResult.Items[i]; Inc(Result, LineResult.Matches.Count); Assert(TempFile.Count >= (LineResult.LineNo - 1)); FileLine := TempFile.Strings[LineResult.LineNo - 1]; if LineResult.Line <> FileLine then raise Exception.CreateFmt(SFileChangedAbort, [MatchFile, LineResult.Line, FileLine]); if GrepSettings.RegEx then TempString := ReplacePatternInStringWithRegEx(LineResult, GrepSettings, RegEx) else TempString := ReplacePatternInString(LineResult, GrepSettings); TempFile.Strings[LineResult.LineNo - 1] := TempString; end; end; end; procedure WriteResults; var FormFile: TFileStream; FormSource: TStringStream; begin if InMemory then begin EditWriter := GxOtaGetEditWriterForSourceEditor(SourceEditor); EditWriter.DeleteTo(MaxInt); // RemoveLastEOL is necessary because TStringList.Text adds an extra CRLF on the end EditWriter.Insert(PAnsiChar(ConvertToIDEEditorString(RemoveTrailingEOL(TempFile.Text)))); EditWriter := nil; Module := nil; SourceEditor := nil; end else begin if IsForm(MatchFile) and WasBinary then begin FormFile := nil; FormSource := TStringStream.Create(TempFile.Text); try FormSource.Seek(0, soFromBeginning); FormFile := TFileStream.Create(MatchFile, fmOpenWrite or fmShareDenyWrite); FormFile.Seek(0, soFromBeginning); ObjectTextToResource(FormSource, FormFile); FormFile.Size; finally FreeAndNil(FormSource); FreeAndNil(FormFile); end; end else TempFile.SaveToFile(MatchFile); end; end; begin Result := 0; WasBinary := False; if LineMode then begin LineResult := ALineResult; MatchFile := TFileResult(LineResult.Collection).FileName; end else MatchFile := AFileResult.FileName; RegEx := nil; TempFile := TGXUnicodeStringList.Create; try if GrepSettings.RegEx then begin RegEx := TRegExpr.Create; RegEx.Expression := GrepSettings.Pattern; RegEx.ModifierG := True; RegEx.ModifierI := not GrepSettings.CaseSensitive; RegEx.Compile; end; InMemory := GxOtaIsFileOpen(MatchFile, True); try GetFileLines; except on E: ESkipFileReplaceException do begin E.Message := E.Message + sLineBreak + SFileSkipped +sLineBreak+ MatchFile; if MessageDlg(E.Message, mtWarning, [mbOK, mbCancel], 0) = mrCancel then Abort else Exit; end; end; DoReplacement; WriteResults; finally FreeAndNil(RegEx); FreeAndNil(TempFile); end; end; function ReplaceAllInFiles(FileResult: TFileResult; GrepSettings: TGrepSettings): Integer; begin Result := InternalReplace(False, nil, FileResult, GrepSettings); end; function ReplaceLine(LineResult: TLineResult; GrepSettings: TGrepSettings): Integer; begin Result := InternalReplace(True, LineResult, nil, GrepSettings); end; end.
unit Machine; interface uses DataTypes, Crt, Generics, Streams, Graph; type TMachineState = (msOk, msError, msUserStop, msDataEnd); PMachine = ^TMachine; TMachine = object(TGeneric) private State: TMachineState; SendData: TSendData; Zoom: Integer; CurrentX, CurrentY: Integer; procedure ResetPos; procedure Slow; procedure Stop; procedure Fast; procedure Move(ADeltaX, ADeltaY: Integer); procedure MoveBack(ADeltaX, ADeltaY: Integer); function StartMove: TMachineState; function MoveStep: TMachineState; function GetMachineState: TMachineState; public constructor Create; destructor Destroy; virtual; procedure LoadDataFromStream(AStream: PStream); procedure Run; virtual; end; implementation constructor TMachine.Create; begin inherited Create; SendData.Create; CurrentX := 0; CurrentY := 0; State := msOk; end; destructor TMachine.Destroy; begin SendData.Destroy; inherited Destroy; end; procedure TMachine.LoadDataFromStream(AStream: PStream); begin SendData.Clear; SendData.LoadDataFromStream(AStream); SendData.ProcessDistanceJumps(50); { CurrentX := 0; CurrentY := 0; } CurrentX := - SendData.MinX; CurrentY := - SendData.MinY; end; procedure TMachine.ResetPos; begin CurrentX := - SendData.MinX; CurrentY := - SendData.MinY; end; procedure TMachine.Slow; begin end; procedure TMachine.Stop; begin end; procedure TMachine.Fast; begin end; procedure TMachine.Move(ADeltaX, ADeltaY: Integer); var NewX, NewY: Longint; begin NewX := CurrentX + ADeltaX; NewY := CurrentY + ADeltaY; Line(CurrentX, CurrentY, NewX, NewY); CurrentX := NewX; CurrentY := NewY; end; procedure TMachine.MoveBack(ADeltaX, ADeltaY: Integer); var NewX, NewY: Longint; begin NewX := CurrentX - ADeltaX; NewY := CurrentY - ADeltaY; Line(CurrentX, CurrentY, NewX, NewY); CurrentX := NewX; CurrentY := NewY; end; function TMachine.GetMachineState: TMachineState; begin State := msOk; GetMachineState := State; end; function TMachine.StartMove: TMachineState; var DeltaX, DeltaY: Integer; Mode: Byte; begin if (GetMachineState = msOk) then begin if (SendData.GetFirst(Mode, DeltaX, DeltaY) and (Mode = modReset)) then ResetPos else State := msDataEnd; end; StartMove := State; end; function TMachine.MoveStep: TMachineState; var DeltaX, DeltaY: Integer; Mode: Byte; begin if (GetMachineState = msOk) then begin if SendData.GetNext(Mode, DeltaX, DeltaY) then begin case Mode of modNormal: begin Fast; Move(DeltaX, DeltaY); end; modSlow: begin Slow; Move(DeltaX, DeltaY); end; modStop: begin Stop; end; end; State := msOk; end else State := msDataEnd; end; MoveStep := State; end; procedure TMachine.Run; {var DeltaX, DeltaY: Integer; TotalDeltaX, TotalDeltaY: Integer; Mode: Byte; I: Integer;} begin if StartMove = msOk then while MoveStep = msOk do; {if (SendData.GetFirst(Mode, DeltaX, DeltaY) and (Mode = modReset)) then begin SetColor(7); while SendData.GetNext(Mode, DeltaX, DeltaY) do begin case Mode of modNormal: begin Fast; Move(DeltaX, DeltaY); end; modSlow: begin Slow; Move(DeltaX, DeltaY); end; modStop: begin Stop; end; end; if KeyPressed then begin while KeyPressed do ReadKey; SetColor(5); SendData.GetCurrent( Mode, DeltaX, DeltaY); TotalDeltaX := 0; TotalDeltaY := 0; I := 200; repeat I := I - 1; TotalDeltaX := TotalDeltaX + DeltaX; TotalDeltaY := TotalDeltaY + DeltaY; SendData.GetPrev( Mode, DeltaX, DeltaY); until ((SendData.IsFirst) or (I = 0)); MoveBack(TotalDeltaX, TotalDeltaY); SetColor(7); end; if SendData.IsFirst then begin Sound(2000); Delay(100); NoSound; end; if SendData.IsLast then begin Sound(3000); Delay(100); NoSound; end; end; end;} end; end.
{ For playing through the internet via FICS - Free Internet Chess Server Based on this article: http://blog.mekk.waw.pl/archives/7-How-to-write-a-FICS-bot-part-I.html FICS website: http://www.freechess.org/ } unit mod_fics; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, Forms, Controls, ExtCtrls, maskedit, lTelnetex, lnet, sorokinregexpr, // Rename to regexpr when FPC 2.8 comes with this chessmodules, chessgame, chessdrawer; type { TFICSChessModule } TFICSChessModule = class(TChessModule) private radioConnectionType: TRadioGroup; textPassword: TStaticText; editPassword: TMaskEdit; textSecondPlayerName: TStaticText; editSecondPlayerName: TEdit; public SecondPlayerName: string; TelnetComm: TLTelnetClientEx; FICS_HOST: string; FICS_PORT: Integer; FICS_USER: string; FICS_PASSWORD: string; constructor Create(); override; destructor Destroy; override; procedure CreateUserInterface(); override; procedure ShowUserInterface(AParent: TWinControl); override; procedure HideUserInterface(); override; procedure FreeUserInterface(); override; procedure PrepareForGame(); override; function GetSecondPlayerName(): string; override; procedure HandleOnMove(AFrom, ATo: TPoint); override; procedure HandleOnTimer(); override; procedure HandleOnDebugOut(AStr: string); end; const FICS_LineEnding = #10; OPEN_TIMEOUT = 1000000; PROTECT_LOGOUT_FREQ = 45 * 60 * 1000; // Frequency to issue commands to avoid disconnection, in miliseconds implementation { TFICSChessModule } constructor TFICSChessModule.Create; begin inherited Create; TelnetComm := TLTelnetClientEx.Create(nil); TelnetComm.OnDebugOut := @HandleOnDebugOut; (* $telnet = new Net::Telnet( Timeout => $OPEN_TIMEOUT, Binmode => 1, Errmode => 'die', );*) Name := 'mod_fics.pas'; SelectionDescription := 'Play online - Free Internet Chess Server'; PlayingDescription := 'Playing online - Free Internet Chess Server'; Kind := cmkInternet; FICS_HOST := 'freechess.org'; FICS_PORT := 5000; FICS_USER := 'FPChess'; FICS_PASSWORD := ''; end; destructor TFICSChessModule.Destroy; begin TelnetComm.Free; inherited Destroy; end; procedure TFICSChessModule.CreateUserInterface; begin radioConnectionType := TRadioGroup.Create(nil); radioConnectionType.SetBounds(10, 10, 300, 100); radioConnectionType.Caption := 'FICS Connection Type'; radioConnectionType.Items.Add('Wait for a friend to connect to me'); radioConnectionType.Items.Add('Connect to a friend (he needs to be waiting for the connection)'); radioConnectionType.ItemIndex := 0; textPassword := TStaticText.Create(nil); textPassword.SetBounds(10, 110, 180, 20); textPassword.Caption := 'Your FICS Password'; editPassword := TMaskEdit.Create(nil); editPassword.SetBounds(200, 110, 150, 20); editPassword.Text := ''; textSecondPlayerName := TStaticText.Create(nil); textSecondPlayerName.SetBounds(10, 130, 180, 40); textSecondPlayerName.Caption := 'FICS Login of the other player'; editSecondPlayerName := TEdit.Create(nil); editSecondPlayerName.SetBounds(200, 130, 150, 40); editSecondPlayerName.Text := 'fpchesse'; end; procedure TFICSChessModule.ShowUserInterface(AParent: TWinControl); begin radioConnectionType.Parent := AParent; textPassword.Parent := AParent; editPassword.Parent := AParent; textSecondPlayerName.Parent := AParent; editSecondPlayerName.Parent := AParent; end; procedure TFICSChessModule.HideUserInterface(); begin radioConnectionType.Parent := nil; textPassword.Parent := nil; editPassword.Parent := nil; textSecondPlayerName.Parent := nil; editSecondPlayerName.Parent := nil; end; procedure TFICSChessModule.FreeUserInterface; begin radioConnectionType.Free; textPassword.Free; editPassword.Free; textSecondPlayerName.Free; editSecondPlayerName.Free; end; procedure TFICSChessModule.PrepareForGame; var lResult, WaitTerminated: Boolean; lMsg: string; begin FICS_USER := vChessGame.PlayerName; FICS_PASSWORD := editPassword.Text; // SecondPlayerName := editSecondPlayerName.Text; ChessModuleDebugLn('[TFICSChessModule.PrepareForGame]'); // Opening telnet connection. This is what happens when you issue telnet freechess.org 5000. lResult := TelnetComm.Connect(FICS_HOST, FICS_PORT); if not lResult then begin ChessModuleDebugLn('Failed to connect to FICS'); Exit; end; repeat TelnetComm.CallAction; // repeat this to get info Application.ProcessMessages; Sleep(10); until TelnetComm.Connected; // wait until timeout or we actualy connected ChessModuleDebugLn('Connected to FICS'); // If $FICS_PASSWORD is given, we peform normal full login (give username and password). FICS is standard enough to have Net::Telnet::login routine perform this process properly. if FICS_PASSWORD <> '' then begin //$telnet->login(Name => $FICS_USER, Password => $FICS_PASSWORD); // $username = $FICS_USER; // print STDERR "Successfully logged as user $FICS_USER\n" if $VERBOSE; end // Now let's go to the guest login. Again, try logging to FICS via telnet as guest to understand what we are testing for here. else begin { $telnet->waitfor( Match => '/login[: ]*$/i', Match => '/username[: ]*$/i', Timeout => $OPEN_TIMEOUT); $telnet->print($FICS_USER); } TelnetComm.WaitFor( '.*login:.*', '.*username:.*', OPEN_TIMEOUT); // ... and we send our username once prompted. //ChessModuleDebugLn('Found the login!!!'); ChessModuleDebugLn('Sending: ' + FICS_USER); TelnetComm.SendMessage(FICS_USER + FICS_LineEnding); // Now we read obtained lines scanning for some patterns. TelnetComm.WaitFor( '.*Press return to enter.*', '', OPEN_TIMEOUT); TelnetComm.SendMessage(FICS_LineEnding); (*if ($line =~ /("[^"]*" is a registered name|\S+ is already logged in)/) { die "Can not login as $FICS_USER: $1\n"; } Bad luck, we picked the name used by somebody, it is not possible to login as guest with this nick. *) (* After accepting guest login we may face two things. First, FICS may accept our login and send us a message like Starting FICS session as BotTutorial. This means everything is OK and we can go on. Alternatively, FICS may notice another guest using the same name, in such case it will tell us something like BotTutorial is already logged in and will disconnect. print STDERR "Successfully logged as guest $username\n" if $VERBOSE; my($pre, $match) = $telnet->waitfor( Match => "/Starting FICS session as ([a-zA-Z0-9]+)/", Match => "/\\S+ is already logged in/", Timeout => $OPEN_TIMEOUT); if ( $match =~ /Starting FICS session as ([a-zA-Z0-9]+)/ ) { $username = $1; } else { die "Can not login as $FICS_USER: $match\n"; } } *) TelnetComm.WaitFor( '.*Starting FICS session as.*', '', OPEN_TIMEOUT); end; // Remove those annoying message of people seeking chess adversaries TelnetComm.WaitFor( '.*fics%.*', '', OPEN_TIMEOUT); ChessModuleDebugLn('Sending: set seek 0'); TelnetComm.SendMessage('set seek 0' + FICS_LineEnding); // Set the style TelnetComm.WaitFor( '.*fics%.*', '', OPEN_TIMEOUT); ChessModuleDebugLn('Sending: set style 11'); TelnetComm.SendMessage('set style 11' + FICS_LineEnding); // Wait for a match if radioConnectionType.ItemIndex = 0 then begin vChessGame.FirstPlayerIsWhite := False; // Challenge: GuestZMYL (----) fpchess (----) unrated blitz 2 12. // You can "accept" or "decline", or propose different parameters. TelnetComm.WaitFor( '.*You can "accept" or "decline", or propose different parameters*', '', OPEN_TIMEOUT); ChessModuleDebugLn('Sending: accept'); TelnetComm.SendMessage('accept' + FICS_LineEnding); // You accept the match offer from GuestZMYL. TelnetComm.WaitFor( '.*You accept the match offer from*', '', OPEN_TIMEOUT); end // Challenge a partner else begin TelnetComm.WaitFor( '.*fics%.*', '', OPEN_TIMEOUT); lMsg := 'match ' + editSecondPlayerName.Text + ' 60 White'; ChessModuleDebugLn('Sending: ' + lMsg); TelnetComm.SendMessage(lMsg + FICS_LineEnding); // fpchess accepts the match offer. TelnetComm.WaitFor( '.*accepts the match offer*', '', OPEN_TIMEOUT); end; end; function TFICSChessModule.GetSecondPlayerName: string; begin // Result := SecondPlayerName; end; // If a move came, it is because the local player did a move // so send this move procedure TFICSChessModule.HandleOnMove(AFrom, ATo: TPoint); var lMsg: String; begin lMsg := Format('%s-%s', [TChessGame.BoardPosToChessCoords(AFrom), TChessGame.BoardPosToChessCoords(ATo)]); ChessModuleDebugLn('Sending: ' + lMsg); TelnetComm.SendMessage(lMsg + FICS_LineEnding); // Wait until it shows our move TelnetComm.WaitFor( '.*[PRNBQK]/[abcdefgh][0123456789]-[abcdefgh][0123456789].*', '', OPEN_TIMEOUT); end; // listen for moves procedure TFICSChessModule.HandleOnTimer; var lIndex: Integer; lAnimation: TChessMoveAnimation; lFrom, lTo: TPoint; lMoveStr: String; begin // Example output in style 11 // #@#086GuestZMYL :fpchess *RNBQKBNR PPP PP P PP p p ppp ppprnbqkbnr003B3939-1628-0163P/a2-a4(1:03)@#@ lIndex := TelnetComm.WaitFor( '.*[PRNBQK]/[abcdefgh][0123456789]-[abcdefgh][0123456789].*', '', 0); // if TelnetComm.LastMsg <> '' then // lIndex := lIndex; if lIndex = 0 then begin lMoveStr := Copy(TelnetComm.LastMsg, Pos('/', TelnetComm.LastMsg)+1, 5); TChessGame.ChessMoveCoordsToBoardPos(lMoveStr, lFrom, lTo); lAnimation := TChessMoveAnimation.Create; lAnimation.AFrom := lFrom; lAnimation.ATo := lTo; vChessDrawer.AddAnimation(lAnimation); end; end; procedure TFICSChessModule.HandleOnDebugOut(AStr: string); begin ChessModuleDebugOut(AStr); end; initialization RegisterChessModule(TFICSChessModule.Create); end.
unit savenote; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ImgList, ComCtrls, Grids, AdvGrid, ffsutils, FFSAdvStringGrid, AdvEdit, editlist, TicklerTypes, sBitBtn, sLabel; type TRptFunction = (RptFunLoad, RptFunSave); TfrmSaveNotice = class(TForm) Label1: TsLabel; edtSaveName: TAdvEdit; List: TEditListBox; btnOk: TsBitBtn; btnCancel: TsBitBtn; procedure btnOkClick(Sender: TObject); procedure ListDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ListSelChange(Sender: TObject; ListIndex: Integer); procedure FormShow(Sender: TObject); private FReportType: TTicklerReport; FReportName: string; FileFunction: TRptFunction; SList : TStringList; function InReportList: boolean; public end; function SaveReportAs(AReportType:TTicklerReport;var AName:string):integer; function LoadReport(AReportType:TTicklerReport;var AName:string):integer; function DeleteReport(AReportType:TTicklerReport;var AName:string):integer; implementation uses TicklerGlobals, datamod; {$R *.DFM} // Is there a saved report already with this name? function TfrmSaveNotice.InReportList: boolean; begin InReportList := (List.Items.IndexOf(edtSaveName.text) <> -1); end; // Check if they want to save this report procedure TfrmSaveNotice.btnOkClick(Sender: TObject); begin FReportName := edtSaveName.text; case FileFunction of RptFunSave: begin if edtSaveName.Text = '' then begin MsgAsterisk('Name can not be blank.'); Exit; end; if InReportList then // see if it already is there begin if TrMsgConfirmation('Name already exists. Overwrite?') = IDYES then ModalResult := mrOk else ModalResult := mrNo; end else ModalResult := mrOk; end; RptFunLoad: begin ModalResult := mrOk; end; end; end; procedure TfrmSaveNotice.ListDblClick(Sender: TObject); begin btnOk.Click; end; procedure TfrmSaveNotice.FormCreate(Sender: TObject); begin SList := TStringList.Create; end; procedure TfrmSaveNotice.FormDestroy(Sender: TObject); begin SList.Free; end; // Returns the name to save the report as in AName function SaveReportAs(AReportType :TTicklerReport; var AName :String):integer; var frmSaveNotice : TfrmSaveNotice; begin frmSaveNotice := TfrmSaveNotice.create(nil); try frmSaveNotice.edtSaveName.Text := AName; // Set form field based on what was passed frmSaveNotice.FileFunction := RptFunSave; // Report Save Function frmSaveNotice.Caption := 'Save As...'; frmSaveNotice.Label1.Caption := 'Save As:'; frmSaveNotice.FReportType := AReportType; frmSaveNotice.edtSaveName.SelectAll; frmSaveNotice.ActiveControl := frmSaveNotice.edtSaveName; frmSaveNotice.FReportName := AName; // original report name result := frmSaveNotice.ShowModal; // show file select dialog if result = mrok then AName := frmSaveNotice.FReportName // return back user selected report name else AName := ''; // I guess they really didn't want to save finally frmSaveNotice.Free; end; end; function LoadReport(AReportType:TTicklerReport;var AName:string):integer; var frmSaveNotice : TfrmSaveNotice; begin frmSaveNotice := TfrmSaveNotice.create(nil); try frmSaveNotice.label1.Visible := false; frmSaveNotice.edtSaveName.Visible := false; frmSaveNotice.edtSaveName.text := ''; frmSaveNotice.List.Height := 175; frmSaveNotice.FileFunction := RptFunLoad; frmSaveNotice.Caption := 'Open Report'; frmSaveNotice.FReportType := AReportType; frmSaveNotice.ActiveControl := frmSaveNotice.List; result := frmSaveNotice.ShowModal; if result = mrok then AName := frmSaveNotice.FReportName else AName := ''; finally frmSaveNotice.Free; end; end; function DeleteReport(AReportType:TTicklerReport;var AName:string):integer; var frmSaveNotice : TfrmSaveNotice; begin frmSaveNotice := TfrmSaveNotice.create(nil); try frmSaveNotice.label1.Visible := false; frmSaveNotice.edtSaveName.Visible := false; frmSaveNotice.edtSaveName.text := ''; frmSaveNotice.List.Height := 175; frmSaveNotice.FileFunction := RptFunLoad; frmSaveNotice.Caption := 'Delete Report Settings'; frmSaveNotice.FReportType := AReportType; frmSaveNotice.ActiveControl := frmSaveNotice.List; result := frmSaveNotice.ShowModal; if result = mrok then AName := frmSaveNotice.FReportName else AName := ''; finally frmSaveNotice.Free; end; end; procedure TfrmSaveNotice.ListSelChange(Sender: TObject; ListIndex: Integer); begin edtSaveName.Text := List.Items[ListIndex]; end; procedure TfrmSaveNotice.FormShow(Sender: TObject); var index: integer; begin daapi.GetSavedReportList(CurrentLend.Number, FReportType, SList); List.Items.Clear; List.Items.AddStrings(SList); btnOk.Enabled := (SList.Count > 0) or (FileFunction = RptFunSave) ; if List.Items.count > 0 then begin index := List.Items.IndexOf(FReportName); List.ItemIndex := index; // Set the selected default to the currently open report end; end; end.
unit MdiChilds.ConvertDataToUNITable; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.CustomDialog, JvComponentBase, JvDragDrop, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ComCtrls, ActionHandler, IniFiles, GlobalData, JvBaseDlg, JvSelectDirectory, DataTable, Parsers.Excel, MdiChilds.ProgressForm, DateUtils; type TFmConvertExcel2DataTable = class(TFmProcess) cbRegion: TComboBox; Label1: TLabel; Label2: TLabel; cbType: TComboBox; Label3: TLabel; cbFormat: TComboBox; dtpDate: TDateTimePicker; Label4: TLabel; Label5: TLabel; cbDateFormat: TComboBox; lbFiles: TListBox; Label6: TLabel; SpinEdit1: TSpinEdit; Label7: TLabel; Label8: TLabel; SpinEdit2: TSpinEdit; edtOutputFolder: TLabeledEdit; btnOpen: TButton; DragDrop: TJvDragDrop; JvSelectDirectory: TJvSelectDirectory; procedure btnOpenClick(Sender: TObject); procedure DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private { Private declarations } function GetNum(Str: string): Integer; public procedure DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); override; procedure ReadSettings(); override; end; TConvertActionHandler = class(TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmConvertExcel2DataTable: TFmConvertExcel2DataTable; implementation {$R *.dfm} { TConvertActionHandler } procedure TConvertActionHandler.ExecuteAction(UserData: Pointer); begin TFmConvertExcel2DataTable.Create(Application).Show; end; { TFmConvertExcel2DataTable } procedure TFmConvertExcel2DataTable.btnOpenClick(Sender: TObject); begin if JvSelectDirectory.Execute then edtOutputFolder.Text := JvSelectDirectory.Directory; end; procedure TFmConvertExcel2DataTable.DoOk(Sender: TObject; ProgressForm: TFmProgress; var ShowMessage: Boolean); var I: Integer; P: TExcelSheet2DataTableParser; Table: TFormattedStringDataTable; begin ShowMessage := True; ProgressForm.InitPB(lbFiles.Count); ProgressForm.Show; P := TExcelSheet2DataTableParser.Create; try for I := 0 to lbFiles.Count - 1 do begin ProgressForm.StepIt(lbFiles.Items[I]); if not ProgressForm.InProcess then Break; Table := P.ParseDoc(lbFiles.Items[I]); try if Table <> nil then begin Table.RegionCode := GetNum(cbRegion.Text); Table.TypeCode := GetNum(cbType.Text); Table.FormatCode := GetNum(cbFormat.Text); Table.VersionCode := SpinEdit1.Value; Table.Zone := SpinEdit2.Value; Table.Year := YearOf(dtpDate.DateTime); Table.Month := MonthOf(dtpDate.DateTime); Table.Day := DayOf(dtpDate.DateTime); Table.DateFormat := GetNum(cbDateFormat.Text); Table.SaveToFile(IncludeTrailingPathDelimiter(edtOutputFolder.Text) + ExtractFileName(ChangeFileExt(lbFiles.Items[I], '.dtx'))); end; finally Table.Free; end; end; finally P.Free; end; end; procedure TFmConvertExcel2DataTable.DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin lbFiles.Items.Assign(Value); end; function TFmConvertExcel2DataTable.GetNum(Str: string): Integer; begin Result := STrToInt(Copy(Str, 1, Pos('=', Str) - 1)); end; procedure TFmConvertExcel2DataTable.ReadSettings; var IniFile: TIniFile; I: Integer; begin edtOutputFolder.Text := GlobalData.TempDir; IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'convert_info.ini'); try IniFile.ReadSectionValues('provider', cbRegion.Items); IniFile.ReadSectionValues('type', cbType.Items); IniFile.ReadSectionValues('format', cbFormat.Items); IniFile.ReadSectionValues('date_format', cbDateFormat.Items); for I := 0 to ComponentCount - 1 do if Components[I] is TComboBox then begin if TComboBox(Components[I]).Items.Count > 0 then TComboBox(Components[I]).ItemIndex := 0; end; finally IniFile.Free; end; end; begin ActionHandlerManager.RegisterActionHandler('Конвертация в DTX', hkDefault, TConvertActionHandler); end.
unit sufacetstwin; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Surfaces, ExtCtrls; type TForm1 = class(TForm) map: TImage; Label1: TLabel; x: TEdit; Label2: TLabel; y: TEdit; Label3: TLabel; value: TEdit; Label4: TLabel; strength: TEdit; Button1: TButton; procedure FormCreate(Sender: TObject); private procedure PaintMap; private Surface : TSurface; end; var Form1: TForm1; implementation uses ClassStorage, PyramidalModifier; {$R *.DFM} { SP := TSurfacePool.Create; IP := TIntegratorPool.Create; InitTheClassStorage; TheClassStorage.RegisterClass( tidClassFamily_SurfacePools, tidSurfacePool_Surfaces, SP ); TheClassStorage.RegisterClass( tidClassFamily_SurfacePools, tidSurfacePool_Integrators, IP ); SP.AddSurface( TSurface.Create( 'TestSurface', 'Test Surface' )); M1 := TPyramidalModifier.Create( 'TestSurface', Point(50, 50), 400, 0.1 ); M2 := TPyramidalModifier.Create( 'TestSurface', Point(45, 45), -400, 0.1 ); I := TSurfaceIntegrator.Create( 'TestSurface', Rect( 0, 0, 100, 100 ) ); IP.IntegrateAll; for y := 40 to 60 do begin for x := 40 to 60 do write( ' ', (M1[x, y] + M2[x, y]):2:0 ); writeln; end; writeln( I.Value:2:2 ); writeln( M2[45, 45] ); readln; } procedure TForm1.FormCreate(Sender: TObject); begin InitTheClassStorage; TheClassStorage.RegisterClass( tidClassFamily_SurfacePools, tidSurfacePool_Surfaces, TSurfacePool.Create ); Surface := TSurface.Create( 'TestSurface', 'Test Surface' ); end; procedure TForm1.PaintMap; var x, y : integer; begin for y := 0 to pred(map.Height) do for x := 0 to pred(map.Width) do end; end.
unit FromWithPanel_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Forms" // Автор: Инишев Д.А. // Модуль: "w:/common/components/gui/Garant/Daily/Forms/FromWithPanel_Form.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::FormWithPanel::FromWithPanel // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses vcmInterfaces, vcmEntityForm, vcmUserControls, vtPanel, l3StringIDEx {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , kwBynameControlPush {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , FromWithPanel_ut_FromWithPanel_UserType, Classes {a}, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a} ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} const { FromWithPanelIDs } fm_FromWithPanelForm : TvcmFormDescriptor = (rFormID : (rName : 'FromWithPanelForm'; rID : 0); rFactory : nil); { Идентификатор формы TFromWithPanelForm } type FromWithPanelFormDef = interface(IUnknown) {* Идентификатор формы FromWithPanel } ['{52A98A72-5DD1-4BDA-8FD3-152438D1B28D}'] end;//FromWithPanelFormDef TFromWithPanelForm = {final form} class(TvcmEntityForm, FromWithPanelFormDef) Entities : TvcmEntities; private // private fields f_WorkSpace : TvtPanel; {* Поле для свойства WorkSpace} protected procedure MakeControls; override; protected // overridden protected methods procedure InitControls; override; {* Процедура инициализации контролов. Для перекрытия в потомках } public // public properties property WorkSpace: TvtPanel read f_WorkSpace; end;//TFromWithPanelForm {$IfEnd} //nsTest AND not NoVCM implementation {$R *.DFM} {$If defined(nsTest) AND not defined(NoVCM)} uses Controls {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts , l3MessageID ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} var { Локализуемые строки ut_FromWithPanelLocalConstants } str_ut_FromWithPanelCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_FromWithPanelCaption'; rValue : 'FromWithPanel'); { Заголовок пользовательского типа "FromWithPanel" } type Tkw_FromWithPanel_Control_WorkSpace = class(TtfwControlString) {* Слово словаря для идентификатора контрола WorkSpace ---- *Пример использования*: [code] контрол::WorkSpace TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_FromWithPanel_Control_WorkSpace // start class Tkw_FromWithPanel_Control_WorkSpace {$If not defined(NoScripts)} function Tkw_FromWithPanel_Control_WorkSpace.GetString: AnsiString; {-} begin Result := 'WorkSpace'; end;//Tkw_FromWithPanel_Control_WorkSpace.GetString {$IfEnd} //not NoScripts type Tkw_FromWithPanel_Control_WorkSpace_Push = class(TkwBynameControlPush) {* Слово словаря для контрола WorkSpace ---- *Пример использования*: [code] контрол::WorkSpace:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_FromWithPanel_Control_WorkSpace_Push // start class Tkw_FromWithPanel_Control_WorkSpace_Push {$If not defined(NoScripts)} procedure Tkw_FromWithPanel_Control_WorkSpace_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('WorkSpace'); inherited; end;//Tkw_FromWithPanel_Control_WorkSpace_Push.DoDoIt {$IfEnd} //not NoScripts type Tkw_Form_FromWithPanel = class(TtfwControlString) {* Слово словаря для идентификатора формы FromWithPanel ---- *Пример использования*: [code] 'aControl' форма::FromWithPanel TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_FromWithPanel // start class Tkw_Form_FromWithPanel {$If not defined(NoScripts)} function Tkw_Form_FromWithPanel.GetString: AnsiString; {-} begin Result := 'FromWithPanelForm'; end;//Tkw_Form_FromWithPanel.GetString {$IfEnd} //not NoScripts type Tkw_FromWithPanel_WorkSpace_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола WorkSpace формы FromWithPanel } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_FromWithPanel_WorkSpace_ControlInstance // start class Tkw_FromWithPanel_WorkSpace_ControlInstance {$If not defined(NoScripts)} procedure Tkw_FromWithPanel_WorkSpace_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TFromWithPanelForm).WorkSpace); end;//Tkw_FromWithPanel_WorkSpace_ControlInstance.DoDoIt {$IfEnd} //not NoScripts procedure TFromWithPanelForm.InitControls; //#UC START# *4A8E8F2E0195_51D534260378_var* //#UC END# *4A8E8F2E0195_51D534260378_var* begin //#UC START# *4A8E8F2E0195_51D534260378_impl* inherited; f_WorkSpace.Align := alClient; //#UC END# *4A8E8F2E0195_51D534260378_impl* end;//TFromWithPanelForm.InitControls procedure TFromWithPanelForm.MakeControls; begin inherited; f_WorkSpace := TvtPanel.Create(Self); f_WorkSpace.Name := 'WorkSpace'; f_WorkSpace.Parent := Self; with AddUsertype(ut_FromWithPanelName, str_ut_FromWithPanelCaption, str_ut_FromWithPanelCaption, false, -1, -1, '', nil, nil, nil, vcm_ccNone) do begin end;//with AddUsertype(ut_FromWithPanelName end; {$IfEnd} //nsTest AND not NoVCM initialization {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_FromWithPanel_Control_WorkSpace Tkw_FromWithPanel_Control_WorkSpace.Register('контрол::WorkSpace', TvtPanel); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_FromWithPanel_Control_WorkSpace_Push Tkw_FromWithPanel_Control_WorkSpace_Push.Register('контрол::WorkSpace:push'); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация фабрики формы FromWithPanel fm_FromWithPanelForm.SetFactory(TFromWithPanelForm.Make); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_Form_FromWithPanel Tkw_Form_FromWithPanel.Register('форма::FromWithPanel', TFromWithPanelForm); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_FromWithPanel_WorkSpace_ControlInstance TtfwScriptEngine.GlobalAddWord('.TFromWithPanelForm.WorkSpace', Tkw_FromWithPanel_WorkSpace_ControlInstance); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Инициализация str_ut_FromWithPanelCaption str_ut_FromWithPanelCaption.Init; {$IfEnd} //nsTest AND not NoVCM end.
{***********************************************************************} { TPLANNERCALENDAR component } { for Delphi & C++Builder } { } { written by : } { TMS Software } { copyright © 1999-2012 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } {***********************************************************************} unit PlannerCalRegDE; interface {$I TMSDEFS.INC} uses PlannerCal, PlannerDatePicker, PlannerMaskDatePicker, Classes, PlanStyles , AdvImage, AdvImgDE {$IFDEF DELPHI6_LVL} ,DesignIntf, DesignEditors {$ELSE} ,DsgnIntf {$ENDIF} ; type TPlannerCalendarEditProperty = class(TClassProperty); TPlannerCalendarEditor = class(TDefaultEditor) protected public function GetVerb(index:integer):string; override; function GetVerbCount:integer; override; procedure ExecuteVerb(Index:integer); override; end; procedure Register; implementation uses Dialogs, Forms, Controls; procedure Register; begin RegisterPropertyEditor(TypeInfo(TAdvImage), TPlannerCalendar, 'Background', TAdvImageProperty); RegisterPropertyEditor(TypeInfo(TAdvImage), TPlannerCalendarGroup, 'Background', TAdvImageProperty); RegisterPropertyEditor(TypeInfo(TPlannerCalendar), TPlannerDatePicker, 'Calendar', TPlannerCalendarEditProperty); RegisterPropertyEditor(TypeInfo(TPlannerCalendar), TPlannerMaskDatePicker, 'Calendar', TPlannerCalendarEditProperty); RegisterComponentEditor(TPlannerCalendar, TPlannerCalendarEditor); RegisterComponentEditor(TPlannerDatePicker, TPlannerCalendarEditor); RegisterComponentEditor(TPlannerCalendarGroup, TPlannerCalendarEditor); end; { TPlannerCalendarEditor } procedure TPlannerCalendarEditor.ExecuteVerb(Index: integer); var psf: TPlanStyleForm; begin inherited; if Index = 0 then begin psf := TPlanStyleForm.Create(Application); psf.Caption := 'PlannerCalendar Styles'; if psf.ShowModal = mrOK then begin if (Component is TPlannerCalendar) then (Component as TPlannerCalendar).Style := TPlannerCalendarStyle(psf.RadioGroup1.ItemIndex); if (Component is TPlannerDatePicker) then (Component as TPlannerDatePicker).Calendar.Style := TPlannerCalendarStyle(psf.RadioGroup1.ItemIndex); if (Component is TPlannerCalendarGroup) then (Component as TPlannerCalendarGroup).Style := TPlannerCalendarStyle(psf.RadioGroup1.ItemIndex); Designer.Modified; end; psf.Free; end; end; function TPlannerCalendarEditor.GetVerb(index: integer): string; begin if Index = 0 then Result := 'Styles'; end; function TPlannerCalendarEditor.GetVerbCount: integer; begin Result := 1; end; end.
unit uRelMediaCompra; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frxClass, frxDBSet, DB, ADODB, StdCtrls, CheckLst, ExtCtrls, Buttons, Mask, JvExMask, JvToolEdit, JvExControls, JvSpeedButton; type TfrmRelMediaCompra = class(TForm) Panel1: TPanel; CheckListBox1: TCheckListBox; qr01: TADOQuery; frxDBDataset1: TfrxDBDataset; frxReport1: TfrxReport; btnImprimir: TBitBtn; btnSair: TBitBtn; edtVendedor: TJvComboEdit; Label1: TLabel; JvSpeedButton1: TJvSpeedButton; Label2: TLabel; Label3: TLabel; d01: TJvDateEdit; d02: TJvDateEdit; BitBtn1: TBitBtn; BitBtn2: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure JvSpeedButton1Click(Sender: TObject); procedure edtVendedorButtonClick(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure frxReport1GetValue(const VarName: string; var Value: Variant); private { Private declarations } ListProduto: TStringList; sVendedor: string; procedure GerarRelatorio; public { Public declarations } end; var frmRelMediaCompra: TfrmRelMediaCompra; implementation uses uConsulta_Padrao, uDmAccess; {$R *.dfm} procedure TfrmRelMediaCompra.FormCreate(Sender: TObject); begin if dmAccess = nil then dmAccess := TdmAccess.Create(Self); d01.Date := Date; d02.Date := Date; sVendedor := EmptyStr; ListProduto := TStringList.Create; with qr01 do begin Close; SQL.Clear; SQL.Text := 'select codprod,descrprod from tblprodutos where codprod>0 order by 2'; Open; First; while not Eof do begin ListProduto.Add(Fields[0].AsString); CheckListBox1.Items.Add(Fields[1].AsString); Next; end; Close; end; end; procedure TfrmRelMediaCompra.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfrmRelMediaCompra.FormDestroy(Sender: TObject); begin ListProduto.Free; end; procedure TfrmRelMediaCompra.GerarRelatorio; var sProduto: string; i: Integer; begin with qr01 do begin sProduto := EmptyStr; for i := 0 to Pred(CheckListBox1.Items.Count) do if CheckListBox1.Checked[i] then sProduto := sProduto + ListProduto[i] + ','; if sProduto <> EmptyStr then sProduto := Copy(sProduto, 1, Length(sProduto) - 1); Close; SQL.Clear; SQL.Add('delete from tblTempMediaPreco'); ExecSQL; //Insere Compra Close; SQL.Clear; SQL.Add('INSERT INTO tblTempMediaPreco ( codprod, descrprod, qtde_compra, t_compra, media_compra, prmenor_compra, prmaior_compra )'); SQL.Add('SELECT tblComprasVendas.CodProd, tblProdutos.DescrProd, Sum(tblComprasVendas.QtdCompra) AS QtdeCompra, Sum(tblComprasVendas.VlrTotal) AS T_Compra,'); SQL.Add('CCur([t_compra]/[qtdecompra]) AS Media_Compra, Min(tblComprasVendas.VlrUnit) AS PrMenor_compra, Max(tblComprasVendas.VlrUnit) AS PrMaior_compra'); SQL.Add('FROM tblContasPagar INNER JOIN (tblComprasVendas INNER JOIN tblProdutos ON tblComprasVendas.CodProd = tblProdutos.CodProd) ON tblContasPagar.NumPed = tblComprasVendas.NumPed'); SQL.Add('WHERE (((tblComprasVendas.PedCV)="compra") AND ((tblContasPagar.DataEmis) Between :pDataI And :pDataF))'); SQL.Add('GROUP BY tblComprasVendas.CodProd, tblProdutos.DescrProd'); if sProduto <> EmptyStr then SQL.Add('HAVING (((tblComprasVendas.CodProd) In (' + sProduto + ')))'); SQL.Add('ORDER BY tblProdutos.DescrProd'); Parameters.ParamByName('pDataI').Value := d01.Date; Parameters.ParamByName('pDataF').Value := d02.Date; ExecSQL; //Insere Vendas Close; SQL.Clear; SQL.Add('INSERT INTO tblTempMediaPreco ( codprod, descrprod, qtde_venda, t_venda, media_venda, prmenor_venda, prmaior_venda )'); SQL.Add('SELECT tblComprasVendas.CodProd, tblProdutos.DescrProd, Sum(tblComprasVendas.QtdVenda) AS QtdeVenda, Sum(tblComprasVendas.VlrTotal) AS T_Venda,'); SQL.Add('CCur([t_venda]/[qtdeVenda]) AS Media_Venda, Min(tblComprasVendas.VlrUnit) AS PrMenor_venda, Max(tblComprasVendas.VlrUnit) AS PrMaior_venda'); SQL.Add('FROM (tblComprasVendas INNER JOIN tblContasReceber ON tblComprasVendas.NumPed = tblContasReceber.NumPed) INNER JOIN tblProdutos ON tblComprasVendas.CodProd = tblProdutos.CodProd'); SQL.Add('WHERE (((tblComprasVendas.PedCV)="venda") AND ((tblContasReceber.DataEmis) Between :pDataI And :pDataF))'); if sVendedor <> EmptyStr then begin SQL.Add(' AND ((tblContasReceber.CodVendedor)=:pVendedor)'); Parameters.ParamByName('pVendedor').Value := sVendedor; end; SQL.Add('GROUP BY tblComprasVendas.CodProd, tblProdutos.DescrProd'); if sProduto <> EmptyStr then SQL.Add('HAVING (((tblComprasVendas.CodProd) In (' + sProduto + ')))'); SQL.Add('ORDER BY tblProdutos.DescrProd'); Parameters.ParamByName('pDataI').Value := d01.Date; Parameters.ParamByName('pDataF').Value := d02.Date; ExecSQL; Close; SQL.Clear; SQL.Add('SELECT tblTempMediaPreco.codprod, tblTempMediaPreco.descrprod,'); SQL.Add('Sum(tblTempMediaPreco.qtde_compra) AS qt_compra, Sum(tblTempMediaPreco.t_compra)'); SQL.Add('AS val_compra, Sum(tblTempMediaPreco.media_compra) AS avg_compra,'); SQL.Add('Sum(tblTempMediaPreco.prmenor_compra) AS prmin_compra, Sum(tblTempMediaPreco.prmaior_compra)'); SQL.Add('AS prmax_compra, Sum(tblTempMediaPreco.qtde_venda) AS qt_venda, Sum(tblTempMediaPreco.t_venda)'); SQL.Add('AS val_venda, Sum(tblTempMediaPreco.media_venda) AS avg_venda, Sum(tblTempMediaPreco.prmenor_venda)'); SQL.Add('AS prmin_venda, Sum(tblTempMediaPreco.prmaior_venda) AS prmax_venda, [qt_compra]-[qt_venda] AS estoque,'); SQL.Add('IIf([estoque]>0,[estoque]*[avg_compra],0) AS val_estoque, [val_venda]-[val_compra]+[val_estoque] AS lucro'); SQL.Add('FROM tblTempMediaPreco'); SQL.Add('GROUP BY tblTempMediaPreco.codprod, tblTempMediaPreco.descrprod'); SQL.Add('ORDER BY tblTempMediaPreco.DescrProd'); Open; if IsEmpty then MessageDlg('Não há dados a serem impressos?', mtError, [mbOK], 0) else frxReport1.ShowReport(); Close; end; end; procedure TfrmRelMediaCompra.btnSairClick(Sender: TObject); begin Close; end; procedure TfrmRelMediaCompra.btnImprimirClick(Sender: TObject); begin GerarRelatorio; end; procedure TfrmRelMediaCompra.JvSpeedButton1Click(Sender: TObject); begin edtVendedor.Clear; sVendedor := EmptyStr; end; procedure TfrmRelMediaCompra.edtVendedorButtonClick(Sender: TObject); begin with TfrmConsulta_Padrao.Create(self) do begin DataSet := qr01; qr01.Close; with qr01.SQL do begin Clear; Add('select * from tblvendedor'); Add('where nomevendedor like :pFantasia'); Add('order by 2'); end; with DBGrid do begin Columns.Clear; Columns.Add; Columns[0].FieldName := 'nomevendedor'; Columns[0].Title.Caption := 'Nome do Vendedor'; Columns[0].Width := 250; end; CampoLocate := 'nomevendedor'; Parametro := 'pFantasia'; ColunasGrid := -1; ShowModal; if Tag = 1 then begin sVendedor := qr01.Fields[0].AsString; edtVendedor.Text := qr01.Fields[1].AsString; end; Free; end; end; procedure TfrmRelMediaCompra.BitBtn1Click(Sender: TObject); var i: Integer; begin for i := 0 to Pred(CheckListBox1.Count) do CheckListBox1.Checked[i] := True; end; procedure TfrmRelMediaCompra.BitBtn2Click(Sender: TObject); var i: Integer; begin for i := 0 to Pred(CheckListBox1.Count) do CheckListBox1.Checked[i] := False; end; procedure TfrmRelMediaCompra.frxReport1GetValue(const VarName: string; var Value: Variant); var s: string; begin s := 'Período do Relatório: ' + formatdatetime('dd/mm/yy', d01.Date) + ' À ' + formatdatetime('dd/mm/yy', d02.Date); if sVendedor <> EmptyStr then s := s + ' Vendedor: ' + edtVendedor.Text; if CompareText(VarName, 'periodo') = 0 then Value := s; end; end.
unit adItemEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, adEngine, OvcBase, afwControlPrim, afwBaseControl, afwControl, afwInputControl, vtLister, Mask, ToolEdit, StdCtrls, Buttons, l3Interfaces, vtStringLister, l3StringList; type TadItemEditDlg = class(TForm) edName: TEdit; lblName: TLabel; edAlias: TEdit; lblAlias: TLabel; deTarget: TDirectoryEdit; lblTarget: TLabel; lstFiles: TvtLister; lblFileList: TLabel; sbAddFile: TSpeedButton; sbDelFile: TSpeedButton; btnOK: TButton; btnCancel: TButton; odFiles: TOpenDialog; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure lstFilesGetItemColor(Sender: TObject; Index: Integer; var FG, BG: TColor); procedure lstFilesGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); procedure sbAddFileClick(Sender: TObject); procedure sbDelFileClick(Sender: TObject); private f_Item: TadItem; f_FileValidity: array of Boolean; f_FileList: Tl3StringList; f_IsDataValid: Boolean; procedure CheckValidity; procedure pm_SetItem(const Value: TadItem); procedure PutData; procedure UpdateFileList; { Private declarations } public function Execute: Boolean; property Item: TadItem read f_Item write pm_SetItem; { Public declarations } end; var adItemEditDlg: TadItemEditDlg; implementation {$R *.dfm} uses l3Types, l3Base, l3DatLst, l3StringListPrim, l3Chars, l3String; procedure TadItemEditDlg.FormCreate(Sender: TObject); begin f_FileList := Tl3StringList.Make; end; procedure TadItemEditDlg.FormDestroy(Sender: TObject); begin FreeAndNil(f_FileList); FreeAndNil(f_Item); end; procedure TadItemEditDlg.btnOKClick(Sender: TObject); begin CheckValidity; if f_IsDataValid then begin PutData; ModalResult := mrOK; end else MessageDlg('Невалидные данные', mtError, [mbOK], 0); end; procedure TadItemEditDlg.CheckValidity; var l_Alias: AnsiString; begin f_IsDataValid := True; if edName.Text = '' then begin lblName.Font.Color := clRed; f_IsDataValid := False; end else lblName.Font.Color := clWindowText; l_Alias := edAlias.Text; if (l_Alias = '') or (l3CharSetPresentExR(PAnsiChar(@l_Alias[1]), Length(l_Alias)-1, cc_WordDelimANSISet) >= 0) then begin lblAlias.Font.Color := clRed; f_IsDataValid := False; end else lblAlias.Font.Color := clWindowText; if deTarget.Text = '' then begin lblTarget.Font.Color := clRed; f_IsDataValid := False; end else if not DirectoryExists(deTarget.Text) then begin lblTarget.Font.Color := clRed; f_IsDataValid := False; end else lblTarget.Font.Color := clWindowText; if lstFiles.Total = 0 then begin lblFileList.Font.Color := clRed; f_IsDataValid := False; end else lblFileList.Font.Color := clWindowText; end; function TadItemEditDlg.Execute: Boolean; begin Result := ShowModal = mrOk; end; procedure TadItemEditDlg.lstFilesGetItemColor(Sender: TObject; Index: Integer; var FG, BG: TColor); begin if f_FileValidity[Index] then FG := clWindowText else FG := clRed; end; procedure TadItemEditDlg.lstFilesGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); begin ItemString := f_FileList.ItemC[Index]; end; procedure TadItemEditDlg.pm_SetItem(const Value: TadItem); var I: Integer; begin Value.SetRefTo(f_Item); edName.Text := f_Item.Name; edAlias.Text := f_Item.Alias; deTarget.Text := f_Item.TargetFolder; for I := 0 to f_Item.FilesCount-1 do f_FileList.Add(f_Item.Files[I]); UpdateFileList; CheckValidity; end; procedure TadItemEditDlg.PutData; var I: Integer; begin f_Item.Name := edName.Text; f_Item.Alias := edAlias.Text; f_Item.TargetFolder := deTarget.Text; f_Item.ClearFiles; for I := 0 to f_FileList.Count-1 do f_Item.AddFile(f_FileList.Items[I].AsString); end; procedure TadItemEditDlg.sbAddFileClick(Sender: TObject); var I: Integer; begin if odFiles.Execute then begin lstFiles.BeginUpdate; try for I := 0 to odFiles.Files.Count - 1 do f_FileList.Add(odFiles.Files[I]); UpdateFileList; finally lstFiles.EndUpdate end; end; end; procedure TadItemEditDlg.sbDelFileClick(Sender: TObject); var I: Integer; begin if MessageDlg('Действительно удалить выбранные элементы?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin lstFiles.BeginUpdate; try for I := f_FileList.Count-1 downto 0 do if lstFiles.Selected[I] then f_FileList.Delete(I); UpdateFileList; finally lstFiles.EndUpdate; end; end; end; procedure TadItemEditDlg.UpdateFileList; function CheckOne(Data: Pointer; Index: Long): Bool; begin Result := True; f_FileValidity[Index] := FileExists(Tl3PrimString(Data^).AsString); end; var l_IA: Tl3IteratorAction; begin SetLength(f_FileValidity, f_FileList.Count); l_IA := l3L2IA(@CheckOne); f_FileList.IterateAllF(l_IA); lstFiles.Total := f_FileList.Count; lstFiles.Invalidate; end; end.
unit Matrix; interface type IMatrix = interface function getCols : integer; function getRows : integer; procedure setDimensions( n, m : integer ); function getElement ( i, j : integer ) : single; procedure setElement ( i, j : integer; value : single ); end; implementation end.
unit l3Except; {* Базовые исключения L3. } // Модуль: "w:\common\components\rtl\Garant\L3\l3Except.pas" // Стереотип: "Interfaces" // Элемент модели: "l3Except" MUID: (4787B0A8007B) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , SysUtils ; const {* Сообщения об ошибках. } l3_excAbortLoad = 'Прервана загрузка документа.'; type El3Exception = class(Exception) end;//El3Exception El3CannotModify = class(El3Exception) end;//El3CannotModify El3Error = class(El3Exception) end;//El3Error El3Warning = class(El3Exception) end;//El3Warning El3NotFound = class(El3Error) end;//El3NotFound El3Abort = class(El3Error) end;//El3Abort El3AbortLoad = class(El3Abort) end;//El3AbortLoad El3FilerError = class(El3Error) end;//El3FilerError El3ReadError = class(El3FilerError) end;//El3ReadError El3NoLoggedException = class(El3Exception) {* предок ошибок, которые в лог не попадают (см. l3ExceptionsLog) } end;//El3NoLoggedException El3InfoException = class(El3Exception) {* предок ошибок для информационных целей (внутренее использование) } end;//El3InfoException El3DuplicateItem = class(El3Exception) {* дублирование элемента в списке } end;//El3DuplicateItem El3ConvertError = class(El3Exception) end;//El3ConvertError El3BadPictureFormat = class(El3Error) end;//El3BadPictureFormat El3AbortLoadFilter = class(El3AbortLoad) end;//El3AbortLoadFilter El3BadDataInPara = class(El3Exception) end;//El3BadDataInPara implementation uses l3ImplUses {$If NOT Defined(NoScripts)} , TtfwTypeRegistrator_Proxy {$IfEnd} // NOT Defined(NoScripts) ; initialization {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3Exception)); {* Регистрация типа El3Exception } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3CannotModify)); {* Регистрация типа El3CannotModify } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3Error)); {* Регистрация типа El3Error } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3Warning)); {* Регистрация типа El3Warning } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3NotFound)); {* Регистрация типа El3NotFound } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3Abort)); {* Регистрация типа El3Abort } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3AbortLoad)); {* Регистрация типа El3AbortLoad } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3FilerError)); {* Регистрация типа El3FilerError } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3ReadError)); {* Регистрация типа El3ReadError } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3NoLoggedException)); {* Регистрация типа El3NoLoggedException } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3InfoException)); {* Регистрация типа El3InfoException } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3DuplicateItem)); {* Регистрация типа El3DuplicateItem } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3ConvertError)); {* Регистрация типа El3ConvertError } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3BadPictureFormat)); {* Регистрация типа El3BadPictureFormat } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3AbortLoadFilter)); {* Регистрация типа El3AbortLoadFilter } {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} TtfwTypeRegistrator.RegisterType(TypeInfo(El3BadDataInPara)); {* Регистрация типа El3BadDataInPara } {$IfEnd} // NOT Defined(NoScripts) end.
unit Funcoes; interface uses Vcl.Forms, System.SysUtils, ACBrValidador, System.Classes, krnConst, Vcl.Dialogs, Winapi.Windows, Vcl.Controls; function FsMesExtenso(Value : TDateTime) : string; function FsDataExtenso(Value : TDateTime) : string; function FsPastaApp : string; function FsTemp : string; function fsMascara(numCasa: Integer; const moeda : string = ''; const porcentagem : Boolean = false): string; function fsCopyChar(vezes:Integer; const caracter : Char = '#'): string; function PreencheString(Texto: String; Tamanho:Integer; CampoNumerico: Boolean): String; Procedure PMontaStringList(VSParametros: String; var VStrLstAux: TStringList); overload; Procedure PMontaStringList(VSParametros: String; var VStrLstAux: TStringList; VsSeparador: String); overload; Function FsValorStringList(VsString: String; ViPosicao: Integer): String; procedure AlertaInfo(Mensagem : PWideChar); procedure AlertaError(Mensagem : PWideChar); function Perguntar(Mensagem : PWideChar; const defaultrespostayes: boolean = true) : integer; function CurrentMonth : Word; function AddMonth(const dData: TDateTime; const Months: Extended;const DiaFixo: integer = 0): TDateTime; Function VersaoExe: String; function NumSerie (const disco : string = 'C'): string; implementation function NumSerie (const disco : string = 'C'): string; var Serial:DWORD; DirLen, Flag: DWORD; DLabel: array[0..11] of Char; begin try GetVolumeInformation( PChar(disco+':\'), DLabel,12,@Serial, DirLen, Flag, nil,0 ); Result := IntToHex(Serial,8); except Result:=''; end; end; Function VersaoExe: String; type PFFI = ^vs_FixedFileInfo; var F : PFFI; Handle : Dword; Len : Longint; Data : Pchar; Buffer : Pointer; Tamanho : Dword; Parquivo: Pchar; Arquivo : String; begin Arquivo := Application.ExeName; Parquivo := StrAlloc(Length(Arquivo) + 1); StrPcopy(Parquivo, Arquivo); Len := GetFileVersionInfoSize(Parquivo, Handle); Result := ''; if Len > 0 then begin Data:=StrAlloc(Len+1); if GetFileVersionInfo(Parquivo,Handle,Len,Data) then begin VerQueryValue(Data, '',Buffer,Tamanho); F := PFFI(Buffer); Result := Format('%d.%d.%d.%d', [HiWord(F^.dwFileVersionMs), LoWord(F^.dwFileVersionMs), HiWord(F^.dwFileVersionLs), Loword(F^.dwFileVersionLs) ] ); end; StrDispose(Data); end; StrDispose(Parquivo); end; function FsDataExtenso(Value : TDateTime) : string; var Dia, Mes, Ano : Word; begin DecodeDate(Value,Ano,Mes, Dia); Result := IntToStr(dia) + ' de ' + FsMesExtenso(Value) + ' de ' + IntToStr(Ano); end; function FsMesExtenso(Value : TDateTime) : string; var Dia, Mes, Ano : Word; const Meses : array[1..12] of string = ('Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho', 'Agosto', 'Setembro', 'Outubro','Novembro','Dezembro'); begin DecodeDate(Value,Ano,Mes, Dia); Result := Meses[Mes]; end; function AddMonth(const dData: TDateTime; const Months: Extended;const DiaFixo: integer = 0): TDateTime; {*** * IsBisexto() * Retorna 'True' caso o ano seja bisexto * *} function IsBisexto(Ano: Word): Boolean; begin Result := (Ano mod 4 = 0) and ((Ano mod 100 <> 0) or (Ano mod 400 = 0)); end; var Dia, Mes, Ano: Word; iMes: Integer; begin DecodeDate (dData, Ano, Mes, Dia); if diafixo > 0 then Dia := DiaFixo; iMes := Mes + Trunc (Months); if iMes > 12 then begin Ano := Ano + (iMes - 1) div 12; iMes := iMes mod 12; if iMes = 0 then iMes := 12; end else if iMes < 1 then begin Ano := Ano + (iMes div 12) - 1; iMes := 12 - Abs(iMes) mod 12; end; Mes := iMes; // Ensure Day of Month is valid if Mes = 2 then begin if IsBiSexto(Ano) and (Dia > 29) then Dia := 29 else if not IsBiSexto(Ano) and (Dia > 28) then Dia := 28; end else if (Mes in [9, 4, 6, 11]) and (Dia = 31) then Dia := 30; if Months < 0 then Result := EncodeDate(Ano, Mes, Dia) - Frac(Abs(Months)) * 30 - Frac(dData) else Result := EncodeDate (Ano, Mes, Dia) + Frac(Months) * 30 + Frac(dData); end; function CurrentMonth : Word; var MesAtual: TSystemTime; begin GetLocalTime(Mesatual); Result := MesAtual.wMonth; end; function Perguntar(Mensagem : PWideChar; const defaultrespostayes: boolean = true) : integer; begin if defaultrespostayes then result:= MessageBox(0, Mensagem,NOME_SISTEMA, MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON1) else result:= MessageBox(0, Mensagem,NOME_SISTEMA, MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2); end; procedure AlertaError(Mensagem : PWideChar); begin Application.MessageBox(Mensagem, NOME_SISTEMA,MB_ICONERROR); end; procedure AlertaInfo(Mensagem : PWideChar); begin Application.MessageBox( PChar( Mensagem), NOME_SISTEMA,MB_ICONINFORMATION); end; Procedure PMontaStringList(VSParametros: String; var VStrLstAux: TStringList; VsSeparador: String); overload; var vi, viAux, viQuantParametros: Integer; vsAux: String; VPchParametros: PChar; ArrsParametros: Array[0..300] of String; begin vi := 0; viAux:=0; vsAux:=''; VPchParametros:=Pchar(VsParametros); //Trata parametros If Length(VPchParametros)>0 then Repeat If VPchParametros[vi] <> VsSeparador Then vsAux:=vsAux+VPchParametros[vi] else Begin Inc(viAux); vsAux:=''; end; ArrsParametros[viAux]:=vsAux; Inc(vi); Until vi = Length(VPchParametros); If Length(VPchParametros)>0 then viQuantParametros:=viAux+1 else viQuantParametros:=0; Try For ViAux:=0 to viQuantParametros-1 do VStrLstAux.Add((ArrsParametros[viAux])); Finally end; end; Procedure PMontaStringList(VSParametros: String; var VStrLstAux: TStringList); overload; begin PMontaStringList(VSParametros, VStrLstAux, '|'); end; Function FsValorStringList(VsString: String; ViPosicao: Integer): String; var VStrLstAux: TStringList; begin Try Try VStrLstAux:=TStringList.Create; PMontaStringList(VsString, VStrLstAux); If ViPosicao>VStrLstAux.Count-1 then Result:='' else Result:=VStrLstAux.Strings[ViPosicao];// (VStrLstAux.IndexOf(VsString)>-1); Finally FreeAndNil(VStrLstAux); end; except Result:=''; end; end; function PreencheString(Texto: String; Tamanho: Integer; CampoNumerico: Boolean): String; var Espacos: Integer; AuxTexto: String; begin Espacos:= Tamanho - Length(Texto); Result:= Copy(Texto,1,Tamanho); if Espacos > 0 then begin if CampoNumerico then begin repeat AuxTexto:= AuxTexto + '0' until Length(AuxTexto) = Espacos; Result:= AuxTexto+Result; end else begin repeat Result := Result + ' '; Espacos:= Espacos -1; until Espacos = 0 end; end; end; function fsCopyChar(vezes:Integer; const caracter : Char = '#'): string; var I: Integer; sAux: string; sAuxZero: string; begin sAux:=''; sAuxZero := ''; for I := 0 to vezes-1 do begin sAux := sAux + caracter; sAuxZero := sAuxZero + '0'; end; Result := caracter +','+ sAux+'0.'+sAuxZero; end; function fsMascara(numCasa: Integer; const moeda : string = ''; const porcentagem : Boolean = false ): string; var sAux: string; begin sAux := moeda; if sAux<> '' then sAux := sAux+ ' '; if numCasa<0 then Result :=fsCopyChar(2) else begin case numCasa of 0: Result :=sAux+fsCopyChar(2); 1: Result := sAux+'#0'; else Result := sAux+fsCopyChar(numCasa); end; if porcentagem then Result := Result + ' %'; end; end; function FsTemp : string; begin result:= fspastaApp+'\temp\'; end; function FsPastaApp : string; begin result := ExtractFilePath(Application.ExeName); end; end.
unit eInterestSimulator.Controller.Interfaces; interface uses eInterestSimulator.Model.Interfaces, System.Generics.Collections, eInterestSimulator.Controller.Observer.Interfaces; type iControllerResultado = interface ['{A90C187E-221C-4DFA-945F-085D380B8302}'] function Calcular: iControllerResultado; function Resultado: TList<iResultado>; overload; function Resultado(Value: TList<iResultado>): iControllerResultado; overload; function Simulador: iSimulador; overload; function Simulador(Value: iSimulador): iControllerResultado; overload; function SimuladorFactory: iSimulador; procedure ValidarDados; function ObserverResultado : iSubjectResultado; end; iControllerSistema = interface procedure AdicionaSistemas; overload; function SistemasLiberados: TDictionary<TTypeSistema, iSistema>; function SistemasLiberadosList: TList<iSistema>; end; implementation end.
//UDEBUG code already inserted. Please do not remove this line. {$I ok_server.inc} unit Props; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, xLngdefs, Mask; type TfrmProps = class(TForm) gbDC: TGroupBox; rbtNoCheck: TRadioButton; rbtCheck: TRadioButton; edClientsCheckInterval: TEdit; lMin: TLabel; gbCommon: TGroupBox; chbProvExecLogging: TCheckBox; edTimeout: TEdit; lTimeout: TLabel; lMinTimeout: TLabel; lMaxLogSize: TLabel; edMaxLogSize: TEdit; cbMaxLogSize: TComboBox; cbLanguage: TComboBox; lLanguage: TLabel; gbDebug: TGroupBox; cbDebugLevel: TComboBox; btnRepairSS: TButton; Panel1: TPanel; btnOk: TButton; lDebugLevel: TLabel; lLogBackupQuantity: TLabel; edLogBackupQuantity: TMaskEdit; procedure FormCreate(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure rbtNoCheckClick(Sender: TObject); procedure edClientsCheckIntervalKeyPress(Sender: TObject; var Key: Char); procedure cbLanguageChange(Sender: TObject); procedure cbDebugLevelChange(Sender: TObject); procedure btnRepairSSClick(Sender: TObject); private procedure SetCaptions; end; var frmProps: TfrmProps; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses {$IFDEF UDEBUG}udebug,{$ENDIF} MAth, ssSrvConst, ssSrvDB, ServerData, ssRegUtils, ShellAPI; {$IFDEF UDEBUG} var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$ENDIF} {$R *.dfm} //============================================================================================== procedure TfrmProps.FormCreate(Sender: TObject); var i: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.FormCreate') else _udebug := nil;{$ENDIF} chbProvExecLogging.Checked := ProvExecLogging; edClientsCheckInterval.Text := IntToStr(ClientCheckInterval div 60000); edTimeOut.Text := IntToStr(ClientCheckTimeOut div 60000); edLogBackupQuantity.Text := IntTosTr(MaxLogBackupsQuantity); if CheckForDeadConnections then rbtCheck.Checked := True else rbtNoCheck.Checked := True; cbLanguage.Clear; with dmData.Lng do begin for i := 0 to FilesCount-1 do cbLanguage.Items.Add(Files[i].LangName); cbLanguage.ItemIndex := ActiveLngIndex; end; cbDebugLevel.ItemIndex := DebugLevel; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.btnOkClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.btnOkClick') else _udebug := nil;{$ENDIF} ProvExecLogging := chbProvExecLogging.Checked; CheckForDeadConnections := rbtCheck.Checked; ClientCheckInterval := Trunc(StrToInt(edClientsCheckInterval.Text) * 60000); ClientCheckTimeOut := Trunc(StrToInt(edTimeout.Text) * 60000); if cbMaxLogSize.ItemIndex = 0 then MaxLogSize := StrToInt(edMaxLogSize.Text) else MaxLogSize := StrToInt(edMaxLogSize.Text) * 1000; xSrvDB.Timer.Interval := ClientCheckInterval; MaxLogBackupsQuantity := StrToInt(edLogBackupQuantity.Text); WriteToRegInt(ServerRegKey, 'CheckForDeadConnections', Integer(CheckForDeadConnections), HKEY_LOCAL_MACHINE); WriteToRegInt(ServerRegKey, 'ClientCheckInterval', ClientCheckInterval, HKEY_LOCAL_MACHINE); WriteToRegInt(ServerRegKey, 'ClientCheckTimeOut', ClientCheckTimeOut, HKEY_LOCAL_MACHINE); WriteToRegInt(ServerRegKey, 'MaxLogSize', MaxLogSize, HKEY_LOCAL_MACHINE); WriteToRegInt(ServerRegKey, 'MaxLogBackups', MaxLogBackupsQuantity, HKEY_LOCAL_MACHINE); WriteToRegStr(ServerRegKey, 'Lang', LangName, HKEY_LOCAL_MACHINE); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.rbtNoCheckClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.rbtNoCheckClick') else _udebug := nil;{$ENDIF} edClientsCheckInterval.Enabled := rbtCheck.Checked; lMin.Enabled := rbtCheck.Checked; lTimeout.Enabled := rbtCheck.Checked; lMinTimeout.Enabled := rbtCheck.Checked; edTimeOut.Enabled := rbtCheck.Checked; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.edClientsCheckIntervalKeyPress(Sender: TObject; var Key: Char); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.edClientsCheckIntervalKeyPress') else _udebug := nil;{$ENDIF} if not (Key in ['0'..'9', #13, #8]) then Key := #0; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.SetCaptions; var i: Integer; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.SetCaptions') else _udebug := nil;{$ENDIF} with dmData.Lng do begin Self.Caption := GetRS(Self.Name, 'rs_Title'); //gbLogging.Caption := ' ' + GetRS(Self.Name, 'rs_LogOptions') + ' '; gbDC.Caption := ' ' + GetRS(Self.Name, 'rs_CheckingDeadConn') + ' '; chbProvExecLogging.Caption := GetRS(Self.Name, 'rs_LoggingProvExec'); rbtNoCheck.Caption := GetRS(Self.Name, 'rs_DontCheckDC'); rbtCheck.Caption := GetRS(Self.Name, 'rs_CheckDC'); lMin.Caption := GetRS(Self.Name, 'rs_Min'); lMinTimeout.Caption := GetRS(Self.Name, 'rs_Min'); lTimeout.Caption := GetRS(Self.Name, 'rs_DCTimeout'); gbCommon.Caption := ' ' + GetRS(Self.Name, 'rs_Common') + ' '; lMaxLogSize.Caption := GetRS(Self.Name, 'rs_MaxLogSize') + ':'; lLogBackupQuantity.Caption := GetRS(Self.Name, 'lLogBackupQuantity') + ':'; with cbMaxLogSize do begin Items.Clear; Items.Add(GetRS(Self.Name, 'rs_InKB')); Items.Add(GetRS(Self.Name, 'rs_InMB')); end; if MaxLogSize >= 1000 then begin edMaxLogSize.Text := IntToStr(MaxLogSize div 1000); cbMaxLogSize.ItemIndex := 1; end else begin edMaxLogSize.Text := IntToStr(MaxLogSize); cbMaxLogSize.ItemIndex := 0; end; lLanguage.Caption := GetRS(Self.Name, 'rs_LangLabel'); btnRepairSS.Caption := GetRS(Self.Name, 'btnRepairSS'); gbDebug.Caption := ' ' + GetRS(Self.Name, 'gbDebug') + ' '; lDebugLevel.Caption := GetRS(Self.Name, 'lDebugLevel'); cbDebugLevel.Items.Clear; cbDebugLevel.Items.BeginUpdate; for i := 0 to 11 do case i of 0,3,5,10,11: cbDebugLevel.Items.Add(GetRS(Self.Name, 'dl' + IntTostr(i))); else cbDebugLevel.Items.Add(IntToStr(i)); end;//case cbDebugLevel.Items.endUpdate; cbDebugLevel.ItemIndex := DebugLevel; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.cbLanguageChange(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.cbLanguageChange') else _udebug := nil;{$ENDIF} with dmData.Lng do begin ActiveLngIndex := cbLanguage.ItemIndex; LangID := cbLanguage.ItemIndex; LangName := langNames[LangID]; Active := true; end; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.cbDebugLevelChange(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmProps.cbDebugLevelChange') else _udebug := nil;{$ENDIF} DebugLevel := cbDebugLevel.ItemIndex; WriteToRegInt(ServerRegKey, 'DebugLevel', DebugLevel); {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmProps.btnRepairSSClick(Sender: TObject); begin ShellExecute(Application.Handle, nil, PChar(serverPath + '\\scktsrvr.exe'), '/silent /install', nil, SW_HIDE); end; //============================================================================================== initialization {$IFDEF UDEBUG} Debugging := False; DEBUG_unit_ID := debugRegisterUnit('Props', @Debugging, DEBUG_group_ID); {$ENDIF} //============================================================================================== finalization {$IFDEF UDEBUG} //debugUnregisterUnit(DEBUG_unit_ID); {$ENDIF} end.
unit RDOServer; interface uses SyncObjs, RDOInterfaces, RDOObjectRegistry, RDOObjectServer, RDOQueryServer; type TRDOClientConnectEvent = procedure ( const ClientConnection : IRDOConnection ) of object; TRDOClientDisconnectEvent = procedure ( const ClientConnection : IRDOConnection ) of object; type TRDOServer = class private fObjectRegistry : TRDOObjectsRegistry; fQueryServer : IRDOQueryServer; fObjectServer : TRDOObjectServer; fOnClientConnect : TRDOClientConnectEvent; fOnClientDisConnect : TRDOClientDisconnectEvent; public constructor Create( ServerConnection : IRDOServerConnection; MaxQueryThreads : integer; QueryCritSection : TCriticalSection ); destructor Destroy; override; public procedure RegisterObject( ObjectName : string; ObjectId : integer ); procedure RegisterLogAgents( Agents : ILogAgents ); public procedure SetCriticalSection( CriticalSection : TCriticalSection ); procedure Lock; procedure UnLock; private function GetBusy : boolean; procedure SetBusy(value : boolean); public property OnClientConnect : TRDOClientConnectEvent read fOnClientConnect write fOnClientConnect; property OnClientDisconnect : TRDOClientDisconnectEvent read fOnClientDisconnect write fOnClientDisconnect; property Busy : boolean read GetBusy write SetBusy; end; implementation uses Windows; type TRDOConnectionsServerSink = class( TInterfacedObject, IRDOConnectionServerEvents ) private fRDOServer : TRDOServer; constructor Create( RDOServer : TRDOServer ); procedure OnClientConnect( const ClientConnection : IRDOConnection ); procedure OnClientDisconnect( const ClientConnection : IRDOConnection ); end; // TRDOConnectionsServerSink constructor TRDOConnectionsServerSink.Create( RDOServer : TRDOServer ); begin inherited Create; fRDOServer := RDOServer end; procedure TRDOConnectionsServerSink.OnClientConnect( const ClientConnection : IRDOConnection ); begin with fRDOServer do if Assigned( fOnClientConnect ) then fOnClientConnect( ClientConnection ) end; procedure TRDOConnectionsServerSink.OnClientDisconnect( const ClientConnection : IRDOConnection ); begin with fRDOServer do if Assigned( fOnClientDisconnect ) then fOnClientDisconnect( ClientConnection ) end; // TRDOServer constructor TRDOServer.Create( ServerConnection : IRDOServerConnection; MaxQueryThreads : integer; QueryCritSection : TCriticalSection ); var ConnServer : IRDOConnectionsServer; Sink : TRDOConnectionsServerSink; begin inherited Create; fObjectRegistry := TRDOObjectsRegistry.Create; fObjectServer := TRDOObjectServer.Create( fObjectRegistry, QueryCritSection ); fQueryServer := TRDOQueryServer.Create( fObjectServer ); ServerConnection.SetQueryServer( fQueryServer ); ServerConnection.MaxQueryThreads := MaxQueryThreads; if Succeeded( ServerConnection.QueryInterface( IRDOConnectionsServer, ConnServer ) ) then begin Sink := TRDOConnectionsServerSink.Create(Self); ConnServer.InitEvents(Sink); end; end; destructor TRDOServer.Destroy; begin fObjectRegistry.Free; fObjectServer.Free; inherited Destroy end; procedure TRDOServer.RegisterObject( ObjectName : string; ObjectId : integer ); begin fObjectRegistry.RegisterObject( ObjectName, ObjectId ) end; procedure TRDOServer.RegisterLogAgents( Agents : ILogAgents ); begin try (fQueryServer as IRDOLog).RegisterAgents( Agents ); except end; end; procedure TRDOServer.SetCriticalSection( CriticalSection : TCriticalSection ); begin fObjectServer.SetCriticalSection( CriticalSection ) end; procedure TRDOServer.Lock; begin fObjectServer.Lock end; procedure TRDOServer.UnLock; begin fObjectServer.UnLock end; function TRDOServer.GetBusy : boolean; begin result := fQueryServer.Busy; end; procedure TRDOServer.SetBusy(value : boolean); begin fQueryServer.Busy := value; end; end.
{$include lem_directives.inc} unit GamePostviewScreen; interface uses Windows, Classes, SysUtils, Controls, UMisc, Gr32, Gr32_Image, Gr32_Layers, LemCore, LemTypes, LemStrings, LemLevelSystem, LemGame, GameControl, GameBaseScreen; // LemCore, LemGame, LemDosFiles, LemDosStyles, LemControls, //LemDosScreen; {------------------------------------------------------------------------------- The dos postview screen, which shows you how you've done it. -------------------------------------------------------------------------------} type TGamePostviewScreen = class(TGameBaseScreen) private function GetScreenText: string; function BuildText(intxt: Array of char): string; procedure Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Form_KeyPress(Sender: TObject; var Key: Char); procedure Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure HandleMouseClick(Button: TMouseButton); protected procedure PrepareGameParams(Params: TDosGameParams); override; procedure BuildScreen; override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; published end; implementation uses Forms, LemStyle; (* const // results from worst to best OrigResultStrings: array[0..8] of string = ( 'ROCK BOTTOM! I hope for your sake' + #13 + 'that you nuked that level.', 'Better rethink your strategy before' + #13 + 'you try this level again!', 'A little more practice on this level' + #13 + 'is definitely recommended.', 'You got pretty close that time.' + #13 + 'Now try again for that few % extra.', 'OH NO, So near and yet so far (teehee)' + #13 + 'Maybe this time.....', 'RIGHT ON. You can''t get much closer' + #13 + 'than that. Let''s try the next...', 'That level seemed no problem to you on' + #13 + 'that attempt. Onto the next....', 'You totally stormed that level!' + #13 + 'Let''s see if you can storm the next...', 'Superb! You rescued every lemmings on' + #13 + 'that level. Can you do it again....' ); *) { TDosGamePreview } procedure TGamePostviewScreen.PrepareGameParams(Params: TDosGameParams); begin inherited; end; function TGamePostviewScreen.BuildText(intxt: Array of char): String; var tstr : String; x : byte; begin Result := ''; tstr := ''; for x := 0 to 35 do begin if (tstr <> '') or (intxt[x] <> ' ') then begin tstr := tstr + intxt[x]; end; end; Result := Trim(tstr); end; procedure TGamePostviewScreen.BuildScreen; var Temp: TBitmap32; // DstRect: TRect; begin //fSection := aSection; //fLevelNumber := aLevelNumber; //fGameResult := aResult; ScreenImg.BeginUpdate; Temp := TBitmap32.Create; try InitializeImageSizeAndPosition(640, 350); ExtractBackGround; ExtractPurpleFont; Temp.SetSize(640, 350); Temp.Clear(0); TileBackgroundBitmap(0, 0, Temp); DrawPurpleTextCentered(Temp, GetScreenText, 16); ScreenImg.Bitmap.Assign(Temp); finally ScreenImg.EndUpdate; Temp.Free; end; end; constructor TGamePostviewScreen.Create(aOwner: TComponent); begin inherited Create(aOwner); Stretched := True; OnKeyDown := Form_KeyDown; OnKeyPress := Form_KeyPress; OnMouseDown := Form_MouseDown; ScreenImg.OnMouseDown := Img_MouseDown; end; destructor TGamePostviewScreen.Destroy; begin inherited Destroy; end; function TGamePostviewScreen.GetScreenText: string; var i: Integer; STarget: string; SDone: string; H: string; procedure Add(const S: string); begin Result := Result + S + #13; end; procedure LF(aCount: Integer); begin Result := Result + StringOfChar(#13, aCount); end; function GetResultIndex: Integer; var i: Integer; begin // i := 0; with GameParams.GameResult do begin // result text if gDone = 100 then i := 8 else if gDone = 0 then i := 0 else if gDone < gTarget div 2 then i := 1 else if gDone < gTarget - 5 then i := 2 else if gDone < gTarget - 1 then i := 3 else if gDone = gTarget - 1 then i := 4 else if gDone = gTarget then i := 5 else if gDone < gTarget + 20 then i := 6 else if gDone >= gTarget + 20 then i := 7 else raise exception.Create('leveltext error'); end; Result := i; end; function GetNext(var NextInfo: TDosGamePlayInfoRec): Boolean; begin with GameParams do begin NextInfo := Info; Result := Style.LevelSystem.FindNextLevel(NextInfo); end; end; var NextInfo: TDosGamePlayInfoRec; NextAvail, Congrats: Boolean; x : byte; begin Result := ''; with GameParams, GameResult do begin {$ifdef testmode} if fTestMode then begin gSuccess := false; NextAvail := false; gCheated := false; //fLevelOverride := $0000; end; {$endif} {$ifdef extra} if (GameParams.Info.dSection = 4) and (GameParams.Info.dLevel = 2) then GameParams.GameResult.gTarget := 66; {$endif} NextAvail := GetNext(NextInfo); Congrats := not NextAvail and gSuccess; // all levels finished if Congrats then begin {$ifndef flexi}Add(SCongrats); {$else} for x := 0 to 17 do begin Add(BuildText(SysDat.Congrats[x])); end; {$endif} // lemstrings end // default else begin // init some local strings STarget := PadL(i2s(gTarget) + '%', 4); SDone := PadL(i2s(gDone) + '%', 4); // top text if gTimeIsUp then Add(SYourTimeIsUp) else Add(SAllLemmingsAccountedFor); LF(1); Add(Format(SYouRescuedYouNeeded_ss, [SDone, STarget])); LF(1); i := GetResultIndex; {$ifndef flexi}Add(ResultStrings[i]); {$else} Add(BuildText(SysDat.SResult[i][0]) + #13 + BuildText(SysDat.SResult[i][1])); {$endif} LF(6); if gSuccess then begin H := Style.LevelSystem.GetLevelCode(NextInfo); // NextInfo.dSectionName + i2s(NextInfo.dLevel + 1); Add(Format(SYourAccessCode_ds, [NextInfo.dLevel + 1, H])); LF(3); end else begin H := Style.LevelSystem.GetLevelCode(GameParams.Info); // NextInfo.dSectionName + i2s(NextInfo.dLevel + 1); Add(Format(SYourAccessCode_ds, [GameParams.Info.dLevel + 1, H])); LF(3); end; end; // force bottomtext to a fixed position LF(18 - CountChars(#13, Result)); // bottom text // check final screen if Congrats then begin Add(SPressMouseToContinue) end // default bottom text else begin if gSuccess then Add(SPressLeftMouseForNextLevel) else Add(SPressLeftMouseToRetryLevel); Add(SPressRightMouseForMenu); end; end; end; procedure TGamePostviewScreen.Form_KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin {$ifdef testmode}if GameParams.fTestMode then CloseScreen(gstExit) else{$endif} CloseScreen(gstMenu); end; VK_RETURN: CloseScreen(gstPreview); end; end; procedure TGamePostviewScreen.Form_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin HandleMouseClick(Button); end; procedure TGamePostviewScreen.Img_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin HandleMouseClick(Button); end; procedure TGamePostviewScreen.HandleMouseClick(Button: TMouseButton); begin if Button = mbLeft then CloseScreen(gstPreview) else if Button = mbRight then begin {$ifdef testmode}if GameParams.fTestMode then CloseScreen(gstExit) else{$endif} CloseScreen(gstMenu); end; end; procedure TGamePostviewScreen.Form_KeyPress(Sender: TObject; var Key: Char); begin case Key of 'u': begin GlobalGame.Save; (* if not ForceDirectories(AppPath + 'Replay\') then Exit; GlobalGame.Recorder.SaveToFile(AppPath + 'Replay\' + gameparams.Info.dSectionName + '_' + leadzerostr(gameparams.info.dLevel + 1, 2) + '.lrb'); GlobalGame.Recorder.SaveToTxt(AppPath + 'Replay\' + gameparams.Info.dSectionName + '_' + leadzerostr(gameparams.info.dLevel + 1, 2) + '.txt'); *) end; end; end; end. function TGamePostviewScreen.GetScreenText_old: string; var N, i: Integer; SToRescuePerc: string; SRescuedPerc: string; procedure Add_oud(const S: string; LineFeeds: Integer); begin if S <> '' then Result := Result + PadC(S, 40) + StringOfChar(#13, LineFeeds) else Result := Result + #13 + StringOfChar(#13, LineFeeds) end; procedure AddResultText(const S: string); // adds result, splitting and adding 6 linefeeds begin Result := Result + PadC(SplitString(S, 0, #13), 40) + #13; Result := Result + PadC(SplitString(S, 1, #13), 40); Result := Result + StringOfChar(#13, 6); end; procedure Add(const S: string; LineFeeds: Integer); begin if S <> '' then Result := Result + S + StringOfChar(#13, LineFeeds) else Result := Result + #13 + StringOfChar(#13, LineFeeds) end; (* procedure AddResultText(const S: string); // adds result, splitting and adding 6 linefeeds begin Result := Result + PadC(SplitString(S, 0, #13), 40) + #13; Result := Result + PadC(SplitString(S, 1, #13), 40); Result := Result + StringOfChar(#13, 6); end;*) procedure PrepareText; var L: tstringlist; i: Integer; s: string; begin l:=SplitString_To_StringList(Result, #13); // deblist(l); result := ''; for i := 0 to l.count-1 do begin s:=l[i]; if s <> #13 then begin s := padc(s, 40); l[i] := s; end; if result <> '' then result := result + #13; result := result + s; end; l.free; end; var H: string; begin Result := ''; with GameParams, GameResult do begin // init some local strings SToRescuePerc := PadL(i2s(gTarget) + '%', 4); SRescuedPerc := PadL(i2s(gDone) + '%', 4); // top text Add('', 0); if gTimeIsUp then Add(SYourTimeIsUp) else Add(SAllLemmingsAccountedFor); Add(''); Add(Format(SYouRescued_s, [SRescuedPerc])); Add(Format(SYouNeeded_s, [SToRescuePerc])); Add(''); // result text if gDone = 100 then i := 8 else if gDone = 0 then i := 0 else if gDone < gTarget div 2 then i := 1 else if gDone < gTarget - 5 then i := 2 else if gDone < gTarget - 1 then i := 3 else if gDone = gTarget - 1 then i := 4 else if gDone = gTarget then i := 5 else if gDone < gTarget + 20 then i := 6 else if gDone >= gTarget + 20 then i := 7 else raise exception.Create('leveltext error'); Add(ResultStrings[i]); Add(''); Add(''); Add(''); Add(''); Add(''); Add(''); if gSuccess then begin H := Info.dSectionName {+ ''} + i2s(Info.dLevel + 2); Add(Format(SYourAccessCode_d, [Info.dLevel + 2])); Add('is ' + Info.dSectionName {+ ''} + i2s(Info.dLevel + 2)); // Add(''); (* // new levelcode text Add('Your Access Code for Level ' + i2s(Info.dLevel + 2), 1); //Add('is ABCDEFGHIJ', 3); { TODO : this must be changed when sections change } Add('is ' + Info.dSectionName {+ ''} + i2s(Info.dLevel + 2), 3); *) end else begin // else fake space Add(''); Add(''); Add(''); Add(''); end; // bottom text if gSuccess then Add(SPressLeftMouseForNextLevel, 1) else Add(SPressLeftMouseToRetryLevel, 1); Add(SPressRightMouseForMenu, 0); end; preparetext; end; function TGamePostviewScreen.GetScreenText_old: string; var N, i: Integer; STarget: string; SDone: string; H: string; procedure Add(const S: string); begin if Result <> '' then Result := Result + #13; if S <> '' then Result := Result + S; end; begin Result := ''; with GameParams, GameResult do begin // init some local strings STarget := PadL(i2s(gTarget) + '%', 4); SDone := PadL(i2s(gDone) + '%', 4); // top text if gTimeIsUp then Add(SYourTimeIsUp) else Add(SAllLemmingsAccountedFor); Add(Format(SYouRescued_s, [SRescuedPerc])); Add(Format(SYouNeeded_s, [SToRescuePerc])); // result text if gDone = 100 then i := 8 else if gDone = 0 then i := 0 else if gDone < gTarget div 2 then i := 1 else if gDone < gTarget - 5 then i := 2 else if gDone < gTarget - 1 then i := 3 else if gDone = gTarget - 1 then i := 4 else if gDone = gTarget then i := 5 else if gDone < gTarget + 20 then i := 6 else if gDone >= gTarget + 20 then i := 7 else raise exception.Create('leveltext error'); Add(ResultStrings[i], 6); //AddResultText(ResultStrings[i]); if gSuccess then begin H := Info.dSectionName {+ ''} + i2s(Info.dLevel + 2); Add( Format(SYourAccessCode_d, [Info.dLevel + 2]), 1); Add('is ' + Info.dSectionName {+ ''} + i2s(Info.dLevel + 2), 3); // (* // new levelcode text Add('Your Access Code for Level ' + i2s(Info.dLevel + 2), 1); //Add('is ABCDEFGHIJ', 3); { TODO : this must be changed when sections change } Add('is ' + Info.dSectionName {+ ''} + i2s(Info.dLevel + 2), 3); *) end else begin // else fake space Add('', 1); Add('', 3); end; // bottom text if gSuccess then Add(SPressLeftMouseForNextLevel, 1) else Add(SPressLeftMouseToRetryLevel, 1); Add(SPressRightMouseForMenu, 0); end; preparetext; end;
unit PassForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, TntComCtrls, Menus, Checksum, ExtCtrls, StdCtrls, m_GlobalDefs, m_api, hpp_global, hpp_contacts, hpp_database, hpp_forms; type TfmPass = class(TForm) Image1: TImage; rbProtAll: TRadioButton; rbProtSel: TRadioButton; lvCList: TTntListView; bnPass: TButton; laPassState: TLabel; Bevel1: TBevel; bnCancel: TButton; bnOK: TButton; PopupMenu1: TPopupMenu; Refresh1: TMenuItem; Label1: TLabel; procedure bnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure rbProtSelClick(Sender: TObject); procedure bnPassClick(Sender: TObject); procedure bnOKClick(Sender: TObject); procedure Refresh1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private PassMode: Byte; Password: String; FLastContact: THandle; procedure FillList; procedure UpdatePassword; procedure SetlastContact(const Value: THandle); procedure TranslateForm; public property LastContact: THandle read FLastContact write SetLastContact; { Public declarations } end; var fmPass: TfmPass; const PASSMODE_PROTNONE = 0; // no protection, not used PASSMODE_PROTALL = 1; // protect all contacts PASSMODE_PROTSEL = 2; // protect ONLY selected contacts PASSMODE_PROTNOTSEL = 3; // protect ALL, except selected contacts (not used) function ReadPassModeFromDB: Byte; function GetPassMode: Byte; function GetPassword: String; function IsPasswordBlank(Password: String): Boolean; function IsUserProtected(hContact: THandle): Boolean; function CheckPassword(Pass: String): Boolean; procedure RunPassForm; implementation uses PassNewForm, hpp_options, PassCheckForm; {$I m_database.inc} {$I m_langpack.inc} {$I m_clist.inc} {$R *.DFM} procedure RunPassForm; begin if Assigned(PassFm) then begin PassFm.Show; exit; end; if Assigned(PassCheckFm) then begin PassCheckFm.Show; exit; end; if IsPasswordBlank(GetPassword) then begin if not Assigned(PassFm) then begin PassFm := TfmPass.Create(nil); end; PassFm.Show; end else begin PassCheckFm := TfmPassCheck.Create(nil); PassCheckFm.Show; end; end; function CheckPassword(Pass: String): Boolean; begin Result := (DigToBase(HashString(Pass)) = GetPassword); end; function IsUserProtected(hContact: THandle): Boolean; var mode: Byte; begin Result := False; mode := GetPassMode; if mode = PASSMODE_PROTNONE then Result := False; if mode = PASSMODE_PROTALL then Result := True; if mode = PASSMODE_PROTSEL then Result := (DBGetContactSettingByte(hContact,hppDBName,'PasswordProtect',0) = 1); if mode = PASSMODE_PROTNOTSEL then Result := (DBGetContactSettingByte(hContact,hppDBName,'PasswordProtect',1) = 1); if IsPasswordBlank(GetPassword) then end; function IsPasswordBlank(Password: String): Boolean; begin Result := (Password = DigToBase(HashString(''))); end; function GetPassword: String; begin Result := GetDBStr(hppDBName,'Password',DigToBase(HashString(''))); end; function ReadPassModeFromDB: Byte; begin Result := GetDBByte(hppDBName,'PasswordMode',PASSMODE_PROTALL); end; function GetPassMode: Byte; begin Result := ReadPassModeFromDB; if IsPasswordBlank(GetPassword) then Result := PASSMODE_PROTNONE; end; procedure TfmPass.bnCancelClick(Sender: TObject); begin close; end; procedure TfmPass.FillList; procedure AddContact(Contact: THandle); var li: TTntListItem; Check: Byte; Capt: WideString; begin li := lvCList.Items.Add; if Contact = 0 then begin Capt := GetContactDisplayName(Contact,'ICQ'); Capt := AnsiToWideString(Translate('System History'),CP_ACP)+' ('+Capt+')'; end else Capt := GetContactDisplayName(Contact); li.Caption := Capt; li.Data := Pointer(Contact); Check := DBGetContactSettingByte(Contact,hppDBName,'PasswordProtect',0); if Check = 1 then li.Checked := True; end; var hCont: THandle; begin lvCList.Items.BeginUpdate; try lvCList.Items.Clear; hCont := PluginLink.CallService(MS_DB_CONTACT_FINDFIRST,0,0); while hCont <> 0 do begin AddContact(hCont); hCont := PluginLink.CallService(MS_DB_CONTACT_FINDNEXT,hCont,0); end; AddContact(0); lvCList.SortType := stNone; lvCList.SortType := stText; finally lvCList.Items.EndUpdate; end; end; procedure TfmPass.FormCreate(Sender: TObject); begin DesktopFont := True; MakeFontsParent(Self); TranslateForm; FillList; PassMode := ReadPassModeFromDB; if not (PassMode in [PASSMODE_PROTALL,PASSMODE_PROTSEL]) then PassMode := PASSMODE_PROTALL; Password := GetPassword; if PassMode = PASSMODE_PROTSEL then rbProtSel.Checked := true else rbProtAll.Checked := true; rbProtSelClick(Self); UpdatePassword; end; procedure TfmPass.rbProtSelClick(Sender: TObject); begin if rbProtSel.Checked then PassMode := PASSMODE_PROTSEL; if rbProtAll.Checked then PassMode := PASSMODE_PROTALL; if rbProtSel.Checked then begin lvCList.Enabled := True; lvCList.Color := clWindow; end else begin lvCList.Color := clInactiveBorder; lvCList.Enabled := False; end; end; procedure TfmPass.bnPassClick(Sender: TObject); begin with TfmPassNew.Create(Self) do begin if ShowModal = mrOK then begin Password := DigToBase(HashString(edPass.Text)); UpdatePassword; end; Free; end; end; procedure TfmPass.UpdatePassword; begin if Password = DigToBase(HashString('')) then begin // password not set laPassState.Font.Style := laPassState.Font.Style + [fsBold]; laPassState.Caption := Translate('Password not set'); end else begin // password set laPassState.ParentFont := True; laPassState.Caption := Translate('Password set'); end; end; procedure TfmPass.bnOKClick(Sender: TObject); var i: Integer; li: TListItem; begin WriteDBByte(hppDBName,'PasswordMode',PassMode); WriteDBStr(hppDBName,'Password',Password); if PassMode = PASSMODE_PROTSEL then begin for i := 0 to lvCList.Items.Count-1 do begin li := lvCList.Items[i]; if li.Checked then DBWriteContactSettingByte(Integer(li.Data),hppDBName,'PasswordProtect',1) else DBDeleteContactSetting(Integer(li.Data),hppDBName,'PasswordProtect'); end; end; Close; end; procedure TfmPass.SetlastContact(const Value: THandle); begin FLastContact := Value; end; procedure TfmPass.Refresh1Click(Sender: TObject); begin FillList; end; procedure TfmPass.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TfmPass.FormDestroy(Sender: TObject); begin try PassFm := nil; except end; end; procedure TfmPass.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Mask: Integer; begin with Sender as TWinControl do begin if Perform(CM_CHILDKEY, Key, Integer(Sender)) <> 0 then Exit; Mask := 0; case Key of VK_TAB: Mask := DLGC_WANTTAB; VK_RETURN, VK_EXECUTE, VK_ESCAPE, VK_CANCEL: Mask := DLGC_WANTALLKEYS; end; if (Mask <> 0) and (Perform(CM_WANTSPECIALKEY, Key, 0) = 0) and (Perform(WM_GETDLGCODE, 0, 0) and Mask = 0) and (Self.Perform(CM_DIALOGKEY, Key, 0) <> 0) then Exit; end; end; procedure TfmPass.TranslateForm; begin Caption := Translate(PChar(Caption)); Label1.Caption := Translate(PChar(Label1.Caption)); rbProtAll.Caption := Translate(PChar(rbProtAll.Caption)); rbProtSel.Caption := Translate(PChar(rbProtSel.Caption)); bnPass.Caption := Translate(PChar(bnPass.Caption)); bnOK.Caption := Translate(PChar(bnOK.Caption)); bnCancel.Caption := Translate(PChar(bnCancel.Caption)); Refresh1.Caption := Translate(PChar(Refresh1.Caption)); end; end.
unit Voyager; interface uses VoyagerInterfaces, Collection, Controls; type // TMetaFrame is a wrapper to a IMetaURLHandler. It contains an // IMetaURLHandler and also implements it. TMetaFrame = class( TObject, IURLHandler ) public constructor Create( aMetaURLHandler : IMetaURLHandler ); destructor Destroy; override; private fMetaURLHandler : IMetaURLHandler; fFrames : TCollection; private function GetName : string; function GetOptions : TURLHandlerOptions; function GetInstanceLimit : integer; public property Name : string read GetName; property Options : TURLHandlerOptions read GetOptions; property InstanceLimit : integer read GetInstanceLimit; public function Instantiate : IURLHandler; end; // TFrame is a wrapper to a IURLHandler. It contains a IURLHandler and also // implements it. TFrame = class( TObject, IURLHandler ) public constructor Create( aMetaFrame : TMetaFrame ); destructor Destroy; override; private fMetaFrame : TMetaFrame; fURLHandler : TURLHandler; private function GetControl : TControl; public property Control : TControl read GetControl; public function HandleURL( URL : string ) : TURLHandlingResult; function DisplayStatus( StatusId : TStatusId; var status ); end; implementation end.
unit uDataProcess; interface uses Windows, System.SysUtils, System.Classes, uPublic, uServerPublic, HPSocketSDKUnit, QMsgPack ; type // 处理接受客户端结构体 TDataProcess = class(TThread) private FConnID: DWORD; FMsgPack: TQMsgPack; function SetGroupName: Boolean; function fnRetResult: Boolean; function fnSendSms: Boolean; function GetDeviceInfo(AGroupName: string; var ADeviceInfo: TDeviceInfo): Boolean; protected procedure Execute; override; public constructor Create(AConnid: DWORD; AData: Pointer; ADataLen: Integer); destructor Destroy; override; end; implementation { TDataProcess } constructor TDataProcess.Create(AConnid: DWORD; AData: Pointer; ADataLen: Integer); var vBin: TBytes; begin inherited Create(False); FMsgPack := TQMsgPack.Create; try SetLength(vBin, ADataLen); CopyMemory(vBin, AData, ADataLen); FMsgPack.Parse(vBin); FConnID := AConnid; FreeOnTerminate := True; finally SetLength(vBin, 0); end; end; destructor TDataProcess.Destroy; begin FreeAndNil(FMsgPack); inherited; end; procedure TDataProcess.Execute; var vCommType: TCommType; begin // inherited; vCommType := TCommType(FMsgPack.ItemByName('Cmd').AsInteger); case vCommType of ctNone: ; ctResult: fnRetResult; ctGroupName: SetGroupName; ctSendMsg: fnSendSms; ctRecvMsg: ; end; end; function TDataProcess.GetDeviceInfo(AGroupName: string; var ADeviceInfo: TDeviceInfo): Boolean; var dwKey: DWORD; begin Result := False; //--获取Device的ConnectID for dwKey in GDeviceInfos.Keys do begin if GDeviceInfos[dwKey].GroupName = AGroupName then begin ADeviceInfo := GDeviceInfos[dwKey]; Result := True; Break; end; end; end; function TDataProcess.fnRetResult: Boolean; begin Result := False; try Result := SendResult( FMsgPack.ItemByName('ClientId').AsInteger, TCommType(FMsgPack.ItemByName('PriorCmd').AsInteger), TResultState(FMsgPack.ItemByName('Ret').AsInteger), FMsgPack.ItemByName('Content').AsString ); AddLogMsg('Result to client[%d]...', [FMsgPack.ItemByName('ClientId').AsInteger]); except AddLogMsg('ProcessResult fail[%d]...', [FMsgPack.ItemByName('ClientId').AsInteger]); end; end; function TDataProcess.fnSendSms: Boolean; var sQQ: string; sGroupName, sComPort: string; vMsgPack: TQMsgPack; vCmdType: TCommType; vConnId: DWORD; vDeviceInfo: TDeviceInfo; vBuf: TBytes; begin Result := False; try vCmdType := TCommType(FMsgPack.ItemByName('Cmd').AsInteger); sQQ := FMsgPack.ItemByName('QQ').AsString; if sQQ = '' then begin SendResult(FConnID, vCmdType, rsFail, 'QQ号不能为空'); Exit; end; // {$IFDEF DEBUG} // sGroupName := 'ModelPool2'; // sComPort := 'COM36'; // {$ELSE} if not GetModelPoolInfo(sQQ, sGroupName, sComPort) then begin SendResult(FConnID, vCmdType, rsFail, '没有找到此账号对应的串口'); Exit; end; // {$ENDIF} if not GetDeviceInfo(sGroupName, vDeviceInfo) then begin SendResult(FConnID, vCmdType, rsFail, '没有找到链接的设备'); Exit; end; vMsgPack := FMsgPack.Copy; try vMsgPack.Add('ComPort', sComPort); vMsgPack.Add('ClientId', FConnID); vBuf := vMsgPack.Encode; if not SendData(vDeviceInfo.ConnectID, vBuf, Length(vBuf)) then begin SendResult(FConnID, vCmdType, rsFail, '给设备发送信息失败'); Exit; end; AddLogMsg('vSmsData to add database...', []); Result := True; finally SetLength(vBuf, 0); FreeAndNil(vMsgPack); end; except AddLogMsg('ProcessSmsData fail[%d]...', [GetLastError()]); end; end; function TDataProcess.SetGroupName: Boolean; var vDeviceInfo: TDeviceInfo; I: Integer; sGroupName: string; begin Result := False; try sGroupName := FMsgPack.ItemByName('GroupName').AsString; //TODO: if not GDeviceInfos.ContainsKey(FConnID) then begin vDeviceInfo.ConnectID := FConnID; end else begin vDeviceInfo := TDeviceInfo(GDeviceInfos[FConnID]); end; vDeviceInfo.IsDevice := True; vDeviceInfo.GroupName := sGroupName; GDeviceInfos.AddOrSetValue(FConnID, vDeviceInfo); SendMessage(GFrmMainHwnd, WM_ADD_DEVICE, 0, LPARAM(FConnID)); except AddLogMsg('SetGroupName fail[%d]...', [GetLastError()]); Exit; end; Result := True; end; end.
unit FFSComboBox; interface uses Windows, Messages, Classes, Forms, Controls, Graphics, StdCtrls, sysutils; type TFFSComboBox = class(TCustomComboBox) private FAutoFocus: boolean; FFlat: Boolean; FEtched: Boolean; FOldColor: TColor; FOldParentColor: Boolean; FButtonWidth: Integer; FFocusBorder: Boolean; FMouseInControl: Boolean; fDropWidth: integer; procedure SetEtched(const Value: Boolean); procedure SetFlat(const Value: Boolean); procedure SetButtonWidth(const Value: Integer); procedure DrawButtonBorder(DC:HDC); procedure DrawControlBorder(DC:HDC); procedure DrawBorders; function Is3DBorderControl: Boolean; function Is3DBorderButton: Boolean; procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMEnabledChanged(var Msg: TMessage); message CM_ENABLEDCHANGED; procedure CNCommand (var Message: TWMCommand); message CN_COMMAND; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMNCPaint (var Message: TMessage); message WM_NCPAINT; procedure SetDropWidth(const Value: integer); protected published property ButtonWidth: integer read fButtonWidth write SetButtonWidth; property Flat: Boolean read FFlat write SetFlat; property Etched: Boolean read FEtched write SetEtched; property FocusBorder: Boolean read FFocusBorder write FFocusBorder; property AutoFocus: Boolean read FAutoFocus write FAutoFocus; property DropWidth: integer read fDropWidth write SetDropWidth; property Style; property Color; property Ctl3D; property DragCursor; property DragMode; property DropDownCount; property Enabled; property Font; {$IFNDEF DELPHI2_LVL} property ImeMode; property ImeName; {$ENDIF} property ItemHeight; property Items; property MaxLength; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Sorted; property TabOrder; property TabStop; property Text; property Visible; property OnChange; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnStartDrag; {$IFDEF DELPHI4_LVL} property Anchors; property BiDiMode; property Constraints; property DragKind; property ParentBiDiMode; property OnEndDock; property OnStartDock; {$ENDIF} public constructor Create(AOwner: TComponent); override; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Controls', [TFFSComboBox]); end; { TFFSComboBox } constructor TFFSComboBox.Create(AOwner: TComponent); begin inherited; FButtonWidth:=GetSystemMetrics(SM_CXVSCROLL) + 2; FOldColor:=inherited Color; FOldParentColor:=inherited ParentColor; FFlat:=true; FMouseInControl:=false; end; procedure TFFSComboBox.SetButtonWidth(const Value: integer); begin if (value<14) or (value>32) then exit; fButtonWidth:=value; Invalidate; end; procedure TFFSComboBox.SetFlat(const Value: Boolean); begin if Value<>FFlat then begin FFlat:=Value; Ctl3D:=not Value; Invalidate; end; end; procedure TFFSComboBox.SetEtched(const Value: Boolean); begin if Value<>FEtched then begin FEtched:=Value; Invalidate; end; end; procedure TFFSComboBox.CMEnter(var Message: TCMEnter); begin inherited; if not (csDesigning in ComponentState) then DrawBorders; end; procedure TFFSComboBox.CMExit(var Message: TCMExit); begin inherited; if not (csDesigning in ComponentState) then DrawBorders; end; procedure TFFSComboBox.CMMouseEnter(var Message: TMessage); begin inherited; if not FMouseInControl and Enabled then begin FMouseInControl := True; DrawBorders; end; if fAutoFocus then self.SetFocus; end; procedure TFFSComboBox.CMMouseLeave(var Message: TMessage); begin inherited; if FMouseInControl and Enabled then begin FMouseInControl := False; DrawBorders; end; end; procedure TFFSComboBox.CMEnabledChanged(var Msg: TMessage); begin if FFlat then begin if Enabled then begin inherited ParentColor:=FOldParentColor; inherited Color:=FOldColor; end else begin FOldParentColor:=inherited Parentcolor; FOldColor:=inherited Color; inherited ParentColor:=True; end; end; inherited; end; procedure TFFSComboBox.WMNCPaint(var Message: TMessage); begin inherited; if fFlat then DrawBorders; end; procedure TFFSComboBox.WMPaint(var Message: TWMPaint); var DC: HDC; PS: TPaintStruct; procedure DrawButton; var ARect: TRect; begin GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); Inc(ARect.Left, ClientWidth - FButtonWidth); InflateRect(ARect, -1, -1); DrawFrameControl(DC, ARect, DFC_SCROLL, DFCS_SCROLLCOMBOBOX or DFCS_FLAT ); ExcludeClipRect(DC, ClientWidth - FButtonWidth - 2, 0, ClientWidth, ClientHeight); end; begin if not FFlat then begin inherited; Exit; end; if Message.DC = 0 then DC:=BeginPaint(Handle, PS) else DC:=Message.DC; try if (Style<>csSimple) then begin FillRect(DC, ClientRect, Brush.Handle); DrawButton; end; PaintWindow(DC); finally if Message.DC=0 then EndPaint(Handle, PS); end; DrawBorders; end; function TFFSComboBox.Is3DBorderControl: Boolean; begin if csDesigning in ComponentState then Result:=false else Result:=FMouseInControl or (Screen.ActiveControl = Self); result:=result and fFocusBorder; end; function TFFSComboBox.Is3DBorderButton: Boolean; begin if csDesigning in ComponentState then Result:=Enabled else Result:=FMouseInControl or (Screen.ActiveControl = Self); end; procedure TFFSComboBox.DrawButtonBorder(DC: HDC); const Flags: array[Boolean] of Integer = (0, BF_FLAT); Edge: array[Boolean] of Integer = (EDGE_RAISED,EDGE_ETCHED); var ARect: TRect; BtnFaceBrush: HBRUSH; begin ExcludeClipRect(DC, ClientWidth - FButtonWidth + 4, 4, ClientWidth - 4, ClientHeight - 4); GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); Inc(ARect.Left, ClientWidth - FButtonWidth - 2); InflateRect(ARect, -2, -2); if Is3DBorderButton then DrawEdge(DC, ARect, Edge[Etched], BF_RECT or Flags[DroppedDown]) else begin BtnFaceBrush:=CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); InflateRect(ARect, 0, -1); arect.right:=arect.right-1; FillRect(DC, ARect, BtnFaceBrush); DeleteObject(BtnFaceBrush); end; ExcludeClipRect(DC, ARect.Left, ARect.Top, ARect.Right, ARect.Bottom); end; procedure TFFSComboBox.DrawControlBorder(DC: HDC); var ARect:TRect; BtnFaceBrush, WindowBrush: HBRUSH; begin if Is3DBorderControl then BtnFaceBrush:=CreateSolidBrush(GetSysColor(COLOR_BTNFACE)) else BtnFaceBrush:=CreateSolidBrush(ColorToRGB((parent as TWinControl).brush.color)); WindowBrush:=CreateSolidBrush(ColorToRGB(self.Color)); try GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); if Is3DBorderControl then begin DrawEdge(DC, ARect, BDR_SUNKENOUTER, BF_RECT or BF_ADJUST); FrameRect(DC, ARect, BtnFaceBrush); InflateRect(ARect, -1, -1); FrameRect(DC, ARect, WindowBrush); end else begin DrawEdge(DC, ARect, BDR_SUNKENOUTER, BF_BOTTOM or BF_MONO or BF_ADJUST); // FrameRect(DC, ARect, BtnFaceBrush); // InflateRect(ARect, -1, -1); FrameRect(DC, ARect, BtnFaceBrush); InflateRect(ARect, -1, -1); FrameRect(DC, ARect, WindowBrush); end; finally DeleteObject(WindowBrush); DeleteObject(BtnFaceBrush); end; end; procedure TFFSComboBox.DrawBorders; var DC: HDC; begin if not FFlat then Exit; DC:=GetWindowDC(Handle); try DrawControlBorder(DC); if (Style<>csSimple) then DrawButtonBorder(DC); finally ReleaseDC(Handle,DC); end; end; procedure TFFSComboBox.CNCommand(var Message: TWMCommand); var r:trect; begin inherited; if (Message.NotifyCode in [CBN_CLOSEUP,CBN_DROPDOWN]) then begin r:=GetClientRect; r.left:=r.right-fbuttonwidth; InvalidateRect(Handle,@r,FALSE); end; end; procedure TFFSComboBox.SetDropWidth(const Value: integer); begin fDropWidth := Value; if (value>0) then SendMessage(self.handle,CB_SETDROPPEDWIDTH,fDropWidth,0); end; end.