text
stringlengths
14
6.51M
{$I-,Q-,R-,S-} {Broken Necklace You have a necklace of N red, white, or blue beads (3<=N<=350) some of which are red, others blue, and others white, arranged at random. Here are two examples for n=29: 1 2 1 2 r b b r b r r b r b b b r r b r r r w r b r w w b b r r b b b b b b r b r r b r b r r r b r r r r r r b r b r r r w Figure A Figure B r red bead b blue bead w white bead The beads considered first and second in the text that follows have been marked in the picture. The configuration in Figure A may be represented as a string of b's and r's, where b represents a blue bead and r represents a red one, as follows: brbrrrbbbrrrrrbrrbbrbbbbrrrrb . Suppose you are to break the necklace at some point, lay it out straight, and then collect beads of the same color from one end until you reach a bead of a different color, and do the same for the other end (which might not be of the same color as the beads collected before this). Determine the point where the necklace should be broken so that the most number of beads can be collected. Example For example, for the necklace in Figure A, 8 beads can be collected, with the breaking point either between bead 9 and bead 10 or else between bead 24 and bead 25. In some necklaces, white beads had been included as shown in Figure B above. When collecting beads, a white bead that is encountered may be treated as either red or blue and then painted with the desired color. The string that represents this configuration will include the three symbols r, b and w. Write a program to determine the largest number of beads that can be collected from a supplied necklace. PROGRAM NAME: beads INPUT FORMAT Line 1: N, the number of beads Line 2: a string of N characters, each of which is r, b, or w SAMPLE INPUT (file beads.in) 29 wwwbbrwrbrbrrbrbrwrwwrbwrwrrb OUTPUT FORMAT A single line containing the maximum of number of beads that can be collected from the supplied necklace. SAMPLE OUTPUT (file beads.out) 11 OUTPUT EXPLANATION Consider two copies of the beads (kind of like being able to runaround the ends). The string of 11 is marked. wwwbbrwrbrbrrbrbrwrwwrbwrwrrb wwwbbrwrbrbrrbrbrwrwwrbwrwrrb ***** ****** } const max = 1056; var fe,fs : text; n,cont,sol : longint; tab : array[0..max] of char; procedure open; var i : longint; begin assign(fe,'beads.in'); reset(fe); assign(fs,'beads.out'); rewrite(fs); readln(fe,n); for i:=1 to n do begin read(fe,tab[i]); tab[i+n]:=tab[i]; tab[i+n*2]:=tab[i]; end; close(fe); end; function cut(x,y : longint; ch : char) : longint; var i : longint; begin i:=x + y; while ((tab[i] = 'w') or (tab[i] = ch)) and (cont < n) do begin i:=i + y; cont:=cont + 1; end; cut:=i; end; procedure work; var i,x : longint; begin sol:=0; for i:=n to n*2+1 do begin cont:=1; x:=i; if tab[i] = 'w' then begin x:=cut(i,-1,'w'); cont:=cont + 1; end; cut(x,-1,tab[x]); cont:=cont + 1; x:=i+1; if tab[x] = 'w' then begin x:=cut(x,1,'w'); cont:=cont + 1; end; cut(x,1,tab[x]); if (cont > sol) then sol:=cont; end; if sol > n then sol:=n; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
unit uSaveToFile; interface uses classes; const ERROR_INVALID_PATH = 0; ERROR_EMPTY_PATH = 1; ERROR_BLANK_TEXT = 2; ERROR_CREATING_FILE = 3; Type TSaveFile = Class private FBodyText : TStringList; FPath : String; public Constructor Create; Destructor Destroy; override; property FilePath : String read FPath write FPath; procedure AddText(sText : String); procedure InsertText(sText:String; iPos:Integer); procedure OpenFile; function CreateFile:Integer; end; implementation uses Sysutils; Constructor TSaveFile.Create; begin inherited Create; FBodyText := TStringList.Create; end; Destructor TSaveFile.Destroy; begin FBodyText.Free; inherited Destroy; end; procedure TSaveFile.InsertText(sText:String; iPos:Integer); begin if Trim(sText) <> '' then FBodyText.Insert(iPos, sText); end; procedure TSaveFile.AddText(sText : String); begin if Trim(sText) <> '' then FBodyText.Add(sTExt); end; procedure TSaveFile.OpenFile; var fText : TextFile; begin if not FileExists(FPath) then Exit; Try FBodyText.LoadFromFile(FPath); Except end; end; function TSaveFile.CreateFile:Integer; var fText : TextFile; begin Result := -1; if FPath = '' then begin Result := ERROR_EMPTY_PATH; Exit; end; try Try AssignFile(fText, FPath); Rewrite(fText); Append(fText); Write(fText, FBodyText.Text); Except Result := ERROR_CREATING_FILE; end; finally CloseFile(fText); end; end; end.
function GetMemoryTotalPhys : DWord; // // Retorna o total de memoria do computador // var ms : TMemoryStatus; begin ms.dwLength := SizeOf( ms ); GlobalMemoryStatus( ms ); Result := ms.dwTotalPhys; end;
unit Modules.Database; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteWrapper.Stat, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Comp.DataSet; type TDBController = class(TDataModule) QuDateLimits: TFDQuery; Connection: TFDConnection; QuStates: TFDQuery; procedure DataModuleCreate(Sender: TObject); private FDateFirst: TDate; FDateLast: TDate; function GetDateFirst: TDate; function GetDateLast: TDate; { Private declarations } public { Public declarations } property DateFirst: TDate read GetDateFirst write FDateFirst; property DateLast: TDate read GetDateLast write FDateLast; end; TSQLStatements = class public class function GetIncidents: String; end; var DBController: TDBController; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDBController.DataModuleCreate(Sender: TObject); begin QuStates.Open; QuDateLimits.Open; end; function TDBController.GetDateFirst: TDate; begin Result := QuDateLimits.FieldByName('first').AsDateTime; end; function TDBController.GetDateLast: TDate; begin Result := QuDateLimits.FieldByName('last').AsDateTime; end; { TSQLStatements } class function TSQLStatements.GetIncidents: String; begin Result := 'SELECT id, severity, start_time, end_time, start_lat, start_lng, end_lat, end_lng ' + 'FROM incidents WHERE (start_date = :date) AND (state = :code)'; end; end.
(**************************************************************************** * * WinLIRC plug-in for jetAudio * * Copyright (c) 2016 Tim De Baets * **************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************** * * jetAudio plug-in base class * ****************************************************************************) unit JFBase; interface {$ALIGN ON} {$MINENUMSIZE 4} uses Windows, JDefine; type TJFInfo = record // Filter does not use this variable. This is used internally by Host. m_szFileName: array[0..256-1] of Char; m_bActive: BOOL; // Filter should fill the following variables m_szFilterName: array[0..80-1] of Char; m_szFilterWriter: array[0..80-1] of Char; m_szFilterDesc: array[0..256-1] of Char; m_szFileExts: array[0..256-1] of Char; // *.wav;*.avi; ... m_szFileExtsString: array[0..256-1] of Char; // Windows Sounds (*.wav)|*.wav| m_uSDKVersion: UINT; // Currently, this is 0x100 m_uCategory: UINT; m_uInputDeviceType: UINT; m_uOutputDeviceType: UINT; m_uInputStreamType: UINT; m_uOutputStreamType: UINT; m_uCaps: UINT; m_bUnvisible: BOOL; // Typically, this is "0" m_dwReserved: array[0..128-1] of DWORD; end; PJFInfo = ^TJFInfo; type TJFBase = class public procedure CDestroy(Val: Integer); virtual; stdcall; abstract; procedure GetInfo(pInfo: PJFInfo); virtual; stdcall; abstract; function SetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar; iValSize: Integer): BOOL; virtual; stdcall; abstract; { return FALSE; } function GetPropertyPTR(pszPropName: PAnsiChar; pVal: PAnsiChar; iValSize: Integer): BOOL; virtual; stdcall; abstract; { return FALSE; } function SetPropertyINT(pszPropName: PAnsiChar; nVal: Integer): BOOL; virtual; stdcall; abstract; { return FALSE; } function GetPropertyINT(pszPropName: PAnsiChar; pnVal: PInteger): BOOL; virtual; stdcall; abstract; { return FALSE; } procedure Config(hWnd: HWND); virtual; stdcall; abstract; { return; } procedure About(hWnd: HWND); virtual; stdcall; abstract; { return; } function GetErrorString(pszBuffer: PAnsiChar; nBufferSize: Integer): JERROR_TYPE; virtual; stdcall; abstract; { return JERROR_UNKNOWN; } end; implementation end.
unit ParseTest; {$mode objfpc}{$H+} interface uses fpcunit, testregistry, uIntXLibTypes, uIntX; type { TTestParse } TTestParse = class(TTestCase) published procedure Zero(); procedure WhiteSpace(); procedure Sign(); procedure Base(); procedure CallNull(); procedure CallInvalidFormat(); procedure CallInvalidFormat2(); procedure CallInvalidFormat3(); procedure BigDec(); private procedure Null(); procedure InvalidFormat(); procedure InvalidFormat2(); procedure InvalidFormat3(); end; implementation procedure TTestParse.Zero(); var int1: TIntX; begin int1 := TIntX.Parse('0'); AssertTrue(int1 = 0); end; procedure TTestParse.WhiteSpace(); var int1: TIntX; begin int1 := TIntX.Parse(' 7 '); AssertTrue(int1 = 7); end; procedure TTestParse.Sign(); var int1: TIntX; begin int1 := TIntX.Parse('-7'); AssertTrue(int1 = -7); int1 := TIntX.Parse('+7'); AssertTrue(int1 = 7); end; procedure TTestParse.Base(); var int1: TIntX; begin int1 := TIntX.Parse('abcdef', 16); AssertTrue(int1 = $ABCDEF); int1 := TIntX.Parse('100', 8); AssertTrue(int1 = 64); int1 := TIntX.Parse('0100'); AssertTrue(int1 = 64); int1 := TIntX.Parse('0100000000000'); AssertTrue(int1 = $200000000); int1 := TIntX.Parse('$abcdef'); AssertTrue(int1 = $ABCDEF); int1 := TIntX.Parse('$ABCDEF'); AssertTrue(int1 = $ABCDEF); int1 := TIntX.Parse('020000000000'); AssertTrue(int1 = $80000000); int1 := TIntX.Parse('0xDEADBEEF'); AssertTrue(int1 = $DEADBEEF); int1 := TIntX.Parse('0xdeadbeef'); AssertTrue(int1 = $DEADBEEF); int1 := TIntX.Parse('0Xdeadbeef'); AssertTrue(int1 = $DEADBEEF); end; procedure TTestParse.Null(); begin TIntX.Parse(''); end; procedure TTestParse.CallNull(); var TempMethod: TRunMethod; begin TempMethod := @Null; AssertException(EArgumentNilException, TempMethod); end; procedure TTestParse.InvalidFormat(); begin TIntX.Parse('-123-'); end; procedure TTestParse.CallInvalidFormat(); var TempMethod: TRunMethod; begin TempMethod := @InvalidFormat; AssertException(EFormatException, TempMethod); end; procedure TTestParse.InvalidFormat2(); begin TIntX.Parse('abc'); end; procedure TTestParse.CallInvalidFormat2(); var TempMethod: TRunMethod; begin TempMethod := @InvalidFormat2; AssertException(EFormatException, TempMethod); end; procedure TTestParse.InvalidFormat3(); begin TIntX.Parse('987', 2); end; procedure TTestParse.CallInvalidFormat3(); var TempMethod: TRunMethod; begin TempMethod := @InvalidFormat3; AssertException(EFormatException, TempMethod); end; procedure TTestParse.BigDec(); var IntX: TIntX; begin IntX := TIntX.Parse( '34589238954389567586547689234723587070897800300450823748275895896384753238944985'); AssertEquals('34589238954389567586547689234723587070897800300450823748275895896384753238944985', IntX.ToString()); end; initialization RegisterTest(TTestParse); end.
unit AES_HMAC; // This is an implementation of HMAC, the FIPS standard keyed hash function interface uses Windows, AES_Type, OverbyteIcsSha1, RDGlobal // sha1; ; const HASH_INPUT_SIZE = 64; // HASH_OUTPUT_SIZE = SHA1HashSize; HASH_OUTPUT_SIZE = 20; HMAC_OK = 0; HMAC_BAD_MODE = -1; HMAC_IN_DATA = Integer($ffffffff); { ShaBlockSize = 64; // see sha1.h ShaDigestSize = 20; ShaLength = 23; HMacContextSize = ShaBlockSize+4*ShaLength+sizeof(integer); } //type // THMacContext = packed array[0..HMacContextSize-1] of byte; type hmac_ctx = record key : array[0..HASH_INPUT_SIZE-1] of AnsiChar; ctx : SHA1Context; // ctx : T_Sha1_Ctx; klen : Integer; end; // TData_Type = array of byte; procedure hmac_sha1_begin(var cx : hmac_ctx); function hmac_sha1_key(const key : RawByteString; key_len : Integer; var cx : hmac_ctx) : Integer; procedure hmac_sha1_data(const data : Pointer; data_len : Integer; var cx : hmac_ctx); procedure hmac_sha1_end(mac : PByte; mac_len : Integer; cx : hmac_ctx); procedure hmac_sha(const key : RawByteString; key_len : Integer; const data : Pointer; data_len : Int64; var mac : RawByteString; const mac_len : Integer); function derive_key(const pwd : RawByteString; // the PASSWORD const salt : RawByteString; //* the SALT and its */ const iter : Integer; //* the number of iterations */ const key_len : Integer)//* and its required length */ : RawByteString; (* Field lengths (in bytes) versus File Encryption Mode (0 < mode < 4) Mode Key Salt MAC Overhead 1 16 8 10 18 2 24 12 10 22 3 32 16 10 26 The following macros assume that the mode value is correct. *) const KEY_LENGTH : array[1..3] of byte = (16, 24, 32); SALT_LENGTH : array[1..3] of byte = (8, 12, 16); MAC_LENGTH = 10; EXPKEY_LENGTH : array[1..3] of byte = (44, 54, 64); PWD_VER_LENGTH = 2; MAX_KEY_LENGTH = 32; MAX_PWD_LENGTH = 128; MAX_SALT_LENGTH = 16; KEYING_ITERATIONS = 1000; AES_BLOCK_SIZE = 16; //* the AES block size in bytes */ BLOCK_SIZE = AES_BLOCK_SIZE; //* a maximum of 60 32-bit words are needed for the key schedule */ KS_LENGTH = 64; GOOD_RETURN = 0; PASSWORD_TOO_LONG = -100; BAD_MODE = -101; type Pint = ^Cardinal; type // aes_encrypt_ctx = record // ks : array[0..KS_LENGTH-1] of cardinal; // end; fcrypt_ctx = record nonce : array[0..BLOCK_SIZE-1] of Byte; //* the CTR nonce */ encr_bfr : array[0..BLOCK_SIZE-1] of Byte; //* encrypt buffer */ // nonce : TAESBuffer; //* the CTR nonce */ // encr_bfr : TAESBuffer; //* encrypt buffer */ // nonce : TAESBlock; //* the CTR nonce */ // encr_bfr : TAESBlock; //* encrypt buffer */ // encr_ctx : T_AES_Ctx; //* encryption context */ aes_ctx : TAESContext; auth_ctx : hmac_ctx; //* authentication context */ // auth_ctx : THMacContext; encr_pos : cardinal; //* block position (enc) */ pwd_len : cardinal; //* password length */ mode : cardinal; //* File encryption mode */ end; //* initialise file encryption or decryption */ function fcrypt_init( mode : byte; //* the mode to be used (input) */ const pwd : RawByteString; //* the user specified password (input) */ // unsigned int pwd_len, //* the length of the password (input) */ const salt : RawByteString; //* the salt (input) */ var pwd_ver : RawByteString; //* 2 byte password verifier (output) */ var cx : fcrypt_ctx) : Integer; //* the file encryption context (output) */ //* perform 'in place' encryption or decryption and authentication */ procedure fcrypt_encrypt(data : Pointer; data_len : Integer; var cx : fcrypt_ctx); procedure fcrypt_decrypt(data : Pointer; data_len : Integer; var cx : fcrypt_ctx); //* close encryption/decryption and return the MAC value */ //* the return value is the length of the MAC */ function fcrypt_end(var cx : fcrypt_ctx) //* the context (input) */ : RawByteString; //* the MAC value (output) */ implementation uses SysUtils, // DIFileEncrypt, AES_Encr ; (* {$L sha1.obj} {$L hmac.obj} { ---------------------------------------------------------------------------- } // replacement for C library functions procedure _memset (var Dest; Value,Count : integer); cdecl; begin FillChar (Dest,Count,chr(Value)); end; procedure _memcpy (var Dest; const Source; Count : integer); cdecl; begin Move (Source,Dest,Count); end; { ---------------------------------------------------------------------------- } procedure hmac_sha1_begin (var HMacContext : THMacContext); external; procedure hmac_sha1_key (const Key : PAnsiChar; KeyLen : cardinal; var HMacContext : THMacContext); external; procedure hmac_sha1_data (const Data : PAnsiChar; DataLen : cardinal; var HMacContext : THMacContext); external; procedure hmac_sha1_end (const Mac : PAnsiChar; MacLen : cardinal; var HMacContext : THMacContext); external; *) function derive_key(const pwd : RawByteString; // the PASSWORD const salt : RawByteString; //* the SALT and its */ const iter : Integer; //* the number of iterations */ const key_len : Integer)//* and its required length */ : RawByteString; var i, j, k, n_blk : Integer; // k_ipad, k_opad: array[0..64] of Byte; // uu, ux : array[0..SHA1HashSize-1] of char; // uu, ux : array[0..HASH_OUTPUT_SIZE-1] of Byte; uu, ux : array[1..HASH_OUTPUT_SIZE] of Byte; // uu, ux : String[HASH_OUTPUT_SIZE]; // uu, ux : RawByteString; // s : AnsiString; // hmac_ctx c1[1], c2[1], c3[1]; c1, c2, c3: hmac_ctx; // c1, c2, c3: THMacContext; begin // SetLength(uu, HASH_OUTPUT_SIZE); // SetLength(ux, HASH_OUTPUT_SIZE); SetLength(Result, key_len); //* set HMAC context (c1) for password */ hmac_sha1_begin(c1); hmac_sha1_key(PAnsiChar(pwd), Length(pwd), c1); //* set HMAC context (c2) for password and salt */ // memcpy(c2, c1, sizeof(hmac_ctx)); CopyMemory(@c2, @c1, sizeof(c1)); hmac_sha1_data(Pointer(salt), Length(salt), c2); //* find the number of SHA blocks in the key */ n_blk := 1 + (key_len - 1) div HASH_OUTPUT_SIZE; // for(i = 0; i < n_blk; ++i) /* for each block in key */ for i := 0 to n_blk-1 do //* for each block in key */ begin //* ux[] holds the running xor value */ // memset(ux, 0, HASH_OUTPUT_SIZE); FillMemory(@ux[1], HASH_OUTPUT_SIZE, 00); //* set HMAC context (c3) for password and salt */ // memcpy(c3, c2, sizeof(hmac_ctx)); CopyMemory(@c3, @c2, sizeof(c2)); //* enter additional data for 1st block into uu */ uu[1] := Byte((i + 1) shr 24); uu[2] := Byte((i + 1) shr 16); uu[3] := Byte((i + 1) shr 8); uu[4] := Byte(i + 1); //* this is the key mixing iteration */ k := 4; for j := 0 to iter-1 do begin //* add previous round data to HMAC */ hmac_sha1_data(@uu[1], k, c3); //* obtain HMAC for uu[] */ // hmac_sha1_end(PAnsiChar(uu), HASH_OUTPUT_SIZE, c3); hmac_sha1_end(@uu[1], HASH_OUTPUT_SIZE, c3); //* xor into the running xor block */ for k := 1 to HASH_OUTPUT_SIZE do ux[k] := Byte(byte(ux[k]) xor byte(uu[k])); //* set HMAC context (c3) for password */ // memcpy(c3, c1, sizeof(hmac_ctx)); CopyMemory(@c3, @c1, sizeof(c1)); k := HASH_OUTPUT_SIZE; end; //* compile key blocks into the key output */ j := 0; k := i * HASH_OUTPUT_SIZE; while(j < HASH_OUTPUT_SIZE) and (k < key_len) do begin Result[k+1] := AnsiChar(ux[j+1]); inc(k); inc(j); end; end; end; //* initialise the HMAC context to zero */ procedure hmac_sha1_begin(var cx : hmac_ctx); begin FillMemory(@cx, SizeOf(hmac_ctx), 00); end; //* input the HMAC key (can be called multiple times) */ function hmac_sha1_key(const key : RawByteString; key_len : Integer; var cx : hmac_ctx) : Integer; begin if (cx.klen = HMAC_IN_DATA) then //* error if further key input */ begin result := HMAC_BAD_MODE; //* is attempted in data mode */ Exit; end; if(cx.klen + key_len > HASH_INPUT_SIZE) then //* if the key has to be hashed */ begin if(cx.klen <= HASH_INPUT_SIZE) then //* if the hash has not yet been */ begin //* started, initialise it and */ // sha1_begin(cx.ctx); //* hash stored key characters */ // sha1_hash(@cx.key[0], cx.klen, cx.ctx); SHA1Reset (cx.ctx); SHA1Input(cx.ctx, cx.key, cx.klen); end; // sha1_hash(@key[1], key_len, cx.ctx); //* hash long key data into hash */ SHA1Input(cx.ctx, PAnsiChar(key), key_len); end else //* otherwise store key data */ // memcpy(cx->key + cx->klen, key, key_len); CopyMemory(@cx.key[cx.klen], Pointer(key), key_len); // cx.klen += key_len; //* update the key length count */ inc(cx.klen, key_len); Result := HMAC_OK; end; //* input the HMAC data (can be called multiple times) - */ //* note that this call terminates the key input phase */ procedure hmac_sha1_data(const data : Pointer; data_len : Integer; var cx : hmac_ctx); var k : Integer; res : SHA1Digest; // res : T_Sha1_Digest; begin if(cx.klen <> HMAC_IN_DATA) then //* if not yet in data phase */ begin if(cx.klen > HASH_INPUT_SIZE) then //* if key is being hashed */ begin //* complete the hash and */ // sha1_end(res, cx.ctx); //* store the result as the */ SHA1Result(cx.ctx, res); CopyMemory(@cx.key[0], @res[0], HASH_OUTPUT_SIZE); cx.klen := HASH_OUTPUT_SIZE; //* key and set new length */ end; //* pad the key if necessary */ // memset(cx->key + cx->klen, 0, HASH_INPUT_SIZE - cx->klen); FillMemory(@cx.key[cx.klen], HASH_INPUT_SIZE - cx.klen, 00); //* xor ipad into key value */ // for i := 0 to HASH_INPUT_SIZE do // byte(cx.key[i]) := byte(cx.key[i]) xor $36; k := 0; while k < HASH_INPUT_SIZE do begin Pint(@cx.key[k])^ := Pint(@cx.key[k])^ xor $36363636; Inc(k, 4); end; //* and start hash operation */ // sha1_begin(cx.ctx); // sha1_hash(@cx.key[0], HASH_INPUT_SIZE, cx.ctx); SHA1Reset(cx.ctx); SHA1Input(cx.ctx, cx.key, HASH_INPUT_SIZE); //* mark as now in data mode */ cx.klen := HMAC_IN_DATA; end; //* hash the data (if any) */ if (data_len > 0) then // sha1_hash(data, data_len, cx.ctx); SHA1Input(cx.ctx, data, data_len); // SHA1Input(cx.ctx, PAnsiChar(data), data_len); end; //* input the HMAC data (can be called multiple times) - */ //* note that this call terminates the key input phase */ procedure hmac_sha1_end(mac : PByte; mac_len : Integer; cx : hmac_ctx); var dig : SHA1Digest; // dig : T_Sha1_Digest; i, k : Integer; begin //* if no data has been entered perform a null data phase */ if (cx.klen <> HMAC_IN_DATA) then hmac_sha1_data(nil, 0, cx); // hmac_sha_data(i, 0, cx); // sha1_end(dig, cx.ctx); //* complete the inner hash */ SHA1Result(cx.ctx, dig); //* set outer key value using opad and removing ipad */ { for i := 0 to (HASH_INPUT_SIZE) do // ((unsigned long*)cx->key)[i] ^= 0x36363636 ^ 0x5c5c5c5c; byte(cx.key[i]) := byte(cx.key[i]) xor $36 xor $5c; } k := 0; while k < HASH_INPUT_SIZE do begin Pint(@cx.key[k])^ := Pint(@cx.key[k])^ xor $36363636 xor $5c5c5c5c; Inc(k, 4); end; //* perform the outer hash operation */ // sha1_begin(cx.ctx); // sha1_hash(@cx.key[0], HASH_INPUT_SIZE, cx.ctx); // sha1_hash(@dig[0], HASH_OUTPUT_SIZE, cx.ctx); // sha1_end(dig, cx.ctx); SHA1Reset(cx.ctx); SHA1Input(cx.ctx, cx.key, HASH_INPUT_SIZE); SHA1Input(cx.ctx, dig, HASH_OUTPUT_SIZE); SHA1Result(cx.ctx, dig); // SetLength(mac, HASH_OUTPUT_SIZE); //* output the hash value */ // SetLength(mac, mac_len); for i := 0 to mac_len-1 do // mac[i+1] := AnsiChar(dig[i]); // mac[i] := Byte(dig[i]); Byte(PByte(Cardinal(mac)+i)^) := Byte(dig[i]); end; //* 'do it all in one go' subroutine */ procedure hmac_sha(const key : RawByteString; key_len : Integer; const data : Pointer; data_len : Int64; var mac : RawByteString; const mac_len : Integer); var cx : hmac_ctx; begin hmac_sha1_begin(cx); hmac_sha1_key(key, key_len, cx); hmac_sha1_data(data, data_len, cx); SetLength(mac, mac_len); hmac_sha1_end(@mac[1], mac_len, cx); end; //* initialise file encryption or decryption */ function fcrypt_init( mode : byte; //* the mode to be used (input) */ const pwd : RawByteString; //* the user specified password (input) */ // unsigned int pwd_len, //* the length of the password (input) */ const salt : RawByteString; //* the salt (input) */ var pwd_ver : RawByteString; //* 2 byte password verifier (output) */ var cx : fcrypt_ctx) : Integer; //* the file encryption context (output) */ var // kbuf : array[0..2 * MAX_KEY_LENGTH + PWD_VER_LENGTH-1] of byte; buf, buf2 : RawByteString; // ab: TAESBlock; // act : TAESContext; begin if(Length(pwd) > MAX_PWD_LENGTH) then begin Result := PASSWORD_TOO_LONG; exit; end; if(mode < 1) or (mode > 3) then begin Result := BAD_MODE; Exit; end; cx.mode := mode; cx.pwd_len := Length(pwd); //* initialise the encryption nonce and buffer pos */ cx.encr_pos := BLOCK_SIZE; //* if we need a random component in the encryption */ //* nonce, this is where it would have to be set */ // memset(cx.nonce, 0, BLOCK_SIZE * sizeof(unsigned char)); FillMemory(@cx.nonce[0], BLOCK_SIZE, 00); //* derive the encryption and authetication keys and the password verifier */ buf := derive_key(pwd, salt, KEYING_ITERATIONS, 2 * KEY_LENGTH[mode] + PWD_VER_LENGTH); //* set the encryption key */ { CopyMemory(@cx.encr_ctx.ks[0], @cx.aes_ctx.RK[0][0], EXPKEY_LENGTH[mode]); // aes_encrypt_key(kbuf, KEY_LENGTH(mode), cx->encr_ctx); } // aes_encrypt_key(@buf[1], KEY_LENGTH[mode], cx.encr_ctx); AES_Init_Encr(Pointer(buf)^, KEY_LENGTH[mode] * 8, cx.aes_ctx); //* initialise for authentication */ hmac_sha1_begin(cx.auth_ctx); //* set the authentication key */ buf2 := Copy(buf, KEY_LENGTH[mode]+1, KEY_LENGTH[mode]); // hmac_sha1_key(PAnsichar(buf) + KEY_LENGTH[mode], KEY_LENGTH[mode], cx.auth_ctx); hmac_sha1_key(buf2, KEY_LENGTH[mode], cx.auth_ctx); // memcpy(pwd_ver, kbuf + 2 * KEY_LENGTH(mode), PWD_VER_LENGTH); pwd_ver := copy(buf, 2 * KEY_LENGTH[mode] + 1, PWD_VER_LENGTH); //* clear the buffer holding the derived key values */ // memset(kbuf, 0, 2 * KEY_LENGTH(mode) + PWD_VER_LENGTH); buf := ''; Result := GOOD_RETURN; end; procedure encr_data(var data : Pointer; d_len : Integer; var cx : fcrypt_ctx); var i, j : Integer; pos : Cardinal; begin i := 0; pos := cx.encr_pos; while(i < d_len) do begin if(pos = BLOCK_SIZE) then begin j := 0; //* increment encryption nonce */ // while(j < 8 && !++cx->nonce[j]) // ++j; while j < 8 do begin inc(cx.nonce[j]); // if cx.nonce[j] = 0 then if cx.nonce[j] <> 0 then Break; inc(j); end; //* encrypt the nonce to form next xor buffer */ // aes_encrypt(cx->nonce, cx->encr_bfr, cx->encr_ctx); { EncryptAES(cx.nonce, ExpKey2^, cx.encr_bfr); } // AES_CTR_Encrypt(@cx.nonce[0], @cx.encr_bfr[0], BLOCK_SIZE, cx.aes_ctx); AES_Encr.AES_Encrypt(cx.aes_ctx, TAESBlock(cx.nonce), TAESBlock(cx.encr_bfr)); // diaes.aes_encrypt(@cx.nonce[0], @cx.encr_bfr[0], cx.encr_ctx); pos := 0; end; Byte(Pointer(Cardinal(data)+i)^) := Byte(Pointer(Cardinal(data)+i)^) xor cx.encr_bfr[pos]; inc(i); inc(pos); end; cx.encr_pos := pos; end; //* perform 'in place' encryption or decryption and authentication */ procedure fcrypt_encrypt(data : Pointer; data_len : Integer; var cx : fcrypt_ctx); begin encr_data(data, data_len, cx); hmac_sha1_data(data, data_len, cx.auth_ctx); end; procedure fcrypt_decrypt(data : Pointer; data_len : Integer; var cx : fcrypt_ctx); begin hmac_sha1_data(data, data_len, cx.auth_ctx); encr_data(data, data_len, cx); end; //* close encryption/decryption and return the MAC value */ //* the return value is the length of the MAC */ function fcrypt_end(var cx : fcrypt_ctx) //* the context (input) */ : RawByteString; //* the MAC value (output) */ begin SetLength(Result, MAC_LENGTH); hmac_sha1_end(@Result[1], MAC_LENGTH, cx.auth_ctx); // hmac_sha1_end(Result, MAC_LENGTH, cx.auth_ctx); // memset(cx, 0, sizeof(fcrypt_ctx)); //* clear the encryption context */ FillMemory(@cx, sizeof(fcrypt_ctx), 0); // Result MAC_LENGTH(res); //* return MAC length in bytes */ end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit BasicSliderCrank; interface uses Test; type TBasicSliderCrank = class(TTest) public constructor Create; class function CreateTest: TTest; static; end; implementation uses System.Math, Box2D.Common, Box2D.Collision, Box2D.Dynamics, DebugDraw; { TBasicSliderCrank } constructor TBasicSliderCrank.Create; var ground, body, prevBody: b2BodyWrapper; bd: b2BodyDef; shape: b2PolygonShapeWrapper; rjd: b2RevoluteJointDef; pjd: b2PrismaticJointDef; begin inherited; bd := b2BodyDef.Create; bd.position.&Set(0.0, 17.0); ground := m_world.CreateBody(@bd); prevBody := ground; // Define crank. shape := b2PolygonShapeWrapper.Create; shape.SetAsBox(4.0, 1.0); bd.&type := b2_dynamicBody; bd.position.&Set(-8.0, 20.0); body := m_world.CreateBody(@bd); body.CreateFixture(shape, 2.0); rjd := b2RevoluteJointDef.Create; rjd.Initialize(prevBody, body, b2Vec2.Create(-12.0, 20.0)); m_world.CreateJoint(@rjd); prevBody := body; // Define connecting rod shape.SetAsBox(8.0, 1.0); bd.&type := b2_dynamicBody; bd.position.&Set(4.0, 20.0); body := m_world.CreateBody(@bd); body.CreateFixture(shape, 2.0); rjd.Initialize(prevBody, body, b2Vec2.Create(-4.0, 20.0)); m_world.CreateJoint(@rjd); prevBody := body; // Define piston shape.SetAsBox(3.0, 3.0); bd.&type := b2_dynamicBody; bd.fixedRotation := true; bd.position.&Set(12.0, 20.0); body := m_world.CreateBody(@bd); body.CreateFixture(shape, 2.0); rjd.Initialize(prevBody, body, b2Vec2.Create(12.0, 20.0)); m_world.CreateJoint(@rjd); pjd := b2PrismaticJointDef.Create; pjd.Initialize(ground, body, b2Vec2.Create(12.0, 17.0), b2Vec2.Create(1.0, 0.0)); m_world.CreateJoint(@pjd); shape.Destroy; end; class function TBasicSliderCrank.CreateTest: TTest; begin Result := TBasicSliderCrank.Create; end; initialization RegisterTest(TestEntry.Create('BasicSliderCrank', @TBasicSliderCrank.CreateTest)); end.
unit uIntfImageDrawingUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IntfGraphics, FPimage; procedure ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false); procedure DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; Filled: Boolean; ADiameter: Integer; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean); procedure ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean); implementation procedure ClipDrawPixel(X, Y: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false); var vAlpha, vInverseAlpha: Word; CurColor: TFPColor; begin IF (X >= 0) and (X <= ADataImage.Width-1) and (Y >= 0) and (Y <= ADataImage.Height-1) THEN //ADataImage.TColors[X, Y] := AColor; BEGIN if (not AAlphaBlend) and (not AAlphaMergeOnly) then ADataImage.Colors[X, Y] := AFPColor else begin // TODO: this is from LazIntfImage... is this correct blending ? vAlpha := AFPColor.alpha; vInverseAlpha := $FFFF - vAlpha; if vAlpha = $FFFF then begin ADataImage.Colors[X, Y] := AFPColor; end else if vAlpha > $00 then begin if AAlphaBlend then begin // TODO: why is Alpha untouched with AlphaBlend ?? CurColor := ADataImage.Colors[X, Y]; CurColor.Red := Round( CurColor.Red * vInverseAlpha / $FFFF + AFPColor.Red * vAlpha / $FFFF); CurColor.Green := Round( CurColor.Green * vInverseAlpha / $FFFF + AFPColor.Green * vAlpha / $FFFF); CurColor.Blue := Round( CurColor.Blue * vInverseAlpha / $FFFF + AFPColor.Blue * vAlpha / $FFFF); ADataImage.Colors[X, Y] := CurColor; end else begin // here is AAlphaMergeOnly ; CurColor := ADataImage.Colors[X, Y]; CurColor.Red := AFPColor.Red; CurColor.Green := AFPColor.green; CurColor.Blue := AFPColor.blue; // new 02.08.ju: merge alpha channels otherwise alpha stays as background(=0) //multiplikativ //CurColor.alpha := $FFFF - (round( ($FFFF - CurColor.alpha) / $FFFF * vInverseAlpha)); //additiv ? CurColor.alpha := $FFFF - (round( ($FFFF - CurColor.alpha) / $FFFF + vInverseAlpha)) DIV 2; //CurColor.alpha := Round( // CurColor.alpha * vInverseAlpha / $FFFF + // AFPColor.alpha * vAlpha / $FFFF); ADataImage.Colors[X, Y] := CurColor; end; end; end; END; end; procedure DrawCircleEx(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; Filled: Boolean; ADiameter: Integer; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean); var vRadius, vRy: Integer; vLoop, vLoopy: Integer; vLastY: Integer; begin CASE ADiameter of 0: exit; 1,2: ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); 3,4: begin ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); if Filled then begin ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); end; end; 5: begin ClipDrawPixel(Pt.X-2, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X+2, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X-1, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X+1, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y-2, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X-1, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X+1, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y+2, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); if Filled then begin ClipDrawPixel(Pt.X, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X-1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X+1, Pt.Y, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y-1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); ClipDrawPixel(Pt.X, Pt.Y+1, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); end; end; END; IF ADiameter < 6 THEN exit ELSE BEGIN vRadius := ADiameter DIV 2; vLastY := vRadius; IF Filled THEN BEGIN for vLoop := -vRadius to vRadius do begin vRy := trunc( sqrt( sqr(vRadius) - sqr(vLoop))); for vLoopy := -vRy to vRy do ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); end; END ELSE BEGIN for vLoop := 0 to vRadius do begin vRy := round( sqrt( sqr(vRadius) - sqr(vLoop))); for vLoopy := vLastY downto vRy do begin ClipDrawPixel(Pt.x+ vLoop, Pt.y-vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q1 ClipDrawPixel(Pt.x- vLoop, Pt.y-vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q2 ClipDrawPixel(Pt.x- vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q3 ClipDrawPixel(Pt.x+ vLoop, Pt.y+vLoopy, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly); // Q4 end; vLastY := vRy; end; END; END; end; procedure ClipDrawLine(A, B: TPoint; ALineWidth: Integer; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean); var dx,dy: Integer; vXleading: Boolean; vLoop: Integer; vX1, vX2: Integer; vY1, vY2: Integer; vPoint: TPoint; begin dx := (B.X-A.X); dy := (B.Y-A.Y); IF (dx = 0) and (dy = 0 ) THEN begin ClipDrawPixel(A.X, A.Y, ADataImage,AFPColor, AAlphaBlend, AAlphaMergeOnly); exit; end; IF abs(dx) > abs(dy) THEN vXleading := TRUE ELSE vXleading := FALSE; IF vXleading THEN BEGIN IF B.X > A.X THEN begin vX1 := A.X; vY1 := A.Y; vX2 := B.X; end else begin vX1 := B.X; vY1 := B.Y; vX2 := A.X; end; for vLoop := vX1 to vX2 do begin vY2 := trunc(dy/dx * (vLoop-vX1)) + vY1; // trunc(dy/dx * (vLoop-vX1) + 1) + vY1; why +1 ???????????????? also in Lazarus bug ? vPoint.X := vLoop; vPoint.Y := vY2; DrawCircleEx(vPoint, ADataImage, AFPColor, TRUE, ALineWidth, AAlphaBlend, AAlphaMergeOnly); end; END ELSE BEGIN IF B.Y > A.Y THEN begin vY1 := A.Y; vX1 := A.X; vY2 := B.Y; end else begin vY1 := B.Y; vX1 := B.X; vY2 := A.Y; end; for vLoop := vY1 to vY2 do begin vX2 := trunc(dx/dy * (vLoop-vY1)) + vX1; vPoint.X := vX2; vPoint.Y := vLoop; DrawCircleEx(vPoint, ADataImage, AFPColor, TRUE, ALineWidth, AAlphaBlend, AAlphaMergeOnly); end; END; end; end.
unit uFuncionarioDAOClient; interface uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, Funcionario; type TFuncionarioDAOClient = class(TDSAdminClient) private FListCommand: TDBXCommand; FNextCodigoCommand: TDBXCommand; FInsertCommand: TDBXCommand; FUpdateCommand: TDBXCommand; FDeleteCommand: TDBXCommand; FFindByCodigoCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function List: TDBXReader; function NextCodigo: string; function Insert(Funcionario: TFuncionario): Boolean; function Update(Funcionario: TFuncionario): Boolean; function Delete(Funcionario: TFuncionario): Boolean; function FindByCodigo(Codigo: string): TFuncionario; end; implementation function TFuncionarioDAOClient.List: TDBXReader; begin if FListCommand = nil then begin FListCommand := FDBXConnection.CreateCommand; FListCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListCommand.Text := 'TFuncionarioDAO.List'; FListCommand.Prepare; end; FListCommand.ExecuteUpdate; Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TFuncionarioDAOClient.NextCodigo: string; begin if FNextCodigoCommand = nil then begin FNextCodigoCommand := FDBXConnection.CreateCommand; FNextCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FNextCodigoCommand.Text := 'TFuncionarioDAO.NextCodigo'; FNextCodigoCommand.Prepare; end; FNextCodigoCommand.ExecuteUpdate; Result := FNextCodigoCommand.Parameters[0].Value.GetWideString; end; function TFuncionarioDAOClient.Insert(Funcionario: TFuncionario): Boolean; begin if FInsertCommand = nil then begin FInsertCommand := FDBXConnection.CreateCommand; FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsertCommand.Text := 'TFuncionarioDAO.Insert'; FInsertCommand.Prepare; end; if not Assigned(Funcionario) then FInsertCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Funcionario), True); if FInstanceOwner then Funcionario.Free finally FreeAndNil(FMarshal) end end; FInsertCommand.ExecuteUpdate; Result := FInsertCommand.Parameters[1].Value.GetBoolean; end; function TFuncionarioDAOClient.Update(Funcionario: TFuncionario): Boolean; begin if FUpdateCommand = nil then begin FUpdateCommand := FDBXConnection.CreateCommand; FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod; FUpdateCommand.Text := 'TFuncionarioDAO.Update'; FUpdateCommand.Prepare; end; if not Assigned(Funcionario) then FUpdateCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Funcionario), True); if FInstanceOwner then Funcionario.Free finally FreeAndNil(FMarshal) end end; FUpdateCommand.ExecuteUpdate; Result := FUpdateCommand.Parameters[1].Value.GetBoolean; end; function TFuncionarioDAOClient.Delete(Funcionario: TFuncionario): Boolean; begin if FDeleteCommand = nil then begin FDeleteCommand := FDBXConnection.CreateCommand; FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteCommand.Text := 'TFuncionarioDAO.Delete'; FDeleteCommand.Prepare; end; if not Assigned(Funcionario) then FDeleteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Funcionario), True); if FInstanceOwner then Funcionario.Free finally FreeAndNil(FMarshal) end end; FDeleteCommand.ExecuteUpdate; Result := FDeleteCommand.Parameters[1].Value.GetBoolean; end; function TFuncionarioDAOClient.FindByCodigo(Codigo: string): TFuncionario; begin if FFindByCodigoCommand = nil then begin FFindByCodigoCommand := FDBXConnection.CreateCommand; FFindByCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFindByCodigoCommand.Text := 'TFuncionarioDAO.FindByCodigo'; FFindByCodigoCommand.Prepare; end; FFindByCodigoCommand.Parameters[0].Value.SetWideString(Codigo); FFindByCodigoCommand.ExecuteUpdate; if not FFindByCodigoCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDBXClientCommand(FFindByCodigoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TFuncionario(FUnMarshal.UnMarshal(FFindByCodigoCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FFindByCodigoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; constructor TFuncionarioDAOClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TFuncionarioDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TFuncionarioDAOClient.Destroy; begin FreeAndNil(FListCommand); FreeAndNil(FNextCodigoCommand); FreeAndNil(FInsertCommand); FreeAndNil(FUpdateCommand); FreeAndNil(FDeleteCommand); FreeAndNil(FFindByCodigoCommand); inherited; end; end.
(* * Copyright (c) 2013-2016 Thundax Macro Actions * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'Thundax Macro Actions' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit thundax.lib.actions; interface uses Generics.Collections; type TActionType = (tMousePos, TMouseLClick, TMouseLDClick, TMouseRClick, TMouseRDClick, TKey, TMessage, TWait); TActionTypeHelper = class(TObject) class function CastToString(action: TActionType): string; end; IAction = interface procedure Execute; function ToString(): string; end; TParameters<T> = class(TObject) private Fparam2: T; Fparam1: T; procedure Setparam1(const Value: T); procedure Setparam2(const Value: T); public property param1: T read Fparam1 write Setparam1; property param2: T read Fparam2 write Setparam2; function IntegerConverterP1(): Integer; function IntegerConverterP2(): Integer; function StringConverterP1(): String; function StringConverterP2(): String; constructor Create(param1: T; param2: T); end; TAction<T> = class(TInterfacedObject, IAction) private Fparam: TParameters<T>; Faction: TActionType; procedure Setaction(const Value: TActionType); procedure Setparam(const Value: TParameters<T>); function getKey(key: String): Char; procedure TypeMessage(Msg: string); public property action: TActionType read Faction write Setaction; property param: TParameters<T>read Fparam write Setparam; constructor Create(action: TActionType; param: TParameters<T>); procedure Execute(); function ToString(): string; override; end; TActionList = class(TList<IAction>) procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); end; function GenericAsInteger(const Value): Integer; inline; function GenericAsString(const Value): string; inline; implementation uses Windows, TypInfo, Variants, SysUtils, dbxjson, dbxjsonreflect, dialogs, XMLDoc, xmldom, XMLIntf; { TParameters<T> } function GenericAsInteger(const Value): Integer; begin Result := Integer(Value); end; function GenericAsString(const Value): string; begin Result := string(Value); end; constructor TParameters<T>.Create(param1, param2: T); begin Setparam1(param1); Setparam2(param2); end; function TParameters<T>.IntegerConverterP1: Integer; begin Result := GenericAsInteger(Fparam1); end; function TParameters<T>.IntegerConverterP2: Integer; begin Result := GenericAsInteger(Fparam2); end; procedure TParameters<T>.Setparam1(const Value: T); begin Fparam1 := Value; end; procedure TParameters<T>.Setparam2(const Value: T); begin Fparam2 := Value; end; function TParameters<T>.StringConverterP1: String; begin Result := GenericAsString(Fparam1); end; function TParameters<T>.StringConverterP2: String; begin Result := GenericAsString(Fparam2); end; { TAction<T> } constructor TAction<T>.Create(action: TActionType; param: TParameters<T>); begin Setaction(action); Setparam(param); end; procedure TAction<T>.Execute; var p: Integer; begin case Faction of tMousePos: SetCursorPos(param.IntegerConverterP1, param.IntegerConverterP2); TMouseLClick: begin mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; TMouseLDClick: begin mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); GetDoubleClickTime; mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); end; TMouseRClick: begin mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); end; TMouseRDClick: begin mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); GetDoubleClickTime; mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0); mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0); end; TKey: TypeMessage(getKey(param.StringConverterP1)); TMessage: TypeMessage(param.StringConverterP1); TWait: Sleep(param.IntegerConverterP1 * 1000); end; end; function TAction<T>.getKey(key: String): Char; begin if key = 'TAB' then Result := Char(VK_TAB); if key = 'CLEAR' then Result := Char(VK_CLEAR); if key = 'RETURN' then Result := Char(VK_RETURN); if key = 'SHIFT' then Result := Char(VK_SHIFT); if key = 'CONTROL' then Result := Char(VK_CONTROL); if key = 'ESCAPE' then Result := Char(VK_ESCAPE); if key = 'SPACE' then Result := Char(VK_SPACE); if key = 'LEFT' then Result := Char(VK_LEFT); if key = 'UP' then Result := Char(VK_UP); if key = 'RIGHT' then Result := Char(VK_RIGHT); if key = 'DOWN' then Result := Char(VK_DOWN); if key = 'INSERT' then Result := Char(VK_INSERT); if key = 'DELETE' then Result := Char(VK_DELETE); if key = 'F1' then Result := Char(VK_F1); if key = 'F2' then Result := Char(VK_F2); if key = 'F3' then Result := Char(VK_F3); if key = 'F4' then Result := Char(VK_F4); if key = 'F5' then Result := Char(VK_F5); if key = 'F6' then Result := Char(VK_F6); if key = 'F7' then Result := Char(VK_F7); if key = 'F8' then Result := Char(VK_F8); if key = 'F9' then Result := Char(VK_F9); if key = 'F10' then Result := Char(VK_F10); if key = 'F11' then Result := Char(VK_F11); if key = 'F12' then Result := Char(VK_F12); end; function TAction<T>.ToString: string; var varRes: TVarType; description: string; x, y: Integer; p: string; begin description := TActionTypeHelper.CastToString(Faction); Case PTypeInfo(TypeInfo(T))^.Kind of tkInteger: begin if Faction = TWait then description := description + ' ' + IntToStr(param.IntegerConverterP1) + 's' else description := description + ' (' + IntToStr(param.IntegerConverterP1) + ', ' + IntToStr(param.IntegerConverterP2) + ')'; end; tkString, tkUString, tkChar, tkWChar, tkLString, tkWString, tkUnknown, tkVariant: begin if param.StringConverterP1 <> '' then description := description + ' (' + param.StringConverterP1 + ')'; end; End; Result := description; end; //********************************* //This code has been extracted from: //http://stackoverflow.com/questions/9673442/how-can-i-send-keys-to-another-application-using-delphi-7 //http://stackoverflow.com/users/1211614/dampsquid //********************************* procedure TAction<T>.TypeMessage(Msg: string); var CapsOn: boolean; i: Integer; ch: Char; shift: boolean; key: short; begin CapsOn := (GetKeyState(VK_CAPITAL) and $1) <> 0; for i := 1 to length(Msg) do begin ch := Msg[i]; ch := UpCase(ch); if ch <> Msg[i] then begin if CapsOn then keybd_event(VK_SHIFT, 0, 0, 0); keybd_event(ord(ch), 0, 0, 0); keybd_event(ord(ch), 0, KEYEVENTF_KEYUP, 0); if CapsOn then keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0); end else begin key := VKKeyScan(ch); if ((not CapsOn) and (ch >= 'A') and (ch <= 'Z')) or ((key and $100) > 0) then keybd_event(VK_SHIFT, 0, 0, 0); keybd_event(key, 0, 0, 0); keybd_event(key, 0, KEYEVENTF_KEYUP, 0); if ((not CapsOn) and (ch >= 'A') and (ch <= 'Z')) or ((key and $100) > 0) then keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0); end; end; end; procedure TAction<T>.Setaction(const Value: TActionType); begin Faction := Value; end; procedure TAction<T>.Setparam(const Value: TParameters<T>); begin Fparam := Value; end; { TActionTypeHelper } class function TActionTypeHelper.CastToString(action: TActionType): string; begin case action of tMousePos: Result := 'Mouse position'; TMouseLClick: Result := 'Mouse Left Click'; TMouseLDClick: Result := 'Mouse Left Double Click'; TMouseRClick: Result := 'Mouse Right Click'; TMouseRDClick: Result := 'Mouse Right Double Click'; TKey: Result := 'Press special key'; TMessage: Result := 'Type message'; TWait: Result := 'Waiting Time'; end; end; { TActionList } procedure TActionList.LoadFromFile(const FileName: string); begin end; procedure TActionList.SaveToFile(const FileName: string); var Document: IXMLDocument; iXMLRootNode, iNode: IXMLNode; i: Integer; begin XMLDoc := TXMLDocument.Create(nil); XMLDoc.Active := true; for i := 0 to count-1 do begin Self[i].ToString end; end; end.
unit uDMValidatePetTextFile; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uDMValidateTextFile, ADODB; type TDMValidatePetTextFile = class(TDMValidateTextFile) private IsClientServer: Boolean; function ValidateFields: Boolean; function ValidateTableField(ATable, AFieldName, AFieldValue : String) : Boolean; public function Validate: Boolean; override; end; implementation uses uDMGlobal; {$R *.dfm} { TDMValidatePetTextFile } function TDMValidatePetTextFile.Validate: Boolean; begin TextFile.First; while not TextFile.Eof do begin Result := ValidateFields; TextFile.Next; end; Result := True; end; function TDMValidatePetTextFile.ValidateFields: Boolean; var sMsg : String; begin IsClientServer := DMGlobal.IsClientServer(SQLConnection); sMsg := ''; if not IsClientServer then begin if ((TextFile.FieldByName('SKU').AsString = '') AND (TextFile.FieldByName('Microchip').AsString = '') AND (TextFile.FieldByName('Collar').AsString = '')) then begin sMsg := 'SKU or Microchip or Collar. '; Result := False; end; if (TextFile.FieldByName('Species').AsString = '') or (not ValidateTableField('Pet_Species', 'Species', TextFile.FieldByName('Species').AsString)) then begin sMsg := sMsg + 'Species. '; Result := False; end; if (TextFile.FieldByName('Breed').AsString = '') then begin sMsg := sMsg + 'Breed. '; Result := False; end; end else begin sMsg := 'Replication Database!'; Result := False; end; if (sMsg <> '') then begin TextFile.Edit; TextFile.FieldByName('Warning').AsString := 'Error: Invalid field(s) [' + sMsg + ']'; TextFile.FieldByName('Validation').AsBoolean := Result; TextFile.Post; end; end; function TDMValidatePetTextFile.ValidateTableField(ATable, AFieldName, AFieldValue : String): Boolean; var FQuery : TADOQuery; begin try FQuery := TADOQuery.Create(Self); FQuery.Connection := SQLConnection; FQuery.SQL.Add('SELECT ' + AFieldName); FQuery.SQL.Add('FROM ' + ATable); FQuery.SQL.Add('WHERE '+AFieldName+' = :' + AFieldName); FQuery.Parameters.ParamByName(AFieldName).Value := AFieldValue; FQuery.Open; Result := not FQuery.IsEmpty; finally FQuery.Close; FreeAndNil(FQuery); end; end; end.
unit Android.ProgressDialog; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.App, Androidapi.JNI.GraphicsContentViewText, AndroidAPI.JNI.JavaTypes; type JProgressDialog = interface; JProgressDialogClass = interface (JAlertDialogClass) ['{4A287A8D-51CF-45CA-A8A6-D5D2F8B78B9E}'] {Property Methods} function _GetSTYLE_HORIZONTAL: Integer; function _GetSTYLE_SPINNER: Integer; {Properties} property STYLE_HORIZONTAL: Integer read _GetSTYLE_HORIZONTAL; property STYLE_SPINNER: Integer read _GetSTYLE_SPINNER; function show(context: JContext; title: JCharSequence; message: JCharSequence): JProgressDialog; cdecl; overload; function show(context: JContext; title: JCharSequence; message: JCharSequence; indeterminate: Boolean; cancelable: Boolean): JProgressDialog; cdecl; overload; function show(context: JContext; title: JCharSequence; message: JCharSequence; indeterminate: Boolean; cancelable: Boolean; cancelListener: JDialogInterface_OnCancelListener): JProgressDialog; cdecl; overload; function show(context: JContext; title: JCharSequence; message: JCharSequence; indeterminate: Boolean): JProgressDialog; cdecl; overload; end; [JavaSignature('android/app/ProgressDialog')] JProgressDialog = interface(JAlertDialog) ['{919C1A6E-1754-4E5D-8BA7-D6659C7FE88D}'] function getMax: Integer; cdecl; function getProgress: Integer; cdecl; function getSecondaryProgress: Integer; cdecl; procedure incrementProgressBy(diff: Integer); cdecl; function isIndeterminate: Boolean; cdecl; procedure onStart; cdecl; procedure setIndeterminate(indeterminate: Boolean); cdecl; procedure setIndeterminateDrawable(d: JDrawable); cdecl; procedure setMax(max: Integer); cdecl; procedure setMessage(message: JCharSequence); cdecl; procedure setProgress(value: Integer); cdecl; procedure setProgressDrawable(d: JDrawable); cdecl; procedure setProgressNumberFormat(format: JString); cdecl; //procedure setProgressPercentFormat(format: JNumberFormat); cdecl; procedure setProgressStyle(style: Integer); procedure setSecondaryProgress(secondaryProgress: Integer); end; TJProgressDialog = class(TJavaGenericImport<JProgressDialogClass, JProgressDialog>) end; implementation end.
namespace; interface uses System, System.IO, System.Web, WindowsLive; type login = public partial class(System.Web.UI.Page) protected const LoginCookie = 'webauthtoken'; class var WLL: WindowsLiveLogin := new WindowsLiveLogin(true); class var AppId: String := WLL.AppId; var m_userId: String; method Page_Load(sender: Object; e: EventArgs); end; implementation method login.Page_Load(sender: Object; e: EventArgs); begin { If the user token has been cached in a site cookie, attempt to process it and extract the user ID. } var l_req := HttpContext.Current.Request; var l_cookie := l_req.Cookies[LoginCookie]; if l_cookie <> nil then begin var l_token := l_cookie.Value; if (l_token <> nil) and (l_token.Length <> 0) then begin var l_user := WLL.ProcessToken(l_token); if l_user <> nil then begin m_userId := l_user.Id; end; end; end; end; end.
(************************************************************************* ========= AkelPad text editor plugin API =========== ** Origin: AkelEdit.h located at http://akelpad.cvs.sourceforge.net/viewvc/akelpad/akelpad_4/AkelFiles/Plugs/AkelDLL/AkelEdit.h ** Converted with C to Pascal Converter 2.0 ** Release: 2.20.11.2011 ** Email: al_gun@ncable.net.au ** Updates: http://cc.codegear.com/Author/302259 ** Blogs: http://delphiprogrammingwithalgun.blogspot.com/ ** Copyright (c) 2005, 2011 Ural Gunaydin (a.k.a. Al Gun) =========== Edited by Fr0sT =========== = Tested on RAD Studio XE2 but compiles on D7 and should = = work on other versions also. = **************************************************************************) unit AkelEdit; interface uses Windows, Messages, RichEdit, AkelDLL; //// Defines const AES_AKELEDITA = AnsiString('AkelEditA'); const AES_AKELEDITA_UNICODE = WideString('AkelEditA'); const AES_AKELEDITW_ANSI = AnsiString('AkelEditW'); const AES_AKELEDITW = WideString('AkelEditW'); const AES_RICHEDIT20A = AnsiString('RichEdit20A'); const AES_RICHEDIT20A_UNICODE = WideString('RichEdit20A'); const AES_RICHEDIT20W_ANSI = AnsiString('RichEdit20W'); const AES_RICHEDIT20W = WideString('RichEdit20W'); // Fr0sT: these C types aren't defined in used units type SIZE_T = INT_PTR; HDROP = THandle; //AEM_CONTROLCLASS const AECLASS_AKELEDIT = 1; const AECLASS_RICHEDIT = 2; //Window styles { Fr0sT: these constants are already defined in RTL since D7 const ES_MULTILINE = $00000004; //See AECO_MULTILINE. const ES_NOHIDESEL = $00000100; //See AECO_NOHIDESEL. const ES_READONLY = $00000800; //See AECO_READONLY. const ES_WANTRETURN = $00001000; //See AECO_WANTRETURN. const ES_DISABLENOSCROLL = $00002000; //See AECO_DISABLENOSCROLL. } const ES_GLOBALUNDO = $00004000; //Use process heap for Undo/Redo instead of window heap. Required for AEM_DETACHUNDO and AEM_ATTACHUNDO. //Compatibility: define same as ES_SUNKEN. const ES_HEAP_SERIALIZE = $00008000; //Mutual exclusion will be used when the heap functions allocate and free memory from window heap. Serialization of heap access allows two or more threads to simultaneously allocate and free memory from the same heap. //Compatibility: define same as ES_SAVESEL. const AES_WORDDELIMITERSW : WideString = ' '#9#13#10'''`\"\\|[](){}<>,.;:+-=~!@#$%^&*/?'; const AES_WRAPDELIMITERSW : WideString = ' '#9; const AES_URLLEFTDELIMITERSW : WideString = ' '#9#13#10'''`\"(<{[='; const AES_URLRIGHTDELIMITERSW : WideString = ' '#9#13#10'''`\")>}]'; const AES_URLPREFIXESW : WideString = 'http:'#0'https:'#0'www.'#0'ftp:'#0'file:'#0'mailto:'#0#0; //AEM_SETEVENTMASK flags const AENM_SCROLL = $00000001; //Sends AEN_HSCROLL and AEN_VSCROLL notifications. const AENM_PAINT = $00000002; //Sends AEN_PAINT notifications. const AENM_MAXTEXT = $00000010; //Don't use it. For internal code only. const AENM_PROGRESS = $00000020; //Sends AEN_PROGRESS notifications. const AENM_MODIFY = $00000040; //Sends AEN_MODIFY notifications. const AENM_SELCHANGE = $00000080; //Sends AEN_SELCHANGING and AEN_SELCHANGED notifications. const AENM_TEXTCHANGE = $00000100; //Sends AEN_TEXTCHANGING and AEN_TEXTCHANGED notifications. const AENM_TEXTINSERT = $00000200; //Sends AEN_TEXTINSERTBEGIN and AEN_TEXTINSERTEND notifications. const AENM_TEXTDELETE = $00000400; //Sends AEN_TEXTDELETEBEGIN and AEN_TEXTDELETEEND notifications. const AENM_POINT = $00000800; //Sends AEN_POINT notifications. const AENM_DROPFILES = $00010000; //Sends AEN_DROPFILES notifications. const AENM_DRAGDROP = $00020000; //Sends AEN_DROPSOURCE and AEN_DROPTARGET notifications. const AENM_LINK = $00040000; //Sends AEN_LINK notifications. const AENM_MARKER = $00080000; //Sends AEN_MARKER notifications. //AEN_SELCHANGING and AEN_SELCHANGED types const AESCT_REPLACESEL = $00000001; //Replacing selection. const AESCT_APPENDTEXT = $00000002; //Appending text. const AESCT_SETTEXT = $00000004; //Setting text. const AESCT_STREAMIN = $00000008; //Stream in. const AESCT_WRAP = $00000010; //Sending AEM_SETWORDWRAP. const AESCT_UNDO = $00000020; //Undo. const AESCT_REDO = $00000040; //Redo. const AESCT_CUT = $00000080; //Cut. const AESCT_CHAR = $00000100; //Inserting char. const AESCT_KEYRETURN = $00000200; //Pressing VK_RETURN. const AESCT_KEYBACKSPACE = $00000400; //Pressing VK_BACK. const AESCT_KEYDELETE = $00000800; //Pressing VK_DELETE. const AESCT_DRAGDELETE = $00001000; //Dragging text delete. const AESCT_DROPINSERT = $00002000; //Dropping text insert. const AESCT_MOUSESINGLECLK = $00100000; //Mouse single click. const AESCT_MOUSEDOUBLECLK = $00200000; //Mouse double click. const AESCT_MOUSETRIPLECLK = $00400000; //Mouse triple click. const AESCT_MOUSECAPTURE = $00800000; //Mouse made non-empty selection. const AESCT_MOUSELEFTMARGIN = $01000000; //Left margin mouse action. const AESCT_KEYBOARD = $02000000; //Selection is changed by keyboard. const AESCT_SETSELMESSAGE = $04000000; //Sending AEM_EXSETSEL, AEM_SETSEL, EM_SETSEL, EM_EXSETSEL. const AESCT_UPDATESELECTION = $08000000; //Selection is updated. const AESCT_IME = $10000000; //Input Method Editors (IME). //AEN_TEXTCHANGING, AEN_TEXTINSERTBEGIN, AEN_TEXTINSERTEND, AEN_TEXTDELETEBEGIN, AEN_TEXTDELETEEND and AEN_TEXTCHANGED types const AETCT_REPLACESEL = $00000001; //Replacing selection. const AETCT_APPENDTEXT = $00000002; //Appending text. const AETCT_SETTEXT = $00000004; //Setting text. const AETCT_STREAMIN = $00000008; //Stream in. const AETCT_WRAP = $00000010; //Sending AEM_SETWORDWRAP. const AETCT_UNDO = $00000020; //Undo. const AETCT_REDO = $00000040; //Redo. const AETCT_CUT = $00000080; //Cut. const AETCT_CHAR = $00000100; //Inserting char. const AETCT_KEYRETURN = $00000200; //Pressing VK_RETURN. const AETCT_KEYBACKSPACE = $00000400; //Pressing VK_BACK. const AETCT_KEYDELETE = $00000800; //Pressing VK_DELETE. const AETCT_DRAGDELETE = $00001000; //Dragging text delete. const AETCT_DROPINSERT = $00002000; //Dropping text insert. const AETCT_COLUMNGROUP = $00004000; //Undo/Redo column text is grouped from one-line actions. //AEN_TEXTCHANGED types const AETCT_NONE = $00100000; //No text is changed. const AETCT_DELETEALL = $00200000; //Indicate that due to AETCT_* action all text has been modified. //Insert text flags const AEINST_LOCKUNDO = $00000001; const AEINST_LOCKSCROLL = $00000002; const AEINST_LOCKUPDATEHSCROLL = $00000004; const AEINST_LOCKUPDATEVSCROLL = $00000008; const AEINST_LOCKUPDATECARET = $00000010; const AEINST_LOCKUPDATETEXT = $00000020; const AEINST_LOCKUPDATEALL = (AEINST_LOCKUPDATEHSCROLL or AEINST_LOCKUPDATEVSCROLL or AEINST_LOCKUPDATECARET or AEINST_LOCKUPDATETEXT); //Delete text flags const AEDELT_LOCKUNDO = $00000001; const AEDELT_LOCKSCROLL = $00000002; const AEDELT_LOCKUPDATEHSCROLL = $00000004; const AEDELT_LOCKUPDATEVSCROLL = $00000008; const AEDELT_LOCKUPDATECARET = $00000010; const AEDELT_LOCKUPDATETEXT = $00000020; const AEDELT_SAVECOLUMNSEL = $00000040; const AEDELT_LOCKUPDATEALL = (AEDELT_LOCKUPDATEHSCROLL or AEDELT_LOCKUPDATEVSCROLL or AEDELT_LOCKUPDATECARET or AEDELT_LOCKUPDATETEXT); //AEN_POINT types const AEPTT_SETTEXT = $00000001; //All document text has been changed. All points reset to first character. const AEPTT_STREAMIN = $00000002; //All document text has been changed. All points reset to first character. const AEPTT_INSERT = $00000004; //Insert operation. const AEPTT_DELETE = $00000008; //Delete operation. //AEPOINT flags const AEPTF_MODIFY = $00000002; //If set, text in (AEPOINT.ciPoint + AEPOINT.nPointLen) area has been modified. const AEPTF_INSERT = $00000004; //If set, AEPOINT.nPointLen index has been increased. Additional for AEPTF_MODIFY flag. const AEPTF_DELETE = $00000008; //If set, AEPOINT.nPointLen index has been decreased. Additional for AEPTF_MODIFY flag. const AEPTF_NOTIFYDELETE = $00000010; //Don't use it. For internal code only. const AEPTF_NOTIFYINSERT = $00000020; //Don't use it. For internal code only. const AEPTF_VALIDLINE = $00000040; //Don't use it. For internal code only. const AEPTF_FOLD = $00000100; //If set, AEPOINT.ciPoint index is used in fold. AEPOINT.dwUserData is pointer to a AEFOLD structure. const AEPTF_MOVEOFFSET = $00001000; //If set, AEPOINT.nPointOffset has been changed. const AEPTF_MOVELINE = $00002000; //If set, AEPOINT.ciPoint.nLine has been changed. //AEPOINT character offset value const AEPTO_IGNORE = -1; //Character RichEdit offset is not used in AEPOINT. const AEPTO_CALC = -2; //Character RichEdit offset will calculated automatically by AEM_ADDPOINT. //AEM_COLLAPSELINE and AEM_COLLAPSEFOLD flags const AECF_EXPAND = $00000000; //Expand fold (default). const AECF_COLLAPSE = $00000001; //Collapse fold. const AECF_RECURSE = $00000002; //Recursive processing with all children. const AECF_NOUPDATE = $00000004; //Don't update scroll and selection. const AECF_NOCARETCORRECT = $00000008; //If in collapsed fold located caret, don't move it to fold start. //AEN_DROPTARGET actions const AEDT_TARGETENTER = 1; //Enter into the target window. const AEDT_TARGETOVER = 2; //Moving over the target window. const AEDT_TARGETLEAVE = 3; //Leaving the target window. const AEDT_TARGETDROP = 4; //Drops the data into the target window. //AEN_DROPSOURCE actions const AEDS_SOURCEBEGIN = 1; //Begin selection dragging. const AEDS_SOURCEEND = 2; //End selection dragging. Before selection deletion. const AEDS_SOURCEDONE = 3; //End dragging operation. Same as EN_DRAGDROPDONE. //AEN_PROGRESS type const AEPGS_SETTEXT = $00000001; //Setting text. const AEPGS_WRAPTEXT = $00000002; //Wrapping text. const AEPGS_STREAMIN = $00000004; //Receiving stream text. //AEN_PAINT type const AEPNT_BEGIN = $00000001; //Sends before painting is started, only AENPAINT.hDC member is valid. const AEPNT_END = $00000002; //Sends before clean-up paint resources. const AEPNT_DRAWLINE = $00000004; //Sends before line is drawn. //AEM_SETOPTIONS flags // Window styles: const AECO_READONLY = $00000001; //Set read-only mode. You can use ES_READONLY window style. const AECO_DISABLENOSCROLL = $00000002; //Disables scroll bars instead of hiding them when they are not needed. You can use ES_DISABLENOSCROLL window style. const AECO_NOHIDESEL = $00000004; //If you do not specify this style, then hides the selection when the control loses the input focus and inverts the selection when the control receives the input focus. You can use ES_NOHIDESEL window style. const AECO_WANTRETURN = $00000008; //If you do not specify this style, pressing the ENTER key has the same effect as pressing the dialog box's default push button. You can use ES_WANTRETURN window style. const AECO_MULTILINE = $00000010; //Designates a multiline edit control. The default is single-line edit control. You can use ES_MULTILINE window style. // Other: const AECO_DETAILEDUNDO = $00000020; //The control stores any typing action, into a new action in the undo queue. const AECO_PASTESELECTCOLUMN = $00000040; //Selects pasted text in column mode. const AECO_DISABLEDRAG = $00000080; //Disables OLE text dragging. const AECO_DISABLEDROP = $00000100; //Disables OLE text dropping. const AECO_CARETOUTEDGE = $00000200; //Allow caret moving out of the line edge. const AECO_ACTIVECOLUMN = $00000400; //Draw caret vertical line. const AECO_ACTIVELINE = $00000800; //Draw active line. const AECO_ACTIVELINEBORDER = $00001000; //Draw active line border. const AECO_ALTLINEBORDER = $00002000; //Draw alternating lines border. const AECO_NONEWLINEDRAW = $00004000; //Disables drawing new line selection as space character. const AECO_ENTIRENEWLINEDRAW = $00008000; //Draw new line selection to the right edge. const AECO_NONEWLINEMOUSESELECT = $00010000; //Triple click and left margin click selects only line contents without new line. const AECO_LBUTTONUPCONTINUECAPTURE = $00020000; //After WM_LBUTTONUP message capture operations doesn't stopped. const AECO_RBUTTONDOWNMOVECARET = $00040000; //WM_RBUTTONDOWN message moves caret to a click position. const AECO_MBUTTONDOWNNOSCROLL = $00080000; //No scrolling after WM_MBUTTONDOWN message. const AECO_MARGINSELUNWRAPLINE = $00100000; //Left margin line selection with mouse selects all wrapped line. const AECO_NOMARGINSEL = $00200000; //Disables left margin line selection with mouse. const AECO_NOMARKERMOVE = $00400000; //Disables changing position of column marker with mouse and shift button. const AECO_NOMARKERAFTERLASTLINE = $00800000; //Disables marker painting after last line. const AECO_VSCROLLBYLINE = $01000000; //Unit of vertical scrolling is line (default is pixel). const AECO_NOSCROLLDELETEALL = $02000000; //Turn off scrolling to caret, when undo/redo operations replace all text. const AECO_NOSCROLLSELECTALL = $04000000; //Turn off scrolling to caret, when all text is selected. const AECO_NOCOLUMNPASTEHOTKEY = $08000000; //Turn off Alt+V for columnar paste. const AECO_DISABLEBEEP = $10000000; //Disables sound beep, when unallowable action occur. const AECO_NODCBUFFER = $20000000; //Don't use device context output buffering in AE_Paint. Cause edit window flashing. const AECO_PAINTGROUP = $40000000; //Paint text by group of characters (default is character by character). //With this flag some text recognition programs could start to work, printer could print faster, but highlighted symbols and combined unicode symbols can be drawn differently and editing of whose characters may become uncomfortable. const AECO_NOPRINTCOLLAPSED = $80000000; //Disables print collapsed lines. See AEM_COLLAPSEFOLD message. //AEM_EXSETOPTIONS flags const AECOE_DETECTURL = $00000001; //Enables detection and highlighting of URLs by an edit control. const AECOE_LOCKSELECTION = $00000002; //Prevent selection changing. Use it with AECO_READONLY flag. const AECOE_OVERTYPE = $00000004; //Turn on overtype mode instead of insert mode. const AECOE_ALTDECINPUT = $00000008; //Do Alt+NumPad decimal input with NumLock on (default is decimal input after two "Num 0"). const AECOOP_SET = 1; //Sets the options to those specified by lParam. const AECOOP_OR = 2; //Combines the specified options with the current options. const AECOOP_AND = 3; //Retains only those current options that are also specified by lParam. const AECOOP_XOR = 4; //Logically exclusive OR the current options with those specified by lParam. //Modifier flags const AEMOD_ALT = $1; //ALT key const AEMOD_SHIFT = $2; //SHIFT key const AEMOD_CONTROL = $4; //CTRL key //AEM_GETLINENUMBER flags const AEGL_LINECOUNT = 0; //Total number of text lines. If the control has no text, the return value is 1. const AEGL_FIRSTSELLINE = 1; //First line of the selection. const AEGL_LASTSELLINE = 2; //Last line of the selection. const AEGL_CARETLINE = 3; //Caret line. const AEGL_FIRSTVISIBLELINE = 4; //First visible line. const AEGL_LASTVISIBLELINE = 5; //Last visible line. const AEGL_FIRSTFULLVISIBLELINE = 6; //First fully visible line. const AEGL_LASTFULLVISIBLELINE = 7; //Last fully visible line. const AEGL_LINEUNWRAPCOUNT = 11; //Total number of unwrapped text lines. If the control has no text, the return value is 1. const AEGL_UNWRAPSELMULTILINE = 12; //Returns value: TRUE - if selection on multiple lines. FALSE - if no selection or selection is on single line. //AEM_GETINDEX and AEM_GETRICHOFFSET flags const AEGI_FIRSTCHAR = 1; //First character. const AEGI_LASTCHAR = 2; //Last character. const AEGI_FIRSTSELCHAR = 3; //First character of the selection. const AEGI_LASTSELCHAR = 4; //Last character of the selection. const AEGI_CARETCHAR = 5; //Caret character. const AEGI_FIRSTVISIBLECHAR = 6; //First visible character, collapsed lines are skipped. const AEGI_LASTVISIBLECHAR = 7; //Last visible character, collapsed lines are skipped. const AEGI_FIRSTFULLVISIBLECHAR = 8; //First fully visible character, collapsed lines are skipped. const AEGI_LASTFULLVISIBLECHAR = 9; //Last fully visible character, collapsed lines are skipped. const AEGI_FIRSTVISIBLELINE = 10; //First character of the first visible line, collapsed lines are skipped. const AEGI_LASTVISIBLELINE = 11; //Last character of the last visible line, collapsed lines are skipped. const AEGI_FIRSTFULLVISIBLELINE = 12; //First character of the first fully visible line, collapsed lines are skipped. const AEGI_LASTFULLVISIBLELINE = 13; //Last character of the last fully visible line, collapsed lines are skipped. // //Next flags require pointer to the input index in lParam. const AEGI_VALIDCHARINLINE = 15; //Correct character to make sure that it is on line. //For better performance use AEC_ValidCharInLine instead. const AEGI_LINEBEGIN = 16; //First character in line. // const AEGI_LINEEND = 17; //Last character in line. // const AEGI_WRAPLINEBEGIN = 18; //First character of the unwrapped line. Returns number of characters as AEM_GETINDEX result. //For better performance use AEC_WrapLineBeginEx instead. const AEGI_WRAPLINEEND = 19; //Last character of the unwrapped line. Returns number of characters as AEM_GETINDEX result. //For better performance use AEC_WrapLineEndEx instead. const AEGI_NEXTCHARINLINE = 20; //Next character in line. //For better performance use AEC_NextCharInLineEx instead. const AEGI_PREVCHARINLINE = 21; //Previous character in line. //For better performance use AEC_PrevCharInLineEx instead. const AEGI_NEXTCHAR = 22; //Next wide character. //For better performance use AEC_NextCharEx instead. const AEGI_PREVCHAR = 23; //Previous wide character. //For better performance use AEC_PrevCharEx instead. const AEGI_NEXTLINE = 24; //First character of the next line. //For better performance use AEC_NextLineEx instead. const AEGI_PREVLINE = 25; //First character of the previous line. //For better performance use AEC_PrevLineEx instead. const AEGI_NEXTUNCOLLAPSEDCHAR = 26; //Next wide character, collapsed lines are skipped. const AEGI_PREVUNCOLLAPSEDCHAR = 27; //Previous wide character, collapsed lines are skipped. const AEGI_NEXTUNCOLLAPSEDLINE = 28; //First character of the next line, collapsed lines are skipped. const AEGI_PREVUNCOLLAPSEDLINE = 29; //First character of the previous line, collapsed lines are skipped. //AEM_ISDELIMITER parameter const AEDLM_PREVCHAR = $00000001; //Check previous char. const AEDLM_WORD = $00000010; //Word delimiter. const AEDLM_WRAP = $00000020; //Wrap delimiter. const AEDLM_URLLEFT = $00000040; //URL left delimiter. const AEDLM_URLRIGHT = $00000080; //URL right delimiter. //AEM_COLUMNTOINDEX and AEM_INDEXTOCOLUMN flags const AECTI_WRAPLINEBEGIN = $0001; //If set, scan from first character of the unwrapped line. If not set, scan from first character of the wrapped line. const AECTI_FIT = $0002; //AEM_COLUMNTOINDEX: if set, character position must be equal or less than column boundary. If not set, character position must be equal or larger than column boundary. //AEM_SETSEL and AEM_UPDATESEL flags const AESELT_COLUMNON = $00000001; //Make column selection ON. const AESELT_COLUMNASIS = $00000002; //Leave column selection as is. const AESELT_LOCKNOTIFY = $00000004; //Disable AEN_SELCHANGING and AEN_SELCHANGED notifications. const AESELT_LOCKSCROLL = $00000008; //Lock edit window scroll. const AESELT_LOCKUPDATE = $00000010; //Lock edit window update. const AESELT_LOCKCARET = $00000020; //Lock caret reposition. const AESELT_LOCKUNDOGROUPING = $00000040; //Don't use it. For internal code only. const AESELT_NOCARETHORZINDENT = $00000080; //Caret horizontal indent isn't changed. const AESELT_NOVERTSCROLLCORRECT = $00000100; //On some conditions scroll can be increased to a height of one line. const AESELT_MOUSE = $00000200; //Don't use it. For internal code only. const AESELT_RESETSELECTION = $00000400; //Don't use it. For internal code only. const AESELT_INDEXUPDATE = $00000800; //Update lpLine member of the AEM_SETSEL message structures, to avoid dangling of a pointer after text change. //AEM_REPLACESEL flags const AEREPT_COLUMNON = $00000001; //Make column selection ON. const AEREPT_COLUMNASIS = $00000002; //Leave column selection as is. const AEREPT_LOCKSCROLL = $00000004; //Lock edit window scroll. However edit window can be scrolled during window resize when AECO_DISABLENOSCROLL option not set. const AEREPT_UNDOGROUPING = $00000100; //Continue undo grouping. //AEM_CHARFROMPOS return value const AEPC_ERROR = 0; //Error. const AEPC_EQUAL = 1; //Char exactly in specified position. const AEPC_BEFORE = 2; //Char before the specified position. const AEPC_AFTER = 3; //Char after the specified position. //New line value const AELB_ASINPUT = 1; //Use input new line, see AEM_SETNEWLINE with AENL_INPUT. const AELB_ASOUTPUT = 2; //Use output new line, see AEM_SETNEWLINE with AENL_OUTPUT. const AELB_ASIS = 3; //Use new line of the source. const AELB_EOF = 4; //End-of-file, last line in document. const AELB_R = 5; //"\r" new line. const AELB_N = 6; //"\n" new line. const AELB_RN = 7; //"\r\n" new line. const AELB_RRN = 8; //"\r\r\n" new line. const AELB_WRAP = 9; //No new line, this line is wrapped. //AEM_SETNEWLINE flags const AENL_INPUT = $00000001; //Sets default new line for the input operations, for example AEM_PASTE. const AENL_OUTPUT = $00000002; //Sets default new line for the output operations, for example AEM_COPY. //AEM_PASTE flags const AEPFC_ANSI = $00000001; //Paste text as ANSI. Default is paste as Unicode text, if no Unicode text available ANSI text will be used. const AEPFC_COLUMN = $00000002; //Paste to column selection. //AEM_LOCKUPDATE FLAGS const AELU_SCROLLBAR = $00000001; const AELU_CARET = $00000002; //AEM_SETDOCUMENT flags const AESWD_NOCHECKFOCUS = $00000001; //Don't update focus state. const AESWD_NODRAGDROP = $00000002; //Don't register drag-and-drop with a new IDropTarget. const AESWD_NOSHOWSCROLLBARS = $00000004; //Don't update scrollbars visibility. const AESWD_NOUPDATESCROLLBARS = $00000008; //Don't update scrollbars position. const AESWD_NOUPDATECARET = $00000010; //Don't update caret. const AESWD_NOINVALIDATERECT = $00000020; //Don't redraw edit window. const AESWD_NOREDRAW = (AESWD_NOUPDATESCROLLBARS or AESWD_NOUPDATECARET or AESWD_NOINVALIDATERECT); const AESWD_NOALL = (AESWD_NOCHECKFOCUS or AESWD_NODRAGDROP or AESWD_NOSHOWSCROLLBARS or AESWD_NOREDRAW); //AEM_DRAGDROP flags const AEDD_GETDRAGWINDOW = 1; //Return dragging window handle. const AEDD_STOPDRAG = 2; //Set stop dragging operation flag. //AEM_SETCOLORS flags const AECLR_DEFAULT = $00000001; //Use default system colors for the specified flags, all members of the AECOLORS structure are ignored. const AECLR_CARET = $00000002; //Sets caret color. crCaret member is valid. const AECLR_BASICTEXT = $00000004; //Sets basic text color. crBasicText member is valid. const AECLR_BASICBK = $00000008; //Sets basic background color. crBasicBk member is valid. const AECLR_SELTEXT = $00000010; //Sets text in selection color. crSelText member is valid. const AECLR_SELBK = $00000020; //Sets background in selection color. crSelBk member is valid. const AECLR_ACTIVELINETEXT = $00000040; //Sets active line text color. crActiveLineText member is valid. const AECLR_ACTIVELINEBK = $00000080; //Sets active line background color. crActiveLineBk member is valid. const AECLR_URLTEXT = $00000100; //Sets hyperlink text color. crUrlText member is valid. const AECLR_ACTIVECOLUMN = $00000200; //Sets active column color. crActiveColumn member is valid. const AECLR_COLUMNMARKER = $00000400; //Sets column marker color. crColumnMarker member is valid. const AECLR_URLCURSORTEXT = $00000800; //Sets active hyperlink text color. crUrlCursorText member is valid. const AECLR_URLVISITTEXT = $00001000; //Sets visited hyperlink text color. crUrlVisitText member is valid. const AECLR_ACTIVELINEBORDER = $00002000; //Sets active line border color. crActiveLineBorder member is valid. const AECLR_ALTLINETEXT = $00004000; //Sets alternating line text color. crAltLineText member is valid. const AECLR_ALTLINEBK = $00008000; //Sets alternating line background color. crAltLineBk member is valid. const AECLR_ALTLINEBORDER = $00010000; //Sets alternating line border color. crAltLineBorder member is valid. const AECLR_ALL = (AECLR_CARET or AECLR_BASICTEXT or AECLR_BASICBK or AECLR_SELTEXT or AECLR_SELBK or AECLR_ACTIVELINETEXT or AECLR_ACTIVELINEBK or AECLR_URLTEXT or AECLR_ACTIVECOLUMN or AECLR_COLUMNMARKER or AECLR_URLCURSORTEXT or AECLR_URLVISITTEXT or AECLR_ACTIVELINEBORDER or AECLR_ALTLINETEXT or AECLR_ALTLINEBK or AECLR_ALTLINEBORDER); //Print const AEPRN_TEST = $001; //Calculate data without painting. const AEPRN_INHUNDREDTHSOFMILLIMETERS = $002; //Indicates that hundredths of millimeters are the unit of measurement for margins. const AEPRN_INTHOUSANDTHSOFINCHES = $004; //Indicates that thousandths of inches are the unit of measurement for margins. const AEPRN_WRAPNONE = $008; //Print without wrapping. const AEPRN_WRAPWORD = $010; //Print with word wrapping (default). const AEPRN_WRAPSYMBOL = $020; //Print with symbols wrapping. const AEPRN_IGNOREFORMFEED = $040; //Ignore form-feed character '\f'. const AEPRN_ANSI = $080; //Ansi text output. Can solve draw problems on Win95/98/Me. const AEPRN_COLOREDTEXT = $100; //Print colored text. const AEPRN_COLOREDBACKGROUND = $200; //Print on colored background. const AEPRN_COLOREDSELECTION = $400; //Print text selection. //Highlight options const AEHLO_IGNOREFONTNORMAL = $00000001; //Use AEHLS_NONE font style, if font style to change is AEHLS_FONTNORMAL. const AEHLO_IGNOREFONTBOLD = $00000002; //Use AEHLS_FONTNORMAL font style, if font style to change is AEHLS_FONTBOLD. //Use AEHLS_FONTITALIC font style, if font style to change is AEHLS_FONTBOLDITALIC. const AEHLO_IGNOREFONTITALIC = $00000004; //Use AEHLS_FONTNORMAL font style, if font style to change is AEHLS_FONTITALIC. //Use AEHLS_FONTBOLD font style, if font style to change is AEHLS_FONTBOLDITALIC. //Highlight flags const AEHLF_MATCHCASE = $00000001; //If set, the highlight operation is case-sensitive. If not set, the highlight operation is case-insensitive. const AEHLF_WORDCOMPOSITION = $00000002; //Word is a composition of characters. For example, AEWORDITEM.pWord equal to "1234567890" with this flag, means highlight words that contain only digits. const AEHLF_QUOTEEND_REQUIRED = $00000004; //If quote end isn't found, text after quote start will not be highlighted. const AEHLF_QUOTESTART_ISDELIMITER = $00000008; //Last meet delimiter used as quote start (AEQUOTEITEM.pQuoteStart member is ignored). const AEHLF_QUOTEEND_ISDELIMITER = $00000010; //First meet delimiter used as quote end (AEQUOTEITEM.pQuoteEnd member is ignored). const AEHLF_QUOTESTART_NOHIGHLIGHT = $00000020; //Don't highlight quote start string. const AEHLF_QUOTEEND_NOHIGHLIGHT = $00000040; //Don't highlight quote end string. const AEHLF_QUOTESTART_NOCATCH = $00000080; //Don't catch and don't highlight quote start string. const AEHLF_QUOTEEND_NOCATCH = $00000100; //Don't catch and don't highlight quote end string. const AEHLF_ATLINESTART = $00000200; //Quote start, delimiter or word located at line start. const AEHLF_ATLINEEND = $00000400; //Quote end, delimiter or word located at line end. const AEHLF_QUOTESTART_ISWORD = $00000800; //Quote start is surrounded with delimiters. const AEHLF_QUOTEEND_ISWORD = $00001000; //Quote end is surrounded with delimiters. const AEHLF_QUOTEWITHOUTDELIMITERS = $00002000; //Quote doesn't contain delimiters. const AEHLF_QUOTESTART_CATCHONLY = $00004000; //Only quote start string is catched. const AEHLF_QUOTEEMPTY = $00008000; //Quote doesn't contain any character. const AEHLF_QUOTEINCLUDE = $00010000; //Quote include string is valid. const AEHLF_QUOTEEXCLUDE = $00020000; //Quote exclude string is valid. //Regular exression: const AEHLF_REGEXP = $10000000; //Can be used in AEQUOTEITEM.dwFlags. // AEQUOTEITEM.pQuoteStart is a regular exression pattern, // AEQUOTEITEM.pQuoteEnd is a regular exression match map in format: // "\BackRef1=(FontStyle,ColorText,ColorBk) \BackRef2=(FontStyle,ColorText,ColorBk) ..." // Notes: // Color need to be in RRGGBB or RGB format with # prefix or without. // If color equal to zero, then color ignored. // Instead of color backreference can be used. // Example (highlight quoted string): // AEQUOTEITEM.pQuoteStart (")([^"\\]*(\\.[^"\\]*)*)(") // AEQUOTEITEM.pQuoteEnd \1=(0,#FF0000,0) \2=(0,#00F,0) \4=(0,#FF0000,0) // Example (highlight #RRGGBB or #RGB word with its color): // AEQUOTEITEM.pQuoteStart #([A-F\d]{6}|[A-F\d]{3})\b // AEQUOTEITEM.pQuoteEnd \0=(0,\1,0) //Can be used in AEMARKTEXTITEM.dwFlags. // AEMARKTEXTITEM.pMarkText is a regular exression pattern. //Highlight font style const AEHLS_NONE = 0; //Current style. const AEHLS_FONTNORMAL = 1; //Normal style. const AEHLS_FONTBOLD = 2; //Bold style. const AEHLS_FONTITALIC = 3; //Italic style. const AEHLS_FONTBOLDITALIC = 4; //Bold italic style. //Highlight elements const AEHLE_DELIMITER = 1; //Delimiter. New line, start of file and end of file are delimiters by default. const AEHLE_WORD = 2; //Word - string surrounded with delimiters. const AEHLE_QUOTE = 3; //Quote - text started with quote start string and ended with quote end string. const AEHLE_MARKTEXT = 4; //Mark text - mark specified text. const AEHLE_MARKRANGE = 5; //Mark range - mark specified range of characters. //Highlight AEM_HLGETHIGHLIGHT flags const AEGHF_NOSELECTION = $00000001; //Ignore text selection coloring. const AEGHF_NOACTIVELINE = $00000002; //Ignore active line colors. const AEGHF_NOALTLINE = $00000004; //Ignore alternating line colors. //Highlight paint type const AEHPT_SELECTION = $00000001; const AEHPT_DELIM1 = $00000002; const AEHPT_WORD = $00000004; const AEHPT_DELIM2 = $00000008; const AEHPT_QUOTE = $00000010; const AEHPT_MARKTEXT = $00000020; const AEHPT_MARKRANGE = $00000040; const AEHPT_LINK = $00000080; const AEHPT_FOLD = $00000100; //AEREGROUPCOLOR flags const AEREGCF_BACKREFCOLORTEXT = $00000001; //AEREGROUPCOLOR.crText is backreference index for text color in format #RRGGBB or RRGGBB. const AEREGCF_BACKREFCOLORBK = $00000002; //AEREGROUPCOLOR.crBk is backreference index for background color in format #RRGGBB or RRGGBB. //AEM_FINDFOLD flags const AEFF_FINDOFFSET = $00000001; //AEFINDFOLD.dwFindIt is RichEdit offset. const AEFF_FINDINDEX = $00000002; //AEFINDFOLD.dwFindIt is pointer to a AECHARINDEX structure. const AEFF_FINDLINE = $00000004; //AEFINDFOLD.dwFindIt is zero based line number. const AEFF_FOLDSTART = $00000008; //Fold is also accepted if AEFINDFOLD.dwFindIt points to fold start. const AEFF_FOLDEND = $00000010; //Fold is also accepted if AEFINDFOLD.dwFindIt points to fold end. const AEFF_RECURSE = $00000020; //Recursive search. Returned fold will be deepest possible. const AEFF_GETROOT = $00000040; //Return root fold. // //The following groups of flags cannot be used together: // AEFF_FINDOFFSET, AEFF_FINDINDEX and AEFF_FINDLINE. // AEFF_RECURSE and AEFF_GETROOT. //AEM_SCROLL, AEM_LINESCROLL flags const AESB_HORZ = $00000001; //Horizontal scroll. Cannot be used with AESB_VERT. const AESB_VERT = $00000002; //Vertical scroll. Cannot be used with AESB_HORZ. const AESB_RETURNUNITS = $00000004; //If AESB_HORZ specified, number of characters scrolled returns. If AESB_VERT specified, number of lines scrolled returns. const AESB_ALIGNLEFT = $00000008; //Align first visible char. const AESB_ALIGNRIGHT = $00000010; //Align last visible char. const AESB_ALIGNTOP = $00000020; //Align first visible line. const AESB_ALIGNBOTTOM = $00000040; //Align last visible line. //AEM_SCROLLTOPOINT flags const AESC_TEST = $00000001; //Only test for scroll. Returns result, but not actually scroll. const AESC_POINTCARET = $00000010; //Caret position is used and AESCROLLTOPOINT.ptPos is ignored. const AESC_POINTGLOBAL = $00000020; //AESCROLLTOPOINT.ptPos is position in the virtual text space coordinates. const AESC_POINTCLIENT = $00000040; //AESCROLLTOPOINT.ptPos is position in the client area coordinates (default). const AESC_POINTOUT = $00000080; //AESCROLLTOPOINT.ptPos will contain new scroll position after AEM_SCROLLTOPOINT returns. const AESC_OFFSETPIXELX = $00000100; //AESCROLLTOPOINT.nOffsetX specifies pixels number. const AESC_OFFSETPIXELY = $00000200; //AESCROLLTOPOINT.nOffsetY specifies pixels number. const AESC_OFFSETCHARX = $00000400; //AESCROLLTOPOINT.nOffsetX specifies characters number. const AESC_OFFSETCHARY = $00000800; //AESCROLLTOPOINT.nOffsetY specifies characters number. const AESC_OFFSETRECTDIVX = $00001000; //AESCROLLTOPOINT.nOffsetX specifies divisor of the edit rectangle width. const AESC_OFFSETRECTDIVY = $00002000; //AESCROLLTOPOINT.nOffsetY specifies divisor of the edit rectangle width. const AESC_FORCELEFT = $00010000; //Scrolls to the left even if AESCROLLTOPOINT.ptPos visible. const AESC_FORCETOP = $00020000; //Scrolls to the top even if AESCROLLTOPOINT.ptPos visible. const AESC_FORCERIGHT = $00040000; //Scrolls to the right even if AESCROLLTOPOINT.ptPos visible. const AESC_FORCEBOTTOM = $00080000; //Scrolls to the bottom even if AESCROLLTOPOINT.ptPos visible. //AEM_SCROLLTOPOINT return values const AECSE_SCROLLEDX = $00000001; //Edit control was horizontally scrolled. const AECSE_SCROLLEDY = $00000002; //Edit control was vertically scrolled. const AECSE_SCROLLEDLEFT = $00000004; //Edit control was scrolled left horizontally. const AECSE_SCROLLEDRIGHT = $00000008; //Edit control was scrolled right horizontally. const AECSE_SCROLLEDUP = $00000010; //Edit control was scrolled up vertically. const AECSE_SCROLLEDDOWN = $00000020; //Edit control was scrolled down vertically. //AEM_GETFONT type const AEGF_CURRENT = 0; //Current font handle. const AEGF_NORMAL = 1; //Normal style font handle. const AEGF_BOLD = 2; //Bold style font handle. const AEGF_ITALIC = 3; //Italic style font handle. const AEGF_BOLDITALIC = 4; //Bold italic style font handle. const AEGF_URL = 5; //URL style font handle. //AEM_GETCHARSIZE flags const AECS_HEIGHT = 0; //Current font character height including line gap. lParam not used. const AECS_AVEWIDTH = 1; //Current font character average width. lParam not used. const AECS_INDEXWIDTH = 2; //lParam is character index, which width is retrieving. const AECS_POINTSIZE = 3; //Current font point size. lParam not used. const AECS_SPACEWIDTH = 4; //Current font space width. lParam not used. const AECS_TABWIDTH = 5; //Current font tabulation width. lParam not used. //AEM_CONVERTPOINT flags const AECPT_GLOBALTOCLIENT = 0; //Convert position in the virtual text space of the document, to client area coordinates. const AECPT_CLIENTTOGLOBAL = 1; //Convert position in the client area coordinates, to virtual text space of the document. //Coordinate type const AECT_GLOBAL = 0; //Position in the virtual text space coordinates. const AECT_CLIENT = 1; //Position in the client area coordinates. //Rectangle flags const AERC_UPDATE = $01; //Redraw edit window. Only for AEM_SETRECT and AEM_SETERASERECT. const AERC_MARGINS = $02; //Rectangle contain edit area margins instead of edit area coordinates. const AERC_NOLEFT = $04; //Don't set/retrieve left side. const AERC_NOTOP = $08; //Don't set/retrieve top side. const AERC_NORIGHT = $10; //Don't set/retrieve right side. const AERC_NOBOTTOM = $20; //Don't set/retrieve bottom side. //AEM_POINTONMARGIN sides const AESIDE_LEFT = $00000001; const AESIDE_TOP = $00000002; const AESIDE_RIGHT = $00000004; const AESIDE_BOTTOM = $00000008; //AEM_GETMOUSESTATE types const AEMS_CAPTURE = 1; //Capture state. const AEMS_SELECTION = 2; //Selection state. //AEM_GETMOUSESTATE capture const AEMSC_MOUSEMOVE = $1; //Text selection. const AEMSC_MOUSESCROLL = $2; //Middle button scroll. const AEMSC_MOUSEDRAG = $4; //Selection dragging. const AEMSC_MOUSEMARKER = $8; //Marker moving. //AEM_GETMOUSESTATE selection const AEMSS_LBUTTONUP = $1; //WM_LBUTTONUP has been received. const AEMSS_CHARS = $2; //Characters selection. const AEMSS_WORDS = $4; //Words selection. const AEMSS_LINES = $8; //Lines selection. //AEM_FINDTEXT, AEM_ISMATCH flags const AEFR_DOWN = $00000001; //Same as FR_DOWN. If set, the search is from the beginning to the end of the search range. If not set, the search is from the end to the beginning of the search range. const AEFR_WHOLEWORD = $00000002; //Same as FR_WHOLEWORD. If set, the operation searches only for whole words that match the search string. If not set, the operation also searches for word fragments that match the search string. const AEFR_MATCHCASE = $00000004; //Same as FR_MATCHCASE. If set, the search operation is case-sensitive. If not set, the search operation is case-insensitive. const AEFR_REGEXP = $00080000; //Regular expression search. const AEFR_REGEXPNONEWLINEDOT = $00100000; //Symbol . specifies any character except new line. const AEFR_REGEXPMINMATCH = $00200000; //Allow zero length match at string edges. For example: "^" at the string beginning or "$" at the string ending. //AEM_SETWORDWRAP flags const AEWW_NONE = $00000000; //Turn off wrap. const AEWW_WORD = $00000001; //Wrap by words. const AEWW_SYMBOL = $00000002; //Wrap by symbols. const AEWW_LIMITPIXEL = $00000100; //Limit in pixels (default). const AEWW_LIMITSYMBOL = $00000200; //Limit in symbols. //AEM_SETMARKER types const AEMT_PIXEL = 0; //Pixel integer. const AEMT_SYMBOL = 1; //Column number. //AEM_SETWORDBREAK flags const AEWB_LEFTWORDSTART = $00000001; //Left movement is stopped, when word start is found. const AEWB_LEFTWORDEND = $00000002; //Left movement is stopped, when word end is found. const AEWB_RIGHTWORDSTART = $00000004; //Right movement is stopped, when word start is found. const AEWB_RIGHTWORDEND = $00000008; //Right movement is stopped, when word end is found. const AEWB_STOPSPACESTART = $00000010; //Movement is stopped, when spacing start is found. Cannot be combined with AEWB_SKIPSPACESTART. const AEWB_STOPSPACEEND = $00000020; //Movement is stopped, when spacing end is found. Cannot be combined with AEWB_SKIPSPACEEND. const AEWB_SKIPSPACESTART = $00000040; //Movement is continued, when spacing start is found. Cannot be combined with AEWB_STOPSPACESTART. const AEWB_SKIPSPACEEND = $00000080; //Movement is continued, when spacing end is found. Cannot be combined with AEWB_STOPSPACEEND. const AEWB_STOPNEWLINE = $00000100; //Movement is stopped, when new line is found. const AEWB_MINMOVE = $00001000; //Minimum movement or not move at all if flags matched. //AEM_STREAMIN, AEM_STREAMOUT flags const AESF_SELECTION = $00000001; //Stream-in (read) or stream-out (write) the current selection. If not specified, stream-in (read) or stream-out (write) the entire contents of the control. const AESF_FILLSPACES = $00000002; //Stream-out (write) the current column selection with the filling empty spaces. Valid if bColumnSel member of a AESTREAMOUT structure is TRUE. //AEM_ISRANGEMODIFIED return value const AEIRM_UNMODIFIED = 1; const AEIRM_MODIFIEDUNSAVED = 2; const AEIRM_MODIFIEDSAVED = 3; { Fr0sT: these constants are defined in AkelDLL.pas so do not redefine them here const FR_DOWN = $00000001; const FR_WHOLEWORD = $00000002; } const FR_MATCHCASE = $00000004; { Fr0sT: these constants are defined in RTL since D7 const EC_LEFTMARGIN = $0001; const EC_RIGHTMARGIN = $0002; const SPI_GETWHEELSCROLLLINES = $0068; const WM_MOUSEWHEEL = $020A; const EN_DRAGDROPDONE = $070c; const WC_NO_BEST_FIT_CHARS = $00000400; const GT_SELECTION = $0002; } const EM_SHOWSCROLLBAR = (WM_USER + 96); const EM_GETSCROLLPOS = (WM_USER + 221); const EM_SETSCROLLPOS = (WM_USER + 222); const EM_SETTEXTEX = (WM_USER + 97); const ST_DEFAULT = $0000; const ST_KEEPUNDO = $0001; const ST_SELECTION = $0002; const ST_NEWCHARS = $0004; type SETTEXTEX = record flags: DWORD; codepage: UINT; end; // Fr0sT: mod => Abs() // #define mod(a) (((a) < 0) ? (0 - (a)) : (a)) // Fr0sT: already defined in AkelDLL // AEHDOC = THandle; type AEHPRINT = THandle; type AEHTHEME = THandle; type AEHDELIMITER = THandle; type AEHWORD = THandle; type AEHQUOTE = THandle; type AEHMARKTEXT = THandle; type AEHMARKRANGE = THandle; // Fr0sT: already defined in AkelDLL // hDoc Document handle returned by AEM_GETDOCUMENT or AEM_CREATEDOCUMENT. // uMsg Message ID for example EM_SETSEL. // lParam Additional parameter. // wParam Additional parameter. // // Return Value // Depends on message. // AEEditProc = function(hDoc: AEHDOC; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; //// Structures for x64 RichEdit support type PCHARRANGE64 = ^TCHARRANGE64; _CHARRANGE64 = record cpMin: INT_PTR; cpMax: INT_PTR; end; TCHARRANGE64 = _CHARRANGE64; type _TEXTRANGE64A = record chrg: TCHARRANGE64; lpstrText: LPSTR; end; TTEXTRANGE64A = _TEXTRANGE64A; type _TEXTRANGE64W = record chrg: TCHARRANGE64; lpstrText: LPWSTR; end; TTEXTRANGE64W = _TEXTRANGE64W; type _FINDTEXTEX64A = record chrg: TCHARRANGE64; lpstrText: LPCSTR; chrgText: TCHARRANGE64; end; TFINDTEXTEX64A = _FINDTEXTEX64A; type _FINDTEXTEX64W = record chrg: TCHARRANGE64; lpstrText: LPCWSTR; chrgText: TCHARRANGE64; end; TFINDTEXTEX64W = _FINDTEXTEX64W; type _GETTEXTEX64 = record cb: UINT_PTR; flags: DWORD; codepage: UINT; lpDefaultChar: LPCSTR; lpUsedDefChar: PBOOL; end; TGETTEXTEX64 = _GETTEXTEX64; type _SELCHANGE64 = record nmhdr: NMHDR; chrg: TCHARRANGE; seltyp: WORD; chrg64: TCHARRANGE64; end; TSELCHANGE64 = _SELCHANGE64; type _ENDROPFILES64 = record nmhdr: NMHDR; hDrop: THandle; cp: LongInt; fProtected: BOOL; cp64: INT_PTR; end; TENDROPFILES64 = _ENDROPFILES64; type _ENLINK64 = record nmhdr: NMHDR; msg: UINT; wParam: WPARAM; lParam: LPARAM; chrg: TCHARRANGE; chrg64: TCHARRANGE64; end; TENLINK64 = _ENLINK64; //// Structures for x64 support type _POINT64 = record x: INT_PTR; y: INT_PTR; end; TPOINT64 = _POINT64; type _SIZE64 = record cx: INT_PTR; cy: INT_PTR; end; TSIZE64 = _SIZE64; //// Structures // Fr0sT: already defined in AkelDLL // HSTACK type PStack = ^TStack; TStack = record next: PStack; prev: PStack; end; // Fr0sT: already defined in AkelDLL // AELINEDATA // AELINEINDEX // AECHARINDEX // AECHARRANGE type _AESELECTION = record crSel: TAECHARRANGE; //Characters range. dwFlags: DWORD; //See AESELT_* defines. dwType: DWORD; //See AESCT_* defines. end; TAESELECTION = _AESELECTION; type PAEPOINT = ^TAEPOINT; _AEPOINT = record next: PAEPOINT; //Pointer to the next AEPOINT structure. prev: PAEPOINT; //Pointer to the previous AEPOINT structure. ciPoint: TAECHARINDEX; //Read-only character index. nPointOffset: INT_PTR; //Character RichEdit offset or one of the AEPTO_* define. nPointLen: Integer; //Point length. dwFlags: DWORD; //See AEPTF_* defines. dwUserData: UINT_PTR; //User data. nTmpPointOffset: INT_PTR; //Don't use it. For internal code only. nTmpPointLen: Integer; //Don't use it. For internal code only. end; TAEPOINT = _AEPOINT; type PAEFOLD = ^TAEFOLD; _AEFOLD = record next: PAEFOLD; //Pointer to the next AEFOLD structure. prev: PAEFOLD; //Pointer to the previous AEFOLD structure. parent: PAEFOLD; //Pointer to the parent AEFOLD structure. firstChild: PAEFOLD; //Pointer to the first child AEFOLD structure. lastChild: PAEFOLD; //Pointer to the last child AEFOLD structure. lpMinPoint: PAEPOINT; //Minimum line point. lpMaxPoint: PAEPOINT; //Maximum line point. bCollapse: BOOL; //Collapse state. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Text color. If -1, then don't set. crBk: COLORREF; //Background color. If -1, then don't set. dwUserData: UINT_PTR; //User data. end; TAEFOLD = _AEFOLD; type _AEFINDFOLD = record dwFlags: DWORD; //[in] See AEFF_* defines. dwFindIt: UINT_PTR; //[in] Depend on AEFF_FIND* define. lpParent: PAEFOLD; //[out] Parent fold. lpPrevSubling: PAEFOLD; //[out] Previous subling fold. end; TAEFINDFOLD = _AEFINDFOLD; type _AESETTEXTA = record pText: PAnsiChar; //[in] Text to append. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. nCodePage: Integer; //[in] Code page identifier (any available in the system). You can also specify one of the following values: CP_ACP - ANSI code page, CP_OEMCP - OEM code page, CP_UTF8 - UTF-8 code page. end; TAESETTEXTA = _AESETTEXTA; type _AESETTEXTW = record pText: PWideChar; //[in] Text to append. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. end; TAESETTEXTW = _AESETTEXTW; type _AEAPPENDTEXTA = record pText: PAnsiChar; //[in] Text to append. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. nCodePage: Integer; //[in] Code page identifier (any available in the system). You can also specify one of the following values: CP_ACP - ANSI code page, CP_OEMCP - OEM code page, CP_UTF8 - UTF-8 code page. end; TAEAPPENDTEXTA = _AEAPPENDTEXTA; type _AEAPPENDTEXTW = record pText: PWideChar; //[in] Text to append. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. end; TAEAPPENDTEXTW = _AEAPPENDTEXTW; type _AEREPLACESELA = record pText: PAnsiChar; //[in] Text to replace with. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. dwFlags: DWORD; //[in] See AEREPT_* defines. ciInsertStart: PAECHARINDEX; //[out] Insert "from" character index after replacement. ciInsertEnd: PAECHARINDEX; //[out] Insert "to" character index after replacement. nCodePage: Integer; //[in] Code page identifier (any available in the system). You can also specify one of the following values: CP_ACP - ANSI code page, CP_OEMCP - OEM code page, CP_UTF8 - UTF-8 code page. end; TAEREPLACESELA = _AEREPLACESELA; type _AEREPLACESELW = record pText: PWideChar; //[in] Text to replace with. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. dwFlags: DWORD; //[in] See AEREPT_* defines. ciInsertStart: PAECHARINDEX; //[out] Insert "from" character index after replacement. ciInsertEnd: PAECHARINDEX; //[out] Insert "to" character index after replacement. end; TAEREPLACESELW = _AEREPLACESELW; type _AETEXTRANGEA = record cr: TAECHARRANGE; //[in] Characters range to retrieve. bColumnSel: BOOL; //[in] Column selection. If this value is -1, use current selection type. pBuffer: PAnsiChar; //[out] Pointer to buffer that receives the text. If this value is NULL, the function returns the required buffer size in characters. dwBufferMax: UINT_PTR; //[in] Specifies the maximum number of characters to copy to the buffer, including the NULL character. nNewLine: Integer; //[in] See AELB_* defines. nCodePage: Integer; //[in] Code page identifier (any available in the system). You can also specify one of the following values: CP_ACP - ANSI code page, CP_OEMCP - OEM code page, CP_UTF8 - UTF-8 code page. lpDefaultChar: PAnsiChar; //[in] Points to the character used if a wide character cannot be represented in the specified code page. If this member is NULL, a system default value is used. lpUsedDefChar: PBOOL; //[in] Points to a flag that indicates whether a default character was used. The flag is set to TRUE if one or more wide characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This member may be NULL. bFillSpaces: BOOL; //[in] If bColumnSel is TRUE, fill empties with spaces. end; TAETEXTRANGEA = _AETEXTRANGEA; type _AETEXTRANGEW = record cr: TAECHARRANGE; //[in] Characters range to retrieve. bColumnSel: BOOL; //[in] Column selection. If this value is -1, use current selection type. If bColumnSel is TRUE, then selection must be exist, otherwise it is not necessary. pBuffer: PWideChar; //[out] Pointer to buffer that receives the text. If this value is NULL, the function returns the required buffer size in characters. dwBufferMax: UINT_PTR; //[in] Specifies the maximum number of characters to copy to the buffer, including the NULL character. nNewLine: Integer; //[in] See AELB_* defines. nCodePage: Integer; //[in] Ignored. Code page is always 1200 (UTF-16 LE). lpDefaultChar: PWideChar; //[in] Ignored. lpUsedDefChar: PBOOL; //[in] Ignored. bFillSpaces: BOOL; //[in] If bColumnSel is TRUE, fill empties with spaces. end; TAETEXTRANGEW = _AETEXTRANGEW; type //dwCookie Value of the dwCookie member of the AESTREAMIN or AESTREAMOUT structure. The application specifies this value when it sends the AEM_STREAMIN or AEM_STREAMOUT message. //wszBuf Pointer to a buffer to read from or write to. For a stream-in (read) operation, the callback function fills this buffer with data to transfer into the edit control. For a stream-out (write) operation, the buffer contains data from the control that the callback function writes to some storage. //dwBufBytesSize Number of bytes to read or write. //dwBufBytesDone Pointer to a variable that the callback function sets to the number of bytes actually read or written. // //Return Value // The callback function returns zero to indicate success. // //Remarks // The control continues to call the callback function until one of the following conditions occurs: // * The callback function returns a nonzero value. // * The callback function returns zero in the *dwBufBytesDone parameter. TAEStreamCallback = function(dwCookie: UINT_PTR; var wszBuf: PWideChar; dwBufBytesSize: DWORD; var dwBufBytesDone: DWORD): DWORD; stdcall; type _AESTREAMIN = record dwCookie: UINT_PTR; //[in] Specifies an application-defined value that the edit control passes to the AEStreamCallback function specified by the lpCallback member. dwError: DWORD; //[out] Indicates the results of the stream-in (read) operation. lpCallback: TAEStreamCallback; //[in] Pointer to an AEStreamCallback function, which is an application-defined function that the control calls to transfer data. The control calls the callback function repeatedly, transferring a portion of the data with each call. nNewLine: Integer; //[in] See AELB_* defines. dwTextLen: UINT_PTR; //[in] Text length. Need if using AEN_PROGRESS notification. nFirstNewLine: Integer; //[out] Indicates first new line. See AELB_* defines. end; TAESTREAMIN = _AESTREAMIN; type _AESTREAMOUT = record dwCookie: UINT_PTR; //[in] Specifies an application-defined value that the edit control passes to the AEStreamCallback function specified by the lpCallback member. dwError: DWORD; //[out] Indicates the result of the stream-out (write) operation. lpCallback: TAEStreamCallback; //[in] Pointer to an AEStreamCallback function, which is an application-defined function that the control calls to transfer data. The control calls the callback function repeatedly, transferring a portion of the data with each call. nNewLine: Integer; //[in] See AELB_* defines. bColumnSel: BOOL; //[in] Column selection. If this value is -1, use current selection type. end; TAESTREAMOUT = _AESTREAMOUT; type _AEFINDTEXTA = record dwFlags: DWORD; //[in] See AEFR_* defines. pText: PAnsiChar; //[in] Text to find. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. crSearch: TAECHARRANGE; //[in] Range of characters to search. crFound: TAECHARRANGE; //[out] Range of characters in which text is found. nCompileErrorOffset: INT_PTR; //[out] Contain pattern offset, if error occurred during compile pattern. Return when AEFR_REGEXP is set. end; TAEFINDTEXTA = _AEFINDTEXTA; type _AEFINDTEXTW = record dwFlags: DWORD; //[in] See AEFR_* defines. pText: PWideChar; //[in] Text to find. dwTextLen: UINT_PTR; //[in] Text length. If this value is -1, the string is assumed to be null-terminated and the length is calculated automatically. nNewLine: Integer; //[in] See AELB_* defines. crSearch: TAECHARRANGE; //[in] Range of characters to search. crFound: TAECHARRANGE; //[out] Range of characters in which text is found. nCompileErrorOffset: INT_PTR; //[out] Contain pattern offset, if error occurred during compile pattern. Return when AEFR_REGEXP is set. end; TAEFINDTEXTW = _AEFINDTEXTW; // Fr0sT: already defined in AkelDLL // AECOLORS = record type _AECHARCOLORS = record dwFlags: DWORD; //[in] See AEGHF_* defines. dwFontStyle: DWORD; //[Out] See AEHLS_* defines. crText: COLORREF; //[Out] Text color in line. crBk: COLORREF; //[Out] Background color in line. crBorderTop: COLORREF; //[Out] Top border color of the line. crBorderBottom: COLORREF; //[Out] Bottom border color of the line. end; TAECHARCOLORS = _AECHARCOLORS; type _AEINDEXOFFSET = record ciCharIn: PAECHARINDEX; //[in] Input character index. ciCharOut: PAECHARINDEX; //[out] Output character index (result). nOffset: INT_PTR; //[in] Offset can be positive or negative. For example, +1 will return next character, -1 will return previous character. nNewLine: Integer; //[in] See AELB_* defines. end; TAEINDEXOFFSET = _AEINDEXOFFSET; type _AEINDEXSUBTRACT = record ciChar1: PAECHARINDEX; //[in] First character index. If NULL, first character is used. ciChar2: PAECHARINDEX; //[in] Second character index. If NULL, last character is used. bColumnSel: BOOL; //[in] Column selection. If this value is -1, use current selection type. nNewLine: Integer; //[in] See AELB_* defines. end; TAEINDEXSUBTRACT = _AEINDEXSUBTRACT; type _AESCROLLTOPOINT = record dwFlags: DWORD; //[in] See AESC_* defines. ptPos: TPOINT64; //[in,out] Point to scroll to, ignored if AESC_POINTCARET flag specified. nOffsetX: Integer; //[in] Horizontal scroll offset. nOffsetY: Integer; //[in] Vertical scroll offset. end; TAESCROLLTOPOINT = _AESCROLLTOPOINT; type _AESCROLLCARETOPTIONS = record dwFlags: DWORD; //See AESC_OFFSET* defines. dwSelFlags: DWORD; //See AESELT_* defines. Can be zero. dwSelType: DWORD; //See AESCT_* defines. nOffsetX: Integer; //Minimal number of characters to horizontal window edge. nOffsetY: Integer; //Minimal number of lines to vertical window edge. end; TAESCROLLCARETOPTIONS = _AESCROLLCARETOPTIONS; type _AESENDMESSAGE = record hDoc: AEHDOC; //Document handle. See AEM_CREATEDOCUMENT message. uMsg: UINT; //Window message. wParam: WPARAM; //Window first additional parameter. lParam: LPARAM; //Window second additional parameter. lResult: LRESULT; //cResult after window message returns. end; TAESENDMESSAGE = _AESENDMESSAGE; type _AEPRINT = record dwFlags: DWORD; //[in] See AEPRN_* defines. hPrinterDC: HDC; //[in] Printer device context. hEditFont: HFONT; //[in] Edit font. hPrintFont: HFONT; //[out] Print font (mapped edit font). nCharHeight: Integer; //[out] Print character height. nAveCharWidth: Integer; //[out] Print character average width. nSpaceCharWidth: Integer; //[out] Print space width. nTabWidth: Integer; //[out] Print tabulation width. rcMargins: TRect; //[in] Specifies the widths of the left, top, right, and bottom margins. The AEPRN_INHUNDREDTHSOFMILLIMETERS or AEPRN_INTHOUSANDTHSOFINCHES flag indicates the units of measurement. rcPageFull: TRect; //[out] Complete page rectangle. Filled by AEM_STARTPRINTDOC message. rcPageIn: TRect; //[in,out] Available page rectangle (minus margins). Filled by AEM_STARTPRINTDOC message and can be modified by user before AEM_PRINTPAGE call. rcPageOut: TRect; //[out] Filled page rectangle. Filled by AEM_PRINTPAGE message. crText: TAECHARRANGE; //[in,out] Text range to print. Filled by user and changed after AEM_PRINTPAGE message. end; TAEPRINT = _AEPRINT; type PAEDELIMITEMA = ^TAEDELIMITEMA; _AEDELIMITEMA = record next: PAEDELIMITEMA; prev: PAEDELIMITEMA; nIndex: Integer; //Position of the element if positive inserts to begin of stack if negative to end. pDelimiter: PAnsiChar; //Delimiter string. nDelimiterLen: Integer; //Delimiter string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Delimiter text color. If -1, then don't set. crBk: COLORREF; //Delimiter background color. If -1, then don't set. end; TAEDELIMITEMA = _AEDELIMITEMA; type PAEDELIMITEMW = ^TAEDELIMITEMW; _AEDELIMITEMW = record next: PAEDELIMITEMW; prev: PAEDELIMITEMW; nIndex: Integer; //Position of the element if positive inserts to begin of stack if negative to end. pDelimiter: PWideChar; //Delimiter string. nDelimiterLen: Integer; //Delimiter string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Delimiter text color. If -1, then don't set. crBk: COLORREF; //Delimiter background color. If -1, then don't set. end; TAEDELIMITEMW = _AEDELIMITEMW; type PAEWORDITEMA = ^TAEWORDITEMA; _AEWORDITEMA = record next: PAEWORDITEMA; prev: PAEWORDITEMA; nIndex: Integer; //Reserved. Word items are automatically sorted. pWord: PAnsiChar; //Word string. nWordLen: Integer; //Word string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Word text color. If -1, then don't set. crBk: COLORREF; //Word background color. If -1, then don't set. end; TAEWORDITEMA = _AEWORDITEMA; type PAEWORDITEMW = ^TAEWORDITEMW; _AEWORDITEMW = record next: PAEWORDITEMW; prev: PAEWORDITEMW; nIndex: Integer; //Reserved. Word items are automatically sorted. pWord: PWideChar; //Word string. nWordLen: Integer; //Word string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Word text color. If -1, then don't set. crBk: COLORREF; //Word background color. If -1, then don't set. end; TAEWORDITEMW = _AEWORDITEMW; type PAEQUOTEITEMA = ^TAEQUOTEITEMA; _AEQUOTEITEMA = record next: PAEQUOTEITEMA; prev: PAEQUOTEITEMA; nIndex: Integer; //Reserved. Quote start items are automatically grouped in standalone stack, if following members are equal: pQuoteStart, chEscape and dwFlags with AEHLF_QUOTESTART_ISDELIMITER, AEHLF_ATLINESTART, AEHLF_QUOTESTART_ISWORD. pQuoteStart: PAnsiChar; //Quote start string. nQuoteStartLen: Integer; //Quote start string length. pQuoteEnd: PAnsiChar; //Quote end string. If NULL, line end used as quote end. nQuoteEndLen: Integer; //Quote end string length. chEscape: AnsiChar; //Escape character. If it precedes quote string then quote ignored. pQuoteInclude: PAnsiChar; //Quote include string. nQuoteIncludeLen: Integer; //Quote include string length. pQuoteExclude: PAnsiChar; //Quote exclude string. nQuoteExcludeLen: Integer; //Quote exclude string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Quote text color. If -1, then don't set. crBk: COLORREF; //Quote background color. If -1, then don't set. lpQuoteStart: Pointer; //Don't use it. For internal code only. nCompileErrorOffset: INT_PTR; //Contain pQuoteStart offset, if error occurred during compile regular exression pattern. end; TAEQUOTEITEMA = _AEQUOTEITEMA; type PAEQUOTEITEMW = ^TAEQUOTEITEMW; _AEQUOTEITEMW = record next: PAEQUOTEITEMW; prev: PAEQUOTEITEMW; nIndex: Integer; //Reserved. Quote start items are automatically grouped in standalone stack, if following members are equal: pQuoteStart, chEscape and dwFlags with AEHLF_QUOTESTART_ISDELIMITER, AEHLF_ATLINESTART, AEHLF_QUOTESTART_ISWORD. pQuoteStart: PWideChar; //Quote start string. nQuoteStartLen: Integer; //Quote start string length. pQuoteEnd: PWideChar; //Quote end string. If NULL, line end used as quote end. nQuoteEndLen: Integer; //Quote end string length. chEscape: WideChar; //Escape character. If it precedes quote string then quote ignored. pQuoteInclude: PWideChar; //Quote include string. nQuoteIncludeLen: Integer; //Quote include string length. pQuoteExclude: PWideChar; //Quote exclude string. nQuoteExcludeLen: Integer; //Quote exclude string length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Quote text color. If -1, then don't set. crBk: COLORREF; //Quote background color. If -1, then don't set. lpQuoteStart: Pointer; //Don't use it. For internal code only. nCompileErrorOffset: INT_PTR; //Contain pQuoteStart offset, if error occurred during compile regular exression pattern. (* !! original: union { void *lpREGroupStack; //Don't use it. For internal code only. INT_PTR nCompileErrorOffset; //Contain pQuoteStart offset, if error occurred during compile regular exression pattern. }; *) {$IF SizeOf(INT_PTR) <> SizeOf(Pointer)}oops{$IFEND} end; TAEQUOTEITEMW = _AEQUOTEITEMW; type _AEREGROUPCOLOR = record dwFlags: DWORD; //See AEREGCF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Quote text color. If -1, then don't set. crBk: COLORREF; //Quote background color. If -1, then don't set. end; TAEREGROUPCOLOR = _AEREGROUPCOLOR; type PAEMARKTEXTITEMA = ^TAEMARKTEXTITEMA; _AEMARKTEXTITEMA = record next: PAEMARKTEXTITEMA; prev: PAEMARKTEXTITEMA; nIndex: Integer; //Position of the element if positive inserts to begin of stack if negative to end. pMarkText: PAnsiChar; //Mark text. nMarkTextLen: Integer; //Mark text length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Mark text color. If -1, then don't set. crBk: COLORREF; //Mark background color. If -1, then don't set. nCompileErrorOffset: INT_PTR; //Contain pMarkText offset, if error occurred during compile regular exression pattern. end; TAEMARKTEXTITEMA = _AEMARKTEXTITEMA; type PAEMARKTEXTITEMW = ^TAEMARKTEXTITEMW; _AEMARKTEXTITEMW = record next: PAEMARKTEXTITEMW; prev: PAEMARKTEXTITEMW; nIndex: Integer; //Position of the element if positive inserts to begin of stack if negative to end. pMarkText: PWideChar; //Mark text. nMarkTextLen: Integer; //Mark text length. dwFlags: DWORD; //See AEHLF_* defines. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Mark text color. If -1, then don't set. crBk: COLORREF; //Mark background color. If -1, then don't set. nCompileErrorOffset: INT_PTR; //Contain pMarkText offset, if error occurred during compile regular exression pattern. (* !! original: union { void *lpREGroupStack; //Don't use it. For internal code only. INT_PTR nCompileErrorOffset; //Contain pMarkText offset, if error occurred during compile regular exression pattern. }; *) {$IF SizeOf(INT_PTR) <> SizeOf(Pointer)}oops{$IFEND} end; TAEMARKTEXTITEMW = _AEMARKTEXTITEMW; type PAEMARKRANGEITEM = ^TAEMARKRANGEITEM; _AEMARKRANGEITEM = record next: PAEMARKRANGEITEM; prev: PAEMARKRANGEITEM; nIndex: Integer; //Position of the element if positive inserts to begin of stack if negative to end. crMarkRange: TCHARRANGE64; //cpMin member is the first character in the range (RichEdit offset), cpMax member is the last character in the range (RichEdit offset). dwFlags: DWORD; //Reserved. dwFontStyle: DWORD; //See AEHLS_* defines. crText: COLORREF; //Mark text color. If -1, then don't set. crBk: COLORREF; //Mark background color. If -1, then don't set. end; TAEMARKRANGEITEM = _AEMARKRANGEITEM; type _AEMARKTEXTMATCH = record lpMarkText: PAEMARKTEXTITEMW; crMarkText: TAECHARRANGE; end; TAEMARKTEXTMATCH = _AEMARKTEXTMATCH; type _AEMARKRANGEMATCH = record lpMarkRange: PAEMARKRANGEITEM; crMarkRange: TCHARRANGE64; end; TAEMARKRANGEMATCH = _AEMARKRANGEMATCH; type AEQUOTEMATCH = record lpQuote: PAEQUOTEITEMW; crQuoteStart: TAECHARRANGE; crQuoteEnd: TAECHARRANGE; end; TAEQUOTEMATCH = AEQUOTEMATCH; type AEWORDMATCH = record lpDelim1: PAEDELIMITEMW; crDelim1: TAECHARRANGE; lpWord: PAEWORDITEMW; crWord: TAECHARRANGE; lpDelim2: PAEDELIMITEMW; crDelim2: TAECHARRANGE; end; TAEWORDMATCH = AEWORDMATCH; type AEFOLDMATCH = record crFold: TCHARRANGE64; lpFold: PAEFOLD; end; TAEFOLDMATCH = AEFOLDMATCH; type PAEHLPAINT = ^TAEHLPAINT; _AEHLPAINT = record dwDefaultText: DWORD; //Text color without highlighting. dwDefaultBk: DWORD; //Background color without highlighting. dwActiveText: DWORD; //Text color with highlighting. dwActiveBk: DWORD; //Background color with highlighting. dwFontStyle: DWORD; //See AEHLS_* defines. dwPaintType: DWORD; //See AEHPT_* defines. dwFindFirst: DWORD; //Don't use it. For internal code only. wm: TAEWORDMATCH; //Word or/and delimiters items are found, if AEWORDITEMW.lpDelim1 or AEWORDITEMW.lpWord or AEWORDITEMW.lpDelim2 aren't NULL. qm: TAEQUOTEMATCH; //Quote item is found, if AEQUOTEMATCH.lpQuote isn't NULL. mrm: TAEMARKRANGEMATCH; //Mark range item is found, if AEMARKRANGEMATCH.lpMarkRange isn't NULL. mtm: TAEMARKTEXTMATCH; //Mark text item is found, if AEMARKTEXTMATCH.lpMarkText isn't NULL. fm: TAEFOLDMATCH; //Fold item is found, if AEFOLDMATCH.lpFold isn't NULL. crLink: TAECHARRANGE; //URL item is found, if AECHARRANGE.ciMin.lpLine and AECHARRANGE.ciMax.lpLine aren't NULL. end; TAEHLPAINT = _AEHLPAINT; type //dwCookie Value of the dwCookie member of the AEGETHIGHLIGHT structure. The application specifies this value when it sends the AEM_HLGETHIGHLIGHT message. //crAkelRange Range of highlighted characters. //crRichRange Range of highlighted characters (RichEdit offset). //hlp Highlighted information. // //Return Value // To continue processing, the callback function must return zero; to stop processing, it must return nonzero. TAEGetHighLightCallback = function(dwCookie: UINT_PTR; crAkelRange: PAECHARRANGE; crRichRange: PCHARRANGE64; hlp: PAEHLPAINT): DWORD; stdcall; type _AEGETHIGHLIGHT = record dwCookie: UINT_PTR; //[in] Specifies an application-defined value that the edit control passes to the AEGetHighLightCallback function specified by the lpCallback member. dwError: DWORD; //[out] Indicates the result of the callback function. lpCallback: TAEGetHighLightCallback; //[in] Pointer to an AEGetHighLightCallback function, which is an application-defined function that the control calls to pass highlighting information. crText: TAECHARRANGE; //[in] Range of characters to process. dwFlags: DWORD; //[in] See AEGHF_* defines. end; TAEGETHIGHLIGHT = _AEGETHIGHLIGHT; type _AENMHDR = record hwndFrom: HWND; idFrom: UINT_PTR; code: UINT; docFrom: AEHDOC; //Document handle. See AEM_CREATEDOCUMENT message. end; TAENMHDR = _AENMHDR; type _AENERRSPACE = record hdr: TAENMHDR; dwBytes: SIZE_T; //Number of bytes that cannot be allocated. end; TAENERRSPACE = _AENERRSPACE; type _AENFOCUS = record hdr: TAENMHDR; hWndChange: HWND; //AEN_SETFOCUS - handle to the window that has lost the keyboard focus. end; TAENFOCUS = _AENFOCUS; type _AENSCROLL = record hdr: TAENMHDR; nPosNew: INT_PTR; //Current scroll position. nPosOld: INT_PTR; //Previous scroll position. nPosMax: INT_PTR; //Maximum scroll position. end; TAENSCROLL = _AENSCROLL; type _AENSETRECT = record hdr: TAENMHDR; rcDraw: TRect; //Draw rectangle. rcEdit: TRect; //Edit client rectangle. end; TAENSETRECT = _AENSETRECT; type _AENPAINT = record hdr: TAENMHDR; dwType: DWORD; //See AEPNT_* defines. hDC: HDC; //Device context. ciMinDraw: TAECHARINDEX; //First index in line to paint. ciMaxDraw: TAECHARINDEX; //Last index in line to paint. nMinDrawOffset: INT_PTR; //First character in line to paint (RichEdit offset). nMaxDrawOffset: INT_PTR; //Last character in line to paint (RichEdit offset). ptMinDraw: TPoint; //Left upper corner in client coordinates of first character in line to paint. ptMaxDraw: TPoint; //Left upper corner in client coordinates of last character in line to paint. end; TAENPAINT = _AENPAINT; type _AENMAXTEXT = record hdr: TAENMHDR; dwTextLimit: UINT_PTR; //Current text limit. end; TAENMAXTEXT = _AENMAXTEXT; type _AENPROGRESS = record hdr: TAENMHDR; dwType: DWORD; //See AEPGS_* defines. dwTimeElapsed: DWORD; //Elapsed time since action was start. nCurrent: INT_PTR; //Characters processed. Equal to zero, if first message. nMaximum: INT_PTR; //Total number of characters. Equal to nCurrent member, if last message. end; TAENPROGRESS = _AENPROGRESS; type _AENMODIFY = record hdr: TAENMHDR; bModified: BOOL; //TRUE document state is set to modified, FALSE document state is set to unmodified. end; TAENMODIFY = _AENMODIFY; type _AENSELCHANGE = record hdr: TAENMHDR; crSel: TAECHARRANGE; //Current selection. ciCaret: TAECHARINDEX; //Caret character index position. dwType: DWORD; //See AESCT_* defines. bColumnSel: BOOL; //Column selection. crRichSel: TCHARRANGE64; //Current selection (RichEdit offset). end; TAENSELCHANGE = _AENSELCHANGE; type _AENTEXTCHANGE = record hdr: TAENMHDR; crSel: TAECHARRANGE; //Current selection. ciCaret: TAECHARINDEX; //Caret character index position. dwType: DWORD; //See AETCT_* defines. bColumnSel: BOOL; //Column selection. crRichSel: TCHARRANGE64; //Current selection (RichEdit offset). end; TAENTEXTCHANGE = _AENTEXTCHANGE; type _AENTEXTINSERT = record hdr: TAENMHDR; crSel: TAECHARRANGE; //Reserved. ciCaret: TAECHARINDEX; //Reserved. dwType: DWORD; //See AETCT_* defines. wpText: PWideChar; //Text to insert. dwTextLen: UINT_PTR; //Text length. nNewLine: Integer; //See AELB_* defines. bColumnSel: BOOL; //Column selection. dwInsertFlags: DWORD; //See AEINST_* defines. crAkelRange: TAECHARRANGE; //AEN_TEXTINSERTBEGIN - text insert position or AEN_TEXTINSERTEND - text range after insertion. crRichRange: TCHARRANGE64; //AEN_TEXTINSERTBEGIN - text insert position or AEN_TEXTINSERTEND - text range after insertion (RichEdit offset). end; TAENTEXTINSERT = _AENTEXTINSERT; type _AENTEXTDELETE = record hdr: TAENMHDR; crSel: TAECHARRANGE; //Reserved. ciCaret: TAECHARINDEX; //Reserved. dwType: DWORD; //See AETCT_* defines. bColumnSel: BOOL; //Column selection. dwDeleteFlags: DWORD; //See AEDELT_* defines. crAkelRange: TAECHARRANGE; //AEN_TEXTDELETEBEGIN - text delete range or AEN_TEXTDELETEEND - text range after deletion. crRichRange: TCHARRANGE64; //AEN_TEXTDELETEBEGIN - text delete range or AEN_TEXTDELETEEND - text range after deletion (RichEdit offset). end; TAENTEXTDELETE = _AENTEXTDELETE; type _AENPOINT = record hdr: TAENMHDR; dwType: DWORD; //See AEPTT_* defines. lpPoint: PAEPOINT; //Pointer to a AEPOINT structure. NULL if type is AEPTT_SETTEXT or AEPTT_STREAMIN. end; TAENPOINT = _AENPOINT; type _AENDROPFILES = record hdr: TAENMHDR; hDrop: HDROP; //Handle to the dropped files list (same as with WM_DROPFILES). ciChar: TAECHARINDEX; //Character index at which the dropped files would be inserted. end; TAENDROPFILES = _AENDROPFILES; type _AENDROPSOURCE = record hdr: TAENMHDR; nAction: Integer; //See AEDS_* defines. dwEffect: DWORD; //Cursor effect: DROPEFFECT_COPY, DROPEFFECT_MOVE or DROPEFFECT_NONE. dwDropResult: DWORD; //Drop cResult. Valid if nAction equal to AEDS_SOURCEEND or AEDS_SOURCEDONE. end; TAENDROPSOURCE = _AENDROPSOURCE; type _AENDROPTARGET = record hdr: TAENMHDR; nAction: Integer; //See AEDT_* defines. pt: TPoint; //Cursor position in screen coordinates. dwEffect: DWORD; //Cursor effect: DROPEFFECT_COPY, DROPEFFECT_MOVE or DROPEFFECT_NONE. end; TAENDROPTARGET = _AENDROPTARGET; type _AENLINK = record hdr: TAENMHDR; uMsg: UINT; //Mouse message: WM_LBUTTONDBLCLK, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_RBUTTONDBLCLK, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR. wParam: WPARAM; //First parameter of a message. lParam: LPARAM; //Second parameter of a message. crLink: TAECHARRANGE; //Range of characters which contain URL text. nVisitCount: Integer; //URL visit count. Variable must be incremented, if URL is opened. end; TAENLINK = _AENLINK; type _AENMARKER = record hdr: TAENMHDR; dwType: DWORD; //Column marker cType. dwPos: DWORD; //Column marker position. bMouse: BOOL; //Column marker position is changed with mouse. end; TAENMARKER = _AENMARKER; //// AkelEdit messages //Error notifications const AEN_ERRSPACE = (WM_USER + 1001); //0x7E9 //Window notifications const AEN_SETFOCUS = (WM_USER + 1026); //0x802 const AEN_KILLFOCUS = (WM_USER + 1027); //0x803 const AEN_HSCROLL = (WM_USER + 1028); //0x804 const AEN_VSCROLL = (WM_USER + 1029); //0x805 const AEN_SETRECT = (WM_USER + 1030); //0x806 const AEN_PAINT = (WM_USER + 1031); //0x807 //Text notifications const AEN_MAXTEXT = (WM_USER + 1050); //0x81A const AEN_PROGRESS = (WM_USER + 1051); //0x81B const AEN_MODIFY = (WM_USER + 1052); //0x81C const AEN_SELCHANGING = (WM_USER + 1053); //0x81D const AEN_SELCHANGED = (WM_USER + 1054); //0x81E const AEN_TEXTCHANGING = (WM_USER + 1055); //0x81F const AEN_TEXTINSERTBEGIN = (WM_USER + 1056); //0x820 const AEN_TEXTINSERTEND = (WM_USER + 1057); //0x821 const AEN_TEXTDELETEBEGIN = (WM_USER + 1058); //0x822 const AEN_TEXTDELETEEND = (WM_USER + 1059); //0x823 const AEN_TEXTCHANGED = (WM_USER + 1060); //0x824 const AEN_POINT = (WM_USER + 1061); //0x825 //Mouse notifications const AEN_DROPFILES = (WM_USER + 1076); //0x834 const AEN_DROPSOURCE = (WM_USER + 1077); //0x835 const AEN_DROPTARGET = (WM_USER + 1078); //0x836 const AEN_LINK = (WM_USER + 1079); //0x837 const AEN_MARKER = (WM_USER + 1080); //0x838 //RichEdit Unicode extension const EM_REPLACESELA = (WM_USER + 1901); const EM_REPLACESELW = (WM_USER + 1902); const EM_GETSELTEXTA = (WM_USER + 1905); const EM_GETSELTEXTW = (WM_USER + 1906); const EM_GETLINEA = (WM_USER + 1907); const EM_GETLINEW = (WM_USER + 1908); //RichEdit x64 extension const EM_GETSEL64 = (WM_USER + 1951); const EM_EXGETSEL64 = (WM_USER + 1952); const EM_EXSETSEL64 = (WM_USER + 1953); const EM_FINDTEXTEX64 = (WM_USER + 1954); const EM_FINDTEXTEX64A = (WM_USER + 1955); const EM_FINDTEXTEX64W = (WM_USER + 1956); const EM_GETTEXTRANGE64 = (WM_USER + 1961); const EM_GETTEXTRANGE64A = (WM_USER + 1962); const EM_GETTEXTRANGE64W = (WM_USER + 1963); const EM_GETTEXTEX64 = (WM_USER + 1964); //Text retrieval and modification const AEM_EXSETTEXTA = (WM_USER + 1999); const AEM_EXSETTEXTW = (WM_USER + 2000); const AEM_SETTEXTA = (WM_USER + 2001); const AEM_SETTEXTW = (WM_USER + 2002); const AEM_APPENDTEXTA = (WM_USER + 2003); const AEM_APPENDTEXTW = (WM_USER + 2004); const AEM_REPLACESELA = (WM_USER + 2005); const AEM_REPLACESELW = (WM_USER + 2006); const AEM_GETTEXTRANGEA = (WM_USER + 2007); const AEM_GETTEXTRANGEW = (WM_USER + 2008); const AEM_STREAMIN = (WM_USER + 2009); const AEM_STREAMOUT = (WM_USER + 2010); const AEM_CANPASTE = (WM_USER + 2011); const AEM_PASTE = (WM_USER + 2012); const AEM_CUT = (WM_USER + 2013); const AEM_COPY = (WM_USER + 2014); const AEM_CHECKCODEPAGE = (WM_USER + 2015); const AEM_FINDTEXTA = (WM_USER + 2016); const AEM_FINDTEXTW = (WM_USER + 2017); const AEM_ISMATCHA = (WM_USER + 2018); const AEM_ISMATCHW = (WM_USER + 2019); const AEM_KEYDOWN = (WM_USER + 2020); const AEM_INSERTCHAR = (WM_USER + 2021); const AEM_CHARAT = (WM_USER + 2022); const AEM_INPUTLANGUAGE = (WM_USER + 2023); const AEM_DRAGDROP = (WM_USER + 2024); //Undo and Redo const AEM_CANUNDO = (WM_USER + 2051); const AEM_CANREDO = (WM_USER + 2052); const AEM_UNDO = (WM_USER + 2053); const AEM_REDO = (WM_USER + 2054); const AEM_EMPTYUNDOBUFFER = (WM_USER + 2055); const AEM_STOPGROUPTYPING = (WM_USER + 2056); const AEM_BEGINUNDOACTION = (WM_USER + 2057); const AEM_ENDUNDOACTION = (WM_USER + 2058); const AEM_LOCKCOLLECTUNDO = (WM_USER + 2059); const AEM_GETUNDOLIMIT = (WM_USER + 2060); const AEM_SETUNDOLIMIT = (WM_USER + 2061); const AEM_GETMODIFY = (WM_USER + 2062); const AEM_SETMODIFY = (WM_USER + 2063); const AEM_UNDOBUFFERSIZE = (WM_USER + 2064); const AEM_ISRANGEMODIFIED = (WM_USER + 2065); const AEM_DETACHUNDO = (WM_USER + 2066); const AEM_ATTACHUNDO = (WM_USER + 2067); //Text coordinates const AEM_EXGETSEL = (WM_USER + 2099); const AEM_EXSETSEL = (WM_USER + 2100); const AEM_GETSEL = (WM_USER + 2101); const AEM_SETSEL = (WM_USER + 2102); const AEM_GETCOLUMNSEL = (WM_USER + 2103); const AEM_UPDATESEL = (WM_USER + 2104); const AEM_GETLINENUMBER = (WM_USER + 2105); const AEM_GETINDEX = (WM_USER + 2106); const AEM_GETLINEINDEX = (WM_USER + 2107); const AEM_INDEXUPDATE = (WM_USER + 2108); const AEM_INDEXCOMPARE = (WM_USER + 2109); const AEM_INDEXSUBTRACT = (WM_USER + 2110); const AEM_INDEXOFFSET = (WM_USER + 2111); const AEM_INDEXTORICHOFFSET = (WM_USER + 2112); const AEM_RICHOFFSETTOINDEX = (WM_USER + 2113); const AEM_GETRICHOFFSET = (WM_USER + 2114); const AEM_GETWRAPLINE = (WM_USER + 2118); const AEM_GETUNWRAPLINE = (WM_USER + 2119); const AEM_GETNEXTBREAK = (WM_USER + 2120); const AEM_GETPREVBREAK = (WM_USER + 2121); const AEM_ISDELIMITER = (WM_USER + 2122); const AEM_INDEXTOCOLUMN = (WM_USER + 2123); const AEM_COLUMNTOINDEX = (WM_USER + 2124); const AEM_INDEXINURL = (WM_USER + 2125); const AEM_ADDPOINT = (WM_USER + 2141); const AEM_DELPOINT = (WM_USER + 2142); const AEM_GETPOINTSTACK = (WM_USER + 2143); //Screen coordinates const AEM_CHARFROMGLOBALPOS = (WM_USER + 2149); const AEM_GLOBALPOSFROMCHAR = (WM_USER + 2150); const AEM_CHARFROMPOS = (WM_USER + 2151); const AEM_POSFROMCHAR = (WM_USER + 2152); const AEM_GETRECT = (WM_USER + 2153); const AEM_SETRECT = (WM_USER + 2154); const AEM_GETSCROLLPOS = (WM_USER + 2155); const AEM_SETSCROLLPOS = (WM_USER + 2156); const AEM_SCROLL = (WM_USER + 2157); const AEM_LINESCROLL = (WM_USER + 2158); const AEM_SCROLLTOPOINT = (WM_USER + 2159); const AEM_LOCKSCROLL = (WM_USER + 2161); const AEM_GETCHARSIZE = (WM_USER + 2164); const AEM_GETSTRWIDTH = (WM_USER + 2165); const AEM_GETCARETPOS = (WM_USER + 2166); const AEM_GETCARETHORZINDENT = (WM_USER + 2167); const AEM_SETCARETHORZINDENT = (WM_USER + 2168); const AEM_CONVERTPOINT = (WM_USER + 2169); const AEM_POINTONMARGIN = (WM_USER + 2170); const AEM_POINTONSELECTION = (WM_USER + 2171); const AEM_POINTONURL = (WM_USER + 2172); const AEM_LINEFROMVPOS = (WM_USER + 2173); const AEM_VPOSFROMLINE = (WM_USER + 2174); const AEM_GETMOUSESTATE = (WM_USER + 2175); //Options const AEM_CONTROLCLASS = (WM_USER + 2199); const AEM_CONTROLVERSION = (WM_USER + 2200); const AEM_GETEVENTMASK = (WM_USER + 2201); const AEM_SETEVENTMASK = (WM_USER + 2202); const AEM_GETOPTIONS = (WM_USER + 2203); const AEM_SETOPTIONS = (WM_USER + 2204); const AEM_GETNEWLINE = (WM_USER + 2205); const AEM_SETNEWLINE = (WM_USER + 2206); const AEM_GETCOLORS = (WM_USER + 2207); const AEM_SETCOLORS = (WM_USER + 2208); const AEM_EXGETOPTIONS = (WM_USER + 2209); const AEM_EXSETOPTIONS = (WM_USER + 2210); const AEM_GETCARETWIDTH = (WM_USER + 2213); const AEM_SETCARETWIDTH = (WM_USER + 2214); const AEM_GETTABSTOP = (WM_USER + 2215); const AEM_SETTABSTOP = (WM_USER + 2216); const AEM_GETWORDWRAP = (WM_USER + 2217); const AEM_SETWORDWRAP = (WM_USER + 2218); const AEM_GETWORDDELIMITERS = (WM_USER + 2219); const AEM_SETWORDDELIMITERS = (WM_USER + 2220); const AEM_GETWRAPDELIMITERS = (WM_USER + 2221); const AEM_SETWRAPDELIMITERS = (WM_USER + 2222); const AEM_GETURLLEFTDELIMITERS = (WM_USER + 2223); const AEM_SETURLLEFTDELIMITERS = (WM_USER + 2224); const AEM_GETURLRIGHTDELIMITERS = (WM_USER + 2225); const AEM_SETURLRIGHTDELIMITERS = (WM_USER + 2226); const AEM_GETURLPREFIXES = (WM_USER + 2227); const AEM_SETURLPREFIXES = (WM_USER + 2228); const AEM_GETURLMAXLENGTH = (WM_USER + 2229); const AEM_SETURLMAXLENGTH = (WM_USER + 2230); const AEM_GETWORDBREAK = (WM_USER + 2231); const AEM_SETWORDBREAK = (WM_USER + 2232); const AEM_GETMARKER = (WM_USER + 2233); const AEM_SETMARKER = (WM_USER + 2234); const AEM_GETLINEGAP = (WM_USER + 2235); const AEM_SETLINEGAP = (WM_USER + 2236); const AEM_GETTEXTLIMIT = (WM_USER + 2237); const AEM_SETTEXTLIMIT = (WM_USER + 2238); const AEM_GETFONT = (WM_USER + 2239); const AEM_GETALTLINE = (WM_USER + 2240); const AEM_SETALTLINE = (WM_USER + 2241); const AEM_GETCHARCOLORS = (WM_USER + 2242); const AEM_SCROLLCARETOPTIONS = (WM_USER + 2243); //Draw const AEM_SHOWSCROLLBAR = (WM_USER + 2351); const AEM_UPDATESCROLLBAR = (WM_USER + 2352); const AEM_UPDATECARET = (WM_USER + 2353); const AEM_UPDATESIZE = (WM_USER + 2354); const AEM_LOCKUPDATE = (WM_USER + 2355); const AEM_LOCKERASERECT = (WM_USER + 2356); const AEM_GETERASERECT = (WM_USER + 2357); const AEM_SETERASERECT = (WM_USER + 2358); const AEM_HIDESELECTION = (WM_USER + 2361); const AEM_REDRAWLINERANGE = (WM_USER + 2362); const AEM_GETBACKGROUNDIMAGE = (WM_USER + 2366); const AEM_SETBACKGROUNDIMAGE = (WM_USER + 2367); //Folding const AEM_GETFOLDSTACK = (WM_USER + 2381); const AEM_GETFOLDCOUNT = (WM_USER + 2382); const AEM_ADDFOLD = (WM_USER + 2383); const AEM_DELETEFOLD = (WM_USER + 2384); const AEM_ISFOLDVALID = (WM_USER + 2385); const AEM_FINDFOLD = (WM_USER + 2386); const AEM_NEXTFOLD = (WM_USER + 2387); const AEM_PREVFOLD = (WM_USER + 2388); const AEM_ISLINECOLLAPSED = (WM_USER + 2389); const AEM_COLLAPSELINE = (WM_USER + 2390); const AEM_COLLAPSEFOLD = (WM_USER + 2391); const AEM_UPDATEFOLD = (WM_USER + 2392); //Document const AEM_CREATEDOCUMENT = (WM_USER + 2401); const AEM_DELETEDOCUMENT = (WM_USER + 2402); const AEM_GETDOCUMENT = (WM_USER + 2403); const AEM_SETDOCUMENT = (WM_USER + 2404); const AEM_GETDOCUMENTPROC = (WM_USER + 2405); const AEM_GETDOCUMENTWINDOW = (WM_USER + 2406); const AEM_SENDMESSAGE = (WM_USER + 2407); //Clone const AEM_ADDCLONE = (WM_USER + 2421); const AEM_DELCLONE = (WM_USER + 2422); const AEM_GETMASTER = (WM_USER + 2423); const AEM_GETCLONE = (WM_USER + 2424); //Print const AEM_STARTPRINTDOC = (WM_USER + 2451); const AEM_PRINTPAGE = (WM_USER + 2452); const AEM_ENDPRINTDOC = (WM_USER + 2453); //Highlight const AEM_HLCREATETHEMEA = (WM_USER + 2501); const AEM_HLCREATETHEMEW = (WM_USER + 2502); const AEM_HLGETTHEMEA = (WM_USER + 2503); const AEM_HLGETTHEMEW = (WM_USER + 2504); const AEM_HLGETTHEMENAMEA = (WM_USER + 2505); const AEM_HLGETTHEMENAMEW = (WM_USER + 2506); const AEM_HLGETTHEMESTACK = (WM_USER + 2507); const AEM_HLTHEMEEXISTS = (WM_USER + 2508); const AEM_HLSETTHEME = (WM_USER + 2509); const AEM_HLDELETETHEME = (WM_USER + 2510); const AEM_HLDELETETHEMEALL = (WM_USER + 2511); const AEM_HLADDDELIMITERA = (WM_USER + 2521); const AEM_HLADDDELIMITERW = (WM_USER + 2522); const AEM_HLDELETEDELIMITER = (WM_USER + 2523); const AEM_HLADDWORDA = (WM_USER + 2531); const AEM_HLADDWORDW = (WM_USER + 2532); const AEM_HLDELETEWORD = (WM_USER + 2533); const AEM_HLADDQUOTEA = (WM_USER + 2541); const AEM_HLADDQUOTEW = (WM_USER + 2542); const AEM_HLDELETEQUOTE = (WM_USER + 2543); const AEM_HLADDMARKTEXTA = (WM_USER + 2551); const AEM_HLADDMARKTEXTW = (WM_USER + 2552); const AEM_HLDELETEMARKTEXT = (WM_USER + 2553); const AEM_HLADDMARKRANGE = (WM_USER + 2561); const AEM_HLDELETEMARKRANGE = (WM_USER + 2562); const AEM_HLGETHIGHLIGHT = (WM_USER + 2571); const AEM_HLGETOPTIONS = (WM_USER + 2581); const AEM_HLSETOPTIONS = (WM_USER + 2582); //// RichEdit messages (* //// RichEdit messages AkelEdit can emulate RichEdit 3.0 and support the following messages: EN_CHANGE EN_DRAGDROPDONE EN_DROPFILES EN_ERRSPACE EN_HSCROLL EN_KILLFOCUS EN_LINK EN_MAXTEXT EN_MSGFILTER EN_SELCHANGE EN_SETFOCUS EN_VSCROLL EM_AUTOURLDETECT EM_CANPASTE EM_CANREDO EM_CANUNDO EM_CHARFROMPOS EM_EMPTYUNDOBUFFER EM_EXGETSEL EM_EXLIMITTEXT EM_EXLINEFROMCHAR EM_EXSETSEL EM_FINDTEXT EM_FINDTEXTEX EM_FINDTEXTEXW EM_FINDTEXTW EM_FINDWORDBREAK EM_GETAUTOURLDETECT EM_GETEVENTMASK EM_GETFIRSTVISIBLELINE EM_GETLIMITTEXT EM_GETLINE EM_GETLINECOUNT EM_GETMARGINS EM_GETMODIFY EM_GETOPTIONS EM_GETRECT EM_GETSCROLLPOS EM_GETSEL EM_GETSELTEXT EM_GETTEXTEX EM_GETTEXTLENGTHEX EM_GETTEXTRANGE EM_GETTHUMB EM_HIDESELECTION EM_LIMITTEXT EM_LINEFROMCHAR EM_LINEINDEX EM_LINELENGTH EM_LINESCROLL EM_POSFROMCHAR EM_REDO EM_REPLACESEL EM_SCROLL EM_SCROLLCARET EM_SELECTIONTYPE EM_SETBKGNDCOLOR EM_SETEVENTMASK EM_SETLIMITTEXT EM_SETMARGINS EM_SETMODIFY EM_SETOPTIONS EM_SETREADONLY EM_SETRECT EM_SETRECTNP EM_SETSCROLLPOS EM_SETSEL EM_SETTEXTEX EM_SETUNDOLIMIT EM_SHOWSCROLLBAR EM_STOPGROUPTYPING EM_STREAMIN EM_STREAMOUT EM_UNDO Additional messages for Unicode support: EM_REPLACESELA EM_REPLACESELW EM_GETTEXTRANGEA EM_GETTEXTRANGEW EM_GETSELTEXTA EM_GETSELTEXTW EM_GETLINEA EM_GETLINEW Additional messages for x64 support: EM_GETSEL64 EM_EXGETSEL64 EM_EXSETSEL64 EM_FINDTEXTEX64 EM_FINDTEXTEX64A EM_FINDTEXTEX64W EM_GETTEXTRANGE64 EM_GETTEXTRANGE64A EM_GETTEXTRANGE64W EM_GETTEXTEX64 *) // Messages manual: look AkelEdit.h //// UNICODE define {$ifndef UNICODE} const AES_AKELEDIT = AES_AKELEDITA; AES_RICHEDIT20 = AES_RICHEDIT20A; type TTEXTRANGE64 = TTEXTRANGE64A; TFINDTEXTEX64 = TFINDTEXTEX64A; TAEAPPENDTEXT = TAEAPPENDTEXTA; TAEREPLACESEL = TAEREPLACESELA; TAETEXTRANGE = TAETEXTRANGEA; TAEFINDTEXT = TAEFINDTEXTA; TAEDELIMITEM = TAEDELIMITEMA; TAEWORDITEM = TAEWORDITEMA; TAEQUOTEITEM = TAEQUOTEITEMA; TAEMARKTEXTITEM = TAEMARKTEXTITEMA; const AEM_SETTEXT = AEM_SETTEXTA; AEM_APPENDTEXT = AEM_APPENDTEXTA; AEM_REPLACESEL = AEM_REPLACESELA; AEM_GETTEXTRANGE = AEM_GETTEXTRANGEA; AEM_FINDTEXT = AEM_FINDTEXTA; AEM_ISMATCH = AEM_ISMATCHA; AEM_HLCREATETHEME = AEM_HLCREATETHEMEA; AEM_HLGETTHEME = AEM_HLGETTHEMEA; AEM_HLGETTHEMENAME = AEM_HLGETTHEMENAMEA; AEM_HLADDDELIMITER = AEM_HLADDDELIMITERA; AEM_HLADDWORD = AEM_HLADDWORDA; AEM_HLADDQUOTE = AEM_HLADDQUOTEA; AEM_HLADDMARKTEXT = AEM_HLADDMARKTEXTA; {$else} const AES_AKELEDIT = AES_AKELEDITW; AES_RICHEDIT20 = AES_RICHEDIT20W; type TTEXTRANGE64 = TTEXTRANGE64W; TFINDTEXTEX64 = TFINDTEXTEX64W; TAEAPPENDTEXT = TAEAPPENDTEXTW; TAEREPLACESEL = TAEREPLACESELW; TAETEXTRANGE = TAETEXTRANGEW; TAEFINDTEXT = TAEFINDTEXTW; TAEDELIMITEM = TAEDELIMITEMW; TAEWORDITEM = TAEWORDITEMW; TAEQUOTEITEM = TAEQUOTEITEMW; TAEMARKTEXTITEM = TAEMARKTEXTITEMW; const AEM_SETTEXT = AEM_SETTEXTW; AEM_APPENDTEXT = AEM_APPENDTEXTW; AEM_REPLACESEL = AEM_REPLACESELW; AEM_GETTEXTRANGE = AEM_GETTEXTRANGEW; AEM_FINDTEXT = AEM_FINDTEXTW; AEM_ISMATCH = AEM_ISMATCHW; AEM_HLCREATETHEME = AEM_HLCREATETHEMEW; AEM_HLGETTHEME = AEM_HLGETTHEMEW; AEM_HLGETTHEMENAME = AEM_HLGETTHEMENAMEW; AEM_HLADDDELIMITER = AEM_HLADDDELIMITERW; AEM_HLADDWORD = AEM_HLADDWORDW; AEM_HLADDQUOTE = AEM_HLADDQUOTEW; AEM_HLADDMARKTEXT = AEM_HLADDMARKTEXTW; {$endif} // Fr0sT: inlines available since D2006 {$IF CompilerVersion >= 16} {$DEFINE INLINES} {$IFEND} function AEC_IsSurrogate(c: WideChar): Boolean; {$IFDEF INLINES}inline;{$ENDIF} function AEC_IsHighSurrogate(c: WideChar): Boolean; {$IFDEF INLINES}inline;{$ENDIF} function AEC_IsLowSurrogate(c: WideChar): Boolean; {$IFDEF INLINES}inline;{$ENDIF} function AEC_ScalarFromSurrogate(high, low: WideChar): UCS4Char; function AEC_HighSurrogateFromScalar(c: UCS4Char): WideChar; function AEC_LowSurrogateFromScalar(c: UCS4Char): WideChar; function AEC_CopyChar(wszTarget: PWideChar; dwTargetSize: DWORD; const wpSource: PWideChar): Integer; function AEC_IndexInc(var ciChar: TAECHARINDEX): Integer; function AEC_IndexDec(var ciChar: TAECHARINDEX): Integer; function AEC_IndexLen(const ciChar: TAECHARINDEX): Integer; function AEC_IndexCompare(const ciChar1, ciChar2: TAECHARINDEX): Integer; function AEC_IndexCompareEx(const ciChar1, ciChar2: TAECHARINDEX): Integer; function AEC_NextLine(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_PrevLine(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_NextLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_PrevLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_NextChar(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_PrevChar(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_NextCharEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_PrevCharEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_NextCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_PrevCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_NextCharInLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_PrevCharInLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; function AEC_ValidCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; function AEC_WrapLineBegin(var ciChar: TAECHARINDEX): Integer; function AEC_WrapLineEnd(var ciChar: TAECHARINDEX): Integer; function AEC_WrapLineBeginEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): Integer; function AEC_WrapLineEndEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): Integer; function AEC_CharAtIndex(var ciChar: TAECHARINDEX): Integer; function AEC_IsCharInSelection(var ciChar: TAECHARINDEX): Boolean; function AEC_IsFirstCharInLine(var ciChar: TAECHARINDEX): Boolean; function AEC_IsLastCharInLine(var ciChar: TAECHARINDEX): Boolean; function AEC_IsFirstCharInFile(var ciChar: TAECHARINDEX): Boolean; function AEC_IsLastCharInFile(var ciChar: TAECHARINDEX): Boolean; function AEC_NextFold(var lpFold: PAEFOLD; bRecursive: Boolean): PAEFOLD; function AEC_PrevFold(var lpFold: PAEFOLD; bRecursive: Boolean): PAEFOLD; implementation //// AkelEdit functions function AEC_IsSurrogate(c: WideChar): Boolean; begin Result := (c >= #$D800) and (c <= #$DFFF); end; function AEC_IsHighSurrogate(c: WideChar): Boolean; begin Result := (c >= #$D800) and (c <= #$DBFF); end; function AEC_IsLowSurrogate(c: WideChar): Boolean; begin Result := (c >= #$DC00) and (c <= #$DFFF); end; function AEC_ScalarFromSurrogate(high, low: WideChar): UCS4Char; begin // ((((high) - $D800) * $400) + ((low) - $DC00) + $10000) Result := (Word(high) - $D800)*$400 + (Word(low) - $DC00) + $10000; end; function AEC_HighSurrogateFromScalar(c: UCS4Char): WideChar; begin Result := WideChar((c - $10000) div $400 + $D800); end; function AEC_LowSurrogateFromScalar(c: UCS4Char): WideChar; begin Result := WideChar((c - $10000) mod $400 + $DC00); end; function AEC_CopyChar(wszTarget: PWideChar; dwTargetSize: DWORD; const wpSource: PWideChar): Integer; begin Result := 0; if AEC_IsSurrogate(wpSource^) then begin if dwTargetSize >= 2 then begin if AEC_IsHighSurrogate(wpSource^) and AEC_IsLowSurrogate((wpSource + 1)^) then begin if wszTarget <> nil then begin wszTarget^ := wpSource^; (wszTarget + 1)^ := (wpSource + 1)^; end; Result := 2; end; end; end else begin if wszTarget <> nil then wszTarget^ := wpSource^; Result := 1; end; end; function AEC_IndexInc(var ciChar: TAECHARINDEX): Integer; begin Result := 1; if (ciChar.nCharInLine >= 0) and (ciChar.nCharInLine + 1 < ciChar.lpLine.nLineLen) then if AEC_IsHighSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine]) and AEC_IsLowSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine + 1]) then Result := 2; Inc(ciChar.nCharInLine, Result); end; function AEC_IndexDec(var ciChar: TAECHARINDEX): Integer; begin Result := 1; if (ciChar.nCharInLine - 2 >= 0) and (ciChar.nCharInLine - 1 < ciChar.lpLine.nLineLen) then if AEC_IsLowSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine - 1]) and AEC_IsHighSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine - 2]) then Result := 2; Dec(ciChar.nCharInLine, Result); end; function AEC_IndexLen(const ciChar: TAECHARINDEX): Integer; begin Result := 1; if (ciChar.nCharInLine >= 0) and (ciChar.nCharInLine + 1 < ciChar.lpLine.nLineLen) then if AEC_IsHighSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine]) and AEC_IsLowSurrogate(ciChar.lpLine.wpLine[ciChar.nCharInLine + 1]) then Result := 2; end; function AEC_IndexCompare(const ciChar1, ciChar2: TAECHARINDEX): Integer; begin if (ciChar1.nLine = ciChar2.nLine) and (ciChar1.nCharInLine = ciChar2.nCharInLine) then Result := 0 else if (ciChar1.nLine < ciChar2.nLine) or ((ciChar1.nLine = ciChar2.nLine) and (ciChar1.nCharInLine < ciChar2.nCharInLine)) then Result := -1 else Result := 1; end; function AEC_IndexCompareEx(const ciChar1, ciChar2: TAECHARINDEX): Integer; begin if ( (ciChar1.nLine = ciChar2.nLine) and (ciChar1.nCharInLine = ciChar2.nCharInLine) ) or ( (ciChar1.lpLine <> nil) and (ciChar2.lpLine <> nil) and ( ( (ciChar1.lpLine.next = ciChar2.lpLine) and (ciChar1.lpLine.nLineBreak = AELB_WRAP) and (ciChar1.nCharInLine = ciChar1.lpLine.nLineLen) and (ciChar2.nCharInLine = 0) ) or ( (ciChar2.lpLine.next = ciChar1.lpLine) and (ciChar2.lpLine.nLineBreak = AELB_WRAP) and (ciChar2.nCharInLine = ciChar2.lpLine.nLineLen) and (ciChar1.nCharInLine = 0) ) )) then Result := 0 else if (ciChar1.nLine < ciChar2.nLine) or ( (ciChar1.nLine = ciChar2.nLine) and (ciChar1.nCharInLine < ciChar2.nCharInLine) ) then Result := -1 else Result := 1; end; function AEC_NextLine(var ciChar: TAECHARINDEX): PAELINEDATA; begin if ciChar.lpLine <> nil then begin Inc(ciChar.nLine); ciChar.lpLine := ciChar.lpLine.next; ciChar.nCharInLine :=0; end; Result := ciChar.lpLine; end; function AEC_PrevLine(var ciChar: TAECHARINDEX): PAELINEDATA; begin if ciChar.lpLine <> nil then begin Dec(ciChar.nLine); ciChar.lpLine := ciChar.lpLine.prev; if ciChar.lpLine <> nil then ciChar.nCharInLine := ciChar.lpLine.nLineLen else ciChar.nCharInLine := 0; end; Result := ciChar.lpLine; end; function AEC_NextLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_NextLine(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_PrevLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_PrevLine(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_NextChar(var ciChar: TAECHARINDEX): PAELINEDATA; begin AEC_IndexInc(ciChar); if ciChar.nCharInLine >= ciChar.lpLine.nLineLen then if (ciChar.nCharInLine > ciChar.lpLine.nLineLen) or (ciChar.lpLine.nLineBreak = AELB_WRAP) then AEC_NextLine(ciChar); Result := ciChar.lpLine; end; function AEC_PrevChar(var ciChar: TAECHARINDEX): PAELINEDATA; begin AEC_IndexDec(ciChar); if ciChar.nCharInLine < 0 then if AEC_PrevLine(ciChar) <> nil then if ciChar.lpLine.nLineBreak = AELB_WRAP then AEC_IndexDec(ciChar); Result := ciChar.lpLine; end; function AEC_NextCharEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_NextChar(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_PrevCharEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_PrevChar(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_NextCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; begin AEC_IndexInc(ciChar); if ciChar.nCharInLine >= ciChar.lpLine.nLineLen then if ciChar.lpLine.nLineBreak = AELB_WRAP then AEC_NextLine(ciChar) else begin Result := nil; Exit; end; Result := ciChar.lpLine; end; function AEC_PrevCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; begin if ciChar.nCharInLine = 0 then if (ciChar.lpLine.prev = nil) or (ciChar.lpLine.prev.nLineBreak <> AELB_WRAP) then begin Result := nil; Exit; end; AEC_PrevChar(ciChar); Result := ciChar.lpLine; end; function AEC_NextCharInLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_NextCharInLine(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_PrevCharInLineEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): PAELINEDATA; var ciTmp: TAECHARINDEX; begin ciTmp := ciIn; if AEC_PrevCharInLine(ciTmp) <> nil then begin ciOut := ciTmp; Result := ciOut.lpLine; end else begin ciOut := ciIn; Result := nil; end end; function AEC_ValidCharInLine(var ciChar: TAECHARINDEX): PAELINEDATA; begin if ciChar.nCharInLine >= ciChar.lpLine.nLineLen then if ciChar.lpLine.nLineBreak = AELB_WRAP then AEC_NextLine(ciChar) else ciChar.nCharInLine := ciChar.lpLine.nLineLen else if ciChar.nCharInLine < 0 then ciChar.nCharInLine := 0; Result := ciChar.lpLine; end; function AEC_WrapLineBegin(var ciChar: TAECHARINDEX): Integer; begin Result := ciChar.nCharInLine; if ciChar.lpLine <> nil then begin while ciChar.lpLine.prev <> nil do begin if ciChar.lpLine.prev.nLineBreak <> AELB_WRAP then Break; Dec(ciChar.nLine); ciChar.lpLine := ciChar.lpLine.prev; Inc(Result, ciChar.lpLine.nLineLen); end; end; ciChar.nCharInLine := 0; end; function AEC_WrapLineEnd(var ciChar: TAECHARINDEX): Integer; begin Result := ciChar.lpLine.nLineLen - ciChar.nCharInLine; while ciChar.lpLine <> nil do begin if ciChar.lpLine.nLineBreak <> AELB_WRAP then Break; Inc(ciChar.nLine); ciChar.lpLine := ciChar.lpLine.next; Inc(Result, ciChar.lpLine.nLineLen); end; ciChar.nCharInLine := ciChar.lpLine.nLineLen; end; function AEC_WrapLineBeginEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): Integer; begin ciOut := ciIn; Result := AEC_WrapLineBegin(ciOut); end; function AEC_WrapLineEndEx(const ciIn: TAECHARINDEX; var ciOut: TAECHARINDEX): Integer; begin ciOut := ciIn; Result := AEC_WrapLineEnd(ciOut); end; // Fr0sT: Returns WideChar if >= 0 and line break type if < 0 function AEC_CharAtIndex(var ciChar: TAECHARINDEX): Integer; begin if ciChar.nCharInLine >= ciChar.lpLine.nLineLen then if ciChar.lpLine.nLineBreak = AELB_WRAP then begin Result := Integer(ciChar.lpLine.next.wpLine^); if AEC_IsHighSurrogate(WideChar(Result)) then Result := AEC_ScalarFromSurrogate(WideChar(Result), (ciChar.lpLine.next.wpLine + 1)^); Exit; end else Result := -ciChar.lpLine.nLineBreak else begin Result := Integer( (ciChar.lpLine.wpLine + ciChar.nCharInLine)^ ); if AEC_IsHighSurrogate(WideChar(Result)) then Result := AEC_ScalarFromSurrogate(WideChar(Result), (ciChar.lpLine.next.wpLine + ciChar.nCharInLine + 1)^); Exit; end; end; function AEC_IsCharInSelection(var ciChar: TAECHARINDEX): Boolean; begin Result := (ciChar.lpLine.nSelStart <= ciChar.nCharInLine) and (ciChar.nCharInLine < ciChar.lpLine.nSelEnd); end; function AEC_IsFirstCharInLine(var ciChar: TAECHARINDEX): Boolean; begin Result := (ciChar.nCharInLine = 0) and ((ciChar.lpLine.prev <> nil) or (ciChar.lpLine.prev.nLineBreak <> AELB_WRAP)); end; function AEC_IsLastCharInLine(var ciChar: TAECHARINDEX): Boolean; begin Result := (ciChar.nCharInLine = ciChar.lpLine.nLineLen) and (ciChar.lpLine.nLineBreak <> AELB_WRAP); end; function AEC_IsFirstCharInFile(var ciChar: TAECHARINDEX): Boolean; begin Result := (ciChar.nCharInLine = 0) and (ciChar.lpLine.prev <> nil); end; function AEC_IsLastCharInFile(var ciChar: TAECHARINDEX): Boolean; begin Result := (ciChar.nCharInLine = ciChar.lpLine.nLineLen) and (ciChar.lpLine.next <> nil); end; function AEC_NextFold(var lpFold: PAEFOLD; bRecursive: Boolean): PAEFOLD; begin if lpFold <> nil then begin if bRecursive then if lpFold.firstChild <> nil then begin Result := lpFold.firstChild; Exit; end; repeat if lpFold.next <> nil then begin Result := lpFold.next; Exit; end; lpFold := lpFold.parent; until lpFold = nil; end; Result := lpFold; end; function AEC_PrevFold(var lpFold: PAEFOLD; bRecursive: Boolean): PAEFOLD; begin if lpFold <> nil then begin if bRecursive then if lpFold.lastChild <> nil then begin Result := lpFold.lastChild; Exit; end; repeat if lpFold.prev <> nil then begin Result := lpFold.prev; Exit; end; lpFold := lpFold.parent; until lpFold = nil; end; Result := lpFold; end; end.
unit pangoft2; interface uses glib, freetypelib, fontconfiglib, pangolib, pangoft2lib, pango; type IPangoFcFontMap = interface; IPangoFT2FontMap = interface; IPangoFcFont = interface; IPangoFcDecoder = interface; IPangoOTInfo = interface; IPangoOTRuleset = interface; IPangoOTBuffer = interface; IPangoFcFontMap = interface(IPangoFontMap) ['{0D7214F7-61C5-4F90-9B2C-23B2057D0DE8}'] procedure Shutdown; procedure CacheClear; procedure AddDecoderFindFunc(findfunc: PangoFcDecoderFindFunc; userData: Pointer; dnotify: GDestroyNotify); end; IPangoFT2FontMap = interface(IPangoFcFontMap) ['{EAFA8AC0-5463-4176-B1B1-EAF01497DC44}'] procedure SetResolution(dpiX, dpiY: double); procedure SetDefaultSubstitute(func: PangoFT2SubstituteFunc; data: Pointer; notify: GDestroyNotify); procedure SubstituteChanged; end; IPangoFcFont = interface(IPangoFont) ['{A2DEF8A8-3506-421A-A73D-36015AD9F9F5}'] function HasChar(wc: WideChar): Boolean; function GetGlyph(wc: WideChar): Cardinal; function GetUnknownGlyph(wc: WideChar): PangoGlyph; procedure KernGlyphs(glyphs: IPangoGlyphString); function LockFace: FT_Face; procedure UnlockFace; function NewOtBuffer: IPangoOTBuffer; end; IPangoFcDecoder = interface(IGObject) ['{F00DBC04-7251-4A9F-8A98-041A3E95AFB5}'] function GetCharset(fcfont: IPangoFcFont): PFcCharSet; function GetGlyph(fcfont: IPangoFcFont; wc: Cardinal): PangoGlyph; end; IPangoOTInfo = interface(IGObject) ['{63056577-1FBC-4BF5-9E90-E8818749DBD3}'] function FindScript(tableType: PangoOTTableType; scriptTag: PangoOTTag; scriptIndex: PCardinal): Boolean; function FindLanguage(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag; languageIndex, requiredFeatureIndex: PCardinal): Boolean; function FindFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; scriptIndex, languageIndex: Cardinal; featureIndex: PCardinal): Boolean; function ListScripts(tableType: PangoOTTableType): PPangoOTTag; function ListLanguages(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag): PPangoOTTag; function ListFeatures(tableType: PangoOTTableType; tag: PangoOTTag; scriptIndex, languageIndex: Cardinal): PPangoOTTag; function GetRulesetForDescription(desc: PPangoOTRulesetDescription): IPangoOTRuleset; function NewRuleset: IPangoOTRuleset; function NewRulesetFor(script: PangoScript; language: PPangoLanguage): IPangoOTRuleset; function NewRulesetFromDescription(desc: PPangoOTRulesetDescription): IPangoOTRuleset; end; IPangoOTRuleset = interface(IGObject) ['{27E3FBC4-2477-4E6F-9915-ACE74BE81778}'] procedure AddFeature(tableType: PangoOTTableType; featureIndex, propertyBit: Cardinal); function MaybeAddFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; propertyBit: Cardinal): Boolean; function MaybeAddFeatures(tableType: PangoOTTableType; features: PPangoOTFeatureMap; nFeatures: Cardinal): Cardinal; function GetFeatureCount(nGsubFeatures, nGposFeatures: PCardinal): Cardinal; procedure Substitute(buffer: IPangoOTBuffer); procedure Position(buffer: IPangoOTBuffer); end; IPangoOTBuffer = interface ['{A5C7FA0C-736A-41FB-9B07-8AC4D704A300}'] function GetHandle: PPangoOTBuffer; procedure Clear; procedure SetRtl(rtl: Boolean); procedure AddGlyph(glyph, properties, cluster: Cardinal); procedure GetGlyphs(var glyphs: PPangoOTGlyph; var nGlyphs: Integer); procedure Output(glyphs: IPangoGlyphString); procedure SetZeroWidthMarks(zeroWidthMarks: Boolean); property Handle: PPangoOTBuffer read GetHandle; end; TPangoFcFontMap = class(TPangoFontMap, IPangoFcFontMap) protected procedure Shutdown; procedure CacheClear; procedure AddDecoderFindFunc(findfunc: PangoFcDecoderFindFunc; userData: Pointer; dnotify: GDestroyNotify); end; TPangoFT2FontMap = class(TPangoFcFontMap, IPangoFT2FontMap) protected procedure SetResolution(dpiX, dpiY: double); procedure SetDefaultSubstitute(func: PangoFT2SubstituteFunc; data: Pointer; notify: GDestroyNotify); procedure SubstituteChanged; public constructor Create; virtual; end; TPangoFcFont = class(TPangoFont, IPangoFcFont) protected function HasChar(wc: WideChar): Boolean; function GetGlyph(wc: WideChar): Cardinal; function GetUnknownGlyph(wc: WideChar): PangoGlyph; procedure KernGlyphs(glyphs: IPangoGlyphString); function LockFace: FT_Face; procedure UnlockFace; function NewOtBuffer: IPangoOTBuffer; end; TPangoFcDecoder = class(TGObject, IPangoFcDecoder) protected function GetCharset(fcfont: IPangoFcFont): PFcCharSet; function GetGlyph(fcfont: IPangoFcFont; wc: Cardinal): PangoGlyph; end; TPangoOTInfo = class(TGObject, IPangoOTInfo) protected function FindScript(tableType: PangoOTTableType; scriptTag: PangoOTTag; scriptIndex: PCardinal): Boolean; function FindLanguage(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag; languageIndex, requiredFeatureIndex: PCardinal): Boolean; function FindFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; scriptIndex, languageIndex: Cardinal; featureIndex: PCardinal): Boolean; function ListScripts(tableType: PangoOTTableType): PPangoOTTag; function ListLanguages(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag): PPangoOTTag; function ListFeatures(tableType: PangoOTTableType; tag: PangoOTTag; scriptIndex, languageIndex: Cardinal): PPangoOTTag; function GetRulesetForDescription(desc: PPangoOTRulesetDescription): IPangoOTRuleset; function NewRuleset: IPangoOTRuleset; function NewRulesetFor(script: PangoScript; language: PPangoLanguage): IPangoOTRuleset; function NewRulesetFromDescription(desc: PPangoOTRulesetDescription): IPangoOTRuleset; public constructor Create(face: FT_Face); virtual; end; TPangoOTBuffer = class(TInterfacedObject, IPangoOTBuffer) private FPangoOTBuffer: PPangoOTBuffer; constructor CreateInternal(Handle: PPangoOTBuffer); protected function GetHandle: PPangoOTBuffer; procedure Clear; procedure SetRtl(rtl: Boolean); procedure AddGlyph(glyph, properties, cluster: Cardinal); procedure GetGlyphs(var glyphs: PPangoOTGlyph; var nGlyphs: Integer); procedure Output(glyphs: IPangoGlyphString); procedure SetZeroWidthMarks(zeroWidthMarks: Boolean); public destructor Destroy; override; end; TPangoOTRuleset = class(TGObject, IPangoOTRuleset) protected procedure AddFeature(tableType: PangoOTTableType; featureIndex, propertyBit: Cardinal); function MaybeAddFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; propertyBit: Cardinal): Boolean; function MaybeAddFeatures(tableType: PangoOTTableType; features: PPangoOTFeatureMap; nFeatures: Cardinal): Cardinal; function GetFeatureCount(nGsubFeatures, nGposFeatures: PCardinal): Cardinal; procedure Substitute(buffer: IPangoOTBuffer); procedure Position(buffer: IPangoOTBuffer); end; implementation function PangoGlyphStringHandle(const I: IPangoGlyphString): PPangoGlyphString; inline; begin if I <> nil then Result := I.Handle else Result := nil; end; function PangoOTBufferHandle(const I: IPangoOTBuffer): PPangoOTBuffer; inline; begin if I <> nil then Result := I.Handle else Result := nil; end; { TPangoFcFont } function TPangoFcFont.GetGlyph(wc: WideChar): Cardinal; begin Result := pango_fc_font_get_glyph(GetHandle, wc); end; function TPangoFcFont.GetUnknownGlyph(wc: WideChar): PangoGlyph; begin Result := pango_fc_font_get_unknown_glyph(GetHandle, wc); end; function TPangoFcFont.HasChar(wc: WideChar): Boolean; begin Result := pango_fc_font_has_char(GetHandle, wc); end; procedure TPangoFcFont.KernGlyphs(glyphs: IPangoGlyphString); begin pango_fc_font_kern_glyphs(GetHandle, PangoGlyphStringHandle(glyphs)); end; function TPangoFcFont.LockFace: FT_Face; begin Result := pango_fc_font_lock_face(GetHandle); end; function TPangoFcFont.NewOtBuffer: IPangoOTBuffer; begin Result := TPangoOTBuffer.CreateInternal(pango_ot_buffer_new(GetHandle)); end; procedure TPangoFcFont.UnlockFace; begin pango_fc_font_unlock_face(GetHandle); end; { TPangoFcDecoder } function TPangoFcDecoder.GetCharset(fcfont: IPangoFcFont): PFcCharSet; begin Result := pango_fc_decoder_get_charset(GetHandle, GObjectHandle(fcfont)) end; function TPangoFcDecoder.GetGlyph(fcfont: IPangoFcFont; wc: Cardinal): PangoGlyph; begin Result := pango_fc_decoder_get_glyph(GetHandle, GObjectHandle(fcfont), wc); end; { TPangoFcFontMap } procedure TPangoFcFontMap.AddDecoderFindFunc(findfunc: PangoFcDecoderFindFunc; userData: Pointer; dnotify: GDestroyNotify); begin pango_fc_font_map_add_decoder_find_func(GetHandle, findfunc, userData, dnotify); end; procedure TPangoFcFontMap.CacheClear; begin pango_fc_font_map_cache_clear(GetHandle); end; procedure TPangoFcFontMap.Shutdown; begin pango_fc_font_map_shutdown(GetHandle); end; { TPangoFT2FontMap } constructor TPangoFT2FontMap.Create; begin CreateInternal(pango_ft2_font_map_new); end; procedure TPangoFT2FontMap.SetDefaultSubstitute(func: PangoFT2SubstituteFunc; data: Pointer; notify: GDestroyNotify); begin pango_ft2_font_map_set_default_substitute(GetHandle, func, data, notify); end; procedure TPangoFT2FontMap.SetResolution(dpiX, dpiY: double); begin pango_ft2_font_map_set_resolution(GetHandle, dpiX, dpiY); end; procedure TPangoFT2FontMap.SubstituteChanged; begin pango_ft2_font_map_substitute_changed(GetHandle); end; { TPangoOTInfo } constructor TPangoOTInfo.Create(face: FT_Face); begin CreateInternal(g_object_ref(pango_ot_info_get(face))); end; function TPangoOTInfo.FindFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; scriptIndex, languageIndex: Cardinal; featureIndex: PCardinal): Boolean; begin Result := pango_ot_info_find_feature(GetHandle, tableType, featureTag, scriptIndex, languageIndex, featureIndex); end; function TPangoOTInfo.FindLanguage(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag; languageIndex, requiredFeatureIndex: PCardinal): Boolean; begin Result := pango_ot_info_find_language(GetHandle, tableType, scriptIndex, languageTag, languageIndex, requiredFeatureIndex); end; function TPangoOTInfo.FindScript(tableType: PangoOTTableType; scriptTag: PangoOTTag; scriptIndex: PCardinal): Boolean; begin Result := pango_ot_info_find_script(GetHandle, tableType, scriptTag, scriptIndex); end; function TPangoOTInfo.GetRulesetForDescription( desc: PPangoOTRulesetDescription): IPangoOTRuleset; begin Result := TPangoOTRuleset.CreateInternal(g_object_ref(pango_ot_ruleset_get_for_description(GetHandle, desc))); end; function TPangoOTInfo.ListFeatures(tableType: PangoOTTableType; tag: PangoOTTag; scriptIndex, languageIndex: Cardinal): PPangoOTTag; begin Result := pango_ot_info_list_features(GetHandle, tableType, tag, scriptIndex, languageIndex); end; function TPangoOTInfo.ListLanguages(tableType: PangoOTTableType; scriptIndex: Cardinal; languageTag: PangoOTTag): PPangoOTTag; begin Result := pango_ot_info_list_languages(GetHandle, tableType, scriptIndex, languageTag); end; function TPangoOTInfo.ListScripts(tableType: PangoOTTableType): PPangoOTTag; begin Result := pango_ot_info_list_scripts(GetHandle, tableType); end; function TPangoOTInfo.NewRuleset: IPangoOTRuleset; begin Result := TPangoOTRuleset.CreateInternal(pango_ot_ruleset_new(GetHandle)); end; function TPangoOTInfo.NewRulesetFor(script: PangoScript; language: PPangoLanguage): IPangoOTRuleset; begin Result := TPangoOTRuleset.CreateInternal(pango_ot_ruleset_new_for(GetHandle, script, language)); end; function TPangoOTInfo.NewRulesetFromDescription( desc: PPangoOTRulesetDescription): IPangoOTRuleset; begin Result := TPangoOTRuleset.CreateInternal(pango_ot_ruleset_new_from_description(GetHandle, desc)); end; { TPangoOTBuffer } procedure TPangoOTBuffer.AddGlyph(glyph, properties, cluster: Cardinal); begin pango_ot_buffer_add_glyph(FPangoOTBuffer, glyph, properties, cluster); end; procedure TPangoOTBuffer.Clear; begin pango_ot_buffer_clear(FPangoOTBuffer); end; constructor TPangoOTBuffer.CreateInternal(Handle: PPangoOTBuffer); begin Assert(Handle <> nil); FPangoOTBuffer := Handle; end; destructor TPangoOTBuffer.Destroy; begin pango_ot_buffer_destroy(FPangoOTBuffer); inherited; end; procedure TPangoOTBuffer.GetGlyphs(var glyphs: PPangoOTGlyph; var nGlyphs: Integer); begin pango_ot_buffer_get_glyphs(FPangoOTBuffer, glyphs, nGlyphs); end; function TPangoOTBuffer.GetHandle: PPangoOTBuffer; begin Result := FPangoOTBuffer; end; procedure TPangoOTBuffer.Output(glyphs: IPangoGlyphString); begin pango_ot_buffer_output(FPangoOTBuffer, PangoGlyphStringHandle(glyphs)); end; procedure TPangoOTBuffer.SetRtl(rtl: Boolean); begin pango_ot_buffer_set_rtl(FPangoOTBuffer, rtl); end; procedure TPangoOTBuffer.SetZeroWidthMarks(zeroWidthMarks: Boolean); begin pango_ot_buffer_set_zero_width_marks(FPangoOTBuffer, zeroWidthMarks); end; { TPangoOTRuleset } procedure TPangoOTRuleset.AddFeature(tableType: PangoOTTableType; featureIndex, propertyBit: Cardinal); begin pango_ot_ruleset_add_feature(GetHandle, tableType, featureIndex, propertyBit); end; function TPangoOTRuleset.GetFeatureCount(nGsubFeatures, nGposFeatures: PCardinal): Cardinal; begin Result := pango_ot_ruleset_get_feature_count(GetHandle, nGsubFeatures, nGposFeatures); end; function TPangoOTRuleset.MaybeAddFeature(tableType: PangoOTTableType; featureTag: PangoOTTag; propertyBit: Cardinal): Boolean; begin Result := pango_ot_ruleset_maybe_add_feature(GetHandle, tableType, featureTag, propertyBit); end; function TPangoOTRuleset.MaybeAddFeatures(tableType: PangoOTTableType; features: PPangoOTFeatureMap; nFeatures: Cardinal): Cardinal; begin Result := pango_ot_ruleset_maybe_add_features(GetHandle, tableType, features, nFeatures); end; procedure TPangoOTRuleset.Position(buffer: IPangoOTBuffer); begin pango_ot_ruleset_position(GetHandle, PangoOTBufferHandle(buffer)); end; procedure TPangoOTRuleset.Substitute(buffer: IPangoOTBuffer); begin pango_ot_ruleset_substitute(GetHandle, PangoOTBufferHandle(buffer)); end; end.
{ GasImage - image loading for Gasmas using FPimage } unit GasImage; {$MODE OBJFPC}{$H+} interface uses Classes, SysUtils, Gasmas; function ReadImage(FileName: string; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean; implementation uses FPimage, FPReadBMP, FPReadGIF, FPReadJPEG, FPReadPCX, FPReadPNG, FPReadTGA; function GetReaderForFile(FileName: string): TFPCustomImageReader; begin FileName:=ExtractFileExt(LowerCase(FileName)); if FileName='.bmp' then Result:=TFPReaderBMP.Create else if FileName='.gif' then Result:=TFPReaderGIF.Create else if (FileName='.jpg') or (FileName='.jpeg') then Result:=TFPReaderJPEG.Create else if FileName='.pcx' then Result:=TFPReaderPCX.Create else if FileName='.png' then Result:=TFPReaderPNG.Create else if FileName='.tga' then Result:=TFPReaderTarga.Create else Result:=nil; end; procedure DoReadImageFromStream(Reader: TFPCustomImageReader; Stream: TStream; out Surface: TSurface; SurfaceOptions: TSurfaceOptions); var Img: TFPMemoryImage; Pixels: TColorArray; X, Y, Ctr: Integer; FPC: TFPColor; begin Img:=TFPMemoryImage.Create(1, 1); Img.LoadFromStream(Stream, Reader); if not CreateSurface(Img.Width, Img.Height, Surface, SurfaceOptions) then Exception.Create('Failed to create the image surface'); if not Lock(Surface, Pixels) then raise Exception.Create('Failed to lock the image surface'); Ctr:=0; for Y:=0 to Img.Height - 1 do for X:=0 to Img.Width - 1 do begin FPC:=Img.Colors[X, Y]; Pixels[Ctr]:=Color(FPC.Red shr 8, FPC.Green shr 8, FPC.Blue shr 8, FPC.Alpha shr 8); Inc(Ctr); end; Unlock(Surface); FreeAndNil(Img); end; function ReadImageFromStream(Reader: TFPCustomImageReader; Stream: TStream; out Surface: TSurface; SurfaceOptions: TSurfaceOptions): Boolean; begin try DoReadImageFromStream(Reader, Stream, Surface, SurfaceOptions); Result:=True; except Result:=False; FreeAndNil(Surface); end; end; function ReadImage(FileName: string; out Surface: TSurface; SurfaceOptions: TSurfaceOptions): Boolean; var Stream: TFileStream = nil; Reader: TFPCustomImageReader; begin Reader:=GetReaderForFile(FileName); if not Assigned(Reader) then Exit(False); try Stream:=TFileStream.Create(FileName, fmOpenRead); Result:=ReadImageFromStream(Reader, Stream, Surface, SurfaceOptions); except Result:=False; end; FreeAndNil(Stream); FreeAndNil(Reader); end; end.
// Cette unité sert à tester la classe Serveur afin de vérifier // si le numéro de port et le répertoire de base sont // correctement programmés dans la classe. unit uniteTestServeur; interface uses TestFrameWork, uniteServeur, uniteConsigneurStub, SysUtils, uniteConnexion; type TestServeur = class (TTestCase) published // Cette procédure vérifie si un message d'erreur est envoyé // dans le cas où le port est inférieur à 1. procedure testConstructeurPortLimiteInferieurInvalide; // Cette procédure vérifie si un message d'erreur est envoyé // dans le cas où le dossier est inexistant. procedure testConstructeurRepertoireInvalide; end; implementation // Cette procédure vérifie si un message d'erreur est envoyé // dans le cas où le port est inférieur à 1. procedure TestServeur.testConstructeurPortLimiteInferieurInvalide; var // La classe Serveur a besoin d'un consigneur dans son constructeur. // Il n'est pas testé dans cette unité. unConsigneur : ConsigneurStub; // Sert à conserver les informations sur le serveur courant. unServeur : Serveur; begin // On récupère l'exception si elle est lancé. // Le constructeur de type Serveur a besoin d'un consigneur pour fonctionner. // Cette unité ne sert pas à vérifier le fonctionnement de la classe unConsigneur := ConsigneurStub.create(''); try // Création d'un serveur avec des informations invalides. unServeur := Serveur.create( 0, unConsigneur, 'c:\htdocs' ); // Destruction de l'objet. unServeur.destroy; // Aucun message a été lancé de la classe Serveur. fail('Pas d''exception lancée'); // Vérifie si le message de l'exception est le bon message à afficher. except on e:Exception do check( e.message = 'Le numéro de port doit respecter l''intervalle de [1..65535].' ); end; end; // Cette procédure vérifie si un message d'erreur est envoyé // dans le cas où le dossier est inexistant. procedure TestServeur.testConstructeurRepertoireInvalide; var // La classe Serveur a besoin d'un consigneur dans son constructeur. // Il n'est pas testé dans cette unité. unConsigneur : ConsigneurStub; // Sert à conserver les informations sur le serveur courant. unServeur : Serveur; begin // Le constructeur de type Serveur a besoin d'un consigneur pour fonctionner. // Cette unité ne sert pas à vérifier le fonctionnement de la classe unConsigneur := ConsigneurStub.create(''); // On récupère l'exception si elle est lancé. try // Création d'un serveur avec des informations invalides. unServeur := Serveur.create( 80, unConsigneur, 'c:\toto' ); // Destruction de l'objet. unServeur.destroy; // Aucun message a été lancé de la classe Serveur. fail('Pas d''exception lancée'); // Vérifie si le message de l'exception est le bon message à afficher. except on e:Exception do check( e.message = 'Chemin d''accès au répertoire de base invalide.' ); end; end; initialization TestFrameWork.RegisterTest(TestServeur.Suite); end.
unit InflatablesList_Backup; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses AuxTypes, InflatablesList_Types; const IL_BACKUP_DEFAULT_MAX_DEPTH = 25; IL_BACKUP_DEFAULT_MANGERFILENAME = 'backups.ini'; IL_BACKUP_TEMP_SUFFIX = '.tmp'; type TILBackupEntry = record FileName: String; // only file name, not full path SaveTime: TDateTime; SaveVersion: Int64; BackupTime: TDateTime; Size: UInt64; Flags: UInt32; end; TILBackupManager = class(TObject) protected fStaticSettings: TILStaticManagerSettings; fMaxDepth: Integer; fUtilFileName: String; // only file name, not full path fBackups: array of TILBackupEntry; // getters, setters procedure SetStaticSettings(Value: TILStaticManagerSettings); virtual; procedure SetMaxDepth(Value: Integer); procedure SetUtilFileName(const Value: String); Function GetBackupCount: Integer; Function GetBackup(Index: Integer): TILBackupEntry; // other methods procedure Initialize; virtual; procedure Finalize; virtual; procedure AddToBeginning(Entry: TILBackupEntry); virtual; procedure AddToEnd(Entry: TILBackupEntry); virtual; public constructor Create; constructor CreateAsCopy(Source: TILBackupManager; UniqueCopy: Boolean); destructor Destroy; override; procedure Delete(Index: Integer); virtual; procedure LoadBackups; virtual; procedure SaveBackups; virtual; procedure Backup; virtual; procedure Restore(Index: Integer; BackupFirst: Boolean = True); virtual; property StaticSettings: TILStaticManagerSettings read fStaticSettings write SetStaticSettings; property MaxDepth: Integer read fMaxDepth write SetMaxDepth; property UtilFileName: String read fUtilFileName write SetUtilFileName; property BackupCount: Integer read GetBackupCount; property Backups[Index: Integer]: TILBackupEntry read GetBackup; default; end; Function IL_ThreadSafeCopy(Value: TILBackupEntry): TILBackupEntry; overload; implementation uses SysUtils, IniFiles, StrRect, FloatHex, WinFileInfo, InflatablesList_Utils, InflatablesList_Manager; Function IL_ThreadSafeCopy(Value: TILBackupEntry): TILBackupEntry; begin Result := Value; UniqueString(Result.FileName); end; //============================================================================== procedure TILBackupManager.SetStaticSettings(Value: TILStaticManagerSettings); begin fStaticSettings := IL_ThreadSafeCopy(Value); end; //------------------------------------------------------------------------------ procedure TILBackupManager.SetMaxDepth(Value: Integer); begin If Value >= 1 then fMaxDepth := Value; end; //------------------------------------------------------------------------------ procedure TILBackupManager.SetUtilFileName(const Value: String); begin fUtilFileName := Value; UniqueString(fUtilFileName); end; //------------------------------------------------------------------------------ Function TILBackupManager.GetBackupCount: Integer; begin Result := Length(fBackups); end; //------------------------------------------------------------------------------ Function TILBackupManager.GetBackup(Index: Integer): TILBackupEntry; begin If (Index >= Low(fBackups)) and (Index <= High(fBackups)) then Result := fBackups[Index] else raise Exception.CreateFmt('TILBackupManager.GetBackup: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILBackupManager.Initialize; begin fMaxDepth := IL_BACKUP_DEFAULT_MAX_DEPTH; fUtilFileName := IL_BACKUP_DEFAULT_MANGERFILENAME; SetLength(fBackups,0); end; //------------------------------------------------------------------------------ procedure TILBackupManager.Finalize; begin SetLength(fBackups,0); end; //------------------------------------------------------------------------------ procedure TILBackupManager.AddToBeginning(Entry: TILBackupEntry); var i: Integer; begin SetLength(fBackups,Length(fBackups) + 1); For i := High(fBackups) downto Succ(Low(fBackups)) do fBackups[i] := fBackups[i - 1]; fBackups[Low(fBackups)] := Entry; end; //------------------------------------------------------------------------------ procedure TILBackupManager.AddToEnd(Entry: TILBackupEntry); begin SetLength(fBackups,Length(fBackups) + 1); fBackups[High(fBackups)] := Entry; end; //============================================================================== constructor TILBackupManager.Create; begin inherited Create; Initialize; end; //------------------------------------------------------------------------------ constructor TILBackupManager.CreateAsCopy(Source: TILBackupManager; UniqueCopy: Boolean); var i: Integer; begin Create; fStaticSettings := IL_ThreadSafeCopy(Source.StaticSettings); fMaxDepth := Source.MaxDepth; fUtilFileName := Source.UtilFileName; UniqueString(fUtilFileName); SetLength(fBackups,Source.BackupCount); For i := Low(fBackups) to High(fBackups) do fBackups[i] := IL_ThreadSafeCopy(Source[i]); end; //------------------------------------------------------------------------------ destructor TILBackupManager.Destroy; begin Finalize; inherited; end; //------------------------------------------------------------------------------ procedure TILBackupManager.Delete(Index: Integer); var i: Integer; begin If (Index >= Low(fBackups)) and (Index <= High(fBackups)) then begin // delete the backup file IL_DeleteFile(fStaticSettings.BackupPath + fBackups[Index].FileName); // remove entry For i := Index to Pred(High(fBackups)) do fBackups[i] := fBackups[i + 1]; SetLength(fBackups,Length(fBackups) - 1); end else raise Exception.CreateFmt('TILBackupManager.Delete: Index (%d) out of bounds.',[Index]); end; //------------------------------------------------------------------------------ procedure TILBackupManager.LoadBackups; var Ini: TIniFile; i: Integer; Temp: TILBackupEntry; begin SetLength(fBackups,0); If IL_FileExists(fStaticSettings.BackupPath + fUtilFileName) then begin Ini := TIniFile.Create(StrToRTL(fStaticSettings.BackupPath + fUtilFileName)); try For i := 0 to Pred(Ini.ReadInteger('Backups','Count',0)) do If Ini.ValueExists('Backups',IL_Format('Backup[%d].FileName',[i])) then begin Temp.FileName := Ini.ReadString('Backups',IL_Format('Backup[%d].FileName',[i]),''); Temp.SaveTime := TDateTime(HexToDouble(Ini.ReadString('Backups',IL_Format('Backup[%d].SaveTime',[i]),'0'))); Temp.SaveVersion := StrToInt64Def('$' + Ini.ReadString('Backups',IL_Format('Backup[%d].SaveVersion',[i]),'0'),0); Temp.BackupTime := TDateTime(HexToDouble(Ini.ReadString('Backups',IL_Format('Backup[%d].BackupTime',[i]),'0'))); Temp.Size := UInt64(StrToInt64Def(Ini.ReadString('Backups',IL_Format('Backup[%d].Size',[i]),'0'),0)); Temp.Flags := UInt32(StrToIntDef('$' + Ini.ReadString('Backups',IL_Format('Backup[%d].Flags',[i]),'0'),0)); If IL_FileExists(StrToRTL(fStaticSettings.BackupPath + Temp.FileName)) then AddToEnd(Temp); end; finally Ini.Free; end; end; end; //------------------------------------------------------------------------------ procedure TILBackupManager.SaveBackups; var i: Integer; Ini: TIniFile; begin // traverse list of backup files and delete all above depth limit For i := fMaxDepth to High(fBackups) do If IL_FileExists(fStaticSettings.BackupPath + fBackups[i].FileName) then IL_DeleteFile(fStaticSettings.BackupPath + fBackups[i].FileName); // truncate the list If Length(fBackups) > fMaxDepth then SetLength(fBackups,fMaxDepth); // save the list IL_CreateDirectoryPathForFile(fStaticSettings.BackupPath + fUtilFileName); Ini := TIniFile.Create(StrToRTL(fStaticSettings.BackupPath + fUtilFileName)); try Ini.WriteInteger('Backups','Count',Length(fBackups)); For i := Low(fBackups) to High(fBackups) do begin Ini.WriteString('Backups',IL_Format('Backup[%d].FileName',[i]),fBackups[i].FileName); Ini.WriteString('Backups',IL_Format('Backup[%d].SaveTime',[i]),DoubleToHex(Double(fBackups[i].SaveTime))); Ini.WriteString('Backups',IL_Format('Backup[%d].SaveVersion',[i]),IntToHex(fBackups[i].SaveVersion,16)); Ini.WriteString('Backups',IL_Format('Backup[%d].BackupTime',[i]),DoubleToHex(Double(fBackups[i].BackupTime))); Ini.WriteString('Backups',IL_Format('Backup[%d].Size',[i]),IntToStr(Int64(fBackups[i].Size))); Ini.WriteString('Backups',IL_Format('Backup[%d].Flags',[i]),IntToHex(fBackups[i].Flags,8)); end; finally Ini.Free; end; end; //------------------------------------------------------------------------------ procedure TILBackupManager.Backup; var Time: TDateTime; Temp: TILBackupEntry; Preload: TILPreloadInfo; begin If IL_FileExists(fStaticSettings.ListFile) then begin // fill entry Time := Now; Temp.FileName := IL_FormatDateTime('yyyy-mm-dd-hh-nn-ss-zzz',Time) + '.inl'; with TILManager.CreateTransient do // for PreloadFile() try Preload := PreloadFile(fStaticSettings.ListFile); If ilprfExtInfo in Preload.ResultFlags then begin Temp.SaveTime := Preload.Time; Temp.SaveVersion := Preload.Version.Full; Temp.Flags := Preload.Flags; end else begin Temp.SaveTime := 0.0; Temp.SaveVersion := 0; Temp.Flags := 0; end; finally Free; end; Temp.BackupTime := Time; with TWinFileInfo.Create(fStaticSettings.ListFile,WFI_LS_LoadSize) do try Temp.Size := Size; finally Free; end; // do file copy IL_CreateDirectoryPath(fStaticSettings.BackupPath); If IL_FileExists(fStaticSettings.BackupPath + Temp.FileName) then IL_DeleteFile(fStaticSettings.BackupPath + Temp.FileName); // to be sure IL_CopyFile(fStaticSettings.ListFile,fStaticSettings.BackupPath + Temp.FileName); // add entry AddToBeginning(Temp); // save new list of backups (also deletes old backups) SaveBackups; end; end; //------------------------------------------------------------------------------ procedure TILBackupManager.Restore(Index: Integer; BackupFirst: Boolean = True); var TempFileName: String; begin If (Index >= Low(fBackups)) and (Index <= High(fBackups)) then begin If BackupFirst then begin { backup will be called... - make copy of restored file - do backup (might delete the restored file) - delete list file - move copy of restored file (rename it in the process) } TempFileName := fStaticSettings.TempPath + fBackups[Index].FileName + IL_BACKUP_TEMP_SUFFIX; IL_CopyFile(fStaticSettings.BackupPath + fBackups[Index].FileName,TempFileName); Backup; IL_DeleteFile(fStaticSettings.ListFile); IL_MoveFile(TempFileName,fStaticSettings.ListFile); end else begin // no backup will be performed, delete list file and restore selected backup IL_DeleteFile(fStaticSettings.ListFile); IL_CopyFile(fStaticSettings.BackupPath + fBackups[Index].FileName,fStaticSettings.ListFile); end; end else raise Exception.CreateFmt('TILBackupManager.Restore: Index (%d) out of bounds.',[Index]); end; end.
program exercise1; USES sysutils; TYPE IntegerArray = ARRAY OF integer; ProcPtr = function(left, right : Integer): Integer; TreeNodePtr = ^TreeNode; VisitProcPtr = Procedure(node: TreeNodePtr); TreeNode = RECORD parent : TreeNodePtr; // pointer to the parent node left: TreeNodePtr; // pointer to the left node right: TreeNodePtr; // pointer to the right node ID: Integer; // Integer ID of the node visit: VisitProcPtr; // function pointer to functions that have no return value and a pointer to a node END; { Compares integer left with the integer right for order. Returns a negative integer, zero, or a positive integer as left is less than, equal to, or greater than right } FUNCTION compareTo(left, right : Integer) : Integer; BEGIN IF left < right THEN BEGIN exit(-1); END ELSE IF left > right THEN BEGIN exit(1); END ELSE BEGIN exit(0); END END; { Sorts array of integers by Quicksort. The integers are compared using the function 'comparator' } PROCEDURE QuickSort(Var a : IntegerArray; comparator : ProcPtr); PROCEDURE Sort ( left, right : integer ); VAR i, j, tmp, pivot : integer; BEGIN i:=left; j:=right; pivot := a[Random(right - left) + left]; REPEAT // sort_function(a[i], x) < 0 WHILE comparator(a[i], pivot) < 0 DO i := i + 1; // sort_function(a[j], x) > 0 WHILE comparator(a[j], pivot) > 0 DO j := j - 1; IF i <= j THEN BEGIN tmp := a[i]; a[i] := a[j]; a[j] := tmp; j := j - 1; i := i + 1; END; UNTIL i > j; IF left < j THEN Sort(left,j); IF i < right THEN Sort(i,right); END; Begin Sort(0, Length(a) - 1); END; { A print-function that can be assigned to the node’s visit function pointer. The function prints the node’s ID on STDOUT seperated by a single whitespace } PROCEDURE print(node: TreeNodePtr); BEGIN write(node^.ID, ' '); END; { Insert new node with ID 'element' at the right place in the tree } PROCEDURE insertID(VAR Tree : TreeNodePtr; insertID: Integer); VAR InsertNode : TreeNodePtr; ParentPtr : TreeNodePtr; CurrentNodePtr : TreeNodePtr; BEGIN CurrentNodePtr := Tree; ParentPtr := NIL; WHILE (CurrentNodePtr <> NIL) DO IF CurrentNodePtr^.ID <> insertID THEN BEGIN ParentPtr := CurrentNodePtr; IF CurrentNodePtr^.ID > insertID THEN CurrentNodePtr := CurrentNodePtr^.left ELSE CurrentNodePtr := CurrentNodePtr^.right END; { Allocate the memory for the nodes dynamically at run-time } New (insertNode); insertNode^.parent := ParentPtr; insertNode^.left := NIL; insertNode^.right := NIL; insertNode^.ID := insertID; insertNode^.visit := @print; IF ParentPtr = NIL THEN Tree := InsertNode ELSE IF ParentPtr^.ID > insertID THEN ParentPtr^.left := insertNode ELSE ParentPtr^.right := insertNode END; { Depth first traversal that traverses the tree from its root and invokes the visit method (http://en.wikipedia.org/wiki/Tree_traversal#Depth-first) } PROCEDURE depthFirstTraversal(root: TreeNodePtr); BEGIN IF root <> NIL THEN BEGIN { Visit the root. } root^.visit(root); { Traverse the left subtree. } depthFirstTraversal(root^.left); { Traverse the right subtree. } depthFirstTraversal(root^.right); END END; { Counts the occurences of separator in str Taken and modified from: http://lists.freepascal.org/fpc-pascal/2007-July/014721.html} function Occurs(const str, separator: string): integer; var i, nSep: integer; begin nSep:= 0; for i:= 1 to Length(str) do if str[i] = separator then Inc(nSep); exit(nSep); end; { Splits string containing Integers separated by separator into array of Integer Taken and modified from: http://lists.freepascal.org/fpc-pascal/2007-July/014719.html } function Split(const str, separator: string): IntegerArray; var i, n: Integer; strline, strfield: string; results : IntegerArray; begin { Number of occurences of the separator } n:= Occurs(str, separator); { Size of the array to be returned is the number of occurences of the separator } SetLength(results, n + 1); i := 0; strline:= str; repeat if Pos(separator, strline) > 0 then begin strfield:= Copy(strline, 1, Pos(separator, strline) - 1); strline:= Copy(strline, Pos(separator, strline) + 1, Length(strline) - pos(separator,strline)); end else begin strfield:= strline; strline:= ''; end; results[i]:= StrToInt(strfield); Inc(i); until strline= ''; Exit(results); end; VAR number: integer; numbersString: String; numbersArray: IntegerArray; tree: TreeNodePtr; BEGIN { Initialize RNG } Randomize; { Creating empty tree by setting the "root" node to NIL } tree := NIL; { Read integers from STDIN and put them into an array } ReadLn (numbersString); numbersArray := Split(numbersString, ' '); { Sort in place } QuickSort(numbersArray, @compareTo); { Insert integers into tree } FOR number IN numbersArray DO BEGIN insertID(tree, number); END; { Print tree depth-first } depthFirstTraversal(tree); END.
program coins (input,output); {Jesse Anderson 8/26/95 c1e15} uses crt; var change, qnbr, dnbr, nnbr, pnbr:Integer; const quarter=25; dime=10; nickel=5; penny=1; begin; clrscr; Write ('Enter the amount of change in cents: '); Readln (change); Writeln; qnbr:=change div quarter; dnbr:=change mod quarter div dime; nnbr:=change mod (dnbr * dime) div nickel; pnbr:=change mod (nnbr * nickel) div penny; Writeln ('Quarters: ', qnbr); Writeln; Writeln ('Dimes: ', dnbr); Writeln; Writeln ('Nickels: ',nnbr); Writeln; Writeln ('Pennies: ', pnbr); end.
unit uFrmLogin; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects; type TWebFormRedirectEvent = procedure(const AURL : string; var DoCloseWebView: boolean) of object; type TFrmLogin = class(TForm) Rectangle1: TRectangle; btnCancel: TButton; WebBrowser1: TWebBrowser; procedure WebBrowser1DidFinishLoad(ASender: TObject); private FOnBeforeRedirect: TWebFormRedirectEvent; { Private declarations } public { Public declarations } property OnBeforeRedirect: TWebFormRedirectEvent read FOnBeforeRedirect write FOnBeforeRedirect; end; var FrmLogin: TFrmLogin; implementation {$R *.fmx} uses Unit1; procedure Facebook_AccessTokenRedirect(const AURL: string; var DoCloseWebView: boolean); var LATPos: integer; LToken: string; begin try LATPos := Pos('access_token=', AURL); if (LATPos > 0) then begin LToken := Copy(AURL, LATPos + 13, Length(AURL)); if (Pos('&', LToken) > 0) then begin LToken := Copy(LToken, 1, Pos('&', LToken) - 1); end; Form1.FAccessToken := LToken; if (LToken <> '') then begin DoCloseWebView := True; end; end else begin LATPos := Pos('api_key=', AURL); if LATPos <= 0 then begin LATPos := Pos('access_denied', AURL); if (LATPos > 0) then begin // Denied, Not Allow Form1.FAccessToken := ''; DoCloseWebView := True; end; end; end; except on E: Exception do ShowMessage(E.Message); END; end; procedure TFrmLogin.WebBrowser1DidFinishLoad(ASender: TObject); var CloseWebView : boolean; url : string; begin url := TWebBrowser(ASender).URL; CloseWebView := false; if url <> '' then Facebook_AccessTokenRedirect(url, CloseWebView); if CloseWebView then begin TWebBrowser(ASender).Stop; TWebBrowser(ASender).URL := ''; FrmLogin.close; ModalResult := mrok; end; end; end.
// // Created by the DataSnap proxy generator. // 26/06/2017 13:13:43 // unit UMetodosServidor; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FFuncaoTesteCommand: TDBXCommand; FgetAlunosCommand: TDBXCommand; FgetFotoAlunoCommand: TDBXCommand; FgetFotoAlunoJSONCommand: TDBXCommand; FsetFotoAlunoCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function FuncaoTeste: string; function getAlunos: TDataSet; function getFotoAluno(codigoAluno: Integer): TStream; function getFotoAlunoJSON(codigoAluno: Integer): TJSONArray; function setFotoAluno(jsa: TJSONArray; codigoAluno: Integer): Boolean; end; implementation function TServerMethods1Client.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.FuncaoTeste: string; begin if FFuncaoTesteCommand = nil then begin FFuncaoTesteCommand := FDBXConnection.CreateCommand; FFuncaoTesteCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFuncaoTesteCommand.Text := 'TServerMethods1.FuncaoTeste'; FFuncaoTesteCommand.Prepare; end; FFuncaoTesteCommand.ExecuteUpdate; Result := FFuncaoTesteCommand.Parameters[0].Value.GetWideString; end; function TServerMethods1Client.getAlunos: TDataSet; begin if FgetAlunosCommand = nil then begin FgetAlunosCommand := FDBXConnection.CreateCommand; FgetAlunosCommand.CommandType := TDBXCommandTypes.DSServerMethod; FgetAlunosCommand.Text := 'TServerMethods1.getAlunos'; FgetAlunosCommand.Prepare; end; FgetAlunosCommand.ExecuteUpdate; Result := TCustomSQLDataSet.Create(nil, FgetAlunosCommand.Parameters[0].Value.GetDBXReader(False), True); Result.Open; if FInstanceOwner then FgetAlunosCommand.FreeOnExecute(Result); end; function TServerMethods1Client.getFotoAluno(codigoAluno: Integer): TStream; begin if FgetFotoAlunoCommand = nil then begin FgetFotoAlunoCommand := FDBXConnection.CreateCommand; FgetFotoAlunoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FgetFotoAlunoCommand.Text := 'TServerMethods1.getFotoAluno'; FgetFotoAlunoCommand.Prepare; end; FgetFotoAlunoCommand.Parameters[0].Value.SetInt32(codigoAluno); FgetFotoAlunoCommand.ExecuteUpdate; Result := FgetFotoAlunoCommand.Parameters[1].Value.GetStream(FInstanceOwner); end; function TServerMethods1Client.getFotoAlunoJSON(codigoAluno: Integer): TJSONArray; begin if FgetFotoAlunoJSONCommand = nil then begin FgetFotoAlunoJSONCommand := FDBXConnection.CreateCommand; FgetFotoAlunoJSONCommand.CommandType := TDBXCommandTypes.DSServerMethod; FgetFotoAlunoJSONCommand.Text := 'TServerMethods1.getFotoAlunoJSON'; FgetFotoAlunoJSONCommand.Prepare; end; FgetFotoAlunoJSONCommand.Parameters[0].Value.SetInt32(codigoAluno); FgetFotoAlunoJSONCommand.ExecuteUpdate; Result := TJSONArray(FgetFotoAlunoJSONCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner)); end; function TServerMethods1Client.setFotoAluno(jsa: TJSONArray; codigoAluno: Integer): Boolean; begin if FsetFotoAlunoCommand = nil then begin FsetFotoAlunoCommand := FDBXConnection.CreateCommand; FsetFotoAlunoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FsetFotoAlunoCommand.Text := 'TServerMethods1.setFotoAluno'; FsetFotoAlunoCommand.Prepare; end; FsetFotoAlunoCommand.Parameters[0].Value.SetJSONValue(jsa, FInstanceOwner); FsetFotoAlunoCommand.Parameters[1].Value.SetInt32(codigoAluno); FsetFotoAlunoCommand.ExecuteUpdate; Result := FsetFotoAlunoCommand.Parameters[2].Value.GetBoolean; end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FFuncaoTesteCommand.DisposeOf; FgetAlunosCommand.DisposeOf; FgetFotoAlunoCommand.DisposeOf; FgetFotoAlunoJSONCommand.DisposeOf; FsetFotoAlunoCommand.DisposeOf; inherited; end; end.
unit unit_messages; interface uses Classes, Generics.Collections, StdCtrls; type TMessageSubject = record id : longint; name : string; ttype : string end; TMessageAuthor = record id : longint; name : string; end; TMessageContent = record subject : TMessageSubject; author : TMessageAuthor; text : string; roottext : string; end; PMessage = ^TMessage; TMessage = record id : longint; name : string; flag : boolean; subject : TMessageSubject; content : TMessageContent; time_created : string; end; TMessageHistory = class public msg: TList<PMessage>; function Count: integer; Constructor Create; Destructor Destroy; function Find(id:longint): integer; function Parse(xmlstr: string): integer; function Dump: string; private end; implementation uses unit_main, MSXML, xmldom, XMLIntf, msxmldom, XMLDoc, SysUtils; const b2s: array[boolean] of string = ('false', 'true'); Constructor TMessageHistory.Create; begin msg := TList<PMessage>.Create; end; Destructor TMessageHistory.Destroy; begin msg.Free; end; function TMessageHistory.Dump: string; var m: PMessage; begin result := ''; for m in msg do begin result := result + '---' + #13#10; result := result + 'subject.id=' + IntToStr(m.subject.id) + #13#10; result := result + 'subject.name=' + m.subject.name + #13#10; result := result + 'subject.ttype=' + m.subject.ttype + #13#10; result := result + 'content.subject.id=' + IntToStr(m.content.subject.id) + #13#10; result := result + 'content.subject.name=' + m.content.subject.name + #13#10; result := result + 'content.subject.ttype=' + m.content.subject.ttype + #13#10; result := result + 'content.author.id=' + IntToStr(m.content.author.id) + #13#10; result := result + 'content.author.name=' + m.content.author.name + #13#10; result := result + 'content.text=' + m.content.text + #13#10; result := result + 'content.rottext=' + m.content.roottext + #13#10; end; end; function TMessageHistory.Find(id: longint): integer; var m: TMessage; i:integer; begin result := -1; try for I := 0 to msg.Count-1 do if msg.Items[i].id = id then result := i; except end; end; function TMessageHistory.Parse(xmlstr: string): integer; var i : integer; xml : IXMLDocument; node : IXmlNode; row : integer; count: integer; m : PMessage; begin //Pre parse count count := msg.Count; //Flag set to false. After parse, all elements withflag=false would be deleted for m in msg do begin m.flag:=false; end; xml := TXMLDocument.Create(nil); xml.LoadFromXML(xmlstr); //If gon an errornous answer try if xml.DocumentElement.ChildNodes['status'].ChildNodes['code'].text <> 'ok' then result:=-1; except result:=-1; end; if (result<0) then exit; for I := 0 to xml.DocumentElement.ChildNodes['data'].ChildNodes['notifications'].ChildNodes.Count - 1 do begin node := xml.DocumentElement.ChildNodes['data'].ChildNodes['notifications'].ChildNodes[I]; row:=Find(StrToInt(node.ChildNodes['id'].text)); //Acurate row selection if row <0 then begin m := New(PMessage); m.flag := true; m.id := 0; try //notification m.id := StrToInt(node.ChildNodes['id'].text); m.name := node.ChildNodes['name'].text; m.time_created := node.ChildNodes['time_created'].text; m.subject.id := StrToInt(node.ChildNodes['subject'].ChildNodes['id'].text); m.subject.name := node.ChildNodes['subject'].ChildNodes['name'].text; m.subject.ttype := node.ChildNodes['subject'].ChildNodes['type'].text; if (m.subject.ttype='comment') then begin m.content.subject.id := StrToInt(node.ChildNodes['content'].ChildNodes['subject'].ChildNodes['id'].text); m.content.subject.name := node.ChildNodes['content'].ChildNodes['subject'].ChildNodes['name'].text; m.content.subject.ttype := node.ChildNodes['content'].ChildNodes['subject'].ChildNodes['type'].text; m.content.author.id := StrToInt(node.ChildNodes['content'].ChildNodes['author'].ChildNodes['id'].text); m.content.author.name := node.ChildNodes['content'].ChildNodes['author'].ChildNodes['name'].text; m.content.text := node.ChildNodes['content'].ChildNodes['text'].text; end; if (m.subject.ttype='task') then m.content.roottext := node.ChildNodes['content'].text; if (m.subject.ttype='task') then m.content.roottext := node.ChildNodes['content'].text; except on e:exception do main.log.lines.add('error xml parse: '+e.Message); end; msg.Add(m); end else begin msg[row].flag := true; end; end; //If we have new messages if count < msg.count then result := msg.Count - count else result := 0; //Delete messages, if they was not in parse list i:=0; while i<msg.Count do begin if msg[i].flag=false then begin msg.Delete(i) end else inc(i); end; end; function mystrtoint(id: integer; str:string; log: tmemo): longint; begin try result:=StrToInt(str); except on e:exception do log.Lines.Add('mystrtoint: '+inttostr(id)+' :'+e.message); end; end; function TMessageHistory.Count: integer; begin result := msg.Count; end; end.
unit PRP; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, ComCtrls, Printers, ActnList, StdActns; function OpenSaveFileDialog(ParentHandle: THandle; const DefExt, Filter, InitialDir, Title: string; var FileName: string; IsOpenDialog: Boolean): Boolean; type TPrintForm = class(TForm) MainMenu: TMainMenu; FileItem: TMenuItem; QuickPrintItem: TMenuItem; PrintItem: TMenuItem; sp1: TMenuItem; SaveAsItem: TMenuItem; sp2: TMenuItem; QuitItem: TMenuItem; FontItem: TMenuItem; StatusBar: TStatusBar; FullScreenItem: TMenuItem; ToolsItem: TMenuItem; sp4: TMenuItem; PrintDlg: TPrintDialog; PrintDates: TRichEdit; FontDlg: TFontDialog; ActionList: TActionList; EditCut: TEditCut; EditCopy: TEditCopy; EditPaste: TEditPaste; EditSelectAll: TEditSelectAll; EditUndo: TEditUndo; EditDelete: TEditDelete; EditItem: TMenuItem; Copytem: TMenuItem; Cuttem: TMenuItem; Deltem: TMenuItem; Pastetem: TMenuItem; SelectAlltem: TMenuItem; Undotem: TMenuItem; Cleartem: TMenuItem; sp5: TMenuItem; sp6: TMenuItem; PrintTextMenu: TPopupMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; s1: TMenuItem; s2: TMenuItem; s3: TMenuItem; s4: TMenuItem; s5: TMenuItem; s6: TMenuItem; s7: TMenuItem; s8: TMenuItem; N5: TMenuItem; N6: TMenuItem; procedure SaveAsItemClick(Sender: TObject); procedure QuitItemClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FullScreenItemClick(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure QuickPrintItemClick(Sender: TObject); procedure PrintItemClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FontItemClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure CleartemClick(Sender: TObject); procedure FormShow(Sender: TObject); private procedure WMGetMinMaxInfo(var msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO; public end; var PrintForm: TPrintForm; implementation uses SP; type POpenFilenameA = ^TOpenFilenameA; POpenFilename = POpenFilenameA; tagOFNA = packed record lStructSize: DWORD; hWndOwner: HWND; hInstance: HINST; lpstrFilter: PAnsiChar; lpstrCustomFilter: PAnsiChar; nMaxCustFilter: DWORD; nFilterIndex: DWORD; lpstrFile: PAnsiChar; nMaxFile: DWORD; lpstrFileTitle: PAnsiChar; nMaxFileTitle: DWORD; lpstrInitialDir: PAnsiChar; lpstrTitle: PAnsiChar; Flags: DWORD; nFileOffset: Word; nFileExtension: Word; lpstrDefExt: PAnsiChar; lCustData: LPARAM; lpfnHook: function(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): UINT stdcall; lpTemplateName: PAnsiChar; end; TOpenFilenameA = tagOFNA; TOpenFilename = TOpenFilenameA; function GetOpenFileName(var OpenFile: TOpenFilename): Bool; stdcall; external 'comdlg32.dll' name 'GetOpenFileNameA'; function GetSaveFileName(var OpenFile: TOpenFilename): Bool; stdcall; external 'comdlg32.dll' name 'GetSaveFileNameA'; const OFN_DONTADDTORECENT = $02000000; OFN_FILEMUSTEXIST = $00001000; OFN_HIDEREADONLY = $00000004; OFN_PATHMUSTEXIST = $00000800; function CharReplace(const Source: string; oldChar, newChar: Char): string; var i: Integer; begin Result := Source; for i := 1 to Length(Result) do if Result[i] = oldChar then Result[i] := newChar; end; {$R *.dfm} const Rect: TRect = (Left: 100; Top: 100; Right: 100; Bottom: 100); FullScreen: Boolean = False; function OpenSaveFileDialog(ParentHandle: THandle; const DefExt, Filter, InitialDir, Title: string; var FileName: string; IsOpenDialog: Boolean): Boolean; var ofn: TOpenFileName; szFile: array[0..MAX_PATH] of Char; begin Result := False; FillChar(ofn, SizeOf(TOpenFileName), 0); with ofn do begin lStructSize := SizeOf(TOpenFileName); hwndOwner := ParentHandle; lpstrFile := szFile; nMaxFile := SizeOf(szFile); if (Title <> '') then lpstrTitle := PChar(Title); if (InitialDir <> '') then lpstrInitialDir := PChar(InitialDir); StrPCopy(lpstrFile, FileName); lpstrFilter := PChar(CharReplace(Filter, '|', #0)+#0#0); if DefExt <> '' then lpstrDefExt := PChar(DefExt); end; if IsOpenDialog then begin if GetOpenFileName(ofn) then begin Result := True; FileName := StrPas(szFile); end; end else begin if GetSaveFileName(ofn) then begin Result := True; FileName := StrPas(szFile); end; end end; procedure PrintStrings(Strings: TStrings); var Prn: TextFile; i: word; begin AssignPrn(Prn); try Rewrite(Prn); try for i := 0 to Strings.Count - 1 do writeln(Prn, Strings.Strings[i]); finally CloseFile(Prn); end; except on EInOutError do MessageDlg('Error Printing text.', mtError, [mbOk], 0); end; end; procedure TPrintForm.SaveAsItemClick(Sender: TObject); var s: String; begin try if OpenSaveFileDialog(PrintForm.Handle, '*.txt', 'Normal text files (*.txt)|*.txt|', ParamStr(0), 'Сохранить', s, False) then begin if FileExists(s) then if Application.MessageBox(PChar('Файл "' + s + '" уже существует.' + #13 + 'Заменить его?'), 'Замена файла', MB_ICONQUESTION + mb_YesNo) <> idYes then begin end else begin PrintDates.Lines.SaveToFile(s); end; if not FileExists(s) then begin PrintDates.Lines.SaveToFile(s); end; end; except end; end; procedure TPrintForm.QuitItemClick(Sender: TObject); begin PrintForm.Close; end; procedure TPrintForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not FullScreenItem.Checked then begin if Key = vk_Escape then Close; end; if FullScreenItem.Checked then begin if Key = vk_Escape then FullScreenItem.Click; end; end; procedure TPrintForm.FullScreenItemClick(Sender: TObject); begin PrintForm.ScreenSnap := False; FullScreen := not FullScreen; if FullScreen then begin FullScreenItem.Checked := True; Rect := BoundsRect; SetBounds( Left - ClientOrigin.X, Top - ClientOrigin.Y, GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth), GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight )); end else begin FullScreenItem.Checked := False; BoundsRect := Rect; if SetForm.Ch14.Checked then PrintForm.ScreenSnap := True else PrintForm.ScreenSnap := False; end; end; procedure TPrintForm.WMGetMinMaxInfo(var msg: TWMGetMinMaxInfo); begin inherited; with msg.MinMaxInfo^.ptMaxTrackSize do begin X := GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth); Y := GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight ); end; end; procedure TPrintForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if SetForm.ch13.Checked then begin ReleaseCapture; Perform(Wm_SysCommand, $f012, 0); end; end; procedure TPrintForm.QuickPrintItemClick(Sender: TObject); begin PrintStrings(PrintDates.Lines); end; procedure TPrintForm.PrintItemClick(Sender: TObject); var s: String; begin if PrintDlg.Execute then PrintDates.Print(s); end; procedure TPrintForm.FormClose(Sender: TObject; var Action: TCloseAction); begin try if FullScreenItem.Checked = True then begin PrintForm.Hide; FullScreenItem.Click; end; PrintForm.Hide; ClientHeight := 350; ClientWidth := 516; except end; end; procedure TPrintForm.FontItemClick(Sender: TObject); begin FontDlg.Font := PrintDates.Font; if FontDlg.Execute then PrintDates.Font.Assign(FontDlg.Font); end; procedure TPrintForm.FormDestroy(Sender: TObject); begin PrintForm.OnActivate := nil; PrintTextMenu.Free; ActionList.Free; PrintDates.Free; StatusBar.Free; PrintDlg.Free; MainMenu.Free; FontDlg.Free; end; procedure TPrintForm.CleartemClick(Sender: TObject); begin PrintDates.Lines.Clear; end; procedure TPrintForm.FormShow(Sender: TObject); begin if SetForm.ch12.Checked then begin SetWindowLong(PrintForm.Handle, GWL_EXSTYLE, GetWindowLOng(PrintForm.Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2009, 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_AES; interface uses SysUtils, Classes, uTPLb_BlockCipher, uTPLb_StreamCipher, uTPLb_Decorators; type {$IF compilerversion >= 21} [DesignDescription( 'From Wikipedia: QUOTE:'#13#10 + 'In cryptography, the Advanced Encryption Standard (AES) is a symmetric-key ' + 'encryption standard adopted by the U.S. government. The standard comprises ' + 'three block ciphers, AES-128, AES-192 and AES-256, adopted from a larger ' + 'collection originally published as Rijndael. Each of these ciphers has a ' + '128-bit block size, with key sizes of 128, 192 and 256 bits, respectively. ' + 'The AES ciphers have been analyzed extensively and are now used worldwide, ' + 'as was the case with its predecessor,[3] the Data Encryption Standard (DES).'#13#10 + #13#10 + 'AES was announced by National Institute of Standards and Technology (NIST) ' + 'as U.S. FIPS PUB 197 (FIPS 197) on November 26, 2001 after a 5-year standa' + 'rdization process in which fifteen competing designs were presented and ' + 'evaluated before Rijndael was selected as the most suitable. It became ' + 'effective as a Federal government standard on May 26, 2002 after approval ' + 'by the Secretary of Commerce. AES is the first publicly accessible and open ' + 'cipher approved by the NSA for top secret information.'#13#10 + 'END QUOTE' )] {$ENDIF} TAES = class( TInterfacedObject, IBlockCipher, ICryptoGraphicAlgorithm, IControlObject) // The IControlObject interface is necessary to support the Design // Description. private FKeySize: integer; // Either 128, 192, or 256 bits. function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DefinitionURL: string; function WikipediaReference: string; function SeedByteSize: integer; // Size that the input of the GenerateKey must be. function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; function BlockSize: integer; // in units of bits. Must be a multiple of 8. function KeySize: integer; function MakeBlockCodec( Key: TSymetricKey): IBlockCodec; function SelfTest_Key: TBytes; function SelfTest_Plaintext: TBytes; function SelfTest_Ciphertext: TBytes; function ControlObject: TObject; public constructor Create( KeySize1: integer); end; implementation uses uTPlb_StrUtils, uTPLb_IntegerUtils, uTPLb_I18n, uTPLb_Constants; /// THE FOLLOWING FRAGMENT WAS GENERATED BY THE PRECOMPUTE PROGRAM. /// BEGIN FRAGMENT +++ type TMixColsFactor = (fx01, fx02, fx03, fx09, fx0b, fx0d, fx0e); const GF2_8_TimesTables: array [ TMixColsFactor, 0..255 ] of byte = ( ( // fx01 --- Times 01 Table. $00, $01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $1A, $1B, $1C, $1D, $1E, $1F, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $2A, $2B, $2C, $2D, $2E, $2F, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $3E, $3F, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $4A, $4B, $4C, $4D, $4E, $4F, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $5A, $5B, $5C, $5D, $5E, $5F, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D, $6E, $6F, $70, $71, $72, $73, $74, $75, $76, $77, $78, $79, $7A, $7B, $7C, $7D, $7E, $7F, $80, $81, $82, $83, $84, $85, $86, $87, $88, $89, $8A, $8B, $8C, $8D, $8E, $8F, $90, $91, $92, $93, $94, $95, $96, $97, $98, $99, $9A, $9B, $9C, $9D, $9E, $9F, $A0, $A1, $A2, $A3, $A4, $A5, $A6, $A7, $A8, $A9, $AA, $AB, $AC, $AD, $AE, $AF, $B0, $B1, $B2, $B3, $B4, $B5, $B6, $B7, $B8, $B9, $BA, $BB, $BC, $BD, $BE, $BF, $C0, $C1, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $CB, $CC, $CD, $CE, $CF, $D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $DA, $DB, $DC, $DD, $DE, $DF, $E0, $E1, $E2, $E3, $E4, $E5, $E6, $E7, $E8, $E9, $EA, $EB, $EC, $ED, $EE, $EF, $F0, $F1, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA, $FB, $FC, $FD, $FE, $FF ), ( // fx02 --- Times 02 Table. $00, $02, $04, $06, $08, $0A, $0C, $0E, $10, $12, $14, $16, $18, $1A, $1C, $1E, $20, $22, $24, $26, $28, $2A, $2C, $2E, $30, $32, $34, $36, $38, $3A, $3C, $3E, $40, $42, $44, $46, $48, $4A, $4C, $4E, $50, $52, $54, $56, $58, $5A, $5C, $5E, $60, $62, $64, $66, $68, $6A, $6C, $6E, $70, $72, $74, $76, $78, $7A, $7C, $7E, $80, $82, $84, $86, $88, $8A, $8C, $8E, $90, $92, $94, $96, $98, $9A, $9C, $9E, $A0, $A2, $A4, $A6, $A8, $AA, $AC, $AE, $B0, $B2, $B4, $B6, $B8, $BA, $BC, $BE, $C0, $C2, $C4, $C6, $C8, $CA, $CC, $CE, $D0, $D2, $D4, $D6, $D8, $DA, $DC, $DE, $E0, $E2, $E4, $E6, $E8, $EA, $EC, $EE, $F0, $F2, $F4, $F6, $F8, $FA, $FC, $FE, $1B, $19, $1F, $1D, $13, $11, $17, $15, $0B, $09, $0F, $0D, $03, $01, $07, $05, $3B, $39, $3F, $3D, $33, $31, $37, $35, $2B, $29, $2F, $2D, $23, $21, $27, $25, $5B, $59, $5F, $5D, $53, $51, $57, $55, $4B, $49, $4F, $4D, $43, $41, $47, $45, $7B, $79, $7F, $7D, $73, $71, $77, $75, $6B, $69, $6F, $6D, $63, $61, $67, $65, $9B, $99, $9F, $9D, $93, $91, $97, $95, $8B, $89, $8F, $8D, $83, $81, $87, $85, $BB, $B9, $BF, $BD, $B3, $B1, $B7, $B5, $AB, $A9, $AF, $AD, $A3, $A1, $A7, $A5, $DB, $D9, $DF, $DD, $D3, $D1, $D7, $D5, $CB, $C9, $CF, $CD, $C3, $C1, $C7, $C5, $FB, $F9, $FF, $FD, $F3, $F1, $F7, $F5, $EB, $E9, $EF, $ED, $E3, $E1, $E7, $E5 ), ( // fx03 --- Times 03 Table. $00, $03, $06, $05, $0C, $0F, $0A, $09, $18, $1B, $1E, $1D, $14, $17, $12, $11, $30, $33, $36, $35, $3C, $3F, $3A, $39, $28, $2B, $2E, $2D, $24, $27, $22, $21, $60, $63, $66, $65, $6C, $6F, $6A, $69, $78, $7B, $7E, $7D, $74, $77, $72, $71, $50, $53, $56, $55, $5C, $5F, $5A, $59, $48, $4B, $4E, $4D, $44, $47, $42, $41, $C0, $C3, $C6, $C5, $CC, $CF, $CA, $C9, $D8, $DB, $DE, $DD, $D4, $D7, $D2, $D1, $F0, $F3, $F6, $F5, $FC, $FF, $FA, $F9, $E8, $EB, $EE, $ED, $E4, $E7, $E2, $E1, $A0, $A3, $A6, $A5, $AC, $AF, $AA, $A9, $B8, $BB, $BE, $BD, $B4, $B7, $B2, $B1, $90, $93, $96, $95, $9C, $9F, $9A, $99, $88, $8B, $8E, $8D, $84, $87, $82, $81, $9B, $98, $9D, $9E, $97, $94, $91, $92, $83, $80, $85, $86, $8F, $8C, $89, $8A, $AB, $A8, $AD, $AE, $A7, $A4, $A1, $A2, $B3, $B0, $B5, $B6, $BF, $BC, $B9, $BA, $FB, $F8, $FD, $FE, $F7, $F4, $F1, $F2, $E3, $E0, $E5, $E6, $EF, $EC, $E9, $EA, $CB, $C8, $CD, $CE, $C7, $C4, $C1, $C2, $D3, $D0, $D5, $D6, $DF, $DC, $D9, $DA, $5B, $58, $5D, $5E, $57, $54, $51, $52, $43, $40, $45, $46, $4F, $4C, $49, $4A, $6B, $68, $6D, $6E, $67, $64, $61, $62, $73, $70, $75, $76, $7F, $7C, $79, $7A, $3B, $38, $3D, $3E, $37, $34, $31, $32, $23, $20, $25, $26, $2F, $2C, $29, $2A, $0B, $08, $0D, $0E, $07, $04, $01, $02, $13, $10, $15, $16, $1F, $1C, $19, $1A ), ( // fx09 --- Times 09 Table. $00, $09, $12, $1B, $24, $2D, $36, $3F, $48, $41, $5A, $53, $6C, $65, $7E, $77, $90, $99, $82, $8B, $B4, $BD, $A6, $AF, $D8, $D1, $CA, $C3, $FC, $F5, $EE, $E7, $3B, $32, $29, $20, $1F, $16, $0D, $04, $73, $7A, $61, $68, $57, $5E, $45, $4C, $AB, $A2, $B9, $B0, $8F, $86, $9D, $94, $E3, $EA, $F1, $F8, $C7, $CE, $D5, $DC, $76, $7F, $64, $6D, $52, $5B, $40, $49, $3E, $37, $2C, $25, $1A, $13, $08, $01, $E6, $EF, $F4, $FD, $C2, $CB, $D0, $D9, $AE, $A7, $BC, $B5, $8A, $83, $98, $91, $4D, $44, $5F, $56, $69, $60, $7B, $72, $05, $0C, $17, $1E, $21, $28, $33, $3A, $DD, $D4, $CF, $C6, $F9, $F0, $EB, $E2, $95, $9C, $87, $8E, $B1, $B8, $A3, $AA, $EC, $E5, $FE, $F7, $C8, $C1, $DA, $D3, $A4, $AD, $B6, $BF, $80, $89, $92, $9B, $7C, $75, $6E, $67, $58, $51, $4A, $43, $34, $3D, $26, $2F, $10, $19, $02, $0B, $D7, $DE, $C5, $CC, $F3, $FA, $E1, $E8, $9F, $96, $8D, $84, $BB, $B2, $A9, $A0, $47, $4E, $55, $5C, $63, $6A, $71, $78, $0F, $06, $1D, $14, $2B, $22, $39, $30, $9A, $93, $88, $81, $BE, $B7, $AC, $A5, $D2, $DB, $C0, $C9, $F6, $FF, $E4, $ED, $0A, $03, $18, $11, $2E, $27, $3C, $35, $42, $4B, $50, $59, $66, $6F, $74, $7D, $A1, $A8, $B3, $BA, $85, $8C, $97, $9E, $E9, $E0, $FB, $F2, $CD, $C4, $DF, $D6, $31, $38, $23, $2A, $15, $1C, $07, $0E, $79, $70, $6B, $62, $5D, $54, $4F, $46 ), ( // fx0B --- Times 0B Table. $00, $0B, $16, $1D, $2C, $27, $3A, $31, $58, $53, $4E, $45, $74, $7F, $62, $69, $B0, $BB, $A6, $AD, $9C, $97, $8A, $81, $E8, $E3, $FE, $F5, $C4, $CF, $D2, $D9, $7B, $70, $6D, $66, $57, $5C, $41, $4A, $23, $28, $35, $3E, $0F, $04, $19, $12, $CB, $C0, $DD, $D6, $E7, $EC, $F1, $FA, $93, $98, $85, $8E, $BF, $B4, $A9, $A2, $F6, $FD, $E0, $EB, $DA, $D1, $CC, $C7, $AE, $A5, $B8, $B3, $82, $89, $94, $9F, $46, $4D, $50, $5B, $6A, $61, $7C, $77, $1E, $15, $08, $03, $32, $39, $24, $2F, $8D, $86, $9B, $90, $A1, $AA, $B7, $BC, $D5, $DE, $C3, $C8, $F9, $F2, $EF, $E4, $3D, $36, $2B, $20, $11, $1A, $07, $0C, $65, $6E, $73, $78, $49, $42, $5F, $54, $F7, $FC, $E1, $EA, $DB, $D0, $CD, $C6, $AF, $A4, $B9, $B2, $83, $88, $95, $9E, $47, $4C, $51, $5A, $6B, $60, $7D, $76, $1F, $14, $09, $02, $33, $38, $25, $2E, $8C, $87, $9A, $91, $A0, $AB, $B6, $BD, $D4, $DF, $C2, $C9, $F8, $F3, $EE, $E5, $3C, $37, $2A, $21, $10, $1B, $06, $0D, $64, $6F, $72, $79, $48, $43, $5E, $55, $01, $0A, $17, $1C, $2D, $26, $3B, $30, $59, $52, $4F, $44, $75, $7E, $63, $68, $B1, $BA, $A7, $AC, $9D, $96, $8B, $80, $E9, $E2, $FF, $F4, $C5, $CE, $D3, $D8, $7A, $71, $6C, $67, $56, $5D, $40, $4B, $22, $29, $34, $3F, $0E, $05, $18, $13, $CA, $C1, $DC, $D7, $E6, $ED, $F0, $FB, $92, $99, $84, $8F, $BE, $B5, $A8, $A3 ), ( // fx0D --- Times 0D Table. $00, $0D, $1A, $17, $34, $39, $2E, $23, $68, $65, $72, $7F, $5C, $51, $46, $4B, $D0, $DD, $CA, $C7, $E4, $E9, $FE, $F3, $B8, $B5, $A2, $AF, $8C, $81, $96, $9B, $BB, $B6, $A1, $AC, $8F, $82, $95, $98, $D3, $DE, $C9, $C4, $E7, $EA, $FD, $F0, $6B, $66, $71, $7C, $5F, $52, $45, $48, $03, $0E, $19, $14, $37, $3A, $2D, $20, $6D, $60, $77, $7A, $59, $54, $43, $4E, $05, $08, $1F, $12, $31, $3C, $2B, $26, $BD, $B0, $A7, $AA, $89, $84, $93, $9E, $D5, $D8, $CF, $C2, $E1, $EC, $FB, $F6, $D6, $DB, $CC, $C1, $E2, $EF, $F8, $F5, $BE, $B3, $A4, $A9, $8A, $87, $90, $9D, $06, $0B, $1C, $11, $32, $3F, $28, $25, $6E, $63, $74, $79, $5A, $57, $40, $4D, $DA, $D7, $C0, $CD, $EE, $E3, $F4, $F9, $B2, $BF, $A8, $A5, $86, $8B, $9C, $91, $0A, $07, $10, $1D, $3E, $33, $24, $29, $62, $6F, $78, $75, $56, $5B, $4C, $41, $61, $6C, $7B, $76, $55, $58, $4F, $42, $09, $04, $13, $1E, $3D, $30, $27, $2A, $B1, $BC, $AB, $A6, $85, $88, $9F, $92, $D9, $D4, $C3, $CE, $ED, $E0, $F7, $FA, $B7, $BA, $AD, $A0, $83, $8E, $99, $94, $DF, $D2, $C5, $C8, $EB, $E6, $F1, $FC, $67, $6A, $7D, $70, $53, $5E, $49, $44, $0F, $02, $15, $18, $3B, $36, $21, $2C, $0C, $01, $16, $1B, $38, $35, $22, $2F, $64, $69, $7E, $73, $50, $5D, $4A, $47, $DC, $D1, $C6, $CB, $E8, $E5, $F2, $FF, $B4, $B9, $AE, $A3, $80, $8D, $9A, $97 ), ( // fx0E --- Times 0E Table. $00, $0E, $1C, $12, $38, $36, $24, $2A, $70, $7E, $6C, $62, $48, $46, $54, $5A, $E0, $EE, $FC, $F2, $D8, $D6, $C4, $CA, $90, $9E, $8C, $82, $A8, $A6, $B4, $BA, $DB, $D5, $C7, $C9, $E3, $ED, $FF, $F1, $AB, $A5, $B7, $B9, $93, $9D, $8F, $81, $3B, $35, $27, $29, $03, $0D, $1F, $11, $4B, $45, $57, $59, $73, $7D, $6F, $61, $AD, $A3, $B1, $BF, $95, $9B, $89, $87, $DD, $D3, $C1, $CF, $E5, $EB, $F9, $F7, $4D, $43, $51, $5F, $75, $7B, $69, $67, $3D, $33, $21, $2F, $05, $0B, $19, $17, $76, $78, $6A, $64, $4E, $40, $52, $5C, $06, $08, $1A, $14, $3E, $30, $22, $2C, $96, $98, $8A, $84, $AE, $A0, $B2, $BC, $E6, $E8, $FA, $F4, $DE, $D0, $C2, $CC, $41, $4F, $5D, $53, $79, $77, $65, $6B, $31, $3F, $2D, $23, $09, $07, $15, $1B, $A1, $AF, $BD, $B3, $99, $97, $85, $8B, $D1, $DF, $CD, $C3, $E9, $E7, $F5, $FB, $9A, $94, $86, $88, $A2, $AC, $BE, $B0, $EA, $E4, $F6, $F8, $D2, $DC, $CE, $C0, $7A, $74, $66, $68, $42, $4C, $5E, $50, $0A, $04, $16, $18, $32, $3C, $2E, $20, $EC, $E2, $F0, $FE, $D4, $DA, $C8, $C6, $9C, $92, $80, $8E, $A4, $AA, $B8, $B6, $0C, $02, $10, $1E, $34, $3A, $28, $26, $7C, $72, $60, $6E, $44, $4A, $58, $56, $37, $39, $2B, $25, $0F, $01, $13, $1D, $47, $49, $5B, $55, $7F, $71, $63, $6D, $D7, $D9, $CB, $C5, $EF, $E1, $F3, $FD, $A7, $A9, $BB, $B5, $9F, $91, $83, $8D ) ); /// END FRAGMENT --- type TMatrix = array[ {product byte index:}0..3, {factor byte index:}0..3 ] of TMixColsFactor; const MixColumsMatrix: TMatrix = ( // Refer page 18 of the standard. (fx02, fx03, fx01, fx01), (fx01, fx02, fx03, fx01), (fx01, fx01, fx02, fx03), (fx03, fx01, fx01, fx02)); InvMixColumsMatrix: TMatrix = ( // Refer page 23 of the standard. (fx0e, fx0b, fx0d, fx09), (fx09, fx0e, fx0b, fx0d), (fx0d, fx09, fx0e, fx0b), (fx0b, fx0d, fx09, fx0e)); const S_Box: array[ 0..255 ] of byte = ( $63, $7c, $77, $7b, $f2, $6b, $6f, $c5, $30, $01, $67, $2b, $fe, $d7, $ab, $76, $ca, $82, $c9, $7d, $fa, $59, $47, $f0, $ad, $d4, $a2, $af, $9c, $a4, $72, $c0, $b7, $fd, $93, $26, $36, $3f, $f7, $cc, $34, $a5, $e5, $f1, $71, $d8, $31, $15, $04, $c7, $23, $c3, $18, $96, $05, $9a, $07, $12, $80, $e2, $eb, $27, $b2, $75, $09, $83, $2c, $1a, $1b, $6e, $5a, $a0, $52, $3b, $d6, $b3, $29, $e3, $2f, $84, $53, $d1, $00, $ed, $20, $fc, $b1, $5b, $6a, $cb, $be, $39, $4a, $4c, $58, $cf, $d0, $ef, $aa, $fb, $43, $4d, $33, $85, $45, $f9, $02, $7f, $50, $3c, $9f, $a8, $51, $a3, $40, $8f, $92, $9d, $38, $f5, $bc, $b6, $da, $21, $10, $ff, $f3, $d2, $cd, $0c, $13, $ec, $5f, $97, $44, $17, $c4, $a7, $7e, $3d, $64, $5d, $19, $73, $60, $81, $4f, $dc, $22, $2a, $90, $88, $46, $ee, $b8, $14, $de, $5e, $0b, $db, $e0, $32, $3a, $0a, $49, $06, $24, $5c, $c2, $d3, $ac, $62, $91, $95, $e4, $79, $e7, $c8, $37, $6d, $8d, $d5, $4e, $a9, $6c, $56, $f4, $ea, $65, $7a, $ae, $08, $ba, $78, $25, $2e, $1c, $a6, $b4, $c6, $e8, $dd, $74, $1f, $4b, $bd, $8b, $8a, $70, $3e, $b5, $66, $48, $03, $f6, $0e, $61, $35, $57, $b9, $86, $c1, $1d, $9e, $e1, $f8, $98, $11, $69, $d9, $8e, $94, $9b, $1e, $87, $e9, $ce, $55, $28, $df, $8c, $a1, $89, $0d, $bf, $e6, $42, $68, $41, $99, $2d, $0f, $b0, $54, $bb, $16); var InvS_Box: array[ 0..255 ] of byte; procedure InitUnit_AES; var Idx: byte; begin for Idx := 0 to 255 do InvS_Box[ S_Box[ Idx]] := Idx end; procedure DoneUnit_AES; begin end; function MulVector( const Matrix: TMatrix; Vector: uint32): uint32; var Row, Col: integer; Temp: byte; begin for Row := 0 to 3 do begin Temp := 0; for Col := 0 to 3 do Temp := Temp xor GF2_8_TimesTables[ Matrix[ Row, Col], longrec( Vector).Bytes[ Col] ]; longrec( result).Bytes[ Row] := Temp end end; type TAESKey = class( TSymetricKey) private FKeySize: integer; // 128, 192 or 256 Nk: integer; // 4, 6 or 8 Nr: integer; // 10, 12 or 14 FCols: integer; // = Nb * (Nr+1) = 44, 52, 60 w: array [ 0 .. 59 ] of uint32; // Logical length is 0 .. Nb*(Nr+1)-1 procedure ExpandKey; public constructor Create( GenSeed: TStream; AES1: TAES); constructor LoadFromStream( Store: TStream; AES1: TAES); destructor Destroy; override; procedure SaveToStream( Stream: TStream); override; procedure Burn; override; end; TAESBlockCodec = class( TInterfacedObject, IBlockCodec) private FCipher: TAES; FKey: TAESKey; State: array[ 0..3 ] of uint32; Nr: integer; procedure MulMatrix( const Matrix: TMatrix); procedure Shift3rdRow; procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); procedure Reset; procedure Burn; procedure AddRoundKey( Column: integer); procedure SubBytes; procedure ShiftRows; procedure MixColumns; procedure InvSubBytes; procedure InvShiftRows; procedure InvMixColumns; constructor Create( Cipher1: TAES; Key1: TAESKey); destructor Destroy; override; end; { TAES } function TAES.BlockSize: integer; begin result := 128 end; function TAES.ControlObject: TObject; begin result := self end; constructor TAES.Create( KeySize1: integer); begin FKeySize := KeySize1; if (FKeySize <> 128) and (FKeySize <> 192) and (FKeySize <> 256) then raise Exception.Create( 'Invalid key size for AES.') end; function TAES.DefinitionURL: string; begin result := 'http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf' end; function TAES.DisplayName: string; begin result := 'AES-%d' end; function TAES.Features: TAlgorithmicFeatureSet; begin result := [afOpenSourceSoftware, afDisplayNameOnKeySize]; if FKeySize = 256 then Include( result, afStar) end; function TAES.KeySize: integer; begin result := FKeySize end; function TAES.ProgId: string; begin result := Format( AES_ProgId, [FKeySize]) end; function TAES.SeedByteSize: integer; begin result := FKeySize div 8 end; function TAES.SelfTest_Key: TBytes; // Refer appendix C. begin case FKeySize of 128: result := AnsiBytesOf('000102030405060708090a0b0c0d0e0f'); 192: result := AnsiBytesOf('000102030405060708090a0b0c0d0e0f1011121314151617'); 256: result := AnsiBytesOf('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'); end end; function TAES.SelfTest_Plaintext: TBytes; // Refer appendix C. begin result := AnsiBytesOf('00112233445566778899aabbccddeeff') end; function TAES.SelfTest_Ciphertext: TBytes; // Refer appendix C. begin case FKeySize of 128: result := AnsiBytesOf('69c4e0d86a7b0430d8cdb78070b4c55a'); 192: result := AnsiBytesOf('dda97ca4864cdfe06eaf70a0ec0d7191'); 256: result := AnsiBytesOf('8ea2b7ca516745bfeafc49904b496089'); end; end; function TAES.WikipediaReference: string; begin result := 'Advanced_Encryption_Standard' end; function TAES.GenerateKey( Seed: TStream): TSymetricKey; begin result := TAESKey.Create( Seed, self) end; function TAES.LoadKeyFromStream( Store: TStream): TSymetricKey; begin result := TAESKey.LoadFromStream( Store, self) end; function TAES.MakeBlockCodec( Key: TSymetricKey): IBlockCodec; begin result := TAESBlockCodec.Create( self, Key as TAESKey) end; { TAESKey } procedure TAESKey.Burn; begin FillChar( w, SizeOf( W), 0) end; //const usingTestVectors = False; constructor TAESKey.Create( GenSeed: TStream; AES1: TAES); begin FKeySize := AES1.FKeySize; // 128, 192 or 256 case FKeySize of 128: begin Nk := 4; Nr := 10 end; 192: begin Nk := 6; Nr := 12 end; 256: begin Nk := 8; Nr := 14 end; end; FCols := 4 * (Nr+1); // 44, 52, 60 GenSeed.ReadBuffer( w, FKeySize div 8); {if usingTestVectors then begin case FKeySize of 128: begin w[0] := $16157e2b; // In appendix A, this is written as bigendien, // but our integers are little-endien so this source // appears to reverse the byte order. w[1] := $a6d2ae28; w[2] := $8815f7ab; w[3] := $3c4fcf09; end; 192: begin w[0] := $f7b0738e; w[1] := $52640eda; w[2] := $2bf310c8; w[3] := $e5799080; w[4] := $d2eaf862; w[5] := $7b6b2c52; end; 256: begin w[0] := $10eb3d60; w[1] := $be71ca15; w[2] := $f0ae732b; w[3] := $81777d85; w[4] := $072c351f; w[5] := $d708613b; w[6] := $a310982d; w[7] := $f4df1409; end; end; end; } ExpandKey end; destructor TAESKey.Destroy; begin Burn; inherited end; function SubWord( Value: uint32): uint32; var j: integer; begin for j := 0 to 3 do longrec( result).Bytes[j] := S_Box[ longrec( Value).Bytes[j]] end; function InvSubWord( Value: uint32): uint32; var j: integer; begin for j := 0 to 3 do longrec( result).Bytes[j] := InvS_Box[ longrec( Value).Bytes[j]] end; const Rcon: array[ 1..10 ] of uint32 = ( $00000001, // In big-endien this is 0x01000000 $00000002, $00000004, $00000008, $00000010, $00000020, $00000040, $00000080, $0000001b, $00000036); procedure TAESKey.ExpandKey; var i: integer; Temp: uint32; SubWord_Frequency: integer; isNewExpandRound: boolean; begin if FKeySize <> 256 then SubWord_Frequency := Nk else SubWord_Frequency := 4; for i := Nk to FCols - 1 do begin Temp := w[ i - 1 ]; isNewExpandRound := (i mod Nk) = 0; if isNewExpandRound then Temp := (Temp shr 8) or (Temp shl 24); if (i mod SubWord_Frequency) = 0 then Temp := SubWord( Temp) ; if isNewExpandRound then Temp := Temp XOR Rcon[ i div Nk ]; w[i] := Temp XOR w[ i - Nk ] end end; constructor TAESKey.LoadFromStream( Store: TStream; AES1: TAES); begin FKeySize := AES1.FKeySize; // 128, 192 or 256 case FKeySize of 128: begin Nk := 4; Nr := 10 end; 192: begin Nk := 6; Nr := 12 end; 256: begin Nk := 8; Nr := 14 end; end; FCols := 4 * (Nr+1); // 44, 52, 60 Store.ReadBuffer( w, FKeySize div 8); ExpandKey end; procedure TAESKey.SaveToStream( Stream: TStream); begin Stream.WriteBuffer( w, FKeySize div 8) end; { TAESBlockCodec } procedure TAESBlockCodec.Burn; begin FillChar( State, SizeOf( State), 0) end; constructor TAESBlockCodec.Create( Cipher1: TAES; Key1: TAESKey); begin FCipher := Cipher1; FKey := Key1; FillChar( State, SizeOf( State), 0); case FKey.FKeySize of 128: Nr := 10; 192: Nr := 12; 256: Nr := 14; end end; procedure TAESBlockCodec.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream); var i: integer; begin Plaintext.Position := 0; Plaintext.Read( State, SizeOf( State)); AddRoundKey( 0); for i := 1 to Nr do begin SubBytes; ShiftRows; if i <> Nr then MixColumns; AddRoundKey( i * 4) end; Ciphertext.Position := 0; Ciphertext.Write( State, SizeOf( State)) end; procedure TAESBlockCodec.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream); var i: integer; begin Ciphertext.Position := 0; Ciphertext.Read( State, SizeOf( State)); for i := Nr downto 1 do begin AddRoundKey( i * 4); if i <> Nr then InvMixColumns; InvShiftRows; InvSubBytes end; AddRoundKey( 0); Plaintext.Position := 0; Plaintext.Write( State, SizeOf( State)) end; destructor TAESBlockCodec.Destroy; begin Burn; inherited end; procedure TAESBlockCodec.Reset; begin end; procedure TAESBlockCodec.AddRoundKey( Column: integer); var j: integer; begin for j := 0 to 3 do State[j] := State[j] XOR FKey.w[ Column + j] end; procedure TAESBlockCodec.MulMatrix( const Matrix: TMatrix); var j: integer; begin for j := 0 to 3 do State[j] := MulVector( Matrix, State[ j]) end; procedure TAESBlockCodec.MixColumns; begin MulMatrix( MixColumsMatrix) end; procedure TAESBlockCodec.InvMixColumns; begin MulMatrix( InvMixColumsMatrix) end; procedure TAESBlockCodec.InvSubBytes; var j: integer; begin for j := 0 to 3 do State[j] := InvSubWord( State[j]) end; procedure TAESBlockCodec.Shift3rdRow; var Mask, Temp: uint32; begin Mask := $00FF0000; // 3rd byte. Temp := State[0] and Mask; State[0] := (State[0] and (not Mask)) or (State[2] and Mask); State[2] := (State[2] and (not Mask)) or Temp; Temp := State[1] and Mask; State[1] := (State[1] and (not Mask)) or (State[3] and Mask); State[3] := (State[3] and (not Mask)) or Temp; end; procedure TAESBlockCodec.ShiftRows; var j: integer; Mask, Temp: uint32; begin // Shift 2nd row left. Mask := $0000FF00; // 2nd LS byte. Temp := State[0] and Mask; for j := 0 to 2 do State[j] := (State[j] and (not Mask)) or (State[j+1] and Mask); State[3] := (State[3] and (not Mask)) or Temp; Shift3rdRow; // Shift 4th row right. Mask := $FF000000; // MS byte. Temp := State[3] and Mask; for j := 3 downto 1 do State[j] := (State[j] and (not Mask)) or (State[j-1] and Mask); State[0] := (State[0] and (not Mask)) or Temp end; procedure TAESBlockCodec.InvShiftRows; var j: integer; Mask, Temp: uint32; begin // Shift 2nd row right. Mask := $0000FF00; // 2nd LS byte. Temp := State[3] and Mask; for j := 3 downto 1 do State[j] := (State[j] and (not Mask)) or (State[j-1] and Mask); State[0] := (State[0] and (not Mask)) or Temp; Shift3rdRow; // Shift 4th row left. Mask := $FF000000; // MS byte. Temp := State[0] and Mask; for j := 0 to 2 do State[j] := (State[j] and (not Mask)) or (State[j+1] and Mask); State[3] := (State[3] and (not Mask)) or Temp end; procedure TAESBlockCodec.SubBytes; var j: integer; begin for j := 0 to 3 do State[j] := SubWord( State[j]) end; initialization InitUnit_AES; finalization DoneUnit_AES; end.
{ An array with capacity, grows in chunks. Like CapString. Much more efficient than regular dynamic arrays for large adds. To change to an array other than array of "byte" just copy this unit into another file and change byte to the other type. Copyright 2020 Lars Olson http://z505.com } unit CapArray; {$IFDEF fpc} {$MODE objfpc} {$H+} {$ENDIF} interface uses SysUtils, Dialogs; // DEBUG type PCapArray = ^TCapArray; TCapArray = record ArrayLen: integer; // array length, not actual setlengthed buffer size GrowBy: integer; // grow the array in chunks of what size Data: array of byte; // array data end; procedure ResetBuf(buf: PCapArray); overload; procedure ResetBuf(buf: PCapArray; GrowBy: integer); overload; procedure AddByte(b: byte; buf: PCapArray); procedure AddArray(const a: array of byte; buf: PCapArray); procedure EndUpdate(buf: PCapArray); procedure Delete(buf: PCapArray; startat: integer; count: integer); function CapArrayToAnsistring(buf: PCapArray): ansistring; { function EndsChar(b: byte; buf: PCapArray): boolean; function EndsArray(a: array of byte; buf: PCapArray): boolean; } const DEFAULT_CHUNK_SIZE = 1024; implementation //*done checks whether ends with specified byte (in string area, not in extra buffer zone) function EndsByte(b: byte; buf: PCapArray): boolean; begin result:= false; if buf^.arraylen < 1 then exit; if buf^.data[buf^.ArrayLen-1] = b then result:= true; end; //*done checks whether ends with specified array (in bytes area, not in extra buffer zone) function EndsArray(a: array of byte; buf: PCapArray): boolean; var StartAt: integer; slen: integer; cnt: integer; i: integer; begin result:= false; if buf^.arraylen < 1 then exit; slen:= length(a); if slen < 1 then exit; // get end piece of capstring to analyze StartAt:= (buf^.ArrayLen - slen) + 1; // i.e. find "ing" in "testing".. ing is at position 5 7-3 = 4 + 1 = 5 cnt:= 0; result:= true; // string matches unless found otherwise in char by char check for i:= StartAt to buf^.ArrayLen do begin inc(cnt); if buf^.data[i-1] <> a[cnt-1] then result:= false; end; end; {*done } procedure Delete(buf: PCapArray; StartAt: integer; count: integer); begin if buf^.arraylen < 1 then exit; // if buf^.data = '' then exit; system.delete(buf^.data, startat, count); buf^.ArrayLen:= buf^.ArrayLen - count; end; {*done call this to reset the data structure to zero and the default growby value } procedure ResetBuf(buf: PCapArray); begin // buf^.Data:= ''; buf^.ArrayLen:= 0; buf^.GrowBy:= DEFAULT_CHUNK_SIZE; end; {*done same as above but with custom growby } procedure ResetBuf(buf: PCapArray; GrowBy: integer); begin // buf^.data:= ''; buf^.ArrayLen:= 0; if buf^.GrowBy < 1 then buf^.GrowBy := DEFAULT_CHUNK_SIZE else buf^.GrowBy := GrowBy; end; {*done private function, grows in chunks automatically only when absolutely needs to } procedure Grow(buf: PCapArray; AddLen: integer); var growmult: integer; begin if addlen <= buf^.GrowBy then // only grow one chunk if there is room for data incoming setlength(buf^.Data, length(buf^.Data) + buf^.growby) else begin // must grow in more than one chunk since data is too large to fit growmult:= (addlen div buf^.GrowBy) + 1; // div discards the remainder so we must add 1 to make room for that extra remainder setlength(buf^.data, length(buf^.Data) + growmult); end; end; { add single byte to caparray } procedure AddByte(b: byte; buf: PCapArray); var newlen: integer; const clen = 1; begin newlen:= buf^.ArrayLen + clen; if newlen > length(buf^.Data) then Grow(buf, clen); buf^.Data[newlen]:= b; // concat buf^.ArrayLen:= newlen; // string length stored, but not actual buffer length end; {*done add existing string to capstring } procedure AddArray(const a: array of byte; buf: PCapArray); var newlen: integer; slen: integer; oldlen: integer; begin slen:= length(a); if slen = 0 then exit; // do nothing oldlen:= length(buf^.Data); newlen:= buf^.ArrayLen + slen; if newlen > oldlen then Grow(buf, slen); // debugln('debug: wslen: ' + inttostr(wslen) ); { for i:= 1 to slen do buf^.data[(buf^.strlen + i)]:= s[i]; } Move(a[0], buf^.Data[buf^.ArrayLen], slen * SizeOf(a[0])); buf^.ArrayLen:= newlen; // string length stored, but not actual buffer length end; {*done endupdate MUST be called after doing your work with the string, this sets the string to the correct length (trims extra buffer spacing at end) } procedure EndUpdate(buf: PCapArray); begin if buf^.ArrayLen < 1 then exit; // if buf^.Data = '' then exit; SetLength(buf^.Data, buf^.ArrayLen); end; function CapArrayToAnsistring(buf: PCapArray): ansistring; var len: integer; begin result := ''; len := buf^.ArrayLen; setlength(result, len); // showmessage('Array Length: '+inttostr(buf^.ArrayLen)); Move(buf^.Data[0], result[1], len); end; end.
unit normals; // VXLSE III 1.4 :: Normals redesigned to support unlimmited directions. // Normals class written by Banshee. interface uses BasicMathsTypes, NormalsConstants; const C_RES_INFINITE = -1; type TNormals = class private FResolution : integer; FPalette : PAVector3f; // Constructors procedure ResetPalette; //Gets function ReadNormal(_id : longword): TVector3f; // Sets procedure SetPalette; procedure SetNormal(_id : longword; _normal : TVector3f); // Adds procedure AddToPalette(_normal: TVector3f); // Removes procedure RemoveFromPalette(_id : longword); // Copies procedure CopyNormalsAtPalette(_source, _dest: longword); public // Constructors constructor Create; overload; procedure Initialize; constructor Create(const _Type : integer); overload; constructor Create(const _Normals : TNormals); overload; destructor Destroy; override; procedure Clear; // Gets function GetIDFromNormal(const _vector : TVector3f): longword; overload; function GetIDFromNormal(_x, _y, _z : single): longword; overload; function GetLastID: integer; // Copies procedure Assign(const _Normals : TNormals); // Adds function AddNormal(const _Normal : TVector3f): longword; // Switch procedure SwitchNormalsType(_Type : integer); // Properties property Normal[_id : longword] : TVector3f read ReadNormal write SetNormal; default; end; PNormals = ^TNormals; // Temporary data for compatibility with the old code. var TSNormals : TNormals; RA2Normals : TNormals; CubeNormals : TNormals; implementation uses BasicFunctions, Math3d; // Constructors constructor TNormals.Create; begin Initialize; end; constructor TNormals.Create(const _Type : integer); begin FResolution := _Type; SetPalette; end; constructor TNormals.Create(const _Normals : TNormals); begin Assign(_Normals); end; procedure TNormals.Initialize; begin FResolution := C_RES_INFINITE; FPalette := nil; end; procedure TNormals.ResetPalette; begin if (FPalette <> nil) and (FResolution = C_RES_INFINITE) then begin SetLength(FPalette^,0); end; end; destructor TNormals.Destroy; begin ResetPalette; inherited Destroy; end; procedure TNormals.Clear; begin ResetPalette; end; // Gets function TNormals.ReadNormal(_id: longword): TVector3f; begin if FResolution = C_RES_INFINITE then begin if (_id <= High(FPalette^)) then Result := CopyVector((FPalette^)[_id]) else Result := SetVector(0,0,0); end else begin if (_id <= High(FPalette^)) then Result := CopyVector((FPalette^)[_id]) else Result := SetVector(0,0,0); end; end; function TNormals.GetIDFromNormal(const _vector : TVector3f): longword; var i : longword; lowerDiff, Diff : single; begin Result := AddNormal(_vector); if Result = $FFFFFFFF then begin lowerDiff := 99999; for i := Low(FPalette^) to High(FPalette^) do begin Diff := (_vector.X - (FPalette^)[i].X) * (_vector.X - (FPalette^)[i].X) + (_vector.Y - (FPalette^)[i].Y) * (_vector.Y - (FPalette^)[i].Y) + (_vector.Z - (FPalette^)[i].Z) * (_vector.Z - (FPalette^)[i].Z); if Diff < lowerDiff then begin lowerDiff := Diff; Result := i; end; end; end; end; function TNormals.GetIDFromNormal(_x, _y, _z : single): longword; begin Result := GetIDFromNormal(SetVector(_X,_Y,_Z)); end; function TNormals.GetLastID: integer; begin if FPalette <> nil then Result := High(FPalette^) else Result := -1; end; // Sets procedure TNormals.SetNormal(_id: longword; _normal: TVector3f); begin if FResolution = C_RES_INFINITE then begin if (_id <= High(FPalette^)) then begin (FPalette^)[_id].X := _Normal.X; (FPalette^)[_id].Y := _Normal.Y; (FPalette^)[_id].Z := _Normal.Z; end; end; end; procedure TNormals.SetPalette; begin if FResolution = 2 then begin FPalette := Addr(TSNormals_Table); end else if FResolution = 4 then begin FPalette := Addr(RA2Normals_Table); end else if FResolution = 6 then begin FPalette := Addr(CubeNormals_Table); end else if FResolution = 7 then begin FPalette := Addr(FaceNormals_Table); end else if FResolution = 8 then begin FPalette := Addr(VertAndEdgeNormals_Table); end else Initialize; end; // Copies procedure TNormals.Assign(const _Normals: TNormals); var i : longword; begin FResolution := _Normals.FResolution; if High(_Normals.FPalette^) > 0 then begin SetLength(FPalette^,High(_Normals.FPalette^)+1); for i := Low(FPalette^) to High(FPalette^) do begin (FPalette^)[i].X := (_Normals.FPalette^)[i].X; (FPalette^)[i].Y := (_Normals.FPalette^)[i].Y; (FPalette^)[i].Z := (_Normals.FPalette^)[i].Z; end; end else FPalette := nil; end; procedure TNormals.CopyNormalsAtPalette(_source, _dest: longword); begin (FPalette^)[_dest].X := (FPalette^)[_source].X; (FPalette^)[_dest].Y := (FPalette^)[_source].Y; (FPalette^)[_dest].Z := (FPalette^)[_source].Z; end; // Adds procedure TNormals.AddToPalette(_normal: TVector3f); begin if FPalette <> nil then begin SetLength(FPalette^,High(FPalette^)+2); end else begin FPalette := new(PAVector3f); SetLength(FPalette^,1); end; (FPalette^)[High(FPalette^)].X := _Normal.X; (FPalette^)[High(FPalette^)].Y := _Normal.Y; (FPalette^)[High(FPalette^)].Z := _Normal.Z; end; function TNormals.AddNormal(const _Normal : TVector3f): longword; var i : integer; begin Result := $FFFFFFFF; if FResolution = C_RES_INFINITE then begin if FPalette <> nil then begin i := Low(FPalette^); while (i <= High(FPalette^)) do begin if (_Normal.X = (FPalette^)[i].X) and (_Normal.Y = (FPalette^)[i].Y) and (_Normal.Z = (FPalette^)[i].Z) then begin Result := i; exit; end; inc(i); end; AddToPalette(_Normal); Result := High(FPalette^); end else begin AddToPalette(_Normal); Result := High(FPalette^); end; end; end; // Removes procedure TNormals.RemoveFromPalette(_id: Cardinal); var i : integer; begin if FPalette <> nil then begin if _id < High(FPalette^) then begin i := _id + 1; while i < High(FPalette^) do begin CopyNormalsAtPalette(i+1,i); inc(i); end; SetLength(FPalette^,High(FPalette^)); end else begin if _id = 0 then begin dispose(FPalette); FPalette := nil; end else begin SetLength(FPalette^,High(FPalette^)); end; end; end; end; // Switch procedure TNormals.SwitchNormalsType(_Type : integer); begin if _Type <> FResolution then begin ResetPalette; FResolution := _Type; SetPalette; end; end; // Temporary data for compatibility with the old code. begin TSNormals := TNormals.Create(2); RA2Normals := TNormals.Create(4); CubeNormals := TNormals.Create(6); end.
{ Laz-Model Copyright (C) 2002 Eldean AB, Peter Söderman, Ville Krumlinde Portions (C) 2016 Peter Dyson. Initial Lazarus port This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uClassTreeEditIntegrator; {$mode objfpc}{$H+} interface uses Controls, uViewIntegrator, uModel, uFeedback, uClassTreeEditForm; type { TClassTreeEditIntegrator } TClassTreeEditIntegrator = class(TViewIntegrator) private MyForm: TClassTreeEditForm; public constructor Create(om: TObjectModel; AParent: TWinControl; AFeedback : IEldeanFeedback = nil); override; destructor Destroy; override; procedure CurrentEntityChanged; override; end; implementation { TClassTreeEditIntegrator } constructor TClassTreeEditIntegrator.Create(om: TObjectModel; AParent: TWinControl; AFeedback: IEldeanFeedback); begin inherited Create(om, AParent, AFeedback); MyForm := ClassTreeEditForm; MyForm.Model := om; end; destructor TClassTreeEditIntegrator.Destroy; begin inherited Destroy; end; procedure TClassTreeEditIntegrator.CurrentEntityChanged; begin inherited CurrentEntityChanged; if MyForm.Visible then MyForm.ModelObject := CurrentEntity; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, StdCtrls, aiOgl, OpenGL, Math; type TMyObject = class(TglObject) public // добавим перенос каждого объекта, чтобы сцена была в начале координат procedure Draw; override; end; TMyScene = class(TglScene) public // переопределяем функцию, чтобы указать, с какими объектами будем работать function glObject: TglObject; override; procedure Draw; override; end; TMainForm = class(TForm) ToolBar2: TToolBar; Button1: TButton; OpenDialog: TOpenDialog; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private glScene: TMyScene; Back, Left, Right, Top, Bottom: TglObject; procedure LoadFile(FileName: string); procedure LookAtComput; procedure RoomDraw; procedure Idle (Sender: TObject; var Done: Boolean); public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.DFM} var Mx, Mn: TVector; StartTime, LastTime: dWord; Light1, Light2 : gluQuadricObj; D, Ang1, Ang2: Extended; procedure TMyObject.Draw; begin // перемещаем каждый объект, чтобы сцена была в центре glTranslatef(-(Mn.X + Mx.X)/2, -(Mn.Y + Mx.Y)/2, -(Mn.Z + Mx.Z)/2); inherited; end; function TMyScene.glObject: TglObject; begin Result:= TMyObject.Create; // будем работать с объектами TMyObject end; procedure TMainForm.Button1Click(Sender: TObject); begin if OpenDialog.Execute then LoadFile(OpenDialog.FileName); end; procedure TMainForm.LookAtComput; var D2: single; begin with CurScene do begin D2:= Abs(Mx.X - Mn.X); if Abs(Mx.Y - Mn.Y) > D2 then D2:= Abs(Mx.Y - Mn.Y); if Abs(Mx.Z - Mn.Z) > D2 then D2:= Abs(Mx.Z - Mn.Z); D2:= D2 / 2; // D2-половина наибольшего размера EyePoint:= Vector(0, 0, 1.2 * D2); // отодвинуть точку взгляда на 20% zNear:= 0.1 * D2; zFar:= 2.4 * D2; // по умолчанию направление взгляда в (0,0,-1) и вектор вверх (0,1,0), т.е. ось Y вверх end; end; function CreatePlane(Point1, Point2, Point3, Point4: TVector): TglObject; begin Result:= TglObject.Create; CurScene.AddObject(Result); with Result do begin Frozen:= True; VertexCount:= 4; Vertices[0].Vector:= Point1; Vertices[1].Vector:= Point2; Vertices[2].Vector:= Point3; Vertices[3].Vector:= Point4; FaceCount:= 2; Faces[0]:= Face(0, 1, 3); Faces[1]:= Face(1, 2, 3); FaceGroupCount:= 1; FaceGroups[0].Material:= Nil; FaceGroups[0].OriginFace:= 0; FaceGroups[0].FaceCount:= 2; GetShadow:= True; end; end; procedure TMainForm.RoomDraw; var Material1, Material2: TMaterial; i: integer; begin Mx:= glScene.Max; Mn:= glScene.Min; D:= Max(Mx.X - Mn.X, Mx.Y - Mn.Y); D:= Max(D, Mx.Z - Mn.Z); with glScene do begin EyePoint.z:= EyePoint.z + 1.5 * D; zFar:= zNear + 5*D; LightsOff; end; with glScene.Lighting do begin Enabled[0]:= True; Infinity[0]:= False; Direction[0]:= NullVector; SpotCutOff[0]:= 180; Enabled[1]:= True; Infinity[1]:= False; Direction[1]:= NullVector; SpotCutOff[1]:= 180; Diffuse[1]:= glScene.Lighting.Diffuse[0]; Specular[1]:= glScene.Lighting.Specular[0]; ModelAmbient:= RGB(255, 255, 255); end; Back:= CreatePlane(Vector(-D, -D, -D), Vector(D, -D, -D), Vector(D, D, -D), Vector(-D, D, -D)); Back.Name:= 'Back'; with Back do begin Vertices[0].U:= 0; Vertices[0].V:= 0; Vertices[1].U:= 3; Vertices[1].V:= 0; Vertices[2].U:= 3; Vertices[2].V:= 3; Vertices[3].U:= 0; Vertices[3].V:= 3; end; Left:= CreatePlane(Vector(-D, -D, -D), Vector(-D, D, -D), Vector(-D, D, D), Vector(-D, -D, D)); Left.Name:= 'Left'; with Left do begin Vertices[0].U:= 3; Vertices[0].V:= 0; Vertices[1].U:= 3; Vertices[1].V:= 3; Vertices[2].U:= 0; Vertices[2].V:= 3; Vertices[3].U:= 0; Vertices[3].V:= 0; end; Right:= CreatePlane(Vector(D, -D, -D), Vector(D, -D, D), Vector(D, D, D), Vector(D, D, -D)); Right.Name:= 'Right'; with Right do begin Vertices[0].U:= 0; Vertices[0].V:= 0; Vertices[1].U:= 3; Vertices[1].V:= 0; Vertices[2].U:= 3; Vertices[2].V:= 3; Vertices[3].U:= 0; Vertices[3].V:= 3; end; Top:= CreatePlane(Vector(-D, D, -D), Vector(D, D, -D), Vector(D, D, D), Vector(-D, D, D)); Top.Name:= 'Top'; Bottom:= CreatePlane(Vector(-D, -D, -D), Vector(-D, -D, D), Vector(D, -D, D), Vector(D, -D, -D)); Bottom.Name:= 'Bottom'; with Bottom do begin Vertices[0].U:= 0; Vertices[0].V:= 6; Vertices[1].U:= 0; Vertices[1].V:= 0; Vertices[2].U:= 6; Vertices[2].V:= 0; Vertices[3].U:= 6; Vertices[3].V:= 6; end; Material1:= glScene.Materials.NewMaterial; Material1.Texture:= glScene.Materials.NewTexture; Material1.Texture.FileName:= 'brick27.bmp'; Material2:= glScene.Materials.NewMaterial; Material2.Texture:= glScene.Materials.NewTexture; Material2.Texture.FileName:= 'Лам.jpeg'; Left.FaceGroups[0].Material:= Material1; Right.FaceGroups[0].Material:= Material1; Back.FaceGroups[0].Material:= Material1; Bottom.FaceGroups[0].Material:= Material2; StartTime:= GetTickCount; end; procedure TMainForm.LoadFile(FileName: string); begin if Assigned(glScene) then CurScene.Free; // убить старую сцену glScene:= TMyScene.Create(Self); SetCurScene(glScene); CurScene.LoadFromFile(FileName); with CurScene do begin Mx:= Max; Mn:= Min; // для ускорения, чтобы не вычислять каждый раз заново // в 3DA хранится точка взгляда, для 3DS надо вычислить if Uppercase(ExtractFileExt(FileName)) = '.3DS' then LookAtComput; RoomDraw; LookAt; // установить точку взгляда ActiveMDIChild.Caption:= ChangeFileExt(ExtractFileName(FileName), ''); GetNormals; // вычислить нормали Render; // рендеринг сцены Paint; // рисуем сцену end; end; procedure TMainForm.Idle(Sender: TObject; var Done: Boolean); var A: extended; begin Done:= False; if not Assigned(glScene) then Exit; Ang1:= (GetTickCount - StartTime) / 1000 / 20; // делает оборот за 20 секунд Ang2:= (GetTickCount - StartTime) / 1000 / 27; // делает оборот за 27 секунд glScene.Lighting.Position[0]:= Vector(cos(2 * pi * Ang1) * 0.9 * D, sin(2 * pi * Ang1) * 0.9 * D, 0); glScene.Lighting.Position[1]:= Vector(cos(2 * pi * Ang2) * 0.9 * D, 0, sin(2 * pi * Ang2) * 0.9 * D); A:= ((GetTickCount - LastTime) mod 1000) * 360 / 1000 / 10; // оборот по всем осям за 10 с glScene.Rotate(A, A, A); LastTime:= GetTickCount; glScene.Paint; end; procedure TMyScene.Draw; begin inherited; glDisable(GL_LIGHTING); glPushMatrix(); with CurScene.Lighting.Position[0] do glTranslatef(X, Y, 0); glRotatef(90, 0, 1, 0); glRotatef(-Ang1 * 360, 1, 0, 0); glColor3f(1, 1, 0); gluCylinder(Light1, D/30, 0, D/30, 12, 12); glPopMatrix(); glPushMatrix(); with CurScene.Lighting.Position[1] do glTranslatef(X, Y, 0); glRotatef(90, 0, 1, 0); glRotatef(-Ang2 * 360, 0, 1, 0); glColor3f(1, 0, 0); gluCylinder(Light2, D/30, 0, D/30, 12, 12); glPopMatrix(); glEnable(GL_LIGHTING); end; procedure TMainForm.FormCreate(Sender: TObject); begin Light1 := gluNewQuadric; Light2 := gluNewQuadric; Application.OnIdle:= Idle; end; procedure TMainForm.FormDestroy(Sender: TObject); begin gluDeleteQuadric(Light1); gluDeleteQuadric(Light2); end; end.
unit SSLDemo.RandFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TRandomFrame = class(TFrame) EditSize: TEdit; EditResult: TEdit; ButtonRandom: TButton; LabelSize: TLabel; procedure ButtonRandomClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation uses Soap.EncdDecd, OpenSSL.RandUtils; {$R *.dfm} procedure TRandomFrame.ButtonRandomClick(Sender: TObject); var Buffer: TBytes; begin Buffer := TRandUtil.GetRandomBytes(StrToInt(EditSize.Text)); EditResult.Text := string(EncodeBase64(Pointer(Buffer), Length(Buffer))); end; end.
unit uQueryDictionary; interface uses DB, DBClient, Classes; const DICTIONARY_COUNT= 4; //下面数组中的值传入dbo.usp_GetBaseTableInfo存储过程,必须与存储过程的值对应. DICTIONARYNAME: array[0..DICTIONARY_COUNT] of WideString = ('dlQueryClass' ,'dlQueryList', 'dlQueryProperty', 'dlQueryMaster', 'dlQueryDetail'); type {TDictionary} TQyDictionary=Class {* 字典表类} private FQyDictionary: array [0..DICTIONARY_COUNT] of TDataSet; function GetQyDictionary(const Index: Integer): TDataSet; procedure GetFieldText(Sender: TField; var Text: String; DisplayText: Boolean); public constructor Create(AOwner: TComponent); {* Create} destructor Destroy; override; {* Destroy} procedure CloseAllDataSet; property cds_QueryClass: TDataSet Index 0{dlQueryClass }read GetQyDictionary; property cds_QueryList: TDataSet Index 1{dlQueryList }read GetQyDictionary; property cds_QueryProperty: TDataSet Index 2{dlQueryProperty }read GetQyDictionary; property cds_QueryMaster: TDataSet Index 3{dlQueryMaster }read GetQyDictionary; property cds_QueryDetail: TDataSet Index 4{dlQueryDetail }read GetQyDictionary; end; function QyDictionary: TQyDictionary; implementation uses SysUtils, Dialogs, Controls, IdGlobal, ServerDllPub, uFNMResource, uLogin; var lDictionary: TQyDictionary; function QyDictionary: TQyDictionary; begin if lDictionary = nil then lDictionary:=TQyDictionary.Create(nil); result:=lDictionary; end; { TFNDictionary } constructor TQyDictionary.Create(AOwner: TComponent); var i: Integer; begin inherited Create; for i := 0 to DICTIONARY_COUNT do FQyDictionary[i] := nil; end; destructor TQyDictionary.Destroy; var i: Integer; begin for i := 0 to DICTIONARY_COUNT do FreeAndNil(FQyDictionary[i]); inherited; end; procedure TQyDictionary.CloseAllDataSet; var i: Integer; begin for i := 0 to DICTIONARY_COUNT do begin if FQyDictionary[i] <> nil then FQyDictionary[i].Active:=false; end end; function TQyDictionary.GeTQyDictionary(const Index: Integer): TDataSet; var i: Integer; vDataSet: OleVariant; sErrorMsg: WideString; begin if Index > DICTIONARY_COUNT then raise Exception.CreateRes(@ERR_PropertyIndex); //本句是为了去掉Delphi的警告,切不可在Try..finally..End中使用result result:=FQyDictionary[Index]; try //相应的字典已经打开则退出 if (FQyDictionary[Index] <> nil) and FQyDictionary[Index].Active then exit; ShowStatusMessage(@STA_GetDictionaryMessage, [DictionaryName[Index]]); FNMServerObj.GetQyDictionary(DictionaryName[Index], vDataSet, sErrorMsg); if sErrorMsg <> '' then raise Exception.CreateResFmt(@ERR_GetQyDictionary, [DictionaryName[Index], sErrorMsg]); if FQyDictionary[Index] = nil then FQyDictionary[Index] := TClientDataSet.Create(nil); (FQyDictionary[Index] as TClientDataSet).Data := vDataSet; if DICTIONARYNAME[index] = 'dlQueryMaster' then with FQyDictionary[Index] as TClientDataSet do FieldByName('Default_Value').OnGetText:=GetFieldText; finally ShowStatusMessage(@STA_Ready, []); result:=FQyDictionary[Index]; end; end; procedure TQyDictionary.GetFieldText(Sender: TField; var Text: String; DisplayText: Boolean); begin Text:=Sender.AsString; if Text = '@Current_Department' then Text:=Login.CurrentDepartment; end; initialization lDictionary:=nil; finalization FreeAndNil(lDictionary); end.
// ----------- Parse::Easy::Runtime ----------- // https://github.com/MahdiSafsafi/Parse-Easy // -------------------------------------------- unit Parse.Easy.Parser.CustomParser; interface uses System.SysUtils, System.Classes, Parse.Easy.StackPtr, Parse.Easy.Lexer.CustomLexer, Parse.Easy.Lexer.Token, Parse.Easy.Parser.Deserializer; type TValue = record case Integer of 0: (AsUByte: Byte); 1: (AsUWord: Word); 2: (AsULong: Cardinal); 3: (AsObject: Pointer); 4: (AsClass: TClass); 5: (AsShortInt: ShortInt); 6: (AsSmallInt: SmallInt); 7: (AsInteger: Integer); 8: (AsSingle: Single); 9: (AsDouble: Double); 10: (AsExtended: Extended); 11: (AsComp: Comp); 12: (AsCurrency: Currency); 13: (AsUInt64: UInt64); 14: (AsSInt64: Int64); 15: (AsMethod: TMethod); 16: (AsPointer: Pointer); 17: (AsToken: TToken); 18: (AsList: TList); 19: (AsPChar: PChar); end; PValue = ^TValue; TCustomParser = class(TDeserializer) private FReturnValue: PValue; FValues: TStackPtr; FExceptList: TList; FInternalObjectHolderList: TList; FValueList: TList; protected procedure ExceptError(Token: TToken); procedure UserAction(Index: Integer); virtual; abstract; function CreateNewList(): TList; function NewValue(): PValue; public function Parse: Boolean; virtual; abstract; constructor Create(ALexer: TCustomLexer); override; destructor Destroy(); override; { properties } property Values: TStackPtr read FValues; property ReturnValue: PValue read FReturnValue write FReturnValue; property ExceptList: TList read FExceptList; end; implementation { TCustomParser } constructor TCustomParser.Create(ALexer: TCustomLexer); begin inherited; FInternalObjectHolderList := TList.Create(); FValueList := TList.Create(); FExceptList := TList.Create(); FValues := TStackPtr.Create(); FReturnValue := nil; end; function TCustomParser.CreateNewList(): TList; begin Result := TList.Create(); FInternalObjectHolderList.Add(Result); end; destructor TCustomParser.Destroy(); var I: Integer; begin FExceptList.Free(); FValues.Free(); for I := 0 to FValueList.Count - 1 do if Assigned(FValueList[I]) then FreeMemory(FValueList[I]); FValueList.Free(); for I := 0 to FInternalObjectHolderList.Count - 1 do if Assigned(FInternalObjectHolderList[I]) then TObject(FInternalObjectHolderList[I]).Free(); FInternalObjectHolderList.Free(); inherited; end; procedure TCustomParser.ExceptError(Token: TToken); var StrList: TStringList; S: string; I: Integer; LNear: string; begin LNear := EmptyStr; S := EmptyStr; if (Assigned(Token)) then LNear := Lexer.GetTokenName(Token.TokenType); StrList := TStringList.Create(); try for I := 0 to ExceptList.Count - 1 do StrList.Add(Lexer.GetTokenName(Integer(ExceptList[I]))); StrList.Delimiter := ','; S := StrList.DelimitedText; finally StrList.Free(); end; raise Exception.CreateFmt('Neer %s ... Expecting one of this: [%s]', [LNear, S]); end; function TCustomParser.NewValue: PValue; begin Result := GetMemory(SizeOf(TValue)); FValueList.Add(Result); end; end.
unit ReprortsST_PAY; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frxClass, frxDBSet, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, frxDesgn,StudcityConst, RxMemDS,IBase, FIBDatabase, pFIBDatabase, ActnList, frxExportXLS, frxExportHTML, frxExportRTF, frxExportPDF; type TfrmST_PAY = class(TForm) pFIBStoredProc: TpFIBStoredProc; pFIBDataSet: TpFIBDataSet; frxDBDataset1: TfrxDBDataset; frxDesigner1: TfrxDesigner; pFIBDataSet3: TpFIBDataSet; Database: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; ActionList1: TActionList; Action1: TAction; frxRTFExport1: TfrxRTFExport; frxHTMLExport1: TfrxHTMLExport; frxXLSExport1: TfrxXLSExport; frxPDFExport1: TfrxPDFExport; frxReport: TfrxReport; procedure FormCreate(Sender: TObject); procedure frxReportPrintReport(Sender: TObject); procedure Action1Execute(Sender: TObject); private constructor Create (Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer);overload; { Private declarations } public { Public declarations } end; function ST_PAY(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer):Integer;stdcall; exports ST_PAY; var frmST_PAY: TfrmST_PAY; count_print:Integer; id_people_pr:Int64; Design_rep:Integer; implementation {$R *.dfm} function ST_PAY(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer):Integer;stdcall; var PrProp:TfrmST_PAY; begin PrProp:=TfrmST_PAY.Create(AOwner,DB,id_people,type_doc_print); // PrProp.ShowModal; PrProp.Free; end; constructor TfrmST_PAY.Create(Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64;type_doc_print:integer); begin Inherited Create(Aowner); Database.Handle:=DBL; id_people_pr:=id_people; end; procedure TfrmST_PAY.FormCreate(Sender: TObject); var numberDoc,ORG,OTD,OSN:String; Summa:Variant; Summa_Need:Variant; dateopl:TDateTime; i:Integer; p:TfrxReportPage; id_s,id_s1:Int64; OUT_MAIN_PEOPLE:String; begin With pFIBStoredProc do begin try // --------------запуск процедуры st_pay------------------------------ // расчет уже уплаченной суммы Database:=Database; Transaction:=WriteTransaction; StoredProcName := 'ST_PAY'; Transaction.StartTransaction; Prepare; ParamByName('ID_DOG_STUD').AsInt64 := id_people_pr; ParamByName('DATE_PROV_CHECK').AsShort := 1; ParamByName('IS_DOC_GEN').AsShort := 1; ParamByName('IS_PROV_GEN').AsShort := 1; ParamByName('IS_SMET_GEN').AsShort := 1; ExecProc; Summa:=FieldByName('STUPLSUM').AsVariant; id_s:=FieldByName('ID_SESSION').AsInt64; except Transaction.Rollback; raise; end; end; With pFIBStoredProc do begin try StoredProcName := 'ST_CALC'; WriteTransaction.StartTransaction; Prepare; ParamByName('ID_KOD').AsInt64 := id_people_pr; ParamByName('STUPLSUM').AsVariant := Summa; ExecProc; Transaction.Commit; dateopl:=FieldByName('STDATEOPL').AsDateTime; Summa_Need:=FieldByName('ST_SNEED').AsVariant; id_s1:=FieldByName('ID_SESSION').AsInt64; Close; except Transaction.Rollback; raise; end; end; with pFIBDataSet do begin Database:=Database; Transaction:=ReadTransaction; Active:=false; ParamByName('param_session').AsInt64:=id_s; Active:=true; FetchAll; end; //получаем ФИО with pFIBDataSet3 do begin Database:=Database; Transaction:=ReadTransaction; Active:=false; SQLs.SelectSQL.Text:='SELECT fam_uk||'''+' '+'''||imya_uk||'''+' '+'''||ot_uk as FIO from st_dt_pfio where st_dt_pfio.id_kod='+VarToStr(id_people_pr); Active:=true; end; //получаем номер справки, и реквизиты организации With pFIBStoredProc do begin try StoredProcName:='ST_DTY_NUMBER_SPAV_SELECT'; Database:=Database; Transaction:=WriteTransaction; WriteTransaction.StartTransaction; Prepare; ExecProc; numberDoc:=FieldByName('NUMBER_SPRAV').AsString; ORG:=FieldByName('OUT_MAIN_DEP').AsString; OTD:=FieldByName('OUT_CHILD_DEP').AsString; Transaction.Commit; except Transaction.Rollback; raise; end; end; //находим адресс и период проживания With pFIBStoredProc do begin try StoredProcName:='ST_DT_PRINT_ST_PAY_DOC'; Database:=Database; Transaction:=WriteTransaction; WriteTransaction.StartTransaction; ParamByName('INPUT_ID_PEOPLE').AsInt64:=id_people_pr; Prepare; ExecProc; OSN:=pFIBDataSet3.FieldByName('FIO').AsString+' '+Studcity_ReportsST_PAY_OSN1; OSN:=OSN+' '+FieldByName('OUT_BUILDS').AsString+','+FieldByName('OUT_ROOMSTR').AsString; OSN:=OSN+' '+FieldByName('OUT_TOWN').AsString+','+Studcity_ReportsST_PAY_OSN3; OSN:=OSN+FieldByName('OUT_ADRESS').AsString+' '+Studcity_ReportsST_PAY_OSN4+FieldByName('OUT_HOUSE').AsString; OSN:=OSN+' '+Studcity_ReportsST_PAY_OSN5+' '+FieldByName('OUT_DATE_BEGIN').AsString; OSN:=OSN+' '+Studcity_ReportsST_PAY_OSN6+' '+FieldByName('OUT_DATE_END').AsString; OUT_MAIN_PEOPLE:=FieldByName('OUT_MAIN_PEOPLE').AsString; Transaction.Commit; except Transaction.Rollback; raise; end; end; frxReport.Clear; frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'PeopleStPayDoc.fr3'); frxReport.Variables.Clear; frxReport.Variables['NAMEREP0']:= ''''+StudcityConst.Studcity_ReportsST_CALC_NameREP0+''''; frxReport.Variables['DATEOPL']:= ''''+DateToStr(dateopl)+''''; frxReport.Variables['ALL_SUM_CAP']:= ''''+Studcity_ReportsST_PAY_OSN7+''''; frxReport.Variables['NUM']:= ''''+Studcity_ReportsST_PAY_CAP_N+''''; frxReport.Variables['DOC']:= ''''+Studcity_ReportsST_PAY_CAP_DOC+''''; frxReport.Variables['SUM']:= ''''+Studcity_ReportsST_PAY_CAP_SUM+''''; frxReport.Variables['OSN_DOC']:= ''''+Studcity_ReportsST_PAY_CAP_OSN+''''; frxReport.Variables['ITOGO']:= ''''+Studcity_ReportsST_PAY_ITOGO+''''; frxReport.Variables['ALL_SUM']:= ''''+Studcity_ReportsST_PAY_ALL+''''; frxReport.Variables['OPL_SUM']:= ''''+Studcity_ReportsST_PAY_OPLSUM+''''; frxReport.Variables['NEED_OPL']:= ''''+Studcity_ReportsST_PAY_NEEDOPLSUM+''''; frxReport.Variables['DOLG']:= ''''+Studcity_ReportsST_PAY_DOLG+''''; frxReport.Variables['OSN']:= ''''+OSN+''''; frxReport.Variables['BUHG']:= ''''+Studcity_ReportsST_PAY_Buhg+''''; frxReport.Variables['DIR']:= ''''+Studcity_ReportsST_PAY_DIR+''''; frxReport.Variables['ORG']:= ''''+ORG+''''; frxReport.Variables['OTGOTD']:= ''''+OTD+''''; frxReport.Variables['NUMBER']:= ''''+Studcity_ReportsST_PAY_SPRAV+' № '+numberDoc+''''; frxReport.Variables['REAL_NEED_OPL']:=''''+VarToStr(Summa_Need)+''''; frxReport.Variables['DOLG_OPL']:=''''+VarToStr(Summa_Need-summa)+''''; frxReport.Variables['GRN']:=''''+Studcity_ReportsST_PAY_GRN+''''; frxReport.Variables['PAYCONF1']:= ''''+StudcityConst.Studcity_ReportsST_CALC_PayConf+''''; frxReport.Variables['PAYCONF2']:= ''''+StudcityConst.Studcity_ReportsST_CALC_PayConf1+''''; frxReport.Variables['REC']:=''''+VarToStr(pFIBDataSet.RecordCount)+''''; frxReport.Variables['ST_MAIN_PEOPLE']:=''''+VarToStr(OUT_MAIN_PEOPLE)+''''; frxReport.PrepareReport(true); frxReport.ShowReport(true); if Design_rep=1 then frxReport.DesignReport; with pFIBStoredProc do begin try Database:=Database; Transaction:=ReadTransaction; StoredProcName := 'ST_PAY_TMP_CLEAR'; Transaction.StartTransaction; Prepare; ParamByName('ID_SESSION').AsInt64:=id_s; ExecProc; Transaction.Commit; except Transaction.Rollback; raise; end; end; with pFIBStoredProc do begin try Database:=Database; Transaction:=ReadTransaction; StoredProcName := 'ST_CALC_TMP_CLEAR'; Transaction.StartTransaction; Prepare; ParamByName('ID_SESSION').AsInt64:=id_s1; ExecProc; Transaction.Commit; except Transaction.Rollback; raise; end; end; end; procedure TfrmST_PAY.frxReportPrintReport(Sender: TObject); var numberDoc:String; begin if count_print=0 then begin With pFIBStoredProc do begin try StoredProcName:='ST_DTY_NUMBER_SPAV_UPDATE'; Database:=Database; Transaction:=WriteTransaction; WriteTransaction.StartTransaction; Prepare; ExecProc; numberDoc:=FieldByName('NUMBER_SPRAV').AsString; Transaction.Commit; except Transaction.Rollback; raise; end; end; frxReport.Variables['NUMBER']:= ''''+Studcity_ReportsST_PAY_SPRAV+' № '+numberDoc+''''; frxReport.PrepareReport; inc(count_print); end; end; procedure TfrmST_PAY.Action1Execute(Sender: TObject); begin if Design_rep=0 then begin Design_rep:=1; MessageBox(Handle,PChar('Вы перешли в режим отладки отчетов.'+#13+'Для отключения данного режима нажмите Ctrl+Shift+Alt+D.'),PChar('Внимание!!!'),MB_OK+MB_ICONWARNING); end else begin Design_rep:=0; MessageBox(Handle,PChar('Режим отладки отчетов отключен.'),PChar('Внимание!!!'),MB_OK+MB_ICONWARNING); end; end; end.
// файл traceUnit.pas, инициализация и трассировка сцены unit traceUnit; interface uses vectorUnit, figureUnit, rayUnit, colorUnit, sphereUnit; const numb_spheres = 5; // количество сфер; depth_recursion = 12; // глубина рекурсии; max_dist = 1000.0; // макс. длина трассировки; var backgr_color : Tcvet; // цвет фона; eye_position : Tpoint3D;// положение камеры; lamp : Tray; // источник света; sphere : array[1..numb_spheres] of Tsphere; recursion : integer; // № рекурсии; procedure init_scene; function trace( ray_source, ray_direction: Tvector ): Tcvet; procedure delete_scene; implementation //----------------------------------- procedure init_scene; // эти данные лучше хранить var center: Tvector; // в файле специального color : Tcvet; // формата описания сцены; begin backgr_color.R := 10; backgr_color.G := 10; backgr_color.B := 30; lamp := Tray.birth( 0, 4, 2, 255, 255, 255 ); center := Tvector.birth( 0, -3, 10 ); color.R := 255; color.G := 255; color.B := 255; sphere[1] := Tsphere.birth( center, color, 5, 0.4, 4.0 ); center := Tvector.birth( 3.0, -1.0, 5 ); color.R := 5; color.G := 255; color.B := 5; sphere[2] := Tsphere.birth( center, color, 1, 0.01, 1.5 ); center := Tvector.birth( -3.0, -1.0, 5 ); color.R := 55; color.G := 255; color.B := 255; sphere[3] := Tsphere.birth( center, color, 5, 0.01, 1.5 ); center := Tvector.birth( 0, 3.0, 8 ); color.R := 255; color.G := 10; color.B := 10; sphere[4] := Tsphere.birth( center, color, 2, 0.1, 2.1 ); center := Tvector.birth( 0, -2.5, 4 ); color.R := 255; color.G := 255; color.B := 10; sphere[5] := Tsphere.birth( center, color, 1, 0.08, 1.5 ); end; //----------------------------------- // трассировщик //----------------------------------- function trace( ray_source, ray_direction: Tvector ): Tcvet; var t, tt, diff_koeff, spec_koeff, min_t, spec : double; color, diff_color, spec_color, plus_color : Tcvet; SHADOWED : boolean; trace_point, light_direction, reflect, tmp,tm : Tvector; i, id : integer; begin inc( recursion ); color := backgr_color; id := numb_spheres + 1; min_t := max_dist; for i := 1 to numb_spheres do begin t := sphere[i].intersection( ray_source, ray_direction ); // ближайшее пересечение сферы с индексом // id с лучом на расстоянии min_t: if ( t >= 0 ) AND ( t < min_t ) then begin min_t := t; id := i; color := sphere[id].get_color; end; end; if ( id = numb_spheres + 1 ) // луч никуда не попал then color := backgr_color // -- вернуть цвет фона, else // иначе -- расчёт цвета begin // точки пересечения: tmp := mult_on_scal( min_t, ray_direction ); trace_point := summ_vectors( ray_source, tmp ); tmp.Free; tmp := mult_on_scal( -1, trace_point ); tm := lamp.get_source; light_direction := summ_vectors( tmp, tm ); tmp.Free; tm.Free; light_direction.normalization; // отражённый луч: reflect := sphere[id].get_reflected( ray_direction, trace_point ); // освещение - затенённость другой сферой: SHADOWED := FALSE; for i := 1 to numb_spheres do begin tt := sphere[i].intersection( trace_point, light_direction ); if ( ( tt > 0 ) AND ( i <> id ) ) then begin SHADOWED := TRUE; color := mult_colors( sphere[id].get_color, 0.2 ); break; end; end; // конец теста затенённости; if ( SHADOWED = FALSE ) then begin // освещение - диффузное освещение: diff_koeff := sphere[id].get_diff( trace_point, light_direction ); diff_color := mult_colors( lamp.get_color, diff_koeff ); color := mix_colors( color, diff_color ); // освещение - specular-ое освещение: if ( sphere[id].get_value_spec > 0 ) then begin spec_koeff := sphere[id].get_spec( trace_point, ray_direction, light_direction ); if ( ( spec_koeff > diff_koeff ) AND ( diff_koeff > 0 ) ) then begin spec_color := mult_colors(lamp.get_color, spec_koeff); spec_color := mix_colors(spec_color, sphere[id].get_color); color := mix_colors( color, spec_color ); end; end; end; // if ( SHADOWED = FALSE )... // отражение (рекурсивные вызовы): if ( recursion <= depth_recursion ) then begin spec := sphere[id].get_value_spec; if ( spec > 0.0 ) then begin plus_color := trace( trace_point, reflect ); plus_color := mult_colors( plus_color, spec ); color := mix_colors( color, plus_color ); end; end; trace_point.Free; light_direction.Free; reflect.Free; end; // else if( id = numb_spheres + 1 )... result := color; end; //----------------------------------- procedure delete_scene; var i: integer; begin lamp.Free; for i := 1 to numb_spheres do sphere[i].Free; end; //----------------------------------- end. // конец файла traceUnit.pas
{ Generic (no real network implementation) classes and declarations for requesting OSM tile images from network. Real network function from any network must be supplied to actually execute request. } unit OSM.NetworkRequest; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses SysUtils, Classes, Contnrs, {$IF NOT DECLARED(TMonitor)} syncobjs, {$IFEND} OSM.SlippyMapUtils; type THttpRequestType = (reqPost, reqGet); THttpRequestProps = record RequestType: THttpRequestType; URL: string; POSTData: string; HttpUserName: string; HttpPassword: string; HeaderLines: TStrings; Additional: Pointer; end; // Generic type of blocking network request function // RequestProps - all details regarding a request // ResponseStm - stream that accepts response data // ErrMsg - error description if any. // Returns: success flag TBlockingNetworkRequestFunc = function (const RequestProps: THttpRequestProps; const ResponseStm: TStream; out ErrMsg: string): Boolean; // Generic type of method to call when request is completed // ! Called from the context of a background thread ! TGotTileCallbackBgThr = procedure (const Tile: TTile; Ms: TMemoryStream; const Error: string) of object; // Queuer of network requests TNetworkRequestQueue = class strict private FTaskQueue: TQueue; // list of tiles to be requested {$IF NOT DECLARED(TMonitor)} FCS: TCriticalSection; {$IFEND} FThreads: TList; FCurrentTasks: TList; // list of tiles that are requested but not yet received FNotEmpty: Boolean; FDestroying: Boolean; // object is being destroyed, do cleanup, don't call any callbacks FMaxTasksPerThread: Cardinal; FMaxThreads: Cardinal; FGotTileCb: TGotTileCallbackBgThr; FRequestFunc: TBlockingNetworkRequestFunc; procedure Lock; procedure Unlock; procedure AddThread; private // for access from TNetworkRequestThread procedure DoRequestComplete(Sender: TThread; const Tile: TTile; Ms: TMemoryStream; const Error: string); function PopTask: Pointer; property NotEmpty: Boolean read FNotEmpty; property RequestFunc: TBlockingNetworkRequestFunc read FRequestFunc; public constructor Create(MaxTasksPerThread, MaxThreads: Cardinal; RequestFunc: TBlockingNetworkRequestFunc; GotTileCb: TGotTileCallbackBgThr); destructor Destroy; override; procedure RequestTile(const Tile: TTile); end; implementation type // Thread that consumes tasks from owner's queue and executes them // When there are no tasks in the queue, it finishes and must be destroyed TNetworkRequestThread = class(TThread) strict private FOwner: TNetworkRequestQueue; public constructor Create(Owner: TNetworkRequestQueue); procedure Execute; override; end; { TNetworkRequestThread } constructor TNetworkRequestThread.Create(Owner: TNetworkRequestQueue); begin FOwner := Owner; inherited Create(False); end; procedure TNetworkRequestThread.Execute; var pT: PTile; tile: TTile; sURL, sErrMsg: string; ms: TMemoryStream; ReqProps: THttpRequestProps; begin ReqProps := Default(THttpRequestProps); ReqProps.RequestType := reqGet; while not Terminated do begin pT := PTile(FOwner.PopTask); if pT <> nil then begin tile := pT^; sURL := TileToFullSlippyMapFileURL(tile); ms := TMemoryStream.Create; ReqProps.URL := sURL; if not FOwner.RequestFunc(ReqProps, ms, sErrMsg) then FreeAndNil(ms) else ms.Position := 0; FOwner.DoRequestComplete(Self, tile, ms, sErrMsg); end; end; end; { TNetworkRequestQueue } // MaxTasksPerThread - if TaskCount > MaxTasksPerThread*ThreadCount, add one more thread // MaxThreads - limit the number of threads // GotTileCb - method to call when request is completed constructor TNetworkRequestQueue.Create(MaxTasksPerThread, MaxThreads: Cardinal; RequestFunc: TBlockingNetworkRequestFunc; GotTileCb: TGotTileCallbackBgThr); begin FTaskQueue := TQueue.Create; {$IF NOT DECLARED(TMonitor)} FCS := TCriticalSection.Create; {$IFEND} FThreads := TList.Create; FCurrentTasks := TList.Create; FMaxTasksPerThread := MaxTasksPerThread; FMaxThreads := MaxThreads; FGotTileCb := GotTileCb; FRequestFunc := RequestFunc; end; destructor TNetworkRequestQueue.Destroy; var i: Integer; begin FDestroying := True; // Command the threads to stop, wait and destroy them for i := 0 to FThreads.Count - 1 do TThread(FThreads[i]).Terminate; for i := 0 to FThreads.Count - 1 do TThread(FThreads[i]).WaitFor; for i := 0 to FThreads.Count - 1 do if TThread(FThreads[i]).Finished then TThread(FThreads[i]).Free else raise Exception.Create('Thread was not finished'); FreeAndNil(FThreads); // Data cleanup while FTaskQueue.Count > 0 do Dispose(PTile(FTaskQueue.Pop)); FreeAndNil(FTaskQueue); for i := 0 to FCurrentTasks.Count - 1 do Dispose(PTile(FCurrentTasks[0])); FreeAndNil(FCurrentTasks); {$IF NOT DECLARED(TMonitor)} FreeAndNil(FCS); {$IFEND} end; procedure TNetworkRequestQueue.Lock; begin {$IF NOT DECLARED(TMonitor)} FCS.Enter; {$ELSE} System.TMonitor.Enter(Self); {$IFEND} end; procedure TNetworkRequestQueue.Unlock; begin {$IF NOT DECLARED(TMonitor)} FCS.Leave; {$ELSE} System.TMonitor.Exit(Self); {$IFEND} end; function IndexOfTile(const Tile: TTile; List: TList): Integer; begin for Result := 0 to List.Count - 1 do if TilesEqual(Tile, PTile(List[Result])^) then Exit; Result := -1; end; type TQueueHack = class(TQueue) end; procedure TNetworkRequestQueue.RequestTile(const Tile: TTile); var pT: PTile; begin Lock; try // check if tile already in process if IndexOfTile(Tile, FCurrentTasks) <> -1 then Exit; // or in queue if IndexOfTile(Tile, TQueueHack(FTaskQueue).List) <> -1 then Exit; New(pT); pT^ := Tile; FTaskQueue.Push(pT); FNotEmpty := True; if (FTaskQueue.Count > FMaxTasksPerThread*FThreads.Count) and (FThreads.Count < FMaxThreads) then AddThread; finally Unlock; end; end; procedure TNetworkRequestQueue.AddThread; begin Lock; try FThreads.Add(TNetworkRequestThread.Create(Self)); finally Unlock; end; end; // Extract next item from queue // ! Executed from bg threads function TNetworkRequestQueue.PopTask: Pointer; begin // Fast check if not NotEmpty then Exit(nil); Lock; try if FTaskQueue.Count > 0 then begin Result := FTaskQueue.Pop; FCurrentTasks.Add(Result); end else Result := nil; FNotEmpty := (FTaskQueue.Count > 0); finally Unlock; end; end; // Network request complete // ! Executed from bg threads procedure TNetworkRequestQueue.DoRequestComplete(Sender: TThread; const Tile: TTile; Ms: TMemoryStream; const Error: string); var idx: Integer; begin Lock; try idx := IndexOfTile(Tile, FCurrentTasks); Dispose(PTile(FCurrentTasks[idx])); FCurrentTasks.Delete(idx); if Sender.Finished then begin Sender.Free; FThreads.Delete(FThreads.IndexOf(Sender)); end; finally Unlock; end; // Run callback or just cleanup if not FDestroying then FGotTileCb(Tile, Ms, Error) else FreeAndNil(Ms); end; end.
unit IdResourceStringsUriUtils; interface resourcestring // TIdURI RSUTF16IndexOutOfRange = '文字インデックス %d は範囲外です (長さ = %d)'; RSUTF16InvalidHighSurrogate = 'インデックス %d の文字は UTF-16 の上位サロゲートとして無効です'; RSUTF16InvalidLowSurrogate = 'インデックス %d の文字は UTF-16 の下位サロゲートとして無効です'; RSUTF16MissingLowSurrogate = 'UTF-16 シーケンスに下位サロゲートが見つかりません'; implementation end.
unit St_sp_Hostel_Form_Add; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, cxLabel, cxTextEdit, cxControls, cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons; type TBuildsFormAdd = class(TForm) OKButton: TcxButton; CancelButton: TcxButton; cxGroupBox1: TcxGroupBox; ShortEdit: TcxTextEdit; ShortNameLabel: TcxLabel; NameLabel: TcxLabel; NameEdit: TcxTextEdit; NumEdit: TcxTextEdit; NumLabel: TcxLabel; cxLabel1: TcxLabel; ChiefEdit: TcxTextEdit; SizeLabel: TcxLabel; SizeEdit: TcxTextEdit; FloorLabel: TcxLabel; FloorEdit: TcxTextEdit; cxGroupBox2: TcxGroupBox; OblastLabel: TcxLabel; OblastEdit: TcxTextEdit; TownLabel: TcxLabel; TownEdit: TcxTextEdit; RaionLabel: TcxLabel; RaionEdit: TcxTextEdit; StreetLabel: TcxLabel; StreetEdit: TcxTextEdit; HouseLabel: TcxLabel; HouseEdit: TcxTextEdit; IndexLabel: TcxLabel; IndexEdit: TcxTextEdit; procedure CancelButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure NumEditKeyPress(Sender: TObject; var Key: Char); procedure ShortEditKeyPress(Sender: TObject; var Key: Char); procedure NameEditKeyPress(Sender: TObject; var Key: Char); procedure SizeEditKeyPress(Sender: TObject; var Key: Char); procedure ChiefEditKeyPress(Sender: TObject; var Key: Char); procedure FloorEditKeyPress(Sender: TObject; var Key: Char); procedure TownEditKeyPress(Sender: TObject; var Key: Char); procedure OblastEditKeyPress(Sender: TObject; var Key: Char); procedure RaionEditKeyPress(Sender: TObject; var Key: Char); procedure StreetEditKeyPress(Sender: TObject; var Key: Char); procedure HouseEditKeyPress(Sender: TObject; var Key: Char); procedure IndexEditKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} function IntegerCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13]) then k := #0; if k = #0 then exit; end; Result := true; end; function FloatCheck(const s : string) : boolean; var i : integer; k : char; begin Result := false; if s = '' then exit; for i := 1 to Length(s) do begin k := s[i]; if not (k in ['0'..'9',#8, #13, DecimalSeparator]) then k := #0; if k = #0 then exit; end; i := pos(DecimalSeparator, s); if i <> 0 then if Copy(s, i + 1, Length(s) - i) = '' then exit; if pos(DecimalSeparator, Copy(s, i + 1, Length(s) - i)) <> 0 then exit; Result := true; end; procedure TBuildsFormAdd.CancelButtonClick(Sender: TObject); begin close; end; procedure TBuildsFormAdd.FormShow(Sender: TObject); begin If cxGroupBox1.Enabled = true then NumEdit.SetFocus else CancelButton.SetFocus; end; procedure TBuildsFormAdd.OKButtonClick(Sender: TObject); begin if not IntegerCheck(NumEdit.Text) then begin ShowMessage('Номер общежития введен неверно.'); NumEdit.SetFocus; exit; end; if ShortEdit.Text = '' then begin ShowMessage('Необходимо ввести сокращенное название.'); ShortEdit.SetFocus; exit; end; if NameEdit.Text = '' then begin ShowMessage('Необходимо ввести название.'); NameEdit.SetFocus; exit; end; if ChiefEdit.Text = '' then begin ShowMessage('Необходимо ввести ФИО коменданта общежития.'); ChiefEdit.SetFocus; exit; end; if not FloatCheck(SizeEdit.Text) then begin ShowMessage('Площадь введена неверно.'); SizeEdit.SetFocus; exit; end; if not IntegerCheck(FloorEdit.Text) then begin ShowMessage('Количество этажей введено неверно.'); FloorEdit.SetFocus; exit; end; if not IntegerCheck(IndexEdit.Text) then begin ShowMessage('Индекс введен неверно.'); IndexEdit.SetFocus; exit; end; ModalResult := mrOK; end; procedure TBuildsFormAdd.NumEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then ShortEdit.SetFocus; end; procedure TBuildsFormAdd.ShortEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then NameEdit.SetFocus; end; procedure TBuildsFormAdd.NameEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then ChiefEdit.SetFocus; end; procedure TBuildsFormAdd.SizeEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then FloorEdit.SetFocus; end; procedure TBuildsFormAdd.ChiefEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then SizeEdit.SetFocus; end; procedure TBuildsFormAdd.FloorEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then OblastEdit.SetFocus; end; procedure TBuildsFormAdd.TownEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then RaionEdit.SetFocus; end; procedure TBuildsFormAdd.OblastEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then TownEdit.SetFocus; end; procedure TBuildsFormAdd.RaionEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then StreetEdit.SetFocus; end; procedure TBuildsFormAdd.StreetEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then HouseEdit.SetFocus; end; procedure TBuildsFormAdd.HouseEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then IndexEdit.SetFocus; end; procedure TBuildsFormAdd.IndexEditKeyPress(Sender: TObject; var Key: Char); begin If Key=#13 then OkButton.SetFocus; end; end.
unit ibSHXHelpFrm; interface uses SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, SynEdit, pSHSynEdit, StdCtrls, ComCtrls; type TibSHXHelpForm = class(TibBTComponentForm) reHelpContext: TRichEdit; private { Private declarations } protected procedure LoadContextHelp; function DoOnOptionsChanged: Boolean; override; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; end; var ibSHXHelpForm: TibSHXHelpForm; implementation {$R *.dfm} { TibSHXHelpForm } constructor TibSHXHelpForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); begin inherited Create(AOwner, AParent, AComponent, ACallString); // Editor := pSHSynEdit1; // Editor.Lines.Clear; // Editor.Lines.Add(Format('Context help for "%s" component', [Component.Hint])); // Editor.Lines.Add('Sorry,... coming soon. Under construction.'); // FocusedControl := Editor; DoOnOptionsChanged; // LoadContextHelp; end; destructor TibSHXHelpForm.Destroy; begin inherited Destroy; end; procedure TibSHXHelpForm.LoadContextHelp; const FILE_EXT = 'SQLHammer*.rtf'; var vDocumentationDir: string; SearchRec: TSearchRec; FileAttrs: Integer; procedure ForceCloseAllBrackets(AStrings: TStrings); var S: string; vOpenedBrackets, vClosedBrackets: Cardinal; I: Integer; begin vOpenedBrackets := 0; vClosedBrackets := 0; S := AStrings.Text; for I := 1 to Length(S) do if S[I] = '{' then begin if not ((I > 1) and (S[I-1] = '\')) then Inc(vOpenedBrackets); end else if S[I] = '}' then begin if not ((I > 1) and (S[I-1] = '\')) then begin Inc(vClosedBrackets); if vClosedBrackets > vOpenedBrackets then begin AStrings.Insert(0, '{'); Inc(vOpenedBrackets); end; end; end; if vOpenedBrackets > vClosedBrackets then for I := 1 to vOpenedBrackets - vClosedBrackets do AStrings.Add('}') else if vOpenedBrackets < vClosedBrackets then for I := 1 to vClosedBrackets - vOpenedBrackets do AStrings.Insert(0, '{'); end; function GetUserManualTempFileName(APrefix: string): string; var vTempPath: PChar; vTempFile: PChar; vNeedPath: Cardinal; begin vTempPath := StrAlloc(MAX_PATH + 1); vTempFile := StrAlloc(MAX_PATH + MAX_PATH + 1); try vNeedPath := GetTempPath(MAX_PATH, vTempPath); if vNeedPath > MAX_PATH then begin StrDispose(vTempPath); vTempPath := StrAlloc(vNeedPath + 1); GetTempPath(vNeedPath, vTempPath); end; GetTempFileName(vTempPath, PChar(APrefix), 0, vTempFile); SetString(Result, vTempFile, StrLen(vTempFile)); DeleteFile(Result); finally StrDispose(vTempPath); StrDispose(vTempFile); end; end; function LoadContextHelpFromFile(AFileName: string): Boolean; var F: TextFile; vComponentHelp: TStringList; vBody: TStringList; S: string; vHeaderLoaded: Boolean; vPos: Integer; vStartFinded: Boolean; vForceDeleteParagraph: Boolean; vSearchIdentifire: string; vFileName: string; begin Result := False; vHeaderLoaded := False; vStartFinded := False; vForceDeleteParagraph := False; vSearchIdentifire := GUIDToString(Component.ClassIID); if Length(vSearchIdentifire) > 1 then begin Delete(vSearchIdentifire, 1, 1); Delete(vSearchIdentifire, Length(vSearchIdentifire), 1); end; AssignFile(F, AFileName); vComponentHelp := TStringList.Create; vBody := TStringList.Create; try Reset(F); while not EOF(F) do begin ReadLn(F, S); if not vHeaderLoaded then begin vPos := Pos('{\info', S); if vPos = 0 then vComponentHelp.Add(S) else begin vComponentHelp.Add(System.Copy(S, 1, vPos - 1)); vHeaderLoaded := True; end; end else begin vPos := Pos(vSearchIdentifire, S); if vPos > 0 then begin if not vStartFinded then begin vPos := vPos + Length(vSearchIdentifire) + 2; vStartFinded := True; S := System.Copy(S, vPos, MaxInt); vPos := Pos('\par', S); if vPos > 0 then begin Delete(S, vPos, Length('\par')); vForceDeleteParagraph := False; end else vForceDeleteParagraph := True; vBody.Add(S); end else begin vPos := vPos - 2; vBody.Add(System.Copy(S, 1, vPos - 1)); Break; end; end else if vStartFinded then begin if vForceDeleteParagraph then begin vPos := Pos('\par', S); if vPos > 0 then begin Delete(S, vPos, Length('\par')); vForceDeleteParagraph := False; end; end; vBody.Add(S); end; end; end; if vBody.Count > 0 then begin vFileName := GetUserManualTempFileName('sha'); ForceCloseAllBrackets(vBody); vComponentHelp.SaveToFile('c:\1.txt'); vComponentHelp.AddStrings(vBody); vComponentHelp.Add('}'); vComponentHelp.SaveToFile('c:\2.txt'); vComponentHelp.SaveToFile(vFileName); reHelpContext.PlainText := False; reHelpContext.Lines.LoadFromFile(vFileName); DeleteFile(vFileName); Result := True; end; finally CloseFile(F); vComponentHelp.Free; vBody.Free; end; end; function GetUserManualDir: string; begin Result := IncludeTrailingPathDelimiter(Designer.GetApplicationPath) + '..\Data\Resources\Documentation\'; end; begin if Assigned(Component) and (not IsEqualGUID(Component.ClassIID, IUnknown)) then begin vDocumentationDir := GetUserManualDir; if DirectoryExists(vDocumentationDir) then begin FileAttrs := 0; if FindFirst(Format('%s%s', [vDocumentationDir, FILE_EXT]), FileAttrs, SearchRec) = 0 then begin repeat if LoadContextHelpFromFile(Format('%s%s', [vDocumentationDir, SearchRec.Name])) then Break; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; end; end; end; function TibSHXHelpForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; if Result and Assigned(Editor) then begin Editor.Highlighter := nil; // Принудительная установка фонта Editor.Font.Charset := 1; Editor.Font.Color := clWindowText; Editor.Font.Height := -13; Editor.Font.Name := 'Courier New'; Editor.Font.Pitch := fpDefault; Editor.Font.Size := 10; Editor.Font.Style := []; Editor.ReadOnly := True; end; end; end.
// // Generated by JavaToPas v1.5 20180804 - 083142 //////////////////////////////////////////////////////////////////////////////// unit android.app.admin.SystemUpdatePolicy_ValidationFailedException; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os; type JSystemUpdatePolicy_ValidationFailedException = interface; JSystemUpdatePolicy_ValidationFailedExceptionClass = interface(JObjectClass) ['{E4E83435-5487-4C1E-8DB2-E5278BA9FA8E}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetERROR_COMBINED_FREEZE_PERIOD_TOO_CLOSE : Integer; cdecl; // A: $19 function _GetERROR_COMBINED_FREEZE_PERIOD_TOO_LONG : Integer; cdecl; // A: $19 function _GetERROR_DUPLICATE_OR_OVERLAP : Integer; cdecl; // A: $19 function _GetERROR_NEW_FREEZE_PERIOD_TOO_CLOSE : Integer; cdecl; // A: $19 function _GetERROR_NEW_FREEZE_PERIOD_TOO_LONG : Integer; cdecl; // A: $19 function _GetERROR_UNKNOWN : Integer; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function getErrorCode : Integer; cdecl; // ()I A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property ERROR_COMBINED_FREEZE_PERIOD_TOO_CLOSE : Integer read _GetERROR_COMBINED_FREEZE_PERIOD_TOO_CLOSE;// I A: $19 property ERROR_COMBINED_FREEZE_PERIOD_TOO_LONG : Integer read _GetERROR_COMBINED_FREEZE_PERIOD_TOO_LONG;// I A: $19 property ERROR_DUPLICATE_OR_OVERLAP : Integer read _GetERROR_DUPLICATE_OR_OVERLAP;// I A: $19 property ERROR_NEW_FREEZE_PERIOD_TOO_CLOSE : Integer read _GetERROR_NEW_FREEZE_PERIOD_TOO_CLOSE;// I A: $19 property ERROR_NEW_FREEZE_PERIOD_TOO_LONG : Integer read _GetERROR_NEW_FREEZE_PERIOD_TOO_LONG;// I A: $19 property ERROR_UNKNOWN : Integer read _GetERROR_UNKNOWN; // I A: $19 end; [JavaSignature('android/app/admin/SystemUpdatePolicy_ValidationFailedException')] JSystemUpdatePolicy_ValidationFailedException = interface(JObject) ['{BD9096EB-2922-4560-B48D-2DC559C9AD0B}'] function describeContents : Integer; cdecl; // ()I A: $1 function getErrorCode : Integer; cdecl; // ()I A: $1 procedure writeToParcel(dest : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJSystemUpdatePolicy_ValidationFailedException = class(TJavaGenericImport<JSystemUpdatePolicy_ValidationFailedExceptionClass, JSystemUpdatePolicy_ValidationFailedException>) end; const TJSystemUpdatePolicy_ValidationFailedExceptionERROR_COMBINED_FREEZE_PERIOD_TOO_CLOSE = 6; TJSystemUpdatePolicy_ValidationFailedExceptionERROR_COMBINED_FREEZE_PERIOD_TOO_LONG = 5; TJSystemUpdatePolicy_ValidationFailedExceptionERROR_DUPLICATE_OR_OVERLAP = 2; TJSystemUpdatePolicy_ValidationFailedExceptionERROR_NEW_FREEZE_PERIOD_TOO_CLOSE = 4; TJSystemUpdatePolicy_ValidationFailedExceptionERROR_NEW_FREEZE_PERIOD_TOO_LONG = 3; TJSystemUpdatePolicy_ValidationFailedExceptionERROR_UNKNOWN = 1; implementation end.
unit MSntdll; interface uses Windows; type // Note: ULONG defined in unit "Windows" USHORT = Word; NTSTATUS = DWORD; const STATUS_SUCCESS = 0; type (* typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } LSA_UNICODE_STRING, *PLSA_UNICODE_STRING, UNICODE_STRING, *PUNICODE_STRING; *) // do NOT pack (for 64 bit windows) see https://forums.embarcadero.com/thread.jspa?threadID=109440 TUNICODE_STRING = record Length: USHORT; MaximumLength: USHORT; Buffer: PWideChar; end; PUNICODE_STRING = ^TUNICODE_STRING; (* typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; typedef CONST OBJECT_ATTRIBUTES *PCOBJECT_ATTRIBUTES; *) // do NOT pack (for 64 bit windows) see https://forums.embarcadero.com/thread.jspa?threadID=109440 TOBJECT_ATTRIBUTES = record Length: ULONG; RootDirectory: THandle; ObjectName: PUNICODE_STRING; Attributes: ULONG; SecurityDescriptor: Pointer; SecurityQualityOfService: Pointer; end; POBJECT_ATTRIBUTES = ^TOBJECT_ATTRIBUTES; const OBJ_INHERIT = $00000002; OBJ_PERMANENT = $00000010; OBJ_EXCLUSIVE = $00000020; OBJ_CASE_INSENSITIVE = $00000040; OBJ_OPENIF = $00000080; OBJ_OPENLINK = $00000100; // OBJ_KERNEL_HANDLE = $ // OBJ_FORCE_ACCESS_CHECK = $ OBJ_VALID_ATTRIBUTES = $000001F2; type TOBJECT_DIRECTORY_INFORMATION = packed record ObjectName: TUNICODE_STRING; ObjectTypeName: TUNICODE_STRING; Data: array [0..0] of byte; end; POBJECT_DIRECTORY_INFORMATION = ^TOBJECT_DIRECTORY_INFORMATION; //OBJECT_DIRECTORY_INFORMATION = TOBJECT_DIRECTORY_INFORMATION; (* VOID RtlInitUnicodeString( PUNICODE_STRING DestinationString, PCWSTR SourceString ); *) {$IFDEF _NTDLL_DYNAMIC} type TRtlInitUnicodeString = procedure(DestinationString: PUNICODE_STRING; SourceString: PWideChar); stdcall; var RtlInitUnicodeString: TRtlInitUnicodeString; {$ELSE} procedure RtlInitUnicodeString(DestinationString: PUNICODE_STRING; SourceString: PWideChar); stdcall; {$EXTERNALSYM RtlInitUnicodeString} {$ENDIF} (* NTSTATUS WINAPI NtOpenDirectoryObject( __out PHANDLE DirectoryHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes ); *) {$IFDEF _NTDLL_DYNAMIC} type TNtOpenDirectoryObject = function( DirectoryHandle: PHandle; DesiredAccess: ACCESS_MASK; ObjectAttributes: POBJECT_ATTRIBUTES ): NTSTATUS; stdcall; var NtOpenDirectoryObject: TNtOpenDirectoryObject; {$ELSE} function NtOpenDirectoryObject( DirectoryHandle: PHandle; DesiredAccess: ACCESS_MASK; ObjectAttributes: POBJECT_ATTRIBUTES ): NTSTATUS; stdcall; {$EXTERNALSYM NtOpenDirectoryObject} {$ENDIF} const DIRECTORY_QUERY = $0001; DIRECTORY_TRAVERSE = $0002; DIRECTORY_CREATE_OBJECT = $0004; DIRECTORY_CREATE_SUBDIRECTORY = $0008; DIRECTORY_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or $F); SYMBOLIC_LINK_QUERY = $0001; SYMBOLIC_LINK_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or $1); (* NTSTATUS WINAPI NtQueryDirectoryObject( __in HANDLE DirectoryHandle, __out_opt PVOID Buffer, __in ULONG Length, __in BOOLEAN ReturnSingleEntry, __in BOOLEAN RestartScan, __inout PULONG Context, __out_opt PULONG ReturnLength ); *) {$IFDEF _NTDLL_DYNAMIC} type TNtQueryDirectoryObject = function( DirectoryHandle: THandle; Buffer: Pointer; Length: ULONG; ReturnSingleEntry: BOOLEAN; RestartScan: boolean; Context: PULONG; ReturnLength: PULONG ): NTSTATUS; stdcall; var NtQueryDirectoryObject: TNtQueryDirectoryObject; {$ELSE} function NtQueryDirectoryObject( DirectoryHandle: THandle; Buffer: Pointer; Length: ULONG; ReturnSingleEntry: BOOLEAN; RestartScan: boolean; Context: PULONG; ReturnLength: PULONG ): NTSTATUS; stdcall; {$EXTERNALSYM NtQueryDirectoryObject} {$ENDIF} (* NTSTATUS WINAPI NtOpenSymbolicLinkObject( __out PHANDLE LinkHandle, __in ACCESS_MASK DesiredAccess, __in POBJECT_ATTRIBUTES ObjectAttributes ); *) {$IFDEF _NTDLL_DYNAMIC} TNtOpenSymbolicLinkObject = function( LinkHandle: PHANDLE; DesiredAccess: ACCESS_MASK; ObjectAttribute: POBJECT_ATTRIBUTES ): NTSTATUS; stdcall; var NtOpenSymbolicLinkObject = TNtOpenSymbolicLinkObject; {$ELSE} function NtOpenSymbolicLinkObject( LinkHandle: PHANDLE; DesiredAccess: ACCESS_MASK; ObjectAttribute: POBJECT_ATTRIBUTES ): NTSTATUS; stdcall; {$EXTERNALSYM NtOpenSymbolicLinkObject} {$ENDIF} type TACCESS_MASK = DWORD; PACCESS_MASK = ^TACCESS_MASK; const DELETE = $00010000; READ_CONTROL = $00020000; WRITE_DAC = $00040000; WRITE_OWNER = $00080000; SYNCHRONIZE = $00100000; STANDARD_RIGHTS_REQUIRED = $000F0000; STANDARD_RIGHTS_READ = READ_CONTROL; STANDARD_RIGHTS_WRITE = READ_CONTROL; STANDARD_RIGHTS_EXECUTE = READ_CONTROL; STANDARD_RIGHTS_ALL = $001F0000; SPECIFIC_RIGHTS_ALL = $0000FFFF; (* NTSTATUS WINAPI NtQuerySymbolicLinkObject( __in HANDLE LinkHandle, __inout PUNICODE_STRING LinkTarget, __out_opt PULONG ReturnedLength ); *) {$IFDEF _NTDLL_DYNAMIC} type TNtQuerySymbolicLinkObject = function( LinkHandle: THandle; LinkTarget: PUNICODE_STRING; ReturnedLengt: PULONG ): NTSTATUS; stdcall; var NtQuerySymbolicLinkObject = TNtQuerySymbolicLinkObject; {$ELSE} function NtQuerySymbolicLinkObject( LinkHandle: THandle; LinkTarget: PUNICODE_STRING; ReturnedLengt: PULONG ): NTSTATUS; stdcall; {$EXTERNALSYM NtQuerySymbolicLinkObject} {$ENDIF} (* NTSTATUS NtClose( HANDLE Handle ); *) {$IFDEF _NTDLL_DYNAMIC} type TNtClose = function( Handle: THandle ): NTSTATUS; stdcall; var NtClose = TNtClose; {$ELSE} function NtClose( Handle: THandle ): NTSTATUS; stdcall; {$EXTERNALSYM NtClose} {$ENDIF} (* VOID InitializeObjectAttributes( OUT POBJECT_ATTRIBUTES InitializedAttributes, IN PUNICODE_STRING ObjectName, IN ULONG Attributes, IN HANDLE RootDirectory, IN PSECURITY_DESCRIPTOR SecurityDescriptor ); *) {$IFDEF _NTDLL_DYNAMIC} type TInitializeObjectAttributes = procedure( InitializedAttributes: POBJECT_ATTRIBUTES; ObjectName: PUNICODE_STRING; Attributes: ULONG; RootDirectory: THandle; SecurityDescriptor: PSECURITY_DESCRIPTOR ); var InitializeObjectAttributes: TInitializeObjectAttributes; {$ELSE} procedure InitializeObjectAttributes( InitializedAttributes: POBJECT_ATTRIBUTES; ObjectName: PUNICODE_STRING; Attributes: ULONG; RootDirectory: THandle; SecurityDescriptor: PSECURITY_DESCRIPTOR ); {$ENDIF} function NT_SUCCESS(status: NTSTATUS): boolean; // Allocate memory for, and populate a UNICODE_STRING structure // Note: Memory allocated *must* be free'd off by called; e.g. by calling FreeRtlInitUnicodeString(...) procedure AllocRtlInitUnicodeString(DestinationString: PUNICODE_STRING; SourceString: WideString); procedure FreeRtlInitUnicodeString(StringToFree: PUNICODE_STRING); function UNICODE_STRINGToWideString(inStr: TUNICODE_STRING): WideString; implementation uses SysUtils; const ntdll = 'ntdll.dll'; {$IFDEF _NTDLL_DYNAMIC} var hLibNtDLL: THandle; {$ELSE} {$ENDIF} {$IFDEF _NTDLL_DYNAMIC} {$ELSE} procedure RtlInitUnicodeString; external ntdll name 'RtlInitUnicodeString'; function NtOpenDirectoryObject; external ntdll name 'NtOpenDirectoryObject'; function NtQueryDirectoryObject; external ntdll name 'NtQueryDirectoryObject'; function NtOpenSymbolicLinkObject; external ntdll name 'NtOpenSymbolicLinkObject'; function NtQuerySymbolicLinkObject; external ntdll name 'NtQuerySymbolicLinkObject'; function NtClose; external ntdll name 'NtClose'; {$ENDIF} function NT_SUCCESS(status: NTSTATUS): boolean; begin Result := (status = STATUS_SUCCESS); end; procedure AllocRtlInitUnicodeString(DestinationString: PUNICODE_STRING; SourceString: Widestring); var newString: PWideChar; begin newString := AllocMem((length(SourceString) + 1)* sizeof(WideChar)); CopyMemory(newstring, PWideString(SourceString), (length(SourceString) * sizeof(newString^)) ); newString[length(SourceString)] := #0; //this doesnt seem to wokr on 64 bit windows RtlInitUnicodeString(DestinationString, newString); // DestinationString.Length := (length(SourceString) + 1)* sizeof(WideChar); // DestinationString.MaximumLength := DestinationString.Length; // DestinationString.Buffer := newstring; end; procedure FreeRtlInitUnicodeString(StringToFree: PUNICODE_STRING); begin StringToFree.Length := 0; StringToFree.MaximumLength := 0; FreeMem(StringToFree.Buffer); StringToFree.Buffer := nil; end; function UNICODE_STRINGToWideString(inStr: TUNICODE_STRING): WideString; var i: integer; begin result := ''; // -1 because index from 0 for i:=0 to ((inStr.Length div 2) - 1) do begin result := result + inStr.Buffer[i]; end; end; procedure InitializeObjectAttributes( InitializedAttributes: POBJECT_ATTRIBUTES; ObjectName: PUNICODE_STRING; Attributes: ULONG; RootDirectory: THandle; SecurityDescriptor: PSECURITY_DESCRIPTOR ); begin InitializedAttributes.Length := sizeof(InitializedAttributes^); InitializedAttributes.Attributes := Attributes; InitializedAttributes.ObjectName := ObjectName; InitializedAttributes.RootDirectory := RootDirectory; InitializedAttributes.SecurityDescriptor := SecurityDescriptor; InitializedAttributes.SecurityQualityOfService := nil; end; {$IFDEF _NTDLL_DYNAMIC} initialization hLibNtDLL := LoadLibrary(ntdll); @RtlInitUnicodeString := 0; @NtOpenDirectoryObject := 0; @NtQueryDirectoryObject := 0; @NtOpenSymbolicLinkObject := 0; @NtQuerySymbolicLinkObject := 0; @NtClose := 0; @InitializeObjectAttributes := 0; if (hLibNtDLL <> 0) then begin @RtlInitUnicodeString := GetProcAddress(hLibNtDLL, 'RtlInitUnicodeString'); @NtOpenDirectoryObject := GetProcAddress(hLibNtDLL, 'NtOpenDirectoryObject'); @NtQueryDirectoryObject := GetProcAddress(hLibNtDLL, 'NtQueryDirectoryObject'); @NtOpenSymbolicLinkObject := GetProcAddress(hLibNtDLL, 'NtOpenSymbolicLinkObject'); @NtQuerySymbolicLinkObject := GetProcAddress(hLibNtDLL, 'NtQuerySymbolicLinkObject'); @NtClose := GetProcAddress(hLibNtDLL, 'NtClose'); @InitializeObjectAttributes := GetProcAddress(hLibNtDLL, 'InitializeObjectAttributes'); end; finalization if (hLibNtDLL <> 0) then begin FreeLibrary(hLibNtDLL); end; {$ELSE} {$ENDIF} END.
unit Cave; interface type Tarray= array of Word; TCave = class private average:Word; swidth:Word; slength:Word; Map_:Tarray; Map2:Tarray; Map_neigh:Array[0..5000,0..5000] of byte; function getMap(x,y:Integer):Word; procedure setMap(x,y:Integer;v:Word); procedure Initialize; procedure Copy_arrays; procedure FillArray(var a:Tarray); function rule(x,y:Word):Boolean; function GetIndex(x,y:Word):LongWord; function neighbours(x: Integer; y: Integer; w:word):Word; public property map[x,y:Integer]:Word read getMap write setMap; constructor Create(x,y:Word); function Iterate:Tarray; end; implementation function TCave.GetIndex(x: Word; y: Word):LongWord; begin result:=y*swidth+x end; function TCave.getMap(x,y:integer):Word; Begin if (x<0) or (x>swidth-1) or (y<0) or (y>slength-1) then result:=1 else result:=Map_[GetIndex(x,y)]; End; procedure TCave.setMap(x: Integer; y: Integer; v: Word); begin Map_[GetIndex(x,y)]:=v; end; procedure TCave.Initialize; var x,y,r:Word; begin for x := 0 to slength-1 do for y := 0 to swidth-1 do Begin r:=Random(100); if r<49 then map[x,y]:=1; Map_neigh[x,y]:=4;//Random(3)+3; End; end; procedure TCave.FillArray(var a:Tarray); var x:LongWord; Begin for x := 0 to swidth*slength do a[x]:=0; End; Constructor TCave.Create(x: Word; y: Word); begin swidth:=x; slength:=y; SetLength(map_,x*y); SetLength(map2,x*y); Fillarray(map_); Fillarray(map2); Initialize; end; procedure TCave.Copy_arrays; var x:LongInt; Begin for x := 0 to swidth*slength do Map_[x]:=Map2[x]; End; function TCave.rule(x,y:Word):Boolean; Begin if Map_neigh[x,y]<neighbours(x,y,1) then result:=true else result:=false End; function TCave.Iterate:Tarray; var x,y:Word; begin for x := 0 to slength-1 do for y := 0 to swidth-1 do if rule(x,y) then Begin if map[x,y]>0 then map2[GetIndex(x,y)]:=map[x,y] else map2[GetIndex(x,y)]:=average End else map2[GetIndex(x,y)]:=0; Copy_arrays; result:=Map_; end; function TCave.neighbours(x: Integer; y: Integer; w:Word):Word; var xx,yy:LongInt; begin average:=0; result:=0; for xx := x-w to x+w do for yy := y-w to y+w do Begin average:=average+map[xx,yy]; if map[xx,yy]>0 then result:=result+1; End; if result>0 then average:=average div result else average:=1; end; end.
unit LoggerPro.OutputDebugStringAppender; { <@abstract(The unit to include if you want to use @link(TLoggerProOutputDebugStringAppender)) @author(Daniele Teti) } interface uses LoggerPro, System.Classes; type { @abstract(This appenders sends logs to the @code(OutputDebugString) function on Windows OSes) To learn how to use this appender, check the sample @code(outputdebugstring_appender.dproj) } TLoggerProOutputDebugStringAppender = class(TLoggerProAppenderBase) private FModuleName: string; public constructor Create; override; procedure Setup; override; procedure TearDown; override; procedure WriteLog(const aLogItem: TLogItem); override; end; implementation uses System.SysUtils, Winapi.Windows, Winapi.Messages, System.IOUtils; { TStringsLogAppender } const DEFAULT_LOG_FORMAT = '%0:s [TID %1:-8d][%2:-10s] %3:s [%4:s]'; constructor TLoggerProOutputDebugStringAppender.Create; begin inherited Create; end; procedure TLoggerProOutputDebugStringAppender.Setup; begin FModuleName := TPath.GetFileName(GetModuleName(HInstance)); end; procedure TLoggerProOutputDebugStringAppender.TearDown; begin // do nothing end; procedure TLoggerProOutputDebugStringAppender.WriteLog(const aLogItem : TLogItem); var lLog: string; begin lLog := Format('(' + FModuleName + ') => ' + DEFAULT_LOG_FORMAT, [datetimetostr(aLogItem.TimeStamp), aLogItem.ThreadID, aLogItem.LogTypeAsString, aLogItem.LogMessage, aLogItem.LogTag]); OutputDebugString(PChar(lLog)); end; end.
{HACER QUE TODO TPOINT APUNTE SIEMPRE A SUS VERTICES Y QUE DEJE DE HACERLO SI UN VERTICE SE DESPRENDE} {ELIMINAR CAMPO REFERENCES DE TPOINT} {3D object handling. this unit is related to uRickGL Tentity: an entity or object tface: a face of an entity, each entity has many faces Tvertex: a vertex of a face, each face has many vertices. By: Ricardo Sarmiento delphiman@hotmail.com } unit U3Dpolys; interface Uses classes, SysUtils, OpenGL; {MWMWMWMWMWMWMWMWMWMW Classes definition MWMWMWMWMWMWMWMWMWMWMWMW} type tface=Class; Tpoint = Class; Ttexture = Class; Tentity = Class(Tobject) {entity or object or 3D mesh} Faces:TList; {2D polygons list belonging to the mesh} Points:Tlist; {list of all the vertices of the entity} R,G,B,A:Byte; {default color to use } Position:array[1..3] of single; {position of entity in space X,Y,Z} rotation:array[1..3] of single; {Orientation, Rx,Ry,Rz} id:GLuInt; {entity's identIfier, optional} Texture:Ttexture; {pointer to a texture} wireframe:byte; {0: use points, 1:use wireframes, 2: use solid poligons} textured:boolean; {indicates if the texture has been created or not} constructor Create; {create a zero-polygon entity} Destructor Destroy; override; Procedure Load(st:String); {load from propietary file format} Procedure Save(st:String); {not yet implemented} Procedure SetColor(iR,iG,iB:Byte); {change entityīs color} Procedure Move(X,Y,Z:single); {move entity to new position} Procedure Rotate(Rx,Ry,Rz:single); {turn entity to new orientation} Procedure Redraw; {construct the entity using OpenGL commands} Procedure LoadDXF(st:String;culling:boolean); {Read DXF file in ST and generate the mesh} {if param culling is true, generate two opposite faces for each polygon in the DXF file} Procedure CalcNormals; {calculate normals for each vertex} Procedure Center; {find the geometric center of the entity and put it at 0,0,0} Function AddFace:tface; {add a new, empty face to the entity} Function FindPoint(ix,iy,iz:single):Tpoint; {search for a point near ix,iy,iz} Function CreateTexture:TTexture; {create and assign a texture to the entity} Procedure DeleteTexture; {delete the texture} end; {Tentity} {useful when rotating entity around itīs center} tface=Class(Tobject) {a face or polygon of an entity} Vertices:Tlist; {the meshīs vertex list} r,g,b:Byte; {face color} Owner:Tentity; {points to the owner entity} ApplyTexture:boolean; {use texturing or not in this face} constructor Create(iOwner:Tentity); {create the face and assign its owner entity} Destructor Destroy; override; Procedure AddVertex(x,y,z,nx,ny,nz:single); {add vertex at X,Y,Z with normal nx,ny,nz} Procedure Redraw; {draw face using OpenGL commands} {calculate normal given 3 points of the face, normally not called directly} Procedure CalcNormal(uno,dos,tres:integer;var inx,iny,inz:single); Procedure SetColor(ir,ig,ib:Byte); {set the desired color of the face} end; {tface} Tpoint = Class(Tobject) {a colored point in space} x,y,z:single; {position x,y,z} r,g,b:Byte; {vertexīs color, rgb} References:Byte; {number of vertices using the point for color and position} Vertices:Tlist; Constructor Create(ix,iy,iz:single); {set position and References to 0} Destructor Destroy; override; Procedure SetColor(ir,ig,ib:Byte); {set the desired color of the point} Procedure SetPosition(ix,iy,iz:single); {move the point to a dIfferent place} end; {Tpoint} Tvertex = Class(Tobject) {a vertex of a flat polygon} nx,ny,nz:single; {normal vector, each vertex has itīs own normal vector, this is useful for certain tricks} point:Tpoint; {points to position and color data} Owner:Tface; {points to the face that owns the vertex} Tx,Tz:single; {Texture X and Z coordinates} constructor Create(iowner:Tface;inx,iny,inz:single); {create vertex with its normal} Procedure SetColor(ir,ig,ib:Byte); {set the desired individual color of the vertex} Procedure SetPosition(ix,iy,iz:single); {move individually the vertex to a dIfferent place} Procedure MakeCopy; {create a new Tpoint instance, so that the vertex can modIfy individualy the color and position} end; {Tvertex} Ttexture = Class(Tobject) {a texture} Automatic:boolean; {use or not automatic texture coordinates generation} AutoXmult:array[0..3] of GLint; {multiply values for X coordinate} AutoZmult:array[0..3] of GLint; {multiply values for Z coordinate} AutoGenModeX:GLint; {coordinate calculation algorithm to be used: } AutoGenModeZ:GLint; {GL_object_linear, GL_Eye_linear or GL_Sphere_map} WrapSMode:Glint; WrapTMode:Glint; MagFilter:Glint; MinFilter:Glint; EnvironmentMode:GLint; {GL_decal, GL_modulate or GL_blend} EnvBlendColor:Array[0..3] of byte; {RGBA color if EnvironmentMode is blend} Owner:Tentity; {a texture can be owned by an Entity} MyList:GLsizei; {number of the display list for this texture} Constructor Create(iowner:Tentity); {set defaults for all fields} Destructor destroy; override;{destroy the display list} Function LoadTexture(st:string):shortint; {load a new texture file, return 0 if ok, negative number if error} Procedure Redraw; {call the display list, itīs not really a redraw, itīs part of one} end; {Ttexture} Const {global constants} MinimalDistance=0.0001; {If two points are this far from each other, they can be considered to be in the same position} var {global variables} // this two variables are used in this unit and in unit UrickGL: PutNames:boolean; {If true put names to vertex and entity primitives when rendering} ActualVertexNumber:LongInt; {used to mark every vertex with a dIfferent name in every entity} implementation {MWMWMWMWMWMWMWMWMWMW IMPLEMENTATION of the CLASSES MWMWMWMWMWMWMWMWMWMWMWMW} constructor Tentity.create; begin inherited create; id:=0; {initiallly this value has no importance} Faces:=Tlist.create; Points:=Tlist.create; SetColor(128,128,128); {use a medium grey color} A:=255; {alpha component is by default opaque} wireframe:=2; {by default use solid poligons for rendering} textured:=False; {a texture has not been assigned to this entity} end; Destructor Tentity.destroy; begin if textured then DeleteTexture; {erase the texture if it exists} Points.Free; Faces.Free; inherited Destroy; end; Procedure Tentity.Load; var f:file; numFaces, NumPoints, NumTextures, i,j:LongInt; IdData:array[0..3] of char; Reserved:array[1..20] of Byte; ix,iy,iz:single; inx,iny,inz:single; ir,ig,ib:Byte; Point:Tpoint; Face:Tface; Vertex:Tvertex; PointNum:longint; numVertices:byte; {this limits the vertex count for each polygon to less than 255 vertices, more than enough} Version, SubVersion:byte; begin assignFile(f,st); If not FileExists(st) then exit; Reset(f,1); BlockRead(f,IdData,sizeof(IdData)); BlockRead(f,Version,sizeof(version)); BlockRead(f,SubVersion,sizeof(SubVersion)); if version=1 then begin {first clear old data stored in object} Faces.Clear; Points.Clear; {then, begin to read new data} BlockRead(f,ir,sizeof(ir)); BlockRead(f,ig,sizeof(ig)); BlockRead(f,ib,sizeof(ib)); SetColor(ir,ig,ib); BlockRead(f,numFaces,sizeof(numFaces)); BlockRead(f,numPoints,sizeof(numPoints)); BlockRead(f,numTextures,sizeof(numTextures)); {not used yet} BlockRead(f,Reserved,sizeof(Reserved)); {for future purposes} {read Points} i:=0; while i<NumPoints do begin BlockRead(f,ix,sizeof(ix)); BlockRead(f,iy,sizeof(iy)); BlockRead(f,iz,sizeof(iz)); BlockRead(f,ir,sizeof(ir)); BlockRead(f,ig,sizeof(ig)); BlockRead(f,ib,sizeof(ib)); Point:=Tpoint.create(ix,iy,iz); Point.SetColor(ir,ig,ib); Points.add(point); inc(i); end; {Read faces} i:=0; while i<NumFaces do begin BlockRead(f,ir,sizeof(ir)); BlockRead(f,ig,sizeof(ig)); BlockRead(f,ib,sizeof(ib)); BlockRead(f,numVertices,SizeOf(numVertices)); Face:=AddFace; Face.SetColor(ir,ig,ib); j:=0; While j<NumVertices do begin BlockRead(f,inx,sizeof(inx)); BlockRead(f,iny,sizeof(iny)); BlockRead(f,inz,sizeof(inz)); BlockRead(f,PointNum,sizeof(PointNum)); Vertex:=Tvertex.create(Face,inx,iny,inz); Vertex.Point:=Tpoint(Points.items[PointNum]); Vertex.Point.Vertices.add(Vertex); {the point must have the references to its vertices} inc(Vertex.Point.references); Face.Vertices.add(vertex); inc(j); end; inc(i); end; {Read Texture coordinates, not yet implemented} end; CloseFile(f); end; Procedure Tentity.Save; var f:file; numFaces, NumPoints, NumTextures, i,j:LongInt; IdData:array[0..3] of char; Reserved:array[1..20] of Byte; Point:Tpoint; Face:Tface; Vertex:Tvertex; PointNum:longint; numVertices:byte; {this limits the vertex count for each polygon to less than 255 vertices, more than enough} Version, SubVersion:byte; begin assignFile(f,st); ReWrite(f,1); IdData[0]:='3'; IdData[1]:='D'; IdData[2]:='P'; IdData[3]:='F'; {3DPF: 3D Propietary Format} Version:=1; {this file was stored using algorithm version 1. } SubVersion:=0; {this file was stored using algorithm version .0} NumFaces:=Faces.count; NumPoints:=Points.Count; NumTextures:=0; {by now no textures are allowed} BlockWrite(f,IdData,sizeof(IdData)); BlockWrite(f,Version,sizeof(Version)); BlockWrite(f,SubVersion,sizeof(SubVersion)); BlockWrite(f,r,sizeof(r)); BlockWrite(f,g,sizeof(g)); BlockWrite(f,b,sizeof(b)); BlockWrite(f,NumFaces,sizeof(NumFaces)); BlockWrite(f,NumPoints,sizeof(NumPoints)); BlockWrite(f,NumTextures,sizeof(NumTextures)); {not used yet} BlockWrite(f,Reserved,sizeof(Reserved)); {for future purposes} {Write Points} i:=0; while i<NumPoints do begin Point:=Tpoint(Points.items[i]); with point do begin BlockWrite(f,x,sizeof(x)); BlockWrite(f,y,sizeof(y)); BlockWrite(f,z,sizeof(z)); BlockWrite(f,r,sizeof(r)); BlockWrite(f,g,sizeof(g)); BlockWrite(f,b,sizeof(b)); end; inc(i); end; {Write faces} i:=0; while i<NumFaces do begin Face:=Tface(Faces.items[i]); with face do begin NumVertices:=Vertices.count; BlockWrite(f,r,sizeof(r)); BlockWrite(f,g,sizeof(g)); BlockWrite(f,b,sizeof(b)); BlockWrite(f,NumVertices,SizeOf(NumVertices)); end; j:=0; While j<NumVertices do begin Vertex:=Tvertex(Face.vertices.items[j]); with Vertex do begin PointNum:=Points.Indexof(Point); BlockWrite(f,nx,sizeof(nx)); BlockWrite(f,ny,sizeof(ny)); BlockWrite(f,nz,sizeof(nz)); BlockWrite(f,PointNum,sizeof(PointNum)); end; inc(j); end; inc(i); end; {Write Texture coordinates, not yet implemented} CloseFile(f); end; Procedure Tentity.SetColor; begin R:=iR; G:=iG; B:=iB; end; Procedure Tentity.Move; begin Position[1]:=x; Position[2]:=y; Position[3]:=z; end; Procedure Tentity.Rotate; begin rotation[1]:=rx; rotation[2]:=ry; rotation[3]:=rz; end; Procedure Tentity.Redraw; var i,num:integer; begin GlPushMatrix(); case wireframe of 0:GlPolygonMode(GL_FRONT_AND_BACK, GL_POINT); 1:GlPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 2:GlPolygonMode(GL_FRONT_AND_BACK, GL_FILL); end; glTranslatef(Position[1],Position[2],Position[3]); {translate, not the object but the coordinate system} glRotatef(rotation[1], 1.0, 0.0, 0.0); {same, rotate the coordinate system} glRotatef(rotation[2], 0.0, 1.0, 0.0); glRotatef(rotation[3], 0.0, 0.0, 1.0); if Assigned(Texture) then {there is a texture assigned} Texture.redraw; If PutNames then {If this is active then each entity has itīs own name} begin GlLoadName(id); GLPassThrough(id); {it should be: GLfloat(id), but it wouldnīt compile} end; i:=0; num:=Faces.count; while i<num do begin If PutNames then begin ActualVertexNumber:=i; {from 0 to Faces.count-1} ActualVertexNumber:=ActualVertexNumber shl 16; {a LongInt has 32 bits, so this shIfts the actual face number to the upper 16 bits} end; tface(Faces.items[i]).Redraw; inc(i); end; GlPopMatrix(); end; Procedure Tentity.LoadDXF; var f:textfile; st1,st2:string; in_entities:boolean; kind,group,err:integer; analyzing:boolean; x1,x2,y1,y2,z1,z2,x3,y3,z3,x4,y4,z4:single; Face:tface; Procedure DivRectangle; begin Face:=AddFace; Face.AddVertex(x4,y4,z4,0,0,1); Face.AddVertex(x3,y3,z3,0,0,1); Face.AddVertex(x2,y2,z2,0,0,1); Face:=AddFace; Face.AddVertex(x4,y4,z4,0,0,1); Face.AddVertex(x2,y2,z2,0,0,1); Face.AddVertex(x1,y1,z1,0,0,1); if Culling then begin {for 3D studio: double the faces but looking the opposite way} Face:=AddFace; Face.AddVertex(x2,y2,z2,0,0,1); Face.AddVertex(x3,y3,z3,0,0,1); Face.AddVertex(x4,y4,z4,0,0,1); Face:=AddFace; Face.AddVertex(x1,y1,z1,0,0,1); Face.AddVertex(x2,y2,z2,0,0,1); Face.AddVertex(x4,y4,z4,0,0,1); end; end; begin {first clear old data stored in object} Faces.Clear; Points.Clear; {then, begin} assignfile(f,st); reset(f); in_entities:=false; repeat readln(f,st1); If st1='ENTITIES' then in_entities:=true; until in_entities or eof(f); analyzing:=false; kind:=0; x1:=0; x2:=0; x3:=0; x4:=0; y1:=0; y2:=0; y3:=0; y4:=0; z1:=0; z2:=0; z3:=0; z4:=0; If in_entities then repeat readln(f,st1); readln(f,st2); group:=StrToInt(st1); case group of 0:begin If analyzing then begin case kind of 1:begin if (x4<>x3) or (y4<>y3) or (z4<>z3) then DivRectangle else begin Face:=AddFace; Face.AddVertex(x3,y3,z3,0,0,1); Face.AddVertex(x2,y2,z2,0,0,1); Face.AddVertex(x1,y1,z1,0,0,1); if Culling then begin {for 3D studio: double the faces but looking the opposite way} Face:=AddFace; Face.AddVertex(x1,y1,z1,0,0,1); Face.AddVertex(x2,y2,z2,0,0,1); Face.AddVertex(x3,y3,z3,0,0,1); end; end; end; end; {case} kind:=0; end; If st2 ='3DFACE' then kind:=1; {line} If kind>0 then analyzing:=true; end; 10: val(st2,x1,err); 20: val(st2,y1,err); 30: val(st2,z1,err); 11: val(st2,x2,err); 21: val(st2,y2,err); 31: val(st2,z2,err); 12: val(st2,x3,err); 22: val(st2,y3,err); 32: val(st2,z3,err); 13: val(st2,x4,err); 23: val(st2,y4,err); 33: val(st2,z4,err); end; {of case} until eof(f); closefile(f); end; Procedure Tentity.CalcNormals; var Face:tface; i,j,numFaces,NumVertices:integer; inx,iny,inz:single; begin i:=0; numFaces:=Faces.Count; while i<numFaces do begin j:=0; Face:=tface(Faces.Items[i]); numVertices:=Face.Vertices.Count; Face.CalcNormal(0,1,2,inx,iny,inz); {it uses the 1st, 2nd and 3rd vertex of the face} while j<numVertices do begin with Tvertex(Face.Vertices[j]) do begin nx:=inx; ny:=iny; nz:=inz; end; inc(j); end; inc(i,1); end; end; Procedure Tentity.Center; var j,NumPoints:integer; x,y,z, maxx,maxy,maxz, minx,miny,minz, cx,cy,cz:single; begin maxx:=-100000000; maxy:=-100000000; maxz:=-100000000; minx:= 100000000; miny:= 100000000; minz:= 100000000; {obtain the farthest vertices} NumPoints:=Points.Count; j:=0; while j<NumPoints do begin x:=Tpoint(Points.items[j]).x; y:=Tpoint(Points.items[j]).y; z:=Tpoint(Points.items[j]).z; If x<minx then minx:=x else If x>maxX then maxX:=x; If y<miny then miny:=y else If y>maxy then maxy:=y; If z<minz then minz:=z else If z>maxz then maxz:=z; inc(j); end; {calculate the center coordinates} cx:=minx+(maxx-minx)/2; cy:=miny+(maxy-miny)/2; cz:=minz+(maxz-minz)/2; {now move the vertices} NumPoints:=Points.Count; j:=0; while j<NumPoints do begin TPoint(Points.items[j]).x:=TPoint(Points.items[j]).x-cx; TPoint(Points.items[j]).y:=TPoint(Points.items[j]).y-cy; TPoint(Points.items[j]).z:=TPoint(Points.items[j]).z-cz; inc(j); end; end; Function Tentity.AddFace; {add a new face to the entity} begin Result:=tface.create(Self); Faces.add(result); Result.SetColor(r,g,b); end; Function Tentity.FindPoint; {search for a point near to x,y,z} var i,NumPoints:integer; begin Result:=nil; numPoints:=Points.count; i:=0; while i<numPoints do begin with Tpoint(points.items[i]) do If SQR(x-ix)+SQR(y-iy)+SQR(z-iz)<MinimalDistance then begin Result:=Tpoint(points.items[i]); Exit; end; inc(i); end; end; Function Tentity.CreateTexture; begin Texture:=Ttexture.create(self); Result:=texture; textured:=True; end; Procedure Tentity.DeleteTexture; begin Texture.free; textured:=False; end; Constructor tface.Create; begin inherited create; Vertices:=Tlist.create; Owner:=iOwner; if Assigned(Owner.texture) then ApplyTexture:=true {if there is a texture assigned, then by default the polygon will be textured too} else ApplyTexture:=false; {the polygon wonīt have a texture on it} r:=128; g:=128; b:=128; end; Destructor tface.Destroy; begin Vertices.free; inherited destroy; end; Procedure tface.AddVertex; var Vertex:Tvertex; Point:Tpoint; begin Vertex:=Tvertex.create(Self,nx,ny,nz); {the vertex is always created} Point:=Owner.FindPoint(x,y,z); {find a very near point to x,y,z, If found it will be used} If (Point=nil) or (point.r<>r) or (point.g<>g) or (point.b<>b) then {a near, same color point was not found} begin Point:=Tpoint.Create(x,y,z); Point.SetColor(r,g,b); Owner.Points.Add(Point); end; Vertex.Point:=Point; {reference the point...} Point.vertices.add(vertex); {...and the point also references the vertex} inc(Point.References); {now the vertex is referencing the point} Vertices.Add(Vertex); end; Procedure tface.Redraw; var i,num:LongInt; manual:boolean; a:byte; begin If PutNames then {each face has itīs own name} begin GlLoadName(ActualVertexNumber); GlPassThrough(ActualVertexNumber); {it should be: GLfloat(ActualVertexNumber), but it wouldnīt compile} end; if not ApplyTexture or not Assigned(owner.texture) then begin gldisable(GL_texture_2d); manual:=true; end else begin glenable(gl_texture_2d); manual:=not owner.texture.automatic; end; A:=owner.A; glBegin(GL_POLYGON); i:=0; num:=Vertices.count; while i<num do with Tvertex(Vertices.items[i]) do begin glnormal3f(nx,ny,nz); glColor4ub(point.r,point.g,point.b,A); if ApplyTexture and manual then GlTexCoord2F(tx,1-tz); glvertex3f(point.x,point.y,point.z); inc(i); end; glEnd; end; Procedure tface.CalcNormal; var longi,vx1,vy1,vz1,vx2,vy2,vz2:single; begin vx1:=Tvertex(Vertices.items[uno]).point.x-Tvertex(Vertices.items[dos]).point.x; vy1:=Tvertex(Vertices.items[uno]).point.y-Tvertex(Vertices.items[dos]).point.y; vz1:=Tvertex(Vertices.items[uno]).point.z-Tvertex(Vertices.items[dos]).point.z; vx2:=Tvertex(Vertices.items[dos]).point.x-Tvertex(Vertices.items[tres]).point.x; vy2:=Tvertex(Vertices.items[dos]).point.y-Tvertex(Vertices.items[tres]).point.y; vz2:=Tvertex(Vertices.items[dos]).point.z-Tvertex(Vertices.items[tres]).point.z; inx:=vy1*vz2 - vz1*vy2; iny:=vz1*vx2 - vx1*vz2; inz:=vx1*vy2 - vy1*vx2; {now reduce the vector to be unitary, length=1} longi:=sqrt(inx*inx + iny*iny + inz*inz); If longi=0 then longi:=1; {avoid zero division error} inx:=inx/ longi; iny:=iny/ longi; inz:=inz/ longi; end; Procedure tface.SetColor; begin r:=iR; g:=iG; b:=iB; end; Constructor Tpoint.Create; begin inherited Create; References:=0; Vertices:=Tlist.create; SetPosition(ix,iy,iz); SetColor(128,128,128); end; Destructor Tpoint.Destroy; var i:integer; begin for i:=0 to vertices.count-1 do Vertices.Items[i]:=nil; vertices.free; inherited destroy; end; Procedure Tpoint.SetColor(ir,ig,ib:Byte); {set the desired color of the point} begin r:=ir; g:=ig; b:=ib; end; Procedure Tpoint.SetPosition(ix,iy,iz:single); {move the point to a dIfferent place} begin x:=ix; y:=iy; z:=iz; end; Constructor Tvertex.Create; begin inherited Create; nx:=inx; ny:=iny; nz:=inz; Point:=nil; Owner:=iOwner; tx:=0; tz:=0; end; Procedure Tvertex.MakeCopy; var NewPoint:TPoint; begin If Point.References>1 then {check If the copy is really necesary} begin {the vertex is sharing the point, so letīs create its own point} dec(Point.References); {this vertex wonīt use that point again} NewPoint:=Tpoint.Create(Point.x,Point.y,Point.z); Owner.Owner.points.add(newPoint); with NewPoint do begin References:=1; {inc the references on the new point} r:=Point.r; g:=Point.g; b:=Point.b; end; Point:=newPoint; end; {now we are ready to set the individual values of our vertex} end; Procedure Tvertex.SetColor; begin MakeCopy; {If itīs necessary, the point will be duplicated so that the individual color can be modIfied} Point.r:=iR; Point.g:=iG; Point.b:=iB; end; Procedure Tvertex.SetPosition; begin MakeCopy; {If itīs necessary, the point will be duplicated so that the individual position can be modIfied} Point.x:=iX; Point.y:=iY; Point.z:=iZ; end; Constructor TTexture.Create; {set defaults for all fields} begin Owner:=iOwner; MyList:=glgenlists(1); {generate an empty list for this texture} WrapSmode:=gl_repeat; {tile the texture in X} WrapTmode:=gl_repeat; {tile the texture in Z} MagFilter:=gl_nearest; {texture using the nearest texel} MinFilter:=gl_nearest; {texture using the nearest texel} Automatic:=False; {by default the texture coordinates have to be calculated by hand} AutoGenModeX:=gl_object_linear; AutoGenModeZ:=gl_object_linear; AutoXmult[0]:=1; AutoXmult[1]:=0; AutoXmult[2]:=0; AutoXmult[3]:=0; AutoZmult[0]:=0; AutoZmult[1]:=0; AutoZmult[2]:=1; AutoZmult[3]:=0; EnvironmentMode:=GL_decal; {like the decals in a racing car} EnvBlendColor[0]:=0; EnvBlendColor[1]:=0; EnvBlendColor[2]:=0; EnvBlendColor[3]:=255; {alpha is by default 1} end; Destructor Ttexture.destroy; begin GLdeleteLists(MyList,1); {destroy the display list of the texture} inherited destroy; end; Function TTexture.LoadTexture(st:string):shortint; Const MB=19778; type ptybuff=^tybuff; ptybuffa=^tybuffa; tybuff=array[1..128000] of record r:byte; g:byte; b:byte; end; tybuffa=array[1..128000] of record r:byte; g:byte; b:byte; a:byte; end; var f:file; Buffer2b:ptybuff; Buffer2:pointer; Buffer3b:ptybuffa; Buffer3:pointer; i:longint; {$A-} header:record FileType:Word; {always MB} size:longint; Reserved1, Reserved2:word; {reserved for future purposes} offset:longint; {offset to image in bytes} end; {header} BMPInfo:record size:longint; {size of BMPinfo in bytes} width:longint; {width of the image in pixels} height:longint; {height of the image in pixels} planes:word; {number of planes (always 1)} Colorbits:word; {number of bits used to describe color in each pixel} compression:longint; {compression used} ImageSize:longint; {image size in bytes} XpixPerMeter:longint; {pixels per meter in X} YpixPerMeter:longint; {pixels per meter in Y} ColorUsed:longint; {number of the color used ŋŋŋ???} Important:longint; {number of "important" colors} end; {info} {$A+} begin if Not FileExists(st) then begin result:=-1; {file not found} exit; end; assignfile(f,st); reset(f,1); blockread(f,header,sizeof(header)); blockread(f,BMPinfo,sizeof(BMPinfo)); if header.FileType <> MB then begin result:=-2; {file type is not BMP} exit; end; header.size:=header.size-sizeof(header)-sizeof(BMPinfo); getmem(buffer2,header.size); getmem(buffer3,header.size*4 div 3); buffer2b:=ptybuff(buffer2); buffer3b:=ptybuffA(buffer3); Blockread(f,buffer2^,header.size); for i:=1 to header.size div 3 do begin buffer3b^[i].r:=buffer2b^[i].b; buffer3b^[i].g:=buffer2b^[i].g; buffer3b^[i].b:=buffer2b^[i].r; buffer3b^[i].a:=envblendcolor[3]; {obtain blend alpha from envblendcolor.alpha} end; closefile(f); GlNewList(MyList,gl_compile); glpixelstorei(gl_unpack_alignment,4); {OpenGL 1.0 ignores this one} glpixelstorei(gl_unpack_row_length,0); glpixelstorei(gl_unpack_skip_rows,0); glpixelstorei(gl_unpack_skip_pixels,0); {for GLteximage2D the parameters are: gl_Texture_2d, level of detail (0 unless using mipmapped textures) components: 3 for RGB, 4 for RGBA 1 for indexed 256 color width, height border: width of the border, between 0 and 2. Format: gl_color_index, GL_RGB, GL_rgbA, GL_luminance are the most used type of the data for each pixel pointer to image data} glenable(GL_BLEND); glblendfunc(gl_src_alpha, gl_one_minus_src_alpha); gltexImage2d(gl_texture_2d,0,4,BMPinfo.width,BMPinfo.height,0,gl_rgba,gl_unsigned_byte,buffer3); glendlist; result:=0; {no error} end; Procedure TTexture.redraw; {call the display list, itīs not really a redraw, itīs part of one} begin if Automatic then {automatic texture coordinates generation} begin gltexgeni (GL_s,gl_texture_gen_mode,AutoGenModeX); gltexgeniv(GL_s,gl_object_plane,addr(AutoXmult)); gltexgeni (GL_t,gl_texture_gen_mode,AutoGenModeZ); gltexgeniv(GL_t,gl_object_plane,addr(AutoZmult)); glenable(GL_TEXTURE_GEN_S); glenable(GL_TEXTURE_GEN_T); end; gltexparameteri(gl_texture_2d,gl_texture_wrap_s,WrapSmode); gltexparameteri(gl_texture_2d,gl_texture_wrap_t,WrapTmode); gltexparameteri(gl_texture_2d,gl_texture_mag_filter,MagFilter); gltexparameteri(gl_texture_2d,gl_texture_min_filter,MinFilter); gltexEnvi(gl_texture_env,gl_texture_env_mode,EnvironmentMode); glcalllist(MyList); end; initialization PutNames:=false; {initially, the primitives will not be named} end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type EDuplicate = class(Exception); TDataType = (dtUnknown, dtString, dtBoolean, dtInteger, dtFloat, dtDate, dtTime, dtDateTime, dtBlob); type { TFormatSettings } TFormatSettings = class private FTranslations: TStrings; procedure SetTranslations(Value: TStrings); protected procedure SetupTranslations; public constructor Create; published property Translations: TStrings read FTranslations write SetTranslations; end; function DataTypeToStr(Value: TDataType): string; function Translate(const ID: string): string; overload; function Translate(const ID: string; const Values: array of string): string; overload; function TranslateRS(const Msg: string; const Args: array of JSValue): String; overload; var FormatSettings: TFormatSettings = nil; ResourceString DuplicateMsg = 'An item with key %0:s already exists'; KeyNotFoundMsg = 'Method: %0:s key [''%1:s''] not found in container'; NotEmptyMsg = 'Hash table not empty.'; SErrNoSuchItem = 'No item in list for %p'; SDuplicateItem = 'Item already exists in list: %p'; implementation { TFormatSettings } constructor TFormatSettings.Create; begin inherited Create; FTranslations := TStringList.Create; SetupTranslations; end; procedure TFormatSettings.SetupTranslations; begin FTranslations.BeginUpdate; try FTranslations.Add('DuplicateMsg=An item with key %0:s already exists'); FTranslations.Add('TYPE_UNKNOWN=Unknown'); FTranslations.Add('TYPE_STRING=String'); FTranslations.Add('TYPE_BOOLEAN=Boolean'); FTranslations.Add('TYPE_INTEGER=Integer'); FTranslations.Add('TYPE_FLOAT=Float'); FTranslations.Add('TYPE_DATE=Date'); FTranslations.Add('TYPE_TIME=Time'); FTranslations.Add('TYPE_DATETIME=DateTime'); FTranslations.Add('TYPE_BLOB=Blob'); FTranslations.Add('TYPE_SYMBOL=Symbol'); FTranslations.Add('DLG_MSG=Message'); FTranslations.Add('DLG_BTN_OK=OK'); FTranslations.Add('DLG_BTN_CANCEL=Cancel'); FTranslations.Add('DLG_BTN_ABORT=Abort'); FTranslations.Add('DLG_BTN_RETRY=Retry'); FTranslations.Add('DLG_BTN_IGNORE=Ignore'); FTranslations.Add('DLG_BTN_YES=Yes'); FTranslations.Add('DLG_BTN_NO=No'); FTranslations.Add('DLG_BTN_ALL=All'); FTranslations.Add('DLG_BTN_NOTOALL=No to All'); FTranslations.Add('DLG_BTN_YESTOALL=Yes to All'); FTranslations.Add('DLG_BTN_CLOSE=Close'); FTranslations.Add('ERR_CMP_DESTROY="%s" component already destroyed'); FTranslations.Add('ERR_LOAD_PERSISTENT=Persistent load error (%s)'); FTranslations.Add('ERR_LOAD_METHOD=Method %s not found'); FTranslations.Add('ERR_SAVE_PERSISTENT=Persistent save error (%s)'); FTranslations.Add('ERR_SET_RANGE=Value "%s" out of range for set'); FTranslations.Add('ERR_BOOLEAN_LITERAL=Invalid boolean literal "%s" specified'); FTranslations.Add('ERR_FORMAT=Error in the format string %s (%s)'); FTranslations.Add('ERR_VALUE_CONVERT=Error converting %s value to %s value'); FTranslations.Add('ERR_VALUE_READONLY="%s" is read-only and cannot be modified'); FTranslations.Add('ERR_DATETIME_DATE=date'); FTranslations.Add('ERR_DATETIME_TIME=time'); FTranslations.Add('ERR_DATETIME_MONTH=Invalid month %s specified'); FTranslations.Add('ERR_DATETIME_DAY=Invalid day %s specified'); FTranslations.Add('ERR_DATETIME_TOOMANYCOMPS=Too many %s components'); FTranslations.Add('ERR_DATETIME_MISSINGCOMP=Missing %s component'); FTranslations.Add('ERR_DATETIME_INVALIDCOMP=Invalid %s component'); FTranslations.Add('ERR_DATETIME_INVALIDFORMAT=Invalid %s format'); FTranslations.Add('ERR_DATETIME_INVALID=Invalid %s (%s)'); FTranslations.Add('ERR_PARSE_TERMSTR=Unterminated string at %s'); FTranslations.Add('ERR_PARSE_MISSING=Missing %s'); FTranslations.Add('ERR_PARSE_EXPECT=Expected %s, instead found %s at %s'); FTranslations.Add('ERR_LIST_BOUNDS=List index %s out of bounds'); FTranslations.Add('ERR_LIST_SORT=You can only use the Find method when a list is sorted'); FTranslations.Add('ERR_OWNER=Invalid owner class %s passed to constructor'); FTranslations.Add('ERR_LOADUI_STATE=Error loading interface state (%s)'); FTranslations.Add('ERR_UI_DUPSTATE=The interface state %s already exists'); FTranslations.Add('ERR_UI_ELEMENTCLASS=Cannot find registered element class information ' + 'for the %s class'); FTranslations.Add('ERR_DOM_EVENTADD=Cannot add event handler to "%s" element for "%s" event'); FTranslations.Add('ERR_DOM_EVENTCLEAR=Cannot remove "%s" event handler from "%s"'); FTranslations.Add('ERR_HTTP_REQUEST=Error executing request "%s" (%s)'); FTranslations.Add('ERR_DATA_DUPCOL=The "%s" column already exists'); FTranslations.Add('ERR_DATA_COLNAME=Column names cannot be blank (%s)'); FTranslations.Add('ERR_DATA_COLTYPE=Unknown column type (%s)'); FTranslations.Add('ERR_DATA_COLLENGTH=Invalid "%s" column length %s'); FTranslations.Add('ERR_DATA_COLSCALE=Invalid "%s" column scale %s'); FTranslations.Add('ERR_DATA_CONNECT=Cannot connect to server'); FTranslations.Add('ERR_DATA_LOADCODE=Status code %s'); FTranslations.Add('ERR_DATA_LOAD=Dataset load response error (%s)'); FTranslations.Add('ERR_DATA_COMMIT=Database commit response error (%s)'); FTranslations.Add('ERR_DATA_TRANSACTIVE=A transaction is not active'); FTranslations.Add('ERR_DATA_PENDREQUEST=There are no pending requests'); FTranslations.Add('ERR_DATA_COLUMNS=At least one column must be defined for the "%s" dataset'); FTranslations.Add('ERR_DATA_OPEN=The "%s" dataset must be open in order to complete this operation'); FTranslations.Add('ERR_DATA_NOTOPEN=The "%s" dataset cannot be open when completing this operation'); FTranslations.Add('ERR_DATA_NOTEDITING=The "%s" dataset must be in an editable mode before a column ' + 'can be assigned a value'); FTranslations.Add('ERR_DATA_TRANSCLOSE=Cannot close the "%s" dataset while there are still ' + 'active transaction operations for the dataset'); FTranslations.Add('ERR_DATA_FINDMODE=The "%s" dataset is not in Find mode'); FTranslations.Add('ERR_DATA_FINDNEAR=You can only search for nearest matches in the "%s" dataset ' + 'when searching on columns that match the current sort order'); FTranslations.Add('ERR_DATA_COLNOTFOUND=Column "%s" not found'); FTranslations.Add('ERR_DATA_TRANSDATASET=Invalid dataset "%s" specified in the transaction operations'); FTranslations.Add('ERR_DATA_TRANSOPTYPE=Invalid or unknown operation type %s specified in the transaction operations'); FTranslations.Add('ERR_DATA_DATASETDB=The "%s" dataset cannot be loaded using the "%s" database'); FTranslations.Add('ERR_APP_ERRORLINE=Line: %s'); FTranslations.Add('ERR_APP_ERRORTITLE=Application Error'); FTranslations.Add('APP_LOAD_MESSAGE=Loading %s...'); FTranslations.Add('ERR_DLG_BUTTONS=You must specify at least one button for the message dialog'); FTranslations.Add('ERR_FORM_SHOWMODAL=You cannot call ShowModal for the embedded form %s'); FTranslations.Add('ERR_CTRL_PARENT=The %s control cannot be a parent of the %s control'); FTranslations.Add('ERR_CALENDAR_COLINDEX=Column index %s out of bounds'); FTranslations.Add('ERR_CALENDAR_ROWINDEX=Row index %s out of bounds'); FTranslations.Add('ERR_GRID_COLINDEX=Column index %s out of bounds'); FTranslations.Add('ERR_GRID_ROWINDEX=Row index %s out of bounds'); FTranslations.Add('ERR_GRID_COLNOTFOUND=Column "%s" not found'); FTranslations.Add('ERR_CANVAS=Your browser does not have HTML5 canvas support'); FTranslations.Add('ERR_STORAGE=Your browser does not have HTML5 persistent storage support'); FTranslations.Add('ERR_SCRIPT_LOAD=Your browser does not support dynamic script loading'); FTranslations.Add('ERR_MEDIA=Your browser does not have HTML5 media support'); FTranslations.Add('ERR_MAP=The map API has not been loaded'); FTranslations.Add('ERR_MAP_GEOCODE=Geocoding request error "%s"'); FTranslations.Add('ERR_MAP_LOCNOTFOUND=Location "%s" not found'); FTranslations.Add('ERR_MAP_DUPLOC=The "%s" location already exists'); FTranslations.Add('ERR_MAP_LOCNAME=Location names cannot be blank (%s)'); FTranslations.Add('ERR_SIZER_CONTROL=The sizer control itself cannot be assigned as the target control'); FTranslations.Add('ERR_ZOOM_FACTOR=Zoom factor %s invalid, factor must be between 1 and 100'); FTranslations.Add('ERR_SLIDE_COUNT=At least %s slide images must be specifed before the slide ' + 'show can be started'); finally FTranslations.EndUpdate; end; end; procedure TFormatSettings.SetTranslations(Value: TStrings); begin FTranslations.Assign(Value); end; function DataTypeToStr(Value: TDataType): string; begin case Value of dtUnknown: Result := Translate('TYPE_UNKNOWN'); dtString: Result := Translate('TYPE_STRING'); dtBoolean: Result := Translate('TYPE_BOOLEAN'); dtInteger: Result := Translate('TYPE_INTEGER'); dtFloat: Result := Translate('TYPE_FLOAT'); dtDate: Result := Translate('TYPE_DATE'); dtTime: Result := Translate('TYPE_TIME'); dtDateTime: Result := Translate('TYPE_DATETIME'); dtBlob: Result := Translate('TYPE_BLOB'); else Result := ''; end; end; function TranslateRS(const Msg: string; const Args: array of JSValue): String; begin Result:= Format(Msg,Args); end; function Translate(const ID: string): string; begin Result:= FormatSettings.Translations.Values[ID]; end; function Translate(const ID: string; const Values: array of string): string; begin Result := Format(Translate(ID), Values); end; initialization FormatSettings := TFormatSettings.Create; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TPFisica = class private FCPF: string; procedure SetCPF(const Value: string); published property CPF: string read FCPF write SetCPF; end; TPJuridica = class private FCNPJ: string; procedure SetCNPJ(const Value: string); published property CNPJ: string read FCNPJ write SetCNPJ; end; TPessoa<T:constructor> = class private FTipo: T; procedure SetTipo(const Value: T); published property Tipo: T read FTipo write SetTipo; public constructor Create; end; TForm1 = class(TForm) Button1: TButton; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { TPJuridica } procedure TPJuridica.SetCNPJ(const Value: string); begin FCNPJ := Value; end; { TPFisica } procedure TPFisica.SetCPF(const Value: string); begin FCPF := Value; end; { TPessoa<T> } constructor TPessoa<T>.Create; begin FTipo := T.Create; end; procedure TPessoa<T>.SetTipo(const Value: T); begin FTipo := Value; end; procedure TForm1.Button1Click(Sender: TObject); var pf: TPessoa<TPFisica>; begin try pf := TPessoa<TPFisica>.Create; pf.Tipo.CPF := '12324444'; finally pf.Free; end; end; procedure TForm1.Button2Click(Sender: TObject); var pj: TPessoa<TPJuridica>; begin try pj := TPessoa<TPJuridica>.Create; pj.Tipo.CNPJ := '234234234234'; finally pj.Free; end; end; end.
unit DXPDateEdit; interface uses SysUtils, Classes, Controls, StdCtrls, Graphics, Messages, Windows, CommCtrl, uIValidatable, Forms, DXPMessageOutPut, DXPUtils; type // opRequired - Validar se foi preenchido; // opPrimaryKey - Desabilita quando o crud esta em estado de dsEdit; TOptions = set of TOption; // TDXPDateEdit = class(TCustomEdit, IValidatable) private FBaseColor: TColor; FOptions: TOptions; FMessageOutPut: TDXPMessageOutPut; FCaption: string; FReadOnly: Boolean; // FEstaDeletando: Boolean; // procedure SetValidations(const Value: TOptions); procedure SetMessageOutPut(const Value: TDXPMessageOutPut); procedure SetReadOnly(const Value: boolean); function GetDate: TDateTime; procedure SetDate(const Value: TDateTime); { Private declarations } protected procedure KeyPress(var Key: Char); override; procedure Change; override; procedure DoEnter; override; procedure DoExit; override; procedure DoSetTextHint(const Value: string); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; // function IsValid: boolean; { Public declarations } published property Align; property Alignment; property Anchors; property AutoSelect; property AutoSize; property BevelEdges; property BevelInner; property BevelKind default bkFlat; property BevelOuter; property BevelWidth; property BiDiMode; property BorderStyle default bsNone; property Caption: string read FCaption write FCaption; property CharCase; property Color; property Constraints; property Ctl3D; property Date: TDateTime read GetDate write SetDate; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property HideSelection; property ImeMode; property ImeName; property MaxLength; property MessageOutPut: TDXPMessageOutPut read FMessageOutPut write SetMessageOutPut; property NumbersOnly; property OEMConvert; property Options: TOptions read FOptions write SetValidations; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PasswordChar; property PopupMenu; property ReadOnly: boolean read FReadOnly write SetReadOnly default false; property ShowHint; property TabOrder; property TabStop; property Text; property TextHint; property Touch; property Visible; property OnChange; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseActivate; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; { Published declarations } end; implementation { TDXPDateEdit } function TDXPDateEdit.GetDate: TDateTime; var Data: TDateTime; begin Result := 0; if ( Text <> '' ) and ( Text <> Name ) then begin try Data := StrToDate( Text ); // Text := FormatDateTime('dd/mm/yyyy', Data); // Result := StrToDate( Text ); except ShowMsgInformation( 'Data incorreta.' ); TryFocus( Self ); end; end; end; procedure TDXPDateEdit.Change; begin inherited; if not( FEstaDeletando ) and ( Length( Text ) in [2,5] ) then begin Text := Text + '/'; SelStart := Length( Text ); end; end; constructor TDXPDateEdit.Create(AOwner: TComponent); begin inherited Create( AOwner ); // BorderStyle := bsNone; BevelKind := bkFlat; FReadOnly := false; MaxLength := 10; end; destructor TDXPDateEdit.Destroy; begin inherited Destroy; end; procedure TDXPDateEdit.DoEnter; begin inherited; // FBaseColor := Color; Color := clInfoBk; end; procedure TDXPDateEdit.DoExit; var Data: TDateTime; Converteu: Boolean; begin if ( Trim( Text ) <> '' ) then begin Converteu := False; try Data := StrToDate( Text ); // Text := FormatDateTime('dd/mm/yyyy', Data); // Converteu := True; except if Assigned( FMessageOutPut ) then FMessageOutPut.AddMessage( 'Data incorreta.', FCaption, Self ) else begin ShowMsgInformation( 'Data incorreta.' ); TryFocus( Self ); end; end; // if not( Converteu ) then Exit; end; // Color := FBaseColor; // inherited DoExit; end; procedure TDXPDateEdit.DoSetTextHint(const Value: string); begin {TODO -oAraujo -cComponents : Validar versão do windows} if CheckWin32Version( 5, 1 ) then SendTextMessage( Handle, EM_SETCUEBANNER, WPARAM(0), Value ); end; function TDXPDateEdit.IsValid: boolean; begin Result := false; // if ( opRequired in FOptions ) and ( Trim( Text ) = '' ) then begin if Assigned( FMessageOutPut ) then FMessageOutPut.AddMessage( 'Obrigatório.', FCaption, Self ) else begin ShowMsgInformation( FCaption + ': Informação obrigatória.' ); TryFocus( Self ); end; // Exit; end; // Result := true; end; procedure TDXPDateEdit.KeyPress(var Key: Char); begin inherited; FEstaDeletando := Key = #8; end; procedure TDXPDateEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification( AComponent, Operation ); // if ( AComponent = FMessageOutPut ) and ( Operation = opRemove ) then FMessageOutPut := nil; end; procedure TDXPDateEdit.SetDate(const Value: TDateTime); begin if ( Value <> 0 ) then Text := FormatDateTime('dd/mm/yyyy', Value) else Text := ''; end; procedure TDXPDateEdit.SetMessageOutPut(const Value: TDXPMessageOutPut); begin if Assigned( FMessageOutPut ) then FMessageOutPut.RemoveFreeNotification( Self ); // FMessageOutPut := Value; // if Assigned( FMessageOutPut ) then FMessageOutPut.FreeNotification( Self ); end; procedure TDXPDateEdit.SetReadOnly(const Value: boolean); begin inherited ReadOnly := Value; FReadOnly := Value; // if FReadOnly then Color := clBtnFace else Color := clWindow; end; procedure TDXPDateEdit.SetValidations(const Value: TOptions); begin if Value <> FOptions then FOptions := Value; end; end.
unit Ecommerce.DTO; interface uses System.Generics.Collections, REST.Json, Serialize.Attributes, Serialialize.Types; {$M+} type TItemDTO = class private FCodigoProduto: String; FDescCategoriaProduto: string; FDescProduto: string; [JsonNameAttribute('codigo')] FIdCategoriaProduto: string; FNomeProduto: string; FPreco: Double; FUnidade: string; FUnidadeCompleta: string; public property CodigoProduto: String read FCodigoProduto write FCodigoProduto; property DescCategoriaProduto: string read FDescCategoriaProduto write FDescCategoriaProduto; property DescProduto: string read FDescProduto write FDescProduto; property IdCategoriaProduto: string read FIdCategoriaProduto write FIdCategoriaProduto; property NomeProduto: string read FNomeProduto write FNomeProduto; property Preco: Double read FPreco write FPreco; property Unidade: string read FUnidade write FUnidade; property UnidadeCompleta: string read FUnidadeCompleta write FUnidadeCompleta; end; TProdutosDTO = class private [ArrayObjects(tpObjectList)] FItems: TObjectList<TItemDTO>; function GetItems: TObjectList<TItemDTO>; public property Items: TObjectList<TItemDTO> read GetItems; constructor Create; destructor Destroy; override; end; implementation { TRootDTO } constructor TProdutosDTO.Create; begin FItems := TObjectList<TItemDTO>.Create(true); // FItemsArray := TArray<TItemDTO>.Create(); // FItems.AddRange(FItemsArray); end; destructor TProdutosDTO.Destroy; begin GetItems.Free; inherited; end; function TProdutosDTO.GetItems: TObjectList<TItemDTO>; begin Result := FItems; end; end.
unit uUtils; {******************************************************************************* * * * Название модуля : * * * * uUtils * * * * Назначение модуля : * * * * Централизованное хранение используемых в приложении процедур и функций. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Windows, Classes, SysUtils, Dialogs, Controls, RxMemDS, DB, pFIBDataBase, Fib, IniFiles, Registry, uTypes, uLib; procedure ReadIniFile ( const aFileName: String; const aDefIniParams: array of TDefIniParams; aIniParams: TStringList ); procedure FillDataSet ( aDataSet: TRxMemoryData; const aSourceList: TUsrStringList; var aSelRecCount: Integer; const aMode: TFillMode = fmInsert ); procedure LogException ( const aFileName: TFileName ); procedure ParseFileName ( const aFileName, aKeyExpr: String; var aScriptInfo: TScriptInfo; aSections: TStringList = nil ); procedure ExtractKeyBlock ( var aKeyBlock: String; var aSeparatorCount: Integer; const aSeparatorChar: String ); procedure CreateMyProcess ( const aAppName, aCommandLine: PAnsiChar; aWindowState: Word ); procedure DelDirEndDelimiter ( var aDirPath: String ); procedure SetDirEndDelimiter ( var aDirPath: String ); function FindText ( aSourceDS: TRxMemoryData; const aSearchFieldName: String; const aSearchParams: TPtr_SearchParams ): Boolean; function GetKeyExpr ( const aProjectName: String ): String; function LoadScripts ( const aFilterParams: TFilterParams; var aScriptNames: TUsrStringList; var aMaxUpdNumber: TUpdateNumInfo ): TLoadScrResult; function RenameScript ( const aOldFileName: String; var aNewFileName: String; const aRenameParams: TRenameParams ): Boolean; function SelectRecords ( aDataSet: TRxMemoryData; const aSelectionMode: TSelectionMode ): Integer; function IsDateInPeriod ( const aCurrDate: TDate; const aDateBeg, aDateEnd: String ): Boolean; function TestConnection ( aDataBase: TpFIBDataBase; const aDBPath, aUserName, aPassword: String; var aErrIBMsg: String; var aErrIBCode: Integer ): Boolean; function GetMaxUpdNumber ( const aMaxUpdNumParams: TMaxUpdNumParams ): TUpdateNumInfo; implementation uses StrUtils, DateUtils; procedure LogException ( const aFileName: TFileName ); {******************************************************************************* * * * Название процедуры : * * * * LogException * * * * Назначение процедуры : * * * * Процедура протоколирует ошибки, возникающие в приложении * * * * IN: * * aFileName - полный путь к файлу протокола. * * * *******************************************************************************} var m : word; Buf : array[0..511] of char; FStream : TFileStream; begin if FileExists( aFileName ) then m := fmOpenReadWrite else m := fmCreate; FStream := TFileStream.Create( aFileName, m ); FStream.Seek( 0, soFromEnd ); StrPCopy( Buf, DateTimeToStr(Now)+ '. ' ); ExceptionErrorMessage( ExceptObject, ExceptAddr, @Buf[ StrLen(Buf) ], SizeOf(Buf) - StrLen(Buf) ); StrCat( Buf, #13#10 ); FStream.WriteBuffer( Buf, StrLen(Buf) ); FStream.Free; end; //End of procedure LogException procedure ExtractKeyBlock ( var aKeyBlock: String; var aSeparatorCount: Integer; const aSeparatorChar: String ); {******************************************************************************* * * * Название процедуры : * * * * ExtractKeyBlock * * * * Назначение процедуры : * * * * Процедура выделяет блок ключевых выражений.(данная процедура явл. * * вспомогательной) * * * * IN: * * * * aKeyBlock - строка, содержащая блоки ключевых выражений. * * aSeparatorChar - символ-разделител, отделяющий друг от друга блоки * * ключевых выражений. * * aSeparatorCount - количество начальных символов-разделителей * * * * OUT: * * * * aKeyBlock - строка, содержащая 1 блок ключевых выражений. * * aSeparatorCount - количество начальных символов-разделителей * * * *******************************************************************************} var Counter : Integer; CharIndex : Integer; begin Counter := 0; CharIndex := 0; aKeyBlock := aSeparatorChar + aKeyBlock; aSeparatorCount := 0; //Ищем начало блока ключевых выражений repeat Inc( Counter ); CharIndex := PosEx( aSeparatorChar, aKeyBlock, CharIndex + 1 ); until ( aKeyBlock[CharIndex] <> aKeyBlock[CharIndex + 1] ); //Получаем количество начальных символов-разделителей aSeparatorCount := Counter - 1; //Отсекаем последовательность символов-разделителей, с которых начинается строка Delete( aKeyBlock, 1, CharIndex ); CharIndex := Pos( aSeparatorChar, aKeyBlock ); //Отсекаем все символы, следующие за блоком ключевых выражений Delete( aKeyBlock, CharIndex, Length( aKeyBlock ) - CharIndex + 1 ); end; //End of procedure ExtractKeyBlock procedure SetDirEndDelimiter ( var aDirPath: String ); {******************************************************************************* * * * Название процедуры : * * * * SetDirEndDelimiter * * * * Назначение процедуры : * * * * В зависимости от типа ОС дополняет путь к дирректории корректным слешем, * * если это необходимо. * * * * IN: * * aDirPath - параметр, содержащий путь к дирректории. * * OUT: * * aDirPath - параметр, содержащий путь к дирректории. * * * *******************************************************************************} begin if Trim( aDirPath ) <> sEMPTY_STR then begin if Pos( sSEPARATOR_FOLDER_WIN, aDirPath ) <> 0 then begin if aDirPath[ Length( aDirPath ) ] <> sSEPARATOR_FOLDER_WIN then aDirPath := aDirPath + sSEPARATOR_FOLDER_WIN end else if aDirPath[ Length( aDirPath ) ] <> sSEPARATOR_FOLDER_UNX then aDirPath := aDirPath + sSEPARATOR_FOLDER_UNX; end; end; //End of procedure SetDirEndDelimiter function GetKeyExpr ( const aProjectName: String ): String; {******************************************************************************* * * * Название функции : * * * * GetKeyExpr * * * * Назначение функции : * * * * Поиск ключевого выражения, соответствующего данному проэкту. * * * * IN: * * aProjectName - название проэкта. * * OUT: * * Result - значение ключевого выражения. * * * * RESULT: String. * * * *******************************************************************************} var i, n : Integer; begin Result := sEMPTY_STR; n := High( cProjectParams ); for i := Low( cProjectParams ) to n do begin if Pos(UpperCase( cProjectParams[i].Name),UpperCase(aProjectName))<>0 //UpperCase( aProjectName ) = UpperCase( cProjectParams[i].Name ) then begin Result := cProjectParams[i].KeyExpr; Break; end; end; end; //End of function GetKeyExpr procedure FillDataSet( aDataSet: TRxMemoryData; const aSourceList: TUsrStringList; var aSelRecCount: Integer; const aMode: TFillMode = fmInsert ); {******************************************************************************* * * * Название процедуры : * * * * FillDataset * * * * Назначение процедуры : * * * * Заполняет набор данных значениями из списка. * * * * IN: * * * * aMode - режим добавления. * * aDataSet - набор данных приемник. * * aSourceList - списко значений, подлежащих добавлению. * * aSelRecCount - количество помеченных записей. * * * * OUT: * * * * aDataSet - заполненный набор данных. * * aSelRecCount - количество помеченных записей. * * * *******************************************************************************} var i, n : Integer; Index : Integer; IsActive : Boolean; CurrFileName : String; begin try //Заполняем НД case aMode of fmInsert : begin //Очищаем НД if aDataSet.Active then aDataSet.Close; aDataSet.Open; aDataSet.DisableControls; n := aSourceList.Count - 1; for i := 0 to n do begin aDataSet.Insert; aDataSet.FieldByName(sIS_ACTIVE_FN ).AsBoolean := cDEF_IS_ACTIVE; aDataSet.FieldByName(sSCRIPT_NAME_FN).AsString := aSourceList.Strings[i]; aDataSet.FieldByName(sFILE_SIZE_FN ).AsFloat := TUsrObject( aSourceList.Objects[i] ).FileSize; aDataSet.FieldByName(sDATE_CHANGE_FN).AsDateTime := TUsrObject( aSourceList.Objects[i] ).FileDateChange; aDataSet.Post; end; aSelRecCount := n + 1; end; fmAppend : begin //Подготавливаем НД к заполнению if not aDataSet.Active then aDataSet.Open; n := aDataSet.RecordCount - 1; aDataSet.DisableControls; aDataSet.First; //Удаляем из НД не актуальные записи for i := 0 to n do begin IsActive := aDataSet.FieldByName(sIS_ACTIVE_FN ).AsBoolean; CurrFileName := aDataSet.FieldByName(sSCRIPT_NAME_FN).AsString; Index := aSourceList.IndexOf( CurrFileName ); if Index = -1 then begin if IsActive then Dec( aSelRecCount ); aDataSet.Delete; end else begin if not IsActive then begin aDataSet.Edit; aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean := cDEF_IS_ACTIVE; aDataSet.Post; Inc( aSelRecCount ); end; aDataSet.Next; end; end; //Актуализируем НД n := aSourceList.Count - 1; for i := 0 to n do begin if not aDataSet.Locate( sSCRIPT_NAME_FN, aSourceList.Strings[i], [] ) then begin aDataSet.Insert; aDataSet.FieldByName(sIS_ACTIVE_FN ).AsBoolean := cDEF_IS_ACTIVE; aDataSet.FieldByName(sSCRIPT_NAME_FN).AsString := aSourceList.Strings[i]; aDataSet.FieldByName(sFILE_SIZE_FN ).AsFloat := TUsrObject( aSourceList.Objects[i] ).FileSize; aDataSet.FieldByName(sDATE_CHANGE_FN).AsDateTime := TUsrObject( aSourceList.Objects[i] ).FileDateChange; aDataSet.Post; Inc( aSelRecCount ); end; end; end; end; aDataSet.First; finally aDataSet.EnableControls; end; end; //End of procedure FillDataset function SelectRecords ( aDataSet: TRxMemoryData; const aSelectionMode: TSelectionMode ): Integer; {******************************************************************************* * * * Название функции : * * * * SelectRecords * * * * Назначение функции : * * * * Помечает множество записей из набора данных в зависимости от типа режима. * * * * IN: * * * * aDataSet - набор данных. * * aSelectionMode - режим выбора множества записей. * * * * OUT: * * * * Result - количество помеченных записей. * * * * RESULT: Integer. * * * *******************************************************************************} var i, n : Integer; Count : Integer; begin n := aDataSet.RecordCount - 1; Count := 0; aDataSet.DisableControls; aDataSet.First; case aSelectionMode of smInvert : begin for i := 0 to n do begin aDataSet.Edit; if aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean then begin aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean := False; end else begin aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean := True; Inc( Count ); end; aDataSet.Post; aDataSet.Next; end; Result := Count; end; smSelectAll : begin Result := n + 1; for i := 0 to n do begin aDataSet.Edit; aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean := True; aDataSet.Post; aDataSet.Next; end; end; smUnSelectAll : begin Result := 0; for i := 0 to n do begin aDataSet.Edit; aDataSet.FieldByName(sIS_ACTIVE_FN).AsBoolean := False; aDataSet.Post; aDataSet.Next; end; end; end; aDataSet.EnableControls; end; //End of function SelectRecords procedure DelDirEndDelimiter ( var aDirPath: String ); {******************************************************************************* * * * Название процедуры : * * * * DelDirEndDelimiter * * * * Назначение процедуры : * * * * В зависимости от типа ОС удаляет завершающий слеш для пути к дирректории, * * если это необходимо. * * * * IN: * * aDirPath - параметр, содержащий путь к дирректории. * * OUT: * * aDirPath - параметр, содержащий путь к дирректории. * * * *******************************************************************************} var StrLength : Integer; begin StrLength := Length( aDirPath ); if StrLength > 0 then begin if ( ( aDirPath[ StrLength ] = sSEPARATOR_FOLDER_WIN ) OR ( aDirPath[ StrLength ] = sSEPARATOR_FOLDER_UNX ) ) AND ( StrLength > cMIN_PATH_LENGTH ) then Delete( aDirPath, StrLength, 1 ); end; end; //End of procedure DelDirEndDelimiter function IsDateInPeriod ( const aCurrDate: TDate; const aDateBeg, aDateEnd: String ): Boolean; {******************************************************************************* * * * Название функции : * * * * IsDateInPeriod * * * * Назначение функции : * * * * Анализирует, попадает ли текущая дата в интервал, заданный двумя другими * * датами. * * * * IN: * * aDateBeg - дата, задающая нижнюю границу временного интервала. * * aDateEnd - дата, задающая верхнюю границу временного интервала. * * aCurrDate - дата, подлежащая проверке. * * * * OUT: * * Result - результат анализа. * * * * RESULT: Boolean. * * Если дата попадает в заданный интервал, то результат, возвращаемый * * функцией - истина; в противном случае - ложь. * * * *******************************************************************************} var DateBeg : TDate; DateEnd : TDate; PeriodBound : TPeriodbound; begin try //Aнализируем границы периода if ( aDateBeg = sEMPTY_STR ) AND ( aDateEnd = sEMPTY_STR ) then PeriodBound := pbNone else if aDateBeg <> sEMPTY_STR then begin DateBeg := StrToDate( aDateBeg ); PeriodBound := pbLeft; if aDateEnd <> sEMPTY_STR then begin DateEnd := StrToDate( aDateEnd ); PeriodBound := pbBoth; end; end else begin DateEnd := StrToDate( aDateEnd ); PeriodBound := pbRight; end; //Вычисляем результат функции case PeriodBound of pbNone : begin Result := True; end; pbLeft : begin if aCurrDate >= DateBeg then Result := True else Result := False; end; pbRight : begin if aCurrDate <= DateEnd then Result := True else Result := False; end; pbBoth : begin if ( aCurrDate >= DateBeg ) AND ( aCurrDate <= DateEnd ) then Result := True else Result := False; end; end; except Result := False; Raise; end; end; //End of function IsDateInPeriod procedure ParseFileName ( const aFileName, aKeyExpr: String; var aScriptInfo: TScriptInfo; aSections: TStringList = nil ); {******************************************************************************* * * * Название процедуры : * * * * ParseFileName * * * * Назначение процедуры : * * * * Выполняет разбор имени файла скрипта в соответствии со спецификациями. * * * * IN: * * aKeyExpr - один или несколько ключевых символов, определяющие * * критерий отбора файлов скриптов. * * aFileName - имя файла скрипта, подлежащее разбору * * aSections - список, содержащий секции из которых состоит имя файла * * скрипта. * * aScriptInfo - запись, содержащая набор параметров скрипта. * * OUT: * * aSections - список, содержащий секции из которых состоит имя файла * * скрипта. * * aScriptInfo - запись, содержащая набор параметров скрипта. * * * *******************************************************************************} var i, j, n, k : Integer; Index : Integer; ErrCode : Integer; KeyIndex : Integer; KeyBlock : String; KeyBlocks : TStringList; UpdateNum : Integer; TmpFileName : String; FmtSettings : TFormatSettings; DelCharCount : Integer; DaysCountScr : Integer; SeparatorCount : Integer; StrScrDateCreate : String; begin try TmpFileName := aFileName; KeyBlocks := TStringList.Create; FmtSettings.DateSeparator := cDATE_SEPARATOR; FmtSettings.ShortDateFormat := sFORMAT_DATE_TO_STR; //Получаем дату создания скрипта StrScrDateCreate := Copy( TmpFileName, 1, cDATE_DIGITS_COUNT ); aScriptInfo.DateCreate := StrToDate( StrScrDateCreate, FmtSettings ); KeyBlocks.Add( DateToStr( aScriptInfo.DateCreate ) ); //Отсекаем дату создания скрипта Delete( TmpFileName, 1, cDATE_DIGITS_COUNT ); //Выделяем из имени файла скрипта блоки ключевых cимволов repeat KeyBlock := TmpFileName; ExtractKeyBlock( KeyBlock, SeparatorCount, sSCR_SEPARATOR ); KeyBlocks.Add( KeyBlock ); DelCharCount := Length( KeyBlock ) + SeparatorCount; Delete( TmpFileName, 1, DelCharCount ); until ( Length( TmpFileName ) = 0 ); //Проверяем: нужно ли применять скрипт к данному проекту? if Pos( aKeyExpr, KeyBlocks.Strings[2] ) <> 0 then begin aScriptInfo.CanExecute := True; end else begin aScriptInfo.CanExecute := False; end; //Проверяем: применен ли уже скрипт к данному проекту? if Pos( aKeyExpr, KeyBlocks.Strings[3] ) <> 0 then begin aScriptInfo.Execute := True end else begin aScriptInfo.Execute := False; end; //Отбрасываем ключевые блоки, содержащие дату создания скрипта, ФИО разработчика и комментарий n := KeyBlocks.Count - 3; aScriptInfo.IsInUpdate := False; aScriptInfo.UpdateNumMajor := sEMPTY_STR; aScriptInfo.UpdateNumMinor := sEMPTY_STR; //Проверяем: вошел ли скрипт в какое-либо-обновление? for i := 4 to n do begin KeyIndex := Pos( aKeyExpr, KeyBlocks.Strings[i] ); //Вычисляем дату применения скрипта if KeyIndex <> 0 then begin KeyBlock := KeyBlocks.Strings[i]; Delete( KeyBlock, KeyIndex, Length( aKeyExpr ) ); Index := Pos( sUPDATE_EXPR, KeyBlock ); //Проверяем: вошел ли скрипт в обновление? if Index <> 0 then begin Delete( KeyBlock, Index, Length( KeyBlock ) - Index + 1 ); end; Val( KeyBlock, DaysCountScr, ErrCode ); //Анализируем результат преобразования разницы в днях между датой создания и датой применения скрипта if ( ErrCode = 0 ) AND ( DaysCountScr >= 0 ) then begin aScriptInfo.DateExecute := aScriptInfo.DateCreate + DaysCountScr; end else begin aScriptInfo.DateExecute := aScriptInfo.DateCreate; end; end; Index := Pos( sUPDATE_EXPR, KeyBlocks.Strings[i] ); //Вычисляем порядковый номер обновления if ( KeyIndex <> 0 ) AND ( Index <> 0 ) then begin aScriptInfo.IsInUpdate := True; aScriptInfo.UpdateNumMajor := sZERO; aScriptInfo.UpdateNumMinor := sZERO; KeyBlock := KeyBlocks.Strings[i]; Delete( KeyBlock, 1, Index ); //Получаем порядковый номер обновления, в которое вошел данный скрипт Index := Pos( cUPDATE_NUMBER_SEPARATOR, KeyBlock ); //Выделяем порядковый номер обновления case Index of 0 : begin Val( KeyBlock, UpdateNum, ErrCode ); //Анализируем полученный результат if ( ErrCode <> 0 ) then begin aScriptInfo.UpdateNumMajor := sDEF_UPDATE_NUMBER; aScriptInfo.UpdateNumMinor := sDEF_UPDATE_NUMBER; end else begin aScriptInfo.UpdateNumMajor := IntToStr( UpdateNum ); end; end; 1 : begin aScriptInfo.UpdateNumMajor := sDEF_UPDATE_NUMBER; end; else begin aScriptInfo.UpdateNumMajor := Copy( KeyBlock, 1, Index - 1 ); aScriptInfo.UpdateNumMinor := Copy( KeyBlock, Index + 1, Length( KeyBlock ) - Index ); end; end; end; end; finally if Assigned( KeyBlocks ) then begin if Assigned( aSections ) then aSections.Assign( KeyBlocks ); FreeAndNil( KeyBlocks ); end; end; end; //End of procedure ParseFileName function LoadScripts ( const aFilterParams: TFilterParams; var aScriptNames: TUsrStringList; var aMaxUpdNumber: TUpdateNumInfo ): TLoadScrResult; {******************************************************************************* * * * Название функции : * * * * LoadScripts * * * * Назначение функции : * * * * Формирование списка имён файлов скриптов, которые должны войти в обновление. * * Поиск максимального номера предыдущих обновлений. * * * * IN: * * * * aScriptNames - список имён файлов скриптов, которые нужно включить в * * обновление. * * aMaxUpdNumber - максимальный номер файла обновления. * * aFilterParams - множество критериев фильтрации, на основании которых * * формируется множество скриптов, которые нужно включить * * в обновление. * * OUT: * * * * Result - расшифровка результатов загрузки имен файлов скриптов. * * aMaxUpdNumber - максимальный номер файла обновления. * * * * RESULT: TLoadScrResult. * * * *******************************************************************************} var FileRec : TSearchRec; UsrObject : TUsrObject; SearchRes : Integer; IsInPeriod : Boolean; ScriptInfo : TScriptInfo; ScriptExist : Boolean; CurrUpdateNum : TUpdateNumInfo; begin try try Result := lrNone; with CurrUpdateNum do begin UpdateNumMajor := cDEF_UPDATE_NUMBER; UpdateNumMinor := cDEF_UPDATE_NUMBER; end; //Пытаемся найти хотя бы один файл скрипта SearchRes := FindFirst( aFilterParams.ScriptPath, faAnyFile, FileRec ); //Проверяем: был ли найден хотя бы один файл скрипта? if SearchRes <> 0 then begin Result := lrScrNotFound; Exit; end else begin Result := lrFilterInvalid; ScriptExist := False; end; //Пытаемся найти все существующие файлы скриптов, удовлетворяющиe критериям фильтрации while ( SearchRes = 0 ) do begin //Выполняем разбор имени файла скрипта ParseFileName( FileRec.Name, aFilterParams.KeyExpr, ScriptInfo ); //Проверяем: может ли текущий скрипт быть включен в обновление? if ScriptInfo.CanExecute then begin //Получаем порядковый номер обновления if ScriptInfo.IsInUpdate then begin with CurrUpdateNum do begin UpdateNumMajor := StrToInt( ScriptInfo.UpdateNumMajor ); UpdateNumMinor := StrToInt( ScriptInfo.UpdateNumMinor ); end; end else begin with CurrUpdateNum do begin UpdateNumMajor := cZERO; UpdateNumMinor := cDEF_UPDATE_NUMBER; end; end; //Находим максимальное значение главной части порядкового номера обновления if aMaxUpdNumber.UpdateNumMajor < CurrUpdateNum.UpdateNumMajor then aMaxUpdNumber.UpdateNumMajor := CurrUpdateNum.UpdateNumMajor; //Находим максимальное значение дополнительной части порядкового номера обновления if aMaxUpdNumber.UpdateNumMinor < CurrUpdateNum.UpdateNumMinor then aMaxUpdNumber.UpdateNumMinor := CurrUpdateNum.UpdateNumMinor; //Проверяем: не включен ли уже текущий скрипт в обновление? if ( not ScriptInfo.Execute AND ( ( aFilterParams.UpdateNumMajor = 0 ) and ( aFilterParams.UpdateNumMinor = 0 ) ) ) OR ( ScriptInfo.Execute AND ( ( aFilterParams.UpdateNumMajor = CurrUpdateNum.UpdateNumMajor ) and ( aFilterParams.UpdateNumMinor = CurrUpdateNum.UpdateNumMinor ) ) ) then begin //Проверяем: попадает ли дата создания данного скрипта в заданный период IsInPeriod := IsDateInPeriod( ScriptInfo.DateCreate, aFilterParams.DateBeg, aFilterParams.DateEnd ); //Запоминаем имя скрипта, который нужно включить в обновление if IsInPeriod then begin UsrObject := TUsrObject.Create; UsrObject.PutFileSize( FileRec.Size ); UsrObject.PutFileDateChange( FileRec.Time ); aScriptNames.AddObject( FileRec.Name, UsrObject ); ScriptExist := True; end; end; end; //Находим следующий файл скрипта SearchRes := FindNext( FileRec ); end; //Формируем возвращаемый функцией результат if ScriptExist then begin Result := lrLoadSuccess; end; finally FindClose( FileRec ); end; except Result := lrNone; Raise; end; end; //End of function LoadScriptsExt function RenameScript ( const aOldFileName: String; var aNewFileName: String; const aRenameParams: TRenameParams ): Boolean; {******************************************************************************* * * * Название функции : * * * * RenameScript * * * * Назначение функции : * * * * Генерация нового имени скрипта на основании старого. * * * * IN: * * aOldFileName - старое имя скрипта. * * aNewFileName - новое имя скрипта. * * aRenameParams - параметры переименования скриптов. * * OUT: * * * * aNewFileName - новое имя скрипта. * * * * RESULT: Boolean. * * * * NOTE: * * Функция возвращает True, если имя скрипта подлежит переименованию и * * False - в противном случае. * *******************************************************************************} var i, j, n, k : Integer; KeyIndex : Integer; KeyBlock : String; EmptyStr : String; KeyBlocks : TStringList; ScriptInfo : TScriptInfo; FmtSettings : TFormatSettings; CurrKeyBlock : String; KeyBlockIndex : Integer; UpdateNumMinorStr : String; UpdateNumMajorStr : String; DaysBetweenCount : Extended; CanEditScriptName : Boolean; DaysBetweenCountStr : String; begin try Result := False; EmptyStr := sEMPTY_CHAR; KeyBlocks := TStringList.Create; with aRenameParams do begin //Выполняем разбор имени файла скрипта ParseFileName( aOldFileName, KeyExpr, ScriptInfo, KeyBlocks ); case RenameMode of rmRename : begin if not( ScriptInfo.Execute OR ScriptInfo.IsInUpdate ) then CanEditScriptName := True else CanEditScriptName := False; end; rmUnRename : begin if ScriptInfo.Execute AND ScriptInfo.IsInUpdate then CanEditScriptName := True else CanEditScriptName := False; end; end; //Проверяем: нужно ли вообще пере(раз)именовывать данный скрипт? if ScriptInfo.CanExecute AND CanEditScriptName then begin KeyIndex := Pos( KeyExpr, KeyBlocks.Strings[2] ); //Заменяем во 2-ом блоке ключевое выражение символами подчеркивания if ScriptInfo.Execute then begin KeyBlock := KeyBlocks.Strings[3]; EmptyStr := DupeString( sEMPTY_CHAR, Length( KeyExpr ) ); Insert( EmptyStr, KeyBlock, KeyIndex + Length( KeyExpr ) ); Delete( KeyBlock, KeyIndex, Length( KeyExpr ) ); KeyBlocks.Strings[3] := KeyBlock; end; //Переименовываем скрипт, если это необходимо case RenameMode of rmRename : begin //Помечаем скрипт, как уже применённый KeyBlock := KeyBlocks.Strings[3]; Insert( KeyExpr, KeyBlock, KeyIndex + Length( KeyExpr ) ); Delete( KeyBlock, KeyIndex, Length( KeyExpr ) ); KeyBlocks.Strings[3] := KeyBlock; //Получаем дату применения скрипта DaysBetweenCount := DateCreate - ScriptInfo.DateCreate; DaysBetweenCountStr := FloatToStr( DaysBetweenCount ); if Length( DaysBetweenCountStr ) < cDAYSBETWEEN_RESERVED_CHAR_COUNT then begin DaysBetweenCountStr := DupeString( sZERO, cDAYSBETWEEN_RESERVED_CHAR_COUNT - Length( DaysBetweenCountStr ) ) + DaysBetweenCountStr; end; //Получаем главную часть порядкового номера обновления UpdateNumMajorStr := IntToStr( aRenameParams.UpdateNumMajor ); if aRenameParams.UpdateNumMajor >= 0 then begin if Length( UpdateNumMajorStr ) < cUPDATE_MAJ_RESERVED_CHAR_COUNT then begin UpdateNumMajorStr := DupeString( sZERO, cUPDATE_MAJ_RESERVED_CHAR_COUNT - Length( UpdateNumMajorStr ) ) + UpdateNumMajorStr; end; //Получаем дополнительную часть порядкового номера обновления UpdateNumMinorStr := IntToStr( aRenameParams.UpdateNumMinor ); if Length( UpdateNumMinorStr ) < cUPDATE_MIN_RESERVED_CHAR_COUNT then begin UpdateNumMinorStr := DupeString( sZERO, cUPDATE_MIN_RESERVED_CHAR_COUNT - Length( UpdateNumMinorStr ) ) + UpdateNumMinorStr; end; end else begin end; //Формируем ключевое выражение CurrKeyBlock := KeyExpr + DaysBetweenCountStr + sUPDATE_EXPR + UpdateNumMajorStr + sMINUS + UpdateNumMinorStr; //Получаем индекс текущего блока с учётом алфавитного порядка KeyBlockIndex := 4; n := KeyBlocks.Count - 3; for i := 4 to n do begin //Отбрасываем спецификации обновления KeyBlock := KeyBlocks.Strings[i]; KeyIndex := Pos( sUPDATE_EXPR, KeyBlock ); Delete( KeyBlock, KeyIndex, Length( KeyBlock ) - KeyIndex + 1 ); UpperCase( KeyBlock ); k := Length( KeyBlock ); //Выделяем ключевое выражение, идентифицирующее проект for j := 1 to k do begin if not( KeyBlock[j] in cLETTERS ) then begin Delete( KeyBlock, j, Length( KeyBlock ) - j + 1 ); Break; end; end; //Проверяем алфавитный порядок следования if KeyBlock > KeyExpr then begin KeyBlockIndex := i; Break; end else begin KeyBlockIndex := i + 1; end; end; //Вставляем текущий блок с учётом алфавитного порядка KeyBlocks.Insert( KeyBlockIndex, CurrKeyBlock ); end; rmUnRename : begin //Находим и удаляем блок, содержащий информацию о дате применения скрипта и обновлении n := KeyBlocks.Count - 3; for i := 4 to n do begin if Pos( KeyExpr, KeyBlocks.Strings[i] ) <> 0 then begin KeyBlocks.Delete( i ); Break; end; end; end; end; //Формируем новое имя файла скрипта FmtSettings.DateSeparator := cDATE_SEPARATOR; FmtSettings.ShortDateFormat := sFORMAT_DATE_TO_STR; aNewFileName := DateToStr( ScriptInfo.DateCreate, FmtSettings ) + sSCR_SEPARATOR; n := KeyBlocks.Count - 2; for i := 1 to n do begin aNewFileName := aNewFileName + KeyBlocks.Strings[i] + DupeString( sSCR_SEPARATOR, cSECTIONS_SEPARATOR_COUNT ); end; aNewFileName := aNewFileName + KeyBlocks.Strings[n+1]; Result := True; end; end; finally if Assigned( KeyBlocks ) then FreeAndNil( KeyBlocks ); end; end; //End of function RenameScript function TestConnection( aDataBase: TpFIBDataBase; const aDBPath, aUserName, aPassword: String; var aErrIBMsg: String; var aErrIBCode: Integer ): Boolean; {******************************************************************************* * * * Название функции : * * * * TestConnection * * * * Назначение функции : * * * * Проверяет корректность параметров соединения. * * * * IN: * * aDataBase - ссылка на компонент, с помощью которого выполняется * * попытка подключения к базе данных. * * aDBPath - путь к файлу базы данных. * * aUserName - имя пользователя. * * aPassword - пароль. * * aErrIBMsg - сообщение об ошибке. * * aErrIBCode - код ошибки. * * * * OUT: * * * * Result: Boolean * * * * RESULT: Функция возвращает True, если парамeтры соединения корректны и * * False в противном случае. * * * *******************************************************************************} begin try try if aDataBase.Connected then aDataBase.Close; aDataBase.DBName := aDBPath; aDataBase.ConnectParams.UserName := aUserName; aDataBase.ConnectParams.Password := aPassword; Result := True; aErrIBMsg := ''; aErrIBCode := -1; aDataBase.Open; finally aDataBase.Close; end; except on E: EFIBError do begin Result := False; aErrIBMsg := E.IBMessage; aErrIBCode := E.IBErrorCode; end; end; end; //End of function TestConnection procedure ReadIniFile ( const aFileName: String; const aDefIniParams: array of TDefIniParams; aIniParams: TStringList ); {******************************************************************************* * * * Название процедуры : * * * * ReadIniFile * * * * Назначение процедуры : * * * * Считывает настройки из ini-файла. * * * * IN: * * aFileName - полный путь к ini-файлу. * * aIniParams - список, содержащий значения умалчиваемых парамтров. * * aDefIniParams - массив, содержащий названия секций для значений * * умалчиваемых парамтров. * * OUT: * * aIniParams - список, содержащий значения умалчиваемых парамтров. * * * *******************************************************************************} var i, n : Integer; IniFile : TIniFile; begin //Заполняем список значениями по умолчанию with aIniParams do begin Values[sKN_SERVER_NAME ] := sDEF_SERVER_NAME; Values[sKN_DB_PATH ] := sDEF_DB_PATH; Values[sKN_USER_NAME ] := sDEF_USER_NAME; Values[sKN_PASSWORD ] := sDEF_PASSWORD; Values[sKN_SCR_PATH ] := sDEF_SCR_PATH; Values[sKN_IBESCRIPT_PATH] := sDEF_IBESCRIPT_PATH; Values[sKN_ACTIVE_PROJECTS] := sDEF_ACTIVE_PROJECTS; end; if FileExists( aFileName ) then begin try IniFile := TIniFile.Create( aFileName ); n := High( aDefIniParams ); //Считываем умалчиваемые значеня из файла настроек for i := Low( aDefIniParams ) to n do begin with aDefIniParams[i] do begin if IniFile.SectionExists( Section ) then begin aIniParams.Values[Key] := IniFile.ReadString( Section, Key, DefValue ); end; end; end; finally if IniFile <> nil then FreeAndNil( IniFile ); end; end; end; // End of procedure ReadIniFile procedure CreateMyProcess ( const aAppName, aCommandLine: PAnsiChar; aWindowState: Word ); {******************************************************************************* * * * Название процедуры : * * * * CreateMyProcess * * * * Назначение процедуры : * * * * Процедура создаёт процесс, в рамках которого в режиме коммандной строки * * выполняется некоторое приложение. * * * * IN: * * * * aAppName - полный путь к запускаемому приложению. * * aCommandLine - параметры коммандной строки. * * aWindowState - тип прорисовки окна приложения. * * * *******************************************************************************} var Result : Boolean; ExitCode : Cardinal; ProcessInfo : TProcessInformation; StartUpInfo : TStartupInfo; begin //Инициализируем объявленные структуры FillChar(StartUpInfo, SizeOf(TStartUpInfo), 0); with StartUpInfo do begin cb := SizeOf(TStartUpInfo); dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK; wShowWindow := aWindowState; end; //Создаём процесс Result := CreateProcess( aAppName, aCommandLine, nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo); if Result then with ProcessInfo do begin WaitForInputIdle(hProcess, INFINITE); // ждем завершения инициализации WaitforSingleObject(ProcessInfo.hProcess, INFINITE); // ждем завершения процесса GetExitCodeProcess(ProcessInfo.hProcess, ExitCode); // получаем код завершения CloseHandle(hThread); // закрываем дескриптор процесса CloseHandle(hProcess); // закрываем дескриптор потока end; end; //End of procedure CreateMyProcess function GetMaxUpdNumber ( const aMaxUpdNumParams: TMaxUpdNumParams ): TUpdateNumInfo; {******************************************************************************* * * * Название функции : * * * * GetMaxUpdNumber * * * * Назначение функции : * * * * Вычисляет максимальный порядковый номер обновления. * * * * IN: * * aMaxUpdNumParams - структура, содержащая критерии поиска. * * * * OUT: * * * * Result: TUpdateNumInfo * * * * RESULT: Функция возвращает 0, если не удалось вычислить максимальный * * порядковый номер обновления и, собственно номер, в противном случае.* * * *******************************************************************************} var FileRec : TSearchRec; SearchRes : Integer; ScriptInfo : TScriptInfo; CurrUpdateNumMajor : Integer; CurrUpdateNumMinor : Integer; begin try try with Result do begin UpdateNumMajor := cZERO; UpdateNumMinor := cZERO; end; //Пытаемся найти хотя бы один файл скрипта(архива с модулями) SearchRes := FindFirst( aMaxUpdNumParams.FilePath, faAnyFile, FileRec ); //Пытаемся найти все существующие файлы скриптов(архивов с модулями), удовлетворяющиe критериям фильтрации while ( SearchRes = 0 ) do begin //Выполняем разбор имени файла скрипта(архива с модулями) ParseFileName( FileRec.Name, aMaxUpdNumParams.KeyExpr, ScriptInfo ); //Анализируем: был ли включен текущий файл в обновление? if ScriptInfo.IsInUpdate then begin CurrUpdateNumMajor := StrToInt( ScriptInfo.UpdateNumMajor ); CurrUpdateNumMinor := StrToInt( ScriptInfo.UpdateNumMinor ); //Находим максимальный порядковый номер обновления with Result do begin if UpdateNumMajor < CurrUpdateNumMajor then begin UpdateNumMajor := CurrUpdateNumMajor; end; if UpdateNumMinor < CurrUpdateNumMinor then begin UpdateNumMinor := CurrUpdateNumMinor; end; end; end; //Находим следующий файл скрипта(архива с модулями) SearchRes := FindNext( FileRec ); end; finally FindClose( FileRec ); end; except with Result do begin UpdateNumMajor := cZERO; UpdateNumMinor := cZERO; end; Raise; end; end; //End of function GetMaxUpdNumber function FindText( aSourceDS: TRxMemoryData; const aSearchFieldName: String; const aSearchParams: TPtr_SearchParams ): Boolean; {******************************************************************************* * * * Название функции : * * * * FindText * * * * Назначение функции : * * * * Выполняет поиск строки текста. * * * * IN: * * * * aSourceDS - набор данных, содержащий искомый тест. * * aSearchParams - указатель на запись, содержащий параметры поиска. * * * * OUT: Result - результат поиска. * * * * * *******************************************************************************} var i, n : Integer; CurrText : String; SearchText : String; begin try Result := False; SearchText := aSearchParams^.TextSearch; aSourceDS.DisableControls; if aSearchParams^.WholeWordsOnly then begin //Анализируем регистрочувствительность символов if not aSearchParams^.CaseSensitive then begin SearchText := UpperCase( SearchText ); //Анализируем направление поиска if aSearchParams^.Direction = dtDown then begin while not aSourceDS.Eof do begin aSourceDS.Next; CurrText := UpperCase( aSourceDS.FieldByName(aSearchFieldName).AsString ); if CurrText = SearchText then begin Result := True; Break; end; end; end else begin while not aSourceDS.Bof do begin aSourceDS.Prior; CurrText := UpperCase( aSourceDS.FieldByName(aSearchFieldName).AsString ); if CurrText = SearchText then begin Result := True; Break; end; end; end; //End of Direction Condition end else begin Result := aSourceDS.Locate( aSearchFieldName, SearchText, [] ); end; //End of CaseSensivity Condition end else begin //Анализируем регистрочувствительность if not aSearchParams^.CaseSensitive then begin SearchText := UpperCase( SearchText ); //Анализируем направление поиска if aSearchParams^.Direction = dtDown then begin aSourceDS.UpdateCursorPos; while not aSourceDS.Eof do begin aSourceDS.Next; aSourceDS.CursorPosChanged; CurrText := UpperCase( aSourceDS.FieldByName(aSearchFieldName).AsString ); if Pos( SearchText, CurrText ) <> 0 then begin Result := True; Break; end; end; end else begin while not aSourceDS.Bof do begin aSourceDS.Prior; CurrText := UpperCase( aSourceDS.FieldByName(aSearchFieldName).AsString ); if Pos( SearchText, CurrText ) <> 0 then begin Result := True; Break; end; end; end; //End of Direction Condition end else begin //Анализируем направление поиска if aSearchParams^.Direction = dtDown then begin while not aSourceDS.Eof do begin aSourceDS.Next; CurrText := aSourceDS.FieldByName(aSearchFieldName).AsString; if Pos( SearchText, CurrText ) <> 0 then begin Result := True; Break; end; end; end else begin while not aSourceDS.Bof do begin aSourceDS.Prior; CurrText := aSourceDS.FieldByName(aSearchFieldName).AsString; if Pos( SearchText, CurrText ) <> 0 then begin Result := True; Break; end; end; end; //End of Direction Condition end; end; //End of PartialType Condition finally aSourceDS.EnableControls; end; end; //End of function FindText end.
unit DataAccess.Books; interface uses Data.DB, System.SysUtils; type IBooksDAO = interface(IInterface) ['{F8482010-9FCB-4994-B7E9-47F1DB115075}'] function fldISBN: TWideStringField; function fldTitle: TWideStringField; function fldAuthors: TWideStringField; function fldStatus: TWideStringField; function fldReleseDate: TDateField; function fldPages: TIntegerField; function fldPrice: TBCDField; function fldCurrency: TWideStringField; function fldImported: TDateTimeField; function fldDescription: TWideStringField; procedure ForEach(proc: TProc<IBooksDAO>); end; implementation end.
unit AppInit; {$mode objfpc}{$H+} //======================================================================================== // // Unit : AppInit.pas // // Description : // // Called By TfrmMain.FormShow: // // Calls : frmSettings : GetSQLiteLibraryName // iniFileExists // ReadSettinsINIFile // pApplicationDirectory // HUConstants // HUMessageBoxes // HUNagScreen : dlgHUNagScreen.ShowModal // HURegistration : RequestRegistrationKey // Main : TerminateApp // // Ver. : 1.0.0 // // Date : 28 Feb 2020 // //======================================================================================== interface uses Classes, Controls, Dialogs, FileUtil, SysUtils, // Application Units AppSettings, // HULib Units HUConstants, HUMessageBoxes, HUNagScreen, HURegistration; function Initialize : Boolean; //======================================================================================== // PUBLIC CONSTANTS //======================================================================================== //======================================================================================== // PUBLIC VARIABLES //======================================================================================== implementation uses Main; //======================================================================================== // PRIVATE CONSTANTS //======================================================================================== //========== // Nessages //========== //======================================================================================== // PRIVATE VARIABLES //======================================================================================== //======================================================================================== // PRIVATE ROUTINES //======================================================================================== //======================================================================================== // PUBLIC ROUTINES //======================================================================================== function Initialize : Boolean; begin // If the ApplicationDatabase does not exist we assume a New Installation and attempt // to create a default ApplicationDatabase. if not FileExists(frmSettings.pcAppDatabaseName) then begin showmessage('No Applcation Database Found'); showmessage('Deletjng Old Directory Structure'); if DirectoryExists(frmSettings.pcAppUserDirectory) then DeleteDirectory(frmSettings.pcAppUserDirectory, False); showmessage('Creating New Directory Structure'); showmessage('Creating default User Directory'); if not CreateDir( frmSettings.pcAppUserDirectory ) then begin showmessage('Unable to create default User Directory'); TerminateApp; end;// if not CreateDir( frmSettings.pcAppUserDirectory ) if not CreateDir( frmSettings.pcAppDataDirectory ) then begin showmessage('Unable to create default AppData Directory'); TerminateApp; end;// if not CreateDir( frmSettings.pcAppDataDirectory ) if not CreateDir( frmSettings.pcAppSettingsDirectory ) then begin showmessage('Unable to create default AppSettings Directory'); TerminateApp; end;// if not CreateDir( frmSettings.pcAppSettingsDirectory ) if not CreateDir( frmSettings.pcAppLogbooksDirectory ) then begin showmessage('Unable to create default AppLogbooks Directory'); TerminateApp; end;// if not CreateDir( frmSettings.pcAppLogbooksDirectory ) if not CreateDir( frmSettings.pcAppBackupsDirectory ) then begin showmessage('Unable to create default AppBackups Directory'); TerminateApp; end;// if not CreateDir( frmSettings.pcAppBackupsDirectory ) // CreateDir( frmSettings.pcAppDataDirectory ); // CreateDir( frmSettings.pcAppSettingsDirectory ); // CreateDir( frmSettings.pcAppLogbooksDirectory ); // CreateDir( frmSettings.pcAppBackupsDirectory ); if not frmSettings.CreateApplicationDataBase then begin showmessage('Failure'); TerminateApp; end;// if not frmSettings.CreateApplicationDataBase end;// if not FileExists(frmSettings.pcAppDatabaseName) if frmSettings.LoadApplicationDatabase then begin showmessage('ApplicationDB loaded'); end else begin showmessage('ApplicationDB load Failure'); TerminateApp; end;// if not frmSettings.LoadApplicationDatabase if dlgHUNagScreen.ShowModal = mrOK then begin // Check for Registration if dlgHURegistration.pRegKey = K_SP then dlgHURegistration.ShowModal; end;// if dlgHUNagScreen.ShowModal = mrOK showmessage('Init Complete'); Result := True; end;// function Initialize //======================================================================================== // PROPERTY ROUTINES //======================================================================================== //======================================================================================== // MENU ROUTINES //======================================================================================== //======================================================================================== // FILE ROUTINES //======================================================================================== //======================================================================================== end.// unit AppInit
unit EdictReader; { Reads EDICT2 and CC-EDICT format. Both are multi-kanji, multi-kana, multi-sense articles in a general form: kanji1 kanji2 [reading1 reading2] /sense1/sense2/ See precise format description in comments below. } //NOTE: Both EDICT2 and CC-EDICT parsers misreplace / with ; in cases like AC/DC // Nothing I can do about it. {$DEFINE CASE_SENSITIVE_MARKERS} { Markers inside one dic are insensitive, but EDICT's (P) is not ENAMDICT's (p). If this breaks anything or when there's case-euqivalent dupes, we'll implement better way } interface uses SysUtils; { EDICT and ENAMDIC support markers such as (P) or (adj-na). They have different sets of markers but we support a union for simplicity. If other EDICT-style dictionaries have other markers we'll see what we can do. } type //We support up to 255 markers for now. TMarker = AnsiChar; TMarkers = AnsiString; TMarkerFlag = ( mfPos, //it's important to distinguish POS markers from non-POS markers: //they are handled differently (see JWBEdictReader.pas) //other marker types are not so important, but they are kept separately by JMDic mfField, //field of application mfDial, //dialect mfPop //"popular" ); TMarkerFlags = set of TMarkerFlag; TMarkerDef = record m: string; //marker text without brackets f: TMarkerFlags; end; PMarkerDef = ^TMarkerDef; TMarkerList = array of TMarkerDef; const //Keep deprecated markers if we want to support older EDICTs. Markers: array[1..126] of TMarkerDef = ( //Part of Speech Marking (m: 'adj-i'; f: [mfPos]), (m: 'adj-na'; f: [mfPos]), (m: 'adj-no'; f: [mfPos]), (m: 'adj-pn'; f: [mfPos]), (m: 'adj-s'; f: [mfPos]), //deprecated (m: 'adj-t'; f: [mfPos]), (m: 'adj-f'; f: [mfPos]), (m: 'adj'; f: [mfPos]), (m: 'adv'; f: [mfPos]), (m: 'adv-n'; f: [mfPos]), (m: 'adv-to'; f: [mfPos]), (m: 'aux'; f: [mfPos]), (m: 'aux-v'; f: [mfPos]), (m: 'aux-adj'; f: [mfPos]), (m: 'conj'; f: [mfPos]), (m: 'ctr'; f: [mfPos]), (m: 'exp'; f: [mfPos]), (m: 'int'; f: [mfPos]), (m: 'iv'; f: [mfPos]), (m: 'n'; f: [mfPos]), (m: 'n-adv'; f: [mfPos]), (m: 'n-pref'; f: [mfPos]), (m: 'n-suf'; f: [mfPos]), (m: 'n-t'; f: [mfPos]), (m: 'neg'; f: [mfPos]), //deprecated (m: 'neg-v'; f: [mfPos]), //deprecated (m: 'num'; f: [mfPos]), (m: 'pn'; f: [mfPos]), (m: 'pref'; f: [mfPos]), (m: 'prt'; f: [mfPos]), (m: 'suf'; f: [mfPos]), (m: 'v1'; f: [mfPos]), (m: 'v2a-s'; f: [mfPos]), (m: 'v4h'; f: [mfPos]), (m: 'v4r'; f: [mfPos]), (m: 'v5'; f: [mfPos]), (m: 'v5aru'; f: [mfPos]), (m: 'v5b'; f: [mfPos]), (m: 'v5g'; f: [mfPos]), (m: 'v5k'; f: [mfPos]), (m: 'v5k-s'; f: [mfPos]), (m: 'v5m'; f: [mfPos]), (m: 'v5n'; f: [mfPos]), (m: 'v5r'; f: [mfPos]), (m: 'v5r-i'; f: [mfPos]), (m: 'v5s'; f: [mfPos]), (m: 'v5t'; f: [mfPos]), (m: 'v5u'; f: [mfPos]), (m: 'v5u-s'; f: [mfPos]), (m: 'v5uru'; f: [mfPos]), (m: 'v5z'; f: [mfPos]), (m: 'vz'; f: [mfPos]), (m: 'vi'; f: [mfPos]), (m: 'vk'; f: [mfPos]), (m: 'vn'; f: [mfPos]), (m: 'vs'; f: [mfPos]), (m: 'vs-c'; f: [mfPos]), (m: 'vs-i'; f: [mfPos]), (m: 'vs-s'; f: [mfPos]), (m: 'vt'; f: [mfPos]), //Field of Application (m: 'Buddh'; f: [mfField]), (m: 'MA'; f: [mfField]), (m: 'comp'; f: [mfField]), (m: 'food'; f: [mfField]), (m: 'geom'; f: [mfField]), (m: 'gram'; f: [mfField]), (m: 'ling'; f: [mfField]), (m: 'math'; f: [mfField]), (m: 'mil'; f: [mfField]), (m: 'physics'; f: [mfField]), //Miscellaneous Markings (m: 'X'), (m: 'abbr'), (m: 'arch'), (m: 'ateji'), (m: 'chn'), (m: 'col'), (m: 'derog'), (m: 'eK'), (m: 'ek'), (m: 'fam'), (m: 'fem'), (m: 'gikun'), (m: 'hon'), (m: 'hum'), (m: 'ik'), (m: 'iK'), (m: 'id'), (m: 'io'), (m: 'm-sl'), (m: 'male'), (m: 'male-sl'), (m: 'oK'), (m: 'obs'), (m: 'obsc'), (m: 'ok'), (m: 'on-mim'), (m: 'poet'), (m: 'pol'), (m: 'rare'), (m: 'sens'), (m: 'sl'), (m: 'uK'), (m: 'uk'), (m: 'vulg'), //Word Priority Marking (m: 'P'; f: [mfPop]), //Regional Words (m: 'kyb'; f: [mfDial]), (m: 'osb'; f: [mfDial]), (m: 'ksb'; f: [mfDial]), (m: 'ktb'; f: [mfDial]), (m: 'tsb'; f: [mfDial]), (m: 'thb'; f: [mfDial]), (m: 'tsug'; f: [mfDial]), (m: 'kyu'; f: [mfDial]), (m: 'rkb'; f: [mfDial]), //Enamdict (m: 's'; f: []), //surname (m: 'p'; f: []), //place-name (m: 'u'; f: []), //person name, either given or surname, as-yet unclassified (m: 'g'; f: []), //given name, as-yet not classified by sex (m: 'f'; f: []), //female given name (m: 'm'; f: []), //male given name (m: 'h'; f: []), //full (usually family plus given) name of a particular person (m: 'pr'; f: []), //product name (m: 'c'; f: []), //company name (m: 'o'; f: []), //organization name (m: 'st'; f: []), //stations (m: 'wk'; f: []) //work of literature, art, film, etc. ); //If your EDICT-compatible dictionary uses other markers, build your own table //and pass it to the parser. function FindMarkDef(m: string): TMarker; //returns marker # or #00 function GetMarkerText(id: TMarker): string; inline; //We use fixed arrays for speed, increase as needed const MaxKanji = 20; //max seen: 14 MaxKana = 20; //must be not less than MaxKanji MaxSense = 50; //at most I've seen 27 in EDICT2 type EEdictParsingException = class(Exception); TKanjiEntry = record kanji: UnicodeString; markers: TMarkers; procedure Reset; end; PKanjiEntry = ^TKanjiEntry; TKanaEntry = record kana: UnicodeString; kanji: array[0..MaxKanji-1] of UnicodeString; kanji_used: integer; markers: TMarkers; procedure Reset; function AddKanji: PUnicodeString; end; PKanaEntry = ^TKanaEntry; TSenseEntry = record pos: TMarkers; markers: TMarkers; text: UnicodeString; procedure Reset; end; PSenseEntry = ^TSenseEntry; TEdictArticle = record ref: string; kanji: array[0..MaxKanji-1] of TKanjiEntry; kanji_used: integer; kana: array[0..MaxKana-1] of TKanaEntry; kana_used: integer; senses: array[0..MaxSense-1] of TSenseEntry; senses_used: integer; pop: boolean; procedure Reset; function AddKanji: PKanjiEntry; function AddKana: PKanaEntry; function AddSense: PSenseEntry; procedure TrimEverything; end; PEdictArticle = ^TEdictArticle; //Parses EDICT2, EDICT procedure ParseEdict2Line(const s:UnicodeString; ed: PEdictArticle); //Parses CC-EDICT, various stages of CEDICT evolution procedure ParseCCEdictLine(const s:UnicodeString; ed: PEdictArticle); implementation uses JWBStrings; function FindMarkDef(m: string): TMarker; var i: integer; begin Result := #00; for i := Low(Markers) to High(Markers) do {$IFDEF CASE_SENSITIVE_MARKERS} if SysUtils.SameStr(markers[i].m, m) then begin {$ELSE} if markers[i].m = m then begin {$ENDIF} Result := AnsiChar(i); break; end; end; function GetMarkerText(id: TMarker): string; begin Result := Markers[byte(id)].m; end; procedure TKanjiEntry.Reset; begin kanji := ''; markers := ''; end; procedure TKanaEntry.Reset; begin kana := ''; kanji_used := 0; markers := ''; end; function TKanaEntry.AddKanji: PUnicodeString; begin Inc(kanji_used); if kanji_used>Length(kanji) then raise EEdictParsingException.Create('KanaEntry: Cannot add one more kanji'); Result := @kanji[kanji_used-1]; Result^ := ''; end; procedure TSenseEntry.Reset; begin pos := ''; markers := ''; text := ''; end; procedure TEdictArticle.Reset; begin ref := ''; kanji_used := 0; kana_used := 0; senses_used := 0; pop := false; end; function TEdictArticle.AddKanji: PKanjiEntry; begin Inc(kanji_used); if kanji_used>Length(kanji) then raise EEdictParsingException.Create('EdictArticle: Cannot add one more kanji'); Result := @kanji[kanji_used-1]; Result^.Reset; end; function TEdictArticle.AddKana: PKanaEntry; begin Inc(kana_used); if kana_used>Length(kana) then raise EEdictParsingException.Create('EdictArticle: Cannot add one more kana'); Result := @kana[kana_used-1]; Result^.Reset; end; function TEdictArticle.AddSense: PSenseEntry; begin Inc(senses_used); if senses_used>Length(senses) then raise EEdictParsingException.Create('EdictArticle: Cannot add one more meaning'); Result := @senses[senses_used-1]; Result^.Reset; end; procedure TEdictArticle.TrimEverything; var i,j: integer; begin for i := 0 to kanji_used - 1 do kanji[i].kanji := UTrim(kanji[i].kanji); for i := 0 to kana_used - 1 do begin kana[i].kana := UTrim(kana[i].kana); for j := 0 to kana[i].kanji_used - 1 do kana[i].kanji[j] := UTrim(kana[i].kanji[j]); end; for i := 0 to senses_used - 1 do senses[i].text := UTrim(senses[i].text); end; function IsNumeric(const s:UnicodeString): boolean; var i: integer; begin Result := true; for i := 1 to Length(s) do if (s[i]<'0') or (s[i]>'9') then begin Result := false; exit; end; end; { EDICT2/EDICT: Example of string: いい加減(P);好い加減;好加減(io) [いいかげん] /(adj-na) (1) (uk) irresponsible/perfunctory/careless /(2) lukewarm/half-baked/halfhearted/vague /(3) (See いい加減にする) reasonable/moderate (usu. in suggestions or orders) /(adv) (4) considerably/quite/rather/pretty /(P) /EntL1277440X/ Features of EDICT2 to watch out for: Multi-kanji, multi-reading, with specific pairings: あっと言う間;あっという間;あっとゆう間 [あっというま(あっと言う間,あっという間); あっとゆうま(あっと言う間,あっとゆう間)] /(exp) (See あっと言う間に) a blink of time/the time it takes to say "Ah!" /EntL2208410/ Common markers for some kanji/readings: Separate (P) markers for article and readings: (P) marker for article applies to all of its entries あり得ない(P);有り得ない(P);有得ない [ありえない] /(adj-i) (uk) (See 有り得る・ありうる) impossible/unlikely/improbable/(P) /EntL2109610X/ POS markers apply to "all senses starting with this one": Non-POS markers apply only to current sense: いい事[いいこと] /(exp,n) (1) good thing/nice thing /(2) (usu. as ~をいいことに(して)) good excuse/good grounds/good opportunity /(int) (3) (fem) interjection used to impress an idea or to urge a response/EntL2583070/ Sequence '/(' can occur legitimately: /(expression of) effort } procedure ParseEdict2Line(const s:UnicodeString; ed: PEdictArticle); const EH_KANJI = 1; EH_KANA = 2; EH_KANAKANJI = 3; EH_SENSE = 4; var curkanji: PKanjiEntry; curkana: PKanaEntry; curkanakanji: PUnicodeString; cursense: PSenseEntry; nextsense: TSenseEntry; //current part of the sense, still not commited curmark: UnicodeString; //current marker word, to be tested inmarker: integer; markdef: TMarker; markch: WideChar; //if inmarker, this holds the marker opening braket type -- only for senses markopen: boolean; //if set, some of the markers weren't found and we added a marker braket back to curtext -- have to close it commpos: TMarkers; //common POS markers -- carried over from the previous sense eh: integer; ch: WideChar; i: integer; procedure CommitNextSense; begin //detect ref if (upos(' ', nextsense.text)=0) and (Length(nextsense.text)>4) and (nextsense.text[1]='E') and (nextsense.text[2]='n') and (nextsense.text[3]='t') and (nextsense.text[4]='L') then begin ed.ref := nextsense.text; end else begin if nextsense.text<>'' then // stuff like /(P)/ can leave us with empty text if cursense^.text<>'' then cursense^.text := cursense^.text + '/' + UTrim(nextsense.text) else cursense^.text := UTrim(nextsense.text); cursense^.markers := cursense^.markers + nextsense.markers; cursense^.pos := cursense^.pos + nextsense.pos; end; nextsense.Reset; end; procedure NewSense; begin //Commit old sense if cursense.pos = '' then cursense.pos := commpos else commpos := cursense.pos; //new pos markers //Add sense cursense := ed.AddSense; end; begin ed.Reset; eh := EH_KANJI; curkanji := ed.AddKanji; curkana := nil; curkanakanji := nil; cursense := nil; nextsense.Reset; inmarker := 0; markopen := false; markch := #00; commpos := ''; i := 1; while i<=Length(s) do begin ch := s[i]; if (eh=EH_KANJI) and (ch='(') then Inc(inmarker) else if (eh=EH_KANJI) and (inmarker=1) and ((ch=',') or (ch=')')) then begin //only on first level of depth markdef := FindMarkDef(UTrim(curmark)); //recognized EDICT marker if markdef <> #00 then curkanji.markers := curkanji.markers + markdef; //there's nothing we can do if it's unrecognized -- have to just drop it curmark := ''; if ch=')' then Dec(inmarker); end else if (eh=EH_KANJI) and (inmarker>1) and (ch=')') then Dec(inmarker) else if (eh=EH_KANJI) and (inmarker>0) then curmark := curmark + ch else if (eh=EH_KANJI) and (inmarker>0) and ((ch=';')or(ch='[')or(ch='/')) then //safety raise EEdictParsingException.Create('Invalid characters in kanji markers') else if (eh=EH_KANJI) and (ch=';') then curkanji := ed.AddKanji else if (eh=EH_KANJI) and (ch='[') then begin eh := EH_KANA; curkana := ed.AddKana; end else if (eh=EH_KANJI) and (ch='/') then begin eh := EH_SENSE; cursense := ed.AddSense; end else if (eh=EH_KANJI) then curkanji.kanji := curkanji.kanji + ch else if (eh=EH_KANA) and (ch='(') then begin if (inmarker<=0) and (EvalChar(s[i+1])=EC_IDG_CHAR) then begin eh := EH_KANAKANJI; curkanakanji := curkana.AddKanji; end else Inc(inmarker); end else if (eh=EH_KANA) and (inmarker=1) and ((ch=',') or (ch=')')) then begin //only on first level of depth markdef := FindMarkDef(UTrim(curmark)); //recognized EDICT marker if markdef <> #00 then curkana.markers := curkana.markers + markdef; curmark := ''; if ch=')' then Dec(inmarker); end else if (eh=EH_KANA) and (inmarker>1) and (ch=')') then Dec(inmarker) else if (eh=EH_KANA) and (inmarker>0) then curmark := curmark + ch else if (eh=EH_KANJI) and (inmarker>0) and ((ch=';')or(ch=']')) then //safety raise EEdictParsingException.Create('Invalid characters in kanji markers') else if (eh=EH_KANA) and (ch=';') then curkana := ed.AddKana else if (eh=EH_KANA) and (ch=']') then begin eh := EH_SENSE; cursense := ed.AddSense; end else if (eh=EH_KANA) then curkana.kana := curkana.kana + ch else if (eh=EH_KANAKANJI) and (ch=',') then curkanakanji := curkana.AddKanji else if (eh=EH_KANAKANJI) and (ch=')') then eh := EH_KANA else if (eh=EH_KANAKANJI) then curkanakanji^ := curkanakanji^ + ch else { We use a special approach for meaning. Anything we read, we put into 'curpart'. When we encounter a '/', we flush 'curpart' into 'current meaning'. If, inside a part, we encounter (2), (3) etc, then it's a new part, and we replace 'current meaning' with a new one. When we encounter markers, we strip known ones and leave unrecognized ones. } if (eh=EH_SENSE) and (ch='/') then begin CommitNextSense(); end else if (eh=EH_SENSE) and ((ch='(')or(ch='{')) then begin Inc(inmarker); if (inmarker=1) then begin markch:=ch; markopen:=false; curmark:=''; end; end else if (eh=EH_SENSE) and (inmarker=1) and ((ch=',')or(ch=')')or(ch='}')) then begin //only on first level //New entry if IsNumeric(curmark) then if curmark='1' then begin end //first entry doesn't need any additional slot, but we still handle it to cut the (1) mark else NewSense() else //(P) marker if curmark='P' then begin ed.pop := true; end else begin markdef := FindMarkDef(UTrim(curmark)); //recognized EDICT marker if markdef <> #00 then begin if mfPos in markers[byte(markdef)].f then nextsense.pos := nextsense.pos + markdef else nextsense.markers := nextsense.markers + markdef; end else //unrecognized marker or normal text begin if not markopen then begin nextsense.text := nextsense.text + markch + curmark; //no trim markopen := true; end else nextsense.text := nextsense.text + ',' + curmark; end; end; curmark := ''; if ch<>',' then begin if markopen then case markch of '(': nextsense.text := nextsense.text + ')'; '{': nextsense.text := nextsense.text + '}'; end; Dec(inmarker); end; end else if (eh=EH_SENSE) and (inmarker>1) and ((ch=')')or(ch='}')) then Dec(inmarker) else if (eh=EH_SENSE) and (inmarker>0) then curmark := curmark + ch else if (eh=EH_SENSE) then nextsense.text := nextsense.text + ch; Inc(i); end; if (eh=EH_SENSE) and (nextsense.text<>'') or (nextsense.markers<>'') or (nextsense.pos<>'') then //shouldnt happen CommitNextSense(); //No sense part => 100% invalid line, helps to catch wrong encodings if eh<>EH_SENSE then raise EEdictParsingException.Create('Invalid EDICT line.'); ed.TrimEverything; end; { CCEDICT is in a similar but different format: Kanji versions are separated by space, not ';': 授計 授计 [shou4 ji4] /to confide a plan to sb/ There are at most two of these (traditional and simplified). Kanji versions can be the same: 授予 授予 [shou4 yu3] /to award/to confer/ There's at most one reading, but it contains spaces: 授受不親 授受不亲 [shou4 shou4 bu4 qin1] Reading is in pinyin, but can contain english letters (I've only seen capital ones): AA制 AA制 [A A zhi4] /to split the bill/to go Dutch/ Can contain commas or · dots when kanji contain those: 一日不見,如隔三秋 一日不见,如隔三秋 [yi1 ri4 bu4 jian4 , ru2 ge2 san1 qiu1] Markers are not supported. EDICT separates senses and glosses: /(1) falter/waver/(2) flap CC-EDICT doesn't, unrelated and related senses are formatted the same: /numerical range/interval/taxation band/ /tired/exhausted/wretched/ Therefore we are either to show ALL glosses as separate senses: (1) tired; (2) exhausted; (3) wretched Or to show them as a single sense: numerical range; interval; taxation band Second one probably looks better. } procedure DeleteDuplicateKanji(ed: PEdictArticle); forward; procedure ParseCCEdictLine(const s:UnicodeString; ed: PEdictArticle); const EH_KANJI = 1; EH_KANA = 2; EH_SENSE = 3; var curkanji: PKanjiEntry; curkana: PKanaEntry; cursense: PSenseEntry; eh: integer; i: integer; ch: WideChar; begin ed.Reset; eh := EH_KANJI; curkanji := nil; curkana := nil; cursense := nil; i := 1; while i<=Length(s) do begin ch := s[i]; if (eh=EH_KANJI) and (ch=' ') then curkanji := nil {kanji over, but perhaps there will be no another kanji} else if (eh=EH_KANJI) and (ch='[') then begin eh := EH_KANA; curkana := ed.AddKana; end else if (eh=EH_KANJI) and (ch='/') then begin eh := EH_SENSE; cursense := ed.AddSense; end else if (eh=EH_KANJI) then begin if curkanji=nil then curkanji := ed.AddKanji; curkanji.kanji := curkanji.kanji + ch; end else if (eh=EH_KANA) and (ch=']') then begin eh := EH_SENSE; cursense := nil; end else if (eh=EH_KANA) then curkana.kana := curkana.kana + ch else if (eh=EH_SENSE) and (cursense=nil) and (ch='/') then cursense := ed.AddSense else //first time we encounter / we just start a sense if (eh=EH_SENSE) and (cursense=nil) then begin { skip until sense start } end else if (eh=EH_SENSE) then cursense.text := cursense.text + ch; Inc(i); end; //Senses usually end on /, so we replaced that with ; if (cursense<>nil) and (Length(cursense.text)>0) and (cursense.text[Length(cursense.text)]='/') then delete(cursense.text, Length(cursense.text), 1); //No sense part => 100% invalid line, helps to catch wrong encodings if eh<>EH_SENSE then raise EEdictParsingException.Create('Invalid CEDICT line.'); ed.TrimEverything; //Simplified kanji could be the same as traditional, so kill off duplicates DeleteDuplicateKanji(ed); end; //Removes duplicate kanji. Checks only the kanji itself and not markers or kana //attachments, so not valid for EDICT2. procedure DeleteDuplicateKanji(ed: PEdictArticle); var i,j: integer; dupshift: integer; //how many cells to skip begin dupshift := 0; for i := 0 to ed.kanji_used - 1 do begin j := 0; while j+dupshift<i do begin if SysUtils.SameStr(ed.kanji[i].kanji,ed.kanji[j].kanji) then break; Inc(j); end; if j+dupshift<i then //found match Inc(dupshift) //skip this one too else //valid cell, shift it to the left if dupshift>0 then ed.kanji[i-dupshift]:=ed.kanji[i]; end; end; end.
unit DBXMetadataHelper; interface uses Forms, SysUtils, SqlExpr, IBDatabase, DbxCommon, DbxMetaDataProvider, DBXDataExpressMetaDataProvider, DbxInterbase, DbxClient; function DBXGetMetaProvider(const AConnection: TDBXConnection) : TDBXDataExpressMetaDataProvider; procedure InitConnection(conn: TSQLConnection; dbname: string; CreateDB: Boolean); function GetDatabaseDirectory: String; procedure AddPrimaryKey(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName: string); procedure AddUniqueIndex(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName: string); procedure AddForeignKey(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName, PrimaryTableName, PrimaryColumn: string); procedure CreateGenerator(Provider: TDBXDataExpressMetaDataProvider; GenName: string); procedure CreateAutoIncTrigger(Provider: TDBXDataExpressMetaDataProvider; Name, Table, Field, GenName: string); implementation function DBXGetMetaProvider(const AConnection: TDBXConnection) : TDBXDataExpressMetaDataProvider; var Provider: TDBXDataExpressMetaDataProvider; begin Provider := TDBXDataExpressMetaDataProvider.Create; try Provider.Connection := AConnection; Provider.Open; except FreeAndNil(Provider); raise ; end; Result := Provider; end; procedure InitConnection(conn: TSQLConnection; dbname: string; CreateDB: Boolean); var db: TIBDatabase; begin conn.DriverName := 'InterBase'; conn.Params.Clear; conn.Params.Add(TDBXPropertyNames.DriverName + '=InterBase'); conn.Params.Add(TDBXPropertyNames.HostName + '=localhost'); conn.Params.Add(TDBXPropertyNames.Database + '=' + GetDatabaseDirectory + dbname); conn.Params.Add(TDBXPropertyNames.UserName + '=sysdba'); conn.Params.Add(TDBXPropertyNames.Password + '=masterkey'); conn.LoginPrompt := false; if (CreateDB) then begin db := TIBDatabase.Create(nil); db.LoginPrompt := false; db.SQLDialect := 3; db.DatabaseName := GetDatabaseDirectory + dbname; db.Params.Text := 'USER "SYSDBA" PASSWORD "masterkey" '; // db.Params.Values['user_name'] := 'sysdba'; // db.Params.Values['password'] := 'masterkey'; db.CreateDatabase; db.Free; // conn.Params.Add('create=true'); end; conn.Open; end; function GetDatabaseDirectory: String; begin Result := GetCurrentDir; if Result[Length(Result)] <> '\' then Result := Result + '\'; Result := Result + 'Database\'; end; procedure AddPrimaryKey(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName: string); var index: TDBXMetaDataIndex; begin index := TDBXMetaDataIndex.Create; index.TableName := TableName; index.AddColumn(ColumnName); Provider.CreatePrimaryKey(index); index.Free; end; procedure AddUniqueIndex(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName: string); var index: TDBXMetaDataIndex; begin index := TDBXMetaDataIndex.Create; index.TableName := TableName; index.AddColumn(ColumnName); Provider.CreateUniqueIndex(index); index.Free; end; procedure AddForeignKey(Provider: TDBXDataExpressMetaDataProvider; TableName, ColumnName, PrimaryTableName, PrimaryColumn: string); var key: TDBXMetaDataForeignKey; begin key := TDBXMetaDataForeignKey.Create; key.PrimaryTableName := PrimaryTableName; key.TableName := TableName; key.AddReference(ColumnName, PrimaryColumn); Provider.CreateForeignKey(key); key.Free; end; procedure CreateGenerator(Provider: TDBXDataExpressMetaDataProvider; GenName: string); var cmd: TDBXCommand; begin cmd := Provider.Connection.CreateCommand; try cmd.CommandType := TDBXCommandTypes.DbxSQL; cmd.Text := 'Create Generator ' + GenName; cmd.ExecuteUpdate; finally cmd.Free; end; end; procedure CreateAutoIncTrigger(Provider: TDBXDataExpressMetaDataProvider; Name, Table, Field, GenName: string); Const Trigger: String = 'Create Trigger %s for %s active BEFORE INSERT ' + #13#10 + 'AS BEGIN ' + #13#10 + ' new.%s = gen_id( %s, 1); ' + #13#10 + ' end'; var cmd: TDBXCommand; begin cmd := Provider.Connection.CreateCommand; try cmd.CommandType := TDBXCommandTypes.DbxSQL; cmd.Text := Format(Trigger, [Name, Table, Field, GenName]); cmd.ExecuteUpdate; finally cmd.Free end; end; end.
unit uReminders; interface uses Windows, Messages, Classes, Controls, StdCtrls, SysUtils, ComCtrls, Menus, Graphics, Forms, ORClasses, ORCtrls, ORDtTm, ORFn, ORNet, Dialogs, uPCE, uVitals, ExtCtrls, fDrawers, fDeviceSelect, TypInfo; type TReminderDialog = class(TObject) private FDlgData: string; FElements: TStringList; // list of TRemDlgElement objects FOnNeedRedraw: TNotifyEvent; FNeedRedrawCount: integer; FOnTextChanged: TNotifyEvent; FTextChangedCount: integer; FPCEDataObj: TPCEData; FNoResolve: boolean; FWHReviewIEN: string; // AGP CHANGE 23.13 Allow for multiple processing of WH Review of Result Reminders FRemWipe: integer; FMHTestArray: TORStringList; protected function GetIEN: string; virtual; function GetPrintName: string; virtual; procedure BeginNeedRedraw; procedure EndNeedRedraw(Sender: TObject); procedure BeginTextChanged; procedure EndTextChanged(Sender: TObject); function GetDlgSL: TORStringList; procedure ComboBoxResized(Sender: TObject); procedure ComboBoxCheckedText(Sender: TObject; NumChecked: integer; var Text: string); function AddData(Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; function Visible: boolean; public constructor BaseCreate; constructor Create(ADlgData: string); destructor Destroy; override; procedure FinishProblems(List: TStrings; var MissingTemplateFields: boolean); function BuildControls(ParentWidth: integer; AParent, AOwner: TWinControl): TWinControl; function Processing: boolean; procedure AddText(Lst: TStrings); property PrintName: string read GetPrintName; property IEN: string read GetIEN; property Elements: TStringList read FElements; property OnNeedRedraw: TNotifyEvent read FOnNeedRedraw write FOnNeedRedraw; property OnTextChanged: TNotifyEvent read FOnTextChanged write FOnTextChanged; property PCEDataObj: TPCEData read FPCEDataObj write FPCEDataObj; property DlgData: string read FDlgData; //AGP Change 24.8 property WHReviewIEN: string read FWHReviewIEN write FWHReviewIEN; //AGP CHANGE 23.13 property RemWipe: integer read FRemWipe write FRemWipe; property MHTestArray: TORStringList read FMHTestArray write FMHTestArray; end; TReminder = class(TReminderDialog) private FRemData: string; FCurNodeID: string; protected function GetDueDateStr: string; function GetLastDateStr: string; function GetIEN: string; override; function GetPrintName: string; override; function GetPriority: integer; function GetStatus: string; public constructor Create(ARemData: string); property DueDateStr: string read GetDueDateStr; property LastDateStr: string read GetLastDateStr; property Priority: integer read GetPriority; property Status: string read GetStatus; property RemData: string read FRemData; property CurrentNodeID: string read FCurNodeID write FCurNodeID; end; TRDChildReq = (crNone, crOne, crAtLeastOne, crNoneOrOne, crAll); TRDElemType = (etCheckBox, etTaxonomy, etDisplayOnly); TRemPrompt = class; TRemDlgElement = class(TObject) private FReminder: TReminderDialog; FParent: TRemDlgElement; FChildren: TList; // Points to other TRemDlgElement objects FData: TList; // List of TRemData objects FPrompts: TList; // list of TRemPrompts objects FText: string; FPNText: string; FRec1: string; FID: string; FDlgID: string; FHaveData: boolean; FTaxID: string; FChecked: boolean; FChildrenShareChecked: boolean; FHasSharedPrompts: boolean; FHasComment: boolean; FHasSubComments: boolean; FCommentPrompt: TRemPrompt; FFieldValues: TORStringList; FMSTPrompt: TRemPrompt; FWHPrintDevice, FWHResultChk, FWHResultNot: String; FVitalDateTime: TFMDateTime; //AGP Changes 26.1 protected procedure Check4ChildrenSharedPrompts; function ShowChildren: boolean; function EnableChildren: boolean; function Enabled: boolean; procedure SetChecked(const Value: boolean); procedure UpdateData; function oneValidCode(Choices: TORStringList; ChoicesActiveDates: TList; encDt: TFMDateTime): String; procedure setActiveDates(Choices: TORStringList; ChoicesActiveDates: TList; ActiveDates: TStringList); procedure GetData; function TrueIndent: integer; procedure cbClicked(Sender: TObject); procedure cbEntered(Sender: TObject); procedure FieldPanelEntered(Sender: TObject); procedure FieldPanelExited(Sender: TObject); procedure FieldPanelKeyPress(Sender: TObject; var Key: Char); procedure FieldPanelOnClick(Sender: TObject); procedure FieldPanelLabelOnClick(Sender: TObject); function BuildControls(var Y: integer; ParentWidth: integer; BaseParent, AOwner: TWinControl): TWinControl; function AddData(Lst: TStrings; Finishing: boolean; AHistorical: boolean = FALSE): integer; procedure FinishProblems(List: TStrings); function IsChecked: boolean; procedure SubCommentChange(Sender: TObject); function EntryID: string; procedure FieldPanelChange(Sender: TObject); procedure GetFieldValues(FldData: TStrings); procedure ParentCBEnter(Sender: TObject); procedure ParentCBExit(Sender: TObject); public constructor Create; destructor Destroy; override; function ElemType: TRDElemType; function Add2PN: boolean; function Indent: integer; function FindingType: string; function Historical: boolean; function ResultDlgID: string; function IncludeMHTestInPN: boolean; function HideChildren: boolean; function ChildrenIndent: integer; function ChildrenSharePrompts: boolean; function ChildrenRequired: TRDChildReq; function Box: boolean; function BoxCaption: string; function IndentChildrenInPN: boolean; function IndentPNLevel: integer; function GetTemplateFieldValues(const Text: string; FldValues: TORStringList = nil): string; procedure AddText(Lst: TStrings); property Text: string read FText; property ID: string read FID; property DlgID: string read FDlgID; property Checked: boolean read FChecked write SetChecked; property Reminder: TReminderDialog read FReminder; property HasComment: boolean read FHasComment; property WHPrintDevice: String read FWHPrintDevice write FWHPrintDevice; property WHResultChk: String read FWHResultChk write FWHResultChk; property WHResultNot: String read FWHResultNot write FWHResultNot; property VitalDateTime: TFMDateTime read FVitalDateTime write FVitalDateTime; end; TRemDataType = (dtDiagnosis, dtProcedure, dtPatientEducation, dtExam, dtHealthFactor, dtImmunization, dtSkinTest, dtVitals, dtOrder, dtMentalHealthTest, dtWHPapResult, dtWhNotPurp); TRemPCERoot = class; TRemData = class(TObject) private FPCERoot: TRemPCERoot; FParent: TRemDlgElement; FRec3: string; FActiveDates: TStringList; //Active dates for finding items. (rectype 3) // FRoot: string; FChoices: TORStringList; FChoicesActiveDates: TList; //Active date ranges for taxonomies. (rectype 5) //List of TStringList objects that contain active date //ranges for each FChoices object of the same index FChoicePrompt: TRemPrompt; //rectype 4 FChoicesMin: integer; FChoicesMax: integer; FChoicesFont: THandle; FSyncCount: integer; protected function AddData(List: TStrings; Finishing: boolean): integer; public destructor Destroy; override; function Add2PN: boolean; function DisplayWHResults: boolean; function InternalValue: string; function ExternalValue: string; function Narrative: string; function Category: string; function DataType: TRemDataType; property Parent: TRemDlgElement read FParent; end; TRemPromptType = (ptComment, ptVisitLocation, ptVisitDate, ptQuantity, ptPrimaryDiag, ptAdd2PL, ptExamResults, ptSkinResults, ptSkinReading, ptLevelSeverity, ptSeries, ptReaction, ptContraindicated, ptLevelUnderstanding, ptWHPapResult, ptWHNotPurp); TRemPrompt = class(TObject) private FFromControl: boolean; FParent: TRemDlgElement; FRec4: string; FCaptionAssigned: boolean; FData: TRemData; FValue: string; FOverrideType: TRemPromptType; FIsShared: boolean; FSharedChildren: TList; FCurrentControl: TControl; FFromParent: boolean; FInitializing: boolean; FMiscText: string; FMonthReq: boolean; FPrintNow: String; FMHTestComplete: integer; protected function RemDataActive(RData: TRemData; EncDt: TFMDateTime):Boolean; function CompareActiveDate(ActiveDates: TStringList; EncDt: TFMDateTime):Boolean; function RemDataChoiceActive(RData: TRemData; j: integer; EncDt: TFMDateTime):Boolean; function GetValue: string; procedure SetValueFromParent(Value: string); procedure SetValue(Value: string); procedure PromptChange(Sender: TObject); procedure VitalVerify(Sender: TObject); procedure ComboBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); function CanShare(Prompt: TRemPrompt): boolean; procedure InitValue; procedure DoMHTest(Sender: TObject); procedure DoWHReport(Sender: TObject); procedure ViewWHText(Sender: TObject); procedure GAFHelp(Sender: TObject); function EntryID: string; procedure EditKeyPress(Sender: TObject; var Key: Char); public constructor Create; destructor Destroy; override; function PromptOK: boolean; function PromptType: TRemPromptType; function Add2PN: boolean; function InternalValue: string; function Forced: boolean; function Caption: string; function ForcedCaption: string; function SameLine: boolean; function Required: boolean; function NoteText: string; function VitalType: TVitalType; function VitalValue: string; function VitalUnitValue: string; property Value: string read GetValue write SetValue; end; TRemPCERoot = class(TObject) private FData: TList; FID: string; FForcedPrompts: TStringList; FValue: string; FValueSet: string; protected class function GetRoot(Data: TRemData; Rec3: string; Historical: boolean): TRemPCERoot; procedure Done(Data: TRemData); procedure Sync(Prompt: TRemPrompt); procedure UnSync(Prompt: TRemPrompt); function GetValue(PromptType: TRemPromptType; var NewValue: string): boolean; public destructor Destroy; override; end; TReminderStatus = (rsDue, rsApplicable, rsNotApplicable, rsNone, rsUnknown); TRemCanFinishProc = function: boolean of object; TRemDisplayPCEProc = procedure of object; TTreeChangeNotifyEvent = procedure(Proc: TNotifyEvent) of object; TRemForm = record Form: TForm; PCEObj: TPCEData; RightPanel: TPanel; CanFinishProc: TRemCanFinishProc; DisplayPCEProc: TRemDisplayPCEProc; DrawerReminderTV: TORTreeView; DrawerReminderTreeChange: TTreeChangeNotifyEvent; DrawerRemoveReminderTreeChange: TTreeChangeNotifyEvent; NewNoteRE: TRichEdit; NoteList: TORListBox; end; var RemForm: TRemForm; NotPurposeValue: string; WHRemPrint: string; InitialRemindersLoaded: boolean = FALSE; const HAVE_REMINDERS = 0; NO_REMINDERS = 1; RemPriorityText: array[1..3] of string = ('High','','Low'); ClinMaintText = 'Clinical Maintenance'; dtUnknown = TRemDataType(-1); dtAll = TRemDataType(-2); dtHistorical = TRemDataType(-3); ptUnknown = TRemPromptType(-1); ptSubComment = TRemPromptType(-2); ptDataList = TRemPromptType(-3); ptVitalEntry = TRemPromptType(-4); ptMHTest = TRemPromptType(-5); ptGAF = TRemPromptType(-6); ptMST = TRemPromptType(-7); MSTCode = 'MST'; MSTDataTypes = [pdcHF, pdcExam]; pnumMST = ord(pnumComment)+4; procedure NotifyWhenRemindersChange(Proc: TNotifyEvent); procedure RemoveNotifyRemindersChange(Proc: TNotifyEvent); procedure StartupReminders; function GetReminderStatus: TReminderStatus; function RemindersEvaluatingInBackground: boolean; procedure ResetReminderLoad; procedure LoadReminderData(ProcessingInBackground: boolean = FALSE); function ReminderEvaluated(Data: string; ForceUpdate: boolean = FALSE): boolean; procedure RemindersEvaluated(List: TStringList); procedure EvalReminder(ien: integer); procedure EvalProcessed; procedure EvaluateCategoryClicked(AData: pointer; Sender: TObject); procedure SetReminderPopupRoutine(Menu: TPopupMenu); procedure SetReminderPopupCoverRoutine(Menu: TPopupMenu); procedure SetReminderMenuSelectRoutine(Menu: TMenuItem); procedure BuildReminderTree(Tree: TORTreeView); function ReminderNode(Node: TTreeNode): TORTreeNode; procedure ClearReminderData; function GetReminder(ARemData: string): TReminder; procedure WordWrap(AText: string; Output: TStrings; LineLength: integer; AutoIndent: integer = 4; MHTest: boolean = false); function InteractiveRemindersActive: boolean; function GetReminderData(Rem: TReminderDialog; Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; overload; function GetReminderData(Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; overload; procedure SetReminderFormBounds(Frm: TForm; DefX, DefY, DefW, DefH, ALeft, ATop, AWidth, AHeight: integer); procedure UpdateReminderDialogStatus; //const // InteractiveRemindersActive = FALSE; var { ActiveReminder string format: IEN^PRINT NAME^DUE DATE/TIME^LAST OCCURENCE DATE/TIME^PRIORITY^DUE^DIALOG where PRIORITY 1=High, 2=Normal, 3=Low DUE 0=Applicable, 1=Due, 2=Not Applicable } ActiveReminders: TORStringList = nil; { OtherReminder string format: IDENTIFIER^TYPE^NAME^PARENT IDENTIFIER^REMINDER IEN^DIALOG where TYPE C=Category, R=Reminder } OtherReminders: TORStringList = nil; RemindersInProcess: TORStringList = nil; CoverSheetRemindersInBackground: boolean = FALSE; KillReminderDialogProc: procedure(frm: TForm) = nil; RemindersStarted: boolean = FALSE; ProcessedReminders: TORStringList = nil; ReminderDialogInfo: TStringList = nil; const CatCode = 'C'; RemCode = 'R'; EduCode = 'E'; pnumVisitLoc = pnumComment + 1; pnumVisitDate = pnumComment + 2; RemTreeDateIdx = 8; IncludeParentID = ';'; OtherCatID = CatCode + '-6'; RemDataCodes: array[TRemDataType] of string = { dtDiagnosis } ('POV', { dtProcedure } 'CPT', { dtPatientEducation } 'PED', { dtExam } 'XAM', { dtHealthFactor } 'HF', { dtImmunization } 'IMM', { dtSkinTest } 'SK', { dtVitals } 'VIT', { dtOrder } 'Q', { dtMentalHealthTest } 'MH', { dtWHPapResult } 'WHR', { dtWHNotPurp } 'WH'); implementation uses rCore, uCore, rReminders, fRptBox, uConst, fReminderDialog, fNotes, rMisc, fMHTest, rPCE, rTemplates, dShared, uTemplateFields, fIconLegend, fReminderTree, uInit, VAUtils, VA508AccessibilityRouter, VA508AccessibilityManager, uDlgComponents, fBase508Form, System.Types, System.UITypes; type TRemFolder = (rfUnknown, rfDue, rfApplicable, rfNotApplicable, rfEvaluated, rfOther); TRemFolders = set of TRemFolder; TValidRemFolders = succ(low(TRemFolder)) .. high(TRemFolder); TExposedComponent = class(TControl); TWHCheckBox = class(TCPRSDialogCheckBox) private FPrintNow: TCPRSDialogCheckBox; FViewLetter: TCPRSDialogCheckBox; FCheck1: TWHCheckBox; FCheck2: TWHCheckBox; FCheck3: TWHCheckBox; FEdit: TEdit; FButton: TButton; FOnDestroy: TNotifyEvent; Flbl, Flbl2: TControl; FPrintVis: String; //FPrintDevice: String; FPntNow: String; FPntBatch: String; FButtonText: String; FCheckNum: String; protected public property lbl: TControl read Flbl write Flbl; property lbl2: TControl read Flbl2 write Flbl2; property PntNow: String read FPntNow write FPntNow; property PntBatch: String read FPntBatch write FPntBatch; property CheckNum: String read FCheckNum write FCheckNum; property ButtonText: String read FButtonText write FButtonText; property PrintNow: TCPRSDialogCheckBox read FPrintNow write FPrintNow; property Check1: TWHCheckBox read FCheck1 write FCheck1; property Check2: TWHCheckBox read FCheck2 write FCheck2; property Check3: TWHCheckBox read FCheck3 write FCheck3; property ViewLetter: TCPRSDialogCheckBox read FViewLetter write FViewLetter; property Button: TButton read FButton write FButton; property Edit: TEdit read FEdit write FEdit; property OnDestroy: TNotifyEvent read FOnDestroy write FOnDestroy; property PrintVis: String read FPrintVis write FPrintVis; end; var LastReminderLocation: integer = -2; EvaluatedReminders: TORStringList = nil; ReminderTreeMenu: TORPopupMenu = nil; ReminderTreeMenuDlg: TORPopupMenu = nil; ReminderCatMenu: TPopupMenu = nil; EducationTopics: TORStringList = nil; WebPages: TORStringList = nil; ReminderCallList: TORStringList = nil; LastProcessingList: string = ''; InteractiveRemindersActiveChecked: boolean = FALSE; InteractiveRemindersActiveStatus: boolean = FALSE; PCERootList: TStringList; PrimaryDiagRoot: TRemPCERoot = nil; ElementChecked: TRemDlgElement = nil; HistRootCount: longint = 0; uRemFolders: TRemFolders = [rfUnknown]; const DueText = 'Due'; ApplicableText = 'Applicable'; NotApplicableText = 'Not Applicable'; EvaluatedText = 'All Evaluated'; OtherText = 'Other Categories'; DueCatID = CatCode + '-2'; DueCatString = DueCatID + U + DueText; ApplCatID = CatCode + '-3'; ApplCatString = ApplCatID + U + ApplicableText; NotApplCatID = CatCode + '-4'; NotApplCatString = NotApplCatID + U + NotApplicableText; EvaluatedCatID = CatCode + '-5'; EvaluatedCatString = EvaluatedCatID + U + EvaluatedText; // OtherCatID = CatCode + '-6'; OtherCatString = OtherCatID + U + OtherText; LostCatID = CatCode + '-7'; LostCatString = LostCatID + U + 'In Process'; ReminderDateFormat = 'mm/dd/yyyy'; RemData2PCECat: array[TRemDataType] of TPCEDataCat = { dtDiagnosis } (pdcDiag, { dtProcedure } pdcProc, { dtPatientEducation } pdcPED, { dtExam } pdcExam, { dtHealthFactor } pdcHF, { dtImmunization } pdcImm, { dtSkinTest } pdcSkin, { dtVitals } pdcVital, { dtOrder } pdcOrder, { dtMentalHealthTest } pdcMH, { dtWHPapResult } pdcWHR, { dtWHNotPurp } pdcWH); RemPromptCodes: array[TRemPromptType] of string = { ptComment } ('COM', { ptVisitLocation } 'VST_LOC', { ptVisitDate } 'VST_DATE', { ptQuantity } 'CPT_QTY', { ptPrimaryDiag } 'POV_PRIM', { ptAdd2PL } 'POV_ADD', { ptExamResults } 'XAM_RES', { ptSkinResults } 'SK_RES', { ptSkinReading } 'SK_READ', { ptLevelSeverity } 'HF_LVL', { ptSeries } 'IMM_SER', { ptReaction } 'IMM_RCTN', { ptContraindicated } 'IMM_CNTR', { ptLevelUnderstanding } 'PED_LVL', { ptWHPapResult } 'WH_PAP_RESULT', { ptWHNotPurp } 'WH_NOT_PURP'); RemPromptTypes: array[TRemPromptType] of TRemDataType = { ptComment } (dtAll, { ptVisitLocation } dtHistorical, { ptVisitDate } dtHistorical, { ptQuantity } dtProcedure, { ptPrimaryDiag } dtDiagnosis, { ptAdd2PL } dtDiagnosis, { ptExamResults } dtExam, { ptSkinResults } dtSkinTest, { ptSkinReading } dtSkinTest, { ptLevelSeverity } dtHealthFactor, { ptSeries } dtImmunization, { ptReaction } dtImmunization, { ptContraindicated } dtImmunization, { ptLevelUnderstanding } dtPatientEducation, { ptWHPapResult } dtWHPapResult, { ptWHNotPurp } dtWHNotPurp); FinishPromptPieceNum: array[TRemPromptType] of integer = { ptComment } (pnumComment, { ptVisitLocation } pnumVisitLoc, { ptVisitDate } pnumVisitDate, { ptQuantity } pnumProcQty, { ptPrimaryDiag } pnumDiagPrimary, { ptAdd2PL } pnumDiagAdd2PL, { ptExamResults } pnumExamResults, { ptSkinResults } pnumSkinResults, { ptSkinReading } pnumSkinReading, { ptLevelSeverity } pnumHFLevel, { ptSeries } pnumImmSeries, { ptReaction } pnumImmReaction, { ptContraindicated } pnumImmContra, { ptLevelUnderstanding } pnumPEDLevel, { ptWHPapResult } pnumWHPapResult, { ptWHNotPurp } pnumWHNotPurp); ComboPromptTags: array[TRemPromptType] of integer = { ptComment } (0, { ptVisitLocation } TAG_HISTLOC, { ptVisitDate } 0, { ptQuantity } 0, { ptPrimaryDiag } 0, { ptAdd2PL } 0, { ptExamResults } TAG_XAMRESULTS, { ptSkinResults } TAG_SKRESULTS, { ptSkinReading } 0, { ptLevelSeverity } TAG_HFLEVEL, { ptSeries } TAG_IMMSERIES, { ptReaction } TAG_IMMREACTION, { ptContraindicated } 0, { ptLevelUnderstanding } TAG_PEDLEVEL, { ptWHPapResult } 0, { ptWHNotPurp } 0); PromptDescriptions: array [TRemPromptType] of string = { ptComment } ('Comment', { ptVisitLocation } 'Visit Location', { ptVisitDate } 'Visit Date', { ptQuantity } 'Quantity', { ptPrimaryDiag } 'Primary Diagnosis', { ptAdd2PL } 'Add to Problem List', { ptExamResults } 'Exam Results', { ptSkinResults } 'Skin Test Results', { ptSkinReading } 'Skin Test Reading', { ptLevelSeverity } 'Level of Severity', { ptSeries } 'Series', { ptReaction } 'Reaction', { ptContraindicated } 'Repeat Contraindicated', { ptLevelUnderstanding } 'Level of Understanding', { ptWHPapResult } 'Women''s Health Procedure', { ptWHNotPurp } 'Women Health Notification Purpose'); RemFolderCodes: array[TValidRemFolders] of char = { rfDue } ('D', { rfApplicable } 'A', { rfNotApplicable } 'N', { rfEvaluated } 'E', { rfOther } 'O'); MSTDescTxt: array[0..4,0..1] of string = (('Yes','Y'),('No','N'),('Declined','D'), ('Normal','N'),('Abnormal','A')); SyncPrompts = [ptComment, ptQuantity, ptAdd2PL, ptExamResults, ptSkinResults, ptSkinReading, ptLevelSeverity, ptSeries, ptReaction, ptContraindicated, ptLevelUnderstanding]; Gap = 3; LblGap = 4; IndentGap = 18; PromptGap = 10; NewLinePromptGap = 18; IndentMult = 9; PromptIndent = 30; gbLeftIndent = 2; gbTopIndent = 9; gbTopIndent2 = 16; DisabledFontColor = clBtnShadow; r3Type = 4; r3Code2 = 6; r3Code = 7; r3Cat = 9; r3Nar = 8; r3GAF = 12; RemTreeCode = 999; CRCode = '<br>'; CRCodeLen = length(CRCode); REMEntryCode = 'REM'; MonthReqCode = 'M'; function InitText(const InStr: string): string; var i: integer; begin Result := InStr; if(copy(Result, 1, CRCodeLen) = CRCode) then begin i := pos(CRCode, copy(Result, CRCodeLen+1, MaxInt)); if(i > 0) and ((i = (CRCodeLen + 1)) or (Trim(copy(Result, CrCodeLen+1, i - 1)) = '')) then delete(Result,1,CRCodeLen + i - 1); end; end; function CRLFText(const InStr: string): string; var i: integer; begin Result := InitText(InStr); repeat i := pos(CRCode, Result); if(i > 0) then Result := copy(Result,1,i-1) + CRLF + copy(REsult,i + CRCodeLen, MaxInt); until(i = 0); end; function Code2VitalType(Code: string): TVitalType; var v: TVitalType; begin Result := vtUnknown; for v := low(TValidVitalTypes) to high(TValidVitalTypes) do begin if(Code = VitalPCECodes[v]) then begin Result := v; break; end; end; end; type TMultiClassObj = record case integer of 0: (edt: TCPRSDialogFieldEdit); 1: (cb: TCPRSDialogCheckBox); 2: (cbo: TCPRSDialogComboBox); 3: (dt: TCPRSDialogDateCombo); 4: (ctrl: TORExposedControl); 5: (vedt: TVitalEdit); 6: (vcbo: TVitalComboBox); 7: (btn: TCPRSDialogButton); 8: (pNow: TORCheckBox); 9: (pBat: TORCheckBox); 10: (lbl: TLabel); 11: (WHChk: TWHCheckBox); end; EForcedPromptConflict = class(EAbort); function IsSyncPrompt(pt: TRemPromptType): boolean; begin if(pt in SyncPrompts) then Result := TRUE else Result := (pt = ptVitalEntry); end; procedure NotifyWhenRemindersChange(Proc: TNotifyEvent); begin ActiveReminders.Notifier.NotifyWhenChanged(Proc); OtherReminders.Notifier.NotifyWhenChanged(Proc); RemindersInProcess.Notifier.NotifyWhenChanged(Proc); Proc(nil); end; procedure RemoveNotifyRemindersChange(Proc: TNotifyEvent); begin ActiveReminders.Notifier.RemoveNotify(Proc); OtherReminders.Notifier.RemoveNotify(Proc); RemindersInProcess.Notifier.RemoveNotify(Proc); end; function ProcessingChangeString: string; var i: integer; TmpSL: TStringList; begin Result := U; if(RemindersInProcess.Count > 0) then begin TmpSL := TStringList.Create; try FastAssign(RemindersInProcess, TmpSL); TmpSL.Sort; for i := 0 to TmpSL.Count-1 do begin if(TReminder(TmpSL.Objects[i]).Processing) then Result := Result + TmpSL[i] + U; end; finally TmpSL.Free; end; end; end; procedure StartupReminders; begin if(not InitialRemindersLoaded) then begin RemindersStarted := TRUE; InitialRemindersLoaded := TRUE; LoadReminderData; end; end; function GetReminderStatus: TReminderStatus; begin if(EvaluatedReminders.IndexOfPiece('1',U,6) >= 0) then Result := rsDue else if(EvaluatedReminders.IndexOfPiece('0',U,6) >= 0) then Result := rsApplicable else if(EvaluatedReminders.IndexOfPiece('2',U,6) >= 0) then Result := rsNotApplicable else Result := rsUnknown; // else if(EvaluatedReminders.Count > 0) or (OtherReminders.Count > 0) or // (not InitialRemindersLoaded) or // (ProcessingChangeString <> U) then Result := rsUnknown // else Result := rsNone; end; function RemindersEvaluatingInBackground: boolean; begin Result := CoverSheetRemindersInBackground; if(not Result) then Result := (ReminderCallList.Count > 0) end; var TmpActive: TStringList = nil; TmpOther: TStringList = nil; procedure BeginReminderUpdate; begin ActiveReminders.Notifier.BeginUpdate; OtherReminders.Notifier.BeginUpdate; TmpActive := TStringList.Create; FastAssign(ActiveReminders, TmpActive); TmpOther := TStringList.Create; FastAssign(OtherReminders, TmpOther); end; procedure EndReminderUpdate(Force: boolean = FALSE); var DoNotify: boolean; begin DoNotify := Force; if(not DoNotify) then DoNotify := (not ActiveReminders.Equals(TmpActive)); KillObj(@TmpActive); if(not DoNotify) then DoNotify := (not OtherReminders.Equals(TmpOther)); KillObj(@TmpOther); OtherReminders.Notifier.EndUpdate; ActiveReminders.Notifier.EndUpdate(DoNotify); end; function GetRemFolders: TRemFolders; var i: TRemFolder; tmp: string; begin if rfUnknown in uRemFolders then begin tmp := GetReminderFolders; uRemFolders := []; for i := low(TValidRemFolders) to high(TValidRemFolders) do if(pos(RemFolderCodes[i], tmp) > 0) then include(uRemFolders, i); end; Result := uRemFolders; end; procedure SetRemFolders(const Value: TRemFolders); var i: TRemFolder; tmp: string; begin if(Value <> uRemFolders) then begin BeginReminderUpdate; try uRemFolders := Value; tmp := ''; for i := low(TValidRemFolders) to high(TValidRemFolders) do if(i in Value) then tmp := tmp + RemFolderCodes[i]; SetReminderFolders(tmp); finally EndReminderUpdate(TRUE); end; end; end; function ReminderEvaluated(Data: string; ForceUpdate: boolean = FALSE): boolean; var idx: integer; Code, Sts, Before: string; begin Result := ForceUpdate; if(Data <> '') then begin Code := Piece(Data, U, 1); if StrToIntDef(Code,0) > 0 then begin ActiveReminders.Notifier.BeginUpdate; try idx := EvaluatedReminders.IndexOfPiece(Code); if(idx < 0) then begin EvaluatedReminders.Add(Data); Result := TRUE; end else begin Before := Piece(EvaluatedReminders[idx], U, 6); EvaluatedReminders[idx] := Data; if(not Result) then Result := (Before <> Piece(Data, U, 6)); end; idx := ActiveReminders.IndexOfPiece(Code); if(idx < 0) then begin Sts := Piece(Data, U, 6); //if(Sts = '0') or (Sts = '1') then if(Sts = '0') or (Sts = '1') or (Sts = '3') or (Sts = '4') then //AGP Error change 26.8 begin Result := TRUE; ActiveReminders.Add(Data); end; end else begin if(not Result) then Result := (ActiveReminders[idx] <> Data); ActiveReminders[idx] := Data; end; idx := ProcessedReminders.IndexOfPiece(Code); if(idx >= 0) then ProcessedReminders.Delete(idx); finally ActiveReminders.Notifier.EndUpdate(Result); end; end else Result := TRUE; // If Code = 0 then it's 0^No Reminders Due, indicating a status change. end; end; procedure RemindersEvaluated(List: TStringList); var i: integer; DoUpdate, RemChanged: boolean; begin DoUpdate := FALSE; ActiveReminders.Notifier.BeginUpdate; try for i := 0 to List.Count-1 do begin RemChanged := ReminderEvaluated(List[i]); if(RemChanged) then DoUpdate := TRUE; end; finally ActiveReminders.Notifier.EndUpdate(DoUpdate); end; end; (* procedure CheckReminders; forward; procedure IdleCallEvaluateReminder(Msg: string); var i:integer; Code: string; begin Code := Piece(Msg,U,1); repeat i := ReminderCallList.IndexOfPiece(Code); if(i >= 0) then ReminderCallList.Delete(i); until(i < 0); ReminderEvaluated(EvaluateReminder(Msg), (ReminderCallList.Count = 0)); CheckReminders; end; procedure CheckReminders; var i:integer; begin for i := ReminderCallList.Count-1 downto 0 do if(EvaluatedReminders.IndexOfPiece(Piece(ReminderCallList[i], U, 1)) >= 0) then ReminderCallList.Delete(i); if(ReminderCallList.Count > 0) then CallRPCWhenIdle(IdleCallEvaluateReminder,ReminderCallList[0]) end; *) procedure CheckReminders; var RemList: TStringList; i: integer; Code: string; begin for i := ReminderCallList.Count-1 downto 0 do if(EvaluatedReminders.IndexOfPiece(Piece(ReminderCallList[i],U,1)) >= 0) then ReminderCallList.Delete(i); if(ReminderCallList.Count > 0) then begin RemList := TStringList.Create; try while (ReminderCallList.Count > 0) do begin Code := Piece(ReminderCallList[0],U,1); ReminderCallList.Delete(0); repeat i := ReminderCallList.IndexOfPiece(Code); if(i >= 0) then ReminderCallList.Delete(i); until(i < 0); RemList.Add(Code); end; if(RemList.Count > 0) then begin EvaluateReminders(RemList); FastAssign(RPCBrokerV.Results, RemList); for i := 0 to RemList.Count-1 do ReminderEvaluated(RemList[i], (i = (RemList.Count-1))); end; finally RemList.Free; end; end; end; procedure ResetReminderLoad; begin LastReminderLocation := -2; LoadReminderData; end; procedure LoadReminderData(ProcessingInBackground: boolean = FALSE); var i, idx: integer; RemID: string; TempList: TORStringList; begin if(RemindersStarted and (LastReminderLocation <> Encounter.Location)) then begin LastReminderLocation := Encounter.Location; BeginReminderUpdate; try GetCurrentReminders; TempList := TORStringList.Create; try if(RPCBrokerV.Results.Count > 0) then begin for i := 0 to RPCBrokerV.Results.Count-1 do begin RemID := RPCBrokerV.Results[i]; idx := EvaluatedReminders.IndexOfPiece(RemID); if(idx < 0) then begin TempList.Add(RemID); if(not ProcessingInBackground) then ReminderCallList.Add(RemID); end else TempList.Add(EvaluatedReminders[idx]); end; end; // FastAssign(TempList,ActiveReminders); for i := 0 to TempList.Count-1 do begin RemID := Piece(TempList[i],U,1); if(ActiveReminders.indexOfPiece(RemID) < 0) then ActiveReminders.Add(TempList[i]); end; finally TempList.Free; end; CheckReminders; GetOtherReminders(OtherReminders); finally EndReminderUpdate; end; end; end; { Supporting events for Reminder TreeViews } procedure GetImageIndex(AData: Pointer; Sender: TObject; Node: TTreeNode); var iidx, oidx: integer; Data, Tmp: string; begin if(Assigned(Node)) then begin oidx := -1; Data := (Node as TORTreeNode).StringData; if(copy(Piece(Data, U, 1),1,1) = CatCode) then begin if(Node.Expanded) then iidx := 1 else iidx := 0; end else begin Tmp := Piece(Data, U, 6); //if(Tmp = '1') then iidx := 2 if (Tmp = '3') or (Tmp = '4') or (Tmp = '1') then iidx :=2 //AGP ERROR CHANGE 26.8 else if(Tmp = '0') then iidx := 3 else begin if(EvaluatedReminders.IndexOfPiece(copy(Piece(Data, U, 1),2,MaxInt),U,1) < 0) then iidx := 5 else iidx := 4; end; if(Piece(Data,U,7) = '1') then begin Tmp := copy(Piece(Data, U, 1),2,99); if(ProcessedReminders.IndexOfPiece(Tmp,U,1) >=0) then oidx := 1 else oidx:= 0; end; end; Node.ImageIndex := iidx; Node.SelectedIndex := iidx; if(Node.OverlayIndex <> oidx) then begin Node.OverlayIndex := oidx; Node.TreeView.Invalidate; end; end; end; type TRemMenuCmd = (rmClinMaint, rmEdu, rmInq, rmWeb, rmDash, rmEval, rmDue, rmApplicable, rmNotApplicable, rmEvaluated, rmOther, rmLegend); TRemViewCmds = rmDue..rmOther; const RemMenuFolder: array[TRemViewCmds] of TRemFolder = { rmDue } (rfDue, { rmApplicable } rfApplicable, { rmNotApplicable } rfNotApplicable, { rmEvaluated } rfEvaluated, { rmOther } rfOther); RemMenuNames: array[TRemMenuCmd] of string = ( { rmClinMaint } ClinMaintText, { rmEdu } 'Education Topic Definition', { rmInq } 'Reminder Inquiry', { rmWeb } 'Reference Information', { rmDash } '-', { rmEval } 'Evaluate Reminder', { rmDue } DueText, { rmApplicable } ApplicableText, { rmNotApplicable } NotApplicableText, { rmEvaluated } EvaluatedText, { rmOther } OtherText, { rmLegend } 'Reminder Icon Legend'); EvalCatName = 'Evaluate Category Reminders'; function GetEducationTopics(EIEN: string): string; var i, idx: integer; Tmp, Data: string; begin if(not assigned(EducationTopics)) then EducationTopics := TORStringList.Create; idx := EducationTopics.IndexOfPiece(EIEN); if(idx < 0) then begin Tmp := copy(EIEN,1,1); idx := StrToIntDef(copy(EIEN,2,MaxInt),0); if(Tmp = RemCode) then GetEducationTopicsForReminder(idx) else if(Tmp = EduCode) then GetEducationSubtopics(idx) else RPCBrokerV.Results.Clear; Tmp := EIEN; if(RPCBrokerV.Results.Count > 0) then begin for i := 0 to RPCBrokerV.Results.Count-1 do begin Data := RPCBrokerV.Results[i]; Tmp := Tmp + U + Piece(Data, U, 1) + ';'; if(Piece(Data, U, 3) = '') then Tmp := Tmp + Piece(Data, U, 2) else Tmp := Tmp + Piece(Data, U, 3); end; end; idx := EducationTopics.Add(Tmp); end; Result := EducationTopics[idx]; idx := pos(U, Result); if(idx > 0) then Result := copy(Result,Idx+1,MaxInt) else Result := ''; end; function GetWebPageName(idx :integer): string; begin Result := Piece(WebPages[idx],U,2); end; function GetWebPageAddress(idx: integer): string; begin Result := Piece(WebPages[idx],U,3); end; function GetWebPages(EIEN: string): string; overload; var i, idx: integer; Tmp, Data, Title: string; RIEN: string; begin RIEN := RemCode + EIEN; if(not assigned(WebPages)) then WebPages := TORStringList.Create; idx := WebPages.IndexOfPiece(RIEN); if(idx < 0) then begin GetReminderWebPages(EIEN); Tmp := RIEN; if(RPCBrokerV.Results.Count > 0) then begin for i := 0 to RPCBrokerV.Results.Count-1 do begin Data := RPCBrokerV.Results[i]; if(Piece(Data,U,1) = '1') and (Piece(Data,U,3) <> '') then begin Data := U + Piece(Data,U,4) + U + Piece(Data,U,3); if(Piece(Data,U,2) = '') then begin Title := Piece(data,U,3); if(length(Title) > 60) then Title := copy(Title,1,57) + '...'; SetPiece(Data,U,2,Title); end; //if(copy(UpperCase(Piece(Data, U, 3)),1,7) <> 'HTTP://') then // SetPiece(Data, U, 3,'http://'+Piece(Data,U,3)); idx := WebPages.IndexOf(Data); if(idx < 0) then idx := WebPages.Add(Data); Tmp := Tmp + U + IntToStr(idx); end; end; end; idx := WebPages.Add(Tmp); end; Result := WebPages[idx]; idx := pos(U, Result); if(idx > 0) then Result := copy(Result,Idx+1,MaxInt) else Result := ''; end; function ReminderName(IEN: integer): string; var idx: integer; SIEN: string; begin SIEN := IntToStr(IEN); Result := ''; idx := EvaluatedReminders.IndexOfPiece(SIEN); if(idx >= 0) then Result := piece(EvaluatedReminders[idx],U,2); if(Result = '') then begin idx := ActiveReminders.IndexOfPiece(SIEN); if(idx >= 0) then Result := piece(ActiveReminders[idx],U,2); end; if(Result = '') then begin idx := OtherReminders.IndexOfPiece(SIEN, U, 5); if(idx >= 0) then Result := piece(OtherReminders[idx],U,3); end; if(Result = '') then begin idx := RemindersInProcess.IndexOfPiece(SIEN); if(idx >= 0) then Result := TReminder(RemindersInProcess.Objects[idx]).PrintName; end; end; procedure ReminderClinMaintClicked(AData: pointer; Sender: TObject); var ien: integer; begin ien := (Sender as TMenuItem).Tag; if(ien > 0) then ReportBox(DetailReminder(ien), RemMenuNames[rmClinMaint] + ': '+ ReminderName(ien), TRUE); end; procedure ReminderEduClicked(AData: pointer; Sender: TObject); var ien: integer; begin ien := (Sender as TMenuItem).Tag; if(ien > 0) then ReportBox(EducationTopicDetail(ien), 'Education Topic: ' + (Sender as TMenuItem).Caption, TRUE); end; procedure ReminderInqClicked(AData: pointer; Sender: TObject); var ien: integer; begin ien := (Sender as TMenuItem).Tag; if(ien > 0) then ReportBox(ReminderInquiry(ien), 'Reminder Inquiry: '+ ReminderName(ien), TRUE); end; procedure ReminderWebClicked(AData: pointer; Sender: TObject); var idx: integer; begin idx := (Sender as TMenuItem).Tag-1; if(idx >= 0) then GotoWebPage(GetWebPageAddress(idx)); end; procedure EvalReminder(ien: integer); var Msg, RName: string; NewStatus: string; begin if(ien > 0) then begin NewStatus := EvaluateReminder(IntToStr(ien)); ReminderEvaluated(NewStatus); NewStatus := piece(NewStatus,U,6); RName := ReminderName(ien); if(RName = '') then RName := 'Reminder'; if(NewStatus = '1') then Msg := 'Due' else if(NewStatus = '0') then Msg := 'Applicable' else if(NewStatus = '3') then Msg := 'Error' //AGP Error code change 26.8 else if (NewStatus = '4') then Msg := 'CNBD' //AGP Error code change 26.8 else Msg := 'Not Applicable'; Msg := RName + ' is ' + Msg + '.'; InfoBox(Msg, RName + ' Evaluation', MB_OK); end; end; procedure EvalProcessed; var i: integer; begin if(ProcessedReminders.Count > 0) then begin BeginReminderUpdate; try while(ProcessedReminders.Count > 0) do begin if(ReminderCallList.IndexOf(ProcessedReminders[0]) < 0) then ReminderCallList.Add(ProcessedReminders[0]); repeat i := EvaluatedReminders.IndexOfPiece(Piece(ProcessedReminders[0],U,1)); if(i >= 0) then EvaluatedReminders.Delete(i); until(i < 0); ProcessedReminders.Delete(0); end; CheckReminders; finally EndReminderUpdate(TRUE); end; end; end; procedure ReminderEvalClicked(AData: pointer; Sender: TObject); begin EvalReminder((Sender as TMenuItem).Tag); end; procedure ReminderViewFolderClicked(AData: pointer; Sender: TObject); var rfldrs: TRemFolders; rfldr: TRemFolder; begin rfldrs := GetRemFolders; rfldr := TRemFolder((Sender as TMenuItem).Tag); if rfldr in rfldrs then exclude(rfldrs, rfldr) else include(rfldrs, rfldr); SetRemFolders(rfldrs); end; procedure EvaluateCategoryClicked(AData: pointer; Sender: TObject); var Node: TORTreeNode; Code: string; i: integer; begin if(Sender is TMenuItem) then begin BeginReminderUpdate; try Node := TORTreeNode(TORTreeNode(TMenuItem(Sender).Tag).GetFirstChild); while assigned(Node) do begin Code := Piece(Node.StringData,U,1); if(copy(Code,1,1) = RemCode) then begin Code := copy(Code,2,MaxInt); if(ReminderCallList.IndexOf(Code) < 0) then ReminderCallList.Add(copy(Node.StringData,2,MaxInt)); repeat i := EvaluatedReminders.IndexOfPiece(Code); if(i >= 0) then EvaluatedReminders.Delete(i); until(i < 0); end; Node := TORTreeNode(Node.GetNextSibling); end; CheckReminders; finally EndReminderUpdate(TRUE); end; end; end; procedure ReminderIconLegendClicked(AData: pointer; Sender: TObject); begin ShowIconLegend(ilReminders); end; procedure ReminderMenuBuilder(MI: TMenuItem; RemStr: string; IncludeActions, IncludeEval, ViewFolders: boolean); var M: TMethod; Tmp: string; Cnt: integer; RemID: integer; cmd: TRemMenuCmd; function Add(Text: string; Parent: TMenuItem; Tag: integer; Typ: TRemMenuCmd): TORMenuItem; var InsertMenu: boolean; idx: integer; begin Result := nil; InsertMenu := TRUE; if(Parent = MI) then begin if(MI.Count > Cnt) then begin Result := TORMenuItem(MI.Items[Cnt]); Result.Enabled := TRUE; Result.Visible := TRUE; Result.ImageIndex := -1; while Result.Count > 0 do Result.Delete(Result.Count-1); InsertMenu := FALSE; end; inc(Cnt); end; if(not assigned(Result)) then Result := TORMenuItem.Create(MI); if(Text = '') then Result.Caption := RemMenuNames[Typ] else Result.Caption := Text; Result.Tag := Tag; Result.Data := RemStr; if(Tag <> 0) then begin case Typ of rmClinMaint: M.Code := @ReminderClinMaintClicked; rmEdu: M.Code := @ReminderEduClicked; rmInq: M.Code := @ReminderInqClicked; rmWeb: M.Code := @ReminderWebClicked; rmEval: M.Code := @ReminderEvalClicked; rmDue..rmOther: begin M.Code := @ReminderViewFolderClicked; case Typ of rmDue: idx := 0; rmApplicable: idx := 2; rmNotApplicable: idx := 4; rmEvaluated: idx := 6; rmOther: idx := 8; else idx := -1; end; if(idx >= 0) and (RemMenuFolder[Typ] in GetRemFolders) then inc(idx); Result.ImageIndex := idx; end; rmLegend: M.Code := @ReminderIconLegendClicked; else M.Code := nil; end; if(assigned(M.Code)) then Result.OnClick := TNotifyEvent(M) else Result.OnClick := nil; end; if(InsertMenu) then Parent.Add(Result); end; procedure AddEducationTopics(Item: TMenuItem; EduStr: string); var i, j: integer; Code: String; NewEduStr: string; itm: TMenuItem; begin if(EduStr <> '') then begin repeat i := pos(';', EduStr); j := pos(U, EduStr); if(j = 0) then j := length(EduStr)+1; Code := copy(EduStr,1,i-1); //AddEducationTopics(Add(copy(EduStr,i+1,j-i-1), Item, StrToIntDef(Code, 0), rmEdu), // GetEducationTopics(EduCode + Code)); NewEduStr := GetEducationTopics(EduCode + Code); if(NewEduStr = '') then Add(copy(EduStr,i+1,j-i-1), Item, StrToIntDef(Code, 0), rmEdu) else begin itm := Add(copy(EduStr,i+1,j-i-1), Item, 0, rmEdu); Add(copy(EduStr,i+1,j-i-1), itm, StrToIntDef(Code, 0), rmEdu); Add('', Itm, 0, rmDash); AddEducationTopics(itm, NewEduStr); end; delete(EduStr,1,j); until(EduStr = ''); end; end; procedure AddWebPages(Item: TMenuItem; WebStr: string); var i, idx: integer; begin if(WebStr <> '') then begin repeat i := pos(U, WebStr); if(i = 0) then i := length(WebStr)+1; idx := StrToIntDef(copy(WebStr,1,i-1),-1); if(idx >= 0) then Add(GetWebPageName(idx), Item, idx+1, rmWeb); delete(WebStr,1,i); until(WebStr = ''); end; end; begin RemID := StrToIntDef(copy(Piece(RemStr,U,1),2,MaxInt),0); Cnt := 0; M.Data := nil; if(RemID > 0) then begin Add('', MI, RemID, rmClinMaint); Tmp := GetEducationTopics(RemCode + IntToStr(RemID)); if(Tmp <> '') then AddEducationTopics(Add('', MI, 0, rmEdu), Tmp) else Add('', MI, 0, rmEdu).Enabled := FALSE; Add('', MI, RemID, rmInq); Tmp := GetWebPages(IntToStr(RemID)); if(Tmp <> '') then AddWebPages(Add('', MI, 0, rmWeb), Tmp) else Add('', MI, 0, rmWeb).Enabled := FALSE; if(IncludeActions or IncludeEval) then begin Add('', MI, 0, rmDash); Add('', MI, RemID, rmEval); end; end; if(ViewFolders) then begin Add('', MI, 0, rmDash); for cmd := low(TRemViewCmds) to high(TRemViewCmds) do Add('', MI, ord(RemMenuFolder[cmd]), cmd); end; Add('', MI, 0, rmDash); Add('', MI, 1, rmLegend); while MI.Count > Cnt do MI.Delete(MI.Count-1); end; procedure ReminderTreePopup(AData: pointer; Sender: TObject); begin ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu).Data, TRUE, FALSE, FALSE); end; procedure ReminderTreePopupCover(AData: pointer; Sender: TObject); begin ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu).Data, FALSE, FALSE, FALSE); end; procedure ReminderTreePopupDlg(AData: pointer; Sender: TObject); begin ReminderMenuBuilder((Sender as TPopupMenu).Items, (Sender as TORPopupMenu).Data, FALSE, TRUE, FALSE); end; procedure ReminderMenuItemSelect(AData: pointer; Sender: TObject); begin ReminderMenuBuilder((Sender as TMenuItem), (Sender as TORMenuItem).Data, FALSE, FALSE, TRUE); end; procedure SetReminderPopupRoutine(Menu: TPopupMenu); var M: TMethod; begin M.Code := @ReminderTreePopup; M.Data := nil; Menu.OnPopup := TNotifyEvent(M); end; procedure SetReminderPopupCoverRoutine(Menu: TPopupMenu); var M: TMethod; begin M.Code := @ReminderTreePopupCover; M.Data := nil; Menu.OnPopup := TNotifyEvent(M); end; procedure SetReminderPopupDlgRoutine(Menu: TPopupMenu); var M: TMethod; begin M.Code := @ReminderTreePopupDlg; M.Data := nil; Menu.OnPopup := TNotifyEvent(M); end; procedure SetReminderMenuSelectRoutine(Menu: TMenuItem); var M: TMethod; begin M.Code := @ReminderMenuItemSelect; M.Data := nil; Menu.OnClick := TNotifyEvent(M); end; function ReminderMenu(Sender: TComponent): TORPopupMenu; begin if(Sender.Tag = RemTreeCode) then begin if(not assigned(ReminderTreeMenuDlg)) then begin ReminderTreeMenuDlg := TORPopupMenu.Create(nil); SetReminderPopupDlgRoutine(ReminderTreeMenuDlg) end; Result := ReminderTreeMenuDlg; end else begin if(not assigned(ReminderTreeMenu)) then begin ReminderTreeMenu := TORPopupMenu.Create(nil); SetReminderPopupRoutine(ReminderTreeMenu); end; Result := ReminderTreeMenu; end; end; procedure RemContextPopup(AData: Pointer; Sender: TObject; MousePos: TPoint; var Handled: Boolean); var Menu: TORPopupMenu; MItem: TMenuItem; M: TMethod; p1: string; UpdateMenu: boolean; begin UpdateMenu := TRUE; Menu := nil; with (Sender as TORTreeView) do begin if((htOnItem in GetHitTestInfoAt(MousePos.X, MousePos.Y)) and (assigned(Selected))) then begin p1 := Piece((Selected as TORTreeNode).StringData, U, 1); if(Copy(p1,1,1) = RemCode) then begin Menu := ReminderMenu(TComponent(Sender)); Menu.Data := TORTreeNode(Selected).StringData; end else if(Copy(p1,1,1) = CatCode) and (p1 <> OtherCatID) and (Selected.HasChildren) then begin if(not assigned(ReminderCatMenu)) then begin ReminderCatMenu := TPopupMenu.Create(nil); MItem := TMenuItem.Create(ReminderCatMenu); MItem.Caption := EvalCatName; M.Data := nil; M.Code := @EvaluateCategoryClicked; MItem.OnClick := TNotifyEvent(M); ReminderCatMenu.Items.Add(MItem); end else MItem := ReminderCatMenu.Items[0]; PopupMenu := ReminderCatMenu; MItem.Tag := Integer(TORTreeNode(Selected)); UpdateMenu := FALSE; end; end; if UpdateMenu then PopupMenu := Menu; Selected := Selected; // This strange line Keeps item selected after a right click if(not assigned(PopupMenu)) then Handled := TRUE; end; end; { StringData of the TORTreeNodes will be in the format: 1 2 3 4 5 6 7 TYPE + IEN^PRINT NAME^DUE DATE/TIME^LAST OCCURENCE DATE/TIME^PRIORITY^DUE^DIALOG 8 9 10 Formated Due Date^Formated Last Occurence Date^InitialAbsoluteIdx where TYPE C=Category, R=Reminder PRIORITY 1=High, 2=Normal, 3=Low DUE 0=Applicable, 1=Due, 2=Not Applicable DIALOG 1=Active Dialog Exists } procedure BuildReminderTree(Tree: TORTreeView); var ExpandedStr: string; TopID1, TopID2: string; SelID1, SelID2: string; i, j: integer; NeedLost: boolean; Tmp, Data, LostCat, Code: string; Node: TORTreeNode; M: TMethod; Rem: TReminder; OpenDue, Found: boolean; function Add2Tree(Folder: TRemFolder; CatID: string; Node: TORTreeNode = nil): TORTreeNode; begin if (Folder = rfUnknown) or (Folder in GetRemFolders) then begin if(CatID = LostCatID) then begin if(NeedLost) then begin (Tree.Items.AddFirst(nil,'') as TORTreeNode).StringData := LostCatString; NeedLost := FALSE; end; end; if(not assigned(Node)) then Node := Tree.FindPieceNode(CatID, 1); if(assigned(Node)) then begin Result := (Tree.Items.AddChild(Node,'') as TORTreeNode); Result.StringData := Data; end else Result := nil; end else Result := nil; end; begin if(not assigned(Tree)) then exit; Tree.Items.BeginUpdate; try Tree.NodeDelim := U; Tree.NodePiece := 2; M.Code := @GetImageIndex; M.Data := nil; Tree.OnGetImageIndex := TTVExpandedEvent(M); Tree.OnGetSelectedIndex := TTVExpandedEvent(M); M.Code := @RemContextPopup; Tree.OnContextPopup := TContextPopupEvent(M); if(assigned(Tree.TopItem)) then begin TopID1 := Tree.GetNodeID(TORTreeNode(Tree.TopItem), 1, IncludeParentID); TopID2 := Tree.GetNodeID(TORTreeNode(Tree.TopItem), 1); end else TopID1 := U; if(assigned(Tree.Selected)) then begin SelID1 := Tree.GetNodeID(TORTreeNode(Tree.Selected), 1, IncludeParentID); SelID2 := Tree.GetNodeID(TORTreeNode(Tree.Selected), 1); end else SelID1 := U; ExpandedStr := Tree.GetExpandedIDStr(1, IncludeParentID); OpenDue := (ExpandedStr = ''); Tree.Items.Clear; NeedLost := TRUE; if(rfDue in GetRemFolders) then (Tree.Items.Add(nil,'') as TORTreeNode).StringData := DueCatString; if(rfApplicable in GetRemFolders) then (Tree.Items.Add(nil,'') as TORTreeNode).StringData := ApplCatString; if(rfNotApplicable in GetRemFolders) then (Tree.Items.Add(nil,'') as TORTreeNode).StringData := NotApplCatString; if(rfEvaluated in GetRemFolders) then (Tree.Items.Add(nil,'') as TORTreeNode).StringData := EvaluatedCatString; if(rfOther in GetRemFolders) then (Tree.Items.Add(nil,'') as TORTreeNode).StringData := OtherCatString; for i := 0 to EvaluatedReminders.Count-1 do begin Data := RemCode + EvaluatedReminders[i]; Tmp := Piece(Data,U,6); // if(Tmp = '1') then Add2Tree(rfDue, DueCatID) if(Tmp = '1') or (Tmp = '3') or (Tmp = '4') then Add2Tree(rfDue, DueCatID) //AGP Error code change 26.8 else if(Tmp = '0') then Add2Tree(rfApplicable, ApplCatID) else Add2Tree(rfNotApplicable, NotApplCatID); Add2Tree(rfEvaluated, EvaluatedCatID); end; if(rfOther in GetRemFolders) and (OtherReminders.Count > 0) then begin for i := 0 to OtherReminders.Count-1 do begin Tmp := OtherReminders[i]; if(Piece(Tmp, U, 2) = CatCode) then Data := CatCode + Piece(Tmp, U, 1) else begin Code := Piece(Tmp, U, 5); Data := RemCode + Code; Node := Tree.FindPieceNode(Data, 1); if(assigned(Node)) then Data := Node.StringData else begin j := EvaluatedReminders.IndexOfPiece(Code); if(j >= 0) then SetPiece(Data, U, 6, Piece(EvaluatedReminders[j], U, 6)); end; end; SetPiece(Data, U, 2, Piece(Tmp, U ,3)); SetPiece(Data, U, 7, Piece(Tmp, U, 6)); Tmp := CatCode + Piece(Tmp, U, 4); Add2Tree(rfOther, OtherCatID, Tree.FindPieceNode(Tmp, 1)); end; end; { The Lost category is for reminders being processed that are no longer in the reminder tree view. This can happen with reminders that were Due or Applicable, but due to user action are no longer applicable, or due to location changes. The Lost category will not be used if a lost reminder is in the other list. } if(RemindersInProcess.Count > 0) then begin for i := 0 to RemindersInProcess.Count-1 do begin Rem := TReminder(RemindersInProcess.Objects[i]); Tmp := RemCode + Rem.IEN; Found := FALSE; Node := nil; repeat Node := Tree.FindPieceNode(Tmp, 1, #0, Node); // look in the tree first if((not Found) and (not assigned(Node))) then begin Data := Tmp + U + Rem.PrintName + U + Rem.DueDateStr + U + Rem.LastDateStr + U + IntToStr(Rem.Priority) + U + Rem.Status; if(Rem.Status = '1') then LostCat := DueCatID else if(Rem.Status = '0') then LostCat := ApplCatID else LostCat := LostCatID; Node := Add2Tree(rfUnknown, LostCat); end; if(assigned(Node)) then begin Node.Bold := Rem.Processing; Found := TRUE; end; until(Found and (not assigned(Node))); end; end; for i := 0 to Tree.Items.Count-1 do begin Node := TORTreeNode(Tree.Items[i]); for j := 3 to 4 do begin Tmp := Piece(Node.StringData, U, j); if(Tmp = '') then Data := '' else Data := FormatFMDateTimeStr(ReminderDateFormat, Tmp); Node.SetPiece(j + (RemTreeDateIdx - 3), Data); end; Node.SetPiece(RemTreeDateIdx + 2, IntToStr(Node.AbsoluteIndex)); Tmp := Piece(Node.StringData, U, 5); if(Tmp <> '1') and (Tmp <> '3') then Node.SetPiece(5, '2'); end; finally Tree.Items.EndUpdate; end; if(SelID1 = U) then Node := nil else begin Node := Tree.FindPieceNode(SelID1, 1, IncludeParentID); if(not assigned(Node)) then Node := Tree.FindPieceNode(SelID2, 1); if(assigned(Node)) then Node.EnsureVisible; end; Tree.Selected := Node; Tree.SetExpandedIDStr(1, IncludeParentID, ExpandedStr); if(OpenDue) then begin Node := Tree.FindPieceNode(DueCatID, 1); if(assigned(Node)) then Node.Expand(FALSE); end; if(TopID1 = U) then Tree.TopItem := Tree.Items.GetFirstNode else begin Tree.TopItem := Tree.FindPieceNode(TopID1, 1, IncludeParentID); if(not assigned(Tree.TopItem)) then Tree.TopItem := Tree.FindPieceNode(TopID2, 1); end; end; function ReminderNode(Node: TTreeNode): TORTreeNode; var p1: string; begin Result := nil; if(assigned(Node)) then begin p1 := Piece((Node as TORTreeNode).StringData, U, 1); if(Copy(p1,1,1) = RemCode) then Result := (Node as TORTreeNode) end; end; procedure LocationChanged(Sender: TObject); begin LoadReminderData; end; procedure ClearReminderData; var Changed: boolean; begin if(assigned(frmReminderTree)) then frmReminderTree.Free; Changed := ((ActiveReminders.Count > 0) or (OtherReminders.Count > 0) or (ProcessingChangeString <> U)); ActiveReminders.Notifier.BeginUpdate; OtherReminders.Notifier.BeginUpdate; RemindersInProcess.Notifier.BeginUpdate; try ProcessedReminders.Clear; if(assigned(KillReminderDialogProc)) then KillReminderDialogProc(nil); ActiveReminders.Clear; OtherReminders.Clear; EvaluatedReminders.Clear; ReminderCallList.Clear; RemindersInProcess.KillObjects; RemindersInProcess.Clear; LastProcessingList := ''; InitialRemindersLoaded := FALSE; CoverSheetRemindersInBackground := FALSE; finally RemindersInProcess.Notifier.EndUpdate; OtherReminders.Notifier.EndUpdate; ActiveReminders.Notifier.EndUpdate(Changed); RemindersStarted := FALSE; LastReminderLocation := -2; RemForm.Form := nil; end; end; procedure RemindersInProcessChanged(Data: Pointer; Sender: TObject; var CanNotify: boolean); var CurProcessing: string; begin CurProcessing := ProcessingChangeString; CanNotify := (LastProcessingList <> CurProcessing); if(CanNotify) then LastProcessingList := CurProcessing; end; procedure InitReminderObjects; var M: TMethod; procedure InitReminderList(var List: TORStringList); begin if(not assigned(List)) then List := TORStringList.Create; end; begin InitReminderList(ActiveReminders); InitReminderList(OtherReminders); InitReminderList(EvaluatedReminders); InitReminderList(ReminderCallList); InitReminderList(RemindersInProcess); InitReminderList(ProcessedReminders); M.Code := @RemindersInProcessChanged; M.Data := nil; RemindersInProcess.Notifier.OnNotify := TCanNotifyEvent(M); AddToNotifyWhenCreated(LocationChanged, TEncounter); RemForm.Form := nil; end; procedure FreeReminderObjects; begin KillObj(@ActiveReminders); KillObj(@OtherReminders); KillObj(@EvaluatedReminders); KillObj(@ReminderTreeMenuDlg); KillObj(@ReminderTreeMenu); KillObj(@ReminderCatMenu); KillObj(@EducationTopics); KillObj(@WebPages); KillObj(@ReminderCallList); KillObj(@TmpActive); KillObj(@TmpOther); KillObj(@RemindersInProcess, TRUE); KillObj(@ReminderDialogInfo, TRUE); KillObj(@PCERootList, TRUE); KillObj(@ProcessedReminders); end; function GetReminder(ARemData: string): TReminder; var idx: integer; SIEN: string; begin Result := nil; SIEN := Piece(ARemData, U, 1); if(Copy(SIEN,1,1) = RemCode) then begin SIEN := copy(Sien, 2, MaxInt); idx := RemindersInProcess.IndexOf(SIEN); if(idx < 0) then begin RemindersInProcess.Notifier.BeginUpdate; try idx := RemindersInProcess.AddObject(SIEN, TReminder.Create(ARemData)); finally RemindersInProcess.Notifier.EndUpdate; end; end; Result := TReminder(RemindersInProcess.Objects[idx]); end; end; var ScootOver: integer = 0; procedure WordWrap(AText: string; Output: TStrings; LineLength: integer; AutoIndent: integer = 4; MHTest: boolean = false); var i, j, l, max, FCount, MHLoop: integer; First, MHRes: boolean; OrgText, Text, Prefix, tmpText: string; begin StripScreenReaderCodes(AText); inc(LineLength, ScootOver); dec(AutoIndent, ScootOver); FCount := Output.Count; First := TRUE; MHLoop := 1; MHRes := False; tmpText := ''; if (MHTest = True) and (Pos('~', AText)>0) then MHLoop := 2; for j := 1 to MHLoop do begin if (j = 1) and (MHLoop = 2) then begin tmpText := Piece(AText, '~', 1); MHRes := True; end else if (j = 2) then begin tmpText := Piece(AText, '~', 2); First := False; MHRes := False; end else if (j = 1) and (MHLoop = 1) then begin tmpText := AText; First := False; MHRes := False; end; if tmpText <> '' then OrgText := tmpText else OrgText := InitText(AText); Prefix := StringOfChar(' ',74-LineLength); repeat i := pos(CRCode, OrgText); if(i = 0) then begin Text := OrgText; OrgText := ''; end else begin Text := copy(OrgText, 1, i - 1); delete(OrgText, 1, i + CRCodeLen - 1); end; if(Text = '') and (OrgText <> '') then begin Output.Add(''); inc(FCount); end; while(Text <> '') do begin max := length(Text); if(max > LineLength) then begin l := LineLength + 1; while(l > 0) and (Text[l] <> ' ') do dec(l); if(l < 1) then begin Output.Add(Prefix+copy(Text,1,LineLength)); delete(Text,1,LineLength); end else begin Output.Add(Prefix+copy(Text,1,l-1)); while(l <= max) and (Text[l] = ' ') do inc(l); delete(Text,1,l-1); end; if(First) then begin dec(LineLength, AutoIndent); Prefix := Prefix + StringOfChar(' ', AutoIndent); First := FALSE; end; end else begin Output.Add(Prefix+Text); Text := ''; end; end; if ((First) and (FCount <> Output.Count)) and (MHRes = False) then begin dec(LineLength, AutoIndent); Prefix := Prefix + StringOfChar(' ', AutoIndent); First := FALSE; end; until(OrgText = ''); end; end; function InteractiveRemindersActive: boolean; begin if(not InteractiveRemindersActiveChecked) then begin InteractiveRemindersActiveStatus := GetRemindersActive; InteractiveRemindersActiveChecked := TRUE; end; Result := InteractiveRemindersActiveStatus; end; function GetReminderData(Rem: TReminderDialog; Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; begin Result := Rem.AddData(Lst, Finishing, Historical); end; function GetReminderData(Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; var i: integer; begin Result := 0; for i := 0 to RemindersInProcess.Count-1 do inc(Result, TReminder(RemindersInProcess.Objects[i]).AddData(Lst, Finishing, Historical)); end; procedure SetReminderFormBounds(Frm: TForm; DefX, DefY, DefW, DefH, ALeft, ATop, AWidth, AHeight: integer); var Rect: TRect; ScreenW, ScreenH: integer; begin SystemParametersInfo(SPI_GETWORKAREA, 0, @Rect, 0); ScreenW := Rect.Right - Rect.Left + 1; ScreenH := Rect.Bottom - Rect.Top + 1; if(AWidth = 0) then AWidth := DefW else DefW := AWidth; if(AHeight = 0) then AHeight := DefH else DefH := AHeight; if(DefX = 0) and (DefY = 0) then begin DefX := (ScreenW - DefW) div 2; DefY := (ScreenH - DefH) div 2; end else dec(DefY, DefH); if((ALeft <= 0) or (ATop <= 0) or ((ALeft + AWidth) > ScreenW) or ((ATop + AHeight) > ScreenH)) then begin if(DefX < 0) then DefX := 0 else if((DefX + DefW) > ScreenW) then DefX := ScreenW-DefW; if(DefY < 0) then DefY := 0 else if((DefY + DefH) > ScreenH) then DefY := ScreenH-DefH; Frm.SetBounds(Rect.Left + DefX, Rect.Top + DefY, DefW, DefH); end else Frm.SetBounds(Rect.Left + ALeft, Rect.Top + ATop, AWidth, AHeight); end; procedure UpdateReminderDialogStatus; var TmpSL: TStringList; Changed: boolean; procedure Build(AList :TORStringList; PNum: integer); var i: integer; Code: string; begin for i := 0 to AList.Count-1 do begin Code := Piece(AList[i],U,PNum); if((Code <> '') and (TmpSL.IndexOf(Code) < 0)) then TmpSL.Add(Code); end; end; procedure Reset(AList: TORStringList; PNum, DlgPNum: integer); var i, j: integer; Tmp, Code, Dlg: string; begin for i := 0 to TmpSL.Count-1 do begin Code := Piece(TmpSL[i],U,1); j := -1; repeat j := AList.IndexOfPiece(Code, U, PNum, j); if(j >= 0) then begin Dlg := Piece(TmpSL[i],U,2); if(Dlg <> Piece(AList[j], U, DlgPNum)) then begin Tmp := AList[j]; SetPiece(Tmp, U, DlgPNum, Dlg); AList[j] := Tmp; Changed := TRUE; end; end; until (j < 0); end; end; begin Changed := FALSE; BeginReminderUpdate; try TmpSL := TStringList.Create; try Build(ActiveReminders, 1); Build(OtherReminders, 5); Build(EvaluatedReminders, 1); GetDialogStatus(TmpSL); Reset(ActiveReminders, 1, 7); Reset(OtherReminders, 5, 6); Reset(EvaluatedReminders, 1, 7); finally TmpSL.Free; end; finally EndReminderUpdate(Changed); end; end; procedure PrepText4NextLine(var txt: string); var tlen: integer; begin if(txt <> '') then begin tlen := length(txt); if(copy(txt, tlen - CRCodeLen + 1, CRCodeLen) = CRCode) then exit; if(copy(txt, tlen, 1) = '.') then txt := txt + ' '; txt := txt + ' '; end; end; procedure ExpandTIUObjects(var Txt: string; msg: string = ''); var ObjList: TStringList; Err: TStringList; i, j, k, oLen: integer; obj, ObjTxt: string; begin ObjList := TStringList.Create; try Err := nil; if(not dmodShared.BoilerplateOK(Txt, CRCode, ObjList, Err)) and (assigned(Err)) then begin try Err.Add(CRLF + 'Contact IRM and inform them about this error.' + CRLF + 'Make sure you give them the name of the reminder that you are processing,' + CRLF + 'and which dialog elements were selected to produce this error.'); InfoBox(Err.Text,'Reminder Boilerplate Object Error', MB_OK + MB_ICONERROR); finally Err.Free; end; end; if(ObjList.Count > 0) then begin GetTemplateText(ObjList); i := 0; while (i < ObjList.Count) do begin if(pos(ObjMarker, ObjList[i]) = 1) then begin obj := copy(ObjList[i], ObjMarkerLen+1, MaxInt); if(obj = '') then break; j := i + 1; while (j < ObjList.Count) and (pos(ObjMarker, ObjList[j]) = 0) do inc(j); if((j - i) > 2) then begin ObjTxt := ''; for k := i+1 to j-1 do ObjTxt := ObjTxt + CRCode + ObjList[k]; end else ObjTxt := ObjList[i+1]; i := j; obj := '|' + obj + '|'; oLen := length(obj); repeat j := pos(obj, Txt); if(j > 0) then begin delete(Txt, j, OLen); insert(ObjTxt, Txt, j); end; until(j = 0); end else inc(i); end end; finally ObjList.Free; end; end; { TReminderDialog } const RPCCalled = '99'; DlgCalled = RPCCalled + U + 'DLG'; constructor TReminderDialog.BaseCreate; var idx, eidx, i: integer; TempSL: TORStringList; ParentID: string; // Line: string; Element: TRemDlgElement; begin TempSL := GetDlgSL; if Piece(TempSL[0],U,2)='1' then begin Self.RemWipe := 1; end; idx := -1; repeat idx := TempSL.IndexOfPiece('1', U, 1, idx); if(idx >= 0) then begin if(not assigned(FElements)) then FElements := TStringList.Create; eidx := FElements.AddObject('',TRemDlgElement.Create); Element := TRemDlgElement(FElements.Objects[eidx]); with Element do begin FReminder := Self; FRec1 := TempSL[idx]; FID := Piece(FRec1, U, 2); FDlgID := Piece(FRec1, U, 3); FElements[eidx] := FDlgID; if(ElemType = etTaxonomy) then FTaxID := BOOLCHAR[Historical] + FindingType else FTaxID := ''; FText := ''; i := -1; // if Piece(FRec1,U,5) <> '1' then repeat i := TempSL.IndexOfPieces(['2',FID,FDlgID],i); if(i >= 0) then begin PrepText4NextLine(FText); FText := FText + Trim(Piece(TempSL[i], U, 4)); end; until(i < 0); ExpandTIUObjects(FText); AssignFieldIDs(FText); if(pos('.',FDlgID)>0) then begin ParentID := FDlgID; i := length(ParentID); while((i > 0) and (ParentID[i] <> '.')) do dec(i); if(i > 0) then begin ParentID := copy(ParentID,1,i-1); i := FElements.IndexOf(ParentID); if(i >= 0) then begin FParent := TRemDlgElement(FElements.Objects[i]); if(not assigned(FParent.FChildren)) then FParent.FChildren := TList.Create; FParent.FChildren.Add(Element); end; end; end; if(ElemType = etDisplayOnly) then SetChecked(TRUE); UpdateData; end; end; until(idx < 0); end; constructor TReminderDialog.Create(ADlgData: string); begin FDlgData := ADlgData; BaseCreate; end; destructor TReminderDialog.Destroy; begin KillObj(@FElements, TRUE); inherited; end; function TReminderDialog.Processing: boolean; var i,j: integer; Elem: TRemDlgElement; RData: TRemData; function ChildrenChecked(Prnt: TRemDlgElement): boolean; forward; function CheckItem(Item: TRemDlgElement): boolean; begin if(Item.ElemType = etDisplayOnly) then begin Result := ChildrenChecked(Item); if(not Result) then Result := Item.Add2PN; end else Result := Item.FChecked; end; function ChildrenChecked(Prnt: TRemDlgElement): boolean; var i: integer; begin Result := FALSE; if(assigned(Prnt.FChildren)) then begin for i := 0 to Prnt.FChildren.Count-1 do begin Result := CheckItem(TRemDlgElement(Prnt.FChildren[i])); if(Result) then break; end; end; end; begin Result := FALSE; if(assigned(FElements)) then begin for i := 0 to FElements.Count-1 do begin Elem := TRemDlgElement(FElements.Objects[i]); if(not assigned(Elem.FParent)) then begin Result := CheckItem(Elem); if (Result = false) then //(AGP CHANGE 24.9 add check to have the finish problem check for MH test) begin if (assigned(Elem.FData)) then begin for j := 0 to Elem.FData.Count-1 do begin RData := TRemData(Elem.FData[j]); if piece(RData.FRec3,U,4)='MH' then Result := True; if (Result) then break; end; end; end; if(Result) then break; end; end; end; end; function TReminderDialog.GetDlgSL: TORStringList; var idx: integer; begin if(not assigned(ReminderDialogInfo)) then ReminderDialogInfo := TStringList.Create; idx := ReminderDialogInfo.IndexOf(GetIEN); if(idx < 0) then idx := ReminderDialogInfo.AddObject(GetIEN, TORStringList.Create); Result := TORStringList(ReminderDialogInfo.Objects[idx]); if(Result.Count = 0) then begin FastAssign(GetDialogInfo(GetIEN, (Self is TReminder)), Result); Result.Add(DlgCalled); // Used to prevent repeated calling of RPC if dialog is empty end; end; function TReminderDialog.BuildControls(ParentWidth: integer; AParent, AOwner: TWinControl): TWinControl; var Y, i: integer; Elem: TRemDlgElement; ERes: TWinControl; begin Result := nil; if(assigned(FElements)) then begin Y := 0; for i := 0 to FElements.Count-1 do begin Elem := TRemDlgElement(FElements.Objects[i]); if (not assigned(Elem.FParent)) then begin ERes := Elem.BuildControls(Y, ParentWidth, AParent, AOwner); if(not assigned(Result)) then Result := ERes; end; end; end; if(AParent.ControlCount = 0) then begin with TVA508StaticText.Create(AOwner) do begin Parent := AParent; Caption := 'No Dialog found for ' + Trim(GetPrintName) + ' Reminder.'; Left := Gap; Top := Gap; end; end; ElementChecked := nil; end; procedure TReminderDialog.AddText(Lst: TStrings); var i, idx: integer; Elem: TRemDlgElement; temp: string; begin if(assigned(FElements)) then begin idx := Lst.Count; for i := 0 to FElements.Count-1 do begin Elem := TRemDlgElement(FElements.Objects[i]); if (not assigned(Elem.FParent)) then Elem.AddText(Lst); end; if (Self is TReminder) and (PrintName <> '') and (idx <> Lst.Count) then begin temp := PrintName; StripScreenReaderCodes(temp); Lst.Insert(idx, ' ' + temp + ':') end; end; end; function TReminderDialog.AddData(Lst: TStrings; Finishing: boolean = FALSE; Historical: boolean = FALSE): integer; var i: integer; Elem: TRemDlgElement; begin Result := 0; if(assigned(FElements)) then begin for i := 0 to FElements.Count-1 do begin Elem := TRemDlgElement(FElements.Objects[i]); if (not assigned(Elem.FParent)) then inc(Result, Elem.AddData(Lst, Finishing, Historical)); end; end; end; procedure TReminderDialog.ComboBoxCheckedText(Sender: TObject; NumChecked: integer; var Text: string); var i, Done: integer; DotLen, ComLen, TxtW, TotalW, NewLen: integer; tmp: string; Fnt: THandle; lb: TORListBox; begin if(NumChecked = 0) then Text := '(None Selected)' else if(NumChecked > 1) then begin Text := ''; lb := (Sender as TORListBox); Fnt := lb.Font.Handle; DotLen := TextWidthByFont(Fnt, '...'); TotalW := (lb.Owner as TControl).ClientWidth - 15; ComLen := TextWidthByFont(fnt, ', '); dec(TotalW,(NumChecked-1) * ComLen); Done := 0; for i := 0 to lb.Items.Count-1 do begin if(lb.Checked[i]) then begin inc(Done); if(Text <> '') then begin Text := Text + ', '; dec(TotalW, ComLen); end; Tmp := lb.DisplayText[i]; if(Done = NumChecked) then TxtW := TotalW else TxtW := TotalW div (NumChecked - Done + 1); NewLen := NumCharsFitInWidth(fnt, Tmp, TxtW); if(NewLen < length(Tmp)) then Tmp := copy(Tmp,1,NumCharsFitInWidth(fnt, Tmp, (TxtW - DotLen))) + '...'; dec(TotalW, TextWidthByFont(fnt, Tmp)); Text := Text + Tmp; end; end; end; end; procedure TReminderDialog.BeginTextChanged; begin inc(FTextChangedCount); end; procedure TReminderDialog.EndTextChanged(Sender: TObject); begin if(FTextChangedCount > 0) then begin dec(FTextChangedCount); if(FTextChangedCount = 0) and assigned(FOnTextChanged) then FOnTextChanged(Sender); end; end; function TReminderDialog.GetIEN: string; begin Result := Piece(FDlgData, U, 1); end; function TReminderDialog.GetPrintName: string; begin Result := Piece(FDlgData, U, 2); end; procedure TReminderDialog.BeginNeedRedraw; begin inc(FNeedRedrawCount); end; procedure TReminderDialog.EndNeedRedraw(Sender: TObject); begin if(FNeedRedrawCount > 0) then begin dec(FNeedRedrawCount); if(FNeedRedrawCount = 0) and (assigned(FOnNeedRedraw)) then FOnNeedRedraw(Sender); end; end; procedure TReminderDialog.FinishProblems(List: TStrings; var MissingTemplateFields: boolean); var i: integer; Elem: TRemDlgElement; TmpSL: TStringList; FldData: TORStringList; begin if(Processing and assigned(FElements)) then begin TmpSL := TStringList.Create; try FldData := TORStringList.Create; try for i := 0 to FElements.Count-1 do begin Elem := TRemDlgElement(FElements.Objects[i]); if (not assigned(Elem.FParent)) then begin Elem.FinishProblems(List); Elem.GetFieldValues(FldData); end; end; FNoResolve := TRUE; try AddText(TmpSL); finally FNoResolve := FALSE; end; MissingTemplateFields := AreTemplateFieldsRequired(TmpSL.Text, FldData); finally FldData.Free; end; finally TmpSL.Free; end; end; end; procedure TReminderDialog.ComboBoxResized(Sender: TObject); begin // This causes the ONCheckedText event to re-fire and re-update the text, // based on the new size of the combo box. if(Sender is TORComboBox) then with (Sender as TORComboBox) do OnCheckedText := OnCheckedText; end; function TReminderDialog.Visible: boolean; begin Result := (CurrentReminderInDialog = Self); end; { TReminder } constructor TReminder.Create(ARemData: string); begin FRemData := ARemData; BaseCreate; end; function TReminder.GetDueDateStr: string; begin Result := Piece(FRemData, U ,3); end; function TReminder.GetIEN: string; begin Result := copy(Piece(FRemData, U, 1), 2, MaxInt); end; function TReminder.GetLastDateStr: string; begin Result := Piece(FRemData, U ,4); end; function TReminder.GetPrintName: string; begin Result := Piece(FRemData, U ,2); end; function TReminder.GetPriority: integer; begin Result := StrToIntDef(Piece(FRemData, U ,5), 2); end; function TReminder.GetStatus: string; begin Result := Piece(FRemData, U ,6); end; { TRemDlgElement } function Code2DataType(Code: string): TRemDataType; var idx: TRemDataType; begin Result := dtUnknown; for idx := low(TRemDataType) to high(TRemDataType) do begin if(Code = RemDataCodes[idx]) then begin Result := idx; break; end; end; end; function Code2PromptType(Code: string): TRemPromptType; var idx: TRemPromptType; begin if(Code = '') then Result := ptSubComment else if(Code = MSTCode) then Result := ptMST else begin Result := ptUnknown; for idx := low(TRemPromptType) to high(TRemPromptType) do begin if(Code = RemPromptCodes[idx]) then begin Result := idx; break; end; end; end; end; function TRemDlgElement.Add2PN: boolean; var Lst: TStringList; begin if (FChecked) then begin Result := (Piece(FRec1, U, 5) <> '1'); //Suppress := (Piece(FRec1,U,1)='1'); if(Result and (ElemType = etDisplayOnly)) then begin //Result := FALSE; if(assigned(FPrompts) and (FPrompts.Count > 0)) or (assigned(FData) and (FData.Count > 0)) or Result then begin Lst := TStringList.Create; try AddData(Lst, FALSE); Result := (Lst.Count > 0); if not assigned(FData) then Result := True; finally Lst.Free; end; end; end; end else Result := FALSE; end; function TRemDlgElement.Box: boolean; begin Result := (Piece(FRec1, U, 19) = '1'); end; function TRemDlgElement.BoxCaption: string; begin if(Box) then Result := Piece(FRec1, U, 20) else Result := ''; end; function TRemDlgElement.ChildrenIndent: integer; begin Result := StrToIntDef(Piece(FRec1, U, 16), 0); end; function TRemDlgElement.ChildrenRequired: TRDChildReq; var Tmp: string; begin Tmp := Piece(FRec1, U, 18); if Tmp = '1' then Result := crOne else if Tmp = '2' then Result := crAtLeastOne else if Tmp = '3' then Result := crNoneOrOne else if Tmp = '4' then result := crAll else Result := crNone; end; function TRemDlgElement.ChildrenSharePrompts: boolean; begin Result := (Piece(FRec1, U, 17) = '1'); end; destructor TRemDlgElement.Destroy; begin KillObj(@FFieldValues); KillObj(@FData, TRUE); KillObj(@FPrompts, TRUE); KillObj(@FChildren); inherited; end; function TRemDlgElement.ElemType: TRDElemType; var Tmp: string; begin Tmp := Piece(FRec1, U, 4); if(Tmp = 'D') then Result := etDisplayOnly else if(Tmp = 'T') then Result := etTaxonomy else Result := etCheckBox; end; function TRemDlgElement.FindingType: string; begin if(ElemType = etTaxonomy) then Result := Piece(FRec1, U, 7) else Result := ''; end; function TRemDlgElement.HideChildren: boolean; begin Result := (Piece(FRec1, U, 15) <> '0'); end; function TRemDlgElement.Historical: boolean; begin Result := (Piece(FRec1, U, 8) = '1'); end; function TRemDlgElement.Indent: integer; begin Result := StrToIntDef(Piece(FRec1, U, 6), 0); end; procedure TRemDlgElement.GetData; var TempSL: TStrings; i: integer; Tmp: string; begin if FHaveData then exit; if(FReminder.GetDlgSL.IndexOfPieces([RPCCalled, FID, FTaxID]) < 0) then begin TempSL := GetDialogPrompts(FID, Historical, FindingType); TempSL.Add(RPCCalled); for i := 0 to TempSL.Count-1 do begin Tmp := TempSL[i]; SetPiece(Tmp,U,2,FID); SetPiece(Tmp,U,3,FTaxID); TempSL[i] := Tmp; end; FastAddStrings(TempSL, FReminder.GetDlgSL); end; UpdateData; end; procedure TRemDlgElement.UpdateData; var Ary: array of integer; idx, i,cnt: integer; TempSL: TORStringList; RData: TRemData; RPrompt: TRemPrompt; Tmp, Tmp2, choiceTmp: string; NewLine: boolean; dt: TRemDataType; pt: TRemPromptType; DateRange: string; ChoicesActiveDates: TStringList; ChoiceIdx: integer; Piece7: string; encDt: TFMDateTime; begin if FHaveData then exit; TempSL := FReminder.GetDlgSL; if(TempSL.IndexOfPieces([RPCCalled, FID, FTaxID]) >= 0) then begin FHaveData := TRUE; RData := nil; idx := -1; repeat idx := TempSL.IndexOfPieces(['3', FID, FTaxID], idx); if (idx >= 0) and (Pieces(TempSL[idx-1],U,1,6) = Pieces(TempSL[idx],u,1,6)) then if pos(':', Piece(TempSL[idx],U,7)) > 0 then //if has date ranges begin if RData <> nil then begin if (not assigned(RData.FActiveDates)) then RData.FActiveDates := TStringList.Create; DateRange := Pieces(Piece(TempSL[idx],U,7),':',2,3); RData.FActiveDates.Add(DateRange); with RData do begin FParent := Self; Piece7 := Piece(Piece(TempSL[idx],U,7),':',1); FRec3 := TempSL[idx]; SetPiece(FRec3,U,7,Piece7); end; end; end; if(idx >= 0) and (Pieces(TempSL[idx-1],U,1,6) <> Pieces(TempSL[idx],u,1,6)) then // if(idx >= 0) and ((Pieces(TempSL[idx-1],U,1,6) <> Pieces(TempSL[idx],u,1,6)) or // ((Pieces(TempSL[idx-1],U,1,6) = Pieces(TempSL[idx],u,1,6)) and // ((pos(':',Piece(TempSL[idx],U,7)) > 0) and (pos(':',Piece(TempSL[idx-1],U,7)) > 0))) and // (Piece(TempSL[idx],U,7) <> Piece(TempSL[idx-1],U,7))) then // if (idx >= 0) then begin dt := Code2DataType(piece(TempSL[idx], U, r3Type)); if(dt <> dtUnknown) and ((dt <> dtOrder) or CharInSet(CharAt(piece(TempSL[idx], U, 11),1), ['D', 'Q', 'M', 'O', 'A'])) and //AGP change 26.10 for allergy orders ((dt <> dtMentalHealthTest) or MHTestsOK) then begin if(not assigned(FData)) then FData := TList.Create; RData := TRemData(FData[FData.Add(TRemData.Create)]); if pos(':',Piece(TempSL[idx],U,7)) > 0 then begin RData.FActiveDates := TStringList.Create; RData.FActiveDates.Add(Pieces(Piece(TempSL[idx],U,7),':',2,3)); end; with RData do begin FParent := Self; Piece7 := Piece(Piece(TempSL[idx],U,7),':',1); FRec3 := TempSL[idx]; SetPiece(FRec3,U,7,Piece7); // FRoot := FRec3; i := idx + 1; ChoiceIdx := 0; while(i < TempSL.Count) and (TempSL.PiecesEqual(i, ['5', FID, FTaxID])) do begin if (Pieces(TempSL[i-1],U,1,6) = Pieces(TempSL[i],U,1,6)) then begin if pos(':', Piece(TempSL[i],U,7)) > 0 then begin if (not assigned(FChoicesActiveDates)) then begin FChoicesActiveDates := TList.Create; ChoicesActiveDates := TStringList.Create; FChoicesActiveDates.Insert(ChoiceIdx, ChoicesActiveDates); end; TStringList(FChoicesActiveDates[ChoiceIdx]).Add(Pieces(Piece(TempSL[i],U,7),':',2,3)); end; inc(i); end else begin if(not assigned(FChoices)) then begin FChoices := TORStringList.Create; if(not assigned(FPrompts)) then FPrompts := TList.Create; FChoicePrompt := TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]); with FChoicePrompt do begin FParent := Self; Tmp := Piece(FRec3,U,10); NewLine := (Tmp <> ''); FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + Tmp + U + BOOLCHAR[NewLine] + U + '1'; FData := RData; FOverrideType := ptDataList; InitValue; end; end; Tmp := TempSL[i]; Piece7 := Piece(Piece(TempSL[i],U,7),':',1); SetPiece(Tmp,U,7,Piece7); Tmp2 := Piece(Piece(Tmp,U,r3Code),':',1); if(Tmp2 <> '') then Tmp2 := ' (' + Tmp2 + ')'; Tmp2 := MixedCase(Piece(Tmp,U,r3Nar)) + Tmp2; SetPiece(Tmp,U,12,Tmp2); ChoiceIdx := FChoices.Add(Tmp); if pos(':',Piece(TempSL[i],U,7)) > 0 then begin if (not assigned(FChoicesActiveDates)) then FChoicesActiveDates := TList.Create; ChoicesActiveDates := TStringList.Create; ChoicesActiveDates.Add(Pieces(Piece(TempSL[i],U,7),':',2,3)); FChoicesActiveDates.Insert(ChoiceIdx, ChoicesActiveDates); end else if assigned(FChoicesActiveDates) then FChoicesActiveDates.Insert(ChoiceIdx, TStringList.Create); inc(i); end; end; choiceTmp := ''; // agp ICD-10 modify this code to handle one valid code against encounter date if combobox contains more than one code. if(assigned(FChoices)) and ((FChoices.Count = 1) or (FChoicesActiveDates.Count = 1)) then // If only one choice just pick it begin choiceTmp := FChoices[0]; end; if (assigned(FChoices)) and (assigned(FChoicesActiveDates)) and (choiceTmp = '') then begin if (assigned(FParent.FReminder.FPCEDataObj)) then encDT := FParent.FReminder.FPCEDataObj.DateTime else encDT := RemForm.PCEObj.VisitDateTime; choiceTmp := oneValidCode(FChoices, FChoicesActiveDates, encDT); end; // if(assigned(FChoices)) and (((FChoices.Count = 1) or (FChoicesActiveDates.Count = 1)) or // (oneValidCode(FChoices, FChoicesActiveDates, FParent.FReminder.FPCEDataObj.DateTime) = true)) then // If only one choice just pick it if (choiceTmp <> '') then begin if (not assigned(RData.FActiveDates)) then begin RData.FActiveDates := TStringList.Create; setActiveDates(FChoices, FChoicesActiveDates, RData.FActiveDates); end; FPrompts.Remove(FChoicePrompt); KillObj(@FChoicePrompt); Tmp := choiceTmp; KillObj(@FChoices); cnt := 5; if(Piece(FRec3,U,9) = '') then inc(cnt); SetLength(Ary,cnt); for i := 0 to cnt-1 do Ary[i] := i+4; SetPieces(FRec3, U, Ary, Tmp); if (not assigned(RData.FActiveDates)) then begin RData.FActiveDates := TStringList.Create; end; end; if(assigned(FChoices)) then begin for i := 0 to FChoices.Count-1 do FChoices.Objects[i] := TRemPCERoot.GetRoot(RData, FChoices[i], Historical); end else FPCERoot := TRemPCERoot.GetRoot(RData, RData.FRec3, Historical); if(dt = dtVitals) then begin if(Code2VitalType(Piece(FRec3,U,6)) <> vtUnknown) then begin if(not assigned(FPrompts)) then FPrompts := TList.Create; FChoicePrompt := TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]); with FChoicePrompt do begin FParent := Self; Tmp := Piece(FRec3,U,10); NewLine := FALSE; // FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U + // RData.InternalValue + U + 'P' + U + Tmp + U + BOOLCHAR[SameL] + U + '1'; FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + Tmp + U + BOOLCHAR[NewLine] + U + '0'; FData := RData; FOverrideType := ptVitalEntry; InitValue; end; end; end; if(dt = dtMentalHealthTest) then begin if(not assigned(FPrompts)) then FPrompts := TList.Create; FChoicePrompt := TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]); with FChoicePrompt do begin FParent := Self; Tmp := Piece(FRec3,U,10); NewLine := FALSE; // FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U + // RData.InternalValue + U + 'P' + U + Tmp + U + BOOLCHAR[SameL] + U + '1'; FRec4 := '4' + U + FID + U + FTaxID + U + U + BOOLCHAR[not RData.Add2PN] + U + U + 'P' + U + Tmp + U + BOOLCHAR[NewLine] + U + '0'; FData := RData; if ((Piece(FRec3, U, r3GAF) = '1')) and (MHDLLFound = false) then begin FOverrideType := ptGAF; SetPiece(FRec4, U, 8, ForcedCaption + ':'); end else FOverrideType := ptMHTest; end; end; end; end; end; until(idx < 0); idx := -1; repeat idx := TempSL.IndexOfPieces(['4', FID, FTaxID], idx); if(idx >= 0) then begin pt := Code2PromptType(piece(TempSL[idx], U, 4)); if(pt <> ptUnknown) and ((pt <> ptComment) or (not FHasComment)) then begin if(not assigned(FPrompts)) then FPrompts := TList.Create; RPrompt := TRemPrompt(FPrompts[FPrompts.Add(TRemPrompt.Create)]); with RPrompt do begin FParent := Self; FRec4 := TempSL[idx]; InitValue; end; if(pt = ptComment) then begin FHasComment := TRUE; FCommentPrompt := RPrompt; end; if(pt = ptSubComment) then FHasSubComments := TRUE; if(pt = ptMST) then FMSTPrompt := RPrompt; end; end; until(idx < 0); idx := -1; repeat idx := TempSL.IndexOfPieces(['6', FID, FTaxID], idx); if(idx >= 0) then begin PrepText4NextLine(FPNText); FPNText := FPNText + Trim(Piece(TempSL[idx], U, 4)); end; until(idx < 0); ExpandTIUObjects(FPNText); end; end; procedure TRemDlgElement.SetChecked(const Value: boolean); var i, j, k: integer; Kid: TRemDlgElement; Prompt: TRemPrompt; RData: TRemData; procedure UpdateForcedValues(Elem: TRemDlgElement); var i: integer; begin if(Elem.IsChecked) then begin if(assigned(Elem.FPrompts)) then begin for i := 0 to Elem.FPrompts.Count-1 do begin Prompt := TRemPrompt(Elem.FPrompts[i]); if Prompt.Forced then begin try Prompt.SetValueFromParent(Prompt.FValue); except on E: EForcedPromptConflict do begin Elem.FChecked := FALSE; InfoBox(E.Message, 'Error', MB_OK or MB_ICONERROR); break; end else raise; end; end; end; end; if(Elem.FChecked) and (assigned(Elem.FChildren)) then for i := 0 to Elem.FChildren.Count-1 do UpdateForcedValues(TRemDlgElement(Elem.FChildren[i])); end; end; begin if(FChecked <> Value) then begin FChecked := Value; if(Value) then begin GetData; if(FChecked and assigned(FParent)) then begin FParent.Check4ChildrenSharedPrompts; if(FParent.ChildrenRequired in [crOne, crNoneOrOne]) then begin for i := 0 to FParent.FChildren.Count-1 do begin Kid := TRemDlgElement(FParent.FChildren[i]); if(Kid <> Self) and (Kid.FChecked) then Kid.SetChecked(FALSE); end; end; end; UpdateForcedValues(Self); end else if(assigned(FPrompts) and assigned(FData)) then begin for i := 0 to FPrompts.Count-1 do begin Prompt := TRemPrompt(FPrompts[i]); if Prompt.Forced and (IsSyncPrompt(Prompt.PromptType)) then begin for j := 0 to FData.Count-1 do begin RData := TRemData(FData[j]); if(assigned(RData.FPCERoot)) then RData.FPCERoot.UnSync(Prompt); if(assigned(RData.FChoices)) then begin for k := 0 to RData.FChoices.Count-1 do begin if(assigned(RData.FChoices.Objects[k])) then TRemPCERoot(RData.FChoices.Objects[k]).UnSync(Prompt); end; end; end; end; end; end; end; end; function TRemDlgElement.TrueIndent: integer; var Prnt: TRemDlgElement; Nudge: integer; begin Result := Indent; Nudge := Gap; Prnt := FParent; while assigned(Prnt) do begin if(Prnt.Box) then begin Prnt := nil; inc(Nudge, Gap); end else begin Result := Result + Prnt.ChildrenIndent; Prnt := Prnt.FParent; end; end; Result := (Result * IndentMult) + Nudge; end; procedure TRemDlgElement.cbClicked(Sender: TObject); begin FReminder.BeginTextChanged; try FReminder.BeginNeedRedraw; try if(assigned(Sender)) then begin SetChecked((Sender as TORCheckBox).Checked); ElementChecked := Self; end; finally FReminder.EndNeedRedraw(Sender); end; finally FReminder.EndTextChanged(Sender); end; RemindersInProcess.Notifier.Notify; if assigned(TORCheckBox(Sender).Associate) and (not ScreenReaderSystemActive) then TDlgFieldPanel(TORCheckBox(Sender).Associate).SetFocus; end; function TRemDlgElement.EnableChildren: boolean; var Chk: boolean; begin if(assigned(FParent)) then Chk := FParent.EnableChildren else Chk := TRUE; if(Chk) then begin if(ElemType = etDisplayOnly) then Result := TRUE else Result := FChecked; end else Result := FALSE; end; function TRemDlgElement.Enabled: boolean; begin if(assigned(FParent)) then Result := FParent.EnableChildren else Result := TRUE; end; function TRemDlgElement.ShowChildren: boolean; begin if(assigned(FChildren) and (FChildren.Count > 0)) then begin if((ElemType = etDisplayOnly) or FChecked) then Result := TRUE else Result := (not HideChildren); end else Result := FALSE; end; type TAccessCheckBox = class(TORCheckBox); procedure TRemDlgElement.cbEntered(Sender: TObject); begin // changing focus because of a mouse click sets ClicksDisabled to false during the // call to SetFocus - this is how we allow the cbClicked code to execute on a mouse // click, which will set the focus after the mouse click. All other cases and the // ClicksDisabled will be FALSE and the focus is reset here. If we don't make this // check, you can't click on the check box.. if (Last508KeyCode = VK_UP) or (Last508KeyCode = VK_LEFT) then begin UnfocusableControlEnter(nil, Sender); exit; end; if not TAccessCheckBox(Sender).ClicksDisabled then begin if ScreenReaderSystemActive then (Sender as TCPRSDialogParentCheckBox).FocusOnBox := true else TDlgFieldPanel(TORCheckBox(Sender).Associate).SetFocus; end; end; procedure TRemDlgElement.ParentCBEnter(Sender: TObject); begin (Sender as TORCheckBox).FocusOnBox := true; end; procedure TRemDlgElement.ParentCBExit(Sender: TObject); begin (Sender as TORCheckBox).FocusOnBox := false; end; type TORExposedWinControl = class(TWinControl); function TRemDlgElement.BuildControls(var Y: integer; ParentWidth: integer; BaseParent, AOwner: TWinControl): TWinControl; var lbl: TLabel; lblText: string; sLbl: TCPRSDialogStaticLabel; lblCtrl: TControl; pnl: TDlgFieldPanel; AutoFocusControl: TWinControl; cb: TCPRSDialogParentCheckBox; gb: TGroupBox; ERes, prnt: TWinControl; PrntWidth: integer; i, X, Y1: integer; LastX, MinX, MaxX: integer; Prompt: TRemPrompt; Ctrl: TMultiClassObj; OK, DoLbl, HasVCombo, cbSingleLine: boolean; ud: TUpDown; HelpBtn: TButton; vCombo: TComboBox; pt: TRemPromptType; SameLineCtrl: TList; Kid: TRemDlgElement; vt: TVitalType; DefaultDate: TFMDateTime; Req: boolean; function GetPanel(const EID, AText: string; const PnlWidth: integer; OwningCheckBox: TCPRSDialogParentCheckBox): TDlgFieldPanel; var idx, p: integer; Entry: TTemplateDialogEntry; begin // This call creates a new TTemplateDialogEntry if necessary and creates the // necessary template field controls with their default values stored in the // TTemplateField object. Entry := GetDialogEntry(BaseParent, EID + IntToStr(Integer(BaseParent)), AText); Entry.InternalID := EID; // This call looks for the Entry's values in TRemDlgElement.FFieldValues idx := FFieldValues.IndexOfPiece(EID); // If the Entry's values were found in the previous step then they will be // restored to the TTemplateDialogEntry.FieldValues in the next step. if(idx >= 0) then begin p := pos(U, FFieldValues[idx]); // Can't use Piece because 2nd piece may contain ^ characters if(p > 0) then Entry.FieldValues := copy(FFieldValues[idx],p+1,MaxInt); end; Entry.AutoDestroyOnPanelFree := TRUE; // The FieldPanelChange event handler is where the Entry.FieldValues are saved to the // Element.FFieldValues. Entry.OnChange := FieldPanelChange; //AGP BACKED OUT THE CHANGE CAUSE A PROBLEM WITH TEMPLATE WORD PROCESSING FIELDS WHEN RESIZING //FieldPanelChange(Entry); // to accomodate fields with default values - CQ#15960 //AGP END BACKED OUT // Calls TTemplateDialogEntry.SetFieldValues which calls // TTemplateDialogEntry.SetControlText to reset the template field default // values to the values that were restored to the Entry from the Element if // they exist, otherwise the default values will remain. Result := Entry.GetPanel(PnlWidth, BaseParent, OwningCheckBox); end; procedure NextLine(var Y: integer); var i: integer; MaxY: integer; C: TControl; begin MaxY := 0; for i := 0 to SameLineCtrl.Count-1 do begin C := TControl(SameLineCtrl[i]); if(MaxY < C.Height) then MaxY := C.Height; end; for i := 0 to SameLineCtrl.Count-1 do begin C := TControl(SameLineCtrl[i]); if(MaxY > C.Height) then C.Top := Y + ((MaxY - C.Height) div 2); end; inc(Y, MaxY); if assigned(cb) and assigned(pnl) then cb.Top := pnl.Top; SameLineCtrl.Clear; end; procedure ProcessLabel(Required, AEnabled: boolean; AParent: TWinControl; Control: TControl); begin if(Trim(Prompt.Caption) = '') and (not Required) then lblCtrl := nil else begin lbl := TLabel.Create(AOwner); lbl.Parent := AParent; if ScreenReaderSystemActive then begin sLbl := TCPRSDialogStaticLabel.Create(AOwner); sLbl.Parent := AParent; sLbl.Height := lbl.Height; // get groop box hearder, if any // (sLbl as ICPRSDialogComponent).BeforeText := ScreenReaderSystem_GetPendingText; lbl.Free; lblCtrl := sLbl; end else lblCtrl := lbl; lblText := Prompt.Caption; if Required then begin if assigned(Control) and Supports(Control, ICPRSDialogComponent) then begin (Control as ICPRSDialogComponent).RequiredField := TRUE; if ScreenReaderSystemActive and (AOwner = frmRemDlg) then frmRemDlg.amgrMain.AccessText[sLbl] := lblText; end; lblText := lblText + ' *'; end; SetStrProp(lblCtrl, CaptionProperty, lblText); if ScreenReaderSystemActive then begin ScreenReaderSystem_CurrentLabel(sLbl); ScreenReaderSystem_AddText(lblText); end; lblCtrl.Enabled := AEnabled; UpdateColorsFor508Compliance(lblCtrl); end; end; procedure ScreenReaderSupport(Control: TWinControl); begin if ScreenReaderSystemActive then begin if Supports(Control, ICPRSDialogComponent) then ScreenReaderSystem_CurrentComponent(Control as ICPRSDialogComponent) else ScreenReaderSystem_Stop; end; end; procedure AddPrompts(Shared: boolean; AParent: TWinControl; PWidth: integer; var Y: integer); var i, j, k, idx: integer; DefLoc: TStrings; LocText: string; LocFound: boolean; m, n: integer; ActDt, InActDt: Double; EncDt: TFMDateTime; ActChoicesSL: TORStringList; Piece12, WHReportStr: String; WrapLeft, LineWidth: integer; begin SameLineCtrl := TList.Create; try if(assigned(cb)) then begin if(not Shared) then begin SameLineCtrl.Add(cb); SameLineCtrl.Add(pnl); end; if(cbSingleLine and (not Shared)) then LastX := cb.Left + pnl.Width + PromptGap + IndentGap else LastX := PWidth; end else begin if(not Shared) then SameLineCtrl.Add(pnl); LastX := PWidth; end; for i := 0 to FPrompts.Count-1 do begin Prompt := TRemPrompt(FPrompts[i]); OK := ((Prompt.FIsShared = Shared) and Prompt.PromptOK and (not Prompt.Forced)); if(OK and Shared) then begin OK := FALSE; for j := 0 to Prompt.FSharedChildren.Count-1 do begin Kid := TRemDlgElement(Prompt.FSharedChildren[j]); // if(Kid.ElemType <> etDisplayOnly) and (Kid.FChecked) then if(Kid.FChecked) then begin OK := TRUE; break; end; end; end; Ctrl.Ctrl := nil; ud := nil; HelpBtn := nil; vCombo := nil; HasVCombo := FALSE; if(OK) then begin pt := Prompt.PromptType; MinX := 0; MaxX := 0; lbl := nil; sLbl := nil; lblCtrl := nil; DoLbl := Prompt.Required; case pt of ptComment, ptQuantity: begin Ctrl.edt := TCPRSDialogFieldEdit.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.edt.Text := Prompt.Value; if(pt = ptComment) then begin Ctrl.edt.MaxLength := 245; MinX := TextWidthByFont(Ctrl.edt.Font.Handle, 'AbCdEfGhIjKlMnOpQrStUvWxYz 1234'); MaxX := PWidth; end else begin ud := TUpDown.Create(AOwner); ud.Parent := AParent; ud.Associate := Ctrl.edt; if(pt = ptQuantity) then begin ud.Min := 1; ud.Max := 100; end else begin ud.Min := 0; ud.Max := 40; end; MinX := TextWidthByFont(Ctrl.edt.Font.Handle, IntToStr(ud.Max)) + 24; ud.Position := StrToIntDef(Prompt.Value, ud.Min); UpdateColorsFor508Compliance(ud); end; Ctrl.edt.OnKeyPress := Prompt.EditKeyPress; Ctrl.edt.OnChange := Prompt.PromptChange; UpdateColorsFor508Compliance(Ctrl.edt); DoLbl := TRUE; end; ptVisitLocation, ptLevelUnderstanding, ptSeries, ptReaction, ptExamResults, ptLevelSeverity, ptSkinResults, ptSkinReading: begin Ctrl.cbo := TCPRSDialogComboBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.cbo.OnKeyDown := Prompt.ComboBoxKeyDown; Ctrl.cbo.Style := orcsDropDown; Ctrl.cbo.Pieces := '2'; if pt = ptSkinReading then begin Ctrl.cbo.Pieces := '1'; Ctrl.cbo.Items.Add(''); for j := 0 to 50 do Ctrl.cbo.Items.Add(inttostr(j)); GetComboBoxMinMax(Ctrl.cbo,MinX, MaxX); end; if pt <> ptSkinReading then begin Ctrl.cbo.Tag := ComboPromptTags[pt]; PCELoadORCombo(Ctrl.cbo, MinX, MaxX); end; if pt = ptVisitLocation then begin DefLoc := GetDefLocations; if DefLoc.Count > 0 then begin idx := 1; for j := 0 to DefLoc.Count-1 do begin LocText := piece(DefLoc[j],U,2); if LocText <> '' then begin if (LocText <> '0') and (IntToStr(StrToIntDef(LocText,0)) = LocText) then begin LocFound := FALSE; for k := 0 to Ctrl.cbo.Items.Count-1 do begin if(piece(Ctrl.cbo.Items[k],U,1) = LocText) then begin LocText := Ctrl.cbo.Items[k]; LocFound := TRUE; break; end; end; if not LocFound then LocText := ''; end else LocText := '0^'+LocText; if LocText <> '' then begin Ctrl.cbo.Items.Insert(idx, LocText); inc(idx); end; end; end; if idx > 1 then begin Ctrl.cbo.Items.Insert(idx, '-1' + LLS_LINE); Ctrl.cbo.Items.Insert(idx+1, '-1' + LLS_SPACE); end; end; end; MinX := MaxX; Ctrl.cbo.SelectByID(Prompt.Value); if(Ctrl.cbo.ItemIndex < 0) then begin Ctrl.cbo.Text := Prompt.Value; if(pt = ptVisitLocation) then Ctrl.cbo.Items[0] := '0' + U + Prompt.Value; end; if(Ctrl.cbo.ItemIndex < 0) then Ctrl.cbo.ItemIndex := 0; Ctrl.cbo.OnChange := Prompt.PromptChange; DoLbl := TRUE; Ctrl.cbo.ListItemsOnly := (pt <> ptVisitLocation); UpdateColorsFor508Compliance(Ctrl.cbo); end; ptWHPapResult: begin if FData<>nil then begin if (TRemData(FData[i]).DisplayWHResults)=true then begin NextLine(Y); Ctrl.btn := TCPRSDialogButton.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.btn.Left := NewLInePromptGap+15; Ctrl.btn.Top := Y+7; Ctrl.btn.OnClick := Prompt.DoWHReport; Ctrl.btn.Caption := 'Review complete report'; Ctrl.btn.Width := TextWidthByFont(Ctrl.btn.Font.Handle, Ctrl.btn.Caption) + 13; Ctrl.btn.Height := TextHeightByFont(Ctrl.btn.Font.Handle, Ctrl.btn.Caption) + 13; Ctrl.btn.Height := TextHeightByFont(Ctrl.btn.Handle, Ctrl.btn.Caption) + 8; ScreenReaderSupport(Ctrl.btn); UpdateColorsFor508Compliance(Ctrl.btn); Y := ctrl.btn.Top + Ctrl.btn.Height; NextLine(Y); Ctrl.WHChk := TWHCheckBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; ProcessLabel(Prompt.Required, TRUE, Ctrl.WHChk.Parent, Ctrl.WHChk); if lblCtrl is TWinControl then TWinControl(lblCtrl).TabOrder := Ctrl.WHChk.TabOrder; Ctrl.WHChk.Flbl := lblCtrl; Ctrl.WHChk.Flbl.Top := Y + 5; Ctrl.WHChk.Flbl.Left := NewLinePromptGap+15; WrapLeft := Ctrl.WHChk.Flbl.Left; // Ctrl.WHChk.Flbl.Width := TextWidthByFont( // TExposedComponent(Ctrl.WHChk.Flbl).Font.Handle, // TExposedComponent(Ctrl.WHChk.Flbl).Caption)+25; // Ctrl.WHChk.Flbl.Height := TextHeightByFont( // TExposedComponent(Ctrl.WHChk.Flbl).Font.Handle, // TExposedComponent(Ctrl.WHChk.Flbl).Caption); //LineWidth := WrapLeft + Ctrl.WHChk.Flbl.Width+10; Y := Ctrl.WHChk.Flbl.Top + Ctrl.WHChk.Flbl.Height; NextLine(Y); Ctrl.WHChk.RadioStyle:=true; Ctrl.WHChk.GroupIndex:=1; Ctrl.WHChk.Check2 := TWHCheckBox.Create(AOwner); Ctrl.WHChk.Check2.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.Check2.RadioStyle:=true; Ctrl.WHChk.Check2.GroupIndex:=1; Ctrl.WHChk.Check3 := TWHCheckBox.Create(AOwner); Ctrl.WHChk.Check3.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.Check3.RadioStyle:=true; Ctrl.WHChk.Check3.GroupIndex:=1; Ctrl.WHChk.Caption := 'NEM (No Evidence of Malignancy)'; Ctrl.WHChk.ShowHint := true; Ctrl.WHChk.Hint := 'No Evidence of Malignancy'; Ctrl.WHChk.Width := TextWidthByFont(Ctrl.WHChk.Font.Handle, Ctrl.WHChk.Caption)+20; Ctrl.WHChk.Height := TextHeightByFont(Ctrl.WHChk.Font.Handle, Ctrl.WHChk.Caption)+4; Ctrl.WHChk.Top := Y + 5; Ctrl.WHChk.Left := WrapLeft; Ctrl.WHChk.OnClick := Prompt.PromptChange; Ctrl.WHChk.Checked := (WHResultChk = 'N'); LineWidth := WrapLeft + Ctrl.WHChk.Width+5; Ctrl.WHChk.Check2.Caption := 'Abnormal'; Ctrl.WHChk.Check2.Width := TextWidthByFont(Ctrl.WHChk.Check2.Font.Handle, Ctrl.WHChk.Check2.Caption) + 20; Ctrl.WHChk.Check2.Height := TextHeightByFont(Ctrl.WHChk.check2.Font.Handle, Ctrl.WHChk.check2.Caption)+4; if (LineWidth + Ctrl.WHChk.Check2.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.Top + Ctrl.WHChk.Height; Nextline(Y); end; Ctrl.WHChk.Check2.Top := Y + 5; Ctrl.WHChk.Check2.Left := LineWidth; Ctrl.WHChk.Check2.OnClick := Prompt.PromptChange; Ctrl.WHChk.Check2.Checked := (WHResultChk = 'A'); LineWidth := LineWidth + Ctrl.WHChk.Check2.Width+5; Ctrl.WHChk.Check3.Caption := 'Unsatisfactory for Diagnosis'; Ctrl.WHChk.Check3.Width := TextWidthByFont(Ctrl.WHChk.Check3.Font.Handle, Ctrl.WHChk.Check3.Caption)+20; Ctrl.WHChk.Check3.Height := TextHeightByFont(Ctrl.WHChk.check3.Font.Handle, Ctrl.WHChk.check3.Caption)+4; if (LineWidth + Ctrl.WHChk.Check3.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.Check2.Top + Ctrl.WHChk.Check2.Height; Nextline(Y); end; Ctrl.WHChk.Check3.Top := Y + 5; Ctrl.WHChk.Check3.OnClick := Prompt.PromptChange; Ctrl.WHChk.Check3.Checked := (WHResultChk = 'U'); Ctrl.WHChk.Check3.Left := LineWidth; UpdateColorsFor508Compliance(Ctrl.WHChk); UpdateColorsFor508Compliance(Ctrl.WHChk.Flbl); UpdateColorsFor508Compliance(Ctrl.WHChk.Check2); UpdateColorsFor508Compliance(Ctrl.WHChk.Check3); ScreenReaderSupport(Ctrl.WHChk); ScreenReaderSupport(Ctrl.WHChk.Check2); ScreenReaderSupport(Ctrl.WHChk.Check3); Y := Ctrl.WHChk.Check3.Top + Ctrl.WHChk.Check3.Height; Nextline(Y); end else DoLbl := FALSE; end else DoLbl :=FALSE; end; ptWHNotPurp: begin NextLine(Y); Ctrl.WHChk := TWHCheckBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; ProcessLabel(Prompt.Required, TRUE, Ctrl.WHChk.Parent, Ctrl.WHChk); Ctrl.WHChk.Flbl := lblCtrl; if lblCtrl is TWinControl then TWinControl(lblCtrl).TabOrder := Ctrl.WHChk.TabOrder; Ctrl.WHChk.Flbl.Top := Y + 7; Ctrl.WHChk.Flbl.Left := NewLInePromptGap+30; WrapLeft := Ctrl.WHChk.Flbl.Left; // Ctrl.WHChk.Flbl.Width := TextWidthByFont( // TExposedComponent(Ctrl.WHChk.Flbl).Font.Handle, // TExposedComponent(Ctrl.WHChk.Flbl).Caption)+25; // Ctrl.WHChk.Flbl.Height := TextHeightByFont( // TExposedComponent(Ctrl.WHChk.Flbl).Font.Handle, // TExposedComponent(Ctrl.WHChk.Flbl).Caption)+4; LineWidth := WrapLeft + Ctrl.WHChk.Flbl.Width+10; Ctrl.WHChk.Check2 := TWHCheckBox.Create(AOwner); Ctrl.WHChk.Check2.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.Check3 := TWHCheckBox.Create(AOwner); Ctrl.WHChk.Check3.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.ShowHint := true; Ctrl.WHChk.Hint := 'Letter will print with next WH batch run'; Ctrl.WHChk.Caption := 'Letter'; Ctrl.WHChk.Width := TextWidthByFont(Ctrl.WHChk.Font.Handle, Ctrl.WHChk.Caption)+25; Ctrl.WHChk.Height := TextHeightByFont(Ctrl.WHChk.Font.Handle, Ctrl.WHChk.Caption)+4; if (LineWidth + Ctrl.WHChk.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.Flbl.Top + Ctrl.WHChk.Flbl.Height; Nextline(Y); end; Ctrl.WHChk.Top := Y + 7; Ctrl.WHChk.Left := LineWidth; Ctrl.WHChk.OnClick := Prompt.PromptChange; Ctrl.WHChk.Checked := (Pos('L',WHResultNot)>0); LineWidth := LineWidth + Ctrl.WHChk.Width+10; Ctrl.WHChk.Check2.Caption := 'In-Person'; Ctrl.WHChk.Check2.Width := TextWidthByFont(Ctrl.WHChk.Check2.Font.Handle, Ctrl.WHChk.Check2.Caption) + 25; Ctrl.WHChk.Check2.Height := TextHeightByFont(Ctrl.WHChk.check2.Font.Handle, Ctrl.WHChk.check2.Caption)+4; if (LineWidth + Ctrl.WHChk.Check2.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.Top + Ctrl.WHChk.Height; Nextline(Y); end; Ctrl.WHChk.Check2.Top := Y + 7; Ctrl.WHChk.Check2.Left := LineWidth; Ctrl.WHChk.Check2.OnClick := Prompt.PromptChange; Ctrl.WHChk.Check2.Checked := (Pos('I',WHResultNot)>0); LineWidth := LineWidth + Ctrl.WHChk.Check2.Width+10; Ctrl.WHChk.Check3.Caption := 'Phone Call'; Ctrl.WHChk.Check3.Width := TextWidthByFont(Ctrl.WHChk.Check3.Font.Handle, Ctrl.WHChk.Check3.Caption)+20; Ctrl.WHChk.Check3.Height := TextHeightByFont(Ctrl.WHChk.check3.Font.Handle, Ctrl.WHChk.check3.Caption)+4; if (LineWidth + Ctrl.WHChk.Check3.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.Check2.Top + Ctrl.WHChk.Check2.Height; Nextline(Y); end; Ctrl.WHChk.Check3.Top := Y + 7; Ctrl.WHChk.Check3.OnClick := Prompt.PromptChange; Ctrl.WHChk.Check3.Checked := (Pos('P',WHResultNot)>0); Ctrl.WHChk.Check3.Left := LineWidth; Y := Ctrl.WHChk.Check3.Top + Ctrl.WHChk.Check3.Height; Nextline(Y); Ctrl.WHChk.Fbutton := TCPRSDialogButton.Create(AOwner); Ctrl.WHChk.FButton.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.FButton.Enabled:=(Pos('L',WHResultNot)>0); Ctrl.WHChk.FButton.Left := Ctrl.WHChk.Flbl.Left; Ctrl.WHChk.FButton.Top := Y+7; Ctrl.WHChk.FButton.OnClick := Prompt.ViewWHText; Ctrl.WHChk.FButton.Caption := 'View WH Notification Letter'; Ctrl.WHChk.FButton.Width := TextWidthByFont(Ctrl.WHChk.FButton.Font.Handle, Ctrl.WHChk.FButton.Caption) + 13; Ctrl.WHChk.FButton.Height := TextHeightByFont(Ctrl.WHChk.FButton.Font.Handle, Ctrl.WHChk.FButton.Caption) + 13; UpdateColorsFor508Compliance(Ctrl.WHChk); UpdateColorsFor508Compliance(Ctrl.WHChk.Flbl); UpdateColorsFor508Compliance(Ctrl.WHChk.Check2); UpdateColorsFor508Compliance(Ctrl.WHChk.Check3); UpdateColorsFor508Compliance(Ctrl.WHChk.FButton); ScreenReaderSupport(Ctrl.WHChk); ScreenReaderSupport(Ctrl.WHChk.Check2); ScreenReaderSupport(Ctrl.WHChk.Check3); ScreenReaderSupport(Ctrl.WHChk.FButton); LineWidth := Ctrl.WHChk.FButton.Left + Ctrl.WHChk.FButton.Width; if piece(Prompt.FRec4,u,12)='1' then begin Ctrl.WHChk.FPrintNow :=TCPRSDialogCheckBox.Create(AOwner); Ctrl.WHChk.FPrintNow.Parent := Ctrl.WHChk.Parent; Ctrl.WHChk.FPrintNow.ShowHint := true; Ctrl.WHChk.FPrintNow.Hint := 'Letter will print after "Finish" button is clicked'; Ctrl.WHChk.FPrintNow.Caption:='Print Now'; Ctrl.WHChk.FPrintNow.Width := TextWidthByFont(Ctrl.WHChk.FPrintNow.Font.Handle, Ctrl.WHChk.FPrintNow.Caption)+20; Ctrl.WHChk.FPrintNow.Height := TextHeightByFont(Ctrl.WHChk.FPrintNow.Font.Handle, Ctrl.WHChk.FPrintNow.Caption)+4; if (LineWidth + Ctrl.WHChk.FPrintNow.Width) > PWidth - 10 then begin LineWidth := WrapLeft; Y := Ctrl.WHChk.FButton.Top + Ctrl.WHChk.FButton.Height; Nextline(Y); end; Ctrl.WHChk.FPrintNow.Left := LineWidth + 15; Ctrl.WHChk.FPrintNow.Top := Y + 7; Ctrl.WHChk.FPrintNow.Enabled := (Pos('L',WHResultNot)>0); Ctrl.WHChk.FPrintNow.Checked :=(WHPrintDevice<>''); Ctrl.WHChk.FPrintNow.OnClick := Prompt.PromptChange; UpdateColorsFor508Compliance(Ctrl.WHChk.FPrintNow); MinX :=PWidth; if (Ctrl.WHChk.FButton.Top + Ctrl.WHChk.FButton.Height) > (Ctrl.WHChk.FPrintNow.Top + Ctrl.WHChk.FPrintNow.Height) then Y := Ctrl.WHChk.FButton.Top + Ctrl.WHChk.FButton.Height + 7 else Y := Ctrl.WHChk.FPrintNow.Top + Ctrl.WHChk.FPrintNow.Height + 7; ScreenReaderSupport(Ctrl.WHChk.FPrintNow); end else Y := Ctrl.WHChk.FButton.Top + Ctrl.WHChk.FButton.Height + 7; NextLine(Y); end; ptVisitDate: begin Ctrl.dt := TCPRSDialogDateCombo.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.dt.LongMonths := TRUE; try DefaultDate := Ctrl.dt.FMDate; Ctrl.dt.FMDate := StrToFloat(Prompt.Value); except on EConvertError do Ctrl.dt.FMDate := DefaultDate; else raise; end; Ctrl.dt.OnChange := Prompt.PromptChange; UpdateColorsFor508Compliance(Ctrl.dt); DoLbl := TRUE; MinX := Ctrl.dt.Width; //TextWidthByFont(Ctrl.dt.Font.Handle, 'May 22, 2000') + 26; end; ptPrimaryDiag, ptAdd2PL, ptContraindicated: begin Ctrl.cb := TCPRSDialogCheckBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.cb.Checked := (Prompt.Value = '1'); Ctrl.cb.Caption := Prompt.Caption; if prompt.Required=false then DoLbl := true; Ctrl.cb.AutoSize := False; Ctrl.cb.OnEnter := ParentCBEnter; Ctrl.cb.OnExit := ParentCBExit; Ctrl.cb.Height := TORCheckBox(Ctrl.cb).Height + 5; Ctrl.cb.Width := 17; Ctrl.cb.OnClick := Prompt.PromptChange; UpdateColorsFor508Compliance(Ctrl.cb); MinX := Ctrl.cb.Width; end; else begin if(pt = ptSubComment) then begin Ctrl.cb := TCPRSDialogCheckBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.cb.Checked := (Prompt.Value = '1'); Ctrl.cb.Caption := Prompt.Caption; Ctrl.cb.AutoSize := TRUE; Ctrl.cb.OnClick := SubCommentChange; Ctrl.cb.Tag := Integer(Prompt); UpdateColorsFor508Compliance(Ctrl.cb); MinX := Ctrl.cb.Width; end else if pt = ptVitalEntry then begin vt := Prompt.VitalType; if(vt = vtPain) then begin Ctrl.cbo := TCPRSDialogComboBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.cbo.Style := orcsDropDown; Ctrl.cbo.Pieces := '1,2'; Ctrl.cbo.OnKeyDown := Prompt.ComboBoxKeyDown; InitPainCombo(Ctrl.cbo); Ctrl.cbo.ListItemsOnly := TRUE; Ctrl.cbo.SelectByID(Prompt.VitalValue); Ctrl.cbo.OnChange := Prompt.PromptChange; Ctrl.cbo.SelLength := 0; MinX := TextWidthByFont(Ctrl.cbo.Font.Handle, Ctrl.cbo.DisplayText[0]) + 24; MaxX := TextWidthByFont(Ctrl.cbo.Font.Handle, Ctrl.cbo.DisplayText[1]) + 24; if(ElementChecked = Self) then begin AutoFocusControl := Ctrl.cbo; ElementChecked := nil; end; UpdateColorsFor508Compliance(Ctrl.cbo); end else begin Ctrl.vedt := TVitalEdit.Create(AOwner); Ctrl.ctrl.Parent := AParent; MinX := TextWidthByFont(Ctrl.vedt.Font.Handle, '12345.67'); Ctrl.vedt.OnKeyPress := Prompt.EditKeyPress; Ctrl.vedt.OnChange := Prompt.PromptChange; Ctrl.vedt.OnExit := Prompt.VitalVerify; UpdateColorsFor508Compliance(Ctrl.vedt); if(vt in [vtTemp, vtHeight, vtWeight]) then begin HasVCombo := TRUE; Ctrl.vedt.LinkedCombo := TVitalComboBox.Create(AOwner); Ctrl.vedt.LinkedCombo.Parent := AParent; Ctrl.vedt.LinkedCombo.OnChange := Prompt.PromptChange; Ctrl.vedt.LinkedCombo.Tag := VitalControlTag(vt, TRUE); Ctrl.vedt.LinkedCombo.OnExit := Prompt.VitalVerify; Ctrl.vedt.LinkedCombo.LinkedEdit := Ctrl.vedt; case vt of vtTemp: begin Ctrl.vedt.LinkedCombo.Items.Add('F'); Ctrl.vedt.LinkedCombo.Items.Add('C'); end; vtHeight: begin Ctrl.vedt.LinkedCombo.Items.Add('IN'); Ctrl.vedt.LinkedCombo.Items.Add('CM'); end; vtWeight: begin Ctrl.vedt.LinkedCombo.Items.Add('LB'); Ctrl.vedt.LinkedCombo.Items.Add('KG'); end; end; Ctrl.vedt.LinkedCombo.SelectByID(Prompt.VitalUnitValue); if(Ctrl.vedt.LinkedCombo.ItemIndex < 0) then Ctrl.vedt.LinkedCombo.ItemIndex := 0; Ctrl.vedt.LinkedCombo.Width := TextWidthByFont(Ctrl.vedt.Font.Handle, Ctrl.vedt.LinkedCombo.Items[1]) + 30; Ctrl.vedt.LinkedCombo.SelLength := 0; UpdateColorsFor508Compliance(Ctrl.vedt.LinkedCombo); inc(MinX, Ctrl.vedt.LinkedCombo.Width); end; if(ElementChecked = Self) then begin AutoFocusControl := Ctrl.vedt; ElementChecked := nil; end; end; Ctrl.ctrl.Text := Prompt.VitalValue; Ctrl.ctrl.Tag := VitalControlTag(vt); DoLbl := TRUE; end else if pt = ptDataList then begin Ctrl.cbo := TCPRSDialogComboBox.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.cbo.Style := orcsDropDown; Ctrl.cbo.Pieces := '12'; if ActChoicesSL = nil then ActChoicesSL := TORStringList.Create; if Self.Historical then EncDt := DateTimeToFMDateTime(Date) else EncDt := RemForm.PCEObj.VisitDateTime; if assigned(Prompt.FData.FChoicesActiveDates) then {csv active/inactive dates} for m := 0 to (Prompt.FData.FChoices.Count - 1) do begin for n := 0 to (TStringList(Prompt.FData.FChoicesActiveDates[m]).Count - 1) do begin ActDt := StrToIntDef((Piece(TStringList(Prompt.FData.FChoicesActiveDates[m]).Strings[n], ':', 1)),0); InActDt := StrToIntDef((Piece(TStringList(Prompt.FData.FChoicesActiveDates[m]).Strings[n], ':', 2)),9999999); Piece12 := Piece(Prompt.FData.FChoices.Strings[m],U,12); Prompt.FData.FChoices.SetStrPiece(m,12,Piece12); if (EncDt >= ActDt) and (EncDt <= InActDt) then ActChoicesSL.AddObject(Prompt.FData.FChoices[m], Prompt.FData.FChoices.Objects[m]); end; {loop through the TStringList object in FChoicesActiveDates[m] object property} end {loop through FChoices/FChoicesActiveDates} else FastAssign(Prompt.FData.FChoices, ActChoicesSL); FastAssign(ActChoicesSL, Ctrl.cbo.Items); Ctrl.cbo.CheckBoxes := TRUE; Ctrl.cbo.SelectByID(Prompt.Value); Ctrl.cbo.OnCheckedText := FReminder.ComboBoxCheckedText; Ctrl.cbo.OnResize := FReminder.ComboBoxResized; Ctrl.cbo.CheckedString := Prompt.Value; Ctrl.cbo.OnChange := Prompt.PromptChange; Ctrl.cbo.ListItemsOnly := TRUE; UpdateColorsFor508Compliance(Ctrl.cbo); if(ElementChecked = Self) then begin AutoFocusControl := Ctrl.cbo; ElementChecked := nil; end; DoLbl := TRUE; if(Prompt.FData.FChoicesFont = Ctrl.cbo.Font.Handle) then begin MinX := Prompt.FData.FChoicesMin; MaxX := Prompt.FData.FChoicesMax; end //agp ICD-10 suppress combobox and label if no values. else if (Ctrl.cbo.Items.Count > 0) then begin GetComboBoxMinMax(Ctrl.cbo, MinX, MaxX); inc(MaxX,18); // Adjust for checkboxes MinX := MaxX; Prompt.FData.FChoicesFont := Ctrl.cbo.Font.Handle; Prompt.FData.FChoicesMin := MinX; Prompt.FData.FChoicesMax := MaxX; end else DoLbl := FALSE end else if(pt = ptMHTest) or ((pt = ptGaf) and (MHDLLFound = true)) then begin Ctrl.btn := TCPRSDialogButton.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.btn.OnClick := Prompt.DoMHTest; Ctrl.btn.Caption := Prompt.ForcedCaption; if Piece(Prompt.FData.FRec3,U,13)='1' then begin Ctrl.btn.Caption := Ctrl.btn.Caption + ' *'; (Ctrl.btn as ICPRSDialogComponent).RequiredField := TRUE; end; MinX := TextWidthByFont(Ctrl.btn.Font.Handle, Ctrl.btn.Caption) + 13; Ctrl.btn.Height := TextHeightByFont(Ctrl.btn.Font.Handle, Ctrl.btn.Caption) + 8; DoLbl := TRUE; end else if ((pt = ptGAF)) and (MHDLLFound = false) then begin Ctrl.edt := TCPRSDialogFieldEdit.Create(AOwner); Ctrl.ctrl.Parent := AParent; Ctrl.edt.Text := Prompt.Value; ud := TUpDown.Create(AOwner); ud.Parent := AParent; ud.Associate := Ctrl.edt; ud.Min := 0; ud.Max := 100; MinX := TextWidthByFont(Ctrl.edt.Font.Handle, IntToStr(ud.Max)) + 24 + Gap; ud.Position := StrToIntDef(Prompt.Value, ud.Min); Ctrl.edt.OnKeyPress := Prompt.EditKeyPress; Ctrl.edt.OnChange := Prompt.PromptChange; if(User.WebAccess and (GAFURL <> '')) then begin HelpBtn := TCPRSDialogButton.Create(AOwner); HelpBtn.Parent := AParent; HelpBtn.Caption := 'Reference Info'; HelpBtn.OnClick := Prompt.GAFHelp; HelpBtn.Width := TextWidthByFont(HelpBtn.Font.Handle, HelpBtn.Caption) + 13; HelpBtn.Height := Ctrl.edt.Height; inc(MinX, HelpBtn.Width); end; DoLbl := TRUE; end else Ctrl.ctrl := nil; end; end; if(DoLbl) and ((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then //if(DoLbl) then begin Req := Prompt.Required; if (not Req) and (pt = ptGaf) and (MHDLLFound = false) then Req := (Piece(Prompt.FData.FRec3,U,13) = '1'); ProcessLabel(Req, Prompt.FParent.Enabled, AParent, Ctrl.Ctrl); if assigned(lblCtrl) then begin inc(MinX, lblCtrl.Width + LblGap); inc(MaxX, lblCtrl.Width + LblGap); end else DoLbl := FALSE; end; if(MaxX < MinX) then MaxX := MinX; if((Prompt.SameLine) and ((LastX + MinX + Gap) < PWidth)) and ((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then //if((Prompt.SameLine) and ((LastX + MinX + Gap) < PWidth)) then begin X := LastX; end else begin if(Shared) and (assigned(FChildren)) and (FChildren.Count > 0) then X := TRemDlgElement(FChildren[0]).TrueIndent else begin if(assigned(cb)) then X := cb.Left + NewLinePromptGap else X := pnl.Left + NewLinePromptGap; end; NextLine(Y); end; if(MaxX > (PWidth - X - Gap)) then MaxX := PWidth - X - Gap; if((DoLbl) or (assigned(Ctrl.Ctrl))) and ((pt <> ptWHNotPurp) and (pt <> ptWHPapResult)) then //if((DoLbl) or (assigned(Ctrl.Ctrl))) then begin if DoLbl then begin lblCtrl.Left := X; lblCtrl.Top := Y; inc(X, lblCtrl.Width + LblGap); dec(MinX, lblCtrl.Width + LblGap); dec(MaxX, lblCtrl.Width + LblGap); SameLineCtrl.Add(lblCtrl); end; if(assigned(Ctrl.Ctrl)) then begin if ScreenReaderSystemActive then begin if Supports(Ctrl.Ctrl, ICPRSDialogComponent) then ScreenReaderSystem_CurrentComponent(Ctrl.Ctrl as ICPRSDialogComponent) else ScreenReaderSystem_Stop; end; Ctrl.Ctrl.Enabled := Prompt.FParent.Enabled; if not Ctrl.Ctrl.Enabled then Ctrl.Ctrl.Font.Color := DisabledFontColor; Ctrl.Ctrl.Left := X; Ctrl.Ctrl.Top := Y; SameLineCtrl.Add(Ctrl.Ctrl); if(assigned(ud)) then begin SameLineCtrl.Add(ud); if(assigned(HelpBtn)) then begin SameLineCtrl.Add(HelpBtn); Ctrl.Ctrl.Width := MinX - HelpBtn.Width - ud.Width; HelpBtn.Left := X + Ctrl.Ctrl.Width + ud.Width + Gap; HelpBtn.Top := Y; HelpBtn.Enabled := Prompt.FParent.Enabled; end else Ctrl.Ctrl.Width := MinX - ud.Width; ud.Left := X + Ctrl.Ctrl.Width; ud.Top := Y; LastX := X + MinX + PromptGap; ud.Enabled := Prompt.FParent.Enabled; end else if(HasVCombo) then begin SameLineCtrl.Add(Ctrl.vedt.LinkedCombo); Ctrl.Ctrl.Width := MinX - Ctrl.vedt.LinkedCombo.Width; Ctrl.vedt.LinkedCombo.Left := X + Ctrl.Ctrl.Width; Ctrl.vedt.LinkedCombo.Top := Y; LastX := X + MinX + PromptGap; Ctrl.vedt.LinkedCombo.Enabled := Prompt.FParent.Enabled; end else begin Ctrl.Ctrl.Width := MaxX; LastX := X + MaxX + PromptGap; end; end; end; end; if(assigned(ud)) then Prompt.FCurrentControl := ud else Prompt.FCurrentControl := Ctrl.Ctrl; end; NextLine(Y); finally SameLineCtrl.Free; end; end; procedure UpdatePrompts(EnablePanel: boolean; ClearCB: boolean); begin if EnablePanel then begin if not ScreenReaderSystemActive then begin pnl.TabStop := TRUE; {tab through the panels instead of the checkboxes} pnl.OnEnter := FieldPanelEntered; pnl.OnExit := FieldPanelExited; end; if ClearCB then cb := nil; end; if (FChecked and assigned(FPrompts) and (FPrompts.Count > 0)) then begin AddPrompts(FALSE, BaseParent, ParentWidth, Y); end else inc(Y, pnl.Height); end; begin Result := nil; cb := nil; pnl := nil; AutoFocusControl := nil; X := TrueIndent; if(assigned(FPrompts)) then begin for i := 0 to FPrompts.Count-1 do TRemPrompt(FPrompts[i]).FCurrentControl := nil; end; if(ElemType = etDisplayOnly) then begin if(FText <> '') then begin inc(Y,Gap); pnl := GetPanel(EntryID, CRLFText(FText), ParentWidth - X - (Gap * 2), nil); pnl.Left := X; pnl.Top := Y; UpdatePrompts(ScreenReaderSystemActive, TRUE); end; end else begin inc(Y,Gap); cb := TCPRSDialogParentCheckBox.Create(AOwner); cb.Parent := BaseParent; cb.Left := X; cb.Top := Y; cb.Tag := Integer(Self); cb.WordWrap := TRUE; cb.AutoSize := TRUE; cb.Checked := FChecked; cb.Width := ParentWidth - X - Gap; if not ScreenReaderSystemActive then cb.Caption := CRLFText(FText); cb.AutoAdjustSize; cbSingleLine := cb.SingleLine; // cb.AutoSize := FALSE; cb.WordWrap := FALSE; cb.Caption := ' '; // cb.Width := 13; // cb.Height := 17; if not ScreenReaderSystemActive then cb.TabStop := False; {take checkboxes out of the tab order} pnl := GetPanel(EntryID, CRLFText(FText), ParentWidth - X - (Gap * 2) - IndentGap, cb); pnl.Left := X + IndentGap; pnl.Top := Y; cb.Associate := pnl; pnl.Tag := Integer(cb); {So the panel can check the checkbox} cb.OnClick := cbClicked; cb.OnEnter := cbEntered; if ScreenReaderSystemActive then cb.OnExit := ParentCBExit; UpdateColorsFor508Compliance(cb); pnl.OnKeyPress := FieldPanelKeyPress; pnl.OnClick := FieldPanelOnClick; for i := 0 to pnl.ControlCount - 1 do if ((pnl.Controls[i] is TLabel) or (pnl.Controls[i] is TVA508StaticText)) and not (fsUnderline in TLabel(pnl.Controls[i]).Font.Style) then //If this isn't a hyperlink change then event handler TLabel(pnl.Controls[i]).OnClick := FieldPanelLabelOnClick; //cb.Enabled := Enabled; if(assigned(FParent) and (FParent.ChildrenRequired in [crOne, crNoneOrOne])) then cb.RadioStyle := TRUE; UpdatePrompts(TRUE, FALSE); end; if(ShowChildren) then begin gb := nil; if(Box) then begin gb := TGroupBox.Create(AOwner); gb.Parent := BaseParent; gb.Left := TrueIndent + (ChildrenIndent * IndentMult); gb.Top := Y; gb.Width := ParentWidth - gb.Left - Gap; PrntWidth := gb.Width - (Gap * 2); gb.Caption := BoxCaption; // if ScreenReaderSystemActive then // begin // ScreenReaderSystem_AddText(gb.Caption + ','); // end; gb.Enabled := EnableChildren; if(not EnableChildren) then gb.Font.Color := DisabledFontColor; UpdateColorsFor508Compliance(gb); prnt := gb; if(gb.Caption = '') then Y1 := gbTopIndent else Y1 := gbTopIndent2; end else begin prnt := BaseParent; Y1 := Y; PrntWidth := ParentWidth; end; for i := 0 to FChildren.Count-1 do begin ERes := TRemDlgElement(FChildren[i]).BuildControls(Y1, PrntWidth, prnt, AOwner); if(not assigned(Result)) then Result := ERes; end; if(FHasSharedPrompts) then AddPrompts(TRUE, prnt, PrntWidth, Y1); if(Box) then begin gb.Height := Y1 + (Gap * 3); inc(Y, Y1 + (Gap * 4)); end else Y := Y1; end; SubCommentChange(nil); if(assigned(AutoFocusControl)) then begin if(AutoFocusControl is TORComboBox) and (TORComboBox(AutoFocusControl).CheckBoxes) and (pos('1',TORComboBox(AutoFocusControl).CheckedString) = 0) then Result := AutoFocusControl else if(TORExposedControl(AutoFocusControl).Text = '') then Result := AutoFocusControl end; if ScreenReaderSystemActive then ScreenReaderSystem_Stop; end; //This is used to get the template field values if this reminder is not the //current reminder in dialog, in which case no uEntries will exist so we have //to get the template field values that were saved in the element. function TRemDlgElement.GetTemplateFieldValues(const Text: string; FldValues: TORStringList = nil): string; var flen, CtrlID, i, j: integer; Fld: TTemplateField; Temp, FldName, NewTxt: string; const TemplateFieldBeginSignature = '{FLD:'; TemplateFieldEndSignature = '}'; TemplateFieldSignatureLen = length(TemplateFieldBeginSignature); TemplateFieldSignatureEndLen = length(TemplateFieldEndSignature); FieldIDDelim = '`'; FieldIDLen = 6; procedure AddNewTxt; begin if(NewTxt <> '') then begin insert(StringOfChar('x',length(NewTxt)), Temp, i); insert(NewTxt, Result, i); inc(i, length(NewTxt)); end; end; begin Result := Text; Temp := Text; repeat i := pos(TemplateFieldBeginSignature, Temp); if(i > 0) then begin CtrlID := 0; if(copy(Temp, i + TemplateFieldSignatureLen, 1) = FieldIDDelim) then begin CtrlID := StrToIntDef(copy(Temp, i + TemplateFieldSignatureLen + 1, FieldIDLen-1), 0); delete(Temp,i + TemplateFieldSignatureLen, FieldIDLen); delete(Result,i + TemplateFieldSignatureLen, FieldIDLen); end; j := pos(TemplateFieldEndSignature, copy(Temp, i + TemplateFieldSignatureLen, MaxInt)); if(j > 0) then begin inc(j, i + TemplateFieldSignatureLen - 1); flen := j - i - TemplateFieldSignatureLen; FldName := copy(Temp, i + TemplateFieldSignatureLen, flen); Fld := GetTemplateField(FldName, FALSE); delete(Temp,i,flen + TemplateFieldSignatureLen + 1); delete(Result,i,flen + TemplateFieldSignatureLen + 1); end else begin delete(Temp,i,TemplateFieldSignatureLen); delete(Result,i,TemplateFieldSignatureLen); Fld := nil; end; // Get the value that was entered if there is one if assigned(FldValues) and (CtrlID > 0) then begin j := FldValues.IndexOfPiece(IntToStr(CtrlID)); if not(j<0) then if Fld.DateType in DateComboTypes then NewTxt := Piece(Piece(FldValues[j],U,2),':',1) else NewTxt := Piece(FldValues[j],U,2); end; // If nothing has been entered, use the default if (NewTxt = '') and assigned(Fld) and //If this template field is a dftHyperlink or dftText that is //excluded (FSepLines = True) then don't get the default text not ((Fld.FldType in [dftHyperlink, dftText]) and Fld.SepLines) then NewTxt := Fld.TemplateFieldDefault; AddNewTxt; end; until not (i > 0); end; procedure TRemDlgElement.AddText(Lst: TStrings); var i, ilvl: integer; Prompt: TRemPrompt; txt: string; FldData: TORStringList; begin if (not (FReminder is TReminder)) then ScootOver := 4; try if Add2PN then begin ilvl := IndentPNLevel; if(FPNText <> '') then txt := FPNText else begin txt := FText; if not FReminder.FNoResolve then //If this is the CurrentReminderInDialog then we get the template field //values from the visual control in the dialog window. if FReminder = CurrentReminderInDialog then txt := ResolveTemplateFields(txt, TRUE) else //If this is not the CurrentReminderInDialog (i.e.: Next or Back button //has been pressed), then we have to get the template field values //that were saved in the element. begin FldData := TORStringList.Create; GetFieldValues(FldData); txt := GetTemplateFieldValues(txt, FldData); end; end; if FReminder.FNoResolve then begin StripScreenReaderCodes(txt); Lst.Add(txt); end else WordWrap(txt, Lst, ilvl); dec(ilvl,2); if(assigned(FPrompts)) then begin for i := 0 to FPrompts.Count-1 do begin Prompt := TRemPrompt(FPrompts[i]); if(not Prompt.FIsShared) then begin if Prompt.PromptType = ptMHTest then WordWrap(Prompt.NoteText, Lst, ilvl, 4, true) else WordWrap(Prompt.NoteText, Lst, ilvl); end; end; end; if(assigned(FParent) and FParent.FHasSharedPrompts) then begin for i := 0 to FParent.FPrompts.Count-1 do begin Prompt := TRemPrompt(FParent.FPrompts[i]); if(Prompt.FIsShared) and (Prompt.FSharedChildren.IndexOf(Self) >= 0) then begin //AGP Change MH dll if (Prompt.PromptType = ptMHTest) then WordWrap(Prompt.NoteText, Lst, ilvl, 4, True) else WordWrap(Prompt.NoteText, Lst, ilvl); end; end; end; end; if (assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then begin for i := 0 to FChildren.Count-1 do begin TRemDlgElement(FChildren[i]).AddText(Lst); end; end; finally if (not (FReminder is TReminder)) then ScootOver := 0; end; end; function TRemDlgElement.AddData(Lst: TStrings; Finishing: boolean; AHistorical: boolean = FALSE): integer; var i, j: integer; OK: boolean; ActDt, InActDt, EncDt: double; RData: TRemData; begin Result := 0; // OK := ((ElemType <> etDisplayOnly) and FChecked); OK := FChecked; if(OK and Finishing) then OK := (Historical = AHistorical); if OK then begin if(assigned(FData)) then begin if Self.Historical then EncDt := DateTimeToFMDateTime(Date) else EncDt := RemForm.PCEObj.VisitDateTime; for i := 0 to FData.Count-1 do begin RData := TRemData(FData[i]); if assigned(RData.FActiveDates) then for j := 0 to (TRemData(FData[i]).FActiveDates.Count - 1) do begin ActDt := StrToIntDef(Piece(TRemData(FData[i]).FActiveDates[j],':',1), 0); InActDt := StrToIntDef(Piece(TRemData(FData[i]).FActiveDates[j], ':', 2), 9999999); if (EncDt >= ActDt) and (EncDt <= InActDt) then begin inc(Result, TRemData(FData[i]).AddData(Lst, Finishing)); Break; end; end else inc(Result, TRemData(FData[i]).AddData(Lst, Finishing)); end; end; end; if (assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then begin for i := 0 to FChildren.Count-1 do inc(Result, TRemDlgElement(FChildren[i]).AddData(Lst, Finishing, AHistorical)); end; end; procedure TRemDlgElement.Check4ChildrenSharedPrompts; var i, j: integer; Kid: TRemDlgElement; PList, EList: TList; FirstMatch: boolean; Prompt: TRemPrompt; begin if(not FChildrenShareChecked) then begin FChildrenShareChecked := TRUE; if(ChildrenSharePrompts and assigned(FChildren)) then begin for i := 0 to FChildren.Count-1 do TRemDlgElement(FChildren[i]).GetData; PList := TList.Create; try EList := TList.Create; try for i := 0 to FChildren.Count-1 do begin Kid := TRemDlgElement(FChildren[i]); // if(Kid.ElemType <> etDisplayOnly) and (assigned(Kid.FPrompts)) then if(assigned(Kid.FPrompts)) then begin for j:= 0 to Kid.FPrompts.Count-1 do begin PList.Add(Kid.FPrompts[j]); EList.Add(Kid); end; end; end; if(PList.Count > 1) then begin for i := 0 to PList.Count-2 do begin if(assigned(EList[i])) then begin FirstMatch := TRUE; Prompt := TRemPrompt(PList[i]); for j := i+1 to PList.Count-1 do begin if(assigned(EList[j]) and (Prompt.CanShare(TRemPrompt(PList[j])))) then begin if(FirstMatch) then begin FirstMatch := FALSE; if(not assigned(FPrompts)) then FPrompts := TList.Create; FHasSharedPrompts := TRUE; Prompt.FIsShared := TRUE; if(not assigned(Prompt.FSharedChildren)) then Prompt.FSharedChildren := TList.Create; Prompt.FSharedChildren.Add(EList[i]); FPrompts.Add(PList[i]); TRemDlgElement(EList[i]).FPrompts.Remove(PList[i]); EList[i] := nil; end; Prompt.FSharedChildren.Add(EList[j]); Kid := TRemDlgElement(EList[j]); Kid.FPrompts.Remove(PList[j]); if(Kid.FHasComment) and (Kid.FCommentPrompt = PList[j]) then begin Kid.FHasComment := FALSE; Kid.FCommentPrompt := nil; end; TRemPrompt(PList[j]).Free; EList[j] := nil; end; end; end; end; end; finally EList.Free; end; finally PList.Free; end; for i := 0 to FChildren.Count-1 do begin Kid := TRemDlgElement(FChildren[i]); if(assigned(Kid.FPrompts) and (Kid.FPrompts.Count = 0)) then begin Kid.FPrompts.Free; Kid.FPrompts := nil; end; end; end; end; end; procedure TRemDlgElement.FinishProblems(List: TStrings); var i,cnt: integer; cReq: TRDChildReq; Kid: TRemDlgElement; Prompt: TRemPrompt; txt, msg, Value: string; pt: TRemPromptType; begin // if(ElemType <> etDisplayOnly) and (FChecked) and (assigned(FPrompts)) then if(FChecked and (assigned(FPrompts))) then begin for i := 0 to FPrompts.Count-1 do begin Prompt := TRemPrompt(FPrompts[i]); Value := Prompt.GetValue; pt := Prompt.PromptType; if(Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and (((pt<>ptWHNotPurp)and(pt<>ptWHPapResult))and ((Value = '') or (Value = '@')) or ((pt = ptVisitDate) and Prompt.FMonthReq and (StrToIntDef(copy(Value,4,2),0) = 0)) or ((pt in [ptVisitDate, ptVisitLocation]) and (Value = '0')))) then begin WordWrap('Element: ' + FText, List, 68, 6); txt := Prompt.ForcedCaption; if(pt = ptVisitDate) and Prompt.FMonthReq then txt := txt + ' (Month Required)'; WordWrap('Item: ' + txt, List, 65, 6); end; if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and ((WHResultChk='') and (Value='')) and ((pt=ptWHPapResult) and (FData<>nil))) then begin WordWrap('Prompt: ' + Prompt.ForcedCaption, List, 65,6); end; if (Prompt.PromptOK and (not Prompt.Forced) and Prompt.Required and (pt=ptWHNotPurp)) and ((WHResultNot = '') and (Value = '')) then begin WordWrap('Element: ' + FText, List, 68, 6); WordWrap('Prompt: ' + Prompt.ForcedCaption, List, 65,6); end; //(AGP Change 24.9 add check to see if MH tests are required) if ((Pt = ptMHTest) or (Pt = ptGAF)) and (StrtoInt(Piece(Prompt.FData.FRec3,U,13)) > 0) and (not Prompt.Forced) then begin if (Piece(Prompt.FData.FRec3,U,13) = '2') and (Prompt.FMHTestComplete = 0) then break; if (Pt = ptMHTest) and (Prompt.FMHTestComplete = 2) then begin if ((Prompt.FValue = '') or (pos('X',Prompt.FValue)>0)) then begin if Prompt.FValue = '' then WordWrap('MH test '+ Piece(Prompt.FData.FRec3,U,8) + ' not done',List,65,6); if pos('X',Prompt.FValue)>0 then WordWrap('You are missing one or more responses in the MH test '+ Piece(Prompt.FData.FRec3,U,8),List,65,6); WordWrap(' ',List,65,6); end; end; if (Pt = ptMHTest) and (Prompt.FMHTestComplete = 0) or ((Prompt.FValue = '') and (Pos('New MH dll',Prompt.FValue) = 0)) then begin if Prompt.FValue = '' then WordWrap('MH test '+ Piece(Prompt.FData.FRec3,U,8) + ' not done',List,65,6); if pos('X',Prompt.FValue)>0 then WordWrap('You are missing one or more responses in the MH test '+ Piece(Prompt.FData.FRec3,U,8),List,65,6); WordWrap(' ',List,65,6); end; if (Pt = ptMHTest) and (Prompt.FMHTestComplete = 0) and (Pos('New MH dll',Prompt.FValue) > 0) then begin WordWrap('MH test ' + Piece(Prompt.FData.FRec3, U, 8) + ' is not complete', List, 65, 6); WordWrap(' ',List,65,6); end; if (Pt = ptGAF) and ((Prompt.FValue = '0') or (Prompt.FValue = '')) then begin WordWrap('GAF test must have a score greater then zero',List,65,6); WordWrap(' ',List,65,6); end; end; end; end; if (assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then begin cReq := ChildrenRequired; if(cReq in [crOne, crAtLeastOne, crAll]) then begin cnt := 0; for i := 0 to FChildren.Count-1 do begin Kid := TRemDlgElement(FChildren[i]); // if(Kid.FChecked and (Kid.ElemType <> etDisplayOnly)) then if(Kid.FChecked) then inc(cnt); end; if(cReq = crOne) and (cnt <> 1) then msg := 'One selection required' else if(cReq = crAtLeastOne) and (cnt < 1) then msg := 'One or more selections required' else if (cReq = crAll) and (cnt < FChildren.Count) then msg := 'All selections are required' else msg := ''; if(msg <> '') then begin txt := BoxCaption; if(txt = '') then txt := FText; WordWrap('Group: ' + txt, List, 68, 6); WordWrap(Msg, List, 65, 0); WordWrap(' ',List,68,6); // (AGP change 24.9 added blank line for display spacing) end; end; for i := 0 to FChildren.Count-1 do TRemDlgElement(FChildren[i]).FinishProblems(List); end; end; function TRemDlgElement.IsChecked: boolean; var Prnt: TRemDlgElement; begin Result := TRUE; Prnt := Self; while Result and assigned(Prnt) do begin Result := ((Prnt.ElemType = etDisplayOnly) or Prnt.FChecked); Prnt := Prnt.FParent; end; end; //agp ICD-10 add this function to scan for valid codes against encounter date. function TRemDlgElement.oneValidCode(Choices: TORStringList; ChoicesActiveDates: TList; encDt: TFMDateTime): string; var C,cnt, lastItem: integer; Prompt: TRemPrompt; begin cnt := 0; Result := ''; Prompt := TRemPrompt.Create(); lastItem := 0; for c := 0 to Choices.Count - 1 do begin if (Prompt.CompareActiveDate(TStringList(ChoicesActiveDates[C]), encDt) = TRUE) then begin cnt := cnt + 1; lastItem := c; if (cnt>1) then break; end; end; if (cnt = 1) then Result := Choices[lastItem]; end; function TRemDlgElement.IndentChildrenInPN: boolean; begin //if(Box) then Result := (Piece(FRec1, U, 21) = '1'); //else // Result := FALSE; end; function TRemDlgElement.IndentPNLevel: integer; begin if(assigned(FParent)) then begin Result := FParent.IndentPNLevel; if(FParent.IndentChildrenInPN) then dec(Result,2); end else Result := 70; end; function TRemDlgElement.IncludeMHTestInPN: boolean; begin Result := (Piece(FRec1, U, 9) = '0'); end; function TRemDlgElement.ResultDlgID: string; begin Result := Piece(FRec1, U, 10); end; procedure TRemDlgElement.setActiveDates(Choices: TORStringList; ChoicesActiveDates: TList; ActiveDates: TStringList); var c: integer; begin for c := 0 to Choices.Count - 1 do begin ActiveDates.Add(TStringList(ChoicesActiveDates[C]).CommaText) end; end; procedure TRemDlgElement.SubCommentChange(Sender: TObject); var i: integer; txt: string; ok: boolean; begin if(FHasSubComments and FHasComment and assigned(FCommentPrompt)) then begin ok := FALSE; if(assigned(Sender)) then begin with (Sender as TORCheckBox) do TRemPrompt(Tag).FValue := BOOLCHAR[Checked]; ok := TRUE; end; if(not ok) then ok := (FCommentPrompt.GetValue = ''); if(ok) then begin txt := ''; for i := 0 to FPrompts.Count-1 do begin with TRemPrompt(FPrompts[i]) do begin if(PromptType = ptSubComment) and (FValue = BOOLCHAR[TRUE]) then begin if(txt <> '') then txt := txt + ', '; txt := txt + Caption; end; end; end; if(txt <> '') then txt[1] := UpCase(txt[1]); FCommentPrompt.SetValue(txt); end; end; end; constructor TRemDlgElement.Create; begin FFieldValues := TORStringList.Create; end; function TRemDlgElement.EntryID: string; begin Result := REMEntryCode + FReminder.GetIEN + '/' + IntToStr(integer(Self)); end; procedure TRemDlgElement.FieldPanelChange(Sender: TObject); var idx: integer; Entry: TTemplateDialogEntry; fval: string; begin FReminder.BeginTextChanged; try Entry := TTemplateDialogEntry(Sender); idx := FFieldValues.IndexOfPiece(Entry.InternalID); fval := Entry.InternalID + U + Entry.FieldValues; if(idx < 0) then FFieldValues.Add(fval) else FFieldValues[idx] := fval; finally FReminder.EndTextChanged(Sender); end; end; procedure TRemDlgElement.GetFieldValues(FldData: TStrings); var i, p: integer; TmpSL: TStringList; begin TmpSL := TStringList.Create; try for i := 0 to FFieldValues.Count-1 do begin p := pos(U, FFieldValues[i]); // Can't use Piece because 2nd piece may contain ^ characters if(p > 0) then begin TmpSL.CommaText := copy(FFieldValues[i],p+1,MaxInt); FastAddStrings(TmpSL, FldData); TmpSL.Clear; end; end; finally TmpSL.Free; end; if (assigned(FChildren)) and (FChecked or (ElemType = etDisplayOnly)) then for i := 0 to FChildren.Count-1 do TRemDlgElement(FChildren[i]).GetFieldValues(FldData); end; {cause the paint event to be called and draw a focus rectangle on the TFieldPanel} procedure TRemDlgElement.FieldPanelEntered(Sender: TObject); begin with TDlgFieldPanel(Sender) do begin Focus := TRUE; Invalidate; if Parent is TDlgFieldPanel then begin TDlgFieldPanel(Parent).Focus := FALSE; TDlgFieldPanel(Parent).Invalidate; end; end; end; {cause the paint event to be called and draw the TFieldPanel without the focus rect.} procedure TRemDlgElement.FieldPanelExited(Sender: TObject); begin with TDlgFieldPanel(Sender) do begin Focus := FALSE; Invalidate; if Parent is TDlgFieldPanel then begin TDlgFieldPanel(Parent).Focus := TRUE; TDlgFieldPanel(Parent).Invalidate; end; end; end; {Check the associated checkbox when spacebar is pressed} procedure TRemDlgElement.FieldPanelKeyPress(Sender: TObject; var Key: Char); begin if Key = ' ' then begin FieldPanelOnClick(Sender); Key := #0; end; end; {So the FieldPanel will check the associated checkbox} procedure TRemDlgElement.FieldPanelOnClick(Sender: TObject); begin // if TFieldPanel(Sender).Focus then TORCheckBox(TDlgFieldPanel(Sender).Tag).Checked := not FChecked; end; {call the FieldPanelOnClick so labels on the panels will also click the checkbox} procedure TRemDlgElement.FieldPanelLabelOnClick(Sender: TObject); begin FieldPanelOnClick(TLabel(Sender).Parent); {use the parent/fieldpanel as the Sender} end; { TRemData } function TRemData.Add2PN: boolean; begin Result := (Piece(FRec3, U, 5) <> '1'); end; function TRemData.AddData(List: TStrings; Finishing: boolean): integer; var i, j, k: integer; PCECat: TPCEDataCat; Primary: boolean; ActDt, InActDt: Double; EncDt: TFMDateTime; procedure AddPrompt(Prompt: TRemPrompt; dt: TRemDataType; var x: string); var pt: TRemPromptType; pnum: integer; Pdt: TRemDataType; v: TVitalType; rte, unt, txt: string; UIEN: Int64; begin pnum := -1; pt := Prompt.PromptType; if(pt = ptSubComment) or (pt = ptUnknown) then exit; if(pt = ptMST) then begin if (PCECat in MSTDataTypes) then begin UIEN := FParent.FReminder.PCEDataObj.Providers.PCEProvider; if UIEN <= 0 then UIEN := User.DUZ; SetPiece(x, U, pnumMST, Prompt.GetValue + ';' + // MST Code FloatToStr(RemForm.PCEObj.VisitDateTime) + ';' + IntToStr(UIEN) + ';' + // Prompt.FMiscText); // IEN of Exam, if any end; end else if(PCECat = pdcVital) then begin if(pt = ptVitalEntry) then begin rte := Prompt.VitalValue; if(rte <> '') then begin v := Prompt.VitalType; unt := Prompt.VitalUnitValue; ConvertVital(v, rte, unt); //txt := U + VitalCodes[v] + U + rte + U + FloatToStr(RemForm.PCEObj.VisitDateTime); AGP Change 26.1 commented out txt := U + VitalCodes[v] + U + rte + U + '0'; //AGP Change 26.1 Use for Vital date/time if(not Finishing) then txt := Char(ord('A')+ord(v)) + FormatVitalForNote(txt); // Add vital sort char List.AddObject(Char(ord('A')+ord(PCECat)) + txt, Self); end; end else exit; end else if(PCECat = pdcMH) then begin if(pt = ptMHTest) or (pt = ptGAF) then x := x + U + Prompt.GetValue else exit; end else if(pt <> ptDataList) and (ord(pt) >= ord(low(TRemPromptType))) then begin Pdt := RemPromptTypes[pt]; if (Pdt = dt) or (Pdt = dtAll) or ((Pdt = dtHistorical) and assigned(Prompt.FParent) and Prompt.FParent.Historical) then pnum := FinishPromptPieceNum[pt]; if(pnum > 0) then begin if(pt = ptPrimaryDiag) then SetPiece(x, U, pnum, BoolChar[Primary]) else SetPiece(x, U, pnum, Prompt.GetValue); end; end; end; procedure Add(Str: string; Root: TRemPCERoot); var i, Qty: integer; Value, IsGAF, txt, x, Code, Nar, Cat: string; Skip: boolean; Prompt: TRemPrompt; dt: TRemDataType; TestDate: TFMDateTime; i1,i2: integer; begin x := ''; dt := Code2DataType(Piece(Str, U, r3Type)); PCECat := RemData2PCECat[dt]; Code := Piece(Str, U, r3Code); if(Code = '') then Code := Piece(Str, U, r3Code2); Nar := Piece(Str, U, r3Nar); Cat := Piece(Str, U, r3Cat); Primary := FALSE; if(assigned(FParent) and assigned(FParent.FPrompts) and (PCECat = pdcDiag)) then begin if(FParent.Historical) then begin for i := 0 to FParent.FPrompts.Count-1 do begin Prompt := TRemPrompt(FParent.FPrompts[i]); if(Prompt.PromptType = ptPrimaryDiag) then begin Primary := (Prompt.GetValue = BOOLCHAR[TRUE]); break; end; end; end else Primary := (Root = PrimaryDiagRoot); end; Skip := FALSE; if (PCECat = pdcMH) then begin IsGAF := Piece(FRec3, U, r3GAF); Value := FChoicePrompt.GetValue; if(Value = '') or ((IsGAF = '1') and (Value = '0')) then Skip := TRUE; end; if Finishing or (PCECat = pdcVital) then begin if(dt = dtOrder) then x := U + Piece(Str,U,6) + U + Piece(Str,U,11) + U + Nar else begin if (PCECat = pdcMH) then begin if(Skip) then x := '' else begin TestDate := Trunc(FParent.FReminder.PCEDataObj.VisitDateTime); if(IsGAF = '1') then ValidateGAFDate(TestDate); x := U + Nar + U + IsGAF + U + FloatToStr(TestDate) + U + IntToSTr(FParent.FReminder.PCEDataObj.Providers.PCEProvider); end; end else if (PCECat <> pdcVital) then begin x := Piece(Str, U, 6); SetPiece(x, U, pnumCode, Code); SetPiece(x, U, pnumCategory, Cat); SetPiece(x, U, pnumNarrative, Nar); end; if(assigned(FParent)) then begin if(assigned(FParent.FPrompts)) then begin for i := 0 to FParent.FPrompts.Count-1 do begin Prompt := TRemPrompt(FParent.FPrompts[i]); if(not Prompt.FIsShared) then AddPrompt(Prompt, dt, x); end; end; if(assigned(FParent.FParent) and FParent.FParent.FHasSharedPrompts) then begin for i := 0 to FParent.FParent.FPrompts.Count-1 do begin Prompt := TRemPrompt(FParent.FParent.FPrompts[i]); if(Prompt.FIsShared) and (Prompt.FSharedChildren.IndexOf(FParent) >= 0) then AddPrompt(Prompt, dt, x); end; end; end; end; if(x <> '') then List.AddObject(Char(ord('A')+ord(PCECat)) + x, Self); end else begin Qty := 1; if(assigned(FParent) and assigned(FParent.FPrompts)) then begin if(PCECat = pdcProc) then begin for i := 0 to FParent.FPrompts.Count-1 do begin Prompt := TRemPrompt(FParent.FPrompts[i]); if(Prompt.PromptType = ptQuantity) then begin Qty := StrToIntDef(Prompt.GetValue, 1); if(Qty < 1) then Qty := 1; break; end; end; end; end; if (not Skip) then begin txt := Char(ord('A')+ord(PCECat)) + GetPCEDataText(PCECat, Code, Cat, Nar, Primary, Qty); if(assigned(FParent) and FParent.Historical) then txt := txt + ' (Historical)'; List.AddObject(txt, Self); inc(Result); end; if assigned(FParent) and assigned(FParent.FMSTPrompt) then begin txt := FParent.FMSTPrompt.Value; if txt <> '' then begin if FParent.FMSTPrompt.FMiscText = '' then begin i1 := 0; i2 := 2; end else begin i1 := 3; i2 := 4; end; for i := i1 to i2 do if txt = MSTDescTxt[i,1] then begin List.AddObject(Char( ord('A') + ord(pdcMST)) + MSTDescTxt[i,0], Self); break; end; end; end; end; end; begin Result := 0; if(assigned(FChoicePrompt)) and (assigned(FChoices)) then begin If not assigned(FChoicesActiveDates) then begin for i := 0 to FChoices.Count - 1 do begin if (copy(FChoicePrompt.GetValue, i+1, 1) = '1') then Add(FChoices[i], TRemPCERoot(FChoices.Objects[i])) end end else {if there are active dates for each choice then check them} begin If Self.FParent.Historical then EncDt := DateTimeToFMDateTime(Date) else EncDt := RemForm.PCEObj.VisitDateTime; k := 0; for i := 0 to FChoices.Count - 1 do begin for j := 0 to (TStringList(Self.FChoicesActiveDates[i]).Count - 1) do begin ActDt := StrToIntDef((Piece(TStringList(Self.FChoicesActiveDates[i]).Strings[j], ':', 1)),0); InActDt := StrToIntDef((Piece(TStringList(Self.FChoicesActiveDates[i]).Strings[j], ':', 2)),9999999); if (EncDt >= ActDt) and (EncDt <= InActDt) then begin if(copy(FChoicePrompt.GetValue, k+1,1) = '1') then Add(FChoices[i], TRemPCERoot(FChoices.Objects[i])); inc(k); end; {Active date check} end; {FChoicesActiveDates.Items[i] loop} end; {FChoices loop} end {FChoicesActiveDates check} end {FChoicePrompt and FChoices check} else Add(FRec3, FPCERoot); {Active dates for this are checked in TRemDlgElement.AddData} end; function TRemData.Category: string; begin Result := Piece(FRec3, U, r3Cat); end; function TRemData.DataType: TRemDataType; begin Result := Code2DataType(Piece(FRec3, U, r3Type)); end; destructor TRemData.Destroy; var i: integer; begin if(assigned(FPCERoot)) then FPCERoot.Done(Self); if(assigned(FChoices)) then begin for i := 0 to FChoices.Count-1 do begin if(assigned(FChoices.Objects[i])) then TRemPCERoot(FChoices.Objects[i]).Done(Self); end; end; KillObj(@FChoices); inherited; end; function TRemData.DisplayWHResults: boolean; begin Result :=False; if FRec3<>'' then Result := (Piece(FRec3, U, 6) <> '0'); end; function TRemData.ExternalValue: string; begin Result := Piece(FRec3, U, r3Code); end; function TRemData.InternalValue: string; begin Result := Piece(FRec3, U, 6); end; function TRemData.Narrative: string; begin Result := Piece(FRec3, U, r3Nar); end; { TRemPrompt } function TRemPrompt.Add2PN: boolean; begin Result := FALSE; if (not Forced) and (PromptOK) then //if PromptOK then Result := (Piece(FRec4, U, 5) <> '1'); if (Result=false) and (Piece(FRec4,U,4)='WH_NOT_PURP') then Result := True; end; function TRemPrompt.Caption: string; begin Result := Piece(FRec4, U, 8); if(not FCaptionAssigned) then begin AssignFieldIDs(Result); SetPiece(FRec4, U, 8, Result); FCaptionAssigned := TRUE; end; end; constructor TRemPrompt.Create; begin FOverrideType := ptUnknown; end; function TRemPrompt.Forced: boolean; begin Result := (Piece(FRec4, U, 7) = 'F'); end; function TRemPrompt.InternalValue: string; var m, d, y: word; Code: string; begin Result := Piece(FRec4, U, 6); Code := Piece(FRec4, U, 4); if(Code = RemPromptCodes[ptVisitDate]) then begin if(copy(Result,1,1) = MonthReqCode) then begin FMonthReq := TRUE; delete(Result,1,1); end; if(Result = '') then begin DecodeDate(Now, y, m, d); Result := inttostr(y-1700)+'0000'; SetPiece(FRec4, U, 6, Result); end; end; end; procedure TRemPrompt.PromptChange(Sender: TObject); var cbo: TORComboBox; pt: TRemPromptType; TmpValue, OrgValue: string; idx, i: integer; NeedRedraw: boolean; dte: TFMDateTime; whCKB: TWHCheckBox; //printoption: TORCheckBox; WHValue, WHValue1: String; begin FParent.FReminder.BeginTextChanged; try FFromControl := TRUE; try TmpValue := GetValue; OrgValue := TmpValue; pt := PromptType; NeedRedraw := FALSE; case pt of ptComment, ptQuantity: TmpValue := (Sender as TEdit).Text; ptVisitDate: begin dte := (Sender as TORDateCombo).FMDate; while (dte > 2000000) and (dte > FMToday) do begin dte := dte - 10000; NeedRedraw := TRUE; end; TmpValue := FloatToStr(dte); if(TmpValue = '1000000') then TmpValue := '0'; end; ptPrimaryDiag, ptAdd2PL, ptContraindicated: begin TmpValue := BOOLCHAR[(Sender as TORCheckBox).Checked]; NeedRedraw := (pt = ptPrimaryDiag); end; ptVisitLocation: begin cbo := (Sender as TORComboBox); if(cbo.ItemIEN < 0) then NeedRedraw := (not cbo.DroppedDown) else begin if(cbo.ItemIndex <= 0) then cbo.Items[0] := '0' + U + cbo.text; TmpValue := cbo.ItemID; if(StrToIntDef(TmpValue,0) = 0) then TmpValue := cbo.Text; end; end; ptWHPapResult: begin if (Sender is TWHCheckBox) then begin whCKB := (Sender as TWHCheckBox); if whCKB.Checked = true then begin if whCKB.Caption ='NEM (No Evidence of Malignancy)' then FParent.WHResultChk := 'N'; if whCKB.Caption ='Abnormal' then FParent.WHResultChk := 'A'; if whCKB.Caption ='Unsatisfactory for Diagnosis' then FParent.WHResultChk := 'U'; //AGP Change 23.13 WH multiple processing for i := 0 to FParent.FData.Count-1 do begin if Piece(TRemData(FParent.FData[i]).FRec3,U,4)='WHR' then begin FParent.FReminder.WHReviewIEN := Piece(TRemData(FParent.FData[i]).FRec3,U,6) end; end; end else begin FParent.WHResultChk := ''; FParent.FReminder.WHReviewIEN := ''; //AGP CHANGE 23.13 end; end; end; ptWHNotPurp: begin if (Sender is TWHCheckBox) then begin whCKB := (Sender as TWHCheckBox); if whCKB.Checked = true then begin if whCKB.Caption ='Letter' then begin if FParent.WHResultNot='' then FParent.WHResultNot := 'L' else if Pos('L',FParent.WHResultNot)=0 then FParent.WHResultNot := FParent.WHResultNot +':L'; if whCKB.FButton <> nil then whCKB.FButton.Enabled := true; if whCKB.FPrintNow <> nil then begin whCKB.FPrintVis :='1'; whCKB.FPrintNow.Enabled := true; end; end; if whCKB.Caption ='In-Person' then begin if FParent.WHResultNot='' then FParent.WHResultNot := 'I' else if Pos('I',FParent.WHResultNot)=0 then FParent.WHResultNot := FParent.WHResultNot+':I'; end; if whCKB.Caption ='Phone Call' then begin if FParent.WHResultNot='' then FParent.WHResultNot := 'P' else if Pos('P',FParent.WHResultNot)=0 then FParent.WHResultNot := FParent.WHResultNot+':P'; end; end else begin // this section is to handle unchecking of boxes and disabling print now and view button WHValue := FParent.WHResultNot; if whCKB.Caption ='Letter' then begin for i:=1 to Length(WHValue) do begin if WHValue1='' then begin if (WHValue[i]<>'L') and (WHValue[i]<>':') then WHValue1 := WHValue[i]; end else if (WHValue[i]<>'L') and (WHValue[i]<>':') then WHValue1 := WHValue1+':'+WHValue[i]; end; if (whCKB.FButton <> nil) and (whCKB.FButton.Enabled = true) then whCKB.FButton.Enabled := false; if (whCKB.FPrintNow <> nil) and (whCKB.FPrintNow.Enabled = true) then begin whCKB.FPrintVis := '0'; if whCKB.FPrintNow.Checked = true then whCKB.FPrintNow.Checked := false; whCKB.FPrintNow.Enabled := false; FParent.WHPrintDevice := ''; end; end; if whCKB.Caption ='In-Person' then begin for i:=1 to Length(WHValue) do begin if WHValue1='' then begin if (WHValue[i]<>'I') and (WHValue[i]<>':') then WHValue1 := WHValue[i]; end else if (WHValue[i]<>'I') and (WHValue[i]<>':') then WHValue1 := WHValue1+':'+WHValue[i]; end; end; if whCKB.Caption ='Phone Call' then begin for i:=1 to Length(WHValue) do begin if WHValue1='' then begin if (WHValue[i]<>'P') and (WHValue[i]<>':') then WHValue1 := WHValue[i]; end else if (WHValue[i]<>'P') and (WHValue[i]<>':') then WHValue1 := WHValue1+':'+WHValue[i]; end; end; FParent.WHResultNot := WHValue1; end; end else if ((Sender as TORCheckBox)<>nil) and (Piece(FRec4,U,12)='1') then begin if (((Sender as TORCheckBox).Caption = 'Print Now') and ((Sender as TORCheckBox).Enabled =true)) and ((Sender as TORCheckBox).Checked = true) and (FParent.WHPrintDevice ='') then begin FParent.WHPrintDevice := SelectDevice(Self, Encounter.Location, false, 'Women Health Print Device Selection'); FPrintNow :='1'; if FParent.WHPrintDevice ='' then begin FPrintNow :='0'; (Sender as TORCheckBox).Checked := false; end; end; if (((Sender as TORCheckBox).Caption = 'Print Now') and ((Sender as TORCheckBox).Enabled =true)) and ((Sender as TORCheckBox).Checked = false) then begin FParent.WHPrintDevice := ''; FPrintNow :='0'; end; end; end; ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction, ptLevelUnderstanding, ptSkinReading: //(AGP Change 26.1) TmpValue := (Sender as TORComboBox).ItemID; else if pt = ptVitalEntry then begin case (Sender as TControl).Tag of TAG_VITTEMPUNIT, TAG_VITHTUNIT, TAG_VITWTUNIT: idx := 2; TAG_VITPAIN: begin idx := -1; TmpValue := (Sender as TORComboBox).ItemID; if FParent.VitalDateTime = 0 then FParent.VitalDateTime := FMNow; end; else idx := 1; end; if(idx > 0) then begin //AGP Change 26.1 change Vital time/date to Now instead of encounter date/time SetPiece(TmpValue, ';', idx, TORExposedControl(Sender).Text); if (FParent.VitalDateTime > 0) and (TORExposedControl(Sender).Text = '') then FParent.VitalDateTime := 0; if (FParent.VitalDateTime = 0) and (TORExposedControl(Sender).Text <> '') then FParent.VitalDateTime := FMNow; end; end else if pt = ptDataList then begin TmpValue := (Sender as TORComboBox).CheckedString; NeedRedraw := TRUE; end else if (pt = ptGAF) and (MHDLLFound = false) then TmpValue := (Sender as TEdit).Text; end; if(TmpValue <> OrgValue) then begin if NeedRedraw then FParent.FReminder.BeginNeedRedraw; try SetValue(TmpValue); finally if NeedRedraw then FParent.FReminder.EndNeedRedraw(Self); end; end else if NeedRedraw then begin FParent.FReminder.BeginNeedRedraw; FParent.FReminder.EndNeedRedraw(Self); end; finally FFromControl := FALSE; end; finally FParent.FReminder.EndTextChanged(Sender); end; if(FParent.ElemType = etDisplayOnly) and (not assigned(FParent.FParent)) then RemindersInProcess.Notifier.Notify; end; procedure TRemPrompt.ComboBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if(Key = VK_RETURN) and (Sender is TORComboBox) and ((Sender as TORComboBox).DroppedDown) then (Sender as TORComboBox).DroppedDown := FALSE; end; function TRemPrompt.PromptOK: boolean; var pt: TRemPromptType; dt: TRemDataType; C, i: integer; encDate: TFMDateTime; begin pt := PromptType; if (pt = ptUnknown) or (pt = ptMST) then Result := FALSE else if (pt = ptDataList) or (pt = ptVitalEntry) or (pt = ptMHTest) or (pt = ptGAF) or (pt = ptWHPapResult) then Result := TRUE else if (pt = ptSubComment) then Result := FParent.FHasComment else begin dt := RemPromptTypes[PromptType]; if (dt = dtAll) then Result := TRUE else if (dt = dtUnknown) then Result := FALSE else if (dt = dtHistorical) then Result := FParent.Historical //hanlde combo box prompts that are not assocaite with codes else if ( dt <> dtProcedure) and (dt <> dtDiagnosis) then begin Result := FALSE; if(assigned(FParent.FData)) then begin for i := 0 to FParent.FData.Count - 1 do begin if (TRemData(FParent.FData[i]).DataType = dt) then begin Result := TRUE; break; end; end; end; end else // agp ICD10 change to screen out prompts if taxonomy does not contain active codes for the encounter date. // historical values override the date check. begin Result := FALSE; if (Assigned(FParent.FData)) then begin for i := 0 to FParent.FData.Count - 1 do begin if (TRemData(FParent.FData[i]).DataType = dt) then begin if (FParent.Historical) then begin Result := TRUE; break; end else if (TRemData(FParent.FData[i]).FActiveDates <> nil) then begin encDate := TRemData(FParent.FData[i]).FParent.FReminder.FPCEDataObj.DateTime; if (RemDataActive(TRemData(FParent.FData[i]), encDate) = TRUE) then Result := TRUE; break; end // else if (Assigned(TRemData(FParent.FData[i]).FChoices) and (TRemData(FParent.FData[i]).FChoices <> nil)) then else if Assigned(TRemData(FParent.FData[i]).FChoices) then begin encDate := TRemData(FParent.FData[i]).FParent.FReminder.FPCEDataObj.DateTime; for C := 0 to TRemData(FParent.FData[i]).FChoices.Count - 1 do begin if (CompareActiveDate(TStringList(TRemData(FParent.FData[i]).FChoicesActiveDates[C]), encDate) = TRUE) then begin Result := TRUE; break; end; end; end; // Result := TRUE; // break; end; end; end; end; end; end; function TRemPrompt.PromptType: TRemPromptType; begin if(assigned(FData)) then Result := FOverrideType else Result := Code2PromptType(Piece(FRec4, U, 4)); end; function TRemPrompt.Required: boolean; var pt: TRemPromptType; begin pt := PromptType; if(pt = ptVisitDate) then Result := TRUE else if(pt = ptSubComment) then Result := FALSE else Result := (Piece(FRec4, U, 10) = '1'); end; function TRemPrompt.SameLine: boolean; begin Result := (Piece(FRec4, U, 9) <> '1'); end; function TRemPrompt.NoteText: string; var pt: TRemPromptType; dateStr, fmt, tmp, WHValue: string; cnt, i, j, k: integer; ActDt, InActDt: Double; EncDt: TFMDateTime; begin Result := ''; if Add2PN then begin pt := PromptType; tmp := GetValue; case pt of ptComment: Result := tmp; ptQuantity: if(StrToIntDef(tmp,1) <> 1) then Result := tmp; (* ptSkinReading: if(StrToIntDef(tmp,0) <> 0) then Result := tmp; *) ptSkinReading: // (AGP Change 26.1) begin Result := tmp; end; ptVisitDate: begin try if(tmp <> '') and (tmp <> '0') and (length(Tmp) = 7) then begin dateStr := ''; if FMonthReq and (copy(tmp,4,2) = '00') then Result := '' else begin if(copy(tmp,4,4) = '0000') then begin fmt := 'YYYY'; dateStr := ' – Exact date is unknown'; end else if(copy(tmp,6,2) = '00') then begin fmt := 'MMMM, YYYY'; dateStr := ' – Exact date is unknown'; end else fmt := 'MMMM D, YYYY'; if dateStr = '' then Result := FormatFMDateTimeStr(fmt, tmp) else Result := FormatFMDateTimeStr(fmt, tmp) + ' ' + dateStr; end; end; except on EConvertError do Result := tmp else raise; end; end; ptPrimaryDiag, ptAdd2PL, ptContraindicated: if(tmp = '1') then Result := ' '; ptVisitLocation: if(StrToIntDef(tmp, 0) = 0) then begin if(tmp <> '0') then Result := tmp; end else begin Result := GetPCEDisplayText(tmp, ComboPromptTags[pt]); end; ptWHPapResult: begin if Fparent.WHResultChk='N' then Result := 'NEM (No Evidence of Malignancy)'; if Fparent.WHResultChk='A' then Result := 'Abnormal'; if Fparent.WHResultChk='U' then Result := 'Unsatisfactory for Diagnosis'; if FParent.WHResultChk='' then Result := ''; end; ptWHNotPurp: begin if FParent.WHResultNot <> '' then begin WHValue := FParent.WHResultNot; //IF Forced = false then //begin if WHValue <> 'CPRS' then begin for cnt := 1 to Length(WHValue) do begin if Result ='' then begin if WHValue[cnt]='L' then Result := 'Letter'; if WHValue[cnt]='I' then Result := 'In-Person'; if WHValue[cnt]='P' then Result := 'Phone Call'; end else begin if (WHValue[cnt]='L')and(Pos('Letter',Result)=0) then Result := Result+'; Letter'; if (WHValue[cnt]='I')and(Pos('In-Person',Result)=0) then Result := Result+'; In-Person'; if (WHValue[cnt]='P')and(Pos('Phone Call',Result)=0) then Result := Result+'; Phone Call'; end; end; end; end else if Forced = true then begin if pos(':',Piece(FRec4,U,6))=0 then begin if Piece(FRec4,U,6)='L' then begin Result := 'Letter'; FParent.WHResultNot :='L'; end; if Piece(FRec4,U,6)='I' then begin Result := 'In-Person'; FParent.WHResultNot := 'I'; end; if Piece(FRec4,U,6)='P' then begin Result := 'Phone Call'; FParent.WHResultNot := 'P'; end; if Piece(FRec4,U,6)='CPRS' then begin Result := ''; FParent.WHResultNot := 'CPRS'; end; end else begin WHValue := Piece(FRec4,U,6); for cnt := 0 to Length(WHValue) do begin if Result ='' then begin if WHValue[cnt]='L' then begin Result := 'Letter'; FParent.WHResultNot := WHValue[cnt]; end; if WHValue[cnt]='I' then begin Result := 'In-Person'; FParent.WHResultNot := WHValue[cnt]; end; if WHValue[cnt]='P' then begin Result := 'Phone Call'; FParent.WHResultNot := WHValue[cnt]; end; end else begin if (WHValue[cnt]='L')and(Pos('Letter',Result)=0) then begin Result := Result +'; Letter'; FParent.WHResultNot := FParent.WHResultNot + ':' + WHValue[cnt]; end; if (WHValue[cnt]='I')and(Pos('In-Person',Result)=0) then begin Result := Result +'; In-Person'; FParent.WHResultNot := FParent.WHResultNot + ':' + WHValue[cnt]; end; if (WHValue[cnt]='P')and(Pos('Phone Call',Result)=0) then begin Result := Result +'; Phone Call'; FParent.WHResultNot := FParent.WHResultNot + ':' + WHValue[cnt]; end; end; end; end; end else Result := ''; end; ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction, ptLevelUnderstanding: begin Result := tmp; if(Piece(Result,U,1) = '@') then Result := '' else Result := GetPCEDisplayText(tmp, ComboPromptTags[pt]); end; else begin if pt = ptDataList then begin if(assigned(FData) and assigned(FData.FChoices)) then begin if not(assigned(FData.FChoicesActiveDates)) then for i := 0 to FData.FChoices.Count - 1 do begin if(copy(tmp,i+1,1) = '1') then begin if (Result <> '') then Result := Result + ', '; Result := Result + Piece(FData.FChoices[i],U,12); end; end else {if there are active dates for each choice then check them} begin if Self.FParent.Historical then EncDt := DateTimeToFMDateTime(Date) else EncDt := RemForm.PCEObj.VisitDateTime; k := 0; for i := 0 to FData.FChoices.Count - 1 do begin for j := 0 to (TStringList(FData.FChoicesActiveDates[i]).Count - 1) do begin ActDt := StrToIntDef((Piece(TStringList(FData.FChoicesActiveDates[i]).Strings[j], ':', 1)),0); InActDt := StrToIntDef((Piece(TStringList(FData.FChoicesActiveDates[i]).Strings[j], ':', 2)),9999999); if (EncDt >= ActDt) and (EncDt <= InActDt) then begin if(copy(tmp,k+1,1) = '1') then begin if(Result <> '') then Result := Result + ', '; Result := Result + Piece(FData.FChoices[i],U,12); end; inc(k); end; {ActiveDate check} end; {FChoicesActiveDates.Items[i] loop} end; {FChoices loop} end; end; end else if pt = ptVitalEntry then begin Result := VitalValue; if(Result <> '') then Result := ConvertVitalData(Result, VitalType, VitalUnitValue); end else if pt = ptMHTest then Result := FMiscText else if (pt = ptGAF) and (MHDLLFound = false) then begin if(StrToIntDef(Piece(tmp, U, 1),0) <> 0) then begin Result := tmp; end end else if pt = ptMHTest then Result := FMiscText; (* GafDate := Trunc(FParent.FReminder.PCEDataObj.VisitDateTime); ValidateGAFDate(GafDate); Result := tmp + CRCode + 'Date Determined: ' + FormatFMDateTime('mm/dd/yyyy', GafDate) + CRCode + 'Determined By: ' + FParent.FReminder.PCEDataObj.Providers.PCEProviderName; *) //end; end; end; end; if(Result <> '') and (Caption <> '') then Result := Trim(Caption + ' ' + Trim(Result)); //end; end; function TRemPrompt.CanShare(Prompt: TRemPrompt): boolean; var pt: TRemPromptType; begin if(Forced or Prompt.Forced or Prompt.FIsShared or Required or Prompt.Required) then Result := FALSE else begin pt := PromptType; Result := (pt = Prompt.PromptType); if(Result) then begin if(pt in [ptAdd2PL, ptLevelUnderstanding]) or ((pt = ptComment) and (not FParent.FHasSubComments)) then Result := ((Add2PN = Prompt.Add2PN) and (Caption = Prompt.Caption)) else Result := FALSE; end; end; end; destructor TRemPrompt.Destroy; begin KillObj(@FSharedChildren); inherited; end; function TRemPrompt.RemDataActive(RData: TRemData; EncDt: TFMDateTime):Boolean; //var // ActDt, InActDt: Double; // j: integer; begin // Result := FALSE; if assigned(RData.FActiveDates) then Result := CompareActiveDate(RData.FActiveDates, EncDt) //agp ICD-10 move code to it own function to reuse the comparison in other parts of dialogs // for j := 0 to (RData.FActiveDates.Count - 1) do // begin // ActDt := StrToIntDef(Piece(RData.FActiveDates[j],':',1), 0); // InActDt := StrToIntDef(Piece(RData.FActiveDates[j], ':', 2), 9999999); // if (EncDt >= ActDt) and (EncDt <= InActDt) then // begin // Result := TRUE; // Break; // end; // end else Result := TRUE; end; //agp ICD-10 code was imported from RemDataActive function TRemPrompt.CompareActiveDate(ActiveDates: TStringList; EncDt: TFMDateTime): Boolean; var ActDt, InActDt: Double; j: integer; begin Result := FALSE; for j := 0 to (ActiveDates.Count - 1) do begin ActDt := StrToIntDef(Piece(ActiveDates[j], ':', 1), 0); InActDt := StrToIntDef(Piece(ActiveDates[j], ':', 2), 9999999); if (EncDt >= ActDt) and (EncDt <= InActDt) then begin Result := TRUE; break; end; end end; function TRemPrompt.RemDataChoiceActive(RData: TRemData; j: integer; EncDt: TFMDateTime):Boolean; var ActDt, InActDt: Double; i: integer; begin Result := FALSE; If not assigned(RData.FChoicesActiveDates) then //if no active dates were sent Result := TRUE //from the server then don't check dates else {if there are active dates for each choice then check them} begin for i := 0 to (TStringList(RData.FChoicesActiveDates[j]).Count - 1) do begin ActDt := StrToIntDef((Piece(TStringList(RData.FChoicesActiveDates[j]).Strings[i], ':', 1)),0); InActDt := StrToIntDef((Piece(TStringList(RData.FChoicesActiveDates[j]).Strings[i], ':', 2)),9999999); if (EncDt >= ActDt) and (EncDt <= InActDt) then begin Result := True; end; {Active date check} end; {FChoicesActiveDates.Items[i] loop} end {FChoicesActiveDates check} end; function TRemPrompt.GetValue: string; //Returns TRemPrompt.FValue if this TRemPrompt is not a ptPrimaryDiag //Returns 0-False or 1-True if this TRemPrompt is a ptPrimaryDiag var i, j, k: integer; RData: TRemData; Ok: boolean; EncDt: TFMDateTime; begin OK := (Piece(FRec4, U, 4) = RemPromptCodes[ptPrimaryDiag]); if(OK) and (assigned(FParent)) then OK := (not FParent.Historical); if OK then begin Ok := FALSE; if(assigned(FParent) and assigned(FParent.FData)) then {If there's FData, see if} begin {there's a primary diagnosis} for i := 0 to FParent.FData.Count-1 do {if there is return True} begin EncDt := RemForm.PCEObj.VisitDateTime; RData := TRemData(FParent.FData[i]); if(RData.DataType = dtDiagnosis) then begin if(assigned(RData.FPCERoot)) and (RemDataActive(RData, EncDt)) then Ok := (RData.FPCERoot = PrimaryDiagRoot) else if(assigned(RData.FChoices)) and (assigned(RData.FChoicePrompt)) then begin k := 0; for j := 0 to RData.FChoices.Count-1 do begin if RemDataChoiceActive(RData, j, EncDt) then begin if(assigned(RData.FChoices.Objects[j])) and (copy(RData.FChoicePrompt.FValue,k+1,1)='1') then begin if(TRemPCERoot(RData.FChoices.Objects[j]) = PrimaryDiagRoot) then begin Ok := TRUE; break; end; end; //if FChoices.Objects (which is the RemPCERoot object) is assigned inc(k); end; //if FChoices[j] is active end; //loop through FChoices end; //If there are FChoices and an FChoicePrompt (i.e.: is this a ptDataList} end; if Ok then break; end; end; Result := BOOLCHAR[Ok]; end else Result := FValue; end; procedure TRemPrompt.SetValue(Value: string); var pt: TRemPromptType; i, j, k : integer; RData: TRemData; Primary, Done: boolean; Tmp: string; OK, NeedRefresh: boolean; EncDt: TFMDateTime; begin NeedRefresh := (not FFromControl); if(Forced and (not FFromParent)) then exit; pt := PromptType; if(pt = ptVisitDate) then begin if(Value = '') then Value := '0' else begin try if(StrToFloat(Value) > FMToday) then begin Value := '0'; InfoBox('Can not enter a future date for a historical event.', 'Invalid Future Date', MB_OK + MB_ICONERROR); end; except on EConvertError do Value := '0' else raise; end; if(Value = '0') then NeedRefresh := TRUE; end; end; if(GetValue <> Value) or (FFromParent) then begin FValue := Value; EncDt := RemForm.PCEObj.VisitDateTime; if((pt = ptExamResults) and assigned(FParent) and assigned(FParent.FData) and (FParent.FData.Count > 0) and assigned(FParent.FMSTPrompt)) then begin FParent.FMSTPrompt.SetValueFromParent(Value); if (FParent.FMSTPrompt.FMiscText = '') then // Assumes first finding item is MST finding FParent.FMSTPrompt.FMiscText := TRemData(FParent.FData[0]).InternalValue; end; OK := (assigned(FParent) and assigned(FParent.FData) and (Piece(FRec4, U, 4) = RemPromptCodes[ptPrimaryDiag])); if (OK = false) and (Value = 'New MH dll') then OK := true; if OK then OK := (not FParent.Historical); if OK then begin Done := FALSE; Primary := (Value = BOOLCHAR[TRUE]); for i := 0 to FParent.FData.Count-1 do begin RData := TRemData(FParent.FData[i]); if(RData.DataType = dtDiagnosis) then begin if(assigned(RData.FPCERoot)) and (RemDataActive(RData, EncDt)) then begin if(Primary) then begin PrimaryDiagRoot := RData.FPCERoot; Done := TRUE; end else begin if(PrimaryDiagRoot = RData.FPCERoot) then begin PrimaryDiagRoot := nil; Done := TRUE; end; end; end else if(assigned(RData.FChoices)) and (assigned(RData.FChoicePrompt)) then begin k := 0; for j := 0 to RData.FChoices.Count-1 do begin if RemDataChoiceActive(RData, j, EncDt) then begin if(Primary) then begin if(assigned(RData.FChoices.Objects[j])) and (copy(RData.FChoicePrompt.FValue,k+1,1)='1') then begin PrimaryDiagRoot := TRemPCERoot(RData.FChoices.Objects[j]); Done := TRUE; break; end; end else begin if(assigned(RData.FChoices.Objects[j])) and (PrimaryDiagRoot = TRemPCERoot(RData.FChoices.Objects[j])) then begin PrimaryDiagRoot := nil; Done := TRUE; break; end; end; inc(k); end; end; end; end; if Done then break; end; end; if(assigned(FParent) and assigned(FParent.FData) and IsSyncPrompt(pt)) then begin for i := 0 to FParent.FData.Count-1 do begin RData := TRemData(FParent.FData[i]); if(assigned(RData.FPCERoot)) and (RemDataActive(RData, EncDt)) then RData.FPCERoot.Sync(Self); if(assigned(RData.FChoices)) then begin for j := 0 to RData.FChoices.Count-1 do begin if(assigned(RData.FChoices.Objects[j])) and RemDataChoiceActive(RData, j, EncDt) then TRemPCERoot(RData.FChoices.Objects[j]).Sync(Self); end; end; end; end; end; if(not NeedRefresh) then NeedRefresh := (GetValue <> Value); if(NeedRefresh and assigned(FCurrentControl) and FParent.FReminder.Visible) then begin case pt of ptComment: (FCurrentControl as TEdit).Text := GetValue; ptQuantity: (FCurrentControl as TUpDown).Position := StrToIntDef(GetValue,1); (* ptSkinReading: (FCurrentControl as TUpDown).Position := StrToIntDef(GetValue,0); *) ptVisitDate: begin try (FCurrentControl as TORDateCombo).FMDate := StrToFloat(GetValue); except on EConvertError do (FCurrentControl as TORDateCombo).FMDate := 0; else raise; end; end; ptPrimaryDiag, ptAdd2PL, ptContraindicated: (FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]); ptVisitLocation: begin Tmp := GetValue; with (FCurrentControl as TORComboBox) do begin if(piece(Tmp,U,1)= '0') then begin Items[0] := Tmp; SelectByID('0'); end else SelectByID(Tmp); end; end; ptWHPapResult: (FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]); ptWHNotPurp: (FCurrentControl as TORCheckBox).Checked := (GetValue = BOOLCHAR[TRUE]); ptExamResults, ptSkinResults, ptLevelSeverity, ptSeries, ptReaction, ptLevelUnderstanding, ptSkinReading: //(AGP Change 26.1) (FCurrentControl as TORComboBox).SelectByID(GetValue); else if(pt = ptVitalEntry) then begin if(FCurrentControl is TORComboBox) then (FCurrentControl as TORComboBox).SelectByID(VitalValue) else if(FCurrentControl is TVitalEdit) then begin with (FCurrentControl as TVitalEdit) do begin Text := VitalValue; if(assigned(LinkedCombo)) then begin Tmp := VitalUnitValue; if(Tmp <> '') then LinkedCombo.Text := VitalUnitValue else LinkedCombo.ItemIndex := 0; end; end; end; end; end; end; end; procedure TRemPrompt.SetValueFromParent(Value: string); begin FFromParent := TRUE; try SetValue(Value); finally FFromParent := FALSE; end; end; procedure TRemPrompt.InitValue; var Value: string; pt: TRemPromptType; idx, i, j: integer; TempSL: TORStringList; Found: boolean; RData: TRemData; begin Value := InternalValue; pt := PromptType; if(ord(pt) >= ord(low(TRemPromptType))) and (ComboPromptTags[pt] <> 0) then begin TempSL := TORStringList.Create; try GetPCECodes(TempSL, ComboPromptTags[pt]); idx := TempSL.CaseInsensitiveIndexOfPiece(Value, U, 1); if(idx < 0) then idx := TempSL.CaseInsensitiveIndexOfPiece(Value, U, 2); if(idx >= 0) then Value := Piece(TempSL[idx],U,1); finally TempSL.Free; end; end; if((not Forced) and assigned(FParent) and assigned(FParent.FData) and IsSyncPrompt(pt)) then begin Found := FALSE; for i := 0 to FParent.FData.Count-1 do begin RData := TRemData(FParent.FData[i]); if(assigned(RData.FPCERoot)) then Found := RData.FPCERoot.GetValue(pt, Value); if(not Found) and (assigned(RData.FChoices)) then begin for j := 0 to RData.FChoices.Count-1 do begin if(assigned(RData.FChoices.Objects[j])) then begin Found := TRemPCERoot(RData.FChoices.Objects[j]).GetValue(pt, Value); if(Found) then break; end; end; end; if(Found) then break; end; end; FInitializing := TRUE; try SetValueFromParent(Value); finally FInitializing := FALSE; end; end; function TRemPrompt.ForcedCaption: string; var pt: TRemPromptType; begin Result := Caption; if(Result = '') then begin pt := PromptType; if(pt = ptDataList) then begin if(assigned(FData)) then begin if(FData.DataType = dtDiagnosis) then Result := 'Diagnosis' else if(FData.DataType = dtProcedure) then Result := 'Procedure'; end; end else if(pt = ptVitalEntry) then Result := VitalDesc[VitalType] + ':' else if(pt = ptMHTest) then Result := 'Perform ' + FData.Narrative else if(pt = ptGAF) then Result := 'GAF Score' else Result := PromptDescriptions[pt]; if(Result = '') then Result := 'Prompt'; end; if(copy(Result,length(Result),1) = ':') then delete(Result,length(Result),1); end; function TRemPrompt.VitalType: TVitalType; begin Result := vtUnknown; if(assigned(FData)) then Result := Code2VitalType(FData.InternalValue); end; procedure TRemPrompt.VitalVerify(Sender: TObject); var vEdt: TVitalEdit; vCbo: TVitalComboBox; AObj: TWinControl; begin if(Sender is TVitalEdit) then begin vEdt := TVitalEdit(Sender); vCbo := vEdt.LinkedCombo; end else if(Sender is TVitalComboBox) then begin vCbo := TVitalComboBox(Sender); vEdt := vCbo.LinkedEdit; end else begin vCbo := nil; vEdt := nil; end; AObj := Screen.ActiveControl; if((not assigned(AObj)) or ((AObj <> vEdt) and (AObj <> vCbo))) then begin if(vEdt.Tag = TAG_VITHEIGHT) then vEdt.Text := ConvertHeight2Inches(vEdt.Text); if VitalInvalid(vEdt, vCbo) then vEdt.SetFocus; end; end; function TRemPrompt.VitalUnitValue: string; var vt: TVitalType; begin vt := VitalType; if (vt in [vtTemp, vtHeight, vtWeight]) then begin Result := Piece(GetValue,';',2); if(Result = '') then begin case vt of vtTemp: Result := 'F'; vtHeight: Result := 'IN'; vtWeight: Result := 'LB'; end; SetPiece(FValue, ';', 2, Result); end; end else Result := ''; end; function TRemPrompt.VitalValue: string; begin Result := Piece(GetValue,';',1); end; procedure TRemPrompt.DoWHReport(Sender: TObject); Var comp, ien: string; i: integer; begin for i := 0 to FParent.FData.Count-1 do begin comp:= Piece(TRemData(FParent.FData[i]).FRec3,U,4); ien:= Piece(TRemData(FParent.FData[i]).FRec3,U,6); end; CallV('ORQQPXRM GET WH REPORT TEXT', [ien]); ReportBox(RPCBrokerV.Results,'Procedure Report Results',True); end; procedure TRemPrompt.ViewWHText(Sender: TObject); var WHRecNum, WHTitle: string; i: integer; begin for i := 0 to FParent.FData.Count-1 do begin if Piece(TRemData(FParent.FData[i]).FRec3,U,4)='WH' then begin WHRecNum:=(Piece(TRemData(FParent.FData[i]).FRec3,U,6)); WHTitle :=(Piece(TRemData(FParent.FData[i]).FRec3,U,8)); end; end; CallV('ORQQPXRM GET WH LETTER TEXT', [WHRecNum]); ReportBox(RPCBrokerV.Results,'Women Health Notification Purpose: '+WHTitle,false); end; procedure TRemPrompt.DoMHTest(Sender: TObject); var TmpSL, tmpScores, tmpResults: TStringList; i, TestComp: integer; Before, After, Score: string; MHRequired: boolean; begin TestComp := 0; try if (Sender is TCPRSDialogButton) then (Sender as TCPRSDialogButton).Enabled := false; if FParent.FReminder.MHTestArray = nil then FParent.FReminder.MHTestArray := TORStringList.Create; if(MHTestAuthorized(FData.Narrative)) then begin FParent.FReminder.BeginTextChanged; try if(FParent.IncludeMHTestInPN) then TmpSL := TStringList.Create else TmpSL := nil; if Piece(self.FData.FRec3,U,13) = '1' then MHRequired := True else MHRequired := false; Before := GetValue; After := PerformMHTest(Before, FData.Narrative, TmpSL, MHRequired); if uinit.TimedOut then After := ''; if Piece(After, U, 1) = 'New MH dll' then begin if Piece(After,U,2)='COMPLETE' then begin FParent.FReminder.MHTestArray.Add(FData.Narrative + U + FParent.FReminder.IEN); self.FMHTestComplete := 1; Score := Piece(After,U,3); if FParent.ResultDlgID <> '' then begin tmpScores := TStringList.Create; tmpResults := TStringList.Create; PiecestoList(copy(score,2,Length(score)),'*',tmpScores); PiecestoList(FParent.ResultDlgID,'~',tmpResults); GetMHResultText(FMiscText, tmpResults, tmpScores); if tmpScores <> nil then tmpScores.Free; if tmpResults <> nil then tmpResults.Free; end; if (FMiscText <> '') then FMiscText := FMiscText + '~<br>'; if tmpSL <> nil then begin for i := 0 to TmpSL.Count-1 do begin if(i > 0) then FMiscText := FMiscText + CRCode; FMiscText := FMiscText + TmpSL[i]; end; end; //end; //ExpandTIUObjects(FMiscText); end else if Piece(After,U,2)='INCOMPLETE' then begin FParent.FReminder.MHTestArray.Add(FData.Narrative + U + FParent.FReminder.IEN); self.FMHTestComplete := 2; FMiscText := ''; After := 'X'; end else if Piece(After,U,2)='CANCELLED' then begin self.FMHTestComplete := 0; FMiscText := ''; After := ''; end; SetValue(After); exit; end; if pos(U,After)>0 then begin TestComp := StrtoInt(Piece(After,U,2)); self.FMHTestComplete := TestComp; After := Piece(After,U,1); end; if(Before <> After) and (not uInit.TimedOut) then begin if(After = '') or (FParent.ResultDlgID = '') then FMiscText := '' else if TestComp > 0 then begin MentalHealthTestResults(FMiscText, FParent.ResultDlgID, FData.Narrative, FParent.FReminder.FPCEDataObj.Providers.PCEProvider, After); if(assigned(TmpSL) and (TmpSL.Count > 0)) then begin if(FMiscText <> '') then FMiscText := FMiscText + CRCode + CRCode; for i := 0 to TmpSL.Count-1 do begin if(i > 0) then FMiscText := FMiscText + CRCode + CRCode; FMiscText := FMiscText + TmpSL[i]; end; end; ExpandTIUObjects(FMiscText); end; SetValue(After); end; finally if not uInit.TimedOut then FParent.FReminder.EndTextChanged(Sender); end; if not uInit.TimedOut then if(FParent.ElemType = etDisplayOnly) and (not assigned(FParent.FParent)) then RemindersInProcess.Notifier.Notify; end else InfoBox('Not Authorized to score the ' + FData.Narrative + ' test.', 'Insufficient Authorization', MB_OK + MB_ICONERROR); finally if (Sender is TCPRSDialogButton) then begin (Sender as TCPRSDialogButton).Enabled := true; (Sender as TCPRSDialogButton).SetFocus; end; end; end; procedure TRemPrompt.GAFHelp(Sender: TObject); begin inherited; GotoWebPage(GAFURL); end; function TRemPrompt.EntryID: string; begin Result := FParent.EntryID + '/' + IntToStr(integer(Self)); end; procedure TRemPrompt.EditKeyPress(Sender: TObject; var Key: Char); begin if (Key = '?') and (Sender is TCustomEdit) and ((TCustomEdit(Sender).Text = '') or (TCustomEdit(Sender).SelStart = 0)) then Key := #0; end; { TRemPCERoot } destructor TRemPCERoot.Destroy; begin KillObj(@FData); KillObj(@FForcedPrompts); inherited; end; procedure TRemPCERoot.Done(Data: TRemData); var i, idx: integer; begin if(assigned(FForcedPrompts) and assigned(Data.FParent) and assigned(Data.FParent.FPrompts)) then begin for i := 0 to Data.FParent.FPrompts.Count-1 do UnSync(TRemPrompt(Data.FParent.FPrompts[i])); end; FData.Remove(Data); if(FData.Count <= 0) then begin idx := PCERootList.IndexOfObject(Self); // if(idx < 0) then // idx := PCERootList.IndexOf(FID); if(idx >= 0) then PCERootList.Delete(idx); if PrimaryDiagRoot = Self then PrimaryDiagRoot := nil; Free; end; end; class function TRemPCERoot.GetRoot(Data: TRemData; Rec3: string; Historical: boolean): TRemPCERoot; var DID: string; Idx: integer; obj: TRemPCERoot; begin if(Data.DataType = dtVitals) then DID := 'V' + Piece(Rec3, U, 6) else begin if(Historical) then begin inc(HistRootCount); DID := IntToStr(HistRootCount); end else DID := '0'; DID := DID + U + Piece(Rec3, U, r3Type) + U + Piece(Rec3, U, r3Code) + U + Piece(Rec3, U, r3Cat) + U + Piece(Rec3, U, r3Nar); end; idx := -1; if(not assigned(PCERootList)) then PCERootList := TStringList.Create else if(PCERootList.Count > 0) then idx := PCERootList.IndexOf(DID); if(idx < 0) then begin obj := TRemPCERoot.Create; try obj.FData := TList.Create; obj.FID := DID; idx := PCERootList.AddObject(DID, obj); except obj.Free; raise; end; end; Result := TRemPCERoot(PCERootList.Objects[idx]); Result.FData.Add(Data); end; function TRemPCERoot.GetValue(PromptType: TRemPromptType; var NewValue: string): boolean; var ptS: string; i: integer; begin ptS := char(ord('D') + ord(PromptType)); i := pos(ptS, FValueSet); if(i = 0) then Result := FALSE else begin NewValue := Piece(FValue, U, i); Result := TRUE; end; end; procedure TRemPCERoot.Sync(Prompt: TRemPrompt); var i, j: integer; RData: TRemData; Prm: TRemPrompt; pt: TRemPromptType; ptS, Value: string; begin // if(assigned(Prompt.FParent) and ((not Prompt.FParent.FChecked) or // (Prompt.FParent.ElemType = etDisplayOnly))) then exit; if(assigned(Prompt.FParent) and (not Prompt.FParent.FChecked)) then exit; pt := Prompt.PromptType; Value := Prompt.GetValue; if(Prompt.Forced) then begin if(not Prompt.FInitializing) then begin if(not assigned(FForcedPrompts)) then FForcedPrompts := TStringList.Create; if(FForcedPrompts.IndexOfObject(Prompt) < 0) then begin for i := 0 to FForcedPrompts.Count-1 do begin Prm := TRemPrompt(FForcedPrompts.Objects[i]); if(pt = Prm.PromptType) and (FForcedPrompts[i] <> Value) and (Prm.FParent.IsChecked) then raise EForcedPromptConflict.Create('Forced Value Error:' + CRLF + CRLF + Prompt.ForcedCaption + ' is already being forced to another value.'); end; FForcedPrompts.AddObject(Value, Prompt); end; end; end else begin if(assigned(FForcedPrompts)) then begin for i := 0 to FForcedPrompts.Count-1 do begin Prm := TRemPrompt(FForcedPrompts.Objects[i]); if(pt = Prm.PromptType) and (FForcedPrompts[i] <> Value) and (Prm.FParent.IsChecked) then begin Prompt.SetValue(FForcedPrompts[i]); if(assigned(Prompt.FParent)) then Prompt.FParent.cbClicked(nil); // Forces redraw exit; end; end; end; end; if(Prompt.FInitializing) then exit; for i := 0 to FData.Count-1 do inc(TRemData(FData[i]).FSyncCount); ptS := char(ord('D') + ord(pt)); i := pos(ptS, FValueSet); if(i = 0) then begin FValueSet := FValueSet + ptS; i := length(FValueSet); end; SetPiece(FValue, U, i, Value); for i := 0 to FData.Count-1 do begin RData := TRemData(FData[i]); if(RData.FSyncCount = 1) and (assigned(RData.FParent)) and (assigned(RData.FParent.FPrompts)) then begin for j := 0 to RData.FParent.FPrompts.Count-1 do begin Prm := TRemPrompt(RData.FParent.FPrompts[j]); if(Prm <> Prompt) and (pt = Prm.PromptType) and (not Prm.Forced) then Prm.SetValue(Prompt.GetValue); end; end; end; for i := 0 to FData.Count-1 do begin RData := TRemData(FData[i]); if(RData.FSyncCount > 0) then dec(RData.FSyncCount); end; end; procedure TRemPCERoot.UnSync(Prompt: TRemPrompt); var idx: integer; begin if(assigned(FForcedPrompts) and Prompt.Forced) then begin idx := FForcedPrompts.IndexOfObject(Prompt); if(idx >= 0) then FForcedPrompts.Delete(Idx); end; end; initialization InitReminderObjects; finalization FreeReminderObjects; end.
unit VH_Types; interface Uses Math3d,Voxel; type TVoxelBox = record Color,Normal,Section : integer; Position,MinBounds,MinBounds2 : TVector3f; Faces : array [1..6] of Boolean; end; TVoxelBoxSection = Record Boxs : array of TVoxelBox; List, NumBoxs : Integer; end; TVoxelBoxs = Record Sections : array of TVoxelBoxSection; NumSections : Integer; end; TGT = record Tex : Cardinal; Name : string; Tile : boolean; end; TGTI = record Tex,ID : cardinal; end; TSKYTex = record Loaded : Boolean; Textures : array [0..5] of Cardinal; Texture_Name : String; Filename : array [0..5] of String; end; // Currently 5 sections. Between each section is a break. If depth => 0 then it isn't used. TVH_Views = record Name : String; XRot, YRot, Depth : Single; Section : Integer; NotUnitRot : Boolean; end; TScreenShot = record Take,TakeAnimation,CaptureAnimation, Take360DAnimation : Boolean; _Type, //0 = BMP, 1 = JPG Width,Height, CompressionRate, Frames,FrameCount : Integer; FrameAdder,OldYRot : Single; end; Type TVVH = record Game : byte; //(2 TS, 4 RA2) GroundName,SkyName : string[50]; DataS_No : integer; DataB_No : integer; end; TVVD = record ID: word; Value : single; end; TVVDB = record ID: word; Value : Boolean; end; TVVSFile = record Version : single; Header : TVVH; DataS : array of TVVD; DataB : array of TVVDB; end; DSIDs = (DSRotX,DSRotY,DSDepth,DSXShift,DSYShift,DSGroundSize,DSGroundHeight,DSSkyXPos,DSSkyYPos,DSSkyZPos,DSSkyWidth,DSSkyHeight,DSSkyLength,DSFOV,DSDistance,DSUnitRot,DSDiffuseX,DSDiffuseY,DSDiffuseZ,DSAmbientX,DSAmbientY,DSAmbientZ,DSTurretRotationX,DSBackgroundColR,DSBackgroundColG,DSBackgroundColB,DSUnitCount,DSUnitSpace); DBIDs = (DBDrawGround,DBTileGround,DBDrawTurret,DBDrawBarrel,DBShowDebug,DBShowVoxelCount,DBDrawSky,DBCullFace,DBLightGround); TControlType = (CTview,CToffset,CThvaposition,CThvarotation); THVA_Main_Header = record FilePath: array[1..16] of Char; (* ASCIIZ string *) N_Frames, (* Number of animation frames *) N_Sections : Longword; (* Number of voxel sections described *) end; TSectionName = array[1..16] of Char; (* ASCIIZ string - name of section *) TTransformMatrix = array[1..3,1..4] of Single; THVAData = record SectionName : TSectionName; end; PHVA = ^THVA; THVA = Record Header : THVA_Main_Header; Data : array of THVAData; TransformMatrixs : array of TTransformMatrix; Data_no : integer; HigherLevel : PHVA; // Added by Banshee, for hierarchy purposes. end; THVAVOXEL = (HVhva,HVvoxel); TUndo_Redo_Data = record _Type : THVAVOXEL; Voxel : PVoxel; HVA : PHVA; Offset : TVector3f; Size : TVector3f; TransformMatrix : TTransformMatrix; Frame,Section : Integer; end; TUndo_Redo = Record Data : Array Of TUndo_Redo_Data; Data_No : Integer; end; implementation end.
unit grg; interface uses System.Inifiles, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; function WriteINIstr(Section, key, Value: string): boolean; function ReadINIstr(Section, key: string): string; function INIstrExists(Section, key: string): boolean; implementation function WriteINIstr(Section, key, Value: string): boolean; var IniFile: TIniFile; begin IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')); try IniFile.WriteString(Section, key, Value); except showmessage('Error writing to inifile'); end; end; function ReadINIstr(Section, key: string): string; var IniFile: TIniFile; begin IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')); result := IniFile.ReadString(Section, key, ''); end; function INIstrExists(Section, key: string): boolean; var IniFile: TIniFile; begin IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')); if IniFile.ValueExists(Section, key) = true then result := true else result := false; end; end.
namespace org.me.openglapplication; //The animated cube code was based on, and enhanced from, an example from //"Hello, Android" by Ed Burnette, published by Pragmatic Bookshelf, 2010 {$define TEXTURES} //also in GLRenderer interface uses java.nio, javax.microedition.khronos.opengles, android.content, android.graphics, android.opengl, android.util; type GLCube = public class private var mVertexBuffer: IntBuffer; {$ifdef TEXTURES} var mTextureBuffer: IntBuffer; {$endif} const Tag = 'GLRenderer'; public constructor; method Draw(gl: GL10); class method loadTexture(gl: GL10; ctx: Context; resource: Integer); end; implementation constructor GLCube; begin var one := 65536; var half := one / 2; var vertices: array of Integer := [ // FRONT -half, -half, half, half, -half, half, -half, half, half, half, half, half, // BACK -half, -half, -half, -half, half, -half, half, -half, -half, half, half, -half, // LEFT -half, -half, half, -half, half, half, -half, -half, -half, -half, half, -half, // RIGHT half, -half, -half, half, half, -half, half, -half, half, half, half, half, // TOP -half, half, half, half, half, half, -half, half, -half, half, half, -half, // BOTTOM -half, -half, half, -half, -half, -half, half, -half, half, half, -half, -half]; {$ifdef TEXTURES} var texCoords: array of Integer := [ // FRONT 0, one, one, one, 0, 0, one, 0, // BACK one, one, one, 0, 0, one, 0, 0, // LEFT one, one, one, 0, 0, one, 0, 0, // RIGHT one, one, one, 0, 0, one, 0, 0, // TOP one, 0, 0, 0, one, one, 0, one, // BOTTOM 0, 0, 0, one, one, 0, one, one]; {$endif} // Buffers to be passed to gl*Pointer() functions must be // direct, i.e., they must be placed on the native heap // where the garbage collector cannot move them. // // Buffers with multi-SByte data types (e.g., short, int, // float) must have their SByte order set to native order var vbb := ByteBuffer.allocateDirect(vertices.length * 4); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer := vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); {$ifdef TEXTURES} var tbb := ByteBuffer.allocateDirect(texCoords.length * 4); tbb.order(ByteOrder.nativeOrder()); mTextureBuffer := tbb.asIntBuffer(); mTextureBuffer.put(texCoords); mTextureBuffer.position(0) {$endif} end; method GLCube.Draw(gl: GL10); begin //Enable vertex buffer for writing to and to be used during render gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); //Identify vertex buffer and its format gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); {$ifdef TEXTURES} //Enable 2D texture buffer for writing to and to be used during render gl.glEnable(GL10.GL_TEXTURE_2D); //Identify texture buffer and its format gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTextureBuffer); {$endif} //Set current colour to white gl.glColor4f(1, 1, 1, 1); gl.glNormal3f(0, 0, 1); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); gl.glNormal3f(0, 0, -1); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 4, 4); //Set current colour to white gl.glColor4f(1, 1, 1, 1); gl.glNormal3f(-1, 0, 0); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 8, 4); gl.glNormal3f(1, 0, 0); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 12, 4); //Set current colour to white gl.glColor4f(1, 1, 1, 1); gl.glNormal3f(0, 1, 0); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 16, 4); gl.glNormal3f(0, -1, 0); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 20, 4); //Disable vertex buffer gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); //Disable texture buffer gl.glDisable(GL10.GL_TEXTURE_2D); end; class method GLCube.loadTexture(gl: GL10; ctx: Context; resource: Integer); begin //Ensure the image is not auto-scaled for device density on extraction var options := new BitmapFactory.Options; options.inScaled := False; //Load image from resources var bmp := BitmapFactory.decodeResource(ctx.Resources, resource, options); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0); GLHelp.GLCheck(gl.glGetError); //Scale linearly if texture is bigger than image gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); //Scale linearly if texture is smaller than image gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); bmp.recycle() end; end.
unit XED.OperandWidthEnum; {$Z4} interface type TXED_Operand_Width_Enum = ( XED_OPERAND_WIDTH_INVALID, XED_OPERAND_WIDTH_ASZ, XED_OPERAND_WIDTH_SSZ, XED_OPERAND_WIDTH_PSEUDO, XED_OPERAND_WIDTH_PSEUDOX87, XED_OPERAND_WIDTH_A16, XED_OPERAND_WIDTH_A32, XED_OPERAND_WIDTH_B, XED_OPERAND_WIDTH_D, XED_OPERAND_WIDTH_I8, XED_OPERAND_WIDTH_U8, XED_OPERAND_WIDTH_I16, XED_OPERAND_WIDTH_U16, XED_OPERAND_WIDTH_I32, XED_OPERAND_WIDTH_U32, XED_OPERAND_WIDTH_I64, XED_OPERAND_WIDTH_U64, XED_OPERAND_WIDTH_F16, XED_OPERAND_WIDTH_F32, XED_OPERAND_WIDTH_F64, XED_OPERAND_WIDTH_DQ, XED_OPERAND_WIDTH_XUB, XED_OPERAND_WIDTH_XUW, XED_OPERAND_WIDTH_XUD, XED_OPERAND_WIDTH_XUQ, XED_OPERAND_WIDTH_X128, XED_OPERAND_WIDTH_XB, XED_OPERAND_WIDTH_XW, XED_OPERAND_WIDTH_XD, XED_OPERAND_WIDTH_XQ, XED_OPERAND_WIDTH_ZB, XED_OPERAND_WIDTH_ZW, XED_OPERAND_WIDTH_ZD, XED_OPERAND_WIDTH_ZQ, XED_OPERAND_WIDTH_MB, XED_OPERAND_WIDTH_MW, XED_OPERAND_WIDTH_MD, XED_OPERAND_WIDTH_MQ, XED_OPERAND_WIDTH_M64INT, XED_OPERAND_WIDTH_M64REAL, XED_OPERAND_WIDTH_MEM108, XED_OPERAND_WIDTH_MEM14, XED_OPERAND_WIDTH_MEM16, XED_OPERAND_WIDTH_MEM16INT, XED_OPERAND_WIDTH_MEM28, XED_OPERAND_WIDTH_MEM32INT, XED_OPERAND_WIDTH_MEM32REAL, XED_OPERAND_WIDTH_MEM80DEC, XED_OPERAND_WIDTH_MEM80REAL, XED_OPERAND_WIDTH_F80, XED_OPERAND_WIDTH_MEM94, XED_OPERAND_WIDTH_MFPXENV, XED_OPERAND_WIDTH_MXSAVE, XED_OPERAND_WIDTH_MPREFETCH, XED_OPERAND_WIDTH_P, XED_OPERAND_WIDTH_P2, XED_OPERAND_WIDTH_PD, XED_OPERAND_WIDTH_PS, XED_OPERAND_WIDTH_PI, XED_OPERAND_WIDTH_Q, XED_OPERAND_WIDTH_S, XED_OPERAND_WIDTH_S64, XED_OPERAND_WIDTH_SD, XED_OPERAND_WIDTH_SI, XED_OPERAND_WIDTH_SS, XED_OPERAND_WIDTH_V, XED_OPERAND_WIDTH_Y, XED_OPERAND_WIDTH_W, XED_OPERAND_WIDTH_Z, XED_OPERAND_WIDTH_SPW8, XED_OPERAND_WIDTH_SPW, XED_OPERAND_WIDTH_SPW5, XED_OPERAND_WIDTH_SPW3, XED_OPERAND_WIDTH_SPW2, XED_OPERAND_WIDTH_I1, XED_OPERAND_WIDTH_I2, XED_OPERAND_WIDTH_I3, XED_OPERAND_WIDTH_I4, XED_OPERAND_WIDTH_I5, XED_OPERAND_WIDTH_I6, XED_OPERAND_WIDTH_I7, XED_OPERAND_WIDTH_VAR, XED_OPERAND_WIDTH_BND32, XED_OPERAND_WIDTH_BND64, XED_OPERAND_WIDTH_PMMSZ16, XED_OPERAND_WIDTH_PMMSZ32, XED_OPERAND_WIDTH_QQ, XED_OPERAND_WIDTH_YUB, XED_OPERAND_WIDTH_YUW, XED_OPERAND_WIDTH_YUD, XED_OPERAND_WIDTH_YUQ, XED_OPERAND_WIDTH_Y128, XED_OPERAND_WIDTH_YB, XED_OPERAND_WIDTH_YW, XED_OPERAND_WIDTH_YD, XED_OPERAND_WIDTH_YQ, XED_OPERAND_WIDTH_YPS, XED_OPERAND_WIDTH_YPD, XED_OPERAND_WIDTH_ZBF16, XED_OPERAND_WIDTH_VV, XED_OPERAND_WIDTH_ZV, XED_OPERAND_WIDTH_WRD, XED_OPERAND_WIDTH_MSKW, XED_OPERAND_WIDTH_ZMSKW, XED_OPERAND_WIDTH_ZF32, XED_OPERAND_WIDTH_ZF64, XED_OPERAND_WIDTH_ZUB, XED_OPERAND_WIDTH_ZUW, XED_OPERAND_WIDTH_ZUD, XED_OPERAND_WIDTH_ZUQ, XED_OPERAND_WIDTH_ZI8, XED_OPERAND_WIDTH_ZI16, XED_OPERAND_WIDTH_ZI32, XED_OPERAND_WIDTH_ZI64, XED_OPERAND_WIDTH_ZU8, XED_OPERAND_WIDTH_ZU16, XED_OPERAND_WIDTH_ZU32, XED_OPERAND_WIDTH_ZU64, XED_OPERAND_WIDTH_ZU128, XED_OPERAND_WIDTH_M384, XED_OPERAND_WIDTH_M512, XED_OPERAND_WIDTH_PTR, XED_OPERAND_WIDTH_TMEMROW, XED_OPERAND_WIDTH_TMEMCOL, XED_OPERAND_WIDTH_TV, XED_OPERAND_WIDTH_ZF16, XED_OPERAND_WIDTH_Z2F16, XED_OPERAND_WIDTH_LAST); /// This converts strings to #xed_operand_width_enum_t types. /// @param s A C-string. /// @return #xed_operand_width_enum_t /// @ingroup ENUM function str2xed_operand_width_enum_t(s: PAnsiChar): TXED_Operand_Width_Enum; cdecl; external 'xed.dll'; /// This converts strings to #xed_operand_width_enum_t types. /// @param p An enumeration element of type xed_operand_width_enum_t. /// @return string /// @ingroup ENUM function xed_operand_width_enum_t2str(const p: TXED_Operand_Width_Enum): PAnsiChar; cdecl; external 'xed.dll'; /// Returns the last element of the enumeration /// @return xed_operand_width_enum_t The last element of the enumeration. /// @ingroup ENUM function xed_operand_width_enum_t_last:TXED_Operand_Width_Enum;cdecl; external 'xed.dll'; implementation end.
unit uTransparentEncryption; interface {$WARN SYMBOL_PLATFORM OFF} uses System.Types, System.SysUtils, System.StrUtils, System.SyncObjs, System.Math, System.Classes, Winapi.Windows, Dmitry.CRC32, Dmitry.Utils.System, Dmitry.Utils.Files, DECUtil, DECHash, DECCipher, uConstants, uErrors, uMemory, uStrongCrypt, uRWLock, {$IFDEF PHOTODB} uSettings, {$ENDIF} uLockedFileNotifications; type TMemoryBlock = class Memory: Pointer; Size: Integer; Index: Int64; end; TEncryptionErrorHandler = procedure(ErrorMessage: string); TEncryptedFile = class(TObject) private FSync: TCriticalSection; FHandle: THandle; FFileBlocks: TList; FMemoryBlocks: TList; FBlockSize: Int64; FMemorySize: Int64; FMemoryLimit: Int64; FHeaderSize: Integer; FContentSize: Int64; FSalt: Binary; FChipper: TDECCipherClass; FIsDecrypted: Boolean; FPassword: string; FFileName: string; FlpOverlapped: POverlapped; FIsAsyncHandle: Boolean; FAsyncFileHandle: THandle; procedure DecodeDataBlock(const Source; var Dest; DataSize: Integer); function GetSize: Int64; function GetBlockByIndex(Index: Int64): TMemoryBlock; public constructor Create(Handle: THandle; FileName: string; IsAsyncHandle: Boolean); destructor Destroy; override; function CanDecryptWithPasswordRequest(FileName: string): Boolean; procedure ReadBlock(const Block; BlockPosition: Int64; BlockSize: Int64; lpOverlapped: POverlapped = nil); function GetBlock(BlockPosition: Int64; BlockSize: Int64): Pointer; procedure FreeBlock(Block: Pointer); property Size: Int64 read GetSize; property Blocks[Index: Int64]: TMemoryBlock read GetBlockByIndex; property HeaderSize: Integer read FHeaderSize; end; TEncryptionOptions = class(TObject) private FSync: IReadWriteSync; FFileExtensionList: string; public constructor Create; destructor Destroy; override; function CanBeTransparentEncryptedFile(FileName: string): Boolean; procedure Refresh; end; procedure WriteEnryptHeaderV3(Stream: TStream; Src: TStream; BlockSize32k: Byte; Password: string; var Seed: Binary; ACipher: TDECCipherClass); function EncryptStreamEx(S, D: TStream; Password: string; ACipher: TDECCipherClass; Progress: TSimpleEncryptProgress = nil): Boolean; function TransparentEncryptFileEx(FileName: string; Password: string; ACipher: TDECCipherClass = nil; Progress: TFileProgress = nil): Integer; function DecryptStreamEx(S, D: TStream; Password: string; Seed: Binary; FileSize: Int64; AChipper: TDECCipherClass; BlockSize32k: Byte; Progress: TSimpleEncryptProgress = nil): Boolean; function ValidEnryptFileEx(FileName: String): Boolean; function ValidEncryptFileExHandle(FileHandle: THandle; IsAsyncHandle: Boolean): Boolean; function CanBeTransparentEncryptedFile(FileName: string): Boolean; function TransparentDecryptFileEx(FileName: string; Password: string; Progress: TFileProgress = nil): Integer; procedure SetEncryptionErrorHandler(ErrorHander: TEncryptionErrorHandler); function EncryptionOptions: TEncryptionOptions; function ReadFile(hFile: THandle; var Buffer; nNumberOfBytesToRead: DWORD; lpNumberOfBytesRead: PDWORD; lpOverlapped: POverlapped): BOOL; stdcall; external kernel32 name 'ReadFile'; implementation var FEncryptionOptions: TEncryptionOptions = nil; FErrorHander: TEncryptionErrorHandler = nil; procedure SetEncryptionErrorHandler(ErrorHander: TEncryptionErrorHandler); begin FErrorHander := ErrorHander; end; function EncryptionOptions: TEncryptionOptions; begin if FEncryptionOptions = nil then FEncryptionOptions := TEncryptionOptions.Create; Result := FEncryptionOptions; end; function CanBeTransparentEncryptedFile(FileName: string): Boolean; begin Result := EncryptionOptions.CanBeTransparentEncryptedFile(FileName); end; procedure WriteEnryptHeaderV3(Stream: TStream; Src: TStream; BlockSize32k: Byte; Password: string; var Seed: Binary; ACipher: TDECCipherClass); var EncryptHeader: TEncryptedFileHeader; EncryptHeaderV1: TEncryptFileHeaderExV1; begin FillChar(EncryptHeader, SizeOf(EncryptHeader), #0); EncryptHeader.ID := PhotoDBFileHeaderID; EncryptHeader.Version := ENCRYPT_FILE_VERSION_TRANSPARENT; EncryptHeader.DBVersion := ReleaseNumber; Stream.Write(EncryptHeader, SizeOf(EncryptHeader)); FillChar(EncryptHeaderV1, SizeOf(EncryptHeaderV1), #0); Randomize; Seed := RandomBinary(16); EncryptHeaderV1.Seed := ConvertSeed(Seed); EncryptHeaderV1.Version := 1; EncryptHeaderV1.Algorith := ACipher.Identity; EncryptHeaderV1.BlockSize32k := BlockSize32k; EncryptHeaderV1.FileSize := Src.Size; EncryptHeaderV1.ProgramVersion := GetExeVersion(ParamStr(0)); CalcStringCRC32(Password, EncryptHeaderV1.PassCRC); EncryptHeaderV1.Displacement := 0; Stream.Write(EncryptHeaderV1, SizeOf(EncryptHeaderV1)); end; function EncryptStreamEx(S, D: TStream; Password: string; ACipher: TDECCipherClass; Progress: TSimpleEncryptProgress = nil): Boolean; var Seed: Binary; BlockSize32k: Byte; Size, SizeToEncrypt: Int64; BreakOperation: Boolean; begin Result := True; BreakOperation := False; BlockSize32k := 1; ACipher := ValidCipher(ACipher); WriteEnryptHeaderV3(D, S, BlockSize32k, Password, Seed, ACipher); Size := S.Size; while S.Position < Size do begin SizeToEncrypt := BlockSize32k * Encrypt32kBlockSize; if S.Position + SizeToEncrypt >= Size then SizeToEncrypt := Size - S.Position; CryptStreamV2(S, D, Password, Seed, nil, cmCTSx, nil, SizeToEncrypt); if Assigned(Progress) then begin Progress(Size, S.Position, BreakOperation); if BreakOperation then Exit(False); end; end; end; procedure DoCodeStreamEx(Source,Dest: TStream; Size: Int64; BlockSize: Integer; const Proc: TDECCipherCodeEvent; const Progress: IDECProgress; Buffer: Binary); var BufferSize, Bytes: Integer; Min, Max, Pos: Int64; begin Pos := Source.Position; if Size < 0 then Size := Source.Size - Pos; Min := Pos; Max := Pos + Size; if Size > 0 then try if StreamBufferSize <= 0 then StreamBufferSize := 8192; BufferSize := StreamBufferSize mod BlockSize; if BufferSize = 0 then BufferSize := StreamBufferSize else BufferSize := StreamBufferSize + BlockSize - BufferSize; if Size > BufferSize then SetLength(Buffer, BufferSize) else SetLength(Buffer, Size); while Size > 0 do begin if Assigned(Progress) then Progress.Process(Min, Max, Pos); Bytes := BufferSize; if Bytes > Size then Bytes := Size; Source.ReadBuffer(Buffer[1], Bytes); Proc(Buffer[1], Buffer[1], Bytes); Dest.WriteBuffer(Buffer[1], Bytes); Dec(Size, Bytes); Inc(Pos, Bytes); end; finally if Assigned(Progress) then Progress.Process(Min, Max, Max); end; end; function DecryptStreamEx(S, D: TStream; Password: string; Seed: Binary; FileSize: Int64; AChipper: TDECCipherClass; BlockSize32k: Byte; Progress: TSimpleEncryptProgress = nil): Boolean; var StartPos, SizeToEncrypt: Int64; APassword: AnsiString; Bytes: TBytes; AHash: TDECHashClass; Key, Buffer: Binary; BreakOperation: Boolean; begin if Password = '' then Exit(False); BreakOperation := False; StartPos := S.Position; AChipper := ValidCipher(AChipper); AHash := ValidHash(nil); Bytes := TEncoding.UTF8.GetBytes(Password); SetLength(APassword, Length(Bytes)); Move(Bytes[0], APassword[1], Length(Bytes)); SetLength(Buffer, BlockSize32k * Encrypt32kBlockSize); try with AChipper.Create do try Mode := CmCTSx; Key := AHash.KDFx(APassword, Seed, Context.KeySize); while S.Position - StartPos < FileSize do begin SizeToEncrypt := BlockSize32k * Encrypt32kBlockSize; if S.Position + SizeToEncrypt - StartPos >= FileSize then SizeToEncrypt := FileSize - (S.Position - StartPos); Init(Key); DoCodeStreamEx(S, D, SizeToEncrypt, Context.BlockSize, Decode, nil, Buffer); if Assigned(Progress) then begin Progress(FileSize, S.Position - StartPos, BreakOperation); if BreakOperation then Exit(False); end; end; finally Free; end; finally ProtectBinary(Buffer); end; Result := True; end; function TransparentEncryptFileEx(FileName: string; Password: string; ACipher: TDECCipherClass = nil; Progress: TFileProgress = nil): Integer; var IsEncrypted: Boolean; SFS, DFS: TFileStream; FA: Integer; FileSize: Int64; EncryptHeader: TEncryptedFileHeader; TmpFileName, TmpErasedFile: string; begin StrongCryptInit; try TryOpenFSForRead(SFS, FileName, DelayReadFileOperation); if SFS = nil then begin Result := CRYPT_RESULT_ERROR_READING_FILE; Exit; end; try FileSize := SFS.Size; SFS.Read(EncryptHeader, SizeOf(EncryptHeader)); if EncryptHeader.ID = PhotoDBFileHeaderID then begin Result := CRYPT_RESULT_ALREADY_CRYPT; Exit; end; TmpFileName := FileName + '.tmp'; TmpErasedFile := FileName + '.erased'; SFS.Seek(0, SoFromBeginning); try DFS := TFileStream.Create(TmpFileName, FmOpenWrite or FmCreate); try IsEncrypted := EncryptStreamEx(SFS, DFS, Password, ACipher, procedure(BytesTotal, BytesDone: Int64; var BreakOperation: Boolean) begin if Assigned(Progress) then //encryption is the first part of operation Progress(FileName, FileSize, BytesDone div 2, BreakOperation); end ); finally F(DFS); end; except Result := CRYPT_RESULT_ERROR_WRITING_FILE; Exit; end; finally F(SFS); end; except Result := CRYPT_RESULT_ERROR_READING_FILE; Exit; end; if not IsEncrypted then begin DeleteFile(PChar(TmpFileName)); Exit(CRYPT_RESULT_FAILED_GENERAL_ERROR); end; FA := FileGetAttr(FileName); ResetFileAttributes(FileName, FA); TLockFiles.Instance.AddLockedFile(FileName, 10000); TLockFiles.Instance.AddLockedFile(TmpErasedFile, 10000); try if RenameFile(FileName, TmpErasedFile) then if RenameFile(TmpFileName, FileName) then begin WipeFile(TmpErasedFile, 1, procedure(FileName: string; BytesTotal, BytesDone: Int64; var BreakOperation: Boolean) begin if Assigned(Progress) then //erase is the second part of operation Progress(FileName, FileSize, FileSize div 2 + BytesDone div 2, BreakOperation); end ); TLockFiles.Instance.RemoveLockedFile(TmpErasedFile); System.SysUtils.DeleteFile(TmpErasedFile); end; finally TLockFiles.Instance.RemoveLockedFile(FileName); TLockFiles.Instance.RemoveLockedFile(TmpErasedFile); end; FileSetAttr(FileName, FA); Result := CRYPT_RESULT_OK; end; function TransparentDecryptFileEx(FileName: string; Password: string; Progress: TFileProgress = nil): Integer; var IsDecrypted: Boolean; SFS, DFS: TFileStream; FA: Integer; EncryptHeader: TEncryptedFileHeader; EncryptHeaderExV1: TEncryptFileHeaderExV1; TmpFileName, TmpErasedFile: string; ACipher: TDECCipherClass; begin StrongCryptInit; TmpFileName := FileName + '.tmp'; TmpErasedFile := FileName + '.erased'; TLockFiles.Instance.AddLockedFile(FileName, 10000); TLockFiles.Instance.AddLockedFile(TmpFileName, 10000); TLockFiles.Instance.AddLockedFile(TmpErasedFile, 10000); try try TryOpenFSForRead(SFS, FileName, DelayReadFileOperation); if SFS = nil then Exit(CRYPT_RESULT_ERROR_READING_FILE); try SFS.Read(EncryptHeader, SizeOf(EncryptHeader)); if EncryptHeader.ID <> PhotoDBFileHeaderID then Exit(CRYPT_RESULT_ALREADY_DECRYPTED); if EncryptHeader.Version <> ENCRYPT_FILE_VERSION_TRANSPARENT then Exit(CRYPT_RESULT_UNSUPORTED_VERSION); SFS.Read(EncryptHeaderExV1, SizeOf(EncryptHeaderExV1)); ACipher := CipherByIdentity(EncryptHeaderExV1.Algorith); if ACipher = nil then Exit(CRYPT_RESULT_UNSUPORTED_VERSION); try DFS := TFileStream.Create(TmpFileName, FmOpenWrite or FmCreate); try IsDecrypted := DecryptStreamEx(SFS, DFS, Password, SeedToBinary(EncryptHeaderExV1.Seed), EncryptHeaderExV1.FileSize, ACipher, EncryptHeaderExV1.BlockSize32k, procedure(BytesTotal, BytesDone: Int64; var BreakOperation: Boolean) begin if Assigned(Progress) then Progress(FileName, EncryptHeaderExV1.FileSize, BytesDone, BreakOperation); end ); finally F(DFS); end; except Result := CRYPT_RESULT_ERROR_WRITING_FILE; Exit; end; finally F(SFS); end; except Result := CRYPT_RESULT_ERROR_READING_FILE; Exit; end; if not IsDecrypted then begin DeleteFile(PChar(TmpFileName)); Exit(CRYPT_RESULT_FAILED_GENERAL_ERROR); end; FA := FileGetAttr(FileName); ResetFileAttributes(FileName, FA); if RenameFile(FileName, TmpErasedFile) then if RenameFile(TmpFileName, FileName) then begin TLockFiles.Instance.RemoveLockedFile(TmpErasedFile); System.SysUtils.DeleteFile(TmpErasedFile); end; finally TLockFiles.Instance.RemoveLockedFile(FileName); TLockFiles.Instance.RemoveLockedFile(TmpFileName); TLockFiles.Instance.RemoveLockedFile(TmpErasedFile); end; FileSetAttr(FileName, FA); Result := CRYPT_RESULT_OK; end; function ValidEncryptFileExStream(Stream: TStream): Boolean; var EncryptHeader: TEncryptedFileHeader; Pos: Int64; begin Pos := Stream.Position; Stream.Read(EncryptHeader, SizeOf(EncryptHeader)); Result := EncryptHeader.ID = PhotoDBFileHeaderID; Stream.Seek(Pos, TSeekOrigin.soBeginning); end; function ValidEncryptFileExHandle(FileHandle: THandle; IsAsyncHandle: Boolean): Boolean; var EncryptHeader: TEncryptedFileHeader; Pos: Int64; Overlapped: TOverlapped; lpNumberOfBytesTransferred: DWORD; begin Result := False; if FileHandle = 0 then Exit; if not IsAsyncHandle then begin Pos := FileSeek(FileHandle, 0, FILE_CURRENT); FileSeek(FileHandle, 0, FILE_BEGIN); if FileRead(FileHandle, EncryptHeader, SizeOf(EncryptHeader)) = SizeOf(EncryptHeader) then Result := EncryptHeader.ID = PhotoDBFileHeaderID; FileSeek(FileHandle, Pos, FILE_BEGIN); end else begin FillChar(Overlapped, SizeOf(TOverlapped), #0); Overlapped.hEvent := CreateEvent(nil, True, False, nil); try ReadFile(FileHandle, EncryptHeader, SizeOf(EncryptHeader), nil, @Overlapped); if ERROR_IO_PENDING <> GetLastError then Exit; if WaitForSingleObject(Overlapped.hEvent, INFINITE) = WAIT_OBJECT_0 then begin if not GetOverlappedResult(FileHandle, Overlapped, lpNumberOfBytesTransferred, True) then Exit; if lpNumberOfBytesTransferred = 0 then Exit; Result := EncryptHeader.ID = PhotoDBFileHeaderID; end; finally CloseHandle(Overlapped.hEvent); end; end; end; procedure TryOpenHandleForRead(var hFile: THandle; FileName: string; DelayReadFileOperation: Integer); var I: Integer; begin hFile := 0; for I := 1 to 20 do begin hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_WRITE or FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if hFile = 0 then begin if GetLastError in [0, ERROR_PATH_NOT_FOUND, ERROR_INVALID_DRIVE, ERROR_NOT_READY, ERROR_FILE_NOT_FOUND, ERROR_GEN_FAILURE, ERROR_INVALID_NAME] then Exit; Sleep(DelayReadFileOperation); end else Break; end; end; function ValidEnryptFileEx(FileName: String): Boolean; var hFile: THandle; begin Result := False; if StartsStr('\\.', FileName) then Exit; TryOpenHandleForRead(hFile, FileName, DelayReadFileOperation); if hFile = 0 then Exit; Result := ValidEncryptFileExHandle(hFile, False); CloseHandle(hFile); end; { TEncryptedFile } function TEncryptedFile.CanDecryptWithPasswordRequest(FileName: string): Boolean; var EncryptHeader: TEncryptedFileHeader; EncryptHeaderV1: TEncryptFileHeaderExV1; Position: Int64; CRC: Cardinal; hFileMapping: THandle; Password, SharedFileName, MessageToSent: string; CD: TCopyDataStruct; Buf: Pointer; P: PByte; WinHandle: HWND; m_pViewOfFile: Pointer; FFilePosition: Int64; procedure InternalFileSeek(Offset: Int64); begin if FIsAsyncHandle then FFilePosition := Offset else FileSeek(FHandle, Offset, FILE_BEGIN) end; procedure InternalFileRead(var Buffer; SizeToRead: Integer); var Res: BOOL; lpNumberOfBytesTransferred: Cardinal; lpOverlapped: POverlapped; begin if FIsAsyncHandle then begin GetMem(lpOverlapped, SizeOf(TOverlapped)); FillChar(lpOverlapped^, SizeOf(TOverlapped), #0); lpOverlapped.Offset := Int64Rec(FFilePosition).Lo; lpOverlapped.OffsetHigh := Int64Rec(FFilePosition).Hi; lpOverlapped.hEvent := CreateEvent(nil, True, False, nil); try Res := ReadFile(FHandle, Buffer, SizeToRead, nil, lpOverlapped); if not Res and (GetLastError = ERROR_IO_PENDING) then begin if not WaitForSingleObject(lpOverlapped.hEvent, INFINITE) = WAIT_OBJECT_0 then Exit; if not GetOverlappedResult(FHandle, lpOverlapped^, lpNumberOfBytesTransferred, True) then Exit; FFilePosition := FFilePosition + Int64(lpNumberOfBytesTransferred); end; finally CloseHandle(lpOverlapped.hEvent); FreeMem(lpOverlapped); end; end else FileRead(FHandle, Buffer, SizeToRead); end; begin Result := False; if FHandle = 0 then Exit; Password := ''; //request password from Photo Dtabase host SharedFileName := 'FILE_HANDLE_' + IntToStr(FHandle); //1024 bytes maximum in pasword hFileMapping := CreateFileMapping( INVALID_HANDLE_VALUE, // system paging file nil, // security attributes PAGE_READWRITE, // protection 0, // high-order DWORD of size 1024, // low-order DWORD of size PChar(SharedFileName)); // name if (hFileMapping <> 0) then begin WinHandle := FindWindow(nil, PChar(DB_ID)); if WinHandle <> 0 then begin MessageToSent := '::PASS:' + SharedFileName + ':' + FileName; cd.dwData := WM_COPYDATA_ID; cd.cbData := ((Length(MessageToSent) + 1) * SizeOf(Char)); GetMem(Buf, cd.cbData); try P := PByte(Buf); StrPLCopy(PChar(P), MessageToSent, Length(MessageToSent)); cd.lpData := Buf; if SendMessage(WinHandle, WM_COPYDATA, 0, NativeInt(@cd)) = 0 then begin ///// Creating a view of the file in the Processes address space m_pViewOfFile := MapViewOfFile( hFileMapping, // handle to file-mapping object FILE_MAP_ALL_ACCESS, // desired access 0, 0, 0); if m_pViewOfFile <> nil then begin Password := string(PChar(m_pViewOfFile)); UnmapViewOfFile(m_pViewOfFile); end; end; finally FreeMem(Buf); end; end; CloseHandle(hFileMapping); end; {$IFDEF TESTPASS} if Password = '' then Password := '1'; {$ENDIF} if Password = '' then Exit; Position := FileSeek(FHandle, Int64(0), FILE_CURRENT); InternalFileSeek(0); FillChar(EncryptHeader, SizeOf(EncryptHeader), #0); FillChar(EncryptHeaderV1, SizeOf(EncryptHeaderV1), #0); InternalFileRead(EncryptHeader, SizeOf(EncryptHeader)); if EncryptHeader.ID = PhotoDBFileHeaderID then begin if EncryptHeader.Version = ENCRYPT_FILE_VERSION_TRANSPARENT then begin StrongCryptInit; InternalFileRead(EncryptHeaderV1, SizeOf(EncryptHeaderV1)); CalcStringCRC32(Password, CRC); if EncryptHeaderV1.PassCRC <> CRC then Exit; FBlockSize := EncryptHeaderV1.BlockSize32k * Encrypt32kBlockSize; FHeaderSize := SizeOf(EncryptHeader) + SizeOf(EncryptHeaderV1); FHeaderSize := FHeaderSize + Integer(EncryptHeaderV1.Displacement); FChipper := CipherByIdentity(EncryptHeaderV1.Algorith); FContentSize := EncryptHeaderV1.FileSize; FSalt := SeedToBinary(EncryptHeaderV1.Seed); FPassword := Password; FIsDecrypted := True; Result := True; end; end; FileSeek(FHandle, Position, FILE_BEGIN); end; constructor TEncryptedFile.Create(Handle: THandle; FileName: string; IsAsyncHandle: Boolean); begin FSync := TCriticalSection.Create; FChipper := nil; FlpOverlapped := nil; FFileBlocks := TList.Create; FMemoryBlocks := TList.Create; FIsDecrypted := False; FHandle := Handle; FFileName := FileName; FIsAsyncHandle := IsAsyncHandle; FHeaderSize := 0; FBlockSize := 0; FContentSize := 0; FMemorySize := 0; FMemoryLimit := 10 * 1024 * 1024; FAsyncFileHandle := 0; if IsAsyncHandle then begin FAsyncFileHandle := CreateFile(PChar(FFileName), GENERIC_READ, FILE_SHARE_WRITE or FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, 0); if FAsyncFileHandle = INVALID_HANDLE_VALUE then FAsyncFileHandle := 0; end; end; procedure TEncryptedFile.DecodeDataBlock(const Source; var Dest; DataSize: Integer); var APassword: AnsiString; Bytes: TBytes; AHash: TDECHashClass; begin AHash := ValidHash(nil); Bytes := TEncoding.UTF8.GetBytes(FPassword); SetLength(APassword, Length(Bytes)); Move(Bytes[0], APassword[1], Length(Bytes)); with FChipper.Create do try Mode := CmCTSx; Init(AHash.KDFx(APassword, FSalt, Context.KeySize)); Decode(Source, Dest, DataSize); finally Free; end; end; destructor TEncryptedFile.Destroy; begin F(FFileBlocks); //don't free items -> application should call FreeBlock to avoid //memory leaks in winows kernel F(FMemoryBlocks); if FAsyncFileHandle <> 0 then CloseHandle(FAsyncFileHandle); F(FSync); inherited; end; procedure TEncryptedFile.FreeBlock(Block: Pointer); var Index: Integer; begin Index := FMemoryBlocks.IndexOf(Block); if Index > -1 then begin FMemoryBlocks.Remove(Block); FreeMem(Block); end; end; function TEncryptedFile.GetBlock(BlockPosition, BlockSize: Int64): Pointer; begin if BlockSize = 0 then BlockSize := Size; GetMem(Result, BlockSize); ReadBlock(Result^, BlockPosition, BlockSize); end; function TEncryptedFile.GetBlockByIndex(Index: Int64): TMemoryBlock; var I: Integer; B: TMemoryBlock; SData, DData: Pointer; Res: BOOL; BlockStart, CurrentPosition: Int64; BlockSize: Integer; lpNumberOfBytesTransferred, lpNumberOfBytesRead: DWORD; MemorySize, FileReadPosition: Int64; lpOverlapped: POverlapped; Async: Boolean; FileHandle: THandle; begin Result := nil; Async := FlpOverlapped <> nil; // FIsAsyncHandle FileHandle := FHandle; if Async and (FAsyncFileHandle <> 0) then FileHandle := FAsyncFileHandle; for I := FFileBlocks.Count - 1 downto 0 do begin B := FFileBlocks[I]; if B.Index = Index then begin if I < FFileBlocks.Count - 1 then begin FFileBlocks.Remove(B); FFileBlocks.Add(B); end; Exit(B); end; end; MemorySize := 0; for I := 0 to FFileBlocks.Count - 1 do MemorySize := MemorySize + TMemoryBlock(FFileBlocks[I]).Size; while (MemorySize > FMemoryLimit) and (FFileBlocks.Count > 0) do begin B := FFileBlocks[0]; MemorySize := MemorySize - B.Size; FFileBlocks.Delete(0); FreeMem(B.Memory); F(B); end; BlockStart := Index * FBlockSize; BlockSize := FBlockSize; if BlockStart + BlockSize >= Size then BlockSize := Size - BlockStart; if BlockSize <= 0 then Exit; CurrentPosition := 0; if not Async then begin CurrentPosition := FileSeek(FileHandle, Int64(0), FILE_CURRENT); FileSeek(FileHandle, BlockStart + FHeaderSize, FILE_BEGIN); end; SData := AllocMem(BlockSize); try lpOverlapped := nil; if Async then begin New(lpOverlapped); FillChar(lpOverlapped^, SizeOf(TOverlapped), #0); FileReadPosition := BlockStart + FHeaderSize; lpOverlapped.Offset := Int64Rec(FileReadPosition).Lo; lpOverlapped.OffsetHigh := Int64Rec(FileReadPosition).Hi; end; try Res := ReadFile(FileHandle, SData^, BlockSize, @lpNumberOfBytesRead, lpOverlapped); if Res or (not Res and Async and (GetLastError = ERROR_IO_PENDING)) then begin if Async then begin if not GetOverlappedResult(FileHandle, lpOverlapped^, lpNumberOfBytesTransferred, True) then Exit(nil); if lpNumberOfBytesTransferred = 0 then Exit(nil); end; GetMem(DData, BlockSize); try DecodeDataBlock(SData^, DData^, BlockSize); Result := TMemoryBlock.Create; Result.Index := Index; Result.Size := BlockSize; Result.Memory := DData; DData := nil; FFileBlocks.Add(Result); finally if DData <> nil then FreeMem(DData); end; end; finally if Async then Dispose(lpOverlapped); end; finally FreeMem(SData); end; if not Async then FileSeek(FileHandle, CurrentPosition, FILE_BEGIN); end; function TEncryptedFile.GetSize: Int64; begin Int64Rec(Result).Lo := Winapi.Windows.GetFileSize(FHandle, @Int64Rec(Result).Hi); Result := Result - FHeaderSize; end; procedure TEncryptedFile.ReadBlock(const Block; BlockPosition, BlockSize: Int64; lpOverlapped: POverlapped = nil); var I, StartBlock, BlockEnd: Integer; B: TMemoryBlock; S, D: Pointer; MemoryToCopy, MemoryCopied, C: Integer; StartBlockPosition: Integer; begin if BlockSize = 0 then Exit; FlpOverlapped := lpOverlapped; StartBlock := BlockPosition div FBlockSize; BlockEnd := Ceil((BlockPosition + BlockSize) / FBlockSize); MemoryToCopy := BlockSize; MemoryCopied := 0; for I := StartBlock to BlockEnd do begin if MemoryToCopy > 0 then begin B := Blocks[I]; if B <> nil then begin C := MemoryToCopy; if C > B.Size then C := B.Size; StartBlockPosition := BlockPosition + MemoryCopied - B.Index * FBlockSize; if StartBlockPosition + C > B.Size then C := B.Size - StartBlockPosition; D := Pointer(MemoryCopied + NativeInt(Addr(Pointer(Block)))); S := Pointer(StartBlockPosition + NativeInt(B.Memory)); CopyMemory(D, S, C); MemoryToCopy := MemoryToCopy - C; MemoryCopied := MemoryCopied + C; end; end; end; if (MemoryToCopy > 0) then begin D := Pointer(MemoryCopied + NativeInt(Addr(Pointer(Block)))); FillChar(D^, MemoryToCopy, #0); if Assigned(FErrorHander) then FErrorHander('ReadBlock, LIMIT'); end; end; { TEncryptionOptions } function TEncryptionOptions.CanBeTransparentEncryptedFile( FileName: string): Boolean; var Ext: string; begin Ext := AnsiUpperCase(ExtractFileExt(FileName)); FSync.BeginRead; try Result := FFileExtensionList.IndexOf(Ext) > 0; finally FSync.EndRead; end; end; constructor TEncryptionOptions.Create; begin FSync := CreateRWLock; Refresh; end; destructor TEncryptionOptions.Destroy; begin FSync := nil; inherited; end; procedure TEncryptionOptions.Refresh; {$IFDEF PHOTODB} var Associations: TStrings; I: Integer; {$ENDIF} begin FSync.BeginWrite; try FFileExtensionList := ''; {$IFDEF PHOTODB} Associations := AppSettings.ReadKeys(cMediaAssociationsData); try for I := 0 to Associations.Count - 1 do FFileExtensionList := FFileExtensionList + ':' + AnsiUpperCase(Associations[I]); finally F(Associations); end; {$ENDIF} finally FSync.EndWrite; end; end; initialization finalization F(FEncryptionOptions); end.
unit Threads; interface uses System.Classes, Winapi.Windows, System.SysUtils; type TMethod = procedure of object; TCoreThread = class(TThread) private ThreadMethod:TMethod; SleepInterval: Uint16; protected procedure Execute; override; public procedure SetThreadMethod(Method:TMethod); procedure SetSleepInterval(Value:UInt16); end; TThreadContainer = class private TCount:UInt16; T1:array[0..64] of TCoreThread; public constructor Create(Method:TMethod); destructor Destroy; override; function GetTCount: Uint16; end; function GetNumberOfProcessors: UInt16; var FT:Int64; ErrorsCounter:UInt32; implementation { ThreadContainer := TThreadContainer.Create(Method); } function GetNumberOfProcessors: UInt16; var SIRecord: TSystemInfo; begin GetSystemInfo(SIRecord); Result := SIRecord.dwNumberOfProcessors; end; { TCoreThread } procedure TCoreThread.Execute; var F:Int64; begin inherited; repeat Synchronize(Self.ThreadMethod); System.YieldProcessor; SleepEx(Self.SleepInterval,False); until Terminated; end; procedure TCoreThread.SetSleepInterval(Value: UInt16); begin Self.SleepInterval := Value; end; procedure TCoreThread.SetThreadMethod(Method: TMethod); begin Self.ThreadMethod := Method; end; { TThreadContainer } constructor TThreadContainer.Create(Method:TMethod); var I:Uint16; begin TCount := GetNumberOfProcessors; for I := 0 to TCount - 1 do begin T1[I] := TCoreThread.Create(True); T1[I].SetThreadMethod(Method); T1[I].Priority := tpIdle; T1[I].SetSleepInterval(0); T1[I].Start; end; end; destructor TThreadContainer.Destroy; var I:Uint16; begin for I := 0 to TCount do T1[I].Free; end; function TThreadContainer.GetTCount: Uint16; begin Result := TCount; end; end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXSAPIL0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* Lists all installed SAPI voice recognition and speech *} {* synthesis engines. Provides a large amount of detail *} {* on each engine. *} {*********************************************************} unit ExSapiL0; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OoMisc, AdSapiEn, ExtCtrls, Grids, StdCtrls; type TForm1 = class(TForm) ApdSapiEngine1: TApdSapiEngine; Panel1: TPanel; gridSR: TStringGrid; Splitter1: TSplitter; gridSS: TStringGrid; Label1: TLabel; Label2: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses ExSapiL1; {$R *.DFM} procedure TForm1.FormCreate(Sender: TObject); var i : Integer; begin if (not ApdSapiEngine1.IsSapi4Installed) then begin ShowMessage ('SAPI is not installed. This example will now exit'); Application.Terminate; Exit; end; frmLoading := TfrmLoading.Create (Self); try frmLoading.ProgressBar1.Max := ApdSapiEngine1.SSVoices.Count + ApdSapiEngine1.SREngines.Count; frmLoading.Show; Application.ProcessMessages; { Fill in the column headers } gridSS.Cells[0, 0] := 'Name'; gridSS.Cells[1, 0] := 'Dialect'; gridSS.Cells[2, 0] := 'Engine ID'; gridSS.Cells[3, 0] := 'Manufacturer Name'; gridSS.Cells[4, 0] := 'Mode ID'; gridSS.Cells[5, 0] := 'Product Name'; gridSS.Cells[6, 0] := 'Speaker'; gridSS.Cells[7, 0] := 'Style'; gridSS.Cells[8, 0] := 'Age'; gridSS.Cells[9, 0] := 'Gender'; gridSS.Cells[10, 0] := 'Language ID'; gridSS.Cells[11, 0] := 'Any Word'; gridSS.Cells[12, 0] := 'Volume'; gridss.Cells[13, 0] := 'Speed'; gridss.Cells[14, 0] := 'Pitch'; gridss.Cells[15, 0] := 'Tagged'; gridss.Cells[16, 0] := 'IPA Unicode'; gridss.Cells[17, 0] := 'Visual'; gridss.Cells[18, 0] := 'Word Position'; gridss.Cells[19, 0] := 'PC Optimized'; gridss.Cells[20, 0] := 'Phone Optimized'; gridss.Cells[21, 0] := 'Fixed Audio'; gridss.Cells[22, 0] := 'Single Instance'; gridss.Cells[23, 0] := 'Thread Safe'; gridss.Cells[24, 0] := 'IPA Text Data'; gridss.Cells[25, 0] := 'Preferred'; gridss.Cells[26, 0] := 'Transplanted'; gridss.Cells[27, 0] := 'SAPI4'; { Get information on the speech synthesis voices } for i := 0 to ApdSapiEngine1.SSVoices.Count - 1 do begin gridSS.RowCount := i + 2; gridSS.Cells[0, i + 1] := ApdSapiEngine1.SSVoices[i]; gridSS.Cells[1, i + 1] := ApdSapiEngine1.SSVoices.Dialect[i]; gridSS.Cells[2, i + 1] := ApdSapiEngine1.SSVoices.EngineID[i]; gridSS.Cells[3, i + 1] := ApdSapiEngine1.SSVoices.MfgName[i]; gridSS.Cells[4, i + 1] := ApdSapiEngine1.SSVoices.ModeID[i]; gridSS.Cells[5, i + 1] := ApdSapiEngine1.SSVoices.ProductName[i]; gridSS.Cells[6, i + 1] := ApdSapiEngine1.SSVoices.Speaker[i]; gridSS.Cells[7, i + 1] := ApdSapiEngine1.SSVoices.Style[i]; case ApdSapiEngine1.SSVoices.Age[i] of tsBaby : gridSS.Cells[8, i + 1] := 'Baby'; tsToddler : gridSS.Cells[8, i + 1] := 'Toddler'; tsChild : gridSS.Cells[8, i + 1] := 'Child'; tsAdolescent : gridSS.Cells[8, i + 1] := 'Adolescent'; tsAdult : gridSS.Cells[8, i + 1] := 'Adult'; tsElderly : gridSS.Cells[8, i + 1] := 'Elderly'; else gridSS.Cells[8, i + 1] := 'Unknown'; end; case ApdSapiEngine1.SSVoices.Gender[i] of tgNeutral : gridSS.Cells[9, i + 1] := 'Neutral'; tgFemale : gridSS.Cells[9, i + 1] := 'Female'; tgMale : gridSS.Cells[9, i + 1] := 'Male'; else gridSS.Cells[9, i + 1] := 'Unknown'; end; gridSS.Cells[10, i + 1] := IntToStr (ApdSapiEngine1.SSVoices.LanguageID[i]); if tfAnyWord in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[11, i + 1] := 'Yes'; if tfVolume in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[12, i + 1] := 'Yes'; if tfSpeed in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[13, i + 1] := 'Yes'; if tfPitch in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[14, i + 1] := 'Yes'; if tfTagged in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[15, i + 1] := 'Yes'; if tfIPAUnicode in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[16, i + 1] := 'Yes'; if tfVisual in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[17, i + 1] := 'Yes'; if tfWordPosition in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[18, i + 1] := 'Yes'; if tfPCOptimized in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[19, i + 1] := 'Yes'; if tfPhoneOptimized in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[20, i + 1] := 'Yes'; if tfFixedAudio in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[21, i + 1] := 'Yes'; if tfSingleInstance in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[22, i + 1] := 'Yes'; if tfThreadSafe in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[23, i + 1] := 'Yes'; if tfIPATextData in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[24, i + 1] := 'Yes'; if tfPreferred in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[25, i + 1] := 'Yes'; if tfTransplanted in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[26, i + 1] := 'Yes'; if tfSAPI4 in ApdSapiEngine1.SSVoices.Features[i] then gridSS.Cells[27, i + 1] := 'Yes'; frmLoading.ProgressBar1.Position := frmLoading.ProgressBar1.Position + 1; end; gridSS.FixedRows := 1; gridSS.FixedCols := 1; frmLoading.Label1.Caption := 'Loading SAPI Speech Recognition Engine Details'; gridSR.Cells[0, 0] := 'Name'; gridSR.Cells[1, 0] := 'Dialect'; gridSR.Cells[2, 0] := 'Engine ID'; gridSR.Cells[3, 0] := 'Mfg Name'; gridSR.Cells[4, 0] := 'Mode ID'; gridSR.Cells[5, 0] := 'Product Name'; gridSR.Cells[6, 0] := 'CFG'; gridSR.Cells[7, 0] := 'Dictation'; gridSR.Cells[8, 0] := 'Limited Domain'; gridSR.Cells[9, 0] := 'Language ID'; gridSR.Cells[10, 0] := 'Max Words State'; gridSR.Cells[11, 0] := 'Max Words Vocab'; gridSR.Cells[12, 0] := 'Sequencing'; gridSR.Cells[13, 0] := 'Indep Speaker'; gridSR.Cells[14, 0] := 'Indep Microphone'; gridSR.Cells[15, 0] := 'Train Word'; gridSR.Cells[16, 0] := 'Train Phonetic'; gridSR.Cells[17, 0] := 'Wildcard'; gridSR.Cells[18, 0] := 'Any Word'; gridSR.Cells[19, 0] := 'PC Optimized'; gridSR.Cells[20, 0] := 'Phone Optimized'; gridSR.Cells[21, 0] := 'Gram List'; gridSR.Cells[22, 0] := 'Gram Link'; gridSR.Cells[23, 0] := 'Multi Lingual'; gridSR.Cells[24, 0] := 'Gram Recursive'; gridSR.Cells[25, 0] := 'IPA Unicode'; gridSR.Cells[26, 0] := 'Single Instance'; gridSR.Cells[27, 0] := 'Thread Safe'; gridSR.Cells[28, 0] := 'Fixed Audio'; gridSR.Cells[29, 0] := 'IPA Word'; gridSR.Cells[30, 0] := 'SAPI4'; for i := 0 to ApdSapiEngine1.SREngines.Count - 1 do begin gridSR.RowCount := i + 2; gridSR.Cells[0, i + 1] := ApdSapiEngine1.SREngines[i]; gridSR.Cells[1, i + 1] := ApdSapiEngine1.SREngines.Dialect[i]; gridSR.Cells[2, i + 1] := ApdSapiEngine1.SREngines.EngineID[i]; gridSR.Cells[3, i + 1] := ApdSapiEngine1.SREngines.MfgName[i]; gridSR.Cells[4, i + 1] := ApdSapiEngine1.SREngines.ModeID[i]; gridSR.Cells[5, i + 1] := ApdSapiEngine1.SREngines.ProductName[i]; if sgCFG in ApdSapiEngine1.SREngines.Grammars[i] then gridSR.Cells[6, i + 1] := 'Yes'; if sgDictation in ApdSapiEngine1.SREngines.Grammars[i] then gridSR.Cells[7, i + 1] := 'Yes'; if sgLimitedDomain in ApdSapiEngine1.SREngines.Grammars[i] then gridSR.Cells[8, i + 1] := 'Yes'; gridSR.Cells[9, i + 1] := IntToStr (ApdSapiEngine1.SREngines.LanguageID[i]); gridSR.Cells[10, i + 1] := IntToStr (ApdSapiEngine1.SREngines.MaxWordsState[i]); gridSR.Cells[11, i + 1] := IntToStr (ApdSapiEngine1.SREngines.MaxWordsVocab[i]); case ApdSapiEngine1.SREngines.Sequencing[i] of ssDiscrete : gridSR.Cells[12, i + 1] := 'Discrete'; ssContinuous : gridSR.Cells[12, i + 1] := 'Continuous'; ssWordSpot : gridSR.Cells[12, i + 1] := 'Word Spotting'; ssContCFGDiscDict : gridSR.Cells[12, i + 1] := 'CFG Discrete Dictionary'; else gridSR.Cells[12, i + 1] := 'Unknown'; end; if sfIndepSpeaker in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[13, i + 1] := 'Yes'; if sfIndepMicrophone in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[14, i + 1] := 'Yes'; if sfTrainWord in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[15, i + 1] := 'Yes'; if sfTrainPhonetic in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[16, i + 1] := 'Yes'; if sfWildcard in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[17, i + 1] := 'Yes'; if sfAnyWord in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[18, i + 1] := 'Yes'; if sfPCOptimized in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[19, i + 1] := 'Yes'; if sfPhoneOptimized in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[20, i + 1] := 'Yes'; if sfGramList in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[21, i + 1] := 'Yes'; if sfGramLink in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[22, i + 1] := 'Yes'; if sfMultiLingual in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[23, i + 1] := 'Yes'; if sfGramRecursive in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[24, i + 1] := 'Yes'; if sfIPAUnicode in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[25, i + 1] := 'Yes'; if sfSingleInstance in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[26, i + 1] := 'Yes'; if sfThreadSafe in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[27, i + 1] := 'Yes'; if sfFixedAudio in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[28, i + 1] := 'Yes'; if sfIPAWord in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[29, i + 1] := 'Yes'; if sfSAPI4 in ApdSapiEngine1.SREngines.Features[i] then gridSR.Cells[30, i + 1] := 'Yes'; frmLoading.ProgressBar1.Position := frmLoading.ProgressBar1.Position + 1; end; gridSR.FixedRows := 1; gridSR.FixedCols := 1; finally frmLoading.Free; end; end; end.
// // This unit is part of the VXScene Project, http://glscene.org // { Implements a HDS Filter that generates HeightData tiles in a seperate thread. This component is a TVXHeightDataSourceFilter, which uses a TVXHeightDataSourceThread, to asyncronously search the HeightData cache for any queued tiles. When found, it then prepares the queued tile in its own TVXHeightDataThread. This allows the GUI to remain responsive, and prevents freezes when new tiles are being prepared. Although this keeps the framerate up, it may cause holes in the terrain to show, if the HeightDataThreads cant keep up with the TerrainRenderer's requests for new tiles. } unit VXS.AsyncHDS; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.HeightData, VXS.CrossPlatform; type TVXAsyncHDS = class; TIdleEvent = procedure(Sender: TVXAsyncHDS; TilesUpdated: boolean) of object; TNewTilePreparedEvent = procedure(Sender: TVXAsyncHDS; HeightData: TVXHeightData) of object; // a tile was updated (called INSIDE the sub-thread?) (* Determines if/how dirty tiles are displayed and when they are released. When a tile is maked as dirty, a replacement is queued immediately. However, the replacement cant be used until the HDThread has finished preparing it. Dirty tiles can be deleted as soon as they are no longer used/displayed. Possible states for a TUseDirtyTiles. hdsNever : Dirty tiles get released immediately, leaving a hole in the terrain, until the replacement is hdsReady. hdsUntilReplaced : Dirty tiles are used, until the HDThread has finished preparing the queued replacement. hdsUntilAllReplaced : Waits until the HDSThread has finished preparing ALL queued tiles, before allowing the renderer to switch over to the new set of tiles. (This prevents a fading checkerbox effect.) *) TUseDirtyTiles=(dtNever,dtUntilReplaced,dtUntilAllReplaced); TVXAsyncHDS = class(TVXHeightDataSourceFilter) private FOnIdleEvent: TIdleEvent; FOnNewTilePrepared: TNewTilePreparedEvent; FUseDirtyTiles: TUseDirtyTiles; FTilesUpdated: boolean; public // TilesUpdated:boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeforePreparingData(HeightData: TVXHeightData); override; procedure StartPreparingData(HeightData: TVXHeightData); override; procedure ThreadIsIdle; override; procedure NewTilePrepared(HeightData: TVXHeightData); function ThreadCount: integer; (* Wait for all running threads to finish. Should only be called after setting Active to false, to prevent new threads from starting. *) procedure WaitFor(TimeOut: integer = 2000); // procedure NotifyChange(Sender : TObject); override; (* This function prevents the user from trying to write directly to this variable. FTilesUpdated if NOT threadsafe and should only be reset with TilesUpdatedFlagReset. *) function TilesUpdated: boolean; // Returns true if tiles have been updated since the flag was last reset procedure TilesUpdatedFlagReset; // sets the TilesUpdatedFlag to false; (is ThreadSafe) published property OnIdle: TIdleEvent read FOnIdleEvent write FOnIdleEvent; property OnNewTilePrepared: TNewTilePreparedEvent read FOnNewTilePrepared write FOnNewTilePrepared; property UseDirtyTiles: TUseDirtyTiles read FUseDirtyTiles write FUseDirtyTiles; property MaxThreads; // sets the maximum number of simultaineous threads that will prepare tiles.(>1 is rarely needed) property Active; // set to false, to ignore new queued tiles.(Partially processed tiles will still be completed) end; TVXAsyncHDThread = class(TVXHeightDataThread) public Owner: TVXAsyncHDS; HDS: TVXHeightDataSource; Procedure Execute; override; Procedure Sync; end; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------ // ------------------ TVXAsyncHDS ------------------ // ------------------ constructor TVXAsyncHDS.Create(AOwner: TComponent); begin inherited Create(AOwner); MaxThreads := 1; FUseDirtyTiles := dtNever; FTilesUpdated := true; end; destructor TVXAsyncHDS.Destroy; begin inherited Destroy; end; procedure TVXAsyncHDS.BeforePreparingData(HeightData: TVXHeightData); begin if FUseDirtyTiles = dtNever then begin if HeightData.OldVersion <> nil then begin HeightData.OldVersion.DontUse := true; HeightData.DontUse := false; end; end; if assigned(HeightDataSource) then HeightDataSource.BeforePreparingData(HeightData); end; procedure TVXAsyncHDS.StartPreparingData(HeightData: TVXHeightData); var HDThread: TVXAsyncHDThread; HDS: TVXHeightDataSource; begin HDS := HeightDataSource; // ---if there is no linked HDS then return an empty tile-- if not assigned(HDS) then begin HeightData.DataState := hdsNone; exit; end; if (Active = false) then exit; // ---If not using threads then prepare the HD tile directly--- (everything else freezes until done) if MaxThreads = 0 then begin HDS.StartPreparingData(HeightData); if HeightData.DataState = hdsPreparing then HeightData.DataState := hdsReady else HeightData.DataState := hdsNone; end else begin // --MaxThreads>0 : start the thread and go back to start the next one-- HeightData.DataState := hdsPreparing; // prevent other threads from preparing this HD. HDThread := TVXAsyncHDThread.Create(true); HDThread.Owner := self; HDThread.HDS := self.HeightDataSource; HDThread.HeightData := HeightData; HeightData.Thread := HDThread; HDThread.FreeOnTerminate := false; HDThread.Start; end; end; procedure TVXAsyncHDS.ThreadIsIdle; var i: integer; lst: TList; HD: TVXHeightData; begin // ----------- dtUntilAllReplaced ------------- // Switch to the new version of ALL dirty tiles lst := self.Data.LockList; try if FUseDirtyTiles = dtUntilAllReplaced then begin i := lst.Count; while (i > 0) do begin dec(i); HD := TVXHeightData(lst.Items[i]); if (HD.DataState in [hdsReady, hdsNone]) and (HD.DontUse) and (HD.OldVersion <> nil) then begin HD.DontUse := false; HD.OldVersion.DontUse := true; FTilesUpdated := true; end; end; end; // Until All Replaced if assigned(FOnIdleEvent) then FOnIdleEvent(self, FTilesUpdated); finally self.Data.UnlockList; end; // -------------------------------------------- end; procedure TVXAsyncHDS.NewTilePrepared(HeightData: TVXHeightData); var HD: TVXHeightData; begin if assigned(HeightDataSource) then HeightDataSource.AfterPreparingData(HeightData); with self.Data.LockList do begin try HD := HeightData; // --------------- dtUntilReplaced ------------- // Tell terrain renderer to display the new tile if (FUseDirtyTiles = dtUntilReplaced) and (HD.DontUse) and (HD.OldVersion <> nil) then begin HD.DontUse := false; // No longer ignore the new tile HD.OldVersion.DontUse := true; // Start ignoring the old tile end; // --------------------------------------------- if HD.DontUse = false then FTilesUpdated := true; if assigned(FOnNewTilePrepared) then FOnNewTilePrepared(self, HeightData); // OnNewTilePrepared Event finally self.Data.UnlockList; end; end; end; function TVXAsyncHDS.ThreadCount: integer; var lst: TList; i, TdCtr: integer; HD: TVXHeightData; begin lst := self.Data.LockList; i := 0; TdCtr := 0; while (i < lst.Count) and (TdCtr < self.MaxThreads) do begin HD := TVXHeightData(lst.Items[i]); if HD.Thread <> nil then Inc(TdCtr); Inc(i); end; self.Data.UnlockList; result := TdCtr; end; procedure TVXAsyncHDS.WaitFor(TimeOut: integer = 2000); var OutTime: TDateTime; begin Assert(self.Active = false); OutTime := now + TimeOut; While ((now < OutTime) and (ThreadCount > 0)) do begin sleep(0); end; Assert(ThreadCount = 0); end; { procedure TVXAsyncHDS.NotifyChange(Sender : TObject); begin TilesChanged:=true; end; } function TVXAsyncHDS.TilesUpdated: boolean; begin result := FTilesUpdated; end; // Set the TilesUpdatedFlag to false. (is Threadsafe) procedure TVXAsyncHDS.TilesUpdatedFlagReset; begin if not assigned(self) then exit; // prevents AV on Application termination. with Data.LockList do try FTilesUpdated := false; finally Data.UnlockList; end; end; // -------------------HD Thread---------------- Procedure TVXAsyncHDThread.Execute; Begin HDS.StartPreparingData(HeightData); HeightData.Thread := nil; Synchronize(Sync); end; Procedure TVXAsyncHDThread.Sync; begin Owner.NewTilePrepared(HeightData); if HeightData.DataState = hdsPreparing then HeightData.DataState := hdsReady; end; // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ RegisterClass(TVXAsyncHDS); end.
unit uFrmTEFCheque; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFrmTEFCheque = class(TForm) btnAbort: TButton; Selecionar: TButton; pnlManual: TPanel; edtCompens: TLabeledEdit; edtBanco: TLabeledEdit; edtAgencia: TLabeledEdit; edtC1: TLabeledEdit; edtContaC: TLabeledEdit; edtC2: TLabeledEdit; edtNumCheque: TLabeledEdit; edtC3: TLabeledEdit; pnlLeituraCMC7: TPanel; edtCMC7: TEdit; Label1: TLabel; procedure btnAbortClick(Sender: TObject); procedure SelecionarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure edtCompensKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtCompensEnter(Sender: TObject); private iStartType : Integer; FResult : String; public function StartManual(Msg: String) : String; function StartLeitura(Msg: String) : String; end; implementation {$R *.dfm} { TFrmTEFCheque } function TFrmTEFCheque.StartManual(Msg: String): String; begin Self.Caption := Msg; pnlManual.Visible := True; pnlLeituraCMC7.Visible := False; iStartType := 0; FResult := '-1'; ShowModal; Result := FResult; end; procedure TFrmTEFCheque.btnAbortClick(Sender: TObject); begin Close; end; procedure TFrmTEFCheque.SelecionarClick(Sender: TObject); begin if iStartType = 0 then FResult := '0:' + edtCompens.Text + edtBanco.Text + edtAgencia.Text + edtC1.Text + edtContaC.Text + edtC2.Text + edtNumCheque.Text + edtC3.Text else FResult := '1:' + edtCMC7.Text; Close; end; procedure TFrmTEFCheque.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; function TFrmTEFCheque.StartLeitura(Msg: String): String; begin Self.Caption := Msg; pnlManual.Visible := False; pnlLeituraCMC7.Visible := True; iStartType := 1; edtCMC7.Clear; FResult := '-1'; ShowModal; Result := FResult; end; procedure TFrmTEFCheque.FormShow(Sender: TObject); begin if iStartType = 1 then if edtCMC7.CanFocus then edtCMC7.SetFocus; end; procedure TFrmTEFCheque.edtCompensKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if TEdit(Sender).MaxLength = Length(TEdit(Sender).Text) then if TEdit(Sender).Name = 'edtCompens' then edtBanco.SetFocus else if TEdit(Sender).Name = 'edtBanco' then edtAgencia.SetFocus else if TEdit(Sender).Name = 'edtAgencia' then edtC1.SetFocus else if TEdit(Sender).Name = 'edtC1' then edtContaC.SetFocus else if TEdit(Sender).Name = 'edtContaC' then edtC2.SetFocus else if TEdit(Sender).Name = 'edtC2' then edtNumCheque.SetFocus else if TEdit(Sender).Name = 'edtNumCheque' then edtC3.SetFocus; end; procedure TFrmTEFCheque.edtCompensEnter(Sender: TObject); begin TEdit(Sender).Clear; end; end.
unit clsTeachers; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, clsHouse; type TTeachers = class private fArrAnswers : array[1..40] of string; fArrQuestions : array[1..40] of string; public constructor Create; destructor Destroy; override; procedure setAnswers; procedure setQuestions; function getAnswer(iNo : integer) : string; function getQuestion(iNo : integer) : string; end; implementation { TTeachers } constructor TTeachers.Create; begin setQuestions; setAnswers; end; destructor TTeachers.Destroy; begin inherited; end; function TTeachers.getAnswer(iNo: integer): string; begin result := fArrAnswers[iNo]; end; function TTeachers.getQuestion(iNo: integer): string; begin result := fArrQuestions[iNo]; end; procedure TTeachers.setAnswers; var sPath, sAdd : string; TFAnswers : textfile; iAnswer : integer; begin iAnswer := 0; sPath := GetCurrentDir()+'\Answers\'; sAdd := 'Teachers' + '.txt'; sPath := sPath + sAdd; if FileExists(sPath) <> true then begin ShowMessage('File ' + sPath + ' does not exist!'); Exit; end; AssignFile(TFAnswers, sPath); Reset(TFAnswers); while (not EOF(TFAnswers)) AND (iAnswer <= 40) do begin inc(iAnswer); readln(TFAnswers, fArrAnswers[iAnswer]); end; CloseFile(TFAnswers); end; procedure TTeachers.setQuestions; var sPath, sAdd : string; TFQuestions : textfile; iQuestion : integer; begin iQuestion := 0; sPath := GetCurrentDir()+'\Questions\'; sAdd := 'Teachers' + '.txt'; sPath := sPath + sAdd; if FileExists(sPath) <> true then begin ShowMessage('File ' + sPath + ' does not exist!'); Exit; end; AssignFile(TFQuestions, sPath); Reset(TFQuestions); while (not EOF(TFQuestions)) AND (iQuestion <= 40) do begin inc(iQuestion); readln(TFQuestions, fArrQuestions[iQuestion]); end; CloseFile(TFQuestions); end; end.
unit HistoryList; { The THistoryList and TBookmarks Components V1.00 MOST IMPORTANT :) ================= This is NOT Freeware: It's PostCardWare. When you use this component or think it's useful, send me a post-card to: Florian Bömers, Colmarer Str.11, D - 28211 Bremen, Germany See legal.txt for more details. And of course, I am very interested in any application that uses this component (or any other application you wrote). If so, mail me (not the program, just an URL or similar) ! (mail address below) Installation: ============= 1. Copy the files HistoryList.pas and HistoryList.dcr to the directory where you store your components (or let it where it is) 2. In Delphi, select Component|Install Component. In the following dialog enter the path and filename of HistoryList.pas and hit OK. 3. Now the THistoryList and TBookmarks components are available in the component palette under "Bome". Description =========== THistoryList: Manage a list of Most Recently Used files. You select the menu where the list will be appended. Usually this is the File menu, but you can also designate a "Recent Files" menu item, as seen in the file menu of Delphi 3. The addFilename procedure adds a filename to the history list. It is always appended at first position. The Directories property lets you specify whether the stored items are directories rather than files. TBookmarks: Manages a bookmark menu. Choose as base menu an empty menu item. At run time an add item is created automatically. When the user selects "Add", the event OnGetBookmark is fired where you have to provide the bookmark and a name for the bookmark. The name will appear in the menu. Also a Delete item is managed which lets the user delete an item. The FileBookmarks property lets you specify that the stored items are files rather than directories. Both components: The OnClick event occurs when the user selected an item. The filename will be passed to the event handler. In both components you have a RegKey item. There you give an unique name in your project. The RegPath is composed of your company name and the program name, separated by a backslash. When you provide the registry parameters, the components initialize themselves at start-up. Use the saveToRegistry procedure to let the component store themselves to registry. They are saved in HKEY_CURRENT_USER\Software\<RegPath>\RegKey. For an example implementation see the demo directory. Copyright ========= (c) 1997-1999 by Florian Bömers send any comments, proposals, enhancements etc. to: delphi@bome.com other free components on: http://www.bome.com } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Registry, Menus; type TMenuNotify=procedure(Sender:TObject; Filename:String) of object; TOnGetBookmark=procedure(Sender:TObject; var Bookmark:String; var Name:String) of object; TDynamicMenuBase = class(TComponent) private FRegPath:String; FRegKey:String; FBaseMenu:TMenuItem; FOnClick:TMenuNotify; FLoadedReg:Boolean; FFirstMenuItemIndex:Integer; FSaveNames:Boolean; FRegFiles:String; FRegNames:String; FHelpContext:THelpContext; function ReadyToLoadReg:Boolean; virtual; abstract; function getFullRegPath:String; function getCount:Integer; virtual; abstract; function getItem(index:Integer):TMenuItem; procedure SetRegPath(RegPath:String); procedure SetRegKey(RegKey:String); procedure SetBaseMenu(baseMenu:TMenuItem); virtual; protected procedure loadFromRegistry; procedure MenuItemClick(Sender:TObject); procedure SetHelpContext(hc:THelpContext); public constructor Create(AOwner:TComponent); override; procedure saveToRegistry; procedure addFilename(Filename:String); virtual; abstract; property Count:Integer read getCount; property Items[Index: Integer]:TMenuItem read getItem; published property RegPath:String read FRegPath write SetRegPath; property RegKey:String read FRegKey write SetRegKey; property BaseMenu:TMenuItem read FBaseMenu write setBaseMenu; property OnClick:TMenuNotify read FOnClick write FOnClick; property HelpContext:THelpContext read FHelpContext write setHelpContext default 0; end; THistoryList = class(TDynamicMenuBase) private FMaxItems:Integer; FMaxItemsSet:Boolean; FDirectories:Boolean; function getCount:Integer; override; procedure SetMaxItems(maxItems:Integer); function ReadyToLoadReg:Boolean; override; procedure SetBaseMenu(baseMenu:TMenuItem); override; procedure RebuildCaptions; public constructor Create(AOwner:TComponent); override; procedure addFilename(Filename:String); override; procedure RemoveFilename(Filename:String); published property MaxItems:Integer read FMaxItems write SetMaxItems stored true; property Directories:Boolean read FDirectories write FDirectories default false; property HelpContext; end; TBookmarks = class(TDynamicMenuBase) private FFileBookmarks:Boolean; FFileBookMarksSet:Boolean; FDeleteMenu:TMenuItem; FOnGetBookmark:TOnGetBookmark; FDelHelpContext:THelpContext; FAddHelpContext:THelpContext; function getCount:Integer; override; procedure SetFileBookmarks(FileBookmarks:Boolean); procedure SetOnGetBookmark(OnGetBookmark:TOnGetBookmark); function ReadyToLoadReg:Boolean; override; procedure SetBaseMenu(baseMenu:TMenuItem); override; procedure SetDelHelpContext(hc:THelpContext); procedure SetAddHelpContext(hc:THelpContext); protected procedure AddClick(Sender:TObject); procedure DelClick(Sender:TObject); public constructor Create(AOwner:TComponent); override; procedure addFilename(Filename:String); override; published property FileBookmarks:Boolean read FFileBookmarks write SetFileBookmarks stored true; property OnGetBookmark:TOnGetBookmark read FOnGetBookmark write SetOnGetBookmark; property HelpContext; property AddHelpContext:THelpContext read FAddHelpContext write SetAddHelpContext default 0; property DelHelpContext:THelpContext read FDelHelpContext write SetDelHelpContext default 0; end; procedure Register; implementation const defaultRegPath='Company\Program Name'; defaultHistoryRegKey='MRUList'; defaultBookmarksRegKey='Bookmarks'; defaultMaxItems=4; RegValueName='MRU'; SNoItemsInHistory='(none)'; function DirectoryExists(const Name: string): Boolean; var Code: Integer; begin Code := GetFileAttributes(PChar(Name)); Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0); end; constructor TDynamicMenuBase.Create(AOwner:TComponent); begin inherited; FRegPath:=defaultRegPath; FRegKey:=''; FBaseMenu:=nil; FOnClick:=nil; FLoadedReg:=false; FFirstMenuItemIndex:=-1; FSaveNames:=true; FRegFiles:='File'; FRegNames:='Name'; FHelpContext:=0; end; procedure TDynamicMenuBase.SetRegPath(RegPath:String); begin FRegPath:=RegPath; LoadFromRegistry; end; procedure TDynamicMenuBase.SetRegKey(RegKey:String); begin FRegKey:=RegKey; LoadFromRegistry; end; procedure TDynamicMenuBase.SetBaseMenu(baseMenu:TMenuItem); begin if ((not assigned(FBaseMenu)) or (csDesigning in ComponentState)) and assigned(baseMenu) then begin FBaseMenu:=BaseMenu; LoadFromRegistry; end; end; function TDynamicMenuBase.getFullRegPath:String; begin result:='\Software\'+FRegPath+'\'+FRegKey; end; procedure TDynamicMenuBase.MenuItemClick(Sender:TObject); begin if assigned(FOnClick) then FOnClick(Self, TMenuItem(Sender).Hint); end; function TDynamicMenuBase.getItem(index:Integer):TMenuItem; begin if Count>0 then result:=BaseMenu[index+FFirstMenuItemIndex] else result:=nil; end; procedure TDynamicMenuBase.loadFromRegistry; var values:TStringList; i:Integer; begin if ReadyToLoadReg and assigned(BaseMenu) and (not (csDesigning in ComponentState)) and (not FLoadedReg) and (RegPath<>'') and (CompareStr(defaultRegPath,RegPath)<>0) then with TRegistry.Create do try if OpenKey(getFullRegPath,false) then try values:=TStringList.Create; // read sorted i:=0; try try while ValueExists(FRegFiles+IntToStr(i)) do begin values.add(ReadString(FRegFiles+IntToStr(i))); inc(i); end; except end; if values.Count>0 then for i:=values.Count-1 downto 0 do addFilename(values[i]); finally values.Free; end; finally CloseKey; end; finally Free; end; end; procedure TDynamicMenuBase.saveToRegistry; var i:Integer; begin if Assigned(BaseMenu) and (RegPath<>'') and (CompareStr(defaultRegPath,RegPath)<>0) and (not (csDesigning in ComponentState)) then with TRegistry.Create do try if OpenKey(getFullRegPath,true) then try // write items for i:=0 to Count-1 do begin WriteString(FRegFiles+IntToStr(i),items[i].Hint); end; // delete eventually old ones i:=getCount; while DeleteValue(FRegFiles+IntToStr(i)) do begin inc(i); end; finally CloseKey; end; finally Free; end; end; procedure TDynamicMenuBase.SetHelpContext(hc:THelpContext); var i:Integer; begin FHelpContext:=hc; if not (csDesigning in ComponentState) then for i:=0 to Count-1 do items[i].HelpContext:=HelpContext; end; { THistoryList } constructor THistoryList.Create(AOwner:TComponent); begin inherited; FRegKey:=defaultHistoryRegKey; FMaxItems:=defaultMaxItems; FMaxItemsSet:=false; FSaveNames:=true; //maybe we can find a default menu ? if (csDesigning in ComponentState) and (AOwner is TForm) and assigned(TForm(AOwner).Menu) then begin if assigned(TForm(AOwner).Menu.Items) and (TForm(AOwner).Menu.Items.Count>0) then FBaseMenu:=TForm(AOwner).Menu.Items.Items[0]; end; end; procedure THistoryList.SetBaseMenu(baseMenu:TMenuItem); begin if not assigned(FBaseMenu) and assigned(baseMenu) and (not (csDesigning in Componentstate)) then begin if BaseMenu.Count=0 then begin // BaseMenu.add(TMenuItem.Create(FBaseMenu)); // BaseMenu[0].Caption:=SNoItemsInHistory; // BaseMenu[0].Enabled:=false; end; end; inherited; end; function isMenuDisabled(menu:TMenuItem):Boolean; begin result:=(Menu.Count=1) and not Menu[0].enabled; end; function THistoryList.getCount:Integer; begin if assigned(BaseMenu) and (FFirstMenuItemIndex>=0) and not isMenuDisabled(BaseMenu) then result:=BaseMenu.Count-FFirstMenuItemIndex else result:=0; end; //name is ignored procedure THistoryList.addFilename(Filename:String); var mi :TMenuItem; i, lastMove :Integer; begin if (Length(FileName)>0) and assigned(BaseMenu) then begin if Count=0 then begin if isMenuDisabled(BaseMenu) then BaseMenu.Delete(0); if BaseMenu.Count>0 then begin mi:=TMenuItem.Create(FBaseMenu); mi.Caption:='-'; BaseMenu.add(mi); end; FFirstMenuItemIndex:=BaseMenu.Count; end; lastMove:=-1; for i:=FFirstMenuItemIndex to BaseMenu.Count-1 do if CompareStr(UpperCase(BaseMenu.Items[i].Hint),UpperCase(Filename))=0 then begin lastMove:=i; break; end; if lastMove=-1 then begin if getCount<MaxItems then begin mi:=TMenuItem.Create(FBaseMenu); mi.OnClick:=MenuItemClick; mi.HelpContext:=HelpContext; BaseMenu.add(mi); end; lastMove:=BaseMenu.Count-1; end; //finally move existing items down, deleting eventually //overwritten items or the last item (if list is full) for i:=lastMove downto FFirstMenuItemIndex+1 do begin BaseMenu.Items[i].Hint:=BaseMenu.Items[i-1].Hint; end; // now 'create' first (latest) item BaseMenu.Items[FFirstMenuItemIndex].Hint:=Filename; RebuildCaptions; end; end; procedure THistoryList.RebuildCaptions; var i, ii :integer; s :string; begin for i:=FFirstMenuItemIndex to BaseMenu.Count-1 do begin ii:=i-FFirstMenuItemIndex+1; s:=IntToStr(ii); if (ii<10) then s:='&'+s; BaseMenu.Items[i].Caption:=s+' '+BaseMenu.Items[i].Hint; end; end; procedure THistoryList.RemoveFilename(Filename:String); var i :integer; begin i:=FFirstMenuItemIndex; while (i<BaseMenu.Count) do begin if (CompareStr(UpperCase(BaseMenu.Items[i].Hint),UpperCase(Filename))=0) then begin BaseMenu.Items[i].Free; RebuildCaptions; BREAK; end; inc(i); end; end; procedure THistoryList.SetMaxItems(maxItems:Integer); begin if MaxItems<1 then begin exit; end; while getCount>maxItems do BaseMenu.Delete(BaseMenu.Count-1); FMaxItems:=MaxItems; if not FMaxItemsSet then begin FMaxItemsSet:=true; LoadFromRegistry; end; end; function THistoryList.ReadyToLoadReg:Boolean; begin result:=FMaxItemsSet; end; { TBookmarks } constructor TBookmarks.Create(AOwner:TComponent); begin inherited; FFileBookmarks:=false; FFileBookMarksSet:=false; FFirstMenuItemIndex:=2; FRegKey:=defaultBookmarksRegKey; FDelHelpContext:=0; FAddHelpContext:=0; // by default: before-last menuitem if (csDesigning in ComponentState) and (AOwner is TForm) and assigned(TForm(AOwner).Menu) then begin if assigned(TForm(AOwner).Menu.Items) and (TForm(AOwner).Menu.Items.Count>0) then begin if TForm(AOwner).Menu.Items.Count>1 then FBaseMenu:=TForm(AOwner).Menu.Items.Items[TForm(AOwner).Menu.Items.Count-2] else FBaseMenu:=TForm(AOwner).Menu.Items.Items[0]; end; end; end; // returns count of bookmarks function TBookmarks.getCount:Integer; begin if assigned(BaseMenu) and (BaseMenu.Count>3) then result:=BaseMenu.Count-3 else result:=0; end; procedure TBookmarks.SetFileBookmarks(FileBookmarks:Boolean); begin FFileBookmarksSet:=true; FFIleBookmarks:=FileBookmarks; LoadFromRegistry; end; procedure TBookmarks.SetOnGetBookmark(OnGetBookmark:TOnGetBookmark); begin FOnGetBookmark:=OnGetBookmark; if assigned(FBaseMenu) and (FBaseMenu.Count>0) then BaseMenu[0].enabled:=assigned(FOnGetBookmark); end; procedure TBookmarks.SetBaseMenu(baseMenu:TMenuItem); begin if not assigned(FBaseMenu) and assigned(baseMenu) and (not (csDesigning in Componentstate)) then begin while BaseMenu.Count>0 do BaseMenu.Delete(0); BaseMenu.add(TMenuItem.Create(FBaseMenu)); BaseMenu[0].Caption:='&Add'; BaseMenu[0].HelpContext:=FAddHelpContext; if FFileBookmarks then BaseMenu[0].Hint:='Add the current file to the bookmarks.' else BaseMenu[0].Hint:='Add the current directory to the bookmarks.'; BaseMenu[0].OnClick:=AddClick; BaseMenu[0].enabled:=assigned(FOnGetBookmark); BaseMenu.add(TMenuItem.Create(FBaseMenu)); BaseMenu[1].Caption:='-'; BaseMenu[1].visible:=false; FDeleteMenu:=TMenuItem.Create(FBaseMenu); FDeleteMenu.Caption:='&Delete'; FDeleteMenu.Hint:='Delete a bookmark'; FDeleteMenu.HelpContext:=FDelHelpContext; FDeleteMenu.visible:=false; BaseMenu.add(FDeleteMenu); end; inherited; end; procedure TBookmarks.addFilename(Filename:String); var mi:TMenuItem; i, ii:Integer; existsAlready:Boolean; name :string; begin name:=''; if (Length(FileName)>0) and (Length(Name)>0) and assigned(BaseMenu) and ((FileBookmarks and FileExists(Filename)) or (DirectoryExists(Filename))) then begin if not FileBookmarks and (Filename[length(Filename)]='\') and not ((length(Filename)>1) and (Filename[length(Filename)-1]=':')) then Filename:=copy(Filename,1,length(Filename)-1); if Count=0 then begin FDeleteMenu.visible:=true; BaseMenu[1].visible:=true; end; // if the path exists already, only the name is changed existsAlready:=false; for i:=0 to Count-1 do if CompareStr(Items[i].Hint,Filename)=0 then begin Items[i].Caption:=Name; for ii:=0 to Count-1 do if CompareStr(FDeleteMenu.Items[ii].Hint,Filename)=0 then begin FDeleteMenu.Items[ii].Caption:=Name; break; end; existsAlready:=true; break; end; if not existsAlready then begin mi:=TMenuItem.Create(FBaseMenu); mi.Caption:=Name; mi.Hint:=Filename; mi.OnClick:=MenuItemClick; mi.HelpContext:=HelpContext; BaseMenu.Insert(BaseMenu.Count-1,mi); mi:=TMenuItem.Create(FBaseMenu); mi.Caption:=Name; mi.Hint:=Filename; mi.OnClick:=DelClick; mi.HelpContext:=FDelHelpContext; FDeleteMenu.Add(mi); end; end; end; procedure TBookmarks.AddClick(Sender:TObject); var Bookmark,Name:String; begin if assigned(FOnGetBookmark) then begin Bookmark:=''; Name:=''; FOnGetBookmark(self,Bookmark,Name); addFilename(Bookmark); end; end; procedure TBookmarks.DelClick(Sender:TObject); var i:Integer; begin for i:=0 to Count-1 do if CompareStr(Items[i].Hint,TMenuItem(sender).Hint)=0 then begin BaseMenu.Remove(Items[i]); break; end; FDeleteMenu.Remove(TMenuItem(sender)); if Count=0 then begin FDeleteMenu.visible:=false; BaseMenu.Items[1].visible:=false; end; end; function TBookmarks.ReadyToLoadReg:Boolean; begin result:=FFileBookmarksSet; end; procedure TBookmarks.SetDelHelpContext(hc:THelpContext); var i:Integer; begin FDelHelpContext:=hc; if not (csDesigning in ComponentState) and assigned(FDeleteMenu) then begin FDeleteMenu.HelpContext:=hc; for i:=0 to FDeleteMenu.Count-1 do FDeleteMenu.Items[i].HelpContext:=hc; end; end; procedure TBookmarks.SetAddHelpContext(hc:THelpContext); begin FAddHelpCOntext:=hc; if not (csDesigning in ComponentState) and Assigned(BaseMenu) and (BaseMenu.Count>0) then BaseMenu.Items[0].HelpContext:=hc; end; procedure Register; begin RegisterComponents('ConTEXT Components', [THistoryList,TBookmarks]); end; end.
unit UGlobalData; interface (****** CONSTANTES PÚBLICAS ******) const // constantes de las operaciones que se pueden realizar kCodeOpTipo01 = 'T01'; kCodeOpTipo02 = 'T02'; kCodeOpTipo03 = 'T03'; kCodeOpTipo04 = 'T04'; kCodeOpTipo05 = 'T05'; kCodeOpTipo06 = 'T06'; kCodeOpTipo07 = 'T07'; kCodeOpTipo08 = 'T08'; kCodeOpTipo09 = 'T09'; kCodeOpTipo10 = 'T10'; kCodeOpTipo11 = 'T11'; kCodeOpTipo12 = 'T12'; kCodeOpTipo13 = 'T13'; kCodeOpTipo14 = 'T14'; kCodeOpTipoDev = 'DEV'; kCodeOpListado = 'LST'; kCodeOpSoporte = 'FLE'; // **** procedimientos de soporte **** procedure Inicializacion; // **** se encarga de establecer los valores iniciales de las variables gloables function getPathExe: String ; // **** encargada de devolver la ruta al ejecutable (impide que se modifique) function getPathDBFiles: String ; // **** encargada de devolver la ruta a los ficheros con los registros... function getStationID: String; // **** encargada de devolver el código de la estación de trabajo function getCanRead: string; // **** encargada de devolver la cadena con los códigos de estaciones de las cuales se pueden leer los registros function getCanDo: string; // **** encargada de devolver la cadena con los tipos de registros que se pueden generar/leer. function testStation( const aStationID: string ): boolean ; // **** encargada de comprobar si un id de estación concreto se está dentro de la lista function testDo( const aType: string ): boolean; // **** encargada de comprobar si un tipo de registro se puede manipular en esta estación function configure: boolean; // **** encargado de lanzar la configuración del sistema implementation uses SysUtils, (* funciones de gestión de directorios *) Windows, (* funciones para consultar datos del ordenador actual *) FileCtrl, (* directoryExists() *) inifiles, (* TIniFile *) Controls, (* valor mrOK *) Dialogs, (* MessageDlg() *) CCriptografiaCutre, (* theCutreCriptoEngine *) VConfigSystemForm ; (* TConfigSystemForm *) (****** CONSTANTES PRIVADAS DEL MÓDULO. ******) const kDefConfigFileName = 'config.ini' ; kExtConfigFileName = '.ini'; // constantes para la rutina de lectura del archivo de configuración kSectionINIFile = 'WORKSTATION' ; kIdentStationID = 'STATIONID' ; kIdentPathToDBFile = 'PATHTODBFILES' ; kIdentCanDo = 'CANDO' ; kIdentCanRead = 'CANREAD' ; kIdentControlCode = 'CODEB'; kRetOK = 0; kRetFileNotExists = -6; kRetWrongCodeB = -5; kRetSectionNotExists = -1; kRetIdentStationIDNotExists = -2; kRetIdentPathToDBFilesNotExists = -3; kRetIdentCanDoNotExists = -4; // mensajes de error de salida kErrMsgWrongConfigFile = 'El fichero de configuración no existe o no es correcto.'; kSubErrMsgNoSection = 'No existe la sección de configuración.'; kSubErrMsgNoDBPath = 'No se ha indicado el directorio de los datos.' ; kSubErrMsgNoIDStation = 'No se ha indicado el número de la estación de trabajo.' ; kSubErrMsgNoCanDo = 'No se ha señalado las operaciones que se pueden realizar en esta estación.' ; kSubErrMsgWrongCodeControl = 'El código de control del archivo es incorrecto o el archivo ha sido manipulado sin permiso.'; (****** VARIABLES PRIVADAS DEL MÓDULO. En este caso se trata de las variables globales del sistema ******) var // variables globales para toda la aplicación pathToExe: String ; // ubicación del ejecutable pathToConfigFile: String ; // ubicación del fichero de configuración nameOfConfigFile: String ; // nombre del fichero de configuración (incluyendo su ubicación) pathToDBFiles: String ; // ubicación de los datos (por defecto <pathExe/../dbFiles>) stationID: String; // identificador de la estación de trabajo canDo: String; // cadena separada por comas con los tipos que se pueden tratar (indicar que hay que normalizar a dos dígitos poniendo 0) canRead: String; // cadena separada por comas con los identificadores de las estaciones de trabajo que se pueden leer (y por ende modificar) fileIsInTheNet: Boolean; // cuando el archivo de configuración está en la red, hay que tenerlo en cuenta para el cálculo del Código de control // variable auxiliar para errores controlCode: string; lastReadFileErrorMsg: String; (***** PROCEDIMIENTOS AUXILIARES Y/O DE SOPORTE *****) // para el programa mostrando una ventana de error procedure ExitWithMessage( const Msg: string ); begin MessageDlg( Msg, mtError, [mbOK], 0 ); Halt; end; // -- ExitWithMessage // una función que devuelve el nombre de la máquina en la que nos encontramos function getMyComputerName: String; var computerName: String; lenName: Cardinal; begin SetLength( computerName, 255 ); lenName := 255; GetComputerName( PChar( computerName ), lenName ); SetLength( computerName, lenName ); Result := UpperCase( Trim( computerName ) ); end; // el Path del archivo de configuración se construye en el momento para comprobar los posibles caminos hacia el archivo procedure getInitConfigPath; begin // primero se comprueba la existencia del archivo en el directorio del ejecutable pathToConfigFile := ExpandFileName( pathToExe + 'CONFIG\' ); fileIsInTheNet := ( getMyComputerName() <> EmptyStr ); if fileIsInTheNet then begin nameOfConfigFile := pathToConfigFile + getMyComputerName() + kExtConfigFileName ; if fileExists( nameOfConfigFile ) then exit; end; // si no está con el nombre de la máquina, procedemos a buscar el nombre genérico nameOfConfigFile := pathToConfigFile + kDefConfigFileName ; fileIsInTheNet := false; if fileExists( nameOfConfigFile ) then exit; // en tercer lugar se procede a buscar en el disco duro local en el directorio config pathToConfigFile := 'C:\'; nameOfConfigFile := pathToConfigFile + 'OPDIVCONFIG' + kExtConfigFileName; fileIsInTheNet := false; if fileExists( nameOfConfigFile ) then exit; // si no existe en ninguno de estos sitios pues se configura los valores por defecto pathToConfigFile := ExpandFileName( pathToExe + 'CONFIG\' ); if getMyComputerName() <> EmptyStr then begin nameOfConfigFile := pathToConfigFile + getMyComputerName() + kExtConfigFileName; fileIsInTheNet := true; end else begin nameOfConfigFile := pathToConfigFile + kDefConfigFileName ; fileIsInTheNet := false; end end; // extrae el Path a partir del ejecutable y, de paso, obtiene la posición donde debería estar el archivo de configuración procedure getInitPaths; begin pathToExe := ExtractFilePath( ParamStr( 0 ) ) ; (* pathToConfigFile := ExpandFileName( pathToExe + 'CONFIG\' ); nameOfConfigFile := pathToConfigFile + kConfigFileName ; *) getInitConfigPath(); end; // -- getInitPaths; // se encarga de leer los datos desde el archivo de configuración. function readConfigFile( stopIfFileNotExist, stopIfNoAIdent, stopIfWrongCodeB: boolean ): integer; // -- stopIfFileNotExist = para el programa en caso de que el fichero no exista // -- stopIfNoAIndent = para el programa en caso de que no haya un identificador necesario // -- stopIfWrongCodeB = para el programa en caso de que el código B almacenado sea erroneo // RETORNA: // 0: si todo es correcto // -1: si no existe la sección [WORKSTATION] // -2: si no existe el identificador STATIONID // -3: si no existe el identificador PATHTODBFILES // -4: si no existe el identificador CANDO // -5: si el código B almacenado no se corresponde con el calculado // -6: el fichero no existe const klSeparador = '^CODE^'; var configFile: TIniFile; codigoA: string; codigoB: string; auxStrCode: string; // se encarga de dar el nuevo valor siempre que ya no haya un error indicado function setResultIfNoError( oldResult, newResult: integer ): integer; begin result := oldResult; if OldResult = kRetOK then result := newResult; end; // -- readCondigFile begin result := kRetOK; // se comprueba a ver si el fichero existe if not FileExists( nameOfConfigFile ) then begin lastReadFileErrorMsg := ''; if stopIfFileNotExist then ExitWithMessage( kErrMsgWrongConfigFile ) else result := kRetFileNotExists; end else begin // ---- existe el archivo de configuración y por tanto se procede a leer configFile := TIniFile.Create( nameOfConfigFile ); // se procede a realizar las comprobaciones if not configFile.SectionExists( kSectionINIFile ) then begin lastReadFileErrorMsg := kSubErrMsgNoSection ; if stopIfNoAIdent then ExitWithMessage( kErrMsgWrongConfigFile + #13 + kSubErrMsgNoSection ) else result := kRetSectionNotExists; end else begin // ---- existe la sección de configuración // -- se compruena StationID if not configFile.ValueExists( kSectionIniFile, kIdentStationID ) then begin lastReadFileErrorMsg := kSubErrMsgNoIDStation ; if stopIfNoAIdent then ExitWithMessage( kErrMsgWrongConfigFile + #13 + kSubErrMsgNoIDStation ) else result := setResultIfNoError( result, kRetIdentStationIDNotExists ); end else stationID := trim( configFile.ReadString( kSectionINIFile, kIdentStationID, '' ) ); // -- se comprueba PathToDBFiles if not configFile.ValueExists( kSectionIniFile, kIdentPathToDBFile ) then begin lastReadFileErrorMsg := kSubErrMsgNoDBPath ; if stopIfNoAIdent then ExitWithMessage( kErrMsgWrongConfigFile + #13 + kSubErrMsgNoDBPath ) else result := setResultIfNoError( result, kRetIdentPathToDBFilesNotExists ); end else pathToDBFiles := trim( configFile.ReadString( kSectionIniFile, kIdentPathToDBFile, '' ) ); // -- se comprueba CanDo if not configFile.ValueExists( kSectionIniFile, kIdentCanDo ) then begin lastReadFileErrorMsg := kSubErrMsgNoCanDo ; if stopIfNoAIdent then ExitWithMessage( kErrMsgWrongConfigFile + #13 + kSubErrMsgNoCanDo ) else result := setResultIfNoError( result, kRetIdentCanDoNotExists ); end else canDo := trim( configFile.ReadString( kSectionIniFile, kIdentCanDo, '' ) ); // -- se lee las estaciones que se pueden tratar canRead := trim( configFile.ReadString( kSectionIniFile, kIdentCanRead, '' ) ); // -- se lee el código B almacenado codigoB := trim( configFile.ReadString( kSectionIniFile, kIdentControlCode, '' ) ); controlCode := codigoB ; // -- se crea la cadena sobre la que se calcula el código de control auxStrCode := klSeparador + stationID + klSeparador + pathToDBFiles + klSeparador + canDo + klSeparador + canRead + klSeparador ; if fileIsInTheNet then auxStrCode := auxStrCode + Trim( getMyComputerName()) + klSeparador ; codigoA := theCutreCriptoEngine.getCodeA( auxStrCode ); if not theCutreCriptoEngine.isCodeBValid( codigoA, codigoB ) then begin lastReadFileErrorMsg := kSubErrMsgWrongCodeControl ; if stopIfWrongCodeB then ExitWithMessage( kErrMsgWrongConfigFile + #13 + kSubErrMsgWrongCodeControl ) else result := setResultIfNoError( result, kRetWrongCodeB ); end; end; // --- if .. SectionExistis(...) // se libera el archivo de configuración configFile.Free; end; end; // -- readConfigFile(...) // se encarga de la inicialización de las variables. Hay dos tipos de variables // las que se obtienen a partir del directorio del ejecutable y las que se deben // extraer del archivo de configuración. procedure Inicializacion; begin getInitPaths; // path del ejecutable y del directorio de configuración // en este punto se comprueba la existencia del directorio de configuración. Si no existe se crea if not DirectoryExists( pathToConfigFile ) then CreateDir( pathToConfigFile ); // en este punto se comprueba la existencia del archivo de configuración. Si no existe se llama al proceso de edición. // Hay que tener en cuenta que si el procedimiento devuelve un valor indicando que se ha cancelado la edición, el // proceso (programa) deberá ser abortado. if not FileExists( nameOfConfigFile ) then begin if not configure then ExitWithMessage( kErrMsgWrongConfigFile ); end; // en el caso de que exista hay que comprobar, además, que no ha sido manipulado. // Esto se realiza empleando el código B almacenado en el archivo conjuntamente con los datos // Si por este motivo, o porque no haya alguno de los identificadores necesarios, se procede // a configurar nuevamente el archivo. if readConfigFile( true, false, false ) <> kRetOK then begin MessageDlg( 'Se ha encontrado que el archivo de configuración es erroneo <' + lastReadFileErrorMsg + '>' + #13 + 'Se procede a reconfigurar. Si cancela el progama abortará.', mtWarning, [mbOK], 0 ); if not configure then ExitWithMessage( kErrMsgWrongConfigFile + #13 + lastReadFileErrorMsg ); end; end; // -- Inicialización (***** IMPLEMENTACIÓN DE FUNCIONES Y PROCEDIMIENTOS PÚBLICOS. *****) function getPathExe: String ; begin result := pathToExe ; end ; // -- getPathExe function getPathDBFiles: String ; begin result := pathToDBFiles ; end; // -- getPathDBFiles function getStationID: String ; begin result := stationID; end; // -- getStationID function getCanRead: string ; begin result := canRead; end; // -- getCanRead function getCanDo: string ; begin result := canDo; end; // -- getCanTypes function testStation( const aStationID: string ): boolean; begin (* result := false; *) result := (Trim(aStationID)=stationID) or (Pos('*',canRead)>0) or (Pos(aStationID,canRead)>0); (* if Pos( '*', canRead ) > 0 then result := true else if Trim( aStationID ) = stationID then result := true if Pos( aStationID, canRead ) > 0 then result := true; *) end; // -- testStation function testDo( const aType: string ): boolean; begin result := false; if Pos( '*', canDo ) > 0 then result := true else if Pos( aType, canDo ) > 0 then result := true; end; // -- testType function configure: boolean; var aConfigForm: TConfigSystemForm; configFile: TIniFile; begin aConfigForm := TConfigSystemForm.Create( nil ); // en el supuesto de que exista un archivo de configuración previo, se procede a leerlo antes de pasárselo al formulario de configuración if FileExists( nameOfConfigFile ) then begin readConfigFile( true, false, false ); aConfigForm.StationID := stationID ; aConfigForm.PathToDBFiles := pathToDBFiles ; aConfigForm.CanDo := canDo ; aConfigForm.CanRead := canRead ; aConfigForm.CodeControl := controlCode ; end; if fileIsInTheNet then aConfigForm.ComputerName := getMyComputerName(); result := ( aConfigForm.ShowModal = mrOK ); // en caso de aceptarse la configuración, hay que proceder a escribir el archivo if result then begin // se procede a crear el fichero de configuración a partir de los datos // introducidos en el diálogo configFile := TIniFile.Create( nameOfConfigFile ); configFile.WriteString( kSectionINIFile, kIdentStationID, aConfigForm.StationID ); configFile.WriteString( kSectionINIFile, kIdentPathToDBFile, aConfigForm.PathToDBFiles ); configFile.WriteString( kSectionINIFile, kIdentCanDo, aConfigForm.CanDo ); configFile.WriteString( kSectionINIFile, kIdentCanRead, aConfigForm.CanRead ); configFile.WriteString( kSectionINIFile, kIdentControlCode, aConfigForm.CodeControl ); configFile.UpdateFile; configFile.Free; // aprovechamos para actualizar los valores globales StationID := aConfigForm.StationID ; pathToDBFiles := aConfigForm.PathToDBFiles ; CanDo := aConfigForm.CanDo ; CanRead := aConfigForm.CanRead ; end; aConfigForm.Free; end; // -- configure initialization Inicializacion; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_SimpleBlockCipher; interface uses SysUtils, Classes, uTPLb_StreamCipher, uTPLb_BlockCipher; type TSimpleBlockCipherKey = class; {$IF CompilerVersion < 21} RawByteString = ansistring; {$IFEND} TSimpleBlockCipher = class( TInterfacedObject, IBlockCipher, ICryptoGraphicAlgorithm) private function DisplayName: string; function ProgId: string; function Features: TAlgorithmicFeatureSet; function DefinitionURL: string; function WikipediaReference: string; function GenerateKey( Seed: TStream): TSymetricKey; function LoadKeyFromStream( Store: TStream): TSymetricKey; function BlockSize: integer; function KeySize: integer; function SeedByteSize: integer; function MakeBlockCodec( Key: TSymetricKey): IBlockCodec; function SelfTest_Key: TBytes; function SelfTest_Plaintext: TBytes; function SelfTest_Ciphertext: TBytes; protected function Encrypt( const Buffer: TBytes; Key: TSimpleBlockCipherKey; doEncrypt: boolean): TBytes; virtual; abstract; public FProgId: string; FDisplayName: string; FFeatures: TAlgorithmicFeatureSet; FBlockSizeInBytes: integer; constructor Create( const ProgId1: string; const DisplayName1: string; Features1: TAlgorithmicFeatureSet; BlockSizeInBytes1: integer); end; TSimpleBlockCipherClass = class of TSimpleBlockCipher; TSimpleBlockCipherKey = class( TSymetricKey) public FKeyData: TBytes; procedure SaveToStream( Stream: TStream); override; procedure Burn; override; end; TSimpleBlockCipherCodec = class( TInterfacedObject, IBlockCodec) protected FKey: TSimpleBlockCipherKey; FBuffer: TBytes; FCipher: TSimpleBlockCipher; procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); procedure Reset; procedure Burn; end; implementation { TSimpleBlockCipher } function TSimpleBlockCipher.BlockSize: integer; begin result := FBlockSizeInBytes * 8 end; constructor TSimpleBlockCipher.Create( const ProgId1, DisplayName1: string; Features1: TAlgorithmicFeatureSet; BlockSizeInBytes1: integer); begin FProgId := ProgId1; FDisplayName := DisplayName1; FFeatures := Features1; FBlockSizeInBytes := BlockSizeInBytes1 end; function TSimpleBlockCipher.DefinitionURL: string; begin result := '' end; function TSimpleBlockCipher.DisplayName: string; begin result := FDisplayName end; function TSimpleBlockCipher.Features: TAlgorithmicFeatureSet; begin result := FFeatures end; function TSimpleBlockCipher.GenerateKey( Seed: TStream): TSymetricKey; var Res: TSimpleBlockCipherKey; begin Res := TSimpleBlockCipherKey.Create; SetLength( Res.FKeyData, FBlockSizeInBytes); result := Res; Seed.Read( Res.FKeyData, Length( Res.FKeyData)) end; function TSimpleBlockCipher.KeySize: integer; begin result := FBlockSizeInBytes * 8 end; function TSimpleBlockCipher.LoadKeyFromStream( Store: TStream): TSymetricKey; var Res: TSimpleBlockCipherKey; begin Res := TSimpleBlockCipherKey.Create; result := Res; Store.Read( Res.FKeyData, Length( Res.FKeyData)) end; function TSimpleBlockCipher.MakeBlockCodec( Key: TSymetricKey): IBlockCodec; var Res: TSimpleBlockCipherCodec; j: integer; begin Res := TSimpleBlockCipherCodec.Create; result := Res; Res.FKey := Key as TSimpleBlockCipherKey; SetLength( Res.FBuffer, FBlockSizeInBytes); for j := 0 to Length( Res.FBuffer) - 1 do Res.FBuffer[ j] := 0; Res.FCipher := self end; function TSimpleBlockCipher.ProgId: string; begin result := FProgId end; function TSimpleBlockCipher.SeedByteSize: integer; begin result := FBlockSizeInBytes end; function TSimpleBlockCipher.SelfTest_Ciphertext: TBytes; begin result := nil end; function TSimpleBlockCipher.SelfTest_Key: TBytes; begin result := nil end; function TSimpleBlockCipher.SelfTest_Plaintext: TBytes; begin result := nil end; function TSimpleBlockCipher.WikipediaReference: string; begin result := '' end; { TSimpleBlockCipherCodec } procedure TSimpleBlockCipherCodec.Burn; var j: integer; begin for j := 0 to Length( FBuffer) - 1 do FBuffer[ j] := 0 end; procedure TSimpleBlockCipherCodec.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream); begin Ciphertext.Position := 0; Plaintext.Position := 0; Ciphertext.Read( FBuffer, Length( FBuffer)); FBuffer := FCipher.Encrypt( FBuffer, FKey, False); Plaintext.Write( FBuffer, Length( FBuffer)) end; procedure TSimpleBlockCipherCodec.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream); begin Plaintext.Position := 0; Ciphertext.Position := 0; Plaintext.Read( FBuffer, Length( FBuffer)); FBuffer := FCipher.Encrypt( FBuffer, FKey, True); Ciphertext.Write( FBuffer, Length( FBuffer)) end; procedure TSimpleBlockCipherCodec.Reset; begin end; { TDemoSymetricKey } procedure TSimpleBlockCipherKey.Burn; var j: integer; begin for j := 1 to Length( FKeyData) do FKeyData[ j] := 0 end; procedure TSimpleBlockCipherKey.SaveToStream( Stream: TStream); begin Stream.Write( FKeyData, Length( FKeyData)) end; end.
{ ****************************************************************************** } { * ini text library,writen by QQ 600585@qq.com * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } (* update history 2017-12-6 performance optimization *) unit TextDataEngine; {$INCLUDE zDefine.inc} interface uses SysUtils, Variants, {$IFDEF FPC} FPCGenericStructlist, {$ENDIF FPC} CoreClasses, UnicodeMixedLib, PascalStrings, ListEngine, MemoryStream64; type THashTextEngine = class(TCoreClassObject) private FComment: TCoreClassStrings; FSectionList, FSectionHashVariantList, FSectionHashStringList: THashObjectList; FAutoUpdateDefaultValue: Boolean; FSectionPoolSize, FListPoolSize: Integer; function GetNames(n: SystemString): TCoreClassStrings; procedure SetNames(n: SystemString; const Value: TCoreClassStrings); function GetHitVariant(SName, VName: SystemString): Variant; procedure SetHitVariant(SName, VName: SystemString; const Value: Variant); function GetHitString(SName, VName: SystemString): SystemString; procedure SetHitString(SName, VName: SystemString; const Value: SystemString); // return override state function GetHVariantList(n: SystemString): THashVariantList; function GetHStringList(n: SystemString): THashStringList; procedure AddDataSection(aSection: SystemString; TextList: TCoreClassStrings); public constructor Create; overload; constructor Create(SectionPoolSize_: Integer); overload; constructor Create(SectionPoolSize_, ListPoolSize_: Integer); overload; destructor Destroy; override; procedure Rebuild; procedure Clear; procedure Delete(n: SystemString); function Exists(n: SystemString): Boolean; function GetDefaultValue(const SectionName, KeyName: SystemString; const DefaultValue: Variant): Variant; procedure SetDefaultValue(const SectionName, KeyName: SystemString; const Value: Variant); function GetDefaultText(const SectionName, KeyName: SystemString; const DefaultValue: SystemString): SystemString; procedure SetDefaultText(const SectionName, KeyName: SystemString; const Value: SystemString); // import section function DataImport(TextList: TCoreClassStrings): Boolean; overload; function DataImport(TextList: TListPascalString): Boolean; overload; // export section procedure DataExport(TextList: TCoreClassStrings); overload; procedure DataExport(TextList: TListPascalString); overload; procedure Merge(sour: THashTextEngine); procedure Assign(sour: THashTextEngine); function Same(sour: THashTextEngine): Boolean; procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromFile(FileName: SystemString); procedure SaveToFile(FileName: SystemString); function TotalCount: NativeInt; function MaxSectionNameLen: Integer; function MinSectionNameLen: Integer; function GetAsText: SystemString; procedure SetAsText(const Value: SystemString); property AsText: SystemString read GetAsText write SetAsText; procedure GetSectionList(dest: TCoreClassStrings); overload; procedure GetSectionList(dest: TListString); overload; procedure GetSectionList(dest: TListPascalString); overload; function GetSectionObjectName(_Obj: THashVariantList): SystemString; overload; function GetSectionObjectName(_Obj: THashStringList): SystemString; overload; property AutoUpdateDefaultValue: Boolean read FAutoUpdateDefaultValue write FAutoUpdateDefaultValue; property Comment: TCoreClassStrings read FComment write FComment; property Hit[SName, VName: SystemString]: Variant read GetHitVariant write SetHitVariant; default; property HitVariant[SName, VName: SystemString]: Variant read GetHitVariant write SetHitVariant; property HitString[SName, VName: SystemString]: SystemString read GetHitString write SetHitString; property Names[n: SystemString]: TCoreClassStrings read GetNames write SetNames; property Strings[n: SystemString]: TCoreClassStrings read GetNames write SetNames; property VariantList[n: SystemString]: THashVariantList read GetHVariantList; property HVariantList[n: SystemString]: THashVariantList read GetHVariantList; property StringList[n: SystemString]: THashStringList read GetHStringList; property HStringList[n: SystemString]: THashStringList read GetHStringList; end; TTextDataEngine = THashTextEngine; TSectionTextData = THashTextEngine; THashTextEngineList_Decl = {$IFDEF FPC}specialize {$ENDIF FPC} TGenericsList<THashTextEngine>; implementation function THashTextEngine.GetNames(n: SystemString): TCoreClassStrings; var h: THashVariantTextStream; begin if not FSectionList.Exists(n) then FSectionList[n] := TCoreClassStringList.Create; if FSectionHashVariantList.Exists(n) then begin Result := TCoreClassStringList.Create; h := THashVariantTextStream.Create(THashVariantList(FSectionHashVariantList[n])); h.DataExport(Result); DisposeObject(h); FSectionList[n] := Result; end; Result := TCoreClassStrings(FSectionList[n]); end; procedure THashTextEngine.SetNames(n: SystemString; const Value: TCoreClassStrings); var ns: TCoreClassStrings; begin ns := TCoreClassStringList.Create; ns.Assign(Value); FSectionList[n] := ns; FSectionHashVariantList.Delete(n); end; function THashTextEngine.GetHitVariant(SName, VName: SystemString): Variant; var nsl: TCoreClassStrings; vl: THashVariantList; vt: THashVariantTextStream; begin Result := Null; vl := THashVariantList(FSectionHashVariantList[SName]); if vl = nil then begin nsl := Names[SName]; if nsl = nil then Exit; if nsl.Count = 0 then Exit; vl := THashVariantList.CustomCreate(FListPoolSize); vl.AutoUpdateDefaultValue := AutoUpdateDefaultValue; vt := THashVariantTextStream.Create(vl); vt.DataImport(nsl); DisposeObject(vt); FSectionHashVariantList[SName] := vl; end; Result := vl[VName]; end; procedure THashTextEngine.SetHitVariant(SName, VName: SystemString; const Value: Variant); var nsl: TCoreClassStrings; vl: THashVariantList; vt: THashVariantTextStream; begin vl := THashVariantList(FSectionHashVariantList[SName]); if vl = nil then begin vl := THashVariantList.CustomCreate(FListPoolSize); vl.AutoUpdateDefaultValue := AutoUpdateDefaultValue; nsl := Names[SName]; if nsl <> nil then begin vt := THashVariantTextStream.Create(vl); vt.DataImport(nsl); DisposeObject(vt); end; FSectionHashVariantList[SName] := vl; end; vl[VName] := Value; end; function THashTextEngine.GetHitString(SName, VName: SystemString): SystemString; var nsl: TCoreClassStrings; sl: THashStringList; st: THashStringTextStream; begin Result := ''; sl := THashStringList(FSectionHashStringList[SName]); if sl = nil then begin nsl := Names[SName]; if nsl = nil then Exit; if nsl.Count = 0 then Exit; sl := THashStringList.CustomCreate(FListPoolSize); sl.AutoUpdateDefaultValue := AutoUpdateDefaultValue; st := THashStringTextStream.Create(sl); st.DataImport(nsl); DisposeObject(st); FSectionHashStringList[SName] := sl; end; Result := sl[VName]; end; procedure THashTextEngine.SetHitString(SName, VName: SystemString; const Value: SystemString); var nsl: TCoreClassStrings; sl: THashStringList; st: THashStringTextStream; begin sl := THashStringList(FSectionHashStringList[SName]); if sl = nil then begin sl := THashStringList.CustomCreate(FListPoolSize); sl.AutoUpdateDefaultValue := AutoUpdateDefaultValue; nsl := Names[SName]; if nsl <> nil then begin st := THashStringTextStream.Create(sl); st.DataImport(nsl); DisposeObject(st); end; FSectionHashStringList[SName] := sl; end; sl[VName] := Value; end; function THashTextEngine.GetHVariantList(n: SystemString): THashVariantList; var nsl: TCoreClassStrings; vt: THashVariantTextStream; begin Result := THashVariantList(FSectionHashVariantList[n]); if Result = nil then begin Result := THashVariantList.CustomCreate(FListPoolSize); Result.AutoUpdateDefaultValue := FAutoUpdateDefaultValue; nsl := Names[n]; if nsl <> nil then begin vt := THashVariantTextStream.Create(Result); vt.DataImport(nsl); DisposeObject(vt); end; FSectionHashVariantList[n] := Result; end; end; function THashTextEngine.GetHStringList(n: SystemString): THashStringList; var nsl: TCoreClassStrings; st: THashStringTextStream; begin Result := THashStringList(FSectionHashStringList[n]); if Result = nil then begin Result := THashStringList.CustomCreate(FListPoolSize); Result.AutoUpdateDefaultValue := FAutoUpdateDefaultValue; nsl := Names[n]; if nsl <> nil then begin st := THashStringTextStream.Create(Result); st.DataImport(nsl); DisposeObject(st); end; FSectionHashStringList[n] := Result; end; end; procedure THashTextEngine.AddDataSection(aSection: SystemString; TextList: TCoreClassStrings); begin while (TextList.Count > 0) and (TextList[0] = '') do TextList.Delete(0); while (TextList.Count > 0) and (TextList[TextList.Count - 1] = '') do TextList.Delete(TextList.Count - 1); FSectionList.Add(aSection, TextList); end; constructor THashTextEngine.Create; begin Create(10, 10); end; constructor THashTextEngine.Create(SectionPoolSize_: Integer); begin Create(SectionPoolSize_, 16); end; constructor THashTextEngine.Create(SectionPoolSize_, ListPoolSize_: Integer); begin inherited Create; FSectionPoolSize := SectionPoolSize_; FListPoolSize := ListPoolSize_; FComment := TCoreClassStringList.Create; FSectionList := THashObjectList.CustomCreate(True, FSectionPoolSize); FSectionHashVariantList := THashObjectList.CustomCreate(True, FSectionPoolSize); FSectionHashStringList := THashObjectList.CustomCreate(True, FSectionPoolSize); FAutoUpdateDefaultValue := False; end; destructor THashTextEngine.Destroy; begin Clear; DisposeObject(FSectionList); DisposeObject(FSectionHashVariantList); DisposeObject(FSectionHashStringList); DisposeObject(FComment); inherited Destroy; end; procedure THashTextEngine.Rebuild; var i: Integer; tmpSecLst: TListPascalString; nsl: TCoreClassStrings; hv: THashVariantTextStream; hs: THashStringTextStream; begin tmpSecLst := TListPascalString.Create; if FSectionHashVariantList.Count > 0 then begin FSectionHashVariantList.GetListData(tmpSecLst); for i := 0 to tmpSecLst.Count - 1 do begin nsl := TCoreClassStringList.Create; hv := THashVariantTextStream.Create(THashVariantList(tmpSecLst.Objects[i])); hv.DataExport(nsl); DisposeObject(hv); FSectionList[tmpSecLst[i]] := nsl; end; FSectionHashVariantList.Clear; end; if FSectionHashStringList.Count > 0 then begin FSectionHashStringList.GetListData(tmpSecLst); for i := 0 to tmpSecLst.Count - 1 do begin nsl := TCoreClassStringList.Create; hs := THashStringTextStream.Create(THashStringList(tmpSecLst.Objects[i])); hs.DataExport(nsl); DisposeObject(hs); FSectionList[tmpSecLst[i]] := nsl; end; FSectionHashStringList.Clear; end; DisposeObject(tmpSecLst); end; procedure THashTextEngine.Clear; begin FSectionList.Clear; FSectionHashVariantList.Clear; FSectionHashStringList.Clear; FComment.Clear; end; procedure THashTextEngine.Delete(n: SystemString); begin FSectionList.Delete(n); FSectionHashVariantList.Delete(n); FSectionHashStringList.Delete(n); end; function THashTextEngine.Exists(n: SystemString): Boolean; begin Result := FSectionList.Exists(n) or FSectionHashVariantList.Exists(n) or FSectionHashStringList.Exists(n); end; function THashTextEngine.GetDefaultValue(const SectionName, KeyName: SystemString; const DefaultValue: Variant): Variant; begin Result := VariantList[SectionName].GetDefaultValue(KeyName, DefaultValue); end; procedure THashTextEngine.SetDefaultValue(const SectionName, KeyName: SystemString; const Value: Variant); begin Hit[SectionName, KeyName] := Value; end; function THashTextEngine.GetDefaultText(const SectionName, KeyName: SystemString; const DefaultValue: SystemString): SystemString; begin Result := HStringList[SectionName].GetDefaultValue(KeyName, DefaultValue); end; procedure THashTextEngine.SetDefaultText(const SectionName, KeyName: SystemString; const Value: SystemString); begin HitString[SectionName, KeyName] := Value; end; function THashTextEngine.DataImport(TextList: TCoreClassStrings): Boolean; var i: Integer; ln: U_String; nsect: SystemString; ntLst: TCoreClassStrings; begin // merge section Rebuild; // import new section ntLst := nil; nsect := ''; Result := False; if Assigned(TextList) then begin if TextList.Count > 0 then begin i := 0; while i < TextList.Count do begin ln := umlTrimChar(TextList[i], ' '); if (ln.Len > 0) and (ln.First = '[') and (ln.Last = ']') then begin if Result then AddDataSection(nsect, ntLst); ntLst := TCoreClassStringList.Create; nsect := umlGetFirstStr(ln, '[]').Text; Result := True; end else if Result then begin ntLst.Append(ln); end else begin if (ln.Len > 0) and (not CharIn(ln.First, [';'])) then FComment.Append(ln); end; inc(i); end; if Result then AddDataSection(nsect, ntLst); end; while (FComment.Count > 0) and (FComment[0] = '') do FComment.Delete(0); while (FComment.Count > 0) and (FComment[FComment.Count - 1] = '') do FComment.Delete(FComment.Count - 1); end; end; function THashTextEngine.DataImport(TextList: TListPascalString): Boolean; var i: Integer; ln: U_String; nsect: SystemString; ntLst: TCoreClassStrings; begin // merge section Rebuild; // import new section ntLst := nil; nsect := ''; Result := False; if Assigned(TextList) then begin if TextList.Count > 0 then begin i := 0; while i < TextList.Count do begin ln := TextList[i].TrimChar(' '); if (ln.Len > 0) and (ln.First = '[') and (ln.Last = ']') then begin if Result then AddDataSection(nsect, ntLst); ntLst := TCoreClassStringList.Create; nsect := umlGetFirstStr(ln, '[]').Text; Result := True; end else if Result then begin ntLst.Append(ln); end else begin if (ln.Len > 0) and (not CharIn(ln.First, [';'])) then FComment.Append(ln); end; inc(i); end; if Result then AddDataSection(nsect, ntLst); end; while (FComment.Count > 0) and (FComment[0] = '') do FComment.Delete(0); while (FComment.Count > 0) and (FComment[FComment.Count - 1] = '') do FComment.Delete(FComment.Count - 1); end; end; procedure THashTextEngine.DataExport(TextList: TCoreClassStrings); var i: Integer; tmpSecLst: TListPascalString; nsl: TCoreClassStrings; begin Rebuild; TextList.AddStrings(FComment); if FComment.Count > 0 then TextList.Append(''); tmpSecLst := TListPascalString.Create; FSectionList.GetListData(tmpSecLst); if tmpSecLst.Count > 0 then for i := 0 to tmpSecLst.Count - 1 do if (tmpSecLst.Objects[i] is TCoreClassStrings) then begin nsl := TCoreClassStrings(tmpSecLst.Objects[i]); if nsl <> nil then begin TextList.Append('[' + tmpSecLst[i] + ']'); TextList.AddStrings(nsl); TextList.Append(''); end; end; DisposeObject(tmpSecLst); end; procedure THashTextEngine.DataExport(TextList: TListPascalString); var i: Integer; tmpSecLst: TListPascalString; nsl: TCoreClassStrings; begin Rebuild; TextList.AddStrings(FComment); if FComment.Count > 0 then TextList.Append(''); tmpSecLst := TListPascalString.Create; FSectionList.GetListData(tmpSecLst); if tmpSecLst.Count > 0 then for i := 0 to tmpSecLst.Count - 1 do if (tmpSecLst.Objects[i] is TCoreClassStrings) then begin nsl := TCoreClassStrings(tmpSecLst.Objects[i]); if nsl <> nil then begin TextList.Append('[' + tmpSecLst[i].Text + ']'); TextList.AddStrings(nsl); TextList.Append(''); end; end; DisposeObject(tmpSecLst); end; procedure THashTextEngine.Merge(sour: THashTextEngine); var ns: TCoreClassStringList; begin try Rebuild; ns := TCoreClassStringList.Create; sour.Rebuild; sour.DataExport(ns); DataImport(ns); DisposeObject(ns); Rebuild; except end; end; procedure THashTextEngine.Assign(sour: THashTextEngine); var ns: TCoreClassStringList; begin try ns := TCoreClassStringList.Create; sour.Rebuild; sour.DataExport(ns); Clear; DataImport(ns); DisposeObject(ns); except end; end; function THashTextEngine.Same(sour: THashTextEngine): Boolean; var i: Integer; ns: TCoreClassStringList; n: SystemString; begin Result := False; Rebuild; sour.Rebuild; // if Comment.Text <> sour.Comment.Text then // Exit; if FSectionList.Count <> sour.FSectionList.Count then Exit; ns := TCoreClassStringList.Create; for i := 0 to ns.Count - 1 do begin n := ns[i]; if not sour.Exists(n) then begin DisposeObject(ns); Exit; end; end; for i := 0 to ns.Count - 1 do begin n := ns[i]; if not SameText(Strings[n].Text, sour.Strings[n].Text) then begin DisposeObject(ns); Exit; end; end; DisposeObject(ns); Result := True; end; procedure THashTextEngine.LoadFromStream(stream: TCoreClassStream); var n: TListPascalString; begin Clear; n := TListPascalString.Create; n.LoadFromStream(stream); DataImport(n); DisposeObject(n); end; procedure THashTextEngine.SaveToStream(stream: TCoreClassStream); var n: TListPascalString; begin n := TListPascalString.Create; DataExport(n); n.SaveToStream(stream); DisposeObject(n); end; procedure THashTextEngine.LoadFromFile(FileName: SystemString); var m64: TMemoryStream64; begin m64 := TMemoryStream64.Create; try m64.LoadFromFile(FileName); except DisposeObject(m64); Exit; end; try LoadFromStream(m64); finally DisposeObject(m64); end; end; procedure THashTextEngine.SaveToFile(FileName: SystemString); var m64: TMemoryStream64; begin m64 := TMemoryStream64.Create; try SaveToStream(m64); m64.SaveToFile(FileName); finally DisposeObject(m64); end; end; function THashTextEngine.TotalCount: NativeInt; var i: Integer; tmpSecLst: TListPascalString; begin Result := 0; tmpSecLst := TListPascalString.Create; FSectionList.GetListData(tmpSecLst); if tmpSecLst.Count > 0 then for i := 0 to tmpSecLst.Count - 1 do if (not FSectionHashVariantList.Exists(tmpSecLst[i])) and (not FSectionHashStringList.Exists(tmpSecLst[i])) then inc(Result, TCoreClassStrings(tmpSecLst.Objects[i]).Count); FSectionHashVariantList.GetListData(tmpSecLst); if tmpSecLst.Count > 0 then for i := 0 to tmpSecLst.Count - 1 do inc(Result, THashVariantList(tmpSecLst.Objects[i]).Count); FSectionHashStringList.GetListData(tmpSecLst); if tmpSecLst.Count > 0 then for i := 0 to tmpSecLst.Count - 1 do inc(Result, THashStringList(tmpSecLst.Objects[i]).Count); DisposeObject(tmpSecLst); end; function THashTextEngine.MaxSectionNameLen: Integer; begin Result := umlMax(FSectionList.HashList.MaxNameLen, umlMax(FSectionHashVariantList.HashList.MaxNameLen, FSectionHashStringList.HashList.MaxNameLen)); end; function THashTextEngine.MinSectionNameLen: Integer; begin Result := umlMin(FSectionList.HashList.MinNameLen, umlMin(FSectionHashVariantList.HashList.MinNameLen, FSectionHashStringList.HashList.MinNameLen)); end; function THashTextEngine.GetAsText: SystemString; var ns: TPascalStringList; begin ns := TPascalStringList.Create; DataExport(ns); Result := ns.AsText; DisposeObject(ns); end; procedure THashTextEngine.SetAsText(const Value: SystemString); var ns: TListPascalString; begin Clear; ns := TListPascalString.Create; ns.AsText := Value; DataImport(ns); DisposeObject(ns); end; procedure THashTextEngine.GetSectionList(dest: TCoreClassStrings); begin Rebuild; FSectionList.GetListData(dest); end; procedure THashTextEngine.GetSectionList(dest: TListString); begin Rebuild; FSectionList.GetListData(dest); end; procedure THashTextEngine.GetSectionList(dest: TListPascalString); begin Rebuild; FSectionList.GetListData(dest); end; function THashTextEngine.GetSectionObjectName(_Obj: THashVariantList): SystemString; begin Result := FSectionHashVariantList.GetObjAsName(_Obj); end; function THashTextEngine.GetSectionObjectName(_Obj: THashStringList): SystemString; begin Result := FSectionHashStringList.GetObjAsName(_Obj); end; end.
unit Render4; interface uses SysUtils, Types, Graphics, Style, Box, Node; type TRenderer = class private Boxes: TBoxList; Canvas: TCanvas; Pen: TPoint; //Width: Integer; protected function GetContextRect(inBox: TBox): TRect; procedure RenderBox(inBox: TBox); virtual; procedure RenderBoxes; public constructor Create(inBoxes: TBoxList; inCanvas: TCanvas; inRect: TRect); end; implementation { TRenderer } constructor TRenderer.Create(inBoxes: TBoxList; inCanvas: TCanvas; inRect: TRect); begin Boxes := inBoxes; Canvas := inCanvas; //Width := inRect.Right - inRect.Left; Pen := Point(inRect.Left, inRect.Top); RenderBoxes; end; procedure TRenderer.RenderBoxes; var i: Integer; begin for i := 0 to Boxes.Max do RenderBox(Boxes[i]); end; function TRenderer.GetContextRect(inBox: TBox): TRect; begin with inBox do Result := Rect(Left, Top, Left + Width, Top + Height); OffsetRect(Result, Pen.X, Pen.Y); end; procedure TRenderer.RenderBox(inBox: TBox); var r: TRect; begin r := GetContextRect(inBox); if (inBox.Node <> nil) then TBoxNode(inBox.Node).Render(inBox, Canvas, r); if (inBox.Boxes <> nil) and (inBox.Boxes.Count > 0) then TRenderer.Create(inBox.Boxes, Canvas, r).Free; Inc(Pen.X, inBox.Offset.X); Inc(Pen.Y, inBox.Offset.Y); end; end.
unit NewFrontiers.Commands; interface uses Classes; type /// <summary> /// Basisklasse für ein Command /// </summary> TCommand = class(TComponent) protected _id: string; _titel: string; _buttonText: string; _beschreibung: string; _icon: integer; procedure setDefaultValues; virtual; abstract; public /// <summary> /// technische ID des Commands. Dieser Wert darf nie geändert werden, da /// über diesen die Funktion angesprochen wird. /// </summary> property Id: string read _id; /// <summary> /// Titel des Commands, der in der Auswahloberfläche angezeigt wird /// </summary> property Titel: string read _titel; /// <summary> /// Text, der auf dem Button angezeigt werden soll /// </summary> property ButtonText: string read _buttonText write _buttonText; /// <summary> /// Beschreibung für das Auswahlfenster /// </summary> property Beschreibung: string read _beschreibung; /// <summary> /// Das Icon für das Command (Index der Icon-Imagelist) /// </summary> property Icon: integer read _icon write _icon; constructor Create(aOwner: TComponent); reintroduce; /// <summary> /// Ausführen des hinterlegten Commands /// </summary> function execute: boolean; virtual; abstract; end; /// <summary> /// Referenz auf den Klassentyp eines Commands /// </summary> TCommandClass = class of TCommand; /// <summary> /// Repository, in dem sich alle zur Verfügung stehenden Commands /// registrieren müssen. Dies kann im initialization Teil der /// implementierenden Datei geschehen. Hierdurch ist es egal wie viele /// Commands vorhanden sind, oder wo diese deklariert werden. /// </summary> TCommandRepository = class protected _actions: TStringlist; constructor Create; public destructor Destroy; override; /// <summary> /// Die Liste der Commands. Abgebildet als String-List, deren /// String-Anteil die ID ist. /// </summary> property Actions: TStringlist read _actions; /// <summary> /// Registriert ein neues Command im Repo /// </summary> class procedure registerCommand(aActionClass: TCommandClass); /// <summary> /// Gibt eine neue Instanz des angefragten Commands zurück. /// </summary> class function getCommand(aId: string): TCommand; /// <summary> /// Singleton-Implementierung /// </summary> class function getInstance: TCommandRepository; end; /// <summary> /// Dieses Attribut kennzeichnet einen Eingangswert einen Commands /// </summary> CommandInput = class(TCustomAttribute); /// <summary> /// Kennzeichnet eine Ausgangsvariable in einem Command /// </summary> CommandOutput = class(TCustomAttribute); implementation var _repositoryInstance: TCommandRepository; { TCommandRepository } constructor TCommandRepository.Create; begin _actions := TStringList.Create; _actions.Sorted := True; _actions.Duplicates := dupIgnore; end; destructor TCommandRepository.Destroy; begin inherited; _actions.Free; _actions := nil; end; class function TCommandRepository.getCommand(aId: string): TCommand; var index: Integer; prototype: TCommand; commandType: TCommandClass; begin // TODO: An der Stelle gibt es ein Speicherleck. Da mit Owner nil instanziiert wird. index := TCommandRepository.getInstance.Actions.IndexOf(aId); if (index >= 0) then begin prototype := TCommand(TCommandRepository.getInstance.Actions.Objects[index]); commandType := TCommandClass(prototype.ClassType); result := commandType.Create(nil); end else result := nil; end; class function TCommandRepository.getInstance: TCommandRepository; begin if _repositoryInstance = nil then _repositoryInstance := TCommandRepository.Create; result := _repositoryInstance; end; class procedure TCommandRepository.registerCommand( aActionClass: TCommandClass); var myClass: TCommand; begin myClass := aActionClass.Create(nil); //TCommandRepository.getInstance.Actions.AddObject(myClass.Id, TObject(aActionClass)); TCommandRepository.getInstance.Actions.AddObject(myClass.Id, myClass); //myClass.Free; end; { TCommand } constructor TCommand.Create(aOwner: TComponent); begin inherited; setDefaultValues; end; end.
namespace Maps; interface uses UIKit; type FlipsideViewController = public class(UIViewController) private public method awakeFromNib; override; method viewDidLoad; override; method didReceiveMemoryWarning; override; property prefersStatusBarHidden: Boolean read true; override; method done(aSender: id); { IBAction } property &delegate: weak IFlipsideViewControllerDelegate; end; IFlipsideViewControllerDelegate = public interface method flipsideViewControllerDidFinish(controller: FlipsideViewController); end; implementation method FlipsideViewController.awakeFromNib; begin contentSizeForViewInPopover := CGSizeMake(320.0, 480.0); inherited awakeFromNib; end; method FlipsideViewController.viewDidLoad; begin inherited viewDidLoad; // Do any additional setup after loading the view. end; method FlipsideViewController.didReceiveMemoryWarning; begin inherited didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; method FlipsideViewController.done(aSender: id); begin &delegate.flipsideViewControllerDidFinish(self); // ToDo: use colon! end; end.
unit uFrmLogin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, uMainFormIntf, uDBIntf, uOtherIntf, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, uWmLabelEditBtn; type TfrmLogin = class(TForm, ILogin) btnLogin: TcxButton; btnCancel: TcxButton; edtName: TWmLabelEditBtn; edtPW: TWmLabelEditBtn; procedure btnLoginClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } function Login: Boolean; //登录窗口 procedure loading(AInfo: string); //正在加载的内容 public { Public declarations } procedure CreateLogin(out anInstance: IInterface); end; var frmLogin: TfrmLogin; implementation uses uSysSvc, uFactoryIntf, uSysFactory, uDefCom; {$R *.dfm} procedure TfrmLogin.btnLoginClick(Sender: TObject); var aIDBAccess: IDBAccess; aUserName, aUserPSW, aMsg: string; aMsgBox: IMsgBox; begin aUserName := Trim(edtName.Text); aUserPSW := Trim(edtPW.Text); aMsg := ''; aMsgBox := SysService as IMsgBox; if (Trim(aUserName) = EmptyStr) then begin aMsgBox.MsgBox('账户不能为空'); Exit; end; if (Trim(aUserPSW) = EmptyStr) then begin aMsgBox.MsgBox('密码不能为空'); Exit; end; aIDBAccess := SysService as IDBAccess; if aIDBAccess.Login(aUserName, aUserPSW, aMsg) <> 0 then begin aMsgBox.MsgBox(aMsg); exit; end; OperatorID := aUserName; ModalResult := mrOk; end; procedure TfrmLogin.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TfrmLogin.loading(AInfo: string); begin end; function CheckDateTimeFormat(): Boolean; var aBuf: pchar; i: Integer; aGPrevShortDate, aGPrevLongDate, aGPrevTimeFormat: string; begin result := false; getmem(aBuf, 100); try i := 100; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, aBuf, i); aGPrevShortDate := string(aBuf); if aGPrevShortDate <> 'yyyy-MM-dd' then begin ShowMessage('系统日期格式应该设置为"yyyy-MM-dd"'); exit; end; i := 100; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STIMEFORMAT, aBuf, i); aGPrevTimeFormat := string(aBuf); if aGPrevTimeFormat <> 'HH:mm:ss' then begin ShowMessage('系统时间格式应该设置为"HH:mm:ss"'); exit; end; result := true; finally FreeMem(aBuf); end; end; function TfrmLogin.Login: Boolean; begin result := false; if not CheckDateTimeFormat() then exit; // frmLogin := TfrmLogin.Create(nil); try Result := frmLogin.ShowModal = mrOk; finally // frmLogin.Free; end; end; procedure TfrmLogin.FormCreate(Sender: TObject); var aRegInf: IRegInf; begin aRegInf := SysService as IRegInf; aRegInf.RegObjFactory(ILogin, Self); // TIntfFactory.Create(ILogin, CreateLogin); end; procedure TfrmLogin.CreateLogin(out anInstance: IInterface); begin // anInstance := TfrmLogin.Create; end; initialization end.
unit IdResourceStringsOpenSSL; interface resourcestring {IdOpenSSL} RSOSSFailedToLoad = '%s を読み込めませんでした。'; RSOSSLModeNotSet = 'モードはまだ設定されていません。'; RSOSSLCouldNotLoadSSLLibrary = 'SSL ライブラリが読み込めませんでした。'; RSOSSLStatusString = 'SSL ステータス: "%s"'; RSOSSLConnectionDropped = 'SSL 接続が解除されました。'; RSOSSLCertificateLookup = 'SSL 証明書要求エラー。'; RSOSSLInternal = 'SSL ライブラリ内部エラー。'; //callback where strings RSOSSLAlert = '%s 警告'; RSOSSLReadAlert = '%s 読み取り警告'; RSOSSLWriteAlert = '%s 書き込み警告'; RSOSSLAcceptLoop = 'アクセプト ループ'; RSOSSLAcceptError = 'アクセプト エラー'; RSOSSLAcceptFailed = 'アクセプト失敗'; RSOSSLAcceptExit = 'アクセプト終了'; RSOSSLConnectLoop = '接続ループ'; RSOSSLConnectError = '接続エラー'; RSOSSLConnectFailed = '接続失敗'; RSOSSLConnectExit = '接続終了'; RSOSSLHandshakeStart = 'ハンドシェイク開始'; RSOSSLHandshakeDone = 'ハンドシェイク完了'; implementation end.
unit UFrmNoteEditorFind; interface uses Vcl.Forms, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, System.Classes; type TFrmNoteEditorFind = class(TForm) BtnOK: TButton; BtnCancel: TButton; Panel1: TPanel; EdFind: TEdit; CkReplaceAll: TCheckBox; Em: TRadioGroup; CkWholeWord: TCheckBox; CkSensitive: TCheckBox; CkReplace: TCheckBox; EdReplace: TEdit; LbLocalizar: TLabel; procedure CkReplaceClick(Sender: TObject); procedure EdFindChange(Sender: TObject); end; implementation {$R *.dfm} procedure TFrmNoteEditorFind.CkReplaceClick(Sender: TObject); begin EdReplace.Enabled := CkReplace.Checked; CkReplaceAll.Enabled := CkReplace.Checked; end; procedure TFrmNoteEditorFind.EdFindChange(Sender: TObject); begin BtnOK.Enabled := (EdFind.Text<>''); end; end.
(*********************************************************************** * Проект: acLib - Библиотека для Delphi * * Copyright (c) Alex & Co 2004,... * ************************************************************************ Модуль: acWorkRes.pas Описание: Доработанный модуль madRes.pas входящий в библиотеку компании Mathias Rauen. Доработка заключается в возможности работать с ресурсами Icon и Bitmap без явного задания языка ресурса и удобство использования. Автор: Сальников А.А. Версия: 1.10.14 21.07.04 - Были сделаны все изменения, которые сделал разработчик madRes в версии 1.0h. 1.10.14 21.07.04 - Добавлена функция "LoadFileResourceW" - Функция записи файла в ресурсы. - Добавлена функция "LoadFileResource" - Функция записи файла в ресурсы без задания языка. - Добавлена функция "SaveFileResourceW" - Функция извлечение файла из ресурсов. - Добавлена функция "SaveFileResource" - Функция извлечение файла из ресурсов без задания языка. - Добавлена функция "SaveFileToDiscW" - Сохранение ресурса ввиде файла на диск. - Добавлена функция "LoadFileToResourceW" - Сохранение ресурса в виде файла на диск. 1.04.07 19.07.04 - Добавлена функция "PWideToString" - Преобразование PWideChar в String. - Исправлена ошибка в функция "SaveIconToDiscW", которая возникала на некоторых системах семейства Win9x. 1.03.05 17.04.04 - Добавлена функция "StringToPWide" - Преобразование String в PWideChar. 1.02.04 16.04.04 - Исправлена ошибка в функция "GetNameIcon". - Добавлена функция "SaveIconToDiscW" - Сохранение иконки на диск. 1.01.02 11.04.04 - Добавлена функция "GetNameIcon" - Функция возвращает наз- вание иконки по ее номеру. 1.00.01 09.04.04 - Создан модуль. ************************************************************************) // *************************************************************** // madRes.pas version: 1.0h · date: 2004-04-11 // ------------------------------------------------------------- // resource functions for both NT and 9x families // ------------------------------------------------------------- // Copyright (C) 1999 - 2004 www.madshi.net, All Rights Reserved // *************************************************************** // 2004-04-11 1.0h (1) "CompareString" replaced by "madStrings.CompareStr" // (2) GetResourceW checks for "update = 0" now // 2004-03-08 1.0g (1) CompareString(LANG_ENGLISH) fixes sort order (czech OS) // (2) force file time touch, when resources are changed // 2003-11-10 1.0f (1) checksum field in the PE header is now set up correctly // (2) CodePage field in the resource headers stays 0 now // (3) ImageDebugDirectory handling improved (Microsoft linker) // 2003-06-09 1.0e (1) language was not treated correctly // (2) cleaning up the internal trees contained a little bug // 2002-11-07 1.0d (1) UpdateResource raised AV (only inside IDE) when update=0 // (2) PImageSectionHeader.PointerToLinenumbers/Relocations // is corrected now (if necessary) // 2002-10-17 1.0c (1) some debug structures were not updated correctly // (2) resources must be sorted alphabetically // 2002-10-12 1.0b CreateFileW is not supported in 9x, of course (dumb me) // 2002-10-11 1.0a (1) the resource data was not always aligned correctly // (2) the virtual size of the res section was sometimes wrong // (3) data given into UpdateResourceW is buffered now // (4) added some icon and bitmap specific functions // 2002-10-10 1.0 initial release // (2) force file time touch, when resources are changed // 2003-11-10 1.0f (1) checksum field in the PE header is now set up correctly // (2) CodePage field in the resource headers stays 0 now // (3) ImageDebugDirectory handling improved (Microsoft linker) // 2003-06-09 1.0e (1) language was not treated correctly // (2) cleaning up the internal trees contained a little bug // 2002-11-07 1.0d (1) UpdateResource raised AV (only inside IDE) when update=0 // (2) PImageSectionHeader.PointerToLinenumbers/Relocations // is corrected now (if necessary) // 2002-10-17 1.0c (1) some debug structures were not updated correctly // (2) resources must be sorted alphabetically // 2002-10-12 1.0b CreateFileW is not supported in 9x, of course (dumb me) // 2002-10-11 1.0a (1) the resource data was not always aligned correctly // (2) the virtual size of the res section was sometimes wrong // (3) data given into UpdateResourceW is buffered now // (4) added some icon and bitmap specific functions // 2002-10-10 1.0 initial release unit acWorkRes; interface {$DEFINE UNICODE} uses Windows; // *************************************************************** // first of all clone the official win32 APIs function BeginUpdateResourceW (fileName : PWideChar; delExistingRes : bool ; Write : boolean = true ) : dword; stdcall; function EndUpdateResourceW (update : dword; discard : bool ) : bool; stdcall; function UpdateResourceW (update : dword; type_ : PWideChar; name : PWideChar; language : word; data : pointer; size : dword ) : bool; stdcall; // *************************************************************** // get the raw data of the specified resource function GetResourceW (update : dword; type_ : PWideChar; name : PWideChar; language : word; var data : pointer; var size : dword ) : bool; stdcall; // *************************************************************** // icon specific types and functions type // structure of icon group resources TPIconGroup = ^TIconGroup; TIconGroup = packed record reserved : word; type_ : word; // 1 = icon itemCount : word; items : array [0..maxInt shr 4 - 1] of packed record width : byte; // in pixels height : byte; colors : byte; // 0 for 256+ colors reserved : byte; planes : word; bitCount : word; imageSize : dword; id : word; // id of linked RT_ICON resource end; end; // structure of ico file header TPIcoHeader = ^TIcoHeader; TIcoHeader = packed record reserved : word; type_ : word; // 1 = icon itemCount : word; items : array [0..maxInt shr 4 - 1] of packed record width : byte; // in pixels height : byte; colors : byte; // 0 for 256+ colors reserved : byte; planes : word; bitCount : word; imageSize : dword; offset : dword; // data offset in ico file end; end; // get the specified icon group resource header function GetIconGroupResourceW (update : dword; name : PWideChar; language : word; var iconGroup : TPIconGroup) : bool; stdcall; // save the specified icon group resource to an ico file function SaveIconGroupResourceW (update : dword; name : PWideChar; language : word; icoFile : PWideChar) : bool; stdcall; // load the specified ico file into the resources // if the icon group with the specified already exists, it gets fully replaced function LoadIconGroupResourceW (update : dword; name : PWideChar; language : word; icoFile : PWideChar) : bool; stdcall; // delete the whole icon group including all referenced icons function DeleteIconGroupResourceW (update : dword; name : PWideChar; language : word ) : bool; stdcall; // *************************************************************** // bitmap specific functions // save the specified bitmap resource to a bmp file function SaveBitmapResourceW (update : dword; name : PWideChar; language : word; bmpFile : PWideChar) : bool; stdcall; // load the specified bmp file into the resources function LoadBitmapResourceW (update : dword; name : PWideChar; language : word; bmpFile : PWideChar) : bool; stdcall; // *************************************************************** ////////////////////////////////// Alx /////////////////////////// var notLang: Boolean = False; // Отключение проверки языка в ресурсе // Целесообразно применять к иконкам и // рисункам т. к. эти типы ресурсов в // 99.99% случаев одного языка function GetImageNtHeaders(module: dword) : PImageNtHeaders; // same as SysUtils.CompareStr, but supports ['д', 'й', ...] //function CompareStr(const s1, s2: string) : integer; assembler; function SaveIconGroupResource(update: dword; name: PWideChar; icoFile: PWideChar) : bool; stdcall; function GetNameIcon(update: dword; ind: Integer) : PWideChar; stdcall; // Функция возвращает название иконки по ее номеру function SaveIconToDiscW(exeFile: PWideChar; ind: Word; icoFile: PWideChar): BOOL; stdcall; // Сохранение иконки на диск // exeFile - Путь к файлу, в котором находиться иконка // ind - Индекс иконки // icoFile - Путь к файлу для сохранения иконки function LoadFileResourceW(update: dword; type_, name: PWideChar; language: word; aFile: PWideChar) : bool; stdcall; // Функция записи файла в ресурсы function LoadFileResource (update: dword; type_, name, aFile: PWideChar) : bool; stdcall; // Функция записи файла в ресурсы без задания языка function SaveFileResourceW(update: dword; type_, name: PWideChar; language: word; aFile: PWideChar) : bool; stdcall; // Функция извлечение файла из ресурсов function SaveFileResource (update: dword; type_, name, aFile: PWideChar) : bool; stdcall; // Функция извлечение файла из ресурсов без задания языка function SaveFileToDiscW(exeFile, type_, name, aFile: PWideChar): BOOL; stdcall; // Сохранение ресурса ввиде файла на диск // exeFile - Путь к файлу, в котором находиться файл // type_ - Тип ресурса (Большими буквами) // name - Имя ресурса (Большими буквами) // aFile - Путь к файлу для сохранения ресурса // Пример использования: // SaveFileToDiscW('e:\Temp\Project1.exe', 'JPEG', 'MYJPEG', 'e:\Temp\Untitled-21.jpg') function LoadFileToResourceW(exeFile, type_, name, aFile: PWideChar): BOOL; stdcall; // Сохранение ресурса в виде файла на диск // exeFile - Путь к файлу, в ресурсы которого загружается файл файл // type_ - Тип ресурса (Большими буквами) // name - Имя ресурса (Большими буквами) // aFile - Путь к файлу, который будет грузиться в ресурс // LoadFileToResourceW('e:\Temp\Project1.exe', 'JPEG', 'MYJPEG', 'e:\Temp\Untitled-21.jpg') function StringToPWide(sStr: AnsiString): PWideChar; // Преобразование String в PWideChar function PWideToString(pw: PWideChar): string; // Преобразование PWideChar в String function CreateFileX(fileName: PWideChar; write, create: boolean) : dword; ////////////////////////////////////////////////////////////////// var DontShrinkResourceSection : boolean = false; implementation uses SysUtils; // *************************************************************** type // Windows internal types TAImageSectionHeader = array [0..maxInt shr 6 - 1] of TImageSectionHeader; TImageResourceDirectoryEntry = packed record NameOrID : dword; OffsetToData : dword; end; PImageResourceDirectoryEntry = ^TImageResourceDirectoryEntry; TImageResourceDirectory = packed record Characteristics : DWORD; timeDateStamp : DWORD; majorVersion : Word; minorVersion : Word; numberOfNamedEntries : Word; numberOfIdEntries : Word; entries : array [0..maxInt shr 4 - 1] of TImageResourceDirectoryEntry; end; PImageResourceDirectory = ^TImageResourceDirectory; TImageResourceDataEntry = packed record OffsetToData : DWORD; Size : DWORD; CodePage : DWORD; Reserved : DWORD; end; PImageResourceDataEntry = ^TImageResourceDataEntry; // madRes internal types TPPResItem = ^TPResItem; TPResItem = ^TResItem; TResItem = packed record id : Integer; name : WideString; child : TPResItem; next : TPResItem; strBuf : Pointer; // temporare memory buffer for item data < 32kb case isDir: Boolean of true : (attr : dword; time : dword; majorVer : word; minorVer : word; namedItems : dword; idItems : dword); false : (data : pointer; size : dword; fileBuf : dword; // temporare file buffer for item data >= 32kb codePage : dword; reserved : dword); end; TDAPResItem = array of TPResItem; TResourceHandle = record fh : dword; map : dword; buf : pointer; nh : PImageNtHeaders; tree : TPResItem; end; TPResourceHandle = ^TResourceHandle; // *************************************************************** // round up the value to the next align boundary function Align(value, align: dword) : dword; begin result := ((value + align - 1) div align) * align; end; // move file contents, can make smaller or bigger // if moving is necessary, the file mapping must be temporarily undone function MoveFileContents(fh, pos: dword; dif: integer; var map: dword; var buf: pointer) : boolean; var moveSize : dword; procedure CloseHandles; begin UnmapViewOfFile(buf); CloseHandle(map); end; function OpenHandles : boolean; begin map := CreateFileMapping(fh, nil, PAGE_READWRITE, 0, 0, nil); buf := MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, 0); result := buf <> nil; end; function CheckPos : boolean; begin result := true; if pos > GetFileSize(fh, nil) then begin if dif < 0 then CloseHandles; SetFilePointer(fh, pos, nil, FILE_BEGIN); SetEndOfFile(fh); if dif < 0 then result := OpenHandles; end; moveSize := GetFileSize(fh, nil) - pos; end; procedure SetSize; begin SetFilePointer(fh, integer(GetFileSize(fh, nil)) + dif, nil, FILE_BEGIN); SetEndOfFile(fh); end; procedure MoveIt; begin Move(pointer(dword(buf) + pos)^, pointer(int64(dword(buf) + pos) + dif)^, moveSize); end; begin result := false; if dif > 0 then begin CloseHandles; CheckPos; SetSize; if OpenHandles then begin MoveIt; result := true; end; end else if CheckPos then begin MoveIt; CloseHandles; SetSize; result := OpenHandles; end; end; // get a pointer tree of all available resources function GetResTree(module, resOfs, virtResOfs: NativeUInt) : TPResItem; function ParseResEntry(nameOrID, offsetToData: dword) : TPResItem; function GetResourceNameFromId(name: dword) : wideString; var wc : PWideChar; i1 : integer; begin wc := pointer(module + resOfs + name); SetLength(result, word(wc[0])); for i1 := 1 to Length(result) do result[i1] := wc[i1]; end; var irs : PImageResourceDirectory; i1 : integer; irde : PImageResourceDataEntry; ppri : ^TPResItem; begin New(result); ZeroMemory(result, sizeOf(result^)); with result^ do begin isDir := offsetToData and $80000000 <> 0; if nameOrID and $80000000 <> 0 then name := GetResourceNameFromId(nameOrID and (not $80000000)) else id := nameOrID; if isDir then begin NativeUInt(irs) := module + resOfs + offsetToData and (not $80000000); attr := irs^.Characteristics; time := irs^.timeDateStamp; majorVer := irs^.majorVersion; minorVer := irs^.minorVersion; namedItems := irs^.numberOfNamedEntries; idItems := irs^.numberOfIdEntries; ppri := @child; for i1 := 0 to irs^.numberOfNamedEntries + irs^.numberOfIdEntries - 1 do begin ppri^ := ParseResEntry(irs^.entries[i1].NameOrID, irs^.entries[i1].OffsetToData); ppri := @ppri^^.next; end; end else begin NativeUInt(irde) := module + resOfs + offsetToData; size := irde^.Size; codePage := irde^.CodePage; reserved := irde^.Reserved; data := pointer(module + irde^.OffsetToData - (virtResOfs - resOfs)); end; end; end; begin result := ParseResEntry(0, $80000000); end; // returns a unique temp file name with full path function GetTempFile(res: TPResItem) : string; var arrCh : array [0..MAX_PATH] of char; begin if GetTempPath(MAX_PATH, arrCh) > 0 then result := string(arrCh) + '\' else result := ''; result := result + '$pdb.tmp' + IntToHex(GetCurrentProcessID, 8) + IntToHex(dword(res), 8) + '$'; end; // totally free the pointer tree procedure DelResTree(var res: TPResItem); var res2 : TPResItem; begin while res <> nil do begin DelResTree(res^.child); res2 := res; res := res^.next; if (not res2^.isDir) and (res2^.fileBuf <> 0) then begin CloseHandle(res2^.fileBuf); DeleteFile(pchar(GetTempFile(res2))); end; if res2.strBuf <> nil then FreeMem(res2.strBuf); Dispose(res2); end; end; // calculate how big the resource section has to be for the current tree // returned is the value for the structure, name and data sections procedure CalcResSectionSize(res: TPResItem; var ss, ns, ds: dword); var res2 : TPResItem; begin with res^ do if isDir then begin inc(ss, 16 + (namedItems + idItems) * sizeOf(TImageResourceDirectoryEntry)); res2 := res^.child; while res2 <> nil do begin if res2^.name <> '' then inc(ns, Length(res2^.name) * 2 + 2); CalcResSectionSize(res2, ss, ns, ds); res2 := res2^.next; end; end else begin inc(ss, sizeOf(TImageResourceDataEntry)); inc(ds, Align(res^.size, 4)); end; end; // creates the whole resource section in a temporare buffer function CreateResSection(virtResOfs: dword; res: TPResItem; var buf: pointer; ss, ns, ds: dword) : boolean; var sp, np, dp : dword; fh : dword; map : dword; s1 : string; procedure Store(res: TPResItem); var c1 : dword; i1 : integer; res2 : TPResItem; wc : PWideChar; begin if res^.isDir then begin with PImageResourceDirectory(dword(buf) + sp)^ do begin inc(sp, 16 + (res^.namedItems + res.idItems) * sizeOf(TImageResourceDirectoryEntry)); Characteristics := res^.attr; timeDateStamp := res^.time; majorVersion := res^.majorVer; minorVersion := res^.minorVer; numberOfNamedEntries := res^.namedItems; numberOfIdEntries := res^.idItems; c1 := 0; res2 := res^.child; while res2 <> nil do begin if c1 < res^.namedItems then begin entries[c1].NameOrID := np or $80000000; wc := pointer(dword(buf) + np); word(wc[0]) := Length(res2^.name); for i1 := 1 to Length(res2^.name) do wc[i1] := res2^.name[i1]; inc(np, Length(res2^.name) * 2 + 2); end else entries[c1].NameOrID := res2^.id; if res2^.isDir then entries[c1].OffsetToData := sp or $80000000 else entries[c1].OffsetToData := sp; Store(res2); inc(c1); res2 := res2^.next; end; end; end else with PImageResourceDataEntry(dword(buf) + sp)^ do begin inc(sp, sizeOf(TImageResourceDataEntry)); OffsetToData := dp + virtResOfs; Size := res^.size; CodePage := res^.codePage; Reserved := res^.reserved; if res^.data <> nil then Move(res^.data^, pointer(dword(buf) + dp)^, Size) else if res^.strBuf <> nil then Move(res^.strBuf^, pointer(dword(buf) + dp)^, Size) else if res^.fileBuf <> 0 then begin SetFilePointer(res^.fileBuf, 0, nil, FILE_BEGIN); ReadFile(res^.fileBuf, pointer(dword(buf) + dp)^, Size, c1, nil); end; inc(dp, Align(Size, 4)); end; end; begin result := false; sp := 0; np := ss; dp := Align(ss + ns, 4); if ss + ns + ds > 0 then begin s1 := GetTempFile(res); fh := CreateFile(pchar(s1), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0); if fh <> INVALID_HANDLE_VALUE then begin SetFilePointer(fh, Align(ss + ns, 4) + ds, nil, FILE_BEGIN); SetEndOfFile(fh); map := CreateFileMapping(fh, nil, PAGE_READWRITE, 0, 0, nil); if map <> 0 then begin buf := MapViewOfFile(map, FILE_MAP_ALL_ACCESS, 0, 0, 0); if buf <> nil then begin ZeroMemory(buf, Align(ss + ns, 4) + ds); Store(res); end; CloseHandle(map); end; CloseHandle(fh); end; DeleteFile(pchar(s1)); end; end; // returns a specific child folder, if it can be found function FindDir(tree: TPResItem; name: PWideChar) : TPPResItem; var ws : wideString; begin result := @tree^.child; if dword(name) and $FFFF0000 <> 0 then begin ws := name; while (result^ <> nil) and ((not result^^.isDir) or (result^^.name <> ws) ) do result := @result^^.next; end else while (result^ <> nil) and ((not result^^.isDir) or (result^^.name <> '') or (result^^.id <> integer(name))) do result := @result^^.next; end; // returns a specific child data item, if it can be found function FindItem(tree: TPResItem; language: word) : TPPResItem; begin result := @tree^.child; if not notLang then while (result^ <> nil) and (result^^.isDir or (result^^.id <> language)) do result := @result^^.next else while (result^ <> nil) and (result^^.isDir ) do result := @result^^.next; end; // *************************************************************** function CreateFileX(fileName: PWideChar; write, create: boolean) : dword; var c1, c2, c3 : dword; begin if write then begin c1 := GENERIC_READ or GENERIC_WRITE; c2 := 0; end else begin c1 := GENERIC_READ; c2 := FILE_SHARE_READ or FILE_SHARE_WRITE; end; if create then c3 := CREATE_ALWAYS else c3 := OPEN_EXISTING; if GetVersion and $80000000 = 0 then result := CreateFileW(fileName, c1, c2, nil, c3, 0, 0) else result := CreateFileA(pansichar(ansistring(wideString(fileName))), c1, c2, nil, c3, 0, 0); end; function BeginUpdateResourceW(fileName: PWideChar; delExistingRes: bool; Write : boolean = true) : dword; stdcall; var rh : TPResourceHandle; ash : ^TAImageSectionHeader; c1 : dword; i1 : integer; FileMappingAccess : Cardinal; FileMapAccess : Cardinal; begin result := 0; New(rh); ZeroMemory(rh, sizeOf(rh^)); if Write then FileMappingAccess:=PAGE_READWRITE else FileMappingAccess:=PAGE_READONLY; if Write then FileMapAccess:=FILE_MAP_ALL_ACCESS else FileMapAccess:=FILE_MAP_READ; with rh^ do begin fh := CreateFileX(fileName, Write, false); if fh <> dword(-1) then begin map := CreateFileMapping(fh, nil, FileMappingAccess, 0, 0, nil); if map <> 0 then begin buf := MapViewOfFile(map, FileMapAccess, 0, 0, 0); if buf <> nil then begin nh := GetImageNtHeaders(dword(buf)); if nh <> nil then begin SetLastError(ERROR_FILE_NOT_FOUND); NativeUInt(ash) := NativeUInt(nh) + sizeOf(nh^); for i1 := 0 to nh^.FileHeader.NumberOfSections - 1 do if ash[i1].VirtualAddress = nh^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress then begin if delExistingRes then begin New(tree); ZeroMemory(tree, sizeOf(tree^)); tree^.isDir := true; end else tree := GetResTree(dword(buf), ash[i1].PointerToRawData, ash[i1].VirtualAddress); result := dword(rh); break; end; end; end; end; end; if result = 0 then begin c1 := GetLastError; EndUpdateResourceW(dword(rh), true); SetLastError(c1); end; end; end; procedure CalcCheckSum(baseAddress: pointer; size: dword); var nh : PImageNtHeaders; i1 : dword; c1 : dword; begin nh := GetImageNtHeaders(dword(baseAddress)); nh^.OptionalHeader.CheckSum := 0; c1 := 0; for i1 := 0 to (size - 1) div 2 do begin c1 := c1 + word(baseAddress^); if c1 and $ffff0000 <> 0 then c1 := c1 and $ffff + c1 shr 16; inc(NativeUInt(baseAddress), 2); end; c1 := word(c1 and $ffff + c1 shr 16); nh^.OptionalHeader.CheckSum := c1 + size; end; {$OVERFLOWCHECKS OFF} function EndUpdateResourceW(update: dword; discard: bool) : bool; stdcall; var rh : TPResourceHandle absolute update; ash : ^TAImageSectionHeader; ss, ns, ds : dword; storeBuf : pointer; i1, i2, i3, i4 : integer; pidb : PImageDebugDirectory; begin result := true; if update <> 0 then try with rh^ do begin if not discard then begin result := false; NativeUInt(ash) := NativeUInt(nh) + sizeOf(nh^); for i1 := 0 to nh^.FileHeader.NumberOfSections - 1 do if ash[i1].VirtualAddress = nh^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress then begin ss := 0; ns := 0; ds := 0; CalcResSectionSize(tree, ss, ns, ds); CreateResSection(nh^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress, tree, storeBuf, ss, ns, ds); i2 := int64(Align(Align(ss + ns, 4) + ds, nh^.OptionalHeader.FileAlignment)) - int64(ash[i1].SizeOfRawData); if (i2 < 0) and DontShrinkResourceSection then i2 := 0; if (i2 <> 0) and (not MoveFileContents(fh, ash[i1].PointerToRawData + ash[i1].SizeOfRawData, i2, map, buf)) then break; nh := GetImageNtHeaders(dword(buf)); NativeUInt(ash) := NativeUInt(nh) + sizeOf(nh^); with nh^.OptionalHeader, DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE] do begin inc(nh^.OptionalHeader.SizeOfInitializedData, i2); i3 := int64(Align(Align(ss + ns, 4) + ds, SectionAlignment)) - Align(Size, SectionAlignment); ash[i1].SizeOfRawData := Align(Align(ss + ns, 4) + ds, FileAlignment); ash[i1].Misc.VirtualSize := Align(ss + ns, 4) + ds; Size := Align(ss + ns, 4) + ds; inc(SizeOfImage, i3); for i4 := 0 to nh^.FileHeader.NumberOfSections - 1 do if ash[i4].VirtualAddress > VirtualAddress then begin inc(ash[i4].VirtualAddress, i3); inc(ash[i4].PointerToRawData, i2); if ash[i4].PointerToLinenumbers > ash[i1].PointerToRawData then inc(ash[i4].PointerToLinenumbers, i2); if ash[i4].PointerToRelocations > ash[i1].PointerToRawData then inc(ash[i4].PointerToRelocations, i2); end; for i4 := low(DataDirectory) to high(DataDirectory) do if DataDirectory[i4].VirtualAddress > VirtualAddress then inc(DataDirectory[i4].VirtualAddress, i3); pidb := nil; if DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size > 0 then for i4 := 0 to nh^.FileHeader.NumberOfSections - 1 do if (DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress >= ash[i4].VirtualAddress) and ( (i4 = nh^.FileHeader.NumberOfSections - 1) or (DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress < ash[i4 + 1].VirtualAddress) ) then begin pidb := pointer(dword(buf) + ash[i4].PointerToRawData + DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress - ash[i4].VirtualAddress); break; end; if pidb <> nil then begin i4 := DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size; if i4 mod sizeOf(TImageDebugDirectory) = 0 then i4 := i4 div sizeOf(TImageDebugDirectory); for i4 := 1 to i4 do begin if pidb^.PointerToRawData > ash[i1].PointerToRawData then begin if pidb^.PointerToRawData <> 0 then inc(pidb^.PointerToRawData, i2); if pidb^.AddressOfRawData <> 0 then inc(pidb^.AddressOfRawData, i3); end; inc(pidb); end; end; end; Move(storeBuf^, pointer(dword(buf) + ash[i1].PointerToRawData)^, Align(ss + ns, 4) + ds); UnmapViewOfFile(storeBuf); DeleteFile(pchar(GetTempFile(tree))); i2 := Align(Align(ss + ns, 4) + ds, nh^.OptionalHeader.FileAlignment) - (Align(ss + ns, 4) + ds); if i2 > 0 then ZeroMemory(pointer(dword(buf) + ash[i1].PointerToRawData + Align(ss + ns, 4) + ds), i2); result := true; break; end; CalcCheckSum(buf, GetFileSize(fh, nil)); end; DelResTree(tree); UnmapViewOfFile(buf); CloseHandle(map); if SetFilePointer(fh, 0, nil, FILE_END) <> $ffffffff then SetEndOfFile(fh); CloseHandle(fh); end; Dispose(rh); except result := false end; end; {$OVERFLOWCHECKS ON} {$R-} function UpdateResourceW(update: dword; type_, name: PWideChar; language: word; data: pointer; size: dword) : bool; stdcall; procedure SetData(item: TPResItem); //var c1 : dword; begin item^.id := language; item^.data := nil; item^.size := size; item^.codePage := 0;//language; //load all resources to memory! {if size > 32 * 1024 then begin item^.fileBuf := CreateFile(pchar(GetTempFile(item)), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0); if item^.fileBuf <> INVALID_HANDLE_VALUE then WriteFile(item^.fileBuf, data^, size, c1, nil) else item^.fileBuf := 0; end else} begin GetMem(item^.strBuf, size); CopyMemory(item^.strBuf, data, size); end; end; function AddItem(tree: TPResItem) : TPResItem; var ppr1 : TPPResItem; begin ppr1 := @tree^.child; while (ppr1^ <> nil) and (ppr1^^.id < language) do ppr1 := @ppr1^^.next; New(result); ZeroMemory(result, sizeOf(result^)); result^.next := ppr1^; ppr1^ := result; SetData(result); inc(tree^.idItems); end; function AddDir(tree: TPResItem; name: PWideChar) : TPResItem; var ppr1 : TPPResItem; s1 : string; begin New(result); ZeroMemory(result, sizeOf(result^)); result^.isDir := true; ppr1 := @tree^.child; if dword(name) and $FFFF0000 = 0 then begin while (ppr1^ <> nil) and ((ppr1^^.name <> '') or (ppr1^^.id < integer(name))) do ppr1 := @ppr1^.next; result^.id := integer(name); inc(tree^.idItems); end else begin s1 := wideString(name); while (ppr1^ <> nil) and (ppr1^^.name <> '') and (CompareStr(ppr1^^.name, s1) < 0) do ppr1 := @ppr1^.next; result^.name := name; inc(tree^.namedItems); end; result^.next := ppr1^; ppr1^ := result; end; procedure DelItem(const items: array of TPPResItem); var pr1 : TPResItem; i1 : integer; begin for i1 := 0 to Length(items) - 2 do begin if items[i1]^.name = '' then dec(items[i1 + 1]^.idItems ) else dec(items[i1 + 1]^.namedItems); pr1 := items[i1]^; items[i1]^ := items[i1]^^.next; if (not pr1^.isDir) and (pr1^.fileBuf <> 0) then begin CloseHandle(pr1^.fileBuf); DeleteFile(pchar(GetTempFile(pr1))); end; if pr1.strBuf <> nil then FreeMem(pr1.strBuf); Dispose(pr1); if items[i1 + 1]^.idItems + items[i1 + 1]^.namedItems > 0 then break; end; end; var ppr1, ppr2, ppr3 : TPPResItem; begin result := true; if update <> 0 then try with TPResourceHandle(update)^ do begin ppr1 := FindDir(tree, type_); if ppr1^ <> nil then begin ppr2 := FindDir(ppr1^, name); if ppr2^ <> nil then begin ppr3 := FindItem(ppr2^, language); if ppr3^ <> nil then begin if data <> nil then SetData(ppr3^) else DelItem([ppr3, ppr2, ppr1, @tree]); end else if data <> nil then AddItem(ppr2^) else if language = 0 then DelItem([ppr2, ppr1, @tree]); end else if data <> nil then AddItem(AddDir(ppr1^, name)) else if (language = 0) and (name = nil) then DelItem([ppr1, @tree]); end else if data <> nil then AddItem(AddDir(AddDir(tree, type_), name)); end; except result := false end; end; {$R+} // *************************************************************** function GetResourceW(update: dword; type_, name: PWideChar; language: word; var data: pointer; var size: dword) : bool; stdcall; var res1 : TPResItem; begin result := false; data := nil; size := 0; try if update <> 0 then with TPResourceHandle(update)^ do begin res1 := FindDir(tree, type_)^; if res1 <> nil then begin res1 := FindDir(res1, name)^; if res1 <> nil then begin res1 := FindItem(res1, language)^; result := res1 <> nil; if result then begin data := res1^.data; size := res1^.size; end; end; end; end; except result := false end; end; // *************************************************************** function GetIconGroupResourceW(update: dword; name: PWideChar; language: word; var iconGroup: TPIconGroup) : bool; stdcall; var c1 : dword; begin result := GetResourceW(update, PWideChar(RT_GROUP_ICON), name, language, pointer(iconGroup), c1); end; function SaveIconGroupResourceW(update: dword; name: PWideChar; language: word; icoFile: PWideChar) : bool; stdcall; var ig : TPIconGroup; fh : dword; ih : TPIcoHeader; id : pointer; i1 : integer; c1, c2 : dword; p1 : pointer; begin {$IFOPT R+} {$DEFINE CKRANGE} {$R-} {$ENDIF} result := false; if GetIconGroupResourceW(update, name, language, ig) then begin fh := CreateFileX(icoFile, true, true); if fh <> INVALID_HANDLE_VALUE then try c2 := 0; for i1 := 0 to ig^.itemCount - 1 do inc(c2, ig^.items[i1].imageSize); ih := nil; id := nil; try GetMem(ih, 6 + 16 * ig^.itemCount); GetMem(id, c2); Move(ig^, ih^, 4); ih^.itemCount := 0; c1 := dword(id); for i1 := 0 to ig^.itemCount - 1 do begin Move(ig^.items[i1], ih^.items[ih^.itemCount], 14); if GetResourceW(update, PWideChar(RT_ICON), PWideChar(ig^.items[i1].id), language, p1, c2) then begin ih^.items[ih^.itemCount].offset := c1 - dword(id); Move(p1^, pointer(c1)^, ig^.items[i1].imageSize); inc(c1, ig^.items[i1].imageSize); inc(ih^.itemCount); end; end; for i1 := 0 to ih^.itemCount - 1 do inc(ih^.items[i1].offset, 6 + 16 * ih^.itemCount); result := (ih^.itemCount > 0) and WriteFile(fh, ih^, 6 + 16 * ih^.itemCount, c2, nil) and WriteFile(fh, id^, c1 - dword(id), c2, nil); finally FreeMem(ih); FreeMem(id); end; finally CloseHandle(fh) end; end; {$IFDEF CKRANGE} {$UNDEF CKRANGE} {$R+} {$ENDIF} end; function LoadIconGroupResourceW(update: dword; name: PWideChar; language: word; icoFile: PWideChar) : bool; stdcall; function FindFreeID(var sid: integer) : integer; var pr1 : TPResItem; begin with TPResourceHandle(update)^ do begin pr1 := FindDir(tree, PWideChar(RT_ICON))^; if pr1 <> nil then begin pr1 := pr1^.child; while true do begin while (pr1 <> nil) and ((pr1^.name <> '') or (pr1^.id <> sid)) do pr1 := pr1^.next; if pr1 <> nil then inc(sid) else break; end; end; result := sid; end; end; var ico : TPIcoHeader; fh : dword; c1, c2 : dword; ig : TPIconGroup; ids : array of integer; i1 : integer; sid : integer; // smallest id begin {$IFOPT R+} {$DEFINE CKRANGE} {$R-} {$ENDIF} result := false; fh := CreateFileX(icoFile, false, false); if fh <> INVALID_HANDLE_VALUE then try c1 := GetFileSize(fh, nil); GetMem(ico, c1); try if ReadFile(fh, pointer(ico)^, c1, c2, nil) and (c1 = c2) then begin if GetIconGroupResourceW(update, name, language, ig) then begin SetLength(ids, ig^.itemCount); sid := maxInt; for i1 := 0 to high(ids) do begin ids[i1] := ig^.items[i1].id; if ids[i1] < sid then sid := ids[i1]; end; end else sid := 50; DeleteIconGroupResourceW(update, name, language); GetMem(ig, 6 + 14 * ico^.itemCount); try Move(ico^, ig^, 6); for i1 := 0 to ico^.itemCount - 1 do begin Move(ico^.items[i1], ig^.items[i1], 14); if i1 < length(ids) then ig^.items[i1].id := ids[i1] else ig^.items[i1].id := FindFreeID(sid); if not UpdateResourceW(update, PWideChar(RT_ICON), PWideChar(ig^.items[i1].id), language, pointer(dword(ico) + ico^.items[i1].offset), ico^.items[i1].imageSize) then exit; end; result := UpdateResourceW(update, PWideChar(RT_GROUP_ICON), name, language, ig, 6 + 14 * ig^.itemCount); finally FreeMem(ig) end; end; finally FreeMem(ico) end; finally CloseHandle(fh) end; {$IFDEF CKRANGE} {$UNDEF CKRANGE} {$R+} {$ENDIF} end; function DeleteIconGroupResourceW(update: dword; name: PWideChar; language: word) : bool; stdcall; var ig : TPIconGroup; i1 : integer; begin {$IFOPT R+} {$DEFINE CKRANGE} {$R-} {$ENDIF} if GetIconGroupResourceW(update, name, language, ig) then begin result := UpdateResourceW(update, PWideChar(RT_GROUP_ICON), name, language, nil, 0); if result then for i1 := 0 to ig^.itemCount - 1 do result := UpdateResourceW(update, PWideChar(RT_ICON), PWideChar(ig^.items[i1].id), language, nil, 0) and result; end else result := true; {$IFDEF CKRANGE} {$UNDEF CKRANGE} {$R+} {$ENDIF} end; // *************************************************************** function SaveBitmapResourceW(update: dword; name: PWideChar; language: word; bmpFile: PWideChar) : bool; stdcall; var bfh : TBitmapFileHeader; p1 : pointer; c1, c2 : dword; fh : dword; begin result := false; if GetResourceW(update, PWideChar(RT_BITMAP), name, language, p1, c1) then begin pansichar(@bfh.bfType)[0] := 'B'; pansichar(@bfh.bfType)[1] := 'M'; bfh.bfSize := sizeOf(bfh) + c1; bfh.bfReserved1 := 0; bfh.bfReserved2 := 0; bfh.bfOffBits := sizeOf(TBitmapFileHeader) + sizeOf(TBitmapInfoHeader); if PBitmapInfo(p1)^.bmiHeader.biBitCount <= 8 then inc(bfh.bfOffBits, 4 shl PBitmapInfo(p1)^.bmiHeader.biBitCount); fh := CreateFileX(bmpFile, true, true); if fh <> INVALID_HANDLE_VALUE then try WriteFile(fh, bfh, sizeOf(bfh), c2, nil); WriteFile(fh, p1^, c1, c2, nil); result := true; finally CloseHandle(fh) end; end; end; function LoadBitmapResourceW(update: dword; name: PWideChar; language: word; bmpFile: PWideChar) : bool; stdcall; var bmp : pointer; c1, c2 : dword; fh : dword; begin result := false; fh := CreateFileX(bmpFile, false, false); if fh <> INVALID_HANDLE_VALUE then try c1 := GetFileSize(fh, nil) - sizeOf(TBitmapFileHeader); GetMem(bmp, c1); try SetFilePointer(fh, sizeOf(TBitmapFileHeader), nil, FILE_BEGIN); result := ReadFile(fh, pointer(bmp)^, c1, c2, nil) and (c1 = c2) and UpdateResourceW(update, PWideChar(RT_BITMAP), name, language, bmp, c1); finally FreeMem(bmp) end; finally CloseHandle(fh) end; end; //////////////////////////////// Alx //////////////////////////////// function SaveIconGroupResource (update : dword; name : PWideChar; icoFile : PWideChar) : bool; stdcall; begin notLang:= True; try Result:= SaveIconGroupResourceW(update, name, LANG_NEUTRAL, icoFile); finally notLang:= False; end; end; function GetNameIcon(update: dword; ind: Integer) : PWideChar; stdcall; // Функция возвращает название иконки по ее номеру var res1 : TPResItem; res2 : TPPResItem; n: Integer; begin result:= ''; try with TPResourceHandle(update)^ do begin res1 := FindDir(tree, PWideChar(RT_GROUP_ICON))^; if res1 <> nil then begin res2:= @res1^.child; for n:= 0 to ind-1 do res2:= @res2^^.next; if res2^^.name = '' then Result:= PWideChar(res2^^.id) else Result:= PWideChar(WideString(res2^^.name)); end; end; except result:= ''; end; end; function SaveIconToDiscW(exeFile: PWideChar; ind: Word; icoFile: PWideChar): BOOL; stdcall; // Сохранение иконки на диск // exeFile - Путь к файлу, в котором находиться иконка // ind - Индекс иконки // icoFile - Путь к файлу для сохранения иконки const tmpFile = 'tmp.tmp'; var hUpdateRes: THandle; Buffer: array [0..MAX_PATH] of Char; begin Result:= False; if Windows.GetTempPath(SizeOf(Buffer), Buffer) > 0 then // Копирование делается, для того чтобы не возникала ошибка не // возможно открыть файл, когда файл загружен // alx 20.07.04 if CopyFileW(exeFile, PWideChar(WideString(Buffer + tmpFile)), False) then try if CopyFile(PChar(PWideToString(exeFile)), PWideChar(Buffer + tmpFile), False) then try exeFile:= PWideChar(WideString(Buffer + tmpFile)); hUpdateRes:= BeginUpdateResourceW(exeFile, False); if hUpdateRes <> 0 then if SaveIconGroupResource(hUpdateRes, GetNameIcon(hUpdateRes, ind), icoFile) then Result:= EndUpdateResourceW(hUpdateRes, False); finally DeleteFileW(exeFile); end; end; function LoadFileResourceW(update: dword; type_, name: PWideChar; language: word; aFile: PWideChar) : bool; stdcall; // Функция записи файла в ресурсы var f : pointer; c1, c2 : dword; fh : dword; begin Result:= False; fh:= CreateFileX(aFile, False, False); if fh <> INVALID_HANDLE_VALUE then try c1:= GetFileSize(fh, nil); GetMem(f, c1); try Result:= ReadFile(fh, pointer(f)^, c1, c2, nil) and (c1 = c2) and UpdateResourceW(update, type_, name, language, f, c1); finally FreeMem(f) end; finally CloseHandle(fh) end; end; function LoadFileResource (update: dword; type_, name, aFile: PWideChar) : bool; stdcall; // Функция записи файла в ресурсы без задания языка begin notLang:= True; try Result:= LoadFileResourceW(update, type_, name, LANG_NEUTRAL, aFile); finally notLang:= False; end; end; function SaveFileResourceW(update: dword; type_, name: PWideChar; language: word; aFile: PWideChar): bool; stdcall; // Функция извлечение файла из ресурсов var p1 : pointer; c1, c2 : dword; fh : dword; begin Result:= False; if GetResourceW(update, type_, name, language, p1, c1) then begin fh:= CreateFileX(aFile, True, True); if fh <> INVALID_HANDLE_VALUE then try WriteFile(fh, p1^, c1, c2, nil); Result:= True; finally CloseHandle(fh); end; end; end; function SaveFileResource (update: dword; type_, name, aFile: PWideChar) : bool; stdcall; // Функция извлечение файла из ресурсов без задания языка begin notLang:= True; try Result:= SaveFileResourceW(update, type_, name, LANG_NEUTRAL, aFile); finally notLang:= False; end; end; function SaveFileToDiscW(exeFile, type_, name, aFile: PWideChar): BOOL; stdcall; // Сохранение ресурса ввиде файла на диск // exeFile - Путь к файлу, в котором находиться файл // type_ - Тип ресурса (Большими буквами) // name - Имя ресурса (Большими буквами) // aFile - Путь к файлу для сохранения ресурса // SaveFileToDiscW('e:\Temp\Project1.exe', 'JPEG', 'MYJPEG', 'e:\Temp\Untitled-21.jpg') const tmpFile = 'tmp.tmp'; var hUpdateRes: THandle; Buffer: array [0..MAX_PATH] of Char; begin Result:= False; if Windows.GetTempPath(SizeOf(Buffer), Buffer) > 0 then // Копирование делается, для того чтобы не возникала ошибка не // возможно открыть файл, когда файл загружен if CopyFile(PChar(PWideToString(exeFile)), PWideChar(Buffer + tmpFile), False) then try exeFile:= PWideChar(WideString(Buffer + tmpFile)); hUpdateRes:= BeginUpdateResourceW(exeFile, False); if hUpdateRes <> 0 then if SaveFileResource(hUpdateRes, type_, name, aFile) then Result:= EndUpdateResourceW(hUpdateRes, False); finally DeleteFileW(exeFile); end; end; function LoadFileToResourceW(exeFile, type_, name, aFile: PWideChar): BOOL; stdcall; // Сохранение ресурса в виде файла на диск // exeFile - Путь к файлу, в ресурсы которого загружается файл файл // type_ - Тип ресурса (Большими буквами) // name - Имя ресурса (Большими буквами) // aFile - Путь к файлу, который будет грузиться в ресурс // LoadFileToResourceW('e:\Temp\Project1.exe', 'JPEG', 'MYJPEG', 'e:\Temp\Untitled-21.jpg') var hUpdateRes: THandle; begin Result:= False; hUpdateRes:= BeginUpdateResourceW(exeFile, False); if hUpdateRes <> 0 then if LoadFileResource(hUpdateRes, type_, name, aFile) then Result:= EndUpdateResourceW(hUpdateRes, False); end; function StringToPWide(sStr: AnsiString): PWideChar; // Преобразование String в PWideChar var pw: PWideChar; iSize: integer; iNewSize: integer; begin iSize:= Length(sStr) + 1; iNewSize:= iSize * 2; pw:= AllocMem(iNewSize); MultiByteToWideChar(CP_ACP, 0, PAnsiChar(sStr), iSize, pw, iNewSize); Result:= pw; end; function PWideToString(pw: PWideChar): string; // Преобразование PWideChar в String {$IFNDEF UNICODE} var p: PAnsiChar; iLen: Integer; {$ENDIF} begin {$IFDEF UNICODE} Result := string(pw); {$ENDIF} {$IFNDEF UNICODE} iLen:= lstrlenw(pw) + 1; GetMem(p, iLen); try WideCharToMultiByte(CP_ACP, 0, pw, iLen, p, iLen * 2, nil, nil); Result := string(p); finally FreeMem(p, iLen); end; {$ENDIF} end; ////////////////////////////// madTools ///////////////////////////// const // PE header constants CENEWHDR = $003C; // offset of new EXE header CEMAGIC = $5A4D; // old EXE magic id: 'MZ' CPEMAGIC = $4550; // NT portable executable function GetImageNtHeaders(module: dword) : PImageNtHeaders; begin result := nil; try if word(pointer(module)^) = CEMAGIC then begin result := pointer(module + dword(pointer(module + CENEWHDR)^)); if result^.signature <> CPEMAGIC then result := nil; end; except result := nil end; end; end.
unit uFunctions; interface uses Forms, IniFiles, SysUtils, Messages, Windows; procedure tbLoadFormStatus(Form: TForm; const Section: string); procedure tbSaveFormStatus(Form: TForm; const Section: string); implementation procedure tbSaveFormStatus(Form: TForm; const Section: string); var Ini: TIniFile; Maximized: boolean; begin Ini := TIniFile.Create(ChangeFileExt(ExtractFilePath(ParamStr(0)) + '\' + ExtractFileName(ParamStr(0)), '.ini')); try Maximized := Form.WindowState = wsMaximized; Ini.WriteBool(Section, 'Maximized', Maximized); if not Maximized then begin Ini.WriteInteger(Section, 'Left', Form.Left); Ini.WriteInteger(Section, 'Top', Form.Top); Ini.WriteInteger(Section, 'Width', Form.Width); Ini.WriteInteger(Section, 'Height', Form.Height); end; finally Ini.Free; end; end; procedure tbLoadFormStatus(Form: TForm; const Section: string); var Ini: TIniFile; Maximized: boolean; begin Maximized := false; { Evita msg do compilador } Ini := TIniFile.Create(ChangeFileExt(ExtractFilePath(ParamStr(0)) + '\' + ExtractFileName(ParamStr(0)), '.ini')); try Maximized := Ini.ReadBool(Section, 'Maximized', Maximized); Form.Left := Ini.ReadInteger(Section, 'Left', Form.Left); Form.Top := Ini.ReadInteger(Section, 'Top', Form.Top); Form.Width := Ini.ReadInteger(Section, 'Width', Form.Width); Form.Height := Ini.ReadInteger(Section, 'Height', Form.Height); if Maximized then Form.Perform(WM_SIZE, SIZE_MAXIMIZED, 0); { A propriedade WindowState apresenta Bug. Por isto usei a mensagem WM_SIZE } finally Ini.Free; end; end; { Em cada formulário que deseja salvar/restaurar: - Inclua na seção uses: uFormFunc - No evento OnShow digite: tbLoadFormStatus(Self, Self.Name); - No evento OnClose digite: tbSaveFormStatus(Self, Self.Name);} {Observações O arquivo INI terá o nome do executável e extensão INI e será salvo no diretório do Windows. A palavra Self indica o Form relacionado com a unit em questão. Poderia ser, por exemplo, Form1, Form2, etc. Onde aparece Self.Name poderá ser colocado um nome a sua escolha. Este nome será usado como SectionName no arquivo INI e deve ser idêntico no evento OnShow e OnClose de um mesmo Form, porém para cada Form deverá ser usado um nome diferente.} end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdHTTP, StdCtrls, IdMultipartFormData, XMLDoc, XMLIntf, IdTCPConnection, IdTCPClient, IdBaseComponent, IdComponent, IdIOHandler, IdIOHandlerSocket, IdSSLOpenSSL; const API_KEY='';//需要你申请一个apikey API_HOST='http://lab.ocrking.com/ok.html';//提交判断的主页 CONST_VALID_IMAGE='https://www.bestpay.com.cn/api/captcha/getCode?1408294248050'; //获取验证码的页面 type //图片类型 TOcrService=(osPassages,osPDF,osPhoneNumber,osPrice,osNumber,osCaptcha,osBarcode,osPDFImage); //语种 TOcrLanguage=(olEng,olSim,olTra,olJpn,olKor); //字符集 TOcrCharset=(ocEnglish,ocNumber,ocLowEnglish,ocUpEnglish,ocNumLowEng,ocNumUpEng ,ocAllEng,ocNumAllEng,ocEngChar,ocEmailWeb,ocShopPrice,ocPhoneNumber,ocFomula); TfrmMain = class(TForm) btn1: TButton; OD: TOpenDialog; cbbService: TComboBox; cbbLanguage: TComboBox; cbbCharset: TComboBox; mm: TMemo; btn2: TButton; idslhndlrsckt1: TIdSSLIOHandlerSocket; FHttp: TIdHTTP; procedure FormCreate(Sender: TObject); procedure btn1Click(Sender: TObject); procedure btn2Click(Sender: TObject); private { Private declarations } public FAppPath:String; end; function OcrLanguage2Str(const AOcrCharset:TOcrLanguage):string;//语言枚举转字符串 function OcrService2Str(const AService:TOcrService):string;//服务类型枚举转字符串 function UrlEncode(const ASrc: string): string;//Url编码 var frmMain: TfrmMain; implementation {$R *.dfm} function UrlEncode(const ASrc: string): string; const UnsafeChars = '*#%<>+ []'; //do not localize var i: Integer; begin Result := ''; //Do not Localize for i := 1 to Length(ASrc) do begin if (AnsiPos(ASrc[i], UnsafeChars) > 0) or (ASrc[i]< #32) or (ASrc[i] > #127) then begin Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); //do not localize end else begin Result := Result + ASrc[i]; end; end; end; function OcrLanguage2Str(const AOcrCharset:TOcrLanguage):string; begin case AOcrCharset of olEng:Result:='eng'; olSim:Result:='sim'; olTra:Result:='tra'; olJpn:Result:='jpn'; olKor:Result:='kor'; end; end; function OcrService2Str(const AService:TOcrService):string; begin case AService of osPassages:Result:='OcrKingForPassages'; osPDF:Result:='OcrKingForPDF'; osPhoneNumber:Result:='OcrKingForPhoneNumber'; osPrice:Result:='OcrKingForPrice'; osNumber:Result:='OcrKingForNumber'; osCaptcha:Result:='OcrKingForCaptcha'; osBarcode:Result:='BarcodeDecode'; osPDFImage:Result:='PDFToImage'; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin FAppPath:=ExtractFilePath(Application.ExeName); if FAppPath[Length(FAppPath)]<>'\' then FAppPath:=FAppPath+'\'; end; procedure TfrmMain.btn1Click(Sender: TObject); var ms:TIdMultiPartFormDataStream; sAll,sUrl,sService,sLanguage,sCharset,sApiKey,sType,sResponse:String; xmlDocument:IXmlDocument; xmlNode:IXMLNode; begin if OD.Execute then begin FHttp.Disconnect; mm.Clear; ms:=TIdMultiPartFormDataStream.Create; try sUrl:='?url=';//如果是直接验证网络图片,则填写验证码生成地址 sService:='&service='+OcrService2Str(TOcrService(cbbService.ItemIndex));//需要识别的类型 sLanguage:='&language='+OcrLanguage2Str(TOcrLanguage(cbbLanguage.ItemIndex));//语种 sCharset:='&charset='+IntToStr(cbbCharset.ItemIndex);//字符集 sApiKey:='&apiKey='+API_KEY;//你申请的apikey sType:='&type='+CONST_VALID_IMAGE;//传递验证码原始产出地址 sAll:=API_HOST+sUrl+sService+sLanguage+sCharset+sApiKey+sType; ms.AddFile('ocrfile',OD.FileName,'');//上传的文件,名称必须为ocrfile //如果你提交的参数有问题,可以尝试手动设置下面的值 //FHttp.Request.ContentType:='multipart/form-data'; //FHttp.Request.Host:='lab.ocrking.com'; //FHttp.Request.Accept:='*/*'; //FHttp.Request.ContentLength:=ms.Size; //FHttp.Request.Connection:='Keep-Alive'; sResponse:=UTF8ToAnsi(FHttp.Post(sAll,ms)); mm.Lines.Append(sResponse); xmlDocument:=LoadXMLData(sResponse); xmlNode:=xmlDocument.ChildNodes.FindNode('Results').ChildNodes.FindNode('ResultList').ChildNodes.FindNode('Item'); mm.Lines.Add('状态:'+xmlNode.ChildNodes.FindNode('Status').NodeValue); mm.Lines.Add('结果:'+xmlNode.ChildNodes.FindNode('Result').NodeValue); finally ms.Free; end; end; end; procedure TfrmMain.btn2Click(Sender: TObject); var ms:TMemoryStream; begin ms:=TMemoryStream.Create; try FHttp.Disconnect; FHttp.Get(CONST_VALID_IMAGE,ms); ms.SaveToFile(FAppPath+'yzm.png'); finally ms.Free; end; end; end.
unit BitmapEx; INTERFACE uses wintypes, winprocs,Messages, SysUtils, Classes, Graphics; type TBitmapEx=class(Tbitmap) public bitmapInfoHeader:TbitmapInfoHeader; constructor create(width0,height0:integer); procedure setLine(var tb;ligne:integer); procedure getLine(var tb;ligne:integer); procedure clear; end; implementation function WidthBytes(I: Longint): Longint; begin Result := ((I + 31) div 32) * 4; end; procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var BI: TBitmapInfoHeader; Colors: Integer); {Identique Ó la procÚdure de Borland.graphics mais biBitCount ne prend pas la valeur 24 quand elle vaut 16 ou 32 } var BM: Wintypes.TBitmap; k:integer; begin GetObject(Bitmap, SizeOf(BM), @BM); with BI do begin biSize := SizeOf(BI); biWidth := BM.bmWidth; biHeight := -BM.bmHeight; if Colors <> 0 then case Colors of 2: biBitCount := 1; 16: biBitCount := 4; 256: biBitCount := 8; end else biBitCount := BM.bmBitsPixel * BM.bmPlanes; biPlanes := 1; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; biCompression := BI_RGB; k:=biBitCount; if k in [16, 32] then k := 24; biSizeImage := -WidthBytes(biWidth * k) * biHeight; end; end; constructor TBitmapEx.create(width0,height0:integer); var tagBM:wintypes.TBitmap; dd:integer; begin inherited create; width:=width0; height:=height0; InitializeBitmapInfoHeader(handle,BitmapInfoHeader,0); end; procedure TBitmapEx.setLine(var tb;ligne:integer); var rr:integer; Focus: HWND; DC: HDC; begin if bitmapInfoHeader.biBitCount<>24 then exit; Focus := GetFocus; DC := GetDC(Focus); try rr:=SetDIBits( dc, { handle of device context } handle, { handle of bitmap } ligne, { starting scan line } 1, { number of scan lines } @tb, { array of bitmap bits } TbitmapInfo(pointer(@bitmapInfoHeader)^), { address of structure with bitmap data} DIB_RGB_COLORS { type of color indices to use} ); finally ReleaseDC(Focus, DC); end; end; procedure TBitmapEx.getLine(var tb;ligne:integer); var rr:integer; Focus: HWND; DC: HDC; begin if bitmapInfoHeader.biBitCount<>24 then exit; Focus := GetFocus; DC := GetDC(Focus); try rr:=getDIBits( dc, { handle of device context } handle, { handle of bitmap } ligne, { starting scan line } 1, { number of scan lines } @tb, { array of bitmap bits } TbitmapInfo(pointer(@bitmapInfoHeader)^), { address of structure with bitmap data} DIB_RGB_COLORS { type of color indices to use} ); finally ReleaseDC(Focus, DC); end; end; procedure TbitmapEx.clear; begin with canvas do begin pen.color:=0; brush.color:=0; rectangle(0,0,width,height); end; end; end.
unit Odontologia.Modelo.Entidades.Paciente; interface uses SimpleAttributes; type [Tabela('DPACIENTE')] TDPACIENTE = class private FPAC_COD_ESTADO : Integer; FPAC_CODIGO : Integer; FPAC_DIRECCION : String; FPAC_DOCUMENTO : String; FPAC_FOTO : String; FPAC_TELEFONO : String; FPAC_NOMBRE : String; procedure SetPAC_COD_ESTADO(const Value: Integer); procedure SetPAC_CODIGO(const Value: Integer); procedure SetPAC_DIRECCION(const Value: String); procedure SetPAC_FOTO (const Value: String); procedure SetPAC_DOCUMENTO(const Value: String); procedure SetPAC_NOMBRE(const Value: String); procedure SetPAC_TELEFONO(const Value: String); published [Campo('PAC_CODIGO'), Pk, AutoInc] property PAC_CODIGO : Integer read FPAC_CODIGO write SetPAC_CODIGO; [Campo('PAC_NOMBRE')] property PAC_NOMBRE : String read FPAC_NOMBRE write SetPAC_NOMBRE; [Campo('PAC_DOCUMENTO')] property PAC_DOCUMENTO : String read FPAC_DOCUMENTO write SetPAC_DOCUMENTO; [Campo('PAC_DIRECCION')] property PAC_DIRECCION : String read FPAC_DIRECCION write SetPAC_DIRECCION; [Campo('PAC_FOTO')] property PAC_FOTO : String read FPAC_FOTO write SetPAC_FOTO; [Campo('PAC_TELEFONO')] property PAC_TELEFONO : String read FPAC_TELEFONO write SetPAC_TELEFONO; [Campo('PAC_COD_ESTADO')] property PAC_COD_ESTADO : Integer read FPAC_COD_ESTADO write SetPAC_COD_ESTADO; end; implementation { TDPACIENTE } procedure TDPACIENTE.SetPAC_CODIGO(const Value: Integer); begin FPAC_CODIGO := Value; end; procedure TDPACIENTE.SetPAC_COD_ESTADO(const Value: Integer); begin FPAC_COD_ESTADO := Value; end; procedure TDPACIENTE.SetPAC_DIRECCION(const Value: String); begin FPAC_DIRECCION := Value; end; procedure TDPACIENTE.SetPAC_DOCUMENTO(const Value: String); begin FPAC_DOCUMENTO := Value; end; procedure TDPACIENTE.SetPAC_FOTO(const Value: String); begin FPAC_FOTO := Value; end; procedure TDPACIENTE.SetPAC_NOMBRE(const Value: String); begin FPAC_NOMBRE := Value; end; procedure TDPACIENTE.SetPAC_TELEFONO(const Value: String); begin FPAC_TELEFONO := Value; end; end.
unit TestSpamFilter; interface uses DelphiSpec.StepDefinitions; type TSpamFilterTestContext = class(TStepDefinitions) private FBlackList: string; FMailCount: Integer; end; implementation uses System.StrUtils , DelphiSpec.Core , DelphiSpec.Assert , DelphiSpec.Parser , DelphiSpec.Attributes; {$I TestSpamFilter.inc} { TSpamFilterTest } procedure TSpamFilterTest.Given_I_have_a_blacklist(const text: String); begin FBlackList := Text; end; procedure TSpamFilterTest.Given_I_have_empty_inbox; begin FMailCount := 0; end; procedure TSpamFilterTest.Then_my_inbox_is_empty; begin Assert.AreEqual(0, FMailCount, 'Inbox should be empty'); end; procedure TSpamFilterTest.When_I_receive_an_email_from_value( const value: String); begin if not ContainsStr(FBlackList, value) then Inc(FMailCount); end; initialization RegisterSpamFilterTest; end.
{ ------------------------------------ 功能说明:平台BPL插件管理 创建日期:2014/07/08 作者:mx 版权:mx ------------------------------------- } unit uSysPluginMgr; interface uses SysUtils, Classes, Windows, Contnrs, Forms, uRegPluginIntf, uPluginBase, uSysSvc, uOtherIntf, uMainFormIntf; const BPLTYPE = 1; DLLTYPE = 2; type TRegisterPlugInPro = procedure(Reg: IRegPlugin); TPluginLoader = class(TInterfacedObject, IRegPlugin) //关联每个BPL或DLL的相关信息 private FIntf: IInterface; FPackageHandle: HMODULE; FPackageFile: string; FPlugin: TPlugin; FFileType: Integer; function GetContainPlugin: Boolean; protected {IRegPlugin} procedure RegisterPluginClass(APluginClass: TPluginClass); public constructor Create(const PackageFile: string; Intf: IInterface); destructor Destroy; override; property ContainPlugin: Boolean read GetContainPlugin; property Plugin: TPlugin read FPlugin; property PackageFile: string read FPackageFile; end; TPluginMgr = class(TObject) //管理每个BPL包的数据 private procedure WriteErrFmt(const AErr: string; const AArgs: array of const); protected FPluginList: TObjectList; procedure GetPackageList(APackageList: TStrings); procedure LoadPackageFromFile(const PackageFile: string; Intf: IInterface); public constructor Create; destructor Destroy; override; procedure LoadPackage(Intf: IInterface); procedure Init; procedure final; end; var PluginMgr: TPluginMgr; implementation uses DBClient, Dialogs, uPubFun; { TPluginMgr } constructor TPluginMgr.Create; begin FPluginList := TObjectList.Create(True); end; destructor TPluginMgr.Destroy; begin FPluginList.Free; inherited; end; procedure TPluginMgr.Init; var i: Integer; PluginLoader: TPluginLoader; aLogin: ILogin; begin PluginLoader := nil; aLogin := SysService as ILogin; if Assigned(aLogin) then begin if not aLogin.Login() then begin (SysService as IMainForm).SetWindowState(wsMinimized); Application.Terminate; Exit; end; end; try for i := 0 to FpluginList.Count - 1 do begin PluginLoader := TPluginLoader(FpluginList.Items[i]); if not PluginLoader.ContainPlugin then Continue; if Assigned(aLogin) then aLogin.loading(Format('正在初始化包[%s]', [ExtractFileName(PluginLoader.PackageFile)])); // if Assigned(SplashForm) then // SplashForm.loading(Format('正在初始化包[%s]', // [ExtractFileName(PluginLoader.PackageFile)])); PluginLoader.Plugin.Init; end; except on E: Exception do begin WriteErrFmt('处理插件Init方法出错([%s]),错误:%s', [ExtractFileName(PluginLoader.PackageFile), E.Message]); raise Exception.CreateFmt('处理插件Init方法出错([%s]),请查看Log目录下的错误日志!', [ExtractFileName(PluginLoader.PackageFile)]); end; end; end; procedure TPluginMgr.LoadPackage(Intf: IInterface); var aList: TStrings; i: Integer; PackageFile: string; begin // 加载其他包 aList := TStringList.Create; try GetPackageList(aList); for i := 0 to aList.Count - 1 do begin PackageFile := aList[i]; // 加载包 if FileExists(PackageFile) then LoadPackageFromFile(PackageFile, Intf) else begin WriteErrFmt('找不到包[%s],无法加载!', [PackageFile]); raise Exception.CreateFmt('找不到包[%s],无法加载,请查看Log目录下的错误日志!', [PackageFile]); end; end; finally aList.Free; end; end; procedure TPluginMgr.final; var i: Integer; PluginLoader: TPluginLoader; begin for i := 0 to FpluginList.Count - 1 do begin PluginLoader := TPluginLoader(FpluginList.Items[i]); if PluginLoader.ContainPlugin then PluginLoader.Plugin.final; end; end; procedure TPluginMgr.GetPackageList(APackageList: TStrings); var aCdsBpl: TClientDataSet; aExePath: string; begin aExePath := ExtractFilePath(ParamStr(0)); // E:\code\delphi\wmpj\Bin\ aCdsBpl := TClientDataSet.Create(nil); try // aDBAC.QuerySQL('SELECT * FROM tbx_Base_PackageInfo where ITypeId <> ''00000'' ORDER BY RowIndex', aCdsBpl); // aCdsBpl.First; // while not aCdsBpl.Eof do // begin // APackageList.Add(aExePath + Trim(aCdsBpl.fieldByName('IFullname').AsString)); // aCdsBpl.Next; // end; APackageList.Add(aExePath + 'Other.bpl'); APackageList.Add(aExePath + 'DBAccess.bpl'); APackageList.Add(aExePath + 'BusinessIntf.bpl'); APackageList.Add(aExePath + 'BusinessLayer.bpl'); APackageList.Add(aExePath + 'BaseForm.bpl'); APackageList.Add(aExePath + 'SysConfig.bpl'); APackageList.Add(aExePath + 'BaseInfo.bpl'); APackageList.Add(aExePath + 'BillForm.bpl'); APackageList.Add(aExePath + 'Report.bpl'); APackageList.Add(aExePath + 'Testdll.dll'); APackageList.Add(aExePath + 'TestBpl.bpl'); finally aCdsBpl.Free; end; end; procedure TPluginMgr.LoadPackageFromFile(const PackageFile: string; Intf: IInterface); var aObj: TObject; begin try aObj := TPluginLoader.Create(PackageFile, Intf); if Assigned(aObj) then FPluginList.Add(aObj); except on E: Exception do begin WriteErrFmt('加载包[%s]出错,错误:%s', [ExtractFileName(PackageFile), E.Message]); raise Exception.CreateFmt('加载包[%s]出错,请查看Log目录下的错误日志!', [ExtractFileName(PackageFile)]); end; end; end; procedure TPluginMgr.WriteErrFmt(const AErr: string; const AArgs: array of const); var aLog: ILog; begin aLog := SysService as ILog; aLog.WriteLogTxt(ltErrSys, StringFormat(AErr, AArgs)); end; { TPluginLoader } constructor TPluginLoader.Create(const PackageFile: string; Intf: IInterface); var RegisterPlugIn: TRegisterPlugInPro; aExt: string; begin FPlugin := nil; FPackageHandle := 0; FIntf := Intf; FPackageFile := PackageFile; aExt := UpperCase(ExtractFileExt(PackageFile)); if aExt = '.BPL' then begin FFileType := BPLTYPE; FPackageHandle := SysUtils.LoadPackage(PackageFile) end else if aExt = '.DLL' then begin FFileType := DLLTYPE; FPackageHandle := LoadLibrary(PAnsiChar(PackageFile)); end; if FPackageHandle <> 0 then begin @RegisterPlugIn := GetProcAddress(FPackageHandle, 'RegisterPlugIn'); RegisterPlugIn(Self); end; end; destructor TPluginLoader.Destroy; begin if Assigned(FPlugin) then FPlugin.Free; case FFileType of BPLTYPE: SysUtils.UnloadPackage(FPackageHandle); DLLTYPE: FreeLibrary(FPackageHandle); else end; inherited; end; function TPluginLoader.GetContainPlugin: Boolean; begin Result := self.FPlugin <> nil; end; procedure TPluginLoader.RegisterPluginClass(APluginClass: TPluginClass); begin if APluginClass <> nil then FPlugin := APluginClass.Create(FIntf); FPlugin.Sys := SysService; end; end.
unit UnitCrypting; interface uses Windows, SysUtils, DB, Classes, JPEG, Dmitry.CRC32, Dmitry.Utils.Files, UnitDBDeclare, uCollectionEvents, uDBForm, uMemory, uDBAdapter, uStrongCrypt, GraphicCrypt, uDBContext, uDBConnection, uErrors; function EncryptImageByFileName(Context: IDBContext; Caller: TDBForm; FileName: string; ID: Integer; Password: string; Options: Integer; DoEvent: Boolean = True; Progress: TFileProgress = nil): Integer; function ResetPasswordImageByFileName(Context: IDBContext; Caller: TObject; FileName: string; ID: Integer; Password: string; Progress: TFileProgress = nil): Integer; function CryptTStrings(TS: TStrings; Pass: string): string; function DeCryptTStrings(S: string; Pass: string): TStrings; function CryptDBRecordByID(Context: IDBContext; ID: Integer; Password: string): Integer; implementation function CryptDBRecordByID(Context: IDBContext; ID: Integer; Password: string): Integer; var Query: TDataSet; JPEG: TJPEGImage; MS: TMemoryStream; DA: TImageTableAdapter; begin Result := CRYPT_RESULT_UNDEFINED; Query := Context.CreateQuery; DA := TImageTableAdapter.Create(Query); try SetSQL(Query,'Select thum from $DB$ where ID = ' + IntToStr(ID)); Query.Open; JPEG := TJPEGImage.Create; try JPEG.Assign(DA.Thumb); MS := TMemoryStream.Create; try EncryptGraphicImage(JPEG, Password, MS); SetSQL(Query, 'Update $DB$ Set thum = :thum where ID = ' + IntToStr(ID)); LoadParamFromStream(Query, 0, MS, ftBlob); finally F(MS); end; finally F(JPEG); end; ExecSQL(Query); finally F(DA); FreeDS(Query); end; Result := CRYPT_RESULT_OK; end; function ResetPasswordDBRecordByID(Context: IDBContext; ID: integer; Password: String): Integer; var Query: TDataSet; JPEG: TJPEGImage; DA: TImageTableAdapter; begin Result := CRYPT_RESULT_UNDEFINED; Query := Context.CreateQuery; DA := TImageTableAdapter.Create(Query); try SetSQL(Query, 'Select thum from $DB$ where ID = ' + IntToStr(ID)); Query.Open; JPEG := TJpegImage.Create; try if DeCryptBlobStreamJPG(DA.Thumb, Password, JPEG) then begin SetSQL(Query,'Update $DB$ Set thum = :thum where ID = ' + IntToStr(ID)); AssignParam(Query, 0, JPEG); ExecSQL(Query); end; finally F(JPEG); end; finally F(DA); FreeDS(Query); end; Result := CRYPT_RESULT_OK; end; function EncryptImageByFileName(Context: IDBContext; Caller: TDBForm; FileName: string; ID: Integer; Password: string; Options: Integer; DoEvent: Boolean = True; Progress: TFileProgress = nil): Integer; var Info: TEventValues; ErrorCode: Integer; begin Info.IsEncrypted := True; Result := CRYPT_RESULT_UNDEFINED; if ValidCryptGraphicFile(FileName) and FileExistsSafe(FileName) then begin Result := CRYPT_RESULT_ALREADY_CRYPT; Exit; end; if FileExistsSafe(FileName) then begin ErrorCode := CryptGraphicFileV3(FileName, Password, Options, Progress); if ErrorCode <> CRYPT_RESULT_OK then begin Result := ErrorCode; Exit; end; end; if ID <> 0 then if CryptDBRecordByID(Context, ID, Password) <> CRYPT_RESULT_OK then begin Result := CRYPT_RESULT_FAILED_CRYPT_DB; end; if Result = CRYPT_RESULT_UNDEFINED then Info.IsEncrypted := True else Info.IsEncrypted := False; if ID <> 0 then if DoEvent then CollectionEvents.DoIDEvent(Caller, ID, [EventID_Param_Crypt], Info) else begin Info.NewName := FileName; if DoEvent then CollectionEvents.DoIDEvent(Caller, ID, [EventID_Param_Name], Info) end; if Result = CRYPT_RESULT_UNDEFINED then Result := CRYPT_RESULT_OK; end; function ResetPasswordImageByFileName(Context: IDBContext; Caller: TObject; FileName: string; ID: Integer; Password: string; Progress: TFileProgress = nil): Integer; begin if not FileExistsSafe(FileName) then Exit(CRYPT_RESULT_ERROR_READING_FILE); if not ValidCryptGraphicFile(FileName) then begin Result := CRYPT_RESULT_ALREADY_DECRYPTED; Exit; end; Result := ResetPasswordInGraphicFile(FileName, Password, Progress); if Result <> CRYPT_RESULT_OK then Exit; if ID <> 0 then if ResetPasswordDBRecordByID(Context, ID, Password) <> CRYPT_RESULT_OK then Result := CRYPT_RESULT_FAILED_CRYPT_DB; end; function DeCryptTStrings(S: string; Pass: string): TStrings; var X: array of Byte; I, Lpass: Integer; CRC: Cardinal; TempStream, MS: TMemoryStream; GraphicHeader: TEncryptedFileHeader; GraphicHeaderV1: TGraphicCryptFileHeaderV1; begin Result := TStringList.Create; MS := TMemoryStream.Create; try MS.WriteBuffer(Pointer(S)^, Length(S)); MS.Seek(0, SoFromBeginning); MS.Read(GraphicHeader, SizeOf(TEncryptedFileHeader)); if GraphicHeader.ID <> '.PHDBCRT' then Exit; if GraphicHeader.Version = 1 then begin MS.Read(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1)); CalcStringCRC32(Pass, CRC); if GraphicHeaderV1.PassCRC <> CRC then Exit; if GraphicHeaderV1.Displacement > 0 then MS.Seek(GraphicHeaderV1.Displacement, SoCurrent); SetLength(X, GraphicHeaderV1.FileSize); MS.Read(Pointer(X)^, GraphicHeaderV1.FileSize); F(MS); Lpass := Length(Pass); for I := 0 to Length(X) - 1 do X[I] := X[I] xor (TMagicByte(GraphicHeaderV1.Magic)[I mod 4 + 1] xor Byte(Pass[I mod Lpass + 1])); TempStream := TMemoryStream.Create; try TempStream.Seek(0, SoFromBeginning); TempStream.WriteBuffer(Pointer(X)^, Length(X)); TempStream.Seek(0, SoFromBeginning); try Result.LoadFromStream(TempStream); except end; finally F(TempStream); end; end; finally F(MS); end; end; function CryptTStrings(TS: TStrings; Pass: string): string; var MS: TMemoryStream; X: array of Byte; I, LPass: Integer; GraphicHeader: TEncryptedFileHeader; GraphicHeaderV1: TGraphicCryptFileHeaderV1; begin Result := ''; MS := TMemoryStream.Create; try TS.SaveToStream(MS); SetLength(X, MS.Size); MS.Seek(0, SoFromBeginning); MS.Read(GraphicHeader, SizeOf(GraphicHeader)); if GraphicHeader.ID = '.PHDBCRT' then Exit; MS.Seek(0, SoFromBeginning); MS.Read(Pointer(X)^, MS.Size); finally F(MS); end; LPass := Length(Pass); Randomize; {$IFOPT R+} {$DEFINE CKRANGE} {$R-} {$ENDIF} GraphicHeaderV1.Magic := Random(High(Integer)); for I := 0 to Length(X) - 1 do X[I] := X[I] xor (TMagicByte(GraphicHeaderV1.Magic)[I mod 4 + 1] xor Byte(Pass[I mod Lpass + 1])); {$IFDEF CKRANGE} {$UNDEF CKRANGE} {$R+} {$ENDIF} MS := TMemoryStream.Create; try MS.Seek(0, SoFromBeginning); GraphicHeader.ID := '.PHDBCRT'; GraphicHeader.Version := 1; GraphicHeader.DBVersion := 0; MS.write(GraphicHeader, SizeOf(TEncryptedFileHeader)); GraphicHeaderV1.Version := 1; GraphicHeaderV1.FileSize := Length(X); CalcStringCRC32(Pass, GraphicHeaderV1.PassCRC); GraphicHeaderV1.CRCFileExists := False; GraphicHeaderV1.CRCFile := 0; GraphicHeaderV1.TypeExtract := 0; GraphicHeaderV1.CryptFileName := False; GraphicHeaderV1.CFileName := ''; GraphicHeaderV1.TypeFileNameExtract := 0; GraphicHeaderV1.FileNameCRC := 0; GraphicHeaderV1.Displacement := 0; MS.Write(GraphicHeaderV1, SizeOf(TGraphicCryptFileHeaderV1)); MS.Write(Pointer(X)^, Length(X)); SetLength(Result, MS.Size); MS.Seek(0, SoFromBeginning); MS.ReadBuffer(Pointer(Result)^, MS.Size); finally F(MS); end; end; end.
unit Model.TableNames; interface const { Tabela USUARIOS } USUARIO_TABLE: string = 'USUARIOS'; USUARIO_ID: string = 'IDUSUARIO'; USUARIO_CODIGO: string = 'CODIGO'; USUARIO_NOME: string = 'NOMEUSUARIO'; USUARIO_LOGIN: string = 'LOGIN'; USUARIO_SENHA: string = 'SENHA'; USUARIO_IDPERFIL: string = 'IDPERFIL'; USUARIO_DATAEXCLUSAO: string = 'DATAEXCLUSAO'; USUARIO_ATUALIZACAO: string = 'ATUALIZACAO'; { Tabela PERFIS } PERFIL_TABLE: string = 'PERFIS'; PERFIL_ID: string = 'IDPERFIL'; PERFIL_DESCRICAO: string = 'DESCRICAO'; { Tabela ROTINAS } ROTINA_TABLE: string = 'ROTINAS'; ROTINA_ID: string = 'IDROTINA'; ROTINA_CODIGO: string = 'CODIGO'; { Tabela PERFILROTINAS } PERFILROTINAS_TABLE: string = 'PERFILROTINAS'; PERFILROTINAS_IDPERFIL: string = 'IDPERFIL'; PERFILROTINAS_IDROTINA: string = 'IDROTINA'; implementation end.
unit AddDeviceRequest; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} Interface Uses IRPMonDLl, AbstractRequest, IRPMonRequest; Type TAddDeviceRequest = Class (TDriverRequest) Public Constructor Create(Var ARequest:REQUEST_ADDDEVICE); Overload; Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override; Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override; end; Implementation Constructor TAddDeviceRequest.Create(Var ARequest:REQUEST_ADDDEVICE); begin Inherited Create(ARequest.Header); end; Function TAddDeviceRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; begin Case AColumnType Of rlmctFileObject, rlmctIOSBStatusValue, rlmctIOSBStatusConstant, rlmctIOSBInformation, rlmctResultValue, rlmctResultConstant, rlmctFileName : Result := False; Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize); end; end; Function TAddDeviceRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; begin Case AColumnType Of rlmctFileObject, rlmctIOSBStatusValue, rlmctIOSBStatusConstant, rlmctIOSBInformation, rlmctResultValue, rlmctResultConstant, rlmctFileName : Result := False; Else Result := Inherited GetColumnValue(AColumnType, AResult); end; end; End.
unit OTFEBestCryptGetDriveLetter_U; // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask; type TGetDriveLetter_F = class(TForm) Label1: TLabel; cbDriveLetter: TComboBox; Label2: TLabel; lblVolFilename: TLabel; pbOK: TButton; pbCancel: TButton; cbAlwaysThisDrive: TCheckBox; cbAutomount: TCheckBox; Label3: TLabel; MaskEdit1: TMaskEdit; Label4: TLabel; procedure FormShow(Sender: TObject); procedure cbAlwaysThisDriveClick(Sender: TObject); private FFilename: string; FDefaultDrive: char; FAutoMountOptionAlwaysEnabled: boolean; FForcedDriveLetter: Ansichar; FProhibitedDriveLetters: ansistring; procedure RefreshDriveLetters(); public constructor Create(AOwner : TComponent); override; published property Filename: string read FFilename write FFilename; property DefaultDrive: char read FDefaultDrive write FDefaultDrive; property AutoMountOptionAlwaysEnabled: boolean read FAutoMountOptionAlwaysEnabled write FAutoMountOptionAlwaysEnabled; // Set ForceDriveLetter to #0 to permit user to select any unused drive // letter. Set to a drive letter to only permit that drive property ForceDriveLetter: Ansichar read FForcedDriveLetter write FForcedDriveLetter; // Set ProhibitedDriveLetters to be a string containing all drive letters // that the user may *not* mount a drive as property ProhibitedDriveLetters: ansistring read FProhibitedDriveLetters write FProhibitedDriveLetters; end; implementation {$R *.DFM} uses INIFiles, OTFEBestCryptStructures_U, SDUGeneral; constructor TGetDriveLetter_F.Create(AOwner : TComponent); begin inherited; ForceDriveLetter := #0; end; procedure TGetDriveLetter_F.FormShow(Sender: TObject); begin self.left := (screen.width-self.width) div 2; self.top := (screen.height-self.height) div 2; RefreshDriveLetters(); if DefaultDrive=#0 then begin cbDriveLetter.itemindex := 0; end else begin if cbDriveLetter.items.indexof(FDefaultDrive)=-1 then begin cbDriveLetter.itemindex := 0; end else begin cbDriveLetter.itemindex := cbDriveLetter.items.indexof(FDefaultDrive); end; end; lblVolFilename.caption := FFilename; cbAutomount.enabled := AutoMountOptionAlwaysEnabled; end; procedure TGetDriveLetter_F.RefreshDriveLetters(); var DriveNum: Integer; DriveChar: char; DriveBits: set of 0..25; begin cbDriveLetter.items.Clear; if (ForceDriveLetter<>#0) then begin cbDriveLetter.Items.Add(ForceDriveLetter+':'); SDUEnableControl(cbDriveLetter, FALSE); end else begin SDUEnableControl(cbDriveLetter, TRUE); Integer(DriveBits) := GetLogicalDrives; for DriveNum := 2 to 25 do // from C: to Z: begin if not(DriveNum in DriveBits) then begin DriveChar := Char(DriveNum + Ord('A')); if (Pos(DriveChar, FProhibitedDriveLetters)<=0) then begin cbDriveLetter.Items.Add(DriveChar+':'); end; end; end; end; end; procedure TGetDriveLetter_F.cbAlwaysThisDriveClick(Sender: TObject); begin if not(AutoMountOptionAlwaysEnabled) then begin cbAutomount.enabled := cbAlwaysThisDrive.checked; if not(cbAutomount.enabled) then begin cbAutomount.checked := FALSE; end; end; end; END.
namespace OxygeneiOSUITableViewCellDemo; interface uses UIKit; type [IBObject] RootViewController = public class(UITableViewController) private //Data for the table dataArray: array of array of String; //IUITableViewDataSource method tableView(tableView: UIKit.UITableView) cellForRowAtIndexPath(indexPath: NSIndexPath): UITableViewCell; method tableView(tableView: UIKit.UITableView) numberOfRowsInSection(section: NSInteger): NSInteger; method numberOfSectionsInTableView(tableView: UITableView): NSInteger; //IUITabkeViewDelegate method tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath); method tableView(tableView: UITableView) heightForRowAtIndexPath(indexPath: NSIndexPath): CGFloat; public method init: id; override; method viewDidLoad; override; end; implementation method RootViewController.init: id; begin self := inherited init; if assigned(self) then begin title := 'Oxygene UITableViewCell Demo'; dataArray := [['Athens','Greece','Summer','1896','April 6 to April 15'], ['Paris','France','Summer','1900','May 14 to October 28'], ['St. Louis','United States','Summer','1904','July 1 to November 23'], ['Athens','Greece','Summer','1906','April 22 to May 2'], ['London','United Kingdom','Summer','1908','April 27 to October 31'], ['Stockholm','Sweden','Summer','1912','May 5 to July 22'], ['Berlin','Germany','Summer','1916','Cancelled due to WWI'], ['Antwerp','Belgium','Summer','1920','April 20 to September 12'], ['Chamonix','France','Winter','1924','January 25 to February 4'], ['Paris','France','Summer','1924','May 4 to July 27'], ['St. Moritz','Switzerland','Winter','1928','February 11 to February 19'], ['Amsterdam','Netherlands','Summer','1928','May 17 to August 12'], ['Lake Placid','United States','Winter','1932','February 4 to February 15'], ['Los Angeles','United States','Summer','1932','July 30 to August 14'], ['Garmisch-Partenkirchen','Germany','Winter','1936','February 6 to February 16'], ['Berlin','Germany','Summer','1936','August 1 to August 16'], ['Sapporo','Japan','Winter','1940','Cancelled due to WWII'], ['Tokyo','Japan','Summer','1940','Cancelled due to WWII'], ["Cortina d'Ampezzo",'Italy','Winter','1944','Cancelled due to WWII'], ['London','United Kingdom','Summer','1944','Cancelled due to WWII'], ['St. Moritz','Switzerland','Winter','1948','January 30 to February 8'], ['London','United Kingdom','Summer','1948','July 29 to August 14'], ['Oslo','Norway','Winter','1952','February 14 to February 25'], ['Helsinki','Finland','Summer','1952','July 19 to August 3'], ["Cortina d'Ampezzo",'Italy','Winter','1956','January 26 to February 5'], ['Melbourne','Australia','Summer','1956','November 22 to December 8'], ['Stockholm','Sweden','Summer',' 1956','June 10 to June 17'], ['Squaw Valley','United States','Winter','1960','February 18 to February 28'], ['Rome','Italy','Summer','1960','August 25 to September 11'], ['Innsbruck','Austria','Winter','1964','January 29 to February 9'], ['Tokyo','Japan','Summer','1964','October 10 to October 24'], ['Grenoble','France','Winter','1968','February 6 to February 18'], ['Mexico City','Mexico','Summer','1968','October 12 to October 27'], ['Sapporo','Japan','Winter','1972','February 3 to February 13'], ['Munich','West Germany','Summer','1972','August 26 to September 11'], ['Innsbruck','Austria','Winter','1976','February 4 to February 15'], ['Montreal','Canada','Summer','1976','July 17 to August 1'], ['Lake Placid','United States','Winter','1980','February 12 to February 24'], ['Moscow','Soviet Union','Summer','1980','July 19 to August 3'], ['Sarajevo','Yugoslavia','Winter','1984','February 7 to February 19'], ['Los Angeles','United States','Summer','1984','July 28 to August 12'], ['Calgary','Canada','Winter','1988','February 13 to February 28'], ['Seoul','South Korea','Summer','1988','September 17 to October 2'], ['Albertville','France','Winter','1992','February 8 to February 23'], ['Barcelona','Spain','Summer','1992','July 25 to August 9'], ['Lillehammer','Norway','Winter','1994','February 12 to February 27'], ['Atlanta','United States','Summer','1996','July 19 to August 4'], ['Nagano','Japan','Winter','1998','February 7 to February 22'], ['Sydney','Australia','Summer','2000','September 15 to October 1'], ['Salt Lake City','United States','Winter','2002','February 8 to February 24'], ['Athens','Greece','Summer','2004','August 13 to August 29'], ['Turin','Italy','Winter','2006','February 10 to February 26'], ['Beijing','China','Summer','2008','August 8 to August 24'], ['Vancouver','Canada','Winter','2010','February 12 to February 28'], ['London','United Kingdom','Summer','2012','July 27 to August 12'], ['Sochi','Russia','Winter','2014','February 7 to February 23'], ['Rio de Janeiro','Brazil','Summer','2016','August 5 to August 21'], ['Pyeongchang','South Korea','Winter','2018','February 9 to February 25'], ['Tokyo','Japan','Summer','2020','July 24 to August 9']]; end; result := self; end; method RootViewController.viewDidLoad; begin inherited viewDidLoad; self.tableView.registerNib(UINib.nibWithNibName("OlympicCityTableViewCell") bundle(NSBundle.mainBundle)) forCellReuseIdentifier("OlympicCityCell"); end; method RootViewController.tableView(tableView: UITableView) cellForRowAtIndexPath(indexPath: NSIndexPath): UITableViewCell; begin var cell : OlympicCityTableViewCell := tableView.dequeueReusableCellWithIdentifier("OlympicCityCell"); // as OlympicCityTableViewCell; cell.city.text := dataArray[indexPath.row][0]; cell.country.text := dataArray[indexPath.row][1]; cell.gamesType.text := dataArray[indexPath.row][2]; cell.year.text := dataArray[indexPath.row][3]; cell.notes.text := dataArray[indexPath.row][4]; result := cell; end; method RootViewController.tableView(tableView: UITableView) numberOfRowsInSection(section: NSInteger): NSInteger; begin result := dataArray.length; end; method RootViewController.numberOfSectionsInTableView(tableView: UITableView): NSInteger; begin result := 1; end; method RootViewController.tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath); begin var cell : OlympicCityTableViewCell := tableView.cellForRowAtIndexPath(indexPath) as OlympicCityTableViewCell; var text := cell.city.text; var message := new UIAlertView withTitle("City Selected") message(text) &delegate(nil) cancelButtonTitle("OK") otherButtonTitles(nil); message.show(); end; method RootViewController.tableView(tableView: UITableView) heightForRowAtIndexPath(indexPath: NSIndexPath): CGFloat; begin result := 143; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, Winapi.OpenGL, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GLObjects, GLHUDObjects, GLMaterial, GLCustomShader, GLAsmShader, GLScene, GLFBORenderer, GLCoordinates, GLCadencer, GLCrossPlatform, GLBaseClasses, GLWin32Viewer, GLSimpleNavigation, GLRenderContextInfo, GLTeapot, GLSLShader; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCadencer1: TGLCadencer; GLMaterialLibrary1: TGLMaterialLibrary; GLCamera1: TGLCamera; GLFBORenderer1: TGLFBORenderer; GLLightSource1: TGLLightSource; GLHUDSprite1: TGLHUDSprite; GLSimpleNavigation1: TGLSimpleNavigation; GLTeapot1: TGLTeapot; GLSLShader1: TGLSLShader; procedure FormCreate(Sender: TObject); procedure GLSLShader1Apply(Shader: TGLCustomGLSLShader); procedure FormResize(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin GLSLShader1.Enabled := true; end; procedure TForm1.FormResize(Sender: TObject); begin // Regenerate blur asm shader, it depend screen size GLFBORenderer1.Width := GLSceneViewer1.Width; GLFBORenderer1.Height := GLSceneViewer1.Height; GLHUDSprite1.Width := GLSceneViewer1.Width; GLHUDSprite1.Height := GLSceneViewer1.Height; GLHUDSprite1.Position.SetPoint(GLSceneViewer1.Width div 2, GLSceneViewer1.Height div 2, 0); GLCamera1.SceneScale := GLSceneViewer1.Width / GLSceneViewer1.Height; end; procedure TForm1.GLSLShader1Apply(Shader: TGLCustomGLSLShader); begin with Shader do begin Param['RT'].AsTexture2D[0] := GLMaterialLibrary1.TextureByName('colorTex'); Param['blur_dist'].AsFloat := 0.006; end; end; end.
unit VisualThread; interface uses Windows, Classes, Forms, Graphics, ExtCtrls, SysUtils, SyncObjs,DAQDefs, pdfw_def, pwrdaq32; type TVisualThread = class(TThread) private FPaintHeight: Integer; FPaintWidth: Integer; FPaintRect: TRect; FPaintCanvas: TCanvas; FGridCanvas: TCanvas; FMemCanvas: TCanvas; FBuffer: PAnalogInputBuffer; FOffset: DWORD; FChannel: DWORD; FScanSize: DWORD; FNumChannels: DWORD; FViewSize: DWORD; FAdapter: THandle; FNumScans: DWORD; FMode: DWORD; protected procedure DoVisualisation; public constructor Create(PaintCanvas: TCanvas; PaintRect: TRect); procedure Execute; override; property Buffer: PAnalogInputBuffer read FBuffer write FBuffer; property Offset: DWORD read FOffset write FOffset; property Channel: DWORD read FChannel write FChannel; property ScanSize: DWORD read FScanSize write FScanSize; property NumScans: DWORD read FNumScans write FNumScans; property Adapter: THandle read FAdapter write FAdapter; property Mode: DWORD read FMode write FMode; end; implementation // Basic methods from AcquisitionThread constructor TVisualThread.Create(PaintCanvas: TCanvas; PaintRect: TRect); var i : Integer; begin // Assign setup FPaintCanvas := PaintCanvas; FPaintRect := PaintRect; // Create back buffer FPaintWidth := PaintRect.Right-PaintRect.Left; FPaintHeight := PaintRect.Bottom-PaintRect.Top; with TImage.Create(nil) do begin Picture.Bitmap := TBitmap.Create; Picture.Bitmap.Width := FPaintWidth; Picture.Bitmap.Height := FPaintHeight; Canvas.Pen.Color := clLime; Canvas.Brush.Color := clBlack; FMemCanvas := Canvas; end; // Create grid with TImage.Create(nil) do begin Picture.Bitmap := TBitmap.Create; Picture.Bitmap.Width := FPaintWidth; Picture.Bitmap.Height := FPaintHeight; Canvas.Pen.Color := clLime; Canvas.Brush.Color := clBlack; FGridCanvas := Canvas; with FGridCanvas do try Pen.Color := clGray; Brush.Color := clBlack; FillRect (PaintRect); for i:=1 to 9 do begin MoveTo(Round(i * FPaintWidth / 10), PaintRect.Top); LineTo(Round(i * FPaintWidth / 10), PaintRect.Bottom); end; for i:=1 to 9 do begin if i=5 then Pen.Color := clWhite else Pen.Color := clGray; MoveTo(PaintRect.Left, Round(i * FPaintHeight / 10)); LineTo(PaintRect.Right, Round(i * FPaintHeight / 10)); end; except end; end; inherited Create(True); end; procedure TVisualThread.Execute; begin while not Terminated do begin Sleep(50); Synchronize(DoVisualisation); end; end; procedure TVisualThread.DoVisualisation; const Delta = 0.1; var i, k, NumPoints, StartPoint: Integer; RawData: array [0..1023] of Word; VoltValues: array [0..1023] of Real; MaxValue, MinValue, Median, DispCoeff, Value: Real; begin if (Buffer <> nil) and (NumScans > FPaintWidth) then try // calculate number of samples to display if NumScans >= High(RawData) then NumPoints := High(RawData) else NumPoints := NumScans; // copy active channel raw data for i:=0 to NumPoints do RawData[i] := Buffer^[(Offset + i)*ScanSize + Channel]; // convert to the volt values PdAInRawToVolts (Adapter, Mode, @RawData, @VoltValues, NumPoints ); // calculate median MaxValue := 0; MinValue := 0; for i:=0 to NumPoints-1 do begin if VoltValues[i] > MaxValue then MaxValue := VoltValues[i] else if VoltValues[i] < MinValue then MinValue := VoltValues[i]; end; Median := MinValue + (MaxValue - MinValue) / 2; // triggering: median, rising level StartPoint := 0; for i:=0 to NumPoints-FPaintWidth do if (VoltValues[i] > Median-Delta) and (VoltValues[i] < Median+Delta) and (VoltValues[i] < VoltValues[i+2]) then begin StartPoint := i; Break; end; if StartPoint = 0 then // special trigger for square waveforms for i:=0 to NumPoints-FPaintWidth do if (VoltValues[i] > MinValue-2*Delta) and (VoltValues[i] < MinValue+2*Delta) and (VoltValues[i+2] > MinValue+2*Delta) then begin StartPoint := i; Break; end; // calculate display coefficient if Mode and AIB_INPRANGE > 0 then DispCoeff := FPaintHeight / 20 else DispCoeff := FPaintHeight / 10; // draw oscilloscope with FMemCanvas do try // clear background CopyRect(FPaintRect, FGridCanvas, FPaintRect); MoveTo( 0, FPaintHeight div 2 - Round (VoltValues[StartPoint] * DispCoeff)); // draw oscilliscope for i := 1 to FPaintWidth do LineTo( i, FPaintHeight div 2 - Round (VoltValues[StartPoint+i] * DispCoeff)); except end; FPaintCanvas.CopyRect(FPaintRect, FMemCanvas, FPaintRect); except end; end; end.
unit uVTHeaderPopupMenu; interface uses Windows, Messages, SysUtils, Menus, Classes, Buttons, Graphics, Controls, ComCtrls, StdCtrls, ExtCtrls, sChatView, VirtualTrees, ShellAPI, VTHeaderPopup, ImgList, uGifVirtualStringTree, Dialogs, uLineNode, uChatUser, uFormPassword, uFormUserInfo, sSpeedButton, sPageControl, sMemo, sEdit, sSplitter, sPanel, sButton, sDialogs, //баженов DChatClientServerPlugin, USettings; //баженов Const //т.к. у нас один обработчик клика по строчке всплываеющего меню, то по этим //константам обработчик понимает по какому именно пункту мы кликнули //константы храняться в .TAG у каждого пункта меню //.Command - read only ((( ONMENUTUserSendPrivateMessage = 1; ONMENUTUserSendPrivateMessageToAll = 2; ONMENUTUserCreatePrivateChat = 3; ONMENUTUserCreateLine = 4; ONMENUTLineNodeCreatePrivateChat = 5; ONMENUTLineNodeConnectToPrivateChat = 6; ONMENUTLineNodeConnectToLine = 7; ONMENUTChatViewClosePrivateChat = 8; ONMENUTTreeViewRefresh = 9; ONMENURxTrayExit = 10; ONMENUTSpeedButtonMessagesState = 11; ONMENUTUserIgnore = 12; ONMENUTDebugMemo1SaveLog = 13; ONMENUTDebugMemo2SaveLog = 14; ONMENUTTreeViewUserInfo = 15; ONMENUTUserSeeShare = 16; ONMENUTUserWriteNickName = 17; //Баженов ONMENUTUserPluginClick = 100;//внимание! от 100 и выше идут плагины!!! type TMenuItemId = class(TMenuItem) private { Private declarations } public { Public declarations } Id: Integer; DChatClientServerPlugin: TDChatClientServerPlugin; end; //Баженов type TDynamicVTHPopupMenu = class(TVTHeaderPopupMenu) private { Private declarations } public { Public declarations } FParentChatLine:TObject;//из-за невозможности подключить в USES модуль //uChatLine нельзя сделать эту переменную //типа FParentChatLine:TChatLine MenuItemId: TMenuItemId; FPDNode : PDataNode; FVirtualNode: PVirtualNode; SpeedButtonNumber: integer; //сюда записывается номер кнопки, иначе никак SpeedButton: TsSpeedButton; constructor CreateDVTH(AComponent:TComponent; ParentChatLine: TObject);{override;} destructor Destroy;override; procedure StringToComponent(Component: TComponent; Value: string); procedure OnComponentClick(Component: TComponent; X, Y: Integer); PROCEDURE OnMenuClick(Sender: TObject); procedure AddNickLinkMenu(Component: TComponent; X, Y: Integer; tUser: TChatUser); procedure AddUserMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode; VirtualNode:PVirtualNode); procedure AddPrivateChatMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode ; VirtualNode:PVirtualNode); procedure AddLineMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode ; VirtualNode:PVirtualNode); procedure OnAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); procedure OnMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); procedure AddRxTrayMenu(Sender: TComponent); end; var Bitmap: TBitmap; Component: TWinControl; implementation uses uFormMain, uChatLine, uFormDebug, DreamChatConfig, uPathBuilder, uImageLoader; procedure TDynamicVTHPopupMenu.StringToComponent(Component: TComponent; Value: string); var StrStream:TStringStream; ms: TMemoryStream; begin StrStream := TStringStream.Create(Value); try ms := TMemoryStream.Create; try ObjectTextToBinary(StrStream, ms); ms.position := 0; ms.ReadComponent(Component); finally ms.Free; end; finally StrStream.Free; end; end; constructor TDynamicVTHPopupMenu.CreateDVTH(AComponent:TComponent; ParentChatLine: TObject); //var // MS: TMemoryStream; begin inherited Create(AComponent); self.FParentChatLine := ParentChatLine; Self.Images := TImageList.Create(Self); self.OwnerDraw := true; //создаем готовые наборы менюшек //==== меню для TPanel ==== MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'Это меню для'; self.Items.Add(MenuItemId); Bitmap := TBitmap.Create; end; destructor TDynamicVTHPopupMenu.Destroy; begin Bitmap.Free; inherited Destroy(); end; procedure TDynamicVTHPopupMenu.OnComponentClick(Component: TComponent; X, Y: Integer); var i: integer; StrList: TStringList; begin //FormMain.Caption := Component.name; //FormMain.Caption := ''; Self.Items.Clear; self.Images.Clear; FParentChatLine := FormMain.GetActiveChatLine; if Component is TsSpeedButton then begin StrList := TStringList.Create; SpeedButton := TsSpeedButton(Component); if TsSpeedButton(Component).Name = 'SpeedButton3' then begin TDreamChatConfig.FillMessagesState0(StrList); // FormMain.ChatConfig.ReadSectionValues('MessagesState0', StrList); SpeedButtonNumber := 0; end; if TsSpeedButton(Component).Name = 'SpeedButton4' then begin TDreamChatConfig.FillMessagesState1(StrList); // FormMain.ChatConfig.ReadSectionValues('MessagesState1', StrList); SpeedButtonNumber := 1; end; if TsSpeedButton(Component).Name = 'SpeedButton5' then begin TDreamChatConfig.FillMessagesState2(StrList); //FormMain.ChatConfig.ReadSectionValues('MessagesState2', StrList); SpeedButtonNumber := 2; end; if TsSpeedButton(Component).Name = 'SpeedButton6' then begin TDreamChatConfig.FillMessagesState3(StrList); //FormMain.ChatConfig.ReadSectionValues('MessagesState3', StrList); SpeedButtonNumber := 3; end; if StrList.Count > 0 then begin for i := 0 to StrList.Count - 1 do begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := StrList.Strings[i]; MenuItemId.OnClick := OnMenuClick; //MenuItemId.Command := ONMENUTSpeedButtonMessagesState; MenuItemId.Tag := ONMENUTSpeedButtonMessagesState; Self.Items.Add(MenuItemId); end; if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); self.Popup(X, Y); end; StrList.free; end; if Component is TsEdit then begin {MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'Это меню для'; Self.Items.Add(MenuItemId); MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'TPanel'; Self.Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); self.Popup(X, Y);} end; if Component is TsPanel then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'Это меню для'; Self.Items.Add(MenuItemId); MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'TPanel'; Self.Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); self.Popup(X, Y); end; if Component is TsPageControl then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'Это меню для'; Items.Add(MenuItemId); MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'TPageControl'; Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); Popup(X, Y); end; if Component is TsChatView then begin if TChatLine(FParentChatLine) <> FormMain.GetMainLine then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := fmInternational.Strings[I_CLOSE];//'Закрыть'; // MenuItemId.ImageIndex := Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_CLOSE].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_CLOSE].Bitmap[0].TransparentColor); MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_CLOSE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_CLOSE).Bitmap[0].TransparentColor); MenuItemId.OnClick := OnMenuClick; //MenuItemId.Command := ONMENUTChatViewClosePrivateChat; MenuItemId.Tag := ONMENUTChatViewClosePrivateChat; Items.Add(MenuItemId); {MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := 'TChatView'; Self.Items.Add(MenuItemId);} end; if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); Popup(X, Y); end; if Component is TVirtualStringTree then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := fmInternational.Strings[I_REFRESH];//Обновить // MenuItemId.ImageIndex:=Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_Refresh].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_Refresh].Bitmap[0].TransparentColor); MenuItemId.ImageIndex:=Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_REFRESH).Bitmap[0], TDreamChatImageLoader.GetImage(G_REFRESH).Bitmap[0].TransparentColor); MenuItemId.OnClick := OnMenuClick; //MenuItemId.Command := ONMENUTTreeViewRefresh; MenuItemId.Tag := ONMENUTTreeViewRefresh; Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); Popup(X, Y); end; if (Component is TsMemo) then begin if TsMemo(Component).Name = 'DebugMemo1' then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := fmInternational.Strings[I_SAVELOG];//Сохранить лог // MenuItemId.ImageIndex:=Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_SAVE].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_SAVE].Bitmap[0].TransparentColor); MenuItemId.ImageIndex:=Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_SAVE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_SAVE).Bitmap[0].TransparentColor); MenuItemId.OnClick := OnMenuClick; //MenuItemId.Command := ONMENUTTreeViewRefresh; MenuItemId.Tag := ONMENUTDebugMemo1SaveLog; Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); Popup(X, Y); end; if TsMemo(Component).Name = 'DebugMemo2' then begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := fmInternational.Strings[I_SAVELOG];//Сохранить лог // MenuItemId.ImageIndex:=Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_SAVE].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_SAVE].Bitmap[0].TransparentColor); MenuItemId.ImageIndex:=Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_SAVE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_SAVE).Bitmap[0].TransparentColor); MenuItemId.OnClick := OnMenuClick; //MenuItemId.Command := ONMENUTTreeViewRefresh; MenuItemId.Tag := ONMENUTDebugMemo2SaveLog; Items.Add(MenuItemId); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); Popup(X, Y); end; end; end; procedure TDynamicVTHPopupMenu.AddNickLinkMenu(Component: TComponent; X, Y: Integer; tUser: TChatUser); var PDNode: PDataNode; // i: integer; VirtualNode: PVirtualNode; begin //создаем меню, появляющегося при нажатии на юзера в дереве //MessageBox(0, PChar(TChatLine(self.FParentChatLine).ChatLineName), PChar(inttostr(0)) ,mb_ok); FParentChatLine := FormMain.GetActiveChatLine; VirtualNode := TChatLine(FParentChatLine).ChatLineTree.GetFirst; while VirtualNode <> nil do begin PDNode := TChatLine(FParentChatLine).ChatLineTree.GetNodeData(VirtualNode); if PDNode.User = tUser then begin AddUserMenu(Component, X, Y, PDNode, VirtualNode); break; end; VirtualNode := VirtualNode.NextSibling; end; end; procedure TDynamicVTHPopupMenu.AddUserMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode ; VirtualNode:PVirtualNode); var p: TPoint; i, MenuNumb : integer; ClientServerPlugin : TDChatClientServerPlugin; MenuCaption: string; begin //создаем меню, появляющегося при нажатии на юзера в дереве //MessageBox(0, PChar(TChatLine(self.FParentChatLine).ChatLineName), PChar(inttostr(0)) ,mb_ok); FParentChatLine := FormMain.GetActiveChatLine; FPDNode := PDNode; FVirtualNode := VirtualNode; Self.Items.Clear; Self.Images.Clear; //========= Добавляем строчку меню: Написать имя self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := fmInternational.Strings[I_WRITENICKNAME] + ' ' + PDNode.User.DisplayNickName;//Личное сообщение //Self.MenuItemId.Command := ONMENUTUserSendPrivateMessage;//короче надо в одном обработчике различать разные клики Self.MenuItemId.Tag := ONMENUTUserWriteNickName;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; //MenuItemId.ImageIndex := Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_NICKNAME].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_NICKNAME].Bitmap[0].TransparentColor); self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_NICKNAME).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_NICKNAME).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: [---------------------] Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := '-'; Self.MenuItemId.Tag := 0;//короче надо в одном обработчике различать разные клики Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: Личное сообщение Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := fmInternational.Strings[I_PRIVATEMESSAGE] + ' ' + PDNode.User.DisplayNickName;//Личное сообщение //Self.MenuItemId.Command := ONMENUTUserSendPrivateMessage;//короче надо в одном обработчике различать разные клики Self.MenuItemId.Tag := ONMENUTUserSendPrivateMessage;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; //MenuItemId.ImageIndex := Self.Images.AddMasked(TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_PRIVATE_MESSAGE].Bitmap[0], // TChatLine(FParentChatLine).ChatLineTree.TreeGifImages[G_POPUP_PRIVATE_MESSAGE].Bitmap[0].TransparentColor); self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_MESSAGE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_MESSAGE).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: Личное сообщение всем Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := fmInternational.Strings[I_PRIVATEMESSAGETOALL] + ' ';//Личное сообщение всем Self.MenuItemId.Tag := ONMENUTUserSendPrivateMessageToAll;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_MASSMESSAGE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_MASSMESSAGE).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: [---------------------] Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := '-'; Self.MenuItemId.Tag := 0;//короче надо в одном обработчике различать разные клики Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= //if AnsiCompareText(TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].ComputerName, TChatLine(FParentChatLine).LocalComputerName) <> 0 then if AnsiCompareText(FPDNode.User.ComputerName, TChatLine(FParentChatLine).LocalComputerName) <> 0 then begin //========= Добавляем строчку меню: Личный чат с Self.MenuItemId := TMenuItemId.Create(Self); //Self.MenuItemId.Caption := 'Личный чат с ' + TChatLine(self.FParentChatLine).ChatLineUsers[PDNode.DataUserId].DisplayNickName; Self.MenuItemId.Caption := fmInternational.Strings[I_PRIVATEWITH] + ' ' + PDNode.User.DisplayNickName;//Личный чат с Self.MenuItemId.Tag := ONMENUTUserCreatePrivateChat; Self.MenuItemId.OnClick := OnMenuClick; self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_CHAT).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_CHAT).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); end; //========= Добавляем строчку меню: Создать линию Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := fmInternational.Strings[I_CREATELINE];//Создать линию Self.MenuItemId.Tag := ONMENUTUserCreateLine; Self.MenuItemId.OnClick := OnMenuClick; MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_CREATE_LINE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_CREATE_LINE).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: [---------------------] Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := '-'; Self.MenuItemId.Tag := 0;//короче надо в одном обработчике различать разные клики Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: Перейти к ресурсам компьютера Self.MenuItemId := TMenuItemId.Create(Self); if ChatMode = cmodTCP then Self.MenuItemId.Caption := fmInternational.Strings[I_SEESHARE] + FPDNode.User.IP else Self.MenuItemId.Caption := fmInternational.Strings[I_SEESHARE] + FPDNode.User.ComputerName; Self.MenuItemId.Tag := ONMENUTUserSeeShare;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_SEE_SHARE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_SEE_SHARE).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: Игнорировать все сообщения //if AnsiCompareText(TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].ComputerName, TChatLine(FParentChatLine).LocalComputerName) <> 0 then if AnsiCompareText(FPDNode.User.ComputerName, TChatLine(FParentChatLine).LocalComputerName) <> 0 then begin Self.MenuItemId := TMenuItemId.Create(Self); //if TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].Ignored = true then if FPDNode.User.Ignored = true then begin Self.MenuItemId.Checked := true; end else begin Self.MenuItemId.Checked := false; end; Self.MenuItemId.Caption := fmInternational.Strings[I_TOTALIGNOR]; Self.MenuItemId.Tag := ONMENUTUserIgnore; Self.MenuItemId.OnClick := OnMenuClick; MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_IGNORED).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_IGNORED).Bitmap[0].TransparentColor); Self.Items.Add(DynamicPopupMenu.MenuItemId); end; //Begin DChat 1.0 //========= Добавляем строчку меню: [ от Плагинов ] if FormMain.FSettings <> nil then with FormMain do begin for i := 0 to FSettings.listBox2.Items.Count - 1 do begin if FSettings.listBox2.Items.Objects[i] <> nil then begin if FSettings.listBox2.Items.Objects[i] is TDChatClientServerPlugin then begin ClientServerPlugin := TDChatClientServerPlugin(FSettings.listBox2.Items.Objects[i]); MenuNumb := 0; //вызываем функцию плагина, передаем ему команду 'GetMenuItem' //в ответ получаем строчку для меню MenuCaption := ClientServerPlugin.ExecuteCommand('GetMenuItem', Pchar(inttostr(MenuNumb)), 0); //вызываем функцию плагина с командой 'GetMenuItem' до тех пор, пока она > 0 //таким образом плагин может вернуть несколько строк для контекстного меню TMenuItem while length(MenuCaption) > 0 do begin MenuItemId := TMenuItemId.Create(Self); MenuItemId.Tag := ONMENUTUserPluginClick + i; MenuItemId.Id := MenuNumb;//0; MenuItemId.DChatClientServerPlugin := ClientServerPlugin; MenuItemId.OnClick := OnMenuClick; //MenuItemId.Caption := 'Это меню для'; MenuItemId.Caption := MenuCaption; Self.Items.Add(MenuItemId); inc(MenuNumb); MenuCaption := ClientServerPlugin.ExecuteCommand('GetMenuItem', Pchar(inttostr(MenuNumb)), 0); end; end; end; end; end; //End DChat 1.0 //========= Добавляем строчку меню: [---------------------] Self.MenuItemId := TMenuItemId.Create(Self); Self.MenuItemId.Caption := '-'; Self.MenuItemId.Tag := 0;//короче надо в одном обработчике различать разные клики Self.Items.Add(DynamicPopupMenu.MenuItemId); //========= Добавляем строчку меню: О пользователе MenuItemId := TMenuItemId.Create(Self); MenuItemId.Caption := fmInternational.Strings[I_USERINFO];//О пользователе MenuItemId.OnClick := OnMenuClick; //FormUI.GetUserInfo(TChatLine(FParentChatLine), FPDNode.DataUserId); FormUI.GetUserInfo(TChatLine(FParentChatLine), FPDNode.User); Bitmap.Height := FormUI.UserInfoChatView.Height; Bitmap.Width := FormUI.UserInfoChatView.Width; FormUI.UserInfoChatView.PaintTo(Bitmap.Canvas.Handle, 0, 0); //bitblt(Bitmap.Canvas.Handle, 0, 0, FormUI.ChatView1.Width, FormUI.ChatView1.Height, // GetDC(FormUI.ChatView1.Handle), 0, 0, SRCCOPY); MenuItemId.OnAdvancedDrawItem := OnAdvancedDrawItem; MenuItemId.OnMeasureItem := OnMeasureItem; MenuItemId.Tag := ONMENUTTreeViewUserInfo; Items.Add(MenuItemId); //========= if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); p.X := X; p.Y := Y; p := (Component as TControl).ClientToScreen(p); Self.Popup(p.X, p.Y {MouseX, MouseY}); end; procedure TDynamicVTHPopupMenu.AddRxTrayMenu(Sender: TComponent); var MenuItemId: TMenuItemId; i, MenuNumb: integer; ClientServerPlugin : TDChatClientServerPlugin; MenuCaption: string; begin DynamicPopupMenu.Items.Clear; DynamicPopupMenu.Images.Clear; //Begin DChat 1.0 //========= Добавляем строчку меню: [ от Плагинов ] if FormMain.FSettings <> nil then begin with FormMain do begin for i := 0 to FSettings.listBox2.Items.Count - 1 do begin if FSettings.listBox2.Items.Objects[i] <> nil then begin if FSettings.listBox2.Items.Objects[i] is TDChatClientServerPlugin then begin ClientServerPlugin := TDChatClientServerPlugin(FSettings.listBox2.Items.Objects[i]); MenuNumb := 0; //вызываем функцию плагина, передаем ему команду 'GetMenuItem' //в ответ получаем строчку для меню MenuCaption := ClientServerPlugin.ExecuteCommand('GetMenuItem', Pchar(inttostr(MenuNumb)), 0); //вызываем функцию плагина с командой 'GetMenuItem' до тех пор, пока она > 0 //таким образом плагин может вернуть несколько строк для контекстного меню TMenuItem MenuItemId := TMenuItemId.Create(Self); MenuItemId.Tag := ONMENUTUserPluginClick + i; MenuItemId.Id := MenuNumb;//0; MenuItemId.DChatClientServerPlugin := ClientServerPlugin; MenuItemId.OnClick := OnMenuClick; //MenuItemId.Caption := 'Это меню для'; MenuItemId.Caption := MenuCaption; Self.Items.Add(MenuItemId); inc(MenuNumb); MenuCaption := ClientServerPlugin.ExecuteCommand('GetMenuItem', Pchar(inttostr(MenuNumb)), 0); end; end; end; end; end; //End DChat 1.0 //========= <Exit> DynamicPopupMenu.MenuItemId := TMenuItemId.Create(Sender); DynamicPopupMenu.MenuItemId.Caption := fmInternational.Strings[I_EXIT]; DynamicPopupMenu.MenuItemId.Tag := ONMENURxTrayExit;//короче надо в одном обработчике различать разные клики DynamicPopupMenu.MenuItemId.OnClick := DynamicPopupMenu.OnMenuClick; DynamicPopupMenu.Items.Add(DynamicPopupMenu.MenuItemId); DynamicPopupMenu.MenuItemId.ImageIndex := DynamicPopupMenu.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_EXIT).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_EXIT).Bitmap[0].TransparentColor); //========= </Exit> end; procedure TDynamicVTHPopupMenu.AddPrivateChatMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode ; VirtualNode:PVirtualNode); var User: TChatUser; p: TPoint; //DChat 1.0 MenuItemId: TMenuItemId; //DChat 1.0 begin //создаем меню, появляющееся при нажатии на Приват в дереве FParentChatLine := FormMain.GetActiveChatLine; FPDNode := PDNode; Self.Items.Clear; Self.MenuItemId := TMenuItemId.Create(Self); //User := TChatLine(self.FParentChatLine).ChatLineUsers[PDNode.DataUserId]; User := PDNode.User; //Self.MenuItem.Caption := 'Войти в приват ' + TLineNode(User.ChatLinesList.Objects[PDNode.DataLineId]).DisplayLineName; Self.MenuItemId.Caption := fmInternational.Strings[I_COMETOPRIVATE] + ' ' + TLineNode(PDNode.LineNode).DisplayLineName; Self.Items.Add(DynamicPopupMenu.MenuItemId); Self.MenuItemId.Tag := ONMENUTLineNodeConnectToPrivateChat;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; Self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_CHAT).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_PRIVATE_CHAT).Bitmap[0].TransparentColor); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); p.X := X; p.Y := Y; p := (Component as TControl).ClientToScreen(p); Self.Popup(p.X, p.Y {MouseX, MouseY}); end; procedure TDynamicVTHPopupMenu.AddLineMenu(Component: TComponent; X, Y: Integer; PDNode: PDataNode ; VirtualNode:PVirtualNode); var User: TChatUser; p:TPoint; begin //создаем меню, появляющееся при нажатии на Линия в дереве FParentChatLine := FormMain.GetActiveChatLine; FPDNode := PDNode; Self.Items.Clear; Self.MenuItemId := TMenuItemId.Create(Self); //User := TChatLine(self.FParentChatLine).ChatLineUsers[PDNode.DataUserId]; User := PDNode.User; //Self.MenuItem.Caption := 'Войти в линию ' + TLineNode(User.ChatLinesList.Objects[PDNode.DataLineId]).DisplayLineName; Self.MenuItemId.Caption := fmInternational.Strings[I_COMETOLINE] + ' ' + TLineNode(PDNode.LineNode).DisplayLineName; Self.Items.Add(DynamicPopupMenu.MenuItemId); Self.MenuItemId.Tag := ONMENUTLineNodeConnectToLine;//короче надо в одном обработчике различать разные клики Self.MenuItemId.OnClick := OnMenuClick; Self.MenuItemId.ImageIndex := Self.Images.AddMasked(TDreamChatImageLoader.GetImage(G_POPUP_CREATE_LINE).Bitmap[0], TDreamChatImageLoader.GetImage(G_POPUP_CREATE_LINE).Bitmap[0].TransparentColor); if uFormMain.FormMain.SkinManMain.Active then uFormMain.FormMain.SkinManMain.SkinableMenus.HookPopupMenu(self,True); p.X := X; p.Y := Y; p := (Component as TControl).ClientToScreen(p); Self.Popup(p.X, p.Y {MouseX, MouseY}); //Self.on end; PROCEDURE TDynamicVTHPopupMenu.OnMenuClick(Sender: TObject); var VirtualKey: Char; User: TChatUser; ChatLine: TChatLine; pResult:PChar; sResult:string; // c: cardinal; //StartupInfo: TStartupInfo; //ProcessInfo: TProcessInformation; ClientServerPlugin : TDChatClientServerPlugin; n, i : integer; InitString: string; begin FParentChatLine := FormMain.GetActiveChatLine; VirtualKey := Char(13);//VK_RETURN; //case TMenuItem(Sender).Command of case TMenuItem(Sender).Tag of ONMENUTUserWriteNickName: begin FormMain.Edit1.Text := FPDNode.User.NickName + ': '; FormMain.Edit1.SelStart := length(FormMain.Edit1.Text); //FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTUserSendPrivateMessage: begin //FormMain.Edit1.Text := '/msg "' + TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].DisplayNickName + '" '; FormMain.Edit1.Text := '/msg "' + FPDNode.User.DisplayNickName + '" '; FormMain.Edit1.SelStart := length(FormMain.Edit1.Text); //FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTUserSendPrivateMessageToAll: begin FormMain.Edit1.Text := '/msg "*" '; FormMain.Edit1.SelStart := length(FormMain.Edit1.Text); //FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTUserCreatePrivateChat: begin //FormMain.Edit1.Text := '/chat "' + TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].DisplayNickName + '"'; FormMain.Edit1.Text := '/chat "' + FPDNode.User.DisplayNickName + '"'; FormMain.Edit1.OnKeyPress(Self, VirtualKey); end; ONMENUTUserCreateLine: begin if ShowPasswordForm(false, '', pResult) = mrOk then begin sResult := pResult; FormMain.Edit1.Text := '/line ' + sResult; //MessageBox(0, PChar(FormMain.Edit1.Text), PChar(inttostr(0)), mb_ok); FormMain.Edit1.OnKeyPress(Self, VirtualKey); end; end; ONMENUTChatViewClosePrivateChat: begin FormMain.Edit1.Text := '/close'; FormMain.Edit1.OnKeyPress(Self, VirtualKey); //FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTLineNodeCreatePrivateChat: begin //FormMain.Edit1.Text := '/chat "' + TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].DisplayNickName + '"'; FormMain.Edit1.Text := '/chat "' + FPDNode.User.DisplayNickName + '"'; //FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTLineNodeConnectToPrivateChat: begin //User := TChatLine(self.FParentChatLine).ChatLineUsers[FPDNode.DataUserId]; FormMain.Edit1.Text := '/connectchat "' + TLineNode(FPDNode.LineNode).LineName + '"'; FormMain.Edit1KeyPress(Self, VirtualKey); end; ONMENUTLineNodeConnectToLine: begin //User := TChatLine(self.FParentChatLine).ChatLineUsers[FPDNode.DataUserId]; //ChatLine := FormMain.GetChatLineByName(TLineNode(User.ChatLinesList.Objects[FPDNode.DataLineId]).LineName); ChatLine := FormMain.GetChatLineByName(TLineNode(FPDNode.LineNode).LineName); if ChatLine <> nil then begin //если такая линия/приват уже существуют, делаем активным его TabSheet FormMain.PageControl1.ActivePageIndex := ChatLine.ChatLineTabSheet.PageIndex; //if User = TChatLine(self.FParentChatLine).GetLocalUser() then end else begin //такой линии нет, будем создавать //if ShowPasswordForm(true, PChar(TLineNode(User.ChatLinesList.Objects[FPDNode.DataLineId]).LineName), pResult) = mrOk then if ShowPasswordForm(true, PChar(TLineNode(FPDNode.LineNode).LineName), pResult) = mrOk then begin sResult := pResult; FormMain.Edit1.Text := '/connectline ' + sResult; FormMain.Edit1.OnKeyPress(Self, VirtualKey); end; end; end; ONMENURxTrayExit: begin if MinimizeOnClose then begin MinimizeOnClose := False; FormMain.Close; MinimizeOnClose := True; end else FormMain.Close; end; ONMENUTTreeViewRefresh: begin ChatLine := TChatLine(self.FParentChatLine); {for c := 0 to ChatLine.UsersCount - 1 do begin //FormMain.ShowUserInTree(ChatLine, c, ShowUser_REDRAW); end;} FormMain.ShowAllUserInTree(ChatLine); end; ONMENUTTreeViewUserInfo: begin //FormUI.GetUserInfo(TChatLine(FParentChatLine), FPDNode.DataUserId); FormUI.GetUserInfo(TChatLine(FParentChatLine), FPDNode.User); if FormUI.Visible = true then FormUI.BringToFront else FormUI.Visible := true; end; ONMENUTSpeedButtonMessagesState: begin User := FormMain.GetMainLine.GetLocalUser; User.MessageStatus.strings[SpeedButtonNumber] := TMenuItem(Sender).Caption; SpeedButton.Click; end; ONMENUTUserSeeShare: begin {FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESTDHANDLES; StartupInfo.wShowWindow := SW_SHOWNORMAL;//SW_HIDE; StartupInfo.hStdOutput := 0; StartupInfo.hStdInput := 0;} if ChatMode = cmodTCP then begin if ShellExecute(0, 'explore', PChar('\\' + FPDNode.User.IP +'\'), '', '', SW_SHOWNORMAL)<33 then TDebugMan.AddLine2('Can''t open \\' + FPDNode.User.IP +'\'); //FormDebug.DebugMemo2.Lines.Add('Can''t open \\' + FPDNode.User.IP +'\'); {CreateProcess(nil, PChar('explorer.exe \\' + FPDNode.User.IP), nil, nil, True, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo)} end else if ShellExecute(0, 'explore', PChar('\\' + FPDNode.User.ComputerName +'\'), '', '', SW_SHOWNORMAL)<33 then TDebugMan.AddLine2('Can''t open \\' + FPDNode.User.ComputerName +'\'); //FormDebug.DebugMemo2.Lines.Add('Can''t open \\' + FPDNode.User.ComputerName +'\'); {CreateProcess(nil, PChar('explorer.exe \\' + FPDNode.User.ComputerName), nil, nil, True, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo);} end; ONMENUTUserIgnore: begin //if TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].Ignored = true then if FPDNode.User.Ignored = true then begin //TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].Ignored := false; FPDNode.User.Ignored := false; TMenuItem(Sender).Checked := false; end else begin //TChatLine(FParentChatLine).ChatLineUsers[FPDNode.DataUserId].Ignored := true; FPDNode.User.Ignored := true; TMenuItem(Sender).Checked := true; end; FormMain.ShowAllUserInTree(TChatLine(FParentChatLine)); end; ONMENUTDebugMemo1SaveLog: begin TDebugMan.SaveToFile1(TPathBuilder.GetExePath() + 'ObjectLog.txt'); //FormDebug.DebugMemo1.Lines.SaveToFile(TPathBuilder.GetExePath() + 'ObjectLog.txt'); end; ONMENUTDebugMemo2SaveLog: begin TDebugMan.SaveToFile1(TPathBuilder.GetExePath() + 'ProtocolLog.txt'); //FormDebug.DebugMemo2.Lines.SaveToFile(TPathBuilder.GetExePath() + 'ProtocolLog.txt'); end else //DChat 1.0 тут происходит обработка нажатия на строку меню, которую добавил плагин begin if TMenuItemId(Sender).Tag >= ONMENUTUserPluginClick then begin // sMessageDlg(inttostr(TMenuItemId(Sender).tag), 'ONMENUTUserPluginClick ', mtInformation, [mbOk], 0) // if FSettings.listBox2.Items.Objects[TMenuItemId(Sender).Tag - 100] is TDChatClientServerPlugin then // begin // ClientServerPlugin := TDChatClientServerPlugin(FSettings.listBox2.Items.Objects[TMenuItemId(Sender).Tag - 100]); // ClientServerPlugin.ShowPluginForm; // end; // end if TMenuItemId(Sender).DChatClientServerPlugin <> nil then begin if TMenuItemId(Sender).DChatClientServerPlugin is TDChatClientServerPlugin then begin ClientServerPlugin := TMenuItemId(Sender).DChatClientServerPlugin; if ClientServerPlugin.PluginInfo.PluginName = 'File client' then begin //если выделен плагин типа TDChatTestPlugin, то у него есть //функция TestFunction1, TestFunction2 n := TMenuItemId(Sender).Id;//{ - Trunc(TMenuItem(Sender).Tag/100)*100}; case n of 0: begin if ClientServerPlugin <> nil then begin ClientServerPlugin.ExecuteCommand('ShowForm', '', 0); // Memo2.Lines.Add('ExecuteCommand ShowForm'); end; end; 1: begin if (ClientServerPlugin <> nil) and (FPDNode <> nil) then begin // Randomize; User := FormMain.GetMainLine.GetLocalUser; InitString := '[Client]' + #13 + // 'ServerIP=127.0.0.1'+ #13 + 'ServerIP=' + FPDNode.User.IP + #13 + 'ServerPort=5557'+ #13 + 'NickName=' + User.NickName + #13 + 'RemoteNickName=' + FPDNode.User.DisplayNickName + #13 + // временно генерим случайный порт, чтобы произошла ошибка связи // 'ServerPort=' + inttostr(random(10000)) + #13 + 'AutoConnect=true'; ClientServerPlugin.ExecuteCommand('Connect', PChar(InitString), 0); // Memo2.Lines.Add('ExecuteCommand Connect'); end; end; end; end; if ClientServerPlugin.PluginInfo.PluginName = 'File server' then begin //если выделен плагин типа TDChatTestPlugin, то у него есть //функция TestFunction1, TestFunction2 if ClientServerPlugin <> nil then begin ClientServerPlugin.ExecuteCommand('ShowForm', '', 0); // Memo2.Lines.Add('ExecuteCommand ShowForm'); end; // Memo2.Lines.Add('MenuItem2'); end; end; end; end else sMessageDlg(inttostr(TMenuItem(Sender).tag), 'OnMenuClick ', mtInformation, [mbOk], 0); end; end; end; procedure TDynamicVTHPopupMenu.OnAdvancedDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); //var DC: hDC; //Point: TPoint; //Window: TWinControl; begin {Bitmap.Height := Component.Height; Bitmap.Width := Component.Width; DC := GetDC(Component.Handle); bitblt(Bitmap.Canvas.Handle, 0, 0, Component.Width, Component.Height, DC, 0, 0, SRCCOPY);} if ACanvas.ClipRect.Right > FormUI.Width then begin //если ширина Формы с инфой пользователя меньше, чем ширина меню //увеличиваем размер формы, до размера меню FormUI.Width := ACanvas.ClipRect.Right + 11; FormUI.Repaint; Bitmap.Height := FormUI.UserInfoChatView.Height; Bitmap.Width := FormUI.UserInfoChatView.Width; FormUI.UserInfoChatView.PaintTo(Bitmap.Canvas.Handle, 0, 0); end; ACanvas.Draw(ARect.Left, ARect.Top, Bitmap); //Edit1.ParentWindow := VTHeaderPopupMenu1.WindowHandle; {Point.x := 20;//ARect.Left; Point.y := 20;//ARect.Top; Window := FindVCLWindow(Point); FormMain.Caption := inttostr(ARect.Left);} //никак не хочет(( //Window := FindControl(VTHeaderPopupMenu1.WindowHandle); {Window := FindControl(VTHeaderPopupMenu1.Items.WindowHandle); //Window := FindControl(ChatView1.Handle);//FindVCLWindow(Point); if Window <> nil then begin MessageBox(0, PChar('1'), PChar(inttostr(1)), mb_ok); Edit1.Parent := Window;//(VTHeaderPopupMenu1); Edit1.Top := 20; Edit1.Left := 0; end;} //Edit1.ParentWindow := ChatView1.Handle; //Edit1.Parent := ChatView1; end; procedure TDynamicVTHPopupMenu.OnMeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); begin Width := FormUI.UserInfoChatView.Width - 11; Height := FormUI.UserInfoChatView.Height; end; {procedure TDynamicVTHPopupMenu.OnPopUp(Sender: TObject);override; begin MessageBox(0, PChar('OnPopUp'), PChar(inttostr(1)) ,mb_ok); inherited OnPopUp; if TComponent(Sender) is TsChatView then begin MenuItem := TMenuItem.Create(Self); MenuItem.Caption := 'Это меню для'; Self.Items.Add(MenuItem); MenuItem := TMenuItem.Create(Self); MenuItem.Caption := 'TChatView'; Self.Items.Add(MenuItem); end; end;} end.
unit ics465cThread; interface uses Windows, Messages, SysUtils, Variants, Classes, SyncObjs, serialportLoad; type TWeighingCallBack = procedure(Weight, Tare: Double; isGross, isOverLoad: Boolean); stdcall; TIcs465c_meter = class(TThread) FCallback: Pointer; FisOpened: Boolean; FComId: Integer; FComPort: TComPort; // 串口对象 FSerialPortDllFileName: string; FisSynchronize: Boolean; // 是否用同步方法 private //FIsOverLoad: Boolean; //FIsGross: Boolean; FIsCommand: Boolean; FAddr: Integer; FWeight, FTotal, FSubtotal: Double; FFlow, FBeltSpeed, FLineSpeed: Double; FCriticalSection: TCriticalSection; procedure Lock; procedure UnLock; function readWeight: Boolean; virtual; function IsOverLoad: Boolean; virtual; function IsGross: Boolean; virtual; function GetDecimalPointFactor(DecimalCount: Byte): Double; //function GetDecimalMultiply(StatusByteA: Byte): Double; //function TestIsGross(StatusByteB : Byte): Boolean; //function GetSign(StatusByteB : Byte): Double; //function TestIsOverLoad(StatusByteB: Byte): Boolean; function GetWeightInternal(var buffer; Pos, size: Integer): Double; procedure SetAddr(Address: Integer); protected procedure ShowData; virtual; //(Weight, Tare: Double; isGross, isOverLoad: Boolean); virtual; procedure Execute; override; public property ComId: Integer read FComId; property SerialPortDllName: string read FSerialPortDllFileName; property IsSynchronize: Boolean read FisSynchronize write FisSynchronize; property IsCommand: Boolean read FIsCommand write FIsCommand; property Address: Integer read FAddr write SetAddr; procedure SetCallBack(CallBack: Pointer); virtual; function GetWeight: Double; virtual; function GetTotal: Double; virtual; function GetSubTotal: Double; virtual; function GetBeltSpeed: Double; virtual; // 皮带速度 function GetLineSpeed: Double; virtual; // 线速度 function OpenCom(SerialPortDllFileName: string; PortId: Integer): Integer; virtual; function CloseCom: Integer; virtual; procedure SetParams(Baud: TBaudRate; StopBit: TStopBits; DataBit: TDataBits; Parity: TParityBits; FlowControl: TFlowControl); virtual; procedure Start; virtual; procedure Stop; virtual; procedure SendCommand; virtual; constructor Create(ComId: Integer); overload; virtual; destructor Destroy; override; published {none} end; implementation constructor TIcs465c_meter.Create(ComId: Integer); begin inherited Create(True); FComId := ComId; FComPort := nil; FSerialPortDllFileName := ''; FCallback := nil; FisOpened := False; FIsCommand := True; FAddr := $0F; FWeight := 0.0; FTotal := 0.0; FSubtotal := 0.0; FFlow := 0.0; FBeltSpeed := 0.0; FLineSpeed := 0.0; //Terminated := True; ReturnValue := 0; FisSynchronize := False; FCriticalSection := TCriticalSection.Create; // 建锁 end; destructor TIcs465c_meter.Destroy; begin try FCriticalSection.Free; except FCriticalSection := nil; end; Stop; // 停止线程 CloseCom; // 关闭串口 inherited Destroy; end; procedure TIcs465c_meter.SetCallBack(CallBack: Pointer); begin FCallback := CallBack; end; procedure TIcs465c_meter.Lock; begin if FCriticalSection <> nil then FCriticalSection.Enter; end; procedure TIcs465c_meter.UnLock; begin if FCriticalSection <> nil then FCriticalSection.Leave; end; function TIcs465c_meter.GetWeight: Double; begin Result := 0; // if not readWeight then Exit; // 读数据 Lock; try Result := FTotal; //FWeight; finally UnLock; end; end; function TIcs465c_meter.GetTotal: Double; begin Result := 0; // if not readWeight then Exit; // 读数据 Lock; try Result := FTotal; //FWeight; finally UnLock; end; end; function TIcs465c_meter.GetSubTotal: Double; begin Result := 0; // if not readWeight then Exit; // 读数据 Lock; try Result := FSubTotal; //FWeight; finally UnLock; end; end; function TIcs465c_meter.GetBeltSpeed: Double; begin Result := 0; // if not readWeight then Exit; // 读数据 Lock; try Result := FBeltSpeed; //FWeight; finally UnLock; end; end; function TIcs465c_meter.GetLineSpeed: Double; begin Result := 0; // if not readWeight then Exit; // 读数据 Lock; try Result := FLineSpeed; //FWeight; finally UnLock; end; end; function TIcs465c_meter.OpenCom(SerialPortDllFileName: string; PortId: Integer): Integer; begin if FComPort = nil then begin FComPort := TComPort.Create(SerialPortDllFileName, ComId); end; Result := FComPort.OpenPort; FisOpened := True; //FComPort end; function TIcs465c_meter.CloseCom: Integer; begin Result := 0; if FComPort <> nil then begin try Result := FComPort.ClosePort; finally try FComPort.Free; finally FComPort := nil; end; end; end; FisOpened := False; end; procedure TIcs465c_meter.SetParams(Baud: TBaudRate; StopBit: TStopBits; DataBit: TDataBits; Parity: TParityBits; FlowControl: TFlowControl); begin if FComPort <> nil then begin FComPort.SetPortParams(Baud, StopBit, DataBit, Parity, FlowControl); end; end; procedure TIcs465c_meter.Start; begin //if Terminated = True then //begin if Suspended then Resume; //Execute; //end; end; procedure TIcs465c_meter.Stop; begin if not Suspended then Self.Suspend; //if not Terminated then //begin // Terminate; // WaitFor; // end; // Self.WaitFor; end; (* function TIcs465c_meter.GetDecimalMultiply(StatusByteA: Byte): Double; begin Result := 1.0; end; function TIcs465c_meter.TestIsGross(StatusByteB : Byte): Boolean; begin Result := False; end; function TIcs465c_meter.GetSign(StatusByteB : Byte): Double; begin Result := 1.0; end; function TIcs465c_meter.TestIsOverLoad(StatusByteB: Byte): Boolean; begin Result := False; end; *) procedure TIcs465c_meter.SetAddr(Address: Integer); begin FAddr := Address and $FF; end; function TIcs465c_meter.GetDecimalPointFactor(DecimalCount: Byte): Double; var decimal_point_pos: Integer; begin decimal_point_pos := (DecimalCount and $FF); case decimal_point_pos of 7: Result := 10000000; 6: Result := 1000000; 5: Result := 100000; 4: Result := 10000; 3: Result := 1000; 2: Result := 100; 1: Result := 10; 0: Result := 1; else Result := 1.0; end; end; function TIcs465c_meter.GetWeightInternal(var buffer; Pos, size: Integer): Double; type TArray = array[1..255] of Byte; var Factor: Double; intTemp: Cardinal; //Integer; begin if size = 5 then begin Factor := GetDecimalPointFactor(TArray(buffer)[Pos]); Inc(Pos); end else Factor := 1000000.0; intTemp := Cardinal(TArray(buffer)[pos]) + ((Cardinal(TArray(buffer)[pos + 1]) shl 8) and $0000FF00) + ((Cardinal(TArray(buffer)[pos + 2]) shl 16) and $00FF0000) + ((Cardinal(TArray(buffer)[pos + 3]) shl 24) and $FF000000); Result := intTemp / Factor; end; procedure TIcs465c_meter.SendCommand; var buffer: array[1..6] of Byte; begin buffer[1] := (FAddr and $FF); buffer[2] := $AA; buffer[3] := $01; buffer[4] := $00; buffer[5] := $A4; buffer[6] := $00; if FComPort <> nil then begin try FComPort.WritePort(buffer, 5); except // end; end; end; function TIcs465c_meter.readWeight: Boolean; const DataLength: Integer = 22; PackageLength: Integer = 22 + 5; PackageTailPos: Integer = 22 + 5; PackageReadLength: Integer = 2; //22+5-1; var isSTX, {isCR,} isFound: Boolean; i, n, m, p, k: Integer; xorSum, intDataLength: Integer; buffer: array[1..255] of Byte; //decimal_point_factor : Double; //decimal_multiply : Double; /////// //pBuffer : ^Byte; // Pointer for byte //sign: Double; //aWeight, aTare : array[1..8] of Byte; //strWeight, strTare: String; // fltWeight, fltTare: Double; begin Result := False; // FWeight := 0.0; // FTotal := 0.0; // FSubTotal := 0.0; // FFlow := 0.0; // FBeltSpeed := 0.0; // FLineSpeed := 0.0; if FComport = nil then Exit; FComport.ClearBuffer(1); // 清空串口对象接收缓冲区 //// if FIsCommand then // 是否命令方式 begin SendCommand; Sleep(100); end; //FComport.ClearBuffer(1); // 清空串口对象接收缓冲区 FillChar(buffer, 255, 0); isSTX := False; //isCR := False; isFound := False; //n := 1; p := 1; k := 0; while isSTX = False do // loop begin //pBuffer := @buffer[p]; //n := FComport.ReadPort(pBuffer, 2); // 前2字节 n := FComport.ReadPort(Buffer, PackageReadLength); // 前2字节 if n = 0 then begin //Exit; // 没有读到数据 sleep(100); Inc(k); if k < 5 then continue // 5次重试 else break; end; xorSum := 0; if ((buffer[p] = FAddr) and (buffer[p + 1] = $AA)) then // 找头标志 begin isSTX := True; xorSum := xorSum xor buffer[p]; // 计算较验 xorSum := xorSum xor buffer[p + 1]; // 计算较验 p := p + PackageReadLength; //+2; // 第3字节开始 while isFound = False do begin m := p - 1; while m < PackageLength do // loop begin //pBuffer := @buffer[p]; //n := FComport.ReadPort(pBuffer, PackageLength-m); n := FComport.ReadPort(Buffer[p], PackageLength - m); if n = 0 then begin Exit; // 没有读到数据 end; Inc(m, n); p := m + 1; // 缓冲区下一次写入位置 end; // loop 读数 k := p - PackageLength - 1; // 包头位置 for i := 3 to (PackageLength - 1) do // 跳过包尾标志(较验值) xorSum := xorSum xor buffer[k + i]; // 计算较验和 if buffer[k + PackageTailPos] = xorSum then // 找尾标志 begin isFound := True; Break; // 找到数据 end else begin //n := p+m; isSTX := False; for i := 2 {p} to PackageLength {n} do begin if (buffer[i] = FAddr) and (buffer[i + 1] = $AA) then // 找头标志 begin p := i; m := PackageLength - i + 1; //n - i - 1; isSTX := True; isFound := False; break; // 继续读取后续数据 end; end; if isSTX then // 找到第2个标头 begin //memmove 将剩余部分前移 for i := 1 to m do begin buffer[i] := buffer[p + i - 1]; end; fillChar(buffer[m + 1], PackageLength - m, 0); // 清空 p := m + 1; continue; // 重新读取 end else begin Exit; // 读到的数据无用 end; end; end; // isFound end; end; // isSTX if isFound then begin if buffer[3] <> $01 then // 功能号是否正确 begin FTotal := 0; FSubtotal := 0; FFlow := 0; FBeltSpeed := 0; FLineSpeed := 0; Exit; // 数据错误 end; intDataLength := Integer(buffer[4]); //if intDataLength <> 22 then // 数据长度不对 //begin // Exit; // 数据错误 //end; //decimal_multiply := GetDecimalMultiply(buffer[2]); //FIsGross ////////// Lock; // 上锁 try FTotal := GetWeightInternal(buffer, 5, 5); FSubtotal := GetWeightInternal(buffer, 10, 5); FFlow := GetWeightInternal(buffer, 15, 4); FBeltSpeed := GetWeightInternal(buffer, 19, 4); FLineSpeed := GetWeightInternal(buffer, 23, 4); finally Unlock; end; //Weight := FloatToStr(fltWeight); // 毛重或净重 //Tare := FloatToStr(fltTare); // 皮重 Result := True; end else begin FTotal := 0; FSubtotal := 0; FFlow := 0; FBeltSpeed := 0; FLineSpeed := 0; end; end; function TIcs465c_meter.IsOverLoad: Boolean; begin Result := False; end; function TIcs465c_meter.IsGross: Boolean; begin Result := False; end; procedure TIcs465c_meter.ShowData; begin if FCallback <> nil then begin try TWeighingCallBack(FCallback) (FTotal, FSubtotal, isGross, isOverLoad); except { none } end; end; end; procedure TIcs465c_meter.Execute; var // Weight, Tare: Double; isOK: Boolean; begin while not Terminated do begin isOK := readWeight; if isOK then begin if FCallback <> nil then begin Lock; try ShowData; finally Unlock; end; end; end; sleep(300); end; end; end.
{$I-,Q-,R-,S-} {49¦ Las Torres Gemelas. México 2006 ---------------------------------------------------------------------- Habia una vez, en un antiguo Imperio, dos torres de formas similares en dos ciudades diferentes. Las torres estaban construidas por losas circulares puestas unas sobre las otras. Cada una de las losas era de la misma altura y tenian radio completo. Sin embargo, no es sorprendente que las dos torres fueran de forma diferente, ellas tenían muchas losas en comun. Sin embargo, mas de mil años después que ellas fueron construidas, el Emperador ordenó a sus arquitectos eliminar algunas de las losas de las dos torres tal que ellas tengan la misma forma y tamaño, y al mismo tiempo permanezcan tal altas como sea posible. El orden de las losas en la nueva torre tiene que ser el mismo que ellas tenian en la torre original. El emperador pensó que, de esta manera las dos torres serían el simbolo de armonia e igualdad entre las dos ciudades. El decidió nombrarlas a ellas las Torres Gemelas Ahora, alrededor de dos mil años después, a usted se le reta con un simple problema de aplanamiento: dada la descripción de dos torres diferentes a usted se le pide solamente encontrar el número de losas en la más alta de las torres gemelas que puede ser construida desde ellas. Entrada El fichero de entrada TOWER.IN contiene en la primera línea dos enteros N1 y N2 (1 <= N1, N2 <= 1000) indicando el numero de losas respectivamente en las dos torres. La segunda linea contiene N1 enteros positivos los que representan el radio de las losas (de arriba hacia debajo) en la primera torre. La tercera linea contiene N2 enteros positivos los que representan el radio de las losas (de arriba hacia debajo) en la segunda torre. Salida El fichero de entrada TOWER.OUT el número de losas en la torre (en una torre) en la posible torre gemela más alta que puede ser construida de ella. Ejemplo de Entrada y de Salida Ejemplo # 1 +----------------------+ +------------+ ¦ TOWER.IN ¦ ¦ TOWER.OUT ¦ +----------------------¦ +------------¦ ¦ 7 6 ¦ ¦ 4 ¦ ¦ 20 15 10 15 25 20 15 ¦ +------------+ ¦ 15 25 10 20 15 20 ¦ +----------------------+ Ejemplo # 2 +----------------------------+ +-----------+ ¦ TOWER.IN ¦ ¦ TOWER.OUT ¦ +----------------------------¦ +-----------¦ ¦ 8 9 ¦ ¦ 6 ¦ ¦ 10 20 20 10 20 10 20 10 ¦ +-----------+ ¦ 20 10 20 10 10 20 10 10 20 ¦ +----------------------------+ } const mx = 1001; var fe,fs : text; n,m,sol : longint; tab : array[1..mx,1..2] of longint; best : array[boolean,0..mx] of longint; procedure open; var i : longint; begin assign(fe,'tower.in'); reset(fe); assign(fs,'tower.out'); rewrite(fs); readln(fe,n,m); for i:=1 to n do read(fe,tab[i,1]); readln(fe); for i:=1 to m do read(fe,tab[i,2]); close(fe); end; procedure work; var i,j : longint; ok : boolean; begin ok:=false; for i:=1 to n do begin ok:=not ok; for j:=1 to m do begin if (tab[i,1] = tab[j,2]) then best[ok,j]:=best[not ok,j-1] + 1 else if best[ok,j-1] > best[not ok,j] then best[ok,j]:=best[ok,j-1] else best[ok,j]:=best[not ok,j]; end; end; sol:=best[ok,m]; end; procedure closer; begin writeln(fs,sol); close(fs); end; begin open; work; closer; end.
{ Lua4Lazalus ActiveXObject License: New BSD Copyright(c)2010- Malcome@Japan All rights reserved. Note: The property name is case insensitive, but the function name is case sensitive. Then, you may use the property name with the small letter if ActiveXObject has same name in property and function name. ex. excel.Visible = true; excel.Visible(); ---> ERROR! excel.visible = true; excel.Visible(); ---> OK! ToDo: Event handling. Version History: 1.52.0 by Malcome Japan. (with Lazarus 1.3 and FPC 2.6.2) 1.0.0 by Malcome Japan. (with Lazarus 0.9.29 and FPC 2.4.1) License for Lua 5.0 and later versions: Copyright(c)1994–2008 Lua.org, PUC-Rio. } unit l4l_activex; {$mode objfpc}{$H+} interface uses Classes, SysUtils, lua52; function CreateActiveXObject(L : Plua_State) : Integer; cdecl; implementation uses Windows, ComObj, ActiveX, variants, varutils; const FIELD_ID = '___IDispatch___'; FIELD_FN = '___FuncName___'; FIELD_IC = '___IteCount___'; procedure DoCreateActiveXObject(L : Plua_State; id: IDispatch); forward; procedure ChkErr(L : Plua_State; Val: HResult; const prop: string=''); var s: string; begin if not(Succeeded(Val)) then begin s:= Format('ActiveX Error(%x)', [Val]); if prop <> '' then s := s + ' in "' + prop + '".'; luaL_error(L, PChar(s)); end; end; function Index(L : Plua_State) : Integer; cdecl; var p: PPointer; key: string; s: string; ws: WideString; id: IDispatch; di: TDispID; param: TDispParams; ret: OleVariant; begin Result := 0; lua_getfield(L, 1, FIELD_ID); p:= lua_touserdata(L, -1); id:= IDispatch(p^); lua_pop(L, 1); key := lua_tostring(L, 2); ws:= UTF8Decode(key); ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), key); param.rgvarg := nil; param.rgdispidNamedArgs := nil; param.cArgs := 0; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); ChkErr(L, id.Invoke(di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET, param, @ret, nil, nil), key); case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varByte: lua_pushinteger(L, ret); varSingle,varDouble: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: DoCreateActiveXObject(L, ret); else begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, PChar(s)); end; end; Result := 1; end; function NewIndex(L : Plua_State) : Integer; cdecl; var p: PPointer; key: string; ws: WideString; id: IDispatch; di, diput: TDispID; param: TDispParams; v: OleVariant; begin Result:=0; lua_getfield(L, 1, FIELD_ID); p:= lua_touserdata(L, -1); id:= IDispatch(p^); lua_pop(L, 1); key := lua_tostring(L, 2); ws:= UTF8Decode(key); ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), key); case lua_type(L, 3) of LUA_TNIL: VariantInit(TVarData({%H-}v)); LUA_TBOOLEAN: v := lua_toboolean(L, 3); LUA_TNUMBER: v := lua_tonumber(L, 3); else v := lua_tostring(L, 3); end; diput := DISPID_PROPERTYPUT; param.rgvarg := @v; param.cArgs := 1; param.rgdispidNamedArgs := @diput; param.cNamedArgs := 1; ChkErr(L, id.Invoke(di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYPUT, param, nil, nil, nil), key); end; function call(L : Plua_State) : Integer; cdecl; var i, c, t: integer; p: PPointer; id: IDispatch; di: TDispID; s, func: string; ws: WideString; arglist, pp: {$IFDEF VER2_4}lPVariantArg{$ELSE}PVariantArg{$ENDIF}; param: TDispParams; v, ret: OleVariant; begin Result:= 0; c:= lua_gettop(L); t:= 1; if lua_istable(L, 2) then Inc(t); { it's x:x() } lua_getfield(L, 1, FIELD_ID); p:= lua_touserdata(L, -1); id:= IDispatch(p^); lua_pop(L, 1); lua_getfield(L, 1, FIELD_FN); func:= lua_tostring(L, -1); lua_pop(L, 1); ws:= UTF8Decode(func); ChkErr(L, id.GetIDsOfNames(GUID_NULL, @ws, 1, GetUserDefaultLCID, @di), func); GetMem(arglist, SizeOf({$IFDEF VER2_4}VariantArg{$ELSE}TVariantArg{$ENDIF}) * (c-t)); try // 逆順で pp := arglist; for i := c downto t+1 do begin VariantInit(TVarData({%H-}v)); case lua_type(L, i) of LUA_TBOOLEAN: v := lua_toboolean(L, i); LUA_TNUMBER: v := lua_tonumber(L, i); LUA_TSTRING: v := lua_tostring(L, i); end; VariantInit(TVarData(pp^)); pp^ := {$IFDEF VER2_4}VariantArg{$ELSE}TVariantArg{$ENDIF}(v); Inc(pp); end; param.cArgs := c - t; {$IFDEF VER2_4} param.rgvarg := arglist; {$ELSE} param.rgvarg := PVariantArgList(arglist); {$ENDIF} param.rgdispidNamedArgs := nil; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); ChkErr(L, id.Invoke( di, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET or DISPATCH_METHOD, param, @ret, nil, nil), func); case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varByte: lua_pushinteger(L, ret); varSingle,varDouble: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: DoCreateActiveXObject(L, ret); else begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, PChar(s)); end; end; Result := 1; finally FreeMem(arglist); end; end; function iterator(L : Plua_State) : Integer; cdecl; var i: integer; p: PPointer; id: IDispatch; s: string; ws: WideString; param: TDispParams; v, ret: OleVariant; begin Result:= 0; lua_getfield(L, 1, FIELD_ID); p:= lua_touserdata(L, -1); id:= IDispatch(p^); lua_pop(L, 1); if lua_isnil(L, 3) then begin i := 0; end else begin lua_pushstring(L, FIELD_IC); lua_rawget(L, 1); i:= lua_tointeger(L, -1) + 1; end; lua_pushstring(L, FIELD_IC); lua_pushinteger(L, i); lua_rawset(L, 1); VariantInit(TVarData({%H-}v)); v := i; param.cArgs := 1; param.rgvarg := @v; param.rgdispidNamedArgs := nil; param.cNamedArgs := 0; VariantInit(TVarData({%H-}ret)); if id.Invoke( DISPID_VALUE, GUID_NULL, GetUserDefaultLCID, DISPATCH_PROPERTYGET or DISPATCH_METHOD, param, @ret, nil, nil) = 0 then begin case VarType(ret) of varNull: lua_pushnil(L); varSmallint,varInteger,varByte: lua_pushinteger(L, ret); varSingle,varDouble: lua_pushnumber(L, ret); varBoolean: lua_pushboolean(L, ret); varDispatch: begin if TVarData(ret).vdispatch <> nil then begin DoCreateActiveXObject(L, ret); end else begin lua_pushnil(L); end; end; else begin ws := ret; s := UTF8Encode(ws); lua_pushstring(L, PChar(s)); end; end; end else begin lua_pushnil(L); end; Result := 1; end; function gc(L : Plua_State) : Integer; cdecl; var p: PPointer; begin p:= lua_touserdata(L, 1); IDispatch(p^)._Release; //IDispatch(p^):= nil; //IDispatch(p^):= Unassigned; Result:= 0; end; procedure DoCreateActiveXObject(L : Plua_State; id: IDispatch); var i, t: integer; p: PPointer; s: string; ws: WideString; ti: ITypeInfo; ta: lPTypeAttr; fd: lPFuncDesc; begin id._AddRef; lua_newtable(L); t:= lua_gettop(L); lua_pushstring(L, FIELD_ID); p:= lua_newuserdata(L, SizeOf(IDispatch)); p^:=id; if lua_getmetatable(L, -1) = 0 then lua_newtable(L); lua_pushstring(L, '__gc'); lua_pushcfunction(L, @gc); lua_settable(L, -3); lua_setmetatable(L, -2); lua_settable(L, -3); ChkErr(L, id.GetTypeInfo(0, 0, ti)); if ti = nil then Exit; ti._AddRef; try ChkErr(L, ti.GetTypeAttr(ta)); try for i := 0 to ta^.cFuncs - 1 do begin ChkErr(L, ti.GetFuncDesc(i, fd)); try ChkErr(L, ti.GetDocumentation(fd^.memid, @ws, nil, nil, nil)); s := UTF8Encode(ws); ws:= ''; lua_pushstring(L, PChar(s)); lua_newtable(L); lua_pushstring(L, FIELD_FN); lua_pushstring(L, PChar(s)); lua_settable(L, -3); lua_newtable(L); lua_pushstring(L, '__call'); lua_pushcfunction(L, @call); lua_settable(L, -3); lua_pushstring(L, '__index'); lua_pushvalue(L, t); // SuperClass lua_settable(L, -3); lua_setmetatable(L, -2); lua_settable(L, -3); finally ti.ReleaseFuncDesc(fd); end; end; finally ti.ReleaseTypeAttr(ta); end; finally ti._Release; ti:= Unassigned; end; lua_newtable(L); lua_pushstring(L, '__newindex'); lua_pushcfunction(L, @NewIndex); lua_settable(L, -3); lua_pushstring(L, '__index'); lua_pushcfunction(L, @Index); lua_settable(L, -3); lua_pushstring(L, '__call'); lua_pushcfunction(L, @iterator); lua_settable(L, -3); lua_setmetatable(L, -2); end; function CreateActiveXObject(L : Plua_State) : Integer; cdecl; begin DoCreateActiveXObject(L, CreateOleObject(lua_tostring(L, 1))); Result := 1; end; end.
(* * FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * *) unit uinifile; {$mode objfpc}{$H+} interface uses inifiles, SysUtils, graphics, LCLIntf, LCLType, Forms, FileUtil; const sINIFILE = DirectorySeparator+'fpg-editor.ini'; sDEFAULT_LNG = DirectorySeparator+'lng'+DirectorySeparator+'Spanish.ini'; sMAIN = 'FPG'; sFONT = 'FNT'; sSIZE_OF_ICON = 'Size of icon'; sAUTOLOAD_IMAGES = 'Autoload images'; sRELOAD_REMOVE = 'Reload remove images'; sVIEW_FLAT = 'Show flat'; sVIEW_SPLASH = 'Show SPLASH screen'; sCOLOR_POINTS = 'Color points'; sIMAGES_PAINT = 'Number of images to repaint'; sANIMATE_DELAY = 'Animate delay'; sLANGUAGE = 'Language'; sEDIT_PROGRAM = 'External edit program'; sBG_COLOR = 'Background Color'; sBG_COLOR_FPG = 'FPG Background Color'; var inifile_program_edit : string; inifile_language : string; inifile_autoload_images, inifile_autoload_remove, inifile_show_splash, inifile_show_flat : boolean; inifile_sizeof_icon, inifile_repaint_number, inifile_color_points, inifile_animate_delay : longint; inifile_bg_color : TColor; inifile_bg_colorFPG : TColor; inifile_charset_to_gen, inifile_fnt_charset, inifile_fnt_height, inifile_fnt_size, inifile_fnt_effects : longint; inifile_fnt_name : string; inifile_symbol_type, inifile_edge_size, inifile_shadow_pos, inifile_shadow_offset, inifile_fnt_color, inifile_edge_color, inifile_shadow_color, inifile_bgcolor : longint; inifile_fnt_image, inifile_edge_image, inifile_shadow_image : string; inifile_admin_tools: Integer; alpha_font, alpha_edge,alpha_shadow :integer; procedure load_inifile; procedure write_inifile; procedure inifile_load_font( var nFnt : TFont ); implementation procedure inifile_load_font( var nFnt : TFont ); var lf: LOGFONT; // Windows native font structure begin FillChar(lf, SizeOf(lf), Byte(0)); lf.lfHeight := inifile_fnt_height; lf.lfCharSet := inifile_fnt_charset; StrCopy(lf.lfFaceName, PChar(inifile_fnt_name)); nFnt.Handle := CreateFontIndirect(lf); end; procedure load_inifile; var inifile : TIniFile; strinifile : string; begin strinifile := ExtractFileDir( ParamStr(0) ) + sINIFILE; if not FileExistsUTF8(strinifile) { *Converted from FileExists* } then begin inifile_sizeof_icon := 50; inifile_autoload_images := true; inifile_autoload_remove := false; inifile_color_points := clBlack; inifile_repaint_number := 20; inifile_animate_delay := 100; inifile_language := ExtractFileDir(Application.ExeName) + sDEFAULT_LNG; inifile_program_edit := ExtractFileDir( ParamStr(0) ) + DirectorySeparator+'myprogram.exe'; inifile_show_flat := true; inifile_show_splash := true; inifile_bg_color := clWhite; inifile_bg_colorFPG := clWhite; inifile_fnt_charset := DEFAULT_CHARSET; inifile_charset_to_gen := 0; inifile_fnt_height := -11; inifile_fnt_effects := 0; // 0-Normal 1-Negrita 2-Subrayado 3-Tachado inifile_fnt_size := 8; inifile_fnt_name := 'Arial'; inifile_symbol_type := 15; //1+2+4+8 inifile_edge_size := 0; inifile_shadow_pos := 8; //123 4-5 678 inifile_shadow_offset := 0; inifile_fnt_color := clWhite; inifile_edge_color := clBlue; inifile_shadow_color := 8; inifile_bgcolor := clBtnFace; inifile_fnt_image := ''; inifile_edge_image := ''; inifile_shadow_image := ''; inifile_admin_tools := 0; write_inifile; end else begin inifile := TIniFile.Create(strinifile); inifile_sizeof_icon := inifile.ReadInteger( sMAIN, sSIZE_OF_ICON , 50); inifile_autoload_images := inifile.ReadBool ( sMAIN, sAUTOLOAD_IMAGES, true); inifile_autoload_remove := inifile.ReadBool ( sMAIN, sRELOAD_REMOVE , false); inifile_show_flat := inifile.ReadBool ( sMAIN, sVIEW_FLAT , false); inifile_show_splash := inifile.ReadBool ( sMAIN, sVIEW_SPLASH , false); inifile_color_points := inifile.ReadInteger( sMAIN, sCOLOR_POINTS , 0); inifile_repaint_number := inifile.ReadInteger( sMAIN, sIMAGES_PAINT , 20); inifile_animate_delay := inifile.ReadInteger( sMAIN, sANIMATE_DELAY , 100); inifile_language := inifile.ReadString ( sMAIN, sLANGUAGE , ExtractFileDir(Application.ExeName) + sDEFAULT_LNG); inifile_program_edit := inifile.ReadString ( sMAIN, sEDIT_PROGRAM , ExtractFileDir(ParamStr(0)) + DirectorySeparator+'myprogram.exe'); inifile_bg_color := inifile.ReadInteger( sMAIN, sBG_COLOR , clWhite); inifile_bg_colorFPG := inifile.ReadInteger( sMAIN, sBG_COLOR_FPG , clWhite); inifile_admin_tools := inifile.ReadInteger(sMAIN, 'ADMIN TOOLS', 0); inifile_fnt_charset := inifile.ReadInteger(sFONT, 'CHARSET', DEFAULT_CHARSET); inifile_charset_to_gen:= inifile.ReadInteger(sFONT, 'CHARSET TO GEN', 0); inifile_fnt_height := inifile.ReadInteger(sFONT, 'HEIGHT' , -11); inifile_fnt_size := inifile.ReadInteger(sFONT, 'SIZE' , 8); inifile_fnt_effects := inifile.ReadInteger(sFONT, 'EFFECTS', 0); inifile_fnt_name := inifile.ReadString (sFONT, 'NAME', 'Arial'); inifile_symbol_type := inifile.ReadInteger(sFONT, 'SYMBOL TYPE', 15); inifile_edge_size := inifile.ReadInteger(sFONT, 'EDGE SIZE', 0); inifile_shadow_pos := inifile.ReadInteger(sFONT, 'SHADOW POSITION', 0); inifile_shadow_offset := inifile.ReadInteger(sFONT, 'SHADOW OFFSET', 0); inifile_fnt_color := inifile.ReadInteger(sFONT, 'FONT COLOR', clWhite); inifile_edge_color := inifile.ReadInteger(sFONT, 'EDGE COLOR', clBlue); inifile_shadow_color := inifile.ReadInteger(sFONT, 'SHADOW COLOR', 8); inifile_bgcolor := inifile.ReadInteger(sFONT, 'BACKGROUND COLOR', clBtnFace); inifile_fnt_image := inifile.ReadString (sFONT, 'FONT IMAGE' , ''); inifile_edge_image := inifile.ReadString (sFONT, 'EDGE IMAGE' , ''); inifile_shadow_image := inifile.ReadString (sFONT, 'SHADOW IMAGE', ''); inifile.Destroy; end; end; procedure write_inifile; var inifile : TIniFile; strinifile : String; begin strinifile := ExtractFileDir( ParamStr(0) ) + sINIFILE; inifile := TIniFile.Create(strinifile); inifile.WriteInteger( sMAIN, sSIZE_OF_ICON , inifile_sizeof_icon); inifile.WriteBool ( sMAIN, sAUTOLOAD_IMAGES, inifile_autoload_images); inifile.WriteBool ( sMAIN, sRELOAD_REMOVE , inifile_autoload_remove); inifile.WriteBool ( sMAIN, sVIEW_FLAT , inifile_show_flat); inifile.WriteBool ( sMAIN, sVIEW_SPLASH , inifile_show_splash); inifile.WriteInteger( sMAIN, sCOLOR_POINTS , inifile_color_points); inifile.WriteInteger( sMAIN, sIMAGES_PAINT , inifile_repaint_number); inifile.WriteInteger( sMAIN, sANIMATE_DELAY , inifile_animate_delay); inifile.WriteString ( sMAIN, sLANGUAGE , inifile_language); inifile.WriteString ( sMAIN, sEDIT_PROGRAM , inifile_program_edit); inifile.WriteInteger( sMAIN, sBG_COLOR , inifile_bg_color); inifile.WriteInteger( sMAIN, sBG_COLOR_FPG , inifile_bg_colorFPG); inifile.WriteInteger (sMAIN, 'ADMIN TOOLS', inifile_admin_tools); inifile.WriteInteger(sFONT, 'CHARSET', inifile_fnt_charset); inifile.WriteInteger(sFONT, 'CHARSET TO GEN', inifile_charset_to_gen); inifile.WriteInteger(sFONT, 'HEIGHT' , inifile_fnt_height); inifile.WriteInteger(sFONT, 'SIZE' , inifile_fnt_size); inifile.WriteInteger(sFONT, 'EFFECTS', inifile_fnt_effects); inifile.WriteString (sFONT, 'NAME' , inifile_fnt_name); inifile.WriteInteger(sFONT, 'SYMBOL TYPE', inifile_symbol_type); inifile.WriteInteger(sFONT, 'EDGE SIZE' , inifile_edge_size); inifile.WriteInteger(sFONT, 'SHADOW POSITION', inifile_shadow_pos); inifile.WriteInteger(sFONT, 'SHADOW OFFSET' , inifile_shadow_offset); inifile.WriteInteger(sFONT, 'FONT COLOR', inifile_fnt_color); inifile.WriteInteger(sFONT, 'EDGE COLOR', inifile_edge_color); inifile.WriteInteger(sFONT, 'SHADOW COLOR', inifile_shadow_color); inifile.WriteInteger(sFONT, 'BACKGROUND COLOR', inifile_bgcolor); inifile.WriteString (sFONT, 'FONT IMAGE' , inifile_fnt_image); inifile.WriteString (sFONT, 'EDGE IMAGE' , inifile_edge_image); inifile.WriteString (sFONT, 'SHADOW IMAGE', inifile_shadow_image); inifile.Destroy; end; end.
unit ini_type_place_FORM; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, pFIBDatabase, Buttons, ToolWin, ComCtrls, ExtCtrls, FIBQuery, FIBDataSet, pFIBDataSet, pFIBStoredProc, ActnList, Menus, COMMON, Grids, Db, DBGrids, pFIBQuery, StdCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxContainer, cxTextEdit, ImgList, FIBDatabase, Ibase, Variants, dxBar, dxBarExtItems, cxTL; type TFini_type_place = class(TForm) DataSource: TDataSource; DataSet: TpFIBDataSet; StoredProc: TpFIBStoredProc; ActionList1: TActionList; Action_Add: TAction; Action_Del: TAction; Action_Mod: TAction; Action_Refresh: TAction; Action_Up: TAction; Action_Down: TAction; Action_Sel: TAction; Action_Exit: TAction; cxGrid1: TcxGrid; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1DBTableView1ID_TYPE_PLACE: TcxGridDBColumn; cxGrid1DBTableView1NAME_FULL: TcxGridDBColumn; cxGrid1DBTableView1NAME_SHORT: TcxGridDBColumn; cxGrid1DBTableView1ORDER: TcxGridDBColumn; SmallImages: TImageList; WorkDatabase: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; dxBarManager1: TdxBarManager; AddButton: TdxBarLargeButton; UpdateButton: TdxBarLargeButton; DelButton: TdxBarLargeButton; ChooseButton: TdxBarLargeButton; RefreshButton: TdxBarLargeButton; CloseButton: TdxBarLargeButton; DownButton: TdxBarLargeButton; UpButton: TdxBarLargeButton; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyle18: TcxStyle; cxStyle19: TcxStyle; cxStyle20: TcxStyle; cxStyle21: TcxStyle; cxStyle22: TcxStyle; cxStyle23: TcxStyle; cxStyle24: TcxStyle; cxStyle25: TcxStyle; cxStyle26: TcxStyle; cxStyle27: TcxStyle; cxStyle28: TcxStyle; cxStyle29: TcxStyle; cxStyle30: TcxStyle; cxStyle31: TcxStyle; cxStyle32: TcxStyle; cxStyle33: TcxStyle; cxStyle34: TcxStyle; cxStyle35: TcxStyle; cxStyle36: TcxStyle; cxStyle37: TcxStyle; cxStyle38: TcxStyle; cxStyle39: TcxStyle; cxStyle40: TcxStyle; cxStyle41: TcxStyle; cxStyle42: TcxStyle; TreeListStyleSheetDevExpress: TcxTreeListStyleSheet; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; procedure ExitButtonClick(Sender: TObject); procedure AddButtonClick(Sender: TObject); procedure ModButtonClick(Sender: TObject); procedure DelButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure DataSetAfterScroll(DataSet: TDataSet); procedure DownButtonClick(Sender: TObject); procedure UpButtonClick(Sender: TObject); procedure Action_AddExecute(Sender: TObject); procedure Action_DelExecute(Sender: TObject); procedure Action_ModExecute(Sender: TObject); procedure Action_RefreshExecute(Sender: TObject); procedure Action_DownExecute(Sender: TObject); procedure Action_UpExecute(Sender: TObject); procedure Action_SelExecute(Sender: TObject); procedure Action_ExitExecute(Sender: TObject); procedure SelButtonClick(Sender: TObject); procedure PM_AddButtonClick(Sender: TObject); procedure PM_DelButtonClick(Sender: TObject); procedure PM_ModButtonClick(Sender: TObject); procedure PM_RefreshButtonClick(Sender: TObject); procedure PM_DownButtonClick(Sender: TObject); procedure PM_UpButtonClick(Sender: TObject); procedure PM_SelButtonClick(Sender: TObject); procedure PM_ExitButtonClick(Sender: TObject); procedure DBGridDblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SearchEditKeyPress(Sender: TObject; var Key: Char); procedure cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); procedure CloseButtonClick(Sender: TObject); public CurFS:TFormStyle; ActualDate:TDateTime; ResultValue:Variant; constructor Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle; ActualDate:TDateTime);overload; procedure CheckButtonsState; procedure SelectAll; procedure LocateRecord(const id : integer); end; function GetIniTypePlace(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant;stdcall; exports GetIniTypePlace; implementation uses BaseTypes, ini_type_place_FORM_ADD; {$R *.DFM} function GetIniTypePlace(AOwner : TComponent; DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle;ActualDate:TDateTime):Variant; var T:TFini_type_place; Res:Variant; begin If FS=fsNormal then begin T:=TFini_type_place.Create(AOwner, DBHANDLE,FS,ActualDate); if T.ShowModal=mrYes then begin Res:=T.ResultValue; end; T.Free; end else begin T:=TFini_type_place.Create(AOwner, DBHANDLE,FS,ActualDate); Res:=NULL; end; GetIniTypePlace:=Res; end; constructor TFini_type_place.Create(AOwner:TComponent;DBHANDLE : TISC_DB_HANDLE; FS:TFormStyle; ActualDate:TDateTime); begin inherited Create(AOwner); Self.WorkDatabase.Handle:=DBHAndle; self.ActualDate:=ActualDate; CurFS:=FS; if CurFS=fsNormal then ChooseButton.Enabled:=true; DataSet.SQLs.SelectSQL.Text := 'select * from VIEW_INI_TYPE_PLACE ORDER BY "ORDER"'; DataSet.Open; self.FormStyle:=FS; end; procedure TFini_type_place.SelectAll; begin DataSet.Active := false; DataSet.SQLs.SelectSQL.Text := 'select * from VIEW_INI_TYPE_PLACE ORDER BY "ORDER"'; DataSet.Active := true; CheckButtonsState; end; //Add record procedure TFini_type_place.AddButtonClick(Sender: TObject); var add_form : Tfini_type_place_form_add; id_type_place : integer; full_name, short_name : string; begin add_form := Tfini_type_place_form_add.Create(Self); add_form.Caption := 'Добавить'; if add_form.ShowModal = mrOK then begin full_name := add_form.FullNameEdit.Text; short_name := add_form.ShortNameEdit.Text; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PUB_INI_TYPE_PLACE_ADD', [full_name, short_name]); id_type_place:=StoredProc.ParamByName('ID_TYPE_PLACE').AsInteger; StoredProc.Transaction.Commit; SelectAll; LocateRecord(id_type_place); end; add_form.Free; end; //Modify record procedure TFini_type_place.ModButtonClick(Sender: TObject); var mod_form : Tfini_type_place_form_add; id_type_place : integer; full_name, short_name : string; begin id_type_place := DataSet['ID_TYPE_PLACE']; full_name := DataSet['NAME_FULL']; short_name := DataSet['NAME_SHORT']; mod_form := Tfini_type_place_form_add.Create(Self); mod_form.Caption := 'Изменить'; mod_form.FullNameEdit.Text := full_name; mod_form.ShortNameEdit.Text := short_name; if mod_form.ShowModal = mrOK then begin full_name := mod_form.FullNameEdit.Text; short_name := mod_form.ShortNameEdit.Text; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PUB_INI_TYPE_PLACE_MOD', [id_type_place, full_name, short_name]); StoredProc.Transaction.Commit; SelectAll; LocateRecord(id_type_place); end; mod_form.Free; end; //Delete record procedure TFini_type_place.DelButtonClick(Sender: TObject); var id_type_place : integer; selected_id : integer; begin if agMessageDlg('Увага', DELETE_QUESTION, mtWarning, [mbYes, mbNo]) = mrNo then exit; id_type_place := DataSet['ID_TYPE_PLACE']; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PUB_INI_TYPE_PLACE_DEL', [id_type_place]); StoredProc.Transaction.Commit; selected_id := cxGrid1DBTableView1.Controller.FocusedRowIndex; SelectAll; cxGrid1DBTableView1.Controller.FocusedRowIndex := selected_id; end; //Refresh dbgrid procedure TFini_type_place.RefreshButtonClick(Sender: TObject); var selected_id : integer; begin if DataSet.RecordCount = 0 then begin SelectAll; exit; end; selected_id := DataSet.FieldByName('ID_TYPE_PLACE').AsInteger; SelectAll; DataSet.Locate('ID_TYPE_PLACE', selected_id, [loCaseInsensitive]); end; //Close form procedure TFini_type_place.ExitButtonClick(Sender: TObject); begin if FormStyle = fsMDIChild then Close else ModalResult := mrCancel; end; //Select record procedure TFini_type_place.SelButtonClick(Sender: TObject); begin if DataSet.Active and (dataSet.RecordCount>0) then begin ResultValue:=VarArrayCreate([0,1],varVariant); ResultValue[0]:=DataSet['ID_TYPE_PLACE']; ResultValue[1]:=DataSet['NAME_FULL']; ModalResult := mrYes; end; end; //Move record up procedure TFini_type_place.DownButtonClick(Sender: TObject); var id_type_place : integer; begin id_type_place := DataSet['ID_TYPE_PLACE']; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PUB_INI_TYPE_PLACE_MOVE_UP', [id_type_place]); StoredProc.Transaction.Commit; SelectAll; LocateRecord(id_type_place); end; //Move record down procedure TFini_type_place.UpButtonClick(Sender: TObject); var id_type_place : integer; begin id_type_place := DataSet['ID_TYPE_PLACE']; StoredProc.Transaction.StartTransaction; StoredProc.ExecProcedure('PUB_INI_TYPE_PLACE_MOVE_DOWN', [id_type_place]); StoredProc.Transaction.Commit; SelectAll; LocateRecord(id_type_place); end; ////////////////////////////////////////////////////////////// // Other procedures(database dependent) ////////////////////////////////////////////////////////////// procedure TFini_type_place.LocateRecord(const id : integer); begin DataSet.Locate('ID_TYPE_PLACE', id, []); end; ////////////////////////////////////////////////////////////// // Other procedures(database independent) ////////////////////////////////////////////////////////////// procedure TFini_type_place.CheckButtonsState; begin if DataSet.RecordCount = 0 then begin DelButton.Enabled := false; UpdateButton.Enabled := false; DownButton.Enabled := false; UpButton.Enabled := false; end else begin DelButton.Enabled := true; UpdateButton.Enabled := true; end; end; //Procedure checks up and down buttons accessibility procedure TFini_type_place.DataSetAfterScroll(DataSet: TDataSet); begin if DataSet.RecNo = DataSet.RecordCount then begin DownButton.Enabled := false; end else begin DownButton.Enabled := true; end; if DataSet.RecNo = 1 then begin UpButton.Enabled := false; end else begin UpButton.Enabled := true; end; end; procedure TFini_type_place.DBGridDblClick(Sender: TObject); begin if ChooseButton.Enabled then SelButtonClick(Self); end; ////////////////////////////////////////////////////////////// // Actions procedures ////////////////////////////////////////////////////////////// procedure TFini_type_place.Action_AddExecute(Sender: TObject); begin AddButtonClick(Self); end; procedure TFini_type_place.Action_DelExecute(Sender: TObject); begin if DelButton.Enabled then DelButtonClick(Self); end; procedure TFini_type_place.Action_ModExecute(Sender: TObject); begin if UpdateButton.Enabled then ModButtonClick(Self); end; procedure TFini_type_place.Action_RefreshExecute(Sender: TObject); begin RefreshButtonClick(Self); end; procedure TFini_type_place.Action_DownExecute(Sender: TObject); begin if DownButton.Enabled then DownButtonClick(Self); end; procedure TFini_type_place.Action_UpExecute(Sender: TObject); begin if UpButton.Enabled then UpButtonClick(Self); end; procedure TFini_type_place.Action_SelExecute(Sender: TObject); begin if ChooseButton.Enabled then SelButtonClick(Self); end; procedure TFini_type_place.Action_ExitExecute(Sender: TObject); begin ExitButtonClick(Self); end; ////////////////////////////////////////////////////////////// // Popup menu procedures ////////////////////////////////////////////////////////////// procedure TFini_type_place.PM_AddButtonClick(Sender: TObject); begin AddButtonClick(Self); end; procedure TFini_type_place.PM_DelButtonClick(Sender: TObject); begin DelButtonClick(Self); end; procedure TFini_type_place.PM_ModButtonClick(Sender: TObject); begin ModButtonClick(Self); end; procedure TFini_type_place.PM_RefreshButtonClick(Sender: TObject); begin RefreshButtonClick(Self); end; procedure TFini_type_place.PM_DownButtonClick(Sender: TObject); begin DownButtonClick(Self); end; procedure TFini_type_place.PM_UpButtonClick(Sender: TObject); begin UpButtonClick(Self); end; procedure TFini_type_place.PM_SelButtonClick(Sender: TObject); begin SelButtonClick(Self); end; procedure TFini_type_place.PM_ExitButtonClick(Sender: TObject); begin ExitButtonClick(Self); end; procedure TFini_type_place.FormClose(Sender: TObject; var Action: TCloseAction); begin if FormStyle = fsMDIChild then Action := caFree; end; procedure TFini_type_place.SearchEditKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then cxGrid1.SetFocus; end; procedure TFini_type_place.cxGrid1DBTableView1KeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then if ChooseButton.Enabled then SelButtonClick(Self); if Key = #27 then Close; end; procedure TFini_type_place.CloseButtonClick(Sender: TObject); begin Close; end; end.
unit uCaixaDAOClient; interface uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Generics.Collections, DBXJSONReflect, Caixa; type TCaixaDAOClient = class(TDSAdminClient) private FAbrirCommand: TDBXCommand; FFecharCommand: TDBXCommand; FCaixaAbertoCommand: TDBXCommand; FRelatorioCommand: TDBXCommand; FListCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function Abrir(Caixa: TCaixa): Boolean; function Fechar: Boolean; function CaixaAberto: TCaixa; function Relatorio(DataInicial, DataFinal: TDateTime): TDBXReader; function List: TDBXReader; end; implementation function TCaixaDAOClient.Abrir(Caixa: TCaixa): Boolean; begin if FAbrirCommand = nil then begin FAbrirCommand := FDBXConnection.CreateCommand; FAbrirCommand.CommandType := TDBXCommandTypes.DSServerMethod; FAbrirCommand.Text := 'TCaixaDAO.Abrir'; FAbrirCommand.Prepare; end; if not Assigned(Caixa) then FAbrirCommand.Parameters[0].Value.SetNull else begin FMarshal := TDBXClientCommand(FAbrirCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FAbrirCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Caixa), True); if FInstanceOwner then Caixa.Free finally FreeAndNil(FMarshal) end end; FAbrirCommand.ExecuteUpdate; Result := FAbrirCommand.Parameters[1].Value.GetBoolean; end; constructor TCaixaDAOClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; function TCaixaDAOClient.CaixaAberto: TCaixa; begin if FCaixaAbertoCommand = nil then begin FCaixaAbertoCommand := FDBXConnection.CreateCommand; FCaixaAbertoCommand.CommandType := TDBXCommandTypes.DSServerMethod; FCaixaAbertoCommand.Text := 'TCaixaDAO.CaixaAberto'; FCaixaAbertoCommand.Prepare; end; FCaixaAbertoCommand.ExecuteUpdate; if not FCaixaAbertoCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDBXClientCommand(FCaixaAbertoCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TCaixa(FUnMarshal.UnMarshal(FCaixaAbertoCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FCaixaAbertoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; constructor TCaixaDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TCaixaDAOClient.Destroy; begin FreeAndNil(FAbrirCommand); FreeAndNil(FFecharCommand); FreeAndNil(FCaixaAbertoCommand); FreeAndNil(FRelatorioCommand); FreeAndNil(FListCommand); inherited; end; function TCaixaDAOClient.Fechar: Boolean; begin if FFecharCommand = nil then begin FFecharCommand := FDBXConnection.CreateCommand; FFecharCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFecharCommand.Text := 'TCaixaDAO.Fechar'; FFecharCommand.Prepare; end; FFecharCommand.ExecuteUpdate; Result := FFecharCommand.Parameters[0].Value.GetBoolean; end; function TCaixaDAOClient.List: TDBXReader; begin if FListCommand = nil then begin FListCommand := FDBXConnection.CreateCommand; FListCommand.CommandType := TDBXCommandTypes.DSServerMethod; FListCommand.Text := 'TCaixaDAO.List'; FListCommand.Prepare; end; FListCommand.ExecuteUpdate; Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner); end; function TCaixaDAOClient.Relatorio(DataInicial, DataFinal: TDateTime): TDBXReader; begin if FRelatorioCommand = nil then begin FRelatorioCommand := FDBXConnection.CreateCommand; FRelatorioCommand.CommandType := TDBXCommandTypes.DSServerMethod; FRelatorioCommand.Text := 'TCaixaDAO.Relatorio'; FRelatorioCommand.Prepare; end; FRelatorioCommand.Parameters[0].Value.AsDateTime := DataInicial; FRelatorioCommand.Parameters[1].Value.AsDateTime := DataFinal; FRelatorioCommand.ExecuteUpdate; Result := FRelatorioCommand.Parameters[2].Value.GetDBXReader(FInstanceOwner); end; end.
unit ibSHSQLEditorFrm; interface uses SHDesignIntf, SHOptionsIntf, SHEvents, ibSHDesignIntf, ibSHDriverIntf, ibSHComponentFrm, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, ExtCtrls, AppEvnts, ImgList, Menus, SynEdit, SynEditKeyCmds, SynEditTypes, pSHSynEdit, ActnList, pSHIntf, pSHSqlTxtRtns, pSHStrUtil,VirtualTrees; type TibSHSQLEditorForm = class(TibBTComponentForm, IibSHSQLEditorForm) Panel2: TPanel; pSHSynEdit2: TpSHSynEdit; Splitter1: TSplitter; Panel1: TPanel; pSHSynEdit1: TpSHSynEdit; ImageList1: TImageList; PopupMenuMessage: TPopupMenu; pmiHideMessage: TMenuItem; function SQLEditorLastContextFileName: string; procedure pSHSynEdit1ProcessUserCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: Char; Data: Pointer); procedure pmiHideMessageClick(Sender: TObject); private { Private declarations } FSQLParser: TSQLParser; FDRVQuery: TComponent; FNeedFecthAll: Boolean; FDMLHistoryComponent: TSHComponent; FDMLHistory: IibSHDMLHistory; FCurrentStatementNo: Integer; FImageIndexMsg: Integer; FDisableAllActions: Boolean; FSuppressPlan: Boolean; procedure GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); procedure SaveEditorContext; procedure AddToHistory(AText: string); function GetBTCLDatabase: IibSHDatabase; function GetSQLEditorIntf: IibSHSQLEditor; function GetDRVQuery: IibSHDRVQuery; function GetData: IibSHData; function GetStatistics: IibSHStatistics; function GetDMLHistory: IibSHDMLHistory; function GetDisableAllActions: Boolean; protected procedure EditorMsgVisible(AShow: Boolean = True); override; function ConfirmEndTransaction: Boolean; function DoOnOptionsChanged: Boolean; override; procedure DoOnIdle; override; function GetCanDestroy: Boolean; override; { ISHFileCommands } // function GetCanOpen: Boolean; virtual; // function GetCanSave: Boolean; virtual; // function GetCanSaveAs: Boolean; virtual; // procedure Open; virtual; // procedure Save; virtual; // procedure SaveAs; virtual; { ISHEditCommands } procedure ClearAll; override; { ISHRunCommands } function GetCanRun: Boolean; override; function GetCanPause: Boolean; override; function GetCanCommit: Boolean; override; function GetCanRollback: Boolean; override; procedure Run; override; procedure Pause; override; procedure Commit; override; procedure Rollback; override; {IibSHSQLEditorForm} function GetSQLText: string; procedure ShowPlan; procedure ShowTransactionCommited; procedure ShowTransactionRolledBack; procedure ShowStatistics; procedure ClearMessages; procedure InsertStatement(AText: string); procedure LoadLastContext; function GetCanPreviousQuery: Boolean; function GetCanNextQuery: Boolean; function GetCanPrepare: Boolean; function GetCanEndTransaction: Boolean; procedure PreviousQuery; procedure NextQuery; procedure RunAndFetchAll; procedure IibSHSQLEditorForm.Prepare = IPrepare; procedure IPrepare; public procedure Prepare(ForceShowPlan: Boolean = False); function PrepareQuery(const AText: string; ForceShowPlan: Boolean = False): Boolean; procedure RunQuery(const AText: string); property DRVQuery: IibSHDRVQuery read GetDRVQuery; property DisableAllActions: Boolean read GetDisableAllActions write FDisableAllActions; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); override; destructor Destroy; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure AddToResultEdit(AText: string); property SQLEditor: IibSHSQLEditor read GetSQLEditorIntf; property DMLHistory: IibSHDMLHistory read GetDMLHistory; property BTCLDatabase: IibSHDatabase read GetBTCLDatabase; property Data: IibSHData read GetData; property Statistics: IibSHStatistics read GetStatistics; end; var ibSHSQLEditorForm: TibSHSQLEditorForm; implementation uses ibSHConsts, ibSHMessages, ibSHValues; {$R *.dfm} const img_success = 0; img_error = 1; { TibSHSQLEditorForm } constructor TibSHSQLEditorForm.Create(AOwner: TComponent; AParent: TWinControl; AComponent: TSHComponent; ACallString: string); var vComponentClass: TSHComponentClass; begin inherited Create(AOwner, AParent, AComponent, ACallString); EditorMsg := pSHSynEdit2; EditorMsg.Lines.Clear; EditorMsg.OnGutterDraw := GutterDrawNotify; EditorMsg.GutterDrawer.ImageList := ImageList1; EditorMsg.GutterDrawer.Enabled := True; FImageIndexMsg := img_success; Editor := pSHSynEdit1; Editor.Lines.Clear; FocusedControl := Editor; RegisterEditors; EditorMsgVisible(False); DoOnOptionsChanged; FSQLParser := TSQLParser.Create; if Assigned(BTCLDatabase) and Assigned(Data) then begin vComponentClass := Designer.GetComponent(BTCLDatabase.BTCLServer.DRVNormalize(IibSHDRVQuery)); if Assigned(vComponentClass) then begin FDRVQuery := vComponentClass.Create(Self); DRVQuery.Database := BTCLDatabase.DRVQuery.Database; DRVQuery.Transaction := Data.Transaction; end; end; with Editor.Keystrokes do AddKey(ecpSHUserFirst + 1, VK_F9, [ssCtrl]); if Assigned(DMLHistory) then FCurrentStatementNo := DMLHistory.Count else FCurrentStatementNo := -1; FDMLHistory := nil; FDMLHistoryComponent := nil; FSuppressPlan := False; end; destructor TibSHSQLEditorForm.Destroy; begin if Assigned(FDMLHistory) then begin FDMLHistory.SaveToFile; if not Assigned(Designer.GetComponentForm(IibSHDMLHistoryForm, SCallDMLStatements)) and Assigned(FDMLHistoryComponent) then begin Designer.ChangeNotification(FDMLHistoryComponent, opRemove); FDMLHistoryComponent.Free; end; end; if Assigned(FDRVQuery) then FDRVQuery.Free; SaveEditorContext; FSQLParser.Free; inherited Destroy; end; procedure TibSHSQLEditorForm.GutterDrawNotify(Sender: TObject; ALine: Integer; var ImageIndex: Integer); begin if ALine = 0 then ImageIndex := FImageIndexMsg; end; procedure TibSHSQLEditorForm.SaveEditorContext; var vFileName: string; begin vFileName := SQLEditorLastContextFileName; if Assigned(BTCLDatabase) and Assigned(Editor) and (not Editor.IsEmpty) and (Length(vFileName) > 0) then try Editor.Lines.SaveToFile(vFileName); except end; end; procedure TibSHSQLEditorForm.AddToHistory(AText: string); begin if Assigned(DMLHistory) then FCurrentStatementNo := DMLHistory.AddStatement(AText, Statistics); end; function TibSHSQLEditorForm.GetBTCLDatabase: IibSHDatabase; begin Supports(Component, IibSHDatabase, Result); end; function TibSHSQLEditorForm.GetSQLEditorIntf: IibSHSQLEditor; begin Supports(Component, IibSHSQLEditor, Result); end; function TibSHSQLEditorForm.GetDRVQuery: IibSHDRVQuery; begin Supports(FDRVQuery, IibSHDRVQuery, Result); end; function TibSHSQLEditorForm.GetData: IibSHData; begin Supports(Component, IibSHData, Result); end; function TibSHSQLEditorForm.GetStatistics: IibSHStatistics; begin Supports(Component, IibSHStatistics, Result); end; function TibSHSQLEditorForm.GetDMLHistory: IibSHDMLHistory; var vHistoryComponentClass: TSHComponentClass; vSHSystemOptions: ISHSystemOptions; begin if not Assigned(FDMLHistory) then begin if not Supports(Designer.FindComponent(Component.OwnerIID, IibSHDMLHistory), IibSHDMLHistory, FDMLHistory) then begin vHistoryComponentClass := Designer.GetComponent(IibSHDMLHistory); if Assigned(vHistoryComponentClass) then begin FDMLHistoryComponent := vHistoryComponentClass.Create(nil); FreeNotification(FDMLHistoryComponent); FDMLHistoryComponent.OwnerIID := Component.OwnerIID; FDMLHistoryComponent.Caption := vHistoryComponentClass.GetHintClassFnc; if Assigned(BTCLDatabase) and Supports(Designer.GetOptions(ISHSystemOptions), ISHSystemOptions, vSHSystemOptions) and not vSHSystemOptions.UseWorkspaces then FDMLHistoryComponent.Caption := Format('%s for %s', [FDMLHistoryComponent.Caption, BTCLDatabase.Alias]); Supports(FDMLHistoryComponent, IibSHDMLHistory, FDMLHistory); end; end; ReferenceInterface(FDMLHistory, opInsert); end; Result := FDMLHistory; end; function TibSHSQLEditorForm.GetDisableAllActions: Boolean; begin Result := FDisableAllActions or (Assigned(SQLEditor) and (not SQLEditor.AutoCommit) and Assigned(Data) and Assigned(Data.Dataset) and Data.Dataset.IsFetching); end; procedure TibSHSQLEditorForm.EditorMsgVisible(AShow: Boolean = True); begin Panel2.Visible := AShow; Splitter1.Visible := AShow; if AShow and Assigned(StatusBar) then StatusBar.Top := Self.Height; end; function TibSHSQLEditorForm.ConfirmEndTransaction: Boolean; begin Result := Assigned(BTCLDatabase) and Assigned(Data) and ( (SameText(BTCLDatabase.DatabaseAliasOptions.DML.ConfirmEndTransaction, ConfirmEndTransactions[0]) and Assigned(Data.Dataset) and Data.Dataset.DataModified) or (SameText(BTCLDatabase.DatabaseAliasOptions.DML.ConfirmEndTransaction, ConfirmEndTransactions[1])) ); end; function TibSHSQLEditorForm.DoOnOptionsChanged: Boolean; begin Result := inherited DoOnOptionsChanged; if Result and Assigned(EditorMsg) then EditorMsg.ReadOnly := True; end; procedure TibSHSQLEditorForm.DoOnIdle; begin end; function TibSHSQLEditorForm.GetCanDestroy: Boolean; var vMsgText: string; procedure DoTransactionAction; begin if Data.Transaction.InTransaction then begin if SameText(BTCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[0]) then Commit else Rollback; end; end; procedure DoTransactionInvertAction; begin if Data.Transaction.InTransaction then begin if SameText(BTCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[0]) then Rollback else Commit; end; end; begin Result := inherited GetCanDestroy; if (not Assigned(BTCLDatabase)) or BTCLDatabase.WasLostconnect then Exit; if Result and Assigned(Data) then begin if Assigned(Data.Dataset) and Data.Dataset.Active and Data.Dataset.IsFetching then begin Result := False; Designer.ShowMsg(SDataFetching, mtInformation); Exit; end; if not SQLEditor.AutoCommit then begin if Data.Transaction.InTransaction then begin if ConfirmEndTransaction then begin if SameText(BTCLDatabase.DatabaseAliasOptions.DML.DefaultTransactionAction, DefaultTransactionActions[0]) then vMsgText := SCommitTransaction else vMsgText := SRollbackTransaction; case Designer.ShowMsg(vMsgText) of ID_YES: DoTransactionAction; ID_NO: DoTransactionInvertAction; else Result := False; end; end else DoTransactionAction; end; end else Commit; end; end; procedure TibSHSQLEditorForm.ClearAll; begin if not pSHSynEdit1.IsEmpty then if not Designer.ShowMsg(SClearEditorContextWorning, mtConfirmation) then Exit; if Assigned(Editor) then begin Editor.Clear; Editor.Modified := False; end; end; function TibSHSQLEditorForm.GetCanRun: Boolean; begin Result := (not DisableAllActions) and Assigned(Editor) and (not Editor.IsEmpty) and Assigned(SQLEditor) and Assigned(SQLEditor.BTCLDatabase) and (not SQLEditor.BTCLDatabase.WasLostConnect); end; function TibSHSQLEditorForm.GetCanPause: Boolean; begin Result := False; end; function TibSHSQLEditorForm.GetCanCommit: Boolean; begin Result := Assigned(Data) and Data.Transaction.InTransaction and not SQLEditor.AutoCommit; end; function TibSHSQLEditorForm.GetCanRollback: Boolean; begin Result := Assigned(Data) and Data.Transaction.InTransaction and not SQLEditor.AutoCommit; end; procedure TibSHSQLEditorForm.Run; begin if Assigned(Editor) and Assigned(SQLEditor) and Assigned(SQLEditor.BTCLDatabase) and (not SQLEditor.BTCLDatabase.WasLostConnect) then with Editor do begin FNeedFecthAll := False; if SelAvail and SQLEditor.ExecuteSelected then RunQuery(SelText) else RunQuery(Text); end; end; procedure TibSHSQLEditorForm.Pause; begin //Do nothing end; procedure TibSHSQLEditorForm.Commit; begin if Assigned(Data) and Data.Transaction.InTransaction then begin Data.Transaction.Commit; ShowTransactionCommited; end; end; procedure TibSHSQLEditorForm.Rollback; begin if Assigned(Data) and Data.Transaction.InTransaction then begin Data.Transaction.Rollback; ShowTransactionRolledBack; end; end; function TibSHSQLEditorForm.GetSQLText: string; begin Result := EmptyStr; if Assigned(Editor) and Assigned(SQLEditor) and Assigned(SQLEditor.BTCLDatabase) and (not SQLEditor.BTCLDatabase.WasLostConnect) then with Editor do begin if SelAvail and SQLEditor.ExecuteSelected then Result := SelText else Result := Text; end; end; procedure TibSHSQLEditorForm.ShowPlan; begin if not FSuppressPlan then begin AddToResultEdit(EmptyStr); if Assigned(Data) and Assigned(Data.Dataset) and Assigned(SQLEditor) and SQLEditor.RetrievePlan then AddToResultEdit(Data.Dataset.Plan); Application.ProcessMessages; end; end; procedure TibSHSQLEditorForm.ShowTransactionCommited; begin if Assigned(SQLEditor) then begin if SQLEditor.AutoCommit and (EditorMsg.Lines.Count > 0) then Designer.TextToStrings(sLineBreak + STransactionCommited, EditorMsg.Lines) else Designer.TextToStrings(STransactionCommited, EditorMsg.Lines, True); FImageIndexMsg := img_success; end; end; procedure TibSHSQLEditorForm.ShowTransactionRolledBack; begin if Assigned(SQLEditor) then begin if SQLEditor.AutoCommit and (Length(EditorMsg.Lines.Text) > 0) then Designer.TextToStrings(sLineBreak + STransactionRolledBack, EditorMsg.Lines) else Designer.TextToStrings(STransactionRolledBack, EditorMsg.Lines, True); FImageIndexMsg := img_success; end; end; procedure TibSHSQLEditorForm.ShowStatistics; var I: Integer; vRunCommands: ISHRunCommands; begin if Assigned(EditorMsg) and Assigned(SQLEditor) and SQLEditor.RetrieveStatistics and Assigned(BTCLDatabase) and (not BTCLDatabase.WasLostConnect) and Assigned(Data) and {Data.Dataset.Active and} Assigned(Statistics) then begin AddToResultEdit(Statistics.TableStatisticsStr(False)); // Designer.TextToStrings(Statistics.TableStatisticsStr(False), EditorMsg.Lines); AddToResultEdit(Statistics.ExecuteTimeStatisticsStr); // Designer.TextToStrings(Statistics.ExecuteTimeStatisticsStr, EditorMsg.Lines); for I := 0 to Pred(Component.ComponentForms.Count) do if Supports(Component.ComponentForms[I], IibSHStatisticsForm) then begin if Supports(Component.ComponentForms[I], ISHRunCommands, vRunCommands) and vRunCommands.CanRefresh then vRunCommands.Refresh; Break; end; end; end; procedure TibSHSQLEditorForm.ClearMessages; begin Designer.TextToStrings(EmptyStr, EditorMsg.Lines, True); end; procedure TibSHSQLEditorForm.InsertStatement(AText: string); var vLinesBefore, vLinesInserted: Integer; vText: string; begin if Assigned(Editor) then begin vLinesBefore := Editor.Lines.Count; Editor.BeginUpdate; vText := TrimRight(AText) + sLineBreak; if vLinesBefore > 0 then vText := vText + sLineBreak; Designer.TextToStrings(vText, Editor.Lines, False, True); Editor.BlockBegin := TBufferCoord(Point(1, 1)); vLinesInserted := Editor.Lines.Count - vLinesBefore; if vLinesBefore > 0 then Editor.BlockEnd := TBufferCoord(Point(Length(Editor.Lines[vLinesInserted - 2]) + 1, vLinesInserted - 1)) else Editor.BlockEnd := TBufferCoord(Point(Length(Editor.Lines[vLinesInserted - 1]) + 1, vLinesInserted)); Editor.EndUpdate; Editor.TopLine := 1; end; end; procedure TibSHSQLEditorForm.LoadLastContext; var vFileName: string; begin vFileName := SQLEditorLastContextFileName; if Assigned(BTCLDatabase) and Assigned(Editor) and (Length(vFileName) > 0) and FileExists(vFileName) then begin if not Editor.IsEmpty then if not Designer.ShowMsg(SReplaceEditorContextWorning, mtConfirmation) then Exit; Editor.Lines.LoadFromFile(vFileName); Editor.Modified := False; Editor.SetFocus; end; end; function TibSHSQLEditorForm.GetCanPreviousQuery: Boolean; begin Result := (not DisableAllActions) and Assigned(DMLHistory) and (FCurrentStatementNo > 0) and (DMLHistory.Count > 0) and (FCurrentStatementNo <= DMLHistory.Count); end; function TibSHSQLEditorForm.GetCanNextQuery: Boolean; begin Result := (not DisableAllActions) and Assigned(DMLHistory) and (FCurrentStatementNo >= 0) and (FCurrentStatementNo < Pred(DMLHistory.Count)); end; function TibSHSQLEditorForm.GetCanPrepare: Boolean; begin Result := (not DisableAllActions) and Assigned(Editor) and (not Editor.IsEmpty); end; function TibSHSQLEditorForm.GetCanEndTransaction: Boolean; begin Result := (not DisableAllActions) and Assigned(SQLEditor) and (not SQLEditor.AutoCommit); end; procedure TibSHSQLEditorForm.PreviousQuery; begin if GetCanPreviousQuery then begin Dec(FCurrentStatementNo); Designer.TextToStrings(TrimRight(DMLHistory.Statement(FCurrentStatementNo)) + sLineBreak, Editor.Lines, True); end; end; procedure TibSHSQLEditorForm.NextQuery; begin if GetCanNextQuery then begin Inc(FCurrentStatementNo); Designer.TextToStrings(TrimRight(DMLHistory.Statement(FCurrentStatementNo)) + sLineBreak, Editor.Lines, True); end; end; procedure TibSHSQLEditorForm.RunAndFetchAll; begin if GetCanRun then with Editor do begin FNeedFecthAll := True; if SelAvail and SQLEditor.ExecuteSelected then RunQuery(SelText) else RunQuery(Text); end; end; procedure TibSHSQLEditorForm.IPrepare; begin ClearMessages; Prepare(True); end; procedure TibSHSQLEditorForm.Prepare(ForceShowPlan: Boolean = False); begin if Assigned(Editor) and Assigned(SQLEditor) and Assigned(SQLEditor.BTCLDatabase) and (not SQLEditor.BTCLDatabase.WasLostConnect) then with Editor do if SelAvail and SQLEditor.ExecuteSelected then PrepareQuery(SelText, ForceShowPlan) else PrepareQuery(Text, ForceShowPlan); end; function TibSHSQLEditorForm.PrepareQuery(const AText: string; ForceShowPlan: Boolean = False): Boolean; var vPlan: string; vDatabase: IibSHDatabase; vBaseErrorCoord: TBufferCoord; begin Result := False; if Supports(Component, IibSHDatabase, vDatabase) then with vDatabase.DRVQuery do begin SQL.Text := AText; try Transaction.StartTransaction; try Result := Prepare; finally Screen.Cursor := crDefault; end; if not Result then begin vBaseErrorCoord := GetErrorCoord(ErrorText); if SQLEditor.ExecuteSelected and Editor.SelAvail then begin vBaseErrorCoord.Char := vBaseErrorCoord.Char + Editor.BlockBegin.Char - 1; vBaseErrorCoord.Line := vBaseErrorCoord.Line + Editor.BlockBegin.Line - 1; end; ErrorCoord := vBaseErrorCoord; AddToResultEdit(ErrorText); FImageIndexMsg := img_error; end else begin AddToResultEdit(EmptyStr); if Assigned(SQLEditor) and (SQLEditor.RetrievePlan or ForceShowPlan) then begin vPlan := Plan; if Length(vPlan) > 0 then AddToResultEdit(vPlan) else if Length(ErrorText) > 0 then begin AddToResultEdit(ErrorText); FImageIndexMsg := img_error; end; end; end; finally Transaction.Commit; end; end; end; procedure TibSHSQLEditorForm.RunQuery(const AText: string); var vRetrieveStatistics: Boolean; vBaseErrorCoord: TBufferCoord; vDDLForm: IibSHDDLForm; PsewdoSQLText: string; I: Integer; vIsSetStatistic: Boolean; vIndexName: string; vPrevStatisticValue: double; vFormatSettings: TFormatSettings; vDBTransactionParams: string; function InputParameters(ADRVQuery: IibSHDRVQuery): Boolean; var vDRVParams: IibSHDRVParams; vInputParameters: IibSHInputParameters; vComponentClass: TSHComponentClass; vComponent: TSHComponent; begin Result := False; vComponentClass := Designer.GetComponent(IibSHInputParameters); if Assigned(vComponentClass) and Supports(ADRVQuery, IibSHDRVParams, vDRVParams) then begin vComponent := vComponentClass.Create(nil); try if Supports(vComponent, IibSHInputParameters, vInputParameters) then begin Result := vInputParameters.InputParameters(vDRVParams); vInputParameters := nil; end; finally FreeAndNil(vComponent); end; vDRVParams := nil; end; end; begin ClearMessages; FSuppressPlan := False; DisableAllActions := True; try FSQLParser.SQLText := AText; if FSQLParser.SQLKind = skDDL then begin if Designer.ShowMsg(SDDLStatementInput) = IDYES then begin with Component as IibSHDDLInfo do begin DDL.Text := AText; end; Designer.ChangeNotification(Component, SCallDDLText, opInsert); if Designer.ExistsComponent(Component, SCallDDLText) then if Component.GetComponentFormIntf(IibSHDDLForm, vDDLForm) then vDDLForm.ShowDDLText; end; end else if (FSQLParser.SQLKind in [skSelect,skExecuteBlock]) then begin if Assigned(Data) then begin Data.Close; Data.ReadOnly := False; Data.Dataset.SelectSQL.Text := AText; vRetrieveStatistics := Assigned(Statistics) and Assigned(SQLEditor) and SQLEditor.RetrieveStatistics; if vRetrieveStatistics then Statistics.StartCollection; if Data.Open then begin Designer.ChangeNotification(Component, SCallQueryResults, opInsert); if FNeedFecthAll then begin Application.ProcessMessages; Data.FetchAll; end; if vRetrieveStatistics and (Length(Data.ErrorText) = 0) then begin Statistics.CalculateStatistics; if Supports(Data.Dataset, IibSHDRVExecTimeStatistics) then Statistics.DRVTimeStatistics := Data.Dataset as IibSHDRVExecTimeStatistics; ShowStatistics; end; AddToHistory(AText); end else begin if Length(Data.ErrorText) > 0 then begin vBaseErrorCoord := GetErrorCoord(Data.ErrorText); if SQLEditor.ExecuteSelected and Editor.SelAvail then begin vBaseErrorCoord.Char := vBaseErrorCoord.Char + Editor.BlockBegin.Char - 1; vBaseErrorCoord.Line := vBaseErrorCoord.Line + Editor.BlockBegin.Line - 1; end; ErrorCoord := vBaseErrorCoord; AddToResultEdit(Data.ErrorText); FImageIndexMsg := img_error; if DMLHistory.Crash then AddToHistory(AText + #13#10#13#10 + Data.ErrorText); end else if DMLHistory.Crash then AddToHistory(AText); end; end; end else begin DRVQuery.SQL.Text := AText; if not DRVQuery.Transaction.InTransaction then begin DRVQuery.Transaction.Params.Text := GetTransactionParams(SQLEditor.IsolationLevel, SQLEditor.TransactionParams.Text); DRVQuery.Transaction.StartTransaction; end; Screen.Cursor := crHourGlass; // Õíÿ vIsSetStatistic := (UpperCase(ExtractWord(1, AText, [' ',#13,#9,#10])) = 'SET') and (UpperCase(ExtractWord(2, AText, [' ',#13,#9,#10])) = 'STATISTICS'); if vIsSetStatistic then begin vIndexName := ExtractWord(4, AText, [' ',#13,#9,#10]); vIsSetStatistic := Length(vIndexName) > 0; end; if vIsSetStatistic then begin BTCLDatabase.DRVQuery.ExecSQL('SELECT IDX.RDB$STATISTICS AS OLD_STATISTICS FROM RDB$INDICES IDX WHERE IDX.RDB$INDEX_NAME = :INDEX_NAME', [vIndexName], False); vPrevStatisticValue := BTCLDatabase.DRVQuery.GetFieldFloatValue(0); if BTCLDatabase.DRVQuery.Transaction.InTransaction then BTCLDatabase.DRVQuery.Transaction.Commit; vDBTransactionParams := BTCLDatabase.DRVQuery.Transaction.Params.Text; BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams; BTCLDatabase.DRVQuery.SQL.Text := AText; if not BTCLDatabase.DRVQuery.Transaction.InTransaction then BTCLDatabase.DRVQuery.Transaction.StartTransaction; Screen.Cursor := crHourGlass; BTCLDatabase.DRVQuery.Execute; if BTCLDatabase.DRVQuery.Transaction.InTransaction then BTCLDatabase.DRVQuery.Transaction.Commit; BTCLDatabase.DRVQuery.Transaction.Params.Text := vDBTransactionParams; if (Length(BTCLDatabase.DRVQuery.ErrorText) = 0) and (not BTCLDatabase.WasLostConnect) then begin vFormatSettings.DecimalSeparator := Char('.'); PsewdoSQLText := Format('SELECT %s AS OLD_STATISTICS, IDX.RDB$STATISTICS AS NEW_STATISTICS FROM RDB$INDICES IDX WHERE IDX.RDB$INDEX_NAME = ''%s''', [FormatFloat('', vPrevStatisticValue, vFormatSettings), vIndexName]); Data.Close; Data.ReadOnly := True; Data.Dataset.SelectSQL.Text := PsewdoSQLText; FSuppressPlan := True; if Data.Open then Designer.ChangeNotification(Component, SCallQueryResults, opInsert); FSuppressPlan := False; end; end else begin if Assigned(SQLEditor) and SQLEditor.RetrievePlan then begin try if DRVQuery.Prepare then AddToResultEdit(DRVQuery.Plan); except AddToResultEdit(SErrorPlanRetrieving); end; end else AddToResultEdit(EmptyStr); Application.ProcessMessages; try if InputParameters(DRVQuery) then begin vRetrieveStatistics := SQLEditor.RetrieveStatistics; if vRetrieveStatistics then Statistics.StartCollection; Screen.Cursor := crHourGlass; DRVQuery.Execute; if vRetrieveStatistics and (Length(DRVQuery.ErrorText) = 0) then begin Statistics.CalculateStatistics; if Supports(DRVQuery, IibSHDRVExecTimeStatistics) then Statistics.DRVTimeStatistics := DRVQuery as IibSHDRVExecTimeStatistics; ShowStatistics; end; end; finally Screen.Cursor := crDefault; end; if Length(DRVQuery.ErrorText) > 0 then begin vBaseErrorCoord := GetErrorCoord(DRVQuery.ErrorText); if SQLEditor.ExecuteSelected and Editor.SelAvail then begin vBaseErrorCoord.Char := vBaseErrorCoord.Char + Editor.BlockBegin.Char - 1; vBaseErrorCoord.Line := vBaseErrorCoord.Line + Editor.BlockBegin.Line - 1; end; ErrorCoord := vBaseErrorCoord; AddToResultEdit(DRVQuery.ErrorText); FImageIndexMsg := img_error; if DMLHistory.Crash then AddToHistory(AText + #13#10#13#10 + DRVQuery.ErrorText ); end else AddToHistory(AText); if (Length(DRVQuery.ErrorText) = 0) and (not BTCLDatabase.WasLostConnect) then begin PsewdoSQLText := EmptyStr; for I := 0 to Pred(DRVQuery.GetFieldCount) do if not DRVQuery.FieldIsBlob(I) then PsewdoSQLText := PsewdoSQLText + Format('''%s'' AS "%s", ', [DRVQuery.GetFieldStrValue(I), DRVQuery.FieldName(I)]) else PsewdoSQLText := PsewdoSQLText + Format('''%s'' AS "%s", ', ['[BLOB]', DRVQuery.FieldName(I)]); if Length(PsewdoSQLText) > 0 then begin Delete(PsewdoSQLText, Length(PsewdoSQLText) - 1, 2); PsewdoSQLText := Format('SELECT %s FROM RDB$DATABASE', [PsewdoSQLText]); Data.Close; Data.ReadOnly := True; Data.Dataset.SelectSQL.Text := PsewdoSQLText; FSuppressPlan := True; if Data.Open then Designer.ChangeNotification(Component, SCallQueryResults, opInsert); FSuppressPlan := False; end; end; end; if SQLEditor.AutoCommit and (DRVQuery.GetFieldCount = 0) then Commit; end; finally DisableAllActions := False; Screen.Cursor := crDefault; end; end; procedure TibSHSQLEditorForm.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) then begin if AComponent.IsImplementorOf(FDMLHistory) then FDMLHistory := nil; if AComponent = FDMLHistoryComponent then FDMLHistoryComponent := nil; end; inherited Notification(AComponent, Operation); end; procedure TibSHSQLEditorForm.AddToResultEdit(AText: string); begin if Assigned(EditorMsg) then begin FImageIndexMsg := img_success; if (Length(AText) > 0) and (Length(EditorMsg.Lines.Text) > 0) then Designer.TextToStrings(sLineBreak, EditorMsg.Lines); Designer.TextToStrings(AText, EditorMsg.Lines); if Length(AText) > 0 then EditorMsgVisible; end; end; { Actions } function TibSHSQLEditorForm.SQLEditorLastContextFileName: string; var vDataRootDirectory: ISHDataRootDirectory; vDir: string; begin Result := EmptyStr; if Supports(BTCLDatabase, ISHDataRootDirectory, vDataRootDirectory) then begin vDir := vDataRootDirectory.DataRootDirectory; if SysUtils.DirectoryExists(vDir) then begin Result := vDir + SQLEditorLastContextFile; vDir := ExtractFilePath(Result); if not SysUtils.DirectoryExists(vDir) then ForceDirectories(vDir); end; end; end; procedure TibSHSQLEditorForm.pSHSynEdit1ProcessUserCommand( Sender: TObject; var Command: TSynEditorCommand; var AChar: Char; Data: Pointer); begin if Command = ecpSHUserFirst + 1 then begin ClearMessages; Prepare; end; end; procedure TibSHSQLEditorForm.pmiHideMessageClick(Sender: TObject); begin EditorMsgVisible(False); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // unit VXS.FilePNG; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.CrossPlatform, VXS.Context, VXS.Graphics, VXS.TextureFormat, VXS.ApplicationFileIO; type TVXPNGImage = class(TVXBaseImage) private public class function Capabilities: TVXDataFileCapabilities; override; procedure LoadFromFile(const filename: string); override; procedure SaveToFile(const filename: string); override; procedure LoadFromStream(stream: TStream); override; procedure SaveToStream(stream: TStream); override; { Assigns from any Texture.} procedure AssignFromTexture(textureContext: TVXContext; const textureHandle: GLuint; textureTarget: TVXTextureTarget; const CurrentFormat: Boolean; const intFormat: TVXInternalFormat); reintroduce; end; //============================================================== implementation //============================================================== // ------------------ // ------------------ TVXPNGImage ------------------ // ------------------ procedure TVXPNGImage.LoadFromFile(const filename: string); var fs: TStream; begin if FileStreamExists(fileName) then begin fs := CreateFileStream(fileName, fmOpenRead); try LoadFromStream(fs); finally fs.Free; ResourceName := filename; end; end else raise EInvalidRasterFile.CreateFmt('File %s not found', [filename]); end; procedure TVXPNGImage.SaveToFile(const filename: string); var fs: TStream; begin fs := CreateFileStream(fileName, fmOpenWrite or fmCreate); try SaveToStream(fs); finally fs.Free; end; ResourceName := filename; end; procedure TVXPNGImage.LoadFromStream(stream: TStream); begin //Do nothing end; procedure TVXPNGImage.SaveToStream(stream: TStream); begin //Do nothing end; procedure TVXPNGImage.AssignFromTexture(textureContext: TVXContext; const textureHandle: GLuint; textureTarget: TVXTextureTarget; const CurrentFormat: Boolean; const intFormat: TVXInternalFormat); var oldContext: TVXContext; contextActivate: Boolean; texFormat: Cardinal; residentFormat: TVXInternalFormat; glTarget: GLEnum; begin if not ((textureTarget = ttTexture2D) or (textureTarget = ttTextureRect)) then Exit; oldContext := CurrentVXContext; contextActivate := (oldContext <> textureContext); if contextActivate then begin if Assigned(oldContext) then oldContext.Deactivate; textureContext.Activate; end; glTarget := DecodeTextureTarget(textureTarget); try textureContext.VXStates.TextureBinding[0, textureTarget] := textureHandle; fLevelCount := 0; fCubeMap := false; fTextureArray := false; // Check level existence glGetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_INTERNAL_FORMAT, @texFormat); if texFormat > 1 then begin glGetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_WIDTH, @FLOD[0].Width); glGetTexLevelParameteriv(glTarget, 0, GL_TEXTURE_HEIGHT, @FLOD[0].Height); FLOD[0].Depth := 0; residentFormat := OpenVXFormatToInternalFormat(texFormat); if CurrentFormat then fInternalFormat := residentFormat else fInternalFormat := intFormat; FindCompatibleDataFormat(fInternalFormat, fColorFormat, fDataType); Inc(fLevelCount); end; if fLevelCount > 0 then begin fElementSize := GetTextureElementSize(fColorFormat, fDataType); ReallocMem(FData, DataSize); glGetTexImage(glTarget, 0, fColorFormat, fDataType, fData); end else fLevelCount := 1; /// CheckOpenGLError; finally if contextActivate then begin textureContext.Deactivate; if Assigned(oldContext) then oldContext.Activate; end; end; end; class function TVXPNGImage.Capabilities: TVXDataFileCapabilities; begin Result := [dfcRead, dfcWrite]; end; //---------------------------------------------------------- initialization //---------------------------------------------------------- { Register this Fileformat-Handler with VXScene } RegisterRasterFormat('png', 'Portable Network Graphic', TVXPNGImage); end.
unit UCliente; interface uses UPessoa,SysUtils,Dialogs; type TCliente = Class (TPessoa) private protected FNome:String; FRG:String; FCPF:String; FSexo:String; public constructor Create; destructor Destroy; procedure setNome(vNome:String); procedure setRG(vRG:string); procedure setCPF(vCPF:string); procedure setSexo(vSexo:String); function getNome:string; function getRG:string; function getCPF:string; function getSexo:String; property Nome:String read getNome write setNome; property RG:string read getRG write setRG; property CPF:string read getCPF write setCPF; property Sexo:String read getSexo write setSexo; function ValidaCPF(VCpf:string):Boolean; end; implementation { TPessoaFisica } constructor TCliente.Create; begin inherited; FNome:=''; FRG:=''; FCPF:=''; FSexo:=''; end; destructor TCliente.Destroy; begin inherited; end; function TCliente.getCPF: string; begin Result:= FCPF; end; function TCliente.getNome: string; begin Result:=FNome; end; function TCliente.getRG: string; begin Result:=FRG; end; function TCliente.getSexo:String; begin Result:=FSexo; end; procedure TCliente.setCPF(vCPF: string); begin FCPF:=vCPF; end; procedure TCliente.setNome(vNome: String); begin FNome:=vNome; end; procedure TCliente.setRG(vRG: string); begin FRG:=vRG; end; procedure TCliente.setSexo(vSexo:String); begin FSexo:=vSexo; end; function TCliente.ValidaCPF(VCpf: string): Boolean; var CPF:array[1..11] of Integer; I,Y,aux,total:integer; strAux:string; begin total:=0; Y:=1; if Length(VCpf) < 14 then Result:=False else begin for I :=1 to 14 do if TryStrToInt(VCpf[I],aux) then begin CPF[Y]:=aux; total:=total+CPF[Y]; Inc(Y); end; strAux:=IntToStr(total); if strAux[1] = strAux[2] then Result:=True else Result:=False; end; end; end.
// XD Pascal - a 32-bit compiler for Windows // Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov {$I-} {$H-} unit Linker; interface uses Common, CodeGen; procedure InitializeLinker; procedure SetProgramEntryPoint; function AddImportFunc(const ImportLibName, ImportFuncName: TString): LongInt; procedure LinkAndWriteProgram(const ExeName: TString); implementation const IMGBASE = $400000; SECTALIGN = $1000; FILEALIGN = $200; MAXIMPORTLIBS = 100; MAXIMPORTS = 2000; type TDOSStub = array [0..127] of Byte; TPEHeader = packed record PE: array [0..3] of TCharacter; Machine: Word; NumberOfSections: Word; TimeDateStamp: LongInt; PointerToSymbolTable: LongInt; NumberOfSymbols: LongInt; SizeOfOptionalHeader: Word; Characteristics: Word; end; TPEOptionalHeader = packed record Magic: Word; MajorLinkerVersion: Byte; MinorLinkerVersion: Byte; SizeOfCode: LongInt; SizeOfInitializedData: LongInt; SizeOfUninitializedData: LongInt; AddressOfEntryPoint: LongInt; BaseOfCode: LongInt; BaseOfData: LongInt; ImageBase: LongInt; SectionAlignment: LongInt; FileAlignment: LongInt; MajorOperatingSystemVersion: Word; MinorOperatingSystemVersion: Word; MajorImageVersion: Word; MinorImageVersion: Word; MajorSubsystemVersion: Word; MinorSubsystemVersion: Word; Win32VersionValue: LongInt; SizeOfImage: LongInt; SizeOfHeaders: LongInt; CheckSum: LongInt; Subsystem: Word; DllCharacteristics: Word; SizeOfStackReserve: LongInt; SizeOfStackCommit: LongInt; SizeOfHeapReserve: LongInt; SizeOfHeapCommit: LongInt; LoaderFlags: LongInt; NumberOfRvaAndSizes: LongInt; end; TDataDirectory = packed record VirtualAddress: LongInt; Size: LongInt; end; TPESectionHeader = packed record Name: array [0..7] of TCharacter; VirtualSize: LongInt; VirtualAddress: LongInt; SizeOfRawData: LongInt; PointerToRawData: LongInt; PointerToRelocations: LongInt; PointerToLinenumbers: LongInt; NumberOfRelocations: Word; NumberOfLinenumbers: Word; Characteristics: LongInt; end; THeaders = packed record Stub: TDOSStub; PEHeader: TPEHeader; PEOptionalHeader: TPEOptionalHeader; DataDirectories: array [0..15] of TDataDirectory; CodeSectionHeader, DataSectionHeader, BSSSectionHeader, ImportSectionHeader: TPESectionHeader; end; TImportLibName = array [0..15] of TCharacter; TImportFuncName = array [0..31] of TCharacter; TImportDirectoryTableEntry = packed record Characteristics: LongInt; TimeDateStamp: LongInt; ForwarderChain: LongInt; Name: LongInt; FirstThunk: LongInt; end; TImportNameTableEntry = packed record Hint: Word; Name: TImportFuncName; end; TImport = record LibName, FuncName: TString; end; TImportSectionData = record DirectoryTable: array [1..MAXIMPORTLIBS + 1] of TImportDirectoryTableEntry; LibraryNames: array [1..MAXIMPORTLIBS] of TImportLibName; LookupTable: array [1..MAXIMPORTS + MAXIMPORTLIBS] of LongInt; NameTable: array [1..MAXIMPORTS] of TImportNameTableEntry; NumImports, NumImportLibs: Integer; end; var Headers: THeaders; Import: array [1..MAXIMPORTS] of TImport; ImportSectionData: TImportSectionData; LastImportLibName: TString; ProgramEntryPoint: LongInt; const DOSStub: TDOSStub = ( $4D, $5A, $90, $00, $03, $00, $00, $00, $04, $00, $00, $00, $FF, $FF, $00, $00, $B8, $00, $00, $00, $00, $00, $00, $00, $40, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $80, $00, $00, $00, $0E, $1F, $BA, $0E, $00, $B4, $09, $CD, $21, $B8, $01, $4C, $CD, $21, $54, $68, $69, $73, $20, $70, $72, $6F, $67, $72, $61, $6D, $20, $63, $61, $6E, $6E, $6F, $74, $20, $62, $65, $20, $72, $75, $6E, $20, $69, $6E, $20, $44, $4F, $53, $20, $6D, $6F, $64, $65, $2E, $0D, $0D, $0A, $24, $00, $00, $00, $00, $00, $00, $00 ); procedure Pad(var f: file; Size, Alignment: Integer); var i: Integer; b: Byte; begin b := 0; for i := 0 to Align(Size, Alignment) - Size - 1 do BlockWrite(f, b, 1); end; procedure FillHeaders(CodeSize, InitializedDataSize, UninitializedDataSize, ImportSize: Integer); const IMAGE_FILE_MACHINE_I386 = $14C; IMAGE_FILE_RELOCS_STRIPPED = $0001; IMAGE_FILE_EXECUTABLE_IMAGE = $0002; IMAGE_FILE_32BIT_MACHINE = $0100; IMAGE_SCN_CNT_CODE = $00000020; IMAGE_SCN_CNT_INITIALIZED_DATA = $00000040; IMAGE_SCN_CNT_UNINITIALIZED_DATA = $00000080; IMAGE_SCN_MEM_EXECUTE = $20000000; IMAGE_SCN_MEM_READ = $40000000; IMAGE_SCN_MEM_WRITE = $80000000; begin FillChar(Headers, SizeOf(Headers), #0); with Headers do begin Stub := DOSStub; with PEHeader do begin PE[0] := 'P'; PE[1] := 'E'; Machine := IMAGE_FILE_MACHINE_I386; NumberOfSections := 4; SizeOfOptionalHeader := SizeOf(PEOptionalHeader) + SizeOf(DataDirectories); Characteristics := IMAGE_FILE_RELOCS_STRIPPED or IMAGE_FILE_EXECUTABLE_IMAGE or IMAGE_FILE_32BIT_MACHINE; end; with PEOptionalHeader do begin Magic := $10B; // PE32 MajorLinkerVersion := 3; SizeOfCode := CodeSize; SizeOfInitializedData := InitializedDataSize; SizeOfUninitializedData := UninitializedDataSize; AddressOfEntryPoint := Align(SizeOf(Headers), SECTALIGN) + ProgramEntryPoint; BaseOfCode := Align(SizeOf(Headers), SECTALIGN); BaseOfData := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN); ImageBase := IMGBASE; SectionAlignment := SECTALIGN; FileAlignment := FILEALIGN; MajorOperatingSystemVersion := 4; MajorSubsystemVersion := 4; SizeOfImage := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN) + Align(InitializedDataSize, SECTALIGN) + Align(UninitializedDataSize, SECTALIGN) + Align(ImportSize, SECTALIGN); SizeOfHeaders := Align(SizeOf(Headers), FILEALIGN); Subsystem := 2 + Ord(IsConsoleProgram); // Win32 GUI/console SizeOfStackReserve := $1000000; SizeOfStackCommit := $100000; SizeOfHeapReserve := $1000000; SizeOfHeapCommit := $100000; NumberOfRvaAndSizes := 16; end; with DataDirectories[1] do // Import directory begin VirtualAddress := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN) + Align(InitializedDataSize, SECTALIGN) + Align(UninitializedDataSize, SECTALIGN); Size := ImportSize; end; with CodeSectionHeader do begin Name[0] := '.'; Name[1] := 't'; Name[2] := 'e'; Name[3] := 'x'; Name[4] := 't'; VirtualSize := CodeSize; VirtualAddress := Align(SizeOf(Headers), SECTALIGN); SizeOfRawData := Align(CodeSize, FILEALIGN); PointerToRawData := Align(SizeOf(Headers), FILEALIGN); Characteristics := LongInt(IMAGE_SCN_CNT_CODE or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_EXECUTE); end; with DataSectionHeader do begin Name[0] := '.'; Name[1] := 'd'; Name[2] := 'a'; Name[3] := 't'; Name[4] := 'a'; VirtualSize := InitializedDataSize; VirtualAddress := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN); SizeOfRawData := Align(InitializedDataSize, FILEALIGN); PointerToRawData := Align(SizeOf(Headers), FILEALIGN) + Align(CodeSize, FILEALIGN); Characteristics := LongInt(IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE); end; with BSSSectionHeader do begin Name[0] := '.'; Name[1] := 'b'; Name[2] := 's'; Name[3] := 's'; VirtualSize := UninitializedDataSize; VirtualAddress := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN) + Align(InitializedDataSize, SECTALIGN); SizeOfRawData := 0; PointerToRawData := Align(SizeOf(Headers), FILEALIGN) + Align(CodeSize, FILEALIGN) + Align(InitializedDataSize, FILEALIGN); Characteristics := LongInt(IMAGE_SCN_CNT_UNINITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE); end; with ImportSectionHeader do begin Name[0] := '.'; Name[1] := 'i'; Name[2] := 'd'; Name[3] := 'a'; Name[4] := 't'; Name[5] := 'a'; VirtualSize := ImportSize; VirtualAddress := Align(SizeOf(Headers), SECTALIGN) + Align(CodeSize, SECTALIGN) + Align(InitializedDataSize, SECTALIGN) + Align(UninitializedDataSize, SECTALIGN); SizeOfRawData := Align(ImportSize, FILEALIGN); PointerToRawData := Align(SizeOf(Headers), FILEALIGN) + Align(CodeSize, FILEALIGN) + Align(InitializedDataSize, FILEALIGN); Characteristics := LongInt(IMAGE_SCN_CNT_INITIALIZED_DATA or IMAGE_SCN_MEM_READ or IMAGE_SCN_MEM_WRITE); end; end; end; procedure InitializeLinker; begin FillChar(Import, SizeOf(Import), #0); FillChar(ImportSectionData, SizeOf(ImportSectionData), #0); LastImportLibName := ''; ProgramEntryPoint := 0; end; procedure SetProgramEntryPoint; begin if ProgramEntryPoint <> 0 then Error('Duplicate program entry point'); ProgramEntryPoint := GetCodeSize; end; function AddImportFunc(const ImportLibName, ImportFuncName: TString): LongInt; begin with ImportSectionData do begin Inc(NumImports); if NumImports > MAXIMPORTS then Error('Maximum number of import functions exceeded'); Import[NumImports].LibName := ImportLibName; Import[NumImports].FuncName := ImportFuncName; if ImportLibName <> LastImportLibName then begin Inc(NumImportLibs); if NumImportLibs > MAXIMPORTLIBS then Error('Maximum number of import libraries exceeded'); LastImportLibName := ImportLibName; end; Result := (NumImports - 1 + NumImportLibs - 1) * SizeOf(LongInt); // Relocatable end; end; procedure FillImportSection(var ImportSize, LookupTableOffset: Integer); var ImportIndex, ImportLibIndex, LookupIndex: Integer; LibraryNamesOffset, NameTableOffset: Integer; begin with ImportSectionData do begin LibraryNamesOffset := SizeOf(DirectoryTable[1]) * (NumImportLibs + 1); LookupTableOffset := LibraryNamesOffset + SizeOf(LibraryNames[1]) * NumImportLibs; NameTableOffset := LookupTableOffset + SizeOf(LookupTable[1]) * (NumImports + NumImportLibs); ImportSize := NameTableOffset + SizeOf(NameTable[1]) * NumImports; LastImportLibName := ''; ImportLibIndex := 0; LookupIndex := 0; for ImportIndex := 1 to NumImports do begin // Add new import library if (ImportLibIndex = 0) or (Import[ImportIndex].LibName <> LastImportLibName) then begin if ImportLibIndex <> 0 then Inc(LookupIndex); // Add null entry before the first thunk of a new library Inc(ImportLibIndex); DirectoryTable[ImportLibIndex].Name := LibraryNamesOffset + SizeOf(LibraryNames[1]) * (ImportLibIndex - 1); DirectoryTable[ImportLibIndex].FirstThunk := LookupTableOffset + SizeOf(LookupTable[1]) * LookupIndex; Move(Import[ImportIndex].LibName[1], LibraryNames[ImportLibIndex], Length(Import[ImportIndex].LibName)); LastImportLibName := Import[ImportIndex].LibName; end; // if // Add new import function Inc(LookupIndex); if LookupIndex > MAXIMPORTS + MAXIMPORTLIBS then Error('Maximum number of lookup entries exceeded'); LookupTable[LookupIndex] := NameTableOffset + SizeOf(NameTable[1]) * (ImportIndex - 1); Move(Import[ImportIndex].FuncName[1], NameTable[ImportIndex].Name, Length(Import[ImportIndex].FuncName)); end; end; end; procedure FixupImportSection(VirtualAddress: LongInt); var i: Integer; begin with ImportSectionData do begin for i := 1 to NumImportLibs do with DirectoryTable[i] do begin Name := Name + VirtualAddress; FirstThunk := FirstThunk + VirtualAddress; end; for i := 1 to NumImports + NumImportLibs do if LookupTable[i] <> 0 then LookupTable[i] := LookupTable[i] + VirtualAddress; end; end; procedure LinkAndWriteProgram(const ExeName: TString); var OutFile: TOutFile; CodeSize, ImportSize, LookupTableOffset: Integer; begin if ProgramEntryPoint = 0 then Error('Program entry point not found'); CodeSize := GetCodeSize; FillImportSection(ImportSize, LookupTableOffset); FillHeaders(CodeSize, InitializedGlobalDataSize, UninitializedGlobalDataSize, ImportSize); Relocate(IMGBASE + Headers.CodeSectionHeader.VirtualAddress, IMGBASE + Headers.DataSectionHeader.VirtualAddress, IMGBASE + Headers.BSSSectionHeader.VirtualAddress, IMGBASE + Headers.ImportSectionHeader.VirtualAddress + LookupTableOffset); FixupImportSection(Headers.ImportSectionHeader.VirtualAddress); // Write output file Assign(OutFile, TGenericString(ExeName)); Rewrite(OutFile, 1); if IOResult <> 0 then Error('Unable to open output file ' + ExeName); BlockWrite(OutFile, Headers, SizeOf(Headers)); Pad(OutFile, SizeOf(Headers), FILEALIGN); BlockWrite(OutFile, Code, CodeSize); Pad(OutFile, CodeSize, FILEALIGN); BlockWrite(OutFile, InitializedGlobalData, InitializedGlobalDataSize); Pad(OutFile, InitializedGlobalDataSize, FILEALIGN); with ImportSectionData do begin BlockWrite(OutFile, DirectoryTable, SizeOf(DirectoryTable[1]) * (NumImportLibs + 1)); BlockWrite(OutFile, LibraryNames, SizeOf(LibraryNames[1]) * NumImportLibs); BlockWrite(OutFile, LookupTable, SizeOf(LookupTable[1]) * (NumImports + NumImportLibs)); BlockWrite(OutFile, NameTable, SizeOf(NameTable[1]) * NumImports); end; Pad(OutFile, ImportSize, FILEALIGN); Close(OutFile); end; end.
unit uImpParams; {******************************************************************************* * * * Название модуля : * * * * uImpParams * * * * Назначение модуля : * * * * Организация интерфейса для ввода параметров импорта. * * * * Copyright © Год 2005, Автор: Найдёнов Е.А * * * *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, DB, Halcn6db, uneTypes; type TfmImpParams = class(TForm) dlgDBFFileName : TOpenDialog; lblDocFileName : TLabel; lblProvFileName : TLabel; edtDocFileName : TcxButtonEdit; edtProvFileName : TcxButtonEdit; dstAllDoc : THalcyonDataSet; dstAllProv : THalcyonDataSet; btnOK : TcxButton; btnCancel : TcxButton; procedure btnOKClick (Sender: TObject); procedure FormShortCut (var Msg: TWMKey; var Handled: Boolean); procedure edtDocFileNamePropertiesButtonClick (Sender: TObject; AButtonIndex: Integer); procedure edtProvFileNamePropertiesButtonClick (Sender: TObject; AButtonIndex: Integer); private { Private declarations } public { Public declarations } end; implementation uses uDataModul, uneUtils; resourcestring sMsgErrFieldType = 'Типы полей НД-источника и приёмника не совпадают!'#13'Продолжить процедуру импорта в аварийном режиме?'; sMsgErrParamsNotFound = 'Параметры импорта отсутствуют!'; sMsgErrFieldsNotFound = 'Структура файла-источника данных некорректна!'; sMsgDocFileNotFound = 'Невозможно выполнить импорт данных,'#13'поскольку файл-источник документов не найден!'; sMsgProvFileNotFound = 'Невозможно выполнить импорт данных,'#13'поскольку файл-источник проводок не найден!'; sMsgErrDocFieldType = 'Невозможно выполнить импорт документов, поскольку'#13'типы полей НД-источника и приёмника не совпадают!'; sMsgErrProvFieldType = 'Невозможно выполнить импорт проводок, поскольку'#13'типы полей НД-источника и приёмника не совпадают!'; sMsgErrDocFieldNotFound = 'Невозможно выполнить импорт данных'#13'структура файла-источника документов некорректна!'; sMsgErrProvFieldNotFound = 'Невозможно выполнить импорт данных'#13'структура файла-источника проводок некорректна!'; {$R *.dfm} //Получаем путь к DBF-файлу документов procedure TfmImpParams.edtDocFileNamePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin dlgDBFFileName.Execute; edtDocFileName.Text := dlgDBFFileName.FileName; end; //Получаем путь к DBF-файлу проводок procedure TfmImpParams.edtProvFileNamePropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); begin dlgDBFFileName.Execute; edtProvFileName.Text := dlgDBFFileName.FileName; end; //Выполняем проверку корректности параметров импорта procedure TfmImpParams.btnOKClick(Sender: TObject); var ModRes : Integer; DocResult : TImportCheckError; ProvResult : TImportCheckError; DocFileName : TFileName; ProvFileName : TFileName; begin DocFileName := edtDocFileName.Text; ProvFileName := edtProvFileName.Text; //Проверяем наличие DBF-файла документов if not FileExists( DocFileName ) then begin ModalResult := mrNone; MessageBox( Handle, PChar( sMsgDocFileNotFound ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; //Проверяем наличие DBF-файла проводок if not FileExists( ProvFileName ) then begin ModalResult := mrNone; MessageBox( Handle, PChar( sMsgProvFileNotFound ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; //Проверяем соответствие полей НД документов и проводок параметрам процедуры импорта DocResult := CheckDBFStructure( dstAllDoc, DocFileName, cProcImpDocFields, [ sMsgErrDocFieldNotFound, sMsgErrDocFieldType ], Handle ); ProvResult := CheckDBFStructure( dstAllProv, ProvFileName, cProcImpProvFields, [ sMsgErrProvFieldNotFound, sMsgErrProvFieldType ], Handle ); if not( ( DocResult = ectNone ) AND ( ProvResult = ectNone ) ) then begin //Оповещаем пользователя о несоответствии типов полей НД-источника и приёмника if ( DocResult = ectFTIcompatible ) OR ( ProvResult = ectFTIcompatible ) then begin ModRes := MessageBox( Handle, PChar( sMsgErrFieldType ), PChar( sMsgCaptionWrn ), MB_YESNO or MB_ICONWARNING ); //Завершам(продолжаем) импорт(в аварийном режиме) if ModRes = ID_NO then begin ModalResult := mrNone; Exit; end else begin end; end else begin ModalResult := mrNone; //Оповещаем пользователя о причинах, препятствующих продолжению импорта if ( DocResult = ectFNUnknown ) OR ( ProvResult = ectFNUnknown ) then MessageBox( Handle, PChar( sMsgErrFieldsNotFound ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ) else MessageBox( Handle, PChar( sMsgErrParamsNotFound ), PChar( sMsgCaptionErr ), MB_OK or MB_ICONERROR ); Exit; end; end; end; //Обрабатываем нажатие "горячих" клавиш procedure TfmImpParams.FormShortCut(var Msg: TWMKey; var Handled: Boolean); begin case Msg.CharCode of VK_F10 : begin btnOK.Click; Handled := True; end; VK_ESCAPE : begin btnCancel.Click; Handled := True; end; end; end; end.