text
stringlengths
14
6.51M
unit IdIDN; { This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2012, Chad Z. Hower and the Indy Pit Crew. All rights reserved. Original Author: J. Peter Mugaas This file uses the "Windows Microsoft Internationalized Domain Names (IDN) Mitigation APIs 1.1" There is a download for some Windows versions at: http://www.microsoft.com/en-us/download/details.aspx?id=734 for Windows XP and that SDK includes a package of run-time libraries that might need to be redistributed to Windows XP users. On some later Windows versions, this is redistributable is not needed. For Windows 8, we do not use this. From: http://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx "On Windows 8 Consumer Preview and Windows Server "8" Beta, the getaddrinfo function provides support for IRI or Internationalized Domain Name (IDN) parsing applied to the name passed in the pNodeName parameter. Winsock performs Punycode/IDN encoding and conversion. This behavior can be disabled using the AI_DISABLE_IDN_ENCODING flag discussed below. } interface {$I IdCompilerDefines.inc} uses IdGlobal {$IFDEF WIN32_OR_WIN64} , Windows {$ENDIF} ; {$IFDEF WIN32_OR_WIN64} { } // ==++== // // Copyright (c) Microsoft Corporation. All Rights Reserved // // ==++== // IdnDl.h // // WARNING: This .DLL is downlevel only. // // This file contains the downlevel versions of the scripts APIs // // 06 Jun 2005 Shawn Steele Initial Implementation const {$EXTERNALSYM VS_ALLOW_LATIN} VS_ALLOW_LATIN = $0001; {$EXTERNALSYM GSS_ALLOW_INHERITED_COMMON} GSS_ALLOW_INHERITED_COMMON = $0001; type {$EXTERNALSYM DownlevelGetLocaleScripts_LPFN} DownlevelGetLocaleScripts_LPFN = function ( lpLocaleName : LPCWSTR; // Locale Name lpScripts : LPWSTR; // Output buffer for scripts cchScripts : Integer // size of output buffer ) : Integer stdcall; {$EXTERNALSYM DownlevelGetStringScripts_LPFN} DownlevelGetStringScripts_LPFN = function ( dwFlags : DWORD; // optional behavior flags lpString : LPCWSTR; // Unicode character input string cchString : Integer; // size of input string lpScripts : LPWSTR; // Script list output string cchScripts : Integer // size of output string ) : Integer stdcall; {$EXTERNALSYM DownlevelVerifyScripts_LPFN} DownlevelVerifyScripts_LPFN = function ( dwFlags : DWORD; // optional behavior flags lpLocaleScripts : LPCWSTR; // Locale list of scripts string cchLocaleScripts : Integer; // size of locale script list string lpTestScripts : LPCWSTR; // test scripts string cchTestScripts : Integer // size of test list string ) : BOOL stdcall; // Normalization.h // Copyright 2002 Microsoft // // Excerpted from LH winnls.h type {$EXTERNALSYM NORM_FORM} NORM_FORM = DWORD; const {$EXTERNALSYM NormalizationOther} NormalizationOther = 0; // Not supported {$EXTERNALSYM NormalizationC} NormalizationC = $1; // Each base plus combining characters to the canonical precomposed equivalent. {$EXTERNALSYM NormalizationD} NormalizationD = $2; // Each precomposed character to its canonical decomposed equivalent. {$EXTERNALSYM NormalizationKC} NormalizationKC = $5; // Each base plus combining characters to the canonical precomposed // equivalents and all compatibility characters to their equivalents. {$EXTERNALSYM NormalizationKD} NormalizationKD = $6; // Each precomposed character to its canonical decomposed equivalent // and all compatibility characters to their equivalents. // // IDN (International Domain Name) Flags // const {$EXTERNALSYM IDN_ALLOW_UNASSIGNED} IDN_ALLOW_UNASSIGNED = $01; // Allow unassigned "query" behavior per RFC 3454 {$EXTERNALSYM IDN_USE_STD3_ASCII_RULES} IDN_USE_STD3_ASCII_RULES = $02; // Enforce STD3 ASCII restrictions for legal characters type // // Windows API Normalization Functions // {$EXTERNALSYM NormalizeString_LPFN} NormalizeString_LPFN = function ( NormForm : NORM_FORM; lpString : LPCWSTR; cwLength : Integer) : DWORD stdcall; {$EXTERNALSYM IsNormalizedString_LPFN} IsNormalizedString_LPFN = function ( NormForm : NORM_FORM; lpString : LPCWSTR; cwLength : Integer ) : BOOL stdcall; // // IDN (International Domain Name) Functions // {$EXTERNALSYM IdnToAscii_LPFN} IdnToAscii_LPFN = function(dwFlags : DWORD; lpUnicodeCharStr : LPCWSTR; cchUnicodeChar : Integer; lpNameprepCharStr : LPWSTR; cchNameprepChar : Integer ) : Integer stdcall; {$EXTERNALSYM IdnToNameprepUnicode_LPFN} IdnToNameprepUnicode_LPFN = function (dwFlags : DWORd; lpUnicodeCharStr : LPCWSTR; cchUnicodeChar : Integer; lpASCIICharStr : LPWSTR; cchASCIIChar : Integer) : Integer stdcall; {$EXTERNALSYM IdnToUnicode_LPFN} IdnToUnicode_LPFN = function (dwFlags : DWORD; lpASCIICharSt : LPCWSTR; cchASCIIChar : Integer; lpUnicodeCharStr : LPWSTR; cchUnicodeChar : Integer) : Integer stdcall; var {$EXTERNALSYM DownlevelGetLocaleScripts} DownlevelGetLocaleScripts : DownlevelGetLocaleScripts_LPFN = nil; {$EXTERNALSYM DownlevelGetStringScripts} DownlevelGetStringScripts : DownlevelGetStringScripts_LPFN = nil; {$EXTERNALSYM DownlevelVerifyScripts} DownlevelVerifyScripts : DownlevelVerifyScripts_LPFN = nil; {$EXTERNALSYM IsNormalizedString} IsNormalizedString : IsNormalizedString_LPFN = nil; {$EXTERNALSYM NormalizeString} NormalizeString : NormalizeString_LPFN = nil; {$EXTERNALSYM IdnToUnicode} IdnToUnicode : IdnToUnicode_LPFN = nil; {$EXTERNALSYM IdnToNameprepUnicode} IdnToNameprepUnicode : IdnToNameprepUnicode_LPFN = nil; {$EXTERNALSYM IdnToAscii} IdnToAscii : IdnToAscii_LPFN = nil; const LibNDL = 'IdnDL.dll'; LibNormaliz = 'Normaliz.dll'; fn_DownlevelGetLocaleScripts = 'DownlevelGetLocaleScripts'; fn_DownlevelGetStringScripts = 'DownlevelGetStringScripts'; fn_DownlevelVerifyScripts = 'DownlevelVerifyScripts'; fn_IsNormalizedString = 'IsNormalizedString'; fn_NormalizeString = 'NormalizeString'; fn_IdnToUnicode = 'IdnToUnicode'; fn_IdnToNameprepUnicode = 'IdnToNameprepUnicode'; fn_IdnToAscii = 'IdnToAscii'; {$ENDIF} // {$IFDEF WIN32_OR_WIN64} function UseIDNAPI : Boolean; function IDNToPunnyCode(const AIDN : TIdUnicodeString) : String; function PunnyCodeToIDN(const APunnyCode : String) : TIdUnicodeString; procedure InitIDNLibrary; procedure CloseIDNLibrary; implementation {$IFDEF WIN32_OR_WIN64} uses SysUtils; var hIdnDL : THandle = 0; hNormaliz : THandle = 0; function UseIDNAPI : Boolean; begin Result := (Win32MajorVersion < 6) or ((Win32MajorVersion = 6) and (Win32MinorVersion < 2)); if Result then begin Result := Assigned( IdnToAscii ) and Assigned( IdnToUnicode ); end; end; function PunnyCodeToIDN(const APunnyCode : String) : TIdUnicodeString; var {$IFNDEF STRING_IS_UNICODE} LTemp: TIdUnicodeString; {$ENDIF} LIDN : TIdUnicodeString; Len : Integer; begin Result := ''; if Assigned(IdnToUnicode) then begin {$IFNDEF STRING_IS_UNICODE} LTemp := TIdUnicodeString(APunnyCode); // explicit convert to Unicode {$ENDIF} Len := IdnToUnicode(0, {$IFDEF STRING_IS_UNICODE} PIdWideChar(APunnyCode), Length(APunnyCode) {$ELSE} PIdWideChar(LTemp), Length(LTemp) {$ENDIF}, nil, 0); if Len = 0 then begin IndyRaiseLastError; end; SetLength(LIDN, Len); Len := IdnToUnicode(0, {$IFDEF STRING_IS_UNICODE} PIdWideChar(APunnyCode), Length(APunnyCode) {$ELSE} PIdWideChar(LTemp), Length(LTemp) {$ENDIF}, PIdWideChar(LIDN), Len); if Len = 0 then begin IndyRaiseLastError; end; Result := LIDN; end else begin // TODO: manual implementation here ... end; end; function IDNToPunnyCode(const AIDN : TIdUnicodeString) : String; var LPunnyCode : TIdUnicodeString; Len : Integer; begin Result := ''; if Assigned(IdnToAscii) then begin Len := IdnToAscii(0, PIdWideChar(AIDN), Length(AIDN), nil, 0); if Len = 0 then begin IndyRaiseLastError; end; SetLength(LPunnyCode, Len); Len := IdnToAscii(0, PIdWideChar(AIDN), Length(AIDN), PIdWideChar(LPunnyCode), Len); if Len = 0 then begin IndyRaiseLastError; end; {$IFDEF STRING_IS_ANSI} Result := AnsiString(LPunnyCode); // explicit convert to Ansi (no data loss because content is ASCII) {$ELSE} Result := LPunnyCode; {$ENDIF} end else begin // TODO: manual implementation here ... end; end; procedure InitIDNLibrary; begin if hIdnDL = 0 then begin hIdnDL := SafeLoadLibrary(LibNDL); if hIdnDL <> 0 then begin DownlevelGetLocaleScripts := GetProcAddress(hIdnDL, fn_DownlevelGetLocaleScripts); DownlevelGetStringScripts := GetProcAddress(hIdnDL, fn_DownlevelGetStringScripts); DownlevelVerifyScripts := GetProcAddress(hIdnDL, fn_DownlevelVerifyScripts); end; end; if hNormaliz = 0 then begin hNormaliz := SafeLoadLibrary(LibNormaliz); if hNormaliz <> 0 then begin IdnToUnicode := GetProcAddress(hNormaliz, fn_IdnToUnicode); IdnToNameprepUnicode := GetProcAddress(hNormaliz, fn_IdnToNameprepUnicode); IdnToAscii := GetProcAddress(hNormaliz, fn_IdnToAscii); IsNormalizedString := GetProcAddress(hNormaliz,fn_IsNormalizedString); NormalizeString := GetProcAddress(hNormaliz, fn_NormalizeString); end; end; end; procedure CloseIDNLibrary; var h : THandle; begin h := InterlockedExchangeTHandle(hIdnDL, 0); if h <> 0 then begin FreeLibrary(h); end; h := InterlockedExchangeTHandle(hNormaliz, 0); if h <> 0 then begin FreeLibrary(h); end; IsNormalizedString := nil; NormalizeString := nil; IdnToUnicode := nil; IdnToNameprepUnicode := nil; IdnToAscii := nil; end; {$ELSE} function UseIDNAPI : Boolean; begin Result := False; end; function IDNToPunnyCode(const AIDN : TIdUnicodeString) : String; begin Todo('IDNToPunnyCode() is not implemented for this platform'); end; function PunnyCodeToIDN(const APunnyCode : String) : TIdUnicodeString; begin Todo('PunnyCodeToIDN() is not implemented for this platform'); end; procedure InitIDNLibrary; begin end; procedure CloseIDNLibrary; begin end; {$ENDIF} // {$IFDEF WIN32_OR_WIN64} initialization finalization CloseIDNLibrary; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Core.Condition; interface uses Behavior3, Behavior3.Core.BaseNode; type (** * Condition is the base class for all condition nodes. Thus, if you want to * create new custom condition nodes, you need to inherit from this class. * * @class Condition * @extends BaseNode **) TB3Condition = class(TB3BaseNode) private protected public (** * Initialization method. * @method initialize * @constructor **) constructor Create; override; end; implementation { TB3Condition } constructor TB3Condition.Create; begin inherited; (** * Node category. Default to `b3.CONDITION`. * @property {String} category * @readonly **) Category := Behavior3.Condition; end; end.
unit BlockLevels; interface uses Collection, SysUtils, Classes, BackupConsts; const BeginRange = '['; RangeSep = ','; EndRange = ']'; type TCollection = Collection.TCollection; TLevelManager = class; TMultiLevelStream = class; TLevelManager = class public constructor Create; destructor Destroy; override; private fLevelFiles : TCollection; fTargetFile : TStream; fLevelPath : string; fLineNumber : integer; public function CreateLevels(aStream : TStream; const Path : string) : boolean; procedure Reset; private function CreateFile(const path : string; level : integer) : boolean; function ReadLine(level : integer; var line : string) : boolean; function WriteLine(level : integer; const line : string) : boolean; function GetLevelPos(level : integer) : integer; function ReadLevel(level : integer) : boolean; private function GetLevel(index : integer) : TStream; function GetLevelCount : integer; public property LevelCount : integer read GetLevelCount; property Levels[index : integer] : TStream read GetLevel; default; end; Bounds = 0..100; TLevelBound = record LvStart : integer; LvEnd : integer; end; PLevelBounds = ^TLevelBounds; TLevelBounds = array[Bounds] of TLevelBound; TMultiLevelStream = class public constructor Create(aStream : TStream; const Path : string); destructor Destroy; override; private fLevelMan : TLevelManager; fLevelProps : TCollection; fCurLevel : integer; fLevelBounds : PLevelBounds; fLog : TStream; private function ReadPropValue(const Name : string; var Prop : string; var eob : boolean) : boolean; public function ReadString(const Name, DefVal : string) : string; function ReadLevel (const Name, DefVal : string) : string; procedure EnterLevel; procedure LeaveLevel; procedure LogText(text : string); private fLargestLevel : TStream; fLargestSize : integer; private function GetPosition : integer; function GetSize : integer; public property Position : integer read GetPosition; property Size : integer read GetSize; property Log : TStream read fLog write fLog; private function GetLevelStart : integer; procedure SetLevelStart(offset : integer); function GetLevelEnd : integer; procedure SetLevelEnd(offset : integer); protected property LevelStart : integer read GetLevelStart write SetLevelStart; property LevelEnd : integer read GetLevelEnd write SetLevelEnd; end; EBlockLevelError = class(Exception); implementation uses CompStringsParser, DelphiStreamUtils; function SkipSpaces(str : pchar) : pchar; begin while (str[0] = ' ') and (str[0] <> #0) do inc(str); result := str; end; // TLevelManager constructor TLevelManager.Create; begin inherited; fLevelFiles := TCollection.Create(0, rkBelonguer); fTargetFile := nil; fLineNumber := 1; end; destructor TLevelManager.Destroy; begin fLevelFiles.Free; inherited; end; function TLevelManager.CreateLevels(aStream : TStream; const Path : string) : boolean; begin fLevelFiles.DeleteAll; fLevelPath := Path; try fTargetFile := aStream; result := {ReadLine(0, voidStr) and } ReadLevel(0); except result := false; end; end; procedure TLevelManager.Reset; var i : integer; begin for i := 0 to pred(fLevelFiles.Count) do TStream(fLevelFiles[i]).Seek(0, soFromBeginning); end; function TLevelManager.CreateFile(const path : string; level : integer) : boolean; begin try fLevelFiles.Insert(TFileStream.Create(path, fmCreate)); result := true; except result := false; end; end; function TLevelManager.ReadLine(level : integer; var line : string) : boolean; var aux : string; begin try if DelphiStreamUtils.ReadLine(fTargetFile, aux) then begin line := SkipSpaces(pchar(aux)); // copy(aux, 2*level + 1, length(aux)-2*level); result := true; inc(fLineNumber); end else result := false; except result := false; end; end; function TLevelManager.WriteLine(level : integer; const line : string) : boolean; begin try result := DelphiStreamUtils.WriteLine(Levels[level], line); except result := false; end; end; function TLevelManager.GetLevelPos(level : integer) : integer; begin if level < fLevelFiles.Count then result := Levels[level].Size else result := 0; end; function TLevelManager.ReadLevel(level : integer) : boolean; var lvStart : integer; lvEnd : integer; curProp : string; nxtProp : string; error : boolean; begin try if level = fLevelFiles.Count then result := CreateFile(fLevelPath + 'level_' + IntToStr(level) + '.txt', level) else result := true; if result and ReadLine(level, nxtProp) then if nxtProp <> EndMark then begin repeat curProp := nxtProp; if ReadLine(level, nxtProp) then if nxtProp = BeginMark then begin lvStart := GetLevelPos(level + 1); if ReadLevel(level + 1) then begin lvEnd := GetLevelPos(level + 1); if WriteLine(level, curProp + '[' + IntToStr(lvStart) + ',' + IntToStr(lvEnd) + ']') then if level > 0 then error := not ReadLine(level, nxtProp) else error := false //error := not ReadLine(level, nxtProp) or (fTargetFile.Position <> fTargetFile.Size) else error := true; end else error := true; end else error := not WriteLine(level, curProp) else error := true; until error or (nxtProp = EndMark) or (fTargetFile.Position = fTargetFile.Size); result := not error; end else result := true else result := false; except result := false; end; end; function TLevelManager.GetLevel(index : integer) : TStream; begin result := TStream(fLevelFiles[index]); end; function TLevelManager.GetLevelCount : integer; begin result := fLevelFiles.Count; end; // TMultiLevelStream constructor TMultiLevelStream.Create(aStream : TStream; const Path : string); var i : integer; begin inherited Create; fLevelMan := TLevelManager.Create; if fLevelMan.CreateLevels(aStream, Path) then begin GetMem(fLevelBounds, (fLevelMan.LevelCount + 1)* sizeof(fLevelBounds[0])); FillChar(fLevelBounds^, (fLevelMan.LevelCount + 1) * sizeof(fLevelBounds[0]), 0); fLargestSize := 0; fLargestLevel := fLevelMan[0]; fLevelProps := TCollection.Create(fLevelMan.LevelCount, rkBelonguer); for i := 0 to pred(fLevelMan.LevelCount) do begin fLevelProps.Insert(TStringList.Create); if fLargestSize < fLevelMan[i].Size then begin fLargestSize := fLevelMan[i].Size; fLargestLevel := fLevelMan[i]; end; end; fLevelMan.Reset; end else begin fLevelMan.Free; fLevelMan := nil; raise EBlockLevelError.Create('Cannot create levels'); end; end; destructor TMultiLevelStream.Destroy; begin fLevelMan.Free; fLevelProps.Free; if fLevelBounds <> nil then FreeMem(fLevelBounds); inherited; end; function GetNameValueFmt(const str : string) : string; var p : integer; begin p := 1; result := GetNextStringUpTo(str, p, ' '); SkipChars(str, p, Spaces); SkipChars(str, p, ['=']); SkipChars(str, p, Spaces); result := result + '=' + GetNextStringUpTo(str, p, #0); end; function TMultiLevelStream.ReadPropValue(const Name : string; var Prop : string; var eob : boolean) : boolean; var line : string; aux : string; Stream : TStream; p : integer; begin Stream := fLevelMan[fCurLevel]; if ReadLine(Stream, line) then begin if Name <> '' then begin aux := Name + EqualSign; if pos(aux, line) = 1 then begin Prop := copy(line, length(aux) + 1, length(line)); result := true; end else begin LogText('Forwarded Property: ' + Name + ' in level ' + IntToStr(fCurLevel)); TStringList(fLevelProps[fCurLevel]).Add(GetNameValueFmt(line)); Prop := ''; result := false; end; end else begin p := pos(EqualSign, line) + length(EqualSign); Prop := copy(line, p, length(line) - p + 1); result := true; end; end else begin result := false; Prop := ''; end; eob := Stream.Position >= LevelEnd; end; function TMultiLevelStream.ReadString(const Name, DefVal : string) : string; var CurLevel : TStringList; index : integer; eob : boolean; begin CurLevel := TStringList(fLevelProps[fCurLevel]); // Check if the prop was already read index := CurLevel.IndexOfName(Name); if index <> -1 then result := CurLevel.Values[Name] else begin eob := false; while not eob and not ReadPropValue(Name, result, eob) do; end; if result = '' then begin result := DefVal; LogText('Missing Property: ' + Name + ' in Level ' + IntToStr(fCurLevel)); end else if index <> -1 then CurLevel.Delete(index); end; { function TMultiLevelStream.ReadString(const Name, DefVal : string) : string; var CurLevel : TStringList; index : integer; begin CurLevel := TStringList(fLevelProps[fCurLevel]); index := CurLevel.IndexOfName(Name); result := CurLevel.Values[Name]; while (result = '') and ReadPropValue(Name, result) do; if result = '' then result := DefVal else if index <> -1 then CurLevel.Delete(index); end; } function TMultiLevelStream.ReadLevel(const Name, DefVal : string) : string; var aux : string; p : integer; begin aux := ReadString(Name, DefVal); if aux <> DefVal then begin p := pos(BeginRange, aux); if p > 0 then with fLevelBounds[fCurLevel + 1] do begin result := copy(aux, 1, p - 1); inc(p); LvStart := StrToInt(GetNextStringUpTo(aux, p, RangeSep)); inc(p); LvEnd := StrToInt(GetNextStringUpTo(aux, p, EndRange)); end else with fLevelBounds[fCurLevel + 1] do begin LvStart := 0; LvStart := 0; result := aux; end; end else result := DefVal; end; procedure TMultiLevelStream.EnterLevel; begin inc(fCurLevel); fLevelMan[fCurLevel].Position := LevelStart; end; procedure TMultiLevelStream.LeaveLevel; var List : TStringList; begin List := TStringList(fLevelProps[fCurLevel]); if List.Count > 0 then begin LogText('Unused Properties in level ' + IntToStr(fCurLevel)); List.SaveToStream(fLog); LogText(''); List.Clear; end; dec(fCurLevel); end; procedure TMultiLevelStream.LogText(text : string); begin DelphiStreamUtils.WriteLine(fLog, text); end; function TMultiLevelStream.GetPosition : integer; begin result := fLargestLevel.Position; end; function TMultiLevelStream.GetSize : integer; begin result := fLargestSize; end; function TMultiLevelStream.GetLevelEnd : integer; begin result := fLevelBounds[fCurLevel].LvEnd; end; procedure TMultiLevelStream.SetLevelEnd(offset : integer); begin fLevelBounds[fCurLevel].LvEnd := offset; end; function TMultiLevelStream.GetLevelStart : integer; begin result := fLevelBounds[fCurLevel].LvStart; end; procedure TMultiLevelStream.SetLevelStart(offset : integer); begin fLevelBounds[fCurLevel].LvStart := offset; end; end.
unit afwAnswer; {* Хак для диалогов для скриптов. } // Модуль: "w:\common\components\rtl\Garant\L3\afwAnswer.pas" // Стереотип: "UtilityPack" // Элемент модели: "afwAnswer" MUID: (4E03119F00B2) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , l3AFWExceptions , l3ProtoObject , l3BatchService , l3ProtoIntegerList , SysUtils ; type EafwTryEnterModalState = El3TryEnterModalState; TafwBatchService = {final} class(Tl3ProtoObject, Il3BatchService) private f_BatchMode: Integer; f_WasDialog: Integer; public function IsBatchMode: Boolean; procedure EnterBatchMode; procedure LeaveBatchMode; procedure PushAnswer(aValue: Integer); function PopAnswer: Integer; procedure SignalWasDialog; function CheckWasDialog: Boolean; procedure ClearAnswers; class function Instance: TafwBatchService; {* Метод получения экземпляра синглетона TafwBatchService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TafwBatchService TafwAnswers = class(Tl3ProtoIntegerList) protected class function GetAnswer: Integer; class procedure SetAnswer(anAnswer: Integer); public class function Instance: TafwAnswers; {* Метод получения экземпляра синглетона TafwAnswers } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TafwAnswers EkwWaitBracketsBalance = class(Exception) end;//EkwWaitBracketsBalance {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , TtfwTypeRegistrator_Proxy , l3Base {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) //#UC START# *4E03119F00B2impl_uses* //#UC END# *4E03119F00B2impl_uses* ; var g_TafwBatchService: TafwBatchService = nil; {* Экземпляр синглетона TafwBatchService } var g_TafwAnswers: TafwAnswers = nil; {* Экземпляр синглетона TafwAnswers } procedure TafwBatchServiceFree; {* Метод освобождения экземпляра синглетона TafwBatchService } begin l3Free(g_TafwBatchService); end;//TafwBatchServiceFree procedure TafwAnswersFree; {* Метод освобождения экземпляра синглетона TafwAnswers } begin l3Free(g_TafwAnswers); end;//TafwAnswersFree function TafwBatchService.IsBatchMode: Boolean; //#UC START# *5507FDED0373_5507FE0A0095_var* //#UC END# *5507FDED0373_5507FE0A0095_var* begin //#UC START# *5507FDED0373_5507FE0A0095_impl* Result := (f_BatchMode > 0); //#UC END# *5507FDED0373_5507FE0A0095_impl* end;//TafwBatchService.IsBatchMode procedure TafwBatchService.EnterBatchMode; //#UC START# *55099B480169_5507FE0A0095_var* //#UC END# *55099B480169_5507FE0A0095_var* begin //#UC START# *55099B480169_5507FE0A0095_impl* Inc(f_BatchMode); //#UC END# *55099B480169_5507FE0A0095_impl* end;//TafwBatchService.EnterBatchMode procedure TafwBatchService.LeaveBatchMode; //#UC START# *55099B590257_5507FE0A0095_var* //#UC END# *55099B590257_5507FE0A0095_var* begin //#UC START# *55099B590257_5507FE0A0095_impl* Dec(f_BatchMode); //#UC END# *55099B590257_5507FE0A0095_impl* end;//TafwBatchService.LeaveBatchMode procedure TafwBatchService.PushAnswer(aValue: Integer); //#UC START# *553F341100FE_5507FE0A0095_var* //#UC END# *553F341100FE_5507FE0A0095_var* begin //#UC START# *553F341100FE_5507FE0A0095_impl* TafwAnswers.SetAnswer(aValue); //#UC END# *553F341100FE_5507FE0A0095_impl* end;//TafwBatchService.PushAnswer function TafwBatchService.PopAnswer: Integer; //#UC START# *553F3424010C_5507FE0A0095_var* //#UC END# *553F3424010C_5507FE0A0095_var* begin //#UC START# *553F3424010C_5507FE0A0095_impl* Result := TafwAnswers.GetAnswer; //#UC END# *553F3424010C_5507FE0A0095_impl* end;//TafwBatchService.PopAnswer procedure TafwBatchService.SignalWasDialog; //#UC START# *553F428003A3_5507FE0A0095_var* //#UC END# *553F428003A3_5507FE0A0095_var* begin //#UC START# *553F428003A3_5507FE0A0095_impl* Inc(f_WasDialog); //#UC END# *553F428003A3_5507FE0A0095_impl* end;//TafwBatchService.SignalWasDialog function TafwBatchService.CheckWasDialog: Boolean; //#UC START# *553F429502D1_5507FE0A0095_var* //#UC END# *553F429502D1_5507FE0A0095_var* begin //#UC START# *553F429502D1_5507FE0A0095_impl* Result := (f_WasDialog > 0); Dec(f_WasDialog); if (f_WasDialog < 0) then raise EkwWaitBracketsBalance.Create('Ожидали диалоговое окно, но не появилось'); //#UC END# *553F429502D1_5507FE0A0095_impl* end;//TafwBatchService.CheckWasDialog procedure TafwBatchService.ClearAnswers; //#UC START# *553F4C9802D8_5507FE0A0095_var* //#UC END# *553F4C9802D8_5507FE0A0095_var* begin //#UC START# *553F4C9802D8_5507FE0A0095_impl* if TafwAnswers.Exists then TafwAnswers.Instance.Clear; f_WasDialog := 0; //#UC END# *553F4C9802D8_5507FE0A0095_impl* end;//TafwBatchService.ClearAnswers class function TafwBatchService.Instance: TafwBatchService; {* Метод получения экземпляра синглетона TafwBatchService } begin if (g_TafwBatchService = nil) then begin l3System.AddExitProc(TafwBatchServiceFree); g_TafwBatchService := Create; end; Result := g_TafwBatchService; end;//TafwBatchService.Instance class function TafwBatchService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TafwBatchService <> nil; end;//TafwBatchService.Exists class function TafwAnswers.GetAnswer: Integer; //#UC START# *4E0321910152_553E013F0125_var* //#UC END# *4E0321910152_553E013F0125_var* begin //#UC START# *4E0321910152_553E013F0125_impl* {$IfNDef NoVCL} if Exists AND (Instance.Count > 0) AND (Instance.Last <> mrNone) then begin Result := Instance.Last; Instance.Delete(Instance.Hi); //Inc(g_WasWait); // - нельзя тут это делать // http://mdp.garant.ru/pages/viewpage.action?pageId=337513713 // http://mdp.garant.ru/pages/viewpage.action?pageId=337513713&focusedCommentId=337514042#comment-337514042 end // if Exists AND (Instance.Last <> mrNone) then else Result := mrNone; {$Else NoVCL} Assert(false); {$EndIf NoVCL} //#UC END# *4E0321910152_553E013F0125_impl* end;//TafwAnswers.GetAnswer class procedure TafwAnswers.SetAnswer(anAnswer: Integer); //#UC START# *4E0312C70245_553E013F0125_var* //#UC END# *4E0312C70245_553E013F0125_var* begin //#UC START# *4E0312C70245_553E013F0125_impl* Instance.Add(anAnswer); //#UC END# *4E0312C70245_553E013F0125_impl* end;//TafwAnswers.SetAnswer class function TafwAnswers.Instance: TafwAnswers; {* Метод получения экземпляра синглетона TafwAnswers } begin if (g_TafwAnswers = nil) then begin l3System.AddExitProc(TafwAnswersFree); g_TafwAnswers := Create; end; Result := g_TafwAnswers; end;//TafwAnswers.Instance class function TafwAnswers.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TafwAnswers <> nil; end;//TafwAnswers.Exists initialization TtfwTypeRegistrator.RegisterType(TypeInfo(EafwTryEnterModalState)); {* Регистрация типа EafwTryEnterModalState } Tl3BatchService.Instance.Alien := TafwBatchService.Instance; {* Регистрация TafwBatchService } TtfwTypeRegistrator.RegisterType(TypeInfo(EkwWaitBracketsBalance)); {* Регистрация типа EkwWaitBracketsBalance } {$IfEnd} // NOT Defined(NoScripts) end.
unit AceOut; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2005 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses windows, Printers, graphics, classes, acesetup, acefile, aceview, aceutil; type TAceCanvas = class; { TAceDestination } TAceDestination = (adPrinter, adAceFile, adPreview, adNoWhere); { TAceOutput } TAceOutput = class(TObject) private FPrinter: TPrinter; FDestination: TAceDestination; FAceCanvas: TAceCanvas; FHandle: THandle; FFileName: String; FAceFile: TAceAceFile; FAcePrinterSetup: TAcePrinterSetup; FPixelsPerInchX, FPixelsPerInchY: Integer; FLoadPercent: Single; FAceViewer: TAceViewer; FDescription: String; FCreateFile: Boolean; FExceptionText: String; protected function GetHandle: THandle; procedure SetAcePrinterSetup(ps: TAcePrinterSetup); procedure SetDestination(dest: TAceDestination); public constructor Create; destructor Destroy; override; procedure FixupPage; procedure BeginDoc; procedure EndDoc; procedure NewPage; procedure EndPage; procedure StartPage; procedure Abort; property ExceptionText: String read FExceptionText; property Destination: TAceDestination read FDestination write SetDestination; property AceCanvas: TAceCanvas read FAceCanvas write FAceCanvas; property Handle: THandle read GetHandle write FHandle; property Printer: TPrinter read FPrinter write FPrinter; property FileName: String read FFileName write FFileName; property AceFile: TAceAceFile read FAceFile write FAceFile; property AceViewer: TAceViewer read FAceViewer write FAceViewer; property PixelsPerInchX: Integer read FPixelsPerInchX write FPixelsPerInchX; property PixelsPerInchY: Integer read FPixelsPerInchY write FPixelsPerInchY; property AcePrinterSetup: TAcePrinterSetup read FAcePrinterSetup write SetAcePrinterSetup; property LoadPercent: Single read FLoadPercent write FLoadPercent; property Description: String read FDescription write FDescription; property CreateFile: Boolean read FCreateFile write FCreateFile; end; { TAceCanvas } TAceCanvas = class(TObject) private FAceOutput: TAceOutput; FFont: TFont; FBrush: TBrush; FPen: TPen; FHandle: THandle; FDestination: TAceDestination; FPixelsPerInchX, FPixelsPerInchY: Integer; FLogFont: TLogFont; FLogPen: TLogPen; FLogBrush: TLogBrush; FSelectFont: THandle; FSelectBrush: THandle; FSelectPen: THandle; protected procedure SetFont(f: TFont); procedure SetLogFont(lf: TLogFont); procedure SetBrush(b: TBrush); procedure SetLogBrush(LB: TLogBrush); procedure SetPen(p: TPen); procedure SetLogPen(LP: TLogPen); procedure SetSelectFont(hnd: THandle); function GetSelectFont: THandle; procedure SetSelectBrush(hnd: THandle); function GetSelectBrush: THandle; procedure SetSelectPen(hnd: THandle); function GetSelectPen: THandle; procedure SetHandle( hnd: THandle ); procedure FontChanged; procedure UpdateFont(Sender: TObject); procedure UpdatePen(Sender: TObject); procedure UpdateBrush(Sender: TObject); public constructor Create; destructor Destroy; override; procedure SetTextAlign(Flags: Word); procedure Textout(x,y: Integer; const Text: string); procedure MoveTo(x,y: Integer); procedure LineTo(x,y: Integer); procedure PTextOut(x,y: Integer; Text: PChar; Count: LongInt); procedure ExtTextout(x,y: Integer; Options: Word; Rect: TRect; Text: PChar; Count: word); procedure TextRect(Rect: TRect; x,y: Integer; const Text: string); procedure FillRect(Rect: TRect); procedure Rectangle(x1,y1,x2,y2: Integer); procedure RoundRect(x1,y1,x2,y2,x3,y3: Integer); procedure Ellipse(x1,y1,x2,y2: Integer); procedure Draw(x,y: Integer; Graphic: TGraphic); procedure StretchDraw(Rect: TRect; Graphic: TGraphic); procedure ShadeRect(Rect: TRect; Shade: TAceShadePercent); procedure SetFontAngle(Angle: Integer); procedure SetBkColor(bkColor: LongInt); procedure TextJustify(Rect: TRect; x,y: Integer; const Text: string; EndParagraph: Boolean;FullRect: TRect); procedure DrawBitmap(X, Y: Integer; Stream: TStream); procedure StretchDrawBitmap(Rect: TRect; Stream: TStream); property AceOutput: TAceOutput read FAceOutput write FAceoutput; property Font: TFont read FFont write SetFont; property LogFont: TLogFont read FLogFont write SetLogFont; property Brush: TBrush read FBrush write SetBrush; property LogBrush: TLogBrush read FLogBrush write SetLogBrush; property Pen: TPen read FPen write SetPen; property LogPen: TLogPen read FLogPen write SetLogPen; property Handle: THandle read FHandle write SetHandle; property Destination: TAceDestination read FDestination write FDestination; property PixelsPerInchX: Integer read FPixelsPerInchX write FPixelsPerInchX; property PixelsPerInchY: Integer read FPixelsPerInchY write FPixelsPerInchY; property SelectFont: THandle read GetSelectFont write SetSelectFont; property SelectBrush: THandle read GetSelectBrush write SetSelectBrush; property SelectPen: THandle read GetSelectPen write SetSelectPen; procedure RtfDraw(Rect: TRect; Stream: TStream; StartPos,EndPos: LongInt; SetDefFont: Boolean); procedure DrawCheckBox(Rect: TRect; CheckStyle: TAceCheckStyle; Color: TColor; Thickness: Integer); procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); procedure Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); procedure DrawShapeType(dt: TAceDrawType; x1,y1,x2,y2,x3,y3,x4,y4: Integer); procedure Polygon(const Points: array of TPoint); procedure Polyline(const Points: array of TPoint); procedure PolyDrawType(pt: TAcePolyType; const Points: array of TPoint); procedure Print3of9Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); procedure Print2of5Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); end; TAcePrintOffsetEvent = procedure; var PrintOffsetX, PrintOffsetY: Integer; OnPrintOffset: TAcePrintOffsetEvent; implementation uses sysutils, dialogs, forms, acetypes, aceimg, acectrl, AceRtfP; { TAceOutput } constructor TAceOutput.Create; begin inherited Create; FExceptionText := ''; FCreateFile := True; FDestination := adPrinter; FAceCanvas := TAceCanvas.Create; FPrinter := Printers.Printer; FHandle := 0; FPixelsPerInchX := Screen.PixelsPerInch; FPixelsPerInchY := Screen.PixelsPerInch; FAcePrinterSetup := TAcePrinterSetup.Create; FLoadPercent := 0; FFileName := ''; end; destructor TAceOutput.Destroy; begin if FAceCanvas <> nil then FAceCanvas.Destroy; if FAceFile <> nil then FAceFile.Free; if FAcePrinterSetup <> nil then FAcePrinterSetup.free; inherited Destroy; end; procedure TAceOutput.SetDestination(dest: TAceDestination); begin if dest <> FDestination then begin FDestination := dest; FAceCanvas.Destination := FDestination; end; end; function TAceOutput.GetHandle: THandle; begin if Destination = adPrinter then result := Printer.handle else result := FHandle; end; procedure TAceOutput.SetAcePrinterSetup(ps: TAcePrinterSetup); begin FAcePrinterSetup.Assign(ps); end; procedure TAceOutput.FixupPage; var OffsetX, OffsetY: Integer; Res: TPoint; begin if FDestination = adPrinter then begin PixelsPerInchX := GetDeviceCaps(Handle, LOGPIXELSX); PixelsPerInchY := GetDeviceCaps(Handle, LOGPIXELSY); SetMapMode(Handle, MM_ANISOTROPIC); if Assigned(OnPrintOffset) then begin OnPrintOffset; end; Res := AceGetResolution(Handle); { Adjust offsets if resolution of printer isn't 300dpi } OffsetX := MulDiv(PrintOffsetX, Res.X, 300); OffsetY := MulDiv(PrintOffsetY, Res.Y, 300); OffsetX := OffsetX - Round(AcePrinterSetup.LeftPrintArea * PixelsPerInchX); OffsetY := OffsetY - Round(AcePrinterSetup.TopPrintArea * PixelsPerInchY); SetViewportOrgEx(handle,OffsetX,OffsetY, nil); end; end; procedure TAceOutput.BeginDoc; begin LoadPercent := 0; FAceViewer := nil; case FDestination of adAceFile,adPreview: begin if AceFile <> nil then begin AceFile.Free; AceFile := nil; end; AceFile := TAceAceFile.Create; if (FDestination = adAceFile) And (FileName <> '') then begin AceFile.CreateFile := CreateFile; end; AceFile.FileName := FileName; AceFile.Description := Description; Handle := 0; AcePrinterSetup.SetData; AcePrinterSetup.GetData; AceFile.AcePrinterSetup := AcePrinterSetup; AceFile.PixelsPerInchX := PixelsPerInchX; AceFile.PixelsPerInchY := PixelsPerInchY; AceFile.BeginDoc; if FDestination = adPreview then begin FAceViewer := TAceViewer.Create(Application); FAceViewer.Generating := True; FAceViewer.SetAceFile(AceFile); FAceViewer.Show; end; end; adPrinter: begin AcePrinterSetup.SetData; AcePrinterSetup.GetData; if Description > '' then Printer.Title := Description else Printer.Title := 'Untitled Report'; Printer.BeginDoc; Handle := Printer.Handle; FixupPage; end; adNoWhere: { do nothing } end; AceCanvas.AceOutput := self; AceCanvas.Handle := Handle; AceCanvas.PixelsPerInchX := PixelsPerInchX; AceCanvas.PixelsPerInchY := PixelsPerInchY; if Destination = adPrinter then begin { For some odd reason this needed to be done } AceCanvas.TextOut(100,400,''); end; end; procedure TAceOutput.EndDoc; begin LoadPercent := 100; AceCanvas.Handle := 0; case FDestination of adAceFile, adPreview: begin if AceFile <> nil then begin AceFile.EndDoc; AceFile.PercentDone := 100; end; { so it doesn't get destroyed by AceOutput } if FDestination = adPreview then begin AceFile := nil; FAceViewer.Generating := False; end; end; adPrinter: begin try Printer.EndDoc; except on E: Exception do FExceptionText := E.Message; end; end; adNoWhere: { do nothing } end; end; procedure TAceOutput.NewPage; begin EndPage; StartPage; end; procedure TAceOutput.EndPage; begin {$ifdef VER_TRIAL} PageCleanup(AceCanvas); {$endif} case FDestination of adAceFile, adPreview: begin end; adPrinter: begin windows.EndPage(handle); end; adNoWhere: { do nothing } end; end; procedure TAceOutput.StartPage; begin case FDestination of adAceFile, adPreview: begin { so any new printer settings get set } AceFile.AcePrinterSetup := AcePrinterSetup; AceFile.NewPage; AceFile.PercentDone := LoadPercent; end; adPrinter: begin windows.StartPage(handle); FixupPage; AceCanvas.FontChanged; end; adNoWhere: { do nothing } end; end; procedure TAceOutput.Abort; begin AceCanvas.Handle := 0; case FDestination of adAceFile, adPreview: EndDoc; adPrinter: begin printer.Abort; windows.AbortDoc(printer.handle); // EndDoc; Was only needed for Delphi 1? end; adNoWhere: EndDoc; end; end; { TAceCanvas } constructor TAceCanvas.Create; begin inherited Create; {$IFDEF VER_TRIAL}if Not Ydaer then Abort;{$ENDIF} FDestination := adPrinter; FPen := TPen.Create; FPen.OnChange := UpdatePen; FFont := TFont.Create; FFont.OnChange := UpdateFont; FBrush := TBrush.Create; FBrush.OnChange := UpdateBrush; FSelectFont := 0; FSelectBrush := 0; FSelectPen := 0; FPixelsPerInchX := Screen.PixelsPerInch; FPixelsPerInchY := Screen.PixelsPerInch; end; destructor TAceCanvas.Destroy; begin Handle := 0; if FPen <> nil then FPen.free; if FFont <> nil then FFont.free; if FBrush <> nil then FBrush.free; if FSelectFont <> 0 then windows.DeleteObject(FSelectFont); if FSelectBrush <> 0 then windows.DeleteObject(FSelectBrush); if FSelectPen <> 0 then windows.DeleteObject(FSelectPen); inherited Destroy; end; procedure TAceCanvas.SetFont(f: TFont); begin FFont.Assign(f); end; procedure TAceCanvas.SetLogFont(LF: TLogFont); begin FLogFont := LF; FLogFont.lfHeight := -MulDiv(FFont.Size, PixelsPerInchY, 72); SelectFont := 0; FontChanged; end; procedure TAceCanvas.SetLogBrush(LB: TLogBrush); begin FLogBrush := LB; SelectBrush := 0; end; procedure TAceCanvas.SetLogPen(LP: TLogPen); begin FLogPen := LP; SelectPen := 0; end; procedure TAceCanvas.SetSelectFont(hnd: THandle); var StockFont: THandle; begin if FSelectFont <> 0 then begin StockFont := windows.GetStockObject(SYSTEM_FONT); windows.SelectObject(FHandle, StockFont); windows.DeleteObject(FSelectFont); end; FSelectFont := hnd; end; function TAceCanvas.GetSelectFont: THandle; begin if FSelectFont = 0 then begin FSelectFont := CreateFontIndirect(FLogFont); end; result := FSelectFont; end; procedure TAceCanvas.SetSelectBrush(hnd: THandle); var StockBrush: THandle; begin if FSelectBrush <> 0 then begin StockBrush := windows.GetStockObject(HOLLOW_BRUSH); windows.SelectObject(FHandle, StockBrush); windows.DeleteObject(FSelectBrush); end; FSelectBrush := hnd; end; function TAceCanvas.GetSelectBrush: THandle; begin if FSelectBrush = 0 then begin FSelectBrush := CreateBrushIndirect(FLogBrush); end; result := FSelectBrush; end; procedure TAceCanvas.SetSelectPen(hnd: THandle); var StockPen: THandle; begin if FSelectPen <> 0 then begin StockPen := windows.GetStockObject(BLACK_PEN); windows.SelectObject(FHandle, StockPen); windows.DeleteObject(FSelectPen); end; FSelectPen := hnd; end; function TAceCanvas.GetSelectPen: THandle; begin if FSelectPen = 0 then begin FSelectPen := CreatePenIndirect(FLogPen); end; result := FSelectPen; end; procedure TAceCanvas.UpdateFont(Sender: TObject); var lf: TLogFont; begin AceGetObject(FFont.Handle, SizeOf(TLogFont), Addr(lf)); LogFont := lf; case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetLogFont(FFont, FLogFont); adPrinter: FontChanged; adNoWhere:; end; end; procedure TAceCanvas.FontChanged; begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetLogFont(FFont, LogFont); adPrinter: begin windows.SelectObject(Handle, SelectFont); windows.SetTextColor(Handle, ColorToRGB(FFont.Color)); end; adNoWhere:; end; end; procedure TAceCanvas.UpdatePen(Sender: TObject); var lp: TLogPen; begin AceGetObject(FPen.Handle, SizeOf(TLogPen), Addr(lp)); LogPen := lp; case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetPen(Pen); adPrinter: begin windows.SelectObject(Handle, SelectPen); end; adNoWhere:; end; end; procedure TAceCanvas.UpdateBrush(Sender: TObject); var lb: TLogBrush; begin AceGetObject(FBrush.Handle, SizeOf(TLogBrush), Addr(lb)); LogBrush := lb; case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetBrush(Brush); adPrinter: begin windows.SelectObject(Handle, SelectBrush); windows.SetBkColor(Handle, LogBrush.lbColor); if LogBrush.lbStyle = BS_Solid then windows.SetBkMode(Handle, OPAQUE) else windows.SetBkMode(Handle, TRANSPARENT); end; adNoWhere: ; end; end; procedure TAceCanvas.SetBrush(b: TBrush); begin FBrush.Assign(b); case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetBrush(FBrush); adPrinter: UpdateBrush(FBrush); adNoWhere: ; end; end; procedure TAceCanvas.SetPen(p: TPen); begin FPen.Assign(p); case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetPen(FPen); adPrinter: UpdatePen(FPen); adNoWhere: ; end; end; procedure TAceCanvas.SetHandle( hnd: THandle ); begin FPen.OnChange := nil; FFont.OnChange := nil; FBrush.OnChange := nil; SelectFont := 0; FFont.Handle := GetStockObject(SYSTEM_FONT); SelectPen := 0; FPen.Handle := GetStockObject(BLACK_PEN); SelectBrush := 0; FBrush.Handle := GetStockObject(HOLLOW_BRUSH); FPen.OnChange := UpdatePen; FFont.OnChange := UpdateFont; FBrush.OnChange := UpdateBrush; FHandle := hnd; end; procedure TAceCanvas.SetTextAlign(flags: Word); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetTextAlign(flags); adPrinter: begin windows.SetTextAlign(Handle,flags); end; adNoWhere: ; end; end; procedure TAceCanvas.TextOut(x,y: Integer; const Text: String); var str: String; begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.TextOut(x,y,Text); adPrinter: begin str := Text; if Length(Str) > 0 then windows.TextOut(Handle, x, y, @Str[1], Length(str)); end; adNoWhere: ; end; end; procedure TAceCanvas.MoveTo(x,y: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.MoveTo(x,y); adPrinter: begin windows.MoveToEx(Handle, x, y, nil); end; adNoWhere: ; end; end; procedure TAceCanvas.LineTo(x,y: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.LineTo(x,y); adPrinter: begin windows.LineTo(Handle, x, y); end; adNoWhere: ; end; end; procedure TAceCanvas.PTextOut(x,y: Integer; Text: PChar; count: LongInt); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.PTextOut(x,y,Text,count); adPrinter: begin windows.TextOut(Handle, x,y,Text, count); end; adNoWhere: ; end; end; procedure TAceCanvas.ExtTextOut(x,y: Integer; Options: Word; Rect: TRect; Text: PChar; count: word); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.ExtTextOut(x,y,Options,Rect,Text,count); adPrinter: begin windows.ExtTextOut(Handle, x, y, Options, @Rect, Text, count, nil); end; adNoWhere: ; end; end; procedure TAceCanvas.TextRect(rect: TRect; x,y: Integer; const Text: string); var W: Word; begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.TextRect(rect,x,y,Text); adPrinter: begin W := ETO_CLIPPED; if FBrush.Style <> bsClear then Inc(W, ETO_OPAQUE); windows.ExtTextOut(Handle, x, y, W, @Rect, @Text[1], Length(Text), nil); end; adNoWhere: ; end; end; procedure TAceCanvas.FillRect(Rect: TRect); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.FillRect(Rect); adPrinter: begin windows.FillRect(Handle, Rect, SelectBrush); end; adNoWhere: ; end; end; procedure TAceCanvas.Rectangle(x1,y1,x2,y2: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.Rectangle(x1,y1,x2,y2); adPrinter: begin windows.Rectangle(Handle, x1,y1,x2,y2); end; adNoWhere: ; end; end; procedure TAceCanvas.RoundRect(x1,y1,x2,y2,x3,y3: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.RoundRect(x1,y1,x2,y2,x3,y3); adPrinter: begin windows.RoundRect(Handle,x1,y1,x2,y2,x3,y3); end; adNoWhere: ; end; end; procedure TAceCanvas.Ellipse(x1,y1,x2,y2: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.Ellipse(x1,y1,x2,y2); adPrinter: begin windows.Ellipse(Handle,x1,y1,x2,y2); end; adNoWhere: ; end; end; procedure TAceCanvas.Draw(X, Y: Integer; Graphic: TGraphic); begin if (Graphic <> nil) and not Graphic.Empty then begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.Draw(X,Y,Graphic); adPrinter: begin windows.SetBkColor(Handle, ColorToRGB(FBrush.Color)); windows.SetTextColor(Handle, ColorToRGB(FFont.Color)); { if Graphic is graphics.TBitMap Then} AceDrawBitmap(Handle, x, y, Graphic); { else if Graphic is graphics.TMetaFile then else if Graphic is graphics.TIcon then DrawIcon(Handle, X, Y, TIcon(Graphic).Handle);} end; adNoWhere: ; end; end; end; procedure TAceCanvas.StretchDraw(Rect: TRect; Graphic: TGraphic); begin if (Graphic <> nil) and not Graphic.Empty then begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.StretchDraw(Rect,Graphic); adPrinter: begin windows.SetBkColor(Handle, ColorToRGB(Brush.Color)); windows.SetTextColor(Handle, ColorToRGB(Font.Color)); { if Graphic is graphics.TBitMap Then} AceStretchDrawBitMap(Handle, Rect, Graphic) { else if Graphic is graphics.TMetaFile then else if Graphic is graphics.TIcon then DrawIcon(Handle, rect.left, rect.top, TIcon(Graphic).Handle); } end; adNoWhere: end; end; end; procedure TAceCanvas.ShadeRect(Rect: TRect; Shade: TAceShadePercent); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.ShadeRect(Rect,Shade); adPrinter: AceShadeRect(Handle, Rect, Shade); adNoWhere: ; end; end; procedure TAceCanvas.SetFontAngle(Angle: Integer); begin FLogFont.lfEscapement := Round(Angle * 10); SetLogFont(LogFont); end; procedure TAceCanvas.SetBkColor(bkColor: LongInt); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.SetBKColor(bkColor); adPrinter: begin windows.SetBkColor(Handle, bkColor); end; adNoWhere: ; end; end; procedure TAceCanvas.TextJustify(rect: TRect; x,y: Integer; const Text: string; EndParagraph: Boolean;FullRect: TRect); {var} { W: Word;} { SetOrigin: Boolean;} begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.TextJustify(rect,x,y,Text, EndParagraph,FullRect); adPrinter: begin { W := ETO_CLIPPED;} { if FBrush.Style <> bsClear then Inc(W, ETO_OPAQUE);} { SetOrigin := GetDeviceCaps(handle, TECHNOLOGY) = DT_DISPFILE;} AceTextJustify(Handle,Rect,x,y,Text,EndParagraph,FullRect); end; adNoWhere: ; end; end; procedure TAceCanvas.DrawBitmap(X, Y: Integer; Stream: TStream); begin if Stream <> nil then begin if Stream.Size > 0 then begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.DrawBitmap(X,Y,Stream); adPrinter: begin windows.SetBkColor(Handle, ColorToRGB(FBrush.Color)); windows.SetTextColor(Handle, ColorToRGB(FFont.Color)); with TAceBitmap.Create do begin LoadFromStream(Stream); Draw(Handle, x, y); Free; end; end; adNoWhere: ; end; end; end; end; procedure TAceCanvas.StretchDrawBitmap(Rect: TRect; Stream: TStream); begin if Stream <> nil then begin if Stream.Size > 0 then begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.StretchDrawBitmap(Rect,Stream); adPrinter: begin windows.SetBkColor(Handle, ColorToRGB(FBrush.Color)); windows.SetTextColor(Handle, ColorToRGB(FFont.Color)); with TAceBitmap.Create do begin LoadFromStream(Stream); StretchDraw(Handle, Rect); Free; end; end; adNoWhere: ; end; end; end; end; procedure TAceCanvas.RtfDraw(Rect: TRect; Stream: TStream; StartPos,EndPos: LongInt; SetDefFont: Boolean); var RtfDraw: TAceRtfDraw; begin if Stream <> nil then begin if Stream.Size > 0 then begin case FDestination of adAceFile, adPreview: begin AceOutput.AceFile.RtfDraw(Rect,Stream, StartPos, EndPos, SetDefFont); end; adPrinter: begin RtfDraw := TAceRtfDraw.Create; RtfDraw.Font := Font; RTfDraw.SetDefaultFont := SetDefFont; RtfDraw.RangeStart := StartPos; RtfDraw.RangeEnd := EndPos; RtfDraw.PixelsPerInchX := PixelsPerInchX; RtfDraw.PixelsPerInchY := PixelsPerInchY; RtfDraw.OutRect := Rect; RtfDraw.Handle := Handle; RtfDraw.LoadFromStream(Stream); windows.SetBkColor(Handle, ColorToRGB(FBrush.Color)); windows.SetTextColor(Handle, ColorToRGB(FFont.Color)); RtfDraw.Print; RtfDraw.Free; end; adNoWhere: ; end; end; end; end; procedure TAceCanvas.DrawCheckBox(Rect: TRect; CheckStyle: TAceCheckStyle; Color: TColor; Thickness: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.DrawCheckBox(Rect, CheckStyle, Color, Thickness); adPrinter: AceDrawCheckBox(Handle, Rect, CheckStyle, Color, Thickness); adNoWhere: ; end; end; procedure TAceCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); begin DrawShapeType(dtArc,x1,y1,x2,y2,x3,y3,x4,y4); end; procedure TAceCanvas.Chord(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); begin DrawShapeType(dtChord,x1,y1,x2,y2,x3,y3,x4,y4); end; procedure TAceCanvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); begin DrawShapeType(dtPie,x1,y1,x2,y2,x3,y3,x4,y4); end; procedure TAceCanvas.DrawShapeType(dt: TAceDrawType; x1,y1,x2,y2,x3,y3,x4,y4: Integer); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.DrawShapeType(dt,x1,y1,x2,y2,x3,y3,x4,y4); adPrinter: AceDrawShapeType(Handle, dt,x1,y1,x2,y2,x3,y3,x4,y4); adNoWhere: ; end; end; procedure TAceCanvas.Polygon(const Points: array of TPoint); begin PolyDrawType(ptPolygon, Points); end; procedure TAceCanvas.Polyline(const Points: array of TPoint); begin PolyDrawType(ptPolyLine, Points); end; procedure TAceCanvas.PolyDrawType(pt: TAcePolyType; const Points: array of TPoint); begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.PolyDrawType(pt,Points); adPrinter: AcePolyDrawType(Handle, pt, Pointer(@Points)^, High(Points) + 1); adNoWhere: ; end; end; procedure TAceCanvas.Print3of9Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); var Ace3of9: TAce3of9BarCode; begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.Print3of9Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth, Inches, Vertical, BarData); adPrinter: begin Ace3of9 := TAce3of9BarCode.Create; Ace3of9.NarrowWidth := NarrowWidth; Ace3of9.WideWidth := WideWidth; Ace3of9.Vertical := Vertical; Ace3of9.WidthInInches_1000 := Inches; Ace3of9.Width := Width; Ace3of9.Height := Height; Ace3of9.Print(Self, Left, Top,BarData); end; adNoWhere: ; end; end; procedure TAceCanvas.Print2of5Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth: Integer; Inches, Vertical: Boolean; BarData: String); var Ace2of5: TAce2of5BarCode; begin case FDestination of adAceFile, adPreview: AceOutput.AceFile.Print2of5Barcode(Left, Top, Width, Height, NarrowWidth, WideWidth, Inches, Vertical, BarData); adPrinter: begin Ace2of5 := TAce2of5BarCode.Create; Ace2of5.NarrowWidth := NarrowWidth; Ace2of5.WideWidth := WideWidth; Ace2of5.Vertical := Vertical; Ace2of5.WidthInInches_1000 := Inches; Ace2of5.Width := Width; Ace2of5.Height := Height; Ace2of5.Print(Self, Left, Top,BarData); end; adNoWhere: ; end; end; initialization PrintOffsetX := 0; PrintOffsetY := 0; OnPrintOffset := nil; end.
unit UWebGMapsDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSWebGMapsWebBrowser, FMX.TMSWebGMapsCommonFunctions, FMX.TMSWebGMapsCommon, FMX.TMSWebGMapsPolygons, FMX.TMSWebGMapsPolylines, FMX.TMSWebGMapsMarkers, FMX.Edit, Sensors, FMX.Layouts, FMX.ListBox, FMX.TMSWebGMaps, FMX.TMSWebGMapsGeocoding, FMX.TMSWebGMapsDirections, FMX.TMSWebGMapsReverseGeocoding, FMX.TabControl, FMX.ExtCtrls, FMX.Memo, FMX.TMSWebGMapsWebUtil; type TForm65 = class(TForm) Panel1: TPanel; btAddMarker: TButton; edTo: TEdit; cbCycle: TCheckBox; btAddPolygon: TButton; TMSFMXWebGMaps1: TTMSFMXWebGMaps; TMSFMXWebGMapsGeocoding1: TTMSFMXWebGMapsGeocoding; btGetDirections: TButton; edFrom: TEdit; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; Label2: TLabel; Label3: TLabel; Label4: TLabel; rbRoad: TRadioButton; rbSatellite: TRadioButton; rbTerrain: TRadioButton; rbHybrid: TRadioButton; cbPano: TCheckBox; cbTraffic: TCheckBox; cbStreetView: TCheckBox; cbWeather: TCheckBox; cbCloud: TCheckBox; cbStreetViewControl: TCheckBox; cbScaleControl: TCheckBox; cbMapType: TCheckBox; cbOverviewControl: TCheckBox; cbZoomControl: TCheckBox; edLatitude: TEdit; Label5: TLabel; Label6: TLabel; edLongitude: TEdit; btAddMarkerAddress: TButton; Label7: TLabel; edMarkerAddress: TEdit; rbMarkerDefault: TRadioButton; Label8: TLabel; rbMarkerImage: TRadioButton; cbAddMarker: TCheckBox; btClearMarkers: TButton; btClearPolygons: TButton; Label9: TLabel; Label10: TLabel; edPolygonLongitude: TEdit; edPolygonLatitude: TEdit; Label11: TLabel; cbPolygonType: TComboBox; btClearDirections: TButton; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; lbRoutes: TListBox; lbRouteDetails: TListBox; Label1: TLabel; lbEvents: TLabel; Memo1: TMemo; procedure btAddMarkerClick(Sender: TObject); procedure cbCycleChange(Sender: TObject); procedure TMSFMXWebGMaps1MapClick(Sender: TObject; Latitude, Longitude: Double; X, Y: Integer); procedure btAddPolygonClick(Sender: TObject); procedure TMSFMXWebGMaps1MarkerClick(Sender: TObject; MarkerTitle: string; IdMarker: Integer; Latitude, Longitude: Double); procedure TMSFMXWebGMaps1PolygonClick(Sender: TObject; IdPolygon: Integer); procedure btGetDirectionsClick(Sender: TObject); procedure rbRoadClick(Sender: TObject); procedure rbSatelliteClick(Sender: TObject); procedure rbTerrainClick(Sender: TObject); procedure rbHybridClick(Sender: TObject); procedure cbStreetViewControlChange(Sender: TObject); procedure btAddMarkerAddressClick(Sender: TObject); procedure btClearMarkersClick(Sender: TObject); procedure btClearPolygonsClick(Sender: TObject); procedure btClearDirectionsClick(Sender: TObject); procedure lbRoutesChange(Sender: TObject); procedure TMSFMXWebGMaps1PolylineClick(Sender: TObject; IdPolyline: Integer); procedure FormCreate(Sender: TObject); procedure TMSFMXWebGMaps1MapZoomChange(Sender: TObject; NewLevel: Integer); procedure TMSFMXWebGMaps1MapMoveEnd(Sender: TObject; Latitude, Longitude: Double; X, Y: Integer); private { Private declarations } public { Public declarations } procedure DisplayRoute; procedure DisplayRouteDetails; procedure ClearDirections; end; var Form65: TForm65; implementation const MarkerImage = 'http://www.tmssoftware.net/public/iwwebgmaps_pin.png'; {$R *.fmx} procedure TForm65.btAddMarkerAddressClick(Sender: TObject); var MarkerIcon: string; begin MarkerIcon := ''; TMSFMXWebGMapsGeocoding1.Address := edMarkerAddress.Text; if TMSFMXWebGMapsGeocoding1.LaunchGeocoding = erOk then begin if rbMarkerImage.IsChecked then MarkerIcon := MarkerImage; TMSFMXWebGmaps1.Markers.Add(TMSFMXWebGMapsGeocoding1.ResultLatitude, TMSFMXWebGMapsGeocoding1.ResultLongitude, edMarkerAddress.Text, MarkerIcon, true, true, true, false, true, 0); TMSFMXWebGMaps1.MapPanTo(TMSFMXWebGMapsGeocoding1.ResultLatitude, TMSFMXWebGMapsGeocoding1.ResultLongitude); end; end; procedure TForm65.btAddMarkerClick(Sender: TObject); var Marker: TMarker; begin if (edLatitude.Text <> '') and (edLongitude.Text <> '') then begin Marker := TMSFMXWebGMaps1.Markers.Add; Marker.Latitude := StrToFloat(edLatitude.Text); Marker.Longitude := StrToFloat(edLongitude.Text); if rbMarkerImage.IsChecked then Marker.Icon := MarkerImage; Marker.MapLabel.Text := 'New Marker'; TMSFMXWebGMaps1.CreateMapMarker(Marker); TMSFMXWebGMaps1.MapPanTo(Marker.Latitude, Marker.Longitude); end; end; procedure TForm65.btClearDirectionsClick(Sender: TObject); begin ClearDirections; end; procedure TForm65.btClearMarkersClick(Sender: TObject); begin TMSFMXWebGMaps1.Markers.Clear; TMSFMXWebGMaps1.DeleteAllMapMarker; end; procedure TForm65.btClearPolygonsClick(Sender: TObject); begin TMSFMXWebGMaps1.Polylines.Clear; TMSFMXWebGMaps1.Polygons.Clear; TMSFMXWebGMaps1.DeleteAllMapPolyline; TMSFMXWebGMaps1.DeleteAllMapPolygon; end; procedure TForm65.btAddPolygonClick(Sender: TObject); var Path: TPath; pi: TPathItem; PolygonLatitude, PolygonLongitude: Double; PolygonItem: TPolygonItem; Circle, Rect: TMapPolygon; begin if TryStrToFloat(edPolygonLatitude.Text, PolygonLatitude) and TryStrToFloat(edPolygonLongitude.Text, PolygonLongitude) then begin TMSFMXWebGMaps1.MapPanTo(PolygonLatitude, PolygonLongitude); //Line if cbPolygonType.ItemIndex = 0 then begin Path := TPath.Create; pi := Path.Add; pi.Latitude := 0; pi.Longitude := 0; pi := Path.Add; pi.Latitude := PolygonLatitude; pi.Longitude := PolygonLongitude; TMSFMXWebGMaps1.Polylines.Add(True, False, False, nil, Path, TAlphaColorRec.Blue, 255, 2, True, 0); end //Circle else if cbPolygonType.ItemIndex = 1 then begin PolygonItem := TMSFMXWebGMaps1.Polygons.Add; Circle := PolygonItem.Polygon; Circle.Clickable := true; Circle.PolygonType := ptCircle; Circle.BackgroundOpacity := 50; Circle.BorderWidth := 2; Circle.Radius := 75000; Circle.Center.Latitude := PolygonLatitude; Circle.Center.Longitude := PolygonLongitude; TMSFMXWebGMaps1.CreateMapPolygon(Circle); end //Square else if cbPolygonType.ItemIndex = 2 then begin PolygonItem := TMSFMXWebGMaps1.Polygons.Add; Rect := PolygonItem.Polygon; Rect.Clickable := true; Rect.PolygonType := ptRectangle; Rect.BackgroundOpacity := 0; Rect.BorderWidth := 2; Rect.BorderColor := TAlphaColorRec.Black; Rect.BorderOpacity := 100; Rect.Bounds.SouthWest.Latitude := PolygonLatitude - 10; Rect.Bounds.SouthWest.Longitude := PolygonLongitude - 10; Rect.Bounds.NorthEast.Latitude := PolygonLatitude; Rect.Bounds.NorthEast.Longitude := PolygonLongitude; TMSFMXWebGMaps1.CreateMapPolygon(Rect); end; end; end; procedure TForm65.btGetDirectionsClick(Sender: TObject); var I, J: Integer; TotalDistance, TotalDuration: integer; Description: string; begin ClearDirections; TMSFMXWebGmaps1.GetDirections(edFrom.Text, edTo.Text, true, tmDriving, usMetric, lnDefault, true); if TMSFMXWebGmaps1.Directions.Count > 0 then begin lbRoutes.BeginUpdate; lbRoutes.Items.Clear; for I := 0 to TMSFMXWebGmaps1.Directions.Count - 1 do begin Description := TMSFMXWebGMaps1.Directions[I].Summary + ': '; if TMSFMXWebGMaps1.Directions[I].Legs.Count = 1 then Description := Description + TMSFMXWebGMaps1.Directions[I].Legs[0].DistanceText + ', ' + TMSFMXWebGMaps1.Directions[I].Legs[0].DurationText else begin TotalDistance := 0; TotalDuration := 0; for J := 0 to TMSFMXWebGMaps1.Directions[I].Legs.Count - 1 do begin TotalDistance := TotalDistance + TMSFMXWebGMaps1.Directions[I].Legs[J].Distance; TotalDuration := TotalDuration + TMSFMXWebGMaps1.Directions[I].Legs[J].Duration; end; Description := Description + FormatFloat('0.00', TotalDistance / 1000) + ' km, ' + FormatFloat('0.00', (TotalDuration / 60) / 60) + ' h' end; lbRoutes.Items.Add(Description); end; lbRoutes.EndUpdate; lbRoutes.ItemIndex := 0; DisplayRouteDetails; DisplayRoute; end else ShowMessage('"From" or "To" location not found.'); end; procedure TForm65.cbCycleChange(Sender: TObject); begin TMSFMXWebGMaps1.MapOptions.ShowBicycling := cbCycle.IsChecked; TMSFMXWebGMaps1.MapOptions.ShowPanoramio := cbPano.IsChecked; TMSFMXWebGMaps1.MapOptions.ShowTraffic := cbTraffic.IsChecked; TMSFMXWebGMaps1.StreetViewOptions.Visible := cbStreetView.IsChecked; TMSFMXWebGMaps1.MapOptions.ShowWeather := cbWeather.IsChecked; TMSFMXWebGMaps1.MapOptions.ShowCloud := cbCloud.IsChecked; end; procedure TForm65.cbStreetViewControlChange(Sender: TObject); begin TMSFMXWebGMaps1.ControlsOptions.StreetViewControl.Visible := cbStreetViewControl.IsChecked; TMSFMXWebGMaps1.ControlsOptions.ScaleControl.Visible := cbScaleControl.IsChecked; TMSFMXWebGMaps1.ControlsOptions.MapTypeControl.Visible := cbMapType.IsChecked; TMSFMXWebGMaps1.ControlsOptions.OverviewMapControl.Visible := cbOverviewControl.IsChecked; TMSFMXWebGMaps1.ControlsOptions.ZoomControl.Visible := cbZoomControl.IsChecked; end; procedure TForm65.ClearDirections; begin TMSFMXWebGMaps1.Directions.Clear; TMSFMXWebGMaps1.Polylines.Clear; TMSFMXWebGMaps1.Polygons.Clear; TMSFMXWebGMaps1.Markers.Clear; TMSFMXWebGmaps1.DeleteAllMapPolyline; TMSFMXWebGmaps1.DeleteAllMapPolygon; TMSFMXWebGmaps1.DeleteAllMapMarker; TMSFMXWebGMaps1.Directions.Clear; lbRoutes.Clear; lbRouteDetails.Clear; end; procedure TForm65.DisplayRoute; var Route: TRoute; Marker: TMarker; Circle: TMapPolygon; Rect: TMapPolygon; PolygonItem: TPolygonItem; // I, J: Integer; begin TMSFMXWebGMaps1.DeleteAllMapPolyline; TMSFMXWebGMaps1.DeleteAllMapPolygon; Route := TMSFMXWebGMaps1.Directions[lbRoutes.ItemIndex]; //Zoom to directions Bounds TMSFMXWebGMaps1.MapZoomTo(Route.Bounds); TMSFMXWebGMaps1.CreateMapPolyline(Route.Polyline); //Add Markers TMSFMXWebGMaps1.DeleteAllMapMarker; Marker := TMSFMXWebGMaps1.Markers.Add; Marker.Draggable := false; Marker.Latitude := Route.Legs[0].StartLocation.Latitude; Marker.Longitude := Route.Legs[0].StartLocation.Longitude; Marker.Title := 'Start Location'; Marker.MapLabel.Text := 'Start Location: ' + Route.Legs[0].StartAddress; TMSFMXWebGMaps1.CreateMapMarker(Marker); Marker := TMSFMXWebGMaps1.Markers.Add; Marker.Draggable := false; Marker.Latitude := Route.Legs[0].EndLocation.Latitude; Marker.Longitude := Route.Legs[0].EndLocation.Longitude; Marker.Title := 'Destination'; Marker.MapLabel.Text := '<b>Destination:</b> ' + Route.Legs[0].EndAddress; Marker.MapLabel.Color := TAlphaColorRec.Yellow; Marker.MapLabel.BorderColor := TAlphaColorRec.Red; Marker.MapLabel.FontColor := TAlphaColorRec.Red; Marker.MapLabel.Font.Size := 14; TMSFMXWebGMaps1.CreateMapMarker(Marker); //Add Polygon Circles // if CheckBox1.Checked then begin PolygonItem := TMSFMXWebGMaps1.Polygons.Add; Circle := PolygonItem.Polygon; Circle.PolygonType := ptCircle; Circle.BackgroundOpacity := 50; Circle.BorderWidth := 2; Circle.Radius := Integer(Route.Legs[0].Distance div 10); Circle.Center.Latitude := Route.Legs[0].StartLocation.Latitude; Circle.Center.Longitude := Route.Legs[0].StartLocation.Longitude; TMSFMXWebGMaps1.CreateMapPolygon(Circle); PolygonItem := TMSFMXWebGMaps1.Polygons.Add; Circle := PolygonItem.Polygon; Circle.PolygonType := ptCircle; Circle.BackgroundOpacity := 50; Circle.BorderWidth := 2; Circle.Radius := Integer(Route.Legs[0].Distance div 10); Circle.Center.Latitude := Route.Legs[0].EndLocation.Latitude; Circle.Center.Longitude := Route.Legs[0].EndLocation.Longitude; TMSFMXWebGMaps1.CreateMapPolygon(Circle); end; //Add Polygon Rectangle // if CheckBox2.Checked then begin PolygonItem := TMSFMXWebGMaps1.Polygons.Add; Rect := PolygonItem.Polygon; Rect.PolygonType := ptRectangle; Rect.BackgroundOpacity := 0; Rect.BorderWidth := 2; // Rect.BorderColor := clBlack; Rect.BorderOpacity := 100; Rect.Bounds.SouthWest.Latitude := Route.Bounds.SouthWest.Latitude; Rect.Bounds.SouthWest.Longitude := Route.Bounds.SouthWest.Longitude; Rect.Bounds.NorthEast.Latitude := Route.Bounds.NorthEast.Latitude; Rect.Bounds.NorthEast.Longitude := Route.Bounds.NorthEast.Longitude; TMSFMXWebGMaps1.CreateMapPolygon(Rect); end; end; procedure TForm65.DisplayRouteDetails; var I, J: Integer; begin lbRoutes.BeginUpdate; lbRouteDetails.Items.Clear; if lbRoutes.ItemIndex >= 0 then begin for J := 0 to TMSFMXWebGMaps1.Directions[lbRoutes.ItemIndex].Legs.Count - 1 do begin for I := 0 to TMSFMXWebGMaps1.Directions[lbRoutes.ItemIndex].Legs[J].Steps.Count - 1 do begin lbRouteDetails.Items.Add(TMSFMXWebGMaps1.Directions[lbRoutes.ItemIndex].Legs[J].Steps[I].Instructions); end; end; end; lbRoutes.EndUpdate; end; procedure TForm65.FormCreate(Sender: TObject); begin rbMarkerDefault.IsChecked := true; rbRoad.IsChecked := true; end; procedure TForm65.lbRoutesChange(Sender: TObject); begin DisplayRouteDetails; DisplayRoute; end; procedure TForm65.rbHybridClick(Sender: TObject); begin TMSFMXWebGMaps1.MapOptions.MapType := mtHybrid; end; procedure TForm65.rbRoadClick(Sender: TObject); begin TMSFMXWebGMaps1.MapOptions.MapType := mtDefault; end; procedure TForm65.rbSatelliteClick(Sender: TObject); begin TMSFMXWebGMaps1.MapOptions.MapType := mtSatellite; end; procedure TForm65.rbTerrainClick(Sender: TObject); begin TMSFMXWebGMaps1.MapOptions.MapType := mtTerrain; end; procedure TForm65.TMSFMXWebGMaps1MapClick(Sender: TObject; Latitude, Longitude: Double; X, Y: Integer); var MarkerIcon: string; begin lbEvents.Text := 'Events: MAP Click: ' + FloatToStr(X) + ' * ' + FloatToStr(Y); if cbAddMarker.IsChecked then begin MarkerIcon := ''; if rbMarkerImage.IsChecked then MarkerIcon := MarkerImage; TMSFMXWebGmaps1.Markers.Add(Latitude, Longitude, 'New Marker', MarkerIcon, true, true, true, false, true, 0); end; end; procedure TForm65.TMSFMXWebGMaps1MapMoveEnd(Sender: TObject; Latitude, Longitude: Double; X, Y: Integer); begin lbEvents.Text := 'Events: MAP Move to: ' + FloatToStr(Latitude); end; procedure TForm65.TMSFMXWebGMaps1MapZoomChange(Sender: TObject; NewLevel: Integer); begin lbEvents.Text := 'Events: MAP Zoom change to level: ' + IntToStr(NewLevel); end; procedure TForm65.TMSFMXWebGMaps1MarkerClick(Sender: TObject; MarkerTitle: string; IdMarker: Integer; Latitude, Longitude: Double); begin lbEvents.Text := 'Events: MAP Marker Click: ' + FloatToStr(Latitude); end; procedure TForm65.TMSFMXWebGMaps1PolygonClick(Sender: TObject; IdPolygon: Integer); begin lbEvents.Text := 'Events: MAP Polygon Click: ' + IntToStr(IdPolygon); end; procedure TForm65.TMSFMXWebGMaps1PolylineClick(Sender: TObject; IdPolyline: Integer); begin lbEvents.Text := 'Events: MAP Polyline Click: ' + IntToStr(IdPolyline); end; end.
unit ce_staticmacro; {$I ce_defines.inc} interface uses Classes, Sysutils, SynEdit, SynCompletion, ce_interfaces, ce_writableComponent, ce_synmemo; type (** * Static macros options containers *) TStaticMacrosOptions = class(TWritableLfmTextComponent) private fAutoInsert: boolean; fShortCut: TShortCut; fMacros: TStringList; procedure setMacros(aValue: TStringList); published property autoInsert: boolean read fAutoInsert write fAutoInsert; property macros: TStringList read fMacros write setMacros; property shortcut: TShortCut read fShortCut write fShortCut; public constructor create(aOwner: TComponent); override; destructor destroy; override; procedure Assign(Source: TPersistent); override; procedure AssignTo(Dest: TPersistent); override; end; (** * TCEStaticEditorMacro is used to insert static macros (parameter-less code snippets) * in an editor. A macro begins with the dollar symbol and ends with an alphanum. * * The dollar symbol is used as starter because it's usually accessible without * modifier: no CTRL, no ALT, no SHIFT. * Erroneous insertion is avoided because in D '$' is either followed * by a symbol: '$-1', '$]' or by a blank '$ ]' * * Shift + SPACE works automatically on the right editor (ICEMultiDocObserver) * Automatic insertion is handled in TCESynMemo.KeyUp() *) TCEStaticEditorMacro = class(TWritableLfmTextComponent, ICEMultiDocObserver, ICEEditableOptions, ICEEditableShortCut) private fCompletor: TSynAutoComplete; fMacros: TStringList; fDoc: TCESynMemo; fAutomatic: boolean; fOptions: TStaticMacrosOptions; fOptionBackup: TStaticMacrosOptions; procedure sanitize; procedure addDefaults; procedure updateCompletor; procedure setMacros(aValue: TStringList); // ICEMultiDocObserver procedure docNew(aDoc: TCESynMemo); procedure docFocused(aDoc: TCESynMemo); procedure docChanged(aDoc: TCESynMemo); procedure docClosing(aDoc: TCESynMemo); // ICEEditableOptions function optionedWantCategory(): string; function optionedWantEditorKind: TOptionEditorKind; function optionedWantContainer: TPersistent; procedure optionedEvent(anEvent: TOptionEditorEvent); function optionedOptionsModified: boolean; // ICEEditableShortcut function scedWantFirst: boolean; function scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; procedure scedSendItem(const category, identifier: string; aShortcut: TShortcut); published // list of string with the format $<..>alnum=<..> property macros: TStringList read fMacros write setMacros; property automatic: boolean read fAutomatic write fAutomatic; public constructor create(aOwner: TComponent); override; destructor destroy; override; // execute using the editor procedure Execute; overload; // execute in aEditor, according to aToken procedure Execute(aEditor: TCustomSynEdit; const aToken: string); overload; end; var StaticEditorMacro: TCEStaticEditorMacro = nil; implementation uses ce_observer, ce_common; const OptFname = 'staticmacros.txt'; defMacros: array[0..14] of string = ( '$a=auto', '$c=class {}', '$e=enum {}', '$it=interface {}', '$im=import ', '$pr=protected {}', '$pu=public {}', '$pv=private {}', '$s=struct {}', '$t=template {}', '$un=union{}', '$ut=unittest{}', '$fo=for(auto i = 0; ; )', '$fe=foreach(elem; )', '$v=void (){}' ); {$REGION TStaticMacrosOptions --------------------------------------------------} constructor TStaticMacrosOptions.create(aOwner: TComponent); begin inherited; fMacros := TStringList.Create; end; destructor TStaticMacrosOptions.destroy; begin fMacros.Free; inherited; end; procedure TStaticMacrosOptions.Assign(Source: TPersistent); var edmac: TCEStaticEditorMacro; opt: TStaticMacrosOptions; begin if Source is TCEStaticEditorMacro then begin edmac := TCEStaticEditorMacro(Source); // fAutoInsert := edmac.automatic; fMacros.Assign(edmac.fMacros); fShortCut := edmac.fCompletor.ShortCut; end else if Source is TStaticMacrosOptions then begin opt := TStaticMacrosOptions(Source); // autoInsert := opt.autoInsert; macros.Assign(opt.fMacros); shortcut := opt.shortcut; end else inherited; end; procedure TStaticMacrosOptions.AssignTo(Dest: TPersistent); var edmac: TCEStaticEditorMacro; opt: TStaticMacrosOptions; begin if Dest is TCEStaticEditorMacro then begin edmac := TCEStaticEditorMacro(Dest); // edmac.automatic := fAutoInsert; // setMacros sanitizes the macros edmac.setMacros(fMacros); fMacros.Assign(edmac.fMacros); // edmac.fCompletor.ShortCut := fShortCut; end else if Dest is TStaticMacrosOptions then begin opt := TStaticMacrosOptions(Dest); // opt.autoInsert := autoInsert; opt.macros.Assign(fMacros); opt.shortcut := shortcut; end else inherited; end; procedure TStaticMacrosOptions.setMacros(aValue: TStringList); begin fMacros.Assign(aValue); end; {$ENDREGION} {$REGION Standard Comp/Obj -----------------------------------------------------} constructor TCEStaticEditorMacro.create(aOwner: TComponent); var fname: string; begin inherited; fAutomatic := true; fCompletor := TSynAutoComplete.Create(self); fCompletor.ShortCut := 8224; // SHIFT + SPACE fMacros := TStringList.Create; fMacros.Delimiter := '='; addDefaults; // fOptions := TStaticMacrosOptions.create(self); fOptionBackup := TStaticMacrosOptions.create(self); fname := getCoeditDocPath + OptFname; if fileExists(fname) then begin fOptions.loadFromFile(fname); // old option file will create a streaming error. if fOptions.hasLoaded then fOptions.AssignTo(self) else fOptions.Assign(self); end else fOptions.Assign(self); // sanitize; updateCompletor; // EntitiesConnector.addObserver(Self); end; destructor TCEStaticEditorMacro.destroy; begin fOptions.saveToFile(getCoeditDocPath + OptFname); EntitiesConnector.removeObserver(Self); // fMacros.Free; inherited; end; procedure TCEStaticEditorMacro.setMacros(aValue: TStringList); begin fMacros.Assign(aValue); addDefaults; sanitize; updateCompletor; end; {$ENDREGION} {$REGION ICEMultiDocObserver ---------------------------------------------------} procedure TCEStaticEditorMacro.docNew(aDoc: TCESynMemo); begin fDoc := aDoc; fCompletor.Editor := fDoc; end; procedure TCEStaticEditorMacro.docFocused(aDoc: TCESynMemo); begin if fDoc = aDoc then exit; fDoc := aDoc; fCompletor.Editor := fDoc; end; procedure TCEStaticEditorMacro.docChanged(aDoc: TCESynMemo); begin if aDoc <> fDoc then exit; end; procedure TCEStaticEditorMacro.docClosing(aDoc: TCESynMemo); begin if aDoc <> fDoc then exit; fDoc := nil; end; {$ENDREGION} {$REGION ICEEditableOptions ----------------------------------------------------} function TCEStaticEditorMacro.optionedWantCategory(): string; begin exit('Static macros'); end; function TCEStaticEditorMacro.optionedWantEditorKind: TOptionEditorKind; begin exit(oekGeneric); end; function TCEStaticEditorMacro.optionedWantContainer: TPersistent; begin fOptions.Assign(self); fOptionBackup.Assign(fOptions); exit(fOptions); end; procedure TCEStaticEditorMacro.optionedEvent(anEvent: TOptionEditorEvent); begin case anEvent of oeeAccept: begin fOptions.AssignTo(self); fOptionBackup.Assign(self); end; oeeCancel: begin fOptionBackup.AssignTo(self); fOptionBackup.AssignTo(fOptions); end; oeeChange: fOptions.AssignTo(self); end; end; function TCEStaticEditorMacro.optionedOptionsModified: boolean; begin exit(false); end; {$ENDREGION} {$REGION ICEEditableShortCut ---------------------------------------------------} function TCEStaticEditorMacro.scedWantFirst: boolean; begin exit(true); end; function TCEStaticEditorMacro.scedWantNext(out category, identifier: string; out aShortcut: TShortcut): boolean; begin category := 'Static macros'; identifier := 'invoke'; aShortcut := fCompletor.ShortCut; exit(false); end; procedure TCEStaticEditorMacro.scedSendItem(const category, identifier: string; aShortcut: TShortcut); begin if category = 'Static macros' then if identifier = 'invoke' then begin fCompletor.ShortCut := aShortcut; fOptionBackup.shortcut := aShortcut; fOptions.shortcut := aShortcut; end; end; {$ENDREGION} {$REGION Macros things ---------------------------------------------------------} procedure TCEStaticEditorMacro.sanitize; var i: Integer; text: string; macro: string; begin for i := fMacros.Count-1 downto 0 do begin text := fMacros.Strings[i]; if length(text) >= 4 then if text[1] = '$' then if Pos('=', text) > 2 then begin macro := fMacros.Names[i]; if (macro[length(macro)] in ['a'..'z', 'A'..'Z', '0'..'9']) then continue; end; fMacros.Delete(i); end; end; procedure TCEStaticEditorMacro.addDefaults; var i: Integer; begin for i := 0 to high(defMacros) do if fMacros.IndexOf(defMacros[i]) = -1 then fMacros.Add(defMacros[i]); end; procedure TCEStaticEditorMacro.updateCompletor; var i: Integer; tok, val: string; begin fCompletor.AutoCompleteList.Clear; for i := 0 to fMacros.Count-1 do begin tok := fMacros.Names[i]; val := fMacros.ValueFromIndex[i]; fCompletor.AutoCompleteList.Add(tok); fCompletor.AutoCompleteList.Add('=' + val); end; end; procedure TCEStaticEditorMacro.Execute; begin if fDoc <> nil then fCompletor.Execute(fDoc.Identifier, fDoc); end; procedure TCEStaticEditorMacro.Execute(aEditor: TCustomSynEdit; const aToken: string); begin if aEditor <> nil then fCompletor.Execute(aToken, aEditor); end; {$ENDREGION} initialization StaticEditorMacro := TCEStaticEditorMacro.create(nil); finalization StaticEditorMacro.Free;; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpX9FieldElement; {$I ..\..\Include\CryptoLib.inc} interface uses ClpBigInteger, ClpECFieldElement, ClpCryptoLibTypes, ClpDerOctetString, ClpX9IntegerConverter, ClpIProxiedInterface, ClpIAsn1OctetString, ClpIECFieldElement, ClpIX9FieldElement, ClpAsn1Encodable; type /// <summary> /// Class for processing an ECFieldElement as a DER object. /// </summary> TX9FieldElement = class(TAsn1Encodable, IX9FieldElement) strict private var Ff: IECFieldElement; function GetValue: IECFieldElement; inline; public constructor Create(const f: IECFieldElement); overload; constructor Create(const p: TBigInteger; const s: IAsn1OctetString); overload; deprecated 'Will be removed'; constructor Create(m, k1, k2, k3: Int32; const s: IAsn1OctetString); overload; deprecated 'Will be removed'; // /** // * Produce an object suitable for an Asn1OutputStream. // * <pre> // * FieldElement ::= OCTET STRING // * </pre> // * <p> // * <ol> // * <li> if <i>q</i> is an odd prime then the field element is // * processed as an Integer and converted to an octet string // * according to x 9.62 4.3.1.</li> // * <li> if <i>q</i> is 2<sup>m</sup> then the bit string // * contained in the field element is converted into an octet // * string with the same ordering padded at the front if necessary. // * </li> // * </ol> // * </p> // */ function ToAsn1Object(): IAsn1Object; override; property Value: IECFieldElement read GetValue; end; implementation { TX9FieldElement } constructor TX9FieldElement.Create(const p: TBigInteger; const s: IAsn1OctetString); begin Create(TFpFieldElement.Create(p, TBigInteger.Create(1, s.GetOctets())) as IFpFieldElement) end; constructor TX9FieldElement.Create(const f: IECFieldElement); begin Inherited Create(); Ff := f; end; constructor TX9FieldElement.Create(m, k1, k2, k3: Int32; const s: IAsn1OctetString); begin Create(TF2mFieldElement.Create(m, k1, k2, k3, TBigInteger.Create(1, s.GetOctets())) as IF2mFieldElement) end; function TX9FieldElement.GetValue: IECFieldElement; begin result := Ff; end; function TX9FieldElement.ToAsn1Object: IAsn1Object; var byteCount: Int32; paddedBigInteger: TCryptoLibByteArray; begin byteCount := TX9IntegerConverter.GetByteLength(Ff); paddedBigInteger := TX9IntegerConverter.IntegerToBytes(Ff.ToBigInteger(), byteCount); result := TDerOctetString.Create(paddedBigInteger); end; end.
unit kwArray; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwArray.pas" // Начат: 12.05.2011 21:14 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Scripting::ScriptEngine::ArrayProcessing::TkwArray // // Определяет поддержку массивов в скриптах. // Пример: // {code} // ARRAY L // 0 10 FOR // ++ // DUP // >>>[] L // NEXT // DROP // @ . ITERATE L // // - печатает числа от 1 до 10 // '' . // 0 @ + ITERATE L . // // - суммирует числа от 1 до 10 и печатает результат // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses l3Interfaces, tfwScriptingInterfaces, kwCompiledWord, l3ParserInterfaces ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\tfwVar.imp.pas} TkwArray = class(_tfwVar_) {* Определяет поддержку массивов в скриптах. Пример: [code] ARRAY L 0 10 FOR ++ DUP >>>[] L NEXT DROP @ . ITERATE L // - печатает числа от 1 до 10 '' . 0 @ + ITERATE L . // - суммирует числа от 1 до 10 и печатает результат [code] } protected // overridden protected methods function CompiledWordClass: RkwCompiledWord; override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwArray {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses kwCompiledArray, kwCompiledVar, SysUtils, l3String, l3Parser, kwInteger, kwString, TypInfo, l3Base, kwIntegerFactory, kwStringFactory, l3Chars, tfwAutoregisteredDiction, tfwScriptEngine ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwArray; {$Include ..\ScriptEngine\tfwVar.imp.pas} // start class TkwArray class function TkwArray.GetWordNameForRegister: AnsiString; //#UC START# *4DB0614603C8_4DCC157102A8_var* //#UC END# *4DB0614603C8_4DCC157102A8_var* begin //#UC START# *4DB0614603C8_4DCC157102A8_impl* Result := 'ARRAY'; //#UC END# *4DB0614603C8_4DCC157102A8_impl* end;//TkwArray.GetWordNameForRegister function TkwArray.CompiledWordClass: RkwCompiledWord; //#UC START# *4DBAEE0D028D_4DCC157102A8_var* //#UC END# *4DBAEE0D028D_4DCC157102A8_var* begin //#UC START# *4DBAEE0D028D_4DCC157102A8_impl* Result := TkwCompiledArray; //#UC END# *4DBAEE0D028D_4DCC157102A8_impl* end;//TkwArray.CompiledWordClass {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\tfwVar.imp.pas} {$IfEnd} //not NoScripts end.
UNIT GENERAL; INTERFACE FUNCTION FILLZERO(x,l:integer):string; FUNCTION FILLSPACE(s:string;l:integer):string; FUNCTION BYTE_HEX(b:byte):string; FUNCTION WORD_HEX(w:word):string; FUNCTION MAJUSCULE(s:string):string; FUNCTION NOMPROPRE(s:string):string; FUNCTION CLEARSPACE(s:string):string; FUNCTION CHAINEVIERGE(s:string):boolean; FUNCTION CODE(s:string;i:integer):string; FUNCTION DECODE(s:string;i:integer):string; IMPLEMENTATION FUNCTION FILLZERO(x,l:integer):string; {*******************************************************} { Transforme x en 000x avec l=nbre chiffres { Transforme -x en -000x avec l=nbre chiffres {*******************************************************} var s:string; i:integer; begin str(x,s); if s[1]='-' then begin for i:=1 to (l-length(s)) do s:=s[1]+'0'+copy(s,2,length(s)-1) end else begin for i:=1 to (l-length(s)) do s:='0'+s end; fillzero:=s; end; FUNCTION FILLSPACE(s:string;l:integer):string; {*******************************************************} {Transforme 's' en ' s' avec l=nbre char {*******************************************************} begin while length(s)<l do s:=' '+s; end; FUNCTION SWAP_BYTE(b:byte):byte; {*******************************************************} {Swap un byte {*******************************************************} var w:word; begin w:=0; w:=b shl 4; SWAP_BYTE:=lo(w)+hi(w); end; FUNCTION SWAP_WORD(w:word):word; {*******************************************************} {Swap un word {*******************************************************} begin SWAP_WORD:=hi(w)+(lo(w) shl 8); end; FUNCTION BYTE_HEX(b:byte):string; {*******************************************************} {Conversion Byte->Hex {*******************************************************} const hexchars:array[0..15] of char='0123456789ABCDEF'; begin Byte_Hex[0]:=#2; Byte_Hex[1]:=hexchars[b shr 4]; Byte_Hex[2]:=hexchars[b and 15]; end; FUNCTION WORD_HEX(w:word):string; {*******************************************************} {Conversion Word->Hex {*******************************************************} begin word_hex:=byte_hex(hi(w))+byte_hex(lo(w)); end; FUNCTION MAJUSCULE(s:string):string; {*******************************************************} {Renvoi chaine s en chaine majuscule {*******************************************************} var i:integer; begin for i:=1 to length(s) do s[i]:=upcase(s[i]); majuscule:=s; end; FUNCTION NOMPROPRE(s:string):string; {*******************************************************} {Renvoi chaine s avec premiŠre lettre en majuscule {*******************************************************} begin s[1]:=upcase(s[1]); nompropre:=s; end; FUNCTION CLEARSPACE(s:string):string; {*******************************************************} {Renvoi la chaine sans espaces {*******************************************************} var b:boolean; i:integer; begin while pos(' ',s)>0 do delete(s,pos(' ',s),1); clearspace:=s; end; FUNCTION CHAINEVIERGE(s:string):boolean; {*******************************************************} {Renvoi True si la chaine s n'a que des espaces {*******************************************************} var b:boolean; i:integer; begin b:=true; for i:=1 to length(s) do b:=(b and (s[i]=' ')); chainevierge:=b; end; FUNCTION CODE(s:string;i:integer):string; {*******************************************************} {Transforme chaine s en chaine cod‚e {*******************************************************} var t:string; j:integer; begin t:=''; for j:=1 to length(s) do begin t:=t+chr(SWAP_BYTE(i xor ord(s[j]))) end; code:=t; end; FUNCTION DECODE(s:string;i:integer):string; {*******************************************************} {Transforme chaine s en chaine cod‚e {*******************************************************} var t:string; j:integer; begin t:=''; for j:=1 to length(s) do begin t:=t+chr(i xor SWAP_BYTE(ord(s[j]))) end; decode:=t; end; end.
{ Subroutine SST_FLAG_USED_OPCODES (FIRST_P) * * Set the USED flags for all symbols eventually referenced by a chain of * ocpcodes. FIRST_P is pointing to the first opcode in the chain. It is * permissable for FIRST_P to be NIL to indicate an empty chain. * * It is assumed that the front end has at least flagged the basic compilable * blocks (modules, programs, routines) as USED where apporpriate. Unused * blocks will be skipped here. } module sst_FLAG_USED_OPCODES; define sst_flag_used_opcodes; %include 'sst2.ins.pas'; procedure sst_flag_used_opcodes ( {flag symbols eventually used from opcodes} in first_p: sst_opc_p_t); {points to first opcode in chain, may be NIL} const max_msg_parms = 1; {max parameters we can pass to a message} var opc_p: sst_opc_p_t; {pointer to current opcode descriptor} case_val_p: sst_case_val_p_t; {points to curr descriptor in chain} case_opc_p: sst_case_opc_p_t; {points to curr descriptor in chain} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin opc_p := first_p; {init pointer to current opcode} while opc_p <> nil do begin {loop thru each opcode in this chain} case opc_p^.opcode of {what kind of opcode is this ?} sst_opc_module_k: begin {start of a grouping of routines} if sst_symflag_used_k in opc_p^.module_sym_p^.flags then begin {used ?} sst_flag_used_symbol (opc_p^.module_sym_p^); sst_flag_used_opcodes (opc_p^.module_p); end; end; sst_opc_prog_k: begin {start of top level program} if sst_symflag_used_k in opc_p^.prog_sym_p^.flags then begin {used ?} sst_flag_used_symbol (opc_p^.prog_sym_p^); sst_flag_used_opcodes (opc_p^.prog_p); end; end; sst_opc_rout_k: begin {start of a routine} if sst_symflag_used_k in opc_p^.rout_sym_p^.flags then begin {used ?} sst_flag_used_symbol (opc_p^.rout_sym_p^); sst_flag_used_opcodes (opc_p^.rout_p); end; end; sst_opc_exec_k: begin {points to chain of executable code} sst_flag_used_opcodes (opc_p^.exec_p); end; sst_opc_label_k: begin {indicate handle for a label} sst_flag_used_symbol (opc_p^.label_sym_p^); end; sst_opc_call_k: begin {subroutine call} sst_flag_used_var (opc_p^.call_var_p^); sst_flag_used_rout (opc_p^.call_proc_p^); end; sst_opc_assign_k: begin {assignment statement} sst_flag_used_var (opc_p^.assign_var_p^); sst_flag_used_exp (opc_p^.assign_exp_p^); end; sst_opc_goto_k: begin {unconditional transfer of control} sst_flag_used_symbol (opc_p^.goto_sym_p^); end; sst_opc_case_k: begin {execute one of N blocks of code} sst_flag_used_exp (opc_p^.case_exp_p^); sst_flag_used_opcodes (opc_p^.case_none_p); case_val_p := opc_p^.case_val_p; while case_val_p <> nil do begin {loop thru all the CASE_VAL blocks} sst_flag_used_exp (case_val_p^.exp_p^); case_val_p := case_val_p^.next_val_p; end; case_opc_p := opc_p^.case_opc_p; while case_opc_p <> nil do begin {loop thru all the CASE_OPC blocks} sst_flag_used_opcodes (case_opc_p^.code_p); case_opc_p := case_opc_p^.next_p; end; end; sst_opc_if_k: begin {IF ... THEN ... ELSE ... statement} sst_flag_used_exp (opc_p^.if_exp_p^); sst_flag_used_opcodes (opc_p^.if_true_p); sst_flag_used_opcodes (opc_p^.if_false_p); end; sst_opc_loop_cnt_k: begin {counted loop (Pascal FOR, Fortran DO, etc)} sst_flag_used_var (opc_p^.lpcn_var_p^); sst_flag_used_exp (opc_p^.lpcn_exp_start_p^); sst_flag_used_exp (opc_p^.lpcn_exp_end_p^); sst_flag_used_exp (opc_p^.lpcn_exp_inc_p^); sst_flag_used_opcodes (opc_p^.lpcn_code_p); end; sst_opc_loop_ttop_k: begin {loop with test at start of loop} sst_flag_used_exp (opc_p^.lptp_exp_p^); sst_flag_used_opcodes (opc_p^.lptp_code_p); end; sst_opc_loop_tbot_k: begin {loop with test at end of loop} sst_flag_used_exp (opc_p^.lpbt_exp_p^); sst_flag_used_opcodes (opc_p^.lpbt_code_p); end; sst_opc_loop_next_k: begin {go to start of next time around loop} end; sst_opc_loop_exit_k: begin {unconditionally exit loop} end; sst_opc_return_k: begin {return from subroutine} end; sst_opc_abbrev_k: begin {abbreviations in effect for block of code} sst_flag_used_opcodes (opc_p^.abbrev_code_p); end; sst_opc_discard_k: begin {call function, but discard its return value} sst_flag_used_exp (opc_p^.discard_exp_p^); end; sst_opc_write_k: begin {write expression value to standard output} sst_flag_used_exp (opc_p^.write_exp_p^); if opc_p^.write_width_exp_p <> nil then begin sst_flag_used_exp (opc_p^.write_width_exp_p^); end; if opc_p^.write_width2_exp_p <> nil then begin sst_flag_used_exp (opc_p^.write_width2_exp_p^); end; end; sst_opc_write_eol_k: begin {write end of line to standard output} end; otherwise sys_msg_parm_int (msg_parm[1], ord(opc_p^.opcode)); syo_error (opc_p^.str_h, 'sst', 'opcode_unexpected', msg_parm, 1); end; {end of opcode type cases} opc_p := opc_p^.next_p; {advance to next opcode in this chain} end; {back and process this new opcode} end;
unit tmsUXlsStrings; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsXlsMessages, SysUtils, Classes, tmsUXlsBaseRecords, tmsUFlxMessages; type TStrLenLength= 1..2; TCharSize=1..2; TExcelString= class private // Common data StrLenLength: TStrLenLength; //this stores if it's a one or two bytes length public StrLen: word; OptionFlags: byte; WideData: UTF16String; ShortData: AnsiString; //Rich text NumberRichTextFormats: word; RichTextFormats: PArrayOfByte; //FarEast FarEastDataSize: LongWord; FarEastData: PArrayOfByte; function GetValue: UTF16String; public constructor Create(const aStrLenLength: TStrLenLength; var aRecord: TBaseRecord; var Ofs: integer);overload; constructor Create(const aStrLenLength: TStrLenLength;const s: UTF16String; const ForceWide: boolean= false); overload; destructor Destroy;override; procedure SaveToStream(const DataStream: TStream);overload; procedure SaveToStream(const DataStream: TStream; const IncludeLen: boolean); overload; function GetCharSize: TCharSize; function HasRichText: boolean; function HasFarInfo: boolean; function Compare(const Str2: TExcelString): integer; //-1 if less, 0 if equal, 1 if more function TotalSize: int64; procedure CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer);overload; procedure CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer; const IncludeLen: boolean);overload; property Value: UTF16String read GetValue; end; implementation { TExcelString } {$IFDEF DELPHI2008UP} function MyShortCompareStr(const S1, S2: AnsiString): Integer; var i:integer; begin Result:=0; if Length(S1)<Length(S2) then Result:=-1 else if Length(S1)>Length(S2) then Result:=1 else for i:=1 to Length(S1) do begin if S1[i]=S2[i] then continue else if S1[i]<S2[i] then Result:=-1 else Result:=1; exit; end; end; {$ELSE} function MyWideCompareStr(const S1, S2: UTF16String): Integer; var i:integer; begin Result:=0; if Length(S1)<Length(S2) then Result:=-1 else if Length(S1)>Length(S2) then Result:=1 else for i:=1 to Length(S1) do begin if S1[i]=S2[i] then continue else if S1[i]<S2[i] then Result:=-1 else Result:=1; exit; end; end; {$ENDIF} constructor TExcelString.Create(const aStrLenLength: TStrLenLength; var aRecord: TBaseRecord; var Ofs: integer); var StrLenByte: byte; DestPos: integer; ActualOptionFlags: byte; begin inherited Create; StrLenLength:=aStrLenLength; if StrLenLength=1 then begin ReadMem(aRecord, Ofs, StrLenLength, @StrLenByte); StrLen:=StrLenByte; end else ReadMem(aRecord, Ofs, StrLenLength, @StrLen); ReadMem(aRecord, Ofs, SizeOf(OptionFlags), @OptionFlags); ActualOptionFlags:=OptionFlags; if HasRichText then ReadMem(aRecord, Ofs, SizeOf(NumberRichTextFormats), @NumberRichTextFormats) else NumberRichTextFormats:=0; if HasFarInfo then ReadMem(aRecord, Ofs, SizeOf(FarEastDataSize), @FarEastDataSize) else FarEastDataSize:=0; DestPos:=0; SetLength( ShortData, StrLen); SetLength( WideData, StrLen); ReadStr(aRecord, Ofs, ShortData, WideData, OptionFlags, ActualOptionFlags, DestPos, StrLen); if GetCharSize=1 then WideData:='' else ShortData:=''; if NumberRichTextFormats>0 then begin GetMem(RichTextFormats, 4* NumberRichTextFormats); ReadMem(aRecord, Ofs, 4* NumberRichTextFormats, RichTextFormats) end; if FarEastDataSize>0 then begin GetMem(FarEastData, FarEastDataSize); ReadMem(aRecord, Ofs, FarEastDataSize, FarEastData) end; end; function TExcelString.Compare(const Str2: TExcelString): integer; begin if StrLenLength< Str2.StrLenLength then begin;Result:=-1;exit; end else if StrLenLength> Str2.StrLenLength then begin;Result:=1;exit; end; if OptionFlags< Str2.OptionFlags then begin; Result:=-1; exit; end else if OptionFlags> Str2.OptionFlags then begin; Result:=1; exit; end; {$IFDEF DELPHI2008UP} if GetCharSize=1 then Result:=MyShortCompareStr(ShortData, Str2.ShortData) else Result:= CompareStr(WideData, Str2.WideData); {$ELSE} if GetCharSize=1 then Result:=CompareStr(ShortData, Str2.ShortData) else Result:= MyWideCompareStr(WideData, Str2.WideData); {$ENDIF} end; constructor TExcelString.Create(const aStrLenLength: TStrLenLength; const s: UTF16String; const ForceWide: boolean); begin inherited Create; StrLenLength:=aStrLenLength; case StrLenLength of 1: if Length(s)> $FF then raise Exception.Create(ErrInvalidStringRecord); end; //case StrLen:=Length(s); OptionFlags:=0; if ForceWide or IsWide(s) then OptionFlags:=1; NumberRichTextFormats:=0; FarEastDataSize:=0; if GetCharSize= 1 then ShortData:=WideStringToStringNoCodePage(s) else WideData:=s; end; destructor TExcelString.Destroy; begin FreeMem(FarEastData); FreeMem(RichTextFormats); inherited; end; function TExcelString.GetCharSize: TCharSize; begin if OptionFlags and $1 = 0 then Result:=1 else Result:=2; end; function TExcelString.HasFarInfo: boolean; begin Result:= OptionFlags and $4 = $4; end; function TExcelString.HasRichText: boolean; begin Result:= OptionFlags and $8 = $8; end; function TExcelString.TotalSize: int64; begin Result:= StrLenLength+ SizeOf(OptionFlags)+ StrLen* GetCharSize; //Rich text if HasRichText then Result:=Result + SizeOf(NumberRichTextFormats)+ 4* NumberRichTextFormats; //FarEast if HasFarInfo then Result:=Result+ SizeOf(FarEastDataSize) + FarEastDataSize; end; procedure TExcelString.SaveToStream(const DataStream: TStream); begin SaveToStream(DataStream, true); end; procedure TExcelString.SaveToStream(const DataStream: TStream; const IncludeLen: boolean); begin if IncludeLen then begin case StrLenLength of 1: DataStream.Write(StrLen, SizeOf(Byte)); 2: DataStream.Write(StrLen, SizeOf(Word)); else raise Exception.Create(ErrInvalidStrLenLength); end; //case end; DataStream.Write(OptionFlags, SizeOf(OptionFlags)); if HasRichText then DataStream.Write(NumberRichTextFormats, SizeOf(NumberRichTextFormats)); if HasFarInfo then DataStream.Write(FarEastDataSize, SizeOf(FarEastDataSize)); if GetCharSize= 1 then if StrLen>0 then DataStream.Write(ShortData[1], Length(ShortData)) else //nothing else if StrLen>0 then DataStream.Write(WideData[1], Length(WideData)* SizeOf(UTF16Char)); if NumberRichTextFormats>0 then DataStream.Write(RichTextFormats^, 4*NumberRichTextFormats); if FarEastDataSize>0 then DataStream.Write(FarEastData^, FarEastDataSize); end; procedure TExcelString.CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer); begin CopyToPtr(Ptr, aPos, true); end; procedure TExcelString.CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer; const IncludeLen: boolean); var Ms: TMemoryStream; begin //Not the most efficient... but this way we avoid duplicating code Ms:= TMemoryStream.Create; try SaveToStream(Ms, IncludeLen); Ms.Position:=0; Ms.ReadBuffer(Ptr[aPos], Ms.Size); finally FreeAndNil(Ms); end; end; function TExcelString.GetValue: UTF16String; begin if GetCharSize=1 then Result:= StringToWideStringNoCodePage(ShortData) else Result:= WideData; end; end.
unit Marquee; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TMarquee = class(TCustomControl) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; private fMarqueeText : string; fCacheText : string; fMarqueeWidth : integer; fCacheWidth : integer; fOffset : integer; private function MatchStrings(perc : byte) : boolean; protected procedure Paint; override; procedure WMEraseBkgnd(var Message: TMessage); public procedure Tick; published { Published declarations } end; procedure Register; implementation uses MathUtils; // TMarquee constructor TMarquee.Create(AOwner: TComponent); begin inherited; Width := 200; Height := 50; end; destructor TMarquee.Destroy; begin inherited; end; function TMarquee.MatchStrings(perc : byte) : boolean; var maxLen : integer; minLen : integer; mrqLen : integer; chLen : integer; begin mrqLen := length(fMarqueeText); chLen := length(fCacheText); maxLen := max(mrqLen, chLen); minLen := min(mrqLen, chLen); result := 100*(maxLen - minLen)/maxLen >= perc; end; procedure TMarquee.Paint; begin Canvas.TextOut(fOffset, 0, fMarqueeText); end; procedure TMarquee.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TMarquee.Tick; begin if Width + fOffset = 0 then fOffset := Width else dec(fOffset, 10); // >> end; procedure Register; begin RegisterComponents('Five', [TMarquee]); end; end.
unit RemoveRouteDestinationRequestUnit; interface uses REST.Json.Types, HttpQueryMemberAttributeUnit, GenericParametersUnit; type TRemoveRouteDestinationRequest = class(TGenericParameters) private [JSONMarshalled(False)] [HttpQueryMember('route_id')] FRouteId: String; [JSONMarshalled(False)] [HttpQueryMember('route_destination_id')] FRouteDestinationId: integer; public property RouteId: String read FRouteId write FRouteId; property RouteDestinationId: integer read FRouteDestinationId write FRouteDestinationId; end; implementation end.
//////////////////////////////////////////////////////////////////////////////////// // // This component was originally developed by Sivv LLC // MemCache.pas - Delphi client for Memcached // Original Project Homepage: // http://code.google.com/p/delphimemcache // Distributed under New BSD License. // // Component was heavily redesigned and refactored. Was added new functionality. // Current author: Nick Remeslennikov // //////////////////////////////////////////////////////////////////////////////////// unit Provect.MemCache; interface uses System.SysUtils, System.Classes, System.SyncObjs, {$IF CompilerVersion > 27.0} Provect.Sockets, {$ELSE} Web.Win.Sockets, {$ENDIF} IdHashSHA; type TObjectEvent = procedure(ASender: TObject; var AObject: TObject) of object; TObjectPool = class(TObject) private FCritSec: TCriticalSection; ObjList: TList; ObjInUse: TBits; FActive: Boolean; FAutoGrow: Boolean; FStopping: Boolean; FGrowToSize: Integer; FPoolSize: Integer; FOnCreateObject: TObjectEvent; FOnDestroyObject: TObjectEvent; FUsageCount: Integer; FRaiseExceptions: Boolean; public constructor Create; virtual; destructor Destroy; override; procedure Start(ARaiseExceptions: Boolean = False); virtual; procedure Stop; virtual; function Acquire: TObject; virtual; procedure Release(AItem: TObject); virtual; property Active: boolean read FActive; property RaiseExceptions: Boolean read FRaiseExceptions write FRaiseExceptions; property UsageCount: Integer read FUsageCount; property PoolSize: Integer read FPoolSize write FPoolSize; property AutoGrow: boolean read FAutoGrow write FAutoGrow; property GrowToSize: Integer read FGrowToSize write FGrowToSize; property OnCreateObject: TObjectEvent read FOnCreateObject write FOnCreateObject; property OnDestroyObject: TObjectEvent read FOnDestroyObject write FOnDestroyObject; end; EMemCacheException = class(Exception); TConnectionPool = class(TObjectPool) public function Acquire: TTCPClient; reintroduce; procedure Release(AItem: TTCPClient); reintroduce; end; TMemCacheServer = class(TObject) private FConnections: TConnectionPool; FIP: string; FPort: Integer; public constructor Create; reintroduce; virtual; destructor Destroy; override; procedure CreateConnection(ASender: TObject; var AObject: TObject); procedure DestroyConnection(ASender: TObject; var AObject: TObject); property Connections: TConnectionPool read FConnections; property IP: string read FIP write FIP; property Port: Integer read FPort write FPort; end; TMemCacheValue = class(TObject) private FStream: TMemoryStream; FFlags: Word; FSafeToken: UInt64; FKey: string; FCommand: string; public constructor Create(ACmd: string; AData: TStream); virtual; destructor Destroy; override; function Command: string; function Value: string; function Key: string; function Stream: TStream; function Bytes: TBytes; function Flags: Word; function SafeToken: UInt64; end; TMemCache = class(TObject) private FServer: TMemCacheServer; FRegisterPosition: Integer; FFailureCheckRate: Integer; FPoolSize: Integer; protected function ToHash(const AStr: string): UInt64; virtual; function ExecuteCommand(const AKey, ACmd: string; AData: TStream = nil): string; virtual; procedure RegisterServer(const AConfigStr: string); virtual; public constructor Create(const ConfigData: string = ''); overload; destructor Destroy; override; procedure Store(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Store(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Store(const Key: string; Value: TBytes; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Append(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Append(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Prepend(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Prepend(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Replace(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Replace(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Insert(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure Insert(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure StoreSafely(const Key, Value: string; SafeToken: UInt64; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure StoreSafely(const Key: string; Value: TStream; SafeToken: UInt64; Expires: TDateTime = 0; Flags: Word = 0); overload; procedure StoreSafely(const Key: string; Value: TBytes; SafeToken: UInt64; Expires: TDateTime = 0; Flags: Word = 0); overload; function Touch(const Key: string; Expires: TDateTime = 0): Boolean; function Lookup(const Key: string; RequestSafeToken: boolean = False): TMemCacheValue; function Delete(const Key: string): boolean; function Increment(const Key: string; ByValue: Integer = 1): UInt64; function Decrement(const Key: string; ByValue: Integer = 1): UInt64; procedure ServerStatistics(AResultList: TStrings); property FailureCheckRate: Integer read FFailureCheckRate write FFailureCheckRate; // in seconds end; function MemcacheConfigFormat(ALoad: Integer; const AIP: string; APort: Integer = 11211): string; implementation uses System.DateUtils, IdGlobal, IdCoderMIME; function Encode64Stream(AStream: TStream): string; begin Result := TIdEncoderMIME.EncodeStream(AStream); end; function Encode64String(AStr: string): string; begin Result := TIdEncoderMIME.EncodeString(AStr); end; procedure Decode64(const AEncodedStr: string; ADestStream: TStream); begin TIdDecoderMIME.DecodeStream(AEncodedStr, ADestStream); end; function MemcacheConfigFormat(ALoad: Integer; const AIP: string; APort: Integer): string; begin Result := Format('%d=%s:%d', [ALoad, AIP, APort]); end; function StrToUInt64(const AString: string): UInt64; var E: Integer; begin Val(AString, Result, E); if E <> 0 then raise Exception.Create('Invalid UINT64'); end; function MemCacheTime(dt: TDateTime): string; var i: Integer; begin if dt <> 0 then begin i := SecondsBetween(Now, dt); if i >= 60 * 60 * 24 * 30 then Result := IntToStr(DateTimeToUnix(dt)) else Result := IntToStr(i); end else Result := '0'; end; function IndexOf(const AString: string; const AStrArray: array of string): Integer; var I: Integer; begin Result := -1; for I := 0 to Pred(Length(AStrArray)) do begin if AString = AStrArray[I] then begin Result := I; Break; end; end; end; { TMemCache } procedure TMemCache.Append(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'append ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Append(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'append ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(length(Value)), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; function TMemCache.Decrement(const Key: string; ByValue: Integer = 1): UInt64; var S: string; begin S := ExecuteCommand(Key, 'decr ' + Key + ' ' + IntToStr(ByValue)); if S = 'NOT_FOUND' then raise EMemCacheException.Create('The specified key does not exist.'); Result := StrToUInt64(S); end; function TMemCache.Delete(const Key: string): boolean; var S: string; begin S := ExecuteCommand(Key, 'delete ' + Key); if S = 'NOT_FOUND' then raise EMemCacheException.Create('The specified key does not exist.'); Result := S = 'DELETED'; end; destructor TMemCache.Destroy; begin FreeAndNil(FServer); inherited Destroy; end; function TMemCache.ExecuteCommand(const AKey, ACmd: string; AData: TStream): string; procedure SendCommandToServer(ATCPConn: TTCPClient; const ACommand: string; ADataStream: TStream); begin try if not ATCPConn.Connected then ATCPConn.Connect; ATCPConn.Sendln(AnsiString(ACommand)); if Assigned(ADataStream) and (ADataStream.Size > 0) then begin AData.Position := 0; ATCPConn.SendStream(ADataStream); ATCPConn.Sendln(AnsiString(EmptyStr)); end; except on E: Exception do begin FServer.Connections.Release(ATCPConn); raise; end else raise; end; end; function RecieveServerResponse(ATCPConn: TTCPClient; const ACommand: string; ADataStream: TStream): string; var TempStr: string; DelimPos: Integer; Buffer: TBytes; begin try Result := String(ATCPConn.Receiveln); if Result.Contains('VALUE') then begin TempStr := Result.Split([' '])[3]; SetLength(Buffer, StrToInt(TempStr)); AData.Position := 0; DelimPos := 0; while DelimPos <> StrToInt(TempStr) do DelimPos := DelimPos + ATCPConn.ReceiveBuf(Buffer[DelimPos], StrToInt(TempStr) - DelimPos); TMemoryStream(AData).Write(Buffer, Length(Buffer)); end; except on E: Exception do begin FServer.Connections.Release(ATCPConn); raise; end; end; end; var TCPConn: TTCPClient; ResponseString: string; IsIncDecCmd, RecieveDone: Boolean; ResultList: TArray<string>; begin Result := EmptyStr; IsIncDecCmd := (Copy(ACmd, 1, 4) = 'incr') or (Copy(ACmd, 1, 4) = 'decr'); TCPConn := FServer.Connections.Acquire; try SendCommandToServer(TCPConn, ACmd, AData); RecieveDone := False; while not RecieveDone do begin ResponseString := RecieveServerResponse(TCPConn, ACmd, AData); while not ResponseString.IsEmpty do begin ResultList := ResponseString.Split([' ']); if Length(ResultList) > 0 then begin if IndexOf(ResultList[0], ['VALUE', 'STAT']) <> -1 then begin if Result.IsEmpty then Result := ResponseString else Result := Result.Join(#13#10, [Result, ResponseString]); ResponseString := EmptyStr; Break; end else if IndexOf(ResultList[0], ['CLIENT_ERROR', 'SERVER_ERROR']) <> -1 then raise EMemCacheException.CreateFmt('Memcache Error: %s', [ResponseString]) else if (IndexOf(ResultList[0], ['END', 'DELETED', 'STORED', 'EXISTS', 'NOT_STORED', 'NOT_FOUND', 'ERROR', 'TOUCHED']) <> -1) or IsIncDecCmd then begin if Result.IsEmpty then Result := ResponseString else Result := Result.Join(#13#10, [Result, ResponseString]); ResponseString := EmptyStr; RecieveDone := True; end; end; end; end; finally FServer.Connections.Release(TCPConn); end; end; function TMemCache.Increment(const Key: string; ByValue: Integer = 1): UInt64; var S: string; begin S := ExecuteCommand(Key, 'incr ' + Key + ' ' + IntToStr(ByValue)); if S = 'NOT_FOUND' then raise EMemCacheException.Create('The specified key does not exist.'); Result := StrToUInt64(TrimRight(S)); end; procedure TMemCache.Insert(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'add ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Insert(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'add ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(length(Value)), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; function TMemCache.Lookup(const Key: string; RequestSafeToken: boolean = False): TMemCacheValue; var Data: TMemoryStream; ExecResult: string; begin Data := TMemoryStream.Create; try if RequestSafeToken then ExecResult := ExecuteCommand(Key, 'gets ' + Key, Data) else ExecResult := ExecuteCommand(Key, 'get ' + Key, Data); Result := TMemCacheValue.Create(ExecResult, Data); finally FreeAndNil(Data); end; end; procedure TMemCache.Prepend(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'prepend ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Prepend(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'prepend ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(length(Value)), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Replace(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'replace ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(length(Value)), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.RegisterServer(const AConfigStr: string); var DelimPos: Integer; begin if AConfigStr <> '' then begin DelimPos := Pos(':', AConfigStr); if DelimPos > 0 then begin FServer.IP := Copy(AConfigStr, 1, DelimPos - 1); FServer.Port := StrToInt(Copy(AConfigStr, DelimPos + 1, MaxInt)); end else FServer.IP := AConfigStr; end; FServer.Connections.PoolSize := FPoolSize; FServer.Connections.Start(True); end; procedure TMemCache.Replace(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'replace ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Store(const Key, Value: string; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'set ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(data.Size), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.ServerStatistics(AResultList: TStrings); var ExecResult: string; begin ExecResult := ExecuteCommand(EmptyStr, 'stats'); AResultList.Clear; while True do begin if Pos(#13#10, ExecResult) <> 0 then begin AResultList.Add(Copy(ExecResult, 1, Pos(#13#10, ExecResult) - 1)); System.Delete(ExecResult, 1, Pos(#13#10, ExecResult) + 1); end else Break; end; end; procedure TMemCache.Store(const Key: string; Value: TStream; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'set ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.StoreSafely(const Key, Value: string; SafeToken: UInt64; Expires: TDateTime = 0; Flags: Word = 0); var S: string; data: TStringStream; begin data := TStringStream.Create(Value); try data.Position := 0; S := ExecuteCommand(Key, 'cas ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(length(Value)) + ' ' + IntToStr(SafeToken), data); finally FreeAndNil(data); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.Store(const Key: string; Value: TBytes; Expires: TDateTime; Flags: Word); var S: string; Strm: TMemoryStream; begin Strm := TMemoryStream.Create; try Strm.WriteBuffer(Value[0], Length(Value)); Strm.Position := 0; S := ExecuteCommand(Key, 'set ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Strm.Size), Strm); finally FreeAndNil(Strm); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.StoreSafely(const Key: string; Value: TBytes; SafeToken: UInt64; Expires: TDateTime; Flags: Word); var S: string; Strm: TStream; begin Strm := TStream.Create; try Strm.WriteBuffer(Value[0], Length(Value)); Strm.Position := 0; S := ExecuteCommand(Key, 'cas ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Strm.Size) + ' ' + UIntToStr(SafeToken), Strm); finally FreeAndNil(Strm); end; if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; procedure TMemCache.StoreSafely(const Key: string; Value: TStream; SafeToken: UInt64; Expires: TDateTime = 0; Flags: Word = 0); var S: string; begin S := ExecuteCommand(Key, 'cas ' + Key + ' ' + IntToStr(Flags) + ' ' + MemCacheTime(Expires) + ' ' + IntToStr(Value.Size) + ' ' + UIntToStr(SafeToken), Value); if S <> 'STORED' then raise EMemCacheException.Create('Error storing Value: ' + S); end; constructor TMemCache.Create(const ConfigData: string); begin inherited Create; FPoolSize := 1; FRegisterPosition := 0; FFailureCheckRate := 30; FServer := TMemCacheServer.Create; RegisterServer(ConfigData); end; function TMemCache.ToHash(const AStr: string): UInt64; function HexToInt64(const AHex: string): UInt64; const HexValues = '0123456789ABCDEF'; var I: Integer; begin Result := 0; case length(AHex) of 0: Result := 0; 1 .. 16: for I := 1 to Length(AHex) do Result := 16 * Result + Pos(Upcase(AHex[I]), HexValues) - 1; else for I := 1 to 16 do Result := 16 * Result + Pos(Upcase(AHex[I]), HexValues) - 1; end; end; var Hash: TIdHashSHA1; begin Hash := TIdHashSHA1.Create; try Result := HexToInt64(Copy(Hash.HashStringAsHex(AStr), 1, 8)); finally FreeAndNil(Hash); end; end; function TMemCache.Touch(const Key: string; Expires: TDateTime): Boolean; var S: string; begin S := ExecuteCommand(Key, 'touch ' + Key + ' ' + MemCacheTime(Expires)); Result := S = 'TOUCHED'; end; { TMemCacheValue } function TMemCacheValue.Bytes: TBytes; begin SetLength(Result, 0); if Assigned(FStream) and (FStream.Size > 0) then begin SetLength(Result, FStream.Size); FStream.Position := 0; FStream.ReadBuffer(Result[0], FStream.Size); FStream.Position := 0; end; end; function TMemCacheValue.Command: string; begin Result := FCommand; end; constructor TMemCacheValue.Create(ACmd: string; AData: TStream); function NextField(var AStr: string): string; var I: Integer; IsSingleLine: Boolean; begin Result := EmptyStr; IsSingleLine := False; for I := 1 to Length(AStr) do begin case AStr[I] of ' ', #13: begin Result := Copy(AStr, 1, I - 1); if AStr[I] = #13 then Delete(AStr, 1, I - 1) else Delete(AStr, 1, I); IsSingleLine := True; Break; end; end; end; if not IsSingleLine and not Result.IsEmpty and not AStr.IsEmpty then begin Result := AStr; AStr := EmptyStr; end; end; var SingleLine: string; DataSize: Integer; begin inherited Create; FStream := TMemoryStream.Create; if ACmd = 'END' then begin FCommand := ACmd; FKey := EmptyStr; FFlags := 0; FSafeToken := 0; FStream.Size := 0; end else begin FCommand := NextField(ACmd); FKey := NextField(ACmd); FFlags := StrToIntDef(NextField(ACmd), 0); DataSize := StrToIntDef(NextField(ACmd), 0); SingleLine := NextField(ACmd); if not SingleLine.IsEmpty then FSafeToken := StrToUInt64(SingleLine) else FSafeToken := 0; AData.Position := 0; FStream.CopyFrom(AData, DataSize); FStream.Position := 0; end; end; destructor TMemCacheValue.Destroy; begin FStream.Free; inherited; end; function TMemCacheValue.Flags: Word; begin Result := FFlags; end; function TMemCacheValue.Key: string; begin Result := FKey; end; function TMemCacheValue.SafeToken: UInt64; begin Result := FSafeToken; end; function TMemCacheValue.Stream: TStream; begin Result := FStream; end; function TMemCacheValue.Value: string; begin SetString(Result, PAnsiChar(FStream.Memory), FStream.Size); end; { TMemCacheServer } constructor TMemCacheServer.Create; begin inherited Create; FPort := 11211; FIP := '127.0.0.1'; FConnections := TConnectionPool.Create; FConnections.OnCreateObject := Self.CreateConnection; FConnections.OnDestroyObject := Self.DestroyConnection; end; procedure TMemCacheServer.CreateConnection(ASender: TObject; var AObject: TObject); var TCPConn: TTCPClient; begin TCPConn := TTCPClient.Create(nil); try TCPConn.RemoteHost := AnsiString(IP); TCPConn.RemotePort := AnsiString(IntToStr(Port)); TCPConn.Connect; except FreeAndNil(TCPConn); raise; end; AObject := TCPConn; end; destructor TMemCacheServer.Destroy; begin FreeAndNil(FConnections); inherited Destroy; end; procedure TMemCacheServer.DestroyConnection(ASender: TObject; var AObject: TObject); begin FreeAndNil(AObject); end; { TConnectionPool } function TConnectionPool.Acquire: TTCPClient; begin Result := TTCPClient(inherited Acquire); end; procedure TConnectionPool.Release(AItem: TTCPClient); begin inherited Release(AItem); end; { TObjectPool } function TObjectPool.Acquire: TObject; var ConnectionIdx: Integer; begin Result := nil; if not FActive then begin if FRaiseExceptions then raise EAbort.Create('Cannot acquire an object before calling Start') else exit; end; FCritSec.Enter; try Inc(FUsageCount); ConnectionIdx := ObjInUse.OpenBit; if ConnectionIdx < FPoolSize then // idx = FPoolSize when there are no openbits begin Result := TObject(ObjList[ConnectionIdx]); ObjInUse[ConnectionIdx] := True; end else begin // Handle the case where the pool is completely acquired. if not AutoGrow or (FPoolSize > FGrowToSize) then begin if FRaiseExceptions then raise Exception.Create('There are no available objects in the pool') else exit; end; Inc(FPoolSize); ObjInUse.Size := FPoolSize; FOnCreateObject(Self, Result); ObjList.Add(Result); ObjInUse[FPoolSize - 1] := True; end; finally FCritSec.Leave; end; end; constructor TObjectPool.Create; begin FCritSec := TCriticalSection.Create; ObjList := TList.Create; ObjInUse := TBits.Create; FActive := False; FAutoGrow := True; FGrowToSize := 1000; FPoolSize := 20; FRaiseExceptions := True; FOnCreateObject := nil; FOnDestroyObject := nil; FStopping := False; end; destructor TObjectPool.Destroy; begin if FActive then Stop; FreeAndNil(FCritSec); ObjList.Free; ObjInUse.Free; inherited Destroy; end; procedure TObjectPool.Release(AItem: TObject); var Idx: Integer; begin if (not FStopping) and (not FActive) then begin if FRaiseExceptions then raise Exception.Create('Cannot release an object before calling Start') else Exit; end; if AItem = nil then begin if FRaiseExceptions then raise Exception.Create('Cannot release an object before calling Start') else Exit; end; FCritSec.Enter; try Idx := ObjList.IndexOf(AItem); if Idx < 0 then begin if FRaiseExceptions then raise Exception.Create('Cannot release an object that is not in the pool') else Exit; end; ObjInUse[Idx] := False; Dec(FUsageCount); finally FCritSec.Leave; end; end; procedure TObjectPool.Start(ARaiseExceptions: Boolean = False); var I: Integer; TmpObject: TObject; begin // Make sure events are assigned before starting the pool. if not Assigned(FOnCreateObject) then raise Exception.Create('There must be an OnCreateObject event before calling Start'); if not Assigned(FOnDestroyObject) then raise Exception.Create('There must be an OnDestroyObject event before calling Start'); // Set the TBits class to the same size as the pool. ObjInUse.Size := FPoolSize; // Call the OnCreateObject event once for each item in the pool. for I := 0 to FPoolSize - 1 do begin TmpObject := nil; FOnCreateObject(Self, TmpObject); ObjList.Add(TmpObject); ObjInUse[I] := False; end; // Set the active flag to true so that the Acquire method will return Values. FActive := True; // Automatically set RaiseExceptions to false by default. This keeps // exceptions from being raised in threads. FRaiseExceptions := ARaiseExceptions; end; procedure TObjectPool.Stop; var I: Integer; TmpObject: TObject; begin // Wait until all objects have been released from the pool. After waiting // 10 seconds, stop anyway. This may cause unforseen problems, but usually // you only Stop a pool as the application is stopping. 40 x 250 = 10,000 for I := 1 to 40 do begin FCritSec.Enter; try // Setting Active to false here keeps the Acquire method from continuing to // retrieve objects. FStopping := True; FActive := False; if FUsageCount = 0 then break; finally FCritSec.Leave; end; // Sleep here to allow give threads time to release their objects. Sleep(250); end; FCritSec.Enter; try // Loop through all items in the pool calling the OnDestroyObject event. for I := 0 to FPoolSize - 1 do begin TmpObject := TObject(ObjList[I]); if Assigned(FOnDestroyObject) then FOnDestroyObject(Self, TmpObject) else TmpObject.Free; end; // clear the memory used by the list object and TBits class. ObjList.Clear; ObjInUse.Size := 0; FRaiseExceptions := True; finally FCritSec.Leave; FStopping := False; end; end; end.
unit f2SettingsStorage; { $Id: f2SettingsStorage.pas,v 1.1 2017/06/28 18:42:15 Антон Exp $ } interface uses d2dClasses, JclStringLists; type Tf2SettingsStorage = class(Td2dProtoObject) private f_Data: IJclStringList; f_DataFN: AnsiString; procedure LoadDataFile; function pm_GetData(aName: AnsiString): Variant; procedure pm_SetData(aName: AnsiString; const Value: Variant); procedure SaveDataFile; property Data[aName: AnsiString]: Variant read pm_GetData write pm_SetData; default; protected procedure Cleanup; override; public constructor Create(const aDataFN: AnsiString); procedure Clear; function IsVarExists(const aName: AnsiString): Boolean; end; implementation uses Classes, SysUtils, furqFiler, d2dUtils; const cSSSignature = 'FURQSS'; cSSVersion = 1; constructor Tf2SettingsStorage.Create(const aDataFN: AnsiString); begin inherited Create; f_DataFN := aDataFN; f_Data := JclStringList; f_Data.Sorted := True; f_Data.CaseSensitive := False; if FileExists(f_DataFN) then LoadDataFile; end; procedure Tf2SettingsStorage.Cleanup; begin f_Data := nil; inherited; end; procedure Tf2SettingsStorage.Clear; begin f_Data.Clear; DeleteFile(f_DataFN); end; function Tf2SettingsStorage.IsVarExists(const aName: AnsiString): Boolean; begin Result := f_Data.IndexOf(aName) >= 0; end; procedure Tf2SettingsStorage.LoadDataFile; var I: Integer; l_Count: Integer; l_Filer: TFURQFiler; l_FS: TFileStream; l_Idx: Integer; begin f_Data.Clear; l_FS := TFileStream.Create(f_DataFN, fmOpenRead); try l_Filer := TFURQFiler.Create(l_FS); try if (l_Filer.ReadString <> cSSSignature) or (l_Filer.ReadByte <> cSSVersion) then Exit; l_Count := l_Filer.ReadInteger; for I := 1 to l_Count do begin l_Idx := f_Data.Add(l_Filer.ReadString); f_Data.Variants[l_Idx] := l_Filer.ReadVarValue; end; finally FreeAndNil(l_Filer); end; finally FreeAndNil(l_FS); end; end; function Tf2SettingsStorage.pm_GetData(aName: AnsiString): Variant; var l_Idx: Integer; begin l_Idx := f_Data.IndexOf(aName); if l_Idx < 0 then Result := 0.0 else Result := f_Data.Variants[l_Idx]; end; procedure Tf2SettingsStorage.pm_SetData(aName: AnsiString; const Value: Variant); var l_Idx: Integer; begin l_Idx := f_Data.IndexOf(aName); if l_Idx < 0 then l_Idx := f_Data.Add(aName); f_Data.Variants[l_Idx] := Value; SaveDataFile; end; procedure Tf2SettingsStorage.SaveDataFile; var I: Integer; l_FS: TFileStream; l_Filer: TFURQFiler; begin l_FS := TFileStream.Create(f_DataFN, fmCreate); try l_Filer := TFURQFiler.Create(l_FS); try l_Filer.WriteString(cSSSignature); l_Filer.WriteByte(cSSVersion); l_Filer.WriteInteger(f_Data.Count); for I := 0 to f_Data.LastIndex do begin l_Filer.WriteString(f_Data.Strings[I]); l_Filer.WriteVarValue(f_Data.Variants[I]); end; finally FreeAndNil(l_Filer); end; finally FreeAndNil(l_FS); end; end; end.
unit MFichas.Model.Pagamento.Formas.Credito; interface uses System.SysUtils, MFichas.Model.Pagamento.Interfaces, MFichas.Model.Pagamento.Formas.Credito.Processar; type TModelPagamentoFormasCredito = class(TInterfacedObject, iModelPagamentoMetodos) private [weak] FParent: iModelPagamento; constructor Create(AParent: iModelPagamento); public destructor Destroy; override; class function New(AParent: iModelPagamento): iModelPagamentoMetodos; function Processar: iModelPagamentoMetodosProcessar; function Estornar : iModelPagamentoMetodosEstornar; function &End : iModelPagamento; end; implementation { TModelPagamentoFormasCredito } function TModelPagamentoFormasCredito.&End: iModelPagamento; begin Result := FParent; end; constructor TModelPagamentoFormasCredito.Create(AParent: iModelPagamento); begin FParent := AParent; end; destructor TModelPagamentoFormasCredito.Destroy; begin inherited; end; function TModelPagamentoFormasCredito.Estornar: iModelPagamentoMetodosEstornar; begin raise Exception.Create( 'Este método de pagamento ainda não está validado no sistema.' + sLineBreak + 'Por favor, utilize outro método.' ); end; class function TModelPagamentoFormasCredito.New(AParent: iModelPagamento): iModelPagamentoMetodos; begin Result := Self.Create(AParent); end; function TModelPagamentoFormasCredito.Processar: iModelPagamentoMetodosProcessar; begin Result := TModelPagamentoFormasCreditoProcessar.New(FParent); end; end.
unit FIFO; interface uses Classes, SyncObjs; type TFIFO = class public constructor Create; destructor Destroy; override; public procedure Write(const Data; aSize : integer); function Read(var Data; aSize : integer) : integer; function Peek(var Data; aSize : integer) : integer; function Advance(aSize : integer) : integer; public procedure Clear; private fBlocks : TList; fSize : integer; fWPos : integer; fRPos : integer; fLock : TCriticalSection; function GetSize : integer; public property Size : integer read GetSize; end; implementation uses SysUtils; const BlockSize = 4096; function Min(a, b : integer) : integer; register; begin if a < b then Result := a else Result := b; end; constructor TFIFO.Create; begin fBlocks := TList.Create; fLock := TCriticalSection.Create; end; destructor TFIFO.Destroy; begin Clear; fBlocks.Free; fLock.Free; end; procedure TFIFO.Write(const Data; aSize : integer); function GetWBlock : pointer; begin if (fBlocks.Count > 0) and (fWPos < BlockSize) then Result := fBlocks.Last else begin getmem(Result, BlockSize); fBlocks.Add(Result); fWPos := 0; end; end; var ptr : pointer; Left : integer; ToWrite : integer; begin fLock.Enter; try Left := aSize; while Left > 0 do begin ptr := GetWBlock; ToWrite := min(BlockSize - fWPos, Left); move(TByteArray(Data)[aSize - Left], PByteArray(ptr)[fWPos], ToWrite); inc(fWPos, ToWrite); dec(Left, ToWrite); end; inc(fSize, aSize); finally fLock.Leave; end; end; function TFIFO.Read(var Data; aSize : integer) : integer; begin fLock.Enter; try Result := Peek(Data, aSize); Advance(Result); finally fLock.Leave; end; end; function TFIFO.Peek(var Data; aSize : integer) : integer; var TempBlockPos : integer; TempSize : integer; CurrentBlock : integer; SizeLeft : integer; ToFeed : integer; begin fLock.Enter; try SizeLeft := aSize; TempBlockPos := fRPos; TempSize := fSize; CurrentBlock := 0; while (SizeLeft > 0) and (TempSize > 0) do begin if TempBlockPos = BlockSize then begin TempBlockPos := 0; inc(CurrentBlock); end; if CurrentBlock < pred(fBlocks.Count) then ToFeed := Min(BlockSize - TempBlockPos, SizeLeft) else ToFeed := Min(fWPos - TempBlockPos, SizeLeft); move(PByteArray(fBlocks[CurrentBlock])[TempBlockPos], PByteArray(@Data)[aSize - SizeLeft], ToFeed); dec(SizeLeft, ToFeed); inc(TempBlockPos, ToFeed); dec(TempSize, ToFeed); end; Result := aSize - SizeLeft; finally fLock.Leave; end; end; function TFIFO.Advance(aSize : integer) : integer; var ToFeed : integer; SizeLeft : integer; begin fLock.Enter; try SizeLeft := aSize; while (SizeLeft > 0) and (fSize > 0) do begin if fRPos = BlockSize then begin fRPos := 0; freemem(fBlocks[0]); fBlocks.Delete(0); end; if fBlocks.Count = 1 then ToFeed := Min(fWPos - fRPos, SizeLeft) else ToFeed := Min(BlockSize - fRPos, SizeLeft); inc(fRPos, ToFeed); dec(SizeLeft, ToFeed); dec(fSize, ToFeed); end; Result := aSize - SizeLeft; finally fLock.Leave; end; end; procedure TFIFO.Clear; var i : integer; begin fLock.Enter; try for i := 0 to pred(fBlocks.Count) do freemem(fBlocks[i]); fBlocks.Clear; fRPos := 0; fWPos := 0; fSize := 0; finally fLock.Leave; end; end; function TFIFO.GetSize : integer; begin fLock.Enter; try Result := fSize; finally fLock.Leave; end; end; end.
unit UMultipeer; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUIButton, FMX.TMSNativeUITextField, FMX.TMSNativeUIView, FMX.TMSNativeUITabBarController, FMX.TMSNativeUIBaseControl, FMX.TMSNativeMultipeerConnectivity, IOUtils, FMX.TMSNativeUITableView, iOSApi.UIKit, FMX.TMSNativeUILabel, FMX.TMSNativeUICore; type TSendMode = (smMessage, smMyInfo, smNone); TMyInfo = class(TComponent) private FEmail: String; FLastName: String; FCompany: String; FPhone: String; FFirstName: String; public constructor Create(AFirstName, ALastName, AEmail, ACompany, APhone: String); reintroduce; overload; constructor Create; reintroduce; overload; published property FirstName: String read FFirstName write FFirstName; property LastName: String read FLastName write FLastName; property Email: String read FEmail write FEmail; property Company: String read FCompany write FCompany; property Phone: String read FPhone write FPhone; end; TForm1175 = class(TForm) TMSFMXNativeMultipeerConnectivity1: TTMSFMXNativeMultipeerConnectivity; TMSFMXNativeUITabBarController1: TTMSFMXNativeUITabBarController; TMSFMXNativeUITabBarItem1: TTMSFMXNativeUITabBarItem; TMSFMXNativeUITabBarItem2: TTMSFMXNativeUITabBarItem; TMSFMXNativeUITabBarItem3: TTMSFMXNativeUITabBarItem; TMSFMXNativeUITextField1: TTMSFMXNativeUITextField; TMSFMXNativeUIView1: TTMSFMXNativeUIView; TMSFMXNativeUIButton1: TTMSFMXNativeUIButton; TMSFMXNativeUITableView1: TTMSFMXNativeUITableView; TMSFMXNativeUILabel1: TTMSFMXNativeUILabel; TMSFMXNativeUITextField2: TTMSFMXNativeUITextField; TMSFMXNativeUILabel2: TTMSFMXNativeUILabel; TMSFMXNativeUITextField3: TTMSFMXNativeUITextField; TMSFMXNativeUILabel3: TTMSFMXNativeUILabel; TMSFMXNativeUITextField4: TTMSFMXNativeUITextField; TMSFMXNativeUILabel4: TTMSFMXNativeUILabel; TMSFMXNativeUITextField5: TTMSFMXNativeUITextField; TMSFMXNativeUILabel5: TTMSFMXNativeUILabel; TMSFMXNativeUITextField6: TTMSFMXNativeUITextField; TMSFMXNativeUIButton2: TTMSFMXNativeUIButton; TMSFMXNativeUITextField7: TTMSFMXNativeUITextField; TMSFMXNativeUILabel6: TTMSFMXNativeUILabel; TMSFMXNativeUILabel7: TTMSFMXNativeUILabel; TMSFMXNativeUITextField8: TTMSFMXNativeUITextField; TMSFMXNativeUITextField9: TTMSFMXNativeUITextField; TMSFMXNativeUILabel8: TTMSFMXNativeUILabel; TMSFMXNativeUILabel9: TTMSFMXNativeUILabel; TMSFMXNativeUITextField10: TTMSFMXNativeUITextField; TMSFMXNativeUITextField11: TTMSFMXNativeUITextField; TMSFMXNativeUILabel10: TTMSFMXNativeUILabel; procedure TMSFMXNativeUIButton1Click(Sender: TObject); procedure TMSFMXNativeMultipeerConnectivity1BrowserViewControllerDidFinish( Sender: TObject); procedure FormCreate(Sender: TObject); procedure TMSFMXNativeMultipeerConnectivity1DidReceiveString( Sender: TObject; AValue: string; APeer: TTMSFMXNativeMultipeerConnectivityPeer); procedure TMSFMXNativeUITableView1GetItemStyle(Sender: TObject; ASection, ARow: Integer; var AStyle: TTMSFMXNativeUITableViewItemStyle); procedure TMSFMXNativeUIButton2Click(Sender: TObject); procedure TMSFMXNativeMultipeerConnectivity1DidReceiveObject( Sender: TObject; AValue: TMemoryStream; APeer: TTMSFMXNativeMultipeerConnectivityPeer); procedure TMSFMXNativeUITextField2Changed(Sender: TObject); procedure TMSFMXNativeMultipeerConnectivity1DidChangeState(Sender: TObject; APeer: TTMSFMXNativeMultipeerConnectivityPeer; AState: TTMSFMXNativeMultipeerConnectivitySessionState); private { Private declarations } FSendMode: TSendMode; procedure CustomizeCell(Sender: TObject; ACell: UITableViewCell; AItemStyle: TTMSFMXNativeUITableViewItemStyle; ASection, ARow: Integer); procedure SendMessage; procedure SendMyInfo; procedure ReceiveFriendsInfo(AValue: TMemoryStream); procedure SaveMyInfo; procedure LoadMyInfo; procedure ReceiveMessage(APeer: TTMSFMXNativeMultipeerConnectivityPeer; AMessage: String); public { Public declarations } end; var Form1175: TForm1175; implementation {$R *.fmx} procedure ShowMessageEx(AMessage: String); var al: UIAlertView; begin al := TUIAlertView.Wrap(TUIAlertView.Wrap(TUIAlertView.OCClass.alloc).initWithTitle(NSStrEx(''), NSStrEx(AMessage), nil, NSStrEx('OK'), nil)); al.show; al.release; end; procedure TForm1175.CustomizeCell(Sender: TObject; ACell: UITableViewCell; AItemStyle: TTMSFMXNativeUITableViewItemStyle; ASection, ARow: Integer); begin if Assigned(ACell) then begin if TMSFMXNativeUITableView1.Sections[ASection].Items[ARow].Tag = 0 then begin ACell.textLabel.setTextAlignment(UITextAlignmentLeft); ACell.textLabel.setTextColor(TUIColor.Wrap(TUIColor.OCClass.greenColor)); end; if TMSFMXNativeUITableView1.Sections[ASection].Items[ARow].Tag = 1 then begin ACell.textLabel.setTextAlignment(UITextAlignmentRight); ACell.textLabel.setTextColor(TUIColor.Wrap(TUIColor.OCClass.redColor)); end; end; end; procedure TForm1175.FormCreate(Sender: TObject); begin TMSFMXNativeMultipeerConnectivity1.MaximumNumberOfPeers := 2; TMSFMXNativeUITableView1.OnItemCustomizeCell := CustomizeCell; LoadMyInfo; end; procedure TForm1175.LoadMyInfo; var sf: TStringList; begin if not TFile.Exists(TPath.GetDocumentsPath + '/MyInfo.txt') then begin TMSFMXNativeUITextField2.Text := 'tms'; TMSFMXNativeUITextField3.Text := 'software'; TMSFMXNativeUITextField4.Text := 'info@tmssoftware.com'; TMSFMXNativeUITextField5.Text := 'tmssoftware.com'; TMSFMXNativeUITextField6.Text := '0123456789'; Exit; end; sf := nil; try sf := TStringList.Create; sf.LoadFromFile(TPath.GetDocumentsPath + '/MyInfo.txt'); if sf.Count = 5 then begin TMSFMXNativeUITextField2.Text := sf[0]; TMSFMXNativeUITextField3.Text := sf[1]; TMSFMXNativeUITextField4.Text := sf[2]; TMSFMXNativeUITextField5.Text := sf[3]; TMSFMXNativeUITextField6.Text := sf[4]; end; finally if Assigned(sf) then sf.Free; end; end; procedure TForm1175.ReceiveMessage( APeer: TTMSFMXNativeMultipeerConnectivityPeer; AMessage: String); var it: TTMSFMXNativeUITableViewItem; begin it := TMSFMXNativeUITableView1.Sections[0].Items.Add; it.Text := APeer.DisplayName + ': ' + AMessage; it.Tag := 1; end; procedure TForm1175.ReceiveFriendsInfo(AValue: TMemoryStream); var c: TMyInfo; begin if not Assigned(AValue) then Exit; try c := TMyInfo.Create; AValue.ReadComponent(c); TMSFMXNativeUITextField7.Text := c.Phone; TMSFMXNativeUITextField8.Text := c.Company; TMSFMXNativeUITextField9.Text := c.Email; TMSFMXNativeUITextField10.Text := c.LastName; TMSFMXNativeUITextField11.Text := c.FirstName; ShowMessageEx('Friends card info received'); TMSFMXNativeUITabBarController1.SelectedItemIndex := 1 finally if Assigned(c) then c.Free; end; end; procedure TForm1175.SaveMyInfo; var sf: TStringList; begin sf := nil; try sf := TStringList.Create; sf.Add(TMSFMXNativeUITextField2.Text); sf.Add(TMSFMXNativeUITextField3.Text); sf.Add(TMSFMXNativeUITextField4.Text); sf.Add(TMSFMXNativeUITextField5.Text); sf.Add(TMSFMXNativeUITextField6.Text); sf.SaveToFile(TPath.GetDocumentsPath + '/MyInfo.txt'); finally if Assigned(sf) then sf.Free; end; end; procedure TForm1175.SendMessage; var it: TTMSFMXNativeUITableViewItem; begin if TMSFMXNativeUITextField1.Text <> '' then begin TMSFMXNativeMultipeerConnectivity1.SendStringToAllPeers(TMSFMXNativeUITextField1.Text); it := TMSFMXNativeUITableView1.Sections[0].Items.Add; it.Text := UTF8ToString(TMSFMXNativeMultipeerConnectivity1.PeerID.displayName.UTF8String) + ': ' + TMSFMXNativeUITextField1.Text; it.Tag := 0; TMSFMXNativeUITextField1.Text := ''; end; end; procedure TForm1175.SendMyInfo; var c: TMyInfo; ms: TMemoryStream; begin try c := TMyInfo.Create(TMSFMXNativeUITextField2.Text, TMSFMXNativeUITextField3.Text, TMSFMXNativeUITextField4.Text, TMSFMXNativeUITextField5.Text, TMSFMXNativeUITextField6.Text); ms := TMemoryStream.Create; ms.WriteComponent(c); TMSFMXNativeMultipeerConnectivity1.SendObjectToAllPeers(ms); ShowMessageEx('My card info sent'); finally if Assigned(ms) then ms.Free; if Assigned(c) then c.Free; end; end; procedure TForm1175.TMSFMXNativeMultipeerConnectivity1BrowserViewControllerDidFinish( Sender: TObject); begin case FSendMode of smMessage: SendMessage; smMyInfo: SendMyInfo; end; FSendMode := smNone; end; procedure TForm1175.TMSFMXNativeMultipeerConnectivity1DidChangeState( Sender: TObject; APeer: TTMSFMXNativeMultipeerConnectivityPeer; AState: TTMSFMXNativeMultipeerConnectivitySessionState); begin case AState of ssSessionStateNotConnected: ShowMessageEx('Connection to ' + APeer.DisplayName + ' is lost'); end; end; procedure TForm1175.TMSFMXNativeMultipeerConnectivity1DidReceiveObject( Sender: TObject; AValue: TMemoryStream; APeer: TTMSFMXNativeMultipeerConnectivityPeer); begin ReceiveFriendsInfo(AValue); end; procedure TForm1175.TMSFMXNativeMultipeerConnectivity1DidReceiveString( Sender: TObject; AValue: string; APeer: TTMSFMXNativeMultipeerConnectivityPeer); begin ReceiveMessage(APeer, AValue); end; procedure TForm1175.TMSFMXNativeUIButton1Click(Sender: TObject); begin if TMSFMXNativeMultipeerConnectivity1.PeerCount = 0 then begin FSendMode := smMessage; TMSFMXNativeMultipeerConnectivity1.SearchForPeers; end else SendMessage; end; procedure TForm1175.TMSFMXNativeUIButton2Click(Sender: TObject); begin if TMSFMXNativeMultipeerConnectivity1.PeerCount = 0 then begin FSendMode := smMyInfo; TMSFMXNativeMultipeerConnectivity1.SearchForPeers; end else SendMyInfo; end; procedure TForm1175.TMSFMXNativeUITableView1GetItemStyle(Sender: TObject; ASection, ARow: Integer; var AStyle: TTMSFMXNativeUITableViewItemStyle); begin AStyle := isTableViewCellStyleDefault; end; procedure TForm1175.TMSFMXNativeUITextField2Changed(Sender: TObject); begin SaveMyInfo; end; { TMyInfo } constructor TMyInfo.Create(AFirstName, ALastName, AEmail, ACompany, APhone: String); begin inherited Create(nil); FFirstName := AFirstName; FLastName := ALastName; FEmail := AEmail; FCompany := ACompany; FPhone := APhone; end; constructor TMyInfo.Create; begin inherited Create(nil); end; end.
{ Subroutine SST_DTYPE_RESOLVE (DTYPE, DTYPE_BASE_P, DTYPE_BASE) * * Resolve the base data type implied by the data type descriptor DTYPE. * DTYPE_BASE_P will be pointing to the first data type descriptor that * is not a copy, which could be DTYPE directly. DTYPE_BASE further * indicates the raw data type ID of the root data type. DTYPE_BASE * differs from DTYPE_BASE_P^.DT if the base data type is a subrange. * In that case DTYPE_BASE is the data type ID of the root data type * the subrange is formed from. Therefore DTYPE_BASE will never indicate * COPY or SUBRANGE, while DTYPE_BASE_P may point to a subrange data type * descriptor. } module sst_DTYPE_RESOLVE; define sst_dtype_resolve; %include 'sst2.ins.pas'; procedure sst_dtype_resolve ( {resolve arbitrary data type to base dtype} in dtype: sst_dtype_t; {descriptor for data type to resolve} out dtype_base_p: sst_dtype_p_t; {points to base data type descriptor} out dtype_base: sst_dtype_k_t); {resolved base data type} var dt_p: sst_dtype_p_t; {scratch data type descriptor pointer} begin dtype_base_p := addr(dtype); {init root dtype pointer to starting dtype} while dtype_base_p^.dtype = sst_dtype_copy_k do begin {resolve nested "copy" types} dtype_base_p := dtype_base_p^.copy_dtype_p; {resolve one layer of "copy"} end; {back and check new data type} dt_p := dtype_base_p; {init dtype descriptor originating DTYPE_BASE} dtype_base := dt_p^.dtype; {init root data type ID} while dtype_base = sst_dtype_range_k do begin {root data type is SUBRANGE ?} dt_p := dt_p^.range_dtype_p; {point to base dtype descriptor of subrange} while dt_p^.dtype = sst_dtype_copy_k do begin {resolve nested "copy" types} dt_p := dt_p^.copy_dtype_p; end; {back and resolve next copy} dtype_base := dt_p^.dtype; {get new root data type ID} end; {back to retry with new root data type desc} end;
unit Model.TabelasDistribuicao; interface type TTabelasDistribuicao = class private var FID: System.Integer; FData: System.TDate; FTabela: System.Integer; FGrupo: System.Integer; FTipo: System.Integer; FEntregador: System.Integer; FLog: system.String; public property ID: System.Integer read FID write FID; property Data: System.TDate read FDATA write FData; property Tabela: System.Integer read FTabela write FTabela; property Grupo: System.Integer read FGrupo write FGrupo; property Tipo: System.Integer read FTipo write FTipo; property Entregador: System.Integer read FEntregador write FEntregador; property Log: System.string read FLog write FLog; constructor Create; overload; constructor Create(pFID: System.Integer; pFData: System.TDate; pFTabela: System.Integer; pFGrupo: System.Integer; pFTipo: System.Integer; pFEntregador: System.Integer; pFLog: System.string); overload; end; implementation constructor TTabelasDistribuicao.Create; begin inherited Create; end; constructor TTabelasDistribuicao.Create(pFID: Integer; pFData: TDate; pFTabela: Integer; pFGrupo: Integer; pFTipo: Integer; pFEntregador: Integer; pFLog: string); begin FID := pFID; FData := pFData; FTabela := pFTabela; FGrupo := pFGrupo; FTipo := pFTipo; FEntregador := pFEntregador; FLog := pFLog; end; end.
unit DirServerSession; interface type IDirServerSession = interface procedure EndSession; function GetCurrentKey : widestring ; function SetCurrentKey( FullPathKey : widestring ) : olevariant; function CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; function CreateKey ( KeyName : widestring ) : olevariant; function FullPathKeyExists( FullPathKey : widestring ) : olevariant; function KeyExists( KeyName : widestring ) : olevariant; function KeysCount : olevariant; function ValuesCount : olevariant; function GetKeyNames : olevariant; function GetValueNames : olevariant; procedure WriteBoolean( Name : widestring; Value : wordbool ); procedure WriteInteger( Name : widestring; Value : integer ); procedure WriteFloat( Name : widestring; Value : double ); procedure WriteString( Name, Value : widestring ); procedure WriteDate( Name : widestring; Value : TDateTime ); procedure WriteDateFromStr( Name, Value : widestring ); procedure WriteCurrency( Name : widestring; Value : currency ); function ReadBoolean( Name : widestring ) : olevariant; function ReadInteger( Name : widestring ) : olevariant; function ReadFloat( Name : widestring ) : olevariant; function ReadString( Name : widestring ) : olevariant; function ReadDate( Name : widestring ) : olevariant; function ReadDateAsStr( Name : widestring ) : olevariant; function ReadCurrency( Name : widestring ) : olevariant; function FullPathValueExists( FullPathName : widestring ) : olevariant; function ValueExists( Name : widestring ) : olevariant; function DeleteFullPathNode( FullPathNode : widestring ) : olevariant; function DeleteNode( NodeName : widestring ) : olevariant; function FullQuery( aQuery : widestring ) : olevariant; function Query( aQuery : widestring ) : olevariant; function IntegrateValues( RelValuePath : widestring ) : olevariant; function QueryKey( FullKeyName, ValueNameList : widestring ) : olevariant; end; // >> the session interface is not complete type TDirServerSession = class(TInterfacedObject, IDirServerSession) public constructor Create(SessionProxy : variant); destructor Destroy; override; private // IDirServerSession procedure EndSession; function GetCurrentKey : widestring; function SetCurrentKey( FullPathKey : widestring ) : olevariant; function CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; function CreateKey( KeyName : widestring ) : olevariant; function FullPathKeyExists( FullPathKey : widestring ) : olevariant; function KeyExists( KeyName : widestring ) : olevariant; function KeysCount : olevariant; function ValuesCount : olevariant; function GetKeyNames : olevariant; function GetValueNames : olevariant; procedure WriteBoolean( Name : widestring; Value : wordbool ); procedure WriteInteger( Name : widestring; Value : integer ); procedure WriteFloat( Name : widestring; Value : double ); procedure WriteString( Name, Value : widestring ); procedure WriteDate( Name : widestring; Value : TDateTime ); procedure WriteDateFromStr( Name, Value : widestring ); procedure WriteCurrency( Name : widestring; Value : currency ); function ReadBoolean( Name : widestring ) : olevariant; function ReadInteger( Name : widestring ) : olevariant; function ReadFloat( Name : widestring ) : olevariant; function ReadString( Name : widestring ) : olevariant; function ReadDate( Name : widestring ) : olevariant; function ReadDateAsStr( Name : widestring ) : olevariant; function ReadCurrency( Name : widestring ) : olevariant; function FullPathValueExists( FullPathName : widestring ) : olevariant; function ValueExists( Name : widestring ) : olevariant; function DeleteFullPathNode( FullPathNode : widestring ) : olevariant; function DeleteNode( NodeName : widestring ) : olevariant; function FullQuery( aQuery : widestring ) : olevariant; function Query( aQuery : widestring ) : olevariant; function IntegrateValues( RelValuePath : widestring ) : olevariant; function QueryKey( FullKeyName, ValueNameList : widestring ) : olevariant; private fSessionProxy : variant; end; implementation // TDirServerSession constructor TDirServerSession.Create(SessionProxy : variant); begin inherited Create; fSessionProxy := SessionProxy; end; destructor TDirServerSession.Destroy; begin EndSession; fSessionProxy := Null; inherited; end; procedure TDirServerSession.EndSession; begin fSessionProxy.RDOEndSession; end; function TDirServerSession.GetCurrentKey : widestring; begin Result := fSessionProxy.RDOGetCurrentKey; end; function TDirServerSession.SetCurrentKey( FullPathKey : widestring ) : olevariant; begin Result := fSessionProxy.RDOSetCurrentKey(FullPathKey); end; function TDirServerSession.CreateFullPathKey( FullPathKey : widestring; ForcePath : wordbool ) : olevariant; begin Result := fSessionProxy.RDOCreateFullPathKey(FullPathKey, ForcePath); end; function TDirServerSession.CreateKey( KeyName : widestring ) : olevariant; begin Result := fSessionProxy.RDOCreateKey(KeyName); end; function TDirServerSession.FullPathKeyExists( FullPathKey : widestring ) : olevariant; begin Result := fSessionProxy.RDOFullPathKeyExists(FullPathKey); end; function TDirServerSession.KeyExists( KeyName : widestring ) : olevariant; begin Result := fSessionProxy.RDOKeyExists(KeyName); end; function TDirServerSession.KeysCount : olevariant; begin Result := fSessionProxy.RDOKeysCount; end; function TDirServerSession.ValuesCount : olevariant; begin Result := fSessionProxy.RDOValuesCount; end; function TDirServerSession.GetKeyNames : olevariant; begin Result := fSessionProxy.RDOGetKeyNames; end; function TDirServerSession.GetValueNames : olevariant; begin Result := fSessionProxy.RDOGetValueNames; end; procedure TDirServerSession.WriteBoolean( Name : widestring; Value : wordbool ); begin fSessionProxy.RDOWriteBoolean(Name, Value); end; procedure TDirServerSession.WriteInteger( Name : widestring; Value : integer ); begin fSessionProxy.RDOWriteInteger(Name, Value); end; procedure TDirServerSession.WriteFloat( Name : widestring; Value : double ); begin fSessionProxy.RDOWriteFloat(Name, Value); end; procedure TDirServerSession.WriteString( Name, Value : widestring ); begin fSessionProxy.RDOWriteString(Name, Value); end; procedure TDirServerSession.WriteDate( Name : widestring; Value : TDateTime ); begin fSessionProxy.RDOWriteDate(Name, Value); end; procedure TDirServerSession.WriteDateFromStr( Name, Value : widestring ); begin fSessionProxy.RDOWriteDateFromStr(Name, Value); end; procedure TDirServerSession.WriteCurrency( Name : widestring; Value : currency ); begin fSessionProxy.RDOWriteCurrency(Name, Value); end; function TDirServerSession.ReadBoolean( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadBoolean(Name); end; function TDirServerSession.ReadInteger( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadInteger(Name); end; function TDirServerSession.ReadFloat( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadFloat(Name); end; function TDirServerSession.ReadString( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadString(Name); end; function TDirServerSession.ReadDate( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadDate(Name); end; function TDirServerSession.ReadDateAsStr( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadDateFromStr(Name); end; function TDirServerSession.ReadCurrency( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOReadCurrency(Name); end; function TDirServerSession.FullPathValueExists( FullPathName : widestring ) : olevariant; begin Result := fSessionProxy.RDOFullPathValueExists(FullPathName); end; function TDirServerSession.ValueExists( Name : widestring ) : olevariant; begin Result := fSessionProxy.RDOValueExists(Name); end; function TDirServerSession.DeleteFullPathNode( FullPathNode : widestring ) : olevariant; begin Result := fSessionProxy.RDODeleteFullPathNode(FullPathNode); end; function TDirServerSession.DeleteNode( NodeName : widestring ) : olevariant; begin Result := fSessionProxy.RDODeleteNode(NodeName); end; function TDirServerSession.FullQuery( aQuery : widestring ) : olevariant; begin Result := fSessionProxy.RDOFullQuery(aQuery); end; function TDirServerSession.Query( aQuery : widestring ) : olevariant; begin Result := fSessionProxy.RDOQuery(aQuery); end; function TDirServerSession.IntegrateValues( RelValuePath : widestring ) : olevariant; begin Result := fSessionProxy.RDOIntegrateValues(RelValuePath); end; function TDirServerSession.QueryKey( FullKeyName, ValueNameList : widestring ) : olevariant; begin Result := fSessionProxy.RDOQueryKey(FullKeyName, ValueNameList); end; end.
{ Mark Sattolo 428500 CSI-1100A DGD-1 TA: Chris Lankester Assignment 10, Question 1 } program ProcessRecords (input,output); uses UNITA10; { *************************************************************************** } procedure HighAdvanced (var U:University; I:integer; var High:real; var Adv:integer); { Find the # of advanced courses for a student and the highest advanced course mark. } { Data Dictionary Givens: U - a University type record. I - an integer giving the position of a student in the Students array. Intermediates: j - an index for the position of a course/mark in StudentInfo. k - the position of a course in the CourseList array. Results: High - the highest mark a student has in an advanced course. Adv - the number of advanced courses taken by a student. } var j,k : integer; begin Adv := 0; High := 0; for j := 1 to NumTaken do begin k := U.Students[I].CoursesTaken[j]; if U.Courses[k].Advanced then begin inc(Adv); if U.Students[I].Marks[j] > High then High := U.Students[I].Marks[j]; end; { if Advanced } end; { for loop } end; { procedure HighAdvanced } { *************************************************************************** } { Main program: Find and output the name, number of advanced courses, and highest advanced mark for each TA in record U. } { Data Dictionary Givens: U - a University type record. nS - the number of students in U. nC - the number of courses in U. seed - a random number used to generate data for U. Intermediates: l - an index for the Students array. m - an index for the Courses array. TAyes - a boolean which is true if a student is a TA, and false otherwise. Results: High - the highest mark a student has in an advanced course. Adv - the number of advanced courses taken by a student. Uses: HighAdvanced, makeData, writeAllCourses, writeAllStudents. } var U : University; nS, nC, l, m, Adv : integer ; seed, High : real; TAyes : boolean; begin repeat { start outer loop } { Read in the program's givens. } writeln('Please enter a value for the random seed [ 0 to exit ]:'); readln(seed); if seed <> 0 then begin writeln('Please enter the # of courses [ at least ', NumTaken, ' ]:'); readln(nC); writeln('Please enter the # of students [ at least 2 * the # of courses ]:'); readln(nS); write('Enter the name of the output file: '); readln(OutputFile); assign(Output, OutputFile); rewrite(Output); { generate and print out the record data } makeData(U,nS,nC,seed); writeln('-------------- COURSES --------------'); writeAllCourses(U); writeln; writeln('-------------- STUDENTS --------------'); writeAllStudents(U) ; writeln; { begin output } { writeln; writeln('************************************************'); writeln(' Mark Sattolo 428500'); writeln(' CSI-1100A DGD-1 TA: Chris Lankester'); writeln(' Assignment 10, Question 1'); writeln('************************************************'); writeln; } { get info and write the table } writeln(output, 'Name':12, '# advanced courses':27, 'Highest advanced mark':25); writeln(output,'--------------- ------------------ ---------------------'); for l := 1 to U.NumStudents do { Loop through the students. } begin HighAdvanced(U, l, High, Adv); { Find the # advanced courses and highest } m := 1; { advanced course mark for each student. } TAyes := false; while (not TAyes) and (m <= U.NumCourses) do { Only need to find the first course for } begin { which the student is a TA.} TAyes := U.Courses[m].TA = l; inc(m); if TAyes then { If a TA, then print out the required info.} with U.Students[l] do begin writeln(output, Name:15, Adv:15, High:20:2); writeln(output); end; { writeln statements } end; { while loop } end; { for loop } writeln(output, '********************************************************************'); writeln; writeln('The data has been written to ', OutputFile); end { if seed <> 0 } else writeln('PROGRAM ENDED'); until seed = 0; { finish outer loop } end.
unit TestAddressBookSamplesUnit; interface uses TestFramework, Classes, SysUtils, BaseTestOnlineExamplesUnit; type TTestAddressBookSamples = class(TTestOnlineExamples) published procedure CreateLocation; procedure GetLocations; procedure GetLocation; procedure GetLocationsByIds; procedure DisplayRouted; procedure LocationSearch; procedure UpdateLocation; procedure RemoveLocations; end; implementation uses AddressBookContactUnit, EnumsUnit, NullableBasicTypesUnit, CommonTypesUnit; var FContact: TAddressBookContact; FContactIdForDelete: integer; procedure TTestAddressBookSamples.CreateLocation; var ErrorString: String; Contact, NewContact: TAddressBookContact; begin Contact := TAddressBookContact.Create; try Contact.Address := '3634 W Market St, Fairlawn, OH 44333'; Contact.FirstName := 'John'; Contact.LastName := 'Smith'; Contact.Latitude := 41.135762259364; Contact.Longitude := -81.629313826561; FContact := FRoute4MeManager.AddressBookContact.Add(Contact, ErrorString); CheckNotNull(FContact); CheckEquals(EmptyStr, ErrorString); CheckTrue(FContact.Id.IsNotNull); finally FreeAndNil(Contact); end; Contact := TAddressBookContact.Create; try Contact.Address := EmptyStr; Contact.Latitude := 41.135762259364; Contact.Longitude := -81.629313826561; NewContact := FRoute4MeManager.AddressBookContact.Add(Contact, ErrorString); try CheckNotNull(NewContact); CheckEquals(EmptyStr, ErrorString); CheckTrue(NewContact.Id.IsNotNull); FContactIdForDelete := NewContact.Id; finally FreeAndNil(NewContact) end; finally FreeAndNil(Contact); end; end; procedure TTestAddressBookSamples.DisplayRouted; var ErrorString: String; Contacts: TAddressBookContactList; Limit, Offset, Total: integer; begin Limit := 2; Offset := 0; Contacts := FRoute4MeManager.AddressBookContact.Find( TDisplayLocations.dlAll, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; Contacts := FRoute4MeManager.AddressBookContact.Find( TDisplayLocations.dlRouted, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; Contacts := FRoute4MeManager.AddressBookContact.Find( TDisplayLocations.dlUnrouted, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; end; procedure TTestAddressBookSamples.GetLocation; var ErrorString: String; Contacts: TAddressBookContactList; Limit, Offset, Total: integer; Query: String; begin Limit := 2; Offset := 0; Query := 'john'; Contacts := FRoute4MeManager.AddressBookContact.Find(Query, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; Query := 'Fairlawn'; Contacts := FRoute4MeManager.AddressBookContact.Find(Query, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; Query := 'uniqueText#$2'; Contacts := FRoute4MeManager.AddressBookContact.Find(Query, Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Total); CheckEquals(0, Contacts.Count); finally FreeAndNil(Contacts) end; end; procedure TTestAddressBookSamples.GetLocations; var ErrorString: String; Contacts: TAddressBookContactList; Limit, Offset, Total: integer; begin Limit := 2; Offset := 0; Contacts := FRoute4MeManager.AddressBookContact.Get(Limit, Offset, Total, ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Contacts.Count > 0); finally FreeAndNil(Contacts) end; end; procedure TTestAddressBookSamples.GetLocationsByIds; var ErrorString: String; Contacts: TAddressBookContactList; begin Contacts := FRoute4MeManager.AddressBookContact.Get([-123], ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); // CheckNotEquals(EmptyStr, ErrorString); CheckEquals(0, Contacts.Count); finally FreeAndNil(Contacts) end; Contacts := FRoute4MeManager.AddressBookContact.Get([-123, -321], ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Contacts.Count); finally FreeAndNil(Contacts) end; Contacts := FRoute4MeManager.AddressBookContact.Get([-123, FContact.Id], ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckEquals(1, Contacts.Count); finally FreeAndNil(Contacts) end; Contacts := FRoute4MeManager.AddressBookContact.Get([FContact.Id, FContactIdForDelete], ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Contacts.Count); finally FreeAndNil(Contacts) end; // todo 4: почему-то, если id единственный, выдает неверный результат. Спросил у Олега // сейчас подогнал логику в TAddressBookContactActions.Get Contacts := FRoute4MeManager.AddressBookContact.Get([FContact.Id], ErrorString); try CheckNotNull(Contacts); CheckEquals(EmptyStr, ErrorString); CheckEquals(1, Contacts.Count); finally FreeAndNil(Contacts) end; end; procedure TTestAddressBookSamples.LocationSearch; var ErrorString: String; FindedResults: T2DimensionalStringArray; Limit, Offset, Total: integer; Query: String; begin Limit := 2; Offset := 0; Query := 'john'; FindedResults := FRoute4MeManager.AddressBookContact.Find( Query, ['address_id','first_name', 'address_1'], Limit, Offset, Total, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Length(FindedResults) > 0); finally Finalize(FindedResults); end; Query := 'Fairlawn'; FindedResults := FRoute4MeManager.AddressBookContact.Find( Query, ['address_1'], Limit, Offset, Total, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue(Length(FindedResults) > 0); finally Finalize(FindedResults); end; Query := 'uniqueText#$2'; FindedResults := FRoute4MeManager.AddressBookContact.Find( Query, ['first_name', 'address_1'], Limit, Offset, Total, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Total); CheckEquals(0, Length(FindedResults)); finally Finalize(FindedResults); end; end; procedure TTestAddressBookSamples.RemoveLocations; var ErrorString: String; begin CheckTrue(FRoute4MeManager.AddressBookContact.Remove([-123], ErrorString)); CheckEquals(EmptyStr, ErrorString); CheckTrue(FRoute4MeManager.AddressBookContact.Remove( [FContact.Id, FContactIdForDelete], ErrorString)); CheckEquals(EmptyStr, ErrorString); FreeAndNil(FContact); end; procedure TTestAddressBookSamples.UpdateLocation; var ErrorString: String; Contact: TAddressBookContact; Id: integer; begin FContact.FirstName := 'Mary'; Contact := FRoute4MeManager.AddressBookContact.Update(FContact, ErrorString); try CheckNotNull(Contact); CheckEquals(EmptyStr, ErrorString); CheckTrue(Contact.Id.IsNotNull); CheckEquals('Mary', Contact.FirstName); finally FreeAndNil(Contact) end; Id := FContact.Id; FContact.Id := NullableInteger.Null; try FContact.FirstName := 'Tom'; Contact := FRoute4MeManager.AddressBookContact.Update(FContact, ErrorString); try CheckNull(Contact); CheckNotEquals(EmptyStr, ErrorString); finally FreeAndNil(Contact) end; finally FContact.Id := Id; end; end; initialization RegisterTest('Examples\Online\AddressBook\', TTestAddressBookSamples.Suite); end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.Classifier; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.IntegralImage, CP.Filter, CP.Quantizer; type { TClassifier } TClassifier = class(TObject) private FFilter: TFilter; FQuantizer: TQuantizer; public property Filter: TFilter read FFilter; property Quantizer: TQuantizer read FQuantizer; public constructor Create(Filter: TFilter = nil; Quantizer: TQuantizer = nil); destructor Destroy; override; function Classify(image: TIntegralImage; offset: integer): integer; end; TClassifierArray = array of TClassifier; implementation { TClassifier } constructor TClassifier.Create(Filter: TFilter; Quantizer: TQuantizer); begin if Filter <> nil then FFilter := Filter else FFilter := TFilter.Create; if Quantizer <> nil then FQuantizer := Quantizer else FQuantizer := TQuantizer.Create; end; destructor TClassifier.Destroy; begin FFilter.Free; FQuantizer.Free; inherited; end; function TClassifier.Classify(image: TIntegralImage; offset: integer): integer; var Value: double; begin Value := FFilter.Apply(image, offset); Result := FQuantizer.Quantize(Value); end; end.
unit PuppetSkinEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, MGR32_Image; type TFrmPuppetSkinEdit = class(TForm) LstSkinPart: TListBox; EdtSkinId: TEdit; Label3: TLabel; LstAction: TListBox; Label5: TLabel; LstDir: TListBox; Label6: TLabel; EdtAnimDelay: TEdit; Label7: TLabel; LstSprite: TListBox; View: TMPaintBox32; Label8: TLabel; PopupSpriteList: TPopupMenu; MainMenu1: TMainMenu; File1: TMenuItem; LoadMonsterSkins1: TMenuItem; SAveMonsters1: TMenuItem; EdtVtxColor: TEdit; Label9: TLabel; GroupBox1: TGroupBox; ChkReverse: TCheckBox; Button1: TButton; Button2: TButton; DlgOpen: TOpenDialog; DlgSave: TSaveDialog; PopupSkinPartList: TPopupMenu; AddSkin1: TMenuItem; Duplicateskin1: TMenuItem; N1: TMenuItem; DeleteSkin1: TMenuItem; Label4: TLabel; ComboColorFx: TComboBox; EdtOffX: TEdit; Label11: TLabel; Label12: TLabel; EdtOffY: TEdit; N2: TMenuItem; AutoFill1: TMenuItem; AutoSort1: TMenuItem; N3: TMenuItem; ClearList1: TMenuItem; Sort1: TMenuItem; Label10: TLabel; EdtSkinName: TEdit; Label13: TLabel; ChkFemale: TCheckBox; Help1: TMenuItem; Options1: TMenuItem; SetMaxAutoFillSearch1: TMenuItem; procedure SavePuppet1Click(Sender: TObject); procedure LoadPuppetSkins1Click(Sender: TObject); procedure AddSkin1Click(Sender: TObject); procedure FormResize(Sender: TObject); procedure DeleteSkin1Click(Sender: TObject); procedure EdtNameChange(Sender: TObject); procedure LstSkinPartClick(Sender: TObject); procedure EdtVtxColorChange(Sender: TObject); procedure EdtAnimDelayChange(Sender: TObject); procedure ComboColorFxChange(Sender: TObject); procedure LstActionClick(Sender: TObject); procedure LstDirClick(Sender: TObject); Procedure RefreshView; procedure LstSpriteDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure LstSpriteDragDrop(Sender, Source: TObject; X, Y: Integer); procedure LstSpriteClick(Sender: TObject); procedure AutoFill1Click(Sender: TObject); procedure ClearList1Click(Sender: TObject); procedure Sort1Click(Sender: TObject); procedure ChkFemaleClick(Sender: TObject); procedure EdtSkinIdChange(Sender: TObject); procedure SetMaxAutoFillSearch1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmPuppetSkinEdit: TFrmPuppetSkinEdit; MaxAutoFillWalk,MaxAutoFillAttack,MaxAutoFillRange:integer; implementation {$R *.dfm} uses comctrls,FastStream,udda,IdTypes,globals; procedure TFrmPuppetSkinEdit.FormCreate(Sender: TObject); begin MaxAutoFillWalk:=ord('m')-ord('a'); MaxAutoFillAttack:=ord('i')-ord('a'); MaxAutoFillRange:=ord('i')-ord('a'); end; procedure TFrmPuppetSkinEdit.FormResize(Sender: TObject); begin LstSkinPart.Height:=(FrmPuppetSkinEdit.ClientHeight-LstSkinPart.Top)-4; LstSprite.Height:=(FrmPuppetSkinEdit.ClientHeight-LstSprite.Top)-4; GroupBox1.Top:=(FrmPuppetSkinEdit.ClientHeight-GroupBox1.Height)-4; View.Width:=(FrmPuppetSkinEdit.ClientWidth-View.Left)-4; View.Height:=(FrmPuppetSkinEdit.ClientHeight-View.Top)-4; end; Procedure ReadFrameFromStream(var Fst:TFastStream;Frame:PFrame); begin Frame^.SpriteName:=Fst.ReadWordString; Frame^.Offx:=Fst.ReadWord; Frame^.Offy:=Fst.ReadWord; end; Procedure ReadSoundFromStream(var Fst:TFastStream;Sound:PSoundInfo); begin Sound^.SoundName:=Fst.ReadWordString; Sound^.PitchDev:=Fst.ReadSingle; end; Procedure WriteFrameToStream(var Fst:TFastStream;Frame:PFrame); begin Fst.WriteWordString(Frame^.SpriteName); Fst.WriteWord(Word(Frame^.Offx)); Fst.WriteWord(Word(Frame^.Offy)); end; Procedure WriteSoundToStream(var Fst:TFastStream;Sound:PSoundInfo); begin Fst.WriteWordString(Sound^.SoundName); Fst.WriteSingle(Sound^.PitchDev); end; procedure TFrmPuppetSkinEdit.LoadPuppetSkins1Click(Sender: TObject); var i,j,k,Count,Version:longint; Fst:TFastStream; Skin:PPuppetSkinPartInfo; Frame:PFrame; Sound:PSoundInfo; begin if DlgOpen.Execute then begin Fst:=TFastStream.Create; Fst.LoadFromFile(DlgOpen.FileName); Version:=Fst.ReadLong; Count:=Fst.ReadLong; for i:=0 to Count-1 do begin new(Skin); with Skin^ do begin SkinName:=Fst.ReadWordString; SkinId:=Fst.ReadWord; Female:=Fst.ReadLong=1; VertexColor:=Fst.ReadLong; ColorFx:=Fst.ReadLong; AnimationDelay:=Fst.ReadSingle; for j:=0 to 7 do begin Walk[j].Reversed:=Fst.ReadLong; Walk[j].GraphCount:=Fst.ReadLong; Walk[j].FrameList:=Tlist.Create; for k:=0 to Walk[j].GraphCount-1 do begin new(Frame); ReadFrameFromStream(Fst,Frame); Walk[j].FrameList.Add(Frame); end; end; for j:=0 to 7 do begin Attack[j].Reversed:=Fst.ReadLong; Attack[j].GraphCount:=Fst.ReadLong; Attack[j].FrameList:=Tlist.Create; for k:=0 to Attack[j].GraphCount-1 do begin new(Frame); ReadFrameFromStream(Fst,Frame); Attack[j].FrameList.Add(Frame); end; end; for j:=0 to 7 do begin Range[j].Reversed:=Fst.ReadLong; Range[j].GraphCount:=Fst.ReadLong; Range[j].FrameList:=Tlist.Create; for k:=0 to Range[j].GraphCount-1 do begin new(Frame); ReadFrameFromStream(Fst,Frame); Range[j].FrameList.Add(Frame); end; end; Death.Reversed:=Fst.ReadLong; Death.GraphCount:=Fst.ReadLong; Death.FrameList:=Tlist.Create; for k:=0 to Death.GraphCount-1 do begin new(Frame); ReadFrameFromStream(Fst,Frame); Death.FrameList.Add(Frame); end; end; LstSkinPart.AddItem(Skin^.SkinName,TObject(Skin)); end; Fst.Free; end; end; procedure TFrmPuppetSkinEdit.SavePuppet1Click(Sender: TObject); var i,j,k,Count,Version:longint; Fst:TFastStream; Skin:PPuppetSkinPartInfo; Frame:PFrame; begin DlgSave.FileName:=DlgOpen.FileName; if DlgSave.Execute then begin Fst:=TFastStream.Create; Version:=1; Fst.WriteLong(Version); Count:=LstSkinPart.Count; Fst.WriteLong(Count); for i:=0 to Count-1 do begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[i]); with Skin^ do begin Fst.WriteWordString(SkinName); Fst.WriteWord(SkinId); Fst.WriteLong(longint(Female)); Fst.WriteLong(VertexColor); Fst.WriteLong(ColorFx); Fst.WriteSingle(AnimationDelay); for j:=0 to 7 do begin Fst.WriteLong(Walk[j].Reversed); Walk[j].GraphCount:=Walk[j].FrameList.Count; Fst.WriteLong(Walk[j].GraphCount); for k:=0 to Walk[j].GraphCount-1 do begin WriteFrameToStream(Fst,Walk[j].FrameList[k]); end; end; for j:=0 to 7 do begin Fst.WriteLong(Attack[j].Reversed); Attack[j].GraphCount:=Attack[j].FrameList.Count; Fst.WriteLong(Attack[j].GraphCount); for k:=0 to Attack[j].GraphCount-1 do begin WriteFrameToStream(Fst,Attack[j].FrameList[k]); end; end; for j:=0 to 7 do begin Fst.WriteLong(Range[j].Reversed); Range[j].GraphCount:=Range[j].FrameList.Count; Fst.WriteLong(Range[j].GraphCount); for k:=0 to Range[j].GraphCount-1 do begin WriteFrameToStream(Fst,Range[j].FrameList[k]); end; end; Fst.WriteLong(Death.Reversed); Death.GraphCount:=Death.FrameList.Count; Fst.WriteLong(Death.GraphCount); for k:=0 to Death.GraphCount-1 do begin WriteFrameToStream(Fst,Death.FrameList[k]); end; end; end; Fst.WriteToFile(DlgSave.FileName); Fst.Free; end; end; procedure TFrmPuppetSkinEdit.SetMaxAutoFillSearch1Click(Sender: TObject); var Result:string; begin Result:='m'; InputQuery('Max autofill Walk','a-z',Result); MaxAutoFillWalk:=(ord(Result[1])-ord('a')); Result:='i'; InputQuery('Max autofill Attack','a-z',Result); MaxAutoFillAttack:=(ord(Result[1])-ord('a')); Result:='i'; InputQuery('Max autofill Range','a-z',Result); MaxAutoFillRange:=(ord(Result[1])-ord('a')); end; procedure TFrmPuppetSkinEdit.Sort1Click(Sender: TObject); begin LstSkinPart.Sorted:=LstSkinPart.Sorted xor true; TMenuItem(sender).Checked:=LstSkinPart.Sorted; end; procedure TFrmPuppetSkinEdit.AddSkin1Click(Sender: TObject); var Skin:PPuppetSkinPartInfo; i:longint; begin New(Skin); with Skin^ do begin SkinName:='NewSkinPart'; //SkinId:=0; VertexColor:=$FFFFFFFF; ColorFx:=0; AnimationDelay:=0.033; for i:=0 to 7 do begin Walk[i].Reversed:=0; Walk[i].GraphCount:=0; Walk[i].FrameList:=TList.Create; Attack[i].Reversed:=0; Attack[i].GraphCount:=0; Attack[i].FrameList:=TList.Create; Range[i].Reversed:=0; Range[i].GraphCount:=0; Range[i].FrameList:=TList.Create; end; for i:=5 to 7 do begin Walk[i].Reversed:=1; Attack[i].Reversed:=1; Range[i].Reversed:=1; end; Death.Reversed:=0; Death.GraphCount:=0; Death.FrameList:=TList.Create; end; LstSkinPart.AddItem(Skin^.SkinName,TObject(Skin)); end; procedure TFrmPuppetSkinEdit.DeleteSkin1Click(Sender: TObject); var Skin:PPuppetSkinPartInfo; i,j:integer; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); With Skin^ do begin for i:=0 to 7 do begin Walk[i].Reversed:=0; Walk[i].GraphCount:=0; for j:=0 to Walk[i].FrameList.Count-1 do begin Dispose(PFrame(Walk[i].FrameList.Items[j])); end; Walk[i].FrameList.Free; Attack[i].Reversed:=0; Attack[i].GraphCount:=0; for j:=0 to Attack[i].FrameList.Count-1 do begin Dispose(PFrame(Attack[i].FrameList.Items[j])); end; Attack[i].FrameList.Free; end; Death.FrameList.free; end; LstSkinPart.DeleteSelected; Dispose(Skin); end; end; function GenerateDeathSuffix(const i:integer):string; var Sec:string; begin Sec:=''; if (i div 26) >0 then Sec:=chr((i div 26)+48); result:='c-'+chr((i mod 26)+97)+sec; end; Function GenerateWalkSuffix(const Dir,i:integer):string; var Sec:string; begin Sec:=''; if (i div 26) >0 then Sec:=chr((i div 26)+48); case Dir of 0:Result:='000-'+chr((i mod 26)+97)+sec; 1:Result:='045-'+chr((i mod 26)+97)+sec; 2:Result:='090-'+chr((i mod 26)+97)+sec; 3:Result:='135-'+chr((i mod 26)+97)+sec; 4:Result:='180-'+chr((i mod 26)+97)+sec; end; end; procedure TFrmPuppetSkinEdit.AutoFill1Click(Sender: TObject); var Skin:PPuppetSkinPartInfo; BaseName:string; SpName:string; Found:boolean; Counter:longint; Sprite:PSprite; Frame,CpyFrame:PFrame; Direction,i,CpyDir:integer; begin // if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); BaseName:=LowerCase(InputBox('Base Sprite Name','Name: ','')); if BaseName='' then exit; //Walk sprites for Direction:=0 to 4 do begin Counter:=0; repeat SpName:=BaseName+GenerateWalkSuffix(Direction,Counter); Sprite:=Index.SpriteHash.SearchByName(SpName); if Sprite=nil then begin Sprite:=Index.SpriteHash.SearchByName('blanksprite'); SpName:='blanksprite'; end; new(Frame); Frame^.SpriteName:=SpName; Frame^.Offx:=0; Frame^.Offy:=0; GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0); Skin^.Walk[Direction].FrameList.Add(Frame); inc(Counter); until Counter>MaxAutoFillWalk; end; //we need to copy the frame for the reversed direction if counter>0 then for Direction:=5 to 7 do begin CpyDir:=3-(Direction-5);//take the related normal direction //copy each frame, and take the good offset for i:=0 to Skin^.Walk[CpyDir].FrameList.Count-1 do begin CpyFrame:=Skin^.Walk[CpyDir].FrameList.Items[i]; new(frame); Frame^.SpriteName:=CpyFrame^.SpriteName; GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,1); Skin^.Walk[Direction].FrameList.Add(Frame); end; end; //Attack sprites for Direction:=0 to 4 do begin Counter:=0; repeat SpName:=BaseName+'a'+GenerateWalkSuffix(Direction,Counter); Sprite:=Index.SpriteHash.SearchByName(SpName); if Sprite=nil then begin Sprite:=Index.SpriteHash.SearchByName('blanksprite'); SpName:='blanksprite'; end; new(Frame); Frame^.SpriteName:=SpName; Frame^.Offx:=0; Frame^.Offy:=0; GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0); Skin^.Attack[Direction].FrameList.Add(Frame); inc(Counter); until Counter>MaxAutoFillAttack; end; //we need to copy the frame for the reversed direction if counter>0 then for Direction:=5 to 7 do begin CpyDir:=3-(Direction-5);//take the related normal direction //copy each frame, and take the good offset for i:=0 to Skin^.Attack[CpyDir].FrameList.Count-1 do begin CpyFrame:=Skin^.Attack[CpyDir].FrameList.Items[i]; new(frame); Frame^.SpriteName:=CpyFrame^.SpriteName; GetSpriteOffset(Frame^.SpriteName,Frame^.Offx,Frame^.Offy,1); Skin^.Attack[Direction].FrameList.Add(Frame); end; end; //range sprites for Direction:=0 to 4 do begin Counter:=0; repeat SpName:=BaseName+'b'+GenerateWalkSuffix(Direction,Counter); Sprite:=Index.SpriteHash.SearchByName(SpName); if Sprite=nil then begin Sprite:=Index.SpriteHash.SearchByName('blanksprite'); SpName:='blanksprite'; end; new(Frame); Frame^.SpriteName:=SpName; Frame^.Offx:=0; Frame^.Offy:=0; GetSpriteOffset(SpName,Frame^.Offx,Frame^.Offy,0); Skin^.Range[Direction].FrameList.Add(Frame); inc(Counter); until Counter>MaxAutoFillRange; end; //we need to copy the frame for the reversed direction if counter>0 then for Direction:=5 to 7 do begin CpyDir:=3-(Direction-5);//take the related normal direction //copy each frame, and take the good offset for i:=0 to Skin.Range[CpyDir].FrameList.Count-1 do begin CpyFrame:=Skin.Range[CpyDir].FrameList.Items[i]; new(frame); Frame.SpriteName:=CpyFrame.SpriteName; GetSpriteOffset(Frame.SpriteName,Frame.Offx,Frame.Offy,1); Skin.Range[Direction].FrameList.Add(Frame); end; end; //death sprites Found:=true; Counter:=0; repeat SpName:=BaseName+GenerateDeathSuffix(Counter); Sprite:=Index.SpriteHash.SearchByName(SpName); if Sprite<>nil then begin new(Frame); Frame.SpriteName:=SpName; Frame.Offx:=0; Frame.Offy:=0; GetSpriteOffset(SpName,Frame.Offx,Frame.Offy,0); Skin.Death.FrameList.Add(Frame); end else begin Found:=false; end; inc(Counter); until Found=false; end; RefreshView; end; procedure TFrmPuppetSkinEdit.LstSkinPartClick(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); EdtSkinName.Text:=Skin.SkinName; EdtSkinId.Text:=IntToStr(Skin.SkinId); EdtAnimDelay.Text:=IntToStr(round(Skin.AnimationDelay*1000)); EdtVtxColor.Text:=IntToHex(Skin.VertexColor,8); ComboColorFx.ItemIndex:=Skin.ColorFx; ChkFemale.Checked:=Skin.Female; RefreshView; end; end; procedure TFrmPuppetSkinEdit.LstActionClick(Sender: TObject); begin if LstSkinPart.ItemIndex>=0 then begin RefreshView; end; end; procedure TFrmPuppetSkinEdit.LstDirClick(Sender: TObject); begin if LstSkinPart.ItemIndex>=0 then begin RefreshView; end; end; procedure TFrmPuppetSkinEdit.RefreshView; var Skin:PPuppetSkinPartInfo; Frame:PFrame; i:longint; begin LstSprite.Items.BeginUpdate; LstSprite.Items.Clear; if LstSkinPart.ItemIndex>=0 then if LstAction.ItemIndex>=0 then if LstDir.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); case LstAction.ItemIndex of 0:begin ChkReverse.Checked:=Boolean(Skin.Walk[LstDir.ItemIndex].Reversed); for i:=0 to Skin.Walk[LstDir.ItemIndex].FrameList.Count-1 do begin Frame:=Skin.Walk[LstDir.ItemIndex].FrameList.Items[i]; LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame)); end; end; 1:begin ChkReverse.Checked:=Boolean(Skin.Attack[LstDir.ItemIndex].Reversed); for i:=0 to Skin.Attack[LstDir.ItemIndex].FrameList.Count-1 do begin Frame:=Skin.Attack[LstDir.ItemIndex].FrameList.Items[i]; LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame)); end; end; 2:begin ChkReverse.Checked:=boolean(Skin.Death.Reversed); for i:=0 to Skin.Death.FrameList.Count-1 do begin Frame:=Skin.Death.FrameList.Items[i]; LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame)); end; end; 3:begin ChkReverse.Checked:=Boolean(Skin.Range[LstDir.ItemIndex].Reversed); for i:=0 to Skin.Range[LstDir.ItemIndex].FrameList.Count-1 do begin Frame:=Skin.Range[LstDir.ItemIndex].FrameList.Items[i]; LstSprite.Items.AddObject(Frame.SpriteName,TObject(Frame)); end; end; end; end; LstSprite.Items.EndUpdate; end; procedure TFrmPuppetSkinEdit.EdtAnimDelayChange(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); if EdtAnimDelay.Text<>'' then Skin^.AnimationDelay:=StrToInt(EdtAnimDelay.Text)/1000; end; end; procedure TFrmPuppetSkinEdit.EdtNameChange(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); Skin^.SkinName:=EdtSkinName.Text; LstSkinPart.Items[LstSkinPart.ItemIndex]:=Skin^.SkinName+':'+IntToStr(Skin.SkinId); end; end; procedure TFrmPuppetSkinEdit.EdtSkinIdChange(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); Skin.SkinId:=StrToInt(EdtSkinId.Text); LstSkinPart.Items[LstSkinPart.ItemIndex]:=Skin^.SkinName+':'+IntToStr(Skin.SkinId); end; end; procedure TFrmPuppetSkinEdit.ChkFemaleClick(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); Skin^.Female:=ChkFemale.Checked; end; end; procedure TFrmPuppetSkinEdit.ComboColorFxChange(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); Skin^.ColorFx:=ComboColorFx.ItemIndex; end; end; procedure TFrmPuppetSkinEdit.EdtVtxColorChange(Sender: TObject); var Skin:PPuppetSkinPartInfo; begin if LstSkinPart.ItemIndex>=0 then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); Skin^.VertexColor:=HexToInt(EdtVtxColor.Text); end; end; procedure TFrmPuppetSkinEdit.LstSpriteClick(Sender: TObject); var Skin:PPuppetSkinPartInfo; Rev:Cardinal; Frame:PFrame; Sprite:PSprite; Surface:PCardinal; begin if (LstSkinPart.ItemIndex>=0) and (LstSprite.ItemIndex>=0) then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); if LstAction.ItemIndex>=0 then if LstDir.ItemIndex>=0 then begin case LstAction.ItemIndex of 0:begin Frame:=Skin^.Walk[LstDir.ItemIndex].FrameList[LstSprite.ItemIndex]; Rev:=Skin^.Walk[LstDir.ItemIndex].Reversed; end; 1:begin Frame:=Skin^.Attack[LstDir.ItemIndex].FrameList[LstSprite.ItemIndex]; Rev:=Skin^.Attack[LstDir.ItemIndex].Reversed; end; 2:begin Frame:=Skin^.Death.FrameList[LstSprite.ItemIndex]; Rev:=Skin^.Death.Reversed; end; 3:begin Frame:=Skin^.Range[LstDir.ItemIndex].FrameList[LstSprite.ItemIndex]; Rev:=Skin^.Range[LstDir.ItemIndex].Reversed; end; end; EdtOffX.Text:=IntToStr(Frame^.Offx); EdtOffY.Text:=IntToStr(Frame^.Offy); //get the sprite Sprite:=nil; if Index.SpriteHash<>nil then Sprite:=Index.SpriteHash.SearchByName(Frame^.SpriteName); if Sprite=nil then exit; Surface:=GetSpriteA8R8G8B8Surface(Sprite); DrawA8R8G8B8(Surface,Sprite^.Width,Sprite^.Height,Frame^.Offx-16,Frame^.Offy-8,Rev,1,Skin^.VertexColor,Skin^.ColorFx,View); FreeMem(Surface); end; end; end; procedure TFrmPuppetSkinEdit.ClearList1Click(Sender: TObject); var Skin:PPuppetSkinPartInfo; Rev:Cardinal; Frame:PFrame; Sprite:PSprite; Surface:PCardinal; begin if (LstSkinPart.ItemIndex>=0) then begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); if LstAction.ItemIndex>=0 then if LstDir.ItemIndex>=0 then begin //TODO Dispose the frame !!!!!! case LstAction.ItemIndex of 0:begin Skin^.Walk[LstDir.ItemIndex].FrameList.Clear; end; 1:begin Skin^.Attack[LstDir.ItemIndex].FrameList.Clear; end; 2:begin Skin^.Death.FrameList.Clear; end; end; end; end; RefreshView; end; procedure TFrmPuppetSkinEdit.LstSpriteDragDrop(Sender, Source: TObject; X, Y: Integer); var TempList:TList; i:integer; Tree:TTreeView; Frame:PFrame; Skin:PPuppetSkinPartInfo; src,dst:integer; begin //drag a list of graph from the graph editor if Source is TTreeView then begin Tree:=TTreeView(Source); if (Tree.SelectionCount>0) and (LstSkinPart.ItemIndex>=0 ) and (LstAction.ItemIndex>=0) then //we got something selected (sanity check) begin Skin:=PPuppetSkinPartInfo(LstSkinPart.Items.Objects[LstSkinPart.ItemIndex]); for i:=0 to Tree.SelectionCount-1 do begin if Tree.Selections[i].ImageIndex=1 then //reject directory begin new(Frame); Frame.SpriteName:=Tree.Selections[i].Text; Frame.Offx:=0; Frame.Offy:=0; case LstAction.ItemIndex of 0:begin Skin.Walk[LstDir.ItemIndex].FrameList.Add(Frame); GetSpriteOffset(Frame.SpriteName,Frame.Offx,Frame.Offy,Skin.Walk[LstDir.ItemIndex].Reversed); end; 1:begin Skin.Attack[LstDir.ItemIndex].FrameList.Add(Frame); GetSpriteOffset(Frame.SpriteName,Frame.Offx,Frame.Offy,Skin.Attack[LstDir.ItemIndex].Reversed); end; 2:begin Skin.Death.FrameList.Add(Frame); GetSpriteOffset(Frame.SpriteName,Frame.Offx,Frame.Offy,Skin.Death.Reversed); end; 3:begin Skin.Range[LstDir.ItemIndex].FrameList.Add(Frame); GetSpriteOffset(Frame.SpriteName,Frame.Offx,Frame.Offy,Skin.Range[LstDir.ItemIndex].Reversed); end; end; end; end; RefreshView; end; end else if Source is TListbox then begin Src:=LstSprite.ItemIndex; dst:=LstSprite.ItemAtPos(Point(x,y),true); if (src>0) and (src<LstSprite.Items.Count) then begin LstSprite.Items.Exchange(src,dst); case LstAction.ItemIndex of 0:begin Skin.Walk[LstDir.ItemIndex].FrameList.Exchange(src,dst); end; 1:begin Skin.Attack[LstDir.ItemIndex].FrameList.Exchange(src,dst); end; 2:begin Skin.Death.FrameList.Exchange(src,dst); end; 3:begin Skin.Range[LstDir.ItemIndex].FrameList.Exchange(src,dst); end; end; end; end; end; procedure TFrmPuppetSkinEdit.LstSpriteDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); var Tree:TTreeView; begin Accept:=false; if Source is TTreeView then begin Tree:=TTreeView(Source); if Tree.Tag=2 then Accept:=true; end else if Source is TListbox then begin if TListBox(Source).Tag=30 then Accept:=true; end; end; end.
unit w640x480; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DXDraws, ExtCtrls, StdCtrls, DXClass, DXInput, DXSprite; type TForm3 = class(TForm) LevelImage: TDXDraw; DXImageList: TDXImageList; DXTimer1: TDXTimer; DXInput1: TDXInput; procedure DXTimer1Timer(Sender: TObject; LagCount: Integer); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } public { Public declarations } procedure CheckKey; procedure DoMoveGuy; procedure DoMoveChips; procedure ShowChips; procedure ShowGuy; end; var Form3: TForm3; implementation {$R *.DFM} type GBackground = class Chips: array of array of int64; // 2D array of segments, pole DifX: integer; // X differention, odchylka dx DifY: integer; // Y differention, odchylka dy MaxX: integer; // X background size, X velikost podkladu (+2 levy a pravy okraj) MaxY: integer; // Y background size, Y velikost podkladu (+2 horni a dolni okraj) WinX: integer; // X window size, X velikost viditelneho okna WinY: integer; // Y window size, Y velikost viditelneho okna SegX: integer; // X position segment, X pozice hruba SegY: integer; // Y position segment, Y poyice hruba OffX: integer; // X position offset, X poyice jemna OffY: integer; // Y position offset, Y poyice jemna OutR: boolean; // out of range, posunout i mimo rozsah DirL: boolean; // direction left, posun doleva DirR: boolean; // direction right, posun doprava DirU: boolean; // direction up, posun nahoru DirD: boolean; // direction down, posun dolu end; // Guy variables GGuy = class DifX: integer; // X differention, odchylka dx DifY: integer; // Y differention, odchylka dy WinL: integer; // Window left corner, levy roh pohyboveho okna WinU: integer; // Window up corner, horni roh pohyboveho okna WinR: integer; // Window right corner, pravy roh pohyboveho okna WinD: integer; // Window down corner, dolni roh pohyboveho okna SegX: integer; // X position segment, X pozice hruba SegY: integer; // Y position segment, Y pozice hruba OffX: integer; // X position offset, X pozice jemna OffY: integer; // Y position offset, Y pozice jemna DirL: boolean; // direction left, posun doleva DirR: boolean; // direction right, posun doprava DirU: boolean; // direction up, posun nahoru DirD: boolean; // direction down, posun dolu Spd: double; // guy speed, rychlost pajdulaka end; var bg: GBackground; gu: GGuy; procedure TForm3.FormCreate(Sender: TObject); begin // DXImageList.Items.MakeColorTable; // LevelImage.ColorTable := DXImageList.Items.ColorTable; // LevelImage.DefColorTable := DXImageList.Items.ColorTable; // SetPriorityClass(GetCurrentProcess, HIGH_PRIORITY_CLASS); end; procedure TForm3.FormDestroy(Sender: TObject); begin // end; procedure TForm3.CheckKey; var lastU: boolean; lastD: boolean; lastL: boolean; lastR: boolean; begin DXInput1.Update; lastU:=False; lastD:=False; lastL:=False; lastR:=False; if (gu.OffY = 0) then begin if isLeft in DXInput1.States then lastL:=True; if isRight in DXInput1.States then lastR:=True; end; if (gu.OffX = 0) then begin if isUp in DXInput1.States then lastU:=True; if isDown in DXInput1.States then lastD:=True; end; if (lastL or lastR) and (lastU or lastD) then begin if (gu.DirL or gu.DirR) then begin lastL:=False; lastR:=False; end; if (gu.DirU or gu.DirD) then begin lastU:=False; lastD:=False; end; end; gu.DirU:=lastU; gu.DirD:=lastD; gu.DirL:=lastL; gu.DirR:=lastR; end; procedure TForm3.DoMoveGuy; var canMove: boolean; begin bg.DirU:=False; bg.DirD:=False; bg.DirL:=False; bg.DirR:=False; if (gu.DirL <> gu.DirR) then begin if gu.DirL then begin canMove:=True; if (gu.SegX = 1) and (gu.OffX = 0) then canMove:=False; if canMove then begin gu.OffX:=gu.OffX-gu.DifX; if gu.OffX < 0 then begin gu.OffX:=gu.OffX+64; gu.SegX:=gu.SegX-1; end; if ((gu.SegX-bg.SegX)*64 - bg.OffX + gu.OffX) < (gu.WinL*64) then bg.DirL:=True; if (gu.SegX < 1) then begin gu.SegX:=1; gu.OffX:=0; end; end; end; if gu.DirR then begin canMove:=True; if (gu.SegX = (bg.MaxX-2)) and (gu.OffX = 0) then canMove:=False; if canMove then begin gu.OffX:=gu.OffX+gu.DifX; if gu.OffX >= 64 then begin gu.OffX:=gu.OffX-64; gu.SegX:=gu.SegX+1; end; if ((gu.SegX-bg.SegX)*64 - bg.OffX + gu.OffX) > (gu.WinR*64) then bg.DirR:=True; if (gu.SegX >= (bg.MaxX-2)) then begin gu.SegX:=bg.MaxX-2; gu.OffX:=0; end; end; end; end; if (gu.DirU <> gu.DirD) then begin if gu.DirU then begin canMove:=True; if (gu.SegY = 1) and (gu.OffY = 0) then canMove:=False; if canMove then begin gu.OffY:=gu.OffY-gu.DifY; if gu.OffY < 0 then begin gu.OffY:=64-gu.DifY; gu.SegY:=gu.SegY-1; end; if ((gu.SegY-bg.SegY)*64 - bg.OffY + gu.OffY) < (gu.WinU*64) then bg.DirU:=True; if (gu.SegY < 1) then begin gu.SegY:=1; gu.OffY:=0; end; end; end; if gu.DirD then begin canMove:=True; if (gu.SegY = (bg.MaxY-2)) and (gu.OffY = 0) then canMove:=False; if canMove then begin gu.OffY:=gu.OffY+gu.DifY; if gu.OffY >= 64 then begin gu.OffY:=0; gu.SegY:=gu.SegY+1; end; if ((gu.SegY-bg.SegY)*64 - bg.OffY + gu.OffY) > (gu.WinD*64) then bg.DirD:=True; if (gu.SegY >= (bg.MaxY-2)) then begin gu.SegY:=bg.MaxY-2; gu.OffY:=0; end; end; end; end; end; procedure TForm3.DoMoveChips; var canMove: boolean; begin if (bg.DirL <> bg.DirR) then begin if bg.DirL then begin canMove:=True; if (bg.SegX = 0) and (bg.OffX = 0) and (not bg.OutR) then canMove:=False; if ((bg.SegX+bg.WinX) = 1) and (bg.OffX = 0) and (bg.OutR) then canMove:=False; if canMove then begin bg.OffX:=bg.OffX-bg.DifX; if bg.OffX < 0 then begin bg.OffX:=bg.OffX+64; bg.SegX:=bg.SegX-1; end; if (bg.SegX < 0) and (not bg.OutR) then begin bg.SegX:=0; bg.OffX:=0; end; if (bg.SegX < (1-bg.WinX)) and (bg.OutR) then begin bg.SegX:=1-bg.WinX; bg.OffX:=0; end; end; end; if bg.DirR then begin canMove:=True; if ((bg.SegX+bg.WinX) = bg.MaxX) and (bg.OffX = 0) and (not bg.OutR) then canMove:=False; if (bg.SegX = (bg.MaxX-1)) and (bg.OffX = 0) and (bg.OutR) then canMove:=False; if canMove then begin bg.OffX:=bg.OffX+bg.DifX; if bg.OffX >= 64 then begin bg.OffX:=bg.OffX-64; bg.SegX:=bg.SegX+1; end; if (bg.SegX >= (bg.MaxX-bg.WinX)) and (not bg.OutR) then begin bg.SegX:=bg.MaxX-bg.WinX; bg.OffX:=0; end; if (bg.SegX >= (bg.MaxX-1)) and (bg.OutR) then begin bg.SegX:=bg.MaxX-1; bg.OffX:=0; end; end; end; end; if (bg.DirU <> bg.DirD) then begin if bg.DirU then begin canMove:=True; if (bg.SegY = 0) and (bg.OffY = 0) and (not bg.OutR) then canMove:=False; if ((bg.SegY+bg.WinY) = 1) and (bg.OffY = 0) and (bg.OutR) then canMove:=False; if canMove then begin bg.OffY:=bg.OffY-bg.DifY; if bg.OffY < 0 then begin bg.OffY:=bg.OffY+64; bg.SegY:=bg.SegY-1; end; if (bg.SegY < 0) and (not bg.OutR) then begin bg.SegY:=0; bg.OffY:=0; end; if (bg.SegY < (1-bg.WinY)) and (bg.OutR) then begin bg.SegY:=1-bg.WinY; bg.OffY:=0; end; end; end; if bg.DirD then begin canMove:=True; if ((bg.SegY+bg.WinY) = bg.MaxY) and (bg.OffY = 0) and (not bg.OutR) then canMove:=False; if (bg.SegY = (bg.MaxY-1)) and (bg.OffY = 0) and (bg.OutR) then canMove:=False; if canMove then begin bg.OffY:=bg.OffY+bg.DifY; if bg.OffY >= 64 then begin bg.OffY:=bg.OffY-64; bg.SegY:=bg.SegY+1; end; if (bg.SegY >= (bg.MaxY-bg.WinY)) and (not bg.OutR) then begin bg.SegY:=bg.MaxY-bg.WinY; bg.OffY:=0; end; if (bg.SegY >= (bg.MaxY-1)) and (bg.OffY <> 0) and (bg.OutR) then begin bg.SegY:=bg.MaxY-1; bg.OffY:=0; end; end; end; end; end; procedure TForm3.ShowChips; var i, j: integer; iMax, jMax: integer; pNumber: integer; begin iMax:=bg.WinX-1; jMax:=bg.WinY; if bg.OffX <> 0 then iMax:=bg.WinX; if bg.OffY > 32 then jMax:=bg.WinY+1; for i:=0 to iMax do for j:=0 to jMax do begin if ((bg.SegX+i) >= 0) and ((bg.SegX+i) < bg.MaxX) and ((bg.SegY+j) >= 0) and ((bg.SegY+j) < bg.MaxY) then pNumber:=bg.Chips[bg.SegX+i,bg.SegY+j] else pNumber:=0; if pNumber in [2..4] then begin DXImageList.Items[pNumber].Draw(LevelImage.Surface, (i*64)-bg.OffX, (j*64)-bg.OffY, 0); end else begin DXImageList.Items[1].Draw(LevelImage.Surface, (i*64)-bg.OffX, (j*64)-bg.OffY, 0); DXImageList.Items[pNumber].Draw(LevelImage.Surface, (i*64)-bg.OffX, (j*64)-bg.OffY, 0); end; end; end; procedure TForm3.ShowGuy; var i, j: integer; begin i:=(gu.SegX-bg.SegX)*64 - bg.OffX + gu.OffX; j:=(gu.SegY-bg.SegY)*64 - bg.OffY + gu.OffY; DXImageList.Items[13].Draw(LevelImage.Surface, i, j, 0); end; procedure TForm3.DXTimer1Timer(Sender: TObject; LagCount: Integer); begin if LevelImage.CanDraw and (gu.DifX <> 0) then begin LevelImage.Surface.Fill(clAqua); CheckKey; DoMoveGuy; DoMoveChips; ShowChips; ShowGuy; LevelImage.Flip; end; end; var X, Y: integer; begin bg:=GBackground.Create; gu:=GGuy.Create; bg.DifX:=2; bg.DifY:=2; bg.MaxX:=50; bg.MaxY:=25; bg.WinX:=10; bg.WinY:=7; bg.SegX:=0; bg.SegY:=0; bg.OffX:=0; bg.OffY:=0; bg.OutR:=False; bg.DirL:=False; bg.DirR:=False; bg.DirU:=False; bg.DirD:=False; SetLength(bg.Chips,bg.MaxX,bg.MaxY); for X:=0 to bg.MaxX-1 do for Y:=0 to bg.MaxY-1 do begin if (odd(X) and not (odd(Y))) or (not (odd(X)) and odd(Y)) then bg.Chips[X,Y]:=1 else bg.Chips[X,Y]:=round(Random(3))+2; end; bg.Chips[0,0]:=5; bg.Chips[bg.MaxX-1,0]:=6; bg.Chips[0,bg.MaxY-1]:=7; bg.Chips[bg.MaxX-1,bg.MaxY-1]:=8; for X:=1 to bg.MaxX-2 do begin bg.Chips[X,0]:=9; bg.Chips[X,bg.MaxY-1]:=12; end; for Y:=1 to bg.MaxY-2 do begin bg.Chips[0,Y]:=10; bg.Chips[bg.MaxX-1,Y]:=11; end; {ladder} bg.Chips[2,2]:=15; bg.Chips[2,3]:=31; bg.Chips[2,4]:=16; bg.Chips[2,5]:=19; bg.Chips[2,6]:=14; bg.Chips[2,7]:=28; {rope} for X:=3 to 6 do begin bg.Chips[X,4]:=20; end; bg.Chips[1,6]:=23; bg.Chips[1,7]:=21; bg.Chips[1,8]:=29; bg.Chips[2,6]:=17; bg.Chips[7,4]:=25; {girder} for X:=3 to 6 do begin bg.Chips[X,6]:=27; end; gu.DifX:=2; gu.DifY:=2; gu.WinL:=3; gu.WinU:=1; gu.WinR:=6; gu.WinD:=4; gu.SegX:=4; gu.SegY:=3; gu.OffX:=0; gu.OffY:=0; gu.DirL:=False; gu.DirR:=False; gu.DirU:=False; gu.DirD:=False; gu.Spd:=0.005; end.
unit UCTRLSyncronization; {$mode delphi} { Copyright (c) 2018 Sphere 10 Software Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. Acknowledgements: - Herman Schoenfeld: unit creator, implementation } interface {$I ..\config.inc} uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, Buttons, UCommon.UI; type { TSyncMode } TSyncMode = (smUnset, smInitialising, smReady); { TCTRLSyncronization } TCTRLSyncronization = class(TApplicationForm) btnBack: TSpeedButton; GroupBox1: TGroupBox; imgSplash: TImage; Label16: TLabel; Label4: TLabel; Label8: TLabel; lblBlockAgeLabel: TLabel; lblBlockAgeValue: TLabel; lblBlocksFound: TLabel; lblBlockTargetLabel: TLabel; lblBlockTargetValue: TLabel; lblCurrentDifficultyCaption1: TLabel; lblCurrentDifficultyCaption2: TLabel; lblMinersClientsValue: TLabel; lblMiningStatusCaption: TLabel; lblNetProtocolVersion: TLabel; lblNodeStatus: TLabel; lblPendingOperationsLabel: TLabel; lblPendingOperationsValue: TLabel; lblProtocolVersion: TLabel; lblReceivedMessages: TLabel; lblTimeAverage: TLabel; lblTimeAverageAux: TLabel; lblTotalAccountsLabel: TLabel; lblTotalAccountsValue: TLabel; lblTotalBlocksLabel: TLabel; lblTotalBlocksValue: TLabel; paSplash: TPanel; paSync: TPanel; procedure btnBackClick(Sender: TObject); procedure lblReceivedMessagesClick(Sender:TObject); private FMinedBlocksCount: Integer; FMode : TSyncMode; procedure SetMinedBlocksCount(const Value: Integer); procedure SetSyncMode(AMode : TSyncMode); protected procedure ActivateFirstTime; override; public property MinedBlocksCount : Integer read FMinedBlocksCount write SetMinedBlocksCount; property SyncMode : TSyncMode read FMode write SetSyncMode; procedure UpdateNodeStatus; procedure UpdateBlockChainState; procedure OnFinishedLoadingDatabase; end; implementation {$R *.lfm} uses UNetProtocol,UTime,UConst, UUserInterface; procedure TCTRLSyncronization.ActivateFirstTime; begin FMode := smInitialising; paSplash.Visible:= true; paSync.Visible := false; end; procedure TCTRLSyncronization.SetSyncMode(AMode : TSyncMode); begin if FMode = AMode then exit; case AMode of smInitialising: begin TUserInterface.Enabled := false; paSplash.Visible:= true; paSync.Visible := false; end; smReady: begin TUserInterface.Enabled := true; paSplash.Visible:= false; paSync.Visible := true; end; end; end; procedure TCTRLSyncronization.UpdateNodeStatus; Var status : AnsiString; begin if not TUserInterface.Started then exit; If Not Assigned(TUserInterface.Node) then begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := 'Initializing...'; end else begin SyncMode:=smReady; If TUserInterface.Node.IsReady(status) then begin if TNetData.NetData.NetStatistics.ActiveConnections>0 then begin lblNodeStatus.Font.Color := clGreen; if TNetData.NetData.IsDiscoveringServers then begin lblNodeStatus.Caption := 'Discovering servers'; end else if TNetData.NetData.IsGettingNewBlockChainFromClient then begin lblNodeStatus.Caption := 'Obtaining new blockchain'; end else begin lblNodeStatus.Caption := 'Running'; end; end else begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := 'Alone in the world...'; end; end else begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := status; end; end; lblProtocolVersion.Caption := Format('%d (%d)', [TUserInterface.Node.Bank.SafeBox.CurrentProtocol,CT_BlockChain_Protocol_Available]); lblNetProtocolVersion.Caption := Format('%d (%d)', [CT_NetProtocol_Version, CT_NetProtocol_Available]); if NOT btnBack.Enabled then begin lblNodeStatus.Caption := 'Please wait until finished - ' + lblNodeStatus.Caption; end; end; procedure TCTRLSyncronization.UpdateBlockChainState; Var f, favg : real; begin if not TUserInterface.Started then exit; UpdateNodeStatus; if Assigned(TUserInterface.Node) then begin if TUserInterface.Node.Bank.BlocksCount>0 then begin lblTotalBlocksValue.Caption := Inttostr(TUserInterface.Node.Bank.BlocksCount)+' (0..'+Inttostr(TUserInterface.Node.Bank.BlocksCount-1)+')'; ; end else lblTotalBlocksValue.Caption := '(none)'; lblTotalAccountsValue.Caption := Inttostr(TUserInterface.Node.Bank.AccountsCount); lblBlockAgeValue.Caption := UnixTimeToLocalElapsedTime(TUserInterface.Node.Bank.LastOperationBlock.timestamp); lblPendingOperationsValue.Caption := Inttostr(TUserInterface.Node.Operations.Count); lblBlockTargetValue.Caption := InttoHex(TUserInterface.Node.Operations.OperationBlock.compact_target,8); favg := TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage); f := (CT_NewLineSecondsAvg - favg) / CT_NewLineSecondsAvg; lblTimeAverage.Caption := 'Last '+Inttostr(CT_CalcNewTargetBlocksAverage)+': '+FormatFloat('0.0',favg)+' sec. (Optimal '+Inttostr(CT_NewLineSecondsAvg)+'s) Deviation '+FormatFloat('0.00%',f*100); if favg>=CT_NewLineSecondsAvg then begin lblTimeAverage.Font.Color := clNavy; end else begin lblTimeAverage.Font.Color := clOlive; end; lblTimeAverageAux.Caption := Format('Last %d: %s sec. - %d: %s sec. - %d: %s sec. - %d: %s sec. - %d: %s sec.',[ CT_CalcNewTargetBlocksAverage * 2 ,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage * 2)), ((CT_CalcNewTargetBlocksAverage * 3) DIV 2) ,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage((CT_CalcNewTargetBlocksAverage * 3) DIV 2)), ((CT_CalcNewTargetBlocksAverage DIV 4)*3),FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(((CT_CalcNewTargetBlocksAverage DIV 4)*3))), CT_CalcNewTargetBlocksAverage DIV 2,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage DIV 2)), CT_CalcNewTargetBlocksAverage DIV 4,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage DIV 4))]); end else begin lblTotalBlocksValue.Caption := ''; lblTotalAccountsValue.Caption := ''; lblBlockAgeValue.Caption := ''; lblPendingOperationsValue.Caption := ''; lblBlockTargetValue.Caption := ''; lblTimeAverage.Caption := ''; lblTimeAverageAux.Caption := ''; end; if (Assigned(TUserInterface.PoolMiningServer)) And (TUserInterface.PoolMiningServer.Active) then begin If TUserInterface.PoolMiningServer.ClientsCount>0 then begin lblMinersClientsValue.Caption := IntToStr(TUserInterface.PoolMiningServer.ClientsCount)+' connected JSON-RPC clients'; lblMinersClientsValue.Font.Color := clNavy; end else begin lblMinersClientsValue.Caption := 'No JSON-RPC clients'; lblMinersClientsValue.Font.Color := clDkGray; end; MinedBlocksCount := TUserInterface.PoolMiningServer.ClientsWins; end else begin MinedBlocksCount := 0; lblMinersClientsValue.Caption := 'JSON-RPC server not active'; lblMinersClientsValue.Font.Color := clRed; end; end; procedure TCTRLSyncronization.SetMinedBlocksCount(const Value: Integer); begin FMinedBlocksCount := Value; lblBlocksFound.Caption := Inttostr(Value); if Value>0 then lblBlocksFound.Font.Color := clGreen else lblBlocksFound.Font.Color := clDkGray; end; procedure TCTRLSyncronization.OnFinishedLoadingDatabase; begin btnBack.Enabled:=true; TUserInterface.ShowWallet; end; procedure TCTRLSyncronization.lblReceivedMessagesClick(Sender:TObject); begin TUserInterface.ShowMessagesForm; end; procedure TCTRLSyncronization.btnBackClick(Sender: TObject); begin TUserInterface.ShowWallet; end; end.
unit MergeFields; interface uses ticklertypes; function IsADateMerge(InsertSymbol: string): boolean; function MergeFieldDesc(index: integer): string; function MergeFieldMax(ALender: TLenderInfoRecord): integer; function MergeFieldName(index: integer): string; procedure RemoveMergeField(s: string); implementation uses classes, sysutils, uStringUtils; const MergeMax = 79; MergeFieldList: array[1..MergeMax] of string = ( 'D=Letter Date', 'BN1=Borrower Name', 'BN2=2nd Borrower Name', 'LN=Letter Name', 'AD1=Borrower Address 1', 'AD2=Borrower Address 2', 'CSZ=Borrower Address 3', 'PH=Borrower Phone', 'C1=Co-Maker Name', 'C2=Co-Maker Address 1', 'C3=Co-Maker Address 2', 'C4=Co-Maker Address 3', 'OI=Officer Initials', 'ON=Officer Name', 'OT=Officer Title', 'OP=Officer Phone', 'OE=Officer Email', 'L#=Loan Number', 'LC1=Collateral #1', 'LC2=Collateral #2', 'LC3=Collateral #3', 'LC4=Collateral #4', 'CV1=Collateral Value 1', 'CV2=Collateral Value 2', 'LB=Loan Balance', 'OD=Loan Open Date', 'MD=Loan Maturity Date', 'PD=Loan Paidout Date', 'LC11=Collateral #1 - part 1', 'LC12=Collateral #1 - part 2', 'LC21=Collateral #2 - part 1', 'LC22=Collateral #2 - part 2', 'CC=Collateral Code', 'CCN=Collateral Name', 'C#=Category Number', 'CN=Category Name', 'IS=Item Sub Number', 'ID=Item Description', 'IR=Item Reference', 'IE=Item Expiration', 'INOTE=Item Note', 'NN=Institution Name', 'NA1=Institution Address 1', 'NA2=Institution Address 2', 'NA3=Institution Address 3', 'NP=Institution Phone', 'V=Division Number', 'VN=Division Name', 'BR#=Branch Number', 'BRN=Branch Name', 'BR1=Branch Address 1', 'BR2=Branch Address 2', 'BR3=Branch Address 3', 'BP=Branch Phone', 'PA1=Postal Address 1', 'PA2=Postal Address 2', 'PA3=Postal Address 3', 'PA4=Postal Address 4', 'PA5=Postal Address 5', 'MP=Map/Panel', 'MED=Map Effective Date', 'FZ=Flood Zone', 'PND=Prior Notice Date', 'RXC=Rate x Coverage', 'COV=Coverage Amt', 'DPT=Department', 'AGC=Agent Code', 'AGN=Agent Name', 'AG1=Agent Address 1', 'AG2=Agent Address 2', 'AG3=Agent Address 3', 'AGP=Agent Phone', 'AGE=Agent Email', 'PC=Payee Code', 'PCN=Payee Name', 'PDD=Premium Due Date', 'PR=Premium', 'CO=Coverage', 'CIFE=CIFEmail'); var SymbolList: TStringList; procedure BuildTheList; var x: integer; w1: widestring; TicklerSetup : TSetupRecord1; begin SymbolList.Clear; for x := 1 to MergeMax do begin W1 := MergeFieldList[x]; ReplaceNew(W1, TicklerSetup.Opts); MergeFieldList[x] := string(W1); SymbolList.add(MergeFieldList[x]); end; end; procedure RemoveMergeField(s: string); var i: integer; begin i := SymbolList.IndexOf(s); if i <> -1 then SymbolList.Delete(i); end; function MergeFieldDesc(index: integer): string; var s: string; begin s := SymbolList.Names[index]; result := SymbolList.Values[s]; end; function MergeFieldMax(ALender: TLenderInfoRecord): integer; begin result := SymbolList.count; end; function MergeFieldName(index: integer): string; begin result := SymbolList.Names[index]; end; function IsADateMerge(InsertSymbol: string): boolean; begin InsertSymbol := ' ' + trim(InsertSymbol) + ' '; result := pos(InsertSymbol, ' D MD PD OD IE MED PND ') > 0; end; initialization SymbolList := TStringList.create; BuildTheList; finalization SymbolList.free; end.
unit MainMenuChangeableMainMenuTypeSettingRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/MainMenu/MainMenuChangeableMainMenuTypeSettingRes.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> F1 Интерфейсные элементы::MainMenu::View::MainMenu::MainMenuChangeableMainMenuTypeSettingRes // // Ресурсы для настройки "Тип изменяемой части основного меню" // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces, afwInterfaces, l3CProtoObject, l3StringIDEx ; type ChangeableMainMenuTypeEnum = ( {* Ключи для настройки "Тип изменяемой части основного меню" } KEY_ChangeableMainMenuType_ST_FINANCE // Налоги и финансы , KEY_ChangeableMainMenuType_ST_HR // Раздел для кадровиков , KEY_ChangeableMainMenuType_ST_LEGAL // Раздел для юристов , KEY_ChangeableMainMenuType_ST_BUDGET_ORGS // Бюджетные организаций );//ChangeableMainMenuTypeEnum const { ChangeableMainMenuTypeKey } pi_MainMenu_ChangeableMainMenuType = '/Тип изменяемой части основного меню'; { Идентификатор настройки "Тип изменяемой части основного меню" } dv_MainMenu_ChangeableMainMenuType = 0; { Значение по-умолчанию настройки "Тип изменяемой части основного меню" } var { Локализуемые строки ChangeableMainMenuTypeName } str_ChangeableMainMenuType : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangeableMainMenuType'; rValue : 'Тип изменяемой части основного меню'); { Тип изменяемой части основного меню } var { Локализуемые строки ChangeableMainMenuTypeValues } str_ChangeableMainMenuType_ST_FINANCE : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangeableMainMenuType_ST_FINANCE'; rValue : 'Налоги и финансы'); { Налоги и финансы } str_ChangeableMainMenuType_ST_HR : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangeableMainMenuType_ST_HR'; rValue : 'Раздел для кадровиков'); { Раздел для кадровиков } str_ChangeableMainMenuType_ST_LEGAL : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangeableMainMenuType_ST_LEGAL'; rValue : 'Раздел для юристов'); { Раздел для юристов } str_ChangeableMainMenuType_ST_BUDGET_ORGS : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ChangeableMainMenuType_ST_BUDGET_ORGS'; rValue : 'Бюджетные организаций'); { Бюджетные организаций } const { Карта преобразования локализованных строк ChangeableMainMenuTypeValues } ChangeableMainMenuTypeValuesMap : array [ChangeableMainMenuTypeEnum] of Pl3StringIDEx = ( @str_ChangeableMainMenuType_ST_FINANCE , @str_ChangeableMainMenuType_ST_HR , @str_ChangeableMainMenuType_ST_LEGAL , @str_ChangeableMainMenuType_ST_BUDGET_ORGS );//ChangeableMainMenuTypeValuesMap type ChangeableMainMenuTypeValuesMapHelper = {final} class {* Утилитный класс для преобразования значений ChangeableMainMenuTypeValuesMap } public // public methods class procedure FillStrings(const aStrings: IafwStrings); {* Заполнение списка строк значениями } class function DisplayNameToValue(const aDisplayName: Il3CString): ChangeableMainMenuTypeEnum; {* Преобразование строкового значения к порядковому } end;//ChangeableMainMenuTypeValuesMapHelper TChangeableMainMenuTypeValuesMapImplPrim = {abstract} class(Tl3CProtoObject, Il3IntegerValueMap) {* Класс для реализации мапы для ChangeableMainMenuTypeValuesMap } protected // realized methods function pm_GetMapID: Tl3ValueMapID; procedure GetDisplayNames(const aList: Il3StringsEx); {* заполняет список значениями "UI-строка" } function MapSize: Integer; {* количество элементов в мапе. } function DisplayNameToValue(const aDisplayName: Il3CString): Integer; function ValueToDisplayName(aValue: Integer): Il3CString; public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TChangeableMainMenuTypeValuesMapImplPrim } end;//TChangeableMainMenuTypeValuesMapImplPrim TChangeableMainMenuTypeValuesMapImpl = {final} class(TChangeableMainMenuTypeValuesMapImplPrim) {* Класс для реализации мапы для ChangeableMainMenuTypeValuesMap } public // public methods class function Make: Il3IntegerValueMap; reintroduce; {* Фабричный метод для TChangeableMainMenuTypeValuesMapImpl } end;//TChangeableMainMenuTypeValuesMapImpl {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3MessageID, l3String, SysUtils, l3Base ; // start class ChangeableMainMenuTypeValuesMapHelper class procedure ChangeableMainMenuTypeValuesMapHelper.FillStrings(const aStrings: IafwStrings); var l_Index: ChangeableMainMenuTypeEnum; begin aStrings.Clear; for l_Index := Low(l_Index) to High(l_Index) do aStrings.Add(ChangeableMainMenuTypeValuesMap[l_Index].AsCStr); end;//ChangeableMainMenuTypeValuesMapHelper.FillStrings class function ChangeableMainMenuTypeValuesMapHelper.DisplayNameToValue(const aDisplayName: Il3CString): ChangeableMainMenuTypeEnum; var l_Index: ChangeableMainMenuTypeEnum; begin for l_Index := Low(l_Index) to High(l_Index) do if l3Same(aDisplayName, ChangeableMainMenuTypeValuesMap[l_Index].AsCStr) then begin Result := l_Index; Exit; end;//l3Same.. raise Exception.CreateFmt('Display name "%s" not found in map "ChangeableMainMenuTypeValuesMap"', [l3Str(aDisplayName)]); end;//ChangeableMainMenuTypeValuesMapHelper.DisplayNameToValue // start class TChangeableMainMenuTypeValuesMapImplPrim class function TChangeableMainMenuTypeValuesMapImplPrim.Make: Il3IntegerValueMap; var l_Inst : TChangeableMainMenuTypeValuesMapImplPrim; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TChangeableMainMenuTypeValuesMapImplPrim.pm_GetMapID: Tl3ValueMapID; {-} begin l3FillChar(Result, SizeOf(Result)); Assert(false); end;//TChangeableMainMenuTypeValuesMapImplPrim.pm_GetMapID procedure TChangeableMainMenuTypeValuesMapImplPrim.GetDisplayNames(const aList: Il3StringsEx); {-} begin ChangeableMainMenuTypeValuesMapHelper.FillStrings(aList); end;//TChangeableMainMenuTypeValuesMapImplPrim.GetDisplayNames function TChangeableMainMenuTypeValuesMapImplPrim.MapSize: Integer; {-} begin Result := Ord(High(ChangeableMainMenuTypeEnum)) - Ord(Low(ChangeableMainMenuTypeEnum)); end;//TChangeableMainMenuTypeValuesMapImplPrim.MapSize function TChangeableMainMenuTypeValuesMapImplPrim.DisplayNameToValue(const aDisplayName: Il3CString): Integer; {-} begin Result := Ord(ChangeableMainMenuTypeValuesMapHelper.DisplayNameToValue(aDisplayName)); end;//TChangeableMainMenuTypeValuesMapImplPrim.DisplayNameToValue function TChangeableMainMenuTypeValuesMapImplPrim.ValueToDisplayName(aValue: Integer): Il3CString; {-} begin Assert(aValue >= Ord(Low(ChangeableMainMenuTypeEnum))); Assert(aValue <= Ord(High(ChangeableMainMenuTypeEnum))); Result := ChangeableMainMenuTypeValuesMap[ChangeableMainMenuTypeEnum(aValue)].AsCStr; end;//TChangeableMainMenuTypeValuesMapImplPrim.ValueToDisplayName // start class TChangeableMainMenuTypeValuesMapImpl var g_TChangeableMainMenuTypeValuesMapImpl : Pointer = nil; procedure TChangeableMainMenuTypeValuesMapImplFree; begin IUnknown(g_TChangeableMainMenuTypeValuesMapImpl) := nil; end; class function TChangeableMainMenuTypeValuesMapImpl.Make: Il3IntegerValueMap; begin if (g_TChangeableMainMenuTypeValuesMapImpl = nil) then begin l3System.AddExitProc(TChangeableMainMenuTypeValuesMapImplFree); Il3IntegerValueMap(g_TChangeableMainMenuTypeValuesMapImpl) := inherited Make; end; Result := Il3IntegerValueMap(g_TChangeableMainMenuTypeValuesMapImpl); end; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ChangeableMainMenuType str_ChangeableMainMenuType.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ChangeableMainMenuType_ST_FINANCE str_ChangeableMainMenuType_ST_FINANCE.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ChangeableMainMenuType_ST_HR str_ChangeableMainMenuType_ST_HR.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ChangeableMainMenuType_ST_LEGAL str_ChangeableMainMenuType_ST_LEGAL.Init; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Инициализация str_ChangeableMainMenuType_ST_BUDGET_ORGS str_ChangeableMainMenuType_ST_BUDGET_ORGS.Init; {$IfEnd} //not Admin AND not Monitorings end.
{ This file is part of the Free Pascal run time library. A file in Amiga system run time library. Copyright (c) 1998-2003 by Nils Sjoholm member of the Amiga RTL development team. See the file COPYING.FPC, included in this distribution, for details about the copyright. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. **********************************************************************} { History: Added the defines use_amiga_smartlink and use_auto_openlib. Implemented autoopening of the library. 13 Jan 2003. Changed cardinal > longword. 09 Feb 2003. nils.sjoholm@mailbox.swipnet.se Nils Sjoholm } {$I useamigasmartlink.inc} {$ifdef use_amiga_smartlink} {$smartlink on} {$endif use_amiga_smartlink} UNIT colorwheel; INTERFACE USES exec, utility; Type { For use with the WHEEL_HSB tag } pColorWheelHSB = ^tColorWheelHSB; tColorWheelHSB = record cw_Hue, cw_Saturation, cw_Brightness : ULONG; end; { For use with the WHEEL_RGB tag } pColorWheelRGB = ^tColorWheelRGB; tColorWheelRGB = record cw_Red, cw_Green, cw_Blue : ULONG; end; {***************************************************************************} const WHEEL_Dummy = (TAG_USER+$04000000); WHEEL_Hue = (WHEEL_Dummy+1) ; { set/get Hue } WHEEL_Saturation = (WHEEL_Dummy+2) ; { set/get Saturation } WHEEL_Brightness = (WHEEL_Dummy+3) ; { set/get Brightness } WHEEL_HSB = (WHEEL_Dummy+4) ; { set/get ColorWheelHSB } WHEEL_Red = (WHEEL_Dummy+5) ; { set/get Red } WHEEL_Green = (WHEEL_Dummy+6) ; { set/get Green } WHEEL_Blue = (WHEEL_Dummy+7) ; { set/get Blue } WHEEL_RGB = (WHEEL_Dummy+8) ; { set/get ColorWheelRGB } WHEEL_Screen = (WHEEL_Dummy+9) ; { init screen/enviroment } WHEEL_Abbrv = (WHEEL_Dummy+10); { "GCBMRY" if English } WHEEL_Donation = (WHEEL_Dummy+11); { colors donated by app } WHEEL_BevelBox = (WHEEL_Dummy+12); { inside a bevel box } WHEEL_GradientSlider = (WHEEL_Dummy+13); { attached gradient slider } WHEEL_MaxPens = (WHEEL_Dummy+14); { max # of pens to allocate } {***************************************************************************} {--- functions in V39 or higher (Release 3) ---} VAR ColorWheelBase : pLibrary; const COLORWHEELNAME : Pchar = 'colorwheel.library'; PROCEDURE ConvertHSBToRGB(hsb : pColorWheelHSB; rgb : pColorWheelRGB); PROCEDURE ConvertRGBToHSB(rgb : pColorWheelRGB; hsb : pColorWheelHSB); IMPLEMENTATION uses msgbox; PROCEDURE ConvertHSBToRGB(hsb : pColorWheelHSB; rgb : pColorWheelRGB); BEGIN ASM MOVE.L A6,-(A7) MOVEA.L hsb,A0 MOVEA.L rgb,A1 MOVEA.L ColorWheelBase,A6 JSR -030(A6) MOVEA.L (A7)+,A6 END; END; PROCEDURE ConvertRGBToHSB(rgb : pColorWheelRGB; hsb : pColorWheelHSB); BEGIN ASM MOVE.L A6,-(A7) MOVEA.L rgb,A0 MOVEA.L hsb,A1 MOVEA.L ColorWheelBase,A6 JSR -036(A6) MOVEA.L (A7)+,A6 END; END; {$I useautoopenlib.inc} {$ifdef use_auto_openlib} {$Info Compiling autoopening of colorwheel.library} var colorwheel_exit : Pointer; procedure ClosecolorwheelLibrary; begin ExitProc := colorwheel_exit; if ColorWheelBase <> nil then begin CloseLibrary(ColorWheelBase); ColorWheelBase := nil; end; end; const { Change VERSION and LIBVERSION to proper values } VERSION : string[2] = '0'; LIBVERSION : longword = 0; begin ColorWheelBase := nil; ColorWheelBase := OpenLibrary(COLORWHEELNAME,LIBVERSION); if ColorWheelBase <> nil then begin colorwheel_exit := ExitProc; ExitProc := @ClosecolorwheelLibrary end else begin MessageBox('FPC Pascal Error', 'Can''t open colorwheel.library version ' + VERSION + #10 + 'Deallocating resources and closing down', 'Oops'); halt(20); end; {$else} {$Warning No autoopening of colorwheel.library compiled} {$Info Make sure you open colorwheel.library yourself} {$endif use_auto_openlib} END. (* UNIT COLORWHEEL *)
unit ReflectionUnit; interface uses System.Windows.Forms, System.Reflection, System.Drawing, Borland.Delphi.SysUtils; type ReflectionForm = class(System.Windows.Forms.Form) private mainMenu : System.Windows.Forms.MainMenu; fileMenu : System.Windows.Forms.MenuItem; separatorItem : System.Windows.Forms.MenuItem; openItem : System.Windows.Forms.MenuItem; exitItem : System.Windows.Forms.MenuItem; showFileLabel : System.Windows.Forms.Label; typesListBox : System.Windows.Forms.ListBox; openFileDialog : System.WIndows.Forms.OpenFileDialog; protected procedure InitializeMenu; procedure InitializeControls; procedure PopulateTypes(fileName : String); { Event Handlers } procedure exitItemClick(sender : TObject; Args : System.EventArgs); procedure openItemClick(sender : TObject; Args : System.EventArgs); public constructor Create; end; implementation constructor ReflectionForm.Create; begin inherited Create; SuspendLayout; InitializeMenu; InitializeControls; { Initialize the form and other member variables } openFileDialog := System.Windows.Forms.OpenFileDialog.Create; openFileDialog.Filter := 'Assemblies (*.dll;*.exe)|*.dll;*.exe'; openFileDialog.Title := 'Open an assembly'; AutoScaleBaseSize := System.Drawing.Size.Create(5, 13); ClientSize := System.Drawing.Size.Create(631, 357); Menu := mainMenu; Name := 'reflectionForm'; Text := 'Reflection in Delphi for .NET'; { Add the controls to the form's collection. } Controls.Add(showFileLabel); Controls.Add(typesListBox); ResumeLayout; end; procedure ReflectionForm.InitializeMenu; var menuItemArray : array of System.Windows.Forms.MenuItem; begin mainMenu := System.Windows.Forms.MainMenu.Create; fileMenu := System.Windows.Forms.MenuItem.Create; openItem := System.Windows.Forms.MenuItem.Create; separatorItem := System.Windows.Forms.MenuItem.Create; exitItem := System.Windows.Forms.MenuItem.Create; { Initialize mainMenu } mainMenu.MenuItems.Add(fileMenu); { Initialize fileMenu } fileMenu.Index := 0; SetLength(menuItemArray, 3); menuItemArray[0] := openItem; menuItemArray[1] := separatorItem; menuItemArray[2] := exitItem; fileMenu.MenuItems.AddRange(menuItemArray); fileMenu.Text := '&File'; // openItem openItem.Index := 0; openItem.Text := '&Open...'; openItem.add_Click(openItemClick); // separatorItem separatorItem.Index := 1; separatorItem.Text := '-'; // exitItem exitItem.Index := 2; exitItem.Text := 'E&xit'; exitItem.add_Click(exitItemClick); end; procedure ReflectionForm.InitializeControls; begin { Initialize showFileLabel } showFileLabel := System.Windows.Forms.Label.Create; showFileLabel.Location := System.Drawing.Point.Create(5, 6); showFileLabel.Name := 'showFileLabel'; showFileLabel.Size := System.Drawing.Size.Create(616, 37); showFileLabel.TabIndex := 0; showFileLabel.Anchor := System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Left or System.Windows.Forms.AnchorStyles.Right; showFileLabel.Text := 'Showing types in: '; { Initialize typesListBox } typesListBox := System.Windows.Forms.ListBox.Create; typesListBox.Anchor := System.Windows.Forms.AnchorStyles.Top or System.Windows.Forms.AnchorStyles.Bottom or System.Windows.Forms.AnchorStyles.Left or System.Windows.Forms.AnchorStyles.Right; typesListBox.Location := System.Drawing.Point.Create(8, 46); typesListBox.Name := 'typesListBox'; typesListBox.Size := System.Drawing.Size.Create(610, 303); typesListBox.Font := System.Drawing.Font.Create('Lucida Console', 8.25, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); typesListBox.TabIndex := 1; end; procedure ReflectionForm.exitItemClick(sender : TObject; Args : System.EventArgs); begin System.Windows.Forms.Application.Exit; end; procedure ReflectionForm.openItemClick(sender : TObject; Args : System.EventArgs); begin if openFileDialog.ShowDialog = DialogResult.OK then begin showFileLabel.Text := 'Showing types in: ' + openFileDialog.FileName; PopulateTypes(openFileDialog.FileName); end; end; procedure ReflectionForm.PopulateTypes(fileName : String); var assy : System.Reflection.Assembly; modules : array of System.Reflection.Module; module : System.Reflection.Module; types : array of System.Type; t : System.Type; members : array of System.Reflection.MemberInfo; m : System.Reflection.MemberInfo; i,j,k : Integer; s : String; begin try { Clear the listbox } typesListBox.BeginUpdate; typesListBox.Items.Clear; { Load the assembly and get its modules } assy := System.Reflection.Assembly.LoadFrom(fileName); modules := assy.GetModules; {For every module, get all types } for i := 0 to High(modules) do begin module := modules[i]; types := module.GetTypes; { For every type, get all of its members } for j := 0 to High(types) do begin t := types[j]; members := t.GetMembers; { for every member, get type information and add to list box } for k := 0 to High(members) do begin m := members[k]; s := module.Name + ':' + t.Name + ': ' + m.Name + ' (' + m.MemberType.ToString + ')'; typesListBox.Items.Add(s); end; end; end; typesListBox.EndUpdate; except System.Windows.Forms.MessageBox.Show('Could not load the assembly.'); end; end; end.
unit MVCBr.NavigatorModel; interface uses System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.Model, MVCBr.Controller; Type TNavigatorModelFactory = class(TModelFactory, INavigatorModel) protected FController:IController; public function Controller(const AController: IController): INavigatorModel; end; implementation { TPersistentModelFactory } function TNavigatorModelFactory.Controller(const AController: IController) : INavigatorModel; begin FController := AController; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Core.BehaviorTree; interface uses System.Classes, System.Generics.Collections, System.Generics.Defaults, System.JSON, Behavior3, Behavior3.Core.Tick, Behavior3.Core.Blackboard; type (** * The BehaviorTree class, as the name implies, represents the Behavior Tree * structure. * * There are two ways to construct a Behavior Tree: by manually setting the * root node, or by loading it from a data structure (which can be loaded * from a JSON). Both methods are shown in the examples below and better * explained in the user guide. * * The tick method must be called periodically, in order to send the tick * signal to all nodes in the tree, starting from the root. The method * `BehaviorTree.tick` receives a target object and a blackboard as * parameters. The target object can be anything: a game agent, a system, a * DOM object, etc. This target is not used by any piece of Behavior3JS, * i.e., the target object will only be used by custom nodes. * * The blackboard is obligatory and must be an instance of `Blackboard`. This * requirement is necessary due to the fact that neither `BehaviorTree` or * any node will store the execution variables in its own object (e.g., the * BT does not store the target, information about opened nodes or number of * times the tree was called). But because of this, you only need a single * tree instance to control multiple (maybe hundreds) objects. * * Manual construction of a Behavior Tree * -------------------------------------- * * var tree = new b3.BehaviorTree(); * * tree.root = new b3.Sequence({children:[ * new b3.Priority({children:[ * new MyCustomNode(), * new MyCustomNode() * ]}), * ... * ]}); * * * Loading a Behavior Tree from data structure * ------------------------------------------- * * var tree = new b3.BehaviorTree(); * * tree.load({ * 'title' : 'Behavior Tree title' * 'description' : 'My description' * 'root' : 'node-id-1' * 'nodes' : { * 'node-id-1' : { * 'name' : 'Priority', // this is the node type * 'title' : 'Root Node', * 'description' : 'Description', * 'children' : ['node-id-2', 'node-id-3'], * }, * ... * } * }) * * * @module b3 * @class BehaviorTree **) TB3BehaviorTree = class(TObject) public (** * The tree id, must be unique. By default, created with `b3.createUUID`. * @property {String} id * @readOnly **) Id: String; (** * The tree title. * @property {String} title * @readonly **) Title: String; (** * Description of the tree. * @property {String} description * @readonly **) Description: String; (** * Scope of the tree. * @property {String} scope * @readonly **) Scope: String; (** * Behavior version of the tree. * @property {String} version * @readonly **) Version: String; (** * The reference to the root node. Must be an instance of `b3.BaseNode`. * @property {BaseNode} root **) FRoot: TObject; // Use Behavior3.Helper for accessing as Root: TB3BaseNode; (** * The reference to the debug instance. * @property {Object} debug **) Debug: TObject; (** * A dictionary with nodes. Useful to during loading * * @property {Object} fnodes * @readonly **) FNodes: TObject; // Use Behavior3.Helper for accessing as Nodes: TB3BaseNodeDictionary; (** * Initialization method. * @method initialize * @constructor **) constructor Create; virtual; destructor Destroy; override; (** * This method loads a Behavior Tree from a data structure, populating this * object with the provided data. Notice that, the data structure must * follow the format specified by Behavior3JS. Consult the guide to know * more about this format. * * You probably want to use custom nodes in your BTs, thus, you need to * provide the `names` object, in which this method can find the nodes by * `names[NODE_NAME]`. This variable can be a namespace or a dictionary, * as long as this method can find the node by its name, for example: * * //json * ... * 'node1': { * 'name': MyCustomNode, * 'title': ... * } * ... * * //code * var bt = new b3.BehaviorTree(); * bt.load(data, {'MyCustomNode':MyCustomNode}) * * * @method load * @param {Object} data The data structure representing a Behavior Tree. * @param {Object} [names] A namespace or dict containing custom nodes. **) procedure Load (Data: String; NodeTypes: TObject = NIL); overload; virtual; procedure Load (JsonTree: TJSONObject; NodeTypes: TObject = NIL); overload; virtual; procedure Load (Stream: TStream; NodeTypes: TObject = NIL); overload; virtual; (** * This method dump the current BT into a data structure. * * Note: This method does not record the current node parameters. Thus, * it may not be compatible with load for now. * * @method dump * @return {Object} A data object representing this tree. **) function Dump: TObject; virtual; (** * Propagates the tick signal through the tree, starting from the root. * * This method receives a target object of any type (Object, Array, * DOMElement, whatever) and a `Blackboard` instance. The target object has * no use at all for all Behavior3JS components, but surely is important * for custom nodes. The blackboard instance is used by the tree and nodes * to store execution variables (e.g., last node running) and is obligatory * to be a `Blackboard` instance (or an object with the same interface). * * Internally, this method creates a Tick object, which will store the * target and the blackboard objects. * * Note: BehaviorTree stores a list of open nodes from last tick, if these * nodes weren't called after the current tick, this method will close them * automatically. * * @method tick * @param {Object} target A target object. * @param {Blackboard} blackboard An instance of blackboard object. * @return {Constant} The tick signal state. **) function Tick(Target: TObject; Blackboard: TB3Blackboard): TB3Status; virtual; end; TB3BehaviorTreeDictionary = class(TObjectDictionary<String, TB3BehaviorTree>) public SelectedTree: TB3BehaviorTree; Scope: String; Version: String; procedure Load (Data: String; NodeTypes: TObject = NIL); overload; virtual; procedure Load (JsonTree: TJSONObject; NodeTypes: TObject = NIL); overload; virtual; procedure Load (Stream: TStream; NodeTypes: TObject = NIL); overload; virtual; end; implementation { TB3BehaviorTree } uses Behavior3.NodeTypes, Behavior3.Helper, Behavior3.Core.BaseNode, System.Math, System.SysUtils; constructor TB3BehaviorTree.Create; begin inherited; Nodes := TB3BaseNodeDictionary.Create([doOwnsValues]); end; destructor TB3BehaviorTree.Destroy; begin Nodes.Free; inherited; end; function TB3BehaviorTree.Dump: TObject; begin Result := NIL; end; procedure TB3BehaviorTree.Load(Data: String; NodeTypes: TObject = NIL); var JsonTree: TJSONObject; begin JsonTree := TJSONObject.ParseJSONValue(Data, False) as TJSONObject; try Load(JsonTree, NodeTypes); finally JsonTree.Free; end; end; procedure TB3BehaviorTree.Load(Stream: TStream; NodeTypes: TObject); var StreamReader: TStreamReader; Data: String; begin StreamReader := TStreamReader.Create(Stream); try Data := StreamReader.ReadToEnd; Load(Data, NodeTypes); finally StreamReader.Free; end; end; procedure TB3BehaviorTree.Load(JsonTree: TJSONObject; NodeTypes: TObject); var JsonNodes: TJSONArray; JsonNode: TJSONValue; JsonNodeObj: TJSONValue; NodeName: String; Node: TB3BaseNode; NodeId: String; ClassNodeTypes: TB3NodeTypes; begin // If not yet assigned NodeTypes (or wrong class type) then create and use global B3NodeTypes if Assigned(NodeTypes) and (NodeTypes.InheritsFrom(TB3NodeTypes)) then ClassNodeTypes := TB3NodeTypes(NodeTypes) else begin if not Assigned(B3NodeTypes) then B3NodeTypes := TB3NodeTypes.Create; ClassNodeTypes := B3NodeTypes; end; Nodes.Clear; Version := JsonTree.GetValue('version', Version); Scope := JsonTree.GetValue('scope', Scope); Id := JsonTree.GetValue('id', Id); Title := JsonTree.GetValue('title', Title); Description := JsonTree.GetValue('description', Description); // Create all nodes JsonNodes := TJSONArray(JsonTree.Get('nodes').JsonValue); for JsonNodeObj in JsonNodes do begin JsonNode := TJSONPair(JSonNodeObj).JsonValue; NodeName := JsonNode.GetValue('name', ''); Node := ClassNodeTypes.CreateNode(NodeName); Node.Id := JsonNode.GetValue('id', ''); Node.Tree := Self; Nodes.Add(Node.Id, Node); end; // Load and link nodes for JsonNodeObj in JsonNodes do begin JsonNode := TJSONPair(JSonNodeObj).JsonValue; NodeId := JsonNode.GetValue('id', ''); Node := Nodes[NodeId]; Node.Load(JsonNode); end; // Set root node Root := Nodes[JsonTree.GetValue('root', '')]; end; function TB3BehaviorTree.Tick(Target: TObject; Blackboard: TB3Blackboard): TB3Status; var Tick: TB3Tick; State: TB3Status; CurrOpenNodes, LastOpenNodes: TB3BaseNodeList; Start, I: Integer; begin if not Assigned(Blackboard) then raise EB3ParameterMissingException.Create('The blackboard parameter is obligatory and must be an ' + 'instance of b3.Blackboard'); if not Assigned(Root) then raise EB3RootMissingException.Create('Node root not defined'); //* CREATE A TICK OBJECT */ Tick := TB3Tick.Create; Tick.Debug := Self; Tick.Target := Target; Tick.Blackboard := Blackboard; Tick.Tree := Self; //* TICK NODE */ State := Root._Execute(Tick); //* CLOSE NODES FROM LAST TICK, IF NEEDED */ LastOpenNodes := TB3Blackboard(blackboard).Get('openNodes', Id).AsObject as TB3BaseNodeList; CurrOpenNodes := Tick._OpenNodes; // process only if there are LastOpenNodes if Assigned(LastOpenNodes) then begin // does not close if it is still open in this tick Start := 0; for I := 0 to Min(LastOpenNodes.Count, CurrOpenNodes.Count) - 1 do begin Start := I + 1; if LastOpenNodes[I] <> CurrOpenNodes[I] then break end; // close the nodes // for (i=lastOpenNodes.length-1; i>=start; i--) { for I := LastOpenNodes.Count - 1 downto Start do LastOpenNodes[I]._Close(Tick); // LastOpenNodes will be overwritten in the Blackboard by CurrOpenNodes LastOpenNodes.Free; end; //* POPULATE BLACKBOARD */ TB3Blackboard(blackboard).&Set('openNodes', CurrOpenNodes, Id); TB3Blackboard(blackboard).&Set('nodeCount', Tick._NodeCount, Id); // Open nodes are now stored in the blackboard Tick.F_OpenNodes := NIL; Tick.Free; Result := State; end; { TB3BehaviorTreeList } procedure TB3BehaviorTreeDictionary.Load(Data: String; NodeTypes: TObject); var JsonTree: TJSONObject; begin JsonTree := TJSONObject.ParseJSONValue(Data, False) as TJSONObject; try Load(JsonTree, NodeTypes); finally JsonTree.Free; end; end; procedure TB3BehaviorTreeDictionary.Load(Stream: TStream; NodeTypes: TObject); var StreamReader: TStreamReader; Data: String; begin StreamReader := TStreamReader.Create(Stream); try Data := StreamReader.ReadToEnd; Load(Data, NodeTypes); finally StreamReader.Free; end; end; procedure TB3BehaviorTreeDictionary.Load(JsonTree: TJSONObject; NodeTypes: TObject); var JsonNodes: TJSONArray; JsonNodeObj: TJSONValue; ClassNodeTypes: TB3NodeTypes; Tree: TB3BehaviorTree; begin // If not yet assigned NodeTypes (or wrong class type) then create and use global B3NodeTypes if Assigned(NodeTypes) and (NodeTypes.InheritsFrom(TB3NodeTypes)) then ClassNodeTypes := TB3NodeTypes(NodeTypes) else begin if not Assigned(B3NodeTypes) then B3NodeTypes := TB3NodeTypes.Create; ClassNodeTypes := B3NodeTypes; end; Version := JsonTree.GetValue('version', Version); Scope := JsonTree.GetValue('scope', Scope); // Create all trees JsonNodes := TJSONArray(JsonTree.Get('trees').JsonValue); for JsonNodeObj in JsonNodes do begin Tree := TB3BehaviorTree.Create; Tree.Load(TJSONObject(JsonNodeObj), ClassNodeTypes); Add(Tree.Id, Tree); end; // Set selected tree SelectedTree := Items[JsonTree.GetValue('selectedTree', '')]; end; end.
{*******************************************************} { Проект: Repository } { Модуль: uDbPersistents.pas } { Описание: Интерфейс хранимых в БД объектов } { Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) } { } { Распространяется по лицензии GPLv3 } {*******************************************************} unit uDbPersistents; interface uses Db; type IDbPersistent = interface(IInterface) ['{0CCC29F3-1740-4E4B-A90D-DF4D78151973}'] function Load(ADataSet: TDataSet): Boolean; stdcall; procedure Save(ADataSet: TDataSet); stdcall; end; implementation end.
{ * Class to access memory of Windows process. * * Stream begin is base of module. * Stream size is size of image of target module. } unit PE.ProcessModuleStream; interface uses System.Classes, System.SysUtils, WinApi.PsApi, WinApi.TlHelp32, WinApi.Windows, WinHelper; type TProcessModuleStream = class(TStream) private FProcessHandle: THandle; FModuleBase: NativeUInt; FModuleSize: DWORD; private FCurrentRVA: UInt64; public constructor Create(ProcessID: DWORD; const me: TModuleEntry32); // Create from known process ID. Module base is found from ModuleName. // If process id is invalid or no module found exception raised. constructor CreateFromPidAndModuleName(ProcessID: DWORD; const ModuleName: string); constructor CreateFromPidAndAddress(ProcessID: DWORD; Address: NativeUInt); // Create from known process id. Main module used (i.e. started exe). constructor CreateFromPid(ProcessID: DWORD); destructor Destroy; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; function Read(var Buffer; Count: Longint): Longint; override; property ModuleBase: NativeUInt read FModuleBase; end; implementation { TProcessModuleStream } procedure RaiseFailedToFindModule; begin raise Exception.Create('Failed to find main module.'); end; constructor TProcessModuleStream.Create(ProcessID: DWORD; const me: TModuleEntry32); begin inherited Create; FProcessHandle := OpenProcess(MAXIMUM_ALLOWED, False, ProcessID); if FProcessHandle = 0 then RaiseLastOSError; FModuleBase := NativeUInt(me.modBaseAddr); FModuleSize := me.modBaseSize; end; constructor TProcessModuleStream.CreateFromPidAndModuleName(ProcessID: DWORD; const ModuleName: string); var me: TModuleEntry32; begin if not FindModuleByName(ProcessID, ModuleName) then RaiseFailedToFindModule; Create(ProcessID, me); end; constructor TProcessModuleStream.CreateFromPidAndAddress(ProcessID: DWORD; Address: NativeUInt); var me: TModuleEntry32; begin if not FindModuleByAddress(ProcessID, Address, me) then RaiseFailedToFindModule; Create(ProcessID, me); end; constructor TProcessModuleStream.CreateFromPid(ProcessID: DWORD); var me: TModuleEntry32; begin if not FindMainModule(ProcessID, me) then RaiseFailedToFindModule; Create(ProcessID, me); end; destructor TProcessModuleStream.Destroy; begin CloseHandle(FProcessHandle); inherited; end; function TProcessModuleStream.Read(var Buffer; Count: Integer): Longint; var p: pbyte; done: NativeUInt; begin p := pbyte(FModuleBase) + FCurrentRVA; done := 0; ReadProcessMemory(FProcessHandle, p, @Buffer, Count, done); inc(FCurrentRVA, done); Result := done; end; function TProcessModuleStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin case Origin of soBeginning: FCurrentRVA := Offset; soCurrent: FCurrentRVA := FCurrentRVA + Offset; soEnd: FCurrentRVA := FModuleSize + Offset; end; Result := FCurrentRVA; end; end.
unit ATxWMP; interface function IsWMP6Installed: boolean; function IsWMP9Installed: boolean; implementation uses Windows, SysUtils, ComObj, ATxRegistry, ATxUtils; function IsGUIDInstalled(const GUID: TGUID): boolean; const sDefault = ''; begin Result:= GetRegKeyStr(HKEY_LOCAL_MACHINE, PChar('SOFTWARE\Classes\TypeLib\'+GUIDToString(GUID)+'\1.0\0\win32'), '', sDefault) <> sDefault; end; const LIBID_MediaPlayer: TGUID = '{22D6F304-B0F6-11D0-94AB-0080C74C7E95}'; LIBID_MediaPlayer9: TGUID = '{6BF52A50-394A-11D3-B153-00C04F79FAA6}'; function IsWMP6Installed: boolean; begin Result:= IsWindowsVista or IsGUIDInstalled(LIBID_MediaPlayer); end; function IsWMP9Installed: boolean; begin Result:= IsWindowsVista or IsGUIDInstalled(LIBID_MediaPlayer9); end; end.
{----------------------------------------------------------------------------- Application: DataPullWizard.exe Unit Name: formWizard Author: J. L. Vasser Date: 2019-06-10 Purpose: Derived from "New Data Pull" utility, FMCSA, October 2017. "This utility reads data from the Production SAFER database schema to create a Carrier Data database for Aspen 3.x (and future ISS 4.x) This utility requires the user to be connected to the AWS environment, either by VPN or by running this from a server within the AWS cloud. The Aspen ISS_FED_DATA.FDB Firebird data file must be present and accessible to the utility. An Oracle TNSNAMES.ORA file with the connection information for production SAFER must be in the same directory with the application." This version derived from "NewDataPull" incorporates much of the same code but uses a wizard-style input screen. For Aspen 3.0 this utility will create a Firebird database file. For Aspen 3.2 and beyond, the file will be SQLite format. This wizard has been developed as both a test of the components used and also to make the steps more clear to a new user. (This utility is intended for a technical user, not for general distribution.) History: This is based on code and concept of Dottie West, UGPTI (NDSU) The utility was modified to use Devart UniDAC components for faster response. Additionally, the GUI was modified some to provide progress feedback. 2018-02-05 JLV - Changes to SAFER Queries. See data module. 2018-02-07 JLV - Modifed query on UCR to limit the amount of (useless) data returned. See DoUCRLoad function. 2018-02-14 JLV - Removed unused procedures and functions. General code clean-up 2018-08-13 JLV - Added Secure BlackBox Zip component to dlgZipProgess. File compression within this utility now works 2019-02-03 JLV - Modifications to also create ISS data in SQLite format for speed and smaller size. The Firebird database is being maintained for compatibility with Aspen 3.0. The SQLite version will be for Aspen versions 3.2 and later. (There is no 3.1). 2019-02-04 JLV - Added global variable "dbSelected". Set by radio buttons on the main form, 0 indicates the user has selected the Firebird database while 1 indicates the user has selected the SQLite database. 2019-04-16 JLV - Added short code snippet and dialog to allow for quick changing between AWS and ADDOT 2019-04-24 JLV - Due to issues with starting the application, renamed data module "dmPull" to "dmSAFER" and recreated the Oracle UniDAC connection. 2019-04-29 JLV - Added new data module "dmReference" [dataModReference.pas] to have a static USDOT# set for creating all child table 2019-06-10 JLV - New Wizard-style interface using Developer Express components 2019-07-15 JLV - Added new procedure "writeExcept" to both display errors and write them to the log -----------------------------------------------------------------------------} unit formWizard; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, VCL.Graphics, VCL.Controls, VCL.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.Menus, Vcl.ComCtrls, RzShellDialogs, Uni, Data.DB, MemDS, DBAccess, cxControls, cxGraphics, cxLookAndFeelPainters, cxLookAndFeels, dxCustomWizardControl, dxWizardControl, dxWizardControlForm, cxContainer, cxEdit, cxTextEdit, cxLabel, cxMemo, cxGroupBox, cxRadioGroup, cxMaskEdit, cxButtonEdit, cxRichEdit, cxProgressBar, cxButtons, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkroom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringtime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinTheBezier, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinOffice2019Colorful, RzPrgres; type TfrmMain = class(TdxWizardControlForm) wizCtrl: TdxWizardControl; WizPage_DataDate: TdxWizardControlPage; btnGetMonthYear: TSpeedButton; lblPage1: TcxLabel; lblDate: TcxLabel; edtDataDate: TcxTextEdit; WizPage_Home: TdxWizardControlPage; cxMemo1: TcxMemo; WizPage_DataLocation: TdxWizardControlPage; WizPage_Target: TdxWizardControlPage; grpTargetSystem: TcxRadioGroup; lblTargetSystem: TcxLabel; lblDataLocation: TcxLabel; edtDataPath: TcxButtonEdit; WizPage_StartProcess: TdxWizardControlPage; WizPage_Processing: TdxWizardControlPage; lblOverallProgress: TcxLabel; lblTableProgress: TcxLabel; lblTotalRecords: TcxLabel; lblConfirmTarget: TcxLabel; lblTargetDataDate: TcxLabel; lblDataPath: TcxLabel; radBtnConfirmFB: TcxRadioButton; radBtnConfirmSQLite: TcxRadioButton; edtConfirmDate: TcxTextEdit; edtConfirmDataPath: TcxTextEdit; dlgDataPath: TRzOpenDialog; btnConfirmed: TcxButton; memoLog: TMemo; progBarTable: TRzProgressBar; progBarOverall: TRzProgressBar; edtRefDataPath: TcxButtonEdit; lblRefData: TcxLabel; lblRefDataPath: TcxLabel; edtConfirmRefPath: TcxTextEdit; procedure btnGetMonthYearClick(Sender: TObject); procedure grpTargetSystemClick(Sender: TObject); procedure edtDataPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FormCreate(Sender: TObject); procedure wizCtrlPageChanged(Sender: TObject); procedure edtDataDatePropertiesChange(Sender: TObject); procedure wizCtrlButtonClick(Sender: TObject; AKind: TdxWizardControlButtonKind; var AHandled: Boolean); procedure btnConfirmedClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtRefDataPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); private { Private declarations } function MakeDataDate: string; function TimeStamp: string; function GetTimeElapsed(TotalTime: Boolean): string; //function CreateZipFile: Boolean; function SetGenId: Boolean; function DoRefLoad: Boolean; function DoCarrierLoad: Boolean; function DoIssLoad: Boolean; function DoLegalNameLoad: Boolean; function DoDbaNameLoad: Boolean; function DoHmLoad: Boolean; function DoInsLoad: Boolean; function DoUcrLoad: Boolean; function DoBasicsLoad: Boolean; function CheckSnapshot: string; procedure BetweenSteps; procedure ResetProgBarTable(RecCount: integer); public { Public declarations } StartTime: TDateTime; EndTime: TDateTime; ZipComplete: Boolean; dbSelected: integer; //dbSelected 0 := Firebird, 1 := SQLite; dmSelected: TDataModule; // sets the selected data module LogPath: string; procedure ClearData(tblname: string); procedure WriteStatus(msg: string; XtraLine: Boolean); procedure StartProcessing; procedure ShowProgress; procedure TableProgress; procedure ProcessBatch; procedure writeExcept(errMsg: string); //procedure CallActivateIndex; end; var frmMain: TfrmMain; implementation {$R *.dfm} uses dataModISS_Firebird, dataModISS_SQLite, dataModReference, dataModSAFER, dialogEnvironment, dialogZipProgress; {----------------------------------------------------------------------------- Procedure: writeExcept Author: J. L. Vasser, FMCSA, 2019-07-15 Comments: Display error message and write the error to the log. -----------------------------------------------------------------------------} procedure TfrmMain.writeExcept(errMsg: string); begin MessageDlg(errMsg,mtError,[mbAbort],0); WriteStatus(errMsg,True); end; {----------------------------------------------------------------------------- Function: MakeDataDate Author: J. L. Vasser, FMCSA Date: 2017-11-13 Arguments: None Return: string Comments: Creates the default Data Date label of MonthYear -----------------------------------------------------------------------------} function TfrmMain.MakeDataDate: string; var monthYear : string ; begin Result := ''; DateTimeToString(monthYear,'mmmmyyyy',now); Result := monthYear; end; {----------------------------------------------------------------------------- Procedure: btnGetMonthYearClick Author: J. L. Vasser, FMCSA, 2019-06-13 Comments: Calls MakeDataDate then returns value to UI 2019-06-26 JLV - Added call to wizCtrlPageChanged procedure -----------------------------------------------------------------------------} procedure TfrmMain.btnGetMonthYearClick(Sender: TObject); begin edtDataDate.Text := MakeDataDate; wizCtrlPageChanged(self); edtConfirmDate.Text := edtDataDate.Text; end; {----------------------------------------------------------------------------- Procedure: btnConfirmedClick Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Calls the wizCtrlPageChanged procedure -----------------------------------------------------------------------------} procedure TfrmMain.btnConfirmedClick(Sender: TObject); begin wizCtrl.Buttons.Next.Enabled := True; end; {----------------------------------------------------------------------------- Procedure: wizCtrlButtonClick Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Closes the wizard application after user confirmation 2019-06-27 JLV - Added code to check if back button clicked, then ensure Next button caption reads "Next" -----------------------------------------------------------------------------} procedure TfrmMain.wizCtrlButtonClick(Sender: TObject; AKind: TdxWizardControlButtonKind; var AHandled: Boolean); begin if AKind = wcbkCancel then begin if MessageDlg('Exit DataPull Wizard?',mtConfirmation,[mbYes,mbNo],0)=mrYes then begin // maybe add close database routines Close; end; end; if AKind = wcbkBack then if wizCtrl.Buttons.Next.Caption = '&Start' then wizCtrl.Buttons.Next.Caption := '&Next'; if (AKind = wcbkNext) and (wizCtrl.Buttons.Next.Caption = 'Finish') then begin // do stuff to check zip file and close database Close; end; end; {----------------------------------------------------------------------------- Procedure: wizCtrlPageChanged Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Enables the "Next" button when specified parameters are complete for each page. -----------------------------------------------------------------------------} procedure TfrmMain.wizCtrlPageChanged(Sender: TObject); var BtnEnabled : Boolean; begin BtnEnabled := False; case wizCtrl.ActivePageIndex of 0 : BtnEnabled := True; // starting page 1 : BtnEnabled := grpTargetSystem.ItemIndex <> -1; // target system page 2 : BtnEnabled := edtDataDate.Text <> ''; // date selected page 3 : BtnEnabled := edtDataPath.Text <> ''; // data path page 4 : begin wizCtrl.Buttons.Next.Caption := '&Start'; // confirmation page end; 5 : begin BtnEnabled := False; memoLog.Repaint; StartProcessing; end; end; wizCtrl.InfoPanel.Caption := 'Carrier Data Pull Wizard - Page '+IntToStr(wizCtrl.ActivePageIndex); wizCtrl.Buttons.Next.Enabled := BtnEnabled; end; {----------------------------------------------------------------------------- Function: TimeStamp Author: J. L. Vasser, FMCSA Date: 2017-11-14 Arguments: None Return: string Comments: Returns the current time in ISO format -----------------------------------------------------------------------------} function TfrmMain.TimeStamp: string; var TimeNow : TDateTime; TimeStr : string; begin TimeNow := now; // Need this for the following function DateTimeToString(TimeStr,'yyyy-mm-dd_hh-mm-ss',TimeNow); // this statement wouldn't work with the function "now" Result := TimeStr; end; {----------------------------------------------------------------------------- Function: GetTimeElapsed Author: J. L. Vasser, FMCSA, 2017-10-12 Comments: Returns string of elapsed time since process started. 2019-06-13 JLV - Added parameter "TotalTime". If true, calculates from StartTime to EndTime. If False, calculates from StartTime to NOW. -----------------------------------------------------------------------------} function TfrmMain.GetTimeElapsed(TotalTime:Boolean): string; var DeltaTime : TDateTime; Hrs, Min, Sec, mSec : word; begin Result := ''; if TotalTime = True then DeltaTime := EndTime - StartTime else DeltaTime := Now - StartTime; DecodeTime(DeltaTime,Hrs,Min,Sec,mSec); if TotalTime = True then Result := 'TOTAL TIME ELAPSED: '+IntToStr(Hrs)+' hours, '+IntToStr(Min)+' minutes, '+IntToStr(Sec)+' seconds.' else Result := 'Time Elapsed: '+IntToStr(Hrs)+' hours, '+IntToStr(Min)+' minutes, '+IntToStr(Sec)+' seconds.'; end; {----------------------------------------------------------------------------- Procedure: grpTargetSystemClick Author: J. L. Vasser, FMCSA, 2019-02-04 Comments: Sets the value of the global variable "dbSelected". This variable indicates to produce a Firedbird or SQLIte output 2019-06-13 JLV - Now using DevExpress progress bars. Made necessary property setting changes for these components 2019-07-08 JLV - Changed to Raize Progress Bar compoents. Too many issues with Dev Express and insufficient documentation -----------------------------------------------------------------------------} procedure TfrmMain.grpTargetSystemClick(Sender: TObject); var dmISS_FB : TdmISS_FB; dmISS_SQLite : TdmISS_SQLite; begin dbSelected := grpTargetSystem.ItemIndex; if dbSelected = 0 then begin lblDataPath.Caption := 'Local Data Path (Firebird database)'; WriteStatus('User selected Aspen 3.0 target (Firebird)',True); dmSelected := dmISS_FB; radBtnConfirmFB.Checked := True; end else begin lblDataPath.Caption := 'Local Data Path (SQLite database)'; dmSelected := dmISS_SQLite; WriteStatus('User selected Aspen 3.2 target (SQLite)',True); radBtnConfirmSQLite.Checked := True; end; {if progBarOverall.Position > 0 then begin progBarOverall.Position := 0; progBarTable.Position := 0; end;} if progBarOverall.PartsComplete > 0 then begin progBarOverall.PartsComplete := 0; progBarTable.PartsComplete := 0; end; wizCtrlPageChanged(self); end; {----------------------------------------------------------------------------- Function: SetGenId Author: J. L. Vasser, FMCSA Date: 2018-02-20 Arguments: None Return: Boolean Comments: Sets the UCR table sequence (generator) ahead by 10 after completion. Having the next value was causing a conflict in Aspen. 2019-02-05 j - Is this needed for SQLite? -----------------------------------------------------------------------------} function TfrmMain.SetGenId: Boolean; var i : integer; begin Result := False; try with dmISS_FB.qryGenValue do begin SQL.Clear; SQL.add('select GEN_ID(UCR_UCR_SEQ_NUM_GEN,0) from RDB$DATABASE'); ExecSql; i := FieldByName('GEN_ID').AsInteger; SQL.Clear; SQL.Add('set generator UCR_UCR_SEQ_NUM_GEN to '+IntToStr(i+10)); ExecSQL; Result := True; end; except on E: Exception do begin MessageDlg('Unable to advance UCR table Generator.'+#13#10+'Set this value manually',mtError,[mbOK],0); WriteStatus('Unable to advance UCR table Generator.'+#13#10+'Set this value manually',True); end; end; end; {----------------------------------------------------------------------------- Procedure: ClearData Author: J. L. Vasser, FMCSA Date: 2017-10-13 Arguments: tblname: string Result: None Comments: Deletes all data from existing database 2019-02-04 JLV - Moved the body to the data module for each database target -----------------------------------------------------------------------------} procedure TfrmMain.ClearData(tblname: string); begin if dbSelected = 0 then dmISS_FB.EmptyDatabase(tblname) else dmISS_SQLite.EmptyDatabase(tblname); end; {----------------------------------------------------------------------------- Procedure: edtDataDatePropertiesChange Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Fires the wizCtrlPageChanged procuedure -----------------------------------------------------------------------------} procedure TfrmMain.edtDataDatePropertiesChange(Sender: TObject); begin wizCtrlPageChanged(self); end; {----------------------------------------------------------------------------- Procedure: edtDataPathPropertiesButtonClick Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Gets the path for the user-selected target database -----------------------------------------------------------------------------} procedure TfrmMain.edtDataPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var db : string; begin dlgDataPath.InitialDir := GetCurrentDir; if dbSelected = 0 then dlgDataPath.Filter := 'Firebird Database|ISS_FED_DATA.FDB|All Files|*.*' else dlgDataPath.Filter := 'SQLite Database|ISS_FED_DATA.db|All Files|*.*'; dlgDataPath.Execute; db := dlgDataPath.FileName; if db = '' then begin MessageDlg('You must select the local data path!',mtError,[mbRetry],0); Exit; end; edtDataPath.Text := db; WriteStatus('User selected database at "'+edtDataPath.Text+'"',True); if dbSelected = 0 then try with dmISS_FB.dbISS_LOCAL do begin if Connected then Disconnect; ConnectString := ''; Server := ''; ProviderName := 'Interbase'; SpecificOptions.Values['ClientLibrary'] := 'fbclient.dll'; //Database := edtDataPath.Text; Database := db; UserName := 'SYSDBA'; Password := 'masterkey'; Connect; //dmISS_FB.dbISS_LOCAL.Open; wizCtrlPageChanged(self); end; except on E: Exception do begin MessageDlg('Database not found. "'+E.Message+'". Please try again',mtError,[mbRetry],0); if edtDataPath.CanFocus then edtDataPath.SetFocus; end; end else // SQLite database (Aspen 3.2) try dmISS_SQLite.dbISS_LOCAL.Database := edtDataPath.Text; dmISS_SQLite.dbISS_LOCAL.Connect; wizCtrlPageChanged(self); //btnStart.Enabled := dmISS_SQLite.dbISS_LOCAL.Connected; except on E: Exception do begin MessageDlg('Database not found. Please try again',mtError,[mbRetry],0); if edtDataPath.CanFocus then edtDataPath.SetFocus; end; end; edtConfirmDataPath.Text := edtDataPath.Text; end; {----------------------------------------------------------------------------- Procedure: edtRefDataPathPropertiesButtonClick Author: J. L. Vasser, FMCSA, 2019-07-10 Comments: User selects the location of the Reference database. This database is used to load all USDOT numbers 1 time to ensure a static snapshot of data. -----------------------------------------------------------------------------} procedure TfrmMain.edtRefDataPathPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var db : string; begin dlgDataPath.InitialDir := GetCurrentDir; dlgDataPath.Filter := 'Reference Database|DataPullRef.db|All Files|*.*'; dlgDataPath.Execute; db := dlgDataPath.FileName; if db = '' then begin MessageDlg('You must select the local data path!',mtError,[mbRetry],0); Exit; end; edtRefDataPath.Text := db; try dmReference.dbReference.Database := edtRefDataPath.Text; dmReference.dbReference.Connect; except on E: Exception do begin MessageDlg('ERROR! Unable to open Wizard Reference Database!',mtError,[mbAbort],0); Exit; end; end; edtConfirmRefPath.Text := edtRefDataPath.Text; end; {----------------------------------------------------------------------------- Procedure: FormCreate Author: J. L. Vasser, FMCSA, 2019-06-26 Comments: Ensures the wizard starts on the start page -----------------------------------------------------------------------------} procedure TfrmMain.FormCreate(Sender: TObject); begin wizCtrl.ActivePageIndex := 0; end; {----------------------------------------------------------------------------- Procedure: WriteStatus Author: J. L. Vasser, FMCSA Date: 2017-10-12 Arguments: msg: string;XtraLine: Boolean Comments: Writes status information to window, for optional save to log. 2018-02-13 JLV - Added lines to move cursor to end. This updates the display to show the latest line. -----------------------------------------------------------------------------} procedure TfrmMain.WriteStatus(msg: string; XtraLine: Boolean); var //lin, col : integer; // cursor position variables pt : TPoint; begin memoLog.Lines.Add(msg); if XtraLine = True then memoLog.Lines.Add(''); if wizCtrl.ActivePageIndex = 5 then begin // only forces repaint if control is visible pt := memoLog.CaretPos; //lin := memoLog.Line; // cursor line position //col := memoLog.Column; // cursor column position //memoLog.JumpTo(lin,col); // force the cursor to that position memoLog.Repaint; // force the display to refresh memoLog.CaretPos := pt; // force the cursor to that position end; end; {----------------------------------------------------------------------------- Procedure: StartProcessing (formerly btnStartClick) Author: J. L. Vasser, FMCSA Date: 2017-10-12 Arguments: Sender: TObject Result: None Comments: The actual data extract process begins here 2017-11-20 JLV - Replaced the LoadData function with specific functions for each dataset. 2017-11-22 JLV - Added "OneByOne" variable. For unknown reason, the process can't find a USDOT number when running sequentially. Running one-by-one doesn't have that issue. 2018-01-30 JLV - Commented "OneByOne" variable and related procedures now that the data generation is working correctly. 2018-02-14 JLV - Remove the one-by-one option entirely. Batch process now working as intended. 2019-07-02 JLV - Copied this procedure over from the old version (non Wizard version) and renamed from "btnStartClick" to "StartProcessing" -----------------------------------------------------------------------------} procedure TfrmMain.StartProcessing; var sNow : string; db : TUniConnection; begin (* Don't think this is necessary any longer. The wizard should catch this. ** if edtDataDate.Text = '' then begin MessageDlg('Please enter a "Data Date"',mtError,[mbRetry],0); if edtDataDate.CanFocus then edtDataDate.SetFocus; Exit; end; *) sNow := ''; StartTime := Now; { set the target database via its data module } if dbSelected = 0 then db := dmISS_FB.dbISS_LOCAL else db := dmISS_SQLite.dbISS_Local; try DateTimeToString(sNow, 'dddd, mmm d, yyyy, hh:mm:ss',StartTime); WriteStatus('Starting Data Pull '+sNow, true); //step 1.0 try if not db.Connected then db.Connect; ShowProgress; except on E: Exception do begin MessageDlg('Unable to connect to LOCAL ISS data',mtError,[mbAbort],0); Exit; end; end; // step 1.1 try //dmSAFER.dbSAFER.Server := '10.75.161.103:1526/safer.safersys.org'; //development connection dmSAFER.dbSAFER.Server := 'safer.safersys.org:1526/safer.safersys.org'; //production connection dmSAFER.dbSAFER.Connect; ShowProgress; Application.ProcessMessages; except on E: Exception do begin MessageDlg('Unable to connect to SAFER database.'+#13#10+ 'Ensure you are connected to the AWS VPN'+#13#10+ 'App will now exit. Check VPN and restart.',mtError,[mbAbort],0); WriteStatus('Unable to connect to SAFER database',False); WriteStatus('Ensure you are connected to the AWS VPN',False); WriteStatus('Check VPN and restart.',True); DateTimeToString(sNow, 'dddd, mmm d, yyyy, hh:mm:ss',Now); WriteStatus('Application terminated '+sNow,False); memoLog.Lines.SaveToFile(LogPath); Application.ProcessMessages; Application.Terminate; Exit; end; end; //step 2.0 WriteStatus('Clearing Tables.................'+DateTimeToStr(now), false); WriteStatus(' Carriers', false); ClearData('CARRIERS'); Application.ProcessMessages; ShowProgress; //step 3 WriteStatus(' ISS', false); ClearData('ISS'); Application.ProcessMessages; ShowProgress; //step 4 WriteStatus(' Insurance', false); ClearData('CARRINS'); Application.ProcessMessages; ShowProgress; Application.ProcessMessages; //step 5 WriteStatus(' UCR', false); ClearData('UCR'); Application.ProcessMessages; ShowProgress; //step 6 WriteStatus(' HM Permit', false); ClearData('HMPERMIT'); Application.ProcessMessages; ShowProgress; // step 7 WriteStatus(' Carrier Names', false); ClearData('CARRNAME'); Application.ProcessMessages; ShowProgress; // step 8 WriteStatus(' BASICs', false); ClearData('BASICSDETAIL'); Application.ProcessMessages; ShowProgress; // step 9 Application.ProcessMessages; WriteStatus('..... Tables emptied', true); //inactivate the indexes// frmMain.Repaint; WriteStatus('Inactivating Indexes..............', false); if dbSelected = 0 then dmISS_FB.scriptInactivateIdx.Execute // also resets the UCR Table generator to zero // else dmISS_SQLite.scriptInactivateIndex.Execute; ShowProgress; Application.ProcessMessages; WriteStatus('..... DONE', true); ShowProgress; // step 10.0 if MessageDlg('Ready to begin loading data. Continue?',mtConfirmation,[mbOK,mbCancel],0) = mrCancel then begin WriteStatus('User aborted operation at '+TimeStamp,true); Exit; end; frmMain.Repaint; Application.ProcessMessages; // step 10.1 WriteStatus('Updating Data Date...............', false); if dbSelected = 0 then begin with dmISS_FB.sqlDataDate do begin ParamByName('newDate').Clear; ParamByName('newDate').AsString := edtDataDate.Text; Execute; dmISS_FB.dbISS_LOCAL.Commit; end; end else begin with dmISS_SQLite.sqlDataDate do begin dmISS_SQLite.dbISS_Local.StartTransaction; ParamByName('newDate').Clear; ParamByName('newDate').AsString := edtDataDate.Text; Execute; dmISS_SQLite.dbISS_Local.Commit; end; end; Application.ProcessMessages; WriteStatus('...............DONE', true); { --------- This is where the data loading finally starts --------- } //step 10.2 -- This loads the reference table with a set of USDOT numbers. // This provides a static list so that both versions of the output // contain the same data. ShowProgress; if not DoRefLoad then begin MessageDlg('An error occurred loading the SNAPSHOT QUERY table',mtError,[mbAbort],0); Exit; end; BetweenSteps; //step 11 -- Now we go through each table of the database. ProcessBatch; // step 19 WriteStatus('Process Complete! '+ DateTimeToStr(now), true); frmMain.Repaint; finally dmSAFER.dbSAFER.Close; // step 20 //ShowProgress; if dmISS_FB.dbISS_LOCAL.Connected then dmISS_FB.dbISS_LOCAL.Close; if dmISS_SQLite.dbISS_LOCAL.Connected then dmIss_SQLite.dbISS_Local.Close; ShowProgress; EndTime := Now; WriteStatus(GetTimeElapsed(true),true); end; end; {----------------------------------------------------------------------------- Procedure: ProcessBatch Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Call procedures to load datasets -----------------------------------------------------------------------------} procedure TfrmMain.ProcessBatch; begin // step 11 continued // step 11 (continued) WriteStatus('Loading Carrier data ............'+DateTimeToStr(now), false); if not DoCarrierLoad then begin WriteStatus('Carrier data load FAILED', false); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // Step 12 WriteStatus('Loading ISS Score data...........'+DateTimeToStr(now), false); if not DoIssLoad then begin WriteStatus('ISS Score data load FAILED', true); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 13 WriteStatus('Loading Carrier Name data .......'+DateTimeToStr(now), false); if not DoLegalNameLoad then begin WriteStatus('Carrier Name data load FAILED', false); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 14 WriteStatus('Loading Carrier DBA Name data...'+DateTimeToStr(now), false); if not DoDbaNameLoad then begin WriteStatus('Carrier DBA Name data load FAILED', false); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 15 WriteStatus('Loading HM Permit data...........'+DateTimeToStr(now), false); if not DoHMLoad then begin WriteStatus('HM Permit data load FAILED', true); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 16 WriteStatus('Loading Insurance data...........'+DateTimeToStr(now), false); if not DoInsLoad then begin WriteStatus('Insurance data load FAILED', false); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 17 WriteStatus('Loading UCR data.................'+DateTimeToStr(now), false); if not DoUcrLoad then begin WriteStatus('UCR data load FAILED', true); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; // step 18 WriteStatus('Loading BASICs Score data........'+DateTimeToStr(now), false); if not DoBasicsLoad then begin WriteStatus('BASICs Score data load FAILED', false); WriteStatus(DateTimeToStr(now),true); Exit; end; BetweenSteps; end; {----------------------------------------------------------------------------- Function: DoRefLoad Author: J. L. Vasser, FMCSA, 2019-05-07 Comments: Loads basic data in the Reference DB "Snapshot" table. This is then used for building all other datasets. -----------------------------------------------------------------------------} function TfrmMain.DoRefLoad: Boolean; var i,t : integer; begin Result := False; if CheckSnapshot = 'KEEP' then begin //check for existing data. Result := True; Exit; // If user elects to keep, exit procedure end; i := 1; // counter of records processed. Commits every 10,000 t := 0; // counter of total records processed. Result := False; Application.ProcessMessages; try Screen.Cursor := crSqlWait; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not dmSAFER.qryCensus.Active then dmSAFER.qryCensus.Open; dmSAFER.qryCensus.First; if not dmReference.dbReference.Connected then dmReference.dbReference.Connect; if dmReference.refTransaction.Active then dmReference.refTransaction.Rollback; finally Screen.Cursor := crDefault; end; with dmSAFER.qryCensus do begin if not dmReference.qrySnapshot.Active then dmReference.qrySnapshot.Open; WriteStatus('Loading Reference Table ......',False); //ProgBarTable.Properties.Max := RecordCount; //ProgBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); // was IntToStr, but the Max property is a double ResetProgBarTable(RecordCount); lblTotalRecords.Caption := IntToStr(progBarTable.TotalParts); First; Application.ProcessMessages; repeat if not dmReference.refTransaction.Active then dmReference.refTransaction.StartTransaction; dmReference.qrySnapshot.Append; dmReference.qrySnapshot.FieldByName('CARRIER_ID_NUMBER').AsInteger := FieldByName('CARRIER_ID_NUMBER').AsInteger; dmReference.qrySnapshot.FieldByName('USDOTNUM').AsString := FieldByName('USDOTNUM').AsString; dmReference.qrySnapshot.FieldByName('STATUS').AsString := FieldByName('STATUS').AsString; dmReference.qrySnapshot.FieldByName('LAST_UPDATE_DATE').AsString := FieldByName('LAST_UPDATE_DATE').AsString; dmReference.qrySnapshot.Post; Inc(i); Inc(t); if i = 10000 then begin if dmReference.refTransaction.Active then dmReference.refTransaction.Commit; WriteStatus('Loaded 10,000 Census records and committed.',False); WriteStatus(IntToStr(t)+' total records processed. '+DateTimeToStr(now),True); i := 1; end; TableProgress; Next; until EOF; try WriteStatus('Saving reference table data ...',False); if dmReference.refTransaction.Active then dmReference.refTransaction.Commit; Result := True; WriteStatus('Successfully saved reference data.',True); except on E: Exception do begin MessageDlg('Error commiting dbReference: "'+E.Message+'"',mtError,[mbAbort],0); WriteStatus('Error commiting dbReference: "'+E.Message+'"',True); end; end; end; dmSAFER.qryCensus.Close; end; {----------------------------------------------------------------------------- Function: DoCarrierLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with all Active Carriers 2018-01-18 JLV - Programming note: The underlying query left-pads the USDOT number with zeroes. This hampers use of the USDOTNUM field as a variable to search other SOURCE tables. Keep this in mind. 2019-07-15 JLV - Implemented writeExcept procedure -----------------------------------------------------------------------------} function TfrmMain.DoCarrierLoad: Boolean; var i,t : integer; db, ref : TUniConnection; qry : TUniQuery; tbl : TUniTable; sfr : TUniQuery; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblCarriers; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblCarriers; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; sfr := dmSAFER.qryCarrier; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; if not qry.Active then qry.Open; Result := False; i := 0; // counter of records processed. Commits every 10,000 t := 0; // counter of total records processed. try with qry do begin ResetProgBarTable(RecordCount); lblTotalRecords.Caption := IntToStr(progBarTable.TotalParts); First; repeat {sfr.Close; sfr.ParamByName('dot').Clear; sfr.ParamByName('dot').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; } sfr.Filtered := False; sfr.Filter := ''; sfr.Filter := 'CARRIER_ID_NUMBER = '+IntToStr(qry.FieldByName('CARRIER_ID_NUMBER').AsInteger); sfr.Filtered := True; if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('ADDRESS').AsString := sfr.FieldByName('ADDRESS').AsString; tbl.FieldByName('ZIPCODE').AsString := sfr.FieldByName('ZIPCODE').AsString; tbl.FieldByName('COUNTRY').AsString := sfr.FieldByName('COUNTRY').AsString; tbl.FieldByName('PHONE').AsString := sfr.FieldByName('PHONE').AsString; { to allow for Aspen 3.0 not accepting longer docket numbers ---------} if dbSelected = 0 then begin if length(sfr.FieldByName('ICC_NUM').AsString) > 6 then tbl.FieldByName('ICC_NUM').AsString := ''; end else tbl.FieldByName('ICC_NUM').AsString := trim(sfr.FieldByName('ICC_NUM').AsString); {-----------------------------------------------------------------------} //tblCarriers.FieldByName('RFC_NUM').AsString := FieldByName(' {* there's no RFC_NUM in SAFER? *} tbl.FieldByName('INSPECTION_VALUE').AsString := sfr.FieldByName('INSPECTION_VALUE').AsString; tbl.FieldByName('INDICATOR').AsString := sfr.FieldByName('INDICATOR').AsString; tbl.FieldByName('TOTAL_VEHICLES').AsInteger := sfr.FieldByName('TOTAL_VEHICLES').AsInteger; tbl.FieldByName('TOTAL_DRIVERS').AsInteger := sfr.FieldByName('TOTAL_DRIVERS').AsInteger; tbl.FieldByName('CARRIER_OPERATION').AsString := sfr.FieldByName('CARRIER_OPERATION').AsString; tbl.FieldByName('NEW_ENTRANT_CODE').AsString := sfr.FieldByName('NEW_ENTRANT_CODE').AsString; tbl.FieldByName('STATUS').AsString := sfr.FieldByName('STATUS').AsString; if sfr.FieldByName('LAST_UPDATE_DATE').AsString <> '' then tbl.FieldByName('LAST_UPDATE_DATE').AsDateTime := sfr.FieldByName('LAST_UPDATE_DATE').AsDateTime; tbl.FieldByName('ENTITY_TYPE').AsString := sfr.FieldByName('ENTITY_TYPE').AsString; tbl.FieldByName('UNDELIVERABLE_PA').AsString := sfr.FieldByName('UNDELIVERABLE_PA').AsString; tbl.FieldByName('UNDELIVERABLE_MA').AsString := sfr.FieldByName('UNDELIVERABLE_MA').AsString; tbl.FieldByName('HAS_POWER_UNITS').AsString := sfr.FieldByName('HAS_POWER_UNITS').AsString; tbl.FieldByName('OPER_AUTH_STATUS').AsString := sfr.FieldByName('OPER_AUTH_STATUS').AsString; if sfr.FieldByName('OOS_DATE').AsString <> '' then tbl.FieldByName('OOS_DATE').AsDateTime := sfr.FieldByName('OOS_DATE').AsDateTime; tbl.FieldByName('OOS_TEXT').AsString := sfr.FieldByName('OOS_TEXT').AsString; tbl.FieldByName('OOS_REASON').AsString := sfr.FieldByName('OOS_REASON').AsString; tbl.FieldByName('MCSIP_STATUS').AsString := sfr.FieldByName('MCSIP_STATUS').AsString; tbl.Post; Inc(i); Inc(t); TableProgress; if i = 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carriers records and committed.'+#10#13+'Total '+IntToStr(t)+' records '+DateTimeToStr(now),True); i := 0; end; Next; until EOF; //until t = 10000; if db.InTransaction then db.Commit; if dbSelected = 0 then begin if dmISS_FB.TransactionLocal.Active then dmISS_FB.TransactionLocal.Commit; end else begin if dmISS_SQLite.transactionLocal.Active then dmISS_SQLite.transactionLocal.Commit; end; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carriers Table at record '+IntToStr(t)+':'+#13#10+'"'+E.Message+'"'); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoLegalNameLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with Carrier Legal Name values 2019-07-15 JLV - implemented writeExcept procedure -----------------------------------------------------------------------------} function TfrmMain.DoLegalNameLoad: Boolean; var d,i,t : integer; dot, dPad : string; db, ref : TUniConnection; qry : TUniQuery; sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblCarriers; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblCarriers; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryNAME; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; // commit counter: issue a database commit when counter reaches 10K t := 0; // progress counter: shows progress of iterating through the table try with qry do begin if not Active then Open; //progBarTable.Properties.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); //was IntToStr ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; if sfr.RecordCount > 0 then begin if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('NAME').AsString := sfr.FieldByName('NAME').AsString; tbl.FieldByName('CITY').AsString := sfr.FieldByName('CITY').AsString; tbl.FieldByName('STATE').AsString := sfr.FieldByName('STATE').AsString; tbl.FieldByName('NAME_TYPE_ID').AsString := '1'; tbl.Post; Inc(i); end else begin WriteStatus('LEGAL NAME value not found for USDOT # '+dot+' at record '+IntToStr(t),False); end; Inc(t); TableProgress; if i = 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carrier Name records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; if dbSelected = 0 then begin if dmISS_FB.TransactionLocal.Active then dmISS_FB.TransactionLocal.Commit; end else begin if dmISS_SQLite.transactionLocal.Active then dmISS_SQLite.transactionLocal.Commit; end; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carrier Name table (Legal Name)for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoDbaNameLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with Carrier Operating Name (DBA) values 2019-05-07 JLV - Added variable "sfr" for dmSAFER.qryNAME2 2019-07-15 JLV - implemented writeExcept procedure -----------------------------------------------------------------------------} function TfrmMain.DoDbaNameLoad: Boolean; var d,i,t : integer; dot, dPad : string; db, ref : TUniConnection; qry,sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblName2; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblName2; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryNAME2; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; t := 0; //d := 0; try with qry do begin if not Active then Open; //progBarTable.Properties.Max := RecordCount; // progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); //was IntToStr ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; if qry.RecordCount > 0 then begin (* While each USDOT# must have a LEGAL NAME, many will not have a "DBA" name *) if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('NAME').AsString := sfr.FieldByName('NAME').AsString; tbl.FieldByName('CITY').AsString := sfr.FieldByName('CITY').AsString; tbl.FieldByName('STATE').AsString := sfr.FieldByName('STATE').AsString; tbl.FieldByName('NAME_TYPE_ID').AsString := '2'; tbl.Post; Inc(i); end; Inc(t); TableProgress; if i = 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carrier DBA Name records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carrier Name table (DBA Name) for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoISSLoad Author: J. L. Vasser, FMCSA, 2017-11-15 Comments: Populate ISS Local table with ISS Score Values 2018-01-16 JLV - Changed to use the already-populated CARRIERS table USDOT number as the parameter for selecting the ISS data to load. 2018-01-24 JLV - Moved "qryISS_DOTNUM" to new "dbReference" connection. Commits to the dbISS_Local connection were closing the qryReference not allowing it to loop to the next record. -----------------------------------------------------------------------------} function TfrmMain.DoISSLoad: Boolean; var d, i, t : integer; dPad, dot : string; db, ref : TUniConnection; qry, sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblISS; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblISS; end; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryISS; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; if not qry.Active then qry.Open; qry.First; Result := False; i := 0; t := 0; //d := 0; //dot := ''; //dPad := ''; try with qry do begin if not Active then Open; //progBarTable.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := IntToStr(progBarTable.Max); ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; { d := 0; dPad := FieldByName('USDOTNUM').AsString; TryStrToInt(dPad, d); dot := IntToStr(d); if dmSAFER.qryISS.Active then begin dmSAFER.qryISS.Close; end; dmSAFER.qryISS.ParamByName('sDOT').Clear; dmSAFER.qryISS.ParamByName('sDOT').AsString := dot; dmSAFER.qryISS.Open; } if qry.RecordCount > 0 then begin if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := dPad; tbl.FieldByName('TOTAL_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('QUANTITY_INSPECTIONS_LAST30').AsFloat); tbl.FieldByName('VEHICLE_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsFloat); tbl.FieldByName('DRIVER_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('DRIVER_INSPECTIONS_LAST30').AsFloat); tbl.FieldByName('HAZMAT_INSPECTIONS').AsString := FloatToStr(sfr.FieldByName('QUANTITY_HAZMAT_PRESENT_LAST30').AsFloat); tbl.FieldByName('OOS_TOTAL').AsString := FloatToStr(sfr.FieldByName('OOS_ALL_TYPES_LAST30').AsFloat); tbl.FieldByName('OOS_VEHICLE').AsString := FloatToStr(sfr.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsFloat); tbl.FieldByName('OOS_DRIVER').AsString := FloatToStr(sfr.FieldByName('OOS_DRIVER_INSPECTIONS_LAST30').AsFloat); tbl.FieldByName('SAFETY_RATING').AsString := sfr.FieldByName('SAFETY_RATING').AsString; tbl.FieldByName('RATING_DATE').AsDateTime := sfr.FieldByName('RATING_DATE').AsDateTime; tbl.FieldByName('VIOL_BRAKES').AsString := FloatToStr(sfr.FieldByName('VIOLATION_BRAKES').AsFloat); tbl.FieldByName('VIOL_WHEELS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_WHEELS').AsFloat); tbl.FieldByName('VIOL_STEERING').AsString := FloatToStr(sfr.FieldByName('VIOLATION_STEERING').AsFloat); tbl.FieldByName('VIOL_MEDICAL').AsString := FloatToStr(sfr.FieldByName('VIOLATION_MEDICAL_CERTIFICATE').AsFloat); tbl.FieldByName('VIOL_LOGS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_LOGS').AsFloat); tbl.FieldByName('VIOL_HOURS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_HOURS').AsFloat); tbl.FieldByName('VIOL_DISQUAL').AsString := FloatToStr(sfr.FieldByName('VIOLATION_LICENSE').AsFloat); tbl.FieldByName('VIOL_DRUGS').AsString := FloatToStr(sfr.FieldByName('VIOLATION_DRUGS').AsFloat); tbl.FieldByName('VIOL_TRAFFIC').AsString := FloatToStr(sfr.FieldByName('VIOLATION_TRAFFIC').AsFloat); tbl.FieldByName('VIOL_HMPAPER').AsString := FloatToStr(sfr.FieldByName('VIOLATION_PAPERS').AsFloat); tbl.FieldByName('VIOL_HMPLAC').AsString := FloatToStr(sfr.FieldByName('VIOLATION_PLACARDS').AsFloat); tbl.FieldByName('VIOL_HMOPER').AsString := FloatToStr(sfr.FieldByName('VIOLATION_OP_EMER_RESP').AsFloat); tbl.FieldByName('VIOL_HMTANK').AsString := FloatToStr(sfr.FieldByName('VIOLATION_TANK').AsFloat); tbl.FieldByName('VIOL_HMOTHR').AsString := FloatToStr(sfr.FieldByName('VIOLATION_OTHER').AsFloat); tbl.Post; Inc(i); end; Inc(t); TableProgress; if i = 10000 then begin db.Commit; WriteStatus('Inserted 10,000 ISS records and committed '+DateTimeToStr(now),false); i := 0; end; Next; //dmSAFER.qryISS_DOTNUM.Next; until EOF; db.Commit; //if dmSAFER.TransactionLocal.Active then // dmSAFER.TransactionLocal.Commit; end; Result := True; except on E: Exception do begin writeExcept('Error updating ISS Scores Table at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoHMLoad Author: J. L. Vasser, FMCSA, 2017-11-16 Comments: Populate ISS Local table with HM Violation data -----------------------------------------------------------------------------} function TfrmMain.DoHMLoad: Boolean; var d, i, t : integer; dPad, dot : string; db, ref : TUniConnection; qry, sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblHMPermit; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblHMPermit; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; t := 0; //d := 0; //dot := ''; //dPad := ''; try with qry do begin if not Active then Open; ///progBarTable.Properties.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); // was IntToStr ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin MessageDlg('Error opening SAFER Carrier table: "'+E.Message+'"',mtError,[mbAbort],0); WriteStatus('Error opening SAFER Carrier table: "'+E.Message+'"',True); Exit; end; end; { d := 0; dPad := FieldByName('USDOTNUM').AsString; TryStrToInt(dPad, d); dot := IntToStr(d); if dmSAFER.qryHMPermit.Active then dmSAFER.qryHMPermit.Close; dmSAFER.qryHMPermit.ParamByName('sDOT').Clear; dmSAFER.qryHMPermit.ParamByName('sDOT').AsString := dot; dmSAFER.qryHMPermit.Open; } if dmSAFER.qryHMPermit.RecordCount > 0 then begin if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('PERMIT_TYPE').AsString := sfr.FieldByName('HM_PERMIT_TYPE').AsString; tbl.FieldByName('PERMIT_STATUS').AsString := sfr.FieldByName('HM_PERMIT_STATUS').AsString; if not tbl.FieldByName('HM_PERMIT_EFFECTIVE_DATE').IsNull then tbl.FieldByName('EFFECTIVE_DATE').AsDateTime := sfr.FieldByName('HM_PERMIT_EFFECTIVE_DATE').AsDateTime; if not tbl.FieldByName('HM_PERMIT_EXPIRATION_DATE').IsNull then tbl.FieldByName('EXPIRATION_DATE').AsDateTime := sfr.FieldByName('HM_PERMIT_EXPIRATION_DATE').AsDateTime; tbl.FieldByName('OPERATING_UNDER_APPEAL').AsString := sfr.FieldByName('OPERATING_UNDER_APPEAL_FLAG').AsString; tbl.Post; if tbl.State in [dsEdit,dsInsert] then tbl.Post; Inc(i); end; Inc(t); TableProgress; if i = 1000 then begin db.Commit; WriteStatus('Inserted 10,000 HM Permit records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; //if dmSAFER.TransactionLocal.Active then // dmSAFER.TransactionLocal.Commit; end; Result := True; except on E: Exception do begin writeExcept('Error updating HM Permit Table at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoInsLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with Carrier Insurance data -----------------------------------------------------------------------------} function TfrmMain.DoInsLoad:Boolean; var d,i,t : integer; dot, dPad : string; db, ref : TUniConnection; qry,sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblCarrIns; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblCarrIns; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryINS; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; t := 0; //d := 0; //dot := ''; //dPad := ''; try with qry do begin if not Active then Open; //progBarTable.Properties.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); // was IntToStr ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; { dPad := FieldByName('USDOTNUM').AsString; TryStrToInt(dPad, d); dot := IntToStr(d); if dmSAFER.qryIns.Active then dmSAFER.qryIns.Close; dmSAFER.qryIns.ParamByName('sDOT').Clear; dmSAFER.qryIns.ParamByName('sDOT').AsString := dot; dmSAFER.qryIns.Open; } if sfr.RecordCount > 0 then begin if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('LIABILITY_STATUS').AsString := sfr.FieldByName('LIABILITY_STATUS').AsString; tbl.FieldByName('LIABILITY_REQUIRED').AsInteger := sfr.FieldByName('LIABILITY_REQUIRED').AsInteger; tbl.FieldByName('CARGO_STATUS').AsString := sfr.FieldByName('CARGO_STATUS').AsString; tbl.FieldByName('BOND_STATUS').AsString := sfr.FieldByName('BOND_STATUS').AsString; tbl.FieldByName('MEX_TERRITORY').AsString := sfr.FieldByName('MEX_TERRITORY').AsString; tbl.Post; Inc(i); end; Inc(t); TableProgress; if i = 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carrier Insurance records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; //if dmSAFER.TransactionLocal.Active then // dmSAFER.TransactionLocal.Commit; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carrier Insurance table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoUcrLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with Carrier UCR Payment data 2018-01-30 JLV - Added repeat loop around the insert statements. USDOT# to UCR is a one-to-many relationship. 2018-02-07 JLV - Changed dmSAFER.qryUCR to accept a parameter for "and REGISTRATION_YEAR > :iRegYear" clause. The query has been running as "> 2011" since inception and this was generating millions of records not used. The new query variable "iRegYear" will be passed the result of a variable "iRgYr" which is calcualted in this function as (current year - 3). This will then make the query clause equivelent to "and REGISTRATION_YEAR > [current year - 3]" For example, current year is 2018. iRgYr would calculate to 2015. The query clause would interpret as "and REGISTRATION_YEAR > 2015" resulting in UCR records for 2016, 2017, and 2018. This concept was concurred upon by SMEs Mike Wilson (Indiana State Police), Holly Skaar (Idaho State police), Ken Keiper (Washington State Patrol), Renee Hill (Arkansas Highway Police), and Tom Kelly (FMCSA). 2018-02-12 JLV - Made changes to fix the looping of adding records. What a mess. -----------------------------------------------------------------------------} function TfrmMain.DoUcrLoad: Boolean; var d,i,t, ct, lp : integer; dot, dPad : string; iRgYr : integer; db, ref : TUniConnection; qry, sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblUCR; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblName2; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryUCR; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; t := 0; //d := 0; //dot := ''; //dPad := ''; { get current year value as integer } iRgYr := (CurrentYear - 3); //System.SysUtils.CurrentYear { --------------------------------- } try with qry do begin if not Active then Open; //progBarTable.Properties.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); // was IntToStr ResetProgBarTable(RecordCount); First; repeat if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; d := 0; lp := 1; // itteration through loop ct := 0; // count of matching records { dPad := FieldByName('USDOTNUM').AsString; TryStrToInt(dPad, d); dot := IntToStr(d); if dmSAFER.qryUCR.Active then begin dmSAFER.qryUCR.Close; end; dmSAFER.qryUCR.ParamByName('sDot').Clear; dmSAFER.qryUCR.ParamByName('sDOT').AsString := dot; // narrow down year selection dmSAFER.qryUCR.ParamByName('iRegYear').AsInteger := iRgYr; // dmSAFER.qryUCR.Open; } sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('iRegYear').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; sfr.ParamByName('iRegYear').AsInteger := iRgYr; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; ct := sfr.RecordCount; //how many UCR records exist for this USDOT#? if ct > 0 then begin // if more than Zero, for lp := lp to ct do begin // loop this code once for each UCR record if sfr.FieldByName('USDOTNUM').AsString <> '' then begin //double check that there is a valid record. if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; tbl.FieldByName('BASE_STATE').AsString := sfr.FieldByName('BASE_STATE').AsString; tbl.FieldByName('PAYMENT_FLAG').AsString := sfr.FieldByName('PAYMENT_FLAG').AsString; tbl.FieldByName('REGISTRATION_YEAR').AsString := sfr.FieldByName('REGISTRATION_YEAR').AsString; if sfr.FieldByName('PAYMENT_DATE').AsString <> '' then tbl.FieldByName('PAYMENT_DATE').AsDateTime := sfr.FieldByName('PAYMENT_DATE').AsDateTime; tbl.FieldByName('INTRASTATE_VEHICLES').AsString := sfr.FieldByName('INTRASTATE_VEHICLES').AsString; end; tbl.Post; sfr.Next; Inc(i); end; // if dot <> '' begin end; // if count > zero Inc(t); TableProgress; if i >= 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carrier UCR records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; //if dmSAFER.TransactionLocal.Active then // dmSAFER.TransactionLocal.Commit; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carrier UCR table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Function: DoBasicsLoad Author: J. L. Vasser, FMCSA, 2017-11-20 Comments: Populate ISS Local table with Carrier BASICs values Primary key is USDOT # + BASIC 2018-01-30 JLV - Added repeat loop around the insert statements. USDOT# to BASICS is a one-to-many relationship. -----------------------------------------------------------------------------} function TfrmMain.DoBasicsLoad: Boolean; var d,i,t, ct, lp : integer; dot, dPad : string; db, ref : TUniConnection; qry,sfr : TUniQuery; tbl : TUniTable; begin if dbSelected = 0 then begin db := dmISS_FB.dbISS_LOCAL; tbl := dmISS_FB.tblBasicsDetail; end else begin db := dmISS_SQLite.dbISS_Local; tbl := dmISS_SQLite.tblBasicsDetail; end; ref := dmReference.dbReference; qry := dmReference.qrySnapshot; sfr := dmSAFER.qryBASICS; if not dmSAFER.dbSAFER.Connected then dmSAFER.dbSAFER.Connect; if not db.Connected then db.Connect; if not ref.Connected then ref.Connect; Result := False; i := 0; t := 0; //d := 0; //dot := ''; //dPad := ''; try with qry do begin if not Active then Open; //progBarTable.Properties.Max := RecordCount; //progBarTable.Position := 0; //lblTotalRecords.Caption := FloatToStr(progBarTable.Properties.Max); // was IntToStr ResetProgBarTable(RecordCount); First; repeat sfr.Close; sfr.ParamByName('sDOT').Clear; sfr.ParamByName('sDOT').AsInteger := qry.FieldByName('CARRIER_ID_NUMBER').AsInteger; try sfr.Open; except on E: Exception do begin writeExcept('Error opening SAFER Carrier table: "'+E.Message+'"'); Exit; end; end; if dbSelected = 1 then dmISS_SQLite.dbISS_Local.StartTransaction; //d := 0; lp := 1; //set the loop counter to 1, otherwise change the loop to "lp to (ct -1)" ct := 0; { dPad := FieldByName('USDOTNUM').AsString; //showmessage('dPad = '+dPad); TryStrToInt(dPad, d); dot := IntToStr(d); //showmessage('dot = '+dot); if dmSAFER.qryBASICS.Active then begin dmSAFER.qryBASICS.Close; end; dmSAFER.qryBASICS.ParamByName('sDOT').Clear; dmSAFER.qryBASICS.ParamByName('sDOT').AsString := dot; dmSAFER.qryBASICS.Open; } //if dmSAFER.qryBASICS.RecordCount > 0 then begin ct := dmSAFER.qryBASICS.RecordCount; //showmessage('ct = '+inttostr(ct)); if ct > 0 then begin //showmessage('ct > zero'); for lp := lp to ct do begin //showmessage('start for ... loop'); //repeat if not tbl.Active then tbl.Open; tbl.Append; tbl.FieldByName('USDOTNUM').AsString := sfr.FieldByName('USDOTNUM').AsString; //showmessage('BASIC = '+inttostr(dmSAFER.qryBASICS.FieldByName('BASIC').AsInteger)); tbl.FieldByName('BASIC').AsInteger := sfr.FieldByName('BASIC').AsInteger; tbl.FieldByName('BASICPERCENTILE').AsInteger := sfr.FieldByName('BASICPERCENTILE').AsInteger; tbl.FieldByName('BASICSDEFIND').AsString := sfr.FieldByName('BASICSDEFIND').AsString; if dmSAFER.qryBASICS.FieldByName('BASICSRUNDATE').AsString <> '' then tbl.FieldByName('BASICSRUNDATE').AsDateTime := sfr.FieldByName('BASICSRUNDATE').AsDateTime; if dmSAFER.qryBASICS.FieldByName('INVESTIGATIONDATE').AsString <> '' then tbl.FieldByName('INVESTIGATIONDATE').AsDateTime := sfr.FieldByName('INVESTIGATIONDATE').AsDateTime; tbl.FieldByName('ROAD_DISPLAY_TEXT').AsString := sfr.FieldByName('ROAD_DISPLAY_TEXT').AsString; tbl.FieldByName('INVEST_DISPLAY_TEXT').AsString := sfr.FieldByName('INVEST_DISPLAY_TEXT').AsString; tbl.FieldByName('OVERALL_DISPLAY_TEXT').AsString := sfr.FieldByName('OVERALL_DISPLAY_TEXT').AsString; tbl.Post; sfr.Next; Inc(i); end; //until EOF; end; Inc(t); TableProgress; if i >= 10000 then begin db.Commit; WriteStatus('Inserted 10,000 Carrier BASICs records and committed '+DateTimeToStr(now),false); i := 0; end; Next; until EOF; db.Commit; if dbSelected = 0 then begin if dmISS_FB.TransactionLocal.Active then dmISS_FB.TransactionLocal.Commit; end else begin if dmISS_SQLite.transactionLocal.Active then dmISS_SQLite.transactionLocal.Commit; end; end; Result := True; except on E: Exception do begin writeExcept('Error updating Carrier BASICS table for USDOT # '+dot+' at record '+IntToStr(t)+':'+#13#10+E.Message); Exit; end; end; end; {----------------------------------------------------------------------------- Procedure: CheckSnapshot Author: J. L. Vasser, FMCSA, 2019-05-07 Comments: Checks for data in the snapshot file, shows date. Allows user to clear the table and start fresh, or reuse the data. -----------------------------------------------------------------------------} function TfrmMain.CheckSnapshot: string; var d : string; c : integer; begin Result := ''; d := ''; c := 0; WriteStatus('Checking Snapshot Reference table',True); if not dmReference.dbReference.Connected then dmReference.dbReference.Connect; with dmReference.qrySnapshot do begin if not Active then Open; c := RecordCount; if c > 0 then begin //First; in theory, the date of the last record should have the latest Last Update Date Last; d := DateTimeToStr(FieldByName('LAST_UPDATE_DATE').AsDateTime); writestatus('Reference table contains '+IntToStr(c)+' records dated '+d,False); if MessageDlg('Snapshot contains '+IntToStr(c)+' records dated '+d+'. Empty the Snapshot table?',mtConfirmation,[mbYes,mbNo],0) = mrYes then begin dmReference.sqlDelete.Execute; writestatus('User selected to purge table',true); Result := 'PURGE'; end else begin WriteStatus('User selected to retain records',true); ShowMessage('Snapshot records retained'); Result := 'KEEP'; end; end else WriteStatus('Reference table is empty. Process continues',True); if Active then Close; end; end; {----------------------------------------------------------------------------- Procedure: TableProgress Author: J. L. Vasser, FMCSA, 2017-10-12 Comments: Shows progress on the current table being imported -----------------------------------------------------------------------------} procedure TfrmMain.TableProgress; begin progBarTable.IncPartsByOne; progBarTable.Repaint; Application.ProcessMessages; end; {----------------------------------------------------------------------------- Procedure: ShowProgress Author: J. L. Vasser, FMCSA, 2019-07-02 Comments: Increments the overall progress indicator. -----------------------------------------------------------------------------} procedure TfrmMain.ShowProgress; begin progBarOverAll.IncPartsByOne; Application.ProcessMessages; end; {----------------------------------------------------------------------------- Procedure: BetweenSteps Author: J. L. Vasser, FMCSA, 2018-02-14 Comments: Repetitive code between loading table steps -----------------------------------------------------------------------------} procedure TfrmMain.BetweenSteps; begin WriteStatus('..........DONE '+DateTimeToStr(now), true); ShowProgress; memoLog.Repaint; Application.ProcessMessages; end; {----------------------------------------------------------------------------- Procedure: ResetProgBarTable Author: J. L. Vasser, FMCSA, 2019-07-08 Comments: Resets the progress bar to zero and label to the total record count -----------------------------------------------------------------------------} procedure TfrmMain.ResetProgBarTable(RecCount: integer); begin progBarTable.TotalParts := RecCount; progBarTable.PartsComplete := 0; lblTotalRecords.Caption := IntToStr(progBarTable.TotalParts); end; procedure TfrmMain.FormShow(Sender: TObject); begin wizCtrl.InfoPanel.Caption := 'Carrier Data Pull Wizard - Page '+IntToStr(wizCtrl.ActivePageIndex+1); end; end.
unit timepilot_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, konami_snd,sound_engine; function timepilot_iniciar:boolean; implementation const timepilot_rom:array[0..2] of tipo_roms=( (n:'tm1';l:$2000;p:0;crc:$1551f1b9),(n:'tm2';l:$2000;p:$2000;crc:$58636cb5), (n:'tm3';l:$2000;p:$4000;crc:$ff4e0d83)); timepilot_char:tipo_roms=(n:'tm6';l:$2000;p:0;crc:$c2507f40); timepilot_sprt:array[0..1] of tipo_roms=( (n:'tm4';l:$2000;p:0;crc:$7e437c3e),(n:'tm5';l:$2000;p:$2000;crc:$e8ca87b9)); timepilot_pal:array[0..3] of tipo_roms=( (n:'timeplt.b4';l:$20;p:0;crc:$34c91839),(n:'timeplt.b5';l:$20;p:$20;crc:$463b2b07), (n:'timeplt.e9';l:$100;p:$40;crc:$4bbb2150),(n:'timeplt.e12';l:$100;p:$140;crc:$f7b7663e)); timepilot_sound:tipo_roms=(n:'tm7';l:$1000;p:0;crc:$d66da813); //Dip timepilot_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),())),()); timepilot_dip_b:array [0..5] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$2;dip_name:'4'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'255'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Bonus Life';number:2;dip:((dip_val:$8;dip_name:'10K 50K'),(dip_val:$0;dip_name:'20K 60K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$70;name:'Difficulty';number:8;dip:((dip_val:$70;dip_name:'1'),(dip_val:$60;dip_name:'2'),(dip_val:$50;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$30;dip_name:'5'),(dip_val:$20;dip_name:'6'),(dip_val:$10;dip_name:'7'),(dip_val:$0;dip_name:'8'),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var scan_line,last:byte; video_enable,nmi_enable:boolean; procedure update_video_timepilot; var x,y,atrib:byte; f,nchar,color:word; begin if not(video_enable) then fill_full_screen(3,$100) else begin for f:=0 to $3ff do begin if gfx[0].buffer[f] then begin x:=31-(f div 32); y:=f mod 32; atrib:=memoria[$a000+f]; color:=(atrib and $1f) shl 2; nchar:=memoria[$a400+f]+((atrib and $20) shl 3); put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $80)<>0,(atrib and $40)<>0); if (atrib and $10)<>0 then put_gfx_flip(x*8,y*8,nchar,color,2,0,(atrib and $80)<>0,(atrib and $40)<>0) else put_gfx_block_trans(x*8,y*8,2,8,8); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(0,32,256,224,1,0,32,256,224,3); for f:=$1f downto $8 do begin atrib:=memoria[$b400+(f*2)]; nchar:=memoria[$b001+(f*2)]; color:=(atrib and $3f) shl 2; x:=memoria[$b401+(f*2)]-1; y:=memoria[$b000+(f*2)]; put_gfx_sprite(nchar,color,(atrib and $80)<>0,(atrib and $40)=0,1); actualiza_gfx_sprite(x,y,3,1); end; actualiza_trozo(0,32,256,224,2,0,32,256,224,3); actualiza_trozo(0,0,256,32,1,0,0,256,32,3); actualiza_trozo(0,248,256,8,1,0,248,256,8,3); end; actualiza_trozo_final(16,0,256,256,3); end; procedure eventos_timepilot; begin if event.arcade then begin if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.left[0] then marcade.in1:=marcade.in1 and $fe else marcade.in1:=marcade.in1 or $1; if arcade_input.right[0] then marcade.in1:=marcade.in1 and $fd else marcade.in1:=marcade.in1 or $2; if arcade_input.up[0] then marcade.in1:=marcade.in1 and $fb else marcade.in1:=marcade.in1 or $4; if arcade_input.down[0] then marcade.in1:=marcade.in1 and $f7 else marcade.in1:=marcade.in1 or $8; if arcade_input.but0[0] then marcade.in1:=marcade.in1 and $ef else marcade.in1:=marcade.in1 or $10; end; end; procedure timepilot_principal; var frame_m:single; begin init_controls(false,false,false,true); frame_m:=z80_0.tframes; while EmuStatus=EsRuning do begin for scan_line:=0 to $ff do begin //Main z80_0.run(frame_m); frame_m:=frame_m+z80_0.tframes-z80_0.contador; //Sound konamisnd_0.run; if ((scan_line=244) and nmi_enable) then z80_0.change_nmi(ASSERT_LINE); end; update_video_timepilot; eventos_timepilot; video_sync; end; end; function timepilot_getbyte(direccion:word):byte; begin case direccion of $0000..$5fff,$a000..$afff:timepilot_getbyte:=memoria[direccion]; $b000..$bfff:case (direccion and $7ff) of $000..$3ff:timepilot_getbyte:=memoria[$b000+(direccion and $ff)]; $400..$7ff:timepilot_getbyte:=memoria[$b400+(direccion and $ff)]; end; $c000..$cfff:case (direccion and $3ff) of $000..$0ff:timepilot_getbyte:=scan_line; $200..$2ff:timepilot_getbyte:=marcade.dswb; $300..$31f,$380..$39f:timepilot_getbyte:=marcade.in0; $320..$33f,$3a0..$3bf:timepilot_getbyte:=marcade.in1; $340..$35f,$3c0..$3df:timepilot_getbyte:=marcade.in2; $360..$37f,$3e0..$3ff:timepilot_getbyte:=marcade.dswa; end; else timepilot_getbyte:=$ff; end; end; procedure timepilot_putbyte(direccion:word;valor:byte); begin case direccion of 0..$5fff:; $a000..$a7ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $a800..$afff:memoria[direccion]:=valor; $b000..$bfff:case (direccion and $7ff) of $000..$3ff:memoria[$b000+(direccion and $ff)]:=valor; $400..$7ff:memoria[$b400+(direccion and $ff)]:=valor; end; $c000..$cfff:case (direccion and $3ff) of $000..$0ff:konamisnd_0.sound_latch:=valor; $300..$3ff:case ((direccion and $f) shr 1) of $0:begin nmi_enable:=(valor and 1)<>0; if not(nmi_enable) then z80_0.change_nmi(CLEAR_LINE); end; $1:main_screen.flip_main_screen:=(valor and $1)=0; $2:begin if ((last=0) and (valor<>0)) then konamisnd_0.pedir_irq:=HOLD_LINE; last:=valor; end; $4:video_enable:=(valor and 1)<>0; end; end; end; end; //Main procedure timepilot_reset; begin z80_0.reset; konamisnd_0.reset; reset_audio; nmi_enable:=false; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; end; function timepilot_iniciar:boolean; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0,8*8+1,8*8+2,8*8+3, 16*8+0,16*8+1,16*8+2,16*8+3,24*8+0,24*8+1,24*8+2,24*8+3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); var colores:tpaleta; f,bit0,bit1,bit2,bit3,bit4:byte; memoria_temp:array[0..$3fff] of byte; begin llamadas_maquina.bucle_general:=timepilot_principal; llamadas_maquina.reset:=timepilot_reset; timepilot_iniciar:=false; iniciar_audio(false); screen_init(1,256,256); screen_init(2,256,256,true); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,false,true); iniciar_video(224,256); //Main CPU z80_0:=cpu_z80.create(3072000,256); z80_0.change_ram_calls(timepilot_getbyte,timepilot_putbyte); //Sound Chip konamisnd_0:=konamisnd_chip.create(2,TIPO_TIMEPLT,1789772,256); if not(roms_load(@konamisnd_0.memoria,timepilot_sound)) then exit; //Cargar las roms... if not(roms_load(@memoria,timepilot_rom)) then exit; //cargar chars if not(roms_load(@memoria_temp,timepilot_char)) then exit; init_gfx(0,8,8,$200); gfx[0].trans[0]:=true; gfx_set_desc_data(2,0,16*8,4,0); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,true,false); //cargar sprites if not(roms_load(@memoria_temp,timepilot_sprt)) then exit; init_gfx(1,16,16,$100); gfx[1].trans[0]:=true; gfx_set_desc_data(2,0,64*8,4,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,true,false); //paleta de colores if not(roms_load(@memoria_temp,timepilot_pal)) then exit; for f:=0 to 31 do begin bit0:= (memoria_temp[f+$20] shr 1) and $01; bit1:= (memoria_temp[f+$20] shr 2) and $01; bit2:= (memoria_temp[f+$20] shr 3) and $01; bit3:= (memoria_temp[f+$20] shr 4) and $01; bit4:= (memoria_temp[f+$20] shr 5) and $01; colores[f].r:=$19*bit0+$24*bit1+$35*bit2+$40*bit3+$4d*bit4; bit0:= (memoria_temp[f+$20] shr 6) and $01; bit1:= (memoria_temp[f+$20] shr 7) and $01; bit2:= (memoria_temp[f] shr 0) and $01; bit3:= (memoria_temp[f] shr 1) and $01; bit4:= (memoria_temp[f] shr 2) and $01; colores[f].g:=$19*bit0+$24*bit1+$35*bit2+$40*bit3+$4d*bit4; bit0:= (memoria_temp[f] shr 3) and $01; bit1:= (memoria_temp[f] shr 4) and $01; bit2:= (memoria_temp[f] shr 5) and $01; bit3:= (memoria_temp[f] shr 6) and $01; bit4:= (memoria_temp[f] shr 7) and $01; colores[f].b:=$19*bit0+$24*bit1+$35*bit2+$40*bit3+$4d*bit4; end; set_pal(colores,$40); //CLUT Sprites for f:=0 to $ff do gfx[1].colores[f]:=memoria_temp[$40+f] and $f; //CLUT chars for f:=0 to $7f do gfx[0].colores[f]:=(memoria_temp[$140+f] and $f)+$10; //Final marcade.dswa:=$ff; marcade.dswb:=$4b; marcade.dswa_val:=@timepilot_dip_a; marcade.dswb_val:=@timepilot_dip_b; timepilot_reset; timepilot_iniciar:=true; end; end.
unit MFichas.View.Dialog.PedirSenha; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.Edit, FMX.ListBox, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.DB, MFichas.Model.Usuario; type TFrameViewPedirSenha = class(TFrame) LayoutPrincipal: TLayout; RectanglePrincipal: TRectangle; LayoutRectangleTop: TLayout; LayoutRectangleClient: TLayout; LayoutRectangleBottom: TLayout; LabelTitulo: TLabel; LayoutDireita: TLayout; LayoutEsquerda: TLayout; RoundRectBotaoConfirmar: TRoundRect; RoundRectBotaoCancelar: TRoundRect; LabelBotaoConfirmar: TLabel; LabelBotaoCancelar: TLabel; LabelUsuario: TLabel; ComboBoxUsuario: TComboBox; Label1: TLabel; EditSenha: TEdit; RectangleSombra: TRectangle; FDMemTableUsuarios: TFDMemTable; private { Private declarations } procedure PreencherUsuariosNoComboBox; public { Public declarations } procedure ConfigurarTamanhoDoModal(AParent: TForm); procedure PreencherTodosUsuariosNoComboBox; procedure PreencherUsuariosFiscaisNoComboBox; procedure PreencherUsuariosGerentesNoComboBox; end; implementation {$R *.fmx} { TFrame1 } { TFrameViewPedirSenha } procedure TFrameViewPedirSenha.ConfigurarTamanhoDoModal(AParent: TForm); begin Self.Align := TAlignLayout.Contents; Self.Visible := False; Self.Parent := AParent; Self.RectanglePrincipal.Margins.Top := AParent.Height / 4.5; Self.RectanglePrincipal.Margins.Bottom := AParent.Height / 4.5; Self.RectanglePrincipal.Margins.Left := AParent.Width / 10; Self.RectanglePrincipal.Margins.Right := AParent.Width / 10; Self.RectangleSombra.Visible := True; Self.Visible := True; end; procedure TFrameViewPedirSenha.PreencherTodosUsuariosNoComboBox; begin TModelUsuario.New .Funcoes .Buscar .FDMemTable(FDMemTableUsuarios) .BuscarTodosAtivos .&End .&End; PreencherUsuariosNoComboBox; end; procedure TFrameViewPedirSenha.PreencherUsuariosFiscaisNoComboBox; begin TModelUsuario.New .Funcoes .Buscar .FDMemTable(FDMemTableUsuarios) .BuscarFiscais .&End .&End; PreencherUsuariosNoComboBox; end; procedure TFrameViewPedirSenha.PreencherUsuariosGerentesNoComboBox; begin TModelUsuario.New .Funcoes .Buscar .FDMemTable(FDMemTableUsuarios) .BuscarProprietarios .&End .&End; PreencherUsuariosNoComboBox; end; procedure TFrameViewPedirSenha.PreencherUsuariosNoComboBox; begin FDMemTableUsuarios.First; while not FDMemTableUsuarios.Eof do begin ComboBoxUsuario.Items.Add(FDMemTableUsuarios.FieldByName('LOGIN').AsString.ToUpper); FDMemTableUsuarios.Next; end; end; end.
unit IRCUtilsTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry; type TIRCUtilsTests = class(TTestCase) published procedure TestRemoveOPVoiceChars; end; implementation uses IRCUtils; procedure TIRCUtilsTests.TestRemoveOPVoiceChars; begin CheckEquals('Op', TIRCUtils.RemoveOPVoicePrefix('@Op')); CheckEquals('Voice', TIRCUtils.RemoveOPVoicePrefix('+Voice')); CheckEquals('User+@', TIRCUtils.RemoveOPVoicePrefix('User+@')); end; initialization RegisterTest(TIRCUtilsTests); end.
unit FuncUn; interface uses Windows; function wsprintf(Output: PChar; Format: PChar): Integer; cdecl; varargs; function AbsL(a: Integer): Integer; Assembler; function MaxZero(a: Integer): Integer; Assembler; function Max(AValueOne, AValueTwo: Integer): Integer; function Min(AValueOne, AValueTwo: Integer): Integer; function IntToStr(Value: Integer) : String; function StrToInt(const S : String) : Integer; procedure _DbgPrint(const Format: String); cdecl; function _FormatC(const Format: String): String; cdecl; function NtQueryTimerResolution(var MinRes: DWORD; var MaxRes: DWORD; var ActRes: DWORD): DWORD; stdcall; external 'ntdll.dll'; function NtSetTimerResolution(DesiredResolution: DWORD; SetResolution: BOOL; var CurrentResolution: DWORD): DWORD; stdcall; external 'ntdll.dll'; function NtDelayExecution(Alertable: BOOL; var DelayInterval: Int64): DWORD; stdcall; external 'ntdll.dll'; const // allows us to use "varargs" in Delphi DbgPrint: procedure(const Format: String); cdecl varargs = _DbgPrint; FormatC: function(const Format: string): string; cdecl varargs = _FormatC; implementation function wsprintf(Output: PChar; Format: PChar): Integer; cdecl; varargs; external 'user32.dll' name 'wsprintfA'; function AbsL(a: Integer): Integer; Assembler; // -> EAX = a asm cdq xor eax,edx sub eax,edx end; // a = (a < 0) ? 0 : a; function MaxZero(a: Integer): Integer; Assembler; // -> EAX = a asm xor edx, edx cmp eax, edx setl dl sub edx, 1 and edx, eax mov eax, edx end; function Max(AValueOne, AValueTwo: Integer): Integer; begin if AValueOne < AValueTwo then Result := AValueTwo else Result := AValueOne; end; function Min(AValueOne, AValueTwo: Integer): Integer; begin if AValueOne > AValueTwo then Result := AValueTwo else Result := AValueOne; end; function IntToStr(Value: Integer) : String; var Int : Integer; Ch : Char; begin Result := ''; repeat Int := Value mod 10; Value := Value div 10; Result := Result + Chr(Int+48); until Value = 0; For Int := 1 to Length(Result) div 2 do begin Ch := Result[Int]; Result[Int] := Result[Length(Result)-Int+1]; Result[Length(Result)-Int+1] := Ch; end; end; function StrToInt(const S : String) : Integer; var N, Len : Integer; begin Result := 0; Len := Length(S); For N := 1 to Len do begin Result := Result*10; Result := Result + (Ord(S[N])-48); end; end; function _FormatC(const Format: string): string; cdecl; const StackSlotSize = SizeOf(Pointer); var Args: va_list; Len: Integer; Buffer: array[0..1024] of Char; begin // va_start(Args, Format) Args := va_list(PAnsiChar(@Format) + ((SizeOf(Format) + StackSlotSize - 1) and not (StackSlotSize - 1))); Len := wvsprintf(Buffer, PChar(Format), Args); SetString(Result, Buffer, Len); end; {$IFDEF DBGLOG} procedure _DbgPrint(const Format: String); cdecl; const StackSlotSize = SizeOf(Pointer); var Args: va_list; Len: Integer; str: array[0..1024] of Char; begin // va_start(Args, Format) Args := va_list(PAnsiChar(@Format) + ((SizeOf(Format) + StackSlotSize - 1) and not (StackSlotSize - 1))); Len := Windows.wvsprintf(str, PChar(Format), Args); Windows.OutputDebugStringA(str); end; {$ENDIF} {$IFNDEF DBGLOG} procedure _DbgPrint(const Format: String); cdecl; begin // end; {$ENDIF} end.
unit TestFramework.DataValidators.TestTNumericDataValidator; interface uses TestFramework, System.SysUtils, System.Variants, Interfaces.IDataValidator, DataValidators.TNumericDataValidator; type TestTNumericDataValidator = class(TTestCase) strict private FNumericDataValidator: IDataValidator; public procedure SetUp; override; procedure TearDown; override; published procedure TestParse_Numeric; procedure TestParse_StringNumeric_Valid; procedure TestParse_StringNumeric_Invalid; end; implementation procedure TestTNumericDataValidator.SetUp; begin FNumericDataValidator := TNumericDataValidator.Create; end; procedure TestTNumericDataValidator.TearDown; begin end; procedure TestTNumericDataValidator.TestParse_Numeric; var ReturnValue: Boolean; AValue: Variant; begin AValue := 1232132.43232; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = True); end; procedure TestTNumericDataValidator.TestParse_StringNumeric_Invalid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '12,32,1,32.43232'; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = False); end; procedure TestTNumericDataValidator.TestParse_StringNumeric_Valid; var ReturnValue: Boolean; AValue: Variant; begin AValue := '1232132.43232'; ReturnValue := FNumericDataValidator.Parse(AValue); Check(ReturnValue = True); end; initialization // Register any test cases with the test runner RegisterTest(TestTNumericDataValidator.Suite); end.
program arrays; var a : array[0..10] of integer; var i, x, temp : integer; var avg : real; begin x := 10; avg := 0.0; // Example from http://www.tutorialspoint.com/pascal/pascal_arrays.htm writeln('The next loop will calculate the average of the array.'); for i := 0 to 10 do begin a[i] := i; avg := avg + a[i]; writeln('running total:', avg); end; avg := avg / 11.0; writeln('average:',avg); writeln(''); for i := 0 to 5 do begin temp := a[i]; a[i] := a[x]; a[x] := temp; x := x - 1; end; writeln('The next prints show the array after reversing.'); for i := 0 to 10 do begin writeln(a[i]); end; end.
unit OwnerList; { Hidden Paths of Delphi 3, by Ray Lischner. Informant Press, 1997. Copyright © 1997 Tempest Software, Inc. OwnerList: list class that owns the objects in the list. Use TOwnerList instead of TList when the list contains the sole references to the objects. Delete an object from the list, and the owner list automatically frees the object. Free the list, and it frees every object in the list. } interface uses Classes; { List class that owns its items. } type TOwnerList = class private fList: TList; function GetItem(Index: Integer): TObject; procedure SetItem(Index: Integer; Item: TObject); function GetCount: Integer; protected property Items[Index: Integer]: TObject read GetItem write SetItem; public constructor Create; virtual; destructor Destroy; override; function Add(Item: TObject): Integer; virtual; procedure Clear; virtual; procedure Delete(Index: Integer); virtual; function IndexOf(Item: TObject): Integer; virtual; function Remove(Item: TObject): Integer; property Count: Integer read GetCount; end; implementation { This class is similar to TList, except it owns the items in the list. Deleting an item deletes the object. Clearing the list deletes all the objects. } constructor TOwnerList.Create; begin inherited Create; fList := TList.Create; end; destructor TOwnerList.Destroy; begin if fList <> nil then Clear; fList.Free; inherited Destroy; end; function TOwnerList.GetItem(Index: Integer): TObject; begin Result := fList[Index] end; procedure TOwnerList.SetItem(Index: Integer; Item: TObject); var OldItem: TObject; begin OldItem := fList[Index]; if OldItem <> Item then begin fList[Index] := nil; OldItem.Free; end; fList[Index] := Item; end; function TOwnerList.GetCount: Integer; begin Result := fList.Count end; function TOwnerList.Add(Item: TObject): Integer; begin Result := fList.Add(Item) end; { Delete items starting at the end of the list because that is much faster than starting at the beginning of the list. } procedure TOwnerList.Clear; var I: Integer; begin for I := fList.Count-1 downto 0 do Delete(I); end; procedure TOwnerList.Delete(Index: Integer); var Item: TObject; begin Item := fList[Index]; fList.Delete(Index); Item.Free; end; function TOwnerList.IndexOf(Item: TObject): Integer; begin Result := fList.IndexOf(Item); end; function TOwnerList.Remove(Item: TObject): Integer; begin Result := IndexOf(Item); if Result >= 0 then Delete(Result); end; end.
unit tdl_glob; { Contains global constants and type definitions. } interface uses support; const maxTitles=maxbufsize div sizeof(word); maxCacheableTitles=maxbufsize div sizeof(longint); TDLtitleFull='The Total DOS Launcher, v. 20200925'; TDLtitle='The Total DOS Launcher'; (*TDLstatus='F1=Help~³~'#24'/'#25'/PgUp/PgDn/Home/End = Navigate~³~Enter = START~³~ESC=exit~³~';*) TDLstatus='F1=Help~³~'#24'/'#25'/PgUp/PgDn/Home/End = Navigate~³~Enter = LAUNCH~³~ESC = exit~³~'; jumpLabel='Jump by letter: '; numAboutLines=9; AboutText:array[0..numAboutLines-1] of pChar=( '', ' Project originator: Jim Leonard', ' ', ' We owe a debt of gratitude to:', ' Randy Hyde (swapping tech)', ' Duncan Murdoch (stream tricks)', ' Norbert Juffa (system library optimization)', ' Bob Ainsbury (interface primitives)', '' ); {metadata bitflag icon indicators} favicon=#03; {heart} favIconCol:byte=$0f; unpicon=#18; unpIconCol:byte=$0f; immediateExit:boolean=false; type PTitleArray=^TTitleArray; TTitleArray=array[0..maxTitles] of word; PTitleOffsets=^TTitleOffsets; TTitleOffsets=array[0..maxCacheableTitles-1] of longint; baseftype=string[12]; cmdlinetype=string[127-sizeof(baseftype)]; titleStrType=string[132]; {Max screenmode we'll support is 132x60} handlertype=(extraction,execution); userlevels=(kiosk,regular,power); MD5hash=array[0..15] of byte; PFileStruct=^TFileStruct; TFileStruct=record ID:word; name:array[0..12-1] of char; end; PTitleStruct=^TTitleStruct; TTitleStruct=record ID:word; Hash:MD5hash; title:titleStrType; end; implementation end.
unit Helper; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Interface to 64-bit helper NOTE: These functions are NOT thread-safe. Do not call them from multiple threads simultaneously. $jrsoftware: issrc/Projects/Helper.pas,v 1.14 2010/10/20 02:43:26 jr Exp $ } interface uses Windows, SysUtils, Struct; function GetHelperResourceName: String; function HelperGrantPermission(const AObjectType: DWORD; const AObjectName: String; const AEntries: TGrantPermissionEntry; const AEntryCount: Integer; const AInheritance: DWORD): DWORD; procedure HelperRegisterTypeLibrary(const AUnregister: Boolean; Filename: String); procedure SetHelperExeFilename(const Filename: String); procedure StopHelper(const DelayAfterStopping: Boolean); implementation {x$DEFINE HELPERDEBUG} uses Forms, Int64Em, CmnFunc, CmnFunc2, PathFunc, Main, InstFunc, Logging, Msgs, MsgIDs; const HELPER_VERSION = 105; const REQUEST_PING = 1; REQUEST_GRANT_PERMISSION = 2; REQUEST_REGISTER_SERVER = 3; { no longer used } REQUEST_REGISTER_TYPE_LIBRARY = 4; type TRequestGrantPermissionData = record ObjectType: DWORD; EntryCount: DWORD; Inheritance: DWORD; ObjectName: array[0..4095] of WideChar; Entries: array[0..MaxGrantPermissionEntries-1] of TGrantPermissionEntry; end; TRequestRegisterServerData = record Unregister: BOOL; FailCriticalErrors: BOOL; Filename: array[0..4095] of WideChar; Directory: array[0..4095] of WideChar; end; TRequestRegisterTypeLibraryData = record Unregister: BOOL; Filename: array[0..4095] of WideChar; end; TRequestData = record SequenceNumber: DWORD; Command: DWORD; DataSize: DWORD; case Integer of 0: (Data: array[0..0] of Byte); 1: (GrantPermissionData: TRequestGrantPermissionData); 2: (RegisterServerData: TRequestRegisterServerData); 3: (RegisterTypeLibraryData: TRequestRegisterTypeLibraryData); end; TResponseData = record SequenceNumber: DWORD; StatusCode: DWORD; ErrorCode: DWORD; DataSize: DWORD; Data: array[0..0] of Byte; { currently, no data is ever returned } end; THelper = class private FRunning, FNeedsRestarting: Boolean; FProcessHandle, FPipe: THandle; FProcessID: DWORD; FCommandSequenceNumber: DWORD; FProcessMessagesProc: procedure of object; FRequest: TRequestData; FResponse: TResponseData; procedure Call(const ACommand, ADataSize: DWORD); procedure InternalCall(const ACommand, ADataSize: DWORD; const AllowProcessMessages: Boolean); procedure Start; public destructor Destroy; override; function GrantPermission(const AObjectType: DWORD; const AObjectName: String; const AEntries: TGrantPermissionEntry; const AEntryCount: Integer; const AInheritance: DWORD): DWORD; procedure RegisterTypeLibrary(const AUnregister: Boolean; Filename: String); procedure Stop(const DelayAfterStopping: Boolean); end; var HelperMainInstance: THelper; HelperExeFilename: String; HelperPipeNameSequence: LongWord; function GetHelperResourceName: String; begin {$R HelperEXEs.res} case ProcessorArchitecture of paX64: Result := 'HELPER_EXE_AMD64'; else Result := ''; end; end; procedure SetHelperExeFilename(const Filename: String); begin HelperExeFilename := Filename; end; procedure StopHelper(const DelayAfterStopping: Boolean); begin HelperMainInstance.Stop(DelayAfterStopping); end; function HelperGrantPermission(const AObjectType: DWORD; const AObjectName: String; const AEntries: TGrantPermissionEntry; const AEntryCount: Integer; const AInheritance: DWORD): DWORD; begin Result := HelperMainInstance.GrantPermission(AObjectType, AObjectName, AEntries, AEntryCount, AInheritance); end; procedure HelperRegisterTypeLibrary(const AUnregister: Boolean; Filename: String); begin HelperMainInstance.RegisterTypeLibrary(AUnregister, Filename); end; procedure FillWideCharBuffer(var Buf: array of WideChar; const S: String); {$IFDEF UNICODE} begin if High(Buf) <= 0 then InternalError('FillWideCharBuffer: Invalid Buf'); if Length(S) > High(Buf) then InternalError('FillWideCharBuffer: String too long'); StrPLCopy(Buf, S, High(Buf)); end; {$ELSE} var SourceLen, DestLen: Integer; begin if High(Buf) <= 0 then InternalError('FillWideCharBuffer: Invalid Buf'); SourceLen := Length(S); if SourceLen = 0 then DestLen := 0 else begin DestLen := MultiByteToWideChar(CP_ACP, 0, PChar(S), SourceLen, Buf, High(Buf)); if DestLen <= 0 then InternalError('FillWideCharBuffer: MultiByteToWideChar failed'); end; Buf[DestLen] := #0; end; {$ENDIF} { THelper } destructor THelper.Destroy; begin Stop(False); inherited; end; procedure THelper.Start; const FILE_FLAG_FIRST_PIPE_INSTANCE = $00080000; InheritableSecurity: TSecurityAttributes = ( nLength: SizeOf(InheritableSecurity); lpSecurityDescriptor: nil; bInheritHandle: True); var PerformanceCount: Integer64; PipeName: String; Pipe, RemotePipe: THandle; Mode: DWORD; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin Log('Starting 64-bit helper process.'); { We don't *have* to check IsWin64 here; the helper *should* run fine without the new APIs added in 2003 SP1. But let's be consistent and disable 64-bit functionality across the board when the user is running 64-bit Windows and IsWin64=False. } if not IsWin64 then InternalError('Cannot utilize 64-bit features on this version of Windows'); if HelperExeFilename = '' then InternalError('64-bit helper EXE wasn''t extracted'); repeat { Generate a very unique pipe name } Inc(HelperPipeNameSequence); FCommandSequenceNumber := GetTickCount; if not QueryPerformanceCounter(TLargeInteger(PerformanceCount)) then GetSystemTimeAsFileTime(TFileTime(PerformanceCount)); PipeName := Format('\\.\pipe\InnoSetup64BitHelper-%.8x-%.8x-%.8x-%.8x%.8x', [GetCurrentProcessId, HelperPipeNameSequence, FCommandSequenceNumber, PerformanceCount.Hi, PerformanceCount.Lo]); { Create the pipe } Pipe := CreateNamedPipe(PChar(PipeName), PIPE_ACCESS_DUPLEX or FILE_FLAG_OVERLAPPED or FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE or PIPE_WAIT, 1, 8192, 8192, 0, nil); if Pipe <> INVALID_HANDLE_VALUE then Break; { Loop if there's a name clash (ERROR_PIPE_BUSY), otherwise raise error } if GetLastError <> ERROR_PIPE_BUSY then Win32ErrorMsg('CreateNamedPipe'); until False; try { Create an inheritable handle to the pipe for the helper to use } RemotePipe := CreateFile(PChar(PipeName), GENERIC_READ or GENERIC_WRITE, 0, @InheritableSecurity, OPEN_EXISTING, 0, 0); if RemotePipe = INVALID_HANDLE_VALUE then Win32ErrorMsg('CreateFile'); try Mode := PIPE_READMODE_MESSAGE or PIPE_WAIT; if not SetNamedPipeHandleState(RemotePipe, Mode, nil, nil) then Win32ErrorMsg('SetNamedPipeHandleState'); FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); if not CreateProcess(PChar(HelperExeFilename), PChar(Format('helper %d 0x%x', [HELPER_VERSION, RemotePipe])), nil, nil, True, CREATE_DEFAULT_ERROR_MODE or CREATE_NO_WINDOW, nil, PChar(GetSystemDir), StartupInfo, ProcessInfo) then Win32ErrorMsg('CreateProcess'); FRunning := True; FNeedsRestarting := False; FProcessHandle := ProcessInfo.hProcess; FProcessID := ProcessInfo.dwProcessId; FPipe := Pipe; Pipe := 0; { ensure the 'except' section can't close it now } CloseHandle(ProcessInfo.hThread); LogFmt('Helper process PID: %u', [FProcessID]); finally { We don't need a handle to RemotePipe after creating the process } CloseHandle(RemotePipe); end; except if Pipe <> 0 then CloseHandle(Pipe); raise; end; end; procedure THelper.Stop(const DelayAfterStopping: Boolean); { Stops the helper process if it's running } var ExitCode: DWORD; begin if not FRunning then Exit; { Before attempting to stop anything, set FNeedsRestarting to ensure Call can never access a partially-stopped helper } FNeedsRestarting := True; LogFmt('Stopping 64-bit helper process. (PID: %u)', [FProcessID]); { Closing our handle to the pipe will cause the helper's blocking ReadFile call to return False, and the process to exit } CloseHandle(FPipe); FPipe := 0; while WaitForSingleObject(FProcessHandle, 10000) = WAIT_TIMEOUT do begin { It should never have to resort to terminating the process, but if the process for some unknown reason didn't exit in response to our closing the pipe, it should be safe to kill it since it most likely isn't doing anything other than waiting for a request. } Log('Helper isn''t responding; killing it.'); TerminateProcess(FProcessHandle, 1); end; if GetExitCodeProcess(FProcessHandle, ExitCode) then begin if ExitCode = 0 then Log('Helper process exited.') else LogFmt('Helper process exited with failure code: 0x%x', [ExitCode]); end else Log('Helper process exited, but failed to get exit code.'); CloseHandle(FProcessHandle); FProcessHandle := 0; FProcessID := 0; FRunning := False; { Give it extra time to fully terminate to ensure that the EXE isn't still locked on SMP systems when we try to delete it in DeinitSetup. (Note: I'm not 100% certain this is needed; I don't have an SMP AMD64 system to test on. It didn't seem to be necessary on IA64, but I suspect that may be because it doesn't execute x86 code in true SMP fashion.) This also limits the rate at which new helper processes can be spawned, which is probably a good thing. } if DelayAfterStopping then Sleep(250); end; procedure THelper.InternalCall(const ACommand, ADataSize: DWORD; const AllowProcessMessages: Boolean); var RequestSize, BytesRead, LastError: DWORD; OverlappedEvent: THandle; Res: BOOL; Overlapped: TOverlapped; begin Inc(FCommandSequenceNumber); { On entry, only Request.Data needs to be filled } FRequest.SequenceNumber := FCommandSequenceNumber; FRequest.Command := ACommand; FRequest.DataSize := ADataSize; RequestSize := Cardinal(@TRequestData(nil^).Data) + ADataSize; try {$IFDEF HELPERDEBUG} LogFmt('Helper[%u]: Sending request (size: %u): Seq=%u, Command=%u, DataSize=%u', [FProcessID, RequestSize, FRequest.SequenceNumber, FRequest.Command, FRequest.DataSize]); {$ENDIF} { Create event object to use in our Overlapped structure. (Technically, I'm not sure we need the event object -- we could just wait on the pipe object instead, however the SDK docs discourage this.) } OverlappedEvent := CreateEvent(nil, True, False, nil); if OverlappedEvent = 0 then Win32ErrorMsg('CreateEvent'); try FillChar(Overlapped, SizeOf(Overlapped), 0); Overlapped.hEvent := OverlappedEvent; if not TransactNamedPipe(FPipe, @FRequest, RequestSize, @FResponse, SizeOf(FResponse), BytesRead, @Overlapped) then begin if GetLastError <> ERROR_IO_PENDING then Win32ErrorMsg('TransactNamedPipe'); { Operation is pending; wait for it to complete. (Note: Waiting is never optional. The system will modify Overlapped when the operation completes; if we were to return early for whatever reason, the stack would get corrupted.) } try if AllowProcessMessages and Assigned(FProcessMessagesProc) then begin repeat { Process any pending messages first because MsgWaitForMultipleObjects (called below) only returns when *new* messages arrive } FProcessMessagesProc; until MsgWaitForMultipleObjects(1, OverlappedEvent, False, INFINITE, QS_ALLINPUT) <> WAIT_OBJECT_0+1; end; finally { Call GetOverlappedResult with bWait=True, even if exception occurred } Res := GetOverlappedResult(FPipe, Overlapped, BytesRead, True); LastError := GetLastError; end; if not Res then Win32ErrorMsgEx('TransactNamedPipe/GetOverlappedResult', LastError); end; finally CloseHandle(OverlappedEvent); end; {$IFDEF HELPERDEBUG} LogFmt('Helper[%u]: Got response (size: %u): Seq=%u, StatusCode=%u, ErrorCode=%u, DataSize=%u', [FProcessID, BytesRead, FResponse.SequenceNumber, FResponse.StatusCode, FResponse.ErrorCode, FResponse.DataSize]); {$ENDIF} if (Cardinal(BytesRead) < Cardinal(@TResponseData(nil^).Data)) or (FResponse.DataSize <> Cardinal(BytesRead) - Cardinal(@TResponseData(nil^).Data)) then InternalError('Helper: Response message has wrong size'); if FResponse.SequenceNumber <> FRequest.SequenceNumber then InternalError('Helper: Wrong sequence number'); if FResponse.StatusCode = 0 then InternalError('Helper: Command did not execute'); except { If an exception occurred, then the helper may have crashed or is in some weird state. Attempt to stop it now, and also set FNeedsRestarting to ensure it's restarted on the next call in case our stop attempt here fails for some reason. } FNeedsRestarting := True; Log('Exception while communicating with helper:' + SNewLine + GetExceptMessage); Stop(True); raise; end; end; procedure THelper.Call(const ACommand, ADataSize: DWORD); begin { Start/restart helper if needed } if not FRunning or FNeedsRestarting then begin Stop(True); Start; end else begin { It is running -- or so we think. Before sending the specified request, send a ping request to verify that it's still alive. It may have somehow died since we last talked to it (unlikely, though). } try InternalCall(REQUEST_PING, 0, False); except { Don't propogate any exception; just log it and restart the helper } Log('Ping failed; helper seems to have died.'); Stop(True); Start; end; end; InternalCall(ACommand, ADataSize, True); end; { High-level interface functions } function THelper.GrantPermission(const AObjectType: DWORD; const AObjectName: String; const AEntries: TGrantPermissionEntry; const AEntryCount: Integer; const AInheritance: DWORD): DWORD; begin if (AEntryCount < 1) or (AEntryCount > SizeOf(FRequest.GrantPermissionData.Entries) div SizeOf(FRequest.GrantPermissionData.Entries[0])) then InternalError('HelperGrantPermission: Invalid entry count'); FRequest.GrantPermissionData.ObjectType := AObjectType; FRequest.GrantPermissionData.EntryCount := AEntryCount; FRequest.GrantPermissionData.Inheritance := AInheritance; FillWideCharBuffer(FRequest.GrantPermissionData.ObjectName, AObjectName); Move(AEntries, FRequest.GrantPermissionData.Entries, AEntryCount * SizeOf(FRequest.GrantPermissionData.Entries[0])); Call(REQUEST_GRANT_PERMISSION, SizeOf(FRequest.GrantPermissionData)); Result := FResponse.ErrorCode; end; procedure THelper.RegisterTypeLibrary(const AUnregister: Boolean; Filename: String); { Registers or unregisters the specified type library inside the helper. Raises an exception on failure. } begin Filename := PathExpand(Filename); FRequest.RegisterTypeLibraryData.Unregister := AUnregister; FillWideCharBuffer(FRequest.RegisterTypeLibraryData.Filename, Filename); { Stop the helper before and after the call to be 100% sure the state of the helper is clean prior to and after registering. Can't trust foreign code. } Stop(False); Call(REQUEST_REGISTER_TYPE_LIBRARY, SizeOf(FRequest.RegisterTypeLibraryData)); Stop(False); case FResponse.StatusCode of 1: begin { The LoadTypeLib call failed } RaiseOleError('LoadTypeLib', FResponse.ErrorCode); end; 2: begin { The call to RegisterTypeLib was made; possibly succeeded } if (FResponse.ErrorCode <> S_OK) or AUnregister then RaiseOleError('RegisterTypeLib', FResponse.ErrorCode); end; 3: begin { The ITypeLib::GetLibAttr call failed } RaiseOleError('ITypeLib::GetLibAttr', FResponse.ErrorCode); end; 4: begin { The call to UnRegisterTypeLib was made; possibly succeeded } if (FResponse.ErrorCode <> S_OK) or not AUnregister then RaiseOleError('UnRegisterTypeLib', FResponse.ErrorCode); end; else InternalError('HelperRegisterTypeLibrary: StatusCode invalid'); end; end; initialization HelperMainInstance := THelper.Create; finalization FreeAndNil(HelperMainInstance); end.
unit DeviceWrapper; // Device and command wrappers. // Device will create an interrogation thread. The interrogation thread will ask for data and // make commands' interrogations. // Implementation detail: there is a circular buffer to communicate between producer(interrogation) // and consumer(gui) threads. interface uses BaseDevice, InputLine, Classes, Graphics, Windows, SyncObjs, Math, Activex, MSScriptControl_TLB; const maxDataSize = 3 * 1024 * 1024; type TCommandState = (waitingInitialization, initialized, waitingExecution); TCommand = class public Constructor Create(command : ICommandInfo; state : TCommandState); function NeedInitialize : boolean; function NeedExecute : boolean; function Executable : boolean; function Initializable : boolean; function Initialize : boolean; procedure Execute; procedure SetInitialized; function ShowForm : integer; procedure SetState(state : TCommandState); private commandInfo : ICommandInfo; commandState : TCommandState; end; TReadFromInputLineData = record // used in the circular buffer timeRead : double; data : double; lineIndex : integer; end; PReadFromInputLineData = ^TReadFromInputLineData; TDevice = class Constructor Create(baseRequestDevice : IBaseRequestOnlyDevice); function IsConnected : boolean; function GetInputLinesNumber : integer; function GetInputLine(inputLineIndex : integer) : TInputLine; function GetCommandsNumber : integer; function GetCommandName(index : integer) : string; function NeedSendInitializationForCommand(index : integer) : boolean; procedure Disconnect; procedure Connect(connectionCallback: IConnectionCallback); function GetName : string; procedure SetListeningFlag(flag : boolean); function GetListeningFlag() : boolean; function GetReadData() : PReadFromInputLineData; procedure ClearReadData(); procedure AddCommand(command : TCommand); overload; function AddCommand(index : integer; commandState : TCommandState) : TCommand; overload; function CreateCommandWrapper(index : integer) : TCommand; function GetWaitingCommand : TCommand; function GetInitializedCommand : TCommand; procedure DeleteCommand(command : TCommand); private requestOnlyDevice : IBaseRequestOnlyDevice; inputLines : TList; isListening : boolean; listenThread : TThread; readDataCircularBuf : array[1..maxDataSize] of TReadFromInputLineData; readDataIndexStart : integer; readDataIndexEnd : integer; commands : TList; commandsCrit : TCriticalSection; procedure CommitNewData(); function PrepareNewData() : PReadFromInputLineData; end; implementation type TListeningThread = class(TThread) Constructor Create(listenDevice : TDevice); procedure Execute; override; private device : TDevice; function ArrToInt(var arr : array of byte) : integer; end; { TDevice } procedure TDevice.AddCommand(command: TCommand); begin commandsCrit.Enter; self.commands.Add(command); commandsCrit.Leave; end; function TDevice.AddCommand(index: integer; commandState: TCommandState) : TCommand; var commandWrapper : TCommand; commandInfo : ICommandInfo; begin commandInfo := requestOnlyDevice.GetCommandInfo(index); commandWrapper := TCommand.Create(commandInfo, commandState); AddCommand(commandWrapper); Result := commandWrapper; end; procedure TDevice.ClearReadData; begin readDataIndexStart := readDataIndexEnd; end; procedure TDevice.CommitNewData; begin // This code will be used on x86 cpu, one thread is producer, another one is // consumer. For x86 here there is no need in memory fence or mutex. Inc(readDataIndexEnd); if (readDataIndexEnd = maxDataSize) then readDataIndexEnd := 1; end; procedure TDevice.Connect(connectionCallback: IConnectionCallback); begin requestOnlyDevice.Connect(connectionCallback); end; constructor TDevice.Create(baseRequestDevice: IBaseRequestOnlyDevice); var i : integer; var inputLine : TInputLine; var defaultGraphColors : Array of TColor; begin isListening := false; commands := TList.Create; commandsCrit := TCriticalSection.Create; SetLength(defaultGraphColors, 5); // hardcoded defaultGraphColors[0] := clRed; defaultGraphColors[1] := clGreen; defaultGraphColors[2] := clYellow; defaultGraphColors[3] := clBlue; defaultGraphColors[4] := clOlive; requestOnlyDevice := baseRequestDevice; inputLines := TList.Create; for i := 0 to requestOnlyDevice.GetInputLinesNumber -1 do begin inputLine := TInputLine.Create(requestOnlyDevice, i); if (i >= Length(defaultGraphColors)) then inputLine.SetGraphColor(RGB(Random(255), Random(255), Random(255))) else inputLine.SetGraphColor(defaultGraphColors[i]); inputLines.Add(inputLine); end; listenThread := TListeningThread.Create(self); readDataIndexStart := 1; readDataIndexEnd := 1; end; function TDevice.CreateCommandWrapper(index: integer): TCommand; var commandWrapper : TCommand; commandInfo : ICommandInfo; begin commandInfo := requestOnlyDevice.GetCommandInfo(index); commandWrapper := TCommand.Create(commandInfo, waitingInitialization); Result := commandWrapper; end; procedure TDevice.DeleteCommand(command: TCommand); var i : integer; begin self.commandsCrit.Enter; try for i := 0 to self.commands.Count - 1 do begin if (commands[i] = command) then begin TCommand(commands[i]).Free; commands.Delete(i); exit; end; end; finally self.commandsCrit.Leave; end; end; procedure TDevice.Disconnect; begin SetListeningFlag(false); requestOnlyDevice.Disconnect; end; function TDevice.GetCommandName(index: integer): string; begin Result := requestOnlyDevice.GetCommandInfo(index).GetName; end; function TDevice.GetCommandsNumber: integer; begin Result := requestOnlyDevice.GetCommandsNumber; end; function TDevice.GetInitializedCommand: TCommand; var i : integer; begin Result := nil; self.commandsCrit.Enter; try for i := 0 to self.commands.Count - 1 do begin if TCommand(commands[i]).commandState = initialized then begin Result := TCommand(commands[i]); commands.Delete(i); end; end; finally self.commandsCrit.Leave; end; end; function TDevice.GetInputLine(inputLineIndex: integer): TInputLine; begin Result := TInputLine(inputLines[inputLineIndex]); end; function TDevice.GetInputLinesNumber: integer; begin Result := requestOnlyDevice.GetInputLinesNumber; end; function TDevice.GetListeningFlag: boolean; begin Result := isListening; end; function TDevice.GetName: string; begin Result := requestOnlyDevice.GetName; end; function TDevice.GetReadData: PReadFromInputLineData; begin if (readDataIndexStart = readDataIndexEnd) then begin Result := nil; exit; end; Result := @readDataCircularBuf[readDataIndexStart]; // No mutex, memory fence needed Inc(readDataIndexStart); if (readDataIndexStart = maxDataSize) then readDataIndexStart := 1; end; function TDevice.GetWaitingCommand: TCommand; var i : integer; begin Result := nil; self.commandsCrit.Enter; try for i := 0 to self.commands.Count - 1 do begin if ((TCommand(commands[i])).commandState = waitingInitialization) or ((TCommand(commands[i])).commandState = waitingExecution) then begin Result := TCommand(commands[i]); end; end; finally self.commandsCrit.Leave; end; end; function TDevice.IsConnected : boolean; begin Result := requestOnlyDevice.IsConnected; end; function TDevice.NeedSendInitializationForCommand(index: integer): boolean; begin Result := requestOnlyDevice.GetCommandInfo(index).NeedSendInitialization; end; function TDevice.PrepareNewData: PReadFromInputLineData; begin Result := @readDataCircularBuf[readDataIndexEnd]; end; procedure TDevice.SetListeningFlag(flag: boolean); begin isListening := flag; if (flag) then listenThread.Resume else begin listenThread.Suspend; end; end; { TListeningThread } function TListeningThread.ArrToInt(var arr: array of byte): integer; var j : integer; begin Result := arr[0]; for j := 1 to Length(arr) - 1 do begin Result := Result shl 8; Result := Result + arr[j]; end; end; constructor TListeningThread.Create(listenDevice: TDevice); begin inherited Create(true); device := listenDevice; end; procedure TListeningThread.Execute; var listenLines,requestLines : TLineIndexesArray; var i,j,len : integer; var maxPerRequest : integer; var readResult, temp : TBytesArray; var inputStart, timeNow : int64; var freq : int64; var readValue : integer; var readData : PReadFromInputLineData; var intervalFromStart : double; var resBytesLen : integer; var command : TCommand; begin // SetThreadAffinityMask(Handle, 1); SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_HIGHEST); QueryPerformanceFrequency(freq); QueryPerformanceCounter(inputStart); while true do begin if (device.IsConnected) then begin command := device.GetWaitingCommand; if Assigned(command) then begin if command.NeedInitialize then begin if command.Initialize then command.SetInitialized else device.DeleteCommand(command); end else if command.NeedExecute then begin command.Execute; device.DeleteCommand(command); end; end; SetLength(listenLines, 0); for i := 0 to device.GetInputLinesNumber - 1 do begin if (device.GetInputLine(i).IsListening) then begin SetLength(listenLines, Length(listenLines) + 1); listenLines[Length(listenLines) - 1] := i; end; end; if (Length(listenLines) = 0) then Sleep(100) else begin if (Length(listenLines) = 1) then begin if (device.requestOnlyDevice.ReadFromInputLine(listenLines[0], readResult)) then begin QueryPerformanceCounter(timeNow); readValue := ArrToInt(readResult); intervalFromStart := (timeNow - inputStart) / freq; readData := device.PrepareNewData; readData^.data := device.GetInputLine(listenLines[0]).Calibrate(readValue); readData^.lineIndex := listenLines[0]; readData^.timeRead := intervalFromStart; device.CommitNewData; end; end else begin maxPerRequest := device.requestOnlyDevice.GetMaxInputLinesNumberPerRequest; for j := 0 to Length(listenLines) div maxPerRequest do begin len := min(maxPerRequest, Length(listenLines) - j * maxPerRequest); if (len = 0) then break; requestLines := Copy(listenLines, j * maxPerRequest, len); if (device.requestOnlyDevice.ReadFromInputLines(requestLines, readResult)) then begin QueryPerformanceCounter(timeNow); resBytesLen := Length(readResult) div Length(requestLines); for i := 0 to len - 1 do begin temp := Copy(readResult, i * resBytesLen, resBytesLen); readValue := ArrToInt(temp); intervalFromStart := (timeNow - inputStart) / freq; readData := device.PrepareNewData; readData^.lineIndex := listenLines[j * maxPerRequest + i]; readData^.data := device.GetInputLine(readData.lineIndex).Calibrate(readValue); readData^.timeRead := intervalFromStart; device.CommitNewData; end; end; end; end; end; end else Sleep(100); end; end; { TCommand } constructor TCommand.Create(command: ICommandInfo; state : TCommandState); begin commandInfo := command; commandState := state; end; function TCommand.Executable: boolean; begin Result := self.commandInfo.NeedExecute; end; procedure TCommand.Execute; begin self.commandInfo.Execute; end; function TCommand.Initializable: boolean; begin Result := self.commandInfo.NeedSendInitialization; end; function TCommand.Initialize: boolean; begin Result := self.commandInfo.Initialize; end; function TCommand.NeedExecute: boolean; begin Result := self.commandState = waitingExecution; end; function TCommand.NeedInitialize: boolean; begin Result := self.commandState = waitingInitialization; end; procedure TCommand.SetInitialized; begin self.commandState := initialized; end; procedure TCommand.SetState(state: TCommandState); begin self.commandState := state; end; function TCommand.ShowForm: integer; begin Result := self.commandInfo.ShowForm; end; end.
unit kwPopEditorLP2DP; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorLP2DP.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_LP2DP // // *Формат:* X Y anEditorControl pop:editor:LP2DP // *Описание:* Переводи значения точки из долей дюйма в пиксели. // *Пример:* // {code} // 100 100 focused:control:push pop:editor:LP2DP // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} TkwPopEditorLP2DP = {final} class(_kwEditorFromStackWord_) {* *Формат:* X Y anEditorControl pop:editor:LP2DP *Описание:* Переводи значения точки из долей дюйма в пиксели. *Пример:* [code] 100 100 focused:control:push pop:editor:LP2DP [code] } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorLP2DP {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses l3Units, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorLP2DP; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} // start class TkwPopEditorLP2DP procedure TkwPopEditorLP2DP.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_503C589F0334_var* var l_X, l_Y : Integer; l_SPoint : Tl3SPoint; //#UC END# *4F4CB81200CA_503C589F0334_var* begin //#UC START# *4F4CB81200CA_503C589F0334_impl* if aCtx.rEngine.IsTopInt then l_Y := aCtx.rEngine.PopInt else Assert(False, 'Не задана координата Y.'); if aCtx.rEngine.IsTopInt then l_X := aCtx.rEngine.PopInt else Assert(False, 'Не задана координата X.'); l_SPoint := anEditor.Canvas.LP2DP(l3Point(l_X, l_Y)); aCtx.rEngine.PushInt(l_SPoint.Y); aCtx.rEngine.PushInt(l_SPoint.X); //#UC END# *4F4CB81200CA_503C589F0334_impl* end;//TkwPopEditorLP2DP.DoWithEditor class function TkwPopEditorLP2DP.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:LP2DP'; end;//TkwPopEditorLP2DP.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit GX_eReverseStatement; interface uses Classes, GX_eSelectionEditorExpert; type TReverseStatementExpert = class(TSelectionEditorExpert) private FMadeChanges: Boolean; function ReverseOneLine(const S: string): string; function ReverseAssignment(var S: string): Boolean; function ReverseForLoop(var S: string): Boolean; protected function ProcessSelected(Lines: TStrings): Boolean; override; public class function GetName: string; override; constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; end; implementation uses SysUtils, GX_EditorExpert, GX_OtaUtils, GX_GenericUtils; { TReverseStatementExpert } constructor TReverseStatementExpert.Create; begin inherited Create; end; function TReverseStatementExpert.GetDefaultShortCut: TShortCut; begin Result := scAlt + scShift + Ord('R'); end; function TReverseStatementExpert.GetDisplayName: string; resourcestring SReverseStatementName = 'Reverse Statement'; begin Result := SReverseStatementName; end; function TReverseStatementExpert.GetHelpString: string; resourcestring SReverseStatementHelp = ' This expert reverses all assignment statements and the loop direction of ' + 'for loops in a selected block of code. ' + sLineBreak + 'For example, a statement like "Foo := Bar;" would be changed into: "Bar := Foo;" ' + 'and "for i := 0 to 99 do" into: "for i := 99 downto 0 do".' + sLineBreak + sLineBreak + ' This expert supports both Delphi and C++ assignments, but only Delphi for loops. ' + 'It expects all reversible statements to be contained on a single line.'; begin Result := SReverseStatementHelp; end; class function TReverseStatementExpert.GetName: string; begin Result := 'ReverseStatement'; end; function TReverseStatementExpert.HasConfigOptions: Boolean; begin Result := False; end; function TReverseStatementExpert.ProcessSelected(Lines: TStrings): Boolean; var i: Integer; begin Assert(Assigned(Lines)); FMadeChanges := False; for i := 0 to Lines.Count - 1 do Lines[i] := ReverseOneLine(Lines[i]); Result := FMadeChanges; end; function TReverseStatementExpert.ReverseOneLine(const S: string): string; begin Result := S; if ReverseForLoop(Result) then Exit; if ReverseAssignment(Result) then Exit; end; function TReverseStatementExpert.ReverseAssignment(var S: string): Boolean; var i: Integer; AssignOp: string; AssignPos: Integer; SemPos: Integer; StringBefore: string; StringAfter: string; TrailingString: string; SpaceBefore: string; SpaceAfter: string; LeadingSpace: string; begin if IsCPPSourceModule(GxOtaGetCurrentSourceEditor.FileName) then AssignOp := '=' else AssignOp := ':='; Result := False; if S = '' then Exit; AssignPos := Pos(AssignOp, S); SemPos := LastDelimiter(';', S); TrailingString := Copy(S, SemPos + 1, 9999); if (AssignPos > 1) and (SemPos > 3) and (Length(S) > AssignPos + 1) then begin if StrContains('//', S) then if Pos('//', S) < AssignPos then Exit; if StrContains('(*', S) then if Pos('(*', S) < AssignPos then Exit; if IsCPPSourceModule(GxOtaGetCurrentSourceEditor.FileName) then begin if StrContains('/*', S) then if Pos('/*', S) < AssignPos then Exit; if Pos(S, '==') = AssignPos then Exit; end else begin if StrContains('{', S) then if Pos('{', S) < AssignPos then Exit; end; i := 1; while IsCharWhitespace(S[i]) do begin LeadingSpace := LeadingSpace + S[i]; Inc(i); end; StringBefore := Copy(S, i, AssignPos - i); i := AssignPos - 1; if StringBefore <> '' then begin while IsCharWhitespace(S[i]) do begin SpaceBefore := S[i] + SpaceBefore; SetLength(StringBefore, Length(StringBefore) - 1); Dec(i) end; end; i := AssignPos + Length(AssignOp); while IsCharWhitespace(S[i]) do begin SpaceAfter := SpaceAfter + S[i]; Inc(i); end; StringAfter := Copy(S, i, SemPos - i); S := LeadingSpace + StringAfter + SpaceAfter + AssignOp + SpaceBefore + StringBefore + ';' + TrailingString; Result := True; FMadeChanges := True; end; end; function TReverseStatementExpert.ReverseForLoop(var S: string): Boolean; const cForString = 'for '; cAssignString = ':='; cToString = ' to '; cDownToString = ' downto '; cDoString = ' do'; var Down: Boolean; iCurr, iPrev: Integer; LeadingString: string; TrailingString: string; StringBefore: string; StringAfter: string; // Copy part of S from iFrom including to iTo excluding: function CopyS(iFrom, iTo: Integer): string; begin Result := Copy(S, iFrom, iTo - iFrom); end; // Search Pat in S, starting from iPrev: function PosInSFromPrev(const Pat: string): Integer; begin Result := CaseInsensitivePosFrom(Pat, S, iPrev); end; begin // STATE-comments: The two ^s show where iPrev and iCurr point to. // The sample input is: // LeadingStuff; for i := aaa to zzz do // trailing stuff Result := False; iPrev := 1; iCurr := PosInSFromPrev(cForString); if iCurr = 0 then Exit; // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ // iPrev iCurr iPrev := iCurr; iCurr := PosInSFromPrev(cAssignString); if iCurr = 0 then Exit; // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ Inc(iCurr, Length(cAssignString)); // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ LeadingString := CopyS(1, iCurr); iPrev := iCurr; iCurr := PosInSFromPrev(cDownToString); Down := iCurr > 0; if not Down then begin iCurr := PosInSFromPrev(cToString); if iCurr = 0 then Exit; end; // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ StringBefore := CopyS(iPrev, iCurr); if Down then Inc(iCurr, Length(cDownToString)) else Inc(iCurr, Length(cToString)); // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ iPrev := iCurr; iCurr := PosInSFromPrev(cDoString); if iCurr = 0 then Exit; // STATE: LeadingStuff; for i := aaa to zzz do // trailing stuff // ^ ^ StringAfter := CopyS(iPrev, iCurr); TrailingString := CopyS(iCurr, Succ(Length(S))); if Down then S := cToString else S := cDownToString; S := TrimRight(LeadingString) + ' ' + Trim(StringAfter) + S + Trim(StringBefore) + ' ' + TrimLeft(TrailingString); Result := True; FMadeChanges := True; end; initialization RegisterEditorExpert(TReverseStatementExpert); end.
unit uFrmMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, HPSocketSDKUnit, uPublic, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin, uServerPublic, uDataProcess, uFrmConfig; type TFrmMain = class(TForm) Panel1: TPanel; btnStop: TButton; btnStart: TButton; btnDisConn: TButton; GroupBox1: TGroupBox; LstDevices: TListView; GroupBox2: TGroupBox; lstMsg: TListBox; btnConfig: TButton; procedure FormCreate(Sender: TObject); procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnDisConnClick(Sender: TObject); procedure lstMsgKeyPress(Sender: TObject; var Key: Char); procedure LstDevicesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure btnConfigClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } procedure SetAppState(state: EnAppState); procedure WmAddLogMsg(var msg: TMessage); message WM_ADD_LOG; procedure WmAddDevice(var msg: TMessage); message WM_ADD_DEVICE; function GetLstDeviceInfoIndex(AConnID: DWORD): Integer; function SaveConfig: Boolean; function LoadConfig: Boolean; public { Public declarations } procedure OnRec(dwConnId: DWORD; const pData: Pointer; iLength: Integer); procedure OnClsConn(dwConnId: DWORD); end; var FrmMain: TFrmMain; implementation uses System.IniFiles; {$R *.dfm} {$REGION 'Socket事件'} function OnPrepareListen(soListen: Pointer): En_HP_HandleResult; stdcall; begin Result := HP_HR_OK; end; function OnAccept(dwConnId: DWORD; pClient: Pointer) : En_HP_HandleResult; stdcall; var ip: array [0 .. 40] of WideChar; ipLength: Integer; port: USHORT; vDeviceInfo: TDeviceInfo; begin ipLength := 40; if HP_Server_GetRemoteAddress(GHPServer, dwConnId, ip, @ipLength, @port) then begin if not GDeviceInfos.ContainsKey(dwConnId) then begin // New(vDeviceInfo); vDeviceInfo.IsDevice := False; vDeviceInfo.ConnectID := dwConnId; vDeviceInfo.ip := string(ip); vDeviceInfo.port := Word(port); GDeviceInfos.Add(dwConnId, vDeviceInfo); end; AddLogMsg('[%d,OnAccept] -> PASS(%s:%d)', [dwConnId, string(ip), port]); end else begin AddLogMsg('[[%d,OnAccept] -> HP_Server_GetClientAddress() Error', [dwConnId]); end; Result := HP_HR_OK; end; function OnServerShutdown(): En_HP_HandleResult; stdcall; begin AddLogMsg('[OnServerShutdown]', []); DisConnDataBase; Result := HP_HR_OK; end; function OnSend(dwConnId: DWORD; const pData: Pointer; iLength: Integer) : En_HP_HandleResult; stdcall; begin AddLogMsg('[%d,OnSend] -> (%d bytes)', [dwConnId, iLength]); Result := HP_HR_OK; end; function OnReceive(dwConnId: DWORD; const pData: Pointer; iLength: Integer) : En_HP_HandleResult; stdcall; begin AddLogMsg('[%d,OnReceive] -> (%d bytes)', [dwConnId, iLength]); FrmMain.OnRec(dwConnId, pData, iLength); Result := HP_HR_OK; end; function OnCloseConn(dwConnId: DWORD): En_HP_HandleResult; stdcall; begin FrmMain.OnClsConn(dwConnId); AddLogMsg('[%d,OnCloseConn]', [dwConnId]); Result := HP_HR_OK; end; function OnError(dwConnId: DWORD; enOperation: En_HP_SocketOperation; iErrorCode: Integer): En_HP_HandleResult; stdcall; begin AddLogMsg('[%d,OnError] -> OP:%d,CODE:%d', [dwConnId, Integer(enOperation), iErrorCode]); Result := HP_HR_OK; end; {$ENDREGION} function TFrmMain.SaveConfig: Boolean; var vIniFile: TIniFile; begin vIniFile := TIniFile.Create(GConfigFileName); try vIniFile.WriteString('Server', 'IP', GConfigInfo.IP); vIniFile.WriteInteger('Server', 'Port', GConfigInfo.Port); vIniFile.WriteString('DataBase', 'Host', GConfigInfo.DB_Host); vIniFile.WriteString('DataBase', 'DBName', GConfigInfo.DB_Name); vIniFile.WriteString('DataBase', 'DBAccount', GConfigInfo.DB_Account); vIniFile.WriteString('DataBase', 'DBPassWord', GConfigInfo.DB_PassWord); finally FreeAndNil(vIniFile); end; end; function TFrmMain.LoadConfig: Boolean; var vIniFile: TIniFile; begin vIniFile := TIniFile.Create(GConfigFileName); try GConfigInfo.IP := vIniFile.ReadString('Server', 'IP', ''); GConfigInfo.Port := vIniFile.ReadInteger('Server', 'Port', 0); GConfigInfo.DB_Host := vIniFile.ReadString('DataBase', 'Host', ''); GConfigInfo.DB_Name := vIniFile.ReadString('DataBase', 'DBName', ''); GConfigInfo.DB_Account := vIniFile.ReadString('DataBase', 'DBAccount', ''); GConfigInfo.DB_PassWord := vIniFile.ReadString('DataBase', 'DBPassWord', ''); finally FreeAndNil(vIniFile); end; end; procedure TFrmMain.SetAppState(state: EnAppState); begin GAppState := state; btnStart.Enabled := (GAppState = EnAppState.ST_STOPED); btnStop.Enabled := (GAppState = EnAppState.ST_STARTED); btnConfig.Enabled := (GAppState = EnAppState.ST_STOPED); btnDisConn.Enabled := ((GAppState = EnAppState.ST_STARTED) and (LstDevices.Selected <> nil)); end; procedure TFrmMain.WmAddDevice(var msg: TMessage); var vConnID: DWORD; vIndex: Integer; vItem: TListItem; begin vConnID := DWORD(msg.LParam); if not GDeviceInfos.ContainsKey(vConnID) then Exit; vIndex := GetLstDeviceInfoIndex(vConnID); if vIndex < 0 then begin // --没有找到,则添加, vItem := LstDevices.Items.Add; vItem.Caption := IntToStr(vConnID); vItem.SubItems.Add(string(GDeviceInfos[vConnID].GroupName)); vItem.SubItems.Add(string(GDeviceInfos[vConnID].ip)); vItem.SubItems.Add(IntToStr(GDeviceInfos[vConnID].port)); end else begin // --找到则修改GroupName LstDevices.Items[vIndex].Caption := IntToStr(vConnID); LstDevices.Items[vIndex].SubItems.Strings[0] := string(GDeviceInfos[vConnID].GroupName); LstDevices.Items[vIndex].SubItems.Strings[1] := string(GDeviceInfos[vConnID].ip); LstDevices.Items[vIndex].SubItems.Strings[2] := IntToStr(GDeviceInfos[vConnID].port); end; end; procedure TFrmMain.WmAddLogMsg(var msg: TMessage); var sText: string; begin sText := Format('%s %s', [FormatDateTime('yyyy-MM-dd HH:mm:ss', Now()), string(msg.LParam)]); if lstMsg.Items.Count > 100 then begin lstMsg.Items.Clear; end; lstMsg.Items.Add(sText); lstMsg.ItemIndex := lstMsg.Items.Count - 1; end; procedure TFrmMain.btnConfigClick(Sender: TObject); var F: TFrmConfig; begin if GAppState <> ST_STOPED then Exit; F := TFrmConfig.Create(Self); try F.edtIpAddress.Text := Trim(GConfigInfo.IP); F.edtPort.Value := GConfigInfo.Port; F.edtDataBaseHost.Text := Trim(GConfigInfo.DB_Host); F.edtDataBaseName.Text := Trim(GConfigInfo.DB_Name); F.edtAccount.Text := Trim(GConfigInfo.DB_Account); F.edtPassWord.Text := Trim(GConfigInfo.DB_PassWord); if F.ShowModal = mrOk then begin GConfigInfo.IP := Trim(F.edtIpAddress.Text); GConfigInfo.Port := F.edtPort.Value; GConfigInfo.DB_Host := Trim(F.edtDataBaseHost.Text); GConfigInfo.DB_Name := Trim(F.edtDataBaseName.Text); GConfigInfo.DB_Account := Trim(F.edtAccount.Text); GConfigInfo.DB_PassWord := Trim(F.edtPassWord.Text); SaveConfig(); end; finally FreeAndNil(F); end; end; procedure TFrmMain.btnDisConnClick(Sender: TObject); var dwConnId: DWORD; begin if LstDevices.Items.Count <= 0 then Exit; if LstDevices.Selected = nil then Exit; dwConnId := StrToIntDef(LstDevices.Selected.Caption, 0); if dwConnId = 0 then Exit; if HP_Server_Disconnect(GHPServer, dwConnId, 1) then AddLogMsg('(%d) Disconnect OK', [dwConnId]) else AddLogMsg('(%d) Disconnect Error', [dwConnId]); end; procedure TFrmMain.btnStartClick(Sender: TObject); var ip: PWideChar; port: USHORT; errorId: En_HP_SocketError; errorMsg: PWideChar; begin SetAppState(ST_STARTING); if not ConnDataBase then Exit; if HP_Server_Start(GHPServer, PWideChar(GConfigInfo.IP), GConfigInfo.Port) then begin AddLogMsg('Server Start OK -> (%s:%d)', [ip, port]); SetAppState(ST_STARTED); end else begin errorId := HP_Server_GetLastError(GHPServer); errorMsg := HP_Server_GetLastErrorDesc(GHPServer); AddLogMsg('Server Start Error -> %s(%d)', [errorMsg, Integer(errorId)]); SetAppState(ST_STOPED); end; end; procedure TFrmMain.btnStopClick(Sender: TObject); var errorId: En_HP_SocketError; errorMsg: PWideChar; begin SetAppState(ST_STOPING); AddLogMsg('Server Stop', []); if HP_Server_Stop(GHPServer) then begin SetAppState(ST_STOPED); end else begin errorId := HP_Server_GetLastError(GHPServer); errorMsg := HP_Server_GetLastErrorDesc(GHPServer); AddLogMsg('Stop Error -> %s(%d)', [errorMsg, Integer(errorId)]); end; end; procedure TFrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if GAppState <> ST_STOPED then begin CanClose := False; Application.MessageBox('服务正在运行, 不能关闭!', '警告', MB_ICONWARNING); end; end; procedure TFrmMain.FormCreate(Sender: TObject); begin GFrmMainHwnd := Self.Handle; // 创建监听器对象 GHPListener := Create_HP_TcpServerListener(); // 创建 Socket 对象 GHPServer := Create_HP_TcpServer(GHPListener); // 设置 Socket 监听器回调函数 HP_Set_FN_Server_OnPrepareListen(GHPListener, OnPrepareListen); HP_Set_FN_Server_OnAccept(GHPListener, OnAccept); HP_Set_FN_Server_OnSend(GHPListener, OnSend); HP_Set_FN_Server_OnReceive(GHPListener, OnReceive); HP_Set_FN_Server_OnClose(GHPListener, OnCloseConn); HP_Set_FN_Server_OnError(GHPListener, OnError); HP_Set_FN_Server_OnShutdown(GHPListener, OnServerShutdown); SetAppState(ST_STOPED); LoadConfig; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin // 销毁 Socket 对象 Destroy_HP_TcpServer(GHPServer); // 销毁监听器对象 Destroy_HP_TcpServerListener(GHPListener); end; function TFrmMain.GetLstDeviceInfoIndex(AConnID: DWORD): Integer; var I: Integer; begin Result := -1; for I := 0 to LstDevices.Items.Count - 1 do begin if LstDevices.Items[I].Caption = IntToStr(AConnID) then begin Result := I; Break; end; end; end; procedure TFrmMain.LstDevicesChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin btnDisConn.Enabled := ((GAppState = EnAppState.ST_STARTED) and (LstDevices.Selected <> nil)); end; procedure TFrmMain.lstMsgKeyPress(Sender: TObject; var Key: Char); begin if (Key = 'c') or (Key = 'C') then lstMsg.Items.Clear; end; procedure TFrmMain.OnRec(dwConnId: DWORD; const pData: Pointer; iLength: Integer); //var // vDataProcess: TDataProcess; begin TDataProcess.Create(dwConnId, pData, iLength); //vDataProcess := TDataProcess.Create(dwConnId, pData, iLength); // 拷贝至指针 //CopyMemory(vDataProcess.Data, pData, iLength); //vDataProcess.DataLen := iLength; //vDataProcess.Resume; end; procedure TFrmMain.OnClsConn(dwConnId: DWORD); var I: Integer; begin // --关闭链接时, 删除信息 if GDeviceInfos.ContainsKey(dwConnId) then begin GDeviceInfos.Remove(dwConnId); end; // --删除界面信息 for I := 0 to LstDevices.Items.Count - 1 do begin if LstDevices.Items[I].Caption = IntToStr(dwConnId) then begin LstDevices.Items[I].Delete; Break; end; end; end; // procedure TDoSerRec.Execute; // var // SendMsg : PTMsg; // begin // inherited; // try // Move(pdata, RecMsg, ilen); // try // case RecMsg.nType of // 1000 : begin // //处理消息 // Synchronize(showmsg); // New(SendMsg); // try // SendMsg.nType := 1001; // SendMsg.nMsg := 'Do Rec; Ready do other thing?'; // HP_Server_Send(pServer, FId, SendMsg, SizeOf(ttmsg)); // finally // Dispose(SendMsg); // end; // end; // end; // except // // end; // finally // // end; // end; end.
unit FuturesDataAccess; interface uses define_dealItem, BaseDataSet, QuickList_int, define_futures_quotes; type { 行情日线数据访问 } TFuturesData = record DealItem: PRT_DealItem; IsDataChangedStatus: Byte; DayDealData: TALIntegerList; FirstDealDate : Word; // 2 LastDealDate : Word; // 2 最后记录交易时间 DataSourceId: integer; end; TFuturesDataAccess = class(TBaseDataSetAccess) protected fFuturesData: TFuturesData; function GetFirstDealDate: Word; procedure SetFirstDealDate(const Value: Word); function GetLastDealDate: Word; procedure SetLastDealDate(const Value: Word); function GetEndDealDate: Word; procedure SetEndDealDate(const Value: Word); procedure SetDealItem(ADealItem: PRT_DealItem); function GetRecordItem(AIndex: integer): Pointer; override; function GetRecordCount: Integer; override; public constructor Create(ADealItem: PRT_DealItem; ADataSrcId: integer); destructor Destroy; override; function FindRecord(ADate: Integer): PRT_Quote_M1_Day; function CheckOutRecord(ADate: Integer): PRT_Quote_M1_Day; procedure Sort; override; property FirstDealDate: Word read GetFirstDealDate; property LastDealDate: Word read GetLastDealDate; property EndDealDate: Word read GetEndDealDate write SetEndDealDate; property DealItem: PRT_DealItem read fFuturesData.DealItem write SetDealItem; property DataSourceId: integer read fFuturesData.DataSourceId write fFuturesData.DataSourceId; end; implementation constructor TFuturesDataAccess.Create(ADealItem: PRT_DealItem; ADataSrcId: integer); begin //inherited; FillChar(fFuturesData, SizeOf(fFuturesData), 0); fFuturesData.DealItem := ADealItem; fFuturesData.DayDealData := TALIntegerList.Create; fFuturesData.FirstDealDate := 0; // 2 fFuturesData.LastDealDate := 0; // 2 最后记录交易时间 fFuturesData.DataSourceId := ADataSrcId; end; destructor TFuturesDataAccess.Destroy; var i: integer; tmpQuoteDay: PRT_Quote_M1_Day; begin for i := fFuturesData.DayDealData.Count - 1 downto 0 do begin tmpQuoteDay := PRT_Quote_M1_Day(fFuturesData.DayDealData.Objects[i]); FreeMem(tmpQuoteDay); end; fFuturesData.DayDealData.Clear; fFuturesData.DayDealData.Free; inherited; end; procedure TFuturesDataAccess.SetDealItem(ADealItem: PRT_DealItem); begin if nil <> ADealItem then begin if fFuturesData.DealItem <> ADealItem then begin end; end; fFuturesData.DealItem := ADealItem; if nil <> fFuturesData.DealItem then begin end; end; function TFuturesDataAccess.GetFirstDealDate: Word; begin Result := fFuturesData.FirstDealDate; end; procedure TFuturesDataAccess.SetFirstDealDate(const Value: Word); begin fFuturesData.FirstDealDate := Value; end; function TFuturesDataAccess.GetLastDealDate: Word; begin Result := fFuturesData.LastDealDate; end; procedure TFuturesDataAccess.SetLastDealDate(const Value: Word); begin fFuturesData.LastDealDate := Value; end; function TFuturesDataAccess.GetEndDealDate: Word; begin Result := 0; end; procedure TFuturesDataAccess.SetEndDealDate(const Value: Word); begin end; function TFuturesDataAccess.GetRecordCount: Integer; begin Result := fFuturesData.DayDealData.Count; end; function TFuturesDataAccess.GetRecordItem(AIndex: integer): Pointer; begin Result := fFuturesData.DayDealData.Objects[AIndex]; end; procedure TFuturesDataAccess.Sort; begin fFuturesData.DayDealData.Sort; end; function TFuturesDataAccess.CheckOutRecord(ADate: Integer): PRT_Quote_M1_Day; begin Result := nil; if ADate < 1 then exit; Result := FindRecord(ADate); if nil = Result then begin if fFuturesData.FirstDealDate = 0 then fFuturesData.FirstDealDate := ADate; if fFuturesData.FirstDealDate > ADate then fFuturesData.FirstDealDate := ADate; if fFuturesData.LastDealDate < ADate then fFuturesData.LastDealDate := ADate; Result := System.New(PRT_Quote_M1_Day); FillChar(Result^, SizeOf(TRT_Quote_M1_Day), 0); Result.DealDateTime.Value := ADate; fFuturesData.DayDealData.AddObject(ADate, TObject(Result)); end; end; function TFuturesDataAccess.FindRecord(ADate: Integer): PRT_Quote_M1_Day; var tmpPos: integer; begin Result := nil; tmpPos := fFuturesData.DayDealData.IndexOf(ADate); if 0 <= tmpPos then Result := PRT_Quote_M1_Day(fFuturesData.DayDealData.Objects[tmpPos]); end; end.
unit MsgAPI; {$I CSXGuard.inc} interface uses CvarDef; procedure Print(const Msg: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Msg: String; R, G, B: Byte; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2, Str3: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2, Str3, Str4: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2, Str3: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure Print(const Str1, Str2, Str3, Str4: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); overload; procedure ReleaseMessages; procedure ClearMessages; implementation uses Common, HLSDK; const MAX_MESSAGES = 192; type TMessageType = (TYPE_DEFAULT = 0, TYPE_DEVELOPER, TYPE_COLORED, TYPE_COLORED_DEV); PMessage = ^TMessage; TMessage = packed record Data: String; MessageType: TMessageType; R, G, B: Byte; end; var Messages: packed array[1..MAX_MESSAGES] of TMessage; MessageCount: LongWord = 0; Released: Boolean = False; procedure AddMessage; begin if MessageCount >= MAX_MESSAGES then ClearMessages; Inc(MessageCount); end; procedure PushToConsole(const Msg: String; const Developer: Boolean = False); begin if Developer then Engine.Con_DPrintF(PChar(Msg)) else Engine.Con_PrintF(PChar(Msg)); end; procedure PushToList(const Msg: String; const Developer: Boolean = False); begin AddMessage; with Messages[MessageCount] do begin Data := Msg; Byte(MessageType) := Byte(TYPE_DEFAULT) + Byte(Developer); end; end; procedure PushColoredToConsole(const Msg: String; R, G, B: Byte; const Developer: Boolean = False); var DefaultColor: TColor24; Ptr: PColor24; begin if Developer then Ptr := Console_TextColorDev else Ptr := Console_TextColor; DefaultColor := Ptr^; Ptr.R := R; Ptr.G := G; Ptr.B := B; if Developer then Engine.Con_DPrintF(PChar(Msg)) else Engine.Con_PrintF(PChar(Msg)); Ptr^ := DefaultColor; end; procedure PushColoredToList(const Msg: String; R, G, B: Byte; const Developer: Boolean = False); var MessagePtr: PMessage; begin AddMessage; MessagePtr := @Messages[MessageCount]; MessagePtr.Data := Msg; Byte(MessagePtr.MessageType) := Byte(TYPE_COLORED) + Byte(Developer); MessagePtr.R := R; MessagePtr.G := G; MessagePtr.B := B; end; procedure Print(const Msg: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); var Developer: Boolean; begin Developer := PRINT_DEVELOPER in Flags; if not FirstFrame then if PRINT_PREFIX in Flags then begin PushToConsole('[', Developer); PushColoredToConsole(Prefix, PREFIX_COLOR_R, PREFIX_COLOR_G, PREFIX_COLOR_B, Developer); if PRINT_LINE_BREAK in Flags then PushToConsole('] ' + Msg + #$A, Developer) else PushToConsole('] ' + Msg, Developer); end else if PRINT_LINE_BREAK in Flags then PushToConsole(Msg + #$A, Developer) else PushToConsole(Msg, Developer) else begin if MessageCount >= MAX_MESSAGES then ClearMessages; Inc(MessageCount); if PRINT_PREFIX in Flags then begin PushToList('[', Developer); PushColoredToList(Prefix, PREFIX_COLOR_R, PREFIX_COLOR_G, PREFIX_COLOR_B, Developer); if PRINT_LINE_BREAK in Flags then PushToList('] ' + Msg + #$A, Developer) else PushToList('] ' + Msg, Developer); end else if PRINT_LINE_BREAK in Flags then PushToList(Msg + #$A, Developer) else PushToList(Msg, Developer); end; end; procedure ReleaseMessages; var I: LongWord; MessagePtr: PMessage; begin if Released then Error('ReleaseMessages: Invalid secondary call to ReleaseMessages.') else Released := True; for I := 1 to MessageCount do begin MessagePtr := @Messages[I]; case MessagePtr.MessageType of TYPE_DEFAULT: Engine.Con_PrintF(PChar(MessagePtr.Data)); TYPE_DEVELOPER: Engine.Con_DPrintF(PChar(MessagePtr.Data)); TYPE_COLORED: PushColoredToConsole(PChar(MessagePtr.Data), MessagePtr.R, MessagePtr.G, MessagePtr.B, False); TYPE_COLORED_DEV: PushColoredToConsole(PChar(MessagePtr.Data), MessagePtr.R, MessagePtr.G, MessagePtr.B, True); else Error('ReleaseMessages: Invalid message type.'); end; end; ClearMessages; end; procedure ClearMessages; begin Finalize(Messages); MessageCount := 0; end; procedure Print(const Msg: String; R, G, B: Byte; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); var Developer: Boolean; begin Developer := PRINT_DEVELOPER in Flags; if not FirstFrame then if PRINT_PREFIX in Flags then begin PushColoredToConsole('[', R, G, B, Developer); PushColoredToConsole(Prefix, PREFIX_COLOR_R, PREFIX_COLOR_G, PREFIX_COLOR_B, Developer); if PRINT_LINE_BREAK in Flags then PushColoredToConsole('] ' + Msg + #$A, R, G, B, Developer) else PushColoredToConsole('] ' + Msg, R, G, B, Developer); end else if PRINT_LINE_BREAK in Flags then PushColoredToConsole(Msg + #$A, R, G, B, Developer) else PushColoredToConsole(Msg, R, G, B, Developer) else begin if MessageCount >= MAX_MESSAGES then ClearMessages; Inc(MessageCount); if PRINT_PREFIX in Flags then begin PushColoredToList('[', R, G, B, Developer); PushColoredToList(Prefix, PREFIX_COLOR_R, PREFIX_COLOR_G, PREFIX_COLOR_B, Developer); if PRINT_LINE_BREAK in Flags then PushColoredToList('] ' + Msg + #$A, R, G, B, Developer) else PushColoredToList('] ' + Msg, R, G, B, Developer); end else if PRINT_LINE_BREAK in Flags then PushColoredToList(Msg + #$A, R, G, B, Developer) else PushColoredToList(Msg, R, G, B, Developer); end; end; procedure Print(const Str1, Str2: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(Str1 + Str2, Flags); end; procedure Print(const Str1, Str2, Str3: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(Str1 + Str2 + Str3, Flags); end; procedure Print(const Str1, Str2, Str3, Str4: String; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(Str1 + Str2 + Str3 + Str4, Flags); end; procedure Print(const Str1, Str2: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(String(Str1) + Str2, Flags); end; procedure Print(const Str1, Str2, Str3: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(String(Str1) + Str2 + Str3, Flags); end; procedure Print(const Str1, Str2, Str3, Str4: PChar; const Flags: TPrintFlags = [PRINT_PREFIX, PRINT_LINE_BREAK]); begin Print(String(Str1) + Str2 + Str3 + Str4, Flags); end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.Xml, RemObjects.Elements.EUnit; type ProcessingInstructionTest = public class (Test) private Doc: XmlDocument; Data: XmlProcessingInstruction; public method Setup; override; method Value; method TestData; method Target; method NodeType; end; implementation method ProcessingInstructionTest.Setup; begin Doc := XmlDocument.FromString(XmlTestData.PIXml); Assert.IsNotNil(Doc); Data := Doc.ChildNodes[0] as XmlProcessingInstruction; Assert.IsNotNil(Data); end; method ProcessingInstructionTest.Value; begin Assert.IsNotNil(Data.Value); Assert.AreEqual(Data.Value, "type=""text/xsl"" href=""test"""); Data.Value := "type=""text/xsl"""; Assert.AreEqual(Data.Value, "type=""text/xsl"""); Assert.Throws(->begin Data.Value := nil; end); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.AreEqual(Data.Value, ""); end; method ProcessingInstructionTest.Target; begin Assert.IsNotNil(Data.Target); Assert.AreEqual(Data.Target, "xml-stylesheet"); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.AreEqual(Data.Target, "custom"); end; method ProcessingInstructionTest.TestData; begin //Data is the same thing as Value Assert.IsNotNil(Data.Data); Assert.AreEqual(Data.Data, "type=""text/xsl"" href=""test"""); Data.Data := "type=""text/xsl"""; Assert.AreEqual(Data.Data, "type=""text/xsl"""); Assert.Throws(->begin Data.Data := nil; end); Data := Doc.ChildNodes[1] as XmlProcessingInstruction; Assert.AreEqual(Data.Data, ""); end; method ProcessingInstructionTest.NodeType; begin Assert.IsTrue(Data.NodeType = XmlNodeType.ProcessingInstruction); end; end.
unit fcImageForm; { // // Components : TfcImageForm // // Copyright (c) 1999 by Woll2Woll Software // // History: // 5/10/99-PYW-Checked for click or mousedown event assigned for a control on a caption bar. // } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, fcMsg, Buttons, fcCommon, fcimage; type TfcImageFormOption = (ifUseWindowsDrag{, ifIncludeBorder}); TfcImageFormOptions = set of TfcImageFormOption; TfcCustomImageForm = class(TfcCustomImage) private FDragTolerance: Integer; FTransparentColor: TColor; FRegion: HRgn; FCaptionBarControl:TControl; FCaptureMessageClass: TfcCaptureMessageClass; FOptions: TfcImageFormOptions; LastFocusRect: TRect; procedure ReadRegions(Reader: TStream); procedure WriteRegions(Writer: TStream); function GetPicture: TPicture; procedure SetPicture(Value: TPicture); procedure SetOptions(Value: TFcImageFormOptions); procedure SetCaptionBarControl(Value: TControl); protected DraggingForm: Boolean; procedure DestroyWnd; function GetTransparentColor: TColor; procedure DrawFocusRect(DC: HDC; FocusRect: TRect); virtual; procedure WndProc(var Message: TMessage); override; procedure FormMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure DefineProperties(Filer: TFiler);override; procedure SetParent(Value:TWinControl); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure AfterFormWndProc(var Message: TMessage); virtual; procedure MouseLoop(X, Y: Integer); virtual; procedure MouseLoop_MouseMove(X, Y: Integer; ACursorPos: TPoint; var FirstTime: Boolean; var FocusRect: TRect; OriginalRect:TRect); virtual; procedure MouseLoop_MouseUp(X, Y: Integer; ACursorPos: TPoint; OriginalRect, FocusRect: TRect); virtual; function GetDragFullWindows: Boolean; virtual; public Patch: Variant; constructor Create(Aowner:TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure ApplyBitmapRegion; virtual; property RegionData: HRgn read FRegion stored True; property CaptionBarControl: TControl read FCaptionBarControl write SetCaptionBarControl; property DragTolerance: Integer read FDragTolerance write FDragTolerance; property Picture: TPicture read GetPicture write SetPicture; property TransparentColor: TColor read FTransparentColor write FTransparentColor default clNone; property Options: TfcImageFormOptions read FOptions write SetOptions default []; end; TfcImageForm = class(TfcCustomImageForm) published property Options; property Align; property AutoSize; property Picture; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property CaptionBarControl; property DragTolerance; property TransparentColor; end; implementation {$r fcFrmBtn.RES} constructor TfcCustomImageForm.Create(Aowner:TComponent); begin inherited; FDragTolerance := 5; FRegion := 0; Align := alClient; FTransparentColor := clNone; FCaptureMessageClass := nil; FOptions:= []; end; destructor TfcCustomImageForm.Destroy; begin if FRegion <> 0 then DeleteObject(FRegion); if FCaptureMessageClass <> nil then FCaptureMessageClass.Free; // FCaptureMessageClass:= nil; inherited Destroy; end; procedure TfcCustomImageForm.DestroyWnd; begin if FRegion <> 0 then begin SetWindowRgn(GetParentForm(self).Handle, 0, False); DeleteObject(FRegion); FRegion := 0; end; end; // 10/26/98 - Added check to use windows setting for dragging of form when UseWindowsDrag is set. function TfcCustomImageForm.GetDragFullWindows: Boolean; var s: integer; begin s:= 0; if ifUseWindowsDrag in Options then SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, Pointer(@s), 0); result:= (s<>0); end; procedure TfcCustomImageForm.AfterFormWndProc(var Message: TMessage); var AControl: TControl; ClickOrMouseDownAssigned:Boolean; begin if not (csDesigning in componentstate) then case Message.Msg of WM_DESTROY: DestroyWnd; WM_LBUTTONDOWN: //Needed to capture mouse messages from caption control with TWMMouse(Message) do begin AControl := Parent.ControlAtPos(Point(XPos, YPos), True); //Check if the caption control is defined. If so, then check if the caption control was clicked on or if //a different control was clicked on in the caption that has an onclick event. Use cheating cast. //3/11/99-PYW-Don't Drag if a different control has an OnMouseDown event as well. ClickOrMouseDownAssigned := Assigned(TButton(AControl).OnClick) or Assigned(TButton(AControl).OnMouseDown); //5/10/99-PYW-Checked for click or mousedown event assigned for a control on a caption bar. if ((FCaptionBarControl <> nil) and not ClickOrMouseDownAssigned) or ((FCaptionBarControl <> nil) and (AControl = CaptionBarControl)) or ((FCaptionBarControl = nil) and (AControl = self)) then FormMouseDown(mbLeft, KeysToShiftState(Keys), XPos, YPos); end; end; end; procedure TfcCustomImageForm.FormMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var p: TPoint; ParentForm: TCustomForm; begin if (FCaptionBarControl <> nil) then with FCaptionBarControl do if not (PtinRect(Rect(Left, Top, Width + Left, Height + Top), Point(x, y))) then Exit; if ssLeft in Shift then begin ParentForm:= GetParentForm(self); if TForm(ParentForm).FormStyle = fsMDIChild then begin p:= ClientToScreen(Point(x,y)); p.x:= p.x - ParentForm.left; p.y:= p.y - ParentForm.Top; end else p := Point(x, y); MouseLoop(p.x, p.y) end else SendMessage(Parent.Handle, WM_SYSCOMMAND, SC_KEYMENU, 0); end; procedure TfcCustomImageForm.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FCaptionBarControl) then FCaptionBarControl := nil; end; procedure TfcCustomImageForm.MouseLoop(X, Y: Integer); var ACursor: TPoint; Msg: TMsg; FirstTime: Boolean; OriginalRect, FocusRect: TRect; begin FirstTime := True; with Parent do OriginalRect := Rect(Left, Top, Left + Width, Top + Height); FocusRect := Rect(0, 0, 0, 0); with GetParentForm(self) do begin SetCapture(Handle); try while GetCapture = Handle do begin GetCursorPos(ACursor); case Integer(GetMessage(Msg, 0, 0, 0)) of -1: Break; 0: begin PostQuitMessage(Msg.WParam); Break; end; end; case Msg.Message of WM_MOUSEMOVE: MouseLoop_MouseMove(X, Y, ACursor, FirstTime, FocusRect, OriginalRect); WM_LBUTTONUP: begin MouseLoop_MouseUp(X, Y, ACursor, OriginalRect, FocusRect); TranslateMessage(Msg); // So OnMouseUp fires DispatchMessage(Msg); if GetCapture = Handle then ReleaseCapture; end; else begin // 12/07/98 - Following code needed to prevent eating of messages. TranslateMessage(Msg); DispatchMessage(Msg); end; end; end; finally if GetCapture = Handle then ReleaseCapture; end; end; end; procedure TfcCustomImageForm.MouseLoop_MouseMove(X, Y: Integer; ACursorPos: TPoint; var FirstTime: Boolean; var FocusRect: TRect; OriginalRect:TRect); var DC: HDC; p: TPoint; Msg: TMsg; PaintFocusRect: TRect; begin p := ClientToScreen(Point(x, y)); if (Abs(ACursorPos.X - p.x) <= DragTolerance) and (Abs(ACursorPos.Y - p.y) <= DragTolerance) then Exit; with GetParentForm(self) do begin // 10/26/98 - Added Check For Full Windows Drag option on ImageForm. if not GetDragFullWindows then begin DC := GetDC(0); try if FirstTime then begin DraggingForm := True; end else begin DrawFocusRect(DC, LastFocusRect); { Hide previous focus rect } end; FocusRect := Rect(ACursorPos.x - x, ACursorPos.y - y, ACursorPos.x - x + Width, ACursorPos.y - y + Height); if TForm(GetParentForm(self)).FormStyle = fsMDIChild then begin PaintFocusRect:= FocusRect; PaintFocusRect.Left:= PaintFocusRect.Left + ClientToScreen(Point(0,0)).x - Left; PaintFocusRect.Top:= PaintFocusRect.Top+ ClientToScreen(Point(0,0)).y - Top; PaintFocusRect.Right:= PaintFocusRect.Left+ Width; PaintFocusRect.Bottom:= PaintFocusRect.Top + Height; end else begin PaintFocusRect:= FocusRect; end; DrawFocusRect(DC, PaintFocusRect); LastFocusRect:= PaintFocusRect; FirstTime:= False; finally ReleaseDC(0, DC); end; end else begin //10/26/98 - Drag Full Windows. DraggingForm := True; sleep(10); while PeekMessage(Msg, Handle, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE) do; GetCursorPos(ACursorPos); SetWindowPos(Handle, 0, ACursorPos.x - x, ACursorPos.y - y, 0, 0, SWP_NOZORDER or SWP_NOSIZE or SWP_NOACTIVATE); end; end; end; procedure TfcCustomImageForm.MouseLoop_MouseUp(X, Y: Integer; ACursorPos: TPoint; OriginalRect, FocusRect: TRect); var DC: HDC; begin if not DraggingForm then Exit; DraggingForm:= False; with GetParentForm(self) do begin if not GetDragFullWindows then begin DC := GetDC(0); try DrawFocusRect(DC, LastFocusRect); // if TForm(GetParentForm(self)).FormStyle = fsMDIChild then // Windows.DrawFocusRect(DC, LastFocusRect) // else // Windows.DrawFocusRect(DC, FocusRect); finally ReleaseDC(0, DC); end; SetWindowPos(Handle, 0, FocusRect.Left, FocusRect.top, 0, 0, SWP_NOZORDER {or SWP_NOMOVE }or SWP_NOSIZE or SWP_NOACTIVATE or SWP_SHOWWINDOW); // RedrawWindow(GetDesktopWindow, @OriginalRect, 0, RDW_UPDATENOW or // RDW_ALLCHILDREN or RDW_INVALIDATE); if GetCapture = Handle then ReleaseCapture; end; end; end; procedure TfcCustomImageForm.ReadRegions(Reader: TStream); var rgnsize:integer; rgndata: pRGNData; begin Reader.Read(RgnSize, 4); if RgnSize <> 0 then begin GetMem(RgnData, RgnSize); try Reader.Read(RgnData^,rgnSize); FRegion := ExtCreateRegion(nil, RgnSize, RgnData^); if not (csDesigning in ComponentState) and (FRegion<>0) then SetWindowRgn(parent.handle,Fregion,true) finally FreeMem(RgnData); end; end else begin FRegion := 0; ApplyBitmapRegion; end end; procedure TfcCustomImageForm.WriteRegions(Writer: TStream); var size:integer; rgndata: pRGNData; stat: integer; begin ApplyBitmapRegion; if (FRegion <> 0) then begin Size := GetRegionData(FRegion, 0, nil); Writer.Write(Size, SizeOf(Size)); if Size > 0 then begin Getmem(RgnData,size); try Stat := GetRegionData(FRegion, Size, RgnData); if Stat > 0 then Writer.Write(RgnData^, Size); finally FreeMem(RgnData); end; end; end else begin Size := 0; Writer.Write(Size, SizeOf(Size)); end; end; procedure TfcCustomImageForm.DefineProperties(Filer: TFiler); begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('RegionData', ReadRegions, WriteRegions, True); end; procedure TfcCustomImageForm.SetParent(Value: TWinControl); begin if (Value <> nil) and not (Value is TCustomForm) then Value := GetParentForm(Value); inherited SetParent(value); if Parent <> nil then SetWindowLong(Parent.Handle, GWL_STYLE, GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_CLIPCHILDREN); if Value<>Nil then TForm(Value).BorderStyle:= bsNone; if (Value<>nil) and { 5/13/99 } (FCaptureMessageClass = nil) and not (csDesigning in ComponentState) then begin FCaptureMessageClass := TfcCaptureMessageClass.Create(Owner); FCaptureMessageClass.WindowHandle := Value.Handle; FCaptureMessageClass.Enabled := True; FCaptureMessageClass.OnWndProc := AfterFormWndProc; end; end; procedure TfcCustomImageForm.ApplyBitmapRegion; begin SetWindowRgn(GetParentForm(self).Handle, 0, False); if FRegion <> 0 then DeleteObject(FRegion); FRegion := fcCreateRegionFromBitmap(Picture.Bitmap, GetTransparentColor); if not (csDesigning in ComponentState) then SetWindowRgn(GetParentForm(self).Handle, FRegion, True); end; function TfcCustomImageForm.GetPicture: TPicture; begin result := inherited Picture; end; function TfcCustomImageForm.GetTransparentColor: TColor; begin result := FTransparentColor; if FTransparentColor=clNone then begin if (Picture.Bitmap<>Nil) then result:= Picture.Bitmap.Canvas.Pixels[0,Picture.Bitmap.height-1] end else result:= FTransparentColor; end; procedure TfcCustomImageForm.SetPicture(Value: TPicture); begin inherited Picture := Value; if (Value <> nil) and (Value.Width > 0) and (Value.height > 0) then begin (Parent as TCustomForm).ClientWidth := Value.Width; (Parent as TCustomForm).ClientHeight := Value.Height; end; Invalidate; end; procedure TfcCustomImageForm.SetOptions(Value: TFcImageFormOptions); begin FOptions:= Value; end; procedure TfcCustomImageForm.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; // Added to support autosizing of the form if AutoSize then with GetParentForm(self) do begin ClientWidth := AWidth; ClientHeight := AHeight; end; end; procedure TfcCustomImageForm.DrawFocusRect(DC: HDC; FocusRect: TRect); begin Windows.DrawFocusRect(DC, FocusRect); InflateRect(FocusRect, -1, -1); Windows.DrawFocusRect(DC, FocusRect); InflateRect(FocusRect, -1, -1); Windows.DrawFocusRect(DC, FocusRect); end; procedure TfcCustomImageForm.SetCaptionBarControl(Value: TControl); begin if Value<>FCaptionBarControl then begin // if CaptionBarControl<>nil then // CaptionBarControl.WindowProc:= FLastCaptionWindowProc; FCaptionBarControl:= Value; // if (CaptionBarControl<>nil) and (not (csDesigning in componentstate)) then // begin // FLastCaptionWindowProc:= CaptionBarControl.WindowProc; // CaptionBarControl.WindowProc:= CaptionWindowProc; // end end end; procedure TfcCustomImageForm.WndProc(var Message: TMessage); begin inherited; end; end.
Unit testcaseTools; {$mode objfpc}{$H+} Interface Uses Classes, SysUtils, uTools, fpcunit, testutils, testregistry; Type { TTestCaseTools } TTestCaseTools = Class(TTestCase) protected Procedure SetUp; override; Procedure TearDown; override; Published Procedure TestHookUp; Procedure TestCammelCase; Procedure TestGlobCheck; Procedure TestGlobCheckAll; End; Implementation Procedure TTestCaseTools.TestHookUp; Begin AssertEquals('ahoj nazdarek', NormalizeTerm('Ahój, Nazdárek')); AssertEquals('prilis zlutoucky kun upel dabelske ody', NormalizeTerm('Příliš žluťoučký kůň - úpěl ďábelské ódy!')); End; Procedure TTestCaseTools.TestCammelCase; Begin AssertEquals('freerapiddownloader', CopyAndSplitCammelCaseString('freerapiddownloader')); AssertEquals('freeRapidDownloader free Rapid Downloader', CopyAndSplitCammelCaseString('freeRapidDownloader')); AssertEquals('freeRapid1Downloader ahoj free Rapid 1 Downloader ahoj', CopyAndSplitCammelCaseString('freeRapid1Downloader ahoj')); End; Procedure TTestCaseTools.TestGlobCheck; Begin AssertTrue(GlobCheck('*aa*', 'aaaa')); AssertFalse(GlobCheck('*ab*', 'aaaa')); AssertTrue(GlobCheck('*aa', 'bbaa')); AssertFalse(GlobCheck('*aa', 'bbaab')); AssertFalse(GlobCheck('*aa', 'bbba')); AssertTrue(GlobCheck('aa*', 'aabb')); AssertFalse(GlobCheck('aa*', 'bbba')); AssertTrue(GlobCheck('aa', 'aa')); AssertTrue(GlobCheck('aa', 'AA')); AssertFalse(GlobCheck('aa', 'ba')); End; Procedure TTestCaseTools.TestGlobCheckAll; Begin AssertTrue(GlobCheckAll('*aa*:*cc', 'ddaadd')); AssertTrue(GlobCheckAll('*xx*:*cc*', 'ddaaccdd')); AssertFalse(GlobCheckAll('*xx*:*cc*', 'ddaacdd')); End; Procedure TTestCaseTools.SetUp; Begin End; Procedure TTestCaseTools.TearDown; Begin End; Initialization RegisterTest(TTestCaseTools); End.
unit ActivityReceiverU; interface uses FMX.Types, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText; type JActivityReceiverClass = interface(JBroadcastReceiverClass) ['{9D967671-9CD8-483A-98C8-161071CE7B64}'] {Methods} // function init: JActivityReceiver; cdecl; end; [JavaSignature('com/blong/test/ActivityReceiver')] JActivityReceiver = interface(JBroadcastReceiver) ['{4B30D537-5221-4451-893D-7916ED11CE1F}'] {Methods} end; TJActivityReceiver = class(TJavaGenericImport<JActivityReceiverClass, JActivityReceiver>) protected constructor _Create; public class function Create: JActivityReceiver; procedure OnReceive(Context: JContext; ReceivedIntent: JIntent); end; implementation uses MainFormU, System.Classes, System.SysUtils, FMX.Helpers.Android, Androidapi.Helpers, Androidapi.NativeActivity, Androidapi.JNI, Androidapi.JNI.JavaTypes, Androidapi.JNI.Toast, ServiceU; {$REGION 'JNI setup code and callback'} var ActivityReceiver: TJActivityReceiver; //This is called from the Java activity's onReceiveNative() method procedure ActivityReceiverOnReceiveNative(PEnv: PJNIEnv; This: JNIObject; JNIContext, JNIReceivedIntent: JNIObject); cdecl; begin Log.d('+ActivityReceiverOnReceiveNative'); Log.d('Thread: Main: %.8x, Current: %.8x, Java:%.8d (%2:.8x)', [MainThreadID, TThread.CurrentThread.ThreadID, TJThread.JavaClass.CurrentThread.getId]); TThread.Queue(nil, procedure begin Log.d('+ThreadSwitcher'); Log.d('Thread: Main: %.8x, Current: %.8x, Java:%.8d (%2:.8x)', [MainThreadID, TThread.CurrentThread.ThreadID, TJThread.JavaClass.CurrentThread.getId]); ActivityReceiver.OnReceive(TJContext.Wrap(JNIContext), TJIntent.Wrap(JNIReceivedIntent)); Log.d('-ThreadSwitcher'); end); Log.d('-ActivityReceiverOnReceiveNative'); end; procedure RegisterDelphiNativeMethods; var PEnv: PJNIEnv; ReceiverClass: JNIClass; NativeMethod: JNINativeMethod; begin Log.d('Starting the Activity Receiver JNI stuff'); PEnv := TJNIResolver.GetJNIEnv; Log.d('Registering interop methods'); NativeMethod.Name := 'activityReceiverOnReceiveNative'; NativeMethod.Signature := '(Landroid/content/Context;Landroid/content/Intent;)V'; NativeMethod.FnPtr := @ActivityReceiverOnReceiveNative; ReceiverClass := TJNIResolver.GetJavaClassID('com.blong.test.ActivityReceiver'); PEnv^.RegisterNatives(PEnv, ReceiverClass, @NativeMethod, 1); PEnv^.DeleteLocalRef(PEnv, ReceiverClass); end; {$ENDREGION} { TActivityReceiver } constructor TJActivityReceiver._Create; begin inherited; Log.d('TJActivityReceiver._Create constructor'); end; class function TJActivityReceiver.Create: JActivityReceiver; begin Log.d('TJActivityReceiver.Create class function'); Result := inherited Create; ActivityReceiver := TJActivityReceiver._Create; end; procedure TJActivityReceiver.OnReceive(Context: JContext; ReceivedIntent: JIntent); var Iteration: Integer; CalculatedValue: Integer; begin //In this sample the activity receiver is unregistered when the app goes to //the background. So this code won't run if the app isn't active. That //includes the Toast, which won't display. //However the service thread will continue to do its thing in the background. Log.d('Activity receiver received a message'); Iteration := ReceivedIntent.getIntExtra(StringToJString(TSampleService.ID_INT_ITERATION), 0); CalculatedValue := ReceivedIntent.getIntExtra(StringToJString(TSampleService.ID_INT_CALCULATED_VALUE), 0); Toast(Format( 'Received call %d from service'#10'with calculated value %d', [Iteration, CalculatedValue]), TToastLength.LongToast) end; initialization RegisterDelphiNativeMethods end.
unit uvITileView; interface uses Classes, Controls; type ITileView = interface; TCloseTileProc = procedure(sender : ITileView) of object; ITileView = interface ['{45779DA7-F5E0-4BBE-B6C0-BE658749610E}'] procedure setPosition(aLeft, aTop, aWidth : integer); function getHeight : integer; function getWidth : integer; procedure setTileData(aTileData : TObject); function getTileData : TObject; function getOwner : TComponent; procedure setParent(aParent : TWinControl); function getParent : TWinControl; procedure setControlName(aName : String); function getControlName : String; procedure setOnCloseClick(aProc : TCloseTileProc); function getTileMinWidth : integer; function getTileMinHeight : integer; end; ITileViewFab = interface ['{579D736D-BDB9-41AF-9DF5-02D7BD9A70A1}'] function getTileViewInstance(aOwner : TComponent; aParent : TWinControl) : ITileView; end; implementation end.
unit ViewDoc; { Unit of functions for viewing documents with a word processor. Author: Phil Hess. Copyright: Copyright (C) 2007 Phil Hess. All rights reserved. License: Modified LGPL. This means you can link your code to this compiled unit (statically in a standalone executable or dynamically in a library) without releasing your code. Only changes to this unit need to be made publicly available. } interface {$IFDEF FPC} {$MODE Delphi} {$ENDIF} uses SysUtils, Classes, {$IFDEF MSWINDOWS} Windows, Registry, ShellApi; {$ENDIF} {$IFDEF DARWIN} {OS X} BaseUnix, Unix; {$ENDIF} {$IFDEF LINUX} FileUtil, Unix; {$ENDIF} type TViewerOptions = set of (ovwUseAsTemplate, ovwAddToDeleteList); function GetViewerCount : Integer; function GetViewerName(Viewer : Integer) : string; function ViewDocument(const FileName : string; Viewer : Integer; Options : TViewerOptions; var ErrorMsg : string) : Boolean; function DeleteViewedDocs : Boolean; implementation const {$IFDEF MSWINDOWS} MaxViewers = 3; {Number of supported word processors} {Names of word processors} ViewerName : array [1..MaxViewers] of string = ('Microsoft Word', 'OpenOffice', 'AbiWord'); {Executable files} ViewerExe : array [1..MaxViewers] of string = ('WINWORD.EXE', 'SOFFICE.EXE', 'AbiWord.exe'); {Command line startup switches. If non-blank, start word processor with a new document based on the specified template. If blank, open document read-only to force user to save under different name.} ViewerSwitch : array [1..MaxViewers] of string = ('/t', '-n ', ''); ViewerRegKey : array [1..MaxViewers] of string = ('', '', 'SOFTWARE\Classes\AbiSuite.AbiWord\shell\open\command'); {$ENDIF} {$IFDEF DARWIN} {OS X} MaxViewers = 4; ViewerName : array [1..MaxViewers] of string = ('Microsoft Word', 'Pages', 'NeoOffice', 'AbiWord'); {OS X Open command doesn't support passing switches to app} ViewerSwitch : array [1..MaxViewers] of string = ('', '', '', ''); MaxViewerFolders = 7; ViewerFolders : array [1..MaxViewerFolders] of string = ('Microsoft Word', 'Microsoft Office 2004/Microsoft Word', 'Microsoft Office X/Microsoft Word', 'Pages.app', 'iWork ''06/Pages.app', 'NeoOffice.app', 'AbiWord.app'); {$ENDIF} {$IFDEF LINUX} MaxViewers = 2; ViewerName : array [1..MaxViewers] of string = ('OpenOffice', 'AbiWord'); ViewerExe : array [1..MaxViewers] of string = ('soffice.bin', 'abiword'); ViewerSwitch : array [1..MaxViewers] of string = ('-n ', ''); {$ENDIF} var DeleteList : TStringList; {List of files to delete when program exits; object is created and destroyed in unit's initialization and finalization sections} function GetViewerCount : Integer; {Return number of viewers defined.} begin Result := MaxViewers; end; function GetViewerName(Viewer : Integer) : string; {Return viewer's name.} begin Result := ViewerName[Viewer]; end; function LocateViewer(Viewer : Integer) : string; {Return path to viewer's executable file, or blank string if can't locate viewer.} {$IFDEF MSWINDOWS} var Reg : TRegistry; begin Result := ''; {With Windows, installed programs usually have Registry entries under the App Paths section, including complete path to program.} Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if ViewerRegKey[Viewer] = '' then begin if Reg.OpenKeyReadOnly( '\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\' + ViewerExe[Viewer]) then begin {Found key, so assume program is installed} try if Reg.ReadString('') <> '' then {Key has (Default) registry entry?} Result := Reg.ReadString(''); except {Trap exception if registry entry does not contain a string} end; end; end else {Non-standard registry key} begin if Reg.OpenKeyReadOnly(ViewerRegKey[Viewer]) then begin {Found key, so assume program is installed} try if Reg.ReadString('') <> '' then {Key as (Default) registry entry?} begin Result := Reg.ReadString(''); if Copy(Result, 1, 1) = '"' then {Strip first quoted item?} Result := Copy(Result, 2, Pos('"', Copy(Result, 2, MaxInt))-1); end; except end; end; end; finally Reg.Free; end; {$ENDIF} {$IFDEF DARWIN} //TODO: Search for app like OS X LaunchServices does. var FolderIdx : Integer; LocIdx : Integer; PathPrefix : string; begin Result := ''; FolderIdx := 0; while (FolderIdx < MaxViewerFolders) and (Result = '') do begin Inc(FolderIdx); if Pos(LowerCase(ViewerName[Viewer]), LowerCase(ViewerFolders[FolderIdx])) > 0 then begin LocIdx := 0; while (LocIdx < 4) and (Result = '') do begin Inc(LocIdx); case LocIdx of 1 : PathPrefix := '/Applications/'; 2 : PathPrefix := '~/Applications/'; 3 : PathPrefix := '~/Desktop/'; 4 : PathPrefix := '~/' end; if FileExists(PathPrefix + ViewerFolders[FolderIdx]) then Result := PathPrefix + ViewerFolders[FolderIdx]; end; end; end; {$ENDIF} {$IFDEF LINUX} begin {Search path for specified file name, returning its expanded file name that includes path to it.} Result := SearchFileInPath( ViewerExe[Viewer], '', GetEnvironmentVariable('PATH'), PathSeparator, [sffDontSearchInBasePath]); {$ENDIF} end; {LocateViewer} function LaunchViewer(const ProgPath : string; const Params : string; const DefaultDir : string) : Integer; {Start viewer program with specified command line parameters by shelling to it, returning shell's code.} {$IFDEF MSWINDOWS} var ProgPathBuf : array [0..MAX_PATH] of Char; ParamsBuf : array [0..MAX_PATH] of Char; DefaultDirBuf : array [0..MAX_PATH] of Char; begin StrPCopy(ProgPathBuf, ProgPath); StrPCopy(ParamsBuf, Params); StrPCopy(DefaultDirBuf, DefaultDir); Result := ShellExecute(0, nil, ProgPathBuf, ParamsBuf, DefaultDirBuf, SW_SHOWNORMAL); {$ENDIF} {$IFDEF DARWIN} begin Result := Shell('Open -a ' + ProgPath + ' ' + Params); {$ENDIF} {$IFDEF LINUX} begin Result := Shell(ProgPath + ' ' + Params); {$ENDIF} end; {LaunchViewer} function ViewDocument(const FileName : string; Viewer : Integer; Options : TViewerOptions; var ErrorMsg : string) : Boolean; {View FileName with Viewer. If successful, return True; if error, return False and error message in ErrorMsg.} var ProgPath : string; Switches : string; ShellStatus : Integer; {$IFDEF DARWIN} FileInfo : Stat; {$ENDIF} begin Result := False; ErrorMsg := 'Unexpected error'; if not FileExists(FileName) then begin ErrorMsg := 'File does not exist.'; Exit; end; if ovwAddToDeleteList in Options then DeleteList.Add(FileName); if Viewer = 0 then {Use first word processor found?} begin ProgPath := ''; while (Viewer < MaxViewers) and (ProgPath = '') do begin Inc(Viewer); ProgPath := LocateViewer(Viewer); end; if ProgPath = '' then begin ErrorMsg := 'Unable to locate a word processor.'; Exit; end; end else {Use specified word processor} begin ProgPath := LocateViewer(Viewer); if ProgPath = '' then begin ErrorMsg := ViewerName[Viewer] + ' does not appear to be installed.'; Exit; end; end; Switches := ''; if ovwUseAsTemplate in Options then begin Switches := ViewerSwitch[Viewer]; if Switches = '' then {No "template" switch to pass?} {Set file read-only so user has to save under different name} {$IFDEF MSWINDOWS} FileSetAttr(FileName, faReadOnly); {$ELSE} {OS X and Linux} begin FpStat(FileName, FileInfo); FpChmod(FileName, FileInfo.st_mode and ($FFFF XOR S_IWUSR)); end; {$ENDIF} end; ShellStatus := LaunchViewer('"' + ProgPath + '"', Switches + '"' + FileName + '"', ''); {$IFDEF MSWINDOWS} if ShellStatus <= 32 then {Windows shell error?} {$ELSE} if ShellStatus = 127 then {Unix shell error?} {$ENDIF} begin ErrorMsg := 'Shell error ' + IntToStr(ShellStatus) + ' attempting to start ' + ViewerName[Viewer] + '.'; Exit; end; ErrorMsg := ''; Result := True; end; {ViewDocument} function DeleteViewedDocs : Boolean; {Attempt to delete documents in deletion list, returning True if all documents deleted or False if unable to delete all documents.} var DocNum : Integer; {$IFDEF DARWIN} FileInfo : Stat; {$ENDIF} begin Result := True; for DocNum := DeleteList.Count - 1 downto 0 do begin if FileExists(DeleteList.Strings[DocNum]) then begin {$IFDEF MSWINDOWS} if (FileGetAttr(DeleteList.Strings[DocNum]) and faReadOnly) <> 0 then FileSetAttr(DeleteList.Strings[DocNum], FileGetAttr(DeleteList.Strings[DocNum]) - faReadOnly); {$ELSE} {OS X and Linux} FpStat(DeleteList.Strings[DocNum], FileInfo); if (FileInfo.st_Mode or S_IWUSR) = 0 then {File read-only?} FpChmod(DeleteList.Strings[DocNum], FileInfo.st_Mode or S_IWUSR); {$ENDIF} if SysUtils.DeleteFile(DeleteList.Strings[DocNum]) then DeleteList.Delete(DocNum) else Result := False; {At least one doc not deleted} end; end; {for DocNum} end; {DeleteViewedDocs} initialization DeleteList := TStringList.Create; finalization DeleteViewedDocs; DeleteList.Free; end.
unit uGnGeneral; interface uses SysUtils, DB, Winapi.Windows, Forms, Types, Classes, Menus, Data.DBXJSON, DateUtils, ShellAPI; type TDataSetHelper = class helper for TDataSet strict private function GetFieldAsString(const FieldName: string): string; procedure SetFieldAsString(const FieldName, FieldValue: string); function GetFieldAsInt(const FieldName: string): Integer; procedure SetFieldAsInt(const FieldName: string; const FieldValue: Integer); public procedure DeleteDef; property FieldAsString[const FieldName: string]: string read GetFieldAsString write SetFieldAsString; property FieldAsInt[const FieldName: string]: Integer read GetFieldAsInt write SetFieldAsInt; end; TFormHelper = class helper for TForm public class function CreateAndShowModal: Integer; end; TComponentHelper = class helper for TComponent public procedure FreeChildren; end; TPopupMenuHelper = class helper for TPopupMenu public procedure NewItem(const ACaption: string; const AOnClick: TNotifyEvent); overload; procedure NewItem(const ACaption: string); overload; end; TJSONObjectHelper = class helper for TJSONObject public function GetValStr(const AStr: string): string; function GetValInt(const AStr: string): Integer; function GetValDateTime(const AStr: string): TDateTime; end; var gnrProgramPath : string; gnrProgramDataPath : string; gnrProgramUserDataPath : string; function IsEmptyStr(const AStr: string; const AUseTrim: Boolean = True): Boolean; function SameTextOne(const AStr: string; const AStrings: array of string): Boolean; function StrArrayToStr(const AStrArray: array of string): string; procedure ShowError(const AMsg: string); function gnrKeyDown(const AKey: Byte) : Boolean; overload; function gnrKeyDown(const AKeyArray: array of Byte) : Boolean; overload; procedure AbortMsg(const AMsg: string); procedure OpenInBrowser(const ALink: string); implementation procedure OpenInBrowser(const ALink: string); begin ShellExecute(0, 'Open', PChar(ALink), nil, nil, SW_SHOWNORMAL); end; function IsEmptyStr(const AStr: string; const AUseTrim: Boolean = True): Boolean; begin if AUseTrim then Result := EmptyStr = Trim(AStr) else Result := EmptyStr = AStr; end; function SameTextOne(const AStr: string; const AStrings: array of string): Boolean; var TempStr: string; begin for TempStr in AStrings do if SameText(AStr, TempStr) then Exit(True); Exit(False); end; function StrArrayToStr(const AStrArray: array of string): string; var Str: string; begin Result := ''; for Str in AStrArray do Result := Result + Str + ', '; if not IsEmptyStr(Result) then Delete(Result, Length(Result) - 1, 2); end; procedure ShowError(const AMsg: string); begin Application.MessageBox(PChar(AMsg), 'CodeZilla'); Abort; end; function gnrKeyDown(const AKey: Byte) : Boolean; var State : TKeyboardState; begin GetKeyboardState(State); Result := ((State[AKey] and 128) <> 0); end; function gnrKeyDown(const AKeyArray: array of Byte) : Boolean; var Key: Byte; begin for Key in AKeyArray do if not gnrKeyDown(Key) then Exit(False); Result := True; end; procedure AbortMsg(const AMsg: string); begin Application.MessageBox(PChar(AMsg), 'Сообщение'); Abort; end; { TDataSetHelper } procedure TDataSetHelper.DeleteDef; begin if Active and not IsEmpty then Delete; end; function TDataSetHelper.GetFieldAsInt(const FieldName: string): Integer; begin Result := FieldByName(FieldName).AsInteger; end; function TDataSetHelper.GetFieldAsString(const FieldName: string): string; begin Result := FieldByName(FieldName).AsString; end; procedure TDataSetHelper.SetFieldAsInt(const FieldName: string; const FieldValue: Integer); begin FieldByName(FieldName).AsInteger := FieldValue; end; procedure TDataSetHelper.SetFieldAsString(const FieldName, FieldValue: string); begin FieldByName(FieldName).AsString := FieldValue; end; { TFormHelper } class function TFormHelper.CreateAndShowModal: Integer; var Form: TForm; begin Form := Self.Create(nil); try Result := Form.ShowModal; finally FreeAndNil(Form); end; end; { TComponentHelper } procedure TComponentHelper.FreeChildren; begin while ComponentCount > 0 do Components[0].Free; end; { TPopupMenuHelper } procedure TPopupMenuHelper.NewItem(const ACaption: string; const AOnClick: TNotifyEvent); var MenuItem: TMenuItem; begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := ACaption; MenuItem.OnClick := AOnClick; Items.Add(MenuItem); end; procedure TPopupMenuHelper.NewItem(const ACaption: string); var MenuItem: TMenuItem; begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := ACaption; Items.Add(MenuItem); end; { TJSONObjectHelper } function TJSONObjectHelper.GetValDateTime(const AStr: string): TDateTime; begin Result := UnixToDateTime(StrToInt(Get(AStr).JsonValue.Value)); end; function TJSONObjectHelper.GetValInt(const AStr: string): Integer; begin if Assigned(Get(AStr)) then Result := StrToInt(Get(AStr).JsonValue.Value) else Result := 0; end; function TJSONObjectHelper.GetValStr(const AStr: string): string; begin Result := Get(AStr).JsonValue.Value; end; end.
// author Marat Shaymardanov, Tomsk 2001, 2013 // // You can freely use this code in any project // if sending any postcards with postage stamp to my address: // Frunze 131/1, 56, Russia, Tomsk, 634021 // // The buffer for strings. // The main purpose of the rapid format of long string. // Features: // 1. Minimize the handling of the memory manager. // 2. One-time allocation of the specified size // 3. The class is not multi-thread safe unit StrBuffer; interface uses Classes, SysUtils; const MaxBuffSize = Maxint div 16; SBufferIndexError = 'Buffer index out of bounds (%d)'; SBufferCapacityError = 'Buffer capacity out of bounds (%d)'; SBufferCountError = 'Buffer count out of bounds (%d)'; type { If you do not have enough space in the string than is taken a piece of memory twice the size and copies the data in this chunk of memory } TStrBuffer = class private FCount: Integer; FCapacity: Integer; FBuff: PAnsiChar; protected class procedure Error(const Msg: string; Data: Integer); public constructor Create; destructor Destroy; override; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure Clear; procedure Add(const aValue: AnsiString); overload; procedure SetCapacity(NewCapacity: Integer); function GetText: AnsiString; function GetCount: Integer; end; PSegment = ^TSegment; TSegment = record Next: PSegment; Size: Integer; Count: Integer; Data: array [0 .. 0] of AnsiChar; end; { add memory done by segments } TSegmentBuffer = class private FCount: Integer; FFirst: PSegment; FLast: PSegment; function AllocateSegment(aSize: Integer): PSegment; protected class procedure Error(const Msg: string; Data: Integer); public constructor Create; destructor Destroy; override; procedure SaveToStream(Stream: TStream); procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); procedure LoadFromStream(Stream: TStream); procedure Clear; procedure AddSegment(aSize: Integer); procedure Add(const aValue: AnsiChar); overload; procedure Add(const aValue: AnsiString); overload; procedure Add(const aValue: PAnsiChar; aCnt: Integer); overload; function GetText: AnsiString; function GetCount: Integer; property Text: AnsiString read GetText; end; implementation {$RANGECHECKS OFF} { TStrBuffer } class procedure TStrBuffer.Error(const Msg: string; Data: Integer); { function ReturnAddr: Pointer; // this is not cross-platform asm MOV EAX,[EBP+4] end; } begin raise EListError.CreateFmt(Msg, [Data]) { at ReturnAddr }; end; constructor TStrBuffer.Create; begin inherited Create; FCount := 0; FCapacity := 0; FBuff := nil; end; destructor TStrBuffer.Destroy; begin Clear; inherited; end; procedure TStrBuffer.Clear; begin FCount := 0; SetCapacity(0); end; procedure TStrBuffer.Add(const aValue: AnsiString); var cnt, delta: Integer; begin cnt := Length(aValue); if FCount + cnt > FCapacity then begin delta := FCapacity div 2; if delta < cnt then delta := cnt * 2; SetCapacity(FCapacity + delta); end; System.Move(Pointer(aValue)^, PAnsiChar(FBuff + FCount)^, cnt); Inc(FCount, cnt); end; function TStrBuffer.GetCount: Integer; begin result := FCount; end; function TStrBuffer.GetText: AnsiString; begin SetLength(result, FCount); System.Move(FBuff^, Pointer(result)^, FCount); end; procedure TStrBuffer.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxBuffSize) then Error(SBufferCapacityError, NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FBuff, NewCapacity); FCapacity := NewCapacity; end; end; procedure TStrBuffer.SaveToStream(Stream: TStream); begin Stream.WriteBuffer(FBuff, FCount); end; procedure TStrBuffer.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TStrBuffer.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TStrBuffer.LoadFromStream(Stream: TStream); var Size: Integer; s: AnsiString; begin Clear; Size := Stream.Size - Stream.Position; SetString(s, nil, Size); Stream.Read(Pointer(s)^, Size); Add(s); end; { TSegmentBuffer } class procedure TSegmentBuffer.Error(const Msg: string; Data: Integer); {function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end;} begin raise EListError.CreateFmt(Msg, [Data]);// at ReturnAddr; end; constructor TSegmentBuffer.Create; begin inherited Create; FCount := 0; FFirst := AllocateSegment(4096); FLast := FFirst; end; destructor TSegmentBuffer.Destroy; begin Clear; FreeMem(FFirst); inherited Destroy; end; procedure TSegmentBuffer.Clear; var p1, p2: PSegment; begin p1 := FFirst; while p1 <> FLast do begin p2 := p1; p1 := p1^.Next; FreeMem(p2); end; FFirst := FLast; FFirst^.Count := 0; FCount := 0; end; function TSegmentBuffer.AllocateSegment(aSize: Integer): PSegment; begin Result:= AllocMem(SizeOf(TSegment) + aSize - 1); Result^.Next:= nil; Result^.Size:= aSize; Result^.Count:= 0; end; procedure TSegmentBuffer.AddSegment(aSize: Integer); var segment: PSegment; begin segment := AllocateSegment(aSize); FLast^.Next := segment; FLast := segment; end; function TSegmentBuffer.GetCount: Integer; begin result := FCount; end; function TSegmentBuffer.GetText: AnsiString; var p: PAnsiChar; segment: PSegment; len: Integer; begin SetString(result, nil, FCount); p := Pointer(result); segment := FFirst; while segment <> nil do begin len := segment^.Count; System.Move(segment^.Data, p^, len); Inc(p, len); segment := segment^.Next; end; end; procedure TSegmentBuffer.Add(const aValue: PAnsiChar; aCnt: Integer); var p: PAnsiChar; tmp: Integer; begin p := aValue; // define size of unused memory in current buffer segment tmp := FLast^.Size - FLast^.Count; // if you do not have enough space in the buffer then copy the "unused" bytes // and reduce current segment if aCnt > tmp then begin System.Move(p^, FLast^.Data[FLast^.Count], tmp); Inc(FLast^.Count, tmp); Inc(FCount, tmp); Inc(p, tmp); Dec(aCnt, tmp); // add another segment of the larger buffer size tmp := FLast^.Size; if tmp < aCnt then tmp := aCnt; AddSegment(tmp * 2); end; if aCnt > 0 then begin Move(p^, FLast^.Data[FLast^.Count], aCnt); Inc(FCount, aCnt); Inc(FLast^.Count, aCnt); end; end; procedure TSegmentBuffer.Add(const aValue: AnsiString); var len: Integer; begin len := Length(aValue); if len > 0 then Add(@aValue[1], len); end; procedure TSegmentBuffer.Add(const aValue: AnsiChar); begin Add(@aValue, 1); end; procedure TSegmentBuffer.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TSegmentBuffer.SaveToStream(Stream: TStream); var segment: PSegment; begin segment := FFirst; while segment <> nil do begin Stream.WriteBuffer(segment^.Data[0], segment^.Count); segment := segment^.Next; end; end; procedure TSegmentBuffer.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TSegmentBuffer.LoadFromStream(Stream: TStream); var Size: Integer; s: AnsiString; begin Clear; Size := Stream.Size - Stream.Position; SetString(s, nil, Size); Stream.Read(Pointer(s)^, Size); Add(s); end; {$RANGECHECKS ON} end.
unit uRegisterUtils; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.ImgList; type TRegisterUtils = class(TForm) public class function ReadFromRegistry(aPath, aNameOfRegistry: string): string; class procedure WriteToRegistry(aPath, aNameOfRegistry, aValueOfRegistry: string); static; class procedure CleanRegistryValue(aPath, aNameOfRegistry: string); static; class function ExistsValueInRegistry(const aPath, aNameOfRegistry, aValue: string): Boolean; end; implementation uses registry, System.StrUtils; { TRegisterUtils } class procedure TRegisterUtils.CleanRegistryValue(aPath, aNameOfRegistry: string); begin with TRegistry.Create do begin try RootKey := HKEY_CURRENT_USER; OpenKey(aPath, True); WriteString(aNameOfRegistry, ''); finally CloseKey; Free; end; end; end; class function TRegisterUtils.ExistsValueInRegistry(const aPath, aNameOfRegistry, aValue: string): Boolean; var lValuesFromRegistry: string; begin (*** Check if in registry aNameOfRegistry on path aPath exists aValue ***) lValuesFromRegistry := ReadFromRegistry(aPath, aNameOfRegistry); Result := AnsiContainsStr(lValuesFromRegistry, aValue); end; class function TRegisterUtils.ReadFromRegistry(aPath, aNameOfRegistry: string): string; begin (*** Read from register on path aPath ***) with TRegistry.Create do begin try RootKey := HKEY_CURRENT_USER; if OpenKey(aPath, True) then begin Result := ReadString(aNameOfRegistry); end; finally CloseKey; Free; end; end; end; class procedure TRegisterUtils.WriteToRegistry(aPath, aNameOfRegistry, aValueOfRegistry: string); begin (*** Write to register on path aPath/aNameOfRegister - value aValueOfRegister ***) with TRegistry.Create do begin try RootKey := HKEY_CURRENT_USER; if OpenKey(aPath, True) then begin WriteString(aNameOfRegistry, (ReadString(aNameOfRegistry) + aValueOfRegistry + ';')); end; finally CloseKey; Free; end; end; end; end.
unit streetfighter_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,m68000,main_engine,controls_engine,gfx_engine,ym_2151,rom_engine, pal_engine,sound_engine,timer_engine,msm5205; function iniciar_sfighter:boolean; implementation const sfighter_rom:array[0..5] of tipo_roms=( (n:'sfd-19.2a';l:$10000;p:0;crc:$faaf6255),(n:'sfd-22.2c';l:$10000;p:$1;crc:$e1fe3519), (n:'sfd-20.3a';l:$10000;p:$20000;crc:$44b915bd),(n:'sfd-23.3c';l:$10000;p:$20001;crc:$79c43ff8), (n:'sfd-21.4a';l:$10000;p:$40000;crc:$e8db799b),(n:'sfd-24.4c';l:$10000;p:$40001;crc:$466a3440)); sfighter_snd:tipo_roms=(n:'sf-02.7k';l:$8000;p:0;crc:$4a9ac534); sfighter_msm:array[0..1] of tipo_roms=( (n:'sfu-00.1h';l:$20000;p:$0;crc:$a7cce903),(n:'sf-01.1k';l:$20000;p:$20000;crc:$86e0f0d5)); sfighter_char:tipo_roms=(n:'sf-27.4d';l:$4000;p:0;crc:$2b09b36d); sfighter_bg:array[0..3] of tipo_roms=( (n:'sf-39.2k';l:$20000;p:0;crc:$cee3d292),(n:'sf-38.1k';l:$20000;p:$20000;crc:$2ea99676), (n:'sf-41.4k';l:$20000;p:$40000;crc:$e0280495),(n:'sf-40.3k';l:$20000;p:$60000;crc:$c70b30de)); sfighter_fg:array[0..7] of tipo_roms=( (n:'sf-25.1d';l:$20000;p:0;crc:$7f23042e),(n:'sf-28.1e';l:$20000;p:$20000;crc:$92f8b91c), (n:'sf-30.1g';l:$20000;p:$40000;crc:$b1399856),(n:'sf-34.1h';l:$20000;p:$60000;crc:$96b6ae2e), (n:'sf-26.2d';l:$20000;p:$80000;crc:$54ede9f5),(n:'sf-29.2e';l:$20000;p:$a0000;crc:$f0649a67), (n:'sf-31.2g';l:$20000;p:$c0000;crc:$8f4dd71a),(n:'sf-35.2h';l:$20000;p:$e0000;crc:$70c00fb4)); sfighter_sprites:array[0..13] of tipo_roms=( (n:'sf-15.1m';l:$20000;p:0;crc:$fc0113db),(n:'sf-16.2m';l:$20000;p:$20000;crc:$82e4a6d3), (n:'sf-11.1k';l:$20000;p:$40000;crc:$e112df1b),(n:'sf-12.2k';l:$20000;p:$60000;crc:$42d52299), (n:'sf-07.1h';l:$20000;p:$80000;crc:$49f340d9),(n:'sf-08.2h';l:$20000;p:$a0000;crc:$95ece9b1), (n:'sf-03.1f';l:$20000;p:$c0000;crc:$5ca05781),(n:'sf-17.3m';l:$20000;p:$e0000;crc:$69fac48e), (n:'sf-18.4m';l:$20000;p:$100000;crc:$71cfd18d),(n:'sf-13.3k';l:$20000;p:$120000;crc:$fa2eb24b), (n:'sf-14.4k';l:$20000;p:$140000;crc:$ad955c95),(n:'sf-09.3h';l:$20000;p:$160000;crc:$41b73a31), (n:'sf-10.4h';l:$20000;p:$180000;crc:$91c41c50),(n:'sf-05.3f';l:$20000;p:$1a0000;crc:$538c7cbe)); sfighter_tile_map1:array[0..1] of tipo_roms=( (n:'sf-37.4h';l:$10000;p:0;crc:$23d09d3d),(n:'sf-36.3h';l:$10000;p:$10000;crc:$ea16df6c)); sfighter_tile_map2:array[0..1] of tipo_roms=( (n:'sf-32.3g';l:$10000;p:$0;crc:$72df2bd9),(n:'sf-33.4g';l:$10000;p:$10000;crc:$3e99d3d5)); //Dip sfighter_dip_a:array [0..7] of def_dip=( (mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 6C'),(),(),(),(),(),(),(),())), (mask:$100;name:'Flip Screen';number:2;dip:((dip_val:$100;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$200;name:'Attract Music';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$200;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$1000;name:'Speed';number:2;dip:((dip_val:$0;dip_name:'Slow'),(dip_val:$1000;dip_name:'Normal'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2000;name:'Demo Sounds';number:2;dip:((dip_val:$2000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4000;name:'Freeze';number:2;dip:((dip_val:$4000;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); sfighter_dip_b:array [0..5] of def_dip=( (mask:$7;name:'Game Continuation';number:6;dip:((dip_val:$7;dip_name:'5th Stage Maximum'),(dip_val:$6;dip_name:'4th Stage Maximum'),(dip_val:$5;dip_name:'3th Stage Maximum'),(dip_val:$4;dip_name:'2th Stage Maximum'),(dip_val:$3;dip_name:'1th Stage Maximum'),(dip_val:$2;dip_name:'None'),(),(),(),(),(),(),(),(),(),())), (mask:$18;name:'Round Time Count';number:4;dip:((dip_val:$18;dip_name:'100'),(dip_val:$10;dip_name:'150'),(dip_val:$8;dip_name:'200'),(dip_val:$0;dip_name:'250'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Normal'),(dip_val:$40;dip_name:'Easy'),(dip_val:$20;dip_name:'Difficult'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$380;name:'Buy-In Feature';number:6;dip:((dip_val:$380;dip_name:'5th Stage Maximum'),(dip_val:$300;dip_name:'4th Stage Maximum'),(dip_val:$280;dip_name:'3th Stage Maximum'),(dip_val:$200;dip_name:'2th Stage Maximum'),(dip_val:$180;dip_name:'1th Stage Maximum'),(dip_val:$80;dip_name:'None'),(),(),(),(),(),(),(),(),(),())), (mask:$400;name:'Number of Countries Selected';number:2;dip:((dip_val:$400;dip_name:'2'),(dip_val:$0;dip_name:'4'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$2ffff] of word; ram1:array[0..$7ff] of word; ram3:array[0..$3fff] of word; rom_misc:array[0..7,0..$7fff] of byte; scroll_bg,scroll_fg:word; bg_paint,fg_paint,bg_act,fg_act,char_act,sp_act:boolean; ram_tile_map1,ram_tile_map2:array[0..$1ffff] of byte; soundlatch,misc_bank:byte; procedure update_video_sfighter; var f,x,y,nchar,atrib,color,pos,nchar1,nchar2,nchar3,nchar4:word; flipx,flipy:boolean; function sf_invert(char:word):word; const delta:array[0..3] of byte=($00,$18,$18,$00); begin sf_invert:=char xor delta[(char shr 3) and 3]; end; begin //bg if bg_act then begin if bg_paint then begin for f:=$0 to $1ff do begin x:=f mod 32; y:=f div 32; pos:=(y*2)+(x*32)+((scroll_bg and $fff0)*2); atrib:=ram_tile_map1[$10000+pos]; nchar:=((ram_tile_map1[$10001+pos] shl 8)+ram_tile_map1[$1+pos]) and $fff; color:=ram_tile_map1[pos] shl 4; put_gfx_flip(x*16,y*16,nchar,color,3,1,(atrib and $1)<>0,(atrib and $2)<>0); end; bg_paint:=false; end; actualiza_trozo((scroll_bg and $f),0,512-(scroll_bg and $f),256,3,0,0,512-(scroll_bg and $f),256,1); end else begin fill_full_screen(1,0); end; //foreground if fg_act then begin if fg_paint then begin for f:=$0 to $1ff do begin x:=f mod 32; y:=f div 32; pos:=(y*2)+(x*32)+((scroll_fg and $fff0)*2); atrib:=ram_tile_map2[$10000+pos]; nchar:=((ram_tile_map2[$10001+pos] shl 8)+ram_tile_map2[$1+pos]) and $1fff; color:=ram_tile_map2[pos] shl 4; put_gfx_trans_flip(x*16,y*16,nchar,color+256,4,2,(atrib and $1)<>0,(atrib and $2)<>0); end; fg_paint:=false; end; actualiza_trozo((scroll_fg and $f),0,512-(scroll_fg and $f),256,4,0,0,512-(scroll_fg and $f),256,1); end; //Sprites if sp_act then begin for f:=$7f downto 0 do begin nchar:=ram3[($6000+(f*$20)) shr 1] and $3fff; atrib:=ram3[($6002+(f*$20)) shr 1]; color:=((atrib and $f) shl 4)+512; flipx:=(atrib and $100)<>0; flipy:=(atrib and $200)<>0; y:=ram3[($6004+(f*$20)) shr 1]; x:=ram3[($6006+(f*$20)) shr 1]; if (atrib and $400)<>0 then begin nchar1:=nchar; nchar2:=nchar+1; nchar3:=nchar+16; nchar4:=nchar+17; if flipx then begin pos:=nchar2;nchar2:=nchar1;nchar1:=pos; pos:=nchar4;nchar4:=nchar3;nchar3:=pos; end; if flipy then begin pos:=nchar3;nchar3:=nchar1;nchar1:=pos; pos:=nchar2;nchar2:=nchar4;nchar4:=pos; end; put_gfx_sprite_diff(sf_invert(nchar1),color,flipx,flipy,3,0,0); put_gfx_sprite_diff(sf_invert(nchar2),color,flipx,flipy,3,16,0); put_gfx_sprite_diff(sf_invert(nchar3),color,flipx,flipy,3,0,16); put_gfx_sprite_diff(sf_invert(nchar4),color,flipx,flipy,3,16,16); actualiza_gfx_sprite_size(x,y,1,32,32); end else begin put_gfx_sprite(sf_invert(nchar),color,flipx,flipy,3); actualiza_gfx_sprite(x,y,1,3); end; end; end; //chars if char_act then begin for f:=$0 to $7ff do begin if gfx[0].buffer[f] then begin x:=f mod 64; y:=f div 64; atrib:=ram1[f]; nchar:=atrib and $3ff; color:=(atrib shr 12) shl 2; flipx:=(atrib and $400)<>0; flipy:=(atrib and $800)<>0; put_gfx_trans_flip(x*8,y*8,nchar,color+768,2,0,flipx,flipy); gfx[0].buffer[f]:=false; end; end; actualiza_trozo(64,16,384,224,2,64,16,384,224,1); end; actualiza_trozo_final(64,16,384,224,1); end; procedure eventos_sfighter; begin if event.arcade then begin //P1 P2 if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fffe) else marcade.in1:=(marcade.in1 or 1); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fffd) else marcade.in1:=(marcade.in1 or 2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fffb) else marcade.in1:=(marcade.in1 or 4); if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fff7) else marcade.in1:=(marcade.in1 or 8); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $ffef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ffdf) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but3[0] then marcade.in1:=(marcade.in1 and $ffbf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.but4[0] then marcade.in1:=(marcade.in1 and $ff7f) else marcade.in1:=(marcade.in1 or $80); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $feff) else marcade.in1:=(marcade.in1 or $100); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fdff) else marcade.in1:=(marcade.in1 or $200); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $fbff) else marcade.in1:=(marcade.in1 or $400); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $f7ff) else marcade.in1:=(marcade.in1 or $800); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $efff) else marcade.in1:=(marcade.in1 or $1000); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $dfff) else marcade.in1:=(marcade.in1 or $2000); if arcade_input.but3[1] then marcade.in1:=(marcade.in1 and $bfff) else marcade.in1:=(marcade.in1 or $4000); if arcade_input.but4[1] then marcade.in1:=(marcade.in1 and $7fff) else marcade.in1:=(marcade.in1 or $8000); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fffe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fffd) else marcade.in0:=(marcade.in0 or 2); if arcade_input.but5[0] then marcade.in0:=(marcade.in0 and $fffb) else marcade.in0:=(marcade.in0 or 4); if arcade_input.but5[1] then marcade.in0:=(marcade.in0 and $feff) else marcade.in0:=(marcade.in0 or $100); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $fdff) else marcade.in0:=(marcade.in0 or $200); if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $fbff) else marcade.in0:=(marcade.in0 or $400); //SYSTEM if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $fffe) else marcade.in2:=(marcade.in2 or 1); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $fffd) else marcade.in2:=(marcade.in2 or 2); end; end; procedure sfighter_principal; var frame_m,frame_s,frame_a:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_1.tframes; frame_a:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //Sound CPU z80_1.run(frame_s); frame_s:=frame_s+z80_1.tframes-z80_1.contador; //ADPCM CPU z80_0.run(frame_a); frame_a:=frame_a+z80_0.tframes-z80_0.contador; if f=239 then begin update_video_sfighter; m68000_0.irq[1]:=HOLD_LINE; end; end; eventos_sfighter; video_sync; end; end; function sfighter_getword(direccion:dword):word; begin case direccion of 0..$4ffff:sfighter_getword:=rom[direccion shr 1]; $800000..$800fff:sfighter_getword:=ram1[(direccion and $fff) shr 1]; $b00000..$b007ff:sfighter_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $c00000:sfighter_getword:=marcade.in0; //IN0 $c00002:sfighter_getword:=marcade.in1; //IN1 $c00004,$c00006,$c0000e:sfighter_getword:=$ffff; $c00008:sfighter_getword:=marcade.dswa; //DSW1 $c0000a:sfighter_getword:=marcade.dswb; //DSW2 $c0000c:sfighter_getword:=marcade.in2; //SYSTEM $c0001a:sfighter_getword:=(byte(char_act) shl 3)+(byte(bg_act) shl 5)+(byte(fg_act) shl 6)+(byte(sp_act) shl 7); $ff8000..$ffffff:sfighter_getword:=ram3[(direccion and $7fff) shr 1]; end; end; procedure sfighter_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.r:=pal4bit(tmp_color shr 8); color.g:=pal4bit(tmp_color shr 4); color.b:=pal4bit(tmp_color); set_pal_color(color,numero); case numero of 0..$ff:bg_paint:=true; $100..$1ff:fg_paint:=true; end; end; begin case direccion of 0..$4ffff:; //ROM $800000..$800fff:if ram1[(direccion and $fff) shr 1]<>valor then begin ram1[(direccion and $fff) shr 1]:=valor; gfx[0].buffer[(direccion and $fff) shr 1]:=true; end; $b00000..$b007ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,(direccion and $7ff) shr 1); end; $c00016,$c00010:; $c00014:if valor<>scroll_fg then begin if abs((scroll_fg and $fff0)-(valor and $fff0))>$f then fg_paint:=true; scroll_fg:=valor; end; $c00018:if valor<>scroll_bg then begin if abs((scroll_bg and $fff0)-(valor and $fff0))>$f then bg_paint:=true; scroll_bg:=valor; end; $c0001a:begin main_screen.flip_main_screen:=(valor and $4)<>0; if char_act<>((valor and $8)<>0) then begin char_act:=(valor and $8)<>0; if char_act then fillchar(gfx[0].buffer,$800,1); end; bg_act:=(valor and $20)<>0; fg_act:=(valor and $40)<>0; sp_act:=(valor and $80)<>0; end; $c0001c:begin soundlatch:=valor and $ff; z80_1.change_nmi(PULSE_LINE); end; $ff8000..$ffffff:ram3[(direccion and $7fff) shr 1]:=valor; end; end; //sound function sf_snd_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$c000..$c7ff:sf_snd_getbyte:=mem_snd[direccion]; $c800:sf_snd_getbyte:=soundlatch; $e001:sf_snd_getbyte:=ym2151_0.status; end; end; procedure sf_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; //ROM $c000..$c7ff:mem_snd[direccion]:=valor; $e000:ym2151_0.reg(valor); $e001:ym2151_0.write(valor); end; end; function sf_misc_getbyte(direccion:word):byte; begin case direccion of 0..$7fff:sf_misc_getbyte:=rom_misc[0,direccion]; $8000..$ffff:sf_misc_getbyte:=rom_misc[misc_bank,direccion and $7fff]; end; end; procedure sf_misc_putbyte(direccion:word;valor:byte); begin end; function sf_misc_inbyte(puerto:word):byte; begin if (puerto and $ff)=1 then sf_misc_inbyte:=soundlatch; end; procedure sf_misc_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of 0:begin msm5205_0.reset_w((valor shr 7) and 1); msm5205_0.data_w(valor); msm5205_0.vclk_w(1); msm5205_0.vclk_w(0); end; 1:begin msm5205_1.reset_w((valor shr 7) and 1); msm5205_1.data_w(valor); msm5205_1.vclk_w(1); msm5205_1.vclk_w(0); end; 2:misc_bank:=valor+1; end; end; procedure ym2151_snd_irq(irqstate:byte); begin z80_1.change_irq(irqstate); end; procedure sound_instruccion; begin ym2151_0.update; end; procedure sf_adpcm_timer; begin z80_0.change_irq(HOLD_LINE); end; //Main procedure reset_sfighter; begin m68000_0.reset; z80_1.reset; z80_0.reset; ym2151_0.reset; msm5205_0.reset; msm5205_1.reset; reset_audio; marcade.in0:=$ffff; marcade.in1:=$ffff; marcade.in2:=$ff7f; scroll_bg:=0; scroll_fg:=0; bg_paint:=false; fg_paint:=false; bg_act:=false; fg_act:=false; char_act:=false; sp_act:=false; misc_bank:=1; end; function iniciar_sfighter:boolean; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3, 16*16+0, 16*16+1, 16*16+2, 16*16+3, 16*16+8+0, 16*16+8+1, 16*16+8+2, 16*16+8+3); ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16, 8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16); var memoria_temp,ptemp:pbyte; f:byte; begin llamadas_maquina.bucle_general:=sfighter_principal; llamadas_maquina.reset:=reset_sfighter; iniciar_sfighter:=false; iniciar_audio(true); screen_init(1,512,512,false,true); screen_init(2,512,256,true); screen_init(3,512,256); screen_init(4,512,256,true); iniciar_video(384,224); //Main CPU m68000_0:=cpu_m68000.create(8000000,256); m68000_0.change_ram16_calls(sfighter_getword,sfighter_putword); //Sound CPU z80_1:=cpu_z80.create(3579545,256); z80_1.change_ram_calls(sf_snd_getbyte,sf_snd_putbyte); z80_1.init_sound(sound_instruccion); //Sub CPU z80_0:=cpu_z80.create(3579545,256); z80_0.change_ram_calls(sf_misc_getbyte,sf_misc_putbyte); z80_0.change_io_calls(sf_misc_inbyte,sf_misc_outbyte); timers.init(z80_0.numero_cpu,3579545/8000,sf_adpcm_timer,nil,true); //Sound Chips ym2151_0:=ym2151_chip.create(3579545); ym2151_0.change_irq_func(ym2151_snd_irq); msm5205_0:=MSM5205_chip.create(384000,MSM5205_SEX_4B,2,nil); msm5205_1:=MSM5205_chip.create(384000,MSM5205_SEX_4B,2,nil); //cargar roms if not(roms_load16w(@rom,sfighter_rom)) then exit; //Sound CPUs if not(roms_load(@mem_snd,sfighter_snd)) then exit; getmem(memoria_temp,$200000); if not(roms_load(memoria_temp,sfighter_msm)) then exit; ptemp:=memoria_temp; for f:=0 to 7 do begin copymemory(@rom_misc[f,0],ptemp,$8000); inc(ptemp,$8000); end; //convertir chars if not(roms_load(memoria_temp,sfighter_char)) then exit; init_gfx(0,8,8,$400); gfx[0].trans[3]:=true; gfx_set_desc_data(2,0,16*8,4,0); convert_gfx(0,0,memoria_temp,@ps_x,@ps_y,false,false); //convertir bg y cargar tile maps if not(roms_load(memoria_temp,sfighter_bg)) then exit; if not(roms_load(@ram_tile_map1,sfighter_tile_map1)) then exit; init_gfx(1,16,16,$1000); gfx_set_desc_data(4,0,64*8,4,0,$40000*8+4,$40000*8+0); convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false); //convertir fg y cargar tile maps if not(roms_load(memoria_temp,sfighter_fg)) then exit; if not(roms_load(@ram_tile_map2,sfighter_tile_map2)) then exit; init_gfx(2,16,16,$2000); gfx[2].trans[15]:=true; gfx_set_desc_data(4,0,64*8,4,0,$80000*8+4,$80000*8+0); convert_gfx(2,0,memoria_temp,@ps_x,@ps_y,false,false); //sprites if not(roms_load(memoria_temp,sfighter_sprites)) then exit; init_gfx(3,16,16,$4000); gfx[3].trans[15]:=true; gfx_set_desc_data(4,0,64*8,4,0,$e0000*8+4,$e0000*8+0); convert_gfx(3,0,memoria_temp,@ps_x[0],@ps_y[0],false,false); //DIP marcade.dswa:=$dfff; marcade.dswb:=$ffff; marcade.dswa_val:=@sfighter_dip_a; marcade.dswb_val:=@sfighter_dip_b; //final freemem(memoria_temp); reset_sfighter; iniciar_sfighter:=true; end; end.
unit ADC.Types; interface uses Winapi.Windows, System.Classes, System.Generics.Collections, System.Generics.Defaults, System.SysUtils, System.DateUtils, Winapi.Messages, Vcl.Controls, Vcl.Graphics, System.RegularExpressions, Winapi.ActiveX, MSXML2_TLB, ActiveDs_TLB; const { Название приложения } APP_TITLE = 'AD Commander'; APP_TITLE_JOKE = 'Zhigadlo AD Commander'; ADC_SEARCH_PAGESIZE = 1000; { Разделы ini файла } INI_SECTION_GENERAL = 'GENERAL'; INI_SECTION_ATTRIBUTES = 'ATTRIBUTES'; INI_SECTION_EVENTS = 'EVENTS'; INI_SECTION_EDITOR = 'EDITOR'; INI_SECTION_FLOATING = 'FLOATING_WINDOW'; INI_SECTION_MOUSE = 'MOUSE'; INI_SECTION_STATE = 'STATE'; INI_SECTION_DMRC = 'DAMEWARE'; INI_SECTION_PSEXEC = 'PSEXEC'; { Тип подключения DameWare } DMRC_CONNECTION_MRC = 0; DMRC_CONNECTION_RDP = 1; { Тип авторизации DameWare } DMRC_AUTH_PROPRIETARY = 0; DMRC_AUTH_WINNT = 1; DMRC_AUTH_WINLOGON = 2; DMRC_AUTH_SMARTCARD = 3; DMRC_AUTH_CURRENTUSER = 4; { Используемый API } ADC_API_LDAP = 0; ADC_API_ADSI = 1; { Опции левой клавиши мыши } MOUSE_LMB_OPTION1 = 1; MOUSE_LMB_OPTION2 = 2; { Опции фильтра записей } FILTER_BY_ANY = 0; FILTER_BY_NAME = 1; { Типы аттрибутов AD } ATTR_TYPE_ANY = '_any_'; ATTR_TYPE_UNDEFINED = 'Undefined'; ATTR_TYPE_DN_STRING = 'DN'; ATTR_TYPE_OID = 'OID'; ATTR_TYPE_CASE_EXACT_STRING = 'CaseExactString'; ATTR_TYPE_CASE_IGNORE_STRING = 'CaseIgnoreString'; ATTR_TYPE_PRINTABLE_STRING = 'PrintableString'; ATTR_TYPE_NUMERIC_STRING = 'NumericString'; ATTR_TYPE_DN_WITH_BINARY = 'DNWithBinary'; ATTR_TYPE_BOOLEAN = 'Boolean'; ATTR_TYPE_INTEGER = 'INTEGER'; ATTR_TYPE_OCTET_STRING = 'OctetString'; ATTR_TYPE_UTC_TIME = 'GeneralizedTime'; ATTR_TYPE_DIRECTORY_STRING = 'DirectoryString'; ATTR_TYPE_PRESENTATION_ADDRESS = 'PresentationAddress'; ATTR_TYPE_DN_WITH_STRING = 'DNWithString'; ATTR_TYPE_NT_SECURITY_DESCRIPTOR = 'ObjectSecurityDescriptor'; ATTR_TYPE_LARGE_INTEGER = 'INTEGER8'; ATTR_TYPE_SID_STRING = 'OctetString'; { Контрольные события } CTRL_EVENT_STORAGE_DISK = 0; CTRL_EVENT_STORAGE_AD = 1; { Режим редактирования } ADC_EDIT_MODE_CREATE = 0; ADC_EDIT_MODE_CHANGE = 1; ADC_EDIT_MODE_DELETE = 2; { Парметры изображения пользователя } USER_IMAGE_EMPTY = 0; USER_IMAGE_ASSIGNED = 1; USER_IMAGE_MAX_WIDTH = 96; USER_IMAGE_MAX_HEIGHT = 96; COLOR_SELBORDER: TColorRef = $00B16300; //RGB(0, 99, 177); COLOR_GRAY_TEXT: TColorRef = $333333; { При запуске нескольких копий приложения } EXEC_NEW_INSTANCE = 1; EXEC_PROMPT_ACTION = 2; { Категория контейнера AD } AD_CONTCAT_CONTAINER = 1; AD_CONTCAT_ORGUNIT = 2; { Объекты фильтра } FILTER_OBJECT_USER = 1; // 1 shl 0 FILTER_OBJECT_GROUP = 2; // 1 shl 1 FILTER_OBJECT_WORKSTATION = 4; // 1 shl 2 FILTER_OBJECT_DC = 8; // 1 shl 3 { Текстовые константы } TEXT_NO_DATA = '<нет данных>'; TEXT_FILE_NOT_FOUND = 'Файл не найден'; {$ALIGN 8} type TFloatingWindowStyle = (fwsLync, fwsSkype); type TAdsValueArray = array[0..ANYSIZE_ARRAY-1] of ADSVALUE; PAdsValueArray = ^TAdsValueArray; type TIPAddr = record FQDN : string; v4 : string; v6 : string; end; PIPAddr = ^TIPAddr; TDHCPInfo = record ServerNetBIOSName: string; ServerName: string; ServerAddress: string; HardwareAddress: string; IPAddress: TIPAddr; SubnetMask: string; LeaseExpires: TDateTime; end; PDHCPInfo = ^TDHCPInfo; type PImgByteArray = ^TImgByteArray; TImgByteArray = array of Byte; TImgByteArrayHelper = record helper for TImgByteArray function AsBinString: string; function AsBinAnsiString: AnsiString; end; type PXMLByteArray = ^TXMLByteArray; TXMLByteArray = array of Byte; TXMLByteArrayHelper = record helper for TXMLByteArray function AsBinString: string; function AsBinAnsiString: AnsiString; end; type PADContainer = ^TADContainer; TADContainer = record name: string; systemFlags: Integer; allowedChildClasses: string; Category: Byte; DistinguishedName: string; CanonicalName: string; Path: string; procedure Clear; end; TOrganizationalUnitHelper = record helper for TADContainer function ExtractName: string; function CanBeDeleted: Boolean; function CanContainClass(AClass: string): Boolean; end; type PADAttribute = ^TADAttribute; TADAttribute = packed record ID: Byte; Name: string[255]; { Имя атрибута Active Directory } ObjProperty: string[255]; { Имя поля объекта TADObject } Title: string[255]; { Текстовое описание атрибута } Comment: string[255]; { Краткий комментарий к атрибуту } Visible: Boolean; { Отображать столбец в списке } Width: Word; { Ширина столбца в списке } Alignment: TAlignment; { Выравнивание при отображении } BgColor: TColor; { Цвет фона } FontColor: TColor; { Цвет шрифта } ReadOnly: Boolean; { Только для чтения } end; type PADGroupMember = ^TADGroupMember; TADGroupMember = record SortKey: Integer; name: string; sAMAccountName: string; distinguishedName: string; end; TADGroupMemberList = class(TList) private FOwnsObjects: Boolean; function Get(Index: Integer): PADGroupMember; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADGroupMember): Integer; procedure Clear; override; property Items[Index: Integer]: PADGroupMember read Get; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; type PADGroup = ^TADGroup; TADGroup = record ImageIndex: Integer; Selected: Boolean; IsMember: Boolean; IsPrimary: Boolean; distinguishedName: string; name: string; description: string; primaryGroupToken: Integer; groupType: Integer; end; TADGroupList = class(TList) protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; private FOwnsObjects: Boolean; function Get(Index: Integer): PADGroup; function GetPrimaryGroupName: string; function GetPrimaryGroupIndex: integer; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADGroup): Integer; procedure Clear; override; function GetPrimaryGroup: PADGroup; procedure SetGroupAsPrimary(AToken: Integer); procedure SetSelected(AIndex: Integer; ASelected: Boolean); function IndexOf(AToken: Integer): Integer; overload; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; property Items[Index: Integer]: PADGroup read Get; default; property PrimaryGroupName: string read GetPrimaryGroupName; property PrimaryGroupIndex: integer read GetPrimaryGroupIndex; end; type PADEvent = ^TADEvent; TADEvent = record ID: Integer; Date: TDate; Description: string; procedure Clear; end; TADEventList = class(TList) private FOwnsObjects: Boolean; procedure Notify(Ptr: Pointer; Action: TListNotification); override; function GenerateItemID: Integer; function Get(Index: Integer): PADEvent; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADEvent): Integer; procedure Clear; override; function GetNearestEvent: TDate; function GetEventByID(AID: Integer): PADEvent; property Items[Index: Integer]: PADEvent read Get; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; type TProgressProc = procedure (AItem: TObject; AProgress: Integer) of object; TExceptionProc = procedure (AMsg: string; ACode: ULONG) of object; TSelectContainerProc = procedure (Sender: TObject; ACont: TADContainer) of object; TCreateUserProc = procedure (Sender: TObject; AOpenEditor: Boolean) of object; TChangeComputerProc = procedure (Sender: TObject) of object; TChangeUserProc = procedure (Sender: TObject) of object; TPwdChangeProc = procedure (Sender: TObject; AChangeOnLogon: Boolean) of object; TSelectGroupProc = procedure (Sender: TObject; AGroupList: TADGroupList) of object; TApplyWorkstationsProc = procedure (Sender: TObject; AWorkstations: string) of object; TChangeEventProc = procedure (Sender: TObject; AMode: Byte; AEvent: TADEvent) of object; TCreateOrganizationalUnitProc = procedure (ANewDN: string) of object; TQueryFullProcessImageName = function (Process: THandle; Flags: DWORD; Buffer: LPTSTR; Size: PDWORD): DWORD; stdcall; function GetUserNameEx(NameFormat: DWORD; lpNameBuffer: LPSTR; var nSize: DWORD): Boolean; stdcall; implementation function GetUserNameEx; external 'secur32.dll' name 'GetUserNameExA'; { TADGroupMemberList } function TADGroupMemberList.Add(Value: PADGroupMember): Integer; begin Result := inherited Add(Value); end; procedure TADGroupMemberList.Clear; var i: Integer; begin if FOwnsObjects then for i := Self.Count - 1 downto 0 do Dispose(Self.Items[i]); inherited Clear; end; constructor TADGroupMemberList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADGroupMemberList.Destroy; begin Clear; inherited; end; function TADGroupMemberList.Get(Index: Integer): PADGroupMember; begin Result := PADGroupMember(inherited Get(Index)); end; { TOrganizationalUnit } procedure TADContainer.Clear; begin Category := 0; name := ''; systemFlags := 0; DistinguishedName := ''; CanonicalName := ''; Path := ''; end; { TImgByteArrayHelper } function TImgByteArrayHelper.AsBinAnsiString: AnsiString; begin SetString(Result, PAnsiChar(@Self[0]), Length(Self)); end; function TImgByteArrayHelper.AsBinString: string; begin SetString(Result, PWideChar(@Self[0]), Length(Self) div 2); end; { TXMLByteArrayHelper } function TXMLByteArrayHelper.AsBinAnsiString: AnsiString; begin SetString(Result, PAnsiChar(@Self[0]), Length(Self)); end; function TXMLByteArrayHelper.AsBinString: string; begin SetString(Result, PWideChar(@Self[0]), Length(Self) div 2); end; { TADGroupList } function TADGroupList.Add(Value: PADGroup): Integer; begin Result := inherited Add(Value); end; procedure TADGroupList.Clear; var i: Integer; begin if FOwnsObjects then for i := Self.Count - 1 downto 0 do Dispose(Self.Items[i]); inherited Clear; end; constructor TADGroupList.Create(AOwnsObjects: Boolean = True); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADGroupList.Destroy; begin inherited Destroy; end; function TADGroupList.Get(Index: Integer): PADGroup; begin Result := PADGroup(inherited Get(Index)); end; function TADGroupList.GetPrimaryGroup: PADGroup; var i: Integer; begin i := Self.PrimaryGroupIndex; if i > -1 then Result := Self[i] else Result := nil; end; function TADGroupList.GetPrimaryGroupIndex: integer; var g: PADGroup; begin Result := -1; for g in Self do if g^.IsPrimary then begin Result := Self.IndexOf(g); Break; end; end; function TADGroupList.GetPrimaryGroupName: string; var g: PADGroup; begin Result := ''; for g in Self do if g^.IsPrimary then begin Result := g^.name; Break; end; end; function TADGroupList.IndexOf(AToken: Integer): Integer; var g: PADGroup; begin Result := -1; for g in Self do if g^.primaryGroupToken = AToken then begin Result := IndexOf(g); Break; end; end; procedure TADGroupList.Notify(Ptr: Pointer; Action: TListNotification); begin case Action of lnAdded: ; lnExtracted: ; lnDeleted: ; end; inherited; end; procedure TADGroupList.SetGroupAsPrimary(AToken: Integer); var g: PADGroup; begin for g in Self do g^.IsPrimary := g^.primaryGroupToken = AToken; end; procedure TADGroupList.SetSelected(AIndex: Integer; ASelected: Boolean); begin try Self.Items[AIndex]^.Selected := ASelected; except end; end; { TADEventList } function TADEventList.Add(Value: PADEvent): Integer; begin Result := inherited Add(Value); end; procedure TADEventList.Clear; var i: Integer; begin for i := Self.Count - 1 downto 0 do Self.Delete(i); inherited Clear; end; constructor TADEventList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADEventList.Destroy; begin inherited; end; function TADEventList.GenerateItemID: Integer; var id: Integer; begin id := 0; repeat id := id + 1; until (Self.GetEventByID(id) = nil) or (id > Self.Count); Result := id; end; function TADEventList.Get(Index: Integer): PADEvent; begin Result := PADEvent(inherited Get(Index)); end; function TADEventList.GetEventByID(AID: Integer): PADEvent; var e: PADEvent; begin Result := nil; for e in Self do begin if e^.ID = AID then begin Result := e; Break; end; end; end; function TADEventList.GetNearestEvent: TDate; var e: PADEvent; res: TDate; begin if Self.Count > 0 then res := Self[0]^.Date else res := 0; for e in Self do if CompareDate(e^.Date, res) < 0 then res := e^.Date; Result := res; end; procedure TADEventList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; case Action of lnAdded: begin PADEvent(Ptr)^.ID := Self.GenerateItemID; end; lnExtracted: begin PADEvent(Ptr)^.ID := 0; end; lnDeleted: begin if FOwnsObjects then Dispose(PADEvent(Ptr)) end; end; end; { TADEvent } procedure TADEvent.Clear; begin ID := 0; Date := 0; Description := ''; end; { TOrganizationalUnitHelper } function TOrganizationalUnitHelper.CanBeDeleted: Boolean; const FLAG_DISALLOW_DELETE = $80000000; begin Result := Self.systemFlags and FLAG_DISALLOW_DELETE = 0; end; function TOrganizationalUnitHelper.CanContainClass(AClass: string): Boolean; var valList: TStringList; begin valList := TStringList.Create; valList.CaseSensitive := False; valList.Delimiter := ','; valList.DelimitedText := Self.allowedChildClasses; Result := valList.IndexOf(AClass) > -1; valList.Free; end; function TOrganizationalUnitHelper.ExtractName: string; var RegEx: TRegEx; begin RegEx := TRegEx.Create('(?<=[\\\/])[^\\\/]+$', [roIgnoreCase]); Result := RegEx.Match(Self.CanonicalName).Value end; end.
unit HTMLParserAll; interface uses Classes, Sysutils, WStrings; type TNodeList = class public FOwnerNode: Pointer{TNode}; FList: TList; public function GetLength: Integer; virtual; function NodeListIndexOf(node: Pointer{TNode}): Integer; procedure NodeListAdd(node: Pointer{TNode}); procedure NodeListDelete(I: Integer); procedure NodeListInsert(I: Integer; node: Pointer{TNode}); procedure NodeListRemove(node: Pointer{TNode}); procedure NodeListClear(WithItems: Boolean); property ownerNode: Pointer{TNode} read FOwnerNode; constructor Create(AOwnerNode: Pointer{TNode}); public destructor Destroy; override; function item(index: Integer): Pointer{TNode}; virtual; property length: Integer read GetLength; end; TNamedNodeMap = class(TNodeList) public function getNamedItem(const name: WideString): Pointer{TNode}; function setNamedItem(arg: Pointer{TNode}): Pointer{TNode}; function removeNamedItem(const name: WideString): Pointer{TNode}; function getNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode}; function setNamedItemNS(arg: Pointer{TNode}): Pointer{TNode}; function removeNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode}; end; TSearchNodeList = class(TNodeList) public FNamespaceParam : WideString; FNameParam : WideString; FSynchronized: Boolean; function GetLength: Integer; override; function acceptNode(node: Pointer{TNode}): Boolean; procedure TraverseTree(rootNode: Pointer{TNode}); procedure Rebuild; public constructor Create(AOwnerNode: Pointer{TNode}; const namespaceURI, name: WideString); destructor Destroy; override; procedure Invalidate; function item(index: Integer): Pointer{TNode}; override; end; TNamespaceURIList = class public FList: TWStringList; function GetItem(I: Integer): WideString; public constructor Create; destructor Destroy; override; procedure Clear; function Add(const NamespaceURI: WideString): Integer; property Item[I: Integer]: WideString read GetItem; default; end; //======================================================= // htmldom define //======================================================= const ERR_INDEX_SIZE = 1; ERR_DOMSTRING_SIZE = 2; ERR_HIERARCHY_REQUEST = 3; ERR_WRONG_DOCUMENT = 4; ERR_INVALID_CHARACTER = 5; ERR_NO_DATA_ALLOWED = 6; ERR_NO_MODIFICATION_ALLOWED = 7; ERR_NOT_FOUND = 8; ERR_NOT_SUPPORTED = 9; ERR_INUSE_ATTRIBUTE = 10; ERR_INVALID_STATE = 11; ERR_SYNTAX = 12; ERR_INVALID_MODIFICATION = 13; ERR_NAMESPACE = 14; ERR_INVALID_ACCESS = 15; {HTML DTDs} DTD_HTML_STRICT = 1; DTD_HTML_LOOSE = 2; DTD_HTML_FRAMESET = 3; DTD_XHTML_STRICT = 4; DTD_XHTML_LOOSE = 5; DTD_XHTML_FRAMESET = 6; const UNKNOWN_TAG = 0; A_TAG = 1; ABBR_TAG = 2; ACRONYM_TAG = 3; ADDRESS_TAG = 4; APPLET_TAG = 5; AREA_TAG = 6; B_TAG = 7; BASE_TAG = 8; BASEFONT_TAG = 9; BDO_TAG = 10; BIG_TAG = 11; BLOCKQUOTE_TAG = 12; BODY_TAG = 13; BR_TAG = 14; BUTTON_TAG = 15; CAPTION_TAG = 16; CENTER_TAG = 17; CITE_TAG = 18; CODE_TAG = 19; COL_TAG = 20; COLGROUP_TAG = 21; DD_TAG = 22; DEL_TAG = 23; DFN_TAG = 24; DIR_TAG = 25; DIV_TAG = 26; DL_TAG = 27; DT_TAG = 28; EM_TAG = 29; FIELDSET_TAG = 30; FONT_TAG = 31; FORM_TAG = 32; FRAME_TAG = 33; FRAMESET_TAG = 34; H1_TAG = 35; H2_TAG = 36; H3_TAG = 37; H4_TAG = 38; H5_TAG = 39; H6_TAG = 40; HEAD_TAG = 41; HR_TAG = 42; HTML_TAG = 43; I_TAG = 44; IFRAME_TAG = 45; IMG_TAG = 46; INPUT_TAG = 47; INS_TAG = 48; ISINDEX_TAG = 49; KBD_TAG = 50; LABEL_TAG = 51; LEGEND_TAG = 52; LI_TAG = 53; LINK_TAG = 54; MAP_TAG = 55; MENU_TAG = 56; META_TAG = 57; NOFRAMES_TAG = 58; NOSCRIPT_TAG = 59; OBJECT_TAG = 60; OL_TAG = 61; OPTGROUP_TAG = 62; OPTION_TAG = 63; P_TAG = 64; PARAM_TAG = 65; PRE_TAG = 66; Q_TAG = 67; S_TAG = 68; SAMP_TAG = 69; SCRIPT_TAG = 70; SELECT_TAG = 71; SMALL_TAG = 72; SPAN_TAG = 73; STRIKE_TAG = 74; STRONG_TAG = 75; STYLE_TAG = 76; SUB_TAG = 77; SUP_TAG = 78; TABLE_TAG = 79; TBODY_TAG = 80; TD_TAG = 81; TEXTAREA_TAG = 82; TFOOT_TAG = 83; TH_TAG = 84; THEAD_TAG = 85; TITLE_TAG = 86; TR_TAG = 87; TT_TAG = 88; U_TAG = 89; UL_TAG = 90; VAR_TAG = 91; BlockTags = [ADDRESS_TAG, BLOCKQUOTE_TAG, CENTER_TAG, DIV_TAG, DL_TAG, FIELDSET_TAG, {FORM_TAG,} H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HR_TAG, NOSCRIPT_TAG, OL_TAG, PRE_TAG, TABLE_TAG, UL_TAG]; BlockParentTags = [ADDRESS_TAG, BLOCKQUOTE_TAG, CENTER_TAG, DIV_TAG, DL_TAG, FIELDSET_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HR_TAG, LI_TAG, NOSCRIPT_TAG, OL_TAG, PRE_TAG, TD_TAG, TH_TAG, UL_TAG]; HeadTags = [BASE_TAG, LINK_TAG, META_TAG, SCRIPT_TAG, STYLE_TAG, TITLE_TAG]; {Elements forbidden from having an end tag, and therefore are empty; from HTML 4.01 spec} EmptyTags = [AREA_TAG, BASE_TAG, BASEFONT_TAG, BR_TAG, COL_TAG, FRAME_TAG, HR_TAG, IMG_TAG, INPUT_TAG, ISINDEX_TAG, LINK_TAG, META_TAG, PARAM_TAG]; PreserveWhiteSpaceTags = [PRE_TAG]; NeedFindParentTags = [COL_TAG, COLGROUP_TAG, DD_TAG, DT_TAG, LI_TAG, OPTION_TAG, P_TAG, TABLE_TAG, TBODY_TAG, TD_TAG, TFOOT_TAG, TH_TAG, THEAD_TAG, TR_TAG]; ListItemParentTags = [DIR_TAG, MENU_TAG, OL_TAG, UL_TAG]; DefItemParentTags = [DL_TAG]; TableSectionParentTags = [TABLE_TAG]; ColParentTags = [COLGROUP_TAG]; RowParentTags = [TABLE_TAG, TBODY_TAG, TFOOT_TAG, THEAD_TAG]; CellParentTags = [TR_TAG]; OptionParentTags = [OPTGROUP_TAG, SELECT_TAG]; const HTMLDOM_NODE_NONE = 0; // extension HTMLDOM_NODE_ELEMENT = 1; HTMLDOM_NODE_ATTRIBUTE = 2; HTMLDOM_NODE_TEXT = 3; HTMLDOM_NODE_CDATA_SECTION = 4; HTMLDOM_NODE_ENTITY_REFERENCE = 5; HTMLDOM_NODE_ENTITY = 6; HTMLDOM_NODE_PROCESSING_INSTRUCTION = 7; HTMLDOM_NODE_COMMENT = 8; HTMLDOM_NODE_DOCUMENT = 9; HTMLDOM_NODE_DOCUMENT_TYPE = 10; HTMLDOM_NODE_DOCUMENT_FRAGMENT = 11; HTMLDOM_NODE_NOTATION = 12; HTMLDOM_NODE_END_ELEMENT = 255; // extension type PHtmlDocDomNode = ^THtmlDocDomNode; PHtmlDomNode = ^THtmlDomNode; THtmlDomNode = record NodeType : Integer; OwnerDocument : PHtmlDocDomNode; ParentDomNode : PHtmlDomNode; NamespaceURI : Integer; Attributes : TNamedNodeMap; ChildNodes : TNodeList; Prefix : WideString; NodeName : WideString; NodeValue : WideString; end; PHtmlAttribDomNode = ^THtmlDomNode; PHtmlTextDomNode = ^THtmlDomNode; PHtmlDocTypeDomNode = ^THtmlDocTypeDomNode; PHtmlElementDomNode = ^THtmlElementDomNode; THtmlDocDomNode = record BaseDomNode : THtmlDomNode; DocTypeDomNode : PHtmlDocTypeDomNode; NamespaceURIList : TNamespaceURIList; SearchNodeLists : TList; end; THtmlElementDomNode = record BaseDomNode : THtmlDomNode; IsEmpty : Boolean; end; THtmlDocTypeDomNode = record BaseDomNode : THtmlDomNode; //Entities : DomNodeList.TNamedNodeMap; //Notations : DomNodeList.TNamedNodeMap; PublicID : WideString; SystemID : WideString; InternalSubset : WideString; end; //======================================================= // htmlparser define //======================================================= const MAX_TAGS_COUNT = 128; MAX_FLAGS_COUNT = 32; type TDelimiters = set of Byte; TReaderState = (rsInitial, rsBeforeAttr, rsBeforeValue, rsInValue, rsInQuotedValue); PHtmlReader = ^THtmlReader; THtmlReaderEvent = procedure(AHtmlReader: PHtmlReader); PHtmlParser = ^THtmlParser; THtmlReader = record Position: Integer; NodeType: Integer; HtmlParser: PHtmlParser; IsEmptyElement: Boolean; Quotation: Word; State: TReaderState; PublicID: WideString; SystemID: WideString; Prefix: WideString; LocalName: WideString; NodeValue: WideString; HtmlStr: WideString; OnAttributeEnd: THtmlReaderEvent; OnAttributeStart: THtmlReaderEvent; OnCDataSection: THtmlReaderEvent; OnComment: THtmlReaderEvent; OnDocType: THtmlReaderEvent; OnElementEnd: THtmlReaderEvent; OnElementStart: THtmlReaderEvent; OnEndElement: THtmlReaderEvent; OnEntityReference: THtmlReaderEvent; OnNotation: THtmlReaderEvent; OnProcessingInstruction: THtmlReaderEvent; OnTextNode: THtmlReaderEvent; end; THtmlTagSet = set of 0..MAX_TAGS_COUNT - 1; THtmlTagFlags = set of 0..MAX_FLAGS_COUNT - 1; PHtmlTag = ^THtmlTag; THtmlTag = record Number: Integer; ParserFlags: THtmlTagFlags; FormatterFlags: THtmlTagFlags; Name: WideString; end; TCompareTag = function(Tag: PHtmlTag): Integer of object; THtmlParser = record HtmlDocument: PHtmlDocDomNode; HtmlReader: PHtmlReader; CurrentNode: PHtmlDomNode; CurrentTag: PHtmlTag; // EntityList: TEntList; // HtmlTagList: THtmlTagList; // URLSchemes: TURLSchemes; end; const TAB = 9; LF = 10; CR = 13; SP = 32; WhiteSpace = [TAB, LF, CR, SP]; startTagChar = Ord('<'); endTagChar = Ord('>'); specialTagChar = Ord('!'); slashChar = Ord('/'); equalChar = Ord('='); quotation = [Ord(''''), Ord('"')]; tagDelimiter = [slashChar, endTagChar]; tagNameDelimiter = whiteSpace + tagDelimiter; attrNameDelimiter = tagNameDelimiter + [equalChar]; startEntity = Ord('&'); startMarkup = [startTagChar, startEntity]; endEntity = Ord(';'); notEntity = [endEntity] + startMarkup + whiteSpace; notAttrText = whiteSpace + quotation + tagDelimiter; numericEntity = Ord('#'); hexEntity = [Ord('x'), Ord('X')]; decDigit = [Ord('0')..Ord('9')]; hexDigit = [Ord('a')..Ord('f'), Ord('A')..Ord('F')]; DocTypeStartStr = 'DOCTYPE'; DocTypeEndStr = '>'; CDataStartStr = '[CDATA['; CDataEndStr = ']]>'; CommentStartStr = '--'; CommentEndStr = '-->'; //======================================================= // //======================================================= function HtmlParserparseString(const htmlStr: WideString): PHtmlDocDomNode; overload; function HtmlParserparseString(AHtmlParser: PHtmlParser; const htmlStr: WideString): PHtmlDocDomNode; overload; function CheckOutHtmlParser: PHtmlParser; procedure CheckInHtmlParser(var AHtmlParser: PHtmlParser); procedure HtmlDomNodeFree(var ADomNode: PHtmlDomNode); function HtmlDomNodeGetName(AHtmlDomNode: PHtmlDomNode): WideString; function CheckOutTextDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; data: WideString): PHtmlDomNode; overload; implementation const htmlTagName = 'html'; headTagName = 'head'; bodyTagName = 'body'; type DomException = class(Exception) public FCode: Integer; public constructor Create(code: Integer); property code: Integer read FCode; end; TEntList = class(TList) private function GetCode(const Name: String): Integer; public constructor Create; property Code[const Name: String]: Integer read GetCode; end; THtmlTagList = class private FList: TList; FUnknownTag: PHtmlTag; FSearchName: WideString; FSearchNumber: Integer; function CompareName(Tag: PHtmlTag): Integer; function CompareNumber(Tag: PHtmlTag): Integer; function GetTag(Compare: TCompareTag): PHtmlTag; public constructor Create; destructor Destroy; override; function GetTagByName(const Name: WideString): PHtmlTag; function GetTagByNumber(Number: Integer): PHtmlTag; end; TURLSchemes = class(TStringList) private FMaxLen: Integer; public function Add(const S: String): Integer; override; function IsURL(const S: String): Boolean; function GetScheme(const S: String): String; property MaxLen: Integer read FMaxLen; end; var EntityList: TEntList = nil; HtmlTagList: THtmlTagList = nil; URLSchemes: TURLSchemes = nil; function CheckOutHtmlTag(const AName: WideString; ANumber: Integer; AParserFlags, AFormatterFlags: THtmlTagFlags): PHtmlTag; begin Result := System.New(PHtmlTag); FillChar(Result^, SizeOf(THtmlTag), 0); Result.Name := AName; Result.Number := ANumber; end; function GetEntValue(const Name: String): WideChar; begin Result := WideChar(EntityList.Code[Name]) end; function CharacterDataNodeGetLength(AHtmlDomNode: PHtmlDomNode): Integer; begin Result := System.Length(AHtmlDomNode.NodeValue) end; function HtmlDocGetDocumentElement(ADocument: PHtmlDocDomNode): PHtmlElementDomNode; var Child: PHtmlDomNode; I: Integer; begin for I := 0 to ADocument.BaseDomNode.childNodes.length - 1 do begin Child := ADocument.BaseDomNode.childNodes.item(I); if HTMLDOM_NODE_ELEMENT = Child.NodeType then begin Result := PHtmlElementDomNode(Child); Exit end end; Result := nil end; procedure HtmlDomNodeSetNamespaceURI(AHtmlDomNode: PHtmlDomNode; const value: WideString); begin if value <> '' then //TODO validate AHtmlDomNode.NamespaceURI := AHtmlDomNode.ownerDocument.namespaceURIList.Add(value) end; function IsNCName(const Value: WideString): Boolean; begin //TODO Result := true end; procedure HtmlDomNodeSetPrefix(AHtmlDomNode: PHtmlDomNode; const value: WideString); begin if not IsNCName(value) then raise DomException.Create(ERR_INVALID_CHARACTER); AHtmlDomNode.Prefix := value end; procedure HtmlDomNodeSetLocalName(AHtmlDomNode: PHtmlDomNode; const value: WideString); begin if not IsNCName(value) then raise DomException.Create(ERR_INVALID_CHARACTER); AHtmlDomNode.NodeName := value end; function HtmlDomNodeGetName(AHtmlDomNode: PHtmlDomNode): WideString; begin if HTMLDOM_NODE_CDATA_SECTION = AHtmlDomNode.NodeType then begin Result := '#cdata-section'; exit; end; if HTMLDOM_NODE_COMMENT = AHtmlDomNode.NodeType then begin Result := '#comment'; exit; end; if HTMLDOM_NODE_TEXT = AHtmlDomNode.NodeType then begin Result := '#text'; exit; end; if HTMLDOM_NODE_DOCUMENT_FRAGMENT = AHtmlDomNode.NodeType then begin Result := '#document-fragment'; exit; end; if HTMLDOM_NODE_DOCUMENT = AHtmlDomNode.NodeType then begin Result := '#document'; Exit; end; if AHtmlDomNode.Prefix <> '' then begin Result := AHtmlDomNode.Prefix + ':' + AHtmlDomNode.NodeName; end else begin Result := AHtmlDomNode.NodeName; end; end; function HtmlDomNodeGetFirstChild(AHtmlDomNode: PHtmlDomNode): PHtmlDomNode; begin if AHtmlDomNode.childNodes.length <> 0 then begin Result := PHtmlDomNode(AHtmlDomNode.childNodes.item(0)); end else begin Result := nil end; end; function NodeIsCanInsert(AOwnerNode, AChildNode: PHtmlDomNode): Boolean; begin Result := false; if HTMLDOM_NODE_ATTRIBUTE = AOwnerNode.NodeType then begin Result := AChildNode.NodeType in [HTMLDOM_NODE_ENTITY_REFERENCE, HTMLDOM_NODE_TEXT]; exit; end; if HTMLDOM_NODE_ELEMENT = AOwnerNode.NodeType then begin Result := not (AChildNode.NodeType in [HTMLDOM_NODE_ENTITY, HTMLDOM_NODE_DOCUMENT, HTMLDOM_NODE_DOCUMENT_TYPE, HTMLDOM_NODE_NOTATION]); exit; end; if HTMLDOM_NODE_DOCUMENT_FRAGMENT = AOwnerNode.NodeType then begin Result := not (AChildNode.NodeType in [HTMLDOM_NODE_ENTITY, HTMLDOM_NODE_DOCUMENT, HTMLDOM_NODE_DOCUMENT_TYPE, HTMLDOM_NODE_NOTATION]); exit; end; if HTMLDOM_NODE_DOCUMENT = AOwnerNode.NodeType then begin Result := (AChildNode.NodeType in [HTMLDOM_NODE_TEXT, HTMLDOM_NODE_COMMENT, HTMLDOM_NODE_PROCESSING_INSTRUCTION]) or (AChildNode.NodeType = HTMLDOM_NODE_ELEMENT) and (HtmlDocGetDocumentElement(PHtmlDocDomNode(AOwnerNode)) = nil); end; end; function NodeGetParentDomNode(AHtmlDomNode: PHtmlDomNode): PHtmlDomNode; begin Result := nil; if nil <> AHtmlDomNode then begin if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then begin Result := nil; end else begin Result := AHtmlDomNode.ParentDomNode; end; end; end; function HtmlDomNodeIsAncestorOf(AHtmlDomNode: PHtmlDomNode; node: PHtmlDomNode): Boolean; var tmpDomNode: PHtmlDomNode; begin tmpDomNode := node; while (nil <> tmpDomNode) do begin if tmpDomNode = AHtmlDomNode then begin Result := true; Exit end; tmpDomNode := NodeGetParentDomNode(tmpDomNode); end; Result := false; end; procedure HtmlDocInvalidateSearchNodeLists(ADocument: PHtmlDocDomNode); var I: Integer; begin for I := 0 to ADocument.SearchNodeLists.Count - 1 do TSearchNodeList(ADocument.SearchNodeLists[I]).Invalidate end; function HtmlDomNodeRemoveChild(AHtmlDomNode, oldChild: PHtmlDomNode): PHtmlDomNode; var I: Integer; begin I := AHtmlDomNode.ChildNodes.NodeListIndexOf(oldChild); if I < 0 then raise DomException.Create(ERR_NOT_FOUND); AHtmlDomNode.ChildNodes.NodeListDelete(I); oldChild.ParentDomNode := nil; Result := oldChild; if (nil <> AHtmlDomNode.ownerDocument) then HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument) end; function HtmlDomNodeInsertSingleNode(AHtmlDomNode, newChild, refChild: PHtmlDomNode): PHtmlDomNode; var I: Integer; tmpNode: PHtmlDomNode; begin if not NodeIsCanInsert(AHtmlDomNode, newChild) or HtmlDomNodeIsAncestorOf(newChild, AHtmlDomNode) then raise DomException.Create(ERR_HIERARCHY_REQUEST); if newChild <> refChild then begin if (nil <> refChild) then begin I := AHtmlDomNode.ChildNodes.NodeListIndexOf(refChild); if I < 0 then raise DomException.Create(ERR_NOT_FOUND); AHtmlDomNode.ChildNodes.NodeListInsert(I, newChild) end else begin AHtmlDomNode.ChildNodes.NodeListAdd(newChild); end; tmpNode := NodeGetParentDomNode(newChild); if (nil <> tmpNode) then HtmlDomNoderemoveChild(tmpNode, newChild); newChild.ParentDomNode := AHtmlDomNode; end; Result := newChild end; function HtmlDomNodeinsertBefore(AHtmlDomNode, newChild, refChild: PHtmlDomNode): PHtmlDomNode; var tmpDomNode: PHtmlDomNode; begin if newChild.ownerDocument <> AHtmlDomNode.ownerDocument then raise DomException.Create(ERR_WRONG_DOCUMENT); if newChild.NodeType = HTMLDOM_NODE_DOCUMENT_FRAGMENT then begin tmpDomNode := HtmlDomNodeGetfirstChild(newChild); while (nil <> tmpDomNode) do begin HtmlDomNodeInsertSingleNode(AHtmlDomNode, tmpDomNode, refChild); tmpDomNode := HtmlDomNodeGetfirstChild(newChild); end; Result := newChild end else begin Result := HtmlDomNodeInsertSingleNode(AHtmlDomNode, newChild, refChild); end; if (nil <> AHtmlDomNode.ownerDocument) then HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument) end; function HtmlDomNodeAppendChild(AHtmlDomNode, newChild: PHtmlDomNode): PHtmlDomNode; begin Result := HtmlDomNodeinsertBefore(AHtmlDomNode, newChild, nil); if (nil <> AHtmlDomNode.ownerDocument) then HtmlDocInvalidateSearchNodeLists(AHtmlDomNode.ownerDocument) end; procedure NodeSetValue(AHtmlDomNode: PHtmlDomNode; const value: WideString); begin if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then begin AHtmlDomNode.ChildNodes.NodeListClear(false); HtmlDomNodeappendChild(AHtmlDomNode, CheckOutTextDomNode(HTMLDOM_NODE_TEXT, AHtmlDomNode.ownerDocument, value)); exit; end; if (HTMLDOM_NODE_TEXT = AHtmlDomNode.NodeType) or (HTMLDOM_NODE_COMMENT = AHtmlDomNode.NodeType) or (HTMLDOM_NODE_CDATA_SECTION = AHtmlDomNode.NodeType) then begin // charset node AHtmlDomNode.NodeValue := value end; end; procedure DomNodeInitialize(AHtmlDomNode: PHtmlDomNode; ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean); var I: Integer; begin AHtmlDomNode.NodeType := ANodeType; AHtmlDomNode.OwnerDocument := ownerDocument; HtmlDomNodeSetNamespaceURI(AHtmlDomNode, namespaceURI); if withNS then begin I := Pos(':', qualifiedName); if I <> 0 then begin HtmlDomNodeSetPrefix(AHtmlDomNode, Copy(qualifiedName, 1, I - 1)); HtmlDomNodeSetLocalName(AHtmlDomNode, Copy(qualifiedName, I + 1, Length(qualifiedName) - I)) end else begin HtmlDomNodeSetLocalName(AHtmlDomNode, qualifiedName) end; end else begin HtmlDomNodeSetLocalName(AHtmlDomNode, qualifiedName); end; AHtmlDomNode.ChildNodes := TNodeList.Create(AHtmlDomNode); end; procedure HtmlDomNodeFree(var ADomNode: PHtmlDomNode); begin if nil = ADomNode then exit; if HTMLDOM_NODE_DOCUMENT = ADomNode.NodeType then begin if nil <> PHtmlDocDomNode(ADomNode).DocTypeDomNode then begin HtmlDomNodeFree(PHtmlDomNode(PHtmlDocDomNode(ADomNode).DocTypeDomNode)); end; PHtmlDocDomNode(ADomNode).NamespaceURIList.Free; PHtmlDocDomNode(ADomNode).SearchNodeLists.Free; end; if (nil <> ADomNode.ChildNodes) then begin ADomNode.ChildNodes.NodeListClear(true); ADomNode.ChildNodes.Free; ADomNode.ChildNodes := nil; end; if (nil <> ADomNode.Attributes) then begin ADomNode.Attributes.NodeListClear(true); ADomNode.Attributes.Free; ADomNode.Attributes := nil; end; FreeMem(ADomNode); ADomNode := nil; end; function CheckOutHtmlDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlDomNode; overload; begin Result := System.New(PHtmlDomNode); FillChar(Result^, SizeOf(THtmlDomNode), 0); DomNodeInitialize(Result, ANodeType, ownerDocument, namespaceURI, qualifiedName, withNS); end; function CheckOutHtmlDomNode: PHtmlDomNode; overload; begin Result := System.New(PHtmlDomNode); FillChar(Result^, SizeOf(THtmlDomNode), 0); end; function CheckOutEntityReferenceNode(ownerDocument: PHtmlDocDomNode; const name: WideString): PHtmlDomNode; begin Result := CheckOutHtmlDomNode; DomNodeInitialize(Result, HTMLDOM_NODE_ENTITY_REFERENCE, ownerDocument, '', name, false); end; //constructor TCharacterDataNode.Create(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; const data: WideString); //begin // inherited Create(ANodeType, ownerDocument, '', '', false); // NodeSetValue(@fNodeData, data); //end; function CheckOutTextDomNode(ANodeType: Integer; ownerDocument: PHtmlDocDomNode; data: WideString): PHtmlDomNode; overload; begin Result := System.New(PHtmlDomNode); FillChar(Result^, SizeOf(THtmlDomNode), 0); DomNodeInitialize(Result, ANodeType, ownerDocument, '', '', false); NodeSetValue(Result, data); end; function CheckOutElementDomNode(ownerDocument: PHtmlDocDomNode; const namespaceURI, qualifiedName: WideString; withNS: Boolean): PHtmlElementDomNode; begin Result := System.New(PHtmlElementDomNode); FillChar(Result^, SizeOf(THtmlElementDomNode), 0); DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_ELEMENT, ownerDocument, namespaceURI, qualifiedName, withNS); Result.BaseDomNode.Attributes := TNamedNodeMap.Create(Result); end; function CheckOutDocTypeDomNode(ownerDocument: PHtmlDocDomNode; const name, publicId, systemId: WideString): PHtmlDocTypeDomNode; begin Result := System.New(PHtmlDocTypeDomNode); FillChar(Result^, SizeOf(THtmlDocTypeDomNode), 0); DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_DOCUMENT_TYPE, ownerDocument, '', name, false); Result.PublicID := publicId; Result.SystemID := systemId; end; function CheckOutDocDomNode(doctype: PHtmlDocTypeDomNode): PHtmlDocDomNode; begin Result := System.New(PHtmlDocDomNode); FillChar(Result^, SizeOf(THtmlDocDomNode), 0); DomNodeInitialize(PHtmlDomNode(Result), HTMLDOM_NODE_DOCUMENT, Result, '', '', false); if nil <> doctype then begin Result.DocTypeDomNode := doctype; end; if (nil <> Result.DocTypeDomNode) then Result.DocTypeDomNode.BaseDomNode.OwnerDocument := Result; Result.NamespaceURIList := TNamespaceURIList.Create; Result.SearchNodeLists := TList.Create; end; function AttrGetLength(AttribNode: PHtmlAttribDomNode): Integer; var Node: PHtmlDomNode; I: Integer; begin Result := 0; for I := 0 to AttribNode.childNodes.length - 1 do begin Node := AttribNode.childNodes.item(I); if Node.NodeType = HTMLDOM_NODE_TEXT then Inc(Result, CharacterDataNodeGetLength(Node)) else if Node.NodeType = HTMLDOM_NODE_ENTITY_REFERENCE then Inc(Result) end end; function NodeGetValue(AHtmlDomNode: PHtmlDomNode): WideString; var Node: PHtmlDomNode; Len, Pos, I, J: Integer; begin Result := ''; if nil = AHtmlDomNode then exit; if HTMLDOM_NODE_ATTRIBUTE = AHtmlDomNode.NodeType then begin Len := AttrGetLength(PHtmlAttribDomNode(AHtmlDomNode)); SetLength(Result, Len); Pos := 0; for I := 0 to AHtmlDomNode.childNodes.length - 1 do begin Node := AHtmlDomNode.childNodes.item(I); if Node.NodeType = HTMLDOM_NODE_TEXT then begin for J := 1 to CharacterDataNodeGetLength(Node) do begin Inc(Pos); Result[Pos] := Node.NodeValue[J] end end else if Node.NodeType = HTMLDOM_NODE_ENTITY_REFERENCE then begin Inc(Pos); Result[Pos] := GetEntValue(HtmlDomNodeGetName(Node)) end end end else begin Result := AHtmlDomNode.NodeValue; end; end; function HtmlParserGetMainElement(AHtmlParser: PHtmlParser; const tagName: WideString): PHtmlElementDomNode; var child: PHtmlDomNode; I: Integer; tmpElement: PHtmlElementDomNode; begin tmpElement := HtmlDocGetDocumentElement(AHtmlParser.HtmlDocument); if tmpElement = nil then begin tmpElement := CheckOutElementDomNode(AHtmlParser.HtmlDocument, '', htmlTagName, false); HtmlDomNodeappendChild(PHtmlDomNode(AHtmlParser.HtmlDocument), PHtmlDomNode(tmpElement)); tmpElement := HtmlDocGetDocumentElement(AHtmlParser.HtmlDocument); end; for I := 0 to tmpElement.BaseDomNode.childNodes.length - 1 do begin child := tmpElement.BaseDomNode.childNodes.item(I); if (child.NodeType = HTMLDOM_NODE_ELEMENT) and (HtmlDomNodeGetName(child) = tagName) then begin Result := PHtmlElementDomNode(child); Exit end end; Result := CheckOutElementDomNode(AHtmlParser.HtmlDocument, '', tagName, false); HtmlDomNodeappendChild(PHtmlDomNode(tmpElement), PHtmlDomNode(Result)); end; function HtmlParserFindParentElement(AHtmlParser: PHtmlParser; tagList: THtmlTagSet): PHtmlElementDomNode; var Node: PHtmlDomNode; HtmlTag: PHtmlTag; begin Node := AHtmlParser.CurrentNode; while Node.NodeType = HTMLDOM_NODE_ELEMENT do begin HtmlTag := HtmlTagList.GetTagByName(HtmlDomNodeGetName(Node)); if HtmlTag.Number in tagList then begin Result := PHtmlElementDomNode(Node); Exit end; Node := NodeGetParentDomNode(Node); if nil = node then Break; end; Result := nil end; function HtmlParserFindDefParent(AHtmlParser: PHtmlParser): PHtmlElementDomNode; var tmpElement: PHtmlElementDomNode; begin if AHtmlParser.CurrentTag.Number in [HEAD_TAG, BODY_TAG] then begin tmpElement := CheckOutElementDomNode(AHtmlParser.HtmlDocument, '', htmlTagName, false); Result := PHtmlElementDomNode(HtmlDomNodeappendChild(PHtmlDomNode(AHtmlParser.HtmlDocument), PHtmlDomNode(tmpElement))); end else if AHtmlParser.CurrentTag.Number in HeadTags then begin Result := HtmlParserGetMainElement(AHtmlParser, headTagName) end else begin Result := HtmlParserGetMainElement(AHtmlParser, bodyTagName) end; end; function HtmlParserFindTableParent(AHtmlParser: PHtmlParser): PHtmlElementDomNode; var Node: PHtmlDomNode; HtmlTag: PHtmlTag; begin Node := AHtmlParser.CurrentNode; while Node.NodeType = HTMLDOM_NODE_ELEMENT do begin HtmlTag := HtmlTagList.GetTagByName(HtmlDomNodeGetName(Node)); if (HtmlTag.Number = TD_TAG) or (HtmlTag.Number in BlockTags) then begin Result := PHtmlElementDomNode(Node); Exit end; Node := NodeGetParentDomNode(Node); if nil = node then Break; end; Result := HtmlParserGetMainElement(AHtmlParser, bodyTagName) end; function HtmlParserFindParent(AHtmlParser: PHtmlParser): PHtmlElementDomNode; begin if (AHtmlParser.CurrentTag.Number = P_TAG) or (AHtmlParser.CurrentTag.Number in BlockTags) then Result := HtmlParserFindParentElement(AHtmlParser, BlockParentTags) else if AHtmlParser.CurrentTag.Number = LI_TAG then Result := HtmlParserFindParentElement(AHtmlParser, ListItemParentTags) else if AHtmlParser.CurrentTag.Number in [DD_TAG, DT_TAG] then Result := HtmlParserFindParentElement(AHtmlParser, DefItemParentTags) else if AHtmlParser.CurrentTag.Number in [TD_TAG, TH_TAG] then Result := HtmlParserFindParentElement(AHtmlParser, CellParentTags) else if AHtmlParser.CurrentTag.Number = TR_TAG then Result := HtmlParserFindParentElement(AHtmlParser, RowParentTags) else if AHtmlParser.CurrentTag.Number = COL_TAG then Result := HtmlParserFindParentElement(AHtmlParser, ColParentTags) else if AHtmlParser.CurrentTag.Number in [COLGROUP_TAG, THEAD_TAG, TFOOT_TAG, TBODY_TAG] then Result := HtmlParserFindParentElement(AHtmlParser, TableSectionParentTags) else if AHtmlParser.CurrentTag.Number = TABLE_TAG then Result := HtmlParserFindTableParent(AHtmlParser) else if AHtmlParser.CurrentTag.Number = OPTION_TAG then Result := HtmlParserFindParentElement(AHtmlParser, OptionParentTags) else if AHtmlParser.CurrentTag.Number in [HEAD_TAG, BODY_TAG] then begin Result := PHtmlElementDomNode(HtmlDocGetDocumentElement(AHtmlParser.HtmlDocument)); end else begin Result := nil; end; if Result = nil then Result := HtmlParserFindDefParent(AHtmlParser) end; function HtmlReaderGetNodeName(AHtmlReader: PHtmlReader): WideString; begin if AHtmlReader.Prefix <> '' then Result := AHtmlReader.Prefix + ':' + AHtmlReader.LocalName else Result := AHtmlReader.LocalName end; function HtmlParserFindThisElement(AHtmlParser: PHtmlParser): PHtmlElementDomNode; var Node: PHtmlDomNode; begin Node := AHtmlParser.CurrentNode; while Node.NodeType = HTMLDOM_NODE_ELEMENT do begin Result := PHtmlElementDomNode(Node); if HtmlDomNodeGetName(PHtmlDomNode(Result)) = HtmlReaderGetNodeName(AHtmlParser.HtmlReader) then Exit; Node := NodeGetParentDomNode(Node); if nil = node then Break; end; Result := nil end; function AttrGetOwnerElement(AttribNode: PHtmlAttribDomNode): PHtmlElementDomNode; begin if nil = AttribNode.ParentDomNode then begin Result := nil; end else begin Result := PHtmlElementDomNode(AttribNode.ParentDomNode); end; end; function ElementsetAttributeNode(AElement: PHtmlElementDomNode; newAttr: PHtmlAttribDomNode): PHtmlAttribDomNode; begin if (nil <> AttrGetOwnerElement(PHtmlAttribDomNode(newAttr))) then raise DomException.Create(ERR_INUSE_ATTRIBUTE); Result := PHtmlAttribDomNode(AElement.BaseDomNode.attributes.setNamedItem(newAttr)); if (nil <> Result) then Result.ParentDomNode := nil; newAttr.ParentDomNode := PHtmlDomNode(AElement); end; procedure HtmlParserProcessAttributeStart(AHtmlReader: PHtmlReader); var Attr: PHtmlDomNode; begin Attr := CheckOutHtmlDomNode(HTMLDOM_NODE_ATTRIBUTE, AHtmlReader.HtmlParser.HtmlDocument, '', HtmlReaderGetNodeName(AHtmlReader), false); ElementsetAttributeNode(PHtmlElementDomNode(AHtmlReader.HtmlParser.CurrentNode), PHtmlAttribDomNode(Attr)); AHtmlReader.HtmlParser.CurrentNode := Attr; end; procedure HtmlParserProcessAttributeEnd(AHtmlReader: PHtmlReader); begin AHtmlReader.HtmlParser.CurrentNode := PHtmlDomNode(AttrGetOwnerElement(PHtmlAttribDomNode(AHtmlReader.HtmlParser.CurrentNode))); end; procedure HtmlParserProcessCDataSection(AHtmlReader: PHtmlReader); var CDataSection: PHtmlDomNode; begin CDataSection := CheckOutTextDomNode(HTMLDOM_NODE_CDATA_SECTION, AHtmlReader.HtmlParser.HtmlDocument, AHtmlReader.HtmlParser.HtmlReader.nodeValue); HtmlDomNodeappendChild(AHtmlReader.HtmlParser.CurrentNode, CDataSection); end; procedure HtmlParserProcessComment(AHtmlReader: PHtmlReader); var Comment: PHtmlDomNode; begin Comment := CheckOutTextDomNode(HTMLDOM_NODE_COMMENT, AHtmlReader.HtmlParser.HtmlDocument, AHtmlReader.HtmlParser.HtmlReader.nodeValue); HtmlDomNodeappendChild(AHtmlReader.HtmlParser.CurrentNode, Comment); end; procedure HtmlDocSetDocType(ADocument: PHtmlDocDomNode; value: PHtmlDocTypeDomNode{TDocumentTypeObj}); begin if (nil <> ADocument.DocTypeDomNode) then begin HtmlDomNodeFree(PHtmlDomNode(ADocument.DocTypeDomNode)); end; ADocument.DocTypeDomNode := value; end; function createDocumentType(const qualifiedName, publicId, systemId: WideString): PHtmlDocTypeDomNode; begin Result := CheckOutDocTypeDomNode(nil, qualifiedName, publicId, systemId); end; procedure HtmlParserProcessDocType(AHtmlReader: PHtmlReader); var tmpDocType: PHtmlDocTypeDomNode; begin //with fHtmlParserData.HtmlReader do tmpDocType := createDocumentType( HtmlReaderGetNodeName(AHtmlReader.HtmlParser.HtmlReader), AHtmlReader.HtmlParser.HtmlReader.publicID, AHtmlReader.HtmlParser.HtmlReader.systemID); HtmlDocSetdocType(AHtmlReader.HtmlParser.HtmlDocument, tmpDocType); end; procedure HtmlParserProcessElementEnd(AHtmlReader: PHtmlReader); begin if AHtmlReader.HtmlParser.HtmlReader.isEmptyElement or (AHtmlReader.HtmlParser.CurrentTag.Number in EmptyTags) then AHtmlReader.HtmlParser.CurrentNode := NodeGetParentDomNode(AHtmlReader.HtmlParser.CurrentNode); AHtmlReader.HtmlParser.CurrentTag := nil end; procedure HtmlParserProcessElementStart(AHtmlReader: PHtmlReader); var Element: PHtmlElementDomNode; Parent: PHtmlDomNode; begin AHtmlReader.HtmlParser.CurrentTag := HtmlTagList.GetTagByName(HtmlReaderGetNodeName(AHtmlReader.HtmlParser.HtmlReader)); if AHtmlReader.HtmlParser.CurrentTag.Number in NeedFindParentTags + BlockTags then begin Parent := PHtmlDomNode(HtmlParserFindParent(AHtmlReader.HtmlParser)); if (nil = Parent) then raise DomException.Create(ERR_HIERARCHY_REQUEST); AHtmlReader.HtmlParser.CurrentNode := Parent; end; Element := CheckOutElementDomNode(AHtmlReader.HtmlParser.HtmlDocument, '', HtmlReaderGetNodeName(AHtmlReader.HtmlParser.HtmlReader), false); HtmlDomNodeappendChild(AHtmlReader.HtmlParser.CurrentNode, PHtmlDomNode(Element)); AHtmlReader.HtmlParser.CurrentNode := PHtmlDomNode(Element); end; procedure HtmlParserProcessEndElement(AHtmlReader: PHtmlReader); var Element: PHtmlElementDomNode; begin Element := HtmlParserFindThisElement(AHtmlReader.HtmlParser); if (nil <> Element) then AHtmlReader.HtmlParser.CurrentNode := NodeGetParentDomNode(PHtmlDomNode(Element)); { else if IsBlockTagName(FHtmlReader.nodeName) then raise DomException.Create(HIERARCHY_REQUEST_ERR)} end; procedure HtmlParserProcessEntityReference(AHtmlReader: PHtmlReader); var EntityReference: PHtmlDomNode; begin EntityReference := CheckOutEntityReferenceNode( AHtmlReader.HtmlParser.HtmlDocument, HtmlReaderGetNodeName(AHtmlReader)); HtmlDomNodeappendChild(AHtmlReader.HtmlParser.CurrentNode, EntityReference); end; procedure HtmlParserProcessTextNode(AHtmlReader: PHtmlReader); begin HtmlDomNodeappendChild(AHtmlReader.HtmlParser.CurrentNode, CheckOutTextDomNode(HTMLDOM_NODE_TEXT, AHtmlReader.HtmlParser.HtmlDocument, AHtmlReader.nodeValue)); end; function HtmlParserparseString(const htmlStr: WideString): PHtmlDocDomNode; overload; var tmpHtmlParser: PHtmlParser; begin tmpHtmlParser := CheckoutHtmlParser; try Result := HtmlParserparseString(tmpHtmlParser, htmlStr); finally CheckInHtmlParser(tmpHtmlParser); end; end; procedure HtmlReaderSetHtmlStr(AHtmlReader: PHtmlReader; const Value: WideString); begin AHtmlReader.HtmlStr := Value; AHtmlReader.Position := 1 end; function createEmptyDocument(doctype: PHtmlDocTypeDomNode): PHtmlDocDomNode; begin Result := nil; if (nil <> doctype) and (nil <> doctype.BaseDomNode.ownerDocument) then begin // raise DomException.Create(ERR_WRONG_DOCUMENT); end; Result := CheckOutDocDomNode(doctype); end; function DecValue(const Digit: WideChar): Word; begin Result := Ord(Digit) - Ord('0') end; function HexValue(const HexChar: WideChar): Word; var C: Char; begin if Ord(HexChar) in decDigit then Result := Ord(HexChar) - Ord('0') else begin C := UpCase(Chr(Ord(HexChar))); Result := Ord(C) - Ord('A') end end; function CheckOutHtmlReader: PHtmlReader; begin Result := System.New(PHtmlReader); FillChar(Result^, SizeOf(THtmlReader), 0); //fHtmlReaderData.HtmlStr := fHtmlReaderData.HtmlStr; Result.Position := 1 end; function HtmlReaderGetToken(AHtmlReader: PHtmlReader; Delimiters: TDelimiters): WideString; var Start: Integer; begin Start := AHtmlReader.Position; while (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and not (Ord(AHtmlReader.HtmlStr[AHtmlReader.Position]) in Delimiters) do Inc(AHtmlReader.Position); Result := Copy(AHtmlReader.HtmlStr, Start, AHtmlReader.Position - Start) end; function HtmlReaderIsAttrTextChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; if AHtmlReader.State = rsInQuotedValue then Result := (Ord(WC) <> AHtmlReader.Quotation) and (Ord(WC) <> startEntity) else Result := not (Ord(WC) in notAttrText) end; function HtmlReaderIsDigit(AHtmlReader: PHtmlReader; HexBase: Boolean): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) in decDigit; if not Result and HexBase then Result := Ord(WC) in hexDigit end; function HtmlReaderIsEndEntityChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = endEntity end; function HtmlReaderIsEntityChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := not (Ord(WC) in notEntity) end; function HtmlReaderIsEqualChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = equalChar end; function HtmlReaderIsHexEntityChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) in hexEntity end; function HtmlReaderIsNumericEntity(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = numericEntity end; function HtmlReaderIsQuotation(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; if AHtmlReader.Quotation = 0 then Result := Ord(WC) in quotation else Result := Ord(WC) = AHtmlReader.Quotation end; function HtmlReaderIsSlashChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = slashChar end; function HtmlReaderIsSpecialTagChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = specialTagChar end; function HtmlReaderIsStartEntityChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = startEntity end; function HtmlReaderIsStartMarkupChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) in startMarkup end; function HtmlReaderIsStartTagChar(AHtmlReader: PHtmlReader): Boolean; var WC: WideChar; begin WC := AHtmlReader.HtmlStr[AHtmlReader.Position]; Result := Ord(WC) = startTagChar end; function HtmlReaderMatch(AHtmlReader: PHtmlReader; const Signature: WideString; IgnoreCase: Boolean): Boolean; var I, J: Integer; W1, W2: WideChar; begin Result := false; for I := 1 to Length(Signature) do begin J := AHtmlReader.Position + I - 1; if (J < 1) or (J > Length(AHtmlReader.HtmlStr)) then Exit; W1 := Signature[I]; W2 := AHtmlReader.HtmlStr[J]; if (W1 <> W2) and (not IgnoreCase or (UpperCase(W1) <> UpperCase(W2))) then Exit end; Result := true end; procedure HtmlReaderSkipWhiteSpaces(AHtmlReader: PHtmlReader); begin while (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and (Ord(AHtmlReader.HtmlStr[AHtmlReader.Position]) in whiteSpace) do Inc(AHtmlReader.Position) end; procedure HtmlReaderSetNodeName(AHtmlReader: PHtmlReader; Value: WideString); var I: Integer; begin I := Pos(':', Value); if I > 0 then begin AHtmlReader.Prefix := Copy(Value, 1, I - 1); AHtmlReader.LocalName := Copy(Value, I + 1, Length(Value) - I) end else begin AHtmlReader.Prefix := ''; AHtmlReader.LocalName := Value end end; procedure HtmlReaderFireEvent(AHtmlReader: PHtmlReader; Event: THtmlReaderEvent); begin if Assigned(Event) then Event(AHtmlReader) end; function HtmlReaderReadAttrNode(AHtmlReader: PHtmlReader): Boolean; var AttrName: WideString; begin Result := false; HtmlReaderSkipWhiteSpaces(AHtmlReader); AttrName := LowerCase(HtmlReaderGetToken(AHtmlReader, attrNameDelimiter)); if AttrName = '' then Exit; HtmlReaderSetNodeName(AHtmlReader, AttrName); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnAttributeStart); AHtmlReader.State := rsBeforeValue; AHtmlReader.Quotation := 0; Result := true end; function HtmlReaderReadAttrTextNode(AHtmlReader: PHtmlReader): Boolean; var Start: Integer; begin Result := false; Start := AHtmlReader.Position; while (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and HtmlReaderIsAttrTextChar(AHtmlReader) do Inc(AHtmlReader.Position); if AHtmlReader.Position = Start then Exit; AHtmlReader.NodeType := HTMLDOM_NODE_TEXT; AHtmlReader.NodeValue:= Copy(AHtmlReader.HtmlStr, Start, AHtmlReader.Position - Start); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnTextNode); Result := true end; function HtmlReaderSkipTo(AHtmlReader: PHtmlReader; const Signature: WideString): Boolean; begin while AHtmlReader.Position <= Length(AHtmlReader.HtmlStr) do begin if HtmlReaderMatch(AHtmlReader, Signature, false) then begin Inc(AHtmlReader.Position, Length(Signature)); Result := true; Exit end; Inc(AHtmlReader.Position) end; Result := false end; function HtmlReaderReadCharacterData(AHtmlReader: PHtmlReader): Boolean; var StartPos: Integer; begin Inc(AHtmlReader.Position, Length(CDataStartStr)); StartPos := AHtmlReader.Position; Result := HtmlReaderSkipTo(AHtmlReader, CDataEndStr); if Result then begin AHtmlReader.NodeType := HTMLDOM_NODE_CDATA_SECTION; AHtmlReader.NodeValue := Copy(AHtmlReader.HtmlStr, StartPos, AHtmlReader.Position - StartPos - Length(CDataEndStr)); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnCDataSection) end end; function HtmlReaderReadComment(AHtmlReader: PHtmlReader): Boolean; var StartPos: Integer; begin Inc(AHtmlReader.Position, Length(CommentStartStr)); StartPos := AHtmlReader.Position; Result := HtmlReaderSkipTo(AHtmlReader, CommentEndStr); if Result then begin AHtmlReader.NodeType := HTMLDOM_NODE_COMMENT; AHtmlReader.NodeValue := Copy(AHtmlReader.HtmlStr, StartPos, AHtmlReader.Position - StartPos - Length(CommentEndStr)); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnComment) end end; function HtmlReaderReadQuotedValue(AHtmlReader: PHtmlReader; var Value: WideString): Boolean; var QuotedChar: WideChar; Start: Integer; begin QuotedChar := AHtmlReader.HtmlStr[AHtmlReader.Position]; Inc(AHtmlReader.Position); Start := AHtmlReader.Position; Result := HtmlReaderSkipTo(AHtmlReader, QuotedChar); if Result then Value := Copy(AHtmlReader.HtmlStr, Start, AHtmlReader.Position - Start) end; function HtmlReaderReadDocumentType(AHtmlReader: PHtmlReader): Boolean; var Name: WideString; begin Result := false; Inc(AHtmlReader.Position, Length(DocTypeStartStr)); HtmlReaderSkipWhiteSpaces(AHtmlReader); Name := HtmlReaderGetToken(AHtmlReader, tagNameDelimiter); if Name = '' then Exit; HtmlReaderSetNodeName(AHtmlReader, Name); HtmlReaderSkipWhiteSpaces(AHtmlReader); HtmlReaderGetToken(AHtmlReader, tagNameDelimiter); HtmlReaderSkipWhiteSpaces(AHtmlReader); if not HtmlReaderReadQuotedValue(AHtmlReader, AHtmlReader.PublicID) then Exit; HtmlReaderSkipWhiteSpaces(AHtmlReader); if AHtmlReader.HtmlStr[AHtmlReader.Position] = '"' then begin if not HtmlReaderReadQuotedValue(AHtmlReader, AHtmlReader.SystemID) then Exit end; Result := HtmlReaderSkipTo(AHtmlReader, DocTypeEndStr) end; function HtmlReaderReadElementNode(AHtmlReader: PHtmlReader): Boolean; var TagName: WideString; begin Result := false; if AHtmlReader.Position < Length(AHtmlReader.HtmlStr) then begin TagName := LowerCase(HtmlReaderGetToken(AHtmlReader, tagNameDelimiter)); if TagName = '' then Exit; AHtmlReader.NodeType := HTMLDOM_NODE_ELEMENT; HtmlReaderSetNodeName(AHtmlReader, TagName); AHtmlReader.State := rsBeforeAttr; HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnElementStart); Result := true end end; function HtmlReaderReadEndElementNode(AHtmlReader: PHtmlReader): Boolean; var TagName: WideString; begin Result := false; Inc(AHtmlReader.Position); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; TagName := LowerCase(HtmlReaderGetToken(AHtmlReader, tagNameDelimiter)); if TagName = '' then Exit; Result := HtmlReaderSkipTo(AHtmlReader, WideChar(endTagChar)); if Result then begin AHtmlReader.NodeType := HTMLDOM_NODE_END_ELEMENT; HtmlReaderSetNodeName(AHtmlReader, TagName); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnEndElement); Result := true end end; function HtmlReaderReadNumericEntityNode(AHtmlReader: PHtmlReader): Boolean; var Value: Word; HexBase: Boolean; begin Result := false; if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; HexBase := HtmlReaderIsHexEntityChar(AHtmlReader); if HexBase then Inc(AHtmlReader.Position); Value := 0; while (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and HtmlReaderIsDigit(AHtmlReader, HexBase) do begin try if HexBase then Value := Value * 16 + HexValue(AHtmlReader.HtmlStr[AHtmlReader.Position]) else Value := Value * 10 + DecValue(AHtmlReader.HtmlStr[AHtmlReader.Position]) except Exit end; Inc(AHtmlReader.Position) end; if (AHtmlReader.Position > Length(AHtmlReader.HtmlStr)) or not HtmlReaderIsEndEntityChar(AHtmlReader) then Exit; Inc(AHtmlReader.Position); AHtmlReader.NodeType := HTMLDOM_NODE_TEXT; AHtmlReader.NodeValue := WideChar(Value); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnTextNode); Result := true end; function HtmlReaderReadNamedEntityNode(AHtmlReader: PHtmlReader): Boolean; var Start: Integer; begin Result := false; if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; Start := AHtmlReader.Position; while (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and HtmlReaderIsEntityChar(AHtmlReader) do Inc(AHtmlReader.Position); if (AHtmlReader.Position > Length(AHtmlReader.HtmlStr)) or not HtmlReaderIsEndEntityChar(AHtmlReader) then Exit; AHtmlReader.NodeType := HTMLDOM_NODE_ENTITY_REFERENCE; HtmlReaderSetNodeName(AHtmlReader, Copy(AHtmlReader.HtmlStr, Start, AHtmlReader.Position - Start)); Inc(AHtmlReader.Position); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnEntityReference); Result := true end; function HtmlReaderReadEntityNode(AHtmlReader: PHtmlReader): Boolean; var CurrPos: Integer; begin Result := false; CurrPos := AHtmlReader.Position; Inc(AHtmlReader.Position); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if HtmlReaderIsNumericEntity(AHtmlReader) then begin Inc(AHtmlReader.Position); Result := HtmlReaderReadNumericEntityNode(AHtmlReader) end else Result := HtmlReaderReadNamedEntityNode(AHtmlReader); if Result then begin AHtmlReader.NodeType := HTMLDOM_NODE_ENTITY_REFERENCE; //FireEvent(FOnEntityReference); VVV - remove, entity node is added in ReadXXXEntityNode end else AHtmlReader.Position := CurrPos end; function HtmlReaderIsStartCharacterData(AHtmlReader: PHtmlReader): Boolean; begin Result := HtmlReaderMatch(AHtmlReader, CDataStartStr, false) end; function HtmlReaderIsStartComment(AHtmlReader: PHtmlReader): Boolean; begin Result := HtmlReaderMatch(AHtmlReader, CommentStartStr, false) end; function HtmlReaderIsStartDocumentType(AHtmlReader: PHtmlReader): Boolean; begin Result := HtmlReaderMatch(AHtmlReader, DocTypeStartStr, true) end; function HtmlReaderReadSpecialNode(AHtmlReader: PHtmlReader): Boolean; begin Result := false; Inc(AHtmlReader.Position); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if HtmlReaderIsStartDocumentType(AHtmlReader) then Result := HtmlReaderReadDocumentType(AHtmlReader) else if HtmlReaderIsStartCharacterData(AHtmlReader) then Result := HtmlReaderReadCharacterData(AHtmlReader) else if HtmlReaderIsStartComment(AHtmlReader) then Result := HtmlReaderReadComment(AHtmlReader) end; function HtmlReaderReadTagNode(AHtmlReader: PHtmlReader): Boolean; var CurrPos: Integer; begin Result := false; CurrPos := AHtmlReader.Position; Inc(AHtmlReader.Position); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if HtmlReaderIsSlashChar(AHtmlReader) then Result := HtmlReaderReadEndElementNode(AHtmlReader) else if HtmlReaderIsSpecialTagChar(AHtmlReader) then Result := HtmlReaderReadSpecialNode(AHtmlReader) else Result := HtmlReaderReadElementNode(AHtmlReader); if not Result then AHtmlReader.Position := CurrPos end; function HtmlReaderReadValueNode(AHtmlReader: PHtmlReader): Boolean; begin Result := false; if AHtmlReader.State = rsBeforeValue then begin HtmlReaderSkipWhiteSpaces(AHtmlReader); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if not HtmlReaderIsEqualChar(AHtmlReader) then Exit; Inc(AHtmlReader.Position); HtmlReaderSkipWhiteSpaces(AHtmlReader); if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if HtmlReaderIsQuotation(AHtmlReader) then begin AHtmlReader.Quotation := Ord(AHtmlReader.HtmlStr[AHtmlReader.Position]); Inc(AHtmlReader.Position); AHtmlReader.State := rsInQuotedValue end else AHtmlReader.State := rsInValue end; if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; if HtmlReaderIsStartEntityChar(AHtmlReader) then begin Result := true; if HtmlReaderReadEntityNode(AHtmlReader) then Exit; Inc(AHtmlReader.Position); AHtmlReader.NodeType := HTMLDOM_NODE_ENTITY_REFERENCE; HtmlReaderSetNodeName(AHtmlReader, 'amp'); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnEntityReference) end else Result := HtmlReaderReadAttrTextNode(AHtmlReader) end; procedure HtmlReaderReadElementTail(AHtmlReader: PHtmlReader); begin HtmlReaderSkipWhiteSpaces(AHtmlReader); if (AHtmlReader.Position <= Length(AHtmlReader.HtmlStr)) and HtmlReaderIsSlashChar(AHtmlReader) then begin AHtmlReader.IsEmptyElement := true; Inc(AHtmlReader.Position) end; HtmlReaderSkipTo(AHtmlReader, WideChar(endTagChar)); AHtmlReader.NodeType := HTMLDOM_NODE_ELEMENT; HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnElementEnd) end; procedure HtmlReaderReadTextNode(AHtmlReader: PHtmlReader); var Start: Integer; begin Start := AHtmlReader.Position; repeat Inc(AHtmlReader.Position) until (AHtmlReader.Position > Length(AHtmlReader.HtmlStr)) or HtmlReaderIsStartMarkupChar(AHtmlReader); AHtmlReader.NodeType := HTMLDOM_NODE_TEXT; AHtmlReader.NodeValue:= Copy(AHtmlReader.HtmlStr, Start, AHtmlReader.Position - Start); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnTextNode) end; function HtmlReaderRead(AHtmlReader: PHtmlReader): Boolean; begin AHtmlReader.NodeType := HTMLDOM_NODE_NONE; AHtmlReader.Prefix := ''; AHtmlReader.LocalName := ''; AHtmlReader.NodeValue := ''; AHtmlReader.PublicID := ''; AHtmlReader.SystemID := ''; AHtmlReader.IsEmptyElement := false; Result := false; if AHtmlReader.Position > Length(AHtmlReader.HtmlStr) then Exit; Result := true; if AHtmlReader.State in [rsBeforeValue, rsInValue, rsInQuotedValue] then begin if HtmlReaderReadValueNode(AHtmlReader) then Exit; if AHtmlReader.State = rsInQuotedValue then Inc(AHtmlReader.Position); AHtmlReader.NodeType := HTMLDOM_NODE_ATTRIBUTE; HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnAttributeEnd); AHtmlReader.State := rsBeforeAttr end else if AHtmlReader.State = rsBeforeAttr then begin if HtmlReaderReadAttrNode(AHtmlReader) then Exit; HtmlReaderReadElementTail(AHtmlReader); AHtmlReader.State := rsInitial; end else if HtmlReaderIsStartTagChar(AHtmlReader) then begin if HtmlReaderReadTagNode(AHtmlReader) then Exit; Inc(AHtmlReader.Position); AHtmlReader.NodeType := HTMLDOM_NODE_ENTITY_REFERENCE; HtmlReaderSetNodeName(AHtmlReader, 'lt'); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnEntityReference); end else if HtmlReaderIsStartEntityChar(AHtmlReader) then begin if HtmlReaderReadEntityNode(AHtmlReader) then Exit; Inc(AHtmlReader.Position); AHtmlReader.NodeType := HTMLDOM_NODE_ENTITY_REFERENCE; HtmlReaderSetNodeName(AHtmlReader, 'amp'); HtmlReaderFireEvent(AHtmlReader, AHtmlReader.OnEntityReference) end else HtmlReaderReadTextNode(AHtmlReader) end; function HtmlParserparseString(AHtmlParser: PHtmlParser; const htmlStr: WideString): PHtmlDocDomNode; overload; begin HtmlReaderSetHtmlStr(AHtmlParser.HtmlReader, htmlStr); AHtmlParser.HtmlDocument := createEmptyDocument(nil); AHtmlParser.CurrentNode := PHtmlDomNode(AHtmlParser.HtmlDocument); try while HtmlReaderRead(AHtmlParser.HtmlReader) do; except // TODO: Add event ? end; Result := AHtmlParser.HtmlDocument; end; function CheckOutHtmlParser: PHtmlParser; begin Result := System.New(PHtmlParser); FillChar(Result^, SizeOf(THtmlParser), 0); Result.HtmlReader := CheckOutHtmlReader; Result.HtmlReader.HtmlParser := Result; Result.HtmlReader.OnAttributeEnd := HtmlParserProcessAttributeEnd; Result.HtmlReader.OnAttributeStart := HtmlParserProcessAttributeStart; Result.HtmlReader.OnCDataSection := HtmlParserProcessCDataSection; Result.HtmlReader.OnComment := HtmlParserProcessComment; Result.HtmlReader.OnDocType := HtmlParserProcessDocType; Result.HtmlReader.OnElementEnd := HtmlParserProcessElementEnd; Result.HtmlReader.OnElementStart := HtmlParserProcessElementStart; Result.HtmlReader.OnEndElement := HtmlParserProcessEndElement; Result.HtmlReader.OnEntityReference := HtmlParserProcessEntityReference; //OnNotation := ProcessNotation; //OnProcessingInstruction := ProcessProcessingInstruction; Result.HtmlReader.OnTextNode := HtmlParserProcessTextNode; end; procedure CheckInHtmlParser(var AHtmlParser: PHtmlParser); begin if nil <>AHtmlParser then begin if nil <> AHtmlParser.HtmlReader then begin AHtmlParser.HtmlReader.PublicID := ''; AHtmlParser.HtmlReader.SystemID := ''; AHtmlParser.HtmlReader.Prefix := ''; AHtmlParser.HtmlReader.LocalName := ''; AHtmlParser.HtmlReader.NodeValue := ''; AHtmlParser.HtmlReader.HtmlStr := ''; FreeMem(AHtmlParser.HtmlReader); AHtmlParser.HtmlReader := nil; end; FreeMem(AHtmlParser); AHtmlParser := nil; end; end; constructor TNodeList.Create(AOwnerNode: Pointer{TNode}); begin inherited Create; FOwnerNode := AOwnerNode; FList := TList.Create end; destructor TNodeList.Destroy; begin FList.Free; inherited Destroy end; function TNodeList.NodeListIndexOf(node: Pointer{TNode}): Integer; begin Result := FList.IndexOf(node) end; function TNodeList.GetLength: Integer; begin Result := FList.Count end; procedure TNodeList.NodeListInsert(I: Integer; Node: Pointer{TNode}); begin FList.Insert(I, Node) end; procedure TNodeList.NodeListDelete(I: Integer); begin FList.Delete(I) end; procedure TNodeList.NodeListAdd(node: Pointer{TNode}); begin FList.Add(node) end; procedure TNodeList.NodeListRemove(node: Pointer{TNode}); begin FList.Remove(node) end; function TNodeList.item(index: Integer): Pointer{TNode}; begin if (index >= 0) and (index < length) then Result := FList[index] else Result := nil end; procedure TNodeList.NodeListClear(WithItems: Boolean); var I: Integer; tmpDomNode: PHtmlDomNode; begin if WithItems then begin for I := length - 1 downto 0 do begin tmpDomNode := item(I); HtmlDomNodeFree(tmpDomNode); end; end; FList.Clear end; constructor TSearchNodeList.Create(AOwnerNode: Pointer{TNode}; const namespaceURI, name: WideString); begin inherited Create(AOwnerNode); FNamespaceParam := namespaceURI; FNameParam := name; Rebuild end; procedure HtmlDocRemoveSearchNodeList(ADocument: PHtmlDocDomNode; NodeList: TNodeList); begin ADocument.SearchNodeLists.Remove(NodeList) end; destructor TSearchNodeList.Destroy; begin if (nil <> ownerNode) then begin if (nil <> PHtmlDomNode(ownerNode).ownerDocument) then begin HtmlDocRemoveSearchNodeList(PHtmlDomNode(ownerNode).ownerDocument, Self); end; end; inherited Destroy end; function TSearchNodeList.GetLength: Integer; begin if not FSynchronized then Rebuild; Result := inherited GetLength end; function HtmlDomNodeGetNamespaceURI(AHtmlDomNode: PHtmlDomNode): WideString; begin Result := AHtmlDomNode.ownerDocument.namespaceURIList[AHtmlDomNode.NamespaceURI] end; function HtmlDomNodeGetLocalName(AHtmlDomNode: PHtmlDomNode): WideString; begin Result := AHtmlDomNode.NodeName; end; function TSearchNodeList.acceptNode(node: Pointer{TNode}): Boolean; begin Result := (PHtmlDomNode(Node).NodeType = HTMLDOM_NODE_ELEMENT) and ((FNamespaceParam = '*') or (FNamespaceParam = HtmlDomNodeGetNamespaceURI(node))) and ((FNameParam = '*') or (FNameParam = HtmlDomNodeGetLocalName(node))) end; procedure TSearchNodeList.TraverseTree(rootNode: Pointer{TNode}); var I: Integer; begin if (rootNode <> ownerNode) and acceptNode(rootNode) then NodeListAdd(rootNode); for I := 0 to PhtmlDomNode(rootNode).childNodes.length - 1 do TraverseTree(PhtmlDomNode(rootNode).childNodes.item(I)) end; procedure HtmlDocAddSearchNodeList(ADocument: PHtmlDocDomNode; NodeList: TNodeList); begin if ADocument.SearchNodeLists.IndexOf(NodeList) < 0 then ADocument.SearchNodeLists.Add(Nodelist) end; procedure TSearchNodeList.Rebuild; begin NodeListClear(false); if (nil <> ownerNode) and (nil <> PHtmlDomNode(ownerNode).ownerDocument) then begin TraverseTree(ownerNode); HtmlDocAddSearchNodeList(PHtmlDomNode(ownerNode).ownerDocument, Self) end; Fsynchronized := true end; procedure TSearchNodeList.Invalidate; begin FSynchronized := false end; function TSearchNodeList.item(index: Integer): Pointer{TNode}; begin if not FSynchronized then Rebuild; Result := inherited item(index) end; function TNamedNodeMap.getNamedItem(const name: WideString): Pointer{TNode}; var I: Integer; begin for I := 0 to length - 1 do begin Result := item(I); if HtmlDomNodeGetName(Result) = name then Exit end; Result := nil end; function TNamedNodeMap.setNamedItem(arg: Pointer{TNode}): Pointer{TNode}; var Attr: PHtmlAttribDomNode; tmpOwnerElement: PHtmlElementDomNode; begin if PHtmlDomNode(arg).ownerDocument <> PHtmlDomNode(ownerNode).ownerDocument then raise DomException(ERR_WRONG_DOCUMENT); if PHtmlDomNode(arg).NodeType = HTMLDOM_NODE_ATTRIBUTE then begin Attr := PHtmlAttribDomNode(arg); tmpOwnerElement := AttrGetOwnerElement(PHtmlAttribDomNode(Attr)); if (nil <> tmpOwnerElement) and (tmpOwnerElement <> ownerNode) then raise DomException(ERR_INUSE_ATTRIBUTE) end; Result := getNamedItem(HtmlDomNodeGetName(arg)); if (nil <> Result) then NodeListRemove(Result); NodeListAdd(arg) end; function TNamedNodeMap.removeNamedItem(const name: WideString): Pointer{TNode}; var Node: PHtmlDomNode; begin Node := getNamedItem(name); if Node = nil then raise DomException.Create(ERR_NOT_FOUND); NodeListRemove(Node); Result := Node end; function TNamedNodeMap.getNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode}; var I: Integer; begin for I := 0 to length - 1 do begin Result := item(I); if (HtmlDomNodeGetLocalName(Result) = localName) and (HtmlDomNodeGetNamespaceURI(Result) = namespaceURI) then Exit end; Result := nil end; function TNamedNodeMap.setNamedItemNS(arg: Pointer{TNode}): Pointer{TNode}; var Attr: PHtmlAttribDomNode; tmpOwnerElement: PHtmlElementDomNode; begin if PHtmlDomNode(arg).ownerDocument <> PHtmlDomNode(ownerNode).ownerDocument then raise DomException(ERR_WRONG_DOCUMENT); if PHtmlDomNode(arg).NodeType = HTMLDOM_NODE_ATTRIBUTE then begin Attr := arg; tmpOwnerElement := AttrGetOwnerElement(PHtmlAttribDomNode(Attr)); if (nil <> tmpOwnerElement) and (tmpOwnerElement <> ownerNode) then raise DomException(ERR_INUSE_ATTRIBUTE) end; Result := getNamedItemNS(HtmlDomNodeGetNamespaceURI(arg), HtmlDomNodeGetLocalName(arg)); if (nil <> Result) then NodeListRemove(Result); NodeListAdd(arg) end; function TNamedNodeMap.removeNamedItemNS(const namespaceURI, localName: WideString): Pointer{TNode}; var Node: PHtmlDomNode; begin Node := getNamedItemNS(namespaceURI, localName); if Node = nil then raise DomException.Create(ERR_NOT_FOUND); NodeListRemove(Node); Result := Node end; constructor TNamespaceURIList.Create; begin inherited Create; FList := TWStringList.Create; FList.Add('') end; destructor TNamespaceURIList.Destroy; begin FList.Free; inherited Destroy end; procedure TNamespaceURIList.Clear; begin FList.Clear end; function TNamespaceURIList.GetItem(I: Integer): WideString; begin Result := FList[I] end; function TNamespaceURIList.Add(const NamespaceURI: WideString): Integer; var I: Integer; begin for I := 0 to FList.Count - 1 do if FList[I] = NamespaceURI then begin Result := I; Exit end; Result := FList.Add(NamespaceURI) end; const EntCount = 252; type PEntity = ^TEntity; TEntity = record Name: String; Code: Word end; TEntities = array[0..EntCount - 1] of TEntity; const EntTab: TEntities = ( (Name: 'nbsp'; Code: 160), (Name: 'iexcl'; Code: 161), (Name: 'cent'; Code: 162), (Name: 'pound'; Code: 163), (Name: 'curren'; Code: 164), (Name: 'yen'; Code: 165), (Name: 'brvbar'; Code: 166), (Name: 'sect'; Code: 167), (Name: 'uml'; Code: 168), (Name: 'copy'; Code: 169), (Name: 'ordf'; Code: 170), (Name: 'laquo'; Code: 171), (Name: 'not'; Code: 172), (Name: 'shy'; Code: 173), (Name: 'reg'; Code: 174), (Name: 'macr'; Code: 175), (Name: 'deg'; Code: 176), (Name: 'plusmn'; Code: 177), (Name: 'sup2'; Code: 178), (Name: 'sup3'; Code: 179), (Name: 'acute'; Code: 180), (Name: 'micro'; Code: 181), (Name: 'para'; Code: 182), (Name: 'middot'; Code: 183), (Name: 'cedil'; Code: 184), (Name: 'sup1'; Code: 185), (Name: 'ordm'; Code: 186), (Name: 'raquo'; Code: 187), (Name: 'frac14'; Code: 188), (Name: 'frac12'; Code: 189), (Name: 'frac34'; Code: 190), (Name: 'iquest'; Code: 191), (Name: 'Agrave'; Code: 192), (Name: 'Aacute'; Code: 193), (Name: 'Acirc'; Code: 194), (Name: 'Atilde'; Code: 195), (Name: 'Auml'; Code: 196), (Name: 'Aring'; Code: 197), (Name: 'AElig'; Code: 198), (Name: 'Ccedil'; Code: 199), (Name: 'Egrave'; Code: 200), (Name: 'Eacute'; Code: 201), (Name: 'Ecirc'; Code: 202), (Name: 'Euml'; Code: 203), (Name: 'Igrave'; Code: 204), (Name: 'Iacute'; Code: 205), (Name: 'Icirc'; Code: 206), (Name: 'Iuml'; Code: 207), (Name: 'ETH'; Code: 208), (Name: 'Ntilde'; Code: 209), (Name: 'Ograve'; Code: 210), (Name: 'Oacute'; Code: 211), (Name: 'Ocirc'; Code: 212), (Name: 'Otilde'; Code: 213), (Name: 'Ouml'; Code: 214), (Name: 'times'; Code: 215), (Name: 'Oslash'; Code: 216), (Name: 'Ugrave'; Code: 217), (Name: 'Uacute'; Code: 218), (Name: 'Ucirc'; Code: 219), (Name: 'Uuml'; Code: 220), (Name: 'Yacute'; Code: 221), (Name: 'THORN'; Code: 222), (Name: 'szlig'; Code: 223), (Name: 'agrave'; Code: 224), (Name: 'aacute'; Code: 225), (Name: 'acirc'; Code: 226), (Name: 'atilde'; Code: 227), (Name: 'auml'; Code: 228), (Name: 'aring'; Code: 229), (Name: 'aelig'; Code: 230), (Name: 'ccedil'; Code: 231), (Name: 'egrave'; Code: 232), (Name: 'eacute'; Code: 233), (Name: 'ecirc'; Code: 234), (Name: 'euml'; Code: 235), (Name: 'igrave'; Code: 236), (Name: 'iacute'; Code: 237), (Name: 'icirc'; Code: 238), (Name: 'iuml'; Code: 239), (Name: 'eth'; Code: 240), (Name: 'ntilde'; Code: 241), (Name: 'ograve'; Code: 242), (Name: 'oacute'; Code: 243), (Name: 'ocirc'; Code: 244), (Name: 'otilde'; Code: 245), (Name: 'ouml'; Code: 246), (Name: 'divide'; Code: 247), (Name: 'oslash'; Code: 248), (Name: 'ugrave'; Code: 249), (Name: 'uacute'; Code: 250), (Name: 'ucirc'; Code: 251), (Name: 'uuml'; Code: 252), (Name: 'yacute'; Code: 253), (Name: 'thorn'; Code: 254), (Name: 'yuml'; Code: 255), (Name: 'fnof'; Code: 402), (Name: 'Alpha'; Code: 913), (Name: 'Beta'; Code: 914), (Name: 'Gamma'; Code: 915), (Name: 'Delta'; Code: 916), (Name: 'Epsilon'; Code: 917), (Name: 'Zeta'; Code: 918), (Name: 'Eta'; Code: 919), (Name: 'Theta'; Code: 920), (Name: 'Iota'; Code: 921), (Name: 'Kappa'; Code: 922), (Name: 'Lambda'; Code: 923), (Name: 'Mu'; Code: 924), (Name: 'Nu'; Code: 925), (Name: 'Xi'; Code: 926), (Name: 'Omicron'; Code: 927), (Name: 'Pi'; Code: 928), (Name: 'Rho'; Code: 929), (Name: 'Sigma'; Code: 931), (Name: 'Tau'; Code: 932), (Name: 'Upsilon'; Code: 933), (Name: 'Phi'; Code: 934), (Name: 'Chi'; Code: 935), (Name: 'Psi'; Code: 936), (Name: 'Omega'; Code: 937), (Name: 'alpha'; Code: 945), (Name: 'beta'; Code: 946), (Name: 'gamma'; Code: 947), (Name: 'delta'; Code: 948), (Name: 'epsilon'; Code: 949), (Name: 'zeta'; Code: 950), (Name: 'eta'; Code: 951), (Name: 'theta'; Code: 952), (Name: 'iota'; Code: 953), (Name: 'kappa'; Code: 954), (Name: 'lambda'; Code: 955), (Name: 'mu'; Code: 956), (Name: 'nu'; Code: 957), (Name: 'xi'; Code: 958), (Name: 'omicron'; Code: 959), (Name: 'pi'; Code: 960), (Name: 'rho'; Code: 961), (Name: 'sigmaf'; Code: 962), (Name: 'sigma'; Code: 963), (Name: 'tau'; Code: 964), (Name: 'upsilon'; Code: 965), (Name: 'phi'; Code: 966), (Name: 'chi'; Code: 967), (Name: 'psi'; Code: 968), (Name: 'omega'; Code: 969), (Name: 'thetasym'; Code: 977), (Name: 'upsih'; Code: 978), (Name: 'piv'; Code: 982), (Name: 'bull'; Code: 8226), (Name: 'hellip'; Code: 8230), (Name: 'prime'; Code: 8242), (Name: 'Prime'; Code: 8243), (Name: 'oline'; Code: 8254), (Name: 'frasl'; Code: 8260), (Name: 'weierp'; Code: 8472), (Name: 'image'; Code: 8465), (Name: 'real'; Code: 8476), (Name: 'trade'; Code: 8482), (Name: 'alefsym'; Code: 8501), (Name: 'larr'; Code: 8592), (Name: 'uarr'; Code: 8593), (Name: 'rarr'; Code: 8594), (Name: 'darr'; Code: 8595), (Name: 'harr'; Code: 8596), (Name: 'crarr'; Code: 8629), (Name: 'lArr'; Code: 8656), (Name: 'uArr'; Code: 8657), (Name: 'rArr'; Code: 8658), (Name: 'dArr'; Code: 8659), (Name: 'hArr'; Code: 8660), (Name: 'forall'; Code: 8704), (Name: 'part'; Code: 8706), (Name: 'exist'; Code: 8707), (Name: 'empty'; Code: 8709), (Name: 'nabla'; Code: 8711), (Name: 'isin'; Code: 8712), (Name: 'notin'; Code: 8713), (Name: 'ni'; Code: 8715), (Name: 'prod'; Code: 8719), (Name: 'sum'; Code: 8721), (Name: 'minus'; Code: 8722), (Name: 'lowast'; Code: 8727), (Name: 'radic'; Code: 8730), (Name: 'prop'; Code: 8733), (Name: 'infin'; Code: 8734), (Name: 'ang'; Code: 8736), (Name: 'and'; Code: 8743), (Name: 'or'; Code: 8744), (Name: 'cap'; Code: 8745), (Name: 'cup'; Code: 8746), (Name: 'int'; Code: 8747), (Name: 'there4'; Code: 8756), (Name: 'sim'; Code: 8764), (Name: 'cong'; Code: 8773), (Name: 'asymp'; Code: 8776), (Name: 'ne'; Code: 8800), (Name: 'equiv'; Code: 8801), (Name: 'le'; Code: 8804), (Name: 'ge'; Code: 8805), (Name: 'sub'; Code: 8834), (Name: 'sup'; Code: 8835), (Name: 'nsub'; Code: 8836), (Name: 'sube'; Code: 8838), (Name: 'supe'; Code: 8839), (Name: 'oplus'; Code: 8853), (Name: 'otimes'; Code: 8855), (Name: 'perp'; Code: 8869), (Name: 'sdot'; Code: 8901), (Name: 'lceil'; Code: 8968), (Name: 'rceil'; Code: 8969), (Name: 'lfloor'; Code: 8970), (Name: 'rfloor'; Code: 8971), (Name: 'lang'; Code: 9001), (Name: 'rang'; Code: 9002), (Name: 'loz'; Code: 9674), (Name: 'spades'; Code: 9824), (Name: 'clubs'; Code: 9827), (Name: 'hearts'; Code: 9829), (Name: 'diams'; Code: 9830), (Name: 'quot'; Code: 34), (Name: 'amp'; Code: 38), (Name: 'lt'; Code: 60), (Name: 'gt'; Code: 62), (Name: 'OElig'; Code: 338), (Name: 'oelig'; Code: 339), (Name: 'Scaron'; Code: 352), (Name: 'scaron'; Code: 353), (Name: 'Yuml'; Code: 376), (Name: 'circ'; Code: 710), (Name: 'tilde'; Code: 732), (Name: 'ensp'; Code: 8194), (Name: 'emsp'; Code: 8195), (Name: 'thinsp'; Code: 8201), (Name: 'zwnj'; Code: 8204), (Name: 'zwj'; Code: 8205), (Name: 'lrm'; Code: 8206), (Name: 'rlm'; Code: 8207), (Name: 'ndash'; Code: 8211), (Name: 'mdash'; Code: 8212), (Name: 'lsquo'; Code: 8216), (Name: 'rsquo'; Code: 8217), (Name: 'sbquo'; Code: 8218), (Name: 'ldquo'; Code: 8220), (Name: 'rdquo'; Code: 8221), (Name: 'bdquo'; Code: 8222), (Name: 'dagger'; Code: 8224), (Name: 'Dagger'; Code: 8225), (Name: 'permil'; Code: 8240), (Name: 'lsaquo'; Code: 8249), (Name: 'rsaquo'; Code: 8250), (Name: 'euro'; Code: 8364) ); function EntCompare(Ent1, Ent2: Pointer): Integer; begin Result := CompareStr(PEntity(Ent1)^.Name, PEntity(Ent2)^.Name) end; constructor TEntList.Create; var I: Integer; begin inherited Create; Capacity := EntCount; for I := 0 to EntCount - 1 do Add(@EntTab[I]); Sort(EntCompare) end; function TEntList.GetCode(const Name: String): Integer; var I, L, U, Cmp: Integer; begin L := 0; U := Count - 1; while L <= U do begin I := (L + U) div 2; Cmp := CompareStr(Name, PEntity(Items[I])^.Name); if Cmp = 0 then begin Result := PEntity(Items[I])^.Code; Exit end; if Cmp < 0 then U := I - 1 else L := I + 1 end; Result := 32 end; function GetEntName(Code: Word): String; var I: Integer; begin for I := 0 to EntCount - 1 do if EntTab[I].Code = Code then begin Result := EntTab[I].Name; Exit end; Result := '' end; constructor THtmlTagList.Create; begin inherited Create; FList := TList.Create; FList.Capacity := MAX_TAGS_COUNT; FList.Add(CheckOutHtmlTag('a', A_TAG, [], [])); FList.Add(CheckOutHtmlTag('abbr', ABBR_TAG, [], [])); FList.Add(CheckOutHtmlTag('acronym', ACRONYM_TAG, [], [])); FList.Add(CheckOutHtmlTag('address', ADDRESS_TAG, [], [])); FList.Add(CheckOutHtmlTag('applet', APPLET_TAG, [], [])); FList.Add(CheckOutHtmlTag('area', AREA_TAG, [], [])); FList.Add(CheckOutHtmlTag('b', B_TAG, [], [])); FList.Add(CheckOutHtmlTag('base', BASE_TAG, [], [])); FList.Add(CheckOutHtmlTag('basefont', BASEFONT_TAG, [], [])); FList.Add(CheckOutHtmlTag('bdo', BDO_TAG, [], [])); FList.Add(CheckOutHtmlTag('big', BIG_TAG, [], [])); FList.Add(CheckOutHtmlTag('blockquote', BLOCKQUOTE_TAG, [], [])); FList.Add(CheckOutHtmlTag('body', BODY_TAG, [], [])); FList.Add(CheckOutHtmlTag('br', BR_TAG, [], [])); FList.Add(CheckOutHtmlTag('button', BUTTON_TAG, [], [])); FList.Add(CheckOutHtmlTag('caption', CAPTION_TAG, [], [])); FList.Add(CheckOutHtmlTag('center', CENTER_TAG, [], [])); FList.Add(CheckOutHtmlTag('cite', CITE_TAG, [], [])); FList.Add(CheckOutHtmlTag('code', CODE_TAG, [], [])); FList.Add(CheckOutHtmlTag('col', COL_TAG, [], [])); FList.Add(CheckOutHtmlTag('colgroup', COLGROUP_TAG, [], [])); FList.Add(CheckOutHtmlTag('dd', DD_TAG, [], [])); FList.Add(CheckOutHtmlTag('del', DEL_TAG, [], [])); FList.Add(CheckOutHtmlTag('dfn', DFN_TAG, [], [])); FList.Add(CheckOutHtmlTag('dir', DIR_TAG, [], [])); FList.Add(CheckOutHtmlTag('div', DIV_TAG, [], [])); FList.Add(CheckOutHtmlTag('dl', DL_TAG, [], [])); FList.Add(CheckOutHtmlTag('dt', DT_TAG, [], [])); FList.Add(CheckOutHtmlTag('em', EM_TAG, [], [])); FList.Add(CheckOutHtmlTag('fieldset', FIELDSET_TAG, [], [])); FList.Add(CheckOutHtmlTag('font', FONT_TAG, [], [])); FList.Add(CheckOutHtmlTag('form', FORM_TAG, [], [])); FList.Add(CheckOutHtmlTag('frame', FRAME_TAG, [], [])); FList.Add(CheckOutHtmlTag('frameset', FRAMESET_TAG, [], [])); FList.Add(CheckOutHtmlTag('h1', H1_TAG, [], [])); FList.Add(CheckOutHtmlTag('h2', H2_TAG, [], [])); FList.Add(CheckOutHtmlTag('h3', H3_TAG, [], [])); FList.Add(CheckOutHtmlTag('h4', H4_TAG, [], [])); FList.Add(CheckOutHtmlTag('h5', H5_TAG, [], [])); FList.Add(CheckOutHtmlTag('h6', H6_TAG, [], [])); FList.Add(CheckOutHtmlTag('head', HEAD_TAG, [], [])); FList.Add(CheckOutHtmlTag('hr', HR_TAG, [], [])); FList.Add(CheckOutHtmlTag('html', HTML_TAG, [], [])); FList.Add(CheckOutHtmlTag('i', I_TAG, [], [])); FList.Add(CheckOutHtmlTag('iframe', IFRAME_TAG, [], [])); FList.Add(CheckOutHtmlTag('img', IMG_TAG, [], [])); FList.Add(CheckOutHtmlTag('input', INPUT_TAG, [], [])); FList.Add(CheckOutHtmlTag('ins', INS_TAG, [], [])); FList.Add(CheckOutHtmlTag('isindex', ISINDEX_TAG, [], [])); FList.Add(CheckOutHtmlTag('kbd', KBD_TAG, [], [])); FList.Add(CheckOutHtmlTag('label', LABEL_TAG, [], [])); FList.Add(CheckOutHtmlTag('legend', LEGEND_TAG, [], [])); FList.Add(CheckOutHtmlTag('li', LI_TAG, [], [])); FList.Add(CheckOutHtmlTag('link', LINK_TAG, [], [])); FList.Add(CheckOutHtmlTag('map', MAP_TAG, [], [])); FList.Add(CheckOutHtmlTag('menu', MENU_TAG, [], [])); FList.Add(CheckOutHtmlTag('meta', META_TAG, [], [])); FList.Add(CheckOutHtmlTag('noframes', NOFRAMES_TAG, [], [])); FList.Add(CheckOutHtmlTag('noscript', NOSCRIPT_TAG, [], [])); FList.Add(CheckOutHtmlTag('object', OBJECT_TAG, [], [])); FList.Add(CheckOutHtmlTag('ol', OL_TAG, [], [])); FList.Add(CheckOutHtmlTag('optgroup', OPTGROUP_TAG, [], [])); FList.Add(CheckOutHtmlTag('option', OPTION_TAG, [], [])); FList.Add(CheckOutHtmlTag('p', P_TAG, [], [])); FList.Add(CheckOutHtmlTag('param', PARAM_TAG, [], [])); FList.Add(CheckOutHtmlTag('pre', PRE_TAG, [], [])); FList.Add(CheckOutHtmlTag('q', Q_TAG, [], [])); FList.Add(CheckOutHtmlTag('s', S_TAG, [], [])); FList.Add(CheckOutHtmlTag('samp', SAMP_TAG, [], [])); FList.Add(CheckOutHtmlTag('script', SCRIPT_TAG, [], [])); FList.Add(CheckOutHtmlTag('select', SELECT_TAG, [], [])); FList.Add(CheckOutHtmlTag('small', SMALL_TAG, [], [])); FList.Add(CheckOutHtmlTag('span', SPAN_TAG, [], [])); FList.Add(CheckOutHtmlTag('strike', STRIKE_TAG, [], [])); FList.Add(CheckOutHtmlTag('strong', STRONG_TAG, [], [])); FList.Add(CheckOutHtmlTag('style', STYLE_TAG, [], [])); FList.Add(CheckOutHtmlTag('sub', SUB_TAG, [], [])); FList.Add(CheckOutHtmlTag('sup', SUP_TAG, [], [])); FList.Add(CheckOutHtmlTag('table', TABLE_TAG, [], [])); FList.Add(CheckOutHtmlTag('tbody', TBODY_TAG, [], [])); FList.Add(CheckOutHtmlTag('td', TD_TAG, [], [])); FList.Add(CheckOutHtmlTag('textarea', TEXTAREA_TAG, [], [])); FList.Add(CheckOutHtmlTag('tfoot', TFOOT_TAG, [], [])); FList.Add(CheckOutHtmlTag('th', TH_TAG, [], [])); FList.Add(CheckOutHtmlTag('thead', THEAD_TAG, [], [])); FList.Add(CheckOutHtmlTag('title', TITLE_TAG, [], [])); FList.Add(CheckOutHtmlTag('tr', TR_TAG, [], [])); FList.Add(CheckOutHtmlTag('tt', TT_TAG, [], [])); FList.Add(CheckOutHtmlTag('u', U_TAG, [], [])); FList.Add(CheckOutHtmlTag('ul', UL_TAG, [], [])); FList.Add(CheckOutHtmlTag('var', VAR_TAG, [], [])); FUnknownTag := CheckOutHtmlTag('', UNKNOWN_TAG, [], []) end; destructor THtmlTagList.Destroy; var I: Integer; begin for I := FList.Count - 1 downto 0 do begin FreeMem(PHtmlTag(FList[I])); end; FList.Clear; FList.Free; FreeMem(FUnknownTag); inherited Destroy end; function THtmlTagList.GetTag(Compare: TCompareTag): PHtmlTag; var I, Low, High, Rel: Integer; begin Low := -1; High := FList.Count - 1; while High - Low > 1 do begin I := (High + Low) div 2; Result := FList[I]; Rel := Compare(Result); if Rel < 0 then High := I else if Rel > 0 then Low := I else Exit end; if High >= 0 then begin Result := FList[High]; if Compare(Result) = 0 then Exit end; Result := nil end; function THtmlTagList.CompareName(Tag: PHtmlTag): Integer; begin Result := CompareStr(FSearchName, Tag.Name) end; function THtmlTagList.CompareNumber(Tag: PHtmlTag): Integer; begin Result := FSearchNumber - Tag.Number end; function THtmlTagList.GetTagByName(const Name: WideString): PHtmlTag; begin FSearchName := Name; Result := GetTag(CompareName); if Result = nil then Result := FUnknownTag end; function THtmlTagList.GetTagByNumber(Number: Integer): PHtmlTag; begin FSearchNumber := Number; Result := GetTag(CompareNumber) end; function TURLSchemes.Add(const S: String): Integer; begin if Length(S) > FMaxLen then FMaxLen := Length(S); Result := inherited Add(S) end; function TURLSchemes.IsURL(const S: String): Boolean; begin Result := IndexOf(LowerCase(S)) >= 0 end; function TURLSchemes.GetScheme(const S: String): String; const SchemeChars = [Ord('A')..Ord('Z'), Ord('a')..Ord('z')]; var I: Integer; begin Result := ''; for I := 1 to MaxLen + 1 do begin if I > Length(S) then Exit; if S[I] = ':' then begin if IsURL(Copy(S, 1, I - 1)) then Result := Copy(S, 1, I - 1); Exit end end end; const ExceptionMsg: array[ERR_INDEX_SIZE..ERR_INVALID_ACCESS] of String = ( 'Index or size is negative, or greater than the allowed value', 'The specified range of text does not fit into a DOMString', 'Node is inserted somewhere it doesn''t belong ', 'Node is used in a different document than the one that created it', 'Invalid or illegal character is specified, such as in a name', 'Data is specified for a node which does not support data', 'An attempt is made to modify an object where modifications are not allowed', 'An attempt is made to reference a node in a context where it does not exist', 'Implementation does not support the requested type of object or operation', 'An attempt is made to add an attribute that is already in use elsewhere', 'An attempt is made to use an object that is not, or is no longer, usable', 'An invalid or illegal string is specified', 'An attempt is made to modify the type of the underlying object', 'An attempt is made to create or change an object in a way which is incorrect with regard to namespaces', 'A parameter or an operation is not supported by the underlying object' ); constructor DomException.Create(code: Integer); begin inherited Create(ExceptionMsg[code]); FCode := code end; initialization EntityList := TEntList.Create; HtmlTagList := THtmlTagList.Create; URLSchemes := TURLSchemes.Create; URLSchemes.Add('http'); URLSchemes.Add('https'); URLSchemes.Add('ftp'); URLSchemes.Add('mailto'); URLSchemes.Add('news'); URLSchemes.Add('nntp'); URLSchemes.Add('gopher'); finalization EntityList.Free; HtmlTagList.Free; URLSchemes.Free; end.
unit UDemo; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSGridOptions, FMX.TMSGridPDFIO, FMX.TMSBitmapContainer, FMX.TMSGridCell, FMX.TMSGridData, FMX.TMSCustomGrid, FMX.TMSGrid, FMX.TMSXUtil, FMX.TMSQuickPDFRenderLib; type TForm719 = class(TForm) TMSFMXGrid1: TTMSFMXGrid; Panel1: TPanel; Button1: TButton; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; TMSFMXGridPDFIO1: TTMSFMXGridPDFIO; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); private { Private declarations } public { Public declarations } procedure InitGrid; end; var Form719: TForm719; renderlib: TTMSFMXQuickPDFRenderLib; implementation {$R *.fmx} { TForm719 } procedure TForm719.Button1Click(Sender: TObject); begin TMSFMXGridPDFIO1.ExportPDF(XGetDocumentsDirectory + '/pdfexport.pdf'); end; procedure TForm719.FormCreate(Sender: TObject); begin InitGrid; end; procedure TForm719.InitGrid; begin renderlib := TTMSFMXQuickPDFRenderLib.Create(Self); TMSFMXGridPDFIO1.PDFRenderLib := renderlib; TMSFMXGrid1.Options.Printing.PrintCellBackGround := cbFull; TMSFMXGrid1.ColumnCount := 6; TMSFMXGrid1.RandomFill; TMSFMXGrid1.AutoNumberCol(0); TMSFMXGrid1.Colors[2,2] := TAlphaColorRec.Red; TMSFMXGrid1.Colors[3,3] := TAlphaColorRec.Lime; TMSFMXGrid1.Colors[4,4] := TAlphaColorRec.Yellow; TMSFMXGrid1.HorzAlignments[2,3] := TTextAlign.taCenter; TMSFMXGrid1.HorzAlignments[3,4] := TTextAlign.taTrailing; TMSFMXGrid1.FontStyles[1,1] := [TFontStyle.fsBold]; TMSFMXGrid1.FontStyles[1,2] := [TFontStyle.fsItalic]; TMSFMXGrid1.MergeCells(1,4,2,2); TMSFMXGrid1.AddBitmap(1,7,'1'); TMSFMXGrid1.AddBitmap(1,8,'2'); TMSFMXGrid1.AddBitmap(1,9,'3'); end; procedure TForm719.TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); begin if (ACol = 5) then begin ALayout.FontFill.Color := TAlphaColorRec.Red; ALayout.TextAlign := TTextAlign.taTrailing; end; end; end.
unit Android.BarcodeScanner; interface // Inspired by http://john.whitham.me.uk/xe5/ // Implemented by Jim McKeeth - jim.mckeeth@embarcadero.com - www.delphi.org // Must have the ZXing barcode scanner installed // https://play.google.com/store/apps/details?id=com.google.zxing.client.android // See the ZXing Google Code page here https://code.google.com/p/zxing/ for more info the library and licensing. // The barcode is tranfered via the clipboard, but the clipboard is preserved. uses FMX.platform, fmx.helpers.android, System.Rtti, FMX.Types, System.Classes, System.SysUtils, androidapi.JNI.GraphicsContentViewText, androidapi.jni.JavaTypes, FMX.StdCtrls, FMX.Edit; type TAndroidBarcodeScanner = class; TAndroidBarcodeEvent = procedure (Sender: TAndroidBarcodeScanner; ABarcode: string) of object; TAndroidBarcodeAnonEvent = reference to procedure(ABarcode: string); TAndroidBarcodeScanner = class(TComponent) private FClipService: IFMXClipboardService; FOldClipboard: TValue; FMonitorClipboard: Boolean; FOnBarcode: TAndroidBarcodeEvent; FHandler: TAndroidBarcodeAnonEvent; const ClipboardCanary = 'waiting'; procedure CallScan(AScanCmd: string); procedure GetBarcodeValue; public { Public declarations } type TBarcodeMode = (bmOneD, bmQRCode, bmProduct, bmDataMatrix); type TBarcodeModes = set of TBarcodeMode; function HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; constructor Create(RegisterApplicationEventHandler: Boolean = True); procedure Scan; overload; procedure Scan(AMode: TBarcodeMode); overload; procedure Scan(AModes: TBarcodeModes); overload; procedure Scan(AMode: TBarcodeMode; AHandler: TAndroidBarcodeAnonEvent); overload; procedure Scan(AModes: TBarcodeModes; AHandler: TAndroidBarcodeAnonEvent); overload; const AllBarcodeModes: TBarcodeModes = [bmOneD, bmQRCode, bmProduct, bmDataMatrix]; property OnBarcode: TAndroidBarcodeEvent read FOnBarcode write FOnBarcode; private const BarcodeModes: array [bmOneD .. bmDataMatrix] of string = ('ONE_D_MODE', 'QR_CODE_MODE', 'PRODUCT_MODE', 'DATA_MATRIX_MODE'); function GetModeString(AModes: TBarcodeModes): string; end; implementation { TAndroidBarcodeScanner } constructor TAndroidBarcodeScanner.Create(RegisterApplicationEventHandler: Boolean); var aFMXApplicationEventService: IFMXApplicationEventService; begin FMonitorClipboard := false; if not TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, IInterface(FClipService)) then FClipService := nil; if RegisterApplicationEventHandler then begin if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(aFMXApplicationEventService)) then aFMXApplicationEventService.SetApplicationEventHandler(HandleAppEvent) else Log.d('Application Event Service is not supported.'); end; end; function TAndroidBarcodeScanner.HandleAppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; begin if FMonitorClipboard and (AAppEvent = aeBecameActive) then begin GetBarcodeValue; end; end; procedure TAndroidBarcodeScanner.Scan(AMode: TBarcodeMode); begin Scan([AMode]); end; procedure TAndroidBarcodeScanner.Scan; begin Scan(AllBarcodeModes); end; procedure TAndroidBarcodeScanner.Scan(AModes: TBarcodeModes); begin CallScan(GetModeString(AModes)); end; procedure TAndroidBarcodeScanner.Scan(AModes: TBarcodeModes; AHandler: TAndroidBarcodeAnonEvent); begin FHandler := AHandler; Scan(AModes); end; procedure TAndroidBarcodeScanner.Scan(AMode: TBarcodeMode; AHandler: TAndroidBarcodeAnonEvent); begin FHandler := AHandler; Scan([AMode]); end; procedure TAndroidBarcodeScanner.CallScan(AScanCmd: string); var intent: JIntent; begin if assigned(FClipService) then begin FOldClipboard := FClipService.GetClipboard; FMonitorClipboard := True; FClipService.SetClipboard(ClipboardCanary); intent := tjintent.Create; intent.setAction(stringtojstring('com.google.zxing.client.android.SCAN')); intent.putExtra(tjintent.JavaClass.EXTRA_TEXT, stringtojstring(AScanCmd)); sharedactivity.startActivityForResult(intent, 0); end; end; procedure TAndroidBarcodeScanner.GetBarcodeValue; var value: String; begin FMonitorClipboard := false; if (FClipService.GetClipboard.ToString <> ClipboardCanary) then begin value := FClipService.GetClipboard.ToString; if assigned(FHandler) then FHandler(value) else if assigned(FOnBarcode) then FOnBarcode(Self, FClipService.GetClipboard.ToString); FHandler := nil; end; FClipService.SetClipboard(FOldClipboard); end; function TAndroidBarcodeScanner.GetModeString(AModes: TBarcodeModes): string; var mode: TBarcodeMode; begin Result := ''; for mode in AModes do begin Result := Result + ',' + BarcodeModes[mode]; end; Result := StringReplace(Result, ',', '"SCAN_MODE","', []) + '"'; end; end.
{$include lem_directives.inc} unit GameReplay; interface uses Classes, SysUtils, UMisc, UTools, LemCore, LemTypes; { TODO : make None versions for our types. Replay is suffering from unclearness } type TRecordedType = ( rtNone, rtStartIncreaseRR, rtStartDecreaseRR, rtStopChangingRR, rtSelectSkill, rtAssignSkill, rtNuke ); TReplayItem = class(TCollectionItem) private fIteration : Integer; fRecTyp : TRecordedType; fSkill : TBasicLemmingAction; fLemmingIndex : Integer; fLemmingX : Integer; fLemmingY : Integer; fReleaseRate : Integer; fButtonSkill : TButtonSkill; // only the assign-buttons protected public constructor Create(aCollection: TCollection); override; published property Iteration: Integer read fIteration write fIteration; property RecTyp: TRecordedType read fRecTyp write fRecTyp; property Skill: TBasicLemmingAction read fSkill write fSkill default baWalking; property LemmingIndex : Integer read fLemmingIndex write fLemmingIndex default -1; property LemmingX: Integer read fLemmingX write fLemmingX default 0; property LemmingY: Integer read fLemmingY write fLemmingY default 0; property ReleaseRate: Integer read fReleaseRate write fReleaseRate default 0; property ButtonSkill: TButtonSkill read fButtonSkill write fButtonSkill default bskSlower; end; TReplayItems = class(TCollectionEx) private function GetItem(Index: Integer): TReplayItem; procedure SetItem(Index: Integer; const Value: TReplayItem); protected public constructor Create; procedure SaveToFile(const aFileName: string); procedure SaveToTxt(const aFileName: string); procedure SaveToStream(S: TStream); procedure LoadFromFile(const aFileName: string); procedure LoadFromTxt(const aFileName: string); procedure LoadFromStream(S: TStream); function Add: TReplayItem; function Insert(Index: Integer): TReplayItem; property Items[Index: Integer]: TReplayItem read GetItem write SetItem; default; published // level information + checksum end; // replay wrapper to stream it TReplay = class(TComponent) private fReplayItems: TReplayItems; published property ReplayItems: TReplayItems read fReplayItems write fReplayItems; end; implementation { TReplayItems } function TReplayItems.Add: TReplayItem; begin Result := TReplayItem(inherited Add); end; constructor TReplayItems.Create; begin inherited Create(TReplayItem); end; function TReplayItems.GetItem(Index: Integer): TReplayItem; begin Result := TReplayItem(inherited GetItem(Index)) end; function TReplayItems.Insert(Index: Integer): TReplayItem; begin Result := TReplayItem(inherited Insert(Index)) end; procedure TReplayItems.SaveToFile(const aFileName: string); var F: TFileStream; begin F := TFileStream.Create(aFilename, fmCreate); try SaveToStream(F); finally F.Free; end; end; procedure TReplayItems.SaveToStream(S: TStream); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; S.WriteComponent(R) finally R.Free; end; end; procedure TReplayItems.SaveToTxt(const aFileName: string); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; ComponentToTextFile(R, aFileName); finally R.Free; end; end; procedure TReplayItems.LoadFromFile(const aFileName: string); var F: TFileStream; begin F := TFileStream.Create(aFilename, fmOpenRead); try LoadFromStream(F); finally F.Free; end; end; procedure TReplayItems.LoadFromStream(S: TStream); var R: TReplay; begin R := TReplay.Create(nil); try R.fReplayItems := Self; S.ReadComponent(R) finally R.Free; end; end; procedure TReplayItems.LoadFromTxt(const aFileName: string); begin raise exception.create('loadfromtxt not yet implemented') end; procedure TReplayItems.SetItem(Index: Integer; const Value: TReplayItem); begin inherited SetItem(Index, Value); end; { TReplayItem } constructor TReplayItem.Create(aCollection: TCollection); begin inherited; fLemmingIndex := -1; end; end.
unit evMultiSelectEditorWindow; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/evMultiSelectEditorWindow.pas" // Начат: 10.01.2004 17:35 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<GuiControl::Class>> Shared Delphi::Everest::Editors::TevMultiSelectEditorWindow // // Редактор с возможностью множественного выделения // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses evCustomEditorWindowModelPart, evCustomEditorWindow ; type TevMultiSelectEditorWindow = class(TevCustomEditorWindowModelPart) {* Редактор с возможностью множественного выделения } private // private fields f_AllowMultiSelect : Boolean; {* Поле для свойства AllowMultiSelect} protected // property methods function pm_GetAllowMultiSelect: Boolean; protected // overridden protected methods function GetAllowMultiSelect: Boolean; override; function SelectionClass: RevSelection; override; function HotSpotClass: RevEditorWindowHotSpot; override; public // public properties property AllowMultiSelect: Boolean read pm_GetAllowMultiSelect write f_AllowMultiSelect default false; end;//TevMultiSelectEditorWindow implementation uses evMultiSelection, evMultiSelectEditorWindowHotSpot ; // start class TevMultiSelectEditorWindow function TevMultiSelectEditorWindow.pm_GetAllowMultiSelect: Boolean; //#UC START# *48E4972B039C_4829D8C50010get_var* //#UC END# *48E4972B039C_4829D8C50010get_var* begin //#UC START# *48E4972B039C_4829D8C50010get_impl* Result := inherited pm_GetAllowMultiSelect; //#UC END# *48E4972B039C_4829D8C50010get_impl* end;//TevMultiSelectEditorWindow.pm_GetAllowMultiSelect function TevMultiSelectEditorWindow.GetAllowMultiSelect: Boolean; //#UC START# *48E1F321030C_4829D8C50010_var* //#UC END# *48E1F321030C_4829D8C50010_var* begin //#UC START# *48E1F321030C_4829D8C50010_impl* Result := f_AllowMultiSelect; //#UC END# *48E1F321030C_4829D8C50010_impl* end;//TevMultiSelectEditorWindow.GetAllowMultiSelect function TevMultiSelectEditorWindow.SelectionClass: RevSelection; //#UC START# *48E22866033A_4829D8C50010_var* //#UC END# *48E22866033A_4829D8C50010_var* begin //#UC START# *48E22866033A_4829D8C50010_impl* Result := TevMultiSelection; //#UC END# *48E22866033A_4829D8C50010_impl* end;//TevMultiSelectEditorWindow.SelectionClass function TevMultiSelectEditorWindow.HotSpotClass: RevEditorWindowHotSpot; //#UC START# *48E2297000D3_4829D8C50010_var* //#UC END# *48E2297000D3_4829D8C50010_var* begin //#UC START# *48E2297000D3_4829D8C50010_impl* if AllowMultiSelect then Result := TevMultiSelectEditorWindowHotSpot else Result := inherited HotSpotClass; //#UC END# *48E2297000D3_4829D8C50010_impl* end;//TevMultiSelectEditorWindow.HotSpotClass end.
// Lister API definitions. // This unit is written by Christian Ghisler, it's from Total Commander // Lister API Guide, which can be found at http://ghisler.com. // Version: 1.8. unit WLXPlugin; interface uses Windows; const lc_copy=1; lc_newparams=2; lc_selectall=3; lc_setpercent=4; lcp_wraptext=1; lcp_fittowindow=2; lcp_ansi=4; lcp_ascii=8; lcp_variable=12; lcp_forceshow=16; lcp_fitlargeronly=32; lcp_center=64; lcs_findfirst=1; lcs_matchcase=2; lcs_wholewords=4; lcs_backwards=8; itm_percent=$FFFE; itm_fontstyle=$FFFD; itm_wrap=$FFFC; itm_fit=$FFFB; itm_next=$FFFA; itm_center=$FFF9; LISTPLUGIN_OK=0; LISTPLUGIN_ERROR=1; type tListDefaultParamStruct=record size, PluginInterfaceVersionLow, PluginInterfaceVersionHi:longint; DefaultIniName:array[0..MAX_PATH-1] of AnsiChar; end; pListDefaultParamStruct=^tListDefaultParamStruct; { Function prototypes: Functions need to be defined exactly like this!} { function ListLoad(ParentWin:thandle;FileToLoad:PAnsiChar;ShowFlags:integer):thandle; stdcall; function ListLoadNext(ParentWin,PluginWin:thandle;FileToLoad:PAnsiChar;ShowFlags:integer):integer; stdcall; procedure ListCloseWindow(ListWin:thandle); stdcall; procedure ListGetDetectString(DetectString:PAnsiChar;maxlen:integer); stdcall; function ListSearchText(ListWin:thandle;SearchString:PAnsiChar; SearchParameter:integer):integer; stdcall; function ListSearchDialog(ListWin:thandle;FindNext:integer):integer; stdcall; function ListSendCommand(ListWin:thandle;Command,Parameter:integer):integer; stdcall; function ListPrint(ListWin:thandle;FileToPrint,DefPrinter:PAnsiChar; PrintFlags:integer;var Margins:trect):integer; stdcall; function ListNotificationReceived(ListWin:thandle;Message,wParam,lParam:integer):integer; stdcall; procedure ListSetDefaultParams(dps:pListDefaultParamStruct); stdcall; function ListGetPreviewBitmap(FileToLoad:PAnsiChar;width,height:integer; contentbuf:PAnsiChar;contentbuflen:integer):hbitmap; stdcall; } implementation end.
unit PidlPath; interface uses Windows, ShlObj; function PidlToFilePath( pidl : PItemIDList ) : string; function FilePathToPidl( Filename : string ) : PItemIDList; implementation uses SysUtils; function PidlToFilePath( pidl : PItemIDList ) : string; begin if pidl <> nil then begin SetLength( Result, MAX_PATH ); if SHGetPathFromIDList( pidl, pchar( Result ) ) then SetLength( Result, strlen( pchar( Result ) ) ) else SetLength( Result, 0 ); end else Result := ''; end; function FilePathToPidl( Filename : string ) : PItemIDList; var DesktopFolder : IShellFolder; OlePath : array[0..pred( MAX_PATH )] of widechar; Eaten : ULONG; Attr : ULONG; begin if Succeeded( SHGetDesktopFolder( DesktopFolder ) ) then begin MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, pchar( Filename ), -1, OlePath, MAX_PATH ); if not Succeeded( DesktopFolder.ParseDisplayName( THandle( nil ), nil, OlePath, Eaten, Result, Attr ) ) then Result := nil; DesktopFolder := nil; end else Result := nil; end; end.
unit Provect.Helpers.Str; interface type TStringHelper = record helper for string function Contains(const Value: string): Boolean; function IsEmpty: Boolean; function ToCurrency: Currency; function ToInteger: Integer; class function Join(const Separator: string; const values: array of const): string; overload; static; class function Join(const Separator: string; const Values: array of string): string; overload; static; class function Join(const Separator: string; const Values: IEnumerator<string>): string; overload; static; class function Join(const Separator: string; const Values: IEnumerable<string>): string; overload; static; class function Join(const Separator: string; const value: array of string; StartIndex: Integer; Count: Integer): string; overload; static; end; implementation uses System.SysUtils, System.SysConst; { TStringHelper } class function TStringHelper.Join(const Separator: string; const Values: array of string): string; begin Result := Join(Separator, Values, 0, System.Length(Values)); end; class function TStringHelper.Join(const Separator: string; const Values: IEnumerable<string>): string; var eValues: IEnumerator<string>; begin if Assigned(Values) then begin eValues := Values.GetEnumerator; Result := eValues.Current; while eValues.MoveNext do Result := Result + Separator + eValues.Current; end else Result := ''; end; class function TStringHelper.Join(const Separator: string; const Values: IEnumerator<string>): string; begin if Assigned(Values) then begin Result := Values.Current; while Values.MoveNext do Result := Result + Separator + Values.Current; end else Result := ''; end; function TStringHelper.Contains(const Value: string): Boolean; begin Result := System.Pos(Value, Self) > 0; end; function TStringHelper.IsEmpty: Boolean; begin Result := Self = EmptyStr; end; class function TStringHelper.Join(const Separator: string; const Value: array of string; StartIndex, Count: Integer): string; var I: Integer; Max: Integer; begin if StartIndex >= System.Length(Value) then raise ERangeError.Create(SRangeError); if (StartIndex + Count) > System.Length(Value) then Max := System.Length(Value) else Max := StartIndex + Count; Result := Value[StartIndex]; for I:= StartIndex + 1 to Max - 1 do Result := Result + Separator + Value[I]; end; function TStringHelper.ToCurrency: Currency; var TempStr: string; begin TempStr := StringReplace(Self, '.', FormatSettings.DecimalSeparator, [rfReplaceAll]); TempStr := StringReplace(TempStr, ',', FormatSettings.DecimalSeparator, [rfReplaceAll]); TempStr := StringReplace(TempStr, FormatSettings.ThousandSeparator, EmptyStr, [rfReplaceAll]); Result := StrToCurrDef(TempStr, 0); end; function TStringHelper.ToInteger: Integer; begin Result := StrToIntDef(Self, 0); end; class function TStringHelper.Join(const Separator: string; const values: array of const): string; var I: Integer; len: Integer; function ValueToString(const val: TVarRec):string; begin case val.VType of vtInteger: Result := IntToStr(val.VInteger); {$IFNDEF NEXTGEN} vtChar: Result := Char(val.VChar); vtPChar: Result := string(val.VPChar); {$ENDIF !NEXTGEN} vtExtended: Result := FloatToStr(val.VExtended^); vtObject: Result := TObject(val.VObject).Classname; vtClass: Result := val.VClass.Classname; vtCurrency: Result := CurrToStr(val.VCurrency^); vtInt64: Result := IntToStr(PInt64(val.VInt64)^); vtUnicodeString: Result := string(val.VUnicodeString); else Result := Format('(Unknown) : %d',[val.VType]); end; end; begin len := System.Length(Values); if len = 0 then Result := '' else begin Result := ValueToString(Values[0]); for I := 1 to len-1 do Result := Result + Separator + ValueToString(Values[I]); end; end; end.
unit MapTypes; interface uses Windows, Messages, Classes, Graphics, GameTypes, Threads, LanderTypes, Land; type TZoomRes = (zr4x8, zr8x16, zr16x32, zr32x64, zr64x128); // ZoomLevel ~ ord(ZoomRes) type TMapImage = TGameImage; type TMapPoint = record r, c : integer; end; const idMask = $FFFF0000; idLandMask = $00000000; type idLand = byte; type ILocalCacheManager = interface function Load(const url : string) : boolean; function GetLandMap : TMapImage; function GetLandImage(const zoom : TZoomRes; id : idLand) : TGameImage; function GetSpareImage(const zoom : TZoomRes) : TGameImage; function GetShadeImage(const zoom : TZoomRes) : TGameImage; function GetRedShadeImage(const zoom : TZoomRes) : TGameImage; function GetBlackShadeImage(const zoom : TZoomRes) : TGameImage; end; // Messages const msgBase = WM_USER + 1024; const msgGeneralBase = msgBase; msgViewZoomed = msgGeneralBase + 3; const msgMoveBase = msgBase + 60; msgMoveTo = msgMoveBase + 0; type TViewZoomedMsg = record id : integer; Zoom : TZoomLevel; end; type TMoveMessage = record id : integer; i, j : integer; end; type TMoveToMsg = TMoveMessage; // Warnings const verbBase = WM_USER + 6*1024; const verbViewRegionUpdated = verbBase + 0; // Data type TFocusData = object ok : boolean; row : integer; col : integer; end; type TSelectionData = object(TFocusData) id : integer; r : integer; c : integer; ClassId : integer; Company : integer; Text : string; TextRect : TRect; end; implementation end.
unit View.RecepcaoPedidos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, cxGroupBox, cxRadioGroup, Vcl.ComCtrls, dxCore, cxDateUtils, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, System.Actions, Vcl.ActnList, dxLayoutControlAdapters, Vcl.Menus, Vcl.StdCtrls, cxButtons, Common.ENum, Control.Clientes, Control.Entregas, Control.Sistema, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxDBLookupComboBox, FireDAC.Comp.Client, cxCheckBox, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog; type Tview_RecepcaoPedidos = class(TForm) dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; cxLabel1: TcxLabel; dxLayoutItem1: TdxLayoutItem; crbRecepcao: TcxRadioGroup; dxLayoutItem2: TdxLayoutItem; cboCliente: TcxComboBox; dxLayoutItem3: TdxLayoutItem; aclRecepcao: TActionList; actFechar: TAction; actIniciar: TAction; cxButton1: TcxButton; dxLayoutItem4: TdxLayoutItem; txtLeitura: TcxTextEdit; dxLayoutItem5: TdxLayoutItem; tvRecepcao: TcxGridDBTableView; lvRecepcao: TcxGridLevel; grdRecepcao: TcxGrid; dxLayoutItem6: TdxLayoutItem; dsRecepcao: TDataSource; tvRecepcaonum_nossonumero: TcxGridDBColumn; tvRecepcaocod_cliente: TcxGridDBColumn; tvRecepcaonum_nf: TcxGridDBColumn; tvRecepcaonom_consumidor: TcxGridDBColumn; tvRecepcaodat_expedicao: TcxGridDBColumn; tvRecepcaoqtd_volumes: TcxGridDBColumn; tvRecepcaoqtd_peso_real: TcxGridDBColumn; tvRecepcaodat_recebido: TcxGridDBColumn; tvRecepcaonum_container: TcxGridDBColumn; tvRecepcaonum_pedido: TcxGridDBColumn; dsEmbarcadores: TDataSource; cxButton2: TcxButton; dxLayoutItem7: TdxLayoutItem; actGravar: TAction; cxButton3: TcxButton; dxLayoutItem8: TdxLayoutItem; actCancelar: TAction; cxButton4: TcxButton; dxLayoutItem9: TdxLayoutItem; dxLayoutGroup1: TdxLayoutGroup; dxLayoutAutoCreatedGroup3: TdxLayoutAutoCreatedGroup; dxLayoutGroup2: TdxLayoutGroup; dxLayoutGroup3: TdxLayoutGroup; datInicio: TcxDateEdit; dxLayoutItem10: TdxLayoutItem; datFinal: TcxDateEdit; dxLayoutItem11: TdxLayoutItem; dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup; cboSituacao: TcxComboBox; dxLayoutItem12: TdxLayoutItem; actPesquisar: TAction; cxButton5: TcxButton; dxLayoutItem13: TdxLayoutItem; SaveDialog: TSaveDialog; dxLayoutAutoCreatedGroup4: TdxLayoutAutoCreatedGroup; lblResultado: TcxLabel; dxLayoutItem14: TdxLayoutItem; procedure txtLeituraPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure crbRecepcaoPropertiesChange(Sender: TObject); procedure cboClientePropertiesChange(Sender: TObject); procedure actFecharExecute(Sender: TObject); procedure actGravarExecute(Sender: TObject); procedure actCancelarExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actIniciarExecute(Sender: TObject); procedure dxLayoutGroup2TabChanged(Sender: TObject); procedure tvRecepcaoNavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure actPesquisarExecute(Sender: TObject); private { Private declarations } procedure PopulaEmbarcadores(iCliente: Integer); procedure LocalizaEntrega(sChave: String; iCliente, iOpcao: Integer); procedure SetupEntregas(FDQuery: TFDquery); procedure SetupGrade(sNN: String; FDQuery: TFDQuery); procedure LocalizaContainer(sChave: String; iCliente: Integer); procedure PesquisaEntregas(dtInicio: TDate; dtFinal: TDate; iSituacao: Integer; iCliente: Integer); procedure Iniciar; procedure Cancelar; procedure Gravar; procedure Exportar; procedure LabelResultado(iTipo: Integer; sTexto: String); procedure Aviso(sTexto: String); function RetornaNN(sLeitura: String; icliente: Integer): String; public { Public declarations } end; var view_RecepcaoPedidos: Tview_RecepcaoPedidos; clientes : TClientesControl; entregas : TEntregasControl; implementation {$R *.dfm} uses Data.SisGeF, Common.Utils, TFO.Barras, Global.Parametros, View.Aviso; { Tview_RecepcaoPedidos } procedure Tview_RecepcaoPedidos.actCancelarExecute(Sender: TObject); begin if Application.MessageBox('Confirma cancelar a operação?', 'Cancelar', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit; Cancelar; end; procedure Tview_RecepcaoPedidos.actFecharExecute(Sender: TObject); begin Perform(WM_CLOSE, 0, 0); end; procedure Tview_RecepcaoPedidos.actGravarExecute(Sender: TObject); begin Gravar; end; procedure Tview_RecepcaoPedidos.actIniciarExecute(Sender: TObject); begin Iniciar; end; procedure Tview_RecepcaoPedidos.actPesquisarExecute(Sender: TObject); begin PesquisaEntregas(datInicio.Date, datFinal.Date, cboSituacao.ItemIndex,cboCliente.ItemIndex); end; procedure Tview_RecepcaoPedidos.Cancelar; begin if Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Close; Data_Sisgef.mtbRecepcaoPedidos.Open; cboCliente.Properties.ReadOnly := False; cboCliente.ItemIndex := 0; txtLeitura.Properties.ReadOnly := True; actGravar.Enabled := False; actCancelar.Enabled := False; crbRecepcao.Properties.ReadOnly := False; crbRecepcao.ItemIndex := 0; end; procedure Tview_RecepcaoPedidos.cboClientePropertiesChange(Sender: TObject); begin if Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Close; Data_Sisgef.mtbRecepcaoPedidos.Open; end; procedure Tview_RecepcaoPedidos.crbRecepcaoPropertiesChange(Sender: TObject); begin if Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Close; Data_Sisgef.mtbRecepcaoPedidos.Open; end; procedure Tview_RecepcaoPedidos.dxLayoutGroup2TabChanged(Sender: TObject); begin Cancelar; end; procedure Tview_RecepcaoPedidos.Exportar; begin SaveDialog.Filter := ''; SaveDialog.Filter := 'Excel (*.xls) |*.xls|XML (*.xml) |*.xml|Arquivo Texto (*.txt) |*.txt|Página Web (*.html)|*.html'; SaveDialog.Title := 'Exportar Dados'; SaveDialog.DefaultExt := 'xls'; if SaveDialog.Execute then begin TUtils.ExportarDados(grdRecepcao, SaveDialog.FileName); end; end; procedure Tview_RecepcaoPedidos.FormClose(Sender: TObject; var Action: TCloseAction); begin if Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Close; Action := caFree; view_RecepcaoPedidos := nil; end; procedure Tview_RecepcaoPedidos.FormKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 then begin Key := #0; if grdRecepcao.IsFocused then Exit; Perform(Wm_NextDlgCtl, 0, 0); end; end; procedure Tview_RecepcaoPedidos.Gravar; var FDQuery: TFDQuery; aParam: array of variant; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; entregas := TEntregasControl.Create; if Application.MessageBox('Confirma gravar a recepção?', 'Gravar', MB_YESNO + MB_ICONQUESTION) = IDNO then Exit; if not Data_Sisgef.mtbRecepcaoPedidos.IsEmpty then Data_Sisgef.mtbRecepcaoPedidos.First; while not Data_Sisgef.mtbRecepcaoPedidos.eof do begin SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := Data_Sisgef.mtbRecepcaoPedidosnum_nossonumero.AsString; FDQuery := entregas.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then begin SetupEntregas(FDQuery); entregas.Entregas.Recebimento := Data_Sisgef.mtbRecepcaoPedidosdat_recebido.AsDateTime; entregas.Entregas.Recebido := 'S'; entregas.Entregas.Rastreio := entregas.Entregas.Rastreio + #13 + '> ' + FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' pedido recebido por ' + Global.Parametros.pUser_Name; entregas.Entregas.Acao := tacAlterar; if not entregas.Gravar then begin Application.MessageBox(PChar('Erro ao gravar o pedido NN ' + entregas.Entregas.NN + ' !'), 'Erro', MB_OK + MB_ICONERROR); end; end; Data_Sisgef.mtbRecepcaoPedidos.Next; end; Application.MessageBox('Recepção gravada com sucesso!', 'Atenção', MB_OK + MB_ICONINFORMATION); Cancelar; finally FDQuery.Free; entregas.Free; end; end; procedure Tview_RecepcaoPedidos.Iniciar; begin if cboCliente.ItemIndex = 0 then begin Application.MessageBox('Selecione o cliente.', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; if crbRecepcao.ItemIndex = -1 then begin Application.MessageBox('Selecione o tipo de recepção.', 'Atenção', MB_OK + MB_ICONWARNING); Exit; end; PopulaEmbarcadores(cboCliente.ItemIndex); cboCliente.Properties.ReadOnly := True; crbRecepcao.Properties.ReadOnly := True; txtLeitura.Properties.ReadOnly := False; actGravar.Enabled := True; actCancelar.Enabled := True; txtLeitura.SetFocus; end; procedure Tview_RecepcaoPedidos.LocalizaContainer(sChave: String; iCliente: Integer); var FDQuery : TFDQuery; aParam : Array of variant; barra : TBarrTFO; bFlagGravar: Boolean; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; entregas := TEntregasControl.Create; SetLength(aParam,2); aParam[0] := 'CONTAINER'; aParam[1] := sChave; FDQuery := entregas.Localizar(aParam); Finalize(aParam); if FDQuery.IsEmpty then begin Application.MessageBox(PChar('Container ' + sChave + ' não encontrado no banco de dados!'), 'Atenção', MB_OK + MB_ICONHAND); Exit; end; FDQuery.First; while not FDQuery.Eof do begin bFlagGravar := True; if FDQuery.FieldByName('DOM_RECEBIDO').AsString <> 'N' then begin bFlagGravar := False; end; if not Data_Sisgef.mtbRecepcaoPedidos.IsEmpty then Data_Sisgef.mtbRecepcaoPedidos.First; while not Data_Sisgef.mtbRecepcaoPedidos.eof do begin if Data_Sisgef.mtbRecepcaoPedidosnum_nossonumero.AsString = FDQuery.FieldByName('num_nossonumero').AsString then bFlagGravar := False; Data_Sisgef.mtbRecepcaoPedidos.Next; end; if bFlagGravar then begin SetupGrade(FDQuery.FieldByName('num_nossonumero').AsString,FDQuery); end; FDQuery.Next; end; finally txtLeitura.SetFocus; FDQuery.Free; entregas.Free; end; end; procedure Tview_RecepcaoPedidos.LocalizaEntrega(sChave: String; iCliente, iOpcao: Integer); var FDQuery : TFDQuery; aParam : Array of variant; sNN: String; barra : TBarrTFO; bFlagGravar: Boolean; dPesoMax: Double; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; entregas := TEntregasControl.Create; sNN := ''; if iCliente = 4 then begin dPesoMax := 30; end else begin dPesoMax := 25; end; if cboCliente.ItemIndex <> 3 then begin sNN := RetornaNN(sChave, iCliente); SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := sNN; end else begin sNN := Trim(sChave); SetLength(aParam,2); aParam[0] := 'FILTRO'; aParam[1] := 'where des_retorno like ' + QuotedStr(sNN+'%'); end; FDQuery := entregas.Localizar(aParam); Finalize(aParam); if FDQuery.IsEmpty then begin LabelResultado(2, 'Pedido ' + sNN + ' não encontrado!'); Aviso('Pedido ' + sNN + ' não encontrado!'); LabelResultado(0,''); Exit; end; sNN := FDQuery.FieldByName('num_nossonumero').AsString; if sNN.IsEmpty then begin LabelResultado(2, 'Pedido ' + sNN + ' inválido!'); Aviso('Pedido ' + sNN + ' inválido!'); LabelResultado(0,''); Exit; end; bFlagGravar := True; if not Data_Sisgef.mtbRecepcaoPedidos.IsEmpty then Data_Sisgef.mtbRecepcaoPedidos.First; while not Data_Sisgef.mtbRecepcaoPedidos.eof do begin if Data_Sisgef.mtbRecepcaoPedidosnum_nossonumero.AsString = sNN then bFlagGravar := False; Data_Sisgef.mtbRecepcaoPedidos.Next; end; if not bFlagGravar then begin LabelResultado(2, 'Pedido ' + sNN + ' já consta na lista de recebimento!'); Aviso('Pedido ' + sNN + ' já foi recebido anteriormente!'); LabelResultado(0,''); Exit; end; if FDQuery.FieldByName('DOM_RECEBIDO').AsString = 'S' then begin LabelResultado(2, 'Pedido ' + sNN + ' já foi recebido anteriormente!'); Aviso('Pedido ' + sNN + ' já foi recebido anteriormente!'); LabelResultado(0,''); Exit; end; if iOpcao = 2 then begin if FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat > dPesoMax then begin LabelResultado(2, 'Categoria do Pedido ' + sNN + ' é PESADO!'); Aviso('Categoria do Pedido ' + sNN + ' é PESADO!'); LabelResultado(0,''); Exit; end; end else if iOpcao = 3 then begin if FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat <= dPesoMax then begin LabelResultado(2, 'Categoria do Pedido ' + sNN + ' é LEVE!'); Aviso('Categoria do Pedido ' + sNN + ' é LEVE!'); LabelResultado(0,''); Exit; end; end; SetupGrade(sNN,FDQuery); finally txtLeitura.SetFocus; FDQuery.Free; entregas.Free; end; end; procedure Tview_RecepcaoPedidos.PesquisaEntregas(dtInicio, dtFinal: TDate; iSituacao, iCliente: Integer); var FDQuery: TFDQuery; aParam: Array of variant; sQuery: String; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; entregas := TEntregasControl.Create; if Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Close; Data_Sisgef.mtbRecepcaoPedidos.Open; SetLength(aParam,2); aParam[0] := 'FILTRO'; sQuery := ''; if iSituacao = 1 then begin sQuery := 'where dat_recebido between ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtInicio)) + ' and ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtFinal)) + ' and cod_cliente_empresa = ' + iCliente.ToString + ' and dom_recebido = ' + QuotedStr('S'); end else if iSituacao = 2 then begin sQuery := 'where dat_expedicao between ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtInicio)) + ' and ' + QuotedStr(FormatDateTime('yyyy-mm-dd', dtFinal)) + ' and cod_cliente_empresa = ' + iCliente.ToString + ' and dom_recebido <> ' + QuotedStr('S'); end; aParam[1] := sQuery; FDQuery := entregas.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then FDQuery.First; while not FDQuery.Eof do begin SetupGrade(FDQuery.FieldByName('num_nossonumero').AsString, FDQuery); FDQuery.Next; end; finally FDQuery.Free; entregas.Free; end; end; procedure Tview_RecepcaoPedidos.PopulaEmbarcadores(iCliente: Integer); var FDQuery : TFDQuery; aParam : Array of variant; begin try FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery; clientes := TClientesControl.Create; if Data_Sisgef.mtbEmbarcadores.Active then Data_Sisgef.mtbEmbarcadores.Close; SetLength(aParam,2); aParam[0] := 'CLIENTE'; aParam[1] := iCliente; FDQuery := clientes.Localizar(aParam); if not FDQuery.IsEmpty then begin Data_Sisgef.mtbEmbarcadores.Data := FDQuery.Data; end; FDQuery.Close; finally clientes.Free; FDquery.Free; end;end; function Tview_RecepcaoPedidos.RetornaNN(sLeitura: String; icliente: Integer): String; var sNN: String; barra : TBarrTFO; begin sNN := ''; if iCliente = 1 then begin if TUtils.ENumero(sLeitura) then begin sNN := sLeitura; end else begin barra := TBarrTFO.Create; if barra.RetornaNN(sLeitura) then begin sNN := barra.NossoNumero; end; barra.Free; end; end else if icliente = 2 then begin sNN := Copy(sLeitura,2,11); end else if icliente = 3 then begin sNN := Copy(sLeitura,23,12); end else begin sNn := sLeitura; end; Result := sNN; end; procedure Tview_RecepcaoPedidos.SetupEntregas(FDQuery: TFDquery); begin entregas.Entregas.NN := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString; entregas.Entregas.Distribuidor := FDQuery.FieldByName('COD_AGENTE').AsInteger; entregas.Entregas.Entregador := FDQuery.FieldByName('COD_ENTREGADOR').AsInteger; entregas.Entregas.Cliente := FDQuery.FieldByName('COD_CLIENTE').AsInteger; entregas.Entregas.NF := FDQuery.FieldByName('NUM_NF').AsString; entregas.Entregas.Consumidor := FDQuery.FieldByName('NOM_CONSUMIDOR').AsString; entregas.Entregas.Endereco := FDQuery.FieldByName('DES_ENDERECO').AsString; entregas.Entregas.Complemento := FDQuery.FieldByName('DES_COMPLEMENTO').AsString; entregas.Entregas.Bairro := FDQuery.FieldByName('DES_BAIRRO').AsString; entregas.Entregas.Cidade := FDQuery.FieldByName('NOM_CIDADE').AsString; entregas.Entregas.Cep := FDQuery.FieldByName('NUM_CEP').AsString; entregas.Entregas.Telefone := FDQuery.FieldByName('NUM_TELEFONE').AsString ; entregas.Entregas.Expedicao := FDQuery.FieldByName('DAT_EXPEDICAO').AsDateTime; entregas.Entregas.Previsao := FDQuery.FieldByName('DAT_PREV_DISTRIBUICAO').AsDateTime; entregas.Entregas.Volumes := FDQuery.FieldByName('QTD_VOLUMES').AsInteger; entregas.Entregas.Atribuicao := FDQuery.FieldByName('DAT_ATRIBUICAO').AsDateTime; entregas.Entregas.Baixa := FDQuery.FieldByName('DAT_BAIXA').AsDateTime; entregas.Entregas.Baixado := FDQuery.FieldByName('DOM_BAIXADO').AsString; entregas.Entregas.Pagamento := FDQuery.FieldByName('DAT_PAGAMENTO').AsDateTime; entregas.Entregas.Pago := FDQuery.FieldByName('DOM_PAGO').AsString; entregas.Entregas.Fechado := FDQuery.FieldByName('DOM_FECHADO').AsString; entregas.Entregas.Status := FDQuery.FieldByName('COD_STATUS').AsInteger; entregas.Entregas.Entrega := FDQuery.FieldByName('DAT_ENTREGA').AsDateTime; entregas.Entregas.PesoReal := FDQuery.FieldByName('QTD_PESO_REAL').AsFloat; entregas.Entregas.PesoFranquia := FDQuery.FieldByName('QTD_PESO_FRANQUIA').AsFloat; entregas.Entregas.VerbaFranquia := FDQuery.FieldByName('VAL_VERBA_FRANQUIA').AsFloat; entregas.Entregas.Advalorem := FDQuery.FieldByName('VAL_ADVALOREM').AsFloat; entregas.Entregas.PagoFranquia := FDQuery.FieldByName('VAL_PAGO_FRANQUIA').AsFloat; entregas.Entregas.VerbaEntregador := FDQuery.FieldByName('VAL_VERBA_ENTREGADOR').AsFloat; entregas.Entregas.Extrato := FDQuery.FieldByName('NUM_EXTRATO').AsString; entregas.Entregas.Atraso := FDQuery.FieldByName('QTD_DIAS_ATRASO').AsInteger; entregas.Entregas.VolumesExtra := FDQuery.FieldByName('QTD_VOLUMES_EXTRA').AsFloat; entregas.Entregas.ValorVolumes := FDQuery.FieldByName('VAL_VOLUMES_EXTRA').AsFloat; entregas.Entregas.PesoCobrado := FDQuery.FieldByName('QTD_PESO_COBRADO').AsFloat; entregas.Entregas.TipoPeso := FDQuery.FieldByName('DES_TIPO_PESO').AsString; entregas.Entregas.Recebimento := FDQuery.FieldByName('DAT_RECEBIDO').AsDateTime; entregas.Entregas.Recebido := FDQuery.FieldByName('DOM_RECEBIDO').AsString; entregas.Entregas.CTRC := FDQuery.FieldByName('NUM_CTRC').AsInteger; entregas.Entregas.Manifesto := FDQuery.FieldByName('NUM_MANIFESTO').AsInteger; entregas.Entregas.Rastreio := FDQuery.FieldByName('DES_RASTREIO').AsString; entregas.Entregas.Lote := FDQuery.FieldByName('NUM_LOTE_REMESSA').AsInteger; entregas.Entregas.Retorno := FDQuery.FieldByName('DES_RETORNO').AsString; entregas.Entregas.Credito := FDQuery.FieldByName('DAT_CREDITO').AsDateTime; entregas.Entregas.Creditado := FDQuery.FieldByName('DOM_CREDITO').AsString; entregas.Entregas.Container := FDQuery.FieldByName('NUM_CONTAINER').AsString; entregas.Entregas.ValorProduto := FDQuery.FieldByName('VAL_PRODUTO').AsFloat; entregas.Entregas.Altura := FDQuery.FieldByName('QTD_ALTURA').AsInteger; entregas.Entregas.Largura := FDQuery.FieldByName('QTD_LARGURA').AsInteger; entregas.Entregas.Comprimento := FDQuery.FieldByName('QTD_COMPRIMENTO').AsInteger; entregas.Entregas.CodigoFeedback := FDQuery.FieldByName('COD_FEEDBACK').AsInteger; entregas.Entregas.DataFeedback := FDQuery.FieldByName('DAT_FEEDBACK').AsDateTime; entregas.Entregas.Conferido := FDQuery.FieldByName('DOM_CONFERIDO').AsInteger; entregas.Entregas.Pedido := FDQuery.FieldByName('NUM_PEDIDO').AsString; entregas.Entregas.CodCliente := FDQuery.FieldByName('COD_CLIENTE_EMPRESA').AsInteger; end; procedure Tview_RecepcaoPedidos.SetupGrade(sNN: String; FDQuery: TFDQuery); var pParam: Array of variant; begin if not Data_Sisgef.mtbRecepcaoPedidos.Active then Data_Sisgef.mtbRecepcaoPedidos.Active := True; Data_Sisgef.mtbRecepcaoPedidos.Insert; Data_Sisgef.mtbRecepcaoPedidosnum_nossonumero.AsString := FDQuery.FieldByName('NUM_NOSSONUMERO').AsString; Data_Sisgef.mtbRecepcaoPedidoscod_cliente.AsInteger := FDQuery.FieldByName('COD_CLIENTE').AsInteger; Data_Sisgef.mtbRecepcaoPedidosnum_nf.AsString := FDQuery.FieldByName('NUM_NF').AsString; Data_Sisgef.mtbRecepcaoPedidosnom_consumidor.AsString := FDquery.FieldByName('NOM_CONSUMIDOR').AsString; Data_Sisgef.mtbRecepcaoPedidosdat_expedicao.AsDateTime := FDquery.FieldByName('DAT_EXPEDICAO').AsDateTime; Data_Sisgef.mtbRecepcaoPedidosqtd_volumes.AsInteger := FDquery.FieldByName('QTD_VOLUMES').AsInteger; Data_Sisgef.mtbRecepcaoPedidosqtd_peso_real.AsFloat := FDquery.FieldByName('QTD_PESO_REAL').AsFloat; Data_Sisgef.mtbRecepcaoPedidosnum_container.AsString := FDQuery.FieldByName('NUM_CONTAINER').AsString; Data_Sisgef.mtbRecepcaoPedidosnum_pedido.AsString := FDQuery.FieldByName('NUM_PEDIDO').AsString; Data_Sisgef.mtbRecepcaoPedidosdat_recebido.AsDateTime := Now; Data_Sisgef.mtbRecepcaoPedidos.Post; end; procedure Tview_RecepcaoPedidos.tvRecepcaoNavigatorButtonsButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); begin case AButtonIndex of 16: Exportar; end; end; procedure Tview_RecepcaoPedidos.txtLeituraPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin if crbRecepcao.ItemIndex = 1 then begin if DisplayValue <> '' then LocalizaContainer(DisplayValue,cboCliente.ItemIndex); DisplayValue := ''; end else begin if DisplayValue <> '' then LocalizaEntrega(DisplayValue,cboCliente.ItemIndex, crbRecepcao.ItemIndex); DisplayValue := ''; end; end; procedure Tview_RecepcaoPedidos.LabelResultado(iTipo: Integer; sTexto: String); begin lblResultado.Caption := sTexto; if iTipo = 1 then begin lblResultado.Style.Color := clWindow; lblResultado.Style.Font.Color := clLime; end else if iTipo = 2 then begin lblResultado.Style.Color := clWindow; lblResultado.Style.Font.Color := clRed; TUtils.TocaErro; end else begin lblResultado.Style.Color := clWindow; lblResultado.Style.Font.Color := clWindowText; Tutils.CancelaTocaErro; end; lblResultado.Refresh; end; procedure Tview_RecepcaoPedidos.Aviso(sTexto: String); var iModal: Integer; begin if not Assigned(view_Aviso) then begin view_Aviso := Tview_Aviso.Create(Application); end; view_Aviso.memAviso.Text := sTexto; iModal := view_Aviso.ShowModal; FreeAndNil(view_Aviso); end; end.
unit uActors; interface uses IniFiles, Classes, Graphics, UNPC, UConfig, UCommon, USigns, Types, TypInfo; type NEffect = (efPoison, efBlind, efDisease, efStun, efBleedy, efFrozen, efBursted, efSpider, efForest, efDungeon, efAcid, efWeak); TEffect = class(THODObject) private FID: NEffect; protected //** Конструктор. constructor Create(AID: NEffect); public property ID: NEffect read FID; end; TEffects = class(TObjList) private function GetEffects(Eff: NEffect): TEffect; procedure SetEffects(Eff: NEffect; const Value: TEffect); property Effects[Eff: NEffect]: TEffect read GetEffects write SetEffects; default; public function HasEffect(Eff: NEffect): Integer; function EffectValue(Eff: NEffect): Integer; end; TActor = class(THODObject) private FX, FY: Word; public //** Конструктор. constructor Create(AX, AY: Word); function GetGraphic: Tbitmap; virtual; procedure SetXY(AX, AY: Integer); virtual; property X: Word read FX; property Y: Word read FY; function Move(x2, y2: Word): Boolean; virtual; procedure Die(); end; TAI = class(TActor) private FSpeed: Single; FMoveDelay: Integer; procedure SetMoved(const Value: Boolean); virtual; function Movecost(x, y, Direction: smallint): Smallint; virtual; procedure SetMoveDelay(const Value: Integer); procedure ModifyMoveDelay(const Value: Integer); function GetMoved: Boolean; function GetIsStuned: Boolean; public property Moved: Boolean read GetMoved write SetMoved; property MoveDelay: Integer read FMoveDelay write SetMoveDelay; function Move(x2, y2: Word): Boolean; override; property IsStuned: Boolean read GetIsStuned; end; TNPC = class(TAI) private FID{, FX, FY}: Integer; FNPCID: Integer; FDest: TPoint; FIsWandering: Boolean; // FSetup: Boolean; function GetIntParams(Index: NNpcParam): Integer; function GetStrParams(Index: NNpcParam): string; procedure SetNPCID(const Value: Integer); procedure SetMoved(const Value: Boolean); override; function Movecost(x, y, Direction: smallint): Smallint; override; public procedure SetupWander(); function Move(x2, y2: Word): Boolean; override; procedure ExecScript; //** Конструктор. constructor Create(AID: Integer; AScript: string = ''); function GetGraphic: TBitmap; override; property ID: Integer read FID; property StrParams[Index: NNpcParam]: string read GetStrParams; property IntParams[Index: NNpcParam]: Integer read GetIntParams; property NPCID: Integer read FNPCID write SetNPCID; property Dest: TPoint read FDest; end; TProjectile = class(TActor) private FDest: TPoint; FDelta: TPoint; procedure SetDelta(const Value: TPoint); public function Move(x2, y2: Word): Boolean; override; property Delta: TPoint read FDelta write SetDelta; end; TArrow = class(TProjectile) private protected public function GetGraphic: TBitmap; override; end; TFireBall = class(TProjectile) private FFrame, FFrameCnt, FLightId, FLife: Integer; protected public //** Конструктор. constructor Create(); destructor Destroy(); override; procedure SetXY(AX, AY: Integer); override; function GetGraphic: TBitmap; override; end; TCreature = class(THODObject) private FSh: Integer; FHP: Integer; FImageIndex: Integer; FDamage: Integer; FDXT: Integer; FExp: Integer; FDescription: string; FDungeons: string; FName: string; FEffects: TEffects; FDungMax: Integer; FDungMin: Integer; FAgrRadius: Integer; function GetBMP: TBitmap; procedure SetAgrRadius(const Value: Integer); protected procedure SetDamage(const Value: Integer); procedure SetDescription(const Value: string); procedure SetDXT(const Value: Integer); procedure SetEffects(const Value: TEffects); procedure SetExp(const Value: Integer); procedure SetHP(const Value: Integer); procedure SetImageIndex(const Value: Integer); procedure SetName(const Value: string); procedure SetSh(const Value: Integer); procedure SetDungeons(const Value: string); procedure SetDungMax(const Value: Integer); procedure SetDungMin(const Value: Integer); //** Конструктор. constructor Create(); public destructor Destroy(); override; property Name: string read FName write SetName; property Description: string read FDescription write SetDescription; property DungMin: Integer read FDungMin write SetDungMin; property DungMax: Integer read FDungMax write SetDungMax; property HP: Integer read FHP write SetHP; property Exp: Integer read FExp write SetExp; property Sh: Integer read FSh write SetSh; property DXT: Integer read FDXT write SetDXT; property Damage: Integer read FDamage write SetDamage; property ImageIndex: Integer read FImageIndex write SetImageIndex; property Effects: TEffects read FEffects write SetEffects; property BMP: TBitmap read GetBMP; property AgrRadius: Integer read FAgrRadius write SetAgrRadius; // could be a boss or minion, or just any modifier, works as a list of references // (it means doesn't own) to a full list of affixes // property Affixes : TCreatureAffixes; end; TCreatures = class(TObjList) private BMPs: array[0..255] of TBitMap; function GetCreature(Index: Integer): TCreature; procedure SetCreature(Index: Integer; const Value: TCreature); protected procedure LoadCreatures(); procedure LoadGraphics(); //** Конструктор. constructor Create(); public destructor Destroy(); override; function GetRandomFitDung(Dung: Integer): Integer; property Creatures[Index: Integer]: TCreature read GetCreature write SetCreature; default; end; TMonster = class(TAI) private FCreature: TCreature; FLife: Word; FAgrRadius: Integer; FID: Integer; Bmp: TBitmap; //** Конструктор. constructor Create(Cr: TCreature; AID: Integer); destructor Destroy; override; procedure SetLife(const Value: Word); procedure SetAgrRadius(const Value: Integer); public function GetGraphic: TBitmap; override; function Move(x2, y2: Word): Boolean; override; property Life: Word read FLife write SetLife; property Creature: TCreature read FCreature; property AgrRadius: Integer read FAgrRadius write SetAgrRadius; property ID: Integer read FID; end; TActors = class(TObjList) private function GetActor(Index: integer): TActor; public function AddMob(Cr: TCreature): TMonster; function AddNPC(AScript: string = ''): TNPC; function AddProjectile(ShotType: Integer): TProjectile; property Actors[Index: integer]: TActor read GetActor; default; end; const // the possibility to push NPC wandering WanderCoef = 0.005; // the distance where npc tends to stop before he reaches the sign NpcSignDist = 1; // must be 1 or more // range of possibility to npc make a move when pc goes StartPoss = 0.2; PossRange = 0.3; // the way to get internal(in-unit) instances function Creatures(): TCreatures; function Actors(): TActors; implementation uses uVars, SysUtils, uUtils, uLog, uMap, uScript, PathFind, math, UTileMask, UMapCommon, uAdvMap; var TheCreatures: TCreatures; TheEffects: TEffects; TheActors: TActors; j: NEffect; function Creatures(): TCreatures; begin Result := TheCreatures; end; function Actors(): TActors; begin Result := TheActors; end; { TCreatures } constructor TCreatures.Create(); begin inherited Create(); Capacity := 256; LoadCreatures; LoadGraphics; end; destructor TCreatures.Destroy; var i: Integer; begin for i := 0 to 255 do FreeAndNil(Bmps[i]); inherited; end; function TCreatures.GetCreature(Index: Integer): TCreature; begin Result := TCreature(inherited Get(Index)); end; procedure TCreatures.SetCreature(Index: Integer; const Value: TCreature); begin inherited Put(Index, Value); end; procedure TCreatures.LoadCreatures; const EffNames: array[NEffect] of string = ('Poisoned', 'Blind', 'Diseased', 'Stunned', 'Bleed', 'Frozen', 'Bursted', 'Spider', 'Forest', 'Dungeon', 'Acid', 'Weak'); var i: Word; j: NEffect; S, ds: string; H: TIniFile; Cr: TCreature; // CH: Char; begin H := TIniFile.Create(Path + '\Data\Creatures.ini'); try VM.SetInt('Creatures.Count', 0); for i := 0 to 255 do begin Cr := TCreature.Create; Add(Cr); S := IntToStr(i + 1); // trying load a creature from inifile if H.SectionExists(S) then begin Cr.Name := H.ReadString(S, 'Name', ''); Cr.Description := H.ReadString(S, 'Description', ''); ds := H.ReadString(S, 'Dungeons', ''); Cr.DungMin := StrToIntDef(Copy(ds, 1, Pos('-', ds) - 1), 0); System.Delete(ds, 1, Pos('-', ds)); Cr.DungMax := StrToIntDef(ds, 100); Cr.HP := H.ReadInteger(S, 'HP', 1); Cr.Exp := H.ReadInteger(S, 'Exp', 1); Cr.Damage := H.ReadInteger(s, 'Damage', 1); Cr.SH := H.ReadInteger(S, 'Sh', 0); Cr.DXT := H.ReadInteger(S, 'DXT', 0); Cr.ImageIndex := H.ReadInteger(S, 'ImageIndex', 0); Cr.AgrRadius := H.ReadInteger(S, 'AgrRadius', 5); for j := Low(NEffect) to High(NEffect) do if H.ReadBool(S, EffNames[j], False) then Cr.Effects.Add(TheEffects[j]); VM.Inc('Creatures.Count', 1); end; end; finally Log.Log(Format('%s: %s', ['Количество существ', VM.GetStrInt('Creatures.Count')])); H.Free; end; end; function TCreatures.GetRandomFitDung(Dung: Integer): Integer; var Lst: TList; i: Integer; begin Lst := TList.Create; Lst.Capacity := Count; for i := 0 to Count - 1 do if Dung in [Creatures[i].DungMin..Creatures[i].DungMax] then Lst.Add(pointer(i)); if Lst.Count <> 0 then Result := Integer(Lst[Random(Lst.Count)]) else Result := 0; Lst.Free; end; procedure TCreatures.LoadGraphics; var i: Integer; begin for i := 0 to 255 do begin BMPs[i] := TBitmap.Create; BMPs[i].Transparent := True; BMPs[i].TransparentColor := clFuchsia; end; SplitBMP(BMPs, Path + 'Data\Images\Creatures.bmp'); end; { TCreature } constructor TCreature.Create; begin inherited; FEffects := TEffects.Create(false); end; destructor TCreature.Destroy; begin FEffects.Free; inherited; end; function TCreature.GetBMP: TBitmap; begin Result := TheCreatures.BMPs[imageindex]; end; procedure TCreature.SetAgrRadius(const Value: Integer); begin FAgrRadius := Value; end; procedure TCreature.SetDamage(const Value: Integer); begin FDamage := Value; end; procedure TCreature.SetDescription(const Value: string); begin FDescription := Value; end; procedure TCreature.SetDungeons(const Value: string); begin FDungeons := Value; end; procedure TCreature.SetDungMax(const Value: Integer); begin FDungMax := Value; end; procedure TCreature.SetDungMin(const Value: Integer); begin FDungMin := Value; end; procedure TCreature.SetDXT(const Value: Integer); begin FDXT := Value; end; procedure TCreature.SetEffects(const Value: TEffects); begin if FEffects <> nil then FEffects.free; FEffects := Value; end; procedure TCreature.SetExp(const Value: Integer); begin FExp := Value; end; procedure TCreature.SetHP(const Value: Integer); begin FHP := Value; end; procedure TCreature.SetImageIndex(const Value: Integer); begin FImageIndex := Value; end; procedure TCreature.SetName(const Value: string); begin FName := Value; end; procedure TCreature.SetSh(const Value: Integer); begin FSh := Value; end; { TEffects } function TEffects.EffectValue(Eff: NEffect): Integer; var i: Integer; begin Result := 0; i := HasEffect(Eff); if i < 0 then Exit; // (Items[i] as TEffect). //effect value end; function TEffects.GetEffects(Eff: NEffect): TEffect; begin Result := TEffect(inherited Get(Ord(Eff))); end; function TEffects.HasEffect(Eff: NEffect): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do if (Items[i] as TEffect).ID = Eff then begin Result := i; Exit; end; end; procedure TEffects.SetEffects(Eff: NEffect; const Value: TEffect); begin end; { TEffect } constructor TEffect.Create(AID: NEffect); begin inherited Create; FID := AID; end; { TMonster } constructor TMonster.Create(Cr: TCreature; AID: Integer); begin inherited Create(0, 0); FCreature := Cr; Life := cr.HP; AgrRadius := cr.AgrRadius; FID := AID; FSpeed := 1; Bmp := TBitmap.Create; end; destructor TMonster.Destroy; begin FreeAndNil(Bmp); inherited; end; function TMonster.GetGraphic: TBitmap; begin Bmp.Assign(Creature.Bmp); if IsStuned then Bmp.Canvas.Draw(0, 0, Map.Stun[(Movedelay - 2) mod Length(Map.Stun)]); result := Bmp; end; function TMonster.Move(x2, y2: Word): Boolean; var MapPath: TPath; begin Result := inherited Move(x2, y2); if not Result then Exit; MapPath := FindPath(Map.Width, Map.Height, x, y, x2, y2, MoveCost); if Length(MapPath) in [1..Max(Abs(x - x2), Abs(y - y2)) + 1] then begin Result := True; Moved := True; SetXY(MapPath[1].x, MapPath[1].y); // mob opens door if Map.MapObj[x, y] in [64..71] then Map.MapObj[x, y] := Map.MapObj[x, y] + 8; end else Result := False; end; procedure TMonster.SetAgrRadius(const Value: Integer); begin FAgrRadius := Value; end; procedure TMonster.SetLife(const Value: Word); begin FLife := Value; end; { TMonsters } function TActors.AddMob(Cr: TCreature): Tmonster; begin Result := TMonster.Create(cr, Count + 1); Add(Result); end; function TActors.AddNPC(AScript: string = ''): TNPC; begin Result := TNPC.Create(Count + 1, AScript); Add(Result); end; function TActors.AddProjectile(ShotType: Integer): TProjectile; begin Result := nil; // just turn off warning case ShotType of 1: Result := TArrow.Create(0, 0); 2: Result := TFireBall.Create(); else Assert(False); end; Add(Result); end; function TActors.GetActor(Index: integer): TActor; begin Result := TActor(inherited Get(Index)); end; { TActor } constructor TActor.Create(AX, AY: Word); begin end; procedure TActor.Die; begin Actors.remove(Map.MapDyn[x, y]); Map.MapDyn[x, y] := nil; end; function TActor.GetGraphic: Tbitmap; begin Result := nil; end; function TActor.Move(x2, y2: Word): Boolean; begin Result := False; end; procedure TActor.SetXY(AX, AY: Integer); begin if Map.MapDyn[x, y] = Self then Map.MapDyn[x, y] := nil; FX := AX; FY := AY; Map.MapDyn[x, y] := Self; end; { TNPC } constructor TNPC.Create(AID: Integer; AScript: string = ''); begin inherited Create(0, 0); FID := AID; FSpeed := StartPoss + PossRange * Random; end; procedure TNPC.ExecScript; begin if (Strparams[npScript] = '') and (Strparams[npDialog] = '') then Run('Quests\EmptyDialog.pas') else begin VM.SetStr('NPC.Name', Strparams[npName]); VM.SetStr('NPC.Portrait', Strparams[npPortrait]); VM.SetStr('NPC.TradeType', Strparams[npTradeType]); if (Strparams[npDialog] <> '') then Run('begin Dialog(''' + Strparams[npDialog] + ''', ''''); end') else Run('Quests\' + Strparams[npScript]); end; end; function TNPC.GetGraphic: TBitmap; var I: Integer; begin if NPCID = 0 then Result := Map.MapObjects[11] else begin Result := NPCConfig.bmps[strtoint(NPCConfig.Items[npcid, npobjimgid])]; I := StrToInt(NPCConfig.Items[npcid, npTradeType]); if (I > 0) and (I <= 8) then begin PP[I - 1].Transparent := True; Result.Canvas.Draw(0, 0, PP[I - 1]); end; end; end; function TNPC.GetIntParams(Index: NNpcParam): Integer; begin Result := Strtoint(NPCConfig.Items[NPCID, Index]); end; function TNPC.GetStrParams(Index: NNpcParam): string; begin Result := NPCConfig.Items[NPCID, Index]; end; function TNPC.Move(x2, y2: Word): Boolean; var MapPath: TPath; AX, AY: Integer; begin Result := inherited Move(x2, y2); if not FIsWandering or (FSpeed < Random) then Exit; MapPath := FindPath(Map.Width, Map.Height, x, y, x2, y2, MoveCost); if (Length(MapPath) > NpcSignDist) then begin Result := True; Moved := True; AX := MapPath[1].x; AY := MapPath[1].Y; if Map.isHeroCell(AX, AY) or (Map.mapDyn[AX, AY] <> nil) then Exit; SetXY(AX, AY); // mob opens door if Map.MapObj[fx, fy] in [64..71] then Map.MapObj[x, y] := Map.MapObj[x, y] + 8; end else begin if Length(MapPath) in [1..NpcSignDist] then // any except 0 FIsWandering := False; Result := False; end; end; procedure TNPC.SetMoved(const Value: Boolean); begin inherited; SetupWander(); end; procedure TNPC.SetNPCID(const Value: Integer); begin FNPCID := Value; end; procedure TNPC.SetupWander; var pt, us: TPoint; cnt: integer; PntList: TList; I, w: Integer; begin if not FIsWandering and (Random < WanderCoef * IntParams[npWanderRatio]) then begin PntList := TList.Create; if not IsSpecWanderModel(StrParams[npWanderModel]) then begin PntList.Capacity := SignList.Count; for I := 0 to SignList.Count - 1 do PntList.Add(Pointer(I + 1)); // make list of all signs Ids, ids start from 1 end else for I := 0 to SignList.Count - 1 do begin if TryStrToInt(NPCConfig.Read(Format('%d%s%s%d', [NPCId, NPCConfig.Delim, 'Point', i + 1])), w) then PntList.Add(Pointer(w)); // make list of sign Ids stored in npcconfig end; us := Point(FX, FY); Pt := us; cnt := 0; I := 0; while (PointsEqual(pt, us)) and (cnt < 10) do begin case NWanderModel(GetEnumValue(TypeInfo(NWanderModel), StrParams[npWanderModel])) of wmStand:; wmRandom, wmSpec: // random uses full signlist, spec only stored I := Integer(PntList[Random(PntList.Count)]); wmHost: // more of 50% of chance npc goes to his home - first signID in npcconfig if Random(2) = 1 then i := Integer(PntList[Random(PntList.Count)]) else I := Integer(PntList[0]); wmGuard: // Goes to next sign in his list, patrols thru signs begin I := signlist.Find(FX, FY, fpID); // current position as signID under npc if i <= 0 then I := Integer(PntList[0]) else I := Integer(PntList[(PntList.IndexOf(Pointer(i)) + 1) mod PntList.Count]); end; end; if i > 0 then begin if signlist.FindItemByID(i) = nil then begin Inc(cnt); Continue; end; pt := signlist.FindItemByID(i).ToPoint(); end; Inc(cnt); end; FIsWandering := not PointsEqual(pt, us); if FIsWandering then FDest := pt; FreeAndNil(PntList); end; end; function TNPC.Movecost(x, y, Direction: smallint): Smallint; begin // if door or passable if Map.CellMask(x, y, cmpassable) or (Map.MapObj[x, y] in [12, 55, 63..79]) then Result := 2 else Result := -1; // if no actor and (no obj or hero) if (Result <> -1) and ((Map.mapDyn[x, y] = nil) or ((x = fdest.x) and (y = fdest.y))) and ((Map.MapObj[x, y] in [0, 12, 55, 63..79]) or Map.IsHeroCell(x, y)) then Result := 2 else Result := -1; if (Result <> -1) and Odd(Direction) then Result := Result + Result div 2; end; { TAI } function TAI.GetIsStuned: Boolean; begin Result := MoveDelay > 1; end; function TAI.GetMoved: Boolean; begin Result := MoveDelay <> 0; end; procedure TAI.ModifyMoveDelay(const Value: Integer); const MaxStunValue = 10; begin FMoveDelay := Clamp(MoveDelay + Value, 0, MaxStunValue); end; function TAI.Move(x2, y2: Word): Boolean; begin Result := inherited Move(x2, y2) or not Moved; end; function TAI.Movecost(x, y, Direction: smallint): Smallint; begin // if door or passable if Map.CellMask(x, y, cmpassable) or (Map.MapObj[x, y] in [12, 55, 63..79]) then Result := 2 else Result := -1; // if no actor and (no obj or hero) if (Result <> -1) and (Map.mapDyn[x, y] = nil) and ((Map.MapObj[x, y] in [0, 12, 55, 63..79]) or Map.IsHeroCell(x, y)) then Result := 2 else Result := -1; if (Result <> -1) and Odd(Direction) then Result := Result + Result div 2; end; procedure TAI.SetMoved(const Value: Boolean); begin ModifyMoveDelay(Ord(Value) * 2 - 1); end; procedure TAI.SetMoveDelay(const Value: Integer); begin FMoveDelay := Value; end; { TArrow } function TArrow.GetGraphic: TBitmap; var BmpId: Integer; begin BmpId := 8; case Delta.X of -1: BmpId := 7 - (Delta.y + 1); 0: BmpId := (Delta.y + 1) * 2; 1: BmpId := Delta.y + 2; end; Result := Map.Shots[BmpId]; end; { TProjectile } function TProjectile.Move(x2, y2: Word): Boolean; //var // MapPath: TPath; // AX, AY: Integer; begin Result := inherited Move(x2, y2); SetXY(x2, y2); // Run('ShotInteract'); end; procedure TProjectile.SetDelta(const Value: TPoint); begin FDelta := Value; end; { TFireBall } constructor TFireBall.Create; begin inherited Create(0, 0); FLightId := Map.Lights.Add(TLightSource.Create(0, 0, 3, self)); end; destructor TFireBall.Destroy; begin Map.Lights.Delete(FLightId); inherited; end; function TFireBall.GetGraphic: TBitmap; begin Result := Map.Fireball[FFrame]; end; procedure TFireBall.SetXY(AX, AY: Integer); begin inherited; FFrame := (FFrame + 1) mod (Length(Map.Fireball) - 2); // last usual cadre, the actual last is "bang" Inc(FLife); if Flife > 40 then // suicide if projectile lives too long Die(); end; initialization TheEffects := TEffects.Create; for j := Low(NEffect) to High(NEffect) do TheEffects.Add(TEffect.Create(j)); TheCreatures := TCreatures.Create; TheActors := TActors.Create; finalization TheCreatures.Free; TheEffects.Free; TheActors.Free; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.LinkedLabel.Mac; interface uses System.Classes, FMX.Platform, FGX.LinkedLabel; type { TMacLaunchService } TMacLaunchService = class sealed (TInterfacedObject, IFGXLaunchService) public { IFMXLaunchService } function OpenURL(const AUrl: string): Boolean; end; procedure RegisterService; procedure UnregisterService; implementation uses Macapi.Foundation, Macapi.AppKit; { TWinLaunchService } function TMacLaunchService.OpenURL(const AUrl: string): Boolean; var Workspace: NSWorkspace; Url: NSURL; begin Workspace := TNSWorkspace.Wrap(TNSWorkspace.OCClass.sharedWorkspace); Url := TNSUrl.Wrap(TNSUrl.OCClass.URLWithString(NSStr(AUrl))); Result := Workspace.openURL(Url); end; procedure RegisterService; begin TPlatformServices.Current.AddPlatformService(IFGXLaunchService, TMacLaunchService.Create); end; procedure UnregisterService; begin TPlatformServices.Current.RemovePlatformService(IFGXLaunchService); end; end.
program deepred; {$mode objfpc}{$H+} uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes, SysUtils, DaemonApp, inifiles, dr_server, pascalscriptfcl, dr_api, dr_script; type TCustomDeepRedServer = class (TDeepRedServer) protected procedure WriteLog(evType : TEventType; const msg : string); override; end; TDeepRedDaemon = class (TCustomDaemon) private _server : TCustomDeepRedServer; _log : TFileStream; procedure AWriteln(evtype : TEventType; const msg : string); public //Daemon control function Start : boolean; override; function Stop : boolean; override; function Shutdown : boolean; override; function Install : boolean; override; function Execute : boolean; override; end; TDeepRedDaemonMapper = class (TCustomDaemonMapper) constructor Create(AOwner : TComponent); override; end; //============================================================================== // TDeepRedDaemonMapper //============================================================================== constructor TDeepRedDaemonMapper.Create(AOwner : TComponent); var d : TDaemonDef; begin inherited Create(AOwner); d:=DaemonDefs.Add as TDaemonDef; d.Options:=[doAllowStop]; d.DisplayName:='DeepRed Server'; d.Name:='DeepRedDaemon'; d.DaemonClassName:='TDeepRedDaemon'; d.WinBindings.ServiceType:=stWin32; end; //============================================================================== // TDeepRedDaemon //============================================================================== function TDeepRedDaemon.Start : boolean; var iniFile : TIniFile; //bindings : TStringList; i : cardinal; str : string; begin //**************************************************** //Daemon configuration section //**************************************************** //_log := TFileStream.Create('deepred.log',fmOpenWrite); if not FileExists(ChangeFileExt(Application.ExeName,'.conf')) then begin AWriteln(etError,'DeepRed Daemon : no configuration file found! you must have a '+ ChangeFileExt(ExtractFileName(Application.ExeName),'.conf')+ ' inside the daemon''s executable directory ...'); exit(false); end; Result := inherited Start; if not Result then begin AWriteln(etError,'DeepRed Daemon : cannot instanciate daemon!'); exit(false); end; AWriteln(etInfo,'DeepRed Daemon : starting ...'); iniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.conf')); (* _server := TDeepRedServer.Create(iniFile.ReadInteger('Repository','Port',61993), iniFile.ReadInteger('Repository','TerminateWaitTime',5000), iniFile.ReadInteger('Repository','MaxConnections',20), iniFile.ReadString('SQLite','Host','xswag.db')); if _server.Error <> '' then AWriteln(etError,'DeepRed Daemon : '+_server.Error); _server.SetMOTD(iniFile.ReadString('Repository','MOTD','')); _server.SetPathToArchives(iniFile.ReadString('Repository','PathToArchives','.')); _server.ClearBindings;*) //iniFile.ReadSectionRaw('Bindings',bindings); iniFile.Free; //**************************************************** _server := TCustomDeepRedServer.Create('brookapi.cfg',''); //_server.StartServer; AWriteln(etInfo,'DeepRed Daemon : started.'); end; function TDeepRedDaemon.Stop : boolean; var serverr: string; begin try _server.StopServer; serverr := _server.Error; _server.Free; //_log.Free; except if serverr <> '' then AWriteln(etError,'DeepRed Daemon : Server reported the following error : '+serverr); end; AWriteln(etInfo,'DeepRed Daemon : stopped.'); {$IFDEF WINDOWS} // _log.Free; {$ELSE} {$ENDIF} result := inherited Stop; end; function TDeepRedDaemon.Shutdown : boolean; begin AWriteln(etInfo,'DeepRed Daemon : shutdown required.'); try //_server.Free; Result := inherited Shutdown; finally Application.Terminate; end; end; function TDeepRedDaemon.Install : boolean; begin result := inherited Install; AWriteln(etInfo,'DeepRed Daemon : installed.'); end; function TDeepRedDaemon.Execute : boolean; begin result := inherited Execute; //AWriteln(etInfo,'DeepRed Daemon : running.'); end; procedure TDeepRedDaemon.AWriteln(evType : TEventType; const msg : string); var str : string; begin case evType of etInfo : str := '[INFO] '+msg; etWarning : str := '[WARN] '+msg; etError : str := '[ERROR] '+msg; etDebug : str := '[DEBUG] '+msg; end; (* _log.Write(str,length(str)); _log.WriteByte(10); _log.WriteByte(13); *) Application.Log(evType,msg); end; //============================================================================== // TCustomDeepRedServer //============================================================================== procedure TCustomDeepRedServer.WriteLog(evType : TEventType; const msg : string); var str : string; begin case evType of etInfo : str := '[INFO] [DeepRedServer] '+msg; etWarning : str := '[WARN] [DeepRedServer] '+msg; etError : str := '[ERROR] [DeepRedServer] '+msg; etDebug : str := '[DEBUG] [DeepRedServer] '+msg; end; Application.Log(evType,msg); end; //============================================================================== // M A I N //============================================================================== {$R *.res} begin RegisterDaemonClass(TDeepRedDaemon); RegisterDaemonMapper(TDeepRedDaemonMapper); Application.Title:='Deep Red'; Application.Run; end.
unit GX_eSelectIdentifier; interface implementation uses Classes, GX_EditorExpert, GX_OtaUtils; type TSelectIdentifierExpert = class(TEditorExpert) protected function GetDisplayName: string; override; class function GetName: string; override; public constructor Create; override; function GetDefaultShortCut: TShortCut; override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; procedure Execute(Sender: TObject); override; end; { TSelectIdentifierExpert } constructor TSelectIdentifierExpert.Create; begin inherited; end; procedure TSelectIdentifierExpert.Execute(Sender: TObject); begin GxOtaSelectCurrentIdent(GxOtaGetCurrentSourceEditor); end; function TSelectIdentifierExpert.GetDefaultShortCut: TShortCut; begin Result := scShift + scAlt + Ord('I'); end; function TSelectIdentifierExpert.GetDisplayName: string; resourcestring SSelectIdentName = 'Select Identifier'; begin Result := SSelectIdentName; end; function TSelectIdentifierExpert.GetHelpString: string; resourcestring SSelectIdentHelp = ' This expert selects the identifier under the edit cursor.'; begin Result := SSelectIdentHelp; end; class function TSelectIdentifierExpert.GetName: string; begin Result := 'SelectIdent'; end; function TSelectIdentifierExpert.HasConfigOptions: Boolean; begin Result := False; end; initialization RegisterEditorExpert(TSelectIdentifierExpert); end.
unit uDlgCollision; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TdlgFileCollision = class(TForm) btnOverwrite: TButton; btnRename: TButton; btnAbort: TButton; lbMessage: TLabel; Image1: TImage; private { Private-Deklarationen } public { Public-Deklarationen } class function Execute(var FileName: string): boolean; end; var dlgFileCollision: TdlgFileCollision; implementation uses Consts; {$R *.dfm} { TdlgFileCollision } function FindFreeName(const fn: string): String; var p,n,e: String; i: integer; begin p:= ExtractFilePath(fn); n:= ChangeFileExt(ExtractFileName(fn),''); e:= ExtractFileExt(fn); Result:= fn; i:= 1; while FileExists(Result) do begin Result:= IncludeTrailingPathDelimiter(p) + n + '('+IntToStr(i)+')' + e; inc(i); end; end; class function TdlgFileCollision.Execute(var FileName: string): boolean; var alterName: string; begin Result:= false; with TdlgFileCollision.Create(Application) do try Caption:= SMsgDlgConfirm; Image1.Picture.Icon.Handle:= LoadIcon(0, IDI_QUESTION); alterName:= FindFreeName(FileName); lbMessage.Caption:= format(lbMessage.Caption, [FileName]); btnRename.Hint:= alterName; case ShowModal of mrYes: begin // overwrite Result:= true; end; mrOk: begin // rename FileName:= alterName; Result:= true; end; mrCancel: begin //cancel Result:= false; end; end; finally Release; end; end; end.
unit evdTasksHelpers; // Модуль: "w:\common\components\rtl\Garant\EVD\evdTasksHelpers.pas" // Стереотип: "UtilityPack" // Элемент модели: "evdTasksHelpers" MUID: (53BD13B4023B) {$Include w:\common\components\rtl\Garant\EVD\evdDefine.inc} interface uses l3IntfUses , l3Interfaces , l3LongintList , Classes , l3ProtoObject , l3Variant , k2SizedMemoryPool ; (* MIntegerListTransformator = interface procedure ToList(aDest: Tl3LongintList); procedure FromList(aSource: Tl3LongintList); overload; procedure FromList(const aSource: Il3IntegerList); overload; function AsIntegerList: Il3IntegerList; end;//MIntegerListTransformator *) type DocumentIDListHelper = interface ['{0ACFDC6E-9BDD-4EE0-AA18-98EE006B7348}'] function Get_Count: Integer; function Get_Items(anIndex: Integer): Integer; procedure Save(aStream: TStream); procedure Load(aStream: TStream); procedure Clear; procedure Add(anItem: Integer); procedure Remove(anItem: Integer); procedure ToList(aDest: Tl3LongintList); procedure FromList(aSource: Tl3LongintList); overload; procedure FromList(const aSource: Il3IntegerList); overload; function AsIntegerList: Il3IntegerList; property Count: Integer read Get_Count; property Items[anIndex: Integer]: Integer read Get_Items; end;//DocumentIDListHelper StringListHelper = interface ['{F19CA673-59AD-46E7-8D1F-58BD23E54A95}'] function Get_Count: Integer; function Get_Strings(anIndex: Integer): AnsiString; procedure Add(const anItem: AnsiString); procedure CopyTo(aDest: TStrings); procedure CopyFrom(aSource: TStrings); property Count: Integer read Get_Count; property Strings[anIndex: Integer]: AnsiString read Get_Strings; default; end;//StringListHelper TevdTagHelper = class(Tl3ProtoObject) private f_Value: Tl3Tag; protected procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(aValue: Tl3Tag); reintroduce; protected property Value: Tl3Tag read f_Value; end;//TevdTagHelper SABStreamHelper = interface(DocumentIDListHelper) ['{92B4DB96-8C8E-45B8-975A-CC383649BD96}'] function Get_Size: Int64; procedure CopyFrom(Source: TStream; Count: Int64); procedure CopyTo(Dest: TStream; Count: Int64); property Size: Int64 read Get_Size; end;//SABStreamHelper TAbstractStringListHelper = class(TevdTagHelper, StringListHelper) protected procedure DoAdd(const anItem: AnsiString); virtual; abstract; function DoGetStrings(anIndex: Integer): AnsiString; virtual; abstract; function Get_Count: Integer; function Get_Strings(anIndex: Integer): AnsiString; procedure Add(const anItem: AnsiString); procedure CopyTo(aDest: TStrings); procedure CopyFrom(aSource: TStrings); end;//TAbstractStringListHelper RegionIDListHelper = DocumentIDListHelper; TasksIDListHelper = interface(StringListHelper) ['{252940D3-C632-4B3D-97A5-04EB9A3533A9}'] end;//TasksIDListHelper FoundSelectorHelper = interface ['{1749A04B-EF51-4902-94EC-4AB11093E526}'] function Get_Count: Integer; procedure Add(aPara: LongInt; aWord: Word; aDocument: LongInt); procedure GetValue(anIndex: Integer; out thePara: LongInt; out theWord: Word; out theDocument: LongInt); property Count: Integer read Get_Count; end;//FoundSelectorHelper AccGroupsIDListHelper = DocumentIDListHelper; RejectedIDListHelper = interface ['{DF923F97-69D2-4740-AC73-ED1ECA2C5207}'] function Get_Count: Integer; procedure Add(anID: Cardinal; const aComment: AnsiString); procedure GetValue(anIndex: Integer; out theID: Cardinal; out theComment: AnsiString); property Count: Integer read Get_Count; end;//RejectedIDListHelper TDocumentIDListHelper = class(TevdTagHelper, DocumentIDListHelper) protected procedure Save(aStream: TStream); procedure Load(aStream: TStream); procedure Clear; procedure Add(anItem: Integer); procedure Remove(anItem: Integer); function Get_Count: Integer; function Get_Items(anIndex: Integer): Integer; public class function Make(aValue: Tl3Tag): DocumentIDListHelper; reintroduce; procedure ToList(aDest: Tl3LongintList); procedure FromList(aSource: Tl3LongintList); overload; procedure FromList(const aSource: Il3IntegerList); overload; function AsIntegerList: Il3IntegerList; end;//TDocumentIDListHelper ImportedDocListHelper = DocumentIDListHelper; TSourceIDListHelper = TDocumentIDListHelper; SourceIDListHelper = DocumentIDListHelper; TDossierSourceIDListHelper = TDocumentIDListHelper; DossierSourceIDListHelper = DocumentIDListHelper; TDocTypesIDListHelper = TDocumentIDListHelper; DocTypesIDListHelper = DocumentIDListHelper; TFASSourceIDListHelper = TDocumentIDListHelper; FASSourceIDListHelper = DocumentIDListHelper; TRegionIDListHelper = TDocumentIDListHelper; TBelongsIDListHelper = TDocumentIDListHelper; BelongsIDListHelper = DocumentIDListHelper; ExcludeAccGroupsIDListHelper = DocumentIDListHelper; TExcludeAccGroupsIDListHelper = TDocumentIDListHelper; CommentsIDListHelper = DocumentIDListHelper; TCommentsIDListHelper = TDocumentIDListHelper; ExcludeDocTypesIDListHelper = DocumentIDListHelper; TExcludeDocTypesIDListHelper = TDocumentIDListHelper; ExcludeDocBasesIDListHelper = DocumentIDListHelper; TExcludeDocBasesIDListHelper = TDocumentIDListHelper; BasesIDListHelper = DocumentIDListHelper; TBasesIDListHelper = TDocumentIDListHelper; TInfoIDListHelper = TDocumentIDListHelper; InfoIDListHelper = DocumentIDListHelper; TSABStreamHelper = class(TDocumentIDListHelper, SABStreamHelper) protected function Get_Size: Int64; public class function Make(aValue: Tl3Tag): SABStreamHelper; reintroduce; procedure CopyFrom(Source: TStream; Count: Int64); procedure CopyTo(Dest: TStream; Count: Int64); end;//TSABStreamHelper TTasksIDListHelper = class(TAbstractStringListHelper, TasksIDListHelper) protected procedure DoAdd(const anItem: AnsiString); override; function DoGetStrings(anIndex: Integer): AnsiString; override; public class function Make(aValue: Tl3Tag): TasksIDListHelper; reintroduce; end;//TTasksIDListHelper TAccGroupsIDListHelper = TDocumentIDListHelper; TFoundSelectorHelper = class(TevdTagHelper, FoundSelectorHelper) protected function Get_Count: Integer; procedure Add(aPara: LongInt; aWord: Word; aDocument: LongInt); procedure GetValue(anIndex: Integer; out thePara: LongInt; out theWord: Word; out theDocument: LongInt); public class function Make(aValue: Tl3Tag): FoundSelectorHelper; reintroduce; end;//TFoundSelectorHelper TImportedDocListHelper = TDocumentIDListHelper; TRejectedIDListHelper = class(TevdTagHelper, RejectedIDListHelper) protected function Get_Count: Integer; procedure Add(anID: Cardinal; const aComment: AnsiString); procedure GetValue(anIndex: Integer; out theID: Cardinal; out theComment: AnsiString); public class function Make(aValue: Tl3Tag): RejectedIDListHelper; reintroduce; end;//TRejectedIDListHelper AttributesHelper = DocumentIDListHelper; TAttributesHelper = TDocumentIDListHelper; implementation uses l3ImplUses , SysUtils , Address_Const , k2Tags , l3InterfacedIntegerList , TaskID_Const , FoundSelector_Const , DocIDWithComment_Const //#UC START# *53BD13B4023Bimpl_uses* //#UC END# *53BD13B4023Bimpl_uses* ; constructor TevdTagHelper.Create(aValue: Tl3Tag); //#UC START# *53BD1BCF010B_53BFD54A01CC_var* //#UC END# *53BD1BCF010B_53BFD54A01CC_var* begin //#UC START# *53BD1BCF010B_53BFD54A01CC_impl* inherited Create; f_Value := aValue; // - пока БЕЗ счётчика ссылок, пока НЕ НАЖРЁМСЯ //#UC END# *53BD1BCF010B_53BFD54A01CC_impl* end;//TevdTagHelper.Create procedure TevdTagHelper.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_53BFD54A01CC_var* //#UC END# *479731C50290_53BFD54A01CC_var* begin //#UC START# *479731C50290_53BFD54A01CC_impl* inherited; //#UC END# *479731C50290_53BFD54A01CC_impl* end;//TevdTagHelper.Cleanup function TAbstractStringListHelper.Get_Count: Integer; //#UC START# *53BFCD4C03BF_53EDDCC203B4get_var* //#UC END# *53BFCD4C03BF_53EDDCC203B4get_var* begin //#UC START# *53BFCD4C03BF_53EDDCC203B4get_impl* Result := f_Value.ChildrenCount; //#UC END# *53BFCD4C03BF_53EDDCC203B4get_impl* end;//TAbstractStringListHelper.Get_Count function TAbstractStringListHelper.Get_Strings(anIndex: Integer): AnsiString; //#UC START# *53BFCD5501FC_53EDDCC203B4get_var* //#UC END# *53BFCD5501FC_53EDDCC203B4get_var* begin //#UC START# *53BFCD5501FC_53EDDCC203B4get_impl* Result := DoGetStrings(anIndex); //#UC END# *53BFCD5501FC_53EDDCC203B4get_impl* end;//TAbstractStringListHelper.Get_Strings procedure TAbstractStringListHelper.Add(const anItem: AnsiString); //#UC START# *53BFCD800222_53EDDCC203B4_var* //#UC END# *53BFCD800222_53EDDCC203B4_var* begin //#UC START# *53BFCD800222_53EDDCC203B4_impl* DoAdd(anItem); //#UC END# *53BFCD800222_53EDDCC203B4_impl* end;//TAbstractStringListHelper.Add procedure TAbstractStringListHelper.CopyTo(aDest: TStrings); //#UC START# *53BFCDAA0388_53EDDCC203B4_var* var l_Index : Integer; //#UC END# *53BFCDAA0388_53EDDCC203B4_var* begin //#UC START# *53BFCDAA0388_53EDDCC203B4_impl* aDest.Clear; for l_Index := 0 to Pred(f_Value.ChildrenCount) do aDest.Add(Self.Get_Strings(l_Index)); //#UC END# *53BFCDAA0388_53EDDCC203B4_impl* end;//TAbstractStringListHelper.CopyTo procedure TAbstractStringListHelper.CopyFrom(aSource: TStrings); //#UC START# *53BFCE310249_53EDDCC203B4_var* var l_Index : Integer; //#UC END# *53BFCE310249_53EDDCC203B4_var* begin //#UC START# *53BFCE310249_53EDDCC203B4_impl* f_Value.DeleteChildren; for l_Index := 0 to Pred(aSource.Count) do Self.Add(aSource[l_Index]); //#UC END# *53BFCE310249_53EDDCC203B4_impl* end;//TAbstractStringListHelper.CopyFrom class function TDocumentIDListHelper.Make(aValue: Tl3Tag): DocumentIDListHelper; var l_Inst : TDocumentIDListHelper; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TDocumentIDListHelper.Make procedure TDocumentIDListHelper.Save(aStream: TStream); //#UC START# *53BD20D702C0_53BD13DC0048_var* var l_List : Tl3LongintList; //#UC END# *53BD20D702C0_53BD13DC0048_var* begin //#UC START# *53BD20D702C0_53BD13DC0048_impl* l_List := Tl3LongintList.Create; try Self.ToList(l_List); l_List.Save(aStream); finally FreeAndNil(l_List); end;//try..finally //#UC END# *53BD20D702C0_53BD13DC0048_impl* end;//TDocumentIDListHelper.Save procedure TDocumentIDListHelper.Load(aStream: TStream); //#UC START# *53BD20ED0368_53BD13DC0048_var* var l_List : Tl3LongintList; //#UC END# *53BD20ED0368_53BD13DC0048_var* begin //#UC START# *53BD20ED0368_53BD13DC0048_impl* Clear; l_List := Tl3LongintList.Create; try l_List.Load(aStream); Self.FromList(l_List); finally FreeAndNil(l_List); end;//try..finally //#UC END# *53BD20ED0368_53BD13DC0048_impl* end;//TDocumentIDListHelper.Load procedure TDocumentIDListHelper.Clear; //#UC START# *53BD214603DA_53BD13DC0048_var* //#UC END# *53BD214603DA_53BD13DC0048_var* begin //#UC START# *53BD214603DA_53BD13DC0048_impl* f_Value.DeleteChildren; //#UC END# *53BD214603DA_53BD13DC0048_impl* end;//TDocumentIDListHelper.Clear procedure TDocumentIDListHelper.Add(anItem: Integer); //#UC START# *53BD216B039D_53BD13DC0048_var* var l_Addr : Tl3Tag; //#UC END# *53BD216B039D_53BD13DC0048_var* begin //#UC START# *53BD216B039D_53BD13DC0048_impl* l_Addr := k2_typAddress.MakeTag.AsObject; l_Addr.IntA[k2_tiDocID] := anItem; f_Value.AddChild(l_Addr); //#UC END# *53BD216B039D_53BD13DC0048_impl* end;//TDocumentIDListHelper.Add procedure TDocumentIDListHelper.Remove(anItem: Integer); //#UC START# *53BD267000B9_53BD13DC0048_var* var l_Child : Tl3Tag; //#UC END# *53BD267000B9_53BD13DC0048_var* begin //#UC START# *53BD267000B9_53BD13DC0048_impl* l_Child := f_Value.rAtomEx([k2_tiChildren, k2_tiDocID, anItem]); //Assert(l_Child.IsValid); if l_Child.IsValid then f_Value.DeleteChild(l_Child); //#UC END# *53BD267000B9_53BD13DC0048_impl* end;//TDocumentIDListHelper.Remove function TDocumentIDListHelper.Get_Count: Integer; //#UC START# *53BD303603B8_53BD13DC0048get_var* //#UC END# *53BD303603B8_53BD13DC0048get_var* begin //#UC START# *53BD303603B8_53BD13DC0048get_impl* Result := f_Value.ChildrenCount; //#UC END# *53BD303603B8_53BD13DC0048get_impl* end;//TDocumentIDListHelper.Get_Count function TDocumentIDListHelper.Get_Items(anIndex: Integer): Integer; //#UC START# *53BD303C009F_53BD13DC0048get_var* //#UC END# *53BD303C009F_53BD13DC0048get_var* begin //#UC START# *53BD303C009F_53BD13DC0048get_impl* Result := f_Value.Child[anIndex].IntA[k2_tiDocID]; //#UC END# *53BD303C009F_53BD13DC0048get_impl* end;//TDocumentIDListHelper.Get_Items procedure TDocumentIDListHelper.ToList(aDest: Tl3LongintList); //#UC START# *53DA2FCA03C8_53BD13DC0048_var* var l_Index : Integer; //#UC END# *53DA2FCA03C8_53BD13DC0048_var* begin //#UC START# *53DA2FCA03C8_53BD13DC0048_impl* aDest.Clear; for l_Index := 0 to Pred(f_Value.ChildrenCount) do aDest.Add(f_Value.Child[l_Index].IntA[k2_tiDocID]); //#UC END# *53DA2FCA03C8_53BD13DC0048_impl* end;//TDocumentIDListHelper.ToList procedure TDocumentIDListHelper.FromList(aSource: Tl3LongintList); //#UC START# *53DA307D03A7_53BD13DC0048_var* var l_Index : Integer; //#UC END# *53DA307D03A7_53BD13DC0048_var* begin //#UC START# *53DA307D03A7_53BD13DC0048_impl* Self.Clear; if Assigned(aSource) then for l_Index := 0 to Pred(aSource.Count) do Self.Add(aSource.Items[l_Index]); //#UC END# *53DA307D03A7_53BD13DC0048_impl* end;//TDocumentIDListHelper.FromList procedure TDocumentIDListHelper.FromList(const aSource: Il3IntegerList); //#UC START# *53DA30A10113_53BD13DC0048_var* var l_Index : Integer; //#UC END# *53DA30A10113_53BD13DC0048_var* begin //#UC START# *53DA30A10113_53BD13DC0048_impl* Self.Clear; if Assigned(aSource) then for l_Index := 0 to Pred(aSource.Count) do Self.Add(aSource.Items[l_Index]); //#UC END# *53DA30A10113_53BD13DC0048_impl* end;//TDocumentIDListHelper.FromList function TDocumentIDListHelper.AsIntegerList: Il3IntegerList; //#UC START# *53DA30C501BC_53BD13DC0048_var* var l_List : Tl3InterfacedIntegerList; l_Index : Integer; //#UC END# *53DA30C501BC_53BD13DC0048_var* begin //#UC START# *53DA30C501BC_53BD13DC0048_impl* l_List := Tl3InterfacedIntegerList.Create; try Result := l_List; for l_Index := 0 to Pred(f_Value.ChildrenCount) do l_List.Add(f_Value.Child[l_Index].IntA[k2_tiDocID]); finally FreeAndNil(l_List); end;//try..finally //#UC END# *53DA30C501BC_53BD13DC0048_impl* end;//TDocumentIDListHelper.AsIntegerList class function TSABStreamHelper.Make(aValue: Tl3Tag): SABStreamHelper; var l_Inst : TSABStreamHelper; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TSABStreamHelper.Make procedure TSABStreamHelper.CopyFrom(Source: TStream; Count: Int64); //#UC START# *53B55ED6016D_53BD48A2009C_var* var l_Pos : Int64; l_Count : Integer; l_CountToRead : Integer; l_Index : Integer; l_Item : Integer; //#UC END# *53B55ED6016D_53BD48A2009C_var* begin //#UC START# *53B55ED6016D_53BD48A2009C_impl* Clear; if (Count > 0) then begin l_Pos := Source.Position; try Source.ReadBuffer(l_Count, SizeOf(l_Count)); finally Source.Position := l_Pos; end;//try..finally if (l_Count = Count) then // - НОВЫЙ ФОРМАТ, читаем как список целых Load(Source) else begin // - СТАРЫЙ ФОРМАТ, читаем как "сырой поток" целых Assert(Count mod 4 = 0, 'Размер списка целыех не кратен размеру целого'); Assert(Source.Size - l_Pos > Count, 'Размер списка целых меньше оставшегося размера потока'); l_CountToRead := Count div 4; for l_Index := 0 to Pred(l_CountToRead) do begin Source.ReadBuffer(l_Item, SizeOf(l_Item)); Self.Add(l_Item); end;//for l_Index end;//l_Count = Count end;//Count > 0 //#UC END# *53B55ED6016D_53BD48A2009C_impl* end;//TSABStreamHelper.CopyFrom procedure TSABStreamHelper.CopyTo(Dest: TStream; Count: Int64); //#UC START# *53B55EF0025D_53BD48A2009C_var* //#UC END# *53B55EF0025D_53BD48A2009C_var* begin //#UC START# *53B55EF0025D_53BD48A2009C_impl* if (Count > 0) then Save(Dest); //#UC END# *53B55EF0025D_53BD48A2009C_impl* end;//TSABStreamHelper.CopyTo function TSABStreamHelper.Get_Size: Int64; //#UC START# *53BD52D902BE_53BD48A2009Cget_var* //#UC END# *53BD52D902BE_53BD48A2009Cget_var* begin //#UC START# *53BD52D902BE_53BD48A2009Cget_impl* Result := Get_Count; //#UC END# *53BD52D902BE_53BD48A2009Cget_impl* end;//TSABStreamHelper.Get_Size class function TTasksIDListHelper.Make(aValue: Tl3Tag): TasksIDListHelper; var l_Inst : TTasksIDListHelper; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TTasksIDListHelper.Make procedure TTasksIDListHelper.DoAdd(const anItem: AnsiString); //#UC START# *53EDDCE10317_54646EB103D5_var* var l_ID : Tl3Tag; //#UC END# *53EDDCE10317_54646EB103D5_var* begin //#UC START# *53EDDCE10317_54646EB103D5_impl* l_ID := k2_typTaskID.MakeTag.AsObject; l_ID.StrA[k2_tiName] := anItem; f_Value.AddChild(l_ID); //#UC END# *53EDDCE10317_54646EB103D5_impl* end;//TTasksIDListHelper.DoAdd function TTasksIDListHelper.DoGetStrings(anIndex: Integer): AnsiString; //#UC START# *53F1FD130157_54646EB103D5_var* //#UC END# *53F1FD130157_54646EB103D5_var* begin //#UC START# *53F1FD130157_54646EB103D5_impl* Result := f_Value.Child[anIndex].StrA[k2_tiName]; //#UC END# *53F1FD130157_54646EB103D5_impl* end;//TTasksIDListHelper.DoGetStrings class function TFoundSelectorHelper.Make(aValue: Tl3Tag): FoundSelectorHelper; var l_Inst : TFoundSelectorHelper; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TFoundSelectorHelper.Make function TFoundSelectorHelper.Get_Count: Integer; //#UC START# *57C55E300362_57BEADEE00FCget_var* //#UC END# *57C55E300362_57BEADEE00FCget_var* begin //#UC START# *57C55E300362_57BEADEE00FCget_impl* Result := f_Value.ChildrenCount; //#UC END# *57C55E300362_57BEADEE00FCget_impl* end;//TFoundSelectorHelper.Get_Count procedure TFoundSelectorHelper.Add(aPara: LongInt; aWord: Word; aDocument: LongInt); //#UC START# *57C55E50024D_57BEADEE00FC_var* var l_Addr : Tl3Tag; //#UC END# *57C55E50024D_57BEADEE00FC_var* begin //#UC START# *57C55E50024D_57BEADEE00FC_impl* l_Addr := k2_typFoundSelector.MakeTag.AsObject; l_Addr.IntA[k2_attrPara] := aPara; l_Addr.IntA[k2_attrWord] := aWord; l_Addr.IntA[k2_attrDocument] := aDocument; f_Value.AddChild(l_Addr); //#UC END# *57C55E50024D_57BEADEE00FC_impl* end;//TFoundSelectorHelper.Add procedure TFoundSelectorHelper.GetValue(anIndex: Integer; out thePara: LongInt; out theWord: Word; out theDocument: LongInt); //#UC START# *57C55E5D000A_57BEADEE00FC_var* var l_Addr : Tl3Tag; //#UC END# *57C55E5D000A_57BEADEE00FC_var* begin //#UC START# *57C55E5D000A_57BEADEE00FC_impl* l_Addr := f_Value.Child[anIndex]; thePara := l_Addr.IntA[k2_attrPara]; theWord := l_Addr.IntA[k2_attrWord]; theDocument := l_Addr.IntA[k2_attrDocument]; //#UC END# *57C55E5D000A_57BEADEE00FC_impl* end;//TFoundSelectorHelper.GetValue class function TRejectedIDListHelper.Make(aValue: Tl3Tag): RejectedIDListHelper; var l_Inst : TRejectedIDListHelper; begin l_Inst := Create(aValue); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TRejectedIDListHelper.Make function TRejectedIDListHelper.Get_Count: Integer; //#UC START# *57DBA025026A_57DB9ED80225get_var* //#UC END# *57DBA025026A_57DB9ED80225get_var* begin //#UC START# *57DBA025026A_57DB9ED80225get_impl* Result := f_Value.ChildrenCount; //#UC END# *57DBA025026A_57DB9ED80225get_impl* end;//TRejectedIDListHelper.Get_Count procedure TRejectedIDListHelper.Add(anID: Cardinal; const aComment: AnsiString); //#UC START# *57DBA04200B7_57DB9ED80225_var* var l_Addr : Tl3Tag; //#UC END# *57DBA04200B7_57DB9ED80225_var* begin //#UC START# *57DBA04200B7_57DB9ED80225_impl* l_Addr := k2_typDocIDWithComment.MakeTag.AsObject; l_Addr.IntA[k2_attrDocID] := anID; l_Addr.StrA[k2_attrDocComment] := aComment; f_Value.AddChild(l_Addr); //#UC END# *57DBA04200B7_57DB9ED80225_impl* end;//TRejectedIDListHelper.Add procedure TRejectedIDListHelper.GetValue(anIndex: Integer; out theID: Cardinal; out theComment: AnsiString); //#UC START# *57DBA11103B8_57DB9ED80225_var* var l_Addr : Tl3Tag; //#UC END# *57DBA11103B8_57DB9ED80225_var* begin //#UC START# *57DBA11103B8_57DB9ED80225_impl* l_Addr := f_Value.Child[anIndex]; theID := l_Addr.IntA[k2_attrDocID]; theComment := l_Addr.StrA[k2_attrDocComment]; //#UC END# *57DBA11103B8_57DB9ED80225_impl* end;//TRejectedIDListHelper.GetValue end.
unit TThreadSocketSplitter; interface uses syncobjs, Dialogs, Sysutils, Windows, classes, winsock, {$ifdef Lazarus}TCPSocket_Lazarus{$else}TCPSocket{$endif}, ReadWriteEvent, StatusThread; const TimeOut = 10000; Thread_Working = 300; Thread_Finished = 301; Thread_SuspendedBeforeExit = 309; Thread_ReadFromSocket = 310; type {############################################################################## # # # TEventEx zählt die Anzahl Wartender Threads mit! # # # ##############################################################################} TEventEx = class(TEvent) private FThreadsWaiting: Integer; public property ThreadsWaiting: Integer read FThreadsWaiting; function WaitFor(Timeout: DWORD): TWaitResult; constructor Create(EventAttributes: PSecurityAttributes; AManualReset, InitialState: Boolean; const Name: string); end; ETerminated = class(Exception); EDeMultiplexer = class(Exception); TExceptionEvent = procedure(Sender: TThread; E: Exception; msg: String) of object; TSpltPacket1 = record Size: Word; ProzessIndex: Word; end; TDeMultiplexerOnNoneThreadData = procedure(Sender: TObject; var Data; Size, ProcIndex: Word) of object; TDeMultiplexer = class(TSThread) private protected Socket: TTCPSocket; //DIE Verbindung zur Gegenstelle! NextLayer: TSpltPacket1; //Verwendet Execute als ReadBuffer und zum Austausch der daten mit RecvBuf! SyncData: pointer; //Wird von "Execute" zum Lesen von "Notes" und hauptsächlich zum DatenAustausch mit "SyncOnNoneThreadData" verwendet! CanWrite, //Wírd von "SendBuf" verwendet um gleichzeitigen Zugriff auf Socket.SendBuf zu verhindern! NewLayer, //Execute setzt dieses Event -> RecvBuf wartet darauf und gibt (setzt erneut) es bei Bedarf weiter! LayerProcessed: TEventEx; //Execute wartet hier bis dieses Event von RecvBuf aufgerufen wird und damit die erfolgrieche Abarbeitung von NextLayer signalisiert. procedure SyncOnNoneThreadData; procedure SyncOnEndConnection; procedure CloseRecvBufLoops; public nTLimit: Word; ThreadAsync: Word; ThreadLimit: Word; NoteIndex: Word; OnNoneThreadData: TDeMultiplexerOnNoneThreadData; OnEndConnection: TNotifyEvent; {$ifndef Lazarus}OnException: TExceptionEvent;{$endif} property TCPSocket: TTCPSocket read Socket; constructor Create(ASocket: TTCPSocket); procedure SendBuf(var buf; Size, ProcIndex: Word; note: string); procedure Execute; override; destructor Destroy; override; //function RecvBufLength(ProcessID: Word): word; brauchts nicht! function DataAvailable(ProcessID: Word; var Size: Word): Boolean; overload; function DataAvailable(ProcessID: Word): Boolean; overload; function RecvBuf(var Buf; Size, ProcIndex: Word; SmallPacketAllowed: Boolean = False): Integer; end; TClientThreadEvent = function(Sender: TThread): Integer of object; TClientThreadNoThreadData = procedure(Sender: TThread; var Data; Size, ProcIndex: Word) of object; TClientThread = class(TSThread) protected FOnException: TExceptionEvent; procedure SocketOnNoThreadData(Sender: TObject; var Data; Size, ProcIndex: Word); procedure SocketOnEndConnection(Sender: TObject); procedure Sync_ThreadEnd; procedure SelfOnThreadStatusChanged(Sender: TObject); procedure SetOnException(p: TExceptionEvent); function GetOnException: TExceptionEvent; public Socket: TDeMultiplexer; Data: Pointer; Server: Boolean; OnNoThreadData: TClientThreadNoThreadData; OnDoLogin: TClientThreadEvent; OnDoSync: TClientThreadEvent; OnThreadEnd: TNotifyEvent; property OnException: TExceptionEvent read GetOnException write SetOnException; property Terminated; constructor Create(CreateSuspended: Boolean; ASocket: TTCPSocket); procedure Execute; override; destructor Destroy; override; procedure SendBuf(var buf; Size, ProcIndex: Word; note: string); //SendBuf und RecvBuf sind einfach nur weiterleitungen zum DeMultiplexer! procedure RecvBuf(var Buf; Size, ProcIndex: Word); //Es werden manchmal direkt die DeMultiplexerfunktionen gestarten, und manchmal diese hier! end; TOnClientThreadHostEvent = function(Sender: TObject; ClientThread: TClientThread; ServerSite: Boolean): integer of object; TClientThreadHost_noThDa = procedure(Sender: TThread; ClientThread: TClientThread; var Data; Size, ProcIndex: Word) of object; TnoThDaProc = record ProcIndex: word; Proc: TClientThreadHost_noThDa; end; TFilterFunction = function(AClientThread: TClientThread): Boolean; TClientThreadHost = class(TSThread) private procedure Server_ClientConnect(Sender: TObject; newSocket: TSocket); protected Sync_OnClientConnect_ClientThread: TClientThread; NTDProcs: array of TnoThDaProc; EV_Clients: TEvent; procedure Sync_OnClientConnect; procedure ClientThreadNoThreadData(Sender: TThread; var Data; Size, ProcIndex: Word); function ClientThreadLogin(Sender: TThread): Integer; function ClientThreadSync(Sender: TThread): Integer; procedure SetClientEvents(ClientThread: TClientThread); procedure ClientThreadEnd(Sender: TObject); public Clients: array of TClientThread; OnClientConnect: TOnClientThreadHostEvent; OnClientDisconnect: TOnClientThreadHostEvent; OnClientDoLogin: TOnClientThreadHostEvent; OnClientDoSync: TOnClientThreadHostEvent; ClientArrayReadWrite: TReadWriteEvent; {$ifndef Lazarus}OnException: TExceptionEvent;{$endif} Server: TSimpleServer; constructor Create; procedure Connect(IP: String; Port: Integer); procedure AddNoThreadDataProc(ProcIndex: Word; Proc: TClientThreadHost_noThDa); procedure SendBuf(var buf; Size, ProcID: Word; DontSendAt: TClientThread; Filter: TFilterFunction; note: string); destructor Destroy; override; procedure Disconnect(Index: Integer); procedure Execute; override; {procedure LockClientList; procedure ReleaseClientList;} end; var SendNotes: Boolean; implementation uses Math; procedure TClientThread.SocketOnNoThreadData(Sender: TObject; var Data; Size, ProcIndex: Word); begin if Assigned(OnNoThreadData) then OnNoThreadData(Self,Data,Size,ProcIndex); end; procedure TClientThreadHost.AddNoThreadDataProc(ProcIndex: Word; Proc: TClientThreadHost_noThDa); var i: integer; begin i := length(NTDProcs); SetLength(NTDProcs,i+1); NTDProcs[i].ProcIndex := ProcIndex; NTDProcs[i].Proc := Proc; end; procedure TClientThreadHost.ClientThreadNoThreadData(Sender: TThread; var Data; Size, ProcIndex: Word); var i: integer; begin for i := 0 to length(NTDProcs)-1 do if NTDProcs[i].ProcIndex = ProcIndex then begin if Assigned(NTDProcs[i].Proc) then NTDProcs[i].Proc(Self,TClientThread(Sender),Data,Size,ProcIndex); break; end; end; constructor TClientThread.Create(CreateSuspended: Boolean; ASocket: TTCPSocket); begin Socket := TDeMultiplexer.Create(ASocket); Socket.OnNoneThreadData := {$ifdef Lazarus}@{$endif}SocketOnNoThreadData; Socket.OnEndConnection := {$ifdef Lazarus}@{$endif}SocketOnEndConnection; OnOnThreadStatusChange := {$ifdef Lazarus}@{$endif}SelfOnThreadStatusChanged; Data := nil; inherited Create(CreateSuspended); FreeOnTerminate := True; Name := Name + ' ' + ASocket.RemoteHost.IP + ':' + IntToStr(ASocket.RemoteHost.Port); end; procedure TClientThread.Execute; var r: integer; begin ReturnValue := Thread_Working; if Socket.Socket.Connected then begin Status := 'Run OnDoLogin; if Assigned'; r := 0; try if Assigned(OnDoLogin) then r := OnDoLogin(Self); If r = 0 then begin Status := 'Run OnDoSynch; if Assigend'; if Assigned(OnDoSync) then OnDoSync(Self); end; except on E: Exception do begin Status := 'Exception in ' + Name + ':' + E.Message + ' (' + E.ClassName + ')'; if Assigned(FOnException) then FOnException(Self,E,Status); Terminate; //Wenn was Schief läuft, Trennen! end; end; if not Terminated then //Pause nur dann, wenn alles Glattgelaufen ist begin Status := 'Pausiert, bis Verbindung beendet!'; ReturnValue := Thread_SuspendedBeforeExit; Suspend; ReturnValue := Thread_Working; end; Terminate; Status := 'leaving Execute'; end; if Socket.ReturnValue <> Thread_Finished then begin Socket.Terminate; //Beenden des DeMultiplexers Socket.Socket.Close; //Schließen dessen Sockets, damit er aus der Blockierenden Read-Function rauskommt end; if Assigned(OnThreadEnd) then begin Status := 'Run OnThreadEnd'; Synchronize({$ifdef Lazarus}@{$endif}Sync_ThreadEnd); end; Status := 'Left Execute'; ReturnValue := Thread_Finished; end; constructor TDeMultiplexer.Create(ASocket: TTCPSocket); begin //braucht schon verbundenen Socket! Socket := ASocket; CanWrite := TEventEx.Create(nil,False,True,''); NewLayer := TEventEx.Create(nil,False,False,''); LayerProcessed := TEventEx.Create(nil,False,False,''); NoteIndex := 5; ThreadAsync := 512; nTLimit := 1024; ThreadLimit := High(ThreadLimit); FreeOnTerminate := False; inherited Create(false); Name := Name + ' ' + ASocket.RemoteHost.IP + ':' + IntToStr(ASocket.RemoteHost.Port); end; destructor TDeMultiplexer.Destroy; begin //FreeOnTerminate := False; is in Create sowiso so festgelegt Terminate; Socket.Close; CanWrite.Free; while (LayerProcessed.ThreadsWaiting > 0) do LayerProcessed.SetEvent; LayerProcessed.Free; if ReturnValue <> Thread_Finished then WaitFor; Socket.Free; Inherited Destroy; end; procedure TDeMultiplexer.Execute; begin Status := 'Enter Execute'; ReturnValue := Thread_Working; try while (not Terminated)and(Socket.Connected) do begin Status := 'Read ...'; Socket.ReceiveBuf(NextLayer,sizeof(NextLayer)); if (NextLayer.ProzessIndex = NoteIndex) then begin //Die Möglichkeit der Gegenstelle eine Statusnotiz zu geben! GetMem(SyncData,NextLayer.Size+1); FillChar(SyncData^,NextLayer.Size+1,0); Socket.ReceiveBuf(SyncData^,NextLayer.Size); Status := 'remote-note: ' + PChar(SyncData); FreeMem(SyncData); end else if (NextLayer.ProzessIndex <= nTLimit) then //NoneThread-Bereich! begin GetMem(SyncData,NextLayer.Size); Status := 'Read noThreadData ' + IntToStr(NextLayer.ProzessIndex) + '/' + IntToStr(NextLayer.Size); Socket.ReceiveBuf(SyncData^,NextLayer.Size); if Assigned(OnNoneThreadData) then begin if (NextLayer.ProzessIndex >= ThreadAsync) then SyncOnNoneThreadData else Synchronize({$ifdef Lazarus}@{$endif}SyncOnNoneThreadData); end; FreeMem(SyncData); end else if (NextLayer.ProzessIndex <= ThreadLimit) then //Thread-Bereich! begin NewLayer.SetEvent; //Neues Layer da! Status := 'Wait for LayerProcessed ' + IntToStr(NextLayer.ProzessIndex) + '/' + IntToStr(NextLayer.Size); if (LayerProcessed.WaitFor(TimeOut) <> wrSignaled) then //Warte bis Layer verarbeitet! begin raise EDeMultiplexer.Create('API: Execute, Timeout beim warten auf Datenverarbeitung (index/size:' + IntToStr(NextLayer.ProzessIndex) + '/' + IntToStr(NextLayer.Size)); end; end; end; except on E: Exception do begin Status := 'Exception in ' + Name + ':' + E.Message + ' (' + E.ClassName + ')'; If Assigned(OnException) then OnException(Self,E,Status); end; end; Status := 'Leaving Execute'; Socket.Close; CloseRecvBufLoops; //Beende eventuelle RecvBuf-Schleifen beendet werden! if Assigned(OnEndConnection) then begin Status := 'Run OnEndConnection'; Synchronize({$ifdef Lazarus}@{$endif}SyncOnEndConnection); end; Status := 'Left Execute'; ReturnValue := Thread_Finished; end; {function TDeMultiplexer.RecvBuf -> Wartet auf das Event NewLayer, das angibt, dass der multiplexer das nächste Packet gelesen hat. -> Falls der ProcIndex stimmt, gibt die Funktion das Packet an die aufrufende Funktion zurück und setzt das Event LayerProcessed um dem Multiplexer zu sagen, das das Packet verarbeitet wurde und ein neues gelesen werden kann. -> Wenn ProcIndex nicht stimmt, wird das Event NewLayer nochmal aufgerufen, um das aktuelle Packet an den nächsten Thread weiterzuleiten. -> Wenn der Multiplexer terminiert wurde, wird eine Exception aufgerufen! -> Wenn ein Timeout beim warten auf NewLayer auftritt, wird nochmal drauf gewartet. Es gibt also kein wirkliches Timeout hier! -> Die angegebene Packetgröße muss mit der empfangenen übereinstimmen, außer SmallPacketAllowed ist True. Aber selbst dann darf die empfangene Größe auf keinen Fall >größer< sein als von der aufrufenden Function angegeben!} function TDeMultiplexer.RecvBuf(var Buf; Size, ProcIndex: Word; SmallPacketAllowed: Boolean = False): Integer; var ready: Boolean; begin Result := -1; if Terminated then raise ETerminated.Create('API: RecvBuf, ReadThread terminiert!'); ready := False; while (not ready) do begin ready := (NewLayer.WaitFor(TimeOut) = wrSignaled); if Terminated then raise ETerminated.Create('API: RecvBuf, ReadThread terminiert!'); if ready then begin if (NextLayer.ProzessIndex = ProcIndex) then begin if (NextLayer.Size = Size)or((NextLayer.Size <= Size)and(SmallPacketAllowed)) then begin if NextLayer.Size > 0 then //wenn null, dann dann blockt socket.recv solange bis wieder was kommt, auch wenn er eigentlich nix lesen müsste! Socket.ReceiveBuf(buf,Size); Result := NextLayer.Size; LayerProcessed.SetEvent; //Layer wurde Verarbeitet! end else raise EDeMultiplexer.Create('API: RecvBuf, BufSizeDiff!'); end //(NextLayer.ProzessIndex = ProcIndex) else begin NewLayer.SetEvent; //Weil Falscher Layer -> Starte Neue Layer nochmal("unecht"), damit andere Threads drannkommen! ready := False; end; end; end; end; { procedure TDeMultiplexer.SendBuf -> Sendet Daten über die im Multiplexer vorhandene Verbindung (Socket) -> Zum sicherstellen, das keine 2 sendvorgänge gleichzeitig passieren können, wird das TEventobject CanWrite verwendet -> CanWrite muss immer wieder gesetzt werden, falls kein Timeout beim Warten auf dieses Event aufgetreten ist! -> Ruft eine Exception auf, falls der Multiplexer terminiert wurde, oder ein Timeout beim Warten auf CanWrite auftritt! } procedure TDeMultiplexer.SendBuf(var buf; Size, ProcIndex: Word; note: string); var Layer: TSpltPacket1; begin Layer.Size := Size; Layer.ProzessIndex := ProcIndex; Status := 'Sende: ' + IntToStr(ProcIndex) + '/' + IntToStr(Size) + ' - ' + Note; if (CanWrite.WaitFor(TimeOut) = wrSignaled) then //Sperren! try while not Socket.SelectWrite(1000) do sleep(100); if Terminated then raise ETerminated.Create('API: SendBuf, ReadThread wurde terminiert!'); Socket.SendBuf(Layer,sizeof(Layer)); if Size > 0 then Socket.SendBuf(buf,size); if SendNotes and (note <> '') then //NoteIndex - Packete werden direkt im DeMultiplexer-Execute-Thread verarbeitet! begin Layer.Size := length(note); Layer.ProzessIndex := NoteIndex; Socket.SendBuf(Layer,sizeof(Layer)); if Layer.Size > 0 then Socket.SendBuf(PChar(note)^,Layer.Size); end; finally CanWrite.SetEvent; //Freigeben! end else raise ETerminated.Create('API: SendBuf, Timeout beim Warten auf Schreiberlaubnis'); end; procedure TDeMultiplexer.SyncOnNoneThreadData; begin {###### # Wird von Execute Aufgerufen wenn NoneThreadData angekommen sind! Diese Daten befinden sich dann in SyncData! ######} OnNoneThreadData(Self,SyncData^,NextLayer.Size,NextLayer.ProzessIndex); end; procedure TClientThreadHost.Connect(IP: String; Port: Integer); var i: integer; sock: TTCPSocket; begin sock := TTCPSocket.Create(-1); Status := 'Verbinde mit "' + IP + ':' + IntToStr(Port) + '" ...'; if sock.Connect(IP,Port) then begin Status := 'Verbunden! Erstelle Clientthread ...'; if ClientArrayReadWrite.LockAll(TimeOut) then try i := length(Clients); Setlength(Clients,i+1); Clients[i] := TClientThread.Create(True,sock); Clients[i].Server := False; SetClientEvents(Clients[i]); if Assigned(OnClientConnect) then OnClientConnect(Self,Clients[i],False); Status := 'Starte Clientthread!'; Clients[i].Resume; finally ClientArrayReadWrite.Unlock; end else begin sock.Free; raise Exception.Create('TClientThreadHost.Connect: ClientArrayReadWrite.LockAll(TimeOut) ... Failed!'); end; end else begin Status := 'Verbindung Fehlgeschlagen!'; sock.free; end; end; constructor TClientThreadHost.Create; begin inherited Create(False); ClientArrayReadWrite := TReadWriteEvent.Create(); SetLength(Clients,0); EV_Clients := TEvent.Create(nil,false,True,''); Server := TSimpleServer.Create; Server.OnClientConnect := {$ifdef Lazarus}@{$endif}Server_ClientConnect; FreeOnTerminate := False; end; procedure TClientThreadHost.Sync_OnClientConnect; begin OnClientConnect(Self,Sync_OnClientConnect_ClientThread,Sync_OnClientConnect_ClientThread.Server); end; function TClientThreadHost.ClientThreadLogin(Sender: TThread): Integer; begin if Assigned(OnClientDoLogin) then Result := OnClientDoLogin(Self,TClientThread(Sender),TClientThread(Sender).Server) else Result := -1; end; function TClientThreadHost.ClientThreadSync(Sender: TThread): Integer; begin if Assigned(OnClientDoSync) then Result := OnClientDoSync(Self,TClientThread(Sender),TClientThread(Sender).Server) else Result := -1; end; procedure TClientThreadHost.SetClientEvents(ClientThread: TClientThread); begin ClientThread.OnThreadEnd := {$ifdef Lazarus}@{$endif}ClientThreadEnd; ClientThread.OnNoThreadData := {$ifdef Lazarus}@{$endif}ClientThreadNoThreadData; ClientThread.OnDoLogin := {$ifdef Lazarus}@{$endif}ClientThreadLogin; ClientThread.OnDoSync := {$ifdef Lazarus}@{$endif}ClientThreadSync; ClientThread.OnThreadStatus := OnThreadStatus; //geerbt von TSThread ClientThread.OnException := OnException; end; procedure TClientThreadHost.SendBuf(var buf; Size, ProcID: Word; DontSendAt: TClientThread; Filter: TFilterFunction; note: string); var i: integer; begin ClientArrayReadWrite.LockWrite(TimeOut); for i := 0 to length(Clients)-1 do if (Clients[i] <> nil)and(Clients[i].Socket <> nil)and(Clients[i] <> DontSendAt)and((not Assigned(Filter))or(Filter(Clients[i]))) then begin try //in sendbuf können fehler auftreten! Die anderen sockets sollen aber trotzdem auch die daten bekommen! Clients[i].Socket.SendBuf(buf,Size,ProcID,note); except //nix end; end; ClientArrayReadWrite.Unlock; end; destructor TClientThreadHost.Destroy; var i: integer; begin for i := 0 to length(Clients)-1 do begin Clients[i].OnThreadEnd := nil; Clients[i].Terminate; Clients[i].Socket.Socket.Close; Clients[i].OnThreadStatus := nil; //Fehlermeldung, weil form mit routine nichtmehr vorhanden! end; inherited Destroy; end; destructor TClientThread.Destroy; begin FreeOnTerminate := False; Terminate; if ReturnValue = Thread_SuspendedBeforeExit then Resume; if not (ReturnValue = Thread_Finished) then WaitFor; //Wenn also destroy nicht aus dem selben Thread aufgerufen! Socket.Free; if ReturnValue <> Thread_Finished then begin if Suspended then Resume; WaitFor; end; inherited Destroy; end; procedure TClientThreadHost.Disconnect(Index: Integer); begin if (Index < length(Clients)) then begin Clients[Index].Terminate; Clients[Index].Socket.Socket.Close; end; end; procedure TClientThread.SocketOnEndConnection(Sender: TObject); begin Terminate; if ReturnValue = Thread_SuspendedBeforeExit then Resume; end; procedure TClientThreadHost.ClientThreadEnd(Sender: TObject); var i,j: integer; begin (* Hier wird der ClientThread nur aus der Liste gelöscht, Freigeben tut er sich am Ende selber.*) i := 0; if ClientArrayReadWrite.LockAll(TimeOut) then try while (i < length(Clients)) do begin if Clients[i] = TClientThread(Sender) then begin for j := i to length(Clients)-2 do Clients[j] := Clients[j+1]; SetLength(Clients,length(Clients)-1); if Assigned(OnClientDisConnect) then OnClientDisConnect(Self,TClientThread(Sender),TClientThread(Sender).Server); Break; //gefunden -> Schleife frühzeitig verlassen! end else inc(i); end; finally ClientArrayReadWrite.Unlock; end else raise Exception.Create('TClientThreadHost.ClientThreadEnd: ClientArrayReadWrite.LockAll(TimeOut) ... Failed!'); end; procedure TClientThread.Sync_ThreadEnd; begin OnThreadEnd(self); end; procedure TDeMultiplexer.SyncOnEndConnection; begin OnEndConnection(Self); end; procedure TClientThread.SelfOnThreadStatusChanged(Sender: TObject); begin if Sender = Self then begin Socket.OnThreadStatus := OnThreadStatus; end else raise Exception.Create('Fataler Fehler: Sender <> Self'); end; function TDeMultiplexer.DataAvailable(ProcessID: Word): Boolean; var Size: Word; begin Result := DataAvailable(ProcessID,Size); end; function TDeMultiplexer.DataAvailable(ProcessID: Word; var Size: Word): Boolean; begin Result := NewLayer.WaitFor(0) = wrSignaled; //Wenn Layer da (in einer Millisekunde) if Result then begin Result := (NextLayer.ProzessIndex = ProcessID); //und die nummer stimmt! If Result Then Size := NextLayer.Size; //größe mit zurückgeben! NewLayer.SetEvent; //Rückgabe, aber nur wenn eins da ist! end; end; {procedure TClientThreadHost.LockClientList; begin ClientArrayReadWrite.LockAll(TimeOut); end; procedure TClientThreadHost.ReleaseClientList; begin ClientArrayReadWrite.Unlock; end;} procedure TClientThread.SendBuf(var buf; Size, ProcIndex: Word; note: string); begin Socket.SendBuf(buf,Size,ProcIndex,note); end; procedure TClientThread.RecvBuf(var Buf; Size, ProcIndex: Word); begin Socket.RecvBuf(Buf,Size,ProcIndex); end; constructor TEventEx.Create(EventAttributes: PSecurityAttributes; AManualReset, InitialState: Boolean; const Name: string); begin inherited; FThreadsWaiting := 0; end; function TEventEx.WaitFor(Timeout: DWORD): TWaitResult; begin inc(FThreadsWaiting); Result := inherited WaitFor(Timeout); dec(FThreadsWaiting); end; procedure TDeMultiplexer.CloseRecvBufLoops; var loopcount: integer; begin Terminate; loopcount := 0; while (NewLayer.ThreadsWaiting > 0)and(loopcount < 255) do begin NewLayer.SetEvent; Inc(loopcount); end; //Die Recv-Buf Schleifen müssen so gestaltet sein, dass sie, direkt nach dem erfolgreichen warten auf NewLayer, gleich terminate überprüfen und dann eine exception raushaun! //Sie müssen aber auch vor dem warten terminated überprüfen, damit sie nach diesem aufruf hier nicht wieder anfangen zu warten! end; procedure TClientThread.SetOnException(p: TExceptionEvent); begin if Assigned(Socket) then Socket.OnException := p; FOnException := p; end; function TClientThread.GetOnException: TExceptionEvent; begin Result := FOnException; end; procedure TClientThreadHost.Server_ClientConnect(Sender: TObject; newSocket: TSocket); var i: integer; TCPSOCK: TTCPSocket; begin {############################################################################## Verarbeitet neue Clientverbindungen vom Server(TSimpleServer). ->Erstellt eine TTCPSocket und fügt ihn ins Array ein! ##############################################################################} Status := 'ClientArrayReadWrite.LockAll ... Wait'; if not ClientArrayReadWrite.LockAll(Timeout) then raise Exception.Create('ClientArrayReadWrite.LockAll ... Failed!'); try Status := 'Create Client'; i := length(Clients); Setlength(Clients,i+1); TCPSock := TTCPSocket.Create(newSocket); Clients[i] := TClientThread.Create(True,TCPSock); Clients[i].Server := True; SetClientEvents(Clients[i]); Sync_OnClientConnect_ClientThread := Clients[i]; finally ClientArrayReadWrite.Unlock; end; if Assigned(OnClientConnect) then OnClientConnect(Self,Clients[i],True); Clients[i].Resume; end; procedure TClientThreadHost.Execute; begin //nothing! end; end.
unit sql; interface uses SysUtils, Classes, Windows, ActiveX, Dialogs, Forms, Data.DB, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZStoredProcedure; var PConnect: TZConnection; PQuery: TZQuery; DataSource: TDataSource; function ConfigPostgresSetting(InData: bool): bool; function SqlCalculatedData: bool; function SqlTemperature: bool; implementation uses main, settings; function ConfigPostgresSetting(InData: bool): bool; begin if InData then begin PConnect := TZConnection.Create(nil); PQuery := TZQuery.Create(nil); try PConnect.LibraryLocation := CurrentDir + '\'+ PgSqlConfigArray[3]; PConnect.Protocol := 'postgresql-9'; PConnect.HostName := PgSqlConfigArray[1]; PConnect.Port := strtoint(PgSqlConfigArray[6]); PConnect.User := PgSqlConfigArray[4]; PConnect.Password := PgSqlConfigArray[5]; PConnect.Database := PgSqlConfigArray[2]; PConnect.Connect; PQuery.Connection := PConnect; DataSource := TDataSource.Create(nil); except on E: Exception do Showmessage('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end else begin FreeAndNil(DataSource); FreeAndNil(PQuery); FreeAndNil(PConnect); end; end; function SqlCalculatedData: bool; begin try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('SELECT cast(to_char(TO_TIMESTAMP(t2.timestamp), ''YYYY-MM-DD HH24:MI:SS'') as varchar(20)) as timestamp'); PQuery.SQL.Add(', t1.heat, t1.section'); PQuery.SQL.Add(', cast(case t1.side when 0 then ''Левая'' else ''Правая'' end as varchar(10)) as side'); PQuery.SQL.Add(', cast(case t2.step when 0 then ''Красный'' else ''Зеленый'' end as varchar(10)) as step'); PQuery.SQL.Add(', t2.coefficient_yield_point_value'); PQuery.SQL.Add(', t2.coefficient_rupture_strength_value'); PQuery.SQL.Add(', t2.heat_to_work'); PQuery.SQL.Add(', t2.limit_rolled_products_min'); PQuery.SQL.Add(', t2.limit_rolled_products_max'); PQuery.SQL.Add(', cast(case t2.type_rolled_products when ''yield_point'' then'); PQuery.SQL.Add('''предел текучести'' else ''временное сопротивление'' end as varchar(30)) as type_rolled_products'); PQuery.SQL.Add(', t2.mechanics_avg'); PQuery.SQL.Add(', t2.mechanics_std_dev'); PQuery.SQL.Add(', t2.mechanics_min'); PQuery.SQL.Add(', t2.mechanics_max'); PQuery.SQL.Add(', t2.mechanics_diff'); PQuery.SQL.Add(', t2.coefficient_min'); PQuery.SQL.Add(', t2.coefficient_max'); PQuery.SQL.Add(', t2.temp_avg'); PQuery.SQL.Add(', t2.temp_std_dev'); PQuery.SQL.Add(', t2.temp_min'); PQuery.SQL.Add(', t2.temp_max'); PQuery.SQL.Add(', t2.temp_diff'); PQuery.SQL.Add(', t2.r'); PQuery.SQL.Add(', t2.adjustment_min'); PQuery.SQL.Add(', t2.adjustment_max'); PQuery.SQL.Add(', t2.low'); PQuery.SQL.Add(', t2.high'); PQuery.SQL.Add(', t2.ce_min_down'); PQuery.SQL.Add(', t2.ce_min_up'); PQuery.SQL.Add(', t2.ce_max_down'); PQuery.SQL.Add(', t2.ce_max_up'); PQuery.SQL.Add(', t2.ce_avg'); PQuery.SQL.Add(', t2.ce_avg_down'); PQuery.SQL.Add(', t2.ce_avg_up'); PQuery.SQL.Add(', t2.ce_category'); PQuery.SQL.Add('from temperature_current t1'); PQuery.SQL.Add('INNER JOIN'); PQuery.SQL.Add('calculated_data t2'); PQuery.SQL.Add('on t1.tid=t2.cid'); if trim(form1.e_heat.Text) <> '' then PQuery.SQL.Add('where t1.heat = '''+trim(form1.e_heat.Text)+''''); PQuery.SQL.Add('order by t1.tid desc, t2.step asc'); PQuery.Open; except on E: Exception do Showmessage('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; function SqlTemperature: bool; begin try PQuery.Close; PQuery.SQL.Clear; PQuery.SQL.Add('SELECT cast(to_char(TO_TIMESTAMP(t2.timestamp), ''YYYY-MM-DD HH24:MI:SS'') as varchar(20)) as timestamp'); PQuery.SQL.Add(', t1.heat, t1.section'); PQuery.SQL.Add(', cast(case t1.side when 0 then ''Левая'' else ''Правая'' end as varchar(10)) as side'); PQuery.SQL.Add(', t2.temperature'); PQuery.SQL.Add('from temperature_current t1'); PQuery.SQL.Add('INNER JOIN'); PQuery.SQL.Add('temperature_historical t2'); PQuery.SQL.Add('on t1.tid=t2.tid'); PQuery.SQL.Add('where t1.heat = '''+trim(form1.e_heat.Text)+''''); PQuery.SQL.Add('order by t1.tid desc'); PQuery.Open; except on E: Exception do Showmessage('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message); end; end; end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} (* Version History 03/16/2002 ElDBButtonEdit made unicode *) unit ElDBBtnEdit; interface uses DB, DBCtrls, ElBtnEdit, ElStrUtils, ElDBConst, Forms, Windows, Controls, StdCtrls, Messages, {$ifdef VCL_6_USED} Types, {$endif} Classes, SysUtils; type TElDBButtonEdit = class(TCustomElButtonEdit) private FDataLink: TFieldDataLink; procedure ActiveChange(Sender: TObject); procedure DataChange(Sender: TObject); procedure EditingChange(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; procedure ResetMaxLength; procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure UpdateData(Sender: TObject); procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; protected FUnicodeMode: TElDBUnicodeMode; procedure Change; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; {$ifdef VCL_4_USED} function ExecuteAction(Action: TBasicAction): Boolean; override; function UpdateAction(Action: TBasicAction): Boolean; override; function UseRightToLeftAlignment: Boolean; override; {$endif} property Field: TField read GetField; property Text; property Lines; published property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property TopMargin; property LeftMargin; property RightMargin; property AutoSize; property RightAlignedText; property RightAlignedView; property BorderSides; property PasswordChar; property MaxLength; property Transparent; property FlatFocusedScrollBars; property WantTabs; property HandleDialogKeys; property HideSelection; property TabSpaces; {$ifdef ELPACK_USE_IMAGEFORM} property ImageForm; {$endif} property WordWrap; property ScrollBars; property OnMouseEnter; property OnMouseLeave; property OnResize; property OnChange; property OnSelectionChange; property Multiline; // inherited property Flat; property ActiveBorderType; property InactiveBorderType; property LineBorderActiveColor; property LineBorderInactiveColor; property UseBackground; property Alignment; property AutoSelect; property Background; {$IFDEF USE_SOUND_MAP} property ButtonCaption; property ButtonClickSound; property ButtonDownSound; property ButtonUpSound; property ButtonSoundMap; {$ENDIF} property ButtonColor; property ButtonDown; property ButtonEnabled; property ButtonFlat; property ButtonGlyph; property ButtonHint; property ButtonIcon; property ButtonNumGlyphs; property ButtonPopupPlace; property ButtonPullDownMenu; property ButtonShortcut; property ButtonUseIcon; property ButtonVisible; property ButtonWidth; property OnButtonClick; property AltButtonCaption; {$IFDEF USE_SOUND_MAP} property AltButtonClickSound; property AltButtonDownSound; property AltButtonUpSound; property AltButtonSoundMap; {$ENDIF} property AltButtonColor; property AltButtonDown; property AltButtonEnabled; property AltButtonFlat; property AltButtonGlyph; property AltButtonHint; property AltButtonIcon; property AltButtonNumGlyphs; property AltButtonPopupPlace; property AltButtonPosition; property AltButtonPullDownMenu; property AltButtonShortcut; property AltButtonUseIcon; property AltButtonVisible; property AltButtonWidth; property OnAltButtonClick; // VCL properties property BorderStyle; property Ctl3D; property ParentCtl3D; property Enabled; property TabStop default True; property TabOrder; property PopupMenu; property Color; property ParentColor; property Align; property Font; property ParentFont; property ParentShowHint; property ShowHint; property Visible; property ReadOnly; property OnEnter; property OnExit; property OnClick; property OnDblClick; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnStartDrag; property OnDragDrop; property OnDragOver; {$IFDEF VCL_4_USED} property OnEndDock; {$ENDIF} property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; {$IFDEF VCL_4_USED} property OnStartDock; {$ENDIF} {$IFDEF VCL_4_USED} property Anchors; property Constraints; property DockOrientation; property Floating; property DoubleBuffered; property DragKind; property UnicodeMode: TElDBUnicodeMode read FUnicodeMode write FUnicodeMode default umFieldType; {$ENDIF} end; implementation constructor TElDBButtonEdit.Create(AOwner : TComponent); begin inherited; inherited ReadOnly := true; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnEditingChange := EditingChange; FDataLink.OnUpdateData := UpdateData; FDataLink.OnActiveChange := ActiveChange; end; destructor TElDBButtonEdit.Destroy; begin FDataLink.Free; FDataLink := nil; inherited; end; procedure TElDBButtonEdit.ActiveChange(Sender: TObject); begin ResetMaxLength; end; procedure TElDBButtonEdit.Change; begin FDataLink.Modified; inherited Change; end; procedure TElDBButtonEdit.DataChange(Sender: TObject); {$ifdef ELPACK_UNICODE} var W : WideString; {$endif} begin if FDataLink.Field <> nil then begin if Alignment <> FDataLink.Field.Alignment then begin Text := ''; {forces update} Alignment := FDataLink.Field.Alignment; end; if not (csDesigning in ComponentState) then begin if (FDataLink.Field.DataType in [ftString{$ifdef VCL_4_USED}, ftWideString{$endif}]) and (MaxLength = 0) then MaxLength := FDataLink.Field.Size; end; {$ifdef ELPACK_UNICODE} if FDataLink.Field.isNull then W := '' else if (UnicodeMode = umForceUTF8) and (ConvertUTF8toUTF16(FDataLink.Field.asString, W, strictConversion, false) <> sourceIllegal) then else begin if (FDataLink.Field.DataType = ftWideString) then W := FDataLink.Field.Value else Text := FDataLink.Field.AsString; end; Text := W; {$else} Text := FDataLink.Field.AsString; {$endif} end else begin Alignment := taLeftJustify; if csDesigning in ComponentState then Text := Name else Text := ''; end; end; procedure TElDBButtonEdit.EditingChange(Sender: TObject); begin inherited ReadOnly := not FDataLink.Editing; end; {$ifdef VCL_4_USED} function TElDBButtonEdit.ExecuteAction(Action: TBasicAction): Boolean; begin Result := inherited ExecuteAction(Action) or (FDataLink <> nil) and FDataLink.ExecuteAction(Action); end; {$endif} function TElDBButtonEdit.GetDataField: string; begin Result := FDataLink.FieldName; end; function TElDBButtonEdit.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TElDBButtonEdit.GetField: TField; begin Result := FDataLink.Field; end; procedure TElDBButtonEdit.KeyDown(var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) or ((Key = VK_INSERT) and (ssShift in Shift)) or (Key = VK_BACK) then FDataLink.Edit; inherited KeyDown(Key, Shift); end; procedure TElDBButtonEdit.KeyPress(var Key: Char); begin if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin MessageBeep(0); Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; #27: begin FDataLink.Reset; SelectAll; Key := #0; end; end; inherited KeyPress(Key); end; procedure TElDBButtonEdit.Loaded; begin inherited Loaded; ResetMaxLength; if (csDesigning in ComponentState) then DataChange(Self); end; procedure TElDBButtonEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TElDBButtonEdit.ResetMaxLength; var F: TField; begin if (MaxLength > 0) and Assigned(DataSource) and Assigned(DataSource.DataSet) then begin F := DataSource.DataSet.FindField(DataField); if Assigned(F) and (F.DataType in [ftString{$ifdef VCL_4_USED}, ftWideString{$endif}]) and (F.Size = MaxLength) then MaxLength := 0; end; end; procedure TElDBButtonEdit.SetDataField(const Value: string); begin if not (csDesigning in ComponentState) then ResetMaxLength; FDataLink.FieldName := Value; end; procedure TElDBButtonEdit.SetDataSource(Value: TDataSource); begin {$ifdef VCL_5_USED} if FDataLink.DataSource <> nil then if not (csDestroying in FDatALink.DataSource.ComponentState) then FDataLink.DataSource.RemoveFreeNotification(Self); {$endif} if not (FDataLink.DataSourceFixed and (csLoading in ComponentState)) then FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; {$ifdef VCL_4_USED} function TElDBButtonEdit.UpdateAction(Action: TBasicAction): Boolean; begin Result := inherited UpdateAction(Action) or (FDataLink <> nil) and FDataLink.UpdateAction(Action); end; {$endif} procedure TElDBButtonEdit.UpdateData(Sender: TObject); {$ifdef ELPACK_UNICODE} var W : WideString; st: string; {$endif} begin {$ifdef ELPACK_UNICODE} if UnicodeMode = umForceUTF8 then begin ConvertUTF16toUTF8(Text, st, strictConversion, false); FDataLink.Field.Text := st; end else if UnicodeMode = umFieldType then begin if (FDataLink.Field.DataType = ftWideString) and (not FDataLink.Field.IsNull) then begin W := Text; FDataLink.Field.Value := W; end else FDataLink.Field.Text := Text; end {$else} FDataLink.Field.Text := Text; {$endif} end; {$ifdef VCL_4_USED} function TElDBButtonEdit.UseRightToLeftAlignment: Boolean; begin Result := DBUseRightToLeftAlignment(Self, Field); end; {$endif} procedure TElDBButtonEdit.CMExit(var Message: TCMExit); begin try FDataLink.UpdateRecord; except SetFocus; raise; end; inherited; end; procedure TElDBButtonEdit.CMGetDataLink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; end.
unit k2EVDWriterService; // Модуль: "w:\common\components\rtl\Garant\K2\k2EVDWriterService.pas" // Стереотип: "Service" // Элемент модели: "Tk2EVDWriterService" MUID: (555DCEA8017E) {$Include w:\common\components\rtl\Garant\K2\k2Define.inc} interface uses l3IntfUses , l3ProtoObject , k2CustomFileGenerator , l3Variant ; (* Mk2EVDWriterService = interface {* Контракт сервиса Tk2EVDWriterService } function GetWriter: Tk2CustomFileGenerator; function MakeWriter(const aFileName: AnsiString): Ik2TagGenerator; end;//Mk2EVDWriterService *) type Ik2EVDWriterService = interface {* Интерфейс сервиса Tk2EVDWriterService } function GetWriter: Tk2CustomFileGenerator; function MakeWriter(const aFileName: AnsiString): Ik2TagGenerator; end;//Ik2EVDWriterService Tk2EVDWriterService = {final} class(Tl3ProtoObject) private f_Alien: Ik2EVDWriterService; {* Внешняя реализация сервиса Ik2EVDWriterService } protected procedure pm_SetAlien(const aValue: Ik2EVDWriterService); procedure ClearFields; override; public function GetWriter: Tk2CustomFileGenerator; function MakeWriter(const aFileName: AnsiString): Ik2TagGenerator; class function Instance: Tk2EVDWriterService; {* Метод получения экземпляра синглетона Tk2EVDWriterService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: Ik2EVDWriterService write pm_SetAlien; {* Внешняя реализация сервиса Ik2EVDWriterService } end;//Tk2EVDWriterService implementation uses l3ImplUses , SysUtils , l3Base //#UC START# *555DCEA8017Eimpl_uses* //#UC END# *555DCEA8017Eimpl_uses* ; var g_Tk2EVDWriterService: Tk2EVDWriterService = nil; {* Экземпляр синглетона Tk2EVDWriterService } procedure Tk2EVDWriterServiceFree; {* Метод освобождения экземпляра синглетона Tk2EVDWriterService } begin l3Free(g_Tk2EVDWriterService); end;//Tk2EVDWriterServiceFree procedure Tk2EVDWriterService.pm_SetAlien(const aValue: Ik2EVDWriterService); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//Tk2EVDWriterService.pm_SetAlien function Tk2EVDWriterService.GetWriter: Tk2CustomFileGenerator; //#UC START# *555DCEC1021B_555DCEA8017E_var* //#UC END# *555DCEC1021B_555DCEA8017E_var* begin //#UC START# *555DCEC1021B_555DCEA8017E_impl* if (f_Alien <> nil) then Result := f_Alien.GetWriter else Result := nil; //#UC END# *555DCEC1021B_555DCEA8017E_impl* end;//Tk2EVDWriterService.GetWriter function Tk2EVDWriterService.MakeWriter(const aFileName: AnsiString): Ik2TagGenerator; //#UC START# *55701AE20388_555DCEA8017E_var* //#UC END# *55701AE20388_555DCEA8017E_var* begin //#UC START# *55701AE20388_555DCEA8017E_impl* if (f_Alien <> nil) then Result := f_Alien.MakeWriter(aFileName) else Result := nil; //#UC END# *55701AE20388_555DCEA8017E_impl* end;//Tk2EVDWriterService.MakeWriter class function Tk2EVDWriterService.Instance: Tk2EVDWriterService; {* Метод получения экземпляра синглетона Tk2EVDWriterService } begin if (g_Tk2EVDWriterService = nil) then begin l3System.AddExitProc(Tk2EVDWriterServiceFree); g_Tk2EVDWriterService := Create; end; Result := g_Tk2EVDWriterService; end;//Tk2EVDWriterService.Instance class function Tk2EVDWriterService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tk2EVDWriterService <> nil; end;//Tk2EVDWriterService.Exists procedure Tk2EVDWriterService.ClearFields; begin Alien := nil; inherited; end;//Tk2EVDWriterService.ClearFields end.
unit MainWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, D3DXCore, DirectDraw, Direct3D, SurfaceSpriteImages, ExtCtrls, FullScreenWindowMgr; const cMaxImages = $FFFFF; type PImageArray = ^TImageArray; TImageArray = array [0..cMaxImages] of TSurfaceFrameImage; const cImageFileNamesFile = 'C:\Work\Five\Release\Client\LoadedImages.log'; type TMainForm = class(TForm) StatusLine: TPanel; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } function RenderTest(Alpha : single) : HRESULT; procedure LoadSprites; procedure ApplicationOnIdle(Sender : TObject; var Done : boolean); //HandleModeChanges : HRESULT; public { Public declarations } fD3DXContext : ID3DXContext; fDirectDraw : IDirectDraw7; fDirect3DDevice : IDirect3DDevice7; fPrimarySurface : IDirectDrawSurface7; fBackBuffer : IDirectDrawSurface7; fFSWindowManager : TFullScreenWindowManager; fImageFileNames : TStringList; fImages : PImageArray; fImageCount : integer; end; var MainForm: TMainForm; implementation {$R *.DFM} uses D3DXSprite, D3DXErr, ImageLoader, GifLoader, DDrawD3DManager, ClipBrd, DirectDrawUtils; const cScreenWidth = 1024; cScreenHeight = 768; procedure TMainForm.FormCreate(Sender: TObject); begin Left := 0; Top := 0; Width := cScreenWidth; Height := cScreenHeight; InitDDrawD3D(Handle, cScreenWidth, cScreenHeight); fD3DXContext := DDrawD3DMgr.D3DXContext; fDirectDraw := DDrawD3DMgr.DirectDraw; fDirect3DDevice := DDrawD3DMgr.Direct3DDevice; fPrimarySurface := DDrawD3DMgr.PrimarySurface; fBackBuffer := DDrawD3DMgr.BackBuffer; fFSWindowManager := TFullScreenWindowManager.Create(Handle, fDirectDraw, fPrimarySurface, fBackBuffer); fFSWindowManager.RegisterWindow(StatusLine.Handle, false, 0); //Application.OnIdle := ApplicationOnIdle; fImageFileNames := TStringList.Create; fImageFileNames.LoadFromFile(cImageFileNamesFile); end; function TMainForm.RenderTest(Alpha : single) : HRESULT; const cLoopCount = 1500; var hr : HRESULT; viewport : TD3DVIEWPORT7; x, y : integer; initialtickcount : integer; elapsedticks : integer; i : integer; errstr : string; ImageRect : TRect; imgidx : integer; begin if fImageCount > 0 then if Succeeded(fDirect3DDevice.BeginScene) then begin //fD3DXContext.Clear(D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER); fDirect3DDevice.Clear(0, nil, D3DCLEAR_TARGET, D3DRGBA(0.0, 0.0, 0.0, 0.0), 0, 0); // We need to setup the rasterizer for rendering sprites; // this only needs to be done once for all the sprites that // are rendered; however this function does need to be called // again if any render state changes are made outside of the // bltsprite call. D3DXPrepareDeviceForSprite(fDirect3DDevice, false); fDirect3DDevice.SetRenderState(D3DRENDERSTATE_COLORKEYENABLE, 1); // Get our current viewport hr := fDirect3DDevice.GetViewport(viewport); if Succeeded(hr) then begin initialtickcount := GetTickCount(); // Go ahead and do the render for i := 0 to pred(cLoopCount) do begin x := random(cScreenWidth); y := random(cScreenHeight); imgidx := random(fImageCount); ImageRect := Rect(x, y, x + fImages[imgidx].Width, y + fImages[imgidx].Height); IntersectRect(ImageRect, ImageRect, ClientRect); fImages[imgidx].Draw(x, y, 0, 0, 1.0, ImageRect, fDirect3DDevice, nil); end; fDirect3DDevice.EndScene; //hr := fD3DXContext.UpdateFrame(D3DX_DEFAULT); //hr := fPrimarySurface.Flip(nil, DDFLIP_DONOTWAIT); fFSWindowManager.UpdateScreen([ClientRect]); if Failed(hr) then begin SetLength(errstr, 1000); D3DXGetErrorString(hr, 1000, pchar(errstr)); Application.MessageBox(pchar(errstr), 'Error', MB_OK); end; { if (hr = DDERR_SURFACELOST) or (hr = DDERR_SURFACEBUSY) then hr = HandleModeChanges(); } elapsedticks := GetTickCount() - initialtickcount; StatusLine.Caption := IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.'; //Clipboard.AsText := StatusLine.Caption; Sleep(1); fDirect3DDevice.BeginScene; initialtickcount := GetTickCount(); // Go ahead and do the render for i := 0 to pred(cLoopCount) do begin x := random(cScreenWidth); y := random(cScreenHeight); imgidx := random(fImageCount); ImageRect := Rect(x, y, x + fImages[imgidx].Width, y + fImages[imgidx].Height); IntersectRect(ImageRect, ImageRect, ClientRect); fImages[imgidx].Draw(x, y, 0, 0, 1.0, ImageRect, fDirect3DDevice, nil); end; fDirect3DDevice.EndScene; //hr := fD3DXContext.UpdateFrame(D3DX_DEFAULT); //hr := fPrimarySurface.Flip(nil, DDFLIP_DONOTWAIT); fFSWindowManager.UpdateScreen([ClientRect]); if Failed(hr) then begin SetLength(errstr, 1000); D3DXGetErrorString(hr, 1000, pchar(errstr)); Application.MessageBox(pchar(errstr), 'Error', MB_OK); end; { if (hr = DDERR_SURFACELOST) or (hr = DDERR_SURFACEBUSY) then hr = HandleModeChanges(); } elapsedticks := GetTickCount() - initialtickcount; StatusLine.Caption := StatusLine.Caption + ' ' + IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.'; Clipboard.AsText := StatusLine.Caption; //Application.MessageBox(pchar(IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.'), 'Report', MB_OK); //OutputDebugString(pchar(IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.')); end; end else hr := E_FAIL else hr := E_FAIL; Result := hr; end; procedure TMainForm.LoadSprites; var i : integer; begin fImageCount := fImageFileNames.Count; getmem(fImages, fImageCount*sizeof(fImages[0])); for i := 0 to pred(fImageCount) do fImages[i] := LoadGameImage(fImageFileNames[i]); end; procedure TMainForm.ApplicationOnIdle(Sender : TObject; var Done : boolean); var ddscaps : TDDSCaps2; totalmemfree : dword; freemem : dword; megs : dword; tmprest : dword; kilobytes : dword; bytes : dword; begin InitRecord(ddscaps, sizeof(ddscaps)); with ddscaps do //ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN; ddsCaps.dwCaps := DDSCAPS_TEXTURE; if Succeeded(fDirectDraw.GetAvailableVidMem(ddscaps, totalmemfree, freemem)) then begin megs := totalmemfree div (1024*1024); tmprest := totalmemfree mod (1024*1024); kilobytes := tmprest div 1024; bytes := tmprest mod 1024; StatusLine.Caption := IntToStr(megs) + ' Megs ' + IntToStr(kilobytes) + ' K and ' + IntToStr(bytes) + ' bytes.'; megs := freemem div (1024*1024); tmprest := freemem mod (1024*1024); kilobytes := tmprest div 1024; bytes := tmprest mod 1024; StatusLine.Caption := StatusLine.Caption + ' ' + IntToStr(megs) + ' Megs ' + IntToStr(kilobytes) + ' K and ' + IntToStr(bytes) + ' bytes.'; end else StatusLine.Caption := 'Error'; end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of VK_F3: LoadSprites; VK_F4: RenderTest(8); VK_F5: RenderTest(4); end; end; end.
unit uROSimpleEventRepository; interface uses uROEventRepository, uROClient, uROTypes, uROClientIntf, uROHTTPWebsocketServer, uROSessions, Classes, SyncObjs; type TROSimpleWebsocketEventRepository = class(TInterfacedObject, IROEventRepository) private FMessage: TROMessage; FROServer: TROIndyHTTPWebsocketServer; FEventCount: Integer; protected {IROEventRepository} procedure AddSession(aSessionID : TGUID); overload; procedure AddSession(aSessionID : TGUID; aEventSinkId: AnsiString); overload; procedure RemoveSession(aSessionID : TGUID); overload; procedure RemoveSession(aSessionID : TGUID; aEventSinkId: AnsiString); overload; procedure StoreEventData(SourceSessionID : TGUID; Data : Binary; const ExcludeSender: Boolean; const ExcludeSessionList: Boolean; const SessionList: String); overload; procedure StoreEventData(SourceSessionID : TGUID; Data : Binary; const ExcludeSender: Boolean; const ExcludeSessionList: Boolean; const SessionList: String; const EventSinkId: AnsiString); overload; function GetEventData(SessionID : TGUID; var TargetStream : Binary) : integer; public function GetEventWriter(const IID: TGUID): IROEventWriter; property Message : TROMessage read FMessage write FMessage; property ROServer: TROIndyHTTPWebsocketServer read FROServer write FROServer; end; implementation uses IdContext, IdIOHandlerWebsocket, Windows; { TSimpleEventRepository } procedure TROSimpleWebsocketEventRepository.AddSession(aSessionID: TGUID); begin //no session end; procedure TROSimpleWebsocketEventRepository.AddSession(aSessionID: TGUID; aEventSinkId: AnsiString); begin //no session end; procedure TROSimpleWebsocketEventRepository.RemoveSession(aSessionID: TGUID; aEventSinkId: AnsiString); begin //no session end; procedure TROSimpleWebsocketEventRepository.RemoveSession(aSessionID: TGUID); begin //no session end; function TROSimpleWebsocketEventRepository.GetEventWriter( const IID: TGUID): IROEventWriter; var lEventWriterClass: TROEventWriterClass; begin lEventWriterClass := FindEventWriterClass(IID); if not assigned(lEventWriterClass) then exit; result := lEventWriterClass.Create(fMessage, Self) as IROEventWriter; end; function TROSimpleWebsocketEventRepository.GetEventData(SessionID: TGUID; var TargetStream: Binary): integer; begin Result := -1; Assert(False); end; procedure TROSimpleWebsocketEventRepository.StoreEventData(SourceSessionID: TGUID; Data: Binary; const ExcludeSender, ExcludeSessionList: Boolean; const SessionList: String; const EventSinkId: AnsiString); begin StoreEventData(SourceSessionID, Data, ExcludeSender, ExcludeSessionList, SessionList); end; procedure TROSimpleWebsocketEventRepository.StoreEventData(SourceSessionID: TGUID; Data: Binary; const ExcludeSender, ExcludeSessionList: Boolean; const SessionList: String); var i, iEventNr: Integer; LContext: TIdContext; l: TList; ws: TIdIOHandlerWebsocket; begin l := ROServer.IndyServer.Contexts.LockList; try if l.Count <= 0 then Exit; iEventNr := -1 * InterlockedIncrement(FEventCount); //negative = event, positive is normal RO message if iEventNr > 0 then begin InterlockedExchange(FEventCount, 0); iEventNr := -1 * InterlockedIncrement(FEventCount); //negative = event, positive is normal RO message end; Assert(iEventNr < 0); Data.Position := Data.Size; Data.Write(AnsiString('WSNR'), Length('WSNR')); Data.Write(iEventNr, SizeOf(iEventNr)); Data.Position := 0; //direct write to ALL connections for i := 0 to l.Count - 1 do begin LContext := TIdContext(l.Items[i]); ws := (LContext.Connection.IOHandler as TIdIOHandlerWebsocket); if not ws.IsWebsocket then Continue; ws.Lock; try ws.Write(Data, wdtBinary); finally ws.Unlock; end; end; finally ROServer.IndyServer.Contexts.UnlockList; end; end; end.
unit ULiveCalendarDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListBox, FMX.TMSCloudBase, FMX.TMSCloudLiveCalendar, FMX.Layouts, FMX.Edit, FMX.ExtCtrls, DateUtils, FMX.Objects, IOUtils, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLive, FMX.TMSCloudLiveFMX, FMX.TMSCloudCustomLiveCalendar, FMX.DateTimeCtrls; type TForm82 = class(TForm) ToolBar1: TToolBar; Button1: TButton; Button2: TButton; ComboBox1: TComboBox; ListBox1: TListBox; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Label3: TLabel; CheckBox1: TCheckBox; Label4: TLabel; CalendarEdit1: TCalendarEdit; CalendarEdit2: TCalendarEdit; Label5: TLabel; Edit2: TEdit; SpeedButton6: TSpeedButton; Image6: TImage; SpeedButton7: TSpeedButton; Image7: TImage; SpeedButton1: TSpeedButton; Image1: TImage; TMSFMXCloudLiveCalendar1: TTMSFMXCloudLiveCalendar; procedure Button1Click(Sender: TObject); procedure ComboBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } Connected: Boolean; public { Public declarations } procedure FillCalendars; procedure FillCalendarItems; procedure Init; procedure ClearControls; procedure ToggleControls; procedure SetCalendarItem(Item: TLiveCalendarItem); end; var Form82: TForm82; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // LiveAppkey = 'xxxxxxxxx'; // LiveAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm82.Button1Click(Sender: TObject); begin TMSFMXCloudLiveCalendar1.App.Key := LiveAppKey; TMSFMXCloudLiveCalendar1.App.Secret := LiveAppSecret; TMSFMXCloudLiveCalendar1.Logging := true; if not TMSFMXCloudLiveCalendar1.TestTokens then TMSFMXCloudLiveCalendar1.RefreshAccess; if not TMSFMXCloudLiveCalendar1.TestTokens then TMSFMXCloudLiveCalendar1.DoAuth else Init; end; procedure TForm82.Button4Click(Sender: TObject); begin ClearControls; end; procedure TForm82.SetCalendarItem(Item: TLiveCalendarItem); begin Item.Summary := Edit1.Text; Item.Description := Edit2.Text; Item.Location := ''; Item.StartTime := CalendarEdit1.Date; Item.EndTime := CalendarEdit2.Date; Item.IsAllDay := CheckBox1.IsChecked; end; procedure TForm82.SpeedButton1Click(Sender: TObject); var li: TLiveCalendarItem; begin if Assigned(ListBox1.Selected) then begin li := (ListBox1.Selected.Data as TLiveCalendarItem); SetCalendarItem(li); TMSFMXCloudLiveCalendar1.Update(li); FillCalendarItems; end; end; procedure TForm82.Button5Click(Sender: TObject); var li: TLiveCalendarItem; begin li := TMSFMXCloudLiveCalendar1.Items.Add; SetCalendarItem(li); li.CalendarID := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TLiveCalendar).ID; TMSFMXCloudLiveCalendar1.Add(li); FillCalendarItems; end; procedure TForm82.ClearControls; begin Edit1.Text := ''; Edit2.Text := ''; CheckBox1.IsChecked := False; CalendarEdit1.Date := Now; CalendarEdit2.Date := Now; end; procedure TForm82.ComboBox1Change(Sender: TObject); begin ClearControls; FillCalendarItems; end; procedure TForm82.FillCalendarItems; var I: Integer; LiveCalendar: TLiveCalendar; begin if ComboBox1.ItemIndex >= 0 then begin LiveCalendar := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TLiveCalendar); TMSFMXCloudLiveCalendar1.GetCalendar(LiveCalendar.ID); ListBox1.Items.Clear; for I := 0 to TMSFMXCloudLiveCalendar1.Items.Count - 1 do ListBox1.Items.AddObject(TMSFMXCloudLiveCalendar1.Items[I].Summary, TMSFMXCloudLiveCalendar1.Items[I]); end; end; procedure TForm82.FillCalendars; var I: Integer; begin TMSFMXCloudLiveCalendar1.GetCalendars; ComboBox1.Items.Clear; for I := 0 to TMSFMXCloudLiveCalendar1.Calendars.Count - 1 do begin ComboBox1.Items.AddObject(TMSFMXCloudLiveCalendar1.Calendars[I].Summary, TMSFMXCloudLiveCalendar1.Calendars[I]); end; ComboBox1.ItemIndex := 0; end; procedure TForm82.FormCreate(Sender: TObject); begin CalendarEdit1.Date := Now; CalendarEdit2.Date := Now; TMSFMXCloudLiveCalendar1.PersistTokens.Key := TPath.GetDocumentsPath + '/live.ini'; TMSFMXCloudLiveCalendar1.PersistTokens.Section := 'tokens'; TMSFMXCloudLiveCalendar1.LoadTokens; ClearControls; Connected := false; ToggleControls; end; procedure TForm82.Init; begin Connected := true; ToggleControls; FillCalendars; FillCalendarItems; end; procedure TForm82.TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudLiveCalendar1.SaveTokens; Init; end; procedure TForm82.ToggleControls; begin SpeedButton6.Enabled := Connected; SpeedButton7.Enabled := Connected; SpeedButton1.Enabled := Connected; ComboBox1.Enabled := Connected; Edit1.Enabled := Connected; ListBox1.Enabled := Connected; CheckBox1.Enabled := Connected; CalendarEdit1.Enabled := Connected; CalendarEdit2.Enabled := Connected; Edit2.Enabled := Connected; Button1.Enabled := not Connected; end; end.
program ejercicio4; type str40= String[40]; rangoSeman = 1..42; vPeso = array[rangoSeman] of Real; paciente = record nombre : str40; apellido : str40; semana : rangoSeman; peso : vPeso; end; lista = ^nodo; // se DISPONE nodo = record datos : paciente; sig : lista; end; procedure leerDatos(var p:paciente); begin with p do begin write('Ingrese NOMBRE: '); // esto no lo dice el ejercicio pero lo hice para hacer un corte de control readln(nombre); if (nombre <> 'zzz') then begin write('Ingrese APELLIDO: '); readln(apellido); write('Ingrese la SEMANA (1-42): '); readln(semana); write('Ingrese PESO: '); readln(peso); writeln('-------------------------'); end; end; end; procedure agregarAdelante(var l:lista; p:paciente); var nue: lista; begin new(nue); nue^.datos:= p; nue^.sig:= l; l:= nue; end; //el cargar listo no es necesario en este ejercicio se DISPONE la informacion //lo realizo para poder porbrar el ejercicio como tal procedure cargarLista(var l:lista); var p: paciente; begin leerDatos(p); while (p.peso <> 0) do begin agregarAdelante(l,p); leerDatos(p); end; end; procedure procesarPaciente(p:paciente); var max,total: Real; maxSemana, i: Integer; begin max:= -1; total:= 0; for i := 1 to p.semana do begin total:= total + p.peso[i]; if (p.peso[i] > max ) then begin max:= p.peso[i]; maxSemana:= i; end; writeln('La semana con mayor aumento de peso fue: ', maxSemana); writeln('El aumento de peso total fue: ', total); end; end; procedure calcular(l:lista); begin while (l <> nil) do begin procesarPaciente(p); l:=l^.sig; end; end; var l: lista; begin l:= nil; cargarLista(l); calcular(l); readln(); end.
unit uOptions; {$MODE Delphi} interface uses {Windows, Messages,} SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls, Grids, MPHexEditor, ValEdit, MPHexEditorEx, LCLType; type { TdlgOptions } TdlgOptions = class(TForm) FontDialog1: TFontDialog; GroupBox1: TGroupBox; Label2: TLabel; Label3: TLabel; cbColors: TComboBox; cbFore: TColorButton; cbBack: TColorButton; GroupBox2: TGroupBox; ValueListEditor1: TValueListEditor; btnFont: TButton; Label1: TLabel; Bevel1: TBevel; Hexer: TMPHexEditorEx; BitBtn1: TBitBtn; BitBtn2: TBitBtn; procedure FormCreate(Sender: TObject); procedure cbColorsSelect(Sender: TObject); procedure cbForeSelect(Sender: TObject); procedure btnFontClick(Sender: TObject); procedure FontDialog1Apply(Sender: TObject; Wnd: HWND); procedure ValueListEditor1Validate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); procedure ValueListEditor1KeyPress(Sender: TObject; var Key: Char); procedure ValueListEditor1StringsChange(Sender: TObject); procedure HexerQueryPublicProperty(Sender: TObject; const PropertyName: String; var IsPublic: Boolean); private { Private-Deklarationen } public { Public-Deklarationen } procedure SetProperties; end; var dlgOptions: TdlgOptions; function EditEditorOptions(var Options: string): Boolean; implementation function EditEditorOptions(var Options: string): Boolean; begin with TDlgOptions.Create(Application) do try Hexer.PropertiesAsString := Options; SetProperties; Result := ShowModal = mrOK; if Result then Options := Hexer.PropertiesAsString; finally Free; end; end; const // value list strings STR_VL_NOSIZECHG = 'Fixed file size'; STR_VL_SWAPNIBBLES = 'Swap halfbytes (nibbles)'; STR_VL_SHOWGRID = 'Show grid'; STR_VL_OLEDND = 'OLE drag and drop'; STR_VL_CREATEBACKUP = 'Create backups'; STR_VL_BACKUPEXT = 'Backup file extension'; STR_VL_CLIPHEX = 'Clipboard text data has Hex format'; STR_VL_FLUSHCLIP = 'Preserve clipboard contents on close'; STR_VL_FOREIGNCLIP = 'Support foreign clipboard formats'; STR_VL_ZOOMONWHEEL = 'Use mouse wheel for zooming'; STR_VL_MASKCHAR = 'Substitute whiteSpaces by'; STR_VL_MAXUNDO = 'Max. size of Undo buffer (Byte)'; STR_VL_HEXLOWER = 'Hex numbers in lower case'; STR_VL_GUTTER3D = 'Gutter has 3D border'; STR_VL_RULER = 'Show ruler'; STR_VL_AUTOBYTESPERROW = 'Automatic row size'; STR_BOOL: array[Boolean] of string = ( 'No', 'Yes' ); {$R *.lfm} procedure TdlgOptions.FormCreate(Sender: TObject); var LIntLoop: Integer; LStrData: string; LrecBook:TMPHBookmark; begin LStrData := ''; for LIntLoop := 0 to 255 do LStrData := LStrData + Char(LIntLoop); Hexer.AsText := LStrData; Hexer.Seek(0,soFromBeginning); LrecBook.mPosition := 2; LrecBook.mInCharField := True; Hexer.Bookmark[4] := LrecBook; Hexer.ByteChanged[1] := True; end; procedure TdlgOptions.cbColorsSelect(Sender: TObject); begin Label2.Enabled := True; Label3.Enabled := True; cbFore.Enabled := True; cbBack.Enabled := True; cbFore.OnColorChanged := nil; cbBack.OnColorChanged := nil; with cbColors do case ItemIndex of 0://Offset begin cbFore.ButtonColor := Hexer.Colors.Offset; cbBack.ButtonColor := Hexer.Colors.OffsetBackGround; end; 1://Current Offset begin cbFore.ButtonColor := Hexer.Colors.CurrentOffset; cbBack.ButtonColor := Hexer.Colors.CurrentOffsetBackGround; end; 2://Characters begin cbFore.ButtonColor := Hexer.Font.Color; cbBack.ButtonColor := Hexer.Colors.Background; end; 3://Even Column begin cbFore.ButtonColor := Hexer.Colors.EvenColumn; cbBack.ButtonColor := Hexer.Colors.Background; end; 4://Odd Column begin cbFore.ButtonColor := Hexer.Colors.OddColumn; cbBack.ButtonColor := Hexer.Colors.Background; end; 5://Modified begin cbFore.ButtonColor := Hexer.Colors.ChangedText; cbBack.ButtonColor := Hexer.Colors.ChangedBackground; end; 6://Grid begin cbFore.ButtonColor := Hexer.Colors.Grid; cbBack.ButtonColor := Hexer.Colors.Background; end; 7: begin cbBack.ButtonColor := Hexer.Colors.ActiveFieldBackground; cbFore.Enabled := False; Label2.Enabled := False; end; else Label2.Enabled := False; Label3.Enabled := False; cbFore.Enabled := False; cbBack.Enabled := False; end; cbFore.OnColorChanged := cbForeSelect; cbBack.OnColorChanged := cbForeSelect; end; procedure TdlgOptions.cbForeSelect(Sender: TObject); begin with cbColors do case ItemIndex of 0://Offset begin Hexer.Colors.Offset := cbFore.ButtonColor; Hexer.Colors.OffsetBackGround := cbBack.ButtonColor; end; 1://Current Offset begin Hexer.Colors.CurrentOffset := cbFore.ButtonColor; Hexer.Colors.CurrentOffsetBackGround := cbBack.ButtonColor; end; 2://Characters begin Hexer.Font.Color := cbFore.ButtonColor; Hexer.Colors.Background := cbBack.ButtonColor; end; 3://Even Column begin Hexer.Colors.EvenColumn := cbFore.ButtonColor; Hexer.Colors.Background := cbBack.ButtonColor; end; 4://Odd Column begin Hexer.Colors.OddColumn := cbFore.ButtonColor; Hexer.Colors.Background := cbBack.ButtonColor; end; 5://Modified begin Hexer.Colors.ChangedText := cbFore.ButtonColor; Hexer.Colors.ChangedBackground := cbBack.ButtonColor; end; 6://Grid begin Hexer.Colors.Grid := cbFore.ButtonColor; Hexer.Colors.Background := cbBack.ButtonColor; end; 7: Hexer.Colors.ActiveFieldBackground := cbBack.ButtonColor; end; end; procedure TdlgOptions.btnFontClick(Sender: TObject); var LfntTemp: TFont; begin LfntTemp := TFont.Create; try LfntTemp.Assign(Hexer.Font); with FontDialog1 do begin // Device := fdScreen; Options := Options+[fdApplyButton]; Font.Assign(LfntTemp); if Execute then Hexer.Font.Assign(Font) else Hexer.Font.Assign(LfntTemp); end; finally LfntTemp.Free; end; end; procedure TdlgOptions.FontDialog1Apply(Sender: TObject; Wnd: HWND); begin Hexer.Font.Assign(FontDialog1.Font); end; procedure TdlgOptions.SetProperties; procedure AddBool(const Key: string; const Value: Boolean); var LIntRow: Integer; begin with ValueListEditor1 do begin LIntRow := Strings.Add(Key+'='+STR_BOOL[Value]); with ItemProps[LIntRow] do begin EditStyle := esPickList; PickList.Text := STR_BOOL[False]+#13#10+STR_BOOL[True]; ReadOnly := True; end; end; end; procedure AddString(const Key, Value: string); begin ValueListEditor1.Strings.Add(Key+'='+Value) end; begin cbColors.ItemIndex := 0; cbColorsSelect(cbColors); ValueListEditor1.Clear; with Hexer do begin AddBool(STR_VL_NOSIZECHG, NoSizeChange); AddBool(STR_VL_SWAPNIBBLES, SwapNibbles); AddBool(STR_VL_SHOWGRID, DrawGridLines); AddBool(STR_VL_OLEDND, OleDragDrop); AddBool(STR_VL_CREATEBACKUP, CreateBackup); AddString(STR_VL_BACKUPEXT, BackupExtension); AddBool(STR_VL_CLIPHEX, ClipboardAsHexText); AddBool(STR_VL_FLUSHCLIP, FlushClipboardAtShutDown); AddBool(STR_VL_FOREIGNCLIP, SupportsOtherClipFormats); AddBool(STR_VL_ZOOMONWHEEL, ZoomOnWheel); AddString(STR_VL_MASKCHAR, MaskChar); AddString(STR_VL_MAXUNDO, IntToStr(MaxUndo)); AddBool(STR_VL_HEXLOWER, HexLowerCase); AddBool(STR_VL_GUTTER3D, DrawGutter3D); AddBool(STR_VL_RULER, ShowRuler); AddBool(STR_VL_AUTOBYTESPERROW, AutoBytesPerRow); end; Hexer.AllowInsertMode := False; Hexer.ReadOnlyView := True; Hexer.ByteChanged[1] := True; end; procedure TdlgOptions.ValueListEditor1Validate(Sender: TObject; ACol, ARow: Integer; const KeyName, KeyValue: String); begin with Hexer do case ARow of 1: NoSizeChange := KeyValue = STR_BOOL[True]; 2: SwapNibbles := KeyValue = STR_BOOL[True]; 3: DrawGridLines := KeyValue = STR_BOOL[True]; 4: OleDragDrop := KeyValue = STR_BOOL[True]; 5: CreateBackup := KeyValue = STR_BOOL[True]; 6: BackupExtension := KeyValue; 7: ClipboardAsHexText := KeyValue = STR_BOOL[True]; 8: FlushClipboardAtShutDown := KeyValue = STR_BOOL[True]; 9: SupportsOtherClipFormats := KeyValue = STR_BOOL[True]; 10: ZoomOnWheel := KeyValue = STR_BOOL[True]; 11: MaskChar := (KeyValue+#0)[1]; 12: MaxUndo := StrToInt('0'+KeyValue); 13: HexLowerCase := KeyValue = STR_BOOL[True]; 14: DrawGutter3D := KeyValue = STR_BOOL[True]; 15: ShowRuler := KeyValue = STR_BOOL[True]; 16: AutoBytesPerRow := KeyValue = STR_BOOL[True]; end; end; procedure TdlgOptions.ValueListEditor1KeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then with ValueListEditor1 do ValueListEditor1Validate(ValueListEditor1, Col, Row, Keys[Row],Values[Keys[Row]]); end; procedure TdlgOptions.ValueListEditor1StringsChange(Sender: TObject); begin with ValueListEditor1 do if Values[Keys[Row]] <> '' then ValueListEditor1Validate(ValueListEditor1, Col, Row, Keys[Row],Values[Keys[Row]]); end; procedure TdlgOptions.HexerQueryPublicProperty(Sender: TObject; const PropertyName: String; var IsPublic: Boolean); const // properties not to get/set NO_PROPS = ';ReadOnlyView;AllowInsertMode;CaretKind;InsertMode;'; begin IsPublic := Pos(';'+LowerCase(PropertyName)+';', LowerCase(NO_PROPS)) = 0; end; end.
unit F1LikeTextLoad_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Forms" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Daily/Forms/F1LikeTextLoad_Form.pas" // Начат: 23.09.2010 14:51 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMForm::Class>> Shared Delphi Operations For Tests::TestForms::Forms::Everest::F1LikeTextLoad // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses vcmInterfaces, eeTextSourceExport, eeEditorExport, vcmUserControls, l3StringIDEx, PrimTextLoad_Form {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , kwBynameControlPush {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , F1LikeTextLoad_ut_F1LikeTextLoad_UserType, evCustomTextSource, evCustomEditor, evLoadDocumentManager, Classes {a}, l3InterfacedComponent {a}, vcmComponent {a}, vcmBaseEntities {a}, vcmEntities {a}, vcmExternalInterfaces {a}, vcmEntityForm {a} ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} const { F1LikeTextLoadIDs } fm_F1LikeTextLoadForm : TvcmFormDescriptor = (rFormID : (rName : 'F1LikeTextLoadForm'; rID : 0); rFactory : nil); { Идентификатор формы TF1LikeTextLoadForm } type F1LikeTextLoadFormDef = interface(IUnknown) {* Идентификатор формы F1LikeTextLoad } ['{FAAC10AB-4EAF-4B43-B184-7BFAADA53CAD}'] end;//F1LikeTextLoadFormDef TF1LikeTextLoadForm = {final form} class(TvcmEntityFormRef, F1LikeTextLoadFormDef) Entities : TvcmEntities; private // private fields f_Text : TeeEditorExport; {* Поле для свойства Text} f_TextSource : TeeTextSourceExport; {* Поле для свойства TextSource} protected procedure MakeControls; override; protected // realized methods function pm_GetTextSource: TevCustomTextSource; override; function pm_GetText: TevCustomEditor; override; public // public properties property Text: TeeEditorExport read f_Text; property TextSource: TeeTextSourceExport read f_TextSource; end;//TF1LikeTextLoadForm {$IfEnd} //nsTest AND not NoVCM implementation {$R *.DFM} {$If defined(nsTest) AND not defined(NoVCM)} uses SysUtils {$If not defined(NoScripts)} , tfwScriptEngine {$IfEnd} //not NoScripts , l3MessageID ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} var { Локализуемые строки ut_F1LikeTextLoadLocalConstants } str_ut_F1LikeTextLoadCaption : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ut_F1LikeTextLoadCaption'; rValue : 'F1LikeTextLoad'); { Заголовок пользовательского типа "F1LikeTextLoad" } type Tkw_F1LikeTextLoad_Control_Text = class(TtfwControlString) {* Слово словаря для идентификатора контрола Text ---- *Пример использования*: [code] контрол::Text TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_Control_Text // start class Tkw_F1LikeTextLoad_Control_Text {$If not defined(NoScripts)} function Tkw_F1LikeTextLoad_Control_Text.GetString: AnsiString; {-} begin Result := 'Text'; end;//Tkw_F1LikeTextLoad_Control_Text.GetString {$IfEnd} //not NoScripts type Tkw_F1LikeTextLoad_Control_Text_Push = class(TkwBynameControlPush) {* Слово словаря для контрола Text ---- *Пример использования*: [code] контрол::Text:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_Control_Text_Push // start class Tkw_F1LikeTextLoad_Control_Text_Push {$If not defined(NoScripts)} procedure Tkw_F1LikeTextLoad_Control_Text_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('Text'); inherited; end;//Tkw_F1LikeTextLoad_Control_Text_Push.DoDoIt {$IfEnd} //not NoScripts type Tkw_F1LikeTextLoad_Component_TextSource = class(TtfwControlString) {* Слово словаря для идентификатора компонента TextSource ---- *Пример использования*: [code] компонент::TextSource TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_Component_TextSource // start class Tkw_F1LikeTextLoad_Component_TextSource {$If not defined(NoScripts)} function Tkw_F1LikeTextLoad_Component_TextSource.GetString: AnsiString; {-} begin Result := 'TextSource'; end;//Tkw_F1LikeTextLoad_Component_TextSource.GetString {$IfEnd} //not NoScripts type Tkw_Form_F1LikeTextLoad = class(TtfwControlString) {* Слово словаря для идентификатора формы F1LikeTextLoad ---- *Пример использования*: [code] 'aControl' форма::F1LikeTextLoad TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_F1LikeTextLoad // start class Tkw_Form_F1LikeTextLoad {$If not defined(NoScripts)} function Tkw_Form_F1LikeTextLoad.GetString: AnsiString; {-} begin Result := 'F1LikeTextLoadForm'; end;//Tkw_Form_F1LikeTextLoad.GetString {$IfEnd} //not NoScripts type Tkw_F1LikeTextLoad_Text_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола Text формы F1LikeTextLoad } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_Text_ControlInstance // start class Tkw_F1LikeTextLoad_Text_ControlInstance {$If not defined(NoScripts)} procedure Tkw_F1LikeTextLoad_Text_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TF1LikeTextLoadForm).Text); end;//Tkw_F1LikeTextLoad_Text_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_F1LikeTextLoad_TextSource_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола TextSource формы F1LikeTextLoad } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_TextSource_ControlInstance // start class Tkw_F1LikeTextLoad_TextSource_ControlInstance {$If not defined(NoScripts)} procedure Tkw_F1LikeTextLoad_TextSource_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TF1LikeTextLoadForm).TextSource); end;//Tkw_F1LikeTextLoad_TextSource_ControlInstance.DoDoIt {$IfEnd} //not NoScripts type Tkw_F1LikeTextLoad_LoadManager_ControlInstance = class(TtfwWord) {* Слово словаря для доступа к экземпляру контрола LoadManager формы F1LikeTextLoad } protected // realized methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_F1LikeTextLoad_LoadManager_ControlInstance // start class Tkw_F1LikeTextLoad_LoadManager_ControlInstance {$If not defined(NoScripts)} procedure Tkw_F1LikeTextLoad_LoadManager_ControlInstance.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushObj((aCtx.rEngine.PopObj As TF1LikeTextLoadForm).LoadManager); end;//Tkw_F1LikeTextLoad_LoadManager_ControlInstance.DoDoIt {$IfEnd} //not NoScripts function TF1LikeTextLoadForm.pm_GetTextSource: TevCustomTextSource; //#UC START# *4C9B21D20187_4C9B31190392get_var* //#UC END# *4C9B21D20187_4C9B31190392get_var* begin //#UC START# *4C9B21D20187_4C9B31190392get_impl* Result := TextSource; //#UC END# *4C9B21D20187_4C9B31190392get_impl* end;//TF1LikeTextLoadForm.pm_GetTextSource function TF1LikeTextLoadForm.pm_GetText: TevCustomEditor; //#UC START# *4C9B21E400A4_4C9B31190392get_var* //#UC END# *4C9B21E400A4_4C9B31190392get_var* begin //#UC START# *4C9B21E400A4_4C9B31190392get_impl* Result := Text; //#UC END# *4C9B21E400A4_4C9B31190392get_impl* end;//TF1LikeTextLoadForm.pm_GetText procedure TF1LikeTextLoadForm.MakeControls; begin inherited; f_Text := TeeEditorExport.Create(Self); f_Text.Name := 'Text'; f_Text.Parent := Self; f_TextSource := TeeTextSourceExport.Create(Self); f_TextSource.Name := 'TextSource'; with AddUsertype(ut_F1LikeTextLoadName, str_ut_F1LikeTextLoadCaption, str_ut_F1LikeTextLoadCaption, false, -1, -1, '', nil, nil, nil, vcm_ccNone) do begin end;//with AddUsertype(ut_F1LikeTextLoadName end; {$IfEnd} //nsTest AND not NoVCM initialization {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_Control_Text Tkw_F1LikeTextLoad_Control_Text.Register('контрол::Text', TeeEditorExport); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_Control_Text_Push Tkw_F1LikeTextLoad_Control_Text_Push.Register('контрол::Text:push'); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_Component_TextSource Tkw_F1LikeTextLoad_Component_TextSource.Register('компонент::TextSource', TeeTextSourceExport); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация фабрики формы F1LikeTextLoad fm_F1LikeTextLoadForm.SetFactory(TF1LikeTextLoadForm.Make); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_Form_F1LikeTextLoad Tkw_Form_F1LikeTextLoad.Register('форма::F1LikeTextLoad', TF1LikeTextLoadForm); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_Text_ControlInstance TtfwScriptEngine.GlobalAddWord('.TF1LikeTextLoadForm.Text', Tkw_F1LikeTextLoad_Text_ControlInstance); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_TextSource_ControlInstance TtfwScriptEngine.GlobalAddWord('.TF1LikeTextLoadForm.TextSource', Tkw_F1LikeTextLoad_TextSource_ControlInstance); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Регистрация Tkw_F1LikeTextLoad_LoadManager_ControlInstance TtfwScriptEngine.GlobalAddWord('.TF1LikeTextLoadForm.LoadManager', Tkw_F1LikeTextLoad_LoadManager_ControlInstance); {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // Инициализация str_ut_F1LikeTextLoadCaption str_ut_F1LikeTextLoadCaption.Init; {$IfEnd} //nsTest AND not NoVCM end.
unit Thread.ConsolidaExtratoExpressa; interface uses System.Classes, Control.Bases, Control.EntregadoresExpressas, Control.Cadastro, System.SysUtils, Forms, Windows, System.Variants, Control.Bancos, Control.FechamentoExpressas, System.DateUtils; type TThread_ConsolidaExtratoExpressa = class(TThread) public FbGravar: Boolean; private { Private declarations } FBases : TBasesControl; FCadastro: TCadastroControl; FEntregadores: TEntregadoresExpressasControl; FBancos: TBancosControl; iConta: Integer; protected procedure Execute; override; procedure StartProc; procedure FinalizeProc; procedure UpdateCount; procedure ShowForm; procedure SalvaConsolidacao(); 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_ConsolidaExtratoExpressa.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 Data.SisGeF, View.ConsolidacaoExpressas, View.ExtratoExpressas, Common.Utils; { Thread_ConsolidaExtratoExpressa } procedure TThread_ConsolidaExtratoExpressa.Execute; var bCancel : Boolean; dtDate : TDate; iTipo, iCodigo, iEntregador: Integer; sForma, sBanco, sAgencia, sConta, sTipoConta, sFavorecido, sCPFCNPJ, sCadastro, sNome, sNomeBanco, sBimer, sTitulo, sModalidade: String; begin { Place thread code here } try try Synchronize(StartProc); FBases := TBasesControl.Create; FCadastro := TCadastroControl.Create; FEntregadores := TEntregadoresExpressasControl.Create; FBancos := TBancosControl.Create; if not Data_Sisgef.mtbExtratosExpressas.IsEmpty then Data_Sisgef.mtbExtratosExpressas.First; if not Data_Sisgef.mtbFechamentoExpressas.Active then Data_Sisgef.mtbFechamentoExpressas.Close; Data_Sisgef.mtbFechamentoExpressas.Open; while not Data_Sisgef.mtbExtratosExpressas.Eof do begin iTipo := 0; iCodigo := 0; iEntregador := 0; sNome := ''; sForma := ''; sBanco := ''; sNomeBanco := ''; sAgencia := ''; sConta := ''; sTipoConta := ''; sFavorecido := ''; sCPFCNPJ := ''; sCadastro := ''; sBimer := ''; sTitulo := ''; sForma := FBases.GetField('des_forma_pagamento','cod_agente', Data_Sisgef.mtbExtratosExpressascod_base.AsString); if sForma.IsEmpty then sForma := 'NENHUMA'; sTitulo := IntToStr(YearOf(Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime)) + IntToStr(DayOf(Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime)) + IntToStr(MonthOf(Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime)) + IntToStr(DayOf(Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime)) + IntToStr(MonthOf(Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime)); dtDate := IncMonth(Data_Sisgef.mtbFechamentoExpressasdat_fim.AsDateTime,1); // dados bancários da base if sForma <> 'NENHUMA' then begin iTipo := 1; iCodigo := Data_Sisgef.mtbExtratosExpressascod_base.AsInteger; sNome := FBases.GetField('nom_fantasia','cod_agente', iCodigo.ToString); sBanco := FBases.GetField('cod_banco','cod_agente', iCodigo.ToString); sNomeBanco := FBancos.GetField('nom_banco','cod_banco',QuotedStr(sBanco)); sModalidade := FBancos.GetField('cod_modalidade','cod_banco',QuotedStr(sBanco)); sAgencia := FBases.GetField('cod_agencia','cod_agente', iCodigo.ToString); sConta := FBases.GetField('num_conta','cod_agente', iCodigo.ToString); sTipoConta := FBases.GetField('des_tipo_conta','cod_agente', iCodigo.ToString); sFavorecido := FBases.GetField('nom_favorecido','cod_agente', iCodigo.ToString); sCPFCNPJ := FBases.GetField('num_cpf_cnpj_favorecido','cod_agente', iCodigo.ToString); sBimer := FBases.GetField('cod_centro_custo','cod_agente', iCodigo.ToString); sTitulo := sTitulo + IntToStr(iTipo) + IntToStr(iCodigo); end else begin sCadastro := FEntregadores.GetField('cod_cadastro', 'cod_entregador', Data_Sisgef.mtbExtratosExpressascod_entregador.AsString); sNome := FEntregadores.GetField('nom_fantasia', 'cod_entregador', Data_Sisgef.mtbExtratosExpressascod_entregador.AsString); sForma := FCadastro.GetField('des_forma_pagamento','cod_cadastro', sCadastro); if sForma.IsEmpty then sForma := 'NENHUMA'; // dados bancários do entregador // *** rotina alterada para demonstrar entregadores sem dados bancários. *** //if sForma <> 'NENHUMA' then //begin iTipo := 2; iCodigo := StrToIntDef(sCadastro,0); if iCodigo = 0 then begin iCodigo := Data_Sisgef.mtbExtratosExpressascod_entregador.AsInteger; end; sBanco := FCadastro.GetField('cod_banco','cod_cadastro', sCadastro); sNomeBanco := FBancos.GetField('nom_banco','cod_banco',QuotedStr(sBanco)); sModalidade := FBancos.GetField('cod_modalidade','cod_banco',QuotedStr(sBanco)); sAgencia := FCadastro.GetField('cod_agencia','cod_cadastro', sCadastro); sConta := FCadastro.GetField('num_conta','cod_cadastro', sCadastro); sTipoConta := FCadastro.GetField('des_tipo_conta','cod_cadastro', sCadastro); sFavorecido := FCadastro.GetField('nom_favorecido','cod_cadastro', sCadastro); sCPFCNPJ := FCadastro.GetField('num_cpf_cnpj_favorecido','cod_cadastro', sCadastro); sBimer := FCadastro.GetField('cod_centro_custo','cod_cadastro', sCadastro); sTitulo := sTitulo + IntToStr(iTipo) + IntToStr(iCodigo); //end; end; if Data_Sisgef.mtbFechamentoExpressas.LocateEx('cod_expressa;cod_tipo_expressa', VarArrayOf([iCodigo, iTipo]), []) then begin Data_Sisgef.mtbFechamentoExpressas.Edit; Data_Sisgef.mtbFechamentoExpressasqtd_volumes.AsInteger := Data_Sisgef.mtbFechamentoExpressasqtd_volumes.AsInteger + Data_Sisgef.mtbExtratosExpressasqtd_volumes.AsInteger; Data_Sisgef.mtbFechamentoExpressasqtd_entregas.AsInteger := Data_Sisgef.mtbFechamentoExpressasqtd_entregas.AsInteger + Data_Sisgef.mtbExtratosExpressasqtd_entregas.AsInteger; Data_Sisgef.mtbFechamentoExpressasqtd_volumes_extra.AsFloat := Data_Sisgef.mtbFechamentoExpressasqtd_volumes_extra.AsFloat + Data_Sisgef.mtbExtratosExpressasqtd_volumes_extra.AsFloat; Data_Sisgef.mtbFechamentoExpressasqtd_atraso.AsInteger := Data_Sisgef.mtbFechamentoExpressasqtd_atraso.AsInteger + Data_Sisgef.mtbExtratosExpressasqtd_atraso.AsInteger; Data_Sisgef.mtbFechamentoExpressasval_producao.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_producao.AsFloat + Data_Sisgef.mtbExtratosExpressasval_producao.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_total_ticket.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_total_ticket.AsFloat + Data_Sisgef.mtbExtratosExpressasval_total_empresa.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_extravios.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_extravios.AsFloat + Data_Sisgef.mtbExtratosExpressasval_extravios.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_debitos.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_debitos.AsFloat + Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_creditos.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_creditos.AsFloat + Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat + Data_Sisgef.mtbExtratosExpressasval_total_expressa.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_volume_extra.AsFloat := Data_Sisgef.mtbFechamentoExpressasval_volume_extra.AsFloat + Data_Sisgef.mtbExtratosExpressasval_volumes_extra.AsFloat; Data_Sisgef.mtbFechamentoExpressasCampoEmpresa.AsString := '00003'; Data_Sisgef.mtbFechamentoExpressasCampoCodigoPessoa.AsString := Format('%.6d', [StrToIntDef(sBimer,0)]); Data_Sisgef.mtbFechamentoExpressasCampoNomeTitulo.AsString := sFavorecido; Data_Sisgef.mtbFechamentoExpressasCampoCNPJCPFPessoa.AsString := Common.Utils.TUtils.DesmontaCPFCNPJ(sCPFCNPJ); Data_Sisgef.mtbFechamentoExpressasCampoNumeroTitulo.AsString := sTitulo; Data_Sisgef.mtbFechamentoExpressasCampoNaturezaLancamento.AsString := '000054'; Data_Sisgef.mtbFechamentoExpressasCampoFormaPagamento.AsString := '000011'; Data_Sisgef.mtbFechamentoExpressasCampoAgencia.AsString := sAgencia; Data_Sisgef.mtbFechamentoExpressasCampoConta.AsString := sConta; Data_Sisgef.mtbFechamentoExpressasCampoBanco.AsString := Format('%.3d', [StrToIntDef(sBanco,0)]); Data_Sisgef.mtbFechamentoExpressasCampoValorTitulo.AsString := FormatFloat( '###0.00' , Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat); Data_Sisgef.mtbFechamentoExpressasCampoDtEmissao.AsString := FormatDateTime('dd/mm/yyyy', Now); Data_Sisgef.mtbFechamentoExpressasCampoDtVencimento.AsString := FormatDateTime('dd/mm/yyyy', dtDate); Data_Sisgef.mtbFechamentoExpressasCampoModalidade.AsString := sModalidade; Data_Sisgef.mtbFechamentoExpressas.Post; end else begin Data_Sisgef.mtbFechamentoExpressas.Insert; Data_Sisgef.mtbFechamentoExpressasdat_inicio.AsDateTime := Data_Sisgef.mtbExtratosExpressasdat_inicio.AsDateTime; Data_Sisgef.mtbFechamentoExpressasdat_fim.AsDateTime := Data_Sisgef.mtbExtratosExpressasdat_final.AsDateTime; Data_Sisgef.mtbFechamentoExpressasqtd_volumes.AsInteger := Data_Sisgef.mtbExtratosExpressasqtd_volumes.AsInteger; Data_Sisgef.mtbFechamentoExpressasqtd_entregas.AsInteger := Data_Sisgef.mtbExtratosExpressasqtd_entregas.AsInteger; Data_Sisgef.mtbFechamentoExpressasqtd_volumes_extra.AsFloat := Data_Sisgef.mtbExtratosExpressasqtd_volumes_extra.AsFloat; Data_Sisgef.mtbFechamentoExpressasqtd_atraso.AsInteger := Data_Sisgef.mtbExtratosExpressasqtd_atraso.AsInteger; Data_Sisgef.mtbFechamentoExpressasval_producao.AsFloat := Data_Sisgef.mtbExtratosExpressasval_producao.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_total_ticket.AsFloat := Data_Sisgef.mtbExtratosExpressasval_total_empresa.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_extravios.AsFloat := Data_Sisgef.mtbExtratosExpressasval_extravios.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_debitos.AsFloat := Data_Sisgef.mtbExtratosExpressasval_debitos.AsFloat; Data_Sisgef.mtbFechamentoExpressasval_creditos.AsFloat := Data_Sisgef.mtbExtratosExpressasval_creditos.AsFloat; Data_Sisgef.mtbFechamentoExpressascod_tipo_expressa.AsInteger := iTipo; Data_Sisgef.mtbFechamentoExpressasnom_expressa.AsString := sNome; Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat := Data_Sisgef.mtbExtratosExpressasval_total_expressa.AsFloat; Data_Sisgef.mtbFechamentoExpressasnom_banco.AsString := sNomeBanco; Data_Sisgef.mtbFechamentoExpressasnum_agencia.AsString := sAgencia; Data_Sisgef.mtbFechamentoExpressasnum_conta.AsString := sConta; Data_Sisgef.mtbFechamentoExpressasnom_favorecido.AsString := sFavorecido; Data_Sisgef.mtbFechamentoExpressasnum_cpf_cnpj.AsString := sCPFCNPJ; Data_Sisgef.mtbFechamentoExpressasdes_tipo_conta.AsString := sTipoConta; Data_Sisgef.mtbFechamentoExpressasqtd_pfp.AsInteger := 0; Data_Sisgef.mtbFechamentoExpressasval_volume_extra.AsFloat := Data_Sisgef.mtbExtratosExpressasval_volumes_extra.AsFloat; Data_Sisgef.mtbFechamentoExpressascod_expressa.AsInteger := iCodigo; Data_Sisgef.mtbFechamentoExpressasdes_unique_key.AsString := Data_Sisgef.mtbExtratosExpressasdes_unique_key.AsString; Data_Sisgef.mtbFechamentoExpressasdat_credito.AsDateTime := Data_Sisgef.mtbExtratosExpressasdat_credito.AsDateTime; Data_Sisgef.mtbFechamentoExpressasdom_boleto.AsInteger := 0; Data_Sisgef.mtbFechamentoExpressasnum_extrato.AsString := Data_Sisgef.mtbExtratosExpressasnum_extrato.AsString; Data_Sisgef.mtbFechamentoExpressasCampoEmpresa.AsString := '00003'; Data_Sisgef.mtbFechamentoExpressasCampoCodigoPessoa.AsString := Format('%.6d', [StrToIntDef(sBimer,0)]); Data_Sisgef.mtbFechamentoExpressasCampoNomeTitulo.AsString := sFavorecido; Data_Sisgef.mtbFechamentoExpressasCampoCNPJCPFPessoa.AsString := Common.Utils.TUtils.DesmontaCPFCNPJ(sCPFCNPJ); Data_Sisgef.mtbFechamentoExpressasCampoNumeroTitulo.AsString := sTitulo; Data_Sisgef.mtbFechamentoExpressasCampoNaturezaLancamento.AsString := '000054'; Data_Sisgef.mtbFechamentoExpressasCampoFormaPagamento.AsString := '000011'; Data_Sisgef.mtbFechamentoExpressasCampoAgencia.AsString := sAgencia; Data_Sisgef.mtbFechamentoExpressasCampoConta.AsString := sConta; Data_Sisgef.mtbFechamentoExpressasCampoBanco.AsString := Format('%.3d', [StrToIntDef(sBanco,0)]); Data_Sisgef.mtbFechamentoExpressasCampoValorTitulo.AsString := FormatFloat( '###0.00' , Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat); Data_Sisgef.mtbFechamentoExpressasCampoDtEmissao.AsString := FormatDateTime('dd/mm/yyyy', Now); Data_Sisgef.mtbFechamentoExpressasCampoDtVencimento.AsString := FormatDateTime('dd/mm/yyyy', dtDate); Data_Sisgef.mtbFechamentoExpressasCampoModalidade.AsString := sModalidade; Data_Sisgef.mtbFechamentoExpressas.Post; end; iConta := Data_Sisgef.mtbExtratosExpressas.RecNo; Synchronize(UpdateCount); Data_Sisgef.mtbExtratosExpressas.Next; end; if not Data_Sisgef.mtbFechamentoExpressas.IsEmpty then Data_Sisgef.mtbFechamentoExpressas.First; while not Data_Sisgef.mtbFechamentoExpressas.Eof do begin if Data_Sisgef.mtbFechamentoExpressasval_total.AsFloat <= 0 then begin Data_Sisgef.mtbFechamentoExpressas.Delete; end else begin if not Data_Sisgef.mtbFechamentoExpressas.Eof then Data_Sisgef.mtbFechamentoExpressas.Next; end; end; if not Data_Sisgef.mtbFechamentoExpressas.IsEmpty then Data_Sisgef.mtbFechamentoExpressas.First; Except on E: Exception do begin Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR); bCancel := True; end; end; Synchronize(FinalizeProc); finally if bCancel then begin Application.MessageBox('Processo Cancelado!', 'Consolidação do extrato', MB_OK + MB_ICONWARNING); end else begin if FbGravar then begin Synchronize(ShowForm); end else begin Synchronize(SalvaConsolidacao); end; end; FBases.Free; FEntregadores.Free; FCadastro.Free; end; end; procedure TThread_ConsolidaExtratoExpressa.FinalizeProc; begin view_ExtratoExpressas.dsExtrato.Enabled := True; view_ExtratoExpressas.dxLayoutItem19.Visible := False; if FbGravar then begin view_ExtratoExpressas.actProcessar.Enabled := True; view_ExtratoExpressas.actEncerrarExtrato.Enabled := True; view_ExtratoExpressas.actAlterarCliente.Enabled := True; view_ExtratoExpressas.actVisualizarParamatros.Enabled:= True; end; view_ExtratoExpressas.actFechar.Enabled := True; view_ExtratoExpressas.tvExtrato.ViewData.Expand(True); end; procedure TThread_ConsolidaExtratoExpressa.SalvaConsolidacao; var FFechamento : TFechamentoExpressasControl; begin try FFechamento := TFechamentoExpressasControl.Create; if not FFechamento.SaveDB(Data_Sisgef.mtbFechamentoExpressas) then begin Application.MessageBox('Consolidação NÃO foi gravada no banco de dados!', 'Atenção', MB_OK + MB_ICONWARNING); end else begin Application.MessageBox('Consolidação gravada no banco de dados!', 'Gravação', MB_OK + MB_ICONINFORMATION); end; finally FFechamento.Free; end; end; procedure TThread_ConsolidaExtratoExpressa.ShowForm; begin if not Assigned(view_ConsolidacaoExpressas) then begin view_ConsolidacaoExpressas := Tview_ConsolidacaoExpressas.Create(Application); end; view_ConsolidacaoExpressas.Show; end; procedure TThread_ConsolidaExtratoExpressa.StartProc; begin view_ExtratoExpressas.dsExtrato.Enabled := False; view_ExtratoExpressas.actProcessar.Enabled := False; view_ExtratoExpressas.actEncerrarExtrato.Enabled := False; view_ExtratoExpressas.actAlterarCliente.Enabled := False; view_ExtratoExpressas.actVisualizarParamatros.Enabled:= False; if FbGravar then begin view_ExtratoExpressas.actFechar.Enabled := False; end; end; procedure TThread_ConsolidaExtratoExpressa.UpdateCount; begin if not view_ExtratoExpressas.dxLayoutItem19.Visible then view_ExtratoExpressas.dxLayoutItem19.Visible := True; view_ExtratoExpressas.cxLabel2.Caption := iConta.ToString; view_ExtratoExpressas.cxLabel2.Refresh; end; end.
unit Route4MeManagerUnit; interface uses Classes, SysUtils, OptimizationParametersUnit, DataObjectUnit, IRoute4MeManagerUnit, AddressBookContactUnit, AddressBookContactActionsUnit, OptimizationActionsUnit, RouteActionsUnit, IConnectionUnit, UserActionsUnit, AddressNoteActionsUnit, AddressActionsUnit, AvoidanceZoneUnit, AvoidanceZoneActionsUnit, OrderActionsUnit, ActivityActionsUnit, TrackingActionsUnit, GeocodingActionsUnit, TerritoryActionsUnit, VehicleActionsUnit, FileUploadingActionsUnit, TelematicActionsUnit; type TRoute4MeManager = class(TInterfacedObject, IRoute4MeManager) private FConnection: IConnection; FAddressBookContact: TAddressBookContactActions; FOptimization: TOptimizationActions; FRoute: TRouteActions; FUser: TUserActions; FAddressNote: TAddressNoteActions; FAddress: TAddressActions; FAvoidanceZone: TAvoidanceZoneActions; FGeocoding: TGeocodingActions; FOrder: TOrderActions; FActivity: TActivityActions; FTracking: TTrackingActions; FTerritory: TTerritoryActions; FVehicle: TVehicleActions; FUploading: TFileUploadingActions; FTelematics: TTelematicActions; public constructor Create(Connection: IConnection); destructor Destroy; override; procedure Clear; procedure SetConnectionProxy(Host: String; Port: integer; Username, Password: String); function Optimization: TOptimizationActions; function Route: TRouteActions; function AddressBookContact: TAddressBookContactActions; function User: TUserActions; function AddressNote: TAddressNoteActions; function Address: TAddressActions; function AvoidanceZone: TAvoidanceZoneActions; function Geocoding: TGeocodingActions; function Order: TOrderActions; function ActivityFeed: TActivityActions; function Tracking: TTrackingActions; function Territory: TTerritoryActions; function Vehicle: TVehicleActions; function Uploading: TFileUploadingActions; function Telematics: TTelematicActions; function Connection: IConnection; end; implementation { TRoute4MeManager } uses EnumsUnit; function TRoute4MeManager.AddressNote: TAddressNoteActions; begin if (FAddressNote = nil) then FAddressNote := TAddressNoteActions.Create(FConnection, Self); Result := FAddressNote; end; function TRoute4MeManager.AvoidanceZone: TAvoidanceZoneActions; begin if (FAvoidanceZone = nil) then FAvoidanceZone := TAvoidanceZoneActions.Create(FConnection); Result := FAvoidanceZone; end; procedure TRoute4MeManager.Clear; begin FreeAndNil(FTelematics); FreeAndNil(FUploading); FreeAndNil(FVehicle); FreeAndNil(FTerritory); FreeAndNil(FTracking); FreeAndNil(FActivity); FreeAndNil(FOrder); FreeAndNil(FAvoidanceZone); FreeAndNil(FGeocoding); FreeAndNil(FAddress); FreeAndNil(FAddressNote); FreeAndNil(FUser); FreeAndNil(FRoute); FreeAndNil(FAddressBookContact); FreeAndNil(FOptimization); FConnection := nil; end; function TRoute4MeManager.Connection: IConnection; begin Result := FConnection; end; constructor TRoute4MeManager.Create(Connection: IConnection); begin FConnection := Connection; FAddressBookContact := nil; FOptimization := nil; FRoute := nil; FUser := nil; FAddressNote := nil; FAddress := nil; FAvoidanceZone := nil; FGeocoding := nil; FOrder := nil; FActivity := nil; FTracking := nil; FTerritory := nil; FVehicle := nil; FUploading := nil; FTelematics := nil; end; destructor TRoute4MeManager.Destroy; begin Clear; inherited; end; function TRoute4MeManager.Geocoding: TGeocodingActions; begin if (FGeocoding = nil) then FGeocoding := TGeocodingActions.Create(FConnection); Result := FGeocoding; end; function TRoute4MeManager.Optimization: TOptimizationActions; begin if (FOptimization = nil) then FOptimization := TOptimizationActions.Create(FConnection); Result := FOptimization; end; function TRoute4MeManager.Order: TOrderActions; begin if (FOrder = nil) then FOrder := TOrderActions.Create(FConnection); Result := FOrder; end; function TRoute4MeManager.Route: TRouteActions; begin if (FRoute = nil) then FRoute := TRouteActions.Create(FConnection); Result := FRoute; end; procedure TRoute4MeManager.SetConnectionProxy(Host: String; Port: integer; Username, Password: String); begin FConnection.SetProxy(Host, Port, Username, Password); end; function TRoute4MeManager.Telematics: TTelematicActions; begin if (FTelematics = nil) then FTelematics := TTelematicActions.Create(FConnection); Result := FTelematics; end; function TRoute4MeManager.Territory: TTerritoryActions; begin if (FTerritory = nil) then FTerritory := TTerritoryActions.Create(FConnection); Result := FTerritory; end; function TRoute4MeManager.Tracking: TTrackingActions; begin if (FTracking = nil) then FTracking := TTrackingActions.Create(FConnection); Result := FTracking; end; function TRoute4MeManager.Uploading: TFileUploadingActions; begin if (FUploading = nil) then FUploading := TFileUploadingActions.Create(FConnection); Result := FUploading; end; function TRoute4MeManager.User: TUserActions; begin if (FUser = nil) then FUser := TUserActions.Create(FConnection); Result := FUser; end; function TRoute4MeManager.Vehicle: TVehicleActions; begin if (FVehicle = nil) then FVehicle := TVehicleActions.Create(FConnection); Result := FVehicle; end; function TRoute4MeManager.ActivityFeed: TActivityActions; begin if (FActivity = nil) then FActivity := TActivityActions.Create(FConnection); Result := FActivity; end; function TRoute4MeManager.Address: TAddressActions; begin if (FAddress = nil) then FAddress := TAddressActions.Create(FConnection); Result := FAddress; end; function TRoute4MeManager.AddressBookContact: TAddressBookContactActions; begin if (FAddressBookContact = nil) then FAddressBookContact := TAddressBookContactActions.Create(FConnection); Result := FAddressBookContact; end; end.
unit TransportInterfaces; interface type TCargoType = byte; TCargoValue = shortint; type ICargoPoint = interface function getX : integer; function getY : integer; function getValue : TCargoValue; procedure setValue( value : TCargoValue ); end; ICargoLayer = interface function CreatePoint( x, y : integer ) : ICargoPoint; procedure DelPoint( x, y : integer ); procedure SetPoint( x, y : integer; Value : TCargoValue ); function GetCargoValue( x, y : integer ) : TCargoValue; function GetCargoSlope( x, y, dx, dy : integer ) : single; end; ICargoSystem = interface function GetLayer( CargoType : TCargoType ) : ICargoLayer; end; implementation end.
{ Kryvich's Delphi Localizer Class Copyright (C) 2006, 2007, 2008 Kryvich, Belarusian Linguistic Software team. } {$include version.inc} unit uFreeLocalizer; interface uses Classes; type // Method of error processing TErrorProcessing = ( epSilent, // Just skip errors (default) - use for public releases epMessage, // Show message to a user - use for a beta testing epException, // Raise exception - use while develop and debug epDebug, // Use DebugOutputString epErrors // Append all messages to a string list ); // Translated form properties TResForm = class Name: string; // Form name Props: TStringList; // Property names Values: TStringList; // Translated property values end; // Dump of original func, pointers to Original & New funcs TFuncReplacement = class private OrigDump: packed array[0..4] of byte; OrigFunc, MyFunc: pointer; fReplaced: boolean; // Is func replaced now procedure SetReplaced(aReplaced: boolean); public constructor Create(aOrigFunc, aMyFunc: pointer); destructor Destroy; override; property Replaced: boolean read fReplaced write SetReplaced; end; // Events of Localizer TBeforeLanguageLoadEvent = procedure(Sender: TObject; const OldLanguageFile, NewLanguageFile: string) of object; TAfterLanguageLoadEvent = procedure(Sender: TObject; const LanguageFile: string) of object; TFreeLocalizer = class private fLanguageFile: string; // Loaded language file ResForms: array of TResForm; // List of all localized forms fAutoTranslate: boolean; InitInheritedRepl: TFuncReplacement; // InitInheritedComponent replacement fBeforeLanguageLoadEvent: TBeforeLanguageLoadEvent; fAfterLanguageLoadEvent: TAfterLanguageLoadEvent; fErrors: TStrings; // Check status of UTF8VCL library class function CheckUtf8vcl: boolean; // Get Humanize settings of a language file procedure GetEncoding(sl: TStringList; var Humanize: boolean; var HumanizedCR, HumanizedCRLF: WideString); // Delete old translations in ResForms procedure ClearResForms; // Load translations from file procedure LoadLanguageFile(const aLanguageFile: string); // Set value PropValue for property PropName in Component RootComp procedure TranslateProp(RootComp: TComponent; const PropName, PropValue: string); // Enable/disable translation of resource strings procedure SetTranslateResourceStrings(aTranslate: boolean); // Enable/Disable autotranslation feature procedure SetAutoTranslate(aAutoTranslate: boolean); // Called when error encountered procedure Error(const Mess: string); // Translate component (form) as component of class CompClassType procedure TranslateAs(Comp: TComponent; const CompClassType: TClass); // Get error messages from fErrors function GetErrors: string; public LanguageDir: string; // Directory with language files (optional) ErrorProcessing: TErrorProcessing; TickSetup : String; constructor Create; destructor Destroy; override; // Translate component (form) procedure Translate(Comp: TComponent); // Translate all forms on Screen procedure TranslateScreen; // Clear error messages in fErrors procedure ClearErrors; // Error messages (set ErrorProcessing to epErrors) property Errors: string read GetErrors; // Language file name. Set it to load a new translation property LanguageFile: string read fLanguageFile write LoadLanguageFile; // Enable/disable translation of resource strings property TranslateResourceStrings: boolean write SetTranslateResourceStrings; // Auto translate a form after creating property AutoTranslate: boolean read fAutoTranslate write SetAutoTranslate; // Occurs exactly before loading new language file // Call silent exception (Abort) to abort the operation property BeforeLanguageLoad: TBeforeLanguageLoadEvent read fBeforeLanguageLoadEvent write fBeforeLanguageLoadEvent; // Occurs exactly after loading new language // Do here necessary operations such as calling TranslateScreen (if AutoTranslate disabled) // and updating of controls state property AfterLanguageLoad: TAfterLanguageLoadEvent read fAfterLanguageLoadEvent write fAfterLanguageLoadEvent; end; var FreeLocalizer: TFreeLocalizer; implementation uses Windows, SysUtils, TypInfo, Forms, uStringUtils {$ifdef D7} ,uLegacyCode {$endif} {$ifndef D5} ,StrUtils {$endif}; const LngHeader = '; Kryvich''s Delphi Localizer Language File.'; sNewMark = '(!)'; sDelMark = '(x)'; var AnsiCP: LongWord; // current ANSI code-page identifier for the system {$ifndef D7}{$region 'EKdlError'}{$endif} type EKdlError = class (Exception) constructor Create(AMessage: string); end; EKdlSilentError = class (EKdlError) constructor Create; end; constructor EKdlError.Create(AMessage: string); begin inherited Create(AMessage); end; constructor EKdlSilentError.Create; begin inherited Create(''); end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'TResStringer'}{$endif} type TResStringer = class private LoadResRepl: TFuncReplacement; // LoadResString replacement ResStrings: TStringList; // Translated resource strings fTranslate: boolean; // Do translations of resource strings // Get resource string function GetString(Id: integer; var s: AnsiString): boolean; // Set translation status procedure SetTranslate(aTranslate: boolean); public constructor Create; destructor Destroy; override; // Read resource strings from sl into ResStrings procedure LoadResStrings(sl: TStringList; var i: integer; Humanize: boolean; const HumanizedCR, HumanizedCRLF: WideString; Utf8vclActive: boolean); property Translate: boolean read fTranslate write SetTranslate; end; var ResStringer: TResStringer; function MyLoadResString(ResStringRec: PResStringRec): AnsiString; begin if ResStringRec = nil then exit; if assigned(ResStringer) and ResStringer.Translate then begin if ResStringRec.Identifier >= 64*1024 then Result := PChar(ResStringRec.Identifier) else if not ResStringer.GetString(ResStringRec.Identifier, result) then begin ResStringer.Translate := false; result := System.LoadResString(ResStringRec); ResStringer.Translate := true; end; end else result := System.LoadResString(ResStringRec); end; { TResStringer } constructor TResStringer.Create; begin LoadResRepl := TFuncReplacement.Create(@System.LoadResString, @MyLoadResString); Translate := true; end; destructor TResStringer.Destroy; begin Translate := false; FreeAndNil(ResStrings); LoadResRepl.Free; inherited; end; procedure TResStringer.SetTranslate(aTranslate: boolean); begin LoadResRepl.Replaced := aTranslate; fTranslate := aTranslate; end; procedure TResStringer.LoadResStrings(sl: TStringList; var i: integer; Humanize: boolean; const HumanizedCR, HumanizedCRLF: WideString; Utf8vclActive: boolean); var s: string; ws, el: WideString; id: integer; oTranslate: boolean; begin oTranslate := Translate; Translate := false; if ResStrings <> nil then ResStrings.Clear else ResStrings := TStringList.Create; while i < sl.Count do begin s := sl[i]; if (s <> '') and (s[1] <> ';') then begin ws := UTF8Decode(s); if ws = '' then FreeLocalizer.Error('Bad UTF-8 line in language file:'#13#10'"' + sl[i] + '"'#13#10'Check file encoding!') else begin if ws[1] = '(' then begin if copy(ws, 1, length(sDelMark)) = sDelMark then FreeLocalizer.Error('Obsolete line in language file:'#13#10'"' + sl[i] + '"'#13#10'You have to delete it!') else if copy(ws, 1, length(sNewMark)) = sNewMark then FreeLocalizer.Error('Untranslated line in language file:'#13#10'"' + sl[i] + '"'#13#10'You have to translate it!'); end else begin if ws[1] = '[' then break; // 65167_ComConst_SOleError='OLE error %.8x' WideSplitBy(ws, '_', el); if not TryStrToInt(el, id) then FreeLocalizer.Error('Bad resource ID in language file: "' + el + '"'); WideSplitBy(ws, '=', el); //#TODO2 translate here only ws := LngToString(ws, Humanize, HumanizedCR, HumanizedCRLF, sLineBreak); if Utf8vclActive then s := ws // Wide --> UTF-8 else WideToAnsiString(ws, s, GetACP); ResStrings.Add(s); ResStrings.Objects[ResStrings.Count-1] := pointer(id); end; end; end; inc(i); end; Translate := oTranslate and (ResStrings.Count > 0); end; function TResStringer.GetString(Id: integer; var s: AnsiString): boolean; var i0, i1, i2: integer; begin if ResStrings = nil then result := false else begin i0 := 0; i2 := ResStrings.Count-1; while i0 < i2 do begin i1 := (i0+i2) div 2; if Id > integer(ResStrings.Objects[i1]) then i0 := i1+1 else i2 := i1; end; result := (Id = integer(ResStrings.Objects[i0])); if result then s := ResStrings[i0]; end; end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'TFreeLocalizer'}{$endif} {$ifndef D7}{$region 'TFreeLocalizer - Form translation'}{$endif} { TFreeLocalizer } class function TFreeLocalizer.CheckUtf8vcl: boolean; begin Result := GetACP = CP_UTF8; end; procedure TFreeLocalizer.ClearErrors; begin fErrors.Clear; end; procedure TFreeLocalizer.ClearResForms; var i: integer; begin for i := 0 to length(ResForms) - 1 do begin ResForms[i].Props.Free; ResForms[i].Values.Free; ResForms[i].Free; end; SetLength(ResForms, 0); end; constructor TFreeLocalizer.Create; begin fErrors := TStringList.Create; ResStringer := TResStringer.Create; end; destructor TFreeLocalizer.Destroy; begin SetAutoTranslate(False); ResStringer.Free; ClearResForms; fErrors.Free; inherited; end; procedure TFreeLocalizer.Error(const Mess: string); begin case ErrorProcessing of epMessage: Application.MessageBox(pChar(Mess), 'K.D.L. Error', MB_ICONERROR+MB_OK+MB_DEFBUTTON1+MB_APPLMODAL); epException: raise EKdlError.Create(Mess); epDebug: OutputDebugString(pChar(Mess)); epErrors: fErrors.Append(Mess); end; end; procedure TFreeLocalizer.GetEncoding(sl: TStringList; var Humanize: boolean; var HumanizedCR, HumanizedCRLF: WideString); var i: integer; s: string; begin Humanize := false; HumanizedCR := defHumanizeDivider; HumanizedCRLF := defHumanizeDivider; i := sl.IndexOfName('Humanize'); if i >= 0 then begin {$ifdef D6} Humanize := (TStringsGetValueFromIndex(sl, i) = '1'); {$else} Humanize := (sl.ValueFromIndex[i] = '1'); {$endif} i := sl.IndexOfName('HumanizeDivider'); if i >= 0 then begin // For backward compatibility {$ifdef D6} s := TStringsGetValueFromIndex(sl, i); {$else} s := sl.ValueFromIndex[i]; {$endif} HumanizedCR := UTF8Decode(s); HumanizedCRLF := HumanizedCR; end; i := sl.IndexOfName('HumanizedCR'); if i >= 0 then begin {$ifdef D6} s := TStringsGetValueFromIndex(sl, i); {$else} s := sl.ValueFromIndex[i]; {$endif} HumanizedCR := UTF8Decode(s); end; i := sl.IndexOfName('HumanizedCRLF'); if i >= 0 then begin {$ifdef D6} s := TStringsGetValueFromIndex(sl, i); {$else} s := sl.ValueFromIndex[i]; {$endif} HumanizedCRLF := UTF8Decode(s); end; end; end; function TFreeLocalizer.GetErrors: string; begin Result := fErrors.Text; end; procedure TFreeLocalizer.LoadLanguageFile(const aLanguageFile: string); const LngExt = '.lng'; var FullLangFile: string; sl: TStringList; i, iResForms: integer; s: string; ws, el: WideString; Utf8vclActive: boolean; // Is the UTF8VCL library linked and active? Humanize: boolean; HumanizedCR, HumanizedCRLF: WideString; begin if AnsiCP = 0 then AnsiCP := 1250; if AnsiCP = 65001 then raise EKdlError.Create('K.D.L. initialization error.'#13#10+ 'Please put uFreeLocalizer before UTF8VCL in an uses clause of Application'); if Assigned(fBeforeLanguageLoadEvent) then fBeforeLanguageLoadEvent(Self, LanguageFile, aLanguageFile); try ClearResForms; Utf8vclActive := CheckUtf8vcl; // Build Full name of language file FullLangFile := LanguageDir; if (FullLangFile <> '') and not (FullLangFile[length(FullLangFile)] in ['/', '\']) then FullLangFile := FullLangFile + '\'; FullLangFile := FullLangFile + aLanguageFile; if not AnsiEndsText(LngExt, FullLangFile) then FullLangFile := FullLangFile + LngExt; sl := TStringList.Create; try sl.LoadFromFile(FullLangFile); if (sl.Count <= 0) or ((sl[0] <> LngHeader) and (sl[0] <> UnicodeLabel + LngHeader)) then begin Error('Bad signature in language file "' + FullLangFile + '"'); exit; end; GetEncoding(sl, Humanize, HumanizedCR, HumanizedCRLF); iResForms := -1; i := 1; while i < sl.Count do begin s := sl[i]; if (s <> '') and (s[1] <> ';') then begin if s[1] = '[' then begin if UpperCase(s) = '[RESOURCESTRINGS]' then begin inc(i); ResStringer.LoadResStrings(sl, i, Humanize, HumanizedCR, HumanizedCRLF, Utf8vclActive); continue; end else begin if copy(s, 2, length(sDelMark)) = sDelMark then begin Error('Deleted component in language file:'#13#10'"' + sl[i] + '"'#13#10'You have to remove it!'); exit; end; inc(iResForms); SetLength(ResForms, iResForms+1); ResForms[iResForms] := TResForm.Create; ResForms[iResForms].Name := copy(s, 2, length(s)-2); ResForms[iResForms].Props := TStringList.Create; ResForms[iResForms].Values := TStringList.Create; end; end else if iResForms >= 0 then begin ws := UTF8Decode(s); if ws = '' then Error('Bad UTF-8 line in language file:'#13#10'"' + sl[i] + '"'#13#10'Check file encoding!') else begin if ws[1] = '(' then begin if copy(ws, 1, length(sDelMark)) = sDelMark then Error('Obsolete line in language file:'#13#10'"' + sl[i] + '"'#13#10'You have to remove it!') else if copy(ws, 1, length(sNewMark)) = sNewMark then Error('Untranslated line in language file:'#13#10'"' + sl[i] + '"'#13#10'You have to translate it!'); end else begin WideSplitBy(ws, '=', el); ReplaceNew(ws,TickSetup ); //#TODO2 translate here only ws := LngToString(ws, Humanize, HumanizedCR, HumanizedCRLF, #13); if Utf8vclActive then s := ws // Wide --> UTF-8 else WideToAnsiString(ws, s, GetACP); ResForms[iResForms].Values.Add(s); // btnNewForm.Caption{1} -> drop version # WideSplitBy(el, '{', ws); if ws = '' then begin Error('Bad line in language file: "' + sl[i] + '"'); exit; end; ResForms[iResForms].Props.Add(ws); end; end; end; end; inc(i); end; finally sl.Free; end; fLanguageFile := aLanguageFile; if AutoTranslate then TranslateScreen; if Assigned(fAfterLanguageLoadEvent) then fAfterLanguageLoadEvent(Self, fLanguageFile); except on E: Exception do Error('Error while loading language file "' + FullLangFile + '"'#13#10 + E.Message); end; end; procedure TFreeLocalizer.TranslateAs(Comp: TComponent; const CompClassType: TClass); var ResForm: TResForm; ParentClassType: TClass; i: integer; begin // Whether the component's ancestor can contain localizable controls? ParentClassType := CompClassType.ClassParent; if (ParentClassType <> TForm) and (ParentClassType <> TDataModule) and (ParentClassType <> TObject) then TranslateAs(Comp, ParentClassType) else begin // Translate nested frames for i := 0 to Comp.ComponentCount - 1 do if Comp.Components[i] is TFrame then FreeLocalizer.Translate(Comp.Components[i]); end; ResForm := Nil; for i := 0 to length(ResForms)-1 do if CompClassType.ClassName = ResForms[i].Name then begin ResForm := ResForms[i]; break; end; if ResForm = Nil then exit; // This component not translated for i := 0 to ResForm.Props.Count - 1 do TranslateProp(Comp, ResForm.Props[i], ResForm.Values[i]); end; procedure TFreeLocalizer.Translate(Comp: TComponent); begin TranslateAs(Comp, Comp.ClassType); end; procedure TFreeLocalizer.TranslateProp(RootComp: TComponent; const PropName, PropValue: string); procedure SetStringsProp(st: TStrings); var i: integer; s, el: string; begin s := PropValue; i := 0; st.BeginUpdate; try while s <> '' do begin SplitBy(s, ListDivider, el); //#TODO1 May need to convert e1 here .,. if i < st.Count then st[i] := el else st.Add(el); inc(i); end; while st.Count > i do st.Delete(st.Count-1); finally st.EndUpdate; end; end; procedure SetProp(Obj: TObject; const pName: string); var PropInfo: PPropInfo; begin if Obj is TStrings then SetStringsProp(Obj as TStrings) else begin PropInfo := GetPropInfo(Obj.ClassInfo, pName); if PropInfo <> Nil // Property exists then {$ifdef D7} SetPropValue(Obj, pName, PropValue) {$else} SetPropValue(Obj, PropInfo, PropValue) {$endif} else raise EKdlSilentError.Create; end; end; label CheckComp, CheckClass; var s, el: string; Comp, cmp, OwnerComp: TComponent; obj: TObject; PropInfo: PPropInfo; i: integer; begin try OwnerComp := RootComp; Comp := RootComp; s := PropName; repeat SplitBy(s, '.', el); CheckComp: if s = '' then begin // el is property name SetProp(Comp, el); exit; end; cmp := Comp.FindComponent(el); if cmp = Nil then break; Comp := cmp; if Comp is TFrame then OwnerComp := Comp; until false; // Check for nested classes obj := Comp; while Obj is TPersistent do begin PropInfo := GetPropInfo(obj.ClassInfo, el); if (PropInfo = Nil) or (PropInfo.PropType^.Kind <> tkClass) then break; // Such class property not exists {$ifdef D7} obj := pointer(longint(GetPropValue(Obj, el))); {$else} obj := pointer(longint(GetPropValue(Obj, PropInfo))); {$endif} CheckClass: SplitBy(s, '.', el); if s = '' then begin // el is property name SetProp(obj, el); exit; end; if Obj is TCollection then break; end; // Check for nested TCollection if (obj is TCollection) and (length(el) >= 3) and (el[1] = '(') and (el[length(el)] = ')') and TryStrToInt(copy(el, 2, length(el)-2), i) then begin // el = '(0)' s = ...rest of nested classes and properties obj := (obj as TCollection).Items[i]; goto CheckClass; end; // Try to find out el among components of OwnerComp if Comp <> OwnerComp then begin Comp := OwnerComp; goto CheckComp; end; // yet untranslated... raise EKdlSilentError.Create; except on E: EKdlSilentError do begin s := 'Unknown property "%s" found in component "%s".'#13#10 + 'Remove it from language file'; Error(Format(s, [PropName, RootComp.Name])); end; on E: Exception do begin s := 'Translation error of property "%s" in component "%s"'#13#10 + E.Message; Error(Format(s, [PropName, RootComp.Name])); end; end; end; procedure TFreeLocalizer.TranslateScreen; var i: integer; begin for i := 0 to Screen.FormCount - 1 do Translate(Screen.Forms[i]); end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'TFreeLocalizer - Auto translation feature'}{$endif} function MyInitInheritedComponent(Instance: TComponent; RootAncestor: TClass): Boolean; begin FreeLocalizer.InitInheritedRepl.Replaced := false; try result := InitInheritedComponent(Instance, RootAncestor); FreeLocalizer.Translate(Instance); finally FreeLocalizer.InitInheritedRepl.Replaced := true; end; end; procedure TFreeLocalizer.SetAutoTranslate(aAutoTranslate: boolean); begin if aAutoTranslate = fAutoTranslate then exit; if aAutoTranslate then begin InitInheritedRepl := TFuncReplacement.Create( @Classes.InitInheritedComponent, @MyInitInheritedComponent); InitInheritedRepl.Replaced := true; end else begin InitInheritedRepl.Free; end; fAutoTranslate := aAutoTranslate; end; procedure TFreeLocalizer.SetTranslateResourceStrings(aTranslate: boolean); begin ResStringer.Translate := aTranslate; end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'TFuncReplacement'}{$endif} { TFuncReplacement } type PWin9xDebugThunk = ^TWin9xDebugThunk; TWin9xDebugThunk = packed record PUSH: Byte; // PUSH instruction opcode ($68) Addr: Pointer; // The actual address of the DLL routine JMP: Byte; // JMP instruction opcode ($E9) Rel: Integer; // Relative displacement (a Kernel32 address) end; PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp; TAbsoluteIndirectJmp = packed record OpCode: Word; // Addr: PPointer; Addr: ^Pointer; end; function IsWin9xDebugThunk(AnAddr: Pointer): Boolean; // extract from JclPeImage.pas { -> EAX: AnAddr } asm TEST EAX, EAX JZ @@NoThunk CMP BYTE PTR [EAX].TWin9xDebugThunk.PUSH, $68 JNE @@NoThunk CMP BYTE PTR [EAX].TWin9xDebugThunk.JMP, $E9 JNE @@NoThunk XOR EAX, EAX MOV AL, 1 JMP @@exit @@NoThunk: XOR EAX, EAX @@exit: end; function GetActualAddr(Proc: Pointer): Pointer; begin if Proc <> nil then begin if (SysUtils.Win32Platform <> VER_PLATFORM_WIN32_NT) and IsWin9xDebugThunk(Proc) then Proc := PWin9xDebugThunk(Proc).Addr; if PAbsoluteIndirectJmp(Proc).OpCode = $25FF then // JMP mem32 Result := Pointer(PAbsoluteIndirectJmp(Proc).Addr^) else Result := Proc; end else Result := nil; end; constructor TFuncReplacement.Create(aOrigFunc, aMyFunc: pointer); var OldProtect: cardinal; begin OrigFunc := GetActualAddr(aOrigFunc); MyFunc := aMyFunc; move(OrigFunc^, OrigDump[0], 5); VirtualProtect(OrigFunc, 5, PAGE_EXECUTE_READWRITE, @OldProtect); end; destructor TFuncReplacement.Destroy; begin SetReplaced(false); inherited; end; procedure TFuncReplacement.SetReplaced(aReplaced: boolean); var Offset: integer; begin if aReplaced = fReplaced then exit; if aReplaced then begin // Set MyFunc Offset := integer(MyFunc) - integer(OrigFunc) - 5; byte(OrigFunc^) := $E9; move(Offset, pointer(cardinal(OrigFunc)+1)^, 4); end else // Set OrigFunc move(OrigDump[0], OrigFunc^, 5); fReplaced := aReplaced; end; {$ifndef D7}{$endregion}{$endif} Initialization AnsiCP := GetACP; SetMultiByteConversionCodePage(CP_THREAD_ACP); FreeLocalizer := TFreeLocalizer.Create; Finalization FreeLocalizer.Free; end.
unit UDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBaseControl, FMX.TMSPlannerBase, FMX.TMSPlannerData, FMX.TMSPlanner, FMX.ListBox, FMX.Layouts, UIConsts, FMX.TMSBitmapContainer, FMX.Objects, FMX.Colors; type TForm1 = class(TForm) TMSFMXPlanner1: TTMSFMXPlanner; Panel4: TPanel; Label1: TLabel; ComboBox1: TComboBox; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; Rectangle1: TRectangle; Rectangle2: TRectangle; Label2: TLabel; Label3: TLabel; Panel1: TPanel; lblPatient: TLabel; imgPatient: TImage; Panel2: TPanel; chkOperation: TCheckBox; Label4: TLabel; Image1: TImage; Label5: TLabel; cboCategory: TColorComboBox; Label6: TLabel; procedure ComboBox1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TMSFMXPlanner1AfterDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItem: TTMSFMXPlannerItem); procedure TMSFMXPlanner1IsDateTimeInActive(Sender: TObject; ADateTime: TDateTime; APosition: Integer; var AInActive: Boolean); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure TMSFMXPlanner1GetCustomContentPanel(Sender: TObject; AItem: TTMSFMXPlannerItem; var AContentPanel: TControl); procedure TMSFMXPlanner1CustomContentPanelToItem(Sender: TObject; AContentPanel: TControl; AItem: TTMSFMXPlannerItem); procedure TMSFMXPlanner1ItemToCustomContentPanel(Sender: TObject; AItem: TTMSFMXPlannerItem; AContentPanel: TControl); procedure TMSFMXPlanner1BeforeOpenInplaceEditor(Sender: TObject; AStartTime, AEndTime: TDateTime; APosition: Integer; AItem: TTMSFMXPlannerItem; var ACanOpen: Boolean); procedure TMSFMXPlanner1GetItemTitleText(Sender: TObject; AItem: TTMSFMXPlannerItem; AMode: TTMSFMXPlannerGetTextMode; var ATitle: string); procedure TMSFMXPlanner1BeforeDrawItemTitleText(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItem: TTMSFMXPlannerItem; ATitle: string; var AAllow: Boolean); procedure TMSFMXPlanner1AfterOpenUpdateDialog(Sender: TObject; AStartTime, AEndTime: TDateTime; APosition: Integer; AItem: TTMSFMXPlannerItem); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses DateUtils; {$R *.fmx} procedure TForm1.Button1Click(Sender: TObject); begin TMSFMXPlanner1.EditItem(TMSFMXPlanner1.Items[0]); end; procedure TForm1.Button2Click(Sender: TObject); begin if TMSFMXPlanner1.IsEditing then TMSFMXPlanner1.CancelEditing; end; procedure TForm1.ComboBox1Change(Sender: TObject); begin TMSFMXPlanner1.Interaction.UpdateMode := TTMSFMXPlannerUpdateMode(ComboBox1.ItemIndex); end; procedure TForm1.FormCreate(Sender: TObject); var lbl: TLabel; res: TTMSFMXPlannerResource; it: TTMSFMXPlannerItem; dt: TDateTime; begin Image1.Bitmap.Assign(TMSFMXBitmapContainer1.FindBitmap('warning')); label4.Text := 'Change the editing mode with the combobox on the top left. Click on the item to select it and click again to start editing.'+#13#10#13#10+ '1. The patiŽnts for Dr. Sheryl Simmons and Dr. Mark Hall can be moved, sized and edited through the dialog and inplace editor.'+#13#10+ '2. The patiŽnts for Dr. Gregory House cannot be moved nor sized, editing is limited to the dialog mode only and the content of the dialog is replaced with a custom dialog.'; TMSFMXPlanner1.BitmapContainer := TMSFMXBitmapContainer1; TMSFMXPlanner1.Interaction.UpdateMode := pumDialog; TMSFMXPlanner1.Resources.Clear; TMSFMXPlanner1.Mode := pmDay; dt := Now; TMSFMXPlanner1.ModeSettings.StartTime := dt; TMSFMXPlanner1.PositionsAppearance.TopFont.Size := 18; TMSFMXPlanner1.PositionsAppearance.TopFont.Style := [TFontStyle.fsBold]; res := TMSFMXPlanner1.Resources.Add; res.Name := 'Dr. Sheryl Simmons'; res.Text := '<img width="36" src="nurse"/> ' + res.Name; res := TMSFMXPlanner1.Resources.Add; res.Name := 'Dr. Gregory House'; res.Text := '<img width="36" src="surgeon"/> ' + res.Name; res := TMSFMXPlanner1.Resources.Add; res.Name := 'Dr. Mark Hall'; res.Text := '<img width="36" src="doctor"/> ' + res.Name; TMSFMXPlanner1.ItemsAppearance.Stroke.Kind := TBrushKind.bkSolid; TMSFMXPlanner1.ItemsAppearance.Stroke.Color := claDarkgray; TMSFMXPlanner1.ItemsAppearance.ActiveStroke.Color := claGreen; TMSFMXPlanner1.ItemsAppearance.ActiveStroke.Kind := TBrushKind.bkSolid; TMSFMXPlanner1.Interaction.MouseEditMode := pmemSingleClickOnSelectedItem; TMSFMXPlanner1.TimeLine.DisplayStart := 8; TMSFMXPlanner1.TimeLine.DisplayEnd := 41; TMSFMXPlanner1.DefaultItem.Color := claWhitesmoke; TMSFMXPlanner1.DefaultItem.ActiveColor := claLightgreen; TMSFMXPlanner1.DefaultItem.ActiveFontColor := claGreen; TMSFMXPlanner1.DefaultItem.ActiveTitleFontColor := claGreen; TMSFMXPlanner1.Items.Clear; it := TMSFMXPlanner1.Items.Add; it.StartTime := Int(dt) + EncodeTime(8, 0, 0, 0); it.EndTime := it.StartTime + EncodeTime(1, 30, 0, 0); it.Title := 'John Appleseed'; it.Text := 'Examination of the heart'; it.DataString := 'heart'; it := TMSFMXPlanner1.Items.Add; it.StartTime := Int(dt) + EncodeTime(9, 0, 0, 0); it.EndTime := it.StartTime + EncodeTime(2, 30, 0, 0); it.Title := 'Angela Parks'; it.Text := ''; it := TMSFMXPlanner1.Items.Add; it.Resource := 1; it.StartTime := Int(dt) + EncodeTime(9, 30, 0, 0); it.EndTime := it.StartTime + EncodeTime(3, 0, 0, 0); it.Movable := False; it.Sizeable := False; it.Title := 'John Appleseed'; it.Text := 'Bypass surgery of the heart<br><ul><li>Heart diagram<li>Scalpel<li>Anesthesia</ul>'; it.DataBoolean := False; it.DataString := 'heart'; it := TMSFMXPlanner1.Items.Add; it.Resource := 2; it.StartTime := Int(dt) + EncodeTime(14, 30, 0, 0); it.EndTime := it.StartTime + EncodeTime(1, 30, 0, 0); it.Title := 'John Appleseed'; it.Text := 'Heart surgery recovery'; it.DataString := 'heart'; lbl := TMSFMXPlanner1.GetEditingDialog.ResourceLabel; if Assigned(lbl) then lbl.Text := 'Doctor'; Fill.Color := claWhite; Fill.Kind := TBrushKind.bkSolid; Rectangle1.Fill.Assign(TMSFMXPlanner1.GridCellAppearance.InActiveFill); Rectangle2.Fill.Assign(TMSFMXPlanner1.GridCellAppearance.Fill); TMSFMXPlanner1.TimeLine.ViewStart := Int(dt) + EncodeTime(6, 0, 0, 0); end; procedure TForm1.TMSFMXPlanner1AfterDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItem: TTMSFMXPlannerItem); var bmp: TBitmap; rbmp: TRectF; begin if TMSFMXPlanner1.HasItem(AItem.StartTime, AItem.EndTime, TMSFMXPlanner1.ResourceToPosition(AItem.Resource), AItem.Index, False) then begin bmp := TMSFMXBitmapContainer1.FindBitmap('warning'); if Assigned(bmp) then begin rbmp := RectF(ARect.Right - 26, ARect.Bottom - 26, ARect.Right - 2, ARect.Bottom - 2); ACanvas.DrawBitmap(bmp, RectF(0, 0, bmp.Width, bmp.Height), rbmp, 1); end; end else if AItem.DataBoolean then begin bmp := TMSFMXBitmapContainer1.FindBitmap('ok'); if Assigned(bmp) then begin rbmp := RectF(ARect.Left + 2, ARect.Bottom - 26, ARect.Left + 26, ARect.Bottom - 2); ACanvas.DrawBitmap(bmp, RectF(0, 0, bmp.Width, bmp.Height), rbmp, 1); end; end; end; procedure TForm1.TMSFMXPlanner1AfterOpenUpdateDialog(Sender: TObject; AStartTime, AEndTime: TDateTime; APosition: Integer; AItem: TTMSFMXPlannerItem); begin if AItem.Resource = 1 then TMSFMXPlanner1.GetEditingDialog(AItem.Index).ButtonRemove.Visible := False; end; procedure TForm1.TMSFMXPlanner1BeforeDrawItemTitleText(Sender: TObject; ACanvas: TCanvas; ARect: TRectF; AItem: TTMSFMXPlannerItem; ATitle: string; var AAllow: Boolean); begin if AItem.DataBoolean then ACanvas.Font.Size := 12; end; procedure TForm1.TMSFMXPlanner1BeforeOpenInplaceEditor(Sender: TObject; AStartTime, AEndTime: TDateTime; APosition: Integer; AItem: TTMSFMXPlannerItem; var ACanOpen: Boolean); begin ACanOpen := APosition <> 1; end; function FindChild(AContainer: TControl; AName: String): TControl; var I: Integer; begin Result := nil; for I := 0 to AContainer.ControlsCount - 1 do begin if AContainer.Controls[I].Name = AName then begin Result := AContainer.Controls[I]; Break; end; Result := FindChild(AContainer.Controls[I], AName); end; end; procedure TForm1.TMSFMXPlanner1CustomContentPanelToItem(Sender: TObject; AContentPanel: TControl; AItem: TTMSFMXPlannerItem); var c: TCheckBox; b: TColorComboBox; begin c := FindChild(AContentPanel, 'chkOperation') as TCheckBox; b := FindChild(AContentPanel, 'cboCategory') as TColorComboBox; AItem.BeginUpdate; AItem.Color := b.Color; AItem.DataBoolean := c.IsChecked; AItem.EndUpdate; end; procedure TForm1.TMSFMXPlanner1GetCustomContentPanel(Sender: TObject; AItem: TTMSFMXPlannerItem; var AContentPanel: TControl); begin if Assigned(AItem) and (AItem.Resource = 1) then AContentPanel := Panel1; end; procedure TForm1.TMSFMXPlanner1GetItemTitleText(Sender: TObject; AItem: TTMSFMXPlannerItem; AMode: TTMSFMXPlannerGetTextMode; var ATitle: string); begin if AItem.DataBoolean and (AMode = pgtmDrawing) then ATitle := AItem.Title + ' [Operation Successful]'; end; procedure TForm1.TMSFMXPlanner1IsDateTimeInActive(Sender: TObject; ADateTime: TDateTime; APosition: Integer; var AInActive: Boolean); var dt: TDateTime; begin dt := TMSFMXPlanner1.ModeSettings.StartTime; case APosition of 0: begin AInActive := AInActive or ((CompareDateTime(ADateTime, Int(dt) + EncodeTime(11, 30, 0, 0)) in [GreaterThanValue, EqualsValue]) and (CompareDateTime(ADateTime, Int(dt) + EncodeTime(13, 30, 0, 0)) = LessThanValue)) or (CompareDateTime(ADateTime, Int(dt) + EncodeTime(18, 30, 0, 0)) in [GreaterThanValue, EqualsValue]); end; 1: begin AInActive := AInActive or ((CompareDateTime(ADateTime, Int(dt) + EncodeTime(11, 30, 0, 0)) in [GreaterThanValue, EqualsValue]) and (CompareDateTime(ADateTime, Int(dt) + EncodeTime(13, 30, 0, 0)) = LessThanValue)) or (CompareDateTime(ADateTime, Int(dt) + EncodeTime(20, 30, 0, 0)) in [GreaterThanValue, EqualsValue]); AInActive := AInActive and not (CompareDateTime(ADatetime, Int(dt) + EncodeTime(7, 0, 0, 0)) = EqualsValue); AInActive := AInActive and not (CompareDateTime(ADatetime, Int(dt) + EncodeTime(7, 30, 0, 0)) = EqualsValue); end; 2: begin AInActive := AInActive or ((CompareDateTime(ADateTime, Int(dt) + EncodeTime(11, 30, 0, 0)) in [GreaterThanValue, EqualsValue]) and (CompareDateTime(ADateTime, Int(dt) + EncodeTime(13, 30, 0, 0)) = LessThanValue)) or (CompareDateTime(ADateTime, Int(dt) + EncodeTime(16, 30, 0, 0)) in [GreaterThanValue, EqualsValue]); end; end; end; procedure TForm1.TMSFMXPlanner1ItemToCustomContentPanel(Sender: TObject; AItem: TTMSFMXPlannerItem; AContentPanel: TControl); var l: TLabel; c: TCheckBox; img: TImage; b: TColorComboBox; begin l := FindChild(AContentPanel, 'lblPatient') as TLabel; l.Text := 'PatiŽnt: ' + AItem.Title; c := FindChild(AContentPanel, 'chkOperation') as TCheckBox; c.IsChecked := AItem.DataBoolean; img := FindChild(AContentPanel, 'imgPatient') as TImage; img.Bitmap.Assign(TMSFMXBitmapContainer1.FindBitmap(AItem.DataString)); b := FindChild(AContentPanel, 'cboCategory') as TColorComboBox; b.Color := AItem.Color; end; end.
unit uModeloRelatorio; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBaseCadastro, Data.DB, Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, Vcl.ComCtrls, uDMModeloRelatorio, uModeloRelatorioController, Vcl.Mask, Vcl.DBCtrls, uFuncoesSIDomper, uImagens, uRevendaController, uRevenda; type TfrmModeloRelatorio = class(TfrmBaseCadastro) Label4: TLabel; Label5: TLabel; edtCodigo: TDBEdit; Label6: TLabel; DBEdit1: TDBEdit; Label7: TLabel; edtCodRevenda: TDBEdit; DBEdit2: TDBEdit; btnRevenda: TSpeedButton; edtObservacao: TDBEdit; procedure edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnFiltroClick(Sender: TObject); procedure dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormDestroy(Sender: TObject); procedure btnNovoClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnFecharEdicaoClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure dbDadosTitleClick(Column: TColumn); procedure FormShow(Sender: TObject); procedure edtCodRevendaExit(Sender: TObject); procedure btnRevendaClick(Sender: TObject); procedure edtCodRevendaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FController: TModeloRelatorioController; procedure Localizar(ATexto: string); procedure BuscarRevenda(AId, ACodigo: Integer); public { Public declarations } constructor create(APesquisar: Boolean = False); end; var frmModeloRelatorio: TfrmModeloRelatorio; implementation {$R *.dfm} uses uGrade, uDM, uFormatarTexto; procedure TfrmModeloRelatorio.btnEditarClick(Sender: TObject); begin FController.Editar(dbDados.Columns[0].Field.AsInteger, Self); inherited; if edtObservacao.Enabled then edtObservacao.SetFocus; end; procedure TfrmModeloRelatorio.btnExcluirClick(Sender: TObject); begin if TFuncoes.Confirmar('Excluir Registro?') then begin FController.Excluir(dm.IdUsuario, dbDados.Columns[0].Field.AsInteger); inherited; end; end; procedure TfrmModeloRelatorio.btnFecharEdicaoClick(Sender: TObject); begin FController.Cancelar; inherited; end; procedure TfrmModeloRelatorio.btnFiltroClick(Sender: TObject); begin inherited; Localizar(edtDescricao.Text); end; procedure TfrmModeloRelatorio.btnImprimirClick(Sender: TObject); begin Localizar(edtDescricao.Text); FController.Imprimir(dm.IdUsuario); inherited; end; procedure TfrmModeloRelatorio.btnNovoClick(Sender: TObject); begin FController.Novo(dm.IdUsuario); inherited; edtObservacao.SetFocus; end; procedure TfrmModeloRelatorio.btnRevendaClick(Sender: TObject); begin inherited; TFuncoes.CriarFormularioModal(TfrmRevenda.create(true)); if dm.IdSelecionado > 0 then BuscarRevenda(dm.IdSelecionado, 0); end; procedure TfrmModeloRelatorio.btnSalvarClick(Sender: TObject); begin FController.Salvar(dm.IdUsuario); FController.FiltrarCodigo(FController.CodigoAtual()); inherited; end; procedure TfrmModeloRelatorio.BuscarRevenda(AId, ACodigo: Integer); var RevendaController: TRevendaController; begin RevendaController := TRevendaController.Create; try try RevendaController.Pesquisar(AId, ACodigo); except On E: Exception do begin ShowMessage(E.Message); edtCodRevenda.SetFocus; end; end; finally TFuncoes.ModoEdicaoInsercao(FController.Model.CDSCadastro); FController.Model.CDSCadastroModR_Revenda.AsString := RevendaController.Model.CDSCadastroRev_Id.AsString; FController.Model.CDSCadastroRev_Codigo.AsString := RevendaController.Model.CDSCadastroRev_Codigo.AsString; FController.Model.CDSCadastroRev_Nome.AsString := RevendaController.Model.CDSCadastroRev_Nome.AsString; FreeAndNil(RevendaController); end; edtCodRevenda.Modified := False; end; constructor TfrmModeloRelatorio.create(APesquisar: Boolean); begin inherited create(nil); FController := TModeloRelatorioController.Create; dsPesquisa.DataSet := FController.Model.CDSConsulta; dsCad.DataSet := FController.Model.CDSCadastro; TGrade.RetornaCamposGrid(dbDados, cbbCampos); Localizar('ABCDE'); if APesquisar then begin cbbSituacao.ItemIndex := 0; Pesquisa := APesquisar; end; end; procedure TfrmModeloRelatorio.dbDadosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then begin dbDadosDblClick(Self); if edtCodigo.Enabled then edtCodigo.SetFocus; end; end; procedure TfrmModeloRelatorio.dbDadosTitleClick(Column: TColumn); begin inherited; TFuncoes.OrdenarCamposGrid(FController.Model.cdsconsulta, Column.FieldName); end; procedure TfrmModeloRelatorio.edtCodRevendaExit(Sender: TObject); begin inherited; if edtCodRevenda.Modified then BuscarRevenda(0, StrToIntDef(edtCodRevenda.Text, 0)); end; procedure TfrmModeloRelatorio.edtCodRevendaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_F9 then btnRevendaClick(Self); end; procedure TfrmModeloRelatorio.edtDescricaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_RETURN then Localizar(edtDescricao.Text); end; procedure TfrmModeloRelatorio.FormDestroy(Sender: TObject); begin inherited; FreeAndNil(FController); end; procedure TfrmModeloRelatorio.FormShow(Sender: TObject); var Img: TfrmImagens; begin inherited; img := TfrmImagens.Create(self); try btnRevenda.Glyph := img.btnProcurar.Glyph; finally FreeAndNil(img); end; end; procedure TfrmModeloRelatorio.Localizar(ATexto: string); var sCampo: string; sSituacao: string; bContem: Boolean; begin sCampo := TGrade.FiltrarCampo(dbDados, cbbCampos); sSituacao := Copy(cbbSituacao.Items.Strings[cbbSituacao.ItemIndex], 1, 1); bContem := (cbbPesquisa.ItemIndex = 1); // FController.Filtrar(sCampo, ATexto, sSituacao, bContem); FController.FiltrarUsuario(sCampo, ATexto, sSituacao, bContem); end; end.
unit uSelfApp; interface uses System.SysUtils, uIConnection, uFirebirdConnection; type TSelfApp = class strict private class var Instance: TSelfApp; private FDirApp: string; FConnection: IConnection; class procedure ReleaseInstance(); constructor Create; destructor Destroy; override; public class function GetInstance(): TSelfApp; property DirApp: string read FDirApp; property Connection: IConnection read FConnection; end; var SelfApp: TSelfApp; const NOME_BANCO_DADOS = 'DB.FDB'; implementation { TSelfApp } constructor TSelfApp.Create; begin FDirApp := ExtractFilePath(ParamStr(0)); FConnection := TFirebirdConnection.Create(FDirApp + NOME_BANCO_DADOS); end; destructor TSelfApp.Destroy; begin FConnection := nil; inherited; end; class function TSelfApp.GetInstance: TSelfApp; begin if not Assigned(Self.Instance) then self.Instance := TSelfApp.Create; Result := Self.Instance; end; class procedure TSelfApp.ReleaseInstance; begin if Assigned(Self.Instance) then Self.Instance.Free; end; initialization SelfApp := TSelfApp.GetInstance(); finalization TSelfApp.ReleaseInstance(); end.
unit f2FontPool; interface uses d2dClasses, d2dInterfaces, JclStringLists; type Tf2FontPool = class(Td2dProtoObject, Id2dFontProvider) private f_Fonts: IJclStringList; f_SysMenuFont: Id2dFont; f_SysTextFont: Id2dFont; public constructor Create(const aSysFont, aSysMenuFont: Id2dFont); function GetFont(const aFontName: string): Id2dFont; function Id2dFontProvider.GetByID = GetFont; procedure Clear; property SysMenuFont: Id2dFont read f_SysMenuFont; property SysTextFont: Id2dFont read f_SysTextFont; end; implementation uses SysUtils, f2Types, f2FontLoad; constructor Tf2FontPool.Create(const aSysFont, aSysMenuFont: Id2dFont); begin inherited Create; f_SysTextFont := aSysFont; f_SysMenuFont := aSysMenuFont; end; procedure Tf2FontPool.Clear; begin if f_Fonts <> nil then f_Fonts.Clear; end; function Tf2FontPool.GetFont(const aFontName: string): Id2dFont; var l_Idx: Integer; begin if AnsiSameText(aFontName, c_Sysfont) then Result := f_SysTextFont else if AnsiSameText(aFontName, c_SysMenuFont) then Result := f_SysMenuFont else begin if f_Fonts = nil then begin f_Fonts := JclStringList; f_Fonts.Sorted := True; f_Fonts.CaseSensitive := False; end; l_Idx := f_Fonts.IndexOf(aFontName); if l_Idx >= 0 then Result := f_Fonts.Interfaces[l_Idx] as Id2dFont else begin Result := f2LoadFont(aFontName); if Result <> nil then begin l_Idx := f_Fonts.Add(aFontName); f_Fonts.Interfaces[l_Idx] := Result; end else Result := f_SysTextFont; end; end; end; end.
{ ORIGINAL FILE: EmoStateDLL.h --------------------------------------------------------------------------------------- |EmoState Interface | |Copyright (c) 2009 Emotiv Systems, Inc. | | | |Header file to define constants and interfaces to access the EmoState. | | | |EmoStates are generated by the Emotiv detection engine (EmoEngine) and represent | |the emotional status of the user at a given time. | | | |EmoStateHandle is an opaque reference to an internal EmoState structure | | | |None of the EmoState interface functions are thread-safe. | | | |This header file is designed to be includable under C and C++ environment. | --------------------------------------------------------------------------------------- Translated by LaKraven Studios Ltd (14th October 2011) Copyright (C) 2011, LaKraven Studios Ltd, All Rights Reserved Last Updated: 14th October 2011 } unit EDK.EmoState; interface uses Windows; const EDK_DLL = 'edk.dll'; type { Pointers } EmoStateHandle = Pointer; PEmoStateHandle = EmoStateHandle; { Enums } EE_EmotivSuite_t = (EE_EXPRESSIV = 0, EE_AFFECTIV, EE_COGNITIV); TEmotivSuite = EE_EmotivSuite_t; EE_ExpressivAlgo_t = (EXP_NEUTRAL = $0001, EXP_BLINK = $0002, EXP_WINK_LEFT = $0004, EXP_WINK_RIGHT = $0008, EXP_HORIEYE = $0010, EXP_EYEBROW = $0020, EXP_FURROW = $0040, EXP_SMILE = $0080, EXP_CLENCH = $0100, EXP_LAUGH = $0200, EXP_SMIRK_LEFT = $0400, EXP_SMIRK_RIGHT = $0800); TExpressivAlgo = EE_ExpressivAlgo_t; EE_AffectivAlgo_t = (AFF_EXCITEMENT = $0001, AFF_MEDITATION = $0002, AFF_FRUSTRATION = $0004, AFF_ENGAGEMENT_BOREDOM = $0008); TAffectivAlgo = EE_AffectivAlgo_t; EE_CognitivAction_t = (COG_NEUTRAL = $0001, COG_PUSH = $0002, COG_PULL = $0004, COG_LIFT = $0008, COG_DROP = $0010, COG_LEFT = $0020, COG_RIGHT = $0040, COG_ROTATE_LEFT = $0080, COG_ROTATE_RIGHT = $0100, COG_ROTATE_CLOCKWISE = $0200, COG_ROTATE_COUNTER_CLOCKWISE = $0400, COG_ROTATE_FORWARDS = $0800, COG_ROTATE_REVERSE = $1000, COG_DISAPPEAR = $2000); PCognitivAction = ^TCognitivAction; TCognitivAction = EE_CognitivAction_t; PEE_CognitivAction_t = ^EE_CognitivAction_t; EE_SignalStrength_t = (NO_SIGNAL = 0, BAD_SIGNAL, GOOD_SIGNAL); TSignalStrength = EE_SignalStrength_t; EE_InputChannels_t = (EE_CHAN_CMS = 0, EE_CHAN_DRL, EE_CHAN_FP1, EE_CHAN_AF3, EE_CHAN_F7, EE_CHAN_F3, EE_CHAN_FC5, EE_CHAN_T7, EE_CHAN_P7, EE_CHAN_O1, EE_CHAN_O2, EE_CHAN_P8, EE_CHAN_T8, EE_CHAN_FC6, EE_CHAN_F4, EE_CHAN_F8, EE_CHAN_AF4, EE_CHAN_FP2); TInputChannels = EE_InputChannels_t; PEE_EEG_ContactQuality_t = ^EE_EEG_ContactQuality_t; EE_EEG_ContactQuality_t = (EEG_CQ_NO_SIGNAL, EEG_CQ_VERY_BAD, EEG_CQ_POOR, EEG_CQ_FAIR, EEG_CQ_GOOD); TEEGContactQuality = EE_EEG_ContactQuality_t; function ES_Create: EmoStateHandle; cdecl; external EDK_DLL; procedure ES_Free(state: EmoStateHandle); cdecl; external EDK_DLL; procedure ES_Init(state: EmoStateHandle); cdecl; external EDK_DLL; function ES_GetTimeFromStart(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_GetHeadsetOn(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_GetNumContactQualityChannels(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_GetContactQuality(state: EmoStateHandle; electroIdx: Integer): EE_EEG_ContactQuality_t; cdecl; external EDK_DLL; function ES_GetContactQualityFromAllChannels(state: EmoStateHandle; contactQuality: PEE_EEG_ContactQuality_t; numChannels: size_t): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsBlink(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsLeftWink(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsRightWink(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsEyesOpen(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsLookingUp(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsLookingDown(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsLookingLeft(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivIsLookingRight(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; procedure ES_ExpressivGetEyelidState(state: EmoStateHandle; leftEye, rightEye: PSingle); cdecl; external EDK_DLL; procedure ES_ExpressivGetEyeLocation(state: EmoStateHandle; x, y: PSingle); cdecl; external EDK_DLL; function ES_ExpressivGetEyebrowExtent(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_ExpressivGetSmileExtent(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_ExpressivGetClenchExtent(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_ExpressivGetUpperFaceAction(state: EmoStateHandle): EE_ExpressivAlgo_t; cdecl; external EDK_DLL; function ES_ExpressivGetUpperFaceActionPower(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_ExpressivGetLowerFaceAction(state: EmoStateHandle): EE_ExpressivAlgo_t; cdecl; external EDK_DLL; function ES_ExpressivGetLowerFaceActionPower(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_ExpressivIsActive(state: EmoStateHandle; etype: EE_ExpressivAlgo_t): Integer; cdecl; external EDK_DLL; function ES_AffectivGetExcitementLongTermScore(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_AffectivGetExcitementShortTermScore(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_AffectivIsActive(state: EmoStateHandle; etype: EE_AffectivAlgo_t): Integer; cdecl; external EDK_DLL; function ES_AffectivGetMeditationScore(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_AffectivGetFrustrationScore(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_AffectivGetEngagementBoredomScore(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_CognitivGetCurrentAction(state: EmoStateHandle): EE_CognitivAction_t; cdecl; external EDK_DLL; function ES_CognitivGetCurrentActionPower(state: EmoStateHandle): Single; cdecl; external EDK_DLL; function ES_CognitivIsActive(state: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_GetWirelessSignalStatus(state: EmoStateHandle): EE_SignalStrength_t; cdecl; external EDK_DLL; procedure ES_Copy(a, b: EmoStateHandle); cdecl; external EDK_DLL; function ES_AffectivEqual(a, b: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_ExpressivEqual(a, b: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_CognitivEqual(a, b: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_EmoEngineEqual(a, b: EmoStateHandle): Integer; cdecl; external EDK_DLL; function ES_Equal(a, b: EmoStateHandle): Integer; cdecl; external EDK_DLL; procedure ES_GetBatteryChargeLevel(state: EmoStateHandle; chargeLevel, maxChargeLevel: PInteger); cdecl; external EDK_DLL; implementation end.
unit D_NewClassNameEd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, D_NameEd, OvcBase, evEditorWindow, evEditor, evMemo, StdCtrls, Buttons, ExtCtrls, l3Interfaces, l3Types, vtSpin, TB97Ctls, evMultiSelectEditorWindow, evCustomEditor, evEditorWithOperations, afwControl, afwControlPrim, afwBaseControl, nevControl, evCustomMemo; type TNewClassNameEditDlg = class(TNameEditDlg) AddedDataPanel: TPanel; Label2: TLabel; mComment: TevMemo; pnlRelinkID: TPanel; Label1: TLabel; edtRelinkDictID: TvtSpinEdit; pnlJuristicChanges: TPanel; cbxJuristicChanges: TCheckBox; procedure mEditorTextSourceBruttoCharCountChangeRus(Sender: TObject); procedure mEditorTextSourceBruttoCharCountChangeEng(Sender: TObject); private procedure SetROnly(aValue : boolean); override; procedure SetCommentText(const aValue : Tl3PCharLen); function GetCommentText : Tl3PCharLen; public property CommentText : Tl3PCharLen Read GetCommentText Write SetCommentText; end; implementation {$R *.dfm} uses //Dialogs, //SysUtils, StrShop; procedure TNewClassNameEditDlg.SetROnly(aValue : boolean); begin Inherited; mComment.ReadOnly := aValue; edtRelinkDictID.Enabled := Not aValue; end; procedure TNewClassNameEditDlg.SetCommentText(const aValue : Tl3PCharLen); begin mComment.Buffer := aValue; {NameEditor.IsOpen := True;} end; function TNewClassNameEditDlg.GetCommentText : Tl3PCharLen; begin Tl3WString(Result) := mComment.Buffer; end; procedure TNewClassNameEditDlg.mEditorTextSourceBruttoCharCountChangeRus(Sender: TObject); begin mNameTextSourceBruttoCharCountChange(Sender); If mNameRus.TextLen > 75 then mNameRus.Color := clAqua else mNameRus.Color := clWindow; end; procedure TNewClassNameEditDlg.mEditorTextSourceBruttoCharCountChangeEng(Sender: TObject); begin mNameTextSourceBruttoCharCountChange(Sender); If mNameEng.TextLen > 75 then mNameEng.Color := clAqua else mNameEng.Color := clWindow; end; end.