text
stringlengths
14
6.51M
unit UxlEdit; interface uses Windows, Messages, UxlWinControl, UxlClasses, UxlFunctions, UxlStrUtils, CommDlg; type TxlEditControl = class (TxlControl) private procedure f_SetReadOnly (b_readonly: boolean); procedure f_SetModify (value: boolean); function f_GetModify (): boolean; procedure f_SetSelText (const value: widestring); function f_PeekLineText (l_line: integer; var s: widestring; var c: widechar; var m: integer): integer; protected FOnChange: TNotifyEvent; FReadOnly: boolean; FTabStops: integer; FWordWrap: boolean; procedure OnCreateControl (); override; procedure ReCreate (); override; procedure f_SetWordWrap (value: boolean); procedure f_SetTabStops (value: integer); function f_GetLineNumber (): integer; function f_GetLineCharIndex (i_line: integer): integer; function f_GetSelText (): widestring; virtual; function f_GetSelLineText (): widestring; procedure f_SetSelLineText (const value: widestring); function f_GetLine (i_linenumber: integer): widestring; procedure f_OnChange (); property TabStops: integer read FTabStops write f_SetTabStops; property LineNumber: integer read f_GetLineNumber; // 包括wordwrap造成的非物理行 property LineText: widestring read f_GetSelLineText write f_SetSelLineText; // 物理行 property Lines[index: integer]: widestring read f_GetLine; default; public procedure Clear (); procedure Undo (); procedure Redo (); virtual; procedure SelectAll (); procedure Cut (); procedure Copy (); procedure Paste (); procedure DeleteSel (); function CanClear (): boolean; function CanUndo (): boolean; function CanRedo (): boolean; virtual; // function CanSelAll (): boolean; function CanCut (): boolean; function CanCopy (): boolean; function CanPaste (): boolean; function IsEmpty (): boolean; procedure GetSel (var i_start, i_length: integer); virtual; procedure SetSel (i_start, i_length: integer); virtual; procedure LocateLine (var i_start, i_end: integer; i_linenumber: integer = -1); function TextCount (b_withcrlf: boolean = true): cardinal; virtual; function LineCount (): cardinal; procedure ClearUndoBuffer (); procedure AddLine (const s: widestring = ''; b_noemptyline: boolean = false); procedure LoadFromFile (const s_file: widestring); function ProcessCommand (dwEvent: WORD): DWORD; override; property WordWrap: boolean read FWordWrap write f_setwordwrap; property OnChange: TNotifyEvent read FOnChange write FOnchange; property ReadOnly: boolean read FReadOnly write f_setreadonly; property MOdified: boolean read f_getmodify write f_setmodify; property SelText: widestring read f_GetSelText write f_SetSelText; end; type TxlEdit = class (TxlEditControl) protected function DoCreateControl (HParent: HWND): HWND; override; public end; type TMaskType = (msNumber, msPassword); type TxlMaskEdit = class (TxlEdit) public procedure SetMaskType (ms: TMaskType); end; type TxlMemo = class (TxlEditControl) private protected function DoCreateControl (HParent: HWND): HWND; override; public // property WordWrap: boolean read FWordWrap write f_setwordwrap; property TabStops: integer read FTabStops write f_SetTabStops; property LineNumber: integer read f_GetLineNumber; property LineText: widestring read f_GetSelLineText write f_SetSelLineText; property Lines[index: integer]: widestring read f_GetLine; default; end; implementation uses UxlCommDlgs, UxlMath, UxlList; procedure TxlEditControl.OnCreateControl (); begin FTabStops := 8; end; procedure TxlEditControl.ReCreate (); var b_modified: boolean; b_readonly: boolean; i_tabstops: integer; begin b_modified := Modified; b_readonly := ReadOnly; i_tabstops := TabStops; inherited ReCreate (); ReadOnly := b_ReadOnly; TabStops := i_TabStops; Modified := b_modified; end; procedure TxlEditControl.f_SetWordWrap (value: boolean); begin if FWordWrap <> value then begin FWordWrap := value; ReCreate(); end; end; procedure TxlEditControl.f_SetReadOnly (b_readonly: boolean); begin Perform (EM_SETREADONLY, BoolToInt(b_readonly), 0); FReadOnly := b_readonly; f_OnChange; end; procedure TxlEditControl.f_SetModify (value: boolean); begin Perform (EM_SETMODIFY, BoolToInt(value), 0); end; function TxlEditControl.f_GetModify (): boolean; begin result := IntToBool (Perform (EM_GETMODIFY, 0, 0)); end; function TxlEditControl.f_PeekLineText (l_line: integer; var s: widestring; var c: widechar; var m: integer): integer; var n: integer; begin m := f_GetLineCharIndex (l_line); n := 0; if m < TextCount (false) then n := Perform (EM_LINELENGTH, m, 0); setlength (s, n + 1); pword(s)^ := n + 1; Perform (EM_GETLINE, l_line, dword(pwidechar(s))); c := s[n + 1]; setlength (s, n); result := n; end; function TxlEditControl.f_GetSelLineText (): widestring; begin result := f_GetLine (LineNumber); end; procedure TxlEditControl.f_SetSelLineText (const value: widestring); var i_start, i_end: integer; begin LocateLine (i_start, i_end); SetSel (i_start, i_end - i_start); SelText := value; end; function TxlEditControl.f_GetLine (i_linenumber: integer): widestring; var i, j, m, n: integer; s: widestring; c: widechar; begin result := ''; if i_linenumber >= LineCount then exit; n := Perform (EM_GETLINECOUNT, 0, 0); i := i_linenumber; j := i; repeat f_PeekLineText (j, s, c, m); result := result + s; inc (j); until (c = #13) or (c = #11) or (j = n); while i > 0 do begin dec (i); f_PeekLineText (i, s, c, m); if (c = #13) or (c = #11) then break; result := s + result; end; end; procedure TxlEditControl.LocateLine (var i_start, i_end: integer; i_linenumber: integer = -1); var i, j, n, o, i_len: integer; s: widestring; c: widechar; begin n := Perform (EM_GETLINECOUNT, 0, 0); if i_linenumber < 0 then i_linenumber := LineNumber; i := i_linenumber; j := i; repeat i_len := f_PeekLineText (j, s, c, o); if j = i then i_start := o; i_end := o + i_len; inc (j); until (c = #13) or (c = #11) or (j = n); while i > 0 do begin dec (i); f_PeekLineText (i, s, c, o); if (c = #13) or (c = #11) then break; i_start := o; end; end; function TxlEditControl.f_GetLineNumber (): integer; var o_point, o_point2: TPoint; i_char: integer; begin // result := Perform (EM_LINEFROMCHAR, dword(-1), 0); // 对于最后一行,会有问题 GetCaretPos (o_point); i_char := Perform (EM_CHARFROMPOS, 0, lparam(@o_point)); result := Perform (EM_LINEFROMCHAR, i_char, 0); Perform (EM_POSFROMCHAR, wparam(@o_point2), i_char); if o_point2.y < o_point.y then inc (result); end; function TxlEditControl.f_GetLineCharIndex (i_line: integer): integer; begin result := Perform (EM_LINEINDEX, i_line, 0); end; procedure TxlEditControl.f_SetTabStops (value: integer); var pi: pdword; begin new (pi); pi^ := value * 5; Perform (EM_SETTABSTOPS, 1, dword(pi)); dispose (pi); FTabStops := value; end; procedure TxlEditControl.Clear (); begin SetRedraw (false); SelectAll (); Perform (WM_CLEAR, 0, 0); SetRedraw (true); end; procedure TxlEditControl.Undo (); begin Perform (EM_UNDO, 0, 0); end; procedure TxlEditControl.Redo (); begin Undo (); end; procedure TxlEditControl.SelectAll (); begin SetFocus; SetSel (0, TextLength); end; procedure TxlEditControl.Cut (); begin Perform (WM_CUT, 0, 0); end; procedure TxlEditControl.Copy (); begin Perform (WM_COPY, 0, 0); end; procedure TxlEditControl.Paste (); begin Perform (WM_PASTE, 0, 0); end; procedure TxlEditControl.DeleteSel (); begin Perform (WM_CLEAR); end; function TxlEditControl.CanClear (): boolean; begin result := (not readonly) and (not IsEmpty); end; function TxlEditControl.CanUndo (): boolean; begin result := (Perform(EM_CANUNDO, 0, 0) <> 0); end; function TxlEditControl.CanRedo (): boolean; begin result := CanUndo (); end; //function TxlEditControl.CanSelAll (): boolean; //var i_start, i_sellength: integer; //begin // if IsEmpty then // result := false // else // begin // GetSel (i_start, i_sellength); // if i_start > 0 then // result := true // else // result := (i_sellength < TextCount); // end; //end; function TxlEditControl.CanCut (): boolean; begin result := (not ReadOnly) and CanCopy; end; function TxlEditControl.CanCopy (): boolean; var i, j: integer; begin GetSel (i, j); result := not (j = 0); end; function TxlEditControl.CanPaste (): boolean; begin result := (not ReadOnly) and IsClipboardFormatAvailable (CF_UNICODETEXT); end; function TxlEditControl.IsEmpty (): boolean; begin result := (TextLength <= 0); end; function TxlEditControl.TextCount (b_withcrlf: boolean = true): cardinal; begin result := length (Text); end; function TxlEditControl.LineCount (): cardinal; begin result := Perform ( EM_GETLINECOUNT, 0, 0 ); end; procedure TxlEditControl.ClearUndoBuffer (); begin Perform (EM_EMPTYUNDOBUFFER, 0, 0); end; procedure TxlEditControl.GetSel (var i_start, i_length: integer); var i_end: integer; begin Perform (EM_GETSEL, dword(@i_start), dword(@i_end)); i_length := i_end - i_start; end; procedure TxlEditControl.SetSel (i_start, i_length: integer); begin Perform (EM_SETSEL, i_start, i_start + i_length); end; function TxlEditControl.f_GetSelText (): widestring; var i_start, i_length: integer; begin GetSel (i_start, i_length); result := MidStr (text, i_start, i_length); end; procedure TxlEditControl.f_SetSelText (const value: widestring); begin Perform (EM_REPLACESEL, 1, dword(pwidechar(value))); end; procedure TxlEditcontrol.AddLine (const s: widestring = ''; b_noemptyline: boolean = false); var s_text: widestring; begin s_text := Text; if b_noemptyline then while rightstr(s_text, 2) = #13#10 do s_text := leftstr (s_text, length(s_text) - 2); if (s_text <> '') and (rightstr(s_text, 2) <> #13#10) then s_text := s_text + #13#10; s_text := s_text + s; Text := s_text; end; procedure TxlEditControl.LoadFromFile (const s_file: widestring); var sl: TxlStrList; begin sl := TxlStrList.Create; sl.LoadFromFile (s_file); self.Text := sl.Text; sl.free; end; function TxlEditControl.ProcessCommand (dwEvent: WORD): DWORD; begin result := 0; case dwEvent of EN_UPDATE: f_OnChange; end; end; procedure TxlEditControl.f_OnChange (); begin if assigned (FOnChange) then FOnChange (self); end; //----------------------- function TxlEdit.DoCreateControl (HParent: HWND): HWND; begin result := CreateWin32Control (HParent, 'edit', ES_LEFT or ES_AUTOHSCROLL, WS_EX_CLIENTEDGE); end; //------------------------ procedure TxlMaskEdit.SetMaskType (ms: TMaskType); begin SetWndStyle (ES_Number, (ms = msNumber)); SetWndStyle (ES_Password, (ms = msPassword)); end; //------------------------ function TxlMemo.DoCreateControl (HParent: HWND): HWND; var i_style: DWord; begin i_Style := ES_LEFT or ES_MULTILINE or ES_AUTOVSCROLL or ES_WANTRETURN or WS_VSCROLL; if not FWordWrap then i_style := i_style or ES_AUTOHSCROLL or WS_HSCROLL; result := CreateWin32Control (HParent, 'edit', i_style, WS_EX_CLIENTEDGE); end; end.
unit FirmaDigitale2; interface uses Classes,IInterface,FirmaDigitale,AstaClientDataset; type TDll = record DllPath: string; PrivateKey: string; Controllo: boolean; end; TFirmaKrill = class(TFirmaDigitale) private DllPath: array of TDll; DLLLoaded: Boolean; { is DLL (dynamically) loaded already? } DLLHandle: THandle; ErrorMode: Integer; Env: Pointer; procedure LoadDLL; procedure SettaSlot; public constructor Create( tf: Integer; DllFirma: TAstaClientDataSet); destructor Destroy; override; function Firma(PassPhrase: string; Nominativo: string; MyStream: TMemoryStream; OutStream: TMemoryStream; var ErrString: string): TpResultFirma; override; procedure ApriSessione(PassPhrase: string); override; procedure ChiudiSessione; override; function LeggiOwner: string; override; function DecodeStream(MyStream: TMemoryStream; OutStream: TMemoryStream): integer; override; end; // function FirmaDecodErrore( const funzione: string; cod: integer ): string; var KpkiInit: function: Pointer cdecl stdcall; KpkiSetPrivateKey: function(nFile: PChar; Format: char; Env: Pointer): Integer cdecl stdcall; KpkiSetUserCertificate: function(Loc: Char; Id: PChar; Env: Pointer): Integer cdecl stdcall; KpkiSignFile: function(FileToSign: PChar; FileSigned: PChar; password: PChar; Env: Pointer): Integer cdecl stdcall; KpkiVerifyFile: function(FileToVerify: PChar; FileVerified: PChar; Env: Pointer): Integer cdecl stdcall; KpkiFree: function(x: Pointer): Integer cdecl stdcall; KpkiSetCACertificate: function(Loc: Char; Id: PChar; Env: Pointer): Integer cdecl stdcall; KpkiSignData: function(DataToSign: PChar; var DataSigned: PChar; DataLength: Integer; var DataSignedLength: Integer; password: PChar; Env: Pointer): Integer cdecl stdcall; KpkiVerifyData: function(DataToVerify: PChar; var DataVerified: PChar; length: Integer; var Verifiedlength: Integer; Env: Pointer): Integer cdecl stdcall; // KpkiGetTokenPubKey: function(PinCode: PChar; var pubKey: PChar; pubKeyLen: integer; Env: Pointer): Integer cdecl stdcall; KpkiClose: function(Env: Pointer): Integer cdecl stdcall; KpkiGetDestCertSerial: function(Env: Pointer): Integer cdecl stdcall; KpkiSetSCEngine: function(Env: Pointer; DllName: PChar; SlotID: SmallInt): Integer cdecl stdcall; KpkiSetSCModule: function(ModuleName: PChar; Env: Pointer): Integer cdecl stdcall; KpkiSetSCSlot: function(SlotId: Integer; Env: Pointer): Integer cdecl stdcall; KpkiSetKeepPKCS11Login: function(SlotId: Integer; Env: Pointer): Integer cdecl stdcall; KpkiGetDestCertDN: function(Env: Pointer): PChar cdecl stdcall; KpkiGetVerifyCertDescription: function(Env: Pointer): PChar cdecl stdcall; KpkiGetDestCertIssuer: function(Env: Pointer): PChar cdecl stdcall; KpkiGetVerifyCertDN: function(Env: Pointer): PChar cdecl stdcall; KpkiGetVerifyCertValidity: function(Env: Pointer): TDateTime cdecl stdcall; KpkiGetVerifyCertNotBefore: function(Env: Pointer): TDateTime cdecl stdcall; kpkiErrorMessagesArray: array of string; var Tipo: integer; const maxNrErrori = 197; implementation uses Forms,Controls,sysutils,Windows,DMCommon,Msgdlgs; constructor TFirmaKrill.Create( tf: Integer; DllFirma: TAstaClientDataSet); //var // tmp: WideString; begin Env := nil; DLLLoaded := False; FTipoFirma := tf; try DllFirma.Open; SetLength(DllPath,DllFirma.RecordCount); while not DllFirma.eof do begin DllPath[DllFirma.FieldbyName('TIPO_CARTA').AsInteger].DllPath := DllFirma.FieldbyName('DLL_NAME').AsString; if not DllFirma.FieldbyName('PRIVATE_KEY').IsNull then begin DllPath[DllFirma.FieldbyName('TIPO_CARTA').AsInteger].PrivateKey := DllFirma.FieldbyName('PRIVATE_KEY').AsString; DllPath[DllFirma.FieldbyName('TIPO_CARTA').AsInteger].Controllo := true; end else begin DllPath[DllFirma.FieldbyName('TIPO_CARTA').AsInteger].PrivateKey := gblcodfisc; DllPath[DllFirma.FieldbyName('TIPO_CARTA').AsInteger].Controllo := false; end; DllFirma.Next; end; FSessioneAperta := False; FAttivata := True; except on E:Exception do begin FAttivata := False; MsgDlg(E.Message, '', ktError, [kbOk], dfFirst); end; end; end; destructor TFirmaKrill.Destroy; begin if DLLLoaded then FreeLibrary(DLLHandle); inherited; end; const KPKI_P12 = #1; KPKIONFILE = #1; KPKIONSC = #4; KPKI_PINPROTECTED = #4; KPKI_P12_ON_SC = #6; { DllPath1 = '.\IpmPki32_1202.dll'; // -- driver del lettore smartcard: versione 1202 DllPath2 = '.\IpmPki32.dll'; // -- driver del lettore smartcard: versione 1203 DllPath3 = '.\cvP11_M4.dll'; // -- driver del lettore smartcard: versione 16xx => Sign_Keypair0 DllPath4 = '.\incryptoki2.dll'; // -- driver del lettore smartcard: versione 1204 => DS0 DllPath5 = '.\SI_PKCS11.dll'; // -- driver del lettore smartcard: versione 14/15 Siemens => DS0 } procedure TFirmaKrill.LoadDLL; begin if DLLLoaded then Exit; ErrorMode := SetErrorMode($8000{SEM_NoOpenFileErrorBox}); DLLHandle := LoadLibrary('KPKI.DLL'); if DLLHandle >= 32 then begin DLLLoaded := True; @KpkiInit := GetProcAddress(DLLHandle,'KpkiInit'); {$IFDEF WIN32} Assert(@KpkiInit <> nil); {$ENDIF} @KpkiSetPrivateKey := GetProcAddress(DLLHandle,'KpkiSetPrivateKey'); {$IFDEF WIN32} Assert(@KpkiSetPrivateKey <> nil); {$ENDIF} @KpkiSetUserCertificate := GetProcAddress(DLLHandle,'KpkiSetUserCertificate'); {$IFDEF WIN32} Assert(@KpkiSetUserCertificate <> nil); {$ENDIF} @KpkiSignFile := GetProcAddress(DLLHandle,'KpkiSignFile'); {$IFDEF WIN32} Assert(@KpkiSignFile <> nil); {$ENDIF} @KpkiVerifyFile := GetProcAddress(DLLHandle,'KpkiVerifyFile'); {$IFDEF WIN32} Assert(@KpkiVerifyFile <> nil); {$ENDIF} @KpkiFree := GetProcAddress(DLLHandle,'KpkiFree'); {$IFDEF WIN32} Assert(@KpkiFree <> nil); {$ENDIF} @KpkiSetCACertificate := GetProcAddress(DLLHandle,'KpkiSetCACertificate'); {$IFDEF WIN32} Assert(@KpkiSetCACertificate <> nil); {$ENDIF} @KpkiSignData := GetProcAddress(DLLHandle,'KpkiSignData'); {$IFDEF WIN32} Assert(@KpkiSignData <> nil); {$ENDIF} @KpkiVerifyData := GetProcAddress(DLLHandle,'KpkiVerifyData'); {$IFDEF WIN32} Assert(@KpkiVerifyData <> nil); {$ENDIF} @KpkiClose := GetProcAddress(DLLHandle,'KpkiClose'); {$IFDEF WIN32} Assert(@KpkiClose <> nil); {$ENDIF} (* @KpkiGetTokenPubKey := GetProcAddress(DLLHandle,'KpkiGetTokenPubKey'); {$IFDEF WIN32} Assert(@KpkiGetTokenPubKey <> nil); {$ENDIF} *) @KpkiGetDestCertSerial := GetProcAddress(DLLHandle,'KpkiGetDestCertSerial'); {$IFDEF WIN32} Assert(@KpkiGetDestCertSerial <> nil); {$ENDIF} @KpkiGetDestCertDN := GetProcAddress(DLLHandle,'KpkiGetDestCertDN'); {$IFDEF WIN32} Assert(@KpkiGetDestCertDN <> nil); {$ENDIF} @KpkiGetVerifyCertDescription := GetProcAddress(DLLHandle,'KpkiGetVerifyCertDescription'); {$IFDEF WIN32} Assert(@KpkiGetVerifyCertDescription <> nil); {$ENDIF} @KpkiGetDestCertIssuer := GetProcAddress(DLLHandle,'KpkiGetDestCertIssuer'); {$IFDEF WIN32} Assert(@KpkiGetDestCertIssuer <> nil); {$ENDIF} @KpkiGetVerifyCertDN := GetProcAddress(DLLHandle,'KpkiGetVerifyCertDN'); {$IFDEF WIN32} Assert(@KpkiGetVerifyCertDN <> nil); {$ENDIF} @KpkiGetVerifyCertValidity := GetProcAddress(DLLHandle,'KpkiGetVerifyCertValidity'); {$IFDEF WIN32} Assert(@KpkiGetVerifyCertValidity <> nil); {$ENDIF} @KpkiGetVerifyCertNotBefore := GetProcAddress(DLLHandle,'KpkiGetVerifyCertNotBefore'); {$IFDEF WIN32} Assert(@KpkiGetVerifyCertNotBefore <> nil); {$ENDIF} @KpkiSetSCEngine := GetProcAddress(DLLHandle,'KpkiSetSCEngine'); {$IFDEF WIN32} Assert(@KpkiSetSCEngine <> nil); {$ENDIF} @KpkiSetSCModule := GetProcAddress(DLLHandle,'KpkiSetSCModule'); {$IFDEF WIN32} Assert(@KpkiSetSCModule <> nil); {$ENDIF} @KpkiSetSCSlot := GetProcAddress(DLLHandle,'KpkiSetSCSlot'); {$IFDEF WIN32} Assert(@KpkiSetSCSlot <> nil); {$ENDIF} end else begin DLLLoaded := False; { Error: Kpki.DLL could not be loaded !! } end; SetErrorMode(ErrorMode) end {LoadDLL}; function FirmaDecodErrore( const funzione: string; cod: integer ): string; begin if (-cod>=0) and (-cod<maxNrErrori) then result := kpkiErrorMessagesArray[-cod] else result := format('Errore durante la firma (funzione %s - codice %d)',[funzione,cod]); end; function TFirmaKrill.DecodeStream(MyStream: TMemoryStream; OutStream: TMemoryStream): integer; var DataSigned: PChar; DataSignedLength: Integer; begin Screen.Cursor := crHourGlass; try if not Assigned(Env) then begin ApriSessione(''); end; { if SettaSlot(ErrString)<>0 then exit; } MyStream.Position := 0; result := KpkiVerifyData(MyStream.Memory, DataSigned, MyStream.Size, DataSignedLength, Env); OutStream.Position := 0; OutStream.WriteBuffer(DataSigned[0],DataSignedLength); OutStream.Position := 0; try KpkiFree(DataSigned); except // KpkiClose(Env); end; if not ((result=0) or (result=-77)) then begin raise Exception.Create(FirmaDecodErrore('KpkiVerifyData',result)); end else result := 0; Screen.Cursor := crDefault; except on E:Exception do begin Screen.Cursor := crDefault; result := -1; MsgDlg(E.Message, '', ktError, [kbOk], dfFirst); end; end; end; procedure TFirmaKrill.SettaSlot; var result: Integer; begin try { result := KpkiGetDestCertSerial ( Env ); if result=0 then begin raise Exception.Create( := 'Nessun certificato nella smartcard'; raise Exception.Create(raise Exception.Create(); end; } if Length(DllPath)=0 then begin result := -196; raise Exception.Create( FirmaDecodErrore('DllPath',result) ); end; result := KpkiSetSCEngine(Env,PChar(DllPath[Tipo].DllPath),0); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetSCEngine',result) ); end; result := KpkiSetSCModule (PChar(DllPath[Tipo].DllPath), Env ); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetSCModule',result) ); end; result := KpkiSetSCSlot( 1, Env ); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetSCSlot',result) ); end; result := KpkiSetUserCertificate(KpkiONSC, PChar(DllPath[Tipo].PrivateKey) {PChar(UserCertificate)}, Env); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetUserCertificate',result) ); end; result := KpkiSetCACertificate (KpkiONSC, PChar(DllPath[Tipo].PrivateKey) {PChar(CACertificate)}, Env); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetCACertificate',result) ); end; result := KpkiSetPrivateKey (PChar(DllPath[Tipo].PrivateKey) {PChar(PrivateKey)}, Kpki_P12_ON_SC, Env); if result<>0 then begin raise Exception.Create( FirmaDecodErrore('KpkiSetPrivateKey',result) ); end; except on E:Exception do begin MsgDlg(E.Message, '', ktError, [kbOk], dfFirst); end; end; end; procedure TFirmaKrill.ApriSessione(PassPhrase: string); begin try if not FSessioneAperta and FAttivata then begin {Perform logon} if not DLLLoaded then begin LoadDLL; if not DLLLoaded then raise Exception.Create('KPKI.DLL non trovata'); end; Env := KpkiInit(); if not Assigned(Env) then raise Exception.Create('Errore in KpkiInit'); FSessioneAperta := True; end else begin raise Exception.Create(RS_SmartcardNonDisp); end; except on E:Exception do begin MsgDlg(E.Message, '', ktError, [kbOk], dfFirst); FSessioneAperta := False; end; end; end; procedure TFirmaKrill.ChiudiSessione; begin if Env<>nil then begin // -- Access Violation in chiusura ! { try KpkiClose(Env); except end; } Env := nil; {res :=} FreeLibrary(DLLHandle); DLLLoaded := False; end; FSessioneAperta := False; end; function TFirmaKrill.Firma(PassPhrase: string; Nominativo: string; MyStream: TMemoryStream; OutStream: TMemoryStream; var ErrString: string): TpResultFirma; var DataSignedLength: Integer; DataSigned: PChar; DataVerifiedLength: Integer; DataVerified: PChar; temp: string; // DataInizioValidita,DataFineValidita: TDateTime; res: Integer; begin Screen.Cursor := crHourGlass; // result := -9999; if not FSessioneAperta then ApriSessione(''); SettaSlot; try // -- inizio firma su stream... res := KpkiSignData(MyStream.Memory, DataSigned, MyStream.Size, DataSignedLength, PChar(PassPhrase), Env); if res<>0 then begin ErrString := FirmaDecodErrore('KpkiSignData',res); ChiudiSessione; result := tprErrore; // raise Exception.Create(ErrString); // exit; end else begin result := tprOk; OutStream.WriteBuffer(DataSigned[0],DataSignedLength); OutStream.Position := 0; // try KpkiFree(DataSigned); // except // end; { res :=} KpkiVerifyData(OutStream.Memory, DataVerified, OutStream.Size, DataVerifiedLength, Env); if res<>0 then begin result := tprErrore; ErrString := FirmaDecodErrore('KpkiVerifyData',res); // raise Exception.Create(ErrString); // exit; end else begin result := tprOk; // try KpkiFree(DataVerified); // except // end; // -- verifico l'utente if DllPath[Tipo].Controllo then begin temp := KpkiGetVerifyCertDN(Env); if (Nominativo<>'') and (Pos(Nominativo,temp)=0) then begin result := tprErrore; res := -194; ErrString := format(FirmaDecodErrore('KpkiGetVerifyCertDN',res),[temp]); end else begin (* // -- verifico la validità del certificato DataInizioValidita := KpkiGetVerifyCertNotBefore(Env); DataFineValidita := KpkiGetVerifyCertValidity(Env); if {(Date()<DataInizioValidita) or} (Date()>DataFineValidita) then begin result := -195; ErrString := format( FirmaDecodErrore('KpkiGetVerifyCertValidity',result), [DateTimeToStr(DataInizioValidita),DateTimeToStr(DataFineValidita)]); end; *) end; end; end; end; { if result<>0 then begin ErrString := FirmaDecodErrore('KpkiClose',result); raise Exception.Create(ErrString); end; } { if result=-47 then begin ChiudiSessione; FDMCommon.PassPhrase := ''; end; } finally // ChiudiSessione({Env}); end; Screen.Cursor := crDefault; end; function TFirmaKrill.LeggiOwner: string; var DataSignedLength: Integer; DataSigned: PChar; DataVerifiedLength: Integer; DataVerified: PChar; // temp: string; // DataInizioValidita,DataFineValidita: TDateTime; MyStream: TMemoryStream; OutStream: TMemoryStream; ErrString: string; res: integer; xPassPhrase: string; begin if not Assigned(Env) then begin ApriSessione(''); end; SettaSlot; MyStream := TMemoryStream.Create;; OutStream:= TMemoryStream.Create; try // -- inizio firma su stream... res := KpkiSignData(MyStream.Memory, DataSigned, MyStream.Size, DataSignedLength, PChar(xPassPhrase), Env); if res<>0 then begin ErrString := FirmaDecodErrore('KpkiSignData',res); ChiudiSessione; raise Exception.Create(ErrString); end else begin OutStream.WriteBuffer(DataSigned[0],DataSignedLength); OutStream.Position := 0; // try KpkiFree(DataSigned); // except // end; { res :=} KpkiVerifyData(OutStream.Memory, DataVerified, OutStream.Size, DataVerifiedLength, Env); if res<>0 then begin ErrString := FirmaDecodErrore('KpkiVerifyData',res); raise Exception.Create(ErrString); end else begin // try KpkiFree(DataVerified); // except // end; // -- verifico l'utente result := KpkiGetVerifyCertDN(Env); end; end; finally MyStream.Free; OutStream.Free; end; end; initialization SetLength(kpkiErrorMessagesArray,maxNrErrori); kpkiErrorMessagesArray[0] := 'Operazione riuscita correttamente'; kpkiErrorMessagesArray[1] := 'KPKI non è stato inizializzato'; kpkiErrorMessagesArray[2] := 'Errore nell''allocazione della memoria'; kpkiErrorMessagesArray[3] := 'Il meccanismo non è supportato dalla smartcard'; kpkiErrorMessagesArray[4] := 'Non è stato specificato l''algoritmo asimmetrico'; kpkiErrorMessagesArray[5] := 'Non è stato specificato l''algoritmo di firma'; kpkiErrorMessagesArray[6] := 'Non è stato specificato l''algoritmo simmetrico'; kpkiErrorMessagesArray[7] := 'Non è supportata questa lunghezza per la chiave asimmetrica'; kpkiErrorMessagesArray[8] := 'Non è supportata questa lunghezza per la chiave simmetrica'; kpkiErrorMessagesArray[9] := 'Non è stata specificata la versione del protocollo ldap'; kpkiErrorMessagesArray[10] := 'Non è stato specificato il formato per la richiesta del certificato'; kpkiErrorMessagesArray[11] := 'Non è stato specificato il formato della chiave privata'; kpkiErrorMessagesArray[12] := 'Non è stato specificato il nome o la locazione del certificato'; kpkiErrorMessagesArray[13] := 'La lunghezza della chiave non è supportata dalla smartcard'; kpkiErrorMessagesArray[14] := 'E'' fallito il caricamento del certificato crittato'; kpkiErrorMessagesArray[15] := 'La chiave privata non può essere estratta dalla smartcard'; kpkiErrorMessagesArray[16] := 'Non è stato specificato il motore di crittazione'; kpkiErrorMessagesArray[17] := 'Non è stato specificato se si vuole usare LDAP'; kpkiErrorMessagesArray[18] := 'Non è stato specificato l''indirizzo del server X500'; kpkiErrorMessagesArray[19] := 'Non è stato specificato quale certificato cercare sul server X500'; kpkiErrorMessagesArray[20] := 'Errore nella decrittazione della chiave pubblica RSA'; kpkiErrorMessagesArray[21] := 'I dati crittati non sono in formato PKCS#7'; kpkiErrorMessagesArray[22] := 'I dati in formato PKCS#7 non sono stati imbustati'; kpkiErrorMessagesArray[23] := 'Errore nella decrittazione della chiave simmetrica'; kpkiErrorMessagesArray[24] := 'Errore nella lettura del file di input'; kpkiErrorMessagesArray[25] := 'Il file di input non è stato specificato oppure è vuoto'; kpkiErrorMessagesArray[26] := 'Non e stata specificata la password'; kpkiErrorMessagesArray[27] := 'Non è stato specificato il nome della chiave privata'; kpkiErrorMessagesArray[28] := 'Non è stato specificato il file di output'; kpkiErrorMessagesArray[29] := 'Errore nella creazione del file di output'; kpkiErrorMessagesArray[30] := 'Non ci sono dati in ingresso oppure la lunghezza dei dati in ingresso è nulla'; kpkiErrorMessagesArray[31] := 'Non è stata impostata la chiave privata'; kpkiErrorMessagesArray[32] := 'Errore nella lettura del file della chiave privata'; kpkiErrorMessagesArray[33] := 'Il file di input contenente la chiave privata non è in formato PKCS#12'; kpkiErrorMessagesArray[34] := 'Password errata'; kpkiErrorMessagesArray[35] := 'La chiave PKCS#8 selezionata non supporta l''algoritmo RSA'; kpkiErrorMessagesArray[36] := 'E'' fallita la generazione della chiave'; kpkiErrorMessagesArray[37] := 'Errore nella creazione di un oggetto PKCS#12'; kpkiErrorMessagesArray[38] := 'Errore nella scrittura su un file di output'; kpkiErrorMessagesArray[39] := 'Errore nella creazione di un oggetto PKCS#8'; kpkiErrorMessagesArray[40] := 'Errore nel caricamento della libreria per la smartcard'; kpkiErrorMessagesArray[41] := 'Errore nell''accesso ad una funzione della smartcard'; kpkiErrorMessagesArray[42] := 'E'' fallito l''accesso alla lista delle funzioni della smartcard'; kpkiErrorMessagesArray[43] := 'E'' fallita l''inizializzazione della smartcard'; kpkiErrorMessagesArray[44] := 'E'' fallita l''apertura di sessione della smartcard'; kpkiErrorMessagesArray[45] := 'E'' fallita la chiusura di sessione della smartcard'; kpkiErrorMessagesArray[46] := 'E'' fallita la chiusura della smartcard'; kpkiErrorMessagesArray[47] := 'E'' fallito il login sulla smartcard. Al terzo fallimento consecutivo la SmartCard si blocca automaticamente'; kpkiErrorMessagesArray[48] := 'E'' fallito il logout sulla smartcard'; kpkiErrorMessagesArray[49] := 'E'' fallita l''inizializzazione del digest sulla smartcard'; kpkiErrorMessagesArray[50] := 'E'' fallito il digest sulla smartcard'; kpkiErrorMessagesArray[51] := 'E'' fallita l''inizializzazione della firma sulla smartcard'; kpkiErrorMessagesArray[52] := 'E'' fallita la firma sulla smartcard'; kpkiErrorMessagesArray[53] := 'E'' fallita la generazione della coppia di chiavi sulla smartcard'; kpkiErrorMessagesArray[54] := 'E'' fallita l''inizializzazione della ricerca di oggetti sulla smartcard'; kpkiErrorMessagesArray[55] := 'E'' fallita la ricerca di oggetti sulla smartcard'; kpkiErrorMessagesArray[56] := 'Non è stata trovata la chiave privata sulla smartcard'; kpkiErrorMessagesArray[57] := 'Errore irreversibile'; kpkiErrorMessagesArray[58] := 'Non è possibile ottenere il valore dell''attributo'; kpkiErrorMessagesArray[59] := 'La chiave privata è troppo lunga'; kpkiErrorMessagesArray[60] := 'E'' fallita l''inizializzazione della decrittazione sulla smartcard'; kpkiErrorMessagesArray[61] := 'E'' fallita la decrittazione sulla smartcard'; kpkiErrorMessagesArray[62] := 'Non è possibile ottenere la lista dei meccanismi'; kpkiErrorMessagesArray[63] := 'Non è supportato alcun meccanismo'; kpkiErrorMessagesArray[64] := 'Non è possibile ottenere informazioni sui meccanismi'; kpkiErrorMessagesArray[65] := 'Non è stato trovato il certificato nella smartcard'#13'(private key errata)'; kpkiErrorMessagesArray[66] := 'E'' fallita la creazione dell''oggetto sulla smartcard'; kpkiErrorMessagesArray[67] := 'Non è possibile convertire il certificato dell''utente nel formato X509'; kpkiErrorMessagesArray[68] := 'Non è possibile convertire il certificato del destinatario nel formato X509'; kpkiErrorMessagesArray[69] := 'Non è possibile convertire il certificato della CA nel formato X509'; kpkiErrorMessagesArray[70] := 'I dati firmati e crittati non sono in formato X509'; kpkiErrorMessagesArray[71] := 'I dati in formato PKCS#7 non sono firmati e imbustati'; kpkiErrorMessagesArray[72] := 'Non è stato specificato il certificato dell''utente'; kpkiErrorMessagesArray[73] := 'Non è stata verificata la firma'; kpkiErrorMessagesArray[74] := 'Non è possibile convertire il certificato del firmatario nel formato X509'; kpkiErrorMessagesArray[75] := 'Non è possibile convertire il certificato della CA del firmatario nel formato X509'; kpkiErrorMessagesArray[76] := 'Non è stato verificato il certificato del firmatario'; kpkiErrorMessagesArray[77] := 'Non è disponibile il certificato della CA del firmatario'; kpkiErrorMessagesArray[78] := 'Non è possibile estrarre il Distinguished Name della CA del firmatario'; kpkiErrorMessagesArray[79] := 'Non è possibile estrarre il Common Name della CA del firmatario'; kpkiErrorMessagesArray[80] := 'Errore nella scrittura sul file di output'; kpkiErrorMessagesArray[81] := 'Non è possibile creare il pacchetto di informazioni sul firmatario'; kpkiErrorMessagesArray[82] := 'Non è possibile aggiungere le informazioni del firmatario allo standard PKCS#7'; kpkiErrorMessagesArray[83] := 'I dati firmati non sono in formato PKCS#7'; kpkiErrorMessagesArray[84] := 'I dati in formato PKCS#7 non sono firmati'; kpkiErrorMessagesArray[85] := 'Non è possibile estrarre il certificato dell''utente dallo standard PKCS#7'; kpkiErrorMessagesArray[86] := 'Non è stato specificato l''algortimo di hashing'; kpkiErrorMessagesArray[87] := 'Errore nel caricamento del certificato dell''utente'; kpkiErrorMessagesArray[88] := 'Errore nel caricamento del certificato della CA'; kpkiErrorMessagesArray[89] := 'Non è stato specificato il certificato dell''utente'; kpkiErrorMessagesArray[90] := 'Non è stato specificato il certificato della CA'; kpkiErrorMessagesArray[91] := 'Non è stato specificato il certificato del destinatario'; kpkiErrorMessagesArray[92] := 'Il motore software non consente la gestione di chiavi su smartcard'; kpkiErrorMessagesArray[93] := 'Non è stata specificata la chiave privata'; kpkiErrorMessagesArray[94] := 'Il motore smartcard non consente la gestione di chiavi software'; kpkiErrorMessagesArray[95] := 'Non è stata specificata la modalità stringa'; kpkiErrorMessagesArray[96] := 'Non è stato specificato il certificato del destinatario'; kpkiErrorMessagesArray[97] := 'Il certificato del destinatario è vuoto'; kpkiErrorMessagesArray[98] := 'Non è possibile estrarre le informazioni dal certificato del destinatario'; kpkiErrorMessagesArray[99] := 'Non è stato definito il server X500'; kpkiErrorMessagesArray[100] := 'E'' fallita l''apertura del protocollo LDAP'; kpkiErrorMessagesArray[101] := 'E'' fallita l''inizializzazione della ricerca in LDAP'; kpkiErrorMessagesArray[102] := 'E'' fallita la ricerca in LDAP'; kpkiErrorMessagesArray[103] := 'Il server non è quello di una Certification Authority'; kpkiErrorMessagesArray[104] := 'Il certificato è vuoto'; kpkiErrorMessagesArray[105] := 'Non è possibile scrivere sul flusso di dati in uscita'; kpkiErrorMessagesArray[106] := 'Il certificato non è del tipo X509'; kpkiErrorMessagesArray[107] := 'Non è possibile convertire la chiave selezionata'; kpkiErrorMessagesArray[108] := 'Non è possibile aggiungere la chiave pubblica alla richiesta di certificato'; kpkiErrorMessagesArray[109] := 'Non è possibile firmare la richiesta di certificato'; kpkiErrorMessagesArray[110] := 'Non è possibile convertire la richiesta di certificato in formato DER'; kpkiErrorMessagesArray[111] := 'Non è possibile creare l''algoritmo'; kpkiErrorMessagesArray[112] := 'Non è possibile convertire la chiave pubblica in formato ASN1'; kpkiErrorMessagesArray[113] := 'Non è possibile scrivere la richiesta di certificato su file'; kpkiErrorMessagesArray[114] := 'Non è possibile specificare la versione nella richiesta di certificato'; kpkiErrorMessagesArray[115] := 'Non è possibile specificare la nazione nella richiesta di certificato'; kpkiErrorMessagesArray[116] := 'Non è possibile specificare la provincia nella richiesta di certificato'; kpkiErrorMessagesArray[117] := 'Non è possibile specificare la città nella richiesta di certificato'; kpkiErrorMessagesArray[118] := 'Non è possibile specificare l''organizzazione nella richiesta di certificato'; kpkiErrorMessagesArray[119] := 'Non è possibile specificare il dipartimento nella richiesta di certificato'; kpkiErrorMessagesArray[120] := 'Non è possibile specificare il Common Name nella richiesta di certificato'; kpkiErrorMessagesArray[121] := 'Non è possibile specificare l''indirizzo email nella richiesta di certificato'; kpkiErrorMessagesArray[122] := 'Non è possibile convertire i dati dal formato DER al formato PEM'; kpkiErrorMessagesArray[123] := 'Non è stato riconosciuto il formato della CRL'; kpkiErrorMessagesArray[124] := 'Non è possibile trovare il Serial Number della CRL'; kpkiErrorMessagesArray[125] := 'Non è possibile ottenere il CRL Count'; kpkiErrorMessagesArray[126] := 'I dati della CRL sono vuoti'; kpkiErrorMessagesArray[127] := 'Il certificato è stato revocato'; kpkiErrorMessagesArray[128] := 'La CRL non è stata verificata'; kpkiErrorMessagesArray[129] := 'La funzione non è supportata'; kpkiErrorMessagesArray[130] := 'Non è possibile specificare la Description nella richiesta di certificato'; kpkiErrorMessagesArray[131] := 'Impossibile scrivere sul buffer di output'; kpkiErrorMessagesArray[132] := 'Non è possibile estrarre il certificato della CA dallo standard PKCS#7'; kpkiErrorMessagesArray[133] := 'Numero di firma non valido'; kpkiErrorMessagesArray[134] := 'I dati non sono in formato PKCS7'; kpkiErrorMessagesArray[135] := 'Dimensione della cache non ammessa'; kpkiErrorMessagesArray[136] := 'Impossibile inizializzare la cache'; kpkiErrorMessagesArray[137] := 'Non è stata specificata la locazione della cache'; kpkiErrorMessagesArray[138] := 'Non è stato specificato lo stato della cache'; kpkiErrorMessagesArray[139] := 'Formato della chiave privata errato'; kpkiErrorMessagesArray[140] := 'Impossibile imbustare il digest in PKCS#1'; kpkiErrorMessagesArray[141] := 'Il file di input contenente la chiave privata non è in formato PKCS#8'; kpkiErrorMessagesArray[142] := 'E'' fallito il cambiamento del PIN della SmartCard'; kpkiErrorMessagesArray[143] := 'Non è stata settata la chiave simmetrica di cifratura'; kpkiErrorMessagesArray[144] := 'Destinatario non valido'; kpkiErrorMessagesArray[145] := 'L''estensione Key Usage non è presente'; kpkiErrorMessagesArray[146] := 'Utilizzo del certificato non consentito'; kpkiErrorMessagesArray[147] := 'Certificato non trovato'; kpkiErrorMessagesArray[148] := 'Fallita l''inizializzazione del socket'; kpkiErrorMessagesArray[149] := 'Fallita l''inizializzazione del socket SSL'; kpkiErrorMessagesArray[150] := 'La negoziazione SSL non è riuscita'; kpkiErrorMessagesArray[151] := 'Impossibile effettuare la connessione SSL'; kpkiErrorMessagesArray[152] := 'Risposta HTTP non valida'; kpkiErrorMessagesArray[153] := 'Protocollo sconosciuto'; kpkiErrorMessagesArray[154] := 'Ricezione impossibile su canale SSL'; kpkiErrorMessagesArray[155] := 'Header HTTP non valido'; kpkiErrorMessagesArray[156] := 'Impossibile inviare comandi HTTP'; kpkiErrorMessagesArray[157] := 'Impossibile inviare comandi HTTP sul canale SSL'; kpkiErrorMessagesArray[158] := 'Impossibile ricevere comandi HTTP sul canale SSL'; kpkiErrorMessagesArray[159] := 'La CRL non è stata trovata'; kpkiErrorMessagesArray[160] := 'Percorso di ricerca certificato non valido'; kpkiErrorMessagesArray[161] := 'Certificato sconosciuto. Certificato non affidabile.'; kpkiErrorMessagesArray[162] := 'URL del server OCSP non fornito'; kpkiErrorMessagesArray[163] := 'Certificato dell''emittente non fornito'; kpkiErrorMessagesArray[164] := 'OCSP responder: il certificato dell''OCSP responder non è stato specificato'; kpkiErrorMessagesArray[165] := 'OCSP responder: la richiesta ricevuta non è conforme alla sintassi OCSP'; kpkiErrorMessagesArray[166] := 'OCSP responder: errore interno al server'; kpkiErrorMessagesArray[167] := 'OCSP responder: è occupato, riprovare più tardi'; kpkiErrorMessagesArray[168] := 'OCSP responder: la richesta del client deve essere firmata'; kpkiErrorMessagesArray[169] := 'OCSP responder: questo client non è autorizzato'; kpkiErrorMessagesArray[170] := 'Risposta dell''OCSP responder sconosciuta'; kpkiErrorMessagesArray[171] := 'Il certificato non è in formato X509'; kpkiErrorMessagesArray[172] := 'La sintassi URL del server OCSP non è valida'; kpkiErrorMessagesArray[173] := 'La sintassi URL dell''host OCSP non è valida'; kpkiErrorMessagesArray[174] := 'Il numero di porta del server OCSP non è valido'; kpkiErrorMessagesArray[175] := 'La sintassi URL del path OCSP non è valida'; kpkiErrorMessagesArray[176] := 'Meccanismo di trasporto OCSP non supportato'; kpkiErrorMessagesArray[177] := 'Impossibile esaminare la catena della fiducia del responder OCSP'; kpkiErrorMessagesArray[178] := 'Impossibile aggiungere il certificato alla richiesta OCSP'; kpkiErrorMessagesArray[179] := 'Impossibile aggiungere il numero di serie del certificato alla richiesta OCSP'; kpkiErrorMessagesArray[180] := 'Impossibile aggiungere il certificato o il numero di serie del certificato alla richiesta OCSP'; kpkiErrorMessagesArray[181] := 'Non è stato specificato nessun certificato o numero di serie su cui generare la richiesta'; kpkiErrorMessagesArray[182] := 'Certificato dell''issuer non valido'; kpkiErrorMessagesArray[183] := 'Configurazione client OCSP incompleta'; kpkiErrorMessagesArray[184] := 'OCSP server irraggiungibile'; kpkiErrorMessagesArray[185] := 'La connessione sicura al server OCSP è fallita'; kpkiErrorMessagesArray[186] := 'La connessione al server OCSP è fallita'; kpkiErrorMessagesArray[187] := 'L''invio della richiesta OCSP è fallito'; kpkiErrorMessagesArray[188] := 'La catena della fiducia del responder OCSP non è valida'; kpkiErrorMessagesArray[189] := 'Impossibile interpretare la risposta OCSP'; kpkiErrorMessagesArray[190] := 'Richiesta persa. Impossibile verificare la risposta'; kpkiErrorMessagesArray[191] := 'La verifica del nonce OCSP è fallita'; kpkiErrorMessagesArray[192] := 'Risposta OCSP non valida'; kpkiErrorMessagesArray[193] := 'Errore sconosciuto'; kpkiErrorMessagesArray[194] := 'La smartcard non corrisponde all''utente !'#13'(%s)'; kpkiErrorMessagesArray[195] := 'Controllo validità certificato fallito: validità dal %s al %s '; kpkiErrorMessagesArray[196] := 'Dati per le Dll di firma non caricati'; end.
{AUTEUR : FRANCKY23012301 - 2008 ------- Gratuit pour une utilisation non commerciale} unit BrowserMidi; interface uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, Graphics, Menus, Dialogs; Type {>>TITLE} TBrowserMidiTitle = class(TCustomControl) private fColorTitle:TColor; fColorSubTitle:TColor; fColorRectTitle:TColor; fTitle:String; fSubTitle:String; Procedure setColorTitle(Value:TColor); Procedure setColorSubTitle(Value:TColor); Procedure setColorRectTitle(Value:TColor); Procedure SetTitle(Value:String); Procedure SetSubTitle(Value:String); protected procedure Paint; override; procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property ColorTitle:TColor Read fColorTitle Write SetColorTitle; Property ColorSubTitle:TColor Read fColorSubTitle Write SetColorSubTitle; Property ColorRectTitle:TColor Read fColorRectTitle Write SetColorRectTitle; Property Title:String Read fTitle Write SetTitle; Property SubTitle:String Read fSubTitle Write SetSubTitle; end; {>>TSoundFont} TSoundFont = class(TCollectionItem) private fFileName: string; fName: string; fBank: integer; fOnChange: TNotifyEvent; protected procedure AssignTo(Dest : TPersistent); override; procedure Change; virtual; public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source : TPersistent); override; published Property Bank:Integer Read fBank Write fBank; Property FileName:String Read fFileName Write fFileName; Property Name:String Read fName Write fName; property OnChange :TNotifyEvent read fOnChange write fOnChange; end; {>>TSoundFontCnt} TSoundFontCnt = class(TOwnedCollection) protected function GetItem(Index: integer): TSoundFont; procedure SetItem(Index: integer; Value: TSoundFont); public constructor Create(AOwner: TPersistent); function Add: TSoundFont; property Items[Index: integer]: TSoundFont Read GetItem Write SetItem; end; TSndFntClick_Event=TNotifyEvent; TInstrClick_Event=TNotifyEvent; {>>TBrowserMidi} TBrowserMidi = class(TCustomControl) private fSoundFont:TSoundFontCnt; fBrowserMidiTitle:TBrowserMidiTitle; fColorCategories:TColor; fColorSndFont:TColor; fColorInstrType:TColor; fColorInstr:TColor; fColorSelected:TColor; SndFontShowed:Boolean; InstrShowed:Integer; fOnInstrClick_Event:TInstrClick_Event; fOnSndFntClick_Event:TSndFntClick_Event; Procedure Set_ColorCategories(Value:TColor); Procedure Set_ColorSndFont(Value:TColor); Procedure Set_ColorInstrType(Value:TColor); Procedure Set_ColorInstr(Value:TColor); Procedure Set_ColorSelected(Value:TColor); Procedure Draw_Panel(Caption:String; ATop:Integer;AColor:TColor); protected procedure Paint; override; procedure Resize; override; procedure MouseDown(Button: TMouseButton;Shift: TShiftState; X, Y: Integer); override; public SoundFontSelected:Integer; InstrumentSelected:Integer; Function InstrToString(Instrument:Byte):String; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property Color; Property ColorCategories:TColor Read fColorCategories Write Set_ColorCategories; Property ColorSndFont:TColor Read fColorSndFont Write Set_ColorSndFont; Property ColorInstr:TColor Read fColorInstr Write Set_ColorInstr; Property ColorInstrType:TColor Read fColorInstrType Write Set_ColorInstrType; Property ColorSelected:TColor Read fColorSelected Write Set_ColorSelected; Property SoundFont:TSoundFontCnt Read fSoundFont Write fSoundFont; Property BrowserMidiTitle:TBrowserMidiTitle Read fBrowserMidiTitle Write fBrowserMidiTitle; property OnSndFntClick_Event:TSndFntClick_Event Read fOnSndFntClick_Event Write fOnSndFntClick_Event; Property OnInstrClick_Event:TInstrClick_Event Read fOnInstrClick_Event Write fOnInstrClick_Event; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; procedure Register; implementation procedure Register; begin RegisterComponents('MUSIC_PRO', [TBrowserMidi]); end; {>>TITLE} constructor TBrowserMidiTitle.Create(AOwner: TComponent); begin inherited Create(AOwner); fColorRectTitle:=ClSilver; Title:='MUSIC PRO'; fColorTitle:=$0012526D; SubTitle:='Midi Browser'; fColorSubTitle:=$001A7297; end; destructor TBrowserMidiTitle.Destroy; begin inherited; end; Procedure TBrowserMidiTitle.setColorTitle(Value:TColor); Begin fColorTitle:=Value; Invalidate; End; Procedure TBrowserMidiTitle.setColorSubTitle(Value:TColor); Begin fColorSubTitle:=Value; Invalidate; End; Procedure TBrowserMidiTitle.setColorRectTitle(Value:TColor); Begin fColorRectTitle:=Value; Invalidate; End; Procedure TBrowserMidiTitle.SetTitle(Value:String); Begin fTitle:=Value; Invalidate; End; Procedure TBrowserMidiTitle.SetSubTitle(Value:String); Begin fSubTitle:=Value; Invalidate; End; procedure TBrowserMidiTitle.Resize; Begin Width:=163; If Height<49 Then Height:=49; Invalidate; End; procedure TBrowserMidiTitle.Paint; Var RectTitle:TRect; WidthString,HeightString,LeftString,TopString:Integer; Begin InHerited; With Canvas Do Begin Brush.Style:=BsClear; With RectTitle Do Begin Left:=0; Right:=Self.Width; Top:=0; Bottom:=49; Brush.Color:=Self.fColorRectTitle; Pen.Color:=ClBlack; Pen.Width:=4; Rectangle(RectTitle); Font.Name:='ARIAL'; Font.Size:=14; Font.Color:=fColorTitle; LeftString:=Round(0.05*Self.Width); TopString:=Pen.Width; TextOut(LeftString,TopString,fTitle); Font.Name:='Comic Sans MS'; Font.Size:=11; Font.Color:=Self.fColorSubTitle; WidthString:=TextWidth(fSubTitle); HeightString:=TextHeight(fSubTitle); LeftString:=Self.Width-WidthString-5; TopString:=Bottom-Pen.Width-HeightString; TextOut(LeftString,TopString,fSubTitle); End; End End; {>>TBrowserMidi} constructor TBrowserMidi.Create(AOwner: TComponent); begin inherited Create(AOwner); DoubleBuffered:=True; fSoundFont:=TSoundFontCnt.Create(Self); fBrowserMidiTitle:=TBrowserMidiTitle.Create(Self); RegisterClass(TBrowserMidiTitle); With fBrowserMidiTitle Do Begin Parent:=Self; Top:=0; Left:=0; Height:=49; End; InstrShowed:=-1; SoundFontSelected:=-1; InstrumentSelected:=-1; SndFontShowed:=False; Color:=$00757575; fColorCategories:=$00A3A3A3; fColorSndFont:=$00CCCCD7; fColorInstr:=$00CCCCD7; fColorInstrType:=$00A3A3B6; fColorSelected:=$00CAEBF9; end; destructor TBrowserMidi.Destroy; begin fSoundFont.Free; fBrowserMidiTitle.Free; inherited; end; procedure TBrowserMidi.Set_ColorCategories(Value: TColor); begin fColorCategories:=Value; Self.Invalidate; end; procedure TBrowserMidi.Set_ColorSndFont(Value: TColor); begin fColorSndFont:=Value; Self.Invalidate; end; procedure TBrowserMidi.Set_ColorInstrType(Value: TColor); begin fColorInstrType:=Value; Self.Invalidate; end; procedure TBrowserMidi.Set_ColorInstr(Value: TColor); begin fColorInstr:=Value; Self.Invalidate; end; procedure TBrowserMidi.Set_ColorSelected(Value: TColor); begin fColorSelected:=Value; Self.Invalidate; end; Function TBrowserMidi.InstrToString(Instrument:Byte):String; const InstrName: array [0..15] of array [0..7] of string = (('PIANO A QUEUE','PIANO CONCERT','PIANO ELECT','PIANO HONKY-TON', 'PIANO ELECT 1','PIANO ELECT 2','CLAVECIN','CLAVICORDE'), ('CÉLESTA','CARILLON','BOÎTE À MUSIQUE','VIBRAPHONE', 'MARIMBA','XYLOPHONE','CLOCHES','TYMPANON'), ('ORGUE HAMMOND','ORGUE PERCUSSIF','ORGUE ELECT','GRAND ORGUE', 'HARMONIUM','ACCORDÉON','HARMONICA','BANDONEON'), ('GUITARE CLASS','GUITARE FOLK','GUITARE ELECT JAZZ','GUITARE ELECT CLAIRE', 'GUITARE MUTED','GUITARE SATURÉE','GUITARE DIST','HARMONIQUES'), ('BASSE ACOUST','BASSE ELECT - DOIGT','BASSE ELECT - MED','BASSE FRETLESS', 'BASSE SLAP 1','BASSE SLAP 2','BASSE SYNTHÉ 1','BASSE SYNTHÉ 2'), ('VIOLON','VIOLE','VIOLONCELLE','CONTREBASSE', 'CORDES TREMOLO','CORDES PIZZICATO','HARPE','TIMBALES'), ('QUARTET CORDES 1','QUARTET CORDES 2','CORDES SYNTHÉ 1','CORDES SYNTHÉ 2', 'VOIX AAHS','VOIX OOHS','VOIX SYNTHÉ','COUP D''ORCHESTRE'), ('TROMPETTE','TROMBONE','TUBA','TROMPETTE BOUCHÉE', 'CORS','ENSEMBLE DE CUIVRES','CUIVRES SYNTHÉ 1','CUIVRES SYNTHÉ 2'), ('SAXO SOPRANO','SAXO ALTO','SAXO TÉNOR','SAXO BARYTON', 'SAXO HAUTBOIS','CORS ANGLAIS','BASSON','CLARINETTE'), ('PICCOLO','FLÛTE','FLÛTE À BEC','FLÛTE DE PAN', 'BOUTEILLE','SHAKUHACHI','SIFFLET','OCARINA'), ('SIGNAL CARRÉ','SIGNAL TRIANGLE','ORGUE À VAPEUR','CHIFF', 'CHARANG','VOIX SOLO','QUINTE','BASSE'), ('NEW AGE','WARM','POLYSYNTH','CHŒUR', 'ARCHET','MÉTALLIQUE','HALO','SWEEP'), ('PLUIE','BANDE SON','CRISTAL','ATMOSPHÈRE', 'BRIGHTNESS','GOBLINS','ECHOS','SCIE-FIC'), ('SITAR','BANJO','SHAMISEN','KOTO', 'KALIMBA','CORNEMUSE','VIOLON FOLKLORIQUE','SHANAI'), ('SONNERIE','AGOGO','PERCUS. ACIER','WOODBLOCK', 'TAIKO','TOM MÉLODIQUE','PERCUS. SYNTHÉ','CYMBALE INVERSÉE'), ('CORDES GUITARES','RESPIRATION','RIVAGE','CHANT D''OISEAUX', 'SONNERIE TÉLÉPHONE','HÉLICOPTÈRE','APPLAUDISSEMENTS','COUP DE FEU')); Begin Result:=InstrName[Instrument Div 8, Instrument Mod 8]; End; procedure TBrowserMidi.Resize; Begin InHerited; Width:=163; End; procedure TBrowserMidi.Paint; const TypeInstrName: array [0..15] of string = ('PIANOS','PERCUSSIONS CHROMATIQUES','ORGUES','GUITARES', 'BASSES','CORDES','ENSEMBLES ET CHOEURS','CUIVRES', 'INSTRUMENTS À ANCHES','FLUTES','LEAD SYNTHÉTISEURS','PAD SYNTHÉTISEURS', 'EFFETS SYNTHÉTISEURS','INSTRUMENTS ETHNIQUES','PERCUSSIONS','EFFETS SONORES'); Var IndexPn,IndexInstr,TopRect:Integer; ColorBkGn:TColor; Begin InHerited; With Canvas Do Begin Brush.Style:=BsClear; Brush.Color:=ClBlack; Rectangle(ClientRect); TopRect:=fBrowserMidiTitle.Height; Draw_Panel('SOUNDFONT',TopRect,fColorCategories); If (fSoundFont.Count>0) And (SndFontShowed) Then For IndexPn:=0 To (fSoundFont.Count-1) Do Begin Inc(TopRect,19); If SoundFontSelected<>IndexPn Then ColorBkGn:=fColorSndFont Else ColorBkGn:=fColorSelected; Draw_Panel(fSoundFont.Items[IndexPn].Name,TopRect,ColorBkGn); End; Inc(TopRect,19); Draw_Panel('INSTRUMENTS',TopRect,fColorCategories); For IndexPn:=0 To 15 Do Begin Inc(TopRect,19); Draw_Panel(TypeInstrName[IndexPn],TopRect,fColorInstrType); If InstrShowed=IndexPn Then For IndexInstr:=0 To 7 Do Begin Inc(TopRect,19); If InstrumentSelected<>IndexInstr+IndexPn*8 Then ColorBkGn:=fColorSndFont Else ColorBkGn:=fColorSelected; Draw_Panel(InstrToString(IndexPn*8+IndexInstr),TopRect,ColorBkGn); End; End; Height:=TopRect+19; End; End; Procedure TBrowserMidi.Draw_Panel(Caption:String; ATop:Integer; AColor:TColor); Var Rect:TRect; LeftText,TopText:Integer; Begin With Canvas Do Begin With Rect Do Begin Left:=0; Right:=Width; Top:=ATop; Bottom:=Top+19; LeftText:=((Right-Left)-TextWidth(Caption)) Div 2; TopText:=ATop+((Bottom-Top)-TextHeight(Caption)) Div 2; End; Brush.Color:=AColor; Rectangle(Rect); Brush.Style:=BsClear; Font.Color:=ClBlack; Font.Name:='Arial'; Font.Size:=8; TextOut(LeftText,TopText,Caption); End; End; procedure TBrowserMidi.MouseDown(Button: TMouseButton;Shift: TShiftState; X, Y: Integer); Var DecY, DecTitle:Integer; Begin InHerited; If SSLeft In Shift Then Begin DecTitle:=fBrowserMidiTitle.Height; If (Y<19+DecTitle) And (fSoundFont.Count>0) Then SndFontShowed:=Not SndFontShowed; If Not SndFontShowed Then DecY:=38+DecTitle Else DecY:=44+DecTitle+fSoundFont.Count*19; IF ssDouble In Shift Then If (Y>19+DecTitle) And (Y<DecY-19) Then Begin SoundFontSelected:=(Y-22-DecTitle) Div 19; If Assigned(fOnSndFntClick_Event) Then fOnSndFntClick_Event(Self); End; If (InstrShowed=-1) And (Y>30+DecTitle) Then InstrShowed:=(Y-DecY) Div 19; If (InstrShowed<>-1) Then Begin If (Y>DecY) And (Y<DecY+(InstrShowed+1)*19) Then InstrShowed:=(Y-DecY) Div 19; If (Y>19+DecY+InstrShowed*19+152) Then InstrShowed:=(Y -DecY -152) Div 19; IF ssDouble In Shift Then If (Y-DecY>(InstrShowed+1)*19) And (Y-DecY<(InstrShowed+1)*19+176) Then Begin InstrumentSelected:=(Y-DecY-(InstrShowed+1)*19) Div 19+InstrShowed*8; If Assigned(fOnInstrClick_Event) Then fOnInstrClick_Event(Self); End; IF (Y>DecY-19) And (Y<DecY) Then InstrShowed:=-1; End; Invalidate; End; End; {>>TSoundFontCnt} constructor TSoundFontCnt.Create(AOwner: TPersistent); begin inherited Create(AOwner,TSoundFont); end; function TSoundFontCnt.Add:TSoundFont; begin Result := TSoundFont(inherited Add); end; function TSoundFontCnt.GetItem(Index: integer):TSoundFont; begin Result := TSoundFont(inherited Items[Index]); end; procedure TSoundFontCnt.SetItem(Index: integer; Value:TSoundFont); begin inherited SetItem(Index, Value); end; {>>TSoundFont} constructor TSoundFont.Create; begin inherited Create(ACollection); end; destructor TSoundFont.Destroy; begin inherited Destroy; end; procedure TSoundFont.AssignTo(Dest: TPersistent); begin if Dest is TSoundFont then with TSoundFont(Dest) do begin fOnChange := self.fOnChange; fFileName := Self.fFileName; fName:=Self.fName; fBank:=Self.fBank; Change; end else inherited AssignTo(Dest); end; procedure TSoundFont.Assign(Source : TPersistent); begin if source is TSoundFont then with TSoundFont(Source) do AssignTo(Self) else inherited Assign(source); end; procedure TSoundFont.Change; begin if Assigned(fOnChange) then fOnChange(Self); end; End.
unit VisibleDSA.InsertionSortData; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Generics.Collections; type ArrType = (Default, NearlyOrdered); TInsertionSortData = class private _numbers: array of integer; public OrderedIndex: integer; // [0...orderedIndex) 是有序的 CurrentIndex: integer; // 当前元素的索引 constructor Create(n, randomBound: integer; dataType: ArrType = NearlyOrdered); destructor Destroy; override; procedure Swap(i, j: integer); function Length: integer; function GetValue(index: integer): integer; end; implementation type TArrayHelper_int = specialize TArrayHelper<integer>; { TInsertionSortData } constructor TInsertionSortData.Create(n, randomBound: integer; dataType: ArrType); var i, swapTime, a, b: integer; begin OrderedIndex := -1; CurrentIndex := -1; Randomize; SetLength(_numbers, n); for i := 0 to n - 1 do _numbers[i] := Random(randomBound) + 1; if dataType = ArrType.NearlyOrdered then begin TArrayHelper_int.Sort(_numbers); swapTime := Trunc(0.02 * n); for i := 0 to swapTime - 1 do begin a := Random(n); b := Random(n); Swap(a, b); end; end; end; destructor TInsertionSortData.Destroy; begin inherited Destroy; end; function TInsertionSortData.Length: integer; begin Result := System.Length(_numbers); end; function TInsertionSortData.GetValue(index: integer): integer; begin if (index < 0) or (index >= Length) then raise Exception.Create('Invalid index to access Sort Data.'); Result := _numbers[index]; end; procedure TInsertionSortData.Swap(i, j: integer); var temp: integer; begin if (i < 0) or (i >= Self.Length) or (j < 0) or (j >= Self.Length) then raise Exception.Create('Invalid index to access Sort Data.'); temp := _numbers[j]; _numbers[j] := _numbers[i]; _numbers[i] := temp; end; end.
unit RockSamplePoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, RockSample, Windows, Lithology; type TRockSampleTypeDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TRockSampleSizeTypePoster = class(TImplementedDataPoster) private FAllSampleTypes: TRockSampleTypes; public property AllSampleTypes: TRockSampleTypes read FAllSampleTypes write FAllSampleTypes; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;override; constructor Create; override; end; TRockSampleSizeTypePresencePoster = class(TImplementedDataPoster) private FAllSampleSizeTypes: TRockSampleSizeTypes; public property AllSampleSizeTypes: TRockSampleSizeTypes read FAllSampleSizeTypes write FAllSampleSizeTypes; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;override; constructor Create; override; end; TRockSampleDataPoster = class(TImplementedDataPoster) private FAllLithologies: TLithologies; procedure SetAllLithologies(const Value: TLithologies); public property AllLithologies: TLithologies read FAllLithologies write SetAllLithologies; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;override; constructor Create; override; end; implementation uses Facade, BaseFacades, SysUtils, Variants; { TRockSimpleDataPoster } constructor TRockSampleDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_rock_sample';//'SPD_GET_ROCK_SAMPLES_BY_LAYER'; //DataPostString := 'SPD_ADD_ROCK_SAMPLE'; //DataDeletionString := ''; KeyFieldNames := 'ROCK_SAMPLE_UIN'; FieldNames := 'SLOTTING_UIN, ROCK_SAMPLE_UIN, VCH_GENERAL_NUMBER, NUM_FROM_SLOTTING_TOP,' + 'ROCK_ID, NUM_SAMPLE_CHECKED, MODIFIER_ID, MODIFIER_CLIENT_APP_TYPE_ID'; AccessoryFieldNames := 'SLOTTING_UIN, ROCK_SAMPLE_UIN, VCH_GENERAL_NUMBER, NUM_FROM_SLOTTING_TOP,' + 'ROCK_ID, NUM_SAMPLE_CHECKED, MODIFIER_ID, MODIFIER_CLIENT_APP_TYPE_ID'; AutoFillDates := false; Sort := ''; end; function TRockSampleDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TRockSampleDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o : TRockSample; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TRockSample; o.ID := ds.FieldByName('ROCK_SAMPLE_UIN').AsInteger; o.Name := trim(ds.FieldByName('VCH_GENERAL_NUMBER').AsString); o.FromBegining := ds.FieldByName('NUM_FROM_SLOTTING_TOP').AsFloat; if Assigned(AllLithologies) then o.Lithology := AllLithologies.ItemsByID[ds.FieldByName('ROCK_ID').AsInteger] as TLithology; ds.Next; end; ds.First; end; end; function TRockSampleDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TRockSample; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := AObject as TRockSample; ds.FieldByName('SLOTTING_UIN').AsInteger := o.Owner.Collection.Owner.ID; ds.FieldByName('ROCK_SAMPLE_UIN').AsInteger := o.ID; ds.FieldByName('VCH_GENERAL_NUMBER').AsString := trim (o.Name); ds.FieldByName('NUM_FROM_SLOTTING_TOP').AsFloat := o.FromBegining; if Assigned (o.Lithology) then ds.FieldByName('ROCK_ID').AsInteger := o.Lithology.ID else ds.FieldByName('ROCK_ID').AsInteger := 0; ds.FieldByName('NUM_SAMPLE_CHECKED').AsInteger := 0; ds.FieldByName('MODIFIER_ID').AsInteger := TMainFacade.GetInstance.DBGates.EmployeeID; ds.FieldByName('MODIFIER_CLIENT_APP_TYPE_ID').AsInteger := TMainFacade.GetInstance.DBGates.ClientAppTypeID; ds.Post; o.ID := ds.FieldByName('ROCK_SAMPLE_UIN').Value; end; procedure TRockSampleDataPoster.SetAllLithologies( const Value: TLithologies); begin if FAllLithologies <> Value then FAllLithologies := Value; end; { TRockSampleSizeTypePoster } constructor TRockSampleSizeTypePoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_SAMPLE_TYPE'; KeyFieldNames := 'Sample_Type_ID'; FieldNames := 'Sample_Type_ID, DNR_Sample_Type_Id, vch_Sample_Type_Name, num_Diameter, num_X_Size, num_Y_Size, num_Z_Size, vch_Sample_Type_Short_Name, num_Order'; AccessoryFieldNames := 'Sample_Type_ID, DNR_Sample_Type_Id, vch_Sample_Type_Name, num_Diameter, num_X_Size, num_Y_Size, num_Z_Size, vch_Sample_Type_Short_Name, num_Order'; AutoFillDates := false; Sort := 'num_Order'; end; function TRockSampleSizeTypePoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TRockSampleSizeTypePoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; rst: TRockSampleSizeType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin rst := AObjects.Add as TRockSampleSizeType; rst.ID := ds.FieldByName('Sample_Type_ID').AsInteger; rst.RockSampleType := AllSampleTypes.ItemsById[ds.FieldByName('DNR_Sample_Type_Id').AsInteger] as TRockSampleType; rst.Name := trim(ds.FieldByName('vch_Sample_Type_Name').AsString); rst.ShortName := trim(ds.FieldByName('vch_Sample_Type_Short_Name').AsString); rst.Diameter := ds.FieldByName('num_Diameter').AsFloat; rst.XSize := ds.FieldByName('num_X_Size').AsFloat; rst.YSize := ds.FieldByName('num_Y_Size').AsFloat; rst.ZSize := ds.FieldByName('num_Z_Size').AsFloat; rst.Order := ds.FieldByName('num_Order').AsInteger; ds.Next; end; ds.First; end; end; function TRockSampleSizeTypePoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; rst: TRockSampleSizeType; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); rst := AObject as TRockSampleSizeType; ds.FieldByName('Sample_Type_ID').AsInteger := rst.ID; ds.FieldByName('DNR_Sample_Type_Id').AsInteger := rst.RockSampleType.ID; ds.FieldByName('vch_Sample_Type_Name').AsString := rst.Name; ds.FieldByName('vch_Sample_Type_Short_Name').AsString := rst.ShortName; ds.FieldByName('num_Diameter').AsFloat := rst.Diameter; ds.FieldByName('num_X_Size').AsFloat := rst.XSize; ds.FieldByName('num_Y_Size').AsFloat := rst.YSize; ds.FieldByName('num_Z_Size').AsFloat := rst.ZSize; ds.FieldByName('num_Order').AsInteger := rst.Order; ds.Post; if rst.ID = 0 then rst.ID := ds.FieldByName('Sample_Type_ID').AsInteger; end; { TRockSampleTypeDataPoster } constructor TRockSampleTypeDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_DNR_Sample_Type_dict'; KeyFieldNames := 'DNR_Sample_Type_Id'; FieldNames := 'DNR_Sample_Type_Id, vch_DNR_Sample_Type'; AccessoryFieldNames := 'DNR_Sample_Type_Id, vch_DNR_Sample_Type'; AutoFillDates := false; Sort := 'vch_DNR_Sample_Type'; end; function TRockSampleTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TRockSampleTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; rst: TRockSampleType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin rst := AObjects.Add as TRockSampleType; rst.ID := ds.FieldByName('DNR_Sample_Type_Id').AsInteger; rst.Name := trim(ds.FieldByName('vch_DNR_Sample_Type').AsString); ds.Next; end; ds.First; end; end; function TRockSampleTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; rst: TRockSampleType; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); rst := AObject as TRockSampleType; rst.ID := ds.FieldByName('DNR_Sample_Type_Id').AsInteger; rst.Name := trim(ds.FieldByName('vch_DNR_Sample_Type').AsString); ds.Post; if rst.ID = 0 then rst.ID := ds.FieldByName('DNR_Sample_Type_Id').AsInteger; end; { TRockSampleSizeTypePresencePoster } constructor TRockSampleSizeTypePresencePoster.Create; begin inherited; Options := [soSingleDataSource]; DataSourceString := 'TBL_SLOTTING_SAMPLE_TYPE'; KeyFieldNames := 'SAMPLE_TYPE_ID; SLOTTING_UIN'; FieldNames := 'SAMPLE_TYPE_ID, SLOTTING_UIN, NUM_COUNT'; AccessoryFieldNames := 'SAMPLE_TYPE_ID, SLOTTING_UIN, NUM_COUNT'; AutoFillDates := false; Sort := ''; end; function TRockSampleSizeTypePresencePoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TCommonServerDataSet; begin Result := 0; ds := TMainFacade.GetInstance.DBGates.Add(Self); try // находим строку соответствующую ключу ds.First; if ds.Locate(ds.KeyFieldNames, varArrayOf([AObject.ID, AObject.Collection.Owner.ID]), []) then ds.Delete except Result := -1; end; end; function TRockSampleSizeTypePresencePoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var rstp: TRockSampleSizeTypePresence; ds: TDataSet; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin rstp := AObjects.Add as TRockSampleSizeTypePresence; rstp.RockSampleSizeType := AllSampleSizeTypes.ItemsById[ds.FieldByName('Sample_Type_ID').AsInteger] as TRockSampleSizeType; rstp.ID := rstp.RockSampleSizeType.ID; rstp.Count := ds.FieldByName('num_Count').AsInteger; ds.Next; end; ds.First; end; end; function TRockSampleSizeTypePresencePoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; rstp: TRockSampleSizeTypePresence; begin Result := 0; rstp := AObject as TRockSampleSizeTypePresence; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, rstp.Collection.Owner.ID]), []) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; ds.FieldByName('Sample_Type_ID').AsInteger := rstp.RockSampleSizeType.ID; ds.FieldByName('Slotting_UIN').AsInteger := (rstp.Collection as TRockSampleSizeTypePresences).Owner.ID; ds.FieldByName('num_Count').AsInteger := rstp.Count; ds.Post; end; end.
unit CoordPoster; interface uses DBGate, BaseObjects, PersistentObjects, DB, Coord; type // для источника координат скважин TSourceCoordDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; // для координат скважин TWellCoordDataPoster = class(TImplementedDataPoster) private FAllSourcesCoord: TSourceCoords; procedure SetAllSourcesCoord(const Value: TSourceCoords); public property AllSourcesCoord: TSourceCoords read FAllSourcesCoord write SetAllSourcesCoord; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils; { TWellCoordDataPoster } constructor TWellCoordDataPoster.Create; begin inherited; Options := [soSingleDataSource]; DataSourceString := 'TBL_OBJECT_RESEARCH'; KeyFieldNames := 'OBJECT_UIN'; FieldNames := 'OBJECT_UIN, NUM_OBJECT_TYPE, NUM_OBJECT_SUBTYPE, NUM_ZONE_NUMBER, NUM_RESEARCH_RESULT_X, NUM_RESEARCH_RESULT_Y, DTM_ENTERING_DATE, SOURCE_ID'; AccessoryFieldNames := 'OBJECT_UIN, NUM_OBJECT_TYPE, NUM_OBJECT_SUBTYPE, NUM_ZONE_NUMBER, NUM_RESEARCH_RESULT_X, NUM_RESEARCH_RESULT_Y, SOURCE_ID'; AutoFillDates := false; Sort := 'OBJECT_UIN'; end; function TWellCoordDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TWellCoordDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TWellCoord; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TWellCoord; o.ID := ds.FieldByName('OBJECT_UIN').AsInteger; o.NUM_OBJECT_SUBTYPE := ds.FieldByName('NUM_OBJECT_SUBTYPE').AsInteger; o.NUM_ZONE_NUMBER := ds.FieldByName('NUM_ZONE_NUMBER').AsInteger; o.coordX := ds.FieldByName('NUM_RESEARCH_RESULT_X').AsFloat; o.coordY := ds.FieldByName('NUM_RESEARCH_RESULT_Y').AsFloat; o.dtmEnteringDate := ds.FieldByName('DTM_ENTERING_DATE').AsDateTime; if Assigned (FAllSourcesCoord) then o.SourceCoord := FAllSourcesCoord.ItemsByID[ds.FieldByName('SOURCE_ID').AsInteger] as TSourceCoord; ds.Next; end; ds.First; end; end; function TWellCoordDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TWellCoord; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := AObject as TWellCoord; ds.FieldByName('OBJECT_UIN').Value := o.Collection.Owner.ID; ds.FieldByName('NUM_OBJECT_TYPE').Value := 1; ds.FieldByName('NUM_RESEARCH_RESULT_X').Value := o.coordX; ds.FieldByName('NUM_RESEARCH_RESULT_Y').Value := o.coordY; ds.FieldByName('NUM_ZONE_NUMBER').Value := 10; if Assigned (o.SourceCoord) then ds.FieldByName('SOURCE_ID').Value := o.SourceCoord.ID; ds.Post; end; procedure TWellCoordDataPoster.SetAllSourcesCoord( const Value: TSourceCoords); begin if FAllSourcesCoord <> Value then FAllSourcesCoord := Value; end; { TSourceCoordDataPoster } constructor TSourceCoordDataPoster.Create; begin inherited; Options := [soSingleDataSource, soKeyInsert]; DataSourceString := 'TBL_SOURCE_DICT'; KeyFieldNames := 'SOURCE_ID'; FieldNames := 'SOURCE_ID, VCH_SOURCE_NAME'; AccessoryFieldNames := ''; AutoFillDates := false; Sort := 'VCH_SOURCE_NAME'; end; function TSourceCoordDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TSourceCoordDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TSourceCoord; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TSourceCoord; o.ID := ds.FieldByName('SOURCE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_SOURCE_NAME').AsString); ds.Next; end; ds.First; end; end; function TSourceCoordDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
{ Practica 1 Ejercicio 7b } program p1e7b; uses strings,Crt; type arreglo100 = array[1..100] of integer; procedure intercambio( var a,b: integer ); var aux :integer; begin aux := a; a := b; b := aux; end; procedure busca_minimo_y_reemplaza(var s: arreglo100; a: integer); var i,pos_min: Integer; begin pos_min := 1; for I := 2 to 100 do begin if s[i] < s[pos_min] then pos_min := i ; end; writeln('minimo: ',s[pos_min] ); intercambio( s[pos_min], a ); end; var i: integer; nuevo: integer; arreglo : arreglo100; begin Randomize; for i:=1 to 100 do arreglo[i] := Random(1000); nuevo := Random(1000); busca_minimo_y_reemplaza(arreglo,nuevo); end.
unit Controller.EMPRESA.Interfaces; interface uses Data.DB, System.JSON, System.Generics.Collections, VCL.Forms, Model.Entity.EMPRESA; type iControllerEMPRESA = interface ['{8937F610-F66D-4298-BE67-788F242BE50F}'] function DataSource (aDataSource : TDataSource) : iControllerEMPRESA; overload; function DataSource : TDataSource; overload; function Buscar : iControllerEMPRESA; overload; function Buscar(aID : integer) : iControllerEMPRESA; overload; function Buscar(aFiltro : TJsonobject; aOrdem : string) : iControllerEMPRESA; overload; function Buscar(aSQL : string) : iControllerEMPRESA; overload; function Insert : iControllerEMPRESA; function Delete : iControllerEMPRESA; function Update : iControllerEMPRESA; function Clear: iControllerEMPRESA; function Ultimo(where : string) : iControllerEMPRESA; function EMPRESA : TEMPRESA; function FromJsonObject(aJson : TJsonObject) : iControllerEMPRESA; function List : TObjectList<TEMPRESA>; function ExecSQL(sql : string) : iControllerEMPRESA; function BindForm(aForm : TForm) : iControllerEMPRESA; end; implementation end.
unit UxlExtClasses; interface uses UxlList, UxlClasses, UxlWinControl; type ISaver = interface procedure Save (); end; TxlSaveCenter = class (TxlInterfacedObject, ISaver) private FObservers: TxlInterfaceList; protected procedure OnCreate(); virtual; procedure OnDestroy(); virtual; public constructor Create (); virtual; destructor Destroy (); override; procedure AddObserver (o_observer: ISaver); procedure RemoveObserver(o_observer: ISaver); procedure Save (); virtual; end; type IOptionObserver = Interface procedure OptionChanged (); end; TxlOption = class private FObservers: TxlInterfaceList; protected procedure OnCreate (); virtual; procedure OnDestroy (); virtual; procedure DoLoad (); virtual; abstract; procedure DoSave (); virtual; abstract; function DoSetOptions (WndParent: TxlWinControl): boolean; virtual; abstract; procedure NotifyObservers (); public constructor Create (); destructor Destroy (); override; procedure SetOptions (WndParent: TxlWinControl); procedure AddObserver (o_obj: IOptionObserver); procedure RemoveObserver (o_obj: IOptionObserver); end; type IMemorizer = Interface procedure SaveMemory (); procedure RestoreMemory (); end; TxlMemory = class (TxlInterfacedObject, ISaver) private FObservers: TxlInterfaceList; protected procedure OnCreate (); virtual; procedure OnDestroy (); virtual; procedure DoLoad (); virtual; abstract; procedure DoSave (); virtual; abstract; public constructor Create (); destructor Destroy (); override; procedure Save (); procedure AddObserver (o_obj: IMemorizer); procedure RemoveObserver (o_obj: IMemorizer); end; type ILangObserver = Interface procedure LanguageChanged(); end; TxlLanguage = class (TxlInterfacedObject) private FItemList: TxlStrList; FObservers: TxlInterfaceList; FLanguage: widestring; // 当前语言 FInnerLanguage: widestring; // 字符串嵌入代码之中的语言 function LoadResourceString (id: integer): widestring; protected procedure FillItems (var lang: widestring; itemlist: TxlStrList); virtual; abstract; public constructor Create (); destructor Destroy (); override; procedure SetLanguage (value: widestring = ''); procedure SetInnerLanguage (const value: widestring); property Language: widestring read FLanguage write SetLanguage; // 优先搜索 FItemList,其次 s_defvalue,再次 LoadResourceString; // 允许某些语言 fillitems,某些直接写在代码(s_defvalue)中,某些写在资源文件里 function GetItem (i_index: integer; const s_defvalue: widestring = ''): widestring; procedure AddObserver (o_observer: ILangObserver); procedure RemoveObserver(o_observer: ILangObserver); end; type IEventObserver = interface procedure EventNotify (event, wparam, lparam: integer); end; TxlEventCenter = class (TxlInterfacedObject) private FObservers: TxlInterfaceList; // FMessages: TxlStrList; FMessage: widestring; public constructor Create (); destructor Destroy (); override; procedure AddObserver (o_observer: IEventObserver); procedure RemoveObserver(o_observer: IEventObserver); procedure EventNotify (event: integer; wparam: integer = 0; lparam: integer = 0); property Message: widestring read FMessage write FMessage; // function AddMessage (const s_msg: widestring): integer; // returns message id // function GetMessage (id: integer): widestring; end; type IListProvider = interface procedure FillList (id: integer; o_list: TxlStrList); function GetSubItem (id: integer; var i_index: integer; var s_result: widestring; i_maxchar: integer = -1): boolean; end; TxlListCenter = class private FProviders: TxlInterfaceList; public constructor Create (); destructor Destroy (); override; procedure AddProvider (o_provider: IListProvider); procedure RemoveProvider (o_provider: IListProvider); procedure FillList (id: integer; o_list: TxlStrList); function GetSubItem (id: integer; var i_index: integer; var s_result: widestring; i_maxchar: integer = -1): boolean; end; type ICommandSender = interface procedure SetItemChecked (id: word; value: boolean); function GetItemChecked (id: word): boolean; procedure SetItemEnabled (id: word; value: boolean); function GetItemEnabled (id: word): boolean; procedure SetItemVisible (id: word; value: boolean); function GetItemVisible (id: word): boolean; procedure SetItemText (id: word; const value: widestring); function GetItemText (id: word): widestring; procedure SetCommandProc (value: TCommandEvent); function ItemExists (id: word): boolean; procedure GetItemList (o_list: TxlIntList); end; ICommandExecutor = interface function CheckCommand (opr: word): boolean; procedure ExecuteCommand (opr: word); end; TxlCommandCenter = class (TxlInterfacedObject) private FSenderList: TxlInterfaceList; FExecutorList: TxlInterfaceList; FOnCommand: TCommandEvent; protected procedure SetItemChecked (id: word; value: boolean); procedure SetItemEnabled (id: word; value: boolean); function GetItemChecked (id: word): boolean; function GetItemEnabled (id: word): boolean; procedure SetItemVisible (id: word; value: boolean); function GetItemVisible (id: word): boolean; procedure SetItemText (id: word; const value: widestring); function GetItemText (id: word): widestring; procedure SetCommandProc (value: TCommandEvent); public constructor Create (); destructor Destroy (); override; procedure AddSender (obj: ICommandSender); procedure RemoveSender (obj: ICommandSender); procedure AddExecutor (obj: ICommandExecutor); procedure RemoveExecutor (obj: ICommandExecutor); function ItemExists (id: word): boolean; procedure ExecuteCommand (opr: word); function CheckCommand (opr: word): boolean; procedure CheckCommands (); virtual; procedure SwitchCheck (id: word); property ItemText[id: word]: widestring read GetItemText write SetItemText; property ItemEnabled[id: word]: boolean read GetItemEnabled write SetItemEnabled; property ItemChecked[id: word]: boolean read GetItemChecked write SetItemChecked; property ItemVisible[id: word]: boolean read GetItemVisible write SetItemVisible; property OnCommand: TCommandEvent read FOnCommand write SetCommandProc; end; implementation uses Windows, UxlFunctions, UxlStrUtils; constructor TxlSaveCenter.Create (); begin FObservers := TxlInterfaceList.Create(); OnCreate; end; destructor TxlSaveCenter.Destroy (); begin OnDestroy; FObservers.free; inherited; end; procedure TxlSaveCenter.OnCreate(); begin end; procedure TxlSaveCenter.OnDestroy(); begin end; procedure TxlSaveCenter.AddObserver (o_observer: ISaver); begin FObservers.Add(o_observer); end; procedure TxlSaveCenter.RemoveObserver(o_observer: ISaver); begin FObservers.Remove (o_observer); end; procedure TxlSaveCenter.Save (); var i: integer; begin i := FObservers.Low; while i <= FObservers.High do begin if FObservers[i] <> nil then ISaver (FObservers[i]).Save; inc (i); end; end; //------------------------- constructor TxlOption.Create (); begin FObservers := TxlInterfaceList.Create(); OnCreate; DoLoad; end; destructor TxlOption.Destroy (); begin FObservers.Free; OnDestroy; inherited; end; procedure TxlOption.OnCreate (); begin end; procedure TxlOption.OnDestroy (); begin end; procedure TxlOption.AddObserver (o_obj: IOptionObserver); begin FObservers.Add (o_obj); o_obj.OptionChanged (); end; procedure TxlOption.RemoveObserver (o_obj: IOptionObserver); begin FObservers.Remove (o_obj); end; procedure TxlOption.SetOptions (WndParent: TxlWinControl); begin if DoSetOptions (WndParent) then begin DoSave; NotifyObservers; end; end; procedure TxlOption.NotifyObservers (); var i: integer; begin i := FObservers.Low; while i <= FObservers.High do // SetOption 的过程中可能有些对象 RemoveObserver 导致 High 变化。因此用 for 循环不妥 begin if FObservers[i] <> nil then IOptionObserver(FObservers[i]).OptionChanged (); inc (i); end; end; //---------------------------- constructor TxlMemory.Create (); begin FObservers := TxlInterfaceList.Create; OnCreate; DoLoad; end; destructor TxlMemory.Destroy (); begin OnDestroy; FObservers.Free; inherited; end; procedure TxlMemory.AddObserver (o_obj: IMemorizer); begin FObservers.Add (o_obj); o_obj.RestoreMemory (); end; procedure TxlMemory.RemoveObserver(o_obj: IMemorizer); begin FObservers.Remove (o_obj); end; procedure TxlMemory.Save (); var i: integer; begin i := FObservers.Low; while i <= FObservers.High do begin if FObservers[i] <> nil then IMemorizer(FObservers[i]).SaveMemory (); inc (i); end; DoSave; end; procedure TxlMemory.OnCreate (); begin end; procedure TxlMemory.OnDestroy (); begin end; //------------------ constructor TxlLanguage.Create (); begin FItemList := TxlStrList.create; FObservers := TxlInterfaceList.Create(); FLanguage := ''; end; destructor TxlLanguage.Destroy (); begin FItemList.free; FObservers.Free; inherited; end; procedure TxlLanguage.SetLanguage (value: widestring = ''); var i: integer; begin if value = '' then value := IfThen (IsLocaleChinese(), 'Chinese', 'English'); if value <> FLanguage then begin FLanguage := value; FillItems (FLanguage, FItemList); i := FObservers.Low; while i <= FObservers.High do begin if FObservers[i] <> nil then ILangObserver(FObservers[i]).LanguageChanged ; inc (i); end; end; end; procedure TxlLanguage.SetInnerLanguage(const value: widestring); begin FInnerLanguage := value; end; procedure TxlLanguage.AddObserver(o_observer: ILangObserver); begin FObservers.Add(o_observer); if FLanguage <> '' then o_observer.LanguageChanged; end; procedure TxlLanguage.RemoveObserver(o_observer: ILangObserver); begin FObservers.Remove (o_observer); end; function TxlLanguage.GetItem (i_index: integer; const s_defvalue: widestring = ''): widestring; begin result := FItemList.ItemsByIndex [i_index]; if result = '' then begin if IsSameStr(FLanguage, FInnerLanguage) and (s_defvalue <> '') then result := s_defvalue else result := LoadResourceString (i_index); end; result := ReplaceStrings (result, ['\t', '\n'], [#9, #13#10]); end; var FResStringBuffer: array[0..2000] of ansichar; function TxlLanguage.LoadResourceString (id: integer): widestring; var s: pansichar; begin LoadStringA (system.MainInstance, id, FResStringBuffer, 2000); s := FResSTringBuffer; result := AnsiToUnicode (s); end; //------------------------ constructor TxlEventCenter.Create (); begin FObservers := TxlInterfaceList.Create(); end; destructor TxlEventCenter.Destroy (); begin FObservers.free; inherited; end; procedure TxlEventCenter.AddObserver (o_observer: IEventObserver); begin FObservers.Add(o_observer); end; procedure TxlEventCenter.RemoveObserver(o_observer: IEventObserver); begin FObservers.Remove (o_observer); end; procedure TxlEventCenter.EventNotify (event: integer; wparam: integer = 0; lparam: integer = 0); var i: integer; begin i := FObservers.Low; while i <= FObservers.High do begin if FObservers[i] <> nil then IEventObserver(FObservers[i]).EventNotify (event, wparam, lparam); inc (i); end; end; //--------------------- constructor TxlListCenter.Create (); begin FProviders := TxlInterfaceList.Create(); end; destructor TxlListCenter.Destroy (); begin FProviders.Free; inherited; end; procedure TxlListCenter.AddProvider (o_provider: IListProvider); begin FProviders.Add (o_provider); end; procedure TxlListCenter.RemoveProvider (o_provider: IListProvider); begin FProviders.Remove (o_provider); end; procedure TxlListCenter.FillList (id: integer; o_list: TxlStrList); var i: integer; begin i := FProviders.Low; while i <= FProviders.High do begin if FProviders[i] <> nil then IListProvider(FProviders[i]).FillList (id, o_list); inc (i); end; end; function TxlListCenter.GetSubItem (id: integer; var i_index: integer; var s_result: widestring; i_maxchar: integer = -1): boolean; var i: integer; begin result := false; for i := FProviders.Low to FProviders.High do if (FProviders[i] <> nil) then begin result := IListProvider(FProviders[i]).GetSubItem (id, i_index, s_result, i_maxchar); if result then exit; end; end; //--------------------- constructor TxlCommandCenter.Create (); begin FSenderList := TxlInterfaceList.Create(); FExecutorList := TxlInterfaceList.Create(); FOnCommand := ExecuteCommand; end; destructor TxlCommandCenter.Destroy (); begin FSenderList.Free; FExecutorList.Free; inherited; end; procedure TxlCommandCenter.AddSender (obj: ICommandSender); begin FSenderList.Add(obj); obj.SetCommandProc (FOnCommand); end; procedure TxlCommandCenter.RemoveSender (obj: ICommandSender); begin FSenderList.Remove (obj); end; procedure TxlCommandCenter.AddExecutor (obj: ICommandExecutor); begin FExecutorList.Add(obj); end; procedure TxlCommandCenter.RemoveExecutor (obj: ICommandExecutor); begin FExecutorList.Remove(obj); end; procedure TxlCommandCenter.ExecuteCommand (opr: word); var i: integer; begin i := FExecutorList.Low; while i <= FExecutorList.High do begin if FExecutorList[i] <> nil then ICommandExecutor(FExecutorList[i]).ExecuteCommand(opr); inc (i); end; end; function TxlCommandCenter.CheckCommand (opr: word): boolean; var i: integer; begin i := FExecutorList.Low; while i <= FExecutorList.High do begin if (FExecutorList[i] <> nil) and (not ICommandExecutor(FExecutorList[i]).CheckCommand (opr)) then begin if ItemEnabled[opr] then ItemEnabled[opr] := false; result := false; exit; end; inc (i); end; if not ItemEnabled[opr] then // 性能优化,防止闪烁 ItemEnabled[opr] := true; result := true; end; procedure TxlCommandCenter.CheckCommands (); var i, j: integer; o_list: TxlIntList; begin o_list := TxlIntList.Create(); i := FSenderList.Low; while i <= FSenderList.High do begin if FSenderList[i] <> nil then begin ICommandSender(FSenderList[i]).GetItemList(o_list); for j := o_list.Low to o_list.High do CheckCommand (o_list[j]); end; inc (i); end; o_list.free; end; procedure TxlCommandCenter.SetItemChecked (id: word; value: boolean); var i: integer; begin for i := FSenderList.Low to FSenderList.High do ICommandSender(FSenderList[i]).SetItemChecked (id, value); end; function TxlCommandCenter.GetItemChecked (id: word): boolean; var i: integer; begin result := false; for i := FSenderList.Low to FSenderList.High do if ICommandSender(FSenderList[i]).itemExists (id) then begin result := ICommandSender(FSenderList[i]).GetItemchecked (id); exit; end; end; procedure TxlCommandCenter.SwitchCheck (id: word); var i: integer; ic: ICommandSender; begin for i := FSenderList.Low to FSenderList.High do begin ic := ICommandSender(FSenderList[i]); if ic.itemExists (id) then ic.SetItemChecked ( id, not ic.GetItemChecked(id) ); end; end; procedure TxlCommandCenter.SetItemEnabled (id: word; value: boolean); var i: integer; begin for i := FSenderList.Low to FSenderList.High do ICommandSender(FSenderList[i]).SetItemEnabled (id, value); end; function TxlCommandCenter.GetItemEnabled (id: word): boolean; var i: integer; begin result := false; for i := FSenderList.Low to FSenderList.High do if ICommandSender(FSenderList[i]).itemExists (id) then begin result := ICommandSender(FSenderList[i]).GetItemEnabled (id); exit; end; end; procedure TxlCommandCenter.SetItemVisible (id: word; value: boolean); var i: integer; begin for i := FSenderList.Low to FSenderList.High do ICommandSender(FSenderList[i]).SetItemVisible (id, value); end; function TxlCommandCenter.GetItemVisible (id: word): boolean; var i: integer; begin result := false; for i := FSenderList.Low to FSenderList.High do if ICommandSender(FSenderList[i]).itemExists (id) then begin result := ICommandSender(FSenderList[i]).GetItemVisible (id); exit; end; end; procedure TxlCommandCenter.SetItemText (id: word; const value: widestring); var i: integer; begin for i := FSenderList.Low to FSenderList.High do ICommandSender(FSenderList[i]).SetItemText (id, value); end; function TxlCommandCenter.GetItemText (id: word): widestring; var i: integer; begin result := ''; for i := FSenderList.Low to FSenderList.High do if ICommandSender(FSenderList[i]).itemExists (id) then begin result := ICommandSender(FSenderList[i]).GetItemText (id); exit; end; end; function TxlCommandCenter.ItemExists (id: word): boolean; var i: integer; begin result := false; for i := FSenderList.Low to FSenderList.High do if ICommandSender(FSenderList[i]).itemExists (id) then begin result := true; exit; end; end; procedure TxlCommandCenter.SetCommandProc (value: TCommandEvent); var i: integer; begin FOnCommand := value; for i := FSenderList.Low to FSenderList.High do ICommandSender(FSenderList[i]).SetCommandProc (value); end; end.
unit DataBaseUtil; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,Data.DB, Datasnap.DBClient, SimpleDS, Data.SqlExpr, Data.DBXMySQL, Data.DBXOracle, Data.Win.ADODB, Vcl.StdCtrls; const DBConnectionStr='Driver={MySQL ODBC 8.0 Unicode Driver};Server=127.0.0.1;Database=wikibase;User=root; Password=5166266skf;Option=3;'; const SplitChar='&&&&'; type TDataBaseUtil=class public constructor Create(); overload; //constructor Create(Connection:TADOConnection); overload; destructor Destroy();override; function QueryEntityInfoByName(EntityName:String):TStringList; private Connection:TADOConnection; function QueryEntityInfo(sql:string):TStringList; end; implementation uses MainWin; { TDataBaseUtil } constructor TDataBaseUtil.Create; begin self.Connection:=TADOConnection.Create(nil); self.Connection.ConnectionString:=DBConnectionStr; self.Connection.LoginPrompt:=false; self.Connection.Connected:=True; //self.Connection.Provider:='MSDASQL'; end; destructor TDataBaseUtil.Destroy; begin inherited; self.Connection.Close; end; function TDataBaseUtil.QueryEntityInfo(sql: string): TStringList; var AdoQuery : TADOQuery; StringList:TStringList; begin AdoQuery:=TADOQuery.Create(nil); try AdoQuery.Connection:=self.Connection; AdoQuery.SQL.Add(sql); AdoQuery.Open; StringList:=TStringList.Create; while not AdoQuery.eof do begin StringList.Add(AdoQuery.FieldByName('ID').AsString+SplitChar+ AdoQuery.FieldByName('Name').AsString+SplitChar+ AdoQuery.FieldByName('Description').AsString); AdoQuery.Next; end; result:=StringList; finally AdoQuery.Free; end; end; function TDataBaseUtil.QueryEntityInfoByName(EntityName:String): TStringList; begin result:=self.QueryEntityInfo('select ID,Name,Description from itemInfo where Name="'+EntityName+'"'); end; end.
unit cssmin; { cssmin.pas - 2010-05-05 Author: Mihail Slobodyanuk (slobodyanukma@ukr.net, slobodyanukma@gmail.com) } interface uses Classes; { level 1 - class and comment per line level 2 - all by one line } function css_min(css_source_text: string; level: Integer=1; remove_last_semicolons: Boolean = true; remove_comments: Boolean = true):string; implementation uses SysUtils, StrUtils, functions; type TToken = record value:string; ttype:string; end; Tcss_min = class input, token_text, token_type, last_type, indent_string: string; output: TStringList; whitespace, wordchar: TStringArray; parser_pos: integer; just_added_newline, do_block_just_closed: Boolean; css_source_text: string; opt:record level: Integer; remove_last_semicolons: Boolean; remove_comments: Boolean end; input_length: Integer; in_html_comment:Boolean; function get_next_token: TToken; procedure print_single_space; procedure print_token; procedure trim_output(eat_newlines:Boolean = false); procedure print_newline(ignore_repeated: Boolean = false); public constructor Create(css_source_text: string; level: Integer; remove_last_semicolons: Boolean; remove_comments: Boolean); destructor Destroy; override; function getMin: string; end; constructor Tcss_min.Create(css_source_text: string; level: Integer; remove_last_semicolons: Boolean; remove_comments: Boolean); begin Self.css_source_text := css_source_text; opt.level := level; opt.remove_last_semicolons := remove_last_semicolons; opt.remove_comments := remove_comments; output := TStringList.Create(); whitespace := split(#13#10#9' '); wordchar := split('/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_!@#$%^&*()=.-+'); in_html_comment:=False; end; destructor Tcss_min.Destroy; begin Output.free; end; function Tcss_min.getMin(): string; var t: TToken; i: Integer; lines: TStringArray; label next_token; begin just_added_newline := false; // cache the source's length. input_length := length(css_source_text); //---------------------------------- indent_string := ''; input := css_source_text; last_type := 'TK_END_BLOCK'; // last token type parser_pos := 0; while true do begin t := get_next_token; token_text := t.value; token_type := t.ttype; if token_type = 'TK_EOF' then begin break; end else if token_type = 'TK_WORD' then begin if (last_type='TK_END_BLOCK') then begin print_newline; end else if (last_type='TK_WORD') then begin print_single_space; end else if (last_type='TK_BLOCK_COMMENT') then begin print_newline(); end; print_token(); end else if (token_type = 'TK_COLON') then begin print_token(); end else if (token_type = 'TK_COMMA') then begin print_token(); end else if token_type = 'TK_START_BLOCK' then begin print_token(); end else if token_type = 'TK_END_BLOCK' then begin //Remove last ";" if opt.remove_last_semicolons and (last_type='TK_SEMICOLON') then output.Delete(output.Count - 1); print_token(); end else if token_type = 'TK_SEMICOLON' then begin print_token(); end else if token_type = 'TK_BLOCK_COMMENT' then begin if not opt.remove_comments then begin lines := split(StringReplace(token_text, #13#10, #10, [rfReplaceAll]), #10); print_newline(); output.add(Trim(lines[0])); for i := 1 to high(lines) do begin output.add(' '); output.add(Trim(lines[i])); end; end else //do not change last_type Continue; end else if token_type = 'TK_INLINE_COMMENT' then begin if not opt.remove_comments then begin print_token(); end; //do not change last_type Continue; end else if token_type = 'TK_UNKNOWN' then begin print_single_space(); print_token(); end; next_token: last_type := token_type; end; result := join(output); if Copy(result, Length(Result), 1)=#10 then result:=Copy(result, 1, Length(Result)-1); result := StringReplace(result, #10, #13#10, [rfReplaceAll]); end; procedure Tcss_min.trim_output(eat_newlines:Boolean = false); begin while ((output.Count > 0) and ((output.Strings[output.Count - 1] = ' ') or (output.Strings[output.Count - 1] = indent_string) or (eat_newlines and ((output.Strings[output.Count - 1] = #10) or (output.Strings[output.Count - 1] = #13))))) do begin output.Delete(output.Count - 1); end; end; procedure Tcss_min.print_newline(ignore_repeated: Boolean = false); var i: Integer; begin trim_output(); if (output.Count = 0) then begin exit; // no newline on start of file end; if ((output.Strings[output.Count - 1] <> #10) or not ignore_repeated) then begin just_added_newline := true; if opt.level=1 then output.add(#10); end; end; procedure Tcss_min.print_single_space; var last_output: string; begin last_output := ' '; if (output.count > 0) then begin last_output := output.Strings[output.count - 1]; end; if ((last_output <> ' ') and (last_output <> #10) and (last_output <> indent_string)) then begin // prevent occassional duplicate space output.add(' '); end; end; procedure Tcss_min.print_token; begin just_added_newline := false; output.add(token_text); end; function Tcss_min.get_next_token: TToken; var c: string; comment: string; inline_comment: boolean; beginLine:Boolean; begin if (parser_pos >= input_length) then begin result.value := ''; result.ttype := 'TK_EOF'; Exit; end; beginLine:=False; if parser_pos=0 then beginLine:=true; c := input[parser_pos + 1]; Inc(parser_pos); while (in_array(c, whitespace)) do begin if c=#10 then beginLine:=True; if (parser_pos >= input_length) then begin result.value := ''; result.ttype := 'TK_EOF'; Exit; end; c := input[parser_pos + 1]; Inc(parser_pos); end; if (c = '/') then begin comment := ''; // peek for comment /* ... */ inline_comment := not beginLine; if (input[parser_pos + 1] = '*') then begin Inc(parser_pos); if (parser_pos < input_length) then begin while not ((input[parser_pos + 1] = '*') and (input[parser_pos + 2] = '/') and (parser_pos < input_length)) do begin c := input[parser_pos + 1]; comment := comment + c; if (c = #13) or (c = #10) then begin inline_comment := false; end; Inc(parser_pos); if (parser_pos >= input_length) then begin break; end; end; end; Inc(parser_pos, 2); if (inline_comment) then begin result.value := '/*' + comment + '*/'; result.ttype := 'TK_INLINE_COMMENT'; Exit; end else begin Result.value := '/*' + comment + '*/'; result.ttype := 'TK_BLOCK_COMMENT'; Exit; end; end; end; if (c = '-') and in_html_comment and (Copy(input, parser_pos, 3) = '-->') then begin in_html_comment := false; Inc(parser_pos, 2); result.value := '-->'; result.ttype := 'TK_BLOCK_COMMENT'; Exit; end; if (in_array(c, wordchar)) then begin if (parser_pos < input_length) then begin while (in_array(input[parser_pos + 1], wordchar)) do begin c := c + input[parser_pos + 1]; Inc(parser_pos); if (parser_pos = input_length) then begin break; end; end; end; result.value := c; result.ttype := 'TK_WORD'; Exit; end; if (c = '{') then begin result.value := c; result.ttype := 'TK_START_BLOCK'; Exit; end; if (c = '}') then begin result.value := c; result.ttype := 'TK_END_BLOCK'; Exit; end; if (c = ';') then begin result.value := c; result.ttype := 'TK_SEMICOLON'; Exit; end; if (c = ':') then begin result.value := c; result.ttype := 'TK_COLON'; Exit; end; if (c = ',') then begin result.value := c; result.ttype := 'TK_COMMA'; Exit; end; if (c = '<') and (Copy(input, parser_pos, 4) = '<!--') then begin Inc(parser_pos, 3); in_html_comment := true; result.value := '<!--'; result.ttype := 'TK_BLOCK_COMMENT'; Exit; end; result.value := c; result.ttype := 'TK_UNKNOWN'; Exit; end; function css_min(css_source_text: string; level: Integer=1; remove_last_semicolons: Boolean = true; remove_comments: Boolean = true):string; var jsb:Tcss_min; begin jsb := Tcss_min.Create( css_source_text, level, remove_last_semicolons, remove_comments); result:=jsb.getMin; jsb.free; end; end.
(* * file formats for archives created by pkzip * s.smith, 2-2-89 * *) {$m 6000,0,0} {$s-,r-} {$d+,l+} {$v-} uses MdosIO, DOS; const version = 'ZipV 1.1 - Verbose ZIP directory listing - S.H.Smith, 2-17-89'; type signature_type = longint; const local_file_header_signature = $04034b50; type local_file_header = record version_needed_to_extract: word; general_purpose_bit_flag: word; compression_method: word; last_mod_file_time: word; last_mod_file_date: word; crc32: longint; compressed_size: longint; uncompressed_size: longint; filename_length: word; extra_field_length: word; end; const central_file_header_signature = $02014b50; type central_directory_file_header = record version_made_by: word; version_needed_to_extract: word; general_purpose_bit_flag: word; compression_method: word; last_mod_file_time: word; last_mod_file_date: word; crc32: longint; compressed_size: longint; uncompressed_size: longint; filename_length: word; extra_field_length: word; file_comment_length: word; disk_number_start: word; internal_file_attributes: word; external_file_attributes: longint; relative_offset_local_header: longint; end; const end_central_dir_signature = $06054b50; type end_central_dir_record = record number_this_disk: word; number_disk_with_start_central_directory: word; total_entries_central_dir_on_this_disk: word; total_entries_central_dir: word; size_central_directory: longint; offset_start_central_directory: longint; zipfile_comment_length: word; end; const compression_methods: array[0..6] of string[8] = (' Stored ', ' Shrunk ', 'Reduce-1', 'Reduce-2', 'Reduce-3', 'Reduce-4', '?'); var zipfd: dos_handle; zipfn: dos_filename; type string8 = string[8]; (* ---------------------------------------------------------- *) procedure get_string(len: word; var s: string); var n: word; begin if len > 255 then len := 255; n := dos_read(zipfd,s[1],len); s[0] := chr(len); end; (* ---------------------------------------------------------- *) procedure itoa2(i: integer; var sp); var s: array[1..2] of char absolute sp; begin s[1] := chr( (i div 10) + ord('0')); s[2] := chr( (i mod 10) + ord('0')); end; function format_date(date: word): string8; const s: string8 = 'mm-dd-yy'; begin itoa2(((date shr 9) and 127)+80, s[7]); itoa2( (date shr 5) and 15, s[1]); itoa2( (date ) and 31, s[4]); format_date := s; end; function format_time(time: word): string8; const s: string8 = 'hh:mm:ss'; begin itoa2( (time shr 11) and 31, s[1]); itoa2( (time shr 5) and 63, s[4]); itoa2( (time shl 1) and 63, s[7]); format_time := s; end; (* ---------------------------------------------------------- *) procedure process_local_file_header; var n: word; rec: local_file_header; filename: string; extra: string; begin n := dos_read(zipfd,rec,sizeof(rec)); get_string(rec.filename_length,filename); get_string(rec.extra_field_length,extra); writeln(rec.uncompressed_size:7,' ', compression_methods[rec.compression_method]:8,' ', rec.compressed_size:7,' ', format_date(rec.last_mod_file_date),' ', format_time(rec.last_mod_file_time),' ', filename); dos_lseek(zipfd,rec.compressed_size,seek_cur); end; (* ---------------------------------------------------------- *) procedure process_central_file_header; var n: word; rec: central_directory_file_header; filename: string; extra: string; comment: string; begin n := dos_read(zipfd,rec,sizeof(rec)); get_string(rec.filename_length,filename); get_string(rec.extra_field_length,extra); get_string(rec.file_comment_length,comment); (************** writeln; writeln('central file header'); writeln(' filename = ',filename); writeln(' extra = ',extra); writeln(' file comment = ',comment); writeln(' version_made_by = ',rec.version_made_by); writeln(' version_needed_to_extract = ',rec.version_needed_to_extract); writeln(' general_purpose_bit_flag = ',rec.general_purpose_bit_flag); writeln(' compression_method = ',rec.compression_method); writeln(' last_mod_file_time = ',rec.last_mod_file_time); writeln(' last_mod_file_date = ',rec.last_mod_file_date); writeln(' crc32 = ',rec.crc32); writeln(' compressed_size = ',rec.compressed_size); writeln(' uncompressed_size = ',rec.uncompressed_size); writeln(' disk_number_start = ',rec.disk_number_start); writeln(' internal_file_attributes = ',rec.internal_file_attributes); writeln(' external_file_attributes = ',rec.external_file_attributes); writeln(' relative_offset_local_header = ',rec.relative_offset_local_header); ***********) dos_lseek(zipfd,rec.compressed_size,seek_cur); end; (* ---------------------------------------------------------- *) procedure process_end_central_dir; var n: word; rec: end_central_dir_record; comment: string; begin n := dos_read(zipfd,rec,sizeof(rec)); get_string(rec.zipfile_comment_length,comment); (******* writeln; writeln('end central dir'); writeln(' zipfile comment = ',comment); writeln(' number_this_disk = ',rec.number_this_disk); writeln(' number_disk_with_start_central_directory = ',rec.number_disk_with_start_central_directory); writeln(' total_entries_central_dir_on_this_disk = ',rec.total_entries_central_dir_on_this_disk); writeln(' total_entries_central_dir = ',rec.total_entries_central_dir); writeln(' size_central_directory = ',rec.size_central_directory); writeln(' offset_start_central_directory = ',rec.offset_start_central_directory); ********) end; (* ---------------------------------------------------------- *) procedure process_headers; var sig: longint; fail: integer; begin fail := 0; while true do begin if dos_read(zipfd,sig,sizeof(sig)) <> sizeof(sig) then exit else if sig = local_file_header_signature then process_local_file_header else if sig = central_file_header_signature then process_central_file_header else if sig = end_central_dir_signature then process_end_central_dir else begin inc(fail); if fail > 100 then begin writeln('invalid zipfile header'); exit; end; end; end; end; (* ---------------------------------------------------------- *) procedure list_zip(name: dos_filename); begin zipfd := dos_open(name,open_read); if zipfd = dos_error then begin writeln('Can''t open: ',name); halt(1); end; writeln; if (pos('?',zipfn)+pos('*',zipfn)) > 0 then begin writeln('Zipfile: '+name); writeln; end; writeln(' Size Method Zipped Date Time File Name'); writeln('-------- -------- -------- -------- -------- -------------'); process_headers; dos_close(zipfd); end; (* ---------------------------------------------------------- *) var DirInfo: SearchRec; Dir,Nam,Ext: dos_filename; begin if paramcount <> 1 then begin writeln(version); writeln('Usage: ZipV [directory\]zipfile[.zip]'); halt(1); end; zipfn := paramstr(1); if pos('.',zipfn) = 0 then zipfn := zipfn + '.zip'; FSplit(zipfn,Dir,Nam,Ext); FindFirst(zipfn,$21,DirInfo); while (DosError = 0) do begin list_zip(Dir+DirInfo.name); FindNext(DirInfo); end; halt(0); end.
unit ListArtists; interface uses Generics.Collections, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Grid, FMX.Layouts, Artist, Data.Bind.EngExt, Data.Bind.Components, Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, ArtistsController; type TfrmListArtists = class(TForm) TopLabel: TLabel; BottomLayout: TLayout; ButtonLayout: TLayout; btClose: TButton; btEdit: TButton; CenterLayout: TLayout; Grid: TStringGrid; StringColumn1: TStringColumn; StringColumn2: TStringColumn; btNew: TButton; btDelete: TButton; BindScope1: TBindScope; BindingsList1: TBindingsList; BindGridList1: TBindGridList; procedure btEditClick(Sender: TObject); procedure btDeleteClick(Sender: TObject); procedure btNewClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FArtists: TList<TArtist>; FController: TArtistsController; procedure DestroyArtistList; function GetSelectedArtist: TArtist; procedure LoadArtists; end; implementation uses EditArtist; {$R *.fmx} procedure TfrmListArtists.btEditClick(Sender: TObject); var Artist: TArtist; frmEditArtist: TfrmEditArtist; begin Artist := GetSelectedArtist; if Artist = nil then Exit; frmEditArtist := TfrmEditArtist.Create(Self); try frmEditArtist.SetArtist(Artist.Id); frmEditArtist.ShowModal; if frmEditArtist.ModalResult = mrOk then LoadArtists; finally frmEditArtist.Free; end; end; procedure TfrmListArtists.btDeleteClick(Sender: TObject); var Artist: TArtist; Msg: string; begin Artist := GetSelectedArtist; if Artist = nil then Exit; Msg := 'Are you sure you want to delete Artist "' + Artist.ArtistName + '"?'; if MessageDlg(Msg, TMsgDlgType.mtWarning, mbYesNo, 0) = mrYes then begin FController.DeleteArtist(Artist); LoadArtists; end; end; procedure TfrmListArtists.btNewClick(Sender: TObject); var frmEditArtist: TfrmEditArtist; begin frmEditArtist := TfrmEditArtist.Create(Self); try frmEditArtist.ShowModal; if frmEditArtist.ModalResult = mrOk then LoadArtists; finally frmEditArtist.Free; end; end; procedure TfrmListArtists.DestroyArtistList; begin if FArtists = nil then Exit; FArtists.Free; FArtists := nil; end; procedure TfrmListArtists.LoadArtists; begin BindScope1.Active := False; DestroyArtistList; FArtists := FController.GetAllArtists; BindScope1.DataObject := FArtists; BindScope1.Active := True; end; procedure TfrmListArtists.FormCreate(Sender: TObject); begin FController := TArtistsController.Create; LoadArtists; end; procedure TfrmListArtists.FormDestroy(Sender: TObject); begin BindScope1.Active := false; FController.Free; DestroyArtistList; end; function TfrmListArtists.GetSelectedArtist: TArtist; begin if Grid.Selected < 0 then Exit(nil); Result := FArtists[Grid.Selected]; end; procedure TfrmListArtists.GridDblClick(Sender: TObject); begin btEditClick(Sender); end; end.
unit BCEditor.Editor.CompletionProposal.Columns.Title; interface uses System.Classes, Vcl.Graphics, BCEditor.Editor.CompletionProposal.Columns.Title.Colors; type TBCEditorCompletionProposalColumnTitle = class(TPersistent) strict private FCaption: string; FColors: TBCEditorCompletionProposalColumnTitleColors; FFont: TFont; FVisible: Boolean; procedure SetFont(const AValue: TFont); public constructor Create; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; published property Caption: string read FCaption write FCaption; property Colors: TBCEditorCompletionProposalColumnTitleColors read FColors write FColors; property Font: TFont read FFont write SetFont; property Visible: Boolean read FVisible write FVisible default False; end; implementation constructor TBCEditorCompletionProposalColumnTitle.Create; begin inherited; FColors := TBCEditorCompletionProposalColumnTitleColors.Create; FFont := TFont.Create; FFont.Name := 'Courier New'; FFont.Size := 8; FVisible := False; end; destructor TBCEditorCompletionProposalColumnTitle.Destroy; begin FColors.Free; FFont.Free; inherited; end; procedure TBCEditorCompletionProposalColumnTitle.Assign(ASource: TPersistent); begin if ASource is TBCEditorCompletionProposalColumnTitle then with ASource as TBCEditorCompletionProposalColumnTitle do begin Self.FCaption := FCaption; Self.FColors.Assign(FColors); Self.FFont.Assign(FFont); Self.FVisible := FVisible; end else inherited Assign(ASource); end; procedure TBCEditorCompletionProposalColumnTitle.SetFont(const AValue: TFont); begin FFont.Assign(AValue); end; end.
unit gmAureliusDatasetHelpers; interface uses Aurelius.Bind.Dataset, Aurelius.Engine.AbstractManager, Aurelius.Commands.CommandPerformerFactory, Aurelius.Commands.Inserter, Aurelius.Mapping.Explorer, Aurelius.Mapping.Metadata, Data.DB; type TInserterHelper = class helper for TInserter public procedure SetIdentifier(Entity: TObject; const pSeqName: string); end; TBaseAureliusDatasetHelper = class helper for TBaseAureliusDataset public function MyGetPropValue(APropName: string; Obj: TObject): Variant; function MyGetPkValue: Variant; function CurrentObj: TObject; end; TAbstractManagerHelper = class helper for TAbstractManager public function GetCommandFactory: TCommandPerformerFactory; end; TMappingExplorerHelper = class helper for TMappingExplorer public procedure AddSequence(Clazz: TClass; const pSeqNname: string); function MyGetId(AClass: TClass): TMetaId; function GetIdType(Entity: TObject): TFieldType; end; implementation uses Aurelius.Id.AbstractGenerator, Aurelius.Id.IdentityOrSequence, Aurelius.Mapping.Exceptions, System.Variants, System.SysUtils; type TMyMappingExplorer = class(TMappingExplorer); function TAbstractManagerHelper.GetCommandFactory: TCommandPerformerFactory; begin result := CommandFactory; end; function TBaseAureliusDatasetHelper.MyGetPropValue(APropName: string; Obj: TObject): Variant; begin result := self.GetPropValue(APropName, Obj); end; function TBaseAureliusDatasetHelper.MyGetPkValue: Variant; begin result := FieldByName(PSGetKeyFields).Value; end; function TBaseAureliusDatasetHelper.CurrentObj: TObject; var RecBuf: TAureliusRecordBuffer; begin if State = dsInsert then Exit(self.FInsertObject); RecBuf := self.GetActiveRecBuf; if RecBuf = self.NullBuffer then Exit(nil); Result := self.GetBufferRecInfo(RecBuf)^.Obj; end; procedure TInserterHelper.SetIdentifier(Entity: TObject; const pSeqName: string); var IdGenerator: TAbstractGenerator; NewId: Variant; xNameSeq: string; begin if (Explorer.GetIdType(Entity) in [ftInteger]) then begin IdGenerator := TIdentityOrSequenceGenerator.Create(Entity.ClassType, Explorer, SQLGenerator); try if not Explorer.HasIdValue(Entity) then begin // Generate an id for the entity based on selected generator // Se non è stata definita la sequence nel modello (es. per MSSQL Server, per limiti di Data Modeler... // creiamo per default la corrispondenza interna con una sequence che si chiami come la classe della tabella if pSeqName='' then xNameSeq := Entity.ClassName else xNameSeq := pSeqName; if not Explorer.HasSequence(Entity.ClassType, True) then begin Explorer.AddSequence(Entity.ClassType, xNameSeq); end; NewId := IdGenerator.GenerateId(Entity, GetCommandPerformer); if not VarIsEmpty(NewId) then Explorer.SetIdValue(Entity, NewId); end; finally IdGenerator.Free; end; end; end; procedure TMappingExplorerHelper.AddSequence(Clazz: TClass; const pSeqNname: string); var seq: TSequence; Key: string; begin Key := Clazz.ClassName + '.' + BoolToStr(True {IncludeSuperClasses}); seq := TSequence.Create; seq.SequenceName := pSeqNname; //Clazz.ClassName; // Sequence(A).SequenceName; seq.InitialValue := 1; //Sequence(A).InitialValue; seq.Increment := 1; //Sequence(A).Increment; TMyMappingExplorer(self).FSequencesByClass.AddOrSetValue(Key, seq); end; function TMappingExplorerHelper.MyGetId(AClass: TClass): TMetaId; begin try result := GetId(AClass); except on E: EMappingNotFound do result := nil; else raise; end; end; function TMappingExplorerHelper.GetIdType(Entity: TObject): TFieldType; var Cols: TArray<TColumn>; begin Cols := GetIdColumns(Entity.ClassType); if Length(Cols) >= 1 then Result := Cols[0].FieldType else Result := ftUnknown; end; end.
unit transition; {$mode objfpc}{$H+} interface uses Classes, SysUtils, state, BGRABitmap, BGRABitmapTypes, BGRACanvas2D, BCTypes; type { TTransition } {The transition object - really some kind of aggregate of a graphical and nongraphical item...} TTransition = class(TObject) private fSrc: TState; fDst: TState; fPriority: cardinal; fCondition: string; {The transition condition: "if en = '1' and ..."} fCtlPts: array [0..2] of TPoint; fPlacedIdx: cardinal; fSelected: boolean; {Is the whole transition object selected?} procedure SetCondition(AValue: string); procedure SetDest(AValue: TState); procedure SetPriority(AValue: cardinal); procedure SetSource(AValue: TState); public constructor Create; procedure Draw(ABGRABitmap: TBGRABitmap); function HitTest(X, Y: integer): integer; //See if we clicked on a control point; returns index if true, -1 if false function isPlacing: boolean; procedure PlacePoint(APoint: TPoint); {place a control point into fCtlPts, increments fPlacedIdx } property Source: TState read fSrc write SetSource; property Dest: TState read fDst write SetDest; property Priority: cardinal read fPriority write SetPriority; property Condition: string read fCondition write SetCondition; property Selected: boolean read fSelected write fSelected; property Placing: boolean read isPlacing; end; {The basic transition object, with added items for graphical representation} implementation { TTransition } procedure TTransition.SetDest(AValue: TState); begin if fDst = AValue then Exit; fDst := AValue; end; procedure TTransition.SetCondition(AValue: string); begin if fCondition = AValue then Exit; fCondition := AValue; end; procedure TTransition.SetPriority(AValue: cardinal); begin if fPriority = AValue then Exit; fPriority := AValue; end; procedure TTransition.SetSource(AValue: TState); begin if fSrc = AValue then Exit; fSrc := AValue; end; constructor TTransition.Create; var i: cardinal; begin inherited Create; fPlacedIdx := 0; end; procedure TTransition.Draw(ABGRABitmap: TBGRABitmap); begin end; function TTransition.HitTest(X, Y: integer): integer; begin end; function TTransition.isPlacing: boolean; begin if fPlacedIdx < 3 then Result := True else Result := False; end; procedure TTransition.PlacePoint(APoint: TPoint); begin fCtlPts[fPlacedIdx] := APoint; fPlacedIdx := fPlacedIdx + 1; end; end.
unit uCefUtilConst; interface const MYAPP_CEF_MESSAGE_NAME = 'cefappmsg'; //IDX_DEBUG = 0; IDX_TYPE = 0; IDX_EVENT = 2; IDX_RESULT = 3; IDX_VALUE = 4; IDX_ID = 5; IDX_NAME = 6; IDX_ATTR = 7; IDX_LEFT = 8; IDX_TOP = 9; IDX_RIGHT = 10; IDX_BOTTOM = 11; IDX_X = 12; IDX_Y = 13; IDX_WIDTH = 14; IDX_HEIGHT = 15; IDX_TAG = 16; IDX_CLASS = 17; IDX_VALUE2 = 18; IDX_TEXT = 19; IDX_CLICK_CALLBACKID = 1; IDX_CLICK_X = 2; IDX_CLICK_Y = 3; IDX_KEY_CALLBACKID = 1; IDX_KEY_CODE = 2; IDX_CALLBACK_ID = 1; KEY_TAG = '_TAG_'; VAL_TEST_ID_EXISTS = 1; VAL_SET_VALUE_BY_ID = 2; VAL_SET_VALUE_BY_NAME = 3; VAL_SET_ATTR_BY_NAME = 4; VAL_GET_WINDOW_RECT = 5; VAL_GET_ELEMENT_RECT = 6; VAL_TEST_ELEMENT_EXISTS = 7; VAL_GET_BIDY_RECT = 8; VAL_GET_ELEMENT_TEXT = 9; VAL_SET_ELEMENT_VALUE = 10; VAL_SET_SELECT_VALUE = 11; VAL_GET_ELEMENTS_ATTR = 12; VAL_EXEC_CALLBACK = 13; VAL_CLICK_XY = 14; VAL_FOCUSCLICK_XY = 15; VAL_KEY_PRESS = 16; VAL_NOTIFY_STR = 17; VAL_OUTERHTML = 18; VAL_INNERTEXT = 19; VAL_ASMARKUP = 20; SCROLL_WAIT = 3333; CEF_EVENT_WAIT_TIMEOUT = 1 * 60 * 1000; // a minute TIMEOUT_DEF = 60 * 1000; NAV_WAIT_TIMEOUT = 5 * 1000; SCREEN_WAIT_TIMEOUT = 10 * 1000; implementation end.
unit SysStat; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle In dieser Unit ist die Systemstatustask enthalten. Diese gibt die CPU-Last, Uhrzeit, RTKernel-Ticks und die letzte Systemstatusnachricht z.B. eine Fehlermeldung aus. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface uses SysMB; var Mailbox: SysMB.Mailbox; procedure SystemStatusTask; implementation uses DOS, RTTextIO, Timer, CPUMoni, Types, Tools; {$F+} procedure SystemStatusTask; (***************************************************************************** Beschreibung: Systemstatustask. In: - Out: - *****************************************************************************) var Message: TSystemStatusMessage; SystemStatusIn, SystemStatusOut: text; WindowPosition: TWindowPosition; WindowColor: TWindowColor; Success: boolean; H, M, S, CS: word; begin Debug('Wurde erzeugt'); { Mailbox initialisieren } Debug('Initailisiere Mailbox'); InitMailbox(Mailbox, cSystemStatusMailboxSlots, 'Systemstatus mailbox'); Debug('Mailbox initialisiert'); { Fensterposition } Debug('Warte auf Fensterposition'); SysMB.Get(Mailbox, Message); if Message.Kind <> ssmkWindowPosition then Die('Unexpected command in system status'); WindowPosition := Message.WindowPosition; Debug('Fensterposition empfangen'); { Fensterfarben } Debug('Warte auf Fensterfarben'); SysMB.Get(Mailbox, Message); if Message.Kind <> ssmkWindowColor then Die('Unexpected command in system status'); WindowColor := Message.WindowColor; Debug('Fensterfarben empfangen'); { Fenster erzeugen } Debug('Erzeuge Fenster'); NewWindow(SystemStatusIn, SystemStatusOut, WindowPosition.FirstCol, WindowPosition.FirstRow, WindowPosition.LastCol, WindowPosition.LastRow, WindowColor.FrameColor, ' ' + cSystemStatusTaskName + ' '); SetAttribute(SystemStatusOut, WindowColor.Attribute); Debug('Fenster erzeugt'); { Eine leere Meldung erzeugen } Message.Kind := ssmkSystemStatus; Message.Message := ''; Success := true; while true do begin { Fenster leeren } Write(SystemStatusOut, FormFeed); { CPU-Last anzeigen } WriteLn(SystemStatusOut, 'CPU Auslastung: ', CPUMoni.PercentCPUNeeded:5:2, '%'); { Uhrzeit anzeigen } DOS.GetTime(H, M, S, CS); Write(SystemStatusOut, 'Uhrzeit (DOS): ', IntToStr(H, 2), ':', IntToStr(M, 2), ':', IntToStr(S, 2), #$A#$D); { RTKernel-Ticks anzeigen } WriteLn(SystemStatusOut, 'Ticks (RTKernel): ', RTKernel.GetTime); WriteLn(SystemStatusOut); { Sustemstatusmeldung empfangen und anzeigen } if Success then Debug('Warte auf Systemstatus'); GetCond(Mailbox, Message, Success); if Message.Kind <> ssmkSystemStatus then Die('Unexpected command in system status'); Debug('Systemstatus empfangen'); Debug('Gebe Systemstatus aus'); Write(SystemStatusOut, 'Letzte Meldung: ', Message.Message); Debug('Systemstatus ausgegeben'); { Eine Sekunde warten } RTKernel.Delay(Timer.Ticks(1)); end; end; end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.UITypes, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Imaging.pngimage, RzShellDialogs, Vcl.FileCtrl, Vcl.ComCtrls, Bass, ShellAPI, INIFiles, Vcl.Imaging.GIFImg, Math; type TMusicCleaner = class(TForm) Image1: TImage; Label3: TLabel; LblPlaying: TLabel; Label5: TLabel; PathLabel: TLabel; LblStatus: TLabel; LblFile: TLabel; Image2: TImage; BtnSelectFolder: TButton; BtnSettings: TButton; BtnAbout: TButton; BtnPlay: TButton; BtnPause: TButton; btnStop: TButton; BtnDelete: TButton; BtnCopy: TButton; BtnMove: TButton; BtnExit: TButton; FileListBox1: TFileListBox; BtnHelp: TButton; ProgressBar1: TProgressBar; BtnPre: TButton; BtnNext: TButton; Timer1: TTimer; SelectFolderDialog: TRzSelectFolderDialog; BtnRename: TButton; EdtSearch: TEdit; Label1: TLabel; LblSound: TLabel; VolTrackBar: TTrackBar; procedure FormCreate(Sender: TObject); procedure BtnAboutClick(Sender: TObject); procedure BtnSettingsClick(Sender: TObject); procedure BtnExitClick(Sender: TObject); procedure BtnHelpClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure BtnSelectFolderClick(Sender: TObject); procedure BtnPlayClick(Sender: TObject); procedure BtnPauseClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ProgressBar1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure BtnDeleteClick(Sender: TObject); procedure PlayMusic(Sender: TObject); procedure FileListBox1DblClick(Sender: TObject); procedure BtnCopyClick(Sender: TObject); procedure BtnMoveClick(Sender: TObject); procedure BtnNextClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure BtnPreClick(Sender: TObject); procedure BtnRenameClick(Sender: TObject); procedure EdtSearchChange(Sender: TObject); procedure LblSoundClick(Sender: TObject); procedure VolTrackBarChange(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure InitiliazeBassLIb; Procedure FreeBassLib; Procedure CheckCurItem; Procedure UpdateCurItem; procedure CheckCopyPath(Sender: TObject); procedure CheckMovePath(Sender: TObject); Procedure PlayItem(Item: Integer); Function FileOperation(const source, dest : string; op, flags : Integer) : boolean; Procedure RemoveSelected; Procedure LoadSettings; Procedure SaveSettings; Procedure SetVolume(Vol: float); function GetVolume: float; Procedure GoMute; Procedure UnMutePlayer; end; var MusicCleaner: TMusicCleaner; Stream: HSTREAM; Tracking: Boolean; MoveDir: string; CopyDir: string; CurItem: Boolean; CurFile, RenIndex: Integer; IsPlaying: Boolean; CurVolume: float; PlayerMute: Boolean; implementation {$R *.dfm} uses AboutForm, MainSettings, RenameFrm; // Extract a file name after striping its extension and paths function ExtractFileNameWithoutExtension (const AFileName: String): String; var I: Integer; begin I := LastDelimiter('.' + PathDelim + DriveDelim,AFilename); if (I = 0) or (AFileName[I] <> '.') then I := MaxInt; Result := ExtractFileName(Copy(AFileName, 1, I - 1)) ; end; function SupportedFile(const FileName: string): Boolean; var S: string; begin //Check for supported files Result := false; S := ExtractFileExt(FileName); if S <> '' then begin if S = '.mp3' then Result := True else if S = '.wav' then Result := True else if S = '.ogg' then Result := True; End else Begin Result := false; End; end; procedure TMusicCleaner.BtnAboutClick(Sender: TObject); begin //Show the About Box FormAbout.ShowModal; end; procedure TMusicCleaner.BtnCopyClick(Sender: TObject); Var FileName, TargetFileName: String; OpSuccess : boolean; begin if FileListBox1.ItemIndex < 0 then Exit Else // Check if Copy to Folder Exists CheckCopyPath(Sender); // Copy the File FileName := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]; TargetFileName := CopyDir +PathDelim+ FileListBox1.Items.Strings[FileListBox1.ItemIndex]; OpSuccess := FileOperation(FileName, CopyDir, FO_COPY, FOF_ALLOWUNDO); if (OpSuccess) then begin LblStatus.Caption := 'File Copied to:'; // File copied to below path LblFile.Caption := TargetFileName; end else begin LblStatus.Caption := 'Failed to Copy:'; // Here the file title should be "Copied from" so that we can check // from where the copy command has failed LblFile.Caption := FileName; end; end; procedure TMusicCleaner.BtnDeleteClick(Sender: TObject); Var OpSuccess : boolean; FileOrFolder : string; begin CurItem := False; if FileListBox1.ItemIndex < 0 then begin Exit end Else Begin // Delete the selected file FileOrFolder := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]; CheckCurItem; if CurItem then Begin //CurItem Collides free the bass FreeBassLib; end; OpSuccess := FileOperation(FileOrFolder, '', FO_DELETE, FOF_ALLOWUNDO or FOF_NOCONFIRMATION); if (OpSuccess) then begin LblStatus.Caption := 'File Deleted:'; LblFile.Caption := FileOrFolder; RemoveSelected; UpdateCurItem; end else begin LblStatus.Caption := 'Failed to Delete:'; LblFile.Caption := FileOrFolder; UpdateCurItem; End; if CurItem then begin InitiliazeBassLIb; end else begin Exit; end; End; // Main Procedure BtnPlayClick(sender); end; procedure TMusicCleaner.BtnExitClick(Sender: TObject); begin //Close the Application close; end; procedure TMusicCleaner.BtnHelpClick(Sender: TObject); begin // Show the Help File ShellExecute(Handle, 'open', PChar(ExtractFilePath(Application.ExeName)+'\Help\Help.html'),nil,nil,SW_SHOWNORMAL) ; end; procedure TMusicCleaner.BtnMoveClick(Sender: TObject); Var OpSuccess : boolean; FileOrFolder, MoveTargetFile : string; begin CurItem := False; if FileListBox1.ItemIndex < 0 then begin Exit end Else Begin CheckMovePath(Sender); // Delete File FileOrFolder := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]; MoveTargetFile := MoveDir +PathDelim+ FileListBox1.Items.Strings[FileListBox1.ItemIndex]; CheckCurItem; if CurItem then Begin //CurItem Collides free the bass lib FreeBassLib; end; OpSuccess := FileOperation(FileOrFolder, MoveDir, FO_MOVE, FOF_ALLOWUNDO); if (OpSuccess) then begin LblStatus.Caption := 'File Moved to:'; LblFile.Caption := MoveTargetFile; RemoveSelected; UpdateCurItem; end else begin // RemoveSelected; LblStatus.Caption := 'Failed to Move:'; LblFile.Caption := FileOrFolder; UpdateCurItem; End; if CurItem then begin // If the cuurent item was playing // the bass lib was freed so re-initialize InitiliazeBassLIb; // Also play the next track ;-) BtnPlayClick(sender); end else begin Exit; end; End; // Main Procedure end; procedure TMusicCleaner.BtnNextClick(Sender: TObject); var CurrentOne, NextOne: Integer; begin // Play Next Item if FileListBox1.ItemIndex < 0 then Exit else Begin // Pick the current file CurrentOne := CurFile; // If current track has reached the end of list then go to first track if (CurrentOne = FileListBox1.Items.Count -1) then Begin CurrentOne := 0; end else begin //Go to the next track CurrentOne := CurrentOne + 1; end; // Get the Next Track ID Number and Play the track NextOne := CurrentOne; // Check if File Format is supported if SupportedFile(IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[NextOne]) then Begin PlayItem(NextOne); //Set the current file to the new Track ID Number CurFile := NextOne; //Change the Now Playing Lable Caption FileListBox1.ItemIndex := NextOne; LblPlaying.Caption := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[NextOne]; End else Begin MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK); exit; End; End; end; procedure TMusicCleaner.BtnPauseClick(Sender: TObject); begin // Pause the playing BASS Stream BASS_ChannelPause(stream); end; procedure TMusicCleaner.BtnPlayClick(Sender: TObject); begin if BASS_ChannelIsActive(stream) = BASS_ACTIVE_PAUSED then begin BASS_ChannelPlay(stream, False) end else Begin if FileListBox1.ItemIndex < 0 then Exit else begin if SupportedFile(IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]) then Begin PlayItem(FileListBox1.ItemIndex); CurFile := FileListBox1.ItemIndex; LblPlaying.Caption := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[CurFile]; end else Begin MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK); exit; End; End; End; end; procedure TMusicCleaner.BtnPreClick(Sender: TObject); var CurrentOne, NextOne: Integer; begin // Play Previous Item if FileListBox1.ItemIndex < 0 then Exit else Begin // Get current track CurrentOne := CurFile; // If current track is the first track then go to last track // (As previous of the first track would be last) if CurrentOne = 0 then Begin CurrentOne := FileListBox1.Items.Count -1; end else begin // Go to previous track CurrentOne := CurrentOne - 1; end; // Assign the previous track NextOne := CurrentOne; if SupportedFile(IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[NextOne]) then Begin // Play the previous track PlayItem(NextOne); // Set the current track file CurFile := NextOne; //Change the Now Playing Lable Caption FileListBox1.ItemIndex := NextOne; LblPlaying.Caption := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[NextOne]; End else Begin MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK); exit; End; End; end; procedure TMusicCleaner.BtnRenameClick(Sender: TObject); begin //Rename Selected File by show the Rename File Dialog //Set the CurItem to False Before testing for It CurItem := False; //If nothing is selected then exit if FileListBox1.ItemIndex < 0 then begin Exit end Else Begin //Get the file name in the Rename Dialog RenameForm.EdtRename.Text := ExtractFileNameWithoutExtension(FileListBox1.Items.Strings[FileListBox1.ItemIndex]); //Get the file Extension //RenameForm.Ext := ExtractFileExt(FileListBox1.Items.Strings[FileListBox1.ItemIndex]); //First Clear the EdtExt just to be sure it does not contain the Previous Extension RenameForm.EdtExt.Text := ''; RenameForm.EdtExt.Text := ExtractFileExt(FileListBox1.Items.Strings[FileListBox1.ItemIndex]); //Set the Rename Index RenIndex := FileListBox1.ItemIndex; //Show the Rename Dialog RenameForm.ShowModal; End; end; procedure TMusicCleaner.BtnSelectFolderClick(Sender: TObject); Var Path : String; begin if SelectFolderDialog.Execute then begin Path:=IncludeTrailingPathDelimiter(SelectFolderDialog.SelectedPathName); FileListBox1.Directory := Path; PathLabel.Caption := Path; end; end; procedure TMusicCleaner.BtnSettingsClick(Sender: TObject); begin //Show the Settings Dialog FrmSettings.ShowModal; end; procedure TMusicCleaner.btnStopClick(Sender: TObject); begin // Stop the current playing track BASS_ChannelStop(stream); // Reset the current track position to start BASS_ChannelSetPosition(stream, 0, 0); end; procedure TMusicCleaner.CheckCopyPath(Sender: TObject); begin // Check if the Copy to Directories exist if not create them if System.SysUtils.DirectoryExists (CopyDir) then begin Exit; end else ShowMessage('Copy To Folder does not exist' + #13#10 + 'It will be created'); System.SysUtils.ForceDirectories(CopyDir); end; procedure TMusicCleaner.CheckCurItem; var CurntIndex: Integer; begin // Check the current Playing Item Index CurntIndex := FileListBox1.ItemIndex; if CurntIndex > CurFile then begin exit end else if CurntIndex < CurFile then begin // As it is meant to check only do not alter index Exit; end // If playing the current selected index then set CurItem to True else if CurntIndex = CurFile then Begin CurItem := True; End; end; procedure TMusicCleaner.CheckMovePath(Sender: TObject); begin // Check if the Move to Directories exist if not create them if System.SysUtils.DirectoryExists (MoveDir) then begin // ShowMessage('Copy To Folder Exists'); Exit; end else ShowMessage('Move To Folder does not exist' + #13#10 + 'It will be created'); System.SysUtils.ForceDirectories(MoveDir); end; procedure TMusicCleaner.EdtSearchChange(Sender: TObject); begin FileListBox1.Mask := '*' + EdtSearch.Text + '*'; //If nothing is entered for search or search is cleared //then Re-Enter the Old Mask (Intended for Music Files) //to ensure that TFileListBox shows the right files in the list if EdtSearch.Text = '' then Begin FileListBox1.Mask := '*.mp3;*.wav;*.ogg;'; End; end; procedure TMusicCleaner.FileListBox1DblClick(Sender: TObject); begin // Play the double clicked track PlayMusic(sender); end; function TMusicCleaner.FileOperation(const source, dest: string; op, flags: Integer): boolean; {perform Copy, Move, Delete, Rename on files + folders via WinAPI} var Structure : TSHFileOpStruct; src, dst : string; OpResult : integer; begin {setup file op structure} FillChar(Structure, SizeOf (Structure), #0); src := source + #0#0; dst := dest + #0#0; Structure.Wnd := 0; Structure.wFunc := op; Structure.pFrom := PChar(src); Structure.pTo := PChar(dst); Structure.fFlags := flags or FOF_SILENT; case op of {set title for simple progress dialog} FO_COPY : Structure.lpszProgressTitle := 'Copying...'; FO_DELETE : Structure.lpszProgressTitle := 'Deleting...'; FO_MOVE : Structure.lpszProgressTitle := 'Moving...'; FO_RENAME : Structure.lpszProgressTitle := 'Renaming...'; end; {case op of..} OpResult := 1; try {perform operation} OpResult := SHFileOperation(Structure); finally {report success / failure} result := (OpResult = 0); end; {try..finally..} end; {function FileOperation} procedure TMusicCleaner.FormClose(Sender: TObject; var Action: TCloseAction); begin // Save Form and Directory Settings SaveSettings; end; procedure TMusicCleaner.FormCreate(Sender: TObject); begin // Load the Settings i.e. Default Move and Copy Directories LoadSettings; // Initialize Bass Library // If initialization fails terminate the application if Bass_init( -1, 44100, 0, Handle, nil) = false then begin showmessage('Audio Initalization Failed'+#13#10+'Music Cleaner will now close'); Application.Terminate; end; end; procedure TMusicCleaner.FormDestroy(Sender: TObject); begin // Free Bass Library FreeBassLib; end; procedure TMusicCleaner.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin // Ctrl+P play/pause the track if (Key = 80) and (Shift = [ssCtrl]) then Begin //If the track is paused play it if BASS_ChannelIsActive(stream) = BASS_ACTIVE_PAUSED then begin BASS_ChannelPlay(stream, False) end else Begin //if track is playing pause it BASS_ChannelPause(stream); End; End; // Ctrl+O Open Select Folder Dialog if (Key = 79) and (Shift = [ssCtrl]) then Begin BtnSelectFolderClick(sender); End; // Ctrl+M Mute the Player if (Key = 77) and (Shift = [ssCtrl]) then Begin LblSoundClick(sender); End; // Ctrl+C Copy if (Key = 67) and (Shift = [ssCtrl]) then Begin BtnCopyClick(sender); End; // Ctrl+X Cut / Move if (Key = 88) and (Shift = [ssCtrl]) then Begin BtnMoveClick(sender); End; // Ctrl+Z Delete if (Key = 90) and (Shift = [ssCtrl]) then Begin BtnDeleteClick(sender); End; // Ctrl+B Previous if (Key = 66) and (Shift = [ssCtrl]) then Begin BtnPreClick(sender); End; // Ctrl+N Next if (Key = 78) and (Shift = [ssCtrl]) then Begin BtnNextClick(sender); End; // Ctrl+A Play if (Key = 65) and (Shift = [ssCtrl]) then Begin BtnPlayClick(sender); End; // Ctrl+S Stop if (Key = 83) and (Shift = [ssCtrl]) then Begin BtnStopClick(sender); End; //If F1 key is pressed show the help if (Key = VK_F1) then Begin BtnHelpClick(sender); End; //If F2 Rename if (Key = VK_F2) then Begin BtnRenameClick(sender); End; //If F3 key is pressed jump to search box if (Key = VK_F3) then Begin EdtSearch.SetFocus; End; //If F4 key is pressed show the about box if (Key = VK_F4) then Begin BtnAboutClick(sender); End; //If F5 key is pressed show the settings dialog if (Key = VK_F5) then Begin BtnSettingsClick(sender); End; //VK_PLAY if (Key = VK_PLAY) then Begin BtnPlayClick(sender); End; //VK_MEDIA_PLAY_PAUSE if (Key = VK_MEDIA_PLAY_PAUSE) then begin //If the track is paused play it if BASS_ChannelIsActive(stream) = BASS_ACTIVE_PAUSED then begin BASS_ChannelPlay(stream, False) end else Begin //if track is playing pause it BASS_ChannelPause(stream); End; end; //VK_MEDIA_STOP if (Key = VK_MEDIA_STOP) then Begin BtnStopClick(sender); End; //VK_PAUSE if (Key = VK_PAUSE) then Begin BtnPauseClick(sender); End; //VK_PRIOR if (Key = VK_PRIOR) then Begin BtnPreClick(sender); End; //VK_MEDIA_PREV_TRACK if (Key = VK_MEDIA_PREV_TRACK) then Begin BtnPreClick(sender); End; //VK_MEDIA_NEXT_TRACK if (Key = VK_MEDIA_NEXT_TRACK) then Begin BtnNextClick(sender); End; //VK_NEXT if (Key = VK_NEXT) then Begin BtnNextClick(sender); End; //VK_RETURN if (Key = VK_RETURN) then Begin BtnPlayClick(sender); End; //If escape Key is pressed Stop the Player if (Key = VK_ESCAPE) then Begin BtnStopClick(sender); End; //Delete the File if Delete Key is pressed if (Key = VK_DELETE) then Begin BtnDeleteClick(sender); End; //Show the Help file if HELP Key is pressed //This key exist on MultiMedia Keyboards Only if (Key = VK_HELP) then Begin BtnHelpClick(sender); End; //Slightly up the Volume if Volume UP Key is pressed //This key exist on MultiMedia Keyboards Only if (Key = VK_VOLUME_UP) then Begin //Slightly up the volume at each press if VolTrackBar.Position >= 100 then exit else begin //Up the Volume 5 ticks per key press VolTrackBar.Position := VolTrackBar.Position + 5; end; End; //Slightly Down the Volume if Volume Down Key is pressed //This key exist on MultiMedia Keyboards Only if (Key = VK_VOLUME_DOWN) then Begin //Slightly down the volume at each press if VolTrackBar.Position <= 0 then exit else begin //Down the Volume 5 ticks per key press VolTrackBar.Position := VolTrackBar.Position - 5; End; End; //Slightly UP the Volume if F6 Key is pressed if (Key = VK_F6) then Begin //Slightly up the volume at each press if VolTrackBar.Position >= 100 then exit else begin //Up the Volume 5 ticks per key press VolTrackBar.Position := VolTrackBar.Position + 5; end; End; //Slightly Down the Volume if F7 Key is pressed if (Key = VK_F7) then Begin //Slightly down the volume at each press if VolTrackBar.Position <= 0 then exit else begin //Down the Volume 5 ticks per key press VolTrackBar.Position := VolTrackBar.Position - 5; End; End; end; procedure TMusicCleaner.FreeBassLib; begin // Free the Bass Library BASS_Free(); end; function TMusicCleaner.GetVolume: float; begin //Get the current Volume of Playing Track result := CurVolume*100; end; procedure TMusicCleaner.GoMute; begin //Get the current volume CurVolume := GetVolume; //Mute.... Well you know what it mean dont you :-p BASS_ChannelSetAttribute(stream, BASS_ATTRIB_VOL, 0); PlayerMute := True; LblSound.Caption := 'X'; end; procedure TMusicCleaner.InitiliazeBassLIb; begin if Bass_init( -1, 44100, 0, Handle, nil) = false then exit; end; procedure TMusicCleaner.LblSoundClick(Sender: TObject); begin //If player is not mute then Mute It if PlayerMute then UnMutePlayer //If Player is already muted then UnMute Else GoMute; end; procedure TMusicCleaner.LoadSettings; var ini: TIniFile; begin // Load INI File and load the settings INI := TIniFile.Create(ExtractFilePath(Application.ExeName)+ 'settings.ini'); Try MoveDir := Ini.ReadString('MusicCleaner', 'MoveDir', MoveDir); CopyDir := Ini.ReadString('MusicCleaner', 'CopyDir', CopyDir); Top := INI.ReadInteger('Placement','Top', Top) ; Left := INI.ReadInteger('Placement','Left', Left); VolTrackBar.Position := INI.ReadInteger('MusicPlayer','Volume', VolTrackBar.Position); SetVolume(VolTrackBar.Position); PlayerMute := INI.ReadBool('MusicPlayer','PlayerMute',PlayerMute); Finally Ini.Free; End; // PlayerMute is true then Mute the Player if PlayerMute then Begin GoMute; End; // Initially create the MoveTo and CopyTo Directories if they do not exist if MoveDir <> '' then Begin if not System.SysUtils.DirectoryExists (MoveDir) then Begin //Create the Move To Directory System.SysUtils.ForceDirectories(MoveDir); End; End; if CopyDir <> '' then Begin if not System.SysUtils.DirectoryExists (CopyDir) then Begin //Create the Copy To Directory System.SysUtils.ForceDirectories(CopyDir); End; End; end; procedure TMusicCleaner.PlayItem(Item: Integer); var MyFile:String; begin MyFile := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[Item]; if item < 0 then exit; if SupportedFile(MyFile) then Begin if stream <> 0 then BASS_StreamFree(stream); stream := BASS_StreamCreateFile(False, PChar(MyFile), 0, 0, 0 {$IFDEF UNICODE} or BASS_UNICODE {$ENDIF}); if stream = 0 then MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK) else begin ProgressBar1.Min := 0; ProgressBar1.Max := BASS_ChannelGetLength(stream, 0) -1; ProgressBar1.Position := 0; BASS_ChannelPlay(Stream,False); //Set the Track Volume to the Current Volume SetVolume(GetVolume); // If Player is in Mute State then Keep it as is if PlayerMute then Begin GoMute; End; end; End else Begin MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK); exit; End; end; procedure TMusicCleaner.PlayMusic(Sender: TObject); begin if SupportedFile(IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]) then Begin // Play the selected Item in BASS PlayItem(FileListBox1.ItemIndex); CurFile := FileListBox1.ItemIndex; // Change the Now Playing Lable Caption LblPlaying.Caption := IncludeTrailingPathDelimiter(FileListBox1.Directory)+FileListBox1.Items.Strings[FileListBox1.ItemIndex]; End else Begin MessageDlg('This file format is not supported', mtError, [mbOK], 0, mbOK); exit; End; end; procedure TMusicCleaner.ProgressBar1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Percent: Double; begin Percent := X / ProgressBar1.Width; BASS_ChannelSetPosition(stream, Floor(Percent * (BASS_ChannelGetLength(stream, 0) -1)), 0) end; procedure TMusicCleaner.RemoveSelected; var PrevIndex: Integer; begin // Remove The selected Entry //Get the current Track ID PrevIndex := FileListBox1.ItemIndex; // Remove it from the FileListBox FileListBox1.Items.Delete(PrevIndex); //if removed Track ID is grater than FileListBox items if PrevIndex > (FileListBox1.Items.Count -1) then begin //Then move Track ID to one track previous PrevIndex := FileListBox1.Items.Count -1; //Set the current selected track to the previous track FileListBox1.ItemIndex := PrevIndex; end else begin //If Its not larger than the deleted track then leave as is FileListBox1.ItemIndex := PrevIndex; end; // If the remaining track is single then make it selected if (PrevIndex = 0) and (FileListBox1.Items.Count <> -1) then FileListBox1.ItemIndex := 0; end; procedure TMusicCleaner.SaveSettings; var ini: TIniFile; begin // Save Settings to INI File INI := TIniFile.Create(ExtractFilePath(Application.ExeName)+ 'settings.ini'); Try with INI do begin WriteString('MusicCleaner','MoveDir', MoveDir); WriteString('MusicCleaner','CopyDir', CopyDir); WriteInteger('Placement','Top', Top); WriteInteger('Placement','Left', Left); WriteBool('MusicPlayer','PlayerMute',PlayerMute); WriteInteger('MusicPlayer','Volume', VolTrackBar.Position); end; finally Ini.Free; End; end; procedure TMusicCleaner.SetVolume(Vol: float); begin // Set the Volume Current Playing Track Vol := Vol / 100; if Vol < 0 then Vol := 0; if Vol > 1 then Vol := 1; CurVolume := Vol; BASS_ChannelSetAttribute(stream, BASS_ATTRIB_VOL, CurVolume); end; procedure TMusicCleaner.Timer1Timer(Sender: TObject); begin // Show the progress of the playing item if Tracking = False then ProgressBar1.Position := BASS_ChannelGetPosition(stream,0); end; procedure TMusicCleaner.UnMutePlayer; begin CurVolume := VolTrackBar.Position; SetVolume(CurVolume); PlayerMute := False; LblSound.Caption := 'Xð'; end; procedure TMusicCleaner.UpdateCurItem; var CurntItem: Integer; begin // Check the current Playing Item Index if CurFile <> -1 then begin CurntItem := FileListBox1.ItemIndex; if CurntItem > CurFile then begin //Current Playing File is prior to the index // CurFile Variable will not be disturbed exit end else if CurntItem = CurFile then begin // If CurntItem equals the CurFile then simply exit the function CurFile := CurntItem; Exit; end else if CurntItem < CurFile then begin // CurFile is Greater than current index so 1 will be minused CurFile := CurFile - 1; end; end; end; procedure TMusicCleaner.VolTrackBarChange(Sender: TObject); begin //If player was mute when changing the Volume //UnMute it and then set the volume if PlayerMute then Begin UnMutePlayer; End; SetVolume(VolTrackBar.Position); end; end.
unit ArrayHelper; /////////////////////////////////////////////////////////////////////////////// // // ArrayHelper version 1.3 // extends class TArray and add TArrayRecord<T> to make dynamic arrays // as simple, as TList // // Copyright(c) 2017 by Willi Commer (wcs) // Licence GNU // // Dynamic arrays are smart because its memore usage is handled by the memory // manager. But the funtion libraries are lean and differs from object based. // Based on TArray class, that gives Sort and Binary search, this unit will // extend TArray with functions available for TList or TStrings. // The next level is TArrayRecord<T> record type. It wraps a record around // the dynamic array. This give us the ability to use dynamic arrays like // objects with out the pain to organize the final Free call. // // var // A: TArrayRecord<string>; // S: string; // begin // A.SetValues(['a','b','c']); // A.Add('d'); // assert( A.Count = 4 ); // same as length(A.Items); // assert( A[1] = 'b' ); // assert( A.IndexOf('a') = 0 ); // for S in A do // .. // // For more examples see procedure Test_All_Helper_Functions // For updates check https://github.com/WilliCommer/ArrayHelper // // // History: // version 1.3 // Enumeration added // new functions 'Unique' and 'CopyArray' // // version 1.2 // TArrayRecord<T> // /////////////////////////////////////////////////////////////////////////////// { $DEFINE TEST_FUNCTION} // change to active test function interface uses System.Classes, System.SysUtils, System.RTLConsts, System.Generics.Defaults, System.Generics.Collections; type // callback function for function ForEach TArrayForEachCallback<T> = reference to procedure(var Value: T; Index: integer); // callback function for function Map TArrayMapCallback<T> = reference to function(var Value: T; Index: integer): boolean; // callback function for function MapTo TArrayConvert<T,TTo> = reference to function(const Value: T): TTo; // callback function for function Find TArrayFindCallback<T> = reference to function(const Value: T): boolean; // extends class TArray TArrayHelper = class helper for TArray // add item to array class function Add<T>(var Values: TArray<T>; Item: T): integer; static; // delete item at index class procedure Delete<T>(var Values: TArray<T>; Index: integer); static; // insert item at index class procedure Insert<T>(var Values: TArray<T>; Index: integer; Value: T); static; // append array class procedure AddRange<T>(var Values: TArray<T>; const ValuesToInsert: array of T); static; // insert array at index class procedure InsertRange<T>(var Values: TArray<T>; Index: Integer; const ValuesToInsert: array of T); static; // get index of equal item class function IndexOf<T>(var Values: TArray<T>; Item: T): integer; overload; static; // get index of equal item (using IComparer) class function IndexOf<T>(var Values: TArray<T>; Item: T; const Comparer: IComparer<T>): integer; overload; static; // get index of maximal item class function IndexOfMax<T>(var Values: TArray<T>): integer; overload; static; // get index of maximal item (using IComparer) class function IndexOfMax<T>(var Values: TArray<T>; const Comparer: IComparer<T>): integer; overload; static; // get index of minimal item class function IndexOfMin<T>(var Values: TArray<T>): integer; overload; static; // get index of minimal item (using IComparer) class function IndexOfMin<T>(var Values: TArray<T>; const Comparer: IComparer<T>): integer; overload; static; // is a equal item is member of values class function Contains<T>(var Values: TArray<T>; Item: T): boolean; overload; static; // is a equal item is member of values (using IComparer) class function Contains<T>(var Values: TArray<T>; Item: T; const Comparer: IComparer<T>): boolean; overload; static; // compare two arrays class function Compare<T>(const Values, ValuesToCompare: array of T): boolean; overload; static; // compare two arrays (using IComparer) class function Compare<T>(const Values, ValuesToCompare: array of T; const Comparer: IComparer<T>): boolean; overload; static; // ForEach class procedure ForEach<T>(var Values: TArray<T>; const Callback: TArrayForEachCallback<T>); static; // find with callback class function Find<T>(const Values: TArray<T>; const Callback: TArrayFindCallback<T>; const StartIndex: integer = 0): integer; overload; static; // return an array filtered and converted by callback function class function Map<T>(const Values: TArray<T>; const Callback: TArrayMapCallback<T>): TArray<T>; static; // return the array as TList class procedure List<T>(const Values: TArray<T>; var ValList: TList<T>); static; {$IFDEF TEST_FUNCTION} // test, debug and example function class procedure Test_All_Helper_Functions; {$ENDIF TEST_FUNCTION} end; type TArrayRecord<T> = record strict private type TEnumerator = class private FValue: ^TArrayRecord<T>; FIndex: integer; function GetCurrent: T; public constructor Create(var AValue: TArrayRecord<T>); function MoveNext: Boolean; property Current: T read GetCurrent; end; public function GetEnumerator(): TEnumerator; private function GetCount: integer; procedure SetCount(const Value: integer); function GetItemAt(Index: integer): T; procedure SetItemAt(Index: integer; Value: T); public Items: TArray<T>; property Count: integer read GetCount write SetCount; property ItemAt[Index: Integer]: T read GetItemAt write SetItemAt; default; constructor Create(ACapacity: integer); overload; constructor Create(const AValues: array of T); overload; procedure Clear; procedure SetItems(const Values: array of T); function Add(const Value: T): integer; procedure Delete(Index: integer); procedure Insert(Index: integer; Value: T); function Remove(const AItem: T): boolean; function AddIfNotContains(const AItem: T): boolean; procedure AddRange(const ValuesToInsert: array of T); overload; procedure AddRange(const ValuesToInsert: TArrayRecord<T>); overload; procedure InsertRange(Index: Integer; const ValuesToInsert: array of T); overload; procedure InsertRange(Index: Integer; const ValuesToInsert: TArrayRecord<T>); overload; function IndexOf(Item: T): integer; overload; function IndexOf(Item: T; const Comparer: IComparer<T>): integer; overload; function IndexOfMax: integer; overload; function IndexOfMax(const Comparer: IComparer<T>): integer; overload; function IndexOfMin: integer; overload; function IndexOfMin(const Comparer: IComparer<T>): integer; overload; function Contains(Item: T): boolean; overload; function Contains(Item: T; const Comparer: IComparer<T>): boolean; overload; function Compare(const ValuesToCompare: array of T): boolean; overload; function Compare(const ValuesToCompare: array of T; const Comparer: IComparer<T>): boolean; overload; function Compare(const ValuesToCompare: TArrayRecord<T>): boolean; overload; function Compare(const ValuesToCompare: TArrayRecord<T>; const Comparer: IComparer<T>): boolean; overload; procedure ForEach(const Callback: TArrayForEachCallback<T>); function Find(const Callback: TArrayFindCallback<T>; const StartIndex: integer = 0): integer; overload; function Map(const Callback: TArrayMapCallback<T>): TArrayRecord<T>; function Convert<TTo>(const Callback: TArrayConvert<T,TTo>): TArrayRecord<TTo>; procedure Sort; overload; procedure Sort(const AComparer: IComparer<T>); overload; procedure Sort(const AComparer: IComparer<T>; AIndex, ACount: Integer); overload; function BinarySearch(const AItem: T; out AFoundIndex: Integer; const AComparer: IComparer<T>; AIndex, ACount: Integer): Boolean; overload; function BinarySearch(const AItem: T; out AFoundIndex: Integer; const AComparer: IComparer<T>): Boolean; overload; function BinarySearch(const AItem: T; out AFoundIndex: Integer): Boolean; overload; procedure Unique; // remove duplicates function CopyArray(FromIndex: integer; Count: integer = -1): TArrayRecord<T>; // return array slice procedure List(var ValList: TList<T>); // operator overloads class operator Equal(const L, R: TArrayRecord<T>): boolean; class operator NotEqual(const L, R: TArrayRecord<T>): boolean; end; implementation { TArrayHelper } class function TArrayHelper.Add<T>(var Values: TArray<T>; Item: T): integer; begin Result := Length(Values); SetLength(Values,Result+1); Values[Result] := Item; end; class procedure TArrayHelper.Delete<T>(var Values: TArray<T>; Index: integer); var I: Integer; begin if (Index < Low(Values)) or (Index > High(Values)) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); for I := Index+1 to High(Values) do Values[I-1] := Values[I]; SetLength(Values, length(Values)-1); end; class procedure TArrayHelper.Insert<T>(var Values: TArray<T>; Index: integer; Value: T); var I,H: Integer; begin if (Index < Low(Values)) or (Index > length(Values)) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); H := High(Values); SetLength(Values, length(Values)+1); for I := H downto Index do Values[I+1] := Values[I]; Values[Index] := Value; end; class procedure TArrayHelper.InsertRange<T>(var Values: TArray<T>; Index: Integer; const ValuesToInsert: array of T); var I,L,H: Integer; begin L := length(ValuesToInsert); if L = 0 then EXIT; if (Index < Low(Values)) or (Index > length(Values)) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); H := High(Values); SetLength(Values, length(Values) + L); for I := H downto Index do Values[I+L] := Values[I]; for I := Low(ValuesToInsert) to High(ValuesToInsert) do Values[Index+I] := ValuesToInsert[I]; end; class procedure TArrayHelper.List<T>(const Values: TArray<T>; var ValList: TList<T>); var I: Integer; begin if not Assigned(ValList) then raise Exception.Create('ValList is nil'); ValList.Clear; for I := Low(Values) to High(Values) do ValList.Add(Values[I]); end; class procedure TArrayHelper.AddRange<T>(var Values: TArray<T>; const ValuesToInsert: array of T); var I,Index: Integer; begin Index := length(Values); SetLength(Values, length(Values) + length(ValuesToInsert)); for I := Low(ValuesToInsert) to High(ValuesToInsert) do Values[Index+I] := ValuesToInsert[I]; end; class function TArrayHelper.IndexOf<T>(var Values: TArray<T>; Item: T; const Comparer: IComparer<T>): integer; begin for Result := Low(Values) to High(Values) do if Comparer.Compare(Values[Result], Item) = 0 then EXIT; Result := -1; end; class function TArrayHelper.IndexOf<T>(var Values: TArray<T>; Item: T): integer; begin Result := IndexOf<T>(Values, Item, TComparer<T>.Default); end; class function TArrayHelper.IndexOfMax<T>(var Values: TArray<T>): integer; begin Result := IndexOfMax<T>(Values, TComparer<T>.Default); end; class function TArrayHelper.IndexOfMax<T>(var Values: TArray<T>; const Comparer: IComparer<T>): integer; var I: Integer; begin if length(Values) = 0 then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); Result := 0; for I := 1 to High(Values) do if Comparer.Compare(Values[I], Values[Result]) > 0 then Result := I; end; class function TArrayHelper.IndexOfMin<T>(var Values: TArray<T>): integer; begin Result := IndexOfMin<T>(Values, TComparer<T>.Default); end; class function TArrayHelper.IndexOfMin<T>(var Values: TArray<T>; const Comparer: IComparer<T>): integer; var I: Integer; begin if length(Values) = 0 then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); Result := 0; for I := 1 to High(Values) do if Comparer.Compare(Values[I], Values[Result]) < 0 then Result := I; end; class function TArrayHelper.Contains<T>(var Values: TArray<T>; Item: T; const Comparer: IComparer<T>): boolean; begin Result := IndexOf<T>(Values, Item, Comparer) <> -1; end; class function TArrayHelper.Contains<T>(var Values: TArray<T>; Item: T): boolean; begin Result := Contains<T>(Values, Item, TComparer<T>.Default); end; class function TArrayHelper.Compare<T>(const Values, ValuesToCompare: array of T; const Comparer: IComparer<T>): boolean; var I: Integer; begin if length(Values) <> length(ValuesToCompare) then EXIT( FALSE ); for I := Low(Values) to High(Values) do if Comparer.Compare(Values[I], ValuesToCompare[I]) <> 0 then EXIT( FALSE ); Result := TRUE; end; class function TArrayHelper.Compare<T>(const Values, ValuesToCompare: array of T): boolean; begin Result := Compare<T>(Values, ValuesToCompare, TComparer<T>.Default); end; class procedure TArrayHelper.ForEach<T>(var Values: TArray<T>; const Callback: TArrayForEachCallback<T>); var I: Integer; begin for I := Low(Values) to High(Values) do Callback(Values[I], I); end; class function TArrayHelper.Find<T>(const Values: TArray<T>; const Callback: TArrayFindCallback<T>; const StartIndex: integer): integer; begin if (length(Values) = 0) or (StartIndex < 0) or (StartIndex > High(Values)) then EXIT( -1 ); for Result := StartIndex to High(Values) do if Callback(Values[Result]) then EXIT; Result := -1; end; class function TArrayHelper.Map<T>(const Values: TArray<T>; const Callback: TArrayMapCallback<T>): TArray<T>; var Item: T; I: Integer; begin Result := NIL; for I := Low(Values) to High(Values) do begin Item := Values[I]; if Callback(Item, I) then Add<T>(Result, Item); end; end; { TArrayRecord<T>.TEnumerator } constructor TArrayRecord<T>.TEnumerator.Create(var AValue: TArrayRecord<T>); begin FValue := @AValue; FIndex := -1; end; function TArrayRecord<T>.TEnumerator.GetCurrent: T; begin Result := FValue^.Items[FIndex]; end; function TArrayRecord<T>.TEnumerator.MoveNext: Boolean; begin Result := FIndex < High(FValue^.Items); Inc(FIndex); end; { TArrayRecord<T> } constructor TArrayRecord<T>.Create(ACapacity: integer); begin SetLength(Items, ACapacity); end; constructor TArrayRecord<T>.Create(const AValues: array of T); begin SetLength(Items, 0); AddRange(AValues); end; procedure TArrayRecord<T>.Clear; begin SetLength(Items, 0); end; class operator TArrayRecord<T>.Equal(const L, R: TArrayRecord<T>): boolean; begin Result := L.Compare(R); end; class operator TArrayRecord<T>.NotEqual(const L, R: TArrayRecord<T>): boolean; begin Result := not L.Compare(R); end; function TArrayRecord<T>.GetCount: integer; begin Result := length(Items); end; function TArrayRecord<T>.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; procedure TArrayRecord<T>.SetCount(const Value: integer); begin SetLength(Items, Value); end; procedure TArrayRecord<T>.SetItemAt(Index: integer; Value: T); begin Items[Index] := Value; end; procedure TArrayRecord<T>.SetItems(const Values: array of T); begin SetLength(Items, 0); AddRange(Values); end; function TArrayRecord<T>.GetItemAt(Index: integer): T; begin Result := Items[Index]; end; procedure TArrayRecord<T>.AddRange(const ValuesToInsert: array of T); begin TArray.AddRange<T>(Items, ValuesToInsert); end; procedure TArrayRecord<T>.AddRange(const ValuesToInsert: TArrayRecord<T>); begin TArray.AddRange<T>(Items, ValuesToInsert.Items); end; function TArrayRecord<T>.BinarySearch(const AItem: T; out AFoundIndex: Integer; const AComparer: IComparer<T>; AIndex, ACount: Integer): Boolean; begin Result := TArray.BinarySearch<T>(Items, AItem, AFoundIndex, AComparer, AIndex, ACount); end; function TArrayRecord<T>.BinarySearch(const AItem: T; out AFoundIndex: Integer; const AComparer: IComparer<T>): Boolean; begin Result := TArray.BinarySearch<T>(Items, AItem, AFoundIndex, AComparer); end; function TArrayRecord<T>.BinarySearch(const AItem: T; out AFoundIndex: Integer): Boolean; begin Result := TArray.BinarySearch<T>(Items, AItem, AFoundIndex); end; procedure TArrayRecord<T>.Delete(Index: integer); begin TArray.Delete<T>(Items, Index); end; function TArrayRecord<T>.Remove(const AItem: T): boolean; var I: integer; begin I := IndexOf(AItem); if I < 0 then Result := FALSE else begin Delete(I); Result := TRUE; end; end; function TArrayRecord<T>.AddIfNotContains(const AItem: T): boolean; begin Result := not Contains(AItem); if not Result then Add(AItem); end; function TArrayRecord<T>.Find(const Callback: TArrayFindCallback<T>; const StartIndex: integer): integer; begin Result := TArray.Find<T>(Items, Callback, StartIndex); end; procedure TArrayRecord<T>.ForEach(const Callback: TArrayForEachCallback<T>); begin TArray.ForEach<T>(Items, Callback); end; function TArrayRecord<T>.Compare(const ValuesToCompare: TArrayRecord<T>): boolean; begin Result := TArray.Compare<T>(Items, ValuesToCompare.Items); end; function TArrayRecord<T>.Compare(const ValuesToCompare: TArrayRecord<T>; const Comparer: IComparer<T>): boolean; begin Result := TArray.Compare<T>(Items, ValuesToCompare.Items, Comparer); end; function TArrayRecord<T>.Compare(const ValuesToCompare: array of T): boolean; begin Result := TArray.Compare<T>(Items, ValuesToCompare); end; function TArrayRecord<T>.Compare(const ValuesToCompare: array of T; const Comparer: IComparer<T>): boolean; begin Result := TArray.Compare<T>(Items, ValuesToCompare, Comparer); end; function TArrayRecord<T>.Contains(Item: T; const Comparer: IComparer<T>): boolean; begin Result := TArray.Contains<T>(Items, Item, Comparer); end; function TArrayRecord<T>.Contains(Item: T): boolean; begin Result := TArray.Contains<T>(Items, Item); end; function TArrayRecord<T>.IndexOf(Item: T; const Comparer: IComparer<T>): integer; begin Result := TArray.IndexOf<T>(Items, Item, Comparer); end; function TArrayRecord<T>.IndexOfMax: integer; begin Result := TArray.IndexOfMax<T>(Items); end; function TArrayRecord<T>.IndexOfMax(const Comparer: IComparer<T>): integer; begin Result := TArray.IndexOfMax<T>(Items, Comparer); end; function TArrayRecord<T>.IndexOfMin: integer; begin Result := TArray.IndexOfMin<T>(Items); end; function TArrayRecord<T>.IndexOfMin(const Comparer: IComparer<T>): integer; begin Result := TArray.IndexOfMin<T>(Items, Comparer); end; function TArrayRecord<T>.IndexOf(Item: T): integer; begin Result := TArray.IndexOf<T>(Items, Item); end; procedure TArrayRecord<T>.Insert(Index: integer; Value: T); begin TArray.Insert<T>(Items, Index, Value); end; procedure TArrayRecord<T>.InsertRange(Index: Integer; const ValuesToInsert: TArrayRecord<T>); begin TArray.InsertRange<T>(Items, Index, ValuesToInsert.Items); end; procedure TArrayRecord<T>.List(var ValList: TList<T>); begin TArray.List<T>(Items, ValList); end; procedure TArrayRecord<T>.InsertRange(Index: Integer; const ValuesToInsert: array of T); begin TArray.InsertRange<T>(Items, Index, ValuesToInsert); end; function TArrayRecord<T>.Map(const Callback: TArrayMapCallback<T>): TArrayRecord<T>; begin Result.Items := TArray.Map<T>(Items, Callback); end; function TArrayRecord<T>.Convert<TTo>(const Callback: TArrayConvert<T,TTo>): TArrayRecord<TTo>; var I: Integer; begin Result.Clear; for I := Low(Items) to High(Items) do Result.Add(Callback(Items[I])); end; function TArrayRecord<T>.CopyArray(FromIndex: integer; Count: integer): TArrayRecord<T>; var I: Integer; begin Result.Clear; if Count < 0 then Count := length(Items); if length(Items) < (FromIndex + Count) then Count := length(Items) - FromIndex; if Count > 0 then begin SetLength(Result.Items, Count); for I := 0 to Count-1 do Result.Items[I] := Items[I + FromIndex]; end; end; procedure TArrayRecord<T>.Sort; begin TArray.Sort<T>(Items); end; procedure TArrayRecord<T>.Sort(const AComparer: IComparer<T>); begin TArray.Sort<T>(Items, AComparer); end; procedure TArrayRecord<T>.Sort(const AComparer: IComparer<T>; AIndex, ACount: Integer); begin TArray.Sort<T>(Items, AComparer, AIndex, ACount); end; function TArrayRecord<T>.Add(const Value: T): integer; begin Result := TArray.Add<T>(Items, Value); end; procedure TArrayRecord<T>.Unique; var Hash: TDictionary<T,integer>; I: Integer; begin Hash := TDictionary<T,integer>.Create(length(Items)); try for I := Low(Items) to High(Items) do Hash.AddOrSetValue(Items[I], 0); Items := Hash.Keys.ToArray; finally Hash.Free; end; end; {$IFDEF TEST_FUNCTION} type TTestRecord = record Name: string; Age: integer; constructor Create(AName: string; AAge: integer); class function NameComparer: IComparer<TTestRecord>; static; class function AgeComparer: IComparer<TTestRecord>; static; class function ConvertToNames(const Value: TTestRecord): string; static; class function ConvertToAges(const Value: TTestRecord): integer; static; end; constructor TTestRecord.Create(AName: string; AAge: integer); begin Name := AName; Age := AAge; end; class function TTestRecord.ConvertToNames(const Value: TTestRecord): string; begin Result := Value.Name; end; class function TTestRecord.ConvertToAges(const Value: TTestRecord): integer; begin Result := Value.Age; end; class function TTestRecord.AgeComparer: IComparer<TTestRecord>; begin Result := TComparer<TTestRecord>.Construct( function(const Left, Right: TTestRecord): Integer begin Result := TComparer<integer>.Default.Compare(Left.Age, Right.Age); end ); end; class function TTestRecord.NameComparer: IComparer<TTestRecord>; begin Result := TComparer<TTestRecord>.Construct( function(const Left, Right: TTestRecord): Integer begin Result := TComparer<string>.Default.Compare(Left.Name, Right.Name); end ); end; procedure Test_TestRecord; var List: TArrayRecord<TTestRecord>; StrList: TArrayRecord<string>; I: integer; begin // create list List.Clear; List.Add( TTestRecord.Create('Jack', 26) ); List.Add( TTestRecord.Create('Anton', 28) ); List.Add( TTestRecord.Create('Barbie', 50) ); List.Add( TTestRecord.Create('Mickey Mouse', 90) ); // sort by name List.Sort( TTestRecord.NameComparer ); // convert to string array StrList := List.Convert<string>(TTestRecord.ConvertToNames); assert( StrList.Compare(['Anton','Barbie','Jack','Mickey Mouse']) ); // convert to integer array assert( List.Convert<integer>(TTestRecord.ConvertToAges).Compare([28,50,26,90]) ); // sort by age List.Sort( TTestRecord.AgeComparer ); assert( List[0].Name = 'Jack' ); // IndexOf Min / Max assert( List.IndexOfMax(TTestRecord.AgeComparer) = 3 ); assert( List.IndexOfMin(TTestRecord.AgeComparer) = 0 ); I := List.IndexOfMax(TTestRecord.NameComparer); assert( List[I].Name = 'Mickey Mouse' ); I := List.IndexOfMin(TTestRecord.NameComparer); assert( List[I].Name = 'Anton' ); // Unique List.Add(List[0]); List.Insert(2, List[1]); List.Insert(4, List[1]); List.Unique; List.Sort(TTestRecord.NameComparer); StrList := List.Convert<string>(TTestRecord.ConvertToNames); assert( StrList.Compare(['Anton','Barbie','Jack','Mickey Mouse']) ); end; function CompareJokerFunction(const Value: string): boolean; begin Result := LowerCase(Value) = 'joker'; end; procedure TestArrayContainer; const CWeek: array[1..8] of string = ('Mon','Tues','Wednes','Bug','Thurs','Fri','Satur','Sun'); var AStr: TArrayRecord<string>; AI,AI2: TArrayRecord<integer>; I: Integer; S: string; begin AI := TArrayRecord<integer>.Create(0); assert(AI.Count = 0); AStr := TArrayRecord<string>.Create(10); assert((AStr.Count = 10) and (AStr[1] = '')); // Create AI.Create([1,2,3]); assert( AI.Compare([1,2,3]) ); // Add AI.Clear; assert( AI.Add(1) = 0 ); assert( AI.Add(2) = 1 ); assert( AI.Add(3) = 2 ); // IndexOf assert( AI.IndexOf(1) = 0 ); assert( AI.IndexOf(2) = 1 ); assert( AI.IndexOf(5) = -1 ); // Contains assert( AI.Contains(2) = TRUE ); assert( AI.Contains(5) = FALSE ); assert( AI.Contains(5, TComparer<integer>.Construct( function(const Left, Right: integer): Integer begin Result := (Left + 4) - Right; end )) = TRUE ); // Delete AI.Delete(1); assert( AI.Contains(2) = FALSE ); assert( AI.Count = 2 ); try AI.Delete(2); assert(TRUE); except end; // exception expected AI.Delete(0); assert( AI.Count = 1 ); AI.Delete(0); assert( AI.Count = 0 ); try AI.Delete(0); assert(TRUE); except end; // exception expected // Insert AStr.Clear; AStr.Insert(0, 'one'); AStr.Insert(0, 'two'); assert( AStr.Count = 2 ); assert( AStr[0] = 'two' ); assert( AStr[1] = 'one' ); AStr.Insert(2, 'three'); assert( (AStr.Count = 3) and (AStr[2] = 'three') ); // AddRange AI.Clear; AI.AddRange( TArray<integer>.Create(4,5,6) ); assert( (AI.Count = 3) and (AI[2] = 6) ); AI.AddRange( TArray<integer>.Create(10,11,12) ); assert( (AI.Count = 6) and (AI[5] = 12) and (AI[0] = 4) ); // Compare AI.Create([1,2,3]); AI2 := AI; Assert( AI.Compare([1,2,3]) ); Assert( AI.Compare(AI.Items) ); Assert( AI.Compare(AI2) ); AI2.Add(4); Assert( not AI.Compare(AI2) ); // Equal AI.Create([1,2,3,4,5,6]); AI2 := AI; assert( AI = AI2 ); AI.AddRange( AI2 ); assert( (AI.Count = 12) and (AI <> AI2) ); AI2.InsertRange( AI2.Count, AI2 ); assert( (AI.Count = AI2.Count) and (AI = AI2) ); // InsertRange AI.Clear; AI.InsertRange( 0, TArray<integer>.Create(4,5,6) ); assert( (AI.Count = 3) and (AI[2] = 6) ); AI.InsertRange( 0, [10,11,12]); assert( (AI.Count = 6) and (AI[5] = 6) and (AI[0] = 10) ); AI.InsertRange( 3,[21,22]); assert( (AI.Count = 8) and (AI[7] = 6) and (AI[0] = 10) and (AI[3] = 21) ); // ForEach AI.Items := TArray<integer>.Create(5,4,3,2,1); AStr.Clear; AI.ForEach( procedure(var Value: integer; Index: integer) begin Value := Value * 10; AStr.Add(IntToStr(Value)); end ); // sort AI.Sort; AStr.Sort; assert( AI.Compare([10,20,30,40,50]) ); assert( AStr.Compare(['10','20','30','40','50']) ); // Find AI.Clear; AStr.SetItems(['4','king','joker','7','JOKER','joker','ace','joker']); I := -1; repeat I := AStr.Find(CompareJokerFunction, I+1); if I >= 0 then AI.Add( I); until I < 0; assert( AI.Compare([2,4,5,7]) ); // Map AI.Clear; for I := 1 to 50 do AI.Add( I); AI := AI.Map( function(var Value: integer; Index: integer): boolean begin Result := (Value >= 10) and (Value < 20); if Result then Value := Value + 100; end ); assert( AI.Count = 10 ); assert( AI[1] = 111 ); // Map <string> AStr.SetItems(CWeek); AStr := AStr.Map( function(var Value: string; Index: integer): boolean begin Result := Value <> 'Bug'; Value := Value + 'day'; end ); assert( AStr.Contains('Monday') ); assert( AStr.Contains('Sunday') ); assert( not AStr.Contains('Bugday') ); // enumerate AI.Clear; AStr.SetItems(CWeek); for S in AStr do AI.Add(length(S)); assert( AI.Count = AStr.Count ); assert( AI.Compare([3,4,6,3,5,3,5,3]) ); // check empty enumeration AStr.Clear; for S in AStr do AI.Add(length(S)); assert( AI.Compare([3,4,6,3,5,3,5,3]) ); // Unique AI.Unique; AI.Sort; assert( AI.Compare([3,4,5,6]) ); // CopyArray assert( AI.CopyArray(2).Compare([5,6]) ); assert( AI.CopyArray(0,2).Compare([3,4]) ); assert( AI.CopyArray(1,2).Compare([4,5]) ); end; procedure TestArrayHelper; var AI: TArray<integer>; AStr: TArray<string>; I: Integer; begin // Add AI := NIL; assert( TArray.Add<integer>(AI,1) = 0 ); assert( TArray.Add<integer>(AI,2) = 1 ); assert( TArray.Add<integer>(AI,3) = 2 ); // IndexOf assert( TArray.IndexOf<integer>(AI,1) = 0 ); assert( TArray.IndexOf<integer>(AI,2) = 1 ); assert( TArray.IndexOf<integer>(AI,5) = -1 ); // Contains assert( TArray.Contains<integer>(AI,2) = TRUE ); assert( TArray.Contains<integer>(AI,5) = FALSE ); assert( TArray.Contains<integer>(AI,5, TComparer<integer>.Construct( function(const Left, Right: integer): Integer begin Result := Left - (Right + 4); end )) = FALSE ); // Delete TArray.Delete<integer>(AI,1); assert( TArray.Contains<integer>(AI,2) = FALSE ); assert( length(AI) = 2 ); try TArray.Delete<integer>(AI,2); assert(TRUE); except end; // exception expected TArray.Delete<integer>(AI,0); assert( length(AI) = 1 ); TArray.Delete<integer>(AI,0); assert( length(AI) = 0 ); try TArray.Delete<integer>(AI,0); assert(TRUE); except end; // exception expected // Insert AStr := NIL; TArray.Insert<string>(AStr, 0, 'one'); TArray.Insert<string>(AStr, 0, 'two'); assert( length(AStr) = 2 ); assert( AStr[0] = 'two' ); assert( AStr[1] = 'one' ); TArray.Insert<string>(AStr, 2, 'three'); assert( (length(AStr) = 3) and (AStr[2] = 'three') ); // AddRange AI := NIL; TArray.AddRange<integer>(AI, TArray<integer>.Create(4,5,6)); assert( (length(AI) = 3) and (AI[2] = 6) ); TArray.AddRange<integer>(AI, TArray<integer>.Create(10,11,12)); assert( (length(AI) = 6) and (AI[5] = 12) and (AI[0] = 4) ); // InsertRange AI := NIL; TArray.InsertRange<integer>(AI, 0, TArray<integer>.Create(4,5,6)); assert( (length(AI) = 3) and (AI[2] = 6) ); TArray.InsertRange<integer>(AI, 0, TArray<integer>.Create(10,11,12)); assert( (length(AI) = 6) and (AI[5] = 6) and (AI[0] = 10) ); TArray.InsertRange<integer>(AI, 3, TArray<integer>.Create(21,22)); assert( (length(AI) = 8) and (AI[7] = 6) and (AI[0] = 10) and (AI[3] = 21) ); // ForEach AI := TArray<integer>.Create(5,4,3,2,1); AStr := NIL; TArray.ForEach<integer>( AI, procedure(var Value: integer; Index: integer) begin Value := Value * 10; TArray.Add<string>(AStr, IntToStr(Value)); end ); TArray.Sort<integer>(AI); TArray.Sort<string>(AStr); assert( TArray.Compare<integer>(AI, TArray<integer>.Create(10,20,30,40,50)) ); assert( TArray.Compare<string>(AStr, TArray<string>.Create('10','20','30','40','50')) ); // Find AI := NIL; AStr := TArray<string>.Create('4','king','joker','7','JOKER','joker','ace','joker'); I := -1; repeat I := TArray.Find<string>(AStr, CompareJokerFunction, I+1); if I >= 0 then TArray.Add<integer>(AI, I); until I < 0; assert( TArray.Compare<integer>(AI, TArray<integer>.Create(2,4,5,7)) ); // Map AI := NIL; for I := 1 to 50 do TArray.Add<integer>(AI, I); AI := TArray.Map<integer>(AI, function(var Value: integer; Index: integer): boolean begin Result := (Value >= 10) and (Value < 20); if Result then Value := Value + 100; end ); assert( length(AI) = 10 ); assert( AI[1] = 111 ); // Map <string> AStr := TArray<string>.Create('Mon','Tues','Wednes','Thurs','Fri','Satur','Sun'); AStr := TArray.Map<string>( AStr, function(var Value: string; Index: integer): boolean begin Result := TRUE; Value := Value + 'day'; end ); assert( TArray.Contains<string>(AStr, 'Monday') ); assert( TArray.Contains<string>(AStr, 'Sunday') ); end; class procedure TArrayHelper.Test_All_Helper_Functions; begin TestArrayHelper; TestArrayContainer; Test_TestRecord; end; {$ENDIF TEST_FUNCTION} end.
unit uServerContainer; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSSession, IPPeerServer, IPPeerAPI, Datasnap.DSAuth, System.Generics.Collections, uInterfaceSIP, uRotinasSIP, Forms, uRotinasSIPAntigo, IniFiles; type TServerContainer1 = class(TDataModule) DSServer1: TDSServer; DSServerClass1: TDSServerClass; procedure DSServerClass1GetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure DSServer1Disconnect(DSConnectEventObject: TDSConnectEventObject); private { Private declarations } FSessionID: TDSSession; class var FSession: TDictionary<string, TObject>; class var RotinasSIP:ISip; function ExecutaNovoSIP: Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function GetDictionary: TDictionary<string, TObject>; class function GetObjSIP: String; class function Ligar(const pObj: TObject): String; class function Transferir(const pObj: TObject): String; class function EnviarDTMF(const pObj: TObject): String; class function Desligar(): String; class function Registrar(const pObj: TObject): String; class function GetState(const pObj: TObject): String; end; function DSServer: TDSServer; implementation {$R *.dfm} uses uServerModule; var FModule: TComponent; FDSServer: TDSServer; function DSServer: TDSServer; begin Result := FDSServer; end; class function TServerContainer1.EnviarDTMF(const pObj: TObject): String; begin Result := RotinasSIP.EnviarDTMF(pObj); end; function TServerContainer1.ExecutaNovoSIP:Boolean; var vConfIni:TIniFile; vArquivo:String; begin result := false; vArquivo := ExtractFilePath(Application.ExeName) + 'cfg.ini'; if FileExists(vArquivo) then begin vConfIni:= TIniFile.Create(vArquivo); try result := LowerCase(vConfIni.ReadString('cfg', 'NOVOSIP', 'NAO')) = 'sim'; finally vConfIni.Destroy; end; end; end; constructor TServerContainer1.Create(AOwner: TComponent); begin inherited; FDSServer := DSServer1; if not Assigned(RotinasSIP) then begin if ExecutaNovoSIP then RotinasSIP := TRotinasSIP.Create else RotinasSIP := TRotinasSIPAntigo.Create; end; end; procedure TServerContainer1.DataModuleCreate(Sender: TObject); begin FSession := TDictionary<string, TObject>.Create; end; procedure TServerContainer1.DataModuleDestroy(Sender: TObject); begin FSession.Clear; FSession.Free; end; class function TServerContainer1.Desligar: String; begin Result := RotinasSIP.Desligar(); end; destructor TServerContainer1.Destroy; begin inherited; FDSServer := nil; end; procedure TServerContainer1.DSServer1Disconnect( DSConnectEventObject: TDSConnectEventObject); begin FSessionID := TDSSessionManager.GetThreadSession; end; procedure TServerContainer1.DSServerClass1GetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := uServerModule.TGetSIP; end; class function TServerContainer1.GetDictionary: TDictionary<string, TObject>; begin Result := FSession; end; class function TServerContainer1.GetObjSIP: String; begin Result := DSServer.Name; end; class function TServerContainer1.GetState(const pObj: TObject): String; begin Result := RotinasSIP.GetState; end; class function TServerContainer1.Ligar(const pObj: TObject): String; begin Result := RotinasSIP.Ligar(pObj); end; class function TServerContainer1.Registrar(const pObj: TObject): String; begin Result := RotinasSIP.Registrar(pObj); end; class function TServerContainer1.Transferir(const pObj: TObject): String; begin Result := RotinasSIP.Transferir(pObj); end; initialization FModule := TServerContainer1.Create(nil); finalization FModule.Free; end.
unit UProcesoVisor; interface uses IOUtils, Sysutils, StrUtils, UFolioCarpetaDigi, UFTP; type TProcesoVisor = class private FDatosFolio : TFolioCarpetaDigi; public constructor Create; destructor Destroy; {CONSTRUCTORES Y DESTRUCTORES} {PROPIEDADES} property DatosFolio : TFolioCarpetaDigi read FDatosFolio; {METODOS PROPIOS} Procedure BorrarCarpetaLocal(p_CarpLoca:string); Procedure CrearCarpetaLocal(p_CarpLoca:string); Function VerificarDescargarImagen(p_NombImag: string; p_RutaFtpp: string; p_FormImag: string; p_TipoCone: string): string; Function VerificarDescargarXml(p_NombImag: string; p_RutaFtpp: string; p_TipoCone: string): string; end; implementation {$REGION 'METODOS PROPIOS'} Procedure TProcesoVisor.BorrarCarpetaLocal(p_CarpLoca:string); begin try if TDirectory.Exists(p_CarpLoca) then TDirectory.Delete(p_CarpLoca,TRUE); except end; end; Procedure TProcesoVisor.CrearCarpetaLocal(p_CarpLoca:string); begin try if TDirectory.Exists(p_CarpLoca) then TDirectory.Delete(p_CarpLoca,TRUE); TDirectory.CreateDirectory(p_CarpLoca); FDatosFolio.RutaLocal := p_CarpLoca; except on e:exception do raise Exception.Create('No es posible crear la Carpeta Local de Descarga.' + #10#13 + '* ' + e.Message); end; end; Function TProcesoVisor.VerificarDescargarImagen(p_NombImag: string; p_RutaFtpp: string; p_FormImag: string; p_TipoCone: string): string; var ConexFTP : TFTP; ExteArch : string; ImagFtppDesd : string; {NOMBRE DEL ARCHIVO DE IMAGEN QUE SE VA A DESCARGAR DEPENDIENDO DEL FORMATO (PDF O TIF)} RutaFtppDesd : string; {RUTA DESDE DONDE SE VA A DESCARGAR DEPENDIENDO DEL FORMATO (PDF O TIF)} begin try FDatosFolio.NombreImagenOrig:= p_NombImag; ExteArch := ExtractFileExt(p_NombImag); if UpperCase(ExteArch) <> '.TIF' then Result:= 'La Extensión del Archivo Original es incorrecta' + #10#13 + '[ ' + ExteArch + ' ].' else begin with FDatosFolio do begin RutaFtpOrig := p_RutaFtpp; {SE CAMBIA LA CARPETA RAIZ DE LA RUTA AGREGANDOLE 'FE' (firma y estampa)} RutaFtpFirm := AnsiLeftStr(RutaFtpOrig,Pos('\',RutaFtpOrig)-1) + 'FE' + AnsiMidStr(RutaFtpOrig,Pos('\',RutaFtpOrig),1000); {SE CAMBIA LA EXTENSION DEL ARCHIVO POR 'PDF' } NombreImagenFirm := AnsiLeftStr(NombreImagenOrig, Length(NombreImagenOrig) - Length(ExteArch)) + '.pdf'; if p_FormImag = 'PDF' then begin RutaFtppDesd:= RutaFtpFirm; ImagFtppDesd:= NombreImagenFirm; ImagenLocal := RutaLocal + NombreImagenFirm; end else begin RutaFtppDesd:= RutaFtpOrig; ImagFtppDesd:= NombreImagenOrig; ImagenLocal := RutaLocal + NombreImagenOrig; end; if not FileExists(ImagenLocal) then begin ConexFTP:= TFTP.Create; ConexFTP.ConfigurarFTP(p_TipoCone); if p_FormImag = 'PDF' then RutaFtppDesd:= ConexFTP.CarpetaRaizPdf + RutaFtppDesd else RutaFtppDesd:= ConexFTP.CarpetaRaizTif + RutaFtppDesd ; ConexFTP.BajarArchivo(RutaFtppDesd,ImagFtppDesd, RutaLocal ); ConexFTP.Free; end; end; end; except on E:Exception do begin if FDatosFolio.ImagenLocal <> '' then TFile.Delete(FDatosFolio.ImagenLocal); Result:= 'No es posible Descargar la Imagen ' + #10#13 + '[ ' + ImagFtppDesd + ' ]' + #10#13 + 'en el equipo local.' + #10#13 + '* ' + ifthen (e.Message = 'Falla al copiar', 'Es posible que la Imagen no se encuentre firmada.', e.Message); end; end; end; Function TProcesoVisor.VerificarDescargarXml(p_NombImag: string; p_RutaFtpp: string; p_TipoCone: string): string; var ConexFTP : TFTP; ExteArch : string; RutaXmll : string; begin try ExteArch := ExtractFileExt(p_NombImag); if UpperCase(ExteArch) <> '.TIF' then Result:= 'La Extensión del Archivo Original es incorrecta' + #10#13 + '[ ' + ExteArch + ' ].' else begin with FDatosFolio do begin {SE CAMBIA LA EXTENSION DEL ARCHIVO POR 'XML' } NombreXmlOrig := AnsiLeftStr(p_NombImag,Length(NombreImagenOrig) - Length(ExteArch)) + '.xml'; XmlLocal := RutaLocal + NombreXmlOrig; if not FileExists(XmlLocal) then begin ConexFTP:= TFTP.Create; ConexFTP.ConfigurarFTP(p_TipoCone); RutaXmll := ConexFTP.CarpetaRaizTif + p_RutaFtpp; ConexFTP.BajarArchivo(RutaXmll,NombreXmlOrig, RutaLocal ); ConexFTP.Free; end; end; end; except on E:Exception do begin if FDatosFolio.ImagenLocal <> '' then TFile.Delete(FDatosFolio.XmlLocal); Result:= 'No es posible Descargar el Archivo ' + #10#13 + '[ ' + FDatosFolio.NombreXmlOrig + ' ]' + #10#13 + 'en el equipo local.' + #10#13 + '* ' + ifthen (e.Message = 'Falla al copiar', 'Es posible que el archivo XML no se haya generado.', e.Message); end; end; end; {$ENDREGION} {$REGION 'CONSTRUTOR AND DESTRUCTOR'} constructor TProcesoVisor.Create; begin FDatosFolio := TFolioCarpetaDigi.Create; end; destructor TProcesoVisor.Destroy; begin FDatosFolio.free; end; {$ENDREGION} {$REGION 'GETTERS AND SETTERS'} {$ENDREGION} end.
object fEditArmor: TfEditArmor Left = 205 Top = 107 Caption = 'Edit Armor ' ClientHeight = 265 ClientWidth = 613 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate DesignSize = ( 613 265) PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 8 Top = 8 Width = 50 Height = 13 Caption = 'Armor type' end object Label10: TLabel Left = 8 Top = 33 Width = 60 Height = 13 Caption = 'Protect from ' end object Memo: TMemo Left = 200 Top = 55 Width = 406 Height = 163 Anchors = [akLeft, akTop, akRight] ReadOnly = True TabOrder = 4 end object cbAT: TComboBox Left = 79 Top = 5 Width = 73 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 0 Items.Strings = ( '1' '2' '3' '4') end object cbAss: TCheckBox Left = 176 Top = 7 Width = 125 Height = 17 Alignment = taLeftJustify Caption = 'Used in assassination' TabOrder = 1 end object GroupBox1: TGroupBox Left = 8 Top = 51 Width = 185 Height = 210 TabOrder = 3 object Label2: TLabel Left = 8 Top = 16 Width = 76 Height = 13 Caption = 'slashing attacks' end object Label3: TLabel Left = 8 Top = 38 Width = 75 Height = 13 Caption = 'piercing attacks' end object Label4: TLabel Left = 8 Top = 65 Width = 78 Height = 13 Caption = 'crushing attacks' end object Label5: TLabel Left = 8 Top = 89 Width = 78 Height = 13 Caption = 'cleaving attacks' end object Label6: TLabel Left = 8 Top = 113 Width = 104 Height = 13 Caption = 'armor-piercing attacks' end object Label7: TLabel Left = 8 Top = 137 Width = 70 Height = 13 Caption = 'energy attacks' end object Label8: TLabel Left = 8 Top = 162 Width = 59 Height = 13 Caption = 'spirit attacks' end object Label9: TLabel Left = 8 Top = 186 Width = 76 Height = 13 Caption = 'weather attacks' end object ed1: TEdit Left = 119 Top = 12 Width = 47 Height = 21 TabOrder = 0 Text = '0' end object ed2: TEdit Left = 119 Top = 34 Width = 47 Height = 21 TabOrder = 1 Text = '0' end object ed4: TEdit Left = 119 Top = 85 Width = 47 Height = 21 TabOrder = 3 Text = '0' end object ed3: TEdit Left = 119 Top = 61 Width = 47 Height = 21 TabOrder = 2 Text = '0' end object ed6: TEdit Left = 119 Top = 133 Width = 47 Height = 21 TabOrder = 5 Text = '0' end object ed5: TEdit Left = 119 Top = 109 Width = 47 Height = 21 TabOrder = 4 Text = '0' end object ed8: TEdit Left = 119 Top = 182 Width = 47 Height = 21 TabOrder = 7 Text = '0' end object ed7: TEdit Left = 119 Top = 158 Width = 47 Height = 21 TabOrder = 6 Text = '0' end end object bnCancel: TButton Left = 406 Top = 230 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 6 end object bnOk: TButton Left = 294 Top = 230 Width = 75 Height = 25 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 5 OnClick = bnOkClick end object edFrom: TEdit Left = 79 Top = 29 Width = 74 Height = 21 TabOrder = 2 Text = '0' end end
unit sSpinEdit; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Classes, StdCtrls, ExtCtrls, Controls, Messages, SysUtils, Forms, Graphics, Menus, sEdit, acntUtils, sConst, buttons, sGraphUtils, sSpeedButton; {$IFNDEF NOTFORHELP} const InitRepeatPause = 400; { pause before repeat timer (ms) } RepeatPause = 100; { pause before hint window displays (ms)} {$ENDIF} // NOTFORHELP type {$IFNDEF NOTFORHELP} TNumGlyphs = Buttons.TNumGlyphs; TsTimerSpeedButton = class; TsSpinEdit = class; TsSpinButton = class(TWinControl) private FOwner : TsSpinEdit; FUpButton: TsTimerSpeedButton; FDownButton: TsTimerSpeedButton; FFocusedButton: TsTimerSpeedButton; FFocusControl: TWinControl; FOnUpClick: TNotifyEvent; FOnDownClick: TNotifyEvent; function CreateButton: TsTimerSpeedButton; function GetUpGlyph: TBitmap; function GetDownGlyph: TBitmap; procedure SetUpGlyph(Value: TBitmap); procedure SetDownGlyph(Value: TBitmap); procedure BtnClick(Sender: TObject); procedure BtnMouseDown (Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SetFocusBtn (Btn: TsTimerSpeedButton); procedure AdjustSize(var W, H: Integer); reintroduce; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; protected procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure WndProc (var Message: TMessage); override; public procedure PaintTo(DC : hdc; P : TPoint); constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published property Align; property Anchors; property Constraints; property Ctl3D; property DownGlyph: TBitmap read GetDownGlyph write SetDownGlyph; property DragCursor; property DragKind; property DragMode; property Enabled; property FocusControl: TWinControl read FFocusControl write FFocusControl; property ParentCtl3D; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property UpGlyph: TBitmap read GetUpGlyph write SetUpGlyph; property Visible; property OnDownClick: TNotifyEvent read FOnDownClick write FOnDownClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnStartDock; property OnStartDrag; property OnUpClick: TNotifyEvent read FOnUpClick write FOnUpClick; end; {$ENDIF} // NOTFORHELP TsBaseSpinEdit = class(TsEdit) {$IFNDEF NOTFORHELP} private FButton: TsSpinButton; FEditorEnabled: Boolean; FOnUpClick: TNotifyEvent; FOnDownClick: TNotifyEvent; FAlignment: TAlignment; function GetMinHeight: Integer; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; procedure WMCut(var Message: TWMCut); message WM_CUT; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure SetAlignment(const Value: TAlignment); protected procedure SetEditRect; function IsValidChar(var Key: AnsiChar): Boolean; virtual; procedure UpClick (Sender: TObject); virtual; abstract; procedure DownClick (Sender: TObject); virtual; abstract; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure PaintText; override; procedure PrepareCache; override; public constructor Create(AOwner: TComponent); override; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; destructor Destroy; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; property Button: TsSpinButton read FButton; property CharCase; procedure Loaded; override; procedure WndProc (var Message: TMessage); override; published {$ENDIF} // NOTFORHELP property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify; property EditorEnabled: Boolean read FEditorEnabled write FEditorEnabled default True; property OnDownClick: TNotifyEvent read FOnDownClick write FOnDownClick; property OnUpClick: TNotifyEvent read FOnUpClick write FOnUpClick; end; TsSpinEdit = class(TsBaseSpinEdit) {$IFNDEF NOTFORHELP} private FMinValue: LongInt; FMaxValue: LongInt; FIncrement: LongInt; function GetValue: LongInt; function CheckValue (NewValue: LongInt): Longint; procedure SetValue (NewValue: LongInt); procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL; protected procedure WMPaste(var Message: TWMPaste); message WM_PASTE; function IsValidChar(var Key: AnsiChar): Boolean; override; procedure UpClick (Sender: TObject); override; procedure DownClick (Sender: TObject); override; public constructor Create(AOwner: TComponent); override; published {$ENDIF} // NOTFORHELP property Increment: LongInt read FIncrement write FIncrement default 1; property MaxValue: LongInt read FMaxValue write FMaxValue; property MinValue: LongInt read FMinValue write FMinValue; property Value: LongInt read GetValue write SetValue; end; TsDecimalSpinEdit = class(TsBaseSpinEdit) {$IFNDEF NOTFORHELP} private FValue : Extended; FMinValue: Extended; FMaxValue: Extended; FIncrement: Extended; fDecimalPlaces:Integer; FUseSystemDecSeparator: boolean; function CheckValue (NewValue: Extended): Extended; procedure SetValue (NewValue: Extended); procedure SetDecimalPlaces(New:Integer); procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure FormatText; procedure CMChanged(var Message: TMessage); message CM_CHANGED; procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL; function GetValue: Extended; protected ValueChanging : boolean; TextChanging : boolean; procedure WMPaste(var Message: TWMPaste); message WM_PASTE; function IsValidChar(var Key: AnsiChar): Boolean; override; procedure UpClick (Sender: TObject); override; procedure DownClick (Sender: TObject); override; public constructor Create(AOwner: TComponent); override; procedure CreateWnd; override; published {$ENDIF} // NOTFORHELP property Increment: Extended read FIncrement write FIncrement; property MaxValue: Extended read FMaxValue write FMaxValue; property MinValue: Extended read FMinValue write FMinValue; property Value: Extended read GetValue write SetValue; property DecimalPlaces:Integer read fDecimalPlaces write SetDecimalPlaces default 2; property UseSystemDecSeparator : boolean read FUseSystemDecSeparator write FUseSystemDecSeparator default True; end; {$IFNDEF NOTFORHELP} { TsTimerSpeedButton } TTimeBtnState = set of (tbFocusRect, tbAllowTimer); TsTimerSpeedButton = class(TsSpeedButton) private FOwner : TsSpinButton; FRepeatTimer: TTimer; FTimeBtnState: TTimeBtnState; procedure TimerExpired(Sender: TObject); protected procedure Paint; override; procedure DrawGlyph; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public Up : boolean; constructor Create (AOwner: TComponent); override; destructor Destroy; override; procedure PaintTo(DC : hdc; P : TPoint); property TimeBtnState: TTimeBtnState read FTimeBtnState write FTimeBtnState; end; TacTimePortion = (tvHours, tvMinutes, tvSeconds); TsTimePicker = class(TsBaseSpinEdit) private fHour, fMin, fSec: word; FDoBeep: boolean; FShowSeconds: boolean; FUse12Hour: boolean; function GetValue: TDateTime; procedure SetValue (NewValue: TDateTime); function CheckValue (NewValue: TDateTime): TDateTime; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure SetShowSeconds(const Value: boolean); procedure SetUse12Hour(const Value: boolean); protected FPos : integer; function IsValidChar(var Key: AnsiChar): Boolean; override; procedure UpClick (Sender: TObject); override; procedure DownClick (Sender: TObject); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetHour(NewHour : integer); procedure SetMin(NewMin : integer); procedure SetSec(NewSec : integer); procedure DecodeValue; function Portion : TacTimePortion; procedure SetPos(NewPos : integer; Highlight : boolean = True); procedure IncPos; procedure ReplaceAtPos(APos : integer; AChar : Char); procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure HighlightPos(APos : integer); procedure Change; override; function EmptyText : acString; function TextLength : integer; function Sec : word; public MaxHour : integer; constructor Create(AOwner: TComponent); override; procedure Loaded; override; published property Date: TDateTime read GetValue write SetValue; property DoBeep : boolean read FDoBeep write FDoBeep default False; property Value: TDateTime read GetValue write SetValue; property Time: TDateTime read GetValue write SetValue; property ShowSeconds : boolean read FShowSeconds write SetShowSeconds default True; property Use12Hour : boolean read FUse12Hour write SetUse12Hour default False; end; {$ENDIF} // NOTFORHELP implementation uses sStyleSimply, Math, sSkinProps, sMessages, sCommonData, sSkinManager, sVCLUtils, sDefaults, sAlphaGraph {$IFDEF LOGGED}, sDebugMsgs{$ENDIF}; { TsSpinButton } constructor TsSpinButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption]; FOwner := TsSpinEdit(AOwner); FUpButton := CreateButton; FUpButton.Up := True; FDownButton := CreateButton; FDownButton.Up := False; UpGlyph := nil; DownGlyph := nil; Width := 18; FFocusedButton := FUpButton; end; function TsSpinButton.CreateButton: TsTimerSpeedButton; begin Result := TsTimerSpeedButton.Create(Self); Result.SkinData.SkinSection := s_SpeedButton_Small; Result.Parent := Self; Result.OnClick := BtnClick; Result.NumGlyphs := 1; Result.OnMouseDown := BtnMouseDown; Result.Visible := True; Result.Enabled := True; Result.Flat := False; Result.Transparent := True; Result.TimeBtnState := [tbAllowTimer]; end; procedure TsSpinButton.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FFocusControl) then FFocusControl := nil; end; procedure TsSpinButton.AdjustSize(var W, H: Integer); begin if (FUpButton = nil) or (csLoading in ComponentState) or (H = 0) then Exit; if W < 15 then W := 15; FUpButton.SetBounds(0, 0, W, H div 2); FDownButton.SetBounds(0, FUpButton.Height, W, H - FUpButton.Height); end; procedure TsSpinButton.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var W, H: Integer; begin W := AWidth; H := AHeight; AdjustSize (W, H); inherited SetBounds (ALeft, ATop, W, H); end; procedure TsSpinButton.WMSize(var Message: TWMSize); var W, H: Integer; begin inherited; W := Width; H := Height; AdjustSize(W, H); if (W <> Width) or (H <> Height) then inherited SetBounds(Left, Top, W, H); Message.Result := 0; end; procedure TsSpinButton.WMSetFocus(var Message: TWMSetFocus); begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState + [tbFocusRect]; FFocusedButton.Invalidate; end; procedure TsSpinButton.WMKillFocus(var Message: TWMKillFocus); begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState - [tbFocusRect]; FFocusedButton.Invalidate; end; procedure TsSpinButton.BtnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin SetFocusBtn (TsTimerSpeedButton (Sender)); if (FFocusControl <> nil) and FFocusControl.TabStop and FFocusControl.CanFocus and (GetFocus <> FFocusControl.Handle) then FFocusControl.SetFocus else if TabStop and (GetFocus <> Handle) and CanFocus then SetFocus; end; end; procedure TsSpinButton.BtnClick(Sender: TObject); begin if Sender = FUpButton then begin if Assigned(FOnUpClick) then FOnUpClick(Self); end else if Assigned(FOnDownClick) then FOnDownClick(Self); end; procedure TsSpinButton.SetFocusBtn(Btn: TsTimerSpeedButton); begin if TabStop and CanFocus and (Btn <> FFocusedButton) then begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState - [tbFocusRect]; FFocusedButton := Btn; if (GetFocus = Handle) then begin FFocusedButton.TimeBtnState := FFocusedButton.TimeBtnState + [tbFocusRect]; Invalidate; end; end; end; procedure TsSpinButton.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS; end; procedure TsSpinButton.Loaded; var W, H: Integer; begin inherited Loaded; W := Width; H := Height; AdjustSize (W, H); if (W <> Width) or (H <> Height) then inherited SetBounds (Left, Top, W, H); FUpButton.SkinData.SkinManager := FOwner.SkinData.FSkinManager; FDownButton.SkinData.SkinManager := FOwner.SkinData.FSkinManager; end; function TsSpinButton.GetUpGlyph: TBitmap; begin Result := FUpButton.Glyph; end; procedure TsSpinButton.SetUpGlyph(Value: TBitmap); begin FUpButton.Glyph := Value end; function TsSpinButton.GetDownGlyph: TBitmap; begin Result := FDownButton.Glyph; end; procedure TsSpinButton.SetDownGlyph(Value: TBitmap); begin FDownButton.Glyph := Value end; procedure TsSpinButton.WndProc(var Message: TMessage); var PS : TPaintStruct; begin if Message.MSG = SM_ALPHACMD then case Message.WParamHi of AC_GETBG : begin PacBGInfo(Message.LParam).BgType := btFill; PacBGInfo(Message.LParam).Color := SendMessage(FOwner.Handle, SM_ALPHACMD, MakeWParam(0, AC_GETCONTROLCOLOR), 0); //FOwner.Color; Exit end; AC_PREPARING : begin Message.Result := integer(FOwner.SkinData.FUpdating); Exit end; AC_ENDPARENTUPDATE : exit; end else case Message.Msg of WM_PAINT : if not FOwner.Enabled then begin BeginPaint(Handle, PS); EndPaint(Handle, PS); Exit; end; WM_ERASEBKGND : if not FOwner.Enabled then Exit; end; inherited; case Message.Msg of CM_ENABLEDCHANGED : begin SetUpGlyph(nil); SetDownGlyph(nil); end; end; end; procedure TsSpinButton.PaintTo(DC: hdc; P: TPoint); begin FUpButton.PaintTo(DC, P); inc(P.Y, FUpButton.Height); FDownButton.PaintTo(DC, P); end; { TsSpinEdit } constructor TsBaseSpinEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csSetCaption] + [csAcceptsControls]; FButton := TsSpinButton.Create(Self); FButton.Visible := False; FButton.Parent := Self; FButton.FocusControl := Self; FButton.OnUpClick := UpClick; FButton.OnDownClick := DownClick; FButton.SetUpGlyph(nil); FButton.SetDownGlyph(nil); FButton.Visible := True; ControlStyle := ControlStyle - [csAcceptsControls]; FAlignment := taLeftJustify; FEditorEnabled := True; end; destructor TsBaseSpinEdit.Destroy; begin FButton := nil; inherited Destroy; end; procedure TsBaseSpinEdit.GetChildren(Proc: TGetChildProc; Root: TComponent); begin end; procedure TsBaseSpinEdit.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); case Key of VK_UP: UpClick(Self); VK_DOWN: DownClick(Self); end; if Key <> 0 then SetEditRect; end; procedure TsBaseSpinEdit.KeyPress(var Key: Char); var C : AnsiChar; err : boolean; begin C := AnsiChar(Key); err := not IsValidChar(C); if err or (C = #0) then begin if (C = #0) then Key := #0; if err then MessageBeep(0); end else inherited KeyPress(Key); end; function TsBaseSpinEdit.IsValidChar(var Key: AnsiChar): Boolean; begin Result := CharInSet(Key, [DecimalSeparator, '+', '-', '0'..'9']) or ((Key < #32) and (Key <> Chr(VK_RETURN))); if not FEditorEnabled and Result and ((Key >= #32) or (Key = Char(VK_BACK)) or (Key = Char(VK_DELETE))) then Result := False; end; procedure TsBaseSpinEdit.CreateParams(var Params: TCreateParams); const Alignments: array[TAlignment] of Longword = (ES_LEFT, ES_RIGHT, ES_CENTER); begin inherited CreateParams(Params); Params.Style := Params.Style or ES_MULTILINE or WS_CLIPCHILDREN or Alignments[FAlignment] and not WS_BORDER; end; procedure TsBaseSpinEdit.CreateWnd; begin inherited CreateWnd; SetEditRect; end; procedure TsBaseSpinEdit.SetEditRect; var Loc: TRect; begin SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc)); Loc.Bottom := ClientHeight + 1; {+1 is workaround for windows paint bug} Loc.Right := Width - FButton.Width - 3; Loc.Top := 0; Loc.Left := 0; SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@Loc)); SendMessage(Handle, EM_GETRECT, 0, LongInt(@Loc)); {debug} end; procedure TsBaseSpinEdit.WMSize(var Message: TWMSize); var MinHeight: Integer; begin inherited; MinHeight := GetMinHeight; if Height < MinHeight then Height := MinHeight else if FButton <> nil then begin FButton.SetBounds(Width - FButton.Width - 4, 0, FButton.Width, Height - 4); SetEditRect; end; end; function TsBaseSpinEdit.GetMinHeight: Integer; begin Result := 0; end; procedure TsBaseSpinEdit.WMPaste(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TsBaseSpinEdit.WMCut(var Message: TWMPaste); begin if not FEditorEnabled or ReadOnly then Exit; inherited; end; procedure TsBaseSpinEdit.Loaded; begin inherited; FButton.SetUpGlyph(nil); FButton.SetDownGlyph(nil); SetEditRect; end; constructor tsSpinEdit.Create(AOwner:TComponent); begin inherited create(AOwner); FIncrement := 1; end; procedure TsSpinEdit.CMExit(var Message: TCMExit); begin inherited; if (Text = '-0') or (Text = '-') then Text := '0'; if CheckValue(Value) <> Value then SetValue(Value); end; procedure TsSpinEdit.UpClick (Sender: TObject); begin if ReadOnly then MessageBeep(0) else begin if Assigned(FOnUpClick) then FOnUpClick(Self) else Value := Value + FIncrement; end; end; procedure TsSpinEdit.DownClick (Sender: TObject); begin if ReadOnly then MessageBeep(0) else begin if Assigned(FOnDownClick) then FOnDownClick(Self) else Value := Value - FIncrement; end; end; function TsSpinEdit.GetValue: LongInt; begin if Text <> '' then begin try Result := StrToInt(Text); except Result := FMinValue; end; end else Result := 0; end; procedure TsSpinEdit.SetValue (NewValue: LongInt); begin if not (csLoading in ComponentState) then Text := IntToStr(CheckValue(NewValue)); end; function TsSpinEdit.CheckValue(NewValue: LongInt): LongInt; begin Result := NewValue; if ((FMinValue <> 0) or (FMinValue <> FMaxValue)) and (NewValue < FMinValue) then Result := FMinValue else if (FMaxValue <> 0) and (NewValue > FMaxValue) then Result := FMaxValue; end; function TsSpinEdit.IsValidChar(var Key: AnsiChar): Boolean; begin Result := False; case Key of Chr(VK_RETURN) : begin Key := #0; Exit; end; Char(VK_BACK), Chr(VK_ESCAPE) : Exit; '-' : if (Pos('-', Text) <= 0) or (SelLength >= Length(Text) - 1) then begin if (DWord(SendMessage(Handle, EM_GETSEL, 0, 0)) mod $10000 = 0) then begin if (MinValue <= 0) then Result := True else Result := False; Exit; end; end; end; Result := FEditorEnabled and CharInSet(Key, ['0'..'9']) or (Key < #32); if not Result then Key := #0; end; procedure TsSpinEdit.CMMouseWheel(var Message: TCMMouseWheel); begin inherited; if not ReadOnly and (Message.Result = 0) then begin Value := Value + Increment * (Message.WheelDelta div 120); Message.Result := 1 end; end; procedure TsSpinEdit.WMPaste(var Message: TWMPaste); {$IFDEF DELPHI6UP} var OldValue, NewValue : integer; {$ENDIF} begin if not FEditorEnabled or ReadOnly then Exit; {$IFDEF DELPHI6UP} OldValue := Value; {$ENDIF} inherited; {$IFDEF DELPHI6UP} if not TryStrToInt(Text, NewValue) then Text := IntToStr(OldValue); {$ENDIF} end; {tsDecimalSpinEdit} constructor TsDecimalSpinEdit.Create(AOwner:TComponent); begin inherited create(AOwner); ValueChanging := False; TextChanging := False; FUseSystemDecSeparator := True; FIncrement := 1.0; FDecimalPlaces := 2; end; procedure TsDecimalSpinEdit.CMExit(var Message: TCMExit); begin inherited; if CheckValue(Value) <> Value then SetValue(Value); FormatText; end; procedure tsDecimalSpinEdit.UpClick(Sender: TObject); var CurValue : real; begin if ReadOnly then MessageBeep(0) else begin CurValue := Value; if Assigned(FOnUpClick) then FOnUpClick(Self) else Value := CurValue + FIncrement; end; end; procedure tsDecimalSpinEdit.DownClick (Sender: TObject); var CurValue : real; begin if ReadOnly then MessageBeep(0) else begin CurValue := Value; if Assigned(FOnDownClick) then FOnDownClick(Self) else Value := CurValue - FIncrement; end; end; procedure tsDecimalSpinEdit.SetDecimalPlaces(New : Integer); begin if fDecimalPlaces <> New then begin fDecimalPlaces := New; Value := CheckValue(Value); end; end; procedure tsDecimalSpinEdit.SetValue(NewValue: Extended); begin if MaxValue > MinValue then FValue := max(min(NewValue, MaxValue), MinValue) else FValue := NewValue; ValueChanging := True; if not TextChanging then begin SendMessage(Handle, WM_SETTEXT, 0, Longint(PChar(FloatToStrF(CheckValue(FValue), ffFixed, 18, fDecimalPlaces)))); if not (csLoading in ComponentState) and Assigned(OnChange) then OnChange(Self); end; ValueChanging := False; end; function tsDecimalSpinEdit.CheckValue (NewValue: Extended): Extended; begin Result := NewValue; if (FMinValue <> 0) and (NewValue < FMinValue) then Result := FMinValue else if (FMaxValue <> 0) and (NewValue > FMaxValue) then Result := FMaxValue; end; function tsDecimalSpinEdit.IsValidChar(var Key: AnsiChar): Boolean; var bIsDecSeparator : boolean; begin Result := False; case Key of Chr(VK_RETURN) : begin Key := #0; Exit; end; Char(VK_BACK), Chr(VK_ESCAPE) : Exit; end; if FUseSystemDecSeparator then bIsDecSeparator := Key = AnsiChar(DecimalSeparator) else bIsDecSeparator := CharInSet(Key, ['.', ',']); Result := bIsDecSeparator or CharInSet(Key, ['+', '-', '0'..'9']) or (Key < #32); if (bIsDecSeparator and (DecimalPlaces <= 0)) then Result := False else if (bIsDecSeparator and (Pos(Key, Text) <> 0)) then Result := False else if (bIsDecSeparator and ((Pos('+', Text) - 1 >= SelStart) or (Pos('-', Text) - 1 >= SelStart))) then Result := False else if (CharInSet(Key, ['+', '-']) and ((SelStart <> 0) or (Pos('+', Text) <> 0) or (Pos('-', Text) <> 0))) and (SelLength <= Length(Text) - 1) then Result := False else if not FEditorEnabled and Result then Result := False; if not Result then Key := #0; end; procedure TsDecimalSpinEdit.CMMouseWheel(var Message: TCMMouseWheel); begin inherited; if not ReadOnly and (Message.Result = 0) then begin Value := Value + Increment * (Message.WheelDelta div 120); Message.Result := 1 end; end; function TsDecimalSpinEdit.GetValue: Extended; {$IFDEF DELPHI6UP} var v : Extended; {$ENDIF} begin if not TextChanging then Result := FValue else {$IFDEF DELPHI6UP} if TryStrToFloat(Text, V) then Result := V else Result := 0; {$ELSE} try if Text = '' then Result := 0 else Result := StrToFloat(Text); except Result := 0; end; {$ENDIF} end; procedure TsDecimalSpinEdit.CreateWnd; begin inherited; if HandleAllocated then FormatText; end; procedure TsDecimalSpinEdit.CMChanged(var Message: TMessage); begin inherited; if not (csLoading in ComponentState) and not ValueChanging then begin TextChanging := True; if (Text = '') or (Text = '-') then Value := 0 else Value := StrToFloat(Text); TextChanging := False; end; end; procedure TsDecimalSpinEdit.FormatText; begin ValueChanging := True; if not TextChanging then begin SendMessage(Handle, WM_SETTEXT, 0, Longint(PChar(FloatToStrF(CheckValue(FValue), ffFixed, 18, FDecimalPlaces)))); end; ValueChanging := False; end; procedure TsDecimalSpinEdit.WMPaste(var Message: TWMPaste); {$IFDEF DELPHI6UP} var OldValue, NewValue : extended; {$ENDIF} begin if not FEditorEnabled or ReadOnly then Exit; {$IFDEF DELPHI6UP} OldValue := Value; {$ENDIF} inherited; {$IFDEF DELPHI6UP} if not TryStrToFloat(Text, NewValue) then Text := FloatToStr(OldValue); {$ENDIF} end; {TsTimerSpeedButton} destructor TsTimerSpeedButton.Destroy; begin if FRepeatTimer <> nil then FreeAndNil(FRepeatTimer); inherited Destroy; end; procedure TsTimerSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); Down := True; if tbAllowTimer in FTimeBtnState then begin if FRepeatTimer = nil then FRepeatTimer := TTimer.Create(Self); FRepeatTimer.OnTimer := TimerExpired; FRepeatTimer.Interval := InitRepeatPause; FRepeatTimer.Enabled := True; end; end; procedure TsTimerSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Down := False; inherited MouseUp (Button, Shift, X, Y); if FRepeatTimer <> nil then FRepeatTimer.Enabled := False; end; procedure TsTimerSpeedButton.TimerExpired(Sender: TObject); begin FRepeatTimer.Interval := RepeatPause; if MouseCapture then begin try Click; except FRepeatTimer.Enabled := False; raise; end; end; end; procedure TsTimerSpeedButton.Paint; var R: TRect; begin if (csDestroying in ComponentState) or (csLoading in ComponentState) then Exit; inherited Paint; if tbFocusRect in FTimeBtnState then begin R := Bounds(0, 0, Width, Height); InflateRect(R, -3, -3); if Down then OffsetRect(R, 1, 1); DrawFocusRect(Canvas.Handle, R); end; end; constructor TsTimerSpeedButton.Create(AOwner: TComponent); begin FOwner := TsSpinButton(AOwner); inherited Create(AOwner); end; procedure TsBaseSpinEdit.WndProc(var Message: TMessage); begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} inherited; if Message.MSG = SM_ALPHACMD then case Message.WParamHi of AC_REMOVESKIN, AC_SETNEWSKIN, AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin FButton.FUpButton.Perform(Message.Msg, Message.WParam, Message.LParam); FButton.FdownButton.Perform(Message.Msg, Message.WParam, Message.LParam); if Message.WParamHi in [AC_REFRESH, AC_REMOVESKIN] then begin FButton.FUpButton.Invalidate; FButton.FDownButton.Invalidate; end else begin FButton.FUpButton.Enabled := True; FButton.FDownButton.Enabled := True; end; FButton.SetUpGlyph(nil); FButton.SetDownGlyph(nil); SetEditRect; end; AC_ENDPARENTUPDATE : FButton.Repaint; AC_GETBG : InitBGInfo(SkinData, PacBGInfo(Message.LParam), 0); AC_GETCONTROLCOLOR : begin Message.Result := GetBGColor(SkinData, 0); { if not Enabled then begin TColor(Message.Result) := MixColors(GetControlColor(Parent), TColor(Message.Result), 0.5); end; } end; end else case Message.MSG of CM_MOUSEENTER, CM_MOUSELEAVE : begin FButton.FUpButton.SkinData.FMouseAbove := False; FButton.FUpButton.SkinData.BGChanged := True; FButton.FUpButton.Perform(SM_ALPHACMD, MakeWParam(0, AC_STOPFADING), 0); FButton.FUpButton.GraphRepaint; FButton.FDownButton.SkinData.FMouseAbove := False; FButton.FDownButton.SkinData.BGChanged := True; FButton.FDownButton.Perform(SM_ALPHACMD, MakeWParam(0, AC_STOPFADING), 0); FButton.FDownButton.GraphRepaint; end; CM_ENABLEDCHANGED : begin FButton.Enabled := Enabled; if SkinData.Skinned then FButton.Visible := Enabled else begin FButton.FUpButton.Enabled := Enabled; FButton.FDownButton.Enabled := Enabled; end end; WM_PAINT : if SkinData.Skinned then begin SkinData.Updating := SkinData.Updating; if not SkinData.Updating and Enabled then begin Button.FUpButton.Perform(SM_ALPHACMD, MakeWParam(0, AC_STOPFADING), 0); Button.FUpButton.SkinData.BGChanged := True; Button.FDownButton.Perform(SM_ALPHACMD, MakeWParam(0, AC_STOPFADING), 0); Button.FDownButton.SkinData.BGChanged := True; end; end; WM_SIZE, CM_FONTCHANGED : SetEditRect; WM_SETFOCUS : if AutoSelect then begin Self.SelectAll end; CM_COLORCHANGED : begin if SkinData.CustomColor then PrepareCache; RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE); end; end; end; procedure TsTimerSpeedButton.PaintTo(DC: hdc; P: TPoint); begin PrepareCache; BitBlt(DC, P.X, P.Y, Width, Height, SkinData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); end; procedure TsTimerSpeedButton.DrawGlyph; var C : TColor; P : TPoint; aCanvas : TCanvas; begin if (Glyph = nil) or Glyph.Empty then begin if (SkinData.SkinIndex > -1) and not FOwner.FOwner.SkinData.CustomFont then begin if CurrentState = 0 then C := ColorToRGB(SkinData.SkinManager.gd[FOwner.FOwner.SkinData.SkinIndex].FontColor[1]) else begin if SkinData.SkinManager.gd[SkinData.SkinIndex].States > 1 then C := ColorToRGB(SkinData.SkinManager.gd[SkinData.SkinIndex].HotFontColor[1]) else C := ColorToRGB(SkinData.SkinManager.gd[SkinData.SkinIndex].FontColor[1]) end; end else begin if Enabled then C := ColorToRGB(Font.Color) else C := ColorToRGB(clGrayText) end; if SkinData.Skinned then aCanvas := SkinData.FCacheBmp.Canvas else aCanvas := Canvas; aCanvas.Pen.Color := C; aCanvas.Brush.Style := bsSolid; aCanvas.Brush.Color := clFuchsia; aCanvas.FillRect(Rect(0, 0, Glyph.Width, Glyph.Height)); aCanvas.Pen.Style := psSolid; aCanvas.Brush.Color := C; P.X := (Width - 9) div 2; P.Y := (Height - 5) div 2; if Up then aCanvas.Polygon([Point(P.X + 1, P.Y + 4), Point(P.X + 7, P.Y + 4), Point(P.X + 4, P.Y + 1)]) else aCanvas.Polygon([Point(P.X + 1, P.Y + 1), Point(P.X + 7, P.Y + 1), Point(P.X + 4, P.Y + 4)]); end else inherited; end; { TsSpinButton } constructor TsTimePicker.Create(AOwner:TComponent); begin inherited create(AOwner); MaxHour := 24; FShowSeconds := True; FDoBeep := False; fHour := 0; fMin := 0; fSec := 0; end; procedure TsTimePicker.CMExit(var Message: TCMExit); begin inherited; if CheckValue(Value) <> Value then SetValue(Value); end; procedure TsTimePicker.UpClick (Sender: TObject); var cPortion : TacTimePortion; begin cPortion := Portion; if ReadOnly then begin if FDoBeep then MessageBeep(0); end else if length(Text) = TextLength then begin DecodeValue; case Portion of tvHours : SetHour(FHour + 1); tvMinutes : SetMin(FMin + 1); tvSeconds : SetSec(FSec + 1); end; if ShowSeconds then Text := Format('%0.2d:%0.2d:%0.2d', [fHour, fMin, fSec]) else Text := Format('%0.2d:%0.2d', [fHour, fMin]); if (not (csLoading in ComponentState)) then begin case cPortion of tvHours : SelStart := 0; tvMinutes : SelStart := 3; tvSeconds : SelStart := 6; end; FPos := SelStart + 2; SelLength := 2; end; end; end; procedure TsTimePicker.DownClick (Sender: TObject); var cPortion : TacTimePortion; begin cPortion := Portion; if ReadOnly then begin if FDoBeep then MessageBeep(0); end else if length(Text) = TextLength then begin DecodeValue; case Portion of tvHours : SetHour(FHour - 1); tvMinutes : SetMin(FMin - 1); tvSeconds : SetSec(FSec - 1); end; if ShowSeconds then Text := Format('%0.2d:%0.2d:%0.2d', [fHour, fMin, fSec]) else Text := Format('%0.2d:%0.2d', [fHour, fMin]); if (not (csLoading in ComponentState)) then begin case cPortion of tvHours : SelStart := 0; tvMinutes : SelStart := 3; tvSeconds : SelStart := 6; end; FPos := SelStart + 2; SelLength := 2; end; end; end; function TsTimePicker.GetValue: TDateTime; begin Result := 0; if length(Text) = TextLength then try DecodeValue; Result := EncodeTime(FHour, FMin, Sec, 0) except Result := 0; end; end; procedure TsTimePicker.SetValue(NewValue: TDateTime); var NewText: String; dMSec: Word; begin DecodeTime(NewValue, FHour, FMin, FSec, dMSec); if ShowSeconds then NewText := Format('%0.2d:%0.2d:%0.2d', [FHour, FMin, FSec]) else NewText := Format('%0.2d:%0.2d', [FHour, FMin]); if not (csLoading in ComponentState) then Text := NewText; end; function TsTimePicker.CheckValue (NewValue: TDateTime): TDateTime; begin if NewValue < 0 then Result := 0 else Result := NewValue; end; function TsTimePicker.IsValidChar(var Key: AnsiChar): Boolean; var i : integer; {$IFDEF TNTUNICODE} c : PWideChar; {$ENDIF} s : string; begin Result := False; i := 0; if not FEditorEnabled or CharInSet(Key, [Chr(VK_ESCAPE), Chr(VK_RETURN), #0]) then begin Key := #0; Exit; end; Result := CharInSet(Key, ['0'..'9']); if Result then begin {$IFDEF TNTUNICODE} c := PWideChar(Text); s := WideCharToString(c); {$ELSE} s := Text; {$ENDIF} case FPos of 1 : i := StrToInt(Key + s[2]); 2 : i := StrToInt(s[1] + Key); 4 : i := StrToInt(Key + s[4]); 5 : i := StrToInt(s[4] + Key); 7 : i := StrToInt(Key + s[8]); 8 : i := StrToInt(s[7] + Key) else if not (Key in ['0', '1']) then i := 99; // If selected all, then ignored end; if FPos in [1, 2] then begin if i > 23 then Result := False; end else if i > 59 then Result := False; end; if not Result then Key := #0; end; procedure TsBaseSpinEdit.PrepareCache; var bw : integer; begin InitCacheBmp(SkinData); PaintItem(SkinData, GetParentCache(SkinData), True, integer(ControlIsActive(SkinData)), Rect(0, 0, Width, Height), Point(Left, top), SkinData.FCacheBmp, False); PaintText; if not Enabled then begin bw := integer(BorderStyle <> bsNone) * (1 + integer(Ctl3d)); SkinData.FCacheBmp.Canvas.Lock; FButton.PaintTo(SkinData.FCacheBmp.Canvas.Handle, Point(FButton.Left + bw, FButton.Top + bw)); SkinData.FCacheBmp.Canvas.UnLock; BmpDisabledKind(SkinData.FCacheBmp, DisabledKind, Parent, GetParentCache(SkinData), Point(Left, Top)); end; SkinData.BGChanged := False; end; procedure TsTimePicker.KeyDown(var Key: Word; Shift: TShiftState); begin case Key of VK_UP : UpClick (Self); VK_DOWN : DownClick (Self); VK_RIGHT : if (Shift = []) then IncPos else begin FPos := min(TextLength, FPos + 1); inherited; exit; end; VK_LEFT : if (Shift = []) then SetPos(max(1, FPos - 1 - integer(FPos in [4, 7])), (Shift = [])) else begin FPos := max(1, FPos - 1); inherited; exit; end; VK_BACK, VK_DELETE : if not AllEditSelected(Self) then begin ReplaceAtPos(FPos, '0'); if Key = VK_BACK then begin Key := VK_LEFT; KeyDown(Key, Shift); end else begin HighlightPos(FPos); Key := 0; end end else begin if (not (csLoading in ComponentState)) and not (csDesigning in ComponentState) and Visible then begin SelStart := 0; SelLength := 0; end; Text := EmptyText; SetPos(1); end; end; if Key in [VK_BACK, VK_SPACE, VK_LEFT..VK_DOWN, VK_DELETE] then Key := 0; inherited; case Key of VK_END : begin FPos := TextLength; if (Shift = []) then begin if (not (csLoading in ComponentState)) and not (csDesigning in ComponentState) and Visible then begin SelStart := TextLength - 1; SelLength := 1; end; Key := 0; end; end; VK_HOME : begin if (Shift = []) then begin if (not (csLoading in ComponentState)) and not (csDesigning in ComponentState) and Visible then begin SelStart := 0; SelLength := 1; end; Key := 0; end else SelStart := FPos; FPos := 1; end; end end; procedure TsTimePicker.KeyPress(var Key: Char); var C : AnsiChar; begin C := AnsiChar(Key); if not IsValidChar(C) then begin if C = #0 then begin Key := #0; if FDoBeep then MessageBeep(0); end else begin inherited; end; Exit; end; if AllEditSelected(Self) then SetPos(1); inherited; ReplaceAtPos(FPos, Key); Key := #0; IncPos; end; procedure TsTimePicker.HighlightPos(APos: integer); begin if (not (csLoading in ComponentState)) and not (csDesigning in ComponentState) and Visible then begin SelStart := APos - 1; SelLength := 1; end end; procedure TsTimePicker.SetPos(NewPos: integer; Highlight: boolean); begin FPos := NewPos; if FPos in [3, 6] then dec(FPos); if Highlight then HighlightPos(FPos); end; procedure TsTimePicker.ReplaceAtPos(APos : integer; AChar : Char); var s : string; begin if FEditorEnabled and (APos <= Length(Text)) then begin s := Text; s[APos] := AChar; Text := s; end; end; procedure TsTimePicker.IncPos; begin SetPos(min(TextLength, FPos + 1 + integer(FPos in [2, 5]))); end; function TsTimePicker.Portion: TacTimePortion; var FCurPos: DWord; begin FCurPos := DWord(SendMessage(Handle, EM_GETSEL, 0, 0)) mod $10000; case FCurPos of 0..2 : Result := tvHours; 3..5 : Result := tvMinutes else Result := tvSeconds; end end; procedure TsTimePicker.DecodeValue; var s : string; begin s := Text; FHour := StrToInt(copy(s, 1, 2)); FMin := StrToInt(copy(s, 4, 2)); if (TextLength <= Length(Text)) and ShowSeconds then FSec := StrToInt(copy(s, 7, 2)) else FSec := 0; end; procedure TsTimePicker.SetHour(NewHour: integer); begin if NewHour >= MaxHour then SetHour(NewHour - MaxHour) else if NewHour < 0 then SetHour(NewHour + MaxHour) else FHour := NewHour; end; procedure TsTimePicker.SetMin(NewMin: integer); begin if NewMin >= 60 then begin SetHour(FHour + 1); SetMin(NewMin - 60); end else if NewMin < 0 then begin SetHour(FHour - 1); SetMin(NewMin + 60); end else FMin := NewMin end; procedure TsTimePicker.SetSec(NewSec: integer); begin if NewSec >= 60 then begin SetMin(FMin + 1); SetSec(NewSec - 60); end else if NewSec < 0 then begin SetMin(FMin - 1); SetSec(NewSec + 60); end else FSec := NewSec end; procedure TsTimePicker.Change; begin inherited; end; procedure TsTimePicker.Loaded; begin inherited; if AllEditSelected(Self) then FPos := TextLength + 1 else SetPos(1); if Text = '' then Text := EmptyText; end; procedure TsTimePicker.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var FCurPos: DWord; begin inherited; if SelLength = 0 then begin FCurPos := DWord(SendMessage(Handle, EM_GETSEL, 0, 0)) mod $10000; SetPos(min(TextLength, FCurPos + 1)) end; end; procedure TsTimePicker.SetShowSeconds(const Value: boolean); var CurValue : TDateTime; begin if FShowSeconds <> Value then begin CurValue := Self.Value; FShowSeconds := Value; SetValue(CurValue); if not (csLoading in ComponentState) and Visible then Repaint; end; end; function TsTimePicker.EmptyText: acString; begin if not ShowSeconds then Result := '00:00' else Result := '00:00:00'; end; function TsTimePicker.TextLength: integer; begin if not ShowSeconds then Result := 5 else Result := 8; end; function TsTimePicker.Sec: word; begin if FShowSeconds then Result := FSec else Result := 0; end; procedure TsTimePicker.SetUse12Hour(const Value: boolean); begin FUse12Hour := Value; if Value then MaxHour := 12 else MaxHour := 24; end; procedure TsBaseSpinEdit.SetAlignment(const Value: TAlignment); begin if FAlignment <> Value then begin FAlignment := Value; RecreateWnd; end; end; procedure TsBaseSpinEdit.PaintText; var R : TRect; s : acString; i : integer; BordWidth : integer; Flags : Cardinal; begin if Alignment = taLeftJustify then inherited else begin SkinData.FCacheBMP.Canvas.Font.Assign(Font); if BorderStyle <> bsNone then BordWidth := 1 + integer(Ctl3D) else BordWidth := 0; BordWidth := BordWidth {$IFDEF DELPHI7UP} + integer(BevelKind <> bkNone) * (integer(BevelOuter <> bvNone) + integer(BevelInner <> bvNone)) {$ENDIF}; Flags := DT_TOP or DT_NOPREFIX or DT_SINGLELINE; R := Rect(BordWidth + 1, BordWidth + 1, Width - BordWidth - FButton.Width, Height - BordWidth); {$IFDEF TNTUNICODE} if PasswordChar <> #0 then for i := 1 to Length(Text) do s := s + PasswordChar else s := Text; dec(R.Bottom); dec(R.Top); sGraphUtils.WriteUniCode(SkinData.FCacheBmp.Canvas, s, True, R, Flags or GetStringFlags(Self, Alignment) and not DT_VCENTER, SkinData, ControlIsActive(SkinData) and not ReadOnly); {$ELSE} if PasswordChar <> #0 then begin for i := 1 to Length(Text) do s := s + PasswordChar; end else s := Text; acWriteTextEx(SkinData.FCacheBMP.Canvas, PacChar(s), True, R, Flags or Cardinal(GetStringFlags(Self, Alignment)) and not DT_VCENTER, SkinData, ControlIsActive(SkinData)); {$ENDIF} end; end; procedure TsBaseSpinEdit.WMGetDlgCode(var Message: TWMGetDlgCode); begin inherited; Message.Result := Message.Result and not DLGC_WANTALLKEYS; end; end.
program UsingConstants; const PI = 3.141592654; var radius, diameter, circumference : real; begin writeln('Enter circle radius: '); readln(radius); diameter := 2 * radius; circumference := PI * diameter; writeln('The circumference of the circle is ', circumference:7:2); end.
Program RockPaperScissors; Uses crt; Var player, cpu, uwincount, cwincount, drawCount, playCount : Integer; Playerinput : String; Function WinLoseDraw(player : Integer) : String; {rockR0, paperP1, scissorS2} Begin cursoroff; Randomize; CPU := Random(3); WriteLn; Case cpu Of 0: Begin WriteLn('CPU: '); WriteLn(' _ '); WriteLn(' | | '); WriteLn(' _ __ ___ ___| | __'); WriteLn('| |__/ _ \ / __| |/ /'); WriteLn('| | | (_) | (__| < '); WriteLn('|_| \___/ \___|_|\_\'); End; 1: Begin WriteLn('CPU: '); WriteLn(' _ __ __ _ _ __ ___ _ __ '); WriteLn('| _ \ / _` | _ \ / _ \ __|'); WriteLn('| |_) | (_| | |_) | __/ | '); WriteLn('| .__/ \__,_| .__/ \___|_| '); WriteLn('| | | | '); WriteLn('|_| |_| '); End; 2: Begin WriteLn('CPU: '); WriteLn(' _ '); WriteLn(' (_) '); WriteLn(' ___ ___ _ ___ ___ ___ _ __ ___ '); WriteLn('/ __|/ __| / __/ __|/ _ \| __/ __|'); WriteLn('\__ \ (__| \__ \__ \ (_) | | \__ \'); WriteLn('|___/\___|_|___/___/\___/|_| |___/'); End; End; WriteLn; If cpu = player Then Begin WinLoseDraw := 'Draw!'; drawCount := drawCount+1 End Else If (player = 0) And (cpu = 1) Or (player = 1) And (cpu = 2) Or ( player = 2) And (cpu = 0) Then Begin WinLoseDraw := 'Lose!'; cwincount := cwincount +1; End Else If (player = 1) And (cpu = 0) Or (player = 2) And (cpu = 1) Or ( player = 0) And (cpu = 2) Then Begin WinLoseDraw := 'Win!'; uwincount := uwincount +1; End Else WriteLn('WinLoseDraw error'); End; Procedure center(Str : String; Ln : Integer); Begin GoToXY((80 - Length(Str)) div 2, Ln); Write(Str); End; (* Main *) Begin center('Welcome to the game', 1); center('>Press any key to play.', 2); Readkey; Clrscr; playCount := 1; Repeat WriteLn; WriteLn('Enter (R)ock, (P)aper, (S)cissors. Play', playCount, '/5' ); playerinput := Upcase(Readkey); If (playerinput = 'P') Or (playerinput = 'S') Or (playerinput = 'R') Then Begin WriteLn('Your play:'); If playerinput = 'R' Then Begin WriteLn(' _ '); WriteLn(' | | '); WriteLn(' _ __ ___ ___| | __'); WriteLn('| |__/ _ \ / __| |/ /'); WriteLn('| | | (_) | (__| < '); WriteLn('|_| \___/ \___|_|\_\'); player := 0; End Else If playerinput = 'P' Then Begin WriteLn(' _ __ __ _ _ __ ___ _ __ '); WriteLn('| _ \ / _` | _ \ / _ \ __|'); WriteLn('| |_) | (_| | |_) | __/ | '); WriteLn('| .__/ \__,_| .__/ \___|_| '); WriteLn('| | | | '); WriteLn('|_| |_| '); player := 1; End Else If playerinput = 'S' Then Begin WriteLn(' _ '); WriteLn(' (_) '); WriteLn(' ___ ___ _ ___ ___ ___ _ __ ___ '); WriteLn('/ __|/ __| / __/ __|/ _ \| __/ __|'); WriteLn('\__ \ (__| \__ \__ \ (_) | | \__ \'); WriteLn('|___/\___|_|___/___/\___/|_| |___/'); player := 2; End; WriteLn(WinLoseDraw(player)); playCount := playCount + 1; End Else WriteLn('Try again'); Until playCount = 6; (* playCount := playCount - 1; *) WriteLn; WriteLn('You have played 5 times. Win: ', uwincount, ', Lose: ', cwincount, ', Draw: ', drawCount); WriteLn('Press any key to exit...'); ReadKey; End.
unit JPL.Win.Dialogs; interface uses Windows; { Information = Asterisks Warning = Exclamation Error = Hand = Stop } procedure WinMsg(const Text, Caption: string; Handle: HWND = 0; MBType: DWORD = MB_OK or MB_ICONINFORMATION); procedure MB(const Text: string; Caption: string = 'Information'; Handle: HWND = 0); procedure WinMsgInfo(Text: string; Caption: string = 'Information'; Handle: HWND = 0); procedure WinMsgWarning(Text: string; Caption: string = 'Warning'; Handle: HWND = 0); procedure WinMsgError(Text: string; Caption: string = 'Error'; Handle: HWND = 0); implementation procedure WinMsg(const Text, Caption: string; Handle: HWND = 0; MBType: DWORD = MB_OK or MB_ICONINFORMATION); begin MessageBox(Handle, PChar(Text), PChar(Caption), MBType); end; procedure MB(const Text: string; Caption: string = 'Information'; Handle: HWND = 0); begin WinMsgInfo(Text, Caption, Handle); end; procedure WinMsgInfo(Text: string; Caption: string = 'Information'; Handle: HWND = 0); begin WinMsg(Text, Caption, Handle, MB_OK or MB_ICONINFORMATION); end; procedure WinMsgWarning(Text: string; Caption: string = 'Warning'; Handle: HWND = 0); begin WinMsg(Text, Caption, Handle, MB_OK or MB_ICONWARNING); end; procedure WinMsgError(Text: string; Caption: string = 'Error'; Handle: HWND = 0); begin WinMsg(Text, Caption, Handle, MB_OK or MB_ICONERROR); end; end.
{ Module of routines that deal with tokens within a string. A token is * an individually parseable unit of a string. } module string_token; define string_token_anyd; define string_token; define string_token_comma; define string_token_commasp; define string_token_make; define string_token_bool; %include 'string2.ins.pas'; { ********************************************************************* * * STRING_TOKEN_ANYD (S, P, DELIM, N_DELIM, N_DELIM_REPT, FLAGS, * TOKEN, DELIM_PICK, STAT) * * Extract the next token from string S, and put the result into string TOKEN. * P is the parse index into string S. The first token at or after P is * returned. P is updated so that the next call to any of the STRING_TOKEN * routines will read the next token. * * Tokens are separated in S by delimiter characters. The list of legal * delimiter characters is given in DELIM. N_DELIM indicates the total * number of delimiters in DELIM. The first N_DELIM_REPT delimiters in * DELIM may be repeated, the remaining ones may only appear once between * tokens. DELIM_PICK is returned indicating which delimiter identified the * end of the token. DELIM_PICK always refers to the non-repeated delimiter, * if both repeated and non-repeated delimiters were present. DELIM_PICK * is returned zero when the end of S ended the token. * * FLAGS may be any combination of the following flags: * * STRING_TKOPT_QUOTEQ_K - The token may be a string enclosed in * quotes ("..."). TOKEN will be set to the characters between the * quotes. Two consecutive quotes within the string will be translated * as one quote. No additional characters are allowed after the last * quote. In other words, the last quote must be the last character * in the input string, or immediately followed by a delimiter. * * STRING_TKOPT_QUOTEA_K - Just like STRING_TKOPT_QUOTEQ_K, except * that the quote characters are apostrophies ('...'). * * STRING_TKOPT_PADSP_K - Blanks are padding. Leading and trailing * blanks around the token are stripped. This flag is only useful * when the blank characters is not listed in DELIM as one of the * token delimiters. } procedure string_token_anyd ( {like STRING_TOKEN, user supplies delimiters} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {parse index, init to 1 for start of string} in delim: univ string; {list of delimiters between tokens} in n_delim: sys_int_machine_t; {number of delimiters in DELIM} in n_delim_rept: sys_int_machine_t; {first N delimiters that may be repeated} in flags: string_tkopt_t; {set of option flags} out token: univ string_var_arg_t; {output token parsed from S} out delim_pick: sys_int_machine_t; {index to main delimeter ending token} out stat: sys_err_t); {completion status code} val_param; type parse_k_t = ( {current parsing state options} parse_lead_k, {in leading delimiters} parse_token_k, {reading token characters} parse_quote_k, {reading chars within quoted string token} parse_qend_k, {last character was ending quote} parse_trailp_k, {in trailing padding before delimiters} parse_trail_k); {in trailing delimiters} var i: sys_int_machine_t; {scratch integer and loop counter} npad: sys_int_machine_t; {number padding chars not appended to token} parse: parse_k_t; {current parsing state} c: char; {current character read from S} quote: char; {character to end quoted string} label char_next, char_again, err_afterq, got_trail_delim; begin sys_error_none (stat); {init to no error encountered} token.len := 0; {init returned token to empty} delim_pick := 0; {init to no trailing delimiter} parse := parse_lead_k; {init input string parsing state} npad := 0; {init to no pending pad characters} char_next: {back here for next input string char} if p > s.len then begin {no more characters left in input string ?} case parse of {some parsing states reqire special handling} parse_lead_k: begin {we never found any token characters} sys_stat_set (string_subsys_k, string_stat_eos_k, stat); end; parse_quote_k: begin {we were inside a quoted string} sys_stat_set (string_subsys_k, string_stat_no_endquote_k, stat); end; end; return; end; {done handling input string end encountered} c := s.str[p]; {fetch this input string character} p := p + 1; {update input string parse index} char_again: {jump here with new parse state, same char} case parse of {go to different code for each parse state} { * We are in repeatable delimiters before token. } parse_lead_k: begin if (string_tkopt_padsp_k in flags) and (c = ' ') {leading blank padding ?} then goto char_next; for i := 1 to n_delim_rept do begin {once for each repeatable delimiter} if c = delim[i] then goto char_next; {found another repeatable delimiter ?} end; if {check for token is quoted string} ((string_tkopt_quoteq_k in flags) and (c = '"')) or ((string_tkopt_quotea_k in flags) and (c = '''')) then begin parse := parse_quote_k; {we are now parsing a quoted string} quote := c; {save character that will end quote} goto char_next; {back and process next input character} end; parse := parse_token_k; {assume C is first token character} goto char_again; {re-evaluate this char with new parse mode} end; { * We are in non-quoted token. } parse_token_k: begin for i := 1 to n_delim do begin {once for each of the delimiters} if c = delim[i] then begin {C is a delimiter character ?} parse := parse_trail_k; {now in trailing delimiters after token} goto got_trail_delim; {go process trailing delimiter} end; end; {back and check next delimiter character} if (string_tkopt_padsp_k in flags) and (c = ' ') then begin {possible pad character ?} npad := npad + 1; goto char_next; end; for i := 1 to npad do begin {any previous pads were real token chars} string_append1 (token, ' '); end; npad := 0; {reset to no pending pad characters} string_append1 (token, c); {not delimiter, add to token} end; { * We are in quoted string token. QUOTE is the quote close character. } parse_quote_k: begin if c = quote then begin {found closing quote character ?} parse := parse_qend_k; {next char will be right after close quote} goto char_next; {back and process next input string char} end; string_append1 (token, c); {add character to token} end; { * C is the first character following the closing quote character. } parse_qend_k: begin if c = quote then begin {C is second of two consecutive quote chars ?} string_append1 (token, c); {two consecutive quotes translate as one} parse := parse_quote_k; {back to within quoted string} goto char_next; {back and process next input string char} end; for i := 1 to n_delim do begin {once for each of the delimiters} if c = delim[i] then begin {C is a delimiter character ?} parse := parse_trail_k; {now in trailing delimiters after token} goto got_trail_delim; {go process trailing delimiter} end; end; {back and check next delimiter character} if (string_tkopt_padsp_k in flags) and (c = ' ') then begin {trailing pad character ?} parse := parse_trailp_k; goto char_next; end; err_afterq: {illegal character found after closed quote} sys_stat_set ( {found illegal character after close quote} string_subsys_k, string_stat_after_quote_k, stat); sys_stat_parm_char (c, stat); {offending character} sys_stat_parm_int (p - 1, stat); {index of offending character} sys_stat_parm_vstr (s, stat); {string containing error} return; end; { * In trailing pad characters after token body but before ending delimiters. * This state is only possible if the token was quoted. } parse_trailp_k: begin for i := 1 to n_delim do begin {once for each of the delimiters} if c = delim[i] then begin {C is a delimiter character ?} parse := parse_trail_k; {now in trailing delimiters after token} goto got_trail_delim; {go process trailing delimiter} end; end; {back and check next delimiter character} if c = ' ' then goto char_next; {another pad character ?} goto err_afterq; {illegal character after closed quote} end; { * We are in trailing delimiters after token. At least one repeating delimiter * has already been found. } parse_trail_k: begin for i := 1 to n_delim do begin {once for each of the delimiters} if c = delim[i] then goto got_trail_delim; {C is a delimiter ?} end; {back and check C against next delimiter} if (string_tkopt_padsp_k in flags) and (c = ' ') then begin {trailing pad character ?} goto char_next; {skip this character} end; p := p - 1; {restart next time with this character} return; {return with only repeating trail delim found} got_trail_delim: {C is delimiter, I is DELIM index} if i > n_delim_rept then begin {this is a non-repeating delimiter ?} delim_pick := i; {indicate which delimiter ended token} return; end; if delim_pick = 0 then begin {no previous delimiter logged ?} delim_pick := i; {save index to first delimiter} end; end; { * Done handling the current character, advance to next. } end; {end of parse state cases} goto char_next; {back to process next input string character} end; { ********************************************************************* * * Subroutine STRING_TOKEN (S, P, TOKEN, STAT) * * Extract the next token from string S into TOKEN. This routine works * like STRING_TOKEN_ANYD, except that space is the only delimiter, and * strings within quotes ("...") and apostrophies ('...') are handled as * whole tokens. } procedure string_token ( {get next token from string, blank delimeters} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {parse index, init to 1 for start of string} out token: univ string_var_arg_t; {output token, null string after last token} out stat: sys_err_t); {completion status code} val_param; var i: sys_int_machine_t; begin string_token_anyd ( {parse token with arbitrary delimiters} s, {input string} p, {input string parse index, will be updated} ' ', {list of delimiter characters} 1, {total number of delimiters} 1, {number of repeating delimiters} [string_tkopt_quoteq_k, string_tkopt_quotea_k], {enable special quote handling} token, {returned token} i, {index of terminating delimiter (unused)} stat); {returned completion status code} end; { ********************************************************************* * * Subroutine STRING_TOKEN_COMMA (S, P, TOKEN, STAT) * * Extract the next token from string S into TOKEN. Tokens are only * delimited by commas, may be quoted, and may have leading and trailing * spaces which will be stripped. } procedure string_token_comma ( {like string_token, using blanks and commas} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {parse index, init to 1 for start of string} out token: univ string_var_arg_t; {output token} out stat: sys_err_t); {completion status code} val_param; var i: sys_int_machine_t; begin string_token_anyd ( {parse token with arbitrary delimiters} s, {input string} p, {input string parse index, will be updated} ',', {list of delimiter characters} 1, {total number of delimiters} 0, {number of repeating delimiters} [ string_tkopt_quoteq_k, {enable "" quotes} string_tkopt_quotea_k, {enable '' quotes} string_tkopt_padsp_k], {strip space padding characters} token, {returned token} i, {index of terminating delimiter (unused)} stat); {returned completion status code} end; { ********************************************************************* * * Subroutine STRING_TOKEN_COMMASP (S, P, TOKEN, STAT) * * Extract the next token from string S into TOKEN. A token is delimited by * a single comma or multiple spaces. Leading and trailing spaces surrouinding * the token will be stripped. } procedure string_token_commasp ( {get token, 1 comma or N blank delimiters} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {parse index, init to 1 for start of string} out token: univ string_var_arg_t; {output token} out stat: sys_err_t); {completion status code} val_param; var i: sys_int_machine_t; begin string_token_anyd ( {parse token with arbitrary delimiters} s, {input string} p, {input string parse index, will be updated} ' ,', 2, {list of delimiter characters} 1, {number of repeating delimiters} [ string_tkopt_quoteq_k, {enable "" quotes} string_tkopt_quotea_k], {enable '' quotes} token, {returned token} i, {index of terminating delimiter (unused)} stat); {returned completion status code} end; { ********************************************************************* * * Subroutine STRING_TOKEN_MAKE (STR, TK) * * Create a single parseable token from the input string STR. If * TK is surrounded with blanks and added to a string, then STRING_TOKEN * will parse it as one entity and return the value in STR. This works * regardless of whether STR contains, blanks, quotes, etc. TK may be * returned enclosed in quotes or apostrophies as approriate. In general, * as little modification to STR is made as possible in converting it to * a single token. } procedure string_token_make ( {make individual token from input string} in str: univ string_var_arg_t; {input string} in out tk: univ string_var_arg_t); {will be parsed as one token by STRING_TOKEN} val_param; type spch_k_t = ( {types of special characters we care about} spch_q1_k, {quote type 1, real quote} spch_q2_k, {quote type 2, apostrophie} spch_sp_k); {space} spch_t = set of spch_k_t; var i: sys_int_machine_t; {scratch integer and loop counter} spch: spch_t; {types of special chars in input string} c: char; q: char; {enclosing quote character} label nomod; begin if str.len <= 0 then begin {input string is empty ?} string_vstring (tk, '""', 2); return; end; { * Check for which type of special characters are present in the input * string. } spch := []; {init to no special characters present} for i := 1 to str.len do begin {scan the whole input string} c := str.str[i]; {fetch this input string character} if c = '"' then begin {found quote ?} spch := spch + [spch_q1_k]; next; end; if c = '''' then begin {found apostrophie ?} spch := spch + [spch_q2_k]; next; end; if c = ' ' then begin {found blank ?} spch := spch + [spch_sp_k]; end; end; {back to check next input string character} { * SPCH contains flags for each type of character in the input string that * we have to handle specially. * * Check for whether the input string can be passed back without modification. * This is only true if it contains no blanks and doesn't start with any kind * of quote. } if spch = [] then begin {no special characters at all to deal with ?} nomod: {jump here to pass back unmodified string} string_copy (str, tk); {pass back unmodified input string} return; end; if (str.str[1] <> '"') and (str.str[1] <> '''') and {doesn't start with a quote ?} (not (spch_sp_k in spch)) {doesn't contain any blanks ?} then goto nomod; { * The input string must be passed back as a quoted string. } if spch_q1_k in spch {decide which kind of quote to use} then begin {input string contains quote} if spch_q2_k in spch then q := '"' {both present, pick quote} else q := ''''; {pick the one not present} end else begin {no quote in input string} q := '"'; {pick quote} end ; string_vstring (tk, q, 1); {init output string with starting quote} for i := 1 to str.len do begin {once for each input string character} c := str.str[i]; {fetch this input string character} if c = q then begin {this is the quote char we are using ?} string_append1 (tk, c); {cause quote char to be written twice} end; if tk.len >= tk.max then return; {no room for another char in output string ?} tk.len := tk.len + 1; {one more char in output string} tk.str[tk.len] := c; {copy input string char to output string} end; {back for next input string char} string_append1 (tk, q); {add closing quote to output string} end; { ********************************************************************* * * Subroutine STRING_TOKEN_BOOL (S, P, FLAGS, T, STAT) * * Parse the next token from string S, convert it to a boolean value, and * return the result in T. P is the parse index into string S, and indicates * the first character of S to start looking for the token at. P is * updated so that the next call will find the next token. * * FLAGS selects which keywords are allowed to select the TRUE/FALSE values. * FLAGS can be any combination of the following: * * STRING_TFTYPE_TF_K - TRUE, FALSE * STRING_TFTYPE_YESNO_K - YES, NO * STRING_TFTYPE_ONOFF_K - ON, OFF * * The keywords are always case-insensitive. } procedure string_token_bool ( {parse token and convert to boolean} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {input string parse index, init to 1 at start} in flags: string_tftype_t; {selects which T/F types are allowed} out t: boolean; {TRUE: true, yes, on, FALSE: false, no, off} out stat: sys_err_t); {completion status code} val_param; var tk: string_var80_t; {the token} begin tk.max := size_char(tk.str); {init local var string} string_token (s, p, tk, stat); {parse the token into TK} if sys_error(stat) then return; string_t_bool ( {convert the token to a boolean value} tk, {input string} flags, {option flags} t, {returned boolean value} stat); end;
unit uCinemaFillHistoryProgress; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, aOPCCinema; const am_StartFill = wm_User+10; type TFillHistoryProgress = class(TForm) ProgressBar1: TProgressBar; bCancel: TButton; procedure FormActivate(Sender: TObject); procedure bCancelClick(Sender: TObject); private PressCancel:boolean; procedure AMStartFill(var Message:TMessage);message am_StartFill; procedure StartFill; public OPCCinema : TaOPCCinema; procedure FillHistory(var StopFill:boolean;Progress:integer); end; var FillHistoryProgress: TFillHistoryProgress; implementation {$R *.dfm} procedure TFillHistoryProgress.FillHistory(var StopFill: boolean; Progress: integer); begin ProgressBar1.Position := Progress; Application.ProcessMessages; //sleep(100); StopFill := PressCancel; end; procedure TFillHistoryProgress.bCancelClick(Sender: TObject); begin PressCancel := true; end; procedure TFillHistoryProgress.AMStartFill(var Message: TMessage); begin StartFill; end; procedure TFillHistoryProgress.FormActivate(Sender: TObject); begin StartFill; end; procedure TFillHistoryProgress.StartFill; var OldFHP:TFillHistoryEvent; begin if not Assigned(OPCCinema) then begin ModalResult := mrNone; exit; end; OldFHP := OPCCinema.OnFillHistory; try OPCCinema.OnFillHistory := FillHistory; OPCCinema.Active := true; finally OPCCinema.OnFillHistory := OldFHP; end; ModalResult := mrOk; PostMessage(Handle,WM_CLOSE,0,0); end; end.
unit PasRequestProcessor; interface uses IdCustomHTTPServer, System.SysUtils, IdContext, Winapi.Windows; type { *------------------------------------------------------------------------------ @author forDream @version 2015/12/19 1.0 Initial revision. @todo @comment ------------------------------------------------------------------------------- } TRequestProcessor = class(TObject) private alwaysDoOnCommand: Boolean; // 无论如何都调用onCommand方法 protected function innerRequested(requestUri: string; requestAction: string): Boolean; virtual; abstract; function onGet(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; virtual; function onPost(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; virtual; function onCommand(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; overload; virtual; property alwaysOnCommand: Boolean read alwaysDoOnCommand write alwaysDoOnCommand; public constructor Create; // 处理器是否处理该请求,处理返回true function requested(requestUri: string; requestAction: string): Boolean; // 是否传递给下一个处理器,中断处理链返回false function onCommand(context: TIdContext; requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; overload; end; implementation uses CnDebug, Vcl.Forms; constructor TRequestProcessor.Create; begin Self.alwaysDoOnCommand := False; end; function TRequestProcessor.requested(requestUri: string; requestAction: string): Boolean; begin Result := Self.innerRequested(requestUri, requestAction); if Result then begin CnDebugger.TraceMsgWithTag('Enter:Requested', Self.ClassName); CnDebugger.TraceMsg('Uri:' + requestUri); CnDebugger.TraceMsg('Action:' + requestAction); CnDebugger.TraceMsgWithTag('Leave:Requested', Self.ClassName); end; end; function TRequestProcessor.onCommand(context: TIdContext; requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; begin CnDebugger.TraceMsgWithTag('onCommand', Self.ClassName); CnDebugger.TraceMsg('Command:' + requestInfo.Command); if requestInfo.CommandType = hcGET then Result := Self.onGet(requestInfo, responseInfo) else if requestInfo.CommandType = hcPOST then Result := Self.onPost(requestInfo, responseInfo) else Result := Self.onCommand(requestInfo, responseInfo); // always invoked onCommand Method. if not(requestInfo.CommandType in [hcGET, hcPOST]) and Self.alwaysOnCommand then Result := Self.onCommand(requestInfo, responseInfo); CnDebugger.TraceMsgWithTag('onCommand', Self.ClassName); end; function TRequestProcessor.onGet(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; begin Result := True; end; function TRequestProcessor.onPost(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; begin Result := True; end; function TRequestProcessor.onCommand(requestInfo: TIdHTTPRequestInfo; responseInfo: TIdHTTPResponseInfo): Boolean; begin Result := True; end; end.
program arrayrecord; uses crt; type rec_buku = record kode_buku,judul_buku:String; jml_halaman:Integer; harga:double; end; // membuat array record arr_buku=array[1..6] of rec_buku; var buku:arr_buku; pil_menu,n,i:Integer; procedure tambahData(var buku:arr_buku); var kode:String; label ulang; begin WriteLn('---Tambah Data---'); inc(n); // input data user dan simpan kedaram array record ulang: Write('masukkan kode baru : ');ReadLn(kode); // validasi for i:=1 to n do begin if(kode=buku[i].kode_buku) then begin WriteLn('kode sudah digunakan ,ulangi'); goto ulang; end; end; buku[n].kode_buku:=kode; write('masukkan judul baru : ');ReadLn(buku[n].judul_buku); write('masukkan halaman baru : ');ReadLn(buku[n].jml_halaman); write('masukkan harga baru : ');ReadLn(buku[n].harga); end; procedure tampilkanData(var buku:arr_buku); begin writeln('-- Daftar buku ---'); WriteLn('no. kode Judul Buku Halaman Harga'); WriteLn('------------------------------------------'); for i:=1 to n do begin writeln(i:3,' ',buku[i].kode_buku:5,' ',buku[i].judul_buku:15,' ',buku[i].jml_halaman:12,' ',buku[i].harga:15:2); end; WriteLn('------------------------------------------'); end; procedure hapusData(var buku:arr_buku); var kode:string;indexData:integer;isFound:Boolean=false; begin writeln('---Hapus Data ---'); write('Masukkan kode buku yang akan dihapus =');readln(kode); // proses cari kode for i:=1 to n do begin if(kode = buku[i].kode_buku) then begin indexData:=i; isFound:=true; break; end; end; // jika ketemu lakukan penhapusan // dengan memajukan data untuk menumpuk data yang akan dihapus // kemudian jumlah data yang akan dikurang 1 if isFound then begin for i:=indexData to n do begin buku[i].kode_buku:=buku[i+1].kode_buku; buku[i].judul_buku:=buku[i+1].judul_buku; buku[i].jml_halaman:=buku[i+1].jml_halaman; buku[i].harga:=buku[i+1].harga; end; dec(n); WriteLn('data berhasil dihapus'); end else writeln('data tidak ditemukan'); end; procedure editData(var buku:arr_buku); var kode:string;indexData:integer;isFound:Boolean=false; begin writeln('-- edit Data ---'); write('Masukkan kode buku yang akan diubah : ');readln(kode); // cari kode buku for i:=1 to n do begin if kode=buku[i].kode_buku then begin indexData:=i; isFound:=true; break; end; end; // jika ketemu lakukan pengeditan if isFound then begin write('masukkan kode buku = ');readln(buku[indexData].kode_buku); write('masukkan judul buku = ');readln(buku[indexData].judul_buku); write('masukkan jumlah halaman = ');readln(buku[indexData].jml_halaman); write('masukkan harga = ');readln(buku[indexData].harga); writeln; writeln('data berhasil diubah'); end else WriteLn('data tidak ditemukan'); end; procedure cariData(buku:arr_buku); var kode:string;indexData:integer;isFound:Boolean=false; begin WriteLn('---Cari Data---'); write('Masukkan kode buku = ');readln(kode); // cari kode for i:=1 to n do begin if kode = buku[i].kode_buku then begin isFound:=true; indexData:=i; Break; end; end; if isFound then begin // tampilkan data writeln; writeln('Kode buku = ',buku[indexData].kode_buku); writeln('Judul buku = ',buku[indexData].judul_buku); writeln('Jumlah halaman = ',buku[indexData].jml_halaman); writeln('harga = ',buku[indexData].harga:0:2); end else WriteLn('data tidak ditemukan '); end; begin n:=0; repeat clrscr; WriteLn('Max data =',length(buku)); WriteLn('Jml Data sekarang =',n); WriteLn; writeln('masukkan pilih menu'); WriteLn('1. Tambah Data'); WriteLn('2.Tampilkan Data'); WriteLn('3.Hapus Data'); WriteLn('4.Ubah Data'); WriteLn('5.Cari Data'); WriteLn('0.Keluar'); write('Masukkan pilihan anda = ');readln(pil_menu); WriteLn; case pil_menu of 1:if n>=length(buku) then WriteLn('database penuh') else tambahData(buku); 2:if n=0 then WriteLn('database kosong') else tampilkanData(buku); 3:if n=0 then WriteLn('database kosong') else hapusData(buku); 4:if n=0 then WriteLn('database kosong') else editData(buku); 5:if n=0 then WriteLn('database kosong') else cariData(buku); 0:WriteLn('terimakasih') else WriteLn('input menu salah'); end; ReadLn; until (pil_menu = 0) end.
{******************************************************************************* Transpear XP Main Menu v1.0b (c) Transpear Software 2001 http://www.transpear.net email: kwestlake@yahoo.com Please read enclosed License.txt before continuing any further, you may also find some useful information in the Readme.txt. How to use it: XP Menu is really 2 menu systems in 1, by Turning the XP property on the menus will assume a XP style look. through turning it off you can you can use a Gradient for the Menu Bar. almost every single color used by the menu system can be customised by setting the appropriate value in the BarColors property. How Does it Work: Through using Owner Draw (see my website for links to some cool tutorials), Each TMenuItem's OwnerDraw handlers are set through overriding the standard Forms handler (This is dagerous to do, and can make applications unstable). ***** NOTE ***** If you find you IDE keeps behaving wierdly or crashing then find the XPMainMenu.create() and comment the Marked block out. then call ForceXPStyle() at the end of your forms OnCreate(). Please read all enclosed documentation BEFORE installing/using this software {******************************************************************************} unit XP_MainMenu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus,XP_PopUpMenu,XP_Utils,Extctrls; Type ttfXPMainMenu = class(TMainMenu) Private FBorder : Boolean; FColors : tfBarColors; FOriginalWndProc: TWndMethod; FakeImageList : TImageList; Procedure DrawItem(Sender: TObject; ACanvas: TCanvas;ARect: TRect; Selected: Boolean); procedure ExpandItemWidth(Sender: TObject; ACanvas: TCanvas; var Width,Height: Integer); Procedure DrawGlpyh(Item : TMenuItem; Canvas : TCanvas; Arect : TRect; Idx : Integer); Procedure DrawCaption(Item : TMenuItem; Canvas : TCanvas; Arect : TRect); Procedure DrawChecked(Item : TMenuItem; ACanvas : TCanvas; ARect : TRect); Procedure DrawTick(ACanvas : TCanvas; CheckedRect : TRect; Selected : Boolean); Procedure DrawXPItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); Procedure DrawStandardItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); Procedure MakeSubCustomDraw(SubMenu : TMenuItem); Public procedure ForceXPStyle; procedure WndProc(var Message: TMessage); virtual; procedure Notification(AComponent: TComponent;Operation: TOperation); override; constructor create(AOwner : TComponent); override; destructor destroy; override; Published Property BarColors:tfBarColors read FColors write fColors; Property XP_Border: Boolean read FBorder write FBorder default True; End; procedure Register; implementation {*****************************************************************************} {* Initialisation and Hooking Routines {*****************************************************************************} constructor ttfXPMainMenu.create(AOwner : TComponent); Begin inherited create(AOwner); FakeImageList:=TImageList.create(self); With FakeImageList Do // Image.Width is used to set the draw Begin // Coordinates, so if no image list Width:=16; // is present then we need a fake one Height:=16; End; Images:=FakeImageList; FColors:=tfBarColors.create; OwnerDraw := True; FBorder:=False; XP_Border:=True; OwnerDraw:=True; {-------- Comment the following block if your IDE keeps on crashing -----} if Owner is TCustomForm then begin FOriginalWndProc := TCustomForm(Owner).WindowProc; // Save the Window Handler TCustomForm(Owner).WindowProc := WndProc; // Hook in the new one .. end else raise EInvalidOperation.Create('Owner must be a form'); {--------- END BLOCK -------} ForceXPStyle; End; destructor ttfXPMainMenu.Destroy; Begin inherited Destroy; End; procedure ttfXPMainMenu.Notification(AComponent: TComponent;Operation: TOperation); Begin If (AComponent=Images) Then If (Operation=OpRemove) Then Images:=FakeImageList; // Ensure Fakelist is used .. Inherited Notification(AComponent,Operation); End; procedure ttfXPMainMenu.WndProc(var Message: TMessage); begin Try FOriginalWndProc(Message); // Make sure we process all other messages .. case Message.Msg of WM_INITMENUPOPUP,WM_ENTERMENULOOP: Begin // when Menu is called ForceXPStyle; // Ensure XP draw style End; End; except Application.HandleException(self); end; End; Procedure ttfXPMainMenu.MakeSubCustomDraw(SubMenu : TMenuItem); var i: Integer; begin if (SubMenu.Count > 0) then // Set all MenuItems and Iterate for SubMenus for i := 0 to SubMenu.Count-1 do begin SubMenu.Items[i].OnMeasureItem := ExpandItemWidth; SubMenu.Items[i].OnDrawItem := DrawItem; If SubMenu.Items[i].Count>0 Then MakeSubCustomDraw(SubMenu.Items[i]); end; End; procedure ttfXPMainMenu.ForceXPStyle; var count : Integer; Begin If Items.Count>0 Then // We only make Sub items custom drawn For Count:=0 To Items.Count-1 Do // Else it screws up the menu bar .. If Items[Count].Count>0 Then MakeSubCustomDraw(Items[Count]); End; {*****************************************************************************} {* Drawing and Measuring Functions .. {*****************************************************************************} procedure ttfXPMainMenu.ExpandItemWidth(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer); var MenuItem: TMenuItem; begin MenuItem := TMenuItem(Sender); Width := Width; if Trim(ShortCutToText(MenuItem.ShortCut)) <> '' then Width:=Width+(ACanvas.TextWidth(Trim(ShortCutToText(MenuItem.ShortCut))) div 2)-10; if MenuItem.Visible then Begin If (Sender as TMenuItem).Caption='-' then Height:=3 // Set height for Divider else If XP_Border Then height:=height+8; End; End; Procedure ttfXPMainMenu.DrawGlpyh(Item : TMenuItem; Canvas : TCanvas; Arect : TRect; Idx : Integer); Begin If (Item.Parent.SubMenuImages<>nil) Then Item.Parent.SubMenuImages.Draw(canvas,ARect.Left+4, ((Arect.Bottom+Arect.Top)-Images.Height) Div 2,Idx,True) Else Images.Draw(canvas,ARect.Left+4, ((Arect.Bottom+Arect.Top)-Images.Height) Div 2,Idx,True); End; Procedure ttfXPMainMenu.DrawCaption(Item : TMenuItem; Canvas : TCanvas; Arect : TRect); Var TextLeft : Integer; Caption : String; OldColor : TColor; AccelIdx : Integer; // Accelerator index, so we know were to draw the _ Begin SetBKMode( canvas.Handle, TRANSPARENT ); If Assigned(Images) Then TextLeft:=Images.Width+12+Arect.Left Else TextLeft:=Arect.Left+6; If Item.Caption='-' then // Draw the divider bar and exit .. Begin Canvas.Pen.Color:=$00ADAEAD; Canvas.MoveTo(TextLeft+4,Arect.Top+1); Canvas.LineTo(Arect.Right,Arect.Top+1); Exit; End; OldColor:=Canvas.Font.Color; If Not Item.Enabled Then Canvas.Font.Color:=clGray; Caption:=RemoveChar(Item.Caption,'&',AccelIdx); // Remove controls chars from caption canvas.TextOut(TextLeft+4, ((Arect.Bottom+Arect.Top)- canvas.TextHeight('H')) Div 2,Caption); if Trim(ShortCutToText(Item.ShortCut)) <> '' then // show Shortcut keys .. Begin TextLeft:=(ARect.Right-Arect.Left)- Canvas.TextWidth(Trim(ShortCutToText(Item.ShortCut))+'X')-4; canvas.TextOut(TextLeft, ((Arect.Bottom+Arect.Top)- canvas.TextHeight('H')) Div 2,Trim(ShortCutToText(Item.ShortCut))); Canvas.Font.Color:=OldColor; End; End; // Tick routine taken from XPMenu by Khaled Shagrouni .. http://www.shagrouni.com Procedure ttfXPMainMenu.DrawTick(ACanvas : TCanvas; CheckedRect : TRect; Selected : Boolean); var X1, X2: integer; begin IF Selected Then ACanvas.Pen.color := clWhite else ACanvas.Pen.color:=clBlack; ACanvas.Brush.Color := clWhite; ACanvas.Brush.Style := bsSolid; x1:= CheckedRect.Left + 1; x2 := CheckedRect.Top + 5; ACanvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 2; ACanvas.LineTo(x1, x2); x1:= CheckedRect.Left + 2; x2 := CheckedRect.Top + 5; ACanvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 3; ACanvas.LineTo(x1, x2); x1:= CheckedRect.Left + 2; x2 := CheckedRect.Top + 4; ACanvas.MoveTo(x1, x2); x1 := CheckedRect.Left + 5; x2 := CheckedRect.Bottom - 3; ACanvas.LineTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 3; ACanvas.MoveTo(x1, x2); x1:= CheckedRect.Right + 2; x2 := CheckedRect.Top - 1; ACanvas.LineTo(x1, x2); x1 := CheckedRect.Left + 4; x2 := CheckedRect.Bottom - 2; ACanvas.MoveTo(x1, x2); x1:= CheckedRect.Right - 2; x2 := CheckedRect.Top + 3; ACanvas.LineTo(x1, x2); end; Procedure ttfXPMainMenu.DrawChecked(Item : TMenuItem; ACanvas : TCanvas; ARect : TRect); Begin ACanvas.Brush.Color:=FColors.CheckBoxBackground; With Arect Do Begin ACanvas.FillRect(Rect(Left+2,Top+4,Left+22,Bottom-4)); If (Item.ImageIndex=-1) OR ((Images=FakeImageList) AND (Item.Parent.SubMenuImages=nil)) Then DrawTick(ACanvas,Rect(Left+2,Top+4,Left+20,Bottom-4),true); End; End; Procedure ttfXPMainMenu.DrawXPItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); Var Item : TMenuItem; InnerRect : TRect; TempCanvas : TBitmap; Begin TempCanvas := TBitmap.Create; // Create a intermediary canvas Item:=(Sender As TMenuItem); With TempCanvas Do Begin // give it the same dimensions as menu Item width:=ARect.Right; height:=ARect.Bottom; Canvas.font:=ACanvas.Font; Transparent:=true; ARect.Right:=ARect.Right+6; InnerRect:=ARect; dec(InnerRect.right,7); // Rect inside XP border Inc(InnerRect.top,2); dec(InnerRect.bottom,2); Case Selected Of True : Begin canvas.Brush.Color:=FColors.BackgroundColor; canvas.FillRect (ARect); canvas.Brush.Color:=FColors.IconBackground; Canvas.FillRect(Rect(ARect.Left,ARect.Top,ARect.Left+Images.Width+8,ARect.Bottom)); canvas.Font.Color:=FColors.FontHiLightColor; canvas.Brush.Color:=FColors.ItemGradientEnd; canvas.FillRect (InnerRect); End; False: Begin Canvas.font.Color:=FColors.FontNormalColor; canvas.Brush.Color:=FColors.BackgroundColor; canvas.FillRect (ARect); canvas.Brush.Color:=FColors.IconBackground; Canvas.FillRect(Rect(ARect.Left,ARect.Top,ARect.Left+24,ARect.Bottom)); End; End; If Item.Checked Then DrawChecked(item,Canvas,ARect); If Assigned(Images) Then DrawGlpyh(TMenuItem(Sender),Canvas,ARect,Item.ImageIndex); DrawCaption(Item,canvas,Arect); ACanvas.CopyRect(ARect,canvas,ARect); End; If (XP_Border) and (selected) then // Only Draw XP border on main canvas.. Begin ACanvas.Brush.Color:=FColors.XPBorderColor; ACanvas.FrameRect(InnerRect); End; ACanvas.Refresh; // Force an Update TempCanvas.Free; End; // Only called when XP Border is turned off, this Draw routine // lets the Hilight Bar have a gradient Procedure ttfXPMainMenu.DrawStandardItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); Var Item : TMenuItem; TmpRect : TRect; tmp : TBitmap; Begin tmp := TBitmap.Create; // Create a intermediary canvas tmp.width:=ARect.Right; tmp.height:=ARect.Bottom; tmp.Canvas.font:=ACanvas.Font; With Tmp Do Begin Item:=(Sender As TMenuItem); ARect.Right:=ARect.Right+6; Case Selected Of True : Begin tmp.canvas.Font.Color:=FColors.FontHilightColor; TmpRect:=ARect; if (Assigned(Images)) And (Images.Width>24) Then Inc(TmpRect.Left,20); HorizGradient(tmp.Canvas,TmpRect, FColors.ItemGradientStart,FColors.ItemGradientEnd); End; False: Begin tmp.Canvas.font.Color:=FColors.FontNormalColor; tmp.canvas.Brush.Color:=FColors.BackgroundColor; tmp.canvas.FillRect (ARect); End; End; If Item.Checked Then DrawChecked(item,Canvas,ARect); If Assigned(Images) Then DrawGlpyh(TMenuItem(Sender),Canvas,ARect,Item.ImageIndex); DrawCaption(Item,canvas,Arect); ACanvas.CopyRect(ARect,canvas,ARect); End; ACanvas.Refresh; tmp.Free; End; Procedure ttfXPMainMenu.DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean); Begin If XP_Border Then DrawXPItem(Sender,ACanvas,Arect,Selected) Else DrawStandardItem(Sender,ACanvas,Arect,Selected) End; procedure Register; begin RegisterComponents('Transpear XP', [ttfXPMainMenu]); end; end.
unit URepositorioEstado; interface uses UEstado , UPais , UCidade , UEntidade , URepositorioDB , URepositorioPais , SqlExpr ; type TRepositorioEstado = class (TRepositorioDB<TESTADO>) private FRepositorioPais: TRepositorioPais; public constructor Create; destructor Destroy; override; procedure AtribuiDBParaEntidade (const coESTADO: TESTADO); override; procedure AtribuiEntidadeParaDB (const coESTADO: TESTADO; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM , SysUtils ; {TRepositorioEstado} constructor TRepositorioEstado.Create; begin Inherited Create (TESTADO, TBL_ESTADO, FLD_ENTIDADE_ID, STR_ESTADO); FRepositorioPais := TRepositorioPais.Create; end; destructor TRepositorioEstado.Destroy; begin FreeAndNil(FRepositorioPais); inherited; end; procedure TRepositorioEstado.AtribuiDBParaEntidade(const coESTADO: TESTADO); begin inherited; with FSQLSelect do begin coESTADO.NOME := FieldByName(FLD_ESTADO_NOME).AsString; coESTADO.UF := FieldByName(FLD_ESTADO_UF).AsString; coESTADO.PAIS := TPAIS (FRepositorioPais.Retorna( FieldByName(FLD_ESTADO_PAIS_ID).AsInteger)); end; end; procedure TRepositorioEstado.AtribuiEntidadeParaDB( const coESTADO: TESTADO; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_ESTADO_NOME).AsString := coESTADO.NOME; ParamByName(FLD_ESTADO_UF).AsString := coESTADO.UF; ParamByName(FLD_ESTADO_PAIS_ID).AsInteger := coESTADO.PAIS.ID; end; end; end.
unit Unit5; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm5 = class(TForm) Label1: TLabel; Edit1: TEdit; Edit2: TEdit; Label2: TLabel; Label3: TLabel; Button1: TButton; Button2: TButton; Panel1: TPanel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form5: TForm5; implementation {$R *.dfm} procedure TForm5.Button1Click(Sender: TObject); var pessoas: real; peso: real; begin Panel1.Caption:= ' '; Panel1.Color:= clbtnface; if (edit1.text='') or (edit2.text='') then begin ShowMessage('O campo PESO e PESSOAS não podem ficar em branco!') end else begin pessoas:= strtofloat(edit1.text); peso:= strtofloat(edit2.text); if pessoas >= 6 then begin ShowMessage('Capacidade Excedida! Máximo permitido: 5 Pessoas.') end else begin Panel1.Caption:= 'Subindo!'; Panel1.Color:= clgreen end; if peso >= 531 then begin ShowMessage('Capacidade Excedida! Máximo permitido: 530Kg.') end else begin Panel1.Caption:= 'Subindo!'; Panel1.Color:= clgreen end; end; end; end.
{***********************************************************************************************************} { } { XML Data Binding } { } { Generated on: 13/01/2016 12:19:46 p.m. } { Generated from: D:\TM_UNIANDES_BPO\TRUNK\Aplicacion\GeneradorXML\Persistencia\PlanillasNomina.dtd } { Settings stored in: D:\TM_UNIANDES_BPO\TRUNK\Aplicacion\GeneradorXML\Persistencia\PlanillasNomina.xdb } { } {***********************************************************************************************************} unit PlanillasNomina; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLPLANILLA_NOMINAType = interface; IXMLContenidoType = interface; IXMLContenidoTypeList = interface; IXMLTipo_documentalType = interface; IXMLTitulo_documentoType = interface; IXMLAutor_emisorresponsableType = interface; IXMLClasificacion_accesoType = interface; IXMLFecha_creacionType = interface; IXMLFolio_electronicoType = interface; IXMLTema_asuntoType = interface; IXMLEstructuraType = interface; IXMLEstructuraTypeList = interface; IXMLDescripcionType = interface; IXMLFormatoType = interface; IXMLEstadoType = interface; IXMLProceso_administrativoType = interface; IXMLUnidad_administrativa_respType = interface; IXMLSerieType = interface; IXMLContextoType = interface; IXMLContextoTypeList = interface; IXMLJuridico_administrativoType = interface; IXMLTecnologicoType = interface; IXMLAutenticidadType = interface; IXMLDigitalizacionType = interface; IXMLIndicesType = interface; IXMLIndicesTypeList = interface; { IXMLPLANILLA_NOMINAType } IXMLPLANILLA_NOMINAType = interface(IXMLNode) ['{2A08C006-5CB2-4B3E-B6C7-22DBDDFBE96C}'] { Property Accessors } function Get_Contenido: IXMLContenidoTypeList; function Get_Estructura: IXMLEstructuraTypeList; function Get_Contexto: IXMLContextoTypeList; function Get_Indices: IXMLIndicesTypeList; { Methods & Properties } property Contenido: IXMLContenidoTypeList read Get_Contenido; property Estructura: IXMLEstructuraTypeList read Get_Estructura; property Contexto: IXMLContextoTypeList read Get_Contexto; property Indices: IXMLIndicesTypeList read Get_Indices; end; { IXMLContenidoType } IXMLContenidoType = interface(IXMLNode) ['{93DFE8C4-6A2F-46E7-8351-432F2CCB052E}'] { Property Accessors } function Get_Nombreimagen: UnicodeString; function Get_Periodo_nomina: UnicodeString; function Get_Tipo_documental: IXMLTipo_documentalType; function Get_Titulo_documento: IXMLTitulo_documentoType; function Get_Autor_emisorresponsable: IXMLAutor_emisorresponsableType; function Get_Clasificacion_acceso: IXMLClasificacion_accesoType; function Get_Fecha_creacion: IXMLFecha_creacionType; function Get_Folio_electronico: IXMLFolio_electronicoType; function Get_Tema_asunto: IXMLTema_asuntoType; function Get_Palabras_clave: UnicodeString; procedure Set_Nombreimagen(Value: UnicodeString); procedure Set_Periodo_nomina(Value: UnicodeString); procedure Set_Palabras_clave(Value: UnicodeString); { Methods & Properties } property Nombreimagen: UnicodeString read Get_Nombreimagen write Set_Nombreimagen; property Periodo_nomina: UnicodeString read Get_Periodo_nomina write Set_Periodo_nomina; property Tipo_documental: IXMLTipo_documentalType read Get_Tipo_documental; property Titulo_documento: IXMLTitulo_documentoType read Get_Titulo_documento; property Autor_emisorresponsable: IXMLAutor_emisorresponsableType read Get_Autor_emisorresponsable; property Clasificacion_acceso: IXMLClasificacion_accesoType read Get_Clasificacion_acceso; property Fecha_creacion: IXMLFecha_creacionType read Get_Fecha_creacion; property Folio_electronico: IXMLFolio_electronicoType read Get_Folio_electronico; property Tema_asunto: IXMLTema_asuntoType read Get_Tema_asunto; property Palabras_clave: UnicodeString read Get_Palabras_clave write Set_Palabras_clave; end; { IXMLContenidoTypeList } IXMLContenidoTypeList = interface(IXMLNodeCollection) ['{BEEED181-1DD8-4B71-A2F0-48BD48AC6E42}'] { Methods & Properties } function Add: IXMLContenidoType; function Insert(const Index: Integer): IXMLContenidoType; function Get_Item(Index: Integer): IXMLContenidoType; property Items[Index: Integer]: IXMLContenidoType read Get_Item; default; end; { IXMLTipo_documentalType } IXMLTipo_documentalType = interface(IXMLNode) ['{ADDA8B2E-B93B-4F53-8B1E-B3B03C3FA8A0}'] { Property Accessors } function Get_Seriedocumental: UnicodeString; procedure Set_Seriedocumental(Value: UnicodeString); { Methods & Properties } property Seriedocumental: UnicodeString read Get_Seriedocumental write Set_Seriedocumental; end; { IXMLTitulo_documentoType } IXMLTitulo_documentoType = interface(IXMLNode) ['{C6C5EB6D-92A8-48C5-8035-91659AB856E4}'] { Property Accessors } function Get_Titulodocumento: UnicodeString; procedure Set_Titulodocumento(Value: UnicodeString); { Methods & Properties } property Titulodocumento: UnicodeString read Get_Titulodocumento write Set_Titulodocumento; end; { IXMLAutor_emisorresponsableType } IXMLAutor_emisorresponsableType = interface(IXMLNode) ['{EC3DAA90-BADD-4528-9D84-4DFF10EC533D}'] { Property Accessors } function Get_Fondo: UnicodeString; function Get_Unidad_responsable: UnicodeString; procedure Set_Fondo(Value: UnicodeString); procedure Set_Unidad_responsable(Value: UnicodeString); { Methods & Properties } property Fondo: UnicodeString read Get_Fondo write Set_Fondo; property Unidad_responsable: UnicodeString read Get_Unidad_responsable write Set_Unidad_responsable; end; { IXMLClasificacion_accesoType } IXMLClasificacion_accesoType = interface(IXMLNode) ['{E1CE124E-71B9-4BC1-90E9-64359E4EDCA9}'] { Property Accessors } function Get_Nivel_acceso: UnicodeString; procedure Set_Nivel_acceso(Value: UnicodeString); { Methods & Properties } property Nivel_acceso: UnicodeString read Get_Nivel_acceso write Set_Nivel_acceso; end; { IXMLFecha_creacionType } IXMLFecha_creacionType = interface(IXMLNode) ['{42EBA0F5-7A60-404B-A97B-75FF9001C67D}'] { Property Accessors } function Get_Fechacreacion: UnicodeString; procedure Set_Fechacreacion(Value: UnicodeString); { Methods & Properties } property Fechacreacion: UnicodeString read Get_Fechacreacion write Set_Fechacreacion; end; { IXMLFolio_electronicoType } IXMLFolio_electronicoType = interface(IXMLNode) ['{56C95BA8-C4DE-4985-8C19-204655061737}'] { Property Accessors } function Get_Folios_totales: UnicodeString; function Get_Folio_actual: UnicodeString; procedure Set_Folios_totales(Value: UnicodeString); procedure Set_Folio_actual(Value: UnicodeString); { Methods & Properties } property Folios_totales: UnicodeString read Get_Folios_totales write Set_Folios_totales; property Folio_actual: UnicodeString read Get_Folio_actual write Set_Folio_actual; end; { IXMLTema_asuntoType } IXMLTema_asuntoType = interface(IXMLNode) ['{4F109865-3644-46EE-B2F3-C1142DBB69E4}'] { Property Accessors } function Get_Tema: UnicodeString; procedure Set_Tema(Value: UnicodeString); { Methods & Properties } property Tema: UnicodeString read Get_Tema write Set_Tema; end; { IXMLEstructuraType } IXMLEstructuraType = interface(IXMLNode) ['{82CDA3C2-7FA7-419D-9C45-DF8D311B0F77}'] { Property Accessors } function Get_Descripcion: IXMLDescripcionType; function Get_Formato: IXMLFormatoType; function Get_Estado: IXMLEstadoType; function Get_Proceso_administrativo: IXMLProceso_administrativoType; function Get_Unidad_administrativa_resp: IXMLUnidad_administrativa_respType; function Get_Perfil_autorizado: UnicodeString; function Get_Ubicacion: UnicodeString; function Get_Serie: IXMLSerieType; procedure Set_Perfil_autorizado(Value: UnicodeString); procedure Set_Ubicacion(Value: UnicodeString); { Methods & Properties } property Descripcion: IXMLDescripcionType read Get_Descripcion; property Formato: IXMLFormatoType read Get_Formato; property Estado: IXMLEstadoType read Get_Estado; property Proceso_administrativo: IXMLProceso_administrativoType read Get_Proceso_administrativo; property Unidad_administrativa_resp: IXMLUnidad_administrativa_respType read Get_Unidad_administrativa_resp; property Perfil_autorizado: UnicodeString read Get_Perfil_autorizado write Set_Perfil_autorizado; property Ubicacion: UnicodeString read Get_Ubicacion write Set_Ubicacion; property Serie: IXMLSerieType read Get_Serie; end; { IXMLEstructuraTypeList } IXMLEstructuraTypeList = interface(IXMLNodeCollection) ['{3DEC0B46-3580-491C-9DB1-8C8409629A30}'] { Methods & Properties } function Add: IXMLEstructuraType; function Insert(const Index: Integer): IXMLEstructuraType; function Get_Item(Index: Integer): IXMLEstructuraType; property Items[Index: Integer]: IXMLEstructuraType read Get_Item; default; end; { IXMLDescripcionType } IXMLDescripcionType = interface(IXMLNode) ['{4B48217B-ED2D-42CB-8918-780E60A4FEFF}'] { Property Accessors } function Get_Descripcion_: UnicodeString; procedure Set_Descripcion_(Value: UnicodeString); { Methods & Properties } property Descripcion_: UnicodeString read Get_Descripcion_ write Set_Descripcion_; end; { IXMLFormatoType } IXMLFormatoType = interface(IXMLNode) ['{B69470D6-8533-4DE1-87FB-56862CD9D6F4}'] { Property Accessors } function Get_Formato_: UnicodeString; procedure Set_Formato_(Value: UnicodeString); { Methods & Properties } property Formato_: UnicodeString read Get_Formato_ write Set_Formato_; end; { IXMLEstadoType } IXMLEstadoType = interface(IXMLNode) ['{AA5473F0-D9E1-4657-A6E9-691D8F4B9EC8}'] { Property Accessors } function Get_Estado_elaboracion: UnicodeString; procedure Set_Estado_elaboracion(Value: UnicodeString); { Methods & Properties } property Estado_elaboracion: UnicodeString read Get_Estado_elaboracion write Set_Estado_elaboracion; end; { IXMLProceso_administrativoType } IXMLProceso_administrativoType = interface(IXMLNode) ['{83C9329F-6CB8-4DC5-A52D-1E4C303D7ADB}'] { Property Accessors } function Get_Macroproceso: UnicodeString; function Get_Procesonivel1: UnicodeString; function Get_Procesonivel2: UnicodeString; procedure Set_Macroproceso(Value: UnicodeString); procedure Set_Procesonivel1(Value: UnicodeString); procedure Set_Procesonivel2(Value: UnicodeString); { Methods & Properties } property Macroproceso: UnicodeString read Get_Macroproceso write Set_Macroproceso; property Procesonivel1: UnicodeString read Get_Procesonivel1 write Set_Procesonivel1; property Procesonivel2: UnicodeString read Get_Procesonivel2 write Set_Procesonivel2; end; { IXMLUnidad_administrativa_respType } IXMLUnidad_administrativa_respType = interface(IXMLNode) ['{2FB8764D-1B8A-4EF3-A0D1-F9CACE15D921}'] { Property Accessors } function Get_Unidadadministrativaresp: UnicodeString; procedure Set_Unidadadministrativaresp(Value: UnicodeString); { Methods & Properties } property Unidadadministrativaresp: UnicodeString read Get_Unidadadministrativaresp write Set_Unidadadministrativaresp; end; { IXMLSerieType } IXMLSerieType = interface(IXMLNode) ['{50884E8B-28D7-482D-B470-7759B2D95FF6}'] { Property Accessors } function Get_Serie_: UnicodeString; function Get_Subserie: UnicodeString; procedure Set_Serie_(Value: UnicodeString); procedure Set_Subserie(Value: UnicodeString); { Methods & Properties } property Serie_: UnicodeString read Get_Serie_ write Set_Serie_; property Subserie: UnicodeString read Get_Subserie write Set_Subserie; end; { IXMLContextoType } IXMLContextoType = interface(IXMLNode) ['{249D93B0-AD40-4A2D-A1E1-274D6AAA4D3C}'] { Property Accessors } function Get_Juridico_administrativo: IXMLJuridico_administrativoType; function Get_Documental: UnicodeString; function Get_Procedencia: UnicodeString; function Get_Procedimental: UnicodeString; function Get_Tecnologico: IXMLTecnologicoType; function Get_Autenticidad: IXMLAutenticidadType; function Get_Digitalizacion: IXMLDigitalizacionType; function Get_Indices: IXMLIndicesType; procedure Set_Documental(Value: UnicodeString); procedure Set_Procedencia(Value: UnicodeString); procedure Set_Procedimental(Value: UnicodeString); { Methods & Properties } property Juridico_administrativo: IXMLJuridico_administrativoType read Get_Juridico_administrativo; property Documental: UnicodeString read Get_Documental write Set_Documental; property Procedencia: UnicodeString read Get_Procedencia write Set_Procedencia; property Procedimental: UnicodeString read Get_Procedimental write Set_Procedimental; property Tecnologico: IXMLTecnologicoType read Get_Tecnologico; property Autenticidad: IXMLAutenticidadType read Get_Autenticidad; property Digitalizacion: IXMLDigitalizacionType read Get_Digitalizacion; property Indices: IXMLIndicesType read Get_Indices; end; { IXMLContextoTypeList } IXMLContextoTypeList = interface(IXMLNodeCollection) ['{7BD7AD3A-8573-492A-B3E7-DD16BCE2CB6F}'] { Methods & Properties } function Add: IXMLContextoType; function Insert(const Index: Integer): IXMLContextoType; function Get_Item(Index: Integer): IXMLContextoType; property Items[Index: Integer]: IXMLContextoType read Get_Item; default; end; { IXMLJuridico_administrativoType } IXMLJuridico_administrativoType = interface(IXMLNode) ['{553AB99C-2466-4DF3-95B5-BA42DBCC7E2E}'] { Property Accessors } function Get_Valores_primarios: UnicodeString; function Get_Valores_secundarios: UnicodeString; procedure Set_Valores_primarios(Value: UnicodeString); procedure Set_Valores_secundarios(Value: UnicodeString); { Methods & Properties } property Valores_primarios: UnicodeString read Get_Valores_primarios write Set_Valores_primarios; property Valores_secundarios: UnicodeString read Get_Valores_secundarios write Set_Valores_secundarios; end; { IXMLTecnologicoType } IXMLTecnologicoType = interface(IXMLNode) ['{92D800AD-0816-4AA0-AD86-369BC7C5E6EC}'] { Property Accessors } function Get_Tecnologico_1: UnicodeString; function Get_Tipodefirma: UnicodeString; procedure Set_Tecnologico_1(Value: UnicodeString); procedure Set_Tipodefirma(Value: UnicodeString); { Methods & Properties } property Tecnologico_1: UnicodeString read Get_Tecnologico_1 write Set_Tecnologico_1; property Tipodefirma: UnicodeString read Get_Tipodefirma write Set_Tipodefirma; end; { IXMLAutenticidadType } IXMLAutenticidadType = interface(IXMLNode) ['{017ACF07-C14B-4CFB-B7F3-E654080599B7}'] { Property Accessors } function Get_Dominio_red: UnicodeString; function Get_Ip_usuario: UnicodeString; function Get_MAC_usuario: UnicodeString; procedure Set_Dominio_red(Value: UnicodeString); procedure Set_Ip_usuario(Value: UnicodeString); procedure Set_MAC_usuario(Value: UnicodeString); { Methods & Properties } property Dominio_red: UnicodeString read Get_Dominio_red write Set_Dominio_red; property Ip_usuario: UnicodeString read Get_Ip_usuario write Set_Ip_usuario; property MAC_usuario: UnicodeString read Get_MAC_usuario write Set_MAC_usuario; end; { IXMLDigitalizacionType } IXMLDigitalizacionType = interface(IXMLNode) ['{2A769403-043F-4010-86DA-CC3CC9EFA443}'] { Property Accessors } function Get_Procesado_por: UnicodeString; function Get_Fecha_digitalizacion: UnicodeString; function Get_Fecha_indexacion: UnicodeString; function Get_Resolucion: UnicodeString; function Get_Tamano: UnicodeString; function Get_Software_captura: UnicodeString; function Get_Color: UnicodeString; function Get_Compresion: UnicodeString; function Get_Folio_inicial: UnicodeString; function Get_Folio_final: UnicodeString; procedure Set_Procesado_por(Value: UnicodeString); procedure Set_Fecha_digitalizacion(Value: UnicodeString); procedure Set_Fecha_indexacion(Value: UnicodeString); procedure Set_Resolucion(Value: UnicodeString); procedure Set_Tamano(Value: UnicodeString); procedure Set_Software_captura(Value: UnicodeString); procedure Set_Color(Value: UnicodeString); procedure Set_Compresion(Value: UnicodeString); procedure Set_Folio_inicial(Value: UnicodeString); procedure Set_Folio_final(Value: UnicodeString); { Methods & Properties } property Procesado_por: UnicodeString read Get_Procesado_por write Set_Procesado_por; property Fecha_digitalizacion: UnicodeString read Get_Fecha_digitalizacion write Set_Fecha_digitalizacion; property Fecha_indexacion: UnicodeString read Get_Fecha_indexacion write Set_Fecha_indexacion; property Resolucion: UnicodeString read Get_Resolucion write Set_Resolucion; property Tamano: UnicodeString read Get_Tamano write Set_Tamano; property Software_captura: UnicodeString read Get_Software_captura write Set_Software_captura; property Color: UnicodeString read Get_Color write Set_Color; property Compresion: UnicodeString read Get_Compresion write Set_Compresion; property Folio_inicial: UnicodeString read Get_Folio_inicial write Set_Folio_inicial; property Folio_final: UnicodeString read Get_Folio_final write Set_Folio_final; end; { IXMLIndicesType } IXMLIndicesType = interface(IXMLNode) ['{34CF3218-BDAA-477E-BA0D-A9F671A8C402}'] { Property Accessors } function Get_Fecha_nomina: UnicodeString; function Get_Num_id: UnicodeString; function Get_Tipo: UnicodeString; function Get_Prim_apll: UnicodeString; function Get_Seg_apll: UnicodeString; function Get_Prim_nomb: UnicodeString; function Get_Seg_nomb: UnicodeString; procedure Set_Fecha_nomina(Value: UnicodeString); procedure Set_Num_id(Value: UnicodeString); procedure Set_Tipo(Value: UnicodeString); procedure Set_Prim_apll(Value: UnicodeString); procedure Set_Seg_apll(Value: UnicodeString); procedure Set_Prim_nomb(Value: UnicodeString); procedure Set_Seg_nomb(Value: UnicodeString); { Methods & Properties } property Fecha_nomina: UnicodeString read Get_Fecha_nomina write Set_Fecha_nomina; property Num_id: UnicodeString read Get_Num_id write Set_Num_id; property Tipo: UnicodeString read Get_Tipo write Set_Tipo; property Prim_apll: UnicodeString read Get_Prim_apll write Set_Prim_apll; property Seg_apll: UnicodeString read Get_Seg_apll write Set_Seg_apll; property Prim_nomb: UnicodeString read Get_Prim_nomb write Set_Prim_nomb; property Seg_nomb: UnicodeString read Get_Seg_nomb write Set_Seg_nomb; end; { IXMLIndicesTypeList } IXMLIndicesTypeList = interface(IXMLNodeCollection) ['{0F4F0F7F-9ED8-4E39-BE74-6F7A23452D1B}'] { Methods & Properties } function Add: IXMLIndicesType; function Insert(const Index: Integer): IXMLIndicesType; function Get_Item(Index: Integer): IXMLIndicesType; property Items[Index: Integer]: IXMLIndicesType read Get_Item; default; end; { Forward Decls } TXMLPLANILLA_NOMINAType = class; TXMLContenidoType = class; TXMLContenidoTypeList = class; TXMLTipo_documentalType = class; TXMLTitulo_documentoType = class; TXMLAutor_emisorresponsableType = class; TXMLClasificacion_accesoType = class; TXMLFecha_creacionType = class; TXMLFolio_electronicoType = class; TXMLTema_asuntoType = class; TXMLEstructuraType = class; TXMLEstructuraTypeList = class; TXMLDescripcionType = class; TXMLFormatoType = class; TXMLEstadoType = class; TXMLProceso_administrativoType = class; TXMLUnidad_administrativa_respType = class; TXMLSerieType = class; TXMLContextoType = class; TXMLContextoTypeList = class; TXMLJuridico_administrativoType = class; TXMLTecnologicoType = class; TXMLAutenticidadType = class; TXMLDigitalizacionType = class; TXMLIndicesType = class; TXMLIndicesTypeList = class; { TXMLPLANILLA_NOMINAType } TXMLPLANILLA_NOMINAType = class(TXMLNode, IXMLPLANILLA_NOMINAType) private FContenido: IXMLContenidoTypeList; FEstructura: IXMLEstructuraTypeList; FContexto: IXMLContextoTypeList; FIndices: IXMLIndicesTypeList; protected { IXMLPLANILLA_NOMINAType } function Get_Contenido: IXMLContenidoTypeList; function Get_Estructura: IXMLEstructuraTypeList; function Get_Contexto: IXMLContextoTypeList; function Get_Indices: IXMLIndicesTypeList; public procedure AfterConstruction; override; end; { TXMLContenidoType } TXMLContenidoType = class(TXMLNode, IXMLContenidoType) protected { IXMLContenidoType } function Get_Nombreimagen: UnicodeString; function Get_Periodo_nomina: UnicodeString; function Get_Tipo_documental: IXMLTipo_documentalType; function Get_Titulo_documento: IXMLTitulo_documentoType; function Get_Autor_emisorresponsable: IXMLAutor_emisorresponsableType; function Get_Clasificacion_acceso: IXMLClasificacion_accesoType; function Get_Fecha_creacion: IXMLFecha_creacionType; function Get_Folio_electronico: IXMLFolio_electronicoType; function Get_Tema_asunto: IXMLTema_asuntoType; function Get_Palabras_clave: UnicodeString; procedure Set_Nombreimagen(Value: UnicodeString); procedure Set_Periodo_nomina(Value: UnicodeString); procedure Set_Palabras_clave(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLContenidoTypeList } TXMLContenidoTypeList = class(TXMLNodeCollection, IXMLContenidoTypeList) protected { IXMLContenidoTypeList } function Add: IXMLContenidoType; function Insert(const Index: Integer): IXMLContenidoType; function Get_Item(Index: Integer): IXMLContenidoType; end; { TXMLTipo_documentalType } TXMLTipo_documentalType = class(TXMLNode, IXMLTipo_documentalType) protected { IXMLTipo_documentalType } function Get_Seriedocumental: UnicodeString; procedure Set_Seriedocumental(Value: UnicodeString); end; { TXMLTitulo_documentoType } TXMLTitulo_documentoType = class(TXMLNode, IXMLTitulo_documentoType) protected { IXMLTitulo_documentoType } function Get_Titulodocumento: UnicodeString; procedure Set_Titulodocumento(Value: UnicodeString); end; { TXMLAutor_emisorresponsableType } TXMLAutor_emisorresponsableType = class(TXMLNode, IXMLAutor_emisorresponsableType) protected { IXMLAutor_emisorresponsableType } function Get_Fondo: UnicodeString; function Get_Unidad_responsable: UnicodeString; procedure Set_Fondo(Value: UnicodeString); procedure Set_Unidad_responsable(Value: UnicodeString); end; { TXMLClasificacion_accesoType } TXMLClasificacion_accesoType = class(TXMLNode, IXMLClasificacion_accesoType) protected { IXMLClasificacion_accesoType } function Get_Nivel_acceso: UnicodeString; procedure Set_Nivel_acceso(Value: UnicodeString); end; { TXMLFecha_creacionType } TXMLFecha_creacionType = class(TXMLNode, IXMLFecha_creacionType) protected { IXMLFecha_creacionType } function Get_Fechacreacion: UnicodeString; procedure Set_Fechacreacion(Value: UnicodeString); end; { TXMLFolio_electronicoType } TXMLFolio_electronicoType = class(TXMLNode, IXMLFolio_electronicoType) protected { IXMLFolio_electronicoType } function Get_Folios_totales: UnicodeString; function Get_Folio_actual: UnicodeString; procedure Set_Folios_totales(Value: UnicodeString); procedure Set_Folio_actual(Value: UnicodeString); end; { TXMLTema_asuntoType } TXMLTema_asuntoType = class(TXMLNode, IXMLTema_asuntoType) protected { IXMLTema_asuntoType } function Get_Tema: UnicodeString; procedure Set_Tema(Value: UnicodeString); end; { TXMLEstructuraType } TXMLEstructuraType = class(TXMLNode, IXMLEstructuraType) protected { IXMLEstructuraType } function Get_Descripcion: IXMLDescripcionType; function Get_Formato: IXMLFormatoType; function Get_Estado: IXMLEstadoType; function Get_Proceso_administrativo: IXMLProceso_administrativoType; function Get_Unidad_administrativa_resp: IXMLUnidad_administrativa_respType; function Get_Perfil_autorizado: UnicodeString; function Get_Ubicacion: UnicodeString; function Get_Serie: IXMLSerieType; procedure Set_Perfil_autorizado(Value: UnicodeString); procedure Set_Ubicacion(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLEstructuraTypeList } TXMLEstructuraTypeList = class(TXMLNodeCollection, IXMLEstructuraTypeList) protected { IXMLEstructuraTypeList } function Add: IXMLEstructuraType; function Insert(const Index: Integer): IXMLEstructuraType; function Get_Item(Index: Integer): IXMLEstructuraType; end; { TXMLDescripcionType } TXMLDescripcionType = class(TXMLNode, IXMLDescripcionType) protected { IXMLDescripcionType } function Get_Descripcion_: UnicodeString; procedure Set_Descripcion_(Value: UnicodeString); end; { TXMLFormatoType } TXMLFormatoType = class(TXMLNode, IXMLFormatoType) protected { IXMLFormatoType } function Get_Formato_: UnicodeString; procedure Set_Formato_(Value: UnicodeString); end; { TXMLEstadoType } TXMLEstadoType = class(TXMLNode, IXMLEstadoType) protected { IXMLEstadoType } function Get_Estado_elaboracion: UnicodeString; procedure Set_Estado_elaboracion(Value: UnicodeString); end; { TXMLProceso_administrativoType } TXMLProceso_administrativoType = class(TXMLNode, IXMLProceso_administrativoType) protected { IXMLProceso_administrativoType } function Get_Macroproceso: UnicodeString; function Get_Procesonivel1: UnicodeString; function Get_Procesonivel2: UnicodeString; procedure Set_Macroproceso(Value: UnicodeString); procedure Set_Procesonivel1(Value: UnicodeString); procedure Set_Procesonivel2(Value: UnicodeString); end; { TXMLUnidad_administrativa_respType } TXMLUnidad_administrativa_respType = class(TXMLNode, IXMLUnidad_administrativa_respType) protected { IXMLUnidad_administrativa_respType } function Get_Unidadadministrativaresp: UnicodeString; procedure Set_Unidadadministrativaresp(Value: UnicodeString); end; { TXMLSerieType } TXMLSerieType = class(TXMLNode, IXMLSerieType) protected { IXMLSerieType } function Get_Serie_: UnicodeString; function Get_Subserie: UnicodeString; procedure Set_Serie_(Value: UnicodeString); procedure Set_Subserie(Value: UnicodeString); end; { TXMLContextoType } TXMLContextoType = class(TXMLNode, IXMLContextoType) protected { IXMLContextoType } function Get_Juridico_administrativo: IXMLJuridico_administrativoType; function Get_Documental: UnicodeString; function Get_Procedencia: UnicodeString; function Get_Procedimental: UnicodeString; function Get_Tecnologico: IXMLTecnologicoType; function Get_Autenticidad: IXMLAutenticidadType; function Get_Digitalizacion: IXMLDigitalizacionType; function Get_Indices: IXMLIndicesType; procedure Set_Documental(Value: UnicodeString); procedure Set_Procedencia(Value: UnicodeString); procedure Set_Procedimental(Value: UnicodeString); public procedure AfterConstruction; override; end; { TXMLContextoTypeList } TXMLContextoTypeList = class(TXMLNodeCollection, IXMLContextoTypeList) protected { IXMLContextoTypeList } function Add: IXMLContextoType; function Insert(const Index: Integer): IXMLContextoType; function Get_Item(Index: Integer): IXMLContextoType; end; { TXMLJuridico_administrativoType } TXMLJuridico_administrativoType = class(TXMLNode, IXMLJuridico_administrativoType) protected { IXMLJuridico_administrativoType } function Get_Valores_primarios: UnicodeString; function Get_Valores_secundarios: UnicodeString; procedure Set_Valores_primarios(Value: UnicodeString); procedure Set_Valores_secundarios(Value: UnicodeString); end; { TXMLTecnologicoType } TXMLTecnologicoType = class(TXMLNode, IXMLTecnologicoType) protected { IXMLTecnologicoType } function Get_Tecnologico_1: UnicodeString; function Get_Tipodefirma: UnicodeString; procedure Set_Tecnologico_1(Value: UnicodeString); procedure Set_Tipodefirma(Value: UnicodeString); end; { TXMLAutenticidadType } TXMLAutenticidadType = class(TXMLNode, IXMLAutenticidadType) protected { IXMLAutenticidadType } function Get_Dominio_red: UnicodeString; function Get_Ip_usuario: UnicodeString; function Get_MAC_usuario: UnicodeString; procedure Set_Dominio_red(Value: UnicodeString); procedure Set_Ip_usuario(Value: UnicodeString); procedure Set_MAC_usuario(Value: UnicodeString); end; { TXMLDigitalizacionType } TXMLDigitalizacionType = class(TXMLNode, IXMLDigitalizacionType) protected { IXMLDigitalizacionType } function Get_Procesado_por: UnicodeString; function Get_Fecha_digitalizacion: UnicodeString; function Get_Fecha_indexacion: UnicodeString; function Get_Resolucion: UnicodeString; function Get_Tamano: UnicodeString; function Get_Software_captura: UnicodeString; function Get_Color: UnicodeString; function Get_Compresion: UnicodeString; function Get_Folio_inicial: UnicodeString; function Get_Folio_final: UnicodeString; procedure Set_Procesado_por(Value: UnicodeString); procedure Set_Fecha_digitalizacion(Value: UnicodeString); procedure Set_Fecha_indexacion(Value: UnicodeString); procedure Set_Resolucion(Value: UnicodeString); procedure Set_Tamano(Value: UnicodeString); procedure Set_Software_captura(Value: UnicodeString); procedure Set_Color(Value: UnicodeString); procedure Set_Compresion(Value: UnicodeString); procedure Set_Folio_inicial(Value: UnicodeString); procedure Set_Folio_final(Value: UnicodeString); end; { TXMLIndicesType } TXMLIndicesType = class(TXMLNode, IXMLIndicesType) protected { IXMLIndicesType } function Get_Fecha_nomina: UnicodeString; function Get_Num_id: UnicodeString; function Get_Tipo: UnicodeString; function Get_Prim_apll: UnicodeString; function Get_Seg_apll: UnicodeString; function Get_Prim_nomb: UnicodeString; function Get_Seg_nomb: UnicodeString; procedure Set_Fecha_nomina(Value: UnicodeString); procedure Set_Num_id(Value: UnicodeString); procedure Set_Tipo(Value: UnicodeString); procedure Set_Prim_apll(Value: UnicodeString); procedure Set_Seg_apll(Value: UnicodeString); procedure Set_Prim_nomb(Value: UnicodeString); procedure Set_Seg_nomb(Value: UnicodeString); end; { TXMLIndicesTypeList } TXMLIndicesTypeList = class(TXMLNodeCollection, IXMLIndicesTypeList) protected { IXMLIndicesTypeList } function Add: IXMLIndicesType; function Insert(const Index: Integer): IXMLIndicesType; function Get_Item(Index: Integer): IXMLIndicesType; end; { Global Functions } function GetPLANILLA_NOMINA(Doc: IXMLDocument): IXMLPLANILLA_NOMINAType; function LoadPLANILLA_NOMINA(const FileName: string): IXMLPLANILLA_NOMINAType; function NewPLANILLA_NOMINA: IXMLPLANILLA_NOMINAType; const TargetNamespace = ''; implementation { Global Functions } function GetPLANILLA_NOMINA(Doc: IXMLDocument): IXMLPLANILLA_NOMINAType; begin Result := Doc.GetDocBinding('PLANILLA_NOMINA', TXMLPLANILLA_NOMINAType, TargetNamespace) as IXMLPLANILLA_NOMINAType; end; function LoadPLANILLA_NOMINA(const FileName: string): IXMLPLANILLA_NOMINAType; begin Result := LoadXMLDocument(FileName).GetDocBinding('PLANILLA_NOMINA', TXMLPLANILLA_NOMINAType, TargetNamespace) as IXMLPLANILLA_NOMINAType; end; function NewPLANILLA_NOMINA: IXMLPLANILLA_NOMINAType; begin Result := NewXMLDocument.GetDocBinding('PLANILLA_NOMINA', TXMLPLANILLA_NOMINAType, TargetNamespace) as IXMLPLANILLA_NOMINAType; end; { TXMLPLANILLA_NOMINAType } procedure TXMLPLANILLA_NOMINAType.AfterConstruction; begin RegisterChildNode('contenido', TXMLContenidoType); RegisterChildNode('estructura', TXMLEstructuraType); RegisterChildNode('contexto', TXMLContextoType); RegisterChildNode('indices', TXMLIndicesType); FContenido := CreateCollection(TXMLContenidoTypeList, IXMLContenidoType, 'contenido') as IXMLContenidoTypeList; FEstructura := CreateCollection(TXMLEstructuraTypeList, IXMLEstructuraType, 'estructura') as IXMLEstructuraTypeList; FContexto := CreateCollection(TXMLContextoTypeList, IXMLContextoType, 'contexto') as IXMLContextoTypeList; FIndices := CreateCollection(TXMLIndicesTypeList, IXMLIndicesType, 'indices') as IXMLIndicesTypeList; inherited; end; function TXMLPLANILLA_NOMINAType.Get_Contenido: IXMLContenidoTypeList; begin Result := FContenido; end; function TXMLPLANILLA_NOMINAType.Get_Estructura: IXMLEstructuraTypeList; begin Result := FEstructura; end; function TXMLPLANILLA_NOMINAType.Get_Contexto: IXMLContextoTypeList; begin Result := FContexto; end; function TXMLPLANILLA_NOMINAType.Get_Indices: IXMLIndicesTypeList; begin Result := FIndices; end; { TXMLContenidoType } procedure TXMLContenidoType.AfterConstruction; begin RegisterChildNode('tipo_documental', TXMLTipo_documentalType); RegisterChildNode('titulo_documento', TXMLTitulo_documentoType); RegisterChildNode('autor_emisorresponsable', TXMLAutor_emisorresponsableType); RegisterChildNode('clasificacion_acceso', TXMLClasificacion_accesoType); RegisterChildNode('fecha_creacion', TXMLFecha_creacionType); RegisterChildNode('folio_electronico', TXMLFolio_electronicoType); RegisterChildNode('tema_asunto', TXMLTema_asuntoType); inherited; end; function TXMLContenidoType.Get_Nombreimagen: UnicodeString; begin Result := ChildNodes['nombreimagen'].Text; end; procedure TXMLContenidoType.Set_Nombreimagen(Value: UnicodeString); begin ChildNodes['nombreimagen'].NodeValue := Value; end; function TXMLContenidoType.Get_Periodo_nomina: UnicodeString; begin Result := ChildNodes['periodo_nomina'].Text; end; procedure TXMLContenidoType.Set_Periodo_nomina(Value: UnicodeString); begin ChildNodes['periodo_nomina'].NodeValue := Value; end; function TXMLContenidoType.Get_Tipo_documental: IXMLTipo_documentalType; begin Result := ChildNodes['tipo_documental'] as IXMLTipo_documentalType; end; function TXMLContenidoType.Get_Titulo_documento: IXMLTitulo_documentoType; begin Result := ChildNodes['titulo_documento'] as IXMLTitulo_documentoType; end; function TXMLContenidoType.Get_Autor_emisorresponsable: IXMLAutor_emisorresponsableType; begin Result := ChildNodes['autor_emisorresponsable'] as IXMLAutor_emisorresponsableType; end; function TXMLContenidoType.Get_Clasificacion_acceso: IXMLClasificacion_accesoType; begin Result := ChildNodes['clasificacion_acceso'] as IXMLClasificacion_accesoType; end; function TXMLContenidoType.Get_Fecha_creacion: IXMLFecha_creacionType; begin Result := ChildNodes['fecha_creacion'] as IXMLFecha_creacionType; end; function TXMLContenidoType.Get_Folio_electronico: IXMLFolio_electronicoType; begin Result := ChildNodes['folio_electronico'] as IXMLFolio_electronicoType; end; function TXMLContenidoType.Get_Tema_asunto: IXMLTema_asuntoType; begin Result := ChildNodes['tema_asunto'] as IXMLTema_asuntoType; end; function TXMLContenidoType.Get_Palabras_clave: UnicodeString; begin Result := ChildNodes['palabras_clave'].Text; end; procedure TXMLContenidoType.Set_Palabras_clave(Value: UnicodeString); begin ChildNodes['palabras_clave'].NodeValue := Value; end; { TXMLContenidoTypeList } function TXMLContenidoTypeList.Add: IXMLContenidoType; begin Result := AddItem(-1) as IXMLContenidoType; end; function TXMLContenidoTypeList.Insert(const Index: Integer): IXMLContenidoType; begin Result := AddItem(Index) as IXMLContenidoType; end; function TXMLContenidoTypeList.Get_Item(Index: Integer): IXMLContenidoType; begin Result := List[Index] as IXMLContenidoType; end; { TXMLTipo_documentalType } function TXMLTipo_documentalType.Get_Seriedocumental: UnicodeString; begin Result := ChildNodes['seriedocumental'].Text; end; procedure TXMLTipo_documentalType.Set_Seriedocumental(Value: UnicodeString); begin ChildNodes['seriedocumental'].NodeValue := Value; end; { TXMLTitulo_documentoType } function TXMLTitulo_documentoType.Get_Titulodocumento: UnicodeString; begin Result := ChildNodes['titulodocumento'].Text; end; procedure TXMLTitulo_documentoType.Set_Titulodocumento(Value: UnicodeString); begin ChildNodes['titulodocumento'].NodeValue := Value; end; { TXMLAutor_emisorresponsableType } function TXMLAutor_emisorresponsableType.Get_Fondo: UnicodeString; begin Result := ChildNodes['fondo'].Text; end; procedure TXMLAutor_emisorresponsableType.Set_Fondo(Value: UnicodeString); begin ChildNodes['fondo'].NodeValue := Value; end; function TXMLAutor_emisorresponsableType.Get_Unidad_responsable: UnicodeString; begin Result := ChildNodes['unidad_responsable'].Text; end; procedure TXMLAutor_emisorresponsableType.Set_Unidad_responsable(Value: UnicodeString); begin ChildNodes['unidad_responsable'].NodeValue := Value; end; { TXMLClasificacion_accesoType } function TXMLClasificacion_accesoType.Get_Nivel_acceso: UnicodeString; begin Result := ChildNodes['nivel_acceso'].Text; end; procedure TXMLClasificacion_accesoType.Set_Nivel_acceso(Value: UnicodeString); begin ChildNodes['nivel_acceso'].NodeValue := Value; end; { TXMLFecha_creacionType } function TXMLFecha_creacionType.Get_Fechacreacion: UnicodeString; begin Result := ChildNodes['fechacreacion'].Text; end; procedure TXMLFecha_creacionType.Set_Fechacreacion(Value: UnicodeString); begin ChildNodes['fechacreacion'].NodeValue := Value; end; { TXMLFolio_electronicoType } function TXMLFolio_electronicoType.Get_Folios_totales: UnicodeString; begin Result := ChildNodes['folios_totales'].Text; end; procedure TXMLFolio_electronicoType.Set_Folios_totales(Value: UnicodeString); begin ChildNodes['folios_totales'].NodeValue := Value; end; function TXMLFolio_electronicoType.Get_Folio_actual: UnicodeString; begin Result := ChildNodes['folio_actual'].Text; end; procedure TXMLFolio_electronicoType.Set_Folio_actual(Value: UnicodeString); begin ChildNodes['folio_actual'].NodeValue := Value; end; { TXMLTema_asuntoType } function TXMLTema_asuntoType.Get_Tema: UnicodeString; begin Result := ChildNodes['tema'].Text; end; procedure TXMLTema_asuntoType.Set_Tema(Value: UnicodeString); begin ChildNodes['tema'].NodeValue := Value; end; { TXMLEstructuraType } procedure TXMLEstructuraType.AfterConstruction; begin RegisterChildNode('descripcion', TXMLDescripcionType); RegisterChildNode('formato', TXMLFormatoType); RegisterChildNode('estado', TXMLEstadoType); RegisterChildNode('proceso_administrativo', TXMLProceso_administrativoType); RegisterChildNode('unidad_administrativa_resp', TXMLUnidad_administrativa_respType); RegisterChildNode('serie', TXMLSerieType); inherited; end; function TXMLEstructuraType.Get_Descripcion: IXMLDescripcionType; begin Result := ChildNodes['descripcion'] as IXMLDescripcionType; end; function TXMLEstructuraType.Get_Formato: IXMLFormatoType; begin Result := ChildNodes['formato'] as IXMLFormatoType; end; function TXMLEstructuraType.Get_Estado: IXMLEstadoType; begin Result := ChildNodes['estado'] as IXMLEstadoType; end; function TXMLEstructuraType.Get_Proceso_administrativo: IXMLProceso_administrativoType; begin Result := ChildNodes['proceso_administrativo'] as IXMLProceso_administrativoType; end; function TXMLEstructuraType.Get_Unidad_administrativa_resp: IXMLUnidad_administrativa_respType; begin Result := ChildNodes['unidad_administrativa_resp'] as IXMLUnidad_administrativa_respType; end; function TXMLEstructuraType.Get_Perfil_autorizado: UnicodeString; begin Result := ChildNodes['perfil_autorizado'].Text; end; procedure TXMLEstructuraType.Set_Perfil_autorizado(Value: UnicodeString); begin ChildNodes['perfil_autorizado'].NodeValue := Value; end; function TXMLEstructuraType.Get_Ubicacion: UnicodeString; begin Result := ChildNodes['ubicacion'].Text; end; procedure TXMLEstructuraType.Set_Ubicacion(Value: UnicodeString); begin ChildNodes['ubicacion'].NodeValue := Value; end; function TXMLEstructuraType.Get_Serie: IXMLSerieType; begin Result := ChildNodes['serie'] as IXMLSerieType; end; { TXMLEstructuraTypeList } function TXMLEstructuraTypeList.Add: IXMLEstructuraType; begin Result := AddItem(-1) as IXMLEstructuraType; end; function TXMLEstructuraTypeList.Insert(const Index: Integer): IXMLEstructuraType; begin Result := AddItem(Index) as IXMLEstructuraType; end; function TXMLEstructuraTypeList.Get_Item(Index: Integer): IXMLEstructuraType; begin Result := List[Index] as IXMLEstructuraType; end; { TXMLDescripcionType } function TXMLDescripcionType.Get_Descripcion_: UnicodeString; begin Result := ChildNodes['descripcion_'].Text; end; procedure TXMLDescripcionType.Set_Descripcion_(Value: UnicodeString); begin ChildNodes['descripcion_'].NodeValue := Value; end; { TXMLFormatoType } function TXMLFormatoType.Get_Formato_: UnicodeString; begin Result := ChildNodes['formato_'].Text; end; procedure TXMLFormatoType.Set_Formato_(Value: UnicodeString); begin ChildNodes['formato_'].NodeValue := Value; end; { TXMLEstadoType } function TXMLEstadoType.Get_Estado_elaboracion: UnicodeString; begin Result := ChildNodes['estado_elaboracion'].Text; end; procedure TXMLEstadoType.Set_Estado_elaboracion(Value: UnicodeString); begin ChildNodes['estado_elaboracion'].NodeValue := Value; end; { TXMLProceso_administrativoType } function TXMLProceso_administrativoType.Get_Macroproceso: UnicodeString; begin Result := ChildNodes['macroproceso'].Text; end; procedure TXMLProceso_administrativoType.Set_Macroproceso(Value: UnicodeString); begin ChildNodes['macroproceso'].NodeValue := Value; end; function TXMLProceso_administrativoType.Get_Procesonivel1: UnicodeString; begin Result := ChildNodes['procesonivel1'].Text; end; procedure TXMLProceso_administrativoType.Set_Procesonivel1(Value: UnicodeString); begin ChildNodes['procesonivel1'].NodeValue := Value; end; function TXMLProceso_administrativoType.Get_Procesonivel2: UnicodeString; begin Result := ChildNodes['procesonivel2'].Text; end; procedure TXMLProceso_administrativoType.Set_Procesonivel2(Value: UnicodeString); begin ChildNodes['procesonivel2'].NodeValue := Value; end; { TXMLUnidad_administrativa_respType } function TXMLUnidad_administrativa_respType.Get_Unidadadministrativaresp: UnicodeString; begin Result := ChildNodes['unidadadministrativaresp'].Text; end; procedure TXMLUnidad_administrativa_respType.Set_Unidadadministrativaresp(Value: UnicodeString); begin ChildNodes['unidadadministrativaresp'].NodeValue := Value; end; { TXMLSerieType } function TXMLSerieType.Get_Serie_: UnicodeString; begin Result := ChildNodes['serie_'].Text; end; procedure TXMLSerieType.Set_Serie_(Value: UnicodeString); begin ChildNodes['serie_'].NodeValue := Value; end; function TXMLSerieType.Get_Subserie: UnicodeString; begin Result := ChildNodes['subserie'].Text; end; procedure TXMLSerieType.Set_Subserie(Value: UnicodeString); begin ChildNodes['subserie'].NodeValue := Value; end; { TXMLContextoType } procedure TXMLContextoType.AfterConstruction; begin RegisterChildNode('juridico_administrativo', TXMLJuridico_administrativoType); RegisterChildNode('tecnologico', TXMLTecnologicoType); RegisterChildNode('autenticidad', TXMLAutenticidadType); RegisterChildNode('digitalizacion', TXMLDigitalizacionType); RegisterChildNode('indices', TXMLIndicesType); inherited; end; function TXMLContextoType.Get_Juridico_administrativo: IXMLJuridico_administrativoType; begin Result := ChildNodes['juridico_administrativo'] as IXMLJuridico_administrativoType; end; function TXMLContextoType.Get_Documental: UnicodeString; begin Result := ChildNodes['documental'].Text; end; procedure TXMLContextoType.Set_Documental(Value: UnicodeString); begin ChildNodes['documental'].NodeValue := Value; end; function TXMLContextoType.Get_Procedencia: UnicodeString; begin Result := ChildNodes['procedencia'].Text; end; procedure TXMLContextoType.Set_Procedencia(Value: UnicodeString); begin ChildNodes['procedencia'].NodeValue := Value; end; function TXMLContextoType.Get_Procedimental: UnicodeString; begin Result := ChildNodes['procedimental'].Text; end; procedure TXMLContextoType.Set_Procedimental(Value: UnicodeString); begin ChildNodes['procedimental'].NodeValue := Value; end; function TXMLContextoType.Get_Tecnologico: IXMLTecnologicoType; begin Result := ChildNodes['tecnologico'] as IXMLTecnologicoType; end; function TXMLContextoType.Get_Autenticidad: IXMLAutenticidadType; begin Result := ChildNodes['autenticidad'] as IXMLAutenticidadType; end; function TXMLContextoType.Get_Digitalizacion: IXMLDigitalizacionType; begin Result := ChildNodes['digitalizacion'] as IXMLDigitalizacionType; end; function TXMLContextoType.Get_Indices: IXMLIndicesType; begin Result := ChildNodes['indices'] as IXMLIndicesType; end; { TXMLContextoTypeList } function TXMLContextoTypeList.Add: IXMLContextoType; begin Result := AddItem(-1) as IXMLContextoType; end; function TXMLContextoTypeList.Insert(const Index: Integer): IXMLContextoType; begin Result := AddItem(Index) as IXMLContextoType; end; function TXMLContextoTypeList.Get_Item(Index: Integer): IXMLContextoType; begin Result := List[Index] as IXMLContextoType; end; { TXMLJuridico_administrativoType } function TXMLJuridico_administrativoType.Get_Valores_primarios: UnicodeString; begin Result := ChildNodes['valores_primarios'].Text; end; procedure TXMLJuridico_administrativoType.Set_Valores_primarios(Value: UnicodeString); begin ChildNodes['valores_primarios'].NodeValue := Value; end; function TXMLJuridico_administrativoType.Get_Valores_secundarios: UnicodeString; begin Result := ChildNodes['valores_secundarios'].Text; end; procedure TXMLJuridico_administrativoType.Set_Valores_secundarios(Value: UnicodeString); begin ChildNodes['valores_secundarios'].NodeValue := Value; end; { TXMLTecnologicoType } function TXMLTecnologicoType.Get_Tecnologico_1: UnicodeString; begin Result := ChildNodes['tecnologico_1'].Text; end; procedure TXMLTecnologicoType.Set_Tecnologico_1(Value: UnicodeString); begin ChildNodes['tecnologico_1'].NodeValue := Value; end; function TXMLTecnologicoType.Get_Tipodefirma: UnicodeString; begin Result := ChildNodes['tipodefirma'].Text; end; procedure TXMLTecnologicoType.Set_Tipodefirma(Value: UnicodeString); begin ChildNodes['tipodefirma'].NodeValue := Value; end; { TXMLAutenticidadType } function TXMLAutenticidadType.Get_Dominio_red: UnicodeString; begin Result := ChildNodes['dominio_red'].Text; end; procedure TXMLAutenticidadType.Set_Dominio_red(Value: UnicodeString); begin ChildNodes['dominio_red'].NodeValue := Value; end; function TXMLAutenticidadType.Get_Ip_usuario: UnicodeString; begin Result := ChildNodes['ip_usuario'].Text; end; procedure TXMLAutenticidadType.Set_Ip_usuario(Value: UnicodeString); begin ChildNodes['ip_usuario'].NodeValue := Value; end; function TXMLAutenticidadType.Get_MAC_usuario: UnicodeString; begin Result := ChildNodes['MAC_usuario'].Text; end; procedure TXMLAutenticidadType.Set_MAC_usuario(Value: UnicodeString); begin ChildNodes['MAC_usuario'].NodeValue := Value; end; { TXMLDigitalizacionType } function TXMLDigitalizacionType.Get_Procesado_por: UnicodeString; begin Result := ChildNodes['procesado_por'].Text; end; procedure TXMLDigitalizacionType.Set_Procesado_por(Value: UnicodeString); begin ChildNodes['procesado_por'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Fecha_digitalizacion: UnicodeString; begin Result := ChildNodes['fecha_digitalizacion'].Text; end; procedure TXMLDigitalizacionType.Set_Fecha_digitalizacion(Value: UnicodeString); begin ChildNodes['fecha_digitalizacion'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Fecha_indexacion: UnicodeString; begin Result := ChildNodes['fecha_indexacion'].Text; end; procedure TXMLDigitalizacionType.Set_Fecha_indexacion(Value: UnicodeString); begin ChildNodes['fecha_indexacion'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Resolucion: UnicodeString; begin Result := ChildNodes['resolucion'].Text; end; procedure TXMLDigitalizacionType.Set_Resolucion(Value: UnicodeString); begin ChildNodes['resolucion'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Tamano: UnicodeString; begin Result := ChildNodes['tamano'].Text; end; procedure TXMLDigitalizacionType.Set_Tamano(Value: UnicodeString); begin ChildNodes['tamano'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Software_captura: UnicodeString; begin Result := ChildNodes['software_captura'].Text; end; procedure TXMLDigitalizacionType.Set_Software_captura(Value: UnicodeString); begin ChildNodes['software_captura'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Color: UnicodeString; begin Result := ChildNodes['color'].Text; end; procedure TXMLDigitalizacionType.Set_Color(Value: UnicodeString); begin ChildNodes['color'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Compresion: UnicodeString; begin Result := ChildNodes['compresion'].Text; end; procedure TXMLDigitalizacionType.Set_Compresion(Value: UnicodeString); begin ChildNodes['compresion'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Folio_inicial: UnicodeString; begin Result := ChildNodes['folio_inicial'].Text; end; procedure TXMLDigitalizacionType.Set_Folio_inicial(Value: UnicodeString); begin ChildNodes['folio_inicial'].NodeValue := Value; end; function TXMLDigitalizacionType.Get_Folio_final: UnicodeString; begin Result := ChildNodes['folio_final'].Text; end; procedure TXMLDigitalizacionType.Set_Folio_final(Value: UnicodeString); begin ChildNodes['folio_final'].NodeValue := Value; end; { TXMLIndicesType } function TXMLIndicesType.Get_Fecha_nomina: UnicodeString; begin Result := ChildNodes['fecha_nomina'].Text; end; procedure TXMLIndicesType.Set_Fecha_nomina(Value: UnicodeString); begin ChildNodes['fecha_nomina'].NodeValue := Value; end; function TXMLIndicesType.Get_Num_id: UnicodeString; begin Result := ChildNodes['num_id'].Text; end; procedure TXMLIndicesType.Set_Num_id(Value: UnicodeString); begin ChildNodes['num_id'].NodeValue := Value; end; function TXMLIndicesType.Get_Tipo: UnicodeString; begin Result := ChildNodes['tipo'].Text; end; procedure TXMLIndicesType.Set_Tipo(Value: UnicodeString); begin ChildNodes['tipo'].NodeValue := Value; end; function TXMLIndicesType.Get_Prim_apll: UnicodeString; begin Result := ChildNodes['prim_apll'].Text; end; procedure TXMLIndicesType.Set_Prim_apll(Value: UnicodeString); begin ChildNodes['prim_apll'].NodeValue := Value; end; function TXMLIndicesType.Get_Seg_apll: UnicodeString; begin Result := ChildNodes['seg_apll'].Text; end; procedure TXMLIndicesType.Set_Seg_apll(Value: UnicodeString); begin ChildNodes['seg_apll'].NodeValue := Value; end; function TXMLIndicesType.Get_Prim_nomb: UnicodeString; begin Result := ChildNodes['prim_nomb'].Text; end; procedure TXMLIndicesType.Set_Prim_nomb(Value: UnicodeString); begin ChildNodes['prim_nomb'].NodeValue := Value; end; function TXMLIndicesType.Get_Seg_nomb: UnicodeString; begin Result := ChildNodes['seg_nomb'].Text; end; procedure TXMLIndicesType.Set_Seg_nomb(Value: UnicodeString); begin ChildNodes['seg_nomb'].NodeValue := Value; end; { TXMLIndicesTypeList } function TXMLIndicesTypeList.Add: IXMLIndicesType; begin Result := AddItem(-1) as IXMLIndicesType; end; function TXMLIndicesTypeList.Insert(const Index: Integer): IXMLIndicesType; begin Result := AddItem(Index) as IXMLIndicesType; end; function TXMLIndicesTypeList.Get_Item(Index: Integer): IXMLIndicesType; begin Result := List[Index] as IXMLIndicesType; end; end.
unit RRManagerEditResourceFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, RRManagerBaseObjects, ComCtrls, ToolWin, StdCtrls, ActnList, ImgList, Mask, ToolEdit, CommonComplexCombo, ExtCtrls, RRManagerObjects, ClientCommon, RRManagerEditVersionFrame, RRManagerBaseGUI, RRManagerVersionsFrame; type // TfrmResources = class(TFrame) TfrmResources = class(TBaseFrame) gbxProperties: TGroupBox; tlbrEdit: TToolBar; pgctl: TPageControl; tshResourceEditor: TTabSheet; tlbtnAdd: TToolButton; tlbtnBack: TToolButton; ToolButton4: TToolButton; tlbtnClear: TToolButton; cmplxFluidType: TfrmComplexCombo; cmplxResourceType: TfrmComplexCombo; cmplxResourceCategory: TfrmComplexCombo; edtValue: TEdit; Label4: TLabel; Bevel1: TBevel; Label5: TLabel; frmVersions: TfrmVersions; Splitter1: TSplitter; procedure trwResourcesChange(Sender: TObject; Node: TTreeNode); procedure cmplxFluidTypecmbxNameChange(Sender: TObject); procedure cmplxResourceCategorycmbxNameChange(Sender: TObject); procedure cmplxResourceTypecmbxNameChange(Sender: TObject); procedure edtValueChange(Sender: TObject); procedure trwResourcesChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure frmVersioncmbxDocNameChange(Sender: TObject); private { Private declarations } FLoadAction, FElementAction: TBaseAction; FVersions: TOldAccountVersions; FResource: TOldResource; FTempObject: TbaseObject; FCreatedCollection: TBaseCollection; FCreatedObject: TBaseObject; function GetBed: TOldBed; function GetLayer: TOldLayer; function GetSubstructure: TOldSubstructure; function GetVersions: TOldAccountVersions; procedure SetResource(const Value: TOldResource); procedure SaveResource; procedure ClearOnlyControls; procedure OnChangeVersion(Sender: TObject); procedure AddVersion(Sender: TObject); procedure DeleteVersion(Sender: TObject); procedure AddResource(Sender: TObject); procedure DeleteResource(Sender: TObject); procedure SaveCurrentChecked(Sender: TObject); procedure MakeClear(Sender: TObject); procedure MakeUndo(Sender: TObject); procedure ViewChange(Sender: TObject); procedure OnSaveVersion(Sender: TObject); protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; procedure LocalRegisterInspector; public { Public declarations } property Versions: TOldAccountVersions read GetVersions; property Layer: TOldLayer read GetLayer; property Bed: TOldBed read GetBed; property Substructure: TOldSubstructure read GetSubstructure; property Resource: TOldResource read FResource write SetResource; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Save; override; end; implementation {$R *.DFM} uses RRManagerLoaderCommands, FramesWizard; type TResourceVersionLoadAction = class(TVersionBaseLoadAction) public function Execute(ABaseObject: TBaseObject): boolean; override; end; TResourceByVersionLoadAction = class(TResourceByVersionBaseLoadAction) public function Execute(ABaseObject: TBaseObject): boolean; override; end; { TfrmResourceReserves } procedure TfrmResources.ClearControls; begin FVersions.Free; FVersions := nil; FResource := nil; ClearOnlyControls; end; constructor TfrmResources.Create(AOwner: TComponent); begin inherited; NeedCopyState := false; FCreatedCollection := TBaseCollection.Create(TBaseObject); FCreatedObject := FCreatedCollection.Add; FElementAction := TResourceByVersionLoadAction.Create(Self); FLoadAction := TResourceVersionLoadAction.Create(Self); frmVersions.Prepare(Versions, 'ресурсы', TOldResource, FElementAction); frmVersions.OnAddSubElement := AddResource; frmVersions.OnDeleteSubElement := DeleteResource; frmVersions.OnAddVersion := AddVersion; frmVersions.OnDeleteVersion := DeleteVersion; frmVersions.OnViewChanged := ViewChange; frmVersions.OnSaveCurrentChecked := SaveCurrentChecked; frmVersions.OnSaveVersion := OnSaveVersion; frmVersions.OnUndo := MakeUndo; frmVersions.OnClear := MakeClear; cmplxFluidType.Caption := 'Тип флюида'; cmplxFluidType.FullLoad := true; cmplxFluidType.DictName := 'TBL_FLUID_TYPE_DICT'; cmplxResourceType.Caption := 'Тип ресурсов'; cmplxResourceType.FullLoad := true; cmplxResourceType.DictName := 'TBL_RESOURSE_TYPE_DICT'; cmplxResourceCategory.Caption := 'Категория ресурсов'; cmplxResourceCategory.FullLoad := true; cmplxResourceCategory.DictName := 'TBL_RESOURCES_CATEGORY_DICT'; tshResourceEditor.TabVisible := false; end; procedure TfrmResources.FillControls(ABaseObject: TBaseObject); var actn: TResourceVersionLoadAction; Node: TTreeNode; begin FTempObject := ABaseObject; FVersions.Free; FVersions := nil; actn := TResourceVersionLoadAction.Create(Self); if Assigned(Layer) then actn.Execute(Layer) else actn.Execute(ABaseObject); actn.Free; frmVersions.Versions := FVersions; if frmVersions.trw.Items.Count > 0 then frmVersions.trw.Selected := frmVersions.trw.Items[0]; Node := frmVersions.trw.Items.GetFirstNode; if Assigned(Node) then Node.Expand(true); end; procedure TfrmResources.FillParentControls; begin end; function TfrmResources.GetBed: TOldBed; begin Result := nil; if EditingObject is TOldBed then Result := EditingObject as TOldBed else if EditingObject is TOldLayer then Result := (EditingObject as TOldLayer).Bed; end; function TfrmResources.GetLayer: TOldLayer; begin Result := nil; if EditingObject is TOldLayer then Result := EditingObject as TOldLayer; end; function TfrmResources.GetSubstructure: TOldSubstructure; begin Result := nil; if EditingObject is TOldSubstructure then Result := EditingObject as TOldSubstructure else if EditingObject is TOldLayer then Result := (EditingObject as TOldLayer).Substructure; end; function TfrmResources.GetVersions: TOldAccountVersions; begin if not Assigned(FVersions) then begin FVersions := TOldAccountVersions.Create(nil); if Assigned(Layer) then begin FVersions.Assign(Layer.Versions); // копируем владельца, а то запросы самих ресурсов неудобно делать FVersions.Owner := Layer; end else if Assigned(FTempObject) then begin FVersions.Assign((FTempObject as TOldLayer).Versions); // копируем владельца, а то запросы самих ресурсов неудобно делать FVersions.Owner := FTempObject; end else FVersions.Owner := FCreatedObject; end; Result := FVersions; end; procedure TfrmResources.Save; var i: integer; actn: TBaseAction; begin inherited; if Assigned(FVersions) then begin actn := TResourceByVersionLoadAction.Create(Self); for i := 0 to FVersions.Count - 1 do begin if FVersions.Items[i].Resources.NeedsUpdate then actn.Execute(FVersions.Items[i]); // копируем только ресурсы FVersions.Items[i].Resources.CopyCollection := true; FVersions.Items[i].Reserves.CopyCollection := false; FVersions.Items[i].Parameters.CopyCollection := false; end; actn.Free; if not Assigned(EditingObject) then // если что берем объект из предыдущего фрэйма FEditingObject := ((Owner as TDialogFrame).Frames[0] as TBaseFrame).EditingObject; Layer.Versions.ResourcesClear; Layer.Versions.AddItems(FVersions); end; end; procedure TfrmResources.SetResource(const Value: TOldResource); begin // if FResource <> Value then begin FResource := Value; if Assigned(FResource) then begin cmplxResourceType.AddItem(FResource.ResourceTypeID, FResource.ResourceType); cmplxResourceCategory.AddItem(FResource.ResourceCategoryID, FResource.ResourceCategory); cmplxFluidType.AddItem(FResource.FluidTypeID, FResource.FluidType); edtValue.Text := trim(Format('%7.3f', [FResource.Value])); end else ClearOnlyControls; end; end; procedure TfrmResources.SaveResource; begin if Assigned(Resource) then begin Resource.FluidTypeID := cmplxFluidType.SelectedElementID; Resource.FluidType := cmplxFluidType.SelectedElementName; Resource.ResourceTypeID := cmplxResourceType.SelectedElementID; Resource.ResourceType := cmplxResourceType.SelectedElementName; Resource.ResourceCategoryID := cmplxResourceCategory.SelectedElementID; Resource.ResourceCategory := cmplxResourceCategory.SelectedElementName; try Resource.Value := StrToFloat(edtValue.Text); except Resource.Value := 0; end; if TBaseObject(frmVersions.trw.Selected.Data) is TOldResource then frmVersions.trw.Selected.Text := Resource.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false); end; end; { TResourceVersionLoadAction } function TResourceVersionLoadAction.Execute( ABaseObject: TBaseObject): boolean; var node: TTreeNode; i: integer; begin LastCollection := (ABaseObject as TOldLayer).Versions; if LastCollection.NeedsUpdate then Result := inherited Execute(ABaseObject) else Result := true; if Result then begin // загружаем в интерфейс if Assigned(LastCollection) then with Owner as TfrmResources do begin // получаем версии на форму Versions; frmVersions.trw.Items.BeginUpdate; frmVersions.trw.Selected := nil; // чистим try frmVersions.trw.Items.Clear; except end; // добавляем в дерево не реальные версии // а их копии, чтобы потом сохранять изменения for i := 0 to Versions.Count - 1 do if (((frmVersions.cmbxView.ItemIndex = 0) and Versions.Items[i].ContainsResources) or (frmVersions.cmbxView.ItemIndex = 1)) then begin Node := frmVersions.trw.Items.AddObject(nil, Versions.Items[i].List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), Versions.Items[i]); Node.SelectedIndex := 10; frmVersions.trw.Items.AddChild(Node, 'будут ресурсы'); end; frmVersions.trw.Items.EndUpdate; end; end; end; { TResourceByVersionLoadAction } function TResourceByVersionLoadAction.Execute( ABaseObject: TBaseObject): boolean; var ParentNode, Node: TTreeNode; i: integer; begin LastCollection := (ABaseObject as TOldAccountVersion).Resources; if LastCollection.NeedsUpdate then Result := inherited Execute(ABaseObject) else Result := true; if Result then begin // загружаем в интерфейс if Assigned(LastCollection) then with Owner as TfrmResources do begin frmVersions.trw.Items.BeginUpdate; // чистим if Assigned(frmVersions.trw.Selected) then begin if (TBaseObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then ParentNode := frmVersions.trw.Selected else ParentNode := frmVersions.trw.Selected.Parent; Node := ParentNode.getFirstChild; while Assigned(Node) do begin Node.Delete; Node := ParentNode.getFirstChild; end; // добавляем (ABaseObject as TOldAccountVersion).ContainsResources := LastCollection.Count > 0; for i := 0 to LastCollection.Count - 1 do begin Node := frmVersions.trw.Items.AddChildObject(ParentNode, LastCollection.Items[i].List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), LastCollection.Items[i]); Node.SelectedIndex := 11; end; end; frmVersions.trw.Items.EndUpdate; end; end; end; procedure TfrmResources.trwResourcesChange(Sender: TObject; Node: TTreeNode); begin if Assigned(Node) then begin if TBaseObject(Node.data) is TOldAccountVersion then begin tshResourceEditor.TabVisible := false; end else if TBaseObject(Node.data) is TOldResource then begin Resource := TBaseObject(Node.data) as TOldResource; tshResourceEditor.TabVisible := true; end; end; end; procedure TfrmResources.ClearOnlyControls; begin cmplxFluidType.Clear; cmplxResourceType.Clear; cmplxResourceCategory.Clear; edtValue.Clear; end; procedure TfrmResources.cmplxFluidTypecmbxNameChange(Sender: TObject); begin cmplxFluidType.cmbxNameChange(Sender); if frmVersions.SaveCurrent.Checked then SaveResource; end; procedure TfrmResources.cmplxResourceCategorycmbxNameChange( Sender: TObject); begin cmplxResourceCategory.cmbxNameChange(Sender); if frmVersions.SaveCurrent.Checked then SaveResource; end; procedure TfrmResources.cmplxResourceTypecmbxNameChange(Sender: TObject); begin cmplxResourceType.cmbxNameChange(Sender); if frmVersions.SaveCurrent.Checked then SaveResource; end; procedure TfrmResources.edtValueChange(Sender: TObject); begin if frmVersions.SaveCurrent.Checked then SaveResource; end; procedure TfrmResources.trwResourcesChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin if Assigned(frmVersions.trw.Selected) then begin if frmVersions.trw.Selected.Level = 1 then AllowChange := Inspector.Check end; end; procedure TfrmResources.RegisterInspector; begin inherited; end; procedure TfrmResources.LocalRegisterInspector; begin Inspector.Clear; cmplxFluidType.cmbxName.OnChange := cmplxFluidTypecmbxNameChange; cmplxResourceType.cmbxName.OnChange := cmplxResourceTypecmbxNameChange; cmplxResourceCategory.cmbxName.OnChange := cmplxResourceCategorycmbxNameChange; edtValue.OnChange := edtValueChange; Inspector.Add(cmplxFluidType.cmbxName, nil, ptString, 'тип флюида', false); Inspector.Add(cmplxResourceType.cmbxName, nil, ptString, 'тип ресурсов', false); Inspector.Add(cmplxResourceCategory.cmbxName, nil, ptString, 'категория ресурсов', false); Inspector.Add(edtValue, nil, ptFloat, 'высота залежи', false); end; procedure TfrmResources.frmVersioncmbxDocNameChange(Sender: TObject); begin if Assigned(frmVersions.trw.Selected) and (TObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then frmVersions.trw.Selected.Text := TOldAccountVersion(frmVersions.trw.Selected.Data).List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false) end; procedure TfrmResources.OnChangeVersion(Sender: TObject); var v: TOldAccountVersion; Node: TTreeNode; i: integer; begin v := Versions.Items[Versions.Count - 1]; Node := frmVersions.trw.Items.AddObject(nil, v.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), v); Node.SelectedIndex := 10; frmVersions.trw.Items.AddChild(Node, 'будут ресурсы'); v.Resources.NeedsUpdate := false; i := frmVersions.FindObject(v); if i > -1 then frmVersions.trw.Items[i].Selected := true; end; procedure TfrmResources.AddVersion(Sender: TObject); var i: integer; begin frmVersions.Version.Resources.NeedsUpdate := false; i := frmVersions.FindObject(frmVersions.Version); if i > -1 then frmVersions.trw.Items[i].Selected := true; end; procedure TfrmResources.DeleteVersion(Sender: TObject); begin end; procedure TfrmResources.AddResource(Sender: TObject); var r: TOldResource; Node, NewNode: TTreeNode; i: integer; begin r := frmVersions.Version.Resources.Add; if (TBaseObject(frmVersions.trw.Selected.Data) is TOldAccountVersion) then Node := frmVersions.trw.Selected else Node := frmVersions.trw.Selected.Parent; NewNode := frmVersions.trw.Items.AddChildObject(Node, r.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false), r); NewNode.SelectedIndex := 11; Node.Expand(true); LocalRegisterInspector; Resource := r; i := frmVersions.FindObject(Resource); if i > -1 then frmVersions.trw.Items[i].Selected := true; end; procedure TfrmResources.DeleteResource(Sender: TObject); begin frmVersions.Version.Resources.Remove(TBaseObject(frmVersions.trw.Selected.Data)); frmVersions.trw.Selected.Delete; Resource := nil; frmVersions.trw.Selected := nil; UnCheck; end; procedure TfrmResources.MakeClear(Sender: TObject); begin ClearOnlyControls; end; procedure TfrmResources.MakeUndo(Sender: TObject); begin with pgctl do case ActivePageIndex of 0: begin Resource := nil; Resource := TOldResource(frmVersions.trw.Selected.Data); end; end; end; procedure TfrmResources.SaveCurrentChecked(Sender: TObject); begin SaveResource; end; procedure TfrmResources.ViewChange(Sender: TObject); begin Resource := nil; FLoadAction.Execute(Layer); end; procedure TfrmResources.OnSaveVersion(Sender: TObject); begin end; destructor TfrmResources.Destroy; begin FCreatedCollection.Free; inherited; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_MOVIMENTO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 *******************************************************************************} unit EcfMovimentoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, EcfImpressoraVO, EcfCaixaVO, EcfEmpresaVO, EcfTurnoVO, EcfOperadorVO, EcfFechamentoVO, EcfSuprimentoVO, EcfSangriaVO, EcfDocumentosEmitidosVO, EcfRecebimentoNaoFiscalVO; type [TEntity] [TTable('ECF_MOVIMENTO')] TEcfMovimentoVO = class(TVO) private FID: Integer; FID_ECF_EMPRESA: Integer; FID_ECF_TURNO: Integer; FID_ECF_IMPRESSORA: Integer; FID_ECF_OPERADOR: Integer; FID_ECF_CAIXA: Integer; FID_GERENTE_SUPERVISOR: Integer; FDATA_ABERTURA: TDateTime; FHORA_ABERTURA: String; FDATA_FECHAMENTO: TDateTime; FHORA_FECHAMENTO: String; FTOTAL_SUPRIMENTO: Extended; FTOTAL_SANGRIA: Extended; FTOTAL_NAO_FISCAL: Extended; FTOTAL_VENDA: Extended; FTOTAL_DESCONTO: Extended; FTOTAL_ACRESCIMO: Extended; FTOTAL_FINAL: Extended; FTOTAL_RECEBIDO: Extended; FTOTAL_TROCO: Extended; FTOTAL_CANCELADO: Extended; FSTATUS_MOVIMENTO: String; FEcfImpressoraVO: TEcfImpressoraVO; FEcfCaixaVO: TEcfCaixaVO; FEcfEmpresaVO: TEcfEmpresaVO; FEcfTurnoVO: TEcfTurnoVO; FEcfOperadorVO: TEcfOperadorVO; FEcfGerenteVO: TEcfOperadorVO; FListaEcfFechamentoVO: TObjectList<TEcfFechamentoVO>; FListaEcfSuprimentoVO: TObjectList<TEcfSuprimentoVO>; FListaEcfSangriaVO: TObjectList<TEcfSangriaVO>; FListaEcfDocumentosEmitidosVO: TObjectList<TEcfDocumentosEmitidosVO>; FListaEcfRecebimentoNaoFiscalVO: TObjectList<TEcfRecebimentoNaoFiscalVO>; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_ECF_EMPRESA', 'Id Ecf Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfEmpresa: Integer read FID_ECF_EMPRESA write FID_ECF_EMPRESA; [TColumn('ID_ECF_TURNO', 'Id Ecf Turno', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfTurno: Integer read FID_ECF_TURNO write FID_ECF_TURNO; [TColumn('ID_ECF_IMPRESSORA', 'Id Ecf Impressora', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfImpressora: Integer read FID_ECF_IMPRESSORA write FID_ECF_IMPRESSORA; [TColumn('ID_ECF_OPERADOR', 'Id Ecf Operador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfOperador: Integer read FID_ECF_OPERADOR write FID_ECF_OPERADOR; [TColumn('ID_ECF_CAIXA', 'Id Ecf Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA; [TColumn('ID_GERENTE_SUPERVISOR', 'Id Gerente Supervisor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdGerenteSupervisor: Integer read FID_GERENTE_SUPERVISOR write FID_GERENTE_SUPERVISOR; [TColumn('DATA_ABERTURA', 'Data Abertura', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataAbertura: TDateTime read FDATA_ABERTURA write FDATA_ABERTURA; [TColumn('HORA_ABERTURA', 'Hora Abertura', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraAbertura: String read FHORA_ABERTURA write FHORA_ABERTURA; [TColumn('DATA_FECHAMENTO', 'Data Fechamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataFechamento: TDateTime read FDATA_FECHAMENTO write FDATA_FECHAMENTO; [TColumn('HORA_FECHAMENTO', 'Hora Fechamento', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraFechamento: String read FHORA_FECHAMENTO write FHORA_FECHAMENTO; [TColumn('TOTAL_SUPRIMENTO', 'Total Suprimento', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalSuprimento: Extended read FTOTAL_SUPRIMENTO write FTOTAL_SUPRIMENTO; [TColumn('TOTAL_SANGRIA', 'Total Sangria', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalSangria: Extended read FTOTAL_SANGRIA write FTOTAL_SANGRIA; [TColumn('TOTAL_NAO_FISCAL', 'Total Nao Fiscal', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalNaoFiscal: Extended read FTOTAL_NAO_FISCAL write FTOTAL_NAO_FISCAL; [TColumn('TOTAL_VENDA', 'Total Venda', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalVenda: Extended read FTOTAL_VENDA write FTOTAL_VENDA; [TColumn('TOTAL_DESCONTO', 'Total Desconto', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalDesconto: Extended read FTOTAL_DESCONTO write FTOTAL_DESCONTO; [TColumn('TOTAL_ACRESCIMO', 'Total Acrescimo', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalAcrescimo: Extended read FTOTAL_ACRESCIMO write FTOTAL_ACRESCIMO; [TColumn('TOTAL_FINAL', 'Total Final', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalFinal: Extended read FTOTAL_FINAL write FTOTAL_FINAL; [TColumn('TOTAL_RECEBIDO', 'Total Recebido', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalRecebido: Extended read FTOTAL_RECEBIDO write FTOTAL_RECEBIDO; [TColumn('TOTAL_TROCO', 'Total Troco', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalTroco: Extended read FTOTAL_TROCO write FTOTAL_TROCO; [TColumn('TOTAL_CANCELADO', 'Total Cancelado', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalCancelado: Extended read FTOTAL_CANCELADO write FTOTAL_CANCELADO; [TColumn('STATUS_MOVIMENTO', 'Status Movimento', 8, [ldGrid, ldLookup, ldCombobox], False)] property StatusMovimento: String read FSTATUS_MOVIMENTO write FSTATUS_MOVIMENTO; [TAssociation('ID', 'ID_ECF_IMPRESSORA')] property EcfImpressoraVO: TEcfImpressoraVO read FEcfImpressoraVO write FEcfImpressoraVO; [TAssociation('ID', 'ID_ECF_CAIXA')] property EcfCaixaVO: TEcfCaixaVO read FEcfCaixaVO write FEcfCaixaVO; [TAssociation('ID', 'ID_ECF_EMPRESA')] property EcfEmpresaVO: TEcfEmpresaVO read FEcfEmpresaVO write FEcfEmpresaVO; [TAssociation('ID', 'ID_ECF_TURNO')] property EcfTurnoVO: TEcfTurnoVO read FEcfTurnoVO write FEcfTurnoVO; [TAssociation('ID', 'ID_ECF_OPERADOR')] property EcfOperadorVO: TEcfOperadorVO read FEcfOperadorVO write FEcfOperadorVO; [TAssociation('ID', 'ID_GERENTE_SUPERVISOR')] property EcfGerenteVO: TEcfOperadorVO read FEcfGerenteVO write FEcfGerenteVO; [TManyValuedAssociation('ID_ECF_MOVIMENTO', 'ID')] property ListaEcfFechamentoVO: TObjectList<TEcfFechamentoVO> read FListaEcfFechamentoVO write FListaEcfFechamentoVO; [TManyValuedAssociation('ID_ECF_MOVIMENTO', 'ID')] property ListaEcfSuprimentoVO: TObjectList<TEcfSuprimentoVO> read FListaEcfSuprimentoVO write FListaEcfSuprimentoVO; [TManyValuedAssociation('ID_ECF_MOVIMENTO', 'ID')] property ListaEcfSangriaVO: TObjectList<TEcfSangriaVO> read FListaEcfSangriaVO write FListaEcfSangriaVO; [TManyValuedAssociation('ID_ECF_MOVIMENTO', 'ID')] property ListaEcfDocumentosEmitidosVO: TObjectList<TEcfDocumentosEmitidosVO> read FListaEcfDocumentosEmitidosVO write FListaEcfDocumentosEmitidosVO; [TManyValuedAssociation('ID_ECF_MOVIMENTO', 'ID')] property ListaEcfRecebimentoNaoFiscalVO: TObjectList<TEcfRecebimentoNaoFiscalVO> read FListaEcfRecebimentoNaoFiscalVO write FListaEcfRecebimentoNaoFiscalVO; end; implementation constructor TEcfMovimentoVO.Create; begin inherited; FEcfImpressoraVO := TEcfImpressoraVO.Create; FEcfCaixaVO := TEcfCaixaVO.Create; FEcfEmpresaVO := TEcfEmpresaVO.Create; FEcfTurnoVO := TEcfTurnoVO.Create; FEcfOperadorVO := TEcfOperadorVO.Create; FEcfGerenteVO := TEcfOperadorVO.Create; FListaEcfFechamentoVO := TObjectList<TEcfFechamentoVO>.Create; FListaEcfSuprimentoVO := TObjectList<TEcfSuprimentoVO>.Create; FListaEcfSangriaVO := TObjectList<TEcfSangriaVO>.Create; FListaEcfDocumentosEmitidosVO := TObjectList<TEcfDocumentosEmitidosVO>.Create; FListaEcfRecebimentoNaoFiscalVO := TObjectList<TEcfRecebimentoNaoFiscalVO>.Create; end; destructor TEcfMovimentoVO.Destroy; begin FreeAndNil(FEcfImpressoraVO); FreeAndNil(FEcfCaixaVO); FreeAndNil(FEcfEmpresaVO); FreeAndNil(FEcfTurnoVO); FreeAndNil(FEcfOperadorVO); FreeAndNil(FEcfGerenteVO); FreeAndNil(FListaEcfFechamentoVO); FreeAndNil(FListaEcfSuprimentoVO); FreeAndNil(FListaEcfSangriaVO); FreeAndNil(FListaEcfDocumentosEmitidosVO); FreeAndNil(FListaEcfRecebimentoNaoFiscalVO); inherited; end; initialization Classes.RegisterClass(TEcfMovimentoVO); finalization Classes.UnRegisterClass(TEcfMovimentoVO); end.
unit RaceHorse; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpjsonrtti; const MINIMUM_HORSE_SPEED = 1.75; AVERAGE_HORSE_SPEED = 2.25; MAXIMUM_HORSE_SPEED = 2.75; type THorseSpeedParameters = class(TPersistent) private fBreakSpeed: single; fBreakDistance: single; fEarlySpeed: single; fEarlyDistance: single; fLateSpeed: single; fLateDistance: single; fClosingSpeed: single; published property BreakSpeed: single read fBreakSpeed write fBreakSpeed; property BreakDistance: single read fBreakDistance write fBreakDistance; property EarlySpeed: single read fEarlySpeed write fEarlySpeed; property EarlyDistance: single read fEarlyDistance write fEarlyDistance; property LateSpeed: single read fLateSpeed write fLateSpeed; property LateDistance: single read fLateDistance write fLateDistance; property ClosingSpeed: single read fClosingSpeed write fClosingSpeed; end; TRaceHorse = class(TCollectionItem) private HorsePosition: single; HorseFinishOrder: integer; fName: string; fSpeedInfo: THorseSpeedParameters; public procedure RandomizeSpeedInfo( StartPosition: single; TrackWidth: single); procedure LoadHorse(StartPosition: single); procedure MoveHorse(FinishLine: integer); property Position: single read HorsePosition; property FinishOrder: integer read HorseFinishOrder write HorseFinishOrder; function SpeedIndex: integer; function EarlyPace: integer; function LatePace: integer; procedure FromJson(JsonString: string); function ToJson: string; published property Name: string read fName write fName; property SpeedInfo: THorseSpeedParameters read fSpeedInfo write fSpeedInfo; end; implementation function Greatest(Value1: single; Value2: single): single; begin Result := Value1; if (Value1 < Value2) then begin Result := Value2; end; end; function Least(Value1: single; Value2: single): single; begin Result := Value1; if (Value1 > Value2) then begin Result := Value2; end; end; procedure TRaceHorse.RandomizeSpeedInfo( StartPosition: single; TrackWidth: single); begin SpeedInfo := THorseSpeedParameters.Create; with SpeedInfo do begin BreakSpeed := Greatest( MINIMUM_HORSE_SPEED, Random * AVERAGE_HORSE_SPEED); BreakDistance := StartPosition + (0.25 * Random * TrackWidth); EarlySpeed := Least(BreakSpeed + (Random * AVERAGE_HORSE_SPEED), MAXIMUM_HORSE_SPEED); EarlyDistance := BreakDistance + (0.25 * Random * TrackWidth); LateSpeed := Greatest( Least( EarlySpeed + ((Random - 0.5) * MAXIMUM_HORSE_SPEED), MAXIMUM_HORSE_SPEED), MINIMUM_HORSE_SPEED); LateDistance := EarlyDistance + (0.5 * Random * TrackWidth); ClosingSpeed := Greatest( Least( LateSpeed + ((Random - 0.5) * MAXIMUM_HORSE_SPEED), MAXIMUM_HORSE_SPEED), MINIMUM_HORSE_SPEED); end; end; function ComputeCurrentSpeed( SpeedInfo: THorseSpeedParameters; Position: single): single; begin with SpeedInfo do begin if (Position <= BreakDistance) then Result := BreakSpeed else if (Position <= EarlyDistance) then Result := EarlySpeed else if (Position <= LateDistance) then Result := LateSpeed else Result := ClosingSpeed; end; end; procedure TRaceHorse.LoadHorse(StartPosition: single); begin HorsePosition := StartPosition; HorseFinishOrder := 0; end; procedure TRaceHorse.MoveHorse(FinishLine: integer); var HorseSpeed: single; FinishOrderOffset: single; begin HorseSpeed := ComputeCurrentSpeed(SpeedInfo, HorsePosition); HorsePosition += HorseSpeed * Random; FinishOrderOffset := 6 * (HorseFinishOrder - 1); if (HorsePosition > (FinishLine - FinishOrderOffset)) then begin HorsePosition := FinishLine - FinishOrderOffset; end; end; function TRaceHorse.SpeedIndex: integer; begin with SpeedInfo do begin result := Round(10 * (BreakSpeed + EarlySpeed + LateSpeed + ClosingSpeed)); end; end; function TRaceHorse.EarlyPace: integer; begin with SpeedInfo do begin result := Round(10 * (BreakSpeed + EarlySpeed)); end; end; function TRaceHorse.LatePace: integer; begin with SpeedInfo do begin result := Round(10 * (LateSpeed + ClosingSpeed)); end; end; // http://wiki.freepascal.org/Streaming_JSON procedure TRaceHorse.FromJson(JsonString: string); var DeStreamer: TJSONDeStreamer; begin try DeStreamer := TJSONDeStreamer.Create(nil); SpeedInfo := THorseSpeedParameters.Create; DeStreamer.JSONToObject(JsonString, Self); finally DeStreamer.Destroy; end; end; function TRaceHorse.ToJson: string; var Streamer: TJSONStreamer; JsonString: string; begin try Streamer := TJSONStreamer.Create(nil); JsonString := Streamer.ObjectToJSONString(Self); finally Streamer.Destroy; end; result := JsonString; end; end.
unit AsyncHttpServer.Connection; interface uses System.SysUtils, AsyncIO, AsyncIO.Net.IP, AsyncHttpServer.Request, AsyncHttpServer.RequestHandler, AsyncHttpServer.Response; type HttpConnectionManager = interface; HttpConnection = interface ['{A7AC1C03-AE5C-4A4C-B49E-C591050176B0}'] {$REGION 'Property accessors'} function GetSocket: IPStreamSocket; function GetConnectionManager: HttpConnectionManager; function GetRequestHandler: HttpRequestHandler; {$ENDREGION} procedure Start; procedure Stop; property Socket: IPStreamSocket read GetSocket; property ConnectionManager: HttpConnectionManager read GetConnectionManager; property RequestHandler: HttpRequestHandler read GetRequestHandler; end; HttpConnectionManager = interface ['{4B05AE86-77DC-442C-8679-518353DFAB34}'] procedure StopAll; end; function NewHttpConnection(const Socket: IPStreamSocket; const ConnectionManager: HttpConnectionManager; const RequestHandler: HttpRequestHandler): HttpConnection; function NewHttpConnectionManager: HttpConnectionManager; procedure ManageHttpConnection(const Connection: HttpConnection; const ConnectionManager: HttpConnectionManager); procedure RemoveHttpConnection(const Connection: HttpConnection; const ConnectionManager: HttpConnectionManager); implementation uses System.Generics.Collections, AsyncIO.OpResults, AsyncHttpServer.RequestParser, AsyncHttpServer.Headers, HttpDateTime; type HttpConnectionImpl = class(TInterfacedObject, HttpConnection) public const MaxRequestSize = 16 * 1024 * 1024; // max request size const MaxContentBufferSize = 64 * 1024; // max buffer size when sending content strict private FSocket: IPStreamSocket; FStream: AsyncSocketStream; FConnectionManager: HttpConnectionManager; FRequestHandler: HttpRequestHandler; FRequestParser: HttpRequestParser; FBuffer: StreamBuffer; FContentBuffer: TBytes; FRequest: HttpRequest; FResponse: HttpResponse; procedure Log(const Msg: string); procedure DoReadRequest; procedure DoParseRequest; procedure DoReadResponseContent; procedure DoWriteResponse; procedure StartWriteResponseContent; procedure DoStartConnection; procedure DoShutdownConnection; procedure DoStopConnection; procedure HandleRequest; procedure HandleInvalidRequest; procedure ReadRequestHandler(const Res: OpResult; const BytesTransferred: UInt64); procedure WriteResponseHandler(const Res: OpResult; const BytesTransferred: UInt64); procedure ReadResponseContentHandler(const Res: OpResult; const BytesTransferred: UInt64); procedure WriteResponseContentHandler(const Res: OpResult; const BytesTransferred: UInt64); public constructor Create(const Socket: IPStreamSocket; const ConnectionManager: HttpConnectionManager; const RequestHandler: HttpRequestHandler; const RequestParser: HttpRequestParser); function GetSocket: IPStreamSocket; function GetConnectionManager: HttpConnectionManager; function GetRequestHandler: HttpRequestHandler; procedure Start; procedure Stop; property Socket: IPStreamSocket read FSocket; property ConnectionManager: HttpConnectionManager read FConnectionManager; property RequestHandler: HttpRequestHandler read FRequestHandler; property RequestParser: HttpRequestParser read FRequestParser; end; function NewHttpConnection(const Socket: IPStreamSocket; const ConnectionManager: HttpConnectionManager; const RequestHandler: HttpRequestHandler): HttpConnection; var requestParser: HttpRequestParser; begin requestParser := NewHttpRequestParser(); result := HttpConnectionImpl.Create(Socket, ConnectionManager, RequestHandler, requestParser); end; { HttpConnectionImpl } constructor HttpConnectionImpl.Create(const Socket: IPStreamSocket; const ConnectionManager: HttpConnectionManager; const RequestHandler: HttpRequestHandler; const RequestParser: HttpRequestParser); begin inherited Create; FSocket := Socket; FConnectionManager := ConnectionManager; FRequestHandler := RequestHandler; FRequestParser := RequestParser; end; procedure HttpConnectionImpl.DoParseRequest; var reqStatus: HttpRequestState; begin // any read data has been appended to our buffer // so pass it to the parser reqStatus := RequestParser.Parse(FRequest, FBuffer); case reqStatus of HttpRequestStateValid: begin // we got a valid request, time to handle it HandleRequest; end; HttpRequestStateNeedMoreData: begin // haven't got entire request yet, so queue another read DoReadRequest; end; else // request was bad, send an error response HandleInvalidRequest; end; end; procedure HttpConnectionImpl.DoReadRequest; begin AsyncRead(FStream, FBuffer, TransferAtLeast(1), ReadRequestHandler); end; procedure HttpConnectionImpl.DoReadResponseContent; begin AsyncRead(FResponse.ContentStream, FContentBuffer, TransferAtLeast(1), ReadResponseContentHandler); end; procedure HttpConnectionImpl.DoShutdownConnection; begin FStream.Socket.Shutdown(); DoStopConnection; end; procedure HttpConnectionImpl.DoStartConnection; var con: HttpConnection; begin con := Self; ManageHttpConnection(con, ConnectionManager); end; procedure HttpConnectionImpl.DoStopConnection; var con: HttpConnection; begin con := Self; // socket has been closed RemoveHttpConnection(con, ConnectionManager); end; procedure HttpConnectionImpl.DoWriteResponse; begin // start sending the response we got FBuffer := FResponse.ToBuffer(); AsyncWrite(FStream, FBuffer, TransferAll(), WriteResponseHandler); end; function HttpConnectionImpl.GetConnectionManager: HttpConnectionManager; begin result := FConnectionManager; end; function HttpConnectionImpl.GetRequestHandler: HttpRequestHandler; begin result := FRequestHandler; end; function HttpConnectionImpl.GetSocket: IPStreamSocket; begin result := FSocket; end; procedure HttpConnectionImpl.HandleInvalidRequest; begin FResponse := StandardResponse(StatusBadRequest); DoWriteResponse; end; procedure HttpConnectionImpl.HandleRequest; begin // we've got a valid request, we need to handle it and send the response {$IFDEF DEBUG_LOG} {$IFDEF LOG_DETAILED} Log(Format(#13#10 + ' %s %s HTTP/%d.%d', [FRequest.Method, FRequest.URI, FRequest.HttpVersionMajor, FRequest.HttpVersionMinor]) + FRequest.Headers.ToDebugString()); {$ELSE} Log(FRequest.Method + ' ' + FRequest.URI + ' HTTP/' + FRequest.HttpVersionMajor.ToString() + '.' + FRequest.HttpVersionMinor.ToString()); {$ENDIF} {$ENDIF} try // get the response from our request handler FResponse := RequestHandler.HandleRequest(FRequest); {$IFDEF DEBUG_LOG} {$IFDEF LOG_DETAILED} Log(Format(#13#10 + ' %d %s', [Ord(FResponse.Status), FResponse.Status.ToString()]) + FResponse.Headers.ToDebugString()); {$ELSE} Log(Ord(FResponse.Status).ToString() + ' ' + FResponse.Status.ToString()); {$ENDIF} {$ENDIF} except on E: Exception do begin // something went wrong, get an error response Log(Format('Error processing request (%s %s HTTP/%d.%d): [%s] %s', [FRequest.Method, FRequest.URI, FRequest.HttpVersionMajor, FRequest.HttpVersionMinor, E.ClassName, E.Message])); FResponse := StandardResponse(StatusInternalServerError); end; end; FResponse.Headers.Value['Date'] := SystemTimeToHttpDate(CurrentSystemTime()); FResponse.Headers.Value['Server'] := 'AsyncHttpServer'; // send whatever response we got DoWriteResponse; end; procedure HttpConnectionImpl.Log(const Msg: string); begin WriteLn('[' + FormatDateTime('yyyy.mm.dd hh:nn:ss.zzz', Now()) + '] ' + FSocket.RemoteEndpoint + ' | ' + Msg); end; procedure HttpConnectionImpl.ReadRequestHandler(const Res: OpResult; const BytesTransferred: UInt64); begin if ((Res.Success) and (BytesTransferred > 0)) then begin // we got at least some data forming the request, parse it and handle response if possible DoParseRequest(); end else if ((Res = NetResults.OperationAborted) or (BytesTransferred = 0)) then begin // socket has been closed or shut down DoStopConnection; end; // ingore other errors end; procedure HttpConnectionImpl.ReadResponseContentHandler( const Res: OpResult; const BytesTransferred: UInt64); begin if ((Res.Success) or (Res = SystemResults.EndOfFile)) then begin if (BytesTransferred > 0) then begin // we got some data from the response content stream // so send it to the client AsyncWrite(FStream, MakeBuffer(FContentBuffer, BytesTransferred), TransferAll(), WriteResponseContentHandler); end else begin // nothing more to read, so shut down connection DoShutdownConnection; end; end else begin // something went wrong, so kill connection DoStopConnection; end; end; procedure HttpConnectionImpl.Start; begin FBuffer := StreamBuffer.Create(MaxRequestSize); FStream := NewAsyncSocketStream(Socket); FRequest := NewHttpRequest; DoStartConnection; // we're all good to go, start by reading the request DoReadRequest; end; procedure HttpConnectionImpl.StartWriteResponseContent; begin if (not Assigned(FResponse.ContentStream)) then exit; FBuffer := nil; FContentBuffer := nil; SetLength(FContentBuffer, MaxContentBufferSize); // start by reading from the response content stream DoReadResponseContent; end; procedure HttpConnectionImpl.Stop; begin FSocket.Close; end; procedure HttpConnectionImpl.WriteResponseContentHandler( const Res: OpResult; const BytesTransferred: UInt64); var con: HttpConnection; begin if (Res.Success) then begin // response content stream data has been sent, so try reading some more DoReadResponseContent; end else begin FSocket.Shutdown(SocketShutdownBoth); if (Res = NetResults.OperationAborted) then begin con := Self; RemoveHttpConnection(con, ConnectionManager); end; end; end; procedure HttpConnectionImpl.WriteResponseHandler(const Res: OpResult; const BytesTransferred: UInt64); begin if (Res.Success) then begin // response has been sent, send response content stream if applicable StartWriteResponseContent; end else begin FSocket.Shutdown(SocketShutdownBoth); if (Res = NetResults.OperationAborted) then begin DoStopConnection; end; end; end; type THttpConnectionSet = class strict private FDict: TDictionary<HttpConnection, integer>; public constructor Create; destructor Destroy; override; procedure Add(const Connection: HttpConnection); procedure Remove(const Connection: HttpConnection); function GetEnumerator: TEnumerator<HttpConnection>; end; { THttpConnectionSet } procedure THttpConnectionSet.Add(const Connection: HttpConnection); begin FDict.Add(Connection, 1); end; constructor THttpConnectionSet.Create; begin inherited Create; FDict := TDictionary<HttpConnection, integer>.Create; end; destructor THttpConnectionSet.Destroy; begin FDict.Free; inherited; end; function THttpConnectionSet.GetEnumerator: TEnumerator<HttpConnection>; begin result := FDict.Keys.GetEnumerator(); end; procedure THttpConnectionSet.Remove(const Connection: HttpConnection); var hasConnection: boolean; begin hasConnection := FDict.ContainsKey(Connection); if (not hasConnection) then exit; FDict.Remove(Connection); end; type HttpConnectionManagerAssociation = interface ['{7E5B70C1-A9AD-463F-BDED-7EB0C6DFD854}'] procedure Manage(const Connection: HttpConnection); procedure Remove(const Connection: HttpConnection); end; HttpConnectionManagerImpl = class(TInterfacedObject, HttpConnectionManager, HttpConnectionManagerAssociation) strict private FConnections: THttpConnectionSet; property Connections: THttpConnectionSet read FConnections; public constructor Create; destructor Destroy; override; procedure Manage(const Connection: HttpConnection); procedure Remove(const Connection: HttpConnection); procedure StopAll; end; function NewHttpConnectionManager: HttpConnectionManager; begin result := HttpConnectionManagerImpl.Create; end; procedure ManageHttpConnection(const Connection: HttpConnection; const ConnectionManager: HttpConnectionManager); var assoc: HttpConnectionManagerAssociation; begin assoc := ConnectionManager as HttpConnectionManagerAssociation; assoc.Manage(Connection); end; procedure RemoveHttpConnection(const Connection: HttpConnection; const ConnectionManager: HttpConnectionManager); var assoc: HttpConnectionManagerAssociation; begin assoc := ConnectionManager as HttpConnectionManagerAssociation; assoc.Remove(Connection); end; { HttpConnectionManagerImpl } constructor HttpConnectionManagerImpl.Create; begin inherited Create; FConnections := THttpConnectionSet.Create; end; destructor HttpConnectionManagerImpl.Destroy; begin StopAll; FConnections.Free; inherited; end; procedure HttpConnectionManagerImpl.Manage(const Connection: HttpConnection); begin FConnections.Add(Connection); end; procedure HttpConnectionManagerImpl.Remove(const Connection: HttpConnection); begin FConnections.Remove(Connection); end; procedure HttpConnectionManagerImpl.StopAll; var con: HttpConnection; begin for con in Connections do begin con.Stop; Remove(con); end; end; end.
unit uFiguraInterface; interface uses Graphics, Windows, Classes, uType; type IFigura = interface ['{2B2C658F-3C20-44D5-9341-7FEB09000F85}'] procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; // function GetPos : TFiguraPos; function GetLeftPoint : TPoint; function GetRightPoint: TPoint; function GetDownPoint : TPoint; function GetColor: TColor; procedure SetColor(const Value: TColor); property Color : TColor read GetColor write SetColor; end; IFiguraRotate = interface(IFigura) ['{2FDB1CFD-F67F-4DE1-BE44-D09F9A488B20}'] function GetFiguraState: TFiguraState; procedure SetState(const Value: TFiguraState); property State : TFiguraState read GetFiguraState write SetState; // procedure Rotate; end; ILine = interface(IFiguraRotate) ['{BC5DC715-B37A-4F77-B350-EC85DF8BCCF5}'] procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; End; IL = interface(IFiguraRotate) ['{F40443D4-7AFD-4D58-92EA-A974E93159BB}'] procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; End; I_l_ = interface(IFiguraRotate) ['{7888022C-3DC4-4056-B959-08126AECD648}'] procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; End; IRect = interface(IFigura) ['{9A646174-2780-412F-AC92-C63EBC8AFBB4}'] procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; End; IPoint = interface(IFigura) ['{423DAD07-5F7A-4592-8F84-3960BA9CA7C3}'] // procedure Preview(ACanvas: TCanvas); procedure Draw; procedure MoveLeft; procedure MoveRight; procedure MoveDown; End; function GetIFigura(AType: TFiguraType; APosition: Integer): IFigura; implementation uses uFigura; function GetIFigura(AType: TFiguraType; APosition: Integer): IFigura; begin Result := GetFigura(AType, APosition); end; end.
unit TestUCalculadora; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, math, UIcalculadora, UIObserverCalculos, Ucalculadora, UCalculadoraImpostos, strutils; type TObserverMock = class(TInterfacedObject, IObserverCalculos) public procedure NotifyDetalhe(value: string); procedure NotifyResultado(value: string); end; // Test methods for class TCalculadora TestTCalculadora = class(TTestCase) strict private FCalculadora: TCalculadoraImpostos; FObserver: TObserverMock; private public procedure SetUp; override; procedure TearDown; override; published procedure TesteSoma; procedure TesteSubtracao; procedure TesteDivisao; procedure TesteDivisaoZero; procedure TesteDivisaoZero2; procedure TesteMultiplicacao; procedure TesteLimparVariaveis; procedure TesteSomaSubtracao(); procedure TesteSomaSubtracaoDivisaoMultiplicacao(); procedure TesteSomaTotalizaSubtrai(); procedure TesteSomaTotalizaSubtrai_ComValorAntesDeOperacao(); procedure TesteImposto1; procedure TesteImposto2; procedure TesteImposto3; end; var ValorDetalhe: string; ValorResultado: String; implementation uses System.SysUtils; procedure TestTCalculadora.SetUp; begin FCalculadora := TCalculadoraImpostos.Create(TCalculadora.Create()); FObserver := TObserverMock.Create; FCalculadora.AdicionaObserver(FObserver); end; procedure TestTCalculadora.TearDown; begin FCalculadora.Free; FCalculadora := nil; end; procedure TestTCalculadora.TesteDivisao; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('/'); FCalculadora.Comando('3'); FCalculadora.Comando('='); assert(valorresultado='4'); end; procedure TestTCalculadora.TesteDivisaoZero; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('/'); FCalculadora.Comando('0'); FCalculadora.Comando('='); assert(valorresultado='0', 'Teste 1 de divisão por zero'); end; procedure TestTCalculadora.TesteDivisaoZero2; begin FCalculadora.Comando('0'); FCalculadora.Comando('/'); FCalculadora.Comando('2'); FCalculadora.Comando('='); assert(valorresultado='0', 'Teste 2 de divisão por zero'); end; procedure TestTCalculadora.TesteLimparVariaveis; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('*'); FCalculadora.Comando('3'); FCalculadora.Comando('='); FCalculadora.Comando('cls'); assert( strtocurr(valorresultado)=strtocurr('0')); end; procedure TestTCalculadora.TesteMultiplicacao; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('*'); FCalculadora.Comando('3'); FCalculadora.Comando('='); assert(valorresultado='36'); end; procedure TestTCalculadora.TesteSoma; var value: string; begin // TODO: Setup method call parameters FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('+'); FCalculadora.Comando('3'); FCalculadora.Comando('='); assert(valorresultado='15'); // TODO: Validate method results end; procedure TestTCalculadora.TesteSomaSubtracao; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('+'); FCalculadora.Comando('3'); FCalculadora.Comando('-'); FCalculadora.Comando('5'); FCalculadora.Comando('='); assert(valorresultado='10'); end; procedure TestTCalculadora.TesteSomaSubtracaoDivisaoMultiplicacao; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('+'); FCalculadora.Comando('3'); FCalculadora.Comando('-'); FCalculadora.Comando('5'); FCalculadora.Comando('/'); FCalculadora.Comando('2'); FCalculadora.Comando('*'); FCalculadora.Comando('3'); FCalculadora.Comando('='); assert(valorresultado='15'); end; procedure TestTCalculadora.TesteSomaTotalizaSubtrai; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('+'); FCalculadora.Comando('3'); FCalculadora.Comando('='); FCalculadora.Comando('-'); FCalculadora.Comando('5'); FCalculadora.Comando('='); assert(valorresultado='10'); end; procedure TestTCalculadora.TesteSomaTotalizaSubtrai_ComValorAntesDeOperacao; begin FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('+'); FCalculadora.Comando('3'); FCalculadora.Comando('='); FCalculadora.Comando('9'); FCalculadora.Comando('-'); FCalculadora.Comando('5'); FCalculadora.Comando('='); assert(valorresultado='10'); end; procedure TestTCalculadora.TesteImposto1; begin FCalculadora.Comando('1'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando(imposto1); assert(valorresultado='1500,00'); end; procedure TestTCalculadora.TesteImposto2; begin FCalculadora.Comando('1'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando(imposto2); assert(valorresultado='1485,00'); end; procedure TestTCalculadora.TesteImposto3; begin FCalculadora.Comando('1'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando('0'); FCalculadora.Comando(imposto3); assert(valorresultado='2985,00'); end; procedure TestTCalculadora.TesteSubtracao; var value: string; begin // TODO: Setup method call parameters FCalculadora.Comando('1'); FCalculadora.Comando('2'); FCalculadora.Comando('-'); FCalculadora.Comando('3'); FCalculadora.Comando('='); assert(valorresultado='9'); // TODO: Validate method results end; { ObserverMock } procedure TObserverMock.NotifyDetalhe(value: string); begin ValorDetalhe := value; end; procedure TObserverMock.NotifyResultado(value: string); begin ValorResultado := value; end; initialization // Register any test cases with the test runner RegisterTest(TestTCalculadora.Suite); end.
unit UIDemo2Window; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UI.Aero.Core, UI.Aero.Window, UI.Aero.Core.BaseControl, UI.Aero.Core.CustomControl, UI.Aero.PageManager, UI.Aero.StatusBox, UI.Aero.ThemeElement, UI.Aero.Core.CustomControl.Animation, UI.Aero.Composition, ExtCtrls, StdCtrls; type TDemo2Window = class(TForm) AeroPageManager1: TAeroPageManager; AeroWindow1: TAeroWindow; AeroStatusBar: TAeroThemeElement; statusFiles: TAeroStatusBox; statusSelectedFiles: TAeroStatusBox; statusVersionCheck: TAeroStatusButton; statusArchiveButton: TAeroStatusButton; statusGameName: TAeroStatusBox; statusPlatform: TAeroStatusBox; AeroStatusBox1: TAeroStatusBox; AeroAnimationComposition1: TAeroAnimationComposition; AnimTimer: TTimer; DemoAnim1: TAeroAnimationComposition; procedure AnimTimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Demo2Window: TDemo2Window; implementation uses UI.Aero.Globals; {$R *.dfm} procedure TDemo2Window.AnimTimerTimer(Sender: TObject); begin if DemoAnim1.CurrentItem = 3 then begin DemoAnim1.CurrentItem:= 0; case Random(3) of 0: DemoAnim1.FontCollection[0].Font.Color:= clBlack; 1: DemoAnim1.FontCollection[0].Font.Color:= clMaroon; 2: DemoAnim1.FontCollection[0].Font.Color:= clNavy; 3: DemoAnim1.FontCollection[0].Font.Color:= clGreen; end; end else DemoAnim1.CurrentItem:= DemoAnim1.CurrentItem+1; end; procedure TDemo2Window.FormCreate(Sender: TObject); begin Randomize; DemoAnim1.Items.Add; DemoAnim1.Items.Add; DemoAnim1.Items.Add; DemoAnim1.Items.Add; // with DemoAnim1.Items[0].Composition.Add do begin Top:= 0; Left:= 0; Width:= DemoAnim1.Width; Height:= DemoAnim1.Height; FirstDraw:= cdText; Text.FontIndex:= 0; Text.Text:= 'Demo Anim'; Text.Alignment:= taCenter; Text.Layout:= tlCenter; end; with DemoAnim1.Items[1].Composition.Add do begin Top:= 0; Left:= 0; Width:= DemoAnim1.Width; Height:= DemoAnim1.Height; FirstDraw:= cdText; Text.FontIndex:= 0; Text.Text:= '(Demo Anim)'; Text.Alignment:= taCenter; Text.Layout:= tlCenter; end; with DemoAnim1.Items[2].Composition.Add do begin Top:= 0; Left:= 0; Width:= DemoAnim1.Width; Height:= DemoAnim1.Height; FirstDraw:= cdText; Text.FontIndex:= 0; Text.Text:= '( Demo Anim )'; Text.Alignment:= taCenter; Text.Layout:= tlCenter; end; with DemoAnim1.Items[3].Composition.Add do begin Top:= 0; Left:= 0; Width:= DemoAnim1.Width; Height:= DemoAnim1.Height; FirstDraw:= cdText; Text.FontIndex:= 0; Text.Text:= '( Demo Anim )'; Text.Alignment:= taCenter; Text.Layout:= tlCenter; end; /////// end; initialization begin TAeroBasePageManager.ImageFile_Left:= '..\..\..\Resources\Images\PagesLeft.png'; TAeroBasePageManager.ImageFile_Right:= '..\..\..\Resources\Images\PagesRight.png'; TAeroBaseStatusBox.BandImageLeft:= '..\..\..\Resources\Images\band-left.png'; TAeroBaseStatusBox.BandImageCenter:= '..\..\..\Resources\Images\band-center.png'; TAeroBaseStatusBox.BandImageRight:= '..\..\..\Resources\Images\band-right.png'; TAeroBaseStatusBox.BandImageBreak:= '..\..\..\Resources\Images\band-break.png'; TAeroBaseStatusBox.BandImageLight:= '..\..\..\Resources\Images\band-light.png'; end end.
{ Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Livebindings) @created(29 Nov 2020) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Telegram : @IsaquePinheiro) } unit ormbr.livebindings; interface uses RTTI, Classes, SysUtils, Controls, TypInfo, Bindings.Expression, Bindings.Helper, Data.Bind.Components, Data.Bind.ObjectScope; type // TBindingsListHack = class(TBindingsList); LiveBindingsControl = class(TCustomAttribute) private FLinkControl: String; FFieldName: String; FExpression: String; public constructor Create(const ALinkControl, AFieldName, AExpression: String); overload; constructor Create(const ALinkControl, AFieldName: String); overload; property LinkControl: String read FLinkControl; property FieldName: String read FFieldName; property Expression: String read FExpression; end; TORMBrLivebindings = class(TObject) private // FAdapterBindSource: TAdapterBindSource; // FBindingsList: TBindingsList; // procedure DoCreateAdapter(Sender: TObject; var ABindSourceAdapter: TBindSourceAdapter); public constructor Create; virtual; destructor Destroy; override; end; implementation uses ormbr.controls.helpers; constructor TORMBrLiveBindings.Create; var LContext: TRttiContext; LType: TRttiType; LProperty: TRttiProperty; LCustomAttribute: TCustomAttribute; LLiveBindingsControl: LiveBindingsControl; LControl: TControl; LExpression: String; begin // // AdapterBindSource // FAdapterBindSource := TAdapterBindSource.Create(nil); // // BindingsList // FBindingsList := TBindingsList.Create(nil); // TBindingsListHack(FBindingsList).AddBindComp(nil); LContext := TRttiContext.Create; try LType := LContext.GetType(Self.ClassType); if LType = nil then Exit; for LProperty in LType.GetProperties do begin for LCustomAttribute in LProperty.GetAttributes do begin if not (LCustomAttribute is LiveBindingsControl) then Continue; LLiveBindingsControl := LiveBindingsControl(LCustomAttribute); // Get Component LControl := TListControls.ListComponents.Items[LLiveBindingsControl.LinkControl] as TControl; if LControl = nil then raise Exception.Create('Component [' + LLiveBindingsControl.LinkControl + '] not found!'); // Expression do atributo LExpression := LLiveBindingsControl.Expression; if LExpression = '' then LExpression := Self.ClassName + '.' + LProperty.Name; // Add Components List TListControls.ListFieldNames.AddOrSetValue(LLiveBindingsControl.LinkControl, LLiveBindingsControl.FieldName); // Registro no LiveBindings TBindings.CreateManagedBinding( [ TBindings.CreateAssociationScope( [Associate(Self, Self.ClassName)]) ], LExpression, [ TBindings.CreateAssociationScope( [Associate(LControl, LLiveBindingsControl.LinkControl)]) ], LLiveBindingsControl.LinkControl + '.' + LLiveBindingsControl.FieldName, nil); // Component TBindings.CreateManagedBinding( [ TBindings.CreateAssociationScope( [Associate(LControl, LLiveBindingsControl.LinkControl)]) ], LLiveBindingsControl.LinkControl + '.' + LLiveBindingsControl.FieldName, [ TBindings.CreateAssociationScope( [Associate(Self, Self.ClassName)]) ], Self.ClassName + '.' + LProperty.Name, nil); end; end; finally LContext.Free; end; end; { LiveBindingControl } constructor LiveBindingsControl.Create(const ALinkControl, AFieldName, AExpression: String); begin FLinkControl := ALinkControl; FFieldName := AFieldName; FExpression := AExpression; end; constructor LiveBindingsControl.Create(const ALinkControl, AFieldName: String); begin Create(ALinkControl, AFieldName, ''); end; destructor TORMBrLivebindings.Destroy; begin // FAdapterBindSource.Free; inherited; end; //procedure TORMBrLivebindings.DoCreateAdapter(Sender: TObject; // var ABindSourceAdapter: TBindSourceAdapter); //begin //// ABindSourceAdapter := TListBindSourceAdapter<TORMBrLivebindings>.Create(; //end; end.
unit uBigIDESmartSave; interface uses Windows, Forms, Controls, Classes, Menus, Dialogs, SysUtils, ToolsAPI, Actnlist, Registry; // List of supported IDE functions to override type TIDEAction = (aSaveAll); TIDEActions = set of TIDEAction; // Array of id's to match an action with const ActionId: array[TIDEAction] of String = ('FileSaveAllCommand'); // General class type TBigIDEOverrides = class(TInterfacedObject, IOTAWizard, IOTAMenuWizard) private FOldHandler: array[TIDEAction] of TNotifyEvent; FOverrides: TIDEActions; function GetOverrides: TIDEActions; procedure SetOverrides(const Value: TIDEActions); protected // Action Handlers procedure DoSaveAll(Sender: TObject); virtual; protected // Hooks function GetAllActionsList: String; function FindAction(Id: String): TContainedAction; procedure HookAction(Action: TIDEAction); procedure UnhookAction(Action: TIDEAction); protected // IOTANotifier procedure AfterSave; procedure BeforeSave; procedure Destroyed; procedure Modified; // IOTAWizard { Expert UI strings } function GetIDString: string; function GetName: string; function GetState: TWizardState; { Launch the AddIn } procedure Execute; // IOTAMenuWizard. Temporary. Add menu item in more flexible way later. function GetMenuText: string; protected // Settings procedure LoadActionsFromRegistry; virtual; public constructor Create; virtual; destructor Destroy; override; property Overrides: TIDEActions read GetOverrides write SetOverrides; end; procedure Register; implementation procedure Register; begin RegisterPackageWizard(TBigIDEOverrides.Create as IOTAWizard); end; { TBigIDEOverrides } // These methods need not be implemented, but are required by the wizard interface procedure TBigIDEOverrides.AfterSave; begin end; procedure TBigIDEOverrides.BeforeSave; begin end; procedure TBigIDEOverrides.Destroyed; begin end; procedure TBigIDEOverrides.Modified; begin end; constructor TBigIDEOverrides.Create; begin inherited; // Hook already (defaults) Overrides := [aSaveAll]; // Make possible to disable some by registry settings. LoadActionsFromRegistry end; destructor TBigIDEOverrides.Destroy; begin // Don't forget to restore all actions to normal, else you will get AV's when // unloading this wizard and then using any of the actions. Overrides := []; inherited; end; function TBigIDEOverrides.GetAllActionsList: String; // Development feature, lists the names (and captions) of all actions. var l: Integer; function GetComponentList(p: TComponent): String; var c: TComponent; i: Integer; s: String; begin if l = -1 then Result := #13#10#13#10'APPLICATION COMPONENT LIST'#13#10; Inc(l); try for i := 0 to p.ComponentCount - 1 do begin c := p.Components[i]; s := #13#10 + c.ClassName + ' ('+c.Name+') '; if c is TControl then s := s + TAction(c).Caption; // Just about any control will do to reach text or caption Result := Result + s + GetComponentList(c); end; finally Dec(l); end; end; var MenuService: INTAServices; i: Integer; s: String; c: String; a: TCustomAction; ShortCut: String; begin l := -1; MenuService := BorlandIDEServices as INTAServices; s := ''; for i := 0 to MenuService.ActionList.ActionCount - 1 do begin c := ''; ShortCut := ''; if MenuService.ActionList.Actions[i] is TCustomAction then begin a := TCustomAction(MenuService.ActionList.Actions[i]); c := a.Caption; ShortCut := Format('(%s)', [ShortCutToText(a.ShortCut)]); end; if (MenuService.ActionList.Actions[i] is TAction) then begin end; // List name and caption for each action s := s + Format('%s, %s %s'#13#10, [ MenuService.ActionList.Actions[i].Name, c, ShortCut]); end; Result := s + GetComponentList(Application); end; // Some info about and config for this wizard. function TBigIDEOverrides.GetIDString: string; begin // Unique id. Company.package.wizardname by convention Result := 'GolezTrol.BigIDETools.ActionOverride'; end; function TBigIDEOverrides.GetName: string; begin // What is this name used for? Result := 'Big IDE Action Override'; end; function TBigIDEOverrides.GetMenuText: string; begin // Debug menu item to show the list of actions from Result := 'IDE Action List'; end; function TBigIDEOverrides.GetState: TWizardState; begin // Enable the debug menu item Result := [wsEnabled]; end; procedure TBigIDEOverrides.Execute; begin // Debug feature. The IDE Action List menu shows a list of actions ShowMessage(GetAllActionsList); end; function TBigIDEOverrides.FindAction(Id: String): TContainedAction; var MenuService: INTAServices; i: Integer; begin // Get the action list of the MenuService and find actions by their name. MenuService := BorlandIDEServices as INTAServices; for i := 0 to MenuService.ActionList.ActionCount - 1 do if SameText(MenuService.ActionList.Actions[i].Name, Id) then begin Result := MenuService.ActionList.Actions[i]; Exit; end; Result := nil; end; // The overrides property allows to put an entire set of actions to override. // It also allows -ofcourse- to read the set of currently overridden actions. function TBigIDEOverrides.GetOverrides: TIDEActions; begin Result := FOverrides; end; procedure TBigIDEOverrides.SetOverrides(const Value: TIDEActions); var i: TIDEAction; begin // Just walk the set and call hook or unhook for each action. These methods // will just ignore the call if the action is or isn't already hooked. for i := Low(TIDEAction) to High(TIDEAction) do if i in FOverrides then UnhookAction(i) else HookAction(i); end; procedure TBigIDEOverrides.HookAction(Action: TIDEAction); // Hook a single action var a: TContainedAction; begin // If hooked already, do nothing if not (Action in FOverrides) then begin // Find the action a := FindAction(ActionId[Action]); if Assigned(a) then begin // Store its old execute procedure FOldHandler[Action] := a.OnExecute; // Set a new event handler case Action of aSaveAll: a.OnExecute := DoSaveAll; else raise Exception.Create('Unsupported action to override'); end; // And remember that we have overridden this action Include(FOverrides, Action); end; end; end; procedure TBigIDEOverrides.LoadActionsFromRegistry; // In case any collegue finds it undesirable to overrule any action, make it // possible to disable the action in the registry. var i : TIDEAction; Actions : TIDEActions; Active : Boolean; begin Actions := Overrides; with TRegistry.Create(KEY_READ) do try if OpenKeyReadOnly('\Software\GolezTrol\Big IDE Actions\1.0\Actions\') then begin for i := Low(TIDEAction) to High(TIDEAction) do begin // If the name exists in the registry, its value is read or (on failure) // defaulted to false. If the name does not exist, the state is unchanged. if ValueExists(ActionId[i]) then begin try Active := ReadBool(ActionId[i]); except Active := False; end; if Active then Include(Actions, i) else Exclude(Actions, i); end; end; end; finally Free; end; // Set the actions if Actions <> Overrides then Overrides := Actions; end; procedure TBigIDEOverrides.UnhookAction(Action: TIDEAction); // Unhook a single previously hooked action var a: TContainedAction; begin // If not hooked, do nothing if (Action in FOverrides) then begin // Find the action and restore its event handler a := FindAction(ActionId[Action]); if Assigned(a) then a.OnExecute := FOldHandler[Action]; // Remove this action from the set of hooked actions Exclude(FOverrides, Action); end; end; // ======================================== // // === Action handlers below this point === // // ======================================== // procedure TBigIDEOverrides.DoSaveAll(Sender: TObject); const SaveResultGroup = 'Big SaveAll'; var Modules : IOTAModuleServices; Module : IOTAModule; i, j : Integer; NotSaved : TStringList; Modified : Boolean; FileName : String; Group : IOTAMessageGroup; p : Pointer; Shown : Boolean; begin NotSaved := TStringList.Create; try Modules := (BorlandIDEServices as IOTAModuleServices); for i := 0 to Modules.ModuleCount - 1 do begin Module := Modules.Modules[i]; Modified := False; for j := 0 to Module.ModuleFileCount - 1 do if Module.ModuleFileEditors[j].Modified then begin // Use the filename of the first file that could not be saved. // This might prevent confusion when a pas file is read-only while // its dfm is not. FileName := Module.ModuleFileEditors[j].FileName; Modified := True; Break; end; // If any of the files of the module is modified, try and save. if Modified then begin try // Save returns True if the module is saved and... raises an // exception when it cannot save the file. if not Module.Save(False, True) then raise Exception.Create('You''ll probably never get this exception. Save raises an exception itself, although its boolean result might suggest otherwise...'); except // Do nothing yet. //NotSaved.Add(FileName); end; end; end; // After trying to save all units, check them again to be modified. // Each unit that is modified now, can't really be saved. for i := 0 to Modules.ModuleCount - 1 do begin Module := Modules.Modules[i]; Modified := False; for j := 0 to Module.ModuleFileCount - 1 do if Module.ModuleFileEditors[j].Modified then begin FileName := Module.ModuleFileEditors[j].FileName; Modified := True; Break; end; if Modified then NotSaved.Add(FileName); end; // Some feedback to the user. Group := (BorlandIDEServices as IOTAMessageServices60).GetGroup(SaveResultGroup); // Clear previous results (BorlandIDEServices as IOTAMessageServices60).RemoveMessageGroup(Group); Group := nil; // If any files are not saved, show them here. if NotSaved.Count > 0 then begin NotSaved.Sort; // Message box? //MessageBox((BorlandIDEServices as IOTAServices).GetParentHandle, PChar('The following units could not be saved:'#13#10 + NotSaved.Text), 'Big IDE Smart Save All', MB_ICONERROR or MB_OK); // Show group? This seems to be done automatically. Anyway, don't do it explicitly. // After all, the user won't usually be interested in this information, since all // files that are edited in a 'checked out' state can be saved as well. Other edits // Are implicit edits or small tests that shouldn't be saved. // The user will see by the units icon that it is not saved. //if AShowGroup then // (BorlandIDEServices as IOTAMessageServices60).ShowMessageView(Result); Shown := False; for i := 0 to NotSaved.Count - 1 do begin if not Shown then begin if Group = nil then Group := (BorlandIDEServices as IOTAMessageServices60).AddMessageGroup(SaveResultGroup); (BorlandIDEServices as IOTAMessageServices60).ShowMessageView(Group); Shown := True; end; (BorlandIDEServices as IOTAMessageServices60).AddToolMessage(NotSaved[i], '', 'Not saved', -1, 0, nil, p, Group); end; end; finally NotSaved.Free; end; end; end.
uses Actor; type THumActor = class (TActor)//Size: 0x27C Address: 0x00475BB8 private m_HairSurface :TDirectDrawSurface; //0x250 //0x240 m_WeaponSurface :TDirectDrawSurface; //0x254 //0x244 m_HumWinSurface :TDirectDrawSurface; //0x258 //0x248 m_boWeaponEffect :Boolean; //0x25C //0x24C m_nCurWeaponEffect :Integer; //0x260 //0x250 m_nCurBubbleStruck :Integer; //0x264 //0x254 m_dwWeaponpEffectTime :LongWord; //0x268 m_boHideWeapon :Boolean; //0x26C m_nFrame :Integer; m_dwFrameTick :LongWord; m_dwFrameTime :LongWord; m_bo2D0 :Boolean; protected procedure CalcActorFrame; override; procedure DefaultMotion; override; function GetDefaultFrame (wmode: Boolean): integer; override; public constructor Create; override; destructor Destroy; override; procedure Run; override; procedure RunFrameAction (frame: integer); override; function Light: integer; override; procedure LoadSurface; override; procedure DoWeaponBreakEffect; procedure DrawChr (dsurface: TDirectDrawSurface; dx, dy: integer; blend: Boolean;boFlag:Boolean); override; end; implementation {============================== HUMActor =============================} // 荤恩 {-------------------------------} constructor THumActor.Create; begin inherited Create; m_HairSurface := nil; m_WeaponSurface := nil; m_HumWinSurface:=nil; m_boWeaponEffect := FALSE; m_dwFrameTime:=150; m_dwFrameTick:=GetTickCount(); m_nFrame:=0; m_nHumWinOffset:=0; end; destructor THumActor.Destroy; begin inherited Destroy; end; procedure THumActor.CalcActorFrame; var haircount: integer; begin m_boUseMagic := FALSE; m_boHitEffect := FALSE; m_nCurrentFrame := -1; //human m_btHair := HAIRfeature (m_nFeature); //函版等促. m_btDress := DRESSfeature (m_nFeature); m_btWeapon := WEAPONfeature (m_nFeature); m_btHorse :=Horsefeature(m_nFeatureEx); m_btEffect :=Effectfeature(m_nFeatureEx); m_nBodyOffset := HUMANFRAME * (m_btDress); //m_btSex; //巢磊0, 咯磊1 haircount := g_WHairImgImages.ImageCount div HUMANFRAME div 2; if m_btHair > haircount-1 then m_btHair := haircount-1; m_btHair := m_btHair * 2; if m_btHair > 1 then m_nHairOffset := HUMANFRAME * (m_btHair + m_btSex) else m_nHairOffset := -1; m_nWeaponOffset := HUMANFRAME * m_btWeapon; //(weapon*2 + m_btSex); // if Dress in [1..4] then begin // if Dress in [18..21] then begin // HumWinOffset:=(Dress - 18)* HUMANFRAME; // end; if (m_btEffect = 50) then begin m_nHumWinOffset:=352; end else if m_btEffect <> 0 then m_nHumWinOffset:=(m_btEffect - 1) * HUMANFRAME; case m_nCurrentAction of SM_TURN: begin m_nStartFrame := HA.ActStand.start + m_btDir * (HA.ActStand.frame + HA.ActStand.skip); m_nEndFrame := m_nStartFrame + HA.ActStand.frame - 1; m_dwFrameTime := HA.ActStand.ftime; m_dwStartTime := GetTickCount; m_nDefFrameCount := HA.ActStand.frame; Shift (m_btDir, 0, 0, m_nEndFrame-m_nStartFrame+1); end; SM_WALK, SM_BACKSTEP: begin m_nStartFrame := HA.ActWalk.start + m_btDir * (HA.ActWalk.frame + HA.ActWalk.skip); m_nEndFrame := m_nStartFrame + HA.ActWalk.frame - 1; m_dwFrameTime := HA.ActWalk.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActWalk.UseTick; m_nCurTick := 0; //WarMode := FALSE; m_nMoveStep := 1; if m_nCurrentAction = SM_BACKSTEP then Shift (GetBack(m_btDir), m_nMoveStep, 0, m_nEndFrame-m_nStartFrame+1) else Shift (m_btDir, m_nMoveStep, 0, m_nEndFrame-m_nStartFrame+1); end; SM_RUSH: begin if m_nRushDir = 0 then begin m_nRushDir := 1; m_nStartFrame := HA.ActRushLeft.start + m_btDir * (HA.ActRushLeft.frame + HA.ActRushLeft.skip); m_nEndFrame := m_nStartFrame + HA.ActRushLeft.frame - 1; m_dwFrameTime := HA.ActRushLeft.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActRushLeft.UseTick; m_nCurTick := 0; m_nMoveStep := 1; Shift (m_btDir, 1, 0, m_nEndFrame-m_nStartFrame+1); end else begin m_nRushDir := 0; m_nStartFrame := HA.ActRushRight.start + m_btDir * (HA.ActRushRight.frame + HA.ActRushRight.skip); m_nEndFrame := m_nStartFrame + HA.ActRushRight.frame - 1; m_dwFrameTime := HA.ActRushRight.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActRushRight.UseTick; m_nCurTick := 0; m_nMoveStep := 1; Shift (m_btDir, 1, 0, m_nEndFrame-m_nStartFrame+1); end; end; SM_RUSHKUNG: begin m_nStartFrame := HA.ActRun.start + m_btDir * (HA.ActRun.frame + HA.ActRun.skip); m_nEndFrame := m_nStartFrame + HA.ActRun.frame - 1; m_dwFrameTime := HA.ActRun.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActRun.UseTick; m_nCurTick := 0; m_nMoveStep := 1; Shift (m_btDir, m_nMoveStep, 0, m_nEndFrame-m_nStartFrame+1); end; {SM_BACKSTEP: begin startframe := pm.ActWalk.start + (pm.ActWalk.frame - 1) + Dir * (pm.ActWalk.frame + pm.ActWalk.skip); m_nEndFrame := startframe - (pm.ActWalk.frame - 1); m_dwFrameTime := pm.ActWalk.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := pm.ActWalk.UseTick; m_nCurTick := 0; m_nMoveStep := 1; Shift (GetBack(Dir), m_nMoveStep, 0, m_nEndFrame-startframe+1); end; } SM_SITDOWN: begin m_nStartFrame := HA.ActSitdown.start + m_btDir * (HA.ActSitdown.frame + HA.ActSitdown.skip); m_nEndFrame := m_nStartFrame + HA.ActSitdown.frame - 1; m_dwFrameTime := HA.ActSitdown.ftime; m_dwStartTime := GetTickCount; end; SM_RUN: begin m_nStartFrame := HA.ActRun.start + m_btDir * (HA.ActRun.frame + HA.ActRun.skip); m_nEndFrame := m_nStartFrame + HA.ActRun.frame - 1; m_dwFrameTime := HA.ActRun.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActRun.UseTick; m_nCurTick := 0; //WarMode := FALSE; if m_nCurrentAction = SM_RUN then m_nMoveStep := 2 else m_nMoveStep := 1; //m_nMoveStep := 2; Shift (m_btDir, m_nMoveStep, 0, m_nEndFrame-m_nStartFrame+1); end; SM_HORSERUN: begin m_nStartFrame := HA.ActRun.start + m_btDir * (HA.ActRun.frame + HA.ActRun.skip); m_nEndFrame := m_nStartFrame + HA.ActRun.frame - 1; m_dwFrameTime := HA.ActRun.ftime; m_dwStartTime := GetTickCount; m_nMaxTick := HA.ActRun.UseTick; m_nCurTick := 0; //WarMode := FALSE; if m_nCurrentAction = SM_HORSERUN then m_nMoveStep := 3 else m_nMoveStep := 1; //m_nMoveStep := 2; Shift (m_btDir, m_nMoveStep, 0, m_nEndFrame-m_nStartFrame+1); end; SM_THROW: begin m_nStartFrame := HA.ActHit.start + m_btDir * (HA.ActHit.frame + HA.ActHit.skip); m_nEndFrame := m_nStartFrame + HA.ActHit.frame - 1; m_dwFrameTime := HA.ActHit.ftime; m_dwStartTime := GetTickCount; m_boWarMode := TRUE; m_dwWarModeTime := GetTickCount; m_boThrow := TRUE; Shift (m_btDir, 0, 0, 1); end; SM_HIT, SM_POWERHIT, SM_LONGHIT, SM_WIDEHIT, SM_FIREHIT, SM_CRSHIT, SM_TWINHIT: begin m_nStartFrame := HA.ActHit.start + m_btDir * (HA.ActHit.frame + HA.ActHit.skip); m_nEndFrame := m_nStartFrame + HA.ActHit.frame - 1; m_dwFrameTime := HA.ActHit.ftime; m_dwStartTime := GetTickCount; m_boWarMode := TRUE; m_dwWarModeTime := GetTickCount; if (m_nCurrentAction = SM_POWERHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 1; end; if (m_nCurrentAction = SM_LONGHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 2; end; if (m_nCurrentAction = SM_WIDEHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 3; end; if (m_nCurrentAction = SM_FIREHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 4; end; if (m_nCurrentAction = SM_CRSHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 6; end; if (m_nCurrentAction = SM_TWINHIT) then begin m_boHitEffect := TRUE; m_nMagLight := 2; m_nHitEffectNumber := 7; end; Shift (m_btDir, 0, 0, 1); end; SM_HEAVYHIT: begin m_nStartFrame := HA.ActHeavyHit.start + m_btDir * (HA.ActHeavyHit.frame + HA.ActHeavyHit.skip); m_nEndFrame := m_nStartFrame + HA.ActHeavyHit.frame - 1; m_dwFrameTime := HA.ActHeavyHit.ftime; m_dwStartTime := GetTickCount; m_boWarMode := TRUE; m_dwWarModeTime := GetTickCount; Shift (m_btDir, 0, 0, 1); end; SM_BIGHIT: begin m_nStartFrame := HA.ActBigHit.start + m_btDir * (HA.ActBigHit.frame + HA.ActBigHit.skip); m_nEndFrame := m_nStartFrame + HA.ActBigHit.frame - 1; m_dwFrameTime := HA.ActBigHit.ftime; m_dwStartTime := GetTickCount; m_boWarMode := TRUE; m_dwWarModeTime := GetTickCount; Shift (m_btDir, 0, 0, 1); end; SM_SPELL: begin m_nStartFrame := HA.ActSpell.start + m_btDir * (HA.ActSpell.frame + HA.ActSpell.skip); m_nEndFrame := m_nStartFrame + HA.ActSpell.frame - 1; m_dwFrameTime := HA.ActSpell.ftime; m_dwStartTime := GetTickCount; m_nCurEffFrame := 0; m_boUseMagic := TRUE; case m_CurMagic.EffectNumber of 22: begin //火墙 m_nMagLight := 4; //汾汲拳 m_nSpellFrame := 10; //汾汲拳绰 10 橇贰烙栏肺 函版 end; 26: begin //心灵启示 m_nMagLight := 2; m_nSpellFrame := 20; m_dwFrameTime := m_dwFrameTime div 2; end; 35: begin // m_nMagLight := 2; m_nSpellFrame := 15; end; 43: begin //狮子吼 m_nMagLight := 2; m_nSpellFrame := 20; end; else begin //..... 措雀汗贱, 荤磊辣雀, 葫汲浅 m_nMagLight := 2; m_nSpellFrame := DEFSPELLFRAME; end; end; m_dwWaitMagicRequest := GetTickCount; m_boWarMode := TRUE; m_dwWarModeTime := GetTickCount; Shift (m_btDir, 0, 0, 1); end; (*SM_READYFIREHIT: begin startframe := HA.ActFireHitReady.start + Dir * (HA.ActFireHitReady.frame + HA.ActFireHitReady.skip); m_nEndFrame := startframe + HA.ActFireHitReady.frame - 1; m_dwFrameTime := HA.ActFireHitReady.ftime; m_dwStartTime := GetTickCount; BoHitEffect := TRUE; HitEffectNumber := 4; MagLight := 2; CurGlimmer := 0; MaxGlimmer := 6; WarMode := TRUE; WarModeTime := GetTickCount; Shift (Dir, 0, 0, 1); end; *) SM_STRUCK: begin m_nStartFrame := HA.ActStruck.start + m_btDir * (HA.ActStruck.frame + HA.ActStruck.skip); m_nEndFrame := m_nStartFrame + HA.ActStruck.frame - 1; m_dwFrameTime := m_dwStruckFrameTime; //HA.ActStruck.ftime; m_dwStartTime := GetTickCount; Shift (m_btDir, 0, 0, 1); m_dwGenAnicountTime := GetTickCount; m_nCurBubbleStruck := 0; end; SM_NOWDEATH: begin m_nStartFrame := HA.ActDie.start + m_btDir * (HA.ActDie.frame + HA.ActDie.skip); m_nEndFrame := m_nStartFrame + HA.ActDie.frame - 1; m_dwFrameTime := HA.ActDie.ftime; m_dwStartTime := GetTickCount; end; end; end; procedure THumActor.DefaultMotion; begin inherited DefaultMotion; if (m_btEffect = 50) then begin if (m_nCurrentFrame <= 536) then begin if (GetTickCount - m_dwFrameTick) > 100 then begin if m_nFrame < 19 then Inc(m_nFrame) else begin if not m_bo2D0 then m_bo2D0:=True else m_bo2D0:=False; m_nFrame:=0; end; m_dwFrameTick:=GetTickCount(); end; m_HumWinSurface:=FrmMain.WEffectImg.GetCachedImage (m_nHumWinOffset + m_nFrame, m_nSpx, m_nSpy); end; end else if (m_btEffect <> 0) then begin if m_nCurrentFrame < 64 then begin if (GetTickCount - m_dwFrameTick) > m_dwFrameTime then begin if m_nFrame < 7 then Inc(m_nFrame) else m_nFrame:=0; m_dwFrameTick:=GetTickCount(); end; m_HumWinSurface:=g_WHumWingImages.GetCachedImage (m_nHumWinOffset+ (m_btDir * 8) + m_nFrame, m_nSpx, m_nSpy); end else begin m_HumWinSurface:=g_WHumWingImages.GetCachedImage (m_nHumWinOffset + m_nCurrentFrame, m_nSpx, m_nSpy); end; end; end; function THumActor.GetDefaultFrame (wmode: Boolean): integer; var cf, dr: integer; pm: PTMonsterAction; begin //GlimmingMode := FALSE; //dr := Dress div 2; //HUMANFRAME * (dr) if m_boDeath then Result := HA.ActDie.start + m_btDir * (HA.ActDie.frame + HA.ActDie.skip) + (HA.ActDie.frame - 1) else if wmode then begin //GlimmingMode := TRUE; Result := HA.ActWarMode.start + m_btDir * (HA.ActWarMode.frame + HA.ActWarMode.skip); end else begin m_nDefFrameCount := HA.ActStand.frame; if m_nCurrentDefFrame < 0 then cf := 0 else if m_nCurrentDefFrame >= HA.ActStand.frame then cf := 0 //HA.ActStand.frame-1 else cf := m_nCurrentDefFrame; Result := HA.ActStand.start + m_btDir * (HA.ActStand.frame + HA.ActStand.skip) + cf; end; end; procedure THumActor.RunFrameAction (frame: integer); var meff: TMapEffect; event: TClEvent; mfly: TFlyingAxe; begin m_boHideWeapon := FALSE; if m_nCurrentAction = SM_HEAVYHIT then begin if (frame = 5) and (m_boDigFragment) then begin m_boDigFragment := FALSE; meff := TMapEffect.Create (8 * m_btDir, 3, m_nCurrX, m_nCurrY); meff.ImgLib := FrmMain.WEffectImg; meff.NextFrameTime := 80; PlaySound (s_strike_stone); //PlaySound (s_drop_stonepiece); PlayScene.m_EffectList.Add (meff); event := EventMan.GetEvent (m_nCurrX, m_nCurrY, ET_PILESTONES); if event <> nil then event.m_nEventParam := event.m_nEventParam + 1; end; end; if m_nCurrentAction = SM_THROW then begin if (frame = 3) and (m_boThrow) then begin m_boThrow := FALSE; mfly := TFlyingAxe (PlayScene.NewFlyObject (self, m_nCurrX, m_nCurrY, m_nTargetX, m_nTargetY, m_nTargetRecog, mtFlyAxe)); if mfly <> nil then begin TFlyingAxe(mfly).ReadyFrame := 40; mfly.ImgLib := FrmMain.WMon3Img; mfly.FlyImageBase := FLYOMAAXEBASE; end; end; if frame >= 3 then m_boHideWeapon := TRUE; end; end; procedure THumActor.DoWeaponBreakEffect; begin m_boWeaponEffect := TRUE; m_nCurWeaponEffect := 0; end; procedure THumActor.Run; function MagicTimeOut: Boolean; begin if self = g_MySelf then begin Result := GetTickCount - m_dwWaitMagicRequest > 3000; end else Result := GetTickCount - m_dwWaitMagicRequest > 2000; if Result then m_CurMagic.ServerMagicCode := 0; end; var prv: integer; m_dwFrameTimetime: longword; bofly: Boolean; begin if GetTickCount - m_dwGenAnicountTime > 120 then begin //林贱狼阜 殿... 局聪皋捞记 瓤苞 m_dwGenAnicountTime := GetTickCount; Inc (m_nGenAniCount); if m_nGenAniCount > 100000 then m_nGenAniCount := 0; Inc (m_nCurBubbleStruck); end; if m_boWeaponEffect then begin //公扁 氢惑/何辑咙 瓤苞 if GetTickCount - m_dwWeaponpEffectTime > 120 then begin m_dwWeaponpEffectTime := GetTickCount; Inc (m_nCurWeaponEffect); if m_nCurWeaponEffect >= MAXWPEFFECTFRAME then m_boWeaponEffect := FALSE; end; end; if (m_nCurrentAction = SM_WALK) or (m_nCurrentAction = SM_BACKSTEP) or (m_nCurrentAction = SM_RUN) or (m_nCurrentAction = SM_HORSERUN) or (m_nCurrentAction = SM_RUSH) or (m_nCurrentAction = SM_RUSHKUNG) then exit; m_boMsgMuch := FALSE; if self <> g_MySelf then begin if m_MsgList.Count >= 2 then m_boMsgMuch := TRUE; end; //荤款靛 瓤苞 RunActSound (m_nCurrentFrame - m_nStartFrame); RunFrameAction (m_nCurrentFrame - m_nStartFrame); prv := m_nCurrentFrame; if m_nCurrentAction <> 0 then begin if (m_nCurrentFrame < m_nStartFrame) or (m_nCurrentFrame > m_nEndFrame) then m_nCurrentFrame := m_nStartFrame; if (self <> g_MySelf) and (m_boUseMagic) then begin m_dwFrameTimetime := Round(m_dwFrameTime / 1.8); end else begin if m_boMsgMuch then m_dwFrameTimetime := Round(m_dwFrameTime * 2 / 3) else m_dwFrameTimetime := m_dwFrameTime; end; if GetTickCount - m_dwStartTime > m_dwFrameTimetime then begin if m_nCurrentFrame < m_nEndFrame then begin //付过牢 版快 辑滚狼 脚龋甫 罐酒, 己傍/角菩甫 犬牢茄饶 //付瘤阜悼累阑 场辰促. if m_boUseMagic then begin if (m_nCurEffFrame = m_nSpellFrame-2) or (MagicTimeOut) then begin //扁促覆 场 if (m_CurMagic.ServerMagicCode >= 0) or (MagicTimeOut) then begin //辑滚肺 何磐 罐篮 搬苞. 酒流 救吭栏搁 扁促覆 Inc (m_nCurrentFrame); Inc(m_nCurEffFrame); m_dwStartTime := GetTickCount; end; end else begin if m_nCurrentFrame < m_nEndFrame - 1 then Inc (m_nCurrentFrame); Inc (m_nCurEffFrame); m_dwStartTime := GetTickCount; end; end else begin Inc (m_nCurrentFrame); m_dwStartTime := GetTickCount; end; end else begin if self = g_MySelf then begin if FrmMain.ServerAcceptNextAction then begin m_nCurrentAction := 0; m_boUseMagic := FALSE; end; end else begin m_nCurrentAction := 0; //悼累 肯丰 m_boUseMagic := FALSE; end; m_boHitEffect := FALSE; end; if m_boUseMagic then begin if m_nCurEffFrame = m_nSpellFrame - 1 then begin //付过 惯荤 矫痢 //付过 惯荤 if m_CurMagic.ServerMagicCode > 0 then begin with m_CurMagic do PlayScene.NewMagic (self, ServerMagicCode, EffectNumber, m_nCurrX, m_nCurrY, TargX, TargY, Target, EffectType, Recusion, AniTime, bofly); if bofly then PlaySound (m_nMagicFireSound) else PlaySound (m_nMagicExplosionSound); end; if self = g_MySelf then g_dwLatestSpellTick := GetTickCount; m_CurMagic.ServerMagicCode := 0; end; end; end; if m_btRace = 0 then m_nCurrentDefFrame := 0 else m_nCurrentDefFrame := -10; m_dwDefFrameTime := GetTickCount; end else begin if GetTickCount - m_dwSmoothMoveTime > 200 then begin if GetTickCount - m_dwDefFrameTime > 500 then begin m_dwDefFrameTime := GetTickCount; Inc (m_nCurrentDefFrame); if m_nCurrentDefFrame >= m_nDefFrameCount then m_nCurrentDefFrame := 0; end; DefaultMotion; end; end; if prv <> m_nCurrentFrame then begin m_dwLoadSurfaceTime := GetTickCount; LoadSurface; end; end; function THumActor.Light: integer; var l: integer; begin l := m_nChrLight; if l < m_nMagLight then begin if m_boUseMagic or m_boHitEffect then l := m_nMagLight; end; Result := l; end; procedure THumActor.LoadSurface; begin { BodySurface := FrmMain.WHumImg.GetCachedImage (BodyOffset + m_nCurrentFrame, px, py); if HairOffset >= 0 then HairSurface := FrmMain.WHairImg.GetCachedImage (HairOffset + m_nCurrentFrame, hpx, hpy) else HairSurface := nil; WeaponSurface := FrmMain.WWeapon.GetCachedImage (WeaponOffset + m_nCurrentFrame, wpx, wpy); } //BodySurface := FrmMain.WHumImg.GetCachedImage (BodyOffset + m_nCurrentFrame, px, py); m_BodySurface := FrmMain.GetWHumImg(m_btDress, m_btSex, m_nCurrentFrame, m_nPx, m_nPy); if m_BodySurface = nil then m_BodySurface := FrmMain.GetWHumImg(0, m_btSex, m_nCurrentFrame, m_nPx, m_nPy); if m_nHairOffset >= 0 then m_HairSurface := g_WHairImgImages.GetCachedImage (m_nHairOffset + m_nCurrentFrame, m_nHpx, m_nHpy); else m_HairSurface := nil; if (m_btEffect = 50) then begin if (m_nCurrentFrame <= 536) then begin if (GetTickCount - m_dwFrameTick) > 100 then begin if m_nFrame < 19 then Inc(m_nFrame) else begin if not m_bo2D0 then m_bo2D0:=True else m_bo2D0:=False; m_nFrame:=0; end; m_dwFrameTick:=GetTickCount(); end; m_HumWinSurface:=FrmMain.WEffectImg.GetCachedImage (m_nHumWinOffset + m_nFrame, m_nSpx, m_nSpy); end; end else if (m_btEffect <> 0) then begin if m_nCurrentFrame < 64 then begin if (GetTickCount - m_dwFrameTick) > m_dwFrameTime then begin if m_nFrame < 7 then Inc(m_nFrame) else m_nFrame:=0; m_dwFrameTick:=GetTickCount(); end; m_HumWinSurface:=g_WHumWingImages.GetCachedImage (m_nHumWinOffset+ (m_btDir * 8) + m_nFrame, m_nSpx, m_nSpy); end else begin m_HumWinSurface:=g_WHumWingImages.GetCachedImage (m_nHumWinOffset + m_nCurrentFrame, m_nSpx, m_nSpy); end; end; //WeaponSurface:=FrmMain.WWeapon.GetCachedImage(WeaponOffset + m_nCurrentFrame, wpx, wpy); m_WeaponSurface:=FrmMain.GetWWeaponImg(m_btWeapon,m_btSex,m_nCurrentFrame, m_nWpx, m_nWpy); if m_WeaponSurface = nil then m_WeaponSurface:=FrmMain.GetWWeaponImg(0,m_btSex,m_nCurrentFrame, m_nWpx, m_nWpy); end; procedure THumActor.DrawChr (dsurface: TDirectDrawSurface; dx, dy: integer; blend: Boolean;boFlag:Boolean); var idx, ax, ay: integer; d: TDirectDrawSurface; cEff: TColorEffect; wimg: TWMImages; begin d:=nil;//Jacky if not (m_btDir in [0..7]) then exit; if GetTickCount - m_dwLoadSurfaceTime > 60 * 1000 then begin m_dwLoadSurfaceTime := GetTickCount; LoadSurface; //bodysurface loadsurface end; cEff := GetDrawEffectValue; if m_btRace = 0 then begin if (m_nCurrentFrame >= 0) and (m_nCurrentFrame <= 599) then m_nWpord := WORDER[m_btSex, m_nCurrentFrame]; // if Dress in [1..4] then begin // if Dress in [18..21] then begin if m_btEffect <> 0 then begin if g_MySelf = Self then begin if blend then begin if ((m_btDir = 3) or (m_btDir = 4) or (m_btDir = 5)) and (m_HumWinSurface <> nil) and not boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end else begin//0x0047CED1 if ((m_btDir = 3) or (m_btDir = 4) or (m_btDir = 5)) and (m_HumWinSurface <> nil) and boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end; end; end;//0x0047D03F end else begin;//0x0047CF4D if ((g_FocusCret <> nil) or (g_MagicTarget <> nil)) and blend and ((m_btDir = 3) or (m_btDir = 4) or (m_btDir = 5)) and (m_HumWinSurface <> nil) and not boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end else begin;//0x0047CFD4 if ((m_btDir = 3) or (m_btDir = 4) or (m_btDir = 5)) and (m_HumWinSurface <> nil) and boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end;//0x0047D03F end; end; end;//0x0047D03F if (m_nWpord = 0) and (not blend) and (m_btWeapon >= 2) and (m_WeaponSurface <> nil) and (not m_boHideWeapon) then begin DrawEffSurface (dsurface, m_WeaponSurface, dx + m_nWpx + m_nShiftX, dy + m_nWpy + m_nShiftY, blend, ceNone); //漠篮 祸捞 救函窃 DrawWeaponGlimmer (dsurface, dx + m_nShiftX, dy + m_nShiftY); //dsurface.Draw (dx + wpx + ShiftX, dy + wpy + ShiftY, WeaponSurface.ClientRect, WeaponSurface, TRUE); end; if m_BodySurface <> nil then DrawEffSurface (dsurface, m_BodySurface, dx + m_nPx + m_nShiftX, dy + m_nPy + m_nShiftY, blend, cEff); if m_HairSurface <> nil then DrawEffSurface (dsurface, m_HairSurface, dx + m_nHpx + m_nShiftX, dy + m_nHpy + m_nShiftY, blend, cEff); // if (m_nWpord = 1) and {(not blend) and} (m_btWeapon >= 2) and (m_WeaponSurface <> nil) and (not m_boHideWeapon) then begin DrawEffSurface (dsurface, m_WeaponSurface, dx + m_nWpx + m_nShiftX, dy + m_nWpy + m_nShiftY, blend, ceNone); DrawWeaponGlimmer (dsurface, dx + m_nShiftX, dy + m_nShiftY); //dsurface.Draw (dx + wpx + ShiftX, dy + wpy + ShiftY, WeaponSurface.ClientRect, WeaponSurface, TRUE); end; // if Dress in [1..4] then begin // if Dress in [18..21] then begin if (m_btEffect = 50) then begin if (m_HumWinSurface <> nil) then DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end else if m_btEffect <> 0 then begin if g_MySelf = Self then begin if blend then begin if ((m_btDir = 0) or (m_btDir = 7) or (m_btDir = 1) or (m_btDir = 6) or (m_btDir = 2)) and (m_HumWinSurface <> nil) and not boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end else begin//0x0047D27F if ((m_btDir = 0) or (m_btDir = 7) or (m_btDir = 1) or (m_btDir = 6) or (m_btDir = 2)) and (m_HumWinSurface <> nil) and boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end; end; end;// gogo 0x0047D41D end else begin;//0x0047D30D if ((g_FocusCret <> nil) or (g_MagicTarget <> nil)) and ((m_btDir = 0) or (m_btDir = 7) or (m_btDir = 1) or (m_btDir = 6) or (m_btDir = 2)) and (m_HumWinSurface <> nil) and not boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end else begin;//0x0047D3A0 if ((m_btDir = 0) or (m_btDir = 7) or (m_btDir = 1) or (m_btDir = 6) or (m_btDir = 2)) and (m_HumWinSurface <> nil) and boFlag then begin DrawBlend (dsurface, dx + m_nSpx + m_nShiftX, dy + m_nSpy + m_nShiftY, m_HumWinSurface, 1); end;//0x0047D41D end; end; end;//0x0047D41D //显示魔法盾时效果 if m_nState and $00100000{STATE_BUBBLEDEFENCEUP} <> 0 then begin //林贱狼阜 if (m_nCurrentAction = SM_STRUCK) and (m_nCurBubbleStruck < 3) then idx := MAGBUBBLESTRUCKBASE + m_nCurBubbleStruck else idx := MAGBUBBLEBASE + (m_nGenAniCount mod 3); d := g_WMagicImages.GetCachedImage (idx, ax, ay); if d <> nil then DrawBlend (dsurface, dx + ax + m_nShiftX, dy + ay + m_nShiftY, d, 1); end; end; //显示魔法效果 if m_boUseMagic {and (EffDir[Dir] = 1)} and (m_CurMagic.EffectNumber > 0) then begin if m_nCurEffFrame in [0..m_nSpellFrame-1] then begin GetEffectBase (m_CurMagic.EffectNumber-1, 0, wimg, idx); idx := idx + m_nCurEffFrame; if wimg <> nil then d := wimg.GetCachedImage (idx, ax, ay); if d <> nil then DrawBlend (dsurface, dx + ax + m_nShiftX, dy + ay + m_nShiftY, d, 1); end; end; //显示攻击效果 if m_boHitEffect and (m_nHitEffectNumber > 0) then begin GetEffectBase (m_nHitEffectNumber - 1, 1, wimg, idx); idx := idx + m_btDir*10 + (m_nCurrentFrame-m_nStartFrame); if wimg <> nil then d := wimg.GetCachedImage (idx, ax, ay); if d <> nil then DrawBlend (dsurface, dx + ax + m_nShiftX, dy + ay + m_nShiftY, d, 1); end; //显示武器破碎效果 if m_boWeaponEffect then begin idx := WPEFFECTBASE + m_btDir * 10 + m_nCurWeaponEffect; d := g_WMagicImages.GetCachedImage (idx, ax, ay); if d <> nil then DrawBlend (dsurface, dx + ax + m_nShiftX, dy + ay + m_nShiftY, d, 1); end; end; end.
unit uIncrementerThread; interface uses System.Classes , System.SysUtils , VCL.StdCtrls , uLockableIntf , uGlobalInteger ; type TIncrementerThread = class(TThread) private FLock: ILockable; FMemo: TMemo; protected procedure Execute; override; public constructor Create(aLock: ILockable; aMemo: TMemo); end; implementation { TIncrementerThread } constructor TIncrementerThread.Create(aLock: ILockable; aMemo: TMemo); begin inherited Create(False); FreeOnTerminate := True; FLock := aLock; FMemo := aMemo; end; procedure TIncrementerThread.Execute; begin i := 0; while not Terminated do begin FLock.Lock; try i := i + 1; // i is a global variable Synchronize(procedure begin FMemo.Lines.Add(i.ToString); end); Sleep(1000); finally FLock.Unlock; end; end; end; end.
{ Este exemplo foi baixado no site www.andrecelestino.com Passe por lá a qualquer momento para conferir os novos artigos! :) contato@andrecelestino.com } unit untFormulario; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, untThread; type TFrmThread = class(TForm) ProgressBar1: TProgressBar; ProgressBar2: TProgressBar; btnThread1: TBitBtn; edtTempoThread1: TEdit; edtTempoThread2: TEdit; Bevel2: TBevel; lblTempoThread1: TLabel; lblThread1: TLabel; lblThread2: TLabel; lblTempoThread2: TLabel; Bevel1: TBevel; btnThread2: TBitBtn; procedure btnThread1Click(Sender: TObject); procedure btnThread2Click(Sender: TObject); procedure FormCreate(Sender: TObject); end; var FrmThread: TFrmThread; Thread1: TMinhaThread; Thread2: TMinhaThread; implementation uses Math; {$R *.dfm} procedure TFrmThread.btnThread1Click(Sender: TObject); begin if Trim(edtTempoThread1.Text) = EmptyStr then begin MessageDlg('Preencha o tempo da Thread!', mtWarning, [mbOk], 0); edtTempoThread1.SetFocus; Exit; end; // se a Thread estiver pausada, atualiza o tempo e reinicia a execução if Thread1.Suspended then begin Thread1.Tempo := StrToInt(edtTempoThread1.Text); Thread1.Resume; btnThread1.Caption := 'Pausar'; end // senão, a Thread é pausada else begin Thread1.Suspend; btnThread1.Caption := 'Continuar'; end; end; procedure TFrmThread.btnThread2Click(Sender: TObject); begin if Trim(edtTempoThread2.Text) = EmptyStr then begin MessageDlg('Preencha o tempo da Thread!', mtWarning, [mbOk], 0); edtTempoThread2.SetFocus; Exit; end; // se a Thread estiver pausada, atualiza o tempo e reinicia a execução if Thread2.Suspended then begin Thread2.Tempo := StrToInt(edtTempoThread2.Text); Thread2.Resume; btnThread2.Caption := 'Pausar'; end // senão, a Thread é pausada else begin Thread2.Suspend; btnThread2.Caption := 'Continuar'; end; end; procedure TFrmThread.FormCreate(Sender: TObject); begin // instanciação da Thread 1 Thread1 := TMinhaThread.Create; Thread1.FreeOnTerminate := True; Thread1.ProgressBar := ProgressBar1; // instanciação da Thread 2 Thread2 := TMinhaThread.Create; Thread2.FreeOnTerminate := True; Thread2.ProgressBar := ProgressBar2; end; end.
{ ********************************************************************* * * Autor: Efimov A.A. * E-mail: infocean@gmail.com * GitHub: https://github.com/AndrewEfimov * Requirements: - * Platform: Android, Windows * IDE: Delphi 10.1 Berlin + * ******************************************************************** } unit uArrayHelper; interface uses System.Math, System.SysUtils; type TArrayHelper = class public /// <summary>Создаём массив (длина - ALength) и заполняем по порядку начиная с AStart, перемешиваем массив</summary> class function CreateMixIntArray(const AStart, ALength: Integer): TArray<Integer>; /// <summary>Создаём массив (длина - ALength) и заполняем рандомными неповторяющимися числами в промежутке от AFrom до ATo</summary> class function CreateRandIntArray(const AFrom, ATo, ALength: Integer): TArray<Integer>; /// <summary>Перемешиваем значения массива любого типа</summary> class procedure MixArray<T>(var AArray: TArray<T>); end; implementation { TArrayHelper } class function TArrayHelper.CreateMixIntArray(const AStart, ALength: Integer): TArray<Integer>; var I: Integer; begin SetLength(Result, ALength); // Initialize array for I := Low(Result) to High(Result) do Result[I] := AStart + I; // Mix array MixArray<Integer>(Result); end; class function TArrayHelper.CreateRandIntArray(const AFrom, ATo, ALength: Integer): TArray<Integer>; var I, J: Integer; begin if (ATo - AFrom + 1) < ALength then raise Exception.Create('Диапазон меньше длины массива'); SetLength(Result, ALength); for I := Low(Result) to High(Result) do begin Result[I] := RandomRange(AFrom, ATo + 1); // Check for duplicates J := 0; while J < I do if Result[J] = Result[I] then begin Result[I] := RandomRange(AFrom, ATo + 1); J := 0; end else Inc(J); end; end; class procedure TArrayHelper.MixArray<T>(var AArray: TArray<T>); var I, RandomIndex: Integer; TempValue: T; begin for I := Low(AArray) to High(AArray) do begin RandomIndex := RandomRange(Low(AArray), High(AArray) + 1); TempValue := AArray[I]; AArray[I] := AArray[RandomIndex]; AArray[RandomIndex] := TempValue; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ActnList; const Beg_X = 336; Beg_Y = 301; Beg_Angle = 0; PointsCount = 12; type TPoint = record x, y :real; // координаты точки k :real; // коэффециент масштабирования end; type TForm1 = class(TForm) PaintBox: TPaintBox; ActionList1: TActionList; actLeft: TAction; actRight: TAction; actZoomIn: TAction; actUp: TAction; actDown: TAction; actReturn: TAction; actZoomOut: TAction; actRotateLeft: TAction; actRotateRight: TAction; actFlipOX: TAction; actFlipOY: TAction; actFlipXY: TAction; Panel1: TPanel; btnUp: TButton; btnLeft: TButton; btnRight: TButton; btnDown: TButton; btnReturn: TButton; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; Button7: TButton; Label1: TLabel; actFreeRotate: TAction; Label2: TLabel; procedure FormShow(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); procedure actLeftExecute(Sender: TObject); procedure actRightExecute(Sender: TObject); procedure actZoomInExecute(Sender: TObject); procedure actReturnExecute(Sender: TObject); procedure actUpExecute(Sender: TObject); procedure actDownExecute(Sender: TObject); procedure actRotateLeftExecute(Sender: TObject); procedure actRotateRightExecute(Sender: TObject); procedure actFlipOXExecute(Sender: TObject); procedure actFlipOYExecute(Sender: TObject); procedure actFlipXYExecute(Sender: TObject); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure actZoomOutExecute(Sender: TObject); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FCurX: integer; FCurY: integer; FCurAngle: real; Mas :array[1..PointsCount] of TPoint; // массив точек фигуры Dop :array [1..3] of array [1..3] of real; //матрица преобразования procedure SetCurX(const Value: integer); procedure SetCurY(const Value: integer); procedure SetCurAngle(const Value: real); private // текущее положение фигуры на рисунке property CurX :integer read FCurX write SetCurX; property CurY :integer read FCurY write SetCurY; property CurAngle :real read FCurAngle write SetCurAngle; // в радианах procedure Clear; procedure Init; public procedure DrawFigure; // отрисовка осей координат procedure DrawXY; procedure DrawAll; end; var Form1: TForm1; implementation uses Math; {$R *.dfm} procedure TForm1.DrawFigure; var i, j :integer; Buf :array [1..3] of real; begin Dop[1][1]:=Cos(CurAngle); //если угол поворота не равен 0 то матрица Dop[2][1]:=Sin(CurAngle); //преобразования изменится Dop[1][2]:=-Sin(CurAngle); Dop[2][2]:=Dop[1][1]; for i:=1 to PointsCount do //умножаем матрицу вершин на матрицу begin //преобразования и получаем обновленную for j:=1 to 3 do //матрицу вершин begin Buf[j]:=Dop[j][1]*Mas[i].x+Dop[j][2]*Mas[i].y+Dop[j][3]*Mas[i].k; end; Mas[i].x := Buf[1]/Buf[3]; //третья координата вершин должна быть Mas[i].y := Buf[2]/Buf[3]; //равна 1, поэтому делим на нее все координаты Mas[i].k := 1; end; // рисуем квадрат PaintBox.Canvas.MoveTo(CurX + Round(Mas[1].x), CurY + Round(Mas[1].y)); for i := 2 to 5 do PaintBox.Canvas.LineTo(CurX + Round(Mas[i].x), CurY + Round(Mas[i].y)); // рисуем вложенную фигуру PaintBox.Canvas.MoveTo(CurX + Round(Mas[5].x), CurY + Round(Mas[5].y)); for i := 6 to PointsCount do PaintBox.Canvas.LineTo(CurX + Round(Mas[i].x), CurY + Round(Mas[i].y)); end; procedure TForm1.FormShow(Sender: TObject); begin Init; end; procedure TForm1.DrawXY; begin PaintBox.Canvas.Pen.Width := 3; PaintBox.Canvas.MoveTo(PaintBox.Width div 2, 0); PaintBox.Canvas.LineTo(PaintBox.Width div 2, PaintBox.Height); PaintBox.Canvas.MoveTo(0, PaintBox.Height div 2); PaintBox.Canvas.LineTo(PaintBox.Width, PaintBox.Height div 2); end; procedure TForm1.SetCurX(const Value: integer); begin FCurAngle := 0; Dop[3][3] := 1; FCurX := Value; Clear; DrawAll; end; procedure TForm1.SetCurY(const Value: integer); begin FCurAngle := 0; Dop[3][3] := 1; FCurY := Value; Clear; DrawAll; end; procedure TForm1.Clear; begin PaintBox.Canvas.Brush.Color := clWhite; PaintBox.Canvas.FillRect(PaintBox.Canvas.ClipRect); end; procedure TForm1.DrawAll; begin DrawXY; DrawFigure; end; procedure TForm1.PaintBoxPaint(Sender: TObject); begin Clear; DrawAll; end; procedure TForm1.actLeftExecute(Sender: TObject); begin CurX := CurX - 2; end; procedure TForm1.actRightExecute(Sender: TObject); begin CurX := CurX + 2; end; procedure TForm1.SetCurAngle(const Value: real); begin FCurAngle := Value; Clear; DrawAll; end; procedure TForm1.actReturnExecute(Sender: TObject); begin FCurX := Beg_X; FCurY := Beg_Y; FCurAngle := Beg_Angle; Init; Clear; DrawAll; end; procedure TForm1.actUpExecute(Sender: TObject); begin CurY := CurY - 2; end; procedure TForm1.actDownExecute(Sender: TObject); begin CurY := CurY + 2; end; procedure TForm1.actRotateLeftExecute(Sender: TObject); begin if CurAngle < 0 then FCurAngle := 0; Dop[3][3] := 1; CurAngle := CurAngle + 0.001; end; procedure TForm1.actRotateRightExecute(Sender: TObject); begin if CurAngle > 0 then FCurAngle := 0; Dop[3][3] := 1; CurAngle := CurAngle - 0.001; end; procedure TForm1.actFlipOXExecute(Sender: TObject); var i : integer; begin for i := 1 to PointsCount do Mas[i].y := -Mas[i].y; Clear; DrawAll; end; procedure TForm1.actFlipOYExecute(Sender: TObject); var i : integer; begin for i := 1 to PointsCount do Mas[i].x := -Mas[i].x; Clear; DrawAll; end; procedure TForm1.actFlipXYExecute(Sender: TObject); var i : integer; buf : real; begin for i := 1 to PointsCount do //меняем координаты х и у местами begin //приходится учитывать, что в мониторе buf := -Mas[i].x; //у-координата увеличивается в направлении Mas[i].x := -Mas[i].y; //сверху вниз, а нам надо наооборот Mas[i].y := buf; end; Clear; DrawAll; end; procedure TForm1.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Label1.Caption := IntToStr(x) + ' ' + IntToStr(y); end; procedure TForm1.Init; var i :integer; begin FCurX := Beg_X; FCurY := Beg_Y; FCurAngle := Beg_Angle; // координаты точек квадрата Mas[1].x := 50; Mas[1].y := 50; Mas[2].x := 250; Mas[2].y := 50; Mas[3].x := 250; Mas[3].y := 225; Mas[4].x := 50; Mas[4].y := 225; Mas[5].x := 50; Mas[5].y := 50; // координаты вложенной фигуры Mas[6].x := 150; Mas[6].y := 50; Mas[7].x := 175; Mas[7].y := 150; Mas[8].x := 250; Mas[8].y := 225; Mas[9].x := 150; Mas[9].y := 200; Mas[10].x := 50; Mas[10].y := 225; Mas[11].x := 125; Mas[11].y := 150; Mas[12].x := 150; Mas[12].y := 50; // устанавливаем масштабный коэффециент for i:=1 to PointsCount do Mas[i].k := 1; Dop[1][1]:=1; Dop[2][1]:=0; Dop[3][1]:=0; //задаем матрицу преобразования Dop[1][2]:=0; Dop[2][2]:=1; Dop[3][2]:=0; //единичной матрицей Dop[1][3]:=0; Dop[2][3]:=0; Dop[3][3]:=1; end; procedure TForm1.actZoomInExecute(Sender: TObject); begin FCurAngle := 0; if Dop[3][3] > 1 then Dop[3][3] := 1; Dop[3][3] := Dop[3][3] - 0.001; Clear; DrawAll; end; procedure TForm1.actZoomOutExecute(Sender: TObject); begin FCurAngle := 0; if Dop[3][3] < 1 then Dop[3][3] := 1; Dop[3][3] := Dop[3][3] + 0.001; Clear; DrawAll; end; procedure TForm1.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button = mbLeft) and (MessageDlg('Переместить центр координат в эту точку?', mtConfirmation, [mbYes, mbNo],0) = mrYes) then begin CurX := X; //перемещаем центр координат в точку, куда CurY := Y; //кликнули Clear; DrawAll; end; end; end.
unit test_tpRTTI; (* Copyright (c) 2000-2018 HREF Tools Corp. Permission is hereby granted, on 18-Jun-2017, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) interface {$I hrefdefines.inc} { Master copy of hrefdefines.inc is versioned on Source Forge in the ZaphodsMap project: https://sourceforge.net/p/zaphodsmap/code/HEAD/tree/trunk/ZaphodsMap/Source/hrefdefines.inc } uses SysUtils, Forms, DUnitX.TestFrameWork, tpRTTI; type [TestFixture] TTest_tpRTTI = class(TObject) private FForm: TForm; public [SetUp] procedure SetUp; [TearDown] procedure TearDown; public [Test] procedure TestFindComponentByName; [Test] procedure TestGetPropertyAsInteger; [Test] procedure TestGetPropertyAsString; [Test] procedure TestHasProperty; end; implementation { TTest_tpRTTI } procedure TTest_tpRTTI.SetUp; begin Application.CreateForm(TForm, FForm); FForm.Name := ClassName + '_Form'; {$IFDEF DUNIT} Cleanup_tpRTTI_Cache; {$ENDIF} end; procedure TTest_tpRTTI.TearDown; begin FreeAndNil(FForm); {$IFDEF DUNIT} Cleanup_tpRTTI_Cache; {$ENDIF} end; procedure TTest_tpRTTI.TestFindComponentByName; begin Assert.IsTrue(FForm = FindComponentByName(FForm.Name)); end; procedure TTest_tpRTTI.TestGetPropertyAsInteger; begin FForm.Width := 400; Assert.AreEqual(FForm.Width, GetPropertyAsInteger(FForm.Name, 'Width')); end; procedure TTest_tpRTTI.TestGetPropertyAsString; begin FForm.Caption := 'Test Caption'; Assert.AreEqual(FForm.Caption, GetPropertyAsString(FForm.Name, 'Caption')); end; procedure TTest_tpRTTI.TestHasProperty; begin Assert.IsTrue(HasProperty(FForm.Name, 'ActiveControl')); end; initialization TDUnitX.RegisterTestFixture(TTest_tpRTTI); end.
unit Model.MovimentoEstoqueVA; interface type TMovimentoEstoqueVA = class private var FID: Integer; FData: TDate; FProduto: Integer; FTIpo: SmallInt; FDescricao: String; FQuantidade: Double; FStatus: Smallint; FLog: String; public property ID: Integer read FID write FID; property Data: TDate read FData write FData; property Produto: Integer read FProduto write FProduto; property Tipo: SmallInt read FTipo write FTipo; property Descricao: String read FDescricao write FDescricao; property Quantidade: Double read FQuantidade write FQuantidade; property Status: SmallInt read FStatus write FStatus; property LOG: String read FLog write FLog; constructor Creare; overload; constructor Create(pFID: Integer; pFData: TDate; pFProduto: Integer; pFTIpo: SmallInt; pFDescricao: String; pFQuantidade: Double; pFStatus: Smallint; pFLog: String); end; implementation { TMovimentoEstoqueVA } constructor TMovimentoEstoqueVA.Creare; begin inherited Create; end; constructor TMovimentoEstoqueVA.Create(pFID: Integer; pFData: TDate; pFProduto: Integer; pFTIpo: SmallInt; pFDescricao: String; pFQuantidade: Double; pFStatus: Smallint; pFLog: String); begin FID := pFID; FData := pFData; FProduto := pFProduto; FTIpo := pFTIpo; FDescricao := pFDescricao; FQuantidade := pFQuantidade; FStatus := pFStatus; FLog := pFLog; end; end.
unit LithologyPoster; interface uses DB, PersistentObjects, DBGate, BaseObjects, SysUtils; type TLithologyDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Lithology, Facade; { TLithologyDataPoster } constructor TLithologyDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_LITHOLOGY_DICT'; KeyFieldNames := 'ROCK_ID'; FieldNames := 'ROCK_ID, VCH_ROCK_NAME'; AccessoryFieldNames := 'ROCK_ID, VCH_ROCK_NAME'; AutoFillDates := false; Sort := 'VCH_ROCK_NAME'; end; function TLithologyDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TLithologyDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TLithology; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TLithology; o.ID := ds.FieldByName('ROCK_ID').AsInteger; o.Name := AnsiLowerCase(trim(ds.FieldByName('VCH_ROCK_NAME').AsString)); ds.Next; end; ds.First; end; end; function TLithologyDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
unit ProcessHandlerUnit; {$MODE Delphi} { Will handle all process specific stuff like openening and closing a process The ProcessHandler variable will be in cefuncproc, but a tabswitch to another process will set it to the different tab's process } interface uses {$ifdef darwin} macport, {$endif} {$ifdef windows} windows, {$endif} {$ifndef jni}LCLIntf, {$endif} newkernelhandler, classes, sysutils; type TSystemArchitecture=(archX86=0, archArm=1); TOperatingsystemABI=(abiWindows=0, abiSystemV=1); type TProcessHandler=class private fis64bit: boolean; fIsAndroid: boolean; fprocesshandle: THandle; fpointersize: integer; fSystemArchitecture: TSystemArchitecture; fOSABI: TOperatingsystemABI; //for c-code fHexDigitPreference: integer; procedure setIs64bit(state: boolean); procedure setProcessHandle(processhandle: THandle); public processid: dword; procedure Open; function isNetwork: boolean; //perhaps name it isLinux ? procedure overridePointerSize(newsize: integer); property is64Bit: boolean read fIs64Bit write setIs64bit; property isAndroid: boolean read fIsAndroid; property pointersize: integer read fPointersize; property processhandle: THandle read fProcessHandle write setProcessHandle; property SystemArchitecture: TSystemArchitecture read fSystemArchitecture write fSystemArchitecture; property OSABI: TOperatingsystemABI read fOSABI; property hexdigitpreference: integer read fHexDigitPreference; end; var processhandler: TProcessHandler; function processhandle: THandle; inline; function processid: dword; inline; implementation {$ifdef jni} uses networkinterface, networkInterfaceApi; {$else} uses LuaHandler, mainunit, networkinterface, networkInterfaceApi, ProcessList, lua, FileUtil; {$endif} procedure TProcessHandler.overridePointerSize(newsize: integer); begin fpointersize:=newsize; end; function TProcessHandler.isNetwork: boolean; begin result:=(((processhandle shr 24) and $ff)=$ce) and (getConnection<>nil); end; procedure TProcessHandler.setIs64bit(state: boolean); begin fis64bit:=state; if state then fpointersize:=8 else fpointersize:=4; fhexdigitpreference:=fpointersize*2; end; procedure TProcessHandler.setProcessHandle(processhandle: THandle); var c: TCEConnection; arch: integer; abi: integer; begin //outputdebugstring('TProcessHandler.setProcessHandle'); if (fprocesshandle<>0) and (fprocesshandle<>getcurrentprocess) and (processhandle<>getcurrentprocess) then begin try closehandle(fprocesshandle); except //debugger issue end; fprocesshandle:=0; end; fprocesshandle:=processhandle; c:=getConnection; if c<>nil then begin fIsAndroid:=c.isAndroid; arch:=c.getArchitecture(fprocesshandle); case arch of 0: //i386 begin fSystemArchitecture:=archX86; setIs64Bit(false); end; 1: //x86_64 begin fSystemArchitecture:=archX86; setIs64Bit(true); end; 2: //arm begin fSystemArchitecture:=archArm; setIs64Bit(false); end; 3: //arm64 begin fSystemArchitecture:=archArm; setIs64Bit(true); end; end; abi:=c.GetABI; case abi of 0: fOSABI:=abiWindows; 1: fOSABI:=abiSystemV; end; end else begin fIsAndroid:=false; //outputdebugstring('setProcessHandle not windows'); {$ifdef darwin} if MacIsArm64 then //rosetta2 or I finally ported it to full armv8 fSystemArchitecture:=archArm; {$else} fSystemArchitecture:=archX86; {$endif} {$ifdef windows} fOSABI:=abiWindows; {$else} fOSABI:=abiSystemV; {$endif} setIs64Bit(newkernelhandler.Is64BitProcess(fProcessHandle)); end; {$ifdef ARMTEST} fSystemArchitecture:=archArm; fOSABI:=abiSystemV; setIs64Bit(false); {$endif} if processhandle<>0 then begin outputdebugstring('calling open'); open; end; end; procedure TProcessHandler.Open; var mn: string; begin // outputdebugstring('TProcessHandler.Open'); //GetFirstModuleNa {$ifndef jni} if processid<>0 then begin mn:=GetFirstModuleName(processid); lua_pushstring(luavm, pchar(extractfilename(mn))); lua_setglobal(luavm, 'process'); end; LUA_functioncall('onOpenProcess', [ptruint(processid)]); //todo: Change to a callback array/list {$endif} end; function processhandle: THandle; inline; begin result:=processhandler.processhandle; end; function processid: dword; inline; begin result:=processhandler.processid; end; initialization processhandler:=TProcessHandler.create; end.
unit Expedicao.Services.uSeguro; interface uses FireDAC.Comp.Client, Expedicao.Models.uSeguro, Expedicao.Models.uSeguradora; type TSeguroService = class private public function ObterSeguroDaQuery(pQry: TFDQuery): TSeguro; function ObterSeguroPeloOID(pSeguroOID: Integer): TSeguro; function ObterSeguradora(pSeguradoraID: Integer): TSeguradora; end; implementation uses uDataModule, Expedicao.Services.uSeguradora; { TSeguroService } function TSeguroService.ObterSeguradora(pSeguradoraID: Integer): TSeguradora; var lSvcSeguradora: TSeguradoraService; begin lSvcSeguradora := TSeguradoraService.Create; try Result := lSvcSeguradora.ObterSeguradoraPeloOID(pSeguradoraID); finally lSvcSeguradora.Free; end; end; function TSeguroService.ObterSeguroDaQuery(pQry: TFDQuery): TSeguro; begin Result := TSeguro.Create; with Result do begin SeguroOID := pQry.FieldByName('SeguroOID').AsInteger; DataInicio := pQry.FieldByName('DataInicio').AsDateTime; DataFim := pQry.FieldByName('DataFim').AsDateTime; Cobertura := pQry.FieldByName('Cobertura').AsString; Seguradora := ObterSeguradora(pQry.FieldByName('SeguradoraOID').AsInteger); end; end; function TSeguroService.ObterSeguroPeloOID(pSeguroOID: Integer): TSeguro; var lQry: TFDQuery; begin Result := nil; lQry := DataModule1.ObterQuery; try lQry.Open('SELECT * FROM Seguro WHERE SeguroOID = :SeguroOID', [pSeguroOID]); if lQry.IsEmpty then Exit; Result := ObterSeguroDaQuery(lQry); finally DataModule1.DestruirQuery(lQry); end; end; end.
unit VertexStack; {$mode objfpc}{$H+} interface uses Classes, SysUtils, PartnerStack; type VertexNode = ^TVertexNode; // ссылка на элемент списка вершин графа Vertex = ^TVertex; TVertex = record // вершина графа Partner: TPartner; SuitablePartners: VertexNode; // Подходящие партнеры IsFree: boolean; IsVisited: boolean; end; TVertexNode = record // элемент списка вершин графа Data: Vertex; Next: VertexNode; end; function NewVertex(const P: TPartner; const SP: VertexNode): Vertex; function Pop(var Top: VertexNode): Vertex; procedure Push(var Top: VertexNode; const V: Vertex); procedure PushPartner(var Top: VertexNode; const P: TPartner; const SP: VertexNode); procedure Free(var Top: VertexNode); implementation { Создание новой вершины } function NewVertex(const P: TPartner; const SP: VertexNode): Vertex; var V: Vertex = nil; begin New(V); V^.Partner := P; V^.SuitablePartners := SP; Result := V; end; { Процедура удаления верхнего элемента стэка } function Pop(var Top: VertexNode): Vertex; var TempNode: VertexNode = nil; begin Result := Top^.Data; TempNode := Top; Top := Top^.Next; Dispose(TempNode); end; { Процедура добавления элемента на верх стэка } procedure Push(var Top: VertexNode; const V: Vertex); var TempNode: VertexNode = nil; begin New(TempNode); TempNode^.Data := V; TempNode^.Next := Top; Top := TempNode; end; { Процедура добавления партнера на верх стэка } procedure PushPartner(var Top: VertexNode; const P: TPartner; const SP: VertexNode); var V: Vertex = nil; begin New(V); V^.Partner := P; V^.SuitablePartners := SP; V^.IsFree := True; V^.IsVisited := False; Push(Top, V); end; { Процедура освобождения памяти занятой стэком } procedure Free(var Top: VertexNode); begin while Top <> nil do Pop(Top); end; end.
// Copyright 2018 The Casbin Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. unit Tests.Casbin.Main; interface uses DUnitX.TestFramework, Casbin.Types; type [TestFixture] TTestCasbin = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure testFileConstructor; [Test] procedure testMemoryConstructor; [Test] procedure testAdapterConstructor; [Test] procedure testEnabled; [Test] {$REGION 'Basic Model'} [TestCase ('Basic Model.1','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('Basic Model.2','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('Basic Model.3','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,read#false', '#')] [TestCase ('Basic Model.4','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,write#false', '#')] [TestCase ('Basic Model.5','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('Basic Model.6','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('Basic Model.7','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('Basic Model.8','..\..\..\Examples\Default\basic_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestKeyMatchModel'} // From enforce_test.go - TestKeyMatchModelInMemory [TestCase ('KeyMatch.Allow.1','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/alice_data/resource1,GET#true', '#')] [TestCase ('KeyMatch.Allow.2','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/alice_data/resource1,POST#true', '#')] [TestCase ('KeyMatch.Allow.3','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/alice_data/resource2,GET#true', '#')] [TestCase ('KeyMatch.Allow.4','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/alice_data/resource2,POST#false', '#')] [TestCase ('KeyMatch.Allow.5','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/bob_data/resource1,GET#false', '#')] [TestCase ('KeyMatch.Allow.6','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/bob_data/resource1,POST#false', '#')] [TestCase ('KeyMatch.Allow.7','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/bob_data/resource2,GET#false', '#')] [TestCase ('KeyMatch.Allow.8','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/bob_data/resource2,POST#false', '#')] [TestCase ('KeyMatch.Allow.9','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/bob_data/resource1,GET#false', '#')] [TestCase ('KeyMatch.Allow.10','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/bob_data/resource1,POST#true', '#')] [TestCase ('KeyMatch.Allow.11','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/bob_data/resource2,GET#false', '#')] [TestCase ('KeyMatch.Allow.12','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/bob_data/resource2,POST#true', '#')] [TestCase ('KeyMatch.Allow.13','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/alice_data/resource1,GET#false', '#')] [TestCase ('KeyMatch.Allow.14','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/alice_data/resource1,POST#false', '#')] [TestCase ('KeyMatch.Allow.15','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/alice_data/resource2,GET#true', '#')] [TestCase ('KeyMatch.Allow.16','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'bob,/alice_data/resource2,POST#false', '#')] [TestCase ('KeyMatch.Allow.17','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'cathy,/cathy_data,GET#true', '#')] [TestCase ('KeyMatch.Allow.18','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'cathy,/cathy_data,POST#true', '#')] [TestCase ('KeyMatch.Allow.19','..\..\..\Examples\Tests\keymatch_model_Allow.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'cathy,/cathy_data,DELETE#false', '#')] {$ENDREGION} {$REGION 'TestKeytMatch2Model'} // From enforce_test.go - TestKeyMatch2Model [TestCase ('KeyMatch2.1','..\..\..\Examples\Default\keymatch2_model.conf#'+ '..\..\..\Examples\Default\keymatch2_policy.csv#'+ 'alice,/alice_data,GET#false', '#')] [TestCase ('KeyMatch2.2','..\..\..\Examples\Default\keymatch2_model.conf#'+ '..\..\..\Examples\Default\keymatch2_policy.csv#'+ 'alice,/alice_data/resource1,GET#true', '#')] [TestCase ('KeyMatch2.3','..\..\..\Examples\Default\keymatch2_model.conf#'+ '..\..\..\Examples\Default\keymatch2_policy.csv#'+ 'alice,/alice_data2/myid,GET#false', '#')] [TestCase ('KeyMatch2.4','..\..\..\Examples\Default\keymatch2_model.conf#'+ '..\..\..\Examples\Default\keymatch2_policy.csv#'+ 'alice,/alice_data2/myid/using/res_id,GET#true', '#')] {$ENDREGION} {$REGION 'TestKeyMatchModelDeny'} // From enforce_test.go - TestKeyMatchModelInMemoryDeny [TestCase ('KeyMatchDeny.1','..\..\..\Examples\Tests\keymatch_model_Deny.conf#'+ '..\..\..\Examples\Tests\keymatch_policy.csv#'+ 'alice,/alice_data/resource2,POST#true', '#')] {$ENDREGION} {$REGION 'TestBasicModelWithRoot'} // From model_test.go - TestBasicModelWithRoot [TestCase ('Basic Model.Root.1','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('Basic Model.Root.2','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('Basic Model.Root.3','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,read#false', '#')] [TestCase ('Basic Model.Root.4','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,write#false', '#')] [TestCase ('Basic Model.Root.5','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob, data1, read#false', '#')] [TestCase ('Basic Model.Root.6','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('Basic Model.Root.7','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('Basic Model.Root.8','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,write#true', '#')] [TestCase ('Basic Model.Root.9','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'root, data1, read#true', '#')] [TestCase ('Basic Model.Root.10','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'root,data1,write#true', '#')] [TestCase ('Basic Model.Root.11','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'root,data2,read#true', '#')] [TestCase ('Basic Model.Root.12','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'root,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestBasicModelWithoutUsers'} // From model_test.go - TestBasicModelWithoutUsers [TestCase ('Basic Model.NoUsers.1','..\..\..\Examples\Default\basic_without_users_model.conf#'+ '..\..\..\Examples\Default\basic_without_users_policy.csv#'+ 'data1,read#true', '#')] [TestCase ('Basic Model.NoUsers.2','..\..\..\Examples\Default\basic_without_users_model.conf#'+ '..\..\..\Examples\Default\basic_without_users_policy.csv#'+ 'data1,write#false', '#')] [TestCase ('Basic Model.NoUsers.3','..\..\..\Examples\Default\basic_without_users_model.conf#'+ '..\..\..\Examples\Default\basic_without_users_policy.csv#'+ 'data2,read#false', '#')] [TestCase ('Basic Model.NoUsers.4','..\..\..\Examples\Default\basic_without_users_model.conf#'+ '..\..\..\Examples\Default\basic_without_users_policy.csv#'+ 'data2,write#true', '#')] {$ENDREGION} {$REGION 'TestBasicModelWithoutResources'} // From model_test.go - TestBasicModelWithoutResources [TestCase ('Basic Model.NoResources.1','..\..\..\Examples\Default\basic_without_resources_model.conf#'+ '..\..\..\Examples\Default\basic_without_resources_policy.csv#'+ 'alice,read#true', '#')] [TestCase ('Basic Model.NoResources.2','..\..\..\Examples\Default\basic_without_resources_model.conf#'+ '..\..\..\Examples\Default\basic_without_resources_policy.csv#'+ 'alice,write#false', '#')] [TestCase ('Basic Model.NoResources.3','..\..\..\Examples\Default\basic_without_resources_model.conf#'+ '..\..\..\Examples\Default\basic_without_resources_policy.csv#'+ 'bob,read#false', '#')] [TestCase ('Basic Model.NoResources.4','..\..\..\Examples\Default\basic_without_resources_model.conf#'+ '..\..\..\Examples\Default\basic_without_resources_policy.csv#'+ 'bob,write#true', '#')] {$ENDREGION} {$REGION 'TestIPMatchModel'} // From model_test.go - TestIPMatchModel [TestCase ('IPMatchModel.1','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.2.123,data1,read#true', '#')] [TestCase ('IPMatchModel.2','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.2.123,data1,write#false', '#')] [TestCase ('IPMatchModel.3','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.2.123,data2,read#false', '#')] [TestCase ('IPMatchModel.4','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.2.123,data2,write#false', '#')] [TestCase ('IPMatchModel.5','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.123,data1,read#false', '#')] [TestCase ('IPMatchModel.6','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.123,data1,write#false', '#')] [TestCase ('IPMatchModel.7','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.123,data2,read#false', '#')] [TestCase ('IPMatchModel.8','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.123,data2,write#false', '#')] [TestCase ('IPMatchModel.9','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '10.0.0.5,data1,read#false', '#')] [TestCase ('IPMatchModel.10','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '10.0.0.5,data1,write#false', '#')] [TestCase ('IPMatchModel.11','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '10.0.0.5,data2,read#false', '#')] [TestCase ('IPMatchModel.12','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '10.0.0.5,data2,write#true', '#')] [TestCase ('IPMatchModel.13','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.1,data1,read#false', '#')] [TestCase ('IPMatchModel.14','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.1,data1,write#false', '#')] [TestCase ('IPMatchModel.15','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.1,data2,read#false', '#')] [TestCase ('IPMatchModel.16','..\..\..\Examples\Default\ipmatch_model.conf#'+ '..\..\..\Examples\Default\ipmatch_policy.csv#'+ '192.168.0.1,data2,write#false', '#')] {$ENDREGION} {$REGION 'TestPriorityModel'} // From model_test.go - TestPriorityModel [TestCase ('PriorityModel.1','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('PriorityModel.2','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('PriorityModel.3','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'alice,data2,read#false', '#')] [TestCase ('PriorityModel.4','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'alice,data2,write#false', '#')] [TestCase ('PriorityModel.5','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('PriorityModel.6','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('PriorityModel.7','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'bob,data2,read#true', '#')] [TestCase ('PriorityModel.8','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_policy.csv#'+ 'bob,data2,write#false', '#')] {$ENDREGION} {$REGION 'Indeterminate'} [TestCase ('Indeterminate.1','..\..\..\Examples\Default\priority_model.conf#'+ '..\..\..\Examples\Default\priority_indeterminate_policy.csv#'+ 'alice,data1,read#false', '#')] {$ENDREGION} {$REGION 'TestBasicModelNoPolicy'} // From model_test.go - TestBasicModelNoPolicy [TestCase ('TestBasicModelNoPolicy.1','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'alice,data1,read#false', '#')] [TestCase ('TestBasicModelNoPolicy.2','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'alice,data1,write#false', '#')] [TestCase ('TestBasicModelNoPolicy.3','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'alice,data2,read#false', '#')] [TestCase ('TestBasicModelNoPolicy.4','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'alice,data2,write#false', '#')] [TestCase ('TestBasicModelNoPolicy.5','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'bob,data1,read#false', '#')] [TestCase ('TestBasicModelNoPolicy.6','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'bob,data1,write#false', '#')] [TestCase ('TestBasicModelNoPolicy.7','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'bob,data2,read#false', '#')] [TestCase ('TestBasicModelNoPolicy.8','..\..\..\Examples\Default\basic_model.conf#'+ '#'+ 'bob,data2,write#false', '#')] {$ENDREGION} {$REGION 'TestBasicModelWithRootNoPolicy'} // From model_test.go - TestBasicModelWithRootNoPolicy [TestCase ('TestBasicModelWithRootNoPolicy.1','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'alice,data1,read#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.2','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'alice,data1,write#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.3','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'alice,data2,read#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.4','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'alice,data2,write#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.5','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'bob,data1,read#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.6','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'bob,data1,write#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.7','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'bob,data2,read#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.8','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'bob,data2,write#false', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.9','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'root,data1,read#true', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.10','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'root,data1,write#true', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.11','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'root,data2,read#true', '#')] [TestCase ('TestBasicModelWithRootNoPolicy.12','..\..\..\Examples\Default\basic_with_root_model.conf#'+ '#'+ 'root,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestRBACModel'} // From model_test.go - TestRBACModel [TestCase ('TestRBACModel.1','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('TestRBACModel.2','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('TestRBACModel.3','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data2,read#true', '#')] [TestCase ('TestRBACModel.4','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data2,write#true', '#')] [TestCase ('TestRBACModel.5','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('TestRBACModel.6','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('TestRBACModel.7','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('TestRBACModel.8','..\..\..\Examples\Default\rbac_model.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestRBACModelWithResourcesRoles'} // From model_test.go - TestRBACModelWithResourcesRoles [TestCase ('TestRBACModelWithResourcesRoles.1','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('TestRBACModelWithResourcesRoles.2','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'alice,data1,write#true', '#')] [TestCase ('TestRBACModelWithResourcesRoles.3','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'alice,data2,read#false', '#')] [TestCase ('TestRBACModelWithResourcesRoles.4','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'alice,data2,write#true', '#')] [TestCase ('TestRBACModelWithResourcesRoles.5','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('TestRBACModelWithResourcesRoles.6','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('TestRBACModelWithResourcesRoles.7','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('TestRBACModelWithResourcesRoles.8','..\..\..\Examples\Default\rbac_with_resource_roles_model.conf#'+ '..\..\..\Examples\Default\rbac_with_resource_roles_policy.csv#'+ 'bob,data2,write#true', '#')] {$ENDREGION} {$REGION 'RBACModelWithOnlyDeny'} // From model_test.go - RBACModelWithOnlyDeny [TestCase ('TestRBACModelWithOnlyDeny.1','..\..\..\Examples\Default\rbac_with_not_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'alice,data2,write#false', '#')] {$ENDREGION} //{$REGION 'TestRBACModelWithPatern'} // // From model_test.go - TestRBACModelWithPatern // [TestCase ('TestRBACModelWithPatern.1','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'alice,/book/1,GET#true', '#')] // [TestCase ('TestRBACModelWithPatern.2','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'alice,/book/2,GET#true', '#')] // [TestCase ('TestRBACModelWithPatern.3','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'alice,/pen/1,GET#true', '#')] // [TestCase ('TestRBACModelWithPatern.4','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'alice,/pen/2,GET#false', '#')] // [TestCase ('TestRBACModelWithPatern.5','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'bob,/book/1,GET#false', '#')] // [TestCase ('TestRBACModelWithPatern.6','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'bob,/book/2,GET#false', '#')] // [TestCase ('TestRBACModelWithPatern.7','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'bob,/pen/1,GET#true', '#')] // [TestCase ('TestRBACModelWithPatern.8','..\..\..\Examples\Default\rbac_with_pattern_model.conf#'+ // '..\..\..\Examples\Default\rbac_with_pattern_policy.csv#'+ // 'bob,/pen/2,GET#true', '#')] //{$ENDREGION} {$REGION 'TestRBACModelWithDomains'} // From model_test.go - TestRBACModelWithDomains [TestCase ('TestRBACModelWithDomains.1','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'alice,domain1,data1,read#true', '#')] [TestCase ('TestRBACModelWithDomains.2','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'alice,domain1,data1,write#true', '#')] [TestCase ('TestRBACModelWithDomains.3','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'alice,domain1,data2,read#false', '#')] [TestCase ('TestRBACModelWithDomains.4','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'alice,domain2,data2,write#false', '#')] [TestCase ('TestRBACModelWithDomains.5','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'bob,domain2,data1,read#false', '#')] [TestCase ('TestRBACModelWithDomains.6','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'bob,domain2,data1,write#false', '#')] [TestCase ('TestRBACModelWithDomains.7','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'bob,domain2,data2,read#true', '#')] [TestCase ('TestRBACModelWithDomains.8','..\..\..\Examples\Default\rbac_with_domains_model.conf#'+ '..\..\..\Examples\Default\rbac_with_domains_policy.csv#'+ 'bob,domain2,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestRBACModelWithDeny'} // From model_test.go - TestRBACModelWithDeny [TestCase ('TestRBACModelWithDeny.1','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('TestRBACModelWithDeny.2','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('TestRBACModelWithDeny.3','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'alice,data2,read#true', '#')] [TestCase ('TestRBACModelWithDeny.4','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'alice,data2,write#false', '#')] [TestCase ('TestRBACModelWithDeny.5','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('TestRBACModelWithDeny.6','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('TestRBACModelWithDeny.7','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('TestRBACModelWithDeny.8','..\..\..\Examples\Default\rbac_with_deny_model.conf#'+ '..\..\..\Examples\Default\rbac_with_deny_policy.csv#'+ 'bob,data2,write#true', '#')] {$ENDREGION} {$REGION 'TestRBACModelInMultiLines'} // From model_test.go - TestRBACModelInMultiLines [TestCase ('TestRBACModelInMultiLines.1','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data1,read#true', '#')] [TestCase ('TestRBACModelInMultiLines.2','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data1,write#false', '#')] [TestCase ('TestRBACModelInMultiLines.3','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data2,read#true', '#')] [TestCase ('TestRBACModelInMultiLines.4','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'alice,data2,write#true', '#')] [TestCase ('TestRBACModelInMultiLines.5','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data1,read#false', '#')] [TestCase ('TestRBACModelInMultiLines.6','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data1,write#false', '#')] [TestCase ('TestRBACModelInMultiLines.7','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data2,read#false', '#')] [TestCase ('TestRBACModelInMultiLines.8','..\..\..\Examples\Default\rbac_model_in_multi_line.conf#'+ '..\..\..\Examples\Default\rbac_policy.csv#'+ 'bob,data2,write#true', '#')] {$ENDREGION} /////////////////////////////////////////////// procedure testEnforce(const aModelFile, aPolicyFile, aEnforceParams: string; const aResult: boolean); [Test] {$REGION 'TestABACModel'} // From model_test.go - TestABACModel [TestCase ('ABAC.1','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,read#alice#true', '#')] [TestCase ('ABAC.2','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data1,write#alice#true', '#')] [TestCase ('ABAC.3','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,read#bob#false', '#')] [TestCase ('ABAC.4','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'alice,data2,write#bob#false', '#')] [TestCase ('ABAC.5','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data1,read#alice#false', '#')] [TestCase ('ABAC.6','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data1,write#alice#false', '#')] [TestCase ('ABAC.7','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,read#bob#true', '#')] [TestCase ('ABAC.8','..\..\..\Examples\Default\abac_model.conf#'+ '..\..\..\Examples\Default\basic_policy.csv#'+ 'bob,data2,write#bob#true', '#')] {$ENDREGION} /////////////////////////////////////////////// procedure testEnforceABAC(const aModelFile, aPolicyFile, aEnforceParams: string; const aOwner: string; const aResult: boolean); [Test] /////////////////////////////////////////////// procedure testEnforceRBACInMemoryIndeterminate; [Test] {$REGION 'RBACModelInMemory'} // From enforcer_test.go - TestRBACModelInMemory [TestCase ('RBACInMemory.1', 'alice,data1,read#true', '#')] [TestCase ('RBACInMemory.2', 'alice,data1,write#false', '#')] [TestCase ('RBACInMemory.3', 'alice,data2,read#true', '#')] [TestCase ('RBACInMemory.4', 'alice,data2,write#true', '#')] [TestCase ('RBACInMemory.5', 'bob,data1,read#false', '#')] [TestCase ('RBACInMemory.6', 'bob,data1,write#false', '#')] [TestCase ('RBACInMemory.7', 'bob,data2,read#false', '#')] [TestCase ('RBACInMemory.8', 'bob,data2,write#true', '#')] {$ENDREGION} /////////////////////////////////////////////// procedure testEnforceRBACModelInMemory (const aEnforceParams: string; const aResult: Boolean); {$REGION 'RBACModelInMemory2'} // From enforcer_test.go - TestRBACModelInMemory2 [TestCase ('RBACInMemory2.1', 'alice,data1,read#true', '#')] [TestCase ('RBACInMemory2.2', 'alice,data1,write#false', '#')] [TestCase ('RBACInMemory2.3', 'alice,data2,read#true', '#')] [TestCase ('RBACInMemory2.4', 'alice,data2,write#true', '#')] [TestCase ('RBACInMemory2.5', 'bob,data1,read#false', '#')] [TestCase ('RBACInMemory2.6', 'bob,data1,write#false', '#')] [TestCase ('RBACInMemory2.7', 'bob,data2,read#false', '#')] [TestCase ('RBACInMemory2.8', 'bob,data2,write#true', '#')] {$ENDREGION} /////////////////////////////////////////////// procedure testEnforceRBACModelInMemory2 (const aEnforceParams: string; const aResult: Boolean); {$REGION 'NotUsedRBACModelInMemory'} // From enforcer_test.go - TestNotUsedRBACModelInMemory [TestCase ('NotUsedRBACModelInMemory.1', 'alice,data1,read#true', '#')] [TestCase ('NotUsedRBACModelInMemory.2', 'alice,data1,write#false', '#')] [TestCase ('NotUsedRBACModelInMemory.3', 'alice,data2,read#false', '#')] [TestCase ('NotUsedRBACModelInMemory.4', 'alice,data2,write#false', '#')] [TestCase ('NotUsedRBACModelInMemory.5', 'bob,data1,read#false', '#')] [TestCase ('NotUsedRBACModelInMemory.6', 'bob,data1,write#false', '#')] [TestCase ('NotUsedRBACModelInMemory.7', 'bob,data2,read#false', '#')] [TestCase ('NotUsedRBACModelInMemory.8', 'bob,data2,write#true', '#')] {$ENDREGION} /////////////////////////////////////////////// procedure testEnforceNotUsedRBACModelInMemory (const aEnforceParams: string; const aResult: Boolean); [Test] // From model_test.go - TestRBACModelWithDomainsAtRuntime /////////////////////////////////////////////// procedure testEnforceRBACModelWithDomainsAtRuntime (const aEnforceParams: string; const aResult: Boolean); [Test] // From enforcer_test.go - TestEnableEnforce /////////////////////////////////////////////// procedure testEnableEnforce; [Test] // From enforcer_test.go - TestGetAndSetModel /////////////////////////////////////////////// procedure testGetAndSetModel; [Test] // From enforcer_test.go - TestGetAndSetAdapterInMem /////////////////////////////////////////////// procedure testGetAndSetAdapterInMem; [Test] // From enforcer_test.go - TestSetAdapterFromFile /////////////////////////////////////////////// procedure testGetAndSetAAdapterFromFile; [Test] // From enforcer_test.go - TestInitEmpty /////////////////////////////////////////////// procedure testInitEmpty; end; implementation uses Casbin.Model.Types, Casbin.Policy.Types, Casbin.Model, Casbin.Policy, Casbin, SysUtils, Casbin.Model.Sections.Types, Casbin.Adapter.Types, Casbin.Adapter.Filesystem, Casbin.Adapter.Policy.Types, Casbin.Adapter.Filesystem.Policy, Casbin.Core.Base.Types; procedure TTestCasbin.Setup; begin end; procedure TTestCasbin.TearDown; begin end; procedure TTestCasbin.testAdapterConstructor; var model: IModel; policy: IPolicyManager; casbin: ICasbin; begin model:=TModel.Create('..\..\..\Examples\Default\basic_model.conf'); policy:=TPolicyManager.Create('..\..\..\Examples\Default\basic_policy.csv'); casbin:=TCasbin.Create(model, policy); Assert.IsNotNull(casbin.Logger); Assert.IsNotNull(casbin.Model); Assert.IsNotNull(casbin.Policy); Assert.IsTrue(casbin.Enabled); casbin:=nil; end; procedure TTestCasbin.testEnabled; var casbin: ICasbin; begin casbin:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', '..\..\..\Examples\Default\basic_policy.csv'); Assert.IsTrue(casbin.Enabled); casbin.Enabled:=False; Assert.IsFalse(casbin.Enabled); casbin:=nil; end; procedure TTestCasbin.testEnableEnforce; var casbin: ICasbin; begin casbin:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', '..\..\..\Examples\Default\basic_policy.csv'); casbin.Enabled:=False; Assert.IsTrue(casbin.enforce(['alice','data1','read'])); Assert.IsTrue(casbin.enforce(['alice','data1','write'])); Assert.IsTrue(casbin.enforce(['alice','data2','read'])); Assert.IsTrue(casbin.enforce(['alice','data2','write'])); Assert.IsTrue(casbin.enforce(['bob','data1','read'])); Assert.IsTrue(casbin.enforce(['bob','data1','write'])); Assert.IsTrue(casbin.enforce(['bob','data2','read'])); Assert.IsTrue(casbin.enforce(['bob','data2','write'])); casbin.Enabled:=True; Assert.IsTrue(casbin.enforce(['alice','data1','read'])); Assert.IsFalse(casbin.enforce(['alice','data1','write'])); Assert.IsFalse(casbin.enforce(['alice','data2','read'])); Assert.IsFalse(casbin.enforce(['alice','data2','write'])); Assert.IsFalse(casbin.enforce(['bob','data1','read'])); Assert.IsFalse(casbin.enforce(['bob','data1','write'])); Assert.IsFalse(casbin.enforce(['bob','data2','read'])); Assert.IsTrue(casbin.enforce(['bob','data2','write'])); casbin:=nil; end; procedure TTestCasbin.testEnforce(const aModelFile, aPolicyFile, aEnforceParams: string; const aResult: boolean); var params: TEnforceParameters; casbin: ICasbin; begin casbin:=TCasbin.Create(aModelFile, aPolicyFile); casbin.Policy.Adapter.AutoSave:=False; params:=TFilterArray(aEnforceParams.Split([','])); Assert.AreEqual(aResult, casbin.enforce(params)); casbin:=nil; end; procedure TTestCasbin.testEnforceABAC(const aModelFile, aPolicyFile, aEnforceParams, aOwner: string; const aResult: boolean); type TABACRecord = record Owner: string; end; var params: TEnforceParameters; casbin: ICasbin; rec: TABACRecord; begin casbin:=TCasbin.Create(aModelFile, aPolicyFile); params:=TFilterArray(aEnforceParams.Split([','])); rec.Owner:=aOwner; Assert.AreEqual(aResult, casbin.enforce(params, TypeInfo(TABACRecord), rec)); casbin:=nil; end; procedure TTestCasbin.testEnforceNotUsedRBACModelInMemory( const aEnforceParams: string; const aResult: Boolean); var model: IModel; casbin: ICasbin; begin model:=TModel.Create; model.addDefinition(stRequestDefinition, 'r=sub,obj, act'); model.addDefinition(stPolicyDefinition, 'p', 'sub,obj,act'); model.addDefinition(stRoleDefinition,'g', '_,_'); model.addDefinition(stPolicyEffect, 'e','some(where (p.eft == allow))'); model.addDefinition(stMatchers,'m', 'g(r.sub, p.sub) && r.obj==p.obj && r.act==p.act'); casbin:=TCasbin.Create(model, ''); casbin.Policy.addPolicy(stPolicyRules,'p','alice,data1,read'); casbin.Policy.addPolicy(stPolicyRules,'p','bob,data2, write'); Assert.AreEqual(aResult, casbin.enforce(TFilterArray(aEnforceParams.Split([','])))); end; procedure TTestCasbin.testEnforceRBACInMemoryIndeterminate; var model: IModel; casbin: ICasbin; begin model:=TModel.Create; model.addDefinition(stRequestDefinition, 'r=sub,obj, act'); model.addDefinition(stPolicyDefinition, 'p', 'sub,obj,act'); model.addDefinition(stRoleDefinition,'g', '_,_'); model.addDefinition(stPolicyEffect, 'e','some(where (p.eft == allow))'); model.addDefinition(stMatchers,'m', 'g(r.sub, p.sub) && r.obj==p.obj && r.act==p.act'); casbin:=TCasbin.Create(model, ''); casbin.Policy.addPolicy(stPolicyRules,'p','alice,data1,invalid'); Assert.IsFalse(casbin.enforce(['alice','data1','read'])); end; procedure TTestCasbin.testEnforceRBACModelInMemory(const aEnforceParams: string; const aResult: Boolean); var model: IModel; casbin: ICasbin; begin model:=TModel.Create; model.addDefinition(stRequestDefinition, 'r=sub,obj, act'); model.addDefinition(stPolicyDefinition, 'p', 'sub,obj,act'); model.addDefinition(stRoleDefinition,'g', '_,_'); model.addDefinition(stPolicyEffect, 'e','some(where (p.eft == allow))'); model.addDefinition(stMatchers,'m', 'g(r.sub, p.sub) && r.obj==p.obj && r.act==p.act'); casbin:=TCasbin.Create(model, ''); casbin.Policy.addPolicy(stPolicyRules,'p','alice,data1,read'); casbin.Policy.addPolicy(stPolicyRules,'p','bob,data2, write'); casbin.Policy.addPolicy(stPolicyRules,'p','data2_admin,data2,read'); casbin.Policy.addPolicy(stPolicyRules,'p','data2_admin,data2,write'); casbin.Policy.addPolicy(stRoleRules,'g','alice, data2_admin'); // You may be tempted to write this: // casbin.Policy.addLink('alice', 'data2_admin'); // **** BUT YOU SHOULDN'T **** // Always, add roles using AddPolicy as in the example Assert.AreEqual(aResult, casbin.enforce(TFilterArray(aEnforceParams.Split([','])))); end; procedure TTestCasbin.testEnforceRBACModelInMemory2( const aEnforceParams: string; const aResult: Boolean); var model: IModel; casbin: ICasbin; begin model:=TModel.Create; model.addModel('[request_definition]'+sLineBreak+ 'r = sub, obj, act'+sLineBreak+ '[policy_definition]'+sLineBreak+ 'p = sub, obj, act'+sLineBreak+ '[role_definition]'+sLineBreak+ 'g = _, _'+sLineBreak+ '[policy_effect]'+sLineBreak+ 'e = some(where (p.eft == allow))'+sLineBreak+ '[matchers]'+sLineBreak+ ' m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act'); casbin:=TCasbin.Create(model, ''); casbin.Policy.addPolicy(stPolicyRules,'p','alice,data1,read'); casbin.Policy.addPolicy(stPolicyRules,'p','bob,data2, write'); casbin.Policy.addPolicy(stPolicyRules,'p','data2_admin,data2,read'); casbin.Policy.addPolicy(stPolicyRules,'p','data2_admin,data2,write'); casbin.Policy.addPolicy(stRoleRules,'g','alice, data2_admin'); // You may be tempted to write this: // casbin.Policy.addLink('alice', 'data2_admin'); // **** BUT YOU SHOULDN'T **** // Always, add roles using AddPolicy as in the example Assert.AreEqual(aResult, casbin.enforce(TFilterArray(aEnforceParams.Split([','])))); end; procedure TTestCasbin.testEnforceRBACModelWithDomainsAtRuntime( const aEnforceParams: string; const aResult: Boolean); var casbin: ICasbin; begin casbin:=TCasbin.Create('..\..\..\Examples\Default\rbac_with_domains_model.conf',''); casbin.Policy.addPolicy(stPolicyRules, 'p,admin,domain1,data1,read'); casbin.Policy.addPolicy(stPolicyRules, 'p,admin,domain1,data1,write'); casbin.Policy.addPolicy(stPolicyRules, 'p,admin,domain2,data2,read'); casbin.Policy.addPolicy(stPolicyRules, 'p,admin,domain2,data2,write'); casbin.Policy.addPolicy(stRoleRules, 'g,alice,admin,domain1'); casbin.Policy.addPolicy(stRoleRules, 'g,bob,admin,domain2'); Assert.IsTrue(casbin.enforce(['alice','domain1','data1','read']), '1'); Assert.IsTrue(casbin.enforce(['alice','domain1','data1','write']), '2'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','read']), '3'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','write']), '4'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','read']), '5'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','write']), '6'); Assert.IsTrue(casbin.enforce(['bob','domain2','data2','read']), '7'); Assert.IsTrue(casbin.enforce(['bob','domain2','data2','write']), '8'); casbin.Policy.removePolicy(['*','domain1','data1'], rmImplicit); Assert.IsFalse(casbin.enforce(['alice','domain1','data1','read']), '9'); // Assert.IsFalse(casbin.enforce(['alice','domain1','data1','write']), '10'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','read']), '11'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','write']), '12'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','read']), '13'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','write']), '14'); Assert.IsTrue(casbin.enforce(['bob','domain2','data2','read']), '15'); Assert.IsTrue(casbin.enforce(['bob','domain2','data2','write']), '16'); casbin.Policy.removePolicy(['admin','domain2','data2','read']); Assert.IsFalse(casbin.enforce(['alice','domain1','data1','read']), '17'); // Assert.IsFalse(casbin.enforce(['alice','domain1','data1','write']), '18'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','read']), '19'); Assert.IsFalse(casbin.enforce(['alice','domain1','data2','write']), '20'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','read']), '21'); Assert.IsFalse(casbin.enforce(['bob','domain2','data1','write']), '22'); Assert.IsFalse(casbin.enforce(['bob','domain2','data2','read']), '23'); Assert.IsTrue(casbin.enforce(['bob','domain2','data2','write']), '24'); casbin:=nil; end; procedure TTestCasbin.testFileConstructor; var casbin: ICasbin; begin casbin:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', '..\..\..\Examples\Default\basic_policy.csv'); Assert.IsNotNull(casbin.Logger); Assert.IsNotNull(casbin.Model); Assert.IsNotNull(casbin.Policy); Assert.IsTrue(casbin.Enabled); casbin:=nil; end; procedure TTestCasbin.testGetAndSetAAdapterFromFile; var casbin: ICasbin; adapter: IPolicyAdapter; policy: IPolicyManager; begin casbin:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', ''); Assert.IsFalse(casbin.enforce(['alice','data1','read']), '1'); adapter:=TPolicyFileAdapter.Create('..\..\..\Examples\Default\basic_policy.csv'); policy:=TPolicyManager.Create(adapter); casbin.Policy:=policy; Assert.IsTrue(casbin.enforce(['alice','data1','read']), '2'); casbin:=nil; end; procedure TTestCasbin.testGetAndSetAdapterInMem; var casbin1: ICasbin; casbin2: ICasbin; begin casbin1:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', '..\..\..\Examples\Default\basic_policy.csv'); Assert.IsTrue(casbin1.enforce(['alice','data1','read']), '1'); Assert.IsFalse(casbin1.enforce(['alice','data1','write']), '2'); casbin2:=TCasbin.Create('..\..\..\Examples\Default\basic_model.conf', '..\..\..\Examples\Default\basic_inverse_policy.csv'); casbin1.Policy:=casbin2.Policy; Assert.IsFalse(casbin1.enforce(['alice','data1','read']), '3'); Assert.IsTrue(casbin1.enforce(['alice','data1','write']), '4'); casbin1:=nil; casbin2:=nil; end; procedure TTestCasbin.testGetAndSetModel; var model1: IModel; model2: IModel; casbin: ICasbin; begin model1:=TModel.Create('..\..\..\Examples\Default\basic_model.conf'); model2:=TModel.Create('..\..\..\Examples\Default\basic_with_root_model.conf'); casbin:=TCasbin.Create(model1, ''); Assert.IsFalse(casbin.enforce(['root','data1','read']), 'Model1'); casbin.Model:=model2; Assert.IsTrue(casbin.enforce(['root','data1','read']), 'Model2'); end; procedure TTestCasbin.testInitEmpty; var model: IModel; adapter: IPolicyAdapter; casbin: ICasbin; begin model:=TModel.Create; model.addDefinition(stRequestDefinition, 'r=sub,obj, act'); model.addDefinition(stPolicyDefinition, 'p', 'sub,obj,act'); model.addDefinition(stPolicyEffect, 'e','some(where (p.eft == allow))'); model.addDefinition(stMatchers,'m', 'r.sub == p.sub && keyMatch(r.obj, p.obj) && regexMatch(r.act, p.act)'); adapter:=TPolicyFileAdapter.Create ('..\..\..\Examples\Default\keymatch_policy.csv'); casbin:=TCasbin.Create(model, TPolicyManager.Create(adapter)); Assert.IsTrue(casbin.enforce(['alice', '/alice_data/resource1', 'GET'])); end; procedure TTestCasbin.testMemoryConstructor; var casbin: ICasbin; begin casbin:=TCasbin.Create; Assert.IsNotNull(casbin.Logger); Assert.IsNotNull(casbin.Model); Assert.IsNotNull(casbin.Policy); Assert.IsTrue(casbin.Enabled); casbin:=nil; end; initialization TDUnitX.RegisterTestFixture(TTestCasbin); end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Model relacionado à tabela [FIN_FECHAMENTO_CAIXA_BANCO] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit FinFechamentoCaixaBanco; interface uses Generics.Collections, System.SysUtils, BancoContaCaixa, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TFinFechamentoCaixaBanco = class(TModelBase) private FId: Integer; FIdBancoContaCaixa: Integer; FDataFechamento: TDateTime; FMesAno: string; FMes: string; FAno: string; FSaldoAnterior: Extended; FRecebimentos: Extended; FPagamentos: Extended; FSaldoConta: Extended; FChequeNaoCompensado: Extended; FSaldoDisponivel: Extended; FBancoContaCaixa: TBancoContaCaixa; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_BANCO_CONTA_CAIXA')] [MVCNameAsAttribute('idBancoContaCaixa')] property IdBancoContaCaixa: Integer read FIdBancoContaCaixa write FIdBancoContaCaixa; [MVCColumnAttribute('DATA_FECHAMENTO')] [MVCNameAsAttribute('dataFechamento')] property DataFechamento: TDateTime read FDataFechamento write FDataFechamento; [MVCColumnAttribute('MES_ANO')] [MVCNameAsAttribute('mesAno')] property MesAno: string read FMesAno write FMesAno; [MVCColumnAttribute('MES')] [MVCNameAsAttribute('mes')] property Mes: string read FMes write FMes; [MVCColumnAttribute('ANO')] [MVCNameAsAttribute('ano')] property Ano: string read FAno write FAno; [MVCColumnAttribute('SALDO_ANTERIOR')] [MVCNameAsAttribute('saldoAnterior')] property SaldoAnterior: Extended read FSaldoAnterior write FSaldoAnterior; [MVCColumnAttribute('RECEBIMENTOS')] [MVCNameAsAttribute('recebimentos')] property Recebimentos: Extended read FRecebimentos write FRecebimentos; [MVCColumnAttribute('PAGAMENTOS')] [MVCNameAsAttribute('pagamentos')] property Pagamentos: Extended read FPagamentos write FPagamentos; [MVCColumnAttribute('SALDO_CONTA')] [MVCNameAsAttribute('saldoConta')] property SaldoConta: Extended read FSaldoConta write FSaldoConta; [MVCColumnAttribute('CHEQUE_NAO_COMPENSADO')] [MVCNameAsAttribute('chequeNaoCompensado')] property ChequeNaoCompensado: Extended read FChequeNaoCompensado write FChequeNaoCompensado; [MVCColumnAttribute('SALDO_DISPONIVEL')] [MVCNameAsAttribute('saldoDisponivel')] property SaldoDisponivel: Extended read FSaldoDisponivel write FSaldoDisponivel; [MVCNameAsAttribute('bancoContaCaixa')] property BancoContaCaixa: TBancoContaCaixa read FBancoContaCaixa write FBancoContaCaixa; end; implementation { TFinFechamentoCaixaBanco } constructor TFinFechamentoCaixaBanco.Create; begin FBancoContaCaixa := TBancoContaCaixa.Create; end; destructor TFinFechamentoCaixaBanco.Destroy; begin FreeAndNil(FBancoContaCaixa); inherited; end; procedure TFinFechamentoCaixaBanco.ValidarInsercao; begin inherited; end; procedure TFinFechamentoCaixaBanco.ValidarAlteracao; begin inherited; end; procedure TFinFechamentoCaixaBanco.ValidarExclusao; begin inherited; end; end.
unit uFrmPatch; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, PngCustomButton, ExtCtrls, RzPanel, RzPrgres, RzEdit, XPMan, IniFiles, StrUtils, uAutoUpdate, uMD5, uTFSystem,uProcedureControl; type TFrmPatch = class(TForm) RzPanel1: TRzPanel; Label1: TLabel; RzPanel2: TRzPanel; PngCustomButton1: TPngCustomButton; lblHeadInfo: TLabel; RzPanel3: TRzPanel; btnUpdate: TButton; btnCancel: TButton; prgMain: TRzProgressBar; Label2: TLabel; memInfo: TRzMemo; XPManifest1: TXPManifest; UpdateTimer: TTimer; lblInfo: TLabel; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnUpdateClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure UpdateTimerTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } //传入参数-项目版本 m_strProjectVersion: string; //传入参数-可执行程序名 m_strMainExeName: string; //传入参数-安装路径 m_strSetupPath: string; //读写配置文件 function ReadConfigFile(strFile, strSection, strKey: string; strDefault: string=''): string; procedure WriteConfigFile(strFile, strSection, strKey, strValue: string); //安装升级包 function SetupPatch(strPatchPath, strSetupPath: string): boolean; //从配置文件中得到要安装的文件信息 function GetFileInfoArray(strPatchPath: string; out FileInfoArray: TRsFileInfoArray): integer; //将源目录下的文件复制到指定目录下 function CopyFiles(FileInfoArray: TRsFileInfoArray; strSrcPath, strDesPath, strBakPath: string): integer; // function DeleteFiles(FileInfoArray: TRsFileInfoArray; strSrcPath: string): boolean; //清空指定目录下的文件 function EmptyDir(strPath: string; bDelDir: boolean=False): boolean; function EmptyDirEx(strPath: string; bDelDir: boolean=False): boolean; //复制文件,如果目标路径不存在,则创建 function CopyFileWithDir(strSrcFile, strDesFile: string; bFailIfExists: boolean=True): boolean; procedure DeleteSelf; public { Public declarations } class procedure ShowForm(); end; var FrmPatch: TFrmPatch; implementation {$R *.dfm} class procedure TFrmPatch.ShowForm(); var strProjectVersion, strMainExeName, strSetupPath: string; begin if ParamCount < 3 then Exit; strProjectVersion := Trim(ParamStr(1)); strMainExeName := Trim(ParamStr(2)); strSetupPath := Trim(ParamStr(3)); if (strProjectVersion = '') or (strMainExeName = '') or (strSetupPath = '') then Exit; if FrmPatch = nil then Application.CreateForm(TFrmPatch, FrmPatch); FrmPatch.m_strProjectVersion := strProjectVersion; FrmPatch.m_strMainExeName := strMainExeName; FrmPatch.m_strSetupPath := strSetupPath; FrmPatch.Show; end; procedure TFrmPatch.FormClose(Sender: TObject; var Action: TCloseAction); begin //DeleteSelf; //勿用,不保险 end; procedure TFrmPatch.FormCreate(Sender: TObject); begin DoubleBuffered := true; end; procedure TFrmPatch.FormShow(Sender: TObject); begin lblInfo.Caption := Format('版本号:%s 主程序:%s', [m_strProjectVersion, m_strMainExeName]); memInfo.Clear; UpdateTimer.Enabled := true; end; procedure TFrmPatch.UpdateTimerTimer(Sender: TObject); begin UpdateTimer.Enabled := false; btnUpdate.Click; end; procedure TFrmPatch.btnUpdateClick(Sender: TObject); var strPatchPath, strSetupPath: string; strIniFile: string; begin strPatchPath := ExtractFilePath(Application.ExeName); strSetupPath := m_strSetupPath; if strPatchPath[Length(strPatchPath)] <> '\' then strPatchPath := strPatchPath + '\'; if strSetupPath[Length(strSetupPath)] <> '\' then strSetupPath := strSetupPath + '\'; if not DirectoryExists(strSetupPath) then CreateDir(strSetupPath); memInfo.Lines.Add('正在安装升级包,请稍候……'); memInfo.Lines.Add(Format('安装路径:%s', [strSetupPath])); memInfo.Lines.Add(''); memInfo.Lines.Add('即将关闭主程序进程,请稍候……'); //强制关闭主程序进程 CloseAllProcedure(strSetupPath + m_strMainExeName); Sleep(1000); if SetupPatch(strPatchPath, strSetupPath) then begin memInfo.Lines.Add('更新文件完毕!'); strIniFile := strSetupPath + 'Update.ini'; WriteConfigFile(strIniFile, 'SysConfig', 'ProjectVersion', m_strProjectVersion); WriteConfigFile(strIniFile, 'SysConfig', 'MainExeName', m_strMainExeName); end else begin memInfo.Lines.Add('更新文件失败,请检查后重试!'); end; //打开主程序,关闭程升级序 if FileExists(strSetupPath + m_strMainExeName) then begin WinExec(PChar(strSetupPath + m_strMainExeName), SW_SHOW); Close; end else begin memInfo.Lines.Add(''); memInfo.Lines.Add('系统没有找到可执行的主程序!!!'); end; end; procedure TFrmPatch.btnCancelClick(Sender: TObject); begin Close; end; //============================================================================== function TFrmPatch.ReadConfigFile(strFile, strSection, strKey, strDefault: string): string; var Ini:TIniFile; begin result := strDefault; Ini := TIniFile.Create(strFile); try result := Ini.ReadString(strSection, strKey, strDefault); finally Ini.Free(); end; end; procedure TFrmPatch.WriteConfigFile(strFile, strSection, strKey, strValue: string); var Ini:TIniFile; begin Ini := TIniFile.Create(strFile); try Ini.WriteString(strSection, strKey, strValue); finally Ini.Free(); end; end; function TFrmPatch.SetupPatch(strPatchPath, strSetupPath: string): boolean; var FileInfoArray: TRsFileInfoArray; strBakupPath: string; i, nRet: integer; begin result := false; if strPatchPath[Length(strPatchPath)] <> '\' then strPatchPath := strPatchPath + '\'; if strSetupPath[Length(strSetupPath)] <> '\' then strSetupPath := strSetupPath + '\'; if not DirectoryExists(strSetupPath) then CreateDir(strSetupPath); if GetFileInfoArray(strPatchPath, FileInfoArray) = 0 then begin Box('没有要升级的文件,请检查后重试!'); Exit; end; for i := 0 to Length(FileInfoArray) - 1 do begin if not FileExists(strPatchPath + FileInfoArray[i].strFileName) then begin Box('升级包内文件不完整,请检查后重试!'); Exit; end; end; memInfo.Lines.Add(''); memInfo.Lines.Add('开始更新文件,请稍候……'); prgMain.TotalParts := Length(FileInfoArray); prgMain.PartsComplete := 0; Application.ProcessMessages; strBakupPath := strSetupPath + '_tf_bak\'; if DirectoryExists(strBakupPath) then EmptyDir(strBakupPath, True); if not DirectoryExists(strBakupPath) then CreateDir(strBakupPath); try nRet := CopyFiles(FileInfoArray, strPatchPath, strSetupPath, strBakupPath); result := nRet=mrOk; if nRet = mrNone then Box('更新文件失败,请检查后重试!'); finally if DirectoryExists(strBakupPath) then EmptyDir(strBakupPath, True); if LowerCase(RightStr(strPatchPath, 12)) = '\_tf_update\' then EmptyDirEx(strPatchPath); end; end; function TFrmPatch.GetFileInfoArray(strPatchPath: string; out FileInfoArray: TRsFileInfoArray): integer; var Ini: TIniFile; strFile, strName, strType, strMD5: string; i, nLen, nFileCount: integer; begin result := 0; strFile := strPatchPath + 'Patch.ini'; OutputDebugString(PChar('更新配置文件地址:' + strFile)); if not FileExists(strFile) then exit; Ini := TIniFile.Create(strFile); try nFileCount := Ini.ReadInteger('FileInfo', 'FileCount', 0); OutputDebugString(PChar('获取可更新的文件数:' + inttostr(nFileCount))); for i := 1 to nFileCount do begin strName := Trim(Ini.ReadString('FileName'+IntToStr(i), 'Name', '')); strType := Trim(Ini.ReadString('FileName'+IntToStr(i), 'Type', '')); strMD5 := Trim(Ini.ReadString('FileName'+IntToStr(i), 'MD5', '')); OutputDebugString(PChar(Format('判断可更新文件:名称=%s;类型=%s;MD5=%s',[strName,strType,strMD5]) )); if (strName = '') or (strType = '') or (strMD5 = '') then Continue; nLen := Length(FileInfoArray); SetLength(FileInfoArray, nLen + 1); FileInfoArray[nLen].strFileName := strName; FileInfoArray[nLen].FileType := FileTypeNameToType(strType); FileInfoArray[nLen].strFileMD5 := strMD5; FileInfoArray[nLen].bBackup := False; FileInfoArray[nLen].bUpdate := False; end; result := Length(FileInfoArray); finally Ini.Free(); end; end; function TFrmPatch.CopyFiles(FileInfoArray: TRsFileInfoArray; strSrcPath, strDesPath, strBakPath: string): integer; var strSrcFile, strDesFile, strBakFile: string; strMD5, strTemp: string; i, n: integer; bNextStep: boolean; Label RetryCopy, AbortCopy; begin result := mrNone; try n := 0; for i := 0 to Length(FileInfoArray) - 1 do begin n := i; prgMain.PartsComplete := i; Application.ProcessMessages; strSrcFile := strSrcPath + FileInfoArray[i].strFileName; strDesFile := strDesPath + FileInfoArray[i].strFileName; strBakFile := strBakPath + FileInfoArray[i].strFileName; if not FileExists(strSrcFile) then Continue; if FileExists(strDesFile) then begin if FileInfoArray[i].FileType = ftDBFile then Continue; strMD5 := RivestFile(strDesFile); if FileInfoArray[i].strFileMD5 = strMD5 then Continue; FileInfoArray[i].bBackup := CopyFileWithDir(PChar(strDesFile), PChar(strBakFile), false); end; RetryCopy: if FileExists(strDesFile) then FileSetAttr(strDesFile, 0); if not CopyFileWithDir(PChar(strSrcFile), PChar(strDesFile), false) then begin strTemp := '更新文件失败,请检查目标文件是否占用,是否继续操作?'#13#10#13#10+Format('目标文件:%s', [strDesFile]); case Application.MessageBox(PChar(strTemp), '询问', MB_ABORTRETRYIGNORE + MB_ICONQUESTION) of mrAbort: goto AbortCopy; //撤消安装 mrRetry: goto RetryCopy; //重试 mrIgnore: Continue; end; end; FileInfoArray[i].bUpdate := True; memInfo.Lines.Add(Format('更新文件:%s', [strDesFile])); end; prgMain.PartsComplete := i; Application.ProcessMessages; result := mrOk; Exit; AbortCopy: result := mrAbort; for i := n downto 0 do begin prgMain.PartsComplete := i; Application.ProcessMessages; bNextStep := FileInfoArray[i].bUpdate and FileInfoArray[i].bBackup; FileInfoArray[i].bUpdate := False; FileInfoArray[i].bBackup := False; if not bNextStep then Continue; strDesFile := strDesPath + FileInfoArray[i].strFileName; strBakFile := strBakPath + FileInfoArray[i].strFileName; if not FileExists(strBakFile) then Continue; if FileExists(strDesFile) then FileSetAttr(strDesFile, 0); CopyFile(PChar(strBakFile), PChar(strDesFile), false); end; prgMain.PartsComplete := i; Application.ProcessMessages; except end; end; function TFrmPatch.DeleteFiles(FileInfoArray: TRsFileInfoArray; strSrcPath: string): boolean; var strSrcFile: string; i: integer; begin result := True; try for i := 0 to Length(FileInfoArray) - 1 do begin strSrcFile := strSrcPath + FileInfoArray[i].strFileName; if not FileExists(strSrcFile) then Continue; if LowerCase(strSrcFile) = LowerCase(Application.ExeName) then Continue; FileSetAttr(strSrcFile, 0); result := result and DeleteFile(strSrcFile); end; except end; end; function TFrmPatch.EmptyDir(strPath: string; bDelDir: boolean): boolean; var SearchRec: TSearchRec; strFile: string; begin result := true; if strPath[Length(strPath)] <> '\' then strPath := strPath + '\'; try if FindFirst(strPath+'*.*', faAnyFile, SearchRec) = 0 then begin repeat if SearchRec.Name = '.' then continue; if SearchRec.Name = '..' then continue; strFile := strPath + SearchRec.Name; if (SearchRec.Attr and faDirectory) = faDirectory then begin EmptyDir(strFile, true); end else begin FileSetAttr(strFile, 0); result := result and DeleteFile(strFile); end; until FindNext(SearchRec) <> 0; end; FindClose(SearchRec); if bDelDir then result := result and RemoveDir(strPath); except result := false; end; end; function TFrmPatch.EmptyDirEx(strPath: string; bDelDir: boolean): boolean; var SearchRec: TSearchRec; strFile: string; begin result := true; if strPath[Length(strPath)] <> '\' then strPath := strPath + '\'; try if FindFirst(strPath+'*.*', faAnyFile, SearchRec) = 0 then begin repeat if SearchRec.Name = '.' then continue; if SearchRec.Name = '..' then continue; strFile := strPath + SearchRec.Name; if (SearchRec.Attr and faDirectory) = faDirectory then begin EmptyDir(strFile, true); end else begin if LowerCase(strFile) = LowerCase(Application.ExeName) then Continue; FileSetAttr(strFile, 0); result := result and DeleteFile(strFile); end; until FindNext(SearchRec) <> 0; end; FindClose(SearchRec); if bDelDir then result := result and RemoveDir(strPath); except result := false; end; end; function TFrmPatch.CopyFileWithDir(strSrcFile, strDesFile: string; bFailIfExists: boolean=True): boolean; var strPath: string; begin strPath := ExtractFilePath(strDesFile); if not DirectoryExists(strPath) then ForceDirectories(strPath); result := CopyFile(PChar(strSrcFile), PChar(strDesFile), bFailIfExists); end; procedure TFrmPatch.DeleteSelf; var BatFile: TextFile; strBatFile: string; ProcessInfo: TProcessInformation; StartUpInfo: TStartupInfo; begin strBatFile := ChangeFileExt(Paramstr(0), '.bat'); AssignFile(BatFile, strBatFile); Rewrite(BatFile); //生成批处理命令 Writeln(BatFile, ':try'); Writeln(BatFile, Format('del "%s"', [ParamStr(0)])); Writeln(BatFile, Format('if exist "%s" goto try', [ParamStr(0)])); Writeln(BatFile, 'del %0'); CloseFile(BatFile); FillChar(StartUpInfo, SizeOf(StartUpInfo), $00); StartUpInfo.dwFlags := STARTF_USESHOWWINDOW; StartUpInfo.wShowWindow := SW_HIDE; // create hidden process if CreateProcess(nil,PChar(strBatFile),nil,nil,False,IDLE_PRIORITY_CLASS,nil,nil,StartUpInfo,ProcessInfo) then begin CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); end; end; end.
{ * Copyright 2007 ZXing authors * * 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. * Original Author: Sean Owen * Ported from ZXING Java Source: www.Redivivus.in (suraj.supekar@redivivus.in) * Delphi Implementation by E.Spelt and K. Gossens } unit ZXing.QrCode.Internal.AlignmentPatternImplementation; {$IFDEF FPC} {$mode delphi}{$H+} {$ENDIF} interface uses ZXing.QrCode.Internal.AlignmentPattern; // this is the function that actually creates IAlignmentPattern instances. // the actual implementation of the interface is totally hidden to all other units, // since even its declaration is in the implementation section of this unit function NewAlignmentPattern(const posX, posY, estimatedModuleSize: Single):IAlignmentPattern; implementation uses ZXing.ResultPoint, ZXing.ResultPointImplementation; { TAlignmentPattern } type /// <summary> <p>Encapsulates an alignment pattern, which are the smaller square patterns found in /// all but the simplest QR Codes.</p> /// /// </summary> TAlignmentPattern = class sealed(TResultPoint,IResultPoint,IAlignmentPattern) private estimatedModuleSize: Single; /// <summary> <p>Determines if this alignment pattern "about equals" an alignment pattern at the stated /// position and size -- meaning, it is at nearly the same center with nearly the same size.</p> /// </summary> function aboutEquals(const moduleSize, i, j: Single): Boolean; /// <summary> /// Combines this object's current estimate of a finder pattern position and module size /// with a new estimate. It returns a new {@code FinderPattern} containing an average of the two. /// </summary> /// <param name="i">The i.</param> /// <param name="j">The j.</param> /// <param name="newModuleSize">New size of the module.</param> /// <returns></returns> function combineEstimate(const i, j, newModuleSize: Single): IAlignmentPattern; public constructor Create(const posX, posY, estimatedModuleSize: Single); end; constructor TAlignmentPattern.Create(const posX, posY, estimatedModuleSize: Single); begin inherited Create(posX, posY); Self.estimatedModuleSize := estimatedModuleSize; end; function TAlignmentPattern.aboutEquals(const moduleSize, i, j: Single): Boolean; var moduleSizeDiff: Single; begin if ((Abs(i - Self.y) <= moduleSize) and (Abs(j - Self.x) <= moduleSize)) then begin moduleSizeDiff := Abs(moduleSize - self.estimatedModuleSize); Result := ((moduleSizeDiff <= 1) or (moduleSizeDiff <= self.estimatedModuleSize)); end else Result := false; end; function TAlignmentPattern.combineEstimate(const i, j, newModuleSize: Single): IAlignmentPattern; var combinedX, combinedY, combinedModuleSize : Single; begin combinedX := (self.x + j) / 2.0; combinedY := (self.y + i) / 2.0; combinedModuleSize := (estimatedModuleSize + newModuleSize) / 2.0; Result := TAlignmentPattern.Create(combinedX, combinedY, combinedModuleSize); end; function NewAlignmentPattern(const posX, posY, estimatedModuleSize: Single):IAlignmentPattern; begin result := TAlignmentPattern.Create(posX,posY,estimatedModuleSize); end; end.
unit AnonymousCallBackUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniGUIBaseClasses, uniButton; type TUniAnonymousCallBackForm = class(TUniForm) UniButton1: TUniButton; UniButton2: TUniButton; procedure UniButton1Click(Sender: TObject); procedure UniButton2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; function UniAnonymousCallBackForm: TUniAnonymousCallBackForm; implementation {$R *.dfm} uses MainModule, uniGUIApplication; function UniAnonymousCallBackForm: TUniAnonymousCallBackForm; begin Result := TUniAnonymousCallBackForm(UniMainModule.GetFormInstance(TUniAnonymousCallBackForm)); end; procedure TUniAnonymousCallBackForm.UniButton1Click(Sender: TObject); begin ModalResult:=mrOK; end; procedure TUniAnonymousCallBackForm.UniButton2Click(Sender: TObject); begin ModalResult:=mrCancel; end; end.
unit uImageHashing; {$mode objfpc}{$H+} interface uses Classes, SysUtils, math, IntfGraphics, FPimage, lcltype, lazcanvas, GraphType, fpcanvas; function imgLoadFromFile(aFile: string): TLazIntfImage; function imgConvertCompatibleGrey(source: TLazIntfImage): TLazIntfImage; function imgScaleCompatible(source: TLazIntfImage; Width, Height: integer; Interpolation: TFPCustomInterpolation = nil): TLazIntfImage; function imgGetData(img: TLazIntfImage): PByte; const HASH_BITS = bitsizeof(QWORD); HASH_SIZE = Trunc(sqrt(HASH_BITS)); type TImageHash = bitpacked array[0..HASH_BITS-1] of boolean; PImageHash = ^TImageHash; PLazIntfImage = ^TLazIntfImage; procedure hashDHash(id: PByte; hash: PImageHash); procedure hashDHashSq3(id: PByte; hash00, hash90, hash180: PImageHash); procedure hashFromFileName(aFile: string; const hash00, hash90, hash180: PImageHash; thumbsize:integer=0; thumb: PLazIntfImage = nil; ImgW: PInteger = nil; ImgH: PInteger = nil); function hashToString(hash: PImageHash): string; implementation function imgLoadFromFile(aFile: string): TLazIntfImage; var source: TLazIntfImage; sourceformat: TRawImage; begin try sourceformat.Init; sourceformat.Description.Init_BPP24_B8G8R8_BIO_TTB(0,0); sourceformat.CreateData(false); source:= TLazIntfImage.Create(0,0); source.SetRawImage(sourceformat); source.LoadFromFile(aFile); Result:= source; except FreeAndNil(source); raise; end; end; function imgConvertCompatibleGrey(source: TLazIntfImage): TLazIntfImage; var grey: TLazIntfImage; py, px: Integer; lgrey, lsource: PRGBTriple; c: TRGBTriple; begin try grey:= TLazIntfImage.CreateCompatible(source, source.Width, source.Height); grey.FillPixels(FPColor(0,0,0)); for py:= 0 to source.Height-1 do begin lsource := source.GetDataLineStart(py); lgrey := grey.GetDataLineStart(py); for px:= 0 to source.Width-1 do begin c:= lsource[px]; { When translating a color image to black and white (mode "L"), the library uses the ITU-R 601-2 luma transform:: } lgrey[px].rgbtRed:= trunc(EnsureRange(c.rgbtRed * 299/1000 + c.rgbtGreen * 587/1000 + c.rgbtBlue * 114/1000, low(byte), high(byte))); end; end; Result:= grey; except FreeAndNil(grey); raise; end; end; function imgScaleCompatible(source: TLazIntfImage; Width, Height: integer; Interpolation: TFPCustomInterpolation): TLazIntfImage; var scale: TLazIntfImage; scalecanvas: TLazCanvas; begin try try scale:= TLazIntfImage.CreateCompatible(source, Width, Height); scalecanvas:= TLazCanvas.Create(scale); scalecanvas.Interpolation:= Interpolation; scalecanvas.StretchDraw(0, 0, scale.Width, scale.Height, source); Result:= scale; finally Interpolation.Free; FreeAndNil(scalecanvas); end; except FreeAndNil(scale); raise; end; end; function imgGetData(img: TLazIntfImage): PByte; var py, px: Integer; lsource: PRGBTriple; begin GetMem(Result, img.Width*img.Height); for py:=0 to img.Height-1 do begin lsource := img.GetDataLineStart(py); for px:=0 to img.Width-1 do begin Result[px+py*img.Width]:= lsource[px].rgbtRed; end; end; end; procedure imgDataRotate90R(source, dest: PByte); var py, px: Integer; begin for py:= 0 to HASH_SIZE - 1 do for px:= 0 to HASH_SIZE - 1 do begin dest[px+py*HASH_SIZE]:= source[(HASH_SIZE-1-py)+px*HASH_SIZE]; end; end; procedure hashDHash(id: PByte; hash: PImageHash); var py, px: Integer; begin for py:= 0 to HASH_SIZE - 1 do for px:= 0 to HASH_SIZE - 1 do begin hash^[px+py*HASH_SIZE]:= id[px+py*HASH_SIZE] < id[px+1+py*HASH_SIZE]; end; end; procedure hashDHashP(id: PByte; hash: PImageHash); var py, px: Integer; begin for py:= 0 to HASH_SIZE - 1 do for px:= 0 to HASH_SIZE - 1 do begin hash^[px+py*HASH_SIZE]:= id[px+py*HASH_SIZE] < id[(px+1) mod HASH_SIZE+py*HASH_SIZE]; end; end; procedure hashDHashSq3(id: PByte; hash00, hash90, hash180: PImageHash); var id1, id2: PByte; begin hashDHashP(id, hash00); GetMem(id1, HASH_SIZE*HASH_SIZE); GetMem(id2, HASH_SIZE*HASH_SIZE); try imgDataRotate90R(id, id1); hashDHashP(id1, hash90); imgDataRotate90R(id1, id2); hashDHashP(id2, hash180); finally Freemem(id1); Freemem(id2); end; end; function BitReverse(b: Byte): Byte; const Lookup:array[0..15] of byte = ($0,$8,$4,$c,$2,$a,$6,$e,$1,$9,$5,$d,$3,$b,$7,$f); begin Result:= (Lookup[b and $f] shl 4) or Lookup[b shr 4]; end; procedure hashFromFileName(aFile: string; const hash00, hash90, hash180: PImageHash; thumbsize: integer; thumb: PLazIntfImage; ImgW: PInteger; ImgH: PInteger); var source, inter, scale, grey: TLazIntfImage; fac: Single; id: PByte; FreeInter: Boolean; begin FreeInter:= false; source:= imgLoadFromFile(aFile); // decimate to something useful first fac:= Max(1,Min(source.Width, source.Height)) / (HASH_SIZE*64); if fac > 1 then begin inter:= imgScaleCompatible(source, trunc(source.Width/fac), trunc(source.Height/fac), TFPBoxInterpolation.Create); FreeInter:= true; end else inter:= source; scale:= imgScaleCompatible(inter, HASH_SIZE, HASH_SIZE, TMitchelInterpolation.Create); grey:= imgConvertCompatibleGrey(scale); if thumbsize>0 then begin if source.Width > source.Height then thumb^:= imgScaleCompatible(inter, thumbsize, thumbsize * source.Height div source.Width) else thumb^:= imgScaleCompatible(inter, thumbsize * source.Width div source.Height, thumbsize) end; if Assigned(ImgW) then begin ImgW^:= source.Width; ImgH^:= source.Height; end; id:= imgGetData(grey); hashDHashSq3(id, hash00, hash90, hash180); Freemem(id); if FreeInter then FreeAndNil(inter); FreeAndNil(scale); FreeAndNil(grey); FreeAndNil(source); end; function hashToString(hash: PImageHash): string; const HexTbl : array[0..15] of char='0123456789ABCDEF'; var i: Integer; b: Byte; begin SetLength(Result{%H-}, HASH_BITS div 8 * 2); for i:= 0 to HASH_BITS div 8 - 1 do begin b:= BitReverse(PByte(hash)[i]); //b:= PBYTE(hash)[i]; Result[1+i*2 ]:= HexTbl[b shr 4]; Result[1+i*2+1]:= HexTbl[b and $f]; end; end; end.
{---------------------------------------------------------------------- DEVIUM Content Management System Copyright (C) 2004 by DEIV Development Team. http://www.deiv.com/ $Header: /devium/Devium\040CMS\0402/Source/Products/ProductsPlugin.pas,v 1.1 2004/04/15 15:01:01 paladin Exp $ ------------------------------------------------------------------------} unit ProductsPlugin; interface uses PluginManagerIntf, PluginIntf, DataModuleIntf, ControlPanelElementIntf, Graphics; type TProductsPlugin = class(TPlugin, IPlugin, IDataModule, IControlPanelElement) private FDataPath: String; FDescription: String; FDisplayName: string; FBitmap: TBitmap; public constructor Create(Module: HMODULE; PluginManager: IPluginManager); destructor Destroy; override; { IPlugin } function GetName: string; function Load: Boolean; function UnLoad: Boolean; { IDataModule } function GetDataPath: String; procedure SetDataPath(const Value: String); { IControlPanelElement } function Execute: Boolean; function GetDescription: string; function GetDisplayName: string; function GetBitmap: TBitmap; end; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; exports RegisterPlugin; implementation uses SysUtils, Windows, prodMainForm; function RegisterPlugin(Module: HMODULE; PluginManager: IPluginManager): Boolean; var Plugin: IInterface; begin Plugin := TProductsPlugin.Create(Module, PluginManager); Result := PluginManager.RegisterPlugin(Plugin); end; { TProductsPlugin } constructor TProductsPlugin.Create(Module: HMODULE; PluginManager: IPluginManager); begin inherited; FBitmap := Graphics.TBitmap.Create; FDisplayName := 'Каталог товаров'; FDescription := 'Каталог товаров'; FBitmap.Handle := LoadBitmap(Module, 'PLUGIN_ICON'); end; destructor TProductsPlugin.Destroy; begin FBitmap.Free; inherited; end; function TProductsPlugin.Execute: Boolean; begin Result := (GetMainForm(FPluginManager, FDataPath) = IDOK); end; function TProductsPlugin.GetBitmap: Graphics.TBitmap; begin Result := FBitmap; end; function TProductsPlugin.GetDataPath: String; begin Result := FDataPath; end; function TProductsPlugin.GetDescription: string; begin Result := FDescription; end; function TProductsPlugin.GetDisplayName: string; begin Result := FDisplayName; end; function TProductsPlugin.GetName: string; begin Result := 'ProductsPlugin'; end; function TProductsPlugin.Load: Boolean; begin Result := True; end; procedure TProductsPlugin.SetDataPath(const Value: String); begin FDataPath := IncludeTrailingPathDelimiter(Value); end; function TProductsPlugin.UnLoad: Boolean; begin Result := True; end; end.
{******************************************************************************* 作者: dmzn 2009-2-2 描述: 可移动的自绘控件 *******************************************************************************} unit UMovedControl; interface uses Windows, Classes, Controls, Graphics, SysUtils, Forms, UBoderControl; type TMarkerType = (mtNone, mtSizeW, mtSizeE, mtSizeN, mtSizeS, mtSizeNW, mtSizeNE, mtSizeSW, mtSizeSE); //控制域类型 TMarker = record FRect: TRect; //控制区域 FType: TMarkerType; //控制域类型 end; TMarkers = array[0..7] of TMarker; //控件的控制域 TZnMovedStatus = (msNone, msMove, msResize); //控件状态 TOnSizeChanged = procedure (nNewW,nNewH: integer; nIsApplyed: Boolean) of Object; TZnMovedControl = class(TGraphicControl) private FShortName: string; {*助记标签*} FSelected: Boolean; FOldPoint: TPoint; FStatus: TZnMovedStatus; {*选择移动*} FOldW,FOldH: integer; FNewW,FNewH: integer; FOldT,FOldL: integer; FNewT,FNewL: integer; FPCanvas: TControlCanvas; {*大小区域*} FMarkers: TMarkers; FActiveMarker: TMarkerType; {*变量相关*} FModeEnter: Byte; FModeExit: Byte; //进出场模式 FSpeedEnter: Byte; FSpeedExit: Byte; //进出场速度 FKeedTime: Byte; FModeSerial: Byte; //停留时间,跟随前屏 F8Bit_LTWH: Boolean; //8bit宽高 FOnMoved: TNotifyEvent; FOnSelected: TNotifyEvent; FOnSizeChanged: TOnSizeChanged; {*事件相关*} protected procedure SetSelected(const nValue: Boolean); procedure SetMouseCursor(const nPoint: TPoint); {*设置鼠标指针*} procedure ChangeWidthHeight(const X,Y: integer); {*设置宽高*} procedure Paint; override; {*自绘*} procedure Resize;override; {*更新控制点*} procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure DoMouseMove(Shift: TShiftState; X, Y: Integer); {*鼠标移动*} public constructor Create(AOwner: TComponent); override; destructor Destroy; override; {*创建释放*} procedure DoPaint(const nCanvas: TCanvas; const nRect: TRect); virtual; {*子类绘制细节*} published property ShortName: string read FShortName write FShortName; property Selected: Boolean read FSelected write SetSelected; property OnSelected: TNotifyEvent read FOnSelected write FOnSelected; property OnMoved: TNotifyEvent read FOnMoved write FOnMoved; property OnSizeChanged: TOnSizeChanged read FOnSizeChanged write FOnSizeChanged; {*标准属性*} property Byte_LTWH: Boolean read F8Bit_LTWH write F8Bit_LTWH; property ModeEnter: Byte read FModeEnter write FModeEnter; property ModeExit: Byte read FModeExit write FModeExit; property SpeedEnter: Byte read FSpeedEnter write FSpeedEnter; property SpeedExit: Byte read FSpeedExit write FSpeedExit; property KeedTime: Byte read FKeedTime write FKeedTime; property ModeSerial: Byte read FModeSerial write FModeSerial; {*扩展相关*} property ParentFont; property Font; property Color; property PopupMenu; property OnClick; property OnDblClick; property OnResize; {*基类属性*} end; implementation const MinClientHW = 8; //最小宽高 MarkerClientHW = 3; //控制区域的大小,左右边线为宽,上下边线为高,四个定点为正方形 MarkerCursors: array[TMarkerType] of TCursor = (crDefault, crSizeWE, crSizeWE, crSizeNS, crSizeNS, crSizeNWSE, crSizeNESW, crSizeNESW, crSizeNWSE); //控制点所对应的鼠标指针 //Date: 2009-02-03 //Name: CreateMarkers //Parm: 某个方形区域,正常情况下为控件有效区域 //Desc: 为nRect边界添加八个控制点 function CreateMarkers(const nRect: TRect): TMarkers; begin with Result[0], nRect do //north-west begin FRect := Rect(Left, Top, Left + MarkerClientHW, Top + MarkerClientHW); FType := mtSizeNW; end; with Result[1], nRect do //north begin FRect.TopLeft := Point(Left + MarkerClientHW, Top); FRect.BottomRight := Point(Right - MarkerClientHW, Top + MarkerClientHW); FType := mtSizeN; end; with Result[2], nRect do //north-east begin FRect.TopLeft := Point(Right - MarkerClientHW, Top); FRect.BottomRight := Point(Right, Top + MarkerClientHW); FType := mtSizeNE; end; with Result[3], nRect do //west begin FRect.TopLeft := Point(Left, Top + MarkerClientHW); FRect.BottomRight := Point(Left + MarkerClientHW, Bottom - MarkerClientHW); FType := mtSizeW; end; with Result[4], nRect do //east begin FRect.TopLeft := Point(Right - MarkerClientHW, Top + MarkerClientHW); FRect.BottomRight := Point(Right, Bottom - MarkerClientHW); FType := mtSizeE; end; with Result[5], nRect do //south-west begin FRect.TopLeft := Point(Left, Bottom - MarkerClientHW); FRect.BottomRight := Point(Left + MarkerClientHW, Bottom); FType := mtSizeSW; end; with Result[6], nRect do //south begin FRect.TopLeft := Point(Left + MarkerClientHW, Bottom - MarkerClientHW); FRect.BottomRight := Point(Right - MarkerClientHW, Bottom); FType := mtSizeS; end; with Result[7], nRect do //south-east begin FRect.TopLeft := Point(Right - MarkerClientHW, Bottom - MarkerClientHW); FRect.BottomRight := Point(Right, Bottom); FType := mtSizeSE; end; end; //Desc: 依据nPoint设置鼠标的指针,主要针对控制点 procedure TZnMovedControl.SetMouseCursor(const nPoint: TPoint); var i: integer; begin FActiveMarker := mtNone; if FSelected then begin for i:=High(FMarkers) downto Low(FMarkers) do if PtInRect(FMarkers[i].FRect, nPoint) then begin FActiveMarker := FMarkers[i].FType; Break; end; end; Cursor := MarkerCursors[FActiveMarker]; end; //Desc: 依据鼠标位置x,y确定宽高 procedure TZnMovedControl.ChangeWidthHeight(const X, Y: integer); var nR: TRect; nInt: integer; begin if not Assigned(FPCanvas) then Exit; FPCanvas.Rectangle(FNewL,FNewT,FNewL+FNewW,FNewT+FNewH); {Erase old draw} case FActiveMarker of mtSizeW, mtSizeNW, mtSizeSW: begin FNewW := FOldW - X + FOldPoint.X; FNewL := FOldL + X - FOldPoint.X; end; mtSizeE, mtSizeNE, mtSizeSE: FNewW := FOldW + X - FOldPoint.X end; {Calculate New Width} case FActiveMarker of mtSizeN, mtSizeNW, mtSizeNE: begin FNewH := FOldH - Y + FOldPoint.Y; FNewT := FOldT + Y - FOldPoint.Y end; mtSizeS, mtSizeSW, mtSizeSE: FNewH := FOldH + Y - FOldPoint.Y; end; {Calculate New Top-Height} if (Parent is TZnBorderControl) then begin nInt := FOldL + FOldW; //右边线 if nInt - FNewL < MinClientHW then FNewL := nInt - MinClientHW; nInt := FOldT + FOldH; //下边线 if nInt - FNewT < MinClientHW then FNewT := nInt - MinClientHW; nR := TZnBorderControl(Parent).ValidClientRect; if FNewL < nR.Left then begin FNewW := FNewW - (nR.Left - FNewL); FNewL := nR.Left; end; if FNewL + FNewW > nR.Right then FNewW := nR.Right - FNewL; //xxxxx if FNewT < nR.Top then begin FNewH := FNewH - (nR.Top - FNewT); FNewT := nR.Top; end; if FNewT + FNewH > nR.Bottom then FNewH := nR.Bottom - FNewT; //xxxxx if FNewW < MinClientHW then FNewW := MinClientHW; if FNewH < MinClientHW then FNewH := MinClientHW; end; if F8Bit_LTWH then begin if FNewW mod 8 <> 0 then begin nInt := FNewW; if FNewW > Width then FNewW := (Trunc(FNewW / 8) + 1) * 8 else FNewW := Trunc(FNewW / 8) * 8; case FActiveMarker of mtSizeW,mtSizeNW,mtSizeSW: FNewL := FNewL + (nInt - FNewW); end; end; { if FNewH mod 8 <> 0 then begin nInt := FNewH; if FNewH > Height then FNewH := (Trunc(FNewH / 8) + 1) * 8 else FNewH := Trunc(FNewH / 8) * 8; case FActiveMarker of mtSizeN,mtSizeNW,mtSizeNE: FNewT := FNewT + (nInt - FNewH); end; end; } end; FPCanvas.Rectangle(FNewL,FNewT,FNewL+FNewW,FNewT+FNewH); {Parent Container Draw Rectangle} if Assigned(FOnSizeChanged) then FOnSizeChanged(FNewW, FNewH, False); end; //------------------------------------------------------------------------------ constructor TZnMovedControl.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 64; Height := 64; Color := clBlack; FStatus := msNone; FSelected := False; FActiveMarker := mtNone; F8Bit_LTWH := True; FModeEnter := 0; FModeExit := 0; FSpeedEnter := 0; FSpeedExit := 0; FKeedTime := 0; FModeSerial := 1; end; destructor TZnMovedControl.Destroy; begin if Assigned(FPCanvas) then FPCanvas.Free; inherited; end; //Desc: 自绘过程 procedure TZnMovedControl.Paint; begin with Canvas do begin if FStatus = msNone then begin DoPaint(Canvas, ClientRect); end else //子类绘制 begin Brush.Color := Color; FillRect(ClientRect); end; if Selected then begin Brush.Style := bsClear; Pen.Color := clYellow; Pen.Width := 1; Rectangle(ClientRect); end; end; end; //Desc: 子类向nCanvas画布绘制有效内容 procedure TZnMovedControl.DoPaint(const nCanvas: TCanvas; const nRect: TRect); begin nCanvas.Brush.Color := Color; nCanvas.FillRect(nRect); end; //------------------------------------------------------------------------------ procedure TZnMovedControl.DoMouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Selected := True; if Button <> mbLeft then Exit; FOldPoint := Point(X, Y); if FActiveMarker = mtNone then begin FStatus := msMove; end else begin FStatus := msReSize; FOldT := Top; FOldL := Left; FNewT := Top; FNewL := Left; FOldW := Width; FOldH := Height; FNewW := Width; FNewH := Height; if ( Parent <> nil ) and ( FPCanvas = nil) then begin FPCanvas := TControlCanvas.Create; with FPCanvas do begin Control := Parent; Brush.Style := bsClear; Pen.Width := 1; Pen.Color := clBlack; Pen.Style := psSolid; Pen.Mode := pmNotXor; end; end; {Create Canvas as Parent.Canvas} if Assigned(FPCanvas) then FPCanvas.Rectangle(FNewL,FNewT,FNewL+FNewW,FNewT+FNewH); {First Rectangle} end; end; procedure TZnMovedControl.DoMouseMove(Shift: TShiftState; X, Y: Integer); var nR: TRect; nL,nT: Integer; begin if FStatus = msMove then begin nL := Left + (X - FOldPoint.X); nT := Top + (Y - FOldPoint.Y); //new position if (Parent is TZnBorderControl) then begin nR := TZnBorderControl(Parent).ValidClientRect; if nL < nR.Left then nL := nR.Left; if nL + Width > nR.Right then nL := nR.Right - Width; if nT < nR.Top then nT := nR.Top; if nT + Height > nR.Bottom then nT := nR.Bottom - Height; end; Left := nL; Top := nT; Application.ProcessMessages; if Assigned(FOnMoved) then FOnMoved(Self); Exit; end else //组件移动 if FStatus = msResize then begin ChangeWidthHeight(X, Y); end else //调整大小 begin SetMouseCursor(Point(X, Y)); {Change Mouse Cursor} end; end; procedure TZnMovedControl.DoMouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var nR: TRect; nL,nT: integer; begin if FStatus = msMove then begin if F8Bit_LTWH and (Parent is TZnBorderControl) then begin nR := TZnBorderControl(Parent).ValidClientRect; nL := Left - nR.Left; nT := Top - nR.Top; if nL mod 8 > 4 then nL := (Trunc(nL / 8) + 1) * 8 else nL := Trunc(nL / 8) * 8; if nT mod 8 > 4 then nT := (Trunc(nT / 8) + 1) * 8 else nT := Trunc(nT / 8) * 8; nL := nL + nR.Left; nT := nT + nR.Top; if (nL <> Left) or (nT <> Top) then begin Left := nL; Top := nT; if Assigned(FOnMoved) then FOnMoved(Self); end; end; Invalidate; end else if FStatus = msResize then begin FPCanvas.Rectangle(FNewL,FNewT,FNewL+FNewW,FNewT+FNewH); {Erase old draw} FreeAndNil(FPCanvas); Left := FNewL; Top := FNewT; if (Width <> FNewW) or (Height <> FNewH) then begin Width := FNewW; Height := FNewH; if Assigned(FOnSizeChanged) then FOnSizeChanged(FNewW, FNewH, True); {*New Form Size*} end; end; FStatus := msNone; BringToFront; end; procedure TZnMovedControl.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if not (ssDouble in Shift) then DoMouseDown(Button, Shift, X, Y); inherited; end; procedure TZnMovedControl.MouseMove(Shift: TShiftState; X, Y: Integer); begin DoMouseMove(Shift, X, Y); inherited; end; procedure TZnMovedControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin DoMouseUp(Button, Shift, X, Y); inherited; end; //------------------------------------------------------------------------------ procedure TZnMovedControl.SetSelected(const nValue: Boolean); begin if nValue <> FSelected then begin FSelected := nValue; Invalidate; if Assigned(FOnSelected) then FOnSelected(Self); end; end; //Desc: 调整区域 procedure TZnMovedControl.Resize; begin inherited; FMarkers := CreateMarkers(ClientRect); end; end.
program GameOfLife; uses sysutils, Crt; const xSize = 50; ySize = 50; Space = ' '; Star = '*'; type CellType = record alive : boolean; livingNeighbors : integer; end; GridType = Array[1..xSize,1..ySize] of CellType; var grid: GridType; i, j, generation, numAlive: integer; procedure initializeGrid(var grid: GridType; aliveFactor: Real); begin for i := 1 to xSize do for j := 1 to ySize do begin grid[i,j].alive := Random(100) < 100*aliveFactor; grid[i,j].livingNeighbors := 0; end; end; procedure printBoard(var grid: GridType); var i, j : integer; begin for i :=1 to xSize do begin for j := 1 to ySize do if grid[i,j].alive then write(Star, Space) else write(Space, Space); writeln; end; writeln('Generation = ', generation, ', NumAlive = ', numAlive); end; function calcNumAlive(var grid: GridType) : integer; var i, j : integer; begin calcNumAlive := 0; for i := 1 to xSize do for j := 1 to ySize do begin if grid[i,j].alive = true then calcNumAlive := calcNumAlive + 1; end; end; function adjustX(x : integer) : integer; begin if x >= xSize then x -= xSize; if x < 0 then x += xSize; adjustX := x; end; function adjustY(y : integer) : integer; begin if y >= xSize then y -= xSize; if y < 0 then y += xSize; adjustY := y; end; function getCellLivingNeighbors(var grid: GridType; x, y : integer): integer; var adjScore : integer; begin adjScore := 0; if grid[adjustX(x-1), adjustY(y-1)].alive then adjScore := adjScore + 1; if grid[adjustX(x-1), adjustY(y)].alive then adjScore := adjScore + 1; if grid[adjustX(x-1), adjustY(y+1)].alive then adjScore := adjScore + 1; if grid[adjustX(x), adjustY(y-1)].alive then adjScore := adjScore + 1; if grid[adjustX(x), adjustY(y+1)].alive then adjScore := adjScore + 1; if grid[adjustX(x+1), adjustY(y-1)].alive then adjScore := adjScore + 1; if grid[adjustX(x+1), adjustY(y)].alive then adjScore := adjScore + 1; if grid[adjustX(x+1), adjustY(y+1)].alive then adjScore := adjScore + 1; getCellLivingNeighbors := adjScore; end; procedure calculateLivingGridNeighbors(var grid: GridType); var i, j : integer; begin for i := 1 to xSize do for j := 1 to ySize do grid[i,j].livingNeighbors := getCellLivingNeighbors(grid, i, j); end; {* living cells die if 0, 1, or 4 or more neighbors *} {* deads cells come to life if 3 neighbors *} procedure makeNextGeneration(var grid: GridType); var i, j : integer; begin for i := 1 to xSize do for j := 1 to ySize do begin if (grid[i,j].livingNeighbors <= 1) or (grid[i,j].livingNeighbors >= 4) then grid[i,j].alive := false; if (grid[i,j].alive = false) and (grid[i,j].livingNeighbors = 3) then grid[i,j].alive := true; end; end; procedure runSim(var grid: GridType); begin generation := 0; numAlive := calcNumAlive(grid); printBoard(grid); while numAlive > 0 do begin Sleep(250); generation := generation + 1; calculateLivingGridNeighbors(grid); makeNextGeneration(grid); numAlive := calcNumAlive(grid); ClrScr; printBoard(grid); end; end; {* main program *} begin Randomize; initializeGrid(grid, 0.5); runSim(grid); end.
unit Loops; interface uses Classes, Types, Generics.Collections, CodeElement, WriterIntf; type TLoop = class(TCodeElement) private FRelation: TObjectList<TCodeElement>; public constructor Create(); destructor Destroy(); override; property Relation: TObjectList<TCodeElement> read FRelation; end; TWhileLoop = class(TLoop) public procedure GetDCPUSource(AWriter: IWriter); override; end; TRepeatLoop = class(TLoop) public procedure GetDCPUSource(AWriter: IWriter); override; end; TForLoop = class(TLoop) private FAssignment: TObjectList<TCodeElement>; public constructor Create(); destructor Destroy(); override; procedure GetDCPUSource(AWriter: IWriter); override; property Assignment: TObjectList<TCodeElement> read FAssignment; end; implementation uses Optimizer, Assignment; { TLoop } constructor TLoop.Create; begin inherited Create(''); FRelation := TObjectList<TCodeElement>.Create(); end; destructor TLoop.Destroy; begin FRelation.Free; inherited; end; { TWhileLoop } procedure TWhileLoop.GetDCPUSOurce; var LID: string; LEnd: string; LWhile: string; begin AWriter.AddMapping(Self); LID := GetUniqueID(); LWhile := 'While' + LID; LEnd := 'End' + LID; Self.Write(':' + LWhile); FRelation.Items[0].GetDCPUSource(Self); Self.Write('set x, pop'); Self.Write('ife x, 0'); Self.Write('set pc, ' + LEnd); OptimizeDCPUCode(Self.FSource, Self.FSource); AWriter.WriteList(Self.FSource); inherited; AWriter.Write('set pc, ' + LWhile); AWriter.Write(':' + LEnd); end; { TRepeatLoop } procedure TRepeatLoop.GetDCPUSOurce; var LID: string; LRepeat: string; begin AWriter.AddMapping(Self); LID := GetUniqueID(); LRepeat := 'Repeat' + LID; AWriter.Write(':' + LRepeat); inherited; FRelation.Items[0].GetDCPUSource(Self); Self.Write('set x, pop'); Self.Write('ifn x, 0'); Self.Write('set pc, ' + LRepeat); OptimizeDCPUCode(Self.FSource, Self.FSource); AWriter.WriteList(Self.FSource); end; { TForLoop } constructor TForLoop.Create; begin inherited; FAssignment := TObjectList<TCodeElement>.Create(); end; destructor TForLoop.Destroy; begin FAssignment.Free; inherited; end; procedure TForLoop.GetDCPUSource; var LID: string; LFor: string; LEnd: string; LVar: string; begin AWriter.AddMapping(Self); LID := GetUniqueID(''); LVar := TAssignment(Assignment.Items[0]).TargetVar.GetAccessIdentifier(); if (TAssignment(Assignment.Items[0]).TargetVar.ParamIndex > 3) or (TAssignment(Assignment.Items[0]).TargetVar.ParamIndex < 1) then begin LVar := '[' + LVar + ']'; end; LFor := 'for' + LID; LEnd := 'end' + LID; Assignment.Items[0].GetDCPUSource(Self); OptimizeDCPUCode(Self.FSource, Self.FSource); AWriter.WriteList(Self.FSource); Self.FSource.Clear; //clear it, because we are going to write a new statement to it Relation.Items[0].GetDCPUSource(Self); OptimizeDCPUCode(Self.FSource, Self.FSource); AWriter.WriteList(Self.FSource); AWriter.Write(':' + LFor); AWriter.Write('set x, pop'); AWriter.Write('ifg ' + LVar + ', x'); AWriter.Write('set pc, ' + LEnd); AWriter.Write('set push, x'); inherited; AWriter.Write('add ' + LVar + ', 1'); AWriter.Write('set pc, ' + LFor); AWriter.Write(':' + LEnd); end; end.
unit HopcroftKarp; {$mode objfpc}{$H+} interface uses Dialogs, Classes, SysUtils, PartnerStack, CoupleStack, VertexStack, EdgeStack; type TBipartiteGraph = record Brides: VertexNode; Grooms: VertexNode; Matches: EdgeNode; AugmentingPath: EdgeNode; end; { BipartiteGraph } function FindMaxCouples(var Brides: PartnerNode; var Grooms: PartnerNode): CoupleNode; function GraphDFS(var G: TBipartiteGraph; var V: Vertex): boolean; function GraphBFS(var G: TBipartiteGraph): Vertex; {Helpers} procedure CleanVisitedMarks(var G: TBipartiteGraph); procedure GetMatches(var G: TBipartiteGraph); procedure LoadPartners(var Top: VertexNode; var P: PartnerNode); implementation function FindMaxCouples(var Brides: PartnerNode; var Grooms: PartnerNode): CoupleNode; var TempBrides: VertexNode = nil; TempGrooms: VertexNode = nil; FreeVertex: Vertex = nil; C: TCouple; G: TBipartiteGraph = (Brides: nil; Grooms: nil; Matches: nil; AugmentingPath: nil); begin Result := nil; // Загружаю стэк невест в граф LoadPartners(G.Grooms, Grooms); // Загружаю стэк партнеров в граф LoadPartners(G.Brides, Brides); // Сохраняю ссылку на верх стэка невест TempBrides := G.Brides; // Составляю граф совпадений // Пока не дошел до конца стэка while G.Brides <> nil do begin // Сохраняю ссылку на верх стэка невест TempGrooms := G.Grooms; // Пока не дошел до конца стэка while G.Grooms <> nil do begin // Есл их критерии совпали if IsItMatch(G.Brides^.Data^.Partner, G.Grooms^.Data^.Partner) then begin // Добавляю невесту в список подходящих партнеров VertexStack.Push(G.Grooms^.Data^.SuitablePartners, G.Brides^.Data); // Добавялю жениха в список подходящих партнеров VertexStack.Push(G.Brides^.Data^.SuitablePartners, G.Grooms^.Data); end; // Передвигаюсь дальше по стэку женихов G.Grooms := G.Grooms^.Next; end; // Восстанавливаю указатель на верх стэка G.Grooms := TempGrooms; // Передвигаюсь дальше по стэку невест G.Brides := G.Brides^.Next; end; // Восстанавливаю указатель на верх стэка G.Brides := TempBrides; // Получаю первую свободную вершину FreeVertex := GraphBFS(G); // Пока есть свободная вершина while FreeVertex <> nil do begin // Если нет дополняющего пути из свободной вершины, // то помечаю вершину как несвободную if GraphDFS(G, FreeVertex) <> True then FreeVertex^.IsFree := False else // Иначе, увеличиваю стэк пар за счет увеличивающегося пути. GetMatches(G); // Убираю отметки о посещении CleanVisitedMarks(G); // Получаю следующую свободную вершину FreeVertex := GraphBFS(G); end; // Пока не дошел до конца стэка while G.Matches <> nil do begin // Создаю новую пару C := CoupleStack.NewCouple(G.Matches^.Data^.Bride^.Partner, G.Matches^.Data^.Groom^.Partner); // Добавляю пару в результат работы функции(стэк пар) CoupleStack.Push(Result, C); // Удаляю совпавщую пару и двигаюсь дальше по циклу EdgeStack.Pop(G.Matches); end; // Освобождаю память VertexStack.Free(G.Brides); VertexStack.Free(G.Grooms); end; { Обход графа в ширину. Поиск первой свободной вершины } function GraphBFS(var G: TBipartiteGraph): Vertex; var TempBride: VertexNode; TempGroom: VertexNode; begin Result := nil; // Сохраняю ссылку на верх стэка невест TempBride := G.Brides; // Сохраняю ссылку на верх стэка женихов TempGroom := G.Grooms; // Пока не дошел до конца стэка и не нашёл свободную вершину while (G.Grooms <> nil) and (Result = nil) do begin // Если вершина свободная, то записываем указатель в результат функции if G.Grooms^.Data^.IsFree then Result := G.Grooms^.Data; G.Grooms := G.Grooms^.Next; end; // Пока не дошел до конца стэка и не нашёл свободную вершину while (G.Brides <> nil) and (Result = nil) do begin // Если вершина свободная, то записываем указатель в результат функции if G.Brides^.Data^.IsFree then Result := G.Brides^.Data; G.Brides := G.Brides^.Next; end; // Восстанавливаю ссылки на верх стэка G.Brides := TempBride; G.Grooms := TempGroom; end; { Обход графа в глубину начиная от вершины V. Поиск увеличивающего пути } function GraphDFS(var G: TBipartiteGraph; var V: Vertex): boolean; var TempNode: VertexNode = nil; SuitablePartner: Vertex = nil; begin // Если переданная вершина несуществует или была посещена, // то выхожу из функции с результатом того, что нет увеличивающего пути if (V = nil) or V^.IsVisited then begin Result := False; Exit; end; // Помечаю вершину как посещенную V^.IsVisited := True; // Сохраняю ссылку на верх стэка подходящих партнеров TempNode := V^.SuitablePartners; // Пока не дошел до конца стэка while V^.SuitablePartners <> nil do begin SuitablePartner := V^.SuitablePartners^.Data; // Если подходящий партнер свободен или есть увеличивающий путь, // то добавляю пару в список совпадений. if SuitablePartner^.IsFree or GraphDFS(G, SuitablePartner) then begin // Отмечаю вершину как занятую(есть партнер) V^.IsFree := False; // Отмечаю вершину подходящего партнера как занятую(есть партнер) SuitablePartner^.IsFree := False; // Добавляю пару в увеличивающий путь // Невеста всегда идет первая в паре if V^.Partner.Sex = PartnerSex.man then EdgeStack.Push(G.AugmentingPath, EdgeStack.NewEdge(SuitablePartner, V)) else EdgeStack.Push(G.AugmentingPath, EdgeStack.NewEdge(V, SuitablePartner)); // Восстанавливаю ссылку на верх стэка подходящих партнеров V^.SuitablePartners := TempNode; // Выхожу с положительным результатом // (нашли свободного партнера или дополняющий путь) Result := True; Exit; end; V^.SuitablePartners := V^.SuitablePartners^.Next; end; // Восстанавливаю ссылку на верх стэка подходящих партнеров V^.SuitablePartners := TempNode; // В иных случаях пути не существует. Result := False; end; { Процедура удаления отметок о посещении } procedure CleanVisitedMarks(var G: TBipartiteGraph); var TempNode: VertexNode = nil; begin // Сохраняю ссылку на верх стэка невест TempNode := G.Brides; // Пока не дошел до конца стэка while G.Brides <> nil do begin // Удаляю отметку о песещении G.Brides^.Data^.IsVisited := False; G.Brides := G.Brides^.Next; end; // Восстанавливаю ссылку на верх стэка невест G.Brides := TempNode; // Сохраняю ссылку на верх стэка невест TempNode := G.Grooms; // Пока не дошел до конца стэка while G.Grooms <> nil do begin // Удаляю отметку о песещении G.Grooms^.Data^.IsVisited := False; G.Grooms := G.Grooms^.Next; end; // Восстанавливаю ссылку на верх стэка женихов G.Grooms := TempNode; end; { Процедура увеличения наибольшего паросочетания } procedure GetMatches(var G: TBipartiteGraph); var TempAugmentingPath: EdgeNode = nil; TempMatches: EdgeNode = nil; begin // Сохраняю ссылку на верх стэка увеличивающего пути TempAugmentingPath := G.AugmentingPath; // Пока не дошел до конца стэка while G.AugmentingPath <> nil do begin // Сохраняю ссылку на верх стэка совпадений TempMatches := G.Matches; // Пока не дошел до конца стэка while (G.Matches <> nil) and (G.AugmentingPath <> nil) do begin // Если звено есть и в увеличивающим пути, и в стэке совпадений, // тогда удаляю это звено из обоих стэков (симметрическая разность) if (G.Matches^.Data^.Bride = G.AugmentingPath^.Data^.Bride) and (G.Matches^.Data^.Groom = G.AugmentingPath^.Data^.Groom) then begin EdgeStack.Delete(TempAugmentingPath, G.AugmentingPath); EdgeStack.Delete(TempMatches, G.Matches); end; if G.Matches <> nil then G.Matches := G.Matches^.Next; end; // Восстанавливаю ссылку на верх стэка совпадений G.Matches := TempMatches; if G.AugmentingPath <> nil then G.AugmentingPath := G.AugmentingPath^.Next; end; // Восстанавливаю ссылку на верх стэка увеличивающего пути G.AugmentingPath := TempAugmentingPath; // Добавляю новые звенья увеличивающего пути в стэк совпадений // Пока не дошел до конца стэка while G.AugmentingPath <> nil do begin EdgeStack.Push(G.Matches, G.AugmentingPath^.Data); G.AugmentingPath := G.AugmentingPath^.Next; end; // Восстанавливаю ссылку на верх стэка дополняющего пути G.AugmentingPath := TempAugmentingPath; end; { Процедура загрузки женихов в граф } procedure LoadPartners(var Top: VertexNode; var P: PartnerNode); var TempPartner: PartnerNode = nil; begin // Сохраняю ссылку на верх стэка партнеров TempPartner := P; // Пока не дошел до конца стэка while P <> nil do begin // Добавляю партнера в стэк вершин графа VertexStack.PushPartner(Top, P^.Data, nil); P := P^.Next; end; // Восстанавливаю ссылку на верх стэка партнеров P := TempPartner; end; end.
unit CommonUtil; interface uses IdCoder, IdCoderMIME, IdHashMessageDigest, ZLibEx; type TCommonUtil = class private public //编码 class function md5(s: string): string; class function base64(s: string): string; class function deBase64(s: string): string; class function compressAndBase64(s: string): string; class function deBase64AndDecompress(s: string): string; end; implementation class function TCommonUtil.base64(s: string): string; var encode: TIdEncoderMIME; begin encode := TIdEncoderMIME.Create(nil); try result := encode.EncodeString(s); finally encode.Free; end; end; class function TCommonUtil.compressAndBase64(s: string): string; begin Result := base64(ZCompressStr(s)); end; class function TCommonUtil.deBase64(s: string): string; var decode: TIdDecoderMIME; begin if Length(s) mod 2 <> 0 then //字符串长度是2的倍数才能解码 begin result := ''; exit; end; decode := TIdDecoderMIME.Create(nil); try result := decode.DecodeString(s); finally decode.Free; end; end; class function TCommonUtil.deBase64AndDecompress(s: string): string; begin Result := ZDeCompressStr(DeBase64(s)); end; class function TCommonUtil.md5(s: string): string; var md5: TIdHashMessageDigest5; begin md5 := TIdHashMessageDigest5.Create; try result := md5.AsHex(md5.HashValue(s)); finally md5.Free; end; end; end.
unit IMP_SmartFunctions; interface uses Forms, Classes, SmartFunctions, Variants, BASE_SYS, BASE_EXTERN, PaxScripter; procedure RegisterIMP_SmartFunctions; implementation procedure TCalledFunctions_UpdateHPI(MethodBody: TPAXMethodBody); begin with MethodBody do TCalledFunctions(Self).UpdateHPI(); end; procedure TCalledFunctions_CalcAge1(MethodBody: TPAXMethodBody); begin with MethodBody do result.AsInteger := TCalledFunctions(Self).CalcAge(Params[0].AsString); end; procedure TCalledFunctions_ShowValue(MethodBody: TPAXMethodBody); begin with MethodBody do TCalledFunctions(Self).ShowValue(Params[0].AsString); end; function TCalledFunctions__GetMainForm(Self:TCalledFunctions):TForm; begin result := Self.MainForm; end; procedure TCalledFunctions__PutMainForm(Self:TCalledFunctions;const Value: TForm); begin Self.MainForm := Value; end; procedure RegisterIMP_SmartFunctions; var H: Integer; begin H := RegisterNamespace('SmartFunctions', -1); // Begin of class TCalledFunctions RegisterClassType(TCalledFunctions, H); RegisterMethod(TCalledFunctions, 'procedure EvaluateValues(FieldList: array of string;ValueList: array of Integer;TheMessage: String='''');', @TCalledFunctions.EvaluateValues); RegisterStdMethodEx(TCalledFunctions,'UpdateHPI',TCalledFunctions_UpdateHPI,0,[typeVARIANT]); RegisterStdMethodEx(TCalledFunctions,'CalcAge',TCalledFunctions_CalcAge1,1,[typeSTRING,typeINTEGER]); RegisterStdMethodEx(TCalledFunctions,'ShowValue',TCalledFunctions_ShowValue,1,[typeSTRING,typeVARIANT]); RegisterMethod(TCalledFunctions, 'function TCalledFunctions__GetMainForm(Self:TCalledFunctions):TForm;', @TCalledFunctions__GetMainForm, true); RegisterMethod(TCalledFunctions, 'procedure TCalledFunctions__PutMainForm(Self:TCalledFunctions;const Value: TForm);', @TCalledFunctions__PutMainForm, true); RegisterProperty(TCalledFunctions, 'property MainForm:TForm read TCalledFunctions__GetMainForm write TCalledFunctions__PutMainForm;'); RegisterMethod(TCalledFunctions, 'constructor Create(AOwner: TComponent); virtual;', @TCalledFunctions.Create); // End of class TCalledFunctions end; initialization RegisterIMP_SmartFunctions; end.
program ProceduresAndFunctions; const NUM1 = 42; NUM2 = 69; NUM3 = 171; var minimal : integer; { will be changed by procedure } { the input paremeters are both of the integer type } { the return paremeter is too, of the integer type } function max(a, b: integer): integer; var { local variables to the function } result: integer; begin if ( a > b ) then result := a else result := b; max := result; { Wirth really messed this one } { how about a fu--ing RETURN statement mate? } { IE: you assign the return value to the name } { of the function. Which is pretty weird. } end; function better_max(a, b: integer): integer; begin if a > b then better_max := a else better_max := b; end; procedure find_min(x, y, z: integer; var m: integer); { <- pointer here } begin if x < y then m:= x else m:= y; if z < m then m := z; end; begin writeln('function should return the higher number. '); writeln('the numbers are: ( ', NUM1, ' ) and ( ', NUM2 , ' ). '); writeln('result is: ', max(NUM1, NUM2) ); writeln; writeln('getting the lowerst of three numbers with a procedure. '); writeln('the numbers are: ( ', NUM1, ', ', NUM2, ', ', NUM3, ' ) '); find_min( NUM1, NUM2, NUM3, minimal ); { procedure call } writeln(' lowest number is: ', minimal ); end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.objectset.adapter; interface uses Rtti, TypInfo, Classes, Variants, Generics.Collections, /// orm ormbr.objectset.abstract, ormbr.factory.interfaces, ormbr.session.objectset, ormbr.mapping.classes, ormbr.types.mapping, ormbr.container.objectset.interfaces; type /// <summary> /// M - Object M /// </summary> TObjectSetAdapter<M: class, constructor> = class(TObjectSetAbstract<M>) private FObjectState: TDictionary<string, TObject>; FSession: TSessionObjectSet<M>; FConnection: IDBConnection; procedure CascadeActionsExecute(const AObject: TObject; const ACascadeAction: TCascadeAction); procedure OneToOneCascadeActionsExecute(const AObject: TObject; const AAssociation: TAssociationMapping; const ACascadeAction: TCascadeAction); procedure OneToManyCascadeActionsExecute(const AObject: TObject; const AAssociation: TAssociationMapping; const ACascadeAction: TCascadeAction); procedure SetAutoIncValueChilds(const AObject: TObject; const AColumn: TColumnMapping); procedure SetAutoIncValueOneToOne(const AObject: TObject; const AAssociation: TAssociationMapping; const AProperty: TRttiProperty); procedure SetAutoIncValueOneToMany(const AObject: TObject; const AAssociation: TAssociationMapping; const AProperty: TRttiProperty); procedure AddObjectState(const ASourceObject: TObject); procedure UpdateInternal(const AObject: TObject); function GenerateKey(const AObject: TObject): string; public constructor Create(const AConnection: IDBConnection; const APageSize: Integer = -1); virtual; destructor Destroy; override; function ExistSequence: Boolean; function ModifiedFields: TDictionary<string, TList<string>>; function Find: TObjectList<M>; overload; function Find(const AID: Integer): M; overload; function FindWhere(const AWhere: string; const AOrderBy: string = ''): TObjectList<M>; overload; procedure Insert(const AObject: M); procedure Update(const AObject: M); procedure Delete(const AObject: M); procedure Modify(const AObject: M); procedure NextPacket(const AObjectList: TObjectList<M>); end; implementation uses ormbr.rtti.helper, ormbr.objects.helper, ormbr.mapping.explorer; { TObjectSetAdapter<M> } constructor TObjectSetAdapter<M>.Create(const AConnection: IDBConnection; const APageSize: Integer); begin FConnection := AConnection; FSession := TSessionObjectSet<M>.Create(AConnection, APageSize); FObjectState := TObjectDictionary<string, TObject>.Create([doOwnsValues]); end; procedure TObjectSetAdapter<M>.Delete(const AObject: M); var LInTransaction: Boolean; LIsConnected: Boolean; begin /// <summary> /// Controle de transação externa, controlada pelo desenvolvedor /// </summary> LInTransaction := FConnection.InTransaction; LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try if not LInTransaction then FConnection.StartTransaction; try /// <summary> /// Executa comando delete em cascade /// </summary> CascadeActionsExecute(AObject, CascadeDelete); /// <summary> /// Executa comando delete master /// </summary> FSession.Delete(AObject); /// if not LInTransaction then FConnection.Commit; except if not LInTransaction then FConnection.Rollback; raise; end; finally if not LIsConnected then FConnection.Disconnect; end; end; destructor TObjectSetAdapter<M>.Destroy; begin FObjectState.Clear; FObjectState.Free; FSession.Free; inherited; end; function TObjectSetAdapter<M>.ExistSequence: Boolean; begin Result := FSession.ExistSequence; end; function TObjectSetAdapter<M>.FindWhere(const AWhere, AOrderBy: string): TObjectList<M>; var LIsConnected: Boolean; begin LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try Result := FSession.FindWhere(AWhere, AOrderBy); finally if not LIsConnected then FConnection.Disconnect; end; end; function TObjectSetAdapter<M>.Find(const AID: Integer): M; var LIsConnected: Boolean; begin LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try Result := FSession.Find(AID); finally if not LIsConnected then FConnection.Disconnect; end; end; function TObjectSetAdapter<M>.Find: TObjectList<M>; var LIsConnected: Boolean; begin LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try Result := FSession.Find; finally if not LIsConnected then FConnection.Disconnect; end; end; procedure TObjectSetAdapter<M>.Insert(const AObject: M); var LColumn: TColumnMapping; LInTransaction: Boolean; LIsConnected: Boolean; begin /// <summary> /// Controle de transação externa, controlada pelo desenvolvedor /// </summary> LInTransaction := FConnection.InTransaction; LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try if not LInTransaction then FConnection.StartTransaction; try FSession.Insert(AObject); if FSession.ExistSequence then begin for LColumn in AObject.GetPrimaryKey do SetAutoIncValueChilds(AObject, LColumn); end; /// <summary> /// Executa comando insert em cascade /// </summary> CascadeActionsExecute(AObject, CascadeInsert); /// if not LInTransaction then FConnection.Commit; except if not LInTransaction then FConnection.Rollback; raise; end; finally if not LIsConnected then FConnection.Disconnect; end; end; function TObjectSetAdapter<M>.ModifiedFields: TDictionary<string, TList<string>>; begin Result := FSession.ModifiedFields; end; procedure TObjectSetAdapter<M>.Modify(const AObject: M); begin FObjectState.Clear; AddObjectState(AObject); end; procedure TObjectSetAdapter<M>.NextPacket(const AObjectList: TObjectList<M>); begin FSession.NextPacket(AObjectList); end; procedure TObjectSetAdapter<M>.SetAutoIncValueChilds(const AObject: TObject; const AColumn: TColumnMapping); var LAssociation: TAssociationMapping; LAssociations: TAssociationMappingList; begin /// Association LAssociations := TMappingExplorer.GetInstance.GetMappingAssociation(AObject.ClassType); if LAssociations <> nil then begin for LAssociation in LAssociations do begin if CascadeAutoInc in LAssociation.CascadeActions then begin if LAssociation.Multiplicity in [OneToOne, ManyToOne] then SetAutoIncValueOneToOne(AObject, LAssociation, AColumn.PropertyRtti) else if LAssociation.Multiplicity in [OneToMany, ManyToMany] then SetAutoIncValueOneToMany(AObject, LAssociation, AColumn.PropertyRtti); end; end; end; end; procedure TObjectSetAdapter<M>.SetAutoIncValueOneToMany(const AObject: TObject; const AAssociation: TAssociationMapping; const AProperty: TRttiProperty); var LType: TRttiType; LProperty: TRttiProperty; LValue: TValue; LObjectList: TObjectList<TObject>; LObject: TObject; LFor: Integer; LIndex: Integer; begin LValue := AAssociation.PropertyRtti.GetNullableValue(AObject); if LValue.IsObject then begin LObjectList := TObjectList<TObject>(LValue.AsObject); for LFor := 0 to LObjectList.Count -1 do begin LObject := LObjectList.Items[LFor]; if LObject.GetType(LType) then begin LIndex := AAssociation.ColumnsName.IndexOf(AProperty.Name); if LIndex > -1 then begin LProperty := LType.GetProperty(AAssociation.ColumnsNameRef.Items[LIndex]); if LProperty <> nil then LProperty.SetValue(LObject, AProperty.GetValue(AObject)); end; end; end; end; end; procedure TObjectSetAdapter<M>.SetAutoIncValueOneToOne(const AObject: TObject; const AAssociation: TAssociationMapping; const AProperty: TRttiProperty); var LType: TRttiType; LProperty: TRttiProperty; LValue: TValue; LObject: TObject; LIndex: Integer; begin LValue := AAssociation.PropertyRtti.GetNullableValue(AObject); if LValue.IsObject then begin LObject := LValue.AsObject; if LObject.GetType(LType) then begin LIndex := AAssociation.ColumnsName.IndexOf(AProperty.Name); if LIndex > -1 then begin LProperty := LType.GetProperty(AAssociation.ColumnsNameRef.Items[LIndex]); if LProperty <> nil then LProperty.SetValue(LObject, AProperty.GetValue(AObject)); end; end; end; end; procedure TObjectSetAdapter<M>.Update(const AObject: M); var LRttiType: TRttiType; LProperty: TRttiProperty; LObject: TObject; LKey: string; LInTransaction: Boolean; LIsConnected: Boolean; begin /// <summary> /// Controle de transação externa, controlada pelo desenvolvedor /// </summary> LInTransaction := FConnection.InTransaction; LIsConnected := FConnection.IsConnected; if not LIsConnected then FConnection.Connect; try if not LInTransaction then FConnection.StartTransaction; try /// <summary> /// Executa comando update em cascade /// </summary> CascadeActionsExecute(AObject, CascadeUpdate); /// <summary> /// Gera a lista com as propriedades que foram alteradas /// </summary> if TObject(AObject).GetType(LRttiType) then begin LKey := GenerateKey(AObject); if FObjectState.ContainsKey(LKey) then begin LObject := FObjectState.Items[LKey]; FSession.ModifyFieldsCompare(LKey, AObject, LObject); FObjectState.Remove(LKey); FSession.Update(AObject, LKey); end; /// <summary> /// Remove o item excluído em Update Mestre-Detalhe /// </summary> for LObject in FObjectState.Values do FSession.Delete(LObject); end; if not LInTransaction then FConnection.Commit; except if not LInTransaction then FConnection.Rollback; raise; end; finally if not LIsConnected then FConnection.Disconnect; FObjectState.Clear; end; end; procedure TObjectSetAdapter<M>.CascadeActionsExecute(const AObject: TObject; const ACascadeAction: TCascadeAction); var LAssociation: TAssociationMapping; LAssociations: TAssociationMappingList; begin LAssociations := TMappingExplorer.GetInstance.GetMappingAssociation(AObject.ClassType); if LAssociations <> nil then begin for LAssociation in LAssociations do begin if ACascadeAction in LAssociation.CascadeActions then begin if LAssociation.Multiplicity in [OneToOne, ManyToOne] then OneToOneCascadeActionsExecute(AObject, LAssociation, ACascadeAction) else if LAssociation.Multiplicity in [OneToMany, ManyToMany] then OneToManyCascadeActionsExecute(AObject, LAssociation, ACascadeAction); end; end; end; end; procedure TObjectSetAdapter<M>.OneToManyCascadeActionsExecute(const AObject: TObject; const AAssociation: TAssociationMapping; const ACascadeAction: TCascadeAction); var LValue: TValue; LObjectList: TObjectList<TObject>; LObject: TObject; LObjectKey: TObject; LFor: Integer; LKey: string; begin LValue := AAssociation.PropertyRtti.GetNullableValue(AObject); if LValue.IsObject then begin LObjectList := TObjectList<TObject>(LValue.AsObject); for LFor := 0 to LObjectList.Count -1 do begin LObject := LObjectList.Items[LFor]; if ACascadeAction = CascadeInsert then // Insert FSession.Insert(LObject) else if ACascadeAction = CascadeDelete then // Delete FSession.Delete(LObject) else if ACascadeAction = CascadeUpdate then // Update begin LKey := GenerateKey(LObject); if FObjectState.ContainsKey(LKey) then begin LObjectKey := FObjectState.Items[LKey]; FSession.ModifyFieldsCompare(LKey, LObjectKey, LObject); UpdateInternal(LObject); FObjectState.Remove(LKey); end else FSession.Insert(LObject); end; end; end; end; procedure TObjectSetAdapter<M>.OneToOneCascadeActionsExecute(const AObject: TObject; const AAssociation: TAssociationMapping; const ACascadeAction: TCascadeAction); var LValue: TValue; LObject: TObject; LObjectKey: TObject; LKey: string; begin LValue := AAssociation.PropertyRtti.GetNullableValue(AObject); if LValue.IsObject then begin LObject := LValue.AsObject; if ACascadeAction = CascadeInsert then // Insert FSession.Insert(LObject) else if ACascadeAction = CascadeDelete then // Delete FSession.Delete(LObject) else if ACascadeAction = CascadeUpdate then // Update begin LKey := GenerateKey(LObject); if FObjectState.ContainsKey(LKey) then begin LObjectKey := FObjectState.Items[LKey]; FSession.ModifyFieldsCompare(LKey, LObjectKey, LObject); UpdateInternal(LObject); FObjectState.Remove(LKey); end else FSession.Insert(LObject); end; end; end; procedure TObjectSetAdapter<M>.AddObjectState(const ASourceObject: TObject); const cPropertyTypes = [tkUnknown, tkInterface, tkClassRef, tkPointer, tkProcedure]; var LRttiType: TRttiType; LProperty: TRttiProperty; LObjectList: TObjectList<TObject>; LStateObject: TObject; LObjectItem: TObject; LKey: string; begin if ASourceObject.GetType(LRttiType) then begin /// <summary> /// Cria um novo objeto para ser guardado na lista com o estado atual do ASourceObject. /// </summary> LStateObject := ASourceObject.ClassType.Create; /// <summary> /// Gera uma chave de identificação unica para cada item da lista /// </summary> LKey := GenerateKey(ASourceObject); /// <summary> /// Guarda o novo objeto na lista, identificado pela chave /// </summary> FObjectState.Add(LKey, LStateObject); try for LProperty in LRttiType.GetProperties do begin if not LProperty.IsWritable then Continue; if LProperty.IsNotCascade then Continue; /// <summary> /// Validação para entrar no IF somente propriedades que o tipo não esteja na lista /// </summary> if not (LProperty.PropertyType.TypeKind in cPropertyTypes) then begin if LProperty.PropertyType.TypeKind = tkClass then begin if LProperty.IsList then begin LObjectList := TObjectList<TObject>(LProperty.GetValue(ASourceObject).AsObject); for LObjectItem in LObjectList do begin if LObjectItem <> nil then AddObjectState(LObjectItem); end; end else AddObjectState(LProperty.GetValue(ASourceObject).AsObject); end else LProperty.SetValue(LStateObject, LProperty.GetValue(ASourceObject)); end; end; except raise; end; end; end; function TObjectSetAdapter<M>.GenerateKey(const AObject: TObject): string; var LColumn: TColumnMapping; LKey: string; begin LKey := AObject.ClassName; for LColumn in AObject.GetPrimaryKey do LKey := LKey + '-' + VarToStr(LColumn.PropertyRtti.GetValue(TObject(AObject)).AsVariant); Result := LKey; end; procedure TObjectSetAdapter<M>.UpdateInternal(const AObject: TObject); var LColumn: TColumnMapping; LKey: string; begin LKey := AObject.ClassName; for LColumn in AObject.GetPrimaryKey do LKey := LKey + '-' + VarToStr(LColumn.PropertyRtti.GetValue(TObject(AObject)).AsVariant); /// if FSession.ModifiedFields.ContainsKey(LKey) then if FSession.ModifiedFields.Items[LKey].Count > 0 then FSession.Update(AObject, LKey); end; end.
program tp1_3; uses Crt; type str20 = string[20]; str8 = string[8]; empleado = record nombre: str20; apellido: str20; edad: integer; dni: longint; n_emp: integer; end; archivo = file of empleado; var emp : empleado; opc: integer; function menu():integer; var opc: integer; begin writeln('Elige una opción: '); writeln('=================='); writeln('1. Crear archivo e ingresar información'); writeln('2. Abrir archivo'); writeln('0. Salir'); readln(opc); menu:= opc; end; function submenu():integer; var opc: integer; begin writeln('Abrir archivo: '); writeln('=================='); writeln('1. Listar en pantalla los datos de empleados que tengan un nombre o apellido determinado.'); writeln('2. Listar en pantalla los empleados de a uno por línea'); writeln('3. Listar en pantalla empleados mayores de 70 años'); writeln('0. Volver'); readln(opc); submenu:= opc; end; function crearEmpleados(archivo: str20):boolean; var empleados: archivo; emp: empleado; cont: integer; begin cont:=1; assign(empleados, 'data/'+ archivo+'.txt'); rewrite(empleados); writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); while (emp.apellido <> 'fin') do begin writeln('Ingrese el nombre del empleado #', cont); readln(emp.nombre); writeln('Ingrese la edad del empleado #', cont); readln(emp.edad); writeln('Ingrese el dni del empleado #', cont); readln(emp.dni); writeln('Ingrese el N° de empleado del empleado #', cont); readln(emp.n_emp); write(empleados, emp); cont:= cont+1; writeln('Ingrese el apellido del empleado #', cont); readln(emp.apellido); writeln(); end; close(empleados); ClrScr; crearEmpleados:=true; end; function imprimirEmpleado(emp: empleado): boolean; begin writeln('Empleado #', emp.n_emp, ': '); writeln('================='); writeln('Apellido: '+emp.apellido); writeln('Nombre: '+emp.nombre); writeln('Edad: ',emp.edad); writeln('DNI: ',emp.dni); writeln(); imprimirEmpleado:= true; end; function listarEmpleados(archivo: str20; tipo: str8):boolean; var nombre: str20; empleados: archivo; emp: empleado; cont: integer; begin assign(empleados, 'data/'+ archivo+'.txt'); reset(empleados); cont:=0; case tipo of 'filter': begin writeln('Ingrese el nombre o apellido a filtrar: '); readln(nombre); while (not eof(empleados)) do begin Read(empleados, emp); if((emp.apellido = nombre) or (emp.nombre = nombre)) then begin imprimirEmpleado(emp); cont:=cont+1; end; end; if (cont = 0) then begin writeln('No hay empleados con nombre o apellido igual a '+nombre); writeln(); end; end; 'full': begin if (eof(empleados)) then begin writeln('No hay empleados en la BD.'); end; while (not eof(empleados)) do begin Read(empleados, emp); imprimirEmpleado(emp); end; end; 'old': begin while (not eof(empleados)) do begin Read(empleados, emp); if (emp.edad >= 70) then begin imprimirEmpleado(emp); cont:= cont + 1; end; end; if (cont = 0) then begin writeln('No hay empleados mayores de 70 años.'); writeln(); end; end; end; listarEmpleados:=true; end; var archivo_nombre: str20; fin: boolean; opcion, subopc: integer; begin fin:=false; writeln('Ingrese el nombre del archivo a trabajar: '); readln(archivo_nombre); repeat opcion:= menu(); case opcion of 1: begin ClrScr; crearEmpleados(archivo_nombre); end; 2: begin ClrScr; subopc:= submenu(); case subopc of 1: listarEmpleados(archivo_nombre, 'filter'); 2: listarEmpleados(archivo_nombre, 'full'); 3: listarEmpleados(archivo_nombre, 'old'); end; end; 0: fin:= true; end; until (fin); end.
unit MediaDibImage; interface uses Windows, Classes, MediaCommon; const CLSID_CPCSText: TGUID = '{c3297339-6fc4-4b45-81cc-578b39bfac45}'; IID_IPCText: TGUID = '{E8E0B4CB-9E9A-46f6-AA7D-FA547A3EA1F4}'; const EFFECT_NAME_BUF_LEN = 64; TEXT_FONT_NAME_LEN = 128; TEXT_BUF_MAX_LEN = 1024; type PARTTEXTINFO = ^TARTTEXTINFO; TARTTEXTINFO = record hInst: THandle; szArtID: array[0..64] of PWideChar; uBmpID: UINT; dwReserve: DWORD; end; PTEXTTRANSFORM = ^TTEXTTRANSFORM; TTEXTTRANSFORM = record ptLeftTop: TPoint; ptLeftBottom: TPoint; ptRightTop: TPoint; ptRightBottom: TPoint; end; // 文本数据结构定义 PTRANSFORM_POINTS = ^TRANSFORM_POINTS; TRANSFORM_POINTS = record ptLeftTop: TPOINT; // 左上角坐标 ptRightTop: TPOINT; // 右上角坐标 ptRightBottom: TPOINT; // 右下角坐标 ptLeftBottom: TPOINT; // 左下角坐标 end; // 艺术字参数结构定义 PARTTEXTPARAM = ^TARTTEXTPARAM; TARTTEXTPARAM = record strArtID: array[0..EFFECT_NAME_BUF_LEN - 1] of PWideChar; // 艺术字类型ID nParam1: Integer; nParam2: Integer; nParam3: Integer; nParam4: Integer; nParam5: Integer; dParam6: Double; dParam7: Double; // 1-7号参数意义根据具体的艺术字类型定义 end; IDibImage = interface(IUnknown) ['{2E1ADF80-6F97-47f5-A3AA-9EB80EE12D3F}'] function GetWidth(): Integer; stdcall; function GetHeight(): Integer; stdcall; function GetBitCount(): Integer; stdcall; function GetImageSize(): Integer; stdcall; function GetPitch(): Integer; stdcall; function GetBitmapInfo(): PBITMAPINFO; stdcall; function GetBits(): PBYTE; stdcall; function GetHeaderSize(): Integer; stdcall; end; HDIBIMAGE = IDibImage; TDibImage = class private FHandle: HDIBIMAGE; FOwnedHandle: Boolean; procedure SetBitCount(Value : Integer); function GetBitCount() : Integer; function GetWidth() : Integer; function GetHeight() : Integer; function GetBitmapInfo() : PBITMAPINFO; function GetPitch() : Integer; function GetBits() : PBYTE; procedure SetHeight(Value: Integer); procedure SetWidth(Value: Integer); function GetBitmapInfoSize: Integer; function GetBitsSize: Integer; function GetEmpty: Boolean; public constructor Create(); overload; constructor Create(width : Integer; height : Integer; nBitCount : Integer); overload; constructor Create(hImage: HDIBIMAGE; AOwned: Boolean=True); overload; constructor Create(lpInfo: PBitmapInfoHeader; lpBits: PBYTE); overload; destructor Destroy; override; class function FromStream(AStream: TStream; ASize: Integer): TDibImage; class function FromFile(const AFileName: UnicodeString): TDibImage; class function FromFile32B(const AFileName: UnicodeString): TDibImage; class function FromResource(nID : UINT; hResModule : HMODULE = 0): TDibImage; function Clone: TDibImage; function GetHBitmap() : HBITMAP; function GetThumbnailImage(width : Integer; height : Integer) : HDIBIMAGE; function LoadFromStream(AStream: TStream; ASize: Integer): BOOL; function SaveToStream(AStream: TStream): BOOL; function LoadImage(pFileName : PWideChar) : BOOL; overload; function LoadImage(const AFileName : UnicodeString) : BOOL; overload; function LoadImageFromResource(nID : UINT; hResModule : HMODULE = 0) : BOOL; function LoadImage32B(pFileName : PWideChar) : BOOL; overload; function LoadImage32B(const AFileName : UnicodeString) : BOOL; overload; function Save(pFileName : PWideChar) : BOOL; overload; function Save(const AFileName : UnicodeString) : BOOL; overload; function SaveEx(const pFileName : PWideChar; const pClsName : PWideChar) : BOOL; overload; function SaveEx(const AFileName, AClsName : UnicodeString) : BOOL; overload; function SetContent(width : Integer; height : Integer; nBitCount : Integer) : BOOL; function ConvertFormat(nBitCount: Integer): BOOL; function BltDraw(hDC : HDC; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0) : BOOL; function StretchDraw(hDC : HDC; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0; cxSrc: Integer = 0; cySrc: Integer = 0) : BOOL; function AlphaBlend(hBackImage : HDIBIMAGE; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0; nOpacity : Integer = 100) : BOOL; function AlphaBlendEx(hBackImage : HDIBIMAGE; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0; nOpacity : Integer = 100; nOpacityBk : Integer = 100) : BOOL; function ImageResize(hImgDst : HDIBIMAGE; iin : IMAGE_INTERPOLATION = IIN_BI_LINER) : BOOL; function ImageResizeEx(hImgDst : HDIBIMAGE; xDst : Integer; yDst : Integer; cxDst : Integer; cyDst : Integer; xSrc : Integer; ySrc : Integer; cxSrc : Integer; cySrc : Integer; iin : IMAGE_INTERPOLATION = IIN_BI_LINER) : BOOL; function Rotate(hImgDst : HDIBIMAGE; iRotateAngle : Integer) : BOOL; function RotateSmooth(hImgDst : HDIBIMAGE; iRotateAngle : Integer) : BOOL; function FillColor32(argbColor : DWORD) : BOOL; function BltImage(hImgDest : HDIBIMAGE; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0) : BOOL; function BltMask(hImageMask : HDIBIMAGE; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0) : BOOL; function BltMaskEx(hImageMask : HDIBIMAGE; x : Integer; y : Integer; cx : Integer = -1; cy : Integer = -1; xSrc : Integer = 0; ySrc : Integer = 0) : BOOL; function FillColor32Ex(argbColor: DWORD; x, y: Integer; cx: Integer = -1; cy: Integer = -1) : BOOL; function FillPatchColor32(cx, cy: Integer; argbColor, argbColor2: COLORREF) : BOOL; function FillPatchColor32Ex(cx, cy: Integer; argbColor, argbColor2: COLORREF; x_off, y_off: Integer) : BOOL; function ImageAlphaResize(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION = IIN_BI_LINER) : BOOL; function ImageAlphaResizeEx(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION = IIN_BI_LINER) : BOOL; function ImageStretchMask(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer) : BOOL; function ImageStretchMaskEx(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer) : BOOL; function Transform(hImage: HDIBIMAGE; pTrPoints: PTRANSFORM_POINTS; xSrc: Integer = 0; ySrc: Integer = 0; cxSrc: Integer = -1; cySrc: Integer = -1; iin: IMAGE_INTERPOLATION = IIN_BI_LINER) : BOOL; function MaskImage(pRect: PRECT; dwArgbColor: COLORREF = $80000000) : BOOL; function MergeImage(hBackImage: HDIBIMAGE; x, y: Integer; cx: Integer = -1; cy: Integer = -1; xSrc: Integer = 0; ySrc: Integer = 0; nOpacity: Integer = 100; nOpacityBk: Integer = 100) : BOOL; property Handle: HDIBIMAGE read FHandle; property Width: Integer read GetWidth write SetWidth; property Height: Integer read GetHeight write SetHeight; property BitCount: Integer read GetBitCount write SetBitCount; property Pitch: Integer read GetPitch; property BitmapInfo: PBITMAPINFO read GetBitmapInfo; property Bits: PByte read GetBits; property BitmapInfoSize: Integer read GetBitmapInfoSize; property BitsSize: Integer read GetBitsSize; property Empty: Boolean read GetEmpty; end; implementation { TDibImage } function TDibImage.AlphaBlend(hBackImage: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc, nOpacity: Integer): BOOL; begin end; function TDibImage.AlphaBlendEx(hBackImage: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc, nOpacity, nOpacityBk: Integer): BOOL; begin end; function TDibImage.BltDraw(hDC: HDC; x, y, cx, cy, xSrc, ySrc: Integer): BOOL; begin end; function TDibImage.BltImage(hImgDest: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc: Integer): BOOL; begin end; function TDibImage.BltMask(hImageMask: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc: Integer): BOOL; begin end; function TDibImage.BltMaskEx(hImageMask: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc: Integer): BOOL; begin end; function TDibImage.Clone: TDibImage; begin end; function TDibImage.ConvertFormat(nBitCount: Integer): BOOL; begin end; constructor TDibImage.Create; begin end; constructor TDibImage.Create(lpInfo: PBitmapInfoHeader; lpBits: PBYTE); begin end; constructor TDibImage.Create(hImage: HDIBIMAGE; AOwned: Boolean); begin end; constructor TDibImage.Create(width, height, nBitCount: Integer); begin end; destructor TDibImage.Destroy; begin inherited; end; function TDibImage.FillColor32(argbColor: DWORD): BOOL; begin end; function TDibImage.FillColor32Ex(argbColor: DWORD; x, y, cx, cy: Integer): BOOL; begin end; function TDibImage.FillPatchColor32(cx, cy: Integer; argbColor, argbColor2: COLORREF): BOOL; begin end; function TDibImage.FillPatchColor32Ex(cx, cy: Integer; argbColor, argbColor2: COLORREF; x_off, y_off: Integer): BOOL; begin end; class function TDibImage.FromFile(const AFileName: UnicodeString): TDibImage; begin end; class function TDibImage.FromFile32B(const AFileName: UnicodeString): TDibImage; begin Result:=TDibImage.Create; Result.LoadImage32B(AFileName); end; class function TDibImage.FromResource(nID: UINT; hResModule: HMODULE): TDibImage; begin end; class function TDibImage.FromStream(AStream: TStream; ASize: Integer): TDibImage; begin end; function TDibImage.GetBitCount: Integer; begin end; function TDibImage.GetBitmapInfo: PBITMAPINFO; begin Result := nil; if Assigned(FHandle) then Result := FHandle.GetBitmapInfo(); end; function TDibImage.GetBitmapInfoSize: Integer; var lpbi: PBITMAPINFO; nColor: Integer; begin Result := 0; lpbi := nil; if Assigned(FHandle) then lpbi := FHandle.GetBitmapInfo(); if Assigned(lpbi) then begin Result := SizeOf(TBitmapInfoHeader); if lpbi.bmiHeader.biBitCount <= 8 then begin nColor := lpbi.bmiHeader.biClrUsed; if nColor = 0 then nColor := 1 shl lpbi.bmiHeader.biBitCount; Result := Result + SizeOf(RGBQUAD) * nColor; end; end; end; function TDibImage.GetBits: PBYTE; begin Result := nil; if Assigned(FHandle) then Result := FHandle.GetBits(); end; function TDibImage.GetBitsSize: Integer; begin end; function TDibImage.GetEmpty: Boolean; begin end; function TDibImage.GetHBitmap: HBITMAP; begin end; function TDibImage.GetHeight: Integer; begin end; function TDibImage.GetPitch: Integer; begin end; function TDibImage.GetThumbnailImage(width, height: Integer): HDIBIMAGE; begin end; function TDibImage.GetWidth: Integer; begin end; function TDibImage.ImageAlphaResize(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION): BOOL; begin end; function TDibImage.ImageAlphaResizeEx(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION): BOOL; begin end; function TDibImage.ImageResize(hImgDst: HDIBIMAGE; iin: IMAGE_INTERPOLATION): BOOL; begin end; function TDibImage.ImageResizeEx(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION): BOOL; begin end; function TDibImage.ImageStretchMask(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer): BOOL; begin end; function TDibImage.ImageStretchMaskEx(hImgDst: HDIBIMAGE; xDst, yDst, cxDst, cyDst, xSrc, ySrc, cxSrc, cySrc: Integer): BOOL; begin end; function TDibImage.LoadFromStream(AStream: TStream; ASize: Integer): BOOL; begin end; function TDibImage.LoadImage(pFileName: PWideChar): BOOL; begin end; function TDibImage.LoadImage(const AFileName: UnicodeString): BOOL; begin end; function TDibImage.LoadImage32B(pFileName: PWideChar): BOOL; begin end; function TDibImage.LoadImage32B(const AFileName: UnicodeString): BOOL; begin end; function TDibImage.LoadImageFromResource(nID: UINT; hResModule: HMODULE): BOOL; begin end; function TDibImage.MaskImage(pRect: PRECT; dwArgbColor: COLORREF): BOOL; begin end; function TDibImage.MergeImage(hBackImage: HDIBIMAGE; x, y, cx, cy, xSrc, ySrc, nOpacity, nOpacityBk: Integer): BOOL; begin end; function TDibImage.Rotate(hImgDst: HDIBIMAGE; iRotateAngle: Integer): BOOL; begin end; function TDibImage.RotateSmooth(hImgDst: HDIBIMAGE; iRotateAngle: Integer): BOOL; begin end; function TDibImage.Save(pFileName: PWideChar): BOOL; begin end; function TDibImage.Save(const AFileName: UnicodeString): BOOL; begin end; function TDibImage.SaveEx(const pFileName, pClsName: PWideChar): BOOL; begin end; function TDibImage.SaveEx(const AFileName, AClsName: UnicodeString): BOOL; begin end; function TDibImage.SaveToStream(AStream: TStream): BOOL; begin end; procedure TDibImage.SetBitCount(Value: Integer); begin end; function TDibImage.SetContent(width, height, nBitCount: Integer): BOOL; begin end; procedure TDibImage.SetHeight(Value: Integer); begin end; procedure TDibImage.SetWidth(Value: Integer); begin end; function TDibImage.StretchDraw(hDC: HDC; x, y, cx, cy, xSrc, ySrc, cxSrc, cySrc: Integer): BOOL; begin end; function TDibImage.Transform(hImage: HDIBIMAGE; pTrPoints: PTRANSFORM_POINTS; xSrc, ySrc, cxSrc, cySrc: Integer; iin: IMAGE_INTERPOLATION): BOOL; begin end; end.
// ---------------------------------------------------------------------------- // Unit : PxDTDFile.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2006-06-16 // Version : 1.0 // Description : Set of classes to read definitions from DTD file // Changes log : 2006-06-16 - initial version // ToDo : Testing, comments in code. // ---------------------------------------------------------------------------- unit PxDTDFile; {$I PxDefines.inc} interface uses Classes, SysUtils, RegExpr; const RX_DTD_ELEMENT = '<!ELEMENT\s*(\w+)\s*\((.*?)\)>'; RX_DTD_ATTRIBUTE = '<!ATTLIST\s*(\w+)\s*(\w+)\s*(([\w#]+)|(\([\w| ]+\)))\s*(.+?)>'; type TDTDElementList = class; TDTDAttributeType = (atCDATA, atValueSet, atID, atIDREF, atIDREFS, atNMTOKEN, atNMTOKENS, atENTITY, atENTITIES, atNOTATION); TDTDAttribute = class (TObject) private FName: String; FElementName: String; FAttributeType: TDTDAttributeType; FAttributeValues: TStrings; FDefaultValue: String; FImplied: Boolean; FRequired: Boolean; FFixed: Boolean; FFixedValue: String; public constructor Create; destructor Destroy; override; property Name: String read FName; property ElementName: String read FElementName; property AttributeType: TDTDAttributeType read FAttributeType; property AttributeValues: TStrings read FAttributeValues; property DefaultValue: String read FDefaultValue; property Implied: Boolean read FImplied; property Required: Boolean read FRequired; property Fixed: Boolean read FFixed; property FixedValue: String read FFixedValue; end; TDTDAttributeList = class (TList) private function GetItem(Index: Integer): TDTDAttribute; public property Items[Index: Integer]: TDTDAttribute read GetItem; default; end; TDTDElement = class (TObject) private FName: String; FDefinition: String; FElements: TDTDElementList; FAttributes: TDTDAttributeList; FOptional: Boolean; public constructor Create; destructor Destroy; override; property Name: String read FName; property Definition: String read FDefinition; property Elements: TDTDElementList read FElements; property Attributes: TDTDAttributeList read FAttributes; property Optional: Boolean read FOptional; end; TDTDElementList = class (TList) private function GetItem(Index: Integer): TDTDElement; public property Items[Index: Integer]: TDTDElement read GetItem; default; end; TDTDFile = class (TObject) private FRoot: TDTDElement; FElements: TDTDElementList; FAttributes: TDTDAttributeList; protected procedure ClearElements; procedure ClearAttributes; procedure LoadElements(Source: String); procedure LoadAttributes(Source: String); procedure ProcessDTDElement(Name, Definition: String); procedure ProcessDTDAttribute(ElementName, Name, Type_, Default: String); procedure ResolveRelations(Root: TDTDElement; Elements: TDTDElementList; Attributes: TDTDAttributeList); public constructor Create; destructor Destroy; override; procedure LoadFromFile(FileName: String); property Root: TDTDElement read FRoot; property Elements: TDTDElementList read FElements; property Attributes: TDTDAttributeList read FAttributes; end; function DTDAttributeTypeToStr(Value: TDTDAttributeType): String; {$IFDEF DEBUG} function DTDAttributeToStr(Attribute: TDTDAttribute): String; {$ENDIF} implementation { TDTDAttribute } { Private declarations } { Public declarations } constructor TDTDAttribute.Create; begin inherited Create; FAttributeValues := TStringList.Create; end; destructor TDTDAttribute.Destroy; begin FreeAndNil(FAttributeValues); inherited Destroy; end; { TDTDAttributeList } { Private declarations } function TDTDAttributeList.GetItem(Index: Integer): TDTDAttribute; begin Result := TObject(Get(Index)) as TDTDAttribute; end; { TDTDElement } { Private declarations } { Public declarations } constructor TDTDElement.Create; begin inherited Create; FElements := TDTDElementList.Create; FAttributes := TDTDAttributeList.Create; end; destructor TDTDElement.Destroy; begin FreeAndNil(FAttributes); FreeAndNil(FElements); inherited Destroy; end; { TDTDElementList } { Private declarations } function TDTDElementList.GetItem(Index: Integer): TDTDElement; begin Result := TObject(Get(Index)) as TDTDElement; end; { TDTDFile } { Private declarations } { Protected declarations } procedure TDTDFile.ClearElements; var I: Integer; begin for I := 0 to Elements.Count - 1 do Elements[I].Free; Elements.Clear; FRoot := nil; end; procedure TDTDFile.ClearAttributes; var I: Integer; begin for I := 0 to Attributes.Count - 1 do Attributes[I].Free; Attributes.Clear; end; procedure TDTDFile.ProcessDTDElement(Name, Definition: String); var Element: TDTDElement; begin Element := TDTDElement.Create; if Name[Length(Name)] = '?' then begin Element.FOptional := True; Delete(Name, Length(Name), 1); end else Element.FOptional := False; Element.FName := Name; Element.FDefinition := Definition; Elements.Add(Element); if Root = nil then FRoot := Element; end; procedure TDTDFile.ProcessDTDAttribute(ElementName, Name, Type_, Default: String); var Attribute: TDTDAttribute; begin Attribute := TDTDAttribute.Create; Attribute.FName := Name; Attribute.FElementName := ElementName; if Type_ = 'CDATA' then Attribute.FAttributeType := atCDATA else if Type_ = 'ID' then Attribute.FAttributeType := atID else if Type_ = 'IDREF' then Attribute.FAttributeType := atIDREF else if Type_ = 'IDREFS' then Attribute.FAttributeType := atIDREFS else if Type_ = 'NMTOKEN' then Attribute.FAttributeType := atNMTOKEN else if Type_ = 'NMTOKENS' then Attribute.FAttributeType := atNMTOKENS else if Type_ = 'ENTITY' then Attribute.FAttributeType := atENTITY else if Type_ = 'ENTITIES' then Attribute.FAttributeType := atENTITIES else if Type_ = 'NOTATION' then Attribute.FAttributeType := atNOTATION else if (Type_[1] = '(') and (Type_[Length(Type_)] = ')') then begin Delete(Type_, 1, 1); Delete(Type_, Length(Type_), 1); Attribute.FAttributeType := atValueSet; Attribute.FAttributeValues.Delimiter := '|'; Attribute.FAttributeValues.DelimitedText := Type_; end else raise Exception.CreateFmt('Invalid attribute type %s', [Type_]); if Default = '#IMPLIED' then Attribute.FImplied := True else if Default = '#REQUIRED' then Attribute.FRequired := True else if Copy(Default, 1, 6) = '#FIXED' then begin Delete(Default, 1, 6); Default := Trim(Default); if (Default[1] = '"') and (Default[Length(Default)] = '"') then begin Delete(Default, 1, 1); Delete(Default, Length(Default), 1); Attribute.FFixed := True; Attribute.FFixedValue := Default; end else raise Exception.Create('Error: value in double quotes expected'); end else if (Default[1] = '"') and (Default[Length(Default)] = '"') then begin Delete(Default, 1, 1); Delete(Default, Length(Default), 1); Attribute.FDefaultValue := Default; end; Attributes.Add(Attribute); end; procedure TDTDFile.LoadElements(Source: String); var R: TRegExpr; Found: Boolean; begin R := TRegExpr.Create; try R.Expression := RX_DTD_ELEMENT; Found := R.Exec(Source); while Found do begin ProcessDTDElement(R.Match[1], R.Match[2]); Found := R.ExecNext; end; finally R.Free; end; end; procedure TDTDFile.LoadAttributes(Source: String); var R: TRegExpr; Found: Boolean; begin R := TRegExpr.Create; try R.Expression := RX_DTD_ATTRIBUTE; Found := R.Exec(Source); while Found do begin ProcessDTDAttribute(R.Match[1], R.Match[2], R.Match[3], R.Match[6]); Found := R.ExecNext; end; finally R.Free; end; end; procedure TDTDFile.ResolveRelations(Root: TDTDElement; Elements: TDTDElementList; Attributes: TDTDAttributeList); var I, J: Integer; Element: TDTDElement; SubElements: TStrings; begin SubElements := TStringList.Create; try // subelements SubElements.Delimiter := ','; SubElements.DelimitedText := Root.Definition; for I := 0 to SubElements.Count - 1 do begin SubElements[I] := Trim(SubElements[I]); if (SubElements[I] <> '') and (SubElements[I] <> '#PCDATA') then begin Element := nil; for J := 0 to Elements.Count - 1 do if Elements[J].Name = Trim(SubElements[I]) then begin Element := Elements[J]; Break; end; Assert(Element <> nil, 'Error: undefined element ' + SubElements[I]); Root.Elements.Add(Element); end; end; finally SubElements.Free; end; // attributes for I := 0 to Attributes.Count - 1 do if Attributes[I].ElementName = Root.Name then Root.Attributes.Add(Attributes[I]); end; { Public declarations } constructor TDTDFile.Create; begin inherited Create; FElements := TDTDElementList.Create; FAttributes := TDTDAttributeList.Create; end; destructor TDTDFile.Destroy; begin ClearAttributes; ClearElements; FreeAndNil(FAttributes); FreeAndNil(FElements); inherited Destroy; end; procedure TDTDFile.LoadFromFile(FileName: String); var Source: TStrings; I: Integer; begin ClearElements; Source := TStringList.Create; try Source.LoadFromFile(FileName); LoadElements(Source.Text); LoadAttributes(Source.Text); finally Source.Free; end; for I := 0 to Elements.Count - 1 do ResolveRelations(Elements[I], Elements, Attributes); end; { *** } function DTDAttributeTypeToStr(Value: TDTDAttributeType): String; begin case Value of atCDATA: Result := 'CDATA'; atValueSet: Result := 'ValueSet'; atID: Result := 'ID'; atIDREF: Result := 'IDREF'; atIDREFS: Result := 'IDREFS'; atNMTOKEN: Result := 'NMTOKEN'; atNMTOKENS: Result := 'NMTOKENS'; atENTITY: Result := 'ENTITY'; atENTITIES: Result := 'ENTITIES'; atNOTATION: Result := 'NOTATION'; end; end; {$IFDEF DEBUG} function DTDAttributeToStr(Attribute: TDTDAttribute): String; var I: Integer; begin Result := Format('%s::%s ', [Attribute.FElementName, Attribute.FName]); case Attribute.AttributeType of atCDATA: begin Result := Result + 'CDATA'; if Attribute.DefaultValue <> '' then Result := Result + ' DEFAULT "' + Attribute.DefaultValue + '"'; end; atValueSet: begin Result := Result + 'SET ('; for I := 0 to Attribute.AttributeValues.Count - 1 do begin if I > 0 then Result := Result + '|'; Result := Result + Attribute.AttributeValues[I]; end; Result := Result + ')'; end; atID: Result := Result + 'ID'; atIDREF: Result := Result + 'IDREF'; atIDREFS: Result := Result + 'IDREFS'; atNMTOKEN: Result := Result + 'NMTOKEN'; atNMTOKENS: Result := Result + 'NMTOKENS'; atENTITY: Result := Result + 'ENTITY'; atENTITIES: Result := Result + 'ENTITIES'; atNOTATION: Result := Result + 'NOTATION'; end; if Attribute.Implied then Result := Result + ' IMPLIED'; if Attribute.Required then Result := Result + ' REQUIRED'; if Attribute.Fixed then Result := Result + ' FIXED "' + Attribute.FixedValue + '"'; end; {$ENDIF} end.
{******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Objetivos / Metas para Comissão The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author T2Ti @version 2.0 *******************************************************************************} unit UComissaoObjetivo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ComissaoObjetivoVO, ComissaoObjetivoController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, JvBaseEdits, Controller; type TFComissaoObjetivo = class(TFTelaCadastro) EditCodigo: TLabeledEdit; EditPerfil: TLabeledEdit; EditNome: TLabeledEdit; BevelEdits: TBevel; MemoDescricao: TLabeledMemo; EditIdPerfil: TLabeledCalcEdit; EditIdProduto: TLabeledCalcEdit; EditProduto: TLabeledEdit; ComboboxFormaPagamento: TLabeledComboBox; EditTaxaPagamento: TLabeledCalcEdit; EditValorPagamento: TLabeledCalcEdit; EditValorMeta: TLabeledCalcEdit; EditQuantidade: TLabeledCalcEdit; procedure FormCreate(Sender: TObject); procedure EditIdPerfilKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdProdutoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FComissaoObjetivo: TFComissaoObjetivo; implementation uses ULookup, Biblioteca, ComissaoPerfilVO, ComissaoPerfilController, ProdutoVO, ProdutoController; {$R *.dfm} {$REGION 'Infra'} procedure TFComissaoObjetivo.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TComissaoObjetivoVO; ObjetoController := TComissaoObjetivoController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFComissaoObjetivo.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditCodigo.SetFocus; end; end; function TFComissaoObjetivo.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditCodigo.SetFocus; end; end; function TFComissaoObjetivo.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('ComissaoObjetivoController.TComissaoObjetivoController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('ComissaoObjetivoController.TComissaoObjetivoController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFComissaoObjetivo.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TComissaoObjetivoVO.Create; TComissaoObjetivoVO(ObjetoVO).Codigo := EditCodigo.Text; TComissaoObjetivoVO(ObjetoVO).IdComissaoPerfil := EditIdPerfil.AsInteger; TComissaoObjetivoVO(ObjetoVO).IdProduto := EditIdProduto.AsInteger; TComissaoObjetivoVO(ObjetoVO).Nome := EditNome.Text; TComissaoObjetivoVO(ObjetoVO).Descricao := MemoDescricao.Text; TComissaoObjetivoVO(ObjetoVO).FormaPagamento := IntToStr(ComboboxFormaPagamento.ItemIndex); TComissaoObjetivoVO(ObjetoVO).TaxaPagamento := EditTaxaPagamento.Value; TComissaoObjetivoVO(ObjetoVO).ValorPagamento := EditValorPagamento.Value; TComissaoObjetivoVO(ObjetoVO).ValorMeta := EditValorMeta.Value; TComissaoObjetivoVO(ObjetoVO).Quantidade := EditQuantidade.Value; if StatusTela = stInserindo then begin TController.ExecutarMetodo('ComissaoObjetivoController.TComissaoObjetivoController', 'Insere', [TComissaoObjetivoVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TComissaoObjetivoVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('ComissaoObjetivoController.TComissaoObjetivoController', 'Altera', [TComissaoObjetivoVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controles de Grid'} procedure TFComissaoObjetivo.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TComissaoObjetivoVO(TController.BuscarObjeto('ComissaoObjetivoController.TComissaoObjetivoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditCodigo.Text := TComissaoObjetivoVO(ObjetoVO).Codigo; EditIdPerfil.AsInteger := TComissaoObjetivoVO(ObjetoVO).IdComissaoPerfil; EditIdProduto.AsInteger := TComissaoObjetivoVO(ObjetoVO).IdProduto; EditNome.Text := TComissaoObjetivoVO(ObjetoVO).Nome; MemoDescricao.Text := TComissaoObjetivoVO(ObjetoVO).Descricao; ComboboxFormaPagamento.ItemIndex := StrToInt(TComissaoObjetivoVO(ObjetoVO).FormaPagamento); EditTaxaPagamento.Value := TComissaoObjetivoVO(ObjetoVO).TaxaPagamento; EditValorPagamento.Value := TComissaoObjetivoVO(ObjetoVO).ValorPagamento; EditValorMeta.Value := TComissaoObjetivoVO(ObjetoVO).ValorMeta; EditQuantidade.Value := TComissaoObjetivoVO(ObjetoVO).Quantidade; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFComissaoObjetivo.EditIdPerfilKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdPerfil.Value <> 0 then Filtro := 'ID = ' + EditIdPerfil.Text else Filtro := 'ID=0'; try EditIdPerfil.Clear; EditPerfil.Clear; if not PopulaCamposTransientes(Filtro, TComissaoPerfilVO, TComissaoPerfilController) then PopulaCamposTransientesLookup(TComissaoPerfilVO, TComissaoPerfilController); if CDSTransiente.RecordCount > 0 then begin EditIdPerfil.Text := CDSTransiente.FieldByName('ID').AsString; EditPerfil.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdProduto.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFComissaoObjetivo.EditIdProdutoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdProduto.Value <> 0 then Filtro := 'ID = ' + EditIdProduto.Text else Filtro := 'ID=0'; try EditIdProduto.Clear; EditProduto.Clear; if not PopulaCamposTransientes(Filtro, TProdutoVO, TProdutoController) then PopulaCamposTransientesLookup(TProdutoVO, TProdutoController); if CDSTransiente.RecordCount > 0 then begin EditIdProduto.Text := CDSTransiente.FieldByName('ID').AsString; EditProduto.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditNome.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
unit formReplacement; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, LasFile; type TReplacementFormType = (rftSimple, rftCurves); TformReplac = class(TForm) edtIn: TEdit; edtOut: TEdit; btnOk: TButton; cmbxCurves: TComboBox; procedure cmbxCurvesChange(Sender: TObject); procedure edtOutChange(Sender: TObject); private { Private declarations } FinputString : string; FOutputString: string; FFormType: TReplacementFormType; FCurve : TCurve; procedure SetinputString(const Value: string); procedure SetOutputString(const Value: string); procedure SetFormtype(const Value: TReplacementFormType); procedure SetCurve (const Value: TCurve); function GetCurve: TCurve; public { Public declarations } property FormType: TReplacementFormType read FFormType write SetFormtype; property InputString: string read FinputString write SetinputString; property OutputString: string read FOutputString write SetOutputString; property Curve : TCurve read GetCurve; constructor Create(AOwner: TComponent); override; end; var formReplac: TformReplac; implementation uses Facade, StringUtils; {$R *.dfm} { TformReplac } constructor TformReplac.Create(AOwner: TComponent); begin inherited; FormType := rftSimple; end; procedure TformReplac.SetFormtype(const Value: TReplacementFormType); begin FFormType := Value; cmbxCurves.Visible := FormType = rftCurves; end; procedure TformReplac.SetinputString(const Value: string); var i: integer; tempStr, up1, up2 : string; begin FInputString := Value; edtIn.Text := FinputString; OutputString := FinputString; tempStr:= FinputString; for i:=1 to Length(tempStr) do if tempStr[i]='.' then begin Delete (tempStr, i, Length(tempStr)-i+1); Break; end; cmbxCurves.Clear; for i := 0 to TMainFacade.GetInstance.AllCurves.Count - 1 do begin up1 := AnsiUpperCase(TMainFacade.GetInstance.AllCurves.Items[i].ShortName); up2 := AnsiUpperCase(tempStr); if (Pos(up2, up1) <> 0) then begin cmbxCurves.AddItem(TMainFacade.GetInstance.AllCurves.Items[i].List(), TMainFacade.GetInstance.AllCurves.Items[i]); end; end; if cmbxCurves.Items.Count > 0 then cmbxCurves.ItemIndex := 0; end; procedure TformReplac.SetOutputString(const Value: string); begin FOutputString := Value; edtOut.Text := FOutputString; end; procedure TformReplac.SetCurve(const Value: TCurve); begin FCurve:=Value; end; function TformReplac.GetCurve: TCurve; begin if cmbxCurves.ItemIndex > -1 then begin Result := TCurve(cmbxCurves.Items.Objects[cmbxCurves.ItemIndex]); end else Result := nil; end; procedure TformReplac.cmbxCurvesChange(Sender: TObject); begin SetOutputString(GetCurve.ShortName); end; procedure TformReplac.edtOutChange(Sender: TObject); begin SetOutputString(edtOut.Text); end; end.
unit uJxdGpGifShow; interface uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, GDIPAPI, GDIPOBJ, uJxdGpStyle, uJxdGpBasic {$IF Defined(ResManage)} ,uJxdGpResManage {$ELSEIF Defined(BuildResManage)} ,uJxdGpResManage {$IFEND}; type PGifInfo = ^TGifInfo; TGifInfo = record FPosIndex: Integer; FPauseTime: Cardinal; end; TxdGifShow = class(TxdGraphicsBasic) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected //子类实现 procedure DrawGraphics(const AGh: TGPGraphics); override; procedure DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint); override; procedure SetAutoSize(Value: Boolean); override; private FAutToFreeGif: Boolean; FShowTime: TTimer; FCurShowIndex: Integer; FImgWidth, FImgHeight: Integer; FGifInfoList: TList; procedure ClearList; procedure ReBuildGifImageInfo; procedure DoTimeToChangedGif(Sender: TObject); private FGifImage: TGPBitmap; FGifImgFileName: string; FAutoShowGif: Boolean; procedure SetGifImage(const Value: TGPBitmap); procedure SetGifImgFileName(const Value: string); function GetGifImage: TGPBitmap; inline; procedure SetAutoShowGif(const Value: Boolean); published property AutoSize; property AutoShowGif: Boolean read FAutoShowGif write SetAutoShowGif; property GifImage: TGPBitmap read GetGifImage write SetGifImage; property GifImageFileName: string read FGifImgFileName write SetGifImgFileName; end; implementation { TxdGifShow } procedure TxdGifShow.ClearList; var i: Integer; begin for i := 0 to FGifInfoList.Count - 1 do Dispose( FGifInfoList[i] ); FGifInfoList.Clear; end; constructor TxdGifShow.Create(AOwner: TComponent); begin inherited; FGifInfoList := TList.Create; FCurShowIndex := -1; FShowTime := nil; FGifImage := nil; FAutToFreeGif := False; FImgWidth := 0; FImgHeight := 0; AutoSize := True; FAutoShowGif := True; end; destructor TxdGifShow.Destroy; begin ClearList; FGifInfoList.Free; FreeAndNil( FShowTime ); if FAutToFreeGif then FreeAndNil( FGifImage ); inherited; end; procedure TxdGifShow.DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint); begin //不调用父类方法 end; procedure TxdGifShow.ReBuildGifImageInfo; var i, nCount: Cardinal; pGuids: PGUID; pItem: PPropertyItem; nSize: Cardinal; p: PGifInfo; pPauseTime: PInteger; begin ClearList; if not Assigned(GifImage) then Exit; FImgWidth := GifImage.GetWidth; FImgHeight := GifImage.GetHeight; FCurShowIndex := -1; FreeAndNil( FShowTime ); if AutoSize then begin Width := FImgWidth; Height := FImgHeight; end; nCount := GifImage.GetFrameDimensionsCount; if nCount > 0 then begin GetMem( pGuids, SizeOf(TGUID) * nCount ); try GifImage.GetFrameDimensionsList( pGuids, nCount ); nCount := GifImage.GetFrameCount( pGuids^ ); finally FreeMem( pGuids ); end; nSize := GifImage.GetPropertyItemSize( PropertyTagFrameDelay ); if nSize = 0 then Exit; GetMem( pItem, nSize ); try GifImage.GetPropertyItem( PropertyTagFrameDelay, nSize, pItem ); pPauseTime := pItem^.value; for i := 0 to nCount - 1 do begin New( p ); p^.FPosIndex := i; p^.FPauseTime := pPauseTime^ * 10; FGifInfoList.Add( p ); Inc( pPauseTime ); end; finally FreeMem( pItem ); end; end; if (FGifInfoList.Count > 1) and FAutoShowGif then begin FShowTime := TTimer.Create( Self ); FShowTime.OnTimer := DoTimeToChangedGif; FShowTime.Interval := 500; FShowTime.Enabled := True; end; end; procedure TxdGifShow.DoTimeToChangedGif(Sender: TObject); var p: PGifInfo; begin if FGifInfoList.Count = 0 then begin FreeAndNil( FShowTime ); Exit; end; FCurShowIndex := (FCurShowIndex + 1) mod FGifInfoList.Count; p := FGifInfoList[FCurShowIndex]; FShowTime.Interval := p^.FPauseTime; GifImage.SelectActiveFrame( FrameDimensionTime, p^.FPosIndex ); Invalidate; end; procedure TxdGifShow.DrawGraphics(const AGh: TGPGraphics); var dest: TGPRect; begin if not Assigned(GifImage) then Exit; dest := MakeRect( 0, 0, Width, Height ); AGh.DrawImage( GifImage, dest, 0, 0, FImgWidth, FImgHeight, UnitPixel ); end; function TxdGifShow.GetGifImage: TGPBitmap; begin if not Assigned(FGifImage) then begin if FileExists(FGifImgFileName) then begin FGifImage := TGPBitmap.Create( FGifImgFileName ); FAutToFreeGif := True; // ReBuildGifImageInfo; end {$IFDEF ResManage} else begin if Assigned(GResManage) then begin FGifImage := GResManage.GetRes( FGifImgFileName ); if Assigned(FGifImage) then begin FAutToFreeGif := False; ReBuildGifImageInfo; end; end; end; {$ENDIF} ; end; Result := FGifImage; end; procedure TxdGifShow.SetAutoShowGif(const Value: Boolean); begin if FAutoShowGif <> Value then begin FAutoShowGif := Value; if Value then begin if (FGifInfoList.Count > 0) and not Assigned(FShowTime) then begin FShowTime := TTimer.Create( Self ); FShowTime.OnTimer := DoTimeToChangedGif; FShowTime.Interval := 500; FShowTime.Enabled := True; end; end else begin if Assigned(FShowTime) then begin FShowTime.Enabled := False; FreeAndNil( FShowTime ); FCurShowIndex := 0; if FGifInfoList.Count > 0 then begin GifImage.SelectActiveFrame( FrameDimensionTime, FCurShowIndex ); Invalidate; end; end; end; end; end; procedure TxdGifShow.SetAutoSize(Value: Boolean); begin inherited; if AutoSize and (FImgWidth > 0) and (FImgHeight > 0) then begin Width := FImgWidth; Height := FImgHeight; end; end; procedure TxdGifShow.SetGifImage(const Value: TGPBitmap); begin if Assigned(FGifImage) and FAutToFreeGif then FreeAndNil( FGifImage ); FGifImage := Value; FAutToFreeGif := False; ReBuildGifImageInfo; end; procedure TxdGifShow.SetGifImgFileName(const Value: string); begin if Assigned(FGifImage) and FAutToFreeGif then FreeAndNil( FGifImage ); FGifImgFileName := Value; {$IFDEF BuildResManage} if Assigned(GBuildResManage) then GBuildResManage.AddToRes( FGifImgFileName ); {$ENDIF} FAutToFreeGif := True; ReBuildGifImageInfo; Invalidate; end; end.
PROGRAM ReadNumber(INPUT, OUTPUT); VAR N: INTEGER; Stop: BOOLEAN; PROCEDURE ReadDigit(VAR F: TEXT; VAR Digit: INTEGER); VAR Ch: CHAR; BEGIN{ReadDigit} IF NOT EOLN(F) THEN READ(F, Ch); Digit := -1; IF (Ch >= '0') AND (Ch <= '9') THEN BEGIN IF (Ch = '0') THEN Digit := 0; IF (Ch = '1') THEN Digit := 1; IF (Ch = '2') THEN Digit := 2; IF (Ch = '3') THEN Digit := 3; IF (Ch = '4') THEN Digit := 4; IF (Ch = '5') THEN Digit := 5; IF (Ch = '6') THEN Digit := 6; IF (Ch = '7') THEN Digit := 7; IF (Ch = '8') THEN Digit := 8; IF (Ch = '9') THEN Digit := 9; END; END; {ReadDigit} PROCEDURE ReadNumber(VAR F: TEXT; VAR Num: INTEGER); VAR I, Digit: INTEGER; BEGIN{ReadNumber} Num := 0; I := 0; Digit := -1; WHILE Digit = -1 DO ReadDigit(F, Digit); Num := Digit; Stop := FALSE; WHILE (Digit < MAXINT) AND (NOT EOLN) AND (Digit <> -1) AND (NOT Stop) DO BEGIN ReadDigit(F, Digit); IF (Digit <> -1) AND (Num < (MAXINT DIV 10)) THEN BEGIN Num := Num * 10 + Digit; I := I + 1; END ELSE BEGIN IF (Num = (MAXINT DIV 10)) AND (Digit <= (MAXINT MOD 10)) AND (Digit <> -1) THEN Num := Num * 10 + Digit ELSE BEGIN Num := -1; Stop := TRUE; END; END; END; END; {ReadNumber} BEGIN ReadNumber(INPUT, N); WRITELN(N); END.
unit DebugWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TDebugWindowDlg = class(TForm) Memo1: TMemo; Panel1: TPanel; cbActive: TCheckBox; ListBox1: TListBox; procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private-Deklarationen } AnzIndex : array of integer; public { Public-Deklarationen } procedure OnPrintText (const aText: String); procedure Clear; procedure OnPrintLine(const Index : integer; const ToPrint : string); end; var DebugWindowDlg: TDebugWindowDlg; implementation {$R *.DFM} procedure TDebugWindowDlg.OnPrintText (const aText: String); begin if cbActive.Checked then Memo1.Lines.Add (aText); end; procedure TDebugWindowDlg.Clear; begin Memo1.Lines.Clear; end; procedure TDebugWindowDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin Memo1.Lines.Clear; end; procedure TDebugWindowDlg.OnPrintLine(const Index: integer; const ToPrint: string); var idx : integer; begin for idx := 0 to Length (AnzIndex) - 1 do begin if AnzIndex[idx] = Index then begin ListBox1.Items [idx] := Format ('[0x%.4x] <%s>', [index, ToPrint]); exit; // draw, exit; end; end; idx := Length (AnzIndex); SetLength (AnzIndex, idx + 1); AnzIndex[idx] := Index; ListBox1.Items.Add (ToPrint); end; end.
unit Vector4bComparatorTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type TVector4bComparatorTest = class(TByteVectorBaseTestCase) published procedure TestCompare; procedure TestCompareFalse; procedure TestCreateBytes; procedure TestCreatefrom3b; procedure TestOpAdd; procedure TestOpAddByte; procedure TestOpSub; procedure TestOpSubByte; procedure TestOpMul; procedure TestOpMulByte; procedure TestOpDiv; procedure TestOpDivByte; procedure TestOpEquality; procedure TestOpNotEquals; procedure TestOpAnd; procedure TestOpAndByte; procedure TestOpOr; procedure TestOpOrByte; procedure TestOpXor; procedure TestOpXorByte; procedure TestDivideBy2; procedure TestOpMin; procedure TestOpMinByte; procedure TestOpMax; procedure TestOpMaxByte; procedure TestOpClamp; procedure TestOpClampByte; procedure TestMulAdd; procedure TestMulDiv; procedure TestShuffle; procedure TestSwizzle; procedure TestCombine; procedure TestCombine2; procedure TestCombine3; procedure TestMinXYZComponent; procedure TestMaxXYZComponent; end; implementation {%region%----[ TVector4b Operators ]--------------------------------------------} procedure TVector4bComparatorTest.TestCompare; begin AssertTrue('Test Values do not match'+nbf1.ToString+' --> '+abf1.ToString, Compare(nbf1,abf1)); end; procedure TVector4bComparatorTest.TestCompareFalse; begin AssertFalse('Test Values should not match'+nbf1.ToString+' --> '+abf2.ToString, Compare(nbf1,abf2)); end; procedure TVector4bComparatorTest.TestCreateBytes; begin nbf3.Create(b1,b2,b3,b7); abf3.Create(b1,b2,b3,b7); AssertTrue('Vector Create no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestCreatefrom3b; begin nbf3.Create(nbt1,b7); abf3.Create(abt1,b7); AssertTrue('Vector Create no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpAdd; begin nbf3 := nbf1 + nbf2; abf3 := abf1 + abf2; AssertTrue('Vector + Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpAddByte; begin nbf3 := nbf1 + b1; abf3 := abf1 + b1; AssertTrue('Vector + Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpSub; begin nbf3 := nbf1 - nbf2; abf3 := abf1 - abf2; AssertTrue('Vector - Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpSubByte; begin nbf3 := nbf1 - b1; abf3 := abf1 - b1; AssertTrue('Vector - Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMul; begin nbf3 := nbf1 * nbf2; abf3 := abf1 * abf2; AssertTrue('Vector * Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMulByte; begin nbf3 := nbf1 * b1; abf3 := abf1 * b1; AssertTrue('Vector * Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpDiv; begin nbf3 := nbf1 Div nbf2; abf3 := abf1 Div abf2; AssertTrue('Vector Div Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpDivByte; begin nbf3 := nbf1 Div b1; abf3 := abf1 Div b1; AssertTrue('Vector Div Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpEquality; begin nb := nbf1 = nbf1; ab := abf1 = abf1; AssertTrue('Vector = do not match'+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := nbf1 = nbf2; ab := abf1 = abf2; AssertTrue('Vector = should not match'+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; procedure TVector4bComparatorTest.TestOpNotEquals; begin nb := nbf1 = nbf1; ab := abf1 = abf1; AssertTrue('Vector <> do not match'+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := nbf1 = nbf2; ab := abf1 = abf2; AssertTrue('Vector <> should not match'+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; procedure TVector4bComparatorTest.TestOpAnd; begin nbf3 := nbf1 and nbf2; abf3 := abf1 and abf2; AssertTrue('Vector And Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpAndByte; begin nbf3 := nbf1 and b5; abf3 := abf1 and b5; AssertTrue('Vector And Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpOr; begin nbf3 := nbf1 or nbf2; abf3 := abf1 or abf2; AssertTrue('Vector Or Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpOrByte; begin nbf3 := nbf1 or b1; abf3 := abf1 or b1; AssertTrue('Vector Or Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpXor; begin nbf3 := nbf1 xor nbf2; abf3 := abf1 xor abf2; AssertTrue('Vector Xor Vector no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpXorByte; begin nbf3 := nbf1 xor b1; abf3 := abf1 xor b1; AssertTrue('Vector Xor Byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; {%endregion%} {%region%----[ TVector4b Functions ]--------------------------------------------} procedure TVector4bComparatorTest.TestDivideBy2; begin nbf3 := nbf1.DivideBy2; abf3 := abf1.DivideBy2; AssertTrue('Vector DivideBy2 no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMin; begin nbf3 := nbf1.Min(nbf2); abf3 := abf1.Min(abf2); AssertTrue('Vector Min no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMinByte; begin nbf3 := nbf1.Min(b2); abf3 := abf1.Min(b2); AssertTrue('Vector Min byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMax; begin nbf3 := nbf1.Max(nbf2); abf3 := abf1.Max(abf2); AssertTrue('Vector Max no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpMaxByte; begin nbf3 := nbf1.Max(b2); abf3 := abf1.Max(b2); AssertTrue('Vector Max byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpClamp; begin nbf4 := nbf1.Swizzle(swAGRB); abf4 := abf1.Swizzle(swAGRB); nbf3 := nbf1.Clamp(nbf2, nbf4); abf3 := abf1.Clamp(abf2, abf4); AssertTrue('Vector Clamp no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestOpClampByte; begin nbf3 := nbf1.Clamp(b2, b5); abf3 := abf1.Clamp(b2, b5); AssertTrue('Vector Clamp byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestMulAdd; begin nbf4 := nbf1.Swizzle(swAGRB); abf4 := abf1.Swizzle(swAGRB); nbf3 := nbf1.MulAdd(nbf2, nbf4); abf3 := abf1.MulAdd(abf2, abf4); AssertTrue('Vector MulAdd no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestMulDiv; begin nbf3 := nbf1.MulDiv(nbf2,nbf2); abf3 := abf1.MulDiv(abf2,abf2); AssertTrue('Vector MulDiv byte no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestShuffle; begin nbf3 := nbf1.Shuffle(1,2,3,0); abf3 := abf1.Shuffle(1,2,3,0); AssertTrue('Vector Shuffle no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestSwizzle; begin nbf3 := nbf1.Swizzle(swAGRB); abf3 := abf1.Swizzle(swAGRB); AssertTrue('Vector Swizzle no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestCombine; begin nbf3 := nbf1.Combine(nbf2, b1); abf3 := abf1.Combine(abf2, b1); AssertTrue('Vector Combine no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestCombine2; begin nbf3 := nbf1.Combine2(nbf2, 0.8, 0.21); abf3 := abf1.Combine2(abf2, 0.8, 0.21); AssertTrue('Vector Combine2 no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestCombine3; begin nbf4 := nbf1.Swizzle(swAGRB); abf4 := abf1.Swizzle(swAGRB); nbf3 := nbf1.Combine3(nbf2, nbf4, 0.3, 0.4, 0.2); abf3 := abf1.Combine3(abf2, abf4, 0.3, 0.4, 0.2); AssertTrue('Vector Combine3 no match'+nbf3.ToString+' --> '+abf3.ToString, Compare(nbf3,abf3)); end; procedure TVector4bComparatorTest.TestMinXYZComponent; begin b4 := nbf1.MinXYZComponent; b8 := abf1.MinXYZComponent; AssertEquals('Vector MinXYZComponent no match', b4, b8); end; procedure TVector4bComparatorTest.TestMaxXYZComponent; begin b4 := nbf1.MaxXYZComponent; b8 := abf1.MaxXYZComponent; AssertEquals('Vector MaxXYZComponent no match', b4, b8); end; {%endregion%} initialization RegisterTest(REPORT_GROUP_VECTOR4B, TVector4bComparatorTest); end.
{ DelphiProtocolBuffer: SelfVersion.pas Copyright 2014 Stijn Sanders Made available under terms described in file "LICENSE" https://github.com/stijnsanders/DelphiProtocolBuffer } unit SelfVersion; interface function GetSelfVersion: string; implementation uses SysUtils, Windows; function GetSelfVersion: string; var r:THandle; p:pointer; v:PVSFIXEDFILEINFO; vl:cardinal; begin try r:=LoadResource(HInstance, FindResource(HInstance,MakeIntResource(1),RT_VERSION)); p:=LockResource(r); if VerQueryValue(p,'\',pointer(v),vl) then Result:=Format('v%d.%d.%d.%d', [v.dwFileVersionMS shr 16 ,v.dwFileVersionMS and $FFFF ,v.dwFileVersionLS shr 16 ,v.dwFileVersionLS and $FFFF ]); except Result:='v???'; end; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) } unit ormbr.dml.cache; interface uses Generics.Collections; type TQueryCache = class private class var FQueryCache: TDictionary<String, String>; public class constructor Create; class destructor Destroy; /// <summary> /// Lista para cache de comandos SQL, evitando o ORMBr usar RTTi toda /// vez que for solicitado um SELECT e INSERT. /// </summary> /// <param name="String"> /// Key de localização por classe e comando /// </param> /// <param name="String"> /// Comando SQL pronto para SELECT e INSERT /// </param> class function Get: TDictionary<String, String>; end; implementation { TQueryCache } class constructor TQueryCache.Create; begin FQueryCache := TDictionary<String, String>.Create; end; class destructor TQueryCache.Destroy; begin FQueryCache.Free; end; class function TQueryCache.Get: TDictionary<String, String>; begin Result := FQueryCache; end; end.
unit MainForm; interface uses Com, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Actions, Vcl.ActnList; type TSerialClientMainForm = class(TForm) OpenComPortButton: TButton; PortNumber: TComboBox; Baudrate: TComboBox; Console: TMemo; DataBitsField: TComboBox; StopBitsField: TComboBox; ParityField: TComboBox; procedure FormCreate(Sender: TObject); procedure OpenComPortButtonClick(Sender: TObject); function ReadBaud: cardinal; function ReadDataBits: cardinal; procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private-Deklarationen } public { Public-Deklarationen } end; TReceiveLoop = class(TThread) procedure execute; override; end; var SerialClientMainForm: TSerialClientMainForm; COM: TCOM; ReceiveLoop: TReceiveLoop; implementation {$R *.dfm} function TSerialClientMainForm.ReadBaud: cardinal; begin case BaudRate.ItemIndex of 0: result := 50; 1: result := 75; 2: result := 110; 3: result := 300; 4: result := 600; 5: result := 1200; 6: result := 2400; 7: result := 4800; 8: result := 9600; 9: result := 19200; 10: result := 38400; 11: result := 56000; 12: result := 57600; 13: result := 115200; end; end; function TSerialClientMainForm.ReadDataBits: cardinal; begin case BaudRate.ItemIndex of 0: result := 50; 1: result := 75; 2: result := 110; 3: result := 300; 4: result := 600; 5: result := 1200; 6: result := 2400; 7: result := 4800; 8: result := 9600; 9: result := 19200; 10: result := 38400; 11: result := 56000; 12: result := 57600; 13: result := 115200; end; end; procedure TSerialClientMainForm.OpenComPortButtonClick(Sender: TObject); var Connected: boolean; begin if COM.IsOpen = false then begin COM.Baud := ReadBaud; Console.Lines.Add('Öffne COM ' + IntToStr((PortNumber.ItemIndex) + 1) + sLineBreak + ' ...'); OpenComPortButton.Enabled := false; Connected := COM.TestComPortAvailable((PortNumber.ItemIndex) + 1); PortNumber.Enabled := false; BaudRate.Enabled := false; if COM.IsOpen then begin Console.Lines.add('COM ' + IntToStr(COM.ComNo) + ' geöffnet mit ' + IntToStr(COM.Baud) + ' Baud!' + sLineBreak + 'Datenbits: ' + IntToStr(Com.Databits) + sLineBreak + 'Stoppbits: ' + COM.Stopbits + sLineBreak + 'Parität: ' + COM.Parity + sLineBreak); ReceiveLoop := TReceiveLoop.Create(false); OpenComPortButton.Enabled := true; OpenComPortButton.Caption := 'Port schließen'; end else begin Console.Lines.add('COM ' + IntToStr(COM.ComNo) + ' nicht geöffnet! Fehlercode ' + IntToStr(COM.Error) + sLineBreak); OpenComPortButton.Enabled := true; PortNumber.Enabled := true; BaudRate.Enabled := true; end; end else begin ReceiveLoop.Terminate; ReceiveLoop.WaitFor; ReceiveLoop.free; Console.Lines.Add('schließe COM ' + IntToStr(COM.ComNo) + sLineBreak + ' ...'); OpenComPortButton.Enabled := false; PortNumber.Enabled := false; BaudRate.Enabled := false; COM.Close; if COM.IsOpen then begin OpenComPortButton.Enabled := true; Console.Lines.add('COM ' + IntToStr(COM.ComNo) + ' nicht geschlossen! Fehlercode ' + IntToStr(COM.Error) + sLineBreak); end else begin OpenComPortButton.Enabled := true; OpenComPortButton.Caption := 'Port öffnen'; PortNumber.Enabled := true; BaudRate.Enabled := true; Connected := false; Console.Lines.Add('COM ' + IntToStr(COM.ComNo) + ' geschlossen!' + sLineBreak); end; end; end; procedure TSerialClientMainForm.FormCreate(Sender: TObject); begin COM := TCOM.Create(SerialClientMainForm); end; procedure TSerialClientMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if ReceiveLoop <> nil then begin ReceiveLoop.Terminate; end; if COM <> nil then COM.free; end; // --------------------------------------------------------------- procedure TReceiveLoop.Execute; var RxData: byte; RxString: String; i: integer; SomeThingInBuffer: boolean; RxBinaryData: byte; begin RxData := 0; while not terminated do begin SomeThingInBuffer := false; while COM.GetChar(RxData) do begin RxString := RxString + Char(RxData); SomeThingInBuffer := true; end; if SomeThingInBuffer then SerialClientMainForm.Console.Lines.Add(RxString); RxString := ''; sleep(1); end; end; end.
unit IETFLangTests; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Windows, Sysutils, DUnitX.TestFramework, TextUtilities, IETFLanguageCodeServices; type [TextFixture] TIETFLangTests = Class (TObject) private FDefinitions : TIETFLanguageDefinitions; procedure pass(code : String); procedure fail(code : String); public [Setup] procedure Setup; [TearDown] procedure TearDown; [TestCase] Procedure TestSimple; [TestCase] Procedure TestWrong; end; implementation { TIETFLangTests } procedure TIETFLangTests.fail(code : String); var msg : String; o : TIETFLanguageCodeConcept; begin o := FDefinitions.parse(code, msg); try Assert.IsNull(o); Assert.IsNotEmpty(msg); finally o.Free; end; end; procedure TIETFLangTests.pass(code : String); var msg : String; o : TIETFLanguageCodeConcept; begin o := FDefinitions.parse(code, msg); try Assert.IsNotNull(o, msg); Assert.IsEmpty(msg); finally o.Free; end; end; procedure TIETFLangTests.Setup; begin FDefinitions := TIETFLanguageDefinitions.create(FileToString('C:\work\fhirserver\sql\lang.txt', TEncoding.ASCII)); end; procedure TIETFLangTests.TearDown; begin FDefinitions.Free; end; procedure TIETFLangTests.TestSimple; begin pass('en'); pass('en-AU'); pass('en-Latn-AU'); pass('en-Brai-US'); end; procedure TIETFLangTests.TestWrong; begin fail('enAU'); fail('en-AUA'); end; initialization TDUnitX.RegisterTestFixture(TIETFLangTests); end.
UNIT structures; INTERFACE USES constants; { TYPES : - pion : type du pion primitif - grille : grille globale de la partie - mainJoueur : main du joueur - mainJoueur : pioche générale } TYPE typeArgs = RECORD formes : INTEGER; couleurs : INTEGER; humains : INTEGER; machines : INTEGER; tuiles : INTEGER; graphique : BOOLEAN; END; pion = RECORD couleur : INTEGER; forme : INTEGER; END; couleur = RECORD col1 : INTEGER; col2 : INTEGER; END; grille = ARRAY OF ARRAY OF pion; typePioche = ARRAY OF pion; position = RECORD x : INTEGER; y : INTEGER; END; tabdyn = ARRAY OF INTEGER; tabPos = ARRAY OF position; tabPion = ARRAY OF pion; typeCoup = RECORD pos : tabPos; p : tabPion; END; tabCoups = ARRAY OF typeCoup; typeJoueur = RECORD main : tabPion; genre : BOOLEAN; score : INTEGER; END; tabJoueur = ARRAY OF typeJoueur; dataHistorique = RECORD id : INTEGER; joueur : STRING; pion : pion; posX : INTEGER; posY : INTEGER; END; CONST PION_NULL : pion = (couleur: COULEUR_NULL; forme: FORME_NULL); PION_ROUGE : pion = (couleur: COL_RED; forme: 12); PION_FLECHE : pion = (couleur : 7; forme: 11); IMPLEMENTATION END.
Unit Ucum; { Copyright (c) 2001-2013, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses Sysutils, DecimalSupport, AdvObjects, AdvNames, AdvStringLists, AdvPersistentLists; Const Ucum_CACHE_VERSION = 3; type TConceptKind = (UcumNull, UcumPREFIX, UcumBASEUNIT, UcumUNIT); TUcumProperty = class (TAdvName) private FCommonUnits : TAdvStringList; public Constructor Create; Override; Destructor Destroy; Override; function Link : TUcumProperty; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property CommonUnits : TAdvStringlist read FCommonUnits; end; TUcumPropertyList = class (TAdvNameList) Private function GetUcumProperty(iIndex : integer): TUcumProperty; Protected Function ItemClass : TAdvObjectClass; override; Public Property UcumProperty[iIndex : integer] : TUcumProperty read GetUcumProperty; default; End; TUcumConcept = class (TAdvPersistent) private Fkind : TConceptKind; Fcode : String; FcodeUC : String; FprintSymbol : String; Fnames : TAdvStringList; FText: String; protected Function GetKind : TConceptKind; virtual; public Constructor Create; Override; Destructor Destroy; Override; function Link : TUcumConcept; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property kind : TConceptKind read Getkind; Property code : String read Fcode write FCode; // case sensitive code for this concept Property codeUC : String read FcodeUC write FcodeUC; // case insensitive code for this concept Property printSymbol : String read FprintSymbol write FPrintSymbol; // print symbol for this code Property names : TAdvStringList read Fnames; // names for the concept Property Text : String read FText write FText; End; TUcumConceptList = class (TAdvPersistentList) Private function GetUcumItem(iIndex : integer): TUcumConcept; Protected Function ItemClass : TAdvObjectClass; override; Public Property UcumItem[iIndex : integer] : TUcumConcept read GetUcumItem; default; End; TUcumPrefix = class (TUcumConcept) private Fvalue : TSmartDecimal; protected Function GetKind : TConceptKind; Override; public function Link : TUcumPrefix; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property value : TSmartDecimal read Fvalue write FValue; //value for the prefix - 1^-24 through to 1^24 procedure SetPrecision(i : integer); End; TUcumPrefixList = class (TAdvPersistentList) Private function GetUcumItem(iIndex : integer): TUcumPrefix; Protected Function ItemClass : TAdvObjectClass; override; Public Property UcumItem[iIndex : integer] : TUcumPrefix read GetUcumItem; default; End; TUcumUnit = class (TUcumConcept) private FProperty : Integer; Public function Link : TUcumUnit; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property PropertyType : Integer read FProperty write FProperty; // the kind of thing this represents End; TUcumBaseUnit = class (TUcumUnit) private Fdim : Char; protected Function GetKind : TConceptKind; Override; public function Link : TUcumBaseUnit; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property dim : Char read FDim write FDim; End; TUcumBaseUnitList = class (TAdvPersistentList) Private function GetUcumItem(iIndex : integer): TUcumBaseUnit; Protected Function ItemClass : TAdvObjectClass; override; Public Function ExistsByCode(const sCode : String) : Boolean; Function GetByCode(const sCode : String) : TUcumBaseUnit; Property UcumItem[iIndex : integer] : TUcumBaseUnit read GetUcumItem; default; End; TUcumValue = class (TAdvPersistent) private Funit : String; FunitUC : String; Fvalue : TSmartDecimal; Ftext : String; public function Link : TUcumValue; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property unit_ : String read Funit write FUnit; Property unitUC : String read FunitUC write FUnitUC; Property value : TSmartDecimal read FValue write FValue; Property text : String read Ftext write FText; procedure SetPrecision(i : integer); End; TUcumDefinedUnit = class (TUcumUnit) private Fmetric : boolean; FisSpecial : boolean; Fclass_ : String; Fvalue : TUcumValue; protected Function GetKind : TConceptKind; Override; public Constructor Create; Override; Destructor Destroy; Override; function Link : TUcumDefinedUnit; Overload; Procedure Define(oFiler : TAdvFiler); Override; Property metric : boolean read Fmetric write FMetric; // whether this is a metric unit or not Property isSpecial : boolean read FisSpecial write FIsSpecial; // special means? Property class_ : String read Fclass_ write FClass_; // The class of this unit Property value : TUcumValue read Fvalue; // Value details End; TUcumDefinedUnitList = class (TAdvPersistentList) Private function GetUcumItem(iIndex : integer): TUcumDefinedUnit; Protected Function ItemClass : TAdvObjectClass; override; Public Function ExistsByCode(const sCode : String) : Boolean; Function GetByCode(const sCode : String) : TUcumDefinedUnit; Property UcumItem[iIndex : integer] : TUcumDefinedUnit read GetUcumItem; default; End; TUcumModel = class (TAdvPersistent) private FProperties : TUcumPropertyList; Fprefixes : TUcumPrefixList; FbaseUnits : TUcumBaseUnitList; FdefinedUnits : TUcumDefinedUnitList; FVersion : String; FRevisionDate : String; public Constructor Create; Override; Destructor Destroy; Override; function Link : TUcumModel; Overload; Procedure Define(oFiler : TAdvFiler); Override; Procedure clear; Function GetUnit(sCode : String) : TUcumUnit; Property prefixes : TUcumPrefixList read Fprefixes; Property baseUnits : TUcumBaseUnitList read FbaseUnits; Property definedUnits : TUcumDefinedUnitList read FdefinedUnits; Property Version : String read FVersion write FVersion; Property RevisionDate : String read FRevisionDate write FRevisionDate; Property Properties : TUcumPropertyList read FProperties; End; const CODES_CONCEPT_KIND : array [TConceptKind] of string = ('null', 'PREFIX', 'BASEUNIT', 'UNIT'); implementation { TUcumConcept } constructor TUcumConcept.Create; begin inherited; Fnames := TAdvStringList.Create; end; procedure TUcumConcept.Define(oFiler: TAdvFiler); begin inherited; oFiler['kind'].DefineEnumerated(FKind, CODES_CONCEPT_KIND); oFiler['code'].DefineString(Fcode); oFiler['codeUC'].DefineString(FcodeUC); oFiler['printSymbol'].DefineString(FprintSymbol); oFiler['names'].DefineObject(FNames); oFiler['Text'].DefineString(FText); end; destructor TUcumConcept.Destroy; begin FNames.Free; inherited; end; function TUcumConcept.GetKind: TConceptKind; begin result := UcumNull; end; function TUcumConcept.Link: TUcumConcept; begin result := TUcumConcept(Inherited Link); end; { TUcumPrefix } procedure TUcumPrefix.Define(oFiler: TAdvFiler); begin inherited; oFiler['value'].DefineObject(FValue); end; function TUcumPrefix.GetKind: TConceptKind; begin result := UcumPREFIX; end; function TUcumPrefix.Link: TUcumPrefix; begin result := TUcumPrefix(Inherited Link); end; procedure TUcumPrefix.SetPrecision(i: integer); begin FValue.Precision := i; end; { TUcumUnit } procedure TUcumUnit.Define(oFiler: TAdvFiler); begin inherited; oFiler['Property'].DefineInteger(FProperty); end; function TUcumUnit.Link: TUcumUnit; begin result := TUcumUnit(Inherited Link); end; { TUcumBaseUnit } procedure TUcumBaseUnit.Define(oFiler: TAdvFiler); begin inherited; oFiler['dim'].DefineChar(Fdim); end; function TUcumBaseUnit.GetKind: TConceptKind; begin result := UcumBASEUNIT; end; function TUcumBaseUnit.Link: TUcumBaseUnit; begin result := TUcumBaseUnit(Inherited Link); end; { TUcumValue } procedure TUcumValue.Define(oFiler: TAdvFiler); begin inherited; oFiler['unit'].DefineString(Funit); oFiler['unitUC'].DefineString(FunitUC); oFiler['text'].DefineString(Ftext); oFiler['value'].DefineObject(Fvalue); end; function TUcumValue.Link: TUcumValue; begin result := TUcumValue(Inherited Link); end; procedure TUcumValue.SetPrecision(i: integer); begin FValue.Precision := i; end; { TUcumDefinedUnit } constructor TUcumDefinedUnit.Create; begin inherited; Fvalue := TUcumValue.Create; end; procedure TUcumDefinedUnit.Define(oFiler: TAdvFiler); begin inherited; oFiler['metric'].Defineboolean(Fmetric); oFiler['isSpecial'].Defineboolean(FisSpecial); oFiler['class'].DefineString(Fclass_); oFiler['value'].DefineObject(Fvalue); end; destructor TUcumDefinedUnit.Destroy; begin Fvalue.Free; inherited; end; function TUcumDefinedUnit.GetKind: TConceptKind; begin result := UcumUNIT; end; function TUcumDefinedUnit.Link: TUcumDefinedUnit; begin result := TUcumDefinedUnit(Inherited Link); end; { TUcumPrefixList } function TUcumPrefixList.GetUcumItem(iIndex: integer): TUcumPrefix; begin result := TUcumPrefix(inherited ObjectByIndex[iIndex]); end; function TUcumPrefixList.ItemClass: TAdvObjectClass; begin result := TUcumPrefix; end; { TUcumBaseUnitList } function TUcumBaseUnitList.ExistsByCode(const sCode: String): Boolean; begin result := GetByCode(sCode) <> nil; end; function TUcumBaseUnitList.GetByCode(const sCode: String): TUcumBaseUnit; var i : integer; begin result := nil; for i := 0 to Count -1 do if UcumItem[i].code = sCode then begin result := UcumItem[i]; exit; End; end; function TUcumBaseUnitList.GetUcumItem(iIndex: integer): TUcumBaseUnit; begin result := TUcumBaseUnit(inherited ObjectByIndex[iIndex]); end; function TUcumBaseUnitList.ItemClass: TAdvObjectClass; begin result := TUcumBaseUnit; end; { TUcumDefinedUnitList } function TUcumDefinedUnitList.ExistsByCode(const sCode: String): Boolean; begin result := GetByCode(sCode) <> nil; end; function TUcumDefinedUnitList.GetByCode(const sCode: String): TUcumDefinedUnit; var i : integer; begin result := nil; for i := 0 to Count -1 do if UcumItem[i].code = sCode then begin result := UcumItem[i]; exit; End; end; function TUcumDefinedUnitList.GetUcumItem(iIndex: integer): TUcumDefinedUnit; begin result := TUcumDefinedUnit(inherited ObjectByIndex[iIndex]); end; function TUcumDefinedUnitList.ItemClass: TAdvObjectClass; begin result := TUcumDefinedUnit; end; { TUcumModel } procedure TUcumModel.clear; begin Fprefixes.Clear; FbaseUnits.Clear; FdefinedUnits.Clear; FVersion := ''; FRevisionDate := ''; end; constructor TUcumModel.Create; begin inherited; Fprefixes := TUcumPrefixList.Create; FbaseUnits := TUcumBaseUnitList.Create; FdefinedUnits := TUcumDefinedUnitList.Create; FProperties := TUcumPropertyList.Create; end; procedure TUcumModel.Define(oFiler: TAdvFiler); var i : integer; begin inherited; i := Ucum_CACHE_VERSION; oFiler['streamVersion'].DefineInteger(i); if i <> Ucum_CACHE_VERSION Then raise exception.create('the UCUM cache must be rebuilt using the ''Import UCUM'' operation in the manager application.'); oFiler['Version'].DefineString(FVersion); oFiler['RevisionDate'].DefineString(FRevisionDate); oFiler['prefixes'].DefineObject(Fprefixes); oFiler['baseUnits'].DefineObject(FbaseUnits); oFiler['definedUnits'].DefineObject(FdefinedUnits); oFiler['properties'].DefineObject(FProperties); end; destructor TUcumModel.Destroy; begin Fprefixes.Free; FbaseUnits.Free; FdefinedUnits.Free; FProperties.Free; inherited; end; function TUcumModel.GetUnit(sCode: String): TUcumUnit; begin result := FbaseUnits.GetByCode(sCode); if result = nil Then result := FdefinedUnits.GetByCode(sCode); end; function TUcumModel.Link: TUcumModel; begin result := TUcumModel(inherited Link); end; { TUcumConceptList } function TUcumConceptList.GetUcumItem(iIndex: integer): TUcumConcept; begin result := TUcumConcept(inherited ObjectByIndex[iIndex]); end; function TUcumConceptList.ItemClass: TAdvObjectClass; begin result := TUcumConcept; end; { TUcumPropertyList } function TUcumPropertyList.GetUcumProperty(iIndex: integer): TUcumProperty; begin result := TUcumProperty(Inherited ObjectByIndex[iIndex]); end; function TUcumPropertyList.ItemClass: TAdvObjectClass; begin result := TUcumProperty; end; { TUcumProperty } constructor TUcumProperty.Create; begin inherited; FCommonUnits := TAdvStringList.Create; end; procedure TUcumProperty.Define(oFiler: TAdvFiler); begin inherited; oFiler['CommonUnits'].DefineObject(FCommonUnits); end; destructor TUcumProperty.Destroy; begin FCommonUnits.Free; inherited; end; function TUcumProperty.Link: TUcumProperty; begin result := TUcumProperty(Inherited Link); end; End.
// Copyright (©) Ivan Bondarev, Stanislav Mihalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) ///Модуль элементов управления для GraphWPF unit Controls; interface uses GraphWPF; uses System.Windows; uses System.Windows.Media; uses System.Windows.Controls; procedure AddRightPanel(Width: real := 200; c: Color := Colors.LightGray); procedure AddLeftPanel(Width: real := 200; c: Color := Colors.LightGray); procedure AddTopPanel(Height: real := 70; c: Color := Colors.LightGray); procedure AddBottomPanel(Height: real := 70; c: Color := Colors.LightGray); procedure AddStatusBar(Height: real := 24); var ActivePanel: Panel; GlobalMargin := 5; type GButton = System.Windows.Controls.Button; GTextBlock = System.Windows.Controls.TextBlock; GTextBox = System.Windows.Controls.TextBox; ///!# CommonControl = class protected element: FrameworkElement; function GetM: real := InvokeReal(()->element.Margin.Top); procedure SetMP(m: real) := element.Margin := new Thickness(m); procedure SetM(m: real) := Invoke(SetMP,m); function GetW: real := InvokeReal(()->element.Width); procedure SetWP(w: real) := element.Width := w; procedure SetW(w: real) := Invoke(SetWP,w); function GetH: real := InvokeReal(()->element.Height); procedure SetHP(h: real) := element.Height := h; procedure SetH(h: real) := Invoke(SetHP,h); public property Width: real read GetW write SetW; property Height: real read GetH write SetH; property Margin: real read GetM write SetM; end; ///!# Button = class(CommonControl) protected function b: GButton := element as GButton; procedure BClick(sender: Object; e: RoutedEventArgs); begin if Click <> nil then Click; end; function GetText: string := InvokeString(()->b.Content as string); procedure SetTextP(t: string) := b.Content := t; procedure SetText(t: string) := Invoke(SetTextP,t); procedure CreateP(Txt: string); begin element := new GButton; Margin := GlobalMargin; Text := Txt; b.Click += BClick; ActivePanel.Children.Add(b); end; public event Click: procedure; constructor Create(Txt: string); begin Invoke(CreateP,Txt); end; property Text: string read GetText write SetText; end; ///!# TextBlock = class(CommonControl) protected function b: GTextBlock := element as GTextBlock; function GetText: string := InvokeString(()->b.Text); procedure SetTextP(t: string) := b.Text := t; procedure SetText(t: string) := Invoke(SetTextP,t); procedure CreateP(Txt: string); begin element := new GTextBlock; element.Margin := new Thickness(5,5,5,0); Text := Txt; ActivePanel.Children.Add(b); end; public constructor Create(Txt: string); begin Invoke(CreateP,Txt); end; property Text: string read GetText write SetText; end; ///!# TextBox = class(CommonControl) protected function tb: GTextBox := element as GTextBox; procedure BTextChanged(sender: Object; e: TextChangedEventArgs); begin if Click <> nil then Click; end; function GetText: string := InvokeString(()->tb.Text); procedure SetTextP(t: string) := tb.Text := t; procedure SetText(t: string) := Invoke(SetTextP,t); procedure CreateP(Txt: string); begin element := new GTextBox; element.HorizontalAlignment := HorizontalAlignment.Left; element.Margin := new Thickness(5,0,5,5); //Margin := GlobalMargin; Text := Txt; tb.TextChanged += BTextChanged; ActivePanel.Children.Add(tb); end; public event Click: procedure; constructor Create(Txt: string); begin Invoke(CreateP,Txt); end; property Text: string read GetText write SetText; end; implementation uses System.Windows; uses System.Windows.Controls; uses System.Windows.Controls.Primitives; uses System.Windows.Media.Imaging; var StatusBarPanel: StatusBar; LeftPanel,RightPanel,TopPanel,BottomPanel: Panel; procedure AddPanel(var pp: StackPanel; wh: real; d: Dock; c: Color); begin if pp<>nil then exit; var p := new StackPanel; if (d = Dock.Left) or (d = Dock.Right) then begin p.Orientation := Orientation.Vertical; p.Width := wh; end else begin p.Orientation := Orientation.Horizontal; p.Height := wh; end; p.Background := new SolidColorBrush(c); DockPanel.SetDock(p,d); // Всегда добавлять предпоследним MainDockPanel.children.Insert(MainDockPanel.children.Count-1,p); pp := p; ActivePanel := p; end; procedure AddRightPanel(Width: real; c: Color) := Invoke(AddPanel,RightPanel,Width,Dock.Right,c); procedure AddLeftPanel(Width: real; c: Color) := Invoke(AddPanel,LeftPanel,Width,Dock.Left,c); procedure AddTopPanel(Height: real; c: Color) := Invoke(AddPanel,TopPanel,Height,Dock.Top,c); procedure AddBottomPanel(Height: real; c: Color) := Invoke(AddPanel,BottomPanel,Height,Dock.Bottom,c); procedure AddStatusBarP(Height: real); begin if StatusBarPanel<>nil then exit; var sb := new StatusBar; sb.Height := 24; DockPanel.SetDock(sb,Dock.Bottom); // Всегда первая MainDockPanel.children.Insert(0,sb); StatusBarPanel := sb; {var sbi := new StatusBarItem(); sbi.Content := 'sdghj'; sb.Items.Add(sbi); sbi := new StatusBarItem(); sbi.Content := '222'; sb.Items.Add(sbi);} end; procedure AddStatusBar(Height: real) := Invoke(AddStatusBarP,Height); begin end.
{******************************************************************************* * * * PentireFMX * * * * https://github.com/gmurt/PentireFMX * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksComponentEditors; interface uses Classes, DesignEditors, DesignIntf; const C_VERB_ABOUT = 'About'; C_ADD_TAB = '&Add Tab'; C_NEXT_TAB = '&Next Tab'; C_PREV_TAB = '&Previous Tab'; type TksBaseComponentEditor = class(TComponentEditor) private FVerbs: TStringList; protected procedure BuildVerbs(AVerbs: TStrings); virtual; public constructor Create(AComponent: TComponent; ADesigner: IDesigner); override; destructor Destroy; override; function GetVerbCount: Integer; override; function GetVerb(Index: Integer): string; override; procedure ExecuteVerb(Index: Integer); override; end; TksTabControlComponentEditor = class(TksBaseComponentEditor) private protected procedure BuildVerbs(AVerbs: TStrings); override; public procedure ExecuteVerb(Index: Integer); override; end; procedure Register; implementation uses SysUtils, FMX.Types, FMX.Dialogs, ksTabControl; procedure Register; begin // tab control... RegisterComponentEditor(TksTabControl, TksTabControlComponentEditor); RegisterComponentEditor(TksTabItem, TksTabControlComponentEditor); end; { TksTabControlComponentEditor } procedure TksTabControlComponentEditor.BuildVerbs(AVerbs: TStrings); begin inherited; AVerbs.Add(C_ADD_TAB); AVerbs.Add('-'); AVerbs.Add(C_PREV_TAB); AVerbs.Add(C_NEXT_TAB); end; procedure TksTabControlComponentEditor.ExecuteVerb(Index: Integer); var ItemParent: TFmxObject; ATabControl: TksTabControl; begin inherited; ATabControl := nil; if Component is TksTabControl then ATabControl := (Component as TksTabControl); if Component is TksTabItem then ATabControl := TksTabControl(TksTabItem(Component).Parent); if FVerbs[Index] = C_ADD_TAB then begin if ATabControl <> nil then begin ItemParent := TFmxObject((ATabControl as IItemsContainer).GetObject); Designer.CreateChild(TksTabItem, ItemParent); end; end; if FVerbs[Index] = C_PREV_TAB then ATabControl.PrevTab; if FVerbs[Index] = C_NEXT_TAB then ATabControl.NextTab; end; { TksBaseComponentEditor } procedure TksBaseComponentEditor.BuildVerbs(AVerbs: TStrings); begin end; constructor TksBaseComponentEditor.Create(AComponent: TComponent; ADesigner: IDesigner); begin inherited; FVerbs := TStringList.Create; BuildVerbs(FVerbs); if FVerbs.Count > 0 then FVerbs.Add('-'); FVerbs.Add(C_VERB_ABOUT); FVerbs.Add('-'); end; destructor TksBaseComponentEditor.Destroy; begin FVerbs.Free; inherited; end; procedure TksBaseComponentEditor.ExecuteVerb(Index: Integer); begin inherited; if FVerbs[Index] = C_VERB_ABOUT then ShowMessage('ksComponents - Components for FireMonkey'+#13+#13+ 'Twitter: @kscomponents'+#13+#13+ 'Copyright © 2017 Graham Murt'); end; function TksBaseComponentEditor.GetVerb(Index: Integer): string; begin Result := FVerbs[Index]; end; function TksBaseComponentEditor.GetVerbCount: Integer; begin Result := FVerbs.Count; end; end.
{******************************************************************************* Falcon Sistemas www.falconsistemas.com.br suporte@falconsistemas.com.br Written by Marlon Nardi - ALL RIGHTS RESERVED. *******************************************************************************} {$IF CompilerVersion >= 24.0} // XE3 ou superior {$LEGACYIFEND ON} {$IFEND} unit UniFSPopup; interface uses Classes, TypInfo, SysUtils, System.UITypes, uniGUIApplication, uniGUITypes, uniGUIClasses, uniButton, UniFSCommon; const FSAbout = 'store.falconsistemas.com.br'; PackageVersion = '1.0.0.15'; type TArrowLocation = (top, bottom, left, right); TPopupEvent = (click); TRelativePosition = (t_b, c_c, b_t, l_r, r_l, t_t, b_b, l_l, r_r, tr_bl, tr_br, bl_tr, br_tl); TOnEvents = procedure(EventName: string; Params: TUniStrings) of object; {$IF CompilerVersion >= 23.0} [ComponentPlatformsAttribute(pidWin32 or pidWin64 {$IF CompilerVersion >= 34.0}or pidLinux64{$IFEND})] {$IFEND} TUniFSPopup = class(TUniComponent) private FTarget: TUniBaseButton; FLoaded: Boolean; FWidth: Integer; FArrowLocation: TArrowLocation; FHtml: string; FFadeInDuration: Integer; FFadeOutDuration: Integer; FDimissDelay: Integer; FPopupEvent: TPopupEvent; FRelativeY: Integer; FRelativeX: Integer; FOnEvents: TOnEvents; FRelativePosition: TRelativePosition; protected function GetVersion: string; function GetAbout: string; function GetStrAllowLocation(ArrowLocation: TArrowLocation): string; function GetStrPopupEvent(PopupEvent: TPopupEvent): string; function GetStrRelativePosition(Relative: TRelativePosition): string; procedure WebCreate; override; procedure LoadCompleted; override; procedure BeforeLoadCompleted; override; procedure DOHandleEvent(EventName: string; Params: TUniStrings); override; procedure SetTypeCastControl(Control: TUniControl; Command: string); procedure ExecJS(JS: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetHtml(Value: string); published property Target: TUniBaseButton read FTarget write FTarget; property Width: Integer read FWidth write FWidth; property ArrowLocation: TArrowLocation read FArrowLocation write FArrowLocation; property Html: string read FHtml write SetHtml; property FadeInDuration: Integer read FFadeInDuration write FFadeInDuration; property FadeOutDuration: Integer read FFadeOutDuration write FFadeOutDuration; property DimissDelay: Integer read FDimissDelay write FDimissDelay; property PopupEvent: TPopupEvent read FPopupEvent write FPopupEvent; property RelativeY: Integer read FRelativeY write FRelativeY; property RelativeX: Integer read FRelativeX write FRelativeX; property RelativePosition: TRelativePosition read FRelativePosition write FRelativePosition; property OnEvents: TOnEvents read FOnEvents write FOnEvents; property About : string read GetAbout; property Version : string read GetVersion; end; procedure Register; implementation uses UniFSButton, uniBitBtn, uniSpeedButton; procedure Register; begin RegisterComponents('uniGUI Falcon', [TUniFSPopup]); end; { TUniFSPopup } procedure TUniFSPopup.BeforeLoadCompleted; var StrBuilder: TStringBuilder; begin inherited; if not FLoaded then begin FLoaded := True; if not Assigned(FTarget) then Exit; StrBuilder := TStringBuilder.Create; try StrBuilder.Append('function '+GetStrPopupEvent(FPopupEvent)+'(sender, eOpts) { '); StrBuilder.Append(' console.log("click"); '); StrBuilder.Append(' Ext.widget(''callout'', { '); StrBuilder.Append(' cls: "cartoon", '); StrBuilder.Append(' width: '+IntToStr(FWidth)+', '); StrBuilder.Append(' html: va_'+Self.JSName+', '); StrBuilder.Append(' calloutArrowLocation: "'+GetStrAllowLocation(FArrowLocation)+'", '); StrBuilder.Append(' target: "#'+Target.JSName+'_id", '); StrBuilder.Append(' relativePosition: "'+GetStrRelativePosition(FRelativePosition)+'", '); StrBuilder.Append(' relativeOffsets: ['+IntToStr(FRelativeX)+','+IntToStr(FRelativeY)+'], '); StrBuilder.Append(' fadeInDuration: '+IntToStr(FFadeInDuration)+', '); StrBuilder.Append(' fadeOutDuration: '+IntToStr(FFadeOutDuration)+', '); StrBuilder.Append(' dismissDelay: '+IntToStr(FDimissDelay)+', '); StrBuilder.Append(' }).show(); '); StrBuilder.Append('} '); SetTypeCastControl(Target, StrBuilder.ToString); finally FreeAndNil(StrBuilder); end; end; end; constructor TUniFSPopup.Create(AOwner: TComponent); begin inherited; Self.FWidth := 100; Self.FFadeInDuration := 200; Self.FFadeOutDuration := 200; Self.FDimissDelay := 0; Self.FPopupEvent := TPopupEvent.click; Self.RelativeX := 0; Self.RelativeY := 10; Self.FRelativePosition := TRelativePosition.t_b; end; destructor TUniFSPopup.Destroy; begin inherited; end; procedure TUniFSPopup.DOHandleEvent(EventName: string; Params: TUniStrings); begin inherited; if Assigned(FOnEvents) then FOnEvents(EventName, Params); end; procedure TUniFSPopup.ExecJS(JS: string); begin UniSession.AddJS(JS); end; function TUniFSPopup.GetAbout: string; begin Result := FSAbout; end; function TUniFSPopup.GetStrAllowLocation(ArrowLocation: TArrowLocation): string; begin Result := GetEnumName(TypeInfo(TArrowLocation), Integer(ArrowLocation)); end; function TUniFSPopup.GetStrPopupEvent(PopupEvent: TPopupEvent): string; begin Result := GetEnumName(TypeInfo(TPopupEvent), Integer(PopupEvent)); end; function TUniFSPopup.GetStrRelativePosition( Relative: TRelativePosition): string; begin Result := GetEnumName(TypeInfo(TRelativePosition), Integer(Relative)); Result := StringReplace(Result,'_','-',[]); end; function TUniFSPopup.GetVersion: string; begin Result := PackageVersion; end; procedure TUniFSPopup.LoadCompleted; begin inherited; end; procedure TUniFSPopup.SetTypeCastControl(Control: TUniControl; Command: string); begin if Control is TUniBitBtn then TUniBitBtn(Control).ClientEvents.ExtEvents.Values[Self.GetStrPopupEvent(FPopupEvent)] := Command; if Control is TUniButton then TUniButton(Control).ClientEvents.ExtEvents.Values[Self.GetStrPopupEvent(FPopupEvent)] := Command; if Control is TUniSpeedButton then TUniSpeedButton(Control).ClientEvents.ExtEvents.Values[Self.GetStrPopupEvent(FPopupEvent)] := Command; if Control is TUniFSButton then TUniFSButton(Control).ClientEvents.ExtEvents.Values[Self.GetStrPopupEvent(FPopupEvent)] := Command; end; procedure TUniFSPopup.SetHtml(Value: string); begin FHtml := Value; if not IsDesigning then UniSession.AddJS('va_'+Self.JSName+' = "'+Value+'"; '); end; procedure TUniFSPopup.WebCreate; begin inherited; JSComponent := TJSObject.JSCreate('Object'); UniSession.AddJS('va_'+Self.JSName+' = "'+Self.Name+'"; '); end; initialization UniAddCSSLibrary(CDN+'falcon/css/cartoon.min.css', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddCSSLibrary(CDN+'falcon/css/cartoon-style.css', CDNENABLED, [upoFolderUni, upoPlatformBoth]); UniAddJSLibrary(CDN+'falcon/js/callout.min.js', CDNENABLED, [upoFolderUni, upoPlatformBoth]); end.
unit hcUTCUtils; interface function GetUTC: TDateTime; function MakeUTCTime(DateTime: TDateTime): TDateTime; implementation uses Winapi.Windows ,SysUtils ; function GetUTC: TDateTime; var stim: SYSTEMTIME; begin GetSystemTime(stim); result := SystemTimeToDateTime(stim); end; function MakeUTCTime(DateTime: TDateTime): TDateTime; { Converts a local datetime value into UTC. } var TZI: TTimeZoneInformation; Bias :LongInt; //difference in Minutes from UTC (aka GMT) time begin case GetTimeZoneInformation(TZI) of TIME_ZONE_ID_STANDARD: Bias := TZI.Bias; TIME_ZONE_ID_DAYLIGHT: Bias := TZI.Bias + TZI.DaylightBias; else raise Exception.Create('Error converting to UTC Time. Time zone could not be determined.'); end; Result := DateTime + (Bias / MinsPerHour / HoursPerDay); end; end.
{********************************************************************} { TMS TAdvFocusHelper Demo } { for Delphi & C++Builder } { } { } { written by TMS Software } { copyright 2012 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } {********************************************************************} unit Udemo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AdvFocusHelper, StdCtrls; type TForm100 = class(TForm) AdvFocusHelper1: TAdvFocusHelper; Edit1: TEdit; Edit2: TEdit; ListBox1: TListBox; Button1: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; ComboBox1: TComboBox; private { Private declarations } public { Public declarations } end; var Form100: TForm100; implementation {$R *.dfm} end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.ConvexHullGenerator2D; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types, PasVulkan.Math; type TpvConvexHull2DPixels=array of boolean; procedure GetConvexHull2D(const Pixels:TpvConvexHull2DPixels; const Width,Height:TpvInt32; out ConvexHullVertices:TpvVector2Array; CountVertices:TpvInt32; out CenterX,CenterY,CenterRadius:TpvFloat; const BorderExtendX:TpvFloat=1.0; const BorderExtendY:TpvFloat=1.0; const ConvexHullMode:TpvInt32=0); implementation function IsLeft(const p0,p1,p2:TpvVector2):TpvFloat; begin result:=((p1.x-p0.x)*(p2.y-p0.y))-((p2.x-p0.x)*(p1.y-p0.y)); end; function FindPerpendicularDistance(const p,p1,p2:TpvVector2):TpvFloat; var slope,intercept:TpvFloat; begin if p1.x=p2.x then begin result:=abs(p.x-p1.x); end else begin slope:=(p2.y-p1.y)/(p2.x-p1.x); intercept:=p1.y-(slope*p1.x); result:=abs(((slope*p.x)-p.y)+intercept)/sqrt(sqr(slope)+1); end; end; function RamerDouglasPeucker(const Points:TpvVector2Array;Epsilon:TpvFloat):TpvVector2Array; var FirstPoint,LastPoint:TpvVector2; Index,i,j:TpvInt32; Distance,BestDistance:TpvFloat; r1,r2:TpvVector2Array; begin if length(Points)<3 then begin result:=copy(Points); end else begin result:=nil; FirstPoint:=Points[0]; LastPoint:=Points[length(Points)-1]; Index:=-1; BestDistance:=0; for i:=1 to length(Points)-1 do begin Distance:=FindPerpendicularDistance(Points[i],FirstPoint,LastPoint); if BestDistance<Distance then begin BestDistance:=Distance; Index:=i; end; end; if BestDistance>Epsilon then begin r1:=RamerDouglasPeucker(copy(Points,0,Index+1),Epsilon); r2:=RamerDouglasPeucker(copy(Points,Index,(length(Points)-Index)+1),Epsilon); SetLength(result,(length(r1)-1)+length(r2)); for i:=0 to length(r1)-2 do begin result[i]:=r1[i]; end; j:=length(r1)-1; for i:=0 to length(r2)-1 do begin result[i+j]:=r2[i]; end; end else begin SetLength(result,2); result[0]:=FirstPoint; result[1]:=LastPoint; end; end; end; function GenerateConvexHull(const Points:TpvVector2Array):TpvVector2Array; var bot,top,i,n,minmin,minmax,maxmin,maxmax:TpvInt32; xmin,xmax:TpvFloat; begin // indices for bottom and top of the stack //bot:=0; top:=-1; n:=length(Points); result:=nil; SetLength(result,n*3); // Get the indices of points with min x-coord and min|max y-coord minmin:=0; xmin:=Points[0].x; i:=1; while i<n do begin if Points[i].x<>xmin then begin break; end; inc(i); end; minmax:=i-1; if minmax=(n-1) then begin SetLength(result,3); // degenerate case: all x-coords == xmin inc(top); result[top]:=Points[minmin]; if Points[minmax].y<>Points[minmin].y then begin // a nontrivial segment inc(top); result[top]:=Points[minmax]; end; // add polygon endpoint inc(top); result[top]:=Points[minmin]; SetLength(result,top+1); exit; end; // Get the indices of points with max x-coord and min|max y-coord maxmax:=n-1; xmax:=Points[n-1].x; i:=n-2; while i>=0 do begin if Points[i].x<>xmax then begin break; end; dec(i); end; maxmin:=i+1; // Compute the lower hull on the stack H inc(top); result[top]:=Points[minmin]; // push minmin point onto stack i:=minmax; while true do begin inc(i); if i<=maxmin then begin // the lower line joins P[minmin] with P[maxmin] if (IsLeft(Points[minmin],Points[maxmin],Points[i])>=0) and (i<maxmin) then begin // ignore P[i] above or on the lower line continue; end; while top>0 do begin // test if P[i] is left of the line at the stack top if IsLeft(result[top-1],result[top],Points[i])>0 then begin break; end else begin // pop top point off stack dec(top); end; end; // push P[i] onto stack inc(top); result[top]:=Points[i]; end else begin break; end; end; if maxmax<>maxmin then begin // if distinct xmax points // push maxmax point onto stack inc(top); result[top]:=Points[maxmax]; end; bot:=top; // the bottom point of the upper hull stack i:=maxmin; while true do begin dec(i); if i>=minmax then begin // the upper line joins P[maxmax] with P[minmax] if (IsLeft(Points[maxmax],Points[minmax],Points[i])>=0) and (i>minmax) then begin // ignore P[i] below or on the upper line continue; end; // at least 2 points on the upper stack while top>bot do begin // test if P[i] is left of the line at the stack top if IsLeft(result[top-1],result[top],Points[i])>0 then begin break; // P[i] is a new hull vertex end else begin // pop top point off stack dec(top); end; end; // push P[i] onto stack inc(top); result[top]:=Points[i]; end else begin break; end; end; if minmax<>minmin then begin // push joining endpoint onto stack inc(top); result[top]:=Points[minmin]; end; if (abs(result[0].x-result[top].x)>(1e-18)) or (abs(result[0].y-result[top].y)>(1e-18)) then begin SetLength(result,top+2); result[top+1]:=result[0]; end else begin SetLength(result,top+1); end; end; function VisvalingamWhyatt(const Points:TpvVector2Array;MaxCount:TpvInt32):TpvVector2Array; var Index,Count,MinIndex:TpvInt32; MinArea,Area:TpvFloat; begin result:=copy(Points); Count:=length(result); while (Count>3) and (Count>MaxCount) do begin MinIndex:=0; MinArea:=0; for Index:=1 to Count-2 do begin Area:=abs(((result[Index-1].x-result[Index+1].x)*(result[Index].y-result[Index-1].y))- ((result[Index-1].x-result[Index].x)*(result[Index+1].y-result[Index-1].y)))*0.5; if (MinIndex=0) or (MinArea>Area) then begin MinArea:=Area; MinIndex:=Index; end; end; for Index:=MinIndex to Count-2 do begin result[Index]:=result[Index+1]; end; dec(Count); end; SetLength(result,Count); end; function VisvalingamWhyattModified(const Points:TpvVector2Array;MinimumArea:TpvFloat;MaxCount:TpvInt32):TpvVector2Array; var Index,Count,MinIndex:TpvInt32; MinArea,Area:TpvFloat; begin result:=copy(Points); Count:=length(result); while (Count>3) and (Count>MaxCount) do begin MinIndex:=0; MinArea:=0; for Index:=1 to Count-2 do begin Area:=abs(((result[Index-1].x-result[Index+1].x)*(result[Index].y-result[Index-1].y))- ((result[Index-1].x-result[Index].x)*(result[Index+1].y-result[Index-1].y)))*0.5; if (Area<=MinimumArea) and ((MinIndex=0) or (MinArea>Area)) then begin MinArea:=Area; MinIndex:=Index; end; end; if MinIndex=0 then begin break; end else begin for Index:=MinIndex to Count-2 do begin result[Index]:=result[Index+1]; end; dec(Count); end; end; SetLength(result,Count); end; function GetArea(const Points:TpvVector2Array):TpvFloat; var i:TpvInt32; begin result:=0; for i:=0 to length(Points)-2 do begin result:=result+((Points[i].x*Points[i+1].y)-(Points[i+1].x*Points[i].y)); end; result:=result*0.5; end; function FixLastPoint(const Points:TpvVector2Array):TpvVector2Array; var c:TpvInt32; begin result:=copy(Points); c:=length(Points); if (c>0) and ((abs(Points[0].x-Points[c-1].x)>(1e-18)) or (abs(Points[0].y-Points[c-1].y)>(1e-18))) then begin SetLength(result,c+1); result[c]:=Points[0]; end; end; function FixNoLastPoint(const Points:TpvVector2Array):TpvVector2Array; var c:TpvInt32; begin result:=copy(Points); c:=length(Points); if (c>0) and ((abs(Points[0].x-Points[c-1].x)<=(1e-18)) and (abs(Points[0].y-Points[c-1].y)<=(1e-18))) then begin SetLength(result,c-1); end; end; function FixOrder(const Points:TpvVector2Array):TpvVector2Array; var i,j:TpvInt32; begin result:=copy(Points); if GetArea(Points)<0 then begin // If it is clockwise, so make it counterclockwise j:=length(Points); for i:=0 to length(Points)-1 do begin result[j-(i+1)]:=Points[i]; end; end; end; function SortPoints(const Points:TpvVector2Array):TpvVector2Array; var i:TpvInt32; p:TpvVector2; begin result:=copy(Points); i:=0; while i<(length(result)-1) do begin if (result[i].y>result[i+1].y) or ((result[i].y=result[i+1].y) and (result[i].x>result[i+1].x)) then begin p:=result[i]; result[i]:=result[i+1]; result[i+1]:=p; if i>0 then begin dec(i); end else begin inc(i); end; end else begin inc(i); end; end; end; function SegmentSegmentIntersection(const a1,a2,b1,b2:TpvVector2):TpvFloat; const epsilon=0.0000000001; var r1,r2:TpvVector2; A,B,s,t:TpvFloat; begin r1.x:=a2.x-a1.x; r1.y:=a2.y-a1.y; r2.x:=b2.x-b1.x; r2.y:=b2.y-b1.y; if r1.x=0 then begin result:=-1; exit; end; A:=(a1.y-b1.y)+((r1.y/r1.x)*(b1.x-a1.x)); B:=r2.y-((r1.y/r1.x)*r2.x); if B=0 then begin result:=-1; exit; end; s:=A/B; if (s<=epsilon) or (s>(1.0+epsilon)) then begin result:=-1; exit; end; t:=((b1.x-a1.x)+(s*r2.x))/r1.x; if (t<epsilon) or (t>(1.0+epsilon)) then begin result:=-1; exit; end; result:=t; end; function SegmentHullIntersection(const Points:TpvVector2Array;const a1,a2:TpvVector2):boolean; var i:TpvInt32; begin result:=false; for i:=0 to length(Points)-2 do begin if SegmentSegmentIntersection(a1,a2,Points[i],Points[i+1])>=0 then begin result:=true; break; end; end; end; function PointHullIntersection(const Points:TpvVector2Array;const p:TpvVector2):boolean; var i:TpvInt32; d:TpvFloat; Sign,FirstSign:boolean; begin result:=true; FirstSign:=false; for i:=0 to length(Points)-2 do begin d:=((p.y-Points[i].y)*(Points[i+1].x-Points[i].x))-((p.x-Points[i].x)*(Points[i+1].y-Points[i].y)); if d<>0 then begin Sign:=d>0; if i=0 then begin FirstSign:=Sign; end else if Sign<>FirstSign then begin result:=false; break; end; end; end; end; function PointInHull(const Points:TpvVector2Array;const p:TpvVector2):boolean; var i,j:TpvInt32; d0,d1:TpvVector2; d:TpvFloat; s:boolean; begin result:=false; j:=length(Points)-2; for i:=0 to length(Points)-3 do begin if ((Points[i].y>p.y)<>(Points[j].y>p.y)) and (p.x<(((Points[j].x-Points[i].x)*((p.y-Points[i].y)/(Points[j].y-Points[i].y)))+Points[i].x)) then begin result:=not result; end; j:=i; end; end; function InRect(const a,b,c:TpvVector2):boolean; begin if b.x=c.x then begin result:=(a.y>=Math.min(b.y,c.y)) and (a.y<=Math.max(b.y, c.y)); end else if b.y=c.y then begin result:=(a.x>=Math.min(b.x,c.x)) and (a.x<=Math.max(b.x,c.x)); end else begin result:=((a.x>=Math.min(b.x,c.x)) and (a.x<=Math.max(b.x,c.x))) and ((a.y>=Math.min(b.y,c.y)) and (a.y<=Math.max(b.y,c.y))); end; end; function GetLineIntersection(const a1,a2,b1,b2:TpvVector2;var HitPoint:TpvVector2):boolean; var dax,dbx,day,dby,Den,A,B:TpvFloat; begin result:=false; dax:=a1.x-a2.x; dbx:=b1.x-b2.x; day:=a1.y-a2.y; dby:=b1.y-b2.y; Den:=(dax*dby)-(day*dbx); if abs(Den)<1e-20 then begin exit; end; A:=(a1.x*a2.y)-(a1.y*a2.x); B:=(b1.x*b2.y)-(b1.y*b2.x); HitPoint.x:=((A*dbx)-(dax*B))/Den; HitPoint.y:=((A*dby)-(day*B))/Den; result:=InRect(HitPoint,a1,a2) and InRect(HitPoint,b1,b2); end; function FindOptimalPolygon(const Points:TpvVector2Array;VertexCount:TpvInt32;var DestArea:TpvFloat):TpvVector2Array; type TLine=record Start:TpvVector2; Difference:TpvVector2; end; TLines=array of TLine; var Vertices,Edges,Dest:TpvVector2Array; Counters:array of TpvInt32; Lines:TLines; First:boolean; MinArea:TpvFloat; function Perp(const u,v:TpvVector2):TpvFloat; begin result:=(u.x*v.y)-(u.y*v.x); end; function Intersect(var HitPoint:TpvVector2;const Line0,Line1:TLine):boolean; var d,t:TpvFloat; Difference:TpvVector2; begin result:=false; d:=Perp(Line0.Difference,Line1.Difference); if abs(d)<1e-12 then begin exit; end; Difference.x:=Line0.Start.x-Line1.Start.x; Difference.y:=Line0.Start.y-Line1.Start.y; t:=Perp(Line1.Difference,Difference)/d; if t<0.5 then begin exit; end; HitPoint.x:=Line0.Start.x+(Line0.Difference.x*t); HitPoint.y:=Line0.Start.y+(Line0.Difference.y*t); result:=true; end; procedure DoLevel(Level:TpvInt32); var i:TpvInt32; Area:TpvFloat; begin if (Level+1)=VertexCount then begin while Counters[Level]<length(Lines) do begin if Intersect(Vertices[Level-1],Lines[Counters[Level-1]],Lines[Counters[Level]]) then begin if Intersect(Vertices[Level],Lines[Counters[Level]],Lines[Counters[0]]) then begin for i:=0 to VertexCount-2 do begin Edges[i].x:=Vertices[i+1].x-Vertices[0].x; Edges[i].y:=Vertices[i+1].y-Vertices[0].y; end; Area:=0; for i:=0 to VertexCount-3 do begin Area:=Area+((Edges[i].y*Edges[i+1].x)-(Edges[i].x*Edges[i+1].y)); end; Area:=abs(Area)*0.5; if First or (Area<MinArea) then begin First:=false; MinArea:=Area; for i:=0 to VertexCount-1 do begin Dest[i]:=Vertices[i]; end; end; end; end; inc(Counters[Level]); end; end else begin while Counters[Level]<length(Lines) do begin if Intersect(Vertices[Level-1],Lines[Counters[Level-1]],Lines[Counters[Level]]) then begin Counters[Level+1]:=Counters[Level]+1; DoLevel(Level+1); end; inc(Counters[Level]); end; end; end; var i:TpvInt32; begin Vertices:=nil; Edges:=nil; Dest:=nil; Lines:=nil; Counters:=nil; if (length(Points)>=3) and (VertexCount>=3) then begin try SetLength(Vertices,VertexCount); SetLength(Edges,VertexCount); SetLength(Dest,VertexCount); SetLength(Counters,VertexCount); First:=true; MinArea:=0; SetLength(Lines,length(Points)); if GetArea(Points)<0 then begin // Input is clockwise for i:=0 to length(Points)-1 do begin Lines[i].Start:=Points[i]; Lines[i].Difference.x:=Points[(i+1) mod length(Points)].x-Lines[i].Start.x; Lines[i].Difference.y:=Points[(i+1) mod length(Points)].y-Lines[i].Start.y; end; end else begin // Input is counterclockwise for i:=0 to length(Points)-1 do begin Lines[i].Start:=Points[length(Points)-(i+1)]; Lines[i].Difference.x:=Points[length(Points)-(((i+1) mod length(Points))+1)].x-Lines[i].Start.x; Lines[i].Difference.y:=Points[length(Points)-(((i+1) mod length(Points))+1)].y-Lines[i].Start.y; end; end; for i:=0 to VertexCount-1 do begin Counters[i]:=0; end; while Counters[0]<length(Lines) do begin Counters[1]:=Counters[0]+1; while Counters[1]<length(Lines) do begin if Intersect(Vertices[0],Lines[Counters[0]],Lines[Counters[1]]) then begin Counters[2]:=Counters[1]+1; DoLevel(2); end; inc(Counters[1]); end; inc(Counters[0]); end; DestArea:=MinArea; finally SetLength(Vertices,0); SetLength(Edges,0); SetLength(Lines,0); SetLength(Counters,0); end; end; result:=Dest; end; function FixConvexHull(const OptimizedPoints,OriginalPoints:TpvVector2Array):TpvVector2Array; var Count,Index,OtherIndex,OtherOtherIndex:TpvInt32; pA,pB,oA,oB:PpvVector2; AB,Normal,HitPoint,MidPoint,CenterPoint,BestHitPoint:TpvVector2; First,Last,Denominator,Distance,BestDistance,t,d,x1,y1,x2,y2:TpvFloat; OK:boolean; begin result:=copy(OptimizedPoints); Count:=length(result); CenterPoint.x:=0; CenterPoint.y:=0; x1:=0.0; y1:=0.0; x2:=0.0; y2:=0.0; for OtherIndex:=0 to length(OriginalPoints)-1 do begin oA:=@OriginalPoints[OtherIndex]; if OtherIndex=0 then begin x1:=oA^.x; y1:=oA^.y; x2:=oA^.x; y2:=oA^.y; end else begin x1:=Min(x1,oA^.x); y1:=Min(y1,oA^.y); x2:=Max(x2,oA^.x); y2:=Max(y2,oA^.y); end; end; CenterPoint.x:=(x1+x2)*0.5; CenterPoint.y:=(y1+y2)*0.5; OK:=true; while OK and (Count>3) do begin OK:=false; Index:=0; while Index<(Count-1) do begin pA:=@result[Index+0]; pB:=@result[Index+1]; AB.x:=pB^.x-pA^.x; AB.y:=pB^.y-pA^.y; MidPoint.x:=(pA^.x+pB^.x)*0.25; MidPoint.y:=(pA^.y+pB^.y)*0.25; if PointHullIntersection(OriginalPoints,MidPoint) then begin inc(Count); SetLength(result,Count); for OtherOtherIndex:=Count-1 downto Index+2 do begin result[OtherOtherIndex]:=result[OtherOtherIndex-1]; end; result[Index+1].x:=MidPoint.x; result[Index+1].y:=MidPoint.y; inc(Index); OK:=true; end; pA:=@result[Index+0]; pB:=@result[Index+1]; First:=0; Last:=0; BestDistance:=0; for OtherIndex:=0 to length(OriginalPoints)-2 do begin oA:=@OriginalPoints[OtherIndex+0]; oB:=@OriginalPoints[OtherIndex+1]; if GetLineIntersection(pA^,pB^,oA^,oB^,HitPoint) then begin if ((abs(HitPoint.x-pA^.x)+abs(HitPoint.y-pA^.y))>0) and ((abs(HitPoint.x-pB^.x)+abs(HitPoint.y-pB^.y))>0) then begin Distance:=sqr(CenterPoint.x-HitPoint.x)+sqr(CenterPoint.y-HitPoint.y); if BestDistance<Distance then begin BestDistance:=Distance; BestHitPoint:=HitPoint; end; end; end; end; if BestDistance>0 then begin inc(Count); SetLength(result,Count); for OtherOtherIndex:=Count-1 downto Index+2 do begin result[OtherOtherIndex]:=result[OtherOtherIndex-1]; end; result[Index+1].x:=BestHitPoint.x; result[Index+1].y:=BestHitPoint.y; end; inc(Index); end; end; SetLength(result,Count); end; procedure GetConvexHull2D(const Pixels:TpvConvexHull2DPixels; const Width,Height:TpvInt32; out ConvexHullVertices:TpvVector2Array; CountVertices:TpvInt32; out CenterX,CenterY,CenterRadius:TpvFloat; const BorderExtendX:TpvFloat=1.0; const BorderExtendY:TpvFloat=1.0; const ConvexHullMode:TpvInt32=0); var SpriteW,SpriteH,rx1,ry1,rx2,ry2,x,y,x1,x2,y1,y2,c,c2,i,j,k,n,p:TpvInt32; SpriteBitmap,SpriteBitmap2:TpvConvexHull2DPixels; WorkVertices,HullVertices,OriginalHullVertices:TpvVector2Array; b,OK:boolean; cx,cy,cr,r,d:TpvFloat; begin ConvexHullVertices:=nil; CenterX:=0.0; CenterY:=0.0; CenterRadius:=0.0; SpriteBitmap:=nil; SpriteBitmap2:=nil; WorkVertices:=nil; HullVertices:=nil; OriginalHullVertices:=nil; if (Width>0) and (Height>0) then begin try // Get width and height SpriteW:=Width; SpriteH:=Height; // Initialize arrays SetLength(SpriteBitmap,SpriteW*SpriteH); SetLength(SpriteBitmap2,SpriteW*SpriteH); for x:=0 to (SpriteW*SpriteH)-1 do begin SpriteBitmap[x]:=Pixels[x]; SpriteBitmap2[x]:=false; end; // Content size detection rx1:=SpriteW+1; ry1:=SpriteH+1; rx2:=-1; ry2:=-1; for y:=0 to SpriteH-1 do begin for x:=0 to SpriteW-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin rx1:=min(rx1,x); ry1:=min(ry1,y); rx2:=max(rx2,x); ry2:=max(ry2,y); end; end; end; case ConvexHullMode of 0:begin c:=4; SetLength(WorkVertices,4); WorkVertices[0].x:=0.0; WorkVertices[0].y:=0.0; WorkVertices[1].x:=(SpriteW-1.0)+BorderExtendX; WorkVertices[1].y:=0.0; WorkVertices[2].x:=(SpriteW-1.0)+BorderExtendX; WorkVertices[2].y:=(SpriteH-1.0)+BorderExtendY; WorkVertices[3].x:=0.0; WorkVertices[3].y:=(SpriteH-1.0)+BorderExtendY; end; 1:begin c:=4; SetLength(WorkVertices,4); WorkVertices[0].x:=rx1; WorkVertices[0].y:=ry1; WorkVertices[1].x:=rx2+BorderExtendX; WorkVertices[1].y:=ry1; WorkVertices[2].x:=rx2+BorderExtendX; WorkVertices[2].y:=ry2+BorderExtendY; WorkVertices[3].x:=rx1; WorkVertices[3].y:=ry2+BorderExtendY; end; else begin // Outer edge detection for y:=0 to SpriteH-1 do begin x1:=SpriteW+1; x2:=-1; for x:=0 to SpriteW-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin x1:=min(x1,x); x2:=max(x2,x); end; end; for x:=0 to SpriteW-1 do begin SpriteBitmap2[(y*SpriteW)+x]:=(x=x1) or (x=x2); end; end; for x:=0 to SpriteW-1 do begin y1:=SpriteH+1; y2:=-1; for y:=0 to SpriteH-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin y1:=min(y1,y); y2:=max(y2,y); end; end; for y:=0 to SpriteH-1 do begin SpriteBitmap2[(y*SpriteW)+x]:=SpriteBitmap2[(y*SpriteW)+x] or ((y=y1) or (y=y2)); end; end; // Reduce the count of points for y:=0 to SpriteH-1 do begin for x:=0 to SpriteW-1 do begin b:=SpriteBitmap2[(y*SpriteW)+x]; if b then begin if ((x>0) and SpriteBitmap2[(y*SpriteW)+(x-1)]) and (((x+1)<SpriteW) and SpriteBitmap2[(y*SpriteW)+(x+1)]) then begin b:=false; end else if ((y>0) and SpriteBitmap2[((y-1)*SpriteW)+x]) and (((y+1)<SpriteH) and SpriteBitmap2[((y+1)*SpriteW)+x]) then begin b:=false; end else if (((x>0) and (y>0)) and SpriteBitmap2[((y-1)*SpriteW)+(x-1)]) and ((((x+1)<SpriteW) and ((y+1)<SpriteH)) and SpriteBitmap2[((y+1)*SpriteW)+(x+1)]) then begin b:=false; end else if ((((x+1)<SpriteW) and (y>0)) and SpriteBitmap2[((y-1)*SpriteW)+(x+1)]) and (((x>0) and ((y+1)<SpriteH)) and SpriteBitmap2[((y+1)*SpriteW)+(x-1)]) then begin b:=false; end; end; SpriteBitmap[(y*SpriteW)+x]:=b; end; end; // Generate work vector array c:=0; i:=-1; for y:=0 to SpriteH-1 do begin for x:=0 to SpriteW-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin i:=y; inc(c); break; end; end; for x:=SpriteW-1 downto 0 do begin if SpriteBitmap[(y*SpriteW)+x] then begin i:=y; inc(c); break; end; end; end; SetLength(WorkVertices,c+2); c:=0; for y:=0 to SpriteH-1 do begin for x:=0 to SpriteW-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin WorkVertices[c].x:=x; WorkVertices[c].y:=y; inc(c); break; end; end; for x:=SpriteW-1 downto 0 do begin if SpriteBitmap[(y*SpriteW)+x] then begin WorkVertices[c].x:=x+BorderExtendX; WorkVertices[c].y:=y; inc(c); break; end; end; if (y=i) and (BorderExtendY<>0.0) then begin for x:=0 to SpriteW-1 do begin if SpriteBitmap[(y*SpriteW)+x] then begin WorkVertices[c].x:=x; WorkVertices[c].y:=y+BorderExtendY; inc(c); break; end; end; for x:=SpriteW-1 downto 0 do begin if SpriteBitmap[(y*SpriteW)+x] then begin WorkVertices[c].x:=x+BorderExtendX; WorkVertices[c].y:=y+BorderExtendY; inc(c); break; end; end; end; end; SetLength(WorkVertices,c); end; end; if c>0 then begin HullVertices:=GenerateConvexHull(SortPoints(WorkVertices)); c:=length(HullVertices); cx:=(rx1+rx2)*0.5; cy:=(ry1+ry2)*0.5; cr:=0; for i:=0 to c-1 do begin cr:=max(cr,sqr(cx-HullVertices[i].x)+sqr(cy-HullVertices[i].y)); end; cr:=min(sqrt(cr),sqrt(sqr(rx2-rx1)+sqr(ry2-ry1))*0.5); cr:=ceil(cr); if CountVertices<4 then begin CountVertices:=4; end; OriginalHullVertices:=copy(HullVertices); c2:=length(FixNoLastPoint(HullVertices)); if c2>CountVertices then begin if CountVertices<12 then begin HullVertices:=FindOptimalPolygon(FixNoLastPoint(HullVertices),CountVertices,r); for i:=0 to length(HullVertices)-1 do begin if HullVertices[i].x<cx then begin HullVertices[i].x:=floor(HullVertices[i].x); end else if HullVertices[i].x>cx then begin HullVertices[i].x:=ceil(HullVertices[i].x); end; if HullVertices[i].y<cy then begin HullVertices[i].y:=floor(HullVertices[i].y); end else if HullVertices[i].y>cy then begin HullVertices[i].y:=ceil(HullVertices[i].y); end; end; HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(HullVertices))); end else begin if (CountVertices<=17) and (c>17) then begin HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(RamerDouglasPeucker(FixOrder(HullVertices),1)))); HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(VisvalingamWhyattModified(FixOrder(HullVertices),4,17)))); c2:=length(FixNoLastPoint(HullVertices)); end; if (CountVertices<=50) and (c>50) then begin HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(VisvalingamWhyatt(FixOrder(HullVertices),51)))); end; c2:=length(FixNoLastPoint(HullVertices)); if c2>CountVertices then begin if CountVertices<12 then begin HullVertices:=FindOptimalPolygon(FixNoLastPoint(HullVertices),CountVertices,r); end else begin HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(VisvalingamWhyatt(FixOrder(HullVertices),CountVertices+1)))); end; end; for i:=0 to length(HullVertices)-1 do begin if HullVertices[i].x<cx then begin HullVertices[i].x:=floor(HullVertices[i].x); end else if HullVertices[i].x>cx then begin HullVertices[i].x:=ceil(HullVertices[i].x); end; if HullVertices[i].y<cy then begin HullVertices[i].y:=floor(HullVertices[i].y); end else if HullVertices[i].y>cy then begin HullVertices[i].y:=ceil(HullVertices[i].y); end; end; HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(HullVertices))); for c:=0 to length(OriginalHullVertices)-1 do begin OK:=true; for i:=0 to length(OriginalHullVertices)-1 do begin n:=0; p:=0; for j:=0 to length(HullVertices)-1 do begin if SameValue(HullVertices[j].x,OriginalHullVertices[i].x) and SameValue(HullVertices[j].y,OriginalHullVertices[i].y) then begin OK:=true; break; end; k:=j+1; if j>=length(HullVertices) then begin k:=0; end; d:=((OriginalHullVertices[i].x-HullVertices[j].x)*(HullVertices[k].y-HullVertices[j].y))- ((OriginalHullVertices[i].y-HullVertices[j].y)*(HullVertices[k].x-HullVertices[j].x)); if d<0.0 then begin inc(n); end else if d>0.0 then begin inc(p); end; if (p>0) and (n>0) then begin OK:=false; break; end; end; if not OK then begin SetLength(HullVertices,length(HullVertices)+1); HullVertices[length(HullVertices)-1]:=OriginalHullVertices[i]; HullVertices:=GenerateConvexHull(SortPoints(FixNoLastPoint(HullVertices))); break; end; end; if OK then begin break; end; end; end; end; ConvexHullVertices:=FixNoLastPoint(FixOrder(HullVertices)); CenterX:=cx; CenterY:=cy; CenterRadius:=cr; end; finally SetLength(SpriteBitmap,0); SetLength(SpriteBitmap2,0); SetLength(WorkVertices,0); SetLength(HullVertices,0); end; end; end; end.
(* ------------------------------------------------------ *) (* ZEIGE.PAS *) (* Ersatz fĀr den Dos-Befehl "TYPE". Man kann damit jede *) (* beliebige ASCII-Datei anschauen und darin vorwĄrts *) (* und rĀckwĄrts blĄttern. Aufruf am besten mit dem *) (* Namen der zu lesenden Datei als Parameter, sonst wird *) (* ein Dateiname erfragt. *) (* (c) 1989 Achim Bergmeister & TOOLBOX *) (* ------------------------------------------------------ *) PROGRAM Zeige; USES Crt, Dos; TYPE Str = STRING; StrZeiger = ^Str; CONST maxzahl = 2000; { maximale Zahl einzulesender Zeilen } VAR zeile : ARRAY [1..maxzahl] OF StrZeiger; aktzeile : INTEGER; max, i, j : INTEGER; f : TEXT; Name,z : STRING; ch : CHAR; Regs : Registers; PROCEDURE StringSpeichern(st: Str; VAR zeiger: StrZeiger); { Speichert die jeweils gelesene Zeile in einer } { dynamischen Struktur } VAR x : BYTE ABSOLUTE st; BEGIN GetMem(zeiger, Succ(x)); Move(st, zeiger^, Succ(x)); END; PROCEDURE StringLesen(zeiger: StrZeiger; VAR st: Str); { liest die dynamisch abgespeicherten Zeilen wieder in } { eine normale Stringvariable ein. } BEGIN st := zeiger^; END; PROCEDURE SpeicherFrei(st: StrZeiger); { gibt den belegten Speicherplatz frei } BEGIN FreeMem(st, Succ(Ord(st^[0]))); END; FUNCTION Kleiner(x, y: INTEGER) : INTEGER; BEGIN IF x < y THEN Kleiner := x ELSE Kleiner := y; END; PROCEDURE Stellung; { gibt die Nummer der jeweils letzten auf dem Bildschirm } { dargestellten Zeile und die Gesamtzeilenzahl aus. } BEGIN Window(1,1,80,25); TextAttr := 112; GotoXY(36,1); Write(aktzeile:4, ' von ', max); TextAttr := 10; Window (1,2,80,25); END; PROCEDURE Down; BEGIN IF aktzeile < max THEN BEGIN Inc(aktzeile); StringLesen(zeile[aktzeile], z); GotoXY(1,24); WriteLn(z); END; Stellung; END; PROCEDURE Up; BEGIN IF aktzeile > 23 THEN BEGIN Dec(aktzeile); StringLesen(zeile[aktzeile - 22], z); GotoXY(1,1); InsLine; Write(z); END; Stellung; END; PROCEDURE Ende; BEGIN IF max > 23 THEN BEGIN ClrScr; FOR j := max-23 TO max DO BEGIN StringLesen(zeile[j], z); WriteLn (z); END; aktzeile := max; END; Stellung; END; PROCEDURE Anfang; BEGIN ClrScr; FOR j := 1 TO Kleiner(23, max) DO BEGIN StringLesen(zeile[j], z); WriteLn(z); END; aktzeile := Kleiner(23, max); Stellung; END; PROCEDURE PageDown; BEGIN IF aktzeile < max - 24 THEN BEGIN ClrScr; FOR j := 1 TO 23 DO BEGIN Inc(aktzeile); StringLesen(zeile[aktzeile], z); WriteLn(z); END; END ELSE IF (aktzeile < max) AND (aktzeile >= max - 24) THEN Ende; Stellung; END; PROCEDURE PageUp; BEGIN IF aktzeile > 46 THEN BEGIN ClrScr; Dec(aktzeile, 46); FOR j := 1 TO 23 DO BEGIN Inc(aktzeile); StringLesen(zeile[aktzeile], z); WriteLn(z); END; END ELSE IF (aktzeile > 23) AND (aktzeile < 47) THEN Anfang; Stellung; END; BEGIN IF ParamCount > 0 THEN Name := ParamStr(1) ELSE BEGIN Write ('Dateiname: '); ReadLn (Name); END; IF Name <> '' THEN BEGIN Assign(f, Name); {$I-} Reset(f); {$I+} IF IOResult <> 0 THEN BEGIN Write('Lesefehler !'); Halt; END; { gewĀnschte Datei lesen und dynamisch abspeichern } i := 0; WHILE (NOT Eof (f)) AND (i < maxzahl) DO BEGIN Inc(i); ReadLn(f, z); StringSpeichern(z, zeile[i]); END; max := i; { Anzahl der Zeilen } Close(f); ClrScr; { Titelzeile ausgeben } TextAttr := 112; Write('Datei: ', Name); Write(' ':73 - Length(Name)); GotoXY(49, 1); Write('≥Home≥END≥PgUp≥PgDn≥', Chr(24), '≥', Chr(25), '≥Esc=Ende'); TextAttr := 10; Window (1,2,80,25); GotoXY(1,1); { Cursor verstecken } Regs.ah := 1; Regs.ch := 30; Regs.cl := 30; Intr ($10,Regs); { ZunĄchst die ersten 23 -oder weniger- Zeilen zeigen. } FOR j := 1 TO Kleiner (23, max) DO BEGIN StringLesen(zeile[j], z); WriteLn(z); END; aktzeile := Kleiner(23, max); Stellung; { Schleife mit Tastaturabfrage } REPEAT ch := ReadKey; IF ch = #0 THEN BEGIN ch := ReadKey; CASE ch OF #80 : Down; #72 : Up; #73 : PageUp; #81 : PageDown; #71 : Anfang; #79 : Ende; END; END; UNTIL ch = #27; { bis Esc gedrĀckt } { Speicherplatz wieder freimachen } FOR i := 1 TO max DO SpeicherFrei(zeile[i]); Window(1,1,80,25); GotoXY(1,25); { cursor wieder zeigen } Regs.ah := 1; Regs.ch := 11; Regs.cl := 12; Intr ($10,Regs); END; END. (* ------------------------------------------------------ *) (* Ende von ZEIGE.PAS *)
{ 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Clients) Dec 12th, 1999 - Added 2 procedures KeepAlive - just sends noop to the server Reset - Resets the mailbox to the state before you connected. Useful if you've marked msgs for deletion and then decide not to delete them. Jeremiah Gilbert } unit Pop3Winshoe; interface uses Classes, winshoes, WinshoeMessage; Type TWinshoePOP3 = class(TWinshoeMessageClient) private protected public constructor Create(AOwner: TComponent); override; procedure Connect; override; procedure Disconnect; override; function CheckMessages: Longint; function Delete(const piMsgNo: Integer): boolean; function Retrieve(const piMsgNo: Integer; pMsg: TWinshoeMessage): boolean; function RetrieveHeader(const piMsgNo: Integer; pMsg: TWinshoeMessage): boolean; function RetrieveSize(const piMsgNo: integer):integer; procedure KeepAlive; function Reset: boolean; published property Password; property UserID; end; // procs procedure Register; implementation Uses GlobalWinshoe , SysUtils; procedure Register; begin RegisterComponents('Winshoes Clients' , [TWinshoePOP3]); end; Constructor TWinshoePOP3.Create; Begin inherited Create(AOwner); Port := WSPORT_POP3; End; procedure TWinshoePOP3.Disconnect; begin try WriteLn('Quit'); finally inherited end; end; procedure TWinshoePOP3.Connect; begin inherited Connect; try FsCommandResult := ReadLn; if Copy(FsCommandResult, 1, 3) <> '+OK' then SRaise(EWinshoeConnectRefused); DoStatus('Connected'); Command('User ' + UserID, wsOk, 1, 'User Account is valid'); Command('Pass ' + Password, wsOk, 1, 'Password is valid'); except Disconnect; Raise; end; end; function TWinshoePOP3.Retrieve; begin if Command('RETR ' + IntToStr(piMsgNo), 1, 0, '') = wsOk then begin DoStatus('Retrieving message body '+IntToStr(piMsgNo)+'...'); ReceiveHeader(pMsg, ''); ReceiveBody(pMsg); DoStatus('Finished retrieving message body '+IntToStr(piMsgNo)+'.'); end; // Will only hit here if ok and NO exception, or IF is not executed result := ResultNo = wsOk; end; function TWinshoePOP3.CheckMessages; var s1,s2: string; begin result := 0; try Command('STAT', wsOk, 0, 'Checking for messages...'); s1 := CommandResult ; if s1 <> '' then begin s2 := Copy(s1,5,Length(s1)-5); result := StrToInt(Copy(s2,1,Pos(' ',s2)-1)); end; except on E: Exception do DoStatus(E.Message); end; end; function TWinshoePOP3.Delete; begin Command('DELE ' + IntToStr(piMsgNo), -1, 0, 'Deleting message '+ IntToStr(piMsgNo) + '...'); result := ResultNo = wsOk; end; function TWinShoePOP3.RetrieveHeader(const piMsgNo: Integer; pMsg: TWinshoeMessage): boolean; var sDummy:string; begin if Command('TOP ' + IntToStr(piMsgNo) + ' 0', wsOk, 0, 'Retrieving headers for message '+inttostr(pimsgno)+'...') = wsOk then begin ReceiveHeader(pMsg, ''); sDummy := ReadLn ; while sDummy = '' do sDummy := ReadLn ; if sDummy = '.' then result := true else result := false ; end else result := false ; end ; function TWinshoePOP3.RetrieveSize(const piMsgNo: integer): integer; var s:string; begin try // Returns the size of the message. if an error ocurrs, returns -1. if Command('LIST ' + InttoStr(piMsgNo), wsOK, 0, 'Retrieving size of message '+inttostr(pimsgno)+'...') = wsOk then if CommandResult <> '' then begin s := Copy(CommandResult, 5, Length(CommandResult) - 4); result := StrToIntDef(Copy(s,Pos(' ',s)+1, Length(s)-Pos(' ',s)+1),-1); end else result := -1 else result := -1 ; except on E: Exception do begin DoStatus(E.Message); result := -1 ; end; end; end; procedure TWinshoePOP3.KeepAlive; begin Command('NOOP', wsOK, 0,'Sending Keep Alive(NOOP)...'); end; function TWinshoePOP3.Reset; begin Command('RSET', wsOK, 0,'Resetting mailbox...'); result:= ResultNo = wsOK; end; end.
unit LuaFont; {$mode delphi} interface uses Classes, SysUtils, Graphics,lua, lualib, lauxlib, LuaHandler; procedure initializeLuaFont; implementation uses mainunit, LuaClass, LuaObject; function createFont(L: Plua_State): integer; cdecl; var f: TFont; begin result:=0; lua_pop(L, lua_gettop(L)); f:=TFont.Create; f.assign(mainform.font); //initialize it with the best font there is... luaclass_newClass(L, f); result:=1; end; function Font_getColor(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); lua_pushinteger(L, Font.Color); result:=1; end; function Font_setColor(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then Font.color:=lua_tointeger(L, -1); result:=0; end; function Font_getSize(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); lua_pushinteger(L, Font.Size); result:=1; end; function Font_setSize(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then Font.Size:=lua_tointeger(L, -1); result:=0; end; function Font_getName(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); lua_pushstring(L, Font.Name); result:=1; end; function Font_setName(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then Font.Name:=Lua_ToString(L, -1); result:=0; end; function Font_assign(L: PLua_State): integer; cdecl; var Font: TFont; begin Font:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then Font.Assign(lua_ToCEUserData(L, 1)); result:=0; end; procedure font_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getSize', font_getSize); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setSize', font_setSize); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getName', font_getName); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setName', font_setName); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getColor', font_getColor); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setColor', font_setColor); luaclass_addClassFunctionToTable(L, metatable, userdata, 'assign', font_assign); Luaclass_addPropertyToTable(L, metatable, userdata, 'Size', font_getSize, font_setSize); Luaclass_addPropertyToTable(L, metatable, userdata, 'Name', font_getName, font_setName); Luaclass_addPropertyToTable(L, metatable, userdata, 'Color', font_getColor, font_setColor); end; procedure initializeLuaFont; begin lua_register(LuaVM, 'createFont', createFont); lua_register(LuaVM, 'font_getSize', font_getSize); lua_register(LuaVM, 'font_setSize', font_setSize); lua_register(LuaVM, 'font_getName', font_getName); lua_register(LuaVM, 'font_setName', font_setName); lua_register(LuaVM, 'font_getColor', font_getColor); lua_register(LuaVM, 'font_setColor', font_setColor); end; initialization luaclass_register(TFont, font_addMetaData); end.
{$IFDEF WINDOWS} {$W-} {$ENDIF} {$N-,V-,G+} Unit NatLFN; Interface Uses {$IFDEF Windows} WinDos,WinTypes,WinProcs {$ELSE} Dos {$ENDIF} ,strings,LFN; const fsPathName = 79; LFNRuntimeErrors: boolean = false; { Determines if runtime errors are generated } LFNErr_Uninitialized = 120; { LFN routines called before LFNAssign } LFNErr_NotAllocated = 121; { LFN routines called before LFNNew } LFNErr_NotATextFile = 122; { Appending to a non-text file } {$IFDEF WINDOWS} ofn_LongNames = $00200000; { Required to support LFN in the common dialogs. } { OR it into the Flags record of TOpenFilename. } {$ENDIF} type {$IFNDEF WINDOWS} TSearchRec = SearchRec; TDateTime = DateTime; PString= ^string; {$ENDIF} ShortPathStr = array[0..fsPathName] of char; { Form used for old-style searches, with an embedded TSearchRec } TLFNShortSearchRec = record Attr : longint; Creation : comp; LastAccess : comp; LastMod : comp; HighFileSize : longint; Size : longint; Reserved : comp; Name : array[0..13] of char; SRec : TSearchRec; Filler : array[1..260-14-sizeof(TSearchRec)] of byte; ShortName : array[0..13] of char; Handle : word; end; PLFNShortSearchRec = ^TLFNShortSearchRec; { A record to isolate the UserData parameters } TLFNFileParam = record Handle : word; { The file handle } Mode : word; { The file mode } Res1 : array[1..28] of byte; { Everything else up to UserData } { Begin UserData } lfname : PString; { The long filename in String form } plfname : PChar; { The long filename in AsciiZ form } TextFile : boolean; { Is it a text or binary file } Initialized: boolean; { Has it been LFNAssigned } Magic : string[3]; { ID to check LFNNew } Res2 : array[0..1] of byte; { 2 bytes left in UserData } { End UserData } SName : array[0..79] of char; { The short filename } end; PLFNFileParam = ^TLFNFileParam; var LFNAble: boolean; { Is LFN supported or not. Upon startup it is determined } { by the OS, but can be switched off later if need be. } function LFNToggleSupport(on: boolean): boolean; function PathNameLength: integer; {$IFNDEF WINDOWS} { I need these to access the Srec.Name field properly } function PCharOf(var F): Pchar; {$ENDIF} { Basic API calls } function LFNFindFirst(filespec: PChar; attr: word; var S: TLFNSearchRec): word; function LFNFindNext(var S: TLFNSearchRec): word; function LFNFindClose(var S: TLFNSearchRec): word; function LFNGetFAttr(var F; var Attr: word): integer; { Service routines } {function LFNFileExist(fname: PChar): boolean; function LFNFSearch(Path,DirList: PChar): PChar; procedure LFNFSplit(Path: PChar; Dir,Name,Ext: PChar); function LFNFExpand(Path: PChar): PChar; procedure CanonicalFname(var S: PChar); function CanonicalFilename(Fname: PChar): Pchar;} { Interface to the Pascal Input/Output routines } procedure LFNNew (var F; IsText: boolean); function LFNAssign (var F; name: PChar): integer; function LFNRewrite(var F; RecLen: word): integer; function LFNAppend (var F; RecLen: word): integer; function LFNReset (var F; RecLen: word): integer; function LFNErase (var F): integer; function LFNClose (var F): integer; procedure LFNDispose(var F); function LFNRename (var F; NewName: PChar): integer; implementation const {$IFDEF WINDOWS} SEM_FailCriticalErrors = $0001; SEM_NoOpenFileErrorBox = $8000; {$ELSE} faReadOnly = ReadOnly; faHidden = Hidden; faSysFile = SysFile; faVolumeID = VolumeID; faDirectory = Directory; faArchive = Archive; faAnyFile = AnyFile; {$ENDIF} LFNMagic = 'LFN'; type PSearchRec = ^TSearchRec; TByteArray = array[0..$FFF0-1] of char; PByteArray = ^TByteArray; function PathNameLength: integer; begin if LFNAble then PathNameLength:=255 else PathNameLength:=fsPathName; end; {$IFDEF WINDOWS} procedure Message(S: PChar); begin MessageBox(0,S,'Message',mb_ok or mb_TaskModal); end; {$ELSE} function PCharOf(var F): Pchar; { A very simple function which returns a pointer to its argument. } { Its main use is in turning array[...] of char in to PChar, to } { simulate the TPW/TP7/BP7 extended syntax. } begin PCharOf:=@F; end; {$ENDIF} {$IFDEF WINDOWS} function SupportsLFN: boolean; var WinVersion: word; begin WinVersion := LoWord(GetVersion); SupportsLFN:=true; If ((Lo(WinVersion) = 3) and {windows 95 first} (Hi(WinVersion) < 95)) or {version is 3.95 } (Lo(WinVersion) < 3) then SupportsLFN := False; end; {$ELSE} function SupportsLFN: boolean; assembler; asm mov ax, $160a int $2f cmp ax, 0 jne @no { Not running under Windows } cmp bh, 2 jle @no { Major version <3 } cmp bh, 4 jge @yes { Major version >3 } cmp bl, 94 jle @no { Major version =3, minor <95 } @yes: mov al, true jmp @exit @no: mov al, false @exit: end; { SupportsLFN } {$ENDIF} function LFNToggleSupport(on: boolean): boolean; { This routine toggles LFN support on and off, provided } { the OS supports it. It returns the previous status. } begin LFNToggleSupport:=LFNAble; LFNAble:=on and SupportsLFN; end; {==============================================================} { BASIC LFN API CALLS. } { This is a set of routines which implement the WIn95 LFN API, } { in Turbo Pascal form. } {==============================================================} { Pascal-string based interface routines } function LFNFindFirst(filespec: PChar; attr: word; var S: TLFNSearchRec): word; { Implement the FindFirst procedure. This routine will call the TP } { FindFirst if LFN is not supported, and will translate the result } { into the TLFNSearchRec variable. } { NOTE: Under Win95, the filespec will be checked against both the } { long and the short filenames, so an additional check may be } { necessary. } var EMode: word; begin {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} Attr:=Attr and not faVolumeID; { required on net drives! } If LFNAble then begin LFindFirst(Filespec,Attr,S); if (DosError=0) and (S.shortname[0]=#0) then strcopy(S.shortname,S.name); end else DosError:=2; LFNFindFirst:=DosError; {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} end; { LFNFindFirst } function LFNFindNext(var S: TLFNSearchRec): word; { Implement the FindNext procedure. This routine will call the TP } { FindNext if LFN is not supported, and will translate the result } { into the TLFNSearchRec variable. } { NOTE: Under Win95, the filespec will be checked against both the } { long and the short filenames, so an additional check may be } { necessary. } begin If LFNAble then begin LFindNext(S); if (DosError=0) and (S.shortname[0]=#0) then strcopy(S.shortname,S.name); end else DosError:=18; LFNFindNext:=DosError; end; { LFNFindNext } function LFNFindClose(var S: TLFNSearchRec): word; { Close the Win95 TLFNSearchRec structure. if LFN is not suppported, } { this routine does nothing. } begin If LFNAble then LFNFindClose:=LFindClose(S) else LFNFindClose:=0; end; {====================================================================} { DERIVATIVE SERVICE ROUTINES. } { This is a set of routines which mimic, as closely as possible, the } { equivalent routines in Turbo Pascal, except that they support } { long filenames. In many cases, they are drop-in replacements, but } { some are new. } {====================================================================} function LFNGetFAttr(var F; var Attr: word): integer; { Get the attributes of a file, using its File variable. } { The file should have been LFNAssign'ed first. Its not } { strictly required, except for error checking. } { Returns the DOS error code. } var EMode: word; begin LFNGetFAttr:=0; DosError:=0; with PLFNFileParam(@F)^ do if (Magic<>LFNMagic) or (not Initialized) then begin DosError:=2; LFNGetFAttr:=DosError; Exit; end; {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} GetFAttr(F,Attr); LFNGetFAttr:=DosError; {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} end; { LFNGetFAttr } function LFNFileExist(fname: PChar): boolean; { Returns TRUE if the file exists, and FALSE otherwise. } var fl: file; attr,i,len,EMode: word; P: PChar; begin {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} LFNFileExist:=(LFNAble and LFileExist(fname)); {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} end; { LFNFileExist } {=========================================================================} { BINARY AND TEXT FILE INPUT/OUTPUT ROUTINES. } { This set of routines is an interface between the LFN API and the Pascal } { style input/output routines. It uses ordinary text and file variables, } { storing special info in the UserData field. The variable is then fully } { compatible with the Pascal read(ln), write(ln), BlockRead, BlockWrite, } { etc input/output routines. } { All the functions return the DOS error code, and also put it into } { DOSERROR. The global "LFNRuntimeError" determines if runtime errors } { will be generated (by default, no.) } {=========================================================================} procedure LFNNew(var F; IsText: boolean); { This routine prepares a text or file variable for LFN use. It allocates } { memory for the long name, and initializes the entries in the UserData. } { It must be called before any other. } { The "IsText" flag tells if the variable is of type "file" or "text". } begin with PLFNFileParam(@F)^ do begin TextFile:=IsText; Initialized:=false; Magic:=LFNMagic; lfname:=Nil; plfname:=Nil; GetMem(lfname,261); FillChar(lfname^,261,#0); plfname:=PChar(@PByteArray(lfname)^[1]); end; end; { LFNNew } function LFNAssign(var F; name: PChar): integer; { This routine replaces the Pascal "Assign" routine. For existing files, } { it first determines the short name, and then invokes "Assign". If the } { file does not exist, it only stores the information in the UserData } { fields, since the equivalent short name is not known. The assign } { operation is then deferred to the first "LFNRewrite" call. } { LFNAssign may be called for the same variable for different filenames, } { so long as the type (file or text) is the same. } var tmp: PString; IsText: boolean; P,fname,sname: PChar; EMode: Word; begin if PLFNFileParam(@F)^.Magic<>LFNMagic then begin DosError:=LFNErr_NotAllocated; LFNAssign:=DosError; Exit; end; {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} DosError:=0; LFNAssign:=DosError; fname:=StrNew(name); with PLFNFileParam(@F)^ do begin if LFNFileExist(fname) and (LGetShortName(name,fname)=0) then Initialized:=true; if Initialized then begin IsText:=TextFile; tmp:=lfname; P:=plfname; if IsText then Assign(text(F),fname) else assign(file(F),fname); Initialized:=True; TextFile:=IsText; lfname:=tmp; plfname:=P; Magic:=LFNMagic; end; plfname:=name; end; StrDispose(fname); {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} if PLFNFileParam(@F)^.Initialized then LFNAssign:=DosError else LFNAssign:=LFNErr_Uninitialized; end; { LFNAssign } function Err(e: byte): byte; begin DosError:=e; Err:=e; if LFNRuntimeErrors and (e<>0) then RunError(e); end; function LFNRewrite(var F; RecLen: word): integer; { This routine readies a file for output. If the file does not yet exist, } { it creates an empty file to get the system-determined short name, and } { performs a deferred Assign, since at Assign time a short name was not } { yet available (see description of LFNAssign). } { The routine returns 0 if successful, and the DOS errorcode if not. } var tmp: PString; IsText: boolean; P,fname: PChar; EMode: Word; begin LFNRewrite:=Err(0); if PLFNFileParam(@F)^.Magic<>LFNMagic then begin Err(LFNErr_NotAllocated); Exit; end; {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} with PLFNFileParam(@F)^ do begin if not Initialized then { create the file, so we can get a valid short name } if Err(LCreateEmpty(plfname))=0 then LFNAssign(F,plfname); if Initialized then begin {$I-} if TextFile then Rewrite(text(F)) else if RecLen=0 then Rewrite(file(F)) else Rewrite(file(F),RecLen); Err(IoResult); {$I+} end else LFNRewrite:=DosError; end; {$IFDEF WINDOWS} SetErrorMode(Emode); {$ENDIF} end; { LFNRewrite } function LFNAppend(var F; RecLen: word): integer; { This routines opens a previously LFNAssigned for output at the EOF. } { Its not really necessary, except that it performs additional error } { checking to make sure that the file was properly initialized. } { Also, in contrast to the TP Append, if the file does not exist the } { routine calls LFNRewrite to create and open it. } { The routine returns 0 if successful, and the DOS errorcode if not. } var EMode: Word; begin LFNAppend:=Err(0); if PLFNFileParam(@F)^.Magic<>LFNMagic then begin Err(LFNErr_NotAllocated); Exit; end; with PLFNFileParam(@F)^ do begin if Magic<>LFNMagic then begin Err(LFNErr_NotAllocated); Exit; end else if not TextFile then begin Err(LFNErr_NotATextFile); Exit; end else if not Initialized then Err(LFNRewrite(F,RecLen)) else begin {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} {$I-} Append(text(F)); Err(IoResult); {$I+} {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} end; end; end; { LFNAppend } function LFNReset(var F; RecLen: word): integer; { This routines opens a file for input, instead of "reset". Its not really } { necessary, except that it performs additional error checking to make } { sure that the file was properly initialized. } { The routine returns 0 if successful, and the DOS errorcode if not. } begin LFNReset:=Err(0); if PLFNFileParam(@F)^.Magic<>LFNMagic then begin Err(LFNErr_NotAllocated); Exit; end; with PLFNFileParam(@F)^ do begin if not Initialized then LFNReset:=LFNErr_UnInitialized else begin {$I-} if TextFile then Reset(text(F)) else if RecLen=0 then Reset(file(F)) else Reset(file(F),RecLen); Err(IoResult); {$I+} end; end; end; { LFNReset } function LFNErase(var F): integer; { This routines erases a previously LFNAssigned, but not opened, file. } { Its not really necessary, except that it performs additional error } { checking to make sure that the file was properly initialized. Also, } { it re-assignes the file so it will be properly ready for a rewrite. } { The routine returns 0 if successful, and the DOS errorcode if not. } begin with PLFNFileParam(@F)^ do begin LFNErase:=0; if (Magic<>LFNMagic) then begin Err(LFNErr_NotAllocated); Exit; end else if not Initialized then begin Err(LFNErr_UnInitialized); Exit; end; LFNClose(F); {$I-} if TextFile then Erase(text(F)) else Erase(file(F)); {$I+} if Err(IoResult)=0 then LFNAssign(F,plfname) end; end; { LFNErase } function LFNClose(var F): integer; { This routines closes a previously LFNAssigned and opened file. } { Its not really necessary, except that it performs additional error } { checking to make sure that the file was properly initialized. } { The routine returns 0 if successful, and the DOS errorcode if not. } begin LFNClose:=Err(0); with PLFNFileParam(@F)^ do begin if Magic<>LFNMagic then begin Err(LFNErr_NotAllocated); Exit; end else if not Initialized then begin Err(LFNErr_UnInitialized); Exit; end; {$I-} if TextFile then close(text(F)) else close(file(F)); {$I+} Err(IoResult); end; end; { LFNClose } procedure LFNDispose(var F); { This routine disposes of the additional memory allocated by LFNNew, } { and cleans up the UserData fields. If the file is open, it also } { closes it, so that there is no need to call LFNClose previously. } begin with PLFNFileParam(@F)^ do begin if (Magic<>LFNMagic) or (not Initialized) then Exit; if lfname<>Nil then FreeMem(lfname,261); lfname:=Nil; plfname:=Nil; Initialized:=false; Magic:=''; end; end; { LFNDispose } function LFNRename(var F; NewName: PChar): integer; { This routines renames a previously LFNAssigned, but not opened, file. } { The file variable is then re-assigned to the new name. } { The routine returns 0 if successful, and the DOS errorcode if not. } var i,len: integer; EMode: Word; begin LFNRename:=Err(0); if NewName=nil then Exit; with PLFNFileParam(@F)^ do begin if Magic<>LFNMagic then begin LFNRename:=Err(LFNErr_NotAllocated); Exit; end else if not Initialized then begin LFNRename:=Err(LFNErr_UnInitialized); Exit; end; {$IFDEF WINDOWS} EMode:=SetErrorMode(SEM_FailCriticalErrors or SEM_NoOpenFileErrorBox); {$ENDIF} if Err(LRenameFile(plfname,NewName))=0 then LFNAssign(F,NewName); {$IFDEF WINDOWS} SetErrorMode(EMode); {$ENDIF} end; end; { LFNRename } begin LFNAble:=SupportsLFN; end.
unit URegisterInfoIO; interface uses classes,SysUtils, inifiles, Registry, Math, ShlObj, UMyUtil, Windows, Forms; type {$Region ' 读/写 本地信息 父类 '} ReadAppDataUtil = class public class function getAppDataPath : string; end; TLocalInfoHandle = class protected RegKey : string; AppKey : string; public AppDataKey : string; RegistryKey : string; public constructor Create( _RegKey, _AppKey : string ); end; // 读取信息 父类 TReadLocalInfo = class( TLocalInfoHandle ) public procedure ReadKey; private procedure ReadAppDataKey; procedure ReadRegistryKey; function Decode( EncodeKey : string ):string; end; // 写入信息 父类 TWriteLocalInfo = class( TLocalInfoHandle ) public procedure WriteKey; private function Encode( DecodeKey : string ): string; procedure WriteAppDataKey; procedure WriteRegistryKey; end; {$EndRegion} {$Region ' 读/写 系统运行时间 '} // 读取 系统运行时间 TReadAppRunTime = class( TReadLocalInfo ) public constructor Create; function get : Int64; end; // 写入 系统运行时间 TWriteAppRunTime = class( TWriteLocalInfo ) private RunTime : Int64; public constructor Create( _RunTime : Int64 ); procedure Update; end; {$EndRegion} {$Region ' 读/写 系统激活时间 ' } // 读取 系统激活时间 TReadAppStartTime = class( TReadLocalInfo ) public constructor Create; function get : TDateTime; end; // 写入 系统激活时间 TWriteAppStartTime = class( TWriteLocalInfo ) private StartTime : TDateTime; public constructor Create( _StartTime : TDateTime ); procedure Update; end; {$EndRegion} {$Region ' 读/写 网络时间 ' } // 读取 网络时间 TReadWebTime = class( TReadLocalInfo ) public constructor Create; function get : TDateTime; end; // 写入 网络时间 TWriteWebTime = class( TWriteLocalInfo ) private WebTime : TDateTime; public constructor Create( _WebTime : TDateTime ); procedure Update; end; {$EndRegion} {$Region ' 读/写 本地注册时间 ' } // 读取 网络时间 TReadLocalTrial = class( TReadLocalInfo ) public constructor Create; function get : TDateTime; function getIsWrite : Boolean; end; // 写入 网络时间 TWriteLocalTrial = class( TWriteLocalInfo ) private LocalTrial : TDateTime; public constructor Create( _LocalTrial : TDateTime ); procedure Update; end; {$EndRegion} {$Region ' 写 程序开机自动运行 ' } // 开机自动运行 RunAppStartupUtil = class public class procedure Startup( IsRun : Boolean ); end; {$EndRegion} var RegKey_Root : string = '\Software\BackupCow'; const RegKey_StartTime : string = 'BackupFiles'; RegKey_RunTime : string = 'BackupFolders'; RegKey_WebTime : string = 'BackupPaths'; RegKey_LocalTrial : string = 'BackupCopys'; AppData_BackupCow : string = 'BackupCowData.dat'; AppData_SectionName : string = 'BackupData'; AppData_StartTime : string = 'BackupFiles'; AppData_RunTime : string = 'BackupFolders'; AppData_WebTime : string = 'BackupPaths'; AppData_LocalTrial : string = 'BackupCopys'; RegKeyPath_AppRun = '\SOFTWARE\Microsoft\windows\CurrentVersion\Run'; implementation { TWriteAppRunTime } constructor TWriteAppRunTime.Create(_RunTime: Int64); begin inherited Create( RegKey_RunTime, AppData_RunTime ); RunTime := _RunTime; end; procedure TWriteAppRunTime.Update; begin RegistryKey := IntToStr( RunTime ); AppDataKey := IntToStr( RunTime ); WriteKey; end; { TReadAppRunTime } constructor TReadAppRunTime.Create; begin inherited Create( RegKey_RunTime, AppData_RunTime ); end; function TReadAppRunTime.get: Int64; var RegTime, AppTime, MaxTime : Int64; begin ReadKey; RegTime := StrToInt64Def( RegistryKey, 0 ); AppTime := StrToInt64Def( AppDataKey, 0 ); MaxTime := max( RegTime, AppTime ); Result := max( 0, MaxTime ); end; { TReadLocalInfo } function TReadLocalInfo.Decode(EncodeKey: string): string; begin Result := MyEncrypt.DecodeStr( EncodeKey ); end; procedure TReadLocalInfo.ReadAppDataKey; var AppIni : TIniFile; AppDataPath : string; begin AppDataKey := ''; AppDataPath := ReadAppDataUtil.getAppDataPath; if FileExists( AppDataPath ) then begin AppIni := TIniFile.Create( AppDataPath ); AppDataKey := AppIni.ReadString( AppData_SectionName, AppKey, '' ); AppDataKey := Decode( AppDataKey ); AppIni.Free; end; end; procedure TReadLocalInfo.ReadKey; begin ReadAppDataKey; ReadRegistryKey; end; procedure TReadLocalInfo.ReadRegistryKey; var Reg : TRegistry; begin RegistryKey := ''; Reg := TRegistry.Create; if Reg.OpenKey( RegKey_Root, False ) then begin RegistryKey := Reg.ReadString( RegKey ); if RegistryKey <> '' then RegistryKey := Decode( RegistryKey ); Reg.CloseKey; end; Reg.Free; end; { TLocalInfoHandle } constructor TLocalInfoHandle.Create(_RegKey, _AppKey: string); begin RegKey := _RegKey; AppKey := _AppKey; end; { TWriteLocalInfo } function TWriteLocalInfo.Encode(DecodeKey: string): string; begin Result := MyEncrypt.EncodeStr( DecodeKey ); end; procedure TWriteLocalInfo.WriteAppDataKey; var AppIni : TIniFile; AppDataPath : string; begin AppDataKey := Encode( AppDataKey ); AppDataPath := ReadAppDataUtil.getAppDataPath; ForceDirectories( ExtractFileDir( AppDataPath ) ); AppIni := TIniFile.Create( AppDataPath ); AppIni.WriteString( AppData_SectionName, AppKey, AppDataKey ); AppIni.Free; MyHideFile.Hide( AppDataPath ); end; procedure TWriteLocalInfo.WriteKey; begin WriteRegistryKey; WriteAppDataKey; end; procedure TWriteLocalInfo.WriteRegistryKey; var Reg : TRegistry; begin RegistryKey := Encode( RegistryKey ); Reg := TRegistry.Create; if Reg.OpenKey( RegKey_Root, True ) then begin Reg.WriteString( RegKey, RegistryKey ); Reg.CloseKey; end; Reg.Free; end; { TReadAppStartTime } constructor TReadAppStartTime.Create; begin inherited Create( RegKey_StartTime, AppData_StartTime ); end; function TReadAppStartTime.get: TDateTime; var RegStartTime, AppDataStartTime, MinTime : TDateTime; begin ReadKey; RegStartTime := StrToFloatDef( RegistryKey, Now ); AppDataStartTime := StrToFloatDef( RegistryKey, Now ); Result := Min( RegStartTime, AppDataStartTime ); end; { TWriteAppStartTime } constructor TWriteAppStartTime.Create(_StartTime: TDateTime); begin inherited Create( RegKey_StartTime, AppData_StartTime ); StartTime := _StartTime; end; procedure TWriteAppStartTime.Update; begin RegistryKey := FloatToStr( StartTime ); AppDataKey := FloatToStr( StartTime ); WriteKey; end; { ReadAppDataUtil } class function ReadAppDataUtil.getAppDataPath: string; begin Result := MyAppDataPath.get + AppData_BackupCow; end; { TReadWebTime } constructor TReadWebTime.Create; begin inherited Create( RegKey_WebTime, AppData_WebTime ); end; function TReadWebTime.get: TDateTime; var RegWebTime, AppDataWebTime, MinTime : TDateTime; begin ReadKey; RegWebTime := StrToFloatDef( RegistryKey, Now ); AppDataWebTime := StrToFloatDef( AppDataKey, Now ); Result := Max( RegWebTime, AppDataWebTime ); end; { TWriteWebTime } constructor TWriteWebTime.Create(_WebTime: TDateTime); begin inherited Create( RegKey_WebTime, AppData_WebTime ); WebTime := _WebTime; end; procedure TWriteWebTime.Update; begin RegistryKey := FloatToStr( WebTime ); AppDataKey := FloatToStr( WebTime ); WriteKey; end; { TReadLocalTrial } constructor TReadLocalTrial.Create; begin inherited Create( RegKey_LocalTrial, AppData_LocalTrial ); end; function TReadLocalTrial.get: TDateTime; var RegLocalTrial, AppDataLocalTrial, MinTime : TDateTime; begin ReadKey; RegLocalTrial := StrToFloatDef( RegistryKey, Now ); AppDataLocalTrial := StrToFloatDef( AppDataKey, Now ); Result := Min( RegLocalTrial, AppDataLocalTrial ); end; function TReadLocalTrial.getIsWrite: Boolean; begin ReadKey; Result := ( RegistryKey <> '' ) or ( AppDataKey <> '' ); end; { TWriteLocalTrial } constructor TWriteLocalTrial.Create(_LocalTrial: TDateTime); begin inherited Create( RegKey_LocalTrial, AppData_LocalTrial ); LocalTrial := _LocalTrial; end; procedure TWriteLocalTrial.Update; begin RegistryKey := FloatToStr( LocalTrial ); AppDataKey := FloatToStr( LocalTrial ); WriteKey; end; { RunAppStartupUtil } //开机自动启动 class procedure RunAppStartupUtil.Startup(IsRun: Boolean); var Reg:TRegistry; AppName : string; begin AppName := ExtractFileName( Application.Exename ); AppName := Copy( AppName, 1, Pos('.', AppName) - 1 ); Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey( RegKeyPath_AppRun, True); if IsRun then Reg.writeString( AppName, Application.Exename + ' h') else Reg.DeleteValue( AppName ); Reg.CloseKey; Reg.Free; end; end.
unit Plus.Vcl.PageControlFactory; interface uses System.Classes, Vcl.ComCtrls, Vcl.Forms; type TPageControlFactory = class (TComponent) private FPageControl: TPageControl; procedure SetPageControl(const aPageControl: TPageControl); public procedure AddNewFrame<T: TFrame> (const Caption: string); property PageControl: TPageControl read FPageControl write SetPageControl; end; implementation uses System.SysUtils, Vcl.Controls; { TPageControlFactory } procedure TPageControlFactory.AddNewFrame<T>(const Caption: string); var TabSheet: TTabSheet; AFrame: TFrame; begin if FPageControl=nil then raise Exception.Create('Required PageControl component') else begin TabSheet := TTabSheet.Create(PageControl); TabSheet.Caption := Caption; TabSheet.PageControl := PageControl; PageControl.ActivePage := TabSheet; AFrame := T.Create(TabSheet); AFrame.Parent := TabSheet; AFrame.Align := alClient; end; end; procedure TPageControlFactory.SetPageControl(const aPageControl: TPageControl); begin FPageControl := aPageControl; end; end.
program SelectionSort; {$MODE OBJFPC} const arraySize = 10000; const RandomRange = 1000000; Type IntArray = array [1..arraySize] of integer; var arrayToSort: IntArray; numSwaps, numComparisons: Int64; procedure printArray(var anArray: IntArray); var i : integer; begin for i := Low(anArray) to High(anArray) do begin write(anArray[i] : 7); if i mod 10 = 0 then writeln; end; end; procedure initializeArray(var anArray: IntArray); var i : integer; begin for i := Low(anArray) to High(anArray) do anArray[i] := Random(RandomRange); end; procedure swap(var x, y: integer; var numSwaps : Int64); var tmp: integer; begin numSwaps := numSwaps + 1; tmp := x; x := y; y := tmp; end; function compare(x : Integer; y: Integer; var numComparisons: Int64): Boolean; begin numComparisons := numComparisons + 1; compare := x > y; end; procedure sort(var anArray: IntArray; var numSwaps: Int64; var numComparisons: Int64); var i, j, minIndex, tmp : Integer; begin numSwaps := 0; numComparisons := 0; {* main loop over array *} {* as calculation progression elements with index less than i *} {* will be parted of the sortted section. *} for i := Low(anArray) to High(AnArray) - 1 do begin {* find min for unsortted section *} minIndex := i; for j := i + 1 to High(anArray) do begin numComparisons := numComparisons + 1; if compare(anArray[minIndex], anArray[j], numComparisons) then minIndex := j; end; {* swap if necessary *} if minIndex <> i then begin swap(anArray[i], anArray[minIndex], numSwaps); end; end end; begin Randomize; initializeArray(arrayToSort); writeln('Array Before Sort'); printArray(arrayToSort); writeln; writeln('Array After Sort'); sort(arrayToSort, numSwaps, numComparisons); printArray(arrayToSort); writeln('Number of Swaps: ', numSwaps, ', Number of Comparisons: ', numComparisons); end.
{ Subroutine STRING_PROMPT (S) * * Write the string S to standard output without a newline following. This * may be useful when prompting the user for interactive input. } module string_prompt; define string_prompt; %include 'string2.ins.pas'; %include 'string_sys.ins.pas'; procedure string_prompt ( {string to standard output without newline} in s: univ string_var_arg_t); {prompt string to write} begin write (s.str:s.len); {write prompt to buffer} sys_sys_flush (sys_sys_iounit_stdout_k); {force-write any buffered data} end;
unit Unit_Form; interface uses Unit_Cypher, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtDlgs, Vcl.Menus, Vcl.ToolWin, Vcl.ComCtrls; type TForm1 = class(TForm) btnEnter: TButton; edtValue: TEdit; btnCypher: TButton; btnDecypher: TButton; procedure btnEnterClick(Sender: TObject); procedure edtValueKeyPress(Sender: TObject; var Key: Char); procedure btnCypherClick(Sender: TObject); procedure btnDecypherClick(Sender: TObject); procedure BtnZeroAddClick(Sender: TObject); end; const CInputFile = 'input.txt'; CCypheredFile = 'Cyphered.txt'; CDecypherFile = 'Decyphered.txt'; CCryptFile = 'MainCrypt'; CMaxLenVal = 45; CBinarySet = ['0'..'1']; var Form1: TForm1; InputText, CypherText, DecypherText: text; CryptFile: file of byte; LFSR1, LFSR2, LFSR3: TLFSR; LengthInit1, LengthInit2, LengthInit3: integer; InitValue1, InitValue2, InitValue3: TValue; BitsToCalc1, BitsToCalc2, BitsToCalc3 : TBitsToCalc; KeyByte: byte; Line: Ansistring; LineBits: array of byte absolute Line; implementation {$R *.dfm} procedure GenKeyByte(var KeyByte: byte); var i: integer; begin KeyByte := 0; // Byte size = 8 for i := 1 to 8 do begin KeyByte := KeyByte * 2; Inc(KeyByte, Calculate(LFSR1.LastDigit, LFSR2.LastDigit, LFSR3.LastDigit)); LFSR1.Roll; LFSR2.Roll; LFSR3.Roll; end; end; procedure renewLSFR; begin LFSR1.Value := Copy(InitValue1); LFSR1.LastDigit := InitValue1[0]; LFSR2.Value := Copy(InitValue2); LFSR2.LastDigit := InitValue2[0]; LFSR3.Value := Copy(InitValue3); LFSR3.LastDigit := InitValue3[0]; end; procedure Ciph(const InputFile, OutputFile: string); var InputText, OutputText: text; i: integer; begin AssignFile(InputText, InputFile); AssignFile(OutputText, OutputFile); Reset(InputText); Rewrite(OutputText); Rewrite(CryptFile); while not EOF(InputText) do begin Line := ''; Readln(InputText, Line); for i := 0 to High(LineBits) do if LineBits[i] <> 0 then begin GenKeyByte(KeyByte); LineBits[i] := LineBits[i] xor KeyByte; end; for i := 0 to High(LineBits) do begin write(OutputText, AnsiChar(LineBits[i])); write(CryptFile, LineBits[i]); end; // Add new line GenKeyByte(KeyByte); KeyByte := KeyByte xor 13; write(CryptFile, KeyByte); GenKeyByte(KeyByte); KeyByte := KeyByte xor 10; write(CryptFile, KeyByte); writeln(OutputText); end; Line := ''; CloseFile(CryptFile); CloseFile(OutputText); CloseFile(InputText); end; procedure Deciph(const OutputFile: string); var OutputText: text; CurrentByte: byte; begin AssignFile(OutputText, OutputFile); Rewrite(OutputText); Reset(CryptFile); while not EOF(CryptFile) do begin read(CryptFile, CurrentByte); GenKeyByte(KeyByte); CurrentByte := CurrentByte xor KeyByte; write(OutputText, AnsiChar(CurrentByte)); end; CloseFile(CryptFile); CloseFile(OutputText); end; procedure TForm1.btnDecypherClick(Sender: TObject); begin renewLSFR; Deciph(CDecypherFile); MessageBox(handle, PChar('Дешифрованный текст: ' + CDecypherFile), PChar('Успешно'), (MB_OK)); end; procedure TForm1.btnCypherClick(Sender: TObject); begin renewLSFR; Ciph(CInputFile, CCypheredFile); MessageBox(handle, PChar('Зашифрованный текст: ' + CCypheredFile), PChar('Успешно'), (MB_OK)); end; procedure TForm1.btnEnterClick(Sender: TObject); var i: integer; begin if InitValue1 = nil then begin if (length(edtValue.text) = LengthInit1) and (AnsiPos('1', edtValue.text) <> 0) then begin SetLength(InitValue1, LengthInit1); for i := 0 to LengthInit1 - 1 do InitValue1[i] := StrToInt(edtValue.text[i + 1]); edtValue.text := ''; LFSR1 := TLFSR.Create(InitValue1, BitsToCalc1); btnEnter.Caption := 'Введите 2-ое значение'; end else MessageBox(handle, PChar('Длина для первого значения должна быть равна ' + IntToStr(LengthInit1) + '. Значение должно быть <> 0.'), PChar('Некорректные данные.'), (MB_ICONWARNING + MB_OK)); end else if InitValue2 = nil then begin if (length(edtValue.text) = LengthInit2) and (AnsiPos('1', edtValue.text) <> 0) then begin SetLength(InitValue2, LengthInit2); for i := 0 to LengthInit2 - 1 do InitValue2[i] := StrToInt(edtValue.text[i + 1]); edtValue.text := ''; LFSR2 := TLFSR.Create(InitValue2, BitsToCalc2); btnEnter.Caption := 'Введите 3 значение'; end else MessageBox(handle, PChar('Длина для второго значения должна быть равна ' + IntToStr(LengthInit2) + '. Значение должно быть <> 0.'), PChar('Некорректные данные.'), (MB_ICONWARNING + MB_OK)); end else if InitValue3 = nil then begin if (length(edtValue.text) = LengthInit3) and (AnsiPos('1', edtValue.text) <> 0) then begin SetLength(InitValue3, LengthInit3); for i := 0 to LengthInit3 - 1 do InitValue3[i] := StrToInt(edtValue.text[i + 1]); edtValue.text := ''; LFSR3 := TLFSR.Create(InitValue3, BitsToCalc3); edtValue.Enabled := False; btnEnter.Caption := 'Значения введены'; btnEnter.Enabled := False; btnCypher.Enabled := True; btnDecypher.Enabled := True; end else MessageBox(handle, PChar('Длина для третьего значения должна быть равна ' + IntToStr(LengthInit3) + '. Значение должно быть <> 0.'), PChar('Некорректные данные.'), (MB_ICONWARNING + MB_OK)); end end; procedure TForm1.BtnZeroAddClick(Sender: TObject); var Key: Char; begin Key := '0'; edtValueKeyPress(Sender, Key); end; procedure TForm1.edtValueKeyPress(Sender: TObject; var Key: Char); begin if (not(Key in CBinarySet) or (length(edtValue.text) > CMaxLenVal)) and (Key <> #8) then Key := #0; if InitValue1 = nil then begin if (length(edtValue.text) >= LengthInit1) and (Key <> #8) then Key := #0 end else if InitValue2 = nil then begin if (length(edtValue.text) >= LengthInit2) and (Key <> #8) then Key := #0 end else if InitValue3 = nil then begin if (length(edtValue.text) >= LengthInit3) and (Key <> #8) then Key := #0 end end; initialization begin LengthInit1 := 30; LengthInit2 := 42; LengthInit3 := 37; AssignFile(CryptFile, CCryptFile); SetLength(BitsToCalc1, 2); BitsToCalc1[0] := 10; BitsToCalc1[1] := 22; // (10, 22); SetLength(BitsToCalc2, 2); BitsToCalc2[0] := 14; BitsToCalc2[1] := 24; // (14, 24); SetLength(BitsToCalc3, 2); BitsToCalc3[0] := 7; BitsToCalc3[1] := 31; // (7, 31); end; end.