text
stringlengths
14
6.51M
{$include kode.inc} unit midi_transpose; { untested -1 clearing of buffer... } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_const, kode_types, kode_plugin, kode_parameter; type myPlugin = class(KPlugin) private FTranspose : LongInt; FNoteBuffer : array[0..255{127}] of LongInt; procedure noteOn(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); procedure noteOff(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); public procedure on_create; override; procedure on_parameterChange(AIndex:LongWord; AValue:Single); override; procedure on_midiEvent(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); override; procedure on_processSample(AInputs, AOutputs: PPSingle); override; end; KPluginClass = myPlugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, kode_flags, //kode_memory, kode_utils; //-------------------------------------------------- procedure myPlugin.on_create; var i : longint; begin FName := 'midi_transpose'; FAuthor := 'skei.audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + midi_transpose_id; KSetFlag(FFlags, kpf_perSample + kpf_receiveMidi + kpf_sendMidi ); appendParameter( KParamInt.create('transpose', 0, -24, 24 ) ); // //ZMemset(@FNoteBuffer[0],128,0); for i := 0 to 255 do FNoteBuffer[i] := -1; FTranspose := 0; end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); var i : longint; //p : ZParameter; v : single; begin i := AIndex; //p := FParameters[i]; v := AValue;//p.from01(AValue); case i of 0: FTranspose := trunc(v); end; end; //---------- // [internal] procedure myPlugin.noteOn(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); var note : Byte; begin note := (AMsg2 + FTranspose) and $7F; FNoteBuffer[AMsg2] := note; midiOut(AOffset,AMsg1,note,AMsg3); end; //---------- // [internal] procedure myPlugin.noteOff(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); var note : longint; begin note := FNoteBuffer[AMsg2]; if note <> -1 then midiOut(AOffset,AMsg1,note,AMsg3) else midiOut(AOffset,AMsg1,AMsg2,AMsg3); FNoteBuffer[AMsg2] := -1; end; //---------- procedure myPlugin.on_midiEvent(AOffset:LongWord; AMsg1,AMsg2,AMsg3:Byte); begin case (AMsg1 and $F0) of $80: noteOff(AOffset,AMsg1,AMsg2,AMsg3); $90: if AMsg3 = 0 then noteOff(AOffset,AMsg1,AMsg2,AMsg3) else noteOn(AOffset,AMsg1,AMsg2,AMsg3) else midiOut(AOffset,AMsg1,AMsg2,AMsg3); end; end; //---------- procedure myPlugin.on_processSample(AInputs,AOutputs: PPSingle); begin AOutputs[0]^ := AInputs[0]^; AOutputs[1]^ := AInputs[1]^; end; //---------------------------------------------------------------------- end. { // http://www.somascape.org/midi/tech/spec.html 80 Note Off, note, velocity 90 Note On, note, velocity A0 AfterTouch (ie, key pressure), note, pressure B0 Control Change, num, val C0 Program (patch) change, num D0 Channel Pressure, pressure E0 Pitch Wheel, low7bits, high7bits (0x2000=center) F0 Start sysex, vendor-id, ..., [until Sysex End] F1 MTC Quarter Frame, time code value F2 Song Position, 2 bytes (like pitchwheel) = Midi Beats (see below) F3 Song Select, num F4 F5 [unofficial bus select, bus-number] F6 Tune Request F7 Sysex End F8 Midi Clock F9 [Tick (every 10 ms)] FA Midi Start FB Midi Continue FC Midi Stop FD FE Active Sense (approximately every 300 ms) FF Reset Midi Meats - Songs are always assumed to start on a MIDI Beat of 0. - Each MIDI Beat spans 6 MIDI Clocks. - In other words, each MIDI Beat is a 16th note (since there are 24 MIDI Clocks in a quarter note). Midi Clock There are 24 MIDI Clocks in every quarter note. (12 MIDI Clocks in an eighth note, 6 MIDI Clocks in a 16th, etc). Therefore, when a slave device counts down the receipt of 24 MIDI Clock messages, it knows that one quarter note has passed. When the slave counts off another 24 MIDI Clock messages, it knows that another quarter note has passed. Etc Tick While a master device's "clock" is playing back, it will send a continuous stream of MIDI Tick events at a rate of one per every 10 milliseconds. }
unit Classe.Email; interface uses System.sysUtils,System.classes,IdBaseComponent, IdMessage, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP,idReplySmtp, IDMessageParts, IDEmailAddress,IDAttachmentFile,IdAntiFreezeBase, IdAntiFreeze; type TEmail = class private procedure onWorkSMTP(ASender: TObject;AWorkMode: TWorkMode; AWorkCount: int64); public class function Enviar(const pUser,pSenha,pDestinatario,pAssunto: string; const pBody: TStrings = nil;pAttach: TStrings = nil): String; end; implementation uses Vcl.Forms; { TEmail } class function TEmail.Enviar(const pUser, pSenha, pDestinatario, pAssunto: string; const pBody: TStrings; pAttach: TStrings): String; var lSMTP: TIdSmtp; lAtt: TIdAttachmentFile; lMessage: TIdMessage; lSSL: TIdSSLIOHandlerSocketOpenSSL; lArq: String; lAntiFreeze: TIdAntiFreeze; begin if pSenha = '' then begin Exit('Senha não informada'); end; //Definindo a senha if pDestinatario = '' then begin Exit('Destinatario ao informado.'); end; if lSMTP.Username = '' then begin Exit('Usuario não informado'); end; lSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); lMessage := TIdMessage.Create(nil); lSMTP := TIdSMTP.Create(nil); lAntiFreeze := TIdAntiFreeze.Create(nil); try lSMTP.IOHandler := lSSL; lSMTP.Host := 'smtp.gmail.com'; lSMTP.Port := 587; lSMTP.UseTLS := utUseExplicitTLS; lSMTP.Username := pUser; lSMTP.Password := pSenha; lSSL.Destination := 'smtp.gmail.com:587'; lSSL.Host := 'smtp.gmail.com'; lSSL.Port := 587; lSSL.SSLOptions.Mode := sslmUnassigned; lSSL.SSLOptions.VerifyMode := []; lSSL.SSLOptions.VerifyDepth := 0; lSMTP.Connect; try //obrigatorio lMessage.From.Address := lSMTP.Username; lMessage.Recipients.EMailAddresses := pDestinatario; lMessage.Subject := pAssunto; if Assigned(pBody) then begin lMessage.Body.Text := pBody.Text; end; if Assigned(pAttach) then begin for lArq in pAttach do begin lAtt := TIdAttachmentFile.Create(lMessage.MessageParts,lArq); end; end; try lSMTP.Send(lMessage); except on E: EIdSmtpReplyError do begin raise Exception.Create('Desativar config no Gmail '+sLineBreak + E.message); end else raise Exception.Create('Erro desconhecido'); end; finally lSMTP.Disconnect; if Assigned(pAttach) then begin lAtt.Free; end; end; finally lSMTP.free; lAntiFreeze.free; lSSL.free; lMessage.free; end; end; procedure TEmail.onWorkSMTP(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: int64); begin Application.ProcessMessages; end; end.
//Useful functions and test codes on pascal(Delphi) //made by MCH //ver 1.0 unit DUsfUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Printers, PrintUtils; type TDynArrChar = array of Char; //동적 배열을 매개변수로 전달 시 사용 TIndexList = class(TStringList) public //function indexOf( ///<summary> TStringList Type으로 indexex 리턴 </summary> function indexOfList(sKey :String) :TStringList; overload; end; ///<summary>알파벳 타입 시퀀스 가져오기 eg.)A,B ... AA,AB,AC..</summary> function getNextSeqAlpha(pCharArr :TDynArrChar) :TDynArrChar; ///<summary>프린터 용지 설정 가져오기</summary> function getPaperSize() :Integer; ///<summary>프린터 용지 설정하기</summary> /// <param name="pSize"> /// DMPAPER_A3 = 8; { A3 297 x 420 mm } /// DMPAPER_A4 = 9; { A4 210 x 297 mm } /// DMPAPER_A4SMALL = 10; { A4 Small 210 x 297 mm } /// DMPAPER_A5 = 11; { A5 148 x 210 mm } /// DMPAPER_B4 = 12; { B4 (JIS) 250 x 354 } /// DMPAPER_B5 = 13; { B5 (JIS) 182 x 257 mm } /// </param> procedure setPaperSize(pSize :Integer); function getPrinterInfo() :TStringList; function RightStr(const Str: String; Size: Word): String; function LeftStr(const Str: String; Size: Word): String; function MidStr(Const Str: String; Size: Word): String; implementation function RightStr(const Str: String; Size: Word): String; var len: Byte; begin len := Length(Str); if Size > len then Size := len; RightStr := Copy(Str,len-Size+1,Size) end; function LeftStr(const Str: String; Size: Word): String; begin LeftStr := Copy(Str,1,Size) end; function MidStr(Const Str: String; Size: Word): String; var len: Byte; begin len := Length(Str); if Size > len then Size := len; MidStr := Copy(Str,((len - Size) div 2)+1,Size) end; function getNextSeqAlpha(pCharArr :TDynArrChar) :TDynArrChar; var i :Integer; isIncLength :Boolean; begin isIncLength := False; for i := Length(pCharArr)-2 downto 0 do begin if UpperCase(pCharArr[i]) = 'Z' then begin pCharArr[i] := 'A'; isIncLength := True; Continue; end; isIncLength := False; pCharArr[i] := Char(Integer(pCharArr[i])+1); break; end; if isIncLength then //자리수 증가해야 하는 경우 begin i := Length(pCharArr); SetLength(pCharArr, i+1); pCharArr[i-1] := 'A'; end; result := pCharArr; end; function getPaperSize() :Integer; var ADevMode :PDevMode; hDMode :THandle; Device, Driver, Port :array[0..255] of Char; begin Printer.GetPrinter(Device, Driver, Port, hDMode); ADevMode := GlobalLock(hDMode); GlobalUnlock(hDMode); result := ADevMode.dmPaperSize; end; procedure setPaperSize(pSize :Integer); var ADevMode :PDevMode; hDMode :THandle; Device, Driver, Port :array[0..255] of Char; begin Printer.GetPrinter(Device, Driver, Port, hDMode); ADevMode := GlobalLock(hDMode); ADevMode.dmPaperSize := pSize; GlobalLock(hDMode); Printer.SetPrinter(Device, Driver, Port, hDMode); end; function getPrinterInfo() :TStringList; var ADevMode :PDevMode; hDMode :THandle; Device, Driver, Port :array[0..255] of Char; slStrList :TStringList; begin Printer.GetPrinter(Device, Driver, Port, hDMode); ADevMode := GlobalLock(hDMode); GlobalUnlock(hDMode); slStrList := TStringList.Create; slStrList.Add(IntToStr(ADevMode.dmPaperSize)); slStrList.Add(IntToStr(ADevMode.dmTTOption)); slStrList.Add(ADevMode.dmDeviceName); result := slStrList; end; { TIndexList } function TIndexList.indexOfList(sKey: String): TStringList; var i :Integer; begin Result := TStringList.Create; for i := 0 to GetCount - 1 do begin if CompareStrings(Get(i), sKey) = 0 then Result.Add(IntToStr(i)); end; end; end.
{ ID: ndchiph1 PROG: pprime LANG: PASCAL } uses math; var fi,fo: text; a,b,len: longint; d: array[1..10] of longint; function isprime(x: longint): boolean; var i: longint; begin if (x = 1) then exit(false); if (x = 2) then exit(true); for i:= 2 to trunc(sqrt(x)) do if (x mod i = 0) then exit(false); exit(true); end; procedure process1; var i,j,len1,s: longint; begin len1:= len div 2 + 1; i:= len1; dec(len1); // while (len1 > 0) do begin inc(i); d[i]:= d[len1]; dec(len1); end; // s:= 0; for j:= 1 to i do s:= s*10 + d[j]; if (s < a) then exit; if (s > b) then begin close(fi); close(fo); halt; end; // if isprime(s) then writeln(fo,s); end; procedure process2; var i,j,len1,s: longint; begin len1:= len div 2; i:= len1; // while (len1 > 0) do begin inc(i); d[i]:= d[len1]; dec(len1); end; // s:= 0; for j:= 1 to i do s:= s*10 + d[j]; if (s < a) then exit; if (s > b) then begin close(fi); close(fo); halt; end; // if isprime(s) then writeln(fo,s); end; procedure attempt(i: integer); var j,t: integer; begin if (len mod 2 = 1) then if (i > len div 2 + 1) then begin process1; exit; end; if (len mod 2 = 0) then if (i > len div 2) then begin process2; exit; end; // if (i = 1) then t:= 1 else t:= 0; // for j:= t to 9 do begin d[i]:= j; attempt(i+1); end; end; procedure process; var t,lena,lenb: longint; begin t:= a; lena:= 0; while (t > 0) do begin inc(lena); t:= t div 10; end; t:= b; lenb:= 0; while (t > 0) do begin inc(lenb); t:= t div 10; end; for len:= lena to lenb do attempt(1); end; begin assign(fi,'pprime.in'); reset(fi); assign(fo,'pprime.out'); rewrite(fo); // readln(fi,a,b); process; // close(fi); close(fo); end.
{ -------------------------------------------------------------------------------- Component Name: TWKey Author: Mats Asplund Creation: July 24, 2000 Version: 2.0 Description: A component that stops program execution and waits for a single keystroke. Credit: EMail: mats.asplund@telia.com Site: http://w1.545.telia.com/~u54503556/delphi/mdp.htm Legal issues: Copyright (C) 2000 by Mats Asplund This software is provided 'as-is', without any express or implied warranty. In no event will the author 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 acknowledgment 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. 4. If you decide to use this software in any of your applications. Send me an EMail address and tell me about it. Quick Reference: TWKey is a descendant from TComponent. Published properties: KeyToPress: The key (a-z, AnyKey) that starts program execution. ShowMessage: If true a message is shown when wait is called. MessagePosition: Screen-position for message. MessageColor: FaceColor of the message. Methods: Wait: Stops program execution and waits for a key to be pressed. -------------------------------------------------------------------------------- } unit wkey; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl, ComCtrls; type TKeyIn = (AnyKey,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z); TWKey = class(TComponent) private DForm: TForm; DLabel: TLabel; FKey: TKeyIn; PKey: string; FCop: string; FShow: Boolean; FPosition: TPosition; FColor: TColor; procedure SetKey(Value: TKeyIn); procedure KeyPressed(Sender: TObject; var Key: char); procedure SetShowMessage(Value: Boolean); procedure SetMessagePosition(Value: TPosition); procedure SetMessageColor(Value: TColor); procedure SetCop(Value: string); function GetCop: string; { Private declarations } protected { Protected declarations } public procedure Wait; constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Public declarations } published property KeyToPress: TKeyIn read FKey write SetKey; property ShowMessage: Boolean read FShow write SetShowMessage; property MessagePosition: TPosition read FPosition write SetMessagePosition; property MessageColor: TColor read FColor write SetMessageColor; property Copyright: string read GetCop write SetCop; { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('Vingelmann', [TWKey]); end; constructor TWKey.Create(AOwner: TComponent); begin inherited Create(AOwner); DForm:= TForm.Create(Self); DLabel:= TLabel.Create(Self); DLabel.Parent:= DForm; DForm.Color:= clYellow; DForm.Position:= poScreenCenter; DForm.Borderstyle:= bsNone; DLabel.Top:= 5; DLabel.Left:= 5; DForm.OnKeyPress:= KeyPressed; FKey:= AnyKey; FShow:= true; FColor:= clYellow; FPosition:= poMainFormCenter; FCop:= '2000 (C), Mats Asplund / MAs Prod.'; end; procedure TWKey.KeyPressed(Sender: TObject; var Key: char); var OK: Boolean; begin OK:= false; case FKey of AnyKey: OK:= true; a: if Key = 'a' then OK:= true; b: if Key = 'b' then OK:= true; c: if Key = 'c' then OK:= true; d: if Key = 'd' then OK:= true; E: if Key = 'e' then OK:= true; F: if Key = 'f' then OK:= true; g: if Key = 'g' then OK:= true; h: if Key = 'h' then OK:= true; i: if Key = 'i' then OK:= true; j: if Key = 'j' then OK:= true; k: if Key = 'k' then OK:= true; l: if Key = 'l' then OK:= true; m: if Key = 'm' then OK:= true; n: if Key = 'n' then OK:= true; o: if Key = 'o' then OK:= true; p: if Key = 'p' then OK:= true; q: if Key = 'q' then OK:= true; r: if Key = 'r' then OK:= true; S: if Key = 's' then OK:= true; t: if Key = 't' then OK:= true; u: if Key = 'u' then OK:= true; v: if Key = 'v' then OK:= true; w: if Key = 'w' then OK:= true; x: if Key = 'x' then OK:= true; y: if Key = 'y' then OK:= true; z: if Key = 'z' then OK:= true; end; if OK then DForm.ModalResult:= mrOK; end; destructor TWKey.Destroy; begin DLabel.Free; DForm.Free; inherited Destroy; end; procedure TWKey.Wait; begin if FShow then begin DForm.Width:= 125; DForm.Height:= 24; if FKey = AnyKey then DLabel.Caption:= 'Press a key to continue.' else DLabel.Caption:= 'Press ' + PKey + ' to continue.'; end else begin DForm.Width:= 0; DForm.Height:= 0; end; if DForm.ShowModal = mrOK then end; procedure TWKey.SetKey(Value: TKeyIn); begin FKey:= Value; case FKey of AnyKey: PKey:= 'a key'; a: PKey:= '<a>'; b: PKey:= '<b>'; c: PKey:= '<c>'; d: PKey:= '<d>'; E: PKey:= '<e>'; F: PKey:= '<f>'; g: PKey:= '<g>'; h: PKey:= '<h>'; i: PKey:= '<i>'; j: PKey:= '<j>'; k: PKey:= '<k>'; l: PKey:= '<l>'; m: PKey:= '<m>'; n: PKey:= '<n>'; o: PKey:= '<o>'; p: PKey:= '<p>'; q: PKey:= '<q>'; r: PKey:= '<r>'; S: PKey:= '<s>'; t: PKey:= '<t>'; u: PKey:= '<u>'; v: PKey:= '<v>'; w: PKey:= '<w>'; x: PKey:= '<x>'; y: PKey:= '<y>'; z: PKey:= '<z>'; end; end; function TWKey.GetCop: string; begin Result:= FCop; end; procedure TWKey.SetCop(Value: string); begin FCop:= FCop; end; procedure TWKey.SetShowMessage(Value: Boolean); begin FShow:= Value; end; procedure TWKey.SetMessagePosition(Value: TPosition); begin FPosition:= Value; DForm.Position:= FPosition; end; procedure TWKey.SetMessageColor(Value: TColor); begin FColor:= Value; DForm.Color:= FColor; end; end.
unit URegraCRUDEstado; interface uses URegraCRUD ,URepositorioDB ,URepositorioEstado ,UEntidade ,UPais ,UEstado ; type TRegraCRUDEstado = class (TRegraCRUD) private procedure ValidaPais(const coPais: TPAIS); protected procedure ValidaInsercao(const coENTIDADE: TENTIDADE); override; procedure ValidaAtualizacao(const coENTIDADE: TENTIDADE); override; public constructor Create ; override ; end; implementation uses SysUtils , UUtilitarios , UMensagens , UConstantes ; { TRegraCRUDEstado } constructor TRegraCRUDEstado.Create; begin inherited; FRepositorioDB := TRepositorioDB<TENTIDADE>(TRepositorioEstado.Create); end; procedure TRegraCRUDEstado.ValidaAtualizacao(const coENTIDADE: TENTIDADE); begin with TESTADO(coENTIDADE) do begin ValidaPais(PAIS); end; end; procedure TRegraCRUDEstado.ValidaInsercao(const coENTIDADE: TENTIDADE); var coEstado : TESTADO; begin inherited; coEstado := TESTADO(coENTIDADE); if Trim(coEstado.NOME) = EmptyStr Then raise EValidacaoNegocio.Create(STR_ESTADO_ESTADO_NAO_INFORMADO); if Trim(coEstado.UF) = EmptyStr Then raise EValidacaoNegocio.Create(STR_ESTADO_UF_NAO_INFORMADO ); ValidaPais(coEstado.PAIS); end; procedure TRegraCRUDEstado.ValidaPais(const coPais: TPAIS); begin if (coPAIS = nil) or (coPais.ID = 0) then raise EValidacaoNegocio.Create(STR_ESTADO_PAIS_NAO_INFORMADO); end; end.
unit HttpsbrowserPlugin; interface uses System.SysUtils, System.Classes, WinApi.Windows, WinApi.ShellApi, System.AnsiStrings, System.Net.HttpClient, WfxPlugin, ObjectIni, ObjectLines, UnitStrings, ObjectBookmark, ObjectHistory; type THTTPSBrowserPlugin = class(TWFXPlugin) public HttpCli : THTTPClient; HttpRes : IHTTPResponse; Received : Int64; links : string; GetSizeExtensions: string; BookMark : TBookMark; History : THistory; LastPage : string; AbortCopy : Boolean; URL : string; Parsed : Boolean; OriginalLastPage : string; public constructor Create; override; destructor Destroy; override; procedure Init; function GetFileSize(URL: string): Integer; function GetPage(var URL: string): string; procedure GetBinaryFile(const URL, FileName: string); procedure ParsePage(var sl: TStringList; URL: string); procedure BuildFindData(var FD: TWin32FindData; FileName: string); procedure PageList(var sl: TStringList); procedure RootList(var sl: TStringList); procedure LangList(var sl: TStringList); procedure CreateFileList; procedure GoBack(RemoteName: PWideChar); procedure Connect(RemoteName: PWideChar); function LoadFromWeb(Name: string; RemoteName: PWideChar): Integer; procedure Download; function ExecuteFile(MainWin: THandle; RemoteName, Verb: PWideChar): Integer; override; function FindFirstFile(var FindData: _WIN32_FIND_DATAW; Path: PWideChar): Cardinal; override; function GetFile(RemoteName,LocalName:string):Integer; function GetIcon(RemoteName:string; var TheIcon:HICON):Integer; function Delete(const RemoteName: string):Boolean; override; function GetPluginName: string; override; end; implementation function DateTimeToFileTime(MyDateTime: TDateTime): TFileTime; var MyFileAge : Integer; MyLocalFileTime: _FILETIME; begin MyFileAge := DateTimeToFileDate(MyDateTime); DosDateTimeToFileTime(LongRec(MyFileAge).Hi, LongRec(MyFileAge).Lo, MyLocalFileTime); LocalFileTimeToFileTime(MyLocalFileTime, Result); end; procedure SplitURL(url: string; out domain, folders, page: string); var s : string; i : Integer; prot: string; begin domain := ''; folders := ''; page := ''; s := ''; i := Pos('//', url); if i > 0 then begin prot := Copy(url, 1, i + 1); Delete(url, 1, i + 1); end; i := Pos('/', url); if i = 0 then begin domain := prot + TrimSlashes(url); Exit; end; domain := prot + TrimSlashes(Copy(url, 1, i - 1)); Delete(url, 1, i); i := Pos('/', url); while i > 0 do begin s := s + Copy(url, 1, i); Delete(url, 1, i); i := Pos('/', url); end; folders := s; if Pos('.', url) > 0 then page := TrimSlashes(url) else folders := folders + url; folders := TrimSlashes(folders); end; function GetURLRoot(const url: string): string; var d, f, p: string; begin Result := DeleteUntilLast(url, '\'); SplitURL(Result, d, f, p); Result := d + '/' + f; end; function CompletePath(CurrentPath, RemoteName: string): string; var root : string; d, f, p: string; begin Result := RemoteName; Result := DeleteUntilLast(Result, '\'); if Pos('//', Result) = 0 then begin root := GetURLRoot(CurrentPath); if Result[1] = '/' then begin SplitURL(root, d, f, p); root := d; end; if (root <> '') and (root[Length(root)] = '/') then Result := root + TrimSlashes(Result) else Result := root + '/' + TrimSlashes(Result); end; end; function OnlyFileName(const RemoteName: string): string; begin Result := DeleteUntilLast(RemoteName, '\'); end; function FilterFileName(FileName: string): string; var i: Integer; begin Result := FileName; Result := DeleteUntilLast(Result, '/'); Result := DeleteUntilLast(Result, '\'); i := Pos('?', Result); if i > 0 then Delete(Result, i, Length(Result)); end; function CreateFileName(Path: string): string; var d, f, p: string; begin if Pos('//', Path) > 0 then begin SplitURL(Path, d, f, p); if p <> '' then Result := p else if f <> '' then Result := f + '.htm' else begin d := d.Replace('.', '_'); Result := d + '.htm'; end; end else begin Result := FilterFileName(Path); end; if Pos('http://', Result) = 1 then Delete(Result, 1, 7); Result := Result.Replace('/', '_'); Result := Result.Replace('?', '_'); end; function MakeRelative(CompleteText, root: string): string; begin if Pos(LowerCase(root), LowerCase(CompleteText)) = 1 then Result := Copy(CompleteText, Length(root) + 1, Length(CompleteText)) else Result := CompleteText; end; function CheckValue(const line: string): Boolean; var ll: string; begin if line = '' then Exit(False); ll := LowerCase(line); Result := (ll <> '/') and (Pos('mailto', ll) <> 1) and (Pos('javascript', ll) <> 1) and (Pos('+', ll) = 0) and (Pos('"', ll) = 0) and (Pos('\', ll) = 0) and (Pos('''', ll) = 0) and (Pos('#', ll) <> 1); end; function IsWebPage(url:string; const links: string): Boolean; var i : Integer; d, f, p: string; Ext : string; begin i := Pos('?', url); if i > 0 then Delete(url, i, Length(url)); SplitURL(url, d, f, p); Ext := ExtractFileExt(p); i := Pos(';', Ext); if i > 0 then Delete(Ext, i, Length(Ext)); i := Pos('#', Ext); if i > 0 then Delete(Ext, i, Length(Ext)); Result := (p = '') or (Pos(' ' + LowerCase(Ext) + ' ', links) > 0); end; function IsRoot(var Name: string; const RemoteName: string; const links:string): Boolean; begin Result := Copy(RemoteName, 2, Length(RemoteName)) = Copy(Name, 2, Length(Name)); if Result then begin Name := Copy(Name, 2, Length(Name)); Result := IsWebPage(Name, Links) end; end; function GetFirstString(var Text, LText: string; key: string; var ResultStr: string): Boolean; var c : Char; l : Integer; j : Integer; i : Integer; Code: Integer; begin ResultStr := ''; i := Pos(key, LText); if i = 0 then begin Result := False; Exit; end; Result := True; Inc(i, Length(key) - 1); Delete(Text, 1, i); Delete(LText, 1, i); l := Length(Text); i := 1; // suppress spaces before and after "=" while (i < l) and (Text[i] = ' ') do Inc(i); if (i >= l) or (Text[i] <> '=') then Exit; Inc(i); while (i < l) and (Text[i] = ' ') do Inc(i); if i >= l then Exit; // Cas de code jscript avec des \' au lieu de ' if Text[i] = '\' then Code := 1 else Code := 0; c := Text[i + Code]; // mot simple sans guillemets if not CharInSet(c, ['"', '''']) then begin Delete(Text, 1, i - 1); Delete(LText, 1, i - 1); j := Pos('>', Text); i := Pos(' ', Text); if i = 0 then i := j else if (j <> 0) and (j < i) then i := j; end // Mot entouré de séparateurs else begin Delete(Text, 1, i + Code); Delete(LText, 1, i + Code); j := Pos('>', Text); i := Pos(c, Text); if i = 0 then Exit else if (j > 0) and (j < i) then Exit; end; ResultStr := Copy(Text, 1, i - 1 - Code); System.Delete(Text, 1, i); System.Delete(LText, 1, i); ResultStr := ResultStr .Replace(#13, '') .Replace(#10, ''); end; procedure THTTPSBrowserPlugin.Connect(RemoteName: PWideChar); var LocalURL: string; begin // Connect FileList.Clear; LocalURL := ini.GetS('LastURL', 'http://www.google.com'); if Input('', '', LocalURL, RT_URL) then begin ini.SetValue('LastURL', LocalURL); if not IsWebPage(LocalURL, links) then begin URL := LocalURL; StrPCopy(RemoteName, '\'); Exit; end; History.Add(LocalURL); LastPage := GetPage(LocalURL); Parsed := True; StrPCopy(RemoteName, '\' + LocalURL); CurrentPath := RemoteName; end else StrPCopy(RemoteName, '\'); end; constructor THTTPSBrowserPlugin.Create; begin inherited; HttpCli := THTTPClient.Create; GetSizeExtensions := ' ' + LowerCase(ini.GetS('GetSizeExtensions', '')) + ' '; links := LowerCase(' ' + ini.GetS('LinksExtensions', '.php .htm .html .shtm .shtml .php3 .php4 .php5 .cfm .asp .jsp .swf .jhtm .jhtml .phtml .phtm .chtml .chtml .adp .dml .xml .xhtml .xhtm .xiti') + ' '); BookMark := TBookMark.Create(Self); History := THistory.Create; // HttpReq.ProxySettings.Host := ini.GetS('Proxy'); // HttpCli.ProxySettings.Port := ini.GetS('ProxyPort', '80'); // HttpCli.ProxySettings.UserName := ini.GetS('ProxyLogin'); // HttpCli.ProxySettings.Password := ini.GetS('ProxyPassword'); // HttpCli.OnHeaderEnd := ProgressObject.HeaderEnd; end; function THTTPSBrowserPlugin.Delete(const RemoteName: string):Boolean; var s: string; begin inherited; Result := False; if CurrentPath <> '\' then Exit; Result := True; s := RemoteName; if s <> '' then System.Delete(s, 1, 1); BookMark.Delete(s); end; destructor THTTPSBrowserPlugin.Destroy; begin FreeAndNil(FileList); FreeAndNil(ini); FreeAndNil(HttpCli); FreeAndNil(BookMark); FreeAndNil(Strings); FreeAndNil(History); inherited; end; procedure THTTPSBrowserPlugin.Download; var ofn: string; begin if URL <> '' then begin try ofn := PathExe + CreateFileName(URL); RemoteFile := URL; LocalFile := ofn; GetBinaryFile(URL, ofn); if not AbortCopy then ShellExecute(HInstance, 'Open', PChar(ofn), PChar(''), PChar(''), SW_SHOWNORMAL); AbortCopy := False; finally URL := ''; end; end; end; function THTTPSBrowserPlugin.ExecuteFile(MainWin: THandle; RemoteName, Verb: PWideChar): Integer; var Name : string; FileName : string; vb : string; begin try // @@@ if IsGettingFile then // begin // Result := FS_EXEC_OK; // Exit; // end; Name := RemoteName; Result := FS_EXEC_SYMLINK; vb := Verb; if vb.StartsWith('quote') then Exit; if Name = '\...' then begin GoBack(RemoteName); Exit; end; System.Delete(Name, 1, 1); if Name = Strings[0] then begin Connect(RemoteName); Exit; end; if Name = '' then Exit(FS_EXEC_OK); FileName := OnlyFileName(RemoteName); Name := CompletePath(CurrentPath, RemoteName); if FileName = Strings[2] then // Bookmark begin BookMark.Add(CurrentPath); Result := FS_EXEC_OK; end else if FileName = Strings[6] then // Language StrPCopy(RemoteName, '\' + Strings[6]) else if RemoteName = '\' + Strings[6] + '\' + FileName then // language 2 begin ini.SetValue('Language', FileName); Strings.SetLanguage(PathExe + FileName + '.lng'); StrPCopy(RemoteName, '\'); end else Exit(LoadFromWeb(Name, RemoteName)); except on E: Exception do begin Result := FS_EXEC_ERROR; TCShowMessage('', E.Message); end; end; end; function THTTPSBrowserPlugin.FindFirstFile(var FindData: _WIN32_FIND_DATAW; Path: PWideChar):Cardinal; begin FindData := default(tWIN32FINDDATAW); CurrentPath := Path; if not Parsed then ExecuteFile(0, Path, ''); Parsed := False; CreateFileList; if FileList.Count = 0 then Result := INVALID_HANDLE_VALUE else begin Result := 0; FLIndex := 0; BuildFindData(FindData, FileList[0]); end; Download; end; procedure THTTPSBrowserPlugin.Init; begin PreviousPath := ''; FileDate := DateTimeToFileTime(Now); URL := ''; end; function THTTPSBrowserPlugin.GetFile(RemoteName, LocalName: string): Integer; var i : Integer; url : string; Name : string; LocalPath : string; RemoteFileName: string; sStream : TStringStream; begin try Name := LocalName; // calcule local path RemoteFileName := OnlyFileName(RemoteName); LocalPath := Name; i := Length(Name); if RemoteFileName = '...' then begin System.Delete(LocalPath, i - 2, 3); StrPCopy(PChar(LocalName), IncludeTrailingPathDelimiter(LocalPath) + CreateFileName(CurrentPath)); StrPCopy(PChar(RemoteName), '\' + CurrentPath); sStream := TStringStream.Create(OriginalLastPage); try sStream.SaveToFile(LocalName); finally sStream.Free; end; Result := FS_FILE_OK; Exit; end else begin LocalPath := ExtractFileDir(LocalPath); end; url := CompletePath(CurrentPath, RemoteName); Name := IncludeTrailingPathDelimiter(LocalPath) + CreateFileName(url); LocalName := Name; RemoteName := url; if (CurrentPath = '\') or (CurrentPath = '\' + Strings[6]) then begin Result := FS_FILE_NOTSUPPORTED end else begin RemoteFile := RemoteName; LocalFile := LocalName; if not AbortCopy then GetBinaryFile(url, PChar(Name)); Result := FS_FILE_OK; end; except on E: Exception do begin Result := FS_FILE_READERROR; TCShowMessage('', E.Message); end; end; end; function THTTPSBrowserPlugin.GetFileSize(url: string): Integer; begin try Result := HttpCli.Head(url).ContentLength; except Result := 0; end; end; function THTTPSBrowserPlugin.GetIcon(RemoteName: string; var TheIcon:HICON): Integer; var Name: string; url : string; ofn : string; begin Result := FS_ICON_USEDEFAULT; Name := RemoteName; if Copy(Name, Length(Name) - 3, 4) = '\..\' then begin Exit; end; ofn := OnlyFileName(RemoteName); url := CompletePath(CurrentPath, RemoteName); if Name = '\' + Strings[0] then begin TheIcon := LoadIcon(HInstance, 'ZCONNECT'); Result := FS_ICON_EXTRACTED; end else if Pos('\...', Name) > 0 then begin TheIcon := LoadIcon(HInstance, 'ZBACK'); Result := FS_ICON_EXTRACTED; end else if Pos('\' + Strings[6], Name) = 1 then begin TheIcon := LoadIcon(HInstance, 'ZLANG'); Result := FS_ICON_EXTRACTED; end else if (ofn = Strings[2]) or (BookMark.BMList.IndexOf(ofn) > -1) then begin TheIcon := LoadIcon(HInstance, 'ZBOOK'); Result := FS_ICON_EXTRACTED; end else if (ofn <> '') and IsWebPage(url,Links) then begin TheIcon := LoadIcon(HInstance, 'ZLINK'); Result := FS_ICON_EXTRACTED; end; end; function THTTPSBrowserPlugin.GetPage(var url: string): string; var res:IHTTPResponse; begin res := HttpCli.Get(url); if res.StatusCode = 200 then Result := res.ContentAsString(TEncoding.ASCII) else Result := ''; ProgressBar(PluginNumber, PChar(RemoteFile), PChar(LocalFile), 100); end; function THTTPSBrowserPlugin.GetPluginName: string; begin Result := 'HTTPS Browser'; end; procedure THTTPSBrowserPlugin.GoBack(RemoteName: PWideChar); var s:string; begin s := History.GoBack; StrPCopy(RemoteName, s); System.Delete(s, 1, 1); LastPage := GetPage(s); Parsed := True; end; procedure THTTPSBrowserPlugin.ParsePage(var sl: TStringList; url: string); var page : string; LPage: string; s : string; ls : string; l : string; begin RemoteFile := url; LocalFile := Strings[1]; page := LastPage; LPage := LowerCase(page); if page = '' then Exit; s := page; ls := LPage; while GetFirstString(s, ls, 'href', l) do begin if CheckValue(l) then sl.Add(l); end; s := page; ls := LPage; // while GetFirstString(s, ls, ' src=', '"', '"', l) do while GetFirstString(s, ls, 'src', l) do if CheckValue(l) then sl.Add(l); end; procedure THTTPSBrowserPlugin.BuildFindData(var FD: TWin32FindData; FileName: string); var Ext: string; s : string; begin FillChar(FD, SizeOf(FD), 0); StrCopy(FD.cFileName, PChar(FileName)); FD.nFileSizeLow := 100; if FileName <> Strings[0] then begin if Pos('http', FileName) = 1 then s := FileName else s := GetURLRoot(CurrentPath) + '/' + FileName; Ext := LowerCase(ExtractFileExt(FileName)); if (Ext <> '') and (Ext[1] = '.') and (Pos(' ' + Ext + ' ', GetSizeExtensions) > 0) then FD.nFileSizeLow := GetFileSize(s); FD.ftCreationTime := FileDate; FD.ftLastWriteTime := FileDate; FD.ftLastAccessTime := FileDate; end; end; procedure THTTPSBrowserPlugin.PageList(var sl: TStringList); begin sl.Add('...'); sl.Add(Strings[2]); CurrentPath := DeleteUntilLast(CurrentPath, '\'); ParsePage(sl, CurrentPath); end; procedure THTTPSBrowserPlugin.RootList(var sl: TStringList); begin sl.Add(Strings[0]); // Connect sl.Add(Strings[6]); // Choose Language sl.AddStrings(BookMark.BMList); end; procedure THTTPSBrowserPlugin.LangList(var sl: TStringList); var sr: TSearchRec; begin if System.SysUtils.FindFirst(PathExe + 'hb_*.lng', faAnyFile, sr) = 0 then begin sl.Add(ChangeFileExt(sr.Name, '')); while FindNext(sr) = 0 do sl.Add(ChangeFileExt(sr.Name, '')); end; end; function THTTPSBrowserPlugin.LoadFromWeb(Name: string; RemoteName: PWideChar): Integer; begin if IsWebPage(Name, Links) or IsRoot(Name, RemoteName, Links) then begin // Webpage History.Add(Name); LastPage := GetPage(Name); Parsed := True; StrPCopy(RemoteName, '\' + Name); Result := FS_EXEC_SYMLINK; end else Result := FS_EXEC_YOURSELF; end; procedure THTTPSBrowserPlugin.CreateFileList; begin FileList.Clear; if CurrentPath = '\' then RootList(FileList) else if CurrentPath = '\' + Strings[6] then LangList(FileList) else PageList(FileList); end; procedure THTTPSBrowserPlugin.GetBinaryFile(const url, FileName: string); var fs : TFileStream; begin fs := TFileStream.Create(FileName, fmCreate); try HttpRes := HttpCli.Get(url); fs.CopyFrom(HttpRes.ContentStream, HttpRes.ContentStream.Size); finally fs.Free; end; ProgressBar(PluginNumber, PChar(RemoteFile), PChar(LocalFile), 100); end; end.
unit MiscSupportFunctions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, {$ifndef VER3_0} OpenSSLSockets, {$endif} JsonTools, TypInfo, CastleDownload; type TFormat = Record width: Integer; height: Integer; end; TSource = Record protocol: String; server: String; path: String; key: String; mimetype: String; append: String; format: TFormat; local: Boolean; notes: String; end; TSourceArray = Array of TSource; TLimit = Record protocol: String; server: String; ratelimit: Integer; error_code: Integer; notes: String; end; TLimitsArray = Array of TLimit; TFileDetail = Record uuid: String; cardname: String; setcode: String; cardtype: String; cardlayout: String; cardnum: String; side: String; rarity: String; scryfall: String; hasprice: Boolean; created: Int64; end; TFileDetailsArray = Array of TFileDetail; TCardDownloadList = Record Sources: TSourceArray; Limits: TLimitsArray; FileDetails: TFileDetailsArray; end; const FILELIST_URI = 'https://api.peardox.co.uk/cards.php?setcode=UNH'; procedure MapJsonObject(Json: TJsonNode); function CreateFormat(Json: TJsonNode): TFormat; function CreateSource(Json: TJsonNode): TSource; function CreateLimit(Json: TJsonNode): TLimit; function CreateFileDetail(Json: TJsonNode): TFileDetail; function ExtractJsonData(Stream: TStream; FreeStream: Boolean = False): TCardDownloadList; procedure PrintDownloadList(downloadList: TCardDownloadList); function DownloadFileList: TStream; implementation uses Unit1; // For DebugMessage procedure MapJsonObject(Json: TJsonNode); var Node: TJsonNode; Txt: String; begin for Node in Json do begin case Node.Name of 'dummyField': begin // Just a dummy field end; else begin Txt := Chr(39) + Node.Name + Chr(39) + ':' + LineEnding + ' begin' + LineEnding + ' if not(Node.Kind = ' + Node.KindAsString + ') then' + LineEnding + ' DebugMessage(' + Chr(39) + 'TypeError for ' + Node.Name + ' expected ' + Node.KindAsString + ' got ' + Chr(39) + ' + Node.KindAsString' + ')' + LineEnding + ' else' + LineEnding; if Node.Kind = nkString then Txt += ' Rec.' + Node.Name + ' := Node.AsString;' + LineEnding else if Node.Kind = nkNumber then Txt += ' Rec.' + Node.Name + ' := Trunc(Node.AsNumber);' + LineEnding else if Node.Kind = nkBool then Txt += ' Rec.' + Node.Name + ' := Node.AsBoolean;' + LineEnding else if Node.Kind = nkObject then Txt += ' // Rec.' + Node.Name + ' := MapJsonObject(Node); // *** FIXME ***' + LineEnding else if Node.Kind = nkArray then Txt += ' // Rec.' + Node.Name + ' := MapJsonArray(Node); // *** FIXME ***' + LineEnding else Txt += ' Rec.' + Node.Name + ' := Node.AsString; // *** FIXME ***' + LineEnding; Txt += ' end;'; DebugMessage(Txt); end; end; end; end; function CreateFormat(Json: TJsonNode): TFormat; var Node: TJsonNode; Rec: TFormat; begin Rec := Default(TFormat); for Node in Json do begin case Node.Name of 'width': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for width expected nkNumber got ' + Node.KindAsString) else Rec.width := Trunc(Node.AsNumber); end; 'height': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for height expected nkNumber got ' + Node.KindAsString) else Rec.height := Trunc(Node.AsNumber); end; else DebugMessage('Unexpected data in CreateFormat - ' + Node.Name + ' -> ' + Node.KindAsString); end; end; Result := Rec; end; function CreateSource(Json: TJsonNode): TSource; var Node: TJsonNode; Rec: TSource; begin Rec := Default(TSource); for Node in Json do begin case Node.Name of 'protocol': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for protocol expected nkString got ' + Node.KindAsString) else Rec.protocol := Node.AsString; end; 'server': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for server expected nkString got ' + Node.KindAsString) else Rec.server := Node.AsString; end; 'path': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for path expected nkString got ' + Node.KindAsString) else Rec.path := Node.AsString; end; 'key': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for key expected nkString got ' + Node.KindAsString) else Rec.key := Node.AsString; end; 'mimetype': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for mimetype expected nkString got ' + Node.KindAsString) else Rec.mimetype := Node.AsString; end; 'append': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for append expected nkString got ' + Node.KindAsString) else Rec.append := Node.AsString; end; 'format': begin if not(Node.Kind = nkObject) then DebugMessage('TypeError for format expected nkObject got ' + Node.KindAsString) else Rec.format := CreateFormat(Node); end; 'local': begin if not(Node.Kind = nkBool) then DebugMessage('TypeError for local expected nkBool got ' + Node.KindAsString) else Rec.local := Node.AsBoolean; end; 'notes': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for notes expected nkString got ' + Node.KindAsString) else Rec.notes := Node.AsString; end; else DebugMessage('Unexpected data in CreateSource- ' + Node.Name + ' -> ' + Node.KindAsString); end; end; Result := Rec; end; function CreateLimit(Json: TJsonNode): TLimit; var Node: TJsonNode; Rec: TLimit; begin Rec := Default(TLimit); for Node in Json do begin case Node.Name of 'protocol': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for protocol expected nkString got ' + Node.KindAsString) else Rec.protocol := Node.AsString; end; 'server': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for server expected nkString got ' + Node.KindAsString) else Rec.server := Node.AsString; end; 'ratelimit': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for ratelimit expected nkNumber got ' + Node.KindAsString) else Rec.ratelimit := Trunc(Node.AsNumber); end; 'error_code': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for error_code expected nkNumber got ' + Node.KindAsString) else Rec.error_code := Trunc(Node.AsNumber); end; 'notes': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for notes expected nkString got ' + Node.KindAsString) else Rec.notes := Node.AsString; end; else DebugMessage('Unexpected data in CreateLimit - ' + Node.Name + ' -> ' + Node.KindAsString); end; end; Result := Rec; end; function CreateFileDetail(Json: TJsonNode): TFileDetail; var Node: TJsonNode; Rec: TFileDetail; begin Rec := Default(TFileDetail); for Node in Json do begin case Node.Name of 'uuid': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for uuid expected nkString got ' + Node.KindAsString) else Rec.uuid := Node.AsString; end; 'cardname': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for cardname expected nkString got ' + Node.KindAsString) else Rec.cardname := Node.AsString; end; 'setcode': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for setcode expected nkString got ' + Node.KindAsString) else Rec.setcode := Node.AsString; end; 'cardtype': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for cardtype expected nkString got ' + Node.KindAsString) else Rec.cardtype := Node.AsString; end; 'cardlayout': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for cardlayout expected nkString got ' + Node.KindAsString) else Rec.cardlayout := Node.AsString; end; 'cardnum': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for cardnum expected nkString got ' + Node.KindAsString) else Rec.cardnum := Node.AsString; end; 'side': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for side expected nkString got ' + Node.KindAsString) else Rec.side := Node.AsString; end; 'rarity': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for rarity expected nkString got ' + Node.KindAsString) else Rec.rarity := Node.AsString; end; 'scryfall': begin if not(Node.Kind = nkString) then DebugMessage('TypeError for scryfall expected nkString got ' + Node.KindAsString) else Rec.scryfall := Node.AsString; end; 'hasprice': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for hasprice expected nkNumber got ' + Node.KindAsString) else Rec.hasprice := Node.AsBoolean; end; 'created': begin if not(Node.Kind = nkNumber) then DebugMessage('TypeError for created expected nkNumber got ' + Node.KindAsString) else Rec.created := Trunc(Node.AsNumber); end; else DebugMessage('Unexpected data in CreateFileDetail - ' + Node.Name + ' -> ' + Node.KindAsString); end; end; Result := Rec; end; function ExtractJsonData(Stream: TStream; FreeStream: Boolean = False): TCardDownloadList; var Json: TJsonNode; Node: TJsonNode; CardData: TCardDownloadList; Idx: Integer; begin CardData := Default(TCardDownloadList); Json := TJsonNode.Create; Json.LoadFromStream(Stream); try try for Node in Json do begin if Node.Kind = nkArray then begin DebugMessage(Node.Name + ' -> ' + Node.KindAsString + ' has ' + IntToStr(Node.Count) + ' records'); case Node.Name of 'source': begin SetLength(CardData.Sources, Node.Count); for Idx := 0 to Node.Count - 1 do begin CardData.Sources[Idx] := CreateSource(Node.Child(Idx)); end; end; 'limits': begin SetLength(CardData.Limits, Node.Count); for Idx := 0 to Node.Count - 1 do begin CardData.Limits[Idx] := CreateLimit(Node.Child(Idx)); end; end; 'data': begin SetLength(CardData.FileDetails, Node.Count); for Idx := 0 to Node.Count - 1 do begin // if Idx = 0 then // MapJsonObject(Node.Child(Idx)); CardData.FileDetails[Idx] := CreateFileDetail(Node.Child(Idx)); end; end; else begin DebugMessage('Unexpected data in ExtractJsonData - ' + Node.Name + ' -> ' + Node.KindAsString); end; end; end else DebugMessage('Unexpected data in ExtractJsonData - ' + Node.Name + ' -> ' + Node.KindAsString); end; except on E : Exception do begin DebugMessage('Oops' + LineEnding + 'Trying to download : ' + FILELIST_URI + LineEnding + E.ClassName + LineEnding + E.Message); Json := nil; end; end; finally FreeAndNil(Json); if FreeStream then FreeAndNil(Stream); end; Result := CardData; end; procedure PrintDownloadList(downloadList: TCardDownloadList); var i: Integer; begin DebugMessage('Servers'); DebugMessage('======='); for i := 0 to Length(DownloadList.Sources) - 1 do begin with DownloadList.Sources[i] do begin DebugMessage('Protocol : ' + protocol); DebugMessage('Server : ' + server); DebugMessage('Path : ' + path); DebugMessage('Key : ' + key); DebugMessage('Mimetype : ' + mimetype); DebugMessage('Append : ' + append); DebugMessage('Format(W) : ' + IntToStr(format.width)); DebugMessage('Format(H) : ' + IntToStr(format.height)); if local then DebugMessage('Local : Yes') else DebugMessage('Local : No'); DebugMessage('Notes : ' + notes); end; DebugMessage('====='); end; DebugMessage(LineEnding); DebugMessage('Limits'); DebugMessage('======'); for i := 0 to Length(DownloadList.Limits) - 1 do begin with DownloadList.Limits[i] do begin DebugMessage('Protocol : ' + protocol); DebugMessage('Server : ' + server); DebugMessage('Rate Limit : ' + IntToStr(ratelimit)); DebugMessage('Error Code : ' + IntToStr(error_code)); DebugMessage('Notes : ' + notes); end; DebugMessage('====='); end; DebugMessage(LineEnding); DebugMessage('File Details'); DebugMessage('============'); for i := 0 to Length(DownloadList.FileDetails) - 1 do begin with DownloadList.FileDetails[i] do begin DebugMessage('MTGJSON ID : ' + uuid); DebugMessage('CardName : ' + cardname); DebugMessage('SetCode : ' + setcode); DebugMessage('CardType : ' + cardtype); DebugMessage('CardLayout : ' + cardlayout); DebugMessage('CardNumber : ' + cardnum); DebugMessage('CardSide : ' + side); DebugMessage('Rarity : ' + rarity); DebugMessage('Scryfall ID : ' + scryfall); if hasprice then DebugMessage('HasPrice : Yes') else DebugMessage('HasPrice : No'); DebugMessage('Created : ' + IntToStr(created)); end; DebugMessage('================'); end; DebugMessage(LineEnding); end; function DownloadFileList: TStream; var Stream: TStream; begin Result := nil; EnableBlockingDownloads := True; Stream := Download(FILELIST_URI, [soForceMemoryStream]); try try except on E : Exception do begin DebugMessage('Oops' + LineEnding + 'Trying to download : ' + FILELIST_URI + LineEnding + E.ClassName + LineEnding + E.Message); Stream := nil; end; end; finally Result := Stream; EnableBlockingDownloads := False; end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) btAdicionaItem: TButton; btContar: TButton; btRemoveItem: TButton; btRemoveTudo: TButton; btFecha: TButton; Edit1: TEdit; Label1: TLabel; ListBox1: TListBox; procedure btAdicionaItemClick(Sender: TObject); procedure btContarClick(Sender: TObject); procedure btFechaClick(Sender: TObject); procedure btRemoveItemClick(Sender: TObject); procedure btRemoveTudoClick(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btAdicionaItemClick(Sender: TObject); begin ListBox1.Items.Add(Edit1.Text); Edit1.Clear; Edit1.SetFocus; end; procedure TForm1.btContarClick(Sender: TObject); var n:integer; begin n:=ListBox1.Count; ShowMessage('A lista tem '+IntToStr(n)+' itens'); end; procedure TForm1.btFechaClick(Sender: TObject); begin Form1.Close; end; procedure TForm1.btRemoveItemClick(Sender: TObject); var i:integer; begin i:=ListBox1.ItemIndex; if (i<>-1) then ListBox1.Items.Delete(i) else ShowMessage('Seleciona o Item fdp, acha que eu vou adivinhar?'); end; procedure TForm1.btRemoveTudoClick(Sender: TObject); begin ListBox1.Clear; end; end.
unit BusLineController; interface uses BusLine, Generics.Collections, Aurelius.Engine.ObjectManager, ControllerInterfaces, Aurelius.Criteria.Linq, Aurelius.Criteria.Projections, BusStop; type TBusLineController = class(TInterfacedObject, IController<TBusLine>) private FManager: TObjectManager; public constructor create; destructor destroy; procedure Delete(BusLine: TBusLine); function getAll: TList<TBusLine>; function getBusLine(id: integer): TBusLine; function getBusLineByBeaconUUID(UUID: string): TList<TBusLine>; procedure Save(BusLine: TBusLine); end; implementation uses DBConnection; { TBusLineController } constructor TBusLineController.create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TBusLineController.Delete(BusLine: TBusLine); begin if not FManager.IsAttached(BusLine) then begin BusLine := FManager.Find<TBusLine>(BusLine.ID); FManager.Remove(BusLine); end; end; destructor TBusLineController.destroy; begin FManager.Free; end; function TBusLineController.getAll: TList<TBusLine>; begin Result := FManager.FindAll<TBusLine>; end; function TBusLineController.getBusLine(id: integer): TBusLine; begin Result := FManager.Find<TBusLine>(id); end; function TBusLineController.getBusLineByBeaconUUID(UUID: string): TList<TBusLine>; begin Result := FManager.Find<TBusLine>. CreateAlias('Beacon', 'b'). Where(Linq.Sql('{b.UUID} = '''+UUID+'''')).List; end; procedure TBusLineController.Save(BusLine: TBusLine); begin FManager.Save(BusLine); end; end.
// ---------------------------------------------------------------------------- // Unit : PxLog.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2004-10-10 // Version : 1.0 // Description ; Logging facilities for applications. // Changes log ; 2004-10-10 - Initial version // 2004-10-11 - added type TLogLevel that defines the size of // log level constants // 2004-12-21 - added the possibility to turn on/off date in log // entries. // 2005-03-24 - GetLogLevel and SetLogLevel functions to // manipulate the current LogLevel at runtime. // 2005-05-03 - All procedures (excluding initialization) are now // thread safe // 2005-06-21 - Added additional parameters for logging (all to be // set via [Log] section in application's ini file): // - LogKind (continous, incremental) // - MaxLines (after this amount of logs is achieved // a new log is generated and the previous is // renamed in form logfile.log.x, where x is an // autoincremented value discovered from existing // files in application's folder // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxLog; {$I PxDefines.inc} interface uses Windows, Messages, SysUtils, IniFiles, PxBase, PxUtils; type TLogLevel = type UINT32; const // // Log levels // // default log level LOGLEVEL_DEFAULT = 0; // default debug log level LOGLEVEL_DEBUG = 5; // default strong-debug level (used only while searching for really nasty bugs) LOGLEVEL_STRONG_DEBUG = 10; var // // Indicates if Date should be included in log entries // IncludeDateInLog: Boolean = True; LastLogEntry : String = ''; // // Simply add a log message at the default log level // procedure Log(S: String); overload; // // Add a log message at the default log level. // Passed string is a template for the Format function // procedure Log(S: String; Params: array of const); overload; // // Add a simple log at a given level // procedure Log(Level: TLogLevel; S: String); overload; // // Add a log message at the given log level. // Passed string is a template for the Format function // procedure Log(Level: TLogLevel; S: String; Params: array of const); overload; // // Retrives the current log level // function GetLogLevel: Word; // // Sets the log level (usefull in test applications where creating a .ini file // is not needed). // procedure SetLogLevel(ALogLevel: Word); // // Sets a handle to a list box so that log messages can go there instead of // the real text console // procedure SetLogHandle(Handle: THandle); // // Checks if log entries goes to console (like in debug mode) // function LogToConsole: Boolean; // // Switsches the logging window into console // procedure SwitchLogToConsole; // // Starts the logging subsystem // procedure Initialize; implementation uses {$IFDEF VER130} PxDelphi5, {$ENDIF} PxSettings; type TPxLogStyle = (lsContinuous, lsIncremental); const // section in settings file SLOG : String = 'Log'; // do not localize // file name value key SLOG_FILE_NAME: String = 'FileName'; // do not localize // log level value key SLOG_LEVEL : String = 'Level'; // do not localize SLOG_KIND : String = 'Kind'; SLOG_KIND_CONT: String = 'Continuous'; // default, do not localize SLOG_KIND_INC : String = 'Incremental'; // do not localize SLOG_MAX_LINES: String = 'MaxLines'; // default=0 (disabled), do not localize var // indicates wether logs are written to a log file or console LogToFile: Boolean; // used when no console is available and the log file is not initialized yet LogBootFile: Text; LogBootFileInitialized: Boolean; // if logging to file - this is the file LogFile: Text; LogFileName: String; // if logging is to a console and this is set - a list box is used instead of a real console LogHandle: THandle; // current logging level LogLevel: Word; // thread-safety LogMutex: THandle; LogLevelMutex: THandle; LogHandleMutex: THandle; // style of the logging system LogStyle: TPxLogStyle; // count of logs stored to the LogLines: Integer; MaxLogLines: Integer; LoggingInitialized: Boolean = False; function GetLastLogFileIndex: Integer; var SRec: TSearchRec; SRes, Temp: Integer; begin Result := 0; SRes := FindFirst(LogFileName + '.*', faAnyFile, SRec); while SRes = 0 do begin if TryStrToInt(Copy(SRec.Name, Length(ExtractFileName(LogFileName)) + 2, MaxInt), Temp) and (Temp >= Result) then Result := Temp + 1; SRes := FindNext(SRec); end; end; procedure Log(S: String); begin Log(LOGLEVEL_DEFAULT, S); end; procedure Log(S: String; Params: array of const); begin Log(LOGLEVEL_DEFAULT, Format(S, Params)); end; procedure Log(Level: TLogLevel; S: String); var Index: Integer; begin if IncludeDateInLog then S := FormatDateTime('YYYY-MM-DD HH:NN:SS - ', Now) + S else S := FormatDateTime('HH:NN:SS - ', Now) + S; LastLogEntry := S; if LogLevel >= Level then if WaitForSingleObject(LogMutex, INFINITE) = WAIT_OBJECT_0 then try if LogToFile then begin if (MaxLogLines > 0) and (LogStyle = lsIncremental) then begin Inc(LogLines); if LogLines > MaxLogLines then begin Index := GetLastLogFileIndex; CloseFile(LogFile); RenameFile(LogFileName, LogFileName + '.' + IntToStr(Index)); AssignFile(LogFile, LogFileName); Rewrite(LogFile); LogLines := 0; end; end; Writeln(LogFile, S); Flush(LogFile); end else if IsConsole then Writeln(S) else if LogBootFileInitialized then Writeln(LogBootFile, S); if LogHandle <> 0 then SendMessage(LogHandle, LB_ADDSTRING, 0, Cardinal(PChar(S))); finally ReleaseMutex(LogMutex); end; end; procedure Log(Level: TLogLevel; S: String; Params: array of const); begin Log(Level, Format(S, Params)); end; function GetLogLevel: Word; begin Result := LogLevel; end; procedure SetLogLevel(ALogLevel: Word); begin if WaitForSingleObject(LogLevelMutex, INFINITE) = WAIT_OBJECT_0 then begin LogLevel := ALogLevel; ReleaseMutex(LogLevelMutex); Log(LOGLEVEL_DEBUG, 'Changed LogLevel from %d to %d', [LogLevel, ALogLevel]); end else Log(LOGLEVEL_DEBUG, 'Error while changing LogLevel from %d to %d', [LogLevel, ALogLevel]); end; procedure SetLogHandle(Handle: THandle); begin if WaitForSingleObject(LogHandleMutex, INFINITE) = WAIT_OBJECT_0 then LogHandle := Handle; end; function LogToConsole: Boolean; begin Result := (not LogToFile) and (LogHandle = 0); end; procedure SwitchLogToConsole; begin if LogToConsole then Exit; if LogToFile then begin CloseFile(LogFile); LogToFile := False; end; if LogHandle <> 0 then SetLogHandle(0); Log('Switched into console mode'); end; procedure Initialize; const {$IFDEF DEBUG} DefaultLogLevel = LOGLEVEL_DEBUG; {$ELSE} DefaultLogLevel = LOGLEVEL_DEFAULT; {$ENDIF} var Index: Integer; begin // while running from package as a part of delphi environment don't start the logging subsystem if IsDelphiHost then Exit; if LogMutex = 0 then LogMutex := CreateMutex(nil, False, ''); if LogLevelMutex = 0 then LogLevelMutex := CreateMutex(nil, False, ''); if LogHandleMutex = 0 then LogHandleMutex := CreateMutex(nil, False, ''); if SameText(SLOG_KIND_INC, IniFile.ReadString(SLOG, SLOG_KIND, SLOG_KIND_CONT)) then begin LogStyle := lsIncremental; MaxLogLines := IniFile.ReadInteger(SLOG, SLOG_MAX_LINES, 0); end else begin LogStyle := lsContinuous; MaxLogLines := 0; end; LogLines := 0; try LogFileName := IniFile.ReadString(SLOG, SLOG_FILE_NAME, ChangeFileExt(ParamStr(0), '.log')); LogToFile := LogFileName <> ''; if ExtractFilePath(LogFileName) = '' then LogFileName := ExtractFilePath(ParamStr(0)) + LogFileName; if LogToFile then begin // check if old log is to be backuped or appended if (LogStyle = lsIncremental) and FileExists(LogFileName) then begin Index := GetLastLogFileIndex; RenameFile(LogFileName, LogFileName + '.' + IntToStr(Index)); end; AssignFile(LogFile, LogFileName); if FileExists(LogFileName) then Append(LogFile) else Rewrite(LogFile); end else if not IsConsole then begin AllocConsole; IsConsole := True; end; if LogBootFileInitialized then begin CloseFile(LogBootFile); LogBootFileInitialized := False; end; LogLevel := IniFile.ReadInteger(SLOG, SLOG_LEVEL, DefaultLogLevel); Log('--- Log begin ---'); except LogToFile := False; Log('Error: cannot start log - application terminated'); IniFile.Free; Halt(1); end; LoggingInitialized := True; end; procedure Finalize; begin // while running from package as a part of delphi environment the logging subsystem is inactive so there's nothing to clean up here if IsDelphiHost then Exit; if LoggingInitialized then begin Log('--- Log end ---'); if LogToFile then begin Flush(LogFile); CloseFile(LogFile); end; LoggingInitialized := False; end; end; initialization {$IFDEF AUTO_ENABLE_LOGGING} AssignFile(LogBootFile, ChangeFileExt(ParamStr(0), '.boot.log')); Rewrite(LogBootFile); LogBootFileInitialized := True; Initialize; {$ENDIF} finalization if LogBootFileInitialized then CloseFile(LogBootFile); CloseHandle(LogMutex); CloseHandle(LogLevelMutex); CloseHandle(LogHandleMutex); Finalize; end.
unit FormNews; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Platform.Win, HttpClient, RSSParser, RSSModel, FMX.ListBox, FMX.Controls, System.IOUtils; type TfmNews = class(TForm) lytRCC: TLayout; lytButtons: TLayout; btnLoadNews: TButton; lvRCC: TListView; TimerLoadRSS: TTimer; lytRssChoi˝e: TLayout; cmxRssChoice: TComboBox; StyleBook: TStyleBook; procedure btnLoadNewsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure lvRCCItemClick(const Sender: TObject; const AItem: TListViewItem); procedure TimerLoadRSSTimer(Sender: TObject); procedure FormCreate(Sender: TObject); private FClient: IHttpClient; FParser: IRSSParser; procedure LoadNews(const ARSSUrl: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var fmNews: TfmNews; implementation uses NetHttpClient, XMLDocRssParser, ShellAPI, Winapi.Windows, FMX.Styles; {$R *.fmx} procedure TfmNews.btnLoadNewsClick(Sender: TObject); begin LoadNews(cmxRssChoice.Items[cmxRssChoice.ItemIndex]); end; constructor TfmNews.Create(AOwner: TComponent); begin inherited; FClient := TOwnNetHttpClient.Create; FParser := TXmlDocParser.Create; end; destructor TfmNews.Destroy; begin FParser := nil; FClient := nil; inherited; end; procedure TfmNews.FormCreate(Sender: TObject); begin // TStyleManager.SetStyleFromFile(TPath.Combine(TPath.GetDirectoryName(ParamStr(0)), 'AquaGraphite.Style')); end; procedure TfmNews.FormShow(Sender: TObject); begin LoadNews(cmxRssChoice.Items[cmxRssChoice.ItemIndex]); end; procedure TfmNews.LoadNews(const ARSSUrl: string); var xml: string; feed: TRSSFeed; i: Integer; item: TListViewItem; begin xml := FClient.GetPageByURL(ARSSUrl); feed := FParser.ParseRSSFeed(xml); try lvRCC.BeginUpdate; try lvRCC.Items.Clear; for i := 0 to feed.Items.Count - 1 do begin item := lvRCC.Items.Add; item.Text := DateTimeToStr(feed.Items[i].PubDate); item.Purpose := TListItemPurpose.Header; item := lvRCC.Items.Add; item.Objects.DrawableByName('Title').Data := feed.Items[i].Title; if not feed.Items[i].Description.IsEmpty then item.Objects.DrawableByName('Description').Data := feed.Items[i].Description; item.TagString := feed.Items[i].Link; end; finally lvRCC.EndUpdate; end; finally feed.DisposeOf; end; end; procedure TfmNews.lvRCCItemClick(const Sender: TObject; const AItem: TListViewItem); begin ShellExecute(FormToHWND(Self), 'open', PChar(AItem.TagString), nil, nil, SW_NORMAL); end; procedure TfmNews.TimerLoadRSSTimer(Sender: TObject); begin LoadNews(cmxRssChoice.Items[cmxRssChoice.ItemIndex]); end; end.
unit AddresslistEditor; { Editor for the addresslist an editor at the location of the value field self: when the enter key is pressed set the new value on the provided memoryrecord when the edit box loses focus apply the change and close the editor (OnEditorClose(sender: Editor)) when escape is pressed, do not apply the change and just close (OnEditorClose) When the edit box is clicked between the create time and create time+GetDoubleClickTime(), return an "OnDoubleclick(sender: Editor)" When doubleclicked return an OnDoubleClick When the up or down key is pressed, apply the change, and send an event that the entry is changed (OnEntryChange(sender: editor; direction)) If a dropdown list is implemented, make this an combobox and feed it the list on creation owner: when the view is scrolled/collapsed/expanded the owner should call UpdatePosition, or destroy the editor(optionally applying the current value) } {$mode delphi} //{$warn 3057 off} interface uses {$ifdef darwin} macport, LCLIntf, LMEssages, messages, {$endif} {$ifdef windows} windows, {$endif} Classes, SysUtils, ComCtrls, Controls, StdCtrls, MemoryRecordUnit, Graphics, LCLType, betterControls; type TAddressListEditor=class(TCustomEdit) private fOnEditorClose: TNotifyEvent; fOnDoubleClick: TNotifyEvent; fmemrec: TMemoryrecord; edited: boolean; starttime: dword; canselect: boolean; protected procedure DoClose; procedure DblClick; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure TextChanged; override; procedure DoExit; override; procedure SetSelStart(Val: integer); override; procedure SetSelLength(Val: integer); override; public procedure UpdatePosition(left: integer); constructor create(owner: TTreeView; memrec: TMemoryrecord; left: integer); overload; destructor destroy; override; published property memrec: TMemoryrecord read fmemrec; property OnEditorClose: TNotifyEvent read fOnEditorClose write fOnEditorClose; property OnDblClick; //: TNotifyEvent read fOnDoubleclick write fOnDoubleClick; end; implementation uses addresslist; procedure TAddressListEditor.SetSelStart(Val: integer); begin if canselect then inherited; //(val) end; procedure TAddressListEditor.SetSelLength(Val: integer); begin if canselect then inherited; //(val) end; procedure TAddressListEditor.DblClick; begin edited:=false; DoClose; inherited DblClick; end; procedure TAddressListEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // if gettickcount<starttime+GetDoubleClickTime then // DblClick // else inherited MouseDown(Button, Shift, X, Y); end; procedure TAddressListEditor.DoClose; begin visible:=false; memrec.endEdit; if assigned(fOnEditorClose) then fOnEditorClose(self); end; procedure TAddressListEditor.KeyDown(var Key: Word; Shift: TShiftState); begin case key of VK_ESCAPE: begin edited:=false; DoClose; end; VK_RETURN: begin edited:=true; DoExit; end; VK_UP: begin DoExit; //send an VK_UP to the owner SendMessage(TTreeView(Owner).Handle, WM_KEYDOWN, VK_UP, 0); TAddresslist(TTreeview(owner).Owner).doValueChange; end; VK_DOWN: begin DoExit; //send an VK_UP to the owner SendMessage(TTreeView(Owner).Handle, WM_KEYDOWN, VK_DOWN, 0); TAddresslist(TTreeview(owner).Owner).doValueChange; end; else inherited KeyDown(Key, Shift); end; end; procedure TAddressListEditor.TextChanged; begin edited:=true; inherited TextChanged; end; procedure TAddressListEditor.DoExit; begin if edited then begin try memrec.Value:=text; edited:=false; except beep; end; DoClose; end else inherited DoExit; end; procedure TAddressListEditor.UpdatePosition(left: integer); var dr: Trect; begin dr:=memrec.treenode.DisplayRect(true); self.height:=dr.Bottom-dr.top; self.top:=dr.top; dr:=memrec.treenode.DisplayRect(false); self.width:=dr.Right-left; end; destructor TAddressListEditor.destroy; begin memrec.endEdit; //jic inherited destroy; end; constructor TAddressListEditor.create(owner: TTreeView; memrec: TMemoryrecord; left: integer); var pt: TPoint; i: integer; begin fmemrec:=memrec; memrec.beginEdit; inherited create(owner); self.autosize:=false; self.BorderStyle:=bsNone; self.Left:=left; self.color:=clHighlight; self.text:=memrec.Value; self.font:=owner.Font; self.Font.Color:=clred; updateposition(left); self.parent:=owner; {$ifdef windows} SendMessage(Handle, EM_SETMARGINS, EC_LEFTMARGIN, 0); {$endif} self.SetFocus; starttime:=GetTickCount; if ((GetKeyState(VK_RETURN) shr 15) and 1)=1 then //if launched with RETURN then select all begin canselect:=true; self.SelectAll; canselect:=false; end else begin pt:=self.ScreenToClient(mouse.cursorpos); pt.x:=owner.Canvas.TextFitInfo(text, pt.x); pt.y:=0; self.SetCaretPos(pt); end; end; end.
unit FormRemoveEspacoModelos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Gauges, StdCtrls, DB, ADODB, SqlExpr, DBXpress, ExtCtrls; type TfrmUtilRemoveEspacoBase = class(TForm) btnCancelar: TButton; progresso: TGauge; Label1: TLabel; Timer1: TTimer; procedure FormShow(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } cancelou: Boolean; function getContagemModelos: Integer; function AtualizaModelos(codigoModelo: Integer; modelos: string): Boolean; public { Public declarations } procedure processarRegistros; procedure removerRegistrosDuplicados; end; var frmUtilRemoveEspacoBase: TfrmUtilRemoveEspacoBase; implementation uses DataModule, Configuracoes, Peca, ADOInt, Modelo; {$R *.dfm} function TfrmUtilRemoveEspacoBase.AtualizaModelos(codigoModelo: Integer; modelos: string): Boolean; begin try try result := false; // aqui dm.qryInserirRelacaoDescritorProduto.SQL.Clear; dm.qryInserirRelacaoDescritorProduto.SQL.ADD('UPDATE ESPEC_PRODUTOS SET DESCRICAO = ' + QuotedStr(modelos)); dm.qryInserirRelacaoDescritorProduto.SQL.ADD(' WHERE ESPEC_PRODUTO = ' + IntToStr(codigoModelo)); // até aqui dm.qryInserirRelacaoDescritorProduto.ExecSQL; result := true; except on e: Exception do begin result := false; raise Exception.Create('Erro ao atualizar a relação do produto a especificação de modelo ' + ': ' + e.Message); end; end; finally // dm.qryInserirRelacaoDescritorProduto.Close; dm.qryInserirRelacaoDescritorProduto.Close; end; end; procedure TfrmUtilRemoveEspacoBase.FormShow(Sender: TObject); begin Application.ProcessMessages; end; function TfrmUtilRemoveEspacoBase.getContagemModelos: Integer; var retorno: Integer; begin retorno := 0; try DM.qryModeloContagem.Close; DM.qryModeloContagem.SQL.Clear; DM.qryModeloContagem.SQL.Text := 'SELECT COUNT(ESPEC_PRODUTO) AS CONTAGEM FROM ESPEC_PRODUTOS WHERE ESPECIFICACAO = 7 AND DESCRICAO IS NOT NULL'; DM.qryModeloContagem.Open; if DM.qryModeloContagem.IsEmpty then retorno := 0 else retorno := DM.qryModeloContagem.fieldbyname('CONTAGEM').AsInteger; Result := retorno; finally DM.qryModeloContagem.Close; end; end; procedure TfrmUtilRemoveEspacoBase.btnCancelarClick(Sender: TObject); begin cancelou := True; end; procedure TfrmUtilRemoveEspacoBase.FormClose(Sender: TObject; var Action: TCloseAction); begin DM.DesconectarFirebird; Action := caFree; end; procedure TfrmUtilRemoveEspacoBase.FormCreate(Sender: TObject); begin DM.ConectarFirebird(Configuracao.Servidor, Configuracao.banco, Configuracao.Usuario, Configuracao.Senha); end; procedure TfrmUtilRemoveEspacoBase.processarRegistros; var nrRegs: Integer; index: Integer; listaModelos: TStringList; Trans: TTransactionDesc; begin Self.Show; try try Timer1.Enabled := False; nrRegs := getContagemModelos; progresso.MaxValue := nrRegs; progresso.MinValue := 0; index := 0; Screen.Cursor := crHourGlass; DM.qryObterTodosModelosDB.Close; DM.qryObterTodosModelosDB.SQL.Clear; DM.qryObterTodosModelosDB.SQL.Text := 'SELECT ESPEC_PRODUTO, DESCRICAO FROM ESPEC_PRODUTOS WHERE ESPECIFICACAO = 7 AND DESCRICAO IS NOT NULL'; DM.qryObterTodosModelosDB.Open; DM.qryObterTodosModelosDB.First; while not DM.qryObterTodosModelosDB.Eof do begin if (cancelou) then begin Screen.Cursor := crDefault; if (MessageDlg('Cancelar o processamento dos modelos?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin Exit; end; end else begin cancelou := False; Screen.Cursor := crHourGlass; end; inc(index); Trans.TransactionID := 1; Trans.IsolationLevel := xilREADCOMMITTED; progresso.Progress := index; listaModelos := TStringList.Create; listaModelos.CommaText := trim(DM.qryObterTodosModelosDB.fieldbyname('DESCRICAO').AsString); listaModelos.Delimiter := ','; Application.ProcessMessages; DM.dbFirebird.StartTransaction(Trans); AtualizaModelos(DM.qryObterTodosModelosDB.fieldbyname('ESPEC_PRODUTO').AsInteger, listaModelos.CommaText); DM.dbFirebird.Commit(Trans); FreeAndNil(listaModelos); DM.qryObterTodosModelosDB.Next; Application.ProcessMessages; end; ShowMessage('Registros atualizados com sucesso!'); Close; except on e: Exception do begin raise Exception.Create('Erro ao atualizar a relação do produto a especificação de modelo ' + ': ' + e.Message); end; end; finally DM.qryObterTodosModelosDB.Close; Screen.Cursor := crDefault; end; end; procedure TfrmUtilRemoveEspacoBase.Timer1Timer(Sender: TObject); begin processarRegistros; end; procedure TfrmUtilRemoveEspacoBase.removerRegistrosDuplicados; var nrRegs: Integer; index, interador: Integer; listaModelos, listaGrava: TStringList; Trans: TTransactionDesc; begin Self.Show; try try Timer1.Enabled := False; nrRegs := getContagemModelos; progresso.MaxValue := nrRegs; progresso.MinValue := 0; index := 0; Screen.Cursor := crHourGlass; DM.qryObterTodosModelosDB.Close; DM.qryObterTodosModelosDB.SQL.Clear; DM.qryObterTodosModelosDB.SQL.Text := 'SELECT ESPEC_PRODUTO, DESCRICAO FROM ESPEC_PRODUTOS WHERE ESPECIFICACAO = 7 AND DESCRICAO IS NOT NULL'; DM.qryObterTodosModelosDB.Open; DM.qryObterTodosModelosDB.First; while not DM.qryObterTodosModelosDB.Eof do begin if (cancelou) then begin Screen.Cursor := crDefault; if (MessageDlg('Cancelar o processamento dos modelos?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin Exit; end; end else begin cancelou := False; Screen.Cursor := crHourGlass; end; inc(index); Trans.TransactionID := 1; Trans.IsolationLevel := xilREADCOMMITTED; progresso.Progress := index; listaModelos := TStringList.Create; listaModelos.CommaText := trim(DM.qryObterTodosModelosDB.fieldbyname('DESCRICAO').AsString); listaModelos.Delimiter := ','; listaGrava := TStringList.Create; for interador := 0 to pred(listaModelos.Count) do begin if listaGrava.IndexOf(listaModelos.Strings[interador]) = -1 then listaGrava.Add(listaModelos.Strings[interador]); end; Application.ProcessMessages; if listaGrava.Count > 0 then begin DM.dbFirebird.StartTransaction(Trans); AtualizaModelos(DM.qryObterTodosModelosDB.fieldbyname('ESPEC_PRODUTO').AsInteger, listaGrava.CommaText); DM.dbFirebird.Commit(Trans); end; FreeAndNil(listaModelos); FreeAndNil(listaGrava); DM.qryObterTodosModelosDB.Next; Application.ProcessMessages; end; ShowMessage('Registros atualizados com sucesso!'); Close; except on e: Exception do begin raise Exception.Create('Erro ao atualizar a relação do produto a especificação de modelo ' + ': ' + e.Message); end; end; finally DM.qryObterTodosModelosDB.Close; Screen.Cursor := crDefault; 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>) @author(Skype : ispinheiro) @abstract(Website : http://www.ormbr.com.br) @abstract(Telagram : https://t.me/ormbr) } unit dbcbr.mapping.explorer; interface uses DB, Rtti, Classes, TypInfo, SysUtils, Generics.Collections, /// DBCBr dbcbr.rtti.helper, dbcbr.mapping.classes, dbcbr.mapping.popular, dbcbr.mapping.repository, dbcbr.mapping.register; type TMappingExplorer = class private class var FContext: TRttiContext; FRepositoryMapping: TMappingRepository; FPopularMapping: TMappingPopular; FTableMapping: TDictionary<string, TTableMapping>; FOrderByMapping: TDictionary<string, TOrderByMapping>; FSequenceMapping: TDictionary<string, TSequenceMapping>; FPrimaryKeyMapping: TDictionary<string, TPrimaryKeyMapping>; FForeingnKeyMapping: TDictionary<string, TForeignKeyMappingList>; FIndexeMapping: TDictionary<string, TIndexeMappingList>; FCheckMapping: TDictionary<string, TCheckMappingList>; FColumnMapping: TDictionary<string, TColumnMappingList>; FCalcFieldMapping: TDictionary<string, TCalcFieldMappingList>; FAssociationMapping: TDictionary<string, TAssociationMappingList>; FJoinColumnMapping: TDictionary<string, TJoinColumnMappingList>; FTriggerMapping: TDictionary<string, TTriggerMappingList>; FViewMapping: TDictionary<string, TViewMapping>; FEnumerationMapping: TDictionary<string, TEnumerationMappingList>; FFieldEventsMapping: TDictionary<string, TFieldEventsMappingList>; FPrimaryKeyColumnsMapping: TDictionary<string, TPrimaryKeyColumnsMapping>; // FLazyLoadMapping: TDictionary<string, TLazyMapping>; FNotServerUse: TDictionary<string, Boolean>; class procedure ExecuteCreate; class procedure ExecuteDestroy; public { Public declarations } class function GetMappingTable(const AClass: TClass): TTableMapping; inline; class function GetMappingOrderBy(const AClass: TClass): TOrderByMapping; inline; class function GetMappingSequence(const AClass: TClass): TSequenceMapping; inline; class function GetMappingPrimaryKey(const AClass: TClass): TPrimaryKeyMapping; inline; class function GetMappingForeignKey(const AClass: TClass): TForeignKeyMappingList; inline; class function GetMappingColumn(const AClass: TClass): TColumnMappingList; inline; class function GetMappingCalcField(const AClass: TClass): TCalcFieldMappingList; inline; class function GetMappingAssociation(const AClass: TClass): TAssociationMappingList; inline; class function GetMappingJoinColumn(const AClass: TClass): TJoinColumnMappingList; inline; class function GetMappingIndexe(const AClass: TClass): TIndexeMappingList; inline; class function GetMappingCheck(const AClass: TClass): TCheckMappingList; inline; class function GetMappingTrigger(const AClass: TClass): TTriggerMappingList; inline; class function GetMappingView(const AClass: TClass): TViewMapping; inline; class function GetMappingFieldEvents(const AClass: TClass): TFieldEventsMappingList; inline; class function GetMappingEnumeration(const AClass: TClass): TEnumerationMappingList; inline; class function GetMappingPrimaryKeyColumns(const AClass: TClass): TPrimaryKeyColumnsMapping; inline; class function GetNotServerUse(const AClass: TClass): Boolean; inline; class function GetRepositoryMapping: TMappingRepository; inline; // class procedure GetMappingLazy(const AClass: TClass); end; implementation { TMappingExplorer } class procedure TMappingExplorer.ExecuteCreate; begin FContext := TRttiContext.Create; FPopularMapping := TMappingPopular.Create; FTableMapping := TObjectDictionary<string, TTableMapping>.Create([doOwnsValues]); FOrderByMapping := TObjectDictionary<string, TOrderByMapping>.Create([doOwnsValues]); FSequenceMapping := TObjectDictionary<string, TSequenceMapping>.Create([doOwnsValues]); FPrimaryKeyMapping := TObjectDictionary<string, TPrimaryKeyMapping>.Create([doOwnsValues]); FForeingnKeyMapping := TObjectDictionary<string, TForeignKeyMappingList>.Create([doOwnsValues]); FColumnMapping := TObjectDictionary<string, TColumnMappingList>.Create([doOwnsValues]); FCalcFieldMapping := TObjectDictionary<string, TCalcFieldMappingList>.Create([doOwnsValues]); FAssociationMapping := TObjectDictionary<string, TAssociationMappingList>.Create([doOwnsValues]); FJoinColumnMapping := TObjectDictionary<string, TJoinColumnMappingList>.Create([doOwnsValues]); FIndexeMapping := TObjectDictionary<string, TIndexeMappingList>.Create([doOwnsValues]); FCheckMapping := TObjectDictionary<string, TCheckMappingList>.Create([doOwnsValues]); FTriggerMapping := TObjectDictionary<string, TTriggerMappingList>.Create([doOwnsValues]); FViewMapping := TObjectDictionary<string, TViewMapping>.Create([doOwnsValues]); FFieldEventsMapping := TObjectDictionary<string, TFieldEventsMappingList>.Create([doOwnsValues]); FEnumerationMapping := TObjectDictionary<string, TEnumerationMappingList>.Create([doOwnsValues]); // FLazyLoadMapping := TObjectDictionary<string, TLazyMapping>.Create([doOwnsValues]); FPrimaryKeyColumnsMapping := TObjectDictionary<string, TPrimaryKeyColumnsMapping>.Create([doOwnsValues]); FNotServerUse := TDictionary<string, Boolean>.Create; end; class procedure TMappingExplorer.ExecuteDestroy; begin FContext.Free; FPopularMapping.Free; FTableMapping.Free; FOrderByMapping.Free; FSequenceMapping.Free; FPrimaryKeyMapping.Free; FForeingnKeyMapping.Free; FColumnMapping.Free; FCalcFieldMapping.Free; FAssociationMapping.Free; FJoinColumnMapping.Free; FIndexeMapping.Free; FTriggerMapping.Free; FCheckMapping.Free; FViewMapping.Free; FFieldEventsMapping.Free; FEnumerationMapping.Free; // FLazyLoadMapping.Free; FPrimaryKeyColumnsMapping.Free; FNotServerUse.Free; if Assigned(FRepositoryMapping) then FRepositoryMapping.Free; end; class function TMappingExplorer.GetMappingPrimaryKey( const AClass: TClass): TPrimaryKeyMapping; var LRttiType: TRttiType; begin if FPrimaryKeyMapping.ContainsKey(AClass.ClassName) then Exit(FPrimaryKeyMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularPrimaryKey(LRttiType); // Add List FPrimaryKeyMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingPrimaryKeyColumns( const AClass: TClass): TPrimaryKeyColumnsMapping; var LRttiType: TRttiType; begin if FPrimaryKeyColumnsMapping.ContainsKey(AClass.ClassName) then Exit(FPrimaryKeyColumnsMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularPrimaryKeyColumns(LRttiType, AClass); // Add List FPrimaryKeyColumnsMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingSequence( const AClass: TClass): TSequenceMapping; var LRttiType: TRttiType; begin if FSequenceMapping.ContainsKey(AClass.ClassName) then Exit(FSequenceMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularSequence(LRttiType); // Add List FSequenceMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingCalcField( const AClass: TClass): TCalcFieldMappingList; var LRttiType: TRttiType; begin if FCalcFieldMapping.ContainsKey(AClass.ClassName) then Exit(FCalcFieldMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularCalcField(LRttiType); // Add List FCalcFieldMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingCheck( const AClass: TClass): TCheckMappingList; var LRttiType: TRttiType; begin if FCheckMapping.ContainsKey(AClass.ClassName) then Exit(FCheckMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularCheck(LRttiType); // Add List FCheckMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingColumn(const AClass: TClass): TColumnMappingList; var LRttiType: TRttiType; begin if FColumnMapping.ContainsKey(AClass.ClassName) then Exit(FColumnMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularColumn(LRttiType, AClass); // Add List FColumnMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingEnumeration( const AClass: TClass): TEnumerationMappingList; var LRttiType: TRttiType; begin if FEnumerationMapping.ContainsKey(AClass.ClassName) then Exit(FEnumerationMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularEnumeration(LRttiType); // Add List FEnumerationMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingFieldEvents( const AClass: TClass): TFieldEventsMappingList; var LRttiType: TRttiType; begin if FFieldEventsMapping.ContainsKey(AClass.ClassName) then Exit(FFieldEventsMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularFieldEvents(LRttiType); // Add List FFieldEventsMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingForeignKey( const AClass: TClass): TForeignKeyMappingList; var LRttiType: TRttiType; begin if FForeingnKeyMapping.ContainsKey(AClass.ClassName) then Exit(FForeingnKeyMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularForeignKey(LRttiType); // Add List FForeingnKeyMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingIndexe( const AClass: TClass): TIndexeMappingList; var LRttiType: TRttiType; begin if FIndexeMapping.ContainsKey(AClass.ClassName) then Exit(FIndexeMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularIndexe(LRttiType); // Add List FIndexeMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingJoinColumn( const AClass: TClass): TJoinColumnMappingList; var LRttiType: TRttiType; begin if FJoinColumnMapping.ContainsKey(AClass.ClassName) then Exit(FJoinColumnMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularJoinColumn(LRttiType); // Add List FJoinColumnMapping.Add(AClass.ClassName, Result); end; //class procedure TMappingExplorer.GetMappingLazy(const AClass: TClass); //var // LRttiType: TRttiType; // LFieldName: String; // LField: TRttiField; //begin // LRttiType := FContext.GetType(AClass); // for LField in LRttiType.GetFields do // begin // if LField.IsLazy then // GetMappingLazy(LField.GetLazyValue.AsInstance.MetaclassType) // else // if LField.FieldType.TypeKind = tkClass then // GetMappingLazy(LField.GetTypeValue.AsInstance.MetaclassType) // else // Continue; // LFieldName := 'T' + LField.FieldType.Handle.NameFld.ToString; // FLazyLoadMapping.Add(LFieldName, TLazyMapping.Create(LField)); // end; //end; class function TMappingExplorer.GetMappingOrderBy( const AClass: TClass): TOrderByMapping; var LRttiType: TRttiType; begin if FOrderByMapping.ContainsKey(AClass.ClassName) then Exit(FOrderByMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularOrderBy(LRttiType); // Add List FOrderByMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingAssociation( const AClass: TClass): TAssociationMappingList; var LRttiType: TRttiType; begin if FAssociationMapping.ContainsKey(AClass.ClassName) then Exit(FAssociationMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularAssociation(LRttiType); // Add List FAssociationMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingTable( const AClass: TClass): TTableMapping; var LRttiType: TRttiType; begin if FTableMapping.ContainsKey(AClass.ClassName) then Exit(FTableMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularTable(LRttiType); // Add List FTableMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingTrigger( const AClass: TClass): TTriggerMappingList; var LRttiType: TRttiType; begin if FTriggerMapping.ContainsKey(AClass.ClassName) then Exit(FTriggerMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularTrigger(LRttiType); // Add List FTriggerMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetMappingView( const AClass: TClass): TViewMapping; var LRttiType: TRttiType; begin if FViewMapping.ContainsKey(AClass.ClassName) then Exit(FViewMapping[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularView(LRttiType); // Add List FViewMapping.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetNotServerUse(const AClass: TClass): Boolean; var LRttiType: TRttiType; begin if FNotServerUse.ContainsKey(AClass.ClassName) then Exit(FNotServerUse[AClass.ClassName]); LRttiType := FContext.GetType(AClass); Result := FPopularMapping.PopularNotServerUse(LRttiType); // Add List FNotServerUse.Add(AClass.ClassName, Result); end; class function TMappingExplorer.GetRepositoryMapping: TMappingRepository; begin if not Assigned(FRepositoryMapping) then FRepositoryMapping := TMappingRepository.Create(TRegisterClass.GetAllEntityClass, TRegisterClass.GetAllViewClass); Result := FRepositoryMapping; end; initialization TMappingExplorer.ExecuteCreate; finalization TMappingExplorer.ExecuteDestroy; end.
unit FStruct; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, StdCtrls, SetForm, TSigmaForm; type TCellDrag = record BeginCol : integer; BeginRow : integer; EndCol : integer; EndRow : integer; end; TStringGridHack = class(TStringGrid) public procedure MoveColumn(FromIndex, ToIndex: Longint); procedure MoveRow(FromIndex, ToIndex: Longint); end; TfrmZoneStruct = class(TForm) stgZones: TStringGrid; btnClose: TButton; procedure btnCloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure stgZonesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure stgZonesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure stgZonesGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure stgZonesSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure stgZonesKeyPress(Sender: TObject; var Key: Char); procedure FormActivate(Sender: TObject); private { Private declarations } public ZoneInfo : TZoneInfo; ZoneCount : integer; { Public declarations } end; var frmZoneStruct: TfrmZoneStruct; ColDrag : Boolean; CellDrag : TCellDrag; One,Two : String; implementation {$R *.dfm} procedure TStringGridHack.MoveColumn(FromIndex, ToIndex: Integer); begin inherited; end; procedure TStringGridHack.MoveRow(FromIndex, ToIndex: Integer); begin inherited; end; // Нажатие кнопки "Закрыть" procedure TfrmZoneStruct.btnCloseClick(Sender: TObject); begin Close; end; // Процедура на событие закрытия формы procedure TfrmZoneStruct.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; frmZoneStruct := nil; end; // Отображение таблицы со структурой зон procedure TfrmZoneStruct.FormShow(Sender: TObject); var i, j : integer; begin stgZones.RowCount := ZoneCount+1; stgZones.Rows[0].Text := 'Зона'; stgZones.ColCount := 10; for i:=1 to 8 do begin stgZones.Rows[0].Add('Узел '+IntToStr(i)); end; stgZones.Rows[0].Add('Площадь'); stgZones.ColWidths[9] := 50; for j:=1 to ZoneCount+1 do begin stgZones.Rows[j].Text := IntToStr(ZoneInfo[j-1].ZoneNum+1); for i:=1 to 8 do begin stgZones.Rows[j].Add(IntToStr(ZoneInfo[j-1].NodesNum[i-1])); end; stgZones.Rows[j].Add(FloatToStr(ZoneInfo[j-1].ZoneS)); end; end; procedure TfrmZoneStruct.stgZonesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var col,row:integer; begin stgZones.MouseToCell(x,y,col,row); if (col = 0) and (row<>0 ) and (ColDrag=false) then begin ColDrag:=true; CellDrag.BeginRow:=row; Screen.Cursor:=crDrag; end; end; procedure TfrmZoneStruct.stgZonesMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var col,row:integer; begin stgZones.MouseToCell(x,y,col,row); CellDrag.EndRow:=Row; if ColDrag=true then begin try if (CellDrag.BeginRow<>CellDrag.EndRow) and (CellDrag.EndRow<>0) then begin AddBeckUp; TStringGridHack(stgZones).Moverow(CellDrag.BeginRow,CellDrag.EndRow); Form_SwapZone(CellDrag.BeginRow-1,CellDrag.EndRow-1); SetForm1.UpdateVizParams; SetForm1.MainRePaint; GetZoneInfo(ZoneInfo,ZoneCount); frmZoneStruct.FormShow(frmZoneStruct); end; except end; ColDrag:=false; end; Screen.Cursor:=crDefault; end; procedure TfrmZoneStruct.stgZonesGetEditText(Sender: TObject; ACol, ARow: Integer; var Value: String); begin one:=Value; end; procedure TfrmZoneStruct.stgZonesSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); begin two:=Value; end; procedure TfrmZoneStruct.stgZonesKeyPress(Sender: TObject; var Key: Char); var n,m : word; t: TNode; begin if key=#13 then begin N:=strtoint(One); M:=strtoint(Two); if Form_GetNodeValue(M).Number>0 then begin AddBeckUp; Form_SetNodeNumber(Form_GetNodeValue(M).Number,999); Form_SetNodeNumber(N,M); Form_SetNodeNumber(999,N); end else begin AddBeckUp; Form_SetNodeNumber(N,M); end; SetForm1.UpdateVizParams; SetForm1.MainRePaint; GetZoneInfo(ZoneInfo,ZoneCount); frmZoneStruct.FormShow(frmZoneStruct); end else if not (key in ['0'..'9']) then key:=#0; end; procedure TfrmZoneStruct.FormActivate(Sender: TObject); begin SetForm1.UpdateVizParams; SetForm1.MainRePaint; GetZoneInfo(ZoneInfo,ZoneCount); frmZoneStruct.FormShow(frmZoneStruct); end; end.
unit uRavenConnection; interface uses SysUtils, Variants, Classes ,DateUtils, IdBaseComponent,Generics.Collections,Generics.Defaults, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP,uEvent; const SENTRY_CLIENT = 'raven-delphi/1.0'; USER_AGENT = 'User-Agent'; SENTRY_AUTH = 'X-Sentry-Auth'; DEFAULT_TIMEOUT = 5000; type TRavenConnection = class(TComponent) FIndyClient:TIdHTTP; private sentry_version:string; FDsn:string; FPublicKey:String; FSecretKey:String; FProjecID:String; private procedure setHeader(); public procedure setVersion(_version:string); procedure setDsn(_dsn:string); procedure setPublicKey(_public_key:string); procedure setSecretKey(_secret_key:string); procedure setProjectId(_project_id:string); constructor Create(AOwner: TComponent); override; destructor Destroy; override; property DNS: string read FDsn write setDsn; property PublicKey: string read FPublicKey write setPublicKey; property SecretKey: string read FSecretKey write setSecretKey; property ProjectID: string read FProjecID write setProjectId; function send(_event:BaseEvent):string; function test():string; end; implementation { TRavenClient } constructor TRavenConnection.Create(AOwner: TComponent); begin inherited; FIndyClient := TIdHTTP.Create(self); FIndyClient.Request.CustomHeaders.Values[USER_AGENT] := SENTRY_CLIENT; FIndyClient.Request.CustomHeaders.Values['Content-Encoding'] := 'application/json'; FIndyClient.Request.CustomHeaders.Values['Content-Type'] := 'application/octet-stream'; end; destructor TRavenConnection.Destroy; begin if FIndyClient <> nil then FreeAndNil(FIndyClient); inherited; end; function TRavenConnection.send(_event: BaseEvent):string; var send_stream:TStringStream; begin setHeader; send_stream := TStringStream.Create(_event.ToString); Result := FIndyClient.Post(FDsn,send_stream); end; procedure TRavenConnection.setDsn(_dsn:string); begin self.FDsn := _dsn; end; procedure TRavenConnection.setHeader; var sentry_header : string; begin sentry_header := ''; sentry_header := sentry_header+'Sentry sentry_version='+sentry_version+','; sentry_header := sentry_header+'sentry_client='+SENTRY_CLIENT+','; sentry_header := sentry_header+'sentry_timestamp=' +IntToStr(DateTimeToUnix(Now))+','; sentry_header := sentry_header+'sentry_key='+FPublicKey+ ','; sentry_header := sentry_header+'sentry_secret='+FSecretKey+ ''; FIndyClient.Request.CustomHeaders.Values[SENTRY_AUTH] := sentry_header; end; procedure TRavenConnection.setProjectId(_project_id: string); begin Self.FProjecID := _project_id; end; procedure TRavenConnection.setPublicKey(_public_key: string); begin self.FPublicKey :=_public_key; end; procedure TRavenConnection.setSecretKey(_secret_key: string); begin Self.FSecretKey := _secret_key; end; procedure TRavenConnection.setVersion(_version: string); begin self.sentry_version := _version; end; function TRavenConnection.test: string; begin end; end.
var i: Integer; MainGrid: TNDBGrid; DataSet: TDataSet; Field: DB.TField; Info: uDocInfo.TDocInfo; begin for i := 0 to ComponentCount - 1 do if (Components[i] is TNDBGrid) then Break; MainGrid := (Components[i] as TNDBGrid); DataSet := MainGrid.DataSource.DataSet; Info.ProviderName := ''; if (DataSet is TNDataSet) then Info.ProviderName := (DataSet as TNDataSet).DataStore.ProviderName; SetLength(Info.Fields, DataSet.Fields.Count); for i := 0 to DataSet.Fields.Count - 1 do with DataSet.Fields do begin Field := Fields[i]; Info.Fields[i].Name := Field.FieldName; Info.Fields[i].Caption := Field.DisplayName; Info.Fields[i].KeyFields := Field.KeyFields; Info.Fields[i].LookupKeyFields := Field.LookupKeyFields; Info.Fields[i].LookupResultField := Field.LookupResultField; if (Field is TStringField) then Info.Fields[i].FieldType := FT_STRING else if (Field is TDateField) or (Field is TDateTimeField) then Info.Fields[i].FieldType := FT_DATE else if (Field is TLargeintField) or (Field is TIntegerField) then Info.Fields[i].FieldType := FT_LONG else if (Field is TBCDField) then Info.Fields[i].FieldType := FT_MONEY else Info.Fields[i].FieldType := FT_NONE; end; TInfoForm.CreateAndShow(Info); end;
unit UnitDemoSceneConstraintVehicle; {$MODE Delphi} interface uses LCLIntf,LCLType,LMessages,Math,Kraft,UnitDemoScene; type TDemoSceneConstraintVehicle=class(TDemoScene) public RigidBodyFloor:TKraftRigidBody; ShapeFloorPlane:TKraftShapePlane; ChassisRigidBody:TKraftRigidBody; WheelRigidBodies:array[0..1,0..1] of TKraftRigidBody; WheelHingeJointConstraints:array[0..1,0..1] of TKraftConstraintJointHinge; CarSteering:double; CarSpeed:double; Time:double; InputKeyLeft,InputKeyRight,InputKeyUp,InputKeyDown,InputKeyBrake,InputKeyHandBrake:boolean; constructor Create(const AKraftPhysics:TKraft); override; destructor Destroy; override; procedure Step(const DeltaTime:double); override; procedure DebugDraw; override; function HasOwnKeyboardControls:boolean; override; procedure KeyDown(const aKey:Int32); override; procedure KeyUp(const aKey:Int32); override; function UpdateCamera(var aCameraPosition:TKraftVector3;var aCameraOrientation:TKraftQuaternion):boolean; override; procedure StoreWorldTransforms; override; procedure InterpolateWorldTransforms(const aAlpha:TKraftScalar); override; end; implementation uses UnitFormMain; const CarWidth=2.0; CarLength=4.0; CarHalfWidth=CarWidth*0.5; CountDominos=64; CountStreetElevations=64; CountWheelVertices=128; JumpingRampWidth=16.0; JumpingRampHeight=16.0; JumpingRampLength=64.0; JumpingRampHalfWidth=JumpingRampWidth*0.5; JumpingRampHalfHeight=JumpingRampHeight*0.5; JumpingRampHalfLength=JumpingRampLength*0.5; JumpingRampConvexHullPoints:array[0..5] of TKraftVector3=((x:-JumpingRampHalfWidth;y:0.0;z:0{$ifdef SIMD};w:0.0{$endif}), (x:JumpingRampHalfWidth;y:0.0;z:0{$ifdef SIMD};w:0.0{$endif}), (x:-JumpingRampHalfWidth;y:JumpingRampHeight;z:0.0{$ifdef SIMD};w:0.0{$endif}), (x:JumpingRampHalfWidth;y:JumpingRampHeight;z:0.0{$ifdef SIMD};w:0.0{$endif}), (x:-JumpingRampHalfWidth;y:0.0;z:JumpingRampLength{$ifdef SIMD};w:0.0{$endif}), (x:JumpingRampHalfWidth;y:0.0;z:JumpingRampLength{$ifdef SIMD};w:0.0{$endif}));{} constructor TDemoSceneConstraintVehicle.Create(const AKraftPhysics:TKraft); const WheelPositions:array[0..1,0..1] of TKraftVector3=(((x:CarHalfWidth;y:0.75;z:-CarLength), (x:-CarHalfWidth;y:0.75;z:-CarLength)), ((x:CarHalfWidth;y:0.75;z:0.0), (x:-CarHalfWidth;y:0.75;z:0.0))); var Index,x,y:longint; Shape:TKraftShape; ConvexHull, onvexHull:TKraftConvexHull; RigidBody:TKraftRigidBody; t,s,c:TKraftScalar; begin inherited Create(AKraftPhysics); CarSteering:=0.0; Time:=0.0; RigidBodyFloor:=TKraftRigidBody.Create(KraftPhysics); RigidBodyFloor.SetRigidBodyType(krbtSTATIC); ShapeFloorPlane:=TKraftShapePlane.Create(KraftPhysics,RigidBodyFloor,Plane(Vector3Norm(Vector3(0.0,1.0,0.0)),0.0)); ShapeFloorPlane.Restitution:=0.3; RigidBodyFloor.Finish; RigidBodyFloor.SetWorldTransformation(Matrix4x4Translate(0.0,0.0,0.0)); RigidBodyFloor.CollisionGroups:=[0]; begin ConvexHull:=TKraftConvexHull.Create(KraftPhysics); ConvexHullGarbageCollector.Add(ConvexHull); ConvexHull.Load(pointer(@JumpingRampConvexHullPoints),length(JumpingRampConvexHullPoints)); ConvexHull.Build; ConvexHull.Finish; for Index:=1 to 4 do begin RigidBody:=TKraftRigidBody.Create(KraftPhysics); RigidBody.SetRigidBodyType(krbtSTATIC); Shape:=TKraftShapeConvexHull.Create(KraftPhysics,RigidBody,ConvexHull); Shape.Restitution:=0.3; Shape.Density:=1.0; Shape.Friction:=1.0; RigidBody.Finish; RigidBody.SetWorldTransformation(Matrix4x4Translate(0.0,0.0,-((JumpingRampLength+(CarLength*2.0)))*Index)); RigidBody.CollisionGroups:=[0]; end; for Index:=1 to 4 do begin RigidBody:=TKraftRigidBody.Create(KraftPhysics); RigidBody.SetRigidBodyType(krbtSTATIC); Shape:=TKraftShapeConvexHull.Create(KraftPhysics,RigidBody,ConvexHull); Shape.Restitution:=0.3; Shape.Density:=1.0; Shape.Friction:=1.0; RigidBody.Finish; RigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4RotateY(PI),Matrix4x4Translate(-(JumpingRampWidth+(CarWidth*2.0)),0.0,-((JumpingRampLength+(CarLength*2.0)))*Index))); RigidBody.CollisionGroups:=[0]; end; end; begin // Dominos for Index:=0 to CountDominos-1 do begin RigidBody:=TKraftRigidBody.Create(KraftPhysics); RigidBody.SetRigidBodyType(krbtDYNAMIC); Shape:=TKraftShapeBox.Create(KraftPhysics,RigidBody,Vector3(0.125,1.0,0.5)); Shape.Restitution:=0.4; Shape.Density:=1.0; RigidBody.ForcedMass:=1.0; RigidBody.Finish; RigidBody.SetWorldTransformation(Matrix4x4TermMul(Matrix4x4TermMul(Matrix4x4Translate(0.0,TKraftShapeBox(Shape).Extents.y,-8.0-((Index/CountDominos)*4.0)),Matrix4x4RotateY((Index-((CountDominos-1)*0.5))*(pi/CountDominos)*2.0)),Matrix4x4Translate(JumpingRampWidth+(CarWidth*4),0.0,-12.0))); RigidBody.CollisionGroups:=[0,1]; // RigidBody.Gravity.Vector:=Vector3(0.0,-9.81*4.0,0.0); // RigidBody.Flags:=RigidBody.Flags+[krbfHasOwnGravity]; end; end;//} {}begin // Street elevations for Index:=0 to CountStreetElevations-1 do begin RigidBody:=TKraftRigidBody.Create(KraftPhysics); RigidBody.SetRigidBodyType(krbtSTATIC); Shape:=TKraftShapeCapsule.Create(KraftPhysics,RigidBody,0.25,16); Shape.Restitution:=0.4; Shape.Density:=1.0; RigidBody.ForcedMass:=1.0; RigidBody.Finish; RigidBody.SetWorldTransformation(Matrix4x4TermMul( Matrix4x4RotateZ(PI*0.5), Matrix4x4Translate(-(JumpingRampWidth+(CarWidth*4)),0.0,-(12.0+(Index*0.75))) ) ); RigidBody.CollisionGroups:=[0]; end; end;//} begin ChassisRigidBody:=TKraftRigidBody.Create(KraftPhysics); ChassisRigidBody.SetRigidBodyType(krbtDYNAMIC); Shape:=TKraftShapeBox.Create(KraftPhysics,ChassisRigidBody,Vector3(1.0,1.0,3.0)); Shape.Restitution:=0.3; Shape.Density:=10.0; Shape.LocalTransform:=Matrix4x4Translate(0.0,1.0,0.0); ChassisRigidBody.Finish; ChassisRigidBody.SetWorldTransformation(Matrix4x4Translate(0.0,1.25,-2.0)); ChassisRigidBody.CollisionGroups:=[1]; ChassisRigidBody.AngularVelocityDamp:=10.0; ChassisRigidBody.LinearVelocityDamp:=0.05; end; {ConvexHull:=TKraftConvexHull.Create(KraftPhysics); ConvexHullGarbageCollector.Add(ConvexHull); for y:=0 to CountWheelVertices-1 do begin t:=(y/(CountWheelVertices-1))*PI*2.0; SinCos(t,s,c); s:=s*0.75; c:=c*0.75; ConvexHull.AddVertex(Vector3(-0.5,s,c)); ConvexHull.AddVertex(Vector3(0.5,s,c)); end; ConvexHull.Build; ConvexHull.Finish;} for y:=0 to 1 do begin for x:=0 to 1 do begin WheelRigidBodies[y,x]:=TKraftRigidBody.Create(KraftPhysics); WheelRigidBodies[y,x].SetRigidBodyType(krbtDYNAMIC); // Shape:=TKraftShapeConvexHull.Create(KraftPhysics,WheelRigidBodies[y,x],ConvexHull); Shape:=TKraftShapeSphere.Create(KraftPhysics,WheelRigidBodies[y,x],0.75); Shape.Restitution:=0.3; Shape.Density:=1.0; Shape.Friction:=10.0; WheelRigidBodies[y,x].Finish; WheelRigidBodies[y,x].SetWorldTransformation(Matrix4x4Translate(WheelPositions[y,x])); WheelRigidBodies[y,x].CollisionGroups:=[1]; WheelRigidBodies[y,x].AngularVelocityDamp:=1.0; WheelRigidBodies[y,x].LinearVelocityDamp:=0.05; WheelRigidBodies[y,x].MaximalAngularVelocity:=0.25; WheelHingeJointConstraints[y,x]:=TKraftConstraintJointHinge.Create(KraftPhysics, ChassisRigidBody, WheelRigidBodies[y,x], WheelPositions[y,x], Vector3Norm(Vector3(1.0,0.0,0.0)), false, false, -1.0, 1.0, 1.0, 0.0, false); end; end; InputKeyLeft:=false; InputKeyRight:=false; InputKeyUp:=false; InputKeyDown:=false; InputKeyBrake:=false; InputKeyHandBrake:=false; end; destructor TDemoSceneConstraintVehicle.Destroy; begin inherited Destroy; end; procedure TDemoSceneConstraintVehicle.Step(const DeltaTime:double); const Signs:array[0..1] of longint=(1,-1); MaxAngle=32.0*DEG2RAD; var x,y:longint; CarAngle,Radius:double; SideRadius:array[0..1] of single; AxisVectors:array[0..1,0..1] of TKraftVector3; NeedBeAwake:boolean; WorldTransform:TKraftMatrix4x4; WorldLeft,WorldRight,WorldUp,WorldDown,WorldForward,WorldBackward,WorldPosition, HitPoint,HitNormal,KeepUpNormal,Axis,NewUp,Delta,Force:TKraftVector3; HitTime,Angle:TKraftScalar; HitShape:TKraftShape; SourceQuaternion,TargetQuaternion,DifferenceQuaternion:TKraftQuaternion; begin Time:=Time+DeltaTime; WorldTransform:=ChassisRigidBody.WorldTransform; WorldRight:=PKraftVector3(pointer(@WorldTransform[0,0]))^; WorldLeft:=Vector3Neg(WorldRight); WorldUp:=PKraftVector3(pointer(@WorldTransform[1,0]))^; WorldDown:=Vector3Neg(WorldUp); WorldForward:=PKraftVector3(pointer(@WorldTransform[2,0]))^; WorldBackward:=Vector3Neg(WorldForward); WorldPosition:=PKraftVector3(pointer(@WorldTransform[3,0]))^; CarSteering:=Min(Max((CarSteering*0.99)+(((ord(InputKeyRight) and 1)*0.01)-((ord(InputKeyLeft) and 1)*0.01)),-1.0),1.0); CarSpeed:=Min(Max((CarSpeed*0.99)+(((ord(InputKeyUp) and 1)*0.01)-((ord(InputKeyDown) and 1)*0.01)),-1.0),1.0); CarAngle:=Min(Max(CarSteering,-1.0),1.0)*10.0; NeedBeAwake:=(abs(CarSpeed)>1e-5) or (abs(CarAngle)>1e-5); begin // Keep up { if fKraftPhysics.SphereCast(WorldPosition,1.0,WorldDown,2.0,HitShape,HitTime,HitPoint,HitNormal,[0]) then begin KeepUpNormal:=HitNormal; end else}begin KeepUpNormal:=Vector3Neg(fKraftPhysics.Gravity.Vector); end; // Calculate the new target up-vector NewUp:=Vector3Norm(KeepUpNormal); { // Get difference quaternion between current orientation to target keep-up-right-forward orientation SourceQuaternion:=ChassisRigidBody.Sweep.q; TargetQuaternion:=QuaternionMul(QuaternionFromToRotation(WorldUp,NewUp),ChassisRigidBody.Sweep.q); DifferenceQuaternion:=QuaternionTermNormalize(QuaternionMul(TargetQuaternion,QuaternionInverse(SourceQuaternion))); // Convert difference quaternion to axis angles QuaternionToAxisAngle(DifferenceQuaternion,Axis,Angle); // Transform axis into local space Axis:=Vector3TermMatrixMulTransposedBasis(Axis,ChassisRigidBody.WorldTransform); // Get difference velocity Delta:=Vector3ScalarMul(Axis,Min(Max(Angle,-MaxAngle),MaxAngle)*32.0); Delta.Yaw:=0.0; // Clear yaw ChassisRigidBody.AddWorldTorque(Vector3ScalarMul(Delta,100.0),kfmForce); } // ChassisRigidBody.AddWorldTorque(Vector3ScalarMul(Delta,fKraftPhysics.WorldDeltaTime),kfmVelocity); // AngularVelocity,Vector3ScalarMul(Delta,TimeStep.DeltaTime)); { // Apply difference velocity directly to angular velocity Vector3DirectAdd(LocalAngularVelocity,Vector3ScalarMul(Delta,TimeStep.DeltaTime)); } if Vector3Dot(WorldUp,NewUp)<0.9 then begin Axis:=Vector3Norm(Vector3Cross(WorldUp,NewUp)); // To avoid the vehicle going backwards/forwards (or rolling sideways), // set the pitch/roll to 0 before applying the 'straightening' impulse. //ChassisRigidBody.AngularVelocity:=Vector3(0.0,ChassisRigidBody.AngularVelocity.y,0.0); Force:=Vector3ScalarMul(Axis,ChassisRigidBody.Mass*100.0); if Vector3Length(Force)>1e-6 then begin ChassisRigidBody.AddWorldTorque(Force,kfmForce); NeedBeAwake:=true; end; end; end; begin // All-wheel steering and driving if abs(CarAngle)>EPSILON then begin Radius:=tan(CarAngle*DEG2RAD); end else begin Radius:=tan(EPSILON*DEG2RAD); end; Radius:=CarLength/Radius; SideRadius[0]:=arctan(CarLength/(Radius-CarHalfWidth)); SideRadius[1]:=arctan(CarLength/(Radius+CarHalfWidth)); for y:=0 to 1 do begin for x:=0 to 1 do begin AxisVectors[y,x]:=Vector3TermMatrixMulBasis(Vector3Norm(Vector3(cos(SideRadius[x]),0.0,sin(SideRadius[x])*Signs[y])),ChassisRigidBody.WorldTransform); WheelHingeJointConstraints[y,x].SetWorldRotationAxis(AxisVectors[y,x]); WheelRigidBodies[y,x].AddWorldAngularVelocity(Vector3TermMatrixMul(Vector3ScalarMul(AxisVectors[y,x],-(CarSpeed*0.5)),WheelRigidBodies[y,x].WorldInverseInertiaTensor),kfmVelocity); end; end; end; if NeedBeAwake then begin for y:=0 to 1 do begin for x:=0 to 1 do begin WheelRigidBodies[y,x].SetToAwake; end; end; ChassisRigidBody.SetToAwake; end; end; procedure TDemoSceneConstraintVehicle.DebugDraw; begin inherited DebugDraw; {glDisable(GL_LIGHTING); glEnable(GL_POLYGON_OFFSET_LINE); glEnable(GL_POLYGON_OFFSET_POINT); glPolygonOffset(-8,8); glPointSize(8); glLineWidth(4); glColor4f(1,1,1,1); Vehicle.DebugDraw; glDisable(GL_DEPTH_TEST); glDisable(GL_POLYGON_OFFSET_LINE); glDisable(GL_POLYGON_OFFSET_POINT);} end; function TDemoSceneConstraintVehicle.HasOwnKeyboardControls:boolean; begin result:=true; end; procedure TDemoSceneConstraintVehicle.KeyDown(const aKey:Int32); begin case aKey of VK_LEFT:begin InputKeyLeft:=true; end; VK_RIGHT:begin InputKeyRight:=true; end; VK_UP:begin InputKeyUp:=true; end; VK_DOWN:begin InputKeyDown:=true; end; VK_SPACE:begin InputKeyBrake:=true; end; VK_RETURN:begin InputKeyHandBrake:=true; end; end; end; procedure TDemoSceneConstraintVehicle.KeyUp(const aKey:Int32); begin case aKey of VK_LEFT:begin InputKeyLeft:=false; end; VK_RIGHT:begin InputKeyRight:=false; end; VK_UP:begin InputKeyUp:=false; end; VK_DOWN:begin InputKeyDown:=false; end; VK_SPACE:begin InputKeyBrake:=false; end; VK_RETURN:begin InputKeyHandBrake:=false; end; end; end; function TDemoSceneConstraintVehicle.UpdateCamera(var aCameraPosition:TKraftVector3;var aCameraOrientation:TKraftQuaternion):boolean; var Position,WorldLeft,WorldRight,WorldUp,WorldDown,WorldForward,WorldBackward,WorldPosition:TKraftVector3; TargetMatrix:TKraftMatrix3x3; LerpFactor:TKraftScalar; WorldTransform:TKraftMatrix4x4; begin WorldTransform:=ChassisRigidBody.WorldTransform; WorldRight:=PKraftVector3(pointer(@WorldTransform[0,0]))^; WorldLeft:=Vector3Neg(WorldRight); WorldUp:=PKraftVector3(pointer(@WorldTransform[1,0]))^; WorldDown:=Vector3Neg(WorldUp); WorldForward:=PKraftVector3(pointer(@WorldTransform[2,0]))^; WorldBackward:=Vector3Neg(WorldForward); WorldPosition:=PKraftVector3(pointer(@WorldTransform[3,0]))^; LerpFactor:=1.0-exp(-(1.0/20.0)); Position:=Vector3Add(Vector3Add(WorldPosition,Vector3ScalarMul(WorldForward,10.0)),Vector3ScalarMul(WorldUp,5.0)); PKraftVector3(@TargetMatrix[2,0])^:=Vector3Norm(Vector3Sub(WorldPosition,Position)); PKraftVector3(@TargetMatrix[1,0])^:=WorldUp; PKraftVector3(@TargetMatrix[0,0])^:=Vector3Cross(PKraftVector3(@TargetMatrix[1,0])^,PKraftVector3(@TargetMatrix[2,0])^); PKraftVector3(@TargetMatrix[1,0])^:=Vector3Cross(PKraftVector3(@TargetMatrix[2,0])^,PKraftVector3(@TargetMatrix[0,0])^); aCameraPosition:=Vector3Lerp(aCameraPosition,Position,LerpFactor); aCameraOrientation:=QuaternionSlerp(aCameraOrientation,QuaternionFromMatrix3x3(TargetMatrix),LerpFactor); {} result:=true; end; procedure TDemoSceneConstraintVehicle.StoreWorldTransforms; begin inherited StoreWorldTransforms; //Vehicle.StoreWorldTransforms; end; procedure TDemoSceneConstraintVehicle.InterpolateWorldTransforms(const aAlpha:TKraftScalar); begin inherited InterpolateWorldTransforms(aAlpha); //Vehicle.InterpolateWorldTransforms(aAlpha); end; initialization RegisterDemoScene('Constraint vehicle',TDemoSceneConstraintVehicle); end.
unit SQLConverterKurs; interface uses Classes, SysUtils, DatabaseDefinition, SQLConverter, SQLProducer, RT_BaseTypes, RT_Kurs; type TSQLConverterKurs = class (TInterfacedObject, ISQLConverter) private FTable: TTable; FSQLProducer: TSQLProducer; property SQLProducer: TSQLProducer read FSQLProducer; public constructor Create; destructor Destroy; override; function GetTable: TTable; procedure SetTable(Value: TTable); procedure LoadBinaryData(FileName: String); procedure CreateInserts(Output: TStrings); procedure Convert(BinaryFile: TFileName; Output: TStrings); end; implementation { TSQLConverterKurs } constructor TSQLConverterKurs.Create; begin inherited Create; FSQLProducer := TSQLProducer.Create; end; destructor TSQLConverterKurs.Destroy; begin FreeAndNil(FSQLProducer); inherited Destroy; end; function TSQLConverterKurs.GetTable: TTable; begin Result := FTable; end; procedure TSQLConverterKurs.SetTable(Value: TTable); begin if FTable <> Value then FTable := Value; end; procedure TSQLConverterKurs.LoadBinaryData(FileName: String); begin Kursy.Load(FileName); end; procedure TSQLConverterKurs.CreateInserts(Output: TStrings); var I: Integer; begin for I := 0 to Kursy.Count - 1 do Output.Add(SQLProducer.Insert(FTable, TRT_Kurs(Kursy[I]).D, True)); end; procedure TSQLConverterKurs.Convert(BinaryFile: TFileName; Output: TStrings); var SRec: TSearchRec; SRes: Integer; begin SRes := FindFirst(BinaryFile, faAnyFile, SRec); while SRes = 0 do begin LoadBinaryData(ExtractFilePath(BinaryFile) + SRec.Name); CreateInserts(Output); SRes := FindNext(SRec); end; end; end.
unit Marvin.Console.GUI.Cadastro.TipoCliente; interface uses Marvin.Console.Utils, { comunicação } Marvin.Desktop.Repositorio.AulaMulticamada, { exceções } Marvin.AulaMulticamada.Excecoes.TipoCliente, { classes } Marvin.AulaMulticamada.Classes.TipoCliente, Marvin.AulaMulticamada.Listas.TipoCliente; type TPaginaSalvarTipoCliente = class(TObject) private { comunicação } FClientClasses: IMRVRepositorioAulaMulticamada; { classes } FTipoCliente: TMRVTipoCliente; { status } FPaginaStatus: TPaginaStatus; protected { métodos de apoio } procedure ApresentarLinha; procedure ExibirCabecalhoAlterar; procedure ExibirCabecalhoNovo; procedure ExibirTipoCliente(const ATipoCliente: TMRVTipoCliente); procedure MostrarComandosAlterar; procedure RecuperarComandoAlterar(var ASair: Boolean); procedure RecuperarComandoNovo(var ASair: Boolean); procedure DoSalvar; procedure DoShowNovo; procedure DoShowAlterar; public constructor Create(const AClientClasses: IMRVRepositorioAulaMulticamada; const APaginaStatus: TPaginaStatus); overload; destructor Destroy; override; procedure Show; property TipoCliente: TMRVTipoCliente read FTipoCliente; end; implementation uses System.SysUtils; { TPaginaSalvarTipoCliente } procedure TPaginaSalvarTipoCliente.ApresentarLinha; begin TConsoleUtils.WritelnWithColor('/-------------------------------------------------------------------/', TConsoleUtils.C_GERAL); end; constructor TPaginaSalvarTipoCliente.Create( const AClientClasses: IMRVRepositorioAulaMulticamada; const APaginaStatus: TPaginaStatus); begin FClientClasses := AClientClasses; FPaginaStatus := APaginaStatus; FTipoCliente := TMRVTipoCliente.Create; end; destructor TPaginaSalvarTipoCliente.Destroy; begin FTipoCliente.Free; FClientClasses := nil end; procedure TPaginaSalvarTipoCliente.DoSalvar; var LTipoCliente: TMRVTipoCliente; begin inherited; LTipoCliente := nil; case FPaginaStatus of psNovo: begin { manda o ClientModule incluir } LTipoCliente := FClientClasses.TiposClienteInserir(FTipoCliente) as TMRVTipoCliente; end; psAlterar: begin { manda o ClientModule alterar } LTipoCliente := FClientClasses.TiposClienteAlterar(FTipoCliente) as TMRVTipoCliente; end; end; try FTipoCliente.Assign(LTipoCliente); finally { libera o retorno } LTipoCliente.DisposeOf; end; end; procedure TPaginaSalvarTipoCliente.DoShowAlterar; var LSair: Boolean; begin LSair := False; while not(LSair) do begin { exibe informações atuais do Tipo de Cliente } Self.ExibirCabecalhoAlterar; { recupera os dados } Self.ExibirTipoCliente(FTipoCliente); { exibe comandos } Self.MostrarComandosAlterar; { recupera o comando } Self.RecuperarComandoAlterar(LSair); { salvar } if not(LSair) then begin Self.DoSalvar; end; end; end; procedure TPaginaSalvarTipoCliente.DoShowNovo; var LSair: Boolean; begin LSair := False; while not(LSair) do begin FTipoCliente.Clear; { exibe informações atuais do Tipo de Cliente } Self.ExibirCabecalhoNovo; { recupera o comando } Self.RecuperarComandoNovo(LSair); { salvar } if not(LSair) then begin try Self.DoSalvar; LSair := True; except on E: EMRVExcecoesTipoCliente do begin LSair := False; { exibe mensagem de erro } Writeln(''); TConsoleUtils.WritelnWithColor('[Informação]' + #13#10 + E.Message, TConsoleUtils.C_MENSAGEM_ERRO); Readln; end; else raise; end; end; end; end; procedure TPaginaSalvarTipoCliente.ExibirCabecalhoAlterar; begin TConsoleUtils.ClearScreen; Self.ApresentarLinha; TConsoleUtils.WriteWithColor('| ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor('Alterar Tipo de Cliente', TConsoleUtils.C_CABECALHO_TEXTO); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); Writeln(''); Self.ApresentarLinha; TConsoleUtils.WriteWithColor('| ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor('Código', TConsoleUtils.C_TITULO_TABELA); TConsoleUtils.WriteWithColor(' | ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor('Descrição', TConsoleUtils.C_TITULO_TABELA); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); Writeln(''); Self.ApresentarLinha; end; procedure TPaginaSalvarTipoCliente.ExibirCabecalhoNovo; begin TConsoleUtils.ClearScreen; Self.ApresentarLinha; TConsoleUtils.WriteWithColor('| ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor('Inserir Tipo de Cliente', TConsoleUtils.C_CABECALHO_TEXTO); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); Writeln(''); Self.ApresentarLinha; TConsoleUtils.WriteWithColor('| ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor('Informe a ', TConsoleUtils.C_GERAL_TEXTO); TConsoleUtils.WriteWithColor('Descrição', TConsoleUtils.C_TEXTO_ENFASE); TConsoleUtils.WriteWithColor(' para o NOVO Tipo de Cliente. ', TConsoleUtils.C_GERAL_TEXTO); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); Writeln(''); Self.ApresentarLinha; end; procedure TPaginaSalvarTipoCliente.ExibirTipoCliente( const ATipoCliente: TMRVTipoCliente); begin TConsoleUtils.WriteWithColor('| ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor(Format('%6d', [ATipoCliente.TipoClienteId]), TConsoleUtils.C_TEXTO); TConsoleUtils.WriteWithColor(' | ', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor(Format('%-56S', [ATipoCliente.Descricao]), TConsoleUtils.C_TEXTO); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); Writeln(''); Self.ApresentarLinha; end; procedure TPaginaSalvarTipoCliente.MostrarComandosAlterar; begin TConsoleUtils.WriteWithColor('|', TConsoleUtils.C_GERAL); TConsoleUtils.WriteWithColor(' Informe o novo valor para a ', TConsoleUtils.C_GERAL_TEXTO); TConsoleUtils.WriteWithColor('Descrição', TConsoleUtils.C_TEXTO_ENFASE); TConsoleUtils.WriteWithColor(' do Tipo de Cliente.', TConsoleUtils.C_GERAL_TEXTO); TConsoleUtils.WriteWithColor(' |', TConsoleUtils.C_GERAL); TConsoleUtils.SetConsoleColor(TConsoleUtils.C_TEXTO); Writeln(''); Self.ApresentarLinha; end; procedure TPaginaSalvarTipoCliente.RecuperarComandoAlterar(var ASair: Boolean); var LComando: string; begin { recupera } TConsoleUtils.WriteWithColor('Escreva: ', TConsoleUtils.C_TEXTO); TConsoleUtils.SetConsoleColor(TConsoleUtils.C_TEXTO_ENFASE); Readln(Input, LComando); ASair := (Trim(LComando) = EmptyStr); if not(ASair) then begin FTipoCliente.Descricao := Trim(LComando); end; end; procedure TPaginaSalvarTipoCliente.RecuperarComandoNovo(var ASair: Boolean); var LComando: string; begin { recupera } TConsoleUtils.WriteWithColor('Escreva: ', TConsoleUtils.C_TEXTO); TConsoleUtils.SetConsoleColor(TConsoleUtils.C_TEXTO_ENFASE); Readln(Input, LComando); ASair := (Trim(LComando) = EmptyStr); if not(ASair) then begin FTipoCliente.Descricao := Trim(LComando); end; end; procedure TPaginaSalvarTipoCliente.Show; begin case FPaginaStatus of psNovo: Self.DoShowNovo; psAlterar: Self.DoShowAlterar; end; end; end.
{ Subroutine STRING_TOKEN_INT (S, P, I, STAT) * * Parse the next token from string S and convert it integer I. P is the current * parse index into string S. It should be set to 1 to start at the beginning of * the string, and will be updated after each call so that the next call gets * the next token. STAT is the completion status code. It will indicate * end of string S, NULL token, and string to integer conversion error. * * The parsing rules are defined by subroutine STRING_TOKEN_COMMASP. } module string_token_int; define string_token_int; %include 'string2.ins.pas'; procedure string_token_int ( {get next token and convert to machine integer} in s: univ string_var_arg_t; {input string} in out p: string_index_t; {input string parse index, init to 1 at start} out i: sys_int_machine_t; {output value} out stat: sys_err_t); {completion status code} val_param; var token: string_var132_t; {our token parsed from S} begin token.max := sizeof(token.str); {init local var string} string_token_commasp (s, p, token, stat); {get next token from S} if sys_error(stat) then return; if token.len = 0 then begin sys_stat_set (string_subsys_k, string_stat_null_tk_k, stat); return; {return with NULL TOKEN status} end; string_t_int (token, i, stat); {convert token to integer} end;
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ExtDlgs, ComCtrls, windows; type { TDIPTools } TDIPTools = class(TForm) blueButton: TButton; binaryExecuteButton: TButton; binarySettingsPanel: TPanel; brightnessGroup: TGroupBox; sketchCheckBox: TCheckBox; grayscaleExecuteButton: TButton; inverseButton: TButton; inverseGroup: TGroupBox; binaryRadioGroup: TRadioGroup; grayscaleRadioGroup: TRadioGroup; brightnessIndicator: TLabel; contrastIndicator: TLabel; gValueIndicator: TLabel; colorModeRadioGroup: TRadioGroup; thresholdIndicator: TLabel; executeButton: TButton; kernelValue: TEdit; kernelLabel: TLabel; brightnessOptionsPanel: TPanel; brightnessLabel: TLabel; brightnessButton: TButton; contrastButton: TButton; colorGroup: TGroupBox; colorPanel: TPanel; imagealterGroup: TGroupBox; gValueLabel: TLabel; greenButton: TButton; enhancementPanel: TPanel; contrastGroup: TGroupBox; colorFilterRadioGroup: TRadioGroup; filterRadioGroup: TRadioGroup; methodRadioGroup: TRadioGroup; grayscaleGroup: TGroupBox; binarySettingsGroup: TGroupBox; redButton: TButton; resetButton: TButton; OpenPictureDialog: TOpenPictureDialog; saveFileButton: TButton; openFileButton: TButton; fileGroup: TGroupBox; originalImage: TImage; SavePictureDialog: TSavePictureDialog; targetImage: TImage; colorToggle: TToggleBox; enhanceToggle: TToggleBox; thresholdLabel: TLabel; contrastLabel: TLabel; thresholdTrackbar: TTrackBar; brightnessTrackbar: TTrackBar; contrastTrackbar: TTrackBar; gValueTrackbar: TTrackBar; procedure binaryExecuteButtonClick(Sender: TObject); procedure blueButtonClick(Sender: TObject); procedure brightnessButtonClick(Sender: TObject); procedure contrastButtonClick(Sender: TObject); procedure enhanceToggleChange(Sender: TObject); procedure colorToggleChange(Sender: TObject); procedure executeButtonClick(Sender: TObject); procedure grayscaleExecuteButtonClick(Sender: TObject); procedure greenButtonClick(Sender: TObject); procedure gValueTrackbarChange(Sender: TObject); procedure inverseButtonClick(Sender: TObject); procedure openFileButtonClick(Sender: TObject); procedure redButtonClick(Sender: TObject); procedure resetButtonClick(Sender: TObject); procedure saveFileButtonClick(Sender: TObject); procedure sketchCheck(Sender: TObject); procedure thresholdTrackbarChange(Sender: TObject); procedure brightnessTrackbarChange(Sender: TObject); procedure contrastTrackbarChange(Sender: TObject); private function pixelBoundariesChecker(value: Integer): Integer; procedure initKernel(); procedure initPadding(); procedure showFilterResult(); public end; var DIPTools: TDIPTools; imageWidth: Integer; imageHeight: Integer; bitmapR: array [0..1000, 0..1000] of Byte; bitmapG: array [0..1000, 0..1000] of Byte; bitmapB: array [0..1000, 0..1000] of Byte; bitmapGray: array[1..1000, 0..1000] of Byte; bitmapFilterR: array [0..1000, 0..1000] of Byte; bitmapFilterG: array [0..1000, 0..1000] of Byte; bitmapFilterB: array [0..1000, 0..1000] of Byte; bitmapFilterGray: array[1..1000, 0..1000] of Byte; paddingR, paddingG, paddingB: array[0..3000, 0..3000] of Double; paddingGray: array[0..3000, 0..3000] of Double; kernel: array[0..100, 1..100] of Double; kernelSize, kernelHalf: Integer; implementation {$R *.lfm} { TDIPTools } //Open file procedure TDIPTools.openFileButtonClick(Sender: TObject); var x: Integer; y: Integer; begin if OpenPictureDialog.Execute then begin originalImage.Picture.LoadFromFile(OpenPictureDialog.FileName); targetImage.Picture.LoadFromFile(OpenPictureDialog.FileName); imageWidth:= originalImage.Width; imageHeight:= originalImage.Height; targetImage.Width:= imageWidth; targetImage.Height:= imageHeight; for y := 0 to originalImage.Height - 1 do begin for x := 0 to originalImage.Width - 1 do begin bitmapR[x,y] := GetRValue(originalImage.Canvas.Pixels[x,y]); bitmapG[x,y] := GetGValue(originalImage.Canvas.Pixels[x,y]); bitmapB[x,y] := GetBValue(originalImage.Canvas.Pixels[x,y]); bitmapGray[x, y]:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; end; end; end; end; procedure TDIPTools.redButtonClick(Sender: TObject); var x, y: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin targetImage.Canvas.Pixels[x, y]:= RGB(bitmapR[x, y], 0, 0); end; end; end; //Save file procedure TDIPTools.saveFileButtonClick(Sender: TObject); begin if SavePictureDialog.Execute then; begin targetImage.Picture.SaveToFile(SavePictureDialog.FileName); end; end; //Reset image procedure TDIPTools.resetButtonClick(Sender: TObject); var x: Integer; y: Integer; begin for y:=0 to originalImage.Height-1 do begin for x:=0 to originalImage.Width-1 do begin targetImage.Canvas.Pixels[x,y] := RGB(bitmapR[x,y], bitmapG[x,y], bitmapB[x,y]); end; end; end; //Color Options procedure TDIPTools.colorToggleChange(Sender: TObject); begin enhanceToggle.Checked:= false; if colorPanel.Visible = true then begin colorPanel.Visible:= false; enhancementPanel.Visible:= false; end else begin colorPanel.Visible:= true; enhancementPanel.Visible:= false; thresholdIndicator.Caption:= IntToStr(thresholdTrackbar.Position); end; end; procedure TDIPTools.executeButtonClick(Sender: TObject); var x, y, xK, yK: integer; cR, cG, cB, cGray: double; k, kHalf: Integer; begin kernelSize:= StrToInt(kernelValue.Text); kernelHalf:= kernelSize div 2; k:= kernelSize; kHalf:= kernelHalf; initKernel(); initPadding(); if methodRadioGroup.ItemIndex = 0 then begin for y:= kHalf to (imageHeight+kHalf) do begin for x:= kHalf to (imageWidth+kHalf) do begin if colorFilterRadioGroup.ItemIndex = 0 then begin cR:= 0; cG:= 0; cB:= 0; for yK:= 1 to k do begin for xK:= 1 to k do begin cR:= cR + (paddingR[x+(xK- k + kHalf), y+(yK - k + kHalf)] * kernel[xK, yK]); cG:= cG + (paddingG[x+(xK- k + kHalf), y+(yK - k + kHalf)] * kernel[xK, yK]); cB:= cB + (paddingB[x+(xK- k + kHalf), y+(yK - k + kHalf)] * kernel[xK, yK]); end; end; bitmapFilterR[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cR)); bitmapFilterG[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cG)); bitmapFilterB[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cB)); end else if colorFilterRadioGroup.ItemIndex = 1 then begin cGray:= 0; for yK:= 1 to k do begin for xK:= 1 to k do begin cGray:= cGray + (paddingGray[x+(xK- k + kHalf), y+(yK - k + kHalf)] * kernel[xK, yK]); end; end; bitmapFilterGray[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cGray)); end; end; end; end else if methodRadioGroup.ItemIndex = 1 then begin for y:= kHalf to (imageHeight+kHalf) do begin for x:= kHalf to (imageWidth+kHalf) do begin if colorFilterRadioGroup.ItemIndex = 0 then begin cR:= 0; cG:= 0; cB:= 0; for yK:= 1 to k do begin for xK:= 1 to k do begin cR:= cR + (paddingR[x-(xK- k + kHalf), y-(yK - k + kHalf)] * kernel[xK, yK]); cG:= cG + (paddingG[x-(xK- k + kHalf), y-(yK - k + kHalf)] * kernel[xK, yK]); cB:= cB + (paddingB[x-(xK- k + kHalf), y-(yK - k + kHalf)] * kernel[xK, yK]); end; end; bitmapFilterR[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cR)); bitmapFilterG[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cG)); bitmapFilterB[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cB)); end else if colorFilterRadioGroup.ItemIndex = 1 then begin cGray:= 0; for yK:= 1 to k do begin for xK:= 1 to k do begin cGray:= cGray + (paddingGray[x-(xK- k + kHalf), y-(yK - k + kHalf)] * kernel[xK, yK]); end; end; bitmapFilterGray[x-kHalf, y-kHalf]:= pixelBoundariesChecker(Round(cGray)); end; end; end; end; showFilterResult(); end; procedure TDIPTools.showFilterResult(); var x, y: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin if colorFilterRadioGroup.ItemIndex = 0 then begin targetImage.Canvas.Pixels[x, y]:= RGB(bitmapFilterR[x, y], bitmapFilterG[x, y], bitmapFilterB[x, y]); end else if colorFilterRadioGroup.ItemIndex = 1 then begin if (sketchCheckBox.Checked = True) and (filterRadioGroup.ItemIndex = 1) then targetImage.Canvas.Pixels[x, y]:= RGB(255-bitmapFilterGray[x, y], 255-bitmapFilterGray[x, y], 255-bitmapFilterGray[x, y]) else targetImage.Canvas.Pixels[x, y]:= RGB(bitmapFilterGray[x, y], bitmapFilterGray[x, y], bitmapFilterGray[x, y]); end; end; end; end; procedure TDIPTools.grayscaleExecuteButtonClick(Sender: TObject); var x, y: Integer; gray: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin gray:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; case (grayscaleRadioGroup.ItemIndex) of 0: targetImage.Canvas.Pixels[x, y]:= RGB(gray, 0, 0); 1: targetImage.Canvas.Pixels[x, y]:= RGB(0, gray, 0); 2: targetImage.Canvas.Pixels[x, y]:= RGB(0, 0, gray); 3: targetImage.Canvas.Pixels[x, y]:= RGB(gray, gray, gray); end; end; end; end; procedure TDIPTools.greenButtonClick(Sender: TObject); var x, y: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin targetImage.Canvas.Pixels[x, y]:= RGB(0, bitmapG[x, y], 0); end; end; end; //Enhancement Options procedure TDIPTools.enhanceToggleChange(Sender: TObject); begin colorToggle.Checked:= false; sketchCheckBox.Enabled:= false; if enhancementPanel.Visible = true then begin colorPanel.Visible:= false; enhancementPanel.Visible:= false; end else begin colorPanel.Visible:= false; enhancementPanel.Visible:= true; brightnessIndicator.Caption:= IntToStr(brightnessTrackbar.Position); contrastIndicator.Caption:= IntToStr(contrastTrackbar.Position); gValueIndicator.Caption:= IntToStr(gValueTrackbar.Position); end; end; procedure TDIPTools.blueButtonClick(Sender: TObject); var x, y: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin targetImage.Canvas.Pixels[x, y]:= RGB(0, 0, bitmapB[x, y]); end; end; end; procedure TDIPTools.brightnessButtonClick(Sender: TObject); var x, y: Integer; brightnessCoef: Integer; brightnessR, brightnessG, brightnessB: Integer; brightnessGray: Integer; gray: Integer; begin brightnessCoef:= brightnessTrackbar.Position; for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin if colorModeRadioGroup.ItemIndex = 0 then begin brightnessR:= pixelBoundariesChecker(bitmapR[x, y] + brightnessCoef); brightnessG:= pixelBoundariesChecker(bitmapG[x, y] + brightnessCoef); brightnessB:= pixelBoundariesChecker(bitmapB[x, y] + brightnessCoef); targetImage.Canvas.Pixels[x, y]:= RGB(brightnessR, brightnessG, brightnessB); end else if colorModeRadioGroup.ItemIndex = 1 then begin gray:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; brightnessGray:= pixelBoundariesChecker(gray + brightnessCoef); targetImage.Canvas.Pixels[x, y]:= RGB(brightnessGray, brightnessGray, brightnessGray); end; end; end; end; procedure TDIPTools.contrastButtonClick(Sender: TObject); var x, y: Integer; contrastR, contrastG, contrastB: Integer; contrastGray, gray: Integer; gCoef: Integer; contrastCoef: Integer; begin contrastCoef:= contrastTrackbar.Position; gCoef:= gValueTrackbar.Position; for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin if colorModeRadioGroup.ItemIndex = 0 then begin contrastR:= pixelBoundariesChecker(gCoef * (bitmapR[x, y] - contrastCoef) + contrastCoef); contrastG:= pixelBoundariesChecker(gCoef * (bitmapG[x, y] - contrastCoef) + contrastCoef); contrastB:= pixelBoundariesChecker(gCoef * (bitmapB[x, y] - contrastCoef) + contrastCoef); targetImage.Canvas.Pixels[x, y]:= RGB(contrastR, contrastG, contrastB); end else if colorModeRadioGroup.ItemIndex = 1 then begin gray:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; contrastGray:= pixelBoundariesChecker(gCoef * (gray - contrastCoef) + contrastCoef); targetImage.Canvas.Pixels[x, y]:= RGB(contrastGray, contrastGray, contrastGray); end; end; end; end; procedure TDIPTools.binaryExecuteButtonClick(Sender: TObject); var x, y: Integer; gray: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin gray:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; if gray <= thresholdTrackbar.Position then case (binaryRadioGroup.ItemIndex) of 0: targetImage.Canvas.Pixels[x, y]:= RGB(255, 0, 0); 1: targetImage.Canvas.Pixels[x, y]:= RGB(0, 255, 0); 2: targetImage.Canvas.Pixels[x, y]:= RGB(0, 0, 255); 3: targetImage.Canvas.Pixels[x, y]:= RGB(0, 0, 0); end else targetImage.Canvas.Pixels[x, y]:= RGB(255, 255, 255); end; end; end; //Trackbars procedure TDIPTools.thresholdTrackbarChange(Sender: TObject); begin thresholdIndicator.Caption:= IntToStr(thresholdTrackbar.Position); end; procedure TDIPTools.brightnessTrackbarChange(Sender: TObject); begin brightnessIndicator.Caption:= IntToStr(brightnessTrackbar.Position); end; procedure TDIPTools.contrastTrackbarChange(Sender: TObject); begin contrastIndicator.Caption:= IntToStr(contrastTrackbar.Position); end; function TDIPTools.pixelBoundariesChecker(value: Integer): Integer; begin if value < 0 then pixelBoundariesChecker:= 0 else if value > 255 then pixelBoundariesChecker:= 255 else pixelBoundariesChecker:= value; end; procedure TDIPTools.gValueTrackbarChange(Sender: TObject); begin gValueIndicator.Caption:= IntToStr(gValueTrackbar.Position); end; procedure TDIPTools.inverseButtonClick(Sender: TObject); var x, y: Integer; gray: Integer; begin for y:= 0 to imageHeight-1 do begin for x:= 0 to imageWidth-1 do begin if colorModeRadioGroup.ItemIndex = 1 then begin gray:= (bitmapR[x, y] + bitmapG[x, y] + bitmapB[x, y]) div 3; targetImage.Canvas.Pixels[x, y]:= RGB(255-gray, 255-gray, 255-gray); end else if colorModeRadioGroup.ItemIndex = 0 then targetImage.Canvas.Pixels[x, y]:= RGB(255-bitmapR[x, y], 255-bitmapG[x, y], 255-bitmapB[x, y]); end; end; end; procedure TDIPTools.initKernel(); var x, y: Integer; k, kHalf: Integer; begin k:= kernelSize; kHalf:= kernelHalf; if filterRadioGroup.ItemIndex = 0 then begin for y:= 1 to k do begin for x:= 1 to k do begin kernel[x, y]:= 1 / (k * k); end; end; end else begin for y:= 1 to k do begin for x:= 1 to k do begin kernel[x, y]:= -1; end; end; if filterRadioGroup.ItemIndex = 1 then kernel[kHalf, kHalf]:= (k * k) - 1 else if filterRadioGroup.ItemIndex = 2 then kernel[kHalf, kHalf]:= (k * k); end; end; procedure TDIPTools.initPadding(); var x, y, z: integer; k, kHalf: Integer; begin k:= kernelSize; kHalf:= kernelHalf; if colorFilterRadioGroup.ItemIndex = 0 then begin for y:= 0 to imageHeight+kHalf do begin for z:= 0 to kHalf-1 do begin paddingR[0+z, y]:= 255; paddingR[imageWidth+kHalf+z, y]:= 255; paddingG[0+z, y]:= 255; paddingG[imageWidth+kHalf+z, y]:= 255; paddingB[0+z, y]:= 255; paddingB[imageWidth+kHalf+z, y]:= 255; end; end; for x:= 0 to imageWidth+kHalf do begin for z:= 0 to kHalf-1 do begin paddingR[x, 0+z]:= 255; paddingR[x, imageHeight+kHalf+z]:= 255; paddingG[x, 0+z]:= 255; paddingG[x, imageHeight+kHalf+z]:= 255; paddingB[x, 0+z]:= 255; paddingB[x, imageHeight+kHalf+z]:= 255; end; end; for y:= kHalf to (imageHeight+kHalf-1) do begin for x:= kHalf to (imageWidth+kHalf-1) do begin paddingR[x, y]:= bitmapR[x-kHalf, y-kHalf]; paddingG[x, y]:= bitmapG[x-kHalf, y-kHalf]; paddingB[x, y]:= bitmapB[x-kHalf, y-kHalf]; end; end; end else if colorFilterRadioGroup.ItemIndex = 1 then begin for y:= 0 to imageHeight+kHalf do begin for z:= 0 to kHalf-1 do begin paddingGray[0+z, y]:= 255; paddingGray[imageWidth+kHalf+z, y]:= 255; end; end; for x:= 0 to imageWidth+kHalf do begin for z:= 0 to kHalf-1 do begin paddingGray[x, 0+z]:= 255; paddingGray[x, imageHeight+kHalf+z]:= 255; end; end; for y:= kHalf to (imageHeight+kHalf-1) do begin for x:= kHalf to (imageWidth+kHalf-1) do begin paddingGray[x, y]:= bitmapGray[x-kHalf, y-kHalf]; end; end; end; end; procedure TDIPTools.sketchCheck(Sender: TObject); begin if (colorFilterRadioGroup.ItemIndex = 1) AND (filterRadioGroup.ItemIndex = 1) AND (methodRadioGroup.ItemIndex = 1) then begin sketchCheckBox.Enabled:= true; end else begin sketchCheckBox.Enabled:= false; end; end; end.
unit CRCoreTransferEditFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, ComCtrls, StdCtrls, CoreTransfer, BaseObjects; type TfrmCoreTransferEdit = class(TfrmCommonFrame) gbxCoreTransfer: TGroupBox; dtpTransferStart: TDateTimePicker; dtpTransferFinish: TDateTimePicker; chbxTransferFinish: TCheckBox; lblTransferStart: TStaticText; lblTransferFinish: TStaticText; procedure chbxTransferFinishClick(Sender: TObject); private { Private declarations } protected procedure FillControls(ABaseObject: TIDObject); override; procedure ClearControls; override; procedure RegisterInspector; override; procedure CopyEditingValues(Dest: TIDObject); override; function InternalCheck: Boolean; override; function GetCoreTransfer: TCoreTransfer; public { Public declarations } property CoreTransfer: TCoreTransfer read GetCoreTransfer; constructor Create(AOwner: TComponent); override; procedure Save(AObject: TIDObject = nil); override; end; var frmCoreTransferEdit: TfrmCoreTransferEdit; implementation uses BaseGUI, Facade; {$R *.dfm} procedure TfrmCoreTransferEdit.chbxTransferFinishClick(Sender: TObject); begin inherited; lblTransferFinish.Enabled := chbxTransferFinish.Checked; dtpTransferFinish.Enabled := chbxTransferFinish.Checked; end; procedure TfrmCoreTransferEdit.ClearControls; begin inherited; //dtpTransferStart.Date := null; chbxTransferFinish.Checked := false; chbxTransferFinishClick(chbxTransferFinish); //dtpTransferFinish.Date := null; end; procedure TfrmCoreTransferEdit.CopyEditingValues(Dest: TIDObject); begin inherited; with Dest as TCoreTransfer do begin Name := CoreTransfer.Name; TransferStart := CoreTransfer.TransferStart; TransferFinish := CoreTransfer.TransferFinish; end; end; constructor TfrmCoreTransferEdit.Create(AOwner: TComponent); begin inherited; end; procedure TfrmCoreTransferEdit.FillControls(ABaseObject: TIDObject); begin inherited; dtpTransferStart.Date := CoreTransfer.TransferStart; if CoreTransfer.TransferFinish > CoreTransfer.TransferStart then begin chbxTransferFinish.Checked := True; chbxTransferFinishClick(chbxTransferFinish); dtpTransferFinish.Date := CoreTransfer.TransferFinish; end else begin chbxTransferFinish.Checked := False; chbxTransferFinishClick(chbxTransferFinish); end; end; function TfrmCoreTransferEdit.GetCoreTransfer: TCoreTransfer; begin Result := EditingObject as TCoreTransfer; end; function TfrmCoreTransferEdit.InternalCheck: Boolean; begin Result := true; if chbxTransferFinish.Checked then begin Result := dtpTransferStart.Date < dtpTransferFinish.Date; if not Result then begin StatusBar.Panels[0].Text := 'Дата начала больше даты окончания'; exit; end; end; end; procedure TfrmCoreTransferEdit.RegisterInspector; begin inherited; //Inspector.Add(dtpTransferStart, nil, ptDate, 'дата начала', false); end; procedure TfrmCoreTransferEdit.Save(AObject: TIDObject); begin inherited; EditingClass := TCoreTransfer; if FEditingObject = nil then FEditingObject := TMainFacade.GetInstance.AllCoreTransfers.Add; CoreTransfer.TransferStart := dtpTransferStart.Date; if chbxTransferFinish.Checked then CoreTransfer.TransferFinish := dtpTransferFinish.Date else CoreTransfer.TransferFinish := CoreTransfer.TransferStart; end; end.
(* @created(2019-12-27) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(27/12/2019 : Creation ) ) --------------------------------------------------------------------------------@br ------------------------------------------------------------------------------ Description : ------------------------------------------------------------------------------ @bold(Notes :) Quelques liens : @unorderedList( @item() ) ------------------------------------------------------------------------------@br @bold(Credits :) @unorderedList( @item(FPC/Lazarus) ) ------------------------------------------------------------------------------@br LICENCE : GPL/MPL @br ------------------------------------------------------------------------------ *==============================================================================*) unit BZSoftwareShader_Template; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\..\bzscene_options.inc} //------------------------ {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} //------------------------ //============================================================================== interface uses Classes, SysUtils, BZClasses, BZMath, BZVectorMath, BZRayMarchMath, BZGraphic, BZBitmap, BZCadencer, BZCustomShader; Type { TBZSoftShader_GroundAndDistortPhongSphere } TBZSoftShader_Template = Class(TBZCustomSoftwareShader) protected public Constructor Create; override; Destructor Destroy; override; function Clone : TBZCustomSoftwareShader; override; function ShadePixelFloat:TBZColorVector; override; end; implementation { TBZSoftShader_GroundAndDistortPhongSphere } Constructor TBZSoftShader_Template.Create; begin inherited Create; end; Destructor TBZSoftShader_Template.Destroy; begin inherited Destroy; end; function TBZSoftShader_Template.Clone : TBZCustomSoftwareShader; begin Result := TBZSoftShader_Template.Create; Result.Assign(Self); end; function TBZSoftShader_Template.ShadePixelFloat : TBZColorVector; function ComputePixel(Coord:TBZVector2f; aTime:Single) : TBZColorVector; var {$CODEALIGN VARMIN=16} finalColor : TBZColorVector; {$CODEALIGN VARMIN=4} begin Result := FinaleColor; end; begin Result := ComputePixel(FragCoords, iTime); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [SOCIO_DEPENDENTE] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit SocioDependenteVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('SOCIO_DEPENDENTE')] TSocioDependenteVO = class(TVO) private FID: Integer; FID_SOCIO: Integer; FID_TIPO_RELACIONAMENTO: Integer; FNOME: String; FDATA_NASCIMENTO: TDateTime; FDATA_INICIO_DEPEDENCIA: TDateTime; FDATA_FIM_DEPENDENCIA: TDateTime; FCPF: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_SOCIO', 'Id Socio', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdSocio: Integer read FID_SOCIO write FID_SOCIO; [TColumn('ID_TIPO_RELACIONAMENTO', 'Id Tipo Relacionamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdTipoRelacionamento: Integer read FID_TIPO_RELACIONAMENTO write FID_TIPO_RELACIONAMENTO; [TColumn('NOME', 'Nome', 450, [ldGrid, ldLookup, ldCombobox], False)] property Nome: String read FNOME write FNOME; [TColumn('DATA_NASCIMENTO', 'Data Nascimento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataNascimento: TDateTime read FDATA_NASCIMENTO write FDATA_NASCIMENTO; [TColumn('DATA_INICIO_DEPEDENCIA', 'Data Inicio Depedencia', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataInicioDepedencia: TDateTime read FDATA_INICIO_DEPEDENCIA write FDATA_INICIO_DEPEDENCIA; [TColumn('DATA_FIM_DEPENDENCIA', 'Data Fim Dependencia', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataFimDependencia: TDateTime read FDATA_FIM_DEPENDENCIA write FDATA_FIM_DEPENDENCIA; [TColumn('CPF', 'Cpf', 88, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftCpf, taLeftJustify)] property Cpf: String read FCPF write FCPF; //Transientes end; implementation initialization Classes.RegisterClass(TSocioDependenteVO); finalization Classes.UnRegisterClass(TSocioDependenteVO); end.
{ Copyright (c) 2013 Jeroen Wiert Pluimers for BeSharp.net and Coding In Delphi. Full BSD License is available at http://BeSharp.codeplex.com/license } unit RttiHelpers; interface uses System.Rtti, System.SysUtils; type TRttiTypeHelper = class helper for TRttiType function GetMostQualifiedName(): string; virtual; function GetProtectionString(): string; function GetUnitName(): string; virtual; end; /// Find versus Get: Find* might return nil or empty lists, Get* won't. TRttiContextHelper = record helper for TRttiContext function FindType(const AInterfaceGUID: TGUID): TRttiInterfaceType; overload; function FindTypes(const Predicate: TPredicate<TRttiType>): TArray<TRttiType>; overload; function GetMostQualifiedName<TClass: class; TInterface: IInterface>(): string; overload; function GetMostQualifiedName(const ClassRttiType, InterfaceRttiType: TRttiType): string; overload; function GetType(const AnInstance: TObject): TRttiInstanceType; overload; function GetType<T>(): TRttiType; overload; end; TObjectHelper = class helper for TObject {$REGION 'Documentation'} /// <summary> /// <para> /// The way to write a `helper for class` is by creating a `helper for /// object`, then implement a class method. /// </para> /// <para> /// A `class` method in an `object` helper for TObject can be called /// from a TClass too. /// </para> /// </summary> {$ENDREGION} class function ClassHierarchyDepth(): Integer; end; implementation uses {$ifdef StrictGetType} System.SysConst, {$endif StrictGetType} System.Generics.Collections; function TRttiTypeHelper.GetMostQualifiedName(): string; begin // you cannot ask for QualifiedName on a non-public RttiType if Self.IsPublicType then Result := Self.QualifiedName else Result := Self.Name; end; function TRttiTypeHelper.GetProtectionString(): string; begin if IsPublicType then Result := 'public' else Result := 'private'; end; function TRttiTypeHelper.GetUnitName(): string; begin Result := Copy(QualifiedName, 1, Length(QualifiedName) - Length(Name) - 1); end; function TRttiContextHelper.FindType(const AInterfaceGUID: TGUID): TRttiInterfaceType; var InterfaceGUID: TGUID; Predicate: TPredicate<TRttiType>; RttiInterfaceType: TRttiInterfaceType; RttiType: TRttiType; RttiTypes: TArray<TRttiType>; RttiTypesCount: Integer; begin InterfaceGUID := AInterfaceGUID; // to cicrumvent "E2555 Cannot capture symbol 'AInterfaceGUID'" Predicate := function(ARttiType: TRttiType): Boolean begin if ARttiType is TRttiInterfaceType then begin RttiInterfaceType := TRttiInterfaceType(ARttiType); Result := RttiInterfaceType.GUID = InterfaceGUID; end else Result := False; end; RttiTypes := FindTypes(Predicate); RttiTypesCount := Length(RttiTypes); if RttiTypesCount = 1 then begin RttiType := RttiTypes[0]; if RttiType is TRttiInterfaceType then Result := TRttiInterfaceType(RttiType) else begin {$ifdef StrictGetType} raise ENotSupportedException.CreateFmt('Class %s not supported as interface RTTI', [RttiType.ClassName]); {$else} Result := nil; // the System.Rtti is not strict, returns nil upon failures. {$endif StrictGetType} end; end else begin {$ifdef StrictGetType} raise ERangeError.CreateFmt('%s, Expected 1 result, got %d', [SRangeError, RttiTypesCount]); {$else} Result := nil; // the System.Rtti is not strict, returns nil upon failures. {$endif StrictGetType} end; end; function TRttiContextHelper.FindTypes(const Predicate: TPredicate<TRttiType>): TArray<TRttiType>; var AllRttiTypes: TArray<TRttiType>; FilteredRttiTypes: TList<TRttiType>; RttiType: TRttiType; begin AllRttiTypes := GetTypes(); FilteredRttiTypes := TList<TRttiType>.Create(); try for RttiType in AllRttiTypes do begin if Predicate(RttiType) then FilteredRttiTypes.Add(RttiType); end; Result := FilteredRttiTypes.ToArray(); finally FilteredRttiTypes.Free; end; end; function TRttiContextHelper.GetMostQualifiedName(const ClassRttiType, InterfaceRttiType: TRttiType): string; var TClassName: string; TInterfaceName: string; begin TClassName := ClassRttiType.GetMostQualifiedName(); TInterfaceName := InterfaceRttiType.GetMostQualifiedName(); Result := TClassName + '.' + TInterfaceName; end; function TRttiContextHelper.GetMostQualifiedName<TClass, TInterface>(): string; var ClassRttiType: TRttiType; InterfaceRttiType: TRttiType; begin ClassRttiType := GetType<TClass>(); InterfaceRttiType := GetType<TInterface>(); Result := GetMostQualifiedName(ClassRttiType, InterfaceRttiType); end; function TRttiContextHelper.GetType(const AnInstance: TObject): TRttiInstanceType; begin Result := GetType(AnInstance.ClassType).AsInstance; end; function TRttiContextHelper.GetType<T>(): TRttiType; begin Result := GetType(TypeInfo(T)); end; class function TObjectHelper.ClassHierarchyDepth(): Integer; var Parent: TClass; begin Result := 0; Parent := Self; while Parent <> nil do begin Inc(Result); Parent := Parent.ClassParent; end; end; end.
unit AppControllerU; interface uses MVCFramework, MVCFramework.Commons, MVCFramework.Logger, Web.HTTPApp; type [MVCPath('/')] TApp1MainController = class(TMVCController) public [MVCPath('/name')] [MVCHTTPMethod([httpGET])] procedure Index; [MVCPath('/login/($username)')] [MVCHTTPMethod([httpGET])] procedure DoLogin(username: String); [MVCPath('/logout')] [MVCHTTPMethod([httpGET])] procedure DoLogout; end; implementation { TApp1MainController } procedure TApp1MainController.DoLogin(username: String); begin Session['username'] := username; Render(200, 'Logged in'); end; procedure TApp1MainController.DoLogout; begin Context.SessionStop(false); Render(200, 'Logged out'); end; procedure TApp1MainController.Index; begin ContentType := TMVCMediaType.TEXT_PLAIN; // do not create session if not already created if Context.SessionStarted then begin // automaticaly create the session Render('Hello ' + Session['username']); end else begin Render(400, 'Session not created. Do login first'); end; end; end.
unit Classe.Fornecedor; interface uses Controller.FornecedorInterface; type TFornecedor = class(TInterfacedObject, IFornecedor) private FId: Integer; FNome: string; FCnpj: string; public function GETId(): Integer; function GETNome(): string; function GETCnpj(): string; function Id(const pValue: Integer): IFornecedor; function Nome(const pValue: string): IFornecedor; function CNPJ(const pValue: string): IFornecedor; constructor Create(); destructor Destroy(); override; class function New(): IFornecedor; end; implementation { TFornecedor } constructor TFornecedor.Create; begin end; destructor TFornecedor.Destroy; begin inherited; end; class function TFornecedor.New: IFornecedor; begin Result := Self.Create; end; function TFornecedor.CNPJ(const pValue: string): IFornecedor; begin Result := Self; FCnpj := pValue; end; function TFornecedor.Nome(const pValue: string): IFornecedor; begin Result := Self; FNome := pValue; end; function TFornecedor.Id(const pValue: Integer): IFornecedor; begin Result := Self; FId := pValue; end; function TFornecedor.GETCnpj: string; begin Result := FCnpj; end; function TFornecedor.GETId: Integer; begin Result := FId; end; function TFornecedor.GETNome: string; begin Result := FNome; end; end.
{ Module of routines that deal with character upper/lower case issues. } module string_case; define string_upcase_char; define string_downcase_char; define string_upcase; define string_downcase; define string_char_printable; %include 'string2.ins.pas'; { ********************************************************************* * * Function STRING_UPCASE_CHAR (C) * * Return the upper case version of C. } function string_upcase_char ( {make upper case version of char} in c: char) {character to return upper case of} :char; {always upper case} val_param; begin if (c >= 'a') and (c <= 'z') then begin {input character is lower case} string_upcase_char := chr(ord(c) - ord('a') + ord('A')); end else begin {input char is already upper case} string_upcase_char := c; end ; end; { ********************************************************************* * * Function STRING_DOWNCASE_CHAR (C) * * Return the lower case version of C. } function string_downcase_char ( {make lower case version of char} in c: char) {character to return lower case of} :char; {always lower case} val_param; begin if (c >= 'A') and (c <= 'Z') then begin {input character is upper case} string_downcase_char := chr(ord(c) - ord('A') + ord('a')); end else begin {input char is already lower case} string_downcase_char := c; end ; end; { ********************************************************************* * * Subroutine STRING_UPCASE (S) * * Convert all the lower case alphabetic characters in string S * to their corresponding upper case characters. } procedure string_upcase ( {convert all lower case chars to upper case} in out s: univ string_var_arg_t); {string to upcase} var i: sys_int_machine_t; {loop counter} c: char; begin for i := 1 to s.len do begin {once for each character in string} c := s.str[i]; {fetch this string character} if (c >= 'a') and (c <= 'z') then begin {this is a lower case character ?} s.str[i] := chr(ord(c) - ord('a') + ord('A')); end; end; {back and do next character} end; { ********************************************************************* * * Subroutine STRING_DOWNCASE (S) * * Convert all the upper case alphabetic characters in string S * to their corresponding lower case characters. } procedure string_downcase ( {change all upper case chars to lower case} in out s: univ string_var_arg_t); {string to convert in place} var i: sys_int_machine_t; {loop counter} c: char; begin for i := 1 to s.len do begin {once for each character in string} c := s.str[i]; {fetch this string character} if (c >= 'A') and (c <= 'Z') then begin {this is an upper case character ?} s.str[i] := chr(ord(c) - ord('A') + ord('a')); end; end; {back and do next character} end; { ********************************************************************* * * Function STRING_CHAR_PRINTABLE (C) * * Returns TRUE if C is a normal printable character, FALSE if it is a * control character. Note that space is a printable character. } function string_char_printable ( {test whether character is normal printable} in c: char) {character to test} :boolean; {TRUE if printable, FALSE if control char} val_param; begin string_char_printable := (c >= ' ') and (c <= '~'); end;
unit Config; interface uses IniFiles, Forms, Classes, IBDatabase, SysUtils; const VERSION_DATE = '5.05.2004'; type // конфигурационная информация приложения TConfigurationManager = class public constructor Create; destructor Destroy; override; private FIniFile: TIniFile; FLocalized: Boolean; FConfirmSaveReports: Boolean; FReportDelay: Integer; FSaveLocalization: Boolean; function GetIniPath: string; function GetDir(const Section, Key, DefaultValue: string): string; function GetTempDir: string; procedure CheckKeyExists(const Section, Key, DefaultValue: string); function GetResourceDir: string; function GetDataPath: string; function GetDataStoragePath: string; procedure InitTaxxiVersion; function GetTemplatesDir: string; public property IniFile: TIniFile read FIniFile; property TempDir: string read GetTempDir; procedure SaveDataPath(Path: string); property ResourceDir: string read GetResourceDir; property DataPath: string read GetDataPath write savedatapath; property DataStoragePath: string read GetDataStoragePath; procedure GetDatabaseList(Strings: TStrings); function GetDatabaseProp(const Index: Integer; var Path, UserName, Password: string): Boolean; property Localized: Boolean read FLocalized; property SaveLocalization: Boolean read FSaveLocalization; // сохранять ли ресурсы в папку с локализацией property ConfirmSaveReports: Boolean read FConfirmSaveReports; property ReportDelay: Integer read FReportDelay; property TemplatesDir: string read GetTemplatesDir; end; var AppConfig: TConfigurationManager; implementation uses Windows {, PfoStrings}; procedure TConfigurationManager.CheckKeyExists(const Section, Key, DefaultValue: string); begin if not IniFile.ValueExists(Section, Key) then IniFile.WriteString(Section, Key, DefaultValue); end; constructor TConfigurationManager.Create; begin inherited; FIniFile := TIniFile.Create(GetIniPath); FLocalized := FIniFile.ValueExists('LANGDIR', 'DIR'); FSaveLocalization := FIniFile.ReadBool('LANGDIR', 'Save', False); FConfirmSaveReports := FIniFile.ReadBool('GENERAL', 'ConfirmSaveReports', False); FReportDelay := FIniFile.ReadInteger('GENERAL', 'DelayOpenReports', 0); InitTaxxiVersion; end; destructor TConfigurationManager.Destroy; begin FIniFile.Free; inherited; end; procedure TConfigurationManager.GetDatabaseList(Strings: TStrings); var i: Integer; Value: string; Position: Integer; begin Strings.Clear; if IniFile.SectionExists('DB.LIST') then IniFile.ReadSectionValues('DB.LIST', Strings); for i := 0 to Strings.Count - 1 do begin Value := Strings.Strings[i]; Position := Pos('=', Value); if Position <> 0 then begin Value := Copy(Value, Position + 1, Length(Value)); Strings.Strings[i] := Value; end; end; end; function TConfigurationManager.GetDatabaseProp(const Index: Integer; var Path, UserName, Password: string): Boolean; var Strings: TStringList; Key: string; begin Result := False; Strings := TStringList.Create; try IniFile.ReadSection('DB.LIST', Strings); if Index > Strings.Count - 1 then Exit; Key := Strings.Strings[Index]; finally Strings.Free; end; if not IniFile.ValueExists('DB.SETTINGS', Key + '.Path') then raise Exception.CreateFmt('Некорректный файл настройки ', ['Unable to find "' + '[DB.SETTINGS] ' + Key + '.Path".']) else Path := IniFile.ReadString('DB.SETTINGS', Key + '.Path', ''); if not IniFile.ValueExists('DB.SETTINGS', Key + '.Username') then raise Exception.CreateFmt('Некорректный файл настройки ', ['Unable to find "' + '[DB.SETTINGS] ' + Key + '.Username".']) else UserName := IniFile.ReadString('DB.SETTINGS', Key + '.Username', ''); if not IniFile.ValueExists('DB.SETTINGS', Key + '.Password') then raise Exception.CreateFmt('Некорректный файл настройки ', ['Unable to find "' + '[DB.SETTINGS] ' + Key + '.Password".']) else Password := IniFile.ReadString('DB.SETTINGS', Key + '.Password', ''); Result := True; end; function TConfigurationManager.GetDir(const Section, Key, DefaultValue: string): string; var CurrentDir: string; begin CheckKeyExists(Section, Key, DefaultValue); Result := IniFile.ReadString(Section, Key, DefaultValue); CurrentDir := GetCurrentDir; try SetCurrentDir(ExtractFileDir(Application.ExeName)); Result := ExcludeTrailingBackslash(ExtractFilePath(ExpandFileName(ExcludeTrailingBackslash(Result) + '\test.txt'))) + '\'; if not DirectoryExists(Result) then ForceDirectories(Result); if not DirectoryExists(Result) then raise Exception.CreateFmt('Не могу создать каталог', [Result]); finally SetCurrentDir(CurrentDir); end; end; function TConfigurationManager.GetResourceDir: string; begin Result := GetDir('LANGDIR', 'Dir', 'lang\eng'); end; function TConfigurationManager.GetDataStoragePath: string; begin Result := GetDir('DATASTORAGE', 'Dir', 'DB_DAT\DATA'); end; function TConfigurationManager.GetDataPath: string; begin Result := GetDir('DataPath', 'Dir', 'data'); end; function TConfigurationManager.GetIniPath: string; begin Result := ChangeFileExt(Application.ExeName, '.ini'); end; function TConfigurationManager.GetTempDir: string; begin Result := GetDir('DIR', 'Temp', 'Temp'); end; procedure TConfigurationManager.InitTaxxiVersion; begin end; function TConfigurationManager.GetTemplatesDir: string; begin Result := ExtractFilePath(Application.ExeName) + '\Templates\'; end; procedure TConfigurationManager.SaveDataPath(Path: string); begin // dataPath:=Path; inifile.writestring('DataPath', 'Dir', Path); end; initialization AppConfig := TConfigurationManager.Create; finalization if AppConfig <> nil then AppConfig.Free; end.
(* @abstract(Contient les classes et collections pour la gestion des sources audio et des effets) ------------------------------------------------------------------------------------------------------------- @created(2016-11-16) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(05/11/2017 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : ------------------------------------------------------------------------------------------------------------- @bold(Dépendances) : BZClasses, BZVectorMath, BZSoundSample, BZXCollection, BZCadencer, BZUtils, BZMath, BZLIbOpenAL ------------------------------------------------------------------------------------------------------------- Credits : @unorderedList( @item (Codé sur une base de GLScene http://www.sourceforge.net/glscene) ) ------------------------------------------------------------------------------------------------------------- @bold(Licence) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) unit BZSound; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\bzscene_options.inc} //============================================================================== interface uses Classes, SysUtils, BZClasses, BZVectorMath, BZSoundSample, BZXCollection, BZCadencer; type // TBZAbstractSoundFXLibrary = class; TBZSoundFXLibrary = class; TBZSoundFXName = string; (* IBZSoundFXLibrarySupported = interface(IInterface) ['{D9457925-AD4E-4854-BE8B-790D54AC2AF9}'] function GetSoundFXLibrary: TBZAbstractSoundFXLibrary; end; *) { Stores a single PCM coded sound sample. } TBZSoundSampleItem = class(TCollectionItem) //TBZXCollectionItem //@TODO à renommer en TBZSoundSampleItemItem private FName: string; FData: TBZSoundSample; FTag: Integer; protected procedure DefineProperties(Filer: TFiler); override; procedure ReadData(Stream: TStream); virtual; procedure WriteData(Stream: TStream); virtual; function GetDisplayName: string; override; procedure SetData(const val: TBZSoundSample); public constructor Create(aCollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure LoadFromFile(const fileName: string); // This Tag is reserved for sound manager use only property ManagerTag: Integer read FTag write FTag; published property Name: string read FName write FName; property Data: TBZSoundSample read FData write SetData stored False; end; { Gestion d'une collection d'échantillons audio } TBZSoundSampleItems = class(TCollection) //TBZXCollection protected FOwner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TBZSoundSampleItem); function GetItems(index: Integer): TBZSoundSampleItem; public constructor Create(AOwner: TComponent); function Add: TBZSoundSampleItem; function FindItemID(ID: Integer): TBZSoundSampleItem; function GetByName(const aName: string): TBZSoundSampleItem; function AddFile(const fileName: string; const sampleName: string = ''): TBZSoundSampleItem; property Items[index: Integer]: TBZSoundSampleItem read GetItems write SetItems; default; end; { Composant non-visuel pour gérer une liste d'échantillon audio } TBZSoundLibrary = class(TComponent) private FSamples: TBZSoundSampleItems; protected procedure SetSamples(const val: TBZSoundSampleItems); procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Samples: TBZSoundSampleItems read FSamples write SetSamples; end; TBZSoundSourceChange = (sscTransformation, sscSample, sscStatus, sscFXStatus, sscNewSample); //sscEffects, sscFilters TBZSoundSourceChanges = set of TBZSoundSourceChange; TBZSoundSourceFXChange = (sfxcDirectFilter, sfxEffectSlot0Status, sfxEffectFiltering, sfxcFilter); //sscEffects, sscFilters TBZSoundSourceFXChanges = set of TBZSoundSourceFXChange; //TBZBSoundEmitter = class; { Description d' un effet audio } TBZCustomSoundFXItem = class(TBZXCollectionItem)//, IBZSoundFXLibrarySupported) private FTag: PtrUInt; protected procedure SetName(const val: string); override; {Override this function to write subclass data. } procedure WriteToFiler(Awriter: TWriter); override; {Override this function to read subclass data. } procedure ReadFromFiler(Areader: TReader); override; public constructor Create(aOwner: TBZXCollection); override; destructor Destroy; override; class function FriendlyName: String; override; //procedure DoProgress(const progressTime: TProgressTimes); virtual; // This Tag is reserved for sound manager use only property ManagerTag: PtrUInt read FTag write FTag; end; { Classe de type TBZCustomSoundFXItem } BZSoundFXItemClass = class of TBZCustomSoundFXItem; { Classe abstraite à hériter pour la gestion de filtres audio } TBZCustomSoundFilterItem = class(TBZCustomSoundFXItem) public class function FriendlyName: String; override; End; { Déclaration d'un filtre de type "Low-pass" } TBZLowPassSoundFilter = Class(TBZCustomSoundFilterItem) private FGAIN : Single; FGAINHF : Single; protected procedure WriteToFiler(AWriter: TWriter); override; procedure ReadFromFiler(AReader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; published property Gain : Single read FGain Write FGain; property GainHF : Single read FGainHF Write FGainHF; end; { Déclaration d'un filtre de type "High-pass" } TBZHighPassSoundFilter = Class(TBZCustomSoundFilterItem) private FGAIN : Single; FGAINLF : Single; protected procedure WriteToFiler(AWriter: TWriter); override; procedure ReadFromFiler(AReader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; published property Gain : Single read FGain Write FGain; property GainLF : Single read FGainLF Write FGainLF; end; { Déclaration d'un filtre de type "Band-pass" } TBZBandPassSoundFilter = Class(TBZCustomSoundFilterItem) private FGAIN : Single; FGAINHF : Single; FGAINLF : Single; protected procedure WriteToFiler(AWriter: TWriter); override; procedure ReadFromFiler(AReader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; published property Gain : Single read FGain Write FGain; property GainLF : Single read FGainLF Write FGainLF; property GainHF : Single read FGainLF Write FGainHF; end; { Classe abstraite à hériter pour la gestion d'effets audio } TBZCustomSoundEffectItem = class(TBZCustomSoundFXItem) private FFilterName : String; FFilteringActivated : Boolean; protected public function GetFilter : TBZCustomSoundFilterItem; class function FriendlyName: String; override; published property FilterName : String read FFilterName Write FFilterName; property FilteringActivated : Boolean read FFilteringActivated write FFilteringActivated; end; { EAX standard sound environments. (112 presets) } TBZSoundReverbEnvironment = ( seGeneric, sePaddedCell, seRoom, seBathroom, seLivingRoom, seStoneroom, seAuditorium, seConcertHall, seCave, seArena, seHangar, seCarpetedHallway, seHallway, seStoneCorridor, seAlley, seForest, seCity, seMountains, seQuarry, sePlain, seParkingLot, seSewerPipe, seUnderWater, seDrugged, seDizzy, sePsychotic, seCastle_SmallRoom, seCastle_ShortPassage, seCastle_MediumRoom, seCastle_LargeRoom, seCastle_LongPassage, seCastle_Hall, seCastle_CupBoarb, seCastle_CourtYard, seCastle_Alcove, seFactory_SmallRoom, seFactory_ShortPassage, seFactory_MediumRoom, seFactory_LargeRoom, seFactory_LongPassage, seFactory_Hall, seFactory_CupBoard, seFactory_CourtYard, seFactory_Alcove, seIcePalace_SmallRoom, seIcePalace_ShortPassage, seIcePalace_MediumRoom, seIcePalace_LargeRoom, seIcePalace_LongPassage, seIcePalace_Hall, seIcePalace_CupBoard, seIcePalace_CourtYard, seIcePalace_Alcove, seSpaceStation_SmallRoom, seSpaceStation_ShortPassage, seSpaceStation_MediumRoom, seSpaceStation_LargeRoom, seSpaceStation_LongPassage, seSpaceStation_Hall, seSpaceStation_CupBoard, seSpaceStation_Alcove, //seSpaceStation_CourtYard, seWooden_SmallRoom, seWooden_ShortPassage, seWooden_MediumRoom, seWooden_LargeRoom, seWooden_LongPassage, seWooden_Hall, seWooden_CupBoard, seWooden_CourtYard, seWooden_Alcove, seSport_EmptyStadium, seSport_SquashCourt, seSport_SmallSwimmingPool, seSport_LargeSwimmingPool, seSport_Gymnasium, seSport_FullStadium, seSport_StadiumTannoy, sePrefab_WorkShop, sePrefab_SchoolRoom, sePrefab_PractiseRoom, sePrefab_OutHouse, sePrefab_Caravan, seDome_Tomb, sePipe_Small, seDome_SaintPauls, sePipe_Longthin, sePipe_Large, sePipe_Resonant, seOutDoors_BackYard, seOutDoors_RollingPlains, seOutDoors_DeepCanyon, seOutDoors_Creek, seOutDoors_Valley, seMood_Heaven, seMood_Hell, seMood_Memory, seDriving_Commentator, seDriving_PitGarage, seDriving_Incar_Racer, seDriving_Incar_Sports, seDriving_Incar_Luxury, seDriving_FullGrandStand, seDriving_EmptyGrandStand, seDriving_Tunnel, seCity_Streets, seCity_SubWay, seCity_Museum, seCity_Library, seCity_UnderPass, seCity_Abandoned, seDustyRoom, seChapel, seSmallWaterRoom); { Description de l'effet audio "Reverb" } TBZReverbSoundEffect = Class(TBZCustomSoundEffectItem) private FPreset : TBZSoundReverbEnvironment; FDENSITY : Single; FDIFFUSION : Single; FGAIN : Single; FGAINHF : Single; FDECAY_TIME : Single; FDECAY_HFRATIO : Single; FREFLECTIONS_GAIN : Single; FREFLECTIONS_DELAY : Single; FLATE_REVERB_GAIN : Single; FLATE_REVERB_DELAY : Single; FAIR_ABSORPTION_GAINHF : Single; FROOM_ROLLOFF_FACTOR : Single; FDECAY_HFLIMIT : Boolean; procedure SetPreset(val : TBZSoundReverbEnvironment); protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(AReader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; published property Preset : TBZSoundReverbEnvironment read FPreset write SetPreset; property DENSITY : Single read FDensity write FDensity; property DIFFUSION : Single read FDiffusion write FDiffusion; property GAIN : Single read FGain write FGain; property GAINHF : Single read FGainHF write FGainHF; property DECAY_TIME : Single read FDecay_Time write FDecay_Time; property DECAY_HFRATIO : Single read FDecay_HFRatio write FDecay_HFRatio; property REFLECTIONS_GAIN : Single read FReflections_Gain write FReflections_Gain; property REFLECTIONS_DELAY : Single read FReflections_Delay write FReflections_Delay; property LATE_REVERB_GAIN : Single read FLate_Reverb_Gain write FLate_Reverb_Gain; property LATE_REVERB_DELAY : Single read FLate_Reverb_Delay write FLate_Reverb_Delay; property AIR_ABSORPTION_GAINHF : Single read FAir_Absorption_GainHF write FAir_Absorption_GainHF; property ROOM_ROLLOFF_FACTOR : Single read FRoom_RollOff_Factor write FRoom_RollOff_Factor; property DECAY_HFLIMIT : Boolean read FDecay_HFLimit write FDecay_HFLimit; end; { Description de l'effet audio "EAX Reverb" } TBZEAXReverbSoundEffect = Class(TBZCustomSoundEffectItem) private FPreset : TBZSoundReverbEnvironment; FDENSITY : Single; FDIFFUSION : Single; FGAIN : Single; FGAINHF : Single; FGAINLF : Single; FDECAY_TIME : Single; FDECAY_HFRATIO : Single; FDECAY_LFRATIO : Single; FREFLECTIONS_GAIN : Single; FREFLECTIONS_DELAY : Single; // FREFLECTIONS_PAN : TBZVector; FLATE_REVERB_GAIN : Single; FLATE_REVERB_DELAY : Single; // FLATE_REVERB_PAN : TBZVector; FECHO_TIME : Single; FECHO_DEPTH : Single; FMODULATION_TIME : Single; FMODULATION_DEPTH : Single; FAIR_ABSORPTION_GAINHF : Single; FHF_REFERENCE : Single; FLF_REFERENCE : Single; FROOM_ROLLOFF_FACTOR : Single; FDECAY_HFLIMIT : Boolean; procedure SetPreset(val : TBZSoundReverbEnvironment); protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; published property Preset : TBZSoundReverbEnvironment read FPreset write SetPreset; property DENSITY : Single read FDensity write FDensity; property DIFFUSION : Single read FDiffusion write FDiffusion; property GAIN : Single read FGain write FGain; property GAINHF : Single read FGainHF write FGainHF; property GAINLF : Single read FGainHF write FGainLF; property DECAY_TIME : Single read FDecay_Time write FDecay_Time; property DECAY_HFRATIO : Single read FDecay_HFRatio write FDecay_LFRatio; property DECAY_LFRATIO : Single read FDecay_LFRatio write FDecay_LFRatio; property REFLECTIONS_GAIN : Single read FReflections_Gain write FReflections_Gain; property REFLECTIONS_DELAY : Single read FReflections_Delay write FReflections_Delay; // property REFLECTIONS_PAN : TBZVector read FReflections_Pan write FReflections_Pan; property LATE_REVERB_GAIN : Single read FLate_Reverb_Gain write FLate_Reverb_Gain; property LATE_REVERB_DELAY : Single read FLate_Reverb_Delay write FLate_Reverb_Delay; // property LATE_REVERB_PAN : TBZVector read FLate_Reverb_Delay write FLate_Reverb_Pan; property ECHO_TIME : Single read FEcho_Time write FEcho_Time; property ECHO_DEPTH : Single read FEcho_Depth write FEcho_Depth; property MODULATION_TIME : Single read FModulation_Time write FModulation_Time; property MODULATION_DEPTH : Single read FModulation_Depth write FModulation_Depth; property AIR_ABSORPTION_GAINHF : Single read FAir_Absorption_GainHF write FAir_Absorption_GainHF; property HF_REFERENCE : Single read FHF_Reference write FHF_Reference; property LF_REFERENCE : Single read FLF_Reference write FLF_Reference; property ROOM_ROLLOFF_FACTOR : Single read FRoom_RollOff_Factor write FRoom_RollOff_Factor; property DECAY_HFLIMIT : Boolean read FDecay_HFLimit write FDecay_HFLimit; end; { Description de l'effet audio "Chorus" } TBZChorusSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Description de l'effet audio "Echo" } TBZEchoSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Description de l'effet audio "Distortion" } TBZDistortionSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Description de l'effet audio "Flanger" } TBZFlangerSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Description de l'effet audio "Compressor" } TBZCompressorSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Description de l'effet audio "Equalizer" } TBZEqualizerSoundEffect = Class(TBZCustomSoundEffectItem) private protected procedure WriteToFiler(Awriter: TWriter); override; procedure ReadFromFiler(Areader: TReader); override; public constructor Create(AOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: String; override; end; { Gestion d'une collection d'effets audio } TBZSoundFXLib = class(TBZXCollection) protected function GetItem(index: Integer): TBZCustomSoundFXItem; public function GetNamePath: string; override; class function ItemsClass: TBZXCollectionItemClass; override; property FXItems[index: Integer]: TBZCustomSoundFXItem read GetItem; default; function CanAdd(aClass: TBZXCollectionItemClass): Boolean; override; //procedure DoProgress(const progressTimes: TBZProgressTimes); function GetItemByName(const AName: TBZSoundFXName): TBZCustomSoundFXItem; function AddFilterLowPass(AName: TBZSoundFXName) : TBZLowPassSoundFilter; function AddFilterHighPass(AName: TBZSoundFXName) : TBZHighPassSoundFilter; function AddFilterBandPass(AName: TBZSoundFXName) : TBZBandPassSoundFilter; function GetFilterLowPassByName(const AName: TBZSoundFXName): TBZLowPassSoundFilter; function GetFilterHighPassByName(const AName: TBZSoundFXName): TBZHighPassSoundFilter; function GetFilterBandPassByName(const AName: TBZSoundFXName): TBZBandPassSoundFilter; function AddEffectReverb(AName: TBZSoundFXName) : TBZReverbSoundEffect; function AddEffectEAXReverb(AName: TBZSoundFXName) : TBZEAXReverbSoundEffect; function AddEffectChorus(AName: TBZSoundFXName) : TBZChorusSoundEffect; function AddEffectEcho(AName: TBZSoundFXName) : TBZEchoSoundEffect; function AddEffectDistortion(AName: TBZSoundFXName) : TBZDistortionSoundEffect; function AddEffectFlanger(AName: TBZSoundFXName) : TBZFlangerSoundEffect; function AddEffectCompressor(AName: TBZSoundFXName) : TBZCompressorSoundEffect; function AddEffectEqualizer(AName: TBZSoundFXName) : TBZEqualizerSoundEffect; function GetEffectReverbByName(const AName: TBZSoundFXName): TBZReverbSoundEffect; function GetEffectEAXReverbByName(const AName: TBZSoundFXName): TBZEAXReverbSoundEffect; function GetEffectChorusByName(const AName: TBZSoundFXName): TBZChorusSoundEffect; function GetEffectEchoByName(const AName: TBZSoundFXName): TBZEchoSoundEffect; function GetEffectDistortionByName(const AName: TBZSoundFXName): TBZDistortionSoundEffect; function GetEffectFlangerByName(const AName: TBZSoundFXName): TBZFlangerSoundEffect; function GetEffectCompressorByName(const AName: TBZSoundFXName): TBZCompressorSoundEffect; function GetEffectEqualizerByName(const AName: TBZSoundFXName): TBZEqualizerSoundEffect; end; { Composant non-visuel pour gérer une liste d'effets audio } TBZSoundFXLibrary = class(TComponent) private FSoundFXLib: TBZSoundFXLib; protected procedure SetSoundFXLib(const val: TBZSoundFXLib); procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property FX: TBZSoundFXLib read FSoundFXLib write SetSoundFXLib; end; { Descritpion d'un "Slot" permettant d'assigner un effet à un échantillon audio } TBZSoundFXAuxSlot = class(TCollectionItem) private FTag : PtrUInt; FSoundFXLibrary : TBZSoundFXLibrary; FSoundFXLibraryName : String; FSoundFXName : String; FSoundFXCache : TBZCustomSoundFXItem; FActivated : Boolean; FEffectGain : Single; FAutoAdjust : Boolean; function GetSoundFXLibrary : TBZSoundFXLibrary; procedure SetSoundFXLibrary(Const AValue : TBZSoundFXLibrary); // procedure SetSoundFXLibraryName(AValue : String); procedure SetSoundFXName(Val : String); procedure SetActivated(val : Boolean); protected procedure WriteToFiler(Awriter: TWriter); procedure ReadFromFiler(Areader: TReader); public constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; //procedure SetCacheFX(Val : TBZCustomSoundFXItem); property ManagerTag : PtrUInt read FTag write FTag; property CacheFX : TBZCustomSoundFXItem read FSoundFXCache; property SoundFXLibrary : TBZSoundFXLibrary read GetSoundFXLibrary write SetSoundFXLibrary; published property SoundFXlibraryName : String Read FSoundFXLibraryName Write FSoundFXLibraryName; property Name : String read FSoundFXName Write SetSoundFXName; property Activated : Boolean read FActivated Write SetActivated; property Gain : Single read FEffectGain write FEffectGain; property AutoAdjust : Boolean read FAutoAdjust write FAutoAdjust; End; { Gestion d'une collection de "slots" } TBZSoundFXAuxSlots = class(TCollection) protected FOwner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TBZSoundFXAuxSlot); function GetItems(index: Integer): TBZSoundFXAuxSlot; function FindItemID(ID: Integer): TBZSoundFXAuxSlot; public constructor Create(AOwner: TComponent); function Add: TBZSoundFXAuxSlot; property Items[index: Integer]: TBZSoundFXAuxSlot read GetItems write SetItems; default; End; { Description de base d'un échantillon audio } TBZBaseSoundSource = class(TCollectionItem) private //FBehaviourToNotify: TBZBSoundEmitter; FAutoFreeOnStop : Boolean; // private only, NOT persistent, not assigned FPriority: Integer; //FOrigin: TBZBaseSceneObject; // NOT persistent FVolume: Single; FMinDistance, FMaxDistance: Single; FInsideConeAngle, FOutsideConeAngle: Single; FConeOutsideVolume: Single; FSoundLibraryName: string; // used for persistence FSoundLibrary: TBZSoundLibrary; // persistence via name FSoundName: string; FSoundFXLibraryName : String; FSoundFXLibrary: TBZSoundFXLibrary; // persistence via name FAuxSlots : TBZSoundFXAuxSlots; (* FAuxSlots: array of PtrUInt; FAuxSlotCount : Byte; FAuxSlotFXName : array of string; FAuxSlotFXActivated : array of Boolean; FAuxSlotFXCache : Array of TBZCustomSoundFXItem; *) // FDirectFilteringType : TBZSoundFilteringType; FDirectFilterName : String; FDirectFilterActivated : Boolean; FDirectFilterTag : PtrUInt; FDirectFilterCache : TBZCustomSoundFilterItem; FMute: Boolean; FPause: Boolean; FPlaying: Boolean; FPitch : Single; FChanges: TBZSoundSourceChanges; // NOT persistent, not assigned FFXChanges: TBZSoundSourceFXChanges; // NOT persistent, not assigned FNbLoops: Integer; FTag: PtrUInt; // NOT persistent, not assigned FLoaded : Boolean; FTimePosition : Single; FFrequency: Integer;// A voir si on garde FUseEnvironnment : Boolean; //Slot 2 FUseEqualizer : Boolean; //Slot 3 protected procedure WriteToFiler(Awriter: TWriter); procedure ReadFromFiler(Areader: TReader); function GetDisplayName: string; override; procedure SetPriority(const val: Integer); //procedure SetOrigin(const val: TBZBaseSceneObject); procedure SetVolume(const val: Single); procedure SetMinDistance(const val: Single); procedure SetMaxDistance(const val: Single); procedure SetInsideConeAngle(const val: Single); procedure SetOutsideConeAngle(const val: Single); procedure SetConeOutsideVolume(const val: Single); function GetSoundLibrary: TBZSoundLibrary; procedure SetSoundLibrary(const val: TBZSoundLibrary); procedure SetSoundName(const val: string); function GetSoundFXLibrary: TBZSoundFXLibrary; procedure SetSoundFXLibrary(const val: TBZSoundFXLibrary); procedure setDirectFilterName(val : String); procedure SetDirectFilterActivated(val : Boolean); function GetDirectFilterActivated: Boolean; function GetDirectFilterFXCache:TBZCustomSoundFilterItem; procedure SetMute(const val: Boolean); procedure SetPause(const val: Boolean); procedure SetPlaying(const val: Boolean); procedure SetNbLoops(const val: Integer); procedure SetFrequency(const val: Integer); procedure SetPitch(const val: Single); Function GetTimePositionInByte:Int64; //function GetPeaksMeter(PosInByte : Int64; var Channels : Array of single); public //OpenALBuffers : array[0..1] of PtrUInt; // Pour OpenAL constructor Create(ACollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property Changes: TBZSoundSourceChanges read FChanges Write FChanges; property FXChanges: TBZSoundSourceFXChanges read FFXChanges Write FFXChanges; function Sample: TBZSoundSampleItem; procedure UpdateTimePosition(Const val : Single); // This Tag is reserved for sound manager use only property ManagerTag: PtrUInt read FTag write FTag; property DirectFilterTag : PtrUInt read FDirectFilterTag write FDirectFilterTag; property DirectFilterFX : TBZCustomSoundFilterItem read GetDirectFilterFXCache; { Origin object for the sound sources. Absolute object position/orientation are taken into account, the object's TBZBInertia is considered if any. If origin is nil, the source is assumed to be static at the origin. Note : since TCollectionItem do not support the "Notification" scheme, it is up to the Origin object to take care of updating this property prior to release/destruction. } //property Origin: TBZBaseSceneObject read FOrigin write SetOrigin; // property DirectFilter : TBZCustomSoundFilter read FDirectFilter; property TimePosition : Single Read FTimePosition; property TimePositionInByte : Int64 read GetTimePositionInByte; published property SoundLibrary: TBZSoundLibrary read GetSoundLibrary write SetSoundLibrary; property SoundName: string read FSoundName write SetSoundName; property SoundFXLibrary : TBZSoundFXLibrary read GetSoundFXLibrary write SetSoundFXLibrary; property DirectFilter : String read FDirectFilterName Write setDirectFilterName; property DirectFilterActivated : Boolean read GetDirectFilterActivated Write setDirectFilterActivated; property AuxSlots : TBZSoundFXAuxSlots read FAuxSlots; { Volume of the source, [0.0; 1.0] range } property Volume: Single read FVolume write SetVolume; { Nb of playing loops. } property NbLoops: Integer read FNbLoops write SetNbLoops default 1; property Mute: Boolean read FMute write SetMute default False; property Pause: Boolean read FPause write SetPause default False; property Playing: Boolean read FPlaying write SetPlaying default False; { Sound source priority, the higher the better. When maximum number of sound sources is reached, only the sources with the highest priority will continue to play, however, even non-playing sources should be tracked by the manager, thus allowing an "unlimited" amount of sources from the application point of view. } property Priority: Integer read FPriority write SetPriority default 0; { Min distance before spatial attenuation occurs. 1.0 by default } property MinDistance: Single read FMinDistance write SetMinDistance; { Max distance, if source is further away, it will not be heard. 100.0 by default } property MaxDistance: Single read FMaxDistance write SetMaxDistance; { Inside cone angle, [0° 360°]. Sound volume is maximal within this cone. See DirectX SDK for details. } property InsideConeAngle: Single read FInsideConeAngle write SetInsideConeAngle; { Outside cone angle, [0°; 360°]. Between inside and outside cone, sound volume decreases between max and cone outside volume. See DirectX SDK for details. } property OutsideConeAngle: Single read FOutsideConeAngle write SetOutsideConeAngle; { Cone outside volume, [0.0; 1.0] range. See DirectX SDK for details. } property ConeOutsideVolume: Single read FConeOutsideVolume write SetConeOutsideVolume; { Sample custom playback frequency. Values null or negative are interpreted as 'default frequency'. } property Frequency: Integer read FFrequency write SetFrequency default -1; property Pitch: Single read FPitch write SetPitch default 1.0; property UseEnvironnment : Boolean read FUseEnvironnment write FUseEnvironnment; property UseEqualizer : Boolean read FUseEnvironnment write FUseEqualizer; property AutoFreeOnStop : Boolean read FAutoFreeOnStop write FAutoFreeOnStop; end; { Description d'un échantillon audio avec prise en charge de l'orientation. @br @bold(Note) : l'orientation" est la Direction de propagation l'onde sonore} TBZSoundSource = class(TBZBaseSoundSource) public destructor Destroy; override; published //property Origin; end; { Gestion d'une collection d'échantillons audio } TBZSoundSources = class(TCollection) protected FOwner: TComponent; function GetOwner: TPersistent; override; procedure SetItems(index: Integer; const val: TBZSoundSource); function GetItems(index: Integer): TBZSoundSource; function Add: TBZSoundSource; function FindItemID(ID: Integer): TBZSoundSource; public constructor Create(AOwner: TComponent); property Items[index: Integer]: TBZSoundSource read GetItems write SetItems; default; end; TBZSoundManagerChange = (smcTransformation, smcEnvironnment, smcEqualizer); //sscEffects, sscFiltersmc TBZSoundManagerChanges = set of TBZSoundManagerChange; { @abstract(Classe de base pour les composants du gestionnaire de son. @br Le composant sound manager est l'interface d'une API audio de bas niveau (comme DirectSound, Bass, FMod, OpenAL...)) Il ne peut y avoir qu'un seul gestionnaire actif à tout moment (Cette classe prend soin de cela). @br La sous-classe doit remplacer les méthodes protégées DoActivate et DoDeActivate pour 'initialiser / unitialiser' leur couche sonore. } TBZSoundManager = class(TBZCadenceAbleComponent) private FActive: Boolean; FMute: Boolean; FPause: Boolean; FPlaying : Boolean; FMasterVolume: Single; //FListener: TBZBaseSceneObject; //FLastListenerPosition: TVector; FSources: TBZSoundSources; FMaxChannels: Integer; FOutputFrequency: Integer; FUpdateFrequency: Single; FDistanceFactor: Single; FRollOffFactor: Single; FDopplerFactor: Single; FSoundEnvironment: TBZSoundReverbEnvironment; FLastUpdateTime, FLastDeltaTime: Single; // last time UpdateSources was fired, not persistent FCadencer: TBZCadencer; FUseEnvironment : Boolean; procedure SetActive(const val: Boolean); procedure SetMute(const val: Boolean); procedure SetPause(const val: Boolean); procedure SetPlaying(const val: Boolean); procedure SetUseEnvironment(const val: Boolean); procedure WriteDoppler(writer: TWriter); procedure ReadDoppler(reader: TReader); protected procedure Notification(AComponent: TComponent; Operation: TOperation);override; procedure SetSources(const val: TBZSoundSources); procedure SetMasterVolume(const val: Single); //procedure SetListener(const val: TBZBaseSceneObject); procedure SetMaxChannels(const val: Integer); procedure SetOutputFrequency(const val: Integer); procedure SetUpdateFrequency(const val: Single); function StoreUpdateFrequency: Boolean; procedure SetCadencer(const val: TBZCadencer); procedure SetDistanceFactor(const val: Single); function StoreDistanceFactor: Boolean; procedure SetRollOffFactor(const val: Single); function StoreRollOffFactor: Boolean; procedure SetDopplerFactor(const val: Single); procedure SetSoundEnvironment(const val: TBZSoundReverbEnvironment); procedure Loaded; override; procedure DefineProperties(Filer: TFiler); override; procedure ListenerCoordinates(var position, velocity, direction, up: TBZVector); function DoActivate: Boolean; dynamic; // Invoked AFTER all sources have been stopped procedure DoDeActivate; dynamic; { Effect mute of all sounds. Default implementation call MuteSource for all non-muted sources with "True" as parameter. } function DoMute: Boolean; dynamic; { Effect un-mute of all sounds. Default implementation call MuteSource for all non-muted sources with "False" as parameter. } procedure DoUnMute; dynamic; { Effect pause of all sounds. Default implementation call PauseSource for all non-paused sources with "True" as parameter. } function DoPause: Boolean; dynamic; { Effect un-pause of all sounds. Default implementation call PauseSource for all non-paused sources with "True" as parameter. } procedure DoUnPause; dynamic; procedure DoPlay;Dynamic; procedure DoStop;Dynamic; procedure NotifyMasterVolumeChange; dynamic; procedure Notify3DFactorsChanged; dynamic; procedure NotifyEnvironmentChanged; dynamic; // Called when a source will be freed procedure KillSource(aSource: TBZBaseSoundSource); virtual; { Request to update source's data in low-level sound API. Default implementation just clears the "Changes" flags. } procedure UpdateSource(aSource: TBZBaseSoundSource); virtual; procedure MuteSource(aSource: TBZBaseSoundSource; muted: Boolean); virtual; procedure PauseSource(aSource: TBZBaseSoundSource; paused: Boolean); virtual; procedure PlaySource(aSource : TBZBaseSoundSource; playing : Boolean); virtual; function GetDefaultFrequency(aSource : TBZBaseSoundSource) : Integer; virtual; function GetTimePosition(aSource : TBZBaseSoundSource): Single; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Manual request to update all sources to reflect changes. Default implementation invokes UpdateSource for all known sources. } procedure UpdateSources; virtual; { Stop and free all sources. } procedure StopAllSources; { Progress notification for time synchronization. This method will call UpdateSources depending on the last time it was performed and the value of the UpdateFrequency property. } procedure DoProgress(const progressTime: TBZProgressTimes); override; { Sound manager API reported CPU Usage. Returns -1 when unsupported. } function CPUUsagePercent: Single; virtual; { True if EAX is supported. } function EAXSupported: Boolean; dynamic; function GetInformations : String; virtual; published { Activation/deactivation of the low-level sound API } property Active: Boolean read FActive write SetActive default False; { Maximum number of sound output channels. While some drivers will just ignore this value, others cannot dynamically adjust the maximum number of channels (you need to de-activate and re-activate the manager for this property to be taken into account). } property MaxChannels: Integer read FMaxChannels write SetMaxChannels default 8; { Sound output mixing frequency. Commonly used values ar 11025, 22050 and 44100. Note that most driver cannot dynamically adjust the output frequency (you need to de-ativate and re-activate the manager for this property to be taken into account). } property OutputFrequency: Integer read FOutputFrequency write SetOutputFrequency default 44100; { Request to mute all sounds. All sound requests should be handled as if sound is unmuted though, however drivers should try to take a CPU advantage of mute over MasterVolume=0 } property Mute: Boolean read FMute write SetMute default False; { Request to pause all sound, sound output should be muted too. When unpausing, all sound should resume at the point they were paused. } property Pause: Boolean read FPause write SetPause default False; { Master Volume adjustement in the [0.0; 1.0] range. Driver should take care of properly clamping the master volume. } property MasterVolume: Single read FMasterVolume write SetMasterVolume; { Scene object that materializes the listener. The sceneobject's AbsolutePosition and orientation are used to define the listener coordinates, velocity is automatically calculated (if you're using DoProgress or connected the manager to a cadencer). If this property is nil, the listener is assumed to be static at the NullPoint coordinate, facing Z axis, with up being Y (ie. the default GLScene orientation). } // property Listener: TBZBaseSceneObject read FListener write SetListener; { Currently active and playing sound sources. } property Sources: TBZSoundSources read FSources write SetSources; { Update frequency for time-based control (DoProgress). Default value is 10 Hz (frequency is clamped in the 1Hz-60Hz range). } property UpdateFrequency: Single read FUpdateFrequency write SetUpdateFrequency stored StoreUpdateFrequency; { Cadencer for time-based control. } property Cadencer: TBZCadencer read FCadencer write SetCadencer; { Engine relative distance factor, compared to 1.0 meters. Equates to 'how many units per meter' your engine has. } property DistanceFactor: Single read FDistanceFactor write SetDistanceFactor stored StoreDistanceFactor; { Sets the global attenuation rolloff factor. Normally volume for a sample will scale at 1 / distance. This gives a logarithmic attenuation of volume as the source gets further away (or closer). Setting this value makes the sound drop off faster or slower. The higher the value, the faster volume will fall off. } property RollOffFactor: Single read FRollOffFactor write SetRollOffFactor stored StoreRollOffFactor; { Engine relative Doppler factor, compared to 1.0 meters. Equates to 'how many units per meter' your engine has. } property DopplerFactor: Single read FDopplerFactor write SetDopplerFactor stored False; { Sound environment (requires EAX compatible soundboard). } property Environment: TBZSoundReverbEnvironment read FSoundEnvironment write SetSoundEnvironment default seGeneric; property UseEnvironment : Boolean read FUseEnvironment write SetUseEnvironment; // property Equalizer : TBZEqualizerSoundEffect read FEqualizer; end; // TBZBSoundEmitter // { A sound emitter behaviour, plug it on any object to make it noisy. This behaviour is just an interface to a TBZSoundSource, for editing convenience. } (* TBZBSoundEmitter = class(TBZBehaviour) private FPlaying: Boolean; // used at design-time ONLY FSource: TBZBaseSoundSource; FPlayingSource: TBZSoundSource; protected procedure WriteToFiler(writer: TWriter); override; procedure ReadFromFiler(reader: TReader); override; procedure Loaded; override; procedure SetSource(const val: TBZBaseSoundSource); procedure SetPlaying(const val: Boolean); function GetPlaying: Boolean; procedure NotifySourceDestruction(aSource: TBZSoundSource); public constructor Create(aOwner: TBZXCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; class function FriendlyName: string; override; class function FriendlyDescription: string; override; class function UniqueItem: Boolean; override; procedure DoProgress(const progressTime: TProgressTimes); override; property PlayingSource: TBZSoundSource read FPlayingSource; published property Source: TBZBaseSoundSource read FSource write SetSource; property Playing: Boolean read GetPlaying write SetPlaying default False; end; *) { Retourne le gestionnaire d'audio actuellement actif } function ActiveSoundManager: TBZSoundManager; { Retourne la librairie d'un échantillon audio d'après son nom } function GetSoundLibraryByName(const aName: string): TBZSoundLibrary; //function GetOrCreateSoundEmitter(behaviours: TBZBehaviours): TBZBSoundEmitter; overload; //function GetOrCreateSoundEmitter(obj: TBZBaseSceneObject): TBZBSoundEmitter; overload; var { Variable global pour l'affichage des erreurs } vVerboseGLSMErrors: Boolean = True; //vActiveSoundManager: TBZSoundManager; implementation uses BZUtils, BZMath, BZLIbOpenAL, Dialogs; var vSoundLibraries: TList; vSoundFXLibraries: TList; vActiveSoundManager: TBZSoundManager; vBZSoundFXItemNameChangeEvent: TNotifyEvent; function ActiveSoundManager: TBZSoundManager; begin Result := vActiveSoundManager; end; function GetSoundLibraryByName(const aName: string): TBZSoundLibrary; var i: Integer; begin Result := nil; if Assigned(vSoundLibraries) then for i := 0 to vSoundLibraries.Count - 1 do if TBZSoundLibrary(vSoundLibraries[i]).Name = aName then begin Result := TBZSoundLibrary(vSoundLibraries[i]); Break; end; end; function GetSoundFXLibraryByName(const aName: string): TBZSoundFXLibrary; var i: Integer; begin Result := nil; if Assigned(vSoundFXLibraries) then for i := 0 to vSoundLibraries.Count - 1 do if TBZSoundFXLibrary(vSoundFXLibraries[i]).Name = aName then begin Result := TBZSoundFXLibrary(vSoundFXLibraries[i]); Break; end; end; (* function GetOrCreateSoundEmitter(behaviours: TBZBehaviours): TBZBSoundEmitter; var i: Integer; begin i := behaviours.IndexOfClass(TBZBSoundEmitter); if i >= 0 then Result := TBZBSoundEmitter(behaviours[i]) else Result := TBZBSoundEmitter.Create(behaviours); end; function GetOrCreateSoundEmitter(obj: TBZBaseSceneObject): TBZBSoundEmitter; begin Result := GetOrCreateSoundEmitter(obj.Behaviours); end; *) {%region=====[ TBZSoundSampleItem ]===============================================} constructor TBZSoundSampleItem.Create(ACollection: TCollection); begin inherited Create(ACollection); FData := TBZSoundSample.Create(Self); end; destructor TBZSoundSampleItem.Destroy; begin FreeAndNil(FData); inherited Destroy; end; procedure TBZSoundSampleItem.Assign(Source: TPersistent); begin if Source is TBZSoundSampleItem then begin FName := TBZSoundSampleItem(Source).Name; FData.Free; FData := TBZSoundSample(TBZSoundSampleItem(Source).Data.CreateCopy(Self)); end else inherited Assign(Source); // error end; procedure TBZSoundSampleItem.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('BinData', @ReadData, @WriteData, Assigned(FData)); end; procedure TBZSoundSampleItem.ReadData(Stream: TStream); var n: Integer; clName: AnsiString; begin n:=0; with Stream do begin Read(n, SizeOf(Integer)); SetLength(clName, n); if n > 0 then Read(clName[1], n); FData := TBZSoundSample.Create(Self); //TBZSoundSampleClass(FindClass(string(clName))).Create(Self); FData.LoadFromStream(Stream); end; end; procedure TBZSoundSampleItem.WriteData(Stream: TStream); var n: Integer; buf: AnsiString; begin with Stream do begin n := Length(FData.ClassName); Write(n, SizeOf(Integer)); buf := AnsiString(FData.ClassName); if n > 0 then Write(buf[1], n); FData.SaveToStream(Stream); end; end; function TBZSoundSampleItem.GetDisplayName: string; var s: string; begin if Assigned(FData) then begin if Data.NbChannels > 1 then s := 's' else s := ''; Result := Format('%s (%d Hz, %d bits, %d channel%s, %.2f sec)', [Name, Data.Frequency, Data.BitsPerSample, Data.NbChannels, s, Data.LengthInSec]) end else Result := Format('%s (empty)', [Name]); end; procedure TBZSoundSampleItem.LoadFromFile(const fileName: string); begin FData.LoadFromFile(FileName); FName := ExtractFileName(fileName); end; (* procedure TBZSoundSampleItem.PlayOnWaveOut; begin if Assigned(FData) then FData.PlayOnWaveOut; end; *) procedure TBZSoundSampleItem.SetData(const val: TBZSoundSample); begin FData.Free; if Assigned(val) then FData := TBZSoundSample(val.CreateCopy(Self)) else FData := nil; end; constructor TBZSoundSampleItems.Create(AOwner: TComponent); begin FOwner := AOwner; inherited Create(TBZSoundSampleItem); end; function TBZSoundSampleItems.GetOwner: TPersistent; begin Result := Owner; end; {%endregion%} {%region=====[ TBZSoundSampleItems ]==============================================} procedure TBZSoundSampleItems.SetItems(index: Integer; const val: TBZSoundSampleItem); begin inherited Items[index] := val; end; function TBZSoundSampleItems.GetItems(index: Integer): TBZSoundSampleItem; begin Result := TBZSoundSampleItem(inherited Items[index]); end; function TBZSoundSampleItems.Add: TBZSoundSampleItem; begin Result := TBZSoundSampleItem.Create(Self);//(inherited Add) as TBZSoundSampleItem; end; function TBZSoundSampleItems.FindItemID(ID: Integer): TBZSoundSampleItem; begin Result := (inherited FindItemID(ID)) as TBZSoundSampleItem; end; function TBZSoundSampleItems.GetByName(const aName: string): TBZSoundSampleItem; var i: Integer; begin Result := nil; for i := 0 to Count - 1 do if CompareText(Items[i].Name, aName) = 0 then begin Result := Items[i]; Break; end; end; function TBZSoundSampleItems.AddFile(const fileName: string; const sampleName: string = ''): TBZSoundSampleItem; begin Result := Add; Result.LoadFromFile(fileName); if sampleName <> '' then Result.Name := sampleName; end; {%endregion%} {%region=====[ TBZSoundLibrary ]==============================================} constructor TBZSoundLibrary.Create(AOwner: TComponent); begin inherited Create(AOwner); FSamples := TBZSoundSampleItems.Create(Self); vSoundLibraries.Add(Self); end; destructor TBZSoundLibrary.Destroy; begin vSoundLibraries.Remove(Self); FSamples.Free; inherited Destroy; end; procedure TBZSoundLibrary.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; end; procedure TBZSoundLibrary.SetSamples(const val: TBZSoundSampleItems); begin FSamples.Assign(val); end; {%endregion%} {%region=====[ TBZCustomSoundFXItem ]=========================================} constructor TBZCustomSoundFXItem.Create(aOwner: TBZXCollection); begin inherited Create(aOwner); FTag := 0; end; destructor TBZCustomSoundFXItem.Destroy; begin inherited Destroy; end; procedure TBZCustomSoundFXItem.SetName(const val: string); begin inherited SetName(val); if Assigned(vBZSoundFXItemNameChangeEvent) then vBZSoundFXItemNameChangeEvent(Self); end; procedure TBZCustomSoundFXItem.WriteToFiler(Awriter: TWriter); begin inherited; with Awriter do begin WriteInteger(0); // Archive Version 0 end; end; procedure TBZCustomSoundFXItem.ReadFromFiler(Areader: TReader); begin if Owner.ArchiveVersion > 0 then inherited; with AReader do begin if ReadInteger <> 0 then Assert(False); end; end; class function TBZCustomSoundFXItem.FriendlyName: String; begin Result := 'Custom_Sound_FX_Item'; End; (*function TBZCustomSoundFXItem.OwnerBaseSceneObject: TGLBaseSceneObject; begin Result := TGLBaseSceneObject(Owner.Owner); end; procedure TBZCustomSoundFXItem.DoProgress(const progressTime: TProgressTimes); begin end; *) {%endregion%} {%region=====[ TBZCustomSoundEffectItem ]=====================================} function TBZCustomSoundEffectItem.GetFilter:TBZCustomSoundFilterItem; var idx : integer; begin Result := nil; idx := Owner.IndexOfName(FFilterName); if idx>0 then Result := TBZCustomSoundFilterItem(Owner.Items[Idx]); end; class function TBZCustomSoundEffectItem.FriendlyName: String; begin Result := 'Custom_Sound_Effect_Item'; End; {%endregion%} {%region=====[ TBZReverbSoundEffect ]=========================================} constructor TBZReverbSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); FPreset := seGeneric; FDENSITY := 1.0; FDIFFUSION := 1.0; FGAIN := 0.32; FGAINHF := 0.89; FDECAY_TIME := 1.49; FDECAY_HFRATIO := 0.83; FREFLECTIONS_GAIN := 0.05; FREFLECTIONS_DELAY := 0.007; FLATE_REVERB_GAIN := 1.26; FLATE_REVERB_DELAY := 0.011; FAIR_ABSORPTION_GAINHF := 0.994; FROOM_ROLLOFF_FACTOR := 0.0; FDECAY_HFLIMIT := True; end; destructor TBZReverbSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZReverbSoundEffect.FriendlyName: String; begin Result := 'EFX_Reverb_Sound_Effect'; End; procedure TBZReverbSoundEffect.SetPreset(val : TBZSoundReverbEnvironment); var ThePreset : EFXEAXREVERBPROPERTIES; procedure SetParams(aPreset : EFXEAXREVERBPROPERTIES); begin FDENSITY := aPreset.flDensity; FDIFFUSION := aPreset.flDiffusion; FGAIN := aPreset.flGain; FGAINHF := aPreset.flGainHF; FDECAY_TIME := aPreset.flDecayTime; FDECAY_HFRATIO := aPreset.flDecayHFRatio; FREFLECTIONS_GAIN := aPreset.flReflectionsGain; FREFLECTIONS_DELAY := aPreset.flReflectionsDelay; FLATE_REVERB_GAIN := aPreset.flLateReverbGain; FLATE_REVERB_DELAY := aPreset.flLateReverbDelay; FAIR_ABSORPTION_GAINHF := aPreset.flAirAbsorptionGainHF; FROOM_ROLLOFF_FACTOR := aPreset.flRoomRolloffFactor; FDECAY_HFLIMIT := (aPreset.iDecayHFLimit>0); End; begin Case val of seGeneric : ThePreset := EFX_REVERB_PRESET_GENERIC; sePaddedCell : ThePreset := EFX_REVERB_PRESET_PADDEDCELL; seRoom : ThePreset := EFX_REVERB_PRESET_ROOM; seBathroom : ThePreset := EFX_REVERB_PRESET_BATHROOM; seLivingRoom : ThePreset := EFX_REVERB_PRESET_LIVINGROOM; seStoneroom : ThePreset := EFX_REVERB_PRESET_STONEROOM; seAuditorium : ThePreset := EFX_REVERB_PRESET_AUDITORIUM; seConcertHall : ThePreset := EFX_REVERB_PRESET_CONCERTHALL; seCave : ThePreset := EFX_REVERB_PRESET_CAVE; seArena : ThePreset := EFX_REVERB_PRESET_ARENA; seHangar : ThePreset := EFX_REVERB_PRESET_HANGAR; seCarpetedHallway : ThePreset := EFX_REVERB_PRESET_CARPETEDHALLWAY; seHallway : ThePreset := EFX_REVERB_PRESET_HALLWAY; seStoneCorridor : ThePreset := EFX_REVERB_PRESET_STONECORRIDOR; seAlley : ThePreset := EFX_REVERB_PRESET_ALLEY; seForest : ThePreset := EFX_REVERB_PRESET_FOREST; seCity : ThePreset := EFX_REVERB_PRESET_CITY; seMountains : ThePreset := EFX_REVERB_PRESET_MOUNTAINS; seQuarry : ThePreset := EFX_REVERB_PRESET_QUARRY; sePlain : ThePreset := EFX_REVERB_PRESET_PLAIN; seParkingLot : ThePreset := EFX_REVERB_PRESET_PARKINGLOT; seSewerPipe : ThePreset := EFX_REVERB_PRESET_SEWERPIPE; seUnderWater : ThePreset := EFX_REVERB_PRESET_UNDERWATER; seDrugged : ThePreset := EFX_REVERB_PRESET_DRUGGED; seDizzy : ThePreset := EFX_REVERB_PRESET_DIZZY; sePsychotic : ThePreset := EFX_REVERB_PRESET_PSYCHOTIC; seCastle_SmallRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_SMALLROOM; seCastle_ShortPassage : ThePreset := EFX_REVERB_PRESET_CASTLE_SHORTPASSAGE; seCastle_MediumRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_MEDIUMROOM; seCastle_LargeRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_LARGEROOM; seCastle_LongPassage : ThePreset := EFX_REVERB_PRESET_CASTLE_LONGPASSAGE; seCastle_Hall : ThePreset := EFX_REVERB_PRESET_CASTLE_HALL; seCastle_CupBoarb : ThePreset := EFX_REVERB_PRESET_CASTLE_CUPBOARD; seCastle_CourtYard : ThePreset := EFX_REVERB_PRESET_CASTLE_COURTYARD; seCastle_Alcove : ThePreset := EFX_REVERB_PRESET_CASTLE_ALCOVE; seFactory_SmallRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_SMALLROOM; seFactory_ShortPassage : ThePreset := EFX_REVERB_PRESET_FACTORY_SHORTPASSAGE; seFactory_MediumRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_MEDIUMROOM; seFactory_LargeRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_LARGEROOM; seFactory_LongPassage : ThePreset := EFX_REVERB_PRESET_FACTORY_LONGPASSAGE; seFactory_Hall : ThePreset := EFX_REVERB_PRESET_FACTORY_HALL; seFactory_CupBoard : ThePreset := EFX_REVERB_PRESET_FACTORY_CUPBOARD; seFactory_CourtYard : ThePreset := EFX_REVERB_PRESET_FACTORY_COURTYARD; seFactory_Alcove : ThePreset := EFX_REVERB_PRESET_FACTORY_ALCOVE; seIcePalace_SmallRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_SMALLROOM; seIcePalace_ShortPassage : ThePreset := EFX_REVERB_PRESET_ICEPALACE_SHORTPASSAGE; seIcePalace_MediumRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_MEDIUMROOM; seIcePalace_LargeRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_LARGEROOM; seIcePalace_LongPassage : ThePreset := EFX_REVERB_PRESET_ICEPALACE_LONGPASSAGE; seIcePalace_Hall : ThePreset := EFX_REVERB_PRESET_ICEPALACE_HALL; seIcePalace_CupBoard : ThePreset := EFX_REVERB_PRESET_ICEPALACE_CUPBOARD; seIcePalace_CourtYard : ThePreset := EFX_REVERB_PRESET_ICEPALACE_COURTYARD; seIcePalace_Alcove : ThePreset := EFX_REVERB_PRESET_ICEPALACE_ALCOVE; seSpaceStation_SmallRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_SMALLROOM; seSpaceStation_ShortPassage : ThePreset := EFX_REVERB_PRESET_SPACESTATION_SHORTPASSAGE; seSpaceStation_MediumRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_MEDIUMROOM; seSpaceStation_LargeRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_LARGEROOM; seSpaceStation_LongPassage : ThePreset := EFX_REVERB_PRESET_SPACESTATION_LONGPASSAGE; seSpaceStation_Hall : ThePreset := EFX_REVERB_PRESET_SPACESTATION_HALL; seSpaceStation_CupBoard : ThePreset := EFX_REVERB_PRESET_SPACESTATION_CUPBOARD; // seSpaceStation_CourtYard : ThePreset := EFX_REVERB_PRESET_SPACESTATION_COURTYARD; seSpaceStation_Alcove : ThePreset := EFX_REVERB_PRESET_SPACESTATION_ALCOVE; seWooden_SmallRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_SMALLROOM; seWooden_ShortPassage : ThePreset := EFX_REVERB_PRESET_WOODEN_SHORTPASSAGE; seWooden_MediumRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_MEDIUMROOM; seWooden_LargeRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_LARGEROOM; seWooden_LongPassage : ThePreset := EFX_REVERB_PRESET_WOODEN_LONGPASSAGE; seWooden_Hall : ThePreset := EFX_REVERB_PRESET_WOODEN_HALL; seWooden_CupBoard : ThePreset := EFX_REVERB_PRESET_WOODEN_CUPBOARD; seWooden_CourtYard : ThePreset := EFX_REVERB_PRESET_WOODEN_COURTYARD; seWooden_Alcove : ThePreset := EFX_REVERB_PRESET_WOODEN_ALCOVE; seSport_EmptyStadium : ThePreset := EFX_REVERB_PRESET_SPORT_EMPTYSTADIUM; seSport_SquashCourt : ThePreset := EFX_REVERB_PRESET_SPORT_SQUASHCOURT; seSport_SmallSwimmingPool : ThePreset := EFX_REVERB_PRESET_SPORT_SMALLSWIMMINGPOOL; seSport_LargeSwimmingPool : ThePreset := EFX_REVERB_PRESET_SPORT_LARGESWIMMINGPOOL; seSport_Gymnasium : ThePreset := EFX_REVERB_PRESET_SPORT_GYMNASIUM; seSport_FullStadium : ThePreset := EFX_REVERB_PRESET_SPORT_FULLSTADIUM; seSport_StadiumTannoy : ThePreset := EFX_REVERB_PRESET_SPORT_STADIUMTANNOY; sePrefab_WorkShop : ThePreset := EFX_REVERB_PRESET_PREFAB_WORKSHOP; sePrefab_SchoolRoom : ThePreset := EFX_REVERB_PRESET_PREFAB_SCHOOLROOM; sePrefab_PractiseRoom : ThePreset := EFX_REVERB_PRESET_PREFAB_PRACTISEROOM; sePrefab_OutHouse : ThePreset := EFX_REVERB_PRESET_PREFAB_OUTHOUSE; sePrefab_Caravan : ThePreset := EFX_REVERB_PRESET_PREFAB_CARAVAN; seDome_Tomb : ThePreset := EFX_REVERB_PRESET_DOME_TOMB; seDome_SaintPauls : ThePreset := EFX_REVERB_PRESET_DOME_SAINTPAULS; sePipe_Small : ThePreset := EFX_REVERB_PRESET_PIPE_SMALL; sePipe_Longthin : ThePreset := EFX_REVERB_PRESET_PIPE_LONGTHIN; sePipe_Large : ThePreset := EFX_REVERB_PRESET_PIPE_LARGE; sePipe_Resonant : ThePreset := EFX_REVERB_PRESET_PIPE_RESONANT; seOutDoors_BackYard : ThePreset := EFX_REVERB_PRESET_OUTDOORS_BACKYARD; seOutDoors_RollingPlains : ThePreset := EFX_REVERB_PRESET_OUTDOORS_ROLLINGPLAINS; seOutDoors_DeepCanyon : ThePreset := EFX_REVERB_PRESET_OUTDOORS_DEEPCANYON; seOutDoors_Creek : ThePreset := EFX_REVERB_PRESET_OUTDOORS_CREEK; seOutDoors_Valley : ThePreset := EFX_REVERB_PRESET_OUTDOORS_VALLEY; seMood_Heaven : ThePreset := EFX_REVERB_PRESET_MOOD_HEAVEN; seMood_Hell : ThePreset := EFX_REVERB_PRESET_MOOD_HELL; seMood_Memory : ThePreset := EFX_REVERB_PRESET_MOOD_MEMORY; seDriving_Commentator : ThePreset := EFX_REVERB_PRESET_DRIVING_COMMENTATOR; seDriving_PitGarage : ThePreset := EFX_REVERB_PRESET_DRIVING_PITGARAGE; seDriving_Incar_Racer : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_RACER; seDriving_Incar_Sports : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_SPORTS; seDriving_Incar_Luxury : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_LUXURY; seDriving_FullGrandStand : ThePreset := EFX_REVERB_PRESET_DRIVING_FULLGRANDSTAND; seDriving_EmptyGrandStand : ThePreset := EFX_REVERB_PRESET_DRIVING_EMPTYGRANDSTAND; seDriving_Tunnel : ThePreset := EFX_REVERB_PRESET_DRIVING_TUNNEL; seCity_Streets : ThePreset := EFX_REVERB_PRESET_CITY_STREETS; seCity_SubWay : ThePreset := EFX_REVERB_PRESET_CITY_SUBWAY; seCity_Museum : ThePreset := EFX_REVERB_PRESET_CITY_MUSEUM; seCity_Library : ThePreset := EFX_REVERB_PRESET_CITY_LIBRARY; seCity_UnderPass : ThePreset := EFX_REVERB_PRESET_CITY_UNDERPASS; seCity_Abandoned : ThePreset := EFX_REVERB_PRESET_CITY_ABANDONED; seDustyRoom : ThePreset := EFX_REVERB_PRESET_DUSTYROOM; seChapel : ThePreset := EFX_REVERB_PRESET_CHAPEL; seSmallWaterRoom : ThePreset := EFX_REVERB_PRESET_SMALLWATERROOM; end; Setparams(ThePreset); end; procedure TBZReverbSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZReverbSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZReverbSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZEAXReverbSoundEffect ]======================================} constructor TBZEAXReverbSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZEAXReverbSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZEAXReverbSoundEffect.FriendlyName: String; begin Result := 'EFX_EAX_Reverb_Sound_Effect'; End; procedure TBZEAXReverbSoundEffect.SetPreset(val : TBZSoundReverbEnvironment); var ThePreset : EFXEAXREVERBPROPERTIES; procedure SetParams(aPreset : EFXEAXREVERBPROPERTIES); begin FDENSITY := aPreset.flDensity; FDIFFUSION := aPreset.flDiffusion; FGAIN := aPreset.flGain; FGAINHF := aPreset.flGainHF; FDECAY_TIME := aPreset.flDecayTime; FDECAY_HFRATIO := aPreset.flDecayHFRatio; FREFLECTIONS_GAIN := aPreset.flReflectionsGain; FREFLECTIONS_DELAY := aPreset.flReflectionsDelay; FLATE_REVERB_GAIN := aPreset.flLateReverbGain; FLATE_REVERB_DELAY := aPreset.flLateReverbDelay; FAIR_ABSORPTION_GAINHF := aPreset.flAirAbsorptionGainHF; FROOM_ROLLOFF_FACTOR := aPreset.flRoomRolloffFactor; FDECAY_HFLIMIT := (aPreset.iDecayHFLimit>0); End; begin Case val of seGeneric : ThePreset := EFX_REVERB_PRESET_GENERIC; sePaddedCell : ThePreset := EFX_REVERB_PRESET_PADDEDCELL; seRoom : ThePreset := EFX_REVERB_PRESET_ROOM; seBathroom : ThePreset := EFX_REVERB_PRESET_BATHROOM; seLivingRoom : ThePreset := EFX_REVERB_PRESET_LIVINGROOM; seStoneroom : ThePreset := EFX_REVERB_PRESET_STONEROOM; seAuditorium : ThePreset := EFX_REVERB_PRESET_AUDITORIUM; seConcertHall : ThePreset := EFX_REVERB_PRESET_CONCERTHALL; seCave : ThePreset := EFX_REVERB_PRESET_CAVE; seArena : ThePreset := EFX_REVERB_PRESET_ARENA; seHangar : ThePreset := EFX_REVERB_PRESET_HANGAR; seCarpetedHallway : ThePreset := EFX_REVERB_PRESET_CARPETEDHALLWAY; seHallway : ThePreset := EFX_REVERB_PRESET_HALLWAY; seStoneCorridor : ThePreset := EFX_REVERB_PRESET_STONECORRIDOR; seAlley : ThePreset := EFX_REVERB_PRESET_ALLEY; seForest : ThePreset := EFX_REVERB_PRESET_FOREST; seCity : ThePreset := EFX_REVERB_PRESET_CITY; seMountains : ThePreset := EFX_REVERB_PRESET_MOUNTAINS; seQuarry : ThePreset := EFX_REVERB_PRESET_QUARRY; sePlain : ThePreset := EFX_REVERB_PRESET_PLAIN; seParkingLot : ThePreset := EFX_REVERB_PRESET_PARKINGLOT; seSewerPipe : ThePreset := EFX_REVERB_PRESET_SEWERPIPE; seUnderWater : ThePreset := EFX_REVERB_PRESET_UNDERWATER; seDrugged : ThePreset := EFX_REVERB_PRESET_DRUGGED; seDizzy : ThePreset := EFX_REVERB_PRESET_DIZZY; sePsychotic : ThePreset := EFX_REVERB_PRESET_PSYCHOTIC; seCastle_SmallRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_SMALLROOM; seCastle_ShortPassage : ThePreset := EFX_REVERB_PRESET_CASTLE_SHORTPASSAGE; seCastle_MediumRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_MEDIUMROOM; seCastle_LargeRoom : ThePreset := EFX_REVERB_PRESET_CASTLE_LARGEROOM; seCastle_LongPassage : ThePreset := EFX_REVERB_PRESET_CASTLE_LONGPASSAGE; seCastle_Hall : ThePreset := EFX_REVERB_PRESET_CASTLE_HALL; seCastle_CupBoarb : ThePreset := EFX_REVERB_PRESET_CASTLE_CUPBOARD; seCastle_CourtYard : ThePreset := EFX_REVERB_PRESET_CASTLE_COURTYARD; seCastle_Alcove : ThePreset := EFX_REVERB_PRESET_CASTLE_ALCOVE; seFactory_SmallRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_SMALLROOM; seFactory_ShortPassage : ThePreset := EFX_REVERB_PRESET_FACTORY_SHORTPASSAGE; seFactory_MediumRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_MEDIUMROOM; seFactory_LargeRoom : ThePreset := EFX_REVERB_PRESET_FACTORY_LARGEROOM; seFactory_LongPassage : ThePreset := EFX_REVERB_PRESET_FACTORY_LONGPASSAGE; seFactory_Hall : ThePreset := EFX_REVERB_PRESET_FACTORY_HALL; seFactory_CupBoard : ThePreset := EFX_REVERB_PRESET_FACTORY_CUPBOARD; seFactory_CourtYard : ThePreset := EFX_REVERB_PRESET_FACTORY_COURTYARD; seFactory_Alcove : ThePreset := EFX_REVERB_PRESET_FACTORY_ALCOVE; seIcePalace_SmallRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_SMALLROOM; seIcePalace_ShortPassage : ThePreset := EFX_REVERB_PRESET_ICEPALACE_SHORTPASSAGE; seIcePalace_MediumRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_MEDIUMROOM; seIcePalace_LargeRoom : ThePreset := EFX_REVERB_PRESET_ICEPALACE_LARGEROOM; seIcePalace_LongPassage : ThePreset := EFX_REVERB_PRESET_ICEPALACE_LONGPASSAGE; seIcePalace_Hall : ThePreset := EFX_REVERB_PRESET_ICEPALACE_HALL; seIcePalace_CupBoard : ThePreset := EFX_REVERB_PRESET_ICEPALACE_CUPBOARD; seIcePalace_CourtYard : ThePreset := EFX_REVERB_PRESET_ICEPALACE_COURTYARD; seIcePalace_Alcove : ThePreset := EFX_REVERB_PRESET_ICEPALACE_ALCOVE; seSpaceStation_SmallRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_SMALLROOM; seSpaceStation_ShortPassage : ThePreset := EFX_REVERB_PRESET_SPACESTATION_SHORTPASSAGE; seSpaceStation_MediumRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_MEDIUMROOM; seSpaceStation_LargeRoom : ThePreset := EFX_REVERB_PRESET_SPACESTATION_LARGEROOM; seSpaceStation_LongPassage : ThePreset := EFX_REVERB_PRESET_SPACESTATION_LONGPASSAGE; seSpaceStation_Hall : ThePreset := EFX_REVERB_PRESET_SPACESTATION_HALL; seSpaceStation_CupBoard : ThePreset := EFX_REVERB_PRESET_SPACESTATION_CUPBOARD; //seSpaceStation_CourtYard : ThePreset := EFX_REVERB_PRESET_SPACESTATION_COURTYARD; seSpaceStation_Alcove : ThePreset := EFX_REVERB_PRESET_SPACESTATION_ALCOVE; seWooden_SmallRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_SMALLROOM; seWooden_ShortPassage : ThePreset := EFX_REVERB_PRESET_WOODEN_SHORTPASSAGE; seWooden_MediumRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_MEDIUMROOM; seWooden_LargeRoom : ThePreset := EFX_REVERB_PRESET_WOODEN_LARGEROOM; seWooden_LongPassage : ThePreset := EFX_REVERB_PRESET_WOODEN_LONGPASSAGE; seWooden_Hall : ThePreset := EFX_REVERB_PRESET_WOODEN_HALL; seWooden_CupBoard : ThePreset := EFX_REVERB_PRESET_WOODEN_CUPBOARD; seWooden_CourtYard : ThePreset := EFX_REVERB_PRESET_WOODEN_COURTYARD; seWooden_Alcove : ThePreset := EFX_REVERB_PRESET_WOODEN_ALCOVE; seSport_EmptyStadium : ThePreset := EFX_REVERB_PRESET_SPORT_EMPTYSTADIUM; seSport_SquashCourt : ThePreset := EFX_REVERB_PRESET_SPORT_SQUASHCOURT; seSport_SmallSwimmingPool : ThePreset := EFX_REVERB_PRESET_SPORT_SMALLSWIMMINGPOOL; seSport_LargeSwimmingPool : ThePreset := EFX_REVERB_PRESET_SPORT_LARGESWIMMINGPOOL; seSport_Gymnasium : ThePreset := EFX_REVERB_PRESET_SPORT_GYMNASIUM; seSport_FullStadium : ThePreset := EFX_REVERB_PRESET_SPORT_FULLSTADIUM; seSport_StadiumTannoy : ThePreset := EFX_REVERB_PRESET_SPORT_STADIUMTANNOY; sePrefab_WorkShop : ThePreset := EFX_REVERB_PRESET_PREFAB_WORKSHOP; sePrefab_SchoolRoom : ThePreset := EFX_REVERB_PRESET_PREFAB_SCHOOLROOM; sePrefab_PractiseRoom : ThePreset := EFX_REVERB_PRESET_PREFAB_PRACTISEROOM; sePrefab_OutHouse : ThePreset := EFX_REVERB_PRESET_PREFAB_OUTHOUSE; sePrefab_Caravan : ThePreset := EFX_REVERB_PRESET_PREFAB_CARAVAN; seDome_Tomb : ThePreset := EFX_REVERB_PRESET_DOME_TOMB; seDome_SaintPauls : ThePreset := EFX_REVERB_PRESET_DOME_SAINTPAULS; sePipe_Small : ThePreset := EFX_REVERB_PRESET_PIPE_SMALL; sePipe_Longthin : ThePreset := EFX_REVERB_PRESET_PIPE_LONGTHIN; sePipe_Large : ThePreset := EFX_REVERB_PRESET_PIPE_LARGE; sePipe_Resonant : ThePreset := EFX_REVERB_PRESET_PIPE_RESONANT; seOutDoors_BackYard : ThePreset := EFX_REVERB_PRESET_OUTDOORS_BACKYARD; seOutDoors_RollingPlains : ThePreset := EFX_REVERB_PRESET_OUTDOORS_ROLLINGPLAINS; seOutDoors_DeepCanyon : ThePreset := EFX_REVERB_PRESET_OUTDOORS_DEEPCANYON; seOutDoors_Creek : ThePreset := EFX_REVERB_PRESET_OUTDOORS_CREEK; seOutDoors_Valley : ThePreset := EFX_REVERB_PRESET_OUTDOORS_VALLEY; seMood_Heaven : ThePreset := EFX_REVERB_PRESET_MOOD_HEAVEN; seMood_Hell : ThePreset := EFX_REVERB_PRESET_MOOD_HELL; seMood_Memory : ThePreset := EFX_REVERB_PRESET_MOOD_MEMORY; seDriving_Commentator : ThePreset := EFX_REVERB_PRESET_DRIVING_COMMENTATOR; seDriving_PitGarage : ThePreset := EFX_REVERB_PRESET_DRIVING_PITGARAGE; seDriving_Incar_Racer : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_RACER; seDriving_Incar_Sports : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_SPORTS; seDriving_Incar_Luxury : ThePreset := EFX_REVERB_PRESET_DRIVING_INCAR_LUXURY; seDriving_FullGrandStand : ThePreset := EFX_REVERB_PRESET_DRIVING_FULLGRANDSTAND; seDriving_EmptyGrandStand : ThePreset := EFX_REVERB_PRESET_DRIVING_EMPTYGRANDSTAND; seDriving_Tunnel : ThePreset := EFX_REVERB_PRESET_DRIVING_TUNNEL; seCity_Streets : ThePreset := EFX_REVERB_PRESET_CITY_STREETS; seCity_SubWay : ThePreset := EFX_REVERB_PRESET_CITY_SUBWAY; seCity_Museum : ThePreset := EFX_REVERB_PRESET_CITY_MUSEUM; seCity_Library : ThePreset := EFX_REVERB_PRESET_CITY_LIBRARY; seCity_UnderPass : ThePreset := EFX_REVERB_PRESET_CITY_UNDERPASS; seCity_Abandoned : ThePreset := EFX_REVERB_PRESET_CITY_ABANDONED; seDustyRoom : ThePreset := EFX_REVERB_PRESET_DUSTYROOM; seChapel : ThePreset := EFX_REVERB_PRESET_CHAPEL; seSmallWaterRoom : ThePreset := EFX_REVERB_PRESET_SMALLWATERROOM; end; Setparams(ThePreset); end; procedure TBZEAXReverbSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZEAXReverbSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZEAXReverbSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZChorusSoundEffect ]=========================================} constructor TBZChorusSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZChorusSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZChorusSoundEffect.FriendlyName: String; begin Result := 'EFX_Chorus_Sound_Effect'; End; procedure TBZChorusSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZChorusSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZChorusSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZEchoSoundEffect ]===========================================} constructor TBZEchoSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZEchoSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZEchoSoundEffect.FriendlyName: String; begin Result := 'EFX_Echo_Sound_Effect'; End; procedure TBZEchoSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZEchoSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZEchoSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZDistorsionSoundEffect ]=====================================} constructor TBZDistortionSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZDistortionSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZDistortionSoundEffect.FriendlyName: String; begin Result := 'EFX_Distortion_Sound_Effect'; End; procedure TBZDistortionSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZDistortionSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZDistortionSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZFlangerSoundEffect ]========================================} constructor TBZFlangerSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZFlangerSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZFlangerSoundEffect.FriendlyName: String; begin Result := 'EFX_Flanger_Sound_Effect'; End; procedure TBZFlangerSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZFlangerSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZFlangerSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZCompressorSoundEffect ]=====================================} constructor TBZCompressorSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZCompressorSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZCompressorSoundEffect.FriendlyName: String; begin Result := 'EFX_Compressor_Sound_Effect'; End; procedure TBZCompressorSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZCompressorSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZCompressorSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZEqualizerSoundEffect ]======================================} constructor TBZEqualizerSoundEffect.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZEqualizerSoundEffect.Destroy; begin Inherited Destroy; end; class function TBZEqualizerSoundEffect.FriendlyName: String; begin Result := 'EFX_Equalizer_Sound_Effect'; End; procedure TBZEqualizerSoundEffect.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZEqualizerSoundEffect.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZEqualizerSoundEffect.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZCustomSoundFilterItem ]=====================================} class function TBZCustomSoundFilterItem.FriendlyName: String; begin Result := 'Custom_Sound_Filter'; End; {%endregion%} {%region=====[ TBZLowPassSoundFilter ]========================================} constructor TBZLowPassSoundFilter.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); FGAIN := 1.0; FGAINHF := 1.0; end; destructor TBZLowPassSoundFilter.Destroy; begin Inherited Destroy; end; class function TBZLowPassSoundFilter.FriendlyName: String; begin Result := 'LowPass_Sound_Filter'; End; procedure TBZLowPassSoundFilter.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZLowPassSoundFilter.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZLowPassSoundFilter.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZHighPassSoundFilter ]=======================================} constructor TBZHighPassSoundFilter.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZHighPassSoundFilter.Destroy; begin Inherited Destroy; end; class function TBZHighPassSoundFilter.FriendlyName: String; begin Result := 'HighPass_Sound_Filter'; End; procedure TBZHighPassSoundFilter.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZHighPassSoundFilter.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZHighPassSoundFilter.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZBandPassSoundFilter ]=======================================} constructor TBZBandPassSoundFilter.Create(AOwner: TBZXCollection); begin inherited Create(AOwner); end; destructor TBZBandPassSoundFilter.Destroy; begin Inherited Destroy; end; class function TBZBandPassSoundFilter.FriendlyName: String; begin Result := 'BandPass_Sound_Filter'; End; procedure TBZBandPassSoundFilter.WriteToFiler(Awriter: TWriter); begin inherited; With AWriter do begin WriteInteger(0); end; end; procedure TBZBandPassSoundFilter.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion end; end; procedure TBZBandPassSoundFilter.Assign(Source: TPersistent); begin if Source is TBZReverbSoundEffect then begin end else inherited Assign(Source); end; {%endregion%} {%region=====[ TBZSoundFXLib ]================================================} (*constructor TBZSoundFXLib.Create(aOwner: TPersistent); begin // Assert(aOwner is TGLBaseSceneObject); inherited Create(aOwner); end; *) function TBZSoundFXLib.GetNamePath: string; var s: string; begin Result := ClassName; if GetOwner = nil then Exit; s := GetOwner.GetNamePath; if s = '' then Exit; Result := s + '.SoundFXLib'; end; class function TBZSoundFXLib.ItemsClass: TBZXCollectionItemClass; begin Result := TBZCustomSoundFXItem; end; function TBZSoundFXLib.GetItem(index: Integer): TBZCustomSoundFXItem; begin // ShowMessage('SoundFXLib GetItem At : '+IntToStr(Index)); Result := nil; if (Index>=0) and (Index<Count) then Result := TBZCustomSoundFXItem(Items[index]); end; function TBZSoundFXLib.CanAdd(aClass: TBZXCollectionItemClass): Boolean; begin Result := (aClass.InheritsFrom(TBZCustomSoundFXItem)) and (inherited CanAdd(aClass)); ShowMessage('CanAdd :'+BoolToStr(Result,True)); end; function TBZSoundFXLib.GetItemByName(const AName: TBZSoundFXName): TBZCustomSoundFXItem; var i:Integer; begin Result := nil; //ShowMessage('Count : '+InttoStr(Count)); for i := 0 to Count - 1 do begin if Items[i]=nil then ShowMessage('ERROR'); // ShowMessage('Compare : '+InttoStr(I)+' - '+AName+' --> '+Self.Items[i].Name); if (Items[i].Name = AName) then begin Result := TBZCustomSoundFXItem(Items[i]); exit; end; end; End; function TBZSoundFXLib.AddFilterLowPass(AName: TBZSoundFXName) : TBZLowPassSoundFilter; begin Result := TBZLowPassSoundFilter.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddFilterHighPass(AName: TBZSoundFXName) : TBZHighPassSoundFilter; begin Result := TBZHighPassSoundFilter.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddFilterBandPass(AName: TBZSoundFXName) : TBZBandPassSoundFilter; begin Result := TBZBandPassSoundFilter.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.GetFilterLowPassByName(const AName: TBZSoundFXName): TBZLowPassSoundFilter; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZLowPassSoundFilter) and (Items[I].Name = AName) then begin Result := TBZLowPassSoundFilter(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetFilterHighPassByName(const AName: TBZSoundFXName): TBZHighPassSoundFilter; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZHighPassSoundFilter) and (Items[I].Name = AName) then begin Result := TBZHighPassSoundFilter(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetFilterBandPassByName(const AName: TBZSoundFXName): TBZBandPassSoundFilter; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZBandPassSoundFilter) and (Items[I].Name = AName) then begin Result := TBZBandPassSoundFilter(Items[I]); exit; end; end; end; function TBZSoundFXLib.AddEffectReverb(AName: TBZSoundFXName) : TBZReverbSoundEffect; begin Result := TBZReverbSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectEAXReverb(AName: TBZSoundFXName) : TBZEAXReverbSoundEffect; begin Result := TBZEAXReverbSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectChorus(AName: TBZSoundFXName) : TBZChorusSoundEffect; begin Result := TBZChorusSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectEcho(AName: TBZSoundFXName) : TBZEchoSoundEffect; begin Result := TBZEchoSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectDistortion(AName: TBZSoundFXName) : TBZDistortionSoundEffect; begin Result := TBZDistortionSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectFlanger(AName: TBZSoundFXName) : TBZFlangerSoundEffect; begin Result := TBZFlangerSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectCompressor(AName: TBZSoundFXName) : TBZCompressorSoundEffect; begin Result := TBZCompressorSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.AddEffectEqualizer(AName: TBZSoundFXName) : TBZEqualizerSoundEffect; begin Result := TBZEqualizerSoundEffect.Create(Self); Result.Name := AName; Add(Result); End; function TBZSoundFXLib.GetEffectReverbByName(const AName: TBZSoundFXName): TBZReverbSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZReverbSoundEffect) and (Items[I].Name = AName) then begin Result := TBZReverbSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectEAXReverbByName(const AName: TBZSoundFXName): TBZEAXReverbSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZEAXReverbSoundEffect) and (Items[I].Name = AName) then begin Result := TBZEAXReverbSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectChorusByName(const AName: TBZSoundFXName): TBZChorusSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZChorusSoundEffect) and (Items[I].Name = AName) then begin Result := TBZChorusSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectEchoByName(const AName: TBZSoundFXName): TBZEchoSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZEchoSoundEffect) and (Items[I].Name = AName) then begin Result := TBZEchoSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectDistortionByName(const AName: TBZSoundFXName): TBZDistortionSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZDistortionSoundEffect) and (Items[I].Name = AName) then begin Result := TBZDistortionSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectFlangerByName(const AName: TBZSoundFXName): TBZFlangerSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZFlangerSoundEffect) and (Items[I].Name = AName) then begin Result := TBZFlangerSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectCompressorByName(const AName: TBZSoundFXName): TBZCompressorSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZCompressorSoundEffect) and (Items[I].Name = AName) then begin Result := TBZCompressorSoundEffect(Items[I]); exit; end; end; end; function TBZSoundFXLib.GetEffectEqualizerByName(const AName: TBZSoundFXName): TBZEqualizerSoundEffect; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do begin if (Items[I] is TBZEqualizerSoundEffect) and (Items[I].Name = AName) then begin Result := TBZEqualizerSoundEffect(Items[I]); exit; end; end; end; (*procedure TBZSoundFXLib.DoProgress(const progressTimes: TProgressTimes); var i: Integer; begin for i := 0 to Count - 1 do TBZCustomSoundFXItem(Items[i]).DoProgress(progressTimes); end; *) {%endregion%} {%region=====[ TBZSoundFXLibrary ]============================================} constructor TBZSoundFXLibrary.Create(AOwner: TComponent); begin inherited Create(AOwner); FSoundFXLib := TBZSoundFXLib.Create(Self); vSoundFXLibraries.Add(Self); end; destructor TBZSoundFXLibrary.Destroy; begin vSoundFXLibraries.Remove(Self); FSoundFXLib.Free; inherited Destroy; end; procedure TBZSoundFXLibrary.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; end; procedure TBZSoundFXLibrary.SetSoundFXLib(const val: TBZSoundFXLib); begin FSoundFXLib.Assign(val); end; {%endregion%} {%region=====[ TBZSoundFXAuxSlot ]============================================} constructor TBZSoundFXAuxSlot.Create(ACollection: TCollection); begin inherited Create(ACollection); FSoundFXName :=''; FSoundFXCache := nil; FSoundFXLibrary := nil; end; destructor TBZSoundFXAuxSlot.Destroy; begin inherited Destroy; end; procedure TBZSoundFXAuxSlot.Assign(Source: TPersistent); begin if Source is TBZSoundFXAuxSlot then begin FSoundFXLibraryName := TBZSoundFXAuxSlot(Source).FSoundFXLibraryName; FSoundFXLibrary := TBZSoundFXAuxSlot(Source).FSoundFXLibrary; FSoundFXName := TBZSoundFXAuxSlot(Source).FSoundFXName; FActivated := TBZSoundFXAuxSlot(Source).FActivated; end else inherited Assign(Source); end; procedure TBZSoundFXAuxSlot.WriteToFiler(Awriter: TWriter); begin inherited; with Awriter do begin WriteInteger(0); // Archive Version 0 if Assigned(FSoundFXLibrary) then WriteString(FSoundFXLibrary.Name) else WriteString(FSoundFXLibraryName); WriteString(FSoundFXName); WriteBoolean(FActivated); // WriteInteger(FFrequency); end; end; procedure TBZSoundFXAuxSlot.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion FSoundFXLibraryName := ReadString; FSoundFXLibrary := nil; FSoundFXName := ReadString; FActivated := ReadBoolean; end; end; function TBZSoundFXAuxSlot.GetSoundFXLibrary: TBZSoundFXLibrary; begin if (FSoundFXLibrary = nil) and (FSoundFXLibraryName <> '') then FSoundFXLibrary := GetSoundFXLibraryByName(FSoundFXLibraryName); Result := FSoundFXLibrary; end; procedure TBZSoundFXAuxSlot.SetSoundFXLibrary(Const AValue : TBZSoundFXLibrary); begin if AValue<>nil then begin if AValue <> FSoundFXLibrary then begin FSoundFXLibrary := AValue; if Assigned(FSoundFXLibrary) then FSoundFXLibraryName := FSoundFXLibrary.Name else FSoundFXLibraryName := ''; //Include(FChanges, sscSample); end; End; end; procedure TBZSoundFXAuxSlot.setSoundFXName(val : String); begin if FSoundFXName = val then exit; FSoundFXName := val; if FSoundFXLibrary=nil then begin showmessage('Error'); exit; End; FSoundFXCache := FSoundFXLibrary.FX.GetItemByName(val); // Include(FChanges, sscSample); end; procedure TBZSoundFXAuxSlot.SetActivated(val : Boolean); begin if FActivated = val then exit; FActivated := val; // Include(FChanges, sscSample); end; {%endregion%} {%region=====[ TBZSoundFXAuxSlots ]===========================================} constructor TBZSoundFXAuxSlots.Create(AOwner: TComponent); begin FOwner := AOwner; inherited Create(TBZSoundFXAuxSlot); end; function TBZSoundFXAuxSlots.GetOwner: TPersistent; begin Result := FOwner; end; procedure TBZSoundFXAuxSlots.SetItems(index: Integer; const val: TBZSoundFXAuxSlot); begin inherited Items[index] := val; end; function TBZSoundFXAuxSlots.GetItems(index: Integer): TBZSoundFXAuxSlot; begin Result := TBZSoundFXAuxSlot(inherited Items[index]); end; function TBZSoundFXAuxSlots.Add: TBZSoundFXAuxSlot; begin Result := (inherited Add) as TBZSoundFXAuxSlot; end; function TBZSoundFXAuxSlots.FindItemID(ID: Integer): TBZSoundFXAuxSlot; begin Result := (inherited FindItemID(ID)) as TBZSoundFXAuxSlot; end; {%endregion%} {%region=====[ TBZBaseSoundSource ]===========================================} constructor TBZBaseSoundSource.Create(ACollection: TCollection); begin inherited Create(ACollection); FAuxSlots := TBZSoundFXAuxSlots.Create(nil); FChanges := [sscTransformation, sscSample, sscStatus]; FVolume := 1.0; FMinDistance := 1.0; FMaxDistance := 100.0; FInsideConeAngle := 360; FOutsideConeAngle := 360; FConeOutsideVolume := 0.0; FPitch := 1.0; FNbLoops := 1; FFrequency := -1; FPause := False; FLoaded := False; FTimePosition := 0.0; FPlaying := False; // On met la lecture en pause; FDirectFilterName := ''; FFXChanges := []; FAutoFreeOnStop := False; end; destructor TBZBaseSoundSource.Destroy; begin FreeAndNil(FAuxSlots); inherited Destroy; end; function TBZBaseSoundSource.GetSoundLibrary: TBZSoundLibrary; begin if (FSoundLibrary = nil) and (FSoundLibraryName <> '') then FSoundLibrary := GetSoundLibraryByName(FSoundLibraryName); Result := FSoundLibrary; end; procedure TBZBaseSoundSource.SetSoundLibrary(const val: TBZSoundLibrary); begin if val <> FSoundLibrary then begin FSoundLibrary := val; if Assigned(FSoundLibrary) then FSoundLibraryName := FSoundLibrary.Name else FSoundLibraryName := ''; // Include(FChanges, sscSample); end; end; procedure TBZBaseSoundSource.SetSoundName(const val: string); begin if val <> FSoundName then begin FSoundName := val; Include(FChanges,sscNewSample); Include(FChanges,sscSample); end; end; function TBZBaseSoundSource.GetSoundFXLibrary: TBZSoundFXLibrary; begin if (FSoundFXLibrary = nil) and (FSoundFXLibraryName <> '') then FSoundFXLibrary := GetSoundFXLibraryByName(FSoundFXLibraryName); Result := FSoundFXLibrary; end; procedure TBZBaseSoundSource.SetSoundFXLibrary(const val: TBZSoundFXLibrary); begin if val <> FSoundFXLibrary then begin FSoundFXLibrary := val; if Assigned(FSoundFXLibrary) then FSoundFXLibraryName := FSoundFXLibrary.Name else FSoundFXLibraryName := ''; Include(FChanges, sscSample); end; end; procedure TBZBaseSoundSource.setDirectFilterName(val : String); begin if FDirectFilterName = val then exit; FDirectFilterName := val; FDirectFilterCache := TBZCustomSoundFilterItem(FSoundFXLibrary.FX.GetItemByName(val)); Include(FChanges, sscSample); end; procedure TBZBaseSoundSource.SetDirectFilterActivated(val : Boolean); begin if FDirectFilterActivated = val then exit; FDirectFilterActivated := val; Include(FChanges, sscFXStatus); Include(FFXChanges, sfxcDirectFilter); End; function TBZBaseSoundSource.GetDirectFilterActivated: Boolean; begin Result := FDirectFilterActivated; End; function TBZBaseSoundSource.GetDirectFilterFXCache:TBZCustomSoundFilterItem; begin result := FDirectFilterCache; End; function TBZBaseSoundSource.GetDisplayName: string; begin Result := Format('%s', [FSoundName]); end; procedure TBZBaseSoundSource.Assign(Source: TPersistent); begin if Source is TBZBaseSoundSource then begin FPriority := TBZBaseSoundSource(Source).FPriority; // FOrigin := TBZBaseSoundSource(Source).FOrigin; FVolume := TBZBaseSoundSource(Source).FVolume; FMinDistance := TBZBaseSoundSource(Source).FMinDistance; FMaxDistance := TBZBaseSoundSource(Source).FMaxDistance; FInsideConeAngle := TBZBaseSoundSource(Source).FInsideConeAngle; FOutsideConeAngle := TBZBaseSoundSource(Source).FOutsideConeAngle; FConeOutsideVolume := TBZBaseSoundSource(Source).FConeOutsideVolume; FSoundLibraryName := TBZBaseSoundSource(Source).FSoundLibraryName; FSoundLibrary := TBZBaseSoundSource(Source).FSoundLibrary; FSoundName := TBZBaseSoundSource(Source).FSoundName; FMute := TBZBaseSoundSource(Source).FMute; FPause := TBZBaseSoundSource(Source).FPause; FPlaying := TBZBaseSoundSource(Source).FPlaying; FChanges := [sscTransformation, sscSample, sscStatus]; FNbLoops := TBZBaseSoundSource(Source).FNbLoops; FFrequency := TBZBaseSoundSource(Source).FFrequency; FPitch := TBZBaseSoundSource(Source).FPitch; end else inherited Assign(Source); end; procedure TBZBaseSoundSource.WriteToFiler(Awriter: TWriter); begin inherited; with Awriter do begin WriteInteger(0); // Archive Version 0 WriteInteger(FPriority); WriteFloat(FVolume); WriteFloat(FMinDistance); WriteFloat(FMaxDistance); WriteFloat(FInsideConeAngle); WriteFloat(FOutsideConeAngle); WriteFloat(FConeOutsideVolume); if Assigned(FSoundLibrary) then WriteString(FSoundLibrary.Name) else WriteString(FSoundLibraryName); WriteString(FSoundName); WriteBoolean(FMute); WriteBoolean(FPause); WriteBoolean(FPlaying); WriteInteger(FNbLoops); WriteFloat(FPitch); // WriteInteger(FFrequency); end; end; procedure TBZBaseSoundSource.ReadFromFiler(Areader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion FPriority := ReadInteger; FVolume := ReadFloat; FMinDistance := ReadFloat; FMaxDistance := ReadFloat; FInsideConeAngle := ReadFloat; FOutsideConeAngle := ReadFloat; FConeOutsideVolume := ReadFloat; FSoundLibraryName := ReadString; FSoundLibrary := nil; FSoundName := ReadString; FMute := ReadBoolean; FPause := ReadBoolean; FPlaying := ReadBoolean; FChanges := [sscTransformation, sscSample, sscStatus]; FNbLoops := ReadInteger; FPitch := ReadFloat; FUseEnvironnment := False; FUseEqualizer := False; // FFrequency:=ReadInteger; end; end; function TBZBaseSoundSource.Sample: TBZSoundSampleItem; begin if SoundLibrary <> nil then Result := FSoundLibrary.Samples.GetByName(FSoundName) else Result := nil; end; procedure TBZBaseSoundSource.SetPriority(const val: Integer); begin if val <> FPriority then begin FPriority := val; Include(FChanges, sscStatus); end; end; (*procedure TBZBaseSoundSource.SetOrigin(const val: TBZBaseSceneObject); begin if val <> FOrigin then begin FOrigin := val; Include(FChanges, sscTransformation); end; end;*) procedure TBZBaseSoundSource.SetVolume(const val: Single); begin if val <> FVolume then begin FVolume := Clamp(val, 0, 1); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetMinDistance(const val: Single); begin if val <> FMinDistance then begin FMinDistance := ClampMin(val, 0); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetMaxDistance(const val: Single); begin if val <> FMaxDistance then begin FMaxDistance := ClampMin(val, 0); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetInsideConeAngle(const val: Single); begin if val <> FInsideConeAngle then begin FInsideConeAngle := Clamp(val, 0, 360); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetOutsideConeAngle(const val: Single); begin if val <> FOutsideConeAngle then begin FOutsideConeAngle := Clamp(val, 0, 360); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetConeOutsideVolume(const val: Single); begin if val <> FConeOutsideVolume then begin FConeOutsideVolume := Clamp(val, 0, 1); Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetPause(const val: Boolean); begin if val <> FPause then begin FPause := val; if Collection <> nil then TBZSoundManager(TBZSoundSources(Collection).owner).PauseSource(Self, FPause); end; end; procedure TBZBaseSoundSource.SetPlaying(const val: Boolean); begin if val <> FPlaying then begin FPlaying := val; if Collection <> nil then TBZSoundManager(TBZSoundSources(Collection).owner).PlaySource(Self, FPlaying); end; end; procedure TBZBaseSoundSource.SetNbLoops(const val: Integer); begin if val <> FNbLoops then begin FNbLoops := val; Include(FChanges, sscSample); end; end; procedure TBZBaseSoundSource.SetPitch(const val: Single); begin if val <> FPitch then begin FPitch:= val; Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetFrequency(const val: integer); begin if val <> FFrequency then begin FFrequency := val; Include(FChanges, sscStatus); end; end; procedure TBZBaseSoundSource.SetMute(const val: Boolean); begin if val <> FMute then begin FMute := val; if Collection <> nil then TBZSoundManager(TBZSoundSources(Collection).owner).MuteSource(Self, FMute); end; end; procedure TBZBaseSoundSource.UpdateTimePosition(Const val : Single); begin FTimePosition := val; end; Function TBZBaseSoundSource.GetTimePositionInByte:Int64; var tp : Single; begin if Collection <> nil then begin tp := TBZSoundManager(TBZSoundSources(Collection).owner).GetTimePosition(Self); result:=Round(tp*Self.Sample.Data.Frequency); end else result := 0; end; {%endregion%} {%region=====[ TBZSoundSource ]===============================================} destructor TBZSoundSource.Destroy; begin //if Assigned(FBehaviourToNotify) then FBehaviourToNotify.NotifySourceDestruction(Self); if Collection <> nil then ((Collection as TBZSoundSources).Owner as TBZSoundManager).KillSource(Self); inherited; end; {%endregion%} {%region=====[ TBZSoundSources ]==============================================} constructor TBZSoundSources.Create(AOwner: TComponent); begin FOwner := AOwner; inherited Create(TBZSoundSource); end; function TBZSoundSources.GetOwner: TPersistent; begin Result := FOwner; end; procedure TBZSoundSources.SetItems(index: Integer; const val: TBZSoundSource); begin inherited Items[index] := val; end; function TBZSoundSources.GetItems(index: Integer): TBZSoundSource; begin Result := TBZSoundSource(inherited Items[index]); end; function TBZSoundSources.Add: TBZSoundSource; begin Result := TBZSoundSource.Create(Self);//(inherited Add);// as TBZSoundSource; end; function TBZSoundSources.FindItemID(ID: Integer): TBZSoundSource; begin Result := (inherited FindItemID(ID)) as TBZSoundSource; end; {%endregion%} {%region=====[ TBZSoundManager ]==============================================} constructor TBZSoundManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FSources := TBZSoundSources.Create(Self); FMasterVolume := 1.0; FOutputFrequency := 44100; FMaxChannels := 8; FUpdateFrequency := 10; FLastUpdateTime := -1e30; FDistanceFactor := 1.0; FRollOffFactor := 1.0; FDopplerFactor := 1.0; FSoundEnvironment := seGeneric; end; destructor TBZSoundManager.Destroy; begin Active := False; // Listener := nil; FSources.Free; inherited Destroy; end; procedure TBZSoundManager.Notification(AComponent: TComponent; Operation:TOperation); begin if Operation = opRemove then begin // if AComponent = FListener then Listener := nil; if AComponent = FCadencer then Cadencer := nil; end; inherited Notification(AComponent, Operation); end; procedure TBZSoundManager.SetActive(const val: Boolean); begin if (csDesigning in ComponentState) or (csLoading in ComponentState) then FActive := val else if val <> FActive then begin if val then begin if Assigned(vActiveSoundManager) then vActiveSoundManager.Active := False; if DoActivate then begin FActive := True; vActiveSoundManager := Self; end; end else begin try StopAllSources; DoDeActivate; finally FActive := val; vActiveSoundManager := nil; end; end; end; end; function TBZSoundManager.DoActivate: Boolean; begin Result := True; end; procedure TBZSoundManager.DoDeActivate; begin StopAllSources; end; procedure TBZSoundManager.SetMute(const val: Boolean); begin if val <> FMute then begin if val then begin if DoMute then FMute := True end else begin DoUnMute; FMute := False; end; end; end; function TBZSoundManager.DoMute: Boolean; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Mute then MuteSource(Sources[i], True); Result := True; end; procedure TBZSoundManager.DoUnMute; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Mute then MuteSource(Sources[i], False); end; procedure TBZSoundManager.DoPlay; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Playing then PlaySource(Sources[i], True); end; procedure TBZSoundManager.DoStop; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Playing then PlaySource(Sources[i], False); end; procedure TBZSoundManager.SetPlaying(const val: Boolean); begin if val <> FPlaying then begin if val then begin DoPlay; FPlaying := True; FPause := False; //SetPause(False); end else begin DoStop; FPlaying := False; FPause := True; end; end; end; procedure TBZSoundManager.SetPause(const val: Boolean); begin if val <> FPause then begin if val then begin if DoPause then FPause := True end else begin DoUnPause; FPause := False; end; end; end; procedure TBZSoundManager.SetUseEnvironment(const val: Boolean); begin if FUseEnvironment = val then exit; FUseEnvironment := Val; //Include(FChange, smcEnv); End; procedure TBZSoundManager.Loaded; begin inherited; if Active and (not (csDesigning in ComponentState)) then begin FActive := False; Active := True; end; end; procedure TBZSoundManager.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Doppler', @ReadDoppler, @WriteDoppler, (DopplerFactor <>1)); end; procedure TBZSoundManager.WriteDoppler(writer: TWriter); begin writer.WriteFloat(DopplerFactor); end; procedure TBZSoundManager.ReadDoppler(reader: TReader); begin FDopplerFactor := reader.ReadFloat; end; function TBZSoundManager.DoPause: Boolean; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Pause then PauseSource(Sources[i], True); Result := True; end; procedure TBZSoundManager.DoUnPause; var i: Integer; begin for i := 0 to Sources.Count - 1 do if not Sources[i].Pause then PauseSource(Sources[i], False); end; procedure TBZSoundManager.SetMasterVolume(const val: Single); begin if val < 0 then FMasterVolume := 0 else if val > 1 then FMasterVolume := 1 else FMasterVolume := val; NotifyMasterVolumeChange; end; procedure TBZSoundManager.SetMaxChannels(const val: Integer); begin if val <> FMaxChannels then begin if val < 1 then FMaxChannels := 1 else FMaxChannels := val; end; end; procedure TBZSoundManager.SetOutputFrequency(const val: Integer); begin if val <> FOutputFrequency then begin if val < 11025 then FOutputFrequency := 11025 else FOutputFrequency := val; end; end; procedure TBZSoundManager.SetUpdateFrequency(const val: Single); begin FUpdateFrequency := Clamp(val, 1, 60); end; function TBZSoundManager.StoreUpdateFrequency: Boolean; begin Result := (FUpdateFrequency <> 10); end; procedure TBZSoundManager.SetCadencer(const val: TBZCadencer); begin if val <> FCadencer then begin if Assigned(FCadencer) then FCadencer.UnSubscribe(Self); FCadencer := val; if Assigned(FCadencer) then FCadencer.Subscribe(Self); end; end; procedure TBZSoundManager.SetDistanceFactor(const val: Single); begin if val <= 0 then FDistanceFactor := 1 else FDistanceFactor := val; Notify3DFactorsChanged; end; function TBZSoundManager.StoreDistanceFactor: Boolean; begin Result := (FDistanceFactor <> 1); end; procedure TBZSoundManager.SetRollOffFactor(const val: Single); begin if val <= 0 then FRollOffFactor := 1 else FRollOffFactor := val; Notify3DFactorsChanged; end; function TBZSoundManager.StoreRollOffFactor: Boolean; begin Result := (FRollOffFactor <> 1); end; procedure TBZSoundManager.SetDopplerFactor(const val: Single); begin if val < 0 then FDopplerFactor := 0 else if val > 10 then FDopplerFactor := 10 else FDopplerFactor := val; Notify3DFactorsChanged; end; procedure TBZSoundManager.SetSoundEnvironment(const val: TBZSoundReverbEnvironment); begin if val <> FSoundEnvironment then begin FSoundEnvironment := val; NotifyEnvironmentChanged; end; end; procedure TBZSoundManager.ListenerCoordinates(var position, velocity, direction, up: TBZVector); var right: TBZVector; begin (* if Listener <> nil then begin position := Listener.AbsolutePosition; if FLastDeltaTime <> 0 then begin velocity := VectorSubtract(position, FLastListenerPosition); ScaleVector(velocity, 1 / FLastDeltaTime); end; FLastListenerPosition := position; if (Listener is TBZCamera) and (TBZCamera(Listener).TargetObject <> nil) then begin // special case of the camera targeting something direction := TBZCamera(Listener).AbsoluteVectorToTarget; NormalizeVector(direction); up := Listener.AbsoluteYVector; right := VectorCrossProduct(direction, up); up := VectorCrossProduct(right, direction); end else begin direction := Listener.AbsoluteZVector; up := Listener.AbsoluteYVector; end; end else *) begin position := NullHmgVector; //NullHmgPoint; velocity := NullHmgVector; direction := ZHmgVector; up := YHmgVector; end; end; procedure TBZSoundManager.NotifyMasterVolumeChange; begin // nothing end; procedure TBZSoundManager.Notify3DFactorsChanged; begin // nothing end; procedure TBZSoundManager.NotifyEnvironmentChanged; begin // nothing end; (* procedure TBZSoundManager.SetListener(const val: TBZBaseSceneObject); begin if Assigned(FListener) then FListener.RemoveFreeNotification(Self); FListener := val; if Assigned(FListener) then FListener.FreeNotification(Self); end; *) procedure TBZSoundManager.SetSources(const val: TBZSoundSources); begin FSources.Assign(val); end; procedure TBZSoundManager.KillSource(aSource: TBZBaseSoundSource); begin // nothing end; procedure TBZSoundManager.UpdateSource(aSource: TBZBaseSoundSource); begin aSource.FChanges := []; end; procedure TBZSoundManager.MuteSource(aSource: TBZBaseSoundSource; muted: Boolean); begin // nothing end; procedure TBZSoundManager.PauseSource(aSource: TBZBaseSoundSource; paused: Boolean); begin // nothing end; procedure TBZSoundManager.PlaySource(aSource : TBZBaseSoundSource; playing : Boolean); begin // nothing end; function TBZSoundManager.GetDefaultFrequency(aSource : TBZBaseSoundSource) : Integer; begin Result := 44100; end; function TBZSoundManager.GetTimePosition(aSource : TBZBaseSoundSource): Single; begin result:=0.0; end; procedure TBZSoundManager.UpdateSources; var i: Integer; begin for i := Sources.Count - 1 downto 0 do UpdateSource(Sources[i]); end; procedure TBZSoundManager.StopAllSources; var i: Integer; begin for i := Sources.Count - 1 downto 0 do Sources.Delete(i); end; procedure TBZSoundManager.DoProgress(const progressTime: TBZProgressTimes); begin if not Active then Exit; with progressTime do if newTime - FLastUpdateTime > 1 / FUpdateFrequency then begin FLastDeltaTime := newTime - FLastUpdateTime; FLastUpdateTime := newTime; UpdateSources; end; end; function TBZSoundManager.CPUUsagePercent: Single; begin Result := -1; end; function TBZSoundManager.EAXSupported: Boolean; begin Result := False; end; function TBZSoundManager.GetInformations : String; begin Result := 'No Informations'; end; {%endregion%} (* constructor TBZBSoundEmitter.Create(aOwner: TBZXCollection); begin inherited Create(aOwner); FSource := TBZSoundSource.Create(nil); end; destructor TBZBSoundEmitter.Destroy; begin if Assigned(FPlayingSource) then FPlayingSource.Free; FSource.Free; inherited Destroy; end; procedure TBZBSoundEmitter.Assign(Source: TPersistent); begin if Source is TBZBSoundEmitter then begin FSource.Assign(TBZBSoundEmitter(Source).FSource); end; inherited Assign(Source); end; procedure TBZBSoundEmitter.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive Version 0 FSource.WriteToFiler(writer); WriteBoolean(FPlaying); end; end; procedure TBZBSoundEmitter.ReadFromFiler(reader: TReader); begin inherited; with AReader do begin ReadInteger; // ignore archiveVersion FSource.ReadFromFiler(reader); FPlaying := ReadBoolean; end; end; procedure TBZBSoundEmitter.Loaded; begin inherited; if not (csDesigning in OwnerBaseSceneObject.ComponentState) then SetPlaying(FPlaying); end; class function TBZBSoundEmitter.FriendlyName: string; begin Result := 'Sound Emitter'; end; class function TBZBSoundEmitter.FriendlyDescription: string; begin Result := 'A simple sound emitter behaviour'; end; class function TBZBSoundEmitter.UniqueItem: Boolean; begin Result := False; end; procedure TBZBSoundEmitter.DoProgress(const progressTime: TProgressTimes); begin // nothing, yet end; procedure TBZBSoundEmitter.SetSource(const val: TBZBaseSoundSource); begin FSource.Assign(val); end; procedure TBZBSoundEmitter.SetPlaying(const val: Boolean); begin if FPlaying = val then exit; if csDesigning in OwnerBaseSceneObject.ComponentState then FPlaying := val else if ActiveSoundManager <> nil then begin if val <> Playing then begin if val then begin FPlayingSource := ActiveSoundManager.Sources.Add; FPlayingSource.FBehaviourToNotify := Self; FPlayingSource.Assign(FSource); FPlayingSource.Origin := OwnerBaseSceneObject; end else FPlayingSource.Free; end; end // else if vVerboseGLSMErrors then // InformationDlg('No Active Sound Manager.'#13#10'Make sure manager is created before emitter'); end; function TBZBSoundEmitter.GetPlaying: Boolean; begin if csDesigning in OwnerBaseSceneObject.ComponentState then Result := FPlaying else Result := Assigned(FPlayingSource); end; procedure TBZBSoundEmitter.NotifySourceDestruction(aSource: TBZSoundSource); begin Assert(FPlayingSource = aSource); FPlayingSource := nil; end; *) initialization // class registrations RegisterClasses([TBZSoundLibrary, TBZSoundFXLibrary]); RegisterXCollectionItemClass(TBZLowPassSoundFilter); RegisterXCollectionItemClass(TBZHighPassSoundFilter); RegisterXCollectionItemClass(TBZBandPassSoundFilter); RegisterXCollectionItemClass(TBZReverbSoundEffect); RegisterXCollectionItemClass(TBZEAXReverbSoundEffect); RegisterXCollectionItemClass(TBZChorusSoundEffect); RegisterXCollectionItemClass(TBZDistortionSoundEffect); RegisterXCollectionItemClass(TBZEchoSoundEffect); RegisterXCollectionItemClass(TBZFlangerSoundEffect); RegisterXCollectionItemClass(TBZCompressorSoundEffect); RegisterXCollectionItemClass(TBZEqualizerSoundEffect); //RegisterXCollectionItemClass(TBZBSoundEmitter); vSoundLibraries := TList.Create; vSoundFXLibraries := TList.Create; finalization if Assigned(vActiveSoundManager) then vActiveSoundManager.Active := False; vSoundLibraries.Free; vSoundLibraries := nil; vSoundFXLibraries.Free; vSoundFXLibraries := nil; UnRegisterXCollectionItemClass(TBZLowPassSoundFilter); UnRegisterXCollectionItemClass(TBZHighPassSoundFilter); UnRegisterXCollectionItemClass(TBZBandPassSoundFilter); UnRegisterXCollectionItemClass(TBZReverbSoundEffect); UnRegisterXCollectionItemClass(TBZEAXReverbSoundEffect); UnRegisterXCollectionItemClass(TBZChorusSoundEffect); UnRegisterXCollectionItemClass(TBZDistortionSoundEffect); UnRegisterXCollectionItemClass(TBZEchoSoundEffect); UnRegisterXCollectionItemClass(TBZFlangerSoundEffect); UnRegisterXCollectionItemClass(TBZCompressorSoundEffect); UnRegisterXCollectionItemClass(TBZEqualizerSoundEffect); //UnregisterXCollectionItemClass(TBZBSoundEmitter); end.
unit eExtLink; interface uses API_ORM, eCommon; type TExtSource = class(TEntity) private FSource: string; public class function GetStructure: TSructure; override; published property Source: string read FSource write FSource; end; TExtLink = class(TEntity) private FExtSource: TExtSource; FExtSourceID: Integer; FLink: string; public class function GetStructure: TSructure; override; published property ExtSource: TExtSource read FExtSource write FExtSource; property ExtSourceID: Integer read FExtSourceID write FExtSourceID; property Link: string read FLink write FLink; end; TMovieExtLink = class(TEntity) private FExtLink: TExtLink; FExtLinkID: Integer; FMovieID: Integer; public class function GetStructure: TSructure; override; constructor Create(aID: Integer = 0); published property ExtLink: TExtLink read FExtLink write FExtLink; property ExtLinkID: Integer read FExtLinkID write FExtLinkID; property MovieID: Integer read FMovieID write FMovieID; end; TMovieExtLinkList = TEntityList<TMovieExtLink>; TExtMovieSearchResult = record public CoverLink: WideString; ID: Integer; Link: WideString; Title: WideString; TitleOrign: WideString; Year: Integer; end; TExtMovieSearchArr = TArray<TExtMovieSearchResult>; implementation uses eVideoMovie; constructor TMovieExtLink.Create(aID: Integer = 0); begin inherited Create(aID); if IsNewInstance then ExtLink := TExtLink.Create; end; class function TMovieExtLink.GetStructure: TSructure; begin Result.TableName := 'VIDEO_EXT_LINKS'; AddForeignKey(Result.ForeignKeyArr, 'EXT_LINK_ID', TExtLink, 'ID'); AddForeignKey(Result.ForeignKeyArr, 'MOVIE_ID', TMovie, 'ID'); end; class function TExtLink.GetStructure: TSructure; begin Result.TableName := 'EXT_LINKS'; AddForeignKey(Result.ForeignKeyArr, 'EXT_SOURCE_ID', TExtSource, 'ID'); end; class function TExtSource.GetStructure: TSructure; begin Result.TableName := 'EXT_SOURCES'; end; end.
// --- eXgine_Utils_Stream --- //Copyright © 2006-2009 eXgine. All rights reserved. BSD License. Authors: XProger // ------------------------ unit eXgine_Utils_Stream; {$DEFINE dgAssert} interface uses dgHeader; type TdgCustomStream = class(TdgStream) protected FSize: Longint; FPos: Longint; public function GetSize: Longint; override; function GetPos: Longint; override; procedure SaveToFile(const aFileName: AnsiString); override; function ReadString: AnsiString; override; function WriteString(const Str: AnsiString): Longint; override; function ReadLine: AnsiString; override; end; TdgMemoryStream = class(TdgCustomStream) constructor Create; overload; constructor Create(MemSize: LongWord); overload; constructor Create(Mem: Pointer; MemSize: LongWord; isCopy: boolean); overload; constructor Create(Stream: TdgStream); overload; constructor Create(const FileName: AnsiString); overload; destructor Destroy; override; protected FMem: pointer; fCapacity: Longint; public function CopyFrom(Stream: TdgStream): Longint; override; function ReadBuffer(out Buf; Count: Longint): Longint; override; function WriteBuffer(const Buf; Count: Longint): Longint; override; procedure Seek(NewPos: Longint); override; procedure SetSize(NewSize: Longint); procedure Clear; property Memory: pointer read FMem; end; TdgFileStream = class(TdgCustomStream) constructor Create; overload; constructor Create(const FileName: AnsiString; isWrite: Boolean = False); overload; destructor Destroy; override; protected F: file; RW: Boolean; FStart: Longint; FValid: Boolean; public function CopyFrom(Stream: TdgStream): Longint; override; function Valid: Boolean; function ReadBuffer(out Buf; Count: Longint): Longint; override; function WriteBuffer(const Buf; Count: Longint): Longint; override; procedure Seek(NewPos: Longint); override; procedure SetBlock(NewStart, NewSize: Longint); end; implementation uses dgTraceCore; {$REGION 'TdgCustomStream'} procedure TdgCustomStream.SaveToFile(const aFileName: AnsiString); var cFileStream: TdgFileStream; begin cFileStream := TdgFileStream.Create(aFileName, true); fPos := 0; cFileStream.CopyFrom(self); cFileStream.Free; end; function TdgCustomStream.GetSize: Longint; begin result := fSize; end; function TdgCustomStream.GetPos: Longint; begin result := fPos; end; function TdgCustomStream.ReadString: AnsiString; var Len: Byte; begin ReadBuffer(Len, SizeOf(Len)); if Len <> 0 then begin SetLength(Result, Len); ReadBuffer(Result[1], Len); end else Result := ''; end; function TdgCustomStream.WriteString(const Str: AnsiString): Longint; var Len: Byte; begin Len := Length(Str); Result := WriteBuffer(Len, SizeOf(Len)) + WriteBuffer(Str[1], Len); end; function TdgCustomStream.ReadLine: AnsiString; var c: char; i: integer; begin result := ''; repeat i := ReadBuffer(c, 1); if i>0 then result := result + c; until (c = dgConst.Str.CR) or (i = 0); end; {$ENDREGION} {$REGION 'TMemoryStream'} constructor TdgMemoryStream.Create; begin inherited Create; GetMem(fMem, 0); FSize := 0; fPos := 0; fCapacity := 0; end; constructor TdgMemoryStream.Create(MemSize: LongWord); begin inherited Create; GetMem(FMem, MemSize); FSize := MemSize; fPos := 0; fCapacity := 0; end; constructor TdgMemoryStream.Create(Mem: Pointer; MemSize: LongWord; isCopy: boolean); begin inherited Create; if isCopy then begin GetMem(FMem, MemSize); move(Mem^, FMem^, MemSize); end else fMem := Mem; FSize := MemSize; fCapacity := MemSize; fPos := 0; end; constructor TdgMemoryStream.Create(Stream: TdgStream); begin inherited Create; fSize := Stream.Size; GetMem(fMem, fSize); Stream.ReadBuffer(FMem^, FSize); fCapacity := fSize; fPos := 0; end; constructor TdgMemoryStream.Create(const FileName: AnsiString); var cFileStream: TdgFileStream; begin inherited Create; cFileStream := TdgFileStream.Create(FileName, false); fSize := cFileStream.Size; GetMem(fMem, fSize); fCapacity := fSize; cFileStream.ReadBuffer(FMem^, FSize); cFileStream.free; fPos := 0; end; destructor TdgMemoryStream.Destroy; begin FreeMem(FMem); inherited; end; procedure TdgMemoryStream.Clear; begin fPos:=0; fSize:=0; end; function TdgMemoryStream.CopyFrom(Stream: TdgStream): Longint; begin {$IFDEF dgAssert} dgTrace.Assert(Stream <> nil, '{6EDD3460-47A7-42BD-9E86-09CF6468E0F4}'); {$ENDIF} if fCapacity < Stream.Size then begin ReallocMem(fMem, Stream.Size); fCapacity := Stream.Size; end; fSize := Stream.Size; fPos := 0; Result := Stream.ReadBuffer(fMem^, Stream.Size); end; function TdgMemoryStream.ReadBuffer(out Buf; Count: Longint): Longint; begin if FSize - FPos < Count then Result := FSize - FPos else Result := Count; if result > 0 then Move(Pointer(Longint(fMem) + fPos)^, Buf, Result); FPos := FPos + Result; end; procedure TdgMemoryStream.SetSize(NewSize: Longint); const MemoryDelta = $2000; { Must be a power of 2 } begin if fCapacity < NewSize then begin if NewSize - fCapacity < MemoryDelta then fCapacity := fCapacity + MemoryDelta else fCapacity := fPos + NewSize; ReallocMem(fMem, fCapacity); end; fSize:=NewSize; end; function TdgMemoryStream.WriteBuffer(const Buf; Count: Longint): Longint; const MemoryDelta = $2000; { Must be a power of 2 } begin if fCapacity - FPos < Count then begin if Count - (fCapacity - FPos) < MemoryDelta then fCapacity := fCapacity + MemoryDelta else fCapacity := fPos + Count; ReallocMem(fMem, fCapacity); end; fSize := fPos + Count; Result := Count; Move(Buf, Pointer(Longint(fMem) + fPos)^, Result); Inc(FPos, Result); end; procedure TdgMemoryStream.Seek(NewPos: Longint); begin if NewPos > FSize then NewPos := FSize; FPos := NewPos; end; {$ENDREGION} {$REGION 'TFileStream'} constructor TdgFileStream.Create; begin inherited Create; {$IFDEF dgAssert} dgTrace.Assert(false, '{4369FE24-580C-4064-86B0-BC271308697D}'); {$ENDIF} end; constructor TdgFileStream.Create(const FileName: AnsiString; isWrite: Boolean); begin inherited Create; FStart:=0; FileMode := 2; Self.RW := isWrite; AssignFile(F, FileName); {$I-} if RW then begin FileMode := 1; // write-only Rewrite(F, 1) end else begin FileMode := 0; // read-only Reset(F, 1); end; {$I+} if IOresult = 0 then begin FSize := FileSize(F); FValid := True; end; {$IFDEF dgAssert} dgTrace.Assert(fValid, '{6D08DCD6-C922-4A47-830A-F5E0CC263117}'); {$ENDIF} end; destructor TdgFileStream.Destroy; begin if FValid then CloseFile(F); inherited; end; function TdgFileStream.CopyFrom(Stream: TdgStream): Longint; var Buf: Pointer; Count: LongWord; begin {$IFDEF dgAssert} dgTrace.Assert(Stream <> nil, '{6EDD3460-47A7-42BD-9E86-09CF6468E0F4}'); {$ENDIF} Count := Stream.Size; if stream is TdgMemoryStream then Result := WriteBuffer(TdgMemoryStream(Stream).Memory^, Stream.Size) else begin //may be error, if big size GetMem(Buf, Count); Result := WriteBuffer(Buf^, Stream.ReadBuffer(Buf^, Count)); FreeMem(Buf); end; end; function TdgFileStream.Valid: Boolean; begin Result := FValid; end; function TdgFileStream.ReadBuffer(out Buf; Count: Longint): Longint; begin Result := 0; if not RW then BlockRead(F, Buf, Count, Result); Inc(FPos, Result); end; function TdgFileStream.WriteBuffer(const Buf; Count: Longint): Longint; begin Result := 0; if RW then BlockWrite(F, Buf, Count, Result); Inc(FSize, Result); Inc(FPos, Result); end; procedure TdgFileStream.Seek(NewPos: Longint); begin System.Seek(F, LongInt(FStart + NewPos)); end; procedure TdgFileStream.SetBlock(NewStart, NewSize: Longint); begin FStart := NewStart; FSize := NewSize; Seek(0); end; {$ENDREGION} end.
unit RRManagerReportFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, RRManagerReport, RRManagerBaseObjects, RRManagerObjects, RRManagerCreateReportForm, RRManagerPersistentObjects, RRManagerBaseGUI, ToolWin, ImgList; type // TfrmSelectReport = class(TFrame) TfrmSelectReport = class(TBaseFrame) gbxReport: TGroupBox; lbxAllReports: TListBox; pnlButtons: TPanel; chbxRemoveEmpties: TCheckBox; prg: TProgressBar; pnlEditReportButtons: TPanel; imgList: TImageList; tlbrReportMan: TToolBar; tlbtnEditReport: TToolButton; tlbtnAddReport: TToolButton; tlbtnDeleteReport: TToolButton; procedure lbxAllReportsClick(Sender: TObject); procedure btnCreateReportClick(Sender: TObject); private FReportFilters: TReportFilters; FReport: TCommonReport; FShowButtons: boolean; FShowRemoveEmpties: boolean; function GetReportFilter: TReportFilter; function GetStructures: TOldStructures; procedure SetShowButtons(const Value: boolean); procedure SetShowRemoveEmpties(const Value: boolean); { Private declarations } protected FReportLoadAction: TBaseAction; FReportEditAction: TBaseAction; FReportAddAction: TBaseAction; FReportDeleteAction: TBaseAction; procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; public { Public declarations } property Structures: TOldStructures read GetStructures; property ReportFilter: TReportFilter read GetReportFilter; property Report: TCommonReport read FReport; property ShowButtons: boolean read FShowButtons write SetShowButtons; property ShowRemoveEmpties: boolean read FShowRemoveEmpties write SetShowRemoveEmpties; procedure Reload; procedure Save; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses Facade; {$R *.DFM} type TReportLoadAction = class(TReportBaseLoadAction) public function Execute: boolean; override; end; TReportEditAction = class(TReportBaseEditAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TReportAddAction = class(TReportEditAction) public function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; TReportDeleteAction = class(TBaseAction) public function Execute: boolean; overload; override; function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; { TfrmSelectReport } procedure TfrmSelectReport.ClearControls; begin lbxAllReports.ItemIndex := -1; end; constructor TfrmSelectReport.Create(AOwner: TComponent); begin inherited; FReportFilters := TReportFilters.Create(nil); FReportLoadAction := TReportLoadAction.Create(Self); FReportEditAction := TReportEditAction.Create(Self); FReportAddAction := TReportAddAction.Create(Self); FReportDeleteAction := TReportDeleteAction.Create(Self); tlbtnAddReport.Action := FReportAddAction; tlbtnEditReport.Action := FReportEditAction; tlbtnDeleteReport.Action := FReportDeleteAction; FReportLoadAction.Execute; NeedCopyState := false; end; procedure TfrmSelectReport.FillControls(ABaseObject: TBaseObject); begin if Assigned(AllReports) then begin FReportLoadAction.Execute; lbxAllReports.ItemIndex := 0; end; end; procedure TfrmSelectReport.FillParentControls; begin inherited; end; function TfrmSelectReport.GetReportFilter: TReportFilter; begin Result := EditingObject as TReportFilter; end; function TfrmSelectReport.GetStructures: TOldStructures; begin if Assigned(ReportFilter) then Result := ReportFilter.Structures else Result := nil; end; procedure TfrmSelectReport.Save; begin inherited; ReportFilter.Report := Report; end; procedure TfrmSelectReport.lbxAllReportsClick(Sender: TObject); begin if lbxAllReports.ItemIndex > -1 then FReport := TCommonReport(lbxAllReports.Items.Objects[lbxAllReports.ItemIndex]) else FReport := nil; if Assigned(FReport) then begin FEditingObject := FReportFilters.GetFilterByReportID(FReport.ID); if not Assigned(FEditingObject) then FEditingObject := FReportFilters.Add; ReportFilter.Report := Report; end; Check; end; destructor TfrmSelectReport.Destroy; begin FReportFilters.Free; FReportEditAction.Free; FReportLoadAction.Free; inherited; end; procedure TfrmSelectReport.RegisterInspector; begin inherited; // Inspector.Add(lbxAllReports, nil, ptSelect, 'отчёт', false); end; procedure TfrmSelectReport.SetShowButtons(const Value: boolean); begin FShowButtons := Value; pnlEditReportButtons.Visible := Value; end; procedure TfrmSelectReport.Reload; begin if AllReports.NeedsUpdate then FReportLoadAction.Execute; end; procedure TfrmSelectReport.SetShowRemoveEmpties(const Value: boolean); begin FShowRemoveEmpties := Value; pnlButtons.Visible := Value; end; { TReportLoadAction } function TReportLoadAction.Execute: boolean; begin AllReports := TReports.Create(nil); Result := inherited Execute; with Owner as TfrmSelectReport do begin lbxAllReports.Items.BeginUpdate; lbxAllReports.Clear; AllReports.MakeList(lbxAllReports.Items, AllOpts.Current.ListOption, false); lbxAllReports.Items.EndUpdate; FReport := nil; end; end; procedure TfrmSelectReport.btnCreateReportClick(Sender: TObject); begin // end; { TReportEditAction } constructor TReportEditAction.Create(AOwner: TComponent); begin inherited; Caption := 'Редактировать отчет'; CanUndo := false; Visible := true; ImageIndex := 1; end; function TReportEditAction.Execute: boolean; begin Result := Execute((Owner as TfrmSelectReport).Report); end; function TReportEditAction.Execute(ABaseObject: TBaseObject): boolean; var lbx: TListBox; begin LastCollection := AllReports; Result := Inherited Execute(ABaseObject); // обновляем представление lbx := (Owner as TfrmSelectReport).lbxAllReports; if not LastCollection.NeedsUpdate and Assigned(ABaseObject) then lbx.Items[lbx.ItemIndex] := ABaseObject.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false) else begin AllReports.NeedsUpdate := true; (Owner as TfrmSelectReport).FReportLoadAction.Execute; end; end; function TReportEditAction.Update: boolean; begin inherited Update; Result := Assigned(AllReports) and Assigned((Owner as TfrmSelectReport).Report); Enabled := Result; end; { TReportAddAction } constructor TReportAddAction.Create(AOwner: TComponent); begin inherited; Caption := 'Добавить отчет'; CanUndo := false; Visible := true; ImageIndex := 0; end; function TReportAddAction.Execute: boolean; begin Result := inherited Execute(nil); end; function TReportAddAction.Update: boolean; begin inherited Update; Result := Assigned(AllReports); Enabled := Result; end; { TReportDeleteAction } constructor TReportDeleteAction.Create(AOwner: TComponent); begin inherited; Caption := 'Удалить отчет'; CanUndo := false; Visible := true; ImageIndex := 2; end; function TReportDeleteAction.Execute: boolean; begin Result := Execute((Owner as TfrmSelectReport).Report); end; function TReportDeleteAction.Execute(ABaseObject: TBaseObject): boolean; var dp: TDataPoster; lbx: TListBox; begin Result := true; if MessageBox(0, PChar('Вы действительно хотите удалить отчёт ' + #13#10 + ABaseObject.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false) + '?'), 'Вопрос', MB_YESNO+MB_APPLMODAL+MB_DEFBUTTON2+MB_ICONQUESTION) = ID_YES then begin dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TReportsDataPoster]; dp.DeleteFromDB(ABaseObject); lbx := (Owner as TfrmSelectReport).lbxAllReports; lbx.Items.Delete(lbx.ItemIndex); (Owner as TfrmSelectReport).FReport := nil; AllReports.NeedsUpdate := true; end; end; function TReportDeleteAction.Update: boolean; begin inherited Update; Result := Assigned(AllReports) and Assigned((Owner as TfrmSelectReport).Report); Enabled := Result; end; end.
unit UfrmEditText; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, GR32_Image, USlide, USourceInfo, Vcl.ExtCtrls, UFastKeysSS, Vcl.Menus; type TfrmEditText = class(TForm, ISlideEditForm) Label2: TLabel; Label3: TLabel; edtOverviewName: TEdit; ImgViewPicto: TImgView32; btnOK: TButton; btnCancel: TButton; mmoText: TMemo; btnInsertSlide: TButton; btnPaste: TButton; cbxAutomaticSmallNumbers: TCheckBox; Shape1: TShape; btnInternet: TButton; btnFill: TButton; cbxPartOfForm: TCheckBox; cbxShowInOverview: TCheckBox; btnSelectPictoNone: TButton; btnConvertToAGB: TButton; btnConvertToDL: TButton; btnConvertToGBA: TButton; btnConvertToHC: TButton; ppmText: TPopupMenu; mniPaste: TMenuItem; btnBibleNBV: TButton; procedure ImgViewPictoClick(Sender: TObject); procedure btnInsertSlideClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure mmoTextKeyPress(Sender: TObject; var Key: Char); procedure btnPasteClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnInternetClick(Sender: TObject); procedure btnFillClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSelectPictoNoneClick(Sender: TObject); procedure btnConvertToHCClick(Sender: TObject); procedure btnConvertToAGBClick(Sender: TObject); procedure btnConvertToDLClick(Sender: TObject); procedure btnConvertToGBAClick(Sender: TObject); procedure mniPasteClick(Sender: TObject); procedure ppmTextPopup(Sender: TObject); procedure btnBibleNBVClick(Sender: TObject); private FStartSlide: string; FConvertedSlide: string; FSlideTemplateName: string; FPictoName: TSourceInfo; FIsBibleText: boolean; FSlideVariables: TFastKeyValuesSS; FSlideOptions: TFastKeyValuesSS; FOverviewType: TOverviewType; { Private declarations } protected function GetSlideAsString: string; procedure SetSlideAsString(const Value: string); function Edit: boolean; procedure ConvertToTemplate(strReadingTemplate, strTextTemplate: string); public property SlideAsString: string read GetSlideAsString write SetSlideAsString; property IsBibleText: boolean read FIsBibleText write FIsBibleText; end; implementation {$R *.dfm} uses Clipbrd, GnuGetText, UUtilsStrings, UUtils, UUtilsForms, USettings, USplitBibleVerses, USlideLayout, UfrmBrowseFTP, USlideTemplate, USlideVariables; { TfrmEditText } procedure TfrmEditText.btnBibleNBVClick(Sender: TObject); begin OpenInternetSource('BeamTeam/Notenbeeld/Bijbel(vertalingen)/NBV'); end; procedure TfrmEditText.btnConvertToAGBClick(Sender: TObject); begin ConvertToTemplate(CTEMPLATE_READING_AGB, CTEMPLATE_TEXT_AGB); end; procedure TfrmEditText.btnConvertToDLClick(Sender: TObject); begin ConvertToTemplate(CTEMPLATE_READING_DL, CTEMPLATE_TEXT_DL); end; procedure TfrmEditText.btnConvertToGBAClick(Sender: TObject); begin ConvertToTemplate(CTEMPLATE_READING_GBA, CTEMPLATE_TEXT_GBA); end; procedure TfrmEditText.btnConvertToHCClick(Sender: TObject); begin ConvertToTemplate(CTEMPLATE_READING_HC, CTEMPLATE_TEXT_HC); end; procedure TfrmEditText.ConvertToTemplate(strReadingTemplate, strTextTemplate: string); var template: TSlideTemplate; slide: TSlide; begin template := nil; case FOverviewType of otSong: ; otIgnore, otReading: template := GetSlideTemplates.FindByName(strReadingTemplate); otText: template := GetSlideTemplates.FindByName(strTextTemplate); end; if Assigned(template) then begin Hide; slide := template.DoOnAdd(true); if Assigned(slide) then begin FConvertedSlide := slide.AsJSon; end; ModalResult := mrOK; end; end; procedure TfrmEditText.btnFillClick(Sender: TObject); var slVariables: TStringList; begin slVariables := TStringList.Create; try slVariables.Duplicates := dupIgnore; slVariables.Sorted := true; DetectSlideVariables(mmoText.Text, slVariables); CleanupSlideVariables(FSlideVariables, slVariables); EditSlideVariables(FSlideVariables, FSlideOptions); finally slVariables.Free; end; end; procedure TfrmEditText.btnInsertSlideClick(Sender: TObject); begin if mmoText.SelText = CNEWSLIDE then begin mmoText.SelText := ''; end else begin mmoText.SelLength := 0; mmoText.SelText := CNEWSLIDE; end; end; procedure TfrmEditText.btnInternetClick(Sender: TObject); begin OpenInternetSource(''); end; procedure TfrmEditText.btnPasteClick(Sender: TObject); var strText: string; aText: TArrayOfString; i: integer; layout: TSlideLayout; content: TLayoutItem; options: TSplitOptions; begin strText := Clipboard.AsText; if strText <> '' then begin content := nil; layout := GetSlideLayouts.FindByName('Content-layout'); if Assigned(layout) then begin content := layout['content']; end; options := [soLineBreaks]; if IsBibleText then options := options + [soNumbers]; aText := SplitBibleVerses(strText, 550, content, options); //mmoText.Lines.Clear; if mmoText.Lines.Count > 0 then begin mmoText.Lines.Add(CNEWSLIDE); end; //mmoText.Lines.Text := aText[0]; mmoText.Lines.Text := mmoText.Lines.Text + aText[0]; for i := 1 to Length(aText) -1 do begin mmoText.Lines.Add(CNEWSLIDE); mmoText.Lines.Text := mmoText.Lines.Text + aText[i]; end; end; end; procedure TfrmEditText.btnSelectPictoNoneClick(Sender: TObject); begin FPictoName.FileName := ''; ImgViewPicto.Bitmap.Clear; end; function TfrmEditText.Edit: boolean; begin Result := ShowModal = mrOk; end; procedure TfrmEditText.FormCreate(Sender: TObject); begin TranslateComponent(self); FSlideVariables := TFastKeyValuesSS.Create; FSlideOptions := TFastKeyValuesSS.Create; FConvertedSlide := ''; end; procedure TfrmEditText.FormDestroy(Sender: TObject); begin FPictoName.Free; FSlideOptions.Free; FSlideVariables.Free; end; procedure TfrmEditText.FormShow(Sender: TObject); var template: TSlideTemplate; begin template := GetSlideTemplates.FindByName(FSlideTemplateName); btnFill.Visible := Assigned(template) and (epSlideVariables in template.EditPossibilities); btnInsertSlide.Caption := CNEWSLIDE; end; function TfrmEditText.GetSlideAsString: string; var slide: TSlide; slideItemContent, slideItemFooter: TSlideItem; aContentStrings: TArrayOfString; i: integer; strPrefix: string; begin if FConvertedSlide <> '' then begin Result := FConvertedSlide; Exit; end; slide := TSlide.Create(FStartSlide); try slide.SlideName := slide.SlideTemplateName + ' : ' + edtOverviewName.Text; slide.OverviewName := edtOverviewName.Text; slide.ShowInOverview := cbxShowInOverview.Checked; slide.IsSubOverview := cbxPartOfForm.Checked; slide.PictoName := FPictoName.DeepCopy; slide.AutomaticSmallNumbers := cbxAutomaticSmallNumbers.Checked; slide.Variables.LoadFromString(FSlideVariables.SaveToString); slideItemFooter := slide['footer']; if Assigned(slideItemFooter) then begin slideItemFooter.ContentSources.Clear; case slide.OverviewType of otIgnore: ; otSong: strPrefix := _('Singing') + ': '; otReading: strPrefix := _('Reading') + ': '; otText: strPrefix := _('Text') + ': '; end; slideItemFooter.ContentSources.Add(TSourceInfo.CreateAsString(strPrefix + RespaceOverviewName(edtOverviewName.Text, false))); end; slideItemContent := slide['content']; if Assigned(slideItemContent) then begin slideItemContent.ContentSources.Clear; aContentStrings := split(mmoText.Lines.Text, CNEWSLIDE); for i := 0 to Length(aContentStrings) -1 do begin slideItemContent.ContentSources.Add(SourceInfoFromMemoText(trim(aContentStrings[i]))); end; end; Result := slide.AsJSon; finally slide.Free; end; end; procedure TfrmEditText.ImgViewPictoClick(Sender: TObject); begin FPictoName := SelectPicto(FPictoName); ViewPNG(FPictoName.FileName, ImgViewPicto.Bitmap); end; procedure TfrmEditText.mmoTextKeyPress(Sender: TObject; var Key: Char); begin if Key = ^A then begin (Sender as TMemo).SelectAll; Key := #0; end; end; procedure TfrmEditText.mniPasteClick(Sender: TObject); begin btnPasteClick(nil); end; procedure TfrmEditText.ppmTextPopup(Sender: TObject); begin mniPaste.Enabled := Clipboard.AsText <> ''; end; procedure TfrmEditText.SetSlideAsString(const Value: string); var slide: TSlide; slideItemContent: TSlideItem; i: Integer; sourceInfo: TSourceInfo; template: TSlideTemplate; begin FStartSlide := Value; slide := TSlide.Create(FStartSlide); try FSlideTemplateName := slide.SlideTemplateName; FSlideVariables.LoadFromString(slide.Variables.SaveToString); FOverviewType := slide.OverviewType; template := GetSlideTemplates.FindByName(FSlideTemplateName); if Assigned(template) then begin FSlideOptions.LoadFromString(template.VariableOptions.SaveToString); end; edtOverviewName.Text := slide.OverviewName; cbxShowInOverview.Checked := slide.ShowInOverview; cbxPartOfForm.Checked := slide.IsSubOverview; FreeAndNil(FPictoName); FPictoName := slide.PictoName.DeepCopy; ViewPNG(FPictoName.FileName, ImgViewPicto.Bitmap); cbxAutomaticSmallNumbers.Checked := slide.AutomaticSmallNumbers; IsBibleText := slide.OverviewType in [otReading, otText]; mmoText.Lines.Clear; slideItemContent := slide['content']; sourceInfo := slideItemContent.ContentSources[0]; mmoText.Lines.Text := SourceInfoToMemoText(sourceInfo); for i := 1 to slideItemContent.ContentSources.Count -1 do begin mmoText.Lines.Add(CNEWSLIDE + #13); sourceInfo := slideItemContent.ContentSources[i]; mmoText.Lines.Text := mmoText.Lines.Text + SourceInfoToMemoText(sourceInfo); end; finally slide.Free; end; end; end.
unit uMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfMain = class(TForm) BtnSearch: TButton; EdtCEP: TEdit; lblCEP: TLabel; LblStreet: TLabel; LblDistrict: TLabel; LblCity: TLabel; LblState: TLabel; lblStreetValue: TLabel; lblDistrictValue: TLabel; lblCityValue: TLabel; lblStateValue: TLabel; procedure BtnSearchClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var fMain: TfMain; implementation {$R *.dfm} uses uAtendeCliente; procedure TfMain.BtnSearchClick(Sender: TObject); var vMailWS: AtendeCliente; vAddress: enderecoERP; begin vMailWS := GetAtendeCliente(True); try vAddress := vMailWS.consultaCEP(EdtCEP.Text); lblStreetValue.Caption := vAddress.end_; LblDistrictValue.Caption := vAddress.bairro; LblCityValue.Caption := vAddress.cidade; LblStateValue.Caption := vAddress.uf; except lblStreetValue.Caption := EmptyStr; LblDistrictValue.Caption := EmptyStr; LblCityValue.Caption := EmptyStr; LblStateValue.Caption := EmptyStr; ShowMessage('CEP not found'); end; end; end.
unit Skeleton; (* Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the gl3ds main unit. * * The Initial Developer of the Original Code is * Noeska Software. * Portions created by the Initial Developer are Copyright (C) 2002-2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * M van der Honing * Sascha Willems * Jan Michalowsky * *) interface uses classes, Bone; type TBaseSkeleton = class; TBaseSkeletonClass = class of TBaseSkeleton; TBaseSkeleton = class(TComponent) protected FBoneClass : TBaseBoneClass; FBone: array of TBaseBone; FName: string; FNumBones: Integer; function GetBone(Index: integer): TBaseBone; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property BoneClass: TBaseBoneClass read FBoneClass write FBoneClass; procedure AddBone; procedure Assign(Source: TPersistent); override; procedure InitBones; procedure UpdateBones(); function GetBoneByName(s: string): TBaseBone; procedure LoadFromFile(Filename: string); virtual; abstract; procedure LoadFromStream(Stream: TStream); virtual; abstract; procedure SaveToFile(AFilename: string); virtual; abstract; procedure SaveToStream(Stream: TStream); virtual; abstract; property Bone[Index: integer]: TBaseBone read GetBone; property Name: string read FName write FName; property NumBones: Integer read FNumBones; end; implementation uses SysUtils; procedure TBaseSkeleton.Assign(Source: TPersistent); var i: integer; begin if Source is TBaseSkeleton then begin with TBaseSkeleton(Source) do begin self.FNumBones := FNumBones; setlength(self.FBone, FNumBones); for i := 0 to FNumBones - 1 do begin self.FBone[i] := FBoneClass.Create(self); self.FBone[i].Assign(FBone[i]); end; self.FName := FName; end; end else inherited; end; constructor TBaseSkeleton.Create(AOwner: TComponent); begin inherited; FBoneClass := TBaseBone; //Make sure a bone class is set end; destructor TBaseSkeleton.Destroy; begin inherited Destroy; //this will automaticaly free the meshes, materials, bones... //however do free the dynamic arrays used SetLength(FBone, 0); end; procedure TBaseSkeleton.AddBone; begin FNumBones := FNumBones + 1; SetLength(FBone, FNumBones); FBone[FNumBones - 1] := FBoneClass.Create(self); end; function TBaseSkeleton.GetBone(Index: integer): TBaseBone; begin Result := FBone[index]; end; function TBaseSkeleton.GetBoneByName(s: string): TBaseBone; var i: Word; begin Result := nil; for i := 0 to High(FBone) do if uppercase(FBone[i].Name) = uppercase(s) then begin Result := FBone[i]; break; end; end; procedure TBaseSkeleton.InitBones; var m: integer; begin //init bone structure If FNumBones > 0 then for m := 0 to FNumBones - 1 do begin FBone[m].Init; end; end; procedure TBaseSkeleton.UpdateBones(); var m: Integer; begin //set the bones to their new positions if FNumBones > 0 then for m := 0 to FNumBones - 1 do begin FBone[m].Update; end; end; end.
unit UTools; {$mode objfpc}{$H+} interface uses Classes, Types, Controls, Graphics, ExtCtrls, StdCtrls, UFigures, UDoublePoint, UPaintSpace, Math, UFigureParams, UToolParams, UParamEditors, UUtils; type TToolMetadata = record Name: String; Bitmap: TBitmap; Cursor: TCursor; end; StringArray = array of String; TParamChangingEvent = procedure(Sender: TObject) of object; TDrawItemEvent = procedure(Control: TWinControl; AIndex: Integer; ARect: TRect; AState: TOwnerDrawState) of object; TTool = class strict protected FMetadata: TToolMetadata; FFigures: TFigures; FPaintSpace: TPaintSpace; FOnHistoryChange: TEventHandler; FOnParamChange: TEventHandler; FOnParamsListChange: TEventHandler; public constructor Create; property OnHistoryChange: TEventHandler read FOnHistoryChange write FOnHistoryChange; property OnParamChange: TEventHandler read FOnParamChange write FOnParamChange; property OnParamsListChange: TEventHandler read FOnParamsListChange write FOnParamsListChange; property Figures: TFigures read FFigures write FFigures; property Metadata: TToolMetadata read FMetadata; property PaintSpace: TPaintSpace write FPaintSpace; class procedure CleanParamsPanel(APanel: TWinControl); procedure SetParamColor(AFigureColors: TFigureColors); virtual; procedure SetParamsPanel(APanel: TPanel); function GetParams: TParamEditorArray; virtual; procedure CleanUp; virtual; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); virtual; abstract; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); virtual; abstract; procedure MouseUp(APoint:TDoublePoint; AShift: TShiftState); virtual; abstract; end; TZoomTool = class(TTool) strict private FModeE: TZoomModePEditor; FPowerE: TZoomPowerPEditor; FFirstPoint: TDoublePoint; FSplitOff: TRectSplitOffFigure; public constructor Create; function GetParams: TParamEditorArray; override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseUp(APoint:TDoublePoint; AShift: TShiftState); override; end; THandTool = class(TTool) strict private FFirstPoint: TDoublePoint; public constructor Create; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseUp(APoint:TDoublePoint; AShift: TShiftState); override; end; TSelectTool = class(TTool) private FSelectBtnE: TSelectAllPEditor; FFirstPoint: TDoublePoint; FSplitOff: TRectSplitOffFigure; FIsFirstOnFigure: Boolean; FLastPoint: TDoublePoint; FCommonParams: array of TFigureParamArray; FFigureEditors: TFigureParamEditorArray; procedure ParamChange; procedure FRevers(AFigure: TFigure); procedure FSelect(AFigure: TFigure); procedure FSelectAllBtnClick(Sender: TObject); procedure InitFiguresParams; procedure AddFigureParamEditor(AParam: TFigureParamEditor); procedure CrossParams(AParams: TFigureParamArray); procedure ShowFiguresEditors(AControl: TWinControl); const CLICK_SIZE: Integer = 3; public constructor Create; function GetParams: TParamEditorArray; override; procedure CleanUp; override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseUp(APoint:TDoublePoint; AShift: TShiftState); override; end; TDrawingTool = class(TTool) strict protected FFigure: TFigure; procedure Finish; procedure CreateFigure; virtual; abstract; procedure InitializeFigure(APoint: TDoublePoint); virtual; abstract; procedure SetFigureParams; virtual; abstract; public procedure MouseUp(APoint:TDoublePoint; AShift: TShiftState); override; end; TLineTool = class(TDrawingTool) strict protected FLineWidthE: TLineWidthPEditor; FLineStyleE: TLineStylePEditor; FLineColorE: TColorPEditor; procedure CreateFigure; override; procedure InitializeFigure(APoint: TDoublePoint); override; procedure SetFigureParams; override; public constructor Create; function GetParams: TParamEditorArray; override; procedure SetParamColor(AFigureColors: TFigureColors); override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; end; TPenTool = class(TLineTool) strict protected procedure InitializeFigure(APoint: TDoublePoint); override; public constructor Create; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; end; TShapeTool = class(TDrawingTool) strict protected FLineWidthE: TLineWidthPEditor; FLineStyleE: TLineStylePEditor; FLineColorE: TColorPEditor; FShapeColorE: TColorPEditor; FShapeStyleE: TShapeStylePEditor; procedure InitializeFigure(APoint: TDoublePoint); override; procedure SetFigureParams; override; public constructor Create; function GetParams: TParamEditorArray; override; procedure SetParamColor(AFigureColors: TFigureColors); override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; end; TEllipseTool = class(TShapeTool) strict protected procedure CreateFigure; override; public constructor Create; end; TRectTool = class(TShapeTool) strict protected procedure CreateFigure; override; public constructor Create; end; TRegularPolygonTool = class(TShapeTool) strict protected FAngleCountE: TAngleCountPEditor; procedure CreateFigure; override; public constructor Create; function GetParams: TParamEditorArray; override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; end; TRoundedRectTool = class(TShapeTool) strict protected FRoundingE: TRoundingPEditor; procedure CreateFigure; override; procedure SetFigureParams; override; public constructor Create; function GetParams: TParamEditorArray; override; procedure MouseMove(APoint: TDoublePoint; AShift: TShiftState); override; procedure MouseDown(APoint: TDoublePoint; AShift: TShiftState); override; end; procedure RegisterTool(ATool: TTool); var Tools: array of TTool; implementation procedure Push(var Element: TFigureParam; var Arr: TFigureParamArray); begin SetLength(Arr, Length(Arr)+1); Arr[High(Arr)]:= Element; end; procedure Push(Element: Integer; var Arr: TIntArray); begin SetLength(Arr, Length(Arr)+1); Arr[High(Arr)]:= Element; end; procedure RegisterTool(ATool: TTool); begin SetLength(Tools, Length(Tools)+1); Tools[High(Tools)]:= ATool; end; constructor TTool.Create; begin FMetadata.Bitmap:= TBitmap.Create; end; class procedure TTool.CleanParamsPanel(APanel: TWinControl); var i: Integer; begin for i:= (APanel.ControlCount-1) downto 0 do APanel.Controls[i].Free; end; procedure TTool.SetParamColor(AFigureColors: TFigureColors); begin end; procedure TTool.SetParamsPanel(APanel: TPanel); var p: TParamEditor; begin CleanParamsPanel(APanel); for p in GetParams do p.FillUserInterface(APanel); end; function TTool.GetParams: TParamEditorArray; begin end; procedure TTool.CleanUp; begin end; procedure TSelectTool.ParamChange; begin FOnHistoryChange; FPaintSpace.PaintBox.Invalidate; end; procedure TSelectTool.FRevers(AFigure: TFigure); begin AFigure.Selected:= not AFigure.Selected; end; procedure TSelectTool.FSelect(AFigure: TFigure); begin AFigure.Selected:= true; end; procedure TSelectTool.FSelectAllBtnClick(Sender: TObject); begin FFigures.SelectAllFigures; FPaintSpace.PaintBox.Invalidate; end; constructor TSelectTool.Create; begin inherited Create; FMetadata.Name:= 'Select'; FSelectBtnE:= TSelectAllPEditor.Create; FSelectBtnE.SelectAllBtnClick:= @FSelectAllBtnClick; FMetadata.Bitmap.LoadFromFile('src/select_tool.bmp'); end; procedure TSelectTool.InitFiguresParams; var i, j: Integer; firstFound: Boolean = false; fp: TFigureParamArray; editors: TFigureParamEditorClassArray; editor: TFigureParamEditor; begin FFigureEditors:= nil; FCommonParams:= nil; for i:= 0 to High(FFigures.Content) do begin if FFigures[i].Selected then begin fp:= Figures[i].GetParams; if not firstFound then begin firstFound:= True; SetLength(FCommonParams, Length(fp)); for j:= 0 to High(FCommonParams) do begin SetLength(FCommonParams[j], 1); FCommonParams[j, 0]:= fp[j]; end; end else CrossParams(fp); end; end; editors:= GetFigureEditorClasses; for i:= Low(FCommonParams) to High(FCommonParams) do begin //writeln(Length(FCommonParams)); for j:= 0 to High(editors) do begin editor:= editors[j].Create; if FCommonParams[i,0].ClassType = editor.GetParamType then begin editor.AttachParams(FCommonParams[i]); AddFigureParamEditor(editor); editor.OnParamChange:= @ParamChange; editor.OnHistoryChange:= FOnHistoryChange; //writeln(editor.GetParamType.ClassName); end else editor.Free; end; end; end; procedure TSelectTool.AddFigureParamEditor(AParam: TFigureParamEditor); begin SetLength(FFigureEditors, Length(FFigureEditors)+1); FFigureEditors[High(FFigureEditors)]:= AParam; end; procedure TSelectTool.CrossParams(AParams: TFigureParamArray); var i, j: Integer; IsFound: Boolean; TempParams: array of array of TFigureParam; DiffIndexes: TIntArray; begin for i:= Low(FCommonParams) to High(FCommonParams) do begin IsFound:= false; for j:= Low(AParams) to High(AParams) do begin if FCommonParams[i, 0].ClassType = AParams[j].ClassType then begin IsFound:= true; Push(AParams[j], FCommonParams[i]); end; end; if not IsFound then begin Push(i, DiffIndexes); end; end; SetLength(TempParams, Length(FCommonParams)-Length(DiffIndexes)); j:= Low(TempParams); for i:= Low(FCommonParams) to High(FCommonParams) do begin if IsInArray(i, DiffIndexes) then Continue; TempParams[j]:= FCommonParams[i]; j+= 1; end; FCommonParams:= TempParams; end; procedure TSelectTool.ShowFiguresEditors(AControl: TWinControl); var e: TFigureParamEditor; begin for e in FFigureEditors do e.FillUserInterface(AControl); end; function TSelectTool.GetParams: TParamEditorArray; var i: Integer; begin SetLength(Result, 1); Result[0]:= FSelectBtnE; //SetLength(Result, Length(Result)+Length(FFigureEditors)); for i:= Low(FFigureEditors) to High(FFigureEditors) do begin SetLength(Result, Length(Result)+1); Result[High(Result)]:= FFigureEditors[i]; end; end; procedure TSelectTool.CleanUp; begin FFigures.UnSelectAllFigures; FPaintSpace.PaintBox.Invalidate; FFigureEditors:= nil; FCommonParams:= nil; end; procedure TSelectTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin FFirstPoint:= APoint; FLastPoint:= APoint; FSplitOff:= TRectSplitOffFigure.Create; FSplitOff.Points[0]:= APoint; FSplitOff.Points[1]:= APoint; FFigures.AddFigure(FSplitOff); FIsFirstOnFigure:= false; if FFigures.GetFigure(FFirstPoint) <> nil then FIsFirstOnFigure:= FFigures.GetFigure(FFirstPoint).Selected; end; procedure TSelectTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin if FIsFirstOnFigure then begin FFigures.MoveSelected(APoint-FLastPoint); FLastPoint:= APoint; Exit; end; if ((FFirstPoint - APoint).Length <= CLICK_SIZE) then Exit; FSplitOff.Points[1]:= APoint; end; procedure TSelectTool.MouseUp(APoint: TDoublePoint; AShift: TShiftState); begin FFigures.RemoveLastFigure; if FIsFirstOnFigure then begin FOnHistoryChange; Exit; end; if (FFirstPoint-APoint).Length > CLICK_SIZE then begin if FFirstPoint.X<APoint.X then begin if ssShift in AShift then FFigures.SetSelectionFullRectFigures(FFirstPoint, APoint, @FSelect) else if ssCtrl in AShift then FFigures.SetSelectionFullRectFigures(FFirstPoint, APoint, @FRevers) else begin FFigures.UnSelectAllFigures; FFigures.SetSelectionFullRectFigures(FFirstPoint, APoint, @FSelect) end; end else begin if ssShift in AShift then FFigures.SetSelectionPartRectFigures(FFirstPoint, APoint, @FSelect) else if ssCtrl in AShift then FFigures.SetSelectionPartRectFigures(FFirstPoint, APoint, @FRevers) else begin FFigures.UnSelectAllFigures; FFigures.SetSelectionPartRectFigures(FFirstPoint, APoint, @FSelect) end; end; end else begin if ssShift in AShift then FFigures.SetSelectionFigure(APoint, @FSelect) else if ssCtrl in AShift then FFigures.SetSelectionFigure(APoint, @FRevers) else begin FFigures.UnSelectAllFigures; FFigures.SetSelectionFigure(APoint, @FSelect); end; end; InitFiguresParams; if Assigned(FOnParamsListChange) then FOnParamsListChange; end; constructor THandTool.Create; begin inherited Create; FMetadata.Name:= 'Hand'; FMetadata.Bitmap.LoadFromFile('src/hand_tool.bmp'); end; procedure THandTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin FFirstPoint:= APoint; end; procedure THandTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin with FPaintSpace do begin Position:= Position-(APoint-FFirstPoint); end; end; procedure THandTool.MouseUp(APoint: TDoublePoint; AShift: TShiftState); begin end; constructor TZoomTool.Create; begin inherited Create; FModeE:= TZoomModePEditor.Create; FPowerE:= TZoomPowerPEditor.Create; FMetadata.Name:= 'Zoom'; FMetadata.Bitmap.LoadFromFile('src/zoom_tool.bmp'); end; function TZoomTool.GetParams: TParamEditorArray; begin SetLength(Result, 2); Result[0]:= FPowerE; Result[1]:= FModeE; end; procedure TZoomTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin FFirstPoint:= APoint; if FModeE.Parameter.Value = TZoomModeParam.TZoomModes.zmtlZoomSpace then begin FSplitOff:= TRectSplitOffFigure.Create; FSplitOff.SetPointsLength(2); FSplitOff.Points[0]:= APoint; FFigures.AddFigure(FSplitOff); end; end; procedure TZoomTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin if FModeE.Parameter.Value = TZoomModeParam.TZoomModes.zmtlZoomSpace then begin FSplitOff.Points[1]:= APoint; end; end; procedure TZoomTool.MouseUp(APoint: TDoublePoint; AShift: TShiftState); begin if ssRight in AShift then exit; case FModeE.Parameter.Value of TZoomModeParam.TZoomModes.zmtlZoomOut : FPaintSpace.SetScalePoint(FPaintSpace.Scale-FPowerE.Parameter.Value, APoint); TZoomModeParam.TZoomModes.zmtlZoomIn : FPaintSpace.SetScalePoint(FPaintSpace.Scale+FPowerE.Parameter.Value, APoint); TZoomModeParam.TZoomModes.zmtlZoomSpace : begin if abs(FFirstPoint.X-APoint.X) > abs(FFirstPoint.Y-APoint.Y) then FPaintSpace.Scale:= FPaintSpace.PaintBox.Width/abs(FFirstPoint.X-APoint.X) else FPaintSpace.Scale:= FPaintSpace.PaintBox.Height/abs(FFirstPoint.Y-APoint.Y); FPaintSpace.Position:= GetDoublePoint(min(FFirstPoint.X, APoint.X), min(FFirstPoint.Y, APoint.Y)); FFigures.RemoveLastFigure; end; end; end; procedure TDrawingTool.Finish; var Min, Max: TDoublePoint; begin if FFigure.IsValid then begin FFigures.BakeLastFigure; FFigures.GetBounds(Min, Max); FPaintSpace.SetFiguresBounds(Min, Max); if Assigned(FOnHistoryChange) then FOnHistoryChange; end else FFigures.RemoveLastFigure; end; procedure TDrawingTool.MouseUp(APoint: TDoublePoint; AShift: TShiftState); begin Finish; end; constructor TLineTool.Create; begin inherited; FLineColorE:= TColorPEditor.Create; FLineWidthE:= TLineWidthPEditor.Create; FLineStyleE:= TLineStylePEditor.Create; FMetadata.Name:= 'Line'; FMetadata.Bitmap:= TBitmap.Create; FMetadata.Bitmap.LoadFromFile('src/line_tool.bmp'); end; function TLineTool.GetParams: TParamEditorArray; begin SetLength(Result, 3); Result[0]:= FLineWidthE; Result[1]:= FLineStyleE; Result[2]:= FLineColorE; end; procedure TLineTool.CreateFigure; begin FFigure:= TLineFigure.Create; FFigures.AddFigure(FFigure); end; procedure TLineTool.InitializeFigure(APoint: TDoublePoint); begin FFigure.Points[0]:= APoint; FFigure.Points[1]:= APoint; end; procedure TLineTool.SetFigureParams; var f: TLineFigure; begin f:= TLineFigure(FFigure); f.LineWidth.Value:= FLineWidthE.Parameter.Value; f.LineStyle.Value:= FLineStyleE.Parameter.Value; f.LineColor.Value:= FLineColorE.Parameter.Value; end; procedure TLineTool.SetParamColor(AFigureColors: TFigureColors); begin FLineColorE.Parameter.Value:= AFigureColors.Pen; end; procedure TLineTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin CreateFigure; InitializeFigure(APoint); SetFigureParams; end; procedure TLineTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin FFigure.Points[1]:= APoint; end; procedure TPenTool.InitializeFigure(APoint: TDoublePoint); begin FFigure.SetPointsLength(1); FFigure.Points[0]:= APoint; end; constructor TPenTool.Create; begin inherited Create; FMetadata.Name:= 'Pen'; FMetadata.Bitmap.LoadFromFile('src/pen_tool.bmp'); end; procedure TPenTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin FFigure.IncreasePointsLength; FFigure.Points[High(FFigure.Points)]:= APoint; end; procedure TShapeTool.InitializeFigure(APoint: TDoublePoint); begin FFigure.Points[0]:= APoint; FFigure.Points[1]:= APoint; end; procedure TShapeTool.SetFigureParams; var f: TShapeFigure; begin f:= TShapeFigure(FFigure); f.LineColor.Value:= FLineColorE.Parameter.Value; f.LineWidth.Value:= FLineWidthE.Parameter.Value; f.LineStyle.Value:= FLineStyleE.Parameter.Value; f.ShapeColor.Value:= FShapeColorE.Parameter.Value; f.ShapeStyle.Value:= FShapeStyleE.Parameter.Value; end; constructor TShapeTool.Create; begin inherited; FLineWidthE:= TLineWidthPEditor.Create; FLineStyleE:= TLineStylePEditor.Create; FLineColorE:= TColorPEditor.Create; FShapeColorE:= TColorPEditor.Create; FShapeStyleE:= TShapeStylePEditor.Create; end; function TShapeTool.GetParams: TParamEditorArray; begin SetLength(Result, 5); Result[0]:= FLineWidthE; Result[1]:= FLineStyleE; Result[2]:= FLineColorE; Result[3]:= FShapeStyleE; Result[4]:= FShapeColorE; end; procedure TShapeTool.SetParamColor(AFigureColors: TFigureColors); begin FLineColorE.Parameter.Value:= AFigureColors.Pen; FShapeColorE.Parameter.Value:= AFigureColors.Brush; end; procedure TShapeTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin CreateFigure; InitializeFigure(APoint); SetFigureParams; end; procedure TShapeTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin FFigure.Points[1]:= APoint; end; procedure TEllipseTool.CreateFigure; begin FFigure:= TEllipseFigure.Create; FFigures.AddFigure(FFigure); end; constructor TEllipseTool.Create; begin inherited; FMetadata.Name:= 'Ellipse'; FMetadata.Bitmap.LoadFromFile('src/ellipse_tool.bmp'); end; procedure TRectTool.CreateFigure; begin FFigure:= TRectFigure.Create; FFigures.AddFigure(FFigure); end; constructor TRectTool.Create; begin inherited; FMetadata.Name:= 'Rect'; FMetadata.Bitmap.LoadFromFile('src/rect_tool.bmp'); end; procedure TRegularPolygonTool.CreateFigure; begin FFigure:= TRegularPolygonFigure.Create; FFigure.SetPointsLength(FAngleCountE.Parameter.Value); FFigures.AddFigure(FFigure); end; constructor TRegularPolygonTool.Create; begin inherited; FMetadata.Name:= 'RegularPolygon'; FAngleCountE:= TAngleCountPEditor.Create; FMetadata.Bitmap.LoadFromFile('src/regular_tool.bmp'); FAngleCountE.Parameter.Value:= 3; end; function TRegularPolygonTool.GetParams: TParamEditorArray; begin Result:= inherited GetParams; SetLength(Result, Length(Result)+1); Result[High(Result)]:= FAngleCountE; end; procedure TRegularPolygonTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin CreateFigure; InitializeFigure(APoint); SetFigureParams; FFigure.Points[1]:= APoint; TRegularPolygonFigure(FFigure).AngleCountParam.Value:= FAngleCountE.Parameter.Value; end; procedure TRegularPolygonTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin FFigure.Points[1]:= APoint; end; procedure TRoundedRectTool.CreateFigure; begin FFigure:= TRoundedRectFigure.Create; FFigures.AddFigure(FFigure); end; procedure TRoundedRectTool.SetFigureParams; begin inherited SetFigureParams; TRoundedRectFigure(FFigure).Rounding:= FRoundingE.Parameter.Value; end; constructor TRoundedRectTool.Create; begin inherited; FRoundingE:= TRoundingPEditor.Create; FMetadata.Name:= 'RoundedRect'; FMetadata.Bitmap.LoadFromFile('src/rect_tool.bmp'); end; function TRoundedRectTool.GetParams: TParamEditorArray; begin Result:= inherited GetParams; SetLength(Result, Length(Result)+1); Result[High(Result)]:= FRoundingE; end; procedure TRoundedRectTool.MouseDown(APoint: TDoublePoint; AShift: TShiftState); begin CreateFigure; InitializeFigure(APoint); SetFigureParams; end; procedure TRoundedRectTool.MouseMove(APoint: TDoublePoint; AShift: TShiftState); begin FFigure.Points[1]:= APoint; end; initialization RegisterTool(TSelectTool.Create); RegisterTool(THandTool.Create); RegisterTool(TLineTool.Create); RegisterTool(TPenTool.Create); RegisterTool(TRectTool.Create); RegisterTool(TEllipseTool.Create); RegisterTool(TRegularPolygonTool.Create); RegisterTool(TRoundedRectTool.Create); RegisterTool(TZoomTool.Create); end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. } { Description: related to datetime, used by many units to visually display formatted time eg: 00:00:00 } unit helper_datetime; interface uses sysutils,windows; const UnixStartDate : tdatetime = 25569.0; TENTHOFSEC=100; SECOND=1000; MINUTE=60000; HOUR=3600000; DAY=86400000; SECONDSPERDAY=86400; function UnixToDelphiDateTime(USec:longint):TDateTime; function DelphiDateTimeToUnix(ConvDate:TdateTime):longint; function format_time(secs:integer):string; function DelphiDateTimeSince1900(ConvDate:TdateTime):longint; function time_now:cardinal; function HR2S(hours:single):cardinal; function SEC(seconds:integer):cardinal; function MIN2S(minutes:single):cardinal; function DateTimeToUnixTime(const DateTime: TDateTime): cardinal; function UnixTimeToDateTime(const UnixTime: cardinal): TDateTime; implementation function DateTimeToUnixTime(const DateTime:TDateTime): cardinal; var FileTime:TFileTime; SystemTime:TSystemTime; I:Int64; begin // first convert datetime to Win32 file time DateTimeToSystemTime(DateTime, SystemTime); SystemTimeToFileTime(SystemTime, FileTime); // simple maths to go from Win32 time to Unix time I:=Int64(FileTime.dwHighDateTime) shl 32 + FileTime.dwLowDateTime; Result:=(I - 116444736000000000) div Int64(10000000); end; function UnixTimeToDateTime(const UnixTime: cardinal): TDateTime; var FileTime:TFileTime; SystemTime:TSystemTime; I:Int64; begin // first convert unix time to a Win32 file time I:=Int64(UnixTime) * Int64(10000000) + 116444736000000000; FileTime.dwLowDateTime:=DWORD(I); FileTime.dwHighDateTime:=I shr 32; // now convert to system time FileTimeToSystemTime(FileTime,SystemTime); // and finally convert the system time to TDateTime Result:=SystemTimeToDateTime(SystemTime); end; function format_time(secs:integer):string; var ore,minuti,secondi,variabile:integer; begin if secs>0 then begin if secs<60 then begin ore:=0; minuti:=0; secondi:=secs; end else if secs<3600 then begin ore:=0; minuti:=(secs div 60); secondi:=(secs-((secs div 60)*60)); end else begin ore:=(secs div 3600); variabile:=(secs-((secs div 3600)*3600)); //minuti avanzati minuti:=variabile div 60; secondi:=variabile-((minuti )* 60); end; if ore=0 then result:='' else result:=inttostr(ore)+':'; if ((minuti=0) and (ore=0)) then result:='0:' else begin if minuti<10 then begin if ore=0 then result:=inttostr(minuti)+':' else result:=result+'0'+inttostr(minuti)+':'; end else result:=result+inttostr(minuti)+':'; end; if secondi<10 then result:=result+'0'+inttostr(secondi) else result:=result+inttostr(secondi); end else result:='0:00'; // fake tempo se non ho niente nella var end; function DelphiDateTimeToUnix(ConvDate:TdateTime):longint; // Converts Delphi TDateTime to Unix seconds, // ConvDate = the Date and Time that you want to convert // example: UnixSeconds:=DelphiDateTimeToUnix(Now); begin Result:=round((ConvDate-UnixStartDate)*SECONDSPERDAY); end; function UnixToDelphiDateTime(USec:longint):TDateTime; {Converts Unix seconds to Delphi TDateTime, USec = the Unix Date Time that you want to convert example: DelphiTimeDate:=UnixToDelphiTimeDate(693596);} begin Result:=(Usec/SECONDSPERDAY)+UnixStartDate; end; function time_now:cardinal; begin result:=DelphiDateTimeSince1900(now); end; function HR2S(hours:single):cardinal; begin result:=MIN2S(hours*60); end; function SEC(seconds:integer):cardinal; begin result:=seconds; end; function MIN2S(minutes:single):cardinal; begin result:=round(minutes * 60); end; function DelphiDateTimeSince1900(ConvDate:TdateTime):longint; // Converts Delphi TDateTime to Unix seconds, // ConvDate = the Date and Time that you want to convert // example: UnixSeconds:=DelphiDateTimeToUnix(Now); begin Result:=round((ConvDate-1.5)*86400); end; end.
unit frmexportarlances; {$mode objfpc}{$H+} interface uses {$IFDEF MSWINDOWS} Windows,windirs, {$ENDIF} Classes, SysUtils, FileUtil, DateTimePicker, Forms, Controls, Graphics, Dialogs, StdCtrls, DbCtrls, EditBtn, Buttons, ActnList, DBGrids, ExtCtrls, datGeneral, ZDataset, ZSqlUpdate, db, memds, LSConfig; type { TfmExportarLances } TfmExportarLances = class(TForm) acExportarLances: TAction; ActionList1: TActionList; bbGuardar: TBitBtn; cbMarcarEnviados: TCheckBox; dtFechaIni: TDateTimePicker; dtFechaFin: TDateTimePicker; dedCarpetaArchivo: TDirectoryEdit; dsExpLances: TDataSource; dbgLances: TDBGrid; dsTmp: TDataSource; dsLances: TDataSource; gbDestino: TGroupBox; gbProduccion: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; mdsTmp: TMemDataset; rgFormato: TRadioGroup; rgFiltro: TRadioGroup; zqExpLancescanastos_procesados: TLongintField; zqExpLancescant_trampas: TLargeintField; zqExpLancescentolla_comercial: TLargeintField; zqExpLancescentolla_total: TLargeintField; zqExpLancescomentarios_calado: TStringField; zqExpLancescomentarios_virada: TStringField; zqExpLancesenviado: TSmallintField; zqExpLancesfecha: TDateTimeField; zqExpLancesidlance: TLongintField; zqExpLancesinvestigacion: TStringField; zqExpLanceslat_fin_calado: TFloatField; zqExpLanceslat_fin_virada: TFloatField; zqExpLanceslat_ini_calado: TFloatField; zqExpLanceslat_ini_virada: TFloatField; zqExpLanceslong_fin_calado: TFloatField; zqExpLanceslong_fin_virada: TFloatField; zqExpLanceslong_ini_calado: TFloatField; zqExpLanceslong_ini_virada: TFloatField; zqExpLancesnro_lance: TLongintField; zqExpLancesoperacion: TStringField; zqExpLancesseleccionado: TSmallintField; zqExpLancestrampas_con_fallo: TLargeintField; zqExpLancestrampas_sin_puerta: TLargeintField; zqLances: TZQuery; zqLancescalada: TLongintField; zqLancescanastos_procesados: TLongintField; zqLancescant_trampas_caladas: TLongintField; zqLancescant_trampas_recuperadas: TLongintField; zqLancescluster_por_canasto: TLongintField; zqLancescod_estado_mar: TLongintField; zqLancescomentarios_calado: TStringField; zqLancescomentarios_virada: TStringField; zqLancesdireccion_viento: TLongintField; zqLancesdsc_lance: TStringField; zqLancesdsc_virada: TStringField; zqLancesfecha_fin_calado: TDateField; zqLancesfecha_fin_virada: TDateField; zqLancesfecha_ini_calado: TDateField; zqLancesfecha_ini_virada: TDateField; zqLanceshora_fin_calado: TTimeField; zqLanceshora_fin_virada: TTimeField; zqLanceshora_ini_calado: TTimeField; zqLanceshora_ini_virada: TTimeField; zqLancesidcarnada: TLongintField; zqLancesidlance: TLongintField; zqLancesidlinea: TLongintField; zqLancesidmarea: TLongintField; zqLancesinvestigacion: TSmallintField; zqLanceskg_carnada: TFloatField; zqLanceslat_fin_calado: TFloatField; zqLanceslat_fin_virada: TFloatField; zqLanceslat_ini_calado: TFloatField; zqLanceslat_ini_virada: TFloatField; zqLanceslong_fin_calado: TFloatField; zqLanceslong_fin_virada: TFloatField; zqLanceslong_ini_calado: TFloatField; zqLanceslong_ini_virada: TFloatField; zqLancesnro_boya: TLongintField; zqLancesnro_lance: TLongintField; zqLancesnro_linea: TLongintField; zqLancesnudos_viento: TLongintField; zqLancesprofundidad_fin_calado: TLongintField; zqLancesprofundidad_fin_virada: TLongintField; zqLancesprofundidad_ini_calado: TLongintField; zqLancesprofundidad_ini_virada: TLongintField; zqLancesprospeccion: TSmallintField; zqLancesrumbo_calado: TLongintField; zqLancesvirada: TLongintField; zqExpLances: TZQuery; zqProduccion: TZQuery; zqProduccioncajas_p1: TLargeintField; zqProduccioncajas_p10: TLargeintField; zqProduccioncajas_p2: TLargeintField; zqProduccioncajas_p3: TLargeintField; zqProduccioncajas_p4: TLargeintField; zqProduccioncajas_p5: TLargeintField; zqProduccioncajas_p6: TLargeintField; zqProduccioncajas_p7: TLargeintField; zqProduccioncajas_p8: TLargeintField; zqProduccioncajas_p9: TLargeintField; zqProduccionfecha: TDateField; zqProduccionkilos_p1: TFloatField; zqProduccionkilos_p10: TFloatField; zqProduccionkilos_p2: TFloatField; zqProduccionkilos_p3: TFloatField; zqProduccionkilos_p4: TFloatField; zqProduccionkilos_p5: TFloatField; zqProduccionkilos_p6: TFloatField; zqProduccionkilos_p7: TFloatField; zqProduccionkilos_p8: TFloatField; zqProduccionkilos_p9: TFloatField; zqProduccionp1: TStringField; zqProduccionp10: TStringField; zqProduccionp2: TStringField; zqProduccionp3: TStringField; zqProduccionp4: TStringField; zqProduccionp5: TStringField; zqProduccionp6: TStringField; zqProduccionp7: TStringField; zqProduccionp8: TStringField; zqProduccionp9: TStringField; zqProducciontot_cajas: TLargeintField; zqProducciontot_kilos: TFloatField; zuExpLances: TZUpdateSQL; procedure acExportarLancesExecute(Sender: TObject); procedure ExportarTxt; procedure ExportarExcel; procedure dbgLancesColEnter(Sender: TObject); procedure dblkLanceFinChange(Sender: TObject); procedure dblkLanceIniChange(Sender: TObject); procedure dedCarpetaArchivoAcceptDirectory(Sender: TObject; var Value: String); procedure dedCarpetaArchivoChange(Sender: TObject); procedure dedCarpetaArchivoExit(Sender: TObject); procedure FormShow(Sender: TObject); procedure rgFiltroClick(Sender: TObject); procedure zqExpLancesAfterOpen(DataSet: TDataSet); procedure zqExpLancesBeforeOpen(DataSet: TDataSet); procedure zqLancesBeforeOpen(DataSet: TDataSet); procedure zqProduccionBeforeOpen(DataSet: TDataSet); private { private declarations } Procedure HabilitarAcciones; public { public declarations } end; var fmExportarLances: TfmExportarLances; max_fecha_lance: TDateTime=-1; fecha_ini_prod, fecha_fin_prod:TDateTime; implementation {$R *.lfm} { TfmExportarLances } procedure TfmExportarLances.FormShow(Sender: TObject); var destino:String; begin // destino:= ipsPreferencias.ReadString('carpeta_destino', GetWindowsSpecialDir(CSIDL_PERSONAL)); LSLoadConfig(['destino_archivo_lances'],[destino],[@destino]); {$IFDEF MSWINDOWS} if destino='' then destino:=GetWindowsSpecialDir(CSIDL_PERSONAL); {$ENDIF} dedCarpetaArchivo.Directory := destino; zqLances.Close; zqLances.Open; zqExpLances.Close; zqExpLances.Open; HabilitarAcciones; end; procedure TfmExportarLances.rgFiltroClick(Sender: TObject); begin zqExpLances.Close; zqExpLances.Open; end; procedure TfmExportarLances.zqExpLancesAfterOpen(DataSet: TDataSet); begin fecha_ini_prod:=MaxDateTime; fecha_fin_prod:=MinDateTime; with zqExpLances do begin DisableControls; First; while not EOF do begin if zqExpLancesenviado.AsBoolean=False then begin Edit; zqExpLancesseleccionado.AsBoolean:=True; Post; end; if zqExpLancesoperacion.AsString='Virado' then begin if zqExpLancesfecha.AsDateTime>fecha_fin_prod then fecha_fin_prod:=zqExpLancesfecha.AsDateTime; if zqExpLancesfecha.AsDateTime<fecha_ini_prod then fecha_ini_prod:=zqExpLancesfecha.AsDateTime; end; Next; end; First; if fecha_ini_prod<>MaxDateTime then dtFechaIni.Date:=fecha_ini_prod; if fecha_fin_prod<>MinDateTime then dtFechaFin.Date:=fecha_fin_prod; EnableControls; end; end; procedure TfmExportarLances.zqExpLancesBeforeOpen(DataSet: TDataSet); begin zqExpLances.ParamByName('idmarea').Value:=dmGeneral.IdMareaActiva; zqExpLances.ParamByName('filtro').Value:=rgFiltro.ItemIndex; end; procedure TfmExportarLances.dedCarpetaArchivoChange(Sender: TObject); begin LSSaveConfig(['destino_archivo_lances'],[dedCarpetaArchivo.Directory]); HabilitarAcciones; end; procedure TfmExportarLances.dedCarpetaArchivoExit(Sender: TObject); begin LSSaveConfig(['destino_archivo_lances'],[dedCarpetaArchivo.Directory]); HabilitarAcciones; end; procedure TfmExportarLances.dedCarpetaArchivoAcceptDirectory(Sender: TObject; var Value: String); begin LSSaveConfig(['destino_archivo_lances'],[dedCarpetaArchivo.Directory]); HabilitarAcciones; end; procedure TfmExportarLances.acExportarLancesExecute(Sender: TObject); begin if rgFormato.ItemIndex=0 then ExportarTxt else ExportarExcel; end; procedure TfmExportarLances.ExportarTxt; var s:TStringList; tmp, archivo:string; i:integer; OLD_DC:char; begin if dedCarpetaArchivo.Directory <> '' then begin try OLD_DC:=DecimalSeparator; DecimalSeparator:=','; s:=TStringList.Create; //Creo el encabezado s.Add(Trim('Marea: '+dmGeneral.zqMareaActivaMareaStr.AsString)); s.Add(Trim('Observador: '+dmGeneral.zqMareaActivaobservador.AsString)); s.Add(''); s.Add('Lance;Linea investigacion;Actividad;Trampas;Rotas o abiertas;Sin puerta o anulada;Fecha/hora;Lat. calado inicial;Long. calado inicial;Lat. calado final;Long. calado final;Lat. virado inicial;Long. virado inicial;Lat. virado final;Long. virado final;Captura total;Captura comercial;Jaulas Prod;Comentarios Calado;Comentarios Virada'); with zqExpLances do begin max_fecha_lance:=-1; DisableControls; First; if RecordCount>0 then begin while not EOF do begin if zqExpLancesseleccionado.AsBoolean=True then begin if zqExpLancesfecha.AsDateTime>max_fecha_lance then max_fecha_lance:=zqExpLancesfecha.AsDateTime; //Concateno el valor de todos los campos (menos el último, que lo proceso aparte para que no //quede con un ";" final //Empiezo en el campo [3] porque el [0] es idlance, el [1] es la marca de "Seleccionado", // y el [2] es la marca de "Enviado" tmp:=''; for i:=3 to Fields.Count-2 do begin tmp:=tmp+Fields[i].AsString+';'; end; tmp:=tmp+Fields[i+1].AsString; s.Add(Trim(tmp)); end; Next; end; end else begin MessageDlg('No se encontró información de lances para exportar', mtInformation, [mbOK],0) end; First; EnableControls; end; //Agrego los datos de producción with zqProduccion do begin Close; Open; First; if RecordCount>0 then begin //Armo la línea de encabezado s.Add(''); s.Add('Producción:'); tmp:='Fecha;'; for i:=1 to 10 do begin if FieldByName('p'+IntToStr(i)).AsString<>'' then begin tmp:=tmp+'Cajas '+FieldByName('p'+IntToStr(i)).AsString+';'; tmp:=tmp+'Kilos '+FieldByName('p'+IntToStr(i)).AsString+';'; end; end; tmp:=tmp+'Total Cajas;Total Kilos'; s.Add(tmp); while not EOF do begin tmp:=FieldByName('fecha').AsString+';'; //Agrego los valores siempre que exista el producto for i:=1 to 10 do begin if FieldByName('p'+IntToStr(i)).AsString<>'' then begin tmp:=tmp+FieldByName('cajas_p'+IntToStr(i)).AsString+';'; tmp:=tmp+FieldByName('kilos_p'+IntToStr(i)).AsString+';'; end; end; tmp:=tmp+FieldByName('tot_cajas').AsString+';'; tmp:=tmp+FieldByName('tot_kilos').AsString; s.Add(Trim(tmp)); Next; end; end else begin MessageDlg('No se encontró información de producción para exportar', mtInformation, [mbOK],0) end; end; if max_fecha_lance=-1 then archivo:=dedCarpetaArchivo.Directory+DirectorySeparator+FormatDateTime('YYYYmmdd',Date)+'.txt' else archivo:=dedCarpetaArchivo.Directory+DirectorySeparator+FormatDateTime('YYYYmmdd',max_fecha_lance)+'.txt'; if (not FileExistsUTF8(archivo)) or (MessageDlg('El archivo '+archivo+' ya existe. ¿Desea reemplazarlo?', mtConfirmation, [mbYes, mbNo],0) = mrYes) then begin s.SaveToFile(archivo); if cbMarcarEnviados.Checked then zqExpLances.ApplyUpdates; zqExpLances.Close; zqExpLances.Open; if MessageDlg('El informe de lances se ha generado correctamente y se ha guardado en '+archivo+'. ¿Desea visualizar el contenido del archivo?', mtConfirmation, [mbYes, mbNo],0) = mrYes then begin {$IFDEF MSWINDOWS} ShellExecute(Handle, 'open', PChar(archivo), nil, nil, SW_SHOWNORMAL) {$ENDIF} {$IFDEF UNIX} Shell(format('gv %s',[ExpandFileNameUTF8(archivo)])); {$ENDIF} end; end; finally DecimalSeparator:=OLD_DC; s.Free; end; end; end; procedure TfmExportarLances.ExportarExcel; begin end; procedure TfmExportarLances.dbgLancesColEnter(Sender: TObject); begin //Sólo se permite editar la columna 0 (Seleccionado) if dbgLances.SelectedIndex<>0 then dbgLances.SelectedIndex := 0; end; procedure TfmExportarLances.dblkLanceFinChange(Sender: TObject); begin HabilitarAcciones; end; procedure TfmExportarLances.dblkLanceIniChange(Sender: TObject); begin HabilitarAcciones; end; procedure TfmExportarLances.zqLancesBeforeOpen(DataSet: TDataSet); begin zqLances.ParamByName('idmarea').Value:=dmGeneral.IdMareaActiva; end; procedure TfmExportarLances.zqProduccionBeforeOpen(DataSet: TDataSet); begin zqProduccion.ParamByName('idmarea').Value:=dmGeneral.IdMareaActiva; zqProduccion.ParamByName('fecha_ini').AsDate:=dtFechaIni.Date; zqProduccion.ParamByName('fecha_fin').AsDate:=dtFechaFin.Date; end; procedure TfmExportarLances.HabilitarAcciones; begin acExportarLances.Enabled:=(dedCarpetaArchivo.Directory<>''); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Scene3D.Renderer.Passes.CascadedShadowMapRenderPass; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application, PasVulkan.FrameGraph, PasVulkan.Scene3D, PasVulkan.Scene3D.Renderer.Globals, PasVulkan.Scene3D.Renderer, PasVulkan.Scene3D.Renderer.Instance, PasVulkan.Scene3D.Renderer.SkyBox; type { TpvScene3DRendererPassesCascadedShadowMapRenderPass } TpvScene3DRendererPassesCascadedShadowMapRenderPass=class(TpvFrameGraph.TRenderPass) private fOnSetRenderPassResourcesDone:boolean; procedure OnSetRenderPassResources(const aCommandBuffer:TpvVulkanCommandBuffer; const aPipelineLayout:TpvVulkanPipelineLayout; const aRenderPassIndex:TpvSizeInt; const aPreviousInFlightFrameIndex:TpvSizeInt; const aInFlightFrameIndex:TpvSizeInt); private fVulkanRenderPass:TpvVulkanRenderPass; fInstance:TpvScene3DRendererInstance; fResourceDepth:TpvFrameGraph.TPass.TUsedImageResource; fMeshVertexShaderModule:TpvVulkanShaderModule; fMeshFragmentShaderModule:TpvVulkanShaderModule; fMeshMaskedFragmentShaderModule:TpvVulkanShaderModule; fVulkanPipelineShaderStageMeshVertex:TpvVulkanPipelineShaderStage; fVulkanPipelineShaderStageMeshFragment:TpvVulkanPipelineShaderStage; fVulkanPipelineShaderStageMeshMaskedFragment:TpvVulkanPipelineShaderStage; fVulkanGraphicsPipelines:array[TpvScene3D.TMaterial.TAlphaMode] of TpvScene3D.TGraphicsPipelines; fVulkanPipelineLayout:TpvVulkanPipelineLayout; public constructor Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); reintroduce; destructor Destroy; override; procedure AcquirePersistentResources; override; procedure ReleasePersistentResources; override; procedure AcquireVolatileResources; override; procedure ReleaseVolatileResources; override; procedure Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); override; procedure Execute(const aCommandBuffer:TpvVulkanCommandBuffer;const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); override; end; implementation { TpvScene3DRendererPassesCascadedShadowMapRenderPass } constructor TpvScene3DRendererPassesCascadedShadowMapRenderPass.Create(const aFrameGraph:TpvFrameGraph;const aInstance:TpvScene3DRendererInstance); var Index:TpvSizeInt; begin inherited Create(aFrameGraph); fInstance:=aInstance; Name:='CascadedShadowMapRenderPass'; MultiviewMask:=0; for Index:=0 to TpvScene3DRendererInstance.CountCascadedShadowMapCascades-1 do begin MultiviewMask:=MultiviewMask or (1 shl Index); end; Queue:=aFrameGraph.UniversalQueue; Size:=TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute, fInstance.CascadedShadowMapWidth, fInstance.CascadedShadowMapHeight, 1.0, TpvScene3DRendererInstance.CountCascadedShadowMapCascades); case fInstance.Renderer.ShadowMode of TpvScene3DRendererShadowMode.MSM:begin if fInstance.Renderer.ShadowMapSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT) then begin fResourceDepth:=AddImageDepthOutput('resourcetype_cascadedshadowmap_depth', 'resource_cascadedshadowmap_single_depth', VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear, TpvVector4.InlineableCreate(1.0,1.0,1.0,1.0)), [TpvFrameGraph.TResourceTransition.TFlag.Attachment] ); end else begin fResourceDepth:=AddImageDepthOutput('resourcetype_cascadedshadowmap_msaa_depth', 'resource_cascadedshadowmap_msaa_depth', VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear, TpvVector4.InlineableCreate(1.0,1.0,1.0,1.0)), [TpvFrameGraph.TResourceTransition.TFlag.Attachment] ); end; end else begin fResourceDepth:=AddImageDepthOutput('resourcetype_cascadedshadowmap_data', 'resource_cascadedshadowmap_data_final', VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, TpvFrameGraph.TLoadOp.Create(TpvFrameGraph.TLoadOp.TKind.Clear, TpvVector4.InlineableCreate(1.0,1.0,1.0,1.0)), [TpvFrameGraph.TResourceTransition.TFlag.Attachment] ); end; end; end; destructor TpvScene3DRendererPassesCascadedShadowMapRenderPass.Destroy; begin inherited Destroy; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.AcquirePersistentResources; var InFlightFrameIndex:TpvSizeInt; Stream:TStream; begin inherited AcquirePersistentResources; Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_vert.spv'); try fMeshVertexShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream); finally Stream.Free; end; Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_depth_frag.spv'); try fMeshFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream); finally Stream.Free; end; if fInstance.Renderer.UseDemote then begin Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_depth_alphatest_demote_frag.spv'); end else if fInstance.Renderer.UseNoDiscard then begin Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_depth_alphatest_nodiscard_frag.spv'); end else begin Stream:=pvScene3DShaderVirtualFileSystem.GetFile('mesh_'+fInstance.Renderer.MeshFragTypeName+'_depth_alphatest_frag.spv'); end; try fMeshMaskedFragmentShaderModule:=TpvVulkanShaderModule.Create(fInstance.Renderer.VulkanDevice,Stream); finally Stream.Free; end; fVulkanPipelineShaderStageMeshVertex:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_VERTEX_BIT,fMeshVertexShaderModule,'main'); fVulkanPipelineShaderStageMeshFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fMeshFragmentShaderModule,'main'); fVulkanPipelineShaderStageMeshMaskedFragment:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_FRAGMENT_BIT,fMeshMaskedFragmentShaderModule,'main'); fVulkanPipelineLayout:=TpvVulkanPipelineLayout.Create(fInstance.Renderer.VulkanDevice); fVulkanPipelineLayout.AddPushConstantRange(TVkShaderStageFlags(VK_SHADER_STAGE_VERTEX_BIT),0,SizeOf(TpvScene3D.TVertexStagePushConstants)); fVulkanPipelineLayout.AddDescriptorSetLayout(fInstance.Renderer.Scene3D.GlobalVulkanDescriptorSetLayout); fVulkanPipelineLayout.Initialize; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.ReleasePersistentResources; var InFlightFrameIndex:TpvSizeInt; begin FreeAndNil(fVulkanPipelineLayout); FreeAndNil(fVulkanPipelineShaderStageMeshVertex); FreeAndNil(fVulkanPipelineShaderStageMeshFragment); FreeAndNil(fVulkanPipelineShaderStageMeshMaskedFragment); FreeAndNil(fMeshVertexShaderModule); FreeAndNil(fMeshFragmentShaderModule); FreeAndNil(fMeshMaskedFragmentShaderModule); inherited ReleasePersistentResources; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.AcquireVolatileResources; var AlphaMode:TpvScene3D.TMaterial.TAlphaMode; PrimitiveTopology:TpvScene3D.TPrimitiveTopology; FaceCullingMode:TpvScene3D.TFaceCullingMode; VulkanGraphicsPipeline:TpvVulkanGraphicsPipeline; begin inherited AcquireVolatileResources; fVulkanRenderPass:=VulkanRenderPass; for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin FreeAndNil(fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]); end; end; end; for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin VulkanGraphicsPipeline:=TpvVulkanGraphicsPipeline.Create(fInstance.Renderer.VulkanDevice, fInstance.Renderer.VulkanPipelineCache, 0, [], fVulkanPipelineLayout, fVulkanRenderPass, VulkanRenderPassSubpassIndex, nil, 0); try VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshVertex); if AlphaMode=TpvScene3D.TMaterial.TAlphaMode.Mask then begin VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshMaskedFragment); end else begin VulkanGraphicsPipeline.AddStage(fVulkanPipelineShaderStageMeshFragment); end; VulkanGraphicsPipeline.InputAssemblyState.Topology:=TVkPrimitiveTopology(PrimitiveTopology); VulkanGraphicsPipeline.InputAssemblyState.PrimitiveRestartEnable:=false; fInstance.Renderer.Scene3D.InitializeGraphicsPipeline(VulkanGraphicsPipeline); VulkanGraphicsPipeline.ViewPortState.AddViewPort(0.0,0.0,fInstance.CascadedShadowMapWidth,fInstance.CascadedShadowMapHeight,0.0,1.0); VulkanGraphicsPipeline.ViewPortState.AddScissor(0,0,fInstance.CascadedShadowMapWidth,fInstance.CascadedShadowMapHeight); VulkanGraphicsPipeline.RasterizationState.DepthClampEnable:=false; VulkanGraphicsPipeline.RasterizationState.RasterizerDiscardEnable:=false; VulkanGraphicsPipeline.RasterizationState.PolygonMode:=VK_POLYGON_MODE_FILL; case FaceCullingMode of TpvScene3D.TFaceCullingMode.Normal:begin VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_BACK_BIT); VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_CLOCKWISE; end; TpvScene3D.TFaceCullingMode.Inversed:begin VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_BACK_BIT); VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_COUNTER_CLOCKWISE; end; else begin VulkanGraphicsPipeline.RasterizationState.CullMode:=TVkCullModeFlags(VK_CULL_MODE_NONE); VulkanGraphicsPipeline.RasterizationState.FrontFace:=VK_FRONT_FACE_CLOCKWISE; end; end; if fInstance.Renderer.ShadowMode=TpvScene3DRendererShadowMode.MSM then begin // For MSM we are using no depth bias at all VulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=false; VulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.0; VulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0; VulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=0.0; end else begin VulkanGraphicsPipeline.RasterizationState.DepthBiasEnable:=true; VulkanGraphicsPipeline.RasterizationState.DepthBiasConstantFactor:=0.5; // Constant bias in depth-resolution units by which shadows are moved away from the light. The value of 0.5 is used to round depth values up. VulkanGraphicsPipeline.RasterizationState.DepthBiasClamp:=0.0; VulkanGraphicsPipeline.RasterizationState.DepthBiasSlopeFactor:=2.0; // Bias based on the change in depth in depth-resolution units by which shadows are moved away from the light. The value of 2.0 works well with PCF and DPCF. end; VulkanGraphicsPipeline.RasterizationState.LineWidth:=1.0; VulkanGraphicsPipeline.MultisampleState.RasterizationSamples:=fInstance.Renderer.ShadowMapSampleCountFlagBits; VulkanGraphicsPipeline.MultisampleState.SampleShadingEnable:=false; VulkanGraphicsPipeline.MultisampleState.MinSampleShading:=0.0; VulkanGraphicsPipeline.MultisampleState.CountSampleMasks:=0; VulkanGraphicsPipeline.MultisampleState.AlphaToCoverageEnable:=false; VulkanGraphicsPipeline.MultisampleState.AlphaToOneEnable:=false; VulkanGraphicsPipeline.ColorBlendState.LogicOpEnable:=false; VulkanGraphicsPipeline.ColorBlendState.LogicOp:=VK_LOGIC_OP_COPY; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[0]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[1]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[2]:=0.0; VulkanGraphicsPipeline.ColorBlendState.BlendConstants[3]:=0.0; if AlphaMode=TpvScene3D.TMaterial.TAlphaMode.Blend then begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT)); end else begin VulkanGraphicsPipeline.ColorBlendState.AddColorBlendAttachmentState(false, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, VK_BLEND_FACTOR_ZERO, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, TVkColorComponentFlags(VK_COLOR_COMPONENT_R_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_G_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_B_BIT) or TVkColorComponentFlags(VK_COLOR_COMPONENT_A_BIT)); end; VulkanGraphicsPipeline.DepthStencilState.DepthTestEnable:=true; VulkanGraphicsPipeline.DepthStencilState.DepthWriteEnable:=true; //AlphaMode<>TpvScene3D.TMaterial.TAlphaMode.Blend; VulkanGraphicsPipeline.DepthStencilState.DepthCompareOp:=VK_COMPARE_OP_LESS_OR_EQUAL; VulkanGraphicsPipeline.DepthStencilState.DepthBoundsTestEnable:=false; VulkanGraphicsPipeline.DepthStencilState.StencilTestEnable:=false; VulkanGraphicsPipeline.Initialize; VulkanGraphicsPipeline.FreeMemory; finally fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]:=VulkanGraphicsPipeline; end; end; end; end; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.ReleaseVolatileResources; var AlphaMode:TpvScene3D.TMaterial.TAlphaMode; PrimitiveTopology:TpvScene3D.TPrimitiveTopology; FaceCullingMode:TpvScene3D.TFaceCullingMode; begin for AlphaMode:=Low(TpvScene3D.TMaterial.TAlphaMode) to High(TpvScene3D.TMaterial.TAlphaMode) do begin for PrimitiveTopology:=Low(TpvScene3D.TPrimitiveTopology) to High(TpvScene3D.TPrimitiveTopology) do begin for FaceCullingMode:=Low(TpvScene3D.TFaceCullingMode) to High(TpvScene3D.TFaceCullingMode) do begin FreeAndNil(fVulkanGraphicsPipelines[AlphaMode,PrimitiveTopology,FaceCullingMode]); end; end; end; inherited ReleaseVolatileResources; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.Update(const aUpdateInFlightFrameIndex,aUpdateFrameIndex:TpvSizeInt); begin inherited Update(aUpdateInFlightFrameIndex,aUpdateFrameIndex); end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.OnSetRenderPassResources(const aCommandBuffer:TpvVulkanCommandBuffer; const aPipelineLayout:TpvVulkanPipelineLayout; const aRenderPassIndex:TpvSizeInt; const aPreviousInFlightFrameIndex:TpvSizeInt; const aInFlightFrameIndex:TpvSizeInt); begin if not fOnSetRenderPassResourcesDone then begin fOnSetRenderPassResourcesDone:=true; end; end; procedure TpvScene3DRendererPassesCascadedShadowMapRenderPass.Execute(const aCommandBuffer:TpvVulkanCommandBuffer; const aInFlightFrameIndex,aFrameIndex:TpvSizeInt); var InFlightFrameState:TpvScene3DRendererInstance.PInFlightFrameState; begin inherited Execute(aCommandBuffer,aInFlightFrameIndex,aFrameIndex); InFlightFrameState:=@fInstance.InFlightFrameStates^[aInFlightFrameIndex]; if InFlightFrameState^.Ready then begin fOnSetRenderPassResourcesDone:=false; if fInstance.Renderer.ShadowMode<>TpvScene3DRendererShadowMode.None then begin fInstance.Renderer.Scene3D.Draw(fVulkanGraphicsPipelines[TpvScene3D.TMaterial.TAlphaMode.Opaque], -1, aInFlightFrameIndex, InFlightFrameState^.CascadedShadowMapRenderPassIndex, InFlightFrameState^.CascadedShadowMapViewIndex, InFlightFrameState^.CountCascadedShadowMapViews, FrameGraph.DrawFrameIndex, aCommandBuffer, fVulkanPipelineLayout, OnSetRenderPassResources, [TpvScene3D.TMaterial.TAlphaMode.Opaque]); fInstance.Renderer.Scene3D.Draw(fVulkanGraphicsPipelines[TpvScene3D.TMaterial.TAlphaMode.Mask], -1, aInFlightFrameIndex, InFlightFrameState^.CascadedShadowMapRenderPassIndex, InFlightFrameState^.CascadedShadowMapViewIndex, InFlightFrameState^.CountCascadedShadowMapViews, FrameGraph.DrawFrameIndex, aCommandBuffer, fVulkanPipelineLayout, OnSetRenderPassResources, [TpvScene3D.TMaterial.TAlphaMode.Mask]); { fInstance.Renderer.Scene3D.Draw(fVulkanGraphicsPipelines[TpvScene3D.TMaterial.TAlphaMode.Blend], -1, aInFlightFrameIndex, InFlightFrameState^.CascadedShadowMapRenderPassIndex, InFlightFrameState^.CascadedShadowMapViewIndex, InFlightFrameState^.CountCascadedShadowMapViews, fFrameGraph.DrawFrameIndex, aCommandBuffer, fVulkanPipelineLayout, OnSetRenderPassResources, [TpvScene3D.TMaterial.TAlphaMode.Blend]);} end; end; end; end.
unit Utils.IntegerArray; interface uses System.SysUtils, System.Generics.Defaults, System.Generics.Collections; type TIntegerArray = TArray<Integer>; TIntegerArrayHelper = record helper for TIntegerArray public procedure Sort(); function Length: Integer; function GetSorted(): TIntegerArray; function GetDistinctArray(): TIntegerArray; end; implementation function TIntegerArrayHelper.GetDistinctArray: TIntegerArray; var arr: TIntegerArray; idx: Integer; prevValue: Integer; destIdx: Integer; begin arr := self.GetSorted(); SetLength(Result, arr.Length); prevValue := -MaxInt; destIdx:=0; for idx := 0 to High(arr) do if prevValue < arr[idx] then begin prevValue := arr[idx]; Result[destIdx] := arr[idx]; inc(destIdx); end; SetLength(Result,destIdx); end; function TIntegerArrayHelper.GetSorted: TIntegerArray; begin // ---- Clone array to Result ---- SetLength(Result, self.Length()); Move(self[0], Result[0], self.Length() * sizeOf(Integer)); // ----- ---- TArray.Sort<Integer>(Result, TDelegatedComparer<Integer>.Construct( function(const Left, Right: Integer): Integer begin Result := TComparer<Integer>.Default.Compare(Left, Right); end)); end; function TIntegerArrayHelper.Length: Integer; begin Result := System.Length(self); end; procedure TIntegerArrayHelper.Sort; begin TArray.Sort<Integer>(self, TDelegatedComparer<Integer>.Construct( function(const Left, Right: Integer): Integer begin Result := TComparer<Integer>.Default.Compare(Left, Right); end)); end; end.
program SnakeGame; {$modeSwitch advancedRecords} uses Crt; type type_food = record Point:integer; ID:integer; Icon:char; Color:integer; end; const (* Map *) MAP_SIZE = 30; WALL = 5; NOTHING = 0; GAME_COLOR = 11; (* Wall Icon *) WALL_HORIZONTAL_TOP = '▄'; WALL_HORIZONTAL_BOTTOM = '▀'; WALL_VERTICAL = '▒'; (* Movimentation *) time_delay = 100; UP = -1; DOWN = -2; RIGHT = -3; LEFT = -4; (* Body Icon *) BODY_HORIZONTAL = '═'; BODY_VERTICAL = '║'; BODY_UPRIGHT = '╔'; BODY_UPLEFT = '╗'; BODY_DOWNRIGHT = '╚'; BODY_DOWNLEFT = '╝'; BODY_COLOR = WHITE; (* Food *) (* See section Constant record *) (* https://wiki.freepascal.org/Record *) (* FOOD ID Start in 301 *) FOOD: array of type_food = ( (* The first food has to be a positive point food *) (point: 1;ID: 301;Icon:'@';Color:GREEN), (point: -1;ID: 302;Icon:'%';Color:RED), (point: -1;ID: 304;Icon:'*';Color:RED) ); type type_coord = record lin,col:integer; end; type_game = record snake: record head,tail:type_coord; end; map: array [1..MAP_SIZE,1..MAP_SIZE] of integer; score:integer; end; procedure change_score(var game:type_game; x:integer); (* Sum x to the score. X can be either negative or positive *) begin game.score:=game.score+x; end; function RandomFreeSpace(var game:type_game):type_coord; begin RandomFreeSpace.lin:=random(MAP_SIZE)+1; RandomFreeSpace.col:=random(MAP_SIZE)+1; while game.map[RandomFreeSpace.lin,RandomFreeSpace.col] <> NOTHING do begin RandomFreeSpace.lin:=random(MAP_SIZE)+1; RandomFreeSpace.col:=random(MAP_SIZE)+1; end; end; procedure create_food(var game:type_game; CreatePosFood:boolean); (* Create a new food in a random place *) (* IF CreatePosFood = TRUE then the program will be forced *) (* to create a positive food *) var i:integer; Coord:type_coord; begin if CreatePosFood then begin (* Create a random positive food*) Coord:=RandomFreeSpace(game); i:=random(length(FOOD)); while FOOD[i].POINT < 0 do i:=random(length(FOOD)); game.map[Coord.lin,Coord.col]:=FOOD[i].ID; end; if random(5) <=2 then begin (* Create a random positive food*) Coord:=RandomFreeSpace(game); i:=random(length(FOOD)); while FOOD[i].POINT > 0 do i:=random(length(FOOD)); game.map[Coord.lin,Coord.col]:=FOOD[i].ID; end; end; function next_position(var game:type_game; action,lin,col:integer):type_coord; (* Calculate the next position if the action is executed *) begin case action of UP:begin next_position.lin:=lin-1; next_position.col:=col; end; DOWN:begin next_position.lin:=lin+1; next_position.col:=col; end; RIGHT:begin next_position.lin:=lin; next_position.col:=col+1; end; LEFT:begin next_position.lin:=lin; next_position.col:=col-1; end; end; end; function ValidAction(var game:type_game; action,lin,col:integer):boolean; (* Verify if the action is invalid like the snake turn off in him-self *) var x:type_coord; begin ValidAction:=true; if (game.map[lin,col]<=-1)and(game.map[lin,col]<>WALL) then begin x:=next_position(game,game.map[lin,col],lin,col); if (x.lin = game.snake.head.lin)and(x.col = game.snake.head.col) then ValidAction:=false; end; end; procedure increase_body(var game:type_game; nex_pos:type_coord; action:integer); begin game.map[game.snake.head.lin,game.snake.head.col]:=action;(* this body part will point to the new position of the body *) game.map[nex_pos.lin,nex_pos.col]:=action;(*Create a new Head *) game.snake.head:=nex_pos; end; procedure decrease_body(var game:type_game); var action:integer; begin action:=game.map[game.snake.tail.lin,game.snake.tail.col];(* Get where the next part of the body is*) game.map[game.snake.tail.lin,game.snake.tail.col]:=NOTHING; game.snake.tail:=next_position(game,action,game.snake.tail.lin,game.snake.tail.col); end; procedure move_snake(var game:type_game; nex_pos:type_coord; action:integer); begin (*Create a new head *) increase_body(game,nex_pos,action); action:=game.map[game.snake.tail.lin,game.snake.tail.col];(* Get where the next part of the body is*) game.map[game.snake.tail.lin,game.snake.tail.col]:=NOTHING; game.snake.tail:=next_position(game,action,game.snake.tail.lin,game.snake.tail.col); end; procedure ate_food(var game:type_game; id_food,action:integer; nex_pos:type_coord); var i:integer; begin i:=0; while FOOD[i].ID <> id_food do i:=i+1; change_score(game,FOOD[I].POINT); if FOOD[i].POINT > 0 then begin (* The snake gain a point and increase *) increase_body(game,nex_pos,action); create_food(game,TRUE); end else begin create_food(game,FALSE); decrease_body(game); game.map[nex_pos.lin,nex_pos.col]:=NOTHING; (* The snake has to be moved, otherwise, the player *) (* will have the impression of the snake stop for a moment *) move_snake(game,nex_pos,action); end; end; function aply_action(var game:type_game; action:integer):boolean; (* Return FALSE if the game end *) (* Return TRUE if the game continue *) var nex_pos:type_coord; map_element:integer; begin aply_action:=TRUE; (* Calculate the next position to test if the move is valid *) nex_pos:=next_position(game,action,game.snake.head.lin,game.snake.head.col); if ValidAction(game,action,nex_pos.lin,nex_pos.col) then begin map_element:=game.map[nex_pos.lin,nex_pos.col]; if map_element = WALL then aply_action:=FALSE else if (map_element>=-4)and(map_element <=-1) then aply_action:=FALSE else if map_element>=301 then (* It is a food *) begin ate_food(game,map_element,action,nex_pos); end else move_snake(game,nex_pos,action); end; end; procedure initializing_game(var game:type_game); var i,j:integer; begin with game do begin score:=0; snake.head.lin:= MAP_SIZE div 2; snake.head.col:= MAP_SIZE div 2; snake.tail.lin:= (MAP_SIZE div 2); snake.tail.col:= (MAP_SIZE div 2)-1; for i:=1 to MAP_SIZE do for j:=1 to MAP_SIZE do if (j=1) or (j=MAP_SIZE) then map[i,j]:=WALL else if (i=1) or (i=MAP_SIZE) then map[i,j]:=WALL else map[i,j]:=NOTHING; map[snake.head.lin,snake.head.col]:=UP; map[snake.tail.lin,snake.tail.col]:=RIGHT; end; end; procedure print_snake(var game:type_game; i,j:integer); begin with game do begin textcolor(BODY_COLOR); if (i=snake.head.lin)and(j=snake.head.col) then write('¤') (* Verify if have to print the corners of the body *) else if ((map[i,j]=LEFT)and(map[i+1,j]=UP))or((map[i,j]=DOWN)and(map[i,j-1]=RIGHT))then write(BODY_UPLEFT) else if ((map[i,j]=RIGHT)and(map[i+1,j]=UP))or((map[i,j]=DOWN)and(map[i,j+1]=LEFT))then write(BODY_UPRIGHT) else if (map[i,j]=UP)and(map[i,j-1]=RIGHT)or((map[i,j]=LEFT)and(map[i-1,j]=DOWN))then write(BODY_DOWNLEFT) else if (map[i,j]=RIGHT)and(map[i-1,j]=DOWN)or((map[i,j]=UP)and(map[i,j+1]=LEFT))then write(BODY_DOWNRIGHT) else (* Print horizontal/vertical parts *) case game.map[i,j] of UP:write(BODY_VERTICAL); DOWN:write(BODY_VERTICAL); LEFT:write(BODY_HORIZONTAL); RIGHT:write(BODY_HORIZONTAL); end; textcolor(GAME_COLOR); end; end; procedure print_elements(var game:type_game; i,j:integer); (* Print elements of the map, like walls, foods, etc *) var k:integer; begin case game.map[i,j] of NOTHING:write(' '); WALL:begin if i = 1 then write(WALL_HORIZONTAL_TOP) else if i = MAP_SIZE then write(WALL_HORIZONTAL_BOTTOM) else write(WALL_VERTICAL); end else begin k:=0; while FOOD[k].ID <> game.map[i,j] do k:=k+1; textcolor(FOOD[k].COLOR); write(FOOD[k].ICON); textcolor(GAME_COLOR); end; end; end; procedure print_map(var game:type_game); var i,j:integer; begin for i:=1 to MAP_SIZE do begin for j:=1 to MAP_SIZE do begin if game.map[i,j]<0 then print_snake(game,i,j) else print_elements(game,i,j); end; writeln; end; end; procedure print_rules(); begin writeln; write('Eat '); textcolor(GREEN); write('Green Food '); textColor(GAME_COLOR); write('to earn points and make the snake longer.'); writeln; write('Avoid '); textcolor(RED); write('Red Food '); textColor(GAME_COLOR); write(', otherwise, you will lose points and make the snake shorter.'); writeln; writeln('Use the arrow keys to move.'); end; var game:type_game; game_continue:boolean; ch:char; begin randomize; ClrScr; textColor(GAME_COLOR); initializing_game(game); create_food(game,TRUE); print_map(game); writeln('Press any key to start'); writeln; print_rules(); repeat until KeyPressed; game_continue:=TRUE; repeat ClrScr; writeln('SCORE: ',game.score); print_map(game); Delay(time_delay); if keypressed then begin ch:=ReadKey; case ch of #0:begin ch:=ReadKey; case ch of #72:game_continue:=aply_action(game,UP); #80:game_continue:=aply_action(game,DOWN); #75:game_continue:=aply_action(game,LEFT); #77:game_continue:=aply_action(game,RIGHT); end; end; #27:game_continue:=true; end; end else (* Keep the snake moving if the player does not press a key *) game_continue:=aply_action(game,game.map[game.snake.head.lin,game.snake.head.col]); if game.score = -1 then game_continue:=false; while keypressed do ch:=ReadKey; until game_continue = false; end.
unit HTTPResponse; interface uses SysUtils; type THTTPStatusCode = (Ok = 200, Created = 201, NoContent = 204, BadRequest = 400, NotFound = 404, Conflict = 409, UnprocessableEntity = 422); THTTPContentType = (PlainText, HTML, JSON); THTTPEncoding = (Ansi, UTF8); IHTTPResponse = interface ['{DE03B0CF-B499-4FB4-9CB1-706A4798E2BC}'] function Content: String; function ContentType: THTTPContentType; function Encoding: THTTPEncoding; function StatusCode: THTTPStatusCode; function StatusText: String; end; THTTPResponse = class sealed(TInterfacedObject, IHTTPResponse) strict private _Content: String; _ContentType: THTTPContentType; _Encoding: THTTPEncoding; _StatusText: String; _StatusCode: THTTPStatusCode; public function Content: String; function ContentType: THTTPContentType; function Encoding: THTTPEncoding; function StatusCode: THTTPStatusCode; function StatusText: String; constructor Create(const Content: String; const ContentType: THTTPContentType; const Encoding: THTTPEncoding; const StatusCode: THTTPStatusCode; const StatusText: String); class function New(const Content: String; const ContentType: THTTPContentType; const Encoding: THTTPEncoding; const StatusCode: THTTPStatusCode; const StatusText: String = ''): IHTTPResponse; end; THTTPJSONResponse = class sealed(TInterfacedObject, IHTTPResponse) strict private _Response: IHTTPResponse; public function Content: String; function ContentType: THTTPContentType; function Encoding: THTTPEncoding; function StatusCode: THTTPStatusCode; function StatusText: String; constructor Create(const Content: String; const StatusCode: THTTPStatusCode; const StatusText: String); class function New(const Content: String; const StatusCode: THTTPStatusCode; const StatusText: String = '') : IHTTPResponse; end; implementation function THTTPResponse.StatusCode: THTTPStatusCode; begin Result := _StatusCode; end; function THTTPResponse.StatusText: String; begin Result := _StatusText; end; function THTTPResponse.Content: String; begin Result := _Content; end; function THTTPResponse.ContentType: THTTPContentType; begin Result := _ContentType; end; function THTTPResponse.Encoding: THTTPEncoding; begin Result := _Encoding; end; constructor THTTPResponse.Create(const Content: String; const ContentType: THTTPContentType; const Encoding: THTTPEncoding; const StatusCode: THTTPStatusCode; const StatusText: String); begin _Content := Content; _ContentType := ContentType; _Encoding := Encoding; _StatusCode := StatusCode; _StatusText := StatusText; end; class function THTTPResponse.New(const Content: String; const ContentType: THTTPContentType; const Encoding: THTTPEncoding; const StatusCode: THTTPStatusCode; const StatusText: String): IHTTPResponse; begin Result := THTTPResponse.Create(Content, ContentType, Encoding, StatusCode, StatusText); end; { THTTPJSONResponse } function THTTPJSONResponse.Content: String; begin Result := _Response.Content; end; function THTTPJSONResponse.ContentType: THTTPContentType; begin Result := _Response.ContentType; end; function THTTPJSONResponse.Encoding: THTTPEncoding; begin Result := _Response.Encoding; end; function THTTPJSONResponse.StatusCode: THTTPStatusCode; begin Result := _Response.StatusCode; end; function THTTPJSONResponse.StatusText: String; begin Result := _Response.StatusText; end; constructor THTTPJSONResponse.Create(const Content: String; const StatusCode: THTTPStatusCode; const StatusText: String); begin _Response := THTTPResponse.Create(Content, THTTPContentType.JSON, THTTPEncoding.UTF8, StatusCode, StatusText); end; class function THTTPJSONResponse.New(const Content: String; const StatusCode: THTTPStatusCode; const StatusText: String = ''): IHTTPResponse; begin Result := THTTPJSONResponse.Create(Content, StatusCode, StatusText); end; end.
unit UnixCompress; interface type HCkTask = Pointer; HCkUnixCompress = Pointer; HCkByteData = Pointer; HCkString = Pointer; function CkUnixCompress_Create: HCkUnixCompress; stdcall; procedure CkUnixCompress_Dispose(handle: HCkUnixCompress); stdcall; function CkUnixCompress_getAbortCurrent(objHandle: HCkUnixCompress): wordbool; stdcall; procedure CkUnixCompress_putAbortCurrent(objHandle: HCkUnixCompress; newPropVal: wordbool); stdcall; procedure CkUnixCompress_getDebugLogFilePath(objHandle: HCkUnixCompress; outPropVal: HCkString); stdcall; procedure CkUnixCompress_putDebugLogFilePath(objHandle: HCkUnixCompress; newPropVal: PWideChar); stdcall; function CkUnixCompress__debugLogFilePath(objHandle: HCkUnixCompress): PWideChar; stdcall; function CkUnixCompress_getHeartbeatMs(objHandle: HCkUnixCompress): Integer; stdcall; procedure CkUnixCompress_putHeartbeatMs(objHandle: HCkUnixCompress; newPropVal: Integer); stdcall; procedure CkUnixCompress_getLastErrorHtml(objHandle: HCkUnixCompress; outPropVal: HCkString); stdcall; function CkUnixCompress__lastErrorHtml(objHandle: HCkUnixCompress): PWideChar; stdcall; procedure CkUnixCompress_getLastErrorText(objHandle: HCkUnixCompress; outPropVal: HCkString); stdcall; function CkUnixCompress__lastErrorText(objHandle: HCkUnixCompress): PWideChar; stdcall; procedure CkUnixCompress_getLastErrorXml(objHandle: HCkUnixCompress; outPropVal: HCkString); stdcall; function CkUnixCompress__lastErrorXml(objHandle: HCkUnixCompress): PWideChar; stdcall; function CkUnixCompress_getLastMethodSuccess(objHandle: HCkUnixCompress): wordbool; stdcall; procedure CkUnixCompress_putLastMethodSuccess(objHandle: HCkUnixCompress; newPropVal: wordbool); stdcall; function CkUnixCompress_getVerboseLogging(objHandle: HCkUnixCompress): wordbool; stdcall; procedure CkUnixCompress_putVerboseLogging(objHandle: HCkUnixCompress; newPropVal: wordbool); stdcall; procedure CkUnixCompress_getVersion(objHandle: HCkUnixCompress; outPropVal: HCkString); stdcall; function CkUnixCompress__version(objHandle: HCkUnixCompress): PWideChar; stdcall; function CkUnixCompress_CompressFile(objHandle: HCkUnixCompress; inFilename: PWideChar; destPath: PWideChar): wordbool; stdcall; function CkUnixCompress_CompressFileAsync(objHandle: HCkUnixCompress; inFilename: PWideChar; destPath: PWideChar): HCkTask; stdcall; function CkUnixCompress_CompressFileToMem(objHandle: HCkUnixCompress; inFilename: PWideChar; outData: HCkByteData): wordbool; stdcall; function CkUnixCompress_CompressFileToMemAsync(objHandle: HCkUnixCompress; inFilename: PWideChar): HCkTask; stdcall; function CkUnixCompress_CompressMemory(objHandle: HCkUnixCompress; inData: HCkByteData; outData: HCkByteData): wordbool; stdcall; function CkUnixCompress_CompressMemToFile(objHandle: HCkUnixCompress; inData: HCkByteData; destPath: PWideChar): wordbool; stdcall; function CkUnixCompress_CompressString(objHandle: HCkUnixCompress; inStr: PWideChar; charset: PWideChar; outData: HCkByteData): wordbool; stdcall; function CkUnixCompress_CompressStringToFile(objHandle: HCkUnixCompress; inStr: PWideChar; charset: PWideChar; destPath: PWideChar): wordbool; stdcall; function CkUnixCompress_IsUnlocked(objHandle: HCkUnixCompress): wordbool; stdcall; function CkUnixCompress_SaveLastError(objHandle: HCkUnixCompress; path: PWideChar): wordbool; stdcall; function CkUnixCompress_UncompressFile(objHandle: HCkUnixCompress; inFilename: PWideChar; destPath: PWideChar): wordbool; stdcall; function CkUnixCompress_UncompressFileAsync(objHandle: HCkUnixCompress; inFilename: PWideChar; destPath: PWideChar): HCkTask; stdcall; function CkUnixCompress_UncompressFileToMem(objHandle: HCkUnixCompress; inFilename: PWideChar; outData: HCkByteData): wordbool; stdcall; function CkUnixCompress_UncompressFileToMemAsync(objHandle: HCkUnixCompress; inFilename: PWideChar): HCkTask; stdcall; function CkUnixCompress_UncompressFileToString(objHandle: HCkUnixCompress; zFilename: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkUnixCompress__uncompressFileToString(objHandle: HCkUnixCompress; zFilename: PWideChar; charset: PWideChar): PWideChar; stdcall; function CkUnixCompress_UncompressFileToStringAsync(objHandle: HCkUnixCompress; zFilename: PWideChar; charset: PWideChar): HCkTask; stdcall; function CkUnixCompress_UncompressMemory(objHandle: HCkUnixCompress; inData: HCkByteData; outData: HCkByteData): wordbool; stdcall; function CkUnixCompress_UncompressMemToFile(objHandle: HCkUnixCompress; inData: HCkByteData; destPath: PWideChar): wordbool; stdcall; function CkUnixCompress_UncompressString(objHandle: HCkUnixCompress; inCompressedData: HCkByteData; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkUnixCompress__uncompressString(objHandle: HCkUnixCompress; inCompressedData: HCkByteData; charset: PWideChar): PWideChar; stdcall; function CkUnixCompress_UnlockComponent(objHandle: HCkUnixCompress; unlockCode: PWideChar): wordbool; stdcall; function CkUnixCompress_UnTarZ(objHandle: HCkUnixCompress; zFilename: PWideChar; destDir: PWideChar; bNoAbsolute: wordbool): wordbool; stdcall; function CkUnixCompress_UnTarZAsync(objHandle: HCkUnixCompress; zFilename: PWideChar; destDir: PWideChar; bNoAbsolute: wordbool): HCkTask; stdcall; implementation {$Include chilkatDllPath.inc} function CkUnixCompress_Create; external DLLName; procedure CkUnixCompress_Dispose; external DLLName; function CkUnixCompress_getAbortCurrent; external DLLName; procedure CkUnixCompress_putAbortCurrent; external DLLName; procedure CkUnixCompress_getDebugLogFilePath; external DLLName; procedure CkUnixCompress_putDebugLogFilePath; external DLLName; function CkUnixCompress__debugLogFilePath; external DLLName; function CkUnixCompress_getHeartbeatMs; external DLLName; procedure CkUnixCompress_putHeartbeatMs; external DLLName; procedure CkUnixCompress_getLastErrorHtml; external DLLName; function CkUnixCompress__lastErrorHtml; external DLLName; procedure CkUnixCompress_getLastErrorText; external DLLName; function CkUnixCompress__lastErrorText; external DLLName; procedure CkUnixCompress_getLastErrorXml; external DLLName; function CkUnixCompress__lastErrorXml; external DLLName; function CkUnixCompress_getLastMethodSuccess; external DLLName; procedure CkUnixCompress_putLastMethodSuccess; external DLLName; function CkUnixCompress_getVerboseLogging; external DLLName; procedure CkUnixCompress_putVerboseLogging; external DLLName; procedure CkUnixCompress_getVersion; external DLLName; function CkUnixCompress__version; external DLLName; function CkUnixCompress_CompressFile; external DLLName; function CkUnixCompress_CompressFileAsync; external DLLName; function CkUnixCompress_CompressFileToMem; external DLLName; function CkUnixCompress_CompressFileToMemAsync; external DLLName; function CkUnixCompress_CompressMemory; external DLLName; function CkUnixCompress_CompressMemToFile; external DLLName; function CkUnixCompress_CompressString; external DLLName; function CkUnixCompress_CompressStringToFile; external DLLName; function CkUnixCompress_IsUnlocked; external DLLName; function CkUnixCompress_SaveLastError; external DLLName; function CkUnixCompress_UncompressFile; external DLLName; function CkUnixCompress_UncompressFileAsync; external DLLName; function CkUnixCompress_UncompressFileToMem; external DLLName; function CkUnixCompress_UncompressFileToMemAsync; external DLLName; function CkUnixCompress_UncompressFileToString; external DLLName; function CkUnixCompress__uncompressFileToString; external DLLName; function CkUnixCompress_UncompressFileToStringAsync; external DLLName; function CkUnixCompress_UncompressMemory; external DLLName; function CkUnixCompress_UncompressMemToFile; external DLLName; function CkUnixCompress_UncompressString; external DLLName; function CkUnixCompress__uncompressString; external DLLName; function CkUnixCompress_UnlockComponent; external DLLName; function CkUnixCompress_UnTarZ; external DLLName; function CkUnixCompress_UnTarZAsync; external DLLName; end.
{ Autor: Jürgen Schlottke, Schönaich-C.-Str. 46, D-W 2200 Elmshorn Tel. 04121/63109 Zweck : Demonstration der Schachprogrammierung unter Turbo-Pascal Datum : irgendwann 1991, als PD freigegeben am 18.01.93 Version: ohne Versionsnummer } unit ChessPlayer; interface uses ChessPlayerCore; type TExitCode = (ecSuccess, ecCheck, ecCheckmate, ecStalemate, ecError); TChessPlayer = class strict private FIniPos, FCurPos: TChessPosition; FHalfmovesCount: integer; FSecondList: TMoveList; public constructor Create; destructor Destroy; override; procedure SetPosition(const APos: string); function PlayMove(const AMove: string): boolean; function BestMoveIndex(const ABestValue: integer): integer; function BestMove(out ACode: TExitCode): string; overload; function BestMove: string; overload; function BoardAsText(const APretty: boolean = TRUE): string; function FEN: string; function SetPositionFromMoves(const APos: string; const AMoves: array of string): string; end; implementation uses Classes, SysUtils, TypInfo, ChessPlayerTypes, Log; const STARTPOS = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; constructor TChessPlayer.Create; begin inherited Create; FIniPos := TChessPosition.Create(STARTPOS); FCurPos := TChessPosition.Create; end; destructor TChessPlayer.Destroy; begin FCurPos.Free; FIniPos.Free; inherited Destroy; end; procedure TChessPlayer.SetPosition(const APos: string); function GetMoveCount(const APos: string): integer; var LFields: TStringList; begin LFields := TStringList.Create; ExtractStrings([' '], [], pchar(APos), LFields); if LFields.Count = 6 then result := 2 * Pred(StrToInt(LFields[5])) + Ord(LFields[1] = 'b') else result := 0; LFields.Free; end; begin FCurPos.SetPosition(APos); FHalfmovesCount := GetMoveCount(APos); end; function TChessPlayer.PlayMove(const AMove: string): boolean; var LAuxPos: TChessPosition; LMove, LPromo, LFrom, LTo: integer; begin MoveToInt(AMove, LMove, LPromo); LFrom := LMove div 100; LTo := LMove mod 100; FCurPos.GenerateMoves; result := FCurPos.IsLegal(LMove); if result then begin LAuxPos := TChessPosition.Create; LAuxPos.SetPosition(FCurPos); LAuxPos.MovePiece(LFrom, LTo, LPromo); LAuxPos.activeColor := CBlack * LAuxPos.activeColor; if LAuxPos.Check then result := FALSE else begin FCurPos.MovePiece(LFrom, LTo, LPromo); Inc(FHalfmovesCount); end; LAuxPos.Free; end; end; function TChessPlayer.BestMoveIndex(const ABestValue: integer): integer; var LAuxPos: TChessPosition; LMaxValue: integer; LSecondListCount: integer; i, j: integer; LLine1, LLine2: string; begin LAuxPos := TChessPosition.Create; with FCurPos do begin LSecondListCount := 0; for i := 1 to moveCount do if firstList[i].FValue = ABestValue then begin Inc(LSecondListCount); FSecondList[LSecondListCount].FFrom := firstList[i].FFrom; FSecondList[LSecondListCount].FTo := firstList[i].FTo; FSecondList[LSecondListCount].FValue := 0 end; end; LMaxValue := Low(integer); result := 0; LLine1 := ''; LLine2 := ''; for i := 1 to LSecondListCount do begin LAuxPos.SetPosition(FCurPos); with LAuxPos do begin if chessboard[FSecondList[i].FFrom] = FIniPos.chessboard[FSecondList[i].FFrom] then begin Inc(FSecondList[i].FValue, 5); if chessboard[FSecondList[i].FFrom] * activeColor = CPawn then Inc(FSecondList[i].FValue, 2); end; if chessboard[FSecondList[i].FFrom] * activeColor = CKing then if Abs(FSecondList[i].FTo - FSecondList[i].FFrom) = 20 then Inc(FSecondList[i].FValue, 20) else Dec(FSecondList[i].FValue, 10); if (FHalfmovesCount < 32) and (chessboard[FSecondList[i].FFrom] * activeColor in [CPawn, CBishop, CKnight]) then Inc(FSecondList[i].FValue, 20); if (FSecondList[i].FFrom div 10 = 1) or (FSecondList[i].FFrom div 10 = 8) or (FSecondList[i].FFrom mod 10 = 1) or (FSecondList[i].FFrom mod 10 = 8) then Inc(FSecondList[i].FValue, 2); if (FSecondList[i].FTo div 10 = 1) or (FSecondList[i].FTo div 10 = 8) or (FSecondList[i].FTo mod 10 = 1) or (FSecondList[i].FTo mod 10 = 8) then Dec(FSecondList[i].FValue, 2); end; LAuxPos.SetPosition(FCurPos); LAuxPos.MovePiece(FSecondList[i].FFrom, FSecondList[i].FTo, CQueen); if LAuxPos.chessboard[FSecondList[i].FTo] = FIniPos.chessboard[FSecondList[i].FTo] then Dec(FSecondList[i].FValue, 10); LAuxPos.activeColor := CBlack * LAuxPos.activeColor; LAuxPos.GenerateSimpleMoves; with LAuxPos do for j := 1 to moveCount do begin Inc(FSecondList[i].FValue); if chessboard[firstList[j].FTo] <> CNil then Inc(FSecondList[i].FValue); end; LAuxPos.activeColor := CBlack * LAuxPos.activeColor; LAuxPos.GenerateSimpleMoves; with LAuxPos do for j := 1 to moveCount do begin Dec(FSecondList[i].FValue); if chessboard[firstList[j].FTo] <> CNil then Dec(FSecondList[i].FValue); end; {$IFDEF DEBUG} with FSecondList[i] do begin LLine1 := LLine1 + Format('%6s', [MoveToStr(100 * FFrom + FTo)]); LLine2 := LLine2 + Format('%6d', [FValue]); end; {$ENDIF} if FSecondList[i].FValue >= LMaxValue then begin LMaxValue := FSecondList[i].FValue; result := i; end; end; {$IFDEF DEBUG} TLog.Append(LLine1); TLog.Append(LLine2); {$ENDIF} LAuxPos.Free; end; function TChessPlayer.BestMove(out ACode: TExitCode): string; const CCodeIllegal: array[boolean] of TExitCode = (ecStalemate, ecCheckmate); CCodeLegal: array[boolean] of TExitCode = (ecSuccess, ecCheck); var i: integer; LCheckBefore, LPromo: boolean; begin result := '0000'; i := FCurPos.BestEval(FCurPos.activeColor, 1, 32000); i := BestMoveIndex(i); if i > 0 then begin Inc(FHalfmovesCount); LCheckBefore := FCurPos.Check; with FSecondList[i] do LPromo := FCurPos.MovePiece(FFrom, FTo, CQueen); FCurPos.activeColor := CBlack * FCurPos.activeColor; if FCurPos.Check then ACode := CCodeIllegal[LCheckBefore] else begin with FSecondList[i] do result := MoveToStr(100 * FFrom + FTo); if LPromo then result := result + 'q'; FCurPos.activeColor := CBlack * FCurPos.activeColor; ACode := CCodeLegal[FCurPos.Check]; end; end else ACode := ecError; if not (ACode in [ecSuccess, ecCheck]) then TLog.Append(Format('bestmove function exit code %d', [ACode])); end; function TChessPlayer.BestMove: string; var LCode: TExitCode; begin result := BestMove(LCode); end; function TChessPlayer.BoardAsText(const APretty: boolean): string; begin result := FCurPos.BoardAsText(APretty); end; function TChessPlayer.FEN: string; begin result := FCurPos.FEN; end; function TChessPlayer.SetPositionFromMoves(const APos: string; const AMoves: array of string): string; var i: integer; begin SetPosition(APos); for i := Low(AMoves) to High(AMoves) do PlayMove(AMoves[i]); result := FEN; end; end.
unit TFlatRegister; interface procedure Register; implementation uses Classes, TFlatButtonUnit, TFlatSpeedButtonUnit, TFlatEditUnit, TFlatMemoUnit, TFlatRadioButtonUnit, TFlatCheckBoxUnit, TFlatProgressBarUnit, TFlatHintUnit, TFlatTabControlUnit, TFlatListBoxUnit, TFlatComboBoxUnit, TFlatAnimWndUnit, TFlatSoundUnit, TFlatGaugeUnit, TFlatSplitterUnit, TFlatAnimationUnit; procedure Register; begin RegisterComponents ('FlatStyle', [TFlatButton, TFlatSpeedButton, TFlatCheckBox, TFlatRadioButton, TFlatEdit, TFlatMemo, TFlatProgressBar, TFlatTabControl, TFlatListBox, TFlatComboBox, TFlatHint, TFlatAnimWnd, TFlatSound, TFlatGauge, TFlatSplitter, TFlatAnimation]); end; end.
unit HumbleBundleJSONObjects; // ************************************************* // Generated By: JsonToDelphiClass - 0.65 // Project link: https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass // Generated On: 2018-01-02 13:40:03 // ************************************************* // Created By : Petar Georgiev - 2014 // WebSite : http://pgeorgiev.com // ************************************************* interface uses Generics.Collections, Rest.Json; type TGameKeyClass = class private FGamekey: String; public property gamekey: String read FGamekey write FGamekey; function ToJsonString: string; class function FromJsonString(AJsonString: string): TGameKeyClass; end; TGameKeysClass = class private FGameKey: TArray<TGameKeyClass>; public property GameKey: TArray<TGameKeyClass> read FGameKey write FGameKey; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TGameKeysClass; end; TPayeeClass = class private FHuman_name: String; FMachine_name: String; public property human_name: String read FHuman_name write FHuman_name; property machine_name: String read FMachine_name write FMachine_name; function ToJsonString: string; class function FromJsonString(AJsonString: string): TPayeeClass; end; TOptions_dictClass = class private public function ToJsonString: string; class function FromJsonString(AJsonString: string): TOptions_dictClass; end; TUrlClass = class private FBittorrent: String; FWeb: String; public property bittorrent: String read FBittorrent write FBittorrent; property web: String read FWeb write FWeb; function ToJsonString: string; class function FromJsonString(AJsonString: string): TUrlClass; end; TDownload_structClass = class private FFile_size: Extended; FHuman_size: String; FMd5: String; FName: String; FSha1: String; FSmall: Extended; FUrl: TUrlClass; public property file_size: Extended read FFile_size write FFile_size; property human_size: String read FHuman_size write FHuman_size; property md5: String read FMd5 write FMd5; property name: String read FName write FName; property sha1: String read FSha1 write FSha1; property small: Extended read FSmall write FSmall; property url: TUrlClass read FUrl write FUrl; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TDownload_structClass; end; TDownloadsClass = class private FAndroid_app_only: Boolean; FDownload_identifier: String; FDownload_struct: TArray<TDownload_structClass>; FMachine_name: String; FOptions_dict: TOptions_dictClass; FPlatform: String; public property android_app_only: Boolean read FAndroid_app_only write FAndroid_app_only; property download_identifier: String read FDownload_identifier write FDownload_identifier; property download_struct: TArray<TDownload_structClass> read FDownload_struct write FDownload_struct; property machine_name: String read FMachine_name write FMachine_name; property options_dict: TOptions_dictClass read FOptions_dict write FOptions_dict; property platform: String read FPlatform write FPlatform; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TDownloadsClass; end; TSubproductsClass = class private FDownloads: TArray<TDownloadsClass>; FHuman_name: String; FIcon: String; FMachine_name: String; FPayee: TPayeeClass; FUrl: String; public property downloads: TArray<TDownloadsClass> read FDownloads write FDownloads; property human_name: String read FHuman_name write FHuman_name; property icon: String read FIcon write FIcon; property machine_name: String read FMachine_name write FMachine_name; property payee: TPayeeClass read FPayee write FPayee; property url: String read FUrl write FUrl; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TSubproductsClass; end; TAutomated_empty_tpkdsClass = class private public function ToJsonString: string; class function FromJsonString(AJsonString: string): TAutomated_empty_tpkdsClass; end; TProductClass = class private FAutomated_empty_tpkds: TAutomated_empty_tpkdsClass; FCategory: String; FHuman_name: String; FMachine_name: String; FPartial_gift_enabled: Boolean; FPost_purchase_text: String; FSupports_canonical: Boolean; public property automated_empty_tpkds: TAutomated_empty_tpkdsClass read FAutomated_empty_tpkds write FAutomated_empty_tpkds; property category: String read FCategory write FCategory; property human_name: String read FHuman_name write FHuman_name; property machine_name: String read FMachine_name write FMachine_name; property partial_gift_enabled: Boolean read FPartial_gift_enabled write FPartial_gift_enabled; property post_purchase_text: String read FPost_purchase_text write FPost_purchase_text; property supports_canonical: Boolean read FSupports_canonical write FSupports_canonical; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TProductClass; end; THumbleOrderClass = class private FAmount_spent: Extended; FClaimed: Boolean; FCreated: String; FGamekey: String; FIs_giftee: Boolean; FPath_ids: TArray<String>; FProduct: TProductClass; FSubproducts: TArray<TSubproductsClass>; FTotal: Extended; FUid: String; public property amount_spent: Extended read FAmount_spent write FAmount_spent; property claimed: Boolean read FClaimed write FClaimed; property created: String read FCreated write FCreated; property gamekey: String read FGamekey write FGamekey; property is_giftee: Boolean read FIs_giftee write FIs_giftee; property path_ids: TArray<String> read FPath_ids write FPath_ids; property product: TProductClass read FProduct write FProduct; property subproducts: TArray<TSubproductsClass> read FSubproducts write FSubproducts; property total: Extended read FTotal write FTotal; property uid: String read FUid write FUid; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): THumbleOrderClass; end; implementation {TPayeeClass} function TPayeeClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TPayeeClass.FromJsonString(AJsonString: string): TPayeeClass; begin result := TJson.JsonToObject<TPayeeClass>(AJsonString) end; {TOptions_dictClass} function TOptions_dictClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TOptions_dictClass.FromJsonString(AJsonString: string): TOptions_dictClass; begin result := TJson.JsonToObject<TOptions_dictClass>(AJsonString) end; {TUrlClass} function TUrlClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TUrlClass.FromJsonString(AJsonString: string): TUrlClass; begin result := TJson.JsonToObject<TUrlClass>(AJsonString) end; {TDownload_structClass} constructor TDownload_structClass.Create; begin inherited; FUrl := TUrlClass.Create(); end; destructor TDownload_structClass.Destroy; begin FUrl.free; inherited; end; function TDownload_structClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TDownload_structClass.FromJsonString(AJsonString: string): TDownload_structClass; begin result := TJson.JsonToObject<TDownload_structClass>(AJsonString) end; {TDownloadsClass} constructor TDownloadsClass.Create; begin inherited; FOptions_dict := TOptions_dictClass.Create(); end; destructor TDownloadsClass.Destroy; var Ldownload_structItem: TDownload_structClass; begin for Ldownload_structItem in FDownload_struct do Ldownload_structItem.free; FOptions_dict.free; inherited; end; function TDownloadsClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TDownloadsClass.FromJsonString(AJsonString: string): TDownloadsClass; begin result := TJson.JsonToObject<TDownloadsClass>(AJsonString) end; {TSubproductsClass} constructor TSubproductsClass.Create; begin inherited; FPayee := TPayeeClass.Create(); end; destructor TSubproductsClass.Destroy; var LdownloadsItem: TDownloadsClass; begin for LdownloadsItem in FDownloads do LdownloadsItem.free; FPayee.free; inherited; end; function TSubproductsClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TSubproductsClass.FromJsonString(AJsonString: string): TSubproductsClass; begin result := TJson.JsonToObject<TSubproductsClass>(AJsonString) end; {TAutomated_empty_tpkdsClass} function TAutomated_empty_tpkdsClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TAutomated_empty_tpkdsClass.FromJsonString(AJsonString: string): TAutomated_empty_tpkdsClass; begin result := TJson.JsonToObject<TAutomated_empty_tpkdsClass>(AJsonString) end; {TProductClass} constructor TProductClass.Create; begin inherited; FAutomated_empty_tpkds := TAutomated_empty_tpkdsClass.Create(); end; destructor TProductClass.Destroy; begin FAutomated_empty_tpkds.free; inherited; end; function TProductClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TProductClass.FromJsonString(AJsonString: string): TProductClass; begin result := TJson.JsonToObject<TProductClass>(AJsonString) end; {THumbleOrderClass} constructor THumbleOrderClass.Create; begin inherited; FProduct := TProductClass.Create(); end; destructor THumbleOrderClass.Destroy; var LsubproductsItem: TSubproductsClass; begin for LsubproductsItem in FSubproducts do LsubproductsItem.free; FProduct.free; inherited; end; function THumbleOrderClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function THumbleOrderClass.FromJsonString(AJsonString: string): THumbleOrderClass; begin result := TJson.JsonToObject<THumbleOrderClass>(AJsonString) end; {TGameKeyClass} function TGameKeyClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TGameKeyClass.FromJsonString(AJsonString: string): TGameKeyClass; begin result := TJson.JsonToObject<TGameKeyClass>(AJsonString) end; {TGameKeysClass} destructor TGameKeysClass.Destroy; var LGameKeyItem: TGameKeyClass; begin for LGameKeyItem in FGameKey do LGameKeyItem.free; inherited; end; function TGameKeysClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TGameKeysClass.FromJsonString(AJsonString: string): TGameKeysClass; begin result := TJson.JsonToObject<TGameKeysClass>(AJsonString) end; end.
unit NeoEcommerceService.Model.Connections.Interfaces; interface uses System.Classes, Data.DB, System.JSON, Datasnap.DBClient; type TEvDisplay = procedure(Value: string) of Object; iModelConnectionParams = interface; iModelConnectionRestParams = interface; iModelConnection = interface ['{F8EA8C21-F79C-402F-ACA2-AA9794412061}'] function Connect: iModelConnection; function EndConnection: TComponent; function Params: iModelConnectionParams; end; iModelConnectionParams = interface ['{7E7DF611-6FE8-4E1E-8D7A-4BB1B36A91D7}'] function DataBase(const Value: string): iModelConnectionParams; function UserName(const Value: string): iModelConnectionParams; function Password(const Value: string): iModelConnectionParams; function DriverID(const Value: string): iModelConnectionParams; function Server(const Value: string): iModelConnectionParams; function Port(const Value: integer): iModelConnectionParams; function EndParams: iModelConnection; end; iModelFactoryConnection = interface ['{C806DF9A-E9E6-438C-89B8-F39DF661473F}'] function ConnectionFiredac: iModelConnection; end; iModelConnectionRest = interface ['{D4228031-7774-49F5-AAD5-FF0D26B15EB2}'] function EndConnection: TComponent; function Params: iModelConnectionRestParams; end; iModelConnectionRestParams = interface ['{98237618-64FA-45E2-ADF1-D20DC3912213}'] function BaseUrl(const Value: string): iModelConnectionRestParams; function UserName(const Value: string): iModelConnectionRestParams; function Password(const Value: string): iModelConnectionRestParams; function EndParams: iModelConnectionRest; end; iModelFactoryConnectionRest = interface ['{FB86F716-AE55-40DF-9585-DD39C7D39631}'] function ConnectionRestDelphi: iModelConnectionRest; end; iModelQuery = interface ['{C5051F28-92FC-482F-98AC-2F0C080DC714}'] function SQL(const Value: TStrings): iModelQuery; function Query: TDataSet; function ExecSQL: iModelQuery; end; iModelFactoryQuery = interface ['{6F588BC1-2C22-4EB5-A862-8FB64085A7DD}'] function FiredacQuery(Connection: iModelConnection): iModelQuery; end; iModelDataSet = interface ['{5CBD1A76-2E1B-4F37-90CF-7E60874280F2}'] function SetDataSet(aValue: TDataSet): iModelDataSet; function CopyDataSet(aValue: TDataSet): iModelDataset; function EndDataSet: TDataSet; end; iModelClientDataSet = interface ['{1CD0D954-7CFF-4E00-99D4-E50CF8E973C4}'] function SetDataSet(aValue: TClientDataSet): iModelClientDataSet; function EndDataSet: TClientDataSet; function Free: iModelClientDataSet; end; iModelFactoryDataSet = interface ['{9D88FA15-B08D-4127-8617-B1A195DA8601}'] function DataSetFiredac: iModelDataSet; function ClientDataSet: iModelClientDataSet; end; iModelRestData = interface ['{38C09079-55EC-489A-A088-C4C7EB570D45}'] function Resource(const Value: string): iModelRestData; function Param(const Value:string): iModelRestData; function QueryParam(const Value:string): iModelRestData; function Execute: iModelRestData; function Get: iModelRestData; function JSonValue: TJsonValue; {function GetStatusCode(Value: TEvDisplay): iModelRestData; function GetStatusText(Value: TEvDisplay): iModelRestData;} //function EndRestData: TComponent; end; iModelFactoryRestData = interface ['{BEEA4D74-18D9-4BB0-867A-2FA688A0E263}'] function RestDataDelphi(ConnectionRest: iModelConnectionRest): iModelRestData; end; implementation end.
unit DBConnect; interface uses Windows, Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, Comobj, inifiles, SysUtils, ComCtrls, DB, ADODB, Variants; type TDBConnectForm = class(TForm) OpenDialog1: TOpenDialog; Panel2: TPanel; PageControl: TPageControl; Label1: TLabel; BitBtnSel: TBitBtn; BitBtnTest: TBitBtn; BtnConn: TBitBtn; BtnCompact: TBitBtn; BtnFix: TBitBtn; BtnCancel: TBitBtn; CBDefault: TCheckBox; TabSheet1: TTabSheet; TabSheet2: TTabSheet; RBAccess: TRadioButton; RBSQL: TRadioButton; BtnClose: TBitBtn; lblIp: TLabel; EdtDBPath: TMemo; BtnCreate: TBitBtn; GBFirst: TGroupBox; Label2: TLabel; EdtIp: TEdit; NTCheck: TCheckBox; Label4: TLabel; Label5: TLabel; EdtUser: TEdit; EdtPass: TEdit; BtnConnect: TBitBtn; GBSecond: TGroupBox; Label3: TLabel; CBDatabase: TComboBox; BtnSave: TBitBtn; LocalBtn: TBitBtn; procedure FormShow(Sender: TObject); procedure BitBtnSelClick(Sender: TObject); procedure BtnCompactClick(Sender: TObject); procedure BtnFixClick(Sender: TObject); procedure CBDefaultClick(Sender: TObject); procedure BtnConnClick(Sender: TObject); procedure BitBtnTestClick(Sender: TObject); procedure RBAccessClick(Sender: TObject); procedure RBSQLClick(Sender: TObject); procedure BtnConnectClick(Sender: TObject); procedure BtnSaveClick(Sender: TObject); procedure NTCheckClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnCloseClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure LocalBtnClick(Sender: TObject); procedure TabSheet2Show(Sender: TObject); procedure BtnCreateClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var DBConnectForm: TDBConnectForm; implementation uses QueryDM, CommonUtil; {$R *.dfm} function DBFileExist(FileName: string; Flag: boolean): string; begin if FileName <> '' then begin if Flag then FileName := ExtractFilePath(ParamStr(0)) + '\Database\Database.mdb'; if FileExists(FileName) then result := FileName else result := '' end else result := '' end; function CompactDatabase(srcFileName, destFileName, dbPassWord: string): boolean; //压缩数据库,覆盖源文件 const SConnectionString = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;' + 'Jet OLEDB:Database Password=%s;'; var DB: OleVariant; begin try DB := CreateOleObject('JRO.JetEngine'); //建立OLE对象,函数结束OLE对象超过作用域自动释放 OleCheck(DB.CompactDatabase(format(SConnectionString, [srcFileName, dbPassWord]), format(SConnectionString, [destFileName, dbPassWord]))); //压缩数据库 result := CopyFile(pchar(destFileName), pchar(srcFileName), False); DeleteFile(destFileName); //删除临时文件 except result := False //压缩失败 end end; procedure TDBConnectForm.FormShow(Sender: TObject); var myini: Tinifile; begin myini := Tinifile.Create(ExtractFilePath(ParamStr(0)) + '\db.ini'); try RBAccess.Checked := myini.ReadInteger('db', 'type', 0) = 0; RBSQL.Checked := myini.ReadInteger('db', 'type', 0) = 1; if RBAccess.Checked then PageControl.ActivePageIndex := 0 else PageControl.ActivePageIndex := 1; EdtDBPath.Text := myini.ReadString('db', 'addr', ''); if myini.ReadBool('db', 'default', True) then begin CBDefault.Checked := True; EdtDBPath.Enabled := False; BitBtnSel.Enabled := False end else CBDefault.Checked := False; CBDatabase.Style := csDropDown; EdtIP.Text := myini.ReadString('db', 'IP', '.'); CBDatabase.Text := myini.ReadString('db', 'DBName', 'weight20'); EdtUser.Text := myini.ReadString('db', 'user', 'sa'); EdtPass.Text := TCommonUtil.deBase64(myini.ReadString('db', 'pass', 'MTIz')); NTCheck.Checked := myini.ReadBool('db', 'Integrated', True); BtnSave.Enabled := False; finally myini.Free; end; end; procedure TDBConnectForm.BitBtnSelClick(Sender: TObject); begin OpenDialog1.Execute; EdtDBPath.Text := OpenDialog1.FileName end; procedure TDBConnectForm.BtnCompactClick(Sender: TObject); var FileName: string; begin FileName := DBFileExist(EdtDBPath.Text, CBDefault.Checked); if FileName <> '' then begin QueryDataModule.DBConnection.Close; if CompactDatabase(FileName, ExtractFilePath(FileName) + '\temp.mdb', QueryDM.DB_PASSWORD) then begin QueryDataModule.DBConnection.Open; MessageDlg('数据库压缩成功!', mtInformation, [mbOK], 0); Close end else MessageDlg('数据库压缩失败!', mtWarning, [mbOK], 0); QueryDataModule.DBConnection.Open end else MessageDlg('数据库文件不存在,无法压缩!', mtWarning, [mbOK], 0) end; procedure TDBConnectForm.BtnFixClick(Sender: TObject); var FileName: string; begin FileName := DBFileExist(EdtDBPath.Text, CBDefault.Checked); if FileName <> '' then begin QueryDataModule.DBConnection.Close; if CompactDatabase(FileName, ExtractFilePath(FileName) + '\temp.mdb', QueryDM.DB_PASSWORD) then begin QueryDataModule.DBConnection.Open; MessageDlg('数据库修复成功!', mtInformation, [mbOK], 0); Close end else MessageDlg('数据库修复失败!', mtWarning, [mbOK], 0); QueryDataModule.DBConnection.Open end else MessageDlg('数据库文件不存在,无法修复!', mtWarning, [mbOK], 0) end; procedure TDBConnectForm.CBDefaultClick(Sender: TObject); begin if CBDefault.Checked then begin BitBtnSel.Enabled := False; EdtDBPath.Text := ExtractFilePath(ParamStr(0)) + '\Database\Database.mdb'; EdtDBPath.Enabled := False end else begin BitBtnSel.Enabled := True; EdtDBPath.Enabled := True; EdtDBPath.Text := '' end end; procedure TDBConnectForm.BtnConnClick(Sender: TObject); var FileName: string; myini: Tinifile; begin FileName := DBFileExist(EdtDBPath.Text, CBDefault.Checked); if FileName <> '' then begin try QueryDataModule.DBConnection.Close; QueryDataModule.DBConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + FileName + ';Persist Security Info=False;Jet OLEDB:Database Password=' + QueryDM.DB_PASSWORD; QueryDataModule.DBConnection.Open; except MessageDlg('数据库连接失败!', mtWarning, [mbOK], 0) end; myini := Tinifile.Create(ExtractFilePath(ParamStr(0)) + '\setup.ini'); try myini.WriteString('db', 'addr', FileName); myini.WriteBool('db', 'default', CBDefault.Checked); MessageDlg('数据库连接成功!', mtInformation, [mbOK], 0); Close finally myini.Free; end; end else MessageDlg('数据库文件不存在,无法连接!', mtWarning, [mbOK], 0) end; procedure TDBConnectForm.BitBtnTestClick(Sender: TObject); var FileName: string; begin FileName := DBFileExist(EdtDBPath.Text, CBDefault.Checked); if FileName <> '' then begin try QueryDataModule.DBConnection.Close; QueryDataModule.DBConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + FileName + ';Persist Security Info=False;Jet OLEDB:Database Password=' + QueryDM.DB_PASSWORD; QueryDataModule.DBConnection.Open; MessageDlg('数据库测试连接成功!', mtInformation, [mbOK], 0); except MessageDlg('数据库测试连接失败!', mtWarning, [mbOK], 0) end end else MessageDlg('数据库文件不存在,无法测试连接!', mtWarning, [mbOK], 0) end; procedure TDBConnectForm.RBAccessClick(Sender: TObject); begin if (Sender as TRadioButton).Checked then RBSQL.Checked := False; end; procedure TDBConnectForm.RBSQLClick(Sender: TObject); begin if (Sender as TRadioButton).Checked then RBAccess.Checked := False; end; procedure TDBConnectForm.BtnConnectClick(Sender: TObject); var ConnStr: string; adoc: TADOConnection; adoq: TADOQuery; begin ConnStr := 'Provider=SQLOLEDB.1;'; //OLE DB连接程序 if NTCheck.Checked then //验证方式 ConnStr := ConnStr + 'Integrated Security=SSPI;' else ConnStr := ConnStr + 'User ID=' + trim(EdtUser.Text) + ';Password=' + trim(EdtPass.Text) + ';'; ConnStr := ConnStr + 'Persist Security Info=True;Initial Catalog=master;Data Source=' + trim(EdtIP.Text); adoc := TADOConnection.Create(Application); try adoc.Close; adoc.LoginPrompt := False; adoc.ConnectionString := ConnStr; try adoc.Open; MessageDlg('连接SQL数据库成功!', mtInformation, [mbOK], 0); BtnSave.Enabled := True; adoq := TADOQuery.Create(Application); try adoq.Connection := adoc; with adoq do begin Close; SQL.Text := 'select name from sysdatabases'; Open; if not IsEmpty then begin CBDatabase.Items.Clear; First; while not EOF do begin CBDatabase.Items.Add(FieldByName('name').AsString); Next; end; end; end; finally adoq.Free; end; except on e: Exception do begin MessageDlg('数据库连接失败,请重新设置' + Chr(13) + Chr(10) + E.Message, mtError, [mbOK], 0); BtnSave.Enabled := False; end; end; finally adoc.Free; end; end; procedure TDBConnectForm.BtnSaveClick(Sender: TObject); var myini: TIniFile; begin if CBDatabase.Text = '' then begin MessageBoxW(Handle, '请先选择数据库', '提示', MB_OK + MB_ICONWARNING + MB_TOPMOST); Exit; end; if myini = nil then myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'db.ini'); try myini.WriteString('db', 'IP', EdtIP.Text); myini.WriteString('db', 'DBName', CBDatabase.Text); myini.WriteString('db', 'user', EdtUser.Text); myini.WriteString('db', 'pass', TCommonUtil.base64(EdtPass.Text)); myini.WriteBool('db', 'integrated', NTCheck.Checked); //验证方式 MessageDlg('保存数据库参数成功!', mtInformation, [mbOK], 0); TCommonUtil.Set_WindowsXP_FireWall(False); Close; finally myini.Free; end; end; procedure TDBConnectForm.NTCheckClick(Sender: TObject); begin EdtUser.Enabled := not NTCheck.Checked; EdtPass.Enabled := not NTCheck.Checked; end; procedure TDBConnectForm.FormClose(Sender: TObject; var Action: TCloseAction); var myini: TiniFile; begin myini := TiniFile.Create(ExtractFilePath(ParamStr(0)) + 'db.ini'); try if RBAccess.Checked then myini.WriteInteger('db', 'type', 0) else if RBSQL.Checked then myini.WriteInteger('db', 'type', 1); finally myini.Free; end; end; procedure TDBConnectForm.BtnCloseClick(Sender: TObject); begin Close; end; procedure TDBConnectForm.BtnCancelClick(Sender: TObject); begin Close end; procedure TDBConnectForm.LocalBtnClick(Sender: TObject); var i: Integer; begin RBSQL.Checked := True; EdtIp.Text := '.'; NTCheck.Checked := True; BtnConnect.Click; for i := 0 to CBDatabase.Items.Count - 1 do begin if UpperCase(CBDatabase.Items.Strings[i]) = 'WEIGHT20' then begin CBDatabase.Text := 'WEIGHT20'; BtnSave.Click; Exit; end end; //未找到数据库 Application.MessageBox('未找到称重数据库参数,设置失败', '错误', MB_OK + MB_ICONSTOP + MB_TOPMOST); end; procedure TDBConnectForm.TabSheet2Show(Sender: TObject); begin lblIp.Caption := Format('本机IP : %s', [TCommonUtil.getLocalIp]); end; procedure TDBConnectForm.BtnCreateClick(Sender: TObject); begin if Application.MessageBox('将删除现有"WEIGHT20"的数据库,是否继续?', '提示', MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2 + MB_TOPMOST) = IDYES then begin if FileExists(ExtractFilePath(ParamStr(0)) + 'Database\WEIGHT20.SQL') then begin WinExec(PChar('osql -E -n -i ' + ExtractFilePath(ParamStr(0)) + 'Database\WEIGHT20.SQL'), SW_SHOW); end else begin Application.MessageBox('脚本文件不存在,系统退出操作.', '提示', MB_OK + MB_ICONINFORMATION + MB_TOPMOST); end; end; end; end. d.
unit uDB1Data; interface uses SysUtils, Classes, Controls, graphics, messages, db, SqlExpr, Dialogs; type TDB1Data = class(TSQLDataSet) private FListaTabelas: TStrings; FListaCampos: TStrings; FListaCondicoes: TStrings; protected { Protected declarations } public constructor Create(AOwner: TComponent); override; { Public declarations } published { Published declarations } property ListaTabelas: TStrings read FListaTabelas write FListaTabelas; property ListaCampos: TStrings read FListaCampos write FListaCampos; property ListaCondicoes: TStrings read FListaCondicoes write FListaCondicoes; procedure Open; end; procedure Register; implementation procedure Register; begin RegisterComponents('DB1 Avaliação', [TDB1Data]); end; constructor TDB1Data.Create(AOwner: TComponent); begin inherited; end; procedure TDB1Data.Open; var sql: string; i: Integer; begin if Trim(ListaTabelas.Text) = '' then begin MessageDlg('Favor informar ao menos uma tabela.',mtError, [mbOK], 0); abort; end; Self.Active := False; sql := 'SELECT '; if trim(ListaCampos.Text) = '' then sql := sql + ' * '; sql := sql + ListaCampos[0]; for i := 1 to ListaCampos.Count - 1 do if Trim(ListaCampos[i]) <> '' then sql := sql + ', ' + ListaCampos[i]; sql := sql + ' FROM ' + ListaTabelas[0]; for i := 1 to ListaTabelas.Count - 1 do if Trim(ListaTabelas[i]) <> '' then sql := sql + ', ' + ListaTabelas[i]; if trim(ListaCondicoes.Text) <> '' then sql := sql + ' WHERE ' + ListaCondicoes[0]; for i := 1 to ListaCondicoes.Count - 1 do begin if Trim(ListaCondicoes[i]) <> '' then sql := sql + ' AND ' + ListaCondicoes[i]; end; Self.CommandText := sql; Self.Active := True; end; end.
unit ArtistsController; interface uses Generics.Collections, Aurelius.Engine.ObjectManager, Artist; type TArtistsController = class private FManager: TObjectManager; public constructor Create; destructor Destroy; override; procedure DeleteArtist(Artist: TArtist); function GetAllArtists: TList<TArtist>; end; implementation uses DBConnection; { TArtistController } constructor TArtistsController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TArtistsController.DeleteArtist(Artist: TArtist); begin if not FManager.IsAttached(Artist) then Artist := FManager.Find<TArtist>(Artist.Id); FManager.Remove(Artist); end; destructor TArtistsController.Destroy; begin FManager.Free; inherited; end; function TArtistsController.GetAllArtists: TList<TArtist>; begin FManager.Clear; Result := FManager.FindAll<TArtist>; end; end.
unit ConsultaSql; interface uses SysUtils, Variants, Classes; type TLayoutQuery = class private FQuery: String; FConditions: String; FOrderBy: String; function GetSqlQuery: string; public constructor Create; overload; published property Query: string read FQuery write FQuery; property Conditions: string read FConditions write FConditions; property OrderBy: string read FOrderBy write FOrderBy; property SqlQuery: string read GetSqlQuery; end; implementation { TLayoutQuery } constructor TLayoutQuery.Create; begin FQuery := ''; FConditions := ''; FOrderBy := ''; end; function TLayoutQuery.GetSqlQuery: string; var sqlQuery: String; begin sqlQuery := FQuery; if FConditions <> '' then sqlQuery := sqlQuery + ' WHERE ' + FConditions; if FOrderBy <> '' then sqlQuery := sqlQuery + ' ORDER BY ' + FOrderBy; result := sqlQuery; end; end.
unit raycastglsl; {$IFNDEF FPC} {$D-,L-,Y-}{$ENDIF} {$O+,Q-,R-,S-} {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} // Inspired by Peter Trier http://www.daimi.au.dk/~trier/?page_id=98 // Philip Rideout http://prideout.net/blog/?p=64 // and Doyub Kim Jan 2009 http://www.doyub.com/blog/759 // Ported to Pascal by Chris Rorden Apr 2011 // Tips for Shaders from // http://pages.cs.wisc.edu/~nowak/779/779ClassProject.html#bound interface {$include options.inc} uses {$IFDEF FPC} {$IFDEF UNIX} LCLIntf,{$ELSE} Windows, {$ENDIF} graphtype, {$ELSE} Windows, {$ENDIF} {$IFDEF ENABLEWATERMARK}watermark,{$ENDIF} {$IFDEF USETRANSFERTEXTURE}texture_3d_unita, {$ELSE} texture_3d_unit,{$ENDIF} graphics, {$IFDEF DGL} dglOpenGL, {$ELSE} gl, glext, {$ENDIF} define_types, sysutils, histogram2d, math, colorbar2d; type TRayCast = RECORD glslprogram, glslprogramSobel, glslprogramBlur: GLuint; ModelessColor: TGLRGBQuad; ScreenCapture: boolean; ClipAzimuth,ClipElevation,ClipDepth, LightAzimuth,LightElevation, Azimuth,Elevation,WINDOW_WIDTH,WINDOW_HEIGHT : integer; OrthoZoom,OrthoX,OrthoY,OrthoZ,Distance,slices: single; {$IFDEF USETRANSFERTEXTURE}transferTexture1, {$ENDIF} intensityOverlay3D, gradientTexture3D,gradientOverlay3D, intensityTexture3D,finalImage, renderBuffer, frameBuffer,backFaceBuffer: TGLuint; MosaicString,ModelessString: string; end; const kDefaultDistance = 2.25; kMaxDistance = 40; var AreaInitialized: boolean = false; var gRayCast: TRayCast; procedure glUniform1ix(prog: GLuint; name: AnsiString; value: integer); procedure glUniform1fx(prog: GLuint; name: AnsiString; value: single ); procedure DisplayGL(var lTex: TTexture); procedure DisplayGLz(var lTex: TTexture; zoom, zoomOffsetX, zoomOffsetY: integer); //function DisplayGL(var lTex: TTexture): boolean; function WarningIfNoveau: boolean; procedure InitGL (InitialSetup: boolean);// (var lTex: TTexture); procedure uniform1f( name: AnsiString; value: single ); procedure uniform1i( name: AnsiString; value: integer); function initVertFrag(vert, frag: string): GLuint; function gpuReport: string; //warning: must be called while in OpenGL context! implementation uses shaderu, mainunit,slices2d; function WarningIfNoveau: boolean; var Vendor: AnsiString; begin result := false; Vendor := glGetString(GL_VENDOR); if length(Vendor) < 2 then exit; if (upcase(Vendor[1]) <> 'N') or (upcase(Vendor[2]) <> 'O') then exit; GLForm1.ShowmessageError('If you have problems, switch from the Noveau to NVidia driver. Edit your preferences to hide this message.'); end; //this GLSL shader will blur data const kSmoothShaderFrag = 'uniform float coordZ, dX, dY, dZ;' +#10'uniform sampler3D intensityVol;' +#10'void main(void) {' +#10' vec3 vx = vec3(gl_TexCoord[0].xy, coordZ);' +#10' vec4 samp = texture3D(intensityVol,vx+vec3(+dX,+dY,+dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(+dX,+dY,-dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(+dX,-dY,+dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(+dX,-dY,-dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(-dX,+dY,+dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(-dX,+dY,-dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(-dX,-dY,+dZ));' +#10' samp += texture3D(intensityVol,vx+vec3(-dX,-dY,-dZ));' +#10' gl_FragColor = samp*0.125;' +#10'}'; //this will estimate a Sobel smooth const kSobelShaderFrag = 'uniform float coordZ, dX, dY, dZ;' +#10'uniform sampler3D intensityVol;' +#10'void main(void) {' +#10' vec3 vx = vec3(gl_TexCoord[0].xy, coordZ);' +#10' float TAR = texture3D(intensityVol,vx+vec3(+dX,+dY,+dZ)).a;' +#10' float TAL = texture3D(intensityVol,vx+vec3(+dX,+dY,-dZ)).a;' +#10' float TPR = texture3D(intensityVol,vx+vec3(+dX,-dY,+dZ)).a;' +#10' float TPL = texture3D(intensityVol,vx+vec3(+dX,-dY,-dZ)).a;' +#10' float BAR = texture3D(intensityVol,vx+vec3(-dX,+dY,+dZ)).a;' +#10' float BAL = texture3D(intensityVol,vx+vec3(-dX,+dY,-dZ)).a;' +#10' float BPR = texture3D(intensityVol,vx+vec3(-dX,-dY,+dZ)).a;' +#10' float BPL = texture3D(intensityVol,vx+vec3(-dX,-dY,-dZ)).a;' +#10' vec4 gradientSample = vec4 (0.0, 0.0, 0.0, 0.0);' +#10' gradientSample.r = BAR+BAL+BPR+BPL -TAR-TAL-TPR-TPL;' +#10' gradientSample.g = TPR+TPL+BPR+BPL -TAR-TAL-BAR-BAL;' +#10' gradientSample.b = TAL+TPL+BAL+BPL -TAR-TPR-BAR-BPR;' +#10' gradientSample.a = (abs(gradientSample.r)+abs(gradientSample.g)+abs(gradientSample.b))*0.29;' +#10' gradientSample.rgb = normalize(gradientSample.rgb);' +#10' gradientSample.rgb = (gradientSample.rgb * 0.5)+0.5;' +#10' gl_FragColor = gradientSample;' +#10'}'; //the gradientSample.a coefficient is critical - 0.25 is technically correct, 0.29 better emulates CPU (where we normalize alpha values in the whole volume) (*const kMinimalShaderFrag = 'uniform float coordZ, dX, dY, dZ;' +#10'uniform sampler3D intensityVol;' +#10'void main(void){' +#10' gl_FragColor = vec4 (0.3, 0.5, 0.7, 0.2);' +#10'}';*) function gpuReport: string; //warning: must be called while in OpenGL context! begin result := ' OpenGL '+glGetString(GL_VERSION)+' GLSL '+glGetString(GL_SHADING_LANGUAGE_VERSION); end; procedure DetectErrorGL(s: string); var err: GLenum; begin err:=glGetError(); if err>0 then //ShowMessage(format('Model_before: glGetError, code: %d',[err])); GLForm1.ShowmessageError('OpenGL error '+s +' : '+inttostr(err)); end; procedure GetError(p: integer); //report OpenGL Error var Error: GLenum; s: string; begin Error := glGetError(); if Error = GL_NO_ERROR then exit; s := inttostr(p)+'->' + inttostr(Error); GLForm1.ShowmessageError('OpenGL error : '+s ); end; procedure ReportCompileShaderError(glObjectID: GLuint); var s : string; maxLength, status : GLint; begin status := 0; glGetShaderiv(glObjectID, GL_COMPILE_STATUS, @status); if (status <> 0) then exit; //report compiling errors. glGetError; glGetShaderiv(glObjectID, GL_INFO_LOG_LENGTH, @maxLength); setlength(s, maxLength); {$IFDEF DGL} glGetShaderInfoLog(glObjectID, maxLength, maxLength, @s[1]); {$ELSE} glGetShaderInfoLog(glObjectID, maxLength, @maxLength, @s[1]); {$ENDIF} s:=trim(s); showDebug('Compile Shader error '+s); GLForm1.ShowmessageError('Shader compile error '+s); end; procedure ReportCompileProgramError(glObjectID: GLuint); var s : string; maxLength : GLint; begin glGetProgramiv(glObjectID, GL_LINK_STATUS, @maxLength); if (maxLength = GL_TRUE) then exit; maxLength := 4096; setlength(s, maxLength); {$IFDEF DGL} glGetProgramInfoLog(glObjectID, maxLength, maxLength, @s[1]); {$ELSE} glGetProgramInfoLog(glObjectID, maxLength, @maxLength, @s[1]); {$ENDIF} s:=trim(s); if length(s) < 2 then exit; GLForm1.ShowmessageError('Program compile error '+s); end; function compileShaderOfType (shaderType: GLEnum; shaderText: string): GLuint; begin result := glCreateShader(shaderType); {$IFDEF DGL} glShaderSource(result, 1, PPGLChar(@shaderText), nil); {$ELSE} glShaderSource(result, 1, PChar(@shaderText), nil); {$ENDIF} glCompileShader(result); ReportCompileShaderError(result); end; function initVertFrag(vert, frag: string): GLuint; var fs, vs: GLuint; begin result := 0; glGetError(); //clear errors result := glCreateProgram(); if (length(vert) > 0) then begin vs := compileShaderOfType(GL_VERTEX_SHADER, vert); if (vs = 0) then exit; glAttachShader(result, vs); end; fs := compileShaderOfType(GL_FRAGMENT_SHADER, frag); if (fs = 0) then exit; glAttachShader(result, fs); glLinkProgram(result); ReportCompileProgramError(result); if (length(vert) > 0) then begin glDetachShader(result, vs); glDeleteShader(vs); end; glDetachShader(result, fs); glDeleteShader(fs); //glUseProgram(result); // <- causes flicker on resize with OSX glUseProgram(0); GetError(1); end; function bindBlankGL(var lTex: TTexture): GLuint; begin //creates an empty texture in VRAM without requiring memory copy from RAM //later run glDeleteTextures(1,&oldHandle); glGenTextures(1, @result); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_3D, result); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //, GL_CLAMP_TO_BORDER) will wrap glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, lTex.FiltDim[1], lTex.FiltDim[2], lTex.FiltDim[3], 0, GL_RGBA, GL_UNSIGNED_BYTE, nil); end; procedure glUniform1fx(prog: GLuint; name: AnsiString; value: single ); begin glUniform1f(glGetUniformLocation(prog, pAnsiChar(Name)), value) ; end; procedure glUniform1ix(prog: GLuint; name: AnsiString; value: integer); begin glUniform1i(glGetUniformLocation(prog, pAnsiChar(Name)), value) ; end; procedure performBlurSobel(var lTex: TTexture; lIsOverlay: boolean); //http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-14-render-to-texture/ //http://www.opengl.org/wiki/Framebuffer_Object_Examples var i: integer; coordZ: single; //dx fb, tempTex3D: GLuint; begin glGenFramebuffersEXT(1, @fb); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb); //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,gRayCast.frameBuffer); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);// <- REQUIRED glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); //glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA8, lTex.FiltDim[1], lTex.FiltDim[2], 0, GL_RGBA, GL_UNSIGNED_BYTE, nil); glViewport(0, 0, lTex.FiltDim[1], lTex.FiltDim[2]); glMatrixMode(GL_PROJECTION); glLoadIdentity(); {$IFDEF DGL} gluOrtho2D(0, 1, 0, 1); {$ELSE} glOrtho (0, 1,0, 1, -1, 1); //gluOrtho2D(0, 1, 0, 1); https://www.opengl.org/sdk/docs/man2/xhtml/gluOrtho2D.xml {$ENDIF} glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); //glDisable(GL_TEXTURE_2D); //STEP 1: run smooth program gradientTexture -> tempTex3D tempTex3D := bindBlankGL(lTex); //glUseProgramObjectARB(gRayCast.glslprogramBlur); glUseProgram(gRayCast.glslprogramBlur); glActiveTexture( GL_TEXTURE1); //glBindTexture(GL_TEXTURE_3D, gRayCast.gradientTexture3D);//input texture if lIsOverlay then glBindTexture(GL_TEXTURE_3D, gRayCast.intensityOverlay3D)//input texture is overlay else glBindTexture(GL_TEXTURE_3D, gRayCast.intensityTexture3D);//input texture is background //glEnable(GL_TEXTURE_2D); //glDisable(GL_TEXTURE_2D); glUniform1ix(gRayCast.glslprogramBlur, 'intensityVol', 1); //glUniform1fx(gRayCast.glslprogramBlur, 'dX', 0.5/lTex.FiltDim[1]); //0.5 for smooth - center contributes //glUniform1fx(gRayCast.glslprogramBlur, 'dY', 0.5/lTex.FiltDim[2]); //glUniform1fx(gRayCast.glslprogramBlur, 'dZ', 0.5/lTex.FiltDim[3]); glUniform1fx(gRayCast.glslprogramBlur, 'dX', 0.7/lTex.FiltDim[1]); //0.5 for smooth - center contributes glUniform1fx(gRayCast.glslprogramBlur, 'dY', 0.7/lTex.FiltDim[2]); glUniform1fx(gRayCast.glslprogramBlur, 'dZ', 0.7/lTex.FiltDim[3]); for i := 0 to (lTex.FiltDim[3]-1) do begin coordZ := 1/lTex.FiltDim[3] * (i + 0.5); glUniform1fx(gRayCast.glslprogramBlur, 'coordZ', coordZ); //glFramebufferTexture3D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, tempTex3D, 0, i);//output texture //Ext required: Delphi compile on Winodws 32-bit XP with NVidia 8400M glFramebufferTexture3DExt(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, tempTex3D, 0, i);//output texture glClear(GL_DEPTH_BUFFER_BIT); // clear depth bit (before render every layer) glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(1.0, 0); glVertex2f(1.0, 0.0); glTexCoord2f(1.0, 1.0); glVertex2f(1.0, 1.0); glTexCoord2f(0, 1.0); glVertex2f(0.0, 1.0); glEnd(); end; glUseProgram(0); //STEP 2: run sobel program gradientTexture -> tempTex3D //glUseProgramObjectARB(gRayCast.glslprogramSobel); glUseProgram(gRayCast.glslprogramSobel); glActiveTexture(GL_TEXTURE1); //x glBindTexture(GL_TEXTURE_3D, gRayCast.intensityTexture3D);//input texture glBindTexture(GL_TEXTURE_3D, tempTex3D);//input texture // glEnable(GL_TEXTURE_2D); // glDisable(GL_TEXTURE_2D); glUniform1ix(gRayCast.glslprogramSobel, 'intensityVol', 1); //glUniform1fx(gRayCast.glslprogramSobel, 'dX', 1.0/lTex.FiltDim[1] ); //1.0 for SOBEL - center excluded //glUniform1fx(gRayCast.glslprogramSobel, 'dY', 1.0/lTex.FiltDim[2]); //glUniform1fx(gRayCast.glslprogramSobel, 'dZ', 1.0/lTex.FiltDim[3]); glUniform1fx(gRayCast.glslprogramSobel, 'dX', 1.2/lTex.FiltDim[1] ); //1.0 for SOBEL - center excluded glUniform1fx(gRayCast.glslprogramSobel, 'dY', 1.2/lTex.FiltDim[2]); glUniform1fx(gRayCast.glslprogramSobel, 'dZ', 1.2/lTex.FiltDim[3]); //for i := 0 to (dim3-1) do begin // glColor4f(0.7,0.3,0.2, 0.7); for i := 0 to (lTex.FiltDim[3]-1) do begin coordZ := 1/lTex.FiltDim[3] * (i + 0.5); glUniform1fx(gRayCast.glslprogramSobel, 'coordZ', coordZ); (*Ext required: Delphi compile on Winodws 32-bit XP with NVidia 8400M if lIsOverlay then glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, gRayCast.gradientOverlay3D, 0, i) else glFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, gRayCast.gradientTexture3D, 0, i);*) if lIsOverlay then glFramebufferTexture3DExt(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, gRayCast.gradientOverlay3D, 0, i)//output is overlay else glFramebufferTexture3DExt(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_3D, gRayCast.gradientTexture3D, 0, i);//output is background glClear(GL_DEPTH_BUFFER_BIT); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2f(0, 0); glTexCoord2f(1.0, 0); glVertex2f(1.0, 0.0); glTexCoord2f(1.0, 1.0); glVertex2f(1.0, 1.0); glTexCoord2f(0, 1.0); glVertex2f(0.0, 1.0); glEnd(); end; glUseProgram(0); //clean up: glDeleteTextures(1,@tempTex3D); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glDeleteFramebuffersEXT(1, @fb); glActiveTexture( GL_TEXTURE0 ); //required if we will draw 2d slices next end; procedure doShaderBlurSobel (var lTex: TTexture); var startTime: DWord; begin if (not lTex.updateBackgroundGradientsGLSL) and (not lTex.updateOverlayGradientsGLSL) then exit; //crapGL(lTex); exit; if (gRayCast.glslprogramBlur = 0) then gRayCast.glslprogramBlur := initVertFrag('',kSmoothShaderFrag); //initFragShader (kSmoothShaderFrag,gRayCast.glslprogramBlur); if (gRayCast.glslprogramSobel = 0) then gRayCast.glslprogramSobel := initVertFrag('',kSobelShaderFrag); //initFragShader (kSobelShaderFrag,gRayCast.glslprogramSobel ); if (lTex.updateBackgroundGradientsGLSL) then begin startTime := gettickcount; performBlurSobel(lTex, false); lTex.updateBackgroundGradientsGLSL := false; if gPrefs.Debug then GLForm1.Caption := 'GLSL gradients '+inttostr(gettickcount-startTime)+' ms '; end; if (lTex.updateOverlayGradientsGLSL) then begin performBlurSobel(lTex, true); lTex.updateOverlayGradientsGLSL := false; end; end; procedure enableRenderbuffers; begin glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, gRayCast.frameBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, gRayCast.renderBuffer); end; procedure disableRenderBuffers; begin glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); end; procedure drawVertex(x,y,z: single); begin glColor3f(x,y,z); glMultiTexCoord3f(GL_TEXTURE1, x, y, z); glVertex3f(x,y,z); end; procedure drawQuads(x,y,z: single); //x,y,z typically 1. // useful for clipping // If x=0.5 then only left side of texture drawn // If y=0.5 then only posterior side of texture drawn // If z=0.5 then only inferior side of texture drawn begin glBegin(GL_QUADS); //* Back side glNormal3f(0.0, 0.0, -1.0); drawVertex(0.0, 0.0, 0.0); drawVertex(0.0, y, 0.0); drawVertex(x, y, 0.0); drawVertex(x, 0.0, 0.0); //* Front side glNormal3f(0.0, 0.0, 1.0); drawVertex(0.0, 0.0, z); drawVertex(x, 0.0, z); drawVertex(x, y, z); drawVertex(0.0, y, z); //* Top side glNormal3f(0.0, 1.0, 0.0); drawVertex(0.0, y, 0.0); drawVertex(0.0, y, z); drawVertex(x, y, z); drawVertex(x, y, 0.0); //* Bottom side glNormal3f(0.0, -1.0, 0.0); drawVertex(0.0, 0.0, 0.0); drawVertex(x, 0.0, 0.0); drawVertex(x, 0.0, z); drawVertex(0.0, 0.0, z); //* Left side glNormal3f(-1.0, 0.0, 0.0); drawVertex(0.0, 0.0, 0.0); drawVertex(0.0, 0.0, z); drawVertex(0.0, y, z); drawVertex(0.0, y, 0.0); //* Right side glNormal3f(1.0, 0.0, 0.0); drawVertex(x, 0.0, 0.0); drawVertex(x, y, 0.0); drawVertex(x, y, z); drawVertex(x, 0.0, z); glEnd(); end; function LoadStr (lFilename: string): string; var myFile : TextFile; text : string; begin result := ''; if not fileexists(lFilename) then begin showDebug('Unable to find '+lFilename); //GLForm1.ShowmessageError('Unable to find '+lFilename); exit; end; AssignFile(myFile,lFilename); Reset(myFile); while not Eof(myFile) do begin ReadLn(myFile, text); result := result+text+#13#10; end; CloseFile(myFile); end; procedure reshapeOrtho(w,h: integer); begin if (h = 0) then h := 1; glViewport(0, 0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); {$IFDEF DGL} gluOrtho2D(0, 1, 0, 1.0); {$ELSE} glOrtho (0, 1,0, 1, -1, 1); //https://www.opengl.org/sdk/docs/man2/xhtml/gluOrtho2D.xml {$ENDIF} glMatrixMode(GL_MODELVIEW);//? end; {$IFNDEF DGL} //glext does not link to the glu functions, so we will write our own procedure gluPerspective (fovy, aspect, zNear, zFar: single); //https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml var i, j : integer; f: single; m : array [0..3, 0..3] of single; begin for i := 0 to 3 do for j := 0 to 3 do m[i,j] := 0; f := cot(degtorad(fovy)/2); m[0,0] := f/aspect; m[1,1] := f; m[2,2] := (zFar+zNear)/(zNear-zFar) ; m[3,2] := (2*zFar*zNear)/(zNear-zFar); m[2,3] := -1; //glLoadMatrixf(@m[0,0]); glMultMatrixf(@m[0,0]); //raise an exception if zNear = 0?? end; {$ENDIF} procedure resize(w,h, zoom, zoomOffsetX, zoomOffsetY: integer); var whratio,scale: single; begin if (h = 0) then h := 1; if zoom > 1 then glViewport(zoomOffsetX, zoomOffsetY, w*zoom, h*zoom) else glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if gPrefs.Perspective then gluPerspective(40.0, w/h, 0.01, kMaxDistance{Distance}) else begin if gRayCast.Distance = 0 then scale := 1 else scale := 1/abs(kDefaultDistance/(gRayCast.Distance+1.0)); whratio := w/h; glOrtho(whratio*-0.5*scale,whratio*0.5*scale,-0.5*scale,0.5*scale, 0.01, kMaxDistance); end; glMatrixMode(GL_MODELVIEW);//? end; procedure InitGL (InitialSetup: boolean);// (var lTex: TTexture); begin glEnable(GL_CULL_FACE); glClearColor(gPrefs.BackColor.rgbRed/255,gPrefs.BackColor.rgbGreen/255,gPrefs.BackColor.rgbBlue/255, 0); //initShaderWithFile('xrc.vert', 'xrc.frag',gRayCast.glslprogramGradient); // Load the vertex and fragment raycasting programs //initShaderWithFile('rc.vert', 'rc.frag',gRayCast.glslprogram); if (gRayCast.glslprogram <> 0) then begin glDeleteProgram(gRayCast.glslprogram); gRayCast.glslprogram := 0; end; gRayCast.glslprogram := initVertFrag(gShader.VertexProgram, gShader.FragmentProgram); if (gRayCast.glslprogram = 0) then begin //error: load default shader gShader := LoadShader(''); gRayCast.glslprogram := initVertFrag(gShader.VertexProgram, gShader.FragmentProgram); end; // Create the to FBO's one for the backside of the volumecube and one for the finalimage rendering if InitialSetup then begin glGenFramebuffersEXT(1, @gRayCast.frameBuffer); glGenTextures(1, @gRayCast.backFaceBuffer); glGenTextures(1, @gRayCast.finalImage); glGenRenderbuffersEXT(1, @gRayCast.renderBuffer); gShader.Vendor:= gpuReport; end; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,gRayCast.frameBuffer); glBindTexture(GL_TEXTURE_2D, gRayCast.backFaceBuffer); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F_ARB, gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, nil); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, gRayCast.backFaceBuffer, 0); glBindTexture(GL_TEXTURE_2D, gRayCast.finalImage); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA16F_ARB, gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, nil); //These next lines moved to DisplayGZz for VirtualBox compatibility glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, gRayCast.renderBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, gRayCast.renderBuffer); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); end; procedure drawUnitQuad; //stretches image in view space. begin glDisable(GL_DEPTH_TEST); glBegin(GL_QUADS); glTexCoord2f(0,0); glVertex2f(0,0); glTexCoord2f(1,0); glVertex2f(1,0); glTexCoord2f(1, 1); glVertex2f(1, 1); glTexCoord2f(0, 1); glVertex2f(0, 1); glEnd(); glEnable(GL_DEPTH_TEST); end; // display the final image on the screen procedure renderBufferToScreen; begin glClear( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,gRayCast.finalImage); //use next line instead of previous to illustrate one-pass rendering //glBindTexture(GL_TEXTURE_2D,backFaceBuffer) reshapeOrtho(gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT); drawUnitQuad(); glDisable(GL_TEXTURE_2D); end; // render the backface to the offscreen buffer backFaceBuffer procedure renderBackFace(var lTex: TTexture); begin glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, gRayCast.backFaceBuffer, 0); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); glMatrixMode(GL_MODELVIEW); glScalef(lTex.Scale[1],lTex.Scale[2],lTex.Scale[3]); drawQuads(1.0,1.0,1.0); glDisable(GL_CULL_FACE); end; procedure uniform1f( name: AnsiString; value: single ); begin glUniform1f(glGetUniformLocation(gRayCast.GLSLprogram, pAnsiChar(Name)), value) ; end; procedure uniform1i( name: AnsiString; value: integer); begin glUniform1i(glGetUniformLocation(gRayCast.GLSLprogram, pAnsiChar(Name)), value) ; end; procedure uniform3fv( name: AnsiString; v1,v2,v3: single); begin glUniform3f(glGetUniformLocation(gRayCast.GLSLprogram, pAnsiChar(Name)), v1,v2,v3) ; end; function lerp (p1,p2,frac: single): single; begin result := round(p1 + frac * (p2 - p1)); end;//linear interpolation function ComputeStepSize (Quality1to10: integer): single; var f: single; begin f := Quality1to10; if f <= 1 then f := 0.25; if f > 10 then f := 10; f := f/10; f := lerp (gRayCast.slices*0.25,gRayCast.slices*2.0,f); if f < 10 then f := 10; result := 1/f; //glForm1.Caption := floattostr(gRayCast.slices); end; FUNCTION Defuzz(CONST x: DOUBLE): DOUBLE; const fuzz : double = 1.0E-6; BEGIN IF ABS(x) < fuzz THEN RESULT := 0.0 ELSE RESULT := x END {Defuzz}; procedure sph2cartDeg90(Azimuth,Elevation: single; var lX,lY,lZ: single); //convert spherical AZIMUTH,ELEVATION,RANGE to Cartesion //see Matlab's [x,y,z] = sph2cart(THETA,PHI,R) // reverse with cart2sph var E,Phi,Theta: single; begin E := Azimuth; while E < 0 do E := E + 360; while E > 360 do E := E - 360; Theta := DegToRad(E); E := Elevation; while E > 90 do E := E - 90; while E < -90 do E := E + 90; Phi := DegToRad(E); lX := cos(Phi)*cos(Theta); lY := cos(Phi)*sin(Theta); lZ := sin(Phi); end; procedure LightUniforms; var lA,lB,lC, lX,lY,lZ: single; lMgl: array[0..15] of GLfloat; begin sph2cartDeg90(gRayCast.LightAzimuth,gRayCast.LightElevation,lX,lY,lZ); if gPrefs.RayCastViewCenteredLight then begin //Could be done in GLSL with following lines of code, but would be computed once per pixel, vs once per volume //vec3 lightPosition = normalize(gl_ModelViewMatrixInverse * vec4(lightPosition,0.0)).xyz ; glGetFloatv(GL_TRANSPOSE_MODELVIEW_MATRIX, @lMgl); lA := lY; lB := lZ; lC := lX; lX := defuzz(lA*lMgl[0]+lB*lMgl[4]+lC*lMgl[8]); lY := defuzz(lA*lMgl[1]+lB*lMgl[5]+lC*lMgl[9]); lZ := defuzz(lA*lMgl[2]+lB*lMgl[6]+lC*lMgl[10]); end; lA := sqrt(sqr(lX)+sqr(lY)+Sqr(lZ)); if lA > 0 then begin //normalize lX := lX/lA; lY := lY/lA; lZ := lZ/lA; end; uniform3fv('lightPosition',lX,lY,lZ); end; procedure sph2cartDeg90x(Azimuth,Elevation,R: single; var lX,lY,lZ: single); //convert spherical AZIMUTH,ELEVATION,RANGE to Cartesion //see Matlab's [x,y,z] = sph2cart(THETA,PHI,R) // reverse with cart2sph var n: integer; E,Phi,Theta: single; begin Theta := DegToRad(Azimuth-90); E := Elevation; if (E > 360) or (E < -360) then begin n := trunc(E / 360) ; E := E - (n * 360); end; if ((E > 89) and (E < 91)) or (E < -269) and (E > -271) then E := 90; if ((E > 269) and (E < 271)) or (E < -89) and (E > -91) then E := -90; Phi := DegToRad(E); lX := r * cos(Phi)*cos(Theta); lY := r * cos(Phi)*sin(Theta); lZ := r * sin(Phi); end; procedure ClipUniforms; var lD,lX,lY,lZ: single; begin sph2cartDeg90x(gRayCast.ClipAzimuth,gRayCast.ClipElevation,1,lX,lY,lZ); uniform3fv('clipPlane',-lX,-lY,-lZ); if gRaycast.ClipDepth < 1 then lD := -1 else lD := 0.5-(gRayCast.ClipDepth/1000); uniform1f( 'clipPlaneDepth', lD); end; procedure drawFrame(x,y,z: single); //x,y,z typically 1. // useful for clipping // If x=0.5 then only left side of texture drawn // If y=0.5 then only posterior side of texture drawn // If z=0.5 then only inferior side of texture drawn begin glColor4f(1,1,1,1); glBegin(GL_LINE_STRIP); //* Back side //glNormal3f(0.0, 0.0, -1.0); drawVertex(0.0, 0.0, 0.0); drawVertex(0.0, y, 0.0); drawVertex(x, y, 0.0); drawVertex(x, 0.0, 0.0); glEnd; glBegin(GL_LINE_STRIP); //* Front side //glNormal3f(0.0, 0.0, 1.0); drawVertex(0.0, 0.0, z); drawVertex(x, 0.0, z); drawVertex(x, y, z); drawVertex(0.0, y, z); glEnd; glBegin(GL_LINE_STRIP); //* Top side //glNormal3f(0.0, 1.0, 0.0); drawVertex(0.0, y, 0.0); drawVertex(0.0, y, z); drawVertex(x, y, z); drawVertex(x, y, 0.0); glEnd; glColor4f(0.2,0.2,0.2,0); glBegin(GL_LINE_STRIP); //* Bottom side //glNormal3f(0.0, -1.0, 0.0); drawVertex(0.0, 0.0, 0.0); drawVertex(x, 0.0, 0.0); drawVertex(x, 0.0, z); drawVertex(0.0, 0.0, z); glEnd; glColor4f(0,1,0,0); glBegin(GL_LINE_STRIP); //* Left side //glNormal3f(-1.0, 0.0, 0.0); drawVertex(0.0, 0.0, 0.0); drawVertex(0.0, 0.0, z); drawVertex(0.0, y, z); drawVertex(0.0, y, 0.0); glEnd; glColor4f(1,0,0,0); glBegin(GL_LINE_STRIP); //* Right side //glNormal3f(1.0, 0.0, 0.0); drawVertex(x, 0.0, 0.0); drawVertex(x, y, 0.0); drawVertex(x, y, z); drawVertex(x, 0.0, z); glEnd(); end; procedure rayCasting (var lTex: TTexture); begin //glUseProgram(gRayCast.glslprogramGradient); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, gRayCast.finalImage, 0); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); //glEnable(GL_TEXTURE_2D); glActiveTexture( GL_TEXTURE0 ); glBindTexture(GL_TEXTURE_2D, gRayCast.backFaceBuffer); glActiveTexture( GL_TEXTURE1 ); glBindTexture(GL_TEXTURE_3D,gRayCast.gradientTexture3D); {$IFDEF USETRANSFERTEXTURE} glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_1D, gRayCast.TransferTexture1); {$ENDIF} glActiveTexture( GL_TEXTURE3 ); glBindTexture(GL_TEXTURE_3D,gRayCast.intensityTexture3D); if (gShader.OverlayVolume > 0) then begin glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_3D,gRayCast.intensityOverlay3D); if (gShader.OverlayVolume > 1) then begin glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_3D,gRayCast.gradientOverlay3D); end; end; glUseProgram(gRayCast.glslprogram); uniform1i( 'loops',round(gRayCast.slices*2.2)); if gRayCast.ScreenCapture then uniform1f( 'stepSize', ComputeStepSize(10) ) else uniform1f( 'stepSize', ComputeStepSize(gPrefs.RayCastQuality1to10) ); uniform1f( 'sliceSize', 1/gRayCast.slices ); uniform1f( 'viewWidth', gRayCast.WINDOW_WIDTH ); uniform1f( 'viewHeight', gRayCast.WINDOW_HEIGHT ); uniform1i( 'backFace', 0 ); // backFaceBuffer -> texture0 uniform1i( 'gradientVol', 1 ); // gradientTexture -> texture2 {$IFDEF USETRANSFERTEXTURE} uniform1i( 'TransferTexture',2); //used when render volumes are scalar, not RGBA{$ENDIF} {$ENDIF} uniform1i( 'intensityVol', 3 ); uniform1i( 'overlayVol', 4 ); uniform1i( 'overlayGradientVol', 5 ); uniform1i( 'overlays', gOpenOverlays); if lTex.DataType = GL_RGBA then uniform1i( 'useTransferTexture',0) else uniform1i( 'useTransferTexture',1); AdjustShaders(gShader); LightUniforms; ClipUniforms; uniform3fv('clearColor',gPrefs.BackColor.rgbRed/255,gPrefs.BackColor.rgbGreen/255,gPrefs.BackColor.rgbBlue/255); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glMatrixMode(GL_MODELVIEW); glScalef(1,1,1); drawQuads(1.0,1.0,1.0); glDisable(GL_CULL_FACE); glUseProgram(0); glActiveTexture( GL_TEXTURE0 ); //glDisable(GL_TEXTURE_2D); end; procedure MakeCube(sz: single); var sz2: single; begin sz2 := sz; glColor4f(0.1,0.1,0.1,1); glBegin(GL_QUADS); //* Bottom side glVertex3f(-sz, -sz, -sz2); glVertex3f(-sz, sz, -sz2); glVertex3f(sz, sz, -sz2); glVertex3f(sz, -sz, -sz2); glEnd; glColor4f(0.8,0.8,0.8,1); glBegin(GL_QUADS); //* Top side glVertex3f(-sz, -sz, sz2); glVertex3f(sz, -sz, sz2); glVertex3f(sz, sz, sz2); glVertex3f(-sz, sz, sz2); glEnd; glColor4f(0,0,0.4,1); glBegin(GL_QUADS); //* Front side glVertex3f(-sz, sz2, -sz); glVertex3f(-sz, sz2, sz); glVertex3f(sz, sz2, sz); glVertex3f(sz, sz2, -sz); glEnd; glColor4f(0.2,0,0.2,1); glBegin(GL_QUADS); //* Back side glVertex3f(-sz, -sz2, -sz); glVertex3f(sz, -sz2, -sz); glVertex3f(sz, -sz2, sz); glVertex3f(-sz, -sz2, sz); glEnd; glColor4f(0.6,0,0,1); glBegin(GL_QUADS); //* Left side glVertex3f(-sz2, -sz, -sz); glVertex3f(-sz2, -sz, sz); glVertex3f(-sz2, sz, sz); glVertex3f(-sz2, sz, -sz); glEnd; glColor4f(0,0.6,0,1); glBegin(GL_QUADS); //* Right side //glNormal3f(1.0, -sz, -sz); glVertex3f(sz2, -sz, -sz); glVertex3f(sz2, sz, -sz); glVertex3f(sz2, sz, sz); glVertex3f(sz2, -sz, sz); glEnd(); end; procedure DrawCube (lScrnWid, lScrnHt, zoomOffsetX, zoomOffsetY: integer); var mn: integer; sz: single; begin mn := lScrnWid; if mn > lScrnHt then mn := lScrnHt; if mn < 10 then exit; sz := mn * 0.03; // glEnable(GL_CULL_FACE); // <- required for Cocoa glDisable(GL_DEPTH_TEST); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho (0, gRayCast.WINDOW_WIDTH,0, gRayCast.WINDOW_Height,-10*sz,10*sz); glEnable(GL_DEPTH_TEST); glDisable (GL_LIGHTING); glDisable (GL_BLEND); glTranslatef(1.8*sz,1.8*sz,0); glTranslatef(zoomOffsetX, zoomOffsetY, 0); glRotatef(90-gRayCast.Elevation,-1,0,0); glRotatef(gRayCast.Azimuth,0,0,1); MakeCube(sz); //glDisable(GL_DEPTH_TEST); //glDisable(GL_CULL_FACE); // <- required for Cocoa end; (*procedure DisplayGLz(var lTex: TTexture; zoom, zoomOffsetX, zoomOffsetY: integer); //Redraw image using ray casting begin //these next lines only required when switching from texture slicing glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, gRayCast.frameBuffer); glMatrixMode( GL_TEXTURE ); glLoadIdentity(); glDisable(GL_TEXTURE_3D); //raycasting follows glClearColor(gPrefs.BackColor.rgbRed/255,gPrefs.BackColor.rgbGreen/255,gPrefs.BackColor.rgbBlue/255, 0); resize(gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT,zoom, zoomOffsetX, zoomOffsetY); glBindFramebufferEXT (GL_FRAMEBUFFER_EXT, gRayCast.frameBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, gRayCast.renderBuffer); glTranslatef(0,0,-gRayCast.Distance); glRotatef(90-gRayCast.Elevation,-1,0,0); glRotatef(gRayCast.Azimuth,0,0,1); glTranslatef(-lTex.Scale[1]/2,-lTex.Scale[2]/2,-lTex.Scale[3]/2); //glScalef(Zoom,Zoom,Zoom); renderBackFace(lTex); rayCasting(lTex); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);//disable framebuffer renderBufferToScreen(); //next, you will need to execute SwapBuffers end; *) procedure DisplayGLz(var lTex: TTexture; zoom, zoomOffsetX, zoomOffsetY: integer); begin //if (gPrefs.SliceView = 5) and (length(gRayCast.MosaicString) < 1) then exit; //we need to draw something, otherwise swapbuffer crashes if (gPrefs.SliceView <> 5) then gRayCast.MosaicString := ''; doShaderBlurSobel(lTex); glClearColor(gPrefs.BackColor.rgbRed/255,gPrefs.BackColor.rgbGreen/255,gPrefs.BackColor.rgbBlue/255, 0); resize(gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT,zoom, zoomOffsetX, zoomOffsetY); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, gRayCast.renderBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT); //required by VirtualBox {$IFDEF ENABLEMOSAICS} if length(gRayCast.MosaicString)> 0 then begin //draw mosaics glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glDisable(GL_CULL_FACE); //<-this is important, otherwise nodes and quads not filled MosaicGL(gRayCast.MosaicString); end else {$ENDIF} if gPrefs.SliceView > 0 then begin //draw 2D orthogonal slices glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ); glDisable(GL_CULL_FACE); //<-this is important, otherwise nodes and quads not filled DrawOrtho(lTex); end else begin //else draw 3D rendering enableRenderbuffers(); glTranslatef(0,0,-gRayCast.Distance); glRotatef(90-gRayCast.Elevation,-1,0,0); glRotatef(gRayCast.Azimuth,0,0,1); glTranslatef(-lTex.Scale[1]/2,-lTex.Scale[2]/2,-lTex.Scale[3]/2); renderBackFace(lTex); rayCasting(lTex); disableRenderBuffers(); renderBufferToScreen(); if gPrefs.SliceDetailsCubeAndText then drawCube(gRayCast.WINDOW_WIDTH*zoom, gRayCast.WINDOW_HEIGHT*zoom, zoomOffsetX, zoomOffsetY); resize(gRayCast.WINDOW_WIDTH, gRayCast.WINDOW_HEIGHT,zoom, zoomOffsetX, zoomOffsetY); end; if gPrefs.ColorEditor then DrawNodes(gRayCast.WINDOW_HEIGHT,gRayCast.WINDOW_WIDTH, lTex, gPrefs); if gPrefs.Colorbar then DrawCLUT( gPrefs.ColorBarPos,0.01, gPrefs);//, gRayCast.WINDOW_WIDTH*zoom, gRayCast.WINDOW_HEIGHT*zoom, zoomOffsetX, zoomOffsetY); {$IFDEF ENABLEWATERMARK} if gWatermark.filename <> '' then LoadWatermark(gWatermark); if gWatermark.Ht > 0 then DrawWatermark(gWatermark.X,gWatermark.Y,gWatermark.Wid,gWatermark.Ht,gWatermark); {$ENDIF} glDisable (GL_BLEND); //just in case one of the previous functions forgot... glFlush;//<-this would pause until all jobs are SUBMITTED //glFinish;//<-this would pause until all jobs finished: generally a bad idea! //next, you will need to execute SwapBuffers end; procedure DisplayGL(var lTex: TTexture); begin DisplayGLz(lTex,1,0,0); end; initialization with gRayCast do begin OrthoZoom := 1.0; OrthoX := 0.5; OrthoY := 0.5; OrthoZ := 0.5; MosaicString:=''; ModelessString := ''; ScreenCapture := false; ModelessColor := RGBA(192,192,192,255); LightAzimuth := 0; LightElevation := 70; ClipAzimuth := 180; ClipElevation := 0; ClipDepth := 0; Azimuth := 110; Elevation := 15; Distance := kDefaultDistance; slices := 256; gradientTexture3D := 0; intensityTexture3D := 0; intensityOverlay3D := 0; gradientOverlay3D := 0; glslprogram := 0; glslprogramBlur := 0; glslprogramSobel := 0; finalImage := 0; renderBuffer := 0; frameBuffer := 0; backFaceBuffer := 0; end;//set gRayCast defaults end.
unit ucFORM; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FMTBcd, DB, DBClient, Provider, SqlExpr, DBGrids, Grids, ToolWin, ComCtrls, StdCtrls, ExtCtrls, StrUtils, DBCtrls, ucCOMP, Menus, TypInfo, Math, ucCOMPPESQ, ucCONFCAMPO, ucCONFCAMPOJSON, ucCONFCAMPOMET; const TAG_OCULTO = -1; TAG_NORMAL = 0; TAG_PK = 1; TAG_FK = 2; TAG_READONLY = 3; TAG_PFK = 4; TAG_LK = 5; // LookUp BTN_HABILITA = 1; BTN_NAO_HABILITA = 0; REG_LIMPO = 00; REG_TOTAL = 30; wEscala = 08; hEscala = 21; wRecuo = 10; hRecuo = 10; linRecuo = 03; colRecuo = 03; larLabel = 100; type TModoFormulario = (mfConsultaSomente, mfConsulta, mfConsultaManutencao, mfManutencao, mfAlteracaoSomente); TTipoClasseForm = (tcfCadastro, tcfConsulta, tcfManutencao); TcFORM = class(TForm) _Query: TSqlQuery; _Provider: TDataSetProvider; _DataSet: TClientDataSet; _DataSource: TDataSource; EditCancel: TEdit; _CoolBar: TCoolBar; _ToolBar: TToolBar; ToolButtonFechar: TToolButton; _CoolBarAtalho: TCoolBar; _ToolBarAtalho: TToolBar; ToolButtonFechar1: TToolButton; _PopupMenu: TPopupMenu; bConsultaLog: TMenuItem; bObservacao: TMenuItem; bConfigurarManutencao: TMenuItem; bMoverCampo: TMenuItem; bAjustarCampo: TMenuItem; bConfigurarRelatorio: TMenuItem; bCampoDescricao: TMenuItem; procedure ColorControl(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormResize(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure p_LerIni; procedure CarregarConfCampoList; procedure p_Consultar(pSql : String; TOT_REG : Integer = REG_TOTAL); function f_VerObrigatorio : Boolean; procedure p_SetarDescr(pEditDes : TEdit; pModoFormulario : TModoFormulario); procedure p_CriarCampos(pParent : TWinControl); procedure p_AjustarCampos(pParent : TWinControl); procedure EditEnter(Sender: TObject); procedure EditExit(Sender: TObject); procedure EditExitVal(Sender: TObject); procedure EditExitCad(Sender: TObject); procedure EditKeyPressCad(Sender: TObject; var Key: Char); procedure EditDblClick(Sender: TObject); procedure EditChange(Sender: TObject); procedure EditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure EditGravarDef(); procedure EditAjuste(Sender: TObject); procedure p_CorrigeEditFkTela; procedure _DataSetAfterPost(DataSet: TDataSet); procedure _DataSetBeforePost(DataSet: TDataSet); procedure p_CarregarCampos(vCampo : String = ''); procedure p_DesCarregarCampos(vCampo : String = ''); procedure _DataSetAfterOpen(DataSet: TDataSet); procedure _DataSetAfterEdit(DataSet: TDataSet); procedure _DataSetNewRecord(DataSet: TDataSet); procedure _DataSetGetText_FK(Sender: TField; var Text: String; DisplayText: Boolean); procedure _DataSetGetText_IN(Sender: TField; var Text: String; DisplayText: Boolean); procedure _DataSetGetText_TP(Sender: TField; var Text: String; DisplayText: Boolean); function f_ConsultarChave : Boolean; function f_GerarChave(vParcial : Boolean = True) : String; procedure p_HabilitaChave(Tipo : Boolean); procedure p_GravarRegistro; procedure p_CarregaRegistro; procedure DBGrid1TitleClick(Column: TColumn); procedure DBGrid1DblClick(Sender: TObject); procedure DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); function f_ObterFiltroSql : String; procedure TP_CONSULTAExit(Sender: TObject); procedure CD_CAMPOChange(Sender: TObject); procedure CD_CAMPOExit(Sender: TObject); procedure fDS_EXPRESSAOExit(Sender: TObject); procedure fDS_EXPRESSAOKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure p_CarreTabela(vStringGrid : TStringGrid); procedure p_CriarTabela(pParent : TWinControl); procedure p_LimpaTabela(vStringGrid : TStringGrid); procedure p_MontaTabela; procedure StringGridDblClick(Sender: TObject); procedure ToolButtonFecharClick(Sender: TObject); procedure p_CriarAtalho; procedure ToolButtonClick(Sender: TObject); procedure bConsultaLogClick(Sender: TObject); procedure bObservacaoClick(Sender: TObject); procedure bConfigurarManutencaoClick(Sender: TObject); procedure bConfigurarRelatorioClick(Sender: TObject); procedure bMoverCampoClick(Sender: TObject); procedure bAjustarCampoClick(Sender: TObject); procedure bCampoDescricaoClickLoad(Sender: TObject; pHint : String); procedure bCampoDescricaoClick(Sender: TObject); private FInEditGravarDef : Boolean; FCaption, FCaptionRel : String; FTabMan, FKeyMan, FIncMan, FColMan, FValMan : String; function GetTabMan: String; function GetKeyMan: String; function GetIncMan: String; function GetValMan: String; procedure SetCaption(const Value: String); procedure SetCaptionRel(const Value: String); function GetColMan: String; procedure SetTabMan(const Value: String); protected FConfCampoList : TcCONFCAMPOLIST; function ClickButton(pName : String) : Boolean; public cModoFormulario : TModoFormulario; cTipoClasseForm : TTipoClasseForm; bClrSis, // Cor sistema bCpoMan, // Campo Fk bGrdMan, // Grid F10 bDplMan, // Duplo click F12 bCtrMan, // Tela centralizada bAutMan : Boolean; // Consulta auto cTB, // Campo tabela cTR : String; // Texto relatorio cRegMan, // Registro manutencao cLogMan, // Log manutencao cSql, // Comando sql cAtaMan, // Atalho de tela cNomTab, // Nome tabela filha cAltTab, // Altura tabela filha cLarTab, // Largura tabela filha cDesCns, // Descricao consulta cOrdCns : String; // Ordenacao consulta iTop, iLeft, iAltura, iLargura : Integer; Capturing : bool; MouseDownSpot : TPoint; FParams, FResult, FFiltro : String; FInImprimindo : Boolean; published property _Caption : String read FCaption write SetCaption; property _CaptionRel : String read FCaptionRel write SetCaptionRel; property _TabMan : String read GetTabMan write SetTabMan; property _KeyMan : String read GetKeyMan write FKeyMan; property _IncMan : String read GetIncMan write FIncMan; property _ValMan : String read GetValMan write FValMan; property _ColMan : String read GetColMan write FColMan; property _Params : String read FParams write FParams; property _Filtro : String read FFiltro write FFiltro; property _Result : String read FResult write FResult; class function execute(pParams : String) : String; end; implementation {$R *.dfm} uses ucCADASTROFUNC, ucFUNCAO, ucITEM, ucDADOS, ucMENU, ucCONST, ucOBS, ucXML, ucLOGALTERACAO, ucSELECT, ucMETADATA, ucCONFMANUT, ucCONFRELAT; procedure TcFORM.p_LerIni; begin bClrSis := IfNullB(LerIni(CLR_SIS), True); bCtrMan := IfNullB(LerIni(CTR_MAN), True); bAutMan := IfNullB(LerIni(_Caption, AUT_MAN), False); bDplMan := IfNullB(LerIni(_Caption, DPL_MAN), False); iAltura := IfNullI(LerIni(_Caption, ALT_MAN), 0); iLargura := IfNullI(LerIni(_Caption, LAR_MAN), 0); cAtaMan := IfNullS(LerIni(_Caption, ATA_MAN), cAtaMan); bAjustarCampo.Checked := IfNullB(LerIni(_Caption, RED_MAN), False); bCampoDescricaoClickLoad(bCampoDescricao, CAD_DES); end; function TcFORM.ClickButton(pName : String) : Boolean; var vToolButton : TToolButton; begin Result := False; vToolButton := TToolButton(FindComponent(pName)); if (vToolButton = nil) then Exit; with vToolButton do begin if (Enabled) and (Visible) then begin Result := True; Click; end; end; end; //-- class function TcFORM.execute(pParams : String) : String; begin Result := ''; Application.CreateForm(TComponentClass(Self), Self); with TcFORM(Self) do begin _Params := pParams; if (ShowModal = mrOK) then begin Result := _Result; end; end; end; procedure TcFORM.ColorControl(Sender: TObject); var Cor: TColor; I: integer; begin if Screen.ActiveForm = nil then Exit; with Screen.ActiveForm do begin for I := 0 to ComponentCount-1 do begin if (Components[I] is TCustomEdit) then begin if TCustomEdit(Components[I]).TabStop then begin if TCustomEdit(Components[I]).Focused then Cor := clYellow else Cor := clWindow; p_SetPropValue(Components[I], 'Color', IntToStr(Cor)); end; end; end; end; end; procedure TcFORM.FormCreate(Sender: TObject); begin _Query.SQLConnection := dDADOS._Conexao; _ToolBar.Images := dDADOS._ImageList; bConfigurarManutencao.Visible := FileExists(CFG_SIS); bConfigurarRelatorio.Visible := FileExists(REL_SIS); FConfCampoList := TcCONFCAMPOLIST.Create(); end; procedure TcFORM.FormShow(Sender: TObject); var I : Integer; begin p_LerIni; if BorderStyle in [bsSizeable] then if (iAltura > 0) and (iLargura > 0) then begin Height := iAltura * 21; Width := iLargura * 8; if bCtrMan then begin Top := (Screen.Height div 2) - (Height div 2); Left := (Screen.Width div 2) - (Width div 2); end; end else begin Top := 25; Left := 0; Width := Screen.WorkAreaWidth; Height := Screen.WorkAreaHeight - 25; end; for I := 0 to ComponentCount - 1 do if (Components[I] is TDBGrid) then begin with TDBGrid(Components[I]) do begin onDrawColumnCell := TcCADASTROFUNC.onDrawColumnCell; onTitleClick := DBGrid1TitleClick; onDblClick := DBGrid1DblClick; onKeyDown := DBGrid1KeyDown; end; end; if (bClrSis) then Screen.OnActiveControlChange := ColorControl; p_CorrigeEditFkTela; p_CriarAtalho; TcCADASTROFUNC.CorrigeDisplayTela(Self); TcCADASTROFUNC.CorrigeShapeTela(Self); TcCADASTROFUNC.CorrigeCarregaImagem(Self); end; procedure TcFORM.FormActivate(Sender: TObject); begin inherited; // TcCADASTROFUNC.PosicaoTela(Self); end; procedure TcFORM.FormKeyPress(Sender: TObject; var Key: Char); begin Key := TiraAcentosChar(UpCase(Key)); end; procedure TcFORM.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var vResult : String; begin if (Key = VK_ESCAPE) then begin if (ActiveControl is TComboBox) then if TComboBox(ActiveControl).DroppedDown then begin TComboBox(ActiveControl).DroppedDown := False; Exit; end; Close; end; if (Key = VK_RETURN) then if (ActiveControl is TMemo) or (ActiveControl is TDBMemo) or (ActiveControl is TStringGrid) or (ActiveControl is TDBGrid) then begin {} end else Perform(WM_NEXTDLGCTL, 0, 0); if (Key = VK_F12) then begin if (ActiveControl is TEdit) then begin with TEdit(ActiveControl) do begin if (Tag = TAG_FK) then begin vResult := cMENU.AbreTela(item('CD_CAMPO', Hint), Text); if (vResult <> '') then Text := vResult; ModalResult := mrNone; Key := 0; end; end; end; end; end; procedure TcFORM.FormResize(Sender: TObject); begin p_AjustarCampos(Self); end; procedure TcFORM.FormClose(Sender: TObject; var Action: TCloseAction); begin Screen.OnActiveControlChange := nil; EditGravarDef(); end; //-- procedure TcFORM.p_Consultar(pSql : String; TOT_REG : Integer = REG_TOTAL); begin _DataSet.PacketRecords := TOT_REG; _DataSet.Close; _Query.Sql.Text := pSql; if LerIniB(TRA_SIS) then p_Grava_Log('Form: ' + _Caption + ' Sql: '+ pSql); _DataSet.Open; end; //-- function TcFORM.f_VerObrigatorio : Boolean; var I : Integer; begin with _DataSet do begin for I := 0 to FieldCount-1 do begin with Fields[I] do begin if (Visible) and (Required) and (AsString='') then begin raise Exception.Create('Campo "' + DisplayLabel + '" é obrigatório!'); end; end; end; end; Result := True; end; //-- procedure TcFORM.p_CriarCampos(pParent : TWinControl); var vLarg, I, J, vTam, vDec, vTag : Integer; vVerFK, vVerLK, vVerCB : String; vComboBox : TcComboBox; vEdit, vEditD : TcEdit; vInCriado : boolean; vLabel : TLabel; vConfCampo : TcCONFCAMPO; begin iTop := hRecuo; iLeft := wRecuo; vTag := TAG_PK; vTam := 0; vDec := 0; with _DataSet do begin for I := 0 to FieldCount-1 do begin with Fields[I] do begin vInCriado := False; vConfCampo := FConfCampoList.Buscar(FieldName); if (FieldName = 'TP_SITUACAO') or not Visible then begin vTag := TAG_NORMAL; vInCriado := True; end; if (_KeyMan <> '') then begin vTag := IfThen(Pos(FieldName, _KeyMan) > 0, TAG_PK, TAG_NORMAL); end; if not vInCriado and (_ColMan <> '') then begin vInCriado := Pos(FieldName, _ColMan) = 0; vTam := vConfCampo.Tamanho; vDec := vConfCampo.Decimal; end; iLeft := wRecuo; if not vInCriado then begin vLabel := TLabel.Create(Self); vLabel.Name := 'label' + FieldName; vLabel.Caption := DisplayLabel + IfThen(Required, ' *', ''); if (Required) then vLabel.Font.Style := vLabel.Font.Style + [fsBold]; vLabel.Parent := pParent; vLabel.Top := iTop; vLabel.Left := iLeft; vLabel.Width := larLabel; vLabel.Transparent := True; vLabel.AutoSize := False; vLabel.Layout := tlCenter; Inc(iLeft, vLabel.Width + colRecuo); if not vInCriado then begin vVerLK := cMENU.f_VerLK(FieldName, _TabMan); if (vVerLK = '') then begin vVerCB := cMENU.f_VerCB(FieldName); end; if (vVerCB <> '') or (vVerLK <> '') then begin vComboBox := TcComboBox.Create(Self); vComboBox.Name := FieldName; vComboBox.Parent := pParent; vComboBox.Height := hEscala; vComboBox.Width := 40 * wEscala; vComboBox.Top := iTop; vComboBox.Left := iLeft; vComboBox.Tag := vTag; vComboBox.Style := csDropDownList; vComboBox._Campo := FieldName; if (vVerLK <> '') then begin dDADOS.p_GeraListaTabela(vComboBox.Items, vVerLK); end else if (vVerCB <> '') then begin vComboBox.p_AddLista(vVerCB); end; vLarg := 0; with vComboBox, vComboBox.Items do for J := 0 to Count-1 do if Length(Items[J]) > vLarg then vLarg := Length(Items[J]); vComboBox.Width := vLarg * wEscala + 30; Inc(iTop, vComboBox.Height + linRecuo); vInCriado := True; end; end; if not vInCriado then begin vEdit := TcEdit.Create(Self); vEdit.Name := FieldName; vEdit.AutoSize := False; vEdit.Parent := pParent; vEdit.Height := hEscala; vEdit.Width := DisplayWidth * wEscala; vEdit.Top := iTop; vEdit.Left := iLeft; vEdit.Tag := vTag; vEdit.Text := ''; vEdit._Campo := FieldName; if (TcCADASTROFUNC.IsFieldAlfa(FieldName, _DataSet)) then begin vEdit.MaxLength := Size; end; if (TcCADASTROFUNC.IsFieldDate(FieldName, _DataSet)) then begin vEdit._TpDado := tpdData; end else if (TcCADASTROFUNC.IsFieldInteger(FieldName, _DataSet)) then begin vEdit._TpDado := tpdInteiro; end else if (TcCADASTROFUNC.IsFieldFloat(FieldName, _DataSet)) then begin vEdit._TpDado := tpdNumero; end else begin vEdit._TpDado := tpdAlfa; end; if (vTam <> 0) then vEdit.Width := vTam * wEscala; if (vDec <> 0) then vEdit.Height := vDec * hEscala; vEdit.OnChange := EditChange; vEdit.OnDblClick := EditDblClick; vEdit.OnEnter := EditEnter; vEdit.OnExit := EditExit; vEdit.OnMouseDown := EditMouseDown; Inc(iTop, vEdit.Height + linRecuo); if ((vEdit.Width + vEdit.Left) > Width) then begin vEdit.Width := Width - vEdit.Left - 100; end; vVerFK := cMENU.f_VerFK(FieldName, _TabMan); if (vVerFK <> '') then begin vEdit.Tag := TAG_FK; vEdit.Hint := vVerFK; vEditD := TcEdit.Create(Self); vEditD.Name := 'd' + FieldName; vEditD.Parent := pParent; vEditD.Height := hEscala; vEditD.Width := (50 * wEscala) - 2; vEditD.Top := vEdit.Top; vEditD.Left := vEdit.Left + vEdit.Width + 2; vEditD.Color := clBtnFace; vEditD.ReadOnly := True; vEditD.TabStop := False; vEditD.Text := ''; if IfNullB(LerIni(_Caption, CAD_DES), False) then begin p_SetarDescr(vEditD, cModoFormulario); end; end; end; end; end; end; end; p_CriarTabela(pParent); end; procedure TcFORM.p_AjustarCampos(pParent : TWinControl); var iLinha, iColuna, iLargura, I : Integer; vCampo, vDescr : TWinControl; vCod, sXY : String; vLabel : TLabel; procedure prcPosicaoAnt(); begin if bAjustarCampo.Checked then begin if (iLeft + iLargura + (larLabel div 2)) > Width then begin Inc(iTop, vCampo.Height + colRecuo); iLeft := wRecuo; end; Exit; end; sXY := LerIni(_Caption, vCampo.Name + 'xy'); iLinha := itemI('NR_LINHA', sXY); iColuna := itemI('NR_COLUNA', sXY); if (iLinha <> 0) then vCampo.Top := iLinha; if (iColuna <> 0) then vCampo.Left := iColuna; end; procedure prcPosicaoPos(); begin if bAjustarCampo.Checked then begin if (iLeft + iLargura + (larLabel div 2)) > Width then begin Inc(iTop, vCampo.Height + colRecuo); iLeft := wRecuo; end else begin Inc(iLeft, iLargura); end; Exit; end; Inc(iTop, vCampo.Height + colRecuo); end; begin if not Visible then Exit; iTop := hRecuo; iLeft := wRecuo; with _DataSet do begin for I:=0 to FieldCount-1 do begin with Fields[I] do begin vCod := FieldName; vLabel := TLabel(Self.FindComponent('label' + vCod)); vCampo := TWinControl(Self.FindComponent(vCod)); vDescr := TWinControl(Self.FindComponent('d' + vCod)); if vCampo = nil then Continue; iLargura := 0; if vLabel <> nil then Inc(iLargura, vLabel.Width + colRecuo); if vCampo <> nil then Inc(iLargura, vCampo.Width + colRecuo); if vDescr <> nil then Inc(iLargura, vDescr.Width + colRecuo); prcPosicaoAnt(); vCampo.Top := iTop; vCampo.Left := iLeft + larLabel; EditAjuste(vCampo); prcPosicaoPos(); end; end; end; end; //-- procedure TcFORM.EditEnter(Sender: TObject); begin // end; procedure TcFORM.EditExit(Sender: TObject); var vEditCod, vEditDes : TEdit; vParams : String; begin vEditCod := TEdit(Sender); if not TcCADASTROFUNC.EditValida(_DataSet, Sender) then Exit; if vEditCod.Tag = TAG_PK then begin if not f_ConsultarChave then begin vEditCod.Text := ''; vEditCod.SetFocus; end else begin Exit; end; end; if (vEditCod.Hint <> '') and (vEditCod.Tag = TAG_FK) then begin vEditDes := TEdit(FindComponent('d' + vEditCod.Name)); if vEditDes <> nil then begin vParams := vEditCod.Hint; putitem(vParams, 'CD_VALUE', vEditCod.Text); vEditDes.Text := dDADOS.f_BuscarDescricao(vParams); end; end; if vEditCod.Name = _ValMan then EditExitVal(Sender); end; procedure TcFORM.EditExitVal(Sender: TObject); var vEditKey, vEditVal : TEdit; vResult, vSql : String; begin if cModoFormulario in [mfConsulta, mfConsultaSomente] then Exit; if (_KeyMan = '') or (_ValMan = '') then Exit; vEditVal := TEdit(Sender); vEditKey := TEdit(FindComponent(_KeyMan)); vSql := 'select * from ' + _TabMan + ' ' + 'where ' + _ValMan + '=''' + vEditVal.Text + ''' ' + 'and ' + _KeyMan + '<>''' + vEditKey.Text + ''' ' ; vResult := dDADOS.f_ConsultaStrSql(vSql, '*'); if item(_KeyMan, vResult) = '' then Exit; if not Pergunta('Registro "' + item(_KeyMan, vResult) + '" já existe cadastrado com a descrição! Deseja carregar ?') then Exit; vEditKey.Text := item(_KeyMan, vResult); f_ConsultarChave; end; //-- pesquisa procedure TcFORM.p_SetarDescr(pEditDes : TEdit; pModoFormulario : TModoFormulario); var vCombo : TcComboBoxPesq; vEditCod : TEdit; vForm : TForm; vCod : String; begin if pModoFormulario in [mfConsulta, mfConsultaSomente] then begin vCod := pEditDes.Name; Delete(vCod, 1, 1); vForm := TForm(pEditDes.Owner); if vForm = nil then Exit; vEditCod := TEdit(vForm.FindComponent(vCod)); if vEditCod = nil then Exit; vCombo := TcComboBoxPesq.create(pEditDes.Owner); with vCombo do begin _EditCod := vEditCod; Parent := pEditDes.Parent; Name := pEditDes.Name + '_Pesq'; TabOrder := pEditDes.TabOrder; Top := pEditDes.Top; Left := pEditDes.Left; Height := pEditDes.Height; Width := pEditDes.Width; Text := ''; end; FreeAndNil(pEditDes); with vCombo do Name := AnsiReplaceStr(Name, '_Pesq', ''); Exit; end; with pEditDes do begin Color := clWindow; ReadOnly := False; TabStop := True; OnExit := EditExitCad; OnKeyPress := EditKeyPressCad; end; end; //-- procedure TcFORM.EditKeyPressCad(Sender: TObject; var Key: Char); begin TcCADASTROFUNC.EditKeyPressDescr(Sender, Key); end; procedure TcFORM.EditExitCad(Sender: TObject); var vLstCod, vParams, vResult, vSql, vEnt, vCod, vDes, vSeq, vVal : String; vEditCod, vEditDes : TEdit; vTotal : Integer; vForm : TForm; begin vEditDes := TEdit(Sender); if vEditDes = nil then Exit; vForm := TForm(vEditDes.Owner); if vForm = nil then Exit; vCod := vEditDes.Name; Delete(vCod, 1, 1); vEditCod := TEdit(vForm.FindComponent(vCod)); if vEditCod = nil then Exit; if vEditDes.Text = '' then begin vEditCod.Text := ''; Exit; end; vParams := vEditCod.Hint; if vParams = '' then Exit; vEnt := item('DS_TABELA', vParams); vCod := item('CD_CAMPO', vParams); vDes := item('DS_CAMPO', vParams); vVal := AllTrim(vEditDes.Text); vParams := ''; putitemX(vParams, 'DS_TABELA', vEnt); putitemX(vParams, 'CD_CAMPO', vCod); putitemX(vParams, 'DS_CAMPO', vDes); putitemX(vParams, 'VL_CAMPO', vVal); vResult := TcComboBoxPesq.Pesquisar(vParams); vLstCod := listCd(vResult); vVal := getitem(vLstCod); vTotal := itemcount(vLstCod); if vTotal > 0 then begin vEditCod.Text := vVal; vEditDes.Text := item(vVal, vResult); Exit; end; if not Pergunta('Registro não cadastrado! Deseja cadastrar ?') then Exit; vSeq := IntToStr(dDADOS.f_IncrementoCodigo(vEnt, vCod)); vSql := 'insert into ' + vEnt + ' (' + vCod + ', ' + vDes + ') ' + 'values (' + vSeq + ', ''' + vEditDes.Text + ''') ' ; dDADOS.f_RunSql(vSql); vEditCod.Text := vSeq; end; procedure TcFORM.EditChange(Sender: TObject); begin if (TEdit(Sender).Tag <> TAG_FK) then Exit; EditExit(Sender); end; procedure TcFORM.EditDblClick(Sender: TObject); var vResult : String; begin vResult := cMENU.AbreTela(item('CD_CAMPO', TEdit(Sender).Hint), TEdit(Sender).Text); if (vResult <> '') then TEdit(Sender).Text := vResult; ModalResult := mrNone; end; //-- procedure TcFORM.EditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); const SC_MOVE = $F012; function Prop(p1, p2 : Integer) : Integer; begin Result := (p1 div p2) * p2; end; begin if not bMoverCampo.Checked then Exit; ReleaseCapture; with TWinControl(Sender) do begin Perform(WM_SYSCOMMAND, SC_MOVE, 0); Top := hRecuo + Prop(Top, hEscala + linRecuo); Left := wRecuo + Prop(Left, wEscala + colRecuo) + 1; EditAjuste(Sender); SetFocus; end; FInEditGravarDef := True; end; procedure TcFORM.EditGravarDef(); var vParams : String; I : Integer; begin if not FInEditGravarDef then Exit; for I := ComponentCount-1 downto 0 do begin if (Components[I] is TEdit) then begin with TWinControl(Components[I]) do begin vParams := ''; putitem(vParams, 'NR_LINHA', Top); putitem(vParams, 'NR_COLUNA', Left); fGravaIni(_Caption, Name + 'xy', vParams); end; end; end; end; procedure TcFORM.EditAjuste(Sender: TObject); var vShape : TShape; vLabel : TLabel; vEdit : TEdit; begin vLabel := TLabel(FindComponent('label' + TEdit(Sender).Name)); if (vLabel <> nil) then begin vLabel.Parent := TEdit(Sender).Parent; vLabel.Left := TEdit(Sender).Left - larLabel - colRecuo; vLabel.Top := TEdit(Sender).Top {- 2}; end; vShape := TShape(FindComponent('Shape' + TEdit(Sender).Name)); if (vShape <> nil) then begin vShape.Parent := TEdit(Sender).Parent; vShape.Left := TEdit(Sender).Left - 2; vShape.Top := TEdit(Sender).Top - 2; end; if (TEdit(Sender).Tag = TAG_FK) then begin vEdit := TEdit(FindComponent('d' + TEdit(Sender).Name)); if (vEdit <> nil) then begin vEdit.Left := TEdit(Sender).Left + TEdit(Sender).Width + 2; vEdit.Top := TEdit(Sender).Top; vShape := TShape(FindComponent('Shape' + vEdit.Name)); if (vShape <> nil) then begin vShape.Left := vEdit.Left - 2; vShape.Top := vEdit.Top - 2; end; end; end; end; //-- procedure TcFORM.p_CorrigeEditFkTela; var I : Integer; begin for I := 0 to ComponentCount - 1 do begin if (Components[I] is TEdit) then begin with TEdit(Components[I]) do begin if (Tag = TAG_FK) then begin if (Hint = '') then begin Hint := cMENU.f_VerFK(Copy(Name, 2, Length(Name)-1)); end; if (Hint <> '') then begin OnChange := EditChange; OnExit := EditExit; OnDblClick := EditDblClick; end; end; end; end; end; end; procedure TcFORM._DataSetAfterPost(DataSet: TDataSet); begin _DataSet.ApplyUpdates(0); end; //-- procedure TcFORM._DataSetBeforePost(DataSet: TDataSet); begin dDADOS.p_IncrementoCodigo(_DataSet, _TabMan, _IncMan); end; //-- procedure TcFORM.p_CarregarCampos(vCampo : String); var Component : TComponent; vCod : String; I : Integer; begin if (FInImprimindo) then Exit; try with _DataSet do begin for I := 0 to FieldCount-1 do begin with Fields[I] do begin vCod := FieldName; if (Visible) and ((vCampo = '') or (vCod = vCampo)) then begin Component := Self.FindComponent(vCod); p_SetPropValue(Component, '_Value', AsString); end; end; end; end; except end; end; procedure TcFORM.p_DesCarregarCampos(vCampo : String); var Component : TComponent; vCod : String; I : Integer; begin EditCancel.SetFocus; with _DataSet do begin for I := 0 to FieldCount - 1 do begin with Fields[I] do begin vCod := FieldName; if (Visible) and ((vCampo = '') or (vCod = vCampo)) then begin Component := Self.FindComponent(vCod); AsString := p_GetPropValue(Component, '_Value'); end; end; end; end; end; //-- procedure TcFORM._DataSetAfterOpen(DataSet: TDataSet); var I : Integer; begin TcCADASTROFUNC.CorrigeDisplayLabel(DataSet); with _DataSet do begin for I := 0 to _DataSet.FieldCount-1 do begin with Fields[I] do begin if (Copy(FieldName, 1, 3) = 'TP_') then begin if (FieldName = 'TP_SITUACAO') then begin Visible := False; end else begin if (cMENU.f_VerCB(FieldName) <> '') then begin OnGetText := _DataSetGetText_TP; Alignment := taLeftJustify; end; end; end; if (Copy(FieldName, 1, 3) = 'IN_') then begin OnGetText := _DataSetGetText_IN; Alignment := taLeftJustify; end; end; end; end; end; procedure TcFORM._DataSetAfterEdit(DataSet: TDataSet); begin putlistitensocc(cLogMan, _DataSet); end; procedure TcFORM._DataSetNewRecord(DataSet: TDataSet); begin cLogMan := ''; putitem(DataSet, 'TP_SITUACAO', 1); dDADOS.p_IncrementoCodigo(_DataSet, _TabMan, _IncMan); end; //-- procedure TcFORM._DataSetGetText_FK(Sender: TField; var Text: String; DisplayText: Boolean); var vVerFK : String; begin vVerFK := cMENU.f_VerFK(TField(Sender).FieldName); if (vVerFK <> '') then begin putitem(vVerFK, 'CD_VALUE', TField(Sender).asString); Text := dDADOS.f_BuscarDescricao(vVerFK); end; end; procedure TcFORM._DataSetGetText_IN(Sender: TField; var Text: String; DisplayText: Boolean); const cLST_BOOL = 'T=Sim;F=Nao'; begin with TField(Sender) do if Text <> '' then Text := item(Text, cLST_BOOL); end; procedure TcFORM._DataSetGetText_TP(Sender: TField; var Text: String; DisplayText: Boolean); var vDsCampo : String; begin if (Copy(TField(Sender).FieldName, 1, 3) = 'TP_') then begin vDsCampo := cMENU.f_VerCB(TField(Sender).FieldName); Text := item(TField(Sender).asString, vDsCampo); end else begin Text := TField(Sender).asString; end; end; //-- function TcFORM.f_ConsultarChave : Boolean; var vSql, vSqlChave : String; begin Result := True; if cModoFormulario in [mfConsulta, mfConsultaSomente] then Exit; vSqlChave := f_GerarChave(False); if vSqlChave = '' then Exit; vSql := 'select * from ' + _TabMan + ' where ' + vSqlChave; if dDADOS.f_ExistSql(vSql) then begin if Pergunta('Registro já existe no banco de dados! Deseja consultar?') then begin p_Consultar(vSql); if itemI('TP_SITUACAO', _DataSet) = 3 then begin if Pergunta('Registro excluído no banco de dados! Deseja reativá-lo novamente?') then begin putitem(_DataSet, 'TP_SITUACAO', 1); Mensagem('Registro reativado com sucesso!'); end; end; _DataSet.Edit; p_CarregarCampos; end else begin Result := False; end; end; end; function TcFORM.f_GerarChave(vParcial : Boolean) : String; var vDsValue, vSql : String; vAchei : Boolean; vEdit : TEdit; I : Integer; begin { ConsultaChave - OK Incremento - OK MontaTabela - OK } vAchei := False; vSql := ''; with _DataSet do begin for I := 0 to FieldCount-1 do begin with Fields[I] do begin if (Tag = TAG_PK) then begin vEdit := TEdit(Self.FindComponent(FieldName)); if (vEdit <> nil) then vDsValue := vEdit.Text; if (vDsValue <> '') then begin if (vSql <> '') then vSql := vSql + ' and '; vSql := vSql + FieldName + '=''' + vDsValue + ''''; end else begin vAchei := True; end; end; end; end; end; if vAchei and not vParcial then vSql := ''; Result := vSql; end; //-- procedure TcFORM.p_HabilitaChave(Tipo : Boolean); var vEdit : TEdit; I : Integer; begin with _DataSet do begin for I := 0 to FieldCount - 1 do begin if (Fields[I].Tag = TAG_PK) then begin vEdit := TEdit(Self.FindComponent(Fields[I].FieldName)); if (vEdit <> nil) then begin vEdit.Enabled := Tipo; vEdit.TabStop := Tipo; end; end; end; end; end; //-- procedure TcFORM.p_GravarRegistro; begin putlistitensocc(cRegMan, _DataSet); end; procedure TcFORM.p_CarregaRegistro; begin if (cRegMan = '') then Exit; getlistitensocc(cRegMan, _DataSet); p_CarregarCampos end; //-- procedure TcFORM.DBGrid1TitleClick(Column: TColumn); begin _DataSet.IndexFieldNames := Column.FieldName; end; procedure TcFORM.DBGrid1DblClick(Sender: TObject); var Component : TComponent; begin if (cModoFormulario = mfConsulta) then Exit; if (bDplMan) then begin if (_KeyMan <> '') then Hint := item(_KeyMan, _DataSet); ModalResult := mrOk; end else begin Component := FindComponent('ToolButtonAlterar'); if (Component is TToolButton) then TToolButton(Component).Click; end; end; procedure TcFORM.DBGrid1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (bDplMan) then begin if (Key = VK_RETURN) then begin bGrdMan := not bGrdMan; with TDBGrid(Sender) do begin if (bGrdMan) then begin Options := Options - [dgRowselect]; Options := Options + [dgEditing]; end else begin Options := Options - [dgEditing]; Options := Options + [dgRowselect]; end; end; end; end; end; //-- function TcFORM.f_ObterFiltroSql : String; var TP_CONSULTA, CD_CAMPO : TComboBox; fDS_EXPRESSAO : TEdit; vCod, vVal : String; begin Result := '/*WHERE*/'; TP_CONSULTA := TComboBox(FindComponent('TP_CONSULTA')); CD_CAMPO := TComboBox(FindComponent('CD_CAMPO')); fDS_EXPRESSAO := TEdit(FindComponent('fDS_EXPRESSAO')); if (TP_CONSULTA = nil) or (CD_CAMPO = nil) or (fDS_EXPRESSAO = nil) then Exit; with _DataSet do begin if Active then begin if (fDS_EXPRESSAO.Text <> '') and (CD_CAMPO.ItemIndex >- 1) then begin vCod := Fields[CD_CAMPO.ItemIndex].FieldName; vVal := fDS_EXPRESSAO.Text; if (Fields[CD_CAMPO.ItemIndex].DataType in [ftDate, ftDateTime]) then vVal := FormatDateTime('yyyy/mm/dd', StrToDateDef(fDS_EXPRESSAO.Text,0)); with TP_CONSULTA do begin if (ItemIndex = 0) then begin // Completa AddSqlWhere(Result, vCod + '=''' + vVal + ''' '); end else if (ItemIndex = 1) then begin // Parcial AddSqlWhere(Result, vCod + ' like ''' + vVal + '%'' '); end else if (ItemIndex = 2) then begin // Qualquer AddSqlWhere(Result, vCod + ' like ''%' + ReplaceStr(vVal,' ','%') + '%'' '); end; end; end; end; end; if (Hint <> '') and (_KeyMan <> '') then AddSqlWhere(Result, _KeyMan + '=''' + Hint + ''' '); if cOrdCns <> '' then AddSqlOrder(Result, cOrdCns + ' '); end; procedure TcFORM.TP_CONSULTAExit(Sender: TObject); begin fGravaIni(_Caption, TIP_CNS, TComboBox(Sender).ItemIndex); end; procedure TcFORM.CD_CAMPOChange(Sender: TObject); var vTP_CONSULTA : TComboBox; begin vTP_CONSULTA := TComboBox(FindComponent('TP_CONSULTA')); if (vTP_CONSULTA = nil) then Exit; with TComboBox(Sender) do if (_DataSet.Fields[ItemIndex].DataType in [ftDate, ftDateTime]) then vTP_CONSULTA.ItemIndex := 0; end; procedure TcFORM.CD_CAMPOExit(Sender: TObject); begin fGravaIni(_Caption, COD_CNS, TComboBox(Sender).ItemIndex); end; procedure TcFORM.fDS_EXPRESSAOExit(Sender: TObject); var vCD_CAMPO : TComboBox; begin vCD_CAMPO := TComboBox(FindComponent('CD_CAMPO')); if (vCD_CAMPO = nil) then Exit; if (vCD_CAMPO.ItemIndex=-1) then Exit; if (TEdit(Sender).Text <> '') then begin TcCADASTROFUNC.EditValida(_DataSet, Sender, _DataSet.Fields[vCD_CAMPO.ItemIndex].FieldName); end; end; procedure TcFORM.fDS_EXPRESSAOKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_SPACE then ClickButton('ToolButtonConsultar'); end; //-- procedure TcFORM.p_CriarTabela(pParent : TWinControl); var vLstCod, vCod, vTB, vAux : String; I, J, T, vLargura : Integer; vStringGrid : TStringGrid; vLabel : TLabel; vNomTab : String; vConfCampoList : TcCONFCAMPOLIST; begin cNomTab := LerIni(_Caption, NOM_TAB); cAltTab := LerIni(_Caption, ALT_TAB); cLarTab := LerIni(_Caption, LAR_TAB); if (cNomTab <> '') then begin T := itemcount(cNomTab); for I := 1 to T do begin vNomTab := getitem(cNomTab, I); vConfCampoList := TcCONFCAMPOMET.CarregarTabMan(vNomTab); putitemX(cTB, vNomTab, 'DS_TABELA=' + vNomTab + ';' + 'DS_CAMPO=' + vConfCampoList._ColMan + ';' + 'DS_TAM=' + vConfCampoList._TamMan + ';' + 'DS_CHAVE=' + vConfCampoList._KeyMan + ';' + 'NR_ALTURA=' + getitem(cAltTab, I) + ';' + 'NR_LARGURA=' + getitem(cLarTab, I)); end; end; vLstCod := listCdX(cTB); while vLstCod <> '' do begin vCod := getitem(vLstCod); if vCod = '' then Break; delitem(vLstCod); vTB := itemX(vCod, cTB); vLabel := TLabel.Create(Self); vLabel.Name := 'label' + 't' + item('DS_TABELA', vTB); vLabel.Caption := item('DS_TABELA', vTB); vLabel.Parent := pParent; vLabel.Top := iTop; vLabel.Left := iLeft; vLabel.Transparent := True; vStringGrid := TStringGrid.Create(Self); vStringGrid.Name := 't' + item('DS_TABELA', vTB); vStringGrid.Parent := pParent; vStringGrid.Left := iLeft + 100; vStringGrid.Top := iTop; vStringGrid.ColCount := itemcount(item('DS_CAMPO', vTB)); vStringGrid.RowCount := itemI('NR_ALTURA', vTB); vStringGrid.Height := (vStringGrid.RowCount + 1) * hEscala; if (item('NR_LARGURA', vTB) <> '') then vStringGrid.Width := itemI('NR_LARGURA', vTB) * wEscala; vStringGrid.Hint := vTB; vStringGrid.DefaultRowHeight := hEscala; vStringGrid.FixedColor := 12615680; vStringGrid.FixedCols := 0; vStringGrid.OnDblClick := StringGridDblClick; vAux := item('DS_TAM', vTB); vLargura := 0; for J := 0 to itemcount(item('DS_CAMPO', vTB))-1 do begin vStringGrid.ColWidths[J] := StrToIntDef(getitem(vAux, J+1),0) * wEscala; vLargura := vLargura + StrToIntDef(getitem(vAux, J+1),0) * wEscala; end; if (item('NR_LARGURA', vTB) = '') then vStringGrid.Width := vLargura + 20; iTop := iTop + vStringGrid.Height + 3; end; end; procedure TcFORM.p_CarreTabela(vStringGrid : TStringGrid); var vTB, vTabela, vCampo, vChave, vSql, vCod : String; begin vTB := vStringGrid.Hint; vTabela := item('DS_TABELA', vTB); vCampo := item('DS_CAMPO', vTB); vChave := item('DS_CHAVE', vTB); vSql := ''; while vCampo <> '' do begin AddSqlField(vSql, getitem(vCampo)); delitem(vCampo) end; AddSqlFrom(vSql, vTabela); while vChave <> '' do begin vCod := getitem(vChave); AddSqlField(vSql, vCod + '=' + item(vCod, _DataSet)); delitem(vChave) end; with dDADOS.getQuery() do begin Close; SQL.Text := vSql; Open; end; end; procedure TcFORM.p_LimpaTabela(vStringGrid : TStringGrid); var L : Integer; begin //Limpar o conteudo dos registros with vStringGrid do begin RowCount := 1; RowCount := 2; FixedRows := 1; with dDADOS.getQuery() do for L := 0 to FieldCount-1 do Cells[L, RowCount-2] := Fields[L].DisplayLabel; end; end; procedure TcFORM.p_MontaTabela; var vLstCod, vCod, vTB : String; vStringGrid : TStringGrid; Component : TComponent; L : Integer; begin vLstCod := listCdX(cTB); while vLstCod <> '' do begin vCod := getitem(vLstCod); if vCod = '' then Break; delitem(vLstCod); vTB := itemX(vCod, cTB); Component := FindComponent('t' + item('DS_TABELA', vTB)); if (Component is TStringGrid) then begin vStringGrid := TStringGrid(Component); p_CarreTabela(vStringGrid); p_LimpaTabela(vStringGrid); with dDADOS.getQuery() do begin if not IsEmpty then begin First; while not EOF do begin for L := 0 to FieldCount-1 do vStringGrid.Cells[L, vStringGrid.RowCount-1] := Fields[L].Text; Next; if not EOF then vStringGrid.RowCount := vStringGrid.RowCount + 1; end; end; end; end; end; end; //-- procedure TcFORM.StringGridDblClick(Sender: TObject); var vCampo : String; begin with TStringGrid(Sender) do begin if (Hint = '') then Exit; vCampo := getitem(item('DS_CHAVE', Hint), 1); if (vCampo = '') then Exit; cMENU.AbreTela(vCampo); end; end; //-- procedure TcFORM.ToolButtonFecharClick(Sender: TObject); begin Close; end; //-- procedure TcFORM.p_CriarAtalho; var T, I : Integer; begin _CoolBarAtalho.Visible := (cAtaMan <> ''); if (cAtaMan = '') then Exit; T := itemcount(cAtaMan); for I := 1 to T do begin with TToolButton.Create(Self) do begin Name := 'ToolButton' + getitem(cAtaMan, I); Caption := PriMaiuscula(getitem(cAtaMan, I)); Hint := getitem(cAtaMan, I); AutoSize := True; Parent := _ToolBarAtalho; OnClick := ToolButtonClick; end; end; end; procedure TcFORM.ToolButtonClick(Sender: TObject); var vConfCampoList : TcCONFCAMPOLIST; vCaption, vCampo : String; begin if (TToolButton(Sender).Hint = '') then Exit; vCaption := TToolButton(Sender).Hint; vConfCampoList := TcCONFCAMPOMET.CarregarCaption(vCaption); vCampo := getitem(vConfCampoList._KeyMan, 1); if (vCampo = '') then Exit; cMENU.AbreTela(vCampo, ''); end; procedure TcFORM.bConsultaLogClick(Sender: TObject); begin TcLOGALTERACAO.Consultar(_DataSet, _TabMan); end; procedure TcFORM.bObservacaoClick(Sender: TObject); begin if _DataSet.IsEmpty then raise Exception.Create(cMESSAGE_CONSULTAVAZIA); TcOBS.Editar(_DataSet, _TabMan); end; procedure TcFORM.bConfigurarManutencaoClick(Sender: TObject); begin TcCONFMANUT.Executar(_Caption, _TabMan); CarregarConfCampoList; end; procedure TcFORM.bConfigurarRelatorioClick(Sender: TObject); begin TcCONFRELAT.Executar(_Caption, _TabMan); CarregarConfCampoList; end; procedure TcFORM.bMoverCampoClick(Sender: TObject); begin bMoverCampo.Checked := not bMoverCampo.Checked; end; procedure TcFORM.bAjustarCampoClick(Sender: TObject); begin bAjustarCampo.Checked := not bAjustarCampo.Checked; fGravaIni(_Caption, RED_MAN, bAjustarCampo.Checked); p_AjustarCampos(Self); end; //-- procedure TcFORM.CarregarConfCampoList; begin if (FCaption <> '') and (FTabMan <> '') then FConfCampoList := TcCONFCAMPOMET.Carregar(FCaption, FTabMan); end; //-- procedure TcFORM.SetCaption(const Value: String); begin FCaption := Value; CarregarConfCampoList(); end; procedure TcFORM.SetCaptionRel(const Value: String); begin FCaptionRel := Value; end; //-- function TcFORM.GetTabMan: String; begin Result := FTabMan; end; procedure TcFORM.SetTabMan(const Value: String); begin FTabMan := Value; CarregarConfCampoList(); end; function TcFORM.GetKeyMan: String; begin Result := FKeyMan; if (Result = '') then Result := FConfCampoList._KeyMan; end; function TcFORM.GetIncMan: String; begin Result := FIncMan; if (Result = '') then Result := FConfCampoList._IncMan; end; function TcFORM.GetValMan: String; begin Result := FValMan; if (Result = '') then Result := FConfCampoList._ValMan; end; function TcFORM.GetColMan: String; begin Result := FColMan; if (Result = '') then Result := FConfCampoList._ColMan; end; //-- procedure TcFORM.bCampoDescricaoClickLoad(Sender: TObject; pHint : String); begin if (pHint <> '') then with TMenuItem(Sender) do begin Hint := pHint; Checked := IfNullB(LerIni(_Caption, Hint), Checked); OnClick := bCampoDescricaoClick; end; end; procedure TcFORM.bCampoDescricaoClick(Sender: TObject); begin with TMenuItem(Sender) do begin if (Hint <> '') then begin Checked := not Checked; fGravaIni(_Caption, Hint, Checked); end; end; end; //-- end.
(* Output: Enter two floats: 1.5 2.75 A: 1.5 B: 2.75 Addition (A+B): 4.25 Subtraction (A-B): -1.25 Multiplying (A*B): 4.125 Dividing (A/B): 0.5454545454545454 *) program Test9; var a, b: real; begin writeln('Enter two floats:'); readln(a, b); writeln('A: ', a); writeln('B: ', b); writeln('Addition (A+B): ', (a+b)); writeln('Subtraction (A-B): ', (a-b)); writeln('Multiplying (A*B): ', (a*b)); writeln('Dividing (A/B): ', (a/b)); end.
unit AsyncHttpServer.Mime; interface type MimeRegistry = interface ['{66E11440-29E8-4D27-B7BF-2D8D1EA52540}'] function DefaultMimeType: string; function FileExtensionToMimeType(const Extension: string): string; end; function NewMimeRegistry: MimeRegistry; implementation uses Winapi.Windows, System.SysUtils, System.Win.Registry, System.Generics.Collections; type MimeRegistryImpl = class(TInterfacedObject, MimeRegistry) strict private FLookupCache: TDictionary<string,string>; FRegistry: TRegistry; public constructor Create; destructor Destroy; override; function DefaultMimeType: string; function FileExtensionToMimeType(const Extension: string): string; end; function NewMimeRegistry: MimeRegistry; begin result := MimeRegistryImpl.Create; end; { MimeRegistryImpl } constructor MimeRegistryImpl.Create; begin inherited Create; FLookupCache := TDictionary<string,string>.Create; FRegistry := TRegistry.Create; FRegistry.RootKey := HKEY_CLASSES_ROOT; end; function MimeRegistryImpl.DefaultMimeType: string; begin result := 'text/plain'; end; destructor MimeRegistryImpl.Destroy; begin FLookupCache.Free; FRegistry.Free; inherited; end; function MimeRegistryImpl.FileExtensionToMimeType( const Extension: string): string; var ext: string; validExtension: boolean; cachedValue: boolean; hasRegEntry: boolean; begin validExtension := (Extension.StartsWith('.')); if (not validExtension) then raise EArgumentException.CreateFmt('Invalid file extension: "%s"', [Extension]); // keep it simple ext := Extension.ToLower; cachedValue := FLookupCache.TryGetValue(ext, result); if (cachedValue) then exit; // default is blank, meaning unknown result := ''; hasRegEntry := FRegistry.OpenKeyReadOnly(ext); if (not hasRegEntry) then exit; try // returns blank if no Content Type value result := FRegistry.ReadString('Content Type'); if (result <> '') then FLookupCache.Add(ext, result); finally FRegistry.CloseKey; end; end; end.
unit Classes.Dalle2AI4Delphi; interface {$SCOPEDENUMS ON} uses System.SysUtils, System.Classes, FMX.Graphics, System.Net.HttpClient, System.Net.HttpClientComponent, Data.DB; CONST APIKEY = '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'; //Default API KEY SIZE1024 = '1024x1024'; // Default Size in DALL-e2 API SIZE512 = '512x512'; SIZE256 = '256x256'; type TDalle2AI4Delphi = class(TComponent) private FHttp: THttpClient; FResponse : IHTTPResponse; FSecretKey: string; FPrompt: string; FNumber: Integer; FBaseURL: string; FResource: string; FSize: string; FResponseContent: string; procedure SetSecretKey(const Value: string); procedure SetNumber(const Value: Integer); procedure SetPrompt(const Value: string); procedure SetBaseURL(const Value: string); procedure SetResource(const Value: string); procedure SetSize(const Value: string); procedure SetResponseContent(const Value: string); procedure SetResponse(const Value: IHTTPResponse); protected public constructor Create(aOwner: TComponent);override; destructor Destroy; override; procedure SetupDalle(AKey, APrompt, ASize: string; ANumber: integer); class function GenerateJSONBodyRequest(APrompt, ASize: string; ANumber: integer) : String; function DoRequest : boolean; function ExtractValueJSONProperty(AJSON2Search, APropertyName : string) : string; procedure DownloadImage(AURL : string; ABitmap : TBitmap); procedure ResponseJSONArrayToDataset(ADataset: TDataset); published property SecretKey : string read FSecretKey write SetSecretKey; property Prompt : string read FPrompt write SetPrompt; property Number : Integer read FNumber write SetNumber; property BaseURL : string read FBaseURL write SetBaseURL; property Resource : string read FResource write SetResource; property Size : string read FSize write SetSize; property Response : IHTTPResponse read FResponse write SetResponse; property ResponseContent : string read FResponseContent write SetResponseContent; end; procedure Register; implementation { TDalle2AI4Delphi } uses System.IOUtils, System.NetEncoding, System.JSON, System.JSON.Readers, System.JSON.Writers, System.JSON.Types, REST.Response.Adapter; constructor TDalle2AI4Delphi.Create(aOwner: TComponent); begin inherited Create(aOwner); Self.SetupDalle(Self.SecretKey, 'delphi beautiful ui/ux software application', SIZE1024, 1); end; destructor TDalle2AI4Delphi.Destroy; begin inherited; end; procedure TDalle2AI4Delphi.DownloadImage(AURL: string; ABitmap: TBitmap); var lMemStream : TMemoryStream; lHTTPClient : TNetHTTPClient; lResponse: IHTTPResponse; begin TThread.Synchronize(TThread.CurrentThread, procedure begin lHTTPClient := TNetHTTPClient.Create(nil); try lMemStream := TMemoryStream.Create(); try lResponse := lHTTPClient.Get(AURL, lMemStream); if lResponse.StatusCode = 200 then begin lMemStream.Position := 0; ABitmap.LoadFromStream(lMemStream); end; finally lMemStream.Free; end; finally lHTTPClient.Free; end; end); end; function TDalle2AI4Delphi.ExtractValueJSONProperty(AJSON2Search, APropertyName: string): string; var lStringReader: TStringReader; lJSONReader: TJsonTextReader; begin lStringReader := TStringReader.Create(AJSON2Search); lJSONReader := TJsonTextReader.Create(lStringReader); try while lJSONReader.Read do case lJSONReader.TokenType of TJsonToken.PropertyName: begin if LowerCase(lJSONReader.Value.AsString) = LowerCase(APropertyName) then begin lJSONReader.Read; Result := lJSONReader.Value.ToString; end; end; end; finally lJSONReader.Free; lStringReader.Free; end; end; class function TDalle2AI4Delphi.GenerateJSONBodyRequest(APrompt, ASize: string; ANumber: integer) : String; var lJSONWriter : TJsonTextWriter; lStringWriter: TStringWriter; begin Result := EmptyStr; lStringWriter := TStringWriter.Create(); lJSONWriter := TJsonTextWriter.Create(lStringWriter); lJSONWriter.Formatting := TJsonFormatting.Indented; try lJSONWriter.WriteStartObject; lJSONWriter.WritePropertyName('prompt'); lJSONWriter.WriteValue(APrompt); if not ASize.IsEmpty then begin lJSONWriter.WritePropertyName('size'); lJSONWriter.WriteValue(ASize); end; if ANumber > 1 then begin lJSONWriter.WritePropertyName('n'); lJSONWriter.WriteValue(ANumber); end; lJSONWriter.WriteEndObject; Result := lStringWriter.ToString; finally lJSONWriter.Free; lStringWriter.Free; end; end; procedure TDalle2AI4Delphi.ResponseJSONArrayToDataset(ADataset: TDataset); var lJSONAdapter : TCustomJSONDataSetAdapter; lJA : TJSONArray; lJO : TJSONObject; begin lJO := TJSonObject.ParseJSONValue(Self.ResponseContent) as TJSONObject; lJSONAdapter := TCustomJSONDataSetAdapter.Create(Nil); if lJO <> nil then begin try lJA := lJO.GetValue('data') as TJSONArray; lJSONAdapter.StringFieldSize := dsMaxStringSize; lJSONAdapter.Dataset := ADataset; lJSONAdapter.UpdateDataSet(lJA); finally lJO.Free; lJSONAdapter.Free; end; end; end; function TDalle2AI4Delphi.DoRequest: boolean; var lRequest: IHTTPRequest; lResponse: IHTTPResponse; lBody: TStringStream; begin Result := False; try if not Assigned(FHttp) then begin FHttp := THttpClient.Create; // allow cookies FHttp.AllowCookies := True; end; lRequest := FHttp.GetRequest('POST', BaseURL + Resource); lRequest.AddHeader('content-type', 'application/json'); lRequest.AddHeader('Authorization', 'Bearer ' + SecretKey); lBody := TStringStream.Create(GenerateJSONBodyRequest(Prompt, Size, Number)) ; lRequest.SourceStream := lBody; lResponse := FHttp.Execute(lRequest); FResponse := lResponse; if lResponse.StatusCode = 200 then begin ResponseContent := lResponse.ContentAsString(); Result := True; end else ResponseContent := Format('%s - %s', [lResponse.StatusCode.ToString, lResponse.StatusText]); except on E: Exception do raise Exception.Create('Error Message: ' + E.Message); end; end; procedure TDalle2AI4Delphi.SetBaseURL(const Value: string); begin FBaseURL := Value; end; procedure TDalle2AI4Delphi.SetNumber(const Value: Integer); begin FNumber := Value; end; procedure TDalle2AI4Delphi.SetPrompt(const Value: string); begin FPrompt := Value; end; procedure TDalle2AI4Delphi.SetResource(const Value: string); begin FResource := Value; end; procedure TDalle2AI4Delphi.SetResponse(const Value: IHTTPResponse); begin FResponse := Value; end; procedure TDalle2AI4Delphi.SetResponseContent(const Value: string); begin FResponseContent := Value; end; procedure TDalle2AI4Delphi.SetSecretKey(const Value: string); begin FSecretKey := Value; end; procedure TDalle2AI4Delphi.SetSize(const Value: string); begin FSize := Value; end; procedure TDalle2AI4Delphi.SetupDalle(AKey, APrompt, ASize: string; ANumber: integer); begin BaseURL := 'https://api.openai.com/v1/images/'; Resource := 'generations'; SecretKey := AKey; Prompt := APrompt; Size := ASize; Number := ANumber; end; procedure Register; begin RegisterComponents('DALL-e2AI', [TDalle2AI4Delphi]); end; end.
{*******************************************************} { } { TFacturaElectronica } { } { Copyright (C) 2017 Bambu Code SA de CV } { } {*******************************************************} unit Facturacion.ProveedorAutorizadoCertificacion; interface uses Facturacion.Comprobante, {$IF Compilerversion >= 22.0} System.SysUtils; {$ELSE} SysUtils; {$IFEND} type EPACNoConfiguradoException = class(Exception); {$REGION 'Documentation'} /// <summary> /// <para> /// Excepcion heredable que tiene la propiedad Reintentable para saber si /// dicha falla es temporal y el programa cliente debe de re-intentar la /// última petición. /// </para> /// <para> /// Si su valor es Falso es debido a que la falla está del lado del cliente /// y el PAC no puede procesar dicha petición (XML incorrecto, Sello mal /// generado, etc.) /// </para> /// </summary> {$ENDREGION} EPACException = class(Exception) private fCodigoErrorSAT: Integer; fCodigoErrorPAC: Integer; fReintentable : Boolean; public constructor Create(const aMensajeExcepcion: String; const aCodigoErrorSAT: Integer; const aCodigoErrorPAC: Integer; const aReintentable: Boolean); property CodigoErrorSAT: Integer read fCodigoErrorSAT; property CodigoErrrorPAC: Integer read fCodigoErrorPAC; property Reintentable : Boolean read fReintentable; end; EPACServicioNoDisponibleException = class(EPACException); EPACCredencialesIncorrectasException = class(EPACException); EPACEmisorNoInscritoException = class(EPACException); EPACErrorGenericoDeAccesoException = class(EPACException); EPACTimbradoRFCNoCorrespondeException = class(EPACException); EPACTimbradoVersionNoSoportadaPorPACException = class(EPACException); EPACTimbradoSinFoliosDisponiblesException = class(EPACException); EPACCAnceladoSinCertificadosException = class(EPACException); EPACNoSePudoObtenerAcuseException = class(EPACException); {$REGION 'Documentation'} /// <summary> /// Este tipo de excepcion se lanza cuando se detecta una falla con el /// internet del usuario el cual es un problema de comunicación con el PAC. /// </summary> {$ENDREGION} EPACProblemaConInternetException = class(EPACException); EPACProblemaTimeoutException = class(EPACException); {$REGION 'Documentation'} /// <summary> /// Excepcion general para errores no programados/manejados. /// </summary> /// <remarks> /// <note type="important"> /// Por defecto se establece que esta excepción es "re-intentable" para /// indicarle al cliente que debe de re-intentar realizar el ultimo proceso /// </note> /// </remarks> {$ENDREGION} EPACErrorGenericoException = class(EPACException); IProveedorAutorizadoCertificacion = interface ['{BB3456F4-277A-46B7-B2BC-A430E35130E8}'] procedure Configurar(const aDominioWebService: string; const aCredencialesPAC: TFacturacionCredencialesPAC; const aTransaccionInicial: Int64); function TimbrarDocumento(const aComprobante: IComprobanteFiscal; const aTransaccion: Int64) : TCadenaUTF8; function ObtenerSaldoTimbresDeCliente(const aRFC: String) : Integer; end; implementation constructor EPACException.Create(const aMensajeExcepcion: String; const aCodigoErrorSAT: Integer; const aCodigoErrorPAC : Integer; const aReintentable: Boolean); begin inherited Create(aMensajeExcepcion); fReintentable := aReintentable; fCodigoErrorSAT := aCodigoErrorSAT; fCodigoErrorPAC := aCodigoErrorPAC; end; end.
unit Expedicao.Controller.uInfracao; interface uses System.SysUtils, System.JSON, FireDAC.Comp.Client, Base.uControllerBase, Expedicao.Models.uInfracao; type TInfracaoController = class(TControllerBase) private { Private declarations } function ObterInfracaoDaQuery(pQry: TFDQuery): TInfracao; function ObterInfracaoPeloOID(pInfracaoOID: Integer): TInfracao; function IncluirInfracao(pInfracao: TInfracao): Boolean; function AlterarInfracao(pInfracao: TInfracao): Boolean; function TestarVeiculoCadastrado(pVeiculoOID: Integer): Boolean; public { Public declarations } function Infracoes: TJSONValue; function Infracao(ID: Integer): TJSONValue; function updateInfracao(Infracao: TJSONObject): TJSONValue; function acceptInfracao(Infracao: TJSONObject): TJSONValue; function cancelInfracao(ID: Integer): TJSONValue; end; implementation uses REST.jSON, uDataModule; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TInfracaoController } function TInfracaoController.ObterInfracaoDaQuery(pQry: TFDQuery): TInfracao; begin Result := TInfracao.Create; with Result do begin InfracaoOID := pQry.FieldByName('InfracaoOID').AsInteger; VeiculoOID := pQry.FieldByName('VeiculoOID').AsInteger; Data := pQry.FieldByName('Data').AsDateTime; Hora := pQry.FieldByName('Hora').AsString; AutoInfracao := pQry.FieldByName('AutoInfracao').AsString; Orgao := pQry.FieldByName('Orgao').AsString; Valor := pQry.FieldByName('Valor').AsFloat; AutorInfracao := pQry.FieldByName('AutorInfracao').AsInteger; TipoInfracao := pQry.FieldByName('TipoInfracao').AsString; end; end; function TInfracaoController.ObterInfracaoPeloOID( pInfracaoOID: Integer): TInfracao; var lQry: TFDQuery; begin Result := nil; lQry := DataModule1.ObterQuery; try lQry.Open('SELECT * FROM Infracao WHERE InfracaoOID = :InfracaoOID', [pInfracaoOID]); if lQry.IsEmpty then Exit; Result := ObterInfracaoDaQuery(lQry); finally DataModule1.DestruirQuery(lQry); end; end; function TInfracaoController.TestarVeiculoCadastrado( pVeiculoOID: Integer): Boolean; var lQry: TFDQuery; begin Result := False; lQry := DataModule1.ObterQuery; try with lQry do begin Open('SELECT COUNT(*) AS Total FROM Veiculo WHERE VeiculoOID = :VeiculoOID', [pVeiculoOID]); Result := FieldByName('Total').AsInteger > 0; end; finally DataModule1.DestruirQuery(lQry); end; end; function TInfracaoController.IncluirInfracao(pInfracao: TInfracao): Boolean; var lQry: TFDQuery; begin Result := False; lQry := DataModule1.ObterQuery; try with lQry do begin SQL.Add('INSERT INTO Infracao ('); SQL.Add('VeiculoOID, Data, Hora, AutoInfracao, Orgao, Valor, AutorInfracao, TipoInfracao'); SQL.Add(') VALUES ('); SQL.Add(':VeiculoOID, :Data, :Hora, :AutoInfracao, :Orgao, :Valor, :AutorInfracao, :TipoInfracao'); SQL.Add(');'); ParamByName('VeiculoOID').AsInteger := pInfracao.VeiculoOID; ParamByName('Data').AsDateTime := pInfracao.Data; ParamByName('Hora').AsString := pInfracao.Hora; ParamByName('AutoInfracao').AsString := pInfracao.AutoInfracao; ParamByName('Orgao').AsString := pInfracao.Orgao; ParamByName('Valor').AsFloat := pInfracao.Valor; ParamByName('AutorInfracao').AsInteger := pInfracao.AutorInfracao; ParamByName('TipoInfracao').AsString := pInfracao.TipoInfracao; ExecSQL; Result := True; end; finally DataModule1.DestruirQuery(lQry); end; end; function TInfracaoController.AlterarInfracao(pInfracao: TInfracao): Boolean; var lQry: TFDQuery; begin Result := False; lQry := DataModule1.ObterQuery; try with lQry do begin SQL.Add('UPDATE Infracao SET '); SQL.Add(' VeiculoOID = :VeiculoOID,'); SQL.Add(' Data = :Data, '); SQL.Add(' Hora = :Hora, '); SQL.Add(' AutoInfracao = :AutoInfracao, '); SQL.Add(' Orgao = :Orgao, '); SQL.Add(' Valor = :Valor, '); SQL.Add(' AutorInfracao = :AutorInfracao, '); SQL.Add(' TipoInfracao = :TipoInfracao '); SQL.Add('WHERE InfracaoOID = :InfracaoOID'); ParamByName('InfracaoOID').AsInteger := pInfracao.InfracaoOID; ParamByName('VeiculoOID').AsInteger := pInfracao.VeiculoOID; ParamByName('Data').AsDateTime := pInfracao.Data; ParamByName('Hora').AsString := pInfracao.Hora; ParamByName('AutoInfracao').AsString := pInfracao.AutoInfracao; ParamByName('Orgao').AsString := pInfracao.Orgao; ParamByName('Valor').AsFloat := pInfracao.Valor; ParamByName('AutorInfracao').AsInteger := pInfracao.AutorInfracao; ParamByName('TipoInfracao').AsString := pInfracao.TipoInfracao; ExecSQL; Result := True; end; finally DataModule1.DestruirQuery(lQry); end; end; function TInfracaoController.Infracoes: TJSONValue; var lInfracao: TInfracao; lQry: TFDQuery; begin lQry := DataModule1.ObterQuery; try with lQry do begin Open('SELECT * FROM Infracao'); if IsEmpty then begin Result := TJSONString.Create('Nenhuma infração encontrada!'); ConfigurarResponse(tmNotFound); end; Result := TJSONArray.Create; while not Eof do begin lInfracao := ObterInfracaoDaQuery(lQry); (Result as TJSONArray).AddElement(TJson.ObjectToJsonObject(lInfracao)); ConfigurarResponse(tmOK); Next; end; end; finally DataModule1.DestruirQuery(lQry); end; end; function TInfracaoController.Infracao(ID: Integer): TJSONValue; var lInfracao: TInfracao; begin lInfracao := ObterInfracaoPeloOID(ID); if not Assigned(lInfracao) then begin Result := TJSONString.Create('Infração não encontrada!'); ConfigurarResponse(tmNotFound); end else begin Result := TJson.ObjectToJsonObject(lInfracao); ConfigurarResponse(tmOK); lInfracao.Free; end; end; function TInfracaoController.acceptInfracao( Infracao: TJSONObject): TJSONValue; var lInfracaoEnviada, lInfracaoCadastrada: TInfracao; begin lInfracaoEnviada := TJson.JsonToObject<TInfracao>(Infracao); try lInfracaoCadastrada := ObterInfracaoPeloOID(lInfracaoEnviada.InfracaoOID); if Assigned(lInfracaoCadastrada) then begin Result := TJSONString.Create('Infração já cadastrada. Inclusão cancelada!'); ConfigurarResponse(tmObjectAlreadyExists); lInfracaoCadastrada.Free; Exit; end; try if not TestarVeiculoCadastrado(lInfracaoEnviada.VeiculoOID) then begin Result := TJSONString.Create('Veículo informado não existe!'); ConfigurarResponse(tmUnprocessableEntity); Exit; end; if IncluirInfracao(lInfracaoEnviada) then begin Result := TJSONString.Create('Infração gravada com sucesso!'); ConfigurarResponse(tmOK); end else raise Exception.Create('Erro ao gravar a Infração!'); except on e: Exception do begin Result := TJSONString.Create(e.Message); ConfigurarResponse(tmUndefinedError); end; end; finally lInfracaoEnviada.Free; end; end; function TInfracaoController.updateInfracao( Infracao: TJSONObject): TJSONValue; var lInfracaoEnviada, lInfracaoCadastrada: TInfracao; begin lInfracaoEnviada := TJson.JsonToObject<TInfracao>(Infracao); try lInfracaoCadastrada := ObterInfracaoPeloOID(lInfracaoEnviada.InfracaoOID); if not Assigned(lInfracaoCadastrada) then begin Result := TJSONString.Create('Infração não encontrada!'); ConfigurarResponse(tmNotFound); Exit; end; lInfracaoCadastrada.Free; try if not TestarVeiculoCadastrado(lInfracaoEnviada.VeiculoOID) then begin Result := TJSONString.Create('Veículo informado não existe!'); ConfigurarResponse(tmUnprocessableEntity); Exit; end; if AlterarInfracao(lInfracaoEnviada) then begin Result := TJSONString.Create('Infração gravada com sucesso!'); ConfigurarResponse(tmOK); end else raise Exception.Create('Erro ao gravar a infração!'); except on e: Exception do begin Result := TJSONString.Create(e.Message); ConfigurarResponse(tmUndefinedError); end; end; finally lInfracaoEnviada.Free; end; end; function TInfracaoController.cancelInfracao( ID: Integer): TJSONValue; var lQry: TFDQuery; lInfracao: TInfracao; begin lInfracao := ObterInfracaoPeloOID(ID); if not Assigned(lInfracao) then begin Result := TJSONString.Create('Infração não encontrada!'); ConfigurarResponse(tmNotFound); Exit; end; lInfracao.Free; lQry := DataModule1.ObterQuery; try try with lQry do begin SQL.Add('DELETE FROM Infracao WHERE InfracaoOID = :InfracaoOID'); ParamByName('InfracaoOID').AsInteger := ID; ExecSQL; Result := TJSONString.Create('Infração excluída com sucesso!'); ConfigurarResponse(tmOK); end; except on e: Exception do begin Result := TJSONString.Create('Erro ao excluir a infração!'); ConfigurarResponse(tmUndefinedError); end; end; finally DataModule1.DestruirQuery(lQry); end; end; end.
unit EFSate.View; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, EFState, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, Vcl.StdCtrls, cxLabel, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, EFStateMovimentoConta, cxTextEdit; type TTransacaoConta = (tcNenhuma, tcSaque, tcDeposito); TEFStateView = class(TForm) Edit1: TEdit; cxLabel1: TcxLabel; Button1: TButton; cxPageControl1: TcxPageControl; cxTabSheet1: TcxTabSheet; cxTabSheet2: TcxTabSheet; GroupBox1: TGroupBox; GroupBox2: TGroupBox; Edit2: TEdit; cxLabel2: TcxLabel; Button2: TButton; Button3: TButton; Label1: TLabel; cxTextEditSaldo: TcxTextEdit; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure cxTabSheet2Show(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } conta: TContaTransacao; procedure ProcessaTransacao(_ATransacao: TTransacaoConta); public { Public declarations } end; var EFStateView: TEFStateView; implementation {$R *.dfm} procedure TEFStateView.Button1Click(Sender: TObject); var orcamento: TOrcamento; begin orcamento := TOrcamento.Create(StrToFloatDef(Edit1.Text, 0)); try orcamento.AplicaDescontoExtra; ShowMessage('Orçamento Em Aprovação Valor: ' + orcamento.Valor.ToString); orcamento.Aprova; orcamento.Aprova; orcamento.AplicaDescontoExtra; ShowMessage('Orçamento Aprovado Valor: ' + orcamento.Valor.ToString); orcamento.Finaliza; finally orcamento.Free; end; end; procedure TEFStateView.Button2Click(Sender: TObject); begin ProcessaTransacao(tcSaque); end; procedure TEFStateView.Button3Click(Sender: TObject); begin ProcessaTransacao(tcDeposito); end; procedure TEFStateView.cxTabSheet2Show(Sender: TObject); begin if not Assigned(conta) then conta := TContaTransacao.Create; end; procedure TEFStateView.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(conta) end; procedure TEFStateView.ProcessaTransacao(_ATransacao: TTransacaoConta); var ValorTransacao: Double; begin try ValorTransacao := StrToFloatDef(Edit2.Text, 0); case _ATransacao of tcSaque: conta.Saque(ValorTransacao); tcDeposito: conta.Deposito(ValorTransacao); end; finally cxTextEditSaldo.Text := conta.Saldo.ToString; end; end; end.
unit ThreeDRod; { usage The TThreeDRod is a derivative of TCustomMesh the data mesh is constructed of straight or bent sections of rod. The sections used are specified by a list of strings with each line representing a segment. By editing ConstructionText and following simple rules it is possible to build complex rods. A straight section requires radius, length, and angle Model Flag=s, Rod Radius, Section Length, Angle in Degrees Example 'S,0.2,0.1,90.0' To get a contiguous rod the angle and radius must match the final angle of the previous segment. Each segment commences from where the last one ends. Straight sections that either start or finish a sequence will have that end filled in. A Bend Section requires rod radius, bend radius, bend angle Model Flag=B, Rod Radius, Bend Radius (To Centre) , Bend Angle in Degrees Example 'B,0.2,0.5,-90.0' A bend aligns itself to the angle of the previous section and applies the angle from that reference. Outstanding Issues The current code does slightly rotate the ends from the YZ plane. I assume it is because the MovePath method is too simplistic but I do not yet understand why. For my purposes it is acceptable but it becomes problematic as the rod radius and the offset increases. } {$IFDEF VER270} {$DEFINE ISXE6_DELPHI} {$ENDIF} {$IFDEF VER280} {$DEFINE ISXE6_DELPHI} {$DEFINE ISXE7_DELPHI} {$ENDIF} {$IFDEF VER290} {$DEFINE ISXE6_DELPHI} {$DEFINE ISXE7_DELPHI} {$DEFINE ISXE8_DELPHI} {$ENDIF} {$IFDEF VER300} {$DEFINE ISXE6_DELPHI} {$DEFINE ISXE7_DELPHI} {$DEFINE ISXE8_DELPHI} {$DEFINE ISD10S_DELPHI} {$ENDIF} {$IFDEF VER310} {$DEFINE ISXE6_DELPHI} {$DEFINE ISXE7_DELPHI} {$DEFINE ISXE8_DELPHI} {$DEFINE ISD10S_DELPHI} {$DEFINE ISD101B_DELPHI} {$ENDIF} interface uses SysUtils, FMX.Objects3D, FMX.Types3D, Classes, System.Math, System.Types, FMX.Types , FMX.Utils , ISLibFmxUtils, System.Math.Vectors; Type TRodSectionBase = Class(TObject) Private FPrev, FNext: TRodSectionBase; FStartLocal, FEndLocal: TPoint3D; FStartAngle, FEndAngle: Single; FRadius: Single; Protected VBuffer: TVertexBuffer; IBuffer: TIndexBuffer; Procedure SetFltValueFrmArrayString(Var AFloat: Single; Var AString: AnsiString); Function RadiusSections: Integer; Procedure AddSq(ASq: TSqArray; Var AVOffset: Integer; Var AIOffset: Integer); Procedure AddCylinder(AR1, AX1, AY1, AZ1, AAlpha1, AR2, AX2, AY2, AZ2, AAlpha2: Real; Var AVOffset: Integer; Var AIOffset: Integer; AStartFill: Boolean = false; AEndFill: Boolean = false); Procedure BuildCylinder(RadiusArray1, RadiusArray2: TPathArray; Var AVOffset: Integer; Var AIOffset: Integer); Procedure BuildCylinderEnd(RadiusArray: TPathArray; AReverse: Boolean; Var AVOffset: Integer; Var AIOffset: Integer); Public Class Function CreateFrmTxt(AText: AnsiString): TRodSectionBase; Destructor Destroy; override; Function DeltaX: Real; virtual; abstract; Function DeltaY: Real; virtual; abstract; Function NoOfVertexes: Integer; virtual; Function NoOfIndexes: Integer; virtual; Procedure AddSection(ANewSection: TRodSectionBase); Procedure AddData(Var NxtData, NxtIndex: Integer); virtual; Property Radius: Single read FRadius write FRadius; End; TRodStraight = Class(TRodSectionBase) Private FLength, FAngleX: Single; FStartFill, FEndFill: Boolean; Public Constructor Create; Constructor CreateFrmTxt(AText: AnsiString); Function DeltaX: Real; override; Function DeltaY: Real; override; Function NoOfVertexes: Integer; override; Function NoOfIndexes: Integer; override; Procedure AddData(Var NxtData, NxtIndex: Integer); override; Property AngleX: Single read FAngleX write FAngleX; Property Length: Single read FLength write FLength; End; TRodBend = Class(TRodSectionBase) Private FBendRadius, FAngleRotateX: Single; FSegments10Deg: Integer; Function GetDeltaXY(AStartAngle, ADeltaAngle: Single): TPointF; Public Constructor CreateFrmTxt(AText: AnsiString); Function DeltaX: Real; override; Function DeltaY: Real; override; Function NoOfVertexes: Integer; override; Function NoOfIndexes: Integer; override; Procedure AddData(Var NxtData, NxtIndex: Integer); override; End; TThreeDRod = Class(TCustomMesh) Private FSections: TRodSectionBase; FConstructionText: TStrings; procedure SetConstructionCode(const Value: TStrings); protected procedure ReadState(Reader: TReader); override; Public constructor Create(AOwner: TComponent); override; Destructor Destroy; override; procedure ResetSections; Procedure AddSection(ANewSection: TRodSectionBase); Procedure AddSectionFrmText(AText: String); Procedure RebuildMesh; Published property MaterialSource; property Position; property Scale; property RotationAngle; property Locked default False; property Width; property Height; property Depth; property Opacity nodefault; property Projection; property HitTest default True; //property ShowContextMenu default True; property TwoSide default False; property Visible default True; property ZWrite default True; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnKeyDown; property OnKeyUp; property OnRender; Property ConstructionText: TStrings Read FConstructionText write SetConstructionCode; End; procedure Register; implementation procedure Register; begin RegisterComponents('Innova Solutions', [TThreeDRod]); end; const QuadPoints = 8; function GetTokenXE3(var S: AnsiString; Separators: AnsiString; Stop: AnsiString = ''): AnsiString; var I, len: Integer; CopyS: AnsiString; begin Result := ''; CopyS := S; len := Length(CopyS); for I := 1 to len do begin if Pos(CopyS[I], Stop) > 0 then Break; Delete(S, 1, 1); if Pos(CopyS[I], Separators) > 0 then begin Result := Result; Break; end; Result := Result + CopyS[I]; end; Result := Trim(Result); S := Trim(S); end; { TThreeDRod } procedure TThreeDRod.AddSection(ANewSection: TRodSectionBase); begin if ANewSection = nil then exit; ANewSection.VBuffer := Data.VertexBuffer; ANewSection.IBuffer := Data.IndexBuffer; if FSections = nil then FSections := ANewSection else FSections.AddSection(ANewSection); end; procedure TThreeDRod.AddSectionFrmText(AText: String); Var NewSection: TRodSectionBase; begin if AText = '' then exit; NewSection := TRodSectionBase.CreateFrmTxt(AText); AddSection(NewSection); end; constructor TThreeDRod.Create(AOwner: TComponent); begin inherited; {$IfDEF ISXE8_DELPHI} WrapMode:=TMeshWrapMode.Original; {$ENDIF} FConstructionText := TStringList.Create; // FConstructionText.Add('S,0.2,0.1,0.0'); FConstructionText.Add('B,0.2,0.5,340.0'); // FConstructionText.Add('S,0.2,0.3,-90.0'); RebuildMesh; end; destructor TThreeDRod.Destroy; begin FSections.Free; FConstructionText.Free; inherited; end; procedure TThreeDRod.ReadState(Reader: TReader); begin inherited; FreeAndNil(FSections); RebuildMesh; end; procedure TThreeDRod.RebuildMesh; var NxtData, NxtIndex: Integer; I: Integer; begin if FSections = nil then Begin if FConstructionText.Count > 0 then for I := 0 to FConstructionText.Count - 1 do AddSectionFrmText(FConstructionText[I]); if FSections = nil then exit; End; { MeshRender uses D3DPT_TRIANGLELIST From http://www.directxtutorial.com/tutorial9/b-direct3dbasics/dx9B4.aspx#still [Table 4.3 - D3DPRIMITIVETYPE Values] Value Description D3DPT_POINTLIST Shows a series of points. D3DPT_LINELIST Shows a series of separated lines. D3DPT_LINESTRIP Shows a series of connected lines. D3DPT_TRIANGLELIST Shows a series of separated triangles. D3DPT_TRIANGLESTRIP Shows a series of connected triangles. D3DPT_TRIANGLEFAN Shows a series of triangles with one shared corner. } NxtData := 0; NxtIndex := 0; Data.VertexBuffer.Length := FSections.NoOfVertexes; Data.IndexBuffer.Length := FSections.NoOfIndexes; FSections.AddData(NxtData, NxtIndex); //XE2 Data.CalcNormals; Data.CalcFaceNormals; //Data.CalcSmoothNormals; //Data.CalcTangentBinormals; end; procedure TThreeDRod.ResetSections; begin FreeAndNil(FSections); end; procedure TThreeDRod.SetConstructionCode(const Value: TStrings); begin FConstructionText.Assign(Value); if FConstructionText.Count > 0 then begin FreeAndNil(FSections); RebuildMesh; end; end; { TRodStraight } procedure TRodStraight.AddData(Var NxtData, NxtIndex: Integer); begin FEndLocal := MovePoint(FStartLocal, DeltaX, DeltaY, 0.0); FStartAngle := FAngleX; FEndAngle := FAngleX; AddCylinder(FRadius, FStartLocal.X, FStartLocal.Y, FStartLocal.Z, FAngleX, FRadius, FEndLocal.X, FEndLocal.Y, FEndLocal.Z, FAngleX, NxtData, NxtIndex, FStartFill, FEndFill); inherited; end; constructor TRodStraight.Create; begin inherited; FLength := 1; FRadius := 1; end; constructor TRodStraight.CreateFrmTxt(AText: AnsiString); Var Flag: AnsiString; AngleXAsDegrees: Single; begin inherited Create; Flag := GetTokenXE3(AText, ',()'); if uppercase(Flag) <> 'S' then raise Exception.Create('TRodStraight.CreateFrmTxt::' + AText); // Model Flag,Rod Radius, Section Length, Angle in Degrees // Example 'S,0.2,0.1,0.0' AngleXAsDegrees := 0.0; SetFltValueFrmArrayString(FRadius, AText); SetFltValueFrmArrayString(FLength, AText); SetFltValueFrmArrayString(AngleXAsDegrees, AText); if AngleXAsDegrees <> 0.0 then FAngleX := AngleXAsDegrees / 180 * Pi; end; function TRodStraight.DeltaX: Real; begin Result := FLength * Cos(FAngleX); end; function TRodStraight.DeltaY: Real; begin Result := FLength * Sin(FAngleX); end; function TRodStraight.NoOfIndexes: Integer; begin FEndFill := FNext = nil; FStartFill := FPrev = nil; // 6 Lines Indexs per Square // X Squares per Length Result := RadiusSections * 6 + Inherited; if FEndFill then Result := Result + QuadPoints * 4 * 3; if FStartFill then Result := Result + QuadPoints * 4 * 3; end; function TRodStraight.NoOfVertexes: Integer; begin FEndFill := FNext = nil; FStartFill := FPrev = nil; // 4 Vertexes per Square // X Squares per Length Result := RadiusSections * 4 + Inherited; if FEndFill then Result := Result + 1 + QuadPoints * 4 * 2; if FStartFill then Result := Result + 1 + QuadPoints * 4 * 2; end; { TRodSectionBase } procedure TRodSectionBase.AddCylinder(AR1, AX1, AY1, AZ1, AAlpha1, AR2, AX2, AY2, AZ2, AAlpha2: Real; var AVOffset, AIOffset: Integer; AStartFill: Boolean = false; AEndFill: Boolean = false); Var RadiusArray1: TPathArray; RadiusArray2: TPathArray; begin RadiusArray1 := RadiusArray(AR1, AX1, AY1, AZ1, AAlpha1, QuadPoints); RadiusArray2 := RadiusArray(AR2, AX2, AY2, AZ2, AAlpha2, QuadPoints); If AStartFill then BuildCylinderEnd(RadiusArray1, false, AVOffset, AIOffset); BuildCylinder(RadiusArray1, RadiusArray2, AVOffset, AIOffset); If AEndFill then BuildCylinderEnd(RadiusArray2, True, AVOffset, AIOffset); end; procedure TRodSectionBase.AddData(var NxtData, NxtIndex: Integer); begin if FNext <> nil then begin FNext.FStartLocal := FEndLocal; FNext.FStartAngle := FEndAngle; FNext.AddData(NxtData, NxtIndex); end; end; procedure TRodSectionBase.AddSection(ANewSection: TRodSectionBase); begin if FNext <> nil then FNext.AddSection(ANewSection) else begin FNext := ANewSection; ANewSection.FPrev := self; // no need for pop??? end; end; procedure TRodSectionBase.AddSq(ASq: TSqArray; var AVOffset, AIOffset: Integer); begin begin VBuffer.Vertices[AVOffset] := ASq[0]; VBuffer.Vertices[AVOffset + 1] := ASq[1];; VBuffer.Vertices[AVOffset + 2] := ASq[2];; VBuffer.Vertices[AVOffset + 3] := ASq[3];; IBuffer.Indices[AIOffset] := AVOffset + 3; IBuffer.Indices[AIOffset + 1] := AVOffset + 2; IBuffer.Indices[AIOffset + 2] := AVOffset + 1; IBuffer.Indices[AIOffset + 3] := AVOffset + 1; IBuffer.Indices[AIOffset + 4] := AVOffset + 0; IBuffer.Indices[AIOffset + 5] := AVOffset + 3; Inc(AVOffset, 4); Inc(AIOffset, 6); end; end; procedure TRodSectionBase.BuildCylinder(RadiusArray1, RadiusArray2: TPathArray; var AVOffset, AIOffset: Integer); Var I, sz: Integer; begin sz := high(RadiusArray1); if high(RadiusArray2) <> sz then raise Exception.Create('BuildCylinder'); I := 0; while I < sz do begin AddSq(SqArray(RadiusArray1[I + 1], RadiusArray1[I], RadiusArray2[I], RadiusArray2[I + 1]), AVOffset, AIOffset); Inc(I); end; AddSq(SqArray(RadiusArray1[0], RadiusArray1[sz], RadiusArray2[sz], RadiusArray2[0]), AVOffset, AIOffset); end; procedure TRodSectionBase.BuildCylinderEnd(RadiusArray: TPathArray; AReverse: Boolean; var AVOffset, AIOffset: Integer); Var I, sz, CtrOffset: Integer; Cntr: TPoint3D; begin sz := high(RadiusArray); if sz < 4 then raise Exception.Create('BuildCylinderEnd'); Cntr := Average3D(RadiusArray[0], RadiusArray[sz div 2]); VBuffer.Vertices[AVOffset] := Cntr; CtrOffset := AVOffset; //VBuffer.Diffuse[CtrOffset] := claYellow; Inc(AVOffset); I := 0; while I <= sz do begin VBuffer.Vertices[AVOffset] := RadiusArray[I]; if I = sz then VBuffer.Vertices[AVOffset + 1] := RadiusArray[0] else VBuffer.Vertices[AVOffset + 1] := RadiusArray[I + 1]; //VBuffer.Diffuse[AVOffset] := claBlue; //VBuffer.Diffuse[AVOffset + 1] := claRed; if AReverse then begin IBuffer.Indices[AIOffset] := AVOffset + 1; IBuffer.Indices[AIOffset + 1] := CtrOffset; IBuffer.Indices[AIOffset + 2] := AVOffset + 0; end else begin IBuffer.Indices[AIOffset] := AVOffset + 0; IBuffer.Indices[AIOffset + 1] := CtrOffset; IBuffer.Indices[AIOffset + 2] := AVOffset + 1; end; Inc(AVOffset, 2); Inc(AIOffset, 3); Inc(I); end; end; class function TRodSectionBase.CreateFrmTxt(AText: AnsiString): TRodSectionBase; begin Result := nil; if Length(AText) < 5 then exit; case AText[1] of 'b', 'B': begin Result := TRodBend.CreateFrmTxt(AText); end; 's', 'S': begin Result := TRodStraight.CreateFrmTxt(AText); end; end; end; destructor TRodSectionBase.Destroy; begin FNext.Free; inherited; end; function TRodSectionBase.NoOfIndexes: Integer; begin if FNext = nil then Result := 0 Else Result := FNext.NoOfIndexes; end; function TRodSectionBase.NoOfVertexes: Integer; begin if FNext = nil then Result := 0 Else Result := FNext.NoOfVertexes; end; function TRodSectionBase.RadiusSections: Integer; begin Result := QuadPoints * 4; end; procedure TRodSectionBase.SetFltValueFrmArrayString(var AFloat: Single; var AString: AnsiString); Var Val: Single; begin Try Val := StrToFloat(GetTokenXE3(AString, ',()'), USFormatSettings); Except Val := 0.0; end; if Val <> 0.0 then AFloat := Val; end; { TRodBend } procedure TRodBend.AddData(var NxtData, NxtIndex: Integer); Var DeltaAlpha, LastAlpha, NxtAlpha: Single; NxtLocal, PrvLocal: TPoint3D; Delta: TPointF; I: Integer; begin FEndLocal := MovePoint(FStartLocal, DeltaX, DeltaY, 0.0); FEndAngle := FStartAngle + FAngleRotateX; if FSegments10Deg < 1 then FSegments10Deg := 1; DeltaAlpha := FAngleRotateX / FSegments10Deg; LastAlpha := FStartAngle; I := 1; PrvLocal := FStartLocal; While I < FSegments10Deg do Begin NxtAlpha := LastAlpha + DeltaAlpha; Delta := GetDeltaXY(LastAlpha, DeltaAlpha); NxtLocal.X := PrvLocal.X + Delta.X; NxtLocal.Y := PrvLocal.Y + Delta.Y; NxtLocal.Z := PrvLocal.Z; AddCylinder(FRadius, PrvLocal.X, PrvLocal.Y, PrvLocal.Z, LastAlpha, FRadius, NxtLocal.X, NxtLocal.Y, NxtLocal.Z, NxtAlpha, NxtData, NxtIndex, false, false); LastAlpha := NxtAlpha; PrvLocal := NxtLocal; Inc(I); End; AddCylinder(FRadius, PrvLocal.X, PrvLocal.Y, PrvLocal.Z, LastAlpha, FRadius, FEndLocal.X, FEndLocal.Y, FEndLocal.Z, FEndAngle, NxtData, NxtIndex, false, false); inherited; end; constructor TRodBend.CreateFrmTxt(AText: AnsiString); Var Flag: AnsiString; AngleXAsDegrees: Single; begin inherited Create; Flag := GetTokenXE3(AText, ',()'); if uppercase(Flag) <> 'B' then raise Exception.Create('TRodBend.CreateFrmTxt::' + AText); // Model Flag, Rod Radius, Bend Radius (To Center) , Bend Angle in Degrees // Example 'B,0.2,0.5,-90.0' SetFltValueFrmArrayString(FRadius, AText); SetFltValueFrmArrayString(FBendRadius, AText); SetFltValueFrmArrayString(AngleXAsDegrees, AText); if AngleXAsDegrees <> 0.0 then FAngleRotateX := AngleXAsDegrees / 180 * Pi; end; function TRodBend.DeltaX: Real; begin Result := GetDeltaXY(FStartAngle, FAngleRotateX).X; end; function TRodBend.DeltaY: Real; begin Result := GetDeltaXY(FStartAngle, FAngleRotateX).Y; end; function TRodBend.GetDeltaXY(AStartAngle, ADeltaAngle: Single): TPointF; Var CordLen: Single; HalfAngle, BaseAngle: Single; begin HalfAngle := ADeltaAngle / 2; CordLen := FBendRadius * 2 * Sin(HalfAngle); BaseAngle := AStartAngle + HalfAngle; Result.X := CordLen * Cos(BaseAngle); Result.Y := CordLen * Sin(BaseAngle); if ADeltaAngle < 0.0 then Begin Result.X := -Result.X; Result.Y := -Result.Y; End; end; function TRodBend.NoOfIndexes: Integer; begin // 6 Lines Indexs per Square // FSegments10Deg Squares per Length FSegments10Deg := Abs(Round(FAngleRotateX / (Pi / 18))); Result := RadiusSections * 6 * FSegments10Deg + Inherited; Result := Result; end; function TRodBend.NoOfVertexes: Integer; begin // 4 Vertexes per Square // FSegments10Deg Squares per Length FSegments10Deg := Abs(Round(FAngleRotateX / (Pi / 18))); Result := RadiusSections * 4 * FSegments10Deg + Inherited; Result := Result; end; end.
unit uCommRecEditor; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Math, System.Classes, Vcl.Graphics, Vcl.StdCtrls, System.StrUtils, System.TypInfo, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, DBAccess, Ora, Vcl.ComCtrls, Vcl.ToolWin, System.Actions, Vcl.ActnList, Vcl.ExtCtrls, CodeSiteLogging, DBCtrlsEh, DBGridEh, DBLookupEh, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, EhLibVCL, GridsEh, DBAxisGridsEh, System.Notification, OraSmart; type TChangeHandler = procedure(Sender: TObject) of object; type TfrmCommRecEditor = class(TForm) pnlTop: TPanel; ALCommon: TActionList; actSaveAndClose: TAction; actRevertChanges: TAction; actClose: TAction; StatusBar: TStatusBar; tbarCommomActions: TToolBar; tbtnClose: TToolButton; tbtnRevert: TToolButton; tbtnSaveClose: TToolButton; odsRecord: TOraDataSource; odsMaster: TOraDataSource; tbarSpecActions: TToolBar; actSave: TAction; tbtnSave: TToolButton; tbarClose: TToolBar; shpAlert: TShape; procedure actCloseExecute(Sender: TObject); virtual; procedure actRevertChangesExecute(Sender: TObject); virtual; procedure FormShow(Sender: TObject); procedure actSaveAndCloseExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); virtual; private function IsVisualCompDBAware(const aComp: TComponent): boolean; function IsMandatoryField(const aComp: TComponent): boolean; procedure WMSysCommand(var Msg: TWMSysCommand); message WM_SYSCOMMAND; published FMandatiryFields: TStringList; procedure CommonEditChange(Sender: TObject); virtual; procedure CommonEditExit(Sender: TObject); virtual; function IsMandatoryFieldsFilled: boolean; virtual; function GetStrValForProps(const aComp: TComponent; Props: TArray<string>) : string; virtual; procedure HideAlertOnControl; virtual; procedure RiseAlertOnControl(const aComp: TControl = nil; const aMessage: string = ''); virtual; // procedure EnableListedControls(var CompList: TArray<TControl>); virtual; public FCanLeave: boolean; // FCanClose: boolean; procedure SetChangeHandlerToAllDbEdits(aHandle: TChangeHandler = nil); procedure SetExitHandlerToAllDbEdits(aHandle: TChangeHandler = nil); constructor Create(Sender: TComponent; dsMaster, dsRecord: TOraDataSource); end; implementation {$R *.dfm} uses uGlobals, uDMCore; { TfCommRecEditor } procedure TfrmCommRecEditor.actCloseExecute(Sender: TObject); var i: integer; begin try SetChangeHandlerToAllDbEdits; // nil to all SetExitHandlerToAllDbEdits; // nil to all if odsRecord.DataSet.State in [dsInsert, dsEdit] then odsRecord.DataSet.Cancel; for i := pred(odsRecord.Owner.ComponentCount) downto 0 do // close in backward order if (odsRecord.Owner.Components[i] is TOraTable) and (TOraTable(odsRecord.Owner.Components[i]).Active) then begin if TOraTable(odsRecord.Owner.Components[i]).State in [dsInsert, dsEdit] then TOraTable(odsRecord.Owner.Components[i]).Cancel; TOraTable(odsRecord.Owner.Components[i]).Close; end; finally ModalResult := Math.IfThen((Sender = actSaveAndClose), mrOK, mrCancel); end; end; procedure TfrmCommRecEditor.actRevertChangesExecute(Sender: TObject); begin HideAlertOnControl; if odsRecord.DataSet.State in [dsInsert, dsEdit] then odsRecord.DataSet.Cancel; if (gvOpenManner = omNew) and (Sender = actRevertChanges) then begin gvOpenManner := omRead; { TODO : precise gvOpenManner here } actCloseExecute(Sender); // just close form end else begin tbarCommomActions.Visible := false; tbarSpecActions.Visible := true; tbarClose.Visible := true; self.Refresh; end; end; procedure TfrmCommRecEditor.actSaveExecute(Sender: TObject); var pTable, pOper, pDog, pDogType, pKPRED, pMode: string; pGod: integer; const cOrgDM = 'dmOrgs'; cDogDM = 'dmDogs'; begin if self.ActiveControl is TDBEditEh then begin self.CommonEditExit(self.ActiveControl); // force exit rules if not FCanLeave then exit; end; odsRecord.DataSet.Post; actRevertChangesExecute(Sender); pOper := IfThen(gvOpenManner = omNew, 'новая запись', 'корректировка'); If odsRecord.Owner.Name = cOrgDM then begin pTable := 'орг-ции'; pDog := EmptyStr; pDogType := EmptyStr; pGod := 0; pKPRED := EmptyStr; end else If odsRecord.Owner.Name = cDogDM then begin pTable := 'договоры'; pDog := odsRecord.DataSet.FieldByName('DOG').AsString; pDogType := odsRecord.DataSet.FieldByName(gcFldDogType).AsString; pGod := odsRecord.DataSet.FieldByName(gcFldDogID).AsInteger; pKPRED := '4'; end; if gvOpenManner = omNew then begin pMode := 'new'; TOraTable(odsRecord.DataSet).RefreshRecord; gvOpenManner := omEdit; If odsRecord.Owner.Name = cOrgDM then gvOrgID := odsRecord.DataSet.FieldByName (TOraTable(odsRecord.DataSet).KeyFields).AsInteger else If odsRecord.Owner.Name = cDogDM then gvDogID := odsRecord.DataSet.FieldByName (TOraTable(odsRecord.DataSet).KeyFields).AsInteger; self.FormShow(self); end else pMode := 'old'; If (odsRecord.Owner.Name = cOrgDM) or (odsRecord.Owner.Name = cDogDM) then dmCore.SetTCORRRecord(pMode, pTable, pOper, pDog, pKPRED, pDogType, gvOrgID, pGod); HideAlertOnControl; end; procedure TfrmCommRecEditor.actSaveAndCloseExecute(Sender: TObject); begin actSaveExecute(Sender); actCloseExecute(Sender); end; procedure TfrmCommRecEditor.CommonEditChange(Sender: TObject); begin if (odsRecord.DataSet.State in [dsInsert, dsEdit]) and (not tbarCommomActions.Visible) then begin tbarClose.Visible := false; tbarSpecActions.Visible := false; tbarCommomActions.Visible := true; self.Refresh; end; end; function TfrmCommRecEditor.IsMandatoryField(const aComp: TComponent): boolean; var i: integer; begin result := false; for i := 0 to pred(FMandatiryFields.Count) do if aComp.Name = FMandatiryFields.ValueFromIndex[i] then begin result := true; break; end; end; function TfrmCommRecEditor.IsMandatoryFieldsFilled: boolean; var i: integer; aComp: TComponent; aValue: string; begin result := false; for i := 0 to pred(FMandatiryFields.Count) do begin aComp := self.FindComponent(FMandatiryFields.ValueFromIndex[i]); if assigned(aComp) then begin aValue := EmptyStr; if aComp is TDBEditEh then aValue := TDBEditEh(aComp).Text else if aComp is TDBComboBoxEh then aValue := TDBComboBoxEh(aComp).Text else if aComp is TDBMemoEh then aValue := TDBMemoEh(aComp).Text else if aComp is TDBDateTimeEditEh then aValue := varToStr(TDBDateTimeEditEh(aComp).Value) else if aComp is TDBLookupComboboxEh then aValue := TDBLookupComboboxEh(aComp).Text; if aValue = EmptyStr then RiseAlertOnControl(TControl(aComp), 'Обязательное поле!'); end; end; result := true; end; procedure TfrmCommRecEditor.CommonEditExit(Sender: TObject); begin FCanLeave := true; // trim blanks and turn single quotes to double if any if TDBEditEh(Sender).Text <> Trim(ReplaceStr(TDBEditEh(Sender).Text, '''', '"')) then TDBEditEh(Sender).Text := Trim(ReplaceStr(TDBEditEh(Sender).Text, '''', '"')); // check whether mandatory field is not empty if IsMandatoryField(TComponent(Sender)) and (TDBEditEh(Sender).Text = EmptyStr) then begin ShowMessage(gcIMMandatoryField); TWinControl(Sender).SetFocus; FCanLeave := false; end; end; constructor TfrmCommRecEditor.Create(Sender: TComponent; dsMaster, dsRecord: TOraDataSource); begin inherited Create(Sender); self.odsMaster := dsMaster; self.odsRecord := dsRecord; self.FMandatiryFields := TStringList.Create; self.FMandatiryFields.StrictDelimiter := true; self.FMandatiryFields.Delimiter := ','; if pos('AdminRefs', TForm(Sender).Name) = 0 then self.Height := TForm(Sender).Parent.Height - 20; end; //procedure TfrmCommRecEditor.EnableListedControls(var CompList // : TArray<TControl>); //const // cEnabled = 'Enabled'; //var // Comp: TControl; //begin // for Comp in CompList do // if assigned(GetPropInfo(Comp.ClassInfo, cEnabled)) then // SetPropValue(Comp, cEnabled, long(true)); //end; procedure TfrmCommRecEditor.FormShow(Sender: TObject); var i: integer; begin if gvOpenManner = omRead then begin // turn controls to RO state self.Caption := self.Caption + gcAccessTypeRO; for i := 0 to pred(ComponentCount) do if Components[i] is TGroupBox then // assume all child controls must be disabled TurnContainerChildsToRO(Components[i]); end else begin SetChangeHandlerToAllDbEdits(CommonEditChange); SetExitHandlerToAllDbEdits(CommonEditExit); self.Caption := self.Caption + IfThen(gvOpenManner = omNew, gcAccessTypeNewRecord, gcAccessTypeEdit); for i := 0 to pred(ComponentCount) do if Components[i] is TGroupBox then // assume all child controls must be enabled TurnContainerChildsToRW(Components[i]); end; end; function TfrmCommRecEditor.GetStrValForProps(const aComp: TComponent; Props: TArray<string>): string; var aPropInfo: PPropInfo; i: integer; begin result := EmptyStr; for i := 0 to pred(Length(Props)) do begin aPropInfo := GetPropInfo(aComp.ClassInfo, Props[i]); if assigned(aPropInfo) then begin result := GetStrProp(aComp, Props[i]); break; end; end; end; function TfrmCommRecEditor.IsVisualCompDBAware(const aComp: TComponent) : boolean; begin result := (assigned(GetPropInfo(aComp.ClassInfo, 'Visible')) and assigned(GetPropInfo(aComp.ClassInfo, 'DataField'))); end; procedure TfrmCommRecEditor.SetChangeHandlerToAllDbEdits (aHandle: TChangeHandler = nil); var i: integer; begin for i := 0 to pred(ComponentCount) do begin try if IsVisualCompDBAware(Components[i]) then begin if Components[i] is TDBCheckBoxEh then TDBCheckBoxEh(Components[i]).OnClick := aHandle // OnClick is a lone else if Components[i] is TDBEditEh then // all others is OnChange TDBEditEh(Components[i]).OnChange := aHandle else if Components[i] is TDBNumberEditEh then TDBNumberEditEh(Components[i]).OnChange := aHandle else if Components[i] is TDBMemoEh then TDBMemoEh(Components[i]).OnChange := aHandle else if Components[i] is TDBLookupComboboxEh then TDBLookupComboboxEh(Components[i]).OnChange := aHandle else if Components[i] is TDBDateTimeEditEh then TDBDateTimeEditEh(Components[i]).OnChange := aHandle else if Components[i] is TDBComboBoxEh then TDBComboBoxEh(Components[i]).OnChange := aHandle; end; except on e: Exception do codesite.Send('Bad attempt while assigning Event Handler to component ' + Components[i].Name + sLineBreak + e.Message); end; end; end; procedure TfrmCommRecEditor.SetExitHandlerToAllDbEdits (aHandle: TChangeHandler = nil); var i: integer; begin for i := 0 to pred(ComponentCount) do if (Components[i] is TDBEditEh) and TDBEditEh(Components[i]).Enabled then TDBEditEh(Components[i]).OnExit := aHandle; end; procedure TfrmCommRecEditor.WMSysCommand(var Msg: TWMSysCommand); begin if Msg.CmdType = SC_MINIMIZE then Application.Minimize else if (Msg.CmdType = SC_CLOSE) and tbarCommomActions.Visible then Abort else inherited; end; procedure TfrmCommRecEditor.HideAlertOnControl(); begin RiseAlertOnControl(); end; procedure TfrmCommRecEditor.RiseAlertOnControl(const aComp: TControl = nil; const aMessage: string = ''); begin if assigned(aComp) then begin shpAlert.Parent := aComp.Parent; shpAlert.Left := aComp.Left - shpAlert.Pen.Width; shpAlert.Top := aComp.Top - shpAlert.Pen.Width; shpAlert.Width := aComp.Width + 2 * shpAlert.Pen.Width; shpAlert.Height := aComp.Height + 2 * shpAlert.Pen.Width; shpAlert.Show; TWinControl(aComp).SetFocus; end else shpAlert.Hide; if not aMessage.IsEmpty then raise Exception.Create(aMessage); end; end.
unit TextEditor.SyncEdit.Colors; interface uses System.Classes, System.UITypes, TextEditor.Consts; type TTextEditorSyncEditColors = class(TPersistent) strict private FBackground: TColor; FEditBorder: TColor; FWordBorder: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write FBackground default TDefaultColors.SyncEditBackground; property EditBorder: TColor read FEditBorder write FEditBorder default TColors.SysWindowText; property WordBorder: TColor read FWordBorder write FWordBorder default TColors.SysHighlight; end; implementation constructor TTextEditorSyncEditColors.Create; begin inherited; FBackground := TDefaultColors.SyncEditBackground; FEditBorder := TColors.SysWindowText; FWordBorder := TColors.SysHighlight; end; procedure TTextEditorSyncEditColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorSyncEditColors) then with ASource as TTextEditorSyncEditColors do begin Self.FBackground := FBackground; Self.FEditBorder := FEditBorder; Self.FWordBorder := FWordBorder; end else inherited Assign(ASource); end; end.
(** * $Id: dco.transport.Transport.pas 840 2014-05-24 06:04:58Z QXu $ * * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the License for the specific language governing rights and limitations under the License. *) unit dco.transport.Transport; interface uses dco.transport.Pdu; type /// <summary>The interface defines the basic behaviors of a transport resource.</summary> ITransport = interface /// <summary>Returns the identifier of the transport resource.</summary> function GetUri: string; /// <summary>Blocks until an inbound message is retrieved.</summary> function Read: TPdu; /// <summary>Sends an outbound message and waits for it is actually sent out.</summary> function WriteEnsured(const Pdu: TPdu): Boolean; /// <summary>Sends an outbound message and returns immediately.</summary> procedure Write(const Pdu: TPdu); /// <summary>Pushs an inbound message to the recipient.</summary> procedure ForceRead(const Pdu: TPdu); end; implementation end.
unit UFormFreeEdition; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, ImgList; type TfrmFreeEdition = class(TForm) nbMain: TNotebook; plEditionCompare: TPanel; Panel2: TPanel; lvEditionCompare: TListView; plError: TPanel; lbDisplay: TLabel; IWarnning: TImage; Panel1: TPanel; btnBuyNow: TButton; btnClose: TButton; plImfomationBtn: TPanel; btnMoreInfomation: TButton; btnErrorClose: TButton; ilEdition: TImageList; procedure btnMoreInfomationClick(Sender: TObject); procedure btnErrorCloseClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnBuyNowClick(Sender: TObject); private procedure SetEdtionComparePage; public procedure ShowWarnning( WarnningStr : string ); procedure ShowInfomation; end; const Page_Error = 0; Page_EditionCompare = 1; var frmFreeEdition: TfrmFreeEdition; implementation uses UMyUtil, UMyUrl; {$R *.dfm} { TfrmFreeEdition } procedure TfrmFreeEdition.btnBuyNowClick(Sender: TObject); begin MyInternetExplorer.OpenWeb( MyUrl.BuyNow ); end; procedure TfrmFreeEdition.btnCloseClick(Sender: TObject); begin Close; end; procedure TfrmFreeEdition.btnErrorCloseClick(Sender: TObject); begin Close; end; procedure TfrmFreeEdition.btnMoreInfomationClick(Sender: TObject); begin SetEdtionComparePage; end; procedure TfrmFreeEdition.SetEdtionComparePage; begin nbMain.PageIndex := Page_EditionCompare; Self.Width := 520; Self.Height := 212; end; procedure TfrmFreeEdition.ShowInfomation; begin SetEdtionComparePage; Show; end; procedure TfrmFreeEdition.ShowWarnning(WarnningStr: string); var btnInfomationWidth : Integer; begin lbDisplay.Caption := WarnningStr; nbMain.PageIndex := Page_Error; Self.Width := lbDisplay.Left + lbDisplay.Width + 30; Self.Height := plImfomationBtn.Top + plImfomationBtn.Height + 50; plImfomationBtn.Left := IWarnning.Left + ( ( lbDisplay.Left - IWarnning.Left + lbDisplay.Width - plImfomationBtn.Width ) div 2 ); Show; end; end.
unit instructions_encoder; interface uses parser,strutils,sysutils; type bin_ptr=^bin; bin= record code:ShortString; next:bin_ptr; end; { pointer_to_list_element = ^list_element; list_element = record string_number:longint; code:ShortString; next:pointer_to_list_element; end;} function list_to_bin(mnemonics:pointer_to_list_element):bin_ptr; implementation function encode_a_instruction(instruction:ShortString):ShortString; var int_val:longint; begin {instruction[1]:='';} int_val:=StrToInt(instruction[2..length(instruction)]); encode_a_instruction:=IntToBin(int_val,16); end; function encode_dest_bits(letters:ShortString):ShortString; var i:integer; a,b,c:ShortString; begin {if length(letters>3) then writeln('Error: too many destinations=)');} a:='0'; b:='0'; c:='0'; for i:=1 to length(letters) do begin if letters[i]= 'A' then a:='1'; if letters[i]= 'D' then b:='1'; if letters[i]= 'M' then c:='1'; end; encode_dest_bits:=a+b+c; end; function encode_jump_bits(letters:ShortString):ShortString; var a,b,c:shortString; i:integer; begin a:='0'; b:='0'; c:='0'; for i:=1 to length(letters) do begin if letters[i]='G' then c:='1'; if (letters[i]='E') and (letters[i-1]<>'N') then b:='1'; if letters[i]='L' then a:='1'; if letters[i]='M' then begin a:='1'; b:='1'; c:='1'; end; if letters[i]='N' then begin a:='1'; b:='0'; c:='1'; end; end; encode_jump_bits:=a+b+c; end; function encode_comp_bits(m:ShortString):ShortString;{Vrry painfull function} var i:integer; a,cmpbts:ShortString; begin {$IFDEF DEBUG} writeln('Code_mnemonics= ',m); {$ENDIF} for i:=1 to length(m) do begin if m[i]='M' then begin a:='1'; break; end else a:='0'; end; if m='0' then cmpbts:= '101010'; if m='1' then cmpbts:= '111111'; if m='-1' then cmpbts:= '111010'; if m='D' then cmpbts:= '001100'; if (m='A') or (m='M') then cmpbts:= '110000'; if m='!D' then cmpbts:= '001101'; if (m='!A') or (m='!M') then cmpbts:= '110001'; if m='-D' then cmpbts:= '001111'; if (m='-A') or (m='-M') then cmpbts:= '110011'; if (m='D-1') then cmpbts:='001110'; if (m='A-1') or (m='M-1') then cmpbts:= '110010'; if (m='D+1') or (m='1+D') then cmpbts:= '011111'; if (m='A+1') or (m='M+1') or (m='1+A') or (m='1+M') then cmpbts:= '110111'; if (m='D+A') or (m='D+M') or (m='A+D') or (m='M+D') then cmpbts:= '000010'; if (m='D-A') or (m='D-M') then cmpbts:= '010011'; if (m='A-D') or (m='M-D') then cmpbts:= '000111'; if (m='D&A') or (m='D&M') or (m='A&D') or (m='M&D') then cmpbts:= '000000'; if (m='D|A') or (m='D|M') or (m='A|D') or (m='M|D') then cmpbts:= '010101'; encode_comp_bits:= a+cmpbts; end; function encode_c_instruction(instruction:ShortString):ShortString; var dest,cmp,jump,comp_part:ShortString; start_of_comp,end_of_comp,i:integer; begin start_of_comp:=1; end_of_comp:=length(instruction); dest:='000'; cmp:='0000000'; jump:='000'; for i:=1 to length(instruction) do begin if instruction[i]='=' then begin dest:=copy(instruction,1,i-1); dest:=encode_dest_bits(dest); start_of_comp:=i+1; end; if instruction[i]=';' then begin jump:=copy(instruction,i+1,length(instruction)); jump:=encode_jump_bits(jump); end_of_comp:=i-1; end; end; comp_part:=copy(instruction,start_of_comp,end_of_comp); cmp:=encode_comp_bits(comp_part); encode_c_instruction:='111'+cmp+dest+jump; end; function mnemonics_to_binary(mnemonic:ShortString) :ShortString; begin {$IFDEF DEBUG} writeln('Mnemonics = ',mnemonic); {$ENDIF} if mnemonic[1]='@' then begin mnemonics_to_binary:=encode_a_instruction(mnemonic); end else begin mnemonics_to_binary:=encode_c_instruction(mnemonic); end; end; function list_to_bin(mnemonics:pointer_to_list_element):bin_ptr; var code:ShortString; tmp:pointer_to_list_element; tmp1:bin_ptr; first:bin_ptr; current:bin_ptr; i:integer; begin {code:=mnemonics^.code;} tmp:=mnemonics; i:=0; new(tmp1); while tmp^.code<>'end of code' do begin i:=i+1; code:=tmp^.code; tmp1^.code:=mnemonics_to_binary(code); if i=1 then begin first:=tmp1; end; tmp:=tmp^.next; current:=tmp1; new(tmp1); tmp1^.code:='end of code'; current^.next:=tmp1; end; list_to_bin:=first; end; {$IFDEF DEBUG} var file_name:ShortString; mnemonics:pointer_to_list_element; res,tmp1:bin_ptr; f2:text; {$ENDIF} begin {$IFDEF DEBUG} writeln(paramstr(1)); file_name:=paramstr(1); writeln(file_name); writeln(length(file_name)); {Name of source code file is passed by command line } {new(mnemonics);} writeln('DEBUG: NOW WE WILL READ THE FILE'); mnemonics:=parse_file(file_name); writeln('DEBUG: OK, NO PROBLEM HERE '); res:=list_to_bin(mnemonics); tmp1:=res; while (tmp1^.code<>'end od code') and assigned(tmp1^.next) do begin writeln(tmp1^.code); tmp1:=tmp1^.next; end; file_name:=file_name+'.hack'; assign(f2,file_name); rewrite(f2); while res^.code<>'end of code' do begin writeln(f2,res^.code); res:=res^.next; end; close(f2); {$ENDIF} end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Bem - Patrimônio The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (alberteije@gmail.com) @version 2.0 ******************************************************************************* } unit UPatrimBem; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, Mask, JvExMask, JvToolEdit, JvCombobox, LabeledCtrls, DBCtrls, LabeledDBCtrls, DB, DBClient, StrUtils, Math, JSonVO, Generics.Collections, Atributos, Constantes, CheckLst, JvExCheckLst, JvCheckListBox, JvBaseEdits, OleCtnrs, WideStrings, FMTBcd, Provider, SqlExpr, DBXMySql, PlatformDefaultStyleActnCtrls, ActnList, ActnMan, ToolWin, ActnCtrls, ShellApi, Biblioteca, System.Actions, Controller; type [TFormDescription(TConstantes.MODULO_PATRIMONIO, 'Bem')] TFPatrimBem = class(TFTelaCadastro) ScrollBox: TScrollBox; EditNome: TLabeledEdit; EditNumero: TLabeledEdit; BevelEdits: TBevel; PageControlDadosPatrimBem: TPageControl; tsDadosComplementares: TTabSheet; tsDocumentoBem: TTabSheet; PanelDocumentacao: TPanel; GridDocumentacao: TJvDBUltimGrid; tsDepreciacaoBem: TTabSheet; PanelDepreciacao: TPanel; GridDepreciacao: TJvDBUltimGrid; EditIdTipoAquisicao: TLabeledCalcEdit; EditTipoAquisicaoNome: TLabeledEdit; EditIdSetor: TLabeledCalcEdit; EditSetorNome: TLabeledEdit; PanelDadosComplementares: TPanel; EditDataAquisicao: TLabeledDateEdit; MemoDescricao: TLabeledMemo; EditDataAceite: TLabeledDateEdit; EditDataCadastro: TLabeledDateEdit; EditValorOriginal: TLabeledCalcEdit; MemoFuncao: TLabeledMemo; CDSPatrimDocumentoBem: TClientDataSet; DSPatrimDocumentoBem: TDataSource; CDSPatrimDepreciacaoBem: TClientDataSet; DSPatrimDepreciacaoBem: TDataSource; tsMovimentacaoBem: TTabSheet; PanelMovimentacao: TPanel; GridMovimentacao: TJvDBUltimGrid; CDSPatrimMovimentacaoBem: TClientDataSet; DSPatrimMovimentacaoBem: TDataSource; CDSPatrimDepreciacaoBemID: TIntegerField; CDSPatrimDepreciacaoBemID_PATRIM_BEM: TIntegerField; CDSPatrimDepreciacaoBemDATA_DEPRECIACAO: TDateField; CDSPatrimDepreciacaoBemDIAS: TIntegerField; CDSPatrimDepreciacaoBemTAXA: TFMTBCDField; CDSPatrimDepreciacaoBemINDICE: TFMTBCDField; CDSPatrimDepreciacaoBemVALOR: TFMTBCDField; CDSPatrimDepreciacaoBemDEPRECIACAO_ACUMULADA: TFMTBCDField; CDSPatrimMovimentacaoBemID: TIntegerField; CDSPatrimMovimentacaoBemID_PATRIM_BEM: TIntegerField; CDSPatrimMovimentacaoBemID_PATRIM_TIPO_MOVIMENTACAO: TIntegerField; CDSPatrimMovimentacaoBemDATA_MOVIMENTACAO: TDateField; CDSPatrimMovimentacaoBemRESPONSAVEL: TStringField; EditGrupoBemNome: TLabeledEdit; EditIdGrupoBem: TLabeledCalcEdit; EditIdColaborador: TLabeledCalcEdit; EditColaboradorNome: TLabeledEdit; EditIdFornecedor: TLabeledCalcEdit; EditFornecedorNome: TLabeledEdit; EditIdEstadoConservacao: TLabeledCalcEdit; EditEstadoConservacaoNome: TLabeledEdit; EditNumeroSerie: TLabeledEdit; EditDataContabilizado: TLabeledDateEdit; EditDataVistoria: TLabeledDateEdit; EditDataMarcacao: TLabeledDateEdit; EditDataBaixa: TLabeledDateEdit; EditDataVencimentoGarantia: TLabeledDateEdit; EditNumeroNF: TLabeledEdit; EditChaveNFe: TLabeledEdit; EditValorCompra: TLabeledCalcEdit; EditValorAtualizado: TLabeledCalcEdit; GroupBoxDepreciacao: TGroupBox; EditValorBaixa: TLabeledCalcEdit; ComboDeprecia: TLabeledComboBox; ComboMetodoDepreciacao: TLabeledComboBox; ComboTipoDepreciacao: TLabeledComboBox; EditInicioDepreciacao: TLabeledDateEdit; EditUltimaDepreciacao: TLabeledDateEdit; EditTaxaAnualDepreciacao: TLabeledCalcEdit; EditTaxaMensalDepreciacao: TLabeledCalcEdit; EditTaxaDepreciacaoAcelerada: TLabeledCalcEdit; EditTaxaDepreciacaoIncentivada: TLabeledCalcEdit; ActionToolBarDepreciacao: TActionToolBar; ActionManagerBem: TActionManager; ActionCalcularDepreciacao: TAction; CDSPatrimDocumentoBemID: TIntegerField; CDSPatrimDocumentoBemID_PATRIM_BEM: TIntegerField; CDSPatrimDocumentoBemNOME: TStringField; CDSPatrimDocumentoBemDESCRICAO: TStringField; CDSPatrimDocumentoBemIMAGEM: TStringField; CDSPatrimDocumentoBemPERSISTE: TStringField; CDSPatrimDepreciacaoBemPERSISTE: TStringField; CDSPatrimMovimentacaoBemPATRIM_TIPO_MOVIMENTACAONOME: TStringField; CDSPatrimMovimentacaoBemPERSISTE: TStringField; ActionToolBar1: TActionToolBar; ActionAcionarGed: TAction; procedure FormCreate(Sender: TObject); procedure GridDocumentacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridDepreciacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GridMovimentacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ActionCalcularDepreciacaoExecute(Sender: TObject); procedure CDSPatrimDocumentoBemAfterEdit(DataSet: TDataSet); procedure CDSPatrimDepreciacaoBemAfterEdit(DataSet: TDataSet); procedure CDSPatrimMovimentacaoBemAfterEdit(DataSet: TDataSet); procedure ActionAcionarGedExecute(Sender: TObject); procedure EditIdSetorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdFornecedorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdGrupoBemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdTipoAquisicaoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdEstadoConservacaoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } IdTipoPatrimBem: Integer; public { Public declarations } procedure GridParaEdits; override; procedure LimparCampos; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; procedure ConfigurarLayoutTela; end; var FPatrimBem: TFPatrimBem; implementation uses NotificationService, PatrimBemVO, PatrimBemController, PatrimDocumentoBemVO, PatrimDepreciacaoBemVO, PatrimMovimentacaoBemVO, ULookup, UDataModule, PatrimTipoAquisicaoBemVO, PatrimTipoAquisicaoBemController, ViewPessoaColaboradorVO, ViewPessoaColaboradorController, PatrimEstadoConservacaoVO, PatrimEstadoConservacaoController, ViewPessoaFornecedorVO, ViewPessoaFornecedorController, PatrimGrupoBemVO, PatrimGrupoBemController, SetorVO, SetorController, PatrimTipoMovimentacaoVO, PatrimTipoMovimentacaoController; {$R *.dfm} {$REGION 'Infra'} procedure TFPatrimBem.FormCreate(Sender: TObject); var Form: TForm; begin ClasseObjetoGridVO := TPatrimBemVO; ObjetoController := TPatrimBemController.Create; inherited; end; procedure TFPatrimBem.LimparCampos; var i: Integer; begin inherited; CDSPatrimDocumentoBem.EmptyDataSet; CDSPatrimDepreciacaoBem.EmptyDataSet; CDSPatrimMovimentacaoBem.EmptyDataSet; ConfigurarLayoutTela; end; procedure TFPatrimBem.ConfigurarLayoutTela; begin PanelEdits.Enabled := True; PageControlDadosPatrimBem.ActivePageIndex := 0; if StatusTela = stNavegandoEdits then begin PanelDadosComplementares.Enabled := False; GridDocumentacao.ReadOnly := True; GridDepreciacao.ReadOnly := True; GridMovimentacao.ReadOnly := True; end else begin PanelDadosComplementares.Enabled := True; GridDocumentacao.ReadOnly := False; GridDepreciacao.ReadOnly := False; GridMovimentacao.ReadOnly := False; end; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFPatrimBem.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdSetor.SetFocus; end; end; function TFPatrimBem.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdSetor.SetFocus; end; end; function TFPatrimBem.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('PatrimBemController.TPatrimBemController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('PatrimBemController.TPatrimBemController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFPatrimBem.DoSalvar: Boolean; var DocumentoBemVO: TPatrimDocumentoBemVO; DepreciacaoBemVO: TPatrimDepreciacaoBemVO; MovimentacaoBemVO: TPatrimMovimentacaoBemVO; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TPatrimBemVO.Create; TPatrimBemVO(ObjetoVO).IdPatrimTipoAquisicaoBem := EditIdTipoAquisicao.AsInteger; TPatrimBemVO(ObjetoVO).PatrimTipoAquisicaoBemNome := EditTipoAquisicaoNome.Text; TPatrimBemVO(ObjetoVO).IdPatrimEstadoConservacao := EditIdEstadoConservacao.AsInteger; TPatrimBemVO(ObjetoVO).PatrimEstadoConservacaoNome := EditEstadoConservacaoNome.Text; TPatrimBemVO(ObjetoVO).IdPatrimGrupoBem := EditIdGrupoBem.AsInteger; TPatrimBemVO(ObjetoVO).PatrimGrupoBemNome := EditGrupoBemNome.Text; TPatrimBemVO(ObjetoVO).IdSetor := EditIdSetor.AsInteger; /// EXERCICIO: permita que o usuário informe o centro de resultado ou preencha de forma dinâmica TPatrimBemVO(ObjetoVO).IdCentroResultado := 1; TPatrimBemVO(ObjetoVO).SetorNome := EditSetorNome.Text; TPatrimBemVO(ObjetoVO).IdFornecedor := EditIdFornecedor.AsInteger; TPatrimBemVO(ObjetoVO).FornecedorPessoaNome := EditFornecedorNome.Text; TPatrimBemVO(ObjetoVO).IdColaborador := EditIdColaborador.AsInteger; TPatrimBemVO(ObjetoVO).ColaboradorPessoaNome := EditColaboradorNome.Text; TPatrimBemVO(ObjetoVO).NumeroNb := EditNumero.Text; TPatrimBemVO(ObjetoVO).Nome := EditNome.Text; TPatrimBemVO(ObjetoVO).Descricao := MemoDescricao.Text; TPatrimBemVO(ObjetoVO).NumeroSerie := EditNumeroSerie.Text; TPatrimBemVO(ObjetoVO).DataAquisicao := EditDataAquisicao.Date; TPatrimBemVO(ObjetoVO).DataAceite := EditDataAceite.Date; TPatrimBemVO(ObjetoVO).DataCadastro := EditDataCadastro.Date; TPatrimBemVO(ObjetoVO).DataContabilizado := EditDataContabilizado.Date; TPatrimBemVO(ObjetoVO).DataVistoria := EditDataVistoria.Date; TPatrimBemVO(ObjetoVO).DataMarcacao := EditDataMarcacao.Date; TPatrimBemVO(ObjetoVO).DataBaixa := EditDataBaixa.Date; TPatrimBemVO(ObjetoVO).VencimentoGarantia := EditDataVencimentoGarantia.Date; TPatrimBemVO(ObjetoVO).NumeroNotaFiscal := EditNumeroNF.Text; TPatrimBemVO(ObjetoVO).ChaveNfe := EditChaveNFe.Text; TPatrimBemVO(ObjetoVO).ValorOriginal := EditValorOriginal.Value; TPatrimBemVO(ObjetoVO).ValorCompra := EditValorCompra.Value; TPatrimBemVO(ObjetoVO).ValorAtualizado := EditValorAtualizado.Value; TPatrimBemVO(ObjetoVO).ValorBaixa := EditValorBaixa.Value; TPatrimBemVO(ObjetoVO).Deprecia := Copy(ComboDeprecia.Text, 1, 1); TPatrimBemVO(ObjetoVO).MetodoDepreciacao := Copy(ComboMetodoDepreciacao.Text, 1, 1); TPatrimBemVO(ObjetoVO).InicioDepreciacao := EditInicioDepreciacao.Date; TPatrimBemVO(ObjetoVO).UltimaDepreciacao := EditUltimaDepreciacao.Date; TPatrimBemVO(ObjetoVO).TipoDepreciacao := Copy(ComboTipoDepreciacao.Text, 1, 1); TPatrimBemVO(ObjetoVO).TaxaAnualDepreciacao := EditTaxaAnualDepreciacao.Value; TPatrimBemVO(ObjetoVO).TaxaMensalDepreciacao := EditTaxaMensalDepreciacao.Value; TPatrimBemVO(ObjetoVO).TaxaDepreciacaoAcelerada := EditTaxaDepreciacaoAcelerada.Value; TPatrimBemVO(ObjetoVO).TaxaDepreciacaoIncentivada := EditTaxaDepreciacaoIncentivada.Value; TPatrimBemVO(ObjetoVO).Funcao := MemoFuncao.Text; // Documento /// EXERCICIO - TENTE IMPLEMENTAR OS DADOS DA LISTA DE DETALHES DE ACORDO COM O NOVO MODELO PROPOSTO NA INFRA CDSPatrimDocumentoBem.DisableControls; CDSPatrimDocumentoBem.First; while not CDSPatrimDocumentoBem.Eof do begin if (CDSPatrimDocumentoBemPERSISTE.AsString = 'S') or (CDSPatrimDocumentoBemID.AsInteger = 0) then begin DocumentoBemVO := TPatrimDocumentoBemVO.Create; DocumentoBemVO.Id := CDSPatrimDocumentoBemID.AsInteger; DocumentoBemVO.IdPatrimBem := TPatrimBemVO(ObjetoVO).Id; DocumentoBemVO.Nome := CDSPatrimDocumentoBemNOME.AsString; DocumentoBemVO.Descricao := CDSPatrimDocumentoBemDESCRICAO.AsString; DocumentoBemVO.Imagem := CDSPatrimDocumentoBemIMAGEM.AsString; TPatrimBemVO(ObjetoVO).ListaPatrimDocumentoBemVO.Add(DocumentoBemVO); end; CDSPatrimDocumentoBem.Next; end; CDSPatrimDocumentoBem.First; CDSPatrimDocumentoBem.EnableControls; // Depreciação CDSPatrimDepreciacaoBem.DisableControls; CDSPatrimDepreciacaoBem.First; while not CDSPatrimDepreciacaoBem.Eof do begin if (CDSPatrimDepreciacaoBemPERSISTE.AsString = 'S') or (CDSPatrimDepreciacaoBemID.AsInteger = 0) then begin DepreciacaoBemVO := TPatrimDepreciacaoBemVO.Create; DepreciacaoBemVO.Id := CDSPatrimDepreciacaoBemID.AsInteger; DepreciacaoBemVO.IdPatrimBem := TPatrimBemVO(ObjetoVO).Id; DepreciacaoBemVO.DataDepreciacao := CDSPatrimDepreciacaoBemDATA_DEPRECIACAO.AsDateTime; DepreciacaoBemVO.Dias := CDSPatrimDepreciacaoBemDIAS.AsInteger; DepreciacaoBemVO.Taxa := CDSPatrimDepreciacaoBemTAXA.AsExtended; DepreciacaoBemVO.Indice := CDSPatrimDepreciacaoBemINDICE.AsExtended; DepreciacaoBemVO.Valor := CDSPatrimDepreciacaoBemVALOR.AsExtended; DepreciacaoBemVO.DepreciacaoAcumulada := CDSPatrimDepreciacaoBemDEPRECIACAO_ACUMULADA.AsExtended; TPatrimBemVO(ObjetoVO).ListaPatrimDepreciacaoBemVO.Add(DepreciacaoBemVO); end; CDSPatrimDepreciacaoBem.Next; end; CDSPatrimDepreciacaoBem.First; CDSPatrimDepreciacaoBem.EnableControls; // Movimentação CDSPatrimMovimentacaoBem.DisableControls; CDSPatrimMovimentacaoBem.First; while not CDSPatrimMovimentacaoBem.Eof do begin if (CDSPatrimMovimentacaoBemPERSISTE.AsString = 'S') or (CDSPatrimMovimentacaoBemID.AsInteger = 0) then begin MovimentacaoBemVO := TPatrimMovimentacaoBemVO.Create; MovimentacaoBemVO.Id := CDSPatrimMovimentacaoBemID.AsInteger; MovimentacaoBemVO.IdPatrimBem := TPatrimBemVO(ObjetoVO).Id; MovimentacaoBemVO.IdPatrimTipoMovimentacao := CDSPatrimMovimentacaoBemID_PATRIM_TIPO_MOVIMENTACAO.AsInteger; MovimentacaoBemVO.PatrimTipoMovimentacaoNome := CDSPatrimMovimentacaoBemPATRIM_TIPO_MOVIMENTACAONOME.AsString; MovimentacaoBemVO.DataMovimentacao := CDSPatrimMovimentacaoBemDATA_MOVIMENTACAO.AsDateTime; MovimentacaoBemVO.Responsavel := CDSPatrimMovimentacaoBemRESPONSAVEL.AsString; TPatrimBemVO(ObjetoVO).ListaPatrimMovimentacaoBemVO.Add(MovimentacaoBemVO); end; CDSPatrimMovimentacaoBem.Next; end; CDSPatrimMovimentacaoBem.First; CDSPatrimMovimentacaoBem.EnableControls; if StatusTela = stInserindo then begin TController.ExecutarMetodo('PatrimBemController.TPatrimBemController', 'Insere', [TPatrimBemVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TPatrimBemVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('PatrimBemController.TPatrimBemController', 'Altera', [TPatrimBemVO(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 'Campos Transientes'} procedure TFPatrimBem.EditIdTipoAquisicaoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdTipoAquisicao.Value <> 0 then Filtro := 'ID = ' + EditIdTipoAquisicao.Text else Filtro := 'ID=0'; try EditIdTipoAquisicao.Clear; EditTipoAquisicaoNome.Clear; if not PopulaCamposTransientes(Filtro, TPatrimTipoAquisicaoBemVO, TPatrimTipoAquisicaoBemController) then PopulaCamposTransientesLookup(TPatrimTipoAquisicaoBemVO, TPatrimTipoAquisicaoBemController); if CDSTransiente.RecordCount > 0 then begin EditIdTipoAquisicao.Text := CDSTransiente.FieldByName('ID').AsString; EditTipoAquisicaoNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdEstadoConservacao.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFPatrimBem.EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdColaborador.Value <> 0 then Filtro := 'ID = ' + EditIdColaborador.Text else Filtro := 'ID=0'; try EditIdColaborador.Clear; EditColaboradorNome.Clear; if not PopulaCamposTransientes(Filtro, TViewPessoaColaboradorVO, TViewPessoaColaboradorController) then PopulaCamposTransientesLookup(TViewPessoaColaboradorVO, TViewPessoaColaboradorController); if CDSTransiente.RecordCount > 0 then begin EditIdColaborador.Text := CDSTransiente.FieldByName('ID').AsString; EditColaboradorNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdFornecedor.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFPatrimBem.EditIdEstadoConservacaoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdEstadoConservacao.Value <> 0 then Filtro := 'ID = ' + EditIdEstadoConservacao.Text else Filtro := 'ID=0'; try EditIdEstadoConservacao.Clear; EditEstadoConservacaoNome.Clear; if not PopulaCamposTransientes(Filtro, TPatrimEstadoConservacaoVO, TPatrimEstadoConservacaoController) then PopulaCamposTransientesLookup(TPatrimEstadoConservacaoVO, TPatrimEstadoConservacaoController); if CDSTransiente.RecordCount > 0 then begin EditIdEstadoConservacao.Text := CDSTransiente.FieldByName('ID').AsString; EditEstadoConservacaoNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditNumero.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFPatrimBem.EditIdFornecedorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdFornecedor.Value <> 0 then Filtro := 'ID = ' + EditIdFornecedor.Text else Filtro := 'ID=0'; try EditIdFornecedor.Clear; EditFornecedorNome.Clear; if not PopulaCamposTransientes(Filtro, TViewPessoaFornecedorVO, TViewPessoaFornecedorController) then PopulaCamposTransientesLookup(TViewPessoaFornecedorVO, TViewPessoaFornecedorController); if CDSTransiente.RecordCount > 0 then begin EditIdFornecedor.Text := CDSTransiente.FieldByName('ID').AsString; EditFornecedorNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdGrupoBem.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFPatrimBem.EditIdGrupoBemKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdGrupoBem.Value <> 0 then Filtro := 'ID = ' + EditIdGrupoBem.Text else Filtro := 'ID=0'; try EditIdGrupoBem.Clear; EditGrupoBemNome.Clear; if not PopulaCamposTransientes(Filtro, TPatrimGrupoBemVO, TPatrimGrupoBemController) then PopulaCamposTransientesLookup(TPatrimGrupoBemVO, TPatrimGrupoBemController); if CDSTransiente.RecordCount > 0 then begin EditIdGrupoBem.Text := CDSTransiente.FieldByName('ID').AsString; EditGrupoBemNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdTipoAquisicao.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFPatrimBem.EditIdSetorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdSetor.Value <> 0 then Filtro := 'ID = ' + EditIdSetor.Text else Filtro := 'ID=0'; try EditIdSetor.Clear; EditSetorNome.Clear; if not PopulaCamposTransientes(Filtro, TSetorVO, TSetorController) then PopulaCamposTransientesLookup(TSetorVO, TSetorController); if CDSTransiente.RecordCount > 0 then begin EditIdSetor.Text := CDSTransiente.FieldByName('ID').AsString; EditSetorNome.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditIdColaborador.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFPatrimBem.GridParaEdits; var DocumentoBemEnumerator: TEnumerator<TPatrimDocumentoBemVO>; DepreciacaoBemEnumerator: TEnumerator<TPatrimDepreciacaoBemVO>; MovimentacaoBemEnumerator: TEnumerator<TPatrimMovimentacaoBemVO>; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TPatrimBemVO(TController.BuscarObjeto('PatrimBemController.TPatrimBemController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdTipoAquisicao.AsInteger := TPatrimBemVO(ObjetoVO).IdPatrimTipoAquisicaoBem; EditIdEstadoConservacao.AsInteger := TPatrimBemVO(ObjetoVO).IdPatrimEstadoConservacao; EditIdGrupoBem.AsInteger := TPatrimBemVO(ObjetoVO).IdPatrimGrupoBem; EditIdSetor.AsInteger := TPatrimBemVO(ObjetoVO).IdSetor; EditIdFornecedor.AsInteger := TPatrimBemVO(ObjetoVO).IdFornecedor; EditIdColaborador.AsInteger := TPatrimBemVO(ObjetoVO).IdColaborador; EditTipoAquisicaoNome.Text := TPatrimBemVO(ObjetoVO).PatrimTipoAquisicaoBemNome; EditEstadoConservacaoNome.Text := TPatrimBemVO(ObjetoVO).PatrimEstadoConservacaoNome; EditGrupoBemNome.Text := TPatrimBemVO(ObjetoVO).PatrimGrupoBemNome; EditSetorNome.Text := TPatrimBemVO(ObjetoVO).SetorNome; EditFornecedorNome.Text := TPatrimBemVO(ObjetoVO).FornecedorPessoaNome; EditColaboradorNome.Text := TPatrimBemVO(ObjetoVO).ColaboradorPessoaNome; EditNumero.Text := TPatrimBemVO(ObjetoVO).NumeroNb; EditNome.Text := TPatrimBemVO(ObjetoVO).Nome; MemoDescricao.Text := TPatrimBemVO(ObjetoVO).Descricao; EditNumeroSerie.Text := TPatrimBemVO(ObjetoVO).NumeroSerie; EditDataAquisicao.Date := TPatrimBemVO(ObjetoVO).DataAquisicao; EditDataAceite.Date := TPatrimBemVO(ObjetoVO).DataAceite; EditDataCadastro.Date := TPatrimBemVO(ObjetoVO).DataCadastro; EditDataContabilizado.Date := TPatrimBemVO(ObjetoVO).DataContabilizado; EditDataVistoria.Date := TPatrimBemVO(ObjetoVO).DataVistoria; EditDataMarcacao.Date := TPatrimBemVO(ObjetoVO).DataMarcacao; EditDataBaixa.Date := TPatrimBemVO(ObjetoVO).DataBaixa; EditDataVencimentoGarantia.Date := TPatrimBemVO(ObjetoVO).VencimentoGarantia; EditNumeroNF.Text := TPatrimBemVO(ObjetoVO).NumeroNotaFiscal; EditChaveNFe.Text := TPatrimBemVO(ObjetoVO).ChaveNfe; EditValorOriginal.Value := TPatrimBemVO(ObjetoVO).ValorOriginal; EditValorCompra.Value := TPatrimBemVO(ObjetoVO).ValorCompra; EditValorAtualizado.Value := TPatrimBemVO(ObjetoVO).ValorAtualizado; EditValorBaixa.Value := TPatrimBemVO(ObjetoVO).ValorBaixa; case AnsiIndexStr(TPatrimBemVO(ObjetoVO).Deprecia, ['S', 'N']) of 0: ComboDeprecia.ItemIndex := 0; 1: ComboDeprecia.ItemIndex := 1; else ComboDeprecia.ItemIndex := -1; end; case AnsiIndexStr(TPatrimBemVO(ObjetoVO).MetodoDepreciacao, ['1', '2', '3', '4']) of 0: ComboMetodoDepreciacao.ItemIndex := 0; 1: ComboMetodoDepreciacao.ItemIndex := 1; 2: ComboMetodoDepreciacao.ItemIndex := 2; 3: ComboMetodoDepreciacao.ItemIndex := 3; else ComboMetodoDepreciacao.ItemIndex := -1; end; EditInicioDepreciacao.Date := TPatrimBemVO(ObjetoVO).InicioDepreciacao; EditUltimaDepreciacao.Date := TPatrimBemVO(ObjetoVO).UltimaDepreciacao; case AnsiIndexStr(TPatrimBemVO(ObjetoVO).TipoDepreciacao, ['N', 'A', 'I']) of 0: ComboTipoDepreciacao.ItemIndex := 0; 1: ComboTipoDepreciacao.ItemIndex := 1; 2: ComboTipoDepreciacao.ItemIndex := 2; else ComboTipoDepreciacao.ItemIndex := -1; end; EditTaxaAnualDepreciacao.Value := TPatrimBemVO(ObjetoVO).TaxaAnualDepreciacao; EditTaxaMensalDepreciacao.Value := TPatrimBemVO(ObjetoVO).TaxaMensalDepreciacao; EditTaxaDepreciacaoAcelerada.Value := TPatrimBemVO(ObjetoVO).TaxaDepreciacaoAcelerada; EditTaxaDepreciacaoIncentivada.Value := TPatrimBemVO(ObjetoVO).TaxaDepreciacaoIncentivada; MemoFuncao.Text := TPatrimBemVO(ObjetoVO).Funcao; // Preenche as grids internas com os dados das Listas que vieram no objeto TController.TratarRetorno<TPatrimDocumentoBemVO>(TPatrimBemVO(ObjetoVO).ListaPatrimDocumentoBemVO, True, True, CDSPatrimDocumentoBem); TController.TratarRetorno<TPatrimDepreciacaoBemVO>(TPatrimBemVO(ObjetoVO).ListaPatrimDepreciacaoBemVO, True, True, CDSPatrimDepreciacaoBem); TController.TratarRetorno<TPatrimMovimentacaoBemVO>(TPatrimBemVO(ObjetoVO).ListaPatrimMovimentacaoBemVO, True, True, CDSPatrimMovimentacaoBem); // Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor TPatrimBemVO(ObjetoVO).ListaPatrimDocumentoBemVO.Clear; TPatrimBemVO(ObjetoVO).ListaPatrimDepreciacaoBemVO.Clear; TPatrimBemVO(ObjetoVO).ListaPatrimMovimentacaoBemVO.Clear; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; procedure TFPatrimBem.GridDocumentacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_RETURN then GridDocumentacao.SelectedIndex := GridDocumentacao.SelectedIndex + 1; end; procedure TFPatrimBem.GridDepreciacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_RETURN then GridDepreciacao.SelectedIndex := GridDepreciacao.SelectedIndex + 1; end; procedure TFPatrimBem.GridMovimentacaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin try PopulaCamposTransientesLookup(TPatrimTipoMovimentacaoVO, TPatrimTipoMovimentacaoController); if CDSTransiente.RecordCount > 0 then begin CDSPatrimMovimentacaoBem.Append; CDSPatrimMovimentacaoBemID_PATRIM_TIPO_MOVIMENTACAO.AsInteger := CDSTransiente.FieldByName('ID').AsInteger; CDSPatrimMovimentacaoBemPATRIM_TIPO_MOVIMENTACAONOME.AsString := CDSTransiente.FieldByName('NOME').AsString; CDSPatrimMovimentacaoBemDATA_MOVIMENTACAO.AsDateTime := Now; CDSPatrimMovimentacaoBem.Post; end; finally CDSTransiente.Close; end; end; If Key = VK_RETURN then GridMovimentacao.SelectedIndex := GridMovimentacao.SelectedIndex + 1; end; procedure TFPatrimBem.CDSPatrimDepreciacaoBemAfterEdit(DataSet: TDataSet); begin CDSPatrimDepreciacaoBemPERSISTE.AsString := 'S'; end; procedure TFPatrimBem.CDSPatrimDocumentoBemAfterEdit(DataSet: TDataSet); begin CDSPatrimDocumentoBemPERSISTE.AsString := 'S'; end; procedure TFPatrimBem.CDSPatrimMovimentacaoBemAfterEdit(DataSet: TDataSet); begin CDSPatrimMovimentacaoBemPERSISTE.AsString := 'S'; end; {$ENDREGION} {$REGION 'Actions'} procedure TFPatrimBem.ActionAcionarGedExecute(Sender: TObject); var Parametros: String; begin if not CDSPatrimDocumentoBem.IsEmpty then begin { Parametros 1 - Login 2 - Senha 3 - Aplicação que chamou 4 - Nome do arquivo (Aplicacao que chamou + Tela que chamou + Numero Apólice } try CDSPatrimDocumentoBem.Edit; CDSPatrimDocumentoBemIMAGEM.AsString := 'PATRIMONIO_BEM_' + EditNumero.Text + '_' + MD5String(CDSPatrimDocumentoBemNOME.AsString); CDSPatrimDocumentoBem.Post; Parametros := Sessao.Usuario.Login + ' ' + Sessao.Usuario.Senha + ' ' + 'PATRIMONIO' + ' ' + 'PATRIMONIO_BEM_' + EditNumero.Text + '_' + MD5String(CDSPatrimDocumentoBemNOME.AsString); ShellExecute( Handle, 'open', 'T2TiERPGed.exe', PChar(Parametros), '', SW_SHOWNORMAL ); except Application.MessageBox('Erro ao tentar executar o módulo.', 'Erro do Sistema', MB_OK + MB_ICONERROR); end; end else begin Application.MessageBox('É preciso adicionar os dados de um documento ao bem.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); GridDocumentacao.SetFocus; GridDocumentacao.SelectedIndex := 1; end; end; procedure TFPatrimBem.ActionCalcularDepreciacaoExecute(Sender: TObject); begin CDSPatrimDepreciacaoBem.Append; CDSPatrimDepreciacaoBemDATA_DEPRECIACAO.AsDateTime := Date; CDSPatrimDepreciacaoBemDIAS.AsInteger := StrToInt(FormatDateTime('dd', Date)); //Normal if ComboTipoDepreciacao.ItemIndex = 0 then begin CDSPatrimDepreciacaoBemTAXA.AsExtended := EditTaxaMensalDepreciacao.Value; CDSPatrimDepreciacaoBemINDICE.AsExtended := (CDSPatrimDepreciacaoBemDIAS.AsInteger / 30) * EditTaxaMensalDepreciacao.Value; end; //Acelerada if ComboTipoDepreciacao.ItemIndex = 1 then begin CDSPatrimDepreciacaoBemTAXA.AsExtended := EditTaxaDepreciacaoAcelerada.Value; CDSPatrimDepreciacaoBemINDICE.AsExtended := (CDSPatrimDepreciacaoBemDIAS.AsInteger / 30) * EditTaxaDepreciacaoAcelerada.Value; end; //Incentivada if ComboTipoDepreciacao.ItemIndex = 2 then begin CDSPatrimDepreciacaoBemTAXA.AsExtended := EditTaxaDepreciacaoIncentivada.Value; CDSPatrimDepreciacaoBemINDICE.AsExtended := (CDSPatrimDepreciacaoBemDIAS.AsInteger / 30) * EditTaxaDepreciacaoIncentivada.Value; end; CDSPatrimDepreciacaoBemVALOR.AsExtended := EditValorOriginal.Value * CDSPatrimDepreciacaoBemINDICE.AsExtended; CDSPatrimDepreciacaoBemDEPRECIACAO_ACUMULADA.AsExtended := EditValorOriginal.Value - CDSPatrimDepreciacaoBemVALOR.AsExtended; CDSPatrimDepreciacaoBem.Post; end; {$ENDREGION} end.
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, windows; type { TForm1 } TForm1 = class(TForm) btnOpenPort : TButton; btnClosePort : TButton; btnSendRequest : TButton; btnGetDCB: TButton; memLog : TMemo; procedure btnClosePortClick(Sender: TObject); procedure btnGetDCBClick(Sender: TObject); procedure btnOpenPortClick(Sender: TObject); procedure btnSendRequestClick(Sender: TObject); private FPortHandle : THandle; FDCB : TDCB; FPortProperty : TCOMMPROP; FPortTimeouts : TCommTimeouts; FEventMask : DWORD; procedure DcbToLog(ADCB : TDCB); procedure TimeoutsToLog(ATimeouts : TCommTimeouts); end; var Form1: TForm1; implementation {$R *.frm} const dcbFlag_Binary = $00000001; dcbFlag_ParityCheck = $00000002; dcbFlag_OutxCtsFlow = $00000004; dcbFlag_OutxDsrFlow = $00000008; dcbFlag_DtrControlDisable = $00000000; dcbFlag_DtrControlEnable = $00000010; dcbFlag_DtrControlHandshake = $00000020; dcbFlag_DtrControlMask = $00000030; dcbFlag_DsrSensitvity = $00000040; dcbFlag_TXContinueOnXoff = $00000080; dcbFlag_OutX = $00000100; dcbFlag_InX = $00000200; dcbFlag_ErrorChar = $00000400; dcbFlag_NullStrip = $00000800; // dcbFlag_RtsControlMask = $00003000; dcbFlag_RtsControlDisable = $00000000; dcbFlag_RtsControlEnable = $00001000; dcbFlag_RtsControlHandshake = $00002000; dcbFlag_RtsControlToggle = $00003000; dcbFlag_AbortOnError = $00004000; dcbFlag_Reserveds = $FFFF8000; { TForm1 } procedure TForm1.btnOpenPortClick(Sender: TObject); var TempDCB : TDCB; TempTimeouts: TCommTimeouts; begin FPortHandle := CreateFile('\\.\COM11', GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if (FPortHandle = INVALID_HANDLE_VALUE) then begin memLog.Lines.add(Format('Open port COM11 - %s',['Не удалось открыть файл'])); Exit; end; FPortProperty.dwProvSpec1 := COMMPROP_INITIALIZED; FPortProperty.wPacketLength := SizeOf(FPortProperty); if not GetCommProperties(FPortHandle,FPortProperty) then begin memLog.Lines.Add(Format('GetCommProperties - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; if not GetCommState(FPortHandle,FDCB)then begin memLog.Lines.Add(Format('GetCommState - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add('Исходная DCB в устройстве:'); DcbToLog(FDCB); FDCB.DCBlength:=sizeof(TDCB); FDCB.BaudRate := 19200; FDCB.Flags := dcbFlag_Binary or dcbFlag_ParityCheck; FDCB.XonLim := 2048; FDCB.XoffLim := 512; FDCB.ByteSize := 8; // - 8 bit FDCB.Parity := 2; // - even FDCB.StopBits := 0; // - 1 bit FDCB.XonChar := #17; FDCB.XoffChar := #19; FDCB.ErrorChar := #0; FDCB.EofChar := #0; FDCB.EvtChar := #0; memLog.Lines.Add('Устанавливаемая DCB :'); DcbToLog(FDCB); if not SetCommState(FPortHandle,FDCB)then begin memLog.Lines.Add(Format('SetCommState DCB - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; if not GetCommState(FPortHandle,TempDCB)then begin memLog.Lines.Add(Format('GetCommState - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add('Установленная DCB :'); DcbToLog(TempDCB); if not GetCommTimeouts(FPortHandle,FPortTimeouts)then begin memLog.Lines.Add(Format('GetCommTimeouts - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add('Исходные таймауты :'); TimeoutsToLog(FPortTimeouts); FPortTimeouts.ReadIntervalTimeout := 50; FPortTimeouts.ReadTotalTimeoutConstant := 0; FPortTimeouts.ReadTotalTimeoutMultiplier := 0; FPortTimeouts.WriteTotalTimeoutConstant := 0; FPortTimeouts.WriteTotalTimeoutMultiplier:= 0; if not SetCommTimeouts(FPortHandle,FPortTimeouts)then begin memLog.Lines.Add(Format('SetCommTimeouts - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; if not GetCommTimeouts(FPortHandle,TempTimeouts)then begin memLog.Lines.Add(Format('GetCommTimeouts - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add('Установленные таймауты :'); TimeoutsToLog(FPortTimeouts); if not SetupComm(FPortHandle,8048,8048)then begin memLog.Lines.Add(Format('SetupComm - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; if not GetCommMask(FPortHandle, FEventMask)then begin memLog.Lines.Add(Format('SetupComm - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add(Format('Исходная маска = %d',[FEventMask])); FEventMask := FEventMask or EV_RXCHAR or EV_TXEMPTY or EV_BREAK or EV_ERR; if not SetCommMask(FPortHandle,FEventMask)then begin memLog.Lines.Add(Format('SetupComm - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; if not GetCommMask(FPortHandle, FEventMask)then begin memLog.Lines.Add(Format('SetupComm - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; memLog.Lines.Add(Format('Установленная маска = %d',[FEventMask])); btnOpenPort.Enabled := False; btnClosePort.Enabled := True; btnSendRequest.Enabled := True; memLog.Lines.Add('Порт открыт'); memLog.Lines.Add(''); end; procedure TForm1.btnSendRequestClick(Sender: TObject); var TempBuffOut : TByteArray; TempBuffIn : TByteArray; TempOverRes : TOVERLAPPED; TempEventHandle : THANDLE; TempRes : Boolean; TempBytes : DWORD; LastErr : Cardinal; TempMask : Cardinal; TempCOMStat : TCOMSTAT; TempIncBytes : Cardinal; Ticks : Cardinal; begin // Запрос: 01 03 00 00 00 7D 85 EB - чтение по 3-й функции 125-и Holding регистров FillChar(TempBuffOut,sizeof(TByteArray),0); FillChar(TempBuffIn,sizeof(TByteArray),0); Ticks := GetTickCount; TempBuffOut[0] := $01; TempBuffOut[1] := $03; TempBuffOut[2] := $00; TempBuffOut[3] := $00; TempBuffOut[4] := $00; TempBuffOut[5] := $7D; TempBuffOut[6] := $85; TempBuffOut[7] := $EB; // Запись запроса в порт FillChar(TempOverRes,sizeof(TOVERLAPPED),0); TempEventHandle := CreateEvent(nil,True,False,nil); TempOverRes.hEvent := TempEventHandle; try TempRes := WriteFile(FPortHandle,TempBuffOut,8,TempBytes,@TempOverRes); if not TempRes then begin LastErr := GetLastError; if LastErr <> ERROR_IO_PENDING then begin memLog.Lines.Add(Format('Write error - %d - %s',[LastErr,SysErrorMessage(LastErr)])); Exit; end; LastErr := WaitForSingleObject(TempEventHandle,1000); case LastErr of WAIT_OBJECT_0 : begin if not GetOverlappedResult(TempEventHandle,TempOverRes,TempBytes,True) then begin LastErr := GetLastError; memLog.Lines.Add(Format('Write. Waite error - %d - %s',[LastErr,SysErrorMessage(LastErr)])); Exit; end; memLog.Lines.Add(Format('Write ok. Writed %d bytes',[TempBytes])); end; WAIT_TIMEOUT : begin memLog.Lines.Add('Write. Waite timeout'); Exit; end; WAIT_FAILED : begin LastErr := GetLastError; memLog.Lines.Add(Format('Write. Waite error - %d - %s',[LastErr,SysErrorMessage(LastErr)])); Exit; end; else memLog.Lines.Add(Format('Write. Waite other - %d',[LastErr])); Exit; end; end; finally CloseHandle(TempEventHandle); TempEventHandle := 0; end; // окончание записи запроса // ожидание ответа if not GetCommMask(FPortHandle,TempMask)then begin memLog.Lines.Add(Format('GetCommMask - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; TempMask := TempMask or EV_RXCHAR; if not SetCommMask(FPortHandle,TempMask)then begin memLog.Lines.Add(Format('SetCommMask - %s',[SysErrorMessage(GetLastError)])); btnClosePortClick(Self); Exit; end; FillChar(TempOverRes,sizeof(TOVERLAPPED),0); TempEventHandle := CreateEvent(nil,True,False,nil); TempOverRes.hEvent := TempEventHandle; try TempMask := 0; TempRes := WaitCommEvent(FPortHandle,TempMask,@TempOverRes); if not TempRes then begin LastErr := GetLastError; if LastErr <> ERROR_IO_PENDING then begin memLog.Lines.Add(Format('WaitCommEvent - %s',[SysErrorMessage(LastErr)])); btnClosePortClick(Self); Exit; end; while WaitForSingleObject(TempEventHandle,1000) = WAIT_TIMEOUT do Sleep(10); if (TempMask and EV_RXCHAR) = EV_RXCHAR then begin memLog.Lines.Add('WaitCommEvent, Пришли данные '); end else begin memLog.Lines.Add('WaitCommEvent, Не дождались данных '); Exit; end; end; finally CloseHandle(TempEventHandle); TempEventHandle := 0; end; // окончание ожидания ответа // ожидание прихода все данных LastErr := 0 ; TempIncBytes := 1; FillChar(TempCOMStat,sizeof(TCOMSTAT),0); while (TempIncBytes<>TempCOMStat.cbInQue)do begin Sleep(5); TempIncBytes := TempCOMStat.cbInQue; TempRes := ClearCommError(FPortHandle,LastErr,@TempCOMStat); if not TempRes then Break; end; memLog.Lines.Add(''); // количество пришедших // чтение ответа FillChar(TempOverRes,sizeof(TOVERLAPPED),0); TempEventHandle := CreateEvent(nil,True,False,nil); TempOverRes.hEvent := TempEventHandle; try TempRes := ReadFile(FPortHandle,TempBuffOut,2048,TempIncBytes,@TempOverRes); if not TempRes then begin LastErr := GetLastError; if LastErr <> ERROR_IO_PENDING then begin memLog.Lines.Add(Format('Read. ReadFile error - %d - %s',[LastErr,SysErrorMessage(LastErr)])); Exit; end; while WaitForSingleObject(TempOverRes.hEvent,1000)=WAIT_TIMEOUT do Sleep(5); if not GetOverlappedResult(TempEventHandle,TempOverRes,TempIncBytes,True) then begin LastErr := GetLastError; memLog.Lines.Add(Format('Read. GetOverlappedResult error - %d - %s',[LastErr,SysErrorMessage(LastErr)])); Exit; end; memLog.Lines.Add(Format('Read. Пришло %d байт',[TempIncBytes])); end; finally CloseHandle(TempEventHandle); end; PurgeComm(FPortHandle,PURGE_RXCLEAR); memLog.Lines.Add(Format('Read. Прошло %d мс',[GetTickCount - Ticks])); memLog.Lines.Add(''); // окончание чтения ответа end; procedure TForm1.btnClosePortClick(Sender: TObject); begin CloseHandle(FPortHandle); FPortHandle := INVALID_HANDLE_VALUE; memLog.Lines.Add('Порт закрыт'); btnOpenPort.Enabled := True; btnClosePort.Enabled := False; btnSendRequest.Enabled := False; end; procedure TForm1.btnGetDCBClick(Sender: TObject); var TempHandl : THANDLE; TempDCB : TDCB; begin TempHandl := CreateFile('\\.\COM11', GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if (TempHandl = INVALID_HANDLE_VALUE) then begin memLog.Lines.add(Format('Get DCB: Open port COM11 - %s',[SysErrorMessage(GetLastError)])); Exit; end; if not GetCommState(TempHandl,TempDCB)then begin memLog.Lines.Add(Format('Get DCB: GetCommState - %s',[SysErrorMessage(GetLastError)])); CloseHandle(TempHandl); Exit; end; memLog.Lines.Add('Get DCB: DCB в устройстве:'); DcbToLog(TempDCB); CloseHandle(TempHandl); end; procedure TForm1.DcbToLog(ADCB: TDCB); begin memLog.Lines.Add(Format('FDCB.DCBlength = %d',[ADCB.DCBlength])); memLog.Lines.Add(Format('FDCB.BaudRate = %d',[ADCB.BaudRate])); memLog.Lines.Add(Format('FDCB.Flags = %d',[ADCB.Flags])); memLog.Lines.Add(Format('FDCB.XonLim = %d',[FDCB.XonLim])); memLog.Lines.Add(Format('FDCB.XoffLim = %d',[FDCB.XoffLim])); memLog.Lines.Add(Format('FDCB.ByteSize = %d',[FDCB.ByteSize])); memLog.Lines.Add(Format('FDCB.Parity = %d',[FDCB.Parity])); memLog.Lines.Add(Format('FDCB.StopBits = %d',[FDCB.StopBits])); memLog.Lines.Add(Format('FDCB.XonChar = %d',[ord(FDCB.XonChar)])); memLog.Lines.Add(Format('FDCB.XoffChar = %d',[ord(FDCB.XoffChar)])); memLog.Lines.Add(Format('FDCB.ErrorChar = %d',[ord(FDCB.ErrorChar)])); memLog.Lines.Add(Format('FDCB.EofChar = %d',[ord(FDCB.EofChar)])); memLog.Lines.Add(Format('FDCB.EvtChar = %d',[ord(FDCB.EvtChar)])); memLog.Lines.Add(''); end; procedure TForm1.TimeoutsToLog(ATimeouts: TCommTimeouts); begin memLog.Lines.Add(Format('ATimeouts.ReadIntervalTimeout = %d',[ATimeouts.ReadIntervalTimeout])); memLog.Lines.Add(Format('ATimeouts.ReadTotalTimeoutMultiplier = %d',[ATimeouts.ReadTotalTimeoutMultiplier])); memLog.Lines.Add(Format('ATimeouts.ReadTotalTimeoutConstant = %d',[ATimeouts.ReadTotalTimeoutConstant])); memLog.Lines.Add(Format('ATimeouts.WriteTotalTimeoutConstant = %d',[ATimeouts.WriteTotalTimeoutConstant])); memLog.Lines.Add(Format('ATimeouts.WriteTotalTimeoutMultiplier = %d',[ATimeouts.WriteTotalTimeoutMultiplier])); memLog.Lines.Add(''); end; end.
unit angFileList; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, SynMemo, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, ComCtrls, StdCtrls, Menus, angDatamodul, angFrmMainController, angpkz, Math, strutils, SynHighlighterAny, SynHighlighterCss, SynHighlighterHtml ,Clipbrd, SynEdit ,SynEditTypes; type { TFileListFileInfo } TFileListFileInfo = class public iImageindex: integer; sFilename: string; sPath: string; iLines: integer; Visible: boolean; ng: string; DI: string; Types : string; Model : string; oneFileInfo: TOneFileInfo; constructor Create; end; { TfrmFileList } TfrmFileList = class(TForm) BitBtn1: TBitBtn; BitBtn2: TBitBtn; eFilter: TEdit; eFilterAng: TEdit; eFilterTypes: TEdit; eFilterPath: TEdit; eFilterNg: TEdit; eFilterModel: TEdit; lblDI: TLabel; lblTypes: TLabel; lblPath: TLabel; lblCount: TLabel; lblNg: TLabel; lblFiles: TLabel; lblTypes1: TLabel; ListView1: TListView; mnuCopyClipboard: TMenuItem; Panel1: TPanel; Panel2: TPanel; pmAngFileList: TPopupMenu; Splitter1: TSplitter; SynMemo1: TSynMemo; procedure BitBtn1Click(Sender: TObject); procedure eFilterKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure eFilterKeyPress(Sender: TObject; var Key: char); procedure eFilterKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure ListView1Click(Sender: TObject); procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn); procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: integer; var Compare: integer); procedure ListView1DblClick(Sender: TObject); procedure ListView1EndDrag(Sender, Target: TObject; X, Y: Integer); procedure ListView1Enter(Sender: TObject); procedure ListView1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ListView1Resize(Sender: TObject); procedure ListView1SelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure mnuCopyClipboardClick(Sender: TObject); procedure SynMemo1StatusChange(Sender: TObject; Changes: TSynStatusChanges); private { private declarations } slFilesToView: TStringList; ColumnToSort: integer; frmMainController1: TFrmMainController; procedure doFilterKeyUp; procedure DoSetSFilename; procedure ShowFiltered; public { public declarations } sFilename: string; SynAnySyn1: TSynAnySyn; SynCssSyn1: TSynCssSyn; SynHTMLSyn1: TSynHTMLSyn; procedure Initialize(frmMainController: TFrmMainController); end; var frmFileList: TfrmFileList; implementation { TFileListFileInfo } constructor TFileListFileInfo.Create; begin iImageindex := 0; sFilename := ''; sPath := ''; Visible := True; end; {$R *.lfm} { TfrmFileList } procedure TfrmFileList.Initialize(frmMainController: TFrmMainController); var i, i2: integer; FileListFileInfo: TFileListFileInfo; s: string; oneFileInfo: TOneFileInfo; begin frmMainController1 := frmMainController; for i := 0 to frmMainController.slAllFilesFound.Count - 1 do begin s := frmMainController.slAllFilesFound[i]; i2 := frmMainController.GetImageindexForFileIfItContainsOnlyTheSameType(s); if i2 = -1 then i2 := frmMainController.CalculateIndexOfFileExtension(s); if i2 <> constItemIndexUnknownFile then begin oneFileInfo := TOneFileInfo(frmMainController.slAllFilesFound.Objects[i]); FileListFileInfo := TFileListFileInfo.Create; FileListFileInfo.iImageindex := i2; FileListFileInfo.sFilename := extractfilename(s); FileListFileInfo.iLines := oneFileInfo.slFileInhalt.Count; FileListFileInfo.ng := Ansireplacestr(oneFileInfo.slngWords.Text, #13#10, ' | '); FileListFileInfo.DI := Ansireplacestr(oneFileInfo.slDependencyInjektionNamen.Text, #13#10, ' | '); FileListFileInfo.sPath := frmMainController.GetFilenameWithoutRootPath(s); FileListFileInfo.oneFileInfo := oneFileInfo; FileListFileInfo.Types := frmMainController.GetAngularTypesForFile(FileListFileInfo.sPath); FileListFileInfo.Model := Ansireplacestr(oneFileInfo.slNgModels.Text, #13#10, ' | '); ; slFilesToView.AddObject(s, FileListFileInfo); end; end; ShowFiltered; end; procedure TfrmFileList.ShowFiltered; var i: integer; myItem: TListitem; FileListFileInfo: TFileListFileInfo; begin ListView1.BeginUpdate; ListView1.Clear; for i := 0 to slFilesToView.Count - 1 do begin FileListFileInfo := TFileListFileInfo(slFilesToView.Objects[i]); if FileListFileInfo.Visible then begin myItem := ListView1.Items.Add; myItem.Caption := extractfilename(FileListFileInfo.sFilename); myitem.SubItems.add(FileListFileInfo.sPath); myitem.SubItems.add(IntToStr(FileListFileInfo.iLines)); myitem.SubItems.add(ExtractFileExt(FileListFileInfo.sFilename)); myitem.SubItems.add(FileListFileInfo.ng); myitem.SubItems.add(FileListFileInfo.DI); myitem.SubItems.add(FileListFileInfo.Types); myitem.Data := FileListFileInfo.oneFileInfo; myitem.SubItems.add(datetimetostr( FileListFileInfo.oneFileInfo.modifiedDateTime) ); myitem.SubItems.add(FileListFileInfo.Model); myitem.ImageIndex := FileListFileInfo.iImageindex; end; end; ListView1.EndUpdate; BitBtn1.Enabled := ListView1.items.Count > 0; lblCount.Caption := IntToStr(ListView1.items.Count); end; procedure TfrmFileList.BitBtn1Click(Sender: TObject); begin DoSetSFilename; end; procedure TfrmFileList.eFilterKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin if key = 40 then Listview1.SetFocus; end; procedure TfrmFileList.DoSetSFilename; var i: integer; myItem: TListitem; begin i := ListView1.ItemIndex; if i = -1 then begin i := 0; if Listview1.Items.Count = 0 then exit; end; myItem := ListView1.Items[i]; sFilename := myItem.subitems[0]; modalresult := mrOk; end; procedure TfrmFileList.eFilterKeyPress(Sender: TObject; var Key: char); begin end; procedure TfrmFileList.eFilterKeyUp(Sender: TObject; var Key: word; Shift: TShiftState); begin doFilterKeyUp ; end; procedure TfrmFileList.doFilterKeyUp; var i: integer; FileListFileInfo: TFileListFileInfo; begin for i := 0 to slFilesToView.Count - 1 do begin FileListFileInfo := TFileListFileInfo(slFilesToView.Objects[i]); FileListFileInfo.Visible := True; if eFilter.Text <> '' then if pos(uppercase(eFilter.Text), uppercase(FileListFileInfo.sFilename)) = 0 then FileListFileInfo.Visible := False; if eFilterPath.Text <> '' then if pos(uppercase(eFilterPath.Text), uppercase(FileListFileInfo.sPath )) = 0 then FileListFileInfo.Visible := False; if eFilterNg.Text <> '' then if pos(uppercase(eFilterNg.Text), uppercase(FileListFileInfo.ng )) = 0 then FileListFileInfo.Visible := False; if eFilterAng.Text <> '' then if pos(uppercase(eFilterAng.Text), uppercase(FileListFileInfo.DI )) = 0 then FileListFileInfo.Visible := False; if eFilterTypes.Text <> '' then if pos(uppercase(eFilterTypes.Text), uppercase(FileListFileInfo.Types )) = 0 then FileListFileInfo.Visible := False; if eFilterModel.Text <> '' then if pos(uppercase(eFilterModel.Text), uppercase(FileListFileInfo.Model )) = 0 then FileListFileInfo.Visible := False; end; ShowFiltered; end; procedure TfrmFileList.FormCreate(Sender: TObject); begin slFilesToView := TStringList.Create; slFilesToView.OwnsObjects := True; end; procedure TfrmFileList.FormDestroy(Sender: TObject); begin slFilesToView.Free; end; procedure TfrmFileList.FormShow(Sender: TObject); begin eFilter.setfocus; end; procedure TfrmFileList.ListView1Click(Sender: TObject); begin end; procedure TfrmFileList.ListView1ColumnClick(Sender: TObject; Column: TListColumn); begin ColumnToSort := Column.Index; Listview1.AlphaSort; end; procedure TfrmFileList.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: integer; var Compare: integer); var i: integer; begin if ColumnToSort = 0 then Compare := CompareText(Item1.Caption, Item2.Caption) else begin i := ColumnToSort - 1; if i = 1 then //lines begin Compare := CompareValue(strtointdef(Item1.SubItems[i], 0), strtointdef(Item2.SubItems[i], 0)); end else if i = 6 then //Datetime begin Compare := CompareValue (strtodatetimedef (Item2.SubItems[i], 0), strtodatetimedef(Item1.SubItems[i], 0)); end else Compare := CompareText(Item1.SubItems[i], Item2.SubItems[i]); end; end; procedure TfrmFileList.ListView1DblClick(Sender: TObject); begin DoSetSFilename; end; procedure TfrmFileList.ListView1EndDrag(Sender, Target: TObject; X, Y: Integer); begin eFilter.Width:=listview1.Columns[0].Width ; end; procedure TfrmFileList.ListView1Enter(Sender: TObject); begin if Listview1.Items.Count > 0 then if Listview1.ItemIndex = -1 then Listview1.ItemIndex := 0; end; procedure TfrmFileList.ListView1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin end; procedure TfrmFileList.ListView1Resize(Sender: TObject); begin end; procedure TfrmFileList.ListView1SelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var {i : integer; item : TListitem; } oneFileInfo : ToneFileInfo; begin {i := Listview1.ItemIndex ; if i = -1 then exit; item := Listview1.items[i]; } oneFileInfo := ToneFileInfo(item.Data); SynMemo1.Lines.text := oneFileinfo.slFileInhalt.Text ; if oneFileinfo.iImageindex = constItemIndexCss then SynMemo1.Highlighter := SynCssSyn1 else if oneFileinfo.iImageindex = constItemIndexHTML then SynMemo1.Highlighter := SynHtmlSyn1 else SynMemo1.Highlighter := SynAnySyn1; end; procedure TfrmFileList.mnuCopyClipboardClick(Sender: TObject); var i : integer; s: string; item : TListitem ; begin s := ''; for i := 0 to ListView1.Items.Count - 1 do begin item := ListView1.Items[i]; s := s + item.Caption + #9 + ansireplacestr(item.SubItems.Text,#13#10,#9) + #13#10 ; end; Clipboard.AsText :=s; end; procedure TfrmFileList.SynMemo1StatusChange(Sender: TObject; Changes: TSynStatusChanges); begin end; end.
(* Copyright 2016 Michael Justin 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 LazLoggerLogger; interface uses LazLogger, djLogAPI, SysUtils; type TLazLogLevel = (Trace, Debug, Info, Warn, Error); { TLazLoggerLogger } TLazLoggerLogger = class(TInterfacedObject, ILogger) private FLevel: TLazLogLevel; FName: string; LogGroup: PLazLoggerLogGroup; function LevelAsString(const ALogLevel: TLazLogLevel): string; function IsEnabledFor(ALogLevel: TLazLogLevel): Boolean; procedure SetLevel(AValue: TLazLogLevel); procedure WriteMsg(const ALogLevel: TLazLogLevel; const AMsg: string); overload; procedure WriteMsg(const ALogLevel: TLazLogLevel; const AMsg: string; const AException: Exception); overload; public constructor Create(const AName: string); procedure Debug(const AMsg: string); overload; procedure Debug(const AFormat: string; const AArgs: array of const); overload; procedure Debug(const AMsg: string; const AException: Exception); overload; procedure Error(const AMsg: string); overload; procedure Error(const AFormat: string; const AArgs: array of const); overload; procedure Error(const AMsg: string; const AException: Exception); overload; procedure Info(const AMsg: string); overload; procedure Info(const AFormat: string; const AArgs: array of const); overload; procedure Info(const AMsg: string; const AException: Exception); overload; procedure Warn(const AMsg: string); overload; procedure Warn(const AFormat: string; const AArgs: array of const); overload; procedure Warn(const AMsg: string; const AException: Exception); overload; procedure Trace(const AMsg: string); overload; procedure Trace(const AFormat: string; const AArgs: array of const); overload; procedure Trace(const AMsg: string; const AException: Exception); overload; function Name: string; function IsDebugEnabled: Boolean; function IsErrorEnabled: Boolean; function IsInfoEnabled: Boolean; function IsWarnEnabled: Boolean; function IsTraceEnabled: Boolean; property Level: TLazLogLevel read FLevel write SetLevel; end; TLazLoggerFactory = class(TInterfacedObject, ILoggerFactory) public function GetLogger(const AName: string): ILogger; end; var DefaultLevel: TLazLogLevel; implementation const MilliSecsPerDay = 24 * 60 * 60 * 1000; SBlanks = ' '; var { Start time for the logging process - to compute elapsed time. } StartTime: TDateTime; { The elapsed time since package start up (in milliseconds). } function GetElapsedTime: LongInt; begin Result := Round((Now - StartTime) * MilliSecsPerDay); end; { TLazLoggerLogger } constructor TLazLoggerLogger.Create(const AName: string); begin FName := AName; LogGroup := DebugLogger.RegisterLogGroup(AName, True); // always on // DebugLogger.ParamForEnabledLogGroups := '--debug-enabled='; end; function TLazLoggerLogger.LevelAsString(const ALogLevel: TLazLogLevel): string; begin case ALogLevel of LazLoggerLogger.Trace: LevelAsString := 'TRACE'; LazLoggerLogger.Debug: LevelAsString := 'DEBUG'; LazLoggerLogger.Info: LevelAsString := 'INFO'; LazLoggerLogger.Warn: LevelAsString := 'WARN'; LazLoggerLogger.Error: LevelAsString := 'ERROR'; end; end; function TLazLoggerLogger.IsEnabledFor(ALogLevel: TLazLogLevel): Boolean; begin Result := Ord(FLevel) <= Ord(ALogLevel); end; procedure TLazLoggerLogger.WriteMsg(const ALogLevel: TLazLogLevel; const AMsg: string); begin LazLogger.DebugLn( LogGroup, IntToStr(GetElapsedTime) + ' ' + LevelAsString(ALogLevel) + ' ' + Name + ' - ' + AMsg); end; procedure TLazLoggerLogger.WriteMsg(const ALogLevel: TLazLogLevel; const AMsg: string; const AException: Exception); begin WriteMsg(ALogLevel, AMsg + SLineBreak + SBlanks + AException.ClassName + SLineBreak + SBlanks + AException.Message); end; procedure TLazLoggerLogger.SetLevel(AValue: TLazLogLevel); begin if FLevel = AValue then Exit; FLevel := AValue; end; procedure TLazLoggerLogger.Debug(const AMsg: string); begin if IsDebugEnabled then WriteMsg(LazLoggerLogger.Debug, AMsg); end; procedure TLazLoggerLogger.Debug(const AFormat: string; const AArgs: array of const); begin if IsDebugEnabled then WriteMsg(LazLoggerLogger.Debug, Format(AFormat, AArgs)); end; procedure TLazLoggerLogger.Debug(const AMsg: string; const AException: Exception); begin if IsDebugEnabled then WriteMsg(LazLoggerLogger.Debug, AMsg, AException); end; procedure TLazLoggerLogger.Error(const AMsg: string; const AException: Exception); begin if IsErrorEnabled then WriteMsg(LazLoggerLogger.Error, AMsg, AException); end; procedure TLazLoggerLogger.Error(const AFormat: string; const AArgs: array of const); begin if IsErrorEnabled then WriteMsg(LazLoggerLogger.Error, Format(AFormat, AArgs)); end; procedure TLazLoggerLogger.Error(const AMsg: string); begin if IsErrorEnabled then WriteMsg(LazLoggerLogger.Error, AMsg); end; function TLazLoggerLogger.IsDebugEnabled: Boolean; begin Result := IsEnabledFor(LazLoggerLogger.Debug); end; function TLazLoggerLogger.IsErrorEnabled: Boolean; begin Result := IsEnabledFor(LazLoggerLogger.Error); end; function TLazLoggerLogger.IsInfoEnabled: Boolean; begin Result := IsEnabledFor(LazLoggerLogger.Info); end; function TLazLoggerLogger.IsTraceEnabled: Boolean; begin Result := IsEnabledFor(LazLoggerLogger.Trace); end; function TLazLoggerLogger.IsWarnEnabled: Boolean; begin Result := IsEnabledFor(LazLoggerLogger.Warn); end; procedure TLazLoggerLogger.Info(const AFormat: string; const AArgs: array of const); begin if IsInfoEnabled then WriteMsg(LazLoggerLogger.Info, Format(AFormat, AArgs)); end; procedure TLazLoggerLogger.Info(const AMsg: string); begin if IsInfoEnabled then WriteMsg(LazLoggerLogger.Info, AMsg); end; procedure TLazLoggerLogger.Info(const AMsg: string; const AException: Exception); begin if IsInfoEnabled then WriteMsg(LazLoggerLogger.Info, AMsg, AException); end; procedure TLazLoggerLogger.Trace(const AMsg: string; const AException: Exception); begin if IsTraceEnabled then WriteMsg(LazLoggerLogger.Trace, AMsg, AException); end; function TLazLoggerLogger.Name: string; begin Result := FName; end; procedure TLazLoggerLogger.Trace(const AFormat: string; const AArgs: array of const); begin if IsTraceEnabled then WriteMsg(LazLoggerLogger.Trace, Format(AFormat, AArgs)); end; procedure TLazLoggerLogger.Trace(const AMsg: string); begin if IsTraceEnabled then WriteMsg(LazLoggerLogger.Trace, AMsg); end; procedure TLazLoggerLogger.Warn(const AMsg: string; const AException: Exception); begin if IsWarnEnabled then WriteMsg(LazLoggerLogger.Warn, AMsg, AException); end; procedure TLazLoggerLogger.Warn(const AFormat: string; const AArgs: array of const); begin if IsWarnEnabled then WriteMsg(LazLoggerLogger.Warn, Format(AFormat, AArgs)); end; procedure TLazLoggerLogger.Warn(const AMsg: string); begin if IsWarnEnabled then WriteMsg(LazLoggerLogger.Warn, AMsg); end; { TLazLoggerFactory } function TLazLoggerFactory.GetLogger(const AName: string): ILogger; var Logger: TLazLoggerLogger; begin Logger := TLazLoggerLogger.Create(AName); Logger.Level := DefaultLevel; Result := Logger; end; initialization StartTime := Now; DefaultLevel:= Info; end.
unit TennivalokMenu; interface uses Windows, ActiveX, ComObj, ShlObj, ShellApi, ComServ, Messages, SysUtils, Registry; type TTennivalokMenu = class(TComObject, IUnknown, IContextMenu, IShellExtInit) private fFileName: string; protected function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HRESULT;stdcall; function InvokeCommand(var lpici: TCMInvokeCommandInfo): HRESULT;stdcall; function GetCommandString(idCmd, uType: UINT;pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult;stdcall; function IShellExtInit.Initialize = InitShellExt; function InitShellExt(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult;stdcall; end; TTennivalokMenuFactory = class (TComObjectFactory) public procedure UpdateRegistry (Register: Boolean); override; end; const Class_TennivalokMenuMenu: TGUID = '{6013C006-251B-474E-BDC9-918799B8C1BA}'; implementation { TToDoMenu } function TTennivalokMenu.GetCommandString(idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; begin if idCmd = 0 then begin strCopy(pszName,'A file Tennivalók adatbázishoz való hozzáadása'); Result := NOERROR; end else Result := E_INVALIDARG; end; function TTennivalokMenu.InitShellExt(pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; var medium : TStgMedium; fe: TFormatEtc; begin Result := E_FAIL; if Assigned(lpdobj) then begin with fe do begin cfFormat := CF_HDROP; ptd := nil; dwAspect := DVASPECT_CONTENT; tymed := TYMED_HGLOBAL; end; Result := lpdobj.GetData(fe,medium); if not Failed(Result) then begin if DragQueryFile(medium.hGlobal,$FFFFFFFF,nil,0) = 1 then begin SetLength(fFileName,1000); DragQueryFile(medium.hGlobal,0,PChar(fFileName),1000); fFileName := PChar(fFileName); Result := NOERROR; end else Result := E_FAIL; end; ReleaseStgMedium(medium); end; end; function TTennivalokMenu.InvokeCommand(var lpici: TCMInvokeCommandInfo): HRESULT; var hwnd: THandle; cds: CopyDataStruct; begin Result := NOERROR; if HiWord(Integer(lpici.lpVerb)) <> 0 then begin Result := E_FAIL; Exit; end; if LoWord(lpici.lpVerb) > 0 then begin Result := E_INVALIDARG; Exit; end; if LoWord(lpici.lpVerb) = 0 then begin hwnd := FindWindow('TTennivalokForm',nil); if hwnd <> 0 then begin cds.dwData := 0; cds.cbData := Length(fFileName); cds.lpData := PChar(fFileName); SetForegroundWindow(hwnd); SendMessage(hwnd,wm_CopyData,lpici.hWnd,Integer(@cds)); end; end; end; function TTennivalokMenu.QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HRESULT; begin if FindWindow('TTennivalokMenu',nil) <>0 then begin InsertMenu(Menu,indexMenu,MF_STRING + MF_BYPOSITION,idCmdFirst,'Tennivalók filehoz adás'); Result := 1; end else Result := 0; end; { TTennivalokMenuFactory } procedure TTennivalokMenuFactory.UpdateRegistry(Register: Boolean); var Reg: TRegistry; begin inherited UpdateRegistry(Register); Reg := TRegistry.Create; try if Register then Reg.CreateKey('\HKEY_CLASSES_ROOT\*\ShellEx\ContextMenuHandler\' + GUIDToString(Class_TennivalokMenuMenu)) else Reg.DeleteKey('HKEY_CLASSES_ROOT\*\ShellEx\ContextMenuHandler\' + GUIDToString(Class_TennivalokMenuMenu)); finally Reg.Free; end; end; initialization TTennivalokMenuFactory.Create( ComServer, TTennivalokMenu, Class_TennivalokMenuMenu, 'TennivalokMenu','Tennivalók menü shell kiterjesztése', ciMultiInstance,tmApartment); end.
unit acCoolBar; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ToolWin, ComCtrls, sCommonData, Commctrl; type TsCoolBar = class(TCoolBar) {$IFNDEF NOTFORHELP} private FGripIndex : integer; FGripMask : integer; FGripsection : string; FGripTexture : integer; FCommonData: TsCommonData; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMNCPaint (var Message: TWMNCPaint); message WM_NCPAINT; procedure ACPaint(DC : HDC = 0; SendUpdated : boolean = True); virtual; procedure PrepareCache; function GetCaptionSize(Band: TCoolBand): Integer; function GetCaptionFontHeight: Integer; function GetGripSize(Band: TCoolBand) : integer; procedure UpdateGripIndex; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure AfterConstruction; override; procedure Loaded; override; procedure WndProc (var Message: TMessage); override; published {$ENDIF} // NOTFORHELP property SkinData : TsCommonData read FCommonData write FCommonData; end; implementation uses acntUtils, sGraphUtils, sAlphaGraph, sVCLUtils, sMessages, ImgList, math, sConst, sStyleSimply, sSkinProps; { TsCoolBar } procedure TsCoolBar.ACPaint; var b : boolean; NewDC : HDC; RW, RC : TRect; i : integer; SavedDC : hdc; R, CaptRect : TRect; CaptSize : integer; procedure PaintGrips; var i : integer; Band: TCoolBand; CI : TCacheInfo; DesignText : boolean; TempBmp : TBitmap; rText : TRect; GripSize : integer; begin CI := MakeCacheInfo(FCommonData.FCacheBmp, ACClientRect(Handle).Left, ACClientRect(Handle).Top); for i := 0 to Bands.Count - 1 do if Assigned(Bands[i].Control) and ((csDesigning in ComponentState) or Bands[i].Visible) then begin Band := Bands[I]; CaptSize := GetCaptionSize(Band); GripSize := GetGripSize(Band); if Vertical then begin CaptRect.TopLeft := Point(min(Band.Control.Left - (Band.Height - Band.Control.Width) div 2, Band.Control.Left), Band.Control.Top - CaptSize); CaptRect.BottomRight := Point(CaptRect.Left + Band.Height, CaptRect.Top + CaptSize); TempBmp := CreateBmp32(Band.Height, CaptSize); BitBlt(TempBmp.Canvas.Handle, 0, 0, TempBmp.Width, TempBmp.Height, FCommonData.FCacheBmp.Canvas.Handle, CaptRect.Left + CI.X, CaptRect.Top + CI.Y, SRCCOPY); if FGripIndex <> -1 then begin PaintItem(FGripIndex, FGripsection, Ci, True, 0, Rect(0, 0, Band.Height, GripSize - 2), Point(CaptRect.Left, CaptRect.Top), TempBmp, SkinData.SkinManager, FGripTexture); end; rText := CaptRect; OffsetRect(rText, -rText.Left, -rText.Top); inc(rText.Top, GripSize); if Assigned(Images) and (Band.ImageIndex > -1) then begin Images.DrawingStyle := dsTransparent; Images.Draw(TempBmp.Canvas, (WidthOf(CaptRect) - Images.Width) div 2, GripSize, Band.ImageIndex); inc(rText.Top, Images.Height + 2); end; DesignText := (csDesigning in ComponentState) and (Band.Control = nil) and (Band.Text = ''); if ShowText or DesignText then begin if DesignText then Text := Band.DisplayName else Text := Band.Text; if Text <> '' then begin TempBMP.Canvas.Font.Assign(Font); acWriteTextEx(TempBMP.Canvas, PacChar(Text), True, rText, DT_EXPANDTABS or DT_SINGLELINE or DT_VCENTER, FCommonData, False); end; end; end else begin CaptRect.TopLeft := Point(Band.Control.Left - CaptSize, min(Band.Control.Top - (Band.Height - Band.Control.Height) div 2, Band.Control.Top)); CaptRect.BottomRight := Point(CaptRect.Left + CaptSize, CaptRect.Top + Band.Height); TempBmp := CreateBmp32(CaptSize, Band.Height); BitBlt(TempBmp.Canvas.Handle, 0, 0, TempBmp.Width, TempBmp.Height, FCommonData.FCacheBmp.Canvas.Handle, CaptRect.Left + CI.X, CaptRect.Top + CI.Y, SRCCOPY); if FGripIndex <> -1 then begin PaintItem(FGripIndex, FGripsection, Ci, True, 0, Rect(0, 0, GripSize - 2, Band.Height), Point(CaptRect.Left, CaptRect.Top), TempBmp, SkinData.SkinManager, FGripTexture); end; rText := CaptRect; OffsetRect(rText, -rText.Left, -rText.Top); inc(rText.Left, GripSize); if Assigned(Images) and (Band.ImageIndex > -1) then begin Images.DrawingStyle := dsTransparent; Images.Draw(TempBmp.Canvas, GripSize, (Band.Height - Images.Height) div 2, Band.ImageIndex); inc(rText.Left, Images.Width + 2); end; DesignText := (csDesigning in ComponentState) and (Band.Control = nil) and (Band.Text = ''); if ShowText or DesignText then begin if DesignText then Text := Band.DisplayName else Text := Band.Text; if Text <> '' then begin TempBMP.Canvas.Font.Assign(Font); acWriteTextEx(TempBMP.Canvas, PacChar(Text), True, rText, DT_EXPANDTABS or DT_SINGLELINE or DT_VCENTER, FCommonData, False); end; end; end; R := Rect(1, 1, 1, 1); GetClipBox(NewDC, R); BitBlt(NewDC, CaptRect.Left, CaptRect.Top, TempBmp.Width, TempBmp.Height, TempBmp.Canvas.Handle, 0, 0, SRCCOPY); FreeAndNil(TempBmp); end; end; begin if (csDestroying in ComponentState) or (csCreating in Parent.ControlState) or not Assigned(FCommonData) or not FCommonData.Skinned or not FCommonData.SkinManager.SkinData.Active then Exit; FCommonData.Updating := FCommonData.Updating; if not FCommonData.Updating then begin // If transparent and form resizing processed b := FCommonData.HalfVisible or FCommonData.BGChanged;// or GetBoolMsg(Parent.Handle, AC_GETHALFVISIBLE); if SkinData.RepaintIfMoved then begin FCommonData.HalfVisible := not (PtInRect(Parent.ClientRect, Point(Left + 1, Top + 1))); FCommonData.HalfVisible := FCommonData.HalfVisible or not PtInRect(Parent.ClientRect, Point(Left + Width - 1, Top + Height - 1)); end else FCommonData.HalfVisible := False; if b and not FCommonData.UrgentPainting then PrepareCache; UpdateCorners(FCommonData, 0); if DC <> 0 then NewDC := DC else Exit; Windows.GetClientRect(Handle, RC); GetWindowRect(Handle, RW); MapWindowPoints(0, Handle, RW, 2); OffsetRect(RC, -RW.Left, -RW.Top); SavedDC := SaveDC(NewDC); for i := 0 to Bands.Count - 1 do if Assigned(Bands[i].Control) and (Bands[i].Visible or (csDesigning in ComponentState)) then begin CaptSize := GetCaptionSize(Bands[i]); if Vertical then begin CaptRect.TopLeft := Point(min(Bands[i].Control.Left - (Bands[i].Height - Bands[i].Control.Width) div 2, Bands[i].Control.Left), Bands[i].Control.Top - CaptSize); CaptRect.BottomRight := Point(CaptRect.Left + Bands[i].Height, CaptRect.Top + CaptSize); end else begin CaptRect.TopLeft := Point(Bands[i].Control.Left - CaptSize, min(Bands[i].Control.Top - (Bands[i].Height - Bands[i].Control.Height) div 2, Bands[i].Control.Top)); CaptRect.BottomRight := Point(CaptRect.Left + CaptSize, CaptRect.Top + Bands[i].Height); end; ExcludeClipRect(NewDC, CaptRect.Left, CaptRect.Top, CaptRect.Right, CaptRect.Bottom); end; R := Rect(1, 1, 1, 1); GetClipBox(NewDC, R); CopyWinControlCache(Self, FCommonData, Rect(RC.Left, RC.Top, 0, 0), Rect(0, 0, WidthOf(RC), HeightOf(RC)), NewDC, True); R := Rect(1, 1, 1, 1); GetClipBox(NewDC, R); RestoreDC(NewDC, SavedDC); R := Rect(1, 1, 1, 1); // GetClipBox(DC, R); sVCLUtils.PaintControls(NewDC, Self, b and SkinData.RepaintIfMoved, Point(0, 0)); PaintGrips; if SendUpdated then SetParentUpdated(Self); end; end; procedure TsCoolBar.AfterConstruction; begin inherited; FCommonData.Loaded; end; constructor TsCoolBar.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommonData := TsCommonData.Create(Self, True); FCommonData.COC := COC_TsCoolBar; UpdateGripIndex; end; destructor TsCoolBar.Destroy; begin if Assigned(FCommonData) then FreeAndNil(FCommonData); inherited Destroy; end; function TsCoolBar.GetCaptionFontHeight: Integer; var TxtMetric: TTextMetric; begin Result := 0; if HandleAllocated then with TControlCanvas.Create do try Control := Self; if (GetTextMetrics(Handle, TxtMetric)) then Result := TxtMetric.tmHeight; finally Free; end; end; const GripSizeIE3 = 8; GripSizeIE4 = 5; ControlMargin = 4; IDMask = $7FFFFFFF; function TsCoolBar.GetCaptionSize(Band: TCoolBand): Integer; var Text: string; Adjust, DesignText: Boolean; begin Result := 0; Adjust := False; if (Band <> nil) and ((csDesigning in ComponentState) or Band.Visible) then begin DesignText := (csDesigning in ComponentState) and (Band.Control = nil) and (Band.Text = ''); if ShowText or DesignText then begin if DesignText then Text := Band.DisplayName else Text := Band.Text; if Text <> '' then begin Adjust := True; if Vertical then Result := GetCaptionFontHeight else with TControlCanvas.Create do try Control := Self; Result := TextWidth(Text) finally Free; end; end; end; if Band.ImageIndex >= 0 then begin if Adjust then Inc(Result, 2); if Images <> nil then begin Adjust := True; if Vertical then Inc(Result, Images.Height) else Inc(Result, Images.Width) end else if not Adjust then Inc(Result, ControlMargin); end; if Adjust then Inc(Result, ControlMargin); inc(Result, GetGripSize(Band)); end; end; { function TsCoolBar.ImageRect(Band: TCoolBand): TRect; begin Result.Left := Band.Control.Left; Result.Top := Band.Control.Top; if Vertical then begin dec(Result.Top, GetCaptionSize(Band) - GetGripSize(Band)); inc(Result.Left, (Band.Width - Images.Width) div 2); end else begin dec(Result.Left, GetCaptionSize(Band) - GetGripSize(Band)); inc(Result.Top, (Band.Height - Images.Height) div 2); end; Result.Right := Result.Left; Result.Bottom := Result.Top; if Assigned(Images) and (Band.ImageIndex > -1) then begin inc(Result.Right, Images.Width); inc(Result.Bottom, Images.Height); end; end; } procedure TsCoolBar.Loaded; begin inherited; FCommonData.Loaded; UpdateGripIndex; end; procedure TsCoolBar.PrepareCache; var CI : TCacheInfo; begin InitCacheBmp(FCommonData); CI := GetParentCache(FCommonData); PaintItem(FCommonData, CI, False, 0, Rect(0, 0, width, Height), Point(Left, Top), FCommonData.FCacheBMP, True); FCommonData.BGChanged := False; end; procedure TsCoolBar.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin if not FCommonData.Skinned then inherited else begin Message.Result := 1; end; end; procedure TsCoolBar.WMNCPaint(var Message: TWMNCPaint); var DC, SavedDC: HDC; RC, RW: TRect; w, h : integer; begin if FCommonData.Skinned then begin if InAnimationProcess then Exit; FCommonData.Updating := FCommonData.Updating; if (csDestroying in ComponentState) or FCommonData.Updating then Exit; DC := GetWindowDC(Handle); SavedDC := SaveDC(DC); try RC := ACClientRect(Handle); ExcludeClipRect(DC, RC.Left, RC.Top, RC.Right, RC.Bottom); { Draw borders in non-client area } w := WidthOf(Rc); h := HeightOf(Rc); if FCommonData.BGChanged then PrepareCache; // Top BitBlt(DC, 0, 0, Width, Rc.Top, SkinData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); // Left BitBlt(DC, 0, Rc.Top, Rc.Left, h, SkinData.FCacheBmp.Canvas.Handle, 0, Rc.Top, SRCCOPY); // Bottom BitBlt(DC, 0, Rc.Bottom, Width, Height - h - Rc.Top, SkinData.FCacheBmp.Canvas.Handle, 0, Rc.Bottom, SRCCOPY); // Right BitBlt(DC, Rc.Right, Rc.Top, Width - Rc.Left - w, h, SkinData.FCacheBmp.Canvas.Handle, Rc.Right, Rc.Top, SRCCOPY); IntersectClipRect(DC, RW.Left, RW.Top, RW.Right, RW.Bottom); finally RestoreDC(DC, SavedDC); ReleaseDC(Handle, DC); end; end else inherited; end; procedure TsCoolBar.WMPaint(var Message: TWMPaint); var PS : TPaintStruct; DC, SavedDC : hdc; cR : TRect; begin if not FCommonData.Skinned then inherited else begin BeginPaint(Handle, PS); SavedDC := 0; if (Message.DC = 0) then begin DC := GetDC(Handle); SavedDC := SaveDC(DC); end else DC := Message.DC; try if not InAnimationProcess then begin cR := Rect(1, 1, 1, 1); GetClipBox(DC, cR); ACPaint(DC); end finally if Message.DC = 0 then begin RestoreDC(DC, SavedDC); ReleaseDC(Handle, DC); end; EndPaint(Handle, PS); end; end; end; procedure TsCoolBar.WndProc(var Message: TMessage); var rc : TRect; i, w, h : integer; SavedDC : hdc; begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_CTRLHANDLED : begin Message.Result := 1; Exit end; // AlphaSkins supported AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end; AC_REMOVESKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin CommonWndProc(Message, FCommonData); UpdateGripIndex; if not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, nil, nil); if HandleAllocated then RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_FRAME or RDW_UPDATENOW); AlphaBroadCast(Self, Message); exit end; AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin if not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, ' ', ' '); AlphaBroadCast(Self, Message); CommonWndProc(Message, FCommonData); UpdateGripIndex; exit end; AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin if not (csDesigning in ComponentState) and (uxthemeLib <> 0) then Ac_SetWindowTheme(Handle, ' ', ' '); CommonWndProc(Message, FCommonData); AlphaBroadCast(Self, Message); Change; RedrawWindow(Handle, nil, 0, RDW_ERASE or RDW_FRAME or RDW_ALLCHILDREN or RDW_INVALIDATE or RDW_UPDATENOW); for i := 0 to Bands.Count - 1 do TCoolBand(Bands[I]).Control.Perform(Message.Msg, Message.WParam, Message.LParam); exit end; AC_GETCACHE : begin InitBGInfo(SkinData, PacBGInfo(Message.LParam), 0); PacBGInfo(Message.LParam)^.Offset.X := ACClientRect(Handle).Left; PacBGInfo(Message.LParam)^.Offset.Y := ACClientRect(Handle).Top; Exit; end; AC_GETBG : begin InitBGInfo(FCommonData, PacBGInfo(Message.LParam), 0); if (PacBGInfo(Message.LParam)^.BgType = btCache) and not PacBGInfo(Message.LParam)^.PleaseDraw then begin PacBGInfo(Message.LParam)^.Offset.X := PacBGInfo(Message.LParam)^.Offset.X + ACClientRect(Handle).Left; PacBGInfo(Message.LParam)^.Offset.Y := PacBGInfo(Message.LParam)^.Offset.Y + ACClientRect(Handle).Top; end; Exit; end; AC_ENDPARENTUPDATE : {if FCommonData.Updating then {????} begin FCommonData.Updating := False; FCommonData.BGChanged := True; RedrawWindow(Handle, nil, 0, RDW_UPDATENOW or RDW_ERASE or RDW_INVALIDATE or RDW_INTERNALPAINT or RDW_ERASENOW or RDW_FRAME); SetParentUpdated(Self); end; AC_PREPARING : begin Message.Result := integer(FCommonData.FUpdating); Exit; end else CommonMessage(Message, FCommonData); end else begin case Message.Msg of CM_VISIBLECHANGED : begin FCommonData.BGChanged := True; inherited; if not FCommonData.Updating then Repaint; Exit; end; // WM_SIZE : FCommonData.Updating := True; WM_KILLFOCUS, WM_SETFOCUS: begin inherited; exit end; WM_PRINT : begin FCommonData.Updating := False; try RC := ACClientRect(Handle); w := WidthOf(Rc); h := HeightOf(Rc); if FCommonData.BGChanged then PrepareCache; // Top BitBlt(TWMPaint(Message).DC, 0, 0, Width, Rc.Top, SkinData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY); // Left BitBlt(TWMPaint(Message).DC, 0, Rc.Top, Rc.Left, h, SkinData.FCacheBmp.Canvas.Handle, 0, Rc.Top, SRCCOPY); // Bottom BitBlt(TWMPaint(Message).DC, 0, Rc.Bottom, Width, Height - h - Rc.Top, SkinData.FCacheBmp.Canvas.Handle, 0, Rc.Bottom, SRCCOPY); // Right BitBlt(TWMPaint(Message).DC, Rc.Right, Rc.Top, Width - Rc.Left - w, h, SkinData.FCacheBmp.Canvas.Handle, Rc.Right, Rc.Top, SRCCOPY); MoveWindowOrg(TWMPaint(Message).DC, Rc.Left, Rc.Top); IntersectClipRect(TWMPaint(Message).DC, 0, 0, w, h); ACPaint(TWMPaint(Message).DC); for i := 0 to Bands.Count - 1 do if Bands[i].Control <> nil then begin SavedDC := SaveDC(TWMPaint(Message).DC); MoveWindowOrg(TWMPaint(Message).DC, Bands[i].Control.Left, Bands[i].Control.Top); IntersectClipRect(TWMPaint(Message).DC, 0, 0, Bands[i].Control.Width, Bands[i].Control.Height); Bands[i].Control.Perform(WM_PAINT, Message.WParam, Message.LParam); RestoreDC(TWMPaint(Message).DC, SavedDC); end; finally end; Exit; end; end; CommonWndProc(Message, FCommonData); inherited; if (FCommonData <> nil) and FCommonData.Skinned then begin case Message.Msg of WM_SIZE : begin FCommonData.BGChanged := True; RedrawWindow(Handle, nil, 0, RDW_UPDATENOW or RDW_ERASE or RDW_INVALIDATE or RDW_INTERNALPAINT or RDW_ERASENOW or RDW_FRAME); end; end; end end; end; function TsCoolBar.GetGripSize(Band: TCoolBand) : integer; begin Result := 0; if (not FixedOrder or (Band.ID and IDMask > 0)) and not Band.FixedSize then begin Inc(Result, ControlMargin); if GetComCtlVersion < ComCtlVersionIE4 then Inc(Result, GripSizeIE3) else Inc(Result, GripSizeIE4); end; end; procedure TsCoolBar.UpdateGripIndex; begin if FCommonData.Skinned then begin if Vertical then FGripsection := s_GripV else FGripsection := s_GripH; FGripIndex := SkinData.SkinManager.GetSkinIndex(FGripsection); if FGripIndex <> -1 then begin FGripMask := SkinData.SkinManager.GetMaskIndex(FGripsection, s_BordersMask); FGripTexture := SkinData.SkinManager.GetTextureIndex(FGripIndex, FGripsection, s_Pattern); end else begin FGripsection := s_ProgressV;//s_Button; FGripIndex := SkinData.SkinManager.GetSkinIndex(FGripsection); FGripMask := SkinData.SkinManager.GetMaskIndex(FGripsection, s_BordersMask); end; end else begin FGripIndex := -1; FGripMask := -1; FGripTexture := -1; end; end; end.
unit hxHexEditorFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Forms, Controls, ComCtrls, ExtCtrls, Dialogs, Menus, ActnList, OMultiPanel, hxGlobal, hxHexEditor, hxBasicViewerFrame, hxDataViewerFrame, hxRecordViewerFrame, hxObjectViewerFrame; type { THexEditorFrame } THexEditorFrame = class(TFrame) SaveDialog: TSaveDialog; private MainPanel: TOMultiPanel; LeftPanel: TOMultiPanel; CenterPanel: TOMultiPanel; RightPanel: TOMultiPanel; BottomPanel: TOMultiPanel; HexPanel: TPanel; FHexEditor: THxHexEditor; FDataViewer: TDataViewerFrame; FRecordViewer: TRecordViewerFrame; FObjectViewer: TObjectViewerFrame; FStatusbarItems: TStatusbarItems; FStatusbarPosDisplay: TOffsetDisplayBase; FStatusbarSelDisplay: TOffsetDisplayBase; FObjectSaveDir: String; FOnChange: TNotifyEvent; FOnUpdateStatusBar: TNotifyEvent; FExtractorAborted: Boolean; FExtractorIndex: Integer; procedure CreateMultiPanels; function GetFileName: String; function GetOffsetDisplayBase(AOffsetFormat: String): TOffsetDisplayBase; function GetOffsetDisplayHexPrefix(AOffsetFormat: String): String; function GetShowDataViewer: Boolean; procedure SetShowDataViewer(AValue: Boolean); function GetDataViewerPosition: TViewerPosition; procedure SetDataViewerPosition(AValue: TViewerPosition); function GetShowObjectViewer: Boolean; procedure SetShowObjectViewer(AValue: Boolean); function GetObjectViewerPosition: TViewerPosition; procedure SetObjectViewerPosition(AValue: TViewerPosition); function GetShowRecordViewer: Boolean; procedure SetShowRecordViewer(AValue: Boolean); function GetRecordViewerPosition: TViewerPosition; procedure SetRecordViewerPosition(AValue: TViewerPosition); procedure SetOnChange(AValue: TNotifyEvent); protected procedure CheckUserAbortHandler(Sender: TObject; var Aborted: Boolean); procedure CreateHexEditor; procedure CreateDataViewer; procedure CreateRecordViewer; procedure CreateObjectViewer; procedure DoUpdateStatusBar; function GetViewerPanel(APosition: TViewerPosition): TOMultiPanel; function GetViewerPosition(AViewer: TBasicViewerFrame): TViewerPosition; function GetWriteProtected: Boolean; procedure HexEditorChanged(Sender: TObject); procedure SetParent(AParent: TWinControl); override; procedure SetViewerPosition(AViewer: TBasicViewerFrame; AValue: TViewerPosition); procedure SetWriteProtected(const AValue: Boolean); procedure UpdateViewerPanelVisible(APanel: TOMultiPanel); procedure LoadFromIni; procedure SaveToIni; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ActiveColors(var AParams: TColorParams); procedure ActiveHexParams(var AParams: THexParams); procedure ApplyHexParams(const AParams: THexParams); function CanSaveFileAs(const AFileName: String): Boolean; procedure ExportObject; procedure FindDlg; procedure FindObjectHandler(Sender: TObject); procedure InsertMode(const AEnable: Boolean); procedure JumpToPosition(APosition: Integer); procedure OpenFile(const AFileName: string; WriteProtected: boolean); procedure ReplaceDlg; procedure SaveFile; procedure SaveFileAs(const AFileName: string); procedure SelectObject; procedure UpdateCaption; procedure UpdateIconSet; procedure UpdateStatusBar(AStatusBar: TStatusBar); procedure UpdateStatusBarPanelWidths(AStatusBar: TStatusBar); property Caption; property ExtractorIndex: Integer read FExtractorIndex; property FileName: String read GetFileName; property HexEditor: THxHexEditor read FHexEditor; property DataViewerPosition: TViewerPosition read GetDataViewerPosition write SetDataViewerPosition; property ObjectViewer: TObjectViewerFrame read FObjectViewer; property ObjectViewerPosition: TViewerPosition read GetObjectViewerPosition write SetObjectViewerPosition; property RecordViewerPosition: TViewerPosition read GetRecordViewerPosition write SetRecordViewerPosition; property ShowDataViewer: Boolean read GetShowDataViewer write SetShowDataViewer; property ShowObjectViewer: Boolean read GetShowObjectViewer write SetShowObjectViewer; property ShowRecordViewer: Boolean read GetShowRecordViewer write SetShowRecordViewer; property WriteProtected: Boolean read GetWriteProtected write SetWriteProtected; property OnChange: TNotifyEvent read FOnChange write SetOnChange; property OnUpdateStatusBar: TNotifyEvent read FOnUpdateStatusBar write FOnUpdateStatusBar; end; implementation {$R *.lfm} uses StrUtils, IniFiles, Math, hxStrings, hxUtils, hxSearchReplaceDlg; constructor THexEditorFrame.Create(AOwner: TComponent); begin inherited; CreateMultiPanels; FExtractorIndex := -1; end; destructor THexEditorFrame.Destroy; begin SaveToIni; inherited; end; procedure THexEditorFrame.ActiveColors(var AParams: TColorParams); begin AParams := ColorParams; if Assigned(HexEditor) then begin AParams.BackgroundColor := HexEditor.Colors.Background; AParams.ActiveFieldBackgroundColor := HexEditor.Colors.ActiveFieldBackground; AParams.OffsetBackgroundColor := HexEditor.Colors.OffsetBackground; AParams.OffsetForegroundColor := HexEditor.Colors.Offset; AParams.CurrentOffsetBackgroundColor := HexEditor.Colors.CurrentOffsetBackground; AParams.CurrentOffsetForegroundColor := HexEditor.Colors.CurrentOffset; AParams.EvenColumnForegroundColor := HexEditor.Colors.EvenColumn; AParams.OddColumnForegroundColor := HexEditor.Colors.OddColumn; AParams.ChangedBackgroundColor := HexEditor.Colors.ChangedBackground; AParams.ChangedForegroundColor := HexEditor.Colors.ChangedText; AParams.CharFieldForegroundColor := HexEditor.Font.Color; end; end; procedure THexEditorFrame.ActiveHexParams(var AParams: THexParams); var i: Integer; begin AParams := HexParams; if Assigned(HexEditor) then begin AParams.ViewOnly := HexEditor.ReadOnlyView; AParams.WriteProtected := HexEditor.ReadOnlyFile; AParams.AllowInsertMode := HexEditor.AllowInsertMode; AParams.InsertMode := HexEditor.InsertMode; AParams.RulerVisible := HexEditor.ShowRuler; AParams.RulerNumberBase := GetOffsetDisplayBase(IntToStr(HexEditor.RulerNumberBase)); AParams.OffsetDisplayBase := GetOffsetDisplayBase(HexEditor.OffsetFormat); AParams.OffsetDisplayHexPrefix := GetOffsetDisplayHexPrefix(HexEditor.OffsetFormat); AParams.BytesPerRow := HexEditor.BytesPerRow; AParams.BytesPerColumn := HexEditor.BytesPerColumn; AParams.MaskChar := HexEditor.MaskChar; AParams.FontName := HexEditor.Font.Name; AParams.FontSize := HexEditor.Font.Size; AParams.HexLowercase := HexEditor.HexLowercase; AParams.DrawGutter3D := HexEditor.DrawGutter3D; end; AParams.StatusbarItems := FStatusbarItems; AParams.StatusbarPosDisplay := FStatusbarPosDisplay; AParams.StatusbarSelDisplay := FStatusbarSelDisplay; if Assigned(FDataViewer) then begin AParams.DataViewerVisible := GetShowDataViewer; AParams.DataViewerPosition := GetDataViewerPosition; for i:=0 to High(AParams.DataViewerColWidths) do AParams.DataViewerColWidths[i] := FDataViewer.ColWidths[i]; end; if Assigned(FObjectViewer) then begin AParams.ObjectViewerVisible := GetShowObjectViewer; AParams.ObjectViewerPosition := GetObjectViewerPosition; end; if Assigned(FRecordViewer) then begin AParams.RecordViewerVisible := GetShowRecordViewer; AParams.RecordViewerPosition := GetRecordViewerPosition; for i:=0 to High(AParams.RecordViewerColWidths) do AParams.RecordViewerColWidths[i] := FRecordViewer.ColWidths[i]; end; end; procedure THexEditorFrame.ApplyHexParams(const AParams: THexParams); var i: Integer; begin ApplyParamsToHexEditor(AParams, HexEditor); FStatusbarItems := AParams.StatusbarItems; FStatusbarPosDisplay := AParams.StatusbarPosDisplay; FStatusbarSelDisplay := AParams.StatusbarSelDisplay; ShowDataViewer := AParams.DataViewerVisible; // this creates the NumViewer if Assigned(FDataViewer) then begin SetDataViewerPosition(AParams.DataViewerPosition); for i := 0 to High(AParams.DataViewerColWidths) do FDataViewer.ColWidths[i] := AParams.DataViewerColWidths[i]; end; ShowObjectViewer := AParams.ObjectViewerVisible; // this creates the ObjectViewer if Assigned(FObjectViewer) then begin SetObjectViewerPosition(AParams.ObjectViewerPosition); end; ShowRecordViewer := AParams.RecordViewerVisible; // this creates the RecordViewer if Assigned(FRecordViewer) then begin SetRecordViewerPosition(AParams.RecordViewerPosition); for i := 0 to High(AParams.RecordViewerColWidths) do FRecordViewer.ColWidths[i] := AParams.RecordViewerColWidths[i]; end; // LoadFromIni; // why this? UpdateViewerPanelVisible(LeftPanel); UpdateViewerPanelVisible(RightPanel); UpdateViewerPanelVisible(BottomPanel); MainPanel.ResizeControls; end; function THexEditorFrame.CanSaveFileAs(const AFileName: String): Boolean; begin Result := not ((AFileName = GetFileName) and HexEditor.ReadOnlyFile); end; procedure THexEditorFrame.CheckUserAbortHandler(Sender: TObject; var Aborted: boolean); begin Aborted := FExtractorAborted; end; procedure THexEditorFrame.CreateHexEditor; begin FHexEditor := THxHexEditor.Create(self); FHexEditor.Parent := HexPanel; FHexEditor.Align := alClient; FHexEditor.DrawGutter3D := false; FHexEditor.WantTabs := false; FHexEditor.OnChange := @HexEditorChanged; FHexEditor.OnSelectionChanged := @HexEditorChanged; ApplyParamsToHexEditor(HexParams, FHexEditor); FHexEditor.ReadOnlyView := true; FHexEditor.ReadOnlyFile := true; // CommonData.BookmarkImages.GetFullBitmap(FHexEditor.BookmarkBitmap); end; procedure THexEditorFrame.CreateDataViewer; var panel: TOMultiPanel; begin FDataViewer.Free; FDataViewer := TDataViewerFrame.Create(self); FDataViewer.Name := ''; panel := GetViewerPanel(HexParams.DataViewerPosition); with (panel.Parent as TOMultiPanel) do begin FindPanel(panel).Visible := true; ResizeControls; end; FDataViewer.Parent := panel; with panel.PanelCollection.Add do Control := FDataViewer; UpdateViewerPanelVisible(panel); end; procedure THexEditorFrame.CreateMultiPanels; begin MainPanel := TOMultiPanel.Create(self); with MainPanel do begin Align := alClient; Parent := self; end; LeftPanel := TOMultiPanel.Create(MainPanel); with LeftPanel do PanelType := ptVertical; CenterPanel :=TOMultiPanel.Create(MainPanel); with CenterPanel do PanelType := ptVertical; RightPanel := TOMultiPanel.Create(MainPanel); with RightPanel do begin PanelType := ptVertical; end; BottomPanel := TOMultiPanel.Create(CenterPanel); HexPanel := TPanel.Create(CenterPanel); MainPanel.PanelCollection.AddControl(LeftPanel); MainPanel.PanelCollection.AddControl(CenterPanel); MainPanel.PanelCollection.AddControl(RightPanel); CenterPanel.PanelCollection.AddControl(HexPanel); CenterPanel.PanelCollection.AddControl(BottomPanel); LeftPanel.Parent := MainPanel; CenterPanel.Parent := MainPanel; RightPanel.Parent := MainPanel; HexPanel.Parent := CenterPanel; BottomPanel.Parent := CenterPanel; MainPanel.PanelCollection[0].Position := 0.25; MainPanel.PanelCollection[1].Position := 0.75; MainPanel.PanelCollection[2].Position := 1.00; CenterPanel.PanelCollection[0].Position := 0.75; CenterPanel.PanelCollection[1].Position := 1.00; end; procedure THexEditorFrame.CreateRecordViewer; var panel: TOMultiPanel; begin FRecordViewer.Free; FRecordViewer := TRecordViewerFrame.Create(self); FRecordViewer.Name := ''; panel := GetViewerPanel(HexParams.RecordViewerPosition); with (panel.Parent as TOMultiPanel) do begin FindPanel(panel).Visible := true; ResizeControls; end; FRecordViewer.Parent := panel; with panel.PanelCollection.Add do Control := FRecordViewer; UpdateViewerPanelVisible(panel); end; procedure THexEditorFrame.CreateObjectViewer; var panel: TOMultiPanel; begin FObjectViewer.Free; FObjectViewer := TObjectViewerFrame.Create(self); FObjectViewer.Name := ''; panel := GetViewerPanel(HexParams.ObjectViewerPosition); with (panel.Parent as TOMultiPanel) do begin FindPanel(panel).Visible := true; ResizeControls; end; FObjectViewer.Parent := panel; with panel.PanelCollection.Add do Control := FObjectViewer; UpdateViewerPanelVisible(panel); end; procedure THexEditorFrame.ExportObject; var stream: TStream; ex: TExtractor; lSize: Integer; begin if FObjectViewer = nil then exit; ex := FObjectViewer.Extractor; if (not ShowObjectViewer) or (not Assigned(ex)) or (not ex.CanExtract(FHexEditor, FHexEditor.GetCursorPos, lSize)) then exit; with SaveDialog do begin InitialDir := FObjectSaveDir; DefaultExt := Lowercase(Format('*.%s', [ex.FirstFileExt])); Filter := ex.ExtractorFilter; FileName := ''; if Execute then begin Application.ProcessMessages; stream := TFileStream.Create(FileName, fmCreate + fmShareDenyNone); try ex.SaveToStream(stream); FObjectSaveDir := ExtractFileDir(FileName); finally stream.Free; end; end; end; end; procedure THexEditorFrame.DoUpdateStatusBar; begin if Assigned(FOnUpdateStatusBar) then FOnUpdateStatusBar(self); end; procedure THexEditorFrame.FindDlg; begin if (FHexEditor = nil) or (FHexEditor.DataSize < 1) then Exit; if SearchReplaceForm = nil then begin SearchReplaceForm := TSearchReplaceForm.Create(Application); SearchReplaceForm.FormStyle := fsStayOnTop; end; SearchReplaceForm.HexEditor := FHexEditor; SearchReplaceForm.BigEndian := HexParams.BigEndian; SearchReplaceForm.Mode := srmSearch; SearchReplaceForm.Show; end; procedure THexEditorFrame.FindObjectHandler(Sender: TObject); var idx: Integer; begin if Assigned(FObjectViewer) then begin idx := (Sender as TComponent).Tag - TAG_FIND_OBJECTS - 1; if (idx < 0) and (FExtractorIndex >= 0) then // "Find next" FObjectViewer.FindObject(FExtractorIndex, HexEditor, HexEditor.GetCursorPos+1) else if (idx >= 0) and FObjectViewer.FindObject(idx, HexEditor, 0) then FExtractorIndex := idx else FExtractorIndex := -1; end; end; function THexEditorFrame.GetFileName: String; begin if Assigned(FHexEditor) then Result := FHexEditor.FileName else Result := ''; end; function THexEditorFrame.GetOffsetDisplayBase(AOffsetFormat: String): TOffsetDisplayBase; var p1, p2: Integer; s: String; begin p1 := Pos('!', AOffsetFormat); p2 := Pos(':', AOffsetFormat); if (p1 = 0) and (p2 = 0) then s := AOffsetFormat else s := '$' + copy(AOffsetFormat, p1+1, p2-p1-1); case StrToInt(s) of 16: Result := odbHex; 10: Result := odbDec; 8: Result := odbOct; end; end; function THexEditorFrame.GetDataViewerPosition: TViewerPosition; begin Result := GetViewerPosition(FDataViewer); end; function THexEditorFrame.GetObjectViewerPosition: TViewerPosition; begin Result := GetViewerPosition(FObjectViewer); end; function THexEditorFrame.GetOffsetDisplayHexPrefix(AOffsetFormat: String): String; var p1, p2: Integer; begin p1 := Pos(':', AOffsetFormat); p2 := Pos('|', AOffsetFormat); Result := Copy(AOffsetFormat, p1+1, p2-p1-1); end; function THexEditorFrame.GetShowDataViewer: Boolean; begin Result := (FDataViewer <> nil) and FDataViewer.Visible; end; function THexEditorFrame.GetShowObjectViewer: Boolean; begin Result := (FObjectViewer <> nil) and FObjectViewer.Visible; end; function THexEditorFrame.GetRecordViewerPosition: TViewerPosition; begin Result := GetViewerPosition(FRecordViewer); end; function THexEditorFrame.GetShowRecordViewer: Boolean; begin Result := (FRecordViewer <> nil) and FRecordViewer.Visible; end; function THexEditorFrame.GetViewerPanel(APosition: TViewerPosition): TOMultiPanel; begin case APosition of vpLeft: Result := LeftPanel; vpRight: Result := RightPanel; vpBottom: Result := BottomPanel; else raise Exception.Create('[THexEditorFrame.GetViewerPanel] Unsupported ViewerPosition.'); end; end; function THexEditorFrame.GetViewerPosition(AViewer: TBasicViewerFrame): TViewerPosition; begin if AViewer.Parent = LeftPanel then Result := vpLeft else if AViewer.Parent = RightPanel then Result := vpRight else if AViewer.Parent = BottomPanel then Result := vpBottom else raise Exception.Create('[THexEditorFrame.GetViewerPosition] Unsupported Parent.'); end; function THexEditorFrame.GetWriteProtected: Boolean; begin Result := Assigned(FHexEditor) and FHexEditor.ReadOnlyView; end; procedure THexEditorFrame.HexEditorChanged(Sender: TObject); begin DoUpdateStatusBar; if Assigned(FDataViewer) then FDataViewer.UpdateData(FHexEditor); if Assigned(FObjectViewer) then FObjectViewer.UpdateData(FHexEditor); if Assigned(FRecordViewer) then FRecordViewer.UpdateData(FHexEditor); if Assigned(FOnChange) then FOnChange(self); end; procedure THexEditorFrame.InsertMode(const AEnable: Boolean); begin if Assigned(FHexEditor) then begin FHexEditor.InsertMode := AEnable; DoUpdateStatusBar; end; end; procedure THexEditorFrame.JumpToPosition(APosition: Integer); var ok : boolean; begin if not Assigned(HexEditor) then exit; ok := true; if APosition < 0 then begin ok := Confirm(SGotoPastBOF); if ok then APosition := 0; end else if APosition > HexEditor.DataSize then begin ok := Confirm(SGotoPastEOF); if ok then APosition := HexEditor.DataSize - 1; end; if ok then HexEditor.Seek(APosition, soFromBeginning); end; procedure THexEditorFrame.LoadFromIni; var ini: TCustomIniFile; begin ini := CreateIniFile; try MainPanel.LoadPositionsFromIniFile(ini, 'MainPanel', 'Positions'); LeftPanel.LoadPositionsFromIniFile(ini, 'LeftPanel', 'Positions'); CenterPanel.LoadPositionsFromIniFile(ini, 'CenterPanel', 'Positions'); RightPanel.LoadPositionsFromIniFile(ini, 'RightPanel', 'Positions'); BottomPanel.LoadPositionsFromIniFile(ini, 'BottomPanel', 'Positions'); finally ini.Free; end; end; procedure THexEditorFrame.OpenFile(const AFileName: string; WriteProtected: boolean); begin if Assigned(HexEditor) then begin HexEditor.LoadFromFile(AFileName); HexEditor.ReadOnlyFile := WriteProtected; UpdateCaption; end; end; procedure THexEditorFrame.ReplaceDlg; begin if (FHexEditor = nil) or (FHexEditor.DataSize < 1) then Exit; if SearchReplaceForm = nil then begin SearchReplaceForm := TSearchReplaceForm.Create(Application); SearchReplaceForm.FormStyle := fsStayOnTop; end; SearchReplaceForm.HexEditor := FHexEditor; SearchReplaceForm.BigEndian := HexParams.BigEndian; SearchReplaceForm.Mode := srmReplace; SearchReplaceForm.Show; end; procedure THexEditorFrame.SaveFile; begin if Assigned(HexEditor) then SaveFileAs(HexEditor.FileName); end; procedure THexEditorFrame.SaveFileAs(const AFileName: string); begin if Assigned(HexEditor) then begin if not CanSaveFileAs(AFileName) then begin MessageDlg(Format(SReadOnlyFile, [AFileName]), mtError, [mbOK], 0); exit; end; try HexEditor.SaveToFile(AFileName); UpdateCaption; except on E: Exception do ErrorFmt(SErrorSavingFile + LineEnding + E.Message, [AFileName]); end; end; end; procedure THexEditorFrame.SelectObject; var P: Integer; lSize: Integer; begin if ShowObjectViewer and Assigned(FObjectViewer.Extractor) then begin P := FHexEditor.GetCursorPos; if FObjectViewer.Extractor.CanExtract(FHexEditor, P, lSize) then begin FHexEditor.SelStart := P; FHexEditor.SelEnd := P + lSize - 1; end; end; end; procedure THexEditorFrame.SetDataViewerPosition(AValue: TViewerPosition); begin SetViewerPosition(FDataViewer, AValue); end; procedure THexEditorFrame.SetObjectViewerPosition(AValue: TViewerPosition); begin SetViewerPosition(FObjectViewer, AValue); end; procedure THexEditorFrame.SetOnChange(AValue: TNotifyEvent); begin FOnChange := AValue; if Assigned(FHexEditor) then FHexEditor.OnChange := FOnChange; end; procedure THexEditorFrame.SetParent(AParent: TWinControl); begin inherited; if (AParent <> nil) and (FHexEditor = nil) then CreateHexEditor; ApplyHexParams(HexParams); ApplyColorsToHexEditor(ColorParams, FHexEditor); if HexEditor.CanFocus then HexEditor.SetFocus; end; procedure THexEditorFrame.SetRecordViewerPosition(AValue: TViewerPosition); begin SetViewerPosition(FRecordViewer, AValue); end; procedure THexEditorFrame.SetShowDataViewer(AValue: Boolean); var panel: TOMultiPanel; begin if AValue then begin // Show number viewer if Assigned(FDataViewer) then exit; CreateDataViewer; FDataViewer.UpdateData(HexEditor); HexParams.DataViewerVisible := true; end else begin // Hide number viewer if not Assigned(FDataViewer) then exit; panel := FDataViewer.Parent as TOMultiPanel; FreeAndNil(FDataViewer); UpdateViewerPanelVisible(panel); HexParams.DataViewerVisible := false; end; end; procedure THexEditorFrame.SetShowObjectViewer(AValue: Boolean); var panel: TOMultiPanel; begin if AValue then begin // Show object viewer if Assigned(FObjectViewer) then exit; CreateObjectViewer; FObjectViewer.UpdateData(HexEditor); HexParams.ObjectViewerVisible := true; end else begin // Hide object viewer if not Assigned(FObjectViewer) then exit; panel := FObjectViewer.Parent as TOMultiPanel; FreeAndNil(FObjectViewer); UpdateViewerPanelVisible(panel); HexParams.ObjectViewerVisible := false; end; end; procedure THexEditorFrame.SetShowRecordViewer(AValue: Boolean); var panel: TOMultiPanel; begin if AValue then begin // Show record viewer if Assigned(FRecordViewer) then exit; CreateRecordViewer; FRecordViewer.UpdateData(HexEditor); HexParams.RecordViewerVisible := true; end else begin // Hide record viewer if not Assigned(FRecordViewer) then exit; panel := FRecordViewer.Parent as TOMultiPanel; FreeAndNil(FRecordViewer); UpdateViewerPanelVisible(panel); HexParams.RecordViewerVisible := false; end; end; procedure THexEditorFrame.SetViewerPosition(AViewer: TBasicViewerFrame; AValue: TViewerPosition); var oldPanel, newPanel: TOMultiPanel; idx: Integer; begin if csDestroying in ComponentState then exit; // Remove from old panel oldPanel := AViewer.Parent as TOMultiPanel; idx := oldPanel.PanelCollection.IndexOf(AViewer); oldPanel.PanelCollection.Delete(idx); // Insert into new panel newPanel := GetViewerPanel(AValue); AViewer.Parent := newPanel; newPanel.PanelCollection.AddControl(AViewer); UpdateViewerPanelVisible(newPanel); if oldPanel <> newPanel then UpdateViewerPanelVisible(oldPanel); //StatusBar.Top := Height * 2; end; procedure THexEditorFrame.SetWriteProtected(const AValue: Boolean); begin if Assigned(FHexEditor) then FHexEditor.ReadOnlyView := AValue; if Assigned(FDataViewer) then FDataViewer.WriteProtected := AValue; if Assigned(FRecordViewer) then FRecordViewer.WriteProtected := AValue; end; procedure THexEditorFrame.UpdateCaption; begin if Assigned(FHexEditor) then begin Caption := ExtractFilename(FHexEditor.FileName); if FHexEditor.Modified then Caption := '* ' + Caption //Format(SWriteProtectedCaption, [Caption]); end else Caption := SEmptyCaption; end; procedure THexEditorFrame.UpdateIconSet; begin if Assigned(FDataViewer) then FDataViewer.UpdateIconSet; if Assigned(FRecordViewer) then FRecordViewer.UpdateIconSet; if Assigned(FObjectViewer) then FObjectViewer.UpdateIconSet; end; procedure THexEditorFrame.UpdateStatusbar(AStatusBar: TStatusBar); // Panel 0: Modified (width=40) // Panel 1: ReadOnly ( 30) // Panel 2: Insert / Overwrite ( 40) // Panel 3: Position ( 80) // Panel 4: Markierung ( 180) // Panel 5: Dateigröße ( 120) var p: integer; i1, i2, n: integer; s: string; hexprefix: String; begin inherited; if Assigned(HexEditor) then begin hexprefix := GetOffsetDisplayHexPrefix(HexEditor.OffsetFormat); AStatusbar.Panels[0].Text := IfThen(HexEditor.Modified, 'MOD', ''); if HexEditor.ReadOnlyView then AStatusBar.Panels[1].Text := 'R/O' else AStatusbar.Panels[1].Text := IfThen(HexEditor.InsertMode, 'INS', 'OVW'); p := 2; if sbPos in FStatusbarItems then begin case FStatusbarPosDisplay of odbDec: s := Format('%.0n', [1.0*HexEditor.GetCursorPos]); odbHex: s := Format('%s%x', [hexprefix, HexEditor.GetCursorPos]); odbOct: s := Format('&%s', [IntToOctal(HexEditor.GetCursorPos)]); end; s := Format(SMaskPos, [s]); AStatusbar.Panels[p].Text := s; inc(p); end; if sbSel in FStatusbarItems then begin if HexEditor.SelCount <> 0 then begin i1 := Min(HexEditor.SelStart, HexEditor.SelEnd); i2 := Max(HexEditor.SelStart, HexEditor.SelEnd); n := HexEditor.SelCount; case FStatusbarSelDisplay of odbDec: s := Format('%.0n ... %.0n (%.0n)', [1.0*i1, 1.0*i2, 1.0*n]); odbHex: s := Format('%0:s%1:x ... %0:s%2:x (%0:s%3:x)', [hexPrefix, i1, i2, n]); odbOct: s := Format('&%s ... &%s (&%s)', [IntToOctal(i1), IntToOctal(i2), IntToOctal(n)]); end; end else s := ''; AStatusBar.Panels[p].Text := s; inc(p); end; if sbSize in FStatusbarItems then begin s := Format('%.0n', [1.0 * HexEditor.DataSize]); AStatusBar.Panels[p].Text := Format(SMaskSize, [s]); inc(p); end; end; end; procedure THexEditorFrame.UpdateStatusbarPanelWidths(AStatusBar: TStatusBar); var n: integer; s: String; hexPrefix: String; begin AStatusbar.Canvas.Font.Assign(AStatusbar.Font); hexprefix := GetOffsetDisplayHexPrefix(HexEditor.OffsetFormat); AStatusBar.Panels.Clear; // "Modified" flag AStatusBar.Panels.Add.Width := 40; // "ReadOnly" flag AStatusBar.Panels.Add.Width := 30; // Position if (sbPos in FStatusBarItems) then if Assigned(HexEditor) then begin case FStatusBarPosDisplay of odbDec: s := Format('%.0n', [1.0*HexEditor.DataSize]); odbHex: s := Format('%s%x', [hexprefix, HexEditor.DataSize]); odbOct: s := Format('&%s', [IntToOctal(HexEditor.DataSize)]); end; s := Format(SMaskPos, [s]); AStatusBar.Panels.Add.Width := AStatusbar.Canvas.TextWidth(s) + 10; end else AStatusBar.Panels.Add.Width := 120; // Selection if sbSel in FStatusbarItems then if Assigned(FHexEditor) then begin n := HexEditor.DataSize; case FStatusbarSelDisplay of odbDec: s := Format('%.0n ... %.0n (%.0n)', [1.0*n, 1.0*n, 1.0*n]); odbHex: s := Format('%0:s%1:x ... %0:s%2:x (%0:s%3:x)', [hexPrefix, n, n, n]); odbOct: s := Format('&%s ... &%s (&%s)', [IntToOctal(n), IntToOctal(n), IntToOctal(n)]); end; AStatusbar.Panels.Add.Width := AStatusbar.Canvas.TextWidth(s) + 10; end else AStatusbar.Panels.Add.Width := 250; // Data size if sbSize in FStatusbarItems then if Assigned(HexEditor) then begin s := Format('%.0n', [1.0 * HexEditor.DataSize]); s := Format(SMaskSize, [s]); AStatusBar.Panels.Add.Width := AStatusBar.Canvas.TextWidth(s) + 10; end else AStatusbar.Panels.Add.Width := 150; // Hint texts AStatusBar.Panels.Add.Width := 200; end; procedure THexEditorFrame.UpdateViewerPanelVisible(APanel: TOMultiPanel); var i: Integer; hasControls: Boolean; item: TOMultiPanelItem; parentPanel: TOMultiPanel; begin hasControls := false; for i := 0 to APanel.PanelCollection.Count-1 do if APanel.PanelCollection[i].Visible and Assigned(APanel.PanelCollection[i].Control) then begin hasControls := true; break; end; parentPanel := APanel.Parent as TOMultiPanel; item := parentPanel.FindPanel(APanel); if Assigned(item) then item.Visible := hasControls; APanel.ResizeControls; parentPanel.ResizeControls; end; procedure THexEditorFrame.SaveToIni; var ini: TCustomIniFile; begin ini := CreateIniFile; try MainPanel.SavePositionsToIniFile(ini, 'MainPanel', 'Positions'); LeftPanel.SavePositionsToIniFile(ini, 'LeftPanel', 'Positions'); CenterPanel.SavePositionsToIniFile(ini, 'CenterPanel', 'Positions'); RightPanel.SavePositionsToIniFile(ini, 'RightPanel', 'Positions'); BottomPanel.SavePositionsToIniFile(ini, 'BottomPanel', 'Positions'); finally ini.Free; end; end; end.
{ Test some GEOS library functionality } unit DummyGeosUseTest; interface uses TestFramework, Geos_c; type Vertex2D = record X , Y : Double; end; Vertex2DArray = array [0..4] of Vertex2D; // No need to override SetUp & TearDown. // GEOS starts in DummyGeosUse unit. TGeosTest = class(TTestCase) private procedure CheckSeqCoords(ASeq: PGEOSCoordSequence; var ACoords: Vertex2DArray; ASize: Integer); procedure CreateSeqChecked(var ASeq: PGEOSCoordSequence; ASize: Integer); procedure FillCoordSeq(ASeq: PGEOSCoordSequence; var ACoords: Vertex2DArray; ASize: Integer); published procedure TestVersion; procedure TestCoordSeqCreation; procedure TestPointCreation; procedure TestLinearRingCreation; procedure TestUnclosedLinearRingCreationFail; procedure TestLineStringCreation; procedure TestPolygonCreationShellOnly; procedure TestPolygonCreationWithHoles; procedure TestWKTReader; procedure TestWKTWriter; procedure TestWKBReader; procedure TestWKBWriter; end; implementation uses DummyGeosUse, System.SysUtils; var coords : Vertex2DArray = ( (X : 1 ; Y : 1), (X : 61 ; Y : 1), (X : 61 ; Y : 61), (X : 1 ; Y : 61), (X : 1 ; Y : 1) ); coordsWKT: string = 'LINESTRING (1 1, 61 1, 61 61, 1 61, 1 1)'; coordsWKBHex: string = '010200000005000000000000000000F03F000000000000F03F0000000000804E40000000000000F03F0000000000804E400000000000804E40000000000000F03F0000000000804E40000000000000F03F000000000000F03F'; coords0 : Vertex2DArray = ( (X : 11 ; Y : 11), (X : 21 ; Y : 11), (X : 21 ; Y : 21), (X : 11 ; Y : 21), (X : 11 ; Y : 11) ); coords1 : Vertex2DArray = ( (X : 31 ; Y : 31), (X : 51 ; Y : 31), (X : 51 ; Y : 51), (X : 31 ; Y : 51), (X : 31 ; Y : 31) ); // thanks, internet :) function xHexToBin(const HexStr: String): TBytes; const HexSymbols = '0123456789ABCDEF'; var i, j: Integer; B: Byte; begin SetLength(Result, (Length(HexStr) + 1) shr 1); B := 0; i := 0; while i < Length(HexStr) do begin j:= 0; while j < Length(HexSymbols) do begin if HexStr[i + 1] = HexSymbols[j + 1] then Break; Inc(j); end; if j = Length(HexSymbols) then ; // error if Odd(i) then Result[i shr 1] := B shl 4 + j else B := j; Inc(i); end; if Odd(i) then Result[i shr 1] := B; end; procedure TGeosTest.CheckSeqCoords(aSeq: PGEOSCoordSequence; var aCoords: Vertex2DArray; aSize: Integer); var Y: Double; X: Double; I: Integer; begin for I := 0 to aSize - 1 do begin Check(GEOSCoordSeq_getX(aSeq, i, @X) <> 0, 'GEOSCoordSeq_getX exeption'); Check(GEOSCoordSeq_getY(aSeq, i, @Y) <> 0, 'GEOSCoordSeq_getY exeption'); CheckEquals(aCoords[I].X, X, 'X not equals'); CheckEquals(aCoords[I].Y, Y, 'Y not equals'); end; end; procedure TGeosTest.CreateSeqChecked(var aSeq: PGEOSCoordSequence; aSize: Integer); begin aSeq := GEOSCoordSeq_create(aSize, 2); Check(Assigned(aSeq), 'ASeq = nil'); end; procedure TGeosTest.FillCoordSeq(aSeq: PGEOSCoordSequence; var aCoords: Vertex2DArray; aSize: Integer); var I: Integer; begin for I := 0 to aSize - 1 do begin Check(GEOSCoordSeq_setX(aSeq, I, aCoords[I].X) <> 0, 'GEOSCoordSeq_setX exception'); Check(GEOSCoordSeq_setY(aSeq, I, aCoords[I].Y) <> 0, 'GEOSCoordSeq_setY exception'); end; end; procedure TGeosTest.TestCoordSeqCreation; var cs: PGEOSCoordSequence; cs_size: Integer; begin cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); CheckSeqCoords(cs, coords, cs_size); GEOSCoordSeq_destroy(cs); //it doesn't make nil //Check(not Assigned(cs), 'cs <> nil'); end; procedure TGeosTest.TestLinearRingCreation; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; begin // closed sequence cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createLinearRing(cs); Check(Assigned(geom), 'Geom = nil'); // get const* CoordSeq cs := GEOSGeom_getCoordSeq(geom); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); // destroy with CoordSequence that belongs to geometry GEOSGeom_destroy(geom); end; procedure TGeosTest.TestUnclosedLinearRingCreationFail; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; begin // unclosed sequence cs_size := 3; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createLinearRing(cs); CheckFalse(Assigned(geom), 'Unclosed LinearRing created?!'); GEOSGeom_destroy(geom); end; procedure TGeosTest.TestLineStringCreation; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; begin cs_size := 3; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createLineString(cs); Check(Assigned(geom), 'Geom = nil'); cs := GEOSGeom_getCoordSeq(geom); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); GEOSGeom_destroy(geom); end; procedure TGeosTest.TestPointCreation; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; begin cs_size := 1; CreateSeqChecked(cs, cs_size); { TODO -oDVF: Если не заполнить, то тест срабатывает, когда координата точки 0,0 } FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createPoint(cs); Check(Assigned(geom), 'Geom = nil'); cs := GEOSGeom_getCoordSeq(geom); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); GEOSGeom_destroy(geom); end; procedure TGeosTest.TestPolygonCreationShellOnly; var cs: PGEOSCoordSequence; cs_size: Integer; shell, poly: PGEOSGeometry; begin // closed sequence cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); shell := GEOSGeom_createLinearRing(cs); Check(Assigned(shell), 'shell = nil'); // construct polygon with no holes poly := GEOSGeom_createPolygon(shell, nil, 0); Check(Assigned(poly), 'poly = nil'); shell := GEOSGetExteriorRing(poly); Check(Assigned(shell), 'shell = nil'); cs := GEOSGeom_getCoordSeq(shell); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); GEOSGeom_destroy(poly); end; procedure TGeosTest.TestPolygonCreationWithHoles; var cs: PGEOSCoordSequence; cs_size, holes_cnt: Integer; shell, poly, hole_ret: PGEOSGeometry; holes : PPGEOSGeometry; begin // closed sequence cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); shell := GEOSGeom_createLinearRing(cs); Check(Assigned(shell), 'shell = nil'); // holes - again closed sequences SetLength(holes, 2); // cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords0, cs_size); holes[0] := GEOSGeom_createLinearRing(cs); Check(Assigned(holes[0]), 'holes[0] = nil'); // cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords1, cs_size); holes[1] := GEOSGeom_createLinearRing(cs); Check(Assigned(holes[1]), 'holes[1] = nil'); // construct polygon with holes poly := GEOSGeom_createPolygon(shell, holes, 2); Check(Assigned(poly), 'poly = nil'); shell := GEOSGetExteriorRing(poly); Check(Assigned(shell), 'shell = nil'); cs := GEOSGeom_getCoordSeq(shell); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); holes_cnt := GEOSGetNumInteriorRings(poly); Check(holes_cnt <> -1, 'GEOSGetNumInteriorRings exeption'); Check(holes_cnt = 2, 'GEOSGetNumInteriorRings <> 2'); hole_ret := GEOSGetInteriorRingN(poly, 0); Check(Assigned(hole_ret), 'hole_ret0 = nil'); cs := GEOSGeom_getCoordSeq(hole_ret); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords0, cs_size); // hole_ret := GEOSGetInteriorRingN(poly, 1); Check(Assigned(hole_ret), 'hole_ret1 = nil'); cs := GEOSGeom_getCoordSeq(hole_ret); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords1, cs_size); GEOSGeom_destroy(poly); end; procedure TGeosTest.TestVersion; var ver: string; buf: PGEOSChar; begin buf := GEOSversion; ver := string(PAnsiChar(buf)); CheckEqualsString('3.4.2-CAPI-1.8.2 r3921', ver); { No need to free. GEOSFree(buf); } end; procedure TGeosTest.TestWKBReader; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; reader: PGEOSWKBReader; wkb: TBytes; size: Integer; begin cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); reader := GEOSWKBReader_create; Check(Assigned(reader), 'reader = nil'); size := Length(coordsWKBHex) div 2; wkb := xHexToBin(coordsWKBHex); geom := GEOSWKBReader_read(reader, PGEOSUChar(wkb), size); Check(Assigned(geom), 'Geom = nil'); cs := GEOSGeom_getCoordSeq(geom); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); GEOSGeom_destroy(geom); GEOSWKBReader_destroy(reader); end; procedure TGeosTest.TestWKBWriter; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; writer: PGEOSWKBWriter; wkb: TBytes; buf: PGEOSUChar; dim: Integer; i, size: Integer; begin cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createLineString(cs); Check(Assigned(geom), 'Geom = nil'); writer := GEOSWKBWriter_create; Check(Assigned(writer), 'writer = nil'); dim := GEOSWKBWriter_getOutputDimension(writer); Check(dim = 2, 'dim <> 2'); // expected wkb := xHexToBin(coordsWKBHex); // got buf := GEOSWKBWriter_write(writer, geom, @size); Check(Length(wkb) = size, 'Length(wkb) <> size'); for i := Low(wkb) to High(wkb) do Check(wkb[i] = PByte(buf)[i], 'wkb <> buf'); GEOSGeom_destroy(geom); GEOSWKBWriter_destroy(writer); GEOSFree(buf); end; procedure TGeosTest.TestWKTReader; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; reader: PGEOSWKTReader; wkt: PAnsiChar; begin cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); reader := GEOSWKTReader_create; Check(Assigned(reader), 'reader = nil'); wkt := PAnsiChar(AnsiString(coordsWKT)); geom := GEOSWKTReader_read(reader, PGEOSChar(wkt)); Check(Assigned(geom), 'Geom = nil'); cs := GEOSGeom_getCoordSeq(geom); Check(Assigned(cs), 'cs = nil'); CheckSeqCoords(cs, coords, cs_size); GEOSGeom_destroy(geom); GEOSWKTReader_destroy(reader); end; procedure TGeosTest.TestWKTWriter; var cs: PGEOSCoordSequence; cs_size: Integer; geom: PGEOSGeometry; writer: PGEOSWKTWriter; wkt: string; buf: PGEOSChar; dim: Integer; begin cs_size := 5; CreateSeqChecked(cs, cs_size); FillCoordSeq(cs, coords, cs_size); geom := GEOSGeom_createLineString(cs); Check(Assigned(geom), 'Geom = nil'); writer := GEOSWKTWriter_create; Check(Assigned(writer), 'writer = nil'); dim := GEOSWKTWriter_getOutputDimension(writer); Check(dim = 2, 'dim <> 2'); GEOSWKTWriter_setRoundingPrecision(writer, 0); buf := GEOSWKTWriter_write(writer, geom); wkt := string(AnsiString(PAnsiChar(buf))); Check(coordsWKT = wkt, 'coordsWKT <> wkt: ' + wkt); GEOSGeom_destroy(geom); GEOSWKTWriter_destroy(writer); GEOSFree(buf); end; initialization RegisterTest(TGeosTest.Suite); end.
unit Calculator.Core.SimpleCalc; interface type { TSimpleCalc } TSimpleCalc = class private FCurrentValue: Integer; public procedure Add(Value: Integer); procedure Divide(Value: Integer); procedure Multiply(Value: Integer); procedure Sub(Value: Integer); function Execute: Integer; end; implementation { TSimpleCalc } procedure TSimpleCalc.Add(Value: Integer); begin Inc(FCurrentValue, Value); end; procedure TSimpleCalc.Divide(Value: Integer); begin FCurrentValue := FCurrentValue div Value; end; function TSimpleCalc.Execute: Integer; begin Result := FCurrentValue; FCurrentValue := 0; end; procedure TSimpleCalc.Multiply(Value: Integer); begin FCurrentValue := FCurrentValue * Value; end; procedure TSimpleCalc.Sub(Value: Integer); begin Dec(FCurrentValue, Value); end; end.
unit PetrophisicsReports; interface uses SDReport, Classes; type TPetrophisicsReport = class(TSDSQLCollectionReport) protected procedure InternalOpenTemplate; override; procedure PreProcessQueryBlock(AQueryBlock: OleVariant); override; public procedure PrepareReport; override; constructor Create(AOwner: TComponent); override; end; TGranulometryReport = class(TSDSQLCollectionReport) protected procedure InternalOpenTemplate; override; procedure PreProcessQueryBlock(AQueryBlock: OleVariant); override; public procedure PrepareReport; override; constructor Create(AOwner: TComponent); override; end; TCentrifugingReport = class(TSDSQLCollectionReport) protected procedure InternalOpenTemplate; override; procedure PreProcessQueryBlock(AQueryBlock: OleVariant); override; public procedure PrepareReport; override; constructor Create(AOwner: TComponent); override; end; implementation uses SysUtils, CommonReport; { TPetrophisicsReport } constructor TPetrophisicsReport.Create(AOwner: TComponent); begin inherited; ReportQueryTemplate := 'select distinct 1, ds.vch_lab_number, s.vch_slotting_number||' + '''' + '/' + '''' + '||rs.vch_general_number, s.num_slotting_top, s.num_slotting_bottom, rs.num_from_slotting_top, ' + '(select first 1 skip 0 l.vch_rock_name from tbl_lithology_dict l where rs.rock_id = l.rock_id), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 144 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (115, 116) and dr.rock_sample_uin = ds.rock_sample_uin and ds.dnr_sample_type_id <> 2), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (115, 116) and dr.rock_sample_uin = ds.rock_sample_uin and ds.dnr_sample_type_id = 2), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 101 and dr.side_id in (0, 1) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 101 and dr.side_id in (2) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 101 and dr.side_id in (3) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 118 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (112, 113) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (114) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (141) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 131 and dr.side_id in (0, 1) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 131 and dr.side_id in (2) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 131 and dr.side_id in (3) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (142) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 132 and dr.side_id in (0, 1) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 132 and dr.side_id in (2) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 132 and dr.side_id in (3) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (133) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (134) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (143) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 102 and dr.side_id in (0, 1) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 102 and dr.side_id in (2) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 102 and dr.side_id in (3) and dr.rock_sample_uin = ds.rock_sample_uin), ' + 'ds.vch_dnr_comment_text ' + 'from tbl_slotting s, tbl_rock_sample rs, tbl_dnr_sample ds, tbl_dnr_research drs ' + 'where ds.rock_sample_uin = rs.rock_sample_uin ' + 'and rs.slotting_uin = s.slotting_uin ' + 'and drs.rock_sample_uin = ds.rock_sample_uin ' + 'and (drs.research_id >= 100 and drs.research_id < 200) ' + 'and s.well_uin in (%s) order by s.num_slotting_top, rs.num_from_slotting_top'; NeedsExcel := true; SilentMode := true; SaveReport := true; AutoNumber := [anColumns, anRows]; RemoveEmptyCols := true; DrawBorders := true; ReportName := 'Петрофизические_свойства' end; procedure TPetrophisicsReport.InternalOpenTemplate; begin inherited; FXLWorkBook := FExcel.Workbooks.add(ExtractFileDir(ParamStr(0))+'\Petrophisics.xltx'); FXLWorksheet := FExcel.ActiveWorkbook.ActiveSheet; end; procedure TPetrophisicsReport.PrepareReport; var cg: TColumnGroup; begin //FExcel.Visible := true; inherited; FirstColIndex := 1; LastColIndex := 31; AutonumberRow := 13; FirstRowIndex := 14; LastRowIndex := 14; Replacements.Clear; Replacements.AddReplacementRow(7, 1, '#skv#', ReportingObjects.List()); Replacements.AddReplacementColumn(7, 14, '<нет данных>', ''); Replacements.AddReplacementColumn(7, 14, ' ', ''); Replacements.AddReplacementColumn(11, 14, '-1', 'Н/П'); Replacements.AddReplacementColumn(12, 14, '-1', 'Н/П'); Replacements.AddReplacementColumn(13, 14, '-1', 'Н/П'); Replacements.AddReplacementColumn(6, 13, '-1', ''); cg := ColumnGroups.Add('Пористость'); cg.Add(8); cg.Add(9); cg.Add(10); cg := ColumnGroups.Add('Газопроницаемость'); cg.Add(11); cg.Add(12); cg.Add(13); cg := ColumnGroups.Add('Нефтенасыщенность'); cg.Add(14); cg := ColumnGroups.Add('Плотность'); cg.Add(15); cg.Add(16); cg := ColumnGroups.Add('УЭС'); cg.Add(17); cg.Add(18); cg.Add(19); cg.Add(20); cg := ColumnGroups.Add('Отнсопр'); cg.Add(21); cg.Add(22); cg.Add(23); cg.Add(24); cg := ColumnGroups.Add('Сопрводы'); cg.Add(25); cg.Add(26); cg := ColumnGroups.Add('Время'); cg.Add(27); cg.Add(28); cg.Add(29); cg := ColumnGroups.Add('Заголовок'); cg.Add(1); cg.Add(2); cg.Add(3); cg.Add(4); cg.Add(5); cg.Add(6); cg.Add(7); cg.Add(31); end; procedure TPetrophisicsReport.PreProcessQueryBlock( AQueryBlock: OleVariant); var Cell1, Cell2: OleVariant; begin inherited; FirstColIndex := 1; LastColIndex := 31; FirstRowIndex := 14; LastRowIndex := 14; Cell1 := FXLWorksheet.Cells.Item[LastRowIndex, FirstColIndex]; Cell2 := FXLWorksheet.Cells.Item[(LastRowIndex + AQueryBlock.RecordCount - 1)*2, FirstColIndex + AQueryBlock.Fields.Count - 1]; NextRange := FXLWorksheet.Range[Cell1,Cell2]; end; { TGranulometryReport } constructor TGranulometryReport.Create(AOwner: TComponent); begin inherited; ReportQueryTemplate := 'select distinct 1, ds.vch_lab_number, s.vch_slotting_number||' + '''' + '/' + '''' + '||rs.vch_general_number, ' + 's.num_slotting_top, s.num_slotting_bottom, rs.num_from_slotting_top, ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 301 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 1 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 2 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 3 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 4 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 5 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 6 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 7 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (302) and dr.value_type_id = 8 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id in (303) and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 l.vch_rock_name from tbl_lithology_dict l where rs.rock_id = l.rock_id) ' + 'from tbl_slotting s, tbl_rock_sample rs, tbl_dnr_sample ds, tbl_dnr_research drs ' + 'where ds.rock_sample_uin = rs.rock_sample_uin and rs.slotting_uin = s.slotting_uin ' + 'and drs.rock_sample_uin = ds.rock_sample_uin and (drs.research_id >= 300 and drs.research_id < 400) ' + 'and s.well_uin in (%s) order by s.num_slotting_top, rs.num_from_slotting_top'; NeedsExcel := true; SilentMode := true; SaveReport := true; AutoNumber := [anColumns, anRows]; RemoveEmptyCols := true; DrawBorders := true; ReportName := 'Гран_сост' end; procedure TGranulometryReport.InternalOpenTemplate; begin inherited; FXLWorkBook := FExcel.Workbooks.add(ExtractFileDir(ParamStr(0))+'\Granulometry.xltx'); FXLWorksheet := FExcel.ActiveWorkbook.ActiveSheet; end; procedure TGranulometryReport.PrepareReport; var cg: TColumnGroup; begin inherited; FirstColIndex := 1; LastColIndex := 17; FirstRowIndex := 13; LastRowIndex := 13; AutonumberRow := 12; Replacements.Clear; Replacements.AddReplacementRow(6, 1, '#skv#', ReportingObjects.List()); Replacements.AddReplacementColumn(17, 13, '<нет данных>', ''); Replacements.AddReplacementColumn(17, 13, ' ', ''); Replacements.AddReplacementColumn(6, 13, '-1', ''); cg := ColumnGroups.Add('Содержание частиц'); cg.AddRange(8, 16); cg := ColumnGroups.Add('Карбонатность'); cg.Add(7); end; procedure TGranulometryReport.PreProcessQueryBlock( AQueryBlock: OleVariant); var Cell1, Cell2: OleVariant; begin inherited; FirstColIndex := 1; LastColIndex := 17; FirstRowIndex := 13; LastRowIndex := 13; Cell1 := FXLWorksheet.Cells.Item[LastRowIndex, FirstColIndex]; Cell2 := FXLWorksheet.Cells.Item[(LastRowIndex + AQueryBlock.RecordCount - 1)*2, FirstColIndex + AQueryBlock.Fields.Count - 1]; NextRange := FXLWorksheet.Range[Cell1,Cell2]; end; { TCentrifugingReport } constructor TCentrifugingReport.Create(AOwner: TComponent); begin inherited; ReportQueryTemplate := 'select distinct 1, ds.vch_lab_number, s.vch_slotting_number||' + '''' + '/' + '''' + '||rs.vch_general_number, ' + 's.num_slotting_top, s.num_slotting_bottom, rs.num_from_slotting_top, ' + '(select first 1 skip 0 l.vch_rock_name from tbl_lithology_dict l where rs.rock_id = l.rock_id), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 2 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 2 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 2 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 3 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 3 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 3 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 4 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 4 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 4 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 5 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 5 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 5 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 6 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 6 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 6 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 7 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 7 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 7 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 203 and dr.value_type_id = 8 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 202 and dr.value_type_id = 8 and dr.rock_sample_uin = ds.rock_sample_uin), ' + '(select first 1 skip 0 dr.num_value from tbl_dnr_research dr where dr.research_id = 201 and dr.value_type_id = 8 and dr.rock_sample_uin = ds.rock_sample_uin) ' + 'from tbl_slotting s, tbl_rock_sample rs, tbl_dnr_sample ds, tbl_dnr_research drs ' + 'where ds.rock_sample_uin = rs.rock_sample_uin and rs.slotting_uin = s.slotting_uin ' + 'and drs.rock_sample_uin = ds.rock_sample_uin and (drs.research_id >= 200 and drs.research_id < 300) ' + 'and s.well_uin in (%s) order by s.num_slotting_top, rs.num_from_slotting_top'; NeedsExcel := true; SilentMode := true; SaveReport := true; AutoNumber := [anColumns, anRows]; RemoveEmptyCols := false; DrawBorders := true; ReportName := 'Центрифугирование_' end; procedure TCentrifugingReport.InternalOpenTemplate; begin inherited; FXLWorkBook := FExcel.Workbooks.add(ExtractFileDir(ParamStr(0))+'\Centrifuging.xltx'); FXLWorksheet := FExcel.ActiveWorkbook.ActiveSheet; end; procedure TCentrifugingReport.PrepareReport; begin inherited; FirstColIndex := 1; LastColIndex := 29; FirstRowIndex := 13; LastRowIndex := 13; AutonumberRow := 12; Replacements.Clear; Replacements.AddReplacementRow(7, 1, '#skv#', ReportingObjects.List()); Replacements.AddReplacementColumn(7, 13, '<нет данных>', ''); Replacements.AddReplacementColumn(7, 13, ' ', ''); Replacements.AddReplacementColumn(6, 13, '-1', ''); end; procedure TCentrifugingReport.PreProcessQueryBlock( AQueryBlock: OleVariant); var Cell1, Cell2: OleVariant; begin inherited; FirstColIndex := 1; LastColIndex := 29; FirstRowIndex := 13; LastRowIndex := 13; Cell1 := FXLWorksheet.Cells.Item[LastRowIndex, FirstColIndex]; Cell2 := FXLWorksheet.Cells.Item[(LastRowIndex + AQueryBlock.RecordCount - 1)*2, FirstColIndex + AQueryBlock.Fields.Count - 1]; NextRange := FXLWorksheet.Range[Cell1,Cell2]; end; end.
unit KSettings; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, AdvObjects; type { TSettingsAdapter } { MV 29/8/01 TSettingsAdapter allows you to interface into many different types of data stores for settings information. Internally they will be read as strings, the interface can be interacted with in native types (eg integers, date/times, etc). } ESettingsError = class(Exception); TSettingsAdapter = class(TAdvObject) Private Protected procedure ApplyTo(const ATarget: TSettingsAdapter); Virtual; Public procedure WriteFloat(const AName: String; const AValue: Double); Virtual; Abstract; procedure WriteBool(const AName: String; const AValue: Boolean); Virtual; Abstract; procedure WriteInteger(const AName: String; const AValue: Integer); Virtual; Abstract; procedure WriteString(const AName, AValue: String; ATransient: Boolean = False); Virtual; Abstract; procedure WriteEncryptedString(const AName, AValue: String; ATransient: Boolean = False); procedure WriteDateTime(const AName: String; AValue: TDateTime); Virtual; Abstract; procedure WriteObjProp(const AComponent: TComponent; APropPath: String; AAlias: String = ''); function ReadFloat(const AName: String; const ADefault: Double = 0): Double; Virtual; Abstract; function ReadBool(const AName: String; const ADefault: Boolean = False): Boolean; Virtual; Abstract; function ReadInteger(const AName: String; const ADefault: Integer = 0): Integer; Virtual; Abstract; function ReadString(const AName: String; const ADefault: String = ''): String; Virtual; Abstract; function ReadEncryptedString(const AName: String; const ADefault: String = ''): String; function ReadDateTime(const AName: String; const ADefault: TDateTime = 0): TDateTime; Virtual; Abstract; procedure ReadObjProp(const AComponent: TComponent; APropPath: String; AAlias: String = ''; ADefault: String = ''); procedure ApplyToObject(AComponent: TComponent); procedure Clear; Virtual; Abstract; function IsTransient(const AName: String): Boolean; Virtual; Abstract; function ValueExists(const AName: String): Boolean; Virtual; Abstract; procedure DeleteValue(const AName: String); Virtual; Abstract; // This procedure works the same as TPersistant, completly // overwrites old settings. // Calls Clear and Apply procedure Assign(const ASource: TSettingsAdapter); // similar to Assign but *shouldn't* completly nuke // old settings, should *add* to them. procedure Apply(const ASource: TSettingsAdapter); Virtual; end; { TCustomStringSettings } TCustomStringSettings = class(TSettingsAdapter) Protected function InternalRead(const AName: String; var AValue: String): Boolean; Virtual; Abstract; procedure InternalWrite(const AName, AValue: String; ATransient: Boolean = False); Virtual; Abstract; Public procedure WriteFloat(const AName: String; const AValue: Double); Override; procedure WriteBool(const AName: String; const AValue: Boolean); Override; procedure WriteInteger(const AName: String; const AValue: Integer); Override; procedure WriteString(const AName, AValue: String; ATransient: Boolean = False); Override; procedure WriteDateTime(const AName: String; AValue: TDateTime); Override; function ReadFloat(const AName: String; const ADefault: Double = 0): Double; Override; function ReadBool(const AName: String; const ADefault: Boolean = False): Boolean; Override; function ReadInteger(const AName: String; const ADefault: Integer = 0): Integer; Override; function ReadString(const AName: String; const ADefault: String = ''): String; Override; function ReadDateTime(const AName: String; const ADefault: TDateTime = 0): TDateTime; Override; end; { TStringSettings } TStringSettings = class(TCustomStringSettings) Private FStrings: TStringList; function GetStrings: TStrings; Protected function InternalRead(const AName: String; var VValue: String): Boolean; Override; procedure InternalWrite(const AName, AValue: String; ATransient: Boolean = False); Override; Public constructor Create(const ACopyFrom: TStrings = NIL); destructor Destroy; Override; procedure Clear; Override; function IsTransient(const AName: String): Boolean; Override; function ValueExists(const AName: String): Boolean; Override; procedure DeleteValue(const AName: String); Override; procedure ApplyTo(const ATarget: TSettingsAdapter); Override; property Strings: TStrings Read GetStrings; end; implementation uses TypInfo; { TSettingsAdapter } procedure TSettingsAdapter.Apply(const ASource: TSettingsAdapter); begin ASource.ApplyTo(self); end; function GetBeforeDot(var AString: String; var ABefore: String): Boolean; var LDotPos: Integer; begin Result := False; LDotPos := Pos('.', AString); if (LDotPos > 1) and (LDotPos < Length(AString)) then begin Result := True; ABefore := Copy(AString, 1, LDotPos - 1); AString := Copy(AString, LDotPos + 1, MAXINT); {eat up to and including the dot} end; end; const OK_PROP_TYPES = [tkInteger, tkChar, tkEnumeration, tkString, tkSet, tkClass]; function TraverseProperties(var AComponent: TPersistent; APath: String): PPropInfo; var LPropName: String; LPropComponent: TObject; LChildComp: TComponent; begin Result := NIL; if Pos('.', APath) > 1 then begin if GetBeforeDot(APath, LPropName) then begin Result := GetPropInfo(AComponent, LPropName, OK_PROP_TYPES); if Assigned(Result) and (Result^.PropType^.Kind = tkClass) and (APath > '') then begin {//it's an object, we need to look for sub properties.} LPropComponent := GetObjectProp(AComponent, Result); if LPropComponent is TPersistent then begin Result := TraverseProperties(TPersistent(LPropComponent), APath); if Assigned(Result) then AComponent := TPersistent(LPropComponent); end; end else { well, hmmm... maybe it's a owned component} if (AComponent is TComponent) then begin LChildComp := TComponent(AComponent).FindComponent(LPropName); if Assigned(LChildComp) then begin Result := TraverseProperties(TPersistent(LChildComp), APath); if Assigned(Result) then AComponent := LChildComp; end; end; end; end else Result := GetPropInfo(AComponent, APath, OK_PROP_TYPES); end; procedure TSettingsAdapter.ReadObjProp(const AComponent: TComponent; APropPath, AAlias, ADefault: String); var LPropInfo: PPropInfo; LValue: String; LSubComponent: TPersistent; begin LSubComponent := AComponent; if AAlias = '' then AAlias := APropPath; if ValueExists(AAlias) then begin LValue := ReadString(AAlias, ADefault); LPropInfo := TraverseProperties(LSubComponent, APropPath); try if Assigned(LPropInfo) then case LPropInfo^.PropType^.Kind of tkString: SetStrProp(LSubComponent, LPropInfo, LValue); tkInteger, tkChar: SetOrdProp(LSubComponent, LPropInfo, StrToIntDef(LValue, 0)); tkEnumeration: if LValue <> '' then SetEnumProp(LSubComponent, LPropInfo, LValue); tkSet: SetSetProp(LSubComponent, LPropInfo, LValue); end; except on E: EPropertyConvertError do;// I don't think we care, do we? end; end; end; procedure TSettingsAdapter.WriteObjProp(const AComponent: TComponent; APropPath: String; AAlias: String = ''); var LPropInfo: PPropInfo; LValue: String; LSubComponent: TPersistent; begin LSubComponent := AComponent; LPropInfo := TraverseProperties(LSubComponent, APropPath); if Assigned(LPropInfo) then case LPropInfo^.PropType^.Kind of tkString: LValue := GetStrProp(LSubComponent, LPropInfo); tkInteger, tkChar: LValue := IntToStr(GetOrdProp(LSubComponent, LPropInfo)); tkEnumeration: LValue := GetEnumProp(LSubComponent, LPropInfo); tkSet: LValue := GetSetProp(LSubComponent, LPropInfo); end; if AAlias <> '' then APropPath := AAlias; WriteString(APropPath, LValue); end; procedure TSettingsAdapter.ApplyToObject(AComponent: TComponent); var i: Integer; LName, LValue: String; LStringSettings: TStringSettings; begin LStringSettings := TStringSettings.Create; try // get a copy of the settings we can enumerate LStringSettings.Apply(self); for i := 0 to LStringSettings.Strings.Count - 1 do begin LName := LStringSettings.Strings.Names[i]; LValue := LStringSettings.Strings.Values[LName]; if (LName <> '') and (LName[1] <> ';') then //commented out line begin try ReadObjProp(AComponent, LName); except on E: EPropertyError do ShowException(E, ExceptAddr); on E: EPropertyConvertError do ShowException(E, ExceptAddr); else raise; end; end; end; finally LStringSettings.Free; end; end; procedure TSettingsAdapter.ApplyTo(const ATarget: TSettingsAdapter); begin raise ESettingsError.Create('Can''t assign/apply a ' + ClassName + ' to a ' + ATarget.ClassName); end; procedure TSettingsAdapter.Assign(const ASource: TSettingsAdapter); begin Clear; Apply(ASource); end; { TCustomStringSettings } // Date in format yyyy-mm-dd hh:nn:ss // eg 2001-08-29 11:29:00 // positions 12345678901234567890 // 1 2 const TIME_FORMAT = 'yyyy-mm-dd hh:nn:ss'; function DTStringToDateTime(const AString: String): TDateTime; var LYear, LMonth, LDay, LHour, LMinute, LSecond: Word; function ToInt(const AString: String; const ABitname: String): Word; var LCode: Integer; begin Val(AString, Result, LCode); if LCode > 0 then raise EConvertError.Create('Invalid value for ' + ABitname + ' reading setting'); end; begin if Length(AString) <> Length(TIME_FORMAT) then raise EConvertError.Create('Date time in invalid format reading setting'); LYear := ToInt(Copy(AString, 1, 4), 'Year'); LMonth := ToInt(Copy(AString, 6, 2), 'Month'); LDay := ToInt(Copy(AString, 9, 2), 'Day'); LHour := ToInt(Copy(AString, 12, 2), 'Hour'); LMinute := ToInt(Copy(AString, 15, 2), 'Minute'); LSecond := ToInt(Copy(AString, 18, 2), 'Second'); Result := EncodeTime(LHour, LMinute, LSecond, 0); // no milliseconds Result := Result + EncodeDate(LYear, LMonth, LDay); end; function DateTimeToDTString(const ADateTime: TDateTime): String; begin Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', ADateTime); end; function TCustomStringSettings.ReadBool(const AName: String; const ADefault: Boolean): Boolean; begin Result := ReadInteger(AName, Ord(ADefault)) <> 0; end; function TCustomStringSettings.ReadDateTime(const AName: String; const ADefault: TDateTime): TDateTime; var LDateTimeStr: String; begin Result := ADefault; if InternalRead(AName, LDateTimeStr) then begin try Result := DTStringToDateTime(LDateTimeStr); except on EConvertError do else raise; end; end; end; function TCustomStringSettings.ReadFloat(const AName: String; const ADefault: Double): Double; var LFloatStr: String; begin Result := ADefault; if InternalRead(AName, LFloatStr) and (LFloatStr <> '') then begin try Result := StrToFloat(LFloatStr); except on EConvertError do else raise; end; end; end; function TCustomStringSettings.ReadInteger(const AName: String; const ADefault: Integer): Integer; var LIntStr: String; begin Result := ADefault; if InternalRead(AName, LIntStr) then begin if (Length(LIntStr) > 2) and (LIntStr[1] = '0') and ((LIntStr[2] = 'X') or (LIntStr[2] = 'x')) then LIntStr := '$' + Copy(LIntStr, 3, Maxint); Result := StrToIntDef(LIntStr, ADefault); end; end; function TCustomStringSettings.ReadString(const AName, ADefault: String): String; begin Result := ADefault; InternalRead(AName, Result); end; procedure TCustomStringSettings.WriteBool(const AName: String; const AValue: Boolean); const LValues: array[Boolean] of String = ('0', '1'); begin InternalWrite(AName, LValues[AValue]); end; procedure TCustomStringSettings.WriteDateTime(const AName: String; AValue: TDateTime); begin InternalWrite(AName, DateTimeToDTString(AValue)); end; procedure TCustomStringSettings.WriteFloat(const AName: String; const AValue: Double); begin InternalWrite(AName, FloatToStr(AValue)); end; procedure TCustomStringSettings.WriteInteger(const AName: String; const AValue: Integer); begin InternalWrite(AName, IntToStr(AValue)); end; procedure TCustomStringSettings.WriteString(const AName, AValue: String; ATransient: Boolean = False); begin InternalWrite(AName, AValue, ATransient); end; {$R-} const Base64Table: array[0..63] of Char = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'); procedure BuildBase64(var OutBuf: array of Char; Index: Longint; Significant: Integer; Value: Longint); var i: Integer; begin for i := 3 downto Significant do begin OutBuf[Index +i] := '='; Value := Value shr 6; end; for i := Significant - 1 downto 0 do begin OutBuf[Index +i] := Base64Table[Value and 63]; Value := Value shr 6; end; end; function Base64ToBinary(var InBuf, OutBuf: array of Char; InLen: Longint): Longint; { This routine converts a Base64 encoded stream back to the original binary stream. No real error checking is done except to ignore unexpected data. For example, only valid Base64 ascii characters are acted upon and Pad characters are ignored unless they are the last or next-to-last characters in the input buffer. Futhermore, any partially decoded data is ignored if the input stream is too short to contain 4 Base64 characters. } var Value, InNdx, OutNdx: Longint; Count, Pad: Integer; begin Value := 0; Count := 0; Pad := 0; OutNdx := 0; for InNdx := 0 to InLen - 1 do begin begin case InBuf[InNdx] of 'A'..'Z': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('A')); Inc(Count); end; 'a'..'z': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('a')) + Longint(26); Inc(Count); end; '0'..'9': begin Value := (Value shl 6) + Longint(Ord(InBuf[InNdx])) - Longint(Ord('0')) + Longint(52); Inc(Count); end; '+': begin Value := (Value shl 6) + 62; Inc(Count); end; '/': begin Value := (Value shl 6) + 63; Inc(Count); end; '=': begin if InNdx >= InLen - 2 then begin Value := (Value shl 6); Inc(Count); Inc(Pad); end; end; end; end; { If we have decoded 4 characters then we need to build the output buffer. If any pad characters were detected then we adjust the values first to ensure we only generate as many output bytes as there originally were. } if Count = 4 then begin Count := 3; if Pad = 1 then begin {Only 16 bits were originally encoded } Value := Value shr 8; Count := 2; end else if Pad = 2 then begin {Only 8 bits were originally encoded } Value := Value shr 16; Count := 1; end; for Pad := Count - 1 downto 0 do begin OutBuf[OutNdx + Pad] := Chr(Value and 255); Value := Value shr 8; end; Inc(OutNdx, Count); Count := 0; Pad := 0; Value := 0; end; end; Result := OutNdx; end; function BinaryToBase64(var InBuf, OutBuf: array of Char; InLen: Longint): Longint; var InNdx, OutNdx, Width: Longint; begin InNdx := 0; OutNdx := 0; Width := 0; while InNdx + 3 <= InLen do begin BuildBase64(OutBuf, OutNdx, 4, (Longint(Ord(InBuf[InNdx])) shl 16) + (Longint(Ord(InBuf[InNdx + 1])) shl 8) + Longint(Ord(InBuf[InNdx + 2]))); inc(OutNdx, 4); inc(Width, 4); if Width = 60 then begin OutBuf[OutNdx + 0] := #13; OutBuf[OutNdx + 1] := #10; Width := 0; inc(OutNdx, 2); end; InNdx := InNdx + 3; end; if InLen - InNdx = 2 then begin BuildBase64(OutBuf, OutNdx, 3, (Longint(Ord(InBuf[InNdx])) shl 16) + (Longint(Ord(InBuf[InNdx + 1])) shl 8)); OutNdx := OutNdx + 4; end else if InLen - InNdx = 1 then begin BuildBase64(OutBuf, OutNdx, 2, Longint(Ord(InBuf[InNdx])) shl 16); OutNdx := OutNdx + 4; end; Result := OutNdx; end; {$R+} function StripEoln(const AStr: String): String; var i: Integer; begin i := Length(AStr); while (i > 0) and ((AStr[i] = #13) or (AStr[i] = #10) or (AStr[i] = ' ')) do Dec(i); Result := Copy(AStr, 1, i); end; function Base64ToBin(AStr: String): String; var LIn, LOut: PChar; LLen: Longint; begin if AStr = '' then begin Result := ''; exit; end; AStr := StripEoln(AStr); GetMem(LIn, Length(AStr)); try GetMem(LOut, length(AStr)); try Move(AStr[1], LIn^, length(AStr)); LLen := Base64ToBinary(LIn^, LOut^, Length(AStr)); Result := ''; if LLen = 0 then exit; SetLength(Result, LLen); Move(LOut^, Result[1], LLen); finally FreeMem(LOut); end; finally FreeMem(LIn); end; end; function BinToBase64(AStr: String): String; var LIn, LOut: PChar; LRLen, LMLen: Longint; k: Integer; begin k := length(AStr); if AStr = '' then begin Result := ''; exit; end; GetMem(LIn, (k + 1)); try Move(AStr[1], LIn^, Length(AStr)); LMLen := Length(AStr) * 2; if LMLen < 4 then LMLen := 4; GetMem(LOut, LMLen); try LRLen := BinaryToBase64(LIn^, LOut^, Length(AStr)); Result := ''; if LRLen = 0 then exit; SetLength(Result, LRLen); Move(LOut^, Result[1], LRLen); finally FreeMem(LOut); end; finally FreeMem(LIn); end; end; const C1 = 52845; C2 = 22719; function GetCryptKey(const AStr: String): Word; var i: Integer; begin {$R-} Result := 1; for i := 1 to Length(AStr) do Result := Result * i * Ord(AStr[i]); {$R+} end; {$R-} {$Q-} function strEncrypt(const AStr: String; AKey: Word): String; var i: Integer; begin Result := ''; setlength(Result, Length(AStr)); for i := 1 to Length(AStr) do begin Result[i] := Char(Ord(AStr[i]) xor (AKey shr 8)); AKey := (Ord(Result[i]) + AKey) * C1 + C2; end; Result := BinTobase64(Result); end; function strDecrypt(const AStr: String; AKey: Word): String; var i: Integer; LStr: String; begin Result := ''; LStr := base64toBin(AStr); setlength(Result, length(LStr)); for i := 1 to Length(LStr) do begin Result[i] := Char(Ord(LStr[i]) xor (AKey shr 8)); AKey := (Ord(LStr[i]) + AKey) * C1 + C2; end; end; {$R+} {$Q+} function TSettingsAdapter.ReadEncryptedString(const AName: String; const ADefault: String): String; begin Result := ReadString(AName); if Result <> '' then begin if not SameText(ReadString(AName + '_Encrypted'), 'no') then begin Result := strDecrypt(Result, 19278); end; end; end; procedure TSettingsAdapter.WriteEncryptedString(const AName, AValue: String; ATransient: Boolean); begin WriteString(AName, strEncrypt(AValue, 19278), ATransient); end; { TStringSettings } procedure TStringSettings.ApplyTo(const ATarget: TSettingsAdapter); var LPos, i: Integer; LLine, LName, LValue: String; LTransient: Boolean; begin for i := 0 to FStrings.Count - 1 do begin LLine := FStrings[i]; LPos := Pos('=', LLine); LName := Copy(LLine, 1, LPos - 1); LValue := Copy(LLine, LPos + 1, MaxInt); LTransient := Boolean(FStrings.Objects[i]); ATarget.WriteString(LName, LValue, LTransient); end; end; procedure TStringSettings.Clear; begin FStrings.Clear; end; constructor TStringSettings.Create(const ACopyFrom: TStrings = NIL); begin inherited Create; FStrings := TStringList.Create; if Assigned(ACopyFrom) then FStrings.Assign(ACopyFrom); end; procedure TStringSettings.DeleteValue(const AName: String); var LIndex: Integer; begin LIndex := FStrings.IndexOfName(AName); if LIndex > -1 then FStrings.Delete(LIndex); end; destructor TStringSettings.Destroy; begin FreeAndNil(FStrings); inherited; end; function TStringSettings.GetStrings: TStrings; begin Result := FStrings; end; function TStringSettings.InternalRead(const AName: String; var VValue: String): Boolean; var LIndex: Integer; begin Result := False; LIndex := FStrings.IndexOfName(AName); if LIndex >= 0 then begin Result := True; VValue := Copy(FStrings.Strings[LIndex], Length(AName) + 2, MaxInt); //copied from TStrings.GetValue end; end; procedure TStringSettings.InternalWrite(const AName, AValue: String; ATransient: Boolean = False); var LIndex: Integer; begin // copied from TStrings.SetValue (with a few mods) LIndex := FStrings.IndexOfName(AName); if LIndex < 0 then LIndex := FStrings.Add(''); FStrings.Strings[LIndex] := AName + '=' + AValue; FStrings.Objects[LIndex] := pointer(ATransient); //yuk, really needs a wrapper class end; function TStringSettings.IsTransient(const AName: String): Boolean; var LIndex: Integer; begin Result := False; LIndex := FStrings.IndexOfName(AName); if LIndex > -1 then Result := Boolean(FStrings.Objects[LIndex]); //yuk, really needs a wrapper class end; function TStringSettings.ValueExists(const AName: String): Boolean; begin Result := FStrings.IndexOfName(AName) <> -1; end; end.
{********************************************************} { } { Zeos Database Objects } { SQL Fields and Indices Collections } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZSqlItems; interface uses DB, ZList, ZSqlTypes; {$INCLUDE ../Zeos.inc} type { Index key's types } TKeyType = (ktNone, ktIndex, ktUnique, ktPrimary); { Sorting type } TSortType = (stNone, stAscending, stDescending); { Autoupdated field's types } TAutoType = (atNone, atAutoInc, atTimestamp, atIdentity, atGenerated); { Field name string } TFieldName = string[MAX_NAME_LENGTH]; { Sql field description structure } TFieldDesc = packed record { General info } Table: TFieldName; // Table name Field: TFieldName; // Field name Alias: TFieldName; // Query column name TypeName: ShortString; // Column type name Index: Integer; // Index in the query (reserved) Length: Integer; // Field length Decimals: Integer; // Decimal scale AutoType: TAutoType; // Auto update type IsNull: Boolean; // Is field null Default: ShortString; // Field default value BlobType: TBlobType; // Blob type ReadOnly: Boolean; // Is field ReadOnly { Local Info } FieldObj: TField; // Linked field DataSize: Integer; // Field content size Offset: Integer; // Field content offset BlobNo: Integer; // Blob content index { Optimize Info } FieldType: TFieldType; // Field type FieldNo: Integer; // Field index in query end; PFieldDesc = ^TFieldDesc; { Fields collection of SQL query } TSqlFields = class(TZItemList) private function GetItem(Index: Integer): PFieldDesc; public constructor Create; function Add(Table, Field, Alias, TypeName: string; FieldType: TFieldType; Length, Decimals: Integer; AutoType: TAutoType; IsNull, ReadOnly: Boolean; Default: string; BlobType: TBlobType): PFieldDesc; function AddDesc(FieldDesc: PFieldDesc): PFieldDesc; function AddField(Field: TField): PFieldDesc; function FindByName(Table, Field: string): PFieldDesc; function FindByAlias(Alias: string): PFieldDesc; function FindByField(Field: TField): PFieldDesc; property Items[Index: Integer]: PFieldDesc read GetItem; default; end; { Internal fields processing class } TIndexDesc = packed record Table: TFieldName; // Table name Name: TFieldName; // Index name Fields: array[0..MAX_INDEX_FIELDS-1] of TFieldName; // Fields list FieldCount: Integer; // Fields count KeyType: TKeyType; // Key mode SortType: TSortType; // Sorting mode end; PIndexDesc = ^TIndexDesc; { Buffer records class } TSqlIndices = class(TZItemList) private function GetItem(Index: Integer): PIndexDesc; public constructor Create; procedure AddIndex(Name, Table, Fields: string; KeyType: TKeyType; SortType: TSortType); function FindByField(Table, Field: string): PIndexDesc; function FindByName(Name: string): PIndexDesc; property Items[Index: Integer]: PIndexDesc read GetItem; default; end; implementation uses SysUtils, ZToken, ZExtra; {*************** TSqlFields class implementation **************} { Class constructor } constructor TSqlFields.Create; begin inherited Create(SizeOf(TFieldDesc)); end; { Get field item } function TSqlFields.GetItem(Index: Integer): PFieldDesc; begin if (Index < 0) or (Index >= Count) then Error('List Index Error at %d', Index); Result := PFieldDesc(List^[Index]); end; { Add new field description } function TSqlFields.Add(Table, Field, Alias, TypeName: string; FieldType: TFieldType; Length, Decimals: Integer; AutoType: TAutoType; IsNull, ReadOnly: Boolean; Default: string; BlobType: TBlobType): PFieldDesc; begin Result := inherited Add; Result.Table := Table; Result.Field := Field; Result.Alias := Alias; Result.TypeName := TypeName; Result.FieldType := FieldType; Result.Length := Length; Result.Decimals := Decimals; Result.AutoType := AutoType; Result.IsNull := IsNull; Result.ReadOnly := ReadOnly; if Result.AutoType = atNone then Result.Default := Default else Result.Default := ''; Result.BlobType := BlobType; Result.FieldObj := nil; end; { Add new field description with another description } function TSqlFields.AddDesc(FieldDesc: PFieldDesc): PFieldDesc; begin with FieldDesc^ do Result := Add(Table, Field, Alias, TypeName, FieldType, Length, Decimals, AutoType, IsNull, ReadOnly, Default, BlobType); end; { Add new field description with Field Object } function TSqlFields.AddField(Field: TField): PFieldDesc; begin Result := inherited Add; Result.Table := ''; Result.Field := ''; Result.Alias := Field.FieldName; Result.TypeName := ''; Result.FieldType := Field.DataType; Result.Length := Field.Size; Result.Decimals := 0; Result.AutoType := atNone; Result.IsNull := not Field.Required; Result.ReadOnly := Field.ReadOnly; Result.Default := ''; Result.BlobType := btInternal; Result.FieldObj := Field; end; { Find field desc by table and field name } function TSqlFields.FindByName(Table, Field: string): PFieldDesc; var I: Integer; begin Result := nil; for I := 0 to Count-1 do if ((Table = '') or StrCaseCmp(Items[I].Table, Table)) and StrCaseCmp(Items[I].Field, Field) then begin Result := Items[I]; Exit; end; end; { Find field desc by field alias } function TSqlFields.FindByAlias(Alias: string): PFieldDesc; var I: Integer; begin Result := nil; Alias := UpperCase(Alias); for I := 0 to Count-1 do if StrCaseCmp(Items[I].Alias, Alias) then begin Result := Items[I]; Exit; end; end; { Find field desc by TField } function TSqlFields.FindByField(Field: TField): PFieldDesc; var I: Integer; begin Result := nil; for I := 0 to Count-1 do if Items[I].FieldObj = Field then begin Result := Items[I]; Exit; end; end; {************* TSqlIndices class implementation ***********} { Class constructor } constructor TSqlIndices.Create; begin inherited Create(SizeOf(TIndexDesc)); end; { Get index item } function TSqlIndices.GetItem(Index: Integer): PIndexDesc; begin if (Index < 0) or (Index >= Count) then Error('List Index Error at %d', Index); Result := PIndexDesc(List^[Index]); end; { Add new index } procedure TSqlIndices.AddIndex(Name, Table, Fields: string; KeyType: TKeyType; SortType: TSortType); var Item: PIndexDesc; Token: string; begin Item := FindByName(Name); if not Assigned(Item) then Item := PIndexDesc(Add); Item.Name := Name; Item.Table := Table; Item.KeyType := KeyType; Item.SortType := SortType; while Fields <> '' do begin Token := Trim(StrTokEx(Fields,';,')); DeleteQuotes(Token); if (Token <> '') and (Item.FieldCount < MAX_INDEX_FIELDS) then begin Item.Fields[Item.FieldCount] := Token; Item.FieldCount := Item.FieldCount + 1; end; end; end; { Find index by field } function TSqlIndices.FindByField(Table, Field: string): PIndexDesc; var I, J: Integer; MaxKey: TKeyType; begin MaxKey := ktNone; Result := nil; for I := 0 to Count-1 do begin if StrCaseCmp(Items[I].Table, Table) then with Items[I]^ do for J := 0 to FieldCount - 1 do if StrCaseCmp(Fields[J], Field) and (MaxKey < KeyType) then begin Result := Items[I]; MaxKey := KeyType; end; if MaxKey = ktPrimary then Exit; end; end; { Find index by name } function TSqlIndices.FindByName(Name: string): PIndexDesc; var I: Integer; begin Result := nil; for I := 0 to Count-1 do begin if StrCaseCmp(Items[I].Name, Name) then begin Result := Items[I]; Exit; end; end; end; end.
unit QuaternionTimingTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, BaseTimingTest, native, BZVectorMath, BZProfiler; type { TQuaternionTimingTest } TQuaternionTimingTest = class(TVectorBaseTimingTest) protected procedure Setup; override; public {$CODEALIGN RECORDMIN=16} nqt1, nqt2,nqt3 : TNativeBZQuaternion; aqt1,aqt2,aqt3 : TBZQuaternion; {$CODEALIGN RECORDMIN=4} published procedure TestCreateSingles; procedure TestCreateImagArrayWithReal; procedure TestCreateTwoUnitAffine; procedure TestCreateTwoUnitHmg; procedure TestCreateAngleAxis; procedure TestCreateEuler; procedure TestCreateEulerOrder; procedure TestMulQuaternion; procedure TestConjugate; procedure TestOpEquals; procedure TestOpNotEquals; procedure TestMagnitude; procedure TestNormalize; procedure TestMultiplyAsSecond; procedure TestSlerpSingle; procedure TestSlerpSpin; procedure TestConvertToMatrix; procedure TestCreateMatrix; procedure TestTransform; procedure TestScale; end; implementation { TQuaternionTimingTest } procedure TQuaternionTimingTest.Setup; begin inherited Setup; Group := rgQuaterion; nqt1.Create(5.850,-15.480,8.512,1.5); nqt2.Create(1.558,6.512,4.525,1.0); aqt1.V := nqt1.V; aqt2.V := nqt2.V; end; procedure TQuaternionTimingTest.TestCreateSingles; begin TestDispName := 'Quaternion Create Singles'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt1.Create(1,2,3,4); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt1.Create(1,2,3,4); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateImagArrayWithReal; var arr: array [0..2] of Single; begin arr := aqt2.ImagePart.V; TestDispName := 'Quaternion Create Array'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt1.Create(arr,4); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt1.Create(arr,4); end; GlobalProfiler[1].Stop; end; // have to be bit more careful with values for quats procedure TQuaternionTimingTest.TestCreateTwoUnitAffine; begin vt1.create(1,0,0,0); vt2.create(0,1,0,0); // positive 90deg on equator nt1.V := vt1.V; nt2.V := vt2.V; TestDispName := 'Quaternion Create TwoUnitAffine'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nqt1.Create(nt1.AsVector3f, nt2.AsVector3f); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsQuarter do begin aqt1.Create(vt1.AsVector3f, vt2.AsVector3f); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateTwoUnitHmg; begin vt1.create(1,0,0,0); vt2.create(0,1,0,0); // positive 90deg on equator nt1.V := vt1.V; nt2.V := vt2.V; TestDispName := 'Quaternion Create TwoUnitHmg'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nqt1.Create(nt1, nt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsQuarter do begin aqt1.Create(vt1, vt2); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateAngleAxis; begin TestDispName := 'Quaternion Create AngleAxis'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nqt1.Create(90, NativeZVector); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsQuarter do begin aqt1.Create(90, ZVector); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateEuler; begin TestDispName := 'Quaternion Create Euler'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsTenth do begin nqt1.Create(12,36,24); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsTenth do begin aqt1.Create(12,36,24); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateEulerOrder; begin TestDispName := 'Quaternion Create Euler Order'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsTenth do begin nqt1.Create(12,36,24, eulZXY); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsTenth do begin aqt1.Create(12,36,24, eulZXY); end; GlobalProfiler[1].Stop; end; {%region%====[ TQuaternionTimingTest ]============================================} procedure TQuaternionTimingTest.TestMulQuaternion; begin TestDispName := 'Quaternion Multiply Quaternion'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt3 := nqt1 * nqt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt3 := aqt1 * aqt2; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestConjugate; begin TestDispName := 'Quaternion Conjugate'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt3 := nqt1.Conjugate; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt3 := aqt1.Conjugate; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestOpEquals; begin TestDispName := 'Quaternion Op Equals'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nb := nqt1 = nqt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin nb := aqt1 = aqt2; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestOpNotEquals; begin TestDispName := 'Quaternion Op Not Equals'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nb := nqt1 <> nqt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin nb := aqt1 <> aqt2; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestMagnitude; begin TestDispName := 'Quaternion Magnitude'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin Fs1 := nqt1.Magnitude; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin Fs2 := aqt1.Magnitude; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestNormalize; begin TestDispName := 'Quaternion Normalize'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt1.Normalize; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt1.Normalize; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestMultiplyAsSecond; begin TestDispName := 'Quaternion Multiply As Second'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt3 := nqt1.MultiplyAsSecond(nqt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt3 := aqt1.MultiplyAsSecond(aqt2); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestSlerpSingle; begin nqt1.AsVector4f := NativeWHmgVector; aqt1.AsVector4f := WHmgVector; // null rotation as start point. nqt2.Create(90,NativeZVector); aqt2.Create(90,ZVector); TestDispName := 'Quaternion Slerp Single'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsTenth do begin nqt3 := nqt1.Slerp(nqt2, 0.5); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsTenth do begin aqt3 := aqt1.Slerp(aqt2, 0.5); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestSlerpSpin; begin nqt1.AsVector4f := NativeWHmgVector; aqt1.AsVector4f := WHmgVector; // null rotation as start point. nqt2.Create(90,NativeZVector); aqt2.Create(90,ZVector); TestDispName := 'Quaternion Slerp Spin'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsTenth do begin nqt3 := nqt1.Slerp(nqt2, 2, 0.5); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsTenth do begin aqt3 := aqt1.Slerp(aqt2, 2, 0.5); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestConvertToMatrix; var nMat{%H-}: TNativeBZMatrix; aMat{%H-}: TBZMatrix; begin nqt2.Create(90,NativeZVector); aqt2.Create(90,ZVector); TestDispName := 'Quaternion To Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nMat := nqt2.ConvertToMatrix; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aMat := aqt1.ConvertToMatrix; end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestCreateMatrix; var nMat: TNativeBZMatrix; aMat: TBZMatrix; begin nqt2.Create(90,NativeZVector); aqt2.Create(90,ZVector); nMat := nqt2.ConvertToMatrix; aMat := aqt1.ConvertToMatrix; TestDispName := 'Quaternion From Matrix'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt1.Create(nMat); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt1.Create(aMat); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestTransform; begin nqt1.Create(90,NativeZVector); aqt1.Create(90,ZVector); TestDispName := 'Quaternion Transform Vector'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nt1 := nqt1.Transform(nt1); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to IterationsQuarter do begin vt1 := aqt1.Transform(vt1); end; GlobalProfiler[1].Stop; end; procedure TQuaternionTimingTest.TestScale; begin nqt1.Create(90,NativeZVector); aqt1.Create(90,ZVector); TestDispName := 'Quaternion Scale'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nqt1.Scale(2.0); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt := 1 to Iterations do begin aqt1.Scale(2.0); end; GlobalProfiler[1].Stop; end; {%endregion%} initialization RegisterTest(REPORT_GROUP_QUATERION, TQuaternionTimingTest); end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [FOLHA_PPP] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit FolhaPppController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, Generics.Collections, FolhaPppVO; type TFolhaPppController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TFolhaPppVO>; class function ConsultaObjeto(pFiltro: String): TFolhaPppVO; class procedure Insere(pObjeto: TFolhaPppVO); class function Altera(pObjeto: TFolhaPppVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses UDataModule, T2TiORM, FolhaPppCatVO, FolhaPppAtividadeVO, FolhaPppFatorRiscoVO, FolhaPppExameMedicoVO; class procedure TFolhaPppController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TFolhaPppVO>; begin try Retorno := TT2TiORM.Consultar<TFolhaPppVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TFolhaPppVO>(Retorno); finally end; end; class function TFolhaPppController.ConsultaLista(pFiltro: String): TObjectList<TFolhaPppVO>; begin try Result := TT2TiORM.Consultar<TFolhaPppVO>(pFiltro, '-1', True); finally end; end; class function TFolhaPppController.ConsultaObjeto(pFiltro: String): TFolhaPppVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TFolhaPppVO>(pFiltro, True); finally end; end; class procedure TFolhaPppController.Insere(pObjeto: TFolhaPppVO); var UltimoID: Integer; FolhaPppCatEnumerator: TEnumerator<TFolhaPppCatVO>; FolhaPppAtividadeEnumerator: TEnumerator<TFolhaPppAtividadeVO>; FolhaPppFatorRiscoEnumerator: TEnumerator<TFolhaPppFatorRiscoVO>; FolhaPppExameMedicoEnumerator: TEnumerator<TFolhaPppExameMedicoVO>; begin try UltimoID := TT2TiORM.Inserir(pObjeto); // CAT FolhaPppCatEnumerator := pObjeto.ListaFolhaPppCatVO.GetEnumerator; try with FolhaPppCatEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppCatEnumerator); end; // Atividade FolhaPppAtividadeEnumerator := pObjeto.ListaFolhaPppAtividadeVO.GetEnumerator; try with FolhaPppAtividadeEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppAtividadeEnumerator); end; // Fator Risco FolhaPppFatorRiscoEnumerator := pObjeto.ListaFolhaPppFatorRiscoVO.GetEnumerator; try with FolhaPppFatorRiscoEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppFatorRiscoEnumerator); end; // Exame Médico FolhaPppExameMedicoEnumerator := pObjeto.ListaFolhaPppExameMedicoVO.GetEnumerator; try with FolhaPppExameMedicoEnumerator do begin while MoveNext do begin Current.IdFolhaPpp := UltimoID; TT2TiORM.Inserir(Current); end; end; finally FreeAndNil(FolhaPppExameMedicoEnumerator); end; Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TFolhaPppController.Altera(pObjeto: TFolhaPppVO): Boolean; var FolhaPppCatEnumerator: TEnumerator<TFolhaPppCatVO>; FolhaPppAtividadeEnumerator: TEnumerator<TFolhaPppAtividadeVO>; FolhaPppFatorRiscoEnumerator: TEnumerator<TFolhaPppFatorRiscoVO>; FolhaPppExameMedicoEnumerator: TEnumerator<TFolhaPppExameMedicoVO>; begin try Result := TT2TiORM.Alterar(pObjeto); // CAT try FolhaPppCatEnumerator := pObjeto.ListaFolhaPppCatVO.GetEnumerator; with FolhaPppCatEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppCatEnumerator); end; // Atividade try FolhaPppAtividadeEnumerator := pObjeto.ListaFolhaPppAtividadeVO.GetEnumerator; with FolhaPppAtividadeEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppAtividadeEnumerator); end; // Fator Risco try FolhaPppFatorRiscoEnumerator := pObjeto.ListaFolhaPppFatorRiscoVO.GetEnumerator; with FolhaPppFatorRiscoEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppFatorRiscoEnumerator); end; // Exame Médico try FolhaPppExameMedicoEnumerator := pObjeto.ListaFolhaPppExameMedicoVO.GetEnumerator; with FolhaPppExameMedicoEnumerator do begin while MoveNext do begin if Current.Id > 0 then Result := TT2TiORM.Alterar(Current) else begin Current.IdFolhaPpp := pObjeto.Id; Result := TT2TiORM.Inserir(Current) > 0; end; end; end; finally FreeAndNil(FolhaPppExameMedicoEnumerator); end; finally end; end; class function TFolhaPppController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TFolhaPppVO; begin try ObjetoLocal := TFolhaPppVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); TratarRetorno(Result); finally FreeAndNil(ObjetoLocal) end; end; class function TFolhaPppController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TFolhaPppController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TFolhaPppController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TFolhaPppVO>(TObjectList<TFolhaPppVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TFolhaPppController); finalization Classes.UnRegisterClass(TFolhaPppController); 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.types.nullable; interface uses Generics.Defaults, SysUtils, Variants, Rtti; type Nullable<T> = record private FValue: T; FHasValue: string; function GetValue: T; function GetHasValue: Boolean; procedure Clear; class function VarIsNullOrEmpty(const Value: Variant): Boolean; static; public constructor Create(const Value: T); overload; constructor Create(const Value: Variant); overload; function GetValueOrDefault: T; overload; function GetValueOrDefault(const defaultValue: T): T; overload; function Equals(const other: Nullable<T>): Boolean; function ToString: String; function ToVariant: Variant; property HasValue: Boolean read GetHasValue; property Value: T read GetValue; { Operator Overloads } class operator Implicit(const Value: Nullable<T>): T; class operator Implicit(const Value: T): Nullable<T>; class operator Implicit(const Value: Nullable<T>): Variant; class operator Implicit(const Value: Variant): Nullable<T>; class operator Implicit(Value: Pointer): Nullable<T>; class operator Explicit(const Value: Nullable<T>): T; class operator Equal(const a, b: Nullable<T>) : Boolean; class operator NotEqual(const a, b: Nullable<T>) : Boolean; end; NullString = Nullable<string>; NullBoolean = Nullable<Boolean>; NullInteger = Nullable<Integer>; NullInt64 = Nullable<Int64>; NullDouble = Nullable<Double>; NullCurrency = Nullable<Currency>; NullDate = Nullable<TDate>; NullTime = Nullable<TTime>; NullDateTime = Nullable<TDateTime>; implementation const CHasValueFlag = '@'; constructor Nullable<T>.Create(const Value: T); begin FValue := Value; FHasValue := CHasValueFlag; end; constructor Nullable<T>.Create(const Value: Variant); var LValue: TValue; begin if not VarIsNullOrEmpty(Value) then begin LValue := TValue.FromVariant(Value); FValue := LValue.AsType<T>; FHasValue := CHasValueFlag; end else Clear; end; procedure Nullable<T>.Clear; begin FHasValue := ''; FValue := Default(T); end; class function Nullable<T>.VarIsNullOrEmpty(const Value: Variant): Boolean; begin Result := VarIsNull(Value) or VarIsEmpty(Value); end; function Nullable<T>.GetHasValue: Boolean; begin Result := FHasValue <> ''; end; function Nullable<T>.GetValue: T; begin // if not HasValue then // raise Exception.Create('Invalid operation, Nullable type has no value.'); Result := FValue; end; function Nullable<T>.GetValueOrDefault: T; begin if HasValue then Result := Value else Result := Default(T); end; function Nullable<T>.GetValueOrDefault(const defaultValue: T): T; begin if HasValue then Result := Value else Result := defaultValue; end; function Nullable<T>.Equals(const other: Nullable<T>): Boolean; begin if HasValue and other.HasValue then Result := TEqualityComparer<T>.Default.Equals(Value, other.Value) else Result := HasValue = other.HasValue; end; class operator Nullable<T>.Implicit(const Value: T): Nullable<T>; begin Result := Nullable<T>.Create(Value); end; class operator Nullable<T>.Implicit(const Value: Nullable<T>): T; begin Result := Value.Value; end; class operator Nullable<T>.Implicit(const Value: Nullable<T>): Variant; var LValue: TValue; begin if Value.HasValue then begin LValue := TValue.From<T>(Value.Value); if LValue.IsType<Boolean> then Result := LValue.AsBoolean else Result := LValue.AsVariant; end else Result := Null; end; class operator Nullable<T>.Implicit(const Value: Variant): Nullable<T>; var LValue: TValue; begin if not VarIsNullOrEmpty(Value) then begin LValue := TValue.FromVariant(Value); Result := Nullable<T>.Create(LValue.AsType<T>); end else Result.Clear; end; class operator Nullable<T>.Implicit(Value: Pointer): Nullable<T>; begin if not Assigned(Value) then Result.Clear else raise Exception.Create('Cannot assigned non-null pointer to nullable type.'); end; class operator Nullable<T>.Explicit(const Value: Nullable<T>): T; begin Result := Value.Value; end; class operator Nullable<T>.Equal(const a, b: Nullable<T>): Boolean; begin Result := a.Equals(b); end; class operator Nullable<T>.NotEqual(const a, b: Nullable<T>): Boolean; begin Result := not a.Equals(b); end; function Nullable<T>.ToString: String; var LValue: TValue; begin if HasValue then begin LValue := TValue.From<T>(FValue); Result := LValue.ToString; end else Result := 'Null'; end; function Nullable<T>.ToVariant: Variant; var LValue: TValue; begin if HasValue then begin LValue := TValue.From<T>(FValue); if LValue.IsType<Boolean> then Result := LValue.AsBoolean else Result := LValue.AsVariant; end else Result := Null; end; end.
unit dll; interface type PEntityNode = ^TEntityNode; TEntityNode = packed record xPrev : PEntityNode; xNext : PEntityNode; yPrev : PEntityNode; yNext : PEntityNode; Key : Pointer; lenKey : Integer; X : Integer; Y : Integer; end; PAddNode = ^TAddNode; TAddNode = packed record Key : Pointer; lenKey : Integer; X : Integer; Y : Integer; end; TCallBackFuncRcd = record print: Pointer; end; type TScene = class public function Init: Boolean; virtual; stdcall; abstract; procedure Free; virtual; stdcall; abstract; procedure registerCallBack(rcd: TCallBackFuncRcd);virtual; stdcall; abstract; function Add(const node: PAddNode): PEntityNode; virtual; stdcall; abstract; function Get(const key: Pointer; const lenKey: Integer): PEntityNode; virtual; stdcall; abstract; function Leave(const key: Pointer; const lenKey: Integer): Boolean; virtual; stdcall; abstract; function Move(const key: Pointer; const lenKey: Integer; const x, y: Integer): PEntityNode; virtual; stdcall; abstract; procedure PrintAll(const isPrintX: Boolean);virtual; stdcall; abstract; procedure PrintAOI(const node: PEntityNode; xArea, yArea: Integer); virtual; stdcall; abstract; end; function NewScene(): TScene; stdcall; implementation function NewScene(): TScene; external 'Scene.dll'; end.
unit Check; interface uses Windows, Messages, SysUtils, Variants, Classes, Controls, Dialogs, StdCtrls, StrUtils, Xml.XMLDoc, Xml.XMLIntf, Generics.Collections; type TCheck = class() Fields: TDictionary<string,string>; MessageList: TStringList; private { Private declarations } procedure TCheck.isNumeric(item: STRING): STRING; procedure TCheck.isDate(item: STRING): STRING; public { Public declarations } Procedure TCheck.setField(line: XML): BOOLEAN; Procedure TCheck.compareField(item, op, variety: STRING): STRING; Procedure TCheck.addMessage(errno: STRING): STRING; Procedure TCheck.checkBasic(item, varaiety, errno: STRING): STRING; Procedure TCheck.checkPair(item, op1, variety, target, op2, condition, errno: STRING): STRING; end; var ErMessages:array[0..100] of STRING = ( "" ); implementation {$R *.dfm} // // procedure TCheck.addMessage(errno: INTEGER): STRING; begin MessageList.add(ErMessages[errno]); end; // // Procedure TCheck.setField(line: XML): BOOLEAN; var key, val: STRING; begin Fields := TDictionary<string,string>.Create; try Fields.Add(key, val); finally Fields.Free; end; // // Procedure TCheck.checkBasic(item, varaiety, errno: STRING): BOOLEAN; begin result := true; if compareField(item, variety) then begin result := true; end else begin addMessage(errno); result := false; end; end; // // Procedure TCheck.checkPair(item, op1, variety, target, op2, condition, errno: STRING): STRING; var x, y: STRING; begin Result := 'OK'; if compareField(item, op1, variety) then begin if compareField(target, op2, condition) then begin addMessage(errno); Result := 'ng'; end else begin Result := 'ok'; end; end else begin if compareStr(y, '') = 0 then Result := 'thru'; end end; end; // // Procedure TCheck.compareField(item, op, variety: STRING): BOOLEAN; var x, y: STRING; ary: TStringDynArray; begin ary := SplitString(variety, ','); x = Fields[item]; result := true; if compareStr(op, '=') = 0 then begin result := false; end; for y in ary do begin if compareStr(y, 'NULL') = 0 then begin y := ''; end; if compareStr(y, 'DATE') = 0 then begin result := isDate(x); exit; end; if compareStr(y, 'NUM') = 0 then begin result := isNumeric(x); exit; end; if compareStr(op, '=') = 0 then begin if compareStr(x, y) = 0 then begin result := 'ok'; exit; end; end else begin if compareStr(x, y) = 0 then begin result := 'ng'; exit; end; end; end; end; // // procedure TCheck.isNumeric(item: STRING): BOOLEAN; var x: STRING; n, c: INTEGER; begin result := true; val(Fields[item], n, c); if c <> 0 then begin Result := false; end; end; // // procedure TCheck.isDate(item: STRING): BOOLEAN; var x, yx, mx, dx, hms: STRING; yyyy, mm, dd, hh, ii, ss: INTEGER; d: Time; begin result := true; x := Fields[item]; yx := copy(x, 0, 4); mx := copy(x, 5, 2); dx := copy(x, 8, 2); hms := copy(x, 11, 8); try d := strToTime(yx+'/'+mx+'/'+dx+' '+hms); if year(d) <> GV-year then addMessage(errno); Result := false; except on e: Exception do addMessage(errno); Result := false; end; end; // // procedure TCheck.loadXML(child_nodes: IXMLNodeList); var xdoc: IXMLDocument; child_node: IXMLNode; i: Integer; key, val: STRING; begin for i := 0 to child_nodes.Count - 1 do begin child_node := child_nodes[i]; key := xdoc.DocumentElement.ChildValues['field']; val := xdoc.DocumentElement.ChildValues['value']; Fields[key] := val; end; end; end.
unit MainMenuUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIForm, uniGUIBaseClasses, uniImageList, Menus, uniMainMenu, uniPanel, uniGUIFrame, FrameMenu; type TMainMenuForm = class(TUniForm) UniPanel1: TUniPanel; UniFormMainMenu: TUniMainMenu; FormMainMenu1: TUniMenuItem; Item11: TUniMenuItem; Item21: TUniMenuItem; SubItem11: TUniMenuItem; SubItem21: TUniMenuItem; UniPanelMenu: TUniMainMenu; MenuForPanel1: TUniMenuItem; Items1: TUniMenuItem; A1: TUniMenuItem; B1: TUniMenuItem; C1: TUniMenuItem; SubItem31: TUniMenuItem; UniNativeImageList1: TUniNativeImageList; private { Private declarations } public { Public declarations } end; function MainMenuForm: TMainMenuForm; implementation {$R *.dfm} uses MainModule, uniGUIApplication; function MainMenuForm: TMainMenuForm; begin Result := TMainMenuForm(UniMainModule.GetFormInstance(TMainMenuForm)); end; end.
program Exercicio_2; { autor: Ozéias silva souza data: 26/09/2020 objetivo: Receber quatro notas e calcular a média aritmetica. } var i, soma : integer; notas : array[1..4] of integer; begin { Inicializando variavel } soma := 0; for i := 1 to 4 do begin write('Nota ', i, ' : '); readln(notas[i]); { atribuindo soma } soma := soma + notas[i]; end; { Mostrando a média } writeln('A media aritmetica : ', (soma/4):3:3); end.
unit UOptionBox; interface uses windows, UxlDialog, Resource, UxlTreeView, CommCtrl, UxlFunctions, UxlStrUtils, UxlStdCtrls, UxlClasses, UGlobalObj, UxlCommDlgs, UxlMiscCtrls, UDialogs, UxlList, UxlPanel, UCommPanels, UOptionManager, UxlComboBox; type TOptionFrame = class (TxlFrame) private FOptions: TOptions; protected procedure AfterOpenTemplate (); override; procedure BeforeCloseTemplate (); override; public function Validate (): boolean; procedure SaveOptions (); property Options: TOptions read FOptions write FOptions; end; TOptionPanel = class (TxlDialogML) protected FOptions: TOptions; public function Validate (): boolean; virtual; procedure Load (const op: TOptions); virtual; abstract; procedure Save (var op: TOptions); virtual; abstract; property Options: TOptions read FOptions write FOptions; end; TOptionPanelClass = class of TOptionPanel; TOptionBox = class (TxlDialog) private FTree: TxlTreeView; FFrame: TOptionFrame; FOptions: TOptions; FOnApplyOption: TNotifyEvent; function f_OnTreeSelChanging (oldhandle, newhandle: HTreeItem): integer; function f_OnTreeSelChanged (oldhandle, newhandle: HTreeItem): integer; protected procedure OnInitialize (); override; procedure OnOpen (); override; procedure OnClose (); override; procedure OnMove (pt: TPoint); override; procedure OnCommand (ctrlID: integer); override; public property Options: TOptions read FOptions write FOptions; property OnApplyOption: TNotifyEvent read FOnApplyOption write FOnApplyOption; end; implementation uses UxlFile, UxlMath, UTypeDef, ULangManager, UOpProgram, UOpAppearance, UOpExtFuncs; procedure TOptionBox.OnInitialize (); begin SetTemplate (Option_Box, m_options); end; const dlg_extfuncs: array[0..4] of integer = (ob_calcpage, ob_dictpage, ob_linkpage, ob_template, ob_clipboard); pic_extfuncs: array[0..4] of integer = (m_newcalc, m_newdict, m_newlink, m_template, m_clipboard); dlg_progoptions: array[0..6] of integer = (ob_edit, ob_notes, ob_import_export, ob_behavior, ob_login, ob_backup, ob_specialmode); pic_progoptions: array[0..6] of integer = (ic_edit, ic_autorecord, m_import, ic_behavior, ic_login, ic_backup, m_specialmode); dlg_approptions: array[0..4] of integer = (ob_treeview, ob_tabcontrol, ob_listview, ob_editor, ob_othercontrols); pic_approptions: array[0..4] of integer = (m_showtree, ic_tabcontrol, ic_listview, ic_editor, ic_othercontrols); const c_OptionBox: array[0..2] of word = (IDOK, IDCANCEL, cb_apply); procedure TOptionBox.OnOpen (); function f_GetTreeItem (id_dialog: integer; i_pic: integer; b_children: boolean): TTreeViewItem; begin with result do begin text := LangMan.GetItem (id_dialog); data := id_dialog; image := i_pic; selectedimage := image; state := 0; children := b_children; end; end; var h, h2: HTreeItem; i_pic, i: integer; begin inherited; RefreshItemTExt (self, c_OptionBox, Option_Box); FFrame := TOptionFrame.Create (self, Itemhandle[st_placeholder]); FFrame.Options := FOptions; FTree := TxlTreeView.create (self, ItemHandle[tv_options]); with FTree do begin ShowImages := true; Items.OnSelChanging := f_OnTreeSelChanging; Items.OnSelChanged := f_OnTreeSelChanged; i_pic := Images.AddIcon (m_options); h := Items.Add (nil, f_GetTreeItem(ob_program, i_pic, true)); for i := Low (dlg_progoptions) to High(dlg_progoptions) do Items.AddChild (h, f_GetTreeItem(dlg_progoptions[i], Images.AddIcon(pic_progoptions[i]), false)); Items.Expand (h); h2 := Items.Add (nil, f_GetTreeItem(ob_appearance, i_pic, true)); for i := Low(dlg_approptions) to High(dlg_approptions) do Items.AddChild (h2, f_GetTreeItem(dlg_approptions[i], Images.AddIcon(pic_approptions[i]), false)); Items.Expand (h2); h2 := Items.Add (nil, f_GetTreeItem(ob_extfuncs, i_pic, true)); for i := Low(dlg_extfuncs) to High(dlg_extfuncs) do Items.AddChild (h2, f_GetTreeItem(dlg_extfuncs[i], Images.AddIcon(pic_extfuncs[i]), false)); Items.Expand (h2); h2 := Items.FindByData (MemoryMan.OptionPage); if h2 = nil then h2 := h; Items.Select (h2, true); end; end; procedure TOptionBox.OnClose (); begin FFrame.CloseTemplate; // Options := FFrame.Options; FFrame.Free; FTree.Free; end; procedure TOptionBox.OnCommand (ctrlID: integer); begin if (ctrlID = IDOK) or (ctrlID = cb_apply) then begin if not FFrame.Validate then exit; FFrame.SaveOptions; Options := FFrame.Options; if assigned (FOnApplyOption) then FOnApplyOption (self); end; inherited OnCommand (ctrlID); end; procedure TOptionBox.OnMove (pt: TPoint); begin if FFrame <> nil then FFrame.AdjustFramePos; end; function TOptionBox.f_OnTreeSelChanging (oldhandle, newhandle: HTreeItem): integer; begin result := IfThen (FFrame.Validate, 0, 1); end; function TOptionBox.f_OnTreeSelChanged (oldhandle, newhandle: HTreeItem): integer; var o_class: TOptionPanelClass; begin result := 0; case FTree.Items[newhandle].data of ob_program: o_class := TOpProgram; ob_edit: o_class := TOpEdit; ob_notes: o_class := TOpNotes; ob_import_export: o_class := TOpImportExport; ob_behavior: o_class := TOpBehavior; ob_login: o_class := TOpLogIn; ob_backup: o_class := TOpBackUp; ob_specialmode: o_class := TOpSpecialMode; ob_appearance: o_class := TOpAppearance; ob_treeview: o_class := TOpTreeView; ob_tabcontrol: o_class := TOpTabControl; ob_listview: o_class := TOpListView; ob_editor: o_class := TOpEditor; ob_othercontrols: o_class := TOpOtherControls; ob_extfuncs: o_class := TOpExtFuncs; ob_calcpage: o_class := TOpCalcPage; ob_dictpage: o_class := TOpDictPage; ob_linkpage: o_class := TOpLinkPage; ob_template: o_class := TOpTemplate; ob_clipboard: o_class := TOpClipboard; else exit; end; MemoryMan.OptionPage := FTree.Items[newhandle].data; FFrame.SetTemplate(o_class); end; //----------------------------- procedure TOptionFrame.AfterOpenTemplate (); begin // TOptionPanel (FFrame).Options := FOptions; TOptionPanel (FFrame).Load (FOptions); end; procedure TOptionFrame.BeforeCloseTemplate (); begin SaveOptions; end; procedure TOptionFrame.SaveOptions (); begin TOptionPanel(FFrame).Save (FOptions); // Options := TOptionPanel(FFrame).Options; end; function TOptionFrame.Validate (): boolean; begin if assigned(FFrame) then result := TOptionPanel(FFrame).Validate else result := true; end; //------------------ function TOptionPanel.Validate (): boolean; begin result := true; end; end.
{*******************************************************} { } { Turbo Pascal Runtime Library } { Windows DOS Interface Unit } { } { Copyright (c) 1991,92 Borland International } { } {*******************************************************} unit WinDos; {$O+,S-,W-} interface { Flags bit masks } const fCarry = $0001; fParity = $0004; fAuxiliary = $0010; fZero = $0040; fSign = $0080; fOverflow = $0800; { File mode magic numbers } const fmClosed = $D7B0; fmInput = $D7B1; fmOutput = $D7B2; fmInOut = $D7B3; { File attribute constants } const faReadOnly = $01; faHidden = $02; faSysFile = $04; faVolumeID = $08; faDirectory = $10; faArchive = $20; faAnyFile = $3F; { Maximum file name component string lengths } const fsPathName = 79; fsDirectory = 67; fsFileName = 8; fsExtension = 4; { FileSplit return flags } const fcExtension = $0001; fcFileName = $0002; fcDirectory = $0004; fcWildcards = $0008; { Registers record used by Intr and MsDos } type TRegisters = record case Integer of 0: (AX, BX, CX, DX, BP, SI, DI, DS, ES, Flags: Word); 1: (AL, AH, BL, BH, CL, CH, DL, DH: Byte); end; { Typed-file and untyped-file record } type TFileRec = record Handle: Word; Mode: Word; RecSize: Word; Private: array[1..26] of Byte; UserData: array[1..16] of Byte; Name: array[0..79] of Char; end; { Textfile record } type PTextBuf = ^TTextBuf; TTextBuf = array[0..127] of Char; TTextRec = record Handle: Word; Mode: Word; BufSize: Word; Private: Word; BufPos: Word; BufEnd: Word; BufPtr: PTextBuf; OpenFunc: Pointer; InOutFunc: Pointer; FlushFunc: Pointer; CloseFunc: Pointer; UserData: array[1..16] of Byte; Name: array[0..79] of Char; Buffer: TTextBuf; end; { Search record used by FindFirst and FindNext } type TSearchRec = record Fill: array[1..21] of Byte; Attr: Byte; Time: Longint; Size: Longint; Name: array[0..12] of Char; end; { Date and time record used by PackTime and UnpackTime } type TDateTime = record Year, Month, Day, Hour, Min, Sec: Word; end; { Error status variable } var DosError: Integer; { DosVersion returns the DOS version number. The low byte of } { the result is the major version number, and the high byte is } { the minor version number. For example, DOS 3.20 returns 3 in } { the low byte, and 20 in the high byte. } function DosVersion: Word; { Intr executes a specified software interrupt with a specified } { TRegisters package. NOTE: To avoid general protection faults } { when running in protected mode, always make sure to } { initialize the DS and ES fields of the TRegisters record with } { valid selector values, or set the fields to zero. } procedure Intr(IntNo: Byte; var Regs: TRegisters); { MsDos invokes the DOS function call handler with a specified } { TRegisters package. } procedure MsDos(var Regs: TRegisters); { GetDate returns the current date set in the operating system. } { Ranges of the values returned are: Year 1980-2099, Month } { 1-12, Day 1-31 and DayOfWeek 0-6 (0 corresponds to Sunday). } procedure GetDate(var Year, Month, Day, DayOfWeek: Word); { SetDate sets the current date in the operating system. Valid } { parameter ranges are: Year 1980-2099, Month 1-12 and Day } { 1-31. If the date is not valid, the function call is ignored. } procedure SetDate(Year, Month, Day: Word); { GetTime returns the current time set in the operating system. } { Ranges of the values returned are: Hour 0-23, Minute 0-59, } { Second 0-59 and Sec100 (hundredths of seconds) 0-99. } procedure GetTime(var Hour, Minute, Second, Sec100: Word); { SetTime sets the time in the operating system. Valid } { parameter ranges are: Hour 0-23, Minute 0-59, Second 0-59 and } { Sec100 (hundredths of seconds) 0-99. If the time is not } { valid, the function call is ignored. } procedure SetTime(Hour, Minute, Second, Sec100: Word); { GetCBreak returns the state of Ctrl-Break checking in DOS. } { When off (False), DOS only checks for Ctrl-Break during I/O } { to console, printer, or communication devices. When on } { (True), checks are made at every system call. } procedure GetCBreak(var Break: Boolean); { SetCBreak sets the state of Ctrl-Break checking in DOS. } procedure SetCBreak(Break: Boolean); { GetVerify returns the state of the verify flag in DOS. When } { off (False), disk writes are not verified. When on (True), } { all disk writes are verified to insure proper writing. } procedure GetVerify(var Verify: Boolean); { SetVerify sets the state of the verify flag in DOS. } procedure SetVerify(Verify: Boolean); { DiskFree returns the number of free bytes on the specified } { drive number (0=Default,1=A,2=B,..). DiskFree returns -1 if } { the drive number is invalid. } function DiskFree(Drive: Byte): Longint; { DiskSize returns the size in bytes of the specified drive } { number (0=Default,1=A,2=B,..). DiskSize returns -1 if the } { drive number is invalid. } function DiskSize(Drive: Byte): Longint; { GetFAttr returns the attributes of a file. F must be a file } { variable (typed, untyped or textfile) which has been assigned } { a name. The attributes are examined by ANDing with the } { attribute masks defined as constants above. Errors are } { reported in DosError. } procedure GetFAttr(var F; var Attr: Word); { SetFAttr sets the attributes of a file. F must be a file } { variable (typed, untyped or textfile) which has been assigned } { a name. The attribute value is formed by adding (or ORing) } { the appropriate attribute masks defined as constants above. } { Errors are reported in DosError. } procedure SetFAttr(var F; Attr: Word); { GetFTime returns the date and time a file was last written. } { F must be a file variable (typed, untyped or textfile) which } { has been assigned and opened. The Time parameter may be } { unpacked throgh a call to UnpackTime. Errors are reported in } { DosError. } procedure GetFTime(var F; var Time: Longint); { SetFTime sets the date and time a file was last written. } { F must be a file variable (typed, untyped or textfile) which } { has been assigned and opened. The Time parameter may be } { created through a call to PackTime. Errors are reported in } { DosError. } procedure SetFTime(var F; Time: Longint); { FindFirst searches the specified (or current) directory for } { the first entry that matches the specified filename and } { attributes. The result is returned in the specified search } { record. Errors (and no files found) are reported in DosError. } procedure FindFirst(Path: PChar; Attr: Word; var F: TSearchRec); { FindNext returs the next entry that matches the name and } { attributes specified in a previous call to FindFirst. The } { search record must be one passed to FindFirst. Errors (and no } { more files) are reported in DosError. } procedure FindNext(var F: TSearchRec); { UnpackTime converts a 4-byte packed date/time returned by } { FindFirst, FindNext or GetFTime into a TDateTime record. } procedure UnpackTime(P: Longint; var T: TDateTime); { PackTime converts a TDateTime record into a 4-byte packed } { date/time used by SetFTime. } procedure PackTime(var T: TDateTime; var P: Longint); { GetIntVec returns the address stored in the specified } { interrupt vector. } procedure GetIntVec(IntNo: Byte; var Vector: Pointer); { SetIntVec sets the address in the interrupt vector table for } { the specified interrupt. } procedure SetIntVec(IntNo: Byte; Vector: Pointer); { FileSearch searches for the file given by Name in the list of } { directories given by List. The directory paths in List must } { be separated by semicolons. The search always starts with the } { current directory of the current drive. If the file is found, } { FileSearch stores a concatenation of the directory path and } { the file name in Dest. Otherwise FileSearch stores an empty } { string in Dest. The maximum length of the result is defined } { by the fsPathName constant. The returned value is Dest. } function FileSearch(Dest, Name, List: PChar): PChar; { FileExpand fully expands the file name in Name, and stores } { the result in Dest. The maximum length of the result is } { defined by the fsPathName constant. The result is an all } { upper case string consisting of a drive letter, a colon, a } { root relative directory path, and a file name. Embedded '.' } { and '..' directory references are removed, and all name and } { extension components are truncated to 8 and 3 characters. The } { returned value is Dest. } function FileExpand(Dest, Name: PChar): PChar; { FileSplit splits the file name specified by Path into its } { three components. Dir is set to the drive and directory path } { with any leading and trailing backslashes, Name is set to the } { file name, and Ext is set to the extension with a preceding } { period. If a component string parameter is NIL, the } { corresponding part of the path is not stored. If the path } { does not contain a given component, the returned component } { string is empty. The maximum lengths of the strings returned } { in Dir, Name, and Ext are defined by the fsDirectory, } { fsFileName, and fsExtension constants. The returned value is } { a combination of the fcDirectory, fcFileName, and fcExtension } { bit masks, indicating which components were present in the } { path. If the name or extension contains any wildcard } { characters (* or ?), the fcWildcards flag is set in the } { returned value. } function FileSplit(Path, Dir, Name, Ext: PChar): Word; { GetCurDir returns the current directory of a specified drive. } { Drive = 0 indicates the current drive, 1 indicates drive A, 2 } { indicates drive B, and so on. The string returned in Dir } { always starts with a drive letter, a colon, and a backslash. } { The maximum length of the resulting string is defined by the } { fsDirectory constant. The returned value is Dir. Errors are } { reported in DosError. } function GetCurDir(Dir: PChar; Drive: Byte): PChar; { SetCurDir changes the current directory to the path specified } { by Dir. If Dir specifies a drive letter, the current drive is } { also changed. Errors are reported in DosError. } procedure SetCurDir(Dir: PChar); { CreateDir creates a new subdirectory with the path specified } { by Dir. Errors are reported in DosError. } procedure CreateDir(Dir: PChar); { RemoveDir removes the subdirectory with the path specified by } { Dir. Errors are reported in DosError. } procedure RemoveDir(Dir: PChar); { GetArgCount returns the number of parameters passed to the } { program on the command line. } function GetArgCount: Integer; { GetArgStr returns the Index'th parameter from the command } { line, or an empty string if Index is less than zero or } { greater than GetArgCount. If Index is zero, GetArgStr returns } { the filename of the current module. The maximum length of the } { string returned in Dest is given by the MaxLen parameter. The } { returned value is Dest. } function GetArgStr(Dest: PChar; Index: Integer; MaxLen: Word): PChar; { GetEnvVar returns a pointer to the value of a specified } { environment variable, i.e. a pointer to the first character } { after the equals sign (=) in the environment entry given by } { VarName. VarName is case insensitive. GetEnvVar returns NIL } { if the specified environment variable does not exist. } function GetEnvVar(VarName: PChar): PChar; implementation {$IFDEF Windows} {$DEFINE ProtectedMode} {$ENDIF} {$IFDEF DPMI} {$DEFINE ProtectedMode} {$ENDIF} {$IFDEF Windows} uses WinTypes, WinProcs, Strings; {$ELSE} uses Strings; {$ENDIF} {$IFDEF Windows} procedure AnsiDosFunc; assembler; var TempName: array[0..fsPathName] of Char; asm PUSH DS PUSH CX PUSH AX MOV SI,DI PUSH ES POP DS LEA DI,TempName PUSH SS POP ES MOV CX,fsPathName CLD @@1: LODSB OR AL,AL JE @@2 STOSB LOOP @@1 @@2: XOR AL,AL STOSB LEA DI,TempName PUSH SS PUSH DI PUSH SS PUSH DI CALL AnsiToOem POP AX POP CX LEA DX,TempName PUSH SS POP DS INT 21H POP DS end; {$ELSE} procedure AnsiDosFunc; assembler; asm PUSH DS MOV DX,DI PUSH ES POP DS INT 21H POP DS end; {$ENDIF} function DosVersion: Word; assembler; asm MOV AH,30H INT 21H end; procedure Intr(IntNo: Byte; var Regs: TRegisters); assembler; asm PUSH DS {$IFDEF ProtectedMode} {$IFDEF Windows} PUSH CS CALL AllocCSToDSAlias {$ELSE} MOV AX,CS ADD AX,SelectorInc {$ENDIF} MOV DS,AX CLI PUSH WORD PTR DS:@@Int PUSH DS MOV AL,IntNo MOV BYTE PTR DS:@@Int+1,AL {$ELSE} PUSH WORD PTR CS:@@Int MOV AL,IntNo MOV BYTE PTR CS:@@Int+1,AL {$ENDIF} LDS SI,Regs CLD LODSW PUSH AX LODSW XCHG AX,BX LODSW XCHG AX,CX LODSW XCHG AX,DX LODSW XCHG AX,BP LODSW PUSH AX LODSW XCHG AX,DI LODSW PUSH AX LODSW {$IFDEF DPMI} VERR AX JNZ @@1 MOV ES,AX @@1: POP AX VERR AX JNZ @@2 MOV DS,AX @@2: {$ELSE} MOV ES,AX POP DS {$ENDIF} POP SI POP AX @@Int: INT 0 STI PUSHF PUSH ES PUSH DI PUSH BP MOV BP,SP {$IFDEF ProtectedMode} ADD BP,14 {$ELSE} ADD BP,12 {$ENDIF} LES DI,Regs CLD STOSW XCHG AX,BX STOSW XCHG AX,CX STOSW XCHG AX,DX STOSW POP AX STOSW XCHG AX,SI STOSW POP AX STOSW MOV AX,DS STOSW POP AX STOSW POP AX STOSW {$IFDEF ProtectedMode} POP DS POP WORD PTR DS:@@Int {$ELSE} POP WORD PTR CS:@@Int {$ENDIF} {$IFDEF Windows} MOV AX,DS POP DS PUSH AX CALL FreeSelector {$ELSE} POP DS {$ENDIF} end; procedure MsDos(var Regs: TRegisters); begin Intr($21, Regs); end; procedure GetDate(var Year, Month, Day, DayOfWeek: Word); assembler; asm MOV AH,2AH INT 21H XOR AH,AH LES DI,DayOfWeek STOSW MOV AL,DL LES DI,Day STOSW MOV AL,DH LES DI,Month STOSW XCHG AX,CX LES DI,Year STOSW end; procedure SetDate(Year, Month, Day: Word); assembler; asm MOV CX,Year MOV DH,BYTE PTR Month MOV DL,BYTE PTR Day MOV AH,2BH INT 21H end; procedure GetTime(var Hour, Minute, Second, Sec100: Word); assembler; asm MOV AH,2CH INT 21H XOR AH,AH MOV AL,DL LES DI,Sec100 STOSW MOV AL,DH LES DI,Second STOSW MOV AL,CL LES DI,Minute STOSW MOV AL,CH LES DI,Hour STOSW end; procedure SetTime(Hour, Minute, Second, Sec100: Word); assembler; asm MOV CH,BYTE PTR Hour MOV CL,BYTE PTR Minute MOV DH,BYTE PTR Second MOV DL,BYTE PTR Sec100 MOV AH,2DH INT 21H end; procedure GetCBreak(var Break: Boolean); assembler; asm MOV AX,3300H INT 21H LES DI,Break MOV ES:[DI],DL end; procedure SetCBreak(Break: Boolean); assembler; asm MOV DL,Break MOV AX,3301H INT 21H end; procedure GetVerify(var Verify: Boolean); assembler; asm MOV AH,54H INT 21H LES DI,Verify STOSB end; procedure SetVerify(Verify: Boolean); assembler; asm MOV AL,Verify MOV AH,2EH INT 21H end; function DiskFree(Drive: Byte): Longint; assembler; asm MOV DL,Drive MOV AH,36H INT 21H MOV DX,AX CMP AX,0FFFFH JE @@1 MUL CX MUL BX @@1: end; function DiskSize(Drive: Byte): Longint; assembler; asm MOV DL,Drive MOV AH,36H INT 21H MOV BX,DX MOV DX,AX CMP AX,0FFFFH JE @@1 MUL CX MUL BX @@1: end; procedure GetFAttr(var F; var Attr: Word); assembler; asm PUSH DS LDS DX,F ADD DX,OFFSET TFileRec.Name MOV AX,4300H INT 21H POP DS JNC @@1 XOR CX,CX JMP @@2 @@1: XOR AX,AX @@2: MOV DosError,AX LES DI,Attr XCHG AX,CX STOSW end; procedure SetFAttr(var F; Attr: Word); assembler; asm PUSH DS LDS DX,F ADD DX,OFFSET TFileRec.Name MOV CX,Attr MOV AX,4301H INT 21H POP DS JC @@1 XOR AX,AX @@1: MOV DosError,AX end; procedure GetFTime(var F; var Time: Longint); assembler; asm LES DI,F MOV BX,ES:[DI].TFileRec.Handle MOV AX,5700H INT 21H JNC @@1 XOR CX,CX XOR DX,DX JMP @@2 @@1: XOR AX,AX @@2: MOV DosError,AX LES DI,Time CLD XCHG AX,CX STOSW XCHG AX,DX STOSW end; procedure SetFTime(var F; Time: Longint); assembler; asm LES DI,F MOV BX,ES:[DI].TFileRec.Handle MOV CX,WORD PTR Time[0] MOV DX,WORD PTR Time[2] MOV AX,5701H INT 21H JC @@1 XOR AX,AX @@1: MOV DosError,AX end; procedure FindFirst(Path: PChar; Attr: Word; var F: TSearchRec); assembler; asm PUSH DS LDS DX,F MOV AH,1AH INT 21H POP DS LES DI,Path MOV CX,Attr MOV AH,4EH CALL AnsiDosFunc JC @@1 {$IFDEF Windows} LES DI,F ADD DI,OFFSET TSearchRec.Name PUSH ES PUSH DI PUSH ES PUSH DI CALL OemToAnsi {$ENDIF} XOR AX,AX @@1: MOV DosError,AX end; procedure FindNext(var F: TSearchRec); assembler; asm PUSH DS LDS DX,F MOV AH,1AH INT 21H POP DS MOV AH,4FH INT 21H JC @@1 {$IFDEF Windows} LES DI,F ADD DI,OFFSET TSearchRec.Name PUSH ES PUSH DI PUSH ES PUSH DI CALL OemToAnsi {$ENDIF} XOR AX,AX @@1: MOV DosError,AX end; procedure UnpackTime(P: Longint; var T: TDateTime); assembler; asm LES DI,T CLD MOV AX,P.Word[2] MOV CL,9 SHR AX,CL ADD AX,1980 STOSW MOV AX,P.Word[2] MOV CL,5 SHR AX,CL AND AX,15 STOSW MOV AX,P.Word[2] AND AX,31 STOSW MOV AX,P.Word[0] MOV CL,11 SHR AX,CL STOSW MOV AX,P.Word[0] MOV CL,5 SHR AX,CL AND AX,63 STOSW MOV AX,P.Word[0] AND AX,31 SHL AX,1 STOSW end; procedure PackTime(var T: TDateTime; var P: Longint); assembler; asm PUSH DS LDS SI,T CLD LODSW SUB AX,1980 MOV CL,9 SHL AX,CL XCHG AX,DX LODSW MOV CL,5 SHL AX,CL ADD DX,AX LODSW ADD DX,AX LODSW MOV CL,11 SHL AX,CL XCHG AX,BX LODSW MOV CL,5 SHL AX,CL ADD BX,AX LODSW SHR AX,1 ADD AX,BX POP DS LES DI,P STOSW XCHG AX,DX STOSW end; procedure GetIntVec(IntNo: Byte; var Vector: Pointer); assembler; asm MOV AL,IntNo MOV AH,35H INT 21H MOV AX,ES LES DI,Vector CLD XCHG AX,BX STOSW XCHG AX,BX STOSW end; procedure SetIntVec(IntNo: Byte; Vector: Pointer); assembler; asm PUSH DS LDS DX,Vector MOV AL,IntNo MOV AH,25H INT 21H POP DS end; function FileSearch(Dest, Name, List: PChar): PChar; assembler; asm PUSH DS CLD LDS SI,List LES DI,Dest MOV CX,fsPathName @@1: PUSH DS PUSH SI JCXZ @@3 LDS SI,Name @@2: LODSB OR AL,AL JE @@3 STOSB LOOP @@2 @@3: XOR AL,AL STOSB LES DI,Dest MOV AX,4300H CALL AnsiDosFunc POP SI POP DS JC @@4 TEST CX,18H JE @@9 @@4: LES DI,Dest MOV CX,fsPathName XOR AH,AH LODSB OR AL,AL JE @@8 @@5: CMP AL,';' JE @@7 JCXZ @@6 MOV AH,AL STOSB DEC CX @@6: LODSB OR AL,AL JNE @@5 DEC SI @@7: JCXZ @@1 CMP AH,':' JE @@1 MOV AL,'\' CMP AL,AH JE @@1 STOSB DEC CX JMP @@1 @@8: STOSB @@9: MOV AX,Dest.Word[0] MOV DX,Dest.Word[2] POP DS end; function FileExpand(Dest, Name: PChar): PChar; assembler; var TempName: array[0..159] of Char; asm PUSH DS CLD LDS SI,Name LEA DI,TempName PUSH SS POP ES LODSW OR AL,AL JE @@1 CMP AH,':' JNE @@1 CMP AL,'a' JB @@2 CMP AL,'z' JA @@2 SUB AL,20H JMP @@2 @@1: DEC SI DEC SI MOV AH,19H INT 21H ADD AL,'A' MOV AH,':' @@2: STOSW CMP [SI].Byte,'\' JE @@3 SUB AL,'A'-1 MOV DL,AL MOV AL,'\' STOSB PUSH DS PUSH SI MOV AH,47H MOV SI,DI PUSH ES POP DS INT 21H POP SI POP DS JC @@3 XOR AL,AL CMP AL,ES:[DI] JE @@3 {$IFDEF Windows} PUSH ES PUSH ES PUSH DI PUSH ES PUSH DI CALL OemToAnsi POP ES {$ENDIF} MOV CX,0FFFFH XOR AL,AL CLD REPNE SCASB DEC DI MOV AL,'\' STOSB @@3: MOV CX,8 @@4: LODSB OR AL,AL JE @@7 CMP AL,'\' JE @@7 CMP AL,'.' JE @@6 JCXZ @@4 DEC CX {$IFNDEF Windows} CMP AL,'a' JB @@5 CMP AL,'z' JA @@5 SUB AL,20H {$ENDIF} @@5: STOSB JMP @@4 @@6: MOV CL,3 JMP @@5 @@7: CMP ES:[DI-2].Word,'.\' JNE @@8 DEC DI DEC DI JMP @@10 @@8: CMP ES:[DI-2].Word,'..' JNE @@10 CMP ES:[DI-3].Byte,'\' JNE @@10 SUB DI,3 CMP ES:[DI-1].Byte,':' JE @@10 @@9: DEC DI CMP ES:[DI].Byte,'\' JNE @@9 @@10: MOV CL,8 OR AL,AL JNE @@5 CMP ES:[DI-1].Byte,':' JNE @@11 MOV AL,'\' STOSB @@11: LEA SI,TempName PUSH SS POP DS MOV CX,DI SUB CX,SI CMP CX,79 JBE @@12 MOV CX,79 @@12: LES DI,Dest PUSH ES PUSH DI {$IFDEF Windows} PUSH ES PUSH DI {$ENDIF} REP MOVSB XOR AL,AL STOSB {$IFDEF Windows} CALL AnsiUpper {$ENDIF} POP AX POP DX POP DS end; {$W+} function FileSplit(Path, Dir, Name, Ext: PChar): Word; var DirLen, NameLen, Flags: Word; NamePtr, ExtPtr: PChar; begin NamePtr := StrRScan(Path, '\'); if NamePtr = nil then NamePtr := StrRScan(Path, ':'); if NamePtr = nil then NamePtr := Path else Inc(NamePtr); ExtPtr := StrScan(NamePtr, '.'); if ExtPtr = nil then ExtPtr := StrEnd(NamePtr); DirLen := NamePtr - Path; if DirLen > fsDirectory then DirLen := fsDirectory; NameLen := ExtPtr - NamePtr; if NameLen > fsFilename then NameLen := fsFilename; Flags := 0; if (StrScan(NamePtr, '?') <> nil) or (StrScan(NamePtr, '*') <> nil) then Flags := fcWildcards; if DirLen <> 0 then Flags := Flags or fcDirectory; if NameLen <> 0 then Flags := Flags or fcFilename; if ExtPtr[0] <> #0 then Flags := Flags or fcExtension; if Dir <> nil then StrLCopy(Dir, Path, DirLen); if Name <> nil then StrLCopy(Name, NamePtr, NameLen); if Ext <> nil then StrLCopy(Ext, ExtPtr, fsExtension); FileSplit := Flags; end; {$W-} function GetCurDir(Dir: PChar; Drive: Byte): PChar; assembler; asm MOV AL,Drive OR AL,AL JNE @@1 MOV AH,19H INT 21H INC AX @@1: MOV DL,AL LES DI,Dir PUSH ES PUSH DI CLD ADD AL,'A'-1 MOV AH,':' STOSW MOV AX,'\' STOSW PUSH DS LEA SI,[DI-1] PUSH ES POP DS MOV AH,47H INT 21H JC @@2 {$IFDEF Windows} PUSH DS PUSH SI PUSH DS PUSH SI CALL OemToAnsi {$ENDIF} XOR AX,AX @@2: POP DS MOV DosError,AX POP AX POP DX end; procedure SetCurDir(Dir: PChar); assembler; asm LES DI,Dir MOV AX,ES:[DI] OR AL,AL JE @@2 CMP AH,':' JNE @@1 AND AL,0DFH SUB AL,'A' MOV DL,AL MOV AH,0EH INT 21H MOV AH,19H INT 21H CMP AL,DL MOV AX,15 JNE @@3 CMP AH,ES:[DI+2] JE @@2 @@1: MOV AH,3BH CALL AnsiDosFunc JC @@3 @@2: XOR AX,AX @@3: MOV DosError,AX end; procedure CreateDir(Dir: PChar); assembler; asm LES DI,Dir MOV AH,39H CALL AnsiDosFunc JC @@1 XOR AX,AX @@1: MOV DosError,AX end; procedure RemoveDir(Dir: PChar); assembler; asm LES DI,Dir MOV AH,3AH CALL AnsiDosFunc JC @@1 XOR AX,AX @@1: MOV DosError,AX end; {$IFDEF Windows} procedure ArgStrCount; assembler; asm LDS SI,CmdLine CLD @@1: LODSB OR AL,AL JE @@2 CMP AL,' ' JBE @@1 @@2: DEC SI MOV BX,SI @@3: LODSB CMP AL,' ' JA @@3 DEC SI MOV AX,SI SUB AX,BX JE @@4 LOOP @@1 @@4: end; function GetArgCount: Integer; assembler; asm PUSH DS XOR CX,CX CALL ArgStrCount XCHG AX,CX NEG AX POP DS end; function GetArgStr(Dest: PChar; Index: Integer; MaxLen: Word): PChar; assembler; asm MOV CX,Index JCXZ @@2 PUSH DS CALL ArgStrCount MOV SI,BX LES DI,Dest MOV CX,MaxLen CMP CX,AX JB @@1 XCHG AX,CX @@1: REP MOVSB XCHG AX,CX STOSB POP DS JMP @@3 @@2: PUSH HInstance PUSH Dest.Word[2] PUSH Dest.Word[0] MOV AX,MaxLen INC AX PUSH AX CALL GetModuleFileName @@3: MOV AX,Dest.Word[0] MOV DX,Dest.Word[2] end; {$ELSE} procedure ArgStrCount; assembler; asm MOV DS,PrefixSeg MOV SI,80H CLD LODSB MOV DL,AL XOR DH,DH ADD DX,SI @@1: CMP SI,DX JE @@2 LODSB CMP AL,' ' JBE @@1 DEC SI @@2: MOV BX,SI @@3: CMP SI,DX JE @@4 LODSB CMP AL,' ' JA @@3 DEC SI @@4: MOV AX,SI SUB AX,BX JE @@5 LOOP @@1 @@5: end; function GetArgCount: Integer; assembler; asm PUSH DS XOR CX,CX CALL ArgStrCount XCHG AX,CX NEG AX POP DS end; function GetArgStr(Dest: PChar; Index: Integer; MaxLen: Word): PChar; assembler; asm PUSH DS MOV CX,Index JCXZ @@1 CALL ArgStrCount MOV SI,BX JMP @@4 @@1: MOV AH,30H INT 21H CMP AL,3 MOV AX,0 JB @@4 MOV DS,PrefixSeg MOV ES,DS:WORD PTR 2CH XOR DI,DI CLD @@2: CMP AL,ES:[DI] JE @@3 MOV CX,-1 REPNE SCASB JMP @@2 @@3: ADD DI,3 MOV SI,DI PUSH ES POP DS MOV CX,256 REPNE SCASB XCHG AX,CX NOT AL @@4: LES DI,Dest MOV CX,MaxLen CMP CX,AX JB @@5 XCHG AX,CX @@5: REP MOVSB XCHG AX,CX STOSB MOV AX,Dest.Word[0] MOV DX,Dest.Word[2] POP DS end; {$ENDIF} {$W+} function GetEnvVar(VarName: PChar): PChar; var L: Word; P: PChar; begin L := StrLen(VarName); {$IFDEF Windows} P := GetDosEnvironment; {$ELSE} P := Ptr(Word(Ptr(PrefixSeg, $2C)^), 0); {$ENDIF} while P^ <> #0 do begin if (StrLIComp(P, VarName, L) = 0) and (P[L] = '=') then begin GetEnvVar := P + L + 1; Exit; end; Inc(P, StrLen(P) + 1); end; GetEnvVar := nil; end; {$W-} end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvFindReplace.PAS, released on 2002-05-26. The Initial Developer of the Original Code is Peter Thörnqvist [peter3 at sourceforge dot net] Portions created by Peter Thörnqvist are Copyright (C) 2002 Peter Thörnqvist. All Rights Reserved. Contributor(s): Olivier Sannier Robert Marquardt You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Description: Wrapper for the TFind / TReplace dialogs and a stand-alone full text search engine with support for all available dialog options: Search up/down, whole word only, case sensitive, replace all etc. Known Issues: -----------------------------------------------------------------------------} // $Id: JvFindReplace.pas 13104 2011-09-07 06:50:43Z obones $ unit JvFindReplace; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, Windows, Messages, Controls, Dialogs, StdCtrls, JvComponentBase, JvEditor; type TJvReplaceProgressEvent = procedure(Sender: TObject; Position: Integer; var Terminate: Boolean) of object; TJvReplaceAllEvent = procedure(Sender: TObject; ReplaceCount: Integer) of object; // for custom property editor TJvEditControlName = TWinControl; // internal type to handle different component ancestry trees TJvFindReplaceEditKind = (etEmpty, etCustomEdit, etJvCustomEditor); {$IFDEF RTL230_UP} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF RTL230_UP} TJvFindReplace = class(TJvComponent) private FOnFind: TNotifyEvent; FOnReplace: TNotifyEvent; FOnReplacingAll: TNotifyEvent; FOnReplacedAll: TJvReplaceAllEvent; FOnShow: TNotifyEvent; FOnClose: TNotifyEvent; FOnNotFound: TNotifyEvent; FOnProgress: TJvReplaceProgressEvent; FOwner: TComponent; FFindDialog: TFindDialog; FReplaceDialog: TReplaceDialog; FOptions: TFindOptions; FPosition: TPoint; FFast: Boolean; FHelpContext: THelpContext; FShowDialogs: Boolean; FFindText: string; FReplaceText: string; FNumberReplaced: Integer; // only used by Replace All FEditControl: TJvEditControlName; FEditKind: TJvFindReplaceEditKind; procedure SetEditControl(Value: TJvEditControlName); procedure SetPosition(Value: TPoint); procedure SetDialogTop(Value: Integer); procedure SetDialogLeft(Value: Integer); procedure SetOptions(Value: TFindOptions); procedure SetHelpContext(Value: THelpContext); procedure SetFindText(const Value: string); procedure SetReplaceText(const Value: string); procedure SetShowDialogs(Value: Boolean); function GetTop: Integer; function GetLeft: Integer; function ReplaceOne(Sender: TObject): Boolean; procedure UpdateDialogs; procedure UpdateProperties(Sender: TObject); procedure NeedDialogs; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetEditText: string; virtual; function GetEditSelText: string; virtual; function GetEditSelStart: Integer; virtual; function GetEditSelLength: Integer; virtual; function GetEditHandle: HWND; virtual; procedure TestEditAssigned; virtual; procedure SetEditText(const Text: string); virtual; procedure SetEditSelText(const Text: string); virtual; procedure SetEditSelStart(Start: Integer); virtual; procedure SetEditSelLength(Length: Integer); virtual; procedure SetEditFocus; virtual; procedure DoOnFind(Sender: TObject); virtual; procedure DoOnReplace(Sender: TObject); virtual; procedure DoOnShow(Sender: TObject); virtual; procedure DoOnClose(Sender: TObject); virtual; procedure DoFailed(Sender: TObject); virtual; procedure DoReplacingAll; virtual; procedure DoReplacedAll(Sender: TObject); virtual; procedure DoProgress(Position: Integer; var Terminate: Boolean); virtual; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; procedure Find; virtual; procedure FindAgain; virtual; procedure Replace; virtual; procedure ReplaceAll(const SearchText, ReplaceText: string); virtual; property Position: TPoint read FPosition write SetPosition; property Top: Integer read GetTop write SetDialogTop default -1; property Left: Integer read GetLeft write SetDialogLeft default -1; published property EditControl: TJvEditControlName read FEditControl write SetEditControl; property Fast: Boolean read FFast write FFast default False; property Options: TFindOptions read FOptions write SetOptions; property FindText: string read FFindText write SetFindText; property ReplaceText: string read FReplaceText write SetReplaceText; property ShowDialogs: Boolean read FShowDialogs write SetShowDialogs default True; property HelpContext: THelpContext read FHelpContext write SetHelpContext default 0; property OnFind: TNotifyEvent read FOnFind write FOnFind; property OnReplace: TNotifyEvent read FOnReplace write FOnReplace; property OnReplacingAll: TNotifyEvent read FOnReplacingAll write FOnReplacingAll; property OnReplacedAll: TJvReplaceAllEvent read FOnReplacedAll write FOnReplacedAll; property OnNotFound: TNotifyEvent read FOnNotFound write FOnNotFound; property OnProgress: TJvReplaceProgressEvent read FOnProgress write FOnProgress; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvFindReplace.pas $'; Revision: '$Revision: 13104 $'; Date: '$Date: 2011-09-07 08:50:43 +0200 (mer. 07 sept. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses Math, {$IFNDEF COMPILER12_UP} JvJCLUtils, {$ENDIF ~COMPILER12_UP} JvConsts, JvResources, JvTypes; { utility } function IsValidWholeWord(const S: string): Boolean; begin Result := (Length(S) > 0) and not (CharInSet(S[1], IdentifierSymbols) or CharInSet(S[Length(S)], IdentifierSymbols)); end; { invert string } function StrRev(const S: string): string; var I, Len: Integer; begin Len := Length(S); SetLength(Result, Len); for I := 1 to Len do begin Result[I] := S[Len]; Dec(Len); end; end; { Pascal adaption of a function originally in C } function BoyerMoore(SubStr, S: PChar): Integer; var CharJump, MatchJump, BackUp: array[0..255] of Integer; PatLen, TextLen, u, uA, uB, uText, uPat: Integer; begin Result := 0; PatLen := StrLen(SubStr); TextLen := StrLen(S); FillChar(CharJump, 256 * SizeOf(Integer), 0); for u := 0 to PatLen do CharJump[Ord(SubStr[u])] := PatLen - u - 1; for u := 1 to PatLen - 1 do MatchJump[u] := 2 * PatLen - u; u := PatLen; uA := PatLen + 1; while u > 0 do begin BackUp[u] := uA; while (uA <= PatLen) and (SubStr[u - 1] <> SubStr[uA - 1]) do begin if MatchJump[uA] > PatLen - u then MatchJump[uA] := PatLen - u; uA := BackUp[uA]; end; Dec(u); Dec(uA); end; for u := 1 to uA do if MatchJump[u] > PatLen + uA - u then MatchJump[u] := PatLen + uA - u; uB := BackUp[uA]; while uA <= PatLen do begin while uA <= uB do begin if MatchJump[uA] > uB - uA + PatLen then MatchJump[uA] := uB - uA + PatLen; Inc(uA); end; uB := BackUp[uB]; end; uPat := PatLen; uText := PatLen - 1; while (uText < TextLen) and (uPat <> 0) do begin if S[uText] = SubStr[uPat - 1] then begin Dec(uText); Dec(uPat); end else { mismatch - slide forward } begin uA := CharJump[Ord(S[uText])]; uB := PatLen - uPat + 1; uText := uText + Max(uA, uB); uPat := PatLen; end; end; if uPat = 0 then Result := uText + 2; end; { Find text, return a Longint } function FindInText(const Text, Search: string; FromPos, Len: Integer; Fast, WholeWord, MatchCase: Boolean): Longint; var Found, SearchLen, TextLen: Integer; S: string; begin Result := -1; // assume failure // first character in string is at position 1 if FromPos = 0 then FromPos := 1; Found := 1; while (Result = -1) and (Found > 0) do begin if Fast then Found := BoyerMoore(PChar(AnsiUpperCase(Search)), PChar(AnsiUpperCase(Copy(Text, FromPos, Len)))) else Found := Pos(AnsiUpperCase(Search), AnsiUpperCase(Copy(Text, FromPos, Len))); if Found > 0 then begin Result := Found + FromPos - 1; SearchLen := Length(Search); TextLen := Length(Text); FromPos := Result + SearchLen; // is match-case required and does it? if MatchCase and (AnsiCompareStr(Search, Copy(Text, Result, SearchLen)) <> 0) then Result := -1 // is whole-word-only required and is it? else if WholeWord and (SearchLen < TextLen) then begin // check for extremes... S := Copy(Text, Result - 1, SearchLen + 2); // check for match at beginning or end of string if Result = 1 then S := Copy(' ' + S, 1, SearchLen + 2); if Result - 1 + SearchLen + 1 > TextLen then S := Copy(S + ' ', Length(S) - SearchLen-2, SearchLen + 2); if not IsValidWholeWord(S) then result := -1; end; end; end; end; { invert and search } function FindInTextRev(const Text, Search: string; FromPos, Len: Integer; Fast, WholeWord, MatchCase: Boolean): Longint; begin Result := FindInText(StrRev(Text), StrRev(Search), FromPos, Len, Fast, WholeWord, MatchCase); if Result > -1 then Result := Length(Text) - (Result - 1) - (Length(Search) - 1); end; //=== { TJvFindReplace } ===================================================== constructor TJvFindReplace.Create(AOwner: TComponent); begin inherited Create(AOwner); FOwner := AOwner; FHelpContext := 0; FShowDialogs := True; FPosition := Point(-1, -1); end; procedure TJvFindReplace.Loaded; begin inherited Loaded; UpdateDialogs; end; procedure TJvFindReplace.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FEditControl) then FEditControl := nil; end; procedure TJvFindReplace.Find; begin TestEditAssigned; UpdateDialogs; if FShowDialogs then FFindDialog.Execute else DoOnFind(FFindDialog); end; procedure TJvFindReplace.FindAgain; begin TestEditAssigned; UpdateDialogs; DoOnFind(FFindDialog); end; procedure TJvFindReplace.Replace; begin TestEditAssigned; UpdateDialogs; if FShowDialogs then FReplaceDialog.Execute else DoOnReplace(FReplaceDialog); end; procedure TJvFindReplace.ReplaceAll(const SearchText, ReplaceText: string); var Txt: string; FoundPos: Longint; SLen, RLen, TLen: Integer; Terminate: Boolean; WholeWord, MatchCase: Boolean; begin TestEditAssigned; Terminate := False; UpdateDialogs; WholeWord := frWholeWord in FOptions; MatchCase := frMatchCase in FOptions; Txt := GetEditText; SLen := Length(SearchText); RLen := Length(ReplaceText); TLen := Length(Txt); FoundPos := FindInText(Txt, SearchText, GetEditSelStart + GetEditSelLength, TLen, FFast, WholeWord, MatchCase); if FoundPos > -1 then begin DoReplacingAll; FNumberReplaced := 0; while FoundPos > -1 do begin Inc(FNumberReplaced); Delete(Txt, FoundPos, SLen); Insert(ReplaceText, Txt, FoundPos); FoundPos := FindInText(Txt, SearchText, FoundPos + RLen + 1, TLen + (RLen - SLen), FFast, WholeWord, MatchCase); DoProgress(FoundPos, Terminate); if Terminate then Exit; end; SetEditText(Txt); DoReplacedAll(FReplaceDialog); end else DoFailed(FReplaceDialog); end; function TJvFindReplace.ReplaceOne(Sender: TObject): Boolean; var Equal: Integer; S, R: string; begin Result := False; if FShowDialogs then begin S := TReplaceDialog(Sender).FindText; R := TReplaceDialog(Sender).ReplaceText; end else begin S := FFindText; R := FReplaceText; end; if frMatchCase in TFindDialog(Sender).Options then Equal := AnsiCompareStr(GetEditSelText, S) else Equal := AnsiCompareText(GetEditSelText, S); if Equal = 0 then begin Result := True; SetEditSelText(R); SetEditFocus; end; end; procedure TJvFindReplace.NeedDialogs; begin if not Assigned(FFindDialog) then begin FFindDialog := TFindDialog.Create(Self); FFindDialog.FindText := FFindText; FFindDialog.OnFind := DoOnFind; FFindDialog.Position := FPosition; end; if not Assigned(FReplaceDialog) then begin FReplaceDialog := TReplaceDialog.Create(Self); FReplaceDialog.FindText := FFindText; FReplaceDialog.ReplaceText := FReplaceText; FReplaceDialog.OnFind := DoOnFind; FReplaceDialog.OnReplace := DoOnReplace; FReplaceDialog.Position := FPosition; end; end; procedure TJvFindReplace.UpdateDialogs; begin if not (csDesigning in ComponentState) and not (csLoading in ComponentState) then begin NeedDialogs; FFindDialog.Position := FPosition; FFindDialog.Options := FOptions; FFindDialog.HelpContext := FHelpContext; FFindDialog.FindText := FFindText; FReplaceDialog.Position := FPosition; FReplaceDialog.Options := FOptions; FReplaceDialog.HelpContext := FHelpContext; FReplaceDialog.FindText := FFindText; FReplaceDialog.ReplaceText := FReplaceText; end; end; procedure TJvFindReplace.UpdateProperties(Sender: TObject); begin if Sender is TFindDialog then begin FPosition := TFindDialog(Sender).Position; FOptions := TFindDialog(Sender).Options; FHelpContext := TFindDialog(Sender).HelpContext; FFindText := TFindDialog(Sender).FindText; end; if Sender is TReplaceDialog then FReplaceText := TReplaceDialog(Sender).ReplaceText; end; procedure TJvFindReplace.DoOnFind(Sender: TObject); var FoundPos: Longint; Offset: Integer; WholeWord, MatchCase: Boolean; begin /// update the local properties with the current values from the dialog /// in case the user has changed the options (or the find/replace text) UpdateProperties(Sender); WholeWord := frWholeWord in FOptions; MatchCase := frMatchCase in FOptions; if not (frDown in FOptions) then begin Offset := GetEditSelStart - 1; if Offset <= 0 then Offset := 1; FoundPos := FindInTextRev(GetEditText, FFindText, Length(GetEditText) - Offset, Length(GetEditText), FFast, WholeWord, MatchCase) end else begin Offset := GetEditSelStart + GetEditSelLength + 1; FoundPos := FindInText(GetEditText, FFindText, Offset, Length(GetEditText), FFast, WholeWord, MatchCase); end; if FoundPos > -1 then begin SetEditFocus; SetEditSelStart(FoundPos - 1); SetEditSelLength(Length(FFindText)); if GetEditHandle <> 0 then SendMessage(GetEditHandle, EM_SCROLLCARET, 0, 0); if Assigned(FOnFind) then FOnFind(Self); end else DoFailed(Sender); end; procedure TJvFindReplace.DoOnReplace(Sender: TObject); begin UpdateProperties(Sender); if frReplaceAll in FOptions then begin ReplaceAll(FFindText, FReplaceText); if Assigned(FOnReplace) then FOnReplace(Self); end else begin if GetEditSelLength < 1 then DoOnFind(Sender); if GetEditSelLength < 1 then Exit; ReplaceOne(Sender); if Assigned(FOnReplace) then FOnReplace(Self); DoOnFind(Sender); end; end; procedure TJvFindReplace.DoOnShow(Sender: TObject); begin TestEditAssigned; UpdateDialogs; if Assigned(FOnShow) then FOnShow(Self); end; procedure TJvFindReplace.DoOnClose(Sender: TObject); begin TestEditAssigned; UpdateProperties(Sender); UpdateDialogs; if Assigned(FOnClose) then FOnClose(Self); end; procedure TJvFindReplace.DoFailed(Sender: TObject); var FCaption: string; begin TestEditAssigned; UpdateProperties(Sender); if Assigned(FOnNotFound) then FOnNotFound(Self); if not FShowDialogs then Exit; if Sender = FReplaceDialog then FCaption := RsReplaceCaption else FCaption := RsFindCaption; MessageBox( TFindDialog(Sender).Handle, PChar(Format(RsNotFound, [FFindText])), PChar(FCaption), MB_OK or MB_ICONINFORMATION); end; procedure TJvFindReplace.DoReplacingAll; begin if Assigned(FOnReplacingAll) then FOnReplacingAll(Self); end; procedure TJvFindReplace.DoReplacedAll(Sender: TObject); begin UpdateProperties(Sender); if FShowDialogs then begin MessageBox( TFindDialog(Sender).Handle, PChar(Format(RsXOccurencesReplaced, [FNumberReplaced, FFindText])), PChar(RsReplaceCaption), MB_OK or MB_ICONINFORMATION); end; if Assigned(FOnReplacedAll) then FOnReplacedAll(Self, FNumberReplaced); end; procedure TJvFindReplace.DoProgress(Position: Integer; var Terminate: Boolean); begin if Assigned(FOnProgress) then FOnProgress(Self, Position, Terminate); end; procedure TJvFindReplace.SetPosition(Value: TPoint); begin FPosition := Value; UpdateDialogs; end; procedure TJvFindReplace.SetDialogTop(Value: Integer); begin FPosition.Y := Value; UpdateDialogs; end; procedure TJvFindReplace.SetDialogLeft(Value: Integer); begin FPosition.X := Value; UpdateDialogs; end; procedure TJvFindReplace.SetOptions(Value: TFindOptions); begin FOptions := Value; UpdateDialogs; end; procedure TJvFindReplace.SetFindText(const Value: string); begin FFindText := Value; UpdateDialogs; end; procedure TJvFindReplace.SetShowDialogs(Value: Boolean); begin if FShowDialogs <> Value then FShowDialogs := Value; if not Value then begin NeedDialogs; FFindDialog.CloseDialog; FReplaceDialog.CloseDialog; end; end; procedure TJvFindReplace.SetReplaceText(const Value: string); begin FReplaceText := Value; UpdateDialogs; end; procedure TJvFindReplace.SetHelpContext(Value: THelpContext); begin FHelpContext := Value; UpdateDialogs; end; function TJvFindReplace.GetTop: Integer; begin Result := FPosition.Y; end; function TJvFindReplace.GetLeft: Integer; begin Result := FPosition.X; end; procedure TJvFindReplace.SetEditControl(Value: TJvEditControlName); begin if FEditControl <> nil then FEditControl.RemoveFreeNotification(Self); FEditControl := Value; if Value <> nil then Value.FreeNotification(Self); if Value is TCustomEdit then FEditKind := etCustomEdit else if Value is TJvCustomEditor then FEditKind := etJvCustomEditor else FEditKind := etEmpty; end; procedure TJvFindReplace.TestEditAssigned; begin if not Assigned(FEditControl) then raise EJVCLException.CreateRes(@RsENoEditAssigned); end; function TJvFindReplace.GetEditText: string; begin case FEditKind of etCustomEdit: Result := TCustomEdit(FEditControl).Text; etJvCustomEditor: Result := TJvCustomEditor(FEditControl).Lines.Text; else Result := ''; end; end; function TJvFindReplace.GetEditSelText: string; begin case FEditKind of etCustomEdit: Result := TCustomEdit(FEditControl).SelText; etJvCustomEditor: Result := TJvCustomEditor(FEditControl).SelText; else Result := ''; end; end; function TJvFindReplace.GetEditSelStart: Integer; begin case FEditKind of etCustomEdit: Result := TCustomEdit(FEditControl).SelStart; etJvCustomEditor: Result := TJvCustomEditor(FEditControl).SelStart; else Result := 0; end; end; function TJvFindReplace.GetEditSelLength: Integer; begin case FEditKind of etCustomEdit: Result := TCustomEdit(FEditControl).SelLength; etJvCustomEditor: Result := TJvCustomEditor(FEditControl).SelLength; else Result := 0; end; end; function TJvFindReplace.GetEditHandle: HWND; begin case FEditKind of etCustomEdit: Result := TCustomEdit(FEditControl).Handle; etJvCustomEditor: Result := TJvCustomEditor(FEditControl).Handle; else Result := HWND(0); end; end; procedure TJvFindReplace.SetEditText(const Text: string); begin case FEditKind of etCustomEdit: TCustomEdit(FEditControl).Text := Text; etJvCustomEditor: TJvCustomEditor(FEditControl).Lines.Text := Text; end; end; procedure TJvFindReplace.SetEditSelText(const Text: string); begin case FEditKind of etCustomEdit: TCustomEdit(FEditControl).SelText := Text; etJvCustomEditor: TJvCustomEditor(FEditControl).SelText := Text; end; end; procedure TJvFindReplace.SetEditSelStart(Start: Integer); begin case FEditKind of etCustomEdit: TCustomEdit(FEditControl).SelStart := Start; etJvCustomEditor: TJvCustomEditor(FEditControl).SelStart := Start; end; end; procedure TJvFindReplace.SetEditSelLength(Length: Integer); begin case FEditKind of etCustomEdit: TCustomEdit(FEditControl).SelLength := Length; etJvCustomEditor: TJvCustomEditor(FEditControl).SelLength := Length; end; end; procedure TJvFindReplace.SetEditFocus; begin case FEditKind of etCustomEdit: TCustomEdit(FEditControl).SetFocus; etJvCustomEditor: TJvCustomEditor(FEditControl).SetFocus; end; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit Utils; interface uses System.Generics.Collections, System.SysUtils; type TMyList<T> = class (TList<T>) type TPredicateRef = reference to function(X : T) : Boolean; public function Where(Lambda : TPredicateRef) : TList<T>; function Any(Lambda : TPredicateRef) : Boolean; end; implementation function TMyList<T>.Where(Lambda: TPredicateRef): TList<T>; var X: T; begin Result := TMyList<T>.Create; for X in Self do if Lambda(X) then Result.Add(X); end; function TMyList<T>.Any(Lambda: TPredicateRef): Boolean; var X: T; begin Result := False; for X in Self do try if Lambda(X) then Exit(True); except end; end; end.
unit Aurelius.Commands.CommandPerformerFactory; {$I Aurelius.inc} interface uses Generics.Collections, Aurelius.Commands.AbstractCommandPerformer, Aurelius.Commands.Listeners, Aurelius.Drivers.Interfaces, Aurelius.Mapping.Explorer, Aurelius.Sql.Interfaces; type TCommandPerformerFactory = class private FConnection: IDBConnection; FSQLGenerator: ISQLGenerator; FExecutionListeners: TList<ICommandExecutionListener>; FEntityManager: TObject; FExplorer: TMappingExplorer; public constructor Create(Conn: IDBConnection; SQLGenerator: ISQLGenerator; EntityManager: TObject; Explorer: TMappingExplorer); virtual; destructor Destroy; override; procedure AddExecutionListener(Listener: ICommandExecutionListener); function GetCommand<T: constructor, TAbstractSQLPerformer>(Clazz: TClass): T; end; implementation uses SysUtils; { TCommandPerformerFactory } procedure TCommandPerformerFactory.AddExecutionListener( Listener: ICommandExecutionListener); begin FExecutionListeners.Add(Listener); end; constructor TCommandPerformerFactory.Create(Conn: IDBConnection; SQLGenerator: ISQLGenerator; EntityManager: TObject; Explorer: TMappingExplorer); begin FConnection := Conn; FSQLGenerator := SQLGenerator; FEntityManager := EntityManager; FExplorer := Explorer; FExecutionListeners := TList<ICommandExecutionListener>.Create; end; destructor TCommandPerformerFactory.Destroy; begin FExecutionListeners.Free; inherited; end; function TCommandPerformerFactory.GetCommand<T>(Clazz: TClass): T; var L: ICommandExecutionListener; begin {$IFDEF TRIAL} if Now > EncodeDate(2014, 6, 1) then raise Exception.Create('TMS Aurelius trial version expired. Please purchase a license for commercial usage.'); {$ENDIF} Result := T.Create; // The order which we set the following injected objects is important // TODO: later change this to be passed in the constructor of command. Result.SetConnection(FConnection); Result.SetSQLGenerator(FSQLGenerator); Result.SetExplorer(FExplorer); Result.SetClass(Clazz); Result.SetEntityManager(FEntityManager); for L in FExecutionListeners do Result.AddExecutionListener(L); end; end.
{* * TV Tool Box Version 2.0 * Copyright (c) 1992, 1993 by Richard W. Hansen * All Rights Reserved * * * TvConst.pas * Turbo Vision command constants for Turbo Pascal 7.0. * *} UNIT TvConst; {$I TVDEFS.INC} INTERFACE { Some keyboard constants Borland left out. } CONST kbCtrlA = $1E01; kbCtrlB = $3002; kbCtrlC = $2E03; kbCtrlD = $2004; kbCtrlE = $1205; kbCtrlF = $2106; kbCtrlG = $2207; kbCtrlH = $2308; kbCtrlI = $1709; kbCtrlJ = $240A; kbCtrlK = $250B; kbCtrlL = $260C; kbCtrlM = $320D; kbCtrlN = $310E; kbCtrlO = $180F; kbCtrlP = $1910; kbCtrlQ = $1011; kbCtrlR = $1312; kbCtrlS = $1F13; kbCtrlT = $1414; kbCtrlU = $1615; kbCtrlV = $2F16; kbCtrlW = $1117; kbCtrlX = $2D18; kbCtrlY = $1519; kbCtrlZ = $2C1A; CONST cmTVTtool1 = 246; cmFirstPage = cmTVTtool1; cmLastPage = cmFirstPage + 1; cmNextPage = cmFirstPage + 2; cmPrevPage = cmFirstPage + 3; cmMaximize = cmFirstPage + 4; cmMinimize = cmFirstPage + 5; cmStartJob = cmFirstPage + 6; cmPauseJob = cmFirstPage + 7; cmContinueJob = cmFirstPage + 8; cmCancelJob = cmFirstPage + 9; cmTVTtool2 = 10000; cmMarkStart = cmTVTtool2; cmMarkEnd = cmTVTtool2 + 1000; cmCursorMoved = cmTVTtool2 + 1001; cmUpdateView = cmTVTtool2 + 1002; cmEditView = cmTVTtool2 + 1003; cmPrint = cmTVTtool2 + 1004; cmJobComplete = cmTVTtool2 + 1005; cmPopMenu = cmTVTtool2 + 1006; cmTakeItem = cmTVTtool2 + 1007; cmDisplayStr = cmTVTtool2 + 1008; cmDisplayClr = cmTVTtool2 + 1009; cmDragView = cmTVTtool2 + 1010; cmIdentify = cmTVTtool2 + 1011; cmSetId = cmTVTtool2 + 1012; cmFieldError = cmTVTtool2 + 1013; CONST ofPosIndicator = $1000; ofVScrollBar = $2000; ofHScrollBar = $4000; (* Picture strings for TPxPictureValidators Type of character Character Description -------------------------------------------------------------------- Special # Accept only a digit ? Accept only a letter (case-insensitive) & Accept only a letter, force to uppercase @ Accept any character ! Accept any character, force to uppercase Match ; Take next character literally * Repetition count [] Option {} Grouping operators , Set of alternatives All others Taken literally *) CONST UnsignedPic1 = '#[#][#]*{[;,]###}'; { unsigned int with optional commas } CONST UnsignedPic2 = '#[#][#]*{;,###}'; { unsigned int with commas } CONST SignedPic1 = '[-]#[#][#]*{[;,]###}'; { signed int with optional commas } CONST SignedPic2 = '[-]#[#][#]*{;,###}'; { { signed int with commas } CONST MoneyPic1 = '[$]*#.{##,00}'; { dollars, with comma and optinal dollar sign } CONST MoneyPic2 = '$*#{.##,.00}'; { dollars, with comma and dollar sign } CONST DatePic1 = '#[#]/#[#]/##'; { date with 2 digit year (dd/mm/yy or mm/dd/yy) } CONST DatePic2 = '#[#]/#[#]/##[##]'; { date with 2 or 4 digit year (mm/dd/yy or mm/dd/yyyy) } CONST DatePic3 = '#[#]/#[#]/####'; { date with 4 digit year (mm/dd/yyyy) } CONST TimePic1 = '{##}:{##}[:{##}]'; { HH:MM:SS with optional seconds } CONST TimePic2 = '{##}:{##}:{##}'; { HH:MM:SS } CONST PhonePic1 = '[(###) ]###-####'; { phone number with optional area code } CONST PhonePic2 = '(###) ###-####'; { phone number with area code } CONST SSNPic = '###-##-####'; CONST FirstCharUpPic = '*{&*? }'; { uppercase the first char of every word } CONST FilenamePic = '{&*7[&]}.{*3[&]}'; { filename (no path) with extension } IMPLEMENTATION END.
unit orm.where; interface uses System.SysUtils, System.DateUtils, System.Variants, System.Generics.Collections; type TWOperador = (woNone, woEquals, woMore, woLess, woMoreEquals, woLessEquals, woDif, woLike, woIs, woIsNot, woBetween, woBetweenField, woIn, woInNot); type TWClausule = (wcNone, wcAnd, wcOr, wcNot, wcIn); type TWLike = (wlStart, wlEnd, wlBoth); Type TWhere = Class private FTable : String; FField : String; FValue : String; FValueMax : String; FCoalesce : String; FSetWhere : Boolean; FOperador : TWOperador; FLike : TWLike; FClausule : TWClausule; FOwner : TWhere; public Constructor Create(Owner : TWhere); Overload; Constructor Create(Table, Field, Value : String; Operador : TWOperador; Owner : TWhere = nil); Overload; function ToString : String; Override; function &And : TWhere; function &Or : TWhere; function Add(Value : TWhere) : TWhere; Overload; function Add(Value : String; W : TWClausule = wcAnd) : TWhere; Overload; function Equal(Table, Field : String; Value : Variant) : TWhere; Overload; function Equal(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function Equal(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function MoreEqual(Table, Field : String; Value : Variant) : TWhere; Overload; function MoreEqual(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function MoreEqual(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function LessEqual(Table, Field : String; Value : Variant) : TWhere; Overload; function LessEqual(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function LessEqual(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function More(Table, Field : String; Value : Variant) : TWhere; Overload; function More(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function More(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function Less(Table, Field : String; Value : Variant) : TWhere; Overload; function Less(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function Less(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function Dif(Table, Field : String; Value : Variant) : TWhere; Overload; function Dif(Table, Field : String; Value : Variant; Size : Integer) : TWhere; Overload; function Dif(Table, Field : String; Value, Coalesce : Variant; Size : Integer = 0) : TWhere; Overload; function Like(Table, Field : String; Value : Variant; L : TWLike = wlBoth) : TWhere; Overload; function Like(Table, Field : String; Values : Array Of Variant; L : TWLike = wlBoth) : TWhere; Overload; function InYes(Table, Field : String; Value : String) : TWhere; Overload; function InYes(Table, Field : String; Values : Array Of Variant) : TWhere; Overload; function InNot(Table, Field : String; Value : String) : TWhere; Overload; function InNot(Table, Field : String; Values : Array Of Variant) : TWhere; Overload; function Between(Table, Field : String; ValueMin, ValueMax : TDateTime; IsDateTime : Boolean) : TWhere; Overload; function Between(Table, Field : String; ValueMin, ValueMax : Variant; Size : Integer) : TWhere; Overload; function Between(Value : Variant; Table, FieldMin, FieldMax : String) : TWhere; Overload; End; function OperadorToStr(O : TWOperador) : String; function ClausuleToStr(C : TWClausule) : String; function Where(IsWhere : Boolean = False) : TWhere; implementation uses sql.utils; function OperadorToStr(O: TWOperador): String; begin Result := ''; Case O Of woEquals : Result := ' = '; woDif : Result := ' <> '; woMore : Result := ' > '; woMoreEquals : Result := ' >= '; woLessEquals : Result := ' <= '; woLess : Result := ' < '; woLike : Result := ' like '; woIs : Result := ' is '; woIsNot : Result := ' is not '; woBetween, woBetweenField : Result := ' between '; woIn : Result := ' in '; woInNot : Result := ' not in '; End; end; function ClausuleToStr(C: TWClausule): String; begin Result := ''; Case C Of wcAnd : Result := ' and '; wcOr : Result := ' or '; wcNot : Result := ' not '; wcIn : Result := ' in '; End; end; { TWhere } function TWhere.Add(Value: TWhere): TWhere; begin Result := TWhere.Create(Self); Result.FValue := Value.ToString; end; function TWhere.Add(Value: String; W : TWClausule): TWhere; begin Result := TWhere.Create(Self); If (Value <> '') Then Begin Result.FValue := Value; Result.FClausule := W; End; end; function TWhere.&And: TWhere; begin Result := TWhere.Create(Self); Result.FClausule := wcAnd; end; function TWhere.Between(Value: Variant; Table, FieldMin, FieldMax: String): TWhere; begin Result := TWhere.Create(Table,FieldMin,Value.SQLFormat(0,False),woBetweenField,Self); Result.FValueMax := FieldMax; end; function TWhere.Between(Table, Field: String; ValueMin, ValueMax: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,ValueMin.SQLFormat(Size,False),woBetween,Self); Result.FValueMax := ValueMax.SQLFormat(Size,False); end; constructor TWhere.Create(Owner: TWhere); begin FOwner := Owner; end; function TWhere.Between(Table, Field: String; ValueMin, ValueMax : TDateTime; IsDateTime : Boolean): TWhere; begin If IsDateTime Then Begin Result := TWhere.Create(Table,Field,SQLFormat(ValueMin,False),woBetween,Self); Result.FValueMax := SQLFormat(ValueMax,False); If (TimeOf(ValueMax) = 0) Then Result.FValueMax := SQLFormat(EndOfTheDay(ValueMax),False); End Else Begin Result := TWhere.Create(Table,Field,SQLFormat(TDate(ValueMin),False),woBetween,Self); Result.FValueMax := SQLFormat(TDate(ValueMax),False); End; end; constructor TWhere.Create(Table, Field, Value : String; Operador : TWOperador; Owner : TWhere); begin FTable := Table; FField := Field; FValue := Value; FOperador := Operador; FOwner := Owner; end; function TWhere.Like(Table, Field: String; Value: Variant; L: TWLike): TWhere; begin Case L Of wlStart : Value := '%' + Value; wlEnd : Value := Value + '%'; wlBoth : Value := '%'+ Value + '%'; End; Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woLike,Self); Result.FLike := L; end; function TWhere.ToString : String; var S : String; begin S := '%s.%s'; If FTable.IsEmpty Then S := '%s%s'; If FSetWhere Then Result := ' where ' Else If (FOperador = woNone) And (FClausule = wcNone) And (not FValue.IsEmpty) Then Result := Format('(%s)',[FValue]) Else If not FField.IsEmpty Then Begin If (FOperador = woBetween) Then Result := Format('('+ S +' %s %s and %s)',[FTable,FField,OperadorToStr(FOperador),FValue,FValueMax]) Else If (FOperador = woBetweenField) Then Result := Format('(%s %s '+ S +' and '+ S +')',[FValue,OperadorToStr(FOperador),FTable,FField,FTable,FValueMax]) Else If (FOperador in [woIn,woInNot]) Then Result := Format('('+ S +' %s (%s))',[FTable,FField,OperadorToStr(FOperador),FValue]) Else Begin If (FValue.Trim = 'null') Then If (FOperador = woEquals) Then FOperador := woIs Else If (FOperador = woDif) Then FOperador := woIsNot; If not FCoalesce.IsEmpty Then Result := Format('(coalesce('+ S +',%s) %s %s)',[FTable,FField,FCoalesce,OperadorToStr(FOperador),FValue]) Else Result := Format('('+ S +' %s %s)',[FTable,FField,OperadorToStr(FOperador),FValue]); End; End Else If (FClausule <> wcNone) And (not FValue.IsEmpty) Then Result := Format('(%s)',[FValue]) + ClausuleToStr(FClausule) Else Result := ClausuleToStr(FClausule); If Assigned(FOwner) Then Result := FOwner.ToString + Result; Destroy; end; function TWhere.Dif(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woDif,Self); end; function TWhere.Dif(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woDif,Self); end; function TWhere.Equal(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woEquals,Self); end; function TWhere.Equal(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woEquals,Self); end; function TWhere.Equal(Table, Field: String; Value, Coalesce: Variant; Size : Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woEquals,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; function TWhere.InNot(Table, Field: String; Values: array of Variant): TWhere; var S : String; V : Variant; begin For V in Values Do If S.IsEmpty Then S := V.SQLFormat(0,False) Else S := S +','+ V.SQLFormat(0,False); Result := InNot(Table,Field,S); end; function TWhere.InNot(Table, Field, Value: String): TWhere; begin Result := TWhere.Create(Table,Field,Value,woInNot,Self); end; function TWhere.InYes(Table, Field, Value: String): TWhere; begin Result := TWhere.Create(Table,Field,Value,woIn,Self); end; function TWhere.InYes(Table, Field: String; Values: array of Variant): TWhere; var S : String; V : Variant; begin For V in Values Do If S.IsEmpty Then S := V.SQLFormat(0,False) Else S := S +','+ V.SQLFormat(0,False); Result := InYes(Table,Field,S); end; function TWhere.Less(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woLess,Self); end; function TWhere.Less(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woLess,Self); end; function TWhere.LessEqual(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woLessEquals,Self); end; function TWhere.LessEqual(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woLessEquals,Self); end; function TWhere.More(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woMore,Self); end; function TWhere.More(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woMore,Self); end; function TWhere.MoreEqual(Table, Field: String; Value: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woMoreEquals,Self); end; function TWhere.&Or: TWhere; begin Result := TWhere.Create(Self); Result.FClausule := wcOr; end; function TWhere.MoreEqual(Table, Field: String; Value: Variant): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(0,False),woMoreEquals,Self); end; function Where(IsWhere : Boolean) : TWhere; Begin Result := TWhere.Create; Result.FSetWhere := IsWhere; End; function TWhere.Dif(Table, Field: String; Value, Coalesce: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woDif,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; function TWhere.Less(Table, Field: String; Value, Coalesce: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woLess,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; function TWhere.LessEqual(Table, Field: String; Value, Coalesce: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woLessEquals,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; function TWhere.Like(Table, Field: String; Values : Array of Variant; L: TWLike): TWhere; var V : Variant; begin Result := nil; For V in Values Do If not Assigned(Result) Then Result := Like(Table,Field,V,L) Else Result := Result;//.Or.Like(Table,Field,V,L); end; function TWhere.More(Table, Field: String; Value, Coalesce: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woMore,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; function TWhere.MoreEqual(Table, Field: String; Value, Coalesce: Variant; Size: Integer): TWhere; begin Result := TWhere.Create(Table,Field,Value.SQLFormat(Size,False),woMoreEquals,Self); Result.FCoalesce := Coalesce.SQLFormat(Size,False); end; end.
unit DC.VCL.PasswordForm; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Dialogs, Messages, aOPCSource, aOPCAuthorization; type TPasswordForm = class(TForm) OKBtn: TButton; CancelBtn: TButton; lUser: TLabel; lPassword: TLabel; cbUser: TComboBox; ePassword: TEdit; bChangePassword: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure bChangePasswordMouseLeave(Sender: TObject); procedure bChangePasswordMouseEnter(Sender: TObject); procedure bChangePasswordClick(Sender: TObject); procedure FormShow(Sender: TObject); private FOPCSource: TaOPCSource; FShowOnTaskBar: Boolean; procedure SetOPCSource(const Value: TaOPCSource); protected procedure CreateParams(var Params: TCreateParams); override; procedure WMSyscommand(var Message: TWmSysCommand); message WM_SYSCOMMAND; public constructor CreateAndShowOnTaskBar(AOwner: TComponent); property OPCSource: TaOPCSource read FOPCSource write SetOPCSource; class function Execute(aAuth: TaOPCAuthorization): Boolean; end; implementation uses aOPCConnectionList, DC.Resources, DC.VCL.ChangePasswordForm; {$R *.dfm} procedure TPasswordForm.bChangePasswordClick(Sender: TObject); var i: integer; //ok: boolean; //aOPCSource: TaOPCSource; aConnection: TOPCConnectionCollectionItem; aConnName: string; aOPCConnectionList: TaOPCConnectionList; begin if Assigned(OPCSource) then begin with TfChangePassword.Create(self) do begin OPCSource := Self.OPCSource; eUser.Text := Self.cbUser.Text; eOldPassword.Text := Self.ePassword.Text; if ShowModal = mrOk then begin //ok := true; aConnection := nil; try if OPCSource.Owner is TaOPCConnectionList then begin aOPCConnectionList := TaOPCConnectionList(OPCSource.Owner); for i := 0 to aOPCConnectionList.Items.Count - 1 do begin aConnection := aOPCConnectionList.Items[i]; if not aConnection.Enable then Continue; aConnection.OPCSource.ChangePassword(eUser.Text, eOldPassword.Text, eNewPassword.Text); end; end else OPCSource.ChangePassword(eUser.Text, eOldPassword.Text, eNewPassword.Text); ShowMessage(sPasswordChangedSuccessfuly); ePassword.Text := eNewPassword.Text; ePassword.SelectAll; PostMessage(Self.OKBtn.Handle, CM_ACTIVATE, 0, 0); except on e: Exception do begin if Assigned(aConnection) then aConnName := aConnection.DisplayName else aConnName := ''; MessageDlg(Format(sUnableChangePasswordFmt, [aConnName]), mtError, [mbOK], 0); end; end; end; end; end; end; procedure TPasswordForm.bChangePasswordMouseEnter(Sender: TObject); begin bChangePassword.Font.Color := clHighlight; bChangePassword.Font.Style := [fsUnderline]; end; procedure TPasswordForm.bChangePasswordMouseLeave(Sender: TObject); begin bChangePassword.Font.Color := clGrayText; bChangePassword.Font.Style := []; end; constructor TPasswordForm.CreateAndShowOnTaskBar(AOwner: TComponent); begin FShowOnTaskBar := true; inherited Create(AOwner); end; procedure TPasswordForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); // http://www.transl-gunsmoker.ru/2009/03/windows-vista-delphi-1.html // для каждой формы, для которой мы хотим иметь кнопку на панели задач // нам нужно переопределить CreateParams if FShowOnTaskBar then Params.ExStyle := Params.ExStyle and not WS_EX_TOOLWINDOW or WS_EX_APPWINDOW; end; class function TPasswordForm.Execute(aAuth: TaOPCAuthorization): Boolean; var f: TPasswordForm; User, Password: string; begin Result := False; f := TPasswordForm.CreateAndShowOnTaskBar(nil); try User := aAuth.User; f.OPCSource := aAuth.OPCSource; f.cbUser.Items.Text := f.OPCSource.GetUsers; f.cbUser.ItemIndex := f.cbUser.Items.IndexOf(User); if f.ShowModal = mrOk then begin try User := f.cbUser.Text; Password := f.ePassword.Text; Result := f.OPCSource.Login(User, Password); if not Result then MessageDlg( Format('У пользователя %s недостаточно прав для работы с системой!', [User]), TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0) else begin aAuth.User := User; aAuth.Password := Password; end; except on e: Exception do MessageDlg(e.Message, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0); end; end; finally f.Free; end; end; procedure TPasswordForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = 86) and (ssAlt in Shift) then bChangePasswordClick(self); //ShowMessage(Chr(Key)); end; procedure TPasswordForm.FormShow(Sender: TObject); begin if cbUser.Text = '' then ActiveControl := cbUser else ActiveControl := ePassword; bChangePassword.Enabled := Assigned(OPCSource); //Application.BringToFront; //SetForegroundWindow(Application.Handle); end; procedure TPasswordForm.SetOPCSource(const Value: TaOPCSource); begin FOPCSource := Value; end; procedure TPasswordForm.WMSyscommand(var Message: TWmSysCommand); begin // http://www.transl-gunsmoker.ru/2009/03/windows-vista-delphi-1.html // для каждой формы, которая имеет кнопку в панели задач и может // минимизироваться, нам надо обрабатывать оконное сообщение WM_SYSCOMMAND case (Message.CmdType and $FFF0) of SC_MINIMIZE: begin ShowWindow(Handle, SW_MINIMIZE); Message.Result := 0; end; SC_RESTORE: begin ShowWindow(Handle, SW_RESTORE); Message.Result := 0; end; else inherited; end; end; end.
(* L'unité BZTypesHelper surcharge les assistants originaux de FPC pour les types. @Br Elle ajoute des fonctions supplémentaires pour tous les types d’assistants. @br Elle inclut également un assistant spécialisée pour le type TDateTime. ------------------------------------------------------------------------------------------------------------- @created(2018-04-13) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(Last Update : 21/04/2018 ) @item(25/11/2017 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes :)@br L'assistant pour les chaines de caractères traite directement avec UTF8 ------------------------------------------------------------------------------------------------------------- @bold(Dépendances) : None ------------------------------------------------------------------------------------------------------------- @bold(Credits :)@br @unorderedList( @item(FPC/Lazarus) @item(J.Delauney) ) ------------------------------------------------------------------------------------------------------------- LICENCE : MPL/GPL ------------------------------------------------------------------------------------------------------------- *) Unit BZTypesHelpers; //============================================================================== // /!\ Dont' Work with trunk versions {$mode objfpc}{$H+} {$modeswitch advancedrecords} {$modeswitch typehelpers} {.$mode delphi} // Work with trunk version only if Delphi Mode is defined {$i ..\bzscene_options.inc} //============================================================================== Interface Uses Classes, SysUtils {$IFDEF WINDOWS} , Windows {$ENDIF}; //============================================================================== Const { Nombre aléatoire pour le calcul du 'hash' d'une chaine de caractères} cHash1 = 130469; { Constante pour le calcul du 'hash' d'une chaine de caractères. Plus la taille est grande, plus le risque de collision est faible } cHash2 = MaxInt Shr 4; Type { Assistant pour le type Boolean} TBooleanHelper = type helper for Boolean public { Convertis le boolean en chaîne de caractères } function ToString(Const DefTrue : String = 'True'; Const defFalse : String = 'False'): String; end; { Assistant pour le type Char } TCharHelper = type helper for Char public { Vérifie si le caractère est un Alpha } function IsAlpha: Boolean; { Vérifie si le caractère est un Numérique } function IsNumeric: Boolean; { Retourne le code du caractère } function ToCharCode : Integer; { Convertie le caractère en majuscule } function ToUpper : Char; { Convertie le caractère en minuscule } function ToLower : Char; end; { Assistant pour le type Byte } TByteHelper = type helper for Byte public const MaxValue = 255; // < Valeur maximum pour le type Byte MinValue = 0; // < Valeur minimum pour le type Byte NormalizedRatio : Single = 1/255; // < Ratio normalisé pour le type Byte public { Convertir une chaîne de caractères en sa représentation en Byte@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Byte=0):Boolean; overload; { Convertir la valeur de la variable Byte en chaîne de caractères } function ToString: string; { Retourne la plus petite valeur entre la valeur de la variable Byte et le paramètre "vMin" } function Min(vMin:Byte):Byte; { Retourne la plus grande valeur entre la valeur de la variable Byte et le paramètre "vMax" } function Max(vMax:Byte):Byte; { Vérifie si la valeur de la variable Byte est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Byte): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Byte; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Byte):Byte; { S'assure que la valeur de la variable Byte est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Byte):Byte; { Retourne la représentation Booleenne de la variable Byte. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la représentation hexadécimal sous forme de chaine de caractères } Function ToHexString: string; { Retourne la valeur normalisée de la variable Byte. Dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable Byte (1/Value) } function Reciprocal: Single; end; { Assistant pour le type ShortInt } TShortIntHelper = type helper for ShortInt public const MaxValue = 127; // < Valeur maximum pour le type ShortInt MinValue = -128; // < Valeur minimum pour le type ShortInt NormalizedRatio : single = 1 / 128; // < Ratio normalisé pour le type ShortInt public { Convertir une chaîne de caractères en sa représentation en ShortInt@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:ShortInt=0):Boolean; { Convertir la valeur de la variable ShortInt en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable ShortInt et le paramètre "vMin" } function Min(vMin:ShortInt):ShortInt; { Retourne la plus grande valeur entre la valeur de la variable ShortInt et le paramètre "vMax" } function Max(vMax:ShortInt):ShortInt; { Vérifie si la valeur de la variable ShortInt est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: ShortInt): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:ShortInt; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :ShortInt):ShortInt; { S'assure que la valeur de la variable ShortInt est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:ShortInt):ShortInt; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:ShortInt; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable ShortInt. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur ShortInt sous forme de chaine de caractères } function ToHexString: string; { Retourne la valeur normalisée du ShortInt comprise dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable ShortInt (1/Value) } function Reciprocal : Single; end; { Assistant pour le type SmallInt } TSmallIntHelper = type helper for SmallInt public const MaxValue = 32767; MinValue = -32768; NormalizedRatio : single = 1 / 32767; public { Convertir une chaîne de caractères en sa représentation en SmallInt@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:SmallInt=0):Boolean; { Convertir la valeur de la variable SmallInt en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable SmallInt et le paramètre "vMin" } function Min(vMin:SmallInt):SmallInt; { Retourne la plus grande valeur entre la valeur de la variable SmallInt et le paramètre "vMax" } function Max(vMax:SmallInt):SmallInt; { Vérifie si la valeur de la variable SmallInt est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: SmallInt): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:SmallInt; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :SmallInt):SmallInt; { S'assure que la valeur de la variable SmallInt est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:SmallInt):SmallInt; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:SmallInt; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable SmallInt. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur SmallInt sous forme de chaine de caractères } function ToHexString: string; { Retourne la valeur normalisée du SmallInt comprise dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable SmallInt (1/value) } function Reciprocal : Single; { Retourne @True si la valeur est une puissance de deux. Si non retourne @False } function IsPowerOfTwo : Boolean; { Retourne la puissance de deux suivante } function NextPowerOfTwo:SmallInt; { Retourne la puissance de deux précédente } function PreviousPowerOfTwo:SmallInt; end; { Assistant pour le type Word } TWordHelper = type helper for Word public const MaxValue = 65535; MinValue = 0; NormalizedRatio : single = 1 / 65535; public { Convertir une chaîne de caractères en sa représentation en Word@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Word=0):Boolean; { Convertir la valeur de la variable Word en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable Word et le paramètre "vMin" } function Min(vMin:Word):Word; { Retourne la plus grande valeur entre la valeur de la variable Word et le paramètre "vMax" } function Max(vMax:Word):Word; { Vérifie si la valeur de la variable Word est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Word): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Word; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax : Word):Word; { S'assure que la valeur de la variable Word est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Word):Word; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable Word. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur Word sous forme de chaine de caractères } function ToHexString: string; { Retourne la valeur normalisée du Word comprise dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable Word (1/value) } function Reciprocal : Single; { Retourne @True si la valeur est une puissance de deux. Si non retourne @False } function IsPowerOfTwo : Boolean; { Retourne la puissance de deux suivante } function NextPowerOfTwo:Word; { Retourne la puissance de deux précédente } function PreviousPowerOfTwo:Word; end; { Assistant pour le type Cardinal (Note : Cardinal = DWord = LongWord ) } TCardinalHelper = type helper for Cardinal public const MaxValue = 4294967295; MinValue = 0; NormalizedRatio : single = 1 / 4294967295; public { Convertir une chaîne de caractères en sa représentation en Cardinal@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Cardinal=0):Boolean; { Convertir la valeur de la variable Cardinal en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable Cardinal et le paramètre "vMin" } function Min(vMin:Cardinal):Cardinal; { Retourne la plus grande valeur entre la valeur de la variable Cardinal et le paramètre "vMax" } function Max(vMax:Cardinal):Cardinal; { Vérifie si la valeur de la variable Cardinal est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Cardinal): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Cardinal; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Cardinal):Cardinal; { S'assure que la valeur de la variable Cardinal est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Cardinal):Cardinal; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable Cardinal. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur Cardinal sous forme de chaine de caractères } function ToHexString: string; { Retourne la valeur normalisée du Cardinal comprise dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable Cardinal (1/value) } function Reciprocal : Single; { Retourne @True si la valeur est une puissance de deux. Si non retourne @False } function IsPowerOfTwo : Boolean; { Renvois la puissance de deux suivante } function NextPowerOfTwo:Cardinal; { Renvois la puissance de deux précédente } function PreviousPowerOfTwo:Cardinal; end; { Assistant pour le type Integer} TIntegerHelper = type helper for Integer public const MaxValue = 2147483647; MinValue = -2147483648; NormalizedRatio : single = 1 / 2147483647; public { Convertir une chaîne de caractères en sa représentation en Integer @br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Integer=0):Boolean; { Convertir la valeur de la variable Integer en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable Integer et le paramètre "vMin" } function Min(vMin:Integer):Integer; { Retourne la plus grande valeur entre la valeur de la variable Integer et le paramètre "vMax" } function Max(vMax:Integer):Integer; { Vérifie si la valeur de la variable Integer est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Integer): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Integer; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Integer):Integer; { S'assure que la valeur de la variable Integer est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Integer):Integer; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:Integer; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable Integer. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur Integer sous forme de chaine de caractèresn } function ToHexString: string; { Retourne la valeur normalisée de l'integer comprise dans l'interval [0..1] } function Normalized : Single; { Retourne la valeur réciproque de la variable Integer (1/value) } function Reciprocal : Single; { Retourne @True si la valeur est une puissance de deux. Si non retourne @False } function IsPowerOfTwo : Boolean; { Renvois la puissance de deux suivante } function NextPowerOfTwo:Integer; { Renvois la puissance de deux précédente } function PreviousPowerOfTwo:Integer; end; { Assistant pour le type Int64 } TInt64Helper = type helper for Int64 public const MaxValue = 9223372036854775807; MinValue = -9223372036854775808; public { Convertir une chaîne de caractères en sa représentation en Int64@br Retourne @True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Int64=0):Boolean; { Convertir la valeur de la variable Int64 en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable Int64 et le paramètre "vMin" } function Min(vMin:Int64):Int64; { Retourne la plus grande valeur entre la valeur de la variable Int64 et le paramètre "vMax" } function Max(vMax:Int64):Int64; { Vérifie si la valeur de la variable Int64 est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Int64): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Int64; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Int64):Int64; { S'assure que la valeur de la variable Int64 est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Int64):Int64; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:Int64; { Retourne la représentation Byte de la variable Int64 comprise dans l'interval [0..255] } function ToByte : Byte; { Retourne la représentation Booleenne de la variable Int64. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur Int64 sous forme de chaine de caractères } function ToHexString: string; end; { Assistant pour le type QWord } TQWordHelper = type helper for QWord public const MaxValue = 18446744073709551615; MinValue = 0; public { Convertir une chaîne de caractères en sa représentation en QWord@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:QWord=0):Boolean; { Convertir la valeur de la variable QWord en chaîne de caractères } function ToString(Const Formatted : Boolean = False): string; { Retourne la plus petite valeur entre la valeur de la variable QWord et le paramètre "vMin" } function Min(vMin:QWord):QWord; { Retourne la plus grande valeur entre la valeur de la variable QWord et le paramètre "vMax" } function Max(vMax:QWord):QWord; { Vérifie si la valeur de la variable QWord est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: QWord): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:QWord; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :QWord):QWord; { S'assure que la valeur de la variable QWord est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:QWord):QWord; { Retourne la représentation Booleenne de la variable QWord. Retourne TRUE si la valeur est plus grande que zero. Sinon retourne FALSE } function ToBoolean : Boolean; { Retourne la representation hexadécimale de la valeur DWord sous forme de chaine de caractères } function ToHexString: string; end; { Assistant pour le type Single } TSingleHelper = type helper for Single public {$push} {$R-} {$Q-} const Epsilon : Single = 1.4012984643248170709e-45; MaxValue : Single = 340282346638528859811704183484516925440.0; MinValue : Single = -340282346638528859811704183484516925440.0; PositiveInfinity : Single = 1.0/0.0; NegativeInfinity : Single = -1.0/0.0; NaN : Single = 0.0/0.0; {$POP} public { Convertir une chaîne de caractères en sa représentation en Single@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Single=0):Boolean; { Convertir la valeur de la variable Single avec nombre "Decimals" derrière la virgule en chaîne de caractères } function ToString(Const Decimals:Integer = 5): string; { Retourne la plus petite valeur entre la valeur de la variable Single et le paramètre "vMin" } function Min(vMin:Single):Single; { Retourne la plus grande valeur entre la valeur de la variable Single et le paramètre "vMax" } function Max(vMax:Single):Single; { Vérifie si la valeur de la variable Single est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Single): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Single; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Single):Single; { S'assure que la valeur de la variable Single est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Single):Single; { Arrondit une valeur vers zéro } function Trunc : Integer; { Arrondit une valeur vers son entier le plus proche } function Round : Integer; { Arrondit la valeur vers l'infini négatif } function Floor : Integer; { Arrondit la valeur vers l'infini positif } function Ceil : Integer; {Arrondit la valeur en virgule flottante à l'entier le plus proche.      Se comporte comme Round mais renvoie une valeur à virgule flottante comme Int.} function RoundInt : Single; { Renvoie la partie fractionnelle de la valeur } function Fract : Single; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:Single; { Retourne la valeur réciproques (1/value) } function Reciprocal : Single; { Retourne @True si la valeur tend vers l'infini positif ou négatif. Sinon retourne @False.} Function IsInfinity: Boolean; { Retuourne @True si la valeur est égale à NaN. Si non retourne @False.} Function IsNan: Boolean; { Retourne @True si la valeur tend vers l'infini négatif. Si non retourne @False.} Function IsNegativeInfinity: Boolean; { Retourne @True si la valeur tend vers l'infini positif. Si non retourne @False.} Function IsPositiveInfinity: Boolean; end; { Assistant pour le type Double } TDoubleHelper = type helper for Double public const {$push} {$R-} {$Q-} Epsilon : Double = 4.9406564584124654418e-324; MaxValue : Double = 1.7976931348623157081e+308; MinValue : Double = -1.7976931348623157081e+308; PositiveInfinity : Double = 1.0/0.0; NegativeInfinity : Double = -1.0/0.0; NaN : Double = 0.0/0.0; {$POP} public { Convertir une chaîne de caractères en sa représentation en Double@br Retourne True an cas de succes sinon retourne False et définie la valeur avec la variable DefValue } function Parse(Num : String; Const defValue:Double=0):Boolean; { Convertir la valeur de la variable Double avec nombre "Decimals" derrière la virgule en chaîne de caractères } function ToString(Const Decimals:Integer = 5): string; { Retourne la plus petite valeur entre la valeur de la variable Double et le paramètre "vMin" } function Min(vMin:Double):Double; { Retourne la plus grande valeur entre la valeur de la variable Double et le paramètre "vMax" } function Max(vMax:Double):Double; { Vérifie si la valeur de la variable Double est comprise et ou égale à l'interval définit par les paramètres "Low et High"} function IsInRange(Low, High: Double): Boolean; { Retourne un nombre aléatoire dans l'interval définit par les constantes "MinValue et MaxValue" } function Random:Double; { Retourne un nombre aléatoire dans l'interval definit par les paramètres "vMin et vMax" } function RandomRange(vMin, vMax :Double):Double; { S'assure que la valeur de la variable Double est comprise entre les paramètres "vMin et vMax" et renvoie la valeur} function Clamp(vMin,vMax:Double):Double; { Arrondit une valeur vers zéro } function Trunc : Integer; { Arrondit une valeur vers son entier le plus proche } function Round : Integer; { Arrondit la valeur vers l'infini négatif } function Floor : Integer; { Arrondit la valeur vers l'infini positif } function Ceil : Integer; {Arrondit la valeur en virgule flottante à l'entier le plus proche. @br      Se comporte comme Round mais renvoie une valeur à virgule flottante comme Int.} function RoundInt : Double; { Renvoie la partie fractionnelle de la valeur } function Fract : Double; { Renvois le signe de la valeur avec la convention (-1, 0, +1) } function Sign:Double; { Retours la valeur réciproques (1/value) } function Reciprocal : Double; { Retourne @True si la valeur tend vers l'infini positif ou négatif. Si non retourne @False.} Function IsInfinity: Boolean; { Returns @True si égale à NaN. Si non retourne @False.} Function IsNan: Boolean; { Retourne @True si la valeur tend vers l'infini négatif. Si non retourne @False.} Function IsNegativeInfinity: Boolean; { Retourne @True si la valeur tend vers l'infini positif. Si non retourne @False.} Function IsPositiveInfinity: Boolean; end; {$IFDEF FPC_HAS_TYPE_EXTENDED} { TODO : Add Helper for Extended } {$ENDIF} { Assistant pour le Type String - Utilise la convention UTF-8 } TStringHelper = type helper for String Private Function GetChar(AIndex : Integer) : Char; Function GetLength : Integer; public Const Empty = ''; public { Définit la chaine de caractère depuis le format System } procedure SetFromSys(aString : String); { Définit la chaine de caractère depuis le format Console } procedure SetFromConsole(aString:String); { Convertit et définit une chaine de caractères vers UTF-8 en utilisant les conventions pascal } procedure SetToUTF8(aString:String); { Convertit la chaine de caractères vers sa représentation au format "System" } function ToSys : String; { Convertit la chaine de caractères vers sa représentation au format "Console" } function ToConsole : String; { Convertit la chaine de caractères vers sa représentation au format "Ansi" } //function ToAnsi : AnsiString; { Supprime les espaces de début / fin et les caractères de contrôle.} function Trim: String; overload; { Supprime les espaces de début et les caractères de contrôle.} function TrimLeft : String; { Supprime les espaces de fin et les caractères de contrôle. } function TrimRight : String; { Renvoie @True si une chaîne n'a pas de caractères au-dessus de ord ('') eg = #32.       Fondamentalement, cela signifie qu'il retourne @True si la chaîne est vide ou contient seulement       des caractères de contrôle ou des espaces.       Note : Beaucoup plus rapide que @code (if Trim(s) = '' Then ...)} function IsEmpty : Boolean; //{ Same as the standard Length function } //function GetLength: Integer; { Convertit la chaine de caractère ne majuscule. } function ToUpper : String; { Convertit la chaine de caractère ne minuscule. } function ToLower : String; { Retourne @True si deux chaine de caractères sont égale. Paramètre si on prend en charge la casse ou pas. } function IsEquals(const Value: string; Const IgnoreCase: Boolean = False): Boolean; { Compare deux chaînes de caractère en ignorant éventuellement la casse en fonction du paramètre "IgnoreCase" @br Retourne : @unorderedlist( @item(-1 si A vient avant B) @item(1 si A vient après B) @item(0 si A et B sont égaux) ) } function Compare(const Value: string; Const IgnoreCase: Boolean = False): Integer; { Répète "count" fois le caractère "C". } procedure RepeatChar(C : Char; Count : Integer); { Répète "count" fois la chaine de caractères "s". } procedure RepeatStr(const s : String; Count : Integer); { Renvois une chaine de caractères centrée par rapport à "TotalLen" et ajoute le caractère "PadChar".} function PadCenter(TotalLen: Integer; Const PadChar : Char = ' '): String; { Ajoute un caractère à la fin de la chaîne jusqu'à ce que la longueur soit égale à "PadLen". @br       Si "PadLen" est négatif, le caractère sera inséré à gauche.} function PadCharRight(PadLen : Integer;Const PadChar : Char = ' ') : String; { Ajoute un caractère au débute tant que sa longueur est plus petite que "PadLen".} function PadCharLeft(PadLen : Integer;Const PadChar : Char = ' ') : String; { Retourne la position d'une chaine de caractère. Identique à la fonction originel "Pos" } function Pos(const SubStr : String;StartPos :integer = 1) : Integer; { Renvoie @True si "Substr1" et "Substr2" sont trouvés et renvoie la position de "Substr1" et "Substr2". @br       Si non retourne @False et -1 pour les positions } function PosBetween(const SubStr1, SubStr2 : String; var StartPos, EndPos : Integer):Boolean; { Retourne la position d'une chaine de caractère. Identique à la fonction originel "Pos" mais avec la prise en charge de la casse en plus } function IndexOf(const SubStr: string; Start: Integer=0; IgnoreCase: Boolean = False): Integer; { Recherche "SubStr", si trouvé, retourne les caractères situé après "SubStr". Si non une chaîne vide est renvoyée.} function After(const SubStr : String; Position : Integer = 1) : String; { Recherche "SubStr", si trouvé, retourne les caractères situé avant "SubStr". Si non la chaîne de caractère complète est renvoyée. } function Before(const SubStr : String; Position : Integer = 1) : String; { Analyse la chaine de caractères pour trouver la combinaison de début "SubStr1" et de fin "SubStr2". @ Retourne le texte entre les deux. @Br       Si SubStr2 est vide, SubStr2 sera considéré comme identique à SubStr1. @Br       Si SubStr2 n'est pas trouvé, une chaîne vide est retournée (par opposition à la fonction Mid)..} function Between(const SubStr1, SubStr2 : String) : String; { Analyse la chaine de caractère et retourne le texte après "SubStr1" et avant "SubStr2" si ces deux chaines de caractères sont trouvées. Si "SubStr2" est vide alors "SubStr2" sera considéré comme identique à "SubStr1". Si "SubStr2" n'est pas trouvé alors la chaine de caractères complète après "SubStr1" sera retourné (à l'opposé de la méthode Between). Note : Cette méthode est la combinaison des méthode Before/After mais en plus rapide.} function Mid(const SubStr1, SubStr2 : String; Position : Integer = 1) : String; { Identique à la fonction "copy" standard, sauf que la limite est par défaut de 2 Go.} function Copy(aStart, aLength : Integer) : string; { Retourne la chaine de caractères entre la position "StartPos" et "EndPos" incluses } function CopyPos(StartPos, EndPos: Integer): String; { Insert un chaine de caractères "SubStr" à la position "Position"} function Insert(const SubStr: string; Position: Integer):String; { Renvoie tous les caractères à gauche d'une position spécifique (y compris)} function LeftOf(Position : Integer) : String; {Renvoie tous les caractères à droite d'une position spécifique (y compris)} function RightOf(Position : Integer) : String; { Convertit le type String vers le type WideString } function ToWideString : WideString; { Définit la chaine de caractères depuis une chaine de caractères de type WideString } procedure SetWideString(S : WideString); { Convertit une valeur de type Interger en sa représentation en chaine de caractères } procedure Parse(Num : Integer); overload; { Convertit une valeur de type Single avec "Decimal" chiffre après la virgule en sa représentation en chaine de caractères } procedure Parse(Num : Single; Const Decimals:Integer = 5); overload; {Convertit une valeur de type Double avec "Decimal" chiffre après la virgule en sa représentation en chaine de caractères } procedure Parse(Num : Double; Const Decimals:Integer = 5); overload; { Encadre la chaine de caractères avec le texte "chs"} function Surround(chs: string): string; overload; { Encadre la chaine de caractères à gauche avec "chsL" et à droite avec "chsR"} function Surround(chsL, chsR: string): string; overload; { Joint les éléments d'une StringList séparé avec "Sep"} procedure Implode(lst:TStringList;sep : string =';'); { Découpe les éléments de la chaine de caractères séparé par "Sep" vers une StringList} function Explode(sep: string = ';'):TStringList; { Retourne @True si "Substr" est présent dans la chaine de caractères. En ignorant éventuellement la casse. } function Contains(const SubStr: string; IgnoreCase: Boolean = False): Boolean; { Encadre la chaine de caractères avec des guillemets } function Quote : String; { Remplace la chaine de caractère "OldPattern" si présente par "NewPattern", en ignorant éventuellement la casse. } function Replace(const OldPattern, NewPattern: string; IgnoreCase: Boolean = False) : string; { Supprime tous les caractères à gauche à partir de la position "StartIndex" } function RemoveLeft(StartIndex : Integer):String; overload; { Supprime "aCount" caractères à gauche a partir de la position "StartIndex" } function RemoveLeft(StartIndex, aCount : Integer):String; overload; { Supprime tous les caractères à droite à partir de la position "StartIndex" } function RemoveRight(StartIndex : Integer):String; overload; { Supprime "aCount" caractères à droite a partir de la position "StartIndex" } function RemoveRight(StartIndex, aCount : Integer):String; overload; { Supprime tous les caractères correspondant à "aChar", en ignorant éventuellement la casse. } function RemoveChar(aChar : Char; Const IgnoreCase : Boolean = False):String; { Efface toutes les cahines de caractères correspond à "SubStr", en ignorant éventuellement la casse. } function Remove(SubStr:String; Const IgnoreCase : Boolean = False):String; { Retourne la chaine des caractères inversée } function Reverse : String; { Limite la longeur de la chaine de caractère maximale à 'MaxCol'} function Wrap(MaxCol : Integer):String; { Retourne le nombre de fois que le caractère "C" est présent dans la chaine de caractères } function CountChars(C: Char):Integer; { Retourne @True si la chaine de caractère contient "DefTrue". @br Retourne @False si la chaine de caractère contient "DefFalse". Si non retourne @True } function ToBoolean(Const DefTrue : String = 'True'; Const defFalse : String = 'False'; Const IgnoreCase : Boolean = false):Boolean; { Convertit la chaine de caractères vers le type Integer. @br Retourne zero par défaut en cas d'erreur. } function ToInteger : Integer; { Convertit la chaine de caractères vers le type Int64. @br Retourne zero par défaut en cas d'erreur. } function ToInt64 : Int64; { Convertit la chaine de caractères vers le type Single. @br Retourne zero par défaut en cas d'erreur. } function ToSingle : Single; { Convertit la chaine de caractères vers le type Double. @br Retourne zero par défaut en cas d'erreur. } function ToDouble : Double; //function ToInt64 : Int64; { Convertit la chaine de caractères vers le type Byte. @br Retourne zero par défaut en cas d'erreur } function ToByte : Byte; { Calcul un "Hash" unique de la chaine de caractères, en ignorant éventuellement la casse} function ComputeHash(Const IgnoreCase : Boolean = False) : Integer; { Retourne le caractère à la position "AIndex" } property Chars[AIndex: Integer]: Char read GetChar; { Retourne la longueur de la chaine de caractères } property Length: Integer read GetLength; End; { Définition du type de format d'un TDateTime pour sa representation en chaine de caractères } TDateFormat =(dfUTC, dfGMT, dfCustom); { @abstract(Assistant pour le type TDateTime) Voir aussi : https://www.freepascal.org/docs-html/rtl/sysutils/formatchars.html @table( @rowHead( @cell(Caractères) @cell(Description)) @row( @cell(c) @cell(Format court de la date (uniquement pour FormatDateTime) )) @row( @cell(d) @cell(Jour du mois )) @row( @cell(dd) @cell(Jour du mois (zero en tête) )) @row( @cell(ddd) @cell(Jour de la semaine (abbreviation) )) @row( @cell(dddd) @cell(Jour de la semaine (Complet) )) @row( @cell(ddddd) @cell(Format long de la date (uniquement pour FormatDateTime) )) @row( @cell(m) @cell(Mois ou minutes si précédé de h )) @row( @cell(mm) @cell(Mois (zero en tête) )) @row( @cell(mmm) @cell(Mois (abbreviation) )) @row( @cell(mmmm) @cell(Mois (Complet) )) @row( @cell(y) @cell(Année (deux chiffres) )) @row( @cell(yy) @cell(Année (deux chiffres) )) @row( @cell(yyyy) @cell(Année (quatre chiffre, avec siècle) )) @row( @cell(h) @cell(Heure )) @row( @cell(hh) @cell(Heure (zero en tête) )) @row( @cell(n) @cell(Minute )) @row( @cell(nn) @cell(Minute (zero en tête) )) @row( @cell(s) @cell(Secondes )) @row( @cell(ss) @cell(Secondes (zero en tête) )) @row( @cell(t) @cell(Format court de l'heure (uniquement pour FormatDateTime) )) @row( @cell(tt) @cell(Format long de l'heure (uniquement pour FormatDateTime) )) @row( @cell(am/pm) @cell(Utilises une horloge sur 12 heures et affiche am ou pm )) @row( @cell(a/p) @cell(Utilises une horloge sur 12 heures et affiche a ou p )) @row( @cell(/) @cell(Insert un séparateur de date )) @row( @cell(:) @cell(Insert un séparateur de temps )) @row( @cell("xx") @cell(Texte literal )) @row( @cell(’xx’) @cell(Texte literal )) ) ---------------------------------------------------------------------------- @bold(Note) : pour l'utilisation du caractère : '/' comme séparateur vous devrez utiliser un double guillemet dans votre chaîne de modèle ( eg : 'YYYY"/"MM"/"DD' ) } TDateTimeHelper = type helper for TDateTime private function getYear: Word; function getMonth: Word; function getDay: Word; function getHour: Word; function getMinute: Word; function getSecond: Word; Function getMillisecond : Word; public Const fmtFullDate : String = 'dddd dd mmmm yyyy '; // < Format long pour la représentation d'une date en chaine de caractères fmtShortDate : String = 'dd"/"mm"/"yyyy'; // < Format cours pour la représentation d'une date en chaine de caractères fmtShortTime : String = 'hh":"nn":"ss'; // < Format pour la représentation d'une "heure" en chaine de caractères public { Définit la valeur à la date du jour } procedure SetToDay; { Définit la valeur du temps à l'heure en cours } Procedure SetToTime; { Définit la valeur à la date et l'heure actuelle } procedure SetToNow; { Définit l'heure en fonction des paramètres H, M, S } procedure SetTime(H,M,S : Integer); { Définit la date en fonction des paramètres Y, M, D } procedure SetDate(Y,M,D : Integer); { Définit la date et l'heure depuis une chaine de caractères d'après le modèle "APattern" } procedure SetFromString(ADateTimeStr : String ;Const APAttern : String = 'YYYY"/"MM"/"DD hh":"nn":"ss'); { Définit la date et l'heure à partir de l'horodatage Unix } procedure SetFromUnixTimeStamp(ADate : Int64); { Définit la date et l'heure à partir de l'horodatage Mac } procedure SetFromMacTimeStamp(ADate : Int64); { Définit la date et l'heure à partir d'une date et heure UTC } procedure SetFromUTC(UT: TDateTime); overload; { Définit la date et l'heure à partir d'une date et heure UTC et un écart } procedure SetFromUTC(UT: TDateTime; ZOffset : Integer); overload; { Définit la date et l'heure à partir d'une date au format "Julian" } procedure SetFromJulian(JulianDate : Double); { Définit la date et l'heure à partir d'une chaine de caractères provenant d'une représentation au format SQL } procedure SetFromSQL(ADataTimeStr : String); { Définit une date et heure aléatoire } procedure SetRandomDate; overload; { Définit une date et heure aléatoire comprise entre les paramètres "StartDate" et "EndDate" } procedure SetRandomDate(StartDate, EndDate : TDateTime); overload; { Définit la date et l'heure depuis la date et heure d'un fichier } procedure SetFromFile(aFileName:String); { Retourne la représentation du TDateTime en chaine de caractères formaté suivant le modèle } function ToString(Const Format: TDateFormat = dfCustom ; Const CustomFormat: string = 'yyyy-mm-dd hh:nn:ss'): string; { Retourne la représentation au format SQL du TDateTime } function ToSQL : String; { Retourne la représentation de la date en chaine de caractères formaté suivant le modèle. eg : YYYY/MM/DD @br @bold(Note) : pour utiliser le séparateur / il faut le "Double Quoter"} function DateToString(Const FormatStr :string = 'dd"/"mm"/"yyyy'): String; { Retourne la représentation de l'heure en chaine de caractères formaté suivant le modèle. eg : H:M:S} function TimeToString(Const FormatStr : string = 'hh:nn:ss') : String; { Compare deux TDateTime. Retourne 0 Si égale. Si non retourne -1 or 1 si elle est plus petite ou plus grande } function Compare(SecondDateTime : TDatetime):Integer; { Compare deux Date. Retourne 0 Si égale. Si non retourne -1 or 1 si elle est plus petite ou plus grande} function CompareDate(SecondDate : TDateTime):Integer; { Compare deux Heure. Retourne 0 Si égale. Si non retourne -1 or 1 si elle est plus petite ou plus grande} function CompareTime(SecondTime : TDateTime):Integer; { Ajoute une année à la date en cours } function AddYear(const A: Integer=1): TDateTime; { Ajoute un mois à la date en cours } function AddMonth(const A: Integer=1): TDateTime; { Ajoute un jour à la date en cours } function AddDay(const A: Integer=1): TDateTime; { Ajoute un semaine à la date en cours } function AddWeek(const A: Integer=1): TDateTime; { Ajoute des heures à l'heure en cours } function AddHour(const A: Integer=1): TDateTime; { Ajoute des minutes à l'heure en cours } function AddMinute(const A: Integer=1): TDateTime; { Ajoute des secondes à l'heure en cours } function AddSecond(const A: Integer=1): TDateTime; { Ajoute des millisecondes à l'heure en cours} function AddMilliSecond(const A: Integer=1): TDateTime; { Convertit la date en cours vers le format "Julian" } function ToJulian : Double; { Convert la date vers la représentation horodatage Unix } function ToUnixTimeStamp : Int64; { Convert la date vers la représentation horodatage Mac } function ToMacTimeStamp : Int64; { Convert la date vers la représentation UTC } function ToUTC : TDateTime; overload; { Convert la date vers la représentation UTC avec un décalage } function ToUTC(ZOffset : Integer) : TDateTime; { Retourne @True si l'anné est bixestile. Si non retourne @False } function IsLeapYear : Boolean; { Retourne le nombre de jour de l'année } function GetDaysInYear : Word; { Retourne le nombre de jour du mois } function GetDaysInMonth : Word; { Retourne le nombre de semaine de l'année } function GetWeeksInYear : Word; { Retourne le numéro du jour de la semaine } function GetDayOfTheWeek : Word; { Retourne le nuémro de la semaine de l'année } function GetWeekOfTheYear : Word; { Retourne les années écoulées entre deux dates } function GetElapsedYears(ATo : TDateTime): Integer; { Renvoie les mois écoulées entre deux dates } function GetElapsedMonths(ATo : TDateTime): Integer; { Renvoie les semaines écoulées entre deux dates } function GetElapsedWeeks(ATo : TDateTime): Integer; { Renvoie les jours écoulées entre deux dates } function GetElapsedDays(ATo : TDateTime): Integer; { Renvois les heures écoulées entre deux heures } function GetElapsedHours(ATo : TDateTime): Int64; { Renvois les minutes écoulées entre deux heures } function GetElapsedMinutes(ATo : TDateTime): Int64; { Renvois les secondes écoulées entre deux heures } function GetElapsedSeconds(ATo : TDateTime): Int64; { Renvois les millisecondes écoulées entre deux heures } function GetElapsedMilliSeconds(ATo : TDateTime): Int64; { Renvois le temps écoulés entre deux TDateTime } function GetElapsedPeriod(ATo : TDateTime): TDateTime; {$IFDEF WINDOWS} { Convertis le FileTime de Windows vers un TDateTime } procedure FromFileTime(const FileTime: TFileTime); {$ENDIF} { Retourne l'année de la date } property Year : Word read getYear; { Retourne le mois de la date } property Month : Word read getMonth; { Retourne le jour de la date } property Day : Word read getDay; { Retourne l'heure de l'heure } property Hour : Word read getHour; { Retourne la minute de l'heure } property Minute : Word read getMinute; { Retourne les secondes de l'heure } property Second : Word read getSecond; { Retourne les millisecondes de l'heure } property MilliSecond : Word read getMilliSecond; end; //============================================================================== var { Variable de formatage pour le choix du séparateur de la décimale des nombres en virgule flottante point --> virgule } vPointSeparator, { Variable de formatage pour le choix du séparateur de la décimale des nombres en virgule flottante virgule --> point } vCommaSeparator: TFormatSettings; //============================================================================== Implementation Uses LazUTF8, Math, DateUtils, LazFileUtils; //{$IFDEF WINDOWS} ,windows{$ENDIF}; //============================================================================== {%region%=====[ Internal tools ]================================================} const cHexTbl : array[0..15] of char='0123456789ABCDEF'; function _hexstr(val : longint;cnt : byte) : shortstring; var i : Integer; begin Result[0]:=char(cnt); for i:=cnt downto 1 do begin result[i]:=chextbl[val and $f]; val:=val shr 4; end; end; {$IFNDEF NO_ASM_OPTIMIZATIONS} // pour éviter l'inclusion de l'unité BZMath function ClampByte(const Value: Integer): Byte; assembler; nostackframe; asm {$IFDEF CPU64} {$IFDEF UNIX} MOV EAX,EDI {$ELSE} MOV EAX,ECX {$ENDIF} {$ENDIF} TEST EAX,$FFFFFF00 JNZ @above RET @above: JS @below MOV EAX,$FF RET @Below: XOR EAX,EAX end; {$ELSE} function ClampByte(const Value: Integer): Byte; begin Result := Value; if Value > 255 then Result := 255 else if Value < 0 then Result := 0; end; {$ENDIF} {%endregion%} {%region%=====[ TBooleanHelper ]================================================} Function TBooleanHelper.Tostring(Const Deftrue : String; Const Deffalse : String) : String; Begin if (Self = True) then result := DefTrue else result := DefFalse; End; {%endregion%} {%region%=====[ TCharHelper ]===================================================} Function TCharHelper.IsAlpha : Boolean; Begin Result := ((Self in ['A'..'Z']) or (Self in ['a'..'z'])); End; Function TCharHelper.IsNumeric : Boolean; Begin Result := (Self in ['0'..'9']); End; Function TCharHelper.ToCharCode : Integer; Begin Result := ord(Self); End; Function TCharHelper.ToUpper : Char; begin result :=UpCase(Self); End; Function TCharHelper.ToLower : Char; Begin Result := LowerCase(Self); End; {%endregion%} {%region%=====[ TByteHelper ]===================================================} function TByteHelper.Parse(Num: String; const defValue: Byte): Boolean; Var I: Integer; Begin Result := false; Self := defValue; if TryStrToInt(Num,I) then begin Self := ClampByte(I); result := true; End; End; function TByteHelper.ToString: string; Begin Result := IntToStr(Self); End; function TByteHelper.Min(vMin: Byte): Byte; Begin if Self<vMin then result := vMin else result := Self; End; function TByteHelper.Max(vMax: Byte): Byte; Begin if Self>vMax then result := vMax else result := Self; End; function TByteHelper.IsInRange(Low, High: Byte): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TByteHelper.Random:Byte; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TByteHelper.RandomRange(vMin, vMax :Byte):Byte; Begin Result:=System.Random(Abs(vMin-vMax)) + Math.Min(vMin,vMax); End; function TByteHelper.Clamp(vMin, vMax: Byte): Byte; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TByteHelper.ToBoolean: Boolean; begin result := (self<>0); end; function TByteHelper.ToHexString: string; begin result :=_hexstr(Self,2) end; function TByteHelper.Normalized: Single; begin result := self * Self.NormalizedRatio; end; function TByteHelper.Reciprocal: Single; Begin Result := 0; If Self = 0 Then exit; Result := 1.0 / Self End; {%endregion%} {%region%=====[ TShortIntHelper ]===============================================} function TShortIntHelper.Parse(Num: String; const defValue: ShortInt): Boolean; Var I: Integer; Begin Result := false; Self := defValue; if TryStrToInt(Num,I) then begin Self := I.Clamp(Shortint.MinValue,ShortInt.MaxValue); result := true; End; End; function TShortIntHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TShortIntHelper.Min(vMin: ShortInt): ShortInt; Begin if Self<vMin then result := vMin else result := Self; End; function TShortIntHelper.Max(vMax: ShortInt): ShortInt; Begin if Self>vMax then result := vMax else result := Self; End; function TShortIntHelper.IsInRange(Low, High: ShortInt): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TShortIntHelper.Random:ShortInt; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TShortIntHelper.RandomRange(vMin, vMax :ShortInt):ShortInt; Begin Result:=System.Random(Abs(vMin-vMax))+ Math.Min(vMin,vMax); End; function TShortIntHelper.Clamp(vMin, vMax: ShortInt): ShortInt; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TShortIntHelper.Sign: ShortInt; begin If Self < 0 Then Result := -1 Else If Self > 0 Then Result := 1 Else Result := 0; end; function TShortIntHelper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TShortIntHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TShortIntHelper.ToHexString: string; begin Result:=_hexstr(Self,8) end; function TShortIntHelper.Normalized: Single; begin Result := Self * Self.NormalizedRatio; end; function TShortIntHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Var a: ShortInt; Begin Result := 0; If Self = 0 Then exit; a := Self.Sign; If ((a * Self) >= cEpsilon) Then Result := 1.0 / Self Else Result := a * (1.0 / cEpsilon); End; {%endregion%} {%region%=====[ TSmallIntHelper ]===============================================} function TSmallIntHelper.Parse(Num: String; const defValue: SmallInt): Boolean; Var I: Integer; Begin Result := false; Self := defValue; if TryStrToInt(Num,I) then begin Self := I.Clamp(SmallInt.MinValue,SmallInt.MaxValue); result := true; End; End; function TSmallIntHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TSmallIntHelper.Min(vMin: SmallInt): SmallInt; Begin if Self<vMin then result := vMin else result := Self; End; function TSmallIntHelper.Max(vMax: SmallInt): SmallInt; Begin if Self>vMax then result := vMax else result := Self; End; function TSmallIntHelper.IsInRange(Low, High: SmallInt): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TSmallIntHelper.Random:SmallInt; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TSmallIntHelper.RandomRange(vMin, vMax :SmallInt):SmallInt; Begin Result:=System.Random(Abs(vMin-vMax))+ Math.Min(vMin,vMax); End; function TSmallIntHelper.Clamp(vMin, vMax: SmallInt): SmallInt; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TSmallIntHelper.Sign: SmallInt; begin If Self < 0 Then Result := -1 Else If Self > 0 Then Result := 1 Else Result := 0; end; function TSmallIntHelper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TSmallIntHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TSmallIntHelper.ToHexString: string; begin Result:=_hexstr(Self,8) end; function TSmallIntHelper.Normalized: Single; begin Result := Self * Self.NormalizedRatio; end; function TSmallIntHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Var a: SmallInt; Begin Result := 0; If Self = 0 Then exit; a := Self.Sign; If ((a * Self) >= cEpsilon) Then Result := 1.0 / Self Else Result := a * (1.0 / cEpsilon); End; function TSmallIntHelper.IsPowerOfTwo: Boolean; Const BitCountTable: Array[0..255] Of Byte = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); Function BitCount(Value: Longword): Longword; Var V: Array[0..3] Of Byte absolute Value; Begin Result := BitCountTable[V[0]] + BitCountTable[V[1]] + BitCountTable[V[2]] + BitCountTable[V[3]]; End; Begin Result := BitCount(abs(Self)) = 1; End; function TSmallIntHelper.NextPowerOfTwo: SmallInt; var value : SmallInt; begin Value := Self; If (Value > 0) Then Begin Dec(Value); Value := Value Or (Value Shr 1); Value := Value Or (Value Shr 2); Value := Value Or (Value Shr 4); Value := Value Or (Value Shr 8); Value := Value Or (Value Shr 16); End; Result := Value + 1; end; function TSmallIntHelper.PreviousPowerOfTwo: SmallInt; Var I, N: SmallInt; Begin Result := 0; For I := 14 Downto 2 Do Begin N := (1 Shl I); If N < Self Then Break Else Result := N; End; end; {%endregion%} {%region%=====[ TWordHelper ]===================================================} function TWordHelper.Parse(Num: String; const defValue: Word): Boolean; Var I: Integer; Begin Result := false; Self := defValue; if TryStrToInt(Num,I) then begin Self := I.Clamp(0,Self.MaxValue); result := true; End; End; function TWordHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TWordHelper.Min(vMin: Word): Word; Begin if Self<vMin then result := vMin else result := Self; End; function TWordHelper.Max(vMax: Word): Word; Begin if Self>vMax then result := vMax else result := Self; End; function TWordHelper.IsInRange(Low, High: Word): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TWordHelper.Random:Word; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TWordHelper.RandomRange(vMin, vMax :Word):Word; Begin Result:=System.Random(Abs(vMin-vMax))+ Math.Min(vMin,vMax); End; function TWordHelper.Clamp(vMin, vMax: Word): Word; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TWordHelper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TWordHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TWordHelper.ToHexString: string; begin Result:=_hexstr(Self,4) end; function TWordHelper.Normalized: Single; begin Result := Self * Self.NormalizedRatio; end; function TWordHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Begin Result := 0; If Self = 0 Then exit; If (Self >= cEpsilon) Then Result := 1.0 / Self Else Result := (1.0 / cEpsilon); End; function TWordHelper.IsPowerOfTwo: Boolean; Const BitCountTable: Array[0..255] Of Byte = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); Function BitCount(Value: Longword): Longword; Var V: Array[0..3] Of Byte absolute Value; Begin Result := BitCountTable[V[0]] + BitCountTable[V[1]] + BitCountTable[V[2]] + BitCountTable[V[3]]; End; Begin Result := BitCount(abs(Self)) = 1; End; function TWordHelper.NextPowerOfTwo: Word; var value : Word; begin Value := Self; If (Value > 0) Then Begin Dec(Value); Value := Value Or (Value Shr 1); Value := Value Or (Value Shr 2); Value := Value Or (Value Shr 4); Value := Value Or (Value Shr 8); Value := Value Or (Value Shr 16); End; Result := Value + 1; end; function TWordHelper.PreviousPowerOfTwo: Word; Var I, N: Word; Begin Result := 0; For I := 14 Downto 2 Do Begin N := (1 Shl I); If N < Self Then Break Else Result := N; End; end; {%endregion%} {%region%=====[ TCardinalHelper ]===============================================} function TCardinalHelper.Parse(Num: String; const defValue: Cardinal): Boolean; Var I: Int64; Begin Result := false; Self := defValue; if TryStrToInt64(Num,I) then begin Self := I.Clamp(Cardinal.MinValue,Cardinal.MaxValue); result := true; End; End; function TCardinalHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TCardinalHelper.Min(vMin: Cardinal): Cardinal; Begin if Self<vMin then result := vMin else result := Self; End; function TCardinalHelper.Max(vMax: Cardinal): Cardinal; Begin if Self>vMax then result := vMax else result := Self; End; function TCardinalHelper.IsInRange(Low, High: Cardinal): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TCardinalHelper.Random:Cardinal; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TCardinalHelper.RandomRange(vMin, vMax :Cardinal):Cardinal; Begin Result:=System.Random(Abs(vMin-vMax))+Math.Min(vMin,vMax); End; function TCardinalHelper.Clamp(vMin, vMax: Cardinal): Cardinal; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TCardinalHelper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TCardinalHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TCardinalHelper.ToHexString: string; begin Result:=_hexstr(Self,8) end; function TCardinalHelper.Normalized: Single; begin Result := Self * Self.NormalizedRatio; end; function TCardinalHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Begin Result := 0; If Self = 0 Then exit; If (Self >= cEpsilon) Then Result := 1.0 / Self Else Result := (1.0 / cEpsilon); End; function TCardinalHelper.IsPowerOfTwo: Boolean; Const BitCountTable: Array[0..255] Of Byte = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); Function BitCount(Value: Longword): Longword; Var V: Array[0..3] Of Byte absolute Value; Begin Result := BitCountTable[V[0]] + BitCountTable[V[1]] + BitCountTable[V[2]] + BitCountTable[V[3]]; End; Begin Result := BitCount(abs(Self)) = 1; End; function TCardinalHelper.NextPowerOfTwo: Cardinal; var value : Cardinal; begin Value := Self; If (Value > 0) Then Begin Dec(Value); Value := Value Or (Value Shr 1); Value := Value Or (Value Shr 2); Value := Value Or (Value Shr 4); Value := Value Or (Value Shr 8); Value := Value Or (Value Shr 16); End; Result := Value + 1; end; function TCardinalHelper.PreviousPowerOfTwo: Cardinal; Var I, N: Cardinal; Begin Result := 0; For I := 14 Downto 2 Do Begin N := (1 Shl I); If N < Self Then Break Else Result := N; End; end; {%endregion%} {%region%=====[ TIntegerHelper ]================================================} function TIntegerHelper.Parse(Num: String; const defValue: Integer): Boolean; Var I: Integer; Begin Result := false; Self := defValue; if TryStrToInt(Num,I) then begin Self := I; result := true; End; End; function TIntegerHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TIntegerHelper.Min(vMin: Integer): Integer; Begin if Self<vMin then result := vMin else result := Self; End; function TIntegerHelper.Max(vMax: Integer): Integer; Begin if Self>vMax then result := vMax else result := Self; End; function TIntegerHelper.IsInRange(Low, High: Integer): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TIntegerHelper.Random:Integer; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TIntegerHelper.RandomRange(vMin, vMax :Integer):Integer; Begin Result:=System.Random(Abs(vMin-vMax))+ Math.Min(vMin,vMax); End; function TIntegerHelper.Clamp(vMin, vMax: Integer): Integer; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TIntegerHelper.Sign: Integer; begin If Self < 0 Then Result := -1 Else If Self > 0 Then Result := 1 Else Result := 0; end; function TIntegerHelper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TIntegerHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TIntegerHelper.ToHexString: string; begin Result:=_hexstr(Self,8) end; function TIntegerHelper.Normalized: Single; begin Result := Self * Self.NormalizedRatio; end; function TIntegerHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Var a: Integer; Begin Result := 0; If Self = 0 Then exit; a := Self.Sign; If ((a * Self) >= cEpsilon) Then Result := 1.0 / Self Else Result := a * (1.0 / cEpsilon); End; function TIntegerHelper.IsPowerOfTwo: Boolean; Const BitCountTable: Array[0..255] Of Byte = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); Function BitCount(Value: Longword): Longword; Var V: Array[0..3] Of Byte absolute Value; Begin Result := BitCountTable[V[0]] + BitCountTable[V[1]] + BitCountTable[V[2]] + BitCountTable[V[3]]; End; Begin Result := BitCount(abs(Self)) = 1; End; function TIntegerHelper.NextPowerOfTwo: Integer; var value : Integer; begin Value := Self; If (Value > 0) Then Begin Dec(Value); Value := Value Or (Value Shr 1); Value := Value Or (Value Shr 2); Value := Value Or (Value Shr 4); Value := Value Or (Value Shr 8); Value := Value Or (Value Shr 16); End; Result := Value + 1; end; function TIntegerHelper.PreviousPowerOfTwo: Integer; Var I, N: Integer; Begin Result := 0; For I := 14 Downto 2 Do Begin N := (1 Shl I); If N < Self Then Break Else Result := N; End; end; {%endregion%} {%region%=====[ TInt64Helper ]==================================================} function TInt64Helper.Parse(Num: String; const defValue: Int64): Boolean; Var I: Int64; Begin Result := false; Self := defValue; if TryStrToInt64(Num,I) then begin Self := I; result := true; End; End; function TInt64Helper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TInt64Helper.Min(vMin: Int64): Int64; Begin if Self<vMin then result := vMin else result := Self; End; function TInt64Helper.Max(vMax: Int64): Int64; Begin if Self>vMax then result := vMax else result := Self; End; function TInt64Helper.IsInRange(Low, High: Int64): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TInt64Helper.Random:Int64; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; { Source : https://oroboro.com/large-random-in-range/ } Function TInt64Helper.RandomRange(vMin, vMax :Int64):Int64; Var Diff : QWord; i, rLow, rHigh, vLow, vHigh :Int64; Begin Diff := vMax - vMin; if (Diff<=Int64.MaxValue) then begin I := Diff; result := System.Random(I)+vMin; end else begin rLow := System.Random(Int64.MaxValue); rHigh := System.Random(Int64.MaxValue); vLow := Diff and $FFFFFFFF; vHigh := Diff shr 32; result := (( rHigh * vLow ) shr 32 ) + (( rLow * vHigh ) shr 32 ) + ( rHigh * vHigh ) + vMin; end; End; function TInt64Helper.Clamp(vMin, vMax: Int64): Int64; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TInt64Helper.Sign: Int64; begin If Self < 0 Then Result := -1 Else If Self > 0 Then Result := 1 Else Result := 0; end; function TInt64Helper.ToByte: Byte; Begin Result := ClampByte(Self); End; function TInt64Helper.ToBoolean: Boolean; begin Result := (Self>0); end; function TInt64Helper.ToHexString: string; begin Result:=IntToHex(Self,16) end; {%endregion%} {%region%=====[ TQWordHelper ]==================================================} function TQWordHelper.Parse(Num: String; const defValue: QWord): Boolean; Var I: QWord; Begin Result := false; Self := defValue; if TryStrToQWord(Num,I) then begin Self := I; result := true; End; End; function TQWordHelper.ToString(const Formatted: Boolean): string; Begin if not(Formatted) then Result := IntToStr(Self) else Result := Format('%.0n',[Self+0.0],vPointSeparator); End; function TQWordHelper.Min(vMin: QWord): QWord; Begin if Self<vMin then result := vMin else result := Self; End; function TQWordHelper.Max(vMax: QWord): QWord; Begin if Self>vMax then result := vMax else result := Self; End; function TQWordHelper.IsInRange(Low, High: QWord): Boolean; Begin result := ((Self >= Low) and (Self <= High)); End; Function TQWordHelper.Random:QWord; Begin Result := Self.RandomRange(Self.MinValue,Self.MaxValue); End; Function TQWordHelper.RandomRange(vMin, vMax :QWord):QWord; Var Diff : QWord; i, rLow, rHigh, vLow, vHigh :Int64; Begin Diff := vMax - vMin; if (Diff<=Int64.MaxValue) then begin I := Diff; result := System.Random(I)+vMin; end else begin rLow := System.Random(Int64.MaxValue); rHigh := System.Random(Int64.MaxValue); vLow := Diff and $FFFFFFFF; vHigh := Diff shr 32; result := (( rHigh * vLow ) shr 32 ) + (( rLow * vHigh ) shr 32 ) + ( rHigh * vHigh ) + vMin; end; End; function TQWordHelper.Clamp(vMin, vMax: QWord): QWord; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TQWordHelper.ToBoolean: Boolean; begin Result := (Self>0); end; function TQWordHelper.ToHexString: string; begin Result:=IntToHex(Self,15); end; {%endregion%} {%region%=====[ TSingleHelper ]=================================================} function TSingleHelper.ToString(const Decimals: Integer ): string; //Const FormatSetting :TFormatSettings Begin result := FloatToStrF(Self, ffNumber, 15 , Decimals, vPointSeparator); End; function TSingleHelper.Parse(Num: String; const defValue: Single): Boolean; var I: Single; Ok : Boolean; Begin result := False; Self := DefValue; if {%H-}Num.Contains('.') then Ok := TryStrToFloat(Num,I,vPointSeparator) else if Num.Contains(',') then Ok := TryStrToFloat(Num,I,vCommaSeparator) else Ok := TryStrToFloat(Num,I); if Ok then begin Result := True; Self := I; End; End; function TSingleHelper.Min(vMin: Single): Single; Begin if Self<vMin then result := vMin else result := Self; End; function TSingleHelper.Max(vMax: Single): Single; Begin if Self>vMax then result := vMax else result := Self; End; function TSingleHelper.IsInRange(Low, High: Single): Boolean; begin result := ((Self >= Low) and (Self <= High)); end; function TSingleHelper.Random : Single; Begin Result :=Self.RandomRange(Self.MinValue, Self.MaxValue); End; function TSingleHelper.RandomRange(vMin,vMax : Single): Single; Begin Result := Random * (vMax - vMin) + vMin; End; function TSingleHelper.Clamp(vMin, vMax: Single): Single; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TSingleHelper.Trunc: Integer; begin result := System.Trunc(Self); end; function TSingleHelper.Round: Integer; begin result := System.Round(Self); end; function TSingleHelper.Floor: Integer; Begin {$HINTS OFF} result :=0; if (Self=0.0) then exit else If (Self > 0) Then Result := System.Trunc(Self) Else Result := System.Trunc(Self-0.999999999); {$HINTS ON} End; function TSingleHelper.Ceil: Integer; begin {$HINTS OFF} Result := System.Trunc(Self); if (Self - Result) > 0 then Inc(Result); {$HINTS ON} end; function TSingleHelper.RoundInt: Single; begin {$HINTS OFF} //Result := system.int Result := System.Round(Self + 0.5); {$HINTS ON} end; function TSingleHelper.Fract: Single; begin result := Self - System.trunc(Self); end; function TSingleHelper.Sign: Single; begin If Self < 0.0 Then Result := -1.0 Else If Self > 0.0 Then Result := 1.0 Else Result := 0.0; end; function TSingleHelper.Reciprocal: Single; Const cEpsilon : Single = 1.4012984643248170709e-45; Var a: Single; Begin Result := 0; If Self = 0 Then exit; a := Self.Sign; If ((a * Self) >= cEpsilon) Then Result := 1.0 / Self Else Result := a * (1.0 / cEpsilon); End; function TSingleHelper.IsInfinity: Boolean; begin result := (Self = Self.NegativeInfinity) or (Self = Self.PositiveInfinity); end; function TSingleHelper.IsNan: Boolean; begin result := (Self = Self.NaN); end; function TSingleHelper.IsNegativeInfinity: Boolean; begin result := (Self = Self.NegativeInfinity) end; function TSingleHelper.IsPositiveInfinity: Boolean; begin Result := (Self = Self.PositiveInfinity); end; {%endregion%} {%region%=====[ TDoubleHelper ]=================================================} function TDoubleHelper.ToString(const Decimals: Integer): string; Begin result := FloatToStrF(Self, ffNumber, 15 , Decimals); End; function TDoubleHelper.Parse(Num: String; const defValue: Double): Boolean; var I:Double; Begin result := False; Self := DefValue; if TryStrToFloat(Num,I) then begin Result := True; Self := I; End; End; function TDoubleHelper.Min(vMin: Double): Double; Begin if Self<vMin then result := vMin else result := Self; End; function TDoubleHelper.Max(vMax: Double): Double; Begin if Self>vMax then result := vMax else result := Self; End; function TDoubleHelper.IsInRange(Low, High: Double): Boolean; begin result := ((Self >= Low) and (Self <= High)); end; function TDoubleHelper.Random : Double; Begin Result :=Self.RandomRange(Self.MinValue, Self.MaxValue); End; function TDoubleHelper.RandomRange(vMin,vMax : Double): Double; Begin Result := Random * (vMax - vMin) + vMin; End; function TDoubleHelper.Clamp(vMin, vMax: Double): Double; begin Result := Self; if Result > vMax then begin Result := vMax; exit; end; if Result < vMin then Result := vMin; end; function TDoubleHelper.Trunc: Integer; begin result := System.Trunc(Self); end; function TDoubleHelper.Round: Integer; begin result := System.Round(Self); end; function TDoubleHelper.Floor: Integer; Begin {$HINTS OFF} result :=0; if (Self=0.0) then exit else If (Self > 0) Then Result := System.Trunc(Self) Else Result := System.Trunc(Self-0.99999999999999999); {$HINTS ON} End; function TDoubleHelper.Ceil: Integer; begin {$HINTS OFF} Result := System.Trunc(Self); if (Self - Result) > 0 then Inc(Result); {$HINTS ON} end; function TDoubleHelper.RoundInt: Double; begin {$HINTS OFF} //Result := system.int Result := System.Round(Self + 0.5); {$HINTS ON} end; function TDoubleHelper.Fract: Double; begin result := Self - System.trunc(Self); end; function TDoubleHelper.Sign: Double; begin If Self < 0.0 Then Result := -1.0 Else If Self > 0.0 Then Result := 1.0 Else Result := 0.0; end; function TDoubleHelper.Reciprocal: Double; Const cEpsilon : Single = 1.4012984643248170709e-45; Var a: Double; Begin Result := 0; If Self = 0 Then exit; a := Self.Sign; If ((a * Self) >= cEpsilon) Then Result := 1.0 / Self Else Result := a * (1.0 / cEpsilon); End; function TDoubleHelper.IsInfinity: Boolean; begin Result := (Self = Self.NegativeInfinity) or (Self = Self.PositiveInfinity); end; function TDoubleHelper.IsNan: Boolean; begin Result := (Self = Self.NaN); end; function TDoubleHelper.IsNegativeInfinity: Boolean; begin Result := (Self = Self.NegativeInfinity); end; function TDoubleHelper.IsPositiveInfinity: Boolean; begin Result := (Self = Self.PositiveInfinity); end; {%endregion%} {%region%=====[ TStringHelper ]=================================================} procedure TStringHelper.SetFromSys(aString : String); Begin Self := SysToUTF8(aString); End; procedure TStringHelper.SetFromConsole(aString : String); Begin Self := ConsoleToUTF8(aString); End; procedure TStringHelper.SetToUTF8(aString : String); begin Self := Utf8EscapeControlChars(AString); End; function TStringHelper.ToSys : String; Begin result := UTF8ToSys(Self); End; function TStringHelper.ToConsole : String; Begin result := UTF8ToConsole(Self); //UTF8ToWinCP(Self); End; function TStringHelper.Trim: String; var i, l: Integer; begin l := UTF8Length(Self); i := 1; while (i <= l) and (Self[i] <= ' ') do Inc(i); if i > l then Result := '' else begin while Self[l] <= ' ' do Dec(l); Result := UTF8Copy(Self, i, l - i + 1); end; End; function TStringHelper.TrimLeft: String; var i, l : Integer; begin l := UTF8Length(Self); i := 1; while (i <= l) and (Self[i] <= ' ') do Inc(i); Result := UTF8Copy(Self, i, Maxint); End; function TStringHelper.TrimRight: String; var i : Integer; begin i := UTF8Length(Self); while (i > 0) and (Self[i] <= ' ') do Dec(i); Result := UTF8Copy(Self, 1, i); End; function TStringHelper.IsEmpty: Boolean; var i,l : Integer; begin l := UTF8Length(Self); Result := False; for i := 1 to l do if Self[i]>=' ' then Exit; Result := True; End; Function TStringHelper.GetChar(AIndex : Integer) : Char; begin Result := Self[1]; if AIndex>0 then if (AIndex<=Length) then result := Self[AIndex] else result := Self[Length]; end; Function TStringHelper.GetLength : Integer; Begin Result := UTF8Length(Self); End; function TStringHelper.ToUpper: String; Begin Result := UTF8UpperString(Self); End; function TStringHelper.ToLower: String; Begin Result := UTF8LowerString(Self); End; function TStringHelper.IsEquals(const Value : string; Const IgnoreCase : Boolean) : Boolean; Begin Result := (Self.Compare(Value,IgnoreCase) = 0); End; function TStringHelper.Compare(const Value : string; Const IgnoreCase : Boolean) : Integer; Var S1,S2 : String; Begin if IgnoreCase then Begin S1 := Self.ToUpper; S2 := {%H-}Value.ToUpper; End else begin S1 := Self; S2 := Value; End; Result := UTF8CompareText(S1,S2); End; procedure TStringHelper.RepeatChar(C: Char; Count: Integer); begin Self:=''; SetLength(Self, Count); if Count>0 then FillChar(Self[1], Count, c); end; procedure TStringHelper.RepeatStr(const s: String; Count: Integer); var p : PChar; Slen : Integer; begin SLen := UTF8Length(s); SetLength(Self, Count*SLen); p := PChar(Self); while Count > 0 do begin Move(PChar(Self)^, p^, SLen); Inc(p, SLen); Dec(Count); end; end; function TStringHelper.PadCenter(TotalLen : Integer; Const PadChar : Char) : String; Var l:Integer; S:String; Begin l := UTF8Length(Self); if l < TotalLen then begin S:=''; S.RepeatChar(PadChar, (TotalLen div 2) - (L div 2)); Result := S + Self; S.RepeatChar(PadChar, TotalLen - UTF8Length(Result)); Result := Result + S; end else Result := Self; End; function TStringHelper.PadCharRight(PadLen : Integer; Const PadChar : Char) : String; var i : Integer; More : Integer; Slen : Integer; begin SLen := UTF8Length(Self); More := Abs(PadLen) - Slen; if More>0 then begin if PadLen<0 then begin SetLength(Result{%H-}, Abs(PadLen)); Move(Self[1], Result[More+1], Slen); for i := 1 to More do Result[i] := PadChar; end else begin Result := Self; SetLength(Result, Abs(PadLen)); for i := SLen+1 to Slen+More do Result[i] := PadChar; end; end else Result := Self; End; function TStringHelper.PadCharLeft(PadLen : Integer; Const PadChar : Char) : String; Begin Result := Self.PadCharRight(-PadLen, PadChar); End; function TStringHelper.Pos(const SubStr: String; StartPos: integer): Integer; Begin Result := UTF8Pos(SubStr,Self,StartPos); End; function TStringHelper.PosBetween(const SubStr1, SubStr2: String; var StartPos, EndPos: Integer): Boolean; var REndPos, RStartPos :Integer; Begin Result:=False; StartPos:=-1; EndPos:=-1; RStartPos:= UTF8Pos(Substr1,Self); REndPos:= UTF8Pos(Substr2,Self); if (RStartPos>0) And (REndPos>0) then begin result:=True; StartPos:=RStartPos+UTF8Length(Substr1); EndPos:=REndpos-1; end; End; function TStringHelper.IndexOf(const SubStr: string; Start: Integer;IgnoreCase: Boolean): Integer; var S1, S2 : String; Begin S1 := Self; S2 := SubStr; if IgnoreCase then Begin S1 := Self.ToUpper; S2 := {%H-}SubStr.ToUpper; End; Result := S1.Pos(S2, Start); End; function TStringHelper.After(const SubStr: String; Position: Integer): String; var p,L,Start : Integer; begin p := UTF8Pos(SubStr, Self,Position); Result := ''; if p>=0 then begin Start:=p+UTF8Length(SubStr); L:=UTF8Length(Self)-(Start-1); Result := UTF8Copy(Self, Start, L); end; End; function TStringHelper.Before(const SubStr: String; Position: Integer): String; var p , L: Integer; begin p := UTF8Pos(SubStr, Self, Position); Result := ''; if p>=0 then begin L:=p-1; Result := Self.Copy(position, L); end; End; function TStringHelper.Between(const SubStr1, SubStr2: String): String; var StartPos,EndPos : Integer; begin StartPos:=0; EndPos:=0; if Self.PosBetween(SubStr1, SubStr2, StartPos, EndPos) then begin EndPos := EndPos + 1; Result := UTF8Copy(Self, StartPos, (EndPos-StartPos)); end else Result := ''; End; function TStringHelper.Mid(const SubStr1, SubStr2: String; Position: Integer): String; var p1,p2, ps,pe : Integer; begin p1 := UTF8Pos(SubStr1, Self, Position); if p1<=0 then Result := '' else begin if SubStr2='' then p2 := UTF8Pos(SubStr1, Self, p1+UTF8Length(SubStr1)) else p2 := UTF8Pos(SubStr2, Self, p1+UTF8Length(SubStr1)); if p2<=0 then begin ps := p1+UTF8Length(SubStr1); pe := UTF8Length(Self); Result := UTF8Copy(Self,ps, pe) end else begin ps := p1+UTF8Length(SubStr1); pe := p2-ps; Result := UTF8Copy(Self,ps ,pe); end; end; End; function TStringHelper.Copy(aStart, aLength: Integer): string; var L : Integer; begin L := UTF8Length(Self); result := Self; if (L=0) or (aStart < 1) or (aLength < 1) then Exit; if ((aStart + aLength) > L) then aLength := (L - aStart)+1; SetLength(Result,aLength); Move(Self[aStart], Result[1], aLength); //Result := UTF8Copy(Self,AStart,ALength); End; function TStringHelper.CopyPos(StartPos, EndPos: Integer): String; var Len:integer; begin if EndPos<StartPos then begin Len:=StartPos+EndPos; end else begin Len:=EndPos-StartPos; end; result:=Self.Copy(StartPos, Len+1); End; function TStringHelper.Insert(const SubStr: string; Position: Integer): String; Begin Result := Self; UTF8Insert(Substr,Result,Position); End; function TStringHelper.LeftOf(Position: Integer): String; Begin Result := UTF8Copy(Self, 1, Position-1); End; function TStringHelper.RightOf(Position: Integer): String; Begin Result := Self.Copy(Position+1, UTF8Length(Self)); End; function TStringHelper.ToWideString: WideString; Begin result := UTF8ToUTF16(Utf8EscapeControlChars(Self)); End; procedure TStringHelper.SetWideString(S: WideString); begin Self :=''; if System.Length(S) < 1 then Exit; WideCharToStrVar(PWideChar(S), Self); Utf8EscapeControlChars(Self) End; procedure TStringHelper.Parse(Num : Integer); Begin Self := IntToStr(Num); End; procedure TStringHelper.Parse(Num : Single; Const Decimals : Integer); Begin Self := FloatToStrF(Num, ffNumber, 15 , Decimals, vPointSeparator); End; procedure TStringHelper.Parse(Num : Double; Const Decimals : Integer); Begin Self := FloatToStrF(Num, ffNumber, 15 , Decimals, vPointSeparator); End; function TStringHelper.Surround(chs: string): string; Begin Result := chs + Self + chs; End; function TStringHelper.Surround(chsL, chsR: string): string; Begin Result := chsL + Self + chsR End; procedure TStringHelper.Implode(lst: TStringList; sep: string); var i,j : integer; s : string; begin S:=''; j:= lst.Count - 1; for i:=0 to j do begin if i < j then s := s + lst[i] + sep else s := s + lst[i]; // don't add last separator end; Self := s; End; function TStringHelper.Explode(sep: string): TStringList; var p : integer; begin p := Self.Pos(sep); Result := TStringList.Create; while p > 0 do begin Result.Add(Self.Copy(1,p-1)); if p <= Self.GetLength then Self := Self.Copy(p+ UTF8length(sep),Self.GetLength); p := Self.Pos(sep); end; Result.Add(Self); End; function TStringHelper.Contains(const SubStr: string; IgnoreCase: Boolean): Boolean; Begin if IgnoreCase then begin Result := (Self.ToUpper.Pos({%H-}Substr.ToUpper) > 0); end else Result := (Self.Pos(Substr) > 0); End; function TStringHelper.Quote: String; Begin Result := Self.Surround('"'); End; function TStringHelper.Replace(const OldPattern, NewPattern: string; IgnoreCase: Boolean): string; var rFlag : TReplaceFlags; Begin rFlag := [rfReplaceAll]; if IgnoreCase then rflag := rFlag + [rfIgnoreCase]; Result := UTF8StringReplace(Self, OldPattern, NewPattern,rFlag); End; function TStringHelper.RemoveLeft(StartIndex : Integer) : String; Var L : Integer; Begin L := UTF8Length(Self)-StartIndex; Result := Self.Copy(StartIndex,L); End; function TStringHelper.RemoveLeft(StartIndex, aCount : Integer) : String; Var L : Integer; Begin L := UTF8Length(Self)-StartIndex; Result := Self.Copy(0,StartIndex-aCount)+Self.Copy(StartIndex,L); End; function TStringHelper.RemoveRight(StartIndex : Integer) : String; Begin Result := Self.Copy(0,StartIndex); End; function TStringHelper.RemoveRight(StartIndex, aCount : Integer) : String; Var L : Integer; Begin L := UTF8Length(Self)-StartIndex-aCount; Result := Self.Copy(0,StartIndex)+Self.Copy(StartIndex+aCount,L); End; function TStringHelper.RemoveChar(aChar : Char; Const IgnoreCase : Boolean) : String; var I,L : Integer; c, c1 : Char; c2 : Char; Begin L := UTF8Length(Self); Result := ''; if IgnoreCase then c2 := {%H-}aChar.ToUpper else c2 := aChar; For I:=1 to L do begin c := Self[I]; if IgnoreCase then c1 := c.ToUpper else c1 := c; if (c1<>c2) then result := result + c; End; End; function TStringHelper.Remove(SubStr : String; Const IgnoreCase : Boolean) : String; Begin Result := Self.Replace(SubStr,'',IgnoreCase); End; function TStringHelper.Reverse: String; Begin Result := Utf8ReverseString(Self); End; function TStringHelper.Wrap(MaxCol: Integer): String; Begin Result := UTF8WrapText(Self,MaxCol); End; function TStringHelper.CountChars(C: Char): Integer; Var i,j,L:Integer; begin L:= UTF8Length(Self); J:=0; For i := 1 to L do begin if (Self[i] = C) then inc(J); end; Result := J; end; function TStringHelper.ToBoolean(Const DefTrue : String; Const defFalse : String; Const IgnoreCase : Boolean) : Boolean; begin if Self.Contains(DefTrue,IgnoreCase) then result := True else if Self.Contains(DefFalse,IgnoreCase) then result := False else result := True; end; function TStringHelper.ToInteger: Integer; Var I: Integer; Begin Result := 0; if TryStrToInt(Self,I) then begin result := I; End; end; function TStringHelper.ToSingle: Single; var I: Single; Ok : Boolean; Begin result := 0.0; if Self.Contains('.') then Ok := TryStrToFloat(Self,I,vPointSeparator) else if Self.Contains(',') then Ok := TryStrToFloat(Self,I,vCommaSeparator) else Ok := TryStrToFloat(Self,I); if Ok then begin Result := I; End; end; function TStringHelper.ToDouble: Double; var I: Double; Ok : Boolean; Begin result := 0.0; if Self.Contains('.') then Ok := TryStrToFloat(Self,I,vPointSeparator) else if Self.Contains(',') then Ok := TryStrToFloat(Self,I,vCommaSeparator) else Ok := TryStrToFloat(Self,I); if Ok then begin Result := I; End; end; function TStringHelper.ToInt64 : Int64; Var I: Int64; Begin Result := 0; if TryStrToInt64(Self,I) then begin result := I; End; end; function TStringHelper.ToByte: Byte; Var I: Integer; Begin Result := 0; if TryStrToInt(Self,I) then begin result := ClampByte(I); End; end; function TStringHelper.ComputeHash(Const IgnoreCase : Boolean = False) : Integer; Var i, j: Integer; Begin Result :=-1; I := UTF8Length(Self); J := Ord(Self[I]); Repeat if IgnoreCase then J := (J * cHash1 + Ord(UpCase(Self[I]))) else J := (J * cHash1 + Ord(Self[I])); Dec(I); Until I = 0; if IgnoreCase then Result := (J Mod cHash2) else Result := abs(J Mod cHash2); End; {%endregion%} {%region%=====[ TDateTimeHelper ]===============================================} function TDateTimeHelper.getYear: Word; var Y, M, D: Word; begin DecodeDate(Self, Y, M, D); Result := Y; end; function TDateTimeHelper.getMonth: Word; var Y, M, D: Word; begin DecodeDate(Self, Y, M, D); Result := M; end; function TDateTimeHelper.getDay: Word; var Y, M, D: Word; begin DecodeDate(Self, Y, M, D); Result := D; end; function TDateTimeHelper.getHour: Word; var H,M,S,MS: Word; begin DecodeTime(Self,H,M,S,MS); Result := H; end; function TDateTimeHelper.getMinute: Word; var H,M,S,MS: Word; begin DecodeTime(Self,H,M,S,MS); Result := M; end; function TDateTimeHelper.getSecond : Word; var H,M,S,MS: Word; begin DecodeTime(Self,H,M,S,MS); Result := S; end; Function TDateTimeHelper.getMillisecond : Word; var H,M,S,MS: Word; begin DecodeTime(Self,H,M,S,MS); Result := MS; end; procedure TDateTimeHelper.SetToDay; Begin Self := Date(); End; procedure TDateTimeHelper.SetToNow; Begin Self := Now; End; Procedure TDateTimeHelper.SetToTime; Begin Self := Time(); End; procedure TDateTimeHelper.SetTime(H, M, S : Integer); Begin if not(TryEncodeDateTime(Year,Month,Day,H,M,S,0, Self)) then Self.SetToNow; End; procedure TDateTimeHelper.SetDate(Y, M, D : Integer); Begin if not(TryEncodeDateTime(Y,M,D,Hour,Minute,Second,0, Self)) then Self.SetToNow; End; procedure TDateTimeHelper.SetFromString(ADateTimeStr : String; Const APAttern : String); Begin Self := ScanDateTime(APattern, ADateTimeStr); End; procedure TDateTimeHelper.SetFromUnixTimeStamp(ADate : Int64); Begin Self := UnixToDateTime(ADate); End; procedure TDateTimeHelper.SetFromMacTimeStamp(ADate : Int64); Begin Self := MacToDateTime(ADate); End; procedure TDateTimeHelper.SetFromUTC(UT : TDateTime); Begin Self := UniversalTimeToLocal(UT); End; procedure TDateTimeHelper.SetFromUTC(UT : TDateTime; ZOffset : Integer); Begin Self := UniversalTimeToLocal(UT,ZOffset); End; procedure TDateTimeHelper.SetFromJulian(JulianDate : Double); Begin Self := JulianDateToDateTime(JulianDate); End; procedure TDateTimeHelper.SetFromSQL(ADataTimeStr : String); var YYYY, MM, DD: word; S:String; begin try S := ADataTimeStr.Copy(1, 4); YYYY := S.ToInteger; // années sur deux chiffres if (YYYY < 100) then begin if (YYYY < 50) then YYYY := 2000 + YYYY else YYYY := 1900 + YYYY; end; MM := ADataTimeStr.Copy(6, 2).ToInteger; DD := ADataTimeStr.Copy(9, 2).ToInteger; Self := EncodeDate(YYYY, MM, DD); except Self := TDateTime(0.0); end; End; { Source : http://codes-sources.commentcamarche.net/source/36519-unite-randdate-fonction-randrangedate-et-randomdate-generatrices-de-dates-aleatoires } procedure TDateTimeHelper.SetRandomDate; var aD, MaxD,D, MaxM,M, MaxY,Y : Integer; begin MaxD := 31; MaxM := 12; MaxY := 9999; Y := RandomRange(1,MaxY+1); Y:=Y.Clamp(1,MaxY); if Y = MaxY then begin M := RandomRange(1,MaxM+1);//.Clamp(1,MaxM); M := M.Clamp(1,MaxM); end else begin M := RandomRange(1,12+1).Clamp(1,12); //M:= M.Clamp(1,12); end; aD := 0; case M of 2 : if SysUtils.IsLeapYear(Y) then aD := 29 else aD := 28; 4,6,9,11 : aD := 30; 1,3,5,7,8,10,12 : aD := 31; end; if M = MaxM then Begin D := RandomRange(1,MaxD+1); D := D.Clamp(1,MaxD) end else begin D := RandomRange(1,aD+1); D := D.Clamp(1,aD); end; Self := EncodeDate(Y,M,D); End; procedure TDateTimeHelper.SetRandomDate(StartDate, EndDate : TDateTime); var aD, MinD,MaxD,D, MinM,MaxM,M, MinY,MaxY,Y : Word; begin DecodeDate(StartDate,MinY,MinM,MinD); DecodeDate(EndDate,MaxY,MaxM,MaxD); Y := RandomRange(MinY,MaxY+1); Y := Y.Clamp(MinY,MaxY); if Y = MinY then begin M := RandomRange(MinM,12+1); M := M.Clamp(MinM,12); end else if Y = MaxY then begin M := RandomRange(1,MaxM+1); M := M.Clamp(1,MaxM); end else begin M := RandomRange(1,12+1).Clamp(1,12); // M := M.Clamp(1,12); end; aD := 0; case M of 2 : if SysUtils.IsLeapYear(Y) then aD := 29 else aD := 28; 4,6,9,11 : aD := 30; 1,3,5,7,8,10,12 : aD := 31; end; if M = MinM then Begin D := RandomRange(MinD,aD+1); D := D.Clamp(MinD,aD); end else if M = MaxM then Begin D := RandomRange(1,MaxD+1); D := D.Clamp(1,MaxD); end else Begin D := RandomRange(1,aD+1); D := D.Clamp(1,aD); end; Self := EncodeDate(Y,M,D); end; procedure TDateTimeHelper.SetFromFile(aFileName : String); Var fa : Longint; Begin fa:=FileAgeUTF8(aFileName); If Fa<>-1 then begin Self :=FileDateToDateTime(fa); end; End; function TDateTimeHelper.ToString(Const Format : TDateFormat; Const CustomFormat : string) : string; begin if Format = dfGMT then Result := FormatDateTime('ddd, d mmm yyyy hh:nn:ss', Self) + ' GMT' else if Format = dfUTC then Result := FormatDateTime('ddd, d mmm yyyy hh:nn:ss', Self) + ' UTC' else result := FormatDateTime(CustomFormat, Self) end; function TDateTimeHelper.ToSQL : String; var YYYY, MM, DD: word; begin DecodeDate(Self, YYYY, MM, DD); Result := Format('%.4d-%.2d-%.2d', [YYYY, MM, DD]); End; function TDateTimeHelper.DateToString(Const FormatStr : string) : String; Begin Result :=FormatDateTime(FormatStr, Self); End; function TDateTimeHelper.TimeToString(Const FormatStr : string) : String; Begin Result :=FormatDateTime(FormatStr, Self); End; function TDateTimeHelper.Compare(SecondDateTime : TDatetime) : Integer; Begin Result := DateUtils.CompareTime(Self,SecondDateTime); End; function TDateTimeHelper.CompareDate(SecondDate : TDateTime) : Integer; Begin Result := DateUtils.CompareDate(Self,SecondDate); End; function TDateTimeHelper.CompareTime(SecondTime : TDateTime) : Integer; Begin Result := DateUtils.CompareTime(Self,SecondTime); End; function TDateTimeHelper.AddYear(const A : Integer) : TDateTime; Begin Result := IncYear(Self,A) End; function TDateTimeHelper.AddMonth(const A : Integer) : TDateTime; Begin Result := IncMonth(Self,A) End; function TDateTimeHelper.AddDay(const A : Integer) : TDateTime; Begin Result := IncDay(Self,A) End; function TDateTimeHelper.AddWeek(const A : Integer) : TDateTime; Begin Result := IncWeek(Self,A) End; function TDateTimeHelper.AddHour(const A : Integer) : TDateTime; Begin Result := IncHour(Self,A) End; function TDateTimeHelper.AddMinute(const A : Integer) : TDateTime; begin Result := IncMinute(Self,A) end; function TDateTimeHelper.AddSecond(const A : Integer) : TDateTime; Begin Result := IncSecond(Self,A) End; function TDateTimeHelper.AddMilliSecond(const A : Integer) : TDateTime; Begin Result := IncMilliSecond(Self,A) End; function TDateTimeHelper.ToJulian : Double; Begin result := DateTimeToJulianDate(Self); End; function TDateTimeHelper.ToUnixTimeStamp : Int64; Begin result := DateTimeToUnix(Self); End; function TDateTimeHelper.ToMacTimeStamp : Int64; Begin Result := DateTimeToMac(Self); End; function TDateTimeHelper.ToUTC : TDateTime; Begin result := LocalTimeToUniversal(Self); End; function TDateTimeHelper.ToUTC(ZOffset : Integer) : TDateTime; Begin result := LocalTimeToUniversal(Self,ZOffset); End; function TDateTimeHelper.IsLeapYear : Boolean; Begin Result := IsInLeapYear(Self); End; function TDateTimeHelper.GetDaysInYear : Word; Begin result := DaysInYear(Self); End; function TDateTimeHelper.GetDaysInMonth : Word; Begin result := DaysInMonth(Self); End; function TDateTimeHelper.GetWeeksInYear : Word; Begin result := WeeksInYear(Self); End; function TDateTimeHelper.GetDayOfTheWeek : Word; Begin Result := DayOfTheWeek(Self); End; function TDateTimeHelper.GetWeekOfTheYear : Word; Begin Result := WeekOfTheYear(Self); End; function TDateTimeHelper.GetElapsedYears(ATo : TDateTime) : Integer; Begin Result := YearsBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedMonths(ATo : TDateTime) : Integer; Begin Result := MonthsBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedWeeks(ATo : TDateTime) : Integer; Begin Result := WeeksBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedDays(ATo : TDateTime) : Integer; Begin Result := DaysBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedHours(ATo : TDateTime) : Int64; Begin Result := HoursBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedMinutes(ATo : TDateTime) : Int64; Begin Result := MinutesBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedSeconds(ATo : TDateTime) : Int64; Begin Result := SecondsBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedMilliSeconds(ATo : TDateTime) : Int64; Begin Result := MilliSecondsBetween(Self,ATo); End; function TDateTimeHelper.GetElapsedPeriod(ATo : TDateTime) : TDateTime; Var Y,M,D : Word; Begin PeriodBetween(Self, ATo, Y, M, D); Result := EncodeDate(Y,M,D); End; {$IFDEF WINDOWS} procedure TDateTimeHelper.FromFileTime(const FileTime : TFileTime); const FileTimeBase = -109205.0; FileTimeStep: Extended = 24.0 * 60.0 * 60.0 * 1000.0 * 1000.0 * 10.0; // 100 nSek per Day Var Tmp : TDateTime; begin Tmp := Int64(FileTime) / FileTimeStep; Self := Tmp + FileTimeBase; end; {$ENDIF} {%endregion%} //============================================================================== Initialization // Format settings to convert a string to a float vPointSeparator := DefaultFormatSettings; vPointSeparator.DecimalSeparator := '.'; vPointSeparator.ThousandSeparator := ' ';// disable the thousand separator vCommaSeparator := DefaultFormatSettings; vCommaSeparator.DecimalSeparator := ','; vCommaSeparator.ThousandSeparator := ' ';// disable the thousand separator Finalization //============================================================================== End.
unit MainFrU; interface uses EventBus; type THideMenuEvent = class(TObject) private FHide: boolean; procedure SetHide(const Value: boolean); public constructor Create(const aHide: Boolean); property aHide: boolean read FHide write SetHide; end; implementation uses System.Classes; { THideMenuEvent } constructor THideMenuEvent.Create(const aHide: Boolean); begin FHide := aHide; end; procedure THideMenuEvent.SetHide(const Value: boolean); begin FHide := Value; end; end.
unit FolderList; interface uses Classes, DBTables, ComCtrls; type TObjectData = class(TPersistent) private FDataSet: TTable; FData: Pointer; FOnDataUpdate: TNotifyEvent; FModified: Boolean; protected function GetRefID : Integer; virtual; public constructor Create(RecID: Integer); virtual; procedure DataUpdate; procedure Load; virtual; abstract; procedure Save; virtual; abstract; property DataSet: TTable read FDataSet write FDataSet; property RefID: Integer read GetRefID; property Data: Pointer read FData write FData; property OnDataUpdate: TNotifyEvent read FOnDataUpdate write FOnDataUpdate; property Modified: Boolean read FModified write FModified; end; TFolderData = class(TObjectData) private FFolderID: Integer; FFolderDesc: string; protected function GetRefID : Integer; override; procedure PositionDataSet; procedure AssignTo(Dest: TPersistent); override; public constructor Create(RecID: Integer); override; procedure Load; override; procedure Save; override; property FolderID: Integer read FFolderID write FFolderID; property FolderDesc: string read FFolderDesc write FFolderDesc; end; THostData = class(TObjectData) private FHostID: Integer; FHostName: string; FHostDesc: string; FFolderID: Integer; FFullName: string; FOrganization: string; FEmail: string; FReply: string; FIncludeDuringScan: Boolean; FPort: Integer; FLoginRequired: Boolean; FUserID: string; FPassword: string; protected function GetRefID : Integer; override; procedure PositionDataSet; procedure AssignTo(Dest: TPersistent); override; public constructor Create(RecID: Integer); override; procedure Load; override; procedure Save; override; property HostID: Integer read FHostID write FHostID; property HostName: string read FHostName write FHostName; property HostDesc: string read FHostDesc write FHostDesc; property FolderID: Integer read FFolderID write FFolderID; property FullName: string read FFullName write FFullName; property Organization: string read FOrganization write FOrganization; property Email: string read FEmail write FEmail; property Reply: string read FReply write FReply; property IncludeDuringScan: Boolean read FIncludeDuringScan write FIncludeDuringScan; property Port: Integer read FPort write FPort; property LoginRequired: Boolean read FLoginRequired write FLoginRequired; property UserID: string read FUserID write FUserID; property Password: string read FPassword write FPassword; end; TNewsgroupData = class(TObjectData) private FNewsgroupID: Integer; FNewsgroupName: string; FNewsgroupDesc: string; FHostID: Integer; FSubscribed: Boolean; FHiMsg: Integer; FList: TStringList; protected function GetRefID : Integer; override; procedure PositionDataSet; procedure AssignTo(Dest: TPersistent); override; public constructor Create(RecID: Integer); override; destructor Destroy; override; procedure Load; override; procedure Save; override; property NewsgroupID: Integer read FNewsgroupID write FNewsgroupID; property NewsgroupName: string read FNewsgroupName write FNewsgroupName; property NewsgroupDesc: string read FNewsgroupDesc write FNewsgroupDesc; property HostID: Integer read FHostID write FHostID; property Subscribed: Boolean read FSubscribed write FSubscribed; property HiMsg: Integer read FHiMsg write FHiMsg; property List: TStringList read FList write FList; end; TObjectDataClass = class of TObjectData; implementation uses MainForm, Datamodule, SysUtils; constructor TObjectData.Create(RecID: Integer); begin inherited Create; Load; end; function TObjectData.GetRefID : Integer; begin Result := 0; end; procedure TObjectData.DataUpdate; begin if Assigned(FOnDataUpdate) then FOnDataUpdate(Self); end; {=====================================================} constructor TFolderData.Create(RecID: Integer); begin FolderID := RecID; DataSet := dataMain.tablFolders; inherited Create(RecID); end; function TFolderData.GetRefID : Integer; begin Result := FolderID; end; procedure TFolderData.PositionDataSet; begin if not DataSet.FindKey([FolderID]) then raise Exception.Create('Unable to locate FolderID: '+IntToStr(FolderID)); end; procedure TFolderData.Load; begin PositionDataSet; with dataMain do begin FolderID := tablFoldersFolder_ID.Value; FolderDesc := tablFoldersFolder_Desc.Value; end; DataUpdate; end; procedure TFolderData.Save; begin PositionDataSet; with dataMain do begin DataSet.Edit; tablFoldersFolder_ID.Value := FolderID; tablFoldersFolder_Desc.Value := FolderDesc; DataSet.Post; end; end; procedure TFolderData.AssignTo(Dest: TPersistent); var Item: TFolderData; begin if not (Dest is TFolderData) then inherited AssignTo(Dest) else begin Item := Dest as TFolderData; Item.DataSet := DataSet; Item.FolderID := FolderID; Item.FolderDesc := FolderDesc; end; end; {===================================================================} constructor THostData.Create(RecID: Integer); begin HostID := RecID; DataSet := dataMain.tablHosts; inherited Create(RecID); end; function THostData.GetRefID : Integer; begin Result := HostID; end; procedure THostData.PositionDataSet; begin if not DataSet.FindKey([HostID]) then raise Exception.Create('Unable to locate HostID: '+IntToStr(HostID)); end; procedure THostData.Load; begin PositionDataSet; with dataMain do begin HostID := tablHostsHost_ID.Value; HostName := tablHostsHost_Name.Value; HostDesc := tablHostsHost_Desc.Value; FolderID := tablHostsFolder_ID.Value; FullName := tablHostsFull_Name.Value; Organization := tablHostsOrganization.Value; Email := tablHostsEmail.Value; Reply := tablHostsReply.Value; IncludeDuringScan := tablHostsInclude_During_Scan.Value; Port := tablHostsPort.Value; LoginRequired := tablHostsLogin_Required.Value; UserID := tablHostsUser_ID.Value; Password := tablHostsPassword.Value; end; DataUpdate; end; procedure THostData.Save; begin PositionDataSet; with dataMain do begin DataSet.Edit; tablHostsHost_ID.Value := HostID; tablHostsHost_Name.Value := HostName; tablHostsHost_Desc.Value := HostDesc; tablHostsFolder_ID.Value := FolderID; tablHostsFull_Name.Value := FullName; tablHostsOrganization.Value := Organization; tablHostsEmail.Value := Email; tablHostsReply.Value := Reply; tablHostsInclude_During_Scan.Value := IncludeDuringScan; tablHostsPort.Value := Port; tablHostsLogin_Required.Value := LoginRequired; tablHostsUser_ID.Value := UserID; tablHostsPassword.Value := Password; DataSet.Post; end; end; procedure THostData.AssignTo(Dest: TPersistent); var Item: THostData; begin if not (Dest is THostData) then inherited AssignTo(Dest) else begin Item := Dest as THostData; Item.DataSet := DataSet; Item.HostID := HostID; Item.HostName := HostName; Item.HostDesc := HostDesc; Item.FolderID := FolderID; Item.FullName := FullName; Item.Organization := Organization; Item.Email := Email; Item.Reply := Reply; Item.IncludeDuringScan := IncludeDuringScan; Item.Port := Port; Item.LoginRequired := LoginRequired; Item.UserID := UserID; Item.Password := Password; end; end; {===================================================================} constructor TNewsgroupData.Create(RecID: Integer); begin NewsgroupID := RecID; DataSet := dataMain.tablNewsgroups; inherited Create(RecID); FList := TStringList.Create; end; destructor TNewsgroupData.Destroy; begin FList.Free; inherited Destroy; end; function TNewsgroupData.GetRefID : Integer; begin Result := NewsgroupID; end; procedure TNewsgroupData.PositionDataSet; begin if not DataSet.FindKey([NewsgroupID]) then raise Exception.Create('Unable to locate NewsgroupID: '+IntToStr(NewsgroupID)); end; procedure TNewsgroupData.Load; begin PositionDataSet; with dataMain do begin NewsgroupID := tablNewsgroupsNewsgroup_ID.Value; NewsgroupName := tablNewsgroupsNewsgroup_Name.Value; NewsgroupDesc := tablNewsgroupsNewsgroup_Desc.Value; HostID := tablNewsgroupsHost_ID.Value; Subscribed := tablNewsgroupsSubscribed.Value; HiMsg := tablNewsgroupsMsg_High.Value; end; DataUpdate; end; procedure TNewsgroupData.Save; begin PositionDataSet; with dataMain do begin DataSet.Edit; tablNewsgroupsNewsgroup_ID.Value := NewsgroupID; tablNewsgroupsNewsgroup_Name.Value := NewsgroupName; tablNewsgroupsNewsgroup_Desc.Value := NewsgroupDesc; tablNewsgroupsHost_ID.Value := HostID; tablNewsgroupsSubscribed.Value := Subscribed; tablNewsgroupsMsg_High.Value := HiMsg; DataSet.Post; end; end; procedure TNewsgroupData.AssignTo(Dest: TPersistent); var Item: TNewsgroupData; begin if not (Dest is TNewsgroupData) then inherited AssignTo(Dest) else begin Item := Dest as TNewsgroupData; Item.DataSet := DataSet; Item.NewsgroupID := NewsgroupID; Item.NewsgroupName := NewsgroupName; Item.NewsgroupDesc := NewsgroupDesc; Item.HostID := HostID; Item.Subscribed := Subscribed; Item.HiMsg := HiMsg; Item.List.Assign(List); end; end; end.
{ ChordClopedia v0.9 source code ------------------------------ software: freeware, compiled in april 1999 with BPC v7.0 author: Apreutesei Cosmin e-mail: cosmin.apreutesei@gmail.com license: GPL General Public License } {$V-} uses windos, strings, mycrt; const scale_namelen=20; MAXFORM=6; type Tscale=record name:string[scale_namelen]; rd:array[0..6] of byte; { rd = root distance } end; ATscale=array[1..2000] of Tscale; PATscale=^ATscale; Tabsnote=record { an abstract note that is ... } note:integer; { (note number in a scale)-1; -1=not used } dist:integer; { distance in s-tones relative to that note } end; { dist < 0 means flat, > 0 means sharp, so 0 means major } Tchord=array[1..MAXFORM] of Tabsnote; const exit_s='Have a musical day.'; title_s:string='The═ChordClopedia═v0.9═(c)''99═by═woods'; author_notice:array[1..5] of string=( 'software: freeware, compiled in april 1999 using bp7', 'proramme: cosmin apreutesei', 'address: str. marasesti 114/A/36, bacau, 5500', 'phone: (+40)034-184570', 'e-mail: woodsmailbox@yahoo.com'); memerr_s='Error allocating memory.'; stringnum=6; { we're talking about a general 6 strings guitar } {maj_scale:TScale=(name:'Major';rd:(0,2,4,5,7,9,11));} notes:array[0..11] of string[2] = ('A','A#','B','C','C#','D','D#','E','F','F#','G','G#'); notes2:array[0..11] of string[2] = (' ','Bb',' ',' ','Db',' ','Eb',' ',' ','Gb',' ','Ab'); ncol:array[0..11] of byte = (12,12,13,14,14,10,10,11,9,9,8,8); main_num=5; { number of options in the main menu } main_options:array[1..main_num] of string=( (' guitar chord formation for '+char(stringnum+byte('0'))+' string guitars '), (' musical and chord theory '), (' apendixes '), (' about the author '), (' quiT ')); filename='scales.txt'; r_key=77; l_key=75; u_key=72; d_key=80; F2_key=60; F3_key=61; enter_key=28; spc_key=57; esc_key=1; tab_key=15; pgup_key=73; pgdn_key=81; scale_key=F2_key; graph_key=F3_key; var cstrings:array[1..stringnum] of byte; { the current guitar tunning in s-tones relative to the note A } inf:text; { the file containing the scales } scalenum,scale_p:integer; scales:PATscale; scale:Tscale; { current scale intervals(key=scale[0]=0) } triads:array[1..7] of Tchord; { triads } chord:Tchord; { current chord } intervals:array[0..21] of integer; { scale notes by semitons } form:array[0..21] of boolean; { intervals used in the current chord } oldexitproc:procedure; { the exit/error handler } endmsg:string[80]; { writeln-ed on screen at program finish } path:string; { program's directory: database files must be there } cmenu,lmenu:byte; { last/current position on the main menu } ucol,mcol:byte; { normal color, inverse color } tcol,acol:byte; { title color, active-item color } rcol:byte; { relief color } f,ff:integer; { contors } i,ii:integer; { temps used in sub-sub..-procedures } s,ss:string; { completes a string with spaces until <tof> } procedure tab(var sf:string;tof:byte); begin for ii:=length(sf)+1 to tof do s[ii]:=' '; s[0]:=char(tof); end; function modnote(notef:integer):integer; { modulo 12 } begin modnote:=(notef+12*5) mod 12; end; procedure myexit; far; begin { my own exitproc } exitproc:=@oldexitproc; cls(' ',7); gotoxy(0,0); writeln('════════════════════'+title_s+'═════════════════════'); for f:=1 to 5 do writeln(author_notice[f]); writeln(#13#10,endmsg); freemem(scales,scalenum*sizeof(TScale)); end; procedure general_load; { load scales and stuff from scales.txt } begin endmsg:='Error in file <'+path+filename+'>'; assign(inf,path+filename); reset(inf); for f:=1 to stringnum do read(inf,cstrings[f]); { get the standard tunning } { get 7 triads } for f:=1 to 7 do begin for ff:=1 to MAXFORM do begin { get notes } read(inf,i); triads[f,ff].note:=i-1; end; for ff:=1 to MAXFORM do { get flat/sharps } read(inf,triads[f,ff].dist); end; readln(inf,scalenum); { get the number of availible scales } endmsg:=memerr_s; getmem(scales,scalenum*sizeof(TScale)); endmsg:='Error in file <'+path+filename+'>'; for ff:=1 to scalenum do begin readln(inf,scales^[ff].name); for f:=1 to 6 do begin read(inf,scales^[ff].rd[f]); scales^[ff].rd[0]:=0; end; readln(inf); end; close(inf); scale:=scales^[scale_p]; endmsg:=exit_s; end; {$I form.pas} {$I fileview.pas} {$I matrix.pas} {-------------------------------main-code-----------------------------------} label l1; var _S,_dir,_name,_ext:array[0..255] of char; begin exitproc:=@myexit; {scale:=maj_scale;} scale_p:=1; { no scale from file } { take the program's path } FileSplit(FileExpand(_S,GetArgStr(_S,0,255)),_dir,_name,_ext); path:=StrPas(_dir); f:=length(path); while path[f] <> '\' do dec(f); path[0]:=char(f); ucol:=colof(7,0); mcol:=colof(white,1); tcol:=colof(white,0); acol:=colof(lightcyan,0); rcol:=colof(yellow,0); cmenu:=1; ctab:=1; write('Loading..'); general_load; chord:=triads[1]; { load selected flags } for f:=1 to 6 do if chord[f].note >= 0 then form[scale.rd[chord[f].note]+chord[f].dist]:=true; cls(' ',ucol); l1: gotoxy(0,0); border(0,0,scrx,scry,ucol); _c_wrs(0,' '+title_s+' ',tcol); _c_wrs(3,' Main Menu ',tcol); for f:=1 to main_num do c_wrs(4+(f shl 1),main_options[f],ucol); c_wrs(4+(cmenu shl 1),main_options[cmenu],mcol); s:='F1=Help════ESC=Exit'; wrs(2,24,s,ucol); repeat lmenu:=cmenu; case getscan of 72: if cmenu > 1 then dec(cmenu); { up } 80: if cmenu < main_num then inc(cmenu); 1: begin endmsg:=exit_s; exit; end; { down } 28: case cmenu of { enter } 1: begin chord_formation; goto l1; end; 2: begin view_file('theory.txt'); goto l1; end; 3: begin view_file('appendix.txt'); goto l1; end; 4: begin matrix; cls(' ',ucol); goto l1; end; 5: begin exit; end; end; end; if lmenu <> cmenu then begin c_wrs(4+(lmenu shl 1),main_options[lmenu],ucol); c_wrs(4+(cmenu shl 1),main_options[cmenu],mcol); end; until false; end.
{$include kode.inc} unit kode_random; // FreePascal's function random uses the MersenneTwister // (for further details, see the file rtl/inc/system.inc) //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- const KRandomMax : LongInt = $7FFFFFFF; //-------- procedure KRandomSeed(ASeed:LongInt); function KRandomInt : LongInt; function KRandomSignedInt : LongInt; function KRandomRangeInt(minval,maxval:longint) : LongInt; function KRandom : Single; function KRandomSigned : Single; function KRandomRange(minval,maxval:single) : Single; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses Math; //---------- // 0..$7fffffff procedure KRandomSeed(ASeed:LongInt); begin Randomize; end; //---------- // 0..KRandomMax function KRandomInt : LongInt; //var // i : longint; begin result := Random($7FFFFFFF); end; //---------- // -KRandomMax..KRandomMax function KRandomSignedInt : LongInt; begin result := Random($FFFFFFFF); end; //---------- // inclusive function KRandomRangeInt(minval,maxval:longint) : LongInt; var range : longint; begin range := maxval-minval+1; if range <= 0 then result := minval else result := minval + (KRandomInt mod range ); end; //---------- // 0..1 function KRandom : Single; begin result := Random; end; //---------- // -1..1 function KRandomSigned : Single; begin result := (Random*2) - 1; end; //---------- // inclusive function KRandomRange(minval,maxval:single) : Single; begin result := minval + (KRandom * (maxval - minval) ); end; //---------------------------------------------------------------------- end. //---------------------------------------------------------------------- // // http://www.musicdsp.org/archive.php?classid=1#217 //---------------------------------------------------------------------- (* { "This is quite a good PRNG! The numbers it generates exhibit a slight a pattern (obviously, since it's not very sophisticated) but they seem quite usable! The real FFT spectrum is very flat and "white" with just one or two aberrant spikes while the imaginary spectrum is almost perfect (as is the case with most PRNGs). Very nice! Either that or I need more practice with MuPad.." "Alternatively you can do: double b_noiselast = b_noise; b_noise = b_noise + 19; b_noise = b_noise * b_noise; b_noise = b_noise + ((-b_noise + b_noiselast) * 0.5); int i_noise = b_noise; b_noise = b_noise - i_noise; This will remove the patterning." } //---------- var rand1_noise : single = 19.1919191919191919191919191919191919191919; rand1_pattern : single = 19; // 1e-19 //---------- // 0..1 function KRandom : Single; var temp : single; i : integer; begin temp := rand1_noise; rand1_noise := rand1_noise + rand1_pattern; rand1_noise := rand1_noise * rand1_noise; rand1_noise := (rand1_noise+temp) * 0.5; i := trunc(rand1_noise); rand1_noise := rand1_noise - i; result := rand1_noise; end; //---------- // -1..1 function KRandomSigned : Single; var i_noise : longint; begin rand1_noise := rand1_noise * rand1_noise; i_noise := trunc(rand1_noise); // |0; rand1_noise := rand1_noise - i_noise; result := rand1_noise - 0.5; rand1_noise := rand1_noise + rand1_pattern; end; *) //---------------------------------------------------------------------- // //---------------------------------------------------------------------- (* { This can be used to generate random numeric sequences or to synthesise a white noise audio signal. If you only use some of the bits, use the most significant bits by shifting right. Do not just mask off the low bits. } var rand2_seed : LongWord = 22222; // Change this for different random sequences. //---------- procedure KRandom2_Seed(aSeed:LongWord); begin rand2_seed := aSeed end; //---------- function KRandom2_Int : LongWord; begin rand2_seed := (rand2_seed * 196314165) + 907633515; result := rand2_seed; end; function KRandom2_Byte : Byte; begin rand2_seed := (rand2_seed * 196314165) + 907633515; result := rand2_seed shr 24; end; *) //---------------------------------------------------------------------- // gaussian random numbers // http://www.musicdsp.org/archive.php?classid=5#129 //---------------------------------------------------------------------- (* { Gaussian random numbers This algorithm (adapted from "Natur als fraktale Grafik" by Reinhard Scholl) implements a generation method for gaussian distributed random numbers with mean=0 and variance=1 (standard gaussian distribution) mapped to the range of -1 to +1 with the maximum at 0. For only positive results you might abs() the return value. The q variable defines the precision, with q=15 the smallest distance between two numbers will be 1/(2^q div 3)=1/10922 which usually gives good results. Note: the random() function used is the standard random function from Delphi/Pascal that produces *linear* distributed numbers from 0 to parameter-1, the equivalent C function is probably rand(). } const rand3_q = 15; rand3_c1 = (1 shl rand3_q)-1; rand3_c2 = (rand3_c1 div 3)+1; rand3_c3 = 1/rand3_c1; //---------- function KRandom3_Gaussian : Single; begin result := (2*(random(rand3_c2)+random(rand3_c2)+random(rand3_c2))-3*(rand3_c2-1))*rand3_c3; end; *) //---------------------------------------------------------------------- // ranmar //---------------------------------------------------------------------- (* const rand4_Seeded : Boolean = False; var rand4_u : array [0..97] of Double; rand4_c, rand4_cd, rand4_cm : Double; rand4_i97, rand4_j97 : Integer; //---------- { This is the initialization routine for the random number generator RANMAR() NOTE: The seed variables can have values between: 0 <= IJ <= 31328 0 <= KL <= 30081 The random number sequences created by these two seeds are of sufficient length to complete an entire calculation with. For example, if sveral different groups are working on different parts of the same calculation, each group could be assigned its own IJ seed. This would leave each group with 30000 choices for the second seed. That is to say, this random number generator can create 900 million different subsequences -- with each subsequence having a length of approximately 10^30. Use IJ = 1802 & KL = 9373 to test the random number generator. The subroutine RANMAR should be used to generate 20000 random numbers. Then display the next six random numbers generated multiplied by 4096*4096 If the random number generator is working properly, the random numbers should be: 6533892.0 14220222.0 7275067.0 6172232.0 8354498.0 10633180.0 } procedure KRandom4_mseed(IJ, KL : Integer); var i, j, k, l, ii, jj, m : Integer; s, t : Double; begin if (ij<0) or (ij>31328) or (kl<0) or (kl>30081) then //raise Exception.Create('Random generator seed not within the valid range!'); exit; i := (ij div 177) mod 177 + 2; j := ij mod 177 + 2; k := (kl div 169) mod 178 + 1; l := kl mod 169; for ii:=1 to 97 do begin s := 0.0; t := 0.5; for jj:=1 to 24 do begin m := (((i*j) mod 179)*k) mod 179; i := j; j := k; k := m; l := (53*l + 1) mod 169; if ((l*m) mod 64 >= 32) then s := s + t; t := t*0.5; end; rand4_u[ii] := s; end; rand4_c := 362436.0 / 16777216.0; rand4_cd := 7654321.0 / 16777216.0; rand4_cm := 16777213.0 / 16777216.0; rand4_i97 := 97; rand4_j97 := 33; rand4_Seeded := True; end; //---------- function KRandom4_mrand: Double; var uni: Double; begin if not rand4_Seeded then exit(0);//raise Exception.Create('Random generator not seeded!'); uni := rand4_u[rand4_i97] - rand4_u[rand4_j97]; if (uni < 0.0) then uni := uni + 1.0; rand4_u[rand4_i97] := uni; Dec(rand4_i97); if rand4_i97 = 0 then rand4_i97 := 97; dec(rand4_j97); if rand4_j97 = 0 then rand4_j97 := 97; rand4_c := rand4_c - rand4_cd; if rand4_c < 0.0 then rand4_c := rand4_c + rand4_cm; uni := uni - rand4_c; if uni < 0.0 then uni := uni + 1.0; Result := uni; end; end. *) //---------------------------------------------------------------------- // linear congruential generator // http://rosettacode.org/wiki/Linear_congruential_generator#Pascal //---------------------------------------------------------------------- (* Program LinearCongruentialGenerator(output); var x1, x2: int64; function bsdrand: longint; const a = 1103515245; c = 12345; m = 2147483648; begin x1 := (a * x1 + c) mod m; bsdrand := x1; end; function msrand: longint; const a = 214013; c = 2531011; m = 2147483648; begin x2 := (a * x2 + c) mod m; msrand := x2 div 65536; end; var i: longint; begin writeln(' BSD MS'); x1 := 0; x2 := 0; for i := 1 to 10 do writeln(bsdrand:12, msrand:12); end. *) //---------------------------------------------------------------------- // rmar // //---------------------------------------------------------------------- (* unit rmar; { This random number generator originally appeared in "Toward a Universal Random Number Generator" by George Marsaglia and Arif Zaman. Florida State University Report: FSU-SCRI-87-50 (1987) It was later modified by F. James and published in "A Review of Pseudo- random Number Generators" THIS IS THE BEST KNOWN RANDOM NUMBER GENERATOR AVAILABLE. (However, a newly discovered technique can yield a period of 10^600. But that is still in the development stage.) It passes ALL of the tests for random number generators and has a period of 2^144, is completely portable (gives bit identical results on all machines with at least 24-bit mantissas in the floating point representation). The algorithm is a combination of a Fibonacci sequence (with lags of 97 and 33, and operation "subtraction plus one, modulo one") and an "arithmetic sequence" (using subtraction). ======================================================================== C language version was written by Jim Butler, and was based on a FORTRAN program posted by David LaSalle of Florida State University. Adapted for Delphi by Anton Zhuchkov (fireton@mail.ru) in February, 2002 } interface { This is the initialization routine for the random number generator RANMAR() NOTE: The seed variables can have values between: 0 <= IJ <= 31328 0 <= KL <= 30081 The random number sequences created by these two seeds are of sufficient length to complete an entire calculation with. For example, if sveral different groups are working on different parts of the same calculation, each group could be assigned its own IJ seed. This would leave each group with 30000 choices for the second seed. That is to say, this random number generator can create 900 million different subsequences -- with each subsequence having a length of approximately 10^30. Use IJ = 1802 & KL = 9373 to test the random number generator. The subroutine RANMAR should be used to generate 20000 random numbers. Then display the next six random numbers generated multiplied by 4096*4096 If the random number generator is working properly, the random numbers should be: 6533892.0 14220222.0 7275067.0 6172232.0 8354498.0 10633180.0 } procedure RMSeed(IJ, KL : Integer); { This is the random number generator proposed by George Marsaglia in Florida State University Report: FSU-SCRI-87-50 } function RMRandom: Double; const Seeded : Boolean = False; implementation uses SysUtils; var u : array [0..97] of Double; c, cd, cm : Double; i97, j97 : Integer; procedure RMSeed(IJ, KL : Integer); var i, j, k, l, ii, jj, m : Integer; s, t : Double; begin if (ij<0) or (ij>31328) or (kl<0) or (kl>30081) then raise Exception.Create('Random generator seed not within the valid range!'); i := (ij div 177) mod 177 + 2; j := ij mod 177 + 2; k := (kl div 169) mod 178 + 1; l := kl mod 169; for ii:=1 to 97 do begin s := 0.0; t := 0.5; for jj:=1 to 24 do begin m := (((i*j) mod 179)*k) mod 179; i := j; j := k; k := m; l := (53*l + 1) mod 169; if ((l*m) mod 64 >= 32) then s := s + t; t := t*0.5; end; u[ii] := s; end; c := 362436.0 / 16777216.0; cd := 7654321.0 / 16777216.0; cm := 16777213.0 / 16777216.0; i97 := 97; j97 := 33; Seeded := True; end; function RMRandom: Double; var uni: Double; begin if not Seeded then raise Exception.Create('Random generator not seeded!'); uni := u[i97] - u[j97]; if (uni < 0.0) then uni := uni + 1.0; u[i97] := uni; Dec(i97); if i97 = 0 then i97 := 97; dec(j97); if j97 = 0 then j97 := 97; c := c - cd; if c < 0.0 then c := c + cm; uni := uni - c; if uni < 0.0 then uni := uni + 1.0; Result := uni; end; end. *) //---------------------------------------------------------------------- // // // //---------------------------------------------------------------------- (* unit z_random; // http://en.wikipedia.org/wiki/List_of_pseudorandom_number_generators //http://en.wikipedia.org/wiki/Linear_congruential_generator interface //procedure KRandomSeed(pattern:Single); function KRandom : Single; function KRandomSigned : Single; function KRandomInt : LongWord; function KRandomGaussian : Single; implementation uses math; // power //http://www.musicdsp.org/archive.php?classid=1#217 { "This is quite a good PRNG! The numbers it generates exhibit a slight a pattern (obviously, since it's not very sophisticated) but they seem quite usable! The real FFT spectrum is very flat and "white" with just one or two aberrant spikes while the imaginary spectrum is almost perfect (as is the case with most PRNGs). Very nice! Either that or I need more practice with MuPad.." "Alternatively you can do: double b_noiselast = b_noise; b_noise = b_noise + 19; b_noise = b_noise * b_noise; b_noise = b_noise + ((-b_noise + b_noiselast) * 0.5); int i_noise = b_noise; b_noise = b_noise - i_noise; This will remove the patterning." } //const var g_noise : single = 19.1919191919191919191919191919191919191919; g_pattern : single = 19; // 1e-19 //---------- {procedure KRandomSeed(pattern:Single); begin g_pattern := pattern; end;} //---------- // 0..1 function KRandom : Single; var temp : single; i : integer; begin temp := g_noise; g_noise := g_noise + g_pattern; g_noise := g_noise * g_noise; g_noise := (g_noise+temp) * 0.5; i := trunc(g_noise); g_noise := g_noise - i; result := g_noise; end; //---------- // -1..1 function KRandomSigned : Single; var i_noise : longint; begin g_noise := g_noise * g_noise; i_noise := trunc(g_noise); // |0; g_noise := g_noise - i_noise; result := g_noise - 0.5; g_noise := g_noise + g_pattern; end; //---------- // Pseudo-Random generator { This can be used to generate random numeric sequences or to synthesise a white noise audio signal. If you only use some of the bits, use the most significant bits by shifting right. Do not just mask off the low bits. } var r_randSeed : LongWord = 22222; // Change this for different random sequences. function KRandomInt : LongWord; begin r_randSeed := (r_randSeed * 196314165) + 907633515; result := r_randSeed; end; //---------- // http://rosettacode.org/wiki/Knuth_shuffle#Pascal program Knuth; const max = 10; type list = array [1..max] of integer; procedure shuffle(var a: list); var i,k,tmp: integer; begin randomize; for i := max downto 2 do begin k := random(i) + 1; if (a[i] <> a[k]) then begin tmp := a[i]; a[i] := a[k]; a[k] := tmp end end end; { Test and display } var a: list; i: integer; begin for i := 1 to max do a[i] := i; shuffle(a); for i := 1 to max do write(a[i], ' '); writeln end. //---------- // http://www.musicdsp.org/archive.php?classid=5#129 { Gaussian random numbers This algorithm (adapted from "Natur als fraktale Grafik" by Reinhard Scholl) implements a generation method for gaussian distributed random numbers with mean=0 and variance=1 (standard gaussian distribution) mapped to the range of -1 to +1 with the maximum at 0. For only positive results you might abs() the return value. The q variable defines the precision, with q=15 the smallest distance between two numbers will be 1/(2^q div 3)=1/10922 which usually gives good results. Note: the random() function used is the standard random function from Delphi/Pascal that produces *linear* distributed numbers from 0 to parameter-1, the equivalent C function is probably rand(). } const gr_q = 15; gr_c1 = (1 shl gr_q)-1; gr_c2 = (gr_c1 div 3)+1; gr_c3 = 1/gr_c1; //---------- function KRandomGaussian : Single; begin result := (2*(random(gr_c2)+random(gr_c2)+random(gr_c2))-3*(gr_c2-1))*gr_c3; end; //---------- // http://en.wikipedia.org/wiki/Xorshift uint32_t xor128(void) { static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; uint32_t t; t = x ^ (x << 11); x = y; y = z; z = w; return w = w ^ (w >> 19) ^ (t ^ (t >> 8)); } function KRandom_XorShift128 : longword; var x,y,z,w,t : longword; begin x := 123456789; y := 362436069; z := 521288629; w := 88675123; t := x ** x << 11; // x ^ (x << 11); x := y; y := z; z := w; w := w ** (w >> 19) ** (t ** (t >> 8)); result := w; end; end. *)