text
stringlengths
14
6.51M
program uva100(input, output); const MAX_MEMO = 65536; var memoized: array[0..MAX_MEMO] of Integer; res: LongInt; function CountSeqLen(n: LongInt): Integer; var res: Integer; begin if n = 1 then res := 1 else if (n <= MAX_MEMO) and (memoized[n] <> 0) then res := memoized[n] else begin if n and 1 = 1 then res := 1 + CountSeqLen(3 * n + 1) else res := 1 + CountSeqLen(n div 2); if n <= MAX_MEMO then memoized[n] := res; end; CountSeqLen := res; end; procedure swap(var i: LongInt; var k: LongInt); var tmp: LongInt; begin tmp := i; i := k; k := tmp; end; var i, k, origI, origK : LongInt; j: LongInt; max, r: Integer; begin memoized[1] := 1; While not eof(input) do begin readln(origI, origK); i := origI; k := origK; if i > k then swap(i,k); max := 0; for j := i to k do begin res := CountSeqLen(j); if res > max then max := res; end; writeln(origI, ' ', origK, ' ', max); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Hash.FastHash; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types; type TpvHashFastHash=class public const m=TpvUInt64($880355f21e6d1965); type TMessageDigest=TpvUInt64; PMessageDigest=^TMessageDigest; public class function Process(const aData:pointer;const aDataLength:TpvSizeUInt;const aSeed:TpvUInt64=0):TMessageDigest; static; end; implementation { TpvHashFastHash } class function TpvHashFastHash.Process(const aData:pointer;const aDataLength:TpvSizeUInt;const aSeed:TpvUInt64):TpvHashFastHash.TMessageDigest; label l6,l5,l4,l3,l2,l1; var CurrentData,DataEnd:Pointer; v:TpvUInt64; begin CurrentData:=aData; DataEnd:=@PpvUInt8Array(aData)^[TpvPtrUInt(aDataLength) and not TpvPtrUInt(7)]; result:=aSeed xor (aDataLength*m); while TpvPtrUInt(CurrentData)<TpvPtrUInt(DataEnd) do begin v:=PpvUInt64(CurrentData)^; inc(PpvUInt64(CurrentData)); v:=(v xor (v shr 23))*TpvUInt64($127599bf4325c37); v:=v xor (v shr 47); result:=(result xor v)*m; end; v:=0; case aDataLength and 7 of 7:begin v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[6]) shl 48); goto l6; end; 6:begin l6: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[5]) shl 40); goto l5; end; 5:begin l5: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[4]) shl 32); goto l4; end; 4:begin l4: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[3]) shl 24); goto l3; end; 3:begin l3: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[2]) shl 16); goto l2; end; 2:begin l2: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[1]) shl 8); goto l1; end; 1:begin l1: v:=v xor (TpvUInt64(PpvUInt8Array(CurrentData)^[0]) shl 0); v:=(v xor (v shr 23))*TpvUInt64($127599bf4325c37); v:=v xor (v shr 47); result:=(result xor v)*m; end; end; result:=(result xor (result shr 23))*TpvUInt64($127599bf4325c37); result:=result xor (result shr 47); end; end.
unit PLAT_RegisterFunctionLink; interface uses PLAT_R9FunctionLink,Sysutils,Classes; type TRegisterFunctionLink=Class(TR9FunctionLink) private FFunctionName:String; FParameterNames:String; FParameterValues:string; public procedure Execute;override; procedure LoadFromStream(Stream:TStream);override; procedure SaveToStream(Stream:TStream);override; end; implementation { TRegisterFunctionLink } uses PLAT_Utils,PLAT_R9SystemFactory; procedure TRegisterFunctionLink.Execute; begin inherited; self.FIntfSystem.ExecuteRigisterFunction(FFunctionName,FParameterNames,FParameterValues); end; procedure TRegisterFunctionLink.LoadFromStream(Stream: TStream); var szData:String; begin inherited; TUtils.LoadStringFromStream (Stream,szData); Tutils.LoadStringFromStream (Stream,FCaption); TUtils.LoadStringFromStream(Stream,FDescription); Stream.Read(FLeft,SizeOf(FLeft)); Stream.Read (FTop,SizeOf(FTop)); TUtils.LoadStringFromStream(Stream,FSubSystemName ); TUtils.LoadStringFromStream (Stream,FAppletFileName); TUtils.LoadStringFromStream(Stream,FFunctionName); TUtils.LoadStringFromStream(Stream,FParameterNames); TUtils.LoadStringFromStream(Stream,FParameterValues); end; procedure TRegisterFunctionLink.SaveToStream(Stream: TStream); var szData:String; begin inherited; szData:=self.ClassName ; TUtils.SaveStringToStream (Stream,szData); //pub start Tutils.SaveStringToStream (Stream,FCaption); TUtils.SaveStringToStream(Stream,FDescription); Stream.Write(FLeft,SizeOf(FLeft)); Stream.Write (FTop,SizeOf(FTop)); //pub start TUtils.SaveStringToStream(Stream,FSubSystemName ); TUtils.SaveStringToStream (Stream,FAppletFileName); TUtils.SaveStringToStream(Stream,FFunctionName); TUtils.SaveStringToStream(Stream,FParameterNames); TUtils.SaveStringToStream(Stream,FParameterValues); FIntfSystem:=TR9SystemFactory.GetInstance.GetSubSysByName (FSubSystemName ,FAppletFileName ); end; end.
unit Gen; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface uses _FAreas; procedure RunGenerator; procedure BuildComment( FD: PFileDef; const Path: String ); { =================================================================== } implementation uses {$IFDEF WIN32} Windows, UnRAR, UnZIP, {$ENDIF} Objects, _LOG, _CFG, SysUtils, MyLib, ArcV, Spawn, AreaPane, EchoPane, _Report, _Script, _CRC32, _Working, _RES, vpUtils, MsgBox, Views; { --------------------------------------------------------- } { TAnnounce } { --------------------------------------------------------- } type PAnItem = ^TAnItem; TAnItem = record FileName: PString; FileDate: UnixTime; AreaCRC : Longint; end; { TAnItem } PAnnounce = ^TAnnounce; TAnnounce = object (TSortedCollection) Modified: Boolean; Version : SmallWord; constructor Init; constructor Load( var S: TStream ); procedure Store( var S: TStream ); function Compare( Key1, Key2: Pointer ) : Integer; virtual; procedure FreeItem( Item: Pointer ); virtual; procedure PutItem( var S: TStream; Item: Pointer ); virtual; function GetItem( var S: TStream ) : Pointer; virtual; procedure Refresh; procedure Freshen( Area: PFileArea; FD: PFileDef ); private function FindItem( FD: PFileDef; Area: PFileArea ) : PAnItem; function NewItem( FD: PFileDef; Area: PFileArea ) : PAnItem; end; { TAnnounce } const AnnSignStr = 'HI-FILES Announce'#26; type TAnnSign = array [0..Length(AnnSignStr)-1] of Char; const AnnSign : TAnnSign = AnnSignStr; const ANNOUNCE_EXT = '.Ann'; var Announce: PAnnounce; { Init ---------------------------------------------------- } constructor TAnnounce.Init; begin inherited Init( 50, 50 ); end; { Init } { Load ---------------------------------------------------- } constructor TAnnounce.Load( var S: TStream ); var Sign: TAnnSign; begin try S.Read( Sign, SizeOf(TAnnSign) ); if StrLComp( Sign, AnnSign, SizeOf(TAnnSign) ) <> 0 then raise Exception.Create( LoadString(_SBadAnFile) ); S.Read( Version, SizeOf(SmallWord) ); if (Version <> 3) and (Version <> 4) then raise Exception.Create( Format(LoadString(_SBadAnVer), [Version] )); inherited Load( S ); except on E: Exception do begin ShowError( Format(LoadString(_SAnFailed), [E.Message] )); Fail; end; end; end; { Load } { Store --------------------------------------------------- } procedure TAnnounce.Store( var S: TStream ); begin Version := 4; S.Write( AnnSign, SizeOf(AnnSign) ); S.Write( Version, SizeOf(SmallWord) ); inherited Store( S ); end; { Store } { FreeItem ------------------------------------------------ } procedure TAnnounce.FreeItem( Item: Pointer ); begin FreeStr( PAnItem(Item)^.FileName ); Dispose( PAnItem(Item) ); end; { FreeItem } { Compare ------------------------------------------------- } function TAnnounce.Compare( Key1, Key2: Pointer ) : Integer; var A1: PAnItem absolute Key1; A2: PAnItem absolute Key2; begin Result := JustCompareText( A1^.FileName^, A2^.FileName^ ); if Result = 0 then begin if A1^.AreaCRC > A2^.AreaCRC then Result := 1 else if A1^.AreaCRC < A2^.AreaCRC then Result := -1 else Result := 0; end; end; { Compare } { PutItem ------------------------------------------------- } procedure TAnnounce.PutItem( var S: TStream; Item: Pointer ); var A: PAnItem absolute Item; begin S.WriteStr( A^.FileName ); S.Write( A^.FileDate, SizeOf(TAnItem) - SizeOf(PString) ); end; { PutItem } { GetItem ------------------------------------------------- } function TAnnounce.GetItem( var S: TStream ) : Pointer; var A: PAnItem; F: String[12]; begin New( A ); if Version = 3 then begin S.Read( F, SizeOf(F) ); A^.FileName := AllocStr(F); end else A^.FileName := S.ReadStr; S.Read( A^.FileDate, SizeOf(TAnItem) - SizeOf(PString) ); Result := A; end; { GetItem } { FindItem ------------------------------------------------ } function TAnnounce.FindItem( FD: PFileDef; Area: PFileArea ) : PAnItem; var A: TAnItem; j: Integer; begin A.FileName := FD^.FileName; A.FileDate := FileTimeToUnix( FD^.Time ); A.AreaCRC := GetStrCRC( Area^.Name^ ); if Search( @A, j ) then Result := At(j) else Result := nil; end; { FindItem } { NewItem ------------------------------------------------- } function TAnnounce.NewItem( FD: PFileDef; Area: PFileArea ) : PAnItem; begin New( Result ); with Result^ do begin FileName := AllocStr( FD^.FileName^ ); FileDate := FileTimeToUnix( FD^.Time ); AreaCRC := GetStrCRC( Area^.Name^ ); end; end; { NewItem } { Refresh ------------------------------------------------- } procedure TAnnounce.Refresh; var j: Integer; Z: UnixTime; A: PAnItem; procedure RefreshArea( Area: PFileArea ); far; var FD: PFileDef; begin j := 0; while j < Area^.Count do begin FD := Area^.At(j); A := FindItem( FD, Area ); if A = nil then begin Insert( NewItem( FD, Area ) ); Modified := True; Inc(j); end else Area^.AtFree(j); end; end; { RefreshArea } begin Log^.Write( ll_Protocol, LoadString(_SLogCheckingAn) ); Z := CurrentUnixTime; j := 0; while j < Count do begin A := At(j); // ’à¥åªà â­ë© § ¯ á ­  㢥«¨ç¥­¨¥ "àã窠¬¨" NewFilesAge if DaysBetween( Z, A^.FileDate ) > 3 * CFG^.NewFilesAge then begin AtFree( j ); Modified := True; Continue; end; Inc( j ); end; FileBase^.ForEach( @RefreshArea ); FileBase^.Clean; end; { Refresh } { Freshen ------------------------------------------------- } procedure TAnnounce.Freshen( Area: PFileArea; FD: PFileDef ); var A: PAnItem; begin A := FindItem( FD, Area ); if A <> nil then begin Free( A ); Modified := True; end; end; { Freshen } { --------------------------------------------------------- } { OpenAnnounce } { --------------------------------------------------------- } procedure OpenAnnounce; var FileName: String; Stream : TBufStream; begin if Announce <> nil then Exit; FileName := ChangeFileExt( ParamStr(0), ANNOUNCE_EXT ); if FileExists( FileName ) then begin Log^.Write( ll_Protocol, LoadString(_SOpeningAnFile) ); Stream.Init( FileName, stOpenRead, 2048 ); if Stream.Status <> stOk then Log^.Write( ll_Warning, Format(LoadString(_SCantOpenAn), [FileName] )) else Announce := New( PAnnounce, Load(Stream) ); Stream.Done; end; if Announce = nil then begin Announce := New( PAnnounce, Init ); Log^.Write( ll_Service, LoadString(_SLogAnCreated) ); end; end; { OpenAnnounce } { --------------------------------------------------------- } { CloseAnnounce } { --------------------------------------------------------- } procedure CloseAnnounce; var FileName: String; Stream : TBufStream; begin if Announce <> nil then begin if Announce^.Modified then begin Log^.Write( ll_Protocol, LoadString(_SLogSavingAn) ); FileName := ChangeFileExt( ParamStr(0), ANNOUNCE_EXT ); Stream.Init( FileName, stCreate, 2048 ); if Stream.Status = stOk then Announce^.Store( Stream ) else Log^.Write( ll_Warning, Format(LoadString(_SCantCreateAn), [FileName] )); Stream.Done; end; Destroy( Announce ); Announce := nil; end; end; { CloseAnnounce } { --------------------------------------------------------- } { ScanArcIndex } { --------------------------------------------------------- } var DizFound: String; procedure ScanArcIndex( const FName: String; FTime, OrigSize, PackSize: Longint ); far; var N: String; begin if DizFound = '' then begin N := Trim( FName ); if CFG^.DizFiles^.Match(N) and (OrigSize > 0) then DizFound := N; end; end; { ScanArcIndex } { --------------------------------------------------------- } { SearchDiz } { --------------------------------------------------------- } function SearchDiz( const Archive: String ) : String; begin DizFound := ''; AddFileCallBack := ScanArcIndex; ReadArchive( Archive ); Result := DizFound; end; { SearchDiz } { --------------------------------------------------------- } { Excluded } { --------------------------------------------------------- } function Excluded( FileName: ShortString ) : Boolean; function Match( Pat: PString ) : Boolean; far; begin Result := WildMatch( FileName, Pat^ ); end; begin Result := JustSameText( FileName, 'FILES.BBS' ) or (CFG^.Exclude^.FirstThat( @Match ) <> nil); end; { Excluded } { --------------------------------------------------------- } { MoveComment } { --------------------------------------------------------- } procedure MoveComment( Source, Target: PFileDef ); procedure DoMove( P: PString ); far; begin Target^.Insert( P ); end; { DoMove } begin Source^.ForEach( @DoMove ); Source^.DeleteAll; end; { MoveComment } { --------------------------------------------------------- } { BuildComment } { --------------------------------------------------------- } procedure BuildComment( FD: PFileDef; const Path: String ); { TryDLL -------------------------------------------------- } {$IFDEF WIN32} function TryDLL: Boolean; const BUFSIZE = 16 * 1024; var A: THandle; ArcName : array [0..260] of Char; DestName: array [0..260] of Char; Buffer : PChar; BufLen : Longint; AD: RAROpenArchiveData; HD: RARHeaderData; RHCode: Integer; PFCode: Integer; Diz : String; Zip : TZipRec; begin Result := False; if JustSameText( ExtractFileExt(FD^.FileName^), '.rar' ) and UnrarLoaded then begin FillChar( AD, SizeOf(AD), 0 ); AD.ArcName := StrPCopy( ArcName, AtPath(FD^.NativeName^, Path)); AD.OpenMode := RAR_OM_EXTRACT; A := RAROpenArchive( AD ); if AD.OpenResult <> 0 then begin Log^.Write( ll_Warning, LoadString(_SLogUnrarOpenError) ); Exit; end; Result := True; try repeat RHCode := RARReadHeader( A, HD ); if RHCode <> 0 then Break; Diz := ExtractFileName( StrPas(HD.FileName) ); if CFG^.DizFiles^.Match( Diz ) then begin Diz := AtPath( Diz, CFG^.TempDir ); StrPCopy( DestName, Diz ); PFCode := RARProcessFile( A, RAR_EXTRACT, nil, DestName ); if PFCode <> 0 then raise Exception.Create( Format(LoadString(_SLogUnrarError), [PFCode] )); FD^.LoadFromFile( Diz ); VFS_EraseFile( Diz ); RARCloseArchive( A ); Log^.Write( ll_Protocol, Format(LoadString(_SDizExtracted), [ExtractFilename(Diz)] )); Exit; end; PFCode := RARProcessFile( A, RAR_SKIP, nil, nil ); if PFCode <> 0 then raise Exception.Create( Format(LoadString(_SLogUnrarError), [PFCode] )); until false; if RHCode = ERAR_BAD_DATA then raise Exception.Create( LoadString(_SLogUnrarHdrBroken) ); except on E: Exception do Log^.Write( ll_Warning, E.Message ); end; RARCloseArchive( A ); end else if JustSameText( ExtractFileExt(FD^.FileName^), '.zip' ) and UnzipLoaded then begin StrPCopy( ArcName, AtPath(FD^.NativeName^, Path) ); try RHCode := GetFirstInZip( ArcName, Zip ); Result := RHCode = unzip_ok; while RHCode = unzip_ok do begin Diz := StrPas( Zip.FileName ); if CFG^.DizFiles^.Match( Diz ) then begin CloseZipFile( Zip ); GetMem( Buffer, BUFSIZE ); BufLen := BUFSIZE; PFCode := UnzipFile( ArcName, Buffer, BufLen, Zip.Offset, 0, 0 ); if PFCode < 0 then raise Exception.Create( Format(LoadString(_SLogUnrarError), [PFCode] )); FD^.EatBuffer( Buffer, BufLen ); // Warning: Buffer destroyed by 'EatBuffer' procedure! Log^.Write( ll_Protocol, Format(LoadString(_SDizExtracted), [ExtractFilename(Diz)] )); Exit; end; RHCode := GetNextInZip( Zip ); end; except on E: Exception do Log^.Write( ll_Warning, E.Message ); end; end; end; { TryDll } {$ENDIF} { TryArchive ---------------------------------------------- } procedure TryArchive; var Arc: String; Exe: String; Par: String; Diz: String; Cur: String; ErrCode: Integer; begin if CFG^.DizFiles^.Count < 1 then Exit; if not CFG^.Archivers^.GetCall( FD^.FileName^, Arc ) then Exit; Diz := SearchDiz( AtPath(FD^.FileName^, Path) ); // …᫨ ¬ £¨ï ­¨ç¥£® ­¥ ­ è« , ¯®¯à®¡ã¥¬ ¨§¢«¥çì ¯¥à¢ë© ®¯¨á â¥«ì ¨§ ᯨ᪠. if Diz = '' then Diz := PString(CFG^.DizFiles^.At(0))^; Cur := GetCurrentDir; try if not SetCurrentDir( CFG^.TempDir ) then raise Exception.Create( Format(LoadString(_SCantSetTmpDir), [CFG^.TempDir] )); if FileExists( Diz ) then begin if not VFS_EraseFile( Diz ) then raise Exception.Create( Format(LoadString(_SCantDelTmpFile), [AtPath(Diz, CFG^.TempDir)]) ); end; Log^.Write( ll_Protocol, Format(LoadString(_SRunExternal), [Arc] )); SplitPair( Arc, Exe, Par ); ErrCode := Execute( Exe, Par + ' ' + AtPath(FD^.FileName^, Path) + ' ' + Diz, True ); if ErrCode < 0 then raise Exception.Create( Format(LoadString(_SExtRunError), [-ErrCode] )); if ErrCode > 0 then raise Exception.Create( Format(LoadString(_SExtRunErrLevel), [ErrCode] )); except on E: Exception do Log^.Write( ll_Warning, E.Message ); end; if FileExists( Diz ) then begin Log^.Write( ll_Protocol, Format(LoadString(_SDizExtracted), [Diz] )); FD^.LoadFromFile( Diz ); VFS_EraseFile( Diz ); end else Log^.Write( ll_Protocol, LoadString(_SLogNoDizInArc) ); SetCurrentDir( Cur ); end; { TryArchive } { TryFetch ------------------------------------------------ } procedure TryFetch; var Exe: String; Diz: String; ErrCode: Integer; begin if not CFG^.Fetches^.GetCall( FD^.FileName^, Exe ) then Exit; Log^.Write( ll_Protocol, Format(LoadString(_SRunExternal), [Exe] )); Diz := AtPath( DIZ_FILE, CFG^.TempDir ); try if FileExists( Diz ) then begin if not VFS_EraseFile( Diz ) then raise Exception.Create( Format(LoadString(_SCantDelTmpFile), [AtPath(Diz, CFG^.TempDir)] )); end; ErrCode := Execute( Exe, AtPath( FD^.FileName^, Path ) + ' ' + Diz, True ); if ErrCode < 0 then raise Exception.Create( Format(LoadString(_SExtRunError), [-ErrCode] )); if ErrCode > 0 then raise Exception.Create( Format(LoadString(_SExtRunErrLevel), [ErrCode] )); if not FileExists( Diz ) then raise Exception.Create( LoadString(_SDizNotBuilt) ); Log^.Write( ll_Protocol, LoadString(_SDizBuilt) ); FD^.LoadFromFile( Diz ); except on E: Exception do Log^.Write( ll_Warning, E.Message ); end; if FileExists( Diz ) then VFS_EraseFile( Diz ); end; { TryFetch } var DllPassed: Boolean; SaveCmt : PFileDef; begin SaveCmt := New( PFileDef, Init(FD^.FileName^) ); MoveComment( FD, SaveCmt ); {$IFDEF WIN32} DllPassed := TryDLL; if FD^.NoComment then begin if not DllPassed then {$ENDIF} TryArchive; if FD^.NoComment then begin TryFetch; if FD^.NoComment then begin if SaveCmt^.NoComment then FD^.AssignDefaultComment else MoveComment( SaveCmt, FD ); end; end; {$IFDEF WIN32} end; {$ENDIF} Destroy( SaveCmt ); end; { BuildComment } { --------------------------------------------------------- } { ScanAreaPath } { --------------------------------------------------------- } procedure ScanAreaPath( Area: PFileArea; const Path: String ); var R : TSearchRec; FD: PFileDef; ShortName: String; LongName : String; FullName : String; DosError : Integer; FileIndex: Integer; begin if (Path = '') or not DirExists(Path) then begin Log.Write( ll_warning, Format(LoadString(_SDirNotExists), [Path]) ); Exit; end; DosError := SysUtils.FindFirst( AtPath('*.*', Path), faArchive + faReadOnly, R ); while DosError = 0 do begin DecodeLFN( R, ShortName, LongName ); try FileTimeToUnix( R.Time ); except Log^.Write( ll_Warning, Format(LoadString(_SBadFileDate), [R.Name] )); Log^.Write( ll_Expand, LoadString(_SDateShouldFixed) ); R.Time := CurrentFileTime; end; if not Excluded( ShortName ) then try FullName := AtPath( R.Name, Path ); if Area^.Search( @ShortName, FileIndex ) then begin FD := Area^.At(FileIndex); FD^.Time := R.Time; FD^.Size := R.Size; ReplaceStr( FD^.LongName, LongName ); if CFG^.ForceCmt or (CFG^.UpdateCmt and FD^.NoComment) then begin Log^.Write( ll_Protocol, Format(LoadString(_SForceDiz), [R.Name] )); BuildComment( FD , Path ); end; if (FileTimeToUnix( FD^.Time ) > Area^.LastScanTime) and (Area^.LastScanTime > 0) then begin Log^.Write( ll_Protocol, Format(LoadString(_SUpdatedFile), [R.Name] )); if not CFG^.KeepOldCmt then BuildComment( FD, Path ); OpenAnnounce; Announce^.Freshen( Area, FD ); end; end else if Area^.Scan then begin Log^.Write( ll_Protocol, Format(LoadString(_SNewFile), [R.Name] )); FD := New( PFileDef, Init(ShortName) ); ReplaceStr( FD^.LongName, LongName ); FD^.Time := R.Time; FD^.Size := R.Size; if CFG^.TouchNew then begin FD^.Time := CurrentFileTime; if not VFS_TouchFile( FullName, FD^.Time ) then Log^.Write( ll_Warning, Format(LoadString(_SCantSetFTime), [FullName] )); end; Area^.Insert( FD ); BuildComment( FD, Path ); end; except on E: Exception do Log^.Write( ll_Error, E.Message ); end; DosError := SysUtils.FindNext( R ); end; SysUtils.FindClose( R ); end; { ScanAreaPath } { --------------------------------------------------------- } { WriteLogo } { --------------------------------------------------------- } procedure WriteLogo( Report: PReport ); var S: String; T: String; begin S := ' ÔÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ'; T := '[Version ' + PROG_VER +']'; Move( T[1], S[33-Length(T)], Length(T) ); with Report^ do begin WriteOut( '' ); WriteOut( ' ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ·' ); WriteOut( ' ³ÞÛ Û ÞÛ ÛÛ ÞÛ ÞÛ ÞÛÛ ÞÛÛÛ Created by Hi-Files file-list generator º' ); WriteOut( ' ³ÞÛÜÛ ÞÛ þ ÛÜ ÞÛ ÞÛ ÞÛÜ ÞÛÜÜ (C) 1997-2006 by Dmitry Liman, 2:461/79 º' ); WriteOut( ' ³ÞÛ Û ÞÛ Û ÞÛ ÞÛÛ ÞÛÜ ÜÜÛ °°°°°±±±±±²²²² ' + GetFileDateStr(CurrentFileTime) + ' ²²²²±±±±±°°°°° º' ); WriteOut( S ); WriteOut( '' ); end; end; { Writelogo } { --------------------------------------------------------- } { BuildTextReport } { --------------------------------------------------------- } procedure BuildTextReport( const ReportName, ScriptName: String ); var Report: PTextReport; begin New( Report, Init(ReportName) ); ExecuteScript( ScriptName, Report, nil ); WriteLogo( Report ); Destroy( Report ); end; { BuildTextReport } { --------------------------------------------------------- } { BuildPktReports } { --------------------------------------------------------- } procedure BuildPktReports; procedure UsePoster( Poster: PPoster ); far; var Report: PPktReport; begin Log^.Write( ll_Protocol, Format(LoadString(_SLogPostInArea), [Poster^.Area] )); New( Report, Init(Poster) ); ExecuteScript( Poster^.Script, Report, Poster ); Destroy( Report ); end; { UsePoster } var Report: PPktReport; begin CFG^.Posters^.ForEach( @UsePoster ); end; { BuildPktReport } { --------------------------------------------------------- } { ExportFreq } { --------------------------------------------------------- } procedure ExportFreq; var Report: PTextReport; procedure DoExport( Area: PFileArea ); far; procedure DoExpPath( P: PString ); far; begin Report^.WriteOut( AddBackSlash(P^) ); end; begin if not Area^.HideFreq then Area^.DL_Path^.ForEach( @DoExpPath ); end; { DoExport } begin New( Report, Init(CFG^.FreqDirs) ); WriteChangedLogo( Report ); FileBase^.ForEach( @DoExport ); Destroy( Report ); end; { ExportFreq } { --------------------------------------------------------- } { TBestList } { --------------------------------------------------------- } type PBestList = ^TBestList; TBestList = object (TSortedCollection) MinDLC: Integer; constructor Init; procedure FreeItem( Item: Pointer ); virtual; function KeyOf( Item: Pointer ) : Pointer; virtual; function Compare( Key1, Key2: Pointer ) : Integer; virtual; procedure Taste( FD: PFileDef ); end; { TBestList } { Init ---------------------------------------------------- } constructor TBestList.Init; begin inherited Init( CFG^.BestCount, 10 ); MinDLC := 1; Duplicates := True; end; { Init } { FreeItem ------------------------------------------------ } procedure TBestList.FreeItem( Item: Pointer ); begin end; { FreeItem } { KeyOf --------------------------------------------------- } function TBestList.KeyOf( Item: Pointer ) : Pointer; begin KeyOf := @PFileDef( Item )^.DLC; end; { KeyOf } { Compare ------------------------------------------------- } function TBestList.Compare( Key1, Key2: Pointer ) : Integer; var d1: ^Integer absolute Key1; d2: ^Integer absolute Key2; begin if d1^ > d2^ then Compare := -1 else if d1^ < d2^ then Compare := 1 else Compare := 0; end; { Compare } { Taste --------------------------------------------------- } procedure TBestList.Taste( FD: PFileDef ); begin if FD^.DLC >= MinDLC then begin Insert( FD ); if Count > CFG^.BestCount then begin AtFree( Count - 1 ); MinDLC := PFileDef( At(Count - 1) )^.DLC; end; end; end; { Taste } { --------------------------------------------------------- } { BuildBestArea } { --------------------------------------------------------- } procedure BuildBestArea; var Area: PFileArea; Best: PBestList; procedure ScanArea( Area: PFileArea ); far; procedure LookFD( FD: PFileDef ); far; begin Best^.Taste( FD ); end; { LookFD } begin if not Area^.Virt then Area^.ForEach( @LookFD ); end; { ScanArea } procedure GiveMe( FD: PFileDef ); far; begin Area^.Insert( FD^.Dupe ); end; { GiveMe } begin if CFG^.DlcDigs = 0 then begin ShowError( LoadString(_SBestAreaFailedNoDLC )); Exit; end; New( Best, Init ); New( Area, Init('The Best Files') ); with Area^ do begin ReplaceStr( Group, 'VIRTUAL' ); fUseAloneCmt := Lowered; fSorted := Lowered; Virt := True; end; FileBase^.ForEach( @ScanArea ); Best^.ForEach( @GiveMe ); Destroy( Best ); FileBase^.Insert( Area ); FileBase^.CalcSummary; end; { BuildBestArea } { --------------------------------------------------------- } { LeaveNewFiles } { --------------------------------------------------------- } procedure LeaveNewFiles; var UNow: UnixTime; function Forgot( const FileName: String ) : Boolean; function Match( const Pattern: String ) : Boolean; far; begin Match := WildMatch( FileName, Pattern ); end; { Match } begin Forgot := CFG^.Forget^.FirstThat( @Match ) <> nil; end; { Forgot } procedure RefineArea( Area: PFileArea ); far; var j : Integer; FD: PFileDef; begin UpdateProgress( FileBase^.IndexOf(Area) ); j := 0; while j < Area^.Count do begin FD := Area^.At(j); if FD^.AloneCmt or FD^.Missing or Forgot( FD^.FileName^ ) or (DaysBetween( UNow, FileTimeToUnix(FD^.Time) ) > CFG^.NewFilesAge) then begin Area^.AtFree(j); Continue; end; Inc(j); end; end; { RefineArea } var j: Integer; begin UNow := CurrentUnixTime; OpenWorking( LoadString(_SLeavingNewFiles) ); OpenProgress( FileBase^.Count ); try FileBase^.ForEach( @RefineArea ); FileBase^.Clean; finally CloseWorking; end; end; { LeaveNewFiles } { --------------------------------------------------------- } { RunGenerator } { --------------------------------------------------------- } procedure RunGenerator; var ACTION: String; procedure ScanArea( Area: PFileArea ); far; procedure ScanPath( Path: PString ); far; begin ScanAreaPath(Area, Path^); end; var n: Integer; begin Log^.Write( ll_Protocol, '[' + Area^.Name^ + ']' ); UpdateProgress( FileBase^.IndexOf(Area) ); if Area^.Loaded then begin if Area^.Recurse then Area^.AddTree; n := Area^.Count; Area^.DL_Path^.ForEach( @ScanPath ); Area^.LastScanTime := CurrentUnixTime; FileBase^.Modified := True; if Area^.Count > n then Area^.Complete; end else Log^.Write( ll_Error, LoadString(_SScanFailedNoBbs) ); end; { ScanArea } begin CloseFileBaseBrowser; CloseFileEchoBrowser; ACTION := LoadString( _SLogScanningFileBase ); Announce := nil; LoadFileBase; if Log^.HasErrors then begin if CFG^.BatchMode or (MessageBox( LoadString(_SCfmIgnoreErrors), nil, mfWarning + mfYesNoCancel ) <> cmYes) then Exit; Log^.Clear; end; Log^.Write( ll_Service, ACTION ); OpenWorking( ACTION ); OpenProgress( FileBase^.Count ); try FileBase^.ForEach( @ScanArea ); finally CloseWorking; end; if CFG^.DropMissing then FileBase^.DropMissingFiles; // WriteFilesBbs should be called _before_ WriteFileAreaCtl ! FileBase^.WriteFilesBbs; if FileBase^.Modified then FileBase^.WriteFileAreaCtl; FileBase^.CalcSummary; if CFG^.FreqDirs <> '' then begin Log^.Write( ll_Service, LoadString(_SLogExportFreq) ); ExportFreq; end; if CFG^.BuildAllList then begin if CFG^.BuildBestArea then begin Log^.Write( ll_Service, LoadString(_SLogBuildingBest) ); BuildBestArea; end; Log^.Write( ll_Service, LoadString(_SLogBuildingAll) ); BuildTextReport( CFG^.AllFilesList, CFG^.AllFilesScript ); end; if CFG^.BuildNewList or CFG^.BuildNewRep then begin Log^.Write( ll_Service, LoadString(_SLogLeavingNew) ); LeaveNewFiles; if FileBase^.Count > 0 then begin if CFG^.BuildNewList then begin Log^.Write( ll_Service, LoadString(_SLogBuildingNew) ); BuildTextReport( CFG^.NewFilesList, CFG^.NewFilesScript ); end; if CFG^.BuildNewRep then begin Log^.Write( ll_Service, LoadString(_SLogBuildingNewRep) ); OpenAnnounce; Announce^.Refresh; if FileBase^.Count > 0 then begin BuildPktReports; ExitCode := EXIT_NEW_FILES_FOUND; end else Log^.Write( ll_Protocol, LoadString(_SLogNothingToAn) ); end; end else Log^.Write( ll_Protocol, LoadString(_SLogNoNewFiles) ); end; CloseAnnounce; CloseFileBase; end; { RunGenerator } end.
{******************************************************************************* 作者: dmzn@163.com 2010-9-2 描述: 系统常量定义 *******************************************************************************} unit USysConst; interface uses Windows, Classes, Forms, Graphics, dxStatusBar, SysUtils, UMgrLang; type TDynamicByteArray = array of Byte; TByteData = array[0..7] of Byte; TByteInt = record FB1,FB2,FB3,FB4: Byte; end; const cByteMask: TByteData = (128, 64, 32, 16, 8, 4, 2, 1); //------------------------------------------------------------------------------ type TCodeText = record FCode: string; //代码 FText: string; //含义 end; const cEnterMode: array[0..14] of TCodeText = ((FCode:'00';FText:'直接显示'), (FCode:'01';FText:'闪烁三次'), (FCode:'02';FText:'向右移入'), (FCode:'03';FText:'向左移入'), (FCode:'04';FText:'向右展开'), (FCode:'05';FText:'向左展开'), (FCode:'06';FText:'从左右向中间'), (FCode:'07';FText:'从中间向左右'), (FCode:'08';FText:'向上移入'), (FCode:'09';FText:'向上展开'), (FCode:'0a';FText:'向下展开'), (FCode:'0b';FText:'从上下向中间'), (FCode:'0c';FText:'从中间向上下'), (FCode:'0d';FText:'水平百叶窗'), (FCode:'0e';FText:'垂直百叶窗')); cExitMode: array[0..14] of TCodeText = ((FCode:'00';FText:'直接消隐'), (FCode:'01';FText:'闪烁三次'), (FCode:'02';FText:'向右移出'), (FCode:'03';FText:'向左移出'), (FCode:'04';FText:'向右擦除'), (FCode:'05';FText:'向左擦除'), (FCode:'06';FText:'从左右向中间'), (FCode:'07';FText:'从中间向左右'), (FCode:'08' ;FText:'向上移出'), (FCode:'09';FText:'向上擦除'), (FCode:'0a';FText:'向下擦除'), (FCode:'0b';FText:'从上下向中间'), (FCode:'0c';FText:'从中间向上下'), (FCode:'0d';FText:'水平百叶窗'), (FCode:'0e';FText:'垂直百叶窗')); cTimeChar: array[0..1] of TCodeText = ((FCode:'00';FText:'汉字'), (FCode:'01';FText:'字符')); //时钟格式 cDispMode: array[0..1] of TCodeText = ((FCode:'00';FText:'固定显示'), (FCode:'01';FText:'跟随模式')); //显示模式 cDispPos: array[0..8] of TCodeText = ((FCode:'00';FText:'上端居左'), (FCode:'01';FText:'上端居中'), (FCode:'02';FText:'上端居右'), (FCode:'03';FText:'中间居左'), (FCode:'04';FText:'中间居中'), (FCode:'05';FText:'中间居右'), (FCode:'06';FText:'下端居左'), (FCode:'07';FText:'下端居中'), (FCode:'08';FText:'下端居右')); //显示位置 //------------------------------------------------------------------------------ const cSendInterval_Long = 4200; cSendInterval_Short = 1000; //发送超时等待 cItemColorList: array[0..2] of TColor = (clRed, clGreen, clYellow); //颜色列表 //------------------------------------------------------------------------------ type TSysParam = record FAppTitle: string; //程序标题 FMainTitle: string; //主窗口 FCopyLeft: string; //状态栏.版权 FCopyRight: string; //关于.版权 FIsAdmin: Boolean; //管理员登录 FCOMMPort: string; //连接端口 FCOMMBote: Integer; //传输波特率 FScreenWidth: Integer; FScreenHeight: Integer; //屏幕宽高 FEnableClock: Boolean; FClockChar: string; FClockMode: string; FClockPos: string; FClockYear: string; FClockMonth: string; FClockDay: string; FClockWeek: string; FClockTime: string; //时钟参数 FClockSYear: string; FClockSMonth: string; FClockSDay: string; FClockSHour: string; FClockSMin: string; FClockSSec: string; FClockSWeek: string; //时钟数据 FEnablePD: Boolean; FPlayDays: string; //播放天数 end; var gPath: string; //程序所在路径 gSysParam: TSysParam; //系统参数 gIsSending: Boolean = False; //发送状态 gSendInterval: Word = cSendInterval_Short; //发送超时 gStatusBar: TdxStatusBar; //全局使用状态栏 //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx sHint: string; //多语言常量 sAsk: string; sWarn: string; sError: string; //------------------------------------------------------------------------------ procedure SetRStringMultiLang; //常量多语言 procedure FillColorList(const nList: TStrings); //填充颜色 function GetColorIndex(const nList: TStrings; const nColor: TColor): Integer; //设置颜色 procedure ShowMsgOnLastPanelOfStatusBar(const nMsg: string); procedure StatusBarMsg(const nMsg: string; const nIdx: integer); //在状态栏显示信息 resourcestring sProgID = 'HBEdit'; //程序标示 sAppTitle = '汉邦电子'; //任务栏 sMainTitle = '图文编辑器'; //主窗口 sConfigFile = 'Config.ini'; //主配置 sFormConfig = 'Forms.ini'; //窗体配置 sBackImage = 'bg.bmp'; //背景 {*语言标记*} sMLMain = 'fFormMain'; sMLCommon = 'Common'; {*默认标题*} rsHint = '提示'; rsAsk = '询问'; rsWarn = '警告'; rsError = '错误'; sCorConcept = '※.科技演绎 技术创新 真诚服务 共创未来'; //企业理念 sCopyRight = '※.版权所有: 汉邦电子'; //版权所有 sInvalidConfig = '配置文件无效或已经损坏'; //配置文件无效 implementation //Desc: 常量字符串翻译 procedure SetRStringMultiLang; begin sHint := ML(rsHint, sMLCommon); sAsk := ML(rsAsk); sWarn := ML(rsWarn); sError := ML(rsError); end; //Desc: 将cItemColorList的颜色填充到nList中 procedure FillColorList(const nList: TStrings); var nIdx: integer; begin nList.Clear; for nIdx:=Low(cItemColorList) to High(cItemColorList) do begin nList.AddObject(IntToStr(nIdx), TObject(cItemColorList[nIdx])) end; end; //Desc: 检索nColor在nList中的索引 function GetColorIndex(const nList: TStrings; const nColor: TColor): Integer; var i: integer; begin Result := -1; for i:=nList.Count - 1 downto 0 do if nList.Objects[i] = TObject(nColor) then begin Result := i; Break; end; end; //------------------------------------------------------------------------------ //Desc: 在全局状态栏最后一个Panel上显示nMsg消息 procedure ShowMsgOnLastPanelOfStatusBar(const nMsg: string); begin if Assigned(gStatusBar) and (gStatusBar.Panels.Count > 0) then begin gStatusBar.Panels[gStatusBar.Panels.Count - 1].Text := nMsg; Application.ProcessMessages; end; end; //Desc: 在索引nIdx的Panel上显示nMsg消息 procedure StatusBarMsg(const nMsg: string; const nIdx: integer); begin if Assigned(gStatusBar) and (gStatusBar.Panels.Count > nIdx) and (nIdx > -1) then begin gStatusBar.Panels[nIdx].Text := nMsg; gStatusBar.Panels[nIdx].Width := gStatusBar.Canvas.TextWidth(nMsg) + 20; Application.ProcessMessages; end; end; end.
unit aOPCTagDictionary; interface uses Classes, aCustomOPCSource, aOPCCollection; type TaOPCTagDictionary = class(TComponent) private FTags: TTagCollection; procedure SetTags(Value: TTagCollection); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOnwer: TComponent); override; destructor Destroy; override; published property Tags: TTagCollection read FTags write SetTags; end; implementation { TaOPCTagDictionary } constructor TaOPCTagDictionary.Create(AOnwer: TComponent); begin inherited Create(AOnwer); FTags := TTagCollection.Create(TTagCollectionItem); end; destructor TaOPCTagDictionary.Destroy; begin FTags.Free; inherited Destroy; end; procedure TaOPCTagDictionary.Notification(AComponent: TComponent; Operation: TOperation); var i:integer; begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent is TaCustomOPCSource) then begin for i := 0 to FTags.Count - 1 do if FTags.Items[i].OPCSource = AComponent then FTags.Items[i].OPCSource := nil; end; end; procedure TaOPCTagDictionary.SetTags(Value: TTagCollection); begin FTags.Assign(Value); end; end.
unit dWebUpdate; interface uses System.SysUtils, System.Classes, WUpdateWiz, WUpdateLanguagesU, WUpdate; const AlfaPetVersion = '1.8'; type TdmWebUpdate = class(TDataModule) WebUpdate1: TWebUpdate; WebUpdateWizard1: TWebUpdateWizard; WebUpdateWizardPortugese1: TWebUpdateWizardPortugese; procedure DataModuleCreate(Sender: TObject); procedure WebUpdate1CustomValidate(Sender: TObject; Msg, Param: string; var Allow: Boolean); private procedure ParseVersion(const Ver: string; var Major, Minor: integer); public procedure ExecuteWizard; function IsNewVersionAvailable: boolean; end; var dmWebUpdate: TdmWebUpdate; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TdmWebUpdate.DataModuleCreate(Sender: TObject); begin WebUpdate1.URL := 'http://www.devgems.com/alfapet/update.inf'; if IsNewVersionAvailable then ExecuteWizard; end; procedure TdmWebUpdate.ExecuteWizard; begin WebUpdateWizard1.Execute; end; function TdmWebUpdate.IsNewVersionAvailable: boolean; begin Result := WebUpdate1.NewVersionAvailable; end; procedure TdmWebUpdate.ParseVersion(const Ver: string; var Major, Minor: integer); var P: integer; begin P := Pos('.', Ver); Major := StrToInt(Copy(Ver, 1, P - 1)); Minor := StrToInt(Copy(Ver, P + 1, MaxInt)); end; procedure TdmWebUpdate.WebUpdate1CustomValidate(Sender: TObject; Msg, Param: string; var Allow: Boolean); var NewMajor, NewMinor: integer; LocalMajor, LocalMinor: integer; begin Allow := false; if Param = '' then Exit; ParseVersion(Param, NewMajor, NewMinor); ParseVersion(AlfaPetVersion, LocalMajor, LocalMinor); Allow := (NewMajor > LocalMajor) or ((NewMajor = LocalMajor) and (NewMinor > LocalMinor)); end; end.
unit Domain.Entity.ItensTabelaPreco; interface uses System.Classes, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types, EF.Mapping.Atributes, Domain.Entity.Produto; type [Table('ItensTabelaPreco')] TItensTabelaPreco = class( TEntityBase ) private FTabelaPrecoId: TInteger; FProdutoId: TInteger; FValor: TFloat; FProduto: TProduto; published [Column('ProdutoId','integer',false)] property ProdutoId:TInteger read FProdutoId write FProdutoId; [Column('TabelaPrecoId','integer',false)] property TabelaPrecoId:TInteger read FTabelaPrecoId write FTabelaPrecoId; [Column('Valor','float',false)] property Valor: TFloat read FValor write FValor; [NotMapped] property Produto: TProduto read FProduto write FProduto; constructor Create;override; end; implementation { TItensTabelaPreco } constructor TItensTabelaPreco.Create; begin inherited; Produto := TProduto.Create; end; initialization RegisterClass(TItensTabelaPreco); finalization UnRegisterClass(TItensTabelaPreco); end.
unit Thread.PopulaRepartes; interface uses System.Classes, System.Generics.Collections, System.SysUtils, Vcl.Forms, System.UITypes, Model.ProdutosVA, Model.BancaVA, Model.DistribuidorVA, Model.RemessasVA, DAO.ProdutosVA, DAO.BancaVA, DAO.DistribuidorVA, DAO.RemessasVA; type Thread_PopulaRepartes = class(TThread) private { Private declarations } FDistribuidor: Integer; FBanca: Integer; FTipo: Integer; FData: TDate; FdPos: Double; banca : TBancaVA; bancas : TObjectList<TBancaVA>; bancaDAO : TBancaVADAO; distribuidor : TDistribuidorVA; distribuidores : TObjectList<TDistribuidorVA>; distribuidorDAO : TDistribuidorVADAO; produto : TProdutosVA; produtos : TObjectList<TProdutosVA>; produtoDAO : TProdutosVADAO; remessa : TRemessasVA; remessas : TObjectList<TRemessasVA>; remessaDAO : TRemessasVADAO; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; public property CodDistribuidor: Integer read FDistribuidor write FDistribuidor; property CodBanca: Integer read FBanca write FBanca; property Tipo: Integer read FTipo write FTipo; property Data: TDate read FData write FData; 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_PopulaRepartes.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 View.ManutencaoRepartes, udm, clUtil; { Thread_PopulaRepartes } procedure Thread_PopulaRepartes.Execute; var bancaTMP: TBancaVA; distribuidorTMP: TDistribuidorVA; produtoTMP: TProdutosVA; remessaTMP: TRemessasVA; iTotal : Integer; iPos : Integer; sCampo: String; begin { Place thread code here } try Synchronize(IniciaProcesso); Screen.Cursor := crHourGlass; if view_ManutencaoRepartesVA.tbRepartes.Active then view_ManutencaoRepartesVA.tbRepartes.Close; view_ManutencaoRepartesVA.tbRepartes.Open; bancaDAO := TBancaVADAO.Create(); distribuidorDAO := TDistribuidorVADAO.Create(); produtoDAO := TProdutosVADAO.Create(); remessaDAO := TRemessasVADAO.Create(); view_ManutencaoRepartesVA.tbRepartes.IsLoading := True; remessas := remessaDAO.FindByMovimento(FDistribuidor,FBanca,FTipo,'',Data); if remessas.Count > 0 then begin iTotal := remessas.Count; for remessaTMP in remessas do begin view_ManutencaoRepartesVA.tbRepartes.Insert; view_ManutencaoRepartesVA.tbRepartesID_REMESSA.AsInteger := remessaTMP.ID; view_ManutencaoRepartesVA.tbRepartesCOD_DISTRIBUIDOR.AsInteger := remessaTMP.Distribuidor; distribuidores := distribuidorDAO.FindByCodigo(remessaTMP.Distribuidor); sCampo := TUtil.AlinhaD(Trim(IntToStr(remessaTMP.Distribuidor)),6); if distribuidores.Count > 0 then begin view_ManutencaoRepartesVA.tbRepartesNOM_DISTRIBUIDOR.AsString := sCampo + '-' + Trim(distribuidores[0].Nome); end else begin view_ManutencaoRepartesVA.tbRepartesNOM_DISTRIBUIDOR.AsString := sCampo; end; view_ManutencaoRepartesVA.tbRepartesCOD_BANCA.AsInteger := remessaTMP.Banca; bancas := bancaDAO.FindByCodigo(remessaTMP.Banca); sCampo := TUtil.AlinhaD(Trim(IntToStr(remessaTMP.Banca)),6); if bancas.Count > 0 then begin view_ManutencaoRepartesVA.tbRepartesNOM_BANCA.AsString := sCampo + '-' + Trim(bancas[0].Nome); end else begin view_ManutencaoRepartesVA.tbRepartesNOM_BANCA.AsString := sCampo; end; view_ManutencaoRepartesVA.tbRepartesCOD_PRODUTO.AsString := remessaTMP.Produto; produtos := produtoDAO.FindByCodigo(remessaTMP.Produto); if produtos.Count > 0 then begin view_ManutencaoRepartesVA.tbRepartesDES_PRODUTO.AsString := Trim(produtos[0].Descricao); end else begin view_ManutencaoRepartesVA.tbRepartesNOM_BANCA.AsString := remessaTMP.Produto; end; view_ManutencaoRepartesVA.tbRepartesDAT_REMESSA.AsDateTime := remessaTMP.DataRemessa; view_ManutencaoRepartesVA.tbRepartesNUM_REMESSA.AsString := remessaTMP.NumeroRemessa; view_ManutencaoRepartesVA.tbRepartesQTD_REMESSA.AsFloat := remessaTMP.Remessa; view_ManutencaoRepartesVA.tbRepartesDAT_RECOBERTURA.AsDateTime := remessaTMP.DataRecobertura; view_ManutencaoRepartesVA.tbRepartesQTD_RECOBERTURA.AsFloat := remessaTMP.Recobertura; view_ManutencaoRepartesVA.tbRepartesDAT_CHAMADA.AsDateTime := remessaTMP.DataChamada; view_ManutencaoRepartesVA.tbRepartesNUM_DEVOLUCAO.AsString := remessaTMP.NumeroDevolucao; view_ManutencaoRepartesVA.tbRepartesQTD_ENCALHE.AsFloat := remessaTMP.Encalhe; view_ManutencaoRepartesVA.tbRepartesVAL_COBRANCA.AsFloat := remessaTMP.ValorCobranca; view_ManutencaoRepartesVA.tbRepartesVAL_VENDA.AsFloat := remessaTMP.ValorVenda; view_ManutencaoRepartesVA.tbRepartesDOM_INVENTARIO.AsInteger := remessaTMP.Inventario; view_ManutencaoRepartesVA.tbRepartesDES_LOG.asString := remessaTMP.Log; view_ManutencaoRepartesVA.tbRepartes.Post; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; end; if not view_ManutencaoRepartesVA.tbRepartes.IsEmpty then view_ManutencaoRepartesVA.tbRepartes.First; finally Synchronize(TerminaProcesso); bancaDAO.Free; distribuidorDAO.Free; produtoDAO.Free; remessaDAO.Free; end; end; procedure Thread_PopulaRepartes.IniciaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Visible := True; view_ManutencaoRepartesVA.dsRepartes.Enabled := False; view_ManutencaoRepartesVA.tbRepartes.IsLoading := True; view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_PopulaRepartes.AtualizaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Position := FdPos; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := FormatFloat('0.00%',FdPos); view_ManutencaoRepartesVA.pbRepartes.Refresh; end; procedure Thread_PopulaRepartes.TerminaProcesso; begin view_ManutencaoRepartesVA.pbRepartes.Position := 0; view_ManutencaoRepartesVA.pbRepartes.Properties.Text := ''; view_ManutencaoRepartesVA.pbRepartes.Refresh; view_ManutencaoRepartesVA.tbRepartes.IsLoading := False; view_ManutencaoRepartesVA.dsDistribuidor.Enabled := True; view_ManutencaoRepartesVA.pbRepartes.Visible := False; end; end.
unit GrantPrivileges; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CreateObjectDialog, Vcl.StdCtrls, BCControls.ComboBox, BCControls.Edit, Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, ActnList, ComCtrls, ToolWin, JvExComCtrls, SynEdit, Vcl.ExtCtrls, JvComCtrls, BCControls.PageControl, BCControls.ToolBar, BCDialogs.Dlg, System.Actions, BCControls.ImageList, BCControls.CheckBox, JvExStdCtrls, JvCheckBox; type TGrantPrivilegesDialog = class(TCreateObjectBaseDialog) AlterCheckBox: TBCCheckBox; DebugCheckBox: TBCCheckBox; DeleteCheckBox: TBCCheckBox; ExecuteCheckBox: TBCCheckBox; GrantGroupBox: TGroupBox; GrantOptionCheckBox: TBCCheckBox; InsertCheckBox: TBCCheckBox; OnEdit: TBCEdit; OnGroupBox: TGroupBox; PublicRadioButton: TRadioButton; RoleComboBox: TBCComboBox; RoleRadioButton: TRadioButton; SelectCheckBox: TBCCheckBox; SettingsTabSheet: TTabSheet; ToGroupBox: TGroupBox; UpdateCheckBox: TBCCheckBox; UserComboBox: TBCComboBox; UserRadioButton: TRadioButton; procedure FormDestroy(Sender: TObject); private { Private declarations } procedure GetRoles; procedure GetUsers; protected function CheckFields: Boolean; override; procedure CreateSQL; override; procedure Initialize; override; end; function GrantPrivilegesDialog: TGrantPrivilegesDialog; implementation {$R *.dfm} uses DataModule, Ora, BCCommon.StyleUtils, BCCommon.Messages; var FGrantPrivilegesDialog: TGrantPrivilegesDialog; function GrantPrivilegesDialog: TGrantPrivilegesDialog; begin if not Assigned(FGrantPrivilegesDialog) then Application.CreateForm(TGrantPrivilegesDialog, FGrantPrivilegesDialog); Result := FGrantPrivilegesDialog; SetStyledFormSize(TDialog(Result)); end; procedure TGrantPrivilegesDialog.FormDestroy(Sender: TObject); begin inherited; FGrantPrivilegesDialog := nil; end; function TGrantPrivilegesDialog.CheckFields: Boolean; begin Result := False; if not SelectCheckBox.Checked and not InsertCheckBox.Checked and not UpdateCheckBox.Checked and not DeleteCheckBox.Checked and not ExecuteCheckBox.Checked and not AlterCheckBox.Checked and not DebugCheckBox.Checked then begin ShowErrorMessage('Set grant.'); Exit; end; if UserRadioButton.Checked and (UserComboBox.Text = '') then begin ShowErrorMessage('Set user.'); Exit; end; if RoleRadioButton.Checked and (RoleComboBox.Text = '') then begin ShowErrorMessage('Set role.'); Exit; end; Result := True; end; procedure TGrantPrivilegesDialog.GetUsers; var OraQuery: TOraQuery; begin OraQuery := TOraQuery.Create(nil); OraQuery.Session := FOraSession; OraQuery.SQL.Add(DM.StringHolder.StringsByName['AllUsersSQL'].Text); with OraQuery do try Prepare; Open; while not Eof do begin UserComboBox.Items.Add(FieldByName('USERNAME').AsString); Next; end; finally Close; UnPrepare; FreeAndNil(OraQuery); end; end; procedure TGrantPrivilegesDialog.GetRoles; var OraQuery: TOraQuery; begin OraQuery := TOraQuery.Create(nil); OraQuery.Session := FOraSession; OraQuery.SQL.Add(DM.StringHolder.StringsByName['DistinctGrantedRolesSQL'].Text); with OraQuery do try Prepare; Open; while not Eof do begin RoleComboBox.Items.Add(FieldByName('GRANTED_ROLE').AsString); Next; end; finally Close; UnPrepare; FreeAndNil(OraQuery); end; end; procedure TGrantPrivilegesDialog.Initialize; begin OnEdit.Text := FSchemaParam + '.' + FObjectName; GetUsers; GetRoles; end; procedure TGrantPrivilegesDialog.CreateSQL; var GrantOption, Privileges, Owner: string; begin try Screen.Cursor := crHourglass; SourceSynEdit.Clear; SourceSynEdit.Lines.BeginUpdate; if SelectCheckBox.Checked then Privileges := 'SELECT'; if InsertCheckBox.Checked then begin if SelectCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'INSERT'; end; if UpdateCheckBox.Checked then begin if SelectCheckBox.Checked or InsertCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'UPDATE'; end; if DeleteCheckBox.Checked then begin if SelectCheckBox.Checked or InsertCheckBox.Checked or UpdateCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'DELETE'; end; if ExecuteCheckBox.Checked then begin if SelectCheckBox.Checked or InsertCheckBox.Checked or UpdateCheckBox.Checked or DeleteCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'EXECUTE'; end; if AlterCheckBox.Checked then begin if SelectCheckBox.Checked or InsertCheckBox.Checked or UpdateCheckBox.Checked or DeleteCheckBox.Checked or ExecuteCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'ALTER'; end; if DebugCheckBox.Checked then begin if SelectCheckBox.Checked or InsertCheckBox.Checked or UpdateCheckBox.Checked or DeleteCheckBox.Checked or ExecuteCheckBox.Checked or AlterCheckBox.Checked then Privileges := Privileges + ', '; Privileges := Privileges + 'DEBUG'; end; Owner := 'PUBLIC'; if UserRadioButton.Checked then Owner := UserComboBox.Text; if RoleRadioButton.Checked then Owner := RoleComboBox.Text; GrantOption := ''; if GrantOptionCheckBox.Checked then GrantOption := ' WITH GRANT OPTION'; SourceSynEdit.Lines.Text := Format('GRANT %s ON %s TO %s%s;', [Privileges, OnEdit.Text, Owner, GrantOption]); SourceSynEdit.Lines.EndUpdate; finally Screen.Cursor := crDefault; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Unit vinculada à tela Menu da aplicação The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 2.0 *******************************************************************************} unit UMenu; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, StdCtrls, ExtCtrls, ImgList, JvExControls, JvComponent, JvPageList, JvTabBar, RibbonLunaStyleActnCtrls, Ribbon, ToolWin, ActnMan, ActnCtrls, ActnList, RibbonSilverStyleActnCtrls, JvExComCtrls, JvStatusBar, ActnMenus, RibbonActnMenus, JvOutlookBar, JvLookOut, ScreenTips, WideStrings, DB, JvComponentBase, Atributos, Enter, XPMan, UBase, IndyPeerImpl, System.Actions, // ULogin, UWmsParametro, UWmsEndereco, UWmsAgendamento, UWmsRecebimento, UWmsArmazenamento, UWmsOrdemSeparacao, UWmsExpedicao, UWmsColeta; type [TFormDescription('Menu','Menu')] TFMenu = class(TFBase) //actions (* OBS: O nome da Action deve ser igual ao nome do formulário sem o "TF". Exemplos: TFUnidadeProduto = ActionUnidadeProduto TFBanco = ActionBanco Deve ser dessa forma por conta do Controle de Acessos. *) ActionColetaDeDados: TAction; ActionEnderecos: TAction; ActionParametros: TAction; ActionArmazenamento: TAction; ActionRecebimento: TAction; ActionAgendamento: TAction; ActionOrdemSeparacao: TAction; ActionExpedicao: TAction; ActionPatrimApoliceSeguro: TAction; ActionSair: TAction; // Image16: TImageList; PopupMenu: TPopupMenu; menuFechar: TMenuItem; menuFecharTodasExcetoEssa: TMenuItem; menuSepararAba: TMenuItem; N2: TMenuItem; JvTabBar: TJvTabBar; JvModernTabBarPainter: TJvModernTabBarPainter; JvPageList: TJvPageList; Ribbon: TRibbon; RibbonPageCadastros: TRibbonPage; RibbonGrupoGeral: TRibbonGroup; ActionManager: TActionManager; JvStatusBar1: TJvStatusBar; RibbonGrupoDiversos: TRibbonGroup; Image48: TImageList; Image32: TImageList; RibbonApplicationMenuBar1: TRibbonApplicationMenuBar; ScreenTipsManager1: TScreenTipsManager; MREnter: TMREnter; procedure PageControlDrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); procedure PageControlChange(Sender: TObject); procedure menuFecharClick(Sender: TObject); procedure menuFecharTodasExcetoEssaClick(Sender: TObject); procedure menuSepararAbaClick(Sender: TObject); procedure JvPageListChange(Sender: TObject); procedure JvTabBarTabClosing(Sender: TObject; Item: TJvTabBarItem; var AllowClose: Boolean); procedure ActionSairExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure JvTabBarTabMoved(Sender: TObject; Item: TJvTabBarItem); procedure JvTabBarTabSelected(Sender: TObject; Item: TJvTabBarItem); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ActionEnderecosExecute(Sender: TObject); procedure ActionColetaDeDadosExecute(Sender: TObject); procedure ActionParametrosExecute(Sender: TObject); procedure ActionArmazenamentoExecute(Sender: TObject); function doLogin: Boolean; function PodeAbrirFormulario(ClasseForm: TFormClass; var Pagina: TJvCustomPage): Boolean; function TotalFormsAbertos(ClasseForm: TFormClass): Integer; procedure AjustarCaptionAbas(ClasseForm: TFormClass); function ObterAba(Pagina: TJvCustomPage): TJvTabBarItem; function ObterPagina(Aba: TJvTabBarItem): TJvCustomPage; procedure ActionAgendamentoExecute(Sender: TObject); procedure ActionRecebimentoExecute(Sender: TObject); procedure ActionOrdemSeparacaoExecute(Sender: TObject); procedure ActionExpedicaoExecute(Sender: TObject); public procedure NovaPagina(ClasseForm: TFormClass; IndiceImagem: Integer); function FecharPagina(Pagina: TJvCustomPage): Boolean; overload; function FecharPagina(Pagina: TJvCustomPage; TodasExcetoEssa: Boolean): Boolean; overload; function FecharPaginas: Boolean; procedure SepararAba(Pagina: TJvCustomPage); end; var FMenu: TFMenu; FormAtivo: String; implementation uses SessaoUsuario; {$R *.dfm} var IdxTabSelected: Integer = -1; {$Region 'Infra'} procedure TFMenu.NovaPagina(ClasseForm: TFormClass; IndiceImagem: Integer); var Aba : TJvTabBarItem; Pagina : TJvCustomPage; Form : TForm; begin //verifica se pode abrir o form if not PodeAbrirFormulario(ClasseForm, Pagina) then begin JvPageList.ActivePage := Pagina; Exit; end; //cria uma nova aba Aba := JvTabBar.AddTab(''); //instancia uma página padrão Pagina := TJvStandardPage.Create(Self); //seta a PageList da nova página para aquela que já está no form principal Pagina.PageList := JvPageList; //cria um form passando a página para o seu construtor, que recebe um TComponent Form := ClasseForm.Create(Pagina); //Propriedades do Form with Form do begin Align := alClient; BorderStyle := bsNone; Parent := Pagina; end; //Propriedades da Aba with Aba do begin Caption := Form.Caption; ImageIndex := IndiceImagem; PopupMenu := Self.PopupMenu; end; //ajusta o título (caption) das abas AjustarCaptionAbas(ClasseForm); //ativa a página JvPageList.ActivePage := Pagina; FormAtivo := Form.Name; //exibe o formulário Form.Show; end; function TFMenu.PodeAbrirFormulario(ClasseForm: TFormClass; var Pagina: TJvCustomPage): Boolean; var I: Integer; begin Result := True; //varre a JvPageList para saber se já existe um Form aberto for I := 0 to JvPageList.PageCount - 1 do //se achou um form if JvPageList.Pages[I].Components[0].ClassType = ClasseForm then begin Pagina := JvPageList.Pages[I]; //permite abrir o form novamente caso a Tag tenha o valor zero Result := (Pagina.Components[0] as TForm).Tag = 0; Break; end; end; //verifica o total de formulários abertos function TFMenu.TotalFormsAbertos(ClasseForm: TFormClass): Integer; var I: Integer; begin Result := 0; for I := 0 to JvPageList.PageCount - 1 do begin if JvPageList.Pages[I].Components[0].ClassType = ClasseForm then Inc(Result); end; end; //ajusta o título (caption) das abas procedure TFMenu.AjustarCaptionAbas(ClasseForm: TFormClass); var I, Indice, TotalForms: Integer; NovoCaption: string; begin TotalForms := TotalFormsAbertos(ClasseForm); if TotalForms > 1 then begin Indice := 1; for I := 0 to JvPageList.PageCount - 1 do begin with JvPageList do begin if Pages[I].Components[0].ClassType = ClasseForm then begin NovoCaption := (Pages[I].Components[0] as TForm).Caption + ' (' + IntToStr(Indice) + ')'; (Pages[I] as TJvStandardPage).Caption := NovoCaption; ObterAba(Pages[I]).Caption := NovoCaption; Inc(Indice); end; end; end; end; end; { Utilize essa função para que o sistema seja aberto apenas por passagem de parametro function TFMenu.doLogin: Boolean; var FormLogin: TFLogin; begin if ParamStr(1) = '' then begin Application.MessageBox('Você não tem acesso para executar a aplicação.', 'Informação do Sistema', MB_OK + MB_IconInformation); Application.Terminate end else begin FormLogin := TFLogin.Create(Self); FormLogin.EditLogin.Text := ParamStr(1); FormLogin.EditSenha.Text := ParamStr(2); FormLogin.BotaoConfirma.Click; try Result := FormLogin.Logado; finally FormLogin.Free; end; end; end;} function TFMenu.doLogin: Boolean; var FormLogin: TFLogin; begin FormLogin := TFLogin.Create(Self); try FormLogin.ShowModal; Result := FormLogin.Logado; finally FormLogin.Free; end; end; //desenha a aba procedure TFMenu.PageControlDrawTab(Control: TCustomTabControl; TabIndex: Integer; const Rect: TRect; Active: Boolean); var CaptionAba, CaptionForm, CaptionContador: string; I: Integer; begin with JvPageList do begin // Separa o caption da aba e o contador de forms CaptionAba := (Pages[TabIndex] as TJvStandardPage).Caption; CaptionForm := Trim(Copy(CaptionAba, 1, Pos('(', CaptionAba))) + ' '; CaptionContador := Copy(CaptionAba, Pos('(', CaptionAba), Length(CaptionAba)); CaptionContador := Copy(CaptionContador, 1, Pos(')', CaptionContador)); Canvas.FillRect(Rect); Canvas.TextOut(Rect.Left + 3, Rect.Top + 3, CaptionForm); I := Canvas.TextWidth(CaptionForm); Canvas.Font.Style := [fsBold]; Canvas.TextOut(Rect.Left + 3 + I, Rect.Top + 3, CaptionContador); end; end; procedure TFMenu.PageControlChange(Sender: TObject); begin Caption := JvTabBar.SelectedTab.Caption; Application.Title := Caption; with (JvPageList.ActivePage.Components[0] as TForm) do begin if not Assigned(Parent) then Show; end; end; //controla o fechamento da página function TFMenu.FecharPagina(Pagina: TJvCustomPage): Boolean; var Form: TForm; PaginaEsquerda: TJvCustomPage; begin PaginaEsquerda := nil; Form := Pagina.Components[0] as TForm; Result := Form.CloseQuery; if Result then begin if Pagina.PageIndex > 0 then begin PaginaEsquerda := JvPageList.Pages[Pagina.PageIndex - 1]; end; Form.Close; ObterAba(Pagina).Free; Pagina.Free; JvPageList.ActivePage := PaginaEsquerda; end; end; //controla o fechamento da página - todas exceto a selecionada function TFMenu.FecharPagina(Pagina: TJvCustomPage; TodasExcetoEssa: Boolean): Boolean; var I: Integer; begin Result := True; for I := JvPageList.PageCount - 1 downto 0 do if JvPageList.Pages[I] <> Pagina then begin Result := FecharPagina(JvPageList.Pages[I]); if not Result then Exit; end; end; function TFMenu.FecharPaginas: Boolean; var I: Integer; begin Result := True; for I := JvPageList.PageCount - 1 downto 0 do begin Result := FecharPagina(JvPageList.Pages[I]); if not Result then Exit; end; end; procedure TFMenu.FormClose(Sender: TObject; var Action: TCloseAction); begin if Application.MessageBox('Deseja Realmente Sair?', 'Sair do Sistema', MB_YesNo + MB_IconQuestion) <> IdYes then Application.Run; FecharPaginas; Sessao.Free; end; procedure TFMenu.FormCreate(Sender: TObject); begin if not doLogin then Application.Terminate else inherited; end; procedure TFMenu.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (shift=[ssCtrl]) and (key=VK_TAB) then begin JvPageList.NextPage; end; end; //separa a aba (formulário) procedure TFMenu.SepararAba(Pagina: TJvCustomPage); begin with Pagina.Components[0] as TForm do begin Align := alNone; BorderStyle := bsSizeable; Left := (((JvPageList.Width )- Width) div 2)+JvPageList.Left; Top := (((JvPageList.ClientHeight)-Height) div 2 )+(JvPageList.Top)-18; Parent := nil; end; ObterAba(Pagina).Visible := False; end; function TFMenu.ObterAba(Pagina: TJvCustomPage): TJvTabBarItem; var Form: TForm; begin Result := nil; Form := Pagina.Components[0] as TForm; FormAtivo := Form.Name; if Assigned(Pagina) then Result := JvTabBar.Tabs[Pagina.PageIndex]; //força o foco no form Form.Hide; Form.Show; end; procedure TFMenu.JvPageListChange(Sender: TObject); begin ObterAba(JvPageList.ActivePage).Selected := True; end; procedure TFMenu.JvTabBarTabClosing(Sender: TObject; Item: TJvTabBarItem; var AllowClose: Boolean); begin AllowClose := FecharPagina(ObterPagina(Item)); end; procedure TFMenu.JvTabBarTabMoved(Sender: TObject; Item: TJvTabBarItem); begin if IdxTabSelected >= 0 then begin JvPageList.Pages[IdxTabSelected].PageIndex := Item.Index; end; end; procedure TFMenu.JvTabBarTabSelected(Sender: TObject; Item: TJvTabBarItem); begin if Assigned(Item) then IdxTabSelected := Item.Index else IdxTabSelected := -1; end; function TFMenu.ObterPagina(Aba: TJvTabBarItem): TJvCustomPage; begin Result := JvPageList.Pages[Aba.Index]; end; {$EndRegion} {$Region 'Actions'} procedure TFMenu.ActionParametrosExecute(Sender: TObject); begin NovaPagina(TFWmsParametro,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionAgendamentoExecute(Sender: TObject); begin NovaPagina(TFWmsAgendamento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionColetaDeDadosExecute(Sender: TObject); begin NovaPagina(TFWmsColeta,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionArmazenamentoExecute(Sender: TObject); begin NovaPagina(TFWmsArmazenamento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionOrdemSeparacaoExecute(Sender: TObject); begin NovaPagina(TFWmsOrdemSeparacao,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionRecebimentoExecute(Sender: TObject); begin NovaPagina(TFWmsRecebimento,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionEnderecosExecute(Sender: TObject); begin NovaPagina(TFWmsEndereco,(Sender as TAction).ImageIndex); end; procedure TFMenu.ActionSairExecute(Sender: TObject); begin Close; end; procedure TFMenu.ActionExpedicaoExecute(Sender: TObject); begin NovaPagina(TFWmsExpedicao,(Sender as TAction).ImageIndex); end; {$EndRegion} {$Region 'PopupMenu'} procedure TFMenu.menuFecharClick(Sender: TObject); begin FecharPagina(JvPageList.ActivePage); end; procedure TFMenu.menuFecharTodasExcetoEssaClick(Sender: TObject); begin FecharPagina(JvPageList.ActivePage, True); end; procedure TFMenu.menuSepararAbaClick(Sender: TObject); begin SepararAba(JvPageList.ActivePage); end; {$EndRegion} end.
unit LuaDisassembler; {$mode delphi} interface uses Classes, SysUtils, disassembler, lua, lauxlib, lualib, symbolhandler, LastDisassembleData; procedure initializeLuaDisassembler(L: PLua_state); procedure LastDisassemblerDataToTable(L: PLua_State; t: integer; const ldd: TLastDisassembleData); procedure LastDisassemblerDataFromTable(L: PLua_State; t: integer; var ldd: TLastDisassembleData); implementation uses LuaHandler, LuaClass, LuaObject; function disassembler_disassemble(L: PLua_State): integer; cdecl; var d: TDisassembler; s,desc: string; address: ptruint; begin result:=0; d:=luaclass_getClassObject(L); if lua_gettop(L)=1 then begin if lua_type(L,1)=LUA_TSTRING then address:=symhandler.getAddressFromNameL(Lua_ToString(L, 1)) else address:=lua_tointeger(L, 1); s:=d.disassemble(address, desc); lua_pushstring(L, s); result:=1; end; end; function disassembler_decodeLastParametersToString(L: PLua_State): integer; cdecl; var d: TDisassembler; begin d:=luaclass_getClassObject(L); lua_pushstring(L, d.DecodeLastParametersToString); result:=1; end; procedure LastDisassemblerDataFromTable(L: PLua_State; t: integer; var ldd: TLastDisassembleData); var bytestable: integer; i, size: integer; begin lua_pushstring(L,'address'); lua_gettable(L, t); ldd.address:=lua_tointeger(L, -1); lua_pop(L, 1); lua_pushstring(L,'opcode'); lua_gettable(L, t); ldd.opcode:=Lua_ToString(L, -1); lua_pop(L, 1); lua_pushstring(L,'parameters'); lua_gettable(L, t); ldd.parameters:=Lua_ToString(L, -1); lua_pop(L, 1); lua_pushstring(L,'description'); lua_gettable(L, t); ldd.description:=Lua_ToString(L, -1); lua_pop(L, 1); lua_pushstring(L,'commentsoverride'); lua_gettable(L, t); ldd.commentsoverride:=Lua_ToString(L, -1); lua_pop(L, 1); lua_pushstring(L,'bytes'); lua_gettable(L, t); bytestable:=lua_gettop(L); size:=lua_objlen(L, bytestable); setlength(ldd.Bytes, size); for i:=1 to size do begin lua_pushinteger(L, i); lua_gettable(L, bytestable); ldd.bytes[i-1]:=lua_tointeger(L, -1); lua_pop(L, 1); end; lua_pop(L, 1); lua_pushstring(L,'modrmValueType'); lua_gettable(L, t); ldd.modrmValueType:=TDisAssemblerValueType(lua_tointeger(L, -1)); lua_pop(L, 1); lua_pushstring(L,'modrmValue'); lua_gettable(L, t); ldd.modrmValue:=lua_tointeger(L, -1); lua_pop(L, 1); lua_pushstring(L,'parameterValueType'); lua_gettable(L, t); ldd.parameterValueType:=TDisAssemblerValueType(lua_tointeger(L, -1)); lua_pop(L, 1); lua_pushstring(L,'parameterValue'); lua_gettable(L, t); ldd.parameterValue:=lua_tointeger(L, -1); lua_pop(L, 1); lua_pushstring(L,'isJump'); lua_gettable(L, t); ldd.isjump:=lua_toboolean(L, -1); lua_pop(L, 1); lua_pushstring(L,'isCall'); lua_gettable(L, t); ldd.isCall:=lua_toboolean(L, -1); lua_pop(L, 1); lua_pushstring(L,'isRet'); lua_gettable(L, t); ldd.isRet:=lua_toboolean(L, -1); lua_pop(L, 1); lua_pushstring(L,'isConditionalJump'); lua_gettable(L, t); ldd.isconditionaljump:=lua_toboolean(L, -1); lua_pop(L, 1); end; procedure LastDisassemblerDataToTable(L: PLua_State; t: integer; const ldd: TLastDisassembleData); var temptable: integer; i: integer; begin lua_pushstring(L,'address'); lua_pushinteger(L, ldd.address); lua_settable(L, t); lua_pushstring(L,'opcode'); lua_pushstring(L, ldd.opcode); lua_settable(L, t); lua_pushstring(L,'parameters'); lua_pushstring(L, ldd.parameters); lua_settable(L, t); lua_pushstring(L,'description'); lua_pushstring(L, ldd.description); lua_settable(L, t); lua_pushstring(L,'commentsoverride'); lua_pushstring(L, ldd.commentsoverride); lua_settable(L, t); lua_pushstring(L, 'bytes'); lua_newtable(L); temptable:=lua_gettop(L); for i:=0 to length(ldd.Bytes)-1 do begin lua_pushinteger(L, i+1); lua_pushinteger(L, ldd.Bytes[i]); lua_settable(L, temptable); end; lua_settable(L, t); lua_pushstring(L, 'modrmValueType'); lua_pushinteger(L, integer(ldd.modrmValueType)); lua_settable(L, t); lua_pushstring(L,'modrmValue'); lua_pushinteger(L, ldd.modrmValue); lua_settable(L, t); lua_pushstring(L, 'parameterValueType'); lua_pushinteger(L, integer(ldd.parameterValueType)); lua_settable(L, t); lua_pushstring(L,'parameterValue'); lua_pushinteger(L, ldd.parameterValue); lua_settable(L, t); lua_pushstring(L,'isJump'); lua_pushboolean(L, ldd.isJump); lua_settable(L, t); lua_pushstring(L,'isCall'); lua_pushboolean(L, ldd.isCall); lua_settable(L, t); lua_pushstring(L,'isRet'); lua_pushboolean(L, ldd.isret); lua_settable(L, t); lua_pushstring(L,'isRep'); lua_pushboolean(L, ldd.isrep); lua_settable(L, t); lua_pushstring(L,'isConditionalJump'); lua_pushboolean(L, ldd.isConditionalJump); lua_settable(L, t); end; function disassembler_getLastDisassembleData(L: PLua_State): integer; cdecl; var d: TDisassembler; t: integer; i: integer; begin result:=1; d:=luaclass_getClassObject(L); lua_newtable(L); t:=lua_gettop(L); LastDisassemblerDataToTable(L, t, d.LastDisassembleData); end; function createDisassembler(L: PLua_State): integer; cdecl; begin luaclass_newClass(L, TDisassembler.Create); result:=1; end; function createCR3Disassembler(L: PLua_State): integer; cdecl; begin result:=0; {$ifdef windows} luaclass_newClass(L, TCR3Disassembler.Create); result:=1; {$endif} end; function getDefaultDisassembler(L: PLua_State): integer; cdecl; begin luaclass_newClass(L, defaultDisassembler); result:=1; end; function getVisibleDisassembler(L: PLua_State): integer; cdecl; begin luaclass_newClass(L, visibleDisassembler); result:=1; end; procedure disassembler_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'disassemble', disassembler_disassemble); luaclass_addClassFunctionToTable(L, metatable, userdata, 'decodeLastParametersToString', disassembler_decodeLastParametersToString); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getLastDisassembleData', disassembler_getLastDisassembleData); luaclass_addPropertyToTable(L, metatable, userdata, 'LastDisassembleData', disassembler_getLastDisassembleData, nil); end; procedure initializeLuaDisassembler(L: PLua_state); begin lua_register(L, 'createDisassembler', createDisassembler); lua_register(L, 'createCR3Disassembler', createCR3Disassembler); lua_register(L, 'getDefaultDisassembler', getDefaultDisassembler); lua_register(L, 'getVisibleDisassembler', getVisibleDisassembler); end; initialization luaclass_register(TDisassembler, disassembler_addMetaData); end.
unit GLSpecials; // GLSpecials - Contains structures and functions for special // effects for GLScene // Version - 0.0.3 // Last Change - 13. August 1998 // for more information see help file interface uses Windows, Classes, Geometry, GLScene, OpenGL12, GLTexture; type // lens flares, used in TLightSource PFlare = ^TFlare; TFlare = record FlareType : Integer; // flare texture index, 0..5 Scale : Single; Location : Single; // postion on axis Color : TAffineVector; ColorAddr : Pointer; end; TShineTex = array[0..9] of Integer; TFlareTex = array[0..5] of Integer; TLensFlares = class(TObject) private FList: TList; FShineTex : TShineTex; FFlareTex : TFlareTex; function Get(Index: Integer): TFlare; function GetCount: Integer; function GetFlareTex(Index: Integer): Integer; function GetShineTex(Index: Integer): Integer; public FlareTic : Integer; constructor Create; destructor Destroy; override; function AddFlare(FlareType: Integer; Location, Scale: Single; Color: TVector; ColorScale: Single): Integer; property Count: Integer read GetCount; property Flare[Index: Integer]: TFlare read Get; default; property FlareTexture[Index: Integer]: Integer read GetFlareTex; property ShineTexture[Index: Integer]: Integer read GetShineTex; end; const Distance = 16; MAP = 256; MH = 256; Comp = 64; type PCOLOUR = ^COLOUR; COLOUR = record r, g, b: TGLubyte; end; // landscape, used in where ????????????????????????? TLandScape = class(TObject) private FFullView: Boolean; FMinFilter : TMinFilter; FMagFilter : TMagFilter; FMinFilterValue: TGLenum; FMagFilterValue: TGLenum; FLandTexture: Integer; FOcenTexture: Integer; FObject: array[0..66048] of byte; y: array[0..66048] of integer; c: array[0..66048] of COLOUR; procedure DrawFLAT(X, Z: Integer; X1, X2, Z1, Z2: Integer); procedure DrawFLAT2(X, Z: Integer; X1, X2, Z1, Z2: Integer); procedure Create_Fractal; procedure SetMagFilter(Value: TMagFilter); procedure SetMinFilter(Value: TMinFilter); procedure GetTextureFilter; //function GetHandle: TObjectHandle; //procedure BuildList public constructor Create; destructor Destroy; override; function Get_Height(SX, SZ: TGLfloat): TGLfloat; procedure RenderLandScape(Camera: TCamera); property LandTexture: Integer read FLandTexture; property OcenTexture: Integer read FOcenTexture; property FullView: Boolean read FFullView write FFullView; property MinFilter: TMinFilter read FMinFilter write SetMinFilter; property MagFilter: TMagFilter read FMagFilter write SetMagFilter; end; procedure InitLensFlares; procedure InitLandScape; var LensFlares : TLensFlares; LandScape: TLandScape; //------------------------------------------------------------------------------ implementation uses Graphics, SysUtils, GLMisc; {$R Special.res} //------------------------------------------------------------------------------ constructor TLensFlares.Create; begin inherited Create; FList := TList.Create; end; //------------------------------------------------------------------------------ destructor TLensFlares.Destroy; var I : Integer; begin glDeleteTextures(10,@FShineTex); glDeleteTextures(6,@FFlareTex); for I:=0 to Count-1 do Dispose(PFlare(FList[I])); FList.Free; inherited Destroy; end; //------------------------------------------------------------------------------ function TLensFlares.Get(Index: Integer): TFlare; begin Result:=PFlare(FList[Index])^; end; //------------------------------------------------------------------------------ function TLensFlares.GetCount: Integer; begin Result:=FList.Count; end; //------------------------------------------------------------------------------ function TLensFlares.GetFlareTex(Index: Integer): Integer; begin Result:=FFlareTex[Index]; end; //------------------------------------------------------------------------------ function TLensFlares.GetShineTex(Index: Integer): Integer; begin Result:=FShineTex[Index]; end; //------------------------------------------------------------------------------ function TLensFlares.AddFlare(FlareType: Integer; Location, Scale: Single; Color: TVector; ColorScale: Single): Integer; var AFlare : PFlare; begin New(AFlare); AFlare.FlareType:=FlareType; AFlare.Location:=Location; AFlare.Scale:=Scale; AFlare.Color:=MakeAffineVector([Color[0],Color[1],Color[2]]); AFlare.ColorAddr:=@AFlare.Color; VectorScale(AFlare.Color,ColorScale); Result:=FList.Add(AFlare); end; //------------------------------------------------------------------------------ (* function SetupTexture(FileName: String; MinFilter, MaxFilter: TGLuint): Integer; var buf : Pointer; Width, Height : Integer; Loader : TSGIGraphic; begin glGenTextures(1,@Result); glBindTexture(GL_TEXTURE_2D,Result); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); glPixelStorei(GL_UNPACK_ALIGNMENT,4); glPixelStorei(GL_UNPACK_ROW_LENGTH,0); glPixelStorei(GL_UNPACK_SKIP_ROWS,0); glPixelStorei(GL_UNPACK_SKIP_PIXELS,0); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,MinFilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,MaxFilter); buf:=nil; Loader:=TSGIGraphic.Create; try buf:=Loader.LoadRaw(FileName,Width,Height); { if (useMipmaps) gluBuild2DMipmaps(GL_TEXTURE_2D, 1, width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, buf); else} glTexImage2D(GL_TEXTURE_2D,0,1,Width,Height,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,buf); finally Loader.Free; FreeMem(buf); end; end; *) //------------------------------------------------------------------------------ //The stream contains a bitmap file function SetupTextureFromStream(Stream: TStream; MinFilter, MaxFilter: TGLuint): Integer; type PPixelArray = ^TByteArray; var Temp: Byte; Bmp: TBitmap; Buffer: PPixelArray; BMInfo : TBitmapInfo; I,ImageSize : Integer; MemDC : HDC; begin glGenTextures(1,@Result); glBindTexture(GL_TEXTURE_2D,Result); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); glPixelStorei(GL_UNPACK_ALIGNMENT,4); glPixelStorei(GL_UNPACK_ROW_LENGTH,0); glPixelStorei(GL_UNPACK_SKIP_ROWS,0); glPixelStorei(GL_UNPACK_SKIP_PIXELS,0); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,MinFilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,MaxFilter); Bmp := TBitmap.Create; Stream.Seek(0, soFromBeginning); Bmp.LoadFromStream(Stream); with BMinfo.bmiHeader do begin // create description of the required image format FillChar(BMInfo, sizeof(BMInfo),0); biSize:=sizeof(TBitmapInfoHeader); biBitCount:=24; biWidth:=RoundUpToPowerOf2(Bmp.Width); biHeight:=RoundUpToPowerOf2(Bmp.Height); ImageSize:=biWidth*biHeight; biPlanes:=1; biCompression:=BI_RGB; MemDC:=CreateCompatibleDC(0); Getmem(Buffer, ImageSize*3); // get the actual bits of the image GetDIBits(MemDC, Bmp.Handle, 0, biHeight, Buffer, BMInfo, DIB_RGB_COLORS); {$IFOPT R+} {$DEFINE RangeCheck} {$R-} {$ENDIF} for I:=0 TO ImageSize-1 do //swap blue with red to go from bgr to rgb begin Temp := Buffer^[I*3]; Buffer^[I*3] := Buffer^[I*3+2]; Buffer^[I*3+2] := Temp; end; // restore range check, if previously activated {$IFDEF RangeCheck} {$UNDEF RangeCheck} {$R+} {$ENDIF} if (MinFilter = GL_NEAREST) or (MinFilter = GL_LINEAR) then glTexImage2d(GL_TEXTURE_2D,0, 3, biWidth,biHeight,0, GL_RGB, GL_UNSIGNED_BYTE, Buffer) else gluBuild2DMipmaps(GL_TEXTURE_2D, 3, biWidth, biHeight, GL_RGB, GL_UNSIGNED_BYTE, Buffer); FreeMem(Buffer); DeleteDC(MemDC); end; Bmp.free; end; //------------------------------------------------------------------------------ procedure InitLensFlares; var i : Integer; Stream: TMemoryStream; Bmp: TBitmap; procedure StreamSpecialBitmap(const resName : String); var bmp24 : TBitmap; begin Bmp.LoadFromResourceName(HInstance, Format('GLS_%s%d', [resName, i])); bmp24:=TBitmap.Create; bmp24.PixelFormat:=pf24Bit; bmp24.Width:=bmp.Width; bmp24.Height:=bmp.Height; bmp24.Canvas.Draw(0, 0, bmp); Stream.Clear; Bmp24.SaveToStream(Stream); bmp24.free; Stream.Seek(0, soFromBeginning); end; begin LensFlares:=TLensFlares.Create; with LensFlares do begin // textures Stream := TMemoryStream.Create; Bmp := TBitmap.Create; try for I:=0 to 9 do begin StreamSpecialBitmap('SHINE'); FShineTex[I] := SetupTextureFromStream(Stream ,GL_NEAREST, GL_NEAREST); end; for I:=0 to 5 do begin StreamSpecialBitmap('FLARE'); FFlareTex[I] := SetupTextureFromStream(Stream ,GL_NEAREST, GL_NEAREST); end; finally Bmp.free; Stream.free; end; // Shines AddFlare(-1,1,0.2,clrBlue,1); AddFlare(-1,1,0.1,clrGreen,1); AddFlare(-1,1,0.15,clrRed,1); // Flares AddFlare(2,1.3,0.04,clrRed,0.6); AddFlare(3,1,0.1,clrRed,0.4); AddFlare(1,0.5,0.2,clrRed,0.3); AddFlare(3,0.2,0.05,clrRed,0.3); AddFlare(0,0,0.04,clrRed,0.3); AddFlare(5,-0.25,0.07,clrRed,0.5); AddFlare(5,-0.4,0.02,clrRed,0.6); AddFlare(5,-0.6,0.04,clrRed,0.4); AddFlare(5,-1,0.03,clrRed,0.2); end; end; //------------------------------------------------------------------------------ procedure InitLandScape; var Bmp: TBitmap; Stream: TMemoryStream; begin LandScape := TLandScape.Create; //lands textures Stream := TMemoryStream.Create; Bmp := TBitmap.Create; Bmp.LoadFromResourceName(HInstance, 'GLS_LAND1'); Stream.Clear; Bmp.SaveToStream(Stream); Stream.Seek(0, soFromBeginning); Bmp.free; LandScape.FLandTexture := SetupTextureFromStream(Stream ,GL_NEAREST, GL_LINEAR); //Ocen texture Bmp := TBitmap.Create; Bmp.LoadFromResourceName(HInstance, 'GLS_OCEN'); Stream.Clear; Bmp.SaveToStream(Stream); Stream.Seek(0, soFromBeginning); Bmp.free; LandScape.FOcenTexture := SetupTextureFromStream(Stream ,GL_NEAREST, GL_LINEAR); Stream.free; end; //------------------------------------------------------------------------------ constructor TLandScape.Create; begin inherited Create; FLandTexture := 0; FOcenTexture := 0; FFullView := False; Create_Fractal; FMinFilter := miLinear; FMagFilter := maLinear; GetTextureFilter; end; //------------------------------------------------------------------------------ destructor TLandScape.Destroy; begin glDeleteTextures(1, @FLandTexture); glDeleteTextures(1, @FOcenTexture); inherited Destroy; end; //------------------------------------------------------------------------------ function NodeIndex(x, y: Integer): Integer; begin Result := (y shl 8) + x; end; //------------------------------------------------------------------------------ procedure TLandScape.Create_Fractal; var bsize, csize: Integer; x, z, i: Integer; g1: Integer; r: Integer; //The maximum random value. begin r := 256; //Make the matrix flat. for X:=0 to MAP do for Z:=0 to MAP do y[NodeIndex(x, z)] := 0; bsize := MAP; Randomize; for i:=0 to 7 do begin X := 0; while X<MAP do begin Z := 0; while Z<MAP do begin y[NodeIndex(x, z)] := y[NodeIndex(x, z)] + Random(19990315) mod (r+1) - (r shr 1); //if (FAllInWater) and (Y[NodeIndex(x, z)]>0) then // Y[NodeIndex(x, z)] := -Y[NodeIndex(x, z)]; Inc(Z, bsize); end; if (i>3) and (r>64) then r := r shr 1; Inc(X, bsize); end; csize := bsize div 2; if (csize>0) then begin X := 0; while X<MAP do begin Z := 0; while Z<MAP do begin if ( x < MAP) then y[NodeIndex(x+csize,z)] := (y[NodeIndex(x+bsize, z)]+y[NodeIndex(x, z)]) div 2; if ( z < MAP) then y[NodeIndex(x,z+csize)] := (y[NodeIndex(x,z+bsize)]+y[NodeIndex(x, z)]) div 2; if ( x < MAP) and (z < MAP ) then y[NodeIndex(x+csize,z+csize)] := ( y[NodeIndex(x, z)] + y[NodeIndex(x+bsize, z)] + y[NodeIndex(x,z+bsize)] + y[NodeIndex(x+bsize,z+bsize)]) div 4; Inc(Z, bsize); end; Inc(X, bsize); end; end; bsize := csize; end; //I am leaving trees out for now. for X:=0 to MAP-1 do for Z:=0 to MAP-1 do FObject[NodeIndex(x,z)] := Ord('n'); for X:=0 to MAP-1 do for Z:=0 to MAP-1 do begin if (y[NodeIndex(x,z)]>MH) then begin i := y[NodeIndex(x,z)]; y[NodeIndex(x,z)] := i * i; y[NodeIndex(x,z)] := Round(y[NodeIndex(x,z)]/MH); end; end; //This next bit smooths down the landscape. for X:=1 to MAP-1 do for Z:=1 to MAP-1 do begin y[NodeIndex(x, z)] := y[NodeIndex(x, z-1)] + y[NodeIndex(x, z+1)] + y[NodeIndex(x-1, z)] + y[NodeIndex(x+1, z)]; y[NodeIndex(x, z)] := y[NodeIndex(x, z)] div 4; end; //This bit actually does the shading etc. */ for x:=0 to MAP-1 do for z:=0 to MAP-1 do begin g1 := Round((y[NodeIndex(x, z)]-y[NodeIndex(x+1, z)]) * 2.0 + 127); if (g1>255) then g1 := 255 else if(g1<0) then g1 := 0; if(y[NodeIndex(x, z)]>=MH) then begin c[NodeIndex(x,z)].r := g1; c[NodeIndex(x,z)].g := c[NodeIndex(x,z)].r; c[NodeIndex(x,z)].b := c[NodeIndex(x,z)].r; end else if(y[NodeIndex(x, z)]>(MH div 2)) then begin c[NodeIndex(x,z)].r := g1; c[NodeIndex(x,z)].g := Round(g1*0.75); c[NodeIndex(x,z)].b := Round(g1*0.5); end else if(y[NodeIndex(x, z)]>0) then begin c[NodeIndex(x,z)].g := g1; c[NodeIndex(x,z)].r := Round(g1*0.75); c[NodeIndex(x,z)].b := 0; end else begin c[NodeIndex(x,z)].r := g1; c[NodeIndex(x,z)].g := Round(g1*0.75); c[NodeIndex(x,z)].b := Round(g1*0.5); end; end; end; //------------------------------------------------------------------------------ procedure TLandScape.DrawFLAT(X, Z: Integer; X1, X2, Z1, Z2: Integer); { var V1, V2, N: TAffineVector; A, B, D: TAffineVector; begin A[0] := x1; A[1] := y[NodeIndex(x,z+1)]; A[2] := z2; B[0] := x2; B[1] := y[NodeIndex(x+1,z+1)]; B[2] := z2; D[0] := x2; D[1] := y[NodeIndex(x+1,z)]; D[2] := z1; // normal vector from face V1 := VectorAffineSubtract(B, A); V2 := VectorAffineSubtract(D, A); N := VectorCrossProduct(V1, V2); glBegin(GL_QUADS); glNormal3fv(@N); glColor3ub(c[NodeIndex(x,z+1)].r, c[NodeIndex(x,z+1)].g, c[NodeIndex(x,z+1)].b); xglTexCoord2f(0.0, 1.0); glVertex3fv(@A); glColor3ub(c[NodeIndex(x+1,z+1)].r, c[NodeIndex(x+1,z+1)].g, c[NodeIndex(x+1,z+1)].b); xglTexCoord2f(1.0, 1.0); glVertex3fv(@B); glColor3ub(c[NodeIndex(x+1,z)].r, c[NodeIndex(x+1,z)].g, c[NodeIndex(x+1,z)].b); xglTexCoord2f(1.0, 0.0); glVertex3fv(@D); glColor3ub(c[NodeIndex(x,z)].r, c[NodeIndex(x,z)].g, c[NodeIndex(x,z)].b); xglTexCoord2f(0.0, 0.0); glVertex3f(x1, y[NodeIndex(x, z)], z1); } begin glBegin(GL_QUADS); glColor3ub(c[NodeIndex(x,z+1)].r, c[NodeIndex(x,z+1)].g, c[NodeIndex(x,z+1)].b); xglTexCoord2f(0.0, 1.0); glVertex3f(x1, y[NodeIndex(x,z+1)], z2); glColor3ub(c[NodeIndex(x+1,z+1)].r, c[NodeIndex(x+1,z+1)].g, c[NodeIndex(x+1,z+1)].b); xglTexCoord2f(1.0, 1.0); glVertex3f(x2, y[NodeIndex(x+1, z+1)], z2); glColor3ub(c[NodeIndex(x+1,z)].r, c[NodeIndex(x+1,z)].g, c[NodeIndex(x+1,z)].b); xglTexCoord2f(1.0, 0.0); glVertex3f(x2, y[NodeIndex(x+1, z)], z1); glColor3ub(c[NodeIndex(x,z)].r, c[NodeIndex(x,z)].g, c[NodeIndex(x,z)].b); xglTexCoord2f(0.0, 0.0); glVertex3f(x1, y[NodeIndex(x, z)], z1); glEnd(); end; //------------------------------------------------------------------------------ procedure TLandScape.DrawFLAT2(X, Z: Integer; X1, X2, Z1, Z2: Integer); { var V1, V2, N: TAffineVector; A, B, D: TAffineVector; begin A[0] := x1; A[1] := y[NodeIndex(x,z+4)]; A[2] := z2; B[0] := x2; B[1] := y[NodeIndex(x+4,z+4)]; B[2] := z2; D[0] := x2; D[1] := y[NodeIndex(x+4,z)]; D[2] := z1; // normal vector from face V1 := VectorAffineSubtract(B, A); V2 := VectorAffineSubtract(D, A); N := VectorCrossProduct(V1, V2); glBegin(GL_QUADS); glNormal3fv(@N); glColor3ub(c[NodeIndex(x,z+4)].r, c[NodeIndex(x,z+4)].g, c[NodeIndex(x,z+4)].b); xglTexCoord2f(0.0, 1.0); glVertex3fv(@A); glColor3ub(c[NodeIndex(x+4,z+4)].r, c[NodeIndex(x+4,z+4)].g, c[NodeIndex(x+4,z+4)].b); xglTexCoord2f(1.0, 1.0); glVertex3fv(@B); glColor3ub(c[NodeIndex(x+4,z)].r, c[NodeIndex(x+4,z)].g, c[NodeIndex(x+4,z)].b); xglTexCoord2f(1.0, 0.0); glVertex3fv(@D); glColor3ub(c[NodeIndex(x,z)].r, c[NodeIndex(x,z)].g, c[NodeIndex(x,z)].b); xglTexCoord2f(0.0, 0.0); glVertex3f(x1, y[NodeIndex(x, z)], z1); } begin glBegin(GL_QUADS); glColor3ub(c[NodeIndex(x,z+4)].r, c[NodeIndex(x,z+4)].g, c[NodeIndex(x,z+4)].b); xglTexCoord2f(0.0, 1.0); glVertex3f(x1, y[NodeIndex(x,z+4)], z2); glColor3ub(c[NodeIndex(x+4,z+4)].r, c[NodeIndex(x+4,z+4)].g, c[NodeIndex(x+4,z+4)].b); xglTexCoord2f(1.0, 1.0); glVertex3f(x2, y[NodeIndex(x+4, z+4)], z2); glColor3ub(c[NodeIndex(x+4,z)].r, c[NodeIndex(x+4,z)].g, c[NodeIndex(x+4,z)].b); xglTexCoord2f(1.0, 0.0); glVertex3f(x2, y[NodeIndex(x+4, z)], z1); glColor3ub(c[NodeIndex(x,z)].r, c[NodeIndex(x,z)].g, c[NodeIndex(x,z)].b); xglTexCoord2f(0.0, 0.0); glVertex3f(x1, y[NodeIndex(x, z)], z1); glEnd(); end; //------------------------------------------------------------------------------ function TLandScape.Get_Height(SX, SZ: TGLfloat): TGLfloat; var x0, x1, lx, lz, x, z, midpoint: TGLfloat; fx, fz: Integer; begin x := SX/comp; z := SZ/comp; fx := Round(x-0.5); fz := Round(z-0.5); //Why does the Trunc function cause a division by zero error //fx := Trunc(x); //fz := Trunc(z); lx := x - fx; lz := z - fz; x0 := y[NodeIndex(fx,fz)] + (y[NodeIndex(fx,fz+1)] - y[NodeIndex(fx,fz)])*lz; x1 := y[NodeIndex(fx+1,fz)] + (y[NodeIndex(fx+1,fz+1)] - y[NodeIndex(fx+1,fz)])*lz; midpoint := x0 + (x1 - x0)*lx; Result := midpoint; { if(x<distance) then posx := ((MAP - distance) shl 6) else if(x>(MAP-distance)) then posx := (distance shl 6); if(z<distance) then posz := ((MAP - distance) shl 6) else if(z>(MAP-distance)) then posz := (distance shl 6); if (FOceans) then if (posy < w_h + 16.0) then posy := w_h + 16.0; } end; //------------------------------------------------------------------------------ procedure TLandScape.GetTextureFilter; begin case FMinFilter of miNearest : FMinFilterValue := GL_NEAREST; miLinear : FMinFilterValue := GL_LINEAR; miNearestMipmapNearest : FMinFilterValue := GL_NEAREST_MIPMAP_NEAREST; miLinearMipmapNearest : FMinFilterValue := GL_LINEAR_MIPMAP_NEAREST; miNearestMipmapLinear : FMinFilterValue := GL_NEAREST_MIPMAP_LINEAR; miLinearMipmapLinear : FMinFilterValue := GL_LINEAR_MIPMAP_LINEAR; end; case FMagFilter of maNearest : FMagFilterValue := GL_NEAREST; maLinear : FMagFilterValue := GL_LINEAR; end; end; //------------------------------------------------------------------------------ procedure TLandScape.SetMagFilter(Value: TMagFilter); begin FMagFilter := Value; GetTextureFilter; end; //------------------------------------------------------------------------------ procedure TLandScape.SetMinFilter(Value: TMinFilter); begin FMinFilter := Value; GetTextureFilter; end; //------------------------------------------------------------------------------ procedure TLandScape.RenderLandScape(Camera: TCamera); var X, Z, Position_X, Position_Z: Integer; X1, X2, Z1, Z2: TGLfloat; fogColor: array[0..3] of TGLfloat; const distance_l = comp * distance; begin fogColor[0] := 0; fogColor[1] := 0; fogColor[2] := 0; fogColor[3] := 1.0; glPushAttrib(GL_ALL_ATTRIB_BITS); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, FMagFilterValue); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, FMinFilterValue); glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); position_x := Round(Camera.Position.X/comp); position_z := Round(Camera.Position.Z/comp); glPushMatrix; Camera.RestoreMatrix; glBindTexture(GL_TEXTURE_2D, FLandTexture); if(FFullView) then begin X := 0; while (X<MAP) do begin Z := 0; while Z<MAP do begin x1 := (x shl 6); x2 := (x shl 6) + (comp shl 2); z1 := (z shl 6); z2 := (z shl 6) + (comp shl 2); DrawFLAT2(x, z, Round(x1), Round(x2), Round(z1), Round(z2)); Inc(Z, 4); end; Inc(X, 4); end; end else begin //********** Warning, this bit needs optimising ! **********/ //* The following bit of code has been written with the */ //* intention of making sure that OpenGL doesn't draw what */ //* cannot be seen by the camera. */ //**********************************************************/ if (Camera.Direction.X>=(-0.75)) and (Camera.Direction.X<=(0.75)) then begin if (Camera.Direction.Z<=0) then begin X := Position_X - Distance; while X<Position_X + Distance do begin Z := Position_Z - Distance; while Z<Position_Z + 2 do begin x1 := (x shl 6); x2 := (x shl 6) + comp; z1 := (z shl 6); z2 := (z shl 6) + comp; DrawFLAT(x, z, Round(x1), Round(x2), Round(z1), Round(z2)); Inc(Z); end; Inc(X); end; end else begin if (Camera.Direction.Z>0) then begin X := Position_X - Distance; while X<Position_X + Distance do begin Z := Position_Z - 2; while Z<Position_Z + Distance do begin x1 := (x shl 6); x2 := (x shl 6) + comp; z1 := (z shl 6); z2 := (z shl 6) + comp; DrawFLAT(x, z, Round(x1), Round(x2), Round(z1), Round(z2)); Inc(Z); end; Inc(X); end; end; end; end else begin if (Camera.Direction.Z>=(-0.75)) and (Camera.Direction.Z<=(0.75)) then begin if (Camera.Direction.X<=0) then begin X := Position_X - Distance; while X<Position_X + 2 do begin Z := Position_Z - Distance; while Z<Position_Z + Distance do begin x1 := (x shl 6); x2 := (x shl 6) + comp; z1 := (z shl 6); z2 := (z shl 6) + comp; DrawFLAT(x, z, Round(x1), Round(x2), Round(z1), Round(z2)); Inc(Z); end; Inc(X); end; end else begin if (Camera.Direction.X>0) then begin X := Position_X - 2; while X<Position_X + Distance do begin Z := Position_Z - Distance; while Z<Position_Z + Distance do begin x1 := (x shl 6); x2 := (x shl 6) + comp; z1 := (z shl 6); z2 := (z shl 6) + comp; DrawFLAT(x, z, Round(x1), Round(x2), Round(z1), Round(z2)); Inc(Z); end; Inc(X); end; end; end; end; end; end; { if (FOceans) then begin } (* glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, FOcenTexture); glEnable(GL_BLEND); glColor4f(0.0, 0.3, 0.6, 0.5); { X := Position_X - Distance; while X<Position_X + DIstance do begin Z := Position_Z - Distance; while Z<Position_Z + Distance do begin x1 := (x shl 6); x2 := (x shl 6) + (comp shl 1); z1 := (z shl 6); z2 := (z shl 6) + (comp shl 1); } glBegin(GL_POLYGON); { glVertex3f(x1, 100, z1);//w_h, z1); glVertex3f(x2, 100, z1); glVertex3f(x2, 100, z2); glVertex3f(x1, 100, z2); } xglTexCoord2f(0.0, 1.0); glVertex3f(0, 0, 100000); xglTexCoord2f(1.0, 1.0); glVertex3f(100000, 0, 100000); xglTexCoord2f(1.0, 0.0); glVertex3f(100000, 0, 0); xglTexCoord2f(0.0, 0.0); glVertex3f(0, 0, 0);//w_h, z1); glEnd; { Inc(Z, 2); end; Inc(X, 2); end; } glDisable(GL_BLEND); { end; } *) glPopMatrix; glPopAttrib; end; begin LandScape := nil; LensFlares := nil; end.
unit ConsoleMainView; interface uses AppController, Orders; type TConsoleMainView = class(TInterfacedObject, IView) strict private FController: TAppController; FModel: TOrders; function GetController: TAppController; procedure SetController(const Value: TAppController); function GetModel: TOrders; procedure SetModel(const Value: TOrders); public property Controller: TAppController read GetController write SetController; property Model: TOrders read GetModel write SetModel; procedure RefreshView; end; implementation uses Order; { TConsoleMainView } function TConsoleMainView.GetController: TAppController; begin Result := FController; end; procedure TConsoleMainView.SetController(const Value: TAppController); begin FController := Value; end; function TConsoleMainView.GetModel: TOrders; begin Result := FModel; end; procedure TConsoleMainView.SetModel(const Value: TOrders); begin FModel := Value; end; procedure TConsoleMainView.RefreshView; var LOrder: TOrder; begin for LOrder in Model.GetAllOrders do System.Writeln(LOrder.Text, LOrder.FullPrice, LOrder.DiscountedPrice); end; end.
unit DropUser; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, BCDialogs.Dlg, BCControls.CheckBox, JvExStdCtrls, JvCheckBox; type TDropUserDialog = class(TDialog) CancelButton: TButton; CascadeCheckBox: TBCCheckBox; GrayLinePanel: TPanel; InfoImage: TImage; MessageLabel: TLabel; OKButton: TButton; Panel1: TPanel; Separator1Panel: TPanel; TopPanel: TPanel; procedure FormDestroy(Sender: TObject); private { Private declarations } function GetCascadeObjects: Boolean; public { Public declarations } function Open(TableName: string): Boolean; property CascadeObjects: Boolean read GetCascadeObjects; end; function DropUserDialog: TDropUserDialog; implementation {$R *.dfm} uses System.Math, BCCommon.StyleUtils; const CAPTION_TEXT = 'Drop user %s, are you sure?'; var FDropUserDialog: TDropUserDialog; function DropUserDialog: TDropUserDialog; begin if not Assigned(FDropUserDialog) then Application.CreateForm(TDropUserDialog, FDropUserDialog); Result := FDropUserDialog; SetStyledFormSize(Result); end; procedure TDropUserDialog.FormDestroy(Sender: TObject); begin FDropUserDialog := nil; end; function TDropUserDialog.GetCascadeObjects: Boolean; begin Result := CascadeCheckBox.Checked; end; function TDropUserDialog.Open(TableName: string): Boolean; begin MessageLabel.Caption := Format(CAPTION_TEXT, [TableName]); InfoImage.Picture.Icon.Handle := LoadIcon(0, IDI_INFORMATION); Width := Max(220, InfoImage.Width + MessageLabel.Width + 40); Result := ShowModal = mrOk; end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Compression.LZBRSF; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$rangechecks off} {$overflowchecks off} interface uses SysUtils, Classes, Math, PasVulkan.Math, PasVulkan.Types; // LZBRSF is a pure byte-wise compression algorithm, so it is pretty fast, but it doesn't compress // very well, but it is still better than nothing, and it is also very fast at decompression, so it // is a pretty good choice for games, where the compression ratio isn't that important, but only the // decompression speed. type TpvLZBRSFLevel=0..9; PpvLZBRSFLevel=^TpvLZBRSFLevel; function LZBRSFCompress(const aInData:TpvPointer;const aInLen:TpvUInt64;out aDestData:TpvPointer;out aDestLen:TpvUInt64;const aLevel:TpvLZBRSFLevel=5;const aWithSize:boolean=true):boolean; function LZBRSFDecompress(const aInData:TpvPointer;aInLen:TpvUInt64;var aDestData:TpvPointer;out aDestLen:TpvUInt64;const aOutputSize:TpvInt64=-1;const aWithSize:boolean=true):boolean; implementation function LZBRSFCompress(const aInData:TpvPointer;const aInLen:TpvUInt64;out aDestData:TpvPointer;out aDestLen:TpvUInt64;const aLevel:TpvLZBRSFLevel;const aWithSize:boolean):boolean; const HashBits=16; HashSize=1 shl HashBits; HashMask=HashSize-1; HashShift=32-HashBits; WindowSize=32768; WindowMask=WindowSize-1; MinMatch=3; MaxMatch=258; MaxOffset=TpvUInt32($7fffffff); MultiplyDeBruijnBytePosition:array[0..31] of TpvUInt8=(0,0,3,0,3,1,3,0,3,2,2,1,3,2,0,1,3,3,1,2,2,2,2,0,3,1,2,0,1,0,1,1); type PHashTable=^THashTable; THashTable=array[0..HashSize-1] of PpvUInt8; PChainTable=^TChainTable; TChainTable=array[0..WindowSize-1] of TpvPointer; PThreeBytes=^TThreeBytes; TThreeBytes=array[0..2] of TpvUInt8; PBytes=^TBytes; TBytes=array[0..$7ffffffe] of TpvUInt8; var CurrentPointer,EndPointer,EndSearchPointer,Head,CurrentPossibleMatch:PpvUInt8; BestMatchDistance,BestMatchLength,MatchLength,Step,MaxSteps, Difference,Offset,SkipStrength,UnsuccessfulFindMatchAttempts:TpvUInt32; HashTable:PHashTable; ChainTable:PChainTable; HashTableItem:PPpvUInt8; Greedy:boolean; LiteralStart:PpvUInt8; LiteralLength:TpvUInt64; AllocatedDestSize:TpvUInt64; procedure DoOutputBlock(const aData:Pointer;const aSize:TpvUInt64); begin if aSize>0 then begin if AllocatedDestSize<(aDestLen+aSize) then begin AllocatedDestSize:=(aDestLen+aSize) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; Move(aData^,PBytes(aDestData)^[aDestLen],aSize); inc(aDestLen,aSize); end; end; procedure DoOutputUInt8(const aValue:TpvUInt8); begin if AllocatedDestSize<(aDestLen+SizeOf(TpvUInt8)) then begin AllocatedDestSize:=(aDestLen+SizeOf(TpvUInt8)) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; PpvUInt8(Pointer(@PBytes(aDestData)^[aDestLen]))^:=aValue; inc(aDestLen,SizeOf(TpvUInt8)); end; procedure DoOutputUInt16(const aValue:TpvUInt16); begin {$ifdef little_endian} if AllocatedDestSize<(aDestLen+SizeOf(TpvUInt16)) then begin AllocatedDestSize:=(aDestLen+SizeOf(TpvUInt16)) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; PpvUInt16(Pointer(@PBytes(aDestData)^[aDestLen]))^:=aValue; inc(aDestLen,SizeOf(TpvUInt16)); {$else} DoOutputUInt8((aValue shr 0) and $ff); DoOutputUInt8((aValue shr 8) and $ff); {$endif} end; procedure DoOutputUInt24(const aValue:TpvUInt32); begin {$ifdef LITTLE_ENDIAN} if AllocatedDestSize<(aDestLen+SizeOf(TpvUInt16)) then begin AllocatedDestSize:=(aDestLen+SizeOf(TpvUInt16)) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; PpvUInt16(Pointer(@PBytes(aDestData)^[aDestLen]))^:=aValue and $ffff; inc(aDestLen,SizeOf(TpvUInt16)); {$else} DoOutputUInt8((aValue shr 0) and $ff); DoOutputUInt8((aValue shr 8) and $ff); {$endif} DoOutputUInt8((aValue shr 16) and $ff); end; procedure DoOutputUInt32(const aValue:TpvUInt32); begin {$ifdef LITTLE_ENDIAN} if AllocatedDestSize<(aDestLen+SizeOf(TpvUInt32)) then begin AllocatedDestSize:=(aDestLen+SizeOf(TpvUInt32)) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; PpvUInt32(Pointer(@PBytes(aDestData)^[aDestLen]))^:=aValue; inc(aDestLen,SizeOf(TpvUInt32)); {$else} DoOutputUInt8((aValue shr 0) and $ff); DoOutputUInt8((aValue shr 8) and $ff); DoOutputUInt8((aValue shr 16) and $ff); DoOutputUInt8((aValue shr 32) and $ff); {$endif} end; procedure DoOutputUInt64(const aValue:TpvUInt64); begin {$ifdef LITTLE_ENDIAN} if AllocatedDestSize<(aDestLen+SizeOf(TpvUInt64)) then begin AllocatedDestSize:=(aDestLen+SizeOf(TpvUInt64)) shl 1; ReallocMem(aDestData,AllocatedDestSize); end; PpvUInt64(Pointer(@PBytes(aDestData)^[aDestLen]))^:=aValue; inc(aDestLen,SizeOf(TpvUInt64)); {$else} DoOutputUInt8((aValue shr 0) and $ff); DoOutputUInt8((aValue shr 8) and $ff); DoOutputUInt8((aValue shr 16) and $ff); DoOutputUInt8((aValue shr 24) and $ff); DoOutputUInt8((aValue shr 32) and $ff); DoOutputUInt8((aValue shr 40) and $ff); DoOutputUInt8((aValue shr 48) and $ff); DoOutputUInt8((aValue shr 56) and $ff); {$endif} end; procedure FlushLiterals; begin if LiteralLength>0 then begin case LiteralLength of 0..59:begin DoOutputUInt8({b00}0 or ((LiteralLength-1) shl 2)); end; 60..$00000ff:begin DoOutputUInt16(({b00}0 or (60 shl 2)) or ((LiteralLength-1) shl 8)); end; $0000100..$0000ffff:begin DoOutputUInt8({b00}0 or (61 shl 2)); DoOutputUInt16(LiteralLength-1); end; $0010000..$00ffffff:begin DoOutputUInt32(({b00}0 or (62 shl 2)) or ((LiteralLength-1) shl 8)); end; else begin DoOutputUInt8({b00}0 or (63 shl 2)); DoOutputUInt32(LiteralLength-1); end; end; DoOutputBlock(LiteralStart,LiteralLength); LiteralStart:=nil; LiteralLength:=0; end; end; procedure DoOutputLiteral(const aPosition:PpvUInt8); begin if (LiteralLength=0) or ((LiteralLength>0) and ((TpvPtrUInt(LiteralStart)+LiteralLength)<>TpvPtrUInt(aPosition))) then begin if LiteralLength>0 then begin FlushLiterals; end; LiteralStart:=aPosition; end; inc(LiteralLength); end; procedure DoOutputCopy(const aDistance,aLength:TpvUInt32); begin if (TpvPtrUInt(TpvPtrUInt(CurrentPointer)-TpvPtrUInt(aInData)))=66141 then begin FlushLiterals; end; if (aDistance>0) and (aLength>1) then begin FlushLiterals; if ((aLength>3) and (aLength<12)) and (aDistance<2048) then begin // Short match DoOutputUInt16({b01} 1 or (((aLength-4) shl 2) or ((aDistance-1) shl 5))); end else if (aLength<=64) and (aDistance<65536) then begin // Medium match DoOutputUInt8({b10}2 or ((aLength-1) shl 2)); DoOutputUInt16(aDistance-1); end else begin case aLength of 0..8191:begin // Long match DoOutputUInt16({b011}3 or ((aLength-1) shl 3)); DoOutputUInt32(aDistance-1); end; else begin // Huge match DoOutputUInt8({b111}7); DoOutputUInt32(aLength-1); DoOutputUInt32(aDistance-1); end; end; end; end; end; procedure OutputStartBlock; begin end; procedure OutputEndBlock; begin FlushLiterals; DoOutputUInt8({b11111111}$ff); end; begin result:=false; AllocatedDestSize:=aInLen; if AllocatedDestSize<SizeOf(TpvUInt32) then begin AllocatedDestSize:=SizeOf(TpvUInt32); end; GetMem(aDestData,AllocatedDestSize); aDestLen:=0; try MaxSteps:=1 shl TpvInt32(aLevel); SkipStrength:=(32-9)+TpvInt32(aLevel); Greedy:=aLevel>=TpvLZBRSFLevel(1); LiteralStart:=nil; LiteralLength:=0; if aWithSize then begin DoOutputUInt64(aInLen); end; OutputStartBlock; GetMem(HashTable,SizeOf(THashTable)); try FillChar(HashTable^,SizeOf(THashTable),#0); GetMem(ChainTable,SizeOf(TChainTable)); try FillChar(ChainTable^,SizeOf(TChainTable),#0); CurrentPointer:=aInData; EndPointer:={%H-}TpvPointer(TpvPtrUInt(TpvPtrUInt(CurrentPointer)+TpvPtrUInt(aInLen))); EndSearchPointer:={%H-}TpvPointer(TpvPtrUInt((TpvPtrUInt(CurrentPointer)+TpvPtrUInt(aInLen))-TpvPtrUInt(TpvInt64(Max(TpvInt64(MinMatch),TpvInt64(SizeOf(TpvUInt32))))))); UnsuccessfulFindMatchAttempts:=TpvUInt32(1) shl SkipStrength; while {%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndSearchPointer) do begin HashTableItem:=@HashTable[((((PpvUInt32(TpvPointer(CurrentPointer))^ and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}){$if defined(FPC_BIG_ENDIAN)}shr 8{$ifend}))*TpvUInt32($1e35a7bd)) shr HashShift) and HashMask]; Head:=HashTableItem^; CurrentPossibleMatch:=Head; BestMatchDistance:=0; BestMatchLength:=1; Step:=0; while assigned(CurrentPossibleMatch) and ({%H-}TpvPtrUInt(CurrentPointer)>{%H-}TpvPtrUInt(CurrentPossibleMatch)) and (TpvPtrInt({%H-}TpvPtrUInt({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(CurrentPossibleMatch)))<TpvPtrInt(MaxOffset)) do begin Difference:=PpvUInt32(TpvPointer(@PBytes(CurrentPointer)^[0]))^ xor PpvUInt32(TpvPointer(@PBytes(CurrentPossibleMatch)^[0]))^; if (Difference and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}))=0 then begin if (BestMatchLength<=({%H-}TpvPtrUInt(EndPointer)-{%H-}TpvPtrUInt(CurrentPointer))) and (PBytes(CurrentPointer)^[BestMatchLength-1]=PBytes(CurrentPossibleMatch)^[BestMatchLength-1]) then begin MatchLength:=MinMatch; while ({%H-}TpvPtrUInt(@PBytes(CurrentPointer)^[MatchLength+(SizeOf(TpvUInt32)-1)])<{%H-}TpvPtrUInt(EndPointer)) do begin Difference:=PpvUInt32(TpvPointer(@PBytes(CurrentPointer)^[MatchLength]))^ xor PpvUInt32(TpvPointer(@PBytes(CurrentPossibleMatch)^[MatchLength]))^; if Difference=0 then begin inc(MatchLength,SizeOf(TpvUInt32)); end else begin {$if defined(FPC_BIG_ENDIAN)} if (Difference shr 16)<>0 then begin inc(MatchLength,not (Difference shr 24)); end else begin inc(MatchLength,2+(not (Difference shr 8))); end; {$else} inc(MatchLength,MultiplyDeBruijnBytePosition[TpvUInt32(TpvUInt32(Difference and (-Difference))*TpvUInt32($077cb531)) shr 27]); {$ifend} break; end; end; if BestMatchLength<MatchLength then begin BestMatchDistance:={%H-}TpvPtrUInt({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(CurrentPossibleMatch)); BestMatchLength:=MatchLength; end; end; end; inc(Step); if Step<MaxSteps then begin CurrentPossibleMatch:=ChainTable^[({%H-}TpvPtrUInt(CurrentPossibleMatch)-{%H-}TpvPtrUInt(aInData)) and WindowMask]; end else begin break; end; end; if (BestMatchDistance>0) and (BestMatchLength>1) then begin DoOutputCopy(BestMatchDistance,BestMatchLength); end else begin if SkipStrength>31 then begin DoOutputLiteral(CurrentPointer); end else begin Step:=UnsuccessfulFindMatchAttempts shr SkipStrength; Offset:=0; while (Offset<Step) and (({%H-}TpvPtrUInt(CurrentPointer)+Offset)<{%H-}TpvPtrUInt(EndSearchPointer)) do begin DoOutputLiteral(@PpvUInt8Array(CurrentPointer)^[Offset]); inc(Offset); end; BestMatchLength:=Offset; inc(UnsuccessfulFindMatchAttempts,ord(UnsuccessfulFindMatchAttempts<TpvUInt32($ffffffff)) and 1); end; end; HashTableItem^:=CurrentPointer; ChainTable^[({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(aInData)) and WindowMask]:=Head; if Greedy then begin inc(CurrentPointer); dec(BestMatchLength); while (BestMatchLength>0) and ({%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndSearchPointer)) do begin HashTableItem:=@HashTable[((((PpvUInt32(TpvPointer(CurrentPointer))^ and TpvUInt32({$if defined(FPC_BIG_ENDIAN)}$ffffff00{$else}$00ffffff{$ifend}){$if defined(FPC_BIG_ENDIAN)}shr 8{$ifend}))*TpvUInt32($1e35a7bd)) shr HashShift) and HashMask]; Head:=HashTableItem^; HashTableItem^:=CurrentPointer; ChainTable^[({%H-}TpvPtrUInt(CurrentPointer)-{%H-}TpvPtrUInt(aInData)) and WindowMask]:=Head; inc(CurrentPointer); dec(BestMatchLength); end; end; inc(CurrentPointer,BestMatchLength); end; while {%H-}TpvPtrUInt(CurrentPointer)<{%H-}TpvPtrUInt(EndPointer) do begin DoOutputLiteral(CurrentPointer); inc(CurrentPointer); end; finally FreeMem(ChainTable); end; finally FreeMem(HashTable); end; OutputEndBlock; finally if aDestLen>0 then begin ReallocMem(aDestData,aDestLen); result:=true; end else if assigned(aDestData) then begin FreeMem(aDestData); aDestData:=nil; end; end; end; function LZBRSFDecompress(const aInData:TpvPointer;aInLen:TpvUInt64;var aDestData:TpvPointer;out aDestLen:TpvUInt64;const aOutputSize:TpvInt64;const aWithSize:boolean):boolean; type TBlock1=TpvUInt8; TBlock2=TpvUInt16; TBlock3=array[0..2] of TpvUInt8; TBlock4=TpvUInt32; TBlock5=array[0..4] of TpvUInt8; TBlock6=array[0..5] of TpvUInt8; TBlock7=array[0..6] of TpvUInt8; TBlock8=TpvUInt64; TBlock16=array[0..1] of TpvUInt64; TBlock32=array[0..3] of TpvUInt64; TBlock64=array[0..7] of TpvUInt64; PBlock1=^TBlock1; PBlock2=^TBlock2; PBlock3=^TBlock3; PBlock4=^TBlock4; PBlock5=^TBlock5; PBlock6=^TBlock6; PBlock7=^TBlock7; PBlock8=^TBlock8; PBlock16=^TBlock16; PBlock32=^TBlock32; PBlock64=^TBlock64; var InputPointer,InputEnd,OutputPointer,OutputEnd,CopyFromPointer:PpvUInt8; Len,Offset,Tag:TpvUInt32; OutputSize:TpvUInt64; Allocated:boolean; begin // If the input size is too small, then exit early if (aWithSize and (aInLen<SizeOf(TpvUInt64))) or ((not aWithSize) and (aInLen=0)) then begin result:=false; exit; end; // Setup stuff InputPointer:=aInData; InputEnd:=@PpvUInt8Array(InputPointer)^[aInLen]; if aWithSize then begin OutputSize:=PpvUInt64(InputPointer)^; {$ifdef BIG_ENDIAN} OutputSize:=((OutputSize and TpvUInt64($ff00000000000000)) shr 56) or ((OutputSize and TpvUInt64($00ff000000000000)) shr 40) or ((OutputSize and TpvUInt64($0000ff0000000000)) shr 24) or ((OutputSize and TpvUInt64($000000ff00000000)) shr 8) or ((OutputSize and TpvUInt64($00000000ff000000)) shl 8) or ((OutputSize and TpvUInt64($0000000000ff0000)) shl 24) or ((OutputSize and TpvUInt64($000000000000ff00)) shl 40) or ((OutputSize and TpvUInt64($00000000000000ff)) shl 56); {$endif} inc(PpvUInt64(InputPointer)); end else begin if aOutputSize>=0 then begin OutputSize:=aOutputSize; end else begin OutputSize:=0; end; end; if OutputSize=0 then begin result:=true; exit; end; aDestLen:=OutputSize; if (aOutputSize>=0) and (aDestLen<>TpvUInt64(aOutputSize)) then begin result:=false; aDestLen:=0; exit; end; Allocated:=not assigned(aDestData); if Allocated then begin if ((not aWithSize) and (aOutputSize<=0)) or (OutputSize=0) then begin result:=false; aDestLen:=0; exit; end; GetMem(aDestData,OutputSize); end; OutputPointer:=aDestData; OutputEnd:=@PpvUInt8Array(OutputPointer)^[OutputSize]; result:=true; while TpvPtrUInt(InputPointer)<TpvPtrUInt(InputEnd) do begin Tag:=TpvUInt8(pointer(InputPointer)^); inc(InputPointer); if (TpvPtrUInt(TpvPtrUInt(OutputPointer)-TpvPtrUInt(aDestData)))=66141 then begin InputEnd:=@PpvUInt8Array(InputPointer)^[aInLen]; end; case Tag and 3 of {b00}0:begin // Literal(s) case Tag shr 2 of 0..59:begin Len:=(Tag shr 2)+1; end; 60:begin if TpvPtrUInt(InputPointer)>=TpvPtrUInt(InputEnd) then begin result:=false; break; end; Len:=TpvUInt8(Pointer(InputPointer)^)+1; inc(InputPointer); end; 61:begin if (TpvPtrUInt(InputPointer)+SizeOf(TpvUInt16))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; {$ifdef LITTLE_ENDIAN} Len:=TpvUInt16(Pointer(InputPointer)^)+1; inc(InputPointer,SizeOf(TpvUInt16)); {$else} Len:=TpvUInt16(Pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt16)); Len:=((((Len and $ff00) shr 8) or ((Len and $ff) shl 8))+1; {$endif} end; 62:begin if (TpvPtrUInt(InputPointer)+(SizeOf(TpvUInt16)+SizeOf(TpvUInt8)))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; {$ifdef LITTLE_ENDIAN} Len:=TpvUInt16(Pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt16)); Len:=(Len or (TpvUInt8(pointer(InputPointer)^) shl 16))+1; inc(InputPointer); {$else} Len:=TpvUInt8(pointer(InputPointer)^); inc(InputPointer); Len:=(Len or (TpvUInt8(pointer(InputPointer)^) shl 8)); inc(InputPointer); Len:=(Len or (TpvUInt8(pointer(InputPointer)^) shl 16))+1; inc(InputPointer); {$endif} end; else {63:}begin if (TpvPtrUInt(InputPointer)+SizeOf(TpvUInt32))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; {$ifdef LITTLE_ENDIAN} Len:=TpvUInt32(pointer(InputPointer)^)+1; inc(InputPointer,SizeOf(TpvUInt32)); {$else} Len:=TpvUInt32(pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt32)); Len:=(((Len and TpvUInt32($ff000000)) shr 24) or ((Len and TpvUInt32($00ff0000)) shr 8) or ((Len and TpvUInt32($0000ff00)) shl 8) or ((Len and TpvUInt32($000000ff)) shl 24))+1; {$endif} end; end; CopyFromPointer:=InputPointer; inc(InputPointer,Len); end; {b01}1:begin // Short match if TpvPtrUInt(InputPointer)>=TpvPtrUInt(InputEnd) then begin result:=false; break; end; Len:=((Tag shr 2) and 7)+4; Offset:=((Tag shr 5) or (TpvUInt8(pointer(InputPointer)^) shl 3))+1; inc(InputPointer); CopyFromPointer:=pointer(TpvPtrUInt(TpvPtrUInt(OutputPointer)-TpvPtrUInt(Offset))); if TpvPtrUInt(CopyFromPointer)<TpvPtrUInt(aDestData) then begin result:=false; break; end; end; {b10}2:begin // Medium match if (TpvPtrUInt(InputPointer)+SizeOf(TpvUInt16))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; Len:=(Tag shr 2)+1; {$ifdef LITTLE_ENDIAN} Offset:=TpvUInt16(pointer(InputPointer)^)+1; inc(InputPointer,SizeOf(TpvUInt16)); {$else} Offset:=TpvUInt16(Pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt16)); Offset:=((((Offset and $ff00) shr 8) or ((Offset and $ff) shl 8))+1; {$endif} CopyFromPointer:=pointer(TpvPtrUInt(TpvPtrUInt(OutputPointer)-TpvPtrUInt(Offset))); if TpvPtrUInt(CopyFromPointer)<TpvPtrUInt(aDestData) then begin result:=false; break; end; end; else {b11}{3:}begin if Tag=$ff then begin // End code break; end else if (Tag and 4)<>0 then begin // {b111}7 - Huge match if (TpvPtrUInt(InputPointer)+(SizeOf(TpvUInt32)+SizeOf(TpvUInt32)))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; Len:=TpvUInt32(pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt32)); Offset:=TpvUInt32(pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt32)); {$ifdef BIG_ENDIAN} Len:=((Len and TpvUInt32($ff000000)) shr 24) or ((Len and TpvUInt32($00ff0000)) shr 8) or ((Len and TpvUInt32($0000ff00)) shl 8) or ((Len and TpvUInt32($000000ff)) shl 24); Offset:=((Offset and TpvUInt32($ff000000)) shr 24) or ((Offset and TpvUInt32($00ff0000)) shr 8) or ((Offset and TpvUInt32($0000ff00)) shl 8) or ((Offset and TpvUInt32($000000ff)) shl 24); {$endif} inc(Len); inc(Offset); end else begin // {b011}3 - Long match if (TpvPtrUInt(InputPointer)+(SizeOf(TpvUInt8)+SizeOf(TpvUInt32)))>TpvPtrUInt(InputEnd) then begin result:=false; break; end; Len:=((Tag shr 3) or (TpvUInt8(pointer(InputPointer)^) shl (8-3)))+1; inc(InputPointer,SizeOf(TpvUInt8)); Offset:=TpvUInt32(pointer(InputPointer)^); inc(InputPointer,SizeOf(TpvUInt32)); {$ifdef BIG_ENDIAN} Offset:=((Offset and TpvUInt32($ff000000)) shr 24) or ((Offset and TpvUInt32($00ff0000)) shr 8) or ((Offset and TpvUInt32($0000ff00)) shl 8) or ((Offset and TpvUInt32($000000ff)) shl 24); {$endif} inc(Offset); end; CopyFromPointer:=pointer(TpvPtrUInt(TpvPtrUInt(OutputPointer)-TpvPtrUInt(Offset))); if TpvPtrUInt(CopyFromPointer)<TpvPtrUInt(aDestData) then begin result:=false; break; end; end; end; if (TpvPtrUInt(OutputPointer)+TpvPtrUInt(Len))>TpvPtrUInt(OutputEnd) then begin result:=false; break; end; if (TpvPtrUInt(CopyFromPointer)<TpvPtrUInt(OutputPointer)) and (TpvPtrUInt(OutputPointer)<(TpvPtrUInt(CopyFromPointer)+TpvPtrUInt(Len))) then begin // Overlapping while Len>0 do begin OutputPointer^:=CopyFromPointer^; inc(OutputPointer); inc(CopyFromPointer); dec(Len); end; end else begin // Non-overlapping if Len>SizeOf(TBlock8) then begin while Len>=SizeOf(TBlock64) do begin PBlock64(pointer(OutputPointer))^:=PBlock64(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock64)); inc(CopyFromPointer,SizeOf(TBlock64)); dec(Len,SizeOf(TBlock64)); end; while Len>=SizeOf(TBlock32) do begin PBlock32(pointer(OutputPointer))^:=PBlock32(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock32)); inc(CopyFromPointer,SizeOf(TBlock32)); dec(Len,SizeOf(TBlock32)); end; while Len>=SizeOf(TBlock16) do begin PBlock16(pointer(OutputPointer))^:=PBlock16(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock16)); inc(CopyFromPointer,SizeOf(TBlock16)); dec(Len,SizeOf(TBlock16)); end; while Len>=SizeOf(TBlock8) do begin PBlock8(pointer(OutputPointer))^:=PBlock8(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock8)); inc(CopyFromPointer,SizeOf(TBlock8)); dec(Len,SizeOf(TBlock8)); end; end; case Len of 0:begin // Do nothing in this case end; 1:begin PBlock1(pointer(OutputPointer))^:=PBlock1(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock1)); end; 2:begin PBlock2(pointer(OutputPointer))^:=PBlock2(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock2)); end; 3:begin PBlock3(pointer(OutputPointer))^:=PBlock3(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock3)); end; 4:begin PBlock4(pointer(OutputPointer))^:=PBlock4(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock4)); end; 5:begin PBlock5(pointer(OutputPointer))^:=PBlock5(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock5)); end; 6:begin PBlock6(pointer(OutputPointer))^:=PBlock6(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock6)); end; 7:begin PBlock7(pointer(OutputPointer))^:=PBlock7(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock7)); end; 8:begin PBlock8(pointer(OutputPointer))^:=PBlock8(pointer(CopyFromPointer))^; inc(OutputPointer,SizeOf(TBlock8)); end; else begin Assert(false); end; end; end; end; OutputSize:=TpvPtrUInt(TpvPtrUInt(OutputPointer)-TpvPtrUInt(aDestData)); if (not aWithSize) and (aOutputSize<0) then begin aDestLen:=OutputSize; end; if not (result and (aDestLen=OutputSize)) then begin result:=false; aDestLen:=0; if Allocated then begin FreeMem(aDestData); aDestData:=nil; end; end; end; initialization end.
unit Timerpnl; { This unit is a generic base class designed to have various things descended from it. Therefore, it really is useless as is. All it attempts to be is a generic 3D panel with a timer attached to it. This timer can be used to do various things. Descendants include a flashing alarm indicator and a panel clock. Author: Gary D. Foster Date: 11/6/95 Change Log: * 11/10/95 -- Gary D. Foster Published ParentShowHint, TabOrder, TabStop, and OnEnter properties. Changed 'Interval' property to 'ClockInterval' * 11/9/95 -- Gary D. Foster Moved SetEnabled and SetClockInterval procedures from private to protected status and added 'virtual'. * 11/16/95 -- Gary D. Foster The TimerPanel now dynamically creates and destroys the underlying ClockDriver (TTimer) object during the SetEnabled procedure. It takes care of storing a pointer to the original OnTimer event if you set one, so the children don't need to worry about this. This should make it considerably more resource friendly. * 12/4/95 -- Gary D. Foster Changed FClockInterval from an Integer to a Word. } interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Menus; type TTimerPanel = class(TCustomPanel) private FClockInterval: Word; FClockEnabled: Boolean; FTimerEvent: TNotifyEvent; protected ClockDriver: TTimer; procedure SetClockEnabled(Value: Boolean); virtual; procedure SetClockInterval(Value: Word); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Align; property Alignment; property BevelInner; property BevelOuter; property BevelWidth; property BorderWidth; property BorderStyle; property DragCursor; property DragMode; property Color; property Ctl3D; property Font; property Locked; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property ClockInterval: Word read FClockInterval write SetClockInterval; property Enabled: Boolean read FClockEnabled write SetClockEnabled default True; end; implementation procedure TTimerPanel.SetClockInterval(Value: Word); begin FClockInterval := Value; if Enabled then ClockDriver.Interval := FClockInterval; end; procedure TTimerPanel.SetClockEnabled(Value: Boolean); begin If Value = FClockEnabled then exit; if Value then begin ClockDriver := TTimer.Create(Self); ClockDriver.Interval := FClockInterval; FClockEnabled := True; ClockDriver.Enabled := True; ClockDriver.OnTimer := FTimerEvent; end else begin FClockEnabled := False; FTimerEvent := ClockDriver.OnTimer; ClockDriver.Free; end; end; constructor TTimerPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FTimerEvent := nil; SetClockInterval(1000); SetClockEnabled(true); end; destructor TTimerPanel.Destroy; begin SetClockEnabled(False); inherited Destroy; end; end.
unit SecurityUtilityUnit; {Jennifer Gallegos @ 8/3/2017} {Utility routines for Stock pricing data stored in a TDataSet.} interface uses System.Classes, System.Generics.Collections, System.SysUtils, Data.DB, DataSnap.DBClient; type TTickerCnt = array of record Tkr: String; Cnt : Integer; end; TSecuritiesUtility = class (TObject) private fldTicker : string; fldTrxDate : string; fldOpen, fldClose : string; fldHigh, fldLow : string; fldVolume : string; securitiesDataInt : TClientDataSet; function GetSecuritiesData: TClientDataSet; public constructor Create(flds : Array of String); property SecuritiesData : TClientDataSet read GetSecuritiesData; procedure LoadFields(flds : Array of String); function LoadDataSetfromCSV(csvString : string): boolean; function AverageValue(ds : TDataSet; fldAvg : string): Extended; function MonthlyAverageValue(ticker : string; startDt, endDt : TDateTime) : TList; function MaxDailyProfit(ticker : string) : TList; function BusyDay(ticker : string; thresholdPct : extended): TList; function BiggestLoser: TList; end; implementation { SecuritiesUtility } {Create SecuritiesUtility by passing the fields needed to create the dataset. If fields are unknown at the time of creation, use LoadFields method. LoadFields could be called to load the headers when the data is imported. @param flds - fields names in order of the expected data import flds are expected in this order: ticker,date,open,close,high,low,volume} constructor TSecuritiesUtility.Create(flds : Array of String); begin inherited Create; securitiesDataInt := TClientDataSet.Create(nil); if Length(flds) <> 0 then LoadFields(flds); end; {if field names were not available at Creation, use LoadFields to initialize. Most likely to be done from headers when importing the data. @param flds - Field Names in order of the expected data import. flds are expected in this order: ticker,date,open,close,high,low,volume} procedure TSecuritiesUtility.LoadFields(flds : Array of String); begin if SecuritiesData.Active or (SecuritiesData.FieldDefs.Count > 0) then begin SecuritiesData.Close; SecuritiesData.FieldDefs.Clear; end; fldTicker := flds[0]; fldTrxDate := flds[1]; fldOpen := flds[2]; fldClose := flds[3]; fldHigh := flds[4]; fldLow := flds[5]; fldVolume := flds[6]; SecuritiesData.FieldDefs.Add(fldTicker,ftString,10,true); SecuritiesData.FieldDefs.Add(fldTrxDate,ftDate,0,true); SecuritiesData.FieldDefs.Add(fldOpen,ftExtended,0,false); SecuritiesData.FieldDefs.Add(fldClose,ftExtended,0,false); SecuritiesData.FieldDefs.Add(fldHigh,ftExtended,0,false); SecuritiesData.FieldDefs.Add(fldLow,ftExtended,0,false); SecuritiesData.FieldDefs.Add(fldVolume,ftExtended,0,false); end; {@return - SecuritiesData TClientDataSet} function TSecuritiesUtility.GetSecuritiesData: TClientDataSet; begin Result := securitiesDataInt; end; {Loads data from the string into an internal TClientDataSet @Param data - expected format for data is a csv converted to a string. The first line of the csv should contain headers. } function TSecuritiesUtility.LoadDataSetfromCSV(csvString : string): boolean; var dataList, itemList : TStringList; year, month, day : string; i, j : integer; begin dataList := TStringList.Create; dataList.Delimiter := #$A; dataList.DelimitedText := csvString; if not SecuritiesData.Active then SecuritiesData.CreateDataSet else SecuritiesData.EmptyDataSet; itemList := TStringList.Create; //init SecuritiesData with values from csvString for i := 1 to dataList.Count-1 do begin //headers have already been loaded, skip them SecuritiesData.Append; itemList.DelimitedText := dataList[i]; for j := 0 to itemList.Count-1 do begin if SecuritiesData.FieldDefs[j].DataType = ftDate then begin //date values come in as yyyy-mm-dd year := Copy(itemList[j],0,itemList[j].IndexOf('-')); month := Copy(itemList[j],itemList[j].IndexOf('-')+2,2); day := Copy(itemList[j],itemList[j].LastIndexOf('-')+2,2); SecuritiesData.Fields[j].AsString := month+'/'+day+'/'+year; end else SecuritiesData.Fields[j].AsString := itemList[j]; end; SecuritiesData.Post; end; end; {Returns the average value (mean) of all the fields in the fldAvg column @param ds - DataSet of values to be averaged @param fldAvg - Field Name for the mean calculation @result - mean of all fldAvg values } function TSecuritiesUtility.AverageValue(ds: TDataSet; fldAvg: string): Extended; var sum : extended; begin if (not ds.Active) or (ds.RecordCount <= 0) then raise Exception.Create('No data to calculate average.'); sum := 0; ds.First; while not ds.Eof do begin sum := sum + ds.FieldByName(fldAvg).AsExtended; ds.Next; end; Result := sum/ds.RecordCount; end; {Returns the average monthly close and open prices for each month within the given date range for the requested ticker within SecuritiesData. Average value will only be returned for each month in the data, so if a partial month is sent, only the average for this partial month will be returned. SecuritiesData can be filtered if a smaller set of data is required. @param ticker - the security ticker symbol requested @param startDt - start date for the monthly average @param endDt - end date for the monthly average @result - returns a TList in the following format for each unique ticker/month: ticker,'month:'month,'average_open:'averageOpen,'average_close:'averageClose returns nil if there is no data or the dataset is not active} function TSecuritiesUtility.MonthlyAverageValue(ticker : string; startDt, endDt : TDateTime) : TList; var saveFilter : string; curMonth, curYear, endMonth, endYear, day : word; ix : integer; begin if SecuritiesData.Filtered then saveFilter := SecuritiesData.Filter; SecuritiesData.Filtered := False; SecuritiesData.Filter := 'ticker='+QuotedStr(ticker); SecuritiesData.Filtered := True; //Exit method of no data is found for requested ticker if (not SecuritiesData.Active) or (SecuritiesData.RecordCount <= 0) or (startDt > endDt) then begin Result := nil; exit; end; Result := TList.Create; try DecodeDate(endDt, endYear, endMonth, day); DecodeDate(startDt, curYear, curMonth, day); while (curYear <= endYear) and (curMonth <= endMonth) do begin SecuritiesData.Filtered := False; //filter - calculate only using the requested Month and date range SecuritiesData.Filter := '(ticker='+QuotedStr(ticker)+')' +' and (Year(date)='+curYear.ToString+')' +' and (Month(date)='+curMonth.ToString+')' +' and (date>='+QuotedStr(DateToStr(startDt))+')' +' and (date<='+QuotedStr(DateToStr(endDt))+')'; SecuritiesData.Filtered := True; SecuritiesData.First; if SecuritiesData.RecordCount > 0 then begin //Load Return Result data ix := Result.Add(TStringList.Create); TStringList(Result[ix]).add( SecuritiesData.FieldByName(fldTicker).AsString); TStringList(Result[ix]).add( 'month:'+curYear.ToString+'-'+Format('%.2d',[curMonth])); TStringList(Result[ix]).add( 'average_open:'+Format('%.2f',[AverageValue(SecuritiesData,fldOpen)])); TStringList(Result[ix]).add( 'average_close:'+Format('%.2f',[AverageValue(SecuritiesData,fldClose)])); end; //increment the month and year curMonth := curMonth + 1; if curMonth > 12 then begin curYear := curYear + 1; curMonth := 1; end; end; //while months exist within range finally //if no data was found within the month range requested, return nil if Result.Count <= 0 then Result := nil; // re-attach the original filter if saveFilter > '' then begin SecuritiesData.Filtered := False; SecuritiesData.Filter := saveFilter; SecuritiesData.Filtered := True; end else begin SecuritiesData.Filter := ''; SecuritiesData.Filtered := false; end; end; end; {Returns the day where the difference between the low price and high price provides the greatest profit. SecuritiesData can be filtered if a smaller set of data is required. @param ticker - the security ticker symbol requested @result - returns a TList in the following format for the largest profit found: ticker,'date:'profitDate,'profit:'profitValue returns nil if there is no data or the dataset is not active} function TSecuritiesUtility.MaxDailyProfit(ticker : string) : TList; var curDif, profit : extended; proDate : TDateTime; proTick : string; ix : integer; savefilter : string; begin if SecuritiesData.Filtered then saveFilter := SecuritiesData.Filter; SecuritiesData.Filtered := False; SecuritiesData.Filter := 'ticker='+QuotedStr(ticker); SecuritiesData.Filtered := True; //Exit method of no data is found for requested ticker if (not SecuritiesData.Active) or (SecuritiesData.RecordCount <= 0) then begin Result := nil; exit; end; Result := TList.Create; SecuritiesData.First; profit := 0; curDif := 0; while not SecuritiesData.Eof do begin curDif := SecuritiesData.FieldByName(fldHigh).AsExtended - SecuritiesData.FieldByName(fldLow).AsExtended; //profit is always the largest positive difference between high and low if profit < curDif then begin profit := curDif; proTick := SecuritiesData.FieldByName(fldTicker).AsString; proDate := SecuritiesData.FieldByName(fldTrxDate).AsDateTime; end; SecuritiesData.Next; end; //Load Return Result data ix := Result.Add(TStringList.Create); TStringList(Result[ix]).add(proTick); TStringList(Result[ix]).add('date:'+FormatDateTime('mm/dd/yyyy',proDate)); TStringList(Result[ix]).add('profit:'+profit.ToString); //if no data was found within the month range requested, return nil if Result.Count <= 0 then Result := nil; // re-attach the original filter if saveFilter > '' then begin SecuritiesData.Filtered := False; SecuritiesData.Filter := saveFilter; SecuritiesData.Filtered := True; end else begin SecuritiesData.Filter := ''; SecuritiesData.Filtered := false; end; end; {Returns the days where the volume is more than thresholdPct higher than the data's average volume for a single security ticker code. Also returns the total average volume value calculated. A negative threshold will return all volumes greater than a percentage less than the average volume. For example, -5 will return all volumes greater than 95% of the average volume. SecuritiesData can be filtered if a smaller set of data is required. @param ticker - the security ticker symbol requested @param thresholdPct - the percentage that determines the cutoff for the list of volumes returned. This value is in percent format, so if requesting all volumes greater than 10% of the average, enter 10. @result - returns a TList in the following format for the volumes found: ticker,'date:'volumeDate,'volume:'volumeValue,'average_volume:'avgVolume returns nil if there is no data or the dataset is not active} function TSecuritiesUtility.BusyDay(ticker : string; thresholdPct: extended): TList; var ix : integer; avgVolume, avgVolumePct, sum : extended; savefilter : string; begin if SecuritiesData.Filtered then saveFilter := SecuritiesData.Filter; SecuritiesData.Filtered := False; SecuritiesData.Filter := 'ticker='+QuotedStr(ticker); SecuritiesData.Filtered := True; //Exit method of no data is found for requested ticker if (not SecuritiesData.Active) or (SecuritiesData.RecordCount <= 0) then begin Result := nil; exit; end; Result := TList.Create; sum := 0; SecuritiesData.First; //calculate the overall average volume and thresholdPct more than average while not SecuritiesData.Eof do begin sum := sum + SecuritiesData.FieldByName(fldVolume).AsExtended; SecuritiesData.Next; end; avgVolume := sum / SecuritiesData.RecordCount; avgVolumePct := avgVolume*(1+thresholdPct/100); SecuritiesData.First; while not SecuritiesData.Eof do begin if SecuritiesData.FieldByName(fldVolume).AsExtended > avgVolumePct then begin //Load Return Result data ix := Result.Add(TStringList.Create); TStringList(Result[ix]).add(SecuritiesData.FieldByName(fldTicker).AsString); TStringList(Result[ix]).add('date:'+SecuritiesData.FieldByName(fldTrxDate).AsString); TStringList(Result[ix]).add('volume:'+SecuritiesData.FieldByName(fldVolume).AsString); TStringList(Result[ix]).add(//'average_volume:'+avgVolume.ToString); 'average_volume:'+Format('%.2f',[avgVolume])); end; SecuritiesData.Next; end; //if no data was found, return nil if Result.Count <= 0 then Result := nil; // re-attach the original filter if saveFilter > '' then begin SecuritiesData.Filtered := False; SecuritiesData.Filter := saveFilter; SecuritiesData.Filtered := True; end else begin SecuritiesData.Filter := ''; SecuritiesData.Filtered := false; end; end; {Returns the security ticker that has the most days where the closing price is less than the opening price. Also returns the total number of losing days. SecuritiesData can be filtered if a smaller set of data is required. @result - returns a TList in the following format for the loser found: ticker,'days:'totalLosingDays returns nil if there is no data or the dataset is not active} function TSecuritiesUtility.BiggestLoser: TList; var losers : TTickerCnt; tkr : string; tkrIx, lasti, maxi, i : integer; worstVal, worstIx, ix : integer; begin //Exit method of no data is found for requested ticker if (not SecuritiesData.Active) or (SecuritiesData.RecordCount <= 0) then begin Result := nil; exit; end; Result := TList.Create; SetLength(losers,1000); lasti := 0; maxi := 0; SecuritiesData.First; while not SecuritiesData.Eof do begin tkr := SecuritiesData.FieldByName(fldTicker).AsString; //always point to the correct ticker for incrementing if losers[lasti].Tkr <> tkr then begin tkrIx := low (losers); while (tkrIx <= maxi) and (losers [tkrIx].Tkr <> tkr) do Inc(tkrIx); if (tkrIx > maxi) then begin maxi := tkrIx; losers[tkrIx].Tkr := tkr; end; lasti := tkrIx; end else tkrIx := lasti; //per ticker, increment count when close price is less than open price if SecuritiesData.FieldByName(fldClose).AsExtended < SecuritiesData.FieldByName(fldOpen).AsExtended then Inc(losers[tkrIx].Cnt); SecuritiesData.Next; end; worstVal := 0; worstIx := 0; //locate the ticker with the highest count (most days where close < open) for i := low(losers) to high(losers) do begin if worstVal < losers[i].cnt then begin worstVal := losers[i].cnt; worstIx := i; end; end; //Load Return Result data ix := Result.Add(TStringList.Create); TStringList(Result[ix]).add(losers[worstIx].Tkr); TStringList(Result[ix]).add('days:'+IntToStr(losers[worstIx].Cnt)); end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Abbrevia * * The Initial Developer of the Original Code is * Robert Love * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit AbZipKitTests; interface uses TestFrameWork,abTestFrameWork,AbZipKit,SysUtils,Classes,abMeter; type TAbZipKitTests = class(TabCompTestCase) private Component : TAbZipKit; protected procedure SetUp; override; procedure TearDown; override; published procedure TestDefaultStreaming; procedure TestComponentLinks; end; implementation { TAbZipKitTests } procedure TAbZipKitTests.SetUp; begin inherited; Component := TAbZipKit.Create(TestForm); end; procedure TAbZipKitTests.TearDown; begin inherited; end; procedure TAbZipKitTests.TestComponentLinks; var MLink1,MLink2,MLink3 : TAbVCLMeterLink; begin MLink1 := TAbVCLMeterLink.Create(TestForm); MLink2 := TAbVCLMeterLink.Create(TestForm); MLink3 := TAbVCLMeterLink.Create(TestForm); Component.ArchiveProgressMeter := MLink1; Component.ItemProgressMeter := MLink2; Component.ArchiveSaveProgressMeter := MLink3; MLink1.Free; MLink2.Free; MLink3.Free; Check(Component.ArchiveProgressMeter = nil,'Notification does not work for TAbZipKit.ArchiveProgressMeter'); Check(Component.ItemProgressMeter = nil,'Notification does not work for TAbZipKit.ItemProgressMeter'); Check(Component.ArchiveSaveProgressMeter = nil,'Notification does not work for TAbZipKit.ArchiveSaveProgressMeter'); end; procedure TAbZipKitTests.TestDefaultStreaming; var CompStr : STring; CompTest : TAbZipKit; begin RegisterClass(TAbZipKit); CompStr := StreamComponent(Component); CompTest := (UnStreamComponent(CompStr) as TAbZipKit); CompareComponentProps(Component,CompTest); UnRegisterClass(TAbZipKit); end; initialization TestFramework.RegisterTest('Abbrevia.Component Level Test Suite', TAbZipKitTests.Suite); end.
unit uXML; interface uses uInterfaces, Variants, uOSMCommon, uModule, SysUtils, Classes, SAX, SAXHelpers, SAXMS; type TMyXMLReader = class(TSAXMSXMLReader) public procedure setContentHandler(const handler: IContentHandler); override; function getContentHandler(): IContentHandler; override; end; TOSMReader = class(TOSManObject, ITransformInputStream, IMapWriter) protected inStreamAdaptor: TInputStreamAdaptor; fSAXReader: TMyXMLReader; fSAXError: WideString; //IMap oMap: OleVariant; function get_eos: WordBool; public destructor destroy; override; published //IInputStream function read(const maxBufSize: integer): OleVariant; property eos: WordBool read get_eos; //ITransformInputStream procedure setInputStream(const inStream: OleVariant); //IMapWriter procedure setOutputMap(const outMap: OleVariant); end; implementation uses Math, ConvUtils; const osmReaderClassGUID: TGUID = '{1028B33B-C674-47F7-B032-4ADDF4B695D4}'; osmWriterClassGUID: TGUID = '{8DB21D39-DC59-49B8-B22B-43CBC064271F}'; osmFastWriterClassGUID: TGUID = '{73D595DA-2EDB-4A6F-8370-30E0834E2D63}'; type TBaseHandler = class(TDefaultHandler) protected fParent: IContentHandler; fReader: TOSMReader; fNestedCount: integer; fOnDone: TNotifyEvent; procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; procedure endElement(const uri, localName, qName: SAXString); override; procedure doOnDone(); virtual; procedure fatalError(const e: ISAXParseError); override; procedure raiseError(const msg: WideString); procedure raiseInvalidTag(const tag: WideString); public constructor create(reader: TOSMReader); reintroduce; virtual; destructor destroy; override; procedure init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil);virtual; end; TDocHandler = class(TBaseHandler) protected procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; procedure endElement(const uri, localName, qName: SAXString); override; end; TDeleteHandler = class(TBaseHandler) protected procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; end; TMapObjHandler = class(TBaseHandler) protected //IMapObject mapObj: OleVariant; //IKeyList objTags: OleVariant; procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; function readObjAttributes(atts: IAttributes):boolean; virtual; public constructor create(reader: TOSMReader); override; procedure init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil);override; end; TOSCHandler = class(TBaseHandler) protected procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; end; TOSMHandler = class(TBaseHandler) protected fNodeHandler,fWayHandler,fRelationHandler:TMapObjHandler; procedure freeHandlers(); //TMapObjHandler.onDone event handler procedure onDoneAdd(sender: TObject); procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; procedure endElement(const uri, localName, qName: SAXString); override; public constructor create(reader: TOSMReader); override; destructor destroy();override; end; TNodeHandler = class(TMapObjHandler) protected function readObjAttributes(atts: IAttributes):boolean; override; public procedure init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil);override; end; TWayHandler = class(TMapObjHandler) protected ndList: array of int64; ndCount: integer; procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; procedure endElement(const uri, localName, qName: SAXString); override; procedure grow(); public procedure init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil);override; end; TRelationHandler = class(TMapObjHandler) protected //IRefList fRefList: OleVariant; procedure startElement(const uri, localName, qName: SAXString; const atts: IAttributes); override; public procedure init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil);override; end; TUTF8Writer = class(TOSManObject, ITransformOutputStream) private //transfrom UTF16 strings into UFT8 byteArray variant stream protected oStream: OleVariant; fBuf: array[Word] of byte; fNextAvail: integer; fEOS: boolean; constructor create(); override; destructor destroy(); override; function quote(const ws: WideString): WideString; procedure flush(); procedure CRLF(); procedure writeUTF8(pc:PAnsiChar;l:integer);overload; procedure writeUTF8(const s:UTF8String);overload; procedure writeUTF16(pc:PWideChar);overload; procedure writeUTF16(const w: WideString);overload; procedure writeLineUTF16(const w: WideString); procedure writeLineUTF8(const s: UTF8String; const indent: integer = 0); published //aBuf - unicode string variant procedure write(const aBuf: OleVariant); procedure set_eos(const aEOS: WordBool);virtual; function get_eos: WordBool; //set pipelined output stream procedure setOutputStream(const outStream: OleVariant); //write "true" if all data stored and stream should release system resources //once set to "true" no write oprerations allowed on stream property eos: WordBool read get_eos write set_eos; end; TOSMWriter = class(TUTF8Writer, IMapReader) protected inMap: Variant; fShouldWriteHeader: boolean; function getObjAtts(const mapObject: OleVariant): UTF8String; procedure writeHeader(); procedure writeFooter(); procedure writeNode(const node: OleVariant); procedure writeWay(const way: OleVariant); procedure writeRelation(const relation: OleVariant); procedure writeTags(const tagsArray: OleVariant); public constructor create(); override; published //Map for storing results procedure setInputMap(const inputMap: OleVariant); //Write data from map to outStream in OSM-XML format //aBuf can hold exporting options. List of available options see in Map.getObjects procedure write(const exportOptions: OleVariant); procedure set_eos(const aEOS: WordBool);override; end; TFastOSMWriter = class(TUTF8Writer, IMapReader) protected inMap,inStg: Variant; procedure writeHeader(); procedure writeNodes(); procedure writeWays(); procedure writeRelations(); procedure writeFooter(); published //Map for storing results procedure setInputMap(const inputMap: OleVariant); //Write data from map to outStream in OSM-XML format //no filtering supported procedure write(const dummy: OleVariant); procedure set_eos(const aEOS: WordBool);override; end; { TOSMReader } destructor TOSMReader.destroy; begin if assigned(inStreamAdaptor) then FreeAndNil(inStreamAdaptor); oMap := Unassigned; inherited; end; function TOSMReader.get_eos: WordBool; begin result := assigned(inStreamAdaptor) and inStreamAdaptor.eos; end; function TOSMReader.read(const maxBufSize: integer): OleVariant; begin fSAXReader := nil; fSAXError := ''; try try fSAXReader := TMyXMLReader.create(); fSAXReader.setContentHandler(TDocHandler.create(self)); fSAXReader.ParseInput(TStreamInputSource.create(inStreamAdaptor, soReference)); finally if assigned(fSAXReader) then FreeAndNil(fSAXReader); end; except on e: Exception do begin if fSAXError <> '' then begin raise ESAXException.create(fSAXError); end else begin raise; end; end; end; end; procedure TOSMReader.setInputStream(const inStream: OleVariant); begin if assigned(inStreamAdaptor) then raise EInOutError.create(toString() + ': input stream already assigned'); inStreamAdaptor := TInputStreamAdaptor.create(inStream); end; procedure TOSMReader.setOutputMap(const outMap: OleVariant); begin if VarIsType(oMap, varDispatch) then raise EInOutError.create(toString() + ': output map already assigned'); oMap := outMap; end; { TBaseHandler } constructor TBaseHandler.create(reader: TOSMReader); begin fReader := reader; end; destructor TBaseHandler.destroy; begin fParent := nil; fReader := nil; inherited; end; procedure TBaseHandler.doOnDone; begin if assigned(fOnDone) then fOnDone(self); end; procedure TBaseHandler.endElement(const uri, localName, qName: SAXString); begin dec(fNestedCount); if fNestedCount = 0 then begin try doOnDone(); finally fReader.fSAXReader.setContentHandler(fParent); fParent.endElement(uri, localName, qName); end; end; end; procedure TBaseHandler.fatalError(const e: ISAXParseError); begin fReader.fSAXError := e.getMessage(); end; procedure TBaseHandler.init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent); begin fParent := fReader.fSAXReader.getContentHandler(); fNestedCount := 1; fOnDone := onDone; fReader.fSAXReader.setContentHandler(self); end; procedure TBaseHandler.raiseError(const msg: WideString); begin fReader.fSAXError := msg; raise ESAXParseException.create(msg); end; procedure TBaseHandler.raiseInvalidTag(const tag: WideString); begin raiseError(ClassName() + ': invalid <' + tag + '> tag'); end; procedure TBaseHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inc(fNestedCount); end; { TMyXMLReader } function TMyXMLReader.getContentHandler: IContentHandler; begin result := inherited getContentHandler(); end; procedure TMyXMLReader.setContentHandler(const handler: IContentHandler); begin inherited; end; { TDocHandler } procedure TDocHandler.endElement(const uri, localName, qName: SAXString); begin //block parent ContextHandler end; procedure TDocHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inherited; if qName = 'osm' then TOSMHandler.create(fReader).init(uri, localName, qName, atts) else if qName = 'osmChange' then TOSCHandler.create(fReader).init(uri, localName, qName, atts) else raiseError('TDocHandler.startElement: unexpected element <' + qName + '>'); end; { TOSMHandler } constructor TOSMHandler.create(reader: TOSMReader); begin inherited; fNodeHandler:=TNodeHandler.create(reader); fWayHandler:=TWayHandler.create(reader); fRelationHandler:=TRelationHandler.create(reader); fNodeHandler._AddRef(); fWayHandler._AddRef(); fRelationHandler._AddRef(); end; destructor TOSMHandler.destroy; begin freeHandlers(); inherited; end; procedure TOSMHandler.endElement(const uri, localName, qName: SAXString); begin inherited; if(fNestedCount=0)then freeHandlers(); end; procedure TOSMHandler.freeHandlers; begin if(assigned(fNodeHandler))then fNodeHandler._Release(); if(assigned(fWayHandler))then fWayHandler._Release(); if(assigned(fRelationHandler))then fRelationHandler._Release(); fNodeHandler:=nil; fWayHandler:=nil; fRelationHandler:=nil; end; procedure TOSMHandler.onDoneAdd(sender: TObject); var mo: TMapObjHandler; begin mo := sender as TMapObjHandler; if VarIsType(mo.mapObj,varDispatch)then fReader.oMap.putObject(mo.mapObj); end; procedure TOSMHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inherited; if qName = 'node' then fNodeHandler.init(uri, localName, qName, atts, onDoneAdd) else if qName = 'way' then fWayHandler.init(uri, localName, qName, atts, onDoneAdd) else if qName = 'relation' then fRelationHandler.init(uri, localName, qName, atts, onDoneAdd) else if (qName = 'bound') or (qName = 'bounds') or (qName='changeset') then begin TBaseHandler.create(fReader).init(uri, localName, qName, atts); end else raiseInvalidTag(qName); end; { TMapObjHandler } constructor TMapObjHandler.create(reader: TOSMReader); begin inherited; end; procedure TMapObjHandler.init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent = nil); begin inherited; objTags := Unassigned; readObjAttributes(atts); end; function TMapObjHandler.readObjAttributes(atts: IAttributes):boolean; function readDef(const aName, defVal: WideString): WideString; begin result := atts.getValue(aName); if result = '' then begin result := defVal; end; end; begin result:=(atts.getValue('visible')<>'false')and(atts.getValue('action')<>'delete'); if not result then begin mapObj:=Unassigned; exit; end; mapObj.id := WideStrToInt64(atts.getValue('id')); mapObj.version := WideStrToInt(readDef('version', '0')); mapObj.userId := WideStrToInt(readDef('uid', '0')); mapObj.userName := atts.getValue('user'); mapObj.changeset := WideStrToInt64(readDef('changeset', '0')); mapObj.timestamp := atts.getValue('timestamp'); end; procedure TMapObjHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inherited; if qName <> 'tag' then exit; if VarIsEmpty(objTags) then begin objTags := mapObj.tags; end; objTags.setByKey(atts.getValue('k'), atts.getValue('v')); end; { TNodeHandler } procedure TNodeHandler.init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent); begin mapObj := fReader.oMap.createNode(); inherited; end; function TNodeHandler.readObjAttributes(atts: IAttributes):boolean; begin result:=inherited readObjAttributes(atts); if result then begin mapObj.lat := StrToFloat(atts.getValue('lat')); mapObj.lon := StrToFloat(atts.getValue('lon')); end; end; { TWayHandler } procedure TWayHandler.endElement(const uri, localName, qName: SAXString); var v: Variant; i: integer; pv: PVarData; begin if (fNestedCount = 1) and (ndCount > 0) then begin v := VarArrayCreate([0, ndCount - 1], varVariant); pv := VarArrayLock(v); try for i := 0 to ndCount - 1 do begin pv.VType := varInt64; pv.VInt64 := ndList[i]; inc(pv); end; finally VarArrayUnlock(v); end; mapObj.nodes := v; end; inherited; end; procedure TWayHandler.grow; begin if ndCount >= length(ndList) then begin setLength(ndList, ndCount * 2); end; end; procedure TWayHandler.init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent); begin mapObj := fReader.oMap.createWay(); inherited; ndCount := 0; setLength(ndList, 14); end; procedure TWayHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); var i64: int64; begin inherited; if qName <> 'nd' then exit; i64 := StrToInt64(atts.getValue('ref')); inc(ndCount); grow(); ndList[ndCount - 1] := i64; end; { TRelationHandler } procedure TRelationHandler.init(const uri, localName, qName: SAXString; const atts: IAttributes; onDone: TNotifyEvent); begin mapObj := fReader.oMap.createRelation(); inherited; fRefList := Unassigned; readObjAttributes(atts); end; procedure TRelationHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inherited; if qName <> 'member' then exit; if VarIsEmpty(fRefList) then fRefList := mapObj.members; fRefList.insertBefore(maxInt, atts.getValue('type'), StrToInt64(atts.getValue('ref')), atts.getValue('role')); end; { TOSCHandler } procedure TOSCHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); begin inherited; if (qName = 'modify') or (qName = 'create') then TOSMHandler.create(fReader).init(uri, localName, qName, atts) else if qName = 'delete' then TDeleteHandler.create(fReader).init(uri, localName, qName, atts) else raiseInvalidTag(qName); end; { TDeleteHandler } procedure TDeleteHandler.startElement(const uri, localName, qName: SAXString; const atts: IAttributes); var id: int64; begin inherited; if fNestedCount > 2 then //ignore tags,references,members exit; id := WideStrToInt64(atts.getValue('id')); if qName = 'node' then fReader.oMap.deleteNode(id) else if qName = 'way' then fReader.oMap.deleteWay(id) else if qName = 'relation' then fReader.oMap.deleteRelation(id) else raiseInvalidTag(qName); end; { TOSMWriter } constructor TOSMWriter.create; begin inherited; fShouldWriteHeader := true; end; function TOSMWriter.getObjAtts(const mapObject: OleVariant): UTF8String; var i64:int64; begin i64:=mapObject.id; result := 'id="' + IntToStr(i64) + '" version="' + IntToStr(mapObject.version) + '" timestamp="' + mapObject.timestamp + '" uid="' + IntToStr(mapObject.userId) + '" user="' + UTF8Encode(quote(mapObject.userName)) + '" changeset="' + IntToStr(mapObject.changeset) + '"'; end; procedure TOSMWriter.setInputMap(const inputMap: OleVariant); begin varCopyNoInd(inMap, inputMap); end; procedure TOSMWriter.set_eos(const aEOS: WordBool); begin if (not eos) and aEOS then begin writeFooter(); end; inherited set_eos(aEOS); end; procedure TOSMWriter.write(const exportOptions: OleVariant); var //IQueryResult allObjects: OleVariant; //IMapObject mo: OleVariant; pv: POleVariant; s: WideString; l: integer; begin if not VarIsType(oStream, varDispatch) then raise EInOutError.create(toString() + '.write: out stream not assigned'); if not VarIsType(inMap, varDispatch) then raise EInOutError.create(toString() + '.write: input map not assigned'); if fShouldWriteHeader then writeHeader(); fShouldWriteHeader := false; allObjects := inMap.getObjects(exportOptions); while not allObjects.eos do begin mo := allObjects.read(1000); if not VarIsArray(mo) or (VarArrayDimCount(mo) <> 1) then raise EInOutError.create(toString() + '.write: result of Map.getObjects.Read is not array'); l := varArrayLength(mo); pv := VarArrayLock(mo); try while (l > 0) do begin if not VarIsType(pv^, varDispatch) then begin if not allObjects.eos then raise EInOutError.create(toString() + '.write: unexpected result of Map.getObjects.Read') else begin eos := true; break; end; end; s := pv^.getClassName; if s = 'Node' then writeNode(pv^) else if s = 'Way' then writeWay(pv^) else if s = 'Relation' then writeRelation(pv^) else raise EInOutError.create(toString() + '.write: illegal object type <' + s + '>'); inc(pv); dec(l); end; finally VarArrayUnlock(mo); end; end; eos := true; end; procedure TOSMWriter.writeFooter; begin writeLineUTF8('</osm>'); end; procedure TOSMWriter.writeHeader; begin writeLineUTF8('<?xml version="1.0" encoding="UTF-8" ?>'); writeLineUTF8('<osm version="0.6" generator="Osman ' + getClassName() + '">'); end; procedure TOSMWriter.writeNode(const node: OleVariant); var s: UTF8String; v: OleVariant; begin s := '<node '+getObjAtts(node)+' lat="' + degToStr(node.lat) + '" lon="' + degToStr(node.lon) + '"'; v := node.tags.getAll; if (VarArrayDimCount(v) = 1) and (varArrayLength(v) > 0) then begin //object has tags writeLineUTF8(s + '>', 1); writeTags(v); writeLineUTF8('</node>', 1); end else begin writeLineUTF8(s + '/>', 1); end; end; procedure TOSMWriter.writeRelation(const relation: OleVariant); var s: UTF8String; t, m: OleVariant; pv, pv1, pv2: PVarData; emptyRelation: boolean; i: integer; i64: int64; begin s := '<relation ' + getObjAtts(relation); t := relation.tags.getAll; m := relation.members.getAll; emptyRelation := true; if not VarIsType(m, varArray or varVariant) then raise EInOutError.create(toString() + '.writeRelation: invalid member ref'); if (VarArrayDimCount(t) = 1) and (varArrayLength(t) > 0) then begin //object has tags if emptyRelation then begin writeLineUTF8(s + '>', 1); emptyRelation := false; end; writeTags(t); end; if (VarArrayDimCount(m) = 1) and (VarArrayLength(m)> 0) then begin //write members i := VarArrayLength(m); if (i mod 3) <> 0 then raise EInOutError.create(toString() + '.writeRelation: invalid member count'); if emptyRelation then begin emptyRelation := false; writeLineUTF8(s + '>', 1); end; pv := VarArrayLock(m); try pv1 := pv; inc(pv1); pv2 := pv; inc(pv2, 2); while i > 0 do begin i64 := PVariant(pv1)^; writeLineUTF8('<member type="' + PVariant(pv)^ + '" ref="' + IntToStr(i64) + '" role="' + UTF8Encode(quote(PVariant(pv2)^)) + '"/>', 2); inc(pv, 3); inc(pv1, 3); inc(pv2, 3); dec(i, 3); end; finally VarArrayUnlock(m); end; end; if emptyRelation then writeLineUTF8(s + '/>') else writeLineUTF8('</relation>', 1); end; procedure TOSMWriter.writeTags(const tagsArray: OleVariant); var pv, pk: PVariant; n: integer; begin n := VarArrayLength(tagsArray) div 2; pk := VarArrayLock(tagsArray); pv := pk; inc(pv); try while n > 0 do begin writeLineUTF8('<tag k="' + UTF8Encode(quote(pk^)) + '" v="' + UTF8Encode(quote(pv^)) + '"/>', 2); dec(n); inc(pk, 2); inc(pv, 2); end; finally VarArrayUnlock(tagsArray); end; end; procedure TOSMWriter.writeWay(const way: OleVariant); var s: UTF8String; t, n: OleVariant; pv: PVarData; emptyWay: boolean; i: integer; i64: int64; begin s := '<way ' + getObjAtts(way); t := way.tags.getAll; n := way.nodes; emptyWay := true; if not VarIsType(n, varArray or varVariant) then raise EInOutError.create(toString() + '.writeWay: invalid node ref'); if (VarArrayDimCount(t) = 1) and (varArrayLength(t) > 0) then begin //object has tags emptyWay:=false; writeLineUTF8(s + '>', 1); writeTags(t); end; if (VarArrayDimCount(n) = 1) and (varArrayLength(n) > 0) then begin if emptyWay then begin emptyWay := false; writeLineUTF8(s + '>', 1); end; i := varArrayLength(n); pv := VarArrayLock(n); try while i > 0 do begin i64 := PVariant(pv)^; writeLineUTF8('<nd ref="' + IntToStr(i64) + '"/>', 2); inc(pv); dec(i); end; finally VarArrayUnlock(n); end; end; if emptyWay then writeLineUTF8(s + '/>') else writeLineUTF8('</way>', 1); end; { TUTF8Writer } constructor TUTF8Writer.create; begin inherited; fEOS := true; end; destructor TUTF8Writer.destroy; begin eos := true; inherited; end; procedure TUTF8Writer.flush; var v: OleVariant; p: PByte; begin if not VarIsType(oStream, varDispatch) then raise EInOutError.create(toString() + '.flush: out stream not assigned'); v := VarArrayCreate([0, fNextAvail - 1], varByte); p := VarArrayLock(v); try move(fBuf, p^, fNextAvail); finally VarArrayUnlock(v); end; oStream.write(v); fNextAvail := 0; end; function TUTF8Writer.get_eos: WordBool; begin result := fEOS; end; procedure TUTF8Writer.set_eos(const aEOS: WordBool); begin if (not eos) and aEOS then begin flush(); end; fEOS := eos or aEOS; if VarIsType(oStream, varDispatch) then oStream.eos := fEOS; end; procedure TUTF8Writer.setOutputStream(const outStream: OleVariant); begin if VarIsType(oStream, varDispatch) then flush(); oStream := outStream; fEOS := outStream.eos; end; procedure TUTF8Writer.write(const aBuf: OleVariant); var p: PVarData; begin p := @aBuf; while (p.VType and varByRef) <> 0 do p := p.VPointer; if (p.VType = varOleStr) then begin writeLineUTF16(p.VOleStr); end else begin writeLineUTF16(aBuf); end; end; procedure TUTF8Writer.writeLineUTF16(const w: WideString); begin writeUTF16(w); CRLF(); end; procedure TUTF8Writer.writeLineUTF8(const s: UTF8String; const indent: integer); var pb: PByte; i, l: integer; begin pb := @fBuf[fNextAvail]; l := indent * 2; while l > 0 do begin i := sizeof(fBuf) - fNextAvail; if (i > l) then i := l; fillchar(pb^, i, ' '); inc(fNextAvail, i); inc(pb, i); dec(l, i); if (fNextAvail = sizeof(fBuf)) then begin flush(); pb := @fBuf[0]; end; end; writeUTF8(PAnsiChar(s), length(s)); CRLF(); end; procedure TUTF8Writer.CRLF(); begin if((fNextAvail+2)>sizeOf(fBuf)) then flush(); fBuf[fNextAvail] := 13; inc(fNextAvail); fBuf[fNextAvail] := 10; inc(fNextAvail); if (fNextAvail >= sizeof(fBuf)) then flush(); end; procedure TUTF8Writer.writeUTF8(pc: PAnsiChar; l: integer); var i: integer; pb: PByte; begin pb:=@fBuf[fNextAvail]; while l > 0 do begin i := sizeof(fBuf) - fNextAvail; if (i > l) then i := l; move(pc^, pb^, i); inc(fNextAvail, i); inc(pc, i); inc(pb, i); dec(l, i); if (fNextAvail = sizeof(fBuf)) then begin flush(); pb := @fBuf[0]; end; end; end; procedure TUTF8Writer.writeUTF16(pc: PWideChar); var cnt: integer; begin if(fNextAvail*2>=sizeOf(fBuf)) then flush(); cnt := UnicodeToUtf8(@fBuf[fNextAvail], pc,sizeof(fBuf) - fNextAvail); if (cnt + fNextAvail) >= sizeof(fBuf) then begin flush(); cnt := UnicodeToUtf8(@fBuf[fNextAvail], pc, sizeof(fBuf) - fNextAvail); if (cnt + fNextAvail) >= sizeof(fBuf) then raise EConvertError.create(toString() + '.writeUTF16: too long string'); end; inc(fNextAvail, cnt - 1); end; procedure TUTF8Writer.writeUTF8(const s: UTF8String); begin writeUTF8(pAnsiChar(s),length(s)); end; procedure TUTF8Writer.writeUTF16(const w: WideString); begin writeUTF16(pWideChar(w)); end; function TUTF8Writer.quote(const ws: WideString): WideString; //As stated in http://www.w3.org/TR/2008/REC-xml-20081126/#syntax // & < > ' " should be quoted const amp: WideString = '&amp;'; lt: WideString = '&lt;'; gt: WideString = '&gt;'; apos: WideString = '&apos;'; quot: WideString = '&quot;'; var ol, nl, i: integer; pwc, pwc1: PWideChar; begin result := ''; ol := length(ws); if ol = 0 then exit; nl := ol; pwc := PWideChar(ws); for i := 1 to ol do begin case pwc^ of '&': inc(nl, length(amp) - 1); '<': inc(nl, length(lt) - 1); '>': inc(nl, length(gt) - 1); '''': inc(nl, length(apos) - 1); '"': inc(nl, length(quot) - 1); end; inc(pwc); end; if nl = ol then begin result := ws; exit; end; setLength(result, nl); pwc := PWideChar(ws); pwc1 := PWideChar(result); for i := 1 to ol do begin case pwc^ of '&': begin move(amp[1], pwc1^, length(amp) * sizeof(WideChar)); inc(pwc1, length(amp) - 1); end; '<': begin move(lt[1], pwc1^, length(lt) * sizeof(WideChar)); inc(pwc1, length(lt) - 1); end; '>': begin move(gt[1], pwc1^, length(gt) * sizeof(WideChar)); inc(pwc1, length(gt) - 1); end; '''': begin move(apos[1], pwc1^, length(apos) * sizeof(WideChar)); inc(pwc1, length(apos) - 1); end; '"': begin move(quot[1], pwc1^, length(quot) * sizeof(WideChar)); inc(pwc1, length(quot) - 1); end; else pwc1^ := pwc^; end; inc(pwc); inc(pwc1); end; end; { TFastOSMWriter } procedure TFastOSMWriter.set_eos(const aEOS: WordBool); begin inherited; end; procedure TFastOSMWriter.setInputMap(const inputMap: OleVariant); begin if(varIsType(inputMap,varDispatch)) then begin varCopyNoInd(inMap,inputMap); end else inMap:=0; end; procedure TFastOSMWriter.write(const dummy: OleVariant); begin if not VarIsType(oStream, varDispatch) then raise EInOutError.create(toString() + '.write: out stream not assigned'); if not VarIsType(inMap, varDispatch) or not VarIsType(inMap.storage, varDispatch) then raise EInOutError.create(toString() + '.write: input map not assigned'); inStg:=inMap.storage; try writeHeader(); writeNodes(); writeWays(); writeRelations(); writeFooter(); finally inStg:=0; eos:=true; end; end; procedure TFastOSMWriter.writeHeader; begin writeLineUTF8('<?xml version="1.0" encoding="UTF-8" ?>'); writeUTF8('<osm version="0.6" generator="Osman '); writeUTF16( getClassName()); writeLineUTF8('">'); end; procedure TFastOSMWriter.writeNodes; function coordFromVar(i32:integer):UTF8String; var l:integer; begin result:=inttostr(abs(i32)); l:=length(result); case l of 1:result:='0.000000'+result; 2:result:='0.00000'+result; 3:result:='0.0000'+result; 4:result:='0.000'+result; 5:result:='0.00'+result; 6:result:='0.0'+result; 7:result:='0.'+result; else result:=copy(result,1,l-7)+'.'+copy(result,l-7+1,7) end; if(i32<0)then result:='-'+result; end; var qAtt,qTgs,sAtt,sTgs,aAtt,aTgs:Variant; pV,pVt:PVariant; n,l:integer; i64:int64; hasTags:boolean; ws:WideString; begin if(cDegToInt<>10000000)then raise EConvertError.Create('cDegToInt changed, so fix coordFromVar routine'); qAtt:=inStg.sqlPrepare('SELECT nodes.id,version,timestamp,userid,users.name,changeset,lat,lon FROM nodes,users WHERE nodes.userid=users.id'); qTgs:=inStg.sqlPrepare('SELECT tagname,tagvalue FROM objtags,tags WHERE :id*4+0=objid AND tagid=tags.id'); sAtt:=inStg.sqlExec(qAtt,0,0); while not sAtt.eos do begin aAtt:=sAtt.read(100); if (not varIsArray(aAtt))or(VarArrayDimCount(aAtt)<>1) then raise EConvertError.Create(toString()+'.writeNodes: unexpected attribute array'); n:=varArrayLength(aAtt) div 8; pV:=VarArrayLock(aAtt); pVt:=nil; try while(n>0)do begin dec(n); writeUTF8(' <node id="'); i64:=pV^; writeUTF8(inttostr(i64)+'" version="'); inc(pV); writeUTF8(inttostr(pV^)+'" timestamp="'); inc(pV); if VarIsType(pV^,varOleStr)then begin ws:=pV^; if (length(ws)<>length('20001010230023'))then writeUTF16(ws) else writeUTF16(timeStampToWideString(WideStrToInt64(ws))); end else writeUTF16(timeStampToWideString(pV^)); inc(pV); writeUTF8('" uid="'+inttostr(pV^)+'" user="'); inc(pV); writeUTF16(quote(pV^)); inc(pV); writeUTF8('" changeset="'+inttostr(pV^)+'" lat="'); inc(pV); writeUTF8(coordFromVar(pV^)+'" lon="'); inc(pV); writeUTF8(coordFromVar(pV^)+'"'); inc(pV); hasTags:=false; sTgs:=inStg.sqlExec(qTgs,':id',i64); while not sTgs.eos do begin aTgs:=sTgs.read(30); if (not varIsArray(aTgs))or(VarArrayDimCount(aTgs)<>1) then raise EConvertError.Create(toString()+'.writeNodes: unexpected tags array'); l:=varArrayLength(aTgs) div 2; if(not hasTags) then begin hasTags:=true; writeLineUTF8('>'); end; pVt:=varArrayLock(aTgs); while(l>0)do begin dec(l); writeUTF8(' <tag k="'); writeUTF16(quote(pVt^)); inc(pVt); writeUTF8('" v="'); writeUTF16(quote(pVt^)); inc(pVt); writeLineUTF8('"/>'); end; varArrayUnlock(aTgs); pVt:=nil; end; if(hasTags)then writeLineUTF8(' </node>') else writeLineUTF8('/>'); end; finally if assigned(pVt) then varArrayUnlock(aTgs); varArrayUnlock(aAtt); end; end; end; procedure TFastOSMWriter.writeRelations; var qAtt,qTgs,qMembers,sAtt,sTgs,aAtt,aTgs:Variant; pV,pVt:PVariant; n,l:integer; i64:int64; ws:WideString; hasTags:boolean; begin qAtt:=inStg.sqlPrepare('SELECT relations.id,version,timestamp,userid,users.name,changeset FROM relations,users WHERE relations.userid=users.id'); qTgs:=inStg.sqlPrepare('SELECT tagname,tagvalue FROM objtags,tags WHERE :id*4+2=objid AND tagid=tags.id'); qMembers:=inStg.sqlPrepare('SELECT memberidxtype & 3,memberid, memberrole FROM relationmembers WHERE relationid=:id ORDER BY memberidxtype'); sAtt:=inStg.sqlExec(qAtt,0,0); while not sAtt.eos do begin aAtt:=sAtt.read(100); if (not varIsArray(aAtt))or(VarArrayDimCount(aAtt)<>1) then raise EConvertError.Create(toString()+'.writeRelations: unexpected attribute array'); n:=varArrayLength(aAtt) div 6; pV:=VarArrayLock(aAtt); pVt:=nil; try while(n>0)do begin dec(n); writeUTF8(' <relation id="'); i64:=pV^; writeUTF8(inttostr(i64)+'" version="'); inc(pV); writeUTF8(inttostr(pV^)+'" timestamp="'); inc(pV); if VarIsType(pV^,varOleStr)then begin ws:=pV^; if (length(ws)<>length('20001010230023'))then writeUTF16(ws) else writeUTF16(timeStampToWideString(WideStrToInt64(ws))); end else writeUTF16(timeStampToWideString(pV^)); inc(pV); writeUTF8('" uid="'+inttostr(pV^)+'" user="'); inc(pV); writeUTF16(quote(pV^)); inc(pV); writeUTF8('" changeset="'+inttostr(pV^)+'"'); inc(pV); hasTags:=false; sTgs:=inStg.sqlExec(qTgs,':id',i64); while not sTgs.eos do begin aTgs:=sTgs.read(30); if (not varIsArray(aTgs))or(VarArrayDimCount(aTgs)<>1) then raise EConvertError.Create(toString()+'.writeRelations: unexpected tags array'); l:=varArrayLength(aTgs) div 2; if(not hasTags) then begin hasTags:=true; writeLineUTF8('>'); end; pVt:=varArrayLock(aTgs); while(l>0)do begin dec(l); writeUTF8(' <tag k="'); writeUTF16(quote(pVt^)); inc(pVt); writeUTF8('" v="'); writeUTF16(quote(pVt^)); inc(pVt); writeLineUTF8('"/>'); end; varArrayUnlock(aTgs); pVt:=nil; end; sTgs:=inStg.sqlExec(qMembers,':id',i64); while not sTgs.eos do begin aTgs:=sTgs.read(30); if (not varIsArray(aTgs))or(VarArrayDimCount(aTgs)<>1) then raise EConvertError.Create(toString()+'.writeRelations: unexpected members array'); l:=varArrayLength(aTgs) div 3; if(not hasTags) then begin hasTags:=true; writeLineUTF8('>'); end; pVt:=varArrayLock(aTgs); while(l>0)do begin dec(l); i64:=pVt^; case i64 of 0:writeUTF8(' <member type="node" ref="'); 1:writeUTF8(' <member type="way" ref="'); 2:writeUTF8(' <member type="relation" ref="'); end; inc(pVt); i64:=pVt^; writeUTF8(inttostr(i64)+'" role="'); inc(pVt); writeUTF16(quote(pVt^)); writeLineUTF8('"/>'); inc(pVt); end; varArrayUnlock(aTgs); pVt:=nil; end; if(hasTags)then writeLineUTF8(' </relation>') else writeLineUTF8('/>'); end; finally if assigned(pVt) then varArrayUnlock(aTgs); varArrayUnlock(aAtt); end; end; end; procedure TFastOSMWriter.writeWays; var qAtt,qTgs,qNodes,sAtt,sTgs,aAtt,aTgs:Variant; pV,pVt:PVariant; n,l:integer; i64:int64; ws:WideString; hasTags:boolean; begin qAtt:=inStg.sqlPrepare('SELECT ways.id,version,timestamp,userid,users.name,changeset FROM ways,users WHERE ways.userid=users.id'); qTgs:=inStg.sqlPrepare('SELECT tagname,tagvalue FROM objtags,tags WHERE :id*4+1=objid AND tagid=tags.id'); qNodes:=inStg.sqlPrepare('SELECT nodeid FROM waynodes WHERE wayid=:id ORDER BY nodeidx'); sAtt:=inStg.sqlExec(qAtt,0,0); while not sAtt.eos do begin aAtt:=sAtt.read(100); if (not varIsArray(aAtt))or(VarArrayDimCount(aAtt)<>1) then raise EConvertError.Create(toString()+'.writeWays: unexpected attribute array'); n:=varArrayLength(aAtt) div 6; pV:=VarArrayLock(aAtt); pVt:=nil; try while(n>0)do begin dec(n); writeUTF8(' <way id="'); i64:=pV^; writeUTF8(inttostr(i64)+'" version="'); inc(pV); writeUTF8(inttostr(pV^)+'" timestamp="'); inc(pV); if VarIsType(pV^,varOleStr)then begin ws:=pV^; if (length(ws)<>length('20001010230023'))then writeUTF16(ws) else writeUTF16(timeStampToWideString(WideStrToInt64(ws))); end else writeUTF16(timeStampToWideString(pV^)); inc(pV); writeUTF8('" uid="'+inttostr(pV^)+'" user="'); inc(pV); writeUTF16(quote(pV^)); inc(pV); writeUTF8('" changeset="'+inttostr(pV^)+'"'); inc(pV); hasTags:=false; sTgs:=inStg.sqlExec(qTgs,':id',i64); while not sTgs.eos do begin aTgs:=sTgs.read(30); if (not varIsArray(aTgs))or(VarArrayDimCount(aTgs)<>1) then raise EConvertError.Create(toString()+'.writeWays: unexpected tags array'); l:=varArrayLength(aTgs) div 2; if(not hasTags) then begin hasTags:=true; writeLineUTF8('>'); end; pVt:=varArrayLock(aTgs); while(l>0)do begin dec(l); writeUTF8(' <tag k="'); writeUTF16(quote(pVt^)); inc(pVt); writeUTF8('" v="'); writeUTF16(quote(pVt^)); inc(pVt); writeLineUTF8('"/>'); end; varArrayUnlock(aTgs); pVt:=nil; end; sTgs:=inStg.sqlExec(qNodes,':id',i64); while not sTgs.eos do begin aTgs:=sTgs.read(30); if (not varIsArray(aTgs))or(VarArrayDimCount(aTgs)<>1) then raise EConvertError.Create(toString()+'.writeWays: unexpected nodes array'); l:=varArrayLength(aTgs); if(not hasTags) then begin hasTags:=true; writeLineUTF8('>'); end; pVt:=varArrayLock(aTgs); while(l>0)do begin dec(l); i64:=pVt^; writeLineUTF8(' <nd ref="'+inttostr(i64)+'"/>'); inc(pVt); end; varArrayUnlock(aTgs); pVt:=nil; end; if(hasTags)then writeLineUTF8(' </way>') else writeLineUTF8('/>'); end; finally if assigned(pVt) then varArrayUnlock(aTgs); varArrayUnlock(aAtt); end; end; end; procedure TFastOSMWriter.writeFooter; begin writeLineUTF8('</osm>'); end; initialization uModule.OSManRegister(TOSMReader, osmReaderClassGUID); uModule.OSManRegister(TOSMWriter, osmWriterClassGUID); uModule.OSManRegister(TFastOSMWriter,osmFastWriterClassGUID); end.
{ Copyright 2019 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2023-04-20 Darian Miller: Unit created - for enhancing ProcessExecutor } unit iaRTL.EnvironmentVariables.Windows; interface uses System.Classes; /// <summary> /// Note: the caller is responsible to call FreeMem on result /// </summar> function CreateEnvironmentBlock(const aEnvironmentList:TStrings):PChar; function GetEnvironmentVariables(const aDestinationList:TStrings):Boolean; implementation uses System.SysUtils, WinAPI.Windows; function CreateEnvironmentBlock(const aEnvironmentList:TStrings):PChar; begin Result := PChar(StringReplace(aEnvironmentList.Text, #13#10, #0, [rfReplaceAll])); //+#0 on the end end; function GetEnvironmentVariables(const aDestinationList:TStrings):Boolean; var StringsPtr, VarPtr:PChar; EnvVar:string; begin StringsPtr := GetEnvironmentStrings; if StringsPtr^ = #0 then Exit(False); Result := True; try VarPtr := StringsPtr; while VarPtr^ <> #0 do begin EnvVar := StrPas(VarPtr); if not EnvVar.StartsWith('=') then // Don't allow invalid/funky names ("=::=::\") begin aDestinationList.Add(EnvVar); end; Inc(VarPtr, StrLen(VarPtr) + 1); end; finally FreeEnvironmentStrings(StringsPtr); end; end; end.
unit orm.Generics.Collections; interface uses System.SysUtils, System.Classes, System.StrUtils, System.DateUtils, System.TypInfo, System.Generics.Collections, System.Generics.Defaults; type TList<T> = Class(System.Generics.Collections.TList<T>) private FFilter : TPredicate<T>; FIndexOfIndex : Integer; FIndexOfPredicate : TPredicate<T>; FIndexOfFunc : TFunc<T,Variant,Boolean>; function DoIndexOfPredicate(Value : TPredicate<T>; V : T) : Boolean; function DoIndexOfFunc(Value : TFunc<T,Variant,Boolean>; A : T; B : Variant) : Boolean; public property Filter : TPredicate<T> Read FFilter Write FFilter; property IndexOfIndex : Integer Read FIndexOfIndex; property IndexOfPredicate : TPredicate<T> Read FIndexOfPredicate Write FIndexOfPredicate; property IndexOfFunc : TFunc<T,Variant,Boolean> Read FIndexOfFunc Write FIndexOfFunc; function IndexOf(var Index : Integer; AIndexOf : TPredicate<T>; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(AIndexOf : TPredicate<T>; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(var Index : Integer; AIndexOf : TFunc<T,Variant,Boolean>; Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(var Index : Integer; Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; type TEnumerator = class(TEnumerator<T>) private FList : TList<T>; FIndex : Integer; FPredicate : TPredicate<T>; protected function DoGetCurrent: T; override; function DoMoveNext: Boolean; override; function DoPredicate(Value : T) : Boolean; public Constructor Create(AList: TList<T>; APredicate : TPredicate<T>); end; function GetEnumerator: TEnumerator; reintroduce; end; TObjectList<T: Class> = Class(System.Generics.Collections.TObjectList<T>) private FFilter : TPredicate<T>; FIndexOfIndex : Integer; FIndexOfPredicate : TPredicate<T>; FIndexOfFunc : TFunc<T,Variant,Boolean>; function DoIndexOfPredicate(Value : TPredicate<T>; V : T) : Boolean; function DoIndexOfFunc(Value : TFunc<T,Variant,Boolean>; A : T; B : Variant) : Boolean; public property Filter : TPredicate<T> Read FFilter Write FFilter; property IndexOfIndex : Integer Read FIndexOfIndex; property IndexOfPredicate : TPredicate<T> Read FIndexOfPredicate Write FIndexOfPredicate; property IndexOfFunc : TFunc<T,Variant,Boolean> Read FIndexOfFunc Write FIndexOfFunc; function IndexOf(var Index : Integer; AIndexOf : TPredicate<T>; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(AIndexOf : TPredicate<T>; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(var Index : Integer; AIndexOf : TFunc<T,Variant,Boolean>; Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(var Index : Integer; Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; function IndexOf(Value : Variant; StartIndex : Integer = 0; IsFiltered : Boolean = True) : Boolean; Overload; procedure AddRange(AList : TObjectList<T>; IsFree : Boolean); Overload; type TEnumerator = class(TEnumerator<T>) private FList : TObjectList<T>; FIndex : Integer; FPredicate : TPredicate<T>; protected function DoGetCurrent: T; override; function DoMoveNext: Boolean; override; function DoPredicate(Value : T) : Boolean; public Constructor Create(AList: TObjectList<T>; APredicate : TPredicate<T>); end; function GetEnumerator: TEnumerator; reintroduce; End; implementation { TList<T> } constructor TList<T>.TEnumerator.Create(AList: TList<T>; APredicate: TPredicate<T>); begin inherited Create; FList := AList; FIndex := -1; FPredicate := APredicate; end; function TList<T>.TEnumerator.DoGetCurrent: T; begin Result := FList[FIndex]; end; function TList<T>.TEnumerator.DoMoveNext: Boolean; begin If FIndex >= FList.Count Then Exit(False); If not Assigned(FPredicate) Then Inc(FIndex) Else Begin Repeat Inc(FIndex); Until (FIndex >= FList.Count) Or DoPredicate(FList[FIndex]); End; Result := FIndex < FList.Count; end; function TList<T>.TEnumerator.DoPredicate(Value: T): Boolean; begin Result := True; If Assigned(FPredicate) Then Result := FPredicate(Value); end; { TObjectList<T> } function TList<T>.DoIndexOfFunc(Value : TFunc<T,Variant,Boolean>; A: T; B: Variant): Boolean; begin Result := True; If Assigned(Value) Then Result := Value(A,B); end; function TList<T>.DoIndexOfPredicate(Value : TPredicate<T>; V: T): Boolean; begin Result := True; If Assigned(Value) Then Result := Value(V); end; function TList<T>.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self,FFilter); end; function TList<T>.IndexOf(var Index: Integer; AIndexOf: TFunc<T, Variant, Boolean>; Value : Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; var I : Integer; V : T; begin Result := False; Index := -1; If IsFiltered Then Begin For V in Self Do If DoIndexOfFunc(AIndexOf,V,Value) Then Begin Index := GetEnumerator.FIndex; Exit(True); End; End Else Begin For I := 0 To (Self.Count - 1) Do If DoIndexOfFunc(AIndexOf,Self[I],Value) Then Begin Index := I; Exit(True); End; End; end; function TList<T>.IndexOf(StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,FIndexOfPredicate,StartIndex,IsFiltered); end; function TList<T>.IndexOf(var Index: Integer; AIndexOf : TPredicate<T>; StartIndex : Integer; IsFiltered : Boolean): Boolean; var I : Integer; V : T; begin Result := False; Index := -1; If IsFiltered Then Begin For V in Self Do If DoIndexOfPredicate(AIndexOf,V) Then Begin Index := GetEnumerator.FIndex; Exit(True); End; End Else Begin For I := 0 To (Self.Count - 1) Do If DoIndexOfPredicate(AIndexOf,Self[I]) Then Begin Index := I; Exit(True); End; End; end; { TObjectList<T> } procedure TObjectList<T>.AddRange(AList : TObjectList<T>; IsFree: Boolean); var I : Integer; begin I := 0; While (AList.Count > I) Do Begin If AList.Filter(AList[I]) Then Self.Add(AList.Extract(AList[I])) Else Inc(I); End; AList.TrimExcess; AList.Pack; If IsFree Then FreeAndNil(AList); end; function TObjectList<T>.DoIndexOfFunc(Value: TFunc<T, Variant, Boolean>; A: T; B: Variant): Boolean; begin Result := True; If Assigned(Value) Then Result := Value(A,B); end; function TObjectList<T>.DoIndexOfPredicate(Value: TPredicate<T>; V: T): Boolean; begin Result := True; If Assigned(Value) Then Result := Value(V); end; function TObjectList<T>.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self,FFilter); end; function TObjectList<T>.IndexOf(AIndexOf: TPredicate<T>; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,AIndexOf,StartIndex,IsFiltered); end; function TObjectList<T>.IndexOf(var Index: Integer; AIndexOf: TPredicate<T>; StartIndex: Integer; IsFiltered: Boolean): Boolean; var I : Integer; V : T; begin Result := False; Index := -1; If IsFiltered Then Begin For V in Self Do If DoIndexOfPredicate(AIndexOf,V) Then Begin Index := GetEnumerator.FIndex; Exit(True); End; End Else Begin For I := 0 To (Self.Count - 1) Do If DoIndexOfPredicate(AIndexOf,Self[I]) Then Begin Index := I; Exit(True); End; End; end; function TObjectList<T>.IndexOf(var Index: Integer; Value: Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(Index,FIndexOfFunc,Value,StartIndex,IsFiltered); end; function TObjectList<T>.IndexOf(Value: Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,FIndexOfFunc,Value,StartIndex,IsFiltered); end; function TObjectList<T>.IndexOf(StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,FIndexOfPredicate,StartIndex,IsFiltered); end; function TObjectList<T>.IndexOf(var Index: Integer; AIndexOf: TFunc<T, Variant, Boolean>; Value: Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; var I : Integer; V : T; begin Result := False; Index := -1; If IsFiltered Then Begin For V in Self Do If DoIndexOfFunc(AIndexOf,V,Value) Then Begin Index := GetEnumerator.FIndex; Exit(True); End; End Else Begin For I := 0 To (Self.Count - 1) Do If DoIndexOfFunc(AIndexOf,Self[I],Value) Then Begin Index := I; Exit(True); End; End; end; { TObjectList<T>.TEnumerator } constructor TObjectList<T>.TEnumerator.Create(AList: TObjectList<T>; APredicate: TPredicate<T>); begin inherited Create; FList := AList; FIndex := -1; FPredicate := APredicate; end; function TObjectList<T>.TEnumerator.DoGetCurrent: T; begin Result := FList[FIndex]; end; function TObjectList<T>.TEnumerator.DoMoveNext: Boolean; begin If FIndex >= FList.Count Then Exit(False); If not Assigned(FPredicate) Then Inc(FIndex) Else Begin Repeat Inc(FIndex); Until (FIndex >= FList.Count) Or DoPredicate(FList[FIndex]); End; Result := FIndex < FList.Count; end; function TObjectList<T>.TEnumerator.DoPredicate(Value: T): Boolean; begin Result := True; If Assigned(FPredicate) Then Result := FPredicate(Value); end; function TList<T>.IndexOf(AIndexOf: TPredicate<T>; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,AIndexOf,StartIndex,IsFiltered); end; function TList<T>.IndexOf(Value: Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(FIndexOfIndex,FIndexOfFunc,Value,StartIndex,IsFiltered); end; function TList<T>.IndexOf(var Index: Integer; Value: Variant; StartIndex: Integer; IsFiltered: Boolean): Boolean; begin Result := IndexOf(Index,FIndexOfFunc,Value,StartIndex,IsFiltered); end; end.
unit BaseContentProvider; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Laz2_XMLCfg; type { TBaseContentProvider } TBaseContentProviderClass = Class of TBaseContentProvider; TBaseContentProvider = class(TObject) private FOnTitleChange: TNotifyEvent; FParent: TWinControl; FTitle: String; FConfig: TXMLConfig; FUpdateCount: Integer; protected FImageList: TImageList; function GetTitle: String; virtual; procedure SetTitle(const AValue: String); virtual; function IsUpdating: Boolean; public function CanGoBack: Boolean; virtual; abstract; function CanGoForward: Boolean; virtual; abstract; function GetHistory: TStrings; virtual; abstract; function LoadURL(const AURL: String; const AContext: THelpContext = -1): Boolean; virtual; abstract; procedure GoHome; virtual; abstract; procedure GoBack; virtual; abstract; procedure GoForward; virtual; abstract; procedure BeginUpdate; virtual; procedure EndUpdate; virtual; procedure LoadPreferences(ACfg: TXMLConfig); virtual; procedure SavePreferences({%H-}ACfg: TXMLConfig); virtual; class function GetProperContentProviderClass(const AURL: String): TBaseContentProviderClass; virtual; abstract; constructor Create(AParent: TWinControl; AImageList: TImageList); virtual; destructor Destroy; override; property Parent: TWinControl read FParent; property Title: String read GetTitle write SetTitle; property OnTitleChange: TNotifyEvent read FOnTitleChange write FOnTitleChange; end; // returns false if the protocol has already been registered function RegisterContentProvider(const Protocol: String; ContentProvider: TBaseContentProviderClass): Boolean; // example: RegisterContentProvider('chm://', TChmContentProvider); function GetContentProviderClass(const Protocol: String): TBaseContentProviderClass; procedure ReadContentProviderList(AValue: TStrings); implementation var ContentProviders: TStringList; function RegisterContentProvider(const Protocol: String; ContentProvider: TBaseContentProviderClass): Boolean; begin Result := False; if ContentProviders.IndexOf(Protocol) > -1 then exit; ContentProviders.AddObject(Protocol, TObject(ContentProvider)); end; function GetContentProviderClass(const Protocol: String): TBaseContentProviderClass; var iIndex: Integer; begin Result := nil; iIndex := ContentProviders.IndexOf(Protocol); if iIndex = -1 then Exit; Result := TBaseContentProviderClass(ContentProviders.Objects[iIndex]); end; procedure ReadContentProviderList(AValue: TStrings); begin AValue.AddStrings(ContentProviders); end; { TBaseContentProvider } function TBaseContentProvider.GetTitle: String; begin Result := FTitle; end; procedure TBaseContentProvider.SetTitle(const AValue: String); begin FTitle := AValue; if Assigned(FOnTitleChange) then FOnTitleChange(Self); end; function TBaseContentProvider.IsUpdating: Boolean; begin Result := FUpdateCount <> 0; end; procedure TBaseContentProvider.BeginUpdate; begin Inc(FUpdateCount); end; procedure TBaseContentProvider.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount < 0 then FUpdateCount := 0; end; procedure TBaseContentProvider.LoadPreferences(ACfg: TXMLConfig); begin FConfig := ACfg; end; procedure TBaseContentProvider.SavePreferences(ACfg: TXMLConfig); begin end; constructor TBaseContentProvider.Create(AParent: TWinControl; AImageList: TImageList); begin FParent:= AParent; FImageList:= AImageList; end; destructor TBaseContentProvider.Destroy; begin SavePreferences(FConfig); inherited Destroy; end; initialization ContentProviders := TStringList.Create; finalization ContentProviders.Free; end.
unit test_tpShareI; (* Permission is hereby granted, on 18-Jul-2017, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) interface {$I hrefdefines.inc} uses SysUtils, Types, DUnitX.TestFrameWork, tpShareI; type [TestFixture] TTest_tpShareI = class(TObject) private FCopy1: TtpSharedInt32; public [Setup] procedure SetUp; [TearDown] procedure TearDown; public [Test] procedure Test_tpShareI_NameSame; [Test] procedure Test_tpShareI_NameDifferent; end; implementation uses System.Classes, System.Threading; procedure TTest_tpShareI.Setup; begin inherited; if NOT Assigned(FCopy1) then begin FCopy1 := TtpSharedInt32.Create(nil); FCopy1.Name := 'FCopy1'; FCopy1.GlobalName := 'DUnitSharedInt'; // cReadWriteSharedMem, cLocalSharedMem); FCopy1.GlobalInteger := 42; end; end; procedure TTest_tpShareI.TearDown; begin FreeAndNil(FCopy1); inherited; end; procedure TTest_tpShareI.Test_tpShareI_NameSame; const cFn = 'Test_tpShareI_NameSame'; var x1, x2: Integer; FCopy2: TtpSharedInt32; begin FCopy2 := nil; TTask.Run(procedure begin try FCopy2 := TtpSharedInt32.Create(nil); // in separate THREAD FCopy2.Name := 'FCopy2'; FCopy2.GlobalName := 'DUnitSharedInt'; x1 := FCopy1.GlobalInteger; x2 := FCopy2.GlobalInteger; Assert.AreEqual(x1, x2, 'from GlobalInteger'); Assert.AreEqual(FCopy1.GlobalInteger, FCopy2.GlobalInteger, 'more directly GlobalInteger'); finally FreeAndNil(FCopy2); end; end); end; procedure TTest_tpShareI.Test_tpShareI_NameDifferent; var FCopy2: TtpSharedInt32; begin FCopy2 := nil; try FCopy2 := TtpSharedInt32.Create(nil); // (nil, FCopy2.Name := 'FCopy2'; FCopy2.GlobalName := 'X'; //, cReadonlySharedMem, cLocalSharedMem); Assert.AreNOTEqual(FCopy1.GlobalInteger, FCopy2.GlobalInteger, 'GlobalInteger vs X'); finally FreeAndNil(FCopy2); end; end; initialization TDUnitX.RegisterTestFixture(TTest_tpShareI); end.
unit uSCSTypes; interface uses System.SysUtils; // SynCommons; type TTrackerOperation = (Add, Update, Delete); TGPSTrackerType = (trtUndefined, trtTDC, trtTeltonika, trtRoadKey, trtGlobalSat, trtAndroid, trtCicada, trtWialonIPS, trtBCE ); TSID = packed record private FPrefix: string; FClientSID: string; FTrackerSID: string; function GetAsText: string; procedure SetAsText(const Value: string); public property AsText: string read GetAsText write SetAsText; end; ESIDConvertException = class(Exception) end; TAddTrackerParamsDTO = packed record private FTrackerSID: string; function GetTrackerSID: string; public Operation: TTrackerOperation; ClientName: string; // Агро ЮГ1 ClientSID: string; // AgroSouth TrackerName: string; // N123 TrackerType: TGPSTrackerType; // tdc, teltonika TrackerModel: string; // TDC02, FMB125 TrackerLogin: string; // 357454071920571 GPS, Ignition: Boolean; CAN300: Boolean; FLCount: Integer; DistanceTO: Boolean; DistanceTrip: Boolean; Location: Boolean; LocationFileName: string; function GetPass: string; function GetClientName: string; function GetFullTrackerSID: string; procedure SetFullTrackerSID(aFullSID: string); procedure InitDef; property TrackerSID: string read GetTrackerSID write FTrackerSID; // N123 end; TTrackerSensorsRec = packed record GPS: Boolean; Ignition: Boolean; CAN300: Boolean; FLCount: Integer; end; // functions function ExtractSID(aSID: string): string; implementation function ExtractSID(aSID: string): string; begin Result := aSID; if Length(aSID) > 0 then if aSID[1] = '$' then Result := Copy(aSID, 2, Length(aSID) - 1); end; { TTrackerParams } function TAddTrackerParamsDTO.GetClientName: string; begin if ClientName = '' then Result := ClientSID else Result := ClientName; end; function TAddTrackerParamsDTO.GetPass: string; begin case TrackerType of trtUndefined, trtTeltonika, trtRoadKey, trtGlobalSat, trtCicada, trtWialonIPS: Result := ''; trtTDC: Result := '7'; trtAndroid: Result := '20'; end; end; function TAddTrackerParamsDTO.GetTrackerSID: string; begin if FTrackerSID = '' then Result := TrackerName else Result := FTrackerSID; end; function TAddTrackerParamsDTO.GetFullTrackerSID: string; begin if FTrackerSID = '' then Result := ClientSID + '.' + TrackerName else Result := ClientSID + '.' + FTrackerSID; end; procedure TAddTrackerParamsDTO.InitDef; begin Operation := TTrackerOperation.Add; TrackerName := ''; TrackerSID := ''; TrackerType := trtUndefined; TrackerModel := ''; ClientName := ''; ClientSID := ''; TrackerLogin := ''; GPS := False; Ignition := False; CAN300 := False; FLCount := 0; DistanceTO := False; DistanceTrip := False; end; procedure TAddTrackerParamsDTO.SetFullTrackerSID(aFullSID: string); var s: string; p: Integer; begin if Length(aFullSID) = 0 then Exit; if aFullSID[1] = '$' then s := Copy(aFullSID, 2, Length(aFullSID) - 1) else s := aFullSID; p := Pos('.', s); if p > 0 then begin ClientSID := Copy(s, 1, p - 1); TrackerSID := Copy(s, p + 1, Length(s) - p); end else TrackerSID := s; end; { TSID } function TSID.GetAsText: string; begin if FPrefix <> '$' then // числовая адресация : 625 Result := FTrackerSID else if FClientSID = '' then // трекер не использует родительский SID : $TrackerN125 Result := FPrefix + FTrackerSID else // трекер использует родительский SID : $Client1.TrackerN125 Result := FPrefix + FClientSID + '.' + FTrackerSID; end; procedure TSID.SetAsText(const Value: string); var p: Integer; s: string; v: Integer; begin if Length(Value) = 0 then begin FPrefix := ''; FClientSID := ''; FTrackerSID := ''; Exit; end; if Value[1] = '$' then begin // значит это строковый адрес FPrefix := '$'; s := Copy(Value, 2, Length(Value) - 1); p := Pos('.', s); if p > 0 then begin // $Client.Tracker FClientSID := Copy(s, 1, p - 1); FTrackerSID := Copy(s, p + 1, Length(s) - p); end else begin // $Tracker FClientSID := ''; FTrackerSID := s; end; end else begin // это должно быть число (адерсация по ID) if TryStrToInt(Value, v) then s := Value else raise ESIDConvertException.CreateFmt('SID "%s" is not correct', [Value]); end; end; end.
unit cmpCountryComboBox; interface uses SysUtils, Classes, Controls, StdCtrls, unitCharsetMap; type TCountryComboBox = class(TCustomComboBox) private fCodes : TCountryCodes; fPreferredCountryCodes: string; procedure SetPreferredCountryCodes(const Value: string); function GetCountryCode(idx: Integer): TCountryCode; protected procedure CreateWnd; override; public constructor Create (AOwner : TComponent); override; destructor Destroy; override; property CountryCode [idx : Integer] : TCountryCode read GetCountryCode; property Items; property Text; published property Align; property AutoComplete default True; property AutoCompleteDelay default 500; property AutoDropDown default False; property AutoCloseUp default False; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property Anchors; property BiDiMode; property CharCase; property Color; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ItemHeight; property ItemIndex default -1; property MaxLength; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; // Use telephone dialling code for counties - 1 = USA, 44 = UK etc. // Eg. Set this property to '44,1' to sort with United Kindom first, United States second, and the // other countries next property PreferredCountryCodes : string read fPreferredCountryCodes write SetPreferredCountryCodes; property ShowHint; property Sorted; property TabOrder; property TabStop; property Visible; property OnChange; property OnClick; property OnCloseUp; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnDropDown; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMeasureItem; property OnMouseEnter; property OnMouseLeave; property OnSelect; property OnStartDock; property OnStartDrag; end; implementation { TCountryComboBox } constructor TCountryComboBox.Create(AOwner: TComponent); begin inherited; Style := csDropDownList; end; procedure TCountryComboBox.CreateWnd; var i : Integer; cc : TCountryCode; begin inherited; if csDesigning in ComponentState then Items.Add ('Countries') else begin if fCodes = Nil then fCodes := TCountryCodes.Create; fCodes.SortByName(fPreferredCountryCodes); Items.BeginUpdate; try Items.Clear; for i := 0 to fCodes.Count - 1 do begin cc := fCodes.CountryCode [i]; Items.Add(cc.Name) end; finally Items.EndUpdate end; if Items.Count > 0 then ItemIndex := 0 end end; destructor TCountryComboBox.Destroy; begin FreeAndNil (fCodes); inherited; end; function TCountryComboBox.GetCountryCode(idx: Integer): TCountryCode; begin result := TCountryCode (fCodes [idx]); end; procedure TCountryComboBox.SetPreferredCountryCodes(const Value: string); begin if Value <> fPreferredCountryCodes then begin fPreferredCountryCodes := Value; if not (csDesigning in ComponentState) then RecreateWnd; end end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Themes, Generics.Defaults, Generics.Collections, Vcl.ExtCtrls; type TForm1 = class(TForm) Button1: TButton; CheckBox1: TCheckBox; Label1: TLabel; Label2: TLabel; Edit1: TEdit; Memo1: TMemo; ListBox1: TListBox; ComboBox1: TComboBox; RadioGroup1: TRadioGroup; Panel1: TPanel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); // var StyleList : TArray<String>; var StyleList : TArray<String>; var currentStyle : String; var FoundIndex : Integer; var maxIndex : Integer; begin StyleList := TStyleManager.StyleNames; maxIndex := Length(StyleList) - 1; TArray.Sort<String>(StyleList, TStringComparer.Ordinal); currentStyle := TStyleManager.ActiveStyle.Name; TArray.BinarySearch<String>(StyleList, currentStyle, FoundIndex, TStringComparer.Ordinal); if FoundIndex = maxIndex then begin FoundIndex := 0; end else begin FoundIndex := FoundIndex + 1; end; TStyleManager.TrySetStyle(StyleList[FoundIndex]); label1.Caption := TStyleManager.ActiveStyle.Name; end; procedure TForm1.FormCreate(Sender: TObject); begin label1.Caption := TStyleManager.ActiveStyle.Name; end; end.
unit unUpdateClient; interface uses Classes, ComObj, ActiveX; type TUpdateClient = class(TComponent) private FApplicationGUID :string; procedure SaveInstallionGUID(const AInstallionGUID: string); function GetMachineGUID :string; protected function GetDeviceFingerPrint :string; virtual; public function RegisterInstall :string; function CheckForUpdates :string; property ApplicationGUID :string read FApplicationGUID write FApplicationGUID; end; implementation uses unIUpdateService, XMLDoc, XMLIntf, unPath, hcUpdateConsts, SysUtils, hcVersionInfo, System.DateUtils, unWebServiceFileUtils, hcUpdateSettings, Winapi.Windows, System.Win.Registry, PJSysInfo, System.TypInfo; function TUpdateClient.CheckForUpdates :string; { This method assumes the current application directory contains the Manifest file and that it contains the ApplicationGUID. It also assume that the AutoUpdates.ini file is present in the same folder and has been updated to contain the InstallationGUID by the registration process. } var UpdateService :IUpdateService; AppUpdateResult :ApplicationUpdateResult; I: Integer; InstallionGUID, ApplicationGUID, AppDir, UpdateDirectory :string; XMLDoc : IXMLDocument; iRootNode, iNode : IXMLNode; StringStream :TStringStream; sPatchFileName :string; slProgress :TStringList; StartTime, EndTime :TDateTime; sError :string; begin slProgress := TStringList.Create; StartTime := Now; slProgress.Add(Format('Update Log for a single request starting %s',[DateTimeToStr(StartTime)])); try InstallionGUID := AutoUpdateSettings.InstallionGUID; if InstallionGUID = EmptyStr then raise Exception.Create('InstallionGUID is Empty!'); try slProgress.Add('Initializing COM'); CoInitialize(nil); try StringStream := TStringStream.Create; try AppDir := ExtractFilePath(AppFileName); //---need to get ApplicationGUID from Manifest file if it exists otherwise we're done if not FileExists(AppDir + ManifestFileName) then raise Exception.CreateFmt('No Manifest file is present in ''%s''',[AppDir]) else begin slProgress.Add('Loading and Processing Existing Manifest'); XMLDoc := TXMLDocument.Create(nil); try XMLDoc.LoadFromFile(AppDir + ManifestFileName); XMLDoc.Active := True; iRootNode := XMLDoc.ChildNodes.First; ApplicationGUID := iRootNode.Attributes['ApplicationGUID']; finally XMLDoc := nil; end; end; slProgress.Add('Getting Reference to IUpdateService'); UpdateService := GetIUpdateService(False, AutoUpdateSettings.WebServiceURI); try slProgress.Add(Format('Calling IUpdateService.GetUpdate with ApplicationGUID: %s InstallionGUID: %s',[ApplicationGUID,InstallionGUID])); AppUpdateResult := UpdateService.GetUpdate(ApplicationGUID,InstallionGUID,StringStream.DataString); except on E: Exception do //server is likely not running begin //translate the exception and re-raise (consumer must handle) Result := ''; slProgress.Add('Call to IUpdateService.GetUpdate FAILED with Error:' + E.Message); raise; end; end; if AppUpdateResult.UpdateIsAvailable then begin slProgress.Add('An Update is available'); //create a directory based on the new update version # UpdateDirectory := Format('%sUpdates\Pending\%s\',[AppDir,AppUpdateResult.NewManifest.UpdateVersion]); slProgress.Add('Forcing Directory :'+UpdateDirectory); ForceDirectories(UpdateDirectory); slProgress.Add('Saving Update Request result'); //save the new manifest and binary components to disk XMLDoc := TXMLDocument.Create(nil); try XMLDoc.Active := True; iRootNode := XMLDoc.AddChild('Manifest'); iRootNode.Attributes['ApplicationGUID'] := AppUpdateResult.ApplicationGUID; iRootNode.Attributes['UpdateVersion'] := AppUpdateResult.NewManifest.UpdateVersion; iRootNode.Attributes['WhatsNew'] := AppUpdateResult.NewManifest.WhatsNew; iRootNode.Attributes['IsMandatory'] := AppUpdateResult.NewManifest.IsMandatory; iRootNode.Attributes['IsSilent'] := AppUpdateResult.NewManifest.IsSilent; iRootNode.Attributes['IsImmediate'] := AppUpdateResult.NewManifest.IsImmediate; for I := Low(AppUpdateResult.NewManifest.Items) to High(AppUpdateResult.NewManifest.Items) do begin slProgress.Add(Format('Saving Manifest Item %d of %d (%s)',[I+1,High(AppUpdateResult.NewManifest.Items),AppUpdateResult.NewManifest.Items[I].FileName])); iNode := iRootNode.AddChild('Item'); iNode.Attributes['FileName'] := AppUpdateResult.NewManifest.Items[I].FileName; iNode.Attributes['IsAPatch'] := AppUpdateResult.NewManifest.Items[I].IsAPatch; iNode.Attributes['IsAZip'] := AppUpdateResult.NewManifest.Items[I].IsAZip; iNode.Attributes['Launch'] := AppUpdateResult.NewManifest.Items[I].Launch; iNode.Attributes['Version'] := AppUpdateResult.NewManifest.Items[I].Version; iNode.Attributes['TargetPath'] := AppUpdateResult.NewManifest.Items[I].TargetPath; if iNode.Attributes['IsAPatch'] then begin sPatchFileName := ChangeFileExt(AppUpdateResult.NewManifest.Items[I].FileName,PatchFileExtension); slProgress.Add(Format('Processing Patch File: %s',[sPatchFileName])); ByteArrayToFile(AppUpdateResult.NewManifest.Items[I].FileData,UpdateDirectory + '\'+ sPatchFileName); end else begin slProgress.Add(Format('Saving File: %s',[AppUpdateResult.NewManifest.Items[I].FileName])); ByteArrayToFile(AppUpdateResult.NewManifest.Items[I].FileData,UpdateDirectory + '\'+ AppUpdateResult.NewManifest.Items[I].FileName); end; end; slProgress.Add('Saving new Manifest'); XMLDoc.SaveToFile(UpdateDirectory+'\Manifest.xml'); finally XMLDoc := nil; end; slProgress.Add('Calling IUpdateService.UpdateReceived'); UpdateService.UpdateReceived(ApplicationGUID,InstallionGUID,AppUpdateResult.NewManifest.UpdateVersion); Result := Format('Update v.%s is available!',[AppUpdateResult.NewManifest.UpdateVersion]); slProgress.Add(Format('Returning Result: %s',[Result])); end else begin slProgress.Add('No Update is Available...'); Result := 'NO Update is available...'; end; AppUpdateResult.Free; finally StringStream.Free; end; finally CoUninitialize; end; except On E: Exception do begin sError := Format('ERROR during Update Request: %s',[E.Message]); slProgress.Add(sError); Result := sError; end; end; finally EndTime := Now; slProgress.Add(Format('END of Update Log %s. Update Request Duration was %d seconds',[DateTimeToStr(EndTime),SecondsBetween(StartTime,EndTime)])); {$ifdef LOGGING} slProgress.SaveToFile(ChangeFileExt(AppFileName,'.log')); {$endif} slProgress.Free; end; end; function TUpdateClient.GetDeviceFingerPrint: string; const cProcessors: array[TPJProcessorArchitecture] of string = ( 'paUnknown', 'paX64', 'paIA64', 'paX86' ); cBootModes: array[TPJBootMode] of string = ( 'bmUnknown', 'bmNormal', 'bmSafeMode', 'bmSafeModeNetwork' ); var slFingerPrint :TStringList; begin slFingerPrint := TStringList.Create; try with slFingerPrint do begin //Computer information AddPair('User Name', TPJComputerInfo.UserName); AddPair('Computer Name', TPJComputerInfo.ComputerName); AddPair('MAC Address', TPJComputerInfo.MACAddress); AddPair('Processor Count', IntToStr(TPJComputerInfo.ProcessorCount)); AddPair('Processor Architecture', cProcessors[TPJComputerInfo.Processor]); AddPair('Processor Identifier', TPJComputerInfo.ProcessorIdentifier); AddPair('Processor Name', TPJComputerInfo.ProcessorName); AddPair('Processor Speed (MHz)', IntToStr(TPJComputerInfo.ProcessorSpeedMHz)); AddPair('Is 64 Bit?', BoolToStr(TPJComputerInfo.Is64Bit,True)); AddPair('Is Network Present?', BoolToStr(TPJComputerInfo.IsNetworkPresent,True)); AddPair('Boot Mode', cBootModes[TPJComputerInfo.BootMode]); AddPair('Is Administrator?', BoolToStr(TPJComputerInfo.IsAdmin,True)); AddPair('Is UAC active?', BoolToStr(TPJComputerInfo.IsUACActive,True)); AddPair('BIOS Vender', TPJComputerInfo.BiosVendor); AddPair('System Manufacturer', TPJComputerInfo.SystemManufacturer); AddPair('System Product Name', TPJComputerInfo.SystemProductName); //OS information AddPair('BuildNumber', IntToStr(TPJOSInfo.BuildNumber)); AddPair('Description', TPJOSInfo.Description); AddPair('Edition', TPJOSInfo.Edition); if SameDateTime(TPJOSInfo.InstallationDate, 0.0) then AddPair('InstallationDate', 'Unknown') else AddPair('InstallationDate', DateTimeToStr(TPJOSInfo.InstallationDate)); AddPair('IsServer', BoolToStr(TPJOSInfo.IsServer,True)); AddPair('IsWin32s', BoolToStr(TPJOSInfo.IsWin32s,True)); AddPair('IsWin9x', BoolToStr(TPJOSInfo.IsWin9x,True)); AddPair('IsWinNT', BoolToStr(TPJOSInfo.IsWinNT,True)); AddPair('IsWow64', BoolToStr(TPJOSInfo.IsWow64,True)); AddPair('IsMediaCenter', BoolToStr(TPJOSInfo.IsMediaCenter,True)); AddPair('IsTabletPC', BoolToStr(TPJOSInfo.IsTabletPC,True)); AddPair('IsRemoteSession', BoolToStr(TPJOSInfo.IsRemoteSession,True)); AddPair('MajorVersion', IntToStr(TPJOSInfo.MajorVersion)); AddPair('MinorVersion', IntToStr(TPJOSInfo.MinorVersion)); AddPair('Platform', GetEnumName(TypeInfo(TPJOSPlatform),Ord(TPJOSInfo.Platform))); AddPair('Product', TPJOSInfo.ProductName); AddPair('ProductID', TPJOSInfo.ProductID); AddPair('ProductName', TPJOSInfo.ProductName); AddPair('ServicePack', TPJOSInfo.ServicePack); AddPair('ServicePackEx', TPJOSInfo.ServicePackEx); AddPair('ServicePackMajor', IntToStr(TPJOSInfo.ServicePackMajor)); AddPair('ServicePackMinor', IntToStr(TPJOSInfo.ServicePackMinor)); AddPair('HasPenExtensions', BoolToStr(TPJOSInfo.HasPenExtensions,True)); AddPair('RegisteredOrganization', TPJOSInfo.RegisteredOrganisation); AddPair('RegisteredOwner', TPJOSInfo.RegisteredOwner); AddPair('CanSpoof', BoolToStr(TPJOSInfo.CanSpoof,True)); AddPair('IsReallyWindows2000OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows2000OrGreater,True)); AddPair('IsReallyWindows2000SP1OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows2000SP1OrGreater,True)); AddPair('IsReallyWindows2000SP2OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows2000SP2OrGreater,True)); AddPair('IsReallyWindows2000SP3OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows2000SP3OrGreater,True)); AddPair('IsReallyWindows2000SP4OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows2000SP4OrGreater,True)); AddPair('IsReallyWindowsXPOrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsXPOrGreater,True)); AddPair('IsReallyWindowsXPSP1OrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsXPSP1OrGreater,True)); AddPair('IsReallyWindowsXPSP2OrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsXPSP2OrGreater,True)); AddPair('IsReallyWindowsXPSP3OrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsXPSP3OrGreater,True)); AddPair('IsReallyWindowsVistaOrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsVistaOrGreater,True)); AddPair('IsReallyWindowsVistaSP1OrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsVistaSP1OrGreater,True)); AddPair('IsReallyWindowsVistaSP2OrGreater', BoolToStr(TPJOSInfo.IsReallyWindowsVistaSP2OrGreater,True)); AddPair('IsReallyWindows7OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows7OrGreater,True)); AddPair('IsReallyWindows7SP1OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows7SP1OrGreater,True)); AddPair('IsReallyWindows8OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows8OrGreater,True)); AddPair('IsReallyWindows8Point1OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows8Point1OrGreater,True)); AddPair('IsReallyWindows10OrGreater', BoolToStr(TPJOSInfo.IsReallyWindows10OrGreater,True)); AddPair('IsWindowsServer', BoolToStr(TPJOSInfo.IsWindowsServer,True)); AddPair('Win32Platform', IntToStr(Win32Platform)); AddPair('Win32MajorVersion', IntToStr(Win32MajorVersion)); AddPair('Win32MinorVersion', IntToStr(Win32MinorVersion)); AddPair('Win32BuildNumber', IntToStr(Win32BuildNumber)); AddPair('Win32CSDVersion', Win32CSDVersion); end; Result := slFingerPrint.Text; finally slFingerPrint.Free; end; end; function TUpdateClient.GetMachineGUID: string; var Registry: TRegistry; begin Registry := TRegistry.Create(KEY_READ or KEY_WOW64_64KEY); try Registry.RootKey := HKEY_LOCAL_MACHINE; if not Registry.OpenKeyReadOnly('SOFTWARE\Microsoft\Cryptography') then raise Exception.Create('Unable to access MachineGUID'); Result := Registry.ReadString('MachineGuid'); finally Registry.Free; end; end; function TUpdateClient.RegisterInstall: string; var UpdateService :IUpdateService; InstallationGUID, ApplicationGUID, AppDir :string; XMLDoc : IXMLDocument; iRootNode :IXMLNode; slProgress :TStringList; StartTime, EndTime :TDateTime; sError :string; DeviceFingerPrint: string; DeviceGUID: string; begin DeviceGUID := GetMachineGUID;; DeviceFingerPrint := GetDeviceFingerPrint; slProgress := TStringList.Create; StartTime := Now; slProgress.Add(Format('Update Log for a RegisterInstall request starting %s',[DateTimeToStr(StartTime)])); try try slProgress.Add('Initializing COM'); CoInitialize(nil); try AppDir := ExtractFilePath(AppFileName); //---need to get ApplicationGUID from Manifest file if it exists otherwise we're done if not FileExists(AppDir + ManifestFileName) then raise Exception.CreateFmt('No Manifest file is present in ''%s''',[AppDir]) else begin slProgress.Add('Loading Manifest for RegisterInstall request'); XMLDoc := TXMLDocument.Create(nil); try XMLDoc.LoadFromFile(AppDir + ManifestFileName); XMLDoc.Active := True; iRootNode := XMLDoc.ChildNodes.First; ApplicationGUID := iRootNode.Attributes['ApplicationGUID']; finally XMLDoc := nil; end; end; slProgress.Add('Getting Reference to IUpdateService'); UpdateService := GetIUpdateService(False, AutoUpdateSettings.WebServiceURI); try slProgress.Add(Format('Calling IUpdateService.RegisterInstall with ApplicationGUID: %s ',[ApplicationGUID])); InstallationGUID := UpdateService.RegisterInstall(ApplicationGUID,DeviceGUID,DeviceFingerPrint); except on E: Exception do //server is likely not running begin //translate the exception and re-raise (consumer must handle) Result := ''; slProgress.Add('Call to IUpdateService.RegisterInstall FAILED with Error:' + E.Message); raise; end; end; if InstallationGUID = EmptyStr then raise Exception.Create('LocationGUID was not returned!') else //save it on the AutoUpdate.config file begin Result := 'Installation Registered Successfully!'; SaveInstallionGUID(InstallationGUID); end; finally CoUninitialize; end; except On E: Exception do begin sError := Format('ERROR during Update Request: %s',[E.Message]); slProgress.Add(sError); Result := sError; end; end; finally EndTime := Now; slProgress.Add(Format('END of Update Log %s. Update Request Duration was %d seconds',[DateTimeToStr(EndTime),SecondsBetween(StartTime,EndTime)])); {$ifdef LOGGING} slProgress.SaveToFile(ChangeFileExt(AppFileName,'.log')); {$endif} slProgress.Free; end; end; procedure TUpdateClient.SaveInstallionGUID(const AInstallionGUID: string); begin AutoUpdateSettings.InstallionGUID := AInstallionGUID; //update folders to actual deployment path AutoUpdateSettings.AppDir := ExtractFilePath(AppFileName); AutoUpdateSettings.WriteSettings; end; end.
unit BlockManager; interface uses TaskClass; type CBlock = class private TaskList: TArray<CTaskManager>; BlockCost: Integer; CurrentTaskPosition: Integer; public procedure Tackt(); procedure Update(); constructor Create(Tasks: TArray<CTaskManager>); function IsWork: Boolean; function IsSleep: Boolean; function IsReady: Boolean; function GetBlockCost(): Integer; end; implementation procedure CBlock.Update(); var I: Integer; begin for I := 0 to High(TaskList) do begin TaskList[I].Update(); end; end; procedure CBlock.Tackt(); begin while (not TaskList[CurrentTaskPosition].IsWork) or (TaskList[CurrentTaskPosition].IsSleep) do begin CurrentTaskPosition := (CurrentTaskPosition + 1) mod Length(TaskList); end; TaskList[CurrentTaskPosition].Process(); CurrentTaskPosition := (CurrentTaskPosition + 1) mod Length(TaskList); end; function CBlock.IsSleep(): Boolean; var I: Integer; begin Result := True; for I := 0 to High(TaskList) do begin Result := Result and TaskList[I].IsSleep; end; end; function CBlock.IsWork(): Boolean; var I: Integer; begin Result := False;; for I := 0 to High(TaskList) do begin Result := Result or TaskList[I].IsWork; end; end; function CBlock.GetBlockCost: Integer; begin Result := BlockCost; end; constructor CBlock.Create(Tasks: TArray<CTaskManager>); var I: Integer; begin TaskList := Tasks; CurrentTaskPosition := 0; BlockCost := 0; for I := 0 to High(Tasks) do begin Inc(BlockCost, Tasks[I].GetTaskCost); end; end; function CBlock.IsReady(): Boolean; var I: Integer; begin Result := False; for I := 0 to High(TaskList) do begin Result := Result or ((not TaskList[I].IsSleep) and TaskList[I].IsWork) end; end; end.
unit Unit2; interface uses Windows, SysUtils, Graphics, Controls, Forms, StdCtrls, ComCtrls, ExtCtrls, SynEdit, SynEditTypes, SynEditHighlighter, SynEditMiscClasses, SynEditExport, SynEditSearch, SynEditAutoComplete, Menus, Classes, Dialogs, Ruler, Fonctions, SynCompletionProposal, SynEditKeyCmds, SynMemo, ShellApi, StrUtils; type TForm2 = class(TForm) SynEdit1 : TSynEdit; StatusBar1 : TStatusBar; GroupBox1 : TGroupBox; Splitter1 : TSplitter; SynEditSearch1 : TSynEditSearch; SaveDialog1 : TSaveDialog; Ruler1 : TRuler; SynCompletionProposal1 : TSynCompletionProposal; SynMemo1 : TSynMemo; procedure FormCreate(Sender : TObject); procedure FormClose(Sender : TObject; var Action : TCloseAction); procedure SynEdit1Change(Sender : TObject); procedure FormCloseQuery(Sender : TObject; var CanClose : Boolean); procedure FormCanResize(Sender : TObject; var NewWidth, NewHeight : Integer; var Resize : Boolean); procedure SynEdit1StatusChange(Sender : TObject; Changes : TSynStatusChanges); procedure SynEdit1KeyPress(Sender : TObject; var Key : Char); procedure Effacer1Click(Sender : TObject); procedure FormActivate(Sender : TObject); private { Déclarations privées } public Nom : string; Modifier : boolean; Projet : boolean; SynAutoComplete : TCustomSynAutoComplete; procedure Enregistrer; procedure EnregistrerSous; procedure Exporter(index : integer; fichier : boolean); function DemandeEnregistrer : integer; end; var Form2 : TForm2; implementation uses Unit1, Unit3; {$R *.dfm} procedure TForm2.Exporter(index : integer; fichier : boolean); var ex : TSynCustomExporter; tmp : string; begin ex := nil; if SynEdit1.Highlighter <> nil then begin case index of 0 : ex := Form1.SynExporterHTML1; 1 : ex := Form1.SynExporterRTF1; 2 : ex := Form1.SynExporterTeX1; end; ex.ExportAsText := fichier; ex.Title := Caption; ex.Highlighter := SynEdit1.Highlighter; if SynEdit1.SelAvail then ex.ExportRange(SynEdit1.Lines, SynEdit1.BlockBegin, SynEdit1.BlockEnd) else ex.ExportAll(SynEdit1.Lines); if fichier then begin tmp := Form1.SaveDialog1.Filter; Form1.SaveDialog1.Filter := ex.DefaultFilter; Form1.SaveDialog1.Title := Form1.GetText('56') + ' ' + Ex.FormatName; if Form1.SaveDialog1.Execute then begin case index of 0 : Form1.SaveDialog1.FileName := ChangeFileExt(Form1.SaveDialog1.FileName, '.html'); 1 : Form1.SaveDialog1.FileName := ChangeFileExt(Form1.SaveDialog1.FileName, '.rtf'); 2 : Form1.SaveDialog1.FileName := ChangeFileExt(Form1.SaveDialog1.FileName, '.tex'); end; ex.SaveToFile(Form1.SaveDialog1.FileName); end; Form1.SaveDialog1.Filter := tmp; end else ex.CopyToClipboard; end else MessageBoxA(Handle, Pchar(Form1.GetText('26') + #13 + Form1.GetText('27')), Pchar('All4Cod - ' + Form1.GetText('ERROR')), 0 + MB_ICONINFORMATION + 0); end; function TForm2.DemandeEnregistrer : integer; begin Result := MessageBoxA(Handle, Pchar(Form1.GetText('28')), Pchar('All4Cod - ' + Caption), MB_YESNOCANCEL + MB_ICONQUESTION + 0); end; procedure TForm2.Enregistrer; begin if nom <> '' then begin SynEdit1.Lines.SaveToFile(nom); modifier := false; StatusBar1.Panels[2].Text := ''; if Form3.CheckBox23.Checked then SynEdit1.UndoList.Clear; end else EnregistrerSous; end; procedure TForm2.EnregistrerSous; begin Form1.SaveDialog1.Title := Caption + ' - ' + Form1.GetText('57') + ' ?'; if Form1.SaveDialog1.Execute then begin modifier := false; StatusBar1.Panels[2].Text := ''; nom := Form1.SaveDialog1.FileName; SynEdit1.Lines.SaveToFile(nom); Form1.AddReOpen(nom); Form1.ListBox3.Items[Form1.ListBox3.Items.IndexOf(Caption)] := ExtractFileName(nom); try Form1.TabControl1.Tabs[Form1.TabControl1.Tabs.IndexOf(Caption)] := ExtractFileName(nom); except end; Caption := ExtractFileName(nom); if Form3.CheckBox23.Checked then SynEdit1.UndoList.Clear; end; end; procedure TForm2.FormCreate(Sender : TObject); begin Icon.Handle := Application.Icon.Handle; Nom := ''; Form1.ComboBox1.ItemIndex := 0; Modifier := false; SynAutoComplete:=TCustomSynAutoComplete.Create(Self); SynAutoComplete.Editor:=SynEdit1; SynEdit1.AddKey(ecAutoCompletion, word('J'), [ssCtrl], 0, []); StatusBar1.Panels[0].Width := StatusBar1.Width - 270; StatusBar1.Panels[0].Text := Form1.GetText('81'); StatusBar1.Panels[3].Text := Form1.GetText('75'); GroupBox1.Caption := Form1.GetText('78'); Ruler1.Visible := Form3.CheckBox44.Checked; with SynCompletionProposal1 do begin if Form3.CheckBox45.Checked then Options := Options + [scoCaseSensitive] else Options := Options - [scoCaseSensitive]; if Form3.CheckBox47.Checked then Options := Options + [scoLimitToMatchedText] else Options := Options - [scoLimitToMatchedText]; if Form3.CheckBox46.Checked then Options := Options + [scoAnsiStrings] else Options := Options - [scoAnsiStrings]; ShortCut := Form3.HotKey1.HotKey; TimerInterval := Form3.SpinEdit8.Value; end; with SynEdit1 do begin if Form3.CheckBox27.Checked then ActiveLineColor := clYellow else ActiveLineColor := clWhite; WordWrap := Form3.CheckBox28.Checked; if Form3.CheckBox29.Checked then Options := Options + [eoShowSpecialChars] else Options := Options - [eoShowSpecialChars]; if Form3.CheckBox31.Checked then Options := Options + [eoDragDropEditing] else Options := Options - [eoDragDropEditing]; Gutter.Width := Form3.SpinEdit2.Value; Gutter.DigitCount := Form3.SpinEdit3.Value; Gutter.Visible := Form3.CheckBox17.Checked; Gutter.ZeroStart := Form3.CheckBox18.Checked; Gutter.LeadingZeros := not (Form3.CheckBox19.Checked); Font := Form3.Label11.Font; HideSelection := Form3.CheckBox20.Checked; if Form3.CheckBox21.Checked then Options := Options + [eoAutoIndent] else Options := Options - [eoAutoIndent]; WantTabs := Form3.CheckBox22.Checked; if Form3.CheckBox24.Checked then Options := Options + [eoSmartTabs] else Options := Options - [eoSmartTabs]; ExtraLineSpacing := Form3.SpinEdit4.Value; TabWidth := Form3.SpinEdit5.Value; MaxUndo := Form3.SpinEdit6.Value; RightEdge := Form3.SpinEdit7.Value; case Form3.ComboBox3.ItemIndex of 0 : ScrollBars := ssNone; 1 : ScrollBars := ssVertical; 2 : ScrollBars := ssHorizontal; 3 : ScrollBars := ssBoth; end; case Form3.ComboBox4.ItemIndex of 0 : begin InsertCaret := ctVerticalLine; OverwriteCaret := ctVerticalLine; end; 1 : begin InsertCaret := ctHorizontalLine; OverwriteCaret := ctHorizontalLine; end; 2 : begin InsertCaret := ctHalfBlock; OverwriteCaret := ctHalfBlock; end; 3 : begin InsertCaret := ctBlock; OverwriteCaret := ctBlock; end; end; Color := Form3.Shape3.Brush.Color; SelectedColor.Foreground := Form3.Shape4.Brush.Color; SelectedColor.Background := Form3.Shape5.Brush.Color; end; end; procedure TForm2.FormClose(Sender : TObject; var Action : TCloseAction); var i : integer; info : boolean; begin info := false; for i := 0 to Form1.MDIChildCount - 1 do if not (Form1.FicheEditeur(i)) then info := true; if Form1.MDIChildCount = 1 then begin Form1.ListBox3.Clear; Form1.TabControl1.Tabs.Clear; Form1.Cpt_Sans_Titre := 1; Form1.Panel8.Visible := false; end else begin if (Form1.MDIChildCount = 2) and info then begin Form1.ListBox3.Clear; Form1.Cpt_Sans_Titre := 1; Form1.ListBox3.Items.Delete(Form1.ListBox3.Items.IndexOf(Caption)); if Form1.TabControl1.Tabs.IndexOf(Caption) > -1 then Form1.TabControl1.Tabs.Delete(Form1.TabControl1.Tabs.IndexOf(Caption)); end else begin Form1.ListBox3.Items.Delete(Form1.ListBox3.Items.IndexOf(Caption)); if Form1.TabControl1.Tabs.IndexOf(Caption) > -1 then Form1.TabControl1.Tabs.Delete(Form1.TabControl1.Tabs.IndexOf(Caption)); end; end; SynAutoComplete.Free; SynEdit1.Free; Action := caFree; end; procedure TForm2.SynEdit1Change(Sender : TObject); begin modifier := true; end; procedure TForm2.FormCloseQuery(Sender : TObject; var CanClose : Boolean); var rep : integer; begin if modifier then begin rep := DemandeEnregistrer; if rep = 6 then Enregistrer else CanClose := rep = 7; end; end; procedure TForm2.FormCanResize(Sender : TObject; var NewWidth, NewHeight : Integer; var Resize : Boolean); begin StatusBar1.Panels[0].Width := StatusBar1.Width - 270; Resize := true; end; procedure TForm2.SynEdit1StatusChange(Sender : TObject; Changes : TSynStatusChanges); begin StatusBar1.Panels[1].Text := IntToStr(SynEdit1.CaretY) + ' : ' + IntToStr(SynEdit1.CaretX); if scModified in Changes then begin modifier := true; if SynEdit1.Modified then StatusBar1.Panels[2].Text := Form1.GetText('77') else StatusBar1.Panels[2].Text := ''; end; if scInsertMode in Changes then begin if SynEdit1.InsertMode then StatusBar1.Panels[3].Text := Form1.GetText('75') else StatusBar1.Panels[3].Text := Form1.GetText('76'); end; end; procedure TForm2.SynEdit1KeyPress(Sender : TObject; var Key : Char); begin if Form3.CheckBox30.Checked and (Key in ['(', '[', '{', '<']) then begin case Ord(Key) of ord('(') : SynEdit1.SelText := '()'; ord('{') : SynEdit1.SelText := '{}'; ord('[') : SynEdit1.SelText := '[]'; ord('<') : SynEdit1.SelText := '<>'; end; SynEdit1.CaretX := SynEdit1.CaretX - 1; Key := #0; end; end; procedure TForm2.Effacer1Click(Sender : TObject); begin SynMemo1.Clear; end; procedure TForm2.FormActivate(Sender : TObject); begin Form1.TabControl1.TabIndex := Form1.ListBox3.Items.IndexOf(Caption); end; end.
{******************************************************************************* 作者: dmzn@163.com 2008-08-07 描述: 系统数据库常量定义 备注: *.自动创建SQL语句,支持变量:$Inc,自增;$Float,浮点;$Integer=sFlag_Integer; $Decimal=sFlag_Decimal;$Image,二进制流 *******************************************************************************} unit USysDB; {$I Link.inc} interface uses SysUtils, Classes; const cSysDatabaseName: array[0..4] of String = ( 'Access', 'SQL', 'MySQL', 'Oracle', 'DB2'); //db names type TSysDatabaseType = (dtAccess, dtSQLServer, dtMySQL, dtOracle, dtDB2); //db types PSysTableItem = ^TSysTableItem; TSysTableItem = record FTable: string; FNewSQL: string; end; //系统表项 var gSysTableList: TList = nil; //系统表数组 gSysDBType: TSysDatabaseType = dtSQLServer; //系统数据类型 //------------------------------------------------------------------------------ const //自增字段 sField_Access_AutoInc = 'Counter'; sField_SQLServer_AutoInc = 'Integer IDENTITY (1,1) PRIMARY KEY'; //小数字段 sField_Access_Decimal = 'Float'; sField_SQLServer_Decimal = 'Decimal(15, 5)'; //图片字段 sField_Access_Image = 'OLEObject'; sField_SQLServer_Image = 'Image'; //日期相关 sField_SQLServer_Now = 'getDate()'; ResourceString {*权限项*} sPopedom_Read = 'A'; //浏览 sPopedom_Add = 'B'; //添加 sPopedom_Edit = 'C'; //修改 sPopedom_Delete = 'D'; //删除 sPopedom_Preview = 'E'; //预览 sPopedom_Print = 'F'; //打印 sPopedom_Export = 'G'; //导出 {*相关标记*} sFlag_Yes = 'Y'; //是 sFlag_No = 'N'; //否 sFlag_Enabled = 'Y'; //启用 sFlag_Disabled = 'N'; //禁用 sFlag_Integer = 'I'; //整数 sFlag_Decimal = 'D'; //小数 {*数据表*} sTable_Group = 'Sys_Group'; //用户组 sTable_User = 'Sys_User'; //用户表 sTable_Menu = 'Sys_Menu'; //菜单表 sTable_Popedom = 'Sys_Popedom'; //权限表 sTable_PopItem = 'Sys_PopItem'; //权限项 sTable_Entity = 'Sys_Entity'; //字典实体 sTable_DictItem = 'Sys_DataDict'; //字典明细 sTable_SysDict = 'Sys_Dict'; //系统字典 sTable_ExtInfo = 'Sys_ExtInfo'; //附加信息 sTable_SysLog = 'Sys_EventLog'; //系统日志 sTable_BaseInfo = 'Sys_BaseInfo'; //基础信息 sTable_TempLog = 'Sys_TempLog'; //温度日志 {*新建表*} sSQL_NewSysDict = 'Create Table $Table(D_ID $Inc, D_Name varChar(15),' + 'D_Desc varChar(30), D_Value varChar(50), D_Memo varChar(20),' + 'D_ParamA $Float, D_ParamB varChar(50), D_Index Integer Default 0)'; {----------------------------------------------------------------------------- 系统字典: SysDict *.D_ID: 编号 *.D_Name: 名称 *.D_Desc: 描述 *.D_Value: 取值 *.D_Memo: 相关信息 *.D_ParamA: 浮点参数 *.D_ParamB: 字符参数 *.D_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewExtInfo = 'Create Table $Table(I_ID $Inc, I_Group varChar(20),' + 'I_ItemID varChar(20), I_Item varChar(30), I_Info varChar(500),' + 'I_ParamA $Float, I_ParamB varChar(50), I_Index Integer Default 0)'; {----------------------------------------------------------------------------- 扩展信息表: ExtInfo *.I_ID: 编号 *.I_Group: 信息分组 *.I_ItemID: 信息标识 *.I_Item: 信息项 *.I_Info: 信息内容 *.I_ParamA: 浮点参数 *.I_ParamB: 字符参数 *.I_Memo: 备注信息 *.I_Index: 显示索引 -----------------------------------------------------------------------------} sSQL_NewSysLog = 'Create Table $Table(L_ID $Inc, L_Date DateTime,' + 'L_Man varChar(32),L_Group varChar(20), L_ItemID varChar(20),' + 'L_KeyID varChar(20), L_Event varChar(220))'; {----------------------------------------------------------------------------- 系统日志: SysLog *.L_ID: 编号 *.L_Date: 操作日期 *.L_Man: 操作人 *.L_Group: 信息分组 *.L_ItemID: 信息标识 *.L_KeyID: 辅助标识 *.L_Event: 事件 -----------------------------------------------------------------------------} sSQL_NewBaseInfo = 'Create Table $Table(B_ID $Inc, B_Group varChar(15),' + 'B_Text varChar(100), B_Py varChar(25), B_Memo varChar(50),' + 'B_PID Integer, B_Index Float)'; {----------------------------------------------------------------------------- 基本信息表: BaseInfo *.B_ID: 编号 *.B_Group: 分组 *.B_Text: 内容 *.B_Py: 拼音简写 *.B_Memo: 备注信息 *.B_PID: 上级节点 *.B_Index: 创建顺序 -----------------------------------------------------------------------------} sSQL_NewTempLog = 'Create Table $Table(T_ID $Inc, ' + 'T_W1 $Float, T_S1 $Float,' + 'T_W2 $Float, T_S2 $Float,' + 'T_W3 $Float, T_S3 $Float,' + 'T_W4 $Float, T_S4 $Float,' + 'T_W5 $Float, T_S5 $Float,' + 'T_W6 $Float, T_S6 $Float,' + 'T_W7 $Float, T_S7 $Float,' + 'T_W8 $Float, T_S8 $Float,' + 'T_W9 $Float, T_S9 $Float,' + 'T_W10 $Float, T_S10 $Float,' + 'T_W11 $Float, T_S11 $Float,' + 'T_W12 $Float, T_S12 $Float,' + 'T_W13 $Float, T_S13 $Float,' + 'T_W14 $Float, T_S14 $Float,' + 'T_W15 $Float, T_S15 $Float,' + 'T_W16 $Float, T_S16 $Float,' + 'T_W17 $Float, T_S17 $Float,' + 'T_W18 $Float, T_S18 $Float,' + 'T_W19 $Float, T_S19 $Float,' + 'T_W20 $Float, T_S20 $Float,' + 'T_W21 $Float, T_S21 $Float,' + 'T_W22 $Float, T_S22 $Float,' + 'T_W23 $Float, T_S23 $Float,' + 'T_W24 $Float, T_S24 $Float,' + 'T_W25 $Float, T_S25 $Float,' + 'T_W26 $Float, T_S26 $Float,' + 'T_W27 $Float, T_S27 $Float,' + 'T_W28 $Float, T_S28 $Float,' + 'T_W29 $Float, T_S29 $Float,' + 'T_Date DateTime)'; {----------------------------------------------------------------------------- 基本信息表: BaseInfo *.T_ID: 编号 *.T_Wx: 温度 *.T_Sx: 湿度 *.T_Date: 日期 -----------------------------------------------------------------------------} implementation //------------------------------------------------------------------------------ //Desc: 添加系统表项 procedure AddSysTableItem(const nTable,nNewSQL: string); var nP: PSysTableItem; begin New(nP); gSysTableList.Add(nP); nP.FTable := nTable; nP.FNewSQL := nNewSQL; end; //Desc: 系统表 procedure InitSysTableList; begin gSysTableList := TList.Create; AddSysTableItem(sTable_SysDict, sSQL_NewSysDict); AddSysTableItem(sTable_ExtInfo, sSQL_NewExtInfo); AddSysTableItem(sTable_SysLog, sSQL_NewSysLog); AddSysTableItem(sTable_BaseInfo, sSQL_NewBaseInfo); AddSysTableItem(sTable_TempLog, sSQL_NewTempLog); end; //Desc: 清理系统表 procedure ClearSysTableList; var nIdx: integer; begin for nIdx:= gSysTableList.Count - 1 downto 0 do begin Dispose(PSysTableItem(gSysTableList[nIdx])); gSysTableList.Delete(nIdx); end; FreeAndNil(gSysTableList); end; initialization InitSysTableList; finalization ClearSysTableList; end.
unit CustomizeScreen; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, InfraGUIBuilderIntf, ComCtrls, StdCtrls, ExtCtrls, List_GUIControl, ActnList, Mask, LayoutManager, InfraGUIBuilderForm, GUIAnnotationLoaderIntf; type TCustomizeScreen = class(TForm) lsvControlList: TListView; pnlBottom: TPanel; btbtCancel: TButton; btbtOK: TButton; btbtEditControl: TButton; actlActions: TActionList; actnClose: TAction; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure actnCloseExecute(Sender: TObject); procedure btbtCancelClick(Sender: TObject); procedure btbtEditControlClick(Sender: TObject); procedure btbtOKClick(Sender: TObject); procedure lsvControlListDblClick(Sender: TObject); private // componentes de tela LayoutManager1: TLayoutManager; editTitle: TEdit; combCaptionPosition: TComboBox; editHeight: TMaskEdit; editWidth: TMaskEdit; combItemLayout: TComboBox; editPaddingLeft: TMaskEdit; editPaddingTop: TMaskEdit; editPaddingRight: TMaskEdit; editPaddingBottom: TMaskEdit; // Outras Variaveis FExecute: Boolean; FForm: TInfraGUIBuilderForm; FGUI: IGUI; FGUIOriginal: IGUI; function GetGUI: IGUI; procedure SetGUI(const Value: IGUI); function GetForm: TInfraGUIBuilderForm; procedure SetForm(const Value: TInfraGUIBuilderForm); protected procedure InterfarceToObject; procedure ObjectToInterface(UpdateListViewOnly: Boolean); public function Execute: Boolean; property Form: TInfraGUIBuilderForm read GetForm write SetForm; property GUI: IGUI read GetGUI write SetGUI; end; implementation uses CustomizeScreenControl, InfraGUIBuilder, GUIAnnotation, GUIAnnotationLoaderXML; {$R *.dfm} procedure TCustomizeScreen.FormDestroy(Sender: TObject); begin editTitle.Free; combCaptionPosition.Free; editHeight.Free; editWidth.Free; combItemLayout.Free; editPaddingLeft.Free; editPaddingTop.Free; editPaddingRight.Free; editPaddingBottom.Free; LayoutManager1.Free; end; procedure TCustomizeScreen.FormCreate(Sender: TObject); begin LayoutManager1 := TLayoutManager.Create(Self); with LayoutManager1 do begin SetBounds(0, 0, 719, 127); AlignMode := alTop; end; editTitle := TEdit.Create(Self); editTitle.Parent := Self; combCaptionPosition := TComboBox.Create(Self); with combCaptionPosition do begin Parent := Self; Style := csDropDownList; ItemHeight := 13; TabOrder := 0; Items.Clear; Items.Add('Above'); Items.Add('Below'); Items.Add('Left'); Items.Add('Right'); end; editHeight := TMaskEdit.Create(Self); editHeight.Parent := Self; editWidth := TMaskEdit.Create(Self); editWidth.Parent := Self; combItemLayout := TComboBox.Create(Self); with combItemLayout do begin Parent := Self; Name := 'combItemLayout'; Style := csDropDownList; Items.Clear; Items.Add('Horizontal'); Items.Add('Vertical'); end; editPaddingLeft := TMaskEdit.Create(Self); with editPaddingLeft do begin Parent := Self; Name := 'editPaddingLeft'; EditMask := '99;1; '; MaxLength := 2; Text := ' '; end; editPaddingTop := TMaskEdit.Create(Self); with editPaddingTop do begin Parent := Self; Name := 'editPaddingTop'; EditMask := '99;1; '; MaxLength := 2; Text := ' '; end; editPaddingRight := TMaskEdit.Create(Self); with editPaddingRight do begin Parent := Self; Name := 'editPaddingRight'; EditMask := '99;1; '; MaxLength := 2; Text := ' '; end; editPaddingBottom := TMaskEdit.Create(Self); with editPaddingBottom do begin Parent := Self; Name := 'editPaddingBottom'; EditMask := '99;1; '; MaxLength := 2; Text := ' '; end; with LayoutManager1 do begin Parent := Self; AlignMode := alTop; Left := 0; Top := 0; with AddControl(editTitle) do begin Name := 'Title'; Caption := 'Title'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 100; end; with AddControl(combCaptionPosition) do begin Name := 'CaptionPosition'; Caption := 'Caption Position'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 30; end; with AddControl(editHeight) do begin Name := 'Height'; Caption := 'Height'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 20; end; with AddControl(editWidth) do begin Name := 'Width'; Caption := 'Width'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 20; end; with AddControl(combItemLayout) do begin Name := 'ItemLayout'; Caption := 'Item Layout'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 30; end; with AddControl(editPaddingLeft) do begin Name := 'PaddingLeft'; Caption := 'Padding - Left'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 24.89568845618915; end; with AddControl(editPaddingTop) do begin Name := 'PaddingTop'; Caption := 'Padding - Top'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 24.89568845618915; end; with AddControl(editPaddingRight) do begin Name := 'PaddingRight'; Caption := 'Padding - Right'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 24.89568845618915; end; with AddControl(editPaddingBottom) do begin Name := 'PaddingBottom'; Caption := 'Padding - Bottom'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 24.89568845618915; end; end; lsvControlList.Align := alClient; end; { TCustomizeScreen } procedure TCustomizeScreen.actnCloseExecute(Sender: TObject); begin Close; end; procedure TCustomizeScreen.btbtCancelClick(Sender: TObject); begin Close; end; procedure TCustomizeScreen.btbtEditControlClick(Sender: TObject); var CustomizeScreenControl: TCustomizeScreenControl; begin if lsvControlList.ItemIndex >= 0 then begin CustomizeScreenControl := TCustomizeScreenControl.Create(nil); try CustomizeScreenControl.GUIControl := GUI.GUIControlList.Items[lsvControlList.ItemIndex]; if CustomizeScreenControl.Execute then begin GUI.GUIControlList.Items[lsvControlList.ItemIndex] := CustomizeScreenControl.GUIControl; ObjectToInterface(True); end; finally CustomizeScreenControl.Free; end; end; end; procedure TCustomizeScreen.btbtOKClick(Sender: TObject); var lXMLLoader: IGUIAnnotationLoader; begin InterfarceToObject; FGUIOriginal := GUI; FExecute := True; lXMLLoader := TGUIAnnotationLoaderXML.Create; lXMLLoader.FileName := GUI.GetConfigurationFileName + '.xml'; lXMLLoader.GUI := FGUIOriginal; lXMLLoader.Save; Close; end; function TCustomizeScreen.Execute: Boolean; begin ShowModal; Result := FExecute; end; procedure TCustomizeScreen.FormShow(Sender: TObject); begin ObjectToInterface(False); end; function TCustomizeScreen.GetForm: TInfraGUIBuilderForm; begin Result := FForm; end; function TCustomizeScreen.GetGUI: IGUI; begin Result := FGUI; end; procedure TCustomizeScreen.InterfarceToObject; var vValue: Variant; lpValue: TLabelPosition; laValue: TLayoutOrientation; procedure VerityScreenInstance; begin if not Assigned(GUI.Screen) then GUI.Screen := TScreen.Create; end; begin //Title vValue := editTitle.Text; if (Assigned(GUI.Screen)) and (not GUI.Screen.Title.IsNull) and (GUI.Screen.Title.AsString <> vValue) or (Form.Caption <> vValue) then begin VerityScreenInstance; GUI.Screen.Title.AsString := vValue; end; //CaptionPosition case combCaptionPosition.ItemIndex of 0: lpValue := lpAbove; 1: lpValue := lpBelow; 3: lpValue := lpRight; else lpValue := lpLeft; end; if (Assigned(GUI.Screen)) and (GUI.Screen.CaptionPosition <> lpValue) or (Form.MainLayoutManager.ItemDefCaptionPos <> lpValue) then begin VerityScreenInstance; GUI.Screen.CaptionPosition := lpValue; end; //Height vValue := StrToIntDef(Trim(editHeight.Text), 0); if (Assigned(GUI.Screen)) and (not GUI.Screen.Height.IsNull) and (GUI.Screen.Height.AsInteger <> vValue) or (Form.Height <> vValue) then begin VerityScreenInstance; GUI.Screen.Height.AsInteger := vValue; end; //Width vValue := StrToIntDef(Trim(editWidth.Text), 0); if (Assigned(GUI.Screen)) and (not GUI.Screen.Width.IsNull) and (GUI.Screen.Width.AsInteger <> vValue) or (Form.Width <> vValue) then begin VerityScreenInstance; GUI.Screen.Width.AsInteger := vValue; end; //ItemLayout if combItemLayout.ItemIndex = 1 then laValue := laVertical else laValue := laHorizontal; if (Assigned(GUI.Screen)) and (GUI.Screen.ItemLayout <> laValue) or (Form.MainLayoutManager.ItemLayout <> laValue) then begin VerityScreenInstance; GUI.Screen.ItemLayout := laValue; end; //Padding - Left vValue := StrToIntDef(Trim(editPaddingLeft.Text), 0); if (Assigned(GUI.Screen)) and (GUI.Screen.Padding.Left <> vValue) or (Form.MainLayoutManager.ItemDefPadding.Left <> vValue) then begin VerityScreenInstance; GUI.Screen.Padding.Left := vValue; end; //Padding - Top vValue := StrToIntDef(Trim(editPaddingTop.Text), 0); if (Assigned(GUI.Screen)) and (GUI.Screen.Padding.Top <> vValue) or (Form.MainLayoutManager.ItemDefPadding.Top <> vValue) then begin VerityScreenInstance; GUI.Screen.Padding.Top := vValue; end; //Padding - Right vValue := StrToIntDef(Trim(editPaddingRight.Text), 0); if (Assigned(GUI.Screen)) and (GUI.Screen.Padding.Right <> vValue) or (Form.MainLayoutManager.ItemDefPadding.Right <> vValue) then begin VerityScreenInstance; GUI.Screen.Padding.Right := vValue; end; //Padding - Bottom vValue := StrToIntDef(Trim(editPaddingBottom.Text), 0); if (Assigned(GUI.Screen)) and (GUI.Screen.Padding.Bottom <> vValue) or (Form.MainLayoutManager.ItemDefPadding.Bottom <> vValue) then begin VerityScreenInstance; GUI.Screen.Padding.Bottom := vValue; end; end; procedure TCustomizeScreen.lsvControlListDblClick(Sender: TObject); begin btbtEditControl.Click; end; procedure TCustomizeScreen.ObjectToInterface(UpdateListViewOnly: Boolean); var iIndex: Integer; It: IGUIControlIterator; lListItem : TListItem; lGUIControl: IGUIControl; sSufix: string; function GetSufix(pMeasureType: TMeasureType): string; begin if pMeasureType = mtFix then Result := 'px' else Result := '%'; end; begin if not UpdateListViewOnly then begin if Assigned(GUI.Screen) and (not GUI.Screen.Title.IsNull) then editTitle.Text := GUI.Screen.Title.AsString else editTitle.Text := GUI.Title; if (Assigned(GUI.Screen)) and (GUI.Screen.CaptionPosition <> lpLeft) then begin case GUI.Screen.CaptionPosition of lpAbove: combCaptionPosition.ItemIndex := 0; lpBelow: combCaptionPosition.ItemIndex := 1; lpRight: combCaptionPosition.ItemIndex := 3; end; end else combCaptionPosition.ItemIndex := 2; if (Assigned(GUI.Screen)) and (not GUI.Screen.Height.IsNull) then editHeight.Text := IntToStr(GUI.Screen.Height.AsInteger) else editHeight.Text := IntToStr(Form.Height); if (Assigned(GUI.Screen)) and (not GUI.Screen.Width.IsNull) then editWidth.Text := IntToStr(GUI.Screen.Width.AsInteger) else editWidth.Text := IntToStr(Form.Width); if (Assigned(GUI.Screen)) and (GUI.Screen.ItemLayout <> laHorizontal) then combItemLayout.ItemIndex := 1 else combItemLayout.ItemIndex := 0; if Assigned(GUI.Screen) then editPaddingLeft.Text := IntToStr(GUI.Screen.Padding.Left) else editPaddingLeft.Text := IntToStr(Form.MainLayoutManager.ItemDefPadding.Left); if Assigned(GUI.Screen) then editPaddingTop.Text := IntToStr(GUI.Screen.Padding.Top) else editPaddingTop.Text := IntToStr(Form.MainLayoutManager.ItemDefPadding.Top); if Assigned(GUI.Screen) then editPaddingRight.Text := IntToStr(GUI.Screen.Padding.Right) else editPaddingRight.Text := IntToStr(Form.MainLayoutManager.ItemDefPadding.Right); if Assigned(GUI.Screen) then editPaddingBottom.Text := IntToStr(GUI.Screen.Padding.Bottom) else editPaddingBottom.Text := IntToStr(Form.MainLayoutManager.ItemDefPadding.Bottom); end; if Assigned(GUI) then begin iIndex := lsvControlList.ItemIndex; lsvControlList.Items.BeginUpdate; lsvControlList.Clear; It := GUI.GUIControlList.NewIterator; while not It.IsDone do begin lGUIControl := It.CurrentItem as IGUIControl; lListItem := lsvControlList.Items.Add; lListItem.Caption := lGUIControl.PropertyName; if (Assigned(lGUIControl.ScreenItem)) and (not lGUIControl.ScreenItem.Caption.IsNull) then lListItem.SubItems.Add(lGUIControl.ScreenItem.Caption.AsString) else lListItem.SubItems.Add(lGUIControl.PropertyName); if (Assigned(lGUIControl.ScreenItem)) and (not lGUIControl.ScreenItem.Visible.AsBoolean) and (not lGUIControl.ScreenItem.Visible.IsNull) then lListItem.SubItems.Add('False') else lListItem.SubItems.Add('True'); if (Assigned(lGUIControl.ScreenItem)) and (not lGUIControl.ScreenItem.CaptionVisible.IsNull) then begin if lGUIControl.ScreenItem.CaptionVisible.AsBoolean then lListItem.SubItems.Add('True') else lListItem.SubItems.Add('False'); end else begin if lGUIControl.Item.CaptionVisible then lListItem.SubItems.Add('True') else lListItem.SubItems.Add('False'); end; if Assigned(lGUIControl.ScreenItem) then lListItem.SubItems.Add(lGUIControl.ScreenItem.PutAfter) else lListItem.SubItems.Add(''); if Assigned(lGUIControl.ScreenItem) then lListItem.SubItems.Add(lGUIControl.ScreenItem.PutBefore) else lListItem.SubItems.Add(''); if Assigned(lGUIControl.ScreenItem) then sSufix := GetSufix(lGUIControl.ScreenItem.ItemHeightMeasureType) else sSufix := GetSufix(lGUIControl.Item.HeightOptions.MeasureType); if (Assigned(lGUIControl.ScreenItem)) and (not lGUIControl.ScreenItem.ItemHeight.IsNull) then lListItem.SubItems.Add(IntToStr(lGUIControl.ScreenItem.ItemHeight.AsInteger) + sSufix) else lListItem.SubItems.Add(FloatToStr(lGUIControl.Item.HeightOptions.Size) + sSufix); if Assigned(lGUIControl.ScreenItem) then sSufix := GetSufix(lGUIControl.ScreenItem.ItemWidthMeasureType) else sSufix := GetSufix(lGUIControl.Item.WidthOptions.MeasureType); if (Assigned(lGUIControl.ScreenItem)) and (not lGUIControl.ScreenItem.ItemWidth.IsNull) then lListItem.SubItems.Add(IntToStr(lGUIControl.ScreenItem.ItemWidth.AsInteger) + sSufix) else lListItem.SubItems.Add(FloatToStr(lGUIControl.Item.WidthOptions.Size) + sSufix); It.Next; end; lsvControlList.Items.EndUpdate; lsvControlList.ItemIndex := iIndex; lsvControlList.SetFocus; end; end; procedure TCustomizeScreen.SetForm(const Value: TInfraGUIBuilderForm); begin FForm := Value; end; procedure TCustomizeScreen.SetGUI(const Value: IGUI); begin FGUIOriginal := Value; FGUI := Value.Clone; end; end.
unit IdHTTPRequestHandler; interface uses AbstractHTTPRequestHandler, IdCustomHTTPServer, DelphiDabblerSnippets, Classes; type TIdHTTPRequestInfoBinder = class(TRequestInfo) private Request : IdCustomHTTPServer.TIdHTTPRequestInfo; Response : IdCustomHTTPServer.TIdHTTPResponseInfo; protected procedure SetContent(v : string); override; function GetContent : string; override; procedure SetContentType(v : string); override; procedure SetContentStream(v : TStream); override; function GetContentStream : TStream; override; function GetContentType : string; override; public constructor Create(aRequest : IdCustomHTTPServer.TIdHTTPRequestInfo; aResponse : IdCustomHTTPServer.TIdHTTPResponseInfo); function WebRequestToURL : string; override; function WebRequestToScriptURL : string; override; function PathInfo : string; override; function Query : string; override; function RequestToTable : string; override; function WebServerHTTP : string; override; end; implementation uses TeraWMSTools; // ************************************************************** // THTTPRequestInfo // ************************************************************** constructor TIdHTTPRequestInfoBinder.Create; begin inherited Create; Request := aRequest; Response := aResponse; end; procedure TIdHTTPRequestInfoBinder.SetContent(v : string); begin Response.ContentText := v; end; procedure TIdHTTPRequestInfoBinder.SetContentType(v : string); begin Response.ContentType := v; end; procedure TIdHTTPRequestInfoBinder.SetContentStream(v : TStream); begin Response.ContentStream := v; end; function TIdHTTPRequestInfoBinder.GetContentStream : TStream; begin Result := Response.ContentStream; end; function TIdHTTPRequestInfoBinder.GetContentType : string; begin Result := Response.ContentType; end; function TIdHTTPRequestInfoBinder.GetContent : string; begin Result := Response.ContentText; end; function TIdHTTPRequestInfoBinder.Query : string; begin Result := Request.QueryParams; end; function TIdHTTPRequestInfoBinder.PathInfo : string; begin Result := Request.Document; end; function TIdHTTPRequestInfoBinder.WebRequestToScriptURL : string; begin Result := 'http://' + Request.Host + Request.Document; // je opravdu command = scriptname?? end; function TIdHTTPRequestInfoBinder.WebRequestToURL : string; var p : string; begin // Result := Request.URL; Result := 'http://' + Request.Host; // + Request.Document; p := Request.Document; if Pos(Request.Command, p) = 1 then Delete(p, 1, Length(Request.Command)); Result := Result + p; if Request.QueryParams <> '' then Result := Result + '?' + QueryFields.Text; // Query NormalizeURL(Result); end; function TIdHTTPRequestInfoBinder.RequestToTable : string; var s : string; function FormatClassString(ClassName : string) : string; begin if ClassName = '' then Result := '' else Result := ' class="' + ClassName + '"'; end; procedure AddLine(a, b : string); begin s := s + '<TR><TD' + FormatClassString('') + '>' + a + '</TD><TD>' + b + '</TD></TR>'; end; var i : integer; SubS : string; begin {$ifdef ConsoleUsed} Console.DefConsole.OpenSection('Building DebugRequest'); {$endif} s := '<TABLE ID="tblTable"' + FormatClassString('') + '>'; SubS := ''; for i := 0 to QueryFields.Count - 1 do SubS := SubS + QueryFields[i] + '<br>'; AddLine('Queries', SubS); AddLine('ExeFileName', ParamStr(0)); AddLine('Accept', Request.Accept); AddLine('AuthPassword', Request.AuthPassword); AddLine('AuthUsername', Request.AuthUsername); AddLine('Command', Request.Command); // AddLine('AuthUsername', Request.Cookies); AddLine('Document', Request.Document); AddLine('Params.Text', Request.Params.Text); AddLine('RawHTTPCommand', Request.RawHTTPCommand); AddLine('RemoteIP', Request.RemoteIP); AddLine('RemoteIP', Request.RemoteIP); AddLine('UnparsedParams', Request.UnparsedParams); AddLine('FormParams', Request.FormParams); AddLine('QueryParams', URLDecode(Request.QueryParams)); AddLine('Version', Request.Version); AddLine('Authentication', Request.AuthUsername); AddLine('Accept', Request.Accept); AddLine('AcceptCharSet', Request.AcceptCharSet); AddLine('AcceptEncoding', Request.AcceptEncoding); AddLine('AcceptLanguage', Request.AcceptLanguage); AddLine('Host', Request.Host); AddLine('From', Request.From); AddLine('Password', Request.Password); AddLine('Referer', Request.Referer); AddLine('UserAgent', Request.UserAgent); AddLine('Username', Request.Username); AddLine('ProxyConnection', Request.ProxyConnection); // AddLine('AuthUsername', Request.RawHeaders); AddLine('CacheControl', Request.CacheControl); AddLine('Connection', Request.Connection); AddLine('ContentEncoding', Request.ContentEncoding); AddLine('ContentLanguage', Request.ContentLanguage); AddLine('ContentType', Request.ContentType); AddLine('ContentVersion', Request.ContentVersion); // AddLine('AuthUsername', Request.CustomHeaders); AddLine('Pragma', Request.Pragma); AddLine('GetNamePath', Request.GetNamePath); AddLine('ClassName', Request.ClassName); s := s + '</TABLE>'; Result := s; {$ifdef ConsoleUsed} Console.DefConsole.CloseSection; {$endif} end; function TIdHTTPRequestInfoBinder.WebServerHTTP : string; begin Result := 'http://' + Request.Host; end; end.
unit uJxdHashTableManage; interface uses Windows, SysUtils, uJxdUdpDefine, uJxdHashCalc, uJxdDataStruct, uJxdDataStream, uJxdUdpSynchroBasic, uJxdMemoryManage; type PUserListInfo = ^TUserListInfo; PHashListInfo = ^THashListInfo; PUserTableInfo = ^TUserTableInfo; PHashTableInfo = ^THashTableInfo; TUserListInfo = record //SizeOf: 8 FUserInfo: PUserTableInfo; FNext: PUserListInfo; end; THashListInfo = record //SizeOf: 8 FHashInfo: PHashTableInfo; FNext: PHashListInfo; end; //用户表 TUserTableInfo = record FUserID: Cardinal; FIP: Cardinal; FPort: Word; FHashCount: Integer; FHashList: PHashListInfo; end; //文件HASH表 THashTableInfo = record FFileHash: TxdHash; FWebHash: TxdHash; FUserCount: Integer; FUserList: PUserListInfo; end; TxdHashTableManage = class public constructor Create; destructor Destroy; override; {处理命令} //用户更新HASH表 procedure DoHandleCmd_UpdateFileHashTable(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); //在线服务器通知用户下线 procedure DoHandleCmd_ClientShutdown(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); //用户搜索HASH procedure DoHandleCmd_SearchFileUser(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); //操作 function CurShareUserCount: Integer; inline; procedure LoopUserList(const ALoopCallBack: TOnLoopNode); private {内存管理对象} FUserTableMem: TxdFixedMemoryManager; //用户表内存管理器 FHashTableMem: TxdFixedMemoryManager; //HASH表内存管理器 FLinkNodeMem: TxdFixedMemoryManager; //TUserListInfo THashListInfo 两者使用内存管理器 {数据操作对象} FUserList: THashArray; //用户列表 FFileHashList: THashArrayEx; //文件HASH列表 FWebHashList: THashArrayEx; //WEB HASH 列表 FLock: TRTLCriticalSection; FMaxUserTableCount: Integer; FMaxHashTableCount: Integer; FActive: Boolean; FAllowDelHashIP: Cardinal; FUDP: TxdUdpSynchroBasic; procedure SetMaxHashTableCount(const Value: Integer); procedure SetMaxUserTableCount(const Value: Integer); procedure SetActive(const Value: Boolean); procedure Lock; inline; procedure UnLock; inline; function NewUserTable: PUserTableInfo; inline; //申请新的用户表 function NewHashTable: PHashTableInfo; inline; //申请HASH共享表 function NewUserLinkNode: PUserListInfo; inline; //连接结点 function NewHashLinkNode: PHashListInfo; inline; //连接结点 function FindHashInfo(const AFileHash: Boolean; const AHash: TxdHash; const AIsDelNode: Boolean): PHashTableInfo; //User表 与 Hash表之间的关联 function RelationUser_Hash(const AHash: PHashTableInfo; const AUser: PUserTableInfo): Boolean; //True: 新增; False: 已经存在 procedure ActiveManage; procedure UnActiveManage; public property Active: Boolean read FActive write SetActive; property Udp: TxdUdpSynchroBasic read FUDP write FUDP; property AllowDelHashIP: Cardinal read FAllowDelHashIP write FAllowDelHashIP; //此IP用于删除用户共享信息,指定0则所有IP都可以删除 property MaxUserTableCount: Integer read FMaxUserTableCount write SetMaxUserTableCount; //最大用户表数量 property MaxHashTableCount: Integer read FMaxHashTableCount write SetMaxHashTableCount; //最大共享HASH数量 end; implementation uses uJxdFileShareManage; const CtUserTableInfoSize = SizeOf(TUserTableInfo); CtHashTableInfoSize = SizeOf(THashTableInfo); CtLinkNodeSize = 8; { TxdHashTableManage } procedure TxdHashTableManage.ActiveManage; var nCount: Integer; begin try if not Assigned(FUDP) then begin OutputDebugString( '必须设置UDP' ); Exit; end; InitializeCriticalSection( FLock ); FUserTableMem := TxdFixedMemoryManager.Create( CtUserTableInfoSize, FMaxUserTableCount ); FHashTableMem := TxdFixedMemoryManager.Create( CtHashTableInfoSize, FMaxHashTableCount ); if FMaxUserTableCount > FMaxHashTableCount then nCount := FMaxUserTableCount else nCount := FMaxHashTableCount; FLinkNodeMem := TxdFixedMemoryManager.Create( CtLinkNodeSize, nCount ); FUserList := THashArray.Create; FUserList.HashTableCount := FMaxUserTableCount div 3; FUserList.MaxHashNodeCount := FMaxUserTableCount; FUserList.Active := True; FFileHashList := THashArrayEx.Create; FFileHashList.HashTableCount := FMaxHashTableCount div 3; FFileHashList.MaxHashNodeCount := FMaxHashTableCount; FFileHashList.Active := True; FWebHashList := THashArrayEx.Create; FWebHashList.HashTableCount := FMaxHashTableCount div 3; FWebHashList.MaxHashNodeCount := FMaxHashTableCount; FWebHashList.Active := True; FActive := True; except UnActiveManage; end; end; function TxdHashTableManage.RelationUser_Hash(const AHash: PHashTableInfo; const AUser: PUserTableInfo): Boolean; var p, pParent: PUserListInfo; p1, pHashLink: PHashListInfo; begin Result := True; p := AHash^.FUserList; pParent := p; while Assigned(p) do begin if Integer(p^.FUserInfo) = Integer(AUser) then begin Result := False; Break; end; pParent := p; p := p^.FNext; end; if Result then begin p := NewUserLinkNode; p^.FUserInfo := AUser; p^.FNext := nil; Inc(AHash^.FUserCount); if Assigned(pParent) then pParent^.FNext := p else AHash^.FUserList := p; pHashLink := NewHashLinkNode; pHashLink^.FHashInfo := AHash; pHashLink^.FNext := nil; Inc( AUser^.FHashCount ); p1 := AUser^.FHashList; if Assigned(p1) then begin while Assigned(p1^.FNext) do p1 := p1^.FNext; p1^.FNext := pHashLink; end else AUser^.FHashList := pHashLink; end; end; constructor TxdHashTableManage.Create; begin FMaxUserTableCount := 10000; FMaxHashTableCount := 50000; FUserTableMem := nil; FHashTableMem := nil; FLinkNodeMem := nil; FActive := False; FAllowDelHashIP := 0; end; function TxdHashTableManage.CurShareUserCount: Integer; begin if Assigned(FUserList) then Result := FUserList.Count else Result := 0; end; destructor TxdHashTableManage.Destroy; begin Active := False; inherited; end; procedure TxdHashTableManage.DoHandleCmd_ClientShutdown(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); var pCmd: PCmdClientShutdownInfo; pUser, p1: PUserTableInfo; pHashLink, pTemp: PHashListInfo; pHash: PHashTableInfo; pParentLink, pUserLink: PUserListInfo; begin if (FAllowDelHashIP <> 0) and (AIP <> FAllowDelHashIP) then begin OutputDebugString( '非指定IP要求删除用户共享HASH,不允许的操作' ); Exit; end; if ABufLen <> CtCmdClientShutdownInfoSize then begin OutputDebugString( 'ClientShutdown命令长度不正确' ); Exit; end; pCmd := PCmdClientShutdownInfo(ABuffer); Lock; try if not FUserList.Find(pCmd^.FShutDownID, Pointer(pUser), True) then Exit; pHashLink := pUser^.FHashList; while Assigned(pHashLink) do begin pHash := pHashLink^.FHashInfo; if pHash^.FUserCount <= 1 then begin if not HashCompare(pHash^.FFileHash, CtEmptyHash) then FindHashInfo(True, pHash^.FFileHash, True); if not HashCompare(pHash^.FWebHash, CtEmptyHash) then FindHashInfo(False, pHash^.FWebHash, True); pUserLink := pHash^.FUserList; FLinkNodeMem.FreeMem( pUserLink ); FHashTableMem.FreeMem( pHash ); end else begin Dec( pHash^.FUserCount ); pUserLink := pHash^.FUserList; pParentLink := nil; while Assigned(pUserLink) do begin p1 := pUserLink^.FUserInfo; if Integer(p1) = Integer(pUser) then begin if Assigned(pParentLink) then pParentLink^.FNext := pUserLink^.FNext else pHash^.FUserList := pHash^.FUserList^.FNext; FLinkNodeMem.FreeMem( pUserLink ); Break; end; pParentLink := pUserLink; pUserLink := pUserLink^.FNext; end; end; //释放连接结点 pTemp := pHashLink; pHashLink := pTemp^.FNext; FLinkNodeMem.FreeMem( pTemp ); end; //释放用户占用内存 FUserTableMem.FreeMem(pUser); finally UnLock; end; end; procedure TxdHashTableManage.DoHandleCmd_SearchFileUser(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); var pCmd: PCmdSearchFileUserInfo; pHash: PHashTableInfo; oSendStream: TxdStaticMemory_16K; i: Integer; nSendUserCount: Word; pLink: PUserListInfo; pUser: PUserTableInfo; nPos, nSize: Int64; begin if ABufLen <> CtCmdSearchFileUserInfoSize then begin OutputDebugString( '搜索命令长度不正确' ); Exit; end; pCmd := PCmdSearchFileUserInfo( ABuffer ); oSendStream := TxdStaticMemory_16K.Create; Lock; try if pCmd^.FHashStyle = hsFileHash then pHash := FindHashInfo(True, TxdHash(pCmd^.FHash), False) else pHash := FindHashInfo(False, TxdHash(pCmd^.FHash), False); if AIsSynchroCmd then FUDP.AddSynchroSign( oSendStream, ASynchroID ); FUDP.AddCmdHead( oSendStream, CtCmdReply_SearchFileUser ); oSendStream.WriteByte( Byte(pCmd^.FHashStyle) ); oSendStream.WriteLong( pCmd^.FHash, CtHashSize ); if not Assigned(pHash) then begin oSendStream.WriteWord( 0 ); nSize := oSendStream.Position; end else begin nPos := oSendStream.Position; oSendStream.Position := oSendStream.Position + 2; nSendUserCount := 0; pLink := pHash^.FUserList; for i := 0 to pHash^.FUserCount - 1 do begin if nSendUserCount >= CtMaxSearchUserCount then Break; pUser := pLink^.FUserInfo; if pUser^.FUserID <> pCmd^.FCmdHead.FUserID then begin oSendStream.WriteCardinal( pUser^.FUserID ); nSendUserCount := nSendUserCount + 1; end; pLink := pLink^.FNext; end; nSize := oSendStream.Position; oSendStream.Position := nPos; oSendStream.WriteWord( nSendUserCount ); end; FUDP.SendBuffer( AIP, APort, oSendStream.Memory, nSize ); finally UnLock; oSendStream.Free; end; end; procedure TxdHashTableManage.DoHandleCmd_UpdateFileHashTable(const AIP: Cardinal; const APort: Word; const ABuffer: pAnsiChar; const ABufLen: Cardinal; const AIsSynchroCmd: Boolean; const ASynchroID: Word); var pCmd: PCmdUpdateFileHashTableInfo; Stream: TxdOuterMemory; nUserID: Cardinal; FileHash, WebHash: TxdHash; pUser: PUserTableInfo; pHash: PHashTableInfo; s: TReplySign; oSendStream: TxdStaticMemory_64Byte; bFindByFileHash, bFileHashOK, bWebHashOK: Boolean; label llSendCmd; begin s := rsSuccess; if ABufLen < CtCmdUpdateFileHashTableInfoSize then begin s := rsError; OutputDebugString( '命令:TCmdUpdateFileHashTableInfo 长度不正确' ); goto llSendCmd; end; pCmd := PCmdUpdateFileHashTableInfo(ABuffer); nUserID := pCmd^.FCmdHead.FUserID; //8 if pCmd^.FHashCount * CtHashSize * 2 <> ABufLen - 8 then begin s := rsError; OutputDebugString( '命令:TCmdUpdateFileHashTableInfo 中指定HASH数量与内存长度不一致' ); goto llSendCmd; end; Lock; Stream := TxdOuterMemory.Create; try if not FUserList.Find(nUserID, Pointer(pUser), False) then begin pUser := NewUserTable; pUser^.FUserID := nUserID; pUser^.FIP := AIP; pUser^.FPort := APort; pUser^.FHashCount := 0; pUser^.FHashList := nil; FUserList.Add( nUserID, pUser ); end; Stream.InitMemory( ABuffer, ABufLen ); Stream.Position := 8; //超过包头 while (Stream.Size - Stream.Position) >= CtHashSize * 2 do begin Stream.ReadLong( FileHash, CtHashSize ); Stream.ReadLong( WebHash, CtHashSize ); bFindByFileHash := False; bFileHashOK := not IsEmptyHash(FileHash); bWebHashOK := not IsEmptyHash(WebHash); pHash := nil; if not bFileHashOK and not bWebHashOK then Continue; if bFileHashOK then pHash := FindHashInfo( True, FileHash, False ); if Assigned(pHash) then bFindByFileHash := True else if bWebHashOK then pHash := FindHashInfo( False, WebHash, False ); if not Assigned(pHash) then begin //新增 pHash := NewHashTable; pHash^.FFileHash := FileHash; pHash^.FWebHash := WebHash; pHash^.FUserCount := 0; pHash^.FUserList := nil; if bFileHashOK then FFileHashList.Add( HashToID(pHash^.FFileHash), pHash ); if bWebHashOK then FWebHashList.Add( HashToID(pHash^.FWebHash), pHash ); end else begin //已经存在的,进行更新, 当由FileHash查找到节点时,只能修改WebHash //当从WebHash查找到节点时,除非FileHash为空,否则不能修改FileHash if bFindByFileHash then begin if bWebHashOK and not HashCompare(pHash^.FWebHash, WebHash) then begin if not IsEmptyHash(pHash^.FWebHash) then FindHashInfo( False, pHash^.FWebHash, True ); pHash^.FWebHash := WebHash; FWebHashList.Add( HashToID(pHash^.FWebHash), pHash ); end; end else begin if bFileHashOK and IsEmptyHash(pHash^.FFileHash) then begin pHash^.FFileHash := FileHash; FFileHashList.Add( HashToID(pHash^.FFileHash), pHash ); end; end; end; RelationUser_Hash(pHash, pUser); end; finally UnLock; Stream.Free; end; llSendCmd: oSendStream := TxdStaticMemory_64Byte.Create; try if AIsSynchroCmd then FUDP.AddSynchroSign( oSendStream, ASynchroID ); FUDP.AddCmdHead( oSendStream, CtCmdReply_UpdateFileHashTable ); oSendStream.WriteByte( Byte(s) ); FUDP.SendBuffer( AIP, APort, oSendStream.Memory, oSendStream.Position ); finally oSendStream.Free; end; end; function TxdHashTableManage.FindHashInfo(const AFileHash: Boolean; const AHash: TxdHash; const AIsDelNode: Boolean): PHashTableInfo; var nID: Cardinal; pNode: PHashNode; p: PHashTableInfo; begin Result := nil; nID := HashToID(AHash); if AFileHash then begin pNode := FFileHashList.FindBegin(nID); try while Assigned(pNode) do begin p := pNode^.NodeData; if HashCompare(p^.FFileHash, AHash) then begin Result := p; if AIsDelNode then FFileHashList.FindDelete( pNode ); Break; end; pNode := FFileHashList.FindNext( pNode ); end; finally FFileHashList.FindEnd; end; end else begin pNode := FWebHashList.FindBegin(nID); try while Assigned(pNode) do begin p := pNode^.NodeData; if HashCompare(p^.FWebHash, AHash) then begin Result := p; if AIsDelNode then FWebHashList.FindDelete( pNode ); Break; end; pNode := FWebHashList.FindNext( pNode ); end; finally FWebHashList.FindEnd; end; end; end; procedure TxdHashTableManage.Lock; begin EnterCriticalSection( FLock ); end; procedure TxdHashTableManage.LoopUserList(const ALoopCallBack: TOnLoopNode); begin if Assigned(FUserList) then FUserList.Loop( ALoopCallBack ); end; function TxdHashTableManage.NewHashLinkNode: PHashListInfo; begin if not FLinkNodeMem.GetMem(Pointer(Result)) then Result := nil; end; function TxdHashTableManage.NewHashTable: PHashTableInfo; begin if not FHashTableMem.GetMem(Pointer(Result)) then Result := nil; end; function TxdHashTableManage.NewUserLinkNode: PUserListInfo; begin if not FLinkNodeMem.GetMem(Pointer(Result)) then Result := nil; end; function TxdHashTableManage.NewUserTable: PUserTableInfo; begin if not FUserTableMem.GetMem(Pointer(Result)) then Result := nil; end; procedure TxdHashTableManage.SetActive(const Value: Boolean); begin if FActive <> Value then begin if Value then ActiveManage else UnActiveManage; end; end; procedure TxdHashTableManage.SetMaxHashTableCount(const Value: Integer); begin FMaxHashTableCount := Value; end; procedure TxdHashTableManage.SetMaxUserTableCount(const Value: Integer); begin FMaxUserTableCount := Value; end; procedure TxdHashTableManage.UnActiveManage; begin FActive := False; DeleteCriticalSection( FLock ); FreeAndNil( FUserTableMem ); FreeAndNil( FHashTableMem ); FreeAndNil( FLinkNodeMem ); FreeAndNil( FUserList ); FreeAndNil( FFileHashList ); FreeAndNil( FWebHashList ); end; procedure TxdHashTableManage.UnLock; begin LeaveCriticalSection( FLock ); end; end.
unit Queue; interface uses dialogs,sysutils; type TInfo = String; PElement = ^TElement; TElement = record info: TInfo; next: PElement; end; TMyQueue = class public constructor Create; //создание очереди destructor Destroy; //очищение procedure Add(i: TInfo); //добавление элемента в конец очереди function isAviable: boolean; //проверка на заполненность очереди function Get: TInfo; //изъятие элемента function GetValue(n:Integer) : TInfo; //получение значения n-ного элемента function GetN(k:integer):TInfo; //изъятие n-ного элемента procedure Delete(n:integer); //удаление n-ного элемента procedure ShowQueue; private headQueue: PElement; tailQueue: PElement; procedure InitQueue; //инициализация procedure FreeQueue; //освобождение end; implementation constructor TMyQueue.Create; begin inherited; InitQueue; end; destructor TMyQueue.Destroy; begin FreeQueue; inherited; end; procedure TMyQueue.InitQueue; begin headQueue := nil; tailQueue := nil; end; procedure TMyQueue.FreeQueue; var ok: boolean; i: real; begin ok := true; while isAviable do Get; end; procedure TMyQueue.Add(i: TInfo); var p: PElement; begin new(p); p.info := i; p.next := nil; if headQueue = nil then begin headQueue := p; tailQueue := p; end else begin headQueue.next := p; headQueue := p; end; end; function TMyQueue.Get: TInfo; var p: PElement; begin if not (Tailqueue=headqueue) then begin result := tailQueue.info; p := tailQueue; tailQueue := tailQueue.next; dispose(p); end else begin result:=HeadQueue.info; p:=HeadQueue; dispose(p); HeadQueue:=nil; TailQueue:=nil; end; end; function TMyQueue.GetValue(n:integer):TInfo; var i:integer; p : PElement; begin p:=TailQueue; if p=nil then result:='' else for i := 1 to n do if i<>n then p:=p.next; if p.info<>'' then result:=p.info; end; function TMyQueue.isAviable: boolean; begin result := true; if tailQueue = nil then begin result := false; exit; end; end; procedure TMyQueue.ShowQueue; var p: PElement; n: integer; s: string; begin p := tailQueue; while p <> nil do begin s := s + p.info + ' '; p := p.next; end; ShowMessage(s); end; function TMyQueue.GetN(k: Integer):TInfo; var i:integer; p: PElement; begin if k=1 then result:=Get else begin result:=GetValue(k); Delete(k); end; end; procedure TMyQueue.Delete(n: Integer); var p,z:PElement; i:integer; begin if n=1 then begin new(p); p.info:=Get; dispose(p); end else begin z:=TailQueue; for I := 1 to n-2 do z:=z.next; p:=z.next; z.next:=p.next; dispose(p); end; end; end.
unit ModuleMgr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, ToolWin, RegIntf, ImgList; type TModuleType = (mtUnKnow, mtBPL, mtDLL); PModuleRec = ^TModuleRec; TModuleRec = record Key: String; Module: string; ModuleFile: String; ModuleFileValue: String; PathInvalid: Boolean; ModuleType: TModuleType; end; Tfrm_ModuleMgr = class(TForm) ToolBar1: TToolBar; btn_InstallModule: TToolButton; btn_UnInstalll: TToolButton; lv_Module: TListView; ToolButton1: TToolButton; ToolButton3: TToolButton; ImageList1: TImageList; btn_Edit: TToolButton; OpenDialog1: TOpenDialog; procedure ToolButton3Click(Sender: TObject); procedure lv_ModuleDeletion(Sender: TObject; Item: TListItem); procedure lv_ModuleInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); procedure lv_ModuleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure btn_EditClick(Sender: TObject); procedure lv_ModuleDblClick(Sender: TObject); procedure btn_UnInstalllClick(Sender: TObject); procedure btn_InstallModuleClick(Sender: TObject); private procedure InstallModule(const ModuleFile: string); procedure UnInstallModule(const ModuleFile: string); procedure DisModuleInList(const Key: String); procedure UpdateValue(mRec: PModuleRec; Load: Boolean); function ModuleType(const ModuleFile: String): TModuleType; public constructor Create(AOwner: TComponent); end; var frm_ModuleMgr: Tfrm_ModuleMgr; implementation uses SysSvc, ModuleInstallerIntf; {$R *.dfm} //Type // TPro_UnInstallModule=procedure(Reg:IRegistry); // TPro_InstallModule=procedure(Reg:IRegistry); //TPro_GetModuleClass=function :TModuleClass; const ModuleKey = 'SYSTEM\LOADMODULE'; Value_Module = 'Module';//注册表关键字。。。 Value_Load = 'load';// procedure Tfrm_ModuleMgr.InstallModule(const ModuleFile: string); var ModuleInstaller: IModuleInstaller; msg: String; begin ModuleInstaller := SysService as IModuleInstaller; try ModuleInstaller.InstallModule(ModuleFile); except on E: Exception do begin msg := Format('错误:%s,可能[%s]不是系统支持的模块!', [E.Message, ModuleFile]); Application.MessageBox(pchar(msg), '安装模块', MB_OK + MB_ICONERROR); end; end; end; procedure Tfrm_ModuleMgr.UnInstallModule(const ModuleFile: string); var ModuleInstaller: IModuleInstaller; msg: String; begin ModuleInstaller := SysService as IModuleInstaller; try ModuleInstaller.UnInstallModule(ModuleFile); except on E: Exception do begin msg := Format('卸载模块失败,错误:%s', [E.Message]); Application.MessageBox(pchar(msg), '卸载模块', MB_OK + MB_ICONERROR); end; end; end; procedure Tfrm_ModuleMgr.ToolButton3Click(Sender: TObject); begin self.Close; end; constructor Tfrm_ModuleMgr.Create(AOwner: TComponent); begin inherited Create(AOwner); self.lv_module.Clear; self.DisModuleInList(ModuleKey); end; function FormatPath(const s: string): string; const Var_AppPath = '($APP_PATH)'; begin Result := StringReplace(s, Var_AppPath, ExtractFilePath(Paramstr(0)), [rfReplaceAll, rfIgnoreCase]); end; procedure Tfrm_ModuleMgr.DisModuleInList(const Key: String); var SubKeyList, ValueList, aList: TStrings; i: Integer; valueStr: string; valueName, vStr, ModuleFile, Load: WideString; NewItem: TListITem; mRec: PModuleRec; ModuleFileValue: String; Reg: IRegistry; begin SubKeyList := TStringList.Create; ValueList := TStringList.Create; aList := TStringList.Create; try Reg := SysService as IRegistry; if Reg.OpenKey(Key, False) then begin //处理值 Reg.GetValueNames(ValueList); for i := 0 to ValueList.count - 1 do begin aList.Clear; ValueName := ValueList[i]; if Reg.ReadString(ValueName, vStr) then begin ValueStr := AnsiUpperCase(vStr); ExtractStrings([';'], [], Pchar(valueStr), aList); ModuleFileValue := aList.Values[Value_Module]; ModuleFile := FormatPath(ModuleFileValue); Load := aList.Values[Value_Load]; NewItem := self.lv_module.Items.Add; New(mRec); mRec^.Key := Key; mRec^.Module := ValueName; mRec^.ModuleFile := ModuleFile; mRec^.ModuleFileValue := ModuleFileValue; mRec^.PathInvalid := not FileExists(ModuleFile); mRec^.ModuleType := self.ModuleType(ModuleFile); NewItem.Data := mRec; NewItem.SubItems.Add(ValueName); NewItem.SubItems.Add(ModuleFileValue); NewItem.Checked := CompareText(Load, 'TRUE') = 0; if mRec^.PathInvalid then NewItem.ImageIndex := 4 else NewItem.ImageIndex := 3; end; end; end; //向下查找 Reg.GetKeyNames(SubKeyList); for i := 0 to SubKeyList.Count - 1 do DisModuleInList(Key + '\' + SubKeyList[i]);//递归 finally SubKeyList.Free; ValueList.Free; aList.Free; end; end; procedure Tfrm_ModuleMgr.lv_ModuleDeletion(Sender: TObject; Item: TListItem); begin if Assigned(Item.Data) then Dispose(PModuleRec(Item.Data)); end; procedure Tfrm_ModuleMgr.lv_ModuleInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); begin if Assigned(Item.Data) then begin if PModuleRec(Item.Data)^.PathInvalid then InfoTip := Format('模块[%s]路径不正确,请重新安装!', [PModuleRec(Item.Data)^.Module]); end; end; procedure Tfrm_ModuleMgr.lv_ModuleMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var HitTest: THitTests; Item: TListItem; begin HitTest := self.lv_module.GetHitTestInfoAt(X, Y); if (htOnStateIcon in HitTest) then begin Item := self.lv_module.GetItemAt(X, Y); if Item <> nil then begin if Assigned(Item.Data) then self.UpdateValue(PModuleRec(Item.Data), Item.Checked); end; end; end; function Tfrm_ModuleMgr.ModuleType(const ModuleFile: String): TModuleType; var ext: String; begin ext := ExtractFileExt(ModuleFile); if SameText(ext, '.bpl') then Result := mtBPL else if SameText(ext, '.dll') then Result := mtDLL else Result := mtUnknow; end; procedure Tfrm_ModuleMgr.UpdateValue(mRec: PModuleRec; Load: Boolean); const V_Str = 'Module=%s;Load=%s'; var Value, LoadStr: String; Reg: IRegistry; begin Reg := SysService as IRegistry; if Reg.OpenKey(mRec^.Key) then begin if Load then LoadStr := 'True' else LoadStr := 'False'; Value := Format(V_Str, [mRec^.ModuleFileValue, LoadStr]); Reg.WriteString(mRec^.Module, Value); end; end; procedure Tfrm_ModuleMgr.btn_EditClick(Sender: TObject); var Path: String; mRec: PModuleRec; begin if Assigned(self.lv_module.Selected) then begin if Assigned(self.lv_module.Selected.Data) then begin mRec := PModuleRec(self.lv_module.Selected.Data); Path := mRec^.ModuleFileValue; if InputQuery('编辑', '编辑模块路径:' + #13#10 + '($APP_PATH)=程序所在目录', Path) then begin mRec^.ModuleFileValue := Path; mRec^.ModuleFile := FormatPath(Path); self.UpdateValue(mRec, self.lv_module.Selected.Checked); self.lv_module.Selected.SubItems[1] := Path; if FileExists(mRec^.ModuleFile) then self.lv_module.Selected.ImageIndex := 3 else self.lv_module.Selected.ImageIndex := 4; end; end; end; end; procedure Tfrm_ModuleMgr.lv_ModuleDblClick(Sender: TObject); begin self.btn_Edit.Click; end; procedure Tfrm_ModuleMgr.btn_UnInstalllClick(Sender: TObject); var mRec: PModuleRec; Reg: IRegistry; begin if Assigned(self.lv_module.Selected) then begin if Assigned(self.lv_module.Selected.Data) then begin mRec := PModuleRec(self.lv_module.Selected.Data); if FileExists(mRec^.ModuleFile) then begin if MessageBox(self.Handle, pchar('你确定要卸载[' + mRec^.Module + ']模块吗?') , '卸载模块', MB_YESNO + MB_ICONQUESTION) <> IDYES then exit; try self.UnInstallModule(mRec^.ModuleFile); self.lv_module.Selected.Delete; except on E: Exception do MessageBox(self.Handle, pchar('卸载出错:' + E.Message), '卸载模块', MB_OK + MB_ICONERROR); end; end else begin if MessageBox(self.Handle, pchar('模块[' + mRec^.Module + ']路径不正确,无法卸载,是否直接从注册表删除该模块信息?'), '卸载模块', MB_YESNO + MB_ICONQUESTION) = IDYES then begin Reg := SysService as IRegistry; if Reg.OpenKey(mRec^.Key) then begin Reg.DeleteValue(mRec^.Module); self.lv_module.Selected.Delete; end; end; end; end; end; end; procedure Tfrm_ModuleMgr.btn_InstallModuleClick(Sender: TObject); var i: Integer; FileName: string; begin if self.OpenDialog1.Execute then begin for i := 0 to self.OpenDialog1.Files.Count - 1 do begin try FileName := self.OpenDialog1.Files[i]; self.InstallModule(FileName); //刷新 self.lv_module.Clear; self.DisModuleInList(ModuleKey); except on E: Exception do MessageBox(self.Handle, pchar('安装模块失败:' + E.Message), '安装模块', MB_OK + MB_ICONERROR); end; end; end; end; end.
{ type cellule <- enregistrement x & y :ENTIER FINENREGISTREMENT TYPE bateau : tableau de 1 a n de cellule Bataille navale : Réaliser l'algo et le Pascal du jeu la bataille navale. Vous utilierez pour représenter la grille du jeu un type record nommé case afin de décrire les cases occupées par les bateaux. De meme, un bateau sera décris par un enxemble de cases et la flotte de bateau à couler sera representée par un ensemle de bateau. Travail a faire : 1. Ecrire un type enregistrement case composé de deux champs ; ligne et colonne de type entiers 2. Ecrire un type bateau composé d'un ensemble de n cases 3. Ecrire la structure flotte composé d'un ensemble de bateaux. 4. Ecrire une fonction de création d'une case. Elle prends en paramètre la ligne et la colonn associée a la case. 5. Ecrire une fonction de comparaison de deux case. Elle renverra vrai ou faux selon le cas. 6. Ecrire une fonction de création de bateaux, elle renverra un type enregistrement bateau correctement remplie. 7. Ecrire un fonction qui vérifie qu'un case appartient a un bateau . Elle renvera vrai ou faux selon le cas. Cette fonction de verfication devra utiliser votre fonction de comparaison de case. 8. Ecrire une fonction qui vérifie qu'un case appartient a une flotte de bateau. Cette fonction devra utiliser votre fonction de verification pour un bateau. 9. Bonne chance. Programme complet. programme Bataille TYPE case DEBUTENREGISTREMENT x,y : entier FINENREGISTREMENET TYPE tabbateau <- tableau de 1 a 3 de case type BATEAU DEBUTENREGISTREMENT tabBateau <- tabBateau FINENREGISTREMENT TYPE tabflotte <- tableau de 1 a 4 de bateau type flotte DEBUTENREGISTREMENT tabflotte <- tabflotte FINENREGISTREMENT fonction comparerCase(case1 : case, case2 : case) :booléen //On compare le contenu de deux cases. Si il est égal, on revoie Vrai. Sinon, on renvoie faux. DEBUTFONCTION SI case1 = case2 ALORS comparerCase = VRAI SINON comparerCase = FAUX FINFONCTION fonction creerBateau( numero : entier) :bateau VAR boat :bateau; i :entier; DEBUTFONCTION SI numero = 1 ALORS POUR i de 1 a 3 FAIRE boat.tabbateau[i].x = 3; POUR i de 1 a 3 FAIRE //On créé le bateau 1 commençant en 3.2 et finissant en 3.4 boat.tabbateau[i].y = i+1; SI numero = 2 ALORS POUR i de 1 a 3 FAIRE boat.tabbateau[i].x = 1; POUR i de 1 a 3 FAIRE //On créé le bateau 2 commençant en 1.8 et finissant en 1.10 boat.tabbateau[i].y = 7+i; SI numero = 3 ALORS POUR i de 1 a 3 FAIRE boat.tabbateau[i].x = i+4; POUR i de 1 a 3 FAIRE //On créé le bateau 3 commençant en 3.2 et finissant en 3.4 boat.tabbateau[i].y = 8; SI numero = 4 ALORS POUR i de 1 a 3 FAIRE boat.tabbateau[i].x = 9; POUR i de 1 a 3 FAIRE //On créé le bateau 4 commençant en 3.2 et finissant en 3.4 boat.tabbateau[i].y = i+3; FINFONCTION fonction checkBateau (case : case, flotte : flotte); VAR i,j :entier; DEBUTFONCTION pour i de 1 a 4 pour j de 1 a 3 SI comparerCase(case.y,flotte.tabFlotte[i].tabBateau[j].y) ET comparerCase(case.x,flotte.tabFlotte[i].tabBateau[j].x) ALORS checkbateau <- VRAI; //On ultilise la fonction compare pour voir si la case entrée est la meme qu'un des cases occupés par un des bateaux de la flotte. FINPOUR //Si c'est le cas, on renvoie vrai, sinon, on revoie faux. FINPOUR checkbateau <- FAUX; FINFONCTION POGRAMME bataille VAR flottejoueur :flotte; xentre,yentre,i,hits :entier; casentre :case; bonnetnre :array [1..12] of integer //Ce tableau sert a stocker les bonnes coordonnées que le joueur a entré pour pouvoir éviter qu'il ne les mettents un deuxieme fois //Elles sont stockés sous la forme x*10+y. DEBUT hits <- 1 pour i e 1 a 4 faire flotte.tabflotte[i] <- creerBateau[i]; //On créé les bateaux et on les stock dnas la flotte FINPOUR repeat repeat ECRIRE "N'entrez pas une valeure que vous avez deja entré." repeat ECRIRE "Veuillez entrer la coordonnée x." //On demande les ccordoné a l'utilisateur. On n'accepte l'input que si LIRE xentre //il est entre 1 et 10 et si il ne correspond pas a un input ayant touché auparavant. until xentre =< 10 ET xentre => 10 repeat ECRIRE "Veuillez entrer la coordonée y." lire yentre until yentre =< 10 ET yentre => 10 until xentre*10+yentre <> bonnentre[1..12] casentre.x <- xentre casentre.y <- yentre SI checkBateau(casentre,flottejoueur) = VRAI ALORS bonnentre[hits] <- xentre*10+yentre //On met les coord rentrées dans le tableau pour éviter qu'elles soient rentrées nouveau. hits <- hits + 1 until hits = 12 //On répète la boucle principale jusqu'a qu'on est touché tout les zones touchables FIN. } program Bataille; uses crt; TYPE cell = record x,y : integer; END; TYPE tabbateau = array [1..3] of cell; TYPE bateau = record bateau : tabbateau; END; TYPE tabflotte = array [1..4] of bateau; TYPE flotte = record flotte : tabflotte; END; function compareCell(cell1 : integer;cell2 : integer) : boolean; BEGIN if cell1 = cell2 then compareCell := true else compareCell := false; END; function createBateau(numero : integer) :bateau; VAR i : integer; lclBoat : tabBateau; boat : bateau; BEGIN if numero = 1 then BEGIN for i := 1 to 3 do BEGIN boat := bateau.tabBateau[i].x := 3; END; for i := 1 to 3 do BEGIN boat := bateau.tabBateau[i].y := 1+i; END; createBateau := boat; END; else if numero = 2 then else if numero = 3 then else if numero = 4 then END; VAR flotte = flotte; bateau1 = bateau; i,j = integer; BEGIN bateau1 := createBateau(1); for i := 1 to 3 do readln(bateau1.tabBateau[i].x); readln(bateau1.tabBateau[i].y); END. flotte[1].bateau[3].x
unit orm.attributes; interface uses System.SysUtils, System.Generics.Collections, //orm.Generics.Collections, orm.attributes.types; type TObjectDB = Class Of ObjectDB; ObjectDB = Class(TCustomAttribute) Private FName : String; FAlias : String; Public property Name : String Read FName Write FName; property Alias : String Read FAlias Write FAlias; constructor Create(Value : String); Overload; constructor Create(ValueName : String; ValueAlias : String); Overload; End; Table = Class(ObjectDB); StoredProcedure = Class(ObjectDB); FunctionDB = Class(ObjectDB); View = Class(ObjectDB); //Field = Class(ObjectDB);// nao pode ser utilizado o nome Field entao ficou Column Column = Class(ObjectDB) Private FSize : Integer; FDefault : Variant; FFieldType : TFieldTypes; FParamType : TParamTypes; Public property Size : Integer Read FSize; property Default : Variant Read FDefault; property FieldType : TFieldTypes Read FFieldType; property ParamType : TParamTypes Read FParamType; constructor Create(FieldName : String; FieldSize : Integer); Overload; constructor Create(FieldName : String; FieldSize : Integer; FieldTypes : TFieldTypes); Overload; constructor Create(FieldName : String; FieldTypes : TFieldTypes); Overload; constructor Create(FieldName : String; FieldSize : Integer; ParamTypes : TParamTypes; FieldTypes : TFieldTypes); Overload; constructor Create(FieldName : String; ParamTypes : TParamTypes; FieldTypes : TFieldTypes); Overload; End; Foreign = Class(TCustomAttribute) Private FJoin : TJoin; FLoad : TLoad; FKeys : TList<String>; FModifys : TModifys; Public property Join : TJoin Read FJoin Write FJoin; property Load : TLoad Read FLoad Write FLoad; property Keys : TList<String> Read FKeys Write FKeys; property Modifys : TModifys Read FModifys Write FModifys; constructor Create(ForeignKeys : String; ForeignModifys : TModifys = []; ForeignValue : TJoin = jLeft; ForeignLoad : TLoad = lEazy); Overload; constructor Create(ForeignModifys : TModifys = []; ForeignValue : TJoin = jLeft; ForeignLoad : TLoad = lEazy); Overload; constructor Create(ForeignLoad : TLoad; ForeignKeys : String = ''; ForeignModifys : TModifys = []); Overload; constructor Create(ForeignLoad : TLoad; ForeignModifys : TModifys); Overload; destructor Destroy; Override; End; implementation { ObjectDB } constructor ObjectDB.Create(Value : String); begin FName := Value; end; constructor ObjectDB.Create(ValueName, ValueAlias : String); begin Name := ValueName; Alias := ValueAlias; If (Alias = '') Then Alias := Name; end; { Column } constructor Column.Create(FieldName: String; FieldSize: Integer); begin inherited Create(FieldName); FSize := FieldSize; end; constructor Column.Create(FieldName: String; FieldTypes: TFieldTypes); begin inherited Create(FieldName); FFieldType := FieldTypes; end; constructor Column.Create(FieldName: String; FieldSize: Integer; FieldTypes : TFieldTypes); begin inherited Create(FieldName); FSize := FieldSize; FFieldType := FieldTypes; end; constructor Column.Create(FieldName: String; ParamTypes: TParamTypes; FieldTypes: TFieldTypes); begin inherited Create(FieldName); FParamType := ParamTypes; FFieldType := FieldTypes; end; constructor Column.Create(FieldName: String; FieldSize: Integer; ParamTypes : TParamTypes; FieldTypes: TFieldTypes); begin inherited Create(FieldName); FSize := FieldSize; FParamType := ParamTypes; FFieldType := FieldTypes; end; { Foreign } constructor Foreign.Create(ForeignKeys : String; ForeignModifys: TModifys; ForeignValue : TJoin; ForeignLoad : TLoad); begin FJoin := ForeignValue; FLoad := ForeignLoad; FModifys := ForeignModifys; FKeys := TList<String>.Create; FKeys.AddRange(ForeignKeys.Split([';'])); end; constructor Foreign.Create(ForeignModifys: TModifys; ForeignValue: TJoin; ForeignLoad: TLoad); begin FJoin := ForeignValue; FLoad := ForeignLoad; FModifys := ForeignModifys; FKeys := TList<String>.Create; end; constructor Foreign.Create(ForeignLoad: TLoad; ForeignKeys: String; ForeignModifys: TModifys); begin FJoin := jLeft; FLoad := ForeignLoad; FModifys := ForeignModifys; FKeys := TList<String>.Create; FKeys.AddRange(ForeignKeys.Split([';'])); end; constructor Foreign.Create(ForeignLoad: TLoad; ForeignModifys: TModifys); begin FJoin := jLeft; FLoad := ForeignLoad; FModifys := ForeignModifys; FKeys := TList<String>.Create; end; destructor Foreign.Destroy; begin FreeAndNil(FKeys); inherited; end; end.
unit uAPIHook; interface uses classes, Windows,SysUtils, messages,dialogs; type TImportCode = packed record JumpInstruction: Word; AddressOfPointerToFunction: PPointer; end; PImportCode = ^TImportCode; PImage_Import_Entry = ^Image_Import_Entry; Image_Import_Entry = record Characteristics: DWORD; TimeDateStamp: DWORD; MajorVersion: Word; MinorVersion: Word; Name: DWORD; LookupTable: DWORD; end; TLongJmp = packed record JmpCode: ShortInt; {指令,用$E9来代替系统的指令} FuncAddr: DWORD; {函数地址} end; TAPIHook = class public constructor Create(IsTrap:boolean;OldFun,NewFun:pointer); destructor Destroy; override; procedure Restore; procedure Change; private FOldFunction,FNewFunction:Pointer;{被截函数、自定义函数} Trap:boolean; {调用方式:True陷阱式,False改引入表式} hProcess: Cardinal; {进程句柄,只用于陷阱式} AlreadyHook:boolean; {是否已安装Hook,只用于陷阱式} AllowChange:boolean; {是否允许安装、卸载Hook,只用于改引入表式} Oldcode: array[0..4]of byte; {系统函数原来的前5个字节} Newcode: TLongJmp; {将要写在系统函数的前5个字节} public property OldFunction: Pointer read FOldFunction; property NewFunction: Pointer read FNewFunction; end; implementation {取函数的实际地址。如果函数的第一个指令是Jmp,则取出它的跳转地址(实际地址),这往往是由于程序中含有Debug调试信息引起的} function FinalFunctionAddress(Code: Pointer): Pointer; Var Func: PImportCode; begin Result:=Code; if Code=nil then exit; try func:=code; if (func.JumpInstruction=$25FF) then {指令二进制码FF 25 汇编指令jmp [...]} Func:=func.AddressOfPointerToFunction^; result:=Func; except Result:=nil; end; end; {更改引入表中指定函数的地址,只用于改引入表式} function PatchAddressInModule(BeenDone:Tlist;hModule: THandle; OldFunc,NewFunc: Pointer):integer; const SIZE=4; Var Dos: PImageDosHeader; NT: PImageNTHeaders; ImportDesc: PImage_Import_Entry; rva: DWORD; Func: PPointer; DLL: String; f: Pointer; written: DWORD; mbi_thunk:TMemoryBasicInformation; dwOldProtect:DWORD; begin Result:=0; if hModule=0 then exit; Dos:=Pointer(hModule); {如果这个DLL模块已经处理过,则退出。BeenDone包含已处理的DLL模块} if BeenDone.IndexOf(Dos)>=0 then exit; BeenDone.Add(Dos);{把DLL模块名加入BeenDone} OldFunc:=FinalFunctionAddress(OldFunc);{取函数的实际地址} {如果这个DLL模块的地址不能访问,则退出} if IsBadReadPtr(Dos,SizeOf(TImageDosHeader)) then exit; {如果这个模块不是以'MZ'开头,表明不是DLL,则退出} if Dos.e_magic<>IMAGE_DOS_SIGNATURE then exit;{IMAGE_DOS_SIGNATURE='MZ'} {定位至NT Header} NT :=Pointer(Integer(Dos) + dos._lfanew); {定位至引入函数表} RVA:=NT^.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; if RVA=0 then exit;{如果引入函数表为空,则退出} {把函数引入表的相对地址RVA转换为绝对地址} ImportDesc := pointer(DWORD(Dos)+RVA);{Dos是此DLL模块的首地址} {遍历所有被引入的下级DLL模块} While (ImportDesc^.Name<>0) do begin {被引入的下级DLL模块名字} DLL:=PChar(DWORD(Dos)+ImportDesc^.Name); {把被导入的下级DLL模块当做当前模块,进行递归调用} PatchAddressInModule(BeenDone,GetModuleHandle(PChar(DLL)),OldFunc,NewFunc); {定位至被引入的下级DLL模块的函数表} Func:=Pointer(DWORD(DOS)+ImportDesc.LookupTable); {遍历被引入的下级DLL模块的所有函数} While Func^<>nil do begin f:=FinalFunctionAddress(Func^);{取实际地址} if f=OldFunc then {如果函数实际地址就是所要找的地址} begin VirtualQuery(Func,mbi_thunk, sizeof(TMemoryBasicInformation)); VirtualProtect(Func,SIZE,PAGE_EXECUTE_WRITECOPY,mbi_thunk.Protect);{更改内存属性} WriteProcessMemory(GetCurrentProcess,Func,@NewFunc,SIZE,written);{把新函数地址覆盖它} VirtualProtect(Func, SIZE, mbi_thunk.Protect,dwOldProtect);{恢复内存属性} end; If Written=4 then Inc(Result); // else showmessagefmt('error:%d',[Written]); Inc(Func);{下一个功能函数} end; Inc(ImportDesc);{下一个被引入的下级DLL模块} end; end; {HOOK的入口,其中IsTrap表示是否采用陷阱式} constructor TAPIHook.Create(IsTrap:boolean;OldFun,NewFun:pointer); begin {求被截函数、自定义函数的实际地址} FOldFunction:=FinalFunctionAddress(OldFun); FNewFunction:=FinalFunctionAddress(NewFun); Trap:=IsTrap; if Trap then{如果是陷阱式} begin {以特权的方式来打开当前进程} hProcess := OpenProcess(PROCESS_ALL_ACCESS,FALSE, GetCurrentProcessID); {生成jmp xxxx的代码,共5字节} Newcode.JmpCode := ShortInt($E9); {jmp指令的十六进制代码是E9} NewCode.FuncAddr := DWORD(FNewFunction) - DWORD(FOldFunction) - 5; {保存被截函数的前5个字节} move(FOldFunction^,OldCode,5); {设置为还没有开始HOOK} AlreadyHook:=false; end; {如果是改引入表式,将允许HOOK} if not Trap then AllowChange:=true; Change; {开始HOOK} {如果是改引入表式,将暂时不允许HOOK} if not Trap then AllowChange:=false; end; {HOOK的出口} destructor TAPIHook.Destroy; begin {如果是改引入表式,将允许HOOK} if not Trap then AllowChange:=true; Restore; {停止HOOK} if Trap then{如果是陷阱式} CloseHandle(hProcess); end; {开始HOOK} procedure TAPIHook.Change; var nCount: DWORD; BeenDone: TList; begin if Trap then{如果是陷阱式} begin if (AlreadyHook)or (hProcess = 0) or (FOldFunction = nil) or (FNewFunction = nil) then exit; AlreadyHook:=true;{表示已经HOOK} WriteProcessMemory(hProcess, FOldFunction, @(Newcode), 5, nCount); end else begin{如果是改引入表式} if (not AllowChange)or(FOldFunction=nil)or(FNewFunction=nil)then exit; BeenDone:=TList.Create; {用于存放当前进程所有DLL模块的名字} try PatchAddressInModule(BeenDone,GetModuleHandle(nil),FOldFunction,FNewFunction); finally BeenDone.Free; end; end; end; {恢复系统函数的调用} procedure TAPIHook.Restore; var nCount: DWORD; BeenDone: TList; begin if Trap then{如果是陷阱式} begin if (not AlreadyHook) or (hProcess = 0) or (FOldFunction = nil) or (FNewFunction = nil) then begin OutputDebugString( 'do not need to hook' ); exit; end; WriteProcessMemory(hProcess, FOldFunction, @(Oldcode), 5, nCount); AlreadyHook:=false;{表示退出HOOK} end else begin{如果是改引入表式} if (not AllowChange)or(FOldFunction=nil)or(FNewFunction=nil)then exit; BeenDone:=TList.Create;{用于存放当前进程所有DLL模块的名字} try PatchAddressInModule(BeenDone,GetModuleHandle(nil),FNewFunction,FOldFunction); finally BeenDone.Free; end; end; end; end.
unit PathDialogForms; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Windows, Messages, SysUtils, Variants, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, NppForms, Vcl.StdCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, nppplugin, AdvGenerics, FHIRBase; type TPathOutcomeDialogMode = (pomError, pomNoMatch, pomMatch); TPathDialogForm = class(TNppForm) Panel2: TPanel; Label1: TLabel; Panel1: TPanel; CheckBox1: TCheckBox; Button1: TButton; Memo1: TMemo; private { Private declarations } public { Public declarations } end; var PathDialogForm: TPathDialogForm; procedure pathOutcomeDialog(owner : TNppPlugin; path, rtype : String; types : TFHIRTypeDetails; mode : TPathOutcomeDialogMode; outcome : String); implementation {$R *.dfm} uses FHIRPluginSettings; function summary(types : TArray<String>) : String; var s : String; b : TStringBuilder; f : boolean; begin if Length(types) = 0 then exit('?? unknown'); f := true; b := TStringBuilder.Create; try for s in types do begin if f then f := false else b.Append(', '); b.Append(s); end; result := b.ToString; finally b.Free; end; end; procedure pathOutcomeDialog(owner : TNppPlugin; path, rtype : String; types : TFHIRTypeDetails; mode : TPathOutcomeDialogMode; outcome : String); var t : string; begin if not Settings.NoPathSummary or (mode = pomError) then begin PathDialogForm := TPathDialogForm.create(owner); try PathDialogForm.CheckBox1.Checked := Settings.NoPathSummary; if types = nil then t := '' else t := types.ToString; case mode of pomError : PathDialogForm.Memo1.Text := 'Path: '+path+#13#10#13#10+'When evaluated against a '+rtype+', this path may return the following types: '+t+#13#10#13#10+'Error Message: '+outcome+#13#10; pomNoMatch : PathDialogForm.Memo1.Text := 'Path: '+path+#13#10#13#10+'When evaluated against a '+rtype+', this path may return the following types: '+t+#13#10#13#10+'Outcome: '+outcome+#13#10; pomMatch : PathDialogForm.Memo1.Text := 'Path: '+path+#13#10#13#10+'When evaluated against a '+rtype+', this path may return the following types: '+t+#13#10#13#10+'Outcome: '+outcome+#13#10#13#10+'Matching Items are shown with a green squiggly: '+#13#10; end; PathDialogForm.ShowModal; Settings.NoPathSummary := PathDialogForm.CheckBox1.Checked; finally FreeAndNil(PathDialogForm); end; end; end; end.
UNIT TreeWorking; INTERFACE USES WordWorking; CONST WordLength = 60; TYPE Tree = ^NodeType; NodeType = RECORD Wd: STRING; Amount: INTEGER; LLink, RLink: Tree; END; PROCEDURE InsertWord(VAR Data: STRING; VAR Ptr: Tree; VAR Nodes: INTEGER); //Добавление нового слова в узел дерева PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); //Вывод отсортированного дерева в выходной файл PROCEDURE ClearTree(VAR Ptr: Tree); //Очистка дерева PROCEDURE Merge(VAR FTempIn, FTempOut: TEXT; VAR Ptr: Tree); //Слияние дерева с файлом PROCEDURE CopyFile(VAR FIn, FOut: TEXT); IMPLEMENTATION PROCEDURE MergeTree(VAR FTempIn, FTempOut: TEXT; VAR Ptr: Tree; VAR TreeWord, FileWord: STRING; VAR TreeAmount, FileAmount: INTEGER); VAR IsMore, IsLess, IsEqual, Flag: BOOLEAN; BEGIN {MergeTree} IF (Ptr <> NIL) THEN BEGIN MergeTree(FTempIn, FTempOut, Ptr^.LLink, TreeWord, FileWord, TreeAmount, FileAmount); IsEqual := FALSE; IsLess := FALSE; TreeWord := Ptr^.Wd; TreeAmount := Ptr^.Amount; IF (FileWord < TreeWord) AND (FileWord <> 'EOF') THEN BEGIN WRITELN(FTempOut, FileWord, ' ', FileAmount); IF EOF(FTempIn) THEN FileWord := 'EOF'; END ELSE IF (FileWord = TreeWord) AND (NOT EOF(FTempIn)) THEN BEGIN WRITELN(FTempOut, FileWord, ' ', FileAmount + TreeAmount); IsEqual := TRUE; END ELSE IsLess := TRUE; WHILE (NOT IsLess) AND (NOT EOF(FTempIn)) DO BEGIN GetWord(FTempIn, FileWord); READLN(FTempIn, FileAmount); IF FileWord < TreeWord THEN BEGIN WRITELN(FTempOut, FileWord, ' ', FileAmount); IF EOF(FTempIn) THEN FileWord := 'EOF' END ELSE IF FileWord = TreeWord THEN BEGIN WRITELN(FTempOut, FileWord, ' ', FileAmount + TreeAmount); IsEqual := TRUE; END ELSE IsLess := TRUE; END; IF NOT IsEqual THEN WRITELN(FTempOut, TreeWord, ' ', TreeAmount); MergeTree(FTempIn, FTempOut, Ptr^.RLink, TreeWord, FileWord, TreeAmount, FileAmount); END; END; {MergeTree} PROCEDURE Merge(VAR FTempIn, FTempOut: TEXT; VAR Ptr: Tree); VAR TreeWord, FileWord: STRING; TreeAmount, FileAmount: INTEGER; Ch: CHAR; BEGIN {Merge} GetWord(FTempIn, FileWord); READ(FTempIn, FileAmount); TreeWord := ''; TreeAmount := 0; READLN(FTempIN); MergeTree(FTempIn, FTempOut, Ptr, TreeWord, FileWord, TreeAmount, FileAmount); IF FileWord <> 'EOF' THEN WRITELN(FTempOut, FileWord, ' ', FileAmount); WHILE NOT EOF(FTempIn) DO BEGIN GetWord(FTempIn, FileWord); READLN(FTempIn, FileAmount); WRITELN(FTempOut, FileWord, ' ', FileAmount); END; END; {Merge} PROCEDURE InsertWord(VAR Data: STRING; VAR Ptr: Tree; VAR Nodes: INTEGER); BEGIN {InsertWord} IF Ptr = NIL THEN BEGIN NEW(Ptr); Ptr^.Wd := Data; Nodes := Nodes + 1; Ptr^.Amount := 1; Ptr^.LLink := NIL; Ptr^.RLink := NIL; END ELSE IF Ptr^.Wd = Data THEN Ptr^.Amount := Ptr^.Amount + 1 ELSE IF Data <= Ptr^.Wd THEN InsertWord(Data, Ptr^.LLink, Nodes) ELSE InsertWord(Data, Ptr^.RLink, Nodes) END; {InsertWord} PROCEDURE PrintTree(VAR Ptr: Tree; VAR FOut: TEXT); BEGIN {PrintTree} IF Ptr <> NIL THEN BEGIN PrintTree(Ptr^.LLink, FOut); WRITELN(FOut, Ptr^.Wd, ' ', Ptr^.Amount); PrintTree(Ptr^.RLink, FOut); END; END; {PrintTree} PROCEDURE ClearTree(VAR Ptr: Tree); BEGIN {ClearTree} IF Ptr <> NIL THEN BEGIN ClearTree(Ptr^.LLink); ClearTree(Ptr^.RLink); DISPOSE(Ptr); Ptr := NIL; END; END; {ClearTree} PROCEDURE CopyFile(VAR FIn, FOut: TEXT); VAR Ch: CHAR; BEGIN {CopyFile} RESET(FIn); REWRITE(FOut); WHILE NOT EOF(FIn) DO BEGIN WHILE NOT EOLN(FIn) DO BEGIN READ(FIn, Ch); WRITE(FOut, Ch); END; WRITELN(FOut); READLN(FIn); END; END; {CopyFile} BEGIN END.
Unit AdvTextFormatters; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses SysUtils, StringSupport, AdvFormatters; Type TAdvTextFormatter = Class(TAdvFormatter) Private FLevel : Integer; FHasWhitespace : Boolean; FWhitespaceCharacter : Char; FWhitespaceMultiple : Integer; {$IFNDEF VER130} FEncoding: TEncoding; {$ENDIF} Protected Function BeforeWhitespace : String; Function AfterWhitespace : String; Public Constructor Create; Override; Function Link : TAdvTextFormatter; Procedure Clear; Override; Procedure ProduceNewLine; Virtual; Procedure ProduceLine(Const sValue : String); Procedure ProduceInline(Const sValue : String); Procedure ProduceFragment(Const sValue : String); Procedure LevelDown; Procedure LevelUp; Property HasWhitespace : Boolean Read FHasWhitespace Write FHasWhitespace; Property WhitespaceCharacter : Char Read FWhitespaceCharacter Write FWhitespaceCharacter; Property WhitespaceMultiple : Integer Read FWhitespaceMultiple Write FWhitespaceMultiple; Property Level : Integer Read FLevel; {$IFNDEF VER130} Property Encoding : TEncoding read FEncoding Write FEncoding; {$ENDIF} End; TAdvTextFormatterClass = Class Of TAdvTextFormatter; Implementation Constructor TAdvTextFormatter.Create; Begin Inherited; FHasWhitespace := True; FWhitespaceCharacter := ' '; FWhitespaceMultiple := 2; {$IFNDEF VER130} Encoding := SysUtils.TEncoding.UTF8; {$ENDIF} End; Function TAdvTextFormatter.Link : TAdvTextFormatter; Begin Result := TAdvTextFormatter(Inherited Link); End; Procedure TAdvTextFormatter.Clear; Begin Inherited; FLevel := 0; End; Function TAdvTextFormatter.BeforeWhitespace : String; Begin // Multiply of the space character by FLevel * 2 is more efficient than Multiply of string ' ' by FLevel because it uses FillChar. If FHasWhitespace Then Result := StringMultiply(FWhitespaceCharacter, FLevel * FWhitespaceMultiple) Else Result := ''; End; Function TAdvTextFormatter.AfterWhitespace : String; Begin If FHasWhitespace Then Result := cReturn Else Result := ''; End; Procedure TAdvTextFormatter.ProduceFragment(Const sValue: String); Begin Produce(sValue); End; Procedure TAdvTextFormatter.ProduceLine(Const sValue: String); Begin Produce(BeforeWhitespace + sValue + AfterWhitespace); End; Procedure TAdvTextFormatter.ProduceNewLine; Begin Produce(cReturn); End; Procedure TAdvTextFormatter.LevelDown; Begin Inc(FLevel); End; Procedure TAdvTextFormatter.LevelUp; Begin Dec(FLevel); End; Procedure TAdvTextFormatter.ProduceInline(Const sValue: String); Begin Produce(sValue); End; End.
unit uDCTeeTools; {$I VCL.DC.inc} interface uses System.Classes, System.Types, Winapi.Windows, {$IFDEF TEEVCL} VCLTee.TeeTools, VCLTee.TeCanvas, VCLTee.TeEngine, {$ELSE} TeeTools, TeCanvas, TeEngine, {$ENDIF} aOPCLabel; type TDCTextColorBandTool = class(TColorBandTool) private FText: string; FFont: TTeeFont; FTextOrientation: Integer; procedure SetText(const Value: string); procedure SetFont(const Value: TTeeFont); protected procedure ChartEvent(AEvent: TChartToolEvent); override; procedure DrawDCText; function GetDisplayText(r: TRect): string; public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; published property Font:TTeeFont read FFont write SetFont; property Text: string read FText write SetText; property TextOrientation: Integer read FTextOrientation write FTextOrientation; end; implementation uses System.SysUtils, TeeHyphen; { TDCTextColorBandTool } procedure TDCTextColorBandTool.ChartEvent(AEvent: TChartToolEvent); begin inherited; case AEvent of cteBeforeDrawAxes: if DrawBehindAxes then DrawDCText; cteBeforeDrawSeries: if DrawBehind and (not DrawBehindAxes) then DrawDCText; cteAfterDraw: if (not DrawBehind) and (not DrawBehindAxes) then DrawDCText; end; // DrawDCText; end; constructor TDCTextColorBandTool.Create(AOwner: TComponent); begin inherited; StartLine.Pen.Width := 0; EndLine.Pen.Width := 0; FFont:=TTeeFont.Create(CanvasChanged); end; destructor TDCTextColorBandTool.Destroy; begin FFont.Free; inherited; end; procedure TDCTextColorBandTool.DrawDCText; var r: TRect; t: String; h: Integer; aStrings: TStrings; begin // r := BoundsRect(); // t := GetDisplayText(r); // TextOut(ParentChart.Canvas.Handle, r.Left, r.Top, t, False); // Exit; aStrings := TStringList.Create; try r := BoundsRect(); InflateRect(r, -1, -1); ParentChart.Canvas.BackMode:=cbmTransparent; ParentChart.Canvas.Font.Assign(Font); if TextOrientation = 0 then begin t := GetDisplayText(r); ParentChart.Canvas.TextAlign := TA_CENTER; ParentChart.Canvas.TextOut(r.Left + r.Width div 2, r.Top, t, True); // DrawText(ParentChart.Canvas.Handle, PChar(t), Length(t), r, DT_WORDBREAK + DT_CENTER); end else begin t := Text; // if Length(t)>20 then // t := Copy(t, 1, 20) + #13#10 + Copy(t,21,Length(t)); h := Abs(ParentChart.Canvas.Font.Height); if r.Width > 3 then begin if (r.Width < h) then begin ParentChart.Canvas.Font.Height := -(r.Width+2); h := Abs(ParentChart.Canvas.Font.Height); end; if TextOrientation = -90 then begin HyphenParagraph(Text, aStrings, r.Height, ParentChart.Canvas); t := Trim(aStrings.Text); ParentChart.Canvas.RotateLabel(r.Left + (r.Width + aStrings.Count * h + 2) div 2, r.Top, t, TextOrientation) end else if TextOrientation = 90 then begin HyphenParagraph(Text, aStrings, r.Height, ParentChart.Canvas); t := Trim(aStrings.Text); ParentChart.Canvas.RotateLabel(r.Right - (r.Width + aStrings.Count * h + 2) div 2, r.Bottom, t, TextOrientation); end; end; end; //ParentChart.Canvas.Font.Orientation := -900; //TextOrientation; //TextOut(r.Left, r.Top, Text, False); finally aStrings.Free; end; end; function TDCTextColorBandTool.GetDisplayText(r: TRect): string; var Strs: TStrings; t:string; begin Strs := TStringList.Create; try HyphenParagraph(Text, Strs, r.Width, ParentChart.Canvas); t := Strs.Text; Result := Copy(t,1,Length(t)-2); finally Strs.Free; end; end; procedure TDCTextColorBandTool.SetFont(const Value: TTeeFont); begin FFont.Assign(Value); end; procedure TDCTextColorBandTool.SetText(const Value: string); begin FText := Value; end; end.
Listing 1 PROGRAM Sqrt0; { A variant record to let us get to the exponent } TYPE fp_record = RECORD CASE boolean of true: (r: real); false:(n: array[1..6] of byte); END; VAR Guess: fp_record; x, e, Root: real; i: integer; { To count the iterations } BEGIN ReadLn(x); Root := Sqrt(x); { To give us something to compare to } WITH Guess DO BEGIN r := x; n[1] := $81 + (n[1] - $81) div 2; i := 1; REPEAT { The iteration loop } e := (r - x/r)/2.0; r := r - e; WriteLn(i, ' ', r, ' ', abs(r - Root)); Inc(i); UNTIL Abs(e/r) <= 1.0e-12; { The stopping criterion } END; ReadLn; { So Turbo will show us the output! } END. ---------------------------------------------------------------------- Listing 2 PROGRAM Sqrt1; VAR r, x, e, Root: real; i: integer; BEGIN ReadLn(x); Root := Sqrt(x); r := 0.840896415; i := 1; REPEAT e := (r - x/r)/2.0; r := r - e; WriteLn(i, ' ', r, ' ', Abs(r - Root)); Inc(i); UNTIL Abs(e/r) <= 1.0e-12; ReadLn; END. ---------------------------------------------------------------------- Listing 3 { Pascal Template for Floating Point Square Root } FUNCTION Root(x: real): real; CONST A = 0.41731942; { Magic numbers for trial value } B = 0.590178532; TYPE { Variant record to adjust exponent} FP_Record = record CASE boolean OF true: (r: real); false:(n: array[1..6] of byte); END; VAR Trial: FP_Record; { Trial Solution } Exp: byte; { Exponent to play with } BEGIN { First, take care of special cases } IF x < 0.0 THEN BEGIN WriteLn(^G, 'Error: Square root of negative number.'); Halt; END ELSE IF x = 0.0 THEN Root := 0.0 ELSE WITH Trial DO BEGIN { Get x so we can play with its exponent} r := x; Exp := n[1]; { Force x to be in the range 0.5 .. 1.0 } n[1] := $80; { Compute trial solution via linear approximation } r := A + B*r; n[1] := $40 + Exp div 2; IF Odd(Exp) THEN r := 1.414213562*r; { Now, do three successive Newton iterations (for higher speed, leave out one or more) } r := (x/r + r)/2.0; r := (x/r + r)/2.0; r := (x/r + r)/2.0; { And return the result } Root := r; END; END; ---------------------------------------------------------------------- Listing 4 { Pascal Template for Integer Square Root } FUNCTION Root(x: integer): integer; TYPE { Variant record to permit shifting } Long = record CASE boolean OF true: (L: LongInt); false:(Lo, Hi: Integer); END; VAR Arg: Long; { The 'accumulator' } i, r, Temp: integer; { r is the root } BEGIN { First, take care of special cases } IF x < 0 THEN BEGIN WriteLn(^G, 'Error: Square root of negative number.'); Halt; END ELSE IF x = 0 THEN Root := 0 ELSE WITH Arg DO BEGIN { Initialize L and r } L := x; r := 0; { Begin computation loop } for i := 1 to 8 do begin r := r SHL 1; { Shift both registers } L := L SHL 2; { Check the range of Hi. Reduce if we can } Temp := 2 * r + 1; IF Hi >= Temp THEN BEGIN Hi := Hi - Temp; r := r + 1; END; END; { At end of loop, answer resides in r } Root := r; END; END;
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Android; {$ifdef fpc} {$mode delphi} {$packrecords c} {$ifdef cpui386} {$define cpu386} {$define cpu32} {$endif} {$ifdef cpu386} {$asmmode intel} {$define cpu32} {$endif} {$ifdef cpuamd64} {$define cpux64} {$define cpux8664} {$define cpu64} {$asmmode intel} {$endif} {$ifdef FPC_LITTLE_ENDIAN} {$define LITTLE_ENDIAN} {$else} {$ifdef FPC_BIG_ENDIAN} {$define BIG_ENDIAN} {$endif} {$endif} {-$pic off} {$define CanInline} {$ifdef FPC_HAS_TYPE_EXTENDED} {$define HAS_TYPE_EXTENDED} {$else} {$undef HAS_TYPE_EXTENDED} {$endif} {$ifdef FPC_HAS_TYPE_DOUBLE} {$define HAS_TYPE_DOUBLE} {$else} {$undef HAS_TYPE_DOUBLE} {$endif} {$ifdef FPC_HAS_TYPE_SINGLE} {$define HAS_TYPE_SINGLE} {$else} {$undef HAS_TYPE_SINGLE} {$endif} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$if declared(UnicodeString)} {$define HAS_TYPE_UNICODESTRING} {$else} {$undef HAS_TYPE_UNICODESTRING} {$ifend} {$else} {$realcompatibility off} {$safedivide off} {$localsymbols on} {$define LITTLE_ENDIAN} {$ifdef cpux64} {$define cpux8664} {$define cpuamd64} {$define cpu64} {$endif} {$ifndef cpu64} {$define cpu32} {$endif} {$define HAS_TYPE_EXTENDED} {$define HAS_TYPE_DOUBLE} {$define HAS_TYPE_SINGLE} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$if declared(RawByteString)} {$define HAS_TYPE_RAWBYTESTRING} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$ifend} {$if declared(UTF8String)} {$define HAS_TYPE_UTF8STRING} {$else} {$undef HAS_TYPE_UTF8STRING} {$ifend} {$if declared(UnicodeString)} {$define HAS_TYPE_UNICODESTRING} {$else} {$undef HAS_TYPE_UNICODESTRING} {$ifend} {$else} {$undef HAS_TYPE_RAWBYTESTRING} {$undef HAS_TYPE_UTF8STRING} {$undef HAS_TYPE_UNICODESTRING} {$endif} {$ifndef BCB} {$ifdef ver120} {$define Delphi4or5} {$endif} {$ifdef ver130} {$define Delphi4or5} {$endif} {$ifdef ver140} {$define Delphi6} {$endif} {$ifdef ver150} {$define Delphi7} {$endif} {$ifdef ver170} {$define Delphi2005} {$endif} {$else} {$ifdef ver120} {$define Delphi4or5} {$define BCB4} {$endif} {$ifdef ver130} {$define Delphi4or5} {$endif} {$endif} {$ifdef conditionalexpressions} {$if CompilerVersion>=24} {$legacyifend on} {$ifend} {$if CompilerVersion>=14.0} {$if CompilerVersion=14.0} {$define Delphi6} {$ifend} {$define Delphi6AndUp} {$ifend} {$if CompilerVersion>=15.0} {$if CompilerVersion=15.0} {$define Delphi7} {$ifend} {$define Delphi7AndUp} {$ifend} {$if CompilerVersion>=17.0} {$if CompilerVersion=17.0} {$define Delphi2005} {$ifend} {$define Delphi2005AndUp} {$finitefloat off} {$ifend} {$if CompilerVersion>=18.0} {$if CompilerVersion=18.0} {$define BDS2006} {$define Delphi2006} {$ifend} {$define Delphi2006AndUp} {$ifend} {$if CompilerVersion>=18.5} {$if CompilerVersion=18.5} {$define Delphi2007} {$ifend} {$define Delphi2007AndUp} {$ifend} {$if CompilerVersion=19.0} {$define Delphi2007Net} {$ifend} {$if CompilerVersion>=20.0} {$if CompilerVersion=20.0} {$define Delphi2009} {$ifend} {$define Delphi2009AndUp} {$define CanInline} {$ifend} {$if CompilerVersion>=21.0} {$if CompilerVersion=21.0} {$define Delphi2010} {$ifend} {$define Delphi2010AndUp} {$ifend} {$if CompilerVersion>=22.0} {$if CompilerVersion=22.0} {$define DelphiXE} {$ifend} {$define DelphiXEAndUp} {$ifend} {$if CompilerVersion>=23.0} {$if CompilerVersion=23.0} {$define DelphiXE2} {$ifend} {$define DelphiXE2AndUp} {$ifend} {$if CompilerVersion>=24.0} {$if CompilerVersion=24.0} {$define DelphiXE3} {$ifend} {$define DelphiXE3AndUp} {$ifend} {$if CompilerVersion>=25.0} {$if CompilerVersion=25.0} {$define DelphiXE4} {$ifend} {$define DelphiXE4AndUp} {$ifend} {$if CompilerVersion>=26.0} {$if CompilerVersion=26.0} {$define DelphiXE5} {$ifend} {$define DelphiXE5AndUp} {$ifend} {$if CompilerVersion>=27.0} {$if CompilerVersion=27.0} {$define DelphiXE6} {$ifend} {$define DelphiXE6AndUp} {$ifend} {$if CompilerVersion>=28.0} {$if CompilerVersion=28.0} {$define DelphiXE7} {$ifend} {$define DelphiXE7AndUp} {$ifend} {$if CompilerVersion>=29.0} {$if CompilerVersion=29.0} {$define DelphiXE8} {$ifend} {$define DelphiXE8AndUp} {$ifend} {$if CompilerVersion>=30.0} {$if CompilerVersion=30.0} {$define Delphi10Seattle} {$ifend} {$define Delphi10SeattleAndUp} {$ifend} {$if CompilerVersion>=31.0} {$if CompilerVersion=31.0} {$define Delphi10Berlin} {$ifend} {$define Delphi10BerlinAndUp} {$ifend} {$endif} {$ifndef Delphi4or5} {$ifndef BCB} {$define Delphi6AndUp} {$endif} {$ifndef Delphi6} {$define BCB6OrDelphi7AndUp} {$ifndef BCB} {$define Delphi7AndUp} {$endif} {$ifndef BCB} {$ifndef Delphi7} {$ifndef Delphi2005} {$define BDS2006AndUp} {$endif} {$endif} {$endif} {$endif} {$endif} {$ifdef Delphi6AndUp} {$warn symbol_platform off} {$warn symbol_deprecated off} {$endif} {$endif} {$ifdef win32} {$define windows} {$endif} {$ifdef win64} {$define windows} {$endif} {$ifdef wince} {$define windows} {$endif} {$ifndef HAS_TYPE_DOUBLE} {$error No double floating point precision} {$endif} {$rangechecks off} {$extendedsyntax on} {$writeableconst on} {$hints off} {$booleval off} {$typedaddress off} {$stackframes off} {$varstringchecks on} {$typeinfo on} {$overflowchecks off} {$longstrings on} {$openstrings on} interface {$if defined(fpc) and defined(Android)} uses ctypes; (* * Manifest constants. *) const JNI_FALSE=0; JNI_TRUE=1; JNI_VERSION_1_1=$00010001; JNI_VERSION_1_2=$00010002; JNI_VERSION_1_4=$00010004; JNI_VERSION_1_6=$00010006; JNI_OK=0; // no error JNI_ERR=-1; // generic error JNI_EDETACHED=-2; // thread detached from the VM JNI_EVERSION=-3; // JNI version error JNI_COMMIT=1; // copy content, do not free buffer JNI_ABORT=2; // free buffer w/o copying back (* * Type definitions. *) type va_list=pointer; TJavaUnicodeString={$if declared(UnicodeString)}UnicodeString{$else}WideString{$ifend}; jboolean=byte; // unsigned 8 bits jbyte=shortint; // signed 8 bits jchar=word; // unsigned 16 bits jshort=smallint; // signed 16 bits jint=longint; // signed 32 bits jlong=int64; // signed 64 bits jfloat=single; // 32-bit IEEE 754 jdouble=double; // 64-bit IEEE 754 jsize=jint; // "cardinal indices and sizes" Pjboolean=^jboolean; Pjbyte=^jbyte; Pjchar=^jchar; Pjshort=^jshort; Pjint=^jint; Pjlong=^jlong; Pjfloat=^jfloat; Pjdouble=^jdouble; Pjsize=^jsize; // Reference type jobject=pointer; jclass=jobject; jstring=jobject; jarray=jobject; jobjectArray=jarray; jbooleanArray=jarray; jbyteArray=jarray; jcharArray=jarray; jshortArray=jarray; jintArray=jarray; jlongArray=jarray; jfloatArray=jarray; jdoubleArray=jarray; jthrowable=jobject; jweak=jobject; jref=jobject; PpvPointer=^pointer; Pjobject=^jobject; Pjclass=^jclass; Pjstring=^jstring; Pjarray=^jarray; PjobjectArray=^jobjectArray; PjbooleanArray=^jbooleanArray; PjbyteArray=^jbyteArray; PjcharArray=^jcharArray; PjshortArray=^jshortArray; PjintArray=^jintArray; PjlongArray=^jlongArray; PjfloatArray=^jfloatArray; PjdoubleArray=^jdoubleArray; Pjthrowable=^jthrowable; Pjweak=^jweak; Pjref=^jref; _jfieldID=record // opaque structure end; jfieldID=^_jfieldID;// field IDs PjfieldID=^jfieldID; _jmethodID=record // opaque structure end; jmethodID=^_jmethodID;// method IDs PjmethodID=^jmethodID; PJNIInvokeInterface=^JNIInvokeInterface; Pjvalue=^jvalue; jvalue={$ifdef packedrecords}packed{$endif} record case integer of 0:(z:jboolean); 1:(b:jbyte); 2:(c:jchar); 3:(s:jshort); 4:(i:jint); 5:(j:jlong); 6:(f:jfloat); 7:(d:jdouble); 8:(l:jobject); end; jobjectRefType=( JNIInvalidRefType=0, JNILocalRefType=1, JNIGlobalRefType=2, JNIWeakGlobalRefType=3); PJNINativeMethod=^JNINativeMethod; JNINativeMethod={$ifdef packedrecords}packed{$endif} record name:pchar; signature:pchar; fnPtr:pointer; end; PJNINativeInterface=^JNINativeInterface; _JNIEnv={$ifdef packedrecords}packed{$endif} record functions:PJNINativeInterface; end; _JavaVM= record functions:PJNIInvokeInterface; end; P_JavaVM = ^_JavaVM; C_JNIEnv=^JNINativeInterface; JNIEnv=^JNINativeInterface; JavaVM=^JNIInvokeInterface; PPJNIEnv=^PJNIEnv; PJNIEnv=^JNIEnv; PPJavaVM=^PJavaVM; PJavaVM=^JavaVM; JNINativeInterface= record reserved0:pointer; reserved1:pointer; reserved2:pointer; reserved3:pointer; GetVersion:function(Env:PJNIEnv):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} DefineClass:function(Env:PJNIEnv;const Name:pchar;Loader:JObject;const Buf:PJByte;Len:JSize):JClass;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} FindClass:function(Env:PJNIEnv;const Name:pchar):JClass;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Reflection Support FromReflectedMethod:function(Env:PJNIEnv;Method:JObject):JMethodID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} FromReflectedField:function(Env:PJNIEnv;Field:JObject):JFieldID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ToReflectedMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;IsStatic:JBoolean):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetSuperclass:function(Env:PJNIEnv;Sub:JClass):JClass;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} IsAssignableFrom:function(Env:PJNIEnv;Sub:JClass;Sup:JClass):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Reflection Support ToReflectedField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;IsStatic:JBoolean):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} Throw:function(Env:PJNIEnv;Obj:JThrowable):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ThrowNew:function(Env:PJNIEnv;AClass:JClass;const Msg:pchar):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ExceptionOccurred:function(Env:PJNIEnv):JThrowable;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ExceptionDescribe:procedure(Env:PJNIEnv);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ExceptionClear:procedure(Env:PJNIEnv);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} FatalError:procedure(Env:PJNIEnv;const Msg:pchar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Local Reference Management PushLocalFrame:function(Env:PJNIEnv;Capacity:JInt):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} PopLocalFrame:function(Env:PJNIEnv;Result:JObject):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewGlobalRef:function(Env:PJNIEnv;LObj:JObject):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} DeleteGlobalRef:procedure(Env:PJNIEnv;GRef:JObject);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} DeleteLocalRef:procedure(Env:PJNIEnv;Obj:JObject);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} IsSameObject:function(Env:PJNIEnv;Obj1:JObject;Obj2:JObject):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Local Reference Management NewLocalRef:function(Env:PJNIEnv;Ref:JObject):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} EnsureLocalCapacity:function(Env:PJNIEnv;Capacity:JInt):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} AllocObject:function(Env:PJNIEnv;AClass:JClass):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewObject:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewObjectV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewObjectA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetObjectClass:function(Env:PJNIEnv;Obj:JObject):JClass;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} IsInstanceOf:function(Env:PJNIEnv;Obj:JObject;AClass:JClass):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetMethodID:function(Env:PJNIEnv;AClass:JClass;const Name:pchar;const Sig:pchar):JMethodID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallObjectMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallObjectMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallObjectMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallBooleanMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallBooleanMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallBooleanMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallByteMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallByteMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallByteMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallCharMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallCharMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallCharMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallShortMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallShortMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallShortMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallIntMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallIntMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallIntMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallLongMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallLongMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallLongMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallFloatMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallFloatMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallFloatMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallDoubleMethod:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallDoubleMethodV:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallDoubleMethodA:function(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallVoidMethod:procedure(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallVoidMethodV:procedure(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:va_list);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallVoidMethodA:procedure(Env:PJNIEnv;Obj:JObject;MethodID:JMethodID;Args:PJValue);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualObjectMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualObjectMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualObjectMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualBooleanMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualBooleanMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualBooleanMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualByteMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualByteMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualByteMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualCharMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualCharMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualCharMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualShortMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualShortMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualShortMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualIntMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualIntMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualIntMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualLongMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualLongMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualLongMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualFloatMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualFloatMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualFloatMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualDoubleMethod:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualDoubleMethodV:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualDoubleMethodA:function(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualVoidMethod:procedure(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualVoidMethodV:procedure(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:va_list);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallNonvirtualVoidMethodA:procedure(Env:PJNIEnv;Obj:JObject;AClass:JClass;MethodID:JMethodID;Args:PJValue);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetFieldID:function(Env:PJNIEnv;AClass:JClass;const Name:pchar;const Sig:pchar):JFieldID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetObjectField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetBooleanField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetByteField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetCharField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetShortField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetIntField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetLongField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetFloatField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetDoubleField:function(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetObjectField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JObject);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetBooleanField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JBoolean);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetByteField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JByte);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetCharField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetShortField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JShort);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetIntField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetLongField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JLong);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetFloatField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JFloat);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetDoubleField:procedure(Env:PJNIEnv;Obj:JObject;FieldID:JFieldID;Val:JDouble);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticMethodID:function(Env:PJNIEnv;AClass:JClass;const Name:pchar;const Sig:pchar):JMethodID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticObjectMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticObjectMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticObjectMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticBooleanMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticBooleanMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticBooleanMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticByteMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticByteMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticByteMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticCharMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticCharMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticCharMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticShortMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticShortMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticShortMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticIntMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticIntMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticIntMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticLongMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticLongMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticLongMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticFloatMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticFloatMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticFloatMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticDoubleMethod:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticDoubleMethodV:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticDoubleMethodA:function(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticVoidMethod:procedure(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticVoidMethodV:procedure(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:va_list);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} CallStaticVoidMethodA:procedure(Env:PJNIEnv;AClass:JClass;MethodID:JMethodID;Args:PJValue);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticFieldID:function(Env:PJNIEnv;AClass:JClass;const Name:pchar;const Sig:pchar):JFieldID;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticObjectField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticBooleanField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticByteField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticCharField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticShortField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticIntField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticLongField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticFloatField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStaticDoubleField:function(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID):JDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticObjectField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JObject);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticBooleanField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JBoolean);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticByteField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JByte);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticCharField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticShortField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JShort);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticIntField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticLongField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JLong);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticFloatField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JFloat);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetStaticDoubleField:procedure(Env:PJNIEnv;AClass:JClass;FieldID:JFieldID;Val:JDouble);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewString:function(Env:PJNIEnv;const Unicode:PJChar;Len:JSize):JString;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStringLength:function(Env:PJNIEnv;Str:JString):JSize;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStringChars:function(Env:PJNIEnv;Str:JString;IsCopy:PJBoolean):PJChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseStringChars:procedure(Env:PJNIEnv;Str:JString;const Chars:PJChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewStringUTF:function(Env:PJNIEnv;const UTF:pchar):JString;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStringUTFLength:function(Env:PJNIEnv;Str:JString):JSize;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStringUTFChars:function(Env:PJNIEnv;Str:JString;IsCopy:PJBoolean):pchar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseStringUTFChars:procedure(Env:PJNIEnv;Str:JString;const Chars:pchar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetArrayLength:function(Env:PJNIEnv;AArray:JArray):JSize;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewObjectArray:function(Env:PJNIEnv;Len:JSize;AClass:JClass;Init:JObject):JObjectArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetObjectArrayElement:function(Env:PJNIEnv;AArray:JObjectArray;Index:JSize):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetObjectArrayElement:procedure(Env:PJNIEnv;AArray:JObjectArray;Index:JSize;Val:JObject);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewBooleanArray:function(Env:PJNIEnv;Len:JSize):JBooleanArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewByteArray:function(Env:PJNIEnv;Len:JSize):JByteArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewCharArray:function(Env:PJNIEnv;Len:JSize):JCharArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewShortArray:function(Env:PJNIEnv;Len:JSize):JShortArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewIntArray:function(Env:PJNIEnv;Len:JSize):JIntArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewLongArray:function(Env:PJNIEnv;Len:JSize):JLongArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewFloatArray:function(Env:PJNIEnv;Len:JSize):JFloatArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} NewDoubleArray:function(Env:PJNIEnv;Len:JSize):JDoubleArray;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetBooleanArrayElements:function(Env:PJNIEnv;AArray:JBooleanArray;var IsCopy:JBoolean):PJBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetByteArrayElements:function(Env:PJNIEnv;AArray:JByteArray;var IsCopy:JBoolean):PJByte;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetCharArrayElements:function(Env:PJNIEnv;AArray:JCharArray;var IsCopy:JBoolean):PJChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetShortArrayElements:function(Env:PJNIEnv;AArray:JShortArray;var IsCopy:JBoolean):PJShort;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetIntArrayElements:function(Env:PJNIEnv;AArray:JIntArray;var IsCopy:JBoolean):PJInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetLongArrayElements:function(Env:PJNIEnv;AArray:JLongArray;var IsCopy:JBoolean):PJLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetFloatArrayElements:function(Env:PJNIEnv;AArray:JFloatArray;var IsCopy:JBoolean):PJFloat;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetDoubleArrayElements:function(Env:PJNIEnv;AArray:JDoubleArray;var IsCopy:JBoolean):PJDouble;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseBooleanArrayElements:procedure(Env:PJNIEnv;AArray:JBooleanArray;Elems:PJBoolean;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseByteArrayElements:procedure(Env:PJNIEnv;AArray:JByteArray;Elems:PJByte;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseCharArrayElements:procedure(Env:PJNIEnv;AArray:JCharArray;Elems:PJChar;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseShortArrayElements:procedure(Env:PJNIEnv;AArray:JShortArray;Elems:PJShort;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseIntArrayElements:procedure(Env:PJNIEnv;AArray:JIntArray;Elems:PJInt;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseLongArrayElements:procedure(Env:PJNIEnv;AArray:JLongArray;Elems:PJLong;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseFloatArrayElements:procedure(Env:PJNIEnv;AArray:JFloatArray;Elems:PJFloat;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseDoubleArrayElements:procedure(Env:PJNIEnv;AArray:JDoubleArray;Elems:PJDouble;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetBooleanArrayRegion:procedure(Env:PJNIEnv;AArray:JBooleanArray;Start:JSize;Len:JSize;Buf:PJBoolean);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetByteArrayRegion:procedure(Env:PJNIEnv;AArray:JByteArray;Start:JSize;Len:JSize;Buf:PJByte);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetCharArrayRegion:procedure(Env:PJNIEnv;AArray:JCharArray;Start:JSize;Len:JSize;Buf:PJChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetShortArrayRegion:procedure(Env:PJNIEnv;AArray:JShortArray;Start:JSize;Len:JSize;Buf:PJShort);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetIntArrayRegion:procedure(Env:PJNIEnv;AArray:JIntArray;Start:JSize;Len:JSize;Buf:PJInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetLongArrayRegion:procedure(Env:PJNIEnv;AArray:JLongArray;Start:JSize;Len:JSize;Buf:PJLong);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetFloatArrayRegion:procedure(Env:PJNIEnv;AArray:JFloatArray;Start:JSize;Len:JSize;Buf:PJFloat);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetDoubleArrayRegion:procedure(Env:PJNIEnv;AArray:JDoubleArray;Start:JSize;Len:JSize;Buf:PJDouble);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetBooleanArrayRegion:procedure(Env:PJNIEnv;AArray:JBooleanArray;Start:JSize;Len:JSize;Buf:PJBoolean);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetByteArrayRegion:procedure(Env:PJNIEnv;AArray:JByteArray;Start:JSize;Len:JSize;Buf:PJByte);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetCharArrayRegion:procedure(Env:PJNIEnv;AArray:JCharArray;Start:JSize;Len:JSize;Buf:PJChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetShortArrayRegion:procedure(Env:PJNIEnv;AArray:JShortArray;Start:JSize;Len:JSize;Buf:PJShort);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetIntArrayRegion:procedure(Env:PJNIEnv;AArray:JIntArray;Start:JSize;Len:JSize;Buf:PJInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetLongArrayRegion:procedure(Env:PJNIEnv;AArray:JLongArray;Start:JSize;Len:JSize;Buf:PJLong);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetFloatArrayRegion:procedure(Env:PJNIEnv;AArray:JFloatArray;Start:JSize;Len:JSize;Buf:PJFloat);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} SetDoubleArrayRegion:procedure(Env:PJNIEnv;AArray:JDoubleArray;Start:JSize;Len:JSize;Buf:PJDouble);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} RegisterNatives:function(Env:PJNIEnv;AClass:JClass;const Methods:PJNINativeMethod;NMethods:JInt):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} UnregisterNatives:function(Env:PJNIEnv;AClass:JClass):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} MonitorEnter:function(Env:PJNIEnv;Obj:JObject):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} MonitorExit:function(Env:PJNIEnv;Obj:JObject):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetJavaVM:function(Env:PJNIEnv;var VM:JavaVM):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // String Operations GetStringRegion:procedure(Env:PJNIEnv;Str:JString;Start:JSize;Len:JSize;Buf:PJChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetStringUTFRegion:procedure(Env:PJNIEnv;Str:JString;Start:JSize;Len:JSize;Buf:pchar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Array Operations GetPrimitiveArrayCritical:function(Env:PJNIEnv;AArray:JArray;var IsCopy:JBoolean):pointer;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleasePrimitiveArrayCritical:procedure(Env:PJNIEnv;AArray:JArray;CArray:pointer;Mode:JInt);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // String Operations GetStringCritical:function(Env:PJNIEnv;Str:JString;var IsCopy:JBoolean):PJChar;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} ReleaseStringCritical:procedure(Env:PJNIEnv;Str:JString;CString:PJChar);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Weak Global References NewWeakGlobalRef:function(Env:PJNIEnv;Obj:JObject):JWeak;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} DeleteWeakGlobalRef:procedure(Env:PJNIEnv;Ref:JWeak);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // Exceptions ExceptionCheck:function(Env:PJNIEnv):JBoolean;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // J2SDK1_4 NewDirectByteBuffer:function(Env:PJNIEnv;Address:pointer;Capacity:JLong):JObject;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetDirectBufferAddress:function(Env:PJNIEnv;Buf:JObject):pointer;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetDirectBufferCapacity:function(Env:PJNIEnv;Buf:JObject):JLong;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} // added in JNI 1.6 GetObjectRefType:function(Env:PJNIEnv;AObject:JObject):jobjectRefType;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} end; JNIInvokeInterface= record reserved0:pointer; reserved1:pointer; reserved2:pointer; DestroyJavaVM:function(PVM:PJavaVM):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} AttachCurrentThread:function(PVM:PJavaVM;PEnv:PPJNIEnv;Args:pointer):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} DetachCurrentThread:function(PVM:PJavaVM):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} GetEnv:function(PVM:PJavaVM;PEnv:Ppvpointer;Version:JInt):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} AttachCurrentThreadAsDaemon:function(PVM:PJavaVM;PEnv:PPJNIEnv;Args:pointer):JInt;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} end; JavaVMAttachArgs=packed record version:jint; // must be >= JNI_VERSION_1_2 name:pchar; // NULL or name of thread as modified UTF-8 str group:jobject; // global ref of a ThreadGroup object, or NULL end; (** * JNI 1.2+ initialization. (As of 1.6, the pre-1.2 structures are no * longer supported.) *) PJavaVMOption=^JavaVMOption; JavaVMOption={$ifdef packedrecords}packed{$endif} record optionString:pchar; extraInfo:pointer; end; JavaVMInitArgs={$ifdef packedrecords}packed{$endif} record version:jint; // use JNI_VERSION_1_2 or later nOptions:jint; options:PJavaVMOption; ignoreUnrecognized:Pjboolean; end; (* * VM initialization functions. * * Note these are the only symbols exported for JNI by the VM. *) {$ifdef jniexternals} function JNI_GetDefaultJavaVMInitArgs(p:pointer):jint;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif}external 'jni' name 'JNI_GetDefaultJavaVMInitArgs'; function JNI_CreateJavaVM(vm:PPJavaVM;AEnv:PPJNIEnv;p:pointer):jint;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif}external 'jni' name 'JNI_CreateJavaVM'; function JNI_GetCreatedJavaVMs(vm:PPJavaVM;ASize:jsize;p:Pjsize):jint;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif}external 'jni' name 'JNI_GetCreatedJavaVMs'; {$endif} (* * Prototypes for functions exported by loadable shared libs. These are * called by JNI, not provided by JNI. *) var CurrentJavaVM:PJavaVM=nil; CurrentJNIEnv:PJNIEnv=nil; function JNI_OnLoad(vm:PJavaVM;reserved:pointer):jint;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} procedure JNI_OnUnload(vm:PJavaVM;reserved:pointer);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} type PARect=^TARect; TARect=packed record left:cint32; top:cint32; right:int32; bottom:cint32; end; const LibAndroidName='libandroid.so'; LibJNIGraphicsName='libjnigraphics.so'; LibLogName='liblog.so'; ANDROID_LOG_UNKNOWN=0; ANDROID_LOG_DEFAULT=1; ANDROID_LOG_VERBOSE=2; ANDROID_LOG_DEBUG=3; ANDROID_LOG_INFO=4; ANDROID_LOG_WARN=5; ANDROID_LOG_ERROR=6; ANDROID_LOG_FATAL=7; ANDROID_LOG_SILENT=8; ANDROID_BITMAP_RESUT_SUCCESS=0; ANDROID_BITMAP_RESULT_BAD_PARAMETER=-1; ANDROID_BITMAP_RESULT_JNI_EXCEPTION=-2; ANDROID_BITMAP_RESULT_ALLOCATION_FAILED=-3; WINDOW_FORMAT_RGBA_8888=1; WINDOW_FORMAT_RGBX_8888=2; WINDOW_FORMAT_RGB_565=4; ALOOPER_PREPARE_ALLOW_NON_CALLBACKS=1 shl 0; ALOOPER_POLL_WAKE=-1; ALOOPER_POLL_CALLBACK=-2; ALOOPER_POLL_TIMEOUT=-3; ALOOPER_POLL_ERROR=-4; ALOOPER_EVENT_INPUT=1 shl 0; ALOOPER_EVENT_OUTPUT=1 shl 1; ALOOPER_EVENT_ERROR=1 shl 2; ALOOPER_EVENT_HANGUP=1 shl 3; ALOOPER_EVENT_INVALID=1 shl 4; AKEYCODE_UNKNOWN=0; AKEYCODE_SOFT_LEFT=1; AKEYCODE_SOFT_RIGHT=2; AKEYCODE_HOME=3; AKEYCODE_BACK=4; AKEYCODE_CALL=5; AKEYCODE_ENDCALL=6; AKEYCODE_0=7; AKEYCODE_1=8; AKEYCODE_2=9; AKEYCODE_3=10; AKEYCODE_4=11; AKEYCODE_5=12; AKEYCODE_6=13; AKEYCODE_7=14; AKEYCODE_8=15; AKEYCODE_9=16; AKEYCODE_STAR=17; AKEYCODE_POUND=18; AKEYCODE_DPAD_UP=19; AKEYCODE_DPAD_DOWN=20; AKEYCODE_DPAD_LEFT=21; AKEYCODE_DPAD_RIGHT=22; AKEYCODE_DPAD_CENTER=23; AKEYCODE_VOLUME_UP=24; AKEYCODE_VOLUME_DOWN=25; AKEYCODE_POWER=26; AKEYCODE_CAMERA=27; AKEYCODE_CLEAR=28; AKEYCODE_A=29; AKEYCODE_B=30; AKEYCODE_C=31; AKEYCODE_D=32; AKEYCODE_E=33; AKEYCODE_F=34; AKEYCODE_G=35; AKEYCODE_H=36; AKEYCODE_I=37; AKEYCODE_J=38; AKEYCODE_K=39; AKEYCODE_L=40; AKEYCODE_M=41; AKEYCODE_N=42; AKEYCODE_O=43; AKEYCODE_P=44; AKEYCODE_Q=45; AKEYCODE_R=46; AKEYCODE_S=47; AKEYCODE_T=48; AKEYCODE_U=49; AKEYCODE_V=50; AKEYCODE_W=51; AKEYCODE_X=52; AKEYCODE_Y=53; AKEYCODE_Z=54; AKEYCODE_COMMA=55; AKEYCODE_PERIOD=56; AKEYCODE_ALT_LEFT=57; AKEYCODE_ALT_RIGHT=58; AKEYCODE_SHIFT_LEFT=59; AKEYCODE_SHIFT_RIGHT=60; AKEYCODE_TAB=61; AKEYCODE_SPACE=62; AKEYCODE_SYM=63; AKEYCODE_EXPLORER=64; AKEYCODE_ENVELOPE=65; AKEYCODE_ENTER=66; AKEYCODE_DEL=67; AKEYCODE_GRAVE=68; AKEYCODE_MINUS=69; AKEYCODE_EQUALS=70; AKEYCODE_LEFT_BRACKET=71; AKEYCODE_RIGHT_BRACKET=72; AKEYCODE_BACKSLASH=73; AKEYCODE_SEMICOLON=74; AKEYCODE_APOSTROPHE=75; AKEYCODE_SLASH=76; AKEYCODE_AT=77; AKEYCODE_NUM=78; AKEYCODE_HEADSETHOOK=79; AKEYCODE_FOCUS=80; // *Camera* focus AKEYCODE_PLUS=81; AKEYCODE_MENU=82; AKEYCODE_NOTIFICATION=83; AKEYCODE_SEARCH=84; AKEYCODE_MEDIA_PLAY_PAUSE=85; AKEYCODE_MEDIA_STOP=86; AKEYCODE_MEDIA_NEXT=87; AKEYCODE_MEDIA_PREVIOUS=88; AKEYCODE_MEDIA_REWIND=89; AKEYCODE_MEDIA_FAST_FORWARD=90; AKEYCODE_MUTE=91; AKEYCODE_PAGE_UP=92; AKEYCODE_PAGE_DOWN=93; AKEYCODE_PICTSYMBOLS=94; AKEYCODE_SWITCH_CHARSET=95; AKEYCODE_BUTTON_A=96; AKEYCODE_BUTTON_B=97; AKEYCODE_BUTTON_C=98; AKEYCODE_BUTTON_X=99; AKEYCODE_BUTTON_Y=100; AKEYCODE_BUTTON_Z=101; AKEYCODE_BUTTON_L1=102; AKEYCODE_BUTTON_R1=103; AKEYCODE_BUTTON_L2=104; AKEYCODE_BUTTON_R2=105; AKEYCODE_BUTTON_THUMBL=106; AKEYCODE_BUTTON_THUMBR=107; AKEYCODE_BUTTON_START=108; AKEYCODE_BUTTON_SELECT=109; AKEYCODE_BUTTON_MODE=110; // Now all elements from android.view.KeyEvent ACTION_DOWN=0; ACTION_MULTIPLE=2; ACTION_UP=1; FLAG_CANCELED=$20; FLAG_CANCELED_LONG_PRESS=$100; FLAG_EDITOR_ACTION=$10; FLAG_FALLBACK=$400; FLAG_FROM_SYSTEM=8; FLAG_KEEP_TOUCH_MODE=4; FLAG_LONG_PRESS=$80; FLAG_SOFT_KEYBOARD=2; FLAG_TRACKING=$200; FLAG_VIRTUAL_HARD_KEY=$40; FLAG_WOKE_HERE=1; KEYCODE_0=7; KEYCODE_1=8; KEYCODE_2=9; KEYCODE_3=10; KEYCODE_3D_MODE=$000000ce; // 3D Mode key. Toggles the display between 2D and 3D mode. KEYCODE_4=11; KEYCODE_5=12; KEYCODE_6=13; KEYCODE_7=14; KEYCODE_8=15; KEYCODE_9=16; KEYCODE_A=29; KEYCODE_ALT_LEFT=$00000039; KEYCODE_ALT_RIGHT=$0000003a; KEYCODE_APOSTROPHE=$0000004b; KEYCODE_APP_SWITCH=$000000bb; KEYCODE_AT=$0000004d; KEYCODE_AVR_INPUT=$000000b6; KEYCODE_AVR_POWER=$000000b5; KEYCODE_B=30; KEYCODE_BACK=4; KEYCODE_BACKSLASH=$00000049; KEYCODE_BOOKMARK=$000000ae; KEYCODE_BREAK=$00000079; KEYCODE_BUTTON_1=$000000bc; KEYCODE_BUTTON_10=$000000c5; KEYCODE_BUTTON_11=$000000c6; KEYCODE_BUTTON_12=$000000c7; KEYCODE_BUTTON_13=$000000c8; KEYCODE_BUTTON_14=$000000c9; KEYCODE_BUTTON_15=$000000ca; KEYCODE_BUTTON_16=$000000cb; // Generic Game Pad Button #16. KEYCODE_BUTTON_2=$000000bd; // Generic Game Pad Button #2. KEYCODE_BUTTON_3=$000000be; KEYCODE_BUTTON_4=$000000bf; KEYCODE_BUTTON_5=$000000c0; KEYCODE_BUTTON_6=$000000c1; KEYCODE_BUTTON_7=$000000c2; KEYCODE_BUTTON_8=$000000c3; KEYCODE_BUTTON_9=$000000c4; // Generic Game Pad Button #9. KEYCODE_BUTTON_A=$00000060; // A Button key. On a game controller, the A button should be either the button labeled A or the first button on the upper row of controller buttons. KEYCODE_BUTTON_B=$00000061; KEYCODE_BUTTON_C=$00000062; KEYCODE_BUTTON_L1=$00000066; // L1 Button key. On a game controller, the L1 button should be either the button labeled L1 (or L) or the top left trigger button. KEYCODE_BUTTON_L2=$00000068; KEYCODE_BUTTON_MODE=$0000006e; // Mode Button key. On a game controller, the button labeled Mode. KEYCODE_BUTTON_R1=$00000067; // R1 Button key. On a game controller, the R1 button should be either the button labeled R1 (or R) or the top right trigger button. KEYCODE_BUTTON_R2=$00000069; // R2 Button key. On a game controller, the R2 button should be either the button labeled R2 or the bottom right trigger button. KEYCODE_BUTTON_SELECT=$0000006d; // Select Button key. On a game controller, the button labeled Select. KEYCODE_BUTTON_START=$0000006c; // Start Button key. On a game controller, the button labeled Start. KEYCODE_BUTTON_THUMBL=$0000006a; // Left Thumb Button key. On a game controller, the left thumb button indicates that the left (or only) joystick is pressed. KEYCODE_BUTTON_THUMBR=$0000006b; // Right Thumb Button key. On a game controller, the right thumb button indicates that the right joystick is pressed. KEYCODE_BUTTON_X=$00000063; // X Button key. On a game controller, the X button should be either the button labeled X or the first button on the lower row of controller buttons. KEYCODE_BUTTON_Y=$00000064; // Y Button key. On a game controller, the Y button should be either the button labeled Y or the second button on the lower row of controller buttons. KEYCODE_BUTTON_Z=$00000065; // Z Button key. On a game controller, the Z button should be either the button labeled Z or the third button on the lower row of controller buttons. KEYCODE_C=31; // 'C' key. KEYCODE_CALCULATOR=$000000d2; // Calculator special function key. Used to launch a calculator application. KEYCODE_CALENDAR=$000000d0; // Calendar special function key. Used to launch a calendar application. KEYCODE_CALL=$00000005; // Call key. KEYCODE_CAMERA=$0000001b; // Camera key. Used to launch a camera application or take pictures. KEYCODE_CAPS_LOCK=$00000073; KEYCODE_CAPTIONS=$000000af; // Toggle captions key. Switches the mode for closed-captioning text, for example during television shows. KEYCODE_CHANNEL_DOWN=$000000a7; // Channel down key. On TV remotes, decrements the television channel. KEYCODE_CHANNEL_UP=$000000a6; // Channel up key. On TV remotes, increments the television channel. KEYCODE_CLEAR=$0000001c; KEYCODE_COMMA=$00000037; KEYCODE_CONTACTS=$000000cf; // Contacts special function key. Used to launch an address book application. KEYCODE_CTRL_LEFT=$00000071; // Left Control modifier key. KEYCODE_CTRL_RIGHT=$00000072; // Right Control modifier key. KEYCODE_D=32; KEYCODE_DEL=$00000043; // Backspace key. Deletes characters before the insertion point, unlike KEYCODE_FORWARD_DEL. KEYCODE_DPAD_CENTER=$00000017; // Directional Pad Center key. May also be synthesized from trackball motions. KEYCODE_DPAD_DOWN=$00000014; // Directional Pad Down key. May also be synthesized from trackball motions. KEYCODE_DPAD_LEFT=$00000015; // Directional Pad Left key. May also be synthesized from trackball motions. KEYCODE_DPAD_RIGHT=$00000016; // Directional Pad Right key. May also be synthesized from trackball motions. KEYCODE_DPAD_UP=$00000013; // Directional Pad Up key. May also be synthesized from trackball motions. KEYCODE_DVR=$000000ad; // DVR key. On some TV remotes, switches to a DVR mode for recorded shows. KEYCODE_E=33; KEYCODE_ENDCALL=$00000006; // End Call key. KEYCODE_ENTER=$00000042; // Enter key. KEYCODE_ENVELOPE=$00000041; // Envelope special function key. Used to launch a mail application. KEYCODE_EQUALS=$00000046; // '=' key. KEYCODE_ESCAPE=$0000006f; // Escape key. KEYCODE_EXPLORER=$00000040; // Explorer special function key. Used to launch a browser application. KEYCODE_F=34; // 'F' key. KEYCODE_F1=$00000083; KEYCODE_F10=$0000008c; KEYCODE_F11=$0000008d; KEYCODE_F12=$0000008e; KEYCODE_F2=$00000084; KEYCODE_F3=$00000085; KEYCODE_F4=$00000086; KEYCODE_F5=$00000087; KEYCODE_F6=$00000088; KEYCODE_F7=$00000089; KEYCODE_F8=$0000008a; KEYCODE_F9=$0000008b; KEYCODE_FOCUS=$00000050; // Camera Focus key. Used to focus the camera. KEYCODE_FORWARD=$0000007d; // Forward key. Navigates forward in the history stack. Complement of KEYCODE_BACK. KEYCODE_FORWARD_DEL=$00000070; // Forward Delete key. Deletes characters ahead of the insertion point, unlike KEYCODE_DEL. KEYCODE_FUNCTION=$00000077; // Function modifier key. KEYCODE_G=35; KEYCODE_GRAVE=$00000044; // '`' (backtick) key. KEYCODE_GUIDE=$000000ac; // Guide key. On TV remotes, shows a programming guide. KEYCODE_H=36; KEYCODE_HEADSETHOOK=$0000004f; // Headset Hook key. Used to hang up calls and stop media. KEYCODE_HOME=$00000003; // Home key. This key is handled by the framework and is never delivered to applications. KEYCODE_I=37; KEYCODE_INFO=$000000a5; // Info key. Common on TV remotes to show additional information related to what is currently being viewed. KEYCODE_INSERT=$0000007c; // Insert key. Toggles insert / overwrite edit mode. KEYCODE_J=38; KEYCODE_K=39; KEYCODE_L=40; KEYCODE_LANGUAGE_SWITCH=$000000cc; // Language Switch key. Toggles the current input language such as switching between English and Japanese on a QWERTY keyboard. On some devices, the same function may be performed by pressing Shift+Spacebar. KEYCODE_LEFT_BRACKET=$00000047; // '[' key. KEYCODE_M=41; KEYCODE_MANNER_MODE=$000000cd; // Manner Mode key. Toggles silent or vibrate mode on and off to make the device behave more politely in certain settings such as on a crowded train. On some devices, the key may only operate when long-pressed. KEYCODE_MEDIA_CLOSE=$00000080; // Close media key. May be used to close a CD tray, for example. KEYCODE_MEDIA_EJECT=$00000081; // Eject media key. May be used to eject a CD tray, for example. KEYCODE_MEDIA_FAST_FORWARD=$0000005a; // Fast Forward media key. KEYCODE_MEDIA_NEXT=$00000057; // Play Next media key. KEYCODE_MEDIA_PAUSE=$0000007f; // Pause media key. KEYCODE_MEDIA_PLAY=$0000007e; // Play media key. KEYCODE_MEDIA_PLAY_PAUSE=$00000055; // Play/Pause media key. KEYCODE_MEDIA_PREVIOUS=$00000058; // Play Previous media key. KEYCODE_MEDIA_RECORD=$00000082; // Record media key. KEYCODE_MEDIA_REWIND=$00000059; // Rewind media key. KEYCODE_MEDIA_STOP=$00000056; // Stop media key. KEYCODE_MENU=$00000052; // Menu key. KEYCODE_META_LEFT=$00000075; // Left Meta modifier key. KEYCODE_META_RIGHT=$00000076; // Right Meta modifier key. KEYCODE_MINUS=$00000045; // '-' KEYCODE_MOVE_END =$0000007b; // End Movement key. Used for scrolling or moving the cursor around to the end of a line or to the bottom of a list. KEYCODE_MOVE_HOME=$0000007a; // Home Movement key. Used for scrolling or moving the cursor around to the start of a line or to the top of a list. KEYCODE_MUSIC=$000000d1; // Music special function key. Used to launch a music player application. KEYCODE_MUTE=$0000005b; //Mute key. Mutes the microphone, unlike KEYCODE_VOLUME_MUTE KEYCODE_N=42; KEYCODE_NOTIFICATION=$00000053; KEYCODE_NUM=$0000004e; // Number modifier key. Used to enter numeric symbols. This key is not Num Lock; it is more like KEYCODE_ALT_LEFT and is interpreted as an ALT key by MetaKeyKeyListener. KEYCODE_NUMPAD_0=$00000090; KEYCODE_NUMPAD_1=$00000091; KEYCODE_NUMPAD_2=$00000092; KEYCODE_NUMPAD_3=$00000093; KEYCODE_NUMPAD_4=$00000094; KEYCODE_NUMPAD_5=$00000095; KEYCODE_NUMPAD_6=$00000096; KEYCODE_NUMPAD_7=$00000097; KEYCODE_NUMPAD_8=$00000098; KEYCODE_NUMPAD_9=$00000099; KEYCODE_NUMPAD_ADD=$0000009d; KEYCODE_NUMPAD_COMMA=$0000009f; KEYCODE_NUMPAD_DIVIDE=$0000009a; KEYCODE_NUMPAD_DOT=$0000009e; KEYCODE_NUMPAD_ENTER=$000000a0; KEYCODE_NUMPAD_EQUALS=$000000a1; KEYCODE_NUMPAD_LEFT_PAREN=$000000a2; KEYCODE_NUMPAD_MULTIPLY=$0000009b; KEYCODE_NUMPAD_RIGHT_PAREN=$000000a3; KEYCODE_NUMPAD_SUBTRACT=$0000009c; KEYCODE_NUM_LOCK=$0000008f; KEYCODE_O=43; KEYCODE_P=44; KEYCODE_PAGE_DOWN=$0000005d; KEYCODE_PAGE_UP=$0000005c; KEYCODE_PERIOD=$00000038; KEYCODE_PICTSYMBOLS=$0000005e; KEYCODE_PLUS=$00000051; // '+' key KEYCODE_POUND=$00000012; // '#' key. KEYCODE_POWER=$0000001a; KEYCODE_PROG_BLUE=$000000ba; KEYCODE_PROG_GREEN=$000000b8; KEYCODE_PROG_RED=$000000b7; KEYCODE_PROG_YELLOW=$000000b9; KEYCODE_Q=45; KEYCODE_R=46; KEYCODE_RIGHT_BRACKET=$00000048; KEYCODE_S=47; KEYCODE_SCROLL_LOCK=$00000074; KEYCODE_SEARCH=$00000054; KEYCODE_SEMICOLON=$0000004a; KEYCODE_SETTINGS=$000000b0; KEYCODE_SHIFT_LEFT=59; KEYCODE_SHIFT_RIGHT=60; KEYCODE_SLASH=$0000004c; // '/' key. KEYCODE_SOFT_LEFT=$00000001; KEYCODE_SOFT_RIGHT=$00000002; KEYCODE_SPACE=$0000003e; KEYCODE_STAR=$00000011; KEYCODE_STB_INPUT=$000000b4; KEYCODE_STB_POWER=$000000b3; KEYCODE_SWITCH_CHARSET=$0000005f; KEYCODE_SYM=$0000003f; // Symbol modifier key. Used to enter alternate symbols. KEYCODE_SYSRQ=$00000078; // System Request / Print Screen key. KEYCODE_T=48; KEYCODE_TAB=$0000003d; KEYCODE_TV=$000000aa; KEYCODE_TV_INPUT=$000000b2; KEYCODE_TV_POWER=$000000b1; KEYCODE_U=49; KEYCODE_UNKNOWN=0; KEYCODE_V=50; KEYCODE_VOLUME_DOWN=$00000019; KEYCODE_VOLUME_MUTE=$000000a4; KEYCODE_VOLUME_UP=$00000018; KEYCODE_W=51; KEYCODE_WINDOW=$000000ab; // Window key. On TV remotes, toggles picture-in-picture mode or other windowing functions. KEYCODE_X=52; KEYCODE_Y=53; KEYCODE_Z=54; KEYCODE_ZOOM_IN=$000000a8; KEYCODE_ZOOM_OUT=$000000a9; MAX_KEYCODE=$00000054; // deprecated! META_ALT_LEFT_ON=$00000010; META_ALT_MASK=$00000032; META_ALT_ON=$00000002; META_ALT_RIGHT_ON=$00000020; META_CAPS_LOCK_ON=$00100000; META_CTRL_LEFT_ON=$00002000; META_CTRL_MASK=$00007000; META_CTRL_ON=$00001000; META_CTRL_RIGHT_ON=$00004000; META_FUNCTION_ON=$00000008; META_META_LEFT_ON=$00020000; META_META_MASK=$00070000; META_META_ON=$00010000; META_META_RIGHT_ON=$00040000; META_NUM_LOCK_ON=$00200000; META_SCROLL_LOCK_ON=$00400000; META_SHIFT_LEFT_ON=$00000040; META_SHIFT_MASK=$000000c1; META_SHIFT_ON=$00000001; META_SHIFT_RIGHT_ON=$00000080; META_SYM_ON=4; AKEY_STATE_UNKNOWN=-1; AKEY_STATE_UP=0; AKEY_STATE_DOWN=1; AKEY_STATE_VIRTUAL=2; AMETA_NONE=0; AMETA_SHIFT_ON=$01; AMETA_ALT_ON=$02; AMETA_SYM_ON=$04; AMETA_ALT_LEFT_ON=$10; AMETA_ALT_RIGHT_ON=$20; AMETA_SHIFT_LEFT_ON=$40; AMETA_SHIFT_RIGHT_ON=$80; AINPUT_EVENT_TYPE_KEY=1; AINPUT_EVENT_TYPE_MOTION=2; AKEY_EVENT_ACTION_DOWN=0; AKEY_EVENT_ACTION_UP=1; AKEY_EVENT_ACTION_MULTIPLE=2; AKEY_EVENT_FLAG_WOKE_HERE=$1; AKEY_EVENT_FLAG_SOFT_KEYBOARD=$2; AKEY_EVENT_FLAG_KEEP_TOUCH_MODE=$4; AKEY_EVENT_FLAG_FROM_SYSTEM=$8; AKEY_EVENT_FLAG_EDITOR_ACTION=$10; AKEY_EVENT_FLAG_CANCELED=$20; AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY=$40; AKEY_EVENT_FLAG_LONG_PRESS=$80; AKEY_EVENT_FLAG_CANCELED_LONG_PRESS=$100; AKEY_EVENT_FLAG_TRACKING=$200; AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT=8; AMOTION_EVENT_ACTION_DOWN=0; AMOTION_EVENT_ACTION_UP=1; AMOTION_EVENT_ACTION_MOVE=2; AMOTION_EVENT_ACTION_CANCEL=3; AMOTION_EVENT_ACTION_OUTSIDE=4; AMOTION_EVENT_ACTION_POINTER_DOWN=5; AMOTION_EVENT_ACTION_POINTER_UP=6; AMOTION_EVENT_ACTION_MASK=$ff; AMOTION_EVENT_ACTION_POINTER_INDEX_MASK=$ff00; AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED=$1; AMOTION_EVENT_EDGE_FLAG_NONE=0; AMOTION_EVENT_EDGE_FLAG_TOP=$01; AMOTION_EVENT_EDGE_FLAG_BOTTOM=$02; AMOTION_EVENT_EDGE_FLAG_LEFT=$04; AMOTION_EVENT_EDGE_FLAG_RIGHT=$08; AINPUT_SOURCE_CLASS_MASK=$000000ff; AINPUT_SOURCE_CLASS_NONE=$00000000; AINPUT_SOURCE_CLASS_BUTTON=$00000001; AINPUT_SOURCE_CLASS_POINTER=$00000002; AINPUT_SOURCE_CLASS_NAVIGATION=$00000004; AINPUT_SOURCE_CLASS_POSITION=$00000008; AINPUT_SOURCE_CLASS_JOYSTICK=$00000010; AINPUT_SOURCE_UNKNOWN=$00000000; AINPUT_SOURCE_KEYBOARD=$00000100 or AINPUT_SOURCE_CLASS_BUTTON; AINPUT_SOURCE_DPAD=$00000200 or AINPUT_SOURCE_CLASS_BUTTON; AINPUT_SOURCE_GAMEPAD=$00000400 or AINPUT_SOURCE_CLASS_BUTTON; AINPUT_SOURCE_TOUCHSCREEN=$00001000 or AINPUT_SOURCE_CLASS_POINTER; AINPUT_SOURCE_MOUSE=$00002000 or AINPUT_SOURCE_CLASS_POINTER; AINPUT_SOURCE_STYLUS=$00004000 or AINPUT_SOURCE_CLASS_POINTER; AINPUT_SOURCE_BLUETOOTH_STYLUS=$00008000 or AINPUT_SOURCE_CLASS_POINTER; AINPUT_SOURCE_TRACKBALL=$00010000 or AINPUT_SOURCE_CLASS_NAVIGATION; AINPUT_SOURCE_MOUSE_RELATIVE=$00020000 or AINPUT_SOURCE_CLASS_NAVIGATION; AINPUT_SOURCE_TOUCHPAD=$00100000 or AINPUT_SOURCE_CLASS_POSITION; AINPUT_SOURCE_NAVIGATION=$00200000 or AINPUT_SOURCE_CLASS_NONE; AINPUT_SOURCE_JOYSTICK=$01000000 or AINPUT_SOURCE_CLASS_JOYSTICK; AINPUT_SOURCE_ROTARY_ENCODER=$00400000 or AINPUT_SOURCE_CLASS_NONE; AINPUT_SOURCE_ANY=$ffffff00; AINPUT_KEYBOARD_TYPE_NONE=0; AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC=1; AINPUT_KEYBOARD_TYPE_ALPHABETIC=2; AINPUT_MOTION_RANGE_X=0; AINPUT_MOTION_RANGE_Y=1; AINPUT_MOTION_RANGE_PRESSURE=2; AINPUT_MOTION_RANGE_SIZE=3; AINPUT_MOTION_RANGE_TOUCH_MAJOR=4; AINPUT_MOTION_RANGE_TOUCH_MINOR=5; AINPUT_MOTION_RANGE_TOOL_MAJOR=6; AINPUT_MOTION_RANGE_TOOL_MINOR=7; AINPUT_MOTION_RANGE_ORIENTATION=8; AASSET_MODE_UNKNOWN=0; AASSET_MODE_RANDOM=1; AASSET_MODE_STREAMING=2; AASSET_MODE_BUFFER=3; ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT=$0001; ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED=$0002; ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY=$0001; ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS=$0002; ACONFIGURATION_ORIENTATION_ANY=$0000; ACONFIGURATION_ORIENTATION_PORT=$0001; ACONFIGURATION_ORIENTATION_LAND=$0002; ACONFIGURATION_ORIENTATION_SQUARE=$0003; ACONFIGURATION_TOUCHSCREEN_ANY=$0000; ACONFIGURATION_TOUCHSCREEN_NOTOUCH=$0001; ACONFIGURATION_TOUCHSCREEN_STYLUS=$0002; ACONFIGURATION_TOUCHSCREEN_FINGER=$0003; ACONFIGURATION_DENSITY_DEFAULT=0; ACONFIGURATION_DENSITY_LOW=120; ACONFIGURATION_DENSITY_MEDIUM=160; ACONFIGURATION_DENSITY_HIGH=240; ACONFIGURATION_DENSITY_NONE=$ffff; ACONFIGURATION_KEYBOARD_ANY=$0000; ACONFIGURATION_KEYBOARD_NOKEYS=$0001; ACONFIGURATION_KEYBOARD_QWERTY=$0002; ACONFIGURATION_KEYBOARD_12KEY=$0003; ACONFIGURATION_NAVIGATION_ANY=$0000; ACONFIGURATION_NAVIGATION_NONAV=$0001; ACONFIGURATION_NAVIGATION_DPAD=$0002; ACONFIGURATION_NAVIGATION_TRACKBALL=$0003; ACONFIGURATION_NAVIGATION_WHEEL=$0004; ACONFIGURATION_KEYSHIDDEN_ANY=$0000; ACONFIGURATION_KEYSHIDDEN_NO=$0001; ACONFIGURATION_KEYSHIDDEN_YES=$0002; ACONFIGURATION_KEYSHIDDEN_SOFT=$0003; ACONFIGURATION_NAVHIDDEN_ANY=$0000; ACONFIGURATION_NAVHIDDEN_NO=$0001; ACONFIGURATION_NAVHIDDEN_YES=$0002; ACONFIGURATION_SCREENSIZE_ANY=$00; ACONFIGURATION_SCREENSIZE_SMALL=$01; ACONFIGURATION_SCREENSIZE_NORMAL=$02; ACONFIGURATION_SCREENSIZE_LARGE=$03; ACONFIGURATION_SCREENSIZE_XLARGE=$04; ACONFIGURATION_SCREENLONG_ANY=$00; ACONFIGURATION_SCREENLONG_NO=$1; ACONFIGURATION_SCREENLONG_YES=$2; ACONFIGURATION_UI_MODE_TYPE_ANY=$00; ACONFIGURATION_UI_MODE_TYPE_NORMAL=$01; ACONFIGURATION_UI_MODE_TYPE_DESK=$02; ACONFIGURATION_UI_MODE_TYPE_CAR=$03; ACONFIGURATION_UI_MODE_NIGHT_ANY=$00; ACONFIGURATION_UI_MODE_NIGHT_NO=$1; ACONFIGURATION_UI_MODE_NIGHT_YES=$2; ACONFIGURATION_MCC=$0001; ACONFIGURATION_MNC=$0002; ACONFIGURATION_LOCALE=$0004; ACONFIGURATION_TOUCHSCREEN=$0008; ACONFIGURATION_KEYBOARD=$0010; ACONFIGURATION_KEYBOARD_HIDDEN=$0020; ACONFIGURATION_NAVIGATION=$0040; ACONFIGURATION_ORIENTATION=$0080; ACONFIGURATION_DENSITY=$0100; ACONFIGURATION_SCREEN_SIZE=$0200; ACONFIGURATION_VERSION=$0400; ACONFIGURATION_SCREEN_LAYOUT=$0800; ACONFIGURATION_UI_MODE=$1000; type android_LogPriority=cint; Pint=^cint; PANativeWindow=^TANativeWindow; TANativeWindow=record end; PANativeWindow_Buffer=^TANativeWindow_Buffer; TANativeWindow_Buffer=packed record width:cint32; height:cint32; stride:cint32; format:cint32; bits:pointer; reserved:array[0..5] of cuint32; end; PALooper=^TALooper; TALooper=record end; PPAInputEvent=^PAInputEvent; PAInputEvent=^TAInputEvent; TAInputEvent=record end; PAInputQueue=^TAInputQueue; TAInputQueue=record end; TALooper_callbackFunc=function(fd,events:cint;data:Pointer):cint; cdecl; PAndroidBitmapFormat=^TAndroidBitmapFormat; TAndroidBitmapFormat=( ANDROID_BITMAP_FORMAT_NONE=0, ANDROID_BITMAP_FORMAT_RGBA_8888=1, ANDROID_BITMAP_FORMAT_RGB_565=4, ANDROID_BITMAP_FORMAT_RGBA_4444=7, ANDROID_BITMAP_FORMAT_A_8=8 ); PAndroidBitmapInfo=^TAndroidBitmapInfo; TAndroidBitmapInfo=record width:uint32; height:uint32; stride:uint32; format:int32; flags:uint32; end; PAAssetManager=^TAAssetManager; TAAssetManager=record end; PAAssetDir=^TAAssetDir; TAAssetDir=record end; PAAsset=^tAAsset; TAAsset=record end; PAConfiguration=^TAConfiguration; TAConfiguration=record end; Poff_t=^coff_t; PANativeActivityCallbacks=^TANativeActivityCallbacks; PANativeActivity=^TANativeActivity; TANativeActivity=packed record callbacks:PANativeActivityCallbacks; vm:PJavaVM; env:PJNIEnv; clazz:jobject; internalDataPath:PAnsiChar; externalDataPath:PAnsiChar; sdkVersion:longword; instance:Pointer; assetManager:PAAssetManager; end; Psize_t=^csize_t; TANativeActivityCallbacks=packed record onStart:procedure(activity:PANativeActivity); cdecl; onResume:procedure(activity:PANativeActivity); cdecl; onSaveInstanceState:function(activity:PANativeActivity;outSize:Psize_t):Pointer; cdecl; onPause:procedure(activity:PANativeActivity); cdecl; onStop:procedure(activity:PANativeActivity); cdecl; onDestroy:procedure(activity:PANativeActivity); cdecl; onWindowFocusChanged:procedure(activity:PANativeActivity;hasFocus:cint); cdecl; onNativeWindowCreated:procedure(activity:PANativeActivity;window:PANativeWindow); cdecl; onNativeWindowResized:procedure(activity:PANativeActivity;window:PANativeWindow); cdecl; onNativeWindowRedrawNeeded:procedure(activity:PANativeActivity;window:PANativeWindow); cdecl; onNativeWindowDestroyed:procedure(activity:PANativeActivity;window:PANativeWindow); cdecl; onInputQueueCreated:procedure(activity:PANativeActivity;queue:PAInputQueue); cdecl; onInputQueueDestroyed:procedure(activity:PANativeActivity;queue:PAInputQueue); cdecl; onContentRectChanged:procedure(activity:PANativeActivity;rect:PARect); cdecl; onConfigurationChanged:procedure(activity:PANativeActivity); cdecl; onLowMemory:procedure(activity:PANativeActivity); cdecl; end; TANativeActivity_createFunc=procedure(activity:PANativeActivity;savedState:pointer;savedStateSize:SizeInt); cdecl; //var ANativeActivity_onCreate:TANativeActivity_createFunc; external; function __android_log_write(prio:cint;tag,text:PAnsiChar):cint; cdecl; external LibLogName name '__android_log_write'; function LOGI(prio:longint;tag,text:PAnsiChar):cint; cdecl; varargs; external LibLogName name '__android_log_print'; procedure LOGW(const Text:PAnsiChar;const Tag:PAnsiChar=''); //function __android_log_print(prio:cint;tag,print:PAnsiChar;params:array of PAnsiChar):cint; cdecl; external LibLogName name '__android_log_print'; procedure ANativeWindow_acquire(window:PANativeWindow); cdecl; external LibAndroidName name 'ANativeWindow_acquire'; procedure ANativeWindow_release(window:PANativeWindow); cdecl; external LibAndroidName name 'ANativeWindow_release'; function ANativeWindow_getWidth(window:PANativeWindow):cint32; cdecl; external LibAndroidName name 'ANativeWindow_getWidth'; function ANativeWindow_getHeight(window:PANativeWindow):cint32; cdecl; external LibAndroidName name 'ANativeWindow_getHeight'; function ANativeWindow_getFormat(window:PANativeWindow):cint32; cdecl; external LibAndroidName name 'ANativeWindow_getFormat'; function ANativeWindow_setBuffersGeometry(window:PANativeWindow;width,height,format:cint32):cint32; cdecl; external LibAndroidName name 'ANativeWindow_setBuffersGeometry'; function ANativeWindow_lock(window:PANativeWindow;outBuffer:PANativeWindow_Buffer;inOutDirtyBounds:PARect):cint32; cdecl; external LibAndroidName name 'ANativeWindow_lock'; function ANativeWindow_unlockAndPost(window:PANativeWindow):cint32; cdecl; external LibAndroidName name 'ANativeWindow_unlockAndPost'; function ALooper_forThread:PALooper; cdecl; external LibAndroidName name 'ALooper_forThread'; function ALooper_prepare(opts:cint):PALooper; cdecl; external LibAndroidName name 'ALooper_prepare'; procedure ALooper_acquire(looper:PALooper); cdecl; external LibAndroidName name 'ALooper_acquire'; procedure ALooper_release(looper:PALooper); cdecl; external LibAndroidName name 'ALooper_release'; function ALooper_pollOnce(timeoutMillis:cint;outFd,outEvents:Pint;outData:PpvPointer):cint; cdecl; external LibAndroidName name 'ALooper_pollOnce'; function ALooper_pollAll(timeoutMillis:cint;outFd,outEvents:Pint;outData:PpvPointer):cint; cdecl; external LibAndroidName name 'ALooper_pollAll'; procedure ALooper_wake(looper:PALooper); cdecl; external LibAndroidName name 'ALooper_wake'; function ALooper_addFd(looper:PALooper;fd,ident,events:cint;callback:TALooper_callbackFunc;data:Pointer):cint; cdecl; external LibAndroidName name 'ALooper_addFd'; function ALooper_removeFd(looper:PALooper;fd:cint):cint; cdecl; external LibAndroidName name 'ALooper_removeFd'; function AInputEvent_getType(event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AInputEvent_getType'; function AInputEvent_getDeviceId(event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AInputEvent_getDeviceId'; function AInputEvent_getSource(event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AInputEvent_getSource'; function AKeyEvent_getAction(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getAction'; function AKeyEvent_getFlags(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getFlags'; function AKeyEvent_getKeyCode(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getKeyCode'; function AKeyEvent_getScanCode(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getScanCode'; function AKeyEvent_getMetaState(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getMetaState'; function AKeyEvent_getRepeatCount(key_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AKeyEvent_getRepeatCount'; function AKeyEvent_getDownTime(key_event:PAInputEvent):cint64; cdecl; external LibAndroidName name 'AKeyEvent_getDownTime'; function AKeyEvent_getEventTime(key_event:PAInputEvent):cint64; cdecl; external LibAndroidName name 'AKeyEvent_getEventTime'; function AMotionEvent_getAction(motion_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AMotionEvent_getAction'; function AMotionEvent_getFlags(motion_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AMotionEvent_getFlags'; function AMotionEvent_getMetaState(motion_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AMotionEvent_getMetaState'; function AMotionEvent_getEdgeFlags(motion_event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AMotionEvent_getEdgeFlags'; function AMotionEvent_getDownTime(motion_event:PAInputEvent):cint64; cdecl; external LibAndroidName name 'AMotionEvent_getDownTime'; function AMotionEvent_getEventTime(motion_event:PAInputEvent):cint64; cdecl; external LibAndroidName name 'AMotionEvent_getEventTime'; function AMotionEvent_getXOffset(motion_event:PAInputEvent):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getXOffset'; function AMotionEvent_getYOffset(motion_event:PAInputEvent):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getYOffset'; function AMotionEvent_getXPrecision(motion_event:PAInputEvent):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getXPrecision'; function AMotionEvent_getYPrecision(motion_event:PAInputEvent):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getYPrecision'; function AMotionEvent_getPointerCount(motion_event:PAInputEvent):csize_t; cdecl; external LibAndroidName name 'AMotionEvent_getPointerCount'; function AMotionEvent_getPointerId(motion_event:PAInputEvent;pointer_index:csize_t):cint32; cdecl; external LibAndroidName name 'AMotionEvent_getPointerId'; function AMotionEvent_getRawX(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getRawX'; function AMotionEvent_getRawY(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getRawY'; function AMotionEvent_getX(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getX'; function AMotionEvent_getY(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getY'; function AMotionEvent_getPressure(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getPressure'; function AMotionEvent_getSize(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getSize'; function AMotionEvent_getTouchMajor(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getTouchMajor'; function AMotionEvent_getTouchMinor(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getTouchMinor'; function AMotionEvent_getToolMajor(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getToolMajor'; function AMotionEvent_getToolMinor(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getToolMinor'; function AMotionEvent_getOrientation(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getOrientation'; function AMotionEvent_getHistorySize(motion_event:PAInputEvent):csize_t; cdecl; external LibAndroidName name 'AMotionEvent_getHistorySize'; function AMotionEvent_getHistoricalEventTime(motion_event:PAInputEvent;history_index:csize_t):cint64; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalEventTime'; function AMotionEvent_getHistoricalRawX(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalRawX'; function AMotionEvent_getHistoricalRawY(motion_event:PAInputEvent;pointer_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalRawY'; function AMotionEvent_getHistoricalX(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalX'; function AMotionEvent_getHistoricalY(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalY'; function AMotionEvent_getHistoricalPressure(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalPressure'; function AMotionEvent_getHistoricalSize(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalSize'; function AMotionEvent_getHistoricalTouchMajor(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalTouchMajor'; function AMotionEvent_getHistoricalTouchMinor(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalTouchMinor'; function AMotionEvent_getHistoricalToolMajor(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalToolMajor'; function AMotionEvent_getHistoricalToolMinor(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalToolMinor'; function AMotionEvent_getHistoricalOrientation(motion_event:PAInputEvent;pointer_index,history_index:csize_t):cfloat; cdecl; external LibAndroidName name 'AMotionEvent_getHistoricalOrientation'; procedure AInputQueue_attachLooper(queue:PAInputQueue;looper:PALooper;ident:cint;callback:TALooper_callbackFunc;data:Pointer); cdecl; external LibAndroidName name 'AInputQueue_attachLooper'; procedure AInputQueue_detachLooper(queue:PAInputQueue); cdecl; external LibAndroidName name 'AInputQueue_detachLooper'; function AInputQueue_hasEvents(queue:PAInputQueue):cint32; cdecl; external LibAndroidName name 'AInputQueue_hasEvents'; function AInputQueue_getEvent(queue:PAInputQueue;outEvent:PPAInputEvent):cint32; cdecl; external LibAndroidName name 'AInputQueue_getEvent'; function AInputQueue_preDispatchEvent(queue:PAInputQueue;event:PAInputEvent):cint32; cdecl; external LibAndroidName name 'AInputQueue_preDispatchEvent'; procedure AInputQueue_finishEvent(queue:PAInputQueue;event:PAInputEvent;handled:cint); cdecl; external LibAndroidName name 'AInputQueue_finishEvent'; function AndroidBitmap_getInfo(env:PJNIEnv;jbitmap:jobject;info: PAndroidBitmapInfo):cint; cdecl; external LibJNIGraphicsName name 'AndroidBitmap_getInfo'; function AndroidBitmap_lockPixels(env:PJNIEnv;jbitmap:jobject;addrPtr:PpvPointer):cint; cdecl; external LibJNIGraphicsName name 'AndroidBitmap_lockPixels'; function AndroidBitmap_unlockPixels(env:PJNIEnv;jbitmap:jobject):cint; cdecl; external LibJNIGraphicsName name 'AndroidBitmap_unlockPixels'; function AAssetManager_fromJava(env:PJNIEnv;assetManager:JObject): PAAssetManager; cdecl; external LibAndroidName name 'AAssetManager_fromJava'; function AAssetManager_openDir(mgr:PAAssetManager;dirName:PAnsiChar):PAAssetDir; cdecl; external LibAndroidName name 'AAssetManager_openDir'; function AAssetManager_open(mgr:PAAssetManager;filename:PAnsiChar;mode:cint):PAAsset; cdecl; external LibAndroidName name 'AAssetManager_open'; function AAssetDir_getNextFileName(assetDir:PAAssetDir):PAnsiChar; cdecl; external LibAndroidName name 'AAssetDir_getNextFileName'; procedure AAssetDir_rewind(assetDir:PAAssetDir); cdecl; external LibAndroidName name 'AAssetDir_rewind'; procedure AAssetDir_close(assetDir:PAAssetDir); cdecl; external LibAndroidName name 'AAssetDir_close'; function AAsset_read(asset:PAAsset;buf:Pointer;count:csize_t):cint; cdecl; external LibAndroidName name 'AAsset_read'; function AAsset_seek(asset:PAAsset;offset:coff_t;whence:cint):coff_t; cdecl; external LibAndroidName name 'AAsset_seek'; procedure AAsset_close(asset:PAAsset); cdecl; external LibAndroidName name 'AAsset_close'; function AAsset_getBuffer(asset:PAAsset):Pointer; cdecl; external LibAndroidName name 'AAsset_getBuffer'; function AAsset_getLength(asset:PAAsset):coff_t; cdecl; external LibAndroidName name 'AAsset_getLength'; function AAsset_getRemainingLength(asset:PAAsset):coff_t; cdecl; external LibAndroidName name 'AAsset_getRemainingLength'; function AAsset_openFileDescriptor(asset:PAAsset;outStart,outLength:Poff_t):cint; cdecl; external LibAndroidName name 'AAsset_openFileDescriptor'; function AAsset_isAllocated(asset:PAAsset):cint; cdecl; external LibAndroidName name 'AAsset_isAllocated'; procedure ANativeActivity_finish(activity:PANativeActivity); cdecl; external LibAndroidName name 'ANativeActivity_finish'; procedure ANativeActivity_setWindowFormat(activity:PANativeActivity;format:cint32); cdecl; external LibAndroidName name 'ANativeActivity_setWindowFormat'; procedure ANativeActivity_setWindowFlags(activity:PANativeActivity;addFlags,removeFlags:cuint32); cdecl; external LibAndroidName name 'ANativeActivity_setWindowFlags'; procedure ANativeActivity_showSoftInput(activity:PANativeActivity;flags:cuint32); cdecl; external LibAndroidName name 'ANativeActivity_showSoftInput'; procedure ANativeActivity_hideSoftInput(activity:PANativeActivity;flags:cuint32); cdecl; external LibAndroidName name 'ANativeActivity_hideSoftInput'; function AConfiguration_new:PAConfiguration; cdecl; external LibAndroidName; procedure AConfiguration_delete(config:PAConfiguration); cdecl; external LibAndroidName; procedure AConfiguration_fromAssetManager(out_:PAConfiguration;am:PAAssetManager); cdecl; external LibAndroidName; procedure AConfiguration_copy(dest,src:PAConfiguration); cdecl; external LibAndroidName; function AConfiguration_getMcc(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setMcc(config:PAConfiguration;mcc:cint32); cdecl; external LibAndroidName; function AConfiguration_getMnc(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setMnc(config:PAConfiguration;mnc:cint32); cdecl; external LibAndroidName; procedure AConfiguration_getLanguage(config:PAConfiguration;outLanguage:Pchar); cdecl; external LibAndroidName; procedure AConfiguration_setLanguage(config:PAConfiguration;language:Pchar); cdecl; external LibAndroidName; procedure AConfiguration_getCountry(config:PAConfiguration;outCountry:Pchar); cdecl; external LibAndroidName; procedure AConfiguration_setCountry(config:PAConfiguration;country:Pchar); cdecl; external LibAndroidName; function AConfiguration_getOrientation(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setOrientation(config:PAConfiguration; orientation:cint32); cdecl; external LibAndroidName; function AConfiguration_getTouchscreen(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setTouchscreen(config:PAConfiguration; touchscreen:cint32); cdecl; external LibAndroidName; function AConfiguration_getDensity(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setDensity(config:PAConfiguration; density:cint32); cdecl; external LibAndroidName; function AConfiguration_getKeyboard(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setKeyboard(config:PAConfiguration; keyboard:cint32); cdecl; external LibAndroidName; function AConfiguration_getNavigation(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setNavigation(config:PAConfiguration; navigation:cint32); cdecl; external LibAndroidName; function AConfiguration_getKeysHidden(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setKeysHidden(config:PAConfiguration; keysHidden:cint32); cdecl; external LibAndroidName; function AConfiguration_getNavHidden(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setNavHidden(config:PAConfiguration; navHidden:cint32); cdecl; external LibAndroidName; function AConfiguration_getSdkVersion(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setSdkVersion(config:PAConfiguration; sdkVersion:cint32); cdecl; external LibAndroidName; function AConfiguration_getScreenSize(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setScreenSize(config:PAConfiguration; screenSize:cint32); cdecl; external LibAndroidName; function AConfiguration_getScreenLong(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setScreenLong(config:PAConfiguration; screenLong:cint32); cdecl; external LibAndroidName; function AConfiguration_getUiModeType(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setUiModeType(config:PAConfiguration; uiModeType:cint32); cdecl; external LibAndroidName; function AConfiguration_getUiModeNight(config:PAConfiguration):cint32; cdecl; external LibAndroidName; procedure AConfiguration_setUiModeNight(config:PAConfiguration; uiModeNight:cint32); cdecl; external LibAndroidName; function AConfiguration_diff(config1,config2:PAConfiguration):cint32; cdecl; external LibAndroidName; function AConfiguration_match(base,requested:PAConfiguration):cint32; cdecl; external LibAndroidName; function AConfiguration_isBetterThan(base,test,requested:PAConfiguration) :cint32; cdecl; external LibAndroidName; function JStringToString(const aEnv:PJNIEnv;const aStr:JString):TJavaUnicodeString; function StringToJString(const aEnv:PJNIEnv;const aStr:TJavaUnicodeString):JString; procedure FreeJString(const aEnv:PJNIEnv;const aStr:JString); function GetHandleField(const aEnv:PJNIEnv;const aObj:jobject):jfieldID; function GetHandle(const aEnv:PJNIEnv;const aObj:jobject):pointer; procedure SetHandle(const aEnv:PJNIEnv;const aObj:jobject;const aPointer:pointer); {$ifend} implementation {$if defined(fpc) and defined(Android)} function JNI_OnLoad(vm:PJavaVM;reserved:pointer):jint;{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} begin {$ifndef Release} __android_log_write(ANDROID_LOG_VERBOSE,'PasVulkanApplication','Entering JNI_OnLoad . . .'); {$endif} CurrentJavaVM:=vm; result:=JNI_VERSION_1_6; {$ifndef Release} __android_log_write(ANDROID_LOG_VERBOSE,'PasVulkanApplication','Leaving JNI_OnLoad . . .'); {$endif} end; procedure JNI_OnUnload(vm:PJavaVM;reserved:pointer);{$ifdef mswindows}stdcall;{$else}cdecl;{$endif} begin {$ifndef Release} __android_log_write(ANDROID_LOG_VERBOSE,'PasVulkanApplication','Entering JNI_OnUnload . . .'); {$endif} {$ifndef Release} __android_log_write(ANDROID_LOG_VERBOSE,'PasVulkanApplication','Leaving JNI_OnUnload . . .'); {$endif} end; procedure LOGW(const Text:PAnsiChar;const Tag:PAnsiChar=''); begin __android_log_write(ANDROID_LOG_FATAL,Tag,text); end; function JStringToString(const aEnv:PJNIEnv;const aStr:JString):TJavaUnicodeString; var Len:Int32; IsCopy:JBoolean; Chars:PJChar; begin result:=''; if assigned(aStr) then begin Len:=aEnv^.GetStringLength(aEnv,aStr); if Len>0 then begin IsCopy:=0; Chars:=aEnv^.GetStringChars(aEnv,aStr,@IsCopy); if assigned(Chars) then begin try SetLength(result,Len); Move(Chars^,result[1],Len*SizeOf(WideChar)); finally aEnv^.ReleaseStringChars(aEnv,aStr,Chars); end; end; end; end; end; function StringToJString(const aEnv:PJNIEnv;const aStr:TJavaUnicodeString):JString; var l:jsize; begin //__android_log_write(ANDROID_LOG_DEBUG,'PasAndroidApplication',PAnsiChar(AnsiString('StringToJString Before: '+aStr))); l:=length(aStr); if l>0 then begin result:=aEnv^.NewString(aEnv,@aStr[1],l); end else begin result:=aEnv^.NewString(aEnv,nil,0); end; //__android_log_write(ANDROID_LOG_DEBUG,'PasAndroidApplication',PAnsiChar(AnsiString('StringToJString After: '+aStr))); end; procedure FreeJString(const aEnv:PJNIEnv;const aStr:JString); begin aEnv^.DeleteLocalRef(aEnv,aStr); end; function GetHandleField(const aEnv:PJNIEnv;const aObj:jobject):jfieldID; begin result:=aEnv^.GetFieldID(aEnv,aEnv^.GetObjectClass(aEnv,aObj),'nativeHandle','J'); end; function GetHandle(const aEnv:PJNIEnv;const aObj:jobject):pointer; begin result:=pointer(PtrUInt(jlong(aEnv^.GetLongField(aEnv,aObj,GetHandleField(aEnv,aObj))))); end; procedure SetHandle(const aEnv:PJNIEnv;const aObj:jobject;const aPointer:pointer); begin aEnv^.SetLongField(aEnv,aObj,GetHandleField(aEnv,aObj),jlong(PtrUInt(pointer(aPointer)))); end; {$ifend} end.
unit potentio; interface uses SysUtils, Classes, Controls, Forms, Messages, Windows, ExtCtrls, Graphics, Dialogs; type TPotentio = class(TCustomControl) private fColorFirst:TColor; fColorSecond:TColor; fColorThird:TColor; fColorEmpty:TColor; fBorderColor:TColor; fButtonColor:TColor; fStickColor:TColor; fMin : Integer; fMax : Integer; fPos:Integer; fDelta:double; fVisiblePosition : Boolean; fText : String; fOnChange: TNotifyEvent; Procedure Set_Min(Value:Integer); Procedure Set_Max(Value:Integer); Procedure Set_Pos(Value:Integer); Procedure Set_ButtonColor(Value:TColor); Procedure Set_StickColor(Value:TColor); Procedure Set_BorderColor(Value:TColor); Procedure Set_ColorFirst(Value:TColor); Procedure Set_ColorSecond(Value:TColor); Procedure Set_ColorThird(Value:TColor); Procedure Set_ColorEmpty(Value:TColor); Procedure Set_VisiblePosition(Value:Boolean); Procedure Set_Text(Value:String); protected procedure Change; virtual; procedure Paint; override; Procedure Resize; Override; procedure MouseDown(Button: TMouseButton;Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X,Y: Integer); override; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; published Property ButtonColor : TColor Read fButtonColor Write Set_ButtonColor; Property StickColor : TColor Read fStickColor Write Set_StickColor; Property BorderColor : TColor Read fBorderColor Write Set_BorderColor; Property ColorFirst:TColor Read fColorFirst Write Set_ColorFirst; Property ColorSecond:TColor Read fColorSecond Write Set_ColorSecond; Property ColorThird:TColor Read fColorThird Write Set_ColorThird; Property ColorEmpty:TColor Read fColorEmpty Write Set_ColorEmpty; Property VisiblePosition : Boolean Read fVisiblePosition Write Set_VisiblePosition; Property Min : Integer Read fMin Write Set_Min Default 0; Property Max : Integer Read fMax Write Set_Max Default 100; Property Pos : Integer Read fPos Write Set_Pos Default 10; Property Text:String Read fText Write Set_Text; Property Color; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnChange :TNotifyEvent read fOnChange write fOnChange; end; procedure Register; implementation procedure Register; begin RegisterComponents('MUSIC_PRO', [TPotentio]); end; constructor TPotentio.Create(AOwner:TComponent); begin inherited Create(AOwner); Parent := TWinControl(AOwner); doublebuffered := True; fMin:=0; fMax:=100; fPos:=0; fButtonColor:=$002E2E2E; fBorderColor:=$004B4B4B; fStickColor:=ClWhite; Color:=clBtnFace; ColorFirst:=$009CE8F5; ColorSecond:=$001ACBEA; ColorThird:=$0013AECA; ColorEmpty:=$00F7F4F2; end; destructor TPotentio.Destroy; begin inherited; end; Procedure TPotentio.Set_StickColor(Value:TColor); Begin if fStickColor=Value then exit; fStickColor:=Value; Invalidate; End; Procedure TPotentio.Set_ButtonColor(Value:TColor); Begin if fButtonColor=Value then exit; fButtonColor:=Value; Invalidate; End; Procedure TPotentio.Set_BorderColor(Value:TColor); Begin if fBorderColor=Value then exit; fBorderColor:=Value; Invalidate; End; Procedure TPotentio.Set_ColorFirst(Value:TColor); begin if fColorFirst=Value then exit; fColorFirst:=Value; Invalidate; end; Procedure TPotentio.Set_ColorSecond(Value:TColor); begin if fColorSecond=Value then exit; fColorSecond:=Value; Invalidate; end; Procedure TPotentio.Set_ColorThird(Value:TColor); begin if fColorThird=Value then exit; fColorThird:=Value; Invalidate; end; Procedure TPotentio.Set_ColorEmpty(Value:TColor); begin if fColorEmpty=Value then exit; fColorEmpty:=Value; Invalidate; end; Procedure TPotentio.Resize; Begin Self.Height:=Self.Width; Invalidate; End; Procedure TPotentio.Set_Min(Value:Integer); Begin If (Value<fMax) and (Value<=fPos) Then fMin:=Value; fdelta:=(fMin-fPos)*(10*PI/6)/(fMax-fMin)+11*PI/6; Invalidate; End; Procedure TPotentio.Set_Max(Value:Integer); Begin If (Value>fMin) and (Value>=fPos) Then fMax:=Value; fdelta:=(fMin-fPos)*(10*PI/6)/(fMax-fMin)+11*PI/6; Invalidate; End; Procedure TPotentio.Set_Pos(Value:Integer); Begin fPos:=Value; If (Value<=fMin) Then fPos:=fMin; If (Value>=fMax) Then fPos:=FMax; fdelta:=(fMin-fPos)*(10*PI/6)/(fMax-fMin)+11*PI/6; Invalidate; End; Procedure TPotentio.Set_VisiblePosition(Value:Boolean); Begin fVisiblePosition:=Value; Invalidate; End; Procedure TPotentio.Set_Text(Value:String); Begin fText:=Value; Invalidate; End; Procedure TPotentio.Paint; var Str:String; Rect:TRect; R,Teta:double; UpperCorner,LowerCorner:Array [0..2] Of TPoint; IndexTeta,X1,Y1,X2,Y2,X3,Y3,X4,Y4,WidthText,HeightText:Integer; begin with Self.Canvas Do begin Pen.Width:=2; UpperCorner[0]:=Point(0,Height); UpperCorner[1]:=Point(0,0); UpperCorner[2]:=Point(Width,0); LowerCorner[0]:=Point(0,Self.Height); LowerCorner[1]:=Point(Width,Height); LowerCorner[2]:=Point(Width,0); Pen.Color:=ClWhite; Polyline(UpperCorner); Pen.Color:=$00657271; Polyline(LowerCorner); Pen.Width:=0; X1:=Width Div 10; Y1:=Height Div 10; X2:=9*Width Div 10; Y2:=9*Height Div 10; R:=4*Width Div 5; For IndexTeta:=1 To 10 Do Begin Teta:=(PI / 6)*IndexTeta; X3:=Round(R*Sin(Teta)+Width/2); Y3:=Round(R*Cos(Teta)+Height/2); X4:=Round(R*Sin(Teta+PI/6)+Width/2); Y4:=Round(R*Cos(Teta+PI/6)+Height/2); Pen.Color:=ClBlack; With Brush Do Begin If Teta<fDelta Then Color:=fColorEmpty Else Begin If (Teta>=8*PI/6) Then Color:=fColorFirst; If (Teta<8*PI/6) And (Teta>=3*PI/6) Then Color:=fColorSecond; If (Teta<=3*PI/6) Then Color:=fColorThird; End; End; Pie(X1,Y1,X2,Y2,X3,Y3,X4,Y4); End; Brush.Color:=Color; With Rect Do Begin Left:=Width Div 6; Right:=5*Width Div 6; Top:=Height Div 6; Bottom:=5*Height Div 6; End; Ellipse(Rect); Brush.Color:=fBorderColor; With Rect Do Begin Left:=Width Div 5; Right:=4*Width Div 5; Top:=Height Div 5; Bottom:=4*Height Div 5; End; Ellipse(Rect); Brush.Color:=fButtonColor; With Rect Do Begin Left:=13*Width Div 50; Right:=37*Width Div 50; Top:=13*Height Div 50; Bottom:=37*Height Div 50; End; Ellipse(Rect); Pen.Color:=fStickColor; R:=10*Width Div 50; MoveTo(Width Div 2, Height Div 2); LineTo(Round(R*Sin(fDelta)+Width / 2),Round(R*Cos(fDelta)+Height / 2)); If VisiblePosition=True Then Begin Font.Name:='Small Fonts'; Font.Color:=ClWhite; Font.Size:=6; Str:=fText+' '+IntToStr(fPos); Brush.Style:=BsClear; WidthText:=TextWidth(Str); HeightText:=TextHeight(Str); TextOut((Width- WidthText) Div 2 ,10*Height Div 11 - HeightText Div 2,Str); End; end; end; procedure TPotentio.MouseDown(Button: TMouseButton;Shift: TShiftState; X, Y: Integer); Begin Inherited; MouseMove(Shift,X,Y); End; procedure TPotentio.MouseMove(Shift: TShiftState; X,Y: Integer); Var I : Extended; Begin Inherited; If Shift=[SSLeft] Then Begin If Y<>Self.Height Div 2 Then Begin I:=(X-Self.Width Div 2)/(Y-Self.Height Div 2); fDelta:=ArcTan(I); If (Y<Height Div 2) Then fDelta:=FDelta+PI; If (X<Width Div 2) And (Y>Height Div 2) Then fDelta:=FDelta+2*PI; If Abs(fDelta)>=(11*PI/6) then fDelta:=(11*PI/6); If Abs(fDelta)<=(PI/6) then fDelta:=(PI/6); fPos:=Round(fMin-(fdelta-11*PI/6)*(fMax-fMin)/(10*PI/6)); Invalidate; End; End; End; procedure TPotentio.Change; begin if Assigned(fOnChange) then fOnChange(Self); end; end.
unit DBModuleCommands; interface uses RDTP_DatabaseConnection, stringx, systemx, typex, commandprocessor, sysutils, dir, classes, storageenginetypes, debug, betterobject, variants; type TDBCommand = class(TCommand) private FRecordResults: boolean; FDBcontext: string; protected slWriteLog, slProblemLog: TStringlist; dbm: TBestDatabaseDM; procedure DoExecute; override; procedure DBExecute;virtual;abstract; public procedure Detach; override; property DBcontext: string read FDBcontext write FDBcontext; property RecordResults: boolean read FRecordResults write FRecordResults; procedure RecordQuery(sQuery: string);overload; procedure RecordQuery(sl: TStringlist);overload;//ONE QUERY PER LINE NO CRLFS IN QUERY! procedure InitExpense; override; procedure WriteAndLog(sQuery: string); procedure WriteQuery(sQuery: string); function ReadQuery(sQuery: string): TSERowSet; function ReadQueryH(sQuery: string): IHolder<TSERowSet>; function FunctionQuery(sQuery: string; default: ni): ni;overload; function FunctionQuery(sQuery: string; default: string): string;overload; function GetCreateTable(sTable: string): string;overload; procedure Problem(sProblem: string); end; function GetReposFolder: string; implementation { TDBCommand } procedure TDBCommand.Detach; begin if detached then exit; slWriteLog.free; slWriteLog := nil; slProblemLog.free; slProblemLog := nil; inherited; end; procedure TDBCommand.DoExecute; begin inherited; slWriteLog := TStringlist.create; slProblemLog := TStringlist.create; dbm := TBestDatabaseDM.create; try // dbm.Context := 'simple;db=mmm_crimp_hd;host=crimp-hd.mysql.database.azure.com;user=crimpdbadmin@crimp-hd;pass=B@W@v}B5y^ue'; dbm.Context := DBContext; // dbm.ConfigureFromContext; dbm.ConnectWrite; DBExecute; var finalfile := GetReposFolder+'_import.sql'; var problemfile := GEtReposFolder+'_problems.txt'; slProblemLog.savetoFile(problemfile); slWriteLog.savetoFile(finalfile); finally dbm.Free; end; end; function TDBCommand.FunctionQuery(sQuery, default: string): string; begin var rows := ReadQueryH(sQuery); if rows.o.RowCount < 1 then exit(default) else begin if varisnull(rows.o.values[0,0]) then exit('') else exit(rows.o.values[0,0]); end; end; function TDBCommand.GetCreateTable(sTable: string): string; begin var rows := ReadQueryH('show create table '+sTable); if rows.o.RowCount < 1 then exit('') else begin if rows.o.FieldCount < 2 then exit(''); if varisnull(rows.o.values[1,0]) then exit('') else exit(rows.o.values[1,0]); end; end; function TDBCommand.FunctionQuery(sQuery: string; default: ni): ni; begin var rows := ReadQueryH(sQuery); if rows.o.RowCount < 1 then exit(default) else exit(rows.o.values[0,0]); end; procedure TDBCommand.InitExpense; begin inherited; memoryexpense := 1.0; end; procedure TDBCommand.Problem(sProblem: string); begin slProblemLog.add(sProblem); end; function TDBCommand.ReadQuery(sQuery: string): TSERowSet; begin result := nil; dbm.ExecuteRead(sQuery, result); end; function TDBCommand.ReadQueryH(sQuery: string): IHolder<TSERowSet>; begin result := THolder<TSERowSet>.create; result.o := ReadQuery(sQuery); end; procedure TDBCommand.RecordQuery(sl: TStringlist); var t: ni; begin for t:= 0 to sl.count-1 do begin RecordQuery(sl[t]); end; end; procedure TDBCommand.RecordQuery(sQuery: string); begin if sQuery = '' then exit; if sQuery[high(sQuery)] <> ';' then sQuery := sQuery + ';'; var sdir := GetReposFolder; forcedirectories(sdir); // var sFile := GetNextSequentialFileName(sDir,'.sql'); // stringx.SaveStringAsFile(sFile, sQuery); slWriteLog.add(sQuery); end; procedure TDBCommand.WriteAndLog(sQuery: string); begin // Debug.Log(sQuery); WriteQuery(sQuery); RecordQuery(sQuery); end; procedure TDBCommand.WriteQuery(sQuery: string); begin dbm.ExecuteWrite(sQuery); end; function GetReposFolder: string; begin result := dllpath+'repos\crimphd\'; end; end.
{==============================================================================| | Project : Delphree - Synapse | 005.000.000 | |==============================================================================| | Content: Serial port support | |==============================================================================| | Copyright (c)2001-2002, Lukas Gebauer | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions are met: | | | | Redistributions of source code must retain the above copyright notice, this | | list of conditions and the following disclaimer. | | | | Redistributions in binary form must reproduce the above copyright notice, | | this list of conditions and the following disclaimer in the documentation | | and/or other materials provided with the distribution. | | | | Neither the name of the Ararat s.r.o. nor the names of its contributors may | | be used to endorse or promote products derived from this software without | | specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR | | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | | DAMAGE. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c)2001. | | All Rights Reserved. | |==============================================================================| | Contributor(s): | | (c)2002, Hans-Georg Joepgen (cpom Comport Ownership Manager and bugfixes | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} {$Q-} {$WEAKPACKAGEUNIT ON} unit SynaSer; interface uses {$IFDEF LINUX} Libc, Types, KernelIoctl, {$ELSE} Windows, Classes, {$ENDIF} SysUtils; const LockfileDirectory = '/var/lock'; {HGJ} PortIsClosed = -1; {HGJ} ErrAlreadyOwned = 9991; {HGJ} ErrAlreadyInUse = 9992; {HGJ} ErrWrongParameter = 9993; {HGJ} ErrPortNotOpen = 9994; {HGJ} ErrNoDeviceAnswer = 9995; {HGJ} ErrMaxBuffer = 9996; ErrTimeout = 9997; ErrNotRead = 9998; ErrFrame = 9999; ErrOverrun = 10000; ErrRxOver = 10001; ErrRxParity = 10002; ErrTxFull = 10003; dcb_Binary = $00000001; dcb_ParityCheck = $00000002; dcb_OutxCtsFlow = $00000004; dcb_OutxDsrFlow = $00000008; dcb_DtrControlMask = $00000030; dcb_DtrControlDisable = $00000000; dcb_DtrControlEnable = $00000010; dcb_DtrControlHandshake = $00000020; dcb_DsrSensivity = $00000040; dcb_TXContinueOnXoff = $00000080; dcb_OutX = $00000100; dcb_InX = $00000200; dcb_ErrorChar = $00000400; dcb_NullStrip = $00000800; dcb_RtsControlMask = $00003000; dcb_RtsControlDisable = $00000000; dcb_RtsControlEnable = $00001000; dcb_RtsControlHandshake = $00002000; dcb_RtsControlToggle = $00003000; dcb_AbortOnError = $00004000; dcb_Reserveds = $FFFF8000; {$IFDEF LINUX} const INVALID_HANDLE_VALUE = THandle(-1); CS7fix = $0000020; type TDCB = packed record DCBlength: DWORD; BaudRate: DWORD; Flags: Longint; wReserved: Word; XonLim: Word; XoffLim: Word; ByteSize: Byte; Parity: Byte; StopBits: Byte; XonChar: CHAR; XoffChar: CHAR; ErrorChar: CHAR; EofChar: CHAR; EvtChar: CHAR; wReserved1: Word; end; PDCB = ^TDCB; const MaxRates = 30; Rates: array[0..MaxRates, 0..1] of cardinal = ( (0, B0), (50, B50), (75, B75), (110, B110), (134, B134), (150, B150), (200, B200), (300, B300), (600, B600), (1200, B1200), (1800, B1800), (2400, B2400), (4800, B4800), (9600, B9600), (19200, B19200), (38400, B38400), (57600, B57600), (115200, B115200), (230400, B230400), (460800, B460800), (500000, B500000), (576000, B576000), (921600, B921600), (1000000, B1000000), (1152000, B1152000), (1500000, B1500000), (2000000, B2000000), (2500000, B2500000), (3000000, B3000000), (3500000, B3500000), (4000000, B4000000) ); {$ENDIF} type THookSerialReason = ( HR_SerialClose, HR_Connect, HR_CanRead, HR_CanWrite, HR_ReadCount, HR_WriteCount ); THookSerialStatus = procedure(Sender: TObject; Reason: THookSerialReason; const Value: string) of object; ESynaSerError = class(Exception) public ErrorCode: integer; ErrorMessage: string; end; TBlockSerial = class(TObject) protected FOnStatus: THookSerialStatus; Fhandle: THandle; FLastError: integer; FBuffer: string; FRaiseExcept: boolean; FRecvBuffer: integer; FSendBuffer: integer; FModemWord: integer; FRTSToggle: Boolean; FDeadlockTimeout: integer; FInstanceActive: boolean; {HGJ} FTestDSR: Boolean; FTestCTS: Boolean; FMaxLineLength: Integer; FLinuxLock: Boolean; {$IFNDEF LINUX} FEventHandle: THandle; function CanEvent(Event: dword; Timeout: integer): boolean; procedure DecodeCommError(Error: DWord); {$ENDIF} procedure SetSizeRecvBuffer(size: integer); function GetDSR: Boolean; procedure SetDTRF(Value: Boolean); function GetCTS: Boolean; procedure SetRTSF(Value: Boolean); function GetCarrier: Boolean; function GetRing: Boolean; procedure DoStatus(Reason: THookSerialReason; const Value: string); procedure GetComNr(Value: string); function PreTestFailing: boolean; {HGJ} function TestCtrlLine: Boolean; {$IFDEF LINUX} procedure DcbToTermios(const dcb: TDCB; var term: termios); procedure TermiosToDcb(const term: termios; var dcb: TDCB); function ReadLockfile: integer; function LockfileName: String; procedure CreateLockfile(PidNr: integer); procedure ErrorMethod(ErrNumber: integer); {HGJ} {$ENDIF} public DCB: Tdcb; FComNr: integer; {$IFDEF LINUX} TermiosStruc: termios; {$ENDIF} constructor Create; destructor Destroy; override; function GetVersion: string; procedure CreateSocket; procedure CloseSocket; //stopbits is: 0- 1 stop bit, 1- 1.5 stop bits, 2- 2 stop bits procedure Connect(comport: string; baud, bits: integer; parity: char; stop: integer; softflow, hardflow: boolean); procedure SetCommState; procedure GetCommState; function SendBuffer(buffer: pointer; length: integer): integer; procedure SendByte(data: byte); procedure SendString(data: string); function RecvBuffer(buffer: pointer; length: integer): integer; function RecvBufferEx(buffer: pointer; length: integer; timeout: integer): integer; function RecvPacket(Timeout: Integer): string; function RecvByte(timeout: integer): byte; function RecvTerminated(Timeout: Integer; const Terminator: string): string; function Recvstring(timeout: integer): string; function WaitingData: integer; function WaitingDataEx: integer; function SendingData: integer; procedure EnableRTSToggle(value: boolean); procedure EnableSoftRTSToggle(value: boolean); procedure Flush; procedure Purge; function CanRead(Timeout: integer): boolean; function CanWrite(Timeout: integer): boolean; function CanReadEx(Timeout: integer): boolean; function ModemStatus: integer; procedure SetBreak(Duration: integer); function ATCommand(value: string): string; function SerialCheck(SerialResult: integer): integer; procedure ExceptCheck; procedure ErrorMethod(ErrNumber: integer); {HGJ} {$IFDEF LINUX} function cpomComportAccessible: boolean; {HGJ} procedure cpomReleaseComport; {HGJ} {$ENDIF} published class function GetErrorDesc(ErrorCode: integer): string; property Handle: THandle read Fhandle write FHandle; property LastError: integer read FLastError; property LineBuffer: string read FBuffer write FBuffer; property RaiseExcept: boolean read FRaiseExcept write FRaiseExcept; property SizeRecvBuffer: integer read FRecvBuffer write SetSizeRecvBuffer; property OnStatus: THookSerialStatus read FOnStatus write FOnStatus; property RTS: Boolean write SetRTSF; property CTS: boolean read GetCTS; property DTR: Boolean write SetDTRF; property DSR: boolean read GetDSR; property Carrier: boolean read GetCarrier; property Ring: boolean read GetRing; property InstanceActive: boolean read FInstanceActive; {HGJ} property TestDSR: boolean read FTestDSR write FTestDSR; property TestCTS: boolean read FTestCTS write FTestCTS; property MaxLineLength: Integer read FMaxLineLength Write FMaxLineLength; property DeadlockTimeout: Integer read FDeadlockTimeout Write FDeadlockTimeout; property LinuxLock: Boolean read FLinuxLock write FLinuxLock; end; implementation constructor TBlockSerial.Create; begin inherited create; FRaiseExcept := false; FHandle := INVALID_HANDLE_VALUE; FComNr:= PortIsClosed; {HGJ} FInstanceActive:= false; {HGJ} Fbuffer := ''; FRTSToggle := False; FMaxLineLength := 0; FTestDSR := False; FTestCTS := False; FDeadlockTimeout := 30000; FLinuxLock := True; {$IFNDEF LINUX} FEventHandle := INVALID_HANDLE_VALUE; {$ENDIF} end; destructor TBlockSerial.Destroy; begin CloseSocket; {$IFNDEF LINUX} if FEventHandle <> INVALID_HANDLE_VALUE then CloseHandle(FEventHandle); {$ENDIF} inherited destroy; end; function TBlockSerial.GetVersion: string; begin Result := 'SynaSer 5.0.0'; end; procedure TBlockSerial.CreateSocket; begin // dummy for compatibility with TBlockSocket classes end; procedure TBlockSerial.CloseSocket; begin if Fhandle <> INVALID_HANDLE_VALUE then begin Purge; RTS := False; DTR := False; FileClose(integer(FHandle)); end; if InstanceActive then begin {$IFDEF LINUX} if FLinuxLock then cpomReleaseComport; {$ENDIF} FInstanceActive:= false end; Fhandle := INVALID_HANDLE_VALUE; FComNr:= PortIsClosed; DoStatus(HR_SerialClose, ''); end; procedure TBlockSerial.GetComNr(Value: string); begin FComNr := PortIsClosed; if pos('COM', uppercase(Value)) = 1 then begin FComNr := StrToIntdef(copy(Value, 4, Length(Value) - 3), PortIsClosed + 1) - 1; end; if pos('/DEV/TTYS', uppercase(Value)) = 1 then begin FComNr := StrToIntdef(copy(Value, 10, Length(Value) - 9), PortIsClosed - 1) + 1; end; end; procedure TBlockSerial.Connect(comport: string; baud, bits: integer; parity: char; stop: integer; softflow, hardflow: boolean); {$IFNDEF LINUX} var CommTimeouts: TCommTimeouts; {$ENDIF} begin // Is this TBlockSerial Instance already busy? if InstanceActive then {HGJ} begin {HGJ} ErrorMethod(ErrAlreadyInUse); {HGJ} Exit; {HGJ} end; {HGJ} FBuffer := ''; GetComNr(comport); if FComNr = PortIsClosed then begin ErrorMethod(ErrWrongParameter); Exit; end; SetLastError (0); {$IFDEF LINUX} comport := '/dev/ttyS' + IntToStr(FComNr); // Comport already owned by another process? {HGJ} if FLinuxLock then if not cpomComportAccessible then begin ErrorMethod(ErrAlreadyOwned); Exit; end; FHandle := THandle(Libc.open(pchar(comport), O_RDWR or O_SYNC)); SerialCheck(integer(FHandle)); if FLastError <> 0 then begin if FLinuxLock then cpomReleaseComport; end; ExceptCheck; if FLastError <> 0 then Exit; {$ELSE} comport := '\\.\COM' + IntToStr(FComNr + 1); FHandle := THandle(CreateFile(PChar(comport), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, 0)); SerialCheck(integer(FHandle)); ExceptCheck; if FLastError <> 0 then Exit; SetCommMask(FHandle, 0); FEventhandle := CreateEvent(nil, True, False, nil); CommTimeOuts.ReadIntervalTimeout := MAXWORD; CommTimeOuts.ReadTotalTimeoutMultiplier := 0; CommTimeOuts.ReadTotalTimeoutConstant := 0; CommTimeOuts.WriteTotalTimeoutMultiplier := 0; CommTimeOuts.WriteTotalTimeoutConstant := 0; SetCommTimeOuts(FHandle, CommTimeOuts); {$ENDIF} GetCommState; dcb.BaudRate := baud; dcb.ByteSize := bits; case parity of 'N', 'n': dcb.parity := 0; 'O', 'o': dcb.parity := 1; 'E', 'e': dcb.parity := 2; 'M', 'm': dcb.parity := 3; 'S', 's': dcb.parity := 4; end; if dcb.Parity > 0 then dcb.Flags := dcb.Flags or dcb_ParityCheck else dcb.Flags := dcb.Flags and (not dcb_ParityCheck); dcb.StopBits := stop; dcb.Flags := dcb.Flags and (not dcb_RtsControlMask); if hardflow then dcb.Flags := dcb.Flags or dcb_OutxCtsFlow or dcb_RtsControlHandshake else begin dcb.Flags := dcb.Flags and (not dcb_OutxCtsFlow); dcb.Flags := dcb.Flags or dcb_RtsControlEnable; end; if softflow then dcb.Flags := dcb.Flags or dcb_OutX or dcb_InX else dcb.Flags := dcb.Flags and (not (dcb_OutX or dcb_InX)); dcb.Flags := dcb.Flags and (not dcb_DtrControlMask); dcb.Flags := dcb.Flags or dcb_DtrControlEnable; SetCommState; if FLastError <> 0 then {HGJ} begin {HGJ} FileClose(FHandle); {HGJ} {$IFDEF LINUX} if FLinuxLock then cpomReleaseComport; {$ENDIF} ExceptCheck; Exit; {HGJ} end; {HGJ} SizeRecvBuffer := 4096; FInstanceActive:= True; {HGJ} if not TestCtrlLine then {HGJ} begin {HGJ} FLastError := ErrNoDeviceAnswer; {HGJ} FileClose(integer(FHandle)); {HGJ} {$IFDEF LINUX} if FLinuxLock then cpomReleaseComport; {HGJ} {$ENDIF} {HGJ} FInstanceActive := false; {HGJ} Fhandle := INVALID_HANDLE_VALUE; {HGJ} FComNr:= PortIsClosed; {HGJ} end; {HGJ} if FLastError = 0 then begin Purge; RTS := True; DTR := True; end; ExceptCheck; DoStatus(HR_Connect, comport); end; function TBlockSerial.SendBuffer(buffer: pointer; length: integer): integer; {$IFNDEF LINUX} var Overlapped: TOverlapped; X, Err: DWord; {$ENDIF} begin Result := 0; if PreTestFailing then {HGJ} Exit; {HGJ} if FRTSToggle then begin Flush; RTS := True; end; {$IFDEF LINUX} result := FileWrite(integer(Fhandle), Buffer^, Length); serialcheck(result); {$ELSE} FillChar(Overlapped, Sizeof(Overlapped), 0); ResetEvent(FEventHandle); Overlapped.hEvent := FEventHandle; x := DWord(WriteFile(FHandle, Buffer^, Length, DWord(Result), @Overlapped)); if (x = 0) or (x = DWord(INVALID_HANDLE_VALUE)) then FLastError := GetLastError; if FlastError = ERROR_IO_PENDING then begin x := WaitForSingleObject(FEventHandle, FDeadlockTimeout); SerialCheck(integer(GetOverlappedResult(FHandle, Overlapped, Dword(Result), False))); if FLastError = ERROR_IO_INCOMPLETE then CancelIO(FHandle); if x = WAIT_TIMEOUT then FLastError := ErrTimeout; end; ResetEvent(FEventHandle); ClearCommError(FHandle, err, nil); if err <> 0 then DecodeCommError(err); {$ENDIF} if FRTSToggle then begin Flush; RTS := False; end; ExceptCheck; DoStatus(HR_WriteCount, IntToStr(Result)); end; procedure TBlockSerial.SendByte(data: byte); begin SendBuffer(@Data, 1); end; procedure TBlockSerial.SendString(data: string); begin SendBuffer(Pointer(Data), Length(Data)); end; function TBlockSerial.RecvBuffer(buffer: pointer; length: integer): integer; {$IFDEF LINUX} begin Result := 0; if PreTestFailing then {HGJ} Exit; {HGJ} result := FileRead(integer(FHandle), Buffer^, length); serialcheck(result); {$ELSE} var Overlapped: TOverlapped; x, Err: DWord; begin Result := 0; if PreTestFailing then {HGJ} Exit; {HGJ} FillChar(Overlapped, Sizeof(Overlapped), 0); Overlapped.hEvent := FEventHandle; x := DWord(ReadFile(FHandle, Buffer^, length, Dword(Result), @Overlapped)); if (x = 0) or (x = Dword(INVALID_HANDLE_VALUE)) then FLastError := GetLastError; if FlastError = ERROR_IO_PENDING then begin x := WaitForSingleObject(FEventHandle, FDeadlockTimeout); SerialCheck(integer(GetOverlappedResult(Handle, Overlapped, DWord(Result), False))); if FLastError = ERROR_IO_INCOMPLETE then CancelIO(FHandle); if x = WAIT_TIMEOUT then FLastError := ErrTimeout; end; ResetEvent(FEventHandle); ClearCommError(FHandle, err, nil); if err <> 0 then DecodeCommError(err); {$ENDIF} ExceptCheck; DoStatus(HR_ReadCount, IntToStr(Result)); end; function TBlockSerial.RecvBufferEx(buffer: pointer; length: integer; timeout: integer): integer; var s, ss, st: string; x, l, lss: integer; fb, fs: integer; max: integer; begin Result := 0; if PreTestFailing then {HGJ} Exit; {HGJ} FLastError := 0; x := system.length(FBuffer); if length <= x then begin fb := length; fs := 0; end else begin fb := x; fs := length - x; end; ss := ''; if fb > 0 then begin s := copy(FBuffer, 1, fb); delete(Fbuffer, 1, fb); end; if fs > 0 then begin Max := FRecvBuffer; if Max = 0 then Max := 1024; ss := ''; while system.length(ss) < fs do begin if canread(timeout) then begin l := WaitingData; if l > max then l := max; if (system.length(ss) + l) > fs then l := fs - system.length(ss); setlength(st, l); x := RecvBuffer(Pointer(st), l); if FlastError <> 0 then break; lss := system.length(ss); setlength(ss, lss + x); Move(pointer(st)^, Pointer(@ss[lss + 1])^, x); {It is 3x faster then ss:=ss+copy(st,1,x);} sleep(0); end else FLastError := ErrTimeout; if Flasterror <> 0 then break; end; fs := system.length(ss); end; result := fb + fs; s := s + ss; move(pointer(s)^, buffer^, result); ExceptCheck; end; function TBlockSerial.RecvPacket(Timeout: Integer): string; var x: integer; s: string; begin Result := ''; if PreTestFailing then {HGJ} Exit; {HGJ} FLastError := 0; x := -1; if FBuffer <> '' then begin Result := FBuffer; FBuffer := ''; end else repeat if CanRead(Timeout) then begin x := WaitingData; if x > 0 then begin SetLength(s, x); x := RecvBuffer(Pointer(s), x); Result := Copy(s, 1, x); end; end else FLastError := ErrTimeout; until not((FlastError = 0) and (x = 0)); ExceptCheck; if x = 0 then FLastError := integer(-1); end; function TBlockSerial.RecvByte(timeout: integer): byte; var s: String; x: integer; begin Result := 0; if PreTestFailing then {HGJ} Exit; {HGJ} if CanRead(timeout) then begin x := WaitingData; if x > 0 then begin SetLength(s, 1); x := RecvBuffer(Pointer(s), 1); SetLength(s, x); if s <> '' then Result := Ord(s[1]) else FLastError := ErrNotRead; end else FLastError := ErrNotRead; end else FLastError := ErrTimeout; ExceptCheck; end; function TBlockSerial.RecvTerminated(Timeout: Integer; const Terminator: string): string; var x: Integer; s: string; l: Integer; begin Result := ''; if PreTestFailing then {HGJ} Exit; {HGJ} s := ''; l := Length(Terminator); if l = 0 then Exit; FLastError := 0; repeat x := 0; if x > 0 then {nothing; work around for warning bug}; {HGJ} if FBuffer = '' then begin FBuffer := RecvPacket(Timeout); if FLastError <> 0 then Break; end; s := s + FBuffer; FBuffer := ''; x := Pos(Terminator, s); if x > 0 then begin FBuffer := Copy(s, x + l, Length(s) - x - l + 1); s := Copy(s, 1, x - 1); end; if (FMaxLineLength <> 0) and (Length(s) > FMaxLineLength) then begin FLastError := ErrMaxBuffer; Break; end; until x > 0; if FLastError = 0 then Result := s else Result := ''; ExceptCheck; end; function TBlockSerial.RecvString(Timeout: Integer): string; var s: string; begin Result := ''; s := RecvTerminated(Timeout, #13 + #10); if FLastError = 0 then Result := s; end; {$IFDEF LINUX} function TBlockSerial.WaitingData: integer; begin serialcheck(ioctl(integer(FHandle), FIONREAD, @result)); ExceptCheck; end; {$ELSE} function TBlockSerial.WaitingData: integer; var stat: TComStat; err: DWORD; x: integer; begin x := integer(ClearCommError(FHandle, err, @stat)); serialcheck(x); ExceptCheck; result := stat.cbInQue; end; {$ENDIF} function TBlockSerial.WaitingDataEx: integer; begin if FBuffer <> '' then Result := Length(FBuffer) else Result := Waitingdata; end; {$IFDEF LINUX} function TBlockSerial.SendingData: integer; begin FLastError := 0; Result := 0; end; {$ELSE} function TBlockSerial.SendingData: integer; var stat: TComStat; err: DWORD; x: integer; begin x := integer(ClearCommError(FHandle, err, @stat)); serialcheck(x); ExceptCheck; result := stat.cbOutQue; end; {$ENDIF} {$IFDEF LINUX} procedure TBlockSerial.DcbToTermios(const dcb: TDCB; var term: termios); var n: integer; x: cardinal; begin //others cfmakeraw(term); term.c_cflag := term.c_cflag or CREAD; term.c_cflag := term.c_cflag or CLOCAL; term.c_cflag := term.c_cflag or HUPCL; //hardware handshake if (dcb.flags and dcb_RtsControlHandshake) > 0 then term.c_cflag := term.c_cflag or CRTSCTS else term.c_cflag := term.c_cflag and (not CRTSCTS); //software handshake if (dcb.flags and dcb_OutX) > 0 then term.c_iflag := term.c_iflag or IXON or IXOFF or IXANY else term.c_iflag := term.c_iflag and (not (IXON or IXOFF or IXANY)); //size of byte term.c_cflag := term.c_cflag and (not CSIZE); case dcb.bytesize of 5: term.c_cflag := term.c_cflag or CS5; 6: term.c_cflag := term.c_cflag or CS6; 7: term.c_cflag := term.c_cflag or CS7fix; 8: term.c_cflag := term.c_cflag or CS8; end; //parity if (dcb.flags and dcb_ParityCheck) > 0 then term.c_cflag := term.c_cflag or PARENB else term.c_cflag := term.c_cflag and (not PARENB); case dcb.parity of 1: //'O' term.c_cflag := term.c_cflag and PARODD; 2: //'E' term.c_cflag := term.c_cflag and (not PARODD); end; //stop bits if dcb.stopbits > 0 then term.c_cflag := term.c_cflag or CSTOPB else term.c_cflag := term.c_cflag and (not CSTOPB); //set baudrate; x := 0; for n := 0 to Maxrates do if rates[n, 0] = dcb.BaudRate then begin x := rates[n, 1]; break; end; cfsetospeed(term, x); cfsetispeed(term, x); end; procedure TBlockSerial.TermiosToDcb(const term: termios; var dcb: TDCB); var n: integer; x: cardinal; begin //set baudrate; dcb.baudrate := 0; x := cfgetospeed(term); for n := 0 to Maxrates do if rates[n, 1] = x then begin dcb.baudrate := rates[n, 0]; break; end; //hardware handshake if (term.c_cflag and CRTSCTS) > 0 then dcb.flags := dcb.flags or dcb_RtsControlHandshake or dcb_OutxCtsFlow else dcb.flags := dcb.flags and (not (dcb_RtsControlHandshake or dcb_OutxCtsFlow)); //software handshake if (term.c_cflag and IXOFF) > 0 then dcb.flags := dcb.flags or dcb_OutX or dcb_InX else dcb.flags := dcb.flags and (not (dcb_OutX or dcb_InX)); //size of byte case term.c_cflag and CSIZE of CS5: dcb.bytesize := 5; CS6: dcb.bytesize := 6; CS7fix: dcb.bytesize := 7; CS8: dcb.bytesize := 8; end; //parity if (term.c_cflag and PARENB) > 0 then dcb.flags := dcb.flags or dcb_ParityCheck else dcb.flags := dcb.flags and (not dcb_ParityCheck); dcb.parity := 0; if (term.c_cflag and PARODD) > 0 then dcb.parity := 1 else dcb.parity := 2; //stop bits if (term.c_cflag and CSTOPB) > 0 then dcb.stopbits := 2 else dcb.stopbits := 0; end; {$ENDIF} {$IFDEF LINUX} procedure TBlockSerial.SetCommState; begin DcbToTermios(dcb, termiosstruc); SerialCheck(tcsetattr(integer(FHandle), TCSANOW, termiosstruc)); ExceptCheck; end; {$ELSE} procedure TBlockSerial.SetCommState; begin SerialCheck(integer(windows.SetCommState(Fhandle, dcb))); ExceptCheck; end; {$ENDIF} {$IFDEF LINUX} procedure TBlockSerial.GetCommState; begin SerialCheck(tcgetattr(integer(FHandle), termiosstruc)); ExceptCheck; TermiostoDCB(termiosstruc, dcb); end; {$ELSE} procedure TBlockSerial.GetCommState; begin SerialCheck(integer(windows.GetCommState(Fhandle, dcb))); ExceptCheck; end; {$ENDIF} procedure TBlockSerial.SetSizeRecvBuffer(size: integer); begin {$IFNDEF LINUX} SetupComm(Fhandle, size, 0); GetCommState; dcb.XonLim := size div 4; dcb.XoffLim := size div 4; SetCommState; {$ENDIF} FRecvBuffer := size; end; function TBlockSerial.GetDSR: Boolean; begin ModemStatus; {$IFDEF LINUX} Result := (FModemWord and TIOCM_DSR) > 0; {$ELSE} Result := (FModemWord and MS_DSR_ON) > 0; {$ENDIF} end; procedure TBlockSerial.SetDTRF(Value: Boolean); begin {$IFDEF LINUX} ModemStatus; if Value then FModemWord := FModemWord or TIOCM_DTR else FModemWord := FModemWord and not TIOCM_DTR; ioctl(integer(FHandle), TIOCMSET, @FModemWord); {$ELSE} if Value then EscapeCommFunction(FHandle, SETDTR) else EscapeCommFunction(FHandle, CLRDTR); {$ENDIF} end; function TBlockSerial.GetCTS: Boolean; begin ModemStatus; {$IFDEF LINUX} Result := (FModemWord and TIOCM_CTS) > 0; {$ELSE} Result := (FModemWord and MS_CTS_ON) > 0; {$ENDIF} end; procedure TBlockSerial.SetRTSF(Value: Boolean); begin {$IFDEF LINUX} ModemStatus; if Value then FModemWord := FModemWord or TIOCM_RTS else FModemWord := FModemWord and not TIOCM_RTS; ioctl(integer(FHandle), TIOCMSET, @FModemWord); {$ELSE} if Value then EscapeCommFunction(FHandle, SETRTS) else EscapeCommFunction(FHandle, CLRRTS); {$ENDIF} end; function TBlockSerial.GetCarrier: Boolean; begin ModemStatus; {$IFDEF LINUX} Result := (FModemWord and TIOCM_CAR) > 0; {$ELSE} Result := (FModemWord and MS_RLSD_ON) > 0; {$ENDIF} end; function TBlockSerial.GetRing: Boolean; begin ModemStatus; {$IFDEF LINUX} Result := (FModemWord and TIOCM_RNG) > 0; {$ELSE} Result := (FModemWord and MS_RING_ON) > 0; {$ENDIF} end; {$IFNDEF LINUX} function TBlockSerial.CanEvent(Event: dword; Timeout: integer): boolean; var ex: DWord; y: Integer; Overlapped: TOverlapped; begin FillChar(Overlapped, Sizeof(Overlapped), 0); ResetEvent(FEventHandle); Overlapped.hEvent := FEventHandle; SetCommMask(FHandle, Event); y := integer(WaitCommEvent(FHandle, ex, @Overlapped)); if (y = 0) or (y = integer(INVALID_HANDLE_VALUE)) then FLastError := GetLastError; if FLastError = ERROR_IO_PENDING then begin WaitForSingleObject(FEventHandle, Timeout); GetOverlappedResult(FHandle, Overlapped, DWord(y), False); if GetLastError = ERROR_IO_INCOMPLETE then CancelIO(FHandle); ResetEvent(FEventHandle); FLastError := 0; end; Result := (ex and Event) = Event; SetCommMask(FHandle, 0); end; {$ENDIF} {$IFDEF LINUX} function TBlockSerial.CanRead(Timeout: integer): boolean; var FDSet: TFDSet; TimeVal: PTimeVal; TimeV: TTimeVal; x: Integer; begin TimeV.tv_usec := (Timeout mod 1000) * 1000; TimeV.tv_sec := Timeout div 1000; TimeVal := @TimeV; if Timeout = -1 then TimeVal := nil; FD_ZERO(FDSet); FD_SET(integer(FHandle), FDSet); x := Select(integer(FHandle) + 1, @FDSet, nil, nil, TimeVal); SerialCheck(x); if FLastError <> 0 then x := 0; Result := x > 0; ExceptCheck; if Result then DoStatus(HR_CanRead, ''); end; {$ELSE} function TBlockSerial.CanRead(Timeout: integer): boolean; begin Result := WaitingData > 0; if not Result then Result := CanEvent(EV_RXCHAR, Timeout); if Result then DoStatus(HR_CanRead, ''); end; {$ENDIF} {$IFDEF LINUX} function TBlockSerial.CanWrite(Timeout: integer): boolean; var FDSet: TFDSet; TimeVal: PTimeVal; TimeV: TTimeVal; x: Integer; begin TimeV.tv_usec := (Timeout mod 1000) * 1000; TimeV.tv_sec := Timeout div 1000; TimeVal := @TimeV; if Timeout = -1 then TimeVal := nil; FD_ZERO(FDSet); FD_SET(integer(FHandle), FDSet); x := Select(integer(FHandle) + 1, nil, @FDSet, nil, TimeVal); SerialCheck(x); if FLastError <> 0 then x := 0; Result := x > 0; ExceptCheck; if Result then DoStatus(HR_CanWrite, ''); end; {$ELSE} function TBlockSerial.CanWrite(Timeout: integer): boolean; begin Result := SendingData = 0; if not Result then Result := CanEvent(EV_TXEMPTY, Timeout); if Result then DoStatus(HR_CanWrite, ''); end; {$ENDIF} function TBlockSerial.CanReadEx(Timeout: integer): boolean; begin if Fbuffer<>'' then Result := True else Result := CanRead(Timeout); end; procedure TBlockSerial.EnableRTSToggle(Value: boolean); begin {$IFDEF LINUX} EnableSoftRTSToggle(Value); {$ELSE} GetCommState; if value then dcb.Flags := dcb.Flags or dcb_RtsControlToggle else dcb.flags := dcb.flags and (not dcb_RtsControlToggle); SetCommState; {$ENDIF} end; procedure TBlockSerial.EnableSoftRTSToggle(Value: boolean); begin FRTSToggle := Value; end; procedure TBlockSerial.Flush; begin {$IFDEF LINUX} SerialCheck(tcdrain(integer(FHandle))); {$ELSE} SerialCheck(integer(Flushfilebuffers(FHandle))); {$ENDIF} ExceptCheck; end; {$IFDEF LINUX} procedure TBlockSerial.Purge; begin SerialCheck(ioctl(integer(FHandle), TCFLSH, TCIOFLUSH)); FBuffer := ''; ExceptCheck; end; {$ELSE} procedure TBlockSerial.Purge; var x: integer; begin x := PURGE_TXABORT or PURGE_TXCLEAR or PURGE_RXABORT or PURGE_RXCLEAR; SerialCheck(integer(PurgeComm(FHandle, x))); FBuffer := ''; ExceptCheck; end; {$ENDIF} function TBlockSerial.ModemStatus: integer; begin {$IFDEF LINUX} SerialCheck(ioctl(integer(FHandle), TIOCMGET, @Result)); {$ELSE} SerialCheck(integer(GetCommModemStatus(FHandle, dword(Result)))); {$ENDIF} ExceptCheck; FModemWord := Result; end; procedure TBlockSerial.SetBreak(Duration: integer); begin {$IFDEF LINUX} SerialCheck(tcsendbreak(integer(FHandle), Duration)); {$ELSE} SetCommBreak(FHandle); Sleep(Duration); SerialCheck(integer(ClearCommBreak(FHandle))); {$ENDIF} end; {$IFNDEF LINUX} procedure TBlockSerial.DecodeCommError(Error: DWord); begin if (Error and DWord(CE_FRAME)) > 1 then FLastError := ErrFrame; if (Error and DWord(CE_OVERRUN)) > 1 then FLastError := ErrOverrun; if (Error and DWord(CE_RXOVER)) > 1 then FLastError := ErrRxOver; if (Error and DWord(CE_RXPARITY)) > 1 then FLastError := ErrRxParity; if (Error and DWord(CE_TXFULL)) > 1 then FLastError := ErrTxFull; end; {$ENDIF} function TBlockSerial.PreTestFailing: Boolean; {HGJ} begin {HGJ} if not FInstanceActive then {HGJ} begin ErrorMethod(ErrPortNotOpen); {HGJ} result:= true; {HGJ} Exit; {HGJ} end; {HGJ} Result := not TestCtrlLine; if result then ErrorMethod(ErrNoDeviceAnswer) {HGJ} end; function TBlockSerial.TestCtrlLine: Boolean; begin result := ((not FTestDSR) or DSR) and ((not FTestCTS) or CTS); end; function TBlockSerial.ATCommand(value: string): string; var s: string; begin result := ''; SendString(value + #$0D); repeat s := RecvTerminated(1000, #$0D); if s <> '' then if s[1] = #$0a then s := Copy(s, 2, Length(s) - 1); if (s <> value) and (s <> value + #$0d) then result := result + s + #$0D + #$0A; if s = 'OK' then break; if s = 'ERROR' then break; until FLastError <> 0; end; function TBlockSerial.SerialCheck(SerialResult: integer): integer; begin if SerialResult = integer(INVALID_HANDLE_VALUE) then result := GetLastError else result := 0; FLastError := result; end; procedure TBlockSerial.ExceptCheck; var e: ESynaSerError; s: string; begin if FRaiseExcept and (FLastError <> 0) then begin s := GetErrorDesc(LastError); e := ESynaSerError.CreateFmt('Communication error %d: %s', [LastError, s]); e.ErrorCode := FLastError; e.ErrorMessage := s; raise e; end; end; procedure TBlockSerial.ErrorMethod(ErrNumber: integer); begin FLastError := ErrNumber; ExceptCheck; end; procedure TBlockSerial.DoStatus(Reason: THookSerialReason; const Value: string); begin if assigned(OnStatus) then OnStatus(Self, Reason, Value); end; {======================================================================} {$IFDEF LINUX} class function TBlockSerial.GetErrorDesc(ErrorCode: integer): string; begin case ErrorCode of ErrAlreadyOwned: Result:= 'Port owned by other process';{HGJ} ErrAlreadyInUse: Result:= 'Instance already in use'; {HGJ} ErrWrongParameter: Result:= 'Wrong paramter at call'; {HGJ} ErrPortNotOpen: Result:= 'Instance not yet connected'; {HGJ} ErrNoDeviceAnswer: Result:= 'No device answer detected'; {HGJ} ErrMaxBuffer: Result:= 'Maximal buffer length exceeded'; ErrTimeout: Result:= 'Timeout during operation'; ErrNotRead: Result:= 'Reading of data failed'; ErrFrame: Result:= 'Receive framing error'; ErrOverrun: Result:= 'Receive Overrun Error'; ErrRxOver: Result:= 'Receive Queue overflow'; ErrRxParity: Result:= 'Receive Parity Error'; ErrTxFull: Result:= 'Tranceive Queue is full'; else Result := 'SynaSer error: ' + IntToStr(ErrorCode); end; end; {$ELSE} class function TBlockSerial.GetErrorDesc(ErrorCode: integer): string; var x: integer; begin Result:= ''; case ErrorCode of ErrAlreadyOwned: Result:= 'Port owned by other process';{HGJ} ErrAlreadyInUse: Result:= 'Instance already in use'; {HGJ} ErrWrongParameter: Result:= 'Wrong paramter at call'; {HGJ} ErrPortNotOpen: Result:= 'Instance not yet connected'; {HGJ} ErrNoDeviceAnswer: Result:= 'No device answer detected'; {HGJ} ErrMaxBuffer: Result:= 'Maximal buffer length exceeded'; ErrTimeout: Result:= 'Timeout during operation'; ErrNotRead: Result:= 'Reading of data failed'; ErrFrame: Result:= 'Receive framing error'; ErrOverrun: Result:= 'Receive Overrun Error'; ErrRxOver: Result:= 'Receive Queue overflow'; ErrRxParity: Result:= 'Receive Parity Error'; ErrTxFull: Result:= 'Tranceive Queue is full'; end; if Result = '' then begin setlength(result, 1023); x := Formatmessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode, 0, pchar(result), 1023, nil); result := copy(result, 1, x); if (Result <> '') then if Pos(#$0d+#$0a, Result) = (Length(Result) - 1) then Result := Copy(Result, 1, Length(Result) - 2); end; end; {$ENDIF} {---------- cpom Comport Ownership Manager Routines ------------- by Hans-Georg Joepgen of Stuttgart, Germany. Copyright (c) 2002, by Hans-Georg Joepgen Stefan Krauss of Stuttgart, Germany, contributed literature and Internet research results, invaluable advice and excellent answers to the Comport Ownership Manager. } {$IFDEF LINUX} function TBlockSerial.LockfileName: String; begin result := LockfileDirectory + '/LCK..ttyS' + IntToStr(FComNr); end; procedure TBlockSerial.CreateLockfile(PidNr: integer); var f: TextFile; s: string; begin // Create content for file s := IntToStr(PidNr); while length(s) < 10 do s := ' ' + s; // Create file AssignFile(f, LockfileName); Rewrite(f); writeln(f, s); CloseFile(f); // Allow all users to enjoy the benefits of cpom s := 'chmod a+rw ' + LockfileName; Libc.system(pchar(s)); end; function TBlockSerial.ReadLockfile: integer; {Returns PID from Lockfile. Lockfile must exist.} var f: TextFile; s: string; begin AssignFile(f, LockfileName); Reset(f); readln(f, s); CloseFile(f); Result := StrToIntDef(s, -1) end; function TBlockSerial.cpomComportAccessible: boolean; var MyPid: integer; Filename: string; begin Filename := LockfileName; MyPid := Libc.getpid; // Make sure, the Lock Files Directory exists. We need it. if not DirectoryExists(LockfileDirectory) then MkDir(LockfileDirectory); // Check the Lockfile if not FileExists (Filename) then begin // comport is not locked. Lock it for us. CreateLockfile(MyPid); result := true; exit; // done. end; // Is port owned by orphan? Then it's time for error recovery. if Libc.getsid(ReadLockfile) = -1 then begin // Lockfile was left from former desaster DeleteFile(Filename); // error recovery CreateLockfile(MyPid); result := true; exit; end; result := false // Sorry, port is owned by living PID and locked end; procedure TBlockSerial.cpomReleaseComport; begin DeleteFile(LockfileName); end; {$ENDIF} {----------------------------------------------------------------} end.
unit ucEXPORTARAQUIVO; interface uses Classes, SysUtils, StrUtils, Dialogs, Forms, DB, ucPREVIEW, QRExport; type TcEXPORTARAQUIVO = class public class function NomeArquivo(v_Arq : String = ''; v_Dir : String = '') : String; class procedure ExportaArquivo(v_PREVIEW : TcPREVIEW; v_Arq : String); class procedure ExportaToPlanilha(v_ClientDataSet : TDataSet; v_Arq : String); end; implementation uses ucFUNCAO; { ucEXPORTARAQUIVO } class function TcEXPORTARAQUIVO.NomeArquivo(v_Arq, v_Dir : String) : String; begin Result := ''; if v_Arq = '' then v_Arq := AnsiReplaceStr(ExtractFileName(Application.ExeName), ExtractFileExt(Application.ExeName), ''); if v_Dir = '' then v_Dir := ExtractFilePath(Application.ExeName) + '\Tempi'; with TOpenDialog.Create(nil) do begin InitialDir := v_Dir; FileName := v_Arq; Filter := 'Arquivo CSV (*.csv)|*.csv|'+ 'Arquivo DOC (*.doc)|*.doc|'+ 'Arquivo EXCEL (*.xls)|*.xls|'+ 'Arquivo HTML (*.html)|*.html|'+ 'Arquivo OpenOffice (*.ods)|*.ods|'+ 'Arquivo Report (*.qrp)|*.qrp|'+ 'Arquivo Texto (*.txt)|*.txt'; DefaultExt := '*.doc'; if Execute then Result := FileName; end; end; class procedure TcEXPORTARAQUIVO.ExportaArquivo(v_PREVIEW : TcPREVIEW; v_Arq: String); begin if not Assigned(v_PREVIEW) then Exit; if v_Arq = '' then Exit; if FileExists(v_Arq) then DeleteFile(v_Arq); with v_PREVIEW do begin if ExtractFileExt(v_Arq) = '.csv' then begin if Assigned(_ClientDataSet) then ExportaToPlanilha(_ClientDataSet, v_Arq) else _Preview.QRPrinter.ExportToFilter(TQRCommaSeparatedFilter.Create(v_Arq)); end else if ExtractFileExt(v_Arq) = '.doc' then begin _Preview.QRPrinter.ExportToFilter(TQRAsciiExportFilter.Create(v_Arq)); //end else if ExtractFileExt(v_Arq) = '.htm' then begin // _Preview.QRPrinter.ExportToFilter(TQRHTMLDocumentFilter.Create(v_Arq)); end else if ExtractFileExt(v_Arq) = '.txt' then begin _Preview.QRPrinter.ExportToFilter(TQRAsciiExportFilter.Create(v_Arq)); end else if ExtractFileExt(v_Arq) = '.qrp' then begin _Preview.QRPrinter.Save(v_Arq); end else if ExtractFileExt(v_Arq) <> '.qrp' then begin ExecutePrograma(v_Arq, '', ''); end; end; end; class procedure TcEXPORTARAQUIVO.ExportaToPlanilha(v_ClientDataSet : TDataSet; v_Arq: String); var v_Aux, v_Esp, v_Sep, v_Cpo : String; I : Integer; F : TextFile; begin if v_Arq = '' then Exit; if not Assigned(v_ClientDataSet) then Exit; if FileExists(v_Arq) then DeleteFile(v_Arq); v_Esp := Replicate(' ', 200); v_Sep := '|'; AssignFile(F, v_Arq); Rewrite(F); with v_ClientDataSet do begin v_Aux:=''; with Fields do for I:=0 to Count-1 do with Fields[I] do if (Pos(FieldName, v_Cpo) > 0) then v_Aux := v_Aux + v_Sep + Copy(DisplayLabel + v_Esp, 1, DisplayWidth); Writeln(F, v_Aux + v_Sep); First; while not EOF do begin v_Aux := ''; with Fields do for I:=0 to Count-1 do with Fields[I] do if (Pos(FieldName, v_Cpo) > 0) then v_Aux := v_Aux + v_Sep + Copy(AsString + v_Esp, 1, DisplayWidth); Writeln(F,v_Aux+v_Sep); Next; end; end; CloseFile(F); end; end.
unit UDialogs; interface uses Windows, UxlDialog, UxlRichEdit, Resource, UxlFunctions, UxlListView, UxlList, UxlWinControl, UxlStrUtils, CommCtrl, UxlStdCtrls, UxlClasses, UGlobalObj, UxlMiscCtrls, UxlCommDlgs, UCommPanels, UTypeDef, UxlFile, UxlComboBox; type TAboutBox = class (TxlDialog) private Fstprogram: TxlStaticText; protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnClose (); override; end; TLogInBox = class (TxlDialog) private FPassword: widestring; protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnCommand (ctrlID: integer); override; public property Password: widestring write FPassword; end; TInsertLinkBox = class (TxlDialog) private FLinkText: widestring; FCmbLinkType: TxlComboBox; procedure f_OnLinkTypeChange (Sender: TObject); function f_LinkType (): TLinkType; protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnClose (); override; procedure OnCommand (ctrlID: integer); override; public property LinkText: widestring read FLinkText; end; implementation uses UxlMenu, ULangManager, UOptionManager; const c_aboutbox: array[0..3] of word = (st_translator, IDOK, st_freeware, st_pleasedonate); procedure TAboutBox.OnInitialize (); begin SetTemplate (About_Box, MainIcon); end; procedure TAboutBox.OnOpen (); begin inherited; if not IsSameStr (LangMan.Language, 'Chinese') then begin // ItemText[st_freeware] := 'This program is a freeware!'; ItemText[st_copyright] := 'Copyright:'; ItemText[st_forum] := 'Forum:'; ItemText[st_homepage] := 'Homepage:'; ItemText[st_forumlink] := 'http://www.nebulasoft.cn/forum'; ItemText[st_authorname] := 'Xu Liang'; ItemText[st_author] := 'Author:'; ItemText[st_donate] := 'Donate'; ItemText[st_releasedate] := 'Release Date:'; // ItemText[st_pleasedonate] := 'If you wish to support, please click:'; end; RefreshItemText (self, c_aboutbox, About_Box); Fstprogram := TxlStaticText.create (self, ItemHandle[st_program]); with Fstprogram.Font do begin name := 'Arial'; Color := rgb(0,0,0); Size := 14; Bold := true; Italic := true; Underline := false; StrikeOut := false; end; Fstprogram.Color := GetSysColor(COLOR_BTNFACE); AddLink (st_homepagelink); AddLink (st_forumlink); AddLink (st_emaillink, 'mailto:' + ItemText[st_emaillink]); if IsSameStr (LangMan.Language, 'Chinese') then AddLink (st_donate, 'http://www.nebulasoft.cn/donate.html') else AddLink (st_donate, 'http://www.nebulasoft.cn/donate_en.html'); with TxlStaticIcon.create(self, ItemHandle[ProgramIcon]) do begin SetIcon (MainIcon); Free; end; end; procedure TAboutBox.OnClose (); begin FstProgram.free; inherited; end; //-------------------- procedure TLogInBox.OnInitialize (); begin inherited; SetTemplate (LogIn_Box, MainIcon); end; const c_loginbox: array [0..2] of word = (st_inputpassword, IDOK, IDCANCEL); procedure TLogInBox.OnOpen (); begin inherited; RefreshItemText (self, c_loginbox, LogIn_Box); FocusControl (sle_password); end; procedure TLogInBox.OnCommand (ctrlID: integer); begin if (ctrlID = IDOK) and (ItemText[sle_password] <> FPassWord) then begin ShowMessage (LangMan.GetItem (sr_wrongpassword, 'ÃÜÂë²»ÕýÈ·£¡'), mtInformation, LangMan.GetItem(sr_prompt)); FocusControl (sle_password); end else inherited OnCommand (ctrlID); end; //------------------------------ procedure TInsertLinkBox.OnInitialize (); begin SetTemplate (InsertLink_Box); end; const c_insertlinkbox: array [0..3] of word = (st_category, st_link, IDOK, IDCANCEL); procedure TInsertLinkBox.OnOpen (); var i: integer; //const c_linktypes: array[0..5] of integer = (sr_filelink, sr_folderlink, sr_pagelink, sr_emaillink, sr_nodelink, sr_otherlink); begin inherited; RefreshItemText (self, c_insertlinkbox, InsertLink_Box); FCmbLinkType := TxlComboBox.Create (self, ItemHandle[cmb_linktype]); FCmbLinkType.Items.OnSelChange := f_OnLinkTypeChange; for i := 0 to 5 do FCmbLinkType.Items.Add (LangMan.GetItem (sr_LinkTypes + i)); FCmbLinkType.Items.SelIndex := Ord(MemoryMan.InsertLinktype); f_OnLinkTypeChange(self); end; procedure TInsertLinkBox.OnClose (); begin MemoryMan.InsertLinkType := f_LinkType; FCmbLinkType.free; inherited; end; procedure TInsertLinkBox.OnCommand (ctrlID: integer); begin case ctrlID of IDOK: FLinkText := '<' + GetFullLink(ItemText[sle_linktext], f_LinkType, true, false) + '>'; cb_browse: if f_LinkType = ltFile then with TxlOpenDialog.create do begin Title := LangMan.GetItem (sr_selectfile); Filter := LangMan.GetItem (sr_filefilter); FilterIndex := 1; FileName := ItemText[sle_linktext]; MultiSelect := false; if Execute then ItemText[sle_linktext] := FulltoRelPath (Path + FileName, ProgDir); free; end else with TxlPathDialog.Create do begin Title := LangMan.GetItem (sr_selectfolder); Path := ItemText[sle_linktext]; if Execute then ItemText[sle_linktext] := FullToRelPath (Path, ProgDir); free; end; end; inherited OnCommand (ctrlID); end; function TInsertLinkBox.f_LinkType (): TLinkType; begin result := TLinkType(FCmbLinkType.Items.SelIndex); end; procedure TInsertLinkBox.f_OnLinkTypeChange (Sender: TObject); begin ItemEnabled[cb_browse] := FCmbLinkType.Items.SelIndex in [0, 1]; end; end.
unit untremotedatabasehelper; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Sockets, Dialogs, untDataStore, untField, untfieldarraylist, untDataStoreArrayList, IdTCPClient, IdGlobal, untUtils, untOnMatchedEventArgs, dateutils, IdIcmpClient; const SocketBufferSize:word=2048; UpdateFileBlockSize:word=2040; ERROR_Success:integer=0; ERROR_Fail:integer=-1; ERROR_NoConnection=-2; type QueryType = (qtExecuteNoResult = 0, qtExecuteSingleCell = 1, qtExecuteMultiRow = 2, qtVerifyFingerPrint=3, qtCheckUpdate=4, qtGetUpdate=5); Commands = (cmdDataSchema = 0, cmdData = 1, cmdEndOfFile = 2, cmdOK = 3, cmdExecuteNonQueryResult = 4, cmdEmptyResult = 5, cmdVerifyFingerPrintResult=6 ,cmdCheckUpdateResult=7, cmdUpdateStream=8); LastEventType = (laExecuteNonQuery, laSingleCell, laMultiRow); VerifyFingerPrintResult=( vfpMatched = 0, vfpNotMatched = 1 ); type { RemoteDatabaseHelper } RemoteDatabaseHelper = class private strRemoteDatabaseIp: string; nPort: word; letLastEvent: LastEventType; nLastCommandResult: integer; bolExecuteFinish: boolean; arySchema: array of Field; reader: TList; datastores: TDataStoreArrayList; sckMain:TIdTCPClient; RDCriticalSection:TRTLCriticalSection; public constructor Create(RemoteDatabaseIp: string; Port: word; var Successful: boolean); destructor Destroy; override; function ConnectToRemote:boolean;overload; function Disconnect: boolean; function Send(Buffer:TIdBytes):integer; function Receive(Buffer:TIdBytes; Length:integer;Append:boolean):integer; function ExecuteNonQuery(CommandText: string): integer; function ExecuteMultiRow(CommandText: string; var rows: TDataStoreArrayList): boolean; procedure CopyToBuffer(var Buffer: TIdBytes; Data: ansistring; Index: integer); function VerifyFingerPrints(RawTemplate: array of byte; LocationId:integer; Threshold:byte; var OMEA: TOnMatchedEventArgs): integer; function CheckUpdate:Int32; function GetUpdate(FileName:string):Int32; procedure CopyMemory(Src, Dest: Pointer; Len: Cardinal; Offset: Integer); function Ping:Boolean; end; implementation { RemoteDatabaseHelper } constructor RemoteDatabaseHelper.Create(RemoteDatabaseIp: string; Port: word; var Successful: boolean); begin strRemoteDatabaseIp := RemoteDatabaseIp; nPort := Port; Successful := True; InitCriticalSection(RDCriticalSection); end; destructor RemoteDatabaseHelper.Destroy; begin inherited Destroy; Disconnect; DoneCriticalsection(RDCriticalSection); end; function RemoteDatabaseHelper.ConnectToRemote: boolean; begin try sckMain:=TIdTCPClient.Create(nil); sckMain.Host:=self.strRemoteDatabaseIp; sckMain.Port:=self.nPort; sckMain.Connect; Result:=true; except on E:Exception do begin WriteLog('RemoteDatabaseHelper.ConnectToRemote, ' +E.ClassName+' error raised, with message : '+E.Message); Result:=false; end; end; end; function RemoteDatabaseHelper.Disconnect: boolean; begin try try if(sckMain.Connected) then sckMain.Disconnect; except on E:Exception do WriteLog('RemoteDatabaseHelper.Disconnect: ' + E.Message); end; finally FreeAndNil(sckMain); end; end; function RemoteDatabaseHelper.Send(Buffer: TIdBytes): integer; begin try sckMain.IOHandler.Write(Buffer); Result:=0; except on E:Exception do begin WriteLog('RemoteDatabeseHelper.Send:' + E.Message); Result:=ERROR_Fail; end; end; end; function RemoteDatabaseHelper.Receive(Buffer: TIdBytes; Length: integer; Append: boolean): integer; begin try sckMain.IOHandler.ReadBytes(Buffer, Length, Append); Result:=0; except on E:Exception do begin WriteLog('RemoteDatabaseHelper.Receive:' + E.Message); Result:=ERROR_Fail; end; end; end; function RemoteDatabaseHelper.ExecuteNonQuery(CommandText: string): integer; var buffer: TIdBytes; str:string; begin Result:=0; EnterCriticalsection(RDCriticalSection); try SetLength(buffer, SocketBufferSize); buffer[0] := byte(qtExecuteNoResult); buffer[1] := (Length(CommandText) + 3) mod 256; buffer[2] := (Length(CommandText) + 3) div 256; CopyToBuffer(buffer, CommandText, 3); if(not ConnectToRemote) then begin result:=ERROR_Fail; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; if Send(buffer)<> ERROR_Success then begin result:=ERROR_Fail; Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; if Receive(buffer, Length(buffer), false)<> ERROR_Success then begin result:=ERROR_Fail; Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; Result := Unaligned(PInteger(@buffer[1])^); finally Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); end; end; function RemoteDatabaseHelper.ExecuteMultiRow(CommandText: string; var rows: TDataStoreArrayList): boolean; var buffer, transBuffer: TIdBytes; nlength, RecordCount: word; i, index: integer; cmdType: Commands; fldArea: Field; row: array of TObject; dataIndex: word; dtsDataStore: TDataStore; fieldName: string; fields: TFieldArrayList; begin EnterCriticalsection(RDCriticalSection); try if(not ConnectToRemote) then begin Result:=false; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; SetLength(buffer, SocketBufferSize); buffer[0] := byte(qtExecuteMultiRow); buffer[1] := (Length(CommandText) + 3) mod 256; buffer[2] := (Length(CommandText) + 3) div 256; CopyToBuffer(buffer, CommandText, 3); if Send(buffer)<> ERROR_Success then begin Result:=false; SetLength(buffer, 0); Disconnect; LeaveCriticalsection(RDCriticalSection); exit; end; //sckMain.IOHandler.Write(buffer); while True do begin if Receive(buffer, Length(buffer), false)<> ERROR_Success then begin Result:=false; SetLength(buffer, 0); Disconnect; LeaveCriticalsection(RDCriticalSection); exit; end; //sckMain.IOHandler.ReadBytes(buffer, Length(buffer), false); if( buffer[0] + buffer[1] + buffer[2] = 0) then begin Continue; end; if (buffer[0] = byte(cmdDataSchema)) then begin index := 3; dataIndex := 3; //RecordCount :=(Unaligned(PWord(@buffer[1]))^ - 3) div 50; RecordCount:=((buffer[1]+buffer[2]*256)-3) div 50 ; fields := TFieldArrayList.Create; for i := 0 to RecordCount - 1 do begin SetString(fieldName, @buffer[i * 50 + index + 3], 47); fieldName:=trim(fieldname); fldArea := Field.Create(fieldName, PWord(@buffer[i * 50 + index + 1])^, FieldType(buffer[i * 50 + index]), DataIndex); fields.Add(fldArea); Inc(DataIndex, PWord(@buffer[i * 50 + index + 1])^); end; fields.nLength:=dataIndex; rows.FieldList:=fields; end else if (buffer[0] = byte(cmdData)) then begin try SetLength(row, fields.Count); index := 3; SetLength(transBuffer, fields.nLength); Move(buffer[0], transBuffer[0], Length(transBuffer)); dtsDataStore := TDataStore.Create(transBuffer, @rows.FieldList); rows.Add(dtsDataStore); except on E:Exception do ShowMessage('untRemoteDatabaseHelper.ExecuteMultiRow'+ E.ClassName + ';' + E.Message ); end; end else if (buffer[0] = byte(cmdEndOfFile)) then begin break; end else if (buffer[0] = byte(cmdEmptyResult)) then begin break; end; end; Result:=true; finally SetLength(buffer, 0); Disconnect; LeaveCriticalsection(RDCriticalSection); end; end; procedure RemoteDatabaseHelper.CopyToBuffer(var Buffer: TIdBytes; Data: ansistring; Index: integer); var i: integer; begin Move(Data[1], Buffer[Index], length(Data) * SizeOf(char)); end; procedure RemoteDatabaseHelper.CopyMemory(Src, Dest: Pointer; Len: Cardinal; Offset: Integer); var OffsetSrc: ^Byte; begin OffsetSrc := Src; inc(OffsetSrc, Offset); Move(OffsetSrc^, Dest^, Len); end; function RemoteDatabaseHelper.Ping: Boolean; var IcmpClient:TIdIcmpClient; begin Result:=true; IcmpClient:=TIdIcmpClient.Create(nil); IcmpClient.ReceiveTimeout:=200; IcmpClient.Host:=self.strRemoteDatabaseIp; IcmpClient.PacketSize:=24; IcmpClient.Protocol:=1; IcmpClient.IPVersion:=Id_IPv4; try IcmpClient.Ping(); Except on E:Exception do begin IcmpClient.Free; Result:=false; exit; end; end; if IcmpClient.ReplyStatus.ReplyStatusType<>rsEcho then Result:=false; IcmpClient.Free; end; function RemoteDatabaseHelper.VerifyFingerPrints(RawTemplate: array of byte; LocationId:integer; Threshold:byte; var OMEA: TOnMatchedEventArgs): integer; var second:Int64; buffer: TIdBytes; str:string; begin EnterCriticalsection(RDCriticalSection); try SetLength(buffer, SocketBufferSize); buffer[0] := byte(qtVerifyFingerPrint); buffer[1]:=Threshold; CopyMemory(@LocationId, @buffer[2], SizeOf(LocationId),0); CopyMemory(@RawTemplate[0], @buffer[6], Length(RawTemplate), 0); if not ConnectToRemote then begin result:=-2; SetLength(buffer,0 ); LeaveCriticalsection(RDCriticalSection); exit; end; if Send(buffer)<> ERROR_Success then //; sckMain.IOHandler.Write(buffer); begin Result:=-2; SetLength(buffer,0 ); LeaveCriticalsection(RDCriticalSection); Disconnect; exit; end; if Receive(buffer, Length(buffer), false)<> ERROR_Success then //; sckMain.IOHandler.Write(buffer); begin Result:=-2; SetLength(buffer,0 ); LeaveCriticalsection(RDCriticalSection); Disconnect; exit; end; //sckMain.IOHandler.ReadBytes(Buffer, Length(Buffer), false); if (Buffer[1]=Byte(vfpMatched)) then Result:=0 else if(buffer[1]=Byte(vfpNotMatched)) then Result:=-1 else Result:=-2; //WriteLog('Verify Result:' + IntToStr(Buffer[1])); OMEA.nMatchedLiableId:=Unaligned(PInteger(@buffer[2])^); OMEA.nMatchedFingerIndex:=Unaligned(PInteger(@buffer[10])^); second:=Unaligned(PInt64(@buffer[20])^); OMEA.dtCapturedTime:=EncodeDateTime(1970, 1, 1, 0, 0, 0, 0); OMEA.dtCapturedTime:=IncSecond(OMEA.dtCapturedTime, second); OMEA.nScore:=buffer[25]; finally Disconnect; LeaveCriticalsection(RDCriticalSection); end; end; function RemoteDatabaseHelper.CheckUpdate: Int32; var buffer: TIdBytes; nVersion:integer; begin EnterCriticalsection(RDCriticalSection); try SetLength(buffer, SocketBufferSize); buffer[0] := byte(qtCheckUpdate); if(not ConnectToRemote) then begin result:=-1; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; if(Send(buffer) <> ERROR_Success) then begin Result:=-1; Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; //sckMain.IOHandler.Write(buffer); if(Receive(buffer, Length(Buffer), false)<>ERROR_Success) then begin Result:=-1; Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); exit; end; //sckMain.IOHandler.ReadBytes(Buffer, Length(Buffer),false); nVersion:=Unaligned(pInt32(@buffer[1])^); Result:=nVersion; finally Disconnect; SetLength(buffer, 0); LeaveCriticalsection(RDCriticalSection); end; end; function RemoteDatabaseHelper.GetUpdate(FileName: string): Int32; var buffer, fsBuffer: TIdBytes; nOrder, nSize:Int16; fsStream:TFileStream; begin EnterCriticalsection(RDCriticalSection); try SetLength(buffer, SocketBufferSize); buffer[0] := byte(qtGetUpdate); if(not ConnectToRemote) then begin result:=-1; LeaveCriticalsection(RDCriticalSection); SetLength(buffer,0); exit; end; if(Send(buffer)<> ERROR_Success) then begin Result:=ERROR_Fail; fsStream.Free; SetLength(buffer, 0); SetLength(fsBuffer, 0); Disconnect; LeaveCriticalsection(RDCriticalSection); end; //sckMain.IOHandler.Write(buffer); fsStream:=TFileStream.Create(FileName, fmCreate); while true do begin if( Receive(buffer, Length(buffer), false) <> ERROR_Success) then begin Result:=ERROR_Fail; Disconnect; fsStream.Free; LeaveCriticalsection(RDCriticalSection); SetLength(buffer,0); exit; end; //sckMain.IOHandler.ReadBytes(Buffer, Length(Buffer),false); nOrder:=Unaligned(pInt32(@buffer[1])^); nSize:=Unaligned(pInt32(@buffer[3])^); if (nOrder = -1 ) then break; SetLength(fsBuffer, nSize); CopyMemory(@buffer[5], @fsBuffer[0], nSize, 0); fsStream.Seek(nOrder* UpdateFileBlockSize, soBeginning); fsStream.Write(fsBuffer, nSize); end; finally fsStream.Free; SetLength(buffer, 0); SetLength(fsBuffer, 0); Disconnect; LeaveCriticalsection(RDCriticalSection); end; end; end.
unit uCAP_User; {##################################################################################} (*!*EXTENDED COMMENT SYNTAX !*) (** This unit uses extended syntax for comments **) (** You don't need to support this, but it's more likely to be readable **) (** if you do **) (** If your IDE is using SynEdit, you may find a SynHighlighterPas.pp-file here: **) (** https://github.com/Life4YourGames/IDE-Extensions **) (** You have to set the colors yourself in your IDEs setting **) (** Afaik: Lazarus and CodeTyphon automatically detect those new attributes **) (** Also: The comments are all valid fpc-comments, you don't have to worry **) (** Syntax-description: **) (*- Divider **) (* Native AnsiComment / Cathegory **) (*! Warning, pay attention !*) (* TODO **) (* DONE **) { native bor comment } //Native double-slash comment (*! End of comment syntax info **) {##################################################################################} {$mode objfpc}{$H+} interface uses Classes, SysUtils (** BaseVars *), ucap_basevars (** BaseObject *), uCAP_BaseObjects (** Permission *), uCAP_Permission (** JSONs *), fpjson; type (*! This is child of "IndexedObject" which means, you can store aditional objects in runtime !*) (** Of course I can't save them to the file, BUT this may be used e.g. for associating a socket to a user *) { TCustomAP_User } TCustomAP_User = class(TCustomAP_IndexedObject) public (*- construction / destruction -*) constructor Create; destructor Destroy; override; private (*- private fields -*) (** Permissions *) FPerms: TCustomAP_PermRef; (** Attributes *) (** For Attribute->Value relations, store them simply as a permission *) FAttributes: TStringList; (** Options *) FOptionNames: TStringList; FOptionValues: TStringList; (** Groups - are not included in perm comparision! *) FGroups: TStringList; (** Default Mask for Perm-Comparision *) FDefaultCompare: string; (** Identify the user *) FUID: string; (* Autosave data *) (** FilePath *) FAutoSaveFile: string; (** Should changes be automatically flushed to file *) FDoAutoSave: boolean; (** Prevents procedure from being run twice or more *) FFileSaveLock: boolean; private (*- private methods *) (* o.o.b.s *) function oob(pIdent: string): boolean; overload; function oob(pIndex: integer): boolean; overload; function Attr_oob(pIndex: integer): boolean; function Opt_oob(pIdent: string): boolean; overload; function Opt_oob(pIndex: integer): boolean; overload; function Grp_oob(pIndex: integer): boolean; (* AutoSave *) procedure RequestFlush; public (*- public methods *) (* Getter *) (** UID *) function GetUID: string; (** Get a permission by ID or Index; Basically forwards to FPerms *) function GetPermission(pIdent: string): TCustomAP_SinglePerm; overload; function GetPermission(pIndex: integer): TCustomAP_SinglePerm; overload; (** Get an Attribute by Index *) function GetAttribute(pIndex: integer): string; (** Get a group by index *) function GetGroup(pIndex: integer): string; (** InstantFlushFile *) function GetFilePath: string; (* Setter *) (** UID *) procedure SetUID(pNewID: string); (** Set a permission by ID or Index; Basically forwards to FPerms *) procedure SetPermission(pIdent: string; pPerm: TCustomAP_SinglePerm); overload; procedure SetPermission(pIndex: integer; pPerm: TCustomAP_SinglePerm); overload; (** Set an Attribute by index; Adds if oob (and not found) *) procedure SetAttribute(pIndex: integer; pAttrib: string); (** Set a group by index; Adds if oob (and not found) *) procedure SetGroup(pIndex: integer; pGroup: string); (** InstantFlushFile *) procedure SetFilePath(pFilePath: string; pDoAutoCreate: boolean = True); (* Utils *) (*- Counts -*) function Count_Permissions: integer; function Count_Attributes: integer; function Count_Options: integer; function Count_Groups: integer; (*- Permissions -*) (** Add a permission, return index; Basically forwards to FPerms *) function AddPermission(pIdent: string; pPerm: TCustomAP_SinglePerm): integer; (** Delete a permission; Basically forwards to FPerms *) procedure DeletePermission(pIdent: string); overload; procedure DeletePermission(pIndex: integer); overload; (** Compare permissions based on FDefaultCompare, uses local permissions for Left side of comparision *) function HasPermission(pIdent: string; pValueIndex: integer; pValue: integer): boolean; overload; virtual; function HasPermission(pPerm: TCustomAP_SinglePerm; pValueIndex: integer): boolean; overload; function HasPermission(pIdent: string): boolean; (** Return Index of permission by Ident OR Object; forwards to FPerms *) function IndexOfPermission(pIdent: string): integer; overload; function IndexOfPermission(pPerm: TCustomAP_SinglePerm): integer; overload; (** Add an Attribute, return index *) function AddAttribute(pAttrib: string): integer; (** Check if attribute exists *) function HasAttribute(pAttrib: string): boolean; (** Return Index of Attribute; -1 if not found *) function IndexOfAttribute(pAttrib: string): integer; (*- Options -*) (** Add an option; Returns index, only returns index, if option Ident exists *) function AddOption(pIdent: string; pValue: string): integer; (** Get an options Value by Ident or Index *) function GetOptionVal(pIdent: string): string; overload; function GetOptionVal(pIndex: integer): string; overload; (* DONE -cUserOptions : Add procedure bodys and notes *) (** Set an option by ID or Index; ID-Procedure adds Option if missing *) procedure SetOptionVal(pIdent: string; pValue: string); procedure SetOptionVal(pIndex: integer; pValue: string); (** Return the ID of an option at a given Index *) function GetOptionID(pIndex: integer): string; (** Change the ID of an option at a given index *) procedure SetOptionID(pIndex: integer; pNewID: string); (** Returns the index of the option; -1 if not found *) function IndexOfOptionID(pIdent: string): integer; (*- Groups -*) (** Add a group, return index *) function AddGroup(pGroup: string): integer; (** Check if group exists *) function HasGroup(pGroup: string): boolean; (** Return Index of group; -1 if not found *) function IndexOfGroup(pGroup: string): integer; (*- Export + File handling -*) (** Throw out/Import a json containing the attributes, the permissions and their values *) function ExportJSON(pFormatOptions: TFormatOptions = CCAP_DefaultJSONFormat): string; procedure ImportJSON(pJSONString: string); {$IFNDEF CAP_DisableAbstract} (** Placeholder for other possibilities to import/export *) function ExportString: string; virtual; abstract; procedure ImportString(pInputString: string); virtual; abstract; {$ENDIF} (** File update *) procedure SaveToFile(pFilePath: string = ''); procedure DisableAutoSave; procedure EnableAutoSave; procedure UpdateFile; function IsFileSaveLocked: boolean; (** Object update *) (** Will load object from file and set FAutoSaveFile if provided, but NOT "FDoAutoSave" *) procedure LoadFromFile(pFilePath: string; pUseAsInstantFlush: boolean = True); (** Reloads from FAutoSaveFile if possible *) procedure ReloadFile; (*- Content management -*) (** Clear object (calls inherited) - will normally request a fileflush *) procedure Wipe; override; (** Clone the object *) function Clone: TCustomAP_User; end; implementation { TCustomAP_User } constructor TCustomAP_User.Create; begin inherited Create; FPerms := TCustomAP_PermRef.Create; FAttributes := TStringList.Create; FDefaultCompare := CCAP_DefaultCompare; FFileSaveLock := False; FDoAutoSave := False; FAutoSaveFile := ''; //Set default UID, you may wanna check your application if you see that in your files... FUID := '__cap_error_uid_not_set__'; end; destructor TCustomAP_User.Destroy; begin FPerms.Wipe; FPerms.Free; FAttributes.Free; inherited Destroy; end; function TCustomAP_User.oob(pIdent: string): boolean; begin Result := oob(FPerms.IndexOf(pIdent)); end; function TCustomAP_User.oob(pIndex: integer): boolean; begin Result := True; if ((pIndex < 0) or (pIndex >= FPerms.Count)) then Exit; Result := False; end; function TCustomAP_User.Attr_oob(pIndex: integer): boolean; begin Result := True; if ((pIndex < 0) or (pIndex >= FAttributes.Count)) then Exit; Result := False; end; function TCustomAP_User.Opt_oob(pIdent: string): boolean; begin Result := (Opt_oob(IndexOfOptionID(pIdent))); end; function TCustomAP_User.Opt_oob(pIndex: integer): boolean; begin Result := ((pIndex < 0) or (pIndex >= FOptionNames.Count)); end; function TCustomAP_User.Grp_oob(pIndex: integer): boolean; begin Result := True; if ((pIndex < 0) or (pIndex >= FGroups.Count)) then Exit; Result := False; end; procedure TCustomAP_User.RequestFlush; begin if (FDoAutoSave = False) then Exit; SaveToFile(''); end; function TCustomAP_User.GetUID: string; begin Result := FUID; end; function TCustomAP_User.GetPermission(pIdent: string): TCustomAP_SinglePerm; begin Result := FPerms.GetPerm(pIdent); end; function TCustomAP_User.GetPermission(pIndex: integer): TCustomAP_SinglePerm; begin Result := FPerms.GetPerm(pIndex); end; function TCustomAP_User.GetAttribute(pIndex: integer): string; begin Result := ''; if (Attr_oob(pIndex) = True) then Exit; Result := FAttributes.Strings[pIndex]; end; function TCustomAP_User.GetGroup(pIndex: integer): string; begin Result := ''; if (Grp_oob(pIndex) = True) then Exit; Result := FGroups.Strings[pIndex]; end; function TCustomAP_User.GetFilePath: string; begin Result := FAutoSaveFile; end; procedure TCustomAP_User.SetUID(pNewID: string); begin if ((pNewID <> FUID) and (Length(pNewID) > 2)) then begin FUID := pNewID; RequestFlush; end; end; procedure TCustomAP_User.SetPermission(pIdent: string; pPerm: TCustomAP_SinglePerm); begin FPerms.SetPerm(pIdent, pPerm); RequestFlush; end; procedure TCustomAP_User.SetPermission(pIndex: integer; pPerm: TCustomAP_SinglePerm); begin FPerms.SetPerm(pIndex, pPerm); RequestFlush; end; procedure TCustomAP_User.SetAttribute(pIndex: integer; pAttrib: string); begin //Attribute exists, exit if (Attr_oob(IndexOfAttribute(pAttrib)) = False) then Exit; if (Attr_oob(pIndex) = True) then begin AddAttribute(pAttrib); Exit; end; FAttributes.Strings[pIndex] := pAttrib; RequestFlush; end; procedure TCustomAP_User.SetGroup(pIndex: integer; pGroup: string); begin //Group exists, exit if (Grp_oob(IndexOfGroup(pGroup)) = False) then Exit; if (Grp_oob(pIndex) = True) then begin AddGroup(pGroup); Exit; end; FGroups.Strings[pIndex] := pGroup; RequestFlush; end; procedure TCustomAP_User.SetFilePath(pFilePath: string; pDoAutoCreate: boolean); begin if (Length(pFilePath) < 3) then Exit; if (pFilePath = FAutoSaveFile) then Exit; FAutoSaveFile := pFilePath; if (pDoAutoCreate = True) then SaveToFile(FAutoSaveFile); end; function TCustomAP_User.Count_Permissions: integer; begin Result := FPerms.Count; end; function TCustomAP_User.Count_Attributes: integer; begin Result := FAttributes.Count; end; function TCustomAP_User.Count_Options: integer; begin Result := FOptionNames.Count; end; function TCustomAP_User.Count_Groups: integer; begin Result := FGroups.Count; end; function TCustomAP_User.AddPermission(pIdent: string; pPerm: TCustomAP_SinglePerm): integer; begin Result := FPerms.AddPerm(pIdent, pPerm); RequestFlush; end; procedure TCustomAP_User.DeletePermission(pIdent: string); begin FPerms.DeletePerm(pIdent); RequestFlush; end; procedure TCustomAP_User.DeletePermission(pIndex: integer); begin FPerms.DeletePerm(pIndex); RequestFlush; end; function TCustomAP_User.HasPermission(pIdent: string; pValueIndex: integer; pValue: integer): boolean; begin Result := False; end; function TCustomAP_User.HasPermission(pPerm: TCustomAP_SinglePerm; pValueIndex: integer): boolean; begin Result := FPerms.ComparePermTo(pPerm, IndexOfPermission(pPerm), pValueIndex, FDefaultCompare); end; function TCustomAP_User.HasPermission(pIdent: string): boolean; begin Result := (oob(IndexOfPermission(pIdent))); end; function TCustomAP_User.IndexOfPermission(pIdent: string): integer; begin Result := FPerms.IndexOf(pIdent); end; function TCustomAP_User.IndexOfPermission(pPerm: TCustomAP_SinglePerm): integer; begin Result := FPerms.IndexOf(pPerm); end; function TCustomAP_User.AddAttribute(pAttrib: string): integer; begin //Exists -> Exit if (Attr_oob(IndexOfAttribute(pAttrib)) = False) then Exit; Result := FAttributes.Add(pAttrib); RequestFlush; end; function TCustomAP_User.HasAttribute(pAttrib: string): boolean; begin Result := (not Attr_oob(IndexOfAttribute(pAttrib))); end; function TCustomAP_User.IndexOfAttribute(pAttrib: string): integer; begin Result := FAttributes.IndexOf(pAttrib); end; function TCustomAP_User.AddOption(pIdent: string; pValue: string): integer; begin Result := (IndexOfOptionID(pIdent)); if (Opt_oob(Result) = True) then begin Result := FOptionNames.Add(pIdent); FOptionValues.Add(pValue); end; end; function TCustomAP_User.GetOptionVal(pIdent: string): string; begin Result := ''; if (Opt_oob(pIdent) = True) then Exit; Result := GetOptionVal(IndexOfOptionID(pIdent)); end; function TCustomAP_User.GetOptionVal(pIndex: integer): string; begin Result := ''; if (Opt_oob(pIndex) = True) then Exit; Result := FOptionValues.Strings[pIndex]; end; procedure TCustomAP_User.SetOptionVal(pIdent: string; pValue: string); begin if (Opt_oob(pIdent) = False) then begin SetOptionVal(IndexOfOptionID(pIdent), pValue); end else begin AddOption(pIdent, pValue); end; end; procedure TCustomAP_User.SetOptionVal(pIndex: integer; pValue: string); begin if (Opt_oob(pIndex) = True) then Exit; FOptionValues.Strings[pIndex] := pValue; end; function TCustomAP_User.GetOptionID(pIndex: integer): string; begin Result := ''; if (Opt_oob(pIndex) = True) then Exit; Result := FOptionNames.Strings[pIndex]; end; procedure TCustomAP_User.SetOptionID(pIndex: integer; pNewID: string); begin if (Opt_oob(pIndex) = True) then Exit; FOptionNames.Strings[pIndex] := pNewID; end; function TCustomAP_User.IndexOfOptionID(pIdent: string): integer; begin Result := FOptionNames.IndexOf(pIdent); end; function TCustomAP_User.AddGroup(pGroup: string): integer; begin //Exists -> Exit if (Grp_oob(IndexOfGroup(pGroup)) = False) then Exit; Result := FGroups.Add(pGroup); RequestFlush; end; function TCustomAP_User.HasGroup(pGroup: string): boolean; begin Result := (not Grp_oob(IndexOfGroup(pGroup))); end; function TCustomAP_User.IndexOfGroup(pGroup: string): integer; begin Result := FGroups.IndexOf(pGroup); end; function TCustomAP_User.ExportJSON(pFormatOptions: TFormatOptions): string; var lObj: TJSONObject; lArr, lArr2: TJSONArray; I: integer; begin lObj := TJSONObject.Create; lObj.Add(CCAP_JSONKey_permRefs, FPerms.ExportJSON); lArr := TJSONArray.Create; for I := 0 to (Count_Attributes - 1) do begin lArr.Add(GetAttribute(I)); end; lObj.Add(CCAP_JSONKey_UAttributes, lArr); lArr := TJSONArray.Create; lArr2 := TJSONArray.Create; for I:=0 to (Count_Options - 1) do begin lArr.Add(GetOptionID(I)); lArr2.Add(GetOptionVal(I)); end; lObj.Add(CCAP_JSONKey_UOptionIDs, lArr); lObj.Add(CCAP_JSONKey_UOptionVals, lArr2); lArr := nil; lArr := TJSONArray.Create; for I := 0 to (Count_Groups - 1) do begin lArr.Add(GetGroup(I)); end; lObj.Add(CCAP_JSONKey_UGroups, lArr); Result := lObj.FormatJSON(pFormatOptions); lObj.Free; end; procedure TCustomAP_User.ImportJSON(pJSONString: string); var lObj: TJSONObject; lData, lData2: TJSONData; lArr, lArr2: TJSONArray; EMsg, lStr, lType, lID: string; I: integer; begin Self.Wipe; //Retreve Object lObj := (GetJSON(pJSONString) as TJSONObject); lType := lObj.Get(CCAP_JSONKey_Type, ''); if (lType <> CCAP_JSONVal_UType) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_201 + 'Invalid type supplied!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; //Import UID lID := lObj.Get(CCAP_JSONKey_ID, ''); if (Length(lID) < 2) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERN_CAP_E_203 + 'Insufficient ID-Length!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; SetUID(lID); //Import Permissions lStr := lObj.Get(CCAP_JSONKey_permRefs); if (Length(lStr) < 2) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERN_CAP_E_203 + 'Insufficient Permission-Length!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; FPerms.ImportJSON(lStr); //Import Attributes lData := lObj.Arrays[CCAP_JSONKey_UAttributes]; if (lData = nil) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_202 + ' This SHOULD NOT happen, fix your files immediately !'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; if (lData.JSONType <> jtArray) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_201 + ' This SHOULD NOT happen, fix your files immediately!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; lArr := (lData as TJSONArray); for I := 0 to (lArr.Count - 1) do begin try AddAttribute(lArr.Strings[I]); except on E: Exception do begin EMsg := ''; EMsg := EC_CAP_E_002 + EC_CAP_E_001 + E.ClassName + ':' + E.Message; raise ECustomAPError.Create(EMsg); lObj.Free; end; end; end; //Import Options lData := lObj.Arrays[CCAP_JSONKey_UOptionIDs]; lData2:= lObj.Arrays[CCAP_JSONKey_UOptionVals]; if ((lData = nil) or (lData2 = nil)) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_202 + 'Options ARE NIL! This SHOULD NOT happen, fix your files immediately !'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; if ((lData.JSONType <> jtArray) or (lData2.JSONType <> jtArray)) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_201 +'OptionTypes are NOT jtArray! This SHOULD NOT happen, fix your files immediately!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; lArr := (lData as TJSONArray); lArr2:= (lData2 as TJSONArray); if (lArr.Count <> lArr2.Count) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_203 +'OptionCounts do NOT match! This SHOULD NOT happen, fix your files immediately!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; for I := 0 to (lArr.Count - 1) do begin try AddOption(lArr.Strings[I], lArr2.Strings[I]); except on E: Exception do begin EMsg := ''; EMsg := EC_CAP_E_002 + EC_CAP_E_001 + E.ClassName + ':' + E.Message; raise ECustomAPError.Create(EMsg); lObj.Free; end; end; end; //Import Groups lData := lObj.Arrays[CCAP_JSONKey_UGroups]; if (lData = nil) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_202 + ' This SHOULD NOT happen, fix your files immediately !'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; if (lData.JSONType <> jtArray) then begin EMsg := ''; EMsg := (EC_CAP_E_002 + ERC_CAP_E_201 + ' This SHOULD NOT happen, fix your files immediately!'); raise ECustomAPError.Create(EMsg); lObj.Free; Exit; end; lArr := (lData as TJSONArray); for I := 0 to (lArr.Count - 1) do begin try AddGroup(lArr.Strings[I]); except on E: Exception do begin EMsg := ''; EMsg := EC_CAP_E_002 + EC_CAP_E_001 + E.ClassName + ':' + E.Message; raise ECustomAPError.Create(EMsg); lObj.Free; end; end; end; lObj.Free; //Update file RequestFlush; end; procedure TCustomAP_User.SaveToFile(pFilePath: string); var lList: TStringList; lStr, EMsg: string; begin if (FFileSaveLock = True) then Exit; if ((pFilePath = '') and (FAutoSaveFile <> '')) then begin SaveToFile(FAutoSaveFile); Exit; end; pFilePath := StringReplace(pFilePath, CCAP_Alias_ID, GetUID, [rfIgnoreCase, rfReplaceAll]); {$IFDEF CAP_StrictSeperations} pFilePath := StringReplace(pFilePath, CCAP_Alias_ObjectID, GetIdent, [rfIgnoreCase, rfReplaceAll]); {$ELSE} pFilePath := StringReplace(pFilePath, CCAP_Alias_ObjectID, GetName, [rfIgnoreCase, rfReplaceAll]); {$ENDIF} pFilePath := StringReplace(pFilePath, CCAP_Alias_Date, DateToStr(now), [rfIgnoreCase, rfReplaceAll]); pFilePath := StringReplace(pFilePath, CCAP_Alias_Time, TimeToStr(now), [rfIgnoreCase, rfReplaceAll]); lStr := ExtractFileName(pFilePath); if (Length(lStr) < 1) then begin EMsg := (EC_CAP_E_003 + ERC_CAP_E_204 + 'Filename "' + pFilePath + '" is invalid!'); raise ECustomAPError.Create(EMsg); Exit; end; ForceDirectories(ExtractFileDir(pFilePath)); FFileSaveLock := True; lList := TStringList.Create; lList.Delimiter := #10; lList.StrictDelimiter := True; lList.DelimitedText := ExportJSON([foUseTabchar]); //Write to file lList.SaveToFile(pFilePath); lList.Free; FFileSaveLock := False; end; procedure TCustomAP_User.DisableAutoSave; begin FDoAutoSave := False; end; procedure TCustomAP_User.EnableAutoSave; begin FDoAutoSave := True; //RequestFlush; end; procedure TCustomAP_User.UpdateFile; begin SaveToFile(FAutoSaveFile); end; function TCustomAP_User.IsFileSaveLocked: boolean; begin Result := FFileSaveLock; end; procedure TCustomAP_User.LoadFromFile(pFilePath: string; pUseAsInstantFlush: boolean); var EMsg: string; lList: TStringList; begin //Load NOT possible while flushing! if (FFileSaveLock = True) then Exit; FFileSaveLock := True; pFilePath := StringReplace(pFilePath, CCAP_Alias_ID, GetUID, [rfIgnoreCase, rfReplaceAll]); {$IFDEF CAP_StrictSeperations} pFilePath := StringReplace(pFilePath, CCAP_Alias_ObjectID, GetIdent, [rfIgnoreCase, rfReplaceAll]); {$ELSE} pFilePath := StringReplace(pFilePath, CCAP_Alias_ObjectID, GetName, [rfIgnoreCase, rfReplaceAll]); {$ENDIF} pFilePath := StringReplace(pFilePath, CCAP_Alias_Date, DateToStr(now), [rfIgnoreCase, rfReplaceAll]); pFilePath := StringReplace(pFilePath, CCAP_Alias_Time, TimeToStr(now), [rfIgnoreCase, rfReplaceAll]); if (FileExists(pFilePath) = False) then begin EMsg := (EC_CAP_E_003 + ERC_CAP_E_204 + 'Filepath "' + pFilePath + '" does NOT exist !'); raise ECustomAPError.Create(EMsg); Exit; end; lList := TStringList.Create; lList.Delimiter := #10; lList.StrictDelimiter := True; lList.LoadFromFile(pFilePath); ImportJSON(lList.Text); if (pUseAsInstantFlush = True) then FAutoSaveFile := pFilePath; FFileSaveLock := False; end; procedure TCustomAP_User.ReloadFile; begin LoadFromFile(FAutoSaveFile); end; procedure TCustomAP_User.Wipe; begin FPerms.Wipe; FAttributes.Clear; FGroups.Clear; inherited Wipe; RequestFlush; end; function TCustomAP_User.Clone: TCustomAP_User; var I: integer; begin Result := TCustomAP_User.Create; Result.DisableAutoSave; Result.SetUID(Self.GetUID); Result.SetFilePath(Self.GetFilePath, True); //Copy items for I := 0 to (Self.Count - 1) do begin Result.AddItem(Self.GetName(I), Self.GetItem(I)); end; //Copy permissions for I := 0 to (Self.Count_Permissions - 1) do begin Result.AddPermission(Self.GetPermission(I).GetID, Self.GetPermission(I)); end; //Copy Attributes for I := 0 to (Self.Count_Attributes - 1) do begin Result.AddAttribute(Self.GetAttribute(I)); end; //Copy Groups for I := 0 to (Self.Count_Groups - 1) do begin Result.AddGroup(Self.GetGroup(I)); end; end; end.
unit uFontInfo; {$mode objfpc} {$H+} {$inline on} interface uses Classes, SysUtils; type { TFontInfo } TFontInfo = class FileName : string; Copyright : string; FamilyName : string; SubFamilyName : string; MajorVersion, MinorVersion : Word; Stream : TMemoryStream; constructor Create; destructor Destroy; override; end; PFontInfo = ^TFontInfo; procedure CollectFonts (PreLoad : boolean = false); function GetFont (byDesc : string; var Size : integer) : TFontInfo; function FontInfo (fn : string; var Info : TFontInfo) : boolean; function GetFontByName (byName : string; Load : boolean) : TFontInfo; var Fonts : TList = nil; implementation uses ulog; var i : integer; type (* 0 Copyright notice. 1 Font Family name. 2 Font Subfamily name. Font style (italic, oblique) and weight (light, bold, black, etc.). A font with no particular differences in weight or style (e.g. medium weight, not italic) should have the string "Regular" stored in this position. 3 Unique font identifier. Usually similar to 4 but with enough additional information to be globally unique. Often includes information from Id 8 and Id 0. 4 Full font name. This should be a combination of strings 1 and 2. Exception: if the font is “Regular” as indicated in string 2, then use only the family name contained in string 1. This is the font name that Windows will expose to users. 5 Version string. Must begin with the syntax ‘Version n.nn ‘ (upper case, lower case, or mixed, with a space following the number). 6 Postscript name for the font. *) TT_OFFSET_TABLE = record uMajorVersion, uMinorVersion, uNumOfTables, uSearchRange, uEntrySelector, uRangeShift : Word; end; // Tables in TTF file and theit placement and name (tag) TT_TABLE_DIRECTORY = record szTag : array [0..3] of Char; // table name uCheckSum, // Check sum uOffset, // Offset from beginning of file uLength : Cardinal; // length of the table in bytes end; // Header of names table TT_NAME_TABLE_HEADER = record uFSelector, // format selector. Always 0 uNRCount, // Name Records count uStorageOffset : Word; // Offset for strings storage, end; // from start of the table // Record in names table TT_NAME_RECORD = record uPlatformID, uEncodingID, uLanguageID, uNameID, uStringLength, uStringOffset : Word; // from start of storage area end; function ByteSwap (const a : cardinal): cardinal; inline; begin Result := ((a and $ff) shl 24) + ((a and $ff00) shl 8) + ((a and $ff0000) shr 8) + ((a and $ff000000) shr 24); end; function ByteSwap16 (w : Word): Word; inline; begin Result := ((w and $ff) shl 8) + ((w and $ff00) shr 8); end; function FontInfo (fn : string; var Info : TFontInfo) : boolean; var f : TFileStream; ot : TT_OFFSET_TABLE; tb : TT_TABLE_DIRECTORY; nth : TT_NAME_TABLE_HEADER; nr : TT_NAME_RECORD; i, j : integer; p : int64; a : string; begin Result := false; Info.Copyright := ''; Info.FamilyName := ''; Info.FileName := ''; Info.SubFamilyName := ''; Info.MajorVersion := 0; Info.MinorVersion := 0; ot.uNumOfTables := 0; // prevent not initialised warning tb.uCheckSum := 0; // prevent not initialised warning nth.uNRCount := 0; // prevent not initialised warning nr.uNameID := 0; // prevent not initialised warning if ExtractFileExt (fn) = '' then fn := fn + '.ttf'; if not FileExists (fn) then exit; Info.FileName := fn; try f := TFileStream.Create (fn, fmOpenRead); try f.Seek (0, soFromBeginning); f.Read (ot, SizeOf (TT_OFFSET_TABLE)); ot.uNumOfTables := ByteSwap16 (ot.uNumOfTables); Info.MajorVersion := ByteSwap16 (ot.uMajorVersion); Info.MinorVersion := ByteSwap16 (ot.uMinorVersion); for i := 1 to ot.uNumOfTables do begin f.Read (tb, SizeOf (TT_TABLE_DIRECTORY)); if CompareText (string (tb.szTag), 'name')= 0 then begin tb.uLength := ByteSwap (tb.uLength); tb.uOffset := ByteSwap (tb.uOffset); f.Seek (tb.uOffset, soFromBeginning); f.Read (nth, SizeOf (TT_NAME_TABLE_HEADER)); nth.uNRCount := ByteSwap16 (nth.uNRCount); nth.uStorageOffset := ByteSwap16 (nth.uStorageOffset); for j := 1 to nth.uNRCount do begin f.Read (nr, SizeOf (TT_NAME_RECORD)); nr.uNameID := ByteSwap16 (nr.uNameID); nr.uStringLength := ByteSwap16 (nr.uStringLength); nr.uStringOffset := ByteSwap16 (nr.uStringOffset); nr.uEncodingID := ByteSwap16 (nr.uEncodingID); nr.uLanguageID := ByteSwap16 (nr.uLanguageID); p := f.Position; f.Seek (tb.uOffset + nth.uStorageOffset + nr.uStringOffset, soFromBeginning); SetLength (a, nr.uStringLength); f.Read (a[1], nr.uStringLength); if nr.uEncodingID = 0 then case nr.uNameID of 0 : Info.Copyright := a; 1 : Info.FamilyName := a; 2 : Info.SubFamilyName := a; end; f.Seek (p, soFromBeginning); end; Result := true; break; end; end; finally f.Free; end; except end; end; procedure CollectFonts (PreLoad : boolean); var sr : TSearchRec; err : integer; fi : TFontInfo; i : integer; f : TFileStream; begin if Fonts = nil then exit; for i := 0 to Fonts.Count - 1 do TFontInfo (Fonts[i]).Free; Fonts.Clear; err := FindFirst ('*.ttf', faArchive, sr); while err = 0 do begin fi := TFontInfo.Create; if FontInfo (sr.Name, fi) then begin Fonts.Add (fi); if Preload then try f := TFileStream.Create (sr.Name, fmOpenRead); fi.Stream := TMemoryStream.Create; fi.Stream.CopyFrom (f, 0); f.Free; except end; end else fi.Free; err := FindNext (sr); end; FindClose (sr); end; const ny : array [boolean] of string = ('NO', 'YES'); function GetFont (byDesc : string; var Size : integer) : TFontInfo; var i, j, k : integer; bd, it : boolean; fn : string; begin Result := nil; i := Pos ('-', byDesc); if i = 0 then exit; fn := ''; bd := false; it := false; try fn := Copy (byDesc, i + 1, length (byDesc) - i); // log ('family name ' + fn); k := 0; for j := 1 to i - 1 do case byDesc[j] of 'B', 'b' : bd := true; 'I', 'i' : it := true; // 'U', 'u' : ul := true; // underline is a rendering function '0'..'9' : k := (k * 10) + (ord (byDesc[j]) - 48); end; if k > 0 then Size := k; except end; for i := 0 to Fonts.Count - 1 do with TFontInfo (Fonts[i]) do if (CompareText (FamilyName, fn) = 0) and ((Pos ('Bold', SubFamilyName) > 0) = bd) and ((Pos ('Italic', SubFamilyName) > 0) = it) then begin Result := TFontInfo (Fonts[i]); exit end; end; function GetFontByName (byName : string; Load : boolean) : TFontInfo; var i : integer; f : TFilestream; begin Result := nil; for i := 0 to Fonts.Count - 1 do begin if TFontInfo (Fonts[i]).FileName = byName then begin Result := TFontInfo (Fonts[i]); break; end; end; if (Result = nil) and FileExists (byName) then begin Result := TFontInfo.Create; if FontInfo (byName, Result) then Fonts.Add (Result) else begin Result.Free; Result := nil; end; end; if (Result = nil) or (not Load) then exit; if Result.Stream <> nil then exit; // already loaded Result.Stream := TMemoryStream.Create; try f := TFileStream.Create (byName, fmOpenRead); Result.Stream.CopyFrom (f, f.Size); f.Free; except // Log ('Error loading font.'); Result.Stream.Free; Result.Stream := nil; end; end; { TFontInfo } constructor TFontInfo.Create; begin Stream := nil; end; destructor TFontInfo.Destroy; begin if Assigned (Stream) then Stream.Free; inherited Destroy; end; initialization Fonts := TList.Create; finalization for i := 0 to Fonts.Count - 1 do TFontInfo (Fonts[i]).Free; Fonts.Free; end.
////////////////////////////////////////////////////////// // Desenvolvedor: Humberto Sales de Oliveira // // Email: humbertoliveira@hotmail.com // // humbertosales@midassistemas.com.br // // humberto_s_o@yahoo.com.br // // Objetivo: // // 1)Conectar software atraves da internet // // usando um servidor CGI - vide pasta "Servidor // // CGI" // // // // // // licensa: free // // // // *Auterações, modificações serão bem vindos // // Créditos: // // // ////////////////////////////////////////////////////////// unit ccon; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Conecta, jsonlib, codificacao, Dialogs, ComCtrls, fphttpclient, DB, BufDataset, memds, fpjson, strutils; Type { TStatus } TStatus = Class private Fstatus: String; procedure Setstatus(AValue: String); Published property status : String read Fstatus write Setstatus; end; { TMyQuery } TMyQuery = Class Private FParams :TParams; FSql : TStringList; Public FMemDataSet : TMemDataset; Constructor create; Destructor Destroy; Override; procedure open; procedure close; procedure clear; procedure insert; procedure post; procedure next; procedure prior; procedure last; procedure first; procedure enablecontrols; procedure disablecontrols; procedure GotoBookmark(const ABookmark: TBookmark); procedure FreeBookmark(ABookmark: TBookmark); function BookmarkValid(ABookmark: TBookmark): Boolean; function GetBookmark: TBookmark; function Fields : TFields; function DataSet : TDataSet; function IsEmpty : Boolean; Function Parambyname(Const AParamName : String) : TParam; Function Bookmark: TBookmark; protected Published property params : TParams read FParams Write Fparams; property Sql : TStringList read FSql Write FSql; property MemDataSet : TMemDataSet read FMemDataSet write FMemDataSet; end; { TCGI } TCGI = Class(TBaseConector) Private Fconectado : Boolean; FStatus: String; procedure SetStatus(AValue: String); Public Constructor create(Configuracao : TPathBanco); overload; Destructor destroy;override; Function CriarQuery : TBaseQuery; Override; procedure open; Override; procedure close; Override; published property Conectado : boolean read FConectado default false; property Status : String read FStatus write SetStatus; end; { TCQry } TCQry = Class(TBaseQuery) Private FQuery : TMyQuery; FDataSource : TDataSource; FStatus: String; procedure SetStatus(AValue: String); Public constructor create; destructor destroy; override; procedure open; override; procedure close; override; procedure execsql; override; procedure posicaocursor(DSet : TDataSet); procedure enviar(Js : TJSONStringType); procedure Reenviar(Js : TJSONStringType); Function dataset : TDataSet; override; function sql : TStringList; override; function Fields : TFields; override; function params : TParams; override; function processarsql(Sq : TStringList; parametros : TParams; Pacotes, Posicao : Integer) : TJSONStringType; function processarparametros(Parametros : TParams) : TJSONStringType; function parambyname(Const AparamName: String) : TParam; override; function isEmpty : Boolean; override; procedure CriarDataSource; override; Function DataSource : TDataSource; override; Published property Status : String read FStatus write SetStatus; end; Var Conf : TPathBanco; FStatusServer : TStatus; implementation { TStatus } procedure TStatus.Setstatus(AValue: String); begin if Fstatus=AValue then Exit; Fstatus:=AValue; end; { TCQry } procedure TCQry.SetStatus(AValue: String); begin if FStatus=AValue then Exit; FStatus:=AValue; FStatusServer.status := AValue; end; constructor TCQry.create; begin FQuery := TMyQuery.create; CriarDataSource; end; destructor TCQry.destroy; begin FreeAndNil(FDataSource); FreeAndNil(Fquery); inherited destroy; end; procedure TCQry.open; Var Js : TJSONStringType; begin Js := processarsql(FQuery.Sql,FQuery.params,strtoint(Conf.Pacotes),0); Js := ReplaceStr(Js,'\n',''); With FQuery do Begin DisableControls; close; MemDataSet.BeforeScroll:= Nil; Clear; Fields.Clear; Enviar( Js ); Open; First; EnableControls; MemDataSet.BeforeScroll:= @posicaocursor; end; end; procedure TCQry.close; begin FQuery.close; FQuery.Params.Clear; end; procedure TCQry.execsql; Var Js : TJSONStringType; begin Js := processarsql(FQuery.Sql,FQuery.Params,StrtoInt(Conf.Pacotes),0); Js := ReplaceStr(Js,'\n',''); FQuery.MemDataSet.BeforeScroll:= Nil; Enviar( Js ); end; procedure TCQry.posicaocursor(DSet: TDataSet); var Js : TJSONStringType; B : TBookMark; begin if DSet.RecNo = DSet.RecordCount then begin With FQuery do begin Js := processarsql(FQuery.Sql,FQuery.Params,strtoint(Conf.Pacotes),dSet.Recno); Try MemDataSet.BeforeScroll := Nil; DisableControls; B := GetBookmark; Reenviar( js ); finally if BookmarkValid(b) then GotoBookmark(b); FreeBookmark(B); EnableControls; MemDataSet.BeforeScroll:= @posicaocursor; end; end; end; end; procedure TCQry.enviar(Js: TJSONStringType); Var Resposta : TStrings; Json : TJSONObject; I : Byte; begin Try Json := TJSONObject.Create; Resposta := TStringList.create; Js := ReplaceStr(Js,'\n',''); Js := ReplaceStr(Js,'\r',''); With TFPHTTPClient.create(nil),Conf do Begin //Get(Conf.Banco + '/acao?query=' + EncodeURLElement(js), Resposta ); Get(Conf.Banco + ':' + Conf.porta + '/acao?query=' + EncodeURLElement(js), Resposta ); Free; end; if Resposta.text = '' then Status := 'Sem resposta do servidor!'; //Raise Exception.Create('Sem resposta do servidor!'); if AnsiContainsStr(LowerCase(Resposta.text) , '#msg' ) then begin Json := TJSONObject( GetJson(Resposta.text) ); Status := Json.Items[0].AsString; end Else Begin Json := TJSONObject( GetJson(Resposta.text) ); Jsonlib.JSONToDataset(TDataSet(FQuery.FMemDataSet),Json); end; finally freeAndNil(Json); FreeAndNil(Resposta); end; end; procedure TCQry.Reenviar(Js: TJSONStringType); var Resposta : TStrings; Json : TJSONObject; i : SmallInt; Buf : TBufDataSet; begin Try Json := TJSONObject.create; Resposta := TStringList.Create; With TFPHTTPClient.Create(nil),Conf do begin //Get( Conf.Banco + '/acao?query=' + EncodeURLElement(js), Resposta ); Get( Conf.Banco + ':' + Conf.porta +'/acao?query=' + EncodeURLElement(js) , Resposta ); free; end; if Resposta .text = '' then Status := 'Sem resposta do servidor!'; if AnsiContainsStr(LowerCase(Resposta.text) , '#msg' ) then begin Json := TJSONObject( GetJson(Resposta.text) ); Status := Json.Items[0].AsString; end Else Begin Buf := TBufDataSet.create(nil); Json := TJSONObject( GetJson(Resposta.text) ); jsonlib.JSONToDataset(TDataSet(Buf),Json); if Buf.IsEmpty = false then Try Buf.first; While not Buf.eof do begin FQuery.insert; For i := 0 to pred(Buf.FieldCount) do FQuery.Fields.Fields[i].value := Buf.Fields.Fields[i].Value; FQuery.post; Buf.next; end; finally Buf.free; end; end; finally Json.Free; Resposta.free; end; end; function TCQry.dataset: TDataSet; begin Result := FQuery.DataSet; end; function TCQry.sql: TStringList; begin Result := FQuery.Sql; end; function TCQry.Fields: TFields; begin Result := FQuery.Fields; end; function TCQry.params: TParams; begin Result := FQuery.Params; end; function TCQry.processarsql(Sq: TStringList; parametros: TParams; Pacotes, Posicao: Integer): TJSONStringType; var Jo : TJSONObject; Jdados : TJSONStringType; begin try Jo := TJSONObject.Create; Jo.Add('sql',Sq.Text); Jo.Add('pacotes',Pacotes); Jo.Add('posicao',Posicao); JDados := processarparametros(parametros); if JDados <> '{}' then Jo.Add('parametros',JDados); JDados := ReplaceStr(Jo.AsJson,'#10',''); JDados := ReplaceStr(JDados,'#13',''); JDados := ReplaceStr(JDados,'"{ \',' { '); JDados := ReplaceStr(JDados,'\"','"'); JDados := ReplaceStr(JDados,'}"','}'); Result := JDados; finally Jo.free; end; end; function TCQry.processarparametros(Parametros: TParams): TJSONStringType; Var Jo : TJSONObject; I : Integer; /////////////////////////// F : TMemoryStream; S : String; MyBuffer: Pointer; J : integer; begin Try Jo := TJSONObject.create; for i := 0 to Pred(Parametros.Count) do begin if Parametros.items[i].DataType = ftBlob then begin Try F := TMemoryStream.Create; J := Parametros.items[i].GetDataSize; MyBuffer:= GetMemory(J); Parametros.ParamByName(Parametros.items[i].name).getData(MyBuffer); F.Write(MyBuffer^,J); Encode64StringToStream(F,S); S := '#blob#' + Converte(S); parambyname( Parametros.items[i].Name ).AsString := S; finally FreeAndNil(F); Freemem(MyBuffer); end; end; Case GetJSONType(Parametros.Items[i].DataType) of 'null' : Jo.add(parametros.items[i].name,parametros.ParamByName(parametros.items[i].name).AsString); 'string' : Jo.add(parametros.items[i].name,parametros.items[i].asstring); 'boolean': Jo.add(parametros.items[i].name,parametros.items[i].asboolean); 'date' : Jo.add(parametros.items[i].name,parametros.items[i].asstring); 'float' : Jo.add(parametros.items[i].name,parametros.items[i].asfloat); 'int' : Jo.add(parametros.items[i].name,parametros.items[i].AsInteger); end; end; Result := JO.AsJSON; finally Jo.free; end; end; function TCQry.parambyname(const AparamName: String): TParam; begin Result := Fquery.ParamByName(AparamName); end; function TCQry.isEmpty: Boolean; begin Result := FQuery.IsEmpty; end; procedure TCQry.CriarDataSource; begin FDataSource := TDataSource.Create(Nil); DataSource.DataSet := FQuery.DataSet; end; function TCQry.DataSource: TDataSource; begin Result := FDataSource; end; { TCGI } procedure TCGI.SetStatus(AValue: String); begin if FStatus=AValue then Exit; FStatus:=AValue; FStatusServer.status := AValue; end; constructor TCGI.create(Configuracao: TPathBanco); Var Resp : TStrings; begin Conf := Configuracao; if Conf.Pacotes = '' then Conf.Pacotes := '10'; Try Resp := TStringList.create; With TFPHTTPClient.create(nil), Conf do begin //Get(Banco + '/online',Resp); Get(Conf.Banco + ':' + Conf.porta + '/online', Resp ); Free; end; if Trim(LowerCase(Resp.text)) = 'online' then FConectado := True Else begin FConectado := False; Raise Exception.Create('O Servidor não está conectado! Verifique as configurações do "PathBanco.txt" e tente novamente'); end; finally Resp.free; end; FStatusServer := TStatus.Create; end; destructor TCGI.destroy; begin end; function TCGI.CriarQuery: TBaseQuery; var Qry : TCQry; begin Qry := TCQry.create; Result := Qry; end; procedure TCGI.open; Var Resp : TStrings; begin if FConectado = False then begin Try Resp := TStringList.create; With TFPHTTPClient.create(nil), Conf do begin //Get(Banco + '/online',resp); Get(Conf.Banco + ':' + Conf.porta + '/online',resp); Free; end; if Trim(LowerCase(Resp.text)) = 'online' then FConectado := True Else FConectado := False; finally Resp.free; end; end; end; procedure TCGI.close; begin FConectado := False; end; { TMyQuery } function TMyQuery.GetBookmark: TBookmark; begin Result := FMemDataSet.Bookmark; end; constructor TMyQuery.create; begin FMemDataSet := TMemDataset.create(nil); FParams := TParams.create; FSql := TStringList.Create; end; destructor TMyQuery.Destroy; begin FreeAndNil(FMemDataSet); FreeAndNil(FParams); FreeAndNil(FSql); inherited Destroy; end; function TMyQuery.Parambyname(const AParamName: String): TParam; var Myparam : TParam; begin if FParams.FindParam(AparamName) = Nil then begin With TParam.create(fParams) do begin Name := AParamName; ParamType:= ptInput; Result := FParams.FindParam(AparamName); end; end Else Result := FParams.FindParam(AparamName); end; procedure TMyQuery.open; begin FMemDataSet.Open; end; procedure TMyQuery.close; begin FMemDataSet.Close; end; procedure TMyQuery.clear; begin FMemDataSet.Clear; end; function TMyQuery.BookmarkValid(ABookmark: TBookmark): Boolean; begin Result := FMemDataSet.BookmarkValid(ABookMark); end; procedure TMyQuery.GotoBookmark(const ABookmark: TBookmark); begin FMemDataSet.GotoBookmark(ABookMark); end; procedure TMyQuery.FreeBookmark(ABookmark: TBookmark); begin FMemDataSet.FreeBookmark(ABookMark); end; function TMyQuery.Bookmark: TBookmark; begin Result := FMemDataSet.Bookmark; end; function TMyQuery.Fields: TFields; begin Result := FMemDataSet.Fields; end; function TMyQuery.DataSet: TDataSet; begin Result := FMemDataSet end; function TMyQuery.IsEmpty: Boolean; begin Result := FMemDataSet.IsEmpty; end; procedure TMyQuery.insert; begin FMemDataSet.Insert; end; procedure TMyQuery.post; begin FMemDataSet.Post; end; procedure TMyQuery.next; begin FMemDataSet.next; end; procedure TMyQuery.prior; begin FMemDataSet.prior; end; procedure TMyQuery.last; begin FMemDataSet.last end; procedure TMyQuery.first; begin FMemDataSet.first; end; procedure TMyQuery.enablecontrols; begin FMemDataSet.EnableControls; end; procedure TMyQuery.disablecontrols; begin FMemDataSet.DisableControls; end; end.
unit gimpCurve; interface procedure dumpCurve(name: string; var red, green, blue : array of Double); implementation uses System.SysUtils; procedure writeCurveDesc(var f : TextFile; name : string); var I : Integer; begin WriteLn(f, '(time 0)'); Write (f, '(channel '); Write (f, name); WriteLn(f, ')'); WriteLn(f, '(curve'); WriteLn(f, ' (curve-type smooth)'); WriteLn(f, ' (n-points 17)'); Write (f, ' (points 34'); for I := 0 to 33 do begin Write(f, ' -1.0'); end; WriteLn(f, ')'); WriteLn(f, '(n-samples 256)'); Write (f, '(samples 256 '); end; procedure writeDummyChannel(var f : TextFile); var i : Integer; fl : String; begin for i := 0 to 255 do begin fl := FloatToStrF(i/255, TFloatFormat.ffFixed, 7, 6); Write (f, ' '); Write (f, fl); end; end; procedure writeChannel(var f : TextFile; var arr : array of Double); var i : Integer; fl : String; begin for i := 0 to 255 do begin fl := FloatToStrF(arr[i], TFloatFormat.ffFixed, 7, 6); Write (f, ' '); Write (f, fl); end; end; procedure dumpCurve(name: string; var red, green, blue : array of Double); var f : TextFile; i : Integer; begin AssignFile(f, name); rewrite(f); WriteLn(f, '# GIMP curves tool settings'); writeCurveDesc(f, 'value'); writeDummyChannel(f); WriteLn (f, '))'); writeCurveDesc(f, 'red'); writeChannel(f, red); WriteLn (f, '))'); writeCurveDesc(f, 'green'); writeChannel(f, green); WriteLn (f, '))'); writeCurveDesc(f, 'blue'); writeChannel(f, blue); WriteLn (f, '))'); CloseFile(f); end; //dumpCurve end.
program Alpine; uses crt; var Hours: Integer; CurHeight: Integer; health: Integer; name: String; Action_id: Integer; FoodPacks: Integer; procedure Init(); begin Hours := 0; CurHeight := 0; health := 100; Randomize; end; procedure Bear(); var Choice_Bear: Integer; begin writeln('You meet a bear'); writeln('Press 1 if you want to run away or 2 if you want to fight him'); readln(Choice_Bear); case Choice_Bear of 1: begin writeln('You are trying to ran away'); CurHeight := CurHeight + 50; Hours := Hours + 1; health := health - 10; end; 2: begin writeln('You are trying to hide'); writeln('The bear has not eaten you'); end; 3: begin writeln('You are trying to give food to bear'); writeln('The bear has not eaten you'); end; else writeln('Invalid input'); end; end; procedure Girl(); var Action_id: Integer; begin writeln('Press 1 if you want to chat with this girl, press 2 if you do not care'); readln(Action_id); case Action_id of 1: begin writeln('You spend a really good time together. Time flies quickly'); health:= health + 10; Hours:= Hours + 2; end; 2: begin writeln('You continue your journey. You regret your decision a bit'); health:= health - 10; end; else writeln('Okay'); end; end; procedure RandomEvent(); var Event_id: Integer; begin Event_id:= Random(6); case Event_id of 0: begin writeln('Everything is ok, you have made a progress today. '); writeln('You made 200 metres leap in 1 hour '); CurHeight := CurHeight + 200; Hours := Hours + 1; end; 1: begin writeln('You made a moderate progress today, it was really freezing'); writeln('You made 100 metres leap in 1 hour '); CurHeight := CurHeight + 100; Hours := Hours + 1; health := health - 10; end; 2: begin writeln('The bear attacked you'); writeln('You survived'); Bear(); end; 3: begin writeln('The bear attacked you'); writeln('You have not survived'); health := health - 100; end; 4: begin writeln('You have made a great progress'); writeln('You went for 300 metres'); CurHeight := CurHeight + 300; Hours := Hours + 1; end; 5: begin writeln('You meet a nice girl'); Girl(); end; end; end; procedure TreeDraw(level:Integer); var i: Integer; j: Integer; begin for i := 1 to level do begin for j := 1 to level - i do begin write(' '); end; for j := 1 to 2*i -1 do begin write('||'); end; writeln(); end; end; procedure Startscreen(); var i: Integer; begin writeln(' Hello, great journey lies ahead'); TreeDraw(8); for i := 0 to 9 do begin write('--') end; writeln('Press any key to continue'); readln(); writeln('Please input your name'); readln(name); end; procedure Action_choose(); begin writeln('Now you can choose a few actions'); writeln('Press 1 if you want to take a nap - health +20, time + 1'); writeln('Press 2 if you want to make an extra effot - health -20, time + 1, progress + 100m '); writeln('Press 3 if you want to do nothing'); readln(Action_id); case Action_id of 1: begin health:= health + 20; Hours:= Hours + 1; end; 2: begin health := health - 20; Hours := Hours + 1; CurHeight := CurHeight + 100; end; 3: begin writeln('Nice choice!'); end; end; end; begin writeln('debug line'); Init(); Startscreen(); writeln('You are currently at the start of your trip.'); while (Hours < 12) and (CurHeight < 800) and (health > 0) do begin RandomEvent(); writeln('You now have' ,(800 - CurHeight), 'metres to go, your health is ', health, ' and time is ', Hours, ' hours'); Action_choose(); end; if (CurHeight >= 800) then begin writeln('You have won'); writeln('\ /\ / _______ \\\ //'); writeln(' \ / \ / | | \\\\\ //'); writeln(' \/ \/ |_______| \\\ >// ' ); end else begin writeln('You have lost'); writeln(); writeln(' O'); writeln('/X\'); writeln('||'); end; readln(); end.
unit frmSimpleTaskDemo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TSimpleTaskForm = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var SimpleTaskForm: TSimpleTaskForm; implementation uses System.Diagnostics , uSlowCode , System.Threading ; {$R *.dfm} procedure TSimpleTaskForm.Button1Click(Sender: TObject); var Stopwatch: TStopWatch; Total: Integer; ElapsedSeconds: Double; begin Stopwatch := TStopwatch.StartNew; Total := PrimesBelow(200000); ElapsedSeconds := StopWatch.Elapsed.TotalSeconds; Memo1.Lines.Add(Format('There are %d primes under 200,000', [Total])); Memo1.Lines.Add(Format('It took %:2f seconds to calcluate that', [ElapsedSeconds])); end; procedure TSimpleTaskForm.Button2Click(Sender: TObject); begin TTask.Run(procedure var Stopwatch: TStopWatch; Total: Integer; ElapsedSeconds: Double; begin Stopwatch := TStopwatch.StartNew; Total := PrimesBelow(200000); ElapsedSeconds := StopWatch.Elapsed.TotalSeconds; TThread.Synchronize(TThread.Current, procedure begin Memo1.Lines.Add(Format('There are %d primes under 200,000', [Total])); Memo1.Lines.Add(Format('It took %:2f seconds to calcluate that', [ElapsedSeconds])); end); end ); end; end.
unit About; interface uses Windows, Messages, SysUtils, Controls, Forms, StdCtrls, Classes, ExtCtrls; type TdlgAbout = class(TForm) lblVersion: TLabel; lblName: TLabel; btnOk: TButton; memExplanation: TMemo; lblInfo: TLabel; Bevel1: TBevel; lblFileName: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnOkClick(Sender: TObject); private { Private 宣言 } public { Public 宣言 } procedure CreateParams(var Params: TCreateParams); override; end; var dlgAbout: TdlgAbout; OSVersionInfo: TOSVersionInfo; procedure ShowAbout(Name, FileName, Explanation: string); function GetFileVersionString(FileName: string; Long: Boolean): string; function GetFileVersion(FileName: string; var Mj, Mn, Rl, Bl: Cardinal): Boolean; implementation {$R *.DFM} // バージョン情報表示 procedure ShowAbout(Name, FileName, Explanation: string); begin if dlgAbout = nil then dlgAbout := TdlgAbout.Create(nil); dlgAbout.lblName.Caption := Name; dlgAbout.lblFileName.Caption := FileName; dlgAbout.lblVersion.Caption := GetFileVersionString(FileName, True); dlgAbout.memExplanation.Text := Explanation; dlgAbout.Show; end; // ファイルバージョン取得 function GetFileVersionString(FileName: string; Long: Boolean): string; var Work: Cardinal; VerInfo: Pointer; VerInfoSize: Cardinal; FileInfo: PVSFixedFileInfo; FileInfoSize: Cardinal; Mj, Mn, Rl, Bl: Cardinal; begin Result := ''; Work := 0; VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Work); if VerInfoSize <> 0 then begin GetMem(VerInfo, VerInfoSize); try if GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, VerInfo) then begin if VerQueryValue(VerInfo, '\', Pointer(FileInfo), FileInfoSize) then begin Mj := HiWord(FileInfo^.dwProductVersionMS); Mn := LoWord(FileInfo^.dwProductVersionMS); Rl := HiWord(FileInfo^.dwProductVersionLS); Bl := LoWord(FileInfo^.dwProductVersionLS); if Long then Result := Format('%d.%d.%d Build %d', [Mj, Mn, Rl, Bl]) else Result := Format('%d.%d.%d.%d', [Mj, Mn, Rl, Bl]); if (FileInfo^.dwFileFlags and VS_FF_PRERELEASE) <> 0 then Result := Result + ' Prerelease'; end; end; finally FreeMem(VerInfo); end; end; end; function GetFileVersion(FileName: string; var Mj, Mn, Rl, Bl: Cardinal): Boolean; var Work: Cardinal; VerInfo: Pointer; VerInfoSize: Cardinal; FileInfo: PVSFixedFileInfo; FileInfoSize: Cardinal; begin Result := False; Work := 0; VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Work); if VerInfoSize <> 0 then begin GetMem(VerInfo, VerInfoSize); try if GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, VerInfo) then begin if VerQueryValue(VerInfo, '\', Pointer(FileInfo), FileInfoSize) then begin Mj := HiWord(FileInfo^.dwProductVersionMS); Mn := LoWord(FileInfo^.dwProductVersionMS); Rl := HiWord(FileInfo^.dwProductVersionLS); Bl := LoWord(FileInfo^.dwProductVersionLS); Result := True; end; end; finally FreeMem(VerInfo); end; end; end; // CreateParams procedure TdlgAbout.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := GetDesktopWindow; end; // フォームはじめ procedure TdlgAbout.FormCreate(Sender: TObject); begin SetClassLong(Handle, GCL_HICON, Application.Icon.Handle); end; // フォーム終わり procedure TdlgAbout.FormDestroy(Sender: TObject); begin dlgAbout := nil; end; // 閉じる procedure TdlgAbout.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; // OKボタン procedure TdlgAbout.btnOkClick(Sender: TObject); begin Close; end; initialization OSVersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(OSVersionInfo); end.
program inventarioSuper; const cantMaxima = 200; type subRango = 1..200; var codigo:subRango; codmin1, codmin2: subRango; min1, min2: real; precio:real; //Var para punto b cantProd: Integer; //Var para punto c totalPrecio: real; begin min1:= 9999; min2:= 9999; cantProd:= 0; totalPrecio:= 0; for(i:=1 to cantMaxima) do begin read(codigo); read(precio); if(precio<min1) then begin min2:= min1; codmin2:=codmin1; min1:=precio; codmin1:=codigo; end else if(precio<min2)then begin min2:= precio; codmin2:=codigo; end; //Cant de prods de mas de $16 con codigo par if(precio>16) and (codigo MOD 2=0) then cantProd:= cantProd+1; //Precio promedio totalPrecio:= totalPrecio + precio; end; //Informar //Punto a WriteLn('Los codigos de los productos mas baratos son:',codmin1, codmin2); //Colocar fuera del For //Punto b WriteLn('La cantidad de productos con precio mayor a $16 es:', cantProd); //Punto c WriteLn('Elprecio promedio es:'totalPrecio/cantMaxima); end; end.
unit PASVirtualDBScrollBase; { VirtualDBScroll Package The MIT License (MIT) Copyright (c) 2014 Jack D Linke 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. } {$mode objfpc}{$H+} {$DEFINE dbgDBScroll} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, PASEmbeddedMemo, PASEmbeddedScrollBar, db, PropEdits, PASFormatEditor, PASEmbeddedPanel, PASDataLink {$ifdef dbgDBScroll}, LazLogger{$endif}, PASVirtualDBScrollUtilities; type { TOperationMode } TOperationMode = (Standard, SmallDataSet, Disconnected); // Standard : The default behavior for scrolling through large DataSets // SmallDataSet: Can be selected when scrolling through a small DataSet (smoother operation) // Disconnected : Allows the programmer to specify the content of the memo (disconnecting from DataSet content) // Hides the Embedded Scrollbar, sets Memo Scrollbar to ssAutoBoth { TPASVirtualDBScrollBase } TPASVirtualDBScrollBase = class(TCustomPanel) private { Private declarations } FScrollBar : TPASEmbeddedScrollBar; FPopupInfo : TPASEmbeddedPanel; FDataLink : TPASDataLink; FCurrentDBName : String; // Stores the current DB Name. This way we can determine if the database has changed FCountingRecords : Boolean; // While performing a RecordCount, this will be set to True FFormat : TStrings; // The format for displaying content FError : String; // FOperationMode : TOperationMode; // Event Handlers procedure OnRecordChanged(Field : TField); procedure OnDataSetChanged(ADataSet : TDataSet); procedure OnDataSetOpen(ADataSet : TDataSet); procedure OnDataSetOpening(ADataSet : TDataSet); procedure OnDataSetClose(ADataSet : TDataSet); procedure OnNewDataSet(ADataSet : TDataSet); procedure OnInvalidDataset(ADataSet : TDataSet); procedure OnInvalidDataSource(ADataSet : TDataSet); procedure OnDataSetScrolled(ADataSet : TDataSet; Distance : Integer); procedure OnLayoutChanged(ADataSet : TDataSet); procedure OnEditingChanged(ADataSet : TDataSet); procedure OnUpdateData(ADataSet : TDataSet); procedure OnDataSetBrowse(ADataSet : TDataSet); procedure OnActiveChanged(ADataSet : TDataSet); procedure EScrollBarOnChange(Sender : TObject); procedure EScrollBarOnScroll(Sender : TObject; ScrollCode : TScrollCode; var ScrollPos : Integer); procedure InitializeWithData; procedure SetFormat(const AValue: TStrings); procedure DoFormatChange(Sender: TObject); protected { Protected declarations } FRecordSliceSize : Integer; // The maximum number of records per record Slice FLineResolution : Integer; // The number of lines positions on the scrollbar allocated to each record FRecordCount : Integer; // Total number of records in the DataSet FRecordSliceCount : Integer; // Number of record Slices in the DataSet FRecordSliceLineCounts : Array of Integer; // Keeps track of the number of lines displayed per Slice FCurrentRecordSlice : Integer; // Tracks which Slice is currently at the center of display public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Paint; override; published { Published declarations } function GetSliceSize : Integer; function GetDataSource : TDataSource; procedure SetSliceSize(const Value : Integer); procedure SetDataSource(Value : TDataSource); procedure SetOperationMode(AValue: TOperationMode); procedure GetRecordCount; procedure CalculateLineResolution; procedure CalculateScrollBarMax; procedure CalculateRecordSliceCount; // Actually calculates both FRecordSliceCount and the length of array FRecordSliceLineCounts property EScrollBar : TPASEmbeddedScrollBar read FScrollBar; property EPopupInfo : TPASEmbeddedPanel read FPopupInfo; property RecordSliceSize : Integer read GetSliceSize write SetSliceSize default 50; // Used to set the number of records per Slice. Allowable range is 1 to 500 property DataLink : TPASDataLink read FDataLink write FDataLink; property DataSource : TDataSource read GetDataSource write SetDataSource; // Used to access the DataLink. The DataLink property of the DataSource must be set for this component to operate property LineResolution : Integer read FLineResolution; // The number of positions on the scrollbar allocated per record. This property is automatically calculated based upon the number of Records in the DataSet property RecordCount : Integer read FRecordCount; // The number of records in the dataset. For instance, if the DataSet is an SQLQuery, this value is the number of records returned from a query. This property is automatically calculated when the dataset is opened. {The Format property allows the programmer to determine how records will be displayed within the component} property Format : TStrings read FFormat write SetFormat; property OperationMode: TOperationMode read FOperationMode write SetOperationMode default Standard; property Align; property Anchors; property AutoSize; property BevelInner; property BevelOuter; property BevelWidth; property BorderStyle; property BorderWidth; property Caption; property Color; property Enabled; property Height; property Left; property Name; property TabOrder; property TabStop; property Tag; property Top; property UseDockManager; property Visible; property Width; end; { TPASOperationModePropertyEditor } TPASOperationModePropertyEditor = class(TEnumPropertyEditor) public procedure GetValues(Proc: TGetStrProc); override; end; procedure Register; var FFieldValues: TStringList; implementation procedure Register; begin RegisterPropertyEditor(TypeInfo(TStrings), TPASVirtualDBScrollBase, 'Format', TPASFormatEditor); RegisterPropertyEditor(TypeInfo(TOperationMode), TPASVirtualDBScrollBase, 'OperationMode', TPASOperationModePropertyEditor); end; { TPASOperationModePropertyEditor } procedure TPASOperationModePropertyEditor.GetValues(Proc: TGetStrProc); type TRestricted = 1..3; TRestrictedNames = array[TRestricted] of ShortString; const RestrictedStyleNames: TRestrictedNames = ('Standard', 'SmallDataSet', 'Disconnected'); var i: TRestricted; begin for i := Low(TRestricted) to High(TRestricted) do Proc(RestrictedStyleNames[i]); end; function TPASVirtualDBScrollBase.GetSliceSize: Integer; begin Result := FRecordSliceSize; end; function TPASVirtualDBScrollBase.GetDataSource: TDataSource; begin result := FDataLink.DataSource; end; procedure TPASVirtualDBScrollBase.SetSliceSize(const Value: Integer); begin if Value < 1 then begin FRecordSliceSize := 1; end else if Value > 500 then begin FRecordSliceSize := 500; end else begin FRecordSliceSize := Value; end; end; procedure TPASVirtualDBScrollBase.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; end; procedure TPASVirtualDBScrollBase.GetRecordCount; begin {$ifdef dbgDBScroll} DebugLnEnter(ClassName,'(inherited).GetRecordCount INIT'); {$endif} // Set this to true to that we're not trying to perform work on the dataset for every OnDataSetChange this creates FCountingRecords := True; DataLink.DataSet.Last; // Need to move to the last record in the dataset in order to get an accurate count FRecordCount := DataLink.DataSet.RecordCount; DataLink.DataSet.First; // Move back to the front // All done FCountingRecords := False; {$ifdef dbgDBScroll} DebugLnExit(ClassName,'(inherited).GetRecordCount DONE RecordCount=', IntToStr(FRecordCount)); {$endif} end; procedure TPASVirtualDBScrollBase.CalculateLineResolution; begin {$ifdef dbgDBScroll} DebugLnEnter(ClassName,'(inherited).CalculateLineResolution INIT'); {$endif} { Based on the number of records in the DataSet, we set the resolution per record. If there are less than 8,389 records, for instance, we allot up to 256,000 positions on the scrollbar per record. In this case, as long as there are less than 256,000 lines in the record, we can scroll smoothly through every line. There should only be a problem when there are millions of records which are very long (several hundred lines each). } if RecordCount < 1 then begin FLineResolution := 1; end else if (RecordCount > 0) and (RecordCount < 8389) then begin FLineResolution := 256000; end else if (RecordCount > 8388) and (RecordCount < 16778) then begin FLineResolution := 128000; end else if (RecordCount > 16777) and (RecordCount < 33555) then begin FLineResolution := 64000; end else if (RecordCount > 33554) and (RecordCount < 67109) then begin FLineResolution := 32000; end else if (RecordCount > 67108) and (RecordCount < 134218) then begin FLineResolution := 16000; end else if (RecordCount > 134217) and (RecordCount < 268436) then begin FLineResolution := 8000; end else if (RecordCount > 268435) and (RecordCount < 536871) then begin FLineResolution := 4000; end else if (RecordCount > 536870) and (RecordCount < 1073742) then begin FLineResolution := 2000; end else if (RecordCount > 1073741) and (RecordCount < 2147484) then begin FLineResolution := 1000; end else if (RecordCount > 2147483) and (RecordCount < 4294968) then begin FLineResolution := 500; end else if (RecordCount > 4294967) and (RecordCount < 8589934) then begin FLineResolution := 250; end; {$ifdef dbgDBScroll} DebugLnExit(ClassName,'(inherited).CalculateLineResolution DONE RecordCount=',IntToStr(RecordCount), ' FLineResolution=',IntToStr(FLineResolution)); {$endif} end; procedure TPASVirtualDBScrollBase.CalculateScrollBarMax; begin {$ifdef dbgDBScroll} DebugLnEnter(ClassName,'(inherited).CalculateScrollBarMax INIT'); {$endif} EScrollBar.Max := RecordCount * LineResolution; {$ifdef dbgDBScroll} DebugLnExit(ClassName,'(inherited).CalculateScrollBarMax DONE EScrollBar.Max=',IntToStr(EScrollBar.Max)); {$endif} end; // Count the number of Slices required based on RecordCount and RecordSliceSize procedure TPASVirtualDBScrollBase.CalculateRecordSliceCount; begin {$ifdef dbgDBScroll} DebugLnEnter(ClassName,'(inherited).CalculateRecordSliceCount INIT'); {$endif} // If the record count divides into the Slice size, getting the Slice count is easy if FRecordCount mod FRecordSliceSize = 0 then begin FRecordSliceCount := FRecordCount div FRecordSliceSize; SetLength(FRecordSliceLineCounts, FRecordCount div FRecordSliceSize); end // Otherwise we need to add one more Slice else begin FRecordSliceCount := (FRecordCount div FRecordSliceSize) + 1; SetLength(FRecordSliceLineCounts, (FRecordCount div FRecordSliceSize) + 1); end; {$ifdef dbgDBScroll} DebugLnExit(ClassName,'(inherited).CalculateRecordSliceCount DONE Length(FRecordSliceLineCounts)=',IntToStr(Length(FRecordSliceLineCounts))); {$endif} end; procedure TPASVirtualDBScrollBase.OnRecordChanged(Field: TField); begin ShowMessage('OnRecordChanged'); end; procedure TPASVirtualDBScrollBase.OnDataSetChanged(ADataSet: TDataSet); begin //ShowMessage('OnDataSetChanged'); {if ADataSet.State = dsBrowse then begin ShowMessage('dsBrowse'); end else if ADataSet.State = dsInactive then begin ShowMessage('dsInactive'); end;} // Every time we move positions within the DataSet // ShowMessage('OnDataSetChanged'); DataLink.DataSet.FieldCount; end; procedure TPASVirtualDBScrollBase.OnDataSetOpen(ADataSet: TDataSet); begin // Called every time the DataSet is Opened (Except when a *New* DataSet is Opened) // Every time this fires we need to get the record count and perform our calculations ShowMessage('OnDataSetOpen'); InitializeWithData; end; procedure TPASVirtualDBScrollBase.OnDataSetOpening(ADataSet: TDataSet); begin ShowMessage('OnDataSetOpening!'); end; procedure TPASVirtualDBScrollBase.OnDataSetClose(ADataSet: TDataSet); var i : Integer; begin // Clear all old values/set back to default FCountingRecords := False; FLineResolution := 1; FRecordCount := 0; FRecordSliceCount := 0; FCurrentRecordSlice := 0; FCurrentDBName := ''; for i := Low(FRecordSliceLineCounts) to High(FRecordSliceLineCounts) do begin FRecordSliceLineCounts[i] := 0; end; SetLength(FRecordSliceLineCounts, 0); ShowMessage('OnDataSetClose'); end; procedure TPASVirtualDBScrollBase.OnNewDataSet(ADataSet: TDataSet); begin // Called only when a *New* DataSet is Opened // Every time this fires we need to get the record count and perform our calculations ShowMessage('OnNewDataSet'); InitializeWithData; end; procedure TPASVirtualDBScrollBase.OnInvalidDataset(ADataSet: TDataSet); begin // Return an error end; procedure TPASVirtualDBScrollBase.OnInvalidDataSource(ADataSet: TDataSet); begin // Return an error end; procedure TPASVirtualDBScrollBase.OnDataSetScrolled(ADataSet: TDataSet; Distance: Integer); begin ShowMessage('OnDataSetScrolled'); end; procedure TPASVirtualDBScrollBase.OnLayoutChanged(ADataSet: TDataSet); begin ShowMessage('OnDataSetLayoutChanged'); end; procedure TPASVirtualDBScrollBase.OnEditingChanged(ADataSet: TDataSet); begin end; procedure TPASVirtualDBScrollBase.OnUpdateData(ADataSet: TDataSet); begin end; procedure TPASVirtualDBScrollBase.OnDataSetBrowse(ADataSet: TDataSet); begin if not FCountingRecords then begin ShowMessage('OnDataSetBrowse'); end; end; procedure TPASVirtualDBScrollBase.OnActiveChanged(ADataSet: TDataSet); begin if ADataSet.Active then begin ShowMessage('OnActiveChanged'); end; end; procedure TPASVirtualDBScrollBase.EScrollBarOnChange(Sender: TObject); begin end; procedure TPASVirtualDBScrollBase.EScrollBarOnScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer); begin end; procedure TPASVirtualDBScrollBase.InitializeWithData; begin {$ifdef dbgDBScroll} DebugLn(ClassName,'(inherited).InitializeWithData'); {$endif} GetRecordCount; CalculateLineResolution; CalculateScrollBarMax; end; procedure TPASVirtualDBScrollBase.SetFormat(const AValue: TStrings); begin FFormat.Assign(AValue); end; procedure TPASVirtualDBScrollBase.SetOperationMode(AValue: TOperationMode); begin if AValue in [SmallDataSet, Disconnected] then begin FOperationMode := AValue; end else begin FOperationMode := Standard; end; end; constructor TPASVirtualDBScrollBase.Create(AOwner: TComponent); begin {$ifdef dbgDBScroll} DebugLnEnter('>> ',ClassName,'(inherited).Create INIT'); {$endif} inherited Create(AOwner); // Set default component size and values with GetControlClassDefaultSize do begin SetInitialBounds(0, 0, CX, CY); end; Height := 50; Caption := ''; FCurrentDBName := ''; // Initialize the Embedded ScrollBar FScrollBar := TPASEmbeddedScrollBar.Create(Self); // Add the embedded memo FScrollBar.Parent := Self; // Show the memo in the panel FScrollBar.SetSubComponent(True); // Tell the IDE to store the modified properties FScrollBar.Name := 'EScrollBar'; FScrollBar.ControlStyle := FScrollBar.ControlStyle - [csNoDesignSelectable]; // Make sure it can not be selected/deleted within the IDE FScrollBar.Width := 15; FScrollBar.Align := alRight; FScrollBar.Kind := sbVertical; FScrollBar.OnChange := @EScrollBarOnChange; FScrollBar.OnScroll := @EScrollBarOnScroll; // Initialize the Embedded Label FPopupInfo := TPASEmbeddedPanel.Create(Self); FPopupInfo.Parent := Self; FPopupInfo.SetSubComponent(True); FPopupInfo.Name := 'EPopupInfo'; FPopupInfo.ControlStyle := FPopupInfo.ControlStyle - [csNoDesignSelectable]; FPopupInfo.IsDisplayed := True; FPopupInfo.Width := 50; FPopupInfo.Height := 24; FPopupInfo.Caption := '0'; FPopupInfo.Left := 0; //Mouse.CursorPos.x; FPopupInfo.Top := 0; //Mouse.CursorPos.y; FPopupInfo.BringToFront; // Initialize the Dataset FDataLink := TPASDataLink.Create; FDataLink.OnRecordChanged := @OnRecordChanged; FDataLink.OnDatasetChanged := @OnDataSetChanged; FDataLink.OnDataSetOpen := @OnDataSetOpen; FDataLink.OnDataSetOpening := @OnDataSetOpening; FDataLink.OnDataSetClose := @OnDataSetClose; FDataLink.OnNewDataSet := @OnNewDataSet; FDataLink.OnInvalidDataSet := @OnInvalidDataset; FDataLink.OnInvalidDataSource := @OnInvalidDataSource; FDataLink.OnDataSetScrolled := @OnDataSetScrolled; FDataLink.OnLayoutChanged := @OnLayoutChanged; FDataLink.OnEditingChanged := @OnEditingChanged; FDataLink.OnUpdateData := @OnUpdateData; FDataLink.OnDataSetBrowse := @OnDataSetBrowse; FDataLink.OnActiveChanged := @OnActiveChanged; FDataLink.VisualControl := True; // Initialize the Format property FFormat := TStringList.Create; TStringList(FFormat).OnChange := @DoFormatChange; // Only true when we're in the midst of performing a RecordCount FCountingRecords := False; // Initially set the Slice size to 50 FRecordSliceSize := 50; // Set Format property default value (blank) //FFormat := ''; FFieldValues := TStringList.Create; {$ifdef dbgDBScroll} DebugLnExit(ClassName,'(inherited).Create DONE'); {$endif} end; destructor TPASVirtualDBScrollBase.Destroy; begin {$ifdef dbgDBScroll} DebugLn('<< ',ClassName,'(inherited).Destroy'); {$endif} FDataLink.Free; FDataLink := Nil; FPopupInfo.Free; FPopupInfo := Nil; FScrollBar.Free; FScrollBar := Nil; FFormat.Free; FFormat := Nil; FFieldValues.Free; FFormat := Nil; inherited Destroy; end; procedure TPASVirtualDBScrollBase.Paint; begin inherited Paint; //inherited Canvas.Rectangle(0,0,self.Width,self.Height); end; procedure TPASVirtualDBScrollBase.DoFormatChange(Sender: TObject); begin Changed; end; end.
{------------------------------------------------------------------------------ Component Installer app Developed by Rodrigo Depine Dalpiaz (digao dalpiaz) Delphi utility app to auto-install component packages into IDE https://github.com/digao-dalpiaz/CompInstall Please, read the documentation at GitHub link. ------------------------------------------------------------------------------} unit UFrm; interface uses Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, Vcl.Controls, System.Classes, // Vcl.Graphics, UDefinitions; type TFrm = class(TForm) LbComponentName: TLabel; EdCompName: TEdit; LbDelphiVersion: TLabel; EdDV: TComboBox; Ck64bit: TCheckBox; LbInstallLog: TLabel; BtnInstall: TBitBtn; BtnExit: TBitBtn; M: TRichEdit; LbVersion: TLabel; LinkLabel1: TLinkLabel; LbComponentVersion: TLabel; EdCompVersion: TEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnExitClick(Sender: TObject); procedure BtnInstallClick(Sender: TObject); procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); procedure FormShow(Sender: TObject); private D: TDefinitions; DefLoaded: Boolean; public procedure LoadDefinitions; procedure SetButtons(bEnabled: Boolean); procedure Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); end; var Frm: TFrm; implementation {$R *.dfm} uses System.SysUtils, Vcl.Dialogs, System.UITypes, Winapi.Windows, Winapi.Messages, Winapi.ShellAPI, UCommon, UProcess, UGitHub, UDelphiVersionCombo; procedure TFrm.Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack); begin //log text at RichEdit control, with some formatted rules M.SelStart := Length(M.Text); if bBold then M.SelAttributes.Style := [fsBold] else M.SelAttributes.Style := []; M.SelAttributes.Color := Color; M.SelText := A+#13#10; SendMessage(M.Handle, WM_VSCROLL, SB_BOTTOM, 0); //scroll to bottom end; procedure TFrm.LoadDefinitions; begin if Assigned(D) then D.Free; DefLoaded := False; D := TDefinitions.Create; try D.LoadIniFile(AppDir+'CompInstall.ini'); EdCompName.Text := D.CompName; EdCompVersion.Text := D.CompVersion; TDelphiVersionComboLoader.Load(EdDV, D.DelphiVersions); Ck64bit.Visible := D.HasAny64bit; DefLoaded := True; except on E: Exception do Log('Error loading component definitions: '+E.Message, True, clRed); end; end; procedure TFrm.FormCreate(Sender: TObject); begin ReportMemoryLeaksOnShutdown := True; AppDir := ExtractFilePath(Application.ExeName); LoadDefinitions; end; procedure TFrm.FormDestroy(Sender: TObject); begin D.Free; TDelphiVersionComboLoader.Clear(EdDV); end; procedure TFrm.FormShow(Sender: TObject); begin if DefLoaded then CheckGitHubUpdate(D.GitHubRepository, D.CompVersion); end; procedure TFrm.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin ShellExecute(0, '', PChar(Link), '', '', SW_SHOWNORMAL); end; procedure TFrm.BtnExitClick(Sender: TObject); begin Close; end; procedure TFrm.BtnInstallClick(Sender: TObject); var P: TProcess; begin if not DefLoaded then raise Exception.Create('Component definitions are not loaded'); M.Clear; //clear log if EdDV.ItemIndex=-1 then begin MessageDlg('Select one Delphi version', mtError, [mbOK], 0); EdDV.SetFocus; Exit; end; //check if Delphi IDE is running if FindWindow('TAppBuilder', nil)<>0 then begin MessageDlg('Please, close Delphi IDE first!', mtError, [mbOK], 0); Exit; end; SetButtons(False); Refresh; P := TProcess.Create(D, TDelphiVersionItem(EdDV.Items.Objects[EdDV.ItemIndex]).InternalNumber, Ck64bit.Checked and Ck64bit.Visible); P.Start; end; procedure TFrm.SetButtons(bEnabled: Boolean); begin BtnInstall.Enabled := bEnabled; BtnExit.Enabled := bEnabled; end; end.
program test_refractive_indices; {$APPTYPE CONSOLE} {$IFDEF FPC} {$linklib libxrl} {$ENDIF} {$mode objfpc} {$h+} uses xraylib, xrltest, Classes, SysUtils, fpcunit, testreport, testregistry; type TestRefractiveIndices = class(TTestCase) private procedure _test_bad_input_0; procedure _test_bad_input_1; procedure _test_bad_input_2; procedure _test_bad_input_3; procedure _test_bad_input_4; procedure _test_bad_input_5; procedure _test_bad_input_6; procedure _test_bad_input_7; procedure _test_bad_input_8; published procedure test_chemical_formulas; procedure test_nist_compounds; procedure test_bad_input; end; procedure TestRefractiveIndices.test_chemical_formulas; var cmplx: xrlComplex; begin AssertEquals(Refractive_Index_Re('H2O', 1.0, 1.0), 0.999763450676632, 1.0e-9); AssertEquals(Refractive_Index_Im('H2O', 1.0, 1.0), 4.021660592312145e-05, 1.0e-9); cmplx := Refractive_Index('H2O', 1.0, 1.0); AssertEquals(cmplx.re, 0.999763450676632, 1.0e-9); AssertEquals(cmplx.im, 4.021660592312145e-05, 1.0e-9); end; procedure TestRefractiveIndices.test_nist_compounds; var cmplx: xrlComplex; begin AssertEquals(Refractive_Index_Re('Air, Dry (near sea level)', 1.0, 1.0), 0.999782559048, 1.0E-12); AssertEquals(Refractive_Index_Im('Air, Dry (near sea level)', 1.0, 1.0), 0.000035578193, 1.0E-12); cmplx := Refractive_Index('Air, Dry (near sea level)', 1.0, 1.0); AssertEquals(cmplx.re, 0.999782559048, 1.0E-12); AssertEquals(cmplx.im, 0.000035578193, 1.0E-12); AssertEquals(Refractive_Index_Re('Air, Dry (near sea level)', 1.0, 0.0), 0.999999737984, 1.0E-12); AssertEquals(Refractive_Index_Im('Air, Dry (near sea level)', 1.0, 0.0), 0.000000042872, 1.0E-12); cmplx := Refractive_Index('Air, Dry (near sea level)', 1.0, 0.0); AssertEquals(cmplx.re, 0.999999737984, 1.0E-12); AssertEquals(cmplx.im, 0.000000042872, 1.0E-12); cmplx := Refractive_Index('Air, Dry (near sea level)', 1.0, -1.0); AssertEquals(cmplx.re, 0.999999737984, 1.0E-12); AssertEquals(cmplx.im, 0.000000042872, 1.0E-12); end; procedure TestRefractiveIndices.test_bad_input; begin AssertException(EArgumentException, @_test_bad_input_0); AssertException(EArgumentException, @_test_bad_input_1); AssertException(EArgumentException, @_test_bad_input_2); AssertException(EArgumentException, @_test_bad_input_3); AssertException(EArgumentException, @_test_bad_input_4); AssertException(EArgumentException, @_test_bad_input_5); AssertException(EArgumentException, @_test_bad_input_6); AssertException(EArgumentException, @_test_bad_input_7); AssertException(EArgumentException, @_test_bad_input_8); end; procedure TestRefractiveIndices._test_bad_input_0; begin Refractive_Index_Re('', 1.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_1; begin Refractive_Index_Im('', 1.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_2; begin Refractive_Index('', 1.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_3; begin Refractive_Index_Re('H2O', 0.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_4; begin Refractive_Index_Im('H2O', 0.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_5; begin Refractive_Index('H2O', 0.0, 1.0); end; procedure TestRefractiveIndices._test_bad_input_6; begin Refractive_Index_Re('H2O', 1.0, 0.0); end; procedure TestRefractiveIndices._test_bad_input_7; begin Refractive_Index_Im('H2O', 1.0, 0.0); end; procedure TestRefractiveIndices._test_bad_input_8; begin Refractive_Index('H2O', 1.0, 0.0); end; var App: TestRunner; begin RegisterTest(TestRefractiveIndices); App := TestRunner.Create(nil); App.Initialize; App.Run; App.Free; end.
unit MedModelConst; interface type THL7SegmentType = (hlsNone, hlsMSH, hlsPID, hlsOBR, hlsOBX); TMSHElement = (msheSegnentName, msheEncodingCharacters, msheSendingApp, msheSendingFacility, msheReceivingApp, msheReceivingFacility, msheDateTimeMsg, msheSecurity, msheMessageType, msheMessageControlID, msheProcessingID, msheVersionID, msheSequenceNumber, msheContinuationPointer, msheAcceptAcknowledgmentType, msheApplicationAcknowledgmentType, msheCountryCode, msheCharacterSet, mshePrincipalLangMsg, msheAltCharacterSetHandlingScheme, msheMsgProfileId, msheSendResponsibleOrg, msheReceivResponsibleOrg, msheSendNetworkAddress, msheReceivNetworkAddress); TPIDElement = (pideSegmentName, pidePatientID, pidePatientIDExt, pidePatientIDInt, pidePatientIDAlt, pidePatientName, pideMothMaidenName, pideDateBirth, pideSex, pidePatientAlias, pideRace, pidePatientAddress, pideCountyCode, pidePhoneNumberHome, pidePhoneNumberBusiness, pidePrimaryLanguage, pideMaritalStatus, pideReligion, pidePatientAccountNumber, pideSSNNumber, pideDriverLicenseNumber, pideMothersIdentifie, pideEthnicGroup, pideBirthPlace, pideMultipleBirthIndicator, pideBirthOrder, pideCitizenship, pideVeteransMilitaryStatus, pideNationality, pidePatientDeathDateTime, pidePatientDeathIndicator, pideIdentityUnknownIndicator, pideIdentityReliabilityCode, pideLastUpdateDateTime, pideLastUpdateFacility, pideSpeciesCode, pideBreedCode, pideStrain, pideProductionClassCode, pideTribalCitizenshi); TOBRElement = (obreSegnentName, obrePlacerOrderNumber, obreFillerOrderNumber, obreUniversalServiceID, obrePriority, obreRequestedDateTime, obreObservationDateTime, obreObservationEndDateTime, obreCollectionVolume, obreCollectorIdentifier, obreSpecimenActionCode, obreDangerCode, obreRelevantClinicalInfo, obreSpecimenReceivedDateTime, obreSpecimenSource, obreOrderingProvider, obreOrderCallbackPhoneNumber, obrePlacerField1, obrePlacerField2, obreFillerField1, obreFillerField2, obreResultsRptStatusChngDateTime, obreChargeToPractice, obreDiagnosticServSectID, obreResultStatus, obreParentResult, obreQuantityOrTiming, obreResultCopiesTo, obreParent, obreTransportationMode, obreReasonForStudy, obrePrincipalResultInterpreter, obreAssistantResultInterpreter, obreTechnician, obreTranscriptionist, obreScheduledDateTime, obreNumberOfSampleContainers, obreTransportLogisticsOfCollectedSample, obreCollectorsComment, obreTransportArrangementResponsibility, obreTransportArranged, obreEscortRequired, obrePlannedPatientTransportComment); TOBXElement = (obxeSegnentName, obxeOBXNumber, obxeValueType, obxeObservationIdentifier, obxeObservationSubID, obxeObservationValue, obxeUnits, obxeReferencesRange, obxeAbnormalFlags, obxeProbability, obxeNatureOfAbnormalTest, obxeObservResultStatus, obxeDateLastObsNormalValues, obxeUserDefinedAccessChecks, obxeDateTimeOfObservation, obxeProducersID, obxeResponsibleObserver, obxeObservationMethod); //SubElements TPatientSubName = (psnSurname, psnFirstName, psnInitials); TPatientSubAddress = (psaAddress1, psaAddress2, psaCity, psaProvinceCode, psaPostalCode, psaSEERCountryGeocode); TAccessionFillerNumber = (afnEntityId, afnNamespaceId, afnUniversalId, afnUniversalIdType); TSpecimenSubSource = (sssName, sssAdditives, sssFreeText, sssBodySite, sssSiteModifier, sssCollectionMethodModifier); TSpecimenSubObservationIdent = (ssoIdentifierST, ssoTextST, ssoNameCodingSys, ssoAltIdentifierST, ssoAltTextST, ssoAltNameCodingSys); const HL7_SEPARATOR = '|'; HL7_SEPARATOR_COMPONENT = '^'; HL7_SRV_ADDRESS = 'localhost'; HL7_PORT = 20032; HL7_SGM_NONE = ''; HL7_SGM_MSH = 'MSH'; HL7_SGM_PID = 'PID'; HL7_SGM_OBR = 'OBR'; HL7_SGM_OBX = 'OBX'; OBX_TEXT_ST_SPEC_LABEL = 'Path report.site of origin'; OBX_TEXT_ST_GROSS_DESC = 'Path report.gross description'; OBX_TEXT_ST_MICROSCOPIC_OBSERV = 'Path report.microscopic observation'; OBX_TEXT_ST_FINAL_DIAGNOSTIC = 'Path report.final diagnosis'; implementation end.
// ************************************************************* // unit ECSCFG_Global // // erstellt: 29.12.2004 RIA // // Projekt: ECSWIN für WinCC // // Funktion: ECSCONFIG_CC Globale Variable // // 15.09.2008 RIA // 09.08.2009 RIA 2.7.0 Sprachumschaltung // 12.04.2010 RIA 2.7.4 Umstellung auf D2010 // 26.04.2011 RIA 2.8.0 ecs_SYS: ecs_NET_nDATABASECONF, ecs_NET_nREDUNDANCYCONF, ecs_SYS_strSTATIONCOM, ecs_SYS_nSTATIONTYPE neu // Tabelle ECS_SYS_CONFIGURATION umstrukturiert // 19.11.2012 RIA 2.11.0 neue Sprachumschaltung // 09.02.2015 RIA 2.14.1 neues Formatfitting WordToBCDWord // 29.09.2015 ria 2.15.1 Benutzung eines Styles // // ************************************************************* unit ECSCFG_Global; interface uses Windows, VCL.Graphics; const STR_ECSWIN = 'DS_ECSWIN'; // Name der ODBC Datenquelle STR_LOGFILE = ''; STR_XLSRANGEEND = '-COLFINISH;'; STR_THISAPPNO = '1'; // Applikationsnr. für ECSCONFIG_CC in Tabelle ECS_SYS_CONFIGURATION STR_COMMONAPPNO = '0'; // Applikationsnr. für ALLGEMEIN in Tabelle ECS_SYS_CONFIGURATION N_THISAPPNO = 1; // Applikationsnr. für ECSCONFIG_CC in Tabelle ECS_SYS_CONFIGURATION N_COMMONAPPNO = 0; // Applikationsnr. für ALLGEMEIN in Tabelle ECS_SYS_CONFIGURATION N_DELETE = 0; // löschen N_SAVE = 1; // speichern N_S5 = 0; // SPS Typ = S5 N_S7 = 1; // SPS Typ = S7 N_AUTECS7 = 1; // Regler Interface N_OTAS = 2; // OTAS Typ N_PROGCOUNT = 17; // Anzahl Programme N_ANALOG_TYPE = 1; // analoger Parameter / Variable N_BINARY_TYPE = 2; // binärer Parameter / Variable STR_ANALOG_TYPE = '1'; // analoger Parameter / Variable STR_BINARY_TYPE = '2'; // binärer Parameter / Variable STR_NOADDRESS = ''; // keine Adresse STR_NOCONNECTION = ''; // keine Verbindung STR_NOSTARTVAL = ''; // kein Startwert N_FORMAT0 = 0; // keine Formatanpassung N_NOSCALING = 0; // ohne Skalierung N_SHOW_ERROR = 1; // Fehlermeldung anzeigen N_SCALING_FROM_TABLE = 1; // Skaling aus ECS_CONVERT lesen N_SCALING_FROM_GLOBAL_VARS = 999; // Skalierung aus globalen Variablen str_ScaleP1..4 N_COMMIT = 0; // ODK Funktion mit COMMIT ausführen N_NOCOMMIT = 1; // ODK Funktion mit COMMIT ausführen N_ACTION = 0; // ??? The fragen N_ERROR_NOT_EXISTS = 1; // Fehler zurückgeben, wenn Variable nicht existiert N_NOERROR = 0; N_VAR_DEL_RAWMESAN = -2; N_VAR_DEL_RAWMESANQ = -3; N_VAR_DELETE = -1; // Variable löschen N_VAR_CREATE = 0; // Variable erzeugen N_VAR_REPLACE = 1; // Variable ersetzen N_VAR_INS_OR_REPLACE = 2; // Variable ggf. löschen u. ersetzen N_VAR_MODIFY = 3; // Variable ändern N_ROWHEIGHT = 18; // Zeilenhöhe in Grids // Konstanten für Fehler, die abgefragt werden N_INVALID_PLCNAME = -5040; // Ungültiger AG- od. Verbindungsname // Konstanten für WinCC Variablentypen DM_VARTYPE_BIT = 1; // Binäre Variable DM_VARTYPE_SBYTE = 2; // 8 Bit Wert (+/-) DM_VARTYPE_BYTE = 3; // 8 Bit Wert DM_VARTYPE_SWORD = 4; // 16 Bit Wert (+/-) DM_VARTYPE_WORD = 5; // 16 Bit Wert DM_VARTYPE_SDWORD = 6; // 32 Bit Wert (+/-) DM_VARTYPE_DWORD = 7; // 32 Bit Wert DM_VARTYPE_FLOAT = 8; // GK 32 Bit IEEE754 DM_VARTYPE_DOUBLE = 9; // GK 64 Bit IEEE754 DM_VARTYPE_TEXT_8 = 10; // Textvar. 8 Bit ZS DM_VARTYPE_TEXT_16 = 11; // Textvar. 16 Bit ZS DM_VARTYPE_RAW = 12; // Rohdatentyp // Konstanten für WinCC Variableneigenschaften DM_INTERNAL_VAR = 2; // interne Variable, projektweit DM_INTERNAL_VAR_LOCAL = 8194; // interne Variable, rechnerlokal DM_EXTERNAL_VAR = 4; // externe Variable // Konstanten für WinCC Formatanpassung // Formatanpassung für Var.-Typ: 8 Bit Wert (+/-) FF_CHAR_TO_SBYTE = 0; // CharToSignedByte FF_CHAR_TO_BYTE = 1; // CharToUnSignedByte // Formatanpassung für Var.-Typ: 8 Bit Wert FF_BYTE_TO_BYTE = 0; // ByteToUnsignedByte FF_BYTE_TO_SBYTE = 3; // ByteToSignedByte // Formatanpassung für Var.-Typ: 16 Bit Wert (+/-) FF_SHORT_TO_SWORD = 0; // ShortToSignedWord FF_SHORT_TO_WORD = 2; // ShortToUnSignedWord // Formatanpassung für Var.-Typ: 16 Bit Wert FF_WORD_TO_WORD = 0; // WordToUnsignedWord FF_WORD_TO_SWORD = 4; // WordToSignedWord FF_WORD_TO_BCDWORD = 7; // WordToBCDWord // Formatanpassung für Var.-Typ: 32 Bit Wert (+/-) FF_LONG_TO_SIMATICBCDTIMER = 30; // LongToSimaticBCDTimer FF_LONG_TO_SIMATICTIMER = 34; // LongToSimaticTimer FF_LONG_TO_SDWORD = 0; // LongToSignedDword FF_LONG_TO_DWORD = 3; // LongToUnSignedDword // Formatanpassung für Var.-Typ: 32 Bit Wert FF_DWORD_TO_SIMATICBCDTIMER = 15; // DwordToSimaticBCDTimer FF_DWORD_TO_SIMATICTIMER = 19; // DwordToSimaticTimer FF_DWORD_TO_DWORD = 0; // DwordToUnsignedDword FF_DWORD_TO_SDWORD = 5; // DwordToSignedDword // Formatanpassung für Var.-Typ: GK 32 Bit IEEE754 FF_FLOAT_TO_BYTE = 1; // FloatToUnsignedByte FF_FLOAT_TO_SBYTE = 4; // FloatToSignedByte FF_FLOAT_TO_WORD = 2; // FloatToUnsignedWord FF_FLOAT_TO_SWORD = 5; // FloatToSignedWord FF_FLOAT_TO_BCDWORD = 12; // FloatToBCDWord FF_FLOAT_TO_SIMATICBCDTIMER = 32; // FloatToSimaticBCDTimer FF_FLOAT_TO_SIMATICTIMER = 37; // FloatToSimaticTimer FF_FLOAT_TO_FLOAT = 0; // FloatToFloat FF_FLOAT_TO_DWORD = 3; // FloatToUnsignedDword FF_FLOAT_TO_SDWORD = 6; // FloatToSignedDword FF_FLOAT_TO_S5FLOAT = 36; // FloatToS5Float // Formatanpassung für Var.-Typ: GK 64 Bit IEEE754 FF_DOUBLE_TO_DOUBLE = 0; // DoubleToDouble // Konstanten für Parameternummer in Funktion // ECS_CCODK_ModifyVariable MODIFY_VARGROUP = 1; // Variablengruppe d. WinCC Var. ändern MODIFY_ADDRESS = 2; // Adresse d. WinCC Var. ändern MODIFY_STARTVAL = 3; // Startwert d. WinCC Var. ändern N_BEFORE_INSERT = 0; N_BEFORE_POST = 1; N_BKCOLOR_COLUMN_SORT = clBlue; // Hintergrundfarbe f. Sortierspalte N_FGCOLOR_COLUMN_SORT = clBlue; // Textfarbe f. Sortierspalte N_BKCOLOREDIT = $00D5FFFF; // Hintergrundfarbe für editierbare Objekte N_FRCOLOREDIT = 0; // Schriftfarbe für editierbare Objekte N_MAXBIT = 15; // maximale erlaubte Bitnummer N_STELL16 = 0; // VM Interface = Stell16 N_STELL2000 = 1; // VM Interface = Stell2000 // Excel-Spaltennamen arr_strCells : array [1..104] of string = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ', 'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ', 'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ'); str_SetDateFormat : string = 'set dateformat dmy'; //STR_LANGUAGES : array [1..5] of string = ('TEXT_L1', 'TEXT_L2', 'TEXT_L3', 'TEXT_L4', 'TEXT_L5'); arr_IsChecked : array [0..1] of Integer = (DFCS_BUTTONCHECK, DFCS_BUTTONCHECK or DFCS_CHECKED); // DFCS_BUTTONCHECK -> Typ Checkbox // DFCS_BUTTONCHECK or DFCS_CHECKED -> Typ Checkbox mit Häkchen var b_LoginPrompt : boolean = false; b_SQLProvider : boolean = true; b_RestartRuntime : boolean; // true -> Runtime muss neu gestartet werden n_MonitorNum : integer; // Monitornummer n_EditBkColor : integer; // Hintergrundfarbe f. Editieren n_EditFrColor : integer; // Fontfarbe f. Editieren str_NameTxt : string = 'Name'; str_NumberTxt : string = 'Nr.'; str_IOByteTxt : string = 'I/O Byte'; str_IOBitTxt : string = 'I/O Bit'; str_InterFaceTxt : string = 'Interface'; str_VISUDBTxt : string = 'VISU DB'; str_BitTxt : string = 'Bit'; str_DecPlTxt : string = 'NK'; str_Complete : string = 'WinCC Variablen komplett!'; str_NotComplete : string = 'WinCC Variablen nicht komplett!'; str_AccessLevel : string = 'Im Feld Access bitte einen Wert zwischen 0 und 10 eingeben!'; str_NoAreas : string = 'Bereiche fehlen! Bitte geben Sie zuerst Bereiche ein!'; str_InValidChar : string = 'Zeichen ist nicht erlaubt!'; str_InputError : string = 'Falsche Eingabe!'; str_PLCInterface : string = 'Einfügen nicht möglich! SPS Schnittstelle nicht komplett!'; str_PLCUpdate : string = 'Speichern nicht möglich! SPS Schnittstelle nicht komplett!'; str_ItemExists : string = 'Name existiert bereits in einer anderen ECSWIN Tabelle!'; str_Limit1 : string = 'Ungültiger Wert für: '; str_Limit2 : string = 'Ein gültiger Wert ist '; str_Limit3l : string = 'größer oder gleich '; str_Limit3u : string = 'kleiner oder gleich '; str_FormatFit : string = 'Adresse, ggf. Formatanpassung und Länge nach Doppelklick auf die Zeile an den neuen Variablentyp anpassen!'; str_MissingScVal : string = 'Mind. ein Wert für die Skalierung fehlt! Bitte einen Wert für alle Skalierungsparameter eingeben!'; str_AlreadyExists : string = 'Diese Kombination existiert bereits! Bitte ändern!'; str_CloseWindow : string = 'S&chließen'; str_Addr_InComplete : string = 'Adresse fehlt oder ist unvollständig!'; str_Wrong_DBConnect : string = 'ACHTUNG: Nicht verbunden mit der Master-Datenbank!'; str_ConnectedTo : string = 'Verbunden mit [Server].Datenbank: '; implementation end.
unit UCAudioProcessor; interface uses Vst3Base,UVST3Processor; type CAudioProcessor = class(TAggregatedObject,IAudioProcessor) private FHostContext:FUnknown; IVST3:IVST3Processor; FSamplerate,Ftempo:single; FPPQ:integer; FPlaying:boolean; public function SetBusArrangements(inputs: PSpeakerArrangement; numIns: int32; outputs: PSpeakerArrangement; numOuts: int32): TResult; stdcall; function GetBusArrangement(dir: TBusDirection; index: int32; var arr: TSpeakerArrangement): TResult; stdcall; function CanProcessSampleSize(symbolicSampleSize: int32): TResult; stdcall; function GetLatencySamples: uint32; stdcall; function SetupProcessing(var setup: TProcessSetup): TResult; stdcall; function SetProcessing(state: TBool): TResult; stdcall; function Process(var data: TProcessData): TResult; stdcall; function GetTailSamples: uint32; stdcall; constructor Create(const Controller: IVST3Processor); end; implementation { CAudioProcessor } uses UCodeSiteLogger, SysUtils, UVSTBase; function CAudioProcessor.CanProcessSampleSize( symbolicSampleSize: int32): TResult; begin WriteLog('CAudioProcessor.CanProcessSampleSize:'+symbolicSampleSize.ToString); result:=kResultFalse; if symbolicSampleSize=kSample32 then result:=kResultTrue; end; constructor CAudioProcessor.Create(const Controller: IVST3Processor); begin inherited Create(controller); IVST3:=Controller; WriteLog('CAudioProcessor.Create'); FhostContext:=NIL; end; function CAudioProcessor.GetBusArrangement(dir: TBusDirection; index: int32; var arr: TSpeakerArrangement): TResult; begin WriteLog('CAudioProcessor.GetBusArrangement'); (* JUCE Version if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index)) { arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout()); return kResultTrue; } return kResultFalse; JUCE Version *) result:=kResultTrue; end; function CAudioProcessor.GetLatencySamples: uint32; begin // WriteLog('CAudioProcessor.GetLatencySamples'); result:=0; end; function CAudioProcessor.GetTailSamples: uint32; begin WriteLog('CAudioProcessor.GetTailSamples'); result:=kNoTail; end; {$POINTERMATH ON} function CAudioProcessor.Process(var data: TProcessData): TResult; (* this does not (yet?) work in reaper... procedure MidiOut(byte0,byte1,byte2:integer); VAR event:TVstEvent; begin event.busIndex := 0; event.sampleOffset := 0; event.ppqPosition := 0; event.flags := 0; event.eventType := kLegacyMIDICCOutEvent; event.midiCCOut.channel := byte0 and $F; event.midiCCOut.controlNumber := byte1; event.midiCCOut.value := byte2; event.midiCCOut.value2 := 0; (* event.eventType := kNoteOnEvent; event.noteOn.channel:= byte0 and $F; event.noteOn.pitch := byte1; event.noteOn.velocity := byte2; // event.midiCCOut.value2 := 0; * event.flags := kIsLive; data.outputEvents.AddEvent(event) end; *) procedure ProcessEvents; VAR numEvents,index:integer; event:TVstEvent; function ToSysEx:string; VAR i:integer; begin result:=''; for i:=0 to event.data.size-1 do result:=result+chr(event.data.bytes[i]); end; const MIDI_NOTE_ON = $90; MIDI_NOTE_OFF = $80; begin numEvents:=data.inputEvents.GetEventCount; for index:=0 to numEvents-1 do begin data.inputEvents.GetEvent(index,event); case event.eventType of kNoteOnEvent : with event.noteOn do IVST3.OnMidiEvent(channel+MIDI_NOTE_ON,pitch,round(127*velocity)); kNoteOffEvent : with event.noteOff do IVST3.OnMidiEvent(channel+MIDI_NOTE_OFF,pitch,round(127*velocity)); kDataEvent : IVST3.OnSysExEvent(ToSysEx); (* not implemented... kPolyPressureEvent : (poly: TPolyPressureEvent); kNoteExpressionValueEvent : (exprValue: TNoteExpressionValueEvent); kNoteExpressionTextEvent : (exprText: TNoteExpressionTextEvent); *) end; end; end; procedure ProcessParameters; VAR index,numParamsChanged,numPoints,j:integer; paramQueue:IParamValueQueue; sampleOffset:integer; value:TParamValue; begin numParamsChanged := data.inputParameterChanges.getParameterCount; for index := 0 to numParamsChanged-1 do begin paramQueue:=data.inputParameterChanges.getParameterData(index); if (paramQueue<>NIL) then begin paramQueue._AddRef; // ??? TODO: I am truly not sure on this... numPoints := paramQueue.getPointCount; for j:=0 to numPoints-1 do if (paramQueue.getPoint (j, sampleOffset, value) = kResultTrue) then IVST3.ProcessorParameterSetValue(paramQueue.getParameterId,value); // first test... MidiOut(0,60,80); end; end; end; procedure ProcessAudio; VAR inputbus,outputbus:TAudioBusBuffers; inputp,outputp:PPSingle; begin inputbus:=data.inputs[0]; outputbus:=data.outputs[0]; inputp:=PPSingle(inputbus.channelBuffers32); outputp:=PPSingle(outputbus.channelBuffers32); IVST3.Process32(data.numSamples,2,inputp,outputp); end; procedure ProcessContext; VAR newTempo,newSampleRate:single; newPPQ:integer; newPlaying,playStateChanged:boolean; state:TStatesAndFlags; begin state:=data.processContext.state; newSamplerate:=data.processContext.sampleRate; if (newSamplerate<>FSampleRate) then begin FSampleRate:=NewSampleRate; IVST3.SamplerateChanged(FSamplerate); end; newTempo:=data.processContext.tempo; if (newTempo<>FTempo) and (state and kTempoValid <> 0) then begin FTempo:=NewTempo; IVST3.TempoChanged(FTempo); end; playstateChanged:=false; newPPQ:=trunc(data.processContext.projectTimeMusic); if (newPPQ<>FPPQ) then begin FPPQ:=NewPPQ; playStateChanged:=true; end; newPlaying:=state and kPlaying <> 0; if (newPlaying<>FPlaying) then begin FPlaying:=NewPlaying; playStateChanged:=true; end; if playstateChanged then IVST3.PlayStateChanged(FPlaying,FPPQ); end; begin // WriteLog('CAudioProcessor.Process'); if (data.inputEvents<>NIL) then ProcessEvents; if (data.inputParameterChanges<>NIL) then ProcessParameters; if (data.numSamples>0) then ProcessAudio; if data.processContext<>NIL then ProcessContext; result:=kResultTrue; end; function CAudioProcessor.SetBusArrangements(inputs: PSpeakerArrangement; numIns: int32; outputs: PSpeakerArrangement; numOuts: int32): TResult; begin WriteLog('CAudioProcessor.SetBusArrangement'); result:=kResultTrue; end; function CAudioProcessor.SetProcessing(state: TBool): TResult; begin WriteLog('CAudioProcessor.SetProcessing'); result:=kResultTrue; end; function CAudioProcessor.SetupProcessing(var setup: TProcessSetup): TResult; begin WriteLog('CAudioProcessor.SetupProcessing'); result:=kResultTrue; (* JUCE Version if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue) return kResultFalse; processSetup = newSetup; processContext.sampleRate = processSetup.sampleRate; getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64 ? AudioProcessor::doublePrecision : AudioProcessor::singlePrecision); preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock); return kResultTrue; JUCE Version *) end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, Vcl.Grids, Vcl.DBGrids, FireDAC.Comp.BatchMove.Text, FireDAC.Comp.BatchMove, FireDAC.Comp.BatchMove.DataSet, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Stan.StorageBin, Vcl.StdCtrls; type TfMain = class(TForm) FDConnection: TFDConnection; fdqEmployee: TFDQuery; FDBatchMoveDataSetWriter: TFDBatchMoveDataSetWriter; FDBatchMove: TFDBatchMove; FDBatchMoveTextReader: TFDBatchMoveTextReader; fdqEmployeeID: TIntegerField; fdqEmployeeNOME: TStringField; fdqEmployeeCIDADE: TStringField; fdqEmployeeEMAIL: TStringField; fdqEmployeeDATANASC: TDateField; fdqEmployeePROFISSAO: TStringField; fdqEmployeeCARTAO: TStringField; dsEmployee: TDataSource; dbgEmployee: TDBGrid; fdmEmployee: TFDMemTable; fdmEmployeeID: TIntegerField; fdmEmployeeNOME: TStringField; fdmEmployeeCIDADE: TStringField; fdmEmployeeEMAIL: TStringField; fdmEmployeeDATANASC: TDateField; fdmEmployeePROFISSAO: TStringField; fdmEmployeeCARTAO: TStringField; btnArrayDML: TButton; procedure FormCreate(Sender: TObject); procedure btnArrayDMLClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fMain: TfMain; implementation {$R *.dfm} uses System.Diagnostics; procedure TfMain.FormCreate(Sender: TObject); begin fdmEmployee.DisableControls; try FDBatchMoveTextReader.FileName := '../../Dados.csv'; FDBatchMove.Execute; fdmEmployee.First; finally fdmEmployee.EnableControls; end; end; procedure TfMain.btnArrayDMLClick(Sender: TObject); var vPosition: integer; vIndex: integer; vStopwatch: TStopwatch; begin fdqEmployee.DisableControls; fdmEmployee.DisableControls; vPosition := fdmEmployee.RecNo; try fdqEmployee.Params.ArraySize := fdmEmployee.RecordCount; vStopwatch := TStopwatch.StartNew; fdmEmployee.First; while (not fdmEmployee.Eof) do begin vIndex := Pred(fdmEmployee.RecNo); fdqEmployee.ParamByName('id').AsIntegers[vIndex] := fdmEmployeeID.AsInteger; fdqEmployee.ParamByName('nome').AsStrings[vIndex] := fdmEmployeeNOME.AsString; fdqEmployee.ParamByName('cidade').AsStrings[vIndex] := fdmEmployeeCIDADE.AsString; fdqEmployee.ParamByName('email').AsStrings[vIndex] := fdmEmployeeEMAIL.AsString; fdqEmployee.ParamByName('datanasc').AsDates[vIndex] := fdmEmployeeDATANASC.AsDateTime; fdqEmployee.ParamByName('profissao').AsStrings[vIndex] := fdmEmployeePROFISSAO.AsString; fdqEmployee.ParamByName('cartao').AsStrings[vIndex] := fdmEmployeeCARTAO.AsString; fdmEmployee.Next; end; fdqEmployee.Execute(fdmEmployee.RecordCount, 0); finally fdmEmployee.RecNo := vPosition; fdmEmployee.EnableControls; fdqEmployee.EnableControls; end; vStopwatch.Stop; ShowMessage('Done in '+ vStopwatch.Elapsed.ToString); end; end.
unit EnvironmentImpl; interface uses Classes,SysUtils,DataAccess,OptionsConfigImpl, DBClient,MConnect,DataAccessInt;//DataAccessImpl const ConnectionDatabaseName='DBConnection'; type TRuntimeEnvironmentImpl=class(TComponent) private FRuned:Boolean; FConnectionContext: IConnectionContext; FConfigSettings:TConfigSettings; //FDataAccess:IDataAccessInt; function GetRuned: Boolean; function GetConfigSettings: TConfigSettings; protected procedure InitializeAdoContext; function GetDataAccess: IDataAccessInt; public constructor Create(AOwner:TComponent);override; destructor Destroy;override; function TryConnectDatabase:Boolean; function JudgeDBConnection(var JudgeResult:string):Boolean; function JudgeConfigSettings(IsServer:Boolean;var JudgeResult:string):Boolean; procedure InitializeEnvironment; procedure Startup; procedure Stop; property Runed:Boolean read GetRuned; property ConnectionContext:IConnectionContext read FConnectionContext; property DataAccess:IDataAccessInt read GetDataAccess; property ConfigSettings:TConfigSettings read GetConfigSettings; end; function _Environment:TRuntimeEnvironmentImpl; implementation uses Forms,SConnect,Adodb,db,ActiveX,ComObj,Math,FrameCommon,DataMainImpl, DataAccessImpl,FrameDataAccessImpl; var Environment:TRuntimeEnvironmentImpl=nil; function _Environment:TRuntimeEnvironmentImpl; begin if Environment=nil then Environment:=TRuntimeEnvironmentImpl.Create(nil); Result:=Environment; end; { TRuntimeEnvironmentImpl } constructor TRuntimeEnvironmentImpl.Create(AOwner: TComponent); begin inherited Create(AOwner); FConfigSettings:=TConfigSettings.Create(AOwner); FConfigSettings.LoadFromStream; end; destructor TRuntimeEnvironmentImpl.Destroy; begin //FRemoteAdapter:=nil ; Freeandnil(FConfigSettings) ; //Freeandnil(FConnectionContext); //Freeandnil(FDataAccess) ; inherited; end; function TRuntimeEnvironmentImpl.GetConfigSettings: TConfigSettings; begin Result:=FConfigSettings; end; function TRuntimeEnvironmentImpl.GetDataAccess: IDataAccessInt; begin // if FDataAccess=nil then // begin // //Result:=DataAccessFactory.GetDataAccessInt(LocalNetAccessTypeName); // Result.Initialize; // end; // // Result:=DataMain as IDataAccessInt ; // Result:=FDataAccess; result:=DataMain as IDataAccessInt; end; function TRuntimeEnvironmentImpl.GetRuned: Boolean; begin Result:=FRuned; end; procedure TRuntimeEnvironmentImpl.InitializeAdoContext; begin with ConfigSettings.ConnStrBulider do begin ConnectionContextMgr.UnRegisterAllConnectionContext; ConnectionContextMgr.RegisterConnectionContext(ConnectionDatabaseName,ConnectionString,dbtSqlServer,1,10,CommandTimeOut*1000); FConnectionContext:=ConnectionContextMgr.GetConnectionContext(ConnectionDatabaseName); end; end; procedure TRuntimeEnvironmentImpl.InitializeEnvironment; begin InitializeAdoContext; end; function TRuntimeEnvironmentImpl.JudgeConfigSettings(IsServer: Boolean; var JudgeResult: string): Boolean; begin Result:=JudgeDBConnection(JudgeResult); end; function TRuntimeEnvironmentImpl.JudgeDBConnection( var JudgeResult: string): Boolean; var Connect:TADOConnection; begin CoInitialize(nil); Connect:=TADOConnection.Create(nil); try Connect.LoginPrompt:=False; Connect.ConnectionString:=ConfigSettings.ConnStrBulider.ConnectionString; try Connect.Connected:=True; Result:=Connect.Connected; except on E:Exception do begin JudgeResult:='数据库连接错误.具体原因:'+E.Message; Result:=False; end; end; finally Connect.Free; end; end; procedure TRuntimeEnvironmentImpl.Startup; begin FRuned:=True; end; procedure TRuntimeEnvironmentImpl.Stop; begin FRuned:=False; end; function TRuntimeEnvironmentImpl.TryConnectDatabase: Boolean; var Connect:TADOConnection; begin begin CoInitialize(nil); Connect:=TADOConnection.Create(nil); try Connect.LoginPrompt:=False; Connect.ConnectionString:=ConfigSettings.ConnStrBulider.ConnectionString; try Connect.Connected:=True; Result:=Connect.Connected; except on E:Exception do begin Result:=False; end; end; finally Connect.Free; end; end; end; initialization _Environment; finalization if Environment<>nil then //Environment=nil; FreeAndNil(Environment); end.
unit Wait; interface Uses Controls, Forms; type TWait = object constructor Init; destructor Done; private OldCursor: TCursor; end; implementation constructor TWait.Init; begin OldCursor := Screen.Cursor; Screen.Cursor := crHourglass; end; destructor TWait.Done; begin Screen.Cursor := OldCursor; end; end.
unit PropertyInfoTests; interface uses InfraCommonIntf, TestFrameWork, ReflectModel, ReflectModelIntf; type TPropertyInfoTests = class(TTestCase) private FPersonInfo: IClassInfo; FStudentInfo: IClassInfo; FPerson: IPerson; FStudent: IStudent; protected procedure SetUp; override; procedure TearDown; override; published procedure TestGetGetterInfo; procedure TestGetSetterInfo; procedure TestGetValue; procedure TestSetValue; procedure TestGetTypeInfo; end; implementation uses SysUtils, InfraConsts, InfraValueTypeIntf, InfraValueType, StdVCL; { TPropertyInfoTests } procedure TPropertyInfoTests.SetUp; begin inherited; TSetupModel.RegisterAddress; FPersonInfo := TSetupModel.RegisterPerson; FStudentInfo := TSetupModel.RegisterStudent; TSetupModel.RegisterPersonAddressRelation(FPersonInfo); FPerson := TPerson.Create; with FPerson do begin Name.AsString := 'Filiph Stradius'; Email.AsString := 'Filiph@Mail'; Birthday.AsDate := StrToDate('10/02/1980'); Address.Street.AsString := 'Filiph Street'; Address.City.AsString := 'Filiph City'; Address.Quarter.AsString := 'Filiph Quarter'; Address.Number.AsInteger := 100; end; FStudent := TStudent.Create; with FStudent do begin Name.AsString := 'Michael Stradius'; Email.AsString := 'Michael@Mail'; SchoolNumber.AsString := 'Michael ShcoolNumber'; Birthday.AsDate := StrToDate('10/02/1980'); Address.Street.AsString := 'Michael Street'; Address.City.AsString := 'Michael City'; Address.Quarter.AsString := 'Michael Quarter'; Address.Number.AsInteger := 25; end; end; procedure TPropertyInfoTests.TearDown; begin TSetupModel.RemoveTypeInfo(IPerson); TSetupModel.RemoveTypeInfo(IAddress); TSetupModel.RemoveTypeInfo(IStudent); inherited; end; procedure TPropertyInfoTests.TestGetGetterInfo; var FPropertyInfo: IPropertyInfo; FMethodInfo: IMethodInfo; begin FPropertyInfo := FPersonInfo.GetPropertyInfo('Email'); FMethodInfo := FPropertyInfo.GetGetterInfo; CheckNotNull(FMethodInfo, 'Email Getter not assigned on Person'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Email'); FMethodInfo := FPropertyInfo.GetGetterInfo; CheckNotNull(FMethodInfo, 'Email Getter not assigned on Student'); FPropertyInfo := FPersonInfo.GetPropertyInfo('Address.Street'); FMethodInfo := FPropertyInfo.GetGetterInfo; CheckNotNull(FMethodInfo, 'Address.Street Getter not assigned on Person'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Address.Street'); FMethodInfo := FPropertyInfo.GetGetterInfo; CheckNotNull(FMethodInfo, 'Address.Street Getter not assigned on Student'); end; procedure TPropertyInfoTests.TestGetSetterInfo; var FPropertyInfo: IPropertyInfo; FMethodInfo: IMethodInfo; begin FPropertyInfo := FPersonInfo.GetPropertyInfo('Email'); FMethodInfo := FPropertyInfo.GetSetterInfo; CheckNotNull(FMethodInfo, 'Email Setter not assigned on Person'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Email'); FMethodInfo := FPropertyInfo.GetSetterInfo; CheckNotNull(FMethodInfo, 'Email Setter not assigned on Student'); FPropertyInfo := FPersonInfo.GetPropertyInfo('Address.Quarter'); FMethodInfo := FPropertyInfo.GetSetterInfo; CheckNotNull(FMethodInfo, 'Address.Quarter Setter not assigned on Person'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Address.Quarter'); FMethodInfo := FPropertyInfo.GetSetterInfo; CheckNotNull(FMethodInfo, 'Address.Quarter Setter not assigned on Student'); end; procedure TPropertyInfoTests.TestGetTypeInfo; var FPropertyInfo: IPropertyInfo; FTypeInfo: IClassInfo; begin FPropertyInfo := FPersonInfo.GetPropertyInfo('Email'); FTypeInfo := FPropertyInfo.GetTypeInfo; CheckNotNull(FTypeInfo, 'Person.Email do not have TypeInfo'); CheckTrue(IsEqualGUID(FTypeInfo.TypeID, IInfraString), 'Person.Email''''s TypeInfo should be an InfraString'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Email'); FTypeInfo := FPropertyInfo.GetTypeInfo; CheckNotNull(FTypeInfo, 'Student.Email do not have TypeInfo'); CheckTrue(IsEqualGUID(FTypeInfo.TypeID, IInfraString), 'Student.Email''''s TypeInfo should be an InfraString'); FPropertyInfo := FPersonInfo.GetPropertyInfo('Address.City'); FTypeInfo := FPropertyInfo.GetTypeInfo; CheckNotNull(FTypeInfo, 'Person.Address.City do not have TypeInfo'); CheckTrue(IsEqualGUID(FTypeInfo.TypeID, IInfraString), 'Person.Address.City''''s TypeInfo should be an InfraString'); FPropertyInfo := FStudentInfo.GetPropertyInfo('Address.City'); FTypeInfo := FPropertyInfo.GetTypeInfo; CheckNotNull(FTypeInfo, 'Student.Address.City do not have TypeInfo'); CheckTrue(IsEqualGUID(FTypeInfo.TypeID, IInfraString), 'Student.Address.City''''s TypeInfo should be an InfraString'); end; procedure TPropertyInfoTests.TestGetValue; var FPropertyInfo: IPropertyInfo; Street: string; begin FPropertyInfo := FPersonInfo.GetPropertyInfo('Email'); CheckEquals('Filiph@Mail', (FPropertyInfo.GetValue(FPerson) as IInfraString).AsString, 'Mismatch Person.Email value: '+ (FPropertyInfo.GetValue(FPerson) as IInfraString).AsString); FPropertyInfo := FStudentInfo.GetPropertyInfo('Email'); CheckEquals('Michael@Mail', (FPropertyInfo.GetValue(FStudent) as IInfraString).AsString, 'Mismatch Student.Email value: '+ (FPropertyInfo.GetValue(FStudent) as IInfraString).AsString); FPropertyInfo := FPersonInfo.GetPropertyInfo('Address.Street'); Street := (FPropertyInfo.GetValue(FPerson.Address) as IInfraString).AsString; CheckEquals('Filiph Street', Street, 'Mismatch Person.Address.Street value: ' + Street); FPropertyInfo := FStudentInfo.GetPropertyInfo('Address.Street'); Street := (FPropertyInfo.GetValue(FStudent.Address) as IInfraString).AsString; CheckEquals('Michael Street', Street, 'Mismatch Person.Address.Street value: ' + Street); end; procedure TPropertyInfoTests.TestSetValue; var FPropertyInfo: IPropertyInfo; begin FPropertyInfo := FPersonInfo.GetPropertyInfo('Email'); FPropertyInfo.SetValue(FPerson, TInfraString.NewFrom('NewFiliph@Mail')); CheckEquals('NewFiliph@Mail', FPerson.Email.AsString, 'Mismatch Person.Email value: ' + FPerson.Email.AsString); FPropertyInfo := FStudentInfo.GetPropertyInfo('Email'); FPropertyInfo.SetValue(FStudent, TInfraString.NewFrom('NewMichael@Mail')); CheckEquals('NewMichael@Mail', FStudent.Email.AsString, 'Mismatch Student.Email value: ' + FStudent.Email.AsString); FPropertyInfo := FPersonInfo.GetPropertyInfo('Address.Street'); FPropertyInfo.SetValue(FPerson.Address, TInfraString.NewFrom('New Filiph Street')); CheckEquals('New Filiph Street', FPerson.Address.Street.AsString, 'Mismatch Person.Address.Street value: ' + FPerson.Address.Street.AsString); FPropertyInfo := FStudentInfo.GetPropertyInfo('Address.Street'); FPropertyInfo.SetValue(FStudent.Address, TInfraString.NewFrom('New Michael Street')); CheckEquals('New Michael Street', FStudent.Address.Street.AsString, 'Mismatch Student.Address.Street value: ' + FStudent.Address.Street.AsString); end; initialization TestFramework.RegisterTest('InfraReflectTests Suite', TPropertyInfoTests.Suite); end.
{ This software is Copyright (c) 2015 by Doddy Hackman. This is free software, licensed under: The Artistic License 2.0 The Artistic License Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } // Project Arsenal X 0.2 // (C) Doddy Hackman 2015 unit form_ping; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, sStatusBar, Vcl.StdCtrls, sButton, sEdit, sGroupBox, functions; type Tping = class(TForm) sGroupBox1: TsGroupBox; txtHost: TsEdit; btnPingIt: TsButton; status: TsStatusBar; procedure btnPingItClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ping: Tping; implementation {$R *.dfm} procedure Tping.btnPingItClick(Sender: TObject); var respuesta: string; begin if not(txtHost.Text = '') then begin status.Panels[0].Text := '[+] Working ...'; form_ping.ping.status.Update; respuesta := ping_it(txtHost.Text); status.Panels[0].Text := respuesta; form_ping.ping.status.Update; end else begin MessageBox(0, 'Write Host', 'Ping it 0.2', MB_ICONINFORMATION); end; end; end. // The End ?
{******************************************} { Animated Progress Bar } { Copyright (c) Dreamsoft 2002 } { Author: Schlecht Eduard } {******************************************} unit DProgress; {$R-} interface uses Messages, Windows, SysUtils, CommCtrl, Classes, Controls, StdCtrls, ExtCtrls; const PBS_MARQUEE = $08; PBM_SETMARQUEE = (WM_USER+10); type { TProgressBar } TDProgressRange = Integer; // for backward compatibility TDProgressBarOrientation = (pbHorizontal, pbVertical); TDProgressBar = class(TWinControl) private F32BitMode: Boolean; FMin: Integer; FMax: Integer; FPosition: Integer; FStep: Integer; FOrientation: TDProgressBarOrientation; FSmooth: Boolean; FAnimating: Boolean; FTimer: TTimer; FInterval: Cardinal; function GetMin: Integer; function GetMax: Integer; function GetPosition: Integer; procedure SetParams(AMin, AMax: Integer); procedure SetMin(Value: Integer); procedure SetMax(Value: Integer); procedure SetPosition(Value: Integer); procedure SetStep(Value: Integer); procedure SetOrientation(Value: TDProgressBarOrientation); procedure SetSmooth(Value: Boolean); // procedure SetMarquee(Value: Boolean); procedure SetInterval(Value: Cardinal); procedure SetIsAnimating(Value: Boolean); procedure DoAnimate(Sender: TObject); protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; public constructor Create(AOwner: TComponent); override; procedure StepIt; procedure StepBy(Delta: Integer); published property Align; property Animate: Boolean read FAnimating write SetIsAnimating default False; property DragCursor; property DragMode; property Enabled; property Hint; property Min: Integer read GetMin write SetMin; property Max: Integer read GetMax write SetMax; property Orientation: TDProgressBarOrientation read FOrientation write SetOrientation default pbHorizontal; property ParentShowHint; property PopupMenu; property Position: Integer read GetPosition write SetPosition default 0; property Smooth: Boolean read FSmooth write SetSmooth default False; property Step: Integer read FStep write SetStep default 10; property Speed: Cardinal read FInterval write SetInterval default 500; property ShowHint; property TabOrder; property TabStop; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; function InitCommonControl(CC: Integer): Boolean; procedure CheckCommonControl(CC: Integer); const ComCtlVersionIE3 = $00040046; ComCtlVersionIE4 = $00040047; ComCtlVersionIE401 = $00040048; function GetComCtlVersion: Integer; procedure Register; implementation {$R DProgress.res} uses Consts, ComStrs; const SectionSizeArea = 8; ShellDllName = 'shell32.dll'; ComCtlDllName = 'comctl32.dll'; var ShellModule: THandle; ComCtlVersion: Integer; function InitCommonControl(CC: Integer): Boolean; var ICC: TInitCommonControlsEx; begin ICC.dwSize := SizeOf(TInitCommonControlsEx); ICC.dwICC := CC; Result := InitCommonControlsEx(ICC); if not Result then InitCommonControls; end; procedure CheckCommonControl(CC: Integer); begin if not InitCommonControl(CC) then raise EComponentError.Create(SInvalidComCtl32); end; function GetShellModule: THandle; var OldError: Longint; begin if ShellModule = 0 then begin OldError := SetErrorMode(SEM_NOOPENFILEERRORBOX); ShellModule := GetModuleHandle(ShellDllName); if ShellModule < HINSTANCE_ERROR then ShellModule := LoadLibrary(ShellDllName); if (ShellModule > 0) and (ShellModule < HINSTANCE_ERROR) then ShellModule := 0; SetErrorMode(OldError); end; Result := ShellModule; end; function GetComCtlVersion: Integer; var FileName: string; InfoSize, Wnd: DWORD; VerBuf: Pointer; FI: PVSFixedFileInfo; VerSize: DWORD; begin if ComCtlVersion = 0 then begin FileName := ComCtlDllName; InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd); if InfoSize <> 0 then begin GetMem(VerBuf, InfoSize); try if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then ComCtlVersion := FI.dwFileVersionMS; finally FreeMem(VerBuf); end; end; end; Result := ComCtlVersion; end; procedure SetComCtlStyle(Ctl: TWinControl; Value: Integer; UseStyle: Boolean); var Style: Integer; begin if Ctl.HandleAllocated then begin Style := GetWindowLong(Ctl.Handle, GWL_STYLE); if not UseStyle then Style := Style and not Value else Style := Style or Value; SetWindowLong(Ctl.Handle, GWL_STYLE, Style); end; end; { TProgressBar } const Limit16 = 65535; procedure Register; begin RegisterComponents('Dreamsoft', [TDProgressBar]); end; procedure ProgressLimitError; begin raise Exception.CreateFmt(SOutOfRange, [0, Limit16]); end; constructor TDProgressBar.Create(AOwner: TComponent); begin F32BitMode := InitCommonControl(ICC_PROGRESS_CLASS); inherited Create(AOwner); Width := 150; Height := GetSystemMetrics(SM_CYVSCROLL); FMin := 0; FMax := 100; FStep := 100; FInterval := 50; FAnimating := false; FOrientation := pbHorizontal; end; procedure TDProgressBar.CreateParams(var Params: TCreateParams); begin if not F32BitMode then InitCommonControls; inherited CreateParams(Params); CreateSubClass(Params, PROGRESS_CLASS); with Params do begin // if FOrientation = pbVertical then Style := Style or PBS_VERTICAL; // if FSmooth then Style := Style or PBS_SMOOTH; end; SetPosition(FPosition); Params.Style := Params.Style or PBS_MARQUEE; end; procedure TDProgressBar.CreateWnd; begin inherited CreateWnd; if F32BitMode then SendMessage(Handle, PBM_SETRANGE32, FMin, FMax) else SendMessage(Handle, PBM_SETRANGE, 0, MakeLong(FMin, FMax)); SendMessage(Handle, PBM_SETSTEP, FStep, 0); Position := FPosition; end; procedure TDProgressBar.DoAnimate(Sender: TObject); begin Position := 100; end; function TDProgressBar.GetMin: Integer; begin if HandleAllocated and F32BitMode then Result := SendMessage(Handle, PBM_GetRange, 1, 0) else Result := FMin; end; function TDProgressBar.GetMax: Integer; begin if HandleAllocated and F32BitMode then Result := SendMessage(Handle, PBM_GetRange, 0, 0) else Result := FMax; end; function TDProgressBar.GetPosition: Integer; begin if HandleAllocated then begin if F32BitMode then Result := SendMessage(Handle, PBM_GETPOS, 0, 0) else Result := SendMessage(Handle, PBM_DELTAPOS, 0, 0) end else Result := FPosition; end; procedure TDProgressBar.SetParams(AMin, AMax: Integer); begin if AMax < AMin then raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]); if not F32BitMode and ((AMin < 0) or (AMin > Limit16) or (AMax < 0) or (AMax > Limit16)) then ProgressLimitError; if (FMin <> AMin) or (FMax <> AMax) then begin if HandleAllocated then begin if F32BitMode then SendMessage(Handle, PBM_SETRANGE32, AMin, AMax) else SendMessage(Handle, PBM_SETRANGE, 0, MakeLong(AMin, AMax)); if FMin > AMin then // since Windows sets Position when increase Min.. SendMessage(Handle, PBM_SETPOS, AMin, 0); // set it back if decrease end; FMin := AMin; FMax := AMax; end; end; procedure TDProgressBar.SetMin(Value: Integer); begin SetParams(Value, FMax); end; procedure TDProgressBar.SetMax(Value: Integer); begin SetParams(FMin, Value); end; procedure TDProgressBar.SetPosition(Value: Integer); begin if not F32BitMode and ((Value < 0) or (Value > Limit16)) then ProgressLimitError; if HandleAllocated then SendMessage(Handle, PBM_SETPOS, Value, 0) else FPosition := Value; end; procedure TDProgressBar.SetStep(Value: Integer); begin if Value <> FStep then begin FStep := Value; if HandleAllocated then SendMessage(Handle, PBM_SETSTEP, FStep, 0); end; end; procedure TDProgressBar.StepIt; begin if HandleAllocated then SendMessage(Handle, PBM_STEPIT, 0, 0); end; procedure TDProgressBar.StepBy(Delta: Integer); begin if HandleAllocated then SendMessage(Handle, PBM_DELTAPOS, Delta, 0); end; procedure TDProgressBar.SetOrientation(Value: TDProgressBarOrientation); begin if FOrientation <> Value then begin FOrientation := Value; RecreateWnd; end; end; procedure TDProgressBar.SetSmooth(Value: Boolean); begin if FSmooth <> Value then begin FSmooth := Value; RecreateWnd; end; end; //procedure TDProgressBar.SetMarquee(Value: Boolean); //begin //if Value = true then //SendMessage(Handle, PBS_SETMARQUEE, 1, 200) else SendMessage(Handle, PBS_SETMARQUEE, 0, 200); //end; procedure TDProgressBar.SetInterval(Value: Cardinal); begin FInterval := Value; if FAnimating then FTimer.Interval := Value; end; procedure TDProgressBar.SetIsAnimating(Value: Boolean); begin if Value <> FAnimating then begin if Value then begin FTimer := TTimer.Create(Self); FTimer.Interval := FInterval; FTimer.OnTimer := DoAnimate; FTimer.Enabled := True; end else begin FTimer.Free; end; FAnimating := Value; end; end; initialization finalization if ShellModule <> 0 then FreeLibrary(ShellModule); end.
unit settings_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, COMMONS,StrUtils, ComCtrls, ExtCtrls, JSON; type TfrmSettings = class(TForm) edtSearch: TEdit; btnSearch: TButton; lstSettings: TListBox; edtSettings: TLabeledEdit; Label1: TLabel; Panel1: TPanel; btnSave: TButton; procedure FormCreate(Sender: TObject); procedure btnSearchClick(Sender: TObject); procedure lstSettingsClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure edtSettingsChange(Sender: TObject); private procedure SelectField(index:integer); procedure RefreashFields(); procedure LoadSettings; var dicSettings : DictObject; public { Public declarations } end; var frmSettings: TfrmSettings; implementation {$R *.dfm} procedure TfrmSettings.btnSaveClick(Sender: TObject); begin JSONParser.JSONSave(dicSettings,'settings.json'); end; procedure TfrmSettings.btnSearchClick(Sender: TObject); var index:integer; begin index := dicSettings.toObject.keys.findIf(edtSearch.Text,Strings.Equivalent); if index <> -1 then begin SelectField(index); end; end; procedure TfrmSettings.edtSettingsChange(Sender: TObject); begin dicSettings.toObject.values[lstSettings.ItemIndex].toString := edtSettings.Text; end; procedure TfrmSettings.FormCreate(Sender: TObject); begin LoadSettings; RefreashFields; end; procedure TfrmSettings.LoadSettings; begin dicSettings := JSONParser.FileParse('settings.json'); end; procedure TfrmSettings.lstSettingsClick(Sender: TObject); begin SelectField(lstSettings.ItemIndex); end; procedure TfrmSettings.RefreashFields; var value:string; begin lstSettings.Items.Clear; for value in dicSettings.toObject.keys.container do lstSettings.Items.Add(value); SelectField(-1); end; procedure TfrmSettings.SelectField(index: integer); begin lstSettings.ItemIndex := index; if index <> -1 then begin edtSettings.EditLabel.Caption := 'Setting: '+dicSettings.toObject.keys[index]; edtSettings.Text := dicSettings.toObject.values[index].toString; end else begin edtSettings.EditLabel.Caption := 'Setting'; edtSettings.Text := ''; end; end; end.
unit cadastro; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) lbCadastro: TLabel; edCodigo: TEdit; edNome: TEdit; edEndereco: TEdit; edQtdeFilhos: TEdit; edSalario: TEdit; edNascimento: TEdit; edEmail: TEdit; lbCodigo: TLabel; lbNome: TLabel; lbEndereco: TLabel; lbQtdeFilhos: TLabel; lbSalario: TLabel; lbNascimento: TLabel; lbEmail: TLabel; btIncluir: TButton; btAlterar: TButton; btConsultar: TButton; btExcluir: TButton; btVelho: TButton; btSalario: TButton; btLimpar: TButton; btSair: TButton; btFilhos: TButton; procedure btIncluirClick(Sender: TObject); procedure btConsultarClick(Sender: TObject); procedure btLimparClick(Sender: TObject); procedure btSairClick(Sender: TObject); procedure btAlterarClick(Sender: TObject); procedure btSalarioClick(Sender: TObject); procedure btVelhoClick(Sender: TObject); procedure btFilhosClick(Sender: TObject); procedure btExcluirClick(Sender: TObject); private { Private declarations } public { Public declarations } end; tCadastro = Record Codigo: integer; Nome: string[20]; Endereco: string[30]; Email: string[20]; Nascimento: tDate; QtdeFilhos: integer; Salario: real; end; const max = 3; var Form1: TForm1; vCadastro: array [1..max] of tCadastro; implementation {$R *.dfm} function GetCurrentDateTime: TDateTime; var SystemTime: TSystemTime; begin GetLocalTime(SystemTime); Result := SystemTimeToDateTime(SystemTime); end; procedure TForm1.btIncluirClick(Sender: TObject); var i: integer; begin try i := StrToInt(edCodigo.text); vCadastro[i].Codigo := StrToInt(edCodigo.text); except ShowMessage('Digite um código válido.'); edCodigo.SetFocus; end; try vCadastro[i].Nome := edNome.text; except ShowMessage('Digite um nome válido.'); edNome.SetFocus; end; try vCadastro[i].Endereco := edEndereco.text; except ShowMessage('Digite um endereço válido.'); edEndereco.SetFocus; end; try vCadastro[i].Email := edEmail.text; except ShowMessage('Digite um e-mail válido.'); edEmail.SetFocus; end; try if (StrToDate(edNascimento.text) < GetCurrentDateTime) then vCadastro[i].Nascimento := StrToDate(edNascimento.text); except ShowMessage('Digite uma data de nascimento válida.'); edNascimento.SetFocus; end; try if StrToInt(edQtdeFilhos.text) >= 0 then vCadastro[i].QtdeFilhos := StrToInt(edQtdeFilhos.text); except ShowMessage('Digite uma quantidade de filhos válida.'); edQtdeFilhos.SetFocus; end; try if StrToFloat(edSalario.text) >= 0 then vCadastro[i].Salario := StrToInt(edSalario.text); except ShowMessage('Digite um valor de salário válido.'); edSalario.SetFocus; end; end; procedure TForm1.btConsultarClick(Sender: TObject); var i: integer; begin try i := StrToInt(edCodigo.Text); if (vCadastro[i].Codigo = 0) then begin showmessage('Nenhum funcionário cadastrado.'); end else begin edCodigo.Text := IntToStr(vCadastro[i].Codigo); edNome.Text := vCadastro[i].Nome; edEndereco.Text := vCadastro[i].Endereco; edEmail.Text := vCadastro[i].Email; edNascimento.Text := DateToStr(vCadastro[i].Nascimento); edSalario.Text := FloatToStr(vCadastro[i].Salario); edQtdeFilhos.Text := IntToStr(vCadastro[i].QtdeFilhos); end; except showmessage('Digite um código válido.'); edCodigo.SetFocus; end; end; procedure TForm1.btLimparClick(Sender: TObject); begin edCodigo.Clear; edNome.Clear; edEndereco.Clear; edEmail.Clear; edNascimento.Clear; edSalario.Clear; edQtdeFilhos.Clear; edCodigo.SetFocus; end; procedure TForm1.btSairClick(Sender: TObject); begin Close; end; procedure TForm1.btAlterarClick(Sender: TObject); var i: integer; begin try i := StrToInt(edCodigo.text); vCadastro[i].Codigo := StrToInt(edCodigo.text); except ShowMessage('Digite um código válido.'); edCodigo.SetFocus; end; try vCadastro[i].Nome := edNome.text; except ShowMessage('Digite um nome válido.'); edNome.SetFocus; end; try vCadastro[i].Endereco := edEndereco.text; except ShowMessage('Digite um endereço válido.'); edEndereco.SetFocus; end; try vCadastro[i].Email := edEmail.text; except ShowMessage('Digite um e-mail válido.'); edEmail.SetFocus; end; try if (StrToDate(edNascimento.text) < GetCurrentDateTime) then vCadastro[i].Nascimento := StrToDate(edNascimento.text); except ShowMessage('Digite uma data de nascimento válida.'); edNascimento.SetFocus; end; try if StrToInt(edQtdeFilhos.text) >= 0 then vCadastro[i].QtdeFilhos := StrToInt(edQtdeFilhos.text); except ShowMessage('Digite uma quantidade de filhos válida.'); edQtdeFilhos.SetFocus; end; try if StrToFloat(edSalario.text) >= 0 then vCadastro[i].Salario := StrToInt(edSalario.text); except ShowMessage('Digite um valor de salário válido.'); edSalario.SetFocus; end; end; procedure TForm1.btSalarioClick(Sender: TObject); var i,j: integer; maior: real; begin maior := 0; for i := 1 to max do begin if (maior < vCadastro[i].Salario) then begin maior := vCadastro[i].Salario; j := i; end; end; edCodigo.Text := IntToStr(vCadastro[j].Codigo); edNome.Text := vCadastro[j].Nome; edEndereco.Text := vCadastro[j].Endereco; edEmail.Text := vCadastro[j].Email; edNascimento.Text := DateToStr(vCadastro[j].Nascimento); edSalario.Text := FloatToStr(vCadastro[j].Salario); edQtdeFilhos.Text := IntToStr(vCadastro[j].QtdeFilhos); end; procedure TForm1.btVelhoClick(Sender: TObject); var i,j: integer; velho: TDate; begin velho := GetCurrentDateTime; for i := 1 to max do begin if (velho > vCadastro[i].Nascimento) then begin velho := vCadastro[i].Nascimento; j := i; end; end; edCodigo.Text := IntToStr(vCadastro[j].Codigo); edNome.Text := vCadastro[j].Nome; edEndereco.Text := vCadastro[j].Endereco; edEmail.Text := vCadastro[j].Email; edNascimento.Text := DateToStr(vCadastro[j].Nascimento); edSalario.Text := FloatToStr(vCadastro[j].Salario); edQtdeFilhos.Text := IntToStr(vCadastro[j].QtdeFilhos); end; procedure TForm1.btFilhosClick(Sender: TObject); var i,j: integer; filhos: integer; begin filhos := 0; for i := 1 to max do begin if (filhos < vCadastro[i].QtdeFilhos) then begin filhos := vCadastro[i].QtdeFilhos; j := i; end; end; edCodigo.Text := IntToStr(vCadastro[j].Codigo); edNome.Text := vCadastro[j].Nome; edEndereco.Text := vCadastro[j].Endereco; edEmail.Text := vCadastro[j].Email; edNascimento.Text := DateToStr(vCadastro[j].Nascimento); edSalario.Text := FloatToStr(vCadastro[j].Salario); edQtdeFilhos.Text := IntToStr(vCadastro[j].QtdeFilhos); end; procedure TForm1.btExcluirClick(Sender: TObject); var i: integer; begin try i := StrToInt(edCodigo.Text); except showmessage('Digite um código válido.'); edCodigo.SetFocus; end; vCadastro[i].Codigo := 0; vCadastro[i].Nome := ''; vCadastro[i].Endereco := ''; vCadastro[i].Email := ''; vCadastro[i].Nascimento := 0; vCadastro[i].Salario := 0; vCadastro[i].QtdeFilhos := 0; edCodigo.Clear; edNome.Clear; edEndereco.Clear; edEmail.Clear; edNascimento.Clear; edSalario.Clear; edQtdeFilhos.Clear; edCodigo.SetFocus; end; end.
unit uContinent; interface type TContinent = ( ctAfrica, ctAsia, ctEurope, ctAmerica, cdAntarctica, ctOceania ); TContinentHelper = record helper for TContinent function AsLabel: string; function AsString: string; function AsByte: SmallInt; function Parse(const pContinent: SmallInt): TContinent; end; Const TContinents: TArray<TContinent> =[ ctAfrica, ctAsia, ctEurope, ctAmerica, cdAntarctica, ctOceania ]; implementation { TContinentHelper } function TContinentHelper.AsByte: SmallInt; begin Result := SmallInt(Self); end; function TContinentHelper.AsLabel: string; begin case self of ctAfrica: Result := 'Africa'; ctAsia: Result := 'Asia'; ctEurope: Result := 'Europe'; ctAmerica: Result := 'America'; cdAntarctica: Result := 'Antarctica'; ctOceania: Result := 'Oceania'; end; end; function TContinentHelper.AsString: string; begin case self of ctAfrica: Result := 'ctAfrica'; ctAsia: Result := 'ctAsia'; ctEurope: Result := 'ctEurope'; ctAmerica: Result := 'ctAmerica'; cdAntarctica: Result := 'cdAntarctica'; ctOceania: Result := 'ctOceania'; end; end; function TContinentHelper.Parse(const pContinent: SmallInt): TContinent; begin Result := TContinent(pContinent); end; end.
unit uBringToSecond; //-------------------------------------------------------------[ in0k (c) 2018 ] // // Перемещение "Окна" (tForm) на ВТОРОЙ план // //--- Схема работы функции на примере ------------------------------------------ // // Z-Index // // 0 Wnd00 +-> Wnd_A Wnd_A // 1 Wnd01 | Wnd00 +-> Wnd_B // 2 ... | Wnd01 | Wnd00 // 3 ... | ... | Wnd01 // ... ... | ... | // N Wnd_A.bringToFront-^ ... | // M ... bringToSecond(Wnd_B)-----^ // ... ... ... // ............................................................... // DeskTop DeskTop DeskTop DeskTop DeskTop DeskTop DeskTop DeskTop // //----------------------------------------------------------------------------// {%region --- Выбираем РЕАЛИзацИЮ --- /fold } {$unDef b2sp_implementation_selected} //--- #0. по ЦЕЛЕВОЙ платформе {$If DEFINED(MSWINDOWS)} {$IF DEFINED(LCLWin32) or DEFINED(LCLWin64)} {$define b2sp_implementation_WIN}{$define b2sp_implementation_selected} {$elseIf DEFINED(LCLqt) or DEFINED(LCLqt5)} {$define b2sp_implementation_WIN}{$define b2sp_implementation_selected} {$elseIf DEFINED(LCLgtk2)} {$define b2sp_implementation_WIN}{$define b2sp_implementation_selected} {$endIF} {$endIF} //--- #1. по ЦЕЛЕВЫМ виджитам {$ifNdef b2sp_implementation_selected} // видимо нативно через ВИДЖИТЫ {$if DEFINED(LCLqt) or DEFINED(LCLqt5)} {$define b2sp_implementation_QtX}{$define b2sp_implementation_SET} {$elseIf DEFINED(LCLgtk2) or DEFINED(LCLgtk3)} {$define b2sp_implementation_GtkX}{$define b2sp_implementation_SET} {$endIF} {$endIF} {%endRegion -------------------------------------------------------------} //----------------------------------------------------------------------------// {$mode objfpc}{$H+} interface uses Forms, {$if defined(b2sp_implementation_WIN) } uBringToSecond_WIN {$elseif defined(b2sp_implementation_QtX) } // теперь надо определить, можно ли использовать X11 НАПРЯМУЮ {$if DEFINED(LCLqt5)} {%region --- воровано `qt56.pas` /fold } {$IFDEF MSWINDOWS} {$ELSE} {$IFDEF DARWIN} {$LINKFRAMEWORK Qt5Pas} {$ELSE} {$IF DEFINED(LINUX) or DEFINED(FREEBSD) or DEFINED(NETBSD)} {$DEFINE BINUX} {$ENDIF} {$ENDIF} {$ENDIF} {%endRegion} {$elseif DEFINED(LCLqt)} {%region --- воровано `qt45.pas` /fold } {$IFNDEF QTOPIA} {$IF DEFINED(LINUX) or DEFINED(FREEBSD) or DEFINED(NETBSD)} {$DEFINE BINUX} {$ENDIF} {$ENDIF} {%endRegion} {$endif} //-- выбор реализаии {$if defined(BINUX)} {$define b2sp_implementation_X11} uBringToSecond_X11 {$else} uBringToSecond_QtX {$endif} {$elseif defined(b2sp_implementation_GtkX)} // теперь надо определить, можно ли использовать X11 НАПРЯМУЮ {$if DEFINED(LCLgtk3)} // буду копать по необходимости {$elseif DEFINED(LCLgtk2)} {%region --- воровано `gtk2defines.inc` /fold } {off $define UseX} {$ifdef Unix} // on darwin we try to use native gtk {$ifdef Darwin} {$ifdef UseX} // it can be overridden {$define HasX} {$endif} {$else} {$define HasX} {$endif} {$endif} {%endRegion} {$endif} //-- выбор реализаии {$if defined(HasX)} {$define b2sp_implementation_X11} uBringToSecond_X11 {$else} uBringToSecond_GtkX {$endif} {$else}{шансов НЕТ .. вариант по умолчанию} bringToSecond_LCL {$note --------------------------------------------------------------------} {$note in0k-bringToSecondPlane: The basic cross-platform version is used. } {$note Can work slowly and with flicker. } {$note --------------------------------------------------------------------} {$endIF}; {$ifOpt D+} const cBringToSecondUNIT= {$if defined(b2sp_implementation_WIN) } 'uBringToSecond_WIN' {$elseif defined(b2sp_implementation_X11) } 'uBringToSecond_X11' {$elseif defined(b2sp_implementation_QtX) } 'uBringToSecond_QtX' {$elseif defined(b2sp_implementation_GtkX)} 'uBringToSecond_GtkX' {$else}'uBringToSecond_LCL'{$endIF}; {$endIF} procedure bringToSecond(const form:TCustomForm); implementation procedure bringToSecond(const form:TCustomForm); begin {$ifOPT D+} Assert(Assigned(form),'`form`: must be defined'); {$endIf} {$if defined(b2sp_implementation_WIN)} uBringToSecond_WIN.bringToSecond(form); {$elseif defined(b2sp_implementation_X11)} uBringToSecond_X11.bringToSecond(form); {$elseif defined(b2sp_implementation_QtX)} uBringToSecond_QtX.bringToSecond(form); {$elseif defined(b2sp_implementation_GtkX)} uBringToSecond_GtkX.bringToSecond(form); {$else} uBringToSecond_LCL.bringToSecond(form); {$endIF} end; end.
unit sFamilyMgr; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uGlobal, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinCaramel, dxSkinscxPC3Painter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxLabel, ADODB, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, Menus, StdCtrls, cxButtons; type TfrmFamilyMgr = class(TForm) cxGrid1: TcxGrid; cxGFamily: TcxGridDBTableView; cxGFamilyRelationshipName: TcxGridDBColumn; cxGFamilyFamilyName: TcxGridDBColumn; cxGFamilyInMate: TcxGridDBColumn; cxGFamilyHealth: TcxGridDBColumn; cxGFamilyETC: TcxGridDBColumn; cxGrid1Level1: TcxGridLevel; adoFamily: TADOQuery; dsFamily: TDataSource; btnFamilyAppend: TcxButton; btnFamilyUpdate: TcxButton; btnFamilyDelete: TcxButton; btnClose: TcxButton; procedure btnFamilyAppendClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnFamilyUpdateClick(Sender: TObject); procedure dsFamilyDataChange(Sender: TObject; Field: TField); procedure btnFamilyDeleteClick(Sender: TObject); private { Private declarations } procedure SetControls; public { Public declarations } Modified: Boolean; oInOut: TInOutInfo; end; var frmFamilyMgr: TfrmFamilyMgr; implementation uses uConfig, uDB, uFamilyInput; {$R *.dfm} procedure TfrmFamilyMgr.btnFamilyAppendClick(Sender: TObject); var oInput: TfrmFamilyInput; nFamilyID: integer; begin if not adoFamily.Active then Exit; Application.CreateForm(TfrmFamilyInput, oInput); oInput.Relation.Clear; if oInput.ShowModal = mrOK then begin adoFamily.DisableControls; try adoFamily.Connection.BeginTrans; adoFamily.Append; adoFamily.FieldByName('HospitalID').AsInteger := oInOut.nHospitalID; adoFamily.FieldByName('PatientID').AsString := oInOut.sPatientID; adoFamily.FieldByName('InDate').AsString := oInOut.sInDate; adoFamily.FieldByName('FamilyName').AsString := oInput.Relation.FamilyName; adoFamily.FieldByName('InMate').AsBoolean := oInput.Relation.InMate; adoFamily.FieldByName('Health').AsString := oInput.Relation.Health; adoFamily.FieldByName('Pay').AsBoolean := oInput.Relation.Pay; adoFamily.FieldByName('RelationshipID').AsInteger := oInput.Relation.RelationshipID; adoFamily.Post; adoFamily.Connection.CommitTrans; nFamilyID := adoFamily.FieldByName('FamilyID').AsInteger; adoFamily.Close; adoFamily.Open; adoFamily.Locate('FamilyID', nFamilyID, [loCaseInsensitive]); oGlobal.Msg('추가하였습니다!'); Modified := True; except adoFamily.Cancel; adoFamily.Connection.RollbackTrans; oGlobal.Msg('추가하지 못햇습니다!'); end; adoFamily.EnableControls; end; oInput.Free; end; procedure TfrmFamilyMgr.btnFamilyDeleteClick(Sender: TObject); begin if adoFamily.IsEmpty then Exit; if oGlobal.YesNo('삭제하시겠습니까?') <> mrYes then Exit; try adoFamily.Delete; oGlobal.Msg('삭제하였습니다!'); Modified := True; except adoFamily.Cancel; oGlobal.Msg('삭제하지 못했습니다!'); end; end; procedure TfrmFamilyMgr.btnFamilyUpdateClick(Sender: TObject); var oInput: TfrmFamilyInput; begin if adoFamily.IsEmpty then Exit; Application.CreateForm(TfrmFamilyInput, oInput); oInput.Relation.Clear; oInput.Relation.FamilyName := adoFamily.FieldByName('FamilyName').AsString; oInput.Relation.Health := adoFamily.FieldByName('Health').AsString; oInput.Relation.InMate := adoFamily.FieldByName('InMate').AsBoolean; oInput.Relation.Pay := adoFamily.FieldByName('Pay').AsBoolean; oInput.Relation.RelationshipID := adoFamily.FieldByName('RelationshipID').AsInteger; oInput.Relation.RelationshipName := adoFamily.FieldByName('RelationshipName').AsString; if oInput.ShowModal = mrOK then begin adoFamily.DisableControls; try adoFamily.Connection.BeginTrans; adoFamily.Edit; adoFamily.FieldByName('FamilyName').AsString := oInput.Relation.FamilyName; adoFamily.FieldByName('InMate').AsBoolean := oInput.Relation.InMate; adoFamily.FieldByName('Health').AsString := oInput.Relation.Health; adoFamily.FieldByName('Pay').AsBoolean := oInput.Relation.Pay; adoFamily.FieldByName('RelationshipID').AsInteger := oInput.Relation.RelationshipID; adoFamily.Post; adoFamily.Connection.CommitTrans; oGlobal.Msg('수정하였습니다!'); Modified := True; except adoFamily.Cancel; adoFamily.Connection.RollbackTrans; oGlobal.Msg('수정하지 못햇습니다!'); end; adoFamily.EnableControls; end; oInput.Free; end; procedure TfrmFamilyMgr.dsFamilyDataChange(Sender: TObject; Field: TField); begin SetControls; end; procedure TfrmFamilyMgr.FormShow(Sender: TObject); begin Modified := False; try adoFamily.SQL.Text := 'select *' + ' ,(select RelationshipName from Relationships where Relationships.RelationshipID = families.RelationshipID) as RelationshipName' + ' from families' + ' where HospitalID=' + inttostr(oInOut.nHospitalID) + ' and PatientID=''' + oInOut.sPatientID + '''' + ' and Indate=''' + oInOut.sInDate + ''''; adoFamily.Open; except oGlobal.Msg('가족관계정보에 접근할 수 없습니다!'); Close; end; end; procedure TfrmFamilyMgr.SetControls; begin btnFamilyAppend.Enabled := adoFamily.Active; btnFamilyUpdate.Enabled := not adoFamily.IsEmpty; btnFamilyDelete.Enabled := not adoFamily.IsEmpty; end; end.
unit URepositorioCliente; interface uses URepositorioDB , UCliente , SqlExpr ; type TRepositorioCliente = class(TRepositorioDB<TCLIENTE>) protected //Atribui os dados do banco no objeto procedure AtribuiDBParaEntidade(const coCLIENTE: TCLIENTE); override; //Atribui os dados do objeto no banco procedure AtribuiEntidadeParaDB(const coCLIENTE: TCLIENTE; const coSQLQuery: TSQLQuery); override; public constructor Create; end; implementation { TRepositorioUsuario } uses UEntidade , UMensagens , SysUtils ; { TRepositorioCliente } procedure TRepositorioCliente.AtribuiDBParaEntidade(const coCLIENTE: TCLIENTE); begin inherited; //Pessoal: coCLIENTE.NOME := FSQLSelect.FieldByName(FLD_CLIENTE_NOME).AsString; coCLIENTE.CPF := FSQLSelect.FieldByName(FLD_CLIENTE_CPF).AsString; coCLIENTE.RG := FSQLSelect.FieldByName(FLD_CLIENTE_RG).AsString; coCLIENTE.DATA_NASCIMENTO := FSQLSelect.FieldByName(FLD_CLIENTE_DATA_NASCIMENTO).AsDateTime; //Contato: coCLIENTE.RESIDENCIAL := FSQLSelect.FieldByName(FLD_CLIENTE_RESIDENCIAL).AsString; coCLIENTE.COMERCIAL := FSQLSelect.FieldByName(FLD_CLIENTE_COMERCIAL).AsString; coCLIENTE.CELULAR := FSQLSelect.FieldByName(FLD_CLIENTE_CELULAR).AsString; coCLIENTE.RECADO := FSQLSelect.FieldByName(FLD_CLIENTE_RECADO).AsString; coCLIENTE.EMAIL := FSQLSelect.FieldByName(FLD_CLIENTE_EMAIL).AsString; //Enderešo: coCLIENTE.RUA := FSQLSelect.FieldByName(FLD_CLIENTE_RUA).AsString; coCLIENTE.NUMERO := FSQLSelect.FieldByName(FLD_CLIENTE_NUMERO).AsString; coCLIENTE.BAIRRO := FSQLSelect.FieldByName(FLD_CLIENTE_BAIRRO).AsString; coCLIENTE.CIDADE := FSQLSelect.FieldByName(FLD_CLIENTE_CIDADE).AsString; coCLIENTE.UF := FSQLSelect.FieldByName(FLD_CLIENTE_UF).AsString; coCLIENTE.COMPLEMENTO := FSQLSelect.FieldByName(FLD_CLIENTE_COMPLEMENTO).AsString; coCLIENTE.PONTO_REFERENCIA := FSQLSelect.FieldByName(FLD_CLIENTE_PONTO_REFERENCIA).AsString; end; procedure TRepositorioCliente.AtribuiEntidadeParaDB(const coCLIENTE: TCLIENTE; const coSQLQuery: TSQLQuery); begin inherited; //Pessoal: coSQLQuery.ParamByName(FLD_CLIENTE_NOME).AsString := coCLIENTE.NOME; coSQLQuery.ParamByName(FLD_CLIENTE_CPF).AsString := coCLIENTE.CPF; coSQLQuery.ParamByName(FLD_CLIENTE_RG).AsString := coCLIENTE.RG; coSQLQuery.ParamByName(FLD_CLIENTE_DATA_NASCIMENTO).AsDate := coCLIENTE.DATA_NASCIMENTO; //Contato: coSQLQuery.ParamByName(FLD_CLIENTE_RESIDENCIAL).AsString := coCLIENTE.RESIDENCIAL; coSQLQuery.ParamByName(FLD_CLIENTE_COMERCIAL).AsString := coCLIENTE.COMERCIAL; coSQLQuery.ParamByName(FLD_CLIENTE_CELULAR).AsString := coCLIENTE.CELULAR; coSQLQuery.ParamByName(FLD_CLIENTE_RECADO).AsString := coCLIENTE.RECADO; coSQLQuery.ParamByName(FLD_CLIENTE_EMAIL).AsString := coCLIENTE.EMAIL; //Enderešo: coSQLQuery.ParamByName(FLD_CLIENTE_RUA).AsString := coCLIENTE.RUA; coSQLQuery.ParamByName(FLD_CLIENTE_NUMERO).AsString := coCLIENTE.NUMERO; coSQLQuery.ParamByName(FLD_CLIENTE_BAIRRO).AsString := coCLIENTE.BAIRRO; coSQLQuery.ParamByName(FLD_CLIENTE_CIDADE).AsString := coCLIENTE.CIDADE; coSQLQuery.ParamByName(FLD_CLIENTE_UF).AsString := coCLIENTE.UF; coSQLQuery.ParamByName(FLD_CLIENTE_COMPLEMENTO).AsString := coCLIENTE.COMPLEMENTO; coSQLQuery.ParamByName(FLD_CLIENTE_PONTO_REFERENCIA).AsString := coCLIENTE.PONTO_REFERENCIA; end; constructor TRepositorioCliente.Create; begin Inherited Create(TCLIENTE, TBL_CLIENTE, FLD_ENTIDADE_ID, STR_CLIENTE); end; end.
unit DefaultUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type { TDefaultForm } TDefaultForm = class(TForm) procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } protected procedure CtrlEnterPressed; virtual; public { Public declarations } end; var DefaultForm: TDefaultForm; implementation {$R *.dfm} { TDefaultForm } procedure TDefaultForm.CtrlEnterPressed; begin if fsModal in FormState then ModalResult := mrOk; end; procedure TDefaultForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var WinControl: TWinControl; begin if (Key = VK_RETURN) and (Shift = []) then begin WinControl := FindNextControl(ActiveControl, True, True, False); if WinControl <> nil then begin WinControl.SetFocus; Key := 0; end; Exit; end; if (Key = VK_RETURN) and (Shift = [ssCtrl]) then begin CtrlEnterPressed; Key := 0; Exit; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [FOLHA_PLANO_SAUDE] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit FolhaPlanoSaudeVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ViewPessoaColaboradorVO, OperadoraPlanoSaudeVO; type [TEntity] [TTable('FOLHA_PLANO_SAUDE')] TFolhaPlanoSaudeVO = class(TVO) private FID: Integer; FID_OPERADORA_PLANO_SAUDE: Integer; FID_COLABORADOR: Integer; FDATA_INICIO: TDateTime; FBENEFICIARIO: String; //Transientes FColaboradorNome: String; FOperadoraNome: String; FColaboradorVO: TViewPessoaColaboradorVO; FOperadoraPlanoSaudeVO: TOperadoraPlanoSaudeVO; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_OPERADORA_PLANO_SAUDE', 'Id Operadora Plano Saude', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdOperadoraPlanoSaude: Integer read FID_OPERADORA_PLANO_SAUDE write FID_OPERADORA_PLANO_SAUDE; [TColumnDisplay('OPERADORA_PLANO_SAUDE.NOME', 'Operadora', 250, [ldGrid, ldLookup, ldComboBox], ftString, 'OperadoraPlanoSaudeVO.TOperadoraPlanoSaudeVO', True)] property OperadoraNome: String read FOperadoraNome write FOperadoraNome; [TColumn('ID_COLABORADOR', 'Id Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR; [TColumnDisplay('COLABORADOR.NOME', 'Colaborador', 250, [ldGrid, ldLookup, ldCombobox], ftString, 'ViewPessoaColaboradorVO.TViewPessoaColaboradorVO', True)] property ColaboradorNome: String read FColaboradorNome write FColaboradorNome; [TColumn('DATA_INICIO', 'Data Inicio', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInicio: TDateTime read FDATA_INICIO write FDATA_INICIO; [TColumn('BENEFICIARIO', 'Beneficiario', 8, [ldGrid, ldLookup, ldCombobox], False)] property Beneficiario: String read FBENEFICIARIO write FBENEFICIARIO; //Transientes [TAssociation('ID', 'ID_COLABORADOR')] property ColaboradorVO: TViewPessoaColaboradorVO read FColaboradorVO write FColaboradorVO; [TAssociation('ID', 'ID_OPERADORA_PLANO_SAUDE')] property OperadoraPlanoSaudeVO: TOperadoraPlanoSaudeVO read FOperadoraPlanoSaudeVO write FOperadoraPlanoSaudeVO; end; implementation constructor TFolhaPlanoSaudeVO.Create; begin inherited; FColaboradorVO := TViewPessoaColaboradorVO.Create; FOperadoraPlanoSaudeVO := TOperadoraPlanoSaudeVO.Create; end; destructor TFolhaPlanoSaudeVO.Destroy; begin FreeAndNil(FColaboradorVO); FreeAndNil(FOperadoraPlanoSaudeVO); inherited; end; initialization Classes.RegisterClass(TFolhaPlanoSaudeVO); finalization Classes.UnRegisterClass(TFolhaPlanoSaudeVO); end.
unit UMainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, LCLType, LCLIntf, {$IFDEF WINDOWS} windows, {$ENDIF} BZHotKeyManager; type { TMainForm } TMainForm = class(TForm) Label1 : TLabel; Label2 : TLabel; Panel1 : TPanel; Image1 : TImage; procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); private HotKeyManager : TBZHotKeyManager; procedure processHotKey(Sender:TObject); public end; var MainForm : TMainForm; implementation {$R *.lfm} { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); var modifiers,key:word; idx:integer; begin modifiers := (MOD_CONTROL + MOD_ALT); key := VK_G; HotKeyManager:=TBZHotKeyManager.Create(self); idx:=HotKeyManager.AddHotKey(HotKeyManager.CreateHotKey(modifiers,Key)); if idx>-1 then HotKeyManager.HotKeys[idx].OnExecute:=@processHotKey else ShowMessage('Il y a une erreur'); HotKeyManager.Active := True; end; procedure TMainForm.FormDestroy(Sender : TObject); begin FreeAndNil(HotKeyManager); end; procedure TMainForm.processHotKey(Sender:TObject); begin Panel1.Visible := True; WindowState:=wsMaximized; end; end.
unit SeisMaterial; interface uses BaseObjects, Registrator, Classes, Material, Structure, ComCtrls, Ex_Grid; type // тип сейс работ TSeisWorkType = class (TRegisteredIDObject) public constructor Create(ACollection: TIDObjects); override; end; TSeisWorkTypes = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TSeisWorkType; public property Items[Index: Integer]: TSeisWorkType read GetItems; constructor Create; override; end; // метод сейс работ TSeisWorkMethod = class (TRegisteredIDObject) public function Update(ACollection: TIDObjects=nil):Integer;override; constructor Create(ACollection: TIDObjects); override; end; TSeisWorkMethods = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TSeisWorkMethod; public property Items[Index: Integer]: TSeisWorkMethod read GetItems; constructor Create; override; end; // сейсмопартия TSeisCrew = class (TRegisteredIDObject) private FSeisCrewNumber:Integer; protected procedure AssignTo(Dest: TPersistent); override; public property SeisCrewNumber: Integer read FSeisCrewNumber write FSeisCrewNumber; function List(AListOption: TListOption = loBrief): string; override; constructor Create(ACollection: TIDObjects); override; end; TSeisCrews = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TSeisCrew; public property Items[Index: Integer]: TSeisCrew read GetItems; constructor Create; override; end; // отчет сейсморазведки TSeismicMaterial = class (TRegisteredIDObject) private FSeisWorkType: TSeisWorkType; FSeisWorkMethod: TSeisWorkMethod; FSeisCrew: TSeisCrew; FSimpleDocument:TSimpleDocument; //FStructure:TStructure; FBeginWorksDate:TDateTime; FEndWorksDate:TDateTime; FReferenceComposition:string; FSeisWorkScale:Integer; FStructMapReflectHorizon:string; FCrossSection:string; protected procedure AssignTo(Dest: TPersistent); override; public property SeisWorkType: TSeisWorkType read FSeisWorkType write FSeisWorkType; property SeisWorkMethod: TSeisWorkMethod read FSeisWorkMethod write FSeisWorkMethod; property SeisCrew: TSeisCrew read FSeisCrew write FSeisCrew; property SimpleDocument: TSimpleDocument read FSimpleDocument write FSimpleDocument; property BeginWorksDate: TDateTime read FBeginWorksDate write FBeginWorksDate; property EndWorksDate: TDateTime read FEndWorksDate write FEndWorksDate; property ReferenceComposition: string read FReferenceComposition write FReferenceComposition; property SeisWorkScale: Integer read FSeisWorkScale write FSeisWorkScale; property StructMapReflectHorizon: string read FStructMapReflectHorizon write FStructMapReflectHorizon; property CrossSection: string read FCrossSection write FCrossSection; //property Structure:TStructure read FStructure write FStructure; function List(AListOption: TListOption = loBrief): string; override; constructor Create(ACollection: TIDObjects); override; end; TSeismicMaterials = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TSeismicMaterial; public property Items[Index: Integer]: TSeismicMaterial read GetItems; constructor Create; override; end; implementation uses Facade, SeisMaterialPoster,SysUtils; { TSeisWorkType } constructor TSeisWorkType.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Тип сейсморазведочных работ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSeisWorkTypeDataPoster]; end; { TTSeisWorkTypes } constructor TSeisWorkTypes.Create; begin inherited; FObjectClass := TSeisWorkType; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSeisWorkTypeDataPoster]; end; function TSeisWorkTypes.GetItems(Index: Integer): TSeisWorkType; begin Result := inherited Items[Index] as TSeisWorkType; end; { TSeisWorkMethod } constructor TSeisWorkMethod.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Метод сейсморазведочных работ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSeisWorkMethodDataPoster]; end; function TSeisWorkMethod.Update(ACollection: TIDObjects): Integer; begin Result:=inherited Update; end; { TSeisWorkMethods } constructor TSeisWorkMethods.Create; begin inherited; FObjectClass := TSeisWorkMethod; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSeisWorkMethodDataPoster]; end; function TSeisWorkMethods.GetItems(Index: Integer): TSeisWorkMethod; begin Result := inherited Items[Index] as TSeisWorkMethod; end; { TSeisCrew } procedure TSeisCrew.AssignTo(Dest: TPersistent); var o:TSeisCrew; begin inherited; o := Dest as TSeisCrew; o.FSeisCrewNumber:=SeisCrewNumber; end; constructor TSeisCrew.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Сейсмопартия'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSeisCrewDataPoster]; end; function TSeisCrew.List(AListOption: TListOption): string; begin Result:=IntToStr(SeisCrewNumber); end; { TSeisCrews } constructor TSeisCrews.Create; begin inherited; FObjectClass := TSeisCrew; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSeisCrewDataPoster]; end; function TSeisCrews.GetItems(Index: Integer): TSeisCrew; begin Result := inherited Items[Index] as TSeisCrew; end; { TSeismicMaterial } procedure TSeismicMaterial.AssignTo(Dest: TPersistent); var o:TSeismicMaterial; begin inherited; o := Dest as TSeismicMaterial; o.FSeisWorkType:=SeisWorkType; o.FSeisWorkMethod:=SeisWorkMethod; o.FSeisCrew:=SeisCrew; o.FSimpleDocument:=SimpleDocument; o.FBeginWorksDate:=BeginWorksDate; o.FEndWorksDate:=EndWorksDate; o.FReferenceComposition:=ReferenceComposition; o.FCrossSection:=CrossSection; o.FStructMapReflectHorizon:=StructMapReflectHorizon; o.FSeisWorkScale:=SeisWorkScale; end; constructor TSeismicMaterial.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Отчет о сейсморазведочных работах'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSeismicMaterialDataPoster]; end; function TSeismicMaterial.List(AListOption: TListOption): string; begin Result:=SimpleDocument.List; end; { TSeismicMaterials } constructor TSeismicMaterials.Create; begin inherited; FObjectClass := TSeismicMaterial; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSeismicMaterialDataPoster]; end; function TSeismicMaterials.GetItems(Index: Integer): TSeismicMaterial; begin Result := inherited Items[Index] as TSeismicMaterial; end; end.
unit GraphQL; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, StringSupport, TextUtilities, AdvObjects, AdvGenerics, AdvTextExtractors, AdvStringStreams, AdvVclStreams, ParserSupport, AdvJson; Type EGraphQLException = class (Exception); TGraphQLSelection = class; TGraphQLFragment = class; TGraphQLArgument = class; TGraphQLValue = class (TAdvObject) public Function Link : TGraphQLValue; overload; procedure write(str : TStringBuilder; indent : integer); virtual; function isValue(v : String): boolean; virtual; end; TGraphQLVariableValue = class (TGraphQLValue) private FValue : String; public Constructor Create(value : String); Function Link : TGraphQLVariableValue; overload; property Value : String read FValue write FValue; procedure write(str : TStringBuilder; indent : integer); override; function ToString : String; override; end; TGraphQLNumberValue = class (TGraphQLValue) private FValue : String; public Constructor Create(value : String); Function Link : TGraphQLNumberValue; overload; property Value : String read FValue write FValue; procedure write(str : TStringBuilder; indent : integer); override; function isValue(v : String): boolean; override; function ToString : String; override; end; TGraphQLNameValue = class (TGraphQLValue) private FValue : String; public Constructor Create(value : String); Function Link : TGraphQLValue; overload; property Value : String read FValue write FValue; procedure write(str : TStringBuilder; indent : integer); override; function isValue(v : String): boolean; override; function ToString : String; override; end; TGraphQLStringValue = class (TGraphQLValue) private FValue : String; public Constructor Create(value : String); Function Link : TGraphQLStringValue; overload; property Value : String read FValue write FValue; procedure write(str : TStringBuilder; indent : integer); override; function isValue(v : String): boolean; override; function ToString : String; override; end; TGraphQLObjectValue = class (TGraphQLValue) private FFields : TAdvList<TGraphQLArgument>; public Constructor Create; overload; override; Constructor Create(json : TJsonObject); overload; Destructor Destroy; override; Function Link : TGraphQLObjectValue; overload; property Fields : TAdvList<TGraphQLArgument> read FFields; function addField(name : String; isList : boolean) : TGraphQLArgument; procedure write(str : TStringBuilder; indent : integer); override; end; TGraphQLArgument = class (TAdvObject) private FName: String; FValues: TAdvList<TGraphQLValue>; FList: boolean; procedure write(str : TStringBuilder; indent : integer); procedure valuesFromNode(json : TJsonNode); public Constructor Create; overload; override; Constructor Create(name : String; value : TGraphQLValue); overload; Constructor Create(name : String; json : TJsonNode); overload; Destructor Destroy; override; Function Link : TGraphQLArgument; overload; property Name : String read FName write FName; property list : boolean read FList write FList; property Values : TAdvList<TGraphQLValue> read FValues; function hasValue(value : String) : boolean; procedure addValue(value : TGraphQLValue); end; TGraphQLDirective = class (TAdvObject) private FName: String; FArguments: TAdvList<TGraphQLArgument>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLDirective; overload; property Name : String read FName write FName; Property Arguments : TAdvList<TGraphQLArgument> read FArguments; end; TGraphQLField = class (TAdvObject) private FName: String; FSelectionSet: TAdvList<TGraphQLSelection>; FAlias: String; FArguments: TAdvList<TGraphQLArgument>; FDirectives: TAdvList<TGraphQLDirective>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLField; overload; property Alias : String read FAlias write FAlias; Property Name : String read FName write FName; Property Arguments : TAdvList<TGraphQLArgument> read FArguments; property Directives : TAdvList<TGraphQLDirective> read FDirectives; property SelectionSet : TAdvList<TGraphQLSelection> read FSelectionSet; function argument(name : String) : TGraphQLArgument; end; TGraphQLFragmentSpread = class (TAdvObject) private FName: String; FDirectives: TAdvList<TGraphQLDirective>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLFragmentSpread; overload; property Name : String read FName write FName; property Directives : TAdvList<TGraphQLDirective> read FDirectives; end; TGraphQLSelection = class (TAdvObject) private FField : TGraphQLField; FInlineFragment: TGraphQLFragment; FFragmentSpread: TGraphQLFragmentSpread; procedure SetField(const Value: TGraphQLField); procedure SetFragmentSpread(const Value: TGraphQLFragmentSpread); procedure SetInlineFragment(const Value: TGraphQLFragment); public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLSelection; overload; property field : TGraphQLField read FField write SetField; property FragmentSpread : TGraphQLFragmentSpread read FFragmentSpread write SetFragmentSpread; property InlineFragment : TGraphQLFragment read FInlineFragment write SetInlineFragment; end; TGraphQLVariable = class (TAdvObject) private FName: String; FDefaultValue: TGraphQLValue; FTypeName: String; procedure SetDefaultValue(const Value: TGraphQLValue); public Destructor Destroy; override; Function Link : TGraphQLVariable; overload; property Name : String read FName write FName; property TypeName : String read FTypeName write FTypeName; property DefaultValue : TGraphQLValue read FDefaultValue write SetDefaultValue; end; TGraphQLOperationType = (qglotQuery, qglotMutation); TGraphQLOperation = class (TAdvObject) private FName: String; FoperationType: TGraphQLOperationType; FSelectionSet: TAdvList<TGraphQLSelection>; FVariables: TAdvList<TGraphQLVariable>; FDirectives: TAdvList<TGraphQLDirective>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLOperation; overload; property operationType : TGraphQLOperationType read FoperationType write FoperationType; property Name : String read FName write FName; property Variables : TAdvList<TGraphQLVariable> read FVariables; property Directives : TAdvList<TGraphQLDirective> read FDirectives; property SelectionSet : TAdvList<TGraphQLSelection> read FSelectionSet; end; TGraphQLFragment = class (TAdvObject) private FName: String; FTypeCondition: String; FSelectionSet: TAdvList<TGraphQLSelection>; FDirectives: TAdvList<TGraphQLDirective>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLFragment; overload; property Name : String read FName write FName; property TypeCondition : String read FTypeCondition write FTypeCondition; property Directives : TAdvList<TGraphQLDirective> read FDirectives; property SelectionSet : TAdvList<TGraphQLSelection> read FSelectionSet; end; TGraphQLDocument = class (TAdvObject) private FFragments: TAdvList<TGraphQLFragment>; FOperations: TAdvList<TGraphQLOperation>; public Constructor Create; override; Destructor Destroy; override; Function Link : TGraphQLDocument; overload; property Operations : TAdvList<TGraphQLOperation> read FOperations; property Fragments : TAdvList<TGraphQLFragment> read FFragments; function fragment(name : String) : TGraphQLFragment; function operation(name : String) : TGraphQLOperation; end; TGraphQLPackage = class (TAdvObject) private FDocument: TGraphQLDocument; FOperationName: String; FVariables: TAdvList<TGraphQLArgument>; procedure SetDocument(const Value: TGraphQLDocument); public Constructor Create; overload; override; Constructor Create(document : TGraphQLDocument); overload; Destructor Destroy; override; function Link : TGraphQLPackage; overload; property Document : TGraphQLDocument read FDocument write SetDocument; property OperationName : String read FOperationName write FOperationName; property Variables : TAdvList<TGraphQLArgument> read FVariables; end; TGraphQLPunctuator = (gqlpBang, gqlpDollar, gqlpOpenBrace, gqlpCloseBrace, gqlpEllipse, gqlpColon, gqlpEquals, gqlpAt, gqlpOpenSquare, gqlpCloseSquare, gqlpOpenCurly, gqlpVertical, gqlpCloseCurly); const LITERALS_TGraphQLPunctuator : array [TGraphQLPunctuator] of String = ('!', '$', '(', ')', '...', ':', '=', '@', '[', ']', '{', '|', '}'); type TGraphQLLexType = (gqlltNull, gqlltName, gqlltPunctuation, gqlltString, gqlltNumber); // graphql documents are in unicode // ignore: BOM, tab, space, #10,#13, comma, comment TGraphQLParser = class (TAdvTextExtractor) private // lexer FToken : TStringBuilder; FPeek : String; FLexType: TGraphQLLexType; FLocation : TSourceLocation; Function getNextChar : Char; Procedure PushChar(ch : Char); procedure skipIgnore; procedure Next; function hasPunctuation(punc : String) : boolean; procedure consumePunctuation(punc : String); function hasName : boolean; overload; function hasName(name : String) : boolean; overload; function consumeName : String; overload; procedure consumeName(name : String); overload; function parseValue : TGraphQLValue; procedure parseFragmentInner(fragment: TGraphQLFragment); function parseFragmentSpread : TGraphQLFragmentSpread; function parseInlineFragment : TGraphQLFragment; function parseArgument : TGraphQLArgument; function parseVariable : TGraphQLVariable; function parseDirective : TGraphQLDirective; function parseField : TGraphQLField; function parseSelection : TGraphQLSelection; procedure parseOperationInner(op : TGraphQLOperation); function parseOperation(name : String) : TGraphQLOperation; function parseFragment: TGraphQLFragment; procedure parseDocument(doc : TGraphQLDocument); public Constructor Create; overload; override; Destructor Destroy; override; Function Link : TGraphQLParser; overload; class function parse(source : String) : TGraphQLPackage; overload; class function parse(source : TStream) : TGraphQLPackage; overload; class function parseFile(filename : String) : TGraphQLPackage; class function parseJson(source : TStream) : TGraphQLPackage; overload; end; implementation { TGraphQLArgument } constructor TGraphQLArgument.Create; begin inherited; FValues := TAdvList<TGraphQLValue>.create; end; procedure TGraphQLArgument.addValue(value: TGraphQLValue); begin FValues.Add(value); end; constructor TGraphQLArgument.Create(name: String; value: TGraphQLValue); begin Create; self.name := name; FValues.Add(value); end; constructor TGraphQLArgument.Create(name: String; json: TJsonNode); begin Create; self.name := name; valuesFromNode(json); end; destructor TGraphQLArgument.Destroy; begin FValues.Free; inherited; end; function TGraphQLArgument.hasValue(value: String): boolean; var v : TGraphQLValue; begin result := false; for v in FValues do if (v.isValue(value)) then exit(true); end; function TGraphQLArgument.Link: TGraphQLArgument; begin result := TGraphQLArgument(inherited Link); end; procedure TGraphQLArgument.valuesFromNode(json: TJsonNode); var v : TJsonNode; begin if json is TJsonString then values.Add(TGraphQLStringValue.Create(TJsonString(json).value)) else if json is TJsonNumber then values.Add(TGraphQLNumberValue.Create(TJsonNumber(json).value)) else if json is TJsonBoolean then values.Add(TGraphQLNameValue.Create(BooleanToString(TJsonBoolean(json).value).ToLower)) else if json is TJsonObject then values.Add(TGraphQLObjectValue.Create(TJsonObject(json))) else if json is TJsonArray then begin for v in TJsonArray(json) do valuesFromNode(v); end else raise EGraphQLException.Create('Unexpected JSON type for "'+name+'": '+json.ClassName) end; procedure TGraphQLArgument.write(str: TStringBuilder; indent : integer); var i : integer; Begin str.Append('"'); for i := 1 to length(name) do case name[i] of '"':str.Append('\"'); '\':str.Append('\\'); #13:str.Append('\r'); #10:str.Append('\n'); #09:str.Append('\t'); else if ord(name[i]) < 32 Then str.Append('\u'+inttohex(ord(name[i]), 4)) else str.Append(name[i]); End; str.Append('":'); if list then begin str.Append('['); for i := 0 to FValues.count - 1 do begin if (i > 0) then str.Append(','); FValues[i].write(str, indent); end; str.Append(']'); end else begin if Values.Count > 1 then raise EGraphQLException.Create('Internal error: non list "'+Name+'" has '+inttostr(values.Count)+' values'); if Values.Count = 0 then str.Append('null') else values[0].write(str, indent); end; end; { TGraphQLDirective } constructor TGraphQLDirective.Create; begin inherited; FArguments := TAdvList<TGraphQLArgument>.create; end; destructor TGraphQLDirective.Destroy; begin FArguments.Free; inherited; end; function TGraphQLDirective.Link: TGraphQLDirective; begin result := TGraphQLDirective(inherited Link); end; { TGraphQLField } function TGraphQLField.argument(name: String): TGraphQLArgument; var p : TGraphQLArgument; begin result := nil; for p in Arguments do if p.Name = name then exit(p); end; constructor TGraphQLField.Create; begin inherited; FSelectionSet := TAdvList<TGraphQLSelection>.create; FArguments := TAdvList<TGraphQLArgument>.create; FDirectives := TAdvList<TGraphQLDirective>.create; end; destructor TGraphQLField.Destroy; begin FSelectionSet.Free; FArguments.Free; FDirectives.Free; inherited; end; function TGraphQLField.Link: TGraphQLField; begin result := TGraphQLField(inherited Link); end; { TGraphQLFragmentSpread } constructor TGraphQLFragmentSpread.Create; begin inherited; FDirectives := TAdvList<TGraphQLDirective>.create; end; destructor TGraphQLFragmentSpread.Destroy; begin FDirectives.Free; inherited; end; function TGraphQLFragmentSpread.Link: TGraphQLFragmentSpread; begin result := TGraphQLFragmentSpread(inherited Link); end; { TGraphQLSelection } constructor TGraphQLSelection.Create; begin inherited; end; destructor TGraphQLSelection.Destroy; begin FField.Free; FInlineFragment.Free; FFragmentSpread.Free; inherited; end; function TGraphQLSelection.Link: TGraphQLSelection; begin result := TGraphQLSelection(inherited Link); end; procedure TGraphQLSelection.SetField(const Value: TGraphQLField); begin FField.Free; FField := Value; end; procedure TGraphQLSelection.SetFragmentSpread(const Value: TGraphQLFragmentSpread); begin FFragmentSpread.Free; FFragmentSpread := Value; end; procedure TGraphQLSelection.SetInlineFragment(const Value: TGraphQLFragment); begin FInlineFragment.Free; FInlineFragment := Value; end; { TGraphQLVariable } destructor TGraphQLVariable.Destroy; begin FDefaultValue.Free; inherited; end; function TGraphQLVariable.Link: TGraphQLVariable; begin result := TGraphQLVariable(inherited Link); end; procedure TGraphQLVariable.SetDefaultValue(const Value: TGraphQLValue); begin FDefaultValue.Free; FDefaultValue := Value; end; { TGraphQLOperation } constructor TGraphQLOperation.Create; begin inherited; FSelectionSet := TAdvList<TGraphQLSelection>.create; FVariables := TAdvList<TGraphQLVariable>.create; FDirectives := TAdvList<TGraphQLDirective>.create; end; destructor TGraphQLOperation.Destroy; begin FSelectionSet.Free; FVariables.Free; FDirectives.Free; inherited; end; function TGraphQLOperation.Link: TGraphQLOperation; begin result := TGraphQLOperation(inherited Link); end; { TGraphQLFragment } constructor TGraphQLFragment.Create; begin inherited; FSelectionSet := TAdvList<TGraphQLSelection>.create; FDirectives := TAdvList<TGraphQLDirective>.create; end; destructor TGraphQLFragment.Destroy; begin FSelectionSet.Free; FDirectives.free; inherited; end; function TGraphQLFragment.Link: TGraphQLFragment; begin result := TGraphQLFragment(inherited Link); end; { TGraphQLDocument } constructor TGraphQLDocument.Create; begin inherited; FFragments := TAdvList<TGraphQLFragment>.create; FOperations := TAdvList<TGraphQLOperation>.create; end; destructor TGraphQLDocument.Destroy; begin FFragments.Free; FOperations.Free; inherited; end; function TGraphQLDocument.fragment(name: String): TGraphQLFragment; var f : TGraphQLFragment; begin result := nil; for f in Fragments do if f.Name = name then exit(f); end; function TGraphQLDocument.Link: TGraphQLDocument; begin result := TGraphQLDocument(inherited Link); end; function TGraphQLDocument.operation(name: String): TGraphQLOperation; var o : TGraphQLOperation; begin result := nil; for o in Operations do if o.Name = name then exit(o); end; { TGraphQLParser } function TGraphQLParser.getNextChar: Char; begin if FPeek <> '' Then Begin result := FPeek[1]; Delete(FPeek, 1, 1); End Else begin result := ConsumeCharacter; if result = #10 then begin inc(FLocation.line); FLocation.col := 1; end else inc(FLocation.col); end; end; function TGraphQLParser.hasName: boolean; begin result := (FLexType = gqlltName) and (FToken.ToString <> ''); end; function TGraphQLParser.hasName(name: String): boolean; begin result := (FLexType = gqlltName) and (FToken.ToString = name); end; function TGraphQLParser.hasPunctuation(punc: String): boolean; begin result := (FLexType = gqlltPunctuation) and (FToken.ToString = punc); end; function TGraphQLParser.Link: TGraphQLParser; begin result := TGraphQLParser(inherited Link); end; function TGraphQLParser.consumeName: String; begin if FLexType <> gqlltName then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting a name'); result := FToken.ToString; next; end; procedure TGraphQLParser.Next; var ch : Char; hex : String; begin skipIgnore; FToken.Clear; if (not more and (FPeek = '')) then FLexType := gqlltNull else begin ch := getNextChar(); if StringArrayExistsSensitive(LITERALS_TGraphQLPunctuator, ch) then begin FLexType := gqlltPunctuation; FToken.Append(ch); end else if ch = '.' then begin repeat FToken.Append(ch); ch := getNextChar; until ch <> '.'; PushChar(ch); if (FToken.Length <> 3) then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting "..."'); end else if charInSet(ch, ['A'..'Z', 'a'..'z', '_']) then begin FLexType := gqlltName; repeat FToken.Append(ch); ch := getNextChar; until not charInSet(ch, ['A'..'Z', 'a'..'z', '_', '0'..'9']); pushChar(ch); end else if charInSet(ch, ['0'..'9', '-']) then begin FLexType := gqlltNumber; repeat FToken.Append(ch); ch := getNextChar; until not (charInSet(ch, ['0'..'9']) or ((ch = '.') and not FToken.ToString.Contains('.'))or ((ch = 'e') and not FToken.ToString.Contains('e'))); pushChar(ch); end else if (ch = '"') then begin FLexType := gqlltString; repeat ch := getNextChar; if (ch = '\') Then Begin if not More then raise EGraphQLException.Create('premature termination of GraphQL during a string constant'); ch := getNextChar; case ch of '"':FToken.Append('"'); '\':FToken.Append('\'); '/':FToken.Append('/'); 'n':FToken.Append(#10); 'r':FToken.Append(#13); 't':FToken.Append(#09); 'u': begin setLength(hex, 4); hex[1] := getNextChar; hex[2] := getNextChar; hex[3] := getNextChar; hex[4] := getNextChar; FToken.Append(chr(StrToInt('$'+hex))); end Else raise EGraphQLException.Create('not supported in GraphQL: \'+ch); End; ch := #0; End Else if (ch <> '"') then FToken.Append(ch); until not More or (ch = '"'); if ch <> '"' Then EGraphQLException.Create('premature termination of GraphQL during a string constant'); end else raise EGraphQLException.Create('Unexpected character "'+ch+'"'); end; end; class function TGraphQLParser.parse(source: String): TGraphQLPackage; var this : TGraphQLParser; stream : TAdvStringStream; doc : TGraphQLDocument; begin stream := TAdvStringStream.Create; try stream.Bytes := TENcoding.UTF8.GetBytes(source); this := TGraphQLParser.Create(stream.link); try this.next; doc := TGraphQLDocument.Create; try this.parseDocument(doc); result := TGraphQLPackage.create(doc.Link); finally doc.free; end; finally this.free; end; finally stream.Free; end; end; class function TGraphQLParser.parse(source: TStream): TGraphQLPackage; var this : TGraphQLParser; stream : TAdvVCLStream; doc : TGraphQLDocument; begin stream := TAdvVCLStream.Create; try stream.Stream := source; this := TGraphQLParser.Create(stream.link); try this.next; doc := TGraphQLDocument.Create; try this.parseDocument(doc); result := TGraphQLPackage.create(doc.Link); finally doc.free; end; finally this.free; end; finally stream.Free; end; end; function TGraphQLParser.parseArgument: TGraphQLArgument; begin result := TGraphQLArgument.Create; try result.Name := consumeName; consumePunctuation(':'); if hasPunctuation('[') then begin result.list := true; consumePunctuation('['); while not hasPunctuation(']') do result.Values.Add(parseValue); consumePunctuation(']'); end else result.Values.Add(parseValue); result.Link; finally result.Free; end; end; function TGraphQLParser.parseDirective: TGraphQLDirective; begin result := TGraphQLDirective.Create; try consumePunctuation('@'); result.Name := consumeName; if hasPunctuation('(') then begin consumePunctuation('('); repeat result.Arguments.Add(parseArgument); until hasPunctuation(')'); consumePunctuation(')'); end; result.Link; finally result.Free; end; end; procedure TGraphQLParser.parseDocument(doc: TGraphQLDocument); var s : String; op : TGraphQLOperation; begin if not hasName then begin op := TGraphQLOperation.Create; try parseOperationInner(op); doc.Operations.Add(op.Link); finally op.Free; end; end else begin while more or (FPeek <> '') do begin s := consumeName; if (s = 'mutation') or (s = 'query') then doc.Operations.Add(parseOperation(s)) else if (s = 'fragment') then doc.Fragments.Add(parseFragment) else raise Exception.Create('Not done yet'); // doc.Operations.Add(parseOperation(s))? end; end; end; function TGraphQLParser.parseField: TGraphQLField; begin result := TGraphQLField.Create; try result.Name := consumeName; result.Alias := result.Name; if hasPunctuation(':') then begin consumePunctuation(':'); result.Name := consumeName; end; if hasPunctuation('(') then begin consumePunctuation('('); while not hasPunctuation(')') do result.Arguments.Add(parseArgument); consumePunctuation(')'); end; while hasPunctuation('@') do result.Directives.Add(parseDirective); if hasPunctuation('{') then begin consumePunctuation('{'); repeat result.SelectionSet.Add(parseSelection); until hasPunctuation('}'); consumePunctuation('}'); end; result.link; finally result.Free; end; end; class function TGraphQLParser.parseFile(filename: String): TGraphQLPackage; var src : String; begin src := FileToString(filename, TEncoding.UTF8); result := parse(src); end; procedure TGraphQLParser.parseFragmentInner(fragment: TGraphQLFragment); begin while hasPunctuation('@') do fragment.Directives.Add(parseDirective); consumePunctuation('{'); repeat fragment.SelectionSet.Add(parseSelection); until hasPunctuation('}'); consumePunctuation('}'); end; function TGraphQLParser.parseFragment: TGraphQLFragment; begin result := TGraphQLFragment.Create; try result.Name := consumeName; consumeName('on'); result.TypeCondition := consumeName; parseFragmentInner(result); result.Link; finally result.free; end; end; function TGraphQLParser.parseFragmentSpread: TGraphQLFragmentSpread; begin result := TGraphQLFragmentSpread.Create; try result.Name := consumeName; while hasPunctuation('@') do result.Directives.Add(parseDirective); result.Link; finally result.Free; end; end; function TGraphQLParser.parseInlineFragment: TGraphQLFragment; begin result := TGraphQLFragment.Create; try if hasName('on') then begin consumeName('on'); result.FTypeCondition := consumeName; end; parseFragmentInner(result); result.Link; finally result.Free; end; end; class function TGraphQLParser.parseJson(source: TStream): TGraphQLPackage; var json : TJsonObject; vl : TJsonObject; n : String; this : TGraphQLParser; stream : TAdvStringStream; begin json := TJSONParser.Parse(source); try result := TGraphQLPackage.Create(TGraphQLDocument.Create); try result.FOperationName := json.str['operationName']; stream := TAdvStringStream.Create; try stream.Bytes := TENcoding.UTF8.GetBytes(json.str['query']); this := TGraphQLParser.Create(stream.link); try this.next; this.parseDocument(result.FDocument); finally this.free; end; finally stream.Free; end; if json.has('variables') then begin vl := json.obj['variables']; for n in vl.properties.Keys do result.Variables.Add(TGraphQLArgument.create(n, vl.properties[n])); end; result.Link; finally result.Free; end; finally json.Free; end; end; function TGraphQLParser.parseOperation(name : String) : TGraphQLOperation; begin result := TGraphQLOperation.Create; try if name = 'mutation' then begin result.operationType := qglotMutation; if hasName then result.Name := consumeName; end else if name = 'query' then begin result.operationType := qglotQuery; if hasName then result.Name := consumeName; end else result.Name := name; parseOperationInner(result); result.Link; finally result.Free; end; end; procedure TGraphQLParser.parseOperationInner(op: TGraphQLOperation); begin if hasPunctuation('(') then begin consumePunctuation('('); repeat op.Variables.Add(parseVariable); until hasPunctuation(')'); consumePunctuation(')'); end; while hasPunctuation('@') do op.Directives.Add(parseDirective); if hasPunctuation('{') then begin consumePunctuation('{'); repeat op.SelectionSet.Add(parseSelection); until hasPunctuation('}'); consumePunctuation('}'); end; end; function TGraphQLParser.parseSelection: TGraphQLSelection; begin result := TGraphQLSelection.Create; try if hasPunctuation('...') then begin consumePunctuation('...'); if hasName and (FToken.ToString <> 'on') then result.FragmentSpread := parseFragmentSpread else result.InlineFragment := parseInlineFragment; end else result.field := parseField; result.Link; finally result.Free; end; end; function TGraphQLParser.parseValue: TGraphQLValue; begin result := nil; try case FLexType of gqlltNull: raise EGraphQLException.Create('Attempt to read a value after reading off the end of the GraphQL statement'); gqlltName: result := TGraphQLNameValue.Create(FToken.ToString); gqlltPunctuation: if hasPunctuation('$') then begin consumePunctuation('$'); result := TGraphQLVariableValue.Create(FToken.ToString); end else if hasPunctuation('{') then begin consumePunctuation('{'); result := TGraphQLObjectValue.Create; while not hasPunctuation('}') do TGraphQLObjectValue(result).Fields.Add(parseArgument); end else raise EGraphQLException.Create('Attempt to read a value at "'+FToken.ToString+'"'); gqlltString: result := TGraphQLStringValue.Create(FToken.ToString); gqlltNumber: result := TGraphQLNumberValue.Create(FToken.ToString); end; next; result.Link; finally result.Free; end; end; function TGraphQLParser.parseVariable: TGraphQLVariable; begin result := TGraphQLVariable.Create; try consumePunctuation('$'); result.Name := consumeName; consumePunctuation(':'); result.TypeName := consumeName; if hasPunctuation('=') then begin consumePunctuation('='); result.DefaultValue := parseValue; end; result.Link; finally result.Free; end; end; procedure TGraphQLParser.consumeName(name: String); begin if FLexType <> gqlltName then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting a name'); if FToken.ToString <> name then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting "'+name+'"'); next; end; procedure TGraphQLParser.consumePunctuation(punc: String); begin if FLexType <> gqlltPunctuation then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting "'+punc+'"'); if FToken.ToString <> punc then raise EGraphQLException.Create('Found "'+FToken.ToString+'" expecting "'+punc+'"'); next; end; constructor TGraphQLParser.Create; begin inherited; FToken := TStringBuilder.Create; end; destructor TGraphQLParser.Destroy; begin FToken.Free; inherited; end; procedure TGraphQLParser.PushChar(ch: Char); begin if (ch <> #0) then insert(ch, FPeek, 1); end; procedure TGraphQLParser.skipIgnore; var ch : char; begin ch := getNextChar; while CharInSet(ch, [' ', #9, #13, #10, ',', #$FE, #$FF]) do ch := getNextChar; if (ch = '#') then begin while not CharInSet(ch, [#13, #10]) do ch := getNextChar; pushChar(ch); skipIgnore; end else pushChar(ch); end; { TGraphQLValue } function TGraphQLValue.isValue(v: String): boolean; begin result := false; end; function TGraphQLValue.Link: TGraphQLValue; begin result := TGraphQLValue(inherited Link); end; procedure TGraphQLValue.write(str : TStringBuilder; indent : integer); begin raise Exception.Create('Need to override '+className+'.write'); end; { TGraphQLNumberValue } constructor TGraphQLNumberValue.Create(value: String); begin Inherited Create; FValue := value; end; function TGraphQLNumberValue.isValue(v: String): boolean; begin result := v = FValue; end; function TGraphQLNumberValue.Link: TGraphQLNumberValue; begin result := TGraphQLNumberValue(inherited Link); end; function TGraphQLNumberValue.ToString: String; begin result := FValue; end; procedure TGraphQLNumberValue.write(str : TStringBuilder; indent : integer); begin str.append(FValue); end; { TGraphQLVariableValue } constructor TGraphQLVariableValue.Create(value: String); begin Inherited Create; FValue := value; end; function TGraphQLVariableValue.Link: TGraphQLVariableValue; begin result := TGraphQLVariableValue(inherited Link); end; function TGraphQLVariableValue.ToString: String; begin result := FValue; end; procedure TGraphQLVariableValue.write(str : TStringBuilder; indent : integer); begin raise Exception.Create('Cannot write a variable to JSON'); end; { TGraphQLNameValue } constructor TGraphQLNameValue.Create(value: String); begin Inherited Create; FValue := value; end; function TGraphQLNameValue.isValue(v: String): boolean; begin result := v = FValue; end; function TGraphQLNameValue.Link: TGraphQLValue; begin result := TGraphQLNameValue(inherited Link); end; function TGraphQLNameValue.ToString: String; begin result := FValue; end; procedure TGraphQLNameValue.write(str: TStringBuilder; indent : integer); begin str.append(FValue); end; { TGraphQLStringValue } constructor TGraphQLStringValue.Create(value: String); begin Inherited Create; FValue := value; end; function TGraphQLStringValue.isValue(v: String): boolean; begin result := v = FValue; end; function TGraphQLStringValue.Link: TGraphQLStringValue; begin result := TGraphQLStringValue(inherited Link); end; function TGraphQLStringValue.ToString: String; begin result := FValue; end; procedure TGraphQLStringValue.write(str: TStringBuilder; indent : integer); var i : integer; Begin str.Append('"'); for i := 1 to length(value) do case value[i] of '"':str.Append('\"'); '\':str.Append('\\'); #13:str.Append('\r'); #10:str.Append('\n'); #09:str.Append('\t'); else if ord(value[i]) < 32 Then str.Append('\u'+inttohex(ord(value[i]), 4)) else str.Append(value[i]); End; str.Append('"'); end; { TGraphQLObjectValue } function TGraphQLObjectValue.addField(name: String; isList: boolean): TGraphQLArgument; var t : TGraphQLArgument; begin result := nil; for t in FFields do if (t.Name = name) then result := t; if result = nil then begin result := TGraphQLArgument.Create; try result.Name := name; result.list := IsList; FFields.Add(result.Link); finally result.Free; end; end else result.list := true; end; constructor TGraphQLObjectValue.Create; begin inherited; FFields := TAdvList<TGraphQLArgument>.create; end; constructor TGraphQLObjectValue.Create(json: TJsonObject); var n : String; begin Create; for n in json.properties.Keys do FFields.Add(TGraphQLArgument.Create(n, json.properties[n])); end; destructor TGraphQLObjectValue.Destroy; begin FFields.Free; inherited; end; function TGraphQLObjectValue.Link: TGraphQLObjectValue; begin result := TGraphQLObjectValue(inherited Link); end; procedure TGraphQLObjectValue.write(str: TStringBuilder; indent : integer); var i, ni : integer; s, se : String; begin str.Append('{'); ni := indent; s := ''; se := ''; if (ni > -1) then begin se := #13#10+StringPadLeft('',' ', ni*2); inc(ni); s := #13#10+StringPadLeft('',' ', ni*2); end; for i := 0 to FFields.count - 1 do begin if (i > 0) then str.Append(','); str.Append(s); FFields[i].write(str, ni); end; str.Append(se); str.Append('}'); end; { TGraphQLPackage } constructor TGraphQLPackage.Create; begin inherited; FVariables := TAdvList<TGraphQLArgument>.create; end; constructor TGraphQLPackage.Create(document: TGraphQLDocument); begin Create; FDocument := Document; end; destructor TGraphQLPackage.Destroy; begin FDocument.Free; FVariables.Free; inherited; end; function TGraphQLPackage.Link: TGraphQLPackage; begin result := TGraphQLPackage(inherited Link); end; procedure TGraphQLPackage.SetDocument(const Value: TGraphQLDocument); begin FDocument.Free; FDocument := Value; end; end.
unit MsgAPI; interface uses Windows, CvarDef, SysUtils; const ERRORTYPE_SEARCH: LongWord = $00001000; ERRORTYPE_PATCH: LongWord = $00002000; procedure RaiseDebugAlert(Extra: String = ''); procedure RaiseError(const Msg: String); overload; procedure RaiseError(Msg: array of const); overload; procedure RaiseAlert(const Msg: String); procedure RaiseInfo(Msg: PChar); procedure ShowPointer(P: Pointer; Base: TLibrary); overload; procedure ShowPointer(P: Pointer); overload; procedure ShowPointer(P: LongWord); overload; procedure ShowMemory(const Addr: Pointer; Length: LongInt = 8); overload; procedure ShowMemory(const Addr: Cardinal; Length: LongInt = 8); overload; procedure ShowRegistersStatus; procedure RaiseErrorCode(Code: LongInt); implementation uses Common; var AlertDebugValue: LongInt = 0; procedure RaiseDebugAlert(Extra: String = ''); begin Inc(AlertDebugValue); RaiseAlert(IntToStr(AlertDebugValue) + sLineBreak + Extra); end; procedure RaiseError(const Msg: String); begin MessageBox(HWND_DESKTOP, PChar(Msg), 'Fatal Error', MB_ICONERROR or MB_SYSTEMMODAL); Halt; end; procedure RaiseError(Msg: array of const); begin MessageBox(HWND_DESKTOP, PChar(StringFromVarRec(Msg)), 'Fatal Error', MB_ICONERROR or MB_SYSTEMMODAL); Halt; end; procedure RaiseAlert(const Msg: String); begin MessageBox(HWND_DESKTOP, PChar(Msg), 'Alert', MB_ICONWARNING or MB_SYSTEMMODAL); end; procedure RaiseInfo(Msg: PChar); begin MessageBox(HWND_DESKTOP, Msg, 'Information', MB_ICONINFORMATION or MB_SYSTEMMODAL); end; procedure ShowPointer(P: Pointer; Base: TLibrary); begin RaiseInfo(PChar(IntToHex(LongInt(P) - Base.BaseStart, 8))); end; procedure ShowPointer(P: Pointer); begin ShowPointer(P, PWGame); end; procedure ShowPointer(P: LongWord); begin ShowPointer(Pointer(P), PWGame); end; procedure ShowMemory(const Addr: Pointer; Length: LongInt = 8); var S: String; L: LongInt; begin S := ''; for L := 0 to Length - 1 do S := S + IntToHex(PByte(LongInt(Addr) + L)^, 2) + ' '; RaiseAlert(S); end; procedure ShowMemory(const Addr: Cardinal; Length: LongInt = 8); begin ShowMemory(Pointer(Addr), Length); end; procedure ShowRegistersStatus; procedure PrintRegs_Internal(EAX, EBX, ECX, EDX, ESI, EDI, EBP, ESP: LongWord); stdcall; var S: String; begin S := 'Registers dump:' + sLineBreak + sLineBreak; S := S + ' EAX: ' + IntToHex(EAX, 8) + '; '; S := S + ' EBX: ' + IntToHex(EBX, 8) + '; '; S := S + ' ECX: ' + IntToHex(ECX, 8) + '; ' + sLineBreak; S := S + ' EDX: ' + IntToHex(EDX, 8) + '; '; S := S + ' ESI: ' + IntToHex(ESI, 8) + '; '; S := S + ' EDI: ' + IntToHex(EDI, 8) + '; ' + sLineBreak; S := S + ' EBP: ' + IntToHex(EBP, 8) + '; '; S := S + ' ESP: ' + IntToHex(ESP, 8); MessageBox(HWND_DESKTOP, PChar(S), 'AsmStatus: Registers', MB_ICONINFORMATION or MB_SYSTEMMODAL); end; asm push esp add [esp], 4 // - call return addr push ebp push edi push esi push edx push ecx push ebx push eax call PrintRegs_Internal end; procedure RaiseErrorCode(Code: LongInt); begin RaiseError(PChar('An error has occured.'#10'Code: ' + IntToStr(Code))); end; end.
unit uClientDataSet; interface uses Datasnap.DBClient, Classes, System.SysUtils, Data.DB, System.Generics.Collections, System.Variants; type TParametros = class public const coTodos: string = 'TODOS'; coID: string = 'ID'; coID_ESPECIE = 'ID_ESPECIE'; coIdPai: string = 'ID_PAI'; coNome: string = 'NOME'; coData: string = 'DATA'; coDataCompra: string = 'DATA_COMPRA'; coDataVencimento:string = 'DATA_VENCIMENTO'; coDataPagamentoRecebimento:string = 'DATA_PAGAMENTO_RECEBIMENTO'; coActive: string = 'ACTIVE'; coLogin: string = 'LOGIN'; coAtivo: string = 'ATIVO'; coStatus: string = 'STATUS'; coStatusEntrega = 'STATUS_ENTREGA'; coStatusDiferente = 'STATUS_DIFERENTE'; coProjeto: string = 'PROJETO'; coProjetoAlocado: string = 'PROJETO_ALOCADO'; coAtividade: string = 'ATIVIDADE'; coNomeCientifico = 'NOME_CIENTIFICO'; coFamiliaBotanica = 'FAMILIA_BOTANICA'; coNomeFantasia = 'NOME_FANTASIA'; coRazaoSocial = 'RAZAO_SOCIAL'; coCpfCnpj = 'CPF_CNPJ'; coEspecie = 'ESPECIE'; coDescricao = 'DESCRICAO'; coFornecedor = 'FORNECEDOR'; coRubrica = 'RUBRICA'; coRubricaOrigemRecurso = 'RUBRICA_ORIGEM_RECURSO'; coPlanoConta = 'PLANO_CONTA'; coClienteFinanciador = 'CLIENTE_FINANCIADOR'; coSolicitante = 'PESSOA_SOLICITANTE'; coResponsavelAnalise = 'PESSOA_ANALISOU'; coComprador = 'PESSOA_COMPROU'; coVendedor = 'PESSOA_VENDEU'; coResponsavelDespesa = 'RESPONSAVEL_DESPESA'; coLoteSemente = 'LOTE_SEMENTE'; coVencida = 'VENCIDA'; coCliente = 'CLIENTE'; coIdColeta = 'ID_COLETA'; coTipo = 'TIPO'; coTipoItem = 'TIPO_ITEM'; coItem = 'ITEM'; coCompra = 'COMPRA'; coVenda = 'VENDA'; coCodigoRastreio = 'CODIGO_RASTREIO'; coFundo = 'FUNDO'; coPossuiEstoque = 'POSSUI_ESTOQUE'; coIdentificadorPlanoContasRubrica = 'IDENTIFICADOR_PLANO_CONTAS_RUBRICA'; coIdentificacao = 'IDENTIFICACAO'; coLocalizacao = 'LOCALIZACAO'; coNotaFiscal = 'NOTA_FISCAL'; coPessoa = 'PESSOA'; coOrganizacao = 'ORGANIZACAO'; coAberto = 'ABERTO'; coClassificacao = 'CLASSIFICACAO'; coBioma = 'BIOMA'; coDelimitador = '§'; coCategoria = 'CATEGORIA'; coSaldoPositivo = 'SALDO_POSITIVO'; coNativa = 'ESPECIE_NATIVA_CERRADO'; end; TOnErroRede = function(e: Exception): Boolean of object; [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] TRFClientDataSet = class(TClientDataSet) private FParametros: TList<String>; FValores: TList<Variant>; FRFApplyAutomatico: Boolean; FPerdeuConexao: Boolean; FOnTratarErroRede: TOnErroRede; FRFNomeTabela: String; procedure SetRFApplyAutomatico(const Value: Boolean); procedure SetPerdeuConexao(const Value: Boolean); procedure SetOnTratarErroRede(const Value: TOnErroRede); procedure SetRFNomeTabela(const Value: String); protected procedure InternalDelete; override; procedure pprChecarReconexao; procedure InternalRefresh; override; procedure SetActive(Value: Boolean); override; public property Parametros: TList<string> read FParametros; property ValoresParametros: TList<Variant> read FValores; property PerdeuConexao: Boolean read FPerdeuConexao write SetPerdeuConexao; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Post; override; function ApplyUpdates(MaxErrors: Integer): Integer; override; procedure ppuDataRequest(const ipParametros: Array of string; ipValores: Array of Variant; ipOperador: string; ipLimparParametros: Boolean); overload; procedure ppuDataRequest(const ipParametros: Array of string; ipValores: Array of Variant; ipOperador: string); overload; procedure ppuDataRequest(const ipParametros: Array of string; ipValores: Array of Variant); overload; procedure ppuDataRequest(); overload; procedure ppuAddParametro(ipParametro: string; ipValor: Variant; ipOperador: String = ' AND '; ipLimparParametros: Boolean = false); procedure ppuAddParametros(const ipParametros: Array of string; ipValores: Array of Variant; ipOperador: String = ' AND '; ipLimparParametros: Boolean = false); procedure ppuLimparParametros; procedure ppuCopiarRegistro(ipDataSet: TDataSet); published property RFApplyAutomatico: Boolean read FRFApplyAutomatico write SetRFApplyAutomatico default true; property OnTratarErroRede: TOnErroRede read FOnTratarErroRede write SetOnTratarErroRede; property RFNomeTabela:String read FRFNomeTabela write SetRFNomeTabela; end; procedure Register; implementation procedure Register; begin RegisterComponents('RafaelComponentes', [TRFClientDataSet]); end; { TRFClientDataSet } function TRFClientDataSet.ApplyUpdates(MaxErrors: Integer): Integer; begin pprChecarReconexao; try Result := inherited; except on e: Exception do begin if not OnTratarErroRede(e) then raise else Result := ApplyUpdates(MaxErrors); end; end; end; constructor TRFClientDataSet.Create(AOwner: TComponent); begin inherited; FRFApplyAutomatico := true; FParametros := TList<String>.Create; FValores := TList<Variant>.Create; end; destructor TRFClientDataSet.Destroy; begin FreeAndNil(FParametros); FreeAndNil(FValores); inherited; end; procedure TRFClientDataSet.InternalDelete; begin try inherited; if FRFApplyAutomatico and (ChangeCount > 0) then ApplyUpdates(0); except on e: Exception do begin if not OnTratarErroRede(e) then raise else InternalDelete; end; end; end; procedure TRFClientDataSet.InternalRefresh; begin pprChecarReconexao; inherited; end; procedure TRFClientDataSet.Post; begin inherited; if FRFApplyAutomatico and (ChangeCount > 0) then ApplyUpdates(0); end; procedure TRFClientDataSet.pprChecarReconexao; begin if FPerdeuConexao then begin FPerdeuConexao := false; if FParametros.Count > 0 then ppuDataRequest() else begin Close; Open; end; end; end; procedure TRFClientDataSet.ppuAddParametro(ipParametro: string; ipValor: Variant; ipOperador: String; ipLimparParametros: Boolean); begin if ipLimparParametros then ppuLimparParametros; if (Trim(ipParametro) <> '') AND (NOT VarIsNull(ipValor)) then begin FParametros.Add(ipParametro); FValores.Add(VarToStr(ipValor) + TParametros.coDelimitador + ipOperador); end else raise Exception.Create('Valores inválidos para o parametro ou para o valor.'); end; procedure TRFClientDataSet.ppuAddParametros(const ipParametros: array of string; ipValores: array of Variant; ipOperador: String; ipLimparParametros: Boolean); var i: Integer; begin if ipLimparParametros then ppuLimparParametros; if High(ipParametros) = High(ipValores) then begin // percorre todo o array add cada elemento no list for i := Low(ipParametros) to High(ipParametros) do begin ppuAddParametro(ipParametros[i], ipValores[i], ipOperador); end; end else raise Exception.Create('Os arrays devem possuir o mesmo tamanho.'); end; procedure TRFClientDataSet.ppuCopiarRegistro(ipDataSet: TDataSet); var i: Integer; vaField: TField; begin if not(State in [dsInsert, dsEdit]) then Insert; for i := 0 to ipDataSet.FieldCount - 1 do // copiando os fields begin vaField := FindField(ipDataSet.Fields[i].FieldName); if Assigned(vaField) and (not vaField.ReadOnly) and (vaField.FieldKind = fkData) then begin vaField.Assign(ipDataSet.Fields[i]); end; end; end; procedure TRFClientDataSet.ppuDataRequest(const ipParametros: array of string; ipValores: array of Variant); begin ppuDataRequest(ipParametros, ipValores, ' AND '); end; procedure TRFClientDataSet.ppuDataRequest; var i: Integer; vaParams: TParams; begin try vaParams := TParams.Create(); try // percorre todo o TList criando os parametros for i := 0 to FParametros.Count - 1 do begin // parametros sem valores nao serao considerados if VarToStrDef(FValores.Items[i], '').Trim <> '' then vaParams.CreateParam(ftString, FParametros.Items[i], ptInput).AsString := FValores.Items[i]; end; // se nenhum parametro foi passado entao passo o parametro active para evitar de carregar toda a tabela if vaParams.Count = 0 then vaParams.CreateParam(ftString, TParametros.coActive, ptInput).AsString := 'NAO_IMPORTA'; // fecho o cds Close; // faz a requisição para o server try DataRequest(PackageParams(vaParams)); // faz a requisição empacotando os parâmetros para OLE Open; finally // limpo os TList // FParametros.Clear; // FValores.Clear; end; finally vaParams.Free; end; except on e: Exception do begin if not OnTratarErroRede(e) then raise else ppuDataRequest; end; end; end; procedure TRFClientDataSet.ppuDataRequest(const ipParametros: array of string; ipValores: array of Variant; ipOperador: string; ipLimparParametros: Boolean); begin ppuAddParametros(ipParametros, ipValores, ipOperador, ipLimparParametros); ppuDataRequest(); end; procedure TRFClientDataSet.ppuDataRequest(const ipParametros: array of string; ipValores: array of Variant; ipOperador: string); begin ppuDataRequest(ipParametros, ipValores, ipOperador, false); end; procedure TRFClientDataSet.ppuLimparParametros; begin FParametros.Clear; FValores.Clear; end; procedure TRFClientDataSet.SetActive(Value: Boolean); begin if Value then pprChecarReconexao; try inherited; except on e: Exception do begin if not OnTratarErroRede(e) then raise else SetActive(Value); end; end; end; procedure TRFClientDataSet.SetOnTratarErroRede(const Value: TOnErroRede); begin FOnTratarErroRede := Value; end; procedure TRFClientDataSet.SetPerdeuConexao(const Value: Boolean); begin FPerdeuConexao := Value; end; procedure TRFClientDataSet.SetRFApplyAutomatico(const Value: Boolean); begin FRFApplyAutomatico := Value; end; procedure TRFClientDataSet.SetRFNomeTabela(const Value: String); begin FRFNomeTabela := Value; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Informativos e Guias para o módulo Escrita Fiscal The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 2.0 ******************************************************************************* } unit UFiscalInformativosGuias; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ActnList, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, DBXJSON, ACBrPonto_AFD_Class, Mask, JvExMask, JvToolEdit, LabeledCtrls, ACBrPonto_AFDT_Class, ComCtrls, JvBaseEdits, SessaoUsuario, System.Actions, Vcl.Imaging.pngimage, Controller, COMObj; type TFFiscalInformativosGuias = class(TForm) PanelCabecalho: TPanel; Bevel1: TBevel; Image1: TImage; Label2: TLabel; ActionToolBarPrincipal: TActionToolBar; ActionManagerLocal: TActionManager; ActionCancelar: TAction; PageControlItens: TPageControl; ActionSair: TAction; tsGuias: TTabSheet; Panel1: TPanel; GroupBox10: TGroupBox; EditValorMulta: TLabeledCalcEdit; EditValorJuros: TLabeledCalcEdit; ActionGerarDarf: TAction; EditDataVencimento: TLabeledDateEdit; EditPeriodoApuracao: TLabeledDateEdit; EditCodigoReceita: TLabeledMaskEdit; EditNumeroReferencia: TLabeledMaskEdit; EditValorPrincipal: TLabeledCalcEdit; EditValorTotal: TLabeledCalcEdit; procedure ActionCancelarExecute(Sender: TObject); procedure ActionSairExecute(Sender: TObject); procedure ActionGerarDarfExecute(Sender: TObject); class function Sessao: TSessaoUsuario; private { Private declarations } public { Public declarations } end; var FFiscalInformativosGuias: TFFiscalInformativosGuias; implementation uses UDataModule; {$R *.dfm} class function TFFiscalInformativosGuias.Sessao: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; procedure TFFiscalInformativosGuias.ActionCancelarExecute(Sender: TObject); begin Close; end; procedure TFFiscalInformativosGuias.ActionSairExecute(Sender: TObject); begin Close; end; procedure TFFiscalInformativosGuias.ActionGerarDarfExecute(Sender: TObject); var (* RemoteDataInfo: TStringList; ConsultaSQL, NomeArquivo: String; i: Integer; *) ReportManager: Variant; begin (* try try NomeArquivo := 'DARF.rep'; FDataModule.VCLReport.GetRemoteParams(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo); FDataModule.VCLReport.Report.Params.ParamByName('PERIODOAPURACAO').Value := EditPeriodoApuracao.Text; FDataModule.VCLReport.Report.Params.ParamByName('DATAVENCIMENTO').Value := EditDataVencimento.Text; FDataModule.VCLReport.Report.Params.ParamByName('CODIGORECEITA').Value := EditCodigoReceita.Text; FDataModule.VCLReport.Report.Params.ParamByName('NUMEROREFERENCIA').Value := EditNumeroReferencia.Text; FDataModule.VCLReport.Report.Params.ParamByName('VALORPRINCIPAL').Value := EditValorPrincipal.Value; FDataModule.VCLReport.Report.Params.ParamByName('VALORMULTA').Value := EditValorMulta.Value; FDataModule.VCLReport.Report.Params.ParamByName('VALORJURO').Value := EditValorJuros.Value; FDataModule.VCLReport.Report.Params.ParamByName('VALORTOTAL').Value := EditValorTotal.Value; // FDataModule.VCLReport.GetRemoteDataInfo(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo); RemoteDataInfo := FDataModule.VCLReport.Report.RemoteDataInfo; // ConsultaSQL := ''; FDataModule.VCLReport.ExecuteRemote(Sessao.ServidorImpressao.Servidor, Sessao.ServidorImpressao.Porta, Sessao.ServidorImpressao.Usuario, Sessao.ServidorImpressao.Senha, Sessao.ServidorImpressao.Alias, NomeArquivo, ConsultaSQL); except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro na construção do relatório. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally end; *) try ReportManager := CreateOleObject('ReportMan.ReportManX'); ReportManager.Preview := True; ReportManager.ShowProgress := True; ReportManager.ShowPrintDialog := False; ReportManager.Filename := 'C:\T2Ti\Relatorios\DARF.rep'; ReportManager.SetParamValue('PERIODOAPURACAO', EditPeriodoApuracao.Text); ReportManager.SetParamValue('DATAVENCIMENTO', EditDataVencimento.Text); ReportManager.SetParamValue('CODIGORECEITA', EditCodigoReceita.Text); ReportManager.SetParamValue('NUMEROREFERENCIA', EditNumeroReferencia.Text); ReportManager.SetParamValue('VALORPRINCIPAL', EditValorPrincipal.Text); ReportManager.SetParamValue('VALORMULTA', EditValorMulta.Text); ReportManager.SetParamValue('VALORJURO', EditValorJuros.Text); ReportManager.SetParamValue('VALORTOTAL', EditValorTotal.Text); ReportManager.execute; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a impressão. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; end; end.
unit REPMap; {$writeableconst on} interface uses REPWorldCanvas, ShareTools, Console, REPDashBoardShared, REPViewCommand, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, AppEvnts, ComCtrls, Buttons, ToolWin, ImgList, Contnrs, IdBaseComponent, IdComponent, IdTCPServer, IdCustomHTTPServer, IdHTTPServer, HTTPApp; type TTabButtonInfos = class; TTabButtonInfo = class Owner : TTabButtonInfos; Button : TSpeedButton; Panel : TPanel; Width : integer; ShowText : boolean; NextToPrevious : boolean; procedure HidePanel; procedure AdjustTabButton(Top : integer); end; TTabButtonInfos = class(TObjectList) private function GetItem(i : integer) : TTabButtonInfo; public property Item[i : integer] : TTabButtonInfo read GetItem; function Add(aButton : TSpeedButton; aPanel : TPanel; aWidth : integer = 0; aShowText : boolean = false) : TTabButtonInfo; function GetWidth(Button : TSpeedButton; DefaultValue : integer) : integer; procedure AdjustTabButtons(Top : integer); end; TZoomAndPanCmd = class(TViewCmd) private // Pan params Dragged : boolean; StartX, StartY : integer; // Zoom params IsDown : boolean; FirstX, FirstY : integer; r : TRect; BackgroundColor : TColor; Scale : Double; {$ifdef DBLCLICKTOSUPERZOOM} FromDoubleClick : boolean; {$endif} public constructor Create; function Name : String; override; function HelpStr : String; override; procedure OnMouseDown(Params : TMouseDownParams); override; procedure OnMouseMove(Sender: TObject; Shift: TShiftState; var X, Y: Integer; WC : TREPWorldCanvas); override; procedure OnMouseUp (Sender: TObject; Shift: TShiftState; X, Y: Integer; WC : TREPWorldCanvas); override; end; TREPMapForm = class(TForm) ApplicationEvents1: TApplicationEvents; MouseScrollTimer: TTimer; ToolBar2: TToolBar; ToolButton9: TToolButton; ToolButton10: TToolButton; enPanel: TPanel; xyPanel: TPanel; BkImage: TImage; PaintBox: TPaintBox; HelpPanel: TPanel; HelpImage: TImage; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; Shape7: TShape; Shape8: TShape; Shape9: TShape; Shape10: TShape; HelpHintAreaShape: TShape; ToolButton1: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; LayersButton: TSpeedButton; FitMapBtn: TSpeedButton; ZoomInImg: TImage; VertBarImg: TImage; ZoomCursorImg: TImage; ZoomOutImg: TImage; HelpBtn: TSpeedButton; ENBtn: TSpeedButton; CoordinatePanel: TPanel; MeasureBtn: TSpeedButton; PrintBtn: TSpeedButton; CopyAs1024x768Btn: TSpeedButton; SaveAsImageBtn: TSpeedButton; IdHTTPServer1: TIdHTTPServer; RunHTTPButton: TSpeedButton; procedure FormCreate(Sender: TObject); procedure SetServerURL(s : string); procedure ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); procedure MouseScrollTimerTimer(Sender: TObject); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormDestroy(Sender: TObject); procedure PaintBoxResize(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FitBtnClick(Sender: TObject); procedure ToogleToImageryBtnClick(Sender: TObject); procedure ToogleToMapBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ToolButton6Click(Sender: TObject); procedure LayersButtonClick(Sender: TObject); procedure ZoomInImgClick(Sender: TObject); procedure ZoomOutImgClick(Sender: TObject); procedure HelpBtnClick(Sender: TObject); procedure ENBtnClick(Sender: TObject); procedure ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean); procedure RunHTTPButtonClick(Sender: TObject); procedure IdHTTPServer1CommandGet(AThread: TIdPeerThread; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure OnShowCoordinatePanel(Sender: TObject); procedure _OnCoorPanelResize(Sender: TObject); procedure OnHideLayersClick(Sender: TObject); private RightInfos : array[0..1] of record Btn : TSpeedButton; Panel : TPanel; OnShowProc : TNotifyEvent; end; _MouseScrollCount : integer; _MouseScrollPoint : Tpoint; _Left, _Top : integer; _LayersControl : TWinControl; fServerURL : string; BkCmd : TZoomAndPanCmd; procedure ShowZoom(AroundX, AroundY : integer; ScaleMult : Double); procedure SetScaleIcon; procedure AdjustRightButtons; public LayerImages : TLayerImages; _BackgroundBMP : TBitmap; Layers : string; SRS, BBOX : string; wc : TREPWorldCanvas; CaptionPrefix : string; property ServerURL : string read fServerURL write SetServerURL; procedure LoadMapImage; procedure DrawBuffer; procedure FlushBackground; end; var REPMapForm: TREPMapForm; const ViewAreaState = ssCtrl; FloatingCanvas : TCanvas = nil; ShowMapDetailsInCaption : boolean = false; MARGIN_SIZE = 10; // od okraje k prvnimu tlacitku BUTTON_SPACE = 5; // mezera mezi tlacitky MapDataDir : string = ''; function ShowMap(ServerURL, Layers, SRS, BBOX : string) : TREPMapForm; implementation {$R *.dfm} uses FastZoomDefs, PngImage, TeraWMSTools, REPLayers, REPThemeSelect, REPHTTPServerOptionsFrm, REPCoordinateDisplayPanel; const MOUSEXY_PANELINDEX = 1; MOUSEEN_PANELINDEX = 2; procedure LoadPNGGlyph(FileName : string; btn : TSpeedButton); var p : TPNGObject; begin p := TPNGObject.Create; try p.LoadFromFile(MapDataDir + FileName); btn.Glyph.Assign(p); btn.Glyph.Transparent := true; btn.Glyph.TransparentMode := tmAuto; finally p.Free; end; end; function ShowMap(ServerURL, Layers, SRS, BBOX : string) : TREPMapForm; begin Application.CreateForm(TREPMapForm, REPMapForm); REPMapForm.ServerURL := ServerURL; REPMapForm.Layers := Layers; REPMapForm.SRS := SRS; REPMapForm.BBOX := BBOX; REPMapForm.FitBtnClick(nil); REPMapForm.Show; Result := REPMapForm; end; procedure ReLoadMapImage; begin if REPMapForm <> nil then REPMapForm.LoadMapImage; end; // ################################################################################################ // TTabButtonInfo // ################################################################################################ procedure TTabButtonInfo.AdjustTabButton; begin Button.Height := 25; Button.Top := Top; if ShowText then begin if Button.Down then begin Button.Width := Owner.GetWidth(Button, 120); Button.Caption := Button.Hint; end else begin Button.Width := 25; Button.Caption := ''; end; end; end; procedure TTabButtonInfo.HidePanel; begin if Panel <> nil then begin Panel.Visible := false; Panel.Enabled := false; end; end; // ################################################################################################ // TTabButtonInfos // ################################################################################################ procedure TTabButtonInfos.AdjustTabButtons(Top : integer); var i : integer; begin for i := 0 to Count - 1 do Item[i].AdjustTabButton(Top); end; function TTabButtonInfos.GetWidth(Button : TSpeedButton; DefaultValue : integer) : integer; var i : integer; begin for i := 0 to Count - 1 do if Item[i].Button = Button then begin Result := Item[i].Width; Exit; end; Result := DefaultValue; end; function TTabButtonInfos.GetItem; begin Result := Pointer(Items[i]); end; function TTabButtonInfos.Add; begin Result := TTabButtonInfo.Create; Result.Button := aButton; Result.Panel := aPanel; Result.Owner := Self; Result.NextToPrevious := false; Result.ShowText := aShowText; if aWidth > 0 then Result.Width := aWidth else Result.Width := aButton.Width; inherited Add(Result); end; // ***************************************************************************** // TZoomAndPanCmd // ***************************************************************************** constructor TZoomAndPanCmd.Create; begin inherited; Dragged := false; IsDown := false; Scale := 1; BackgroundColor := clWhite; end; function TZoomAndPanCmd.Name : String; begin Result := 'Volba výřezu'; end; function TZoomAndPanCmd.HelpStr : String; begin Result := 'Zvětšení,Zmenšení,Posun mapy'; end; procedure TZoomAndPanCmd.OnMouseDown(Params : TMouseDownParams); begin inherited; if (ViewAreaState in Params.Shift) or (Params.Button = mbRight) then begin FirstX := Params.x; FirstY := Params.y; Dragged := true; end else begin if Params.Button = mbLeft then begin Dragged := true; StartX := Params.x; StartY := Params.y; end else begin IsDown := true; FirstX := Params.x; FirstY := Params.y; end; end; end; procedure TZoomAndPanCmd.OnMouseMove(Sender: TObject; Shift: TShiftState; var X, Y: Integer; WC : TREPWorldCanvas); var SrcBitmap : TBitmap; ActX, ActY, dx, dy : integer; procedure TransformPoint(InX, InY : integer; var NewX, NewY : integer); begin NewX := Round(FirstX + Scale*(InX - FirstX)); NewY := Round(FirstY + Scale*(InY - FirstY)); end; var Message: TMessage; begin inherited; if (ViewAreaState in Shift) then begin if Dragged then begin REPMapForm.DrawBuffer; FloatingCanvas.Pen.Style := psSolid; FloatingCanvas.Pen.Color := clRed; FloatingCanvas.Pen.Width := 3; FloatingCanvas.Brush.Style := bsClear; FloatingCanvas.Rectangle(FirstX, FirstY, x, y); end; end else begin if Dragged then begin REPMapForm._Left := REPMapForm._Left + x - StartX; REPMapForm._Top := REPMapForm._Top + y - StartY; StartX := x; StartY := y; REPMapForm.DrawBuffer; end; (* else begin if not IsDown then Exit; ActX := x; ActY := y; dX := x - FirstX; dY := y - FirstY; {$ifdef SUPERZOOMFROMABSDY} Scale := 0.05*Abs(dY); {$else} Scale := 0.1*Sqrt(Sqr(dX) + Sqr(dY)); {$endif} if Scale > 0 then begin if dy < 0 then begin Scale := 1/(1+Scale); // Zoom Out WC.AssignCursor(crZoomOut); end else begin Scale := 1+(Scale/2); // Zoom In WC.AssignCursor(crZoomIn); end; SrcBitmap := PrimaryWorldCanvas.ImgBMP.Picture.Bitmap; Paintbox := PrimaryWorldCanvas.PaintBox; TransformPoint(0, 0, r.Left, r.Top); TransformPoint(SrcBitmap.Width, SrcBitmap.Height, r.Right, r.Bottom); TransformPoint(FirstX, FirstY, x, y); PaintBox.Canvas.Pen.Mode := pmCopy; StretchBlt( PaintBox.Canvas.Handle, r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top, SrcBitmap.Canvas.Handle, 0, 0, SrcBitmap.Width, SrcBitmap.Height, SRCCOPY ); if Scale < 1 then begin // Painting masks PaintBox.Canvas.Brush.Color := BackgroundColor; PaintBox.Canvas.Brush.Style := bsSolid; PaintBox.Canvas.Pen.Color := clBlue; PaintBox.Canvas.Pen.Style := psClear; // Top mask PaintBox.Canvas.Polygon([ Point(r.Left, r.Top), Point(0, 0), Point(PaintBox.Width, 0), Point(r.Right, r.Top), Point(r.Left, r.Top) ]); // Left mask PaintBox.Canvas.Polygon([ Point(r.Left, r.Top), Point(0, 0), Point(0, PaintBox.Height), Point(r.Left, r.Bottom), Point(r.Left, r.Top) ]); // Right mask PaintBox.Canvas.Polygon([ Point(r.Right, r.Top), Point(PaintBox.Width, 0), Point(PaintBox.Width, PaintBox.Height), Point(r.Right, r.Bottom), Point(r.Right, r.Top) ]); // Bottom mask PaintBox.Canvas.Polygon([ Point(r.Left, r.Bottom), Point(0, PaintBox.Height), Point(PaintBox.Width, PaintBox.Height), Point(r.Right, r.Bottom), Point(r.Left, r.Bottom) ]); PaintBox.Canvas.Pen.Style := psSolid; end; PaintBox.Canvas.Pen.Style := psSolid; PaintBox.Canvas.Pen.Color := clRed; PaintBox.Canvas.Pen.Width := 1; PaintBox.Canvas.Polyline([Point(0, FirstY), Point(PaintBox.Width, FirstY)]); PaintBox.Canvas.Polyline([Point(ActX, ActY), Point(FirstX, FirstY)]); PaintBox.Canvas.Brush.Color := clWhite; PaintBox.Canvas.Font.Size := 10; PaintBox.Canvas.Font.Name := 'Tahoma'; PaintBox.Canvas.TextOut(0, 0, '1:' + FloatToStr(wc.CanvasDef.Scale/Scale)); end; end; *) end; end; procedure TZoomAndPanCmd.OnMouseUp(Sender: TObject; Shift: TShiftState; X, Y: Integer; WC : TREPWorldCanvas); var Paintbox : TPaintbox; begin if ViewAreaState in Shift then begin Dragged := false; //FloatingPaintBox.Flush; if (Abs(FirstX - x) > 5) and (Abs(FirstY - y) > 5) then begin wc.ViewAreaXY(FirstX, FirstY, x, y); ReLoadMapImage; end; end else begin if Dragged then begin if (REPMapForm._Left = 0) and (REPMapForm._Top = 0) then begin wc.NewCenter(x, y); REPMapForm.LoadMapImage; end else begin wc.NewCenter((REPMapForm.PaintBox.Width div 2) - REPMapForm._Left, (REPMapForm.PaintBox.Height div 2) - REPMapForm._Top); REPMapForm._Left := 0; REPMapForm._Top := 0; REPMapForm.LoadMapImage; end; end (* else begin if Scale > 0 then begin try __StopCallOnChange := true; PrimaryWorldCanvas.CanvasDef.ViewAreaXY( Round((0 - FirstX)/Scale + FirstX), Round((0 - FirstY)/Scale + FirstY), Round((PrimaryWorldCanvas.CanvasDef.EPixels - FirstX)/Scale + FirstX), Round((PrimaryWorldCanvas.CanvasDef.NPixels - FirstY)/Scale + FirstY) ); finally __StopCallOnChange := false; end; PrimaryWorldCanvas.CanvasDef.NewCenter(FirstX, FirstY); end; end; *) end; Dragged := false; IsDown := false; end; procedure LoadPngToBmp(FileName : string; bmp : TBitmap); var p : TPNGObject; begin p := TPNGObject.Create; p.LoadFromFile(MapDataDir + FileName); bmp.Assign(p); p.Free; end; // ############################################################################ // TREPMapForm // ############################################################################ procedure TREPMapForm.FormCreate(Sender: TObject); var FastZoomButtons : TFastZoomButtons; begin CaptionPrefix := ''; _Left := 0; _Top := 0; SRS := 'EPSG:4326'; FloatingCanvas := PaintBox.Canvas; LayerImages := TLayerImages.Create; BkCmd := TZoomAndPanCmd.Create; HelpImage.Picture.LoadFromFile(MapDataDir + 'Images/HelpImage.png'); HelpPanel.ClientHeight := HelpImage.Picture.Height; HelpPanel.ClientWidth := HelpImage.Picture.Width; LoadPNGGlyph('Images/SuperZoomBtnGlyph.png', SpeedButton1); LoadPNGGlyph('Images/MeasureBtnGlyph.png', SpeedButton2); LoadPNGGlyph('Images/CopyToPowerPointBtnGlyph.png', SpeedButton3); LoadPNGGlyph('Images/FitBtnGlyph.png', FitMapBtn); LoadPNGGlyph('Images/HelpBtnGlyph.png', HelpBtn); LoadPNGGlyph('Images/LayersBtnGlyph.png', LayersButton); LoadPNGGlyph('Images/MeasureCoordinatesBtnGlyph.png', ENBtn); LoadPNGGlyph('Images/Disconnected.png', RunHTTPButton); RunHTTPButton.Caption := ''; FastZoomButtons := TFastZoomButtons.Create(Self, 50); FastZoomButtons.SetTop(LayersButton.Top); FastZoomButtons.AlignToLeft(LayersButton.Left + LayersButton.Width); CoorPanel := TCoordinateDisplayPanel.Create(CoordinatePanel); CoorPanel.Parent := CoordinatePanel; CoorPanel.Left := 0; CoorPanel.Top := 0; CoorPanel.Width := CoordinatePanel.Width; CoorPanel.Height := CoordinatePanel.Height; CoorPanel.Calculate; CoorPanel.ShowCoordinates(0, 0); CoorPanel.Show; CoorPanel.OnResize := _OnCoorPanelResize; _BackgroundBMP := TBitmap.Create; wc := TREPWorldCanvas.Create; // REPThemeSelect.MapWindowMoved(Left, Top); FitMapBtn.Top := MARGIN_SIZE; RightInfos[1].Btn := HelpBtn; RightInfos[1].Panel := HelpPanel; HelpBtn.Hint := 'Nápověda'; RightInfos[0].Btn := ENBtn; RightInfos[0].Panel := CoordinatePanel; RightInfos[0].OnShowProc := OnShowCoordinatePanel; ENBtn.Hint := 'Souřadnice'; HelpBtnClick(nil); PaintBoxResize(nil); FitBtnClick(nil); FitMapBtn.Left := ZoomInImg.Left + (ZoomInImg.Width div 2) - (FitMapBtn.Width div 2); end; procedure TREPMapForm.SetServerURL(s : string); begin s := AddTokenToURLQuery(BuildURLQueryToken(REQUESTPARAM_ID, GETMAP_REQUESTVALUE), s); s := AddTokenToURLQuery(BuildURLQueryToken(SERVICE_PARAM, WMS_SERVICEPARAMVALUE), s); s := AddTokenToURLQuery('SRS=' + SRS, s); s := AddTokenToURLQuery('VERSION=1.1.1', s); s := AddTokenToURLQuery('FORMAT=image/png', s); fServerURL := s; end; procedure TREPMapForm.DrawBuffer; begin // if PaintBox.Canvas.HandleAllocated then begin PaintBox.Canvas.Pen.Style := psClear; PaintBox.Canvas.Brush.Color := clWhite; PaintBox.Canvas.Brush.Style := bsSolid; PaintBox.Canvas.Rectangle(0, 0, PaintBox.Width, PaintBox.Height); PaintBox.Canvas.Draw(_Left, _Top, _BackgroundBMP); LayerImages.DrawToCanvas(_Left, _Top, PaintBox.Canvas); // end; end; procedure TREPMapForm.FlushBackground; begin BkImage.Picture.Bitmap.Assign(_BackgroundBMP); LayerImages.DrawToCanvas(0, 0, BkImage.Picture.Bitmap.Canvas); end; procedure TREPMapForm.LoadMapImage; var s : string; tmpFileName : string; Png : TPngObject; l : TWMSMapLayer; begin if (ServerURL = '') or (Layers = '') or (BBOX = '') then Exit; WaitCursor; try if ShowMapDetailsInCaption then Caption := CaptionPrefix + 'Mapa - ' + Layers + ' na ' + ServerURL; l := TWMSMapLayer.Create; try l.ServerURL := ServerURL; l.Layers := Layers; l.SRS := SRS; _BackgroundBMP.Free; with wc do _BackgroundBMP := l.GetMap(MinE, MinN, MaxE, MaxN, Paintbox.Width, Paintbox.Height); if REPLayers.REPLayersForm <> nil then REPLayers.REPLayersForm.LayersListBoxClickCheck(nil); FlushBackground; //BkImage.Picture.Bitmap.Assign(_BackgroundBMP); DrawBuffer; finally l.Free; end; finally RestoreCursor; end; end; procedure TREPMapForm.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean); var ScaleMult : Double; begin if (Msg.message = WM_MOUSEWHEEL) and PtInRect(Rect(0, 0, PaintBox.Width, PaintBox.Height), PaintBox.ScreenToClient(Msg.pt)) and (Focused) then begin if not MouseScrollTimer.Enabled then begin MouseScrollTimer.Enabled := true; _MouseScrollCount := 0; _MouseScrollPoint := PaintBox.ScreenToClient(msg.pt); end else begin MouseScrollTimer.Enabled := false; MouseScrollTimer.Enabled := true; end; if Msg.wParam < 0 then Inc(_MouseScrollCount) else Dec(_MouseScrollCount); if _MouseScrollCount < 0 then ScaleMult := 1/(1+Abs(_MouseScrollCount)) else ScaleMult := 1 + _MouseScrollCount; ShowZoom(PaintBox.ScreenToClient(msg.pt).x, PaintBox.ScreenToClient(msg.pt).y, ScaleMult); Handled := False; end; { if (Msg.Message = WM_LBUTTONUP) and _ScaleSliderDown then begin VertBarImgMouseUp(WorldCanvas, mbLeft, [], 0, _ScaleSliderDownY); _ScaleSliderDown := false; ScaleSliderLabel.Visible := false; end; if Msg.message = WM_MOUSEMOVE then begin if o_AutoHidePanels then begin if PanelsVisible then begin CheckControl(MapPanel, MapsPanelBtn); CheckControl(MapPanel, ImageryPanelBtn); CheckControl(SearchPanel, SearchPanelBtn); end; end; CheckScaleSlider; if HideHelpPanelAfterStartTimer.Enabled and PtInRect(Rect(0, 0, HelpPanel.Width, HelpPanel.Height), HelpPanel.ScreenToClient(Msg.pt)) then begin HideHelpPanelAfterStartTimer.Enabled := false; Console.DisplayMsg('Help panel timer switched off.') end; end; } end; procedure TREPMapForm.MouseScrollTimerTimer(Sender: TObject); var ScaleMult : Double; begin MouseScrollTimer.Enabled := false; if _MouseScrollCount <> 0 then begin if _MouseScrollCount < 0 then ScaleMult := 1/(1+Abs(_MouseScrollCount)) else ScaleMult := 1 + _MouseScrollCount; wc.ZoomAroundXY(_MouseScrollPoint.x, _MouseScrollPoint.y, ScaleMult); LoadMapImage; end; end; procedure TREPMapForm.ShowZoom(AroundX, AroundY : integer; ScaleMult : Double); procedure Line(x, y : integer; MultX, MultY : integer); begin PaintBox.Canvas.MoveTo(x, y); PaintBox.Canvas.LineTo(x + MultX*15, y + MultY*15); end; var r : TRect; c : TCanvas; begin c := PaintBox.Canvas; c.Brush.Color := clWhite; c.Brush.Style := bsSolid; c.Pen.Style := psClear; c.Rectangle(0, 0, PaintBox.Width, PaintBox.Height); r.Left := AroundX - Round(AroundX/ScaleMult); r.Top := AroundY - Round(AroundY/ScaleMult); r.Right := AroundX + Round((PaintBox.Width - AroundX)/ScaleMult); r.Bottom := AroundY + Round((PaintBox.Height - AroundY)/ScaleMult); StretchBlt( c.Handle, r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top, PaintBox.Canvas.Handle, 0, 0, PaintBox.Width, PaintBox.Height, SRCCOPY ); c.Pen.Color := clRed; c.Pen.Style := psSolid; c.Pen.Width := 3; Line(r.Left, r.Top, +1, 0); Line(r.Left, r.Top, 0, +1); Line(r.Right, r.Top, -1, 0); Line(r.Right, r.Top, 0, +1); Line(r.Left, r.Bottom, +1, 0); Line(r.Left, r.Bottom, 0, -1); Line(r.Right, r.Bottom, -1, 0); Line(r.Right, r.Bottom, 0, -1); end; procedure TREPMapForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if MOUSEXY_PANELINDEX >= 0 then xyPanel.Caption := Format('%d,%d', [x, y]); if MOUSEEN_PANELINDEX >= 0 then enPanel.Caption := Format('%f,%f', [wc.WUfromEIndex(x), wc.WUfromNIndex(y)]); if Assigned(REPCoordinateDisplayPanel.CoorPanel) then begin //CanvasDef.GeodeticSystem.ConvertStoreCoorsToGS(MBRGeoSystem, E, N, L, B); if not REPCoordinateDisplayPanel.CoorPanel.CenterBtn.Enabled then REPCoordinateDisplayPanel.CoorPanel.ShowCoordinates(wc.WUfromEIndex(x), wc.WUfromNIndex(y)); end; BkCmd.OnMouseMove(Sender, Shift, x, y, wc); end; procedure TREPMapForm.FormDestroy(Sender: TObject); begin LayerImages.Free; REPMapForm := nil; _BackgroundBMP.Free; wc.Free; BkCmd.Free; end; procedure TREPMapForm.PaintBoxResize(Sender: TObject); begin wc.EPixels := PaintBox.Width; wc.NPixels := PaintBox.Height; if PaintBox.Canvas.HandleAllocated then LoadMapImage; end; procedure TREPMapForm.SpeedButton1Click(Sender: TObject); begin LoadMapImage; end; procedure TREPMapForm.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin BkCmd.OnMouseUp(Sender, Shift, x, y, wc); end; procedure TREPMapForm.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin BkCmd.CallOnMouseDown(Sender, Button, Shift, x, y, 0, 0, wc); end; procedure TREPMapForm.FitBtnClick(Sender: TObject); var MinX, MinY, MaxX, MaxY : Double; s : string; begin if BBOX = '' then Exit; s := BBOX; MinX := GetAndDeleteFloatItem(s, ','); MinY := GetAndDeleteFloatItem(s, ','); MaxX := GetAndDeleteFloatItem(s, ','); MaxY := GetAndDeleteFloatItem(s, ','); wc.ViewArea(MinX, MinY, MaxX, MaxY); LoadMapImage; end; procedure TREPMapForm.ToogleToImageryBtnClick(Sender: TObject); begin Layers := 'BestImagery'; LoadMapImage; end; procedure TREPMapForm.ToogleToMapBtnClick(Sender: TObject); begin Layers := 'BestMap'; LoadMapImage; end; procedure TREPMapForm.FormShow(Sender: TObject); const FirstTime : boolean = true; begin if FirstTime then begin FirstTime := false; LoadMapImage; end; if (REPLayers.REPLayersForm <> nil) then begin _LayersControl := REPLayers.REPLayersForm.MoveControlsTo(Self); if _LayersControl <> nil then begin _LayersControl.Visible := false; _LayersControl.Left := LayersButton.Left; _LayersControl.Top := LayersButton.Top - _LayersControl.Height; end; end; if (REPThemeSelect.REPThemeSelectForm <> nil) then begin REPThemeSelect.REPThemeSelectForm.MoveControlsTo(MARGIN_SIZE, FitMapBtn.Left + FitMapBtn.Width, Self); REPThemeSelect.REPThemeSelectForm.OnSelectMapTheme := ToogleToMapBtnClick; REPThemeSelect.REPThemeSelectForm.OnSelectImageryTheme := ToogleToImageryBtnClick; end; if REPLayersForm <> nil then REPLayersForm.OnHideButtonClick := OnHideLayersClick; end; procedure TREPMapForm.ToolButton6Click(Sender: TObject); var e, n, SizeE, SizeN, Scale : Double; begin Scale := 2*TToolButton(Sender).Tag; E := (wc.MaxE + wc.MinE)/2; N := (wc.MaxN + wc.MinN)/2; SizeE := Scale*wc.EPixels/2; SizeN := Scale*wc.NPixels/2; wc.ViewArea(E - SizeE, N - SizeN, E + SizeE, N + SizeN); ReLoadMapImage; end; procedure TREPMapForm.LayersButtonClick(Sender: TObject); begin if (_LayersControl <> nil) then begin _LayersControl.Visible := LayersButton.Down; _LayersControl.Left := LayersButton.Left; _LayersControl.Height := LayersButton.Top - ZoomInImg.Top - 10; _LayersControl.Top := LayersButton.Top - _LayersControl.Height; _LayersControl.Anchors := LayersButton.Anchors; end; end; procedure TREPMapForm.ZoomInImgClick(Sender: TObject); begin wc.ZoomIn; LoadMapImage; end; procedure TREPMapForm.ZoomOutImgClick(Sender: TObject); begin wc.ZoomOut; LoadMapImage; end; procedure TREPMapForm.SetScaleIcon; begin // ZoomCursorImg.Top := ScaleSlide_GetPosition(WorldCanvas.CanvasDef.Scale) + ZoomInImg.Top + ZoomInImg.Height - (ZoomCursorImg.Height div 2) - 1; end; procedure TREPMapForm.AdjustRightButtons; var RightEdge, i, x : integer; b : TSpeedButton; begin // Setup buttons appearance. If down, then with caption. for i := Low(RightInfos) to High(RightInfos) do begin b := RightInfos[i].Btn; if b.Down then begin b.Width := 120; b.Caption := b.Hint; end else begin b.Width := b.Height; b.Caption := ''; end; b.Anchors := [akTop,akRight]; b.Top := MARGIN_SIZE; if RightInfos[i].Panel <> nil then begin RightInfos[i].Panel.Visible := b.Down and b.Visible; if RightInfos[i].Panel.Visible then begin RightInfos[i].Panel.Top := b.Top + b.Height; RightInfos[i].Panel.Left := ClientWidth - MARGIN_SIZE - RightInfos[i].Panel.Width; RightInfos[i].Panel.Anchors := [akTop,akRight]; if Assigned(RightInfos[i].OnShowProc) then RightInfos[i].OnShowProc(Self); end; end; end; x := ClientWidth - MARGIN_SIZE; for i := High(RightInfos) downto Low(RightInfos) do begin RightInfos[i].Btn.Left := x - RightInfos[i].Btn.Width; x := RightInfos[i].Btn.Left - BUTTON_SPACE; end; end; procedure TREPMapForm.HelpBtnClick(Sender: TObject); begin AdjustRightButtons; end; procedure TREPMapForm.ENBtnClick(Sender: TObject); begin AdjustRightButtons; end; procedure TREPMapForm.ApplicationEvents1ShortCut(var Msg: TWMKey; var Handled: Boolean); var b : boolean; i : integer; begin if Msg.KeyData = 65537 then begin // Escape character b := not FitMapBtn.Visible; FitMapBtn.Visible := b; ZoomInImg.Visible := b; VertBarImg.Visible := b; ZoomCursorImg.Visible := b; ZoomOutImg.Visible := b; LayersButton.Visible := b; for i := Low(RightInfos) to High(RightInfos) do begin RightInfos[i].Btn.Visible := b; RightInfos[i].Panel.Visible := b and RightInfos[i].Btn.Down; end; end; end; procedure TREPMapForm.RunHTTPButtonClick(Sender: TObject); const BtnHints : array[boolean] of string = ('Spustí WMS server', 'Zastaví WMS server'); GlyphFileNames : array[boolean] of string = ('Images/Disconnected.png', 'Images/Connected.png'); var p : integer; begin if not RunHTTPButton.Down then IdHTTPServer1.Active := false else begin RunHTTPButton.Down := false; p := IdHTTPServer1.DefaultPort; if REPHTTPServerOptionsFrm.ShowDialog(p) then begin IdHTTPServer1.DefaultPort := p; IdHTTPServer1.Active := true; RunHTTPButton.Down := IdHTTPServer1.Active; end; end; RunHTTPButton.Hint := BtnHints[IdHTTPServer1.Active]; if IdHTTPServer1.Active then RunHTTPButton.Hint := RunHTTPButton.Hint + ' na adrese ' + REPHTTPServerOptionsFrm.SelectedWMSAddress; LoadPNGGlyph(GlyphFileNames[IdHTTPServer1.Active], RunHTTPButton); end; procedure TREPMapForm.IdHTTPServer1CommandGet(AThread: TIdPeerThread; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var QueryFields : TStrings; sRequest, xmlstr, sVersion, bbox, sFormat : string; MinX, MinY, MaxX, MaxY : Double; r : TWMSGetMapRequest; b : TBitmap; begin QueryFields := TStringList.Create; try HTTPApp.ExtractHTTPFields(['&'], [], PChar(ARequestInfo.QueryParams), QueryFields); sRequest := UpperCase(QueryFields.Values[REQUESTPARAM_ID]); if sRequest = 'GETCAPABILITIES' then begin AResponseInfo.ContentText := FileToStr('Capabilities.xml'); AResponseInfo.ContentType := 'text/xml'; end; if sRequest = GETMAP_REQUESTVALUE then begin r := TWMSGetMapRequest.Create; r.QueryFields := QueryFields; ClientWidth := r.Width; ClientHeight := r.Height; bbox := qStr(QueryFields, BBOXPARAM_ID, '-180,-90,180,90'); MinX := GetAndDeleteFloatItem(bbox, ','); MinY := GetAndDeleteFloatItem(bbox, ','); MaxX := GetAndDeleteFloatItem(bbox, ','); MaxY := GetAndDeleteFloatItem(bbox, ','); wc.ViewArea(MinX, MinY, MaxX, MaxY); LoadMapImage; sFormat := r.Format; b := TBitmap.Create; try b.Assign(_BackgroundBMP); LayerImages.DrawToCanvas(0, 0, b.Canvas); AResponseInfo.ContentStream := BMPtoWMSStream(b, sFormat); AResponseInfo.ContentType := sFormat; finally b.Free; end; if Assigned(aResponseInfo.ContentStream) then begin // response stream does exist aResponseInfo.ContentLength := aResponseInfo.ContentStream.Size; // set length aResponseInfo.WriteHeader; // write header aResponseInfo.WriteContent; // return content aResponseInfo.ContentStream.Free; // free stream aResponseInfo.ContentStream := nil; end; end; finally QueryFields.Free; end; end; procedure TREPMapForm.OnShowCoordinatePanel(Sender: TObject); begin if CoordinatePanel.Visible then begin CoorPanel.Calculate; CoorPanel.ShowLastCoordinates; _OnCoorPanelResize(nil); end; end; procedure TREPMapForm._OnCoorPanelResize(Sender: TObject); begin CoordinatePanel.ClientHeight := CoorPanel.Height; end; procedure TREPMapForm.OnHideLayersClick(Sender: TObject); begin LayersButton.Down := false; LayersButtonClick(nil); end; end.
unit Endereco; interface Type TEndereco = class Private FId:integer; FCep:Integer; FRua:string; FNumero:string; FSetor:string; FCidade: String; FUf:string; Procedure SetId(const pId : integer = 0); Procedure SetCep(const pCep : Integer = 0); Procedure SetRua(const pRua : string = ''); Procedure SetNumero(const pNumero : string = ''); Procedure SetSetor(const pSetor : string = ''); Procedure SetCidade(const pCidade : string = ''); Procedure SetUf(const pUf : string = ''); public property Id:Integer Read FId Write SetId; property Cep:Integer Read FCep Write SetCep; property Rua:string Read FRua Write SetRua; property Numero:string Read FNumero Write SetNumero; property Setor:string Read FSetor Write SetSetor; property Cidade:string Read FCidade Write SetCidade; property Uf:string Read FUf Write SetUf; Constructor Create(pId:Integer; pCep:Integer; pRua:String; pNumero:String; pSetor:String; pCidade:String; pUf:string); Overload; End; implementation { TEndereco } constructor TEndereco.Create(pId, pCep: Integer; pRua, pNumero, pSetor, pCidade, pUf: string); begin FId := pId; FCep := pCep; FRua := pRua; FNumero := pNumero; FSetor := pSetor; FCidade := pCidade; FUf := pUf; end; procedure TEndereco.SetCep(const pCep: Integer = 0); begin FCep := pCep; end; procedure TEndereco.SetCidade(const pCidade: string = ''); begin FCidade := pCidade; end; procedure TEndereco.SetId(const pId: integer = 0); begin FId := pId; end; procedure TEndereco.SetNumero(const pNumero: string = ''); begin FNumero := pNumero; end; procedure TEndereco.SetRua(const pRua: string = ''); begin FRua := pRua; end; procedure TEndereco.SetSetor(const pSetor: string = ''); begin FSetor := pSetor; end; procedure TEndereco.SetUf(const pUf: string = ''); begin FUf := pUf; end; end.
unit beautify_tests; interface procedure run_beautifier_tests(); implementation uses jsbeautify, SysUtils, Classes; type EExpectationException = class(Exception); var flags:record indent_size:integer; indent_char:char; preserve_newlines:boolean; space_after_anon_function:boolean; braces_on_own_line :boolean; keep_array_indentation :boolean; end; sl:TStringList; function toUnix(input:string):string; begin result:=StringReplace(input, #13#10, #10, [rfReplaceAll]); end; procedure expect(input, expected:string); var output:string; begin output:= js_beautify( input, flags.indent_size, flags.indent_char, flags.preserve_newlines, 0, 0, flags.space_after_anon_function, flags.braces_on_own_line, flags.keep_array_indentation ); if toUnix(output) <> toUnix(expected) then raise EExpectationException.Create('Input:`'#10+input+#10'` Expected:`'#10+expected+#10'`, but get:`'#10+output+#10'`'); end; // test the input on beautifier with the current flag settings // does not check the indentation / surroundings as bt() does procedure test_fragment(input:string; expected:string=''); begin if expected='' then expected := input; expect(input, expected); end; // test the input on beautifier with the current flag settings // test both the input as well as { input } wrapping procedure bt(input:string; expectation:string = ''); var wrapped_input, wrapped_expectation:string; i:Integer; begin if expectation='' then expectation := input; test_fragment(input, expectation); // test also the returned indentation // e.g if input = "asdf();" // then test that this remains properly formatted as well: // { // asdf(); // indent; // } if (flags.indent_size = 4) and (input<>'') then begin wrapped_input := '{'#10+ input + #10'foo=bar;}'; Sl.text:=expectation; for i:=0 to sl.count -1 do if sl[i]<>'' then sl[i]:=' '+sl[i]; wrapped_expectation := '{'#10 + Sl.text + ' foo = bar;'#10'}'; // wrapped_expectation = '{\n' + expectation.replace(/^(.+)$/mg, ' $1') + '\n foo = bar;\n}'; test_fragment(wrapped_input, wrapped_expectation); end; end; // test the input on beautifier with the current flag settings, // but dont't procedure bt_braces(input, expectation:string); var braces_ex:Boolean; begin braces_ex := flags.braces_on_own_line; flags.braces_on_own_line := true; bt(input, expectation); flags.braces_on_own_line := braces_ex; end; procedure run_beautifier_tests(); begin flags.indent_size := 4; flags.indent_char := ' '; flags.preserve_newlines := true; flags.space_after_anon_function := true; flags.keep_array_indentation := false; flags.braces_on_own_line := false; sl:=TStringList.Create(); sl.Delimiter:=#10; bt(''); bt('return .5'); bt('a = 1', 'a = 1'); bt('a=1', 'a = 1'); bt('a();'#10#10'b();'); bt('var a = 1 var b = 2', 'var a = 1'#10'var b = 2'); bt('var a=1, b=c[d], e=6;', 'var a = 1,'#10' b = c[d],'#10' e = 6;'); bt('a = " 12345 "'); bt('a = '' 12345 '''); bt('if (a == 1) b = 2;', 'if (a == 1) b = 2;'); bt('if(1){2}else{3}', 'if (1) {'#10' 2'#10'} else {'#10' 3'#10'}'); bt('if(1||2);', 'if (1 || 2);'); bt('(a==1)||(b==2)', '(a == 1) || (b == 2)'); bt('var a = 1 if (2) 3;', 'var a = 1'#10'if (2) 3;'); bt('a = a + 1'); bt('a = a == 1'); bt('/12345[^678]*9+/.match(a)'); bt('a /= 5'); bt('a = 0.5 * 3'); bt('a *= 10.55'); bt('a < .5'); bt('a <= .5'); bt('a<.5', 'a < .5'); bt('a<=.5', 'a <= .5'); bt('a = 0xff;'); bt('a=0xff+4', 'a = 0xff + 4'); bt('a = [1, 2, 3, 4]'); bt('F*(g/=f)*g+b', 'F * (g /= f) * g + b'); bt('a.b({c:d})', 'a.b({'#10' c: d'#10'})'); bt('a.b'#10'('#10'{'#10'c:'#10'd'#10'}'#10')', 'a.b({'#10' c: d'#10'})'); bt('a=!b', 'a = !b'); bt('a?b:c', 'a ? b : c'); bt('a?1:2', 'a ? 1 : 2'); bt('a?(b):c', 'a ? (b) : c'); bt('x={a:1,b:w=="foo"?x:y,c:z}', 'x = {'#10' a: 1,'#10' b: w == "foo" ? x : y,'#10' c: z'#10'}'); bt('x=a?b?c?d:e:f:g;', 'x = a ? b ? c ? d : e : f : g;'); bt('x=a?b?c?d:{e1:1,e2:2}:f:g;', 'x = a ? b ? c ? d : {'#10' e1: 1,'#10' e2: 2'#10'} : f : g;'); bt('function void(void) {}'); bt('if(!a)foo();', 'if (!a) foo();'); bt('a=~a', 'a = ~a'); bt('a;/*comment*/b;', 'a; /*comment*/'#10'b;'); bt('a;/* comment */b;', 'a; /* comment */'#10'b;'); test_fragment('a;/*'#10'comment'#10'*/b;', 'a;'#10'/*'#10'comment'#10'*/'#10'b;'); // simple comments don't get touched at all bt('a;/**'#10'* javadoc'#10'*/b;', 'a;'#10'/**'#10' * javadoc'#10' */'#10'b;'); bt('if(a)break;', 'if (a) break;'); bt('if(a){break}', 'if (a) {'#10' break'#10'}'); bt('if((a))foo();', 'if ((a)) foo();'); bt('for(var i=0;;)', 'for (var i = 0;;)'); bt('a++;', 'a++;'); bt('for(;;i++)', 'for (;; i++)'); bt('for(;;++i)', 'for (;; ++i)'); bt('return(1)', 'return (1)'); bt('try{a();}catch(b){c();}finally{d();}', 'try {'#10' a();'#10'} catch (b) {'#10' c();'#10'} finally {'#10' d();'#10'}'); bt('(xx)()'); // magic function call bt('a[1]()'); // another magic function call bt('if(a){b();}else if(c) foo();', 'if (a) {'#10' b();'#10'} else if (c) foo();'); bt('switch(x) {case 0: case 1: a(); break; default: break}', 'switch (x) {'#10'case 0:'#10'case 1:'#10' a();'#10' break;'#10'default:'#10' break'#10'}'); bt('switch(x){case -1:break;case !y:break;}', 'switch (x) {'#10'case -1:'#10' break;'#10'case !y:'#10' break;'#10'}'); bt('a !== b'); bt('if (a) b(); else c();', 'if (a) b();'#10'else c();'); bt('// comment'#10'(function something() {})'); // typical greasemonkey start bt('{'#10''#10' x();'#10''#10'}'); // was: duplicating newlines bt('if (a in b) foo();'); //bt('var a, b'); bt('{a:1, b:2}', '{'#10' a: 1,'#10' b: 2'#10'}'); bt('a={1:[-1],2:[+1]}', 'a = {'#10' 1: [-1],'#10' 2: [+1]'#10'}'); bt('var l = {''a'':''1'', ''b'':''2''}', 'var l = {'#10' ''a'': ''1'','#10' ''b'': ''2'''#10'}'); bt('if (template.user[n] in bk) foo();'); bt('{{}/z/}', '{'#10' {}'#10' /z/'#10'}'); bt('return 45', 'return 45'); bt('If[1]', 'If[1]'); bt('Then[1]', 'Then[1]'); bt('a = 1e10', 'a = 1e10'); bt('a = 1.3e10', 'a = 1.3e10'); bt('a = 1.3e-10', 'a = 1.3e-10'); bt('a = -1.3e-10', 'a = -1.3e-10'); bt('a = 1e-10', 'a = 1e-10'); bt('a = e - 10', 'a = e - 10'); bt('a = 11-10', 'a = 11 - 10'); bt('a = 1;// comment'#10'', 'a = 1; // comment'); bt('a = 1; // comment'#10'', 'a = 1; // comment'); bt('a = 1;'#10' // comment'#10, 'a = 1;'#10'// comment'); bt('if (a) {'#10' do();'#10'}'); // was: extra space appended bt('if'#10'(a)'#10'b();', 'if (a) b();'); // test for proper newline removal bt('if (a) {'#10'// comment'#10'}else{'#10'// comment'#10'}', 'if (a) {'#10' // comment'#10'} else {'#10' // comment'#10'}'); // if/else statement with empty body bt('if (a) {'#10'// comment'#10'// comment'#10'}', 'if (a) {'#10' // comment'#10' // comment'#10'}'); // multiple comments indentation bt('if (a) b() else c();', 'if (a) b()'#10'else c();'); bt('if (a) b() else if c() d();', 'if (a) b()'#10'else if c() d();'); bt('{}'); bt('{'#10''#10'}'); bt('do { a(); } while ( 1 );', 'do {'#10' a();'#10'} while (1);'); bt('do {} while (1);'); bt('do {'#10'} while (1);', 'do {} while (1);'); bt('do {'#10''#10'} while (1);'); bt('var a = x(a, b, c)'); bt('delete x if (a) b();', 'delete x'#10'if (a) b();'); bt('delete x[x] if (a) b();', 'delete x[x]'#10'if (a) b();'); bt('for(var a=1,b=2)', 'for (var a = 1, b = 2)'); bt('for(var a=1,b=2,c=3)', 'for (var a = 1, b = 2, c = 3)'); bt('for(var a=1,b=2,c=3;d<3;d++)', 'for (var a = 1, b = 2, c = 3; d < 3; d++)'); bt('function x(){(a||b).c()}', 'function x() {'#10' (a || b).c()'#10'}'); bt('function x(){return - 1}', 'function x() {'#10' return -1'#10'}'); bt('function x(){return ! a}', 'function x() {'#10' return !a'#10'}'); // a common snippet in jQuery plugins bt('settings = $.extend({},defaults,settings);', 'settings = $.extend({}, defaults, settings);'); bt('{xxx;}()', '{'#10' xxx;'#10'}()'); bt('a = ''a'''#10'b = ''b'''); bt('a = /reg/exp'); bt('a = /reg/'); bt('/abc/.test()'); bt('/abc/i.test()'); bt('{/abc/i.test()}', '{'#10' /abc/i.test()'#10'}'); bt('var x=(a)/a;', 'var x = (a) / a;'); bt('x != -1', 'x != -1'); bt('for (; s-->0;)', 'for (; s-- > 0;)'); bt('for (; s++>0;)', 'for (; s++ > 0;)'); bt('a = s++>s--;', 'a = s++ > s--;'); bt('a = s++>--s;', 'a = s++ > --s;'); bt('{x=#1=[]}', '{'#10' x = #1=[]'#10'}'); bt('{a:#1={}}', '{'#10' a: #1={}'#10'}'); bt('{a:#1#}', '{'#10' a: #1#'#10'}'); test_fragment('{a:1},{a:2}', '{'#10' a: 1'#10'}, {'#10' a: 2'#10'}'); test_fragment('var ary=[{a:1}, {a:2}];', 'var ary = [{'#10' a: 1'#10'},'#10'{'#10' a: 2'#10'}];'); test_fragment('{a:#1', '{'#10' a: #1'); // incomplete test_fragment('{a:#', '{'#10' a: #'); // incomplete test_fragment('}}}', '}'#10'}'#10'}'); // incomplete test_fragment('<!--'#10'void();'#10'// -->', '<!--'#10'void();'#10'// -->'); test_fragment('a=/regexp', 'a = /regexp'); // incomplete regexp bt('{a:#1=[],b:#1#,c:#999999#}', '{'#10' a: #1=[],'#10' b: #1#,'#10' c: #999999#'#10'}'); bt('a = 1e+2'); bt('a = 1e-2'); bt('do{x()}while(a>1)', 'do {'#10' x()'#10'} while (a > 1)'); bt('x(); /reg/exp.match(something)', 'x();'#10'/reg/exp.match(something)'); test_fragment('something();(', 'something();'#10'('); bt('function namespace::something()'); test_fragment('<!--'#10'something();'#10'-->', '<!--'#10'something();'#10'-->'); test_fragment('<!--'#10'if(i<0){bla();}'#10'-->', '<!--'#10'if (i < 0) {'#10' bla();'#10'}'#10'-->'); test_fragment('<!--'#10'something();'#10'-->'#10'<!--'#10'something();'#10'-->', '<!--'#10'something();'#10'-->'#10'<!--'#10'something();'#10'-->'); test_fragment('<!--'#10'if(i<0){bla();}'#10'-->'#10'<!--'#10'if(i<0){bla();}'#10'-->', '<!--'#10'if (i < 0) {'#10' bla();'#10'}'#10'-->'#10'<!--'#10'if (i < 0) {'#10' bla();'#10'}'#10'-->'); bt('{foo();--bar;}', '{'#10' foo();'#10' --bar;'#10'}'); bt('{foo();++bar;}', '{'#10' foo();'#10' ++bar;'#10'}'); bt('{--bar;}', '{'#10' --bar;'#10'}'); bt('{++bar;}', '{'#10' ++bar;'#10'}'); // regexps bt('a(/abc\/\/def/);b()', 'a(/abc\/\/def/);'#10'b()'); bt('a(/a[b\\[\\]c]d/);b()', 'a(/a[b\\[\\]c]d/);'#10'b()'); test_fragment('a(/a[b\\[', 'a(/a[b\\['); // incomplete char class // allow unescaped / in char classes bt('a(/[a/b]/);b()', 'a(/[a/b]/);'#10'b()'); bt('a=[[1,2],[4,5],[7,8]]', 'a = ['#10' [1, 2],'#10' [4, 5],'#10' [7, 8]'#10']'); bt('a=[a[1],b[4],c[d[7]]]', 'a = [a[1], b[4], c[d[7]]]'); bt('[1,2,[3,4,[5,6],7],8]', '[1, 2, [3, 4, [5, 6], 7], 8]'); bt('[[[''1'',''2''],[''3'',''4'']],[[''5'',''6'',''7''],[''8'',''9'',''0'']],[[''1'',''2'',''3''],[''4'',''5'',''6'',''7''],[''8'',''9'',''0'']]]', '['#10' ['#10' [''1'', ''2''],'#10' [''3'', ''4'']'#10' ],'#10' ['#10' [''5'', ''6'', ''7''],'#10' [''8'', ''9'', ''0'']'#10' ],'#10' ['#10' [''1'', ''2'', ''3''],'#10' [''4'', ''5'', ''6'', ''7''],'#10' [''8'', ''9'', ''0'']'#10' ]'#10']'); bt('{[x()[0]];indent;}', '{'#10' [x()[0]];'#10' indent;'#10'}'); bt('return ++i', 'return ++i'); bt('return !!x', 'return !!x'); bt('return !x', 'return !x'); bt('return [1,2]', 'return [1, 2]'); bt('return;', 'return;'); bt('return'#10'func', 'return'#10'func'); bt('catch(e)', 'catch (e)'); bt('var a=1,b={foo:2,bar:3},c=4;', 'var a = 1,'#10' b = {'#10' foo: 2,'#10' bar: 3'#10' },'#10' c = 4;'); bt_braces('var a=1,b={foo:2,bar:3},c=4;', 'var a = 1,'#10' b ='#10' {'#10' foo: 2,'#10' bar: 3'#10' },'#10' c = 4;'); // inline comment bt('function x(/*int*/ start, /*string*/ foo)', 'function x( /*int*/ start, /*string*/ foo)'); // javadoc comment bt('/**'#10'* foo'#10'*/', '/**'#10' * foo'#10' */'); bt(' /**'#10' * foo'#10' */', '/**'#10' * foo'#10' */'); bt('{'#10'/**'#10'* foo'#10'*/'#10'}', '{'#10' /**'#10' * foo'#10' */'#10'}'); bt('var a,b,c=1,d,e,f=2;', 'var a, b, c = 1,'#10' d, e, f = 2;'); bt('var a,b,c=[],d,e,f=2;', 'var a, b, c = [],'#10' d, e, f = 2;'); bt('function () {'#10' var a, b, c, d, e = [],'#10' f;'#10'}'); bt('x();'#10''#10'function(){}', 'x();'#10''#10'function () {}'); bt('do/regexp/;'#10'while(1);', 'do /regexp/;'#10'while (1);'); // hmmm bt('var a = a,'#10'a;'#10'b = {'#10'b'#10'}', 'var a = a,'#10' a;'#10'b = {'#10' b'#10'}'); bt('var a = a,'#10' /* c */'#10' b;'); bt('var a = a,'#10' // c'#10' b;'); bt('foo.(''bar'');'); // weird element referencing bt('if (a) a()'#10'else b()'#10'newline()'); bt('if (a) a()'#10'newline()'); flags.space_after_anon_function := true; test_fragment('// comment 1'#10'(function()', '// comment 1'#10'(function ()'); // typical greasemonkey start bt('var a1, b1, c1, d1 = 0, c = function() {}, d = '''';', 'var a1, b1, c1, d1 = 0,'#10' c = function () {},'#10' d = '''';'); bt('var o1=$.extend(a);function(){alert(x);}', 'var o1 = $.extend(a);'#10''#10'function () {'#10' alert(x);'#10'}'); flags.space_after_anon_function := false; test_fragment('// comment 2'#10'(function()'); // typical greasemonkey start bt('var a2, b2, c2, d2 = 0, c = function() {}, d = '''';', 'var a2, b2, c2, d2 = 0,'#10' c = function() {},'#10' d = '''';'); bt('var o2=$.extend(a);function(){alert(x);}', 'var o2 = $.extend(a);'#10''#10'function() {'#10' alert(x);'#10'}'); bt('{''x'':[{''a'':1,''b'':3},7,8,8,8,8,{''b'':99},{''a'':11}]}', '{'#10' ''x'': [{'#10' ''a'': 1,'#10' ''b'': 3'#10' },'#10' 7, 8, 8, 8, 8,'#10' {'#10' ''b'': 99'#10' },'#10' {'#10' ''a'': 11'#10' }]'#10'}'); bt('{''1'':{''1a'':''1b''},''2''}', '{'#10' ''1'': {'#10' ''1a'': ''1b'''#10' },'#10' ''2'''#10'}'); bt('{a:{a:b},c}', '{'#10' a: {'#10' a: b'#10' },'#10' c'#10'}'); bt('{[y[a]];keep_indent;}', '{'#10' [y[a]];'#10' keep_indent;'#10'}'); bt('if (x) {y} else { if (x) {y}}', 'if (x) {'#10' y'#10'} else {'#10' if (x) {'#10' y'#10' }'#10'}'); bt('if (foo) one()'#10'two()'#10'three()'); bt('if (1 + foo() && bar(baz()) / 2) one()'#10'two()'#10'three()'); bt('if (1 + foo() && bar(baz()) / 2) one();'#10'two();'#10'three();'); flags.indent_size := 1; flags.indent_char := ' '; bt('{ one_char() }', '{'#10' one_char()'#10'}'); bt('var a,b=1,c=2', 'var a, b = 1,'#10' c = 2'); flags.indent_size := 4; flags.indent_char := ' '; bt('{ one_char() }', '{'#10' one_char()'#10'}'); flags.indent_size := 1; flags.indent_char := #9; bt('{ one_char() }', '{'#10#9'one_char()'#10'}'); bt('x = a ? b : c; x;', 'x = a ? b : c;'#10'x;'); flags.indent_size := 4; flags.indent_char := ' '; flags.preserve_newlines := false; bt('var'#10'a=dont_preserve_newlines;', 'var a = dont_preserve_newlines;'); // make sure the blank line between function definitions stays // even when preserve_newlines = false bt('function foo() {'#10' return 1;'#10'}'#10''#10'function foo() {'#10' return 1;'#10'}'); bt('function foo() {'#10' return 1;'#10'}'#10'function foo() {'#10' return 1;'#10'}', 'function foo() {'#10' return 1;'#10'}'#10''#10'function foo() {'#10' return 1;'#10'}' ); bt('function foo() {'#10' return 1;'#10'}'#10''#10''#10'function foo() {'#10' return 1;'#10'}', 'function foo() {'#10' return 1;'#10'}'#10''#10'function foo() {'#10' return 1;'#10'}' ); flags.preserve_newlines := true; bt('var'#10'a=do_preserve_newlines;', 'var'#10'a = do_preserve_newlines;'); flags.keep_array_indentation := true; bt('var x = [{}'#10']', 'var x = [{}'#10']'); bt('var x = [{foo:bar}'#10']', 'var x = [{'#10' foo: bar'#10'}'#10']'); bt('a = [''something'','#10'''completely'','#10'''different''];'#10'if (x);', 'a = [''something'','#10' ''completely'','#10' ''different''];'#10'if (x);'); bt('a = [''a'',''b'',''c'']', 'a = [''a'', ''b'', ''c'']'); bt('a = [''a'', ''b'',''c'']', 'a = [''a'', ''b'', ''c'']'); bt('x = [{''a'':0}]', 'x = [{'#10' ''a'': 0'#10'}]'); bt('{a([[a1]], {b;});}', '{'#10' a([[a1]], {'#10' b;'#10' });'#10'}'); bt('a = //comment'#10'/regex/;'); test_fragment('/*'#10' * X'#10' */'); test_fragment('/*'#13#10' * X'#13#10' */', '/*'#10' * X'#10' */'); bt('if (a)'#10'{'#10'b;'#10'}'#10'else'#10'{'#10'c;'#10'}', 'if (a) {'#10' b;'#10'} else {'#10' c;'#10'}'); flags.braces_on_own_line := true; bt('if (a)'#10'{'#10'b;'#10'}'#10'else'#10'{'#10'c;'#10'}', 'if (a)'#10'{'#10' b;'#10'}'#10'else'#10'{'#10' c;'#10'}'); test_fragment('if (foo) {', 'if (foo)'#10'{'); test_fragment('foo {', 'foo'#10'{'); test_fragment('return {', 'return {'); // return needs the brace. maybe something else as well: feel free to report. // test_fragment('return'#10'{', 'return'#10'{'); // can't support this, but that's an improbable and extreme case anyway. test_fragment('return;'#10'{', 'return;'#10'{'); Sl.free; end; end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit genericutils; interface type generic DefaultUtils <T> = record class function Equals(const A, B: T): Boolean; static; inline; class function LessThan(const A, B: T): Boolean; static; inline; class function GreaterThan(const A, B: T): Boolean; static; inline; end; generic DefaultUnorderedUtils <T> = record class function Equals(const A, B: T): Boolean; static; inline; class function LessThan(const A, B: T): Boolean; static; inline; class function GreaterThan(const A, B: T): Boolean; static; inline; end; generic IncomparableUtils <T> = record class function Equals(const A, B: T): Boolean; static; inline; class function LessThan(const A, B: T): Boolean; static; inline; class function GreaterThan(const A, B: T): Boolean; static; inline; end; TObjectUtils = specialize DefaultUnorderedUtils <TObject>; implementation uses sysutils; class function DefaultUtils.Equals(const A, B: T): Boolean; begin Result := A = B; end; class function DefaultUtils.LessThan(const A, B: T): Boolean; begin Result := A < B; end; class function DefaultUtils.GreaterThan(const A, B: T): Boolean; begin Result := A > B; end; class function DefaultUnorderedUtils.Equals(const A, B: T): Boolean; begin Result := A = B; end; class function DefaultUnorderedUtils.LessThan(const A, B: T): Boolean; begin raise Exception.Create('tried to compare unordered data'); Result := False; end; class function DefaultUnorderedUtils.GreaterThan(const A, B: T): Boolean; begin raise Exception.Create('tried to compare unordered data'); Result := False; end; class function IncomparableUtils.Equals(const A, B: T): Boolean; begin Result := False; end; class function IncomparableUtils.LessThan(const A, B: T): Boolean; begin raise Exception.Create('tried to compare unordered data'); Result := False; end; class function IncomparableUtils.GreaterThan(const A, B: T): Boolean; begin raise Exception.Create('tried to compare unordered data'); Result := False; end; end.
{ By: Richard B. Winston email: rbwinst@usgs.gov This file is in the public domain. It may be used for any purpose. The main purpose of this file is to define TRangeSeries which is used to display values along with associated confidence intervals and/or data ranges. } unit ChartRangeUnit; interface uses Classes, TeEngine, Series, Graphics; type TRangeItem = record Mean: Integer; HighCI: Integer; LowCI: Integer; HighRange: Integer; LowRange: Integer; PixelPosition: Integer; tmpLeftWidth: Integer; tmpRightWidth: Integer; end; TRangeStyle = (rsLineGraph, rsBarGraph); TColorList = class(TObject) private FColors: array of TColor; FCount: integer; procedure Grow; function GetColors(Index: integer): TColor; procedure SetCapacity(const Value: integer); procedure SetColors(Index: integer; const Value: TColor); function GetCapacity: integer; public Constructor Create; procedure Add(AColor: TColor); property Count: integer read FCount; property Capacity: integer read GetCapacity write SetCapacity; property Colors[Index: integer]: TColor read GetColors write SetColors; default; procedure Clear; end; TRangeSeries = class(TCustomSeries) private FShowMean: boolean; FShowRange: boolean; FShowConfidenceIntervals: boolean; FLowConfidenceIntervalValues: TChartValueList; FUpperConfidenceIntervalValues: TChartValueList; FHighRangeValues: TChartValueList; FLowRangeValues: TChartValueList; FBarWidth: integer; FRangeStyle: TRangeStyle; FDrawVertical: boolean; FRangeColors: TColorList; FCiColors: TColorList; procedure CalcItem(ValueIndex: Integer; out AItem: TRangeItem); procedure SetHighRangeValues(const Value: TChartValueList); procedure SetLowConfidenceIntervalValues(const Value: TChartValueList); procedure SetLowRangeValues(const Value: TChartValueList); procedure SetMeanValues(const Value: TChartValueList); procedure SetShowConfidenceIntervals(const Value: boolean); procedure SetShowMean(const Value: boolean); procedure SetShowRange(const Value: boolean); procedure SetUpperConfidenceIntervalValues( const Value: TChartValueList); function GetMeanValues: TChartValueList; procedure SetBarWidth(const Value: integer); function GetDark3D: Boolean; function GetDraw3D: Boolean; procedure SetDark3D(const Value: Boolean); procedure SetDraw3D(const Value: Boolean); procedure SetRangeStyle(const Value: TRangeStyle); procedure SetDrawVertical(const Value: boolean); function MaxValue: Double; function MinValue: Double; protected procedure AddSampleValues(NumValues: Integer); override; procedure DrawValue(ValueIndex: Integer); override; public Procedure Assign(Source:TPersistent); override; Procedure Clear; override; function IsValidSourceOf(Value: TChartSeries): Boolean; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AddMean(const PlotPosition, Mean: Double; Const ALabel:String=''; AColor:TColor=clTeeColor): Integer; overload; function AddMean(const ALabel: string; const Mean: Double; AColor:TColor=clTeeColor): Integer; overload; function AddConfidenceInterval(const PlotPosition, Mean, UpperConfidenceInterval, LowerConfidenceInterval: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function AddConfidenceInterval(const ALabel: string; const Mean, UpperConfidenceInterval, LowerConfidenceInterval: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function AddRange(const PlotPosition, Mean, HighRange, LowRange: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function AddRange(const ALabel: string; const Mean, HighRange, LowRange: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function AddCI_AndRange(const PlotPosition, Mean, UpperConfidenceInterval, LowerConfidenceInterval, HighRange, LowRange: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function AddCI_AndRange(const ALabel: string; const Mean, UpperConfidenceInterval, LowerConfidenceInterval, HighRange, LowRange: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; overload; function MaxXValue: Double; override; function MinXValue: Double; override; function MaxYValue: Double; override; function MinYValue: Double; override; published property BarWidth: integer read FBarWidth write SetBarWidth; property LowConfidenceIntervalValues: TChartValueList read FLowConfidenceIntervalValues write SetLowConfidenceIntervalValues; property HighRangeValues: TChartValueList read FHighRangeValues write SetHighRangeValues; property LowRangeValues: TChartValueList read FLowRangeValues write SetLowRangeValues; property MeanValues: TChartValueList read GetMeanValues write SetMeanValues; property RangeStyle: TRangeStyle read FRangeStyle write SetRangeStyle; property ShowConfidenceIntervals: boolean read FShowConfidenceIntervals write SetShowConfidenceIntervals; property ShowMean: boolean read FShowMean write SetShowMean; property ShowRange: boolean read FShowRange write SetShowRange; property UpperConfidenceIntervalValues: TChartValueList read FUpperConfidenceIntervalValues write SetUpperConfidenceIntervalValues; property Active; property ColorEachPoint; property ColorSource; property Cursor; property Depth; property HorizAxis; property Marks; property ParentChart; property DataSource; property PercentFormat; property SeriesColor; property ShowInLegend; property Title; property ValueFormat; property VertAxis; property XLabelsSource; property AfterDrawValues; property BeforeDrawValues; property OnAfterAdd; property OnBeforeAdd; property OnClearValues; property OnClick; property OnDblClick; property OnGetMarkText; property OnMouseEnter; property OnMouseLeave; property Draw3D: Boolean read GetDraw3D write SetDraw3D default False; property Dark3D: Boolean read GetDark3D write SetDark3D default True; property DrawVertical: boolean read FDrawVertical write SetDrawVertical; end; procedure GetRandomRange(const Mean: Double; out HighRange, LowRange, HighCI, LowCI: Double); var crMeanMessage, crUpperConfidenceIntervalMessage, crLowerConfidenceIntervalMessage, crHighRangeMessage, crLowRangeMessage: string; implementation uses TeCanvas; procedure GetRandomRange(const Mean: Double; out HighRange, LowRange, HighCI, LowCI: Double); var CI: double; UpperRangeInterval: double; LowerRangeInterval: double; begin if Mean = 0 then begin CI := 0.5; UpperRangeInterval := 0.7; LowerRangeInterval := -0.7; end else begin CI := Abs(Random * Mean); UpperRangeInterval := CI + Abs(Random * Mean) * 0.2; LowerRangeInterval := CI + Abs(Random * Mean) * 0.2; end; HighRange := Mean + UpperRangeInterval; LowRange := Mean - LowerRangeInterval; HighCI := Mean + CI; LowCI := Mean - CI; end; { TRangeSeries } function TRangeSeries.AddCI_AndRange(const PlotPosition, Mean, UpperConfidenceInterval, LowerConfidenceInterval, HighRange, LowRange: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := UpperConfidenceInterval; LowConfidenceIntervalValues.TempValue := LowerConfidenceInterval; HighRangeValues.TempValue := HighRange; LowRangeValues.TempValue := LowRange; if DrawVertical then begin result := AddXY(PlotPosition, Mean, ALabel, AColor); end else begin result := AddXY(Mean, PlotPosition, ALabel, AColor); end; end; function TRangeSeries.AddConfidenceInterval(const PlotPosition, Mean, UpperConfidenceInterval, LowerConfidenceInterval: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := UpperConfidenceInterval; LowConfidenceIntervalValues.TempValue := LowerConfidenceInterval; HighRangeValues.TempValue := UpperConfidenceInterval; LowRangeValues.TempValue := LowerConfidenceInterval; if DrawVertical then begin result := AddXY(PlotPosition, Mean, ALabel, AColor); end else begin result := AddXY(Mean, PlotPosition, ALabel, AColor); end; ShowRange := False; end; function TRangeSeries.AddMean(const PlotPosition, Mean: Double; Const ALabel:String=''; AColor:TColor=clTeeColor): Integer; begin FRangeColors.Add(clLtGray); FCiColors.Add(clBlack); UpperConfidenceIntervalValues.TempValue := Mean; LowConfidenceIntervalValues.TempValue := Mean; HighRangeValues.TempValue := Mean; LowRangeValues.TempValue := Mean; if DrawVertical then begin result := AddXY(PlotPosition, Mean, ALabel, AColor); end else begin result := AddXY(Mean, PlotPosition, ALabel, AColor); end; ShowRange := False; ShowConfidenceIntervals := False; end; function TRangeSeries.AddRange(const PlotPosition, Mean, HighRange, LowRange: Double; Const ALabel:String=''; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := HighRange; LowConfidenceIntervalValues.TempValue := LowRange; HighRangeValues.TempValue := HighRange; LowRangeValues.TempValue := LowRange; if DrawVertical then begin result := AddXY(PlotPosition, Mean, ALabel, AColor); end else begin result := AddXY(Mean, PlotPosition, ALabel, AColor); end; ShowConfidenceIntervals := False; end; function TRangeSeries.AddRange(const ALabel: string; const Mean, HighRange, LowRange: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := HighRange; LowConfidenceIntervalValues.TempValue := LowRange; HighRangeValues.TempValue := HighRange; LowRangeValues.TempValue := LowRange; if DrawVertical then begin result := AddY(Mean, ALabel, AColor); end else begin result := AddX(Mean, ALabel, AColor); end; ShowConfidenceIntervals := False; end; procedure TRangeSeries.AddSampleValues(NumValues: Integer); var Mean: Double; HighRange: Double; LowRange: Double; HighCI: Double; LowCI: Double; t: Integer; begin with RandomBounds(NumValues) do begin for t := 1 to NumValues do begin Mean := MinY + Random(Round(DifY)); { starting open price } { Generate random figures } GetRandomRange(Mean, HighRange, LowRange, HighCI, LowCI); { call the standard add method } AddCI_AndRange(tmpX, Mean, HighCI, LowCI, HighRange, LowRange); tmpX := tmpX + StepX; { <-- next point X value } end; end; end; procedure TRangeSeries.CalcItem(ValueIndex: Integer; out AItem: TRangeItem); begin if DrawVertical then begin with AItem do begin PixelPosition := CalcXPosValue(XValues.Value[ValueIndex]); { The horizontal position } { Vertical positions of Open, High, Low & Close values for this point } Mean := CalcYPosValue(MeanValues.Value[ValueIndex]); HighCI := CalcYPosValue(UpperConfidenceIntervalValues.Value[ValueIndex]); LowCI := CalcYPosValue(LowConfidenceIntervalValues.Value[ValueIndex]); HighRange := CalcYPosValue(HighRangeValues.Value[ValueIndex]); LowRange := CalcYPosValue(LowRangeValues.Value[ValueIndex]); tmpLeftWidth := FBarWidth div 2; { calc half bar Width } tmpRightWidth := FBarWidth - tmpLeftWidth; end; end else begin with AItem do begin PixelPosition := CalcYPosValue(YValues.Value[ValueIndex]); { The vertical position } { horizontal positions of Open, High, Low & Close values for this point } Mean := CalcXPosValue(MeanValues.Value[ValueIndex]); HighCI := CalcXPosValue(UpperConfidenceIntervalValues.Value[ValueIndex]); LowCI := CalcXPosValue(LowConfidenceIntervalValues.Value[ValueIndex]); HighRange := CalcXPosValue(HighRangeValues.Value[ValueIndex]); LowRange := CalcXPosValue(LowRangeValues.Value[ValueIndex]); tmpLeftWidth := FBarWidth div 2; { calc half bar Width } tmpRightWidth := FBarWidth - tmpLeftWidth; end; end; end; constructor TRangeSeries.Create(AOwner: TComponent); begin inherited; FRangeColors := TColorList.Create; FCiColors := TColorList.Create; FDrawVertical := True; FShowMean := True; FShowRange := True; FShowConfidenceIntervals := True; FBarWidth := 10; YValues.Name := crMeanMessage; FHighRangeValues := TChartValueList.Create(Self, crHighRangeMessage); FLowRangeValues := TChartValueList.Create(Self, crLowRangeMessage); FLowConfidenceIntervalValues := TChartValueList.Create(Self, crLowerConfidenceIntervalMessage); FUpperConfidenceIntervalValues := TChartValueList.Create(Self, crUpperConfidenceIntervalMessage); Pointer.Style := psStar; end; type TPointerAccess = class(TSeriesPointer); procedure TRangeSeries.DrawValue(ValueIndex: Integer); var tmpStyle: TSeriesPointerStyle; tmpItem: TRangeItem; AColor: TColor; OldBrushColor, OldPenColor, RangeColor, CiColor: TColor; begin // Don't call inherited. // inherited; RangeColor := FRangeColors[ValueIndex]; CiColor := FCiColors[ValueIndex]; if ColorEachPoint then begin AColor := ValueColor[ValueIndex]; end else begin AColor := SeriesColor; end; if Assigned(OnGetPointerStyle) then tmpStyle := OnGetPointerStyle(Self, ValueIndex) else tmpStyle := Pointer.Style; { Prepare Pointer Pen and Brush styles } TPointerAccess(Pointer).PrepareCanvas(ParentChart.Canvas, AColor); CalcItem(ValueIndex, tmpItem); with tmpItem, ParentChart {, Canvas} do begin case RangeStyle of rsLineGraph: begin if View3D and Pointer.Draw3D then begin if ShowRange then begin OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Brush.Color := RangeColor; if DrawVertical then begin Canvas.Cube( PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, HighRange, LowRange, StartZ, EndZ, True); end else begin Canvas.Cube( HighRange, LowRange, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, StartZ, EndZ, True); end; finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; if ShowConfidenceIntervals then begin Brush.Color := AColor; if DrawVertical then begin //here Canvas.RectangleY(PixelPosition - tmpLeftWidth, LowCI, PixelPosition + tmpRightWidth, StartZ, EndZ); Canvas.RectangleZ(PixelPosition, HighCI, LowCI, StartZ, EndZ); Canvas.RectangleY(PixelPosition - tmpLeftWidth, HighCI, PixelPosition + tmpRightWidth, StartZ, EndZ); end else begin Canvas.RectangleZ(LowCI, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, StartZ, EndZ); Canvas.RectangleY(LowCI, PixelPosition, HighCI, StartZ, EndZ); Canvas.RectangleZ(HighCI, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, StartZ, EndZ); end; end; end else begin if ShowRange then begin OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Brush.Color := RangeColor; if View3D then begin if DrawVertical then begin Canvas.Cube( PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, HighRange, LowRange, StartZ, EndZ, True); end else begin Canvas.RectangleZ(HighRange, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, StartZ, EndZ); Canvas.RectangleZ(LowRange, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, StartZ, EndZ); end; end else begin if DrawVertical then begin Canvas.Rectangle(PixelPosition - tmpLeftWidth, HighRange, PixelPosition + tmpRightWidth, LowRange); end else begin Canvas.Rectangle(HighRange, PixelPosition - tmpLeftWidth, LowRange, PixelPosition + tmpRightWidth); end; end; finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; if ShowConfidenceIntervals {or ShowRange} then begin OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Pen.Color := CiColor; if View3D then begin if DrawVertical then begin Canvas.RectangleZ(PixelPosition, HighCI, LowCI, StartZ, EndZ); end else begin Canvas.RectangleZ(HighCI, LowCI, PixelPosition, StartZ, EndZ); end; end else begin if DrawVertical then begin Canvas.DoVertLine(PixelPosition, HighCI, LowCI); end else begin Canvas.DoHorizLine(HighCI, LowCI, PixelPosition); end; end finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; if ShowConfidenceIntervals then begin OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Pen.Color := CiColor; Brush.Color := AColor; if DrawVertical then begin Canvas.DoHorizLine(PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, HighCI); Canvas.DoHorizLine(PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, LowCI); end else begin Canvas.DoVertLine(HighCI, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth); Canvas.DoVertLine(LowCI, PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth); end; finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; end; end; rsBarGraph: begin if View3D and Pointer.Draw3D then begin if ShowRange then begin if DrawVertical then begin Canvas.VertLine3D(PixelPosition, HighRange, LowRange, MiddleZ); end else begin Canvas.HorizLine3D(HighRange, LowRange, PixelPosition, MiddleZ); end; end; if ShowConfidenceIntervals then begin OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Pen.Color := CiColor; Brush.Color := AColor; if HighCI = LowCI then Pen.Color := AColor; Canvas.Cube(PixelPosition - tmpLeftWidth, PixelPosition + tmpRightWidth, HighCI, LowCI, StartZ, EndZ, Pointer.Dark3D); finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; end else begin if ShowRange then begin if View3D then begin if DrawVertical then begin Canvas.VertLine3D(PixelPosition, HighRange, LowRange, MiddleZ); end else begin Canvas.HorizLine3D(HighRange, LowRange, PixelPosition, MiddleZ); end; end else begin if DrawVertical then begin Canvas.DoVertLine(PixelPosition, HighRange, LowRange); end else begin Canvas.DoHorizLine(HighRange, LowRange, MiddleZ); end; end; end; if ShowConfidenceIntervals then begin // prevent zero height rectangles if HighCI = LowCI then Dec(LowCI); OldBrushColor := Canvas.Brush.Color; OldPenColor := Canvas.Pen.Color; try Canvas.Pen.Color := CiColor; // draw the candle Brush.Color := AColor; if View3D then Canvas.RectangleWithZ(TeeRect(PixelPosition - tmpLeftWidth, HighCI, PixelPosition + tmpRightWidth, LowCI), MiddleZ) else begin if not Self.Pen.Visible then if HighCI < LowCI then Dec(HighCI) else Dec(LowCI); Canvas.Rectangle(PixelPosition - tmpLeftWidth, HighCI, PixelPosition + tmpRightWidth + 1, LowCI); end; finally Canvas.Brush.Color := OldBrushColor; Canvas.Pen.Color := OldPenColor; end; end; end; end; else Assert(False); end; if ShowMean then begin if DrawVertical then begin Pointer.DrawPointer(ParentChart.Canvas, ParentChart.View3D, PixelPosition, Mean, Pointer.HorizSize, Pointer.VertSize, AColor, tmpStyle); end else begin Pointer.DrawPointer(ParentChart.Canvas, ParentChart.View3D, Mean, PixelPosition, Pointer.HorizSize, Pointer.VertSize, AColor, tmpStyle); end; end; end; end; function TRangeSeries.GetDark3D: Boolean; begin result := Pointer.Dark3D; end; function TRangeSeries.GetDraw3D: Boolean; begin result := Pointer.Draw3D; end; function TRangeSeries.GetMeanValues: TChartValueList; begin if DrawVertical then begin result := YValues; { overrides default YValues } end else begin result := XValues; { overrides default XValues } end; end; function TRangeSeries.IsValidSourceOf(Value: TChartSeries): Boolean; begin result := Value is TRangeSeries; end; function TRangeSeries.MaxYValue: Double; begin if DrawVertical then begin result := MaxValue; end else begin result := inherited MaxYValue; end; end; function TRangeSeries.MinYValue: Double; begin if DrawVertical then begin result := MinValue; end else begin result := inherited MinYValue; end; end; procedure TRangeSeries.SetBarWidth(const Value: integer); begin if FBarWidth <> Value then begin FBarWidth := Value; Repaint; end; end; procedure TRangeSeries.SetDark3D(const Value: Boolean); begin Pointer.Dark3D := Value; end; procedure TRangeSeries.SetDraw3D(const Value: Boolean); begin Pointer.Draw3D := Value; end; procedure TRangeSeries.SetHighRangeValues(const Value: TChartValueList); begin SetChartValueList(FHighRangeValues, Value); end; procedure TRangeSeries.SetLowConfidenceIntervalValues( const Value: TChartValueList); begin SetChartValueList(FLowConfidenceIntervalValues, Value); end; procedure TRangeSeries.SetLowRangeValues(const Value: TChartValueList); begin SetChartValueList(FLowRangeValues, Value); end; procedure TRangeSeries.SetMeanValues(const Value: TChartValueList); begin SetYValues(Value); { overrides default YValues } end; procedure TRangeSeries.SetRangeStyle(const Value: TRangeStyle); begin if FRangeStyle <> Value then begin FRangeStyle := Value; Repaint; end; end; procedure TRangeSeries.SetShowConfidenceIntervals(const Value: boolean); begin if FShowConfidenceIntervals <> Value then begin FShowConfidenceIntervals := Value; Repaint; end; end; procedure TRangeSeries.SetShowMean(const Value: boolean); begin if FShowMean <> Value then begin FShowMean := Value; Repaint; end; end; procedure TRangeSeries.SetShowRange(const Value: boolean); begin if FShowRange <> Value then begin FShowRange := Value; Repaint; end; end; procedure TRangeSeries.SetUpperConfidenceIntervalValues( const Value: TChartValueList); begin SetChartValueList(FUpperConfidenceIntervalValues, Value); end; procedure SetChartRangeMessages; begin crMeanMessage := 'Mean'; crUpperConfidenceIntervalMessage := 'Upper Confidence Interval'; crLowerConfidenceIntervalMessage := 'Lower Confidence Interval'; crHighRangeMessage := 'High Range'; crLowRangeMessage := 'Low Range'; end; function TRangeSeries.AddCI_AndRange(const ALabel: string; const Mean, UpperConfidenceInterval, LowerConfidenceInterval, HighRange, LowRange: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := UpperConfidenceInterval; LowConfidenceIntervalValues.TempValue := LowerConfidenceInterval; HighRangeValues.TempValue := HighRange; LowRangeValues.TempValue := LowRange; if DrawVertical then begin result := AddY(Mean, ALabel, AColor); end else begin result := AddX(Mean, ALabel, AColor); end; end; function TRangeSeries.AddConfidenceInterval(const ALabel: string; const Mean, UpperConfidenceInterval, LowerConfidenceInterval: Double; AColor:TColor=clTeeColor; CiColor: TColor = clBlack; RangeColor: TColor = clLtGray): Integer; begin FRangeColors.Add(RangeColor); FCiColors.Add(CiColor); UpperConfidenceIntervalValues.TempValue := UpperConfidenceInterval; LowConfidenceIntervalValues.TempValue := LowerConfidenceInterval; HighRangeValues.TempValue := UpperConfidenceInterval; LowRangeValues.TempValue := LowerConfidenceInterval; if DrawVertical then begin result := AddY(Mean, ALabel, AColor); end else begin result := AddX(Mean, ALabel, AColor); end; ShowRange := False; end; function TRangeSeries.AddMean(const ALabel: string; const Mean: Double; AColor:TColor=clTeeColor): Integer; begin FRangeColors.Add(clLtGray); FCiColors.Add(clBlack); UpperConfidenceIntervalValues.TempValue := Mean; LowConfidenceIntervalValues.TempValue := Mean; HighRangeValues.TempValue := Mean; LowRangeValues.TempValue := Mean; if DrawVertical then begin result := AddY(Mean, ALabel, AColor); end else begin result := AddX(Mean, ALabel, AColor); end; ShowRange := False; ShowConfidenceIntervals := False; end; procedure TRangeSeries.Assign(Source: TPersistent); begin if Source is TRangeSeries then With TRangeSeries(Source) do begin Self.BarWidth :=BarWidth; Self.ShowMean :=ShowMean; Self.ShowConfidenceIntervals :=ShowConfidenceIntervals; Self.ShowRange :=ShowRange; Self.MeanValues :=MeanValues; Self.UpperConfidenceIntervalValues := UpperConfidenceIntervalValues; Self.LowConfidenceIntervalValues :=LowConfidenceIntervalValues; Self.HighRangeValues :=HighRangeValues; Self.LowRangeValues :=LowRangeValues; Self.RangeStyle :=RangeStyle; end; inherited; end; procedure TRangeSeries.SetDrawVertical(const Value: boolean); begin if FDrawVertical <> Value then begin FDrawVertical := Value; Repaint; end; end; function TRangeSeries.MaxValue: Double; var temp1, temp2: double; resultSet: boolean; begin result := 0; resultSet := False; if ShowMean then begin result := MeanValues.MaxValue; resultSet := True; end; if ShowConfidenceIntervals then begin temp1 := LowConfidenceIntervalValues.MaxValue; temp2 := UpperConfidenceIntervalValues.MaxValue; if temp2 > temp1 then begin temp1 := temp2; end; if resultSet then begin if temp1 > result then begin result := temp1; end; end else begin result := temp1; end; resultSet := True; end; if ShowRange then begin temp1 := HighRangeValues.MaxValue; temp2 := LowRangeValues.MaxValue; if temp2 > temp1 then begin temp1 := temp2; end; if resultSet then begin if temp1 > result then begin result := temp1; end; end else begin result := temp1; end; end; end; function TRangeSeries.MaxXValue: Double; begin if not DrawVertical then begin result := MaxValue; end else begin result := inherited MaxXValue; end; end; function TRangeSeries.MinValue: Double; var temp1, temp2: double; resultSet: boolean; begin result := 0; resultSet := False; if ShowMean then begin result := MeanValues.MinValue; resultSet := True; end; if ShowConfidenceIntervals then begin temp1 := LowConfidenceIntervalValues.MinValue; temp2 := UpperConfidenceIntervalValues.MinValue; if temp2 < temp1 then begin temp1 := temp2; end; if resultSet then begin if temp1 < result then begin result := temp1; end; end else begin result := temp1; end; resultSet := True; end; if ShowRange then begin temp1 := HighRangeValues.MinValue; temp2 := LowRangeValues.MinValue; if temp2 < temp1 then begin temp1 := temp2; end; if resultSet then begin if temp1 < result then begin result := temp1; end; end else begin result := temp1; end; end; end; function TRangeSeries.MinXValue: Double; begin if not DrawVertical then begin result := MinValue; end else begin result := inherited MinXValue; end; end; procedure TRangeSeries.Clear; begin inherited; FRangeColors.Clear; FCiColors.Clear; end; destructor TRangeSeries.Destroy; begin inherited; FCiColors.Free; FRangeColors.Free; end; { TColorList } procedure TColorList.Add(AColor: TColor); begin if Capacity = FCount then begin Grow; end; FColors[FCount] := AColor; Inc(FCount); end; procedure TColorList.Clear; begin SetLength(FColors, 0); FCount := 0; end; constructor TColorList.Create; begin FCount := 0; end; function TColorList.GetCapacity: integer; begin result := Length(FColors); end; function TColorList.GetColors(Index: integer): TColor; begin result := FColors[Index]; end; procedure TColorList.Grow; var Delta: integer; LocalCapacity : integer; begin LocalCapacity := Capacity; if LocalCapacity <= 16 then begin Delta := 4 end else begin Delta := LocalCapacity div 4; end; Inc(LocalCapacity, Delta); SetLength(FColors, LocalCapacity); end; procedure TColorList.SetCapacity(const Value: integer); begin SetLength(FColors, Value); end; procedure TColorList.SetColors(Index: integer; const Value: TColor); begin FColors[Index] := Value; end; initialization SetChartRangeMessages; end.
unit UTreeNavigator; interface uses windows, Messages, CommCtrl, UxlWinControl, UxlDragControl, UNavigatorSuper, UxlTreeView, UxlMiscCtrls, UxlExtClasses, UPageSuper; type TTreeNavigator = class (TNavigatorSuper, IOptionObserver) private FTree: TxlTreeView; FCurrentPage: TPageSuper; FDisableSelChangeMessage: boolean; function Page (h: HTreeItem): TPageSuper; function f_FindItem (value: TPageSuper): HTreeItem; function f_GetTreeItem (o_page: TPageSuper): TTreeViewItem; function f_OnTreeSelChanging (oldhandle, newhandle: HTreeItem): integer; function f_OnTreeBeginLabelEdit (handle: HTreeItem; const newtext: widestring): integer; function f_OnTreeEndLabelEdit (handle: HTreeItem; const newtext: widestring): integer; procedure f_OnTreeContextMenu (handle: HTreeItem); procedure f_OnTreeItemFirstExpanding (h: HTreeItem); procedure f_OnTreeItemDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean); function f_ProcessTreeMessage (AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; procedure f_PopulateChildNodes (hParent: HTreeItem); protected procedure LoadIndex (); override; procedure SelectPage (value: TPageSuper); override; procedure AddPage (value: TPageSuper); override; procedure ResetPage (value: TPageSuper); override; procedure DeletePage (value: TPageSuper); override; procedure RenamePage (value: TPageSuper); override; public constructor Create (WndParent: TxlWinContainer); destructor Destroy (); override; function Control (): TxlDragControl; override; procedure Optionchanged (); end; implementation uses Resource, UGlobalObj, UxlList, UxlClasses, UxlCommDlgs, UxlWindow, UxlWinDef, UxlStrUtils, UPageStore, UPageFactory, UOptionManager, UTypeDef; constructor TTreeNavigator.Create (WndParent: TxlWinContainer); begin FTree := TxlTreeView.create (WndParent); with FTree do begin Images := PageImageList.Images; CanDrag := true; CanDrop := true; Items.OnSelChanging := f_OnTreeSelChanging; Items.OnBeginLabelEdit := f_OnTreeBeginLabelEdit; Items.OnEndLabelEdit := f_OnTreeEndLabelEdit; OnContextMenu := f_OnTreeContextMenu; Items.OnFirstExpanding := f_OnTreeItemFirstExpanding; OnDropEvent := f_OnTreeItemDropEvent; MessageHandler := f_ProcessTreeMessage; end; OptionMan.AddObserver(self); end; destructor TTreeNavigator.Destroy (); begin OptionMan.RemoveObserver(self); FTree.free; inherited; end; function TTreeNavigator.Control (): TxlDragControl; begin result := FTree; end; procedure TTreeNavigator.Optionchanged (); var o_tvstyle: TTreeViewStyle; begin FTree.Font := OptionMan.Options.TreeFont; FTree.Color := OptionMan.Options.TreeColor; with o_tvstyle do begin EditLabels := true; NoHScroll := not OptionMan.Options.TreeHorzScroll; HasButtons := OptionMan.Options.NodeButtons; HasLines := OptionMan.Options.NodeLines; LinesAtRoot := OptionMan.Options.LinesAtRoot; end; FTree.Style := o_tvstyle; if OptionMan.Options.ShowNodeImages <> FTree.ShowImages then begin FTree.ShowImages := OptionMan.Options.ShowNodeImages; if Active then begin LoadIndex (); SelectPage (FCurrentPage); end; end; end; //-------------------- procedure TTreeNavigator.LoadIndex (); begin FDisableSelChangeMessage := true; // 否则 Items.Clear 会引起 SelChanging 事件 FTree.Items.Clear; f_PopulateChildNodes (nil); FDisableSelChangeMessage := false; end; function TTreeNavigator.Page (h: HTreeItem): TPageSuper; var id: integer; begin if h = nil then result := Root else begin id := FTree.Items[h].data; result := PageStore[id]; end; end; procedure TTreeNavigator.f_PopulateChildNodes (hParent: HTreeItem); var o_page: TPageSuper; o_list: TxlIntList; i: integer; o_item: TTreeViewItem; begin if hParent = nil then o_page := Root else o_page := Page(hParent); o_list := TxlIntList.Create; o_page.GetChildList (o_list); for i := o_list.Low to o_list.High do begin o_item := f_GetTreeItem (PageStore[o_list[i]]); FTree.Items.AddChild (hParent, o_item); end; o_list.free; end; function TTreeNavigator.f_GetTreeItem (o_page: TPageSuper): TTreeViewItem; begin with result do begin if FTree.ShowImages then text := o_page.name else text := f_NameToLabel (o_page); data := o_page.id; image := o_page.ImageIndex; selectedimage := image; state := 0; children := (o_page.Childs <> nil) and (o_page.Childs.HasChildInTree); end; end; procedure TTreeNavigator.SelectPage (value: TPageSuper); var h: HTreeItem; begin h := f_FindItem(value); if h <> nil then begin FTree.Items.Select (h, false); FCurrentPage := value; end; end; function TTreeNavigator.f_FindItem (value: TPageSuper): HTreeItem; function f_FindFrom (hParent: HTreeItem; o_list: TxlObjList; i_depth: integer): HTreeItem; // 逐层定位 var h: HTreeItem; begin if hParent <> nil then begin FTree.Items.Expand (hParent); h := FTree.Items.Find (fmChildItem, hParent); end else h := FTree.Items.Find (fmRootItem); while (h <> nil) and (Page(h) <> TPageSuper(o_list[i_depth])) do h := FTree.Items.Find (fmNextItem, h); if h = nil then result := nil else if i_depth < o_list.High then result := f_FindFrom (h, o_list, i_depth + 1) else result := h; end; var o_list: TxlObjList; p: TPageSuper; begin result := nil; if value = nil then exit; // Get Ancestors o_list := TxlObjList.Create; o_list.Add (value); p := value.Owner; while p <> nil do begin o_list.InsertFirst (p); if p.Owner = p then exit; // 防止死循环 p := p.Owner; end; result := f_FindFrom (nil, o_list, o_list.low + 1); o_list.Free; end; procedure TTreeNavigator.AddPage (value: TPageSuper); procedure f_AddChildNode (hOwner: HTREEITEM; o_page: TPageSuper); var o_item: TTreeViewItem; h: HTreeItem; o_list: TxlIntList; i: integer; begin o_item := f_GetTreeItem (o_page); o_list := TxlIntList.Create; Page(hOwner).GetChildList (o_list); h := nil; for i := o_list.High downto o_list.Low do if o_list[i] = o_page.id then begin if h = nil then FTree.Items.AddChild (hOwner, o_item) else FTree.Items.InsertBefore(h, o_item); break; end else if h = nil then h := f_FindItem (PageStore[o_list[i]]) else h := FTree.Items.Find (fmPreviousItem, h); o_list.free; end; var h: HTreeItem; o_item: TTreeViewItem; begin h := f_FindItem (value.Owner); if h <> nil then begin o_item := FTree.Items[h]; o_item.Children := true; FTree.Items[h] := o_item; FTree.Items.Expand (h); end; if f_FindItem (value) = nil then f_AddChildNode (h, value); end; procedure TTreeNavigator.ResetPage (value: TPageSuper); var h: HTreeItem; begin h := f_FindItem (value); if h <> nil then FTree.Items[h] := f_GetTreeItem (value); end; procedure TTreeNavigator.RenamePage (value: TPageSuper); var h: HTreeItem; begin h := f_FindItem (value); if h <> nil then FTree.Items.EditLabel (h); end; procedure TTreeNavigator.DeletePage (value: TPageSuper); var h: HTreeItem; begin h := f_FindItem (value); if h <> nil then FTree.Items.Delete (h, false); end; //------------------- function TTreeNavigator.f_OnTreeSelChanging (oldhandle, newhandle: HTreeItem): integer; begin if (oldhandle <> newhandle) and (not FDisableSelChangeMessage) then PageCenter.ActivePage := Page(newhandle); result := 0; end; function TTreeNavigator.f_OnTreeBeginLabelEdit (handle: HTreeItem; const newtext: widestring): integer; var h_edit: HWND; s_label: widestring; begin result := 0; if FTree.ShowImages then exit; h_edit := FTree.Perform (TVM_GETEDITCONTROL, 0, 0); if h_edit = 0 then exit; s_label := Page(handle).name; SetWindowTextW (h_edit, pwidechar(s_label)); SendMessageW (h_edit, EM_SETSEL, 0, -1); end; function TTreeNavigator.f_OnTreeEndLabelEdit (handle: HTreeItem; const newtext: widestring): integer; begin if newtext <> '' then begin Page(handle).name := MultiLineToSingleLine (newtext, true); result := 1; // accept change EventMan.EventNotify (e_PageNameChanged, Page(handle).id); end else result := 0; end; procedure TTreeNavigator.f_OnTreeContextMenu (handle: HTreeItem); var p: TPageSuper; i_context: integer; begin p := Page(handle); if (p <> nil) and (p <> PageCenter.ActivePage) then PageCenter.ActivePage := p else p := PageCenter.ActivePage; case p.PageType of ptSearch: i_context := SearchContext; ptRecycleBin: i_context := RecycleBinContext; ptRecentModify, ptRecentCreate, ptRecentVisit: i_context := RecentPagesContext; ptRecentRoot, ptTemplate, ptFavorite, ptClip, ptFastLink: i_context := SysPageContext; else i_context := PageContext; end; EventMan.EventNotify (e_ContextMenuDemand, i_context); end; procedure TTreeNavigator.f_OnTreeItemFirstExpanding (h: HTreeItem); begin f_PopulateChildNodes (h); end; procedure TTreeNavigator.f_OnTreeItemDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean); var o_page: TPageSuper; begin if (hidxTarget >= 0) and assigned (OnDropItems) then begin o_page := Page(HTreeItem(hidxTarget)); OnDropItems (o_dragsource, o_page.id, o_page.Owner.id, b_copy); end; end; function TTreeNavigator.f_ProcessTreeMessage (AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWord; begin case AMessage of WM_MBUTTONUP: begin if OptionMan.Options.PageMButtonClick = pbDelete then CommandMan.ExecuteCommand(m_deletepage) else CommandMan.ExecuteCommand(m_switchLock); result := 0; b_processed := true; end; else b_processed := false; end; end; end.
unit cmpTextDisplay; interface uses SysUtils, Classes, Controls, Forms; type TCustomTextDisplay = class(TCustomControl) private { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } end; TTextDisplay = class (TCustomTextDisplay) published property Align; property Anchors; property AutoSize; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind; property BevelWidth; property BiDiMode; property Constraints; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property Color nodefault; property Ctl3D; property Font; property ParentBiDiMode; property ParentBackground default False; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnDockDrop; property OnDockOver; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; implementation end.
unit MqttUtils; interface {$I mormot.defines.inc} uses sysutils, classes, mormot.core.base, mormot.core.os, mormot.core.rtti, mormot.core.data, mormot.core.text, mormot.core.unicode, mormot.core.log, mormot.net.sock, mormot.net.server, mormot.net.async_rw; type TMQTTMessageType = ( mtBROKERCONNECT, // 0 Broker request to connect to Broker mtCONNECT, // 1 Client request to connect to Broker mtCONNACK, // 2 Connect Acknowledgment mtPUBLISH, // 3 Publish message mtPUBACK, // 4 Publish Acknowledgment mtPUBREC, // 5 Publish Received (assured delivery part 1) mtPUBREL, // 6 Publish Release (assured delivery part 2) mtPUBCOMP, // 7 Publish Complete (assured delivery part 3) mtSUBSCRIBE, // 8 Client Subscribe request mtSUBACK, // 9 Subscribe Acknowledgment mtUNSUBSCRIBE, // 10 Client Unsubscribe request mtUNSUBACK, // 11 Unsubscribe Acknowledgment mtPINGREQ, // 12 PING Request mtPINGRESP, // 13 PING Response mtDISCONNECT, // 14 Client is Disconnecting mtReserved15 // 15 ); const CON_MQTT_MAXBYTE = 2048; CON_MQTT_MAXSUB = 5; MQTT_PROTOCOLV3 = 'MQIsdp'; MQTT_VERSION3 = 3; MQTT_VERSION3_CHAR = #3; MQTT_VERSIONLEN3 = 6; MQTT_VERSIONLEN3_CHAR = #6; MQTT_PROTOCOLV311 = 'MQTT'; MQTT_VERSION4 = 4; MQTT_VERSIONLEN311_CHAR = #4; MQTT_VERSION4_CHAR = #4; MQTT_VERSIONLEN311 = 4; MsgNames : array [TMQTTMessageType] of string = ( 'BROKERCONNECT', // 0 Broker request to connect to Broker 'CONNECT', // 1 Client request to connect to Broker 'CONNACK', // 2 Connect Acknowledgment 'PUBLISH', // 3 Publish message 'PUBACK', // 4 Publish Acknowledgment 'PUBREC', // 5 Publish Received (assured delivery part 1) 'PUBREL', // 6 Publish Release (assured delivery part 2) 'PUBCOMP', // 7 Publish Complete (assured delivery part 3) 'SUBSCRIBE', // 8 Client Subscribe request 'SUBACK', // 9 Subscribe Acknowledgment 'UNSUBSCRIBE', // 10 Client Unsubscribe request 'UNSUBACK', // 11 Unsubscribe Acknowledgment 'PINGREQ', // 12 PING Request 'PINGRESP', // 13 PING Response 'DISCONNECT', // 14 Client is Disconnecting 'Reserved15' // 15 ); qtAT_MOST_ONCE=0; // 0 At most once Fire and Forget <=1 qtAT_LEAST_ONCE=1; // 1 At least once Acknowledged delivery >=1 qtAT_EXACTLY_ONCE=2; // 2 Exactly once Assured delivery =1 qtAT_Reserved3=3; // 3 Reserved QOSNames : array [0..3] of string = ( 'AT_MOST_ONCE', // 0 At most once Fire and Forget <=1 'AT_LEAST_ONCE', // 1 At least once Acknowledged delivery >=1 'EXACTLY_ONCE', // 2 Exactly once Assured delivery =1 'RESERVED' // 3 Reserved ); {type TMqttSocket = class(TMqttServerSocket) protected public constructor Create(aServer: TAsyncServer;aTimeOut: PtrInt); reintroduce; function Login(headerMaxTix:Int64):TMqttLoginResult; override; end; } function mqtt_getframelen(p:Pointer;len:integer;out lenbyte:integer):integer; function mqtt_readstr(p:Pointer;leftlen:integer;out sstr:RawByteString):integer; function mqtt_AddTopic(const buf:RawByteString;var topics:TShortStringDynArray):integer; function mqtt_DelTopic(const buf:RawByteString;var topics:TShortStringDynArray):integer; function mqtt_compareTitle(const at:RawByteString;topics:TShortStringDynArray):boolean; function mqtt_get_lenth(alen:integer):RawByteString; function mqtt_get_strlen(strlen:integer):RawByteString; function mqtt_get_subAck(identifierid:RawByteString;returnCode:RawByteString):RawByteString; function mqtt_get_unsubAck(identifierid:RawByteString;returnCode:RawByteString):RawByteString; function mqtt_get_conAck(returCode:Byte):RawByteString; implementation function mqtt_getframelen(p:Pointer;len:integer;out lenbyte:integer):integer; var bitx:byte; begin Result := 0; bitx := 0; lenbyte := 0; while True do BEGIN inc(Result,(pbyte(p)^ AND $7f) shl bitx); if Result>CON_MQTT_MAXBYTE then begin Result := -1; exit; end; inc(bitx,7); if bitx>21 then begin Result := -2; exit; end; inc(lenbyte); if lenbyte>len then begin Result := -3; exit; end; if (pbyte(p)^ AND $80) = 0 then break; inc(PtrUInt(p)); end; end; function mqtt_swaplen(alen:word):word; begin Result := ((alen and $ff) shl 8) + (alen shr 8) and $ff; end; function mqtt_gethdr(MsgType: TMQTTMessageType; Dup: Boolean;Qos: Integer; Retain: Boolean):AnsiChar; begin { Fixed Header Spec: bit |7 6 5 4 | |3 | |2 1 | | 0 | byte 1 |Message Type| |DUP flag| |QoS level| |RETAIN| } Result := AnsiChar((Ord(MsgType) shl 4) + (ord(Dup) shl 3) + (ord (Qos) shl 1) + ord (Retain)); end; function mqtt_add_lenth(p:Pointer;alen:integer):integer; begin Result := 0; repeat PAnsiChar(p)^ := AnsiChar(alen and $7f); alen := alen shr 7; inc(PtrUInt(p),1); inc(Result,1); until (alen = 0); end; function mqtt_get_lenth(alen:integer):RawByteString; var n:byte; begin Result := ''; while True do begin n := alen and $7f; alen := alen shr 7; if(alen<>0) then inc(n,$80); Result := Result + AnsiChar(n); if alen=0 then break; end; end; function mqtt_get_strlen(strlen:integer):RawByteString; begin Result := AnsiChar((strlen shr 8) and $ff) + AnsiChar(strlen and $ff); end; function mqtt_get_conAck(returCode:Byte):RawByteString; begin SetLength(Result,4); Result[1] := mqtt_gethdr(mtCONNACK, false, qtAT_MOST_ONCE, false); mqtt_add_lenth(@Result[2],2); Result[3] := #0; Result[4] := AnsiChar(returCode); end; function mqtt_get_subAck(identifierid:RawByteString;returnCode:RawByteString):RawByteString; begin SetLength(Result,2); Result[1] := mqtt_gethdr(mtSUBACK, false, qtAT_MOST_ONCE, false); mqtt_add_lenth(@Result[2],length(returnCode)+2); Result := Result + identifierid + returnCode; end; function mqtt_get_unsubAck(identifierid:RawByteString;returnCode:RawByteString):RawByteString; begin SetLength(Result,2); Result[1] := mqtt_gethdr(mtUNSUBACK, false, qtAT_MOST_ONCE, false); mqtt_add_lenth(@Result[2],length(returnCode)+2); Result := Result + identifierid + returnCode; end; function mqtt_readstr(p:Pointer;leftlen:integer;out sstr:RawByteString):integer; var alen:word; begin Result := 0; MoveFast(PAnsiChar(p)^,alen,2); alen := mqtt_swaplen(alen); if (alen=0) or ((alen+2)>leftlen) then exit; inc(PtrUInt(p),2); SetLength(sstr,alen); MoveFast(PAnsiChar(p)^,sstr[1],alen); Result := alen + 2; end; function mqtt_AddTopic(const buf:RawByteString;var topics:TShortStringDynArray):Integer; procedure _append(const atopic:RawByteString); var i:integer; begin for i:=0 to high(topics) do if topics[i]=atopic then exit; i := length(topics); SetLength(topics,i+1); topics[i] := atopic; end; var temp:RawByteString; t,n:integer; mQos:byte; begin Result := 0; t := 1; repeat n := mqtt_readstr(@buf[t],length(buf)-t + 1,temp); if n<2 then break; _append(temp); if length(topics) >= CON_MQTT_MAXSUB then begin Result := -2; exit; end; inc(t,n); // qos byte mQos := ord(buf[t]); inc(t); inc(Result); until (t>length(buf)); end; function mqtt_DelTopic(const buf:RawByteString;var topics:TShortStringDynArray):integer; procedure _del(const atopic:RawByteString); var i,j,n:integer; begin for i:=0 to high(topics) do if topics[i]=atopic then begin n := length(topics) - 1; for j:=i+1 to n do topics[j-1] := topics[j]; SetLength(topics,n); exit; end; end; var temp:RawByteString; t,n:integer; mQos:byte; begin Result := 0; t := 1; repeat n := mqtt_readstr(@buf[t],length(buf)-t + 1,temp); if n<2 then break; _del(temp); inc(t,n); inc(Result); until (t>length(buf)); end; function mqtt_compareTitle(const at:RawByteString;topics:TShortStringDynArray):boolean; function _compareTitle(const src,dst:RawByteString):boolean; // is not standard var temp,temp2:RawByteString; begin Result := true; if src = dst then exit; if (dst[length(dst)] = '#') then begin temp := Copy(dst,1,length(dst)-1); if src = temp then exit; if length(temp)=0 then exit; // all if temp[length(temp)] = '/' then begin temp := Copy(dst,1,length(dst)-1); if pos(temp,src) = 1 then exit; end; end else if (dst[length(dst)] = '+') then begin temp := Copy(dst,1,length(dst)-1); // /+ if length(src) > length(temp) then begin temp2 := src; Delete(temp2,1,length(temp)); if Pos('/',temp2)<1 then exit; end; end; Result := false; end; var i:integer; begin Result := true; for i := 0 to High(topics) do if _compareTitle(at,topics[i]) then exit; Result := false; end; { TMqttSocket } //const // teststr = '00064D514973647003C60009000C64633466323235383063666600197075622F686561746374726C2F646334663232353830636666000A7B22636D64223A38387D000474657374000474657374'; { constructor TMqttSocket.Create(aServer: TAsyncServer; aTimeOut: PtrInt); begin inherited create(aServer,timeOut); FUser := ''; FClientID := ''; FPaswd := ''; FWillTopic := ''; end; function TMqttSocket.Login(headerMaxTix: Int64): TMqttLoginResult; var achar:byte; function _getframelen:integer; var bitx:byte; begin Result := 0; bitx := 0; repeat SockRecv(@achar,1); inc(Result,(achar AND $7f) shl bitx); if Result>CON_MQTT_MAXBYTE then begin Result := -1; exit; end; inc(bitx,7); if bitx>21 then begin Result := -2; exit; end; until ( (achar and $80)=0); end; var alen,p,n:integer; buf:array of byte; // temp:RawUtf8; begin result := mmqttError; try CreateSockIn; // abort now with no exception if socket is obviously broken if fServer <> nil then begin if (fServer = nil) or fServer.Terminated then exit; end; // SockRecv(@achar,1); if TMQTTMessageType((achar and $f0) shr 4) <> mtCONNECT then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login title=%',[inttostr(achar)], self); exit; end; alen := _getframelen; if alen<10 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login len=%',[alen], self); exit; end; // {|Protocol Name |byte 1 |Length MSB (0) |0 |0 |0 |0 |0 |0 |0 |0 |byte 2 |Length LSB (4) |0 |0 |0 |0 |0 |1 |0 |0 |byte 3 |¡®M¡¯ |0 |1 |0 |0 |1 |1 |0 |1 |byte 4 |¡®Q¡¯ |0 |1 |0 |1 |0 |0 |0 |1 |byte 5 |¡®T¡¯ |0 |1 |0 |1 |0 |1 |0 |0 |byte 6 |¡®T¡¯ |0 |1 |0 |1 |0 |1 |0 |0 |Protocol Level |byte 7 |Level (4) |0 |0 |0 |0 |0 |1 |0 |0 |Connect Flags |byte 8 |User Name Flag (1) |1 |1 |0 |0 |1 |1 |1 |0 | |Password Flag (1) | |Will Retain (0) | |Will QoS (01) | |Will Flag (1) | |Clean Session (1) | |Reserved (0) |Keep Alive |byte 9 |Keep Alive MSB (0) |0 |0 |0 |0 |0 |0 |0 |0 |byte 10 |Keep Alive LSB (10) |0 |0 |0 |0 |1 |0 |1 |0 /// SetLength(buf,alen); SockRecv(@buf[0],alen); if buf[0] <> 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login %',[BinToHex(@buf[0],alen)], self); exit; end; // if (buf[1]=MQTT_VERSIONLEN3) then begin if alen<12 then exit; if (buf[8]<>MQTT_VERSION3) then exit; if not CompareMemSmall(@buf[2],PAnsiChar(MQTT_PROTOCOLV3),MQTT_VERSIONLEN3) then exit; FKeepliveTimeOut := (buf[10] shl 8) or buf[11]; p := 9; end else if (buf[1]=MQTT_VERSIONLEN311) then begin if (buf[6]<>MQTT_VERSION4) then exit; if not CompareMemSmall(@buf[2],PAnsiChar(MQTT_PROTOCOLV311),length(MQTT_PROTOCOLV311)) then exit; FKeepliveTimeOut := (buf[8] shl 8) or buf[9]; p := 7; end else begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login other ver%',[BinToHex(@buf[0],alen)], self); exit; end; FFlag := buf[p]; inc(p,3); n:=mqtt_readstr(@buf[p],alen-p,FClientID); if n = 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login read err 1 %',[BinToHex(@buf[0],alen)], self); exit; end; p := p + n; if (FFlag and $4)<>0 then begin n := mqtt_readstr(@(buf[p]),alen-p,FWillTopic); if n = 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login read err 2 %',[BinToHex(@buf[0],alen)], self); exit; end; p := p + n; n := mqtt_readstr(@(buf[p]),alen-p,FWillMessage); if n = 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login read err 3 %',[BinToHex(@buf[0],alen)], self); exit; end; p := p + n; end; if (FFlag and $80)<>0 then begin n := mqtt_readstr(@(buf[p]),alen-p,FUser); if n = 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login read err 4 %',[BinToHex(@buf[0],alen)], self); exit; end; p := p + n; end; if (FFlag and $40)<>0 then begin n := mqtt_readstr(@(buf[p]),alen-p,FPaswd); if n = 0 then begin if Assigned(OnLog) then OnLog(sllCustom1, 'Login read err 5 %',[BinToHex(@buf[0],alen)], self); exit; end; p := p + n; end; // if (headerMaxTix > 0) and (GetTickCount64 > headerMaxTix) then begin result := mmqttTimeout; exit; // allow 10 sec for header -> DOS/TCPSYN Flood end; // Write(mqtt_get_conack(0)); result := mmqttok; except end; end; } end.
{ ******************************************************************************* Title: T2TiPDV Description: Formulário Base The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije @version 2.0 ******************************************************************************* } unit UBase; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SessaoUsuario, JvArrowButton, Buttons, Tipos, UDataModule, ComCtrls, JvPageList, Rtti, Atributos, ActnList, Menus, Vcl.ExtCtrls; type TFBase = class(TForm) TimerIntegracao: TTimer; procedure TimerIntegracaoTimer(Sender: TObject); private procedure ReceberCarga; function GetSessaoUsuario: TSessaoUsuario; { Private declarations } public { Public declarations } property Sessao: TSessaoUsuario read GetSessaoUsuario; procedure ExecutarIntegracao(pProcedimento: String); end; var FBase: TFBase; implementation uses UCargaPDV; {$R *.dfm} { TFBase } function TFBase.GetSessaoUsuario: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; procedure TFBase.TimerIntegracaoTimer(Sender: TObject); begin TimerIntegracao.Enabled := False; if Sessao.Configuracao.TipoIntegracao > 0 then begin ReceberCarga; end; end; procedure TFBase.ExecutarIntegracao(pProcedimento: String); begin TimerIntegracao.Enabled := False; if FCargaPDV = nil then Application.CreateForm(TFCargaPDV, FCargaPDV); FCargaPDV.Procedimento := pProcedimento; FCargaPDV.ShowModal; TimerIntegracao.Enabled := True; end; procedure TFBase.ReceberCarga; begin (* TimerIntegracao.Enabled := False; try if ExecutaPing(Sessao.Configuracao.IpServidor) then begin PathCarga := FDataModule.RemoteAppPath + 'Caixa' + IntToStr(Sessao.Configuracao.IdEcfCaixa) + '\carga.txt'; PathSemaforo := FDataModule.RemoteAppPath + 'Caixa' + IntToStr(Sessao.Configuracao.IdEcfCaixa) + '\semaforo'; if (FileExists(PathCarga)) and (FileExists(PathSemaforo)) then begin labelMensagens.Caption := 'Aguarde, Importando Dados'; if FCargaPDV = nil then Application.CreateForm(TFCargaPDV, FCargaPDV); FCargaPDV.Left := Self.Left; FCargaPDV.Width := Self.Left; FCargaPDV.Tipo := 0; FCargaPDV.ShowModal; end else if (FileExists(PathCarga)) then begin Pathlocal := ExtractFilePath(Application.ExeName) + 'ArquivoAuxiliar.ini'; CopyFile(PChar(Pathlocal), PChar(PathSemaforo), False); end; GifAnimadoRede.Animate := true; end else GifAnimadoRede.Animate := False; finally TimerIntegracao.Enabled := true; Application.ProcessMessages; end; *) end; end.
unit tpFilChg; (* Permission is hereby granted, on 1-Jun-2005, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author of original version of this file: Michael Ax *) interface uses Windows, Messages, SysUtils, Classes; const cFileChangeDelay= 100; //grant small delay in case of multiple changes. //lets not be trigger-happy on bulk-deletes! type TtpFileChangeTypes = (cnFileName,cnFileSize,cnFileTime,cnDirName,cnAttribute,cnSecurity); TtpFileChangeFilter = set of TtpFileChangeTypes; TtpFileChange = class(TComponent) private fEnabled: boolean; fDirectory: string; fSubDirectories: boolean; fThread: TThread; fDelay: integer; fFilter: word; fFilters: TtpFileChangeFilter; fOnFileChange: TNotifyEvent; // procedure SetEnabled(Value: Boolean); procedure SetFilters(Value: TtpFileChangeFilter); procedure SetDirectory(Value: string); // procedure SetDelay(Value: Integer); procedure SetSubDirectories(Value: boolean); // procedure Update; procedure CreateThread; procedure DestroyThread; protected public constructor Create(aOwner:TComponent); override; destructor Destroy; override; property Filter: word read fFilter; published property Enabled: boolean read fEnabled write SetEnabled; property Filters: TtpFileChangeFilter read fFilters write SetFilters; property Delay: integer read fDelay write fDelay default cFileChangeDelay; property Directory: string read fDirectory write SetDirectory; property SubDirectories: boolean read fSubDirectories write SetSubDirectories; property OnFileChange: TNotifyEvent read fOnFileChange write fOnFileChange; end; TtpFileChangeThread = class(TThread) private fFileChangeNotify: TtpFileChange; //fSleeperThread: TThread; fDelay: integer; //procedure FileChanged; //procedure SleeperDone; procedure CallBack; procedure DoCallBack; public constructor Create(FileChangeNotify: TtpFileChange; Delay:Integer); procedure Execute; override; end; (* TtpFileChangeSleeperThread = class(TThread) private fFileChangeThread: TtpFileChangeThread; fDelayUntil: Integer; public constructor Create(FileChangeThread: TtpFileChangeThread; DelayUntil:Integer); procedure Execute; override; end; *) implementation uses ucFile; //------------------------------------------------------------------------------ (* constructor TtpFileChangeSleeperThread.Create(FileChangeThread: TtpFileChangeThread; DelayUntil:Integer); begin fDelayUntil:=DelayUntil; fFileChangeThread:= FileChangeThread; FreeOnTerminate:=True; inherited Create(False); end; procedure TtpFileChangeSleeperThread.Execute; var i:integer; begin while not Terminated do begin i:=fDelayUntil-GetTickCount; if i<=0 then break; Sleep(i); end; fFileChangeThread.SleeperDone; end; *) //------------------------------------------------------------------------------ constructor TtpFileChangeThread.Create(FileChangeNotify: TtpFileChange; Delay:Integer); begin fDelay:=Delay; fFileChangeNotify:= FileChangeNotify; inherited Create(False); FreeOnTerminate:=True; end; { procedure TtpFileChangeThread.FileChanged; var i:integer; begin if fDelay=0 then CallBack else begin i:= GetTickCount+fDelay; if assigned(fSleeperThread) then InterlockedExchange(TtpFileChangeSleeperThread(fSleeperThread).fDelayUntil,i) else fSleeperThread:= TtpFileChangeSleeperThread.Create(Self,i); end; end; procedure TtpFileChangeThread.SleeperDone; begin fSleeperThread:=nil; CallBack; end; } procedure TtpFileChangeThread.CallBack; begin if not Terminated then Synchronize(DoCallBack); end; procedure TtpFileChangeThread.DoCallBack; begin if not Terminated then with fFileChangeNotify do if assigned(OnFileChange) then OnFileChange(fFileChangeNotify); end; procedure TtpFileChangeThread.Execute; var c: Integer; h: THandle; d: DWORD; w: DWORD; begin c := 0; if not assigned(fFileChangeNotify) then exit; with fFileChangeNotify do begin h:=FindFirstChangeNotification(pchar(Directory),SubDirectories,Filter); try d:=INFINITE; while not Terminated do begin w:= WaitForSingleObject(h,d); if not Assigned(fFileChangeNotify) then break; if w=0{h} then //0-first item, e.g. h triggered if fDelay=0 then CallBack else d:=fDelay else begin d:=INFINITE; CallBack; end; if c = 20 then begin //close and reopen the change notification to prevent a "leak" in the nonpaged pool under Win2K FindCloseChangeNotification(h); h:=FindFirstChangeNotification(pchar(Directory),SubDirectories,Filter); c := 0; end else FindNextChangeNotification(h); Inc(c); end; finally FindCloseChangeNotification(h); end; end; end; //------------------------------------------------------------------------------ constructor TtpFileChange.Create(aOwner:TComponent); begin inherited Create(aOwner); fDelay:=cFileChangeDelay; end; destructor TtpFileChange.Destroy; begin DestroyThread; inherited Destroy; end; procedure TtpFileChange.CreateThread; begin fThread:= TtpFileChangeThread.Create(Self,Delay); end; procedure TtpFileChange.DestroyThread; begin if Assigned(fThread) then begin //classes //TerminateThread(fThread.Handle,0); fThread.Terminate; fThread:= nil; end; end; procedure TtpFileChange.SetEnabled(Value: boolean); begin if fEnabled<>Value then begin fEnabled:= Value and DirectoryExists(Directory);; if not (csDesigning in ComponentState) then if fEnabled then CreateThread else DestroyThread; end; end; procedure TtpFileChange.Update; begin if Enabled then begin Enabled:=false; Enabled:=true; end; end; procedure TtpFileChange.SetSubDirectories(Value: boolean); begin if fSubDirectories<>Value then begin fSubDirectories:= Value; Update; end; end; procedure TtpFileChange.SetDirectory(Value: string); begin if CompareText(fDirectory,Value)<>0 then begin fDirectory:= Value; if fDirectory='' then Enabled:=False else Update; end; end; { procedure TtpFileChange.SetDelay(Value: Integer); begin if Delay<>Value then begin fDelay:= Value; Update; end; end; } procedure TtpFileChange.SetFilters(Value: TtpFileChangeFilter); begin if Value=Filters then exit; fFilter:= 0; if cnFileName in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_FILE_NAME; if cnFileSize in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_SIZE; if cnFileTime in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_LAST_WRITE; if cnDirName in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_DIR_NAME; if cnAttribute in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_ATTRIBUTES; if cnSecurity in Value then fFilter:=fFilter or FILE_NOTIFY_CHANGE_SECURITY; fFilters:= Value; Update; end; //------------------------------------------------------------------------------ end.
{ ------------------------------------ 功能说明:实现对注册表的读写,因为外部也可能 会操作注册表,所以封装成一个DLL 创建日期:2008/11/14 作者:wzw 版权:wzw ------------------------------------- } unit RegObj; interface uses SysUtils, Classes, RegIntf, XMLDoc, XMLIntf, Variants, ActiveX, SvcInfoIntf, MenuRegIntf, qxml; type TRegObj = class(TInterfacedObject, IRegistry, ISvcInfo, IMenuReg) private FRegFile: String; FXMLDoc: IXMLDocument; FCurrNode: IXMLNode; function GetNode(const key: Widestring; CanCreate: Boolean): IXMLNode; function ReadValue(const aName: Widestring; out Value: OleVariant): Boolean; procedure WriteValue(const aName: Widestring; Value: OleVariant); protected { IRegistry } function OpenKey(const key: Widestring; CanCreate: Boolean = False): Boolean; function DeleteKey(const key: Widestring): Boolean; function KeyExists(const key: Widestring): Boolean; procedure GetKeyNames(Strings: TStrings); procedure GetValueNames(Strings: TStrings); function DeleteValue(const aName: Widestring): Boolean; function ValueExists(const ValueName: Widestring): Boolean; function ReadBool(const aName: Widestring; out Value: Boolean): Boolean; function ReadDateTime(const aName: Widestring; out Value: TDateTime): Boolean; function ReadFloat(const aName: Widestring; out Value: Double): Boolean; function ReadInteger(const aName: Widestring; out Value: Integer): Boolean; function ReadString(const aName: Widestring; out Value: Widestring): Boolean; function ReadBoolDef(const aName: Widestring; Default: Boolean): Boolean; function ReadDateTimeDef(const aName: Widestring; Default: TDateTime): TDateTime; function ReadFloatDef(const aName: Widestring; Default: Double): Double; function ReadIntegerDef(const aName: Widestring; Default: Integer): Integer; function ReadStringDef(const aName: Widestring; Default: Widestring): Widestring; procedure WriteBool(const aName: Widestring; Value: Boolean); procedure WriteDateTime(const aName: Widestring; Value: TDateTime); procedure WriteFloat(const aName: Widestring; Value: Double); procedure WriteInteger(const aName: Widestring; Value: Integer); procedure WriteString(const aName, Value: Widestring); procedure SaveData; procedure LoadRegistryFile(const FileName: Widestring); { ISvcInfo } function GetModuleName: String; function GetTitle: String; function GetVersion: String; function GetComments: String; { IMenuReg } procedure RegMenu(const key, Path: Widestring); procedure UnRegMenu(const key: Widestring); procedure RegToolItem(const key, aCaption, aHint: Widestring); procedure UnRegToolItem(const key: Widestring); public constructor Create(const FileName: Widestring); destructor Destroy; override; end; ERegistryException = class(Exception); implementation //uses msxmldom,xmldom; const MenuKey = 'SYSTEM\MENU'; ToolKey = 'SYSTEM\TOOL'; constructor TRegObj.Create(const FileName: Widestring); begin CoInitialize(nil); self.LoadRegistryFile(FileName); {try //下面这两句用于解决加载DLL报No matching DOM Vendor: ""错误的问题 //引用msxmldom,xmldom两单元 MSXML_DOM:=TMSDOMImplementationFactory.Create; RegisterDOMVendor(MSXML_DOM); Except end; } end; function TRegObj.DeleteKey(const key: Widestring): Boolean; var Node: IXMLNode; begin Result := False; if Trim(key) = '' then exit; Node := GetNode(key, False); if assigned(Node) then Result := Node.ParentNode.ChildNodes.Remove(Node) <> -1; end; function TRegObj.DeleteValue(const aName: Widestring): Boolean; var Node: IXMLNode; begin Result := False; if Trim(aName) = '' then exit; if assigned(FCurrNode) then begin Node := FCurrNode.AttributeNodes.FindNode(WideUpperCase(aName)); if assigned(Node) then Result := FCurrNode.AttributeNodes.Remove(Node) <> -1; end; end; destructor TRegObj.Destroy; begin FXMLDoc := nil; FCurrNode := nil; CoUninitialize; inherited; end; function TRegObj.GetComments: String; begin Result := '框架注册表服务接口,用于操作框架注册表。'; end; procedure TRegObj.GetKeyNames(Strings: TStrings); var i: Integer; begin if Strings = Nil then exit; if assigned(FCurrNode) then begin if FCurrNode.HasChildNodes then begin for i := 0 to FCurrNode.ChildNodes.Count - 1 do Strings.Add(FCurrNode.ChildNodes[i].NodeName); end; end; end; function TRegObj.GetModuleName: String; begin Result := ExtractFileName(SysUtils.GetModuleName(HInstance)); end; function TRegObj.GetNode(const key: Widestring; CanCreate: Boolean): IXMLNode; // 内部函数 function InnerGetNode(const NodeStr: Widestring; FromNode: IXMLNode; aCanCreate: Boolean): IXMLNode; begin Result := Nil; if Trim(NodeStr) = '' then exit; if FromNode = Nil then exit; if aCanCreate then Result := FromNode.ChildNodes[NodeStr] else Result := FromNode.ChildNodes.FindNode(NodeStr); end; var aList: TStrings; ParentNode, FoundNode: IXMLNode; i: Integer; tmpKey: String; begin tmpKey := UpperCase(Trim(key)); // WideUpperCase if tmpKey = '' then begin Result := FXMLDoc.DocumentElement; exit; end; ParentNode := FXMLDoc.DocumentElement; aList := TStringList.Create; try ExtractStrings(['\'], [], pchar(tmpKey), aList); for i := 0 to aList.Count - 1 do begin FoundNode := InnerGetNode(aList[i], ParentNode, CanCreate); if FoundNode = Nil then exit; ParentNode := FoundNode; end; Result := FoundNode; // 同上 finally aList.Free; end; end; function TRegObj.GetTitle: String; begin Result := '注册表接口(IRegistry)'; end; procedure TRegObj.GetValueNames(Strings: TStrings); var i: Integer; begin if Strings = Nil then exit; if assigned(FCurrNode) then begin for i := 0 to FCurrNode.AttributeNodes.Count - 1 do Strings.Add(FCurrNode.AttributeNodes[i].NodeName); end; end; function TRegObj.GetVersion: String; begin Result := '20100421.001'; end; function TRegObj.KeyExists(const key: Widestring): Boolean; var tmpNode: IXMLNode; begin tmpNode := GetNode(key, False); Result := tmpNode <> Nil; end; procedure TRegObj.LoadRegistryFile(const FileName: Widestring); begin try FRegFile := FileName; if FileExists(FRegFile) then FXMLDoc := LoadXMLDocument(FileName) else begin FXMLDoc := NewXMLDocument; FXMLDoc.Encoding := 'UTF-8'; FXMLDoc.DocumentElement := FXMLDoc.CreateNode('Doc'); FXMLDoc.SaveToFile(FRegFile); end; except on E: Exception do raise ERegistryException.CreateFmt('打开注册表出错:%s', [E.Message]); end; end; function TRegObj.OpenKey(const key: Widestring; CanCreate: Boolean): Boolean; begin FCurrNode := GetNode(key, CanCreate); Result := assigned(FCurrNode); end; function TRegObj.ReadBool(const aName: Widestring; out Value: Boolean): Boolean; var tmpValue: OleVariant; begin Result := ReadValue(aName, tmpValue); if VarIsNull(tmpValue) then Value := False else Value := tmpValue; end; function TRegObj.ReadBoolDef(const aName: Widestring; Default: Boolean): Boolean; begin if not self.ReadBool(aName, Result) then Result := Default; end; function TRegObj.ReadDateTime(const aName: Widestring; out Value: TDateTime): Boolean; var tmpValue: OleVariant; begin Result := ReadValue(aName, tmpValue); if VarIsNull(tmpValue) then Value := 0 else Value := tmpValue; end; function TRegObj.ReadDateTimeDef(const aName: Widestring; Default: TDateTime): TDateTime; begin if not self.ReadDateTime(aName, Result) then Result := Default; end; function TRegObj.ReadFloat(const aName: Widestring; out Value: Double): Boolean; var tmpValue: OleVariant; begin Result := ReadValue(aName, tmpValue); if VarIsNull(tmpValue) then Value := 0.0 else Value := tmpValue; end; function TRegObj.ReadFloatDef(const aName: Widestring; Default: Double): Double; begin if not self.ReadFloat(aName, Result) then Result := Default; end; function TRegObj.ReadInteger(const aName: Widestring; out Value: Integer): Boolean; var tmpValue: OleVariant; begin Result := ReadValue(aName, tmpValue); if VarIsNull(tmpValue) then Value := 0 else Value := tmpValue; end; function TRegObj.ReadIntegerDef(const aName: Widestring; Default: Integer): Integer; begin if not self.ReadInteger(aName, Result) then Result := Default; end; function TRegObj.ReadString(const aName: Widestring; out Value: Widestring): Boolean; var tmpValue: OleVariant; begin Result := ReadValue(aName, tmpValue); if VarIsNull(tmpValue) then Value := '' else Value := tmpValue; end; function TRegObj.ReadStringDef(const aName: Widestring; Default: Widestring): Widestring; begin if not self.ReadString(aName, Result) then Result := Default; end; function TRegObj.ReadValue(const aName: Widestring; out Value: OleVariant): Boolean; var Node: IXMLNode; begin Result := False; if assigned(FCurrNode) then begin Node := FCurrNode.AttributeNodes.FindNode(WideUpperCase(aName)); if assigned(Node) then begin Value := Node.NodeValue; Result := True; end; end; end; procedure TRegObj.RegMenu(const key, Path: Widestring); begin if key = '' then exit; if self.OpenKey(MenuKey, True) then self.WriteString(key, Path); end; procedure TRegObj.RegToolItem(const key, aCaption, aHint: Widestring); var S: Widestring; begin if key = '' then exit; if self.OpenKey(ToolKey, True) then begin S := 'Caption=' + aCaption + ',Hint=' + aHint; self.WriteString(key, S); end; end; procedure TRegObj.SaveData; begin if FXMLDoc.Modified then FXMLDoc.SaveToFile(FRegFile); end; procedure TRegObj.UnRegMenu(const key: Widestring); begin if key = '' then exit; if self.OpenKey(MenuKey) then self.DeleteValue(key); end; procedure TRegObj.UnRegToolItem(const key: Widestring); begin if key = '' then exit; if self.OpenKey(ToolKey) then self.DeleteValue(key); end; function TRegObj.ValueExists(const ValueName: Widestring): Boolean; begin Result := False; if assigned(FCurrNode) then Result := FCurrNode.AttributeNodes.FindNode(WideUpperCase(ValueName)) <> Nil; end; procedure TRegObj.WriteBool(const aName: Widestring; Value: Boolean); begin WriteValue(aName, Value); end; procedure TRegObj.WriteDateTime(const aName: Widestring; Value: TDateTime); begin WriteValue(aName, Value); end; procedure TRegObj.WriteFloat(const aName: Widestring; Value: Double); begin WriteValue(aName, Value); end; procedure TRegObj.WriteInteger(const aName: Widestring; Value: Integer); begin WriteValue(aName, Value); end; procedure TRegObj.WriteString(const aName, Value: Widestring); begin WriteValue(aName, Value); end; procedure TRegObj.WriteValue(const aName: Widestring; Value: OleVariant); begin if assigned(FCurrNode) then FCurrNode.Attributes[WideUpperCase(aName)] := Value; end; initialization // CoInitialize(nil); finalization // CoUninitialize; end.
program DuplicateLongInts; type LongItemPtr = ^LongItem; LongItem = record next: LongItemPtr; data: longint; end; QueueOfLongints = record first, last: LongItemPtr; end; procedure QOLInit(var queue: QueueOfLongints); begin queue.first := nil; queue.last := nil; end; procedure QOLPut(var queue: QueueOfLongints; n: longint); begin if queue.first = nil then begin new(queue.first); queue.last := queue.first end else begin new(queue.last^.next); queue.last := queue.last^.next end; queue.last^.data := n; queue.last^.next := nil end; function QOLGet(var queue: QueueOfLongints; var n: longint) : boolean; var cur: LongItemPtr; begin if queue.first = nil then begin QOLGet := false; exit end; n := queue.first^.data; cur := queue.first; queue.first := queue.first^.next; if queue.first = nil then queue.last := nil; dispose(cur); QOLGet := true end; function QOLIsEmpty(var queue: QueueOfLongints) : boolean; begin QOLIsEmpty := queue.first = nil end; var queue: QueueOfLongints; n: longint; begin QOLInit(queue); while not SeekEof do begin read(n); QOLPut(queue, n); end; while QOLGet(queue, n) do begin writeln(n); writeln(n) end; end.
unit InfraCommand; interface uses InfraMVPIntf, InfraCommonIntf, InfraCommon, InfraValueTypeIntf, InfraValueType; type TCommand = class(TElement, ICommand) private FChecked: IInfraBoolean; FEnabled: IInfraBoolean; FGroupIndex: IInfraInteger; FRadioItem: IInfraBoolean; // It is required mapper the method InternalExecute to again. // Delphi not was calling InternalExecute when anyone call // SomeCommand.Execute. // *** procedure ICommand.Execute = InternalExecute; protected function CanUndo: Boolean; virtual; function GetChecked: boolean; function GetEnabled: boolean; function GetGroupIndex: Integer; function GetRadioItem: boolean; procedure SetChecked(Value: boolean); procedure SetEnabled(Value: boolean); procedure SetGroupIndex(Value: Integer); procedure SetRadioItem(Value: boolean); procedure Undo; virtual; property Checked: boolean read GetChecked write SetChecked; property Enabled: boolean read GetEnabled write SetEnabled; property GroupIndex: Integer read GetGroupIndex write SetGroupIndex; property RadioItem: boolean read GetRadioItem write SetRadioItem; public procedure InfraInitInstance; override; end; (* *** TAppendCommand = class(TCommand, IAppendCommand) protected procedure Execute(const Parameters: IInfraList); override; end; TDeleteCommand = class(TCommand, IDeleteCommand) protected procedure Execute(const Parameters: IInfraList); override; end; TSelectionCommand = class(TCommand, ISelectionCommand) protected procedure Update(const Event: IInfraEvent); public function GetSelection: IInfraList; procedure InfraInitInstance; override; property Selection: IInfraList read GetSelection; end; *) procedure RegisterOnReflection; implementation uses SysUtils, InfraNotify; // Só por causa do TInfraEvent que é necessário aqui. procedure RegisterOnReflection; begin with TypeService do begin AddType(ICommand, 'Command', TCommand, IElement, GetType(IElement)); (* *** RegisterNewType(IAppendCommand, 'AppendCommand', TAppendCommand, ICommand, GetTypeInfo(ICommand)); RegisterNewType(IDeleteCommand, 'DeleteCommand', TDeleteCommand, ICommand, GetTypeInfo(ICommand)); with RegisterNewType(ISelectionCommand, 'SelectionCommand', TSelectionCommand, ICommand, GetTypeInfo(ICommand)) do AddMember('Selection', ISelection, @TSelectionCommand.GetSelection); *) end; end; { TCommand } procedure TCommand.InfraInitInstance; var This: IElement; begin inherited; This := Self as IElement; FChecked := TInfraBoolean.create; (FChecked as IProperty).Owner := This; FEnabled := TInfraBoolean.create; (FEnabled as IProperty).Owner := This; FGroupIndex := TInfraInteger.create; (FGroupIndex as IProperty).Owner := This; FRadioItem := TInfraBoolean.create; (FRadioItem as IProperty).Owner := This; end; function TCommand.CanUndo: Boolean; begin Result := False; end; function TCommand.GetChecked: boolean; begin Result := FChecked.AsBoolean; end; function TCommand.GetEnabled: boolean; begin Result := FEnabled.AsBoolean; end; function TCommand.GetGroupIndex: Integer; begin Result := FGroupIndex.AsInteger; end; function TCommand.GetRadioItem: boolean; begin Result := FRadioItem.AsBoolean; end; procedure TCommand.SetChecked(Value: boolean); begin if Value <> FChecked.AsBoolean then begin FChecked.AsBoolean := Value; Publisher.Publish(TInfraEvent.Create(Self, ICommandChangedEvent) as IInfraEvent); end; end; procedure TCommand.SetEnabled(Value: boolean); begin if Value <> FEnabled.AsBoolean then begin FEnabled.AsBoolean := Value; Publisher.Publish(TInfraEvent.Create(Self, ICommandChangedEvent) as IInfraEvent); end; end; procedure TCommand.SetGroupIndex(Value: Integer); begin if Value <> FGroupIndex.AsInteger then begin FGroupIndex.AsInteger := Value; Publisher.Publish(TInfraEvent.Create(Self, ICommandChangedEvent) as IInfraEvent); end; end; procedure TCommand.SetRadioItem(Value: boolean); begin if Value <> FRadioItem.AsBoolean then begin FRadioItem.AsBoolean := Value; Publisher.Publish(TInfraEvent.Create(Self, ICommandChangedEvent) as IInfraEvent); end; end; procedure TCommand.Undo; begin Raise Exception.Create('Undo not available!'); end; (* *** { TAppendCommand } procedure TAppendCommand.Execute(const Parameters: IInfraList); var List: IInfraList; begin List := (Owner as IModel).Value as IInfraList; FResult := List.Append(Parameters[0] as IInfraType); end; { TDeleteCommand } procedure TDeleteCommand.Execute(const Parameters: IInfraList); var Model: IModel; i: Integer; begin Model := Owner as IModel; with Model.Value as IInfraList do for i := 0 to Model.Selection.Count-1 do Remove(Model.Selection[i]); end; { TSelectionCommand } procedure TSelectionCommand.InfraInitInstance; begin inherited; EventService.Subscribe(IInfraChangedEvent, Self as ISubscriber, Update, 'Selection'); end; function TSelectionCommand.GetSelection: IInfraList; begin Result := (Owner as IPresenter).Model.Selection as IInfraList; end; procedure TSelectionCommand.Update(const Event: IInfraEvent); begin Enabled := (Event.Source as IInfraList).Count <> 0; end; *) end.
unit F10; { menu pengembalian buku, load file peminjaman } interface uses typelist; procedure penambahan_buku(var penambahanbuku: List_Buku); implementation var i, count, i_id_buku, i_jumlah_tambah : integer; convert : string; procedure penambahan_buku(var penambahanbuku: List_Buku); {I.S penambahanbuku terdefenisi} {F.S Menambahkan jumlah buku yang ada dalam List_Buku yang sudah terdefinisi} var found : boolean; begin write('Masukkan ID Buku: '); readln(i_id_buku); write('Masukkan jumlah buku yang ditambahkan: '); readln(i_jumlah_tambah); { cari id buku, jika ditemukan maka cari jumlah buku tersebut dan convert id buku menjadi judul buku } i := 1; found := false; count := 0; while (i <= penambahanbuku.Neff) and (found=false) do begin if i_id_buku = penambahanbuku.listbuku[i].ID_Buku then begin found := true; end else begin i := i + 1; end; end; { update } count := penambahanbuku.listbuku[i].Jumlah_Buku; convert := penambahanbuku.listbuku[i].Judul_Buku; writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ', convert, ' di perpustakaan menjadi ', (count + i_jumlah_tambah) ); { menambahkan jumlah buku ke list buku ke-i } penambahanbuku.listbuku[i].Jumlah_Buku := penambahanbuku.listbuku[i].Jumlah_Buku+ i_jumlah_tambah; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(12 Out 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.ddl.generator; interface uses SysUtils, Generics.Collections, dbcbr.ddl.interfaces, dbebr.factory.interfaces, dbcbr.database.mapping, dbcbr.types.mapping; type TDDLSQLGeneratorAbstract = class abstract(TInterfacedObject, IDDLGeneratorCommand) protected FConnection: IDBConnection; public function GenerateCreateTable(ATable: TTableMIK): string; virtual; abstract; function GenerateCreateColumn(AColumn: TColumnMIK): string; virtual; abstract; function GenerateCreatePrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; virtual; abstract; function GenerateCreateForeignKey(AForeignKey: TForeignKeyMIK): string; virtual; abstract; function GenerateCreateSequence(ASequence: TSequenceMIK): string; virtual; abstract; function GenerateCreateIndexe(AIndexe: TIndexeKeyMIK): string; virtual; abstract; function GenerateCreateCheck(ACheck: TCheckMIK): string; virtual; abstract; function GenerateCreateView(AView: TViewMIK): string; virtual; abstract; function GenerateCreateTrigger(ATrigger: TTriggerMIK): string; virtual; abstract; function GenerateAlterColumn(AColumn: TColumnMIK): string; virtual; abstract; function GenerateAlterDefaultValue(AColumn: TColumnMIK): string; virtual; abstract; function GenerateAlterCheck(ACheck: TCheckMIK): string; virtual; abstract; function GenerateAddPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; virtual; abstract; function GenerateDropTable(ATable: TTableMIK): string; virtual; abstract; function GenerateDropPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; virtual; abstract; function GenerateDropForeignKey(AForeignKey: TForeignKeyMIK): string; virtual; abstract; function GenerateDropSequence(ASequence: TSequenceMIK): string; virtual; abstract; function GenerateDropIndexe(AIndexe: TIndexeKeyMIK): string; virtual; abstract; function GenerateDropCheck(ACheck: TCheckMIK): string; virtual; abstract; function GenerateDropColumn(AColumn: TColumnMIK): string; virtual; abstract; function GenerateDropDefaultValue(AColumn: TColumnMIK): string; virtual; abstract; function GenerateDropView(AView: TViewMIK): string; virtual; abstract; function GenerateDropTrigger(ATrigger: TTriggerMIK): string; virtual; abstract; function GenerateEnableForeignKeys(AEnable: Boolean): string; virtual; abstract; function GenerateEnableTriggers(AEnable: Boolean): string; virtual; abstract; /// <summary> /// Propriedade para identificar os recursos de diferentes banco de dados /// usando o mesmo modelo. /// </summary> function GetSupportedFeatures: TSupportedFeatures; virtual; abstract; property SupportedFeatures: TSupportedFeatures read GetSupportedFeatures; end; TDDLSQLGenerator = class(TDDLSQLGeneratorAbstract) protected function GetRuleDeleteActionDefinition(ARuleAction: TRuleAction): string; function GetRuleUpdateActionDefinition(ARuleAction: TRuleAction): string; function GetPrimaryKeyColumnsDefinition(APrimaryKey: TPrimaryKeyMIK): string; function GetForeignKeyFromColumnsDefinition(AForeignKey: TForeignKeyMIK): string; function GetForeignKeyToColumnsDefinition(AForeignKey: TForeignKeyMIK): string; function GetIndexeKeyColumnsDefinition(AIndexeKey: TIndexeKeyMIK): string; function GetUniqueColumnDefinition(AUnique: Boolean): string; function GetFieldTypeDefinition(AColumn: TColumnMIK): string; function GetFieldNotNullDefinition(AColumn: TColumnMIK): string; function GetCreateFieldDefaultDefinition(AColumn: TColumnMIK): string; function GetAlterFieldDefaultDefinition(AColumn: TColumnMIK): string; function BuilderCreateFieldDefinition(AColumn: TColumnMIK): string; virtual; function BuilderAlterFieldDefinition(AColumn: TColumnMIK): string; virtual; function BuilderPrimayKeyDefinition(ATable: TTableMIK): string; virtual; function BuilderIndexeDefinition(ATable: TTableMIK): string; virtual; function BuilderForeignKeyDefinition(ATable: TTableMIK): string; virtual; function BuilderCheckDefinition(ATable: TTableMIK): string; virtual; public function GenerateCreateTable(ATable: TTableMIK): string; override; function GenerateCreateColumn(AColumn: TColumnMIK): string; override; function GenerateCreatePrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; override; function GenerateCreateForeignKey(AForeignKey: TForeignKeyMIK): string; override; function GenerateCreateView(AView: TViewMIK): string; override; function GenerateCreateTrigger(ATrigger: TTriggerMIK): string; override; function GenerateCreateSequence(ASequence: TSequenceMIK): string; override; function GenerateCreateIndexe(AIndexe: TIndexeKeyMIK): string; override; function GenerateCreateCheck(ACheck: TCheckMIK): string; override; function GenerateAlterColumn(AColumn: TColumnMIK): string; override; function GenerateAlterCheck(ACheck: TCheckMIK): string; override; function GenerateAddPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; override; function GenerateDropTable(ATable: TTableMIK): string; override; function GenerateDropColumn(AColumn: TColumnMIK): string; override; function GenerateDropPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; override; function GenerateDropForeignKey(AForeignKey: TForeignKeyMIK): string; override; function GenerateDropIndexe(AIndexe: TIndexeKeyMIK): string; override; function GenerateDropCheck(ACheck: TCheckMIK): string; override; function GenerateDropView(AView: TViewMIK): string; override; function GenerateDropTrigger(ATrigger: TTriggerMIK): string; override; function GenerateDropSequence(ASequence: TSequenceMIK): string; override; /// <summary> /// Propriedade para identificar os recursos de diferentes banco de dados /// usando o mesmo modelo. /// </summary> function GetSupportedFeatures: TSupportedFeatures; override; property SupportedFeatures: TSupportedFeatures read GetSupportedFeatures; end; implementation uses StrUtils; { TDDLSQLGenerator } function TDDLSQLGenerator.GenerateCreateTable(ATable: TTableMIK): string; begin Result := 'CREATE TABLE %s ('; end; function TDDLSQLGenerator.GenerateCreateTrigger(ATrigger: TTriggerMIK): string; begin Result := 'CREATE TRIGGER %s AS %s;'; Result := Format(Result, [ATrigger.Name, ATrigger.Script]); end; function TDDLSQLGenerator.GenerateCreateView(AView: TViewMIK): string; begin Result := 'CREATE VIEW %s AS %s;'; Result := Format(Result, [AView.Name, AView.Script]); end; function TDDLSQLGenerator.GenerateDropTable(ATable: TTableMIK): string; begin Result := 'DROP TABLE %s;'; if ATable.Database.Schema <> '' then Result := Format(Result, [ATable.Database.Schema + '.' + ATable.Name]) else Result := Format(Result, [ATable.Name]); end; function TDDLSQLGenerator.GenerateDropTrigger(ATrigger: TTriggerMIK): string; begin Result := 'DROP TRIGGER %s;'; Result := Format(Result, [ATrigger.Name]); end; function TDDLSQLGenerator.GenerateDropView(AView: TViewMIK): string; begin Result := 'DROP VIEW %s;'; Result := Format(Result, [AView.Name]); end; function TDDLSQLGenerator.GenerateAddPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; begin Result := 'ALTER TABLE %s ADD PRIMARY KEY (%s);'; Result := Format(Result, [APrimaryKey.Table.Name, GetPrimaryKeyColumnsDefinition(APrimaryKey)]); end; function TDDLSQLGenerator.GenerateAlterColumn(AColumn: TColumnMIK): string; begin Result := 'ALTER TABLE %s ALTER COLUMN %s;'; Result := Format(Result, [AColumn.Table.Name, BuilderAlterFieldDefinition(AColumn)]); end; function TDDLSQLGenerator.GenerateCreateCheck(ACheck: TCheckMIK): string; begin Result := 'CONSTRAINT %s CHECK (%s)'; Result := Format(Result, [ACheck.Name, ACheck.Condition]); end; function TDDLSQLGenerator.GenerateAlterCheck(ACheck: TCheckMIK): string; begin Result := 'ALTER TABLE %s ADD CONSTRAINT %s CHECK (%s);'; Result := Format(Result, [ACheck.Table.Name, ACheck.Name, ACheck.Condition]); end; function TDDLSQLGenerator.GenerateCreateColumn(AColumn: TColumnMIK): string; begin Result := 'ALTER TABLE %s ADD %s;'; Result := Format(Result, [AColumn.Table.Name, BuilderCreateFieldDefinition(AColumn)]); end; function TDDLSQLGenerator.GenerateCreateForeignKey(AForeignKey: TForeignKeyMIK): string; begin Result := 'ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s) %s %s'; Result := Format(Result, [AForeignKey.Table.Name, AForeignKey.Name, GetForeignKeyFromColumnsDefinition(AForeignKey), AForeignKey.FromTable, GetForeignKeyToColumnsDefinition(AForeignKey), GetRuleDeleteActionDefinition(AForeignKey.OnDelete), GetRuleUpdateActionDefinition(AForeignKey.OnUpdate)]); Result := Trim(Result) + ';'; end; function TDDLSQLGenerator.GenerateCreateIndexe(AIndexe: TIndexeKeyMIK): string; begin Result := 'CREATE %s INDEX %s ON %s (%s);'; Result := Format(Result, [GetUniqueColumnDefinition(AIndexe.Unique), AIndexe.Name, AIndexe.Table.Name, GetIndexeKeyColumnsDefinition(AIndexe)]); end; function TDDLSQLGenerator.GenerateCreatePrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; begin Result := 'CONSTRAINT %s PRIMARY KEY (%s)'; Result := Format(Result, [APrimaryKey.Name, GetPrimaryKeyColumnsDefinition(APrimaryKey)]); end; function TDDLSQLGenerator.GenerateCreateSequence(ASequence: TSequenceMIK): string; begin Result := ''; end; function TDDLSQLGenerator.GenerateDropColumn(AColumn: TColumnMIK): string; begin Result := 'ALTER TABLE %s DROP COLUMN %s;'; Result := Format(Result, [AColumn.Table.Name, AColumn.Name]); end; function TDDLSQLGenerator.GenerateDropForeignKey(AForeignKey: TForeignKeyMIK): string; begin Result := 'ALTER TABLE %s DROP CONSTRAINT %s;'; Result := Format(Result, [AForeignKey.Table.Name, AForeignKey.Name]); end; function TDDLSQLGenerator.GenerateDropIndexe(AIndexe: TIndexeKeyMIK): string; begin Result := 'DROP INDEX %s ON %s;'; Result := Format(Result, [AIndexe.Name, AIndexe.Table.Name]); end; function TDDLSQLGenerator.GenerateDropCheck(ACheck: TCheckMIK): string; begin Result := 'ALTER TABLE %s DROP CONSTRAINT %s;'; Result := Format(Result, [ACheck.Table.Name, ACheck.Name]); end; function TDDLSQLGenerator.GenerateDropPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; begin Result := 'ALTER TABLE %s DROP CONSTRAINT %s;'; Result := Format(Result, [APrimaryKey.Table.Name, APrimaryKey.Name]); end; function TDDLSQLGenerator.GenerateDropSequence(ASequence: TSequenceMIK): string; begin Result := 'DROP SEQUENCE %s;'; Result := Format(Result, [ASequence.Name]); end; function TDDLSQLGenerator.GetAlterFieldDefaultDefinition(AColumn: TColumnMIK): string; begin Result := IfThen(Length(AColumn.DefaultValue) > 0, AColumn.DefaultValue, ''); end; function TDDLSQLGenerator.GetCreateFieldDefaultDefinition(AColumn: TColumnMIK): string; begin Result := IfThen(Length(AColumn.DefaultValue) > 0, ' DEFAULT ' + AColumn.DefaultValue, ''); end; function TDDLSQLGenerator.BuilderAlterFieldDefinition(AColumn: TColumnMIK): string; begin Result := AColumn.Name + ' ' + GetFieldTypeDefinition(AColumn) + // GetAlterFieldDefaultDefinition(AColumn) + GetFieldNotNullDefinition(AColumn) ; end; function TDDLSQLGenerator.BuilderCheckDefinition(ATable: TTableMIK): string; var oCheck: TPair<string,TCheckMIK>; begin Result := ''; for oCheck in ATable.Checks do begin Result := Result + sLineBreak; Result := Result + ' ' + GenerateCreateCheck(oCheck.Value); end; end; function TDDLSQLGenerator.BuilderCreateFieldDefinition(AColumn: TColumnMIK): string; begin Result := AColumn.Name + ' ' + GetFieldTypeDefinition(AColumn) + GetCreateFieldDefaultDefinition(AColumn) + GetFieldNotNullDefinition(AColumn) ; end; function TDDLSQLGenerator.BuilderForeignKeyDefinition(ATable: TTableMIK): string; var oForeignKey: TPair<string,TForeignKeyMIK>; begin Result := ''; for oForeignKey in ATable.ForeignKeys do begin Result := Result + sLineBreak; Result := Result + ' ' + GenerateCreateForeignKey(oForeignKey.Value); end; end; function TDDLSQLGenerator.GetFieldNotNullDefinition(AColumn: TColumnMIK): string; begin Result := ifThen(AColumn.NotNull, ' NOT NULL', ''); end; function TDDLSQLGenerator.GetFieldTypeDefinition(AColumn: TColumnMIK): string; var LResult: string; begin LResult := AColumn.TypeName; LResult := StringReplace(LResult, '%l', IntToStr(AColumn.Size), [rfIgnoreCase]); LResult := StringReplace(LResult, '%p', IntToStr(AColumn.Precision), [rfIgnoreCase]); LResult := StringReplace(LResult, '%s', IntToStr(AColumn.Scale), [rfIgnoreCase]); Result := ' ' + LResult; end; function TDDLSQLGenerator.BuilderIndexeDefinition(ATable: TTableMIK): string; var oIndexe: TPair<string,TIndexeKeyMIK>; begin Result := ''; for oIndexe in ATable.IndexeKeys do begin Result := Result + sLineBreak; Result := Result + GenerateCreateIndexe(oIndexe.Value); end; end; function TDDLSQLGenerator.BuilderPrimayKeyDefinition(ATable: TTableMIK): string; begin Result := ' ' + GenerateCreatePrimaryKey(ATable.PrimaryKey); end; function TDDLSQLGenerator.GetRuleDeleteActionDefinition(ARuleAction: TRuleAction): string; begin Result := ''; if ARuleAction in [Cascade] then Result := 'ON DELETE CASCADE' else if ARuleAction in [SetNull] then Result := 'ON DELETE SET NULL' else if ARuleAction in [SetDefault] then Result := 'ON DELETE SET DEFAULT'; end; function TDDLSQLGenerator.GetRuleUpdateActionDefinition(ARuleAction: TRuleAction): string; begin Result := ''; if ARuleAction in [Cascade] then Result := 'ON UPDATE CASCADE' else if ARuleAction in [SetNull] then Result := 'ON UPDATE SET NULL' else if ARuleAction in [SetDefault] then Result := 'ON UPDATE SET DEFAULT'; end; function TDDLSQLGenerator.GetSupportedFeatures: TSupportedFeatures; begin Result := [TSupportedFeature.Sequences, TSupportedFeature.ForeignKeys, TSupportedFeature.Checks, TSupportedFeature.Views, TSupportedFeature.Triggers]; end; function TDDLSQLGenerator.GetUniqueColumnDefinition(AUnique: Boolean): string; begin Result := ifThen(AUnique, 'UNIQUE', ''); end; function TDDLSQLGenerator.GetForeignKeyFromColumnsDefinition(AForeignKey: TForeignKeyMIK): string; var oColumn: TPair<string,TColumnMIK>; begin for oColumn in AForeignKey.FromFieldsSort do Result := Result + oColumn.Value.Name + ', '; Result := Trim(Result); Delete(Result, Length(Result), 1); end; function TDDLSQLGenerator.GetForeignKeyToColumnsDefinition(AForeignKey: TForeignKeyMIK): string; var oColumn: TPair<string,TColumnMIK>; begin for oColumn in AForeignKey.ToFieldsSort do Result := Result + oColumn.Value.Name + ', '; Result := Trim(Result); Delete(Result, Length(Result), 1); end; function TDDLSQLGenerator.GetIndexeKeyColumnsDefinition(AIndexeKey: TIndexeKeyMIK): string; var oColumn: TPair<string,TColumnMIK>; begin for oColumn in AIndexeKey.FieldsSort do Result := Result + oColumn.Value.Name + ', '; Result := Trim(Result); Delete(Result, Length(Result), 1); end; function TDDLSQLGenerator.GetPrimaryKeyColumnsDefinition(APrimaryKey: TPrimaryKeyMIK): string; var oColumn: TPair<string,TColumnMIK>; begin for oColumn in APrimaryKey.FieldsSort do Result := Result + oColumn.Value.Name + ', '; Result := Trim(Result); Delete(Result, Length(Result), 1); end; end.