text
stringlengths
14
6.51M
unit UserFld; interface Uses Classes,DB,GUIField,SysUtils; Type TFieldDescr=class(TObject) private function BoolToStr(b:boolean):string; function GetNextParam(var s:string):string; public GUIField : TGUIField; Field : TField; Index,Width : Integer; Checked, Sorted, QuickView : Boolean; procedure LoadFromStr(s:string;fl:boolean); procedure SaveToStr(var s:string); end; implementation function TFieldDescr.GetNextParam(var s:string):string; var i:integer; begin i:=pos('|',s); if i<>0 then begin GetNextParam:=Copy(s,1,i-1); Delete(s,1,i) end else begin GetNextParam:=s; s:=''; end end; function TFieldDescr.BoolToStr(b:boolean):string; begin if b then BoolToStr:='TRUE' else BoolToStr:='FALSE' end; procedure TFieldDescr.LoadFromStr(s:string;fl:boolean); begin if s<>'' then begin Index:=StrToInt(GetNextParam(s)); Width:=StrToInt(GetNextParam(s)); Checked:=GetNextParam(s)='TRUE'; Sorted:=GetNextParam(s)='TRUE'; QuickView:=GetNextParam(s)='TRUE'; end else begin Index:=0; Width:=10; Checked:=not fl; Sorted:=FALSE; QuickView:=FALSE; end; end; procedure TFieldDescr.SaveToStr(var s:string); begin s:=IntToStr(Index)+'|'+IntToStr(Width)+'|'+BoolToStr(Checked)+'|'; s:=s+BoolToStr(Sorted)+'|'+BoolToStr(QuickView); end; end.
{ Subroutine STRING_CMLINE_OPT_BAD * * The last token read from the command line was an unrecognized command line * option. Print appropriate message and bomb program. } module string_CMLINE_OPT_BAD; define string_cmline_opt_bad; %include 'string2.ins.pas'; procedure string_cmline_opt_bad; {indicate last cmd line token was bad} options (noreturn); var msg_parm: {parameter references for message} array[1..1] of sys_parm_msg_t; begin sys_msg_parm_vstr (msg_parm[1], cmline_token_last); sys_message_bomb ('string', 'cmline_opt_bad', msg_parm, 1); end;
UNIT PhanSo1; INTERFACE TYPE T_Dau = -1.. 1; T_PhanSo1 = OBJECT TuSo, MauSo : LongInt; Dau : T_Dau; CONSTRUCTOR KhoiDong; Procedure Doi(r : Real); Procedure ToiGian; Procedure Xuat; End; IMPLEMENTATION CONST Max = 2147483647; R_min = 1E-10; CONSTRUCTOR T_PhanSo1.KhoiDong; Begin End; {--------------------------} Procedure T_PhanSo1.Doi(r : Real); Var PS : T_PhanSo1; Du : Real; Begin If ABS(r) > Max Then RunError(7); If r > 0 Then Dau := 1 Else Dau := -1; r := ABS(r); MauSo := 1; Du := r - Int(r); While Du > R_Min Do Begin r := 10 * r; MauSo := 10 * MauSo; Du := r - Round(r); End; TuSo := Round(r); End; {--------------------------} Procedure T_PhanSo1.ToiGian; Var u : LongInt; Function USCLN(x, y : LongInt) : LongInt; Begin While NOT (x = y) Do If x > y Then x := x - y Else y := y -x; USCLN := x; End; Begin If TuSo = 0 Then Begin MauSo := 1; Dau := 0; Exit; End; u := USCLN(TuSo, MauSo); TuSo := TuSo Div u; MauSo := MauSo Div u; End; {--------------------------} Procedure T_PhanSo1.Xuat; Begin If MauSo = 1 Then Begin If Dau = -1 Then Write('-',TuSo) Else Write(TuSo); Exit End; If Dau = -1 Then Write('-',TuSo, '/', MauSo) Else Write(TuSo,'/',MauSo); End; END.
unit netblock; //////////////////////////////////////////////////////////////////////////////// // // Unit : NETBLOCK // Date : 05.25.2004 // Description : TCPIP network connection blocking unit // //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// // Include units //////////////////////////////////////////////////////////////////////////////// uses Windows, MMSystem; //////////////////////////////////////////////////////////////////////////////// // IPHLPAPI data structures //////////////////////////////////////////////////////////////////////////////// type PMIB_TCPROW = ^MIB_TCPROW; MIB_TCPROW = packed record dwState: DWORD; dwLocalAddr: DWORD; dwLocalPort: DWORD; dwRemoteAddr: DWORD; dwRemotePort: DWORD; end; PMIB_TCPTABLE = ^MIB_TCPTABLE; MIB_TCPTABLE = packed record dwNumEntries: DWORD; Table: Array [0..MaxWord] of MIB_TCPROW; end; type TGetTcpTable = function(pTcpTable: PMIB_TCPTABLE; dwSize: PDWORD; bOrder: BOOL): DWORD; stdcall; TSetTcpEntry = function(pTcpRow: PMIB_TCPROW): DWORD; stdcall; //////////////////////////////////////////////////////////////////////////////// // IPHLPAPI constants //////////////////////////////////////////////////////////////////////////////// const IPHLPAPI_NAME = 'iphlpapi.dll'; GETTCPTABLE_NAME = 'GetTcpTable'; SETTCPENTRY_NAME = 'SetTcpEntry'; const MIB_TCP_STATE_DELETE_TCB= 12; //////////////////////////////////////////////////////////////////////////////// // NetBlock constants //////////////////////////////////////////////////////////////////////////////// const NB_TABLE_SIZE = 1024; const NB_BLOCK_NONE = 0; NB_BLOCK_INTERNET = 1; NB_BLOCK_ALL = 2; //////////////////////////////////////////////////////////////////////////////// // NetBlock data structures //////////////////////////////////////////////////////////////////////////////// type PNetBlockInfo = ^TNetBlockInfo; TNetBlockInfo = packed record dwBlockMode: DWORD; dwResolution: DWORD; dwTimer: DWORD; end; //////////////////////////////////////////////////////////////////////////////// // NetBlock functions //////////////////////////////////////////////////////////////////////////////// function SetNetBlock(lpNetBlockInfo: PNetBlockInfo): DWORD; function StatNetBlock(lpNetBlockInfo: PNetBlockInfo): DWORD; procedure StopNetBlock; var x: DWORD = 0; implementation //////////////////////////////////////////////////////////////////////////////// // Protected variables //////////////////////////////////////////////////////////////////////////////// var hIphlp: HMODULE = 0; dwResolution: DWORD = 0; dwBlockMode: DWORD = 0; dwTimer: DWORD = 0; dwProcError: DWORD = 0; _GetTcpTable: TGetTcpTable = nil; _SetTcpEntry: TSetTcpEntry = nil; procedure NetBlockTimerProc(uTimerID, uMessage: UINT; dwUser, dw1, dw2: DWORD); stdcall; var lpTable: PMIB_TCPTABLE; lpRow: PMIB_TCPROW; bRemove: Boolean; dwReturn: DWORD; dwSize: DWORD; begin Inc(x); // Start with an optimal table size dwSize:=(NB_TABLE_SIZE * SizeOf(MIB_TCPROW)) + SizeOf(DWORD); // Allocate memory for the table GetMem(lpTable, dwSize); // Get the table dwReturn:=_GetTcpTable(lpTable, @dwSize, False); // We may have to reallocate and try again if (dwReturn = ERROR_INSUFFICIENT_BUFFER) then begin // Reallocate memory for new table ReallocMem(lpTable, dwSize); // Make the call again dwReturn:=_GetTcpTable(lpTable, @dwSize, False); end; // Check for succes if (dwReturn = ERROR_SUCCESS) then begin // Iterate the table for dwSize:=0 to Pred(lpTable^.dwNumEntries) do begin // Get the row lpRow:=@lpTable^.Table[dwSize]; // Check for 0.0.0.0 address if (lpRow^.dwLocalAddr = 0) or (lpRow^.dwRemoteAddr = 0) then Continue; // What blocking mode are we in case dwBlockMode of // Need to check the first two bytes in network address NB_BLOCK_INTERNET : bRemove:=not(Word(Pointer(@lpRow^.dwLocalAddr)^) = Word(Pointer(@lpRow^.dwRemoteAddr)^)); // Need to check all four bytes in network address NB_BLOCK_ALL : bRemove:=not(lpRow^.dwLocalAddr = lpRow^.dwRemoteAddr); else // No checking bRemove:=False; end; // Do we need to remove the entry? if bRemove then begin // Set entry state lpRow^.dwState:=MIB_TCP_STATE_DELETE_TCB; // Remove the TCP entry _SetTcpEntry(lpRow); end; end; end; // Free the table FreeMem(lpTable); end; function StatNetBlock(lpNetBlockInfo: PNetBlockInfo): DWORD; begin // Parameter check if not(Assigned(lpNetBlockInfo)) then // Null buffer result:=ERROR_INVALID_PARAMETER else begin // Fill in the current settings lpNetBlockInfo^.dwResolution:=dwResolution; lpNetBlockInfo^.dwBlockMode:=dwBlockMode; lpNetBlockInfo^.dwTimer:=dwTimer; // Success result:=ERROR_SUCCESS; end; end; function SetNetBlock(lpNetBlockInfo: PNetBlockInfo): DWORD; begin // Parameter check if not(Assigned(lpNetBlockInfo)) then begin // Treat the same way as if StopNetBlock had been called StopNetBlock; // Success result:=ERROR_SUCCESS; end else if (@_GetTcpTable = @_SetTcpEntry) then // Failed to load library or get the function pointers result:=dwProcError else if (lpNetBlockInfo^.dwResolution = 0) then // Invalid time specified result:=ERROR_INVALID_PARAMETER else if (lpNetBlockInfo^.dwBlockMode > NB_BLOCK_ALL) then // Invalid blocking mode result:=ERROR_INVALID_PARAMETER else begin // Kill the current timer if the blocking is running if (dwTimer > 0) then timeKillEvent(dwTimer); // Clear timer tracking handle dwTimer:=0; // Save off the current block mode and resolution dwBlockMode:=lpNetBlockInfo^.dwBlockMode; dwResolution:=lpNetBlockInfo^.dwResolution; // If the block mode is NB_BLOCK_NONE then nothing to do if (dwBlockMode = NB_BLOCK_NONE) then // Success result:=ERROR_SUCCESS else begin // Create the timer to handle the network blocking dwTimer:=timeSetEvent(lpNetBlockInfo^.dwResolution, 0, @NetBlockTimerProc, 0, TIME_PERIODIC or TIME_CALLBACK_FUNCTION); // Check timer handle if (dwTimer = 0) then // Failure result:=GetLastError else // Succes result:=ERROR_SUCCESS; end; end; end; procedure StopNetBlock; begin // This will stop the current net blocking if (dwTimer > 0) then begin // Kill the timer timeKillEvent(dwTimer); // Reset all values dwBlockMode:=NB_BLOCK_NONE; dwResolution:=0; dwTimer:=0; end; end; initialization // Load the ip helper api library hIphlp:=LoadLibrary(IPHLPAPI_NAME); // Attempt to get the function addresses if (hIphlp > 0) then begin @_GetTcpTable:=GetProcAddress(hIpHlp, GETTCPTABLE_NAME); if not(Assigned(@_GetTcpTable)) then dwProcError:=GetLastError else begin @_SetTcpEntry:=GetProcAddress(hIpHlp, SETTCPENTRY_NAME); if not(Assigned(@_SetTcpEntry)) then dwProcError:=GetLastError end; end else // Save off the error dwProcError:=GetLastError; finalization // Kill the timer if running if (dwTimer > 0) then timeKillEvent(dwTimer); // Clear functions @_GetTcpTable:=nil; @_SetTcpEntry:=nil; // Free the ip helper api library if (hIphlp > 0) then FreeLibrary(hIphlp); end.
unit model.Pedido; interface uses UConstantes, model.Cliente, model.Loja, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants; type TPedido = class(TObject) private aID : TGUID; aCodigo : Currency; aNumero : String; aTipo : TTipoPedido; aCliente : TCliente; aContato : String; aDataEmissao : TDate; aValorTotal , aValorDesconto, aValorPedido : Currency; aAtivo , aFaturado , aEntregue : Boolean; aObservacao : String; aReferencia : TGUID; aLoja : TLoja; function GetSincronizado : Boolean; public constructor Create; overload; destructor Destroy; overload; property ID : TGUID read aID write aID; property Codigo : Currency read aCodigo write aCodigo; property Numero : String read aNumero write aNumero; property Tipo : TTipoPedido read aTipo write aTipo; property Cliente : TCliente read aCliente write aCliente; property Contato : String read aContato write aContato; property DataEmissao : TDate read aDataEmissao write aDataEmissao; property ValorTotal : Currency read aValorTotal write aValorTotal; property ValorDesconto : Currency read aValorDesconto write aValorDesconto; property ValorPedido : Currency read aValorPedido write aValorPedido; property Ativo : Boolean read aAtivo write aAtivo; property Faturado : Boolean read aFaturado write aFaturado; property Entregue : Boolean read aEntregue write aEntregue; property Sincronizado : Boolean read GetSincronizado; property Observacao : String read aObservacao write aObservacao; property Referencia : TGUID read aReferencia write aReferencia; property Loja : TLoja read aLoja write aLoja; procedure NewID; function ToString : String; override; function GetValorTotalInteiro : Int64; function GetValorDescontoInteiro : Int64; function GetValorPedidoInteiro : Int64; end; TPedidos = Array of TPedido; implementation { TPedido } constructor TPedido.Create; begin inherited Create; aId := GUID_NULL; aCodigo := 0; aNumero := EmptyStr; aTipo := tpOrcamento; aContato := EmptyStr; aDataEmissao := Date; aValorTotal := 0.0; aValorDesconto := 0.0; aValorPedido := 0.0; aAtivo := True; aFaturado := False; aEntregue := False; aObservacao := EmptyStr; aReferencia := GUID_NULL; aCliente := TCliente.Create; aLoja := TLoja.Create; end; destructor TPedido.Destroy; begin aCliente.Free; aLoja.Free; inherited Destroy; end; function TPedido.GetSincronizado : Boolean; begin Result := (aTipo = tpPedido); end; function TPedido.GetValorDescontoInteiro: Int64; begin Result := Trunc(aValorDesconto * 100); end; function TPedido.GetValorPedidoInteiro: Int64; begin Result := Trunc(aValorPedido * 100); end; function TPedido.GetValorTotalInteiro: Int64; begin Result := Trunc(aValorTotal * 100); end; procedure TPedido.NewID; var aGuid : TGUID; begin CreateGUID(aGuid); aId := aGuid; end; function TPedido.ToString: String; begin if (aTipo = TTipoPedido.tpPedido) then begin if (aNumero.Trim = EmptyStr) then Result := 'Pedido #' + FormatFloat('00000', aCodigo) else Result := 'Pedido #' + aNumero.Trim; end else Result := 'Orçamento #' + FormatFloat('00000', aCodigo); end; end.
unit CustomTypes; interface const HEIGHT = 25; LABEL_WIDTH = 170; type TTable = array[1..100, 1..100] of integer; TScoreTable = array[1..100, 1..100, 1..5] of integer; TPlayersList = array[1..100] of integer; TPlayer = record Name : string; Scores: array of integer; FinalScoresSum: integer; Rank : byte; DateOfBorn: TDateTime; end; const INVALID_PLAYER_COUNT = 'Игроков должно быть не меньше двух.'; procedure InitializeTable(arr : TTable;n : integer); implementation procedure InitializeTable(arr : TTable;n : integer); var i, j: integer; begin for i := 1 to n do begin for j := 1 to n do begin arr[i, j] := 0; end; end; end; end.
unit BN02; interface uses Windows, SysUtils, Classes, Graphics, Controls, Dialogs; type TBato = record // caractéristiques d'un bato joueur, vies, sens : byte; cl : integer; lg : integer; end; Tval = record // module d'évaluation déplacement / combat ba : byte; cl : integer; lg : integer; val : integer; end; const kfn = 'BNav.sav'; kvie : array[1..20] of byte = (4,3,3,3,3,2,2,2,2,2,4,3,3,3,3,2,2,2,2,2); var dim : integer = 70; // dimension d'une case rangle : extended; // angle de rotation ix,iy : integer; // longueur d'un pas jr, phase : byte; // phase de jeu joueur ledon,ledof, // LED's du bouton son bato : TBitmap; // image d'un bateau tablo : array[0..11,0..7] of byte; // plateau de jeu batos : array[1..20] of TBato; // stockage des bateaux tbmod : array[1..2,0..4] of TBitmap; // images des bateaux [joueur,vies] tbfon : array[1..5] of TBitmap; // images bateau qui coule tbfeu : array[0..3] of TBitmap; // images de tir ron : array[0..3] of TBitmap; // pions pour l'éditeur nbnav : array[1..2] of byte; // compteur de bateaux tbvie : array[1..20] of byte; // table des vies pour initialisation noba : byte; Fsave : file of TBato; dir : string; debug : boolean = false; fn : string; procedure Trace(n1,n2 : integer); procedure Charge; procedure Decharge; procedure MelangeVies; procedure SauveJeu; procedure RestoreJeu; procedure Rotation(var ABitmap : TBitmap); function RotImage(srcbit: TBitmap; Angle: Extended; FPoint: TPoint; Background: TColor): TBitmap; implementation procedure Trace(n1,n2 : integer); begin showmessage(inttostr(n1)+' - '+inttostr(n2)); end; procedure Charge; // initialisation des images var i,j : byte; begin for j := 1 to 2 do begin for i := 0 to 4 do begin tbmod[j,i] := TBitmap.Create; tbmod[j,i].LoadFromFile('Images\bato'+IntToStr(i)+'.bmp'); tbmod[j,i].Transparent := true; if j = 1 then begin tbmod[j,i].Canvas.Brush.Color := clYellow; tbmod[j,i].Canvas.FloodFill(8,35,clRed,fsSurface); end; end; end; for i := 1 to 5 do begin tbfon[i] := TBitmap.Create; tbfon[i].LoadFromFile('Images\Co0'+IntToStr(i)+'.bmp'); tbfon[i].Transparent := true; tbfon[i].TransparentColor := clWhite; end; for i := 0 to 3 do begin tbfeu[i] := TBitmap.Create; tbfeu[i].LoadFromFile('Images\Feu'+IntToStr(i)+'.bmp'); tbfeu[i].Transparent := true; tbfon[i].TransparentColor := clWhite; end; for i := 0 to 3 do begin ron[i] := TBitmap.Create; case i of 0 : ron[i].LoadFromFile('Images\RB.bmp'); 1 : ron[i].LoadFromFile('Images\RJ.bmp'); 2 : ron[i].LoadFromFile('Images\RR.bmp'); 3 : ron[i].LoadFromFile('Images\RG.bmp'); end; end; ledon := TBitmap.Create; ledon.LoadFromFile('Images\LedOn.bmp'); ledof := TBitmap.Create; ledof.LoadFromFile('Images\LedOff.bmp'); end; procedure Decharge; var i,j : byte; begin for j := 1 to 2 do for i := 0 to 4 do tbmod[j,i].Free; for i := 1 to 5 do tbfon[i].Free; for i := 0 to 3 do tbfeu[i].Free; for i := 0 to 3 do ron[i].Free; ledon.Free; ledof.Free; end; procedure MelangeVies; var i,n,v : byte; begin for i := 1 to 20 do tbvie[i] := kvie[i]; for i := 1 to 10 do begin n := Random(10)+1; v := tbvie[n]; tbvie[n] := tbvie[i]; tbvie[i] := v; end; for i := 11 to 20 do begin n := Random(10)+11; v := tbvie[n]; tbvie[n] := tbvie[i]; tbvie[i] := v; end; end; procedure SauveJeu; var i : byte; begin AssignFile(Fsave,dir+kfn); Rewrite(Fsave); for i := 0 to 20 do Write(Fsave,batos[i]); Closefile(Fsave); end; procedure RestoreJeu; var i : byte; begin AssignFile(Fsave,dir+kfn); Reset(Fsave); for i := 0 to 20 do Read(Fsave,batos[i]); Closefile(Fsave); end; // Vecteur de FromP à ToP function Vecteur(FromP, Top: TPoint): TPoint; begin Result.x := Top.x - FromP.x; Result.y := Top.y - FromP.y; end; // nouveau x du vecteur function XComp(Vecteur: TPoint; Angle: Extended): Integer; begin Result := Round(Vecteur.x * cos(Angle) - (Vecteur.y) * sin(Angle)); end; // nouveau y du vecteur function YComp(Vecteur: TPoint; Angle: Extended): Integer; begin Result := Round((Vecteur.x) * (sin(Angle)) + (Vecteur.y) * cos(Angle)); end; function RotImage(srcbit: TBitmap; Angle: Extended; FPoint: TPoint; Background: TColor): TBitmap; { srcbit: TBitmap; // Bitmap à pivoter Angle: extended; // angle FPoint: TPoint; // Point de rotation Background: TColor): TBitmap; // Couleur de fond } var highest, lowest, mostleft, mostright: TPoint; topoverh, leftoverh: integer; x, y, newx, newy: integer; begin Result := TBitmap.Create; while Angle >= (2 * pi) do begin angle := Angle - (2 * pi); end; if (angle <= (pi / 2)) then begin highest := Point(0,0); //OL Lowest := Point(Srcbit.Width, Srcbit.Height); //UR mostleft := Point(0,Srcbit.Height); //UL mostright := Point(Srcbit.Width, 0); //OR end else if (angle <= pi) then begin highest := Point(0,Srcbit.Height); Lowest := Point(Srcbit.Width, 0); mostleft := Point(Srcbit.Width, Srcbit.Height); mostright := Point(0,0); end else if (Angle <= (pi * 3 / 2)) then begin highest := Point(Srcbit.Width, Srcbit.Height); Lowest := Point(0,0); mostleft := Point(Srcbit.Width, 0); mostright := Point(0,Srcbit.Height); end else begin highest := Point(Srcbit.Width, 0); Lowest := Point(0,Srcbit.Height); mostleft := Point(0,0); mostright := Point(Srcbit.Width, Srcbit.Height); end; topoverh := yComp(Vecteur(FPoint, highest), Angle); leftoverh := xComp(Vecteur(FPoint, mostleft), Angle); Result.Height := Abs(yComp(Vecteur(FPoint, lowest), Angle)) + Abs(topOverh); Result.Width := Abs(xComp(Vecteur(FPoint, mostright), Angle)) + Abs(leftoverh); Topoverh := TopOverh + FPoint.y; Leftoverh := LeftOverh + FPoint.x; Result.Canvas.Brush.Color := Background; Result.Canvas.pen.Color := background; Result.Canvas.Fillrect(Rect(0,0,Result.Width, Result.Height)); for y := 0 to srcbit.Height - 1 do begin for x := 0 to srcbit.Width - 1 do begin newX := xComp(Vecteur(FPoint, Point(x, y)), Angle); newY := yComp(Vecteur(FPoint, Point(x, y)), Angle); newX := FPoint.x + newx - leftoverh; newy := FPoint.y + newy - topoverh; Result.Canvas.Pixels[newx, newy] := srcbit.Canvas.Pixels[x, y]; if ((angle < (pi / 2)) or ((angle > pi) and (angle < (pi * 3 / 2)))) then begin Result.Canvas.Pixels[newx, newy + 1] := srcbit.Canvas.Pixels[x, y]; end else begin Result.Canvas.Pixels[newx + 1,newy] := srcbit.Canvas.Pixels[x, y]; end; end; end; end; // procedure permettant de faire une rotation de 90° procedure Rotation(var ABitmap : TBitmap); type TRGBArray = array[0..10000] of TRGBTriple; pTRGBArray = ^TRGBArray; TArrayLigneCible = array[0..10000] of pTRGBArray; var BitmapSource, BitmapCible : TBitmap; x,y : integer; LigneSource, LigneCible : pTRGBArray; begin BitmapSource := TBitmap.Create; BitmapCible := TBitmap.Create; try BitmapSource.assign (ABitmap); BitmapSource.pixelformat := pf24bit; BitmapCible.pixelformat := pf24bit; BitmapCible.Height := BitmapSource.Width; BitmapCible.Width := BitmapSource.Height; for y:=0 to BitmapSource.Height - 1 do begin LigneSource := BitmapSource.ScanLine[y]; for x:=0 to BitmapSource.Width - 1 do begin LigneCible := BitmapCible.ScanLine[x]; LigneCible[BitmapSource.Height - 1 - y] := LigneSource[x]; end; end; ABitmap.assign(BitmapCible); finally BitmapSource.free; BitmapCible.free; end; end; end.
unit Token; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Diese Unit beinhaltet die Spielsteintask. Diese berechnet die Zugmoeglichkeiten eines Spielsteins, nimmt einen Zug entgegen, sendet diesen an den Displayrechner, empfaengt die Zugbestaetigung und sendet diese an den zustaendigen Spieler. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface procedure TokenTask; implementation uses RTKernel, Types, PTypes, Tools, TokenMsg, LeadMB, Leader, PlayMsg, DispMB, PIPXSnd; procedure ProcessMoveData(MoveData: TMoveData; var FP: TFieldPos; var State: TTokenState); (***************************************************************************** Beschreibung: Verarbeitet Zugdaten. In: MoveData: TMoveData: Zugdaten Out: FP: TFieldPos: Position des Steins State: TTokenState: Zustand des Steins *****************************************************************************) begin with MoveData do begin FP := TargetFP; case Kind of { Stein gesetzt } mkPlace: begin Debug('Wurde gesetzt'); State := tsPlaced; end; { Stein gezogen } mkMove: Debug('Wurde von ' + FieldPosToStr(SourceFP) + ' auf ' + FieldPosToStr(TargetFP) + ' gezogen'); { Stein geschlagen } mkCapture: begin Debug('Wurde geschlagen'); State := tsCaptured; end; { Stein geklaut } mkSteal: begin Debug('Wurde geklaut'); State := tsStolen; end; end; end; end; {$F+} procedure TokenTask; (***************************************************************************** Beschreibung: Spielsteintask. In: - Out: - *****************************************************************************) var PlayerTaskHandle: TaskHandle; Message: TTokenMessage; Field: TField; PlayerMessage: TPlayerMessage; State: TTokenState; MovePossibilities: TMovePossibilities; x: TFieldWidth; y: TFieldHeight; DisplayMessage: TDisplayMessage; PlayerStage: TPlayerStage; FieldPos, TmpFieldPos: TFieldPos; MoveDirections: TDirectionSet; begin Debug('Wurde erzeugt'); { Spielertaskhandle empfangen } Debug('Warte auf Spielertaskhandle'); TokenMsg.Receive(Message); if Message.Kind <> tmkPlayerTaskHandle then Die('Unexpected command in token'); Debug('Spielertaskhandle empfangen'); PlayerTaskHandle := Message.PlayerTaskHandle; while true do begin { Auf Nachrichten warten } Debug('Warte auf Nachrichten'); TokenMsg.Receive(Message); Debug('Nachricht empfangen'); Debug('Analysiere Nachricht'); { Nachricht analysieren } case Message.Kind of { Initialisierungsnachricht } tmkInit: begin Debug('Initialisierungskommando empfangen'); { Position initialisieren } FieldPos.X := Low(TFieldWidth); FieldPos.Y := Low(TFieldHeight); { Zustand initialisieren } State := tsNotPlaced; { Zugrichtungen initialisieren } MoveDirections := []; end; { Anfrage nach Spielsteindaten } tmkGetTokenData: begin Debug('Anfrage nach Spielsteindaten von ' + GetTaskName(Message.SenderTaskHandle) + ' empfangen'); Debug('Initialisiere Zugmoeglichkeiten'); { Zugmoeglichkeiten initialisieren } FillChar(MovePossibilities, SizeOf(MovePossibilities), false); { Zugrichtungen initialisieren } MoveDirections := []; Debug('Zugmoeglichkeiten initialisiert'); { Stein ist noch nicht gesetzt oder gesetzt, also noch im Spiel } if State in [tsNotPlaced, tsPlaced] then begin Debug('Berechne Zugmoeglichkeiten'); { Spielerphase auswerten } case PlayerStage of { Spieler zieht oder springt } psPlace, psFly: begin { Stein kann auf jede freie Position } for x := Low(TFieldWidth) to High(TFieldWidth) - 1 do for y := Low(TFieldHeight) to High(TFieldHeight) - 1 do MovePossibilities[x, y] := Field.Pos[x, y].Valid and (Field.Pos[x, y].Owner = oNone); end; { Spieler zieht } psMove: begin { Alle vier Zugrichtungen ausprobieren. Wenn die Position in der Richtung frei ist, Zugrichtung in die Zugrichtungsmenge aufnehmen } TmpFieldPos := FieldPos; { Links } if GetLeftFieldPos(Field, TmpFieldPos) then begin if Field.Pos[TmpFieldPos.X, TmpFieldPos.Y].Owner = oNone then begin MovePossibilities[TmpFieldPos.X, TmpFieldPos.Y] := true; Include(MoveDirections, dLeft); end; end; TmpFieldPos := FieldPos; { Rechts } if GetRightFieldPos(Field, TmpFieldPos) then begin if Field.Pos[TmpFieldPos.X, TmpFieldPos.Y].Owner = oNone then begin MovePossibilities[TmpFieldPos.X, TmpFieldPos.Y] := true; Include(MoveDirections, dRight); end; end; TmpFieldPos := FieldPos; { Oben } if GetUpperFieldPos(Field, TmpFieldPos) then begin if Field.Pos[TmpFieldPos.X, TmpFieldPos.Y].Owner = oNone then begin MovePossibilities[TmpFieldPos.X, TmpFieldPos.Y] := true; Include(MoveDirections, dUp); end; end; TmpFieldPos := FieldPos; { Unten } if GetLowerFieldPos(Field, TmpFieldPos) then begin if Field.Pos[TmpFieldPos.X, TmpFieldPos.Y].Owner = oNone then begin MovePossibilities[TmpFieldPos.X, TmpFieldPos.Y] := true; Include(MoveDirections, dDown); end; end; end; end; Debug('Zugmoeglichkeiten berechnet'); end; { Spielsteindaten zusammenfassen } with PlayerMessage do begin Kind := plmkTokenData; TokenData.TokenTH := CurrentTaskHandle; TokenData.FieldPos := FieldPos; TokenData.State := State; TokenData.MoveDirections := MoveDirections; TokenData.MovePossibilities := MovePossibilities; end; { Spielsteindaten an den Spieler schicken } Debug('Sende Spielsteindaten an ' + GetTaskName(Message.SenderTaskHandle)); PlayMsg.Send(PlayerTaskHandle, PlayerMessage); Debug('Spielsteindaten an ' + GetTaskName(Message.SenderTaskHandle) + ' gesendet'); end; { Zugnachricht } tmkMove: begin Debug('Zugdaten empfangen'); { Zugdaten an den Anzeigerechner senden } with DisplayMessage do begin Kind := dmkTokenMove; with TokenMoveData do begin TokenTH := CurrentTaskHandle; MoveData := Message.MoveData; end; end; Debug('Sende Zugdaten an Displayrechner'); DispMB.Put(PIPXSnd.Mailbox, DisplayMessage); Debug('Zugdaten an Displayrechner gesendet'); Debug('Warte auf Zugbestaetigung'); end; { Zugbestaetigung vom Anzeigerechner } tmkTokenMoved: begin Debug('Zugbestaetigung empfangen'); Debug('Verarbeite Zugdaten'); { Zug verarbeiten } ProcessMoveData(Message.MoveData, FieldPos, State); Debug('Zugdaten verarbeitet'); { Zugbestaetigung an Spieler senden } with PlayerMessage do begin Kind := plmkTokenMoved; TokenMoveData.TokenTH := CurrentTaskHandle; TokenMoveData.MoveData := Message.MoveData; end; Debug('Sende Zugbestaetigung an Spieler'); { Wenn geschlagen wird, an Gegnerspieler senden } if Message.MoveData.Kind = mkCapture then PlayMsg.Send(Message.MoveData.PlayerTH, PlayerMessage) else PlayMsg.Send(PlayerTaskHandle, PlayerMessage); Debug('Zugbestaetigung an Spieler gesendet'); end; { Spielfeld } tmkField: begin Debug('Spielfeld empfangen'); Field := Message.Field; end; { Spielerphase } tmkPlayerStage: begin Debug('Spielerphase empfangen'); PlayerStage := Message.PlayerStage; end; end; Debug('Nachricht analysiert'); end; Debug('Werde zerstoert'); end; end.
{ Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Livebindings) @created(29 Nov 2020) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Telegram : @IsaquePinheiro) } unit ormbr.controls.helpers; interface uses {$IFDEF HAS_FMX} FMX.Controls, {$ELSE HAS_VCL} VCL.Controls, {$ENDIF} System.Generics.Collections, System.Classes; type /// <summary> /// Lista registradora de cada componente do form, para que o ORMBr /// encontre de forma simples e rápida, para notificar ao LiveBindings /// </summary> TListComponents = TObjectDictionary<String, TComponent>; /// <summary> /// Lista registradora de cada nomes das propriedade do controle para que o /// ORMBr encontre de forma simples e rápida, para notificar ao LiveBindings /// </summary> TListFieldNames = TDictionary<String, String>; /// <summary> /// Classe usada pelo ORMBr para registrar e notificar o livebindings /// </summary> TListControls = class private class var FListComponents: TListComponents; class var FListFieldNames: TListFieldNames; public class constructor Create; class destructor Destroy; class function ListComponents: TListComponents; class function ListFieldNames: TListFieldNames; end; /// <summary> /// Helper do TControl, dando recurso ao ORMBr de capturar o nome da /// propriedade atribuida ao attributo FieldLiveBindings, para cada /// cotrole a ser gerenciado pelo Livebindings. /// </summary> TControlHelper = class helper for TControl private class var FFieldName: String; class procedure SetFieldName(const Value: String); static; public { Public declarations } class property FieldName: String read FFieldName write SetFieldName; end; implementation { TListControls } class constructor TListControls.Create; begin FListComponents := TListComponents.Create; FListFieldNames := TListFieldNames.Create; end; class destructor TListControls.Destroy; begin FListComponents.Clear; FListComponents.Free; FListFieldNames.Free; end; class function TListControls.ListComponents: TListComponents; begin Result := FListComponents; end; class function TListControls.ListFieldNames: TListFieldNames; begin Result := FListFieldNames; end; { TControlHelper } class procedure TControlHelper.SetFieldName(const Value: String); begin FFieldName := Value; end; end.
unit StratClientDataPostersTest; interface uses TestFrameWork, SubdivisionComponent, SubdivisionComponentPoster, Well, BaseObjects; type TStratClientDMTest = class(TTestCase) private FWell: TWell; protected // всё к скважине тестовая 2 8171 procedure SetUp; override; procedure TearDown; override; published procedure TestGetThemes; procedure TestGetEmployees; procedure TestGetStratons; procedure TestGetTectonicBlocks; procedure TestGetSubdivisionComments; procedure TestAddSubdivision; procedure TestDeleteSubdivision; procedure TestAddSubdivisionComponent; procedure TestDeleteSubdivisionComponent; end; implementation uses Facade, SysUtils, SDFacade, DB, DBGate; { TStratClientDMTest } procedure TStratClientDMTest.SetUp; begin inherited; TMainFacade.GetInstance.AllWells.Reload('WELL_UIN = 8171'); FWell := TMainFacade.GetInstance.AllWells.Items[0]; end; procedure TStratClientDMTest.TearDown; begin inherited; end; procedure TStratClientDMTest.TestAddSubdivision; var s: TSubdivision; iCount, iID: integer; dp: TImplementedDataPoster; ds: TDataSet; begin iCount := FWell.Subdivisions.Count; s := FWell.Subdivisions.Add as TSubdivision; s.Theme := (TMainFacade.GetInstance as TMainFacade).AllThemes.Items[0]; s.SingingDate := Date; s.SigningEmployee := (TMainFacade.GetInstance as TMainFacade).AllEmployees.Items[0]; s.Update(); Check(FWell.Subdivisions.Count = iCount + 1, 'Не добавлена новая разбивка'); Check(FWell.Subdivisions.Items[iCount].ID > 0, 'Новая разбивка не сохранена в БД (не присвоен идентификатор)'); iID := FWell.Subdivisions.Items[iCount].ID; dp := TMainFacade.GetInstance.DataPosterByClassType[TSubdivisionDataPoster] as TImplementedDataPoster; dp.GetFromDB('Subdivision_ID = ' + IntToStr(iID), nil); ds := TMainFacade.GetInstance.DBGates.Add(dp) as TDataSet; Check(ds.RecordCount = 1, 'Разбивка не сохранена в БД'); end; procedure TStratClientDMTest.TestAddSubdivisionComponent; var s: TSubdivision; sc: TSubdivisionComponent; iCount, iID: integer; dp: TImplementedDataPoster; ds: TDataSet; begin if FWell.Subdivisions.Count = 0 then begin s := FWell.Subdivisions.Add as TSubdivision; s.Theme := (TMainFacade.GetInstance as TMainFacade).AllThemes.Items[0]; s.SingingDate := Date; s.SigningEmployee := (TMainFacade.GetInstance as TMainFacade).AllEmployees.Items[0]; s.Update(); end else s := FWell.Subdivisions.ITems[0]; iCount := s.SubdivisionComponents.Count; sc := s.SubdivisionComponents.Add as TSubdivisionComponent; sc.Straton := TMainFacade.GetInstance.AllSimpleStratons.Items[0]; sc.Block := (TMainFacade.GetInstance as TMainFacade).AllTectonicBlocks.Items[0]; sc.Comment := (TMainFacade.GetInstance as TMainFacade).AllSubdivisionComments.Items[0]; sc.Depth := 100; sc.Verified := 1; sc.Update(); Check(s.SubdivisionComponents.Count = iCount + 1, 'Не добавлен новый элемент разбивки'); Check(s.SubdivisionComponents.Items[iCount].ID > 0, 'Новый элемент разбивки не сохранен в БД (не присвоен идентификатор)'); iID := s.SubdivisionComponents.Items[iCount].ID; dp := TMainFacade.GetInstance.DataPosterByClassType[TSubdivisionComponentDataPoster] as TImplementedDataPoster; dp.GetFromDB('Subdivision_ID = ' + IntToStr(s.ID) + ' and ' + 'Straton_ID = ' + IntToStr(sc.Straton.ID), nil); ds := TMainFacade.GetInstance.DBGates.Add(dp) as TDataSet; Check(ds.RecordCount = 1, 'Элемент разбивки не сохранен в БД'); end; procedure TStratClientDMTest.TestDeleteSubdivision; var iCount: integer; iId: integer; dp: TImplementedDataPoster; ds: TDataSet; begin iCount := FWell.Subdivisions.Count; if iCount > 0 then begin iID := FWell.Subdivisions.Items[0].ID; FWell.Subdivisions.MarkDeleted(0); FWell.Subdivisions.Update(nil); Check(FWell.Subdivisions.Count = iCount - 1, 'Разбивка не удалена'); dp := TMainFacade.GetInstance.DataPosterByClassType[TSubdivisionDataPoster] as TImplementedDataPoster; dp.GetFromDB('Subdivision_ID = ' + IntToStr(iID), nil); ds := TMainFacade.GetInstance.DBGates.Add(dp) as TDataSet; Check(ds.RecordCount = 0, 'Разбивка не удалена из БД'); end; end; procedure TStratClientDMTest.TestDeleteSubdivisionComponent; var iCount: integer; iId, iStratonID: integer; dp: TImplementedDataPoster; ds: TDataSet; s: TSubdivision; begin if FWell.Subdivisions.Count = 0 then begin s := FWell.Subdivisions.Add as TSubdivision; s.Theme := (TMainFacade.GetInstance as TMainFacade).AllThemes.Items[0]; s.SingingDate := Date; s.SigningEmployee := (TMainFacade.GetInstance as TMainFacade).AllEmployees.Items[0]; s.Update(); end else s := FWell.Subdivisions.ITems[0]; iCount := s.SubdivisionComponents.Count; if iCount > 0 then begin iID := s.ID; iStratonID := s.SubdivisionComponents.Items[0].Straton.ID; s.SubdivisionComponents.MarkDeleted(0); s.SubdivisionComponents.Update(nil); Check(s.SubdivisionComponents.Count = iCount - 1, 'Элемент разбивки не удален'); dp := TMainFacade.GetInstance.DataPosterByClassType[TSubdivisionComponentDataPoster] as TImplementedDataPoster; dp.GetFromDB('Subdivision_ID = ' + IntToStr(iID) + ' and ' + 'Straton_ID ' + ' = ' + IntToStr(iStratonID), nil); ds := TMainFacade.GetInstance.DBGates.Add(dp) as TDataSet; Check(ds.RecordCount = 0, 'Разбивка не удалена из БД'); end; end; procedure TStratClientDMTest.TestGetEmployees; begin Check((TMainFacade.GetInstance as TMainFacade).AllEmployees.Count > 0, 'Не загружен список сотрудников'); end; procedure TStratClientDMTest.TestGetStratons; begin Check((TMainFacade.GetInstance as TMainFacade).AllSimpleStratons.Count > 0, 'Не загружен список тем НИР'); end; procedure TStratClientDMTest.TestGetSubdivisionComments; begin Check((TMainFacade.GetInstance as TMainFacade).AllSubdivisionComments.Count > 0, 'На загружен список комментариев к разбивкам'); end; procedure TStratClientDMTest.TestGetTectonicBlocks; begin Check((TMainFacade.GetInstance as TMainFacade).AllTectonicBlocks.Count > 0, 'На загружен список тектонических блоков'); end; procedure TStratClientDMTest.TestGetThemes; begin Check((TMainFacade.GetInstance as TMainFacade).AllThemes.Count > 0, 'Не загружен список тем НИР'); end; initialization RegisterTest('StratClientTests\StratClientDMTest', TStratClientDMTest.Suite); end.
unit MyLib; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface uses Objects, SysUtils; function JustUpperCase( S: String ) : String; function JustSameText( S1, S2: String ) : Boolean; function JustCompareText( S1, S2: String ) : Integer; function HomeDir: String; function AtPath( const FileName, Path: String ) : String; function AtHome( const FileName: String ) : String; function RelativePath( var S: String ) : Boolean; function HasWildChars(const S: String ) : Boolean; function DefaultExtension( const FileName, Ext: String ) : String; function AddBackSlash(const DirName : string) : string; function RemoveBackSlash( Path: String ) : String; function ExtractFileNameOnly( const FileName: String ) : String; function QuotedFile( const S: String ) : String; function TrimmedName(const Name: String; Limit: Byte): String; function GetCounterStr(ResID, Counter: Integer) : String; type UnixTime = Longint; FileTime = Longint; { ref: GetFTime/SetFTime } function CurrentUnixTime : UnixTime; function CurrentFileTime : FileTime; function FileTimeToUnix( ft: FileTime ) : UnixTime; function UnixTimeToFile( ut: UnixTime ) : FileTime; function UnixTimeToDateStr( ut: UnixTime ) : String; // Всегда возвpащает в фоpмате dd-Mmm-yy function GetFileDateStr( ft: FileTime ) : String; // dd-Mmm-yy hh:mm:ss function LogTimeStamp( ft: FileTime ) : String; function DaysBetween( u1, u2: UnixTime ) : Integer; procedure Sleep( MSec: Word ); type CharSet = set of Char; { Следующие 3 пpоцедуpы - это вpаппеp к интеpфейсу NewStr/DisposeStr } { из TurboVision (Objects.pas), и используется, чтобы отвязаться от } { одноимённый дельфийских пpоцедуp из SysUtils.Pas. Дополнительная } { функциональность: можно спокойно pаботать с пустыми стpоками. } function AllocStr( const S: String ) : PString; procedure FreeStr( var P: PString ); procedure ReplaceStr( var P: PString; const S: String ); function SafeStr( const P: PString ) : String; function WildMatch( Source, Pattern : String) : Boolean; function HasWild( S: String ) : Boolean; function WordCount(const S : string; WordDelims : CharSet) : Integer; function WordPosition(N : Integer; const S : string; WordDelims : CharSet) : Integer; function ExtractWord(N : Integer; const S : string; WordDelims : CharSet) : String; procedure WordWrap(InSt : string; var OutSt, Overlap : string; Margin : Integer; PadToMargin : Boolean); function Replace(const S, What, Value : String ) : String; procedure SplitPair( const S: String; var Key, Value: String ); procedure StripComment( var S: String ); function ExtractQuoted( S: String ) : String; procedure SkipWhiteSpace( S: String; var pos: Integer ); function GetLiterals( S: String; Start: Integer; var Stop: Integer ) : String; function GetRightID( S: String; Start: Integer; var Stop: Integer ) : String; function MakePrintable( const S: String ) : String; function HexToInt( const S: String ) : Longint; function StrToBool( const S: String ) : Boolean; function BoolToStr( B: Boolean ) : String; function IntToSignedStr( N: Integer ) : String; function TwoDigits( N: Integer ) : String; function ASRF( FSize: Double ) : String; function CreateDirTree( DirName: String ) : Boolean; function ExistingDir ( const S: String; AutoCreate: Boolean ) : String; function ExistingPath( const S: String ) : String; // Если путь не указан, дополняется из ParamStr(0) function ExistingFile( const S: String ) : String; function ScanR( var P; Offset, Size: Integer; C: Char ): Integer; function SkipR( var P; Offset, Size: Integer; C: Char ): Integer; function CharStr( C: Char; Len: Integer ) : String; function Pad( const S: String; Len: Integer ) : String; function PadCh( const S: String; Len: Integer; Ch: Char ) : String; function LeftPad( const S: String; Len: Integer ) : String; function LeftPadCh( const S: String; Len: Integer; Ch: Char ) : String; function CenterCh( const S : string; Width : Integer; Ch: Char ) : String; function Center( const S: String; Width: Integer ) : String; function StrSet( Ch: PChar; const S: String; Size: Integer ) : PChar; procedure Destroy( O: PObject ); procedure SetBit( var Where: Longint; Mask: Longint; Raised: Boolean ); function TestBit( Where, Mask: Longint ) : Boolean; const BLANK = [' ']; IDCHARS = ['A'..'z', '0'..'9', '_']; HIDDEN_PREFIX = ';#'; MonthName: array [1..12] of String[3] = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ); DayName: array [1..7] of String[3] = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ); type PStrings = ^TStrings; TStrings = object (TCollection) procedure FreeItem( Item: Pointer ); virtual; end; { TStrings } PNoCaseStrCollection = ^TNoCaseStrCollection; TNoCaseStrCollection = object (TStringCollection) procedure FreeItem( Item: Pointer ); virtual; function Compare( Key1, Key2: Pointer ) : Integer; virtual; end; { TNoCaseStrCollection } // Virtual File System API :) procedure DecodeLFN( var R: TSearchRec; var ShortName, LongName: String ); function VFS_MoveFile( const Source, Target: String ) : Integer; function VFS_CopyFile( const Source, Target: String ) : Boolean; function VFS_TouchFile( const FileName: String; Stamp: FileTime ) : Boolean; function VFS_EraseFile( const FileName: String ) : Boolean; function VFS_RenameFile( const Source, Dest: String ) : Boolean; function VFS_ValidatePath( const Source: String ) : String; {$IFDEF Win32} // Возвращает только короткое имя _файла_, без пути! function VFS_GetShortName( Source: String; var Target: String ) : Boolean; {$ENDIF} procedure VFS_BackupFile( const FileName: String; Level: Integer ); { =================================================================== } implementation uses {$IFDEF WIN32} Windows, {$ENDIF} Dos, VpSysLow, VpUtils, MsgBox, Views, _RES, _Cfg; const DosDelimSet = ['\', '/', ':', #0]; type TXlateArray = array [Char] of Char; const Upper_Xlate: TXlateArray = ( #0, #1, #2, #3, #4, #5, #6, #7, #8, #9, #10, #11, #12, #13, #14, #15, #16, #17, #18, #19, #20, #21, #22, #23, #24, #25, #26, #27, #28, #29, #30, #31, #32, #33, #34, #35, #36, #37, #38, #39, #40, #41, #42, #43, #44, #45, #46, #47, #48, #49, #50, #51, #52, #53, #54, #55, #56, #57, #58, #59, #60, #61, #62, #63, #64, #65, #66, #67, #68, #69, #70, #71, #72, #73, #74, #75, #76, #77, #78, #79, #80, #81, #82, #83, #84, #85, #86, #87, #88, #89, #90, #91, #92, #93, #94, #95, #96, #65, #66, #67, #68, #69, #70, #71, #72, #73, #74, #75, #76, #77, #78, #79, #80, #81, #82, #83, #84, #85, #86, #87, #88, #89, #90, #123, #124, #125, #126, #127, #128, #129, #130, #131, #132, #133, #134, #135, #136, #137, #138, #139, #140, #141, #142, #143, #144, #145, #146, #147, #148, #149, #150, #151, #152, #153, #154, #155, #156, #157, #158, #159, #128, #129, #130, #131, #132, #133, #134, #135, #136, #169, #138, #139, #140, #141, #142, #143, #176, #177, #178, #179, #180, #181, #182, #183, #184, #185, #186, #187, #188, #189, #190, #191, #192, #193, #194, #195, #196, #197, #198, #199, #200, #201, #202, #203, #204, #205, #206, #207, #208, #209, #210, #211, #212, #213, #214, #215, #216, #217, #218, #219, #220, #221, #222, #223, #144, #145, #146, #147, #148, #149, #150, #151, #152, #153, #154, #155, #156, #157, #158, #159, #240, #240, #242, #243, #244, #245, #246, #247, #248, #249, #250, #251, #252, #253, #254, #255 ); { --------------------------------------------------------- } { JustUpperCase } { --------------------------------------------------------- } function JustUpperCase( S: String ) : String; var j: Integer; begin for j := 1 to Length(S) do S[j] := Upper_Xlate[S[j]]; Result := S; end; { JustUpperCase } { --------------------------------------------------------- } { JustSameText } { --------------------------------------------------------- } function JustSameText( S1, S2: String ) : Boolean; var j: Integer; begin Result := False; if Length(S1) <> Length(S2) then Exit; for j := 1 to Length(S1) do if Upper_Xlate[S1[j]] <> Upper_Xlate[S2[j]] then Exit; Result := True; end; { JustSameText } { --------------------------------------------------------- } { JustCompareText } { --------------------------------------------------------- } function JustCompareText( S1, S2: String ) : Integer; begin S1 := JustUpperCase( S1 ); S2 := JustUpperCase( S2 ); Result := CompareStr( S1, S2 ); end; { JustCompareText } { --------------------------------------------------------- } { Sleep } { --------------------------------------------------------- } procedure Sleep( MSec: Word ); begin SysCtrlSleep( MSec ); end; { Sleep } { --------------------------------------------------------- } { AddBackSlash } { --------------------------------------------------------- } function AddBackSlash(const DirName : string) : string; begin if DirName[Length(DirName)] in DosDelimSet then Result := DirName else Result := DirName + SysPathSep; end; { AddBackSlash } { --------------------------------------------------------- } { RemoveBackSlash } { --------------------------------------------------------- } function RemoveBackSlash( Path: String ) : String; var PLen: Byte absolute Path; begin RemoveBackSlash := ''; if PLen = 0 then Exit; if Path[ PLen ] = SysPathSep then Dec( PLen ); RemoveBackSlash := Path; end; { RemoveBackSlash } { --------------------------------------------------------- } { HomeDir } { --------------------------------------------------------- } function HomeDir: String; {$IFDEF Win32} var FNameZ: array [0..260] of Char; begin StrPCopy( FNameZ, ParamStr(0) ); CharToOem( FNameZ, FNameZ ); Result := StrPas( FNameZ ); {$ELSE} begin Result := ParamStr(0); {$ENDIF} end; { HomeDir } { --------------------------------------------------------- } { AtPath } { --------------------------------------------------------- } function AtPath( const FileName, Path: String ) : String; begin Result := AddBackSlash(Path) + ExtractFileName(FileName); end; { AtPath } { --------------------------------------------------------- } { AtHome } { --------------------------------------------------------- } function AtHome( const FileName: String ) : String; begin Result := AtPath( FileName, ExtractFilePath(HomeDir) ); end; { AtHome } { --------------------------------------------------------- } { RelativePath } { --------------------------------------------------------- } function RelativePath(var S: String): Boolean; begin S := Trim(S); RelativePath := not ((S <> '') and ((S[1] = '\') or (S[2] = ':'))); end; { RelativePath } { --------------------------------------------------------- } { HasWildChars } { --------------------------------------------------------- } function HasWildChars(const S: String) : Boolean; begin Result := (Pos('*', S) <> 0) or (Pos('?', S) <> 0); end; { HasWildChars } { --------------------------------------------------------- } { DefaultExtension } { --------------------------------------------------------- } function DefaultExtension( const FileName, Ext: String ) : String; begin if ExtractFileExt( FileName ) = '' then Result := FileName + Ext else Result := FileName; end; { DefaultExtension } { --------------------------------------------------------- } { ExtractFileNameOnly } { --------------------------------------------------------- } function ExtractFileNameOnly( const FileName: String ) : String; var n: Integer; begin Result := ExtractFileName( FileName ); n := Length( Result ); while n > 0 do begin if Result[n] = '.' then begin SetLength( Result, Pred(n) ); Exit; end; Dec(n); end; end; { ExtractFileNameOnly } { --------------------------------------------------------- } { TrimmedName } { --------------------------------------------------------- } function TrimmedName(const Name: String; Limit: Byte): String; var B, E, L: Integer; S: String; begin L := Length(Name); if L <= Limit then TrimmedName := Name else begin B := 1; while (B < L) and (Name[B] <> '\') do Inc(B); while (B < L) and (Name[B] = '\') do Inc(B); E := B; while (E < L) and (L - (E - B) + 3 > Limit) do Inc(E); while (E < L) and (Name[E] <> '\') do Inc(E); if Name[E] = '\' then begin S := Name; Delete(S, B, E - B); Insert('...', S, B); end else S := ExtractFileName(Name); if Length(S) > Limit then S[0] := Char(Limit); TrimmedName := S; end; end; { --------------------------------------------------------- } { GetCounterStr } { --------------------------------------------------------- } function GetCounterStr(ResID, Counter: Integer) : String; var D: Integer; begin D := Counter - (Counter div 10) * 10; case D of 1: Result := LoadString( ResID ); 2, 3, 4: Result := LoadString( ResID + 1 ); else Result := LoadString( ResID + 2 ); end; end; { GetCounterStr } { --------------------------------------------------------- } { Unix-Time routines } { --------------------------------------------------------- } const C1970 = 2440588; D0 = 1461; D1 = 146097; D2 = 1721119; Procedure GregorianToJulianDN( Year, Month, Day : integer; var JulianDN : longint ); var Century, XYear : longint; begin If Month <= 2 then begin Year := Pred(Year); Month := Month + 12; end; Month := Month - 3; Century := Year div 100; XYear := Year mod 100; Century := (Century * D1) shr 2; XYear := (XYear * D0) shr 2; JulianDN := ((((Month * 153) + 2) div 5) + Day) + D2 + XYear + Century; end; Procedure JulianDNToGregorian( JulianDN : longint; var Year, Month, Day : integer ); var Temp, XYear : longint; YYear, YMonth, YDay : integer; begin Temp := (((JulianDN - D2) shl 2) - 1); XYear := (Temp mod D1) or 3; JulianDN := Temp div D1; YYear := (XYear div D0); Temp := ((((XYear mod D0) + 4) shr 2) * 5) - 3; YMonth := Temp div 153; If YMonth >= 10 then begin YYear := YYear + 1; YMonth := YMonth - 12; end; YMonth := YMonth + 3; YDay := Temp mod 153; YDay := (YDay + 5) div 5; Year := YYear + (JulianDN * 100); Month := YMonth; Day := YDay; end; Function FileTimeToUnix( ft: FileTime ) : UnixTime; var DT : DateTime; DateNum, SecsPast, dth, DaysPast : longint; begin UnpackTime(ft,DT); GregorianToJulianDN(DT.Year,DT.Month,DT.Day,DateNum); DaysPast := DateNum - c1970; SecsPast := DaysPast * 86400; {.Fucking Hydra.} DTH:=Dt.hour; SecsPast := SecsPast + DTH * 3600 + DT.Min * 60 + DT.Sec; Result := SecsPast; end; Function UnixTimeToFile( ut: UnixTime ) : FileTime; var DT : DateTime; DateNum : longint; n : word; begin DateNum := (ut div 86400) + c1970; JulianDNToGregorian(DateNum,integer(DT.Year),integer(DT.Month),integer(DT.Day)); ut := ut mod 86400; DT.Hour := ut div 3600; ut := ut mod 3600; DT.Min := ut div 60; DT.Sec := ut mod 60; PackTime(DT,ut); Result := ut; end; { --------------------------------------------------------- } { CurrentUnixTime } { --------------------------------------------------------- } function CurrentUnixTime : UnixTime; begin Result := FileTimeToUnix( CurrentFileTime ); end; { CurrentUnixTime } { --------------------------------------------------------- } { CurrentFileTime } { --------------------------------------------------------- } function CurrentFileTime: FileTime; var Touch: Longint; Today: DateTime; Dummy: Word; begin with Today do GetDate( Year, Month, Day, Dummy ); with Today do GetTime( Hour, Min, Sec, Dummy ); PackTime( Today, Touch ); Result := Touch; end; { CurrentFileTime } { --------------------------------------------------------- } { UnixTimeToDateStr } { --------------------------------------------------------- } function UnixTimeToDateStr( ut: UnixTime ) : String; begin Result := DateToStr( FileDateToDateTime( UnixTimeToFile(ut) ) ); end; { UnixTimeToDateStr } { --------------------------------------------------------- } { GetFileDateStr } { --------------------------------------------------------- } function GetFileDateStr( ft: FileTime ) : String; var D: DateTime; begin UnpackTime( ft, D ); if D.Year >= 2000 then Dec( D.Year, 2000 ) else Dec( D.Year, 1900 ); Result := Format( '%2d-%3s-%2d', [D.Day, MonthName[D.Month], D.Year] ); if Result[1] = ' ' then Result[1] := '0'; if Result[8] = ' ' then Result[8] := '0'; end; { GetFileDateStr } { --------------------------------------------------------- } { LogTimeStamp } { --------------------------------------------------------- } function LogTimeStamp( ft: FileTime ) : String; var Hour, Min, Sec, MSec: SmallWord; begin DecodeTime( FileDateToDateTime(ft), Hour, Min, Sec, MSec ); Result := GetFileDateStr( ft ) + ' ' + TwoDigits( Hour ) + ':' + TwoDigits( Min ) + ':' + TwoDigits( Sec ); end; { LogTimeStamp } { --------------------------------------------------------- } { ClearTimePart } { --------------------------------------------------------- } function ClearTimePart( ut: UnixTime ) : UnixTime; var D: DateTime; f: FileTime; begin UnpackTime( UnixTimeToFile(ut), D ); D.Hour := 0; D.Min := 0; D.Sec := 0; PackTime( D, f ); Result := FileTimeToUnix( f ); end; { ClearTimePart } { --------------------------------------------------------- } { DaysBetween } { --------------------------------------------------------- } function DaysBetween( u1, u2: UnixTime ) : Integer; const SecPerDay = 3600 * 24; begin Result := (ClearTimePart(u1) - ClearTimePart(u2)) div SecPerDay; end; { DaysBetween } { --------------------------------------------------------- } { WildMatch } { --------------------------------------------------------- } function WildMatch( Source, Pattern : String ) : Boolean; function RMatch(var s : String; i : Integer; var p : String; j : Integer) : Boolean; { s = to be tested , i = position in s } { p = pattern to match , j = position in p } var Matched : Boolean; k : Integer; begin if Length(p) = 0 then begin RMatch := True; Exit; end; while True do begin if (i > Length(s)) and (j > Length(p)) then begin RMatch := True; Exit; end else if j > Length(p) then begin RMatch := False; Exit; end else if p[j] = '*' then begin k := i; if j = Length(p) then begin RMatch := True; Exit; end else begin repeat Matched := RMatch(s, k, p, j + 1); Inc(k); until Matched or (k > Length(s)); RMatch := Matched; Exit; end; end else if (p[j] <> '?') and (p[j] <> s[i]) then begin RMatch := False; Exit; end else begin Inc(i); Inc(j); end; end; end { Rmatch }; begin if HasWild( Pattern ) then begin Source := JustUpperCase( Source ); Pattern := JustUpperCase( Pattern ); Result := RMatch( Source, 1, Pattern, 1 ); end else Result := JustSameText( Source, Pattern ); end { WildMatch }; { --------------------------------------------------------- } { HasWild } { --------------------------------------------------------- } function HasWild( S: String ) : Boolean; begin S[Succ(Length(S))] := #0; Result := (StrScan( @S[1], '*' ) <> nil) or (StrScan( @S[1], '?' ) <> nil); end; { HasWild } { --------------------------------------------------------- } { WordCount } { --------------------------------------------------------- } function WordCount(const S : string; WordDelims : CharSet) : Integer; var I : Integer; SLen : Byte absolute S; begin Result := 0; I := 1; while I <= SLen do begin {skip over delimiters} while (I <= SLen) and (S[I] in WordDelims) do Inc(I); {if we're not beyond end of S, we're at the start of a word} if I <= SLen then Inc(Result); {find the end of the current word} while (I <= SLen) and not(S[I] in WordDelims) do Inc(I); end; end; { WordCount } { --------------------------------------------------------- } { WordPosition } { --------------------------------------------------------- } function WordPosition(N : Integer; const S : string; WordDelims : CharSet) : Integer; var Count : Integer; I : Integer; SLen : Byte absolute S; begin Count := 0; I := 1; Result := 0; while (I <= SLen) and (Count <> N) do begin {skip over delimiters} while (I <= SLen) and (S[I] in WordDelims) do Inc(I); {if we're not beyond end of S, we're at the start of a word} if I <= SLen then Inc(Count); {if not finished, find the end of the current word} if Count <> N then while (I <= SLen) and not(S[I] in WordDelims) do Inc(I) else Result := I; end; end; { WordPosition } { --------------------------------------------------------- } { ExtractWord } { --------------------------------------------------------- } function ExtractWord(N : Integer; const S : string; WordDelims : CharSet) : String; var I, Len : Integer; SLen : Byte absolute S; begin Len := 0; I := WordPosition(N, S, WordDelims); if I <> 0 then {find the end of the current word} while (I <= SLen) and not(S[I] in WordDelims) do begin {add the I'th character to result} Inc(Len); Result[Len] := S[I]; Inc(I); end; Result[0] := Char(Len); end; { ExtractWord } { --------------------------------------------------------- } { WordWrap } { --------------------------------------------------------- } procedure WordWrap(InSt : string; var OutSt, Overlap : string; Margin : Integer; PadToMargin : Boolean); {-Wrap InSt at Margin, storing the result in OutSt and the remainder in Overlap} var InStLen : Byte absolute InSt; OutStLen : Byte absolute OutSt; OvrLen : Byte absolute Overlap; EOS, BOS : Word; begin {find the end of the output string} if InStLen > Margin then begin {find the end of the word at the margin, if any} EOS := Margin; while (EOS <= InStLen) and (InSt[EOS] <> ' ') do Inc(EOS); if EOS > InStLen then EOS := InStLen; {trim trailing blanks} while (InSt[EOS] = ' ') and (EOS > 0) do Dec(EOS); if EOS > Margin then begin {look for the space before the current word} while (EOS > 0) and (InSt[EOS] <> ' ') do Dec(EOS); {if EOS = 0 then we can't wrap it} if EOS = 0 then EOS := Margin else {trim trailing blanks} while (InSt[EOS] = ' ') and (EOS > 0) do Dec(EOS); end; end else EOS := InStLen; {copy the unwrapped portion of the line} OutStLen := EOS; Move(InSt[1], OutSt[1], OutStLen); {!!.01} {find the start of the next word in the line} BOS := EOS+1; while (BOS <= InStLen) and (InSt[BOS] = ' ') do Inc(BOS); if BOS > InStLen then OvrLen := 0 else begin {copy from the start of the next word to the end of the line} OvrLen := Succ(InStLen-BOS); Move(InSt[BOS], Overlap[1], OvrLen); {!!.01} end; {pad the end of the output string if requested} if PadToMargin and (OutStLen < Margin) then begin FillChar(OutSt[OutStLen+1], Margin-OutStLen, ' '); OutStLen := Margin; end; end; { WordWrap } { --------------------------------------------------------- } { SplitPair } { --------------------------------------------------------- } procedure SplitPair( const S: String; var Key, Value: String ); const BLANK = [' ']; var j: Integer; begin Key := JustUpperCase( ExtractWord( 1, S, BLANK ) ); if WordCount( S, BLANK ) > 1 then Value := TrimRight( Copy( S, WordPosition( 2, S, BLANK ), Length(S) )) else Value := ''; end; { SplitPair } { --------------------------------------------------------- } { StripComment } { --------------------------------------------------------- } procedure StripComment( var S: String ); var j: Integer; begin if Pos( HIDDEN_PREFIX, S ) = 1 then Delete( S, 1, Length(HIDDEN_PREFIX) ); j := Pos( ';', S ); if j > 0 then S[0] := Chr(j-1); S := Trim( S ); end; { StripComment } { --------------------------------------------------------- } { HexToInt } { --------------------------------------------------------- } function HexToInt( const S: String ) : Longint; var j: Longint; begin Result := 0; for j := 8 downto 1 do begin if S[j] > #57 then Result := Result or (Ord(S[j]) - 55) shl ((8 - j) shl 2) else Result := Result or (Ord(S[j]) - 48) shl ((8 - j) shl 2) end; end; { HexToInt } { --------------------------------------------------------- } { StrToBool } { --------------------------------------------------------- } function StrToBool( const S: String ) : Boolean; const NumVal = 5; type TValues = array [1..NumVal] of String; const TrueValues : TValues = ( 'Yes', 'Y', 'True', 'T', '1' ); FalseValues : TValues = ( 'No', 'N', 'False', 'F', '0' ); var j: Integer; begin for j := 1 to NumVal do begin if JustSameText( S, TrueValues[j] ) then begin Result := True; Exit; end; if JustSameText( S, FalseValues[j] ) then begin Result := False; Exit; end; end; raise EConvertError.Create( Format(LoadString(_SInvalidBool), [S] )); end; { StrToBool } { --------------------------------------------------------- } { IntToSignedStr } { --------------------------------------------------------- } function IntToSignedStr( N: Integer ) : String; begin if N > 0 then Result := '+' else if N < 0 then Result := '-' else Result := ''; Result := Result + IntToStr(N); end; { IntToSignedStr } { --------------------------------------------------------- } { TwoDigits } { --------------------------------------------------------- } function TwoDigits( N: Integer ) : String; begin if N > 99 then raise EIntError.Create( 'TwoDigits: argument > 99' ); if N <= 9 then Result := '0' + IntToStr( N ) else Result := IntToStr( N ); end; { TwoDigits } { --------------------------------------------------------- } { CreateDirTree } { --------------------------------------------------------- } function CreateDirTree( DirName: String ) : Boolean; var S : String; wc: Integer; j : Integer; BS: CharSet; begin BS := [ SysPathSep ]; DirName := FExpand( DirName ); wc := WordCount( DirName, BS ); S := ExtractWord( 1, DirName, BS ); Result := False; for j := 2 to wc do begin S := S + SysPathSep + ExtractWord( j, DirName, BS ); if not DirExists( S ) then begin try MkDir( S ); except Exit; end; end; end; Result := True; end; { MakeDir } { --------------------------------------------------------- } { ExistingDir } { --------------------------------------------------------- } function ExistingDir( const S: String; AutoCreate: Boolean ) : String; begin Result := S; if (S = '') or DirExists( S ) then Exit else if AutoCreate and (MessageBox( Format(LoadString(_SAskCreateDir), [S]), nil, mfWarning + mfYesNoCancel ) = cmYes) then begin if not CreateDirTree(S) then raise Exception.Create( Format(LoadString(_SMkDirFailed), [S])); end else raise Exception.Create( Format(LoadString(_SDirNotExists), [S])); end; { ExistingDir } { --------------------------------------------------------- } { ExistingPath } { --------------------------------------------------------- } function ExistingPath( const S: String ) : String; var P: String; begin P := ExtractFilePath(ExpandFileName(S)); if (S = '') or DirExists(P) then Result := S else raise Exception.Create( Format(LoadString(_SDirNotExists), [S]) ); end; { ExistingPath } { --------------------------------------------------------- } { ExistingFile } { --------------------------------------------------------- } function ExistingFile( const S: String ) : String; begin if S = '' then Result := S else begin if ExtractFileDir( S ) = '' then Result := AtPath( S, ExtractFileDir( HomeDir ) ) else Result := S; if not FileExists( Result ) then raise Exception.Create( Format(LoadString(_SFileMustExists), [S] )); end; end; { ExistingFile } { --------------------------------------------------------- } { BoolToStr } { --------------------------------------------------------- } function BoolToStr( B: Boolean ) : String; begin if B then Result := 'Yes' else Result := 'No'; end; { BoolToStr } { --------------------------------------------------------- } { AllocStr } { --------------------------------------------------------- } const EmptyStr : String[1] = ''; NullStr : PString = @EmptyStr; function AllocStr( const S: String ) : PString; begin if S <> '' then begin GetMem(Result, Length(S) + 1); Move(S, Result^, Length(S) + 1); end else Result := NullStr; end; { AllocStr } { --------------------------------------------------------- } { FreeStr } { --------------------------------------------------------- } procedure FreeStr( var P: PString ); begin if (P <> nil) and (P <> NullStr) then FreeMem(P, Length(P^) + 1); P := nil; end; { FreeStr } { --------------------------------------------------------- } { ReplaceStr } { --------------------------------------------------------- } procedure ReplaceStr( var P: PString; const S: String ); begin FreeStr( P ); P := AllocStr( S ); end; { ReplaceStr } { --------------------------------------------------------- } { SafeStr } { --------------------------------------------------------- } function SafeStr( const P: PString ) : String; begin if (P <> nil) and (P <> NullStr) then Result := P^ else Result := '<none>'; end; { SafeStr } { --------------------------------------------------------- } { ScanR } { --------------------------------------------------------- } { function ScanR( var P; Offset, Size: Integer; C: Char ) : Integer; var B: TByteArray absolute P; begin while (Offset < Size) and (B[Offset] <> Byte(C)) do Inc(Offset); Result := Offset; end; { ScanR } } function ScanR(var P; Offset, Size: Integer; C: Char): Integer; assembler; {&USES esi,edi} {&FRAME-} asm cld mov edi,P mov edx, edi add edi,&Offset mov ecx,Size sub ecx,&Offset mov al,C repne scasb je @@found mov eax, Size jmp @@exit @@found: sub edi, edx mov eax, edi dec eax @@exit: end; { --------------------------------------------------------- } { SkipR } { --------------------------------------------------------- } { function SkipR( var P; Offset, Size: Integer; C: Char ) : Integer; var B: TByteArray absolute P; begin while (Offset < Size) and (B[Offset] = Byte(C)) do Inc(Offset); Result := Offset; end; { ScanR } } function SkipR( var P; Offset, Size: Integer; C: Char ): Integer; assembler; {&USES esi,edi} {&FRAME-} asm cld mov edi,P mov edx, edi add edi,&Offset mov ecx,Size sub ecx,&Offset mov al,C repe scasb jne @@found mov eax, Size jmp @@exit @@found: sub edi, edx mov eax, edi dec eax @@exit: end; { --------------------------------------------------------- } { CharStr } { --------------------------------------------------------- } function CharStr( C: Char; Len: Integer ) : String; begin FillChar( Result[1], Len, C ); Result[0] := Chr(Len); end; { CharStr } { --------------------------------------------------------- } { PadCh } { --------------------------------------------------------- } function PadCh( const S: String; Len: Integer; Ch: Char ) : String; var d: Integer; begin d := Len - Length(S); if d > 0 then Result := S + CharStr( Ch, d ) else Result := Copy( S, 1, Len ); end; { PadCh } { --------------------------------------------------------- } { Pad } { --------------------------------------------------------- } function Pad( const S: String; Len: Integer ) : String; begin Result := PadCh( S, Len, ' ' ); end; { Pad } { --------------------------------------------------------- } { LeftPadCh } { --------------------------------------------------------- } function LeftPadCh( const S: String; Len: Integer; Ch: Char ) : String; var d: Integer; begin d := Len - Length(S); if d > 0 then Result := CharStr( Ch, d ) + S else Result := Copy( S, 1, Len ); end; { LeftPadCh } { --------------------------------------------------------- } { LeftPad } { --------------------------------------------------------- } function LeftPad( const S: String; Len: Integer ) : String; begin Result := LeftPadCh( S, Len, ' ' ); end; { LeftPad } { --------------------------------------------------------- } { CenterCh } { --------------------------------------------------------- } function CenterCh( const S : string; Width : Integer; Ch: Char ) : String; var SLen : Byte absolute S; o : string; begin if SLen >= Width then CenterCh := S else if SLen < 255 then begin o[0] := Chr(Width); FillChar(o[1], Width, Ch); Move(S[1], o[Succ((Width-SLen) shr 1)], SLen); CenterCh := o; end; end; { CenterCh } { --------------------------------------------------------- } { Center } { --------------------------------------------------------- } function Center( const S: String; Width: Integer ) : String; begin Result := CenterCh( S, Width, ' ' ); end; { Center } { --------------------------------------------------------- } { StrSet } { --------------------------------------------------------- } function StrSet( Ch: PChar; const S: String; Size: Integer ) : PChar; begin FillChar( Ch[0], Size, 0 ); if Size > Length(S) then Size := Length(S); Move( S[1], Ch[0], Size ); end; { StrSet } { --------------------------------------------------------- } { ExtractQuoted } { --------------------------------------------------------- } function ExtractQuoted( S: String ) : String; var Start: Integer; Stop : Integer; begin Start := 1; while (Start <= Length(S)) and (S[Start] <> '''') and (S[Start] <> '"') do Inc( Start ); Result := GetLiterals( S, Start, Stop ); end; { ExtractQuoted } { --------------------------------------------------------- } { QuotedFile } { --------------------------------------------------------- } function QuotedFile( const S: String ) : String; begin if Pos( ' ', S ) <> 0 then Result := '"' + S + '"' else Result := S; end; { QuotedFile } { --------------------------------------------------------- } { SkipWhiteSpace } { --------------------------------------------------------- } procedure SkipWhiteSpace( S: String; var pos: Integer ); begin pos := SkipR( S[1], pos, Length(S), ' ' ) + 1; end; { SkipWhiteSpace } { --------------------------------------------------------- } { GetLiterals } { --------------------------------------------------------- } function GetLiterals( S: String; Start: Integer; var Stop: Integer ) : String; label Failure; var ch: Char; begin Result := ''; Stop := Start; if Start > Length(S) then Exit; ch := S[Start]; if (ch <> '''') and (ch <> '"') then goto Failure; Inc(Start); while Start <= Length(S) do begin if S[Start] <> ch then Result := Result + S[Start] else begin Inc(Start); if (Start <= Length(S)) and (S[Start] = ch) then Result := Result + ch else begin Stop := Start; Exit; end; end; Inc(Start); end; Failure: raise Exception.Create( Format(LoadString(_SQuotedExpected), [S] )); end; { GetLiterals } { --------------------------------------------------------- } { GetRightID } { --------------------------------------------------------- } function GetRightID( S: String; Start: Integer; var Stop: Integer ) : String; begin Result := ''; Stop := Start; if (Stop > Length(S)) or (S[Stop] < 'A') or (S[Stop] > 'z') then Exit; while S[Stop] in IDCHARS do Inc(Stop); Result := Copy( S, Start, Stop - Start ); end; { GetRightID } { --------------------------------------------------------- } { MakePrintable } { --------------------------------------------------------- } function MakePrintable( const S: String ) : String; var j: Integer; n: Byte absolute Result; begin n := 0; for j := 1 to Length(S) do begin if S[j] < #$20 then begin Inc(n); Result[n] := '^'; Inc(n); Result[n] := Chr( Ord(S[j]) + $40 ); end else begin Inc(n); Result[n] := S[j]; end; end; end; { MakePrintable } { --------------------------------------------------------- } { Destroy } { --------------------------------------------------------- } procedure Destroy( O: PObject ); begin if O <> nil then Dispose( O, Done ); end; { Destroy } { --------------------------------------------------------- } { SetBit } { --------------------------------------------------------- } procedure SetBit( var Where: Longint; Mask: Longint; Raised: Boolean ); begin if Raised then Where := Where or Mask else Where := Where and not Mask; end; { SetBit } { --------------------------------------------------------- } { TestBit } { --------------------------------------------------------- } function TestBit( Where, Mask: Longint ) : Boolean; begin Result := (Where and Mask) <> 0; end; { TestBit } { --------------------------------------------------------- } { Replace } { --------------------------------------------------------- } function Replace( const S, What, Value: String ) : String; var Start: Integer; begin Result := S; Start := Pos( What, S ); if Start <> 0 then begin Delete( Result, Start, Length(What) ); Insert( Value, Result, Start ); end; end; { Replace } { --------------------------------------------------------- } { ASRF Implements ASRF(tm) format } { ver 2.0 - 24-Oct-01 } { --------------------------------------------------------- } function ASRF( FSize: Double ) : String; const KByte = Longint(1024); MByte = Longint(1024) * KByte; GByte = Longint(1024) * MByte; begin if FSize < KByte then Result := Format( '%4dB', [Trunc(FSize)] ) else if FSize < 10.0 * KByte then Result := Format( '%4.2fK', [FSize / KByte] ) else if FSize < 100.0 * KByte then Result := Format( '%4.1fK', [FSize / KByte] ) else if FSize < MByte then Result := Format( '%4dK', [Trunc(FSize / KByte)] ) else if FSize < 10.0 * MByte then Result := Format( '%4.2fM', [FSize / MByte] ) else if FSize < 100.0 * MByte then Result := Format( '%4.1fM', [FSize / MByte] ) else if FSize < GByte then Result := Format( '%4dM', [Trunc(FSize / MByte)] ) else if FSize < 10.0 * GByte then Result := Format( '%4.2fG', [FSize / GByte] ) else Result := Format( '%4.1fG', [FSize / GByte] ); end; { ASRF } { --------------------------------------------------------- } { TStrings } { --------------------------------------------------------- } { FreeItem ------------------------------------------------ } procedure TStrings.FreeItem( Item: Pointer ); begin FreeStr( PString(Item) ); end; { FreeItem } { --------------------------------------------------------- } { TNoCaseStrCollection } { --------------------------------------------------------- } { FreeItem ------------------------------------------------ } procedure TNoCaseStrCollection.FreeItem( Item: Pointer ); begin FreeStr( PString(Item) ); end; { FreeItem } { Compare ------------------------------------------------- } function TNoCaseStrCollection.Compare( Key1, Key2: Pointer ) : Integer; begin Result := JustCompareText( PString(Key1)^, PString(Key2)^ ); end; { Compare } { --------------------------------------------------------- } { DecodeLFN } { --------------------------------------------------------- } procedure DecodeLFN( var R: TSearchRec; var ShortName, LongName: String ); var S: String; begin {$IFDEF WIN32} with R.FindData do begin if cAlternateFileName[0] = #0 then begin ShortName := StrPas(cFileName); LongName := ''; end else begin ShortName := StrPas(cAlternateFileName); LongName := StrPas(cFileName); end; end; {$ELSE} ShortName := R.Name; LongName := ''; {$ENDIF} case Cfg.FileApi of fapi_primary_long: begin if LongName <> '' then begin S := LongName; LongName := ShortName; ShortName := S; end; end; fapi_native: begin if LongName <> '' then begin ShortName := LongName; LongName := ''; end; end; end; end; { DecodeLFN } { --------------------------------------------------------- } { VFS_TouchFile } { --------------------------------------------------------- } function VFS_TouchFile( const FileName: String; Stamp: FileTime ) : Boolean; var H: Integer; begin H := FileOpen( FileName, fmOpenReadWrite OR fmShareExclusive ); if H > 0 then begin Result := FileSetDate( H, Stamp ) = 0; FileClose( H ); end else Result := False; end; { VFS_TouchFile } { --------------------------------------------------------- } { VFS_EraseFile } { --------------------------------------------------------- } function VFS_EraseFile( const FileName: String ) : Boolean; var Attr: Integer; begin Result := False; Attr := FileGetAttr( FileName ); if Attr = -1 then Exit; if TestBit( Attr, faReadOnly + faHidden ) then begin SetBit( Attr, faReadOnly + faHidden, False ); FileSetAttr( FileName, Attr ); end; Result := SysUtils.DeleteFile( FileName ); end; { VFS_EraseFile } { --------------------------------------------------------- } { VFS_RenameFile } { --------------------------------------------------------- } function VFS_RenameFile( const Source, Dest: String ) : Boolean; begin Result := VFS_MoveFile( Source, Dest ) = 0; end; { VFS_RenameFile } { --------------------------------------------------------- } { VFS_MoveFile } { --------------------------------------------------------- } function VFS_MoveFile( const Source, Target: String ) : Integer; var s, d: array [0..256] of Char; begin StrPCopy( s, ExpandFileName(Source) ); StrPCopy( d, ExpandFileName(Target) ); if StrIComp( s, d ) = 0 then begin Result := 0; Exit; end; {$IFDEF Win32} OemToCharBuff( s, s, 256 ); OemToCharBuff( d, d, 256 ); {$ENDIF} if SysFileExists( d ) then SysFileDelete( d ); if UpCase( s[0] ) = UpCase( d[0] ) then Result := SysFileMove( s, d ) else begin if SysFileCopy( s, d, True ) then Result := SysFileDelete( s ) else Result := 1; end; end; { VFS_MoveFile } { --------------------------------------------------------- } { VFS_CopyFile } { --------------------------------------------------------- } function VFS_CopyFile( const Source, Target: String ) : Boolean; var s, d: array [0..256] of Char; begin {$IFDEF Win32} StrPCopy( s, Source ); OemToCharBuff( s, s, 256 ); StrPCopy( d, Target ); OemToCharBuff( d, d, 256 ); Result := SysFileCopy( s, d, True ); {$ELSE} Result := SysFileCopy( StrPCopy(s, Source), StrPCopy(d, Target), True ); {$ENDIF} end; { VFS_CopyFile } { --------------------------------------------------------- } { VFS_GetShortName } { --------------------------------------------------------- } {$IFDEF Win32} function VFS_GetShortName( Source: String; var Target: String ) : Boolean; var s, d: array [0..256] of Char; begin Result := False; StrPCopy( s, Source ); OemToCharBuff( s, s, 256 ); if GetShortPathName( s, d, 256 ) <> 0 then begin CharToOemBuff( d, d, 256 ); Target := ExtractFileName( StrPas( d ) ); Source := ExtractFileName( Source ); Result := not JustSameText( Source, Target ); end; end; { VFS_GetShortName } {$ENDIF} { --------------------------------------------------------- } { VFS_ValidatePath } { --------------------------------------------------------- } function VFS_ValidatePath( const Source: String ) : String; {$IFDEF Win32} var s, d: array [0..256] of Char; begin if Cfg.FileApi = fapi_primary_short then begin StrPCopy( s, Source ); OemToCharBuff( s, s, 256 ); GetShortPathName( s, d, 256 ); CharToOemBuff( d, d, 256 ); Result := StrPas( d ); end else Result := Source; {$ELSE} begin Result := Source; {$ENDIF} end; { VFS_ValidatePath } { --------------------------------------------------------- } { VFS_BackupFile } { --------------------------------------------------------- } procedure VFS_BackupFile( const FileName: String; Level: Integer ); procedure DoBackup( const Me: String; Deep: Integer ); var Bak: String; begin Bak := ChangeFileExt( Me, '.ba' + Chr( Ord('0') + Deep ) ); if FileExists( Bak ) then begin if Deep < Level then DoBackup( Bak, Deep + 1 ) else VFS_EraseFile( Bak ); end; VFS_RenameFile( Me, Bak ); end; { DoBackup } begin if (Level > 0) and FileExists( FileName ) then DoBackup( FileName, 1 ); end; { Backup } end.
unit WellSearchController; interface uses Classes, SysUtils; type TWellSearchController = class private FStrictAreaSearch: boolean; FStrictWellSearch: boolean; FWellNum: string; FAreaName: string; FAreaList: TStringList; function GetAreaList: TStrings; function BuildQuery: string; public property AreaName: string read FAreaName write FAreaName; property WellNum: string read FWellNum write FWellNum; property StrictAreaSearch: boolean read FStrictAreaSearch write FStrictAreaSearch; property StrictWellSearch: boolean read FStrictWellSearch write FStrictWellSearch; property AreaList: TStrings read GetAreaList; procedure ExecuteQuery; class function GetInstance: TWellSearchController; destructor Destroy; override; end; implementation uses Facade, Variants; { TWellSearchController } function TWellSearchController.BuildQuery: string; var sQuery, sFilter: string; sAreaName, sWellNum: string; sAreaWeakPart, sAreaStrictPart: string; sWellNumWeakPart, sWellNumStrictPart: string; begin sQuery := 'select distinct Area_ID, vch_Area_Name from vw_Well'; sAreaWeakPart := '((rf_rupper(vch_Area_Name) containing ''%s'') or (rf_rupper(vch_Well_Name) containing ''%s''))'; sAreaStrictPart := '((rf_rupper(vch_Area_Name) = ''%s'') or (rf_rupper(vch_Well_Name) containing ''%s''))'; sWellNumWeakPart := '((rf_rupper(vch_Well_Num) containing ''%s'') or (rf_rupper(vch_Well_Name) containing ''%s''))'; sWellNumStrictPart := '((rf_rupper(vch_Well_Num) = ''%s'') or (rf_rupper(vch_Well_Num) containing ''%s''))'; sAreaName := AnsiUpperCase(trim(AreaName)); sWellNum := AnsiUpperCase(trim(WellNum)); if trim(sAreaName) <> '' then begin sFilter := ' where '; if not StrictAreaSearch then sFilter := sFilter + Format(sAreaWeakPart, [sAreaName, sAreaName]) else sFilter := sFilter + Format(sAreaStrictPart, [sAreaName, sAreaName]); end; if trim(sWellNum) <> '' then begin if sFilter <> '' then sFilter := sFilter + ' and ' else sFilter := ' where '; if not StrictWellSearch then sFilter := sFilter + Format(sWellNumWeakPart, [sWellNum, sWellNum]) else sFilter := sFilter + Format(sWellNumStrictPart, [sWellNum, sWellNum]) end; Result := sQuery + ' ' + sFilter; end; destructor TWellSearchController.Destroy; begin FreeAndNil(FAreaList); inherited; end; procedure TWellSearchController.ExecuteQuery; var sQuery: string; vQueryResult: OleVariant; i: integer; begin sQuery := BuildQuery; if TMainFacade.GetInstance.DBGates.ExecuteQuery(sQuery, vQueryResult) > 0 then begin AreaList.Clear; for i := 0 to VarArrayHighBound(vQueryResult, 2) do AreaList.AddObject(varAsType(vQueryResult[1, i], varOleStr), TObject(Integer(varAsType(vQueryResult[0, i], varInteger)))); end; end; function TWellSearchController.GetAreaList: TStrings; begin if not Assigned(FAreaList) then FAreaList := TStringList.Create; Result := FAreaList; end; class function TWellSearchController.GetInstance: TWellSearchController; const wsc: TWellSearchController = nil; begin if not Assigned(wsc) then wsc := TWellSearchController.Create; Result := wsc; end; end.
unit ALIosVKontakteApi; interface uses Macapi.ObjectiveC, iOSapi.Foundation, iOSapi.CocoaTypes, iOSapi.UIKit; {$M+} type {*****************************************} //NS_ENUM(NSUInteger, VKAuthorizationState) VKAuthorizationState = NSUInteger; const {*************************} VKAuthorizationUnknown = 0; VKAuthorizationInitialized = 1; VKAuthorizationPending = 2; VKAuthorizationExternal = 3; VKAuthorizationSafariInApp = 4; VKAuthorizationWebview = 5; VKAuthorizationAuthorized = 6; VKAuthorizationError = 7; type {*************************************************} //NS_ENUM(NSInteger, VKShareDialogControllerResult) VKShareDialogControllerResult = NSUInteger; const {*****************************************} VKShareDialogControllerResultCancelled = 0; VKShareDialogControllerResultDone = 1; type {****************} //enum VKImageType VKImageType = Cardinal; const {*****************} VKImageTypeJpg = 0; VKImageTypePng = 1; type {************************} VKObjectClass = interface; VKError = interface; VKAuthorizationResult = interface; VKAccessToken = interface; VKSdkDelegate = interface; VKSdkUIDelegate = interface; VKSdk = interface; VKImageParameters = interface; VKUploadImage = interface; VKShareLink = interface; VKShareDialogController = interface; {**************************************************************************************************************************************} TVKShareDialogControllerCompletionHandler = procedure(dialog: VKShareDialogController; result: VKShareDialogControllerResult) of object; {******************************} //@interface VKObject : NSObject VKObjectClass = interface(NSObjectClass) ['{73A33031-F242-4DEA-ACDA-235D6F5D119A}'] end; VKObject = interface(NSObject) ['{2B83B160-E4D9-49CD-B568-3E899154D7F8}'] end; TVKObject = class(TOCGenericImport<VKObjectClass, VKObject>) end; {******************************} //@interface VKError : VKObject VKErrorClass = interface(VKObjectClass) ['{B33FC424-445C-4F10-AFEA-23A82935E562}'] //+ (instancetype)errorWithCode:(NSInteger)errorCode; {class} function errorWithCode(errorCode: NSInteger) : VKError {instancetype}; cdecl; //+ (instancetype)errorWithJson:(id)JSON; {class} function errorWithJson(JSON: Pointer) : VKError {instancetype}; cdecl; //+ (instancetype)errorWithQuery:(NSDictionary *)queryParams; {class} function errorWithQuery(queryParams: NSDictionary) : VKError {instancetype}; cdecl; end; VKError = interface(VKObject) ['{37FECAB7-19A6-4366-9046-69F04E676BCE}'] //@property(nonatomic, strong) NSError *httpError; procedure setHttpError(httpError: NSError); cdecl; function httpError : NSError; cdecl; //@property(nonatomic, strong) VKError *apiError; procedure setApiError(apiError: VKError); cdecl; function apiError : VKError; cdecl; //@property(nonatomic, strong) VKRequest *request; //procedure setRequest(request: VKRequest); cdecl; //function request : VKRequest; cdecl; //@property(nonatomic, assign) NSInteger errorCode; procedure setErrorCode(errorCode: NSInteger); cdecl; function errorCode : NSInteger; cdecl; //@property(nonatomic, strong) NSString *errorMessage; procedure setErrorMessage(errorMessage: NSString); cdecl; function errorMessage : NSString; cdecl; //@property(nonatomic, strong) NSString *errorReason; procedure setErrorReason(errorReason: NSString); cdecl; function errorReason : NSString; cdecl; //@property(nonatomic, strong) NSString *errorText; procedure setErrorText(errorText: NSString); cdecl; function errorText : NSString; cdecl; //@property(nonatomic, strong) NSDictionary *requestParams; procedure setRequestParams(requestParams: NSDictionary); cdecl; function requestParams : NSDictionary; cdecl; //@property(nonatomic, strong) NSString *captchaSid; procedure setCaptchaSid(captchaSid: NSString); cdecl; function captchaSid : NSString; cdecl; //@property(nonatomic, strong) NSString *captchaImg; procedure setCaptchaImg(captchaImg: NSString); cdecl; function captchaImg : NSString; cdecl; //@property(nonatomic, strong) NSString *redirectUri; procedure setRedirectUri(redirectUri: NSString); cdecl; function redirectUri : NSString; cdecl; //@property(nonatomic, strong) id json; procedure setJson(json: Pointer); cdecl; function json : Pointer; cdecl; //- (void)answerCaptcha:(NSString *)userEnteredCode; procedure answerCaptcha(userEnteredCode: NSString); cdecl; end; TVKError = class(TOCGenericImport<VKErrorClass, VKError>) end; {*******************************************} //@interface VKAuthorizationResult : VKObject VKAuthorizationResultClass = interface(VKObjectClass) ['{6ED5DDCA-39EF-43E2-AA51-B626DF082867}'] end; VKAuthorizationResult = interface(VKObject) ['{9120AD24-BCA3-4651-A756-275A5D2E55AE}'] //@property(nonatomic, readonly, strong) VKAccessToken *token; function token : VKAccessToken; cdecl; //@property(nonatomic, readonly, strong) VKUser *user; //function user : VKUser; cdecl; //@property(nonatomic, readonly, strong) NSError *error; function error : NSError; cdecl; //@property(nonatomic, readonly, assign) VKAuthorizationState state; function state : VKAuthorizationState; cdecl; end; TVKAuthorizationResult = class(TOCGenericImport<VKAuthorizationResultClass, VKAuthorizationResult>) end; {**********************************************} //@interface VKAccessToken : VKObject <NSCoding> VKAccessTokenClass = interface(VKObjectClass) ['{363241C5-57C5-4ACE-8B6D-2AC3385504A2}'] //+ (instancetype)tokenFromUrlString:(NSString *)urlString; {class} function tokenFromUrlString(urlString: NSString) : VKAccessToken {instancetype}; cdecl; //+ (instancetype)tokenWithToken:(NSString *)accessToken secret:(NSString *)secret userId:(NSString *)userId; {class} function tokenWithToken(accessToken: NSString; secret: NSString; userId: NSString) : VKAccessToken {instancetype}; cdecl; //+ (instancetype)savedToken:(NSString *)defaultsKey; {class} function savedToken(defaultsKey: NSString) : VKAccessToken {instancetype}; cdecl; //+ (void)delete:(NSString *)service; {class} procedure delete(service: NSString); cdecl; end; VKAccessToken = interface(VKObject) ['{CF2B08FD-A5BC-4CA2-8FD3-D34D7D7EACC1}'] //@property(nonatomic, readonly, copy) NSString *accessToken; function accessToken : NSString; cdecl; //@property(nonatomic, readonly, copy) NSString *userId; function userId : NSString; cdecl; //@property(nonatomic, readonly, copy) NSString *secret; function secret : NSString; cdecl; //@property(nonatomic, readonly, copy) NSArray *permissions; function permissions : NSArray; cdecl; //@property(nonatomic, readonly, copy) NSString *email; function email : NSString; cdecl; //@property(nonatomic, readonly, assign) NSInteger expiresIn; function expiresIn : NSInteger; cdecl; //@property(nonatomic, readonly, assign) BOOL httpsRequired; function httpsRequired : Boolean; cdecl; //@property(nonatomic, readonly, assign) NSTimeInterval created; function created : NSTimeInterval; cdecl; //@property(nonatomic, readonly, strong) VKUser *localUser; //function localUser : VKUser; cdecl; //- (void)saveTokenToDefaults:(NSString *)defaultsKey; procedure saveTokenToDefaults(defaultsKey: NSString); cdecl; //- (BOOL)isExpired; function isExpired : Boolean; cdecl; end; TVKAccessToken = class(TOCGenericImport<VKAccessTokenClass, VKAccessToken>) end; {**********************************} //@protocol VKSdkDelegate <NSObject> VKSdkDelegate = interface(IObjectiveC) ['{B86838F7-433A-49BA-8D4D-E3E6698B3F3B}'] //- (void)vkSdkAccessAuthorizationFinishedWithResult:(VKAuthorizationResult *)result; procedure vkSdkAccessAuthorizationFinishedWithResult(result: VKAuthorizationResult); cdecl; //- (void)vkSdkUserAuthorizationFailed; procedure vkSdkUserAuthorizationFailed; cdecl; //- (void)vkSdkAuthorizationStateUpdatedWithResult:(VKAuthorizationResult *)result; procedure vkSdkAuthorizationStateUpdatedWithResult(result: VKAuthorizationResult); cdecl; //- (void)vkSdkAccessTokenUpdated:(VKAccessToken *)newToken oldToken:(VKAccessToken *)oldToken; procedure vkSdkAccessTokenUpdated(newToken: VKAccessToken; oldToken: VKAccessToken); cdecl; //- (void)vkSdkTokenHasExpired:(VKAccessToken *)expiredToken; procedure vkSdkTokenHasExpired(expiredToken: VKAccessToken); cdecl; end; {************************************} //@protocol VKSdkUIDelegate <NSObject> VKSdkUIDelegate = interface(IObjectiveC) ['{D2F9A031-4CFF-4EFF-8639-E4C1F4B49CF4}'] //- (void)vkSdkShouldPresentViewController:(UIViewController *)controller; procedure vkSdkShouldPresentViewController(controller: UIViewController); cdecl; //- (void)vkSdkNeedCaptchaEnter:(VKError *)captchaError; procedure vkSdkNeedCaptchaEnter(captchaError: VKError); cdecl; //- (void)vkSdkWillDismissViewController:(UIViewController *)controller; procedure vkSdkWillDismissViewController(controller: UIViewController); cdecl; //- (void)vkSdkDidDismissViewController:(UIViewController *)controller; procedure vkSdkDidDismissViewController(controller: UIViewController); cdecl; end; {***************************} //@interface VKSdk : NSObject VKSdkClass = interface(NSObjectClass) ['{7412935A-53D4-403A-8C90-31A76A964B22}'] //+ (instancetype)instance; {class} function instance : VKSdk {instancetype}; cdecl; //+ (BOOL)initialized; {class} function initialized : Boolean; cdecl; //+ (instancetype)initializeWithAppId:(NSString *)appId; [MethodName('initializeWithAppId:')] {class} function initializeWithAppId(appId: NSString) : VKSdk {instancetype}; cdecl; //+ (instancetype)initializeWithAppId:(NSString *)appId // apiVersion:(NSString *)version; [MethodName('initializeWithAppId:apiVersion:')] {class} function initializeWithAppIdApiVersion(appId: NSString; apiVersion: NSString) : VKSdk {instancetype}; cdecl; //+ (void)authorize:(NSArray *)permissions; [MethodName('authorize:')] {class} procedure authorize(permissions: NSArray); cdecl; //+ (void)authorize:(NSArray *)permissions withOptions:(VKAuthorizationOptions)options; //[MethodName('authorize:withOptions:')] //{class} procedure authorizeWithOptions(permissions: NSArray; withOptions: VKAuthorizationOptions); cdecl; //+ (VKAccessToken *)accessToken; {class} function accessToken : VKAccessToken; cdecl; //+ (BOOL)processOpenURL:(NSURL *)passedUrl fromApplication:(NSString *)sourceApplication; {class} function processOpenURL(passedUrl: NSURL; fromApplication: NSString) : Boolean; cdecl; //+ (BOOL)isLoggedIn; {class} function isLoggedIn : Boolean; cdecl; //+ (void)wakeUpSession:(NSArray *)permissions completeBlock:(void (^)(VKAuthorizationState state, NSError *error))wakeUpBlock; //{class} procedure wakeUpSession(permissions: NSArray; completeBlock: TVKSdkFrameworkCompleteBlock2); cdecl; //+ (void)forceLogout; {class} procedure forceLogout; cdecl; //+ (BOOL)vkAppMayExists; {class} function vkAppMayExists : Boolean; cdecl; //+ (void)setSchedulerEnabled:(BOOL)enabled; {class} procedure setSchedulerEnabled(enabled: Boolean); cdecl; end; VKSdk = interface(NSObject) ['{E81B4F55-E1D1-4822-B61F-0D9A299F0899}'] //@property(nonatomic, readwrite, weak) id <VKSdkUIDelegate> uiDelegate; procedure setUiDelegate(uiDelegate: VKSdkUIDelegate); cdecl; function uiDelegate : VKSdkUIDelegate; cdecl; //@property(nonatomic, readonly, copy) NSString *currentAppId; function currentAppId : NSString; cdecl; //@property(nonatomic, readonly, copy) NSString *apiVersion; function apiVersion : NSString; cdecl; //- (void)registerDelegate:(id <VKSdkDelegate>)delegate; procedure registerDelegate(delegate: VKSdkDelegate); cdecl; //- (void)unregisterDelegate:(id <VKSdkDelegate>)delegate; procedure unregisterDelegate(delegate: VKSdkDelegate); cdecl; //- (BOOL)hasPermissions:(NSArray *)permissions; function hasPermissions(permissions: NSArray) : Boolean; cdecl; end; TVKSdk = class(TOCGenericImport<VKSdkClass, VKSdk>) end; {***************************************} //@interface VKImageParameters : VKObject VKImageParametersClass = interface(VKObjectClass) ['{6D7D4165-6DCB-424C-B0B0-197AE55B9495}'] //+ (instancetype)pngImage; {class} function pngImage : VKImageParameters {instancetype}; cdecl; //+ (instancetype)jpegImageWithQuality:(float)quality; {class} function jpegImageWithQuality(quality: Single) : VKImageParameters {instancetype}; cdecl; end; VKImageParameters = interface(VKObject) ['{E787BC8E-21F9-4C35-859F-F263A0CF15B5}'] //@property(nonatomic, assign) VKImageType imageType; procedure setImageType(imageType: VKImageType); cdecl; function imageType : VKImageType; cdecl; //@property(nonatomic, assign) CGFloat jpegQuality; procedure setJpegQuality(jpegQuality: CGFloat); cdecl; function jpegQuality : CGFloat; cdecl; //- (NSString *)fileExtension; function fileExtension : NSString; cdecl; //- (NSString *)mimeType; function mimeType : NSString; cdecl; end; TVKImageParameters = class(TOCGenericImport<VKImageParametersClass, VKImageParameters>) end; {***********************************} //@interface VKUploadImage : VKObject VKUploadImageClass = interface(VKObjectClass) ['{FC55F5A9-235B-46E9-A99F-87DEFFDBC87F}'] //+ (instancetype)uploadImageWithData:(NSData *)data andParams:(VKImageParameters *)params; {class} function uploadImageWithData(data: NSData; andParams: VKImageParameters) : VKUploadImage {instancetype}; cdecl; //+ (instancetype)uploadImageWithImage:(UIImage *)image andParams:(VKImageParameters *)params; {class} function uploadImageWithImage(image: UIImage; andParams: VKImageParameters) : VKUploadImage {instancetype}; cdecl; end; VKUploadImage = interface(VKObject) ['{FBD59C1C-D865-4BD1-967D-8A57A0DD3859}'] //@property(nonatomic, strong) NSData *imageData; procedure setImageData(imageData: NSData); cdecl; function imageData : NSData; cdecl; //@property(nonatomic, strong) UIImage *sourceImage; procedure setSourceImage(sourceImage: UIImage); cdecl; function sourceImage : UIImage; cdecl; //@property(nonatomic, strong) VKImageParameters *parameters; procedure setParameters(parameters: VKImageParameters); cdecl; function parameters : VKImageParameters; cdecl; end; TVKUploadImage = class(TOCGenericImport<VKUploadImageClass, VKUploadImage>) end; {*********************************} //@interface VKShareLink : VKObject VKShareLinkClass = interface(VKObjectClass) ['{3FB9D911-11F8-4DA0-95A4-6C827573B8E2}'] end; VKShareLink = interface(VKObject) ['{4E949F57-5713-4F8F-99F7-E02A9BD74B50}'] //@property(nonatomic, copy) NSString *title; procedure setTitle(title: NSString); cdecl; function title : NSString; cdecl; //@property(nonatomic, copy) NSURL *link; procedure setLink(link: NSURL); cdecl; function link : NSURL; cdecl; //- (instancetype)initWithTitle:(NSString *)title link:(NSURL *)link; function initWithTitle(title: NSString; link: NSURL) : VKShareLink {instancetype}; cdecl; end; TVKShareLink = class(TOCGenericImport<VKShareLinkClass, VKShareLink>) end; {*****************************************************} //@interface VKShareDialogController : UIViewController VKShareDialogControllerClass = interface(UIViewControllerClass) ['{D12E9EBA-FA76-4240-863C-3F2F9F11D056}'] end; VKShareDialogController = interface(UIViewController) ['{A2BADE99-4607-419E-B62A-BBC28B89E6A3}'] //@property(nonatomic, strong) NSArray *uploadImages; procedure setUploadImages(uploadImages: NSArray); cdecl; function uploadImages : NSArray; cdecl; //@property(nonatomic, strong) NSArray *vkImages; procedure setVkImages(vkImages: NSArray); cdecl; function vkImages : NSArray; cdecl; //@property(nonatomic, strong) VKShareLink *shareLink; procedure setShareLink(shareLink: VKShareLink); cdecl; function shareLink : VKShareLink; cdecl; //@property(nonatomic, copy) NSString *text; procedure setText(text: NSString); cdecl; function text : NSString; cdecl; //@property(nonatomic, strong) NSArray *requestedScope; procedure setRequestedScope(requestedScope: NSArray); cdecl; function requestedScope : NSArray; cdecl; //@property(nonatomic, copy) void (^completionHandler)(VKShareDialogController *dialog, VKShareDialogControllerResult result); procedure setCompletionHandler(completionHandler: TVKShareDialogControllerCompletionHandler); cdecl; function completionHandler : TVKShareDialogControllerCompletionHandler; cdecl; //@property(nonatomic, assign) BOOL dismissAutomatically; procedure setDismissAutomatically(dismissAutomatically: Boolean); cdecl; function dismissAutomatically : Boolean; cdecl; //@property(nonatomic, readonly, copy) NSString *postId; function postId : NSString; cdecl; end; TVKShareDialogController = class(TOCGenericImport<VKShareDialogControllerClass, VKShareDialogController>) end; implementation {$IF defined(CPUARM)} procedure StubProc1; cdecl; external 'VKSdkFramework' name 'OBJC_CLASS_$_VKSdk'; {$ELSE} // i don't know how to do under ios simulator :( {$ENDIF} end.
unit test02; interface uses System.SysUtils; implementation type hash32 = cardinal; /// internal buffer for SHA256 hashing TSHA256Buffer = array[0..63] of hash32; /// internal work buffer for SHA256 hashing TSHAHash = record A,B,C,D,E,F,G,H: hash32; end; shr0 = hash32; var Hash: TSHAHash; Buffer: TSHA256Buffer; const K: TSHA256Buffer = ( $428a2f98, $71374491, $b5c0fbcf, $e9b5dba5, $3956c25b, $59f111f1, $923f82a4, $ab1c5ed5, $d807aa98, $12835b01, $243185be, $550c7dc3, $72be5d74, $80deb1fe, $9bdc06a7, $c19bf174, $e49b69c1, $efbe4786, $0fc19dc6, $240ca1cc, $2de92c6f, $4a7484aa, $5cb0a9dc, $76f988da, $983e5152, $a831c66d, $b00327c8, $bf597fc7, $c6e00bf3, $d5a79147, $06ca6351, $14292967, $27b70a85, $2e1b2138, $4d2c6dfc, $53380d13, $650a7354, $766a0abb, $81c2c92e, $92722c85, $a2bfe8a1, $a81a664b, $c24b8b70, $c76c51a3, $d192e819, $d6990624, $f40e3585, $106aa070, $19a4c116, $1e376c08, $2748774c, $34b0bcb5, $391c0cb3, $4ed8aa4a, $5b9cca4f, $682e6ff3, $748f82ee, $78a5636f, $84c87814, $8cc70208, $90befffa, $a4506ceb, $bef9a3f7, $c67178f2); procedure TSHA256Compress; var W: TSHA256Buffer; H: TSHAHash; i: integer; t1, t2: hash32; begin H := Hash; for i := 0 to 15 do W[i]:= shr0((Buffer[i*4] shl 24)or(Buffer[i*4+1] shl 16)or (Buffer[i*4+2] shl 8)or Buffer[i*4+3]); for i := 16 to 63 do W[i] := shr0((((W[i-2]shr 17)or(W[i-2]shl 15))xor((W[i-2]shr 19)or(W[i-2]shl 13)) xor (W[i-2]shr 10))+W[i-7]+(((W[i-15]shr 7)or(W[i-15]shl 25)) xor ((W[i-15]shr 18)or(W[i-15]shl 14))xor(W[i-15]shr 3))+W[i-16]); for i := 0 to high(W) do begin t1 := shr0(H.H+(((H.E shr 6)or(H.E shl 26))xor((H.E shr 11)or(H.E shl 21))xor ((H.E shr 25)or(H.E shl 7)))+((H.E and H.F)xor(not H.E and H.G))+K[i]+W[i]); t2 := shr0((((H.A shr 2)or(H.A shl 30))xor((H.A shr 13)or(H.A shl 19))xor ((H.A shr 22)xor(H.A shl 10)))+((H.A and H.B)xor(H.A and H.C)xor(H.B and H.C))); H.H := H.G; H.G := H.F; H.F := H.E; H.E := shr0(H.D+t1); H.D := H.C; H.C := H.B; H.B := H.A; H.A := shr0(t1+t2); end; Hash.A := shr0(Hash.A+H.A); Hash.B := shr0(Hash.B+H.B); Hash.C := shr0(Hash.C+H.C); Hash.D := shr0(Hash.D+H.D); Hash.E := shr0(Hash.E+H.E); Hash.F := shr0(Hash.F+H.F); Hash.G := shr0(Hash.G+H.G); Hash.H := shr0(Hash.H+H.H); end; end.
unit CustomizeObjectBrowser; interface uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Grids, BCDialogs.Dlg, Vcl.Buttons, ActnList, ValEdit, Vcl.Themes, Vcl.ExtCtrls, System.Actions, Vcl.ComCtrls, Vcl.ToolWin, BCControls.ToolBar, Vcl.ImgList, BCControls.ImageList; type TCustomizeObjectBrowserDialog = class(TDialog) ActionList: TActionList; BottomPanel: TPanel; CancelButton: TButton; MoveDownAction: TAction; MoveUpAction: TAction; OKAction: TAction; OKButton: TButton; Separator1Panel: TPanel; Separator2Panel: TPanel; TopPanel: TPanel; ValueListEditor: TValueListEditor; ImageList: TBCImageList; ToolBar: TBCToolBar; MoveUpToolButton: TToolButton; MoveDownToolButton: TToolButton; procedure FormDestroy(Sender: TObject); procedure MoveDownActionExecute(Sender: TObject); procedure MoveUpActionExecute(Sender: TObject); procedure OKActionExecute(Sender: TObject); procedure ValueListEditorClick(Sender: TObject); procedure ValueListEditorDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Private declarations } FInMouseClick: Boolean; procedure FillValueList; procedure WriteIniFile; public { Public declarations } function Open: Boolean; end; function CustomizeObjectBrowserDialog: TCustomizeObjectBrowserDialog; implementation {$R *.dfm} uses Winapi.UxTheme, System.Math, BigIni, BCCommon.StyleUtils, BCCommon.FileUtils; const TXT_MARG: TPoint = (x: 4; y: 2); BTN_WIDTH = 12; CELL_PADDING = 4; var FCustomizeObjectBrowserDialog: TCustomizeObjectBrowserDialog; function CustomizeObjectBrowserDialog: TCustomizeObjectBrowserDialog; begin if not Assigned(FCustomizeObjectBrowserDialog) then Application.CreateForm(TCustomizeObjectBrowserDialog, FCustomizeObjectBrowserDialog); Result := FCustomizeObjectBrowserDialog; SetStyledFormSize(Result); end; procedure TCustomizeObjectBrowserDialog.FormDestroy(Sender: TObject); begin FCustomizeObjectBrowserDialog := nil; end; procedure TCustomizeObjectBrowserDialog.MoveDownActionExecute(Sender: TObject); begin if ValueListEditor.Row < ValueListEditor.RowCount - 1 then begin ValueListEditor.Strings.Exchange(ValueListEditor.Row - 1, ValueListEditor.Row); ValueListEditor.Row := ValueListEditor.Row + 1; end; end; procedure TCustomizeObjectBrowserDialog.MoveUpActionExecute(Sender: TObject); begin if ValueListEditor.Row - 1 > 0 then begin ValueListEditor.Strings.Exchange(ValueListEditor.Row - 1, ValueListEditor.Row - 2); ValueListEditor.Row := ValueListEditor.Row - 1; end; end; procedure TCustomizeObjectBrowserDialog.ValueListEditorClick(Sender: TObject); var where: TPoint; ACol, ARow: integer; Rect, btnRect: TRect; s: TSize; begin //Again, check to avoid recursion: if not FInMouseClick then begin FInMouseClick := true; try //Get clicked coordinates and cell: where := Mouse.CursorPos; where := ValueListEditor.ScreenToClient(where); ValueListEditor.MouseToCell(where.x, where.y, ACol, ARow); if ARow > 0 then begin //Get buttonrect for clicked cell: //btnRect := GetBtnRect(ACol, ARow, false); s.cx := GetSystemMetrics(SM_CXMENUCHECK); s.cy := GetSystemMetrics(SM_CYMENUCHECK); Rect := ValueListEditor.CellRect(ACol, ARow); btnRect.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; btnRect.Bottom := btnRect.Top + s.cy; btnRect.Left := Rect.Left + CELL_PADDING; btnRect.Right := btnRect.Left + s.cx; InflateRect(btnrect, 2, 2); //Allow 2px 'error-range'... //Check if clicked inside buttonrect: if PtInRect(btnRect, where) then if ACol = 1 then begin if ValueListEditor.Cells[ACol, ARow] = 'True' then ValueListEditor.Cells[ACol, ARow] := 'False' else ValueListEditor.Cells[ACol, ARow] := 'True' end; end; finally FInMouseClick := false; end; end; ValueListEditor.Repaint; end; procedure TCustomizeObjectBrowserDialog.ValueListEditorDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var h: HTHEME; s: TSize; r, header, LRect: TRect; LStyles: TCustomStyleServices; LColor: TColor; LDetails: TThemedElementDetails; function Checked(ARow: Integer): Boolean; begin if ValueListEditor.Cells[1, ARow] = 'True' then Result := True else Result := False end; begin LStyles := StyleServices; if ARow = 0 then begin if not LStyles.GetElementColor(LStyles.GetElementDetails(thHeaderItemNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); header := Rect; if Assigned(TStyleManager.ActiveStyle) then if TStyleManager.ActiveStyle.Name <> 'Windows' then Dec(header.Left, 1); Inc(header.Right, 1); Inc(header.Bottom, 1); ValueListEditor.Canvas.Brush.Color := LStyles.GetSystemColor(ValueListEditor.FixedColor); ValueListEditor.Canvas.Font.Color := LColor; ValueListEditor.Canvas.FillRect(header); ValueListEditor.Canvas.Brush.Style := bsClear; if UseThemes then begin LStyles.DrawElement(ValueListEditor.Canvas.Handle, StyleServices.GetElementDetails(thHeaderItemNormal), header); LDetails := LStyles.GetElementDetails(thHeaderItemNormal); Inc(header.Left, 4); Dec(header.Right, 1); Dec(header.Bottom, 1); if ACol = 0 then LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], header, [tfSingleLine, tfVerticalCenter]) else LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], header, [tfCenter, tfSingleLine, tfVerticalCenter]); end; end; if (ARow > 0) then begin if not LStyles.GetElementColor(LStyles.GetElementDetails(tgCellNormal), ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); //get and set the backgroun color ValueListEditor.Canvas.Brush.Color := LStyles.GetStyleColor(scListView); ValueListEditor.Canvas.Font.Color := LColor; if UseThemes and (gdSelected in State) then begin ValueListEditor.Canvas.Brush.Color := LStyles.GetSystemColor(clHighlight); ValueListEditor.Canvas.Font.Color := LStyles.GetSystemColor(clHighlightText); end else if not UseThemes and (gdSelected in State) then begin ValueListEditor.Canvas.Brush.Color := clHighlight; ValueListEditor.Canvas.Font.Color := clHighlightText; end; ValueListEditor.Canvas.FillRect(Rect); ValueListEditor.Canvas.Brush.Style := bsClear; // draw selected if UseThemes and (gdSelected in State) then begin LRect := Rect; Dec(LRect.Left, 1); Inc(LRect.Right, 2); LDetails := LStyles.GetElementDetails(tgCellSelected); LStyles.DrawElement(ValueListEditor.Canvas.Handle, LDetails, LRect); end; s.cx := GetSystemMetrics(SM_CXMENUCHECK); s.cy := GetSystemMetrics(SM_CYMENUCHECK); if (ACol = 1) and UseThemes then begin h := OpenThemeData(ValueListEditor.Handle, 'BUTTON'); if h <> 0 then try GetThemePartSize(h, ValueListEditor.Canvas.Handle, BP_CHECKBOX, CBS_CHECKEDNORMAL, nil, TS_DRAW, s); r.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; r.Bottom := r.Top + s.cy; r.Left := Rect.Left + CELL_PADDING; r.Right := r.Left + s.cx; if Checked(ARow) then LDetails := LStyles.GetElementDetails(tbCheckBoxcheckedNormal) else LDetails := LStyles.GetElementDetails(tbCheckBoxUncheckedNormal); LStyles.DrawElement(ValueListEditor.Canvas.Handle, LDetails, r); finally CloseThemeData(h); end; end else if (ACol = 1) then begin r.Top := Rect.Top + (Rect.Bottom - Rect.Top - s.cy) div 2; r.Bottom := r.Top + s.cy; r.Left := Rect.Left + CELL_PADDING; r.Right := r.Left + s.cx; DrawFrameControl(ValueListEditor.Canvas.Handle, r, DFC_BUTTON, IfThen(Checked(ARow), DFCS_CHECKED, DFCS_BUTTONCHECK)); end; LRect := Rect; Inc(LRect.Left, 4); if (gdSelected in State) then LDetails := LStyles.GetElementDetails(tgCellSelected) else LDetails := LStyles.GetElementDetails(tgCellNormal); if not LStyles.GetElementColor(LDetails, ecTextColor, LColor) or (LColor = clNone) then LColor := LStyles.GetSystemColor(clWindowText); ValueListEditor.Canvas.Font.Color := LColor; if (ACol = 1) then begin Inc(LRect.Left, 20); LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], LRect, [tfSingleLine, tfVerticalCenter, tfEndEllipsis]) end else LStyles.DrawText(ValueListEditor.Canvas.Handle, LDetails, ValueListEditor.Cells[ACol, ARow], LRect, [tfSingleLine, tfVerticalCenter]); end; end; procedure TCustomizeObjectBrowserDialog.FillValueList; var i: Integer; TreeObjects: TStrings; begin { read from ini } TreeObjects := TStringList.Create; try with TBigIniFile.Create(GetINIFilename) do try ReadSectionValues('CustomizeObjectTree', TreeObjects); finally Free; end; if TreeObjects.Count = 0 then Exit; ValueListEditor.Strings.Clear; for i := 0 to TreeObjects.Count - 1 do ValueListEditor.Strings.Add(TreeObjects.Strings[i]); finally TreeObjects.Free; end; end; procedure TCustomizeObjectBrowserDialog.WriteIniFile; var i: Integer; Section: string; begin with TBigIniFile.Create(GetINIFilename) do try Section := 'CustomizeObjectTree'; EraseSection(Section); for i := 1 to ValueListEditor.RowCount - 1 do WriteString(Section, ValueListEditor.Keys[i], ValueListEditor.Values[ValueListEditor.Keys[i]]); finally Free; end; end; procedure TCustomizeObjectBrowserDialog.OKActionExecute(Sender: TObject); begin WriteIniFile; ModalResult := mrOk; end; function TCustomizeObjectBrowserDialog.Open: Boolean; begin FInMouseClick := False; FillValueList; Result := ShowModal = mrOk; end; end.
unit teste.classes.cliente; interface uses Windows, System.classes, System.Generics.Collections, System.SysUtils; type TclienteClass = class Private Fcodigo: integer; Fnome: string; Fcidade: string; Fuf: string; public function Listaclientes(filtro: string): OleVariant; procedure Limpar(); procedure Gravar; procedure Excluir; constructor create(icodigo: integer); published Property Codigo: integer read Fcodigo write Fcodigo; Property Nome: string read Fnome write Fnome; Property Cidade: string read Fcidade write Fcidade; Property Uf: string read Fuf write Fuf; end; Tclientes = TObjectList<TclienteClass>; implementation uses teste.dao.cliente; { Tcliente } { ------------------------------------------------------------------------- } constructor TclienteClass.create(icodigo: integer); begin if icodigo > 0 then begin Codigo := icodigo; Tdaocliente.getcliente(self); end; end; { ------------------------------------------------------------------------- } procedure TclienteClass.Excluir; begin if Tdaocliente.deletecliente(self) then Limpar(); end; { ------------------------------------------------------------------------- } procedure TclienteClass.Gravar; begin Tdaocliente.getcliente(self); end; { ------------------------------------------------------------------------- } procedure TclienteClass.Limpar; begin Fcodigo := 0; Fnome := ''; Fcidade := ''; Fuf := ''; end; { ------------------------------------------------------------------------- } function TclienteClass.Listaclientes(filtro: string): OleVariant; begin result := Tdaocliente.listarclientes(filtro); end; { ------------------------------------------------------------------------- } end.
unit MBRangeArchiver; {$mode objfpc}{$H+} interface uses Classes, SysUtils, syncobjs, contnrs, LoggerItf, MBArchiverConst, MBArchiverTypes; type TMBRangeArchiver = class; { Поток занимается открытием/закрытием файла архива, отслеживанием его размера, записью пакетов в файл. } { TMBRangeArchThread } TMBRangeArchThread = class(TThreadLogged) private FArchiver : TMBRangeArchiver; FIsOwnIncomPack : Boolean; FIsTextArch : Boolean; FFileStream : TFileStream; FFileName : String; FDevNum : Byte; FRangeLen : Word; FRangeType : TMBArchiverRangeType; FRangeStartAddr : Word; FRangeByteLen : Word; FMaxFileLen : Cardinal; FTextCaption : String; FDelimiter : String; FPollDelay : Cardinal; protected procedure Execute; override; function Init : Boolean; procedure Close; procedure FileFlush; procedure FreePack(APack : Pointer); procedure WritePack(APack : Pointer); procedure WriteCaption; procedure WriteAsText(ARecord: PMBWordArchRecord); overload; procedure WriteAsText(ARecord: PMBBoolArchRecord); overload; procedure WriteAsBin(ARecord: PMBWordArchRecord); overload; procedure WriteAsBin(ARecord: PMBBoolArchRecord); overload; public constructor Create(ARengeArch : TMBRangeArchiver); destructor Destroy; override; property PollDelay : Cardinal read FPollDelay write FPollDelay default DefPollDelay; end; { TMBRangeArchiver } TMBRangeArchiver = class(TComponentLogged) private FCSection : TCriticalSection; FThread : TMBRangeArchThread; FQueue : TQueue; FDevNum : Byte; FFileName : String; FIsTextArch : Boolean; FIsOwnIncomPack : Boolean; FMaxFileLen : Cardinal; FPath : String; FRangeLen : Word; FRangeStartAddr : Word; FRangeType : TMBArchiverRangeType; FTextCaption : String; FDelimiter : String; function GetActive: Boolean; function GetDevNum: Byte; function GetFileName: String; function GetIsOwnIncomPack: Boolean; function GetIsTextArch: Boolean; function GetMaxFileLen: Cardinal; function GetPath: String; function GetQueue: TQueue; function GetRangeLen: Word; function GetRangeStartAddr: Word; function GetRangeType: TMBArchiverRangeType; function GetTextCaption: String; procedure SetDelimiter(AValue: String); procedure SetDevNum(AValue: Byte); procedure SetFileName(AValue: String); procedure SetIsOwnIncomPack(AValue: Boolean); procedure SetIsTextArch(AValue: Boolean); procedure SetMaxFileLen(AValue: Cardinal); procedure SetPath(AValue: String); procedure SetRangeLen(AValue: Word); procedure SetRangeStartAddr(AValue: Word); procedure SetRangeType(AValue: TMBArchiverRangeType); procedure SetTextCaption(AValue: String); protected procedure SetLogger(const AValue: IDLogger); override; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Lock; procedure Unlock; function GenFullFileName : String; function GenTextCaption : String; procedure CleanQueue; procedure AddRecordToArchive(ATimeStamp : TDateTime; AData : PWordarray); overload; procedure AddRecordToArchive(ATimeStamp : TDateTime; AData : PByteArray); overload; function Start : Boolean; procedure Stop; property Queue : TQueue read GetQueue; property Active : Boolean read GetActive; property IsOwnIncomPack : Boolean read GetIsOwnIncomPack write SetIsOwnIncomPack default True; property Path : String read GetPath write SetPath {DefLinFilePath DefWinFilePath}; property FileName : String read GetFileName write SetFileName; property MaxFileLen : Cardinal read GetMaxFileLen write SetMaxFileLen default DefMaxFileSize; property IsTextArch : Boolean read GetIsTextArch write SetIsTextArch default False; property TextCaption : String read GetTextCaption write SetTextCaption; property Delimiter : String read FDelimiter write SetDelimiter {default DefColDelimiter}; property DevNum : Byte read GetDevNum write SetDevNum; property RangeStartAddr : Word read GetRangeStartAddr write SetRangeStartAddr; property RangeLen : Word read GetRangeLen write SetRangeLen; property RangeType : TMBArchiverRangeType read GetRangeType write SetRangeType default artWord; end; implementation uses MiscFunctions {$IFDEF UNIX} , Unix{$ELSE} , windows {$ENDIF}, MBArchiverResStrings; { TMBRangeArchThread } constructor TMBRangeArchThread.Create(ARengeArch: TMBRangeArchiver); begin if not Assigned(ARengeArch) then Exit; inherited Create(True,65535); FArchiver := ARengeArch; FFileStream := nil; FIsOwnIncomPack := FArchiver.IsOwnIncomPack; FIsTextArch := FArchiver.IsTextArch; FFileName := FArchiver.GenFullFileName; FMaxFileLen := FArchiver.MaxFileLen; FTextCaption := FArchiver.TextCaption; if FTextCaption = '' then FTextCaption := FArchiver.GenTextCaption; FDelimiter := FArchiver.Delimiter; FDevNum := FArchiver.DevNum; FRangeType := FArchiver.RangeType; FRangeLen := FArchiver.RangeLen; if FRangeType = artBoolean then begin FRangeByteLen := FRangeLen div 8; if (FRangeLen mod 8) <> 0 then Inc(FRangeByteLen); end else FRangeByteLen := FRangeLen * 2; FRangeStartAddr := FArchiver.RangeStartAddr; FPollDelay := DefPollDelay; end; destructor TMBRangeArchThread.Destroy; begin Close; inherited Destroy; end; procedure TMBRangeArchThread.Execute; var IsInit : Boolean; TempPack : Pointer; begin IsInit := Init; try while not Terminated do begin FArchiver.Lock; try TempPack := FArchiver.Queue.Pop; if not IsInit then begin FreePack(TempPack); Sleep(FPollDelay); Continue; end; WritePack(TempPack); FreePack(TempPack); if FFileStream.Size > FMaxFileLen then begin Close; FFileName := FArchiver.GenFullFileName; IsInit := Init; Continue; end; Sleep(FPollDelay); finally FArchiver.Unlock; end; end; finally Close; end; end; function TMBRangeArchThread.Init: Boolean; begin Result := False; try FFileStream := TFileStream.Create(FFileName,fmCreate); except On E : Exception do begin SendLogMessage(llError,rsArchiver, Format(rsArchErrorCreateFile,[E.Message])); FFileStream := nil; Exit; end; end; try FreeAndNil(FFileStream); FFileStream := TFileStream.Create(FFileName,fmOpenWrite or fmShareDenyWrite); SendLogMessage(llInfo,rsArchiver,Format(rsArchFileOpen,[FFileName])); except On E : Exception do begin SendLogMessage(llError,rsArchiver, Format(rsArchErrorOpenFile,[E.Message])); FFileStream := nil; Exit; end; end; WriteCaption; Result := True; end; procedure TMBRangeArchThread.Close; begin if not Assigned(FFileStream) then Exit; SendLogMessage(llInfo,rsArchiver, Format(rsArchFileClose,[FFileStream.Size])); FileFlush; FreeAndNil(FFileStream); end; procedure TMBRangeArchThread.FileFlush; begin {$IFDEF MSWINDOWS} FlushFileBuffers(FFileStream.Handle); {$ELSE} fpfsync(FFileStream.Handle); {$ENDIF} end; procedure TMBRangeArchThread.FreePack(APack: Pointer); begin if not Assigned(APack) then Exit; if not FIsOwnIncomPack then begin if Assigned(PMBWordArchRecord(APack)^.RegsData) then Freemem(PMBWordArchRecord(APack)^.RegsData); end; Freemem(APack); end; procedure TMBRangeArchThread.WritePack(APack: Pointer); begin if not Assigned(APack) then Exit; if FIsTextArch then begin case FRangeType of artWord : WriteAsText(PMBWordArchRecord(APack)); artBoolean : WriteAsText(PMBBoolArchRecord(APack)); end; end else begin case FRangeType of artWord : WriteAsBin(PMBWordArchRecord(APack)); artBoolean : WriteAsBin(PMBBoolArchRecord(APack)); end; end; end; procedure TMBRangeArchThread.WriteCaption; var Tempbyte : Byte; Tempstr : String; begin if FIsTextArch then begin // заголовок текстового файла Tempstr := Format('%d%s%d%s%d%s%d%s%s',[FDevNum, FDelimiter, FRangeStartAddr, FDelimiter, FRangeLen, FDelimiter, Byte(FRangeType), FDelimiter, LineEnding]); FFileStream.Write(Tempstr[1],Length(Tempstr)); FFileStream.Write(FTextCaption[1],Length(FTextCaption)) end else begin // загорловок бинарного файла FFileStream.Write(FDevNum,SizeOf(FDevNum)); // 1 байт FFileStream.Write(FRangeStartAddr,SizeOf(FRangeStartAddr)); // 2 байта FFileStream.write(FRangeLen,SizeOf(FRangeLen)); // 2 байта - количество переменных, а не длинна пакета Tempbyte := Byte(FRangeType); FFileStream.Write(Tempbyte,1); // 1 байт end; FileFlush; end; procedure TMBRangeArchThread.WriteAsText(ARecord: PMBWordArchRecord); var TempRecord : String; begin TempRecord := Format('%s%s%s',[FormatDateTime(DateTimeStrFormat,ARecord^.TimeStamp), FDelimiter, GetWordArrayAsCSVLine(ARecord^.RegsData,FRangeLen,FDelimiter)]); FFileStream.Write(TempRecord[1],Length(TempRecord)); FileFlush; end; procedure TMBRangeArchThread.WriteAsText(ARecord: PMBBoolArchRecord); var TempRecord : String; begin TempRecord := Format('%s%s%s',[FormatDateTime(DateTimeStrFormat,ARecord^.TimeStamp), FDelimiter, GetBoolArrayAsCSVLine(ARecord^.RegsData,FRangeByteLen,FDelimiter)]); FFileStream.Write(TempRecord[1],Length(TempRecord)); FileFlush; end; procedure TMBRangeArchThread.WriteAsBin(ARecord: PMBWordArchRecord); begin FFileStream.Write(ARecord^.TimeStamp,SizeOf(TDateTime)); FFileStream.Write(ARecord^.RegsData^[0],FRangeByteLen); FileFlush; end; procedure TMBRangeArchThread.WriteAsBin(ARecord: PMBBoolArchRecord); begin FFileStream.Write(ARecord^.TimeStamp,SizeOf(TDateTime)); FFileStream.Write(ARecord^.RegsData^[0],FRangeByteLen); FileFlush; end; { TMBRangeArchiver } constructor TMBRangeArchiver.Create(AOwner: TComponent); begin inherited Create(AOwner); FCSection := syncobjs.TCriticalSection.Create; FThread := nil; FQueue := TQueue.Create; FDevNum := 1; FFileName := DefFileName; FIsTextArch := True; FIsOwnIncomPack := True; FMaxFileLen := DefMaxFileSize; {$ifdef UNIX} FPath := DefLinFilePath; {$ELSE} FPath := DefWinFilePath; {$ENDIF} FRangeLen := 0; FRangeStartAddr := 0; FRangeType := artWord; FTextCaption := ''; FDelimiter := DefColDelimiter; end; destructor TMBRangeArchiver.Destroy; begin Stop; CleanQueue; FreeAndNil(FQueue); FreeAndNil(FCSection); inherited Destroy; end; function TMBRangeArchiver.GenFullFileName : String; var TempExt : String; TempLen : Integer; begin Lock; try if FIsTextArch then TempExt := DefTxtArchExt else TempExt := DefBinArchExt; TempLen := Pos(PathDelim,FPath); if TempLen <> Length(FPath) then FPath := FPath + PathDelim; Result := Format('%s%s-%d-%d-%d-%s.%s',[FPath, FFileName, FDevNum, FRangeStartAddr, FRangeLen, FormatDateTime('yyyymmddhhnnsszzz',Now), TempExt]); finally Unlock; end; end; function TMBRangeArchiver.GenTextCaption: String; var TemStart : Word; TempLen : Word; TempDelimiter : String; i : integer; begin Result := ''; Lock; try TempLen := FRangeLen + 1; //тамстампа TemStart := FRangeStartAddr; TempDelimiter := FDelimiter; finally Unlock; end; for i := 0 to TempLen-1 do begin if i = 0 then Result := Format('%s%s',[rsArchTimeCaption,TempDelimiter]) else Result := Format('%sReg%d%s',[Result,i + TemStart - 1,TempDelimiter]); end; end; procedure TMBRangeArchiver.CleanQueue; var TempRec : PMBWordArchRecord; begin Lock; try while FQueue.Count <> 0 do begin TempRec := FQueue.Pop; if Assigned(TempRec) then begin if Assigned(TempRec^.RegsData) then Freemem(TempRec^.RegsData); Freemem(TempRec); end; end; finally Unlock; end; end; procedure TMBRangeArchiver.AddRecordToArchive(ATimeStamp: TDateTime; AData: PWordarray); var TempRec : PMBWordArchRecord; begin if not Assigned(AData) then Exit; if (FRangeType <> artWord) and (FIsOwnIncomPack) then begin if Assigned(AData) then Freemem(AData); Exit; end; TempRec := Getmem(SizeOf(TMBWordArchRecord)); if not Assigned(TempRec) then begin if Assigned(AData) then Freemem(AData); Exit; end; TempRec^.TimeStamp := ATimeStamp; TempRec^.RegsData := AData; FQueue.Push(TempRec); end; procedure TMBRangeArchiver.AddRecordToArchive(ATimeStamp: TDateTime; AData: PByteArray); var TempRec : PMBBoolArchRecord; begin if not Assigned(AData) then Exit; if (FRangeType <> artBoolean) and (FIsOwnIncomPack) then begin if Assigned(AData) then Freemem(AData); Exit; end; TempRec := Getmem(SizeOf(TMBBoolArchRecord)); if not Assigned(TempRec) then begin if Assigned(AData) then Freemem(AData); Exit; end; TempRec^.TimeStamp := ATimeStamp; TempRec^.RegsData := AData; FQueue.Push(TempRec); end; function TMBRangeArchiver.Start: Boolean; begin Result := Active; if Result then Exit; FThread := TMBRangeArchThread.Create(Self); FThread.Logger := Logger; FThread.Start; end; procedure TMBRangeArchiver.Stop; begin FThread.Terminate; FThread.WaitFor; FreeAndNil(FThread); end; function TMBRangeArchiver.GetActive: Boolean; begin Result := Assigned(FThread); end; function TMBRangeArchiver.GetDevNum: Byte; begin Lock; try Result := FDevNum; finally Unlock; end; end; function TMBRangeArchiver.GetFileName: String; begin Lock; try Result := FFileName; finally Unlock; end; end; function TMBRangeArchiver.GetIsOwnIncomPack: Boolean; begin Lock; try Result := FIsOwnIncomPack; finally Unlock; end; end; procedure TMBRangeArchiver.SetIsOwnIncomPack(AValue: Boolean); begin if FIsOwnIncomPack = AValue then Exit; Lock; try FIsOwnIncomPack := AValue; finally end; end; function TMBRangeArchiver.GetIsTextArch: Boolean; begin Lock; try Result := FIsTextArch; finally Unlock; end; end; function TMBRangeArchiver.GetMaxFileLen: Cardinal; begin Lock; try Result := FMaxFileLen; finally Unlock; end; end; function TMBRangeArchiver.GetPath: String; begin Lock; try Result := FPath; finally Unlock; end; end; function TMBRangeArchiver.GetQueue: TQueue; begin Lock; try Result := FQueue; finally Unlock; end; end; function TMBRangeArchiver.GetRangeLen: Word; begin Lock; try Result := FRangeLen; finally Unlock; end; end; function TMBRangeArchiver.GetRangeStartAddr: Word; begin Lock; try Result := FRangeStartAddr; finally Unlock; end; end; function TMBRangeArchiver.GetRangeType: TMBArchiverRangeType; begin Lock; try Result := FRangeType; finally Unlock; end; end; function TMBRangeArchiver.GetTextCaption: String; begin Lock; try Result := FTextCaption; finally Unlock; end; end; procedure TMBRangeArchiver.SetDelimiter(AValue: String); begin if FDelimiter = AValue then Exit; Lock; try FDelimiter := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetDevNum(AValue: Byte); begin if FDevNum = AValue then Exit; Lock; try FDevNum := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetFileName(AValue: String); begin if SameText(FFileName,AValue) then Exit; Lock; try FFileName := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetIsTextArch(AValue: Boolean); begin if FIsTextArch = AValue then Exit; Lock; try FIsTextArch := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetMaxFileLen(AValue: Cardinal); begin if FMaxFileLen = AValue then Exit; Lock; try FMaxFileLen := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetPath(AValue: String); begin if FPath = AValue then Exit; Lock; try FPath := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetRangeLen(AValue: Word); begin if FRangeLen = AValue then Exit; Lock; try FRangeLen := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetRangeStartAddr(AValue: Word); begin if FRangeStartAddr = AValue then Exit; Lock; try FRangeStartAddr := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetRangeType(AValue: TMBArchiverRangeType); begin if FRangeType = AValue then Exit; Lock; try FRangeType := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetTextCaption(AValue: String); begin if FTextCaption = AValue then Exit; Lock; try FTextCaption := AValue; finally Unlock; end; end; procedure TMBRangeArchiver.SetLogger(const AValue: IDLogger); begin inherited SetLogger(AValue); if Active then FThread.Logger := AValue; end; procedure TMBRangeArchiver.Lock; begin FCSection.Enter; end; procedure TMBRangeArchiver.Unlock; begin FCSection.Leave; end; end.
unit FacebookSupport; { Copyright (c) 2001-2013, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, EncodeSupport, DateSupport; Function FacebookCheckLogin(id, secret, url, code : String; var token, expires, error : String) : boolean; Function FacebookGetDetails(token : String; var id, name, email, error : String) : boolean; Function GoogleCheckLogin(id, secret, url, code : String; var token, expires, jwt, error : String) : boolean; Function GoogleGetDetails(token, key, jwtsrc : String; var id, name, email, error : String) : boolean; function FitBitInitiate(secret, key, nonce, callback : String) : String; implementation uses InternetFetcher, IdHTTP, IdSSLOpenSSL, hmac, idHMAC, IdHMACSHA1, BytesSupport, AdvMemories, AdvJson, jwt, ParseMap; Function FacebookCheckLogin(id, secret, url, code : String; var token, expires, error : String) : boolean; var fetch : TInternetFetcher; json : TJSONObject; begin result := false; try fetch := TInternetFetcher.create; try fetch.URL := 'https://graph.facebook.com/oauth/access_token?client_id='+id+'&redirect_uri='+url+'&client_secret='+secret+'&code='+code; fetch.Fetch; json := TJSONParser.Parse(fetch.Buffer.AsUnicode); try token := json.str['access_token']; expires := json.str['expires_in']; finally json.free; end; result := true; finally fetch.free; end; except on e:exception do error := e.Message; end; end; Function GoogleCheckLogin(id, secret, url, code : String; var token, expires, jwt, error : String) : boolean; var http: TIdHTTP; ssl : TIdSSLIOHandlerSocketOpenSSL; post, resp : TBytesStream; json : TJSONObject; begin result := false; try post := TBytesStream.create(TEncoding.ASCII.getBytes( 'code='+code+'&'+ 'client_id='+id+'&'+ 'client_secret='+secret+'&'+ 'redirect_uri='+url+'&'+ 'grant_type=authorization_code')); try result := false; http := TIdHTTP.Create(nil); Try ssl := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); Try http.IOHandler := ssl; ssl.SSLOptions.Mode := sslmClient; ssl.SSLOptions.Method := sslvTLSv1_2; http.Request.ContentType := 'application/x-www-form-urlencoded'; resp := TBytesStream.create; try http.Post('https://accounts.google.com/o/oauth2/token', post, resp); resp.position := 0; json := TJSONParser.Parse(resp); try token := json.vStr['access_token']; expires := json.vStr['expires_in']; jwt := json.vStr['id_token']; result := true; finally json.free; end; finally resp.free; end; finally ssl.free; end; finally http.free; end; finally post.free; end; except on e:exception do error := e.Message; end; end; Function FacebookGetDetails(token : String; var id, name, email, error : String) : boolean; var fetch : TInternetFetcher; json : TJSONObject; begin result := false; try fetch := TInternetFetcher.create; try fetch.URL := 'https://graph.facebook.com/me?access_token='+token; fetch.Fetch; json := TJSONParser.Parse(fetch.Buffer.AsBytes); try id := json.vStr['id']; name := json.vStr['name']; email := json.vStr['email']; finally json.free; end; result := true; finally fetch.free; end; except on e:exception do error := e.Message; end; end; Function GoogleGetDetails(token, key, jwtsrc : String; var id, name, email, error : String) : boolean; var fetch : TInternetFetcher; json : TJSONObject; jwt : TJWT; begin result := false; try fetch := TInternetFetcher.create; try fetch.URL := 'https://www.googleapis.com/plus/v1/people/me?access_token='+token+'&key='+key; fetch.Fetch; json := TJSONParser.Parse(fetch.Buffer.AsBytes); try id := json.vStr['id']; name := json.vStr['displayName']; email := json.vStr['email']; finally json.free; end; result := true; finally fetch.free; end; if (jwtsrc <>'') and ((email = '') or (id = '') or (name = '')) then begin jwt := TJWTUtils.unpack(jwtsrc, false, nil); try if (email = '') then email := jwt.email; if (id = '') then id := jwt.subject; if (name = '') then name := jwt.name; finally jwt.Free; end; end; except on e:exception do error := e.Message; end; end; function SecondsSince1970 : integer; begin result := trunc((now - EncodeDate(1970,1,1)) / DATETIME_SECOND_ONE); end; function oAuthSign(secret, s : String) : String; var bs, bsecret : TBytes; begin bs := AnsiStringAsBytes(AnsiString(s)); bsecret := AnsiStringAsBytes(AnsiString(secret)); // result := EncodeMIME(BinToBase64(THMACUtils.HMAC_HexStr(TIdHMACSHA256, bsecret, bs))); end; function FitBitInitiate(secret, key, nonce, callback : String) : String; var ts : String; base : String; header : String; fetch : TInternetFetcher; begin ts := inttostr(SecondsSince1970); try // build the base correctly: base := 'POST&'+ 'http%3A%2F%2Fapi.fitbit.com%2Foauth%2Frequest_token&'+ 'oauth_callback%3D'+EncodeMIME(callback)+'%26'+ 'oauth_consumer_key%3D'+key+'%26'+ 'oauth_nonce%3D'+nonce+'%26'+ 'oauth_signature_method%3DHMAC-SHA1%26'+ 'oauth_timestamp%3D'+ts+'%26'+ 'oauth_version%3D1.0'; header := 'OAuth oauth_consumer_key="'+key+'", '+ 'oauth_signature_method="HMAC-SHA1", '+ 'oauth_timestamp="'+ts+'", '+ 'oauth_nonce="'+nonce+'", '+ 'oauth_callback="'+EncodeMIME(callback)+'", '+ 'oauth_signature="'+oAuthSign(secret, base)+'"'+ 'oauth_version="1.0"'; fetch := TInternetFetcher.create; try fetch.Method := imfPost; fetch.URL := 'https://https://www.fitbit.com/oauth/request_token'; fetch.Fetch; // parsemap := TParseMap.createSmart(fetch.Buffer.AsUnicode); // try // token := parsemap.GetVar('access_token'); // expires := parsemap.GetVar('expires'); // finally // parsemap.free; // end; // result := true; finally fetch.free; end; except on e : Exception do result := '<p>Error: '+e.message+'</p>'; end; end; end.
{$include kode.inc} unit kode_plugin; { idea: FProcValuesDirty and FEditorValuesDirty could be bitfields instead.. for example, each bit could indicate 8 parameters, so that we only have to check and update 8 params for each bit set.. problem: concurrency when we update the bitfields.. read/modify/write.. } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses {$ifdef KODE_EXE} kode_plugin_exe, {$endif} {$ifdef KODE_VST} kode_plugin_vst, {$endif} kode_parameter, kode_program, kode_queue; const KODE_MAX_QUEUE_SIZE = 1024; type KPlugin = class(KPlugin_Implementation) private FParamValues : array[0..KODE_MAX_PARAMETERS-1] of Single; FProcValues : array[0..KODE_MAX_PARAMETERS-1] of Single; FEditorValues : array[0..KODE_MAX_PARAMETERS-1] of Single; FProcValuesDirty : Boolean; FEditorValuesDirty : Boolean; FProcessQueue : KIntQueue; FEditorQueue : KIntQueue; public constructor create; destructor destroy; override; public { parameters } function appendParameter(AParameter:KParameter) : LongInt; override; procedure deleteParameters; override; function getNumParameters : LongInt; override; function getParameter(AIndex:LongInt) : KParameter; override; function getParameterValue(AIndex:LongInt) : Single; override; procedure setParameterValue(AIndex:LongInt; AValue:Single); override; procedure setDefaultParameters; override; procedure propagateParameters; override; procedure updateParametersInProcess; override; { programs } function appendProgram(AProgram:KProgram) : LongInt; override; procedure deletePrograms; override; function getProgram(AIndex:LongInt) : KProgram; override; //procedure setupPrograms; override; function createDefaultProgram : KProgram; override; procedure saveProgram(AIndex:LongInt); override; procedure loadProgram(AIndex:LongInt); override; { editor } {$ifdef KODE_GUI} procedure updateParameterFromEditor(AParameter:KParameter; AValue:Single); override; procedure updateEditorInIdle; override; {$endif} end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses kode_const, kode_debug, kode_memory; //-------------------------------------------------- // //-------------------------------------------------- constructor KPlugin.create; var size : LongWord; begin inherited; size := KODE_MAX_PARAMETERS * sizeof(Single); KMemset(@FParamValues,0,size); KMemset(@FProcValues,0,size); KMemset(@FEditorValues,0,size); FProcValuesDirty := False; FEditorValuesDirty := False; FProcessQueue := KIntQueue.create(KODE_MAX_QUEUE_SIZE); FEditorQueue := KIntQueue.create(KODE_MAX_QUEUE_SIZE); end; //---------- destructor KPlugin.destroy; begin FProcessQueue.destroy; FEditorQueue.destroy; inherited; end; //-------------------------------------------------- // parameters //-------------------------------------------------- function KPlugin.appendParameter(AParameter:KParameter) : LongInt; var index : longword; begin index := FParameters._size; AParameter.setIndex(index); FParameters.append(AParameter); result := index; end; //---------- procedure KPlugin.deleteParameters; var i : longword; begin if FParameters._size > 0 then begin for i := 0 to FParameters._size-1 do begin FParameters[i].destroy; end; end; end; //---------- function KPlugin.getNumParameters : LongInt; begin result := FParameters._size; end; //---------- function KPlugin.getParameter(AIndex:LongInt) : KParameter; begin result := FParameters[AIndex]; end; //---------- function KPlugin.getParameterValue(AIndex:LongInt) : Single; begin result := FParamValues[AIndex]; end; //---------- procedure KPlugin.setParameterValue(AIndex:LongInt; AValue:Single); begin FParamValues[AIndex] := AValue; //FProcValuesDirty := True; //FEditorValuesDirty := True; FProcessQueue.write(AIndex); FEditorQueue.write(AIndex); end; //---------- { set FParamValues to default values (from FParameter), and set FProcValues & FEditorValues different from this, so that they will be seen as different, and action taken in - KPlugin.updateEditorInIdle - KPlugin.updateParametersInProcess called from: - KPlugin_Vst.main - KPlugin_Exe.main } procedure KPlugin.setDefaultParameters; var i : LongWord; v : Single; begin if FParameters._size > 0 then begin for i := 0 to FParameters._size-1 do begin v := FParameters[i].getDefault; FParamValues[i] := v; // FParameters[i].to01(v); FProcValues[i] := v + 1; // force on_parameterChange FEditorValues[i] := v + 1; // force redraw //FProcessQueue.write(i); //FEditorQueue.write(i); end; FProcValuesDirty := True; FEditorValuesDirty := True; end; end; //---------- { propagate/spread parameter values from plugin (FParamValues) to audio process (FProcValues) and editor (FEditorValues) set FProcValues & FEditorValues different from FParamValues, so that they will be seen as different, and action taken in: - KPlugin.updateEditorInIdle - KPlugin.updateParametersInProcess called from: KPlugin_Vst.vst_dispatcher/effEditOpen } procedure KPlugin.propagateParameters; var i : LongWord; v : Single; begin if FParameters._size > 0 then begin for i := 0 to FParameters._size-1 do begin v := FParamValues[i]; FProcValues[i] := v + 1; // force on_ParameterChange FEditorValues[i] := v + 1; // force redraw //FProcessQueue.write(i); //FEditorQueue.write(i); end; FProcValuesDirty := True; FEditorValuesDirty := True; end; end; //---------- { called from: - KPlugin_Vst.vst_process - [KPlugin_Vst.vst_processdouble] ----- if dirty flag is set, we compare, and potentially update all values. and then clear the queue, since we will check all anyway.. if dirty flag is not set, we read items from the queue until it is empty, and update only those values.. } procedure KPlugin.updateParametersInProcess; var v : single; i : longint{word}; //p : longint; begin { if dirty flag is set, we compare and ventually update all parameters.. } if FProcValuesDirty then begin { we are going to check all parameters, also those eventually in the que, so we just clear it.. } FProcessQueue.clear; { if items are pushed onto the queue after this, they will be handled next round.. } FProcValuesDirty := False; { if flag is set to true after this (from another thread?), we will do this again next round.. } if FParameters._size > 0 then begin for i := 0 to FParameters._size-1 do begin v := FParamValues[i]; if v <> FProcValues[i] then begin FProcValues[i] := v; on_parameterChange(i, FParameters[i].from01(v)); end; end; end; end else { else we pop items off the eventqueue, and check only these.. consider: make sure queue and process() calls are 'n sync' reaper just stops calling process when pause is on, but doesn't let us know via any other call, so, if you tweak a knob in pause mode, the queue fills up.. maybe: if we can't write item to queue, set dirty flag, and clear the queue.. } begin while FProcessQueue.read(i) do begin v := FParamValues[i]; if v <> FProcValues[i] then begin FProcValues[i] := v; on_parameterChange(i, FParameters[i].from01(v)); end; end; end; end; //-------------------------------------------------- // programs //-------------------------------------------------- function KPlugin.appendProgram(AProgram:KProgram) : LongInt; var index : longword; begin index := FPrograms._size; AProgram.setIndex(index); FPrograms.append(AProgram); result := index; end; //---------- procedure KPlugin.deletePrograms; var i : longword; begin if FPrograms._size > 0 then begin for i := 0 to FPrograms._size-1 do begin FPrograms[i].destroy; end; end; end; //---------- function KPlugin.getProgram(AIndex:LongInt) : KProgram; begin result := FPrograms[AIndex]; end; //---------- function KPlugin.createDefaultProgram : KProgram; var i : longint; num : longint; prog : KProgram; v : single; begin num := FParameters._size; if num > 0 then begin //prog := KProgram.create('default',0,nil); prog := KProgram.create('default'); for i := 0 to num-1 do begin v := FParameters[i].getDefault; prog.setValue(i,v); end; result := prog; end else result := nil; end; //---------- procedure KPlugin.saveProgram(AIndex:LongInt); var i : longint; num : longint; prog : KProgram; v : single; begin if FPrograms._size > 0 then begin num := FParameters._size; prog := FPrograms[aIndex]; for i := 0 to num-1 do begin v := FParamValues[i]; prog.setValue(i,v); end; end; end; //---------- procedure KPlugin.loadProgram(AIndex:LongInt); var i : longint; num : longint; prog : KProgram; v : single; begin //if FPrograms._size > 0 then if AIndex < FPrograms._size then begin num := FParameters._size; prog := FPrograms[AIndex]; for i := 0 to num-1 do begin v := prog.getValue(i); FParamValues[i] := v; end; FProcValuesDirty := True; FEditorValuesDirty := True; end; end; //-------------------------------------------------- // editor //-------------------------------------------------- { called from: - KEditor.do_update hmmm.. we change the FParamValues.. next time we're in editor-idle, if this value is different from editor value, the widget is updated.. again.. so, we also set the FEditorValue to avoid redrawing it.. we already did that during the widget tweaking (gui thread) } {$ifdef KODE_GUI} procedure KPlugin.updateParameterFromEditor(AParameter:KParameter; AValue:Single); var index : longint; begin index := AParameter._index; FParamValues[index] := AValue; FEditorValues[index] := AValue; // hack? so we don't redraw it in idle.. //FProcValuesDirty := True; FProcessQueue.write(index); notifyHost(index,AValue); end; {$endif} //---------- { called from: KPlugin_Vst.vst_dispatcher/effEditIdle } {$ifdef KODE_GUI} procedure KPlugin.updateEditorInIdle; var v : single; i : longint{word}; p : KParameter; begin //KTrace('KPlugin.updateEditorInIdle'); if FEditorValuesDirty then begin FEditorQueue.clear; FEditorValuesDirty := False; if FParameters._size > 0 then begin for i := 0 to FParameters._size-1 do begin v := FParamValues[i]; if v <> FEditorValues[i] then begin FEditorValues[i] := v; p := FParameters[i]; FEditor.updateParameterFromHost(p,v); end; end; end; end else begin while FEditorQueue.read(i) do begin v := FParamValues[i]; if v <> FEditorValues[i] then begin FEditorValues[i] := v; p := FParameters[i]; FEditor.updateParameterFromHost(p,v); end; end; end; //KTrace('KPlugin.updateEditorInIdle OK'); end; {$endif} //---------------------------------------------------------------------- end.
unit unitAddRecords; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, DBCtrls; type TfrmAddRecords = class(TForm) pnlMain: TPanel; PageControlMain: TPageControl; tabComponents: TTabSheet; TabTypes: TTabSheet; TabElements: TTabSheet; TabInfo: TTabSheet; pnlComponents: TPanel; lNameComponent: TLabel; editComponentName: TEdit; btnAddComponent: TBitBtn; pnlTypes: TPanel; Label12: TLabel; Label11: TLabel; edtTypeName: TEdit; CBType_Comp: TDBLookupComboBox; btnAddType: TBitBtn; pnlElements: TPanel; btnAddElem: TBitBtn; pnlInfo: TPanel; gbArrivalCharge: TGroupBox; lArrival: TLabel; lCharge: TLabel; Label7: TLabel; ECharge: TEdit; EArrival: TEdit; ECost_For_One: TEdit; lFrom_Whom: TLabel; EFrom_Whom: TEdit; lDate: TLabel; EDate: TEdit; lNum_doc: TLabel; ENum_doc: TEdit; btnAddInfo: TBitBtn; MemInfo: TMemo; Label2: TLabel; gbElem: TGroupBox; cbElem: TDBLookupComboBox; rbName: TRadioButton; rbNUMER: TRadioButton; btnClose: TBitBtn; sbSrez: TSpeedButton; gbElemNew: TGroupBox; EName: TEdit; lNameElem: TLabel; lUnitElem: TLabel; EUnit: TEdit; Enumer: TEdit; lNumer: TLabel; lTypeElem: TLabel; CBElem_type_name: TDBLookupComboBox; GroupBox1: TGroupBox; Label1: TLabel; btnAddLink: TBitBtn; ELink: TEdit; memLinkInfo: TMemo; procedure btnAddComponentClick(Sender: TObject); procedure btnAddTypeClick(Sender: TObject); procedure btnAddElemClick(Sender: TObject); procedure btnAddInfoClick(Sender: TObject); procedure EArrivalExit(Sender: TObject); procedure EChargeExit(Sender: TObject); procedure ECost_For_OneExit(Sender: TObject); procedure EDateExit(Sender: TObject); procedure FormCreate(Sender: TObject); procedure rbNUMERClick(Sender: TObject); procedure rbNameClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure sbSrezClick(Sender: TObject); procedure CBType_CompClick(Sender: TObject); procedure CBElem_type_nameClick(Sender: TObject); procedure cbElemClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure TabInfoShow(Sender: TObject); procedure TabTypesShow(Sender: TObject); procedure TabElementsShow(Sender: TObject); procedure pnlInfoClick(Sender: TObject); procedure pnlTypesClick(Sender: TObject); procedure btnAddLinkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmAddRecords: TfrmAddRecords; implementation uses dmo,unAdd, main; {$R *.dfm} procedure TfrmAddRecords.btnAddComponentClick(Sender: TObject); var tmpStr:string; begin if editComponentName.Text <>'' then with dm do begin try try pnlComponents.Cursor:=crHourGlass; btnAddComponent.Enabled:=false; tmpStr:=qryWork.SQL.Text; qryWork.SQL.clear; qryWork.SQL.Text:='execute procedure add_component('''+editComponentName.Text+''','''+main._login+''')'; qryWork.Open; qryWork.SQL.Text:= tmpStr; editComponentName.SetFocus; showmessage('Операция выполнена успешно'); finally pnlCOmponents.Cursor:=crDefault; btnAddComponent.Enabled:=true; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; end; procedure TfrmAddRecords.btnAddTypeClick(Sender: TObject); var tmpStr:string; begin if (edtTypeName.text <> '') then with dm do begin if (cbType_comp.Text ='') then begin messageDlg('Необходимо заполнить поле "комплектующее"...',mtError,[MbOk],0); exit; end; try try pnlTypes.Cursor:=crHourGlass; btnAddType.Enabled:=false; tmpStr:=qryWork.SQL.Text; qryWork.SQL.Text:='execute procedure add_type('''+edtTypeName.text+''','''+cbType_comp.Text+''','''+main._login+''')'; qryWork.Open; refresh; qryWork.SQL.Text:=tmpStr; edtTypeName.SetFocus; showmessage('Операция выполнена успешно'); finally pnlTypes.Cursor:=crDefault; btnAddType.Enabled:=true; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; end; procedure TfrmAddRecords.btnAddElemClick(Sender: TObject); var tmpStr:string; //cost,presence:string; begin if (EName.text <> '') then with dm do begin if (cbElem_Type_name.Text ='') then begin messageDlg('Необходимо заполнить поле "Тип"...',mtError,[MbOk],0); exit; end; try try pnlElements.Cursor:=crHourGlass; btnAddElem.Enabled:=false; tmpStr:=qryWork.SQL.Text; { if EPresence.text<>'' then presence:=EPresence.Text else presence:='null'; if ECost.text<>'' then cost:=ECost.Text else cost:='null';} qryWork.SQL.Text:='execute procedure add_element('''+EName.text+''','''+EUnit.text+''','+intToStr(CbElem_Type_name.KeyValue)+','''+eNumer.Text+''','''+memInfo.Text+''','''+main._login+''')'; qryWork.Open; refresh; qryWork.SQL.Text:=tmpStr; ename.SetFocus; showmessage('Операция выполнена успешно'); finally pnlElements.Cursor:=crDefault; btnAddElem.Enabled:=true; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; end; procedure TfrmAddRecords.btnAddInfoClick(Sender: TObject); var tmpstr:string; arrival,charge,cost:string; begin if (cbElem.Text ='') then begin messageDlg('Необходимо заполнить поле "Элемент"...',mtInformation,[MbOk],0); exit; end; if messageDlg('Вы уверены, что желаете добавить запись со значениями: '+#13#10+ 'Элемент: '+cbelem.Text+#13#10+ 'Приход: '+earrival.Text+#13#10+ 'Расход: '+echarge.Text+#13#10+ 'Цена за единицу: '+ecost_for_one.Text+#13#10+ 'От кого: '+efrom_whom.Text+#13#10+ 'Дата: '+edate.Text+#13#10+ '№ документа: '+enum_doc.Text,mtconfirmation,[mbyes,mbNo],0)=mrNo then exit; with dm do begin try try pnlInfo.Cursor:=crHourGlass; btnAddInfo.Enabled:=false; tmpStr:=qryWork.SQL.Text; if EArrival.Text <> '' then arrival :=EArrival.Text else arrival:='0'; if ECharge.Text <> '' then charge :=Echarge.Text else charge:='0'; if ECost_for_one.Text <> '' then cost :=Ecost_for_one.Text else cost:='0'; qryWork.SQL.Text:='execute procedure add_info('''+Edate.text+''','''+Enum_doc.text+''','''+(EFrom_Whom.text)+''','+cost+','+Arrival+','+Charge+','+intToStr(cbElem.KeyValue)+','''+main._login+''')'; qryWork.Open; cbElem.SetFocus; qryWork.SQL.Text:=tmpStr; showmessage('Операция выполнена успешно'); finally pnlInfo.Cursor:=crDefault; btnAddInfo.Enabled:=true; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; end; procedure TfrmAddRecords.EArrivalExit(Sender: TObject); const c: set of char = ['0'..'9','.',',']; var i:integer; countKoma: boolean; s,s2:string; begin CountKoma:=true; for i:=1 to length(Earrival.Text) do begin if (Earrival.Text[i] in c) then begin if (Earrival.Text[i] =',') then begin if countKoma then S2:='.' else s2:=''; countKoma:=false; end else s2:=Earrival.Text[i]; if s2='.' then countKoma:=false; s:=s+s2; end; end; earrival.Text:=s; end; procedure TfrmAddRecords.EChargeExit(Sender: TObject); const c: set of char = ['0'..'9','.',',']; var i:integer; countKoma: boolean; s,s2:string; begin CountKoma:=true; for i:=1 to length(Echarge.Text) do begin if (Echarge.Text[i] in c) then begin if (Echarge.Text[i] =',') then begin if countKoma then S2:='.' else s2:=''; countKoma:=false; end else s2:=Echarge.Text[i]; if s2='.' then countKoma:=false; s:=s+s2; end; end; echarge.Text:=s; end; procedure TfrmAddRecords.ECost_For_OneExit(Sender: TObject); const c: set of char = ['0'..'9','.',',']; var i:integer; countKoma: boolean; s,s2:string; begin CountKoma:=true; for i:=1 to length(Ecost_for_one.Text) do begin if (Ecost_for_one.Text[i] in c) then begin if (Ecost_for_one.Text[i] =',') then begin if countKoma then S2:='.' else s2:=''; countKoma:=false; end else s2:=Ecost_for_one.Text[i]; if s2='.' then countKoma:=false; s:=s+s2; end; end; ecost_for_one.Text:=s; end; procedure TfrmAddRecords.EDateExit(Sender: TObject); const c: set of char = ['0'..'9','.',',']; var i:integer; //countKoma: boolean; s,s2:string; begin // CountKoma:=true; for i:=1 to length(Edate.Text) do begin if (Edate.Text[i] in c) then begin if (Edate.Text[i] =',') then begin {if countKoma then} S2:='.'; //else s2:=''; // countKoma:=false; end else s2:=Edate.Text[i]; // if s2='.' then countKoma:=false; s:=s+s2; end; end; edate.Text:=s; end; procedure TfrmAddRecords.FormCreate(Sender: TObject); begin EDate.Text:=dateTostr(date); end; procedure TfrmAddRecords.rbNUMERClick(Sender: TObject); begin if rbNumer.Checked then cbElem.ListField:='NUMER'; end; procedure TfrmAddRecords.rbNameClick(Sender: TObject); begin if rbName.Checked then cbElem.ListField:='NAME'; end; procedure TfrmAddRecords.btnCloseClick(Sender: TObject); begin frmAddRecords.Close; end; procedure TfrmAddRecords.sbSrezClick(Sender: TObject); begin try try if cbElem.Text = '' then showmessage('Заполните поле "Элемент"') else with dm do begin if messageDlg('Вы уверены? Выполнить срез остатков елемента '''+cbElem.text+''' ?',mtConfirmation,[mbYes,MbNo],0)=mrYes then begin qryWork.SQL.Text:='execute procedure add_srez('+intToStr(cbElem.keyValue)+','''+DateToStr(date)+''','''+main._login+''')'; qryWork.Open; showmessage('Срез на '+#13#10+'Дата: '+dateToStr(date)+#13#10+'Время: '+timeToStr(time)+#13#10+'Выполнен'); end; end; finally end; except on E:Exception do showmessage(e.Message); end; end; procedure TfrmAddRecords.CBType_CompClick(Sender: TObject); begin if not dm.tblComponents.Active then dm.tblComponents.Active:=true; end; procedure TfrmAddRecords.CBElem_type_nameClick(Sender: TObject); begin if not dm.tblTypes.Active then dm.tblTypes.Active:=true; end; procedure TfrmAddRecords.cbElemClick(Sender: TObject); begin if not dm.tblElements.Active then dm.tblElements.Active:=true; end; procedure TfrmAddRecords.FormActivate(Sender: TObject); begin frmManeger.btnAllConnect.click; end; procedure TfrmAddRecords.TabInfoShow(Sender: TObject); begin try try pnlinfo.Cursor:=crHourGlass; // cbelem.Refresh; if dm.tblComponents.Active then dm.tblelements.Refresh; finally pnlInfo.Cursor:=crDefault; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; procedure TfrmAddRecords.TabTypesShow(Sender: TObject); begin // CBType_Comp.Refresh; try try pnlTypes.Cursor:=crHourGlass; dm.tblComponents.Refresh; finally pnlTypes.Cursor:=crDefault; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; procedure TfrmAddRecords.TabElementsShow(Sender: TObject); begin try try pnlElements.Cursor:=crHourGlass; // CBElem_type_name.Refresh; IF dm.tblTypes.Active then dm.tbltypes.Refresh; finally pnlElements.Cursor:=crDefault; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; procedure TfrmAddRecords.pnlInfoClick(Sender: TObject); begin {dm.tblElements.Locate('name','loki',[]); showmessage('s');} end; procedure TfrmAddRecords.pnlTypesClick(Sender: TObject); begin // CBType_Comp.Refresh; end; procedure TfrmAddRecords.btnAddLinkClick(Sender: TObject); begin with dm do begin if (cbElem.Text ='') then begin messageDlg('Необходимо выбрать элемент...',mtError,[MbOk],0); exit; end; try try pnlInfo.Cursor:=crHourGlass; btnAddLink.Enabled:=false; qryWork.SQL.Text:='execute procedure add_link('+intToStr(cbElem.KeyValue)+','''+Elink.text+''','''+memLinkInfo.Text+''','''+main._login+''')'; qryWork.Open; // refresh; cbElem.SetFocus; { qryLinkInfo_by_link.Close; qryLinkInfo_by_link.Open;} showmessage('Операция выполнена успешно! Ссылка была добавлена.'); finally pnlInfo.Cursor:=crDefault; btnAddLink.Enabled:=true; Elink.SetFocus; end; except on E:Exception do messageDLG(E.Message,mtError,[mbOk],0); end; end; end; end.
unit uUsuario; interface type TUsuario = class private FDataNascimento: TDateTime; FTipoAposentadoria: Char; FSalario: Currency; FSexo: Char; procedure SetDataNascimento(const Value: TDateTime); procedure SetSalario(const Value: Currency); procedure SetSexo(const Value: Char); procedure SetTipoAposentadoria(const Value: Char); { private declarations } protected { protected declarations } public property Salario: Currency read FSalario write SetSalario; property DataNascimento: TDateTime read FDataNascimento write SetDataNascimento; property Sexo: Char read FSexo write SetSexo; property TipoAposentadoria: Char read FTipoAposentadoria write SetTipoAposentadoria; constructor Create(ASalario: Currency; ADataNascimento: TDateTime; ASexo: Char; ATipoAposentadoria: Char); overload; published { published declarations } end; implementation { TUsuario } constructor TUsuario.Create(ASalario: Currency; ADataNascimento: TDateTime; ASexo, ATipoAposentadoria: Char); begin Salario := ASalario; DataNascimento := ADataNascimento; Sexo := ASexo; TipoAposentadoria := ATipoAposentadoria; end; procedure TUsuario.SetDataNascimento(const Value: TDateTime); begin FDataNascimento := Value; end; procedure TUsuario.SetSalario(const Value: Currency); begin FSalario := Value; end; procedure TUsuario.SetSexo(const Value: Char); begin FSexo := Value; end; procedure TUsuario.SetTipoAposentadoria(const Value: Char); begin FTipoAposentadoria := Value; end; end.
unit aOPCTCPSource_V30; interface uses Classes, SysUtils, System.Character, // uDCLang, uDataTypes, aOPCSource, uDCObjects, uUserMessage, aCustomOPCSource, aCustomOPCTCPSource; const cPV30_BlockSize = 64*1024; type TaOPCTCPSource_V30 = class(TaCustomOPCTCPSource) private FEncrypt: Boolean; FServerSettingsIsLoaded: Boolean; procedure UpdateEncrypted(aLock: Boolean); procedure UpdateComressionLevel(aLock: Boolean); procedure UpdateLanguage(aLock: Boolean); procedure SetConnectionParams; procedure GetServerSettings; function GenerateCryptKey(aCharCount: Integer): RawByteString; protected function GetOpcFS: TFormatSettings; override; function GetEncrypt: boolean; override; procedure SetEncrypt(const Value: Boolean); override; procedure SetLanguage(const Value: string); override; procedure TryConnect; override; procedure Authorize(aUser: string; aPassword: string); override; procedure SetCompressionLevel(const Value: integer); override; procedure DoCommand(aCommand: string); procedure DoCommandFmt(aCommand: string; const Args: array of TVarRec); procedure CheckCommandResult; procedure LockAndConnect; procedure LockAndDoCommand(aCommand: string); procedure LockAndDoCommandFmt(aCommand: string; const Args: array of TVarRec); function LockDoCommandReadLn(aCommand: string): string; function LockDoCommandReadLnFmt(aCommand: string; const Args: array of TVarRec): string; function LockAndGetStringsCommand(aCommand: string): string; function LockAndGetResultCommandFmt(aCommand: string; const Args: array of TVarRec): string; function ExtractValue(var aValues: string; var aValue: string; var aErrorCode: integer; var aErrorStr: string; var aMoment: TDateTime): Boolean; override; public constructor Create(aOwner: TComponent); override; function GetUsers: string; override; function Login(const aUserName, aPassword: string): Boolean; override; function GetUserPermission(const aUser, aPassword, aObject: String): String; override; function GetClientList: string; override; function GetThreadList: string; override; function GetDataFileList(const aPath: string; const aMask: string = ''): string; procedure GetDataFile(aStream: TStream; const aFileName: string; aStartPos: Integer); procedure GetDataFiles(aStream: TStream; aFiles: TStrings); function GetFileList(const aPath: string; const aMask: string = '*.*'; aRecursive: Boolean = False): string; procedure DownloadFile(aStream: TStream; const aFileName: string); function GetThreadProp(aThreadName: string): string; override; function SetThreadState(ConnectionName: string; aNewState: boolean): string; override; function SetThreadLock(ConnectionName: string; aLockState: boolean): string; override; function SendModBusEx(aConnectionName: string; aRequest: string; aRetByteCount: integer; aTimeOut: integer): string; override; function LoadLookup(aName: string; var aTimeStamp: TDateTime): string; override; function GetNameSpace(aObjectID: string = ''; aLevelCount: Integer = 0): Boolean; override; procedure FillNameSpaceStrings(aNameSpace: TStrings; aRootID: string = ''; aLevelCount: Integer = 0; aKinds: TDCObjectKindSet = []); override; procedure ChangePassword(aUser, aOldPassword, aNewPassword: string); override; procedure GetFile(aFileName: string; aStream: TStream); override; procedure UploadFile(aFileName: string; aDestDir: string = ''); override; //function GetSensorProperties(id: string): TSensorProperties; override; function GetSensorPropertiesEx(id: string): string; override; function SetSensorPropertiesEx(id: string; sl: TStrings): string; override; function GetGroupProperties(id: string): string; override; function SetGroupProperties(id: string; sl: TStrings): string; override; function GetDeviceProperties(id: string): string; override; function SetDeviceProperties(id: string; sl: TStrings): string; override; procedure FillHistory(aStream: TStream; SensorID: string; Date1: TDateTime; Date2: TDateTime = 0; aDataKindSet: TDataKindSet = [dkValue]; aCalcLeftVal: Boolean = True; aCalcRightVal: Boolean = True); override; procedure FillHistoryCSV(aStrings: TStrings; SensorID: string; Date1: TDateTime; Date2: TDateTime = 0; aDataKindSet: TDataKindSet = [dkValue]; aCalcLeftVal: Boolean = True; aCalcRightVal: Boolean = True); procedure FillHistoryTable(aStream: TStream; SensorIDs: string; Date1: TDateTime; Date2: TDateTime = 0; aCalcLeftVal: Boolean = True; aCalcRightVal: Boolean = True); function DelSensorValue(PhysID: string; Moment: TDateTime): string; override; function DelSensorValues(PhysID: string; Date1, Date2: TDateTime): string; override; function RecalcSensor(PhysID: string; Date1, Date2: TDateTime; Script: string): string; override; procedure InsertValues(PhysID: string; aBuffer: TSensorDataArr); override; function GetValue(PhysID: string; aAsText: Boolean = False): string; override; function GetValueText(PhysID: string): string; function SetSensorValue(PhysID, Value: string; Moment: TDateTime = 0): string; override; procedure IncSensorValue(PhysID: string; aIncValue: Double; Moment: TDateTime); override; function GetSensorValue(PhysID: String; var ErrorCode: integer; var ErrorString: String; var Moment: TDateTime): string; override; function GetSensorValueText(PhysID: String; var ErrorCode: integer; var ErrorString: String; var Moment: TDateTime): string; function GetSensorValueOnMoment(PhysID: String; var Moment: TDateTime): string; override; function GetSensorsValueOnMoment(PhysIDs: string; Moment: TDateTime): string; override; function GetPermissions(PhysIDs: string): string; override; function GetSensorsValues(PhysIDs: String): string; override; procedure FillSensorsValuesStream(var aValuesStream: TMemoryStream); override; function GetSensorsReadError: string; override; function CalcVolume(aSensorID: integer; aDate1, aDate2: TDateTime): extended; override; function GetTimes(aSensorID: Integer; aDate1, aDate2: TDateTime): string; override; function GetStatistic(aSensorID: string; aDate1, aDate2: TDateTime): string; override; procedure SendUserMessage(aUserGUID: string; aMessage: string); override; function GetMessage: TUserMessage; override; procedure DisconnectUser(aUserGUID: string); override; procedure DownloadSetup(aFileName: string; aStream: TStream); override; // aProgressNotify: TOPCProgressNotify = nil); procedure UpdateDescription; override; procedure ReloadRoles; function GetAccessToCommand(aCommand: string): string; function GetUserObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable): string; function GetObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable): string; procedure SetObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable; aUserPermitions: string); procedure GetSchedule(aSensorID: string; aStream: TStream); //procedure AddSCSTracker(aParams: function Report(aParams: string): string; function JSONReport(aParam: string): string; published property Encrypt: Boolean read FEncrypt write SetEncrypt default False; property ProtocolVersion default 30; property UpdateMode default umStreamPacket; end; implementation uses Math, SynCrossPlatformJSON, // FGInt, FGIntPrimeGeneration, FGIntRSA, flcStdTypes, flcCipherRSA, IdGlobal, IdException, DateUtils, StrUtils, DC.StrUtils, aOPCLog, aOPCUtils, // uDCLocalizer, uDCStrResource, aOPCConsts; { TaOPCTCPSource_V30 } procedure TaOPCTCPSource_V30.Authorize(aUser, aPassword: string); begin DoCommandFmt('Login %s;%s;1', [aUser, StrToHex(aPassword, '')]); ReadLn; // вычитываем приветствие if OPCLog.AutoFillOnAuthorize then begin OPCLog.LoginName := GetLocalUserName; OPCLog.UserName := aUser; OPCLog.ComputerName := GetComputerName; OPCLog.IPAdress := Connection.Socket.Binding.IP; end; end; function TaOPCTCPSource_V30.CalcVolume(aSensorID: integer; aDate1, aDate2: TDateTime): extended; begin // // перед преобразование даты (DateToServer) необходимо уставновить подключение // LockAndConnect; // // LockAndDoCommandFmt('CalcVolume %d;%s;%s', // [aSensorID, DateTimeToStr(DateToServer(aDate1), OpcFS), DateTimeToStr(DateToServer(aDate2), OpcFS)]); // Result := StrToFloat(ReadLn, OpcFS); Result := 0; LockConnection('CalcVolume'); try try DoConnect; DoCommandFmt('CalcVolume %d;%s;%s', [aSensorID, DateTimeToStr(DateToServer(aDate1), OpcFS), DateTimeToStr(DateToServer(aDate2), OpcFS)]); Result := StrToFloat(ReadLn, OpcFS); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('CalcVolume'); end; end; procedure TaOPCTCPSource_V30.ChangePassword(aUser, aOldPassword, aNewPassword: string); begin LockAndDoCommandFmt('ChangePassword %s;%s;%s;1', [aUser, StrToHex(aOldPassword, ''), StrToHex(aNewPassword, '')]); end; procedure TaOPCTCPSource_V30.CheckCommandResult; var aStatus: string; begin aStatus := ReadLn; if aStatus = sError then raise EOPCTCPCommandException.Create(ReadLn) else if aStatus <> sOk then raise EOPCTCPUnknownAnswerException.Create('Нестандартый ответ на команду'); end; constructor TaOPCTCPSource_V30.Create(aOwner: TComponent); begin inherited Create(aOwner); ProtocolVersion := 30; Connection.Intercept := Intercept; UpdateMode := umStreamPacket; end; function TaOPCTCPSource_V30.DelSensorValue(PhysID: string; Moment: TDateTime): string; begin Result := ''; LockConnection('DelSensorValue'); try try DoConnect; DoCommandFmt('DeleteValue %s;%s', [PhysID, FloatToStr(DateToServer(Moment), OpcFS)]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('DelSensorValue'); end; end; function TaOPCTCPSource_V30.DelSensorValues(PhysID: string; Date1, Date2: TDateTime): string; begin Result := ''; LockConnection('DelSensorValues'); try try DoConnect; DoCommandFmt('DeleteValues %s;%s;%s', [PhysID, FloatToStr(DateToServer(Date1), OpcFS), FloatToStr(DateToServer(Date2), OpcFS)]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('DelSensorValues'); end; end; procedure TaOPCTCPSource_V30.DisconnectUser(aUserGUID: string); begin LockAndDoCommandFmt('DisconnectUser %s', [aUserGUID]); end; procedure TaOPCTCPSource_V30.DoCommand(aCommand: string); begin SendCommand(aCommand); CheckCommandResult; end; procedure TaOPCTCPSource_V30.DoCommandFmt(aCommand: string; const Args: array of TVarRec); begin SendCommandFmt(aCommand, Args); CheckCommandResult; end; procedure TaOPCTCPSource_V30.DownloadFile(aStream: TStream; const aFileName: string); var aSize: integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('DownloadFile'); try DoConnect; DoCommandFmt('DownloadFile %s', [Trim(aFileName)]); aSize := StrToInt(ReadLn); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cPV30_BlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin ReadStream(aStream, aBlockSize); if Assigned(OnProgress) then begin OnProgress(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV30_BlockSize, aSize - aStream.Position); end; finally UnLockConnection('DownloadFile'); end; if aCanceled then begin Disconnect; Reconnect; raise EOPCTCPOperationCanceledException.Create('Выполнение прервано пользователем'); end; end; //begin // Assert(Assigned(aStream), 'Не создан поток'); // // LockConnection('DownloadFile'); // try // try // DoConnect; // // DoCommand(Format('DownloadFile %s', [aFileName])); // ReadStream(aStream); // // aStream.Position := 0; // except // on e: EIdException do // if ProcessTCPException(e) then // raise; // end; // finally // UnLockConnection('DownloadFile'); // end; //end; procedure TaOPCTCPSource_V30.DownloadSetup(aFileName: string; aStream: TStream); var aSize: Integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), uDCStrResource.dcResS_StreamNotCreated); LockConnection('DownloadSetup'); try DoConnect; DoCommandFmt('DownloadSetup %s', [aFileName]); aSize := StrToInt(ReadLn); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cTCPMaxBlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin ReadStream(aStream, aBlockSize); if Assigned(OnProgress) then begin OnProgress(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cTCPMaxBlockSize, aSize - aStream.Position); end; finally UnLockConnection('DownloadSetup'); end; if aCanceled then begin Disconnect; Reconnect; raise EOPCTCPOperationCanceledException.Create(uDCStrResource.dcResS_OperationCanceledByUser); end; end; function TaOPCTCPSource_V30.ExtractValue(var aValues, aValue: string; var aErrorCode: integer; var aErrorStr: string; var aMoment: TDateTime): Boolean; var i, p1: integer; s: string; aState: (sValue, sErrorCode, sErrorStr, sMoment, sEOL); aStrLength: integer; begin // разбираем текст вида: // // Value;ErrorCode;ErrorStr;Moment<EOL> // Value;ErrorCode;ErrorStr;Moment<EOL> // <EOL> // ... // Value;ErrorCode;ErrorStr;Moment<EOL> // // удаляем из испходного текста разобранную строку i := 1; aStrLength := Length(aValues); Assert(aStrLength > 0, 'Получена пустая строка'); Result := aValues[i] <> #13; if Result then begin p1 := 1; aState := sValue; while aState <> sEOL do begin // EOL = CR + LF (#13 + #10) if (i > aStrLength) or aValues[i].IsInArray([';', #13]) then //(CharInSet(aValues[i], [';', #13])) then begin s := Copy(aValues, p1, i - p1); p1 := i + 1; case aState of sValue: // значение aValue := s; sErrorCode: // код ошибки aErrorCode := StrToIntDef(s, 0); sErrorStr: // ошибка aErrorStr := s; sMoment: // момент времени aMoment := StrToDateTimeDef(s, DateToClient(aMoment), OpcFS); end; Inc(aState); end; Inc(i); end; aValues := Copy(aValues, i + 1 {LF}, aStrLength); end else aValues := Copy(aValues, i + 2 {CRLF}, aStrLength); end; procedure TaOPCTCPSource_V30.FillNameSpaceStrings(aNameSpace: TStrings; aRootID: string; aLevelCount: Integer; aKinds: TDCObjectKindSet); var Stream: TMemoryStream; aStreamSize: integer; begin Assert(Assigned(aNameSpace)); aNameSpace.Clear; LockConnection('GetNameSpace'); try try DoConnect; DoCommandFmt('GetNameSpace ObjectID=%s;TimeStamp=%s;LevelCount=%d', [aRootID, '0', aLevelCount]); // читаем дату изменения иерархии ReadLn; // читаем размер данных aStreamSize := StrToInt(ReadLn); if aStreamSize = 0 then Exit; Stream := TMemoryStream.Create; try ReadStream(Stream, aStreamSize, False); Stream.Position := 0; aNameSpace.LoadFromStream(Stream); finally FreeAndNil(Stream); end; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetNameSpace'); end; end; procedure TaOPCTCPSource_V30.FillHistory(aStream: TStream; SensorID: string; Date1, Date2: TDateTime; aDataKindSet: TDataKindSet; aCalcLeftVal, aCalcRightVal: Boolean); begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('FillHistory'); try try DoConnect; DoCommand('GetHistory ' + SensorID + ';' + DateTimeToStr(DateToServer(Date1), OpcFS) + ';' + DateTimeToStr(DateToServer(Date2), OpcFS) + ';' + BoolToStr(dkState in aDataKindSet) + ';' + BoolToStr(dkValue in aDataKindSet) + ';' + BoolToStr(dkUser in aDataKindSet) + ';' + BoolToStr(aCalcLeftVal) + ';' + BoolToStr(aCalcRightVal) ); ReadStream(aStream); // переводим даты в наше смещение HistoryDateToClient(aStream, aDataKindSet); aStream.Position := 0; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('FillHistory'); end; end; procedure TaOPCTCPSource_V30.FillHistoryCSV(aStrings: TStrings; SensorID: string; Date1, Date2: TDateTime; aDataKindSet: TDataKindSet; aCalcLeftVal, aCalcRightVal: Boolean); begin Assert(Assigned(aStrings), 'Не создан результирующий TStrings'); LockConnection('FillHistoryCSV'); try try DoConnect; DoCommand('GetHistoryCSV ' + SensorID + ';' + //DateTimeToStr(DateToServer(Date1), OpcFS) + ';' + //DateTimeToStr(DateToServer(Date2), OpcFS) + ';' + DateTimeToIso8601(DateToServer(Date1)) + ';' + DateTimeToIso8601(DateToServer(Date2)) + ';' + BoolToStr(dkState in aDataKindSet) + ';' + BoolToStr(dkValue in aDataKindSet) + ';' + BoolToStr(dkUser in aDataKindSet) + ';' + BoolToStr(aCalcLeftVal) + ';' + BoolToStr(aCalcRightVal) ); //ReadStream(aStream); Connection.IOHandler.ReadStrings(aStrings); // переводим даты в наше смещение //HistoryDateToClient(aStream, aDataKindSet); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('FillHistory'); end; end; procedure TaOPCTCPSource_V30.FillHistoryTable(aStream: TStream; SensorIDs: string; Date1, Date2: TDateTime; aCalcLeftVal, aCalcRightVal: Boolean); begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('FillHistoryTable'); try try DoConnect; DoCommand('GetHistoryTable ' + SensorIDs + ';' + DateTimeToStr(DateToServer(Date1), OpcFS) + ';' + DateTimeToStr(DateToServer(Date2), OpcFS) + ';' + BoolToStr(aCalcLeftVal) + ';' + BoolToStr(aCalcRightVal) ); ReadStream(aStream); aStream.Position := 0; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('FillHistory'); end; end; procedure TaOPCTCPSource_V30.FillSensorsValuesStream(var aValuesStream: TMemoryStream); var i: integer; PhysID: integer; Stream: TMemoryStream; aByteCount: integer; begin aValuesStream.Clear; //if FPhysIDs = '' then // Exit; LockConnection('FillSensorsValuesStream'); try try DoConnect; if FDataLinkGroupsChanged then begin Stream := TMemoryStream.Create; try for i := 0 to DataLinkGroups.Count - 1 do begin PhysID := StrToIntDef(TOPCDataLinkGroup(DataLinkGroups.Items[i]).PhysID, 0); Stream.Write(PhysID, SizeOf(PhysID)); end; Stream.Position := 0; OpenWriteBuffer; try SendCommandFmt('GetStreamValues %d', [DataLinkGroups.Count]); WriteStream(Stream, True, False); finally CloseWriteBuffer; end; CheckCommandResult; // отметим, что мы передали серверу новые адреса запрашиваемых датчиков FDataLinkGroupsChanged := false; finally Stream.Free; end; end // if FPhysIDsChanged then // DoCommandFmt('GetStreamValues %s', [FPhysIDs]) else DoCommand('GetStreamValues'); aByteCount := StrToInt(ReadLn); ReadStream(aValuesStream, aByteCount); ValuesDateToClient(aValuesStream); aValuesStream.Position := 0; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('FillSensorsValuesStream'); end; end; function TaOPCTCPSource_V30.GenerateCryptKey(aCharCount: Integer): RawByteString; var i: integer; begin Randomize; Result := ''; for i := 1 to aCharCount do Result := Result + ByteChar(Random(256)); end; function TaOPCTCPSource_V30.GetAccessToCommand(aCommand: string): string; begin Result := LockDoCommandReadLnFmt('GetAccessToCommand %s', [aCommand]); end; function TaOPCTCPSource_V30.GetClientList: string; begin Result := LockAndGetStringsCommand('GetClientList'); end; procedure TaOPCTCPSource_V30.GetDataFile(aStream: TStream; const aFileName: string; aStartPos: Integer); begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('GetDataFile'); try try DoConnect; DoCommand(Format('GetDataFile %s;%d', [aFileName, aStartPos])); ReadStream(aStream); aStream.Position := 0; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetDataFile'); end; end; function TaOPCTCPSource_V30.GetDataFileList(const aPath: string; const aMask: string = ''): string; begin if aMask = '' then Result := LockAndGetStringsCommand(Format('GetDataFileList %s', [aPath])) else Result := LockAndGetStringsCommand(Format('GetDataFileList %s;%s', [aPath, aMask])); end; procedure TaOPCTCPSource_V30.GetDataFiles(aStream: TStream; aFiles: TStrings); begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('GetDataFiles'); try try DoConnect; aFiles.LineBreak := ';'; DoCommand(Format('GetDataFiles %s', [aFiles.Text])); ReadStream(aStream); aStream.Position := 0; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetDataFiles'); end; end; function TaOPCTCPSource_V30.GetDeviceProperties(id: string): string; begin Result := LockAndGetStringsCommand(Format('GetDeviceProperties %s', [id])); end; function TaOPCTCPSource_V30.GetEncrypt: boolean; begin Result := FEncrypt; end; procedure TaOPCTCPSource_V30.GetFile(aFileName: string; aStream: TStream); var aSize: integer; aBlockSize: Integer; aCanceled: Boolean; begin Assert(Assigned(aStream), 'Не создан поток'); LockConnection('GetFile'); try DoConnect; DoCommandFmt('GetFile %s', [Trim(aFileName)]); aSize := StrToInt(ReadLn); aCanceled := False; aStream.Position := 0; aBlockSize := Min(cPV30_BlockSize, aSize - aStream.Position); while aStream.Position < aSize do begin ReadStream(aStream, aBlockSize); if Assigned(OnProgress) then begin OnProgress(aStream.Position, aSize, aCanceled); if aCanceled then Break; end; aBlockSize := Min(cPV30_BlockSize, aSize - aStream.Position); end; finally UnLockConnection('GetFile'); end; if aCanceled then begin Disconnect; Reconnect; raise EOPCTCPOperationCanceledException.Create('Выполнение прервано пользователем'); end; end; function TaOPCTCPSource_V30.GetFileList(const aPath, aMask: string; aRecursive: Boolean): string; begin if aRecursive then Result := LockAndGetStringsCommand(Format('GetFileList %s;%s;1', [aPath, aMask])) else Result := LockAndGetStringsCommand(Format('GetFileList %s;%s;0', [aPath, aMask])) end; function TaOPCTCPSource_V30.GetGroupProperties(id: string): string; begin Result := LockAndGetStringsCommand(Format('GetGroupProperties %s', [id])); end; function TaOPCTCPSource_V30.GetMessage: TUserMessage; var aMessageStr: string; aMessageLength: integer; begin Result := nil; // сервера 0 версии не поддерживают обмен сообщениями if ServerVer = 0 then Exit; LockConnection('GetMessage'); try try DoConnect; //OPCLog.WriteToLogFmt('%d: GetMessage DoConnect OK.', [GetCurrentThreadId]); DoCommand('GetMessage'); //OPCLog.WriteToLogFmt('%d: GetMessage DoCommand OK.', [GetCurrentThreadId]); aMessageLength := StrToInt(ReadLn); if aMessageLength = 0 then Exit; aMessageStr := ReadString(aMessageLength); //OPCLog.WriteToLogFmt('%d: GetMessage ReadString OK: %s.', [GetCurrentThreadId, aMessageStr]); Result := TUserMessage.Create(aMessageStr); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetMessage'); end; end; function TaOPCTCPSource_V30.GetNameSpace(aObjectID: string; aLevelCount: Integer): boolean; var Stream: TMemoryStream; dt: TDateTime; dtStr: string; aStreamSize: integer; begin Result := false; LockConnection('GetNameSpace'); try try DoConnect; if (aObjectID <> FNameSpaceParentID) or not (FileExists(GetNameSpaceFileName)) then FNameSpaceTimeStamp := 0; dtStr := FloatToStr(FNameSpaceTimeStamp, OpcFS); DoCommandFmt('GetNameSpace ObjectID=%s;TimeStamp=%s;LevelCount=%d', [aObjectID, dtStr, aLevelCount]); dt := StrToDateTimeDef(ReadLn, 0, OpcFS); aStreamSize := StrToInt(ReadLn); if aStreamSize = 0 then Exit; Stream := TMemoryStream.Create; try ReadStream(Stream, aStreamSize, False); Stream.Position := 0; FNameSpaceCash.LoadFromStream(Stream, TEncoding.ANSI); FNameSpaceTimeStamp := dt; FNameSpaceParentID := aObjectID; Result := true; finally FreeAndNil(Stream); end; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetNameSpace'); end; end; function TaOPCTCPSource_V30.GetObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable): string; begin Result := LockAndGetStringsCommand(Format('GetObjectPermission %d;%d;1', [aObjectID, Ord(aObjectTable)])); end; function TaOPCTCPSource_V30.GetOpcFS: TFormatSettings; begin if not FServerSettingsIsLoaded then DoConnect; Result := inherited GetOpcFS; end; function TaOPCTCPSource_V30.GetPermissions(PhysIDs: string): string; begin Result := LockAndGetStringsCommand('GetPermissions ' + PhysIDs); end; function TaOPCTCPSource_V30.GetThreadList: string; begin Result := LockAndGetStringsCommand('GetThreadList'); end; function TaOPCTCPSource_V30.GetThreadProp(aThreadName: string): string; begin Result := LockAndGetStringsCommand(Format('GetThreadProp %s', [aThreadName])); end; function TaOPCTCPSource_V30.GetTimes(aSensorID: Integer; aDate1, aDate2: TDateTime): string; begin Result := LockAndGetStringsCommand( Format('GetTimes %d;%s;%s', [aSensorID, DateTimeToStr(DateToServer(aDate1), OpcFS), DateTimeToStr(DateToServer(aDate2), OpcFS)])); end; function TaOPCTCPSource_V30.GetUsers: string; begin Result := LockAndGetStringsCommand('GetUsers'); end; function TaOPCTCPSource_V30.GetValue(PhysID: string; aAsText: Boolean = False): string; var aStr: String; aErrorCode: Integer; aErrorString: string; aMoment: TDateTime; begin LockConnection('GetValue'); try try DoConnect; if aAsText then DoCommandFmt('GetValue %s;1', [PhysID]) else DoCommandFmt('GetValue %s', [PhysID]); aStr := ReadLn; ExtractValue(aStr, Result, aErrorCode, aErrorString, aMoment); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetValue'); end; end; function TaOPCTCPSource_V30.GetValueText(PhysID: string): string; var aStr: String; aErrorCode: Integer; aErrorString: string; aMoment: TDateTime; begin LockConnection('GetValue'); try try DoConnect; DoCommandFmt('GetValue %s;1', [PhysID]); aStr := ReadLn; ExtractValue(aStr, Result, aErrorCode, aErrorString, aMoment); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetValue'); end; end; procedure TaOPCTCPSource_V30.IncSensorValue(PhysID: string; aIncValue: Double; Moment: TDateTime); begin LockAndDoCommandFmt('IncValue %s;%s;%s', [PhysID, FloatToStr(aIncValue, DotFS), FloatToStr(DateToServer(Moment), DotFS)]); end; procedure TaOPCTCPSource_V30.InsertValues(PhysID: string; aBuffer: TSensorDataArr); begin LockConnection; try try DoConnect; DoCommandFmt('InsertValues %s;%s', [PhysID, DataArrToString(aBuffer)]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; function TaOPCTCPSource_V30.JSONReport(aParam: string): string; begin Result := LockAndGetResultCommandFmt('JSONReport %s', [aParam]); end; //function TaOPCTCPSource_V30.GetSensorProperties(id: string): TSensorProperties; //var // s: TStrings; //begin // s := TStringList.Create; // try // s.Text := LockAndGetStringsCommand(Format('GetSensorProperties %s', [id])); // // with Result do // begin // Name := s.Values[sSensorName]; // наименование датчика // NameEn := s.Values[sSensorNameEn]; // наименование датчика (латиницей) // FullName := s.Values[sSensorFullName]; // полное наименование датчика // // ThreadName := s.Values[sSensorConnectionName]; // имя потока сбора данных // EquipmentPath := s.Values[sSensorControllerAddr]; // адрес контроллера // Path := s.Values[sSensorAddr]; // адрес датчика (тега,сигнала) // // Id := s.Values[sSensorID]; // идентификатор датчика на сервере // UnitName := s.Values[sSensorUnitName]; // единица измерения // DisplayFormat := s.Values[sSensorDisplayFormat]; // формат представления показаний // // CorrectM := s.Values[sSensorCorrectMul]; // коэффициент умножения // Correct := s.Values[sSensorCorrectAdd]; // константа добавления // // Delta := s.Values[sSensorCompression_DeadSpace]; // мёртвая зона (интервал тишины) // Precision := s.Values[sSensorCompression_Precision]; // точность (знаков после запятой) // UpdateInterval := s.Values[sSensorUpdateInterval]; // интервал обновления // MinReadInterval := s.Values[sSensorMinReadInterval]; // минимальный интервал между чтением показаний // Vn := '0';//s.Values[sSensor]; // номинальная скорость изменения показаний // // RefTableName := s.Values[sSensorRefTableName]; // ссылка на справочник расшифровки значений // RefAutoFill := s.Values[sSensorRefAutoFill]; // режим автоматического заполнения справочника // // UpdateDBInterval := s.Values[sSensorDataBuffer_DataWriter_UpdateDBInterval]; // интервал записи в БД // FuncName := s.Values[sSensorFuncName]; // наименование функции вычисления значения датчика // end; // // finally // s.Free; // end; //end; procedure TaOPCTCPSource_V30.GetSchedule(aSensorID: string; aStream: TStream); var aSize: Int64; begin // Assert(Assigned(aStream), TDCLocalizer.GetStringRes(idxStream_NotCreated)); LockConnection('GetSchedule'); try DoConnect; DoCommandFmt('GetSchedule %s', [aSensorID]); aSize := StrToInt(ReadLn); ReadStream(aStream, aSize); aStream.Position := 0; finally UnLockConnection('GetSchedule'); end; end; function TaOPCTCPSource_V30.GetSensorPropertiesEx(id: string): string; begin Result := LockAndGetStringsCommand(Format('GetSensorProperties %s', [id])); end; function TaOPCTCPSource_V30.GetSensorsReadError: string; begin Result := LockAndGetStringsCommand('GetSensorsReadError'); end; function TaOPCTCPSource_V30.GetSensorsValueOnMoment(PhysIDs: string; Moment: TDateTime): string; var p: integer; Str: string; begin LockConnection; try try DoConnect; DoCommandFmt('GetValuesOnMoment %s;%s', [DateTimeToStr(DateToServer(Moment), OpcFS), PhysIDs]); Result := ReadLn; // значения через ; (точку с запятой) except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; function TaOPCTCPSource_V30.GetSensorsValues(PhysIDs: String): string; begin Result := LockAndGetStringsCommand(Format('GetValues %s', [PhysIDs])); end; function TaOPCTCPSource_V30.GetSensorValue(PhysID: String; var ErrorCode: integer; var ErrorString: String; var Moment: TDateTime): string; var aStr: String; begin LockConnection('GetSensorValue'); try try DoConnect; DoCommandFmt('GetValue %s', [PhysID]); aStr := ReadLn; ExtractValue(aStr, Result, ErrorCode, ErrorString, Moment); Moment := DateToClient(Moment); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetSensorValue'); end; end; function TaOPCTCPSource_V30.GetSensorValueOnMoment(PhysID: String; var Moment: TDateTime): string; begin LockConnection('GetSensorValueOnMoment'); try try DoConnect; DoCommandFmt('GetValueOnMoment %s;%s', [PhysID, DateTimeToStr(DateToServer(Moment), OpcFS)]); Result := ReadLn; // значение ReadLn; // ошибки Moment := DateToClient(StrToDateTime(ReadLn, OpcFS)); // момент времени except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetSensorValueOnMoment'); end; end; function TaOPCTCPSource_V30.GetSensorValueText(PhysID: String; var ErrorCode: integer; var ErrorString: String; var Moment: TDateTime): string; var aStr: String; begin LockConnection('GetSensorValue'); try try DoConnect; DoCommandFmt('GetValue %s;1', [PhysID]); aStr := ReadLn; ExtractValue(aStr, Result, ErrorCode, ErrorString, Moment); Moment := DateToClient(Moment); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetSensorValue'); end; end; procedure TaOPCTCPSource_V30.GetServerSettings; var aCount: Integer; s: TStrings; i: Integer; begin try DoCommand('GetServerSettings'); aCount := StrToInt(ReadLn); s := TStringList.Create; try for i := 1 to aCount do s.Add(ReadLn); with FOpcFS do begin ThousandSeparator := s.Values['ThousandSeparator'][low(string)]; DecimalSeparator := s.Values['DecimalSeparator'][low(string)]; TimeSeparator := s.Values['TimeSeparator'][low(string)]; ListSeparator := s.Values['ListSeparator'][low(string)]; CurrencyString := s.Values['CurrencyString']; ShortDateFormat := s.Values['ShortDateFormat']; LongDateFormat := s.Values['LongDateFormat']; TimeAMString := s.Values['TimeAMString']; TimePMString := s.Values['TimePMString']; ShortTimeFormat := s.Values['ShortTimeFormat']; LongTimeFormat := s.Values['LongTimeFormat']; DateSeparator := s.Values['DateSeparator'][low(string)]; end; FServerSettingsIsLoaded := True; FServerVer := StrToInt(s.Values['ServerVer']); FServerEnableMessage := StrToBool(s.Values['EnableMessage']); FServerSupportingProtocols := s.Values['SupportingProtocols']; FServerOffsetFromUTC := StrToTimeDef(s.Values['OffsetFromUTC'], ClientOffsetFromUTC); finally s.Free; end; except on e: EIdException do if ProcessTCPException(e) then raise; end; end; function TaOPCTCPSource_V30.GetStatistic(aSensorID: string; aDate1, aDate2: TDateTime): string; begin Result := LockAndGetStringsCommand( Format('GetStatistic %s;%s;%s', [aSensorID, DateTimeToStr(DateToServer(aDate1), OpcFS), DateTimeToStr(DateToServer(aDate2), OpcFS)])); end; function TaOPCTCPSource_V30.LoadLookup(aName: string; var aTimeStamp: TDateTime): string; var aByteCount: integer; dtStr: string; dt: TDateTime; begin Result := ''; LockConnection('LoadLookup'); try try DoConnect; DoCommandFmt('GetLookupTimeStamp %s', [aName]); dtStr := ReadLn; dt := StrToDateTimeDef(dtStr, 0, OpcFS); if Abs(dt - aTimeStamp) > 1 / 24 / 60 / 60 then // > 1 секунды begin aTimeStamp := dt; DoCommandFmt('GetLookup %s', [aName]); ReadLn; // количество строк данных aByteCount := StrToInt(ReadLn); // количество байт данных // читаем данные Result := ReadString(aByteCount); end; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LoadLookup'); end; end; procedure TaOPCTCPSource_V30.LockAndConnect; begin LockConnection('LockAndConnect'); try try DoConnect; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LockAndConnect'); end; end; procedure TaOPCTCPSource_V30.LockAndDoCommand(aCommand: string); begin LockConnection('LockAndDoCommand: ' + aCommand); try try DoConnect; DoCommand(aCommand); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LockAndDoCommand: ' + aCommand); end; end; procedure TaOPCTCPSource_V30.LockAndDoCommandFmt(aCommand: string; const Args: array of TVarRec); begin LockAndDoCommand(Format(aCommand, Args)); // LockConnection; // try // try // DoConnect; // DoCommandFmt(aCommand, Args); // except // on e: EIdException do // if ProcessTCPException(e) then // raise; // end; // finally // UnLockConnection; // end; end; function TaOPCTCPSource_V30.LockAndGetResultCommandFmt(aCommand: string; const Args: array of TVarRec): string; begin Result := ''; LockConnection; try try DoConnect; DoCommandFmt(aCommand, Args); //CheckCommandResult; // читаем данные Result := ReadLn; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; function TaOPCTCPSource_V30.LockAndGetStringsCommand(aCommand: string): string; var aByteCount: integer; begin // в протоколе V30 многие команды получают в ответ список строк // строки разделены симовлом EOL = CR+LF // формат ответа на такие команды: // ok<EOL> // <LineCount><EOL> - количество строк // <ByteCount><EOL> - количество байт начиная с первого символа первой строки и заканчивая LF последней // Строка 1<EOL> // Строка 2<EOL> // ... // Строка N<EOL> Result := ''; LockConnection('LockAndGetStringsCommand: ' + aCommand); try try DoConnect; DoCommand(aCommand); ReadLn; // количество строк данных aByteCount := StrToInt(ReadLn); // количество байт данных // читаем данные Result := ReadString(aByteCount); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LockAndGetStringsCommand: ' + aCommand); end; end; function TaOPCTCPSource_V30.LockDoCommandReadLn(aCommand: string): string; begin LockConnection('LockDoCommandReadLn'); try try DoConnect; DoCommand(aCommand); Result := ReadLn; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LockDoCommandReadLn'); end; end; function TaOPCTCPSource_V30.LockDoCommandReadLnFmt(aCommand: string; const Args: array of TVarRec): string; begin LockConnection('LockDoCommandReadLnFmt'); try try DoConnect; DoCommandFmt(aCommand, Args); Result := ReadLn; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('LockDoCommandReadLnFmt'); end; end; function TaOPCTCPSource_V30.Login(const aUserName, aPassword: string): Boolean; begin // Result := GetUserPermission(aUserName, aPassword, '') <> ''; Result := False; LockConnection; try try DoConnect; DoCommandFmt('Login %s;%s;1', [aUserName, StrToHex(aPassword, '')]); ReadLn; Result := True; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; function TaOPCTCPSource_V30.RecalcSensor(PhysID: string; Date1, Date2: TDateTime; Script: string): string; begin Result := ''; LockConnection('RecalcSensor'); try try DoConnect; DoCommandFmt('RecalcSensor %s;%s;%s;%s', [PhysID, FloatToStr(DateToServer(Date1), OpcFS), FloatToStr(DateToServer(Date2), OpcFS), Script]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('RecalcSensor'); end; end; procedure TaOPCTCPSource_V30.ReloadRoles; begin LockAndDoCommand('ReloadRoles'); end; function TaOPCTCPSource_V30.Report(aParams: string): string; begin Result := HexToStr(LockAndGetResultCommandFmt('Report %s', [StrToHex(aParams, '')]), ''); end; function TaOPCTCPSource_V30.GetUserObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable): string; begin LockConnection('GetUserObjectPermission'); try DoConnect; DoCommandFmt('GetUserObjectPermission %d;%d', [aObjectID, Ord(aObjectTable)]); Result := ReadLn; finally UnLockConnection('GetUserObjectPermission'); end; end; function TaOPCTCPSource_V30.GetUserPermission(const aUser, aPassword, aObject: String): String; begin Result := ''; LockConnection('GetUserPermission'); try try DoConnect; DoCommandFmt('GetUserPermission %s;%s;%s;1', [aUser, StrToHex(aPassword, ''), aObject]); Result := ReadLn; Authorize(aUser, aPassword); User := aUser; Password := aPassword; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('GetUserPermission'); end; end; function TaOPCTCPSource_V30.SendModBusEx(aConnectionName, aRequest: string; aRetByteCount, aTimeOut: integer): string; begin Result := ''; LockConnection('SendModBusEx'); try try DoConnect; SendCommandFmt('SendModBus %s;%s;%d;%d', [aConnectionName, aRequest, aRetByteCount, aTimeOut]); Result := ReadLn; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnlockConnection('SendModBusEx'); end; end; procedure TaOPCTCPSource_V30.SendUserMessage(aUserGUID, aMessage: string); begin // сервера 0 версии не поддерживают обмен сообщениями if ServerVer = 0 then Exit; LockConnection('SendUserMessage'); try DoConnect; DoCommandFmt('SendMessage %s;%s', [aUserGUID, StrToHex(aMessage, '')]); finally UnLockConnection('SendUserMessage'); end; end; procedure TaOPCTCPSource_V30.SetCompressionLevel(const Value: integer); begin if CompressionLevel = Value then exit; inherited SetCompressionLevel(Value); UpdateComressionLevel(Active); end; procedure TaOPCTCPSource_V30.SetConnectionParams; const cStringEncoding = ''; //'UTF8'; { TODO : проверить, почему не работает передача списка пользователей, если задан UTF8 } //cStringEncoding = 'UTF8'; begin try DoCommandFmt('SetConnectionParams '+ 'ProtocolVersion=%d;'+ //'CompressionLevel=%d;'+ 'EnableMessage=%d;'+ 'Description=%s;'+ 'SystemLogin=%s;'+ 'HostName=%s;'+ 'MaxLineLength=%d;'+ 'Language=%s;'+ 'StringEncoding=%s', [ ProtocolVersion, //CompressionLevel, Ord(EnableMessage), Description, GetLocalUserName, GetComputerName, Connection.IOHandler.MaxLineLength, Language, cStringEncoding ] ); if (ServerVer >= 3) and (cStringEncoding = 'UTF8') then Connection.IOHandler.DefStringEncoding := IndyTextEncoding_UTF8; except on e: EIdException do if ProcessTCPException(e) then raise; end; end; function TaOPCTCPSource_V30.SetDeviceProperties(id: string; sl: TStrings): string; var s: string; i: Integer; begin Result := ''; LockConnection; try try s := Format('SetDeviceProperties %s', [id]); for i := 0 to sl.Count - 1 do s := s + ';' + sl.Names[i] + '=' + StrToHex(sl.ValueFromIndex[i], ''); DoConnect; DoCommand(s); Result := sOk; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; procedure TaOPCTCPSource_V30.SetEncrypt(const Value: Boolean); begin if Encrypt = Value then exit; FEncrypt := Value; UpdateEncrypted(Active); end; function TaOPCTCPSource_V30.SetGroupProperties(id: string; sl: TStrings): string; var s: string; i: Integer; begin Result := ''; LockConnection; try try s := Format('SetGroupProperties %s', [id]); for i := 0 to sl.Count - 1 do s := s + ';' + sl.Names[i] + '=' + StrToHex(sl.ValueFromIndex[i], ''); DoConnect; DoCommand(s); // вычитываем необходимость перезагрузки сервера Result := sOk; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; procedure TaOPCTCPSource_V30.SetLanguage(const Value: string); begin if Language = Value then Exit; inherited SetLanguage(Value); UpdateLanguage(Active); end; procedure TaOPCTCPSource_V30.SetObjectPermission(aObjectID: Integer; aObjectTable: TDCObjectTable; aUserPermitions: string); begin LockAndDoCommandFmt('SetObjectPermission %d;%d;%s;1', [aObjectID, Ord(aObjectTable), EncodeStr(aUserPermitions)]); end; function TaOPCTCPSource_V30.SetSensorPropertiesEx(id: string; sl: TStrings): string; var s: string; i: Integer; begin Result := ''; LockConnection; try try if ServerVer > 1 then begin s := Format('SetSensorProperties.1 %s', [id]); for i := 0 to sl.Count - 1 do s := s + ';' + sl.Names[i] + '=' + StrToHex(sl.ValueFromIndex[i], ''); end else begin s := Format('SetSensorProperties %s', [id]); for i := 0 to sl.Count - 1 do s := s + ';' + sl[i]; end; DoConnect; DoCommand(s); // вычитываем необходимость перезагрузки сервера Result := sOk; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection; end; end; function TaOPCTCPSource_V30.SetSensorValue(PhysID, Value: string; Moment: TDateTime): string; begin Result := ''; LockConnection('SetSensorValue'); try try DoConnect; if ServerVer > 1 then begin // передача значения HEX строкой DoCommandFmt('SetValue.1 %s;%s;%s', [PhysID, StrToHex(Value), FloatToStr(DateToServer(Moment), OpcFS)]) end else begin // старый вариант: будут проблемы, если значение содержит ; DoCommandFmt('SetValue %s;%s;%s', [PhysID, Value, FloatToStr(DateToServer(Moment), OpcFS)]); end; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally UnLockConnection('SetSensorValue'); end; end; function TaOPCTCPSource_V30.SetThreadLock(ConnectionName: string; aLockState: boolean): string; begin LockAndDoCommandFmt('SetThreadLock %s;%s', [ConnectionName, BoolToStr(aLockState)]); end; function TaOPCTCPSource_V30.SetThreadState(ConnectionName: string; aNewState: boolean): string; begin LockAndDoCommandFmt('SetThreadState %s;%s', [ConnectionName, BoolToStr(aNewState)]); end; procedure TaOPCTCPSource_V30.TryConnect; begin Intercept.CryptKey := ''; Intercept.CompressionLevel := 0; inherited TryConnect; GetServerSettings; SetConnectionParams; if Encrypt then UpdateEncrypted(False); if CompressionLevel > 0 then UpdateComressionLevel(False); if User <> '' then begin try Authorize(User, Password); except on e: EIdException do if ProcessTCPException(e) then raise; on e: Exception do ; end; end; end; procedure TaOPCTCPSource_V30.UpdateComressionLevel(aLock: Boolean); begin if Connected then begin if aLock then LockConnection('UpdateComressionLevel'); try try DoCommandFmt('SetConnectionParams CompressionLevel=%d', [CompressionLevel]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally if aLock then UnLockConnection('UpdateComressionLevel'); end; end; Intercept.CompressionLevel := CompressionLevel; end; procedure TaOPCTCPSource_V30.UpdateDescription; begin try DoCommandFmt('SetConnectionParams '+ 'Description=%s', [Description] ); except on e: EIdException do if ProcessTCPException(e) then raise; end; end; procedure TaOPCTCPSource_V30.UpdateEncrypted(aLock: Boolean); var aCode: RawByteString; aCryptKey: RawByteString; //aRSA_e, aRSA_n: TFGInt; aModulus, aExponent: string; aPub: TRSAPublicKey; begin if Encrypt then aCryptKey := GenerateCryptKey(16) else aCryptKey := ''; if Connected then begin if aLock then LockConnection('UpdateEncrypted'); try try if FServerVer >= 4 then begin // новая версия RSA DoCommand('GetPublicKey2'); aModulus := ReadLn; aExponent := ReadLn; RSAPublicKeyInit(aPub); RSAPublicKeyAssignHex(aPub, 256, aModulus, aExponent); aCode := RSAEncryptStr(rsaetRSAES_PKCS1, aPub, aCryptKey); RSAPublicKeyFinalise(aPub); DoCommandFmt('SetCryptKey2 %s', [StrToHex(aCode, '')]); end else begin // для старых серверов шифрование будет ОТКЛЮЧЕНО aCryptKey := ''; // DoCommand('GetPublicKey'); // Base10StringToFGInt(ReadLn, aRSA_e); // Base10StringToFGInt(ReadLn, aRSA_n); // // FGIntRSA.RSAEncrypt(aCryptKey, aRSA_e, aRSA_n, aCode); // // DoCommandFmt('SetCryptKey %s', [StrToHex(aCode, '')]); end; except on e: EIdException do if ProcessTCPException(e) then raise; end; finally if aLock then UnLockConnection('UpdateEncrypted'); end; end; Intercept.CryptKey := aCryptKey; end; procedure TaOPCTCPSource_V30.UpdateLanguage(aLock: Boolean); begin if Connected then begin if aLock then LockConnection('UpdateLanguage'); try try DoCommandFmt('SetConnectionParams Language=%s', [Language]); except on e: EIdException do if ProcessTCPException(e) then raise; end; finally if aLock then UnLockConnection('UpdateLanguage'); end; end; end; procedure TaOPCTCPSource_V30.UploadFile(aFileName: string; aDestDir: string = ''); var aStream: TFileStream; begin LockConnection('UploadFile'); try aStream := TFileStream.Create(Trim(aFileName), fmOpenRead or fmShareDenyNone); try DoConnect; DoCommandFmt('UploadFile %s;%s', [aFileName, aDestDir]); WriteStream(aStream); finally aStream.Free; end; finally UnLockConnection('UploadFile'); end; end; end.
{ ID: a_zaky01 PROG: subsets LANG: PASCAL } Var n,i,p,j,i1,i2,ans:longint; a:array[0..22] of longint; s,idx:array[0..1 shl 20] of longint; subset:array[0..1 shl 20] of boolean; procedure sort(l,r:longint); var i,j,mid,temp:longint; begin i:=l; j:=r; mid:=s[random(r-l+1)+l]; repeat while s[i]<mid do inc(i); while s[j]>mid do dec(j); if i>j then break; temp:=s[i]; s[i]:=s[j]; s[j]:=temp; temp:=idx[i]; idx[i]:=idx[j]; idx[j]:=temp; inc(i); dec(j); until i>j; if l<j then sort(l,j); if i<r then sort(i,r); end; Begin Assign(input, 'subsets.in'); Reset(input); Assign(output, 'subsets.out'); Rewrite(output); readln(n); randomize; p:=(1 shl n)-1; for i:=1 to n do readln(a[i]); for i:=1 to p do for j:=1 to n do if i and (1 shl (j-1))>0 then s[i]:=s[i]+a[j]; for i:=1 to p do idx[i]:=i; sort(1,p); i:=1; while i<=p do begin j:=i+1; while (j<=p) and (s[j]=s[i]) do inc(j); for i1:=i to j-2 do for i2:=i1+1 to j-1 do subset[idx[i1] xor idx[i2]]:=true; i:=j; end; ans:=0; for i:=1 to p do if subset[i] then inc(ans); writeln(ans); Close(input); Close(output); End.
unit htmlayout; interface uses Windows, ExtCtrls, Forms, Controls, Classes, Messages, SysUtils, htmlayout_h, notifications_h; type THtmLayoutHandleLinkEvent = function (param: PNMHL_HYPERLINK): Boolean of object; THtmLayoutAttachBehavior = function (param: NMHL_ATTACH_BEHAVIOR): Integer of object; THtmLayoutCreateControl = function (param: NMHL_CREATE_CONTROL): Integer of object; THtmLayoutLoadData = function (param: NMHL_LOAD_DATA): Integer of object; THtmlLayoutDocumentCompleted = function(): Integer of object; THtmLayout = Class(TCustomPanel) private FTeste: String; FOnHandleLink: THtmLayoutHandleLinkEvent; FOnAttachBehavior: THtmLayoutAttachBehavior; FOnCreateControl: THtmLayoutCreateControl; FOnControlCreated: THtmLayoutCreateControl; FOnLoadData: THtmLayoutLoadData; FOnDataLoaded: THtmLayoutLoadData; FOnDocumentCompleted: THtmlLayoutDocumentCompleted; protected procedure WndProc(var Message: TMessage);override; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; function LoadHTML(html: String): Boolean; function LoadFile(filename: String): Boolean; property Teste: String read FTeste write FTeste; published property Align; property BorderStyle; property OnAttachBehavior: THtmLayoutAttachBehavior read FOnAttachBehavior write FOnAttachBehavior; property OnCreateControl: THtmLayoutCreateControl read FOnCreateControl write FOnCreateControl; property OnControlCreated: THtmLayoutCreateControl read FOnControlCreated write FOnControlCreated; property OnHandleLink: THtmLayoutHandleLinkEvent read FOnHandleLink write FOnHandleLink; property OnLoadData: THtmLayoutLoadData read FOnLoadData write FOnLoadData; property OnDataLoaded: THtmLayoutLoadData read FOnDataLoaded write FOnDataLoaded; property OnDocumentCompleted: THtmlLayoutDocumentCompleted read FOnDocumentCompleted write FOnDocumentCompleted; end; function NotifyHandler(uMsg: UINT; wParam: WPARAM; lParam: LPARAM; vParam: Pointer): LRESULT; stdcall; procedure Register; implementation procedure Register; begin RegisterComponentsProc('Internet', [THtmLayout]); end; function NotifyHandler(uMsg: UINT; wParam: WPARAM; lParam: LPARAM; vParam: Pointer): LRESULT; stdcall; var phdr: ^NMHDR; htmlayout: THtmLayout; begin htmlayout := vParam; phdr := Pointer(lParam); case phdr^.code of HLN_CREATE_CONTROL: begin if (Assigned(htmlayout.OnCreateControl)) then Result := htmlayout.FOnCreateControl(LPNMHL_CREATE_CONTROL(Pointer(lParam))^); end; HLN_CONTROL_CREATED: begin if (Assigned(htmlayout.OnControlCreated)) then Result := htmlayout.FOnControlCreated(LPNMHL_CREATE_CONTROL(Pointer(lParam))^); end; HLN_LOAD_DATA: begin if (Assigned(htmlayout.OnLoadData)) then Result := htmlayout.FOnLoadData(LPNMHL_LOAD_DATA(Pointer(lParam))^); end; HLN_DATA_LOADED: begin if (Assigned(htmlayout.OnDataLoaded)) then Result := htmlayout.FOnDataLoaded(LPNMHL_LOAD_DATA(Pointer(lParam))^); end; HLN_DOCUMENT_COMPLETE: begin if (Assigned(htmlayout.OnDocumentCompleted)) then Result := htmlayout.FOnDocumentCompleted; end; HLN_ATTACH_BEHAVIOR: begin if (Assigned(htmlayout.OnAttachBehavior)) then Result := htmlayout.FOnAttachBehavior(LPNMHL_ATTACH_BEHAVIOR(Pointer(lParam))^); end; else Result := 0; end; end; function THtmLayout.LoadHTML(html: String): Boolean; begin Result := HTMLayoutLoadHtml(Handle, PChar(html), Length(html)); end; function THtmLayout.LoadFile(filename: String): Boolean; var conteudo: TStringList; begin conteudo := TStringList.Create; try conteudo.LoadFromFile(filename); Result := LoadHTML(conteudo.Text); finally conteudo.Free; end; end; constructor THtmLayout.Create(AOwner:TComponent); begin inherited Create(AOwner); end; destructor THtmLayout.Destroy; begin inherited Destroy; end; procedure THtmLayout.WndProc(var Message: TMessage); var lResult: Integer; handled: BOOL; phdr: ^NMHDR; begin if (csDesigning in ComponentState) then begin inherited WndProc(Message); Exit; end; lResult := HTMLayoutProcND(Handle, Message.Msg, Message.WParam, Message.LParam, @handled); if (handled) then begin Message.Result := lResult; Exit; end; case Message.Msg of WM_CREATE: begin HTMLayoutSetCallback(Handle, @NotifyHandler, Self); end; WM_BEHAVIOR_NOTIFY: begin phdr := Pointer(Message.lParam); if (HLN_HYPERLINK = phdr^.code) then begin if Assigned(FOnHandleLink) then begin FOnHandleLink(Pointer(Message.lParam)); end; end; end; WM_ERASEBKGND: begin Message.Result := 1; Exit; end; else begin inherited WndProc(Message); Exit; end; end; Message.Result := 0; end; end.
// vim: set syntax=pascal: // script.simba // Contains or may eventually contain SRL, RSWalker, the OSRS client, some visual debugging tools (maybe), and a logger. // This is the global context of the script, so things that need to be available globally will end up here. // // // Examples // // How to start a client, create player, and login. // // begin // Script.Init('C:\Users\Administrator\jagexcache\jagexlauncher\bin\JagexLauncher'); // Script.DeclarePlayer('foo', 'bar', 420); // Players.SetCurrent(0); // Script.Login(); // end. // // // How to login any player at any time. // // begin // Players.SetCurrent(PlayerIndex); // Script.Login(); // end. {$I SRL/OSR.simba} {$I RSWalker/Walker.simba} {$I SRL/utils/rsclient.simba} {$I SRL/utils/rsclient_overrides.simba} {$include utils.simba} type TScript = record Walker: TRSWalker; Antiban: TAntiban; ClientPath: String; ClientProcess: TProcess; end; var Script: TScript; // Script.LoadMap-: Loads a map into RSWalker. procedure TScript.LoadMap(mapPath: String; downsample: Integer = 6); begin if Assigned(Walker) then writeln('Script.LoadMap-: Walker already initialized. Reloading Walker...'); Walker.Free; writeln('Script.LoadMap-: Loading map: ' + mapPath); Walker.Init(mapPath, downsample); AddOnTerminate(@Walker.Free); end; // Script.StartClient-: Initializes OSRS client & SRL procedure TScript.StartClient(ClientPath: String); begin writeln('Script.StartClient-: Launching client at ' + ClientPath); Script.ClientProcess.Init(nil); Script.ClientProcess.setExecutable(ClientPath); // Script.ClientProcess.setPriority(ppHigh); With Script.ClientProcess.getParameters do begin add('oldschool'); end; Script.ClientProcess.Execute; writeln('Script.StartClient-: Client Launched. Waiting for client to load...'); repeat Wait(1000); until FindJagexLTD(); // finds the little loading bar that happens before the client window opens repeat Wait(1000); until FindRS(); wait(10000); writeln('Script.StartClient-: Setting up SRL.'); SRL.SetupForClient(); repeat Wait(1000); writeln(2); until SRL.IsClientReady(); Wait(1000); RSClient.SetFocus(); writeln('Script.StartClient-: Client loaded (probably...).'); end; // Script.Free-: Frees script resources. procedure TScript.Free; begin writeln('Script.Free-: Freeing Script.'); if Assigned(Walker) then Walker.Free; RSClient.Close(); ClientProcess.Free(); writeln('Script.Free-: Script freed.'); end; // Script.Login-: Logs the Players.CurrentPlayer in. procedure TScript.Login(); var user, pass: String; w: Integer; // world p: TPlayer; // current player begin p := Players.GetCurrent()^; user := p.LoginName; pass := p.Password; w := p.World; writeln(Format('Script.Login-: Logging into World %d as %s.', [w, user])); if not SRL.isLoggedIn then begin if LoginScreen.GetCurrentWorld() <> w then begin writeln('Script.Login-: Selecting world ' + IntToStr(w)); LoginScreen.OpenWorldSwitcher(); WorldSwitcher.SelectWorld(w); end; if LoginScreen.Open() then LoginScreen.EnterDetails(user, pass); Wait(5000); // wait for client loading and window ID change. could be shorter RSClient.Find(); if Lobby.IsOpen() then Lobby.EnterGame(); end; writeln('Script.Login-: Setting default camera options.'); Options.SetZoom(50); Options.SetBrightness(100); Mainscreen.SetAngle(True); writeln('Script.Login-: Login complete.'); end; // Script.Init-: Initializes the Script, Antiban, Debugger, and (eventually) the Logger. procedure TScript.Init(clientPath: String); begin writeln('Script.Init-: Initializing Context.'); if not FindRS() then begin writeln('Script.Init-: Could not find Runescape client process.'); Script.StartClient(clientPath); end else begin writeln('Script.Init-: Found Runescape client process.'); SRL.SetupForClient(); RSClient.SetFocus(); end; writeln('Script.Init-: Initializing Antiban.'); Antiban.Init(SKILL_TOTAL, 4); Antiban.SetupBiometrics(); AddOnTerminate(@Script.Free); writeln('Script.Init-: Done.'); end; // Script.Antiban-: Runs the Antiban. procedure TScript.Antiban; begin writeln('Script.Antiban-: Doing Antiban.'); if not SRL.IsLoggedIn() then begin writeln('Script.Antiban-: Player not logged in, relogging...'); Script.Login(); Exit; end; SRL.DismissRandom(); Antiban.DoAntiban(); writeln('Script.Antiban-: Antiban done!'); end; // Script.DeclarePlayer-: Declares a Player. Returns the index of the new player in the Players array. function TScript.DeclarePlayer(name, pass: String; w: Integer; isActive: Boolean = True; isMember: Boolean = False): Integer; begin with Players.New()^ do begin LoginName := name; Password := pass; IsActive := isActive; IsMember := isMember; World := w; end; writeln(Format('Script.DeclarePlayer-: Username: %s, World: %d', [name, w])); Result := Players.GetCount() - 1; end;
unit PopupFormMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, Grids, Math, ExtCtrls; const ConstantHeight = 0; ConstantWidth = 0; UM_INVALIDATEROW = WM_USER+321; type TMultiSelectType = (mtcheckbox,mthighlight); TKeyboardSelectType = (ktAlpha, ktNumeric); type TCBSMagicGrid = class(TStringGrid) private FMultiSelect: Boolean; FMultiSelectType: TMultiSelectType; FKeyboardSelect: Boolean; FKeyboardSelectType: TKeyboardSelectType; FCheck, FNoCheck: TBitmap; SelectedStrings: TStringList; FStartItem: String; procedure LoadList(const Items: TStringList); procedure SetMultiSelectType(const Value: TMultiSelectType); procedure SetMultiSelect(const Value: Boolean); procedure SetKeyboardSelect(const Value: Boolean); procedure SetKeyboardSelectType(const Value: TKeyboardSelectType); procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override; procedure ClickGrid(Sender: TObject); function SelectCell(ACol, ARow: Longint): Boolean; override; procedure KeyPress(var Key: Char);override; procedure ToggleCheckbox(acol, arow: Integer); procedure SetReturnString(const Value: String); function GetReturnString: String; function RemoveBrackets(const Value: String): String; procedure SetStartItem(const Value: String); procedure Paint; override; procedure UnSelectItem(arow: Integer); procedure SelectItem(arow: Integer); procedure UpdateFromGrid(aRow: Integer; AddOnly: Boolean=False); procedure UpdateGrid(aRow: Integer); procedure SetGridRow; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure UpdateFromSelectedStrings; public constructor Create(AOwner: TComponent);override; destructor Destroy;override; procedure SetGridSize(GridHeight,GridWidth:Integer); // if height or weight is 0, sets to col and row actual, otherwise sets to values, returns values property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False; property MultiSelectType: TMultiSelectType read FMultiSelectType write SetMultiSelectType default mtCheckBox; property KeyboardSelect: Boolean read FKeyboardSelect write SetKeyboardSelect; property KeyboardSelectType: TKeyboardSelectType read FKeyboardSelectType write SetKeyboardSelectType; property ReturnString: String read GetReturnString write SetReturnString; property OnMouseUp; property OnClick; property StartItem: String read FStartItem write SetStartItem; procedure FinalChoice; end; type TPopupstyle = (psCalendar, psMultiCheck, psCalSelect); type TCBSMonthCalendar = class(TMonthCalendar) private property OnMouseUp; end; type TDaysSelector = class(TRadioGroup) public constructor Create(AOwner: TComponent);override; function ChangeDate(StartDate: TDate):TDate; end; type TPopupForm = class(TForm) procedure FormDestroy(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FMultiSelect: Boolean; FReturnString: String; FReturnDate: TDate; FPopupStyle: TPopupStyle; FPopupMonthCalendar: TCBSMonthCalendar; FDaysSelector: TDaysSelector; FGrid: TCBSMagicGrid; FItems: TStringList; procedure SetMultiSelect(const Value: Boolean); procedure SetReturnString(const Value: String); function GetReturnString: String; procedure SetReturnDate(const Value: TDate); procedure SetPopupStyle(const Value: TPopupStyle); procedure SetPopupMonthCalendar(const Value: TCBSMonthCalendar); procedure SetGrid(const Value: TCBSMagicGrid); procedure SetItems(const Value: TStringList); procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure WMNCRBUTTONDOWN(var msg: TMessage); procedure SetDaysSelector(const Value: TDaysSelector); { Private declarations } public { Public declarations } procedure LoadItems(Items: TStringList); property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False; property PopupMonthCalendar: TCBSMonthCalendar read FPopupMonthCalendar write SetPopupMonthCalendar; property DaysSelector: TDaysSelector read FDaysSelector write SetDaysSelector; property Grid: TCBSMagicGrid read FGrid write SetGrid; property ReturnString: String read GetReturnString write SetReturnString; property ReturnDate: TDate read FReturnDate write SetReturnDate; property PopupStyle : TPopupStyle read FPopupStyle write SetPopupStyle; property Items: TStringList read FItems write SetItems; end; implementation {$R *.DFM} procedure TPopupForm.SetReturnString(const Value: String); begin FReturnString := Value; if fPopupStyle = psMultiCheck then Grid.ReturnString := Value; end; procedure TPopupForm.WMNCRBUTTONDOWN(var msg: TMessage); begin ModalResult := mrNo; msg.Result := 0; inherited; end; procedure TPopupForm.SetMultiSelect(const Value: Boolean); begin FMultiSelect := Value; if Assigned(FGrid) then FGrid.MultiSelect := FMultiSelect; end; procedure TPopupForm.FormCreate(Sender: TObject); begin FItems := TStringList.Create; FItems.CaseSensitive := False; Brush.Style:=bsClear; BorderStyle:=bsNone; FReturnString := ''; end; procedure TPopupForm.FormDblClick(Sender: TObject); begin ModalResult := mrYes; end; procedure TPopupForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if ModalResult = mrNo then exit; case fPopupStyle of psCalendar: begin ReturnDate := FPopupMonthCalendar.Date; end; psCalSelect: begin ReturnDate := FDaysSelector.ChangeDate(FPopupMonthCalendar.Date); end; psMultiCheck: begin FReturnString := Grid.ReturnString; end; end; end; procedure TPopupForm.SetReturnDate(const Value: TDate); begin FReturnDate := Value; end; procedure TPopupForm.SetPopupMonthCalendar(const Value: TCBSMonthCalendar); begin end; procedure TPopupForm.SetPopupStyle(const Value: TPopupStyle); begin FPopupStyle := Value; case fPopupStyle of psCalendar: begin if not Assigned(FPopupMonthCalendar) then FPopupMonthCalendar := TCBSMonthCalendar.Create(Self); FPopupMonthCalendar.Parent := Self as TWinControl; FPopupMonthCalendar.Visible := False; FPopupMonthCalendar.OnDblClick := OnDblClick; FPopupMonthCalendar.OnMouseUp := OnMouseUp; end; psMultiCheck: begin if not Assigned(FGrid) then FGrid := TCBSMagicGrid.Create(Self); FGrid.Parent := Self as TWinControl; FGrid.Visible := False; FGrid.OnMouseUp := OnMouseUp; FGrid.OnDblClick := OnDblClick; FGrid.DefaultDrawing := True; end; psCalSelect: begin if not Assigned(FDaysSelector) then FDaysSelector := TDaysSelector.Create(Self); FDaysSelector.Parent := Self as TWinControl; FDaysSelector.Visible := False; FDaysSelector.OnClick := OnDblClick; end; end; end; procedure TPopupForm.FormShow(Sender: TObject); var Corner: TPoint; begin case fPopupStyle of psCalendar: begin FPopupMonthCalendar.Date := ReturnDate; ClientHeight := FPopupMonthCalendar.Height; ClientWidth := FPopupMonthCalendar.Width; FPopupMonthCalendar.Visible := True; end; psCalSelect: begin FPopupMonthCalendar.Date := ReturnDate; FDaysSelector.Height := FPopupMonthCalendar.Height; ClientHeight := max(FDaysSelector.Height, FPopupMonthCalendar.Height); ClientWidth := FPopupMonthCalendar.Width+FDaysSelector.Width; FPopupMonthCalendar.Left := FDaysSelector.Left + FDaysSelector.Width; FPopupMonthCalendar.Visible := True; FDaysSelector.Visible := True; end; psMultiCheck: begin Grid.SetGridSize(0,0); Grid.LoadList(Items); Grid.MultiSelect := FMultiSelect; // if Grid.MultiSelect then // Grid.Width := Grid.Width + Grid.ColWidths[1]; Grid.Visible := True; Height := Grid.Height; //BorderStyle := bsToolWindow; //BorderWidth := Trunc(ConstantWidth/2); ClientHeight := Grid.Height; ClientWidth := Grid.Width; ClientHeight := Grid.Height+ConstantHeight; ClientWidth := Grid.Width+ConstantWidth; BorderWidth := ConstantWidth; Grid.SetFocus; //Caption := 'Enter|DblClick=Select --- Esc|RtClick=Cancel'; end; end; //Adjust position for screen Corner := Point(ClientWidth,ClientHeight); Corner := Self.ClientToScreen(Corner); if Corner.Y > Screen.Height-50 then Corner.Y := Screen.Height-50; if Corner.X > Screen.Width then Corner.X := Screen.Width; Corner := Self.ScreenToClient(Corner); Top := Top + (Corner.Y - ClientHeight); Left := Left + (Corner.X - ClientWidth); Refresh; end; function TPopupForm.GetReturnString: String; begin Result := FReturnString; if PopupStyle = psMultiCheck then Result := Grid.ReturnString; end; procedure TPopupForm.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_RBUTTON then begin ModalResult := mrNo; Key := 0; end; inherited; end; procedure TPopupForm.LoadItems(Items: TStringList); var x: Integer; begin FItems.Clear; for x := 0 to Items.Count - 1 do FItems.Add(Items[x]); if FPopupStyle = psMultiCheck then Grid.LoadList(FItems); end; procedure TPopupForm.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then begin Key := #0; ModalResult := mrNo; end; if Assigned(Grid) then Grid.KeyPress(Key); end; procedure TPopupForm.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbRight then ModalResult := mrNo; end; procedure TPopupForm.FormDestroy(Sender: TObject); begin FItems.Free; // UnHookWindowsHookEx(hkk); end; { TCBSMagicGrid } procedure TCBSMagicGrid.ClickGrid(Sender: TObject); var pt: TPoint; aCol, aRow: Integer; begin inherited; GetCursorPos( pt ); pt:= ScreenToClient( pt ); MouseToCell( pt.x, pt.y, aCol, aRow ); If (aCol = 1) and (aRow >= fixedRows) Then Begin // click landed in a checkbox cell ToggleCheckbox( aCol, aRow ); End; end; constructor TCBSMagicGrid.Create(AOwner: TComponent); var bmp: TBitmap; x: Integer; begin inherited; Onclick := ClickGrid; FCheck := TBitmap.Create; FNoCheck := TBitmap.Create; bmp:= TBitmap.create; SelectedStrings := TStringList.Create; try bmp.handle := LoadBitmap( 0, PChar(OBM_CHECKBOXES )); // bmp now has a 4x3 bitmap of divers state images // used by checkboxes and radiobuttons With FNoCheck Do Begin // the first subimage is the unchecked box width := bmp.width div 4; height := bmp.height div 3; canvas.copyrect( canvas.cliprect, bmp.canvas, canvas.cliprect ); End; With FCheck Do Begin // the second subimage is the checked box width := bmp.width div 4; height := bmp.height div 3; canvas.copyrect( canvas.cliprect, bmp.canvas, rect( width, 0, 2*width, height )); End; finally bmp.free end; BorderStyle := bsNone; // BevelWidth := 1; // BevelKind := bkTile; // BevelInner := bvRaised; // BevelOuter := bvLowered; DefaultRowHeight := 18; DefaultColWidth := 12; FixedCols := 1; FixedColor := clFuchsia; GridLineWidth := 2; FixedRows := 0; ColCount := 3; RowCount := 26; ScrollBars := ssVertical; Options := Options - [ goFixedHorzLine, goHorzLine ]; Options := Options + [ goFixedVertLine ]; ColWidths[2] := 200; for x:= 0 to 25 do Cells[0,x] := CHR(65+x); end; destructor TCBSMagicGrid.Destroy; begin FCheck.Free; FNoCheck.Free; SelectedStrings.Free; inherited; end; procedure TCBSMagicGrid.KeyDown(var Key: Word; Shift: TShiftState); begin if Key = VK_RBUTTON then begin (Parent as TPopupForm).ModalResult := mrNo; Key := 0; end; inherited; end; procedure TCBSMagicGrid.KeyPress(var Key: Char); var KeyToRow: Integer; I: Integer; begin Case Key of #32: If MultiSelect then ToggleCheckbox( 1, row ); 'a'..'z', 'A'..'Z': begin if ('a' <= Key) and (Key <= 'z') then Key := Char(Integer(Key) - 32); // look for letter in visible rows starting at top for I := TopRow to (TopRow+VisibleRowCount) - 1 do if Cells[0,I][1]= Key then begin KeyToRow := I; break; end; if KeyToRow < RowCount then begin Row := KeyToRow; ToggleCheckbox(1,KeyToRow); if not MultiSelect then (Parent as TPopupForm).ModalResult := mrYes; end; end; #27: (Parent as TPopupForm).ModalResult := mrNo; #13: begin UpdateFromGrid(Row,True); (Parent as TPopupForm).ModalResult := mrYes; end; End; Key := #0; inherited; end; procedure TCBSMagicGrid.LoadList(const Items: TStringList); var x, GridHeight: Integer; begin GridHeight := 0; for x := 0 to Items.Count - 1 do begin Cells[2,x] := Items[x]; // Set up the alpha in the first column Cells[0,x] := CHR(65+(x mod 26)); if x < 26 then GridHeight := GridHeight + RowHeights[x]{+GridLineWidth}; end; RowCount := Items.Count; Height := GridHeight+(GridLineWidth); end; procedure TCBSMagicGrid.Paint; var x,y: Integer; begin inherited; end; function TCBSMagicGrid.RemoveBrackets(const Value: String): String; var x: Integer; BetweenBrackets: Boolean; begin Result := ''; BetweenBrackets := False; for x:= 1 to Length(Value) do begin if not BetweenBrackets then begin if Value[x]='[' then BetweenBrackets := True else Result := Result + Value[x]; end else if Value[x]=']' then BetweenBrackets := False; end; Result := Trim(Result); end; function TCBSMagicGrid.SelectCell(ACol, ARow: Integer): Boolean; begin If aCol = 1 Then Options := Options - [ goediting ] Else Options := Options + [ goediting ]; end; procedure TCBSMagicGrid.SetKeyboardSelect(const Value: Boolean); begin FKeyboardSelect := Value; end; procedure TCBSMagicGrid.SetKeyboardSelectType(const Value: TKeyboardSelectType); begin FKeyboardSelectType := Value; end; procedure TCBSMagicGrid.SetMultiSelect(const Value: Boolean); begin FMultiSelect := Value; if FMultiSelect then ColWidths[1] := 18 else ColWidths[1] := -1; end; procedure TCBSMagicGrid.SetMultiSelectType(const Value: TMultiSelectType); begin FMultiSelectType := Value; end; procedure TCBSMagicGrid.SetReturnString(const Value: String); procedure ParseDelimited(const sl : TStrings; const value : string; const delimiter : string) ; var dx : integer; ns : string; txt : string; delta : integer; begin delta := Length(delimiter) ; txt := value + delimiter; sl.BeginUpdate; sl.Clear; try while Length(txt) > 0 do begin dx := Pos(delimiter, txt) ; ns := Trim(Copy(txt,0,dx-1)) ; sl.Add(ns) ; txt := Copy(txt,dx+delta,MaxInt) ; end; finally sl.EndUpdate; end; end; var TempStrings: TStringList; x, SelectedIndex, SelectedRow: Integer; CheckString: String; begin SelectedRow := 0; TempStrings := TStringList.Create; try //Parse the string ParseDelimited(TempStrings,Value,','); // Add any checked items in the Grid for x := 0 to RowCount - 1 do begin if Assigned(Objects[1,x]) then begin CheckString := RemoveBrackets(Cells[2,x]); SelectedIndex := TempStrings.IndexOf(CheckString); if SelectedIndex < 0 then // if it is not there, add it TempStrings.Add(CheckString); end; end; // copy from Temp to the final for x := 0 to TempStrings.count - 1 do if SelectedStrings.IndexOf(TempStrings[x])<0 then SelectedStrings.Add(TempStrings[x]); UpdateFromSelectedStrings; finally TempStrings.Free; end; Row := SelectedRow; end; procedure TCBSMagicGrid.SetStartItem(const Value: String); begin FStartItem := Trim(uppercase(Value)); SetGridRow; end; function TCBSMagicGrid.GetReturnString: String; var x: Integer; begin // check against grid for x := 0 to RowCount - 1 do begin if Assigned(Objects[1,x]) then begin UpdateFromGrid(x); end; end; // Add commas and return Result := ''; for x := 0 to SelectedStrings.Count -1 do begin if Result = '' then Result := SelectedStrings[x] else if Length(SelectedStrings[x]) > 0 then Result := Result + ', '+SelectedStrings[x] end; end; procedure TPopupForm.SetDaysSelector(const Value: TDaysSelector); begin FDaysSelector := Value; end; procedure TPopupForm.SetGrid(const Value: TCBSMagicGrid); begin FGrid := Value; end; procedure TPopupForm.SetItems(const Value: TStringList); begin FItems := Value; Grid.LoadList(Value); Height := Grid.Height; end; procedure TCBSMagicGrid.SetGridRow; var I: Integer; begin for I := 0 to RowCount - 1 do begin if uppercase(RemoveBrackets(Cells[2,I]))=StartItem then begin Row := I; exit; end; end; for I := 0 to RowCount - 1 do begin if uppercase(RemoveBrackets(Cells[2,I]))>StartItem then begin Row := max(0,I-1); exit; end; end; end; procedure TCBSMagicGrid.SetGridSize(GridHeight, GridWidth: Integer); var I: Integer; begin // GridWidth := 0; // GridHeight := 0; if GridHeight <= 0 then for I:=0 to RowCount -1 do GridHeight := GridHeight + Max(0,RowHeights[I]{+(GridLineWidth)}); if GridWidth <= 0 then for I:=0 to ColCount -1 do GridWidth := GridWidth + Max(0,ColWidths[I]+GridLineWidth); Height := GridHeight+(2*GridLineWidth);// Add top and bottom line Width := GridWidth; end; procedure TCBSMagicGrid.UpdateGrid(aRow: Integer); var CheckString: String; SelectedIndex: Integer; begin CheckString := RemoveBrackets(Cells[2, aRow]); SelectedIndex := SelectedStrings.IndexOf(CheckString); // Row value Is in SelectedStrings and not checked if (SelectedIndex >= 0) and (Objects[1, aRow] = nil) then ToggleCheckBox(1, aRow); // Row value is NOT in SelectedString and IS checked if (SelectedIndex < 0) and (Assigned(Objects[1, aRow])) then ToggleCheckBox(1, aRow); end; procedure TCBSMagicGrid.UpdateFromGrid(aRow: Integer; AddOnly: Boolean=False); var CheckString: string; SelectedIndex: Integer; begin if AddOnly and (Objects[1, aRow] = nil) then ToggleCheckBox(1,aRow); CheckString := RemoveBrackets(Cells[2, aRow]); SelectedIndex := SelectedStrings.IndexOf(CheckString); // Row value Is in SelectedStrings and not checked if (SelectedIndex >= 0) and (Objects[1, aRow] = nil) then SelectedStrings.Delete(SelectedIndex); // Row value is NOT in SelectedString and IS checked if (SelectedIndex < 0) and (Assigned(Objects[1, aRow])) then SelectedStrings.Add(CheckString); end; procedure TCBSMagicGrid.SelectItem(arow: Integer); var CheckString: string; SelectedIndex: Integer; begin // check to see if the text is in Selected Strings CheckString := RemoveBrackets(Cells[2, aRow]); // if it is an empty string exit if CheckString = '' then exit; // See if the Checkstring is already part of either selected or sent SelectedIndex := SelectedStrings.IndexOf(CheckString); if SelectedIndex < 0 then // if it is not there, add it if FMultiSelect then SelectedStrings.Add(CheckString) else begin // if this should be added to (,) sent through as last character if trim(SelectedStrings[pred(SelectedStrings.Count)])='' then SelectedStrings[pred(SelectedStrings.Count)] := CheckString else begin // Replace what was sent through SelectedStrings.Clear; SelectedStrings.Add(CheckString); // Clear Grid checks UpdateFromSelectedStrings; end; end; end; procedure TCBSMagicGrid.UnSelectItem(arow: Integer); var CheckString: string; SelectedIndex: Integer; begin // check to see if the text is in Selected Strings CheckString := RemoveBrackets(Cells[2, aRow]); SelectedIndex := SelectedStrings.IndexOf(CheckString); if SelectedIndex >= 0 then // if it is there, delete SelectedStrings.Delete(SelectedIndex); end; procedure TCBSMagicGrid.ToggleCheckbox(acol, arow: Integer); begin If aCol = 1 Then begin If Assigned( Objects[aCol, aRow] ) Then begin //was checked...uncheck it Objects[aCol, aRow] := Nil; UnSelectItem(aRow); end Else begin //was unchecked...check it Objects[aCol, aRow] := Pointer(1); SelectItem(arow); end; InvalidateCell( aCol, aRow ); End; end; procedure TCBSMagicGrid.DrawCell(ACol, ARow: Integer; ARect: TRect; AState: TGridDrawState); begin inherited; If not ( gdFixed In AState ) Then Begin if (aCol = 1) then begin With Canvas Do Begin brush.color := $E0E0E0; // checkboxes look better on a non-white background Fillrect( Arect ); // listbox state is encoded by the Objects property If Assigned(Objects[aCol, aRow]) Then Draw( (Arect.right + Arect.left - FCheck.width) div 2, (Arect.bottom + Arect.top - FCheck.height) div 2, FCheck ) Else Draw( (Arect.right + Arect.left - FNoCheck.width) div 2, (Arect.bottom + Arect.top - FNoCheck.height) div 2, FNoCheck ) End; end else begin if aCol = 0 then Canvas.Font.Style := [fsBold] else Canvas.Font.Style := []; if Row = aRow then begin With Canvas do begin Brush.Color := clBlue; Brush.Style := bsSolid; FillRect( ARect ); Font.Color := clWhite; TextRect( ARect, ARect.Left+2, ARect.Top+2, Cells[acol, arow]); end; end; Canvas.Brush := Brush; end; End; EditorMode := False; // InvalidateGrid; end; procedure TCBSMagicGrid.FinalChoice; begin if Row >=0 then UpdateFromGrid(Row,True); end; procedure TCBSMagicGrid.UpdateFromSelectedStrings; var x: Integer; begin // Update checks in Grid for x := 0 to RowCount - 1 do begin UpdateGrid(x); end; end; { TDaysSelector } function TDaysSelector.ChangeDate(StartDate: TDate): TDate; var DaysToAdd: Integer; begin DaysToAdd := 0; case ItemIndex of 0: DaysToAdd := 7; 1: DaysToAdd := 14; 2: DaysToAdd := 21; 3: DaysToAdd := 30; 4: DaysToAdd := 60; 5: DaysToAdd := 90; 6: DaysToAdd := 120; 7: DaysToAdd := 150; 8: DaysToAdd := 180; 9: DaysToAdd := 210; 10: DaysToAdd := 240; 11: DaysToAdd := 270; 12: DaysToAdd := 300; 13: DaysToAdd := 330; 14: DaysToAdd := 365; 15: DaysToAdd := 730; end; Result := Date + DaysToAdd; end; constructor TDaysSelector.Create(AOwner: TComponent); begin inherited Create(AOwner); Parent := AOwner as TWincontrol; Color := clWindow; Columns := 2; Width := 160; Caption := ''; Ctl3D := False; Items.Add('1 week'); Items.Add('2 weeks'); Items.Add('3 weeks'); Items.Add('1 month'); Items.Add('2 months'); Items.Add('3 months'); Items.Add('4 months'); Items.Add('5 months'); Items.Add('6 months'); Items.Add('7 months'); Items.Add('8 months'); Items.Add('9 months'); Items.Add('10 months'); Items.Add('11 months'); Items.Add('1 year'); Items.Add('2 years'); end; end.
unit UTS1040ALT; interface uses Contnrs, System.Classes, unUtils; type TS1040ALT = class(TObjectList) private function GetItem(Index: Integer): TS1040ALT; function Add: TS1040ALT; public tpAmb_4: String; procEmi_5: String; verProc_6: String; tpInsc_8: String; nrInsc_9: String; codFuncao_13: String; iniValid_14: String; fimValid_15: String; dscFuncao_17: String; codCBO_18: String; iniValid_19: String; fimValid_20: String; property Items[Index: Integer]: TS1040ALT read GetItem; default; procedure GetS1040ALT(const Arq: TStringList); end; implementation { TS1040ALT } function TS1040ALT.Add: TS1040ALT; begin Result := TS1040ALT.Create; inherited Add(Result); end; function TS1040ALT.GetItem(Index: Integer): TS1040ALT; begin Result := TS1040ALT(inherited Items[Index]); end; procedure TS1040ALT.GetS1040ALT(const Arq: TStringList); var I: Integer; Lista: TStringList; Utils: TUtils; begin Utils := TUtils.Create; inherited Clear; for I := 0 to Pred(Arq.Count) do if Copy(Arq[I],0,Pred(Pos('|',Arq[I]))) = 'S1040'then begin Lista := TStringList.Create; ExtractStrings(['|'],[],PChar(Arq[I]),Lista); with Add do begin tpAmb_4 := Utils.RemoveZerosEsp(Lista[1]); procEmi_5 := Utils.RemoveZerosEsp(Lista[2]); verProc_6 := Utils.RemoveZerosEsp(Lista[3]); tpInsc_8 := Utils.RemoveZerosEsp(Lista[4]); nrInsc_9 := Utils.RemoveZerosEsp(Lista[5]); codFuncao_13 := Utils.RemoveZerosEsp(Lista[6]); iniValid_14 := Utils.RemoveZerosEsp(Lista[7]); fimValid_15 := Utils.RemoveZerosEsp(Lista[8]); dscFuncao_17 := Utils.RemoveZerosEsp(Lista[9]); codCBO_18 := Utils.RemoveZerosEsp(Lista[10]); iniValid_19 := Utils.RemoveZerosEsp(Lista[11]); fimValid_20 := Utils.RemoveZerosEsp(Lista[12]); end; Lista.Free; end; end; end.
unit QpFilterListUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MaximizedUnit, ComCtrls, ToolWin, ExtCtrls, ImgList, DbGridUnit, DB, IBCustomDataSet, IBUpdateSQL, IBQuery, DbGridEh; type { TFilterListForm } TFilterListForm = class(TMaximizedForm) ToolImages: TImageList; ToolPanel: TPanel; ToolBar: TToolBar; OKBtn: TToolButton; FilterFrame: TDbGridFrame; Splitter: TSplitter; LimitFrame: TDbGridFrame; EmptyBtn: TToolButton; RefreshBtn: TToolButton; FilterQuery: TIBQuery; FilterUpdate: TIBUpdateSQL; FilterQueryFILTER_ID: TIntegerField; FilterQueryDESCR: TIBStringField; FilterQueryLIMIT_OR: TSmallintField; LimitQuery: TIBQuery; LimitUpdate: TIBUpdateSQL; LimitQueryLIMIT_ID: TIntegerField; LimitQueryFILTER_ID: TIntegerField; LimitQueryKIND: TSmallintField; LimitQueryID: TIntegerField; LimitQueryCONDITION: TIntegerField; LimitQueryATTR_VALUE: TIBBCDField; StationQuery: TIBQuery; CompanyQuery: TIBQuery; ProductQuery: TIBQuery; AttrQuery: TIBQuery; AttrQueryID: TIntegerField; AttrQueryDESCR: TIBStringField; StationQuerySTATION_ID: TIntegerField; StationQueryNAME: TIBStringField; CompanyQueryCOMPANY_ID: TIntegerField; CompanyQueryNAME: TIBStringField; ProductQueryID: TIntegerField; ProductQueryDESCR: TIBStringField; LimitQueryATTR_NAME: TStringField; LimitQuerySTATION_NAME: TStringField; LimitQueryCOMPANY_NAME: TStringField; LimitQueryPRODUCT_NAME: TStringField; LimitQueryID_NAME: TStringField; procedure FilterQueryNewRecord(DataSet: TDataSet); procedure FilterQueryBeforePost(DataSet: TDataSet); procedure LimitQueryNewRecord(DataSet: TDataSet); procedure FilterFrameDataSourceDataChange(Sender: TObject; Field: TField); procedure FormShow(Sender: TObject); procedure LimitQueryKINDChange(Sender: TField); procedure LimitQueryBeforePost(DataSet: TDataSet); procedure LimitQueryCalcFields(DataSet: TDataSet); procedure GridColumns1EditButtonClick(Sender: TObject; var Handled: Boolean); procedure OKBtnClick(Sender: TObject); procedure EmptyBtnClick(Sender: TObject); procedure FormHide(Sender: TObject); procedure LimitFrameGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FilterQueryAfterDelete(DataSet: TDataSet); procedure FilterQueryAfterPost(DataSet: TDataSet); procedure LimitQueryAfterDelete(DataSet: TDataSet); procedure LimitQueryAfterPost(DataSet: TDataSet); private FListID: Integer; FChanged: Boolean; function GetFilterID: Integer; procedure SetFilterID(AFilterID: Integer); procedure FilterQueryChanged; protected procedure FontChanged; override; public constructor Create(AOwner: TComponent); override; function UpdateList(Strings: TStrings; ListID: Integer): Integer; property FilterID: Integer read GetFilterID write SetFilterID; end; var FilterListForm: TFilterListForm; implementation uses DataUnit, DataLookupUnit, ExtraUnit, Math; {$R *.dfm} { TFilterListForm } constructor TFilterListForm.Create(AOwner: TComponent); begin inherited Create(AOwner); IgnoreLimits := True; FListID := 1; end; function TFilterListForm.GetFilterID: Integer; begin Result := FilterQueryFILTER_ID.AsInteger; end; procedure TFilterListForm.SetFilterID(AFilterID: Integer); begin FilterQuery.Locate('FILTER_ID', AFilterID, []); end; function TFilterListForm.UpdateList(Strings: TStrings; ListID: Integer): Integer; var SavedFilterID: Integer; begin if FListID > ListID then begin FilterQuery.Open; FilterQuery.DisableControls; try SavedFilterID := FilterQueryFILTER_ID.AsInteger; try FilterQuery.First; Strings.Clear; while not FilterQuery.Eof do begin Strings.AddObject(FilterQueryDESCR.AsString, Pointer(FilterQueryFILTER_ID.AsInteger)); FilterQuery.Next; end; Strings.Insert(0, '<Нет ограничений>'); Strings.Append('<Редактировать...>'); finally FilterQuery.Locate('FILTER_ID', SavedFilterID, []); end; finally FilterQuery.EnableControls; end; end; Result := FListID; end; procedure TFilterListForm.FilterQueryNewRecord(DataSet: TDataSet); begin FilterQueryLIMIT_OR.AsInteger := 0; end; procedure TFilterListForm.FilterQueryBeforePost(DataSet: TDataSet); begin if FilterQueryLIMIT_OR.IsNull then FilterQueryLIMIT_OR.AsInteger := 0; end; procedure TFilterListForm.LimitQueryNewRecord(DataSet: TDataSet); begin if FilterQuery.State in dsEditModes then FilterQuery.Post; LimitQueryFILTER_ID.AsInteger := FilterQueryFILTER_ID.AsInteger; LimitQueryKIND.AsInteger := 0; end; procedure TFilterListForm.FilterFrameDataSourceDataChange(Sender: TObject; Field: TField); var FilterExists: Boolean; begin FilterExists := not (FilterQuery.Bof and FilterQuery.Eof); OKBtn.Enabled := FilterExists; LimitQuery.Active := FilterExists; end; procedure TFilterListForm.FormShow(Sender: TObject); begin FilterQuery.Open; AttrQuery.Open; StationQuery.Open; CompanyQuery.Open; ProductQuery.Open; end; procedure TFilterListForm.LimitQueryBeforePost(DataSet: TDataSet); begin if LimitQueryKIND.IsNull then LimitQueryKIND.AsInteger := 0; end; procedure TFilterListForm.LimitQueryKINDChange(Sender: TField); begin LimitQueryID.Clear; end; procedure TFilterListForm.LimitQueryCalcFields(DataSet: TDataSet); var S: string; begin case LimitQueryKIND.AsInteger of 0: S := LimitQueryATTR_NAME.AsString; 1: S := LimitQuerySTATION_NAME.AsString; 2, 3, 4: S := LimitQueryCOMPANY_NAME.AsString; 5: S := LimitQueryPRODUCT_NAME.AsString; else S := ''; end; LimitQueryID_NAME.AsString := S; end; procedure TFilterListForm.GridColumns1EditButtonClick(Sender: TObject; var Handled: Boolean); procedure UpdateID(ID: Integer); begin if LimitQueryID.AsInteger <> ID then begin if not (LimitQuery.State in dsEditModes) then LimitQuery.Edit; LimitQueryID.AsInteger := ID; end; end; begin case LimitQueryKIND.AsInteger of 0: UpdateID(LookupAttribute(LimitQueryID.AsInteger)); 1: UpdateID(LookupStation(LimitQueryID.AsInteger)); 2, 3, 4: UpdateID(LookupCompany(LimitQueryID.AsInteger)); 5: UpdateID(LookupProduct(LimitQueryID.AsInteger)); end; Handled := True; end; procedure TFilterListForm.OKBtnClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TFilterListForm.EmptyBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFilterListForm.FilterQueryChanged; begin FChanged := True; end; procedure TFilterListForm.FormHide(Sender: TObject); begin if FilterQuery.State in dsEditModes then FilterQuery.Post; if LimitQuery.State in dsEditModes then LimitQuery.Post; if FChanged then begin Inc(FListID); FChanged := False; end; end; procedure TFilterListForm.LimitFrameGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var Handled: Boolean; begin if (Key = VK_F3) and (Shift = []) and (LimitFrame.Grid.Col = LimitFrame.ColumnByField(LimitQueryID_NAME).Index) then begin GridColumns1EditButtonClick(Self, Handled); end; LimitFrame.FrameKeyDown(Sender, Key, Shift); end; procedure TFilterListForm.FontChanged; begin ToolPanel.Height := 41 + FontHeight(Font); end; procedure TFilterListForm.FilterQueryAfterDelete(DataSet: TDataSet); begin FilterQuery.Transaction.CommitRetaining; FilterQueryChanged; end; procedure TFilterListForm.FilterQueryAfterPost(DataSet: TDataSet); begin FilterQuery.Transaction.CommitRetaining; FilterQueryChanged; end; procedure TFilterListForm.LimitQueryAfterDelete(DataSet: TDataSet); begin LimitQuery.Transaction.CommitRetaining; end; procedure TFilterListForm.LimitQueryAfterPost(DataSet: TDataSet); begin LimitQuery.Transaction.CommitRetaining; end; end.
{ **************************************************************************************** SAPMM memory routines Memory moving and zeroing. Uses SSE2 if CPU supports it **************************************************************************************** } unit SAPSystem; interface {$INCLUDE SAPOptions.inc} type TSapByteArray = array of Byte; // if SSE2 not available, uses System.Move procedure SAPMoveMemory(const Destination, Source: Pointer; const Size: Integer); inline; // Faster zeroing blocks of memory. If SSE2 not supported or block < 128 bytes, then normal FillChar is used procedure SAPZeroMemory(const Destination: Pointer; const Size: Integer); inline; var IsSSE2Supported: Boolean = False; procedure SSE2MemoryCopy(dst, src: Pointer; Size: Cardinal); inline; procedure SSE2MemoryZero(src: Pointer; Size: Cardinal); inline; procedure SSE2DoubleAlignedMemCopy128(dst, src: Pointer; A128bytesmultiple: Integer); procedure SSE2AlignedMemCopy128(dst, src: Pointer; A128bytesmultiple: Integer); procedure SSE2AlignedMemCopy16(dst, src: Pointer; A16bytesmultiple: Integer); procedure SSE2AlignedMemFill128(dst: Pointer; A128bytesmultiple: Integer); procedure SSE2AlignedMemFill16(dst: Pointer; A16bytesmultiple: Integer); implementation {$CODEALIGN 16} procedure SAPMoveMemory(const Destination, Source: Pointer; const Size: Integer); begin if IsSSE2Supported and (Size >= 128) and ((Cardinal(Source) - Cardinal(Size) >= Cardinal(Destination)) or ((Cardinal(Source) + Cardinal(Size)) <= Cardinal(Destination))) then SSE2MemoryCopy(Destination, Source, Size) else Move(Source^, Destination^, Size); end; procedure SAPZeroMemory(const Destination: Pointer; const Size: Integer); begin if IsSSE2Supported and (Size >= 128) then SSE2MemoryZero(Destination, Size) else FillChar(Destination^, Size, 0); end; procedure SSE2AlignedMemCopy128(dst, src: Pointer; A128bytesmultiple: Integer); asm .align 16 @Copy_loop: PREFETCHNTA 32[EDX] // Pre-fetch data PREFETCHNTA 64[EDX] // Pre-fetch data PREFETCHNTA 96[EDX] // Pre-fetch data Movdqa xmm0,[edx] Movdqa xmm1,[edx+16] Movdqa xmm2,[edx+32] Movdqa xmm3,[edx+48] Movdqa xmm4,[edx+64] Movdqa xmm5,[edx+80] Movdqa xmm6,[edx+96] Movdqa xmm7,[edx+112] Movdqu [eax],xmm0 Movdqu [eax+16],xmm1 Movdqu [eax+32],xmm2 Movdqu [eax+48],xmm3 Movdqu [eax+64],xmm4 Movdqu [eax+80],xmm5 Movdqu [eax+96],xmm6 Movdqu [eax+112],xmm7 Add edx,128 Add eax,128 Dec ecx Jnz @Copy_loop end; procedure SSE2DoubleAlignedMemCopy128(dst, src: Pointer; A128bytesmultiple: Integer); asm .align 16 @Copy_loop: PREFETCHNTA 32[EDX] // Pre-fetch data PREFETCHNTA 64[EDX] // Pre-fetch data PREFETCHNTA 96[EDX] // Pre-fetch data Movdqa xmm0,[edx] Movdqa xmm1,[edx+16] Movdqa xmm2,[edx+32] Movdqa xmm3,[edx+48] Movdqa xmm4,[edx+64] Movdqa xmm5,[edx+80] Movdqa xmm6,[edx+96] Movdqa xmm7,[edx+112] Movdqa [eax],xmm0 Movdqa [eax+16],xmm1 Movdqa [eax+32],xmm2 Movdqa [eax+48],xmm3 Movdqa [eax+64],xmm4 Movdqa [eax+80],xmm5 Movdqa [eax+96],xmm6 Movdqa [eax+112],xmm7 Add edx,128 Add eax,128 Dec ecx Jnz @Copy_loop end; procedure SSE2AlignedMemCopy16(dst, src: Pointer; A16bytesmultiple: Integer); asm .align 16 @Copy_loop: Movdqa xmm0,[edx] Movdqu [eax],xmm0 Add edx,16 Add eax,16 Dec ecx Jnz @Copy_loop end; procedure SSE2MemoryCopy(dst, src: Pointer; Size: Cardinal); var Unaligned: Cardinal; Chunks: Cardinal; Aligned128Size: Cardinal; Idx: Integer; AlignedSrc, NewDst: Pointer; begin {$IFOPT R+} {$DEFINE RANGEON} {$R-} // Turn range checks off {$ELSE} {$UNDEF RANGEON} {$ENDIF} // Unaligned bytes for reading Unaligned := (16 - (Cardinal(Src) and 15)) and 15; // Copy First Max 15 Bytes of Unaligned Data if Unaligned > 0 then for Idx := 0 to Unaligned - 1 do TSapByteArray(dst)[Idx] := TSapByteArray(src)[Idx]; // Do the heavy 128 byte Chunks Chunks := (Size - Unaligned) shr 7; NewDst := Pointer(Cardinal(dst) + UnAligned); AlignedSrc := Pointer(Cardinal(src) + UnAligned); // Copy 128 bytes chunks Aligned, or even double Aligned (read and write aligned) if Chunks > 0 then begin if Cardinal(NewDst) and 15 = 0 then SSE2DoubleAlignedMemCopy128(NewDst, AlignedSrc, Chunks) else SSE2AlignedMemCopy128(NewDst, AlignedSrc, Chunks); end; // Copy remainder in 16 byte chunks Aligned128Size := Chunks shl 7; NewDst := Pointer(Cardinal(Newdst) + Aligned128Size); AlignedSrc := Pointer(Cardinal(AlignedSrc) + Aligned128Size); Chunks := (Size - Unaligned - Aligned128Size) shr 4; if Chunks > 0 then SSE2AlignedMemCopy16(NewDst, AlignedSrc, Chunks); // Copy Remaining in Byte chunks NewDst := Pointer(Cardinal(Newdst) + (Chunks shl 4)); AlignedSrc := Pointer(Cardinal(AlignedSrc) + (Chunks shl 4)); for Idx := 0 to Integer(Cardinal(Size - (Cardinal(AlignedSrc) - Cardinal(Src)))) - 1 do TSapByteArray(NewDst)[Idx] := TSapByteArray(AlignedSrc)[Idx]; {$IFDEF RANGEON} // If range checking was on before turning it off {$R+} // Turn range checks back on {$UNDEF RANGEON} {$ENDIF} end; procedure SSE2AlignedMemFill16(dst: Pointer; A16bytesmultiple: Integer); asm PXOR XMM0,XMM0 // All zeros in XMM0 .align 16 @Copy_loop: Movntdq [eax],xmm0 Add eax,16 Dec edx Jnz @Copy_loop sfence end; procedure SSE2AlignedMemFill128(dst: Pointer; A128bytesmultiple: Integer); asm PXOR XMM0,XMM0 // All zeros in XMM0 .align 16 @Copy_loop: Movntdq [eax],xmm0 Movntdq [eax+16],xmm0 Movntdq [eax+32],xmm0 Movntdq [eax+48],xmm0 Movntdq [eax+64],xmm0 Movntdq [eax+80],xmm0 Movntdq [eax+96],xmm0 Movntdq [eax+112],xmm0 Add eax,128 Dec edx Jnz @Copy_loop sfence end; procedure SSE2MemoryZero(src: Pointer; Size: Cardinal); var Unaligned: Cardinal; Chunks: Cardinal; Aligned128Size: Cardinal; Idx: Integer; AlignedSrc: Pointer; begin {$IFOPT R+} {$DEFINE RANGEON} {$R-} // Turn range checks off {$ELSE} {$UNDEF RANGEON} {$ENDIF} // Buggy range checker off // Unaligned bytes for reading Unaligned := (16 - (Cardinal(Src) and 15)) and 15; // Copy First Max 15 Bytes of Unaligned Data if Unaligned > 0 then for Idx := 0 to Unaligned - 1 do TSapByteArray(src)[Idx] := 0; // Do the heavy 128 byte Chunks Chunks := (Size - Unaligned) shr 7; AlignedSrc := Pointer(Cardinal(src) + UnAligned); // Fill 128 bytes chunks Aligned if Chunks > 0 then SSE2AlignedMemFill128(AlignedSrc, Chunks); // Fill remainder in 16 byte chunks Aligned128Size := Chunks shl 7; AlignedSrc := Pointer(Cardinal(AlignedSrc) + Aligned128Size); Chunks := (Size - Unaligned - Aligned128Size) shr 4; if Chunks > 0 then SSE2AlignedMemFill16(AlignedSrc, Chunks); AlignedSrc := Pointer(Cardinal(AlignedSrc) + (Chunks shl 4)); for Idx := 0 to Integer(Cardinal(Size - (Cardinal(AlignedSrc) - Cardinal(Src)))) - 1 do TSapByteArray(AlignedSrc)[Idx] := 0; {$IFDEF RANGEON} // If range checking was on before turning it off {$R+} // Turn range checks back on {$UNDEF RANGEON} {$ENDIF} end; function CPUSupportsSSE2: Boolean; begin Result := False; try asm mov eax, 1 db $0F,$A2 // CPUId Test edx,(1 shl 26) jz @Exit mov Result,1 @Exit: end; except // Ignore errors and assume NO SSE end; end; initialization IsSSE2Supported := CPUSupportsSSE2; end.
unit Storage; interface uses Forms, Controls, Registry, TypInfo, Classes; // helpers procedure LoadWindowState(Form: TForm); procedure SaveWindowState(Form: TForm); type TStorage = class public constructor Create(Section: string); destructor Destroy; override; procedure WriteInteger(Ident: string; Value: Integer); procedure WriteBool(Ident: string; Value: Boolean); procedure WriteString(Ident: string; Value: string); function ReadInteger(Ident: string; Default: Longint): Integer; function ReadBool(Ident: string; Default: Boolean): Boolean; function ReadString(Ident: string; Default: string): string; protected FStorage: TRegIniFile; FSection: string; private procedure OpenKey; procedure CloseKey; end; TComponentStorage = class(TStorage) public constructor Create(Section: string; Component: TComponent); procedure SavePos; procedure LoadPos; procedure SaveSize; procedure LoadSize; procedure SaveProp(PropName: string); procedure LoadProp(PropName: string); procedure SaveComponentProp(Component: TComponent; PropName: string); procedure LoadComponentProp(Component: TComponent; PropName: string); procedure SaveCollectionItemsProp(Component: TComponent; Collection: TCollection; PropName: string); procedure LoadCollectionItemsProp(Component: TComponent; Collection: TCollection; PropName: string); procedure SaveAllComponentProp(ComponentClass: TComponentClass; PropName: string); procedure LoadAllComponentProp(ComponentClass: TComponentClass; PropName: string); protected FComponent: TComponent; end; TFormStorage = class(TComponentStorage) public constructor Create(Form: TForm); procedure SaveWindowState; procedure LoadWindowState; end; implementation uses SysUtils; { helpers } procedure LoadWindowState(Form: TForm); var FStorage: TFormStorage; begin FStorage := TFormStorage.Create(Form); FStorage.LoadWindowState; FStorage.Free; end; procedure SaveWindowState(Form: TForm); var FStorage: TFormStorage; begin FStorage := TFormStorage.Create(Form); FStorage.SaveWindowState; FStorage.Free; end; { TStorage } constructor TStorage.Create(Section: string); begin FSection := Section; end; destructor TStorage.Destroy; begin end; procedure TStorage.OpenKey; begin FStorage := TRegIniFile.Create('Software\Restoran'); end; procedure TStorage.CloseKey; begin FStorage.Free; end; function TStorage.ReadBool(Ident: string; Default: Boolean): Boolean; begin OpenKey; Result := FStorage.ReadBool(FSection, Ident, Default); CloseKey; end; function TStorage.ReadInteger(Ident: string; Default: Integer): Integer; begin OpenKey; Result := FStorage.ReadInteger(FSection, Ident, Default); CloseKey; end; procedure TStorage.WriteBool(Ident: string; Value: Boolean); begin OpenKey; FStorage.WriteBool(FSection, Ident, Value); CloseKey; end; procedure TStorage.WriteInteger(Ident: string; Value: Integer); begin OpenKey; FStorage.WriteInteger(FSection, Ident, Value); CloseKey; end; function TStorage.ReadString(Ident, Default: string): string; begin OpenKey; Result := FStorage.ReadString(FSection, Ident, Default); CloseKey; end; procedure TStorage.WriteString(Ident, Value: string); begin OpenKey; FStorage.WriteString(FSection, Ident, Value); CloseKey; end; { TComponentStorage } constructor TComponentStorage.Create(Section: string; Component: TComponent); begin FComponent := Component; inherited Create(Section); end; procedure TComponentStorage.SaveProp(PropName: string); var s: string; begin try s := GetPropValue(FComponent, PropName); WriteString(PropName, s); except end; end; procedure TComponentStorage.LoadProp(PropName: string); var s: string; begin try s := ReadString(PropName, ''); SetPropValue(FComponent, PropName, s); except end; end; procedure TComponentStorage.LoadComponentProp(Component: TComponent; PropName: string); var s: string; begin try s := ReadString(Component.Name + '_' + PropName, ''); SetPropValue(Component, PropName, s); except end; end; procedure TComponentStorage.SaveComponentProp(Component: TComponent; PropName: string); var s: string; begin try s := GetPropValue(Component, PropName); WriteString(Component.Name + '_' + PropName, s); except end; end; procedure TComponentStorage.SaveAllComponentProp(ComponentClass: TComponentClass; PropName: string); var i: Integer; begin for i := 0 to FComponent.ComponentCount - 1 do if FComponent.Components[i] is ComponentClass then SaveComponentProp(FComponent.Components[i], PropName); end; procedure TComponentStorage.LoadAllComponentProp(ComponentClass: TComponentClass; PropName: string); var i: Integer; begin for i := 0 to FComponent.ComponentCount - 1 do if FComponent.Components[i] is ComponentClass then LoadComponentProp(FComponent.Components[i], PropName); end; procedure TComponentStorage.LoadSize; begin LoadProp('Height'); LoadProp('Width'); end; procedure TComponentStorage.SaveSize; begin SaveProp('Height'); SaveProp('Width'); end; procedure TComponentStorage.SavePos; begin SaveProp('Top'); SaveProp('Left'); SaveSize; end; procedure TComponentStorage.LoadPos; begin LoadProp('Top'); LoadProp('Left'); LoadSize; end; procedure TComponentStorage.LoadCollectionItemsProp( Component: TComponent; Collection: TCollection; PropName: string); var i: Integer; s: string; begin for i := 0 to Collection.Count - 1 do begin try s := ReadString(Component.Name + '_' + Collection.ClassName + '_' + IntToStr(i) + '_' + PropName, ''); SetPropValue(Collection.Items[i], PropName, s); except end; end; end; procedure TComponentStorage.SaveCollectionItemsProp( Component: TComponent; Collection: TCollection; PropName: string); var i: Integer; s: string; begin for i := 0 to Collection.Count - 1 do begin try s := GetPropValue(Collection.Items[i], PropName); WriteString(Component.Name + '_' + Collection.ClassName + '_' + IntToStr(i) + '_' + PropName, s); except end; end; end; { TFormStorage } constructor TFormStorage.Create(Form: TForm); begin inherited Create(Form.ClassName, Form); end; procedure TFormStorage.LoadWindowState; begin LoadPos; LoadProp('WindowState'); end; procedure TFormStorage.SaveWindowState; begin SaveProp('WindowState'); if (FComponent is TForm) then if TForm(FComponent).WindowState = wsNormal then SavePos; end; end.
unit UDefaultPresenter; interface uses Windows, Classes, SysUtils, eiTypes, UTypes, UEasyIpService; type TDefaultPresenter = class(TInterfacedObject, IPresenter) private FPlcService: IPlcService; FView: IView; procedure Refresh; procedure RefreshBlock; procedure RefreshInfo; procedure RefreshSingle; procedure WriteSingle; public constructor Create(view: IView); overload; constructor Create(view: IView; plcService: IPlcService); overload; end; implementation constructor TDefaultPresenter.Create(view: IView); begin inherited Create; Self.Create(view, TEasyIpPlcService.Create); end; constructor TDefaultPresenter.Create(view: IView; plcService: IPlcService); begin FView := view; FPlcService := plcService; end; procedure TDefaultPresenter.Refresh; begin case FView.ViewMode of vmSingle: RefreshSingle(); vmBlock: RefreshBlock(); vmInfo: RefreshInfo(); end; end; procedure TDefaultPresenter.RefreshBlock; var returned: DynamicWordArray; values: TStrings; i: int; begin try FView.Status := 'Reading data block ...'; FView.SetValues(TStringList.Create()); returned := FPlcService.ReadBlock(FView.Host, FView.Address, FView.DataType, FView.Length); values := TStringList.Create(); for i := 0 to Length(returned) - 1 do values.Add('FW' + IntToStr(FView.Address + i) + ' - ' + IntToStr(returned[i])); FView.SetValues(values); values.Free(); except on Ex: Exception do FView.Status := Ex.Message; end; end; procedure TDefaultPresenter.RefreshInfo; var returned: EasyIpInfoPacket; values: TStrings; plcType: string; operandSizes: string; i: int; begin try FView.Status := 'Reading device info ...'; FView.SetInfoValues(TStringList.Create()); returned := FPlcService.ReadInfo(FView.Host); values := TStringList.Create(); with values, returned do begin case ControllerType of 1: plcType := 'FST'; 2: plcType := 'MWT'; 3: plcType := 'DOS'; else plcType := 'Unknown'; end; Append('Controller type - ' + plcType); Append('Controller version - ' + IntToHex(ControllerRevisionHigh, 2) + '.' + IntToHex(ControllerRevisioLow, 2)); Append('EasyIp version - ' + IntToStr(EasyIpRevisionHigh) + '.' + IntToStr(EasyIpRevisionLow)); operandSizes := 'Operand sizes - ' + #13#10; for i := 1 to Length(OperandSize) do operandSizes := operandSizes + IntToStr(OperandSize[i]) + #13#10; Append(operandSizes); end; FView.SetInfoValues(values); values.Free(); except on Ex: Exception do FView.Status := Ex.Message; end; end; procedure TDefaultPresenter.RefreshSingle; var returned: Word; begin try FView.Status := 'Reading single value ...'; returned := FPlcService.Read(FView.Host, FView.Address, FView.DataType); FView.Value := returned; except on Ex: Exception do FView.Status := Ex.Message; end; end; procedure TDefaultPresenter.WriteSingle; begin try FView.Status := 'Writing single value ...'; FPlcService.Write(FView.Host, FView.Address, FView.DataType, FView.Value); except on Ex: Exception do FView.Status := Ex.Message; end; end; end.
unit Server.Models.Cadastros.Cidades; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('CIDADES','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TCidades = class(TTabelaBase) private fNOME: String; fORDEM: String; fUF: String; function Getid: Integer; procedure Setid(const Value: Integer); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('NOME', ftString, 100)] [Dictionary('NOME','Mensagem de validação','','','',taLeftJustify)] property NOME: String read fNOME write fNOME; [Column('ORDEM', ftInteger)] property ORDEM:String read fORDEM write fORDEM; [Column('UF', ftString, 150)] property UF:String read fUF write fUF; end; implementation { TCidades } constructor TCidades.create; begin end; destructor TCidades.destroy; begin inherited; end; function TCidades.Getid: Integer; begin Result := fid; end; procedure TCidades.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TCidades); 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) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.restdataset.clientdataset; interface uses Classes, SysUtils, DB, Rtti, DBClient, Variants, Generics.Collections, /// orm ormbr.criteria, ormbr.dataset.base.adapter, ormbr.restdataset.adapter, ormbr.dataset.events, ormbr.factory.interfaces, ormbr.mapping.classes, ormbr.types.mapping, ormbr.objects.helper, ormbr.rtti.helper, ormbr.mapping.exceptions, ormbr.mapping.attributes, ormbr.session.datasnap; type /// <summary> /// Captura de eventos específicos do componente TClientDataSet /// </summary> TRESTClientDataSetEvents = class(TDataSetEvents) private FBeforeApplyUpdates: TRemoteEvent; FAfterApplyUpdates: TRemoteEvent; public property BeforeApplyUpdates: TRemoteEvent read FBeforeApplyUpdates write FBeforeApplyUpdates; property AfterApplyUpdates: TRemoteEvent read FAfterApplyUpdates write FAfterApplyUpdates; end; /// <summary> /// Adapter TClientDataSet para controlar o Modelo e o Controle definido por: /// M - Object Model /// </summary> TRESTClientDataSetAdapter<M: class, constructor> = class(TRESTDataSetAdapter<M>) private FOrmDataSet: TClientDataSet; FClientDataSetEvents: TRESTClientDataSetEvents; procedure DoBeforeApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure DoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); procedure FilterDataSetChilds; protected procedure EmptyDataSetChilds; override; procedure DoBeforeDelete(DataSet: TDataSet); override; procedure GetDataSetEvents; override; procedure SetDataSetEvents; override; procedure OpenAssociation(const ASQL: string); override; procedure OpenIDInternal(const AID: string); override; procedure OpenSQLInternal(const ASQL: string); override; procedure ApplyInserter(const MaxErros: Integer); override; procedure ApplyUpdater(const MaxErros: Integer); override; procedure ApplyDeleter(const MaxErros: Integer); override; procedure ApplyInternal(const MaxErros: Integer); override; procedure ApplyUpdates(const MaxErros: Integer); override; public constructor Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); overload; override; destructor Destroy; override; end; implementation uses ormbr.dataset.bind, ormbr.dataset.fields; { TRESTClientDataSetAdapter<M> } constructor TRESTClientDataSetAdapter<M>.Create(ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); begin inherited Create(ADataSet, APageSize, AMasterObject); /// <summary> /// Captura o component TClientDataset da IDE passado como parâmetro /// </summary> FOrmDataSet := ADataSet as TClientDataSet; FClientDataSetEvents := TRESTClientDataSetEvents.Create; /// <summary> /// Captura e guarda os eventos do dataset /// </summary> GetDataSetEvents; /// <summary> /// Seta os eventos do ORM no dataset, para que ele sejam disparados /// </summary> SetDataSetEvents; /// if not FOrmDataSet.Active then begin FOrmDataSet.CreateDataSet; FOrmDataSet.LogChanges := False; end; end; destructor TRESTClientDataSetAdapter<M>.Destroy; begin FOrmDataSet := nil; FClientDataSetEvents.Free; inherited; end; procedure TRESTClientDataSetAdapter<M>.DoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); begin if Assigned(FClientDataSetEvents.AfterApplyUpdates) then FClientDataSetEvents.AfterApplyUpdates(Sender, OwnerData); end; procedure TRESTClientDataSetAdapter<M>.DoBeforeApplyUpdates(Sender: TObject; var OwnerData: OleVariant); begin if Assigned(FClientDataSetEvents.BeforeApplyUpdates) then FClientDataSetEvents.BeforeApplyUpdates(Sender, OwnerData); end; procedure TRESTClientDataSetAdapter<M>.DoBeforeDelete(DataSet: TDataSet); begin inherited DoBeforeDelete(DataSet); /// <summary> /// Deleta registros de todos os DataSet filhos /// </summary> EmptyDataSetChilds; end; procedure TRESTClientDataSetAdapter<M>.EmptyDataSetChilds; var LChild: TDataSetBaseAdapter<M>; begin inherited; for LChild in FMasterObject.Values do begin if TRESTClientDataSetAdapter<M>(LChild).FOrmDataSet.Active then TRESTClientDataSetAdapter<M>(LChild).FOrmDataSet.EmptyDataSet; end; end; procedure TRESTClientDataSetAdapter<M>.FilterDataSetChilds; var LRttiType: TRttiType; LAssociations: TAssociationMappingList; LAssociation: TAssociationMapping; LDataSetChild: TDataSetBaseAdapter<M>; LFor: Integer; LFields: string; LIndexFields: string; begin if FOrmDataSet.Active then begin LAssociations := FExplorer.GetMappingAssociation(FCurrentInternal.ClassType); if LAssociations <> nil then begin for LAssociation in LAssociations do begin if LAssociation.PropertyRtti.isList then LRttiType := LAssociation.PropertyRtti.GetTypeValue(LAssociation.PropertyRtti.PropertyType) else LRttiType := LAssociation.PropertyRtti.PropertyType; if FMasterObject.ContainsKey(LRttiType.AsInstance.MetaclassType.ClassName) then begin LDataSetChild := FMasterObject.Items[LRttiType.AsInstance.MetaclassType.ClassName]; LFields := ''; LIndexFields := ''; try TClientDataSet(LDataSetChild.FOrmDataSet).MasterSource := FOrmDataSource; for LFor := 0 to LAssociation.ColumnsName.Count -1 do begin LFields := LFields + LAssociation.ColumnsNameRef[LFor]; LIndexFields := LIndexFields + LAssociation.ColumnsName[LFor]; if LAssociation.ColumnsName.Count -1 > LFor then begin LFields := LFields + '; '; LIndexFields := LIndexFields + '; '; end; end; TClientDataSet(LDataSetChild.FOrmDataSet).IndexFieldNames := LIndexFields; TClientDataSet(LDataSetChild.FOrmDataSet).MasterFields := LFields; finally end; end; end; end; end; end; procedure TRESTClientDataSetAdapter<M>.GetDataSetEvents; begin inherited; if Assigned(FOrmDataSet.BeforeApplyUpdates) then FClientDataSetEvents.BeforeApplyUpdates := FOrmDataSet.BeforeApplyUpdates; if Assigned(FOrmDataSet.AfterApplyUpdates) then FClientDataSetEvents.AfterApplyUpdates := FOrmDataSet.AfterApplyUpdates; end; procedure TRESTClientDataSetAdapter<M>.OpenAssociation(const ASQL: string); begin OpenSQLInternal(ASQL); end; procedure TRESTClientDataSetAdapter<M>.OpenIDInternal(const AID: string); begin FOrmDataSet.DisableControls; DisableDataSetEvents; try FOrmDataSet.EmptyDataSet; inherited; FSession.OpenID(AID); /// <summary> /// Filtra os registros nas sub-tabelas /// </summary> if FOwnerMasterObject = nil then FilterDataSetChilds; finally EnableDataSetEvents; FOrmDataSet.First; FOrmDataSet.EnableControls; end; end; procedure TRESTClientDataSetAdapter<M>.OpenSQLInternal(const ASQL: string); begin FOrmDataSet.DisableControls; DisableDataSetEvents; try FOrmDataSet.EmptyDataSet; inherited; FSession.OpenSQL(ASQL); /// <summary> /// Filtra os registros nas sub-tabelas /// </summary> if FOwnerMasterObject = nil then FilterDataSetChilds; finally EnableDataSetEvents; FOrmDataSet.First; FOrmDataSet.EnableControls; end; end; procedure TRESTClientDataSetAdapter<M>.ApplyInternal(const MaxErros: Integer); var LRecnoBook: TBookmark; LProperty: TRttiProperty; begin LRecnoBook := FOrmDataSet.Bookmark; FOrmDataSet.DisableControls; DisableDataSetEvents; try ApplyInserter(MaxErros); ApplyUpdater(MaxErros); ApplyDeleter(MaxErros); finally FOrmDataSet.GotoBookmark(LRecnoBook); FOrmDataSet.FreeBookmark(LRecnoBook); FOrmDataSet.EnableControls; EnableDataSetEvents; end; end; procedure TRESTClientDataSetAdapter<M>.ApplyDeleter(const MaxErros: Integer); var LFor: Integer; begin inherited; /// Filtar somente os registros excluídos if FSession.DeleteList.Count > 0 then begin for LFor := 0 to FSession.DeleteList.Count -1 do FSession.Delete(FSession.DeleteList.Items[LFor]); end; end; procedure TRESTClientDataSetAdapter<M>.ApplyInserter(const MaxErros: Integer); var LColumn: TColumnMapping; begin inherited; /// Filtar somente os registros inseridos FOrmDataSet.Filter := cInternalField + '=' + IntToStr(Integer(dsInsert)); FOrmDataSet.Filtered := True; FOrmDataSet.First; try while FOrmDataSet.RecordCount > 0 do begin /// Append/Insert if TDataSetState(FOrmDataSet.Fields[FInternalIndex].AsInteger) in [dsInsert] then begin /// <summary> /// Ao passar como parametro a propriedade Current, e disparado o metodo /// que atualiza a var FCurrentInternal, para ser usada abaixo. /// </summary> FSession.Insert(Current); FOrmDataSet.Edit; // if FSession.ExistSequence then // begin // for LColumn in FCurrentInternal.GetPrimaryKey do // begin // FOrmDataSet.Fields[LColumn.GetIndex].Value := LColumn.GetNullableValue(TObject(FCurrentInternal)).AsVariant; // /// <summary> // /// Atualiza o valor do AutoInc nas sub tabelas // /// </summary> // SetAutoIncValueChilds(FOrmDataSet.Fields[LColumn.GetIndex]); // end; // end; FOrmDataSet.Fields[FInternalIndex].AsInteger := -1; FOrmDataSet.Post; end; end; finally FOrmDataSet.Filtered := False; FOrmDataSet.Filter := ''; end; end; procedure TRESTClientDataSetAdapter<M>.ApplyUpdater(const MaxErros: Integer); var LProperty: TRttiProperty; begin inherited; /// Filtar somente os registros modificados FOrmDataSet.Filter := cInternalField + '=' + IntToStr(Integer(dsEdit)); FOrmDataSet.Filtered := True; FOrmDataSet.First; try while FOrmDataSet.RecordCount > 0 do begin /// Edit if TDataSetState(FOrmDataSet.Fields[FInternalIndex].AsInteger) in [dsEdit] then begin if FSession.ModifiedFields.Count > 0 then FSession.Update(Current, M.ClassName); FOrmDataSet.Edit; FOrmDataSet.Fields[FInternalIndex].AsInteger := -1; FOrmDataSet.Post; end; end; finally FOrmDataSet.Filtered := False; FOrmDataSet.Filter := ''; end; end; procedure TRESTClientDataSetAdapter<M>.ApplyUpdates(const MaxErros: Integer); var LDetail: TPair<string, TDataSetBaseAdapter<M>>; LOwnerData: OleVariant; begin inherited; try /// Before Apply DoBeforeApplyUpdates(FOrmDataSet, LOwnerData); ApplyInternal(MaxErros); /// Apply Details for LDetail in FMasterObject do LDetail.Value.ApplyInternal(MaxErros); /// After Apply DoAfterApplyUpdates(FOrmDataSet, LOwnerData); finally /// <summary> /// Lista os fields alterados a lista para novas alterações /// </summary> FSession.ModifiedFields.Items[M.ClassName].Clear; FSession.DeleteList.Clear; end; end; procedure TRESTClientDataSetAdapter<M>.SetDataSetEvents; begin inherited; FOrmDataSet.BeforeApplyUpdates := DoBeforeApplyUpdates; FOrmDataSet.AfterApplyUpdates := DoAfterApplyUpdates; end; end.
unit USistemaControle; interface uses UControle, SqlExpr, Controls, DBClient, DBXCommon, Classes; type TSistemaControle = class (TControle) private FCurrentTransaction: TDBXTransaction; protected property CurrentTransaction: TDBXTransaction read FCurrentTransaction; public constructor Create(SQLConnection: TSQLConnection); override; destructor Destroy; override; procedure CopiarQuery(const Message: string); function StartNewTransaction: TDBXTransaction; overload; function StartNewTransaction(const Isolation: integer): TDBXTransaction; overload; function InTransaction: boolean; procedure StartTransaction; overload; procedure StartTransaction(const Isolation: integer); overload; procedure Commit(var Transaction: TDBXTransaction); overload; procedure Commit; overload; procedure Rollback(var Transaction: TDBXTransaction); overload; procedure Rollback; overload; procedure ReportFileDeviceCreate(Sender: TObject); // published // property MesAno: TMesAno read FMesAno write FMesAno; end; var Sistema: TSistemaControle; implementation uses Clipbrd, ppReport, ppTypes, ppXlsDevice; { TSistemaControle } procedure TSistemaControle.Commit(var Transaction: TDBXTransaction); begin Self.SQLConnection.CommitFreeAndNil(Transaction); end; procedure TSistemaControle.Commit; begin if Self.InTransaction then Self.Commit(Self.FCurrentTransaction); end; procedure TSistemaControle.CopiarQuery(const Message: string); begin Clipboard.AsText := Message; end; constructor TSistemaControle.Create(SQLConnection: TSQLConnection); begin inherited; // FMesAno := TMesAno.Create(Date); // IMesAno(FMesAno)._AddRef; end; destructor TSistemaControle.Destroy; begin inherited; end; function TSistemaControle.InTransaction: boolean; begin Result := Self.SQLConnection.InTransaction; end; procedure TSistemaControle.ReportFileDeviceCreate(Sender: TObject); begin if TppReport(Sender).FileDevice is TppXlsDeviceBase then begin TppReport(Sender).XLSSettings.ExportComponents := [ecText, ecImage, ecRichText, ecBarCode, ecTable, ecOther]; TppReport(Sender).XLSSettings.IncludeSingleHeader := True; end; if TppReport(Sender).FileDevice is TppXlsDataDevice then begin TppXlsDataDevice(TppReport(Sender).FileDevice).DefaultBands := [btDetail, btGroupHeader, btGroupFooter, btSummary]; // TppReportFunctions.ConfigureXLSDataExport(TppReport(Sender)); end; end; procedure TSistemaControle.Rollback; begin if Self.InTransaction then Self.Rollback(Self.FCurrentTransaction); end; procedure TSistemaControle.Rollback(var Transaction: TDBXTransaction); begin if Self.SQLConnection.InTransaction then Self.SQLConnection.RollbackFreeAndNil(Transaction); end; function TSistemaControle.StartNewTransaction: TDBXTransaction; begin Result := Self.SQLConnection.BeginTransaction; end; procedure TSistemaControle.StartTransaction; begin Self.FCurrentTransaction := Self.StartNewTransaction; end; function TSistemaControle.StartNewTransaction( const Isolation: integer): TDBXTransaction; begin Result := Self.SQLConnection.BeginTransaction(Isolation); end; procedure TSistemaControle.StartTransaction(const Isolation: integer); begin Self.FCurrentTransaction := Self.StartNewTransaction(Isolation); end; initialization end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Label2: TLabel; Label1: TLabel; Edit1: TEdit; Edit2: TEdit; Memo1: TMemo; Button1: TButton; RadioGroup1: TRadioGroup; Button2: TButton; procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses Math; procedure TForm1.Button2Click(Sender: TObject); begin Memo1.Clear; end; procedure TForm1.Button1Click(Sender: TObject); VAR a,x,y,f :Double; begin try x := StrToFloat(Edit1.Text); y := StrToFloat(Edit2.Text); except Exit; end; case RadioGroup1.ItemIndex of -1: exit; 0: f := sinh(x); 1: f := x*x; 2: f := exp(x); end; try if (x*y > 0) then a := SQR(f + y) - SQRT(f * y) else if (x*y < 0) then a := SQR(f + y) - SQRT(abs(f * y)) else a := SQR(f + y) + 1; except exit; end; Memo1.Lines.Add('A=' + FloatToStr(a)); end; end.
unit uSettings; interface uses Windows, Classes, IniFiles, SysUtils; procedure ReadIniParams; procedure WriteIniParams; type TSettings = class(TObject) public Active: boolean; UseNumThreadsFromProg: boolean; UseNumThreadsPlug: boolean; CountThreads: integer; TimeRecognition: integer; MethodRecognition: integer; UseAntigateKey: boolean; UseAntigateKeyFromProg: boolean; AntigateKey: string; RecognitionProg: string; CapIniFile: string; CatalogLetters: string; phrase: boolean; regsense: boolean; numeric: integer; calc: boolean; min_len: integer; max_len: integer; MainPControl: integer; UsePremium: boolean; LoginPremium: string; PasswordPremium: string; RecPControl: integer; SkinName: string; SkinDirectory: string; SkinActive: boolean; Saturation: integer; Hue: integer; NumUsualSect: integer; NumProxySect: integer; SubstituteProxySection: boolean; end; var Settings: TSettings; implementation uses uFunctions; procedure ReadIniParams; var IniFile: TIniFile; Buffer: array [byte] of char; NamePlugin: string; PathPlugin: string; PathApplication: string; begin if GetModuleFileName(hInstance, @Buffer, SizeOf(Buffer) - 1) > 0 then NamePlugin := ExtractFileName(StrPas(Buffer)); IniFile := TIniFile.Create(ExtractFilePath(GetModuleFileNameStr(0)) + 'plugins.ini'); if IniFile.SectionExists(NamePlugin) then begin Settings.Active := IniFile.ReadBool(NamePlugin, 'Active', true); Settings.UseNumThreadsFromProg := IniFile.ReadBool(NamePlugin, 'CountThreadsProg', false); Settings.UseNumThreadsPlug := IniFile.ReadBool(NamePlugin, 'CountThreadsPlug', true); Settings.CountThreads := IniFile.ReadInteger(NamePlugin, 'CountThreads', 100); Settings.TimeRecognition := IniFile.ReadInteger(NamePlugin, 'TimeRecognition', 120000); Settings.MethodRecognition := IniFile.ReadInteger(NamePlugin, 'MethodRecognition', 0); Settings.UseAntigateKey := IniFile.ReadBool(NamePlugin, 'UseAntigateKey', false); Settings.UseAntigateKeyFromProg := IniFile.ReadBool(NamePlugin, 'UseAntigateKeyFromProg', true); Settings.AntigateKey := IniFile.ReadString(NamePlugin, 'AntigateKey', ''); Settings.RecognitionProg := IniFile.ReadString(NamePlugin, 'RecognitionProg', ''); Settings.CapIniFile := IniFile.ReadString(NamePlugin, 'CapIniFile', ''); Settings.CatalogLetters := IniFile.ReadString(NamePlugin, 'CatalogLetters', ''); Settings.phrase := IniFile.ReadBool(NamePlugin, 'phrase', false); Settings.regsense := IniFile.ReadBool(NamePlugin, 'regsense', false); Settings.numeric := IniFile.ReadInteger(NamePlugin, 'numeric', 0); Settings.calc := IniFile.ReadBool(NamePlugin, 'calc', false); Settings.min_len := IniFile.ReadInteger(NamePlugin, 'min_len', 0); Settings.max_len := IniFile.ReadInteger(NamePlugin, 'max_len', 0); Settings.MainPControl := IniFile.ReadInteger(NamePlugin, 'MainPControl', 0); Settings.UsePremium := IniFile.ReadBool(NamePlugin, 'UsePremium', false); Settings.LoginPremium := IniFile.ReadString(NamePlugin, 'LoginPremium', ''); Settings.PasswordPremium := IniFile.ReadString(NamePlugin, 'PasswordPremium', ''); Settings.RecPControl := IniFile.ReadInteger(NamePlugin, 'RecPControl', 0); Settings.NumUsualSect := IniFile.ReadInteger(NamePlugin, 'NumUsualSect', 0); Settings.NumProxySect := IniFile.ReadInteger(NamePlugin, 'NumProxySect', 0); Settings.SubstituteProxySection := IniFile.ReadBool(NamePlugin, 'SubstituteProxySection', true); IniFile.Free; end else begin IniFile.Free; Settings.Active := true; Settings.UseNumThreadsFromProg := false; Settings.UseNumThreadsPlug := true; Settings.CountThreads := 100; Settings.TimeRecognition := 120000; Settings.MethodRecognition := 0; Settings.UseAntigateKey := false; Settings.UseAntigateKeyFromProg := true; Settings.AntigateKey := ''; Settings.RecognitionProg := ''; Settings.CapIniFile := ''; Settings.CatalogLetters := ''; Settings.phrase := false; Settings.regsense := false; Settings.numeric := 0; Settings.calc := false; Settings.min_len := 0; Settings.max_len := 0; Settings.MainPControl := 0; Settings.UsePremium := false; Settings.LoginPremium := ''; Settings.PasswordPremium := ''; Settings.RecPControl := 0; Settings.NumUsualSect := 0; Settings.NumProxySect := 0; Settings.SubstituteProxySection := true; WriteIniParams; end; end; procedure WriteIniParams; var IniFile: TIniFile; Buffer: array [byte] of char; NamePlugin: string; begin if GetModuleFileName(hInstance, @Buffer, SizeOf(Buffer) - 1) > 0 then begin NamePlugin := ExtractFileName(StrPas(Buffer)); end; IniFile := TIniFile.Create(ExtractFilePath(GetModuleFileNameStr(0)) + 'plugins.ini'); IniFile.WriteBool(NamePlugin, 'Active', Settings.Active); IniFile.WriteBool(NamePlugin, 'CountThreadsProg', Settings.UseNumThreadsFromProg); IniFile.WriteBool(NamePlugin, 'CountThreadsPlug', Settings.UseNumThreadsPlug); IniFile.WriteInteger(NamePlugin, 'CountThreads', Settings.CountThreads); IniFile.WriteInteger(NamePlugin, 'TimeRecognition', Settings.TimeRecognition); IniFile.WriteInteger(NamePlugin, 'MethodRecognition', Settings.MethodRecognition); IniFile.WriteBool(NamePlugin, 'UseAntigateKey', Settings.UseAntigateKey); IniFile.WriteBool(NamePlugin, 'UseAntigateKeyFromProg', Settings.UseAntigateKeyFromProg); IniFile.WriteString(NamePlugin, 'AntigateKey', Settings.AntigateKey); IniFile.WriteString(NamePlugin, 'RecognitionProg', Settings.RecognitionProg); IniFile.WriteString(NamePlugin, 'CapIniFile', Settings.CapIniFile); IniFile.WriteString(NamePlugin, 'CatalogLetters', Settings.CatalogLetters); IniFile.WriteBool(NamePlugin, 'phrase', Settings.phrase); IniFile.WriteBool(NamePlugin, 'regsense', Settings.regsense); IniFile.WriteBool(NamePlugin, 'calc', Settings.calc); IniFile.WriteInteger(NamePlugin, 'numeric', Settings.numeric); IniFile.WriteInteger(NamePlugin, 'min_len', Settings.min_len); IniFile.WriteInteger(NamePlugin, 'max_len', Settings.max_len); IniFile.WriteInteger(NamePlugin, 'MainPControl', Settings.MainPControl); IniFile.WriteBool(NamePlugin, 'UsePremium', Settings.UsePremium); IniFile.WriteString(NamePlugin, 'LoginPremium', Settings.LoginPremium); IniFile.WriteString(NamePlugin, 'PasswordPremium', Settings.PasswordPremium); IniFile.WriteInteger(NamePlugin, 'RecPControl', Settings.RecPControl); IniFile.WriteInteger(NamePlugin, 'NumUsualSect', Settings.NumUsualSect); IniFile.WriteInteger(NamePlugin, 'NumProxySect', Settings.NumProxySect); IniFile.WriteBool(NamePlugin, 'SubstituteProxySection', Settings.SubstituteProxySection); IniFile.Free; end; end.
{***************************************************************************} { } { DelphiWebDriver } { } { Copyright 2017 inpwtepydjuf@gmail.com } { } {***************************************************************************} { } { 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 Commands.DeleteSession; interface uses Sessions, Vcl.Forms, CommandRegistry, HttpServerCommand; type /// <summary> /// Handles 'DELETE' '/session/(.*)' /// </summary> TDeleteSessionCommand = class(TRestCommand) public class function GetCommand: String; override; class function GetRoute: String; override; procedure Execute(AOwner: TForm); override; end; implementation uses System.SysUtils, Commands; procedure TDeleteSessionCommand.Execute(AOwner: TForm); begin try // Need to delete it! Commands.Sessions.DeleteSession(self.Params[1]); except on e: Exception do Error(404); end; end; class function TDeleteSessionCommand.GetCommand: String; begin result := 'DELETE'; end; class function TDeleteSessionCommand.GetRoute: String; begin result := '/session/(.*)'; end; end.
unit CommonfrmCDBDump_FreeOTFE; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, PasswordRichEdit, Spin64, OTFEFreeOTFEBase_U, Buttons, SDUForms, SDUFrames, SDUSpin64Units, SDUFilenameEdit_U, SDUDialogs, OTFEFreeOTFE_VolumeSelect, CommonfrmCDBDump_Base; type TfrmCDBDump_FreeOTFE = class(TfrmCDBDump_Base) lblOffset: TLabel; seSaltLength: TSpinEdit64; lblSaltLengthBits: TLabel; lblSaltLength: TLabel; seKeyIterations: TSpinEdit64; lblKeyIterations: TLabel; se64UnitOffset: TSDUSpin64Unit_Storage; preUserKey: TPasswordRichEdit; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure ControlChanged(Sender: TObject); procedure pbOKClick(Sender: TObject); private function GetUserKey(): string; function GetOffset(): int64; function GetSaltLength(): integer; function GetKeyIterations(): integer; protected procedure EnableDisableControls(); override; function DumpLUKSDataToFile(): boolean; override; public property UserKey: string read GetUserKey; property Offset: int64 read GetOffset; property SaltLength: integer read GetSaltLength; property KeyIterations: integer read GetKeyIterations; end; implementation {$R *.DFM} uses SDUi18n, SDUGeneral; function TfrmCDBDump_FreeOTFE.GetUserKey(): string; begin Result := preUserKey.Text; end; function TfrmCDBDump_FreeOTFE.GetOffset(): int64; begin Result := se64UnitOffset.Value; end; function TfrmCDBDump_FreeOTFE.GetSaltLength(): integer; begin Result := seSaltLength.Value; end; function TfrmCDBDump_FreeOTFE.GetKeyIterations(): integer; begin Result := seKeyIterations.Value; end; procedure TfrmCDBDump_FreeOTFE.FormCreate(Sender: TObject); begin inherited; self.caption := _('Dump Critical Data Block'); preUserKey.Plaintext := TRUE; // FreeOTFE volumes CAN have newlines in the user's password preUserKey.WantReturns := TRUE; preUserKey.WordWrap := TRUE; preUserKey.Lines.Clear(); preUserKey.PasswordChar := '*'; // se64UnitOffset set in OnShow event (otherwise units not shown correctly) seSaltLength.Increment := 8; seSaltLength.Value := DEFAULT_SALT_LENGTH; seKeyIterations.MinValue := 1; seKeyIterations.MaxValue := 999999; // Need *some* upper value, otherwise setting MinValue won't work properly seKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT; seKeyIterations.Value := DEFAULT_KEY_ITERATIONS; end; procedure TfrmCDBDump_FreeOTFE.EnableDisableControls(); begin pbOK.Enabled := ( (VolumeFilename <> '') AND (feDumpFilename.Filename <> '') AND (feDumpFilename.Filename <> VolumeFilename) AND // Don't overwrite the volume with the dump!!! (KeyIterations > 0) ); end; procedure TfrmCDBDump_FreeOTFE.FormShow(Sender: TObject); begin inherited; se64UnitOffset.Value := 0; EnableDisableControls(); end; procedure TfrmCDBDump_FreeOTFE.ControlChanged(Sender: TObject); begin EnableDisableControls(); end; function TfrmCDBDump_FreeOTFE.DumpLUKSDataToFile(): boolean; begin Result := OTFEFreeOTFE.DumpCriticalDataToFile( VolumeFilename, Offset, UserKey, SaltLength, // In bits KeyIterations, DumpFilename ); end; procedure TfrmCDBDump_FreeOTFE.pbOKClick(Sender: TObject); var {$IFDEF FREEOTFE_TIME_CDB_DUMP} startTime: TDateTime; stopTime: TDateTime; diffTime: TDateTime; Hour, Min, Sec, MSec: Word; {$ENDIF} dumpOK: boolean; notepadCommandLine: string; begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} startTime := Now(); {$ENDIF} dumpOK := DumpLUKSDataToFile(); if dumpOK then begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} stopTime := Now(); diffTime := (stopTime - startTime); DecodeTime(diffTime, Hour, Min, Sec, MSec); showmessage('Time taken to dump CDB: '+inttostr(Hour)+' hours, '+inttostr(Min)+' mins, '+inttostr(Sec)+'.'+inttostr(MSec)+' secs'); {$ENDIF} if (SDUMessageDlg( _('A human readable copy of your critical data block has been written to:')+SDUCRLF+ SDUCRLF+ DumpFilename+SDUCRLF+ SDUCRLF+ _('Do you wish to open this file in Windows Notepad?'), mtInformation, [mbYes,mbNo], 0) = mrYes) then begin notepadCommandLine := 'notepad '+DumpFilename; if (WinExec(PChar(notepadCommandLine), SW_RESTORE))<31 then begin SDUMessageDlg(_('Error running Notepad'), mtError, [], 0); end; end; ModalResult := mrOK; end else begin {$IFDEF FREEOTFE_TIME_CDB_DUMP} stopTime := Now(); diffTime := (stopTime - startTime); DecodeTime(diffTime, Hour, Min, Sec, MSec); showmessage('Time taken to FAIL to dump CDB: '+inttostr(Hour)+' hours, '+inttostr(Min)+' mins, '+inttostr(Sec)+'.'+inttostr(MSec)+' secs'); {$ENDIF} SDUMessageDlg( _('Unable to dump out critical data block.')+SDUCRLF+ SDUCRLF+ _('Please ensure that your password and details are entered correctly, and that this file is not currently in use (e.g. mounted)'), mtError, [mbOK], 0); end; end; END.
(*======================================================================* | cmpPersistentOptions | | | | TRegistryPersistentOptions & TIniFilePersistentOptions components | | | | 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. | | | | Copyright © Colin Wilson 2003 All Rights Reserved | | | Version Date By Description | | ------- ---------- ---- ------------------------------------------| | 1.0 10/09/2003 CPWW Original | | 2.0 27/04/2004 CPWW Added impersonation so that interactive | | services can access HKEY_CURRENT_USER | | for the logged-on user. | *======================================================================*) unit cmpPersistentOptions; interface uses Windows, SysUtils, Classes, unitExSettings; const systemUser = 'SYSTEM'; type TOptions = class; TSections = class; TPersistentOptions = class; TOptionType = (otInteger, otBoolean, otString, otEnum); //--------------------------------------------------------------------- // TOption class. TOption = class (TCollectionItem) private fDefaultValue: string; fName: string; fEnumValues: TStringList; fOptionType: TOptionType; fIntVal : Integer; fStrVal : string; fBoolVal : boolean; fDirty : boolean; function GetBase: TPersistentOptions; function GetAsBoolean: Boolean; function GetAsInteger: Integer; function GetAsString: string; function GetAsEnum: string; procedure SetEnumValues(const Value: TStrings); function GetEnumValues: TStrings; procedure SetOptionType(const Value: TOptionType); procedure SetAsBoolean(const Value: Boolean); procedure SetAsEnum(const Value: string); procedure SetAsInteger(const Value: Integer); procedure SetAsString(const Value: string); procedure Flush; function GetHasDefaultValue: boolean; protected function GetDisplayName : string; override; public constructor Create (Collection : TCollection); override; destructor Destroy; override; property Base : TPersistentOptions read GetBase; property AsInteger : Integer read GetAsInteger write SetAsInteger; property AsString : string read GetAsString write SetAsString; property AsBoolean : Boolean read GetAsBoolean write SetAsBoolean; property AsEnum : string read GetAsEnum write SetAsEnum; property HasDefaultValue : boolean read GetHasDefaultValue; published property Name : string read fName write fName; property DefaultValue : string read fDefaultValue write fDefaultValue; property EnumValues : TStrings read GetEnumValues write SetEnumValues; property OptionType : TOptionType read fOptionType write SetOptionType; end; //--------------------------------------------------------------------- // TOptions class - a collection of options TOptions = class (TOwnedCollection) private fDeleteObsoleteOptions: boolean; function GetOption(idx: Integer): TOption; function GetOptionByName(const name: string): TOption; public constructor Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); property Option [idx : Integer] : TOption read GetOption; default; property OptionByName [const name : string] : TOption read GetOptionByName; published property DeleteObsoleteOptions : boolean read fDeleteObsoleteOptions write fDeleteObsoleteOptions default True; end; //--------------------------------------------------------------------- // TSection class TSection = class (TCollectionItem) private fName: string; fOptions: TOptions; fSections: TSections; function GetOption(const name: string): TOption; function GetSection(const name: string): TSection; protected function GetDisplayName : string; override; public constructor Create(Collection: TCollection); override; destructor Destroy; override; property Option [const name : string] : TOption read GetOption; property Section [const name : string] : TSection read GetSection; published property Name : string read fName write fName; property Options : TOptions read fOptions write fOptions; property Sections : TSections read fSections write fSections; end; //--------------------------------------------------------------------- // TSections class - a collection of sections. TSections = class (TOwnedCollection) private fDeleteObsoleteSections: boolean; function GetSection(idx: Integer): TSection; function GetSectionByName(const name: string): TSection; public property Section [idx : Integer] : TSection read GetSection; default; property SectionByName [const name : string] : TSection read GetSectionByName; published property DeleteObsoleteSections : boolean read fDeleteObsoleteSections write fDeleteObsoleteSections default False; end; //--------------------------------------------------------------------- // TPersistentOptions - base class for TRegistryPersistentOptions and // TIniFilePersistentOptions TPersistentOptions = class(TComponent) private function GetPersist: boolean; function GetLoading: boolean; private fManufacturer: string; fApplication: string; fVersion: string; fOptions: TOptions; fSections: TSections; fUpdating: boolean; function GetDesigning: boolean; function GetOption(path: string): TOption; function GetSection(name: string): TSection; procedure SetApplication(const Value: string); procedure SetManufacturer(const Value: string); procedure SetVersion(const Value: string); procedure RemoveLeadingSlash (var path : string); property Designing : boolean read GetDesigning; property Loading : boolean read GetLoading; property Persist : boolean read GetPersist; function GetDirty: boolean; { Private declarations } protected procedure Loaded; override; procedure DeleteOldOptions (const application, manufacturer, version : string); virtual; abstract; property InUpdate : boolean read fUpdating; public constructor Create (AOwner : TComponent); override; destructor Destroy; override; procedure Save; virtual; abstract; procedure Load; virtual; abstract; procedure BeginUpdate; procedure EndUpdate; property Option [path : string] : TOption read GetOption; default; property Section [name : string] : TSection read GetSection; property Dirty : boolean read GetDirty; { Public declarations } published property Application : string read fApplication write SetApplication; property Manufacturer : string read fManufacturer write SetManufacturer; property Version : string read fVersion write SetVersion; property Options : TOptions read fOptions write fOptions; property Sections : TSections read fSections write fSections; end; TCustomPersistentOptions = class (TPersistentOptions) private fOptionsType: TExSettingsType; procedure LoadOptions (settings : TExSettings; Options : TOptions; forceDefaults : boolean); procedure LoadSections (settings : TExSettings; Sections : TSections; forceDefaults : boolean); procedure SaveOptions (settings : TExSettings; Options : TOptions); procedure SaveSections (settings : TExSettings; Sections : TSections); protected procedure DeleteOldOptions (const application, manufacturer, version : string); override; property OptionsType : TExSettingsType read fOptionsType write fOptionsType; function GetSettingsClass : TExSettingsClass; virtual; abstract; function GetSettingsFile : string; virtual; procedure SettingsCreated (settings : TExSettings); virtual; public procedure Load; override; procedure Save; override; published end; TOnGetSettingsClass = procedure (sender : TObject; var settingsType : TExSettingsClass) of object; TOnGetSettingsFile = procedure (sender : TObject; var fileName : string) of object; TUniPersistentOptions = class (TCustomPersistentOptions) private fOnGetSettingsClass: TOnGetSettingsClass; fOnGetSettingsFile: TOnGetSettingsFile; protected function GetSettingsClass : TExSettingsClass; override; function GetSettingsFile : string; override; published property OptionsType; property OnGetSettingsClass : TOnGetSettingsClass read fOnGetSettingsClass write fOnGetSettingsClass; property OnGetSettingsFile : TOnGetSettingsFile read fOnGetSettingsFile write fOnGetSettingsFile; end; EOptionError = class (Exception) end; EOptionTypeMismatch = class (EOptionError) public constructor Create (Option : TOption); end; resourcestring rstNoAppName = 'Application property can not be blank'; implementation uses unitExFileSettings; resourcestring rstNotEnum = 'Not an enum type'; rstTypeMismatch = '%s is not of %s type'; rstSectionNotFound = 'Section %s not found'; rstOptionNotFound = 'Option %s not found in section %s'; const OptionTypeNames : array [TOptionType] of string = ('integer', 'boolean', 'string', 'emumerated'); { TPersistentOptions } (*----------------------------------------------------------------------* | procedure TPersistentOptions.BeginUpdate | | | | Start updating. Must be matched with EndUpdate |A *----------------------------------------------------------------------*) procedure TPersistentOptions.BeginUpdate; begin fUpdating := True end; (*----------------------------------------------------------------------* | constructor TPersistentOptions.Create | | | | Constructor for TPersistentOptions | *----------------------------------------------------------------------*) constructor TPersistentOptions.Create (AOwner : TComponent); begin inherited Create (AOwner); fOptions := TOptions.Create(self, TOption); fSections := TSections.Create(self, TSection); end; (*----------------------------------------------------------------------* | destructor TPersistentOptions.Destroy | | | | Destructor for TPersistentOptions | *----------------------------------------------------------------------*) destructor TPersistentOptions.Destroy; begin if Dirty then Save; fOptions.Free; fSections.Free; inherited; end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.EndUpdate | | | | End a batch update started with BeginUpdate | *----------------------------------------------------------------------*) procedure TPersistentOptions.EndUpdate; begin if fUpdating and Dirty then Save; fUpdating := False end; (*----------------------------------------------------------------------* | function TPersistentOptions.GetDesigning | | | | Return True if the component is in 'design' mode. | *----------------------------------------------------------------------*) function TPersistentOptions.GetDesigning: boolean; begin result := csDesigning in ComponentState end; (*----------------------------------------------------------------------* | function TPersistentOptions.GetDirty | | | | Return True if any option has had it's value changed, but has not | | yet been persisted to the registry or INI file. | *----------------------------------------------------------------------*) function TPersistentOptions.GetDirty: boolean; function OptionsDirty (options : TOptions) : boolean; var i : Integer; begin result := False; for i := 0 to options.Count - 1 do if options [i].fDirty then begin result := True; break end end; function SectionsDirty (sections : TSections) : boolean; var i : Integer; section : TSection; begin result := False; for i := 0 to sections.Count - 1 do begin section := sections [i]; result := OptionsDirty (section.Options); if not result then result := SectionsDirty (section.Sections); if result then break end end; begin result := OptionsDirty (Options) or SectionsDirty (Sections) end; (*----------------------------------------------------------------------* | TPersistentOptions.GetOption | | | | Return an option by name or path. Note that as a shortcut the | | path passed can contain sections - so you can say | | | | MyPersistentOptions.Section ['Position'].Option ['Width'] | | | | or | | | | MyPersistentOptions.Option ['Position\Width'] | | | | or even (because it's the default property): | | | | MyPersistentOptions ['Position\Width'] | | | | Parameters: | | path: string The option name or path | | | | The function always returns a valid TOption, or raised an exception | *----------------------------------------------------------------------*) function TPersistentOptions.GetLoading: boolean; begin result := (csLoading in ComponentState); end; function TPersistentOptions.GetOption(path: string): TOption; var p : PChar; n : Integer; s : TSection; secName : string; begin RemoveLeadingSlash (path); p := StrRScan (PChar (path), '\'); s := Nil; if Assigned (p) then begin n := Integer (p) - Integer (PChar (path)) + 1; s := Sections.SectionByName [Trim (Copy (path, 1, n - 1))]; path := Trim (Copy (path, n + 1, MaxInt)); end; if Assigned (s) then result := s.Options.OptionByName [path] else result := Options.OptionByName [path]; if result = Nil then begin if Assigned (s) then secName := s.Name else secName := '[Default]'; raise EOptionError.CreateFmt (rstOptionNotFound, [path, secName]) end end; (*----------------------------------------------------------------------* | function TPersistentOptions.GetPersist | | | | Return true if changes to the option values should be persisted to | | the registry or INI file - ie. it's not in design mode, and it's not | | Loading. | *----------------------------------------------------------------------*) function TPersistentOptions.GetPersist: boolean; begin result := not Designing and not (csLoading in ComponentState); end; (*----------------------------------------------------------------------* | function TPersistentOptions.GetSection | | | | Return a section by name or path. Note that as a shortcut the | | path passed can contain sub-sections - so you can say | | | | MyPersistentOptions.Section ['Position'].Section ['Attributes'] | | | | or | | | | MyPersistentOptions.Section ['Position\Attributes'] | | | | Parameters: | | name: string The section name or path | | | | The function returns a valid TSection, or raises an exception | *----------------------------------------------------------------------*) function TPersistentOptions.GetSection(name: string): TSection; begin RemoveLeadingSlash (name); result := Sections.SectionByName [name] end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.Loaded | | | | Overridden 'Loaded' method. Load the registry or ini file | | information. | *----------------------------------------------------------------------*) procedure TPersistentOptions.Loaded; begin inherited; Load end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.RemoveLeadingSlash | | | | Remove the leading slash from a path. | *----------------------------------------------------------------------*) procedure TPersistentOptions.RemoveLeadingSlash (var path : string); begin if Copy (path, 1, 1) = '\' then path := Copy (path, 2, MaxInt); end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.SetApplication | | | | Set method for 'Application' property. If this is changed at | | runtime clear the old .ini file, or delete the old registry entries | | | | Parameters: | | const Value: string New 'Application' value | *----------------------------------------------------------------------*) procedure TPersistentOptions.SetApplication(const Value: string); begin fApplication := Value; end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.SetManufacturer | | | | Set method for 'Manufacturer' property. If this is changed at | | runtime clear the old .ini file, or delete the old registry entries | | | | Parameters: | | const Value: string New 'Manufacturer' value | *----------------------------------------------------------------------*) procedure TPersistentOptions.SetManufacturer(const Value: string); begin fManufacturer := Value; end; (*----------------------------------------------------------------------* | procedure TPersistentOptions.SetVersion | | | | Set method for 'Version' property. If this is changed at runtime | | clear the old .ini file, or delete the old registry entries | | | | Parameters: | | const Value: string New 'Version' value | *----------------------------------------------------------------------*) procedure TPersistentOptions.SetVersion(const Value: string); begin fVersion := Value; end; { TOptions } (*----------------------------------------------------------------------* | constructor TOptions.Create | | | | Constructor for TOptions collection | *----------------------------------------------------------------------*) constructor TOptions.Create(AOwner: TPersistent; ItemClass: TCollectionItemClass); begin inherited Create (AOwner, ItemClass); fDeleteObsoleteOptions := True end; (*----------------------------------------------------------------------* | procedure TOptions.GetOption | | | | Get method for 'Option' array property | *----------------------------------------------------------------------*) function TOptions.GetOption(idx: Integer): TOption; begin result := TOption (Items [idx]) end; (*----------------------------------------------------------------------* | procedure TOptions.GetOptionByName | | | | 'Get' method for OptionByName array property | *----------------------------------------------------------------------*) function TOptions.GetOptionByName(const name: string): TOption; var o : TOption; i : Integer; begin result := Nil; for i := 0 to Count - 1 do begin o := Option [i]; if AnsiSameText (Name, o.Name) then begin result := o; break end end end; { TOption } (*----------------------------------------------------------------------* | constructor TOption.Create | | | | Constructor for TOption class | *----------------------------------------------------------------------*) constructor TOption.Create(Collection: TCollection); begin inherited; if Base.Designing or Base.Loading then begin fEnumValues := TStringList.Create; fEnumValues.CaseSensitive := False end end; (*----------------------------------------------------------------------* | destructor TOption.Destroy | | | | Destructor for TOption class | *----------------------------------------------------------------------*) destructor TOption.Destroy; begin fEnumValues.Free; inherited; end; (*----------------------------------------------------------------------* | procedure TOption.Flush | | | | Save the option. | *----------------------------------------------------------------------*) procedure TOption.Flush; begin if fDirty and not Base.InUpdate then Base.Save end; (*----------------------------------------------------------------------* | function TOption.GetAsBoolean | | | | Return the option value if it's a boolean option - otherwise raise | | an exception. | *----------------------------------------------------------------------*) function TOption.GetAsBoolean: Boolean; begin if OptionType = otBoolean then result := fBoolVal else raise EOptionTypeMismatch (self) end; (*----------------------------------------------------------------------* | function TOption.GetAsEnum | | | | Return the option value if it's an enum option - otherwise raise an | | exception. | *----------------------------------------------------------------------*) function TOption.GetAsEnum: string; begin if OptionType = otEnum then result := EnumValues [fIntVal] else raise EOptionTypeMismatch (self) end; (*----------------------------------------------------------------------* | function TOption.GetAsInteger | | | | Return the option value if it's an integer option - otherwise raise | | an exception. | *----------------------------------------------------------------------*) function TOption.GetAsInteger: Integer; begin if OptionType = otInteger then result := fIntVal else raise EOptionTypeMismatch (self) end; (*----------------------------------------------------------------------* | function TOption.GetAsString | | | | Return the option value if it's a string option - otherwise raise | | an exception. | *----------------------------------------------------------------------*) function TOption.GetAsString: String; begin if OptionType = otString then result := fStrVal else raise EOptionTypeMismatch (self) end; (*----------------------------------------------------------------------* | function TOption.GetBase | | | | Return the owning 'TPersistentOptions' derived object. | *----------------------------------------------------------------------*) function TOption.GetBase: TPersistentOptions; var own : TPersistent; begin own := TOwnedCollection (Collection).Owner; while own is TSection do own := TOwnedCollection (TSection (own).Collection).Owner; result := own as TPersistentOptions end; (*----------------------------------------------------------------------* | function TOption.GetDisplayName | | | | Overridden from TCollectionItem base. Helps the designer. | *----------------------------------------------------------------------*) function TOption.GetDisplayName: string; begin result := Name end; (*----------------------------------------------------------------------* | function TOption.GetEnumValues : TStringList | | | | 'Get' method for EnumValues property | *----------------------------------------------------------------------*) function TOption.GetEnumValues: TStrings; begin result := fEnumValues end; (*----------------------------------------------------------------------* | function TOption.GetHasDefaultValue : boolean | | | | Return True if the option's current value is it's default. | *----------------------------------------------------------------------*) function TOption.GetHasDefaultValue: boolean; begin result := False; case OptionType of otString : result := AnsiCompareStr (DefaultValue, fStrVal) = 0; otInteger : result := StrToIntDef (DefaultValue, 0) = fIntVal; otBoolean : result := StrToBoolDef (DefaultValue, False) = fBoolVal; otEnum : result := fIntVal = EnumValues.IndexOf(DefaultValue) end end; (*----------------------------------------------------------------------* | procedure TOption.SetAsBoolean | | | | Set the option's value if it's a boolean option - otherwise raise | | an exception | *----------------------------------------------------------------------*) procedure TOption.SetAsBoolean(const Value: Boolean); begin if OptionType <> otBoolean then raise EOptionTypeMismatch (self); if Value <> fBoolVal then begin fDirty := True; fBoolVal := Value; Flush end end; (*----------------------------------------------------------------------* | procedure TOption.SetAsEnum | | | | Set the option's value if it's an enum option - otherwise raise | | an exception | *----------------------------------------------------------------------*) procedure TOption.SetAsEnum(const Value: string); begin if Value <> AsEnum then begin fDirty := True; fIntVal := EnumValues.IndexOf(Value); Flush end end; (*----------------------------------------------------------------------* | procedure TOption.SetAsInteger | | | | Set the option's value if it's an integer option - otherwise raise | | an exception | *----------------------------------------------------------------------*) procedure TOption.SetAsInteger(const Value: Integer); begin if OptionType <> otInteger then raise EOptionTypeMismatch (self); if Value <> fIntVal then begin fDirty := True; fIntVal := Value; Flush end end; (*----------------------------------------------------------------------* | procedure TOption.SetAsString | | | | Set the option's value if it's a string option - otherwise raise | | an exception | *----------------------------------------------------------------------*) procedure TOption.SetAsString(const Value: string); begin if OptionType <> otString then raise EOptionTypeMismatch (self); if Value <> fStrVal then begin fDirty := True; fStrVal := Value; Flush end end; (*----------------------------------------------------------------------* | procedure TOption.SetEnumValues | | | | 'Set' method for EnumValues property | *----------------------------------------------------------------------*) procedure TOption.SetEnumValues(const Value: TStrings); begin if (OptionType = otEnum) then fEnumValues.Assign(Value) end; (*----------------------------------------------------------------------* | procedure TOption.SetOptionType | | | | 'Set' method for the OptionType property. | *----------------------------------------------------------------------*) procedure TOption.SetOptionType(const Value: TOptionType); begin if fOptionType <> Value then begin if Base.Designing then begin if not Base.Loading then fEnumValues.Clear end else if not Base.Loading or (Value <> otEnum) then FreeAndNil (fEnumValues); fOptionType := Value; if fOptionType = otEnum then if not Base.Designing and not Base.Loading then fEnumValues := TStringList.Create end end; { TSection } (*----------------------------------------------------------------------* | constructor TSection.Create | | | | Constructor for TSection | *----------------------------------------------------------------------*) constructor TSection.Create(Collection: TCollection); begin inherited; fOptions := TOptions.Create(self, TOption); fSections := TSections.Create(self, TSection); end; (*----------------------------------------------------------------------* | destructor TSection.Destroy | | | | Destructor for TSection | *----------------------------------------------------------------------*) destructor TSection.Destroy; begin fOptions.Free; fSections.Free; inherited; end; (*----------------------------------------------------------------------* | function TSection.GetDisplayName | | | | Override TCollectionItem method to help the designer | *----------------------------------------------------------------------*) function TSection.GetDisplayName: string; begin result := Name end; (*----------------------------------------------------------------------* | function TSection.GetOption | | | | 'Get' method for Option property | *----------------------------------------------------------------------*) function TSection.GetOption(const name: string): TOption; begin result := Options.OptionByName [name]; if result = Nil then raise Exception.Create ('Option ' + name + ' not found'); end; (*----------------------------------------------------------------------* | function TSection.GetSection | | | | 'Get' method for Section propery | *----------------------------------------------------------------------*) function TSection.GetSection(const name: string): TSection; begin result := Sections.SectionByName [name]; if result = Nil then raise Exception.Create ('Section ' + name + ' not found'); end; { EOptionTypeMismatch } constructor EOptionTypeMismatch.Create(Option: TOption); begin inherited CreateFmt (rstTypeMismatch, [Option.Name, OptionTypeNames [Option.OptionType]]) end; { TSections } (*----------------------------------------------------------------------* | function TSections.GetSection | | | | Get method for Section property. | *----------------------------------------------------------------------*) function TSections.GetSection(idx: Integer): TSection; begin result := TSection (Items [idx]) end; (*----------------------------------------------------------------------* | function TSections.GetSectionByName | | | | 'Get' method for SectionByName property | *----------------------------------------------------------------------*) function TSections.GetSectionByName(const name: string): TSection; var i, p : Integer; s : TSection; begin result := Nil; p := Pos ('\', name); if p > 0 then begin s := SectionByName [Trim (Copy (name, 1, p - 1))]; if Assigned (s) then result := s.Sections.SectionByName [Trim (Copy (name, p + 1, MaxInt))] else raise EOptionError.CreateFmt(rstSectionNotFound, [s.Name]); end else for i := 0 to Count - 1 do begin s := Section [i]; if AnsiSameText (name, s.Name) then begin result := s; break end end; if not Assigned (result) then raise EOptionError.CreateFmt (rstSectionNotFound, [name]) end; { TCustomPersistentOptions } procedure TCustomPersistentOptions.DeleteOldOptions(const application, manufacturer, version: string); begin // end; function TCustomPersistentOptions.GetSettingsFile: string; begin // stub end; procedure TCustomPersistentOptions.Load; var settings : TExSettings; openedOK : boolean; begin if not Persist then Exit; settings := GetSettingsClass.Create (Manufacturer, Application, Version, fOptionsType); try SettingsCreated (settings); openedOk := settings.Open(true); LoadOptions (settings, Options, not openedOK); LoadSections (settings, Sections, not openedOK) finally settings.Free end end; procedure TCustomPersistentOptions.LoadOptions(settings: TExSettings; Options: TOptions; forceDefaults: boolean); var i : Integer; option : TOption; begin for i := 0 to Options.Count - 1 do begin option := Options [i]; if forceDefaults or not settings.HasValue(option.Name) then case option.OptionType of otString : option.fStrVal := option.fDefaultValue; otInteger : option.fIntVal := StrToIntDef (option.fDefaultValue, 0); otBoolean : option.fBoolVal := StrToBoolDef (option.fDefaultValue, False); otEnum : option.fIntVal := option.fEnumValues.IndexOf(option.fDefaultValue) end else case option.OptionType of otString : option.fStrVal := settings.StringValue [option.Name]; otInteger : option.fIntVal := settings.IntegerValue [option.Name]; otBoolean : option.fBoolVal := settings.BooleanValue [option.Name]; otEnum : option.fIntVal := settings.IntegerValue [option.Name] end; option.fDirty := False end end; procedure TCustomPersistentOptions.LoadSections(settings: TExSettings; Sections: TSections; forceDefaults: boolean); var i : Integer; section : TSection; settings1 : TExSettings; begin for i := 0 to Sections.Count - 1 do begin section := Sections [i]; settings1 := Nil; try if not forceDefaults then begin settings1 := GetSettingsClass.CreateChild(settings, section.Name); forceDefaults := not settings1.Open (true); end; LoadOptions (settings1, section.Options, forceDefaults); LoadSections (settings1, section.Sections, forceDefaults) finally settings1.Free end; end end; procedure TCustomPersistentOptions.Save; var settings : TExSettings; begin if not Persist then Exit; settings := GetSettingsClass.Create(Manufacturer, Application, Version, fOptionsType); try SettingsCreated (settings); SaveOptions (settings, Options); SaveSections (settings, Sections) finally settings.Free end end; procedure TCustomPersistentOptions.SaveOptions(settings : TExSettings; Options: TOptions); var i, idx : Integer; deleteValues : TStringList; option : TOption; begin deleteValues := TStringList.Create; try // Get a list of values to delete. Start by filling it with all the values // then remove values as we save them, leaving only the obsolete ones. deleteValues.CaseSensitive := False; settings.GetValueNames(deleteValues); deleteValues.Sort; for i := 0 to Options.Count - 1 do begin Option := Options [i]; idx := deleteValues.IndexOf(Option.Name); if idx >= 0 then deleteValues.Delete(idx); case Option.OptionType of otString : settings.SetStringValue (Option.Name, Option.fStrVal, Option.DefaultValue); otInteger : settings.SetIntegerValue (Option.Name, Option.fIntVal, StrToIntDef (Option.DefaultValue, 0)); otBoolean : settings.SetBooleanValue (Option.Name, Option.fBoolVal, StrToBoolDef (Option.DefaultValue, false)); otEnum : settings.SetIntegerValue (Option.Name, Option.fIntVal, Option.EnumValues.IndexOf(Option.DefaultValue)); // The logic behind the 'enum' stuff works so that if the default string value is // not a member of the enum, the actual enum value gets saved. end; Option.fDirty := False end; if Options.DeleteObsoleteOptions then // Delete obsolete values. for i := 0 to deleteValues.count - 1 do settings.DeleteValue(deleteValues [i]) finally deleteValues.Free end end; procedure TCustomPersistentOptions.SaveSections(settings : TExSettings; Sections: TSections); var i, idx : Integer; section : TSection; settings1 : TExSettings; deleteSections : TStringList; begin deleteSections := TStringList.Create; try // Build list of obsolete sections to delete. deleteSections.CaseSensitive := False; settings.GetSectionNames(deleteSections); deleteSections.Sort; // Save the sections & options for i := 0 to Sections.Count - 1 do begin section := Sections [i]; settings1 := GetSettingsClass.CreateChild(settings, section.Name); try idx := deleteSections.IndexOf(Section.Name); if idx >= 0 then deleteSections.Delete(idx); SaveOptions (settings1, section.Options); SaveSections (settings1, section.Sections) finally settings1.Free end; end; // Delete the obsolete sections if Sections.DeleteObsoleteSections then for i := 0 to deleteSections.Count - 1 do // settings.DeleteSection (deleteSections [i]) finally deleteSections.Free; end end; procedure TCustomPersistentOptions.SettingsCreated(settings: TExSettings); begin if settings is TExFileSettings then TExFileSettings (settings).CustomPath := GetSettingsFile; end; { TUniPersistentOptions } function TUniPersistentOptions.GetSettingsClass: TExSettingsClass; begin if Assigned (fOnGetSettingsClass) then OnGetSettingsClass (self, result) else raise EOptionError.Create ('Unable to get settings class'); end; function TUniPersistentOptions.GetSettingsFile: string; begin if Assigned (fOnGetSettingsFile) then OnGetSettingsFile (self, result) end; end.
unit Calculadora.Interfaces; interface type iOperacoes = interface ['{655C8757-9943-4A39-840C-D2DBC0B7039A}'] function Executar : String; end; iCalculadora = interface function Add(Value : String) : iCalculadora; overload; function Add(Value : Integer) : iCalculadora; overload; function Add(Value : Currency) : iCalculadora; overload; function Soma: iOperacoes; function Subtrair: iOperacoes; function Dividir: iOperacoes; function Multiplicar: iOperacoes; end; implementation end.
{******************************************************************************* 作者: dmzn@163.com 2011-01-23 描述: 采购周期 *******************************************************************************} unit UFrameWeeks; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameNormal, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxContainer, Menus, dxLayoutControl, cxTextEdit, cxMaskEdit, cxButtonEdit, ADODB, cxLabel, UBitmapPanel, cxSplitter, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, ComCtrls, ToolWin; type TfFrameWeeks = class(TfFrameNormal) EditName: TcxButtonEdit; dxLayout1Item1: TdxLayoutItem; EditDesc: TcxTextEdit; dxLayout1Item3: TdxLayoutItem; EditSName: TcxTextEdit; dxLayout1Item7: TdxLayoutItem; EditDate: TcxButtonEdit; dxLayout1Item6: TdxLayoutItem; EditID: TcxButtonEdit; dxLayout1Item2: TdxLayoutItem; EditSID: TcxTextEdit; dxLayout1Item5: TdxLayoutItem; procedure EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure BtnAddClick(Sender: TObject); procedure BtnEditClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure EditDatePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure cxView1FocusedRecordChanged(Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); private { Private declarations } protected FStart,FEnd: TDate; {*时间区间*} procedure OnCreateFrame; override; procedure OnDestroyFrame; override; {*基类函数*} function InitFormDataSQL(const nWhere: string): string; override; {*查询SQL*} public { Public declarations } class function FrameID: integer; override; end; implementation {$R *.dfm} uses ULibFun, UMgrControl, USysConst, USysDB, UDataModule, UFormBase, USysBusiness, UFormDateFilter; //------------------------------------------------------------------------------ class function TfFrameWeeks.FrameID: integer; begin Result := cFI_FrameWeeks; end; procedure TfFrameWeeks.OnCreateFrame; var nY,nM,nD: Word; begin inherited; InitDateRange(Name, FStart, FEnd); if FStart = FEnd then begin DecodeDate(FStart, nY, nM, nD); FStart := EncodeDate(nY, 1, 1); FEnd := EncodeDate(nY+1, 1, 1) - 1; end; end; procedure TfFrameWeeks.OnDestroyFrame; begin SaveDateRange(Name, FStart, FEnd); inherited; end; //------------------------------------------------------------------------------ //Desc: 数据查询SQL function TfFrameWeeks.InitFormDataSQL(const nWhere: string): string; begin EditDate.Text := Format('%s 至 %s', [Date2Str(FStart), Date2Str(FEnd)]); Result := 'Select * From $Week '; if nWhere = '' then Result := Result + 'Where (W_Date>=''$S'' and W_Date <''$E'')' else Result := Result + 'Where (' + nWhere + ')'; Result := MacroValue(Result, [MI('$Week', sTable_Weeks), MI('$S', Date2Str(FStart)), MI('$E', Date2Str(FEnd + 1))]); //xxxxx end; //Desc: 添加 procedure TfFrameWeeks.BtnAddClick(Sender: TObject); var nParam: TFormCommandParam; begin nParam.FCommand := cCmd_AddData; CreateBaseFormItem(cFI_FormWeeks, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(''); end; end; //Desc: 修改 procedure TfFrameWeeks.BtnEditClick(Sender: TObject); var nParam: TFormCommandParam; begin if cxView1.DataController.GetSelectedCount < 1 then begin ShowMsg('请选择要编辑的记录', sHint); Exit; end; nParam.FCommand := cCmd_EditData; nParam.FParamA := SQLQuery.FieldByName('W_NO').AsString; CreateBaseFormItem(cFI_FormWeeks, PopedomItem, @nParam); if (nParam.FCommand = cCmd_ModalResult) and (nParam.FParamA = mrOK) then begin InitFormData(FWhere); end; end; //Desc: 删除 procedure TfFrameWeeks.BtnDelClick(Sender: TObject); var nStr,nID: string; begin if cxView1.DataController.GetSelectedCount < 1 then begin ShowMsg('请选择要删除的记录', sHint); Exit; end; nID := SQLQuery.FieldByName('W_NO').AsString; if IsWeekHasEnable(nID) then begin ShowMsg('该周期已经生效', sHint); Exit; end; nID := SQLQuery.FieldByName('W_Name').AsString; nStr := Format('确定要删除名称为[ %s ]的记录吗?', [nID]); if not QueryDlg(nStr, sAsk) then Exit; nStr := 'Delete From %s Where W_ID=''%s'''; nStr := Format(nStr, [sTable_Weeks, nID]); FDM.ExecuteSQL(nStr); InitFormData(FWhere); ShowMsg('记录已删除', sHint); end; //Desc: 执行查询 procedure TfFrameWeeks.EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if Sender = EditID then begin EditID.Text := Trim(EditID.Text); if EditID.Text = '' then Exit; FWhere := 'W_NO like ''%' + EditID.Text + '%'''; InitFormData(FWhere); end else if Sender = EditName then begin EditName.Text := Trim(EditName.Text); if EditName.Text = '' then Exit; FWhere := 'W_Name like ''%' + EditName.Text + '%'''; InitFormData(FWhere); end; end; //Desc: 日期筛选 procedure TfFrameWeeks.EditDatePropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if ShowDateFilterForm(FStart, FEnd) then InitFormData(FWhere); end; procedure TfFrameWeeks.cxView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin if FShowDetailInfo and Assigned(APrevFocusedRecord) then begin EditSID.Text := SQLQuery.FieldByName('W_NO').AsString; EditSName.Text := SQLQuery.FieldByName('W_Name').AsString; EditDesc.Text := Format('%s 至 %s', [ Date2Str(SQLQuery.FieldByName('W_Begin').AsDateTime), Date2Str(SQLQuery.FieldByName('W_End').AsDateTime)]); end; end; initialization gControlManager.RegCtrl(TfFrameWeeks, TfFrameWeeks.FrameID); end.
unit SeismWorkType; interface uses BaseObjects, Registrator, SeismicObject, Work, Classes, SysUtils; type TSimpleSeismWorkType = class (TRegisteredIDObject) private FWorks: TSeismicWorkTypes; function GetWorks: TSeismicWorkTypes; public function List(AListOption: TListOption = loBrief): string; override; property Works: TSeismicWorkTypes read GetWorks; constructor Create(ACollection: TIDObjects); override; end; TSimpleSeismWorkTypes = class (TRegisteredIDObjects) private function GetItems(Index: integer): TSimpleSeismWorkType; public property Items[Index: integer]: TSimpleSeismWorkType read GetItems; constructor Create; override; end; TSeismWorkType = class (TSimpleSeismWorkType) public constructor Create(ACollection: TIDObjects); override; end; TSeismWorkTypes = class (TSimpleSeismWorkTypes) private function GetItems(Index: integer): TSeismWorkType; public property Items[Index: integer]: TSeismWorkType read GetItems; constructor Create; override; end; implementation uses Facade, BaseFacades, SeismWorkTypePoster, Math; { TSeismWorkTypes } constructor TSeismWorkTypes.Create; begin inherited; FObjectClass := TSeismWorkType; end; function TSeismWorkTypes.GetItems(Index: integer): TSeismWorkType; begin Result := inherited Items[Index] as TSeismWorkType; end; { TSeismWorkType } constructor TSeismWorkType.Create(ACollection: TIDObjects); begin inherited; FClassIDString := 'Тип сейсмических работ'; end; { TSimpleSeismWorkTypes } constructor TSimpleSeismWorkTypes.Create; begin inherited; FObjectClass := TSimpleSeismWorkType; Poster := TMainFacade.GetInstance.DataPosterByClassType[TSeismWorkTypeDataPoster]; end; function TSimpleSeismWorkTypes.GetItems(Index: integer): TSimpleSeismWorkType; begin Result := inherited Items[Index] as TSimpleSeismWorkType; end; { TSimpleSeismWorkType } constructor TSimpleSeismWorkType.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Простой тип сейсмических работ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TSeismWorkTypeDataPoster]; end; function TSimpleSeismWorkType.GetWorks: TSeismicWorkTypes; begin If not Assigned (FWorks) then begin FWorks := TSeismicWorkTypes.Create; FWorks.OwnsObjects := true; FWorks.Owner := Self; FWorks.Reload('SEISMWORK_TYPE_ID = ' + IntToStr(ID)); end; Result := FWorks; end; function TSimpleSeismWorkType.List(AListOption: TListOption): string; begin Result := StringReplace(inherited List(AListOption), '(-ое)', '', [rfReplaceAll]); end; end.
unit Dao.Bomba; interface uses uTipos, FireDAC.Comp.Client, Modelo.Bomba; type TBombaDao = class public function RetornaBomba(ACodigo: Integer; var ABomba: TBomba): Boolean; procedure Atualizar(var ABomba: TBomba); procedure Inserir(var ABomba: TBomba); procedure Excluir(ACodigo: Integer); end; implementation uses System.SysUtils, System.StrUtils, Bd.DmConfig, Classes.Funcoes; { TBombaDao } procedure TBombaDao.Atualizar(var ABomba: TBomba); var vSql: string; vDataSet: TFDQuery; begin with ABomba do begin vSql := Concat( 'Update BOMBA ', ' set Codigo = ', IntToStr(Codigo), ', ', ' Descricao = ', QuotedStr(Descricao), ' ', 'Where Codigo = ', IntToStr(Codigo)); end; vDataSet := TFDQuery.Create(nil); try vDataSet.Connection := DmBd.Conexao; TFuncao.ExecutaSql(vSql, vDataSet); finally vDataSet.Free; end; end; procedure TBombaDao.Excluir(ACodigo: Integer); var vSql: string; vDataSet: TFDQuery; begin vSql := Concat('Delete From BOMBA Where Codigo = ', IntToStr(ACodigo)); vDataSet := TFDQuery.Create(nil); try vDataSet.Connection := DmBd.Conexao; TFuncao.ExecutaSql(vSql, vDataSet); finally vDataSet.Free; end; end; procedure TBombaDao.Inserir(var ABomba: TBomba); var vSql: string; vDataSet: TFDQuery; begin with ABomba do begin with TFuncao do begin vSql := Concat( 'Insert Into BOMBA( ', ' Codigo, ', ' Descricao ', ') Values ( ', IntToStr(Codigo), ', ', QuotedStr(Descricao), ') ' ); end; end; vDataSet := TFDQuery.Create(nil); try vDataSet.Connection := DmBd.Conexao; TFuncao.ExecutaSql(vSql, vDataSet); finally vDataSet.Free; end; end; function TBombaDao.RetornaBomba(ACodigo: Integer; var ABomba: TBomba): Boolean; var vSql: string; vDataSet: TFDQuery; begin Result := False; vSql := 'Select * From BOMBA Where Codigo = ' + IntToStr(ACodigo); vDataSet := TFDQuery.Create(nil); try vDataSet.Connection := DmBd.Conexao; with TFuncao do begin if AbreTabela(vSql, vDataSet) then begin vDataSet.First; with ABomba do begin Codigo := vDataSet.FieldByName('Codigo').AsInteger; Descricao := vDataSet.FieldByName('Descricao').AsString; end; Result := True; end; end; finally vDataSet.Free; end; end; end.
unit Magnifier; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls; type TMagnifier = class(TGraphicControl) private FBounds: TRect; FMagnification: Integer; procedure DoMagnify; protected function GetMagnification: Real; function GetOriginalBounds: TRect; procedure SetOriginalBounds(B: TRect); public constructor Create(AOwner: TComponent); override; procedure Magnify(m:Real); virtual; property OriginalBounds: TRect read GetOriginalBounds write SetOriginalBounds; property Magnification: Real read GetMagnification; end; implementation constructor TMagnifier.Create(AOwner: TComponent); begin inherited Create(AOwner); FMagnification := 256; // 1.0 if AOwner is TControl then with AOwner as TControl do begin Self.OnMouseWheel := OnMouseWheel; end; end; procedure TMagnifier.DoMagnify; var R: TRect; begin R := FBounds; with R do begin //WriteLn('Old bounds (', Name, ') = ((', Left, ', ', Top, '), (', Right, ', ', Bottom, '))'); //WriteLn('FMagnification = ', FMagnification, ' <=> ', FMagnification / 256); Left := FMagnification * Left div 256; Top := FMagnification * Top shr 8; Right := FMagnification * Right shr 8; Bottom := FMagnification * Bottom shr 8; //WriteLn('New bounds (', Name, ') = ((', Left, ', ', Top, '), (', Right, ', ', Bottom, '))'); end; BoundsRect := R; end; function TMagnifier.GetMagnification: Real; begin Result := FMagnification / 256; end; function TMagnifier.GetOriginalBounds: TRect; begin Result := FBounds; end; procedure TMagnifier.SetOriginalBounds(B: TRect); begin //with B do begin //WriteLn('Changing bounds (', Name, ') = ((', Left, ', ', Top, '), (', Right, ', ', Bottom, '))'); //end; FBounds := B; Magnify(Magnification); end; procedure TMagnifier.Magnify(m:Real); var i: Integer; Component: TComponent; begin FMagnification := Round(m * 256); DoMagnify; for i := 0 to ComponentCount - 1 do begin Component := Components[i]; if Component is TMagnifier then with Component as TMagnifier do begin Magnify(m); end; end; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cobrança The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit UFinCobranca; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Atributos, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, FinCobrancaVO, FinCobrancaController, Tipos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, ActnList, Generics.Collections, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, ShellApi, System.Actions, Controller; type [TFormDescription(TConstantes.MODULO_CONTAS_RECEBER, 'Cobrança')] TFFinCobranca = class(TFTelaCadastro) ActionManager: TActionManager; ActionConsultarParcelas: TAction; PanelParcelas: TPanel; PanelMestre: TPanel; EditIdCliente: TLabeledCalcEdit; EditCliente: TLabeledEdit; EditDataAcertoPagamento: TLabeledDateEdit; EditValorTotal: TLabeledCalcEdit; EditDataContato: TLabeledDateEdit; DSParcelaReceber: TDataSource; CDSParcelaReceber: TClientDataSet; EditHoraContato: TLabeledMaskEdit; ActionMarcarDataHoraContato: TAction; EditTelefoneContato: TLabeledMaskEdit; PageControlItensLancamento: TPageControl; tsParcelasSimuladoAcordo: TTabSheet; PanelItensLancamento: TPanel; GridParcelas: TJvDBUltimGrid; CDSParcelaReceberID: TIntegerField; CDSParcelaReceberID_FIN_PARCELA_RECEBER: TIntegerField; CDSParcelaReceberID_FIN_COBRANCA: TIntegerField; CDSParcelaReceberVALOR_JURO_SIMULADO: TFMTBCDField; CDSParcelaReceberVALOR_MULTA_SIMULADO: TFMTBCDField; CDSParcelaReceberVALOR_RECEBER_SIMULADO: TFMTBCDField; CDSParcelaReceberVALOR_JURO_ACORDO: TFMTBCDField; CDSParcelaReceberVALOR_MULTA_ACORDO: TFMTBCDField; CDSParcelaReceberVALOR_RECEBER_ACORDO: TFMTBCDField; CDSParcelaReceberPERSISTE: TStringField; CDSParcelaReceberID_FIN_LANCAMENTO_RECEBER: TIntegerField; CDSParcelaReceberDATA_VENCIMENTO: TDateTimeField; CDSParcelaReceberVALOR_PARCELA: TFMTBCDField; tsParcelasVencidas: TTabSheet; PanelParcelasVencidas: TPanel; GridParcelasVencidas: TJvDBUltimGrid; CDSParcelasVencidas: TClientDataSet; DSParcelasVencidas: TDataSource; ActionToolBar2: TActionToolBar; ActionCalcularMultaJuros: TAction; EditValorTotalJuros: TLabeledCalcEdit; EditValorTotalMulta: TLabeledCalcEdit; EditValorTotalAtrasado: TLabeledCalcEdit; ActionSimularValores: TAction; ActionGeraNovoLancamento: TAction; procedure FormCreate(Sender: TObject); procedure GridDblClick(Sender: TObject); procedure GridParcelasKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CDSParcelaReceberAfterEdit(DataSet: TDataSet); procedure CDSParcelaReceberBeforeDelete(DataSet: TDataSet); procedure CDSParcelaReceberAfterPost(DataSet: TDataSet); procedure EditIdClienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ActionMarcarDataHoraContatoExecute(Sender: TObject); procedure ActionConsultarParcelasExecute(Sender: TObject); procedure ActionCalcularMultaJurosExecute(Sender: TObject); procedure CDSParcelasVencidasBeforePost(DataSet: TDataSet); procedure ActionSimularValoresExecute(Sender: TObject); procedure CDSParcelaReceberBeforePost(DataSet: TDataSet); procedure ActionGeraNovoLancamentoExecute(Sender: TObject); private { Private declarations } 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 FFinCobranca: TFFinCobranca; implementation uses ULookup, Biblioteca, UDataModule, PessoaVO, PessoaController, FinParcelaReceberVO, FinParcelaReceberController, ContaCaixaVO, ContaCaixaController, ViewPessoaClienteVO, ViewPessoaClienteController, FinCobrancaParcelaReceberVO, ViewFinLancamentoReceberVO, ViewFinLancamentoReceberController; {$R *.dfm} {$REGION 'Infra'} procedure TFFinCobranca.FormCreate(Sender: TObject); var Filtro: String; begin ClasseObjetoGridVO := TFinCobrancaVO; ObjetoController := TFinCobrancaController.Create; inherited; // Configura a Grid das parcelas vencidas ConfiguraCDSFromVO(CDSParcelasVencidas, TViewFinLancamentoReceberVO); ConfiguraGridFromVO(GridParcelasVencidas, TViewFinLancamentoReceberVO); end; procedure TFFinCobranca.LimparCampos; begin inherited; CDSParcelaReceber.EmptyDataSet; end; procedure TFFinCobranca.ConfigurarLayoutTela; begin PanelEdits.Enabled := True; if StatusTela = stNavegandoEdits then begin PanelMestre.Enabled := False; PanelItensLancamento.Enabled := False; end else begin PanelMestre.Enabled := True; PanelItensLancamento.Enabled := True; end; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFFinCobranca.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdCliente.SetFocus; end; end; function TFFinCobranca.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdCliente.SetFocus; end; end; function TFFinCobranca.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('FinCobrancaController.TFinCobrancaController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('FinCobrancaController.TFinCobrancaController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFFinCobranca.DoSalvar: Boolean; var ParcelaReceber: TFinCobrancaParcelaReceberVO; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TFinCobrancaVO.Create; TFinCobrancaVO(ObjetoVO).IdCliente := EditIdCliente.AsInteger; TFinCobrancaVO(ObjetoVO).ClienteNome := EditCliente.Text; TFinCobrancaVO(ObjetoVO).DataContato := EditDataContato.Date; TFinCobrancaVO(ObjetoVO).HoraContato := EditHoraContato.Text; TFinCobrancaVO(ObjetoVO).TelefoneContato := EditTelefoneContato.Text; TFinCobrancaVO(ObjetoVO).DataAcertoPagamento := EditDataAcertoPagamento.Date; TFinCobrancaVO(ObjetoVO).TotalReceberNaData := EditValorTotal.Value; // Parcelas /// EXERCICIO - TENTE IMPLEMENTAR OS DADOS DA LISTA DE DETALHES DE ACORDO COM O NOVO MODELO PROPOSTO NA INFRA TFinCobrancaVO(ObjetoVO).ListaCobrancaParcelaReceberVO := TObjectList<TFinCobrancaParcelaReceberVO>.Create; CDSParcelaReceber.DisableControls; CDSParcelaReceber.First; while not CDSParcelaReceber.Eof do begin if (CDSParcelaReceberPERSISTE.AsString = 'S') or (CDSParcelaReceberID.AsInteger = 0) then begin ParcelaReceber := TFinCobrancaParcelaReceberVO.Create; ParcelaReceber.Id := CDSParcelaReceberID.AsInteger; ParcelaReceber.IdFinCobranca := TFinCobrancaVO(ObjetoVO).Id; ParcelaReceber.IdFinLancamentoReceber := CDSParcelaReceberID_FIN_LANCAMENTO_RECEBER.AsInteger; ParcelaReceber.IdFinParcelaReceber := CDSParcelaReceberID_FIN_PARCELA_RECEBER.AsInteger; ParcelaReceber.DataVencimento := CDSParcelaReceberDATA_VENCIMENTO.AsDateTime; ParcelaReceber.ValorParcela := CDSParcelaReceberVALOR_PARCELA.AsExtended; ParcelaReceber.ValorJuroSimulado := CDSParcelaReceberVALOR_JURO_SIMULADO.AsExtended; ParcelaReceber.ValorJuroAcordo := CDSParcelaReceberVALOR_JURO_ACORDO.AsExtended; ParcelaReceber.ValorMultaSimulado := CDSParcelaReceberVALOR_MULTA_SIMULADO.AsExtended; ParcelaReceber.ValorMultaAcordo := CDSParcelaReceberVALOR_MULTA_ACORDO.AsExtended; ParcelaReceber.ValorReceberSimulado := CDSParcelaReceberVALOR_RECEBER_SIMULADO.AsExtended; ParcelaReceber.ValorReceberAcordo := CDSParcelaReceberVALOR_RECEBER_ACORDO.AsExtended; TFinCobrancaVO(ObjetoVO).ListaCobrancaParcelaReceberVO.Add(ParcelaReceber); end; CDSParcelaReceber.Next; end; CDSParcelaReceber.EnableControls; if StatusTela = stInserindo then begin TController.ExecutarMetodo('FinCobrancaController.TFinCobrancaController', 'Insere', [TFinCobrancaVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TFinCobrancaVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('FinCobrancaController.TFinCobrancaController', 'Altera', [TFinCobrancaVO(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 TFFinCobranca.EditIdClienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdCliente.Value <> 0 then Filtro := 'ID = ' + EditIdCliente.Text else Filtro := 'ID=0'; try EditIdCliente.Clear; EditCliente.Clear; if not PopulaCamposTransientes(Filtro, TViewPessoaClienteVO, TViewPessoaClienteController) then PopulaCamposTransientesLookup(TViewPessoaClienteVO, TViewPessoaClienteController); if CDSTransiente.RecordCount > 0 then begin EditIdCliente.Text := CDSTransiente.FieldByName('ID').AsString; EditCliente.Text := CDSTransiente.FieldByName('NOME').AsString; end else begin Exit; EditDataContato.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFFinCobranca.GridDblClick(Sender: TObject); begin inherited; ConfigurarLayoutTela; end; procedure TFFinCobranca.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TFinCobrancaVO(TController.BuscarObjeto('FinCobrancaController.TFinCobrancaController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdCliente.AsInteger := TFinCobrancaVO(ObjetoVO).IdCliente; EditCliente.Text := TFinCobrancaVO(ObjetoVO).ClienteNome; EditDataContato.Date := TFinCobrancaVO(ObjetoVO).DataContato; EditHoraContato.Text := TFinCobrancaVO(ObjetoVO).HoraContato; EditTelefoneContato.Text := TFinCobrancaVO(ObjetoVO).TelefoneContato; EditDataAcertoPagamento.Date := TFinCobrancaVO(ObjetoVO).DataAcertoPagamento; EditValorTotal.Value := TFinCobrancaVO(ObjetoVO).TotalReceberNaData; // Preenche as grids internas com os dados das Listas que vieram no objeto // Parcelas TController.TratarRetorno<TFinCobrancaParcelaReceberVO>(TFinCobrancaVO(ObjetoVO).ListaCobrancaParcelaReceberVO, True, True, CDSParcelaReceber); // Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor TFinCobrancaVO(ObjetoVO).ListaCobrancaParcelaReceberVO.Clear; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; ConfigurarLayoutTela; end; procedure TFFinCobranca.GridParcelasKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_RETURN then GridParcelas.SelectedIndex := GridParcelas.SelectedIndex + 1; end; procedure TFFinCobranca.CDSParcelaReceberAfterEdit(DataSet: TDataSet); begin CDSParcelaReceberPERSISTE.AsString := 'S'; end; procedure TFFinCobranca.CDSParcelaReceberAfterPost(DataSet: TDataSet); begin if CDSParcelaReceberDATA_VENCIMENTO.AsString = '' then CDSParcelaReceber.Delete; end; procedure TFFinCobranca.CDSParcelaReceberBeforeDelete(DataSet: TDataSet); begin if CDSParcelaReceberID.AsInteger > 0 then TFinParcelaReceberController.Exclui(CDSParcelaReceberID.AsInteger); end; procedure TFFinCobranca.CDSParcelasVencidasBeforePost(DataSet: TDataSet); begin /// EXERCICIO: SE CONSIDERAR NECESSARIO, PERMITA QUE O USUÁRIO SELECIONE SE DESEJA O CALCULO COM JUROS SIMPLES OU COMPOSTOS (USE COMBOBOXES) CDSParcelasVencidas.FieldByName('VALOR_JURO').AsExtended := (CDSParcelasVencidas.FieldByName('VALOR_PARCELA').AsExtended * (CDSParcelasVencidas.FieldByName('TAXA_JURO').AsExtended / 30) / 100) * (Now - CDSParcelasVencidas.FieldByName('DATA_VENCIMENTO').AsDateTime); CDSParcelasVencidas.FieldByName('VALOR_MULTA').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_PARCELA').AsExtended * (CDSParcelasVencidas.FieldByName('TAXA_MULTA').AsExtended / 100); end; procedure TFFinCobranca.CDSParcelaReceberBeforePost(DataSet: TDataSet); begin CDSParcelaReceber.FieldByName('VALOR_RECEBER_SIMULADO').AsExtended := CDSParcelaReceber.FieldByName('VALOR_PARCELA').AsExtended + CDSParcelaReceber.FieldByName('VALOR_JURO_SIMULADO').AsExtended + CDSParcelaReceber.FieldByName('VALOR_MULTA_SIMULADO').AsExtended; end; {$ENDREGION} {$REGION 'Actions'} procedure TFFinCobranca.ActionCalcularMultaJurosExecute(Sender: TObject); var TotalAtraso, Total, Juros, Multa: Extended; begin /// EXERCICIO: SE CONSIDERAR NECESSARIO, ARMAZENE NO BANCO DE DADOS OS TOTAIS DE JUROS E MULTAS Juros := 0; Multa := 0; Total := 0; TotalAtraso := 0; // CDSParcelaReceber.EmptyDataSet; // CDSParcelasVencidas.DisableControls; CDSParcelasVencidas.First; while not CDSParcelasVencidas.Eof do begin CDSParcelaReceber.Append; CDSParcelaReceber.FieldByName('ID_FIN_LANCAMENTO_RECEBER').AsInteger := CDSParcelasVencidas.FieldByName('ID_LANCAMENTO_RECEBER').AsInteger; CDSParcelaReceber.FieldByName('ID_FIN_PARCELA_RECEBER').AsInteger := CDSParcelasVencidas.FieldByName('ID_PARCELA_RECEBER').AsInteger; CDSParcelaReceber.FieldByName('DATA_VENCIMENTO').AsDateTime := CDSParcelasVencidas.FieldByName('DATA_VENCIMENTO').AsDateTime; CDSParcelaReceber.FieldByName('VALOR_PARCELA').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_PARCELA').AsExtended; CDSParcelaReceber.FieldByName('VALOR_JURO_SIMULADO').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_JURO').AsExtended; CDSParcelaReceber.FieldByName('VALOR_JURO_ACORDO').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_JURO').AsExtended; CDSParcelaReceber.FieldByName('VALOR_MULTA_SIMULADO').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_MULTA').AsExtended; CDSParcelaReceber.FieldByName('VALOR_MULTA_ACORDO').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_MULTA').AsExtended; CDSParcelaReceber.FieldByName('VALOR_RECEBER_SIMULADO').AsExtended := CDSParcelasVencidas.FieldByName('VALOR_PARCELA').AsExtended + CDSParcelasVencidas.FieldByName('VALOR_JURO').AsExtended + CDSParcelasVencidas.FieldByName('VALOR_MULTA').AsExtended; CDSParcelaReceber.FieldByName('VALOR_RECEBER_ACORDO').AsExtended := CDSParcelaReceber.FieldByName('VALOR_RECEBER_SIMULADO').AsExtended; CDSParcelaReceber.Post; TotalAtraso := TotalAtraso + CDSParcelaReceber.FieldByName('VALOR_PARCELA').AsExtended; Total := Total + CDSParcelaReceber.FieldByName('VALOR_RECEBER_SIMULADO').AsExtended; Juros := Juros + CDSParcelaReceber.FieldByName('VALOR_JURO_SIMULADO').AsExtended; Multa := Multa + CDSParcelaReceber.FieldByName('VALOR_MULTA_SIMULADO').AsExtended; CDSParcelasVencidas.Next; end; CDSParcelasVencidas.First; CDSParcelasVencidas.EnableControls; // EditValorTotal.Value := Total; EditValorTotalJuros.Value := Juros; EditValorTotalMulta.Value := Multa; EditValorTotalAtrasado.Value := TotalAtraso; end; procedure TFFinCobranca.ActionConsultarParcelasExecute(Sender: TObject); var Filtro: String; begin /// EXERCICIO: ENCONTRE O ERRO NO FILTRO E CORRIJA. TViewFinLancamentoReceberController.SetDataSet(CDSParcelasVencidas); Filtro := 'SITUACAO_PARCELA=' + QuotedStr('01') + ' and DATA_VENCIMENTO < ' + QuotedStr(DataParaTexto(Now)); TController.ExecutarMetodo('ViewFinLancamentoReceberController.TViewFinLancamentoReceberController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista'); end; procedure TFFinCobranca.ActionMarcarDataHoraContatoExecute(Sender: TObject); begin EditDataContato.Date := Now; EditHoraContato.Text := FormatDateTime('hh:mm:ss', Now); end; procedure TFFinCobranca.ActionSimularValoresExecute(Sender: TObject); var Total, Juros, Multa: Extended; begin /// EXERCICIO: CRIE CAMPOS CALCULADOS PARA VER A DIFERENÇA ENTRE O SIMULADO E O ACORDADO Juros := 0; Multa := 0; Total := 0; CDSParcelaReceber.DisableControls; CDSParcelaReceber.First; while not CDSParcelaReceber.Eof do begin Total := Total + CDSParcelaReceber.FieldByName('VALOR_RECEBER_SIMULADO').AsExtended; Juros := Juros + CDSParcelaReceber.FieldByName('VALOR_JURO_SIMULADO').AsExtended; Multa := Multa + CDSParcelaReceber.FieldByName('VALOR_MULTA_SIMULADO').AsExtended; CDSParcelaReceber.Next; end; CDSParcelaReceber.First; CDSParcelaReceber.EnableControls; // EditValorTotal.Value := Total; EditValorTotalJuros.Value := Juros; EditValorTotalMulta.Value := Multa; end; procedure TFFinCobranca.ActionGeraNovoLancamentoExecute(Sender: TObject); begin /// EXERCICIO: GERE UM NOVO LANÇAMENTO COM BASE NO QUE FOI ACORDADO Application.MessageBox('Lançamento efetuado com sucesso.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); BotaoCancelar.Click; end; /// EXERCICIO: CRIE UMA ACTION QUE PERMITA O USUARIO BAIXAR OS VALORES DOS JUROS/MULTAS COM BASE NUM PERCENTUAL FORNECIDO {$ENDREGION} end.
unit SFtpDir; interface type HCkTask = Pointer; HCkSFtpFile = Pointer; HCkSFtpDir = Pointer; HCkString = Pointer; function CkSFtpDir_Create: HCkSFtpDir; stdcall; procedure CkSFtpDir_Dispose(handle: HCkSFtpDir); stdcall; function CkSFtpDir_getLastMethodSuccess(objHandle: HCkSFtpDir): wordbool; stdcall; procedure CkSFtpDir_putLastMethodSuccess(objHandle: HCkSFtpDir; newPropVal: wordbool); stdcall; function CkSFtpDir_getNumFilesAndDirs(objHandle: HCkSFtpDir): Integer; stdcall; procedure CkSFtpDir_getOriginalPath(objHandle: HCkSFtpDir; outPropVal: HCkString); stdcall; function CkSFtpDir__originalPath(objHandle: HCkSFtpDir): PWideChar; stdcall; function CkSFtpDir_GetFilename(objHandle: HCkSFtpDir; index: Integer; outStr: HCkString): wordbool; stdcall; function CkSFtpDir__getFilename(objHandle: HCkSFtpDir; index: Integer): PWideChar; stdcall; function CkSFtpDir_GetFileObject(objHandle: HCkSFtpDir; index: Integer): HCkSFtpFile; stdcall; function CkSFtpDir_LoadTaskResult(objHandle: HCkSFtpDir; task: HCkTask): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkSFtpDir_Create; external DLLName; procedure CkSFtpDir_Dispose; external DLLName; function CkSFtpDir_getLastMethodSuccess; external DLLName; procedure CkSFtpDir_putLastMethodSuccess; external DLLName; function CkSFtpDir_getNumFilesAndDirs; external DLLName; procedure CkSFtpDir_getOriginalPath; external DLLName; function CkSFtpDir__originalPath; external DLLName; function CkSFtpDir_GetFilename; external DLLName; function CkSFtpDir__getFilename; external DLLName; function CkSFtpDir_GetFileObject; external DLLName; function CkSFtpDir_LoadTaskResult; external DLLName; end.
program AlgLista4Ex1; // Exercicio 1 da lista 4. Autor: Henrique Colodetti Escanferla. type vetor=array[1..100]of integer; // Criação do tipo de variável "vetor". var seq, rep: vetor; // Variáveis globais. seq=> receberá sequência de inteiros; rep=> nºs repetidos. tamseq, irep: integer; // tamseq=> tamanho util de "seq"; irep=> indice de "rep", será tamanho util dele. procedure writelnvet(v:vetor; tamv:integer); // "writelnvet" app nºs do vetor parcialmente pelo indice. begin // Inicio deste procedimento. while tamv<>0 do begin // Inicio deste loop. write(v[tamv],' '); // App d um nº do vetor "v". tamv:=tamv-1; // Prox. indice de "v". end; // Fim deste loop. writeln; // Pula linha na tela. end; // Fim deste procedimento. procedure lervetor(var v:vetor; var i:integer); // "lervetor" recebe vetor, indice inicial e le entrada retornando vetor com a entrada e seu tamanho. var aux:integer; // Variáveis locais: aux=> recebera a sequencia. begin // Inicio deste procedimento. read(aux); // Le 1º numero da sequencia. while aux<>0 do begin // Inicio deste loop. i:=i+1; // Incrementa o indice. v[i]:=aux; // Insere valor no indice do vetor. read(aux); // Le prox. nº da sequencia. end; // Fim deste loop. writeln; end; // Fim deste procedimento. function repeticoes(v:vetor; tamv:integer; num:real):integer; // "repeticoes" le vetor e valor acusando nºs de repetições. var cont:integer; // Variaveis locais: cont=> contará o nº de repetições. begin // Inicio desta função. cont:=0; // Começa com zero. while tamv<>0 do // Se "num" repetir o loop acaba. begin // Inicio deste loop. if v[tamv]=num then cont:=cont+1; // Houve ocorrencia de "num". tamv:=tamv-1; // Prox. indice do vetor. end; // Fim deste loop. repeticoes:=cont; // Coleta do resultado. end; // Fim desta função. begin // Inicio do processo. tamseq:=0; // Começa, naturalmente, com zero. irep:=0; // Começa, naturalmente, com zero. write('Digite uma sequência de números inteiros: '); // Pedido de "aux". lervetor(seq,tamseq); // Chama-se "lervetor". while tamseq<>0 do begin // Inicio deste lopp. if (repeticoes(seq,tamseq,seq[tamseq])>1)and(repeticoes(rep,irep,seq[tamseq])=0) then // Chama-se "repeticoes" tanto para verificar repetições em "seq" quanto para verificar repetições em "rep". begin // Inicio deste if-then. irep:=irep+1; // Prox. indice. rep[irep]:=seq[tamseq]; // Guarda em "rep" valores repetidos em "seq". end; // Fim deste if-then. tamseq:=tamseq-1; // Prox. indice de "seq" a verificar. end; // Fim deste loop. write('Os repetidos são: '); // Parte da app do resultado. writelnvet(rep,irep); // Chama-se "writelnvet". end. // Fim do processo.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl // Encoding : UTF-8 // Version : 1.0 // ************************************************************************ // unit uWSDL_BCB; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:long - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" // !:boolean - "http://www.w3.org/2001/XMLSchema" // !:string - "http://www.w3.org/2001/XMLSchema" // !:decimal - "http://www.w3.org/2001/XMLSchema" WSValorSerieVO = class; { "http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br" } WSSerieVO = class; { "http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br" } ArrayOfflong = array of Int64; { "http://DefaultNamespace" } // ************************************************************************ // // Namespace : http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br // ************************************************************************ // WSValorSerieVO = class(TRemotable) private Fano: Integer; FanoFim: Integer; Fbloqueado: Boolean; FbloqueioLiberado: Boolean; Fdia: Integer; FdiaFim: Integer; Fmes: Integer; FmesFim: Integer; Foid: Int64; FoidSerie: Int64; Fsvalor: WideString; Fvalor: TXSDecimal; public destructor Destroy; override; published property ano: Integer read Fano write Fano; property anoFim: Integer read FanoFim write FanoFim; property bloqueado: Boolean read Fbloqueado write Fbloqueado; property bloqueioLiberado: Boolean read FbloqueioLiberado write FbloqueioLiberado; property dia: Integer read Fdia write Fdia; property diaFim: Integer read FdiaFim write FdiaFim; property mes: Integer read Fmes write Fmes; property mesFim: Integer read FmesFim write FmesFim; property oid: Int64 read Foid write Foid; property oidSerie: Int64 read FoidSerie write FoidSerie; property svalor: WideString read Fsvalor write Fsvalor; property valor: TXSDecimal read Fvalor write Fvalor; end; ArrayOf_tns2_WSValorSerieVO = array of WSValorSerieVO; { "https://www3.bcb.gov.br/wssgs/services/FachadaWSSGS" } // ************************************************************************ // // Namespace : http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br // ************************************************************************ // WSSerieVO = class(TRemotable) private FanoFim: Integer; FanoInicio: Integer; Faviso: WideString; FdiaFim: Integer; FdiaInicio: Integer; Fespecial: Boolean; Ffonte: WideString; FfullName: WideString; FgestorProprietario: WideString; FmesFim: Integer; FmesInicio: Integer; FnomeAbreviado: WideString; FnomeCompleto: WideString; Foid: Int64; Fperiodicidade: WideString; FperiodicidadeSigla: WideString; FpossuiBloqueios: Boolean; Fpublica: Boolean; FshortName: WideString; FultimoValor: WSValorSerieVO; FunidadePadrao: WideString; FunidadePadraoIngles: WideString; FvalorDiaNaoUtil: Boolean; Fvalores: ArrayOf_tns2_WSValorSerieVO; public destructor Destroy; override; published property anoFim: Integer read FanoFim write FanoFim; property anoInicio: Integer read FanoInicio write FanoInicio; property aviso: WideString read Faviso write Faviso; property diaFim: Integer read FdiaFim write FdiaFim; property diaInicio: Integer read FdiaInicio write FdiaInicio; property especial: Boolean read Fespecial write Fespecial; property fonte: WideString read Ffonte write Ffonte; property fullName: WideString read FfullName write FfullName; property gestorProprietario: WideString read FgestorProprietario write FgestorProprietario; property mesFim: Integer read FmesFim write FmesFim; property mesInicio: Integer read FmesInicio write FmesInicio; property nomeAbreviado: WideString read FnomeAbreviado write FnomeAbreviado; property nomeCompleto: WideString read FnomeCompleto write FnomeCompleto; property oid: Int64 read Foid write Foid; property periodicidade: WideString read Fperiodicidade write Fperiodicidade; property periodicidadeSigla: WideString read FperiodicidadeSigla write FperiodicidadeSigla; property possuiBloqueios: Boolean read FpossuiBloqueios write FpossuiBloqueios; property publica: Boolean read Fpublica write Fpublica; property shortName: WideString read FshortName write FshortName; property ultimoValor: WSValorSerieVO read FultimoValor write FultimoValor; property unidadePadrao: WideString read FunidadePadrao write FunidadePadrao; property unidadePadraoIngles: WideString read FunidadePadraoIngles write FunidadePadraoIngles; property valorDiaNaoUtil: Boolean read FvalorDiaNaoUtil write FvalorDiaNaoUtil; property valores: ArrayOf_tns2_WSValorSerieVO read Fvalores write Fvalores; end; ArrayOffWSSerieVO = array of WSSerieVO; { "http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br" } // ************************************************************************ // // Namespace : http://publico.ws.casosdeuso.sgs.pec.bcb.gov.br // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : FachadaWSSGSSoapBinding // service : FachadaWSSGSService // port : FachadaWSSGS // URL : https://www3.bcb.gov.br/wssgs/services/FachadaWSSGS // ************************************************************************ // FachadaWSSGS = interface(IInvokable) ['{A1C63EC0-C9C9-66FD-56BD-D3EE44F902C2}'] function getValoresSeriesVO(const in0: ArrayOfflong; const in1: WideString; const in2: WideString): ArrayOffWSSerieVO; stdcall; function getUltimosValoresSerieVO(const in0: Int64; const in1: Int64): WSSerieVO; stdcall; function getValoresSeriesXML(const in0: ArrayOfflong; const in1: WideString; const in2: WideString): WideString; stdcall; function getUltimoValorVO(const in0: Int64): WSSerieVO; stdcall; function getUltimoValorXML(const in0: Int64): WideString; stdcall; function getValor(const in0: Int64; const in1: WideString): TXSDecimal; stdcall; function getValorEspecial(const in0: Int64; const in1: WideString; const in2: WideString): TXSDecimal; stdcall; end; function GetFachadaWSSGS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): FachadaWSSGS; implementation function GetFachadaWSSGS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): FachadaWSSGS; const defWSDL = 'https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl'; defURL = 'https://www3.bcb.gov.br/wssgs/services/FachadaWSSGS'; defSvc = 'FachadaWSSGSService'; defPrt = 'FachadaWSSGS'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as FachadaWSSGS); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; destructor WSValorSerieVO.Destroy; begin if Assigned(Fvalor) then Fvalor.Free; inherited Destroy; end; destructor WSSerieVO.Destroy; var I: Integer; begin for I := 0 to Length(Fvalores)-1 do if Assigned(Fvalores[I]) then Fvalores[I].Free; SetLength(Fvalores, 0); if Assigned(FultimoValor) then FultimoValor.Free; inherited Destroy; end; initialization InvRegistry.RegisterInterface(TypeInfo(FachadaWSSGS), 'http://publico.ws.casosdeuso.sgs.pec.bcb.gov.br', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(FachadaWSSGS), ''); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfflong), 'http://DefaultNamespace', 'ArrayOfflong'); RemClassRegistry.RegisterXSClass(WSValorSerieVO, 'http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br', 'WSValorSerieVO'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOf_tns2_WSValorSerieVO), 'https://www3.bcb.gov.br/wssgs/services/FachadaWSSGS', 'ArrayOf_tns2_WSValorSerieVO'); RemClassRegistry.RegisterXSClass(WSSerieVO, 'http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br', 'WSSerieVO'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOffWSSerieVO), 'http://comum.ws.casosdeuso.sgs.pec.bcb.gov.br', 'ArrayOffWSSerieVO'); end.
{ Copyright 2023 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2023-04-29 Darian Miller: Unit created } unit iaRTL.Threading.LoggedWorker; interface uses iaRTL.Threading, iaRTL.Logging; type TiaLoggedWorkerThread = class(TiaThread) private const defPauseBetweenWorkMS = 250; defInternalLogEntryType:TiaLogLevel = TiaLogLevel.All; // Logging entries for internal "plumbing" work is not normally captured private fPauseBetweenWorkMS:UInt32; fLogger:ILogger; protected procedure BeforeRun; override; procedure AfterRun; override; procedure BetweenRuns; override; public constructor Create(const ThreadName:string; const OptionalLogger:ILogger = nil); reintroduce; destructor Destroy; override; procedure Log(const LogEntry:string; const LogLevel:TiaLogLevel = TiaLogLevel.Debug); function ShouldWorkTerminate(const SleepAfterCheckMS:Integer = 0):Boolean; property PauseBetweenWorkMS:UInt32 read fPauseBetweenWorkMS write fPauseBetweenWorkMS; end; implementation uses System.SysUtils; constructor TiaLoggedWorkerThread.Create(const ThreadName:string; const OptionalLogger:ILogger = nil); begin inherited Create; fLogger := OptionalLogger; ThreadNameForDebugger := ThreadName; fPauseBetweenWorkMS := defPauseBetweenWorkMS; Log(Format('%s: created WorkerThread', [ThreadName]), defInternalLogEntryType); end; destructor TiaLoggedWorkerThread.Destroy; begin Log(Format('%s: Shutting down WorkerThread', [ThreadNameForDebugger]), defInternalLogEntryType); inherited; Log(Format('%s: WorkerThread shut down', [ThreadNameForDebugger]), defInternalLogEntryType); end; procedure TiaLoggedWorkerThread.BeforeRun; begin Log('WorkerThread BeforeRun', defInternalLogEntryType); inherited; end; procedure TiaLoggedWorkerThread.AfterRun; begin Log('WorkerThread AfterRun', defInternalLogEntryType); inherited; end; procedure TiaLoggedWorkerThread.BetweenRuns; begin Log('WorkerThread BetweenRuns', defInternalLogEntryType); inherited; ShouldWorkTerminate(PauseBetweenWorkMS); end; function TiaLoggedWorkerThread.ShouldWorkTerminate(const SleepAfterCheckMS:Integer = 0):Boolean; begin if ThreadIsActive then begin Result := False; if SleepAfterCheckMS > 0 then begin Log(Format('Sleeping worker thread for %dms', [SleepAfterCheckMS]), defInternalLogEntryType); if not Self.Sleep(SleepAfterCheckMS) then // abortable sleep begin Result := True; end; end; end else begin Log('WorkerThread termination detected', defInternalLogEntryType); Result := True; end; end; procedure TiaLoggedWorkerThread.Log(const LogEntry:string; const LogLevel:TiaLogLevel = TiaLogLevel.Debug); begin if Assigned(fLogger) then begin fLogger.Log(LogEntry, LogLevel); end; end; end.
unit Motif; interface uses System.Classes, System.SysUtils, System.Rtti, System.Generics.Collections; type TPatternItem = class private fResponse: string; fTag: string; fValue: TValue; procedure setTag(const aValue: string); public constructor Create; destructor Destroy; override; property Response: string read fResponse write fResponse; property Tag: string read fTag write setTag; property Value: TValue read fValue write fValue; end; TOnBeforeAdd = procedure (const aPattern: string; var aValue: string; var aContinue:Boolean) of object; TMotif = class private fList: TStringList; fItemsList: TList<TPatternItem>; fOnBeforeAdd: TOnBeforeAdd; procedure addItem(const aTag: string; const aItem: TPatternItem); function getGlobPatternItem(const itemString, tag: string): TList<TPatternItem>; function prepareTag(const aPattern: string): string; procedure retrievePatternItems(const aPattern: string; const aExact: Boolean); function getPatternItemResponse(const index: integer): string; public function add(const aPattern: string; const aReturn: string = ''): TMotif; overload; function add<T>(const aPattern: string; const aFunc: TFunc<T>):TMotif; overload; {$REGION 'Returns a list of strings of the return items based on aPattern'} /// <summary> /// Returns a list of strings of the return items based on aPattern /// </summary> /// <remarks> /// The consumer of the function is responsible for destroying the list /// </remarks> {$ENDREGION} function findByPattern(const aPattern: string; const aExact: Boolean = False): TList<string>; {$IFNDEF DEBUG}inline;{$ENDIF} function findClassByPattern<T>(const aPattern: string; const aExact: Boolean = False): TList<T>; {$IFNDEF DEBUG}inline;{$ENDIF} function list(const aPattern: string; const aExact: Boolean = False): string; procedure remove(const aPattern: string); procedure clear; public constructor Create; destructor Destroy; override; property OnBeforeAdd: TOnBeforeAdd read fOnBeforeAdd write fOnBeforeAdd; end; implementation uses ArrayHelper, System.TypInfo, flcStringPatternMatcher, Aurelius.Criteria.Projections; function TMotif.getGlobPatternItem(const itemString, tag: string): TList<TPatternItem>; var pattern: string; testStr: string; begin result:=nil; if (tag.Contains('?') or tag.Contains('*') or tag.Contains('[') or tag.Contains(']')) or (itemString.Contains('?') or itemString.Contains('*') or itemString.Contains('[') or itemString.Contains(']')) then begin if tag.Contains('?') or tag.Contains('*') or tag.Contains('[') or tag.Contains(']') then begin pattern:=tag; testStr:=itemString; end else begin pattern:=itemString; testStr:=tag; end; if tag.Equals('*') then result:=fList.Objects[fList.IndexOf(itemString)] as TList<TPatternItem> else if StrZMatchPatternW(PWideChar(pattern), PWideChar(testStr)) > 0 then result:=fList.Objects[fList.IndexOf(itemString)] as TList<TPatternItem>; end else if (itemString = tag) or (tag.Trim = '') then result:=fList.Objects[fList.IndexOf(itemString)] as TList<TPatternItem>; end; function TMotif.prepareTag(const aPattern: string): string; var strArray: TArrayRecord<string>; arrList: TList<string>; tag: string; begin tag:=aPattern.Replace('{','') .Replace('}','') .Replace('''','') .Trim .ToUpper; strArray:=TArrayRecord<string>.Create(tag.Split([','])); strArray.ForEach(procedure(var Value: string; Index: integer) begin Value:=Value.Trim; end); arrList:=TList<string>.Create; strArray.List(arrList); result:=string.Join(',', arrList.ToArray); arrList.Free; end; procedure TMotif.retrievePatternItems(const aPattern: string; const aExact: Boolean); var arrList: TList<string>; arrStr: TArrayRecord<string>; index: integer; tag: string; item: TPatternItem; strItem: string; pattern: string; testStr: string; list: TList<TPatternItem>; begin fItemsList.Clear; tag:=prepareTag(aPattern); for strItem in fList do begin if aExact then begin if strItem = tag then for item in (fList.Objects[fList.IndexOf(strItem)] as TList<TPatternItem>) do fItemsList.Add(item); end else begin list:=getGlobPatternItem(strItem, tag); if Assigned(list) then for item in list do fItemsList.Add(item); end; end; if aExact or (fItemsList.Count > 0) then Exit; arrStr:=TArrayRecord<string>.Create(tag.Split([','])); while arrStr.Count > 0 do begin arrStr.Delete(arrStr.Count - 1); arrList:=TList<string>.Create; arrStr.List(arrList); tag:=string.Join(',', arrList.ToArray); arrList.Free; if tag.Trim <> '' then begin list:=getGlobPatternItem(strItem, tag); if Assigned(list) then for item in list do fItemsList.Add(item); end; end; end; function TMotif.getPatternItemResponse(const index: integer): string; var obj: TPatternItem; begin Result:=''; if (index>=0) and (index<=fList.Count - 1) then begin obj:=fList.Objects[index] as TPatternItem; if Assigned(obj) then if obj.Response<>'' then Result := obj.Response; end; end; { TMotif } function TMotif.add(const aPattern: string; const aReturn: string = ''): TMotif; var tag: string; patItem: TPatternItem; patt: string; ret: string; cont: Boolean; begin Result:=Self; patt:=aPattern; ret:=aReturn; cont:=True; if Assigned(fOnBeforeAdd) then fOnBeforeAdd(aPattern, ret, cont); if not cont then Exit; tag:=prepareTag(aPattern); patItem:=TPatternItem.Create; patItem.Response:=ret; patItem.Tag:=aPattern; addItem(tag, patItem); end; function TMotif.add<T>(const aPattern: string; const aFunc: TFunc<T>): TMotif; var tag: string; index: Integer; funRec: T; item: TPatternItem; begin Result:=Self; if not Assigned(aFunc) then Exit; tag:=prepareTag(aPattern); funRec:=aFunc(); item:=TPatternItem.Create; item.Response:=tag; item.Tag:=aPattern; item.Value:=TValue.From<T>(funRec); addItem(tag, item); end; function TMotif.findByPattern(const aPattern: string; const aExact: Boolean = False): TList<string>; var item: TPatternItem; begin Result:=TList<string>.Create; retrievePatternItems(aPattern, aExact); for item in fItemsList do if Assigned(item) then Result.Add(item.Response); end; function TMotif.findClassByPattern<T>(const aPattern: string; const aExact: Boolean = False): TList<T>; var item: TPatternItem; begin Result:=TList<T>.Create; retrievePatternItems(aPattern, aExact); for item in fItemsList do if Assigned(item) then Result.Add(item.Value.AsType<T>); end; function TMotif.list(const aPattern: string; const aExact: Boolean): string; var pattItem: TPatternItem; begin Result:=''; fItemsList.Clear; retrievePatternItems(aPattern, aExact); for pattItem in fItemsList do begin result:=Result+pattItem.Tag+#9+' -> '+#9+pattItem.Response; if not pattItem.Value.IsEmpty then result:=Result+#9+'('+pattItem.Value.AsString+')'; Result:=Result+sLineBreak; end; end; procedure TMotif.remove(const aPattern: string); var item: TPatternItem; list: TList<string>; tag: string; begin retrievePatternItems(aPattern, true); list:=TList<string>.Create; for item in fItemsList do begin list.Add(prepareTag(item.Tag)); item.Free; end; for tag in list do if fList.IndexOf(tag) > -1 then fList.Delete(fList.IndexOf(tag)); list.Free; end; procedure TMotif.clear; var list: TList<TPatternItem>; item: TPatternItem; index: integer; begin for index:=0 to fList.Count-1 do begin list:=fList.Objects[index] as TList<TPatternItem>; if Assigned(list) then begin for item in list do item.Free; // list is freed when fList is destroyed because it owns the objects // list.Free; end; end; fList.Clear; end; constructor TMotif.Create; begin inherited; fList:=TStringList.Create; fList.Sorted:=True; fList.OwnsObjects:=True; fList.Duplicates:=dupIgnore; fItemsList:=TList<TPatternItem>.Create; end; destructor TMotif.Destroy; begin fList.Free; fItemsList.Free; inherited; end; procedure TMotif.addItem(const aTag: string; const aItem: TPatternItem); var index: Integer; list: TList<TPatternItem>; begin if fList.Find(aTag, index) then begin list:=fList.Objects[index] as TList<TPatternItem>; if not list.Contains(aItem) then begin list.Add(aItem); fList.Objects[index]:=list; end else aItem.Free; end else begin list:=TList<TPatternItem>.Create; list.Add(aItem); fList.AddObject(aTag, list); end; end; constructor TPatternItem.Create; begin inherited; fResponse:=''; fValue:=TValue.Empty; end; destructor TPatternItem.Destroy; begin fValue:=TValue.Empty; inherited; end; procedure TPatternItem.setTag(const aValue: string); begin fTag := aValue; end; end.
unit TIsiGridThread; interface uses System.Classes; type TIsiGrid = class(TThread) private { Private declarations } protected procedure Execute; override; procedure isiGrid; end; implementation uses TabbedTemplate; { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TIsiGrid.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { TIsiGrid } procedure TIsiGrid.Execute; begin NameThreadForDebugging('isiGridThread'); { Place thread code here } isiGrid; end; procedure TIsiGrid.isiGrid; var row: TStringList; I: Integer; begin try row := TStringList.Create; TabbedForm.duplicateGrid.RowCount:= logData.Count; for I := 0 to (logData.Count-1) do begin row.Text := logData[I]; row.CommaText := row.Text; row.Delimiter:= ','; TabbedForm.duplicateGrid.Cells[0, I] := row[0]; TabbedForm.duplicateGrid.Cells[1, I] := row[1]; TabbedForm.duplicateGrid.Cells[2, I] := row[2]; TabbedForm.duplicateGrid.Cells[3, I] := row[3]; TabbedForm.duplicateGrid.Cells[4, I] := row[4]; end; finally row.Free; end; end; end.
(* MIT License Copyright (c) 2018 Ondrej Kelle 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. *) unit Console; interface {$include common.inc} uses {$ifdef WINDOWS} Windows, {$endif} SysUtils, Classes, {$ifdef HAS_WIDESTRUTILS} WideStrUtils, {$endif} Compat, ChakraCommon, ChakraCoreUtils, ChakraCoreClasses; type TInfoLevel = (ilNone, ilInfo, ilWarn, ilError); TConsole = class(TChakraCoreNativeObject) private function Assert(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; function Log(Arguments: PJsValueRef; ArgumentCount: Word; Level: TInfoLevel): JsValueRef; function LogError(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; function LogInfo(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; function LogNone(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; function LogWarn(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; procedure Print(const S: UTF8String; Level: TInfoLevel = ilNone; UseAnsiColors: Boolean = True); overload; procedure Print(const S: UnicodeString; Level: TInfoLevel = ilNone; UseAnsiColors: Boolean = True); overload; protected class procedure RegisterMethods(AInstance: JsValueRef); override; end; implementation function FmtSpecPos(S: PWideChar): PWideChar; var P: PWideChar; begin Result := nil; P := WStrPos(S, '%'); while Assigned(P) do begin case (P + 1)^ of #0: Break; 'd', 'i', 'f', 'o', 's': begin Result := P; Break; end; '%': begin Inc(P); if P^ = #0 then Break; end; end; P := WStrPos(P + 1, '%'); end; end; { TConsole private } function TConsole.Assert(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; var ArgCondition: JsValueRef; SMessage: UnicodeString; begin Result := JsUndefinedValue; if ArgumentCount < 1 then Exit; SMessage := 'Assertion failed'; // arg 1 = condition (boolean) ArgCondition := Arguments^; if (JsGetValueType(ArgCondition) <> JsBoolean) then raise Exception.Create('condition passed to console.assert not a boolean'); Inc(Arguments); Dec(ArgumentCount); if (JsBooleanToBoolean(ArgCondition)) then // assertion passed Exit; if ArgumentCount = 0 then // no message/data Print(SMessage, ilError) else Log(Arguments, ArgumentCount, ilError); end; function TConsole.Log(Arguments: PJsValueRef; ArgumentCount: Word; Level: TInfoLevel): JsValueRef; var FirstArg, S, SCopy: UnicodeString; P, PPrev: PWideChar; Arg: PJsValueRef; I, ArgIndex: Integer; begin Result := JsUndefinedValue; if not Assigned(Arguments) then Exit; S := ''; P := nil; PPrev := nil; Arg := Arguments; ArgIndex := 0; if Assigned(Arguments) and (ArgumentCount > 0) and (JsGetValueType(Arguments^) = JsString) then begin FirstArg := JsStringToUnicodeString(Arguments^); PPrev := PWideChar(FirstArg); P := FmtSpecPos(PPrev); end; if Assigned(P) then begin Inc(Arg); Inc(ArgIndex); while Assigned(P) do begin if ArgIndex > ArgumentCount - 1 then begin SetString(SCopy, PPrev, (P - PPrev) + 2); S := S + WideStringReplace(SCopy, '%%', '%', [rfReplaceAll]); end else begin SetString(SCopy, PPrev, P - PPrev); S := S + WideStringReplace(SCopy, '%%', '%', [rfReplaceAll]); case (P + 1)^ of 'd', 'i': S := S + UnicodeString(IntToStr(JsNumberToInt(Arg^))); 'f': S := S + UnicodeString(FloatToStr(JsNumberToDouble(Arg^), DefaultFormatSettings)); 'o': S := S + JsInspect('', Arg^); 's': S := S + JsStringToUnicodeString(Arg^); end; end; PPrev := P + 2; P := FmtSpecPos(PPrev); Inc(Arg); Inc(ArgIndex); end; S := S + WideStringReplace(PPrev, '%%', '%', [rfReplaceAll]); end else begin for I := 0 to ArgumentCount - 1 do begin S := S + JsStringToUnicodeString(Arg^); Inc(Arg); end; end; Print(S, Level, {$ifdef WINDOWS}False{$else}True{$endif}); // TODO Windows 10 console supports ANSI colors end; function TConsole.LogError(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; begin Result := Log(Arguments, ArgumentCount, ilError); end; function TConsole.LogInfo(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; begin Result := Log(Arguments, ArgumentCount, ilInfo); end; function TConsole.LogNone(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; begin Result := Log(Arguments, ArgumentCount, ilNone); end; function TConsole.LogWarn(Arguments: PJsValueRef; ArgumentCount: Word): JsValueRef; begin Result := Log(Arguments, ArgumentCount, ilWarn); end; procedure TConsole.Print(const S: UTF8String; Level: TInfoLevel; UseAnsiColors: Boolean); const StartBlocks: array[TInfoLevel] of RawByteString = ('', #$1b'[32;1m', #$1b'[33;1m', #$1b'[31;1m'); EndBlocks: array[Boolean] of RawByteString = ('', #$1b'[0m'); {$ifdef WINDOwS} BackgroundMask = $F0; TextColors: array[TInfoLevel] of Word = (0, FOREGROUND_GREEN or FOREGROUND_INTENSITY, FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY, FOREGROUND_RED or FOREGROUND_INTENSITY); var Info: TConsoleScreenBufferInfo; {$endif} begin {$ifdef WINDOWS} if UseAnsiColors then Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone]) else begin if (Level = ilNone) or not GetConsoleScreenBufferInfo(TTextRec(Output).Handle, Info) then begin Writeln(S); Exit; end; SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes and BackgroundMask or TextColors[Level]); try Writeln(S); finally SetConsoleTextAttribute(TTextRec(Output).Handle, Info.wAttributes); end; end; {$else} Writeln(StartBlocks[Level], S, EndBlocks[Level <> ilNone]); {$endif} end; procedure TConsole.Print(const S: UnicodeString; Level: TInfoLevel; UseAnsiColors: Boolean); begin Print(UTF8Encode(S), Level, UseAnsiColors); end; { TConsole protected } class procedure TConsole.RegisterMethods(AInstance: JsValueRef); begin RegisterMethod(AInstance, 'assert', @TConsole.Assert); RegisterMethod(AInstance, 'log', @TConsole.LogNone); RegisterMethod(AInstance, 'info', @TConsole.LogInfo); RegisterMethod(AInstance, 'warn', @TConsole.LogWarn); RegisterMethod(AInstance, 'error', @TConsole.LogError); RegisterMethod(AInstance, 'exception', @TConsole.LogError); end; end.
unit uthrImportarEtiquetas; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, clUtil, Messages, Controls, System.DateUtils, clProdutos, clTipoAssinatura, clConexao; type TCSVEtiqueta = record _codigo: String; _tipo: String; _nome: String; _cuidados: String; _endereco: String; _complemento: String; _referencia: String; _bairro: String; _cidade: String; _cep: String; _exemplares: String; _agente: String; _roteiro: String; _condicao: String; _ocorrencias: String; _revista: String; end; type thrImportarEtiquetas = class(TThread) private { Private declarations } CSVEtiqueta: TCSVEtiqueta; produto: TProdutos; tipo: TTipoAssinatura; conexao: TConexao; protected procedure Execute; override; procedure AtualizaProgress; procedure TerminaProcesso; function TrataLinha(sLinha: String): String; function RetornaProduto(sTexto: String): String; function RetornaTipo(sTexto: String): String; end; implementation { thrImportarEtiquetas } uses uGlobais, udm, ufrmProcesso; function thrImportarEtiquetas.TrataLinha(sLinha: String): String; var iConta: Integer; sLin: String; bFlag: Boolean; begin if Pos('"', sLinha) = 0 then begin Result := sLinha; Exit; end; iConta := 1; bFlag := False; sLin := ''; while sLinha[iConta] >= ' ' do begin if sLinha[iConta] = '"' then begin if bFlag then bFlag := False else bFlag := True; end; if bFlag then begin if sLinha[iConta] = ';' then sLin := sLin + ' ' else sLin := sLin + sLinha[iConta]; end else sLin := sLin + sLinha[iConta]; Inc(iConta); end; Result := sLin; end; procedure thrImportarEtiquetas.Execute; var ArquivoCSV: TextFile; Contador, I, LinhasTotal, iRet, iPos, iOcorrencias: Integer; Linha, campo, codigo, sMess, sData, sEdicao, sProduto, sTipo: String; d: Real; // LÍ Linha e Monta os valores function MontaValor: String; var ValorMontado: String; begin ValorMontado := ''; Inc(I); While Linha[I] >= ' ' do begin If Linha[I] = ';' then // vc pode usar qualquer delimitador ... eu // estou usando o ";" break; ValorMontado := ValorMontado + Linha[I]; Inc(I); end; Result := ValorMontado; end; begin LinhasTotal := iLinhas; // Carregando o arquivo ... AssignFile(ArquivoCSV, uGlobais.sParametro1); sData := uGlobais.sParemetro; try Reset(ArquivoCSV); Readln(ArquivoCSV, Linha); iPos := Pos('EDI«√O', Linha); sEdicao := Copy(Linha, iPos + 8, 8); iPos := Pos('PRODUTO:', Linha); sProduto := RetornaProduto(Copy(Linha, iPos + 9, Length(Linha))); sTipo := RetornaTipo(Copy(Linha, iPos + 9, Length(Linha))); Readln(ArquivoCSV, Linha); Readln(ArquivoCSV, Linha); Contador := 4; iOcorrencias := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, Linha); Linha := TrataLinha(Linha); with CSVEtiqueta do begin _codigo := MontaValor; _nome := MontaValor; _cuidados := MontaValor; _endereco := MontaValor; _complemento := MontaValor; _referencia := MontaValor; _bairro := MontaValor; _cidade := MontaValor; _cep := MontaValor; _exemplares := MontaValor; _agente := MontaValor; _roteiro := MontaValor; _condicao := MontaValor; _ocorrencias := MontaValor; _revista := MontaValor; if (not TryStrToInt(_ocorrencias, iOcorrencias)) then begin iOcorrencias := 0; end; dm.tbImportacaoEtiquetas.Insert; dm.tbImportacaoEtiquetasCOD_ASSINANTE.Value := _codigo; dm.tbImportacaoEtiquetasCOD_PRODUTO.Value := sProduto; dm.tbImportacaoEtiquetasNUM_EDICAO.Value := sEdicao; dm.tbimportacaoetiquetasCOD_TIPO_ASSINATURA.Value := sTipo; dm.tbImportacaoEtiquetasDAT_EDICAO.Value := StrToDate(sData); dm.tbImportacaoEtiquetasNOM_ASSINANTE.Value := _nome; dm.tbImportacaoEtiquetasNOM_CUIDADOS.Value := _cuidados; dm.tbImportacaoEtiquetasDES_ENDERECO.Value := _endereco; dm.tbImportacaoEtiquetasDES_COMPLEMENTO.Value := _complemento; dm.tbImportacaoEtiquetasDES_BAIRRO.Value := _bairro; dm.tbImportacaoEtiquetasDES_REFERENCIA.Value := _referencia; dm.tbImportacaoEtiquetasDES_CIDADE.Value := _cidade; dm.tbImportacaoEtiquetasDES_UF.Value := 'RJ'; dm.tbImportacaoEtiquetasCEP_ENDERECO.Value := _cep; dm.tbImportacaoEtiquetasQTD_EXEMPLARES.Value := StrToIntDef(_exemplares, 1); dm.tbImportacaoEtiquetasNUM_ROTEIRO.Value := StrToIntDef(_roteiro, 0); dm.tbImportacaoEtiquetasCOD_BARRA.Value := '0'; if iOcorrencias > 0 then begin dm.tbImportacaoEtiquetasDOM_PROTOCOLO.Value := 'S'; end else begin dm.tbImportacaoEtiquetasDOM_PROTOCOLO.Value := 'N'; end; dm.tbImportacaoEtiquetasID_REVISTA.Value := _revista; dm.tbImportacaoEtiquetas.Post; end; I := 0; iConta := Contador; iTotal := LinhasTotal; dPosicao := (iConta / iTotal) * 100; Inc(Contador, 1); if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin produto.Free; Abort; end; end; finally CloseFile(ArquivoCSV); Synchronize(TerminaProcesso); end; end; procedure thrImportarEtiquetas.AtualizaProgress; begin frmProcesso.cxProgressBar1.Position := dPosicao; frmProcesso.cxProgressBar1.Properties.Text := 'Registro ' + IntToStr(iConta) + ' de ' + IntToStr(iTotal); frmProcesso.cxProgressBar1.Refresh; end; procedure thrImportarEtiquetas.TerminaProcesso; begin dm.tbProdutos.Close; dm.tbProdutos.Open; produto := TProdutos.Create; if produto.getObjects() then begin dm.tbProdutos.LoadFromDataSet(dm.qryGetObject1); dm.qryGetObject1.Close; dm.qryGetObject1.SQL.Clear; produto.Free; end; dm.tbTipoAssinatura.Close; tipo := TTipoAssinatura.Create; if tipo.getObjects() then begin dm.tbTipoAssinatura.Open; dm.tbTipoAssinatura.LoadFromDataSet(dm.qryGetObject1); dm.qryGetObject1.Close; dm.qryGetObject1.SQL.Clear; end; tipo.Free; frmProcesso.Close; dm.dsImportaEtiquetas.Enabled := True; end; function thrImportarEtiquetas.RetornaProduto(sTexto: string): String; var I, Total, iParada: Integer; sCodigo, sDescricao: String; begin Result := ''; produto := TProdutos.Create; I := 0; iParada := 0; iTotal := Length(sTexto); sCodigo := ''; sDescricao := ''; for I := 0 to iTotal do begin if sTexto[I] <> ' ' then begin if Pos(sTexto[I], '0123456789ABC«DEFGHIJKLMNOPQRSTUVXWYZ') > 0 then begin sCodigo := sCodigo + sTexto[I]; end; end else begin iParada := I; break; end; end; iTotal := Pos('EDI«√O', sTexto); sDescricao := Trim(Copy(sTexto, iParada, iTotal - 5)); iTotal := Pos('(', sTexto) - 1; iParada := Pos('TIPO ASSINATURA:', sTexto) + 17; if (not produto.getObject(sCodigo, 'CODIGO')) then begin produto.codigo := Trim(sCodigo); produto.Descricao := Trim(sDescricao); produto.Operacao := 'I'; if (not produto.Insert()) then begin produto.Free; Exit; end; end; dm.qryGetObject1.Close; dm.qryGetObject1.SQL.Clear; produto.Free; Result := sCodigo; end; function thrImportarEtiquetas.RetornaTipo(sTexto: string): String; var I, Total, iParada: Integer; sCodigo, sDescricao, sTipo: String; begin Result := ''; tipo := TTipoAssinatura.Create; I := 0; iParada := 0; iTotal := Length(sTexto); sCodigo := ''; sDescricao := ''; iTotal := Length(sTexto); iParada := Pos('TIPO ASSINATURA:', sTexto) + 17; for I := iParada to iTotal do begin if sTexto[I] <> ' ' then begin if Pos(sTexto[I], '0123456789ABC«DEFGHIJKLMNOPQRSTUVXWYZ') > 0 then begin sCodigo := sCodigo + sTexto[I]; end; end else begin iParada := I; break; end; end; iTotal := Pos('(', sTexto, iParada); sDescricao := Trim(Copy(sTexto, iParada, iTotal - iParada)); if (not tipo.getObject(sCodigo, 'CODIGO')) then begin dm.qryGetObject1.Close; dm.qryGetObject1.SQL.Clear; tipo.codigo := sCodigo; tipo.Descricao := sDescricao; tipo.Operacao := 'I'; if (not tipo.Insert()) then begin tipo.Free; Exit; end; end; dm.qryGetObject1.Close; dm.qryGetObject1.SQL.Clear; tipo.Free; Result := sCodigo; end; end.
/// <summary> /// Provides the 'standard' implementation of the IProjectData interface /// as defined in fieldlogger.data.pas /// </summary> unit fieldlogger.projectdata.standard; interface uses Data.DB, FireDAC.Comp.Client, fieldlogger.Data; type TProjectData = class(TInterfacedObject, IProjectData) private [weak] fConnection: TFDConnection; // - Weak reference because we are not responsible for freeing. strict private // - IProjectData -// function CreateProject(Project: TProject): uint32; function Read(out Projects: TArrayOfProject; ID: uint32 = 0): integer; function Update(Projects: TArrayOfProject): boolean; function Delete(Projects: TArrayOfUInt32): boolean; public constructor Create(Connection: TFDConnection; out ValidConnection: boolean); reintroduce; destructor Destroy; override; end; implementation uses FireDAC.Stan.Param, sysutils; { TProjectData } constructor TProjectData.Create(Connection: TFDConnection; out ValidConnection: boolean); begin inherited Create; fConnection := Connection; // - Check that we have a valid connection which can connect to the database. ValidConnection := False; if fConnection.Connected then begin ValidConnection := True; exit; end; // Attempt connect try fConnection.Connected := True; except on E: Exception do begin exit; // - ValidConnection remains false end; end; // Check connected if not fConnection.Connected then begin exit; // ValidConnection remains false. end; ValidConnection := True; end; function TProjectData.CreateProject(Project: TProject): uint32; var qry: TFDQuery; begin Result := 0; qry := TFDQuery.Create(nil); try qry.Connection := fConnection; // - Using a select statement here instead of insert because, // - with select it is easier to obtain the primary key generated // - for this entry. qry.SQL.Text := 'SELECT * FROM PROJECTS;'; qry.Active := True; if not qry.Active then begin exit; end; qry.Append; qry.FieldByName('PROJ_ID').AsInteger := 0; qry.FieldByName('PROJ_TITLE').AsString := Project.Title; qry.FieldByName('PROJ_DESC').AsString := Project.Description; qry.Post; qry.Refresh; qry.Last; Result := qry.FieldByName('PROJ_ID').AsInteger; finally qry.DisposeOf; end; end; function TProjectData.Delete(Projects: TArrayOfUInt32): boolean; var transaction: TFDTransaction; qry: TFDQuery; idx: integer; begin Result := False; if Length(Projects) = 0 then begin Result := True; exit; end; transaction := TFDTransaction.Create(nil); try transaction.Connection := fConnection; transaction.StartTransaction; try qry := TFDQuery.Create(nil); try qry.Connection := fConnection; qry.transaction := transaction; qry.SQL.Text := 'DELETE FROM PROJECTS WHERE PROJ_ID=:ID;'; for idx := 0 to pred(Length(Projects)) do begin qry.Params.ParamByName('ID').AsInteger := Projects[idx]; try qry.ExecSQL; except on E: Exception do begin transaction.Rollback; raise; // <- For exception safe, replace this with exit, function will exit result=FALSE end; end; end; finally qry.DisposeOf; end; finally transaction.Commit; Result := True; end; finally transaction.DisposeOf; end; end; destructor TProjectData.Destroy; begin fConnection := nil; inherited Destroy; end; function TProjectData.Read(out Projects: TArrayOfProject; ID: uint32): integer; var qry: TFDQuery; idx: integer; begin Result := 0; SetLength(Projects, 0); qry := TFDQuery.Create(nil); try qry.Connection := fConnection; if ID = 0 then begin qry.SQL.Text := 'SELECT * FROM PROJECTS;'; end else begin qry.SQL.Text := 'SELECT * FROM PROJECTS WHERE PROJ_ID=:ID;'; qry.Params.ParamByName('ID').AsInteger := ID; end; qry.Active := True; if not qry.Active then begin exit; end; if qry.RecordCount = 0 then begin exit; end; SetLength(Projects, qry.RecordCount); idx := 0; qry.First; while not qry.EOF do begin Projects[idx].ID := qry.FieldByName('PROJ_ID').AsInteger; Projects[idx].Title := qry.FieldByName('PROJ_TITLE').AsString; Projects[idx].Description := qry.FieldByName('PROJ_DESC').AsString; inc(idx); qry.Next; end; Result := qry.RecordCount; finally qry.DisposeOf; end; end; function TProjectData.Update(Projects: TArrayOfProject): boolean; var transaction: TFDTransaction; qry: TFDQuery; idx: integer; begin Result := False; if Length(Projects) = 0 then begin Result := True; exit; end; transaction := TFDTransaction.Create(nil); try transaction.Connection := fConnection; transaction.StartTransaction; try qry := TFDQuery.Create(nil); try qry.Connection := fConnection; qry.transaction := transaction; qry.SQL.Text := 'UPDATE PROJECTS SET PROJ_TITLE=:PROJ_TITLE, PROJ_DESC=:PROJ_DESC WHERE PROJ_ID=:ID;'; for idx := 0 to pred(Length(Projects)) do begin qry.Params.ParamByName('ID').AsInteger := Projects[idx].ID; qry.Params.ParamByName('PROJ_TITLE').AsString := Projects[idx].Title; qry.Params.ParamByName('PROJ_DESC').AsString := Projects[idx].Description; try qry.ExecSQL; except on E: Exception do begin transaction.Rollback; raise; // <- For exception safe, replace this with exit, function will exit result=FALSE end; end; end; finally qry.DisposeOf; end; finally transaction.Commit; Result := True; end; finally transaction.DisposeOf; end; end; end.
(* Document Server's shared module for client system, DSAPI DLLs and Server projects. Notes: - Mixed 16/32-bit version *) Unit DSAPICom; {*****************************************************************************} {*} Interface {*} {*****************************************************************************} Uses SysUtils; type FM_TStorageType = (FM_cNullStorage, FM_cWorkStorage, FM_cTemporaryArchiveStorage, FM_cPermanentArchiveStorage); const FM_cArchiveStorageTypes = [FM_cTemporaryArchiveStorage, FM_cPermanentArchiveStorage]; { Version IDs specifiers } DS_cAllVersions = -1; DS_cLastVersion = -2; DS_cFirstVersion = -3; { Error codes } DS_cSuccess = 0; DS_cOK = 0; DS_cError = -1; { unspecified error's ID } DS_cErrorVersionNotFound = -2; DS_cErrorDocumentNotFound = -3; { Command codes } DS_cCmdPut = 1; DS_cCmdGet = 2; DS_cCmdDelete = 3; DS_cCmdArchive = 4; DS_cCmdQuery = 5; DS_cCmdReBuildIndex = 6; DS_cCmdGetServerInfo = 7; DS_cCmdUnLockVersion = 8; { File types } DS_cText = 1; DS_cHTML = 2; DS_cDOC95 = 3; DS_cRTF95 = 4; DS_cDOC97 = 5; DS_cRTF97 = 6; DS_cMediumStringLength = 80; DS_cShortStringLength = 32; DS_cTinyStringLength = 16; type {$IfDef WIN32} DS_TString = ShortString; {$Else} DS_TString = string; {$EndIf} DS_TPathString = string[79]; DS_TMediumString = string[DS_cMediumStringLength]; DS_TShortString = string[DS_cShortStringLength]; DS_TTinyString = string[DS_cTinyStringLength]; { Server's description data } DS_TServerInfo = packed record ProductName: DS_TShortString; { product & build information } DeveloperInfo: DS_TMediumString; MajorVersion, MinorVersion, Build: longint; BuildTime: DS_TTinyString; isSearchEnginePresent: boolean; { true if search engine present } isClientSystemControllerPresent: boolean; end; DS_TFileType = longint; DS_PQueryResult = ^DS_TQueryResult; DS_TQueryResult = packed record DocIDInClientSystem, VerIDInClientSystem, DocIDOnServer, VerIDOnServer: longint; end; DS_TInitData = packed record ServerName: DS_TString; Port: longint; DataReceiveTimeOutMSecs, { timeouts for send/receive data } DataSendTimeOutMSecs: longint; { use 0 for default system timeouts } { control (not recomend.) } Protocol:integer; end; DS_TArchiveAction = (DS_cArchive, DS_cRestore); DS_TFileTransferMode = (DS_cNormal, DS_cTextOnly, DS_cNull); { main data exchange packet } DS_RUnifiedExchangeDataPacket = packed record { server descriptor } ServerInfo: DS_TServerInfo; { client descriptor } ClientSystemID, UserID: longint; UserName: DS_TShortString; PhysicalUserID: longint; PhysicalUserName: DS_TShortString; { file/version descriptor } DocIDInClientSystem, VerIDInClientSystem, DocIDOnServer, VerIDOnServer: longint; FileTypeID: DS_TFileType; { result code } ErrorCode: longint; { Query control} QueryStartFrom, QueryResultsCount: longint; { command modifiers } ArchiveAction: DS_TArchiveAction; isEditMode: boolean; AutoUnLockDateTime: TDateTime; isFullRebuild: boolean; FileTransferMode: DS_TFileTransferMode; { internally used by DSAPI DLL } QueryResult: DS_PQueryResult; CommandID: longint; { internally used by Server } UserLocation: DS_TShortString; { network address of user's WS } StorageID: longint; { storage for version } WorkCopyStorageID: longint; { storage for copy from Permanent Archive} StorageType: FM_TStorageType; isNewVersion, isNewDocument: boolean; { for cmd. Put - new version/document flags } { other fields } FileName: DS_TPathString; { internally used by DSAPI & Server } case Byte of 1: (QueryString: DS_TString); 2: (ErrorMessage: DS_TString); 3: (OldFileName: DS_TPathString); { internally used by Server } end; DS_TAbstractDocumentServer = class protected FErrorCode: longint; FErrorMessage: DS_TString; function RErrorMessage: DS_TString; virtual; public function cmdPut(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdGet(var UEDP: DS_RUnifiedExchangeDataPacket): longint ; virtual; abstract; function cmdDelete(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdArchive(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdQuery(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdSettings(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdReBuildIndex(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdGetServerInfo(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; function cmdUnLockVersion(var UEDP: DS_RUnifiedExchangeDataPacket): longint; virtual; abstract; property ErrorCode: longint read FErrorCode; property ErrorMessage: DS_TString read RErrorMessage; end; function DS_CommandIDToStr(CommandID: longint): DS_TString; function DS_CommandParamsToStr(const UEDP: DS_RUnifiedExchangeDataPacket): DS_TString; function DS_ExecResultToStr(const UEDP: DS_RUnifiedExchangeDataPacket): DS_TString; {*****************************************************************************} {*} Implementation {*} {*****************************************************************************} function DS_CommandIDToStr(CommandID: longint): DS_TString; begin case CommandID of DS_cCmdPut: Result := 'PUT'; DS_cCmdGet: Result := 'GET/LOCK'; DS_cCmdDelete: Result :='DELETE'; DS_cCmdArchive: Result := 'ARCHIVE'; DS_cCmdQuery: Result := 'QUERY'; DS_cCmdReBuildIndex: Result := 'ProceedIndex'; DS_cCmdGetServerInfo: Result := 'GetServerInfo'; DS_cCmdUnLockVersion: Result := 'UNLOCK'; else Result := 'Unknown'; end; Result := Result +'('+IntToStr(CommandID)+')'; end; {-----------------------------------------------------------------------------} function DS_CommandParamsToStr(const UEDP: DS_RUnifiedExchangeDataPacket): DS_TString; function VersionInfo: string; var s: string; begin case UEDP.VerIDInClientSystem of DS_cAllVersions: s := 'ALL'; DS_cLastVersion: s := 'LAST'; DS_cFirstVersion: s := 'FIRST'; else s := IntToStr(UEDP.VerIDInClientSystem); end; Result := 'Doc='+IntToStr(UEDP.DocIDInClientSystem)+' '+ 'Ver='+s+'. '; end; function UserInfo: string; begin Result := 'CSID='+IntToStr(UEDP.ClientSystemID)+' '+ 'UserID='+IntToStr(UEDP.UserID)+' '+ 'UserName="'+UEDP.UserName+'". '; end; var s: string; begin {DS_CommandParamsToStr} case UEDP.CommandID of DS_cCmdPut: Result := VersionInfo; DS_cCmdGet: begin Result := VersionInfo+' Mode='; if UEDP.isEditMode then Result := Result+'EDIT&LOCK' else Result := Result+'VIEW'; Result := Result + '. FileTransferMode='; case UEDP.FileTransferMode of DS_cNormal: Result := Result + 'Normal'; DS_cTextOnly: Result := Result + 'TextOnly'; DS_cNull: Result := Result + 'Null'; end; end; DS_cCmdDelete: Result := VersionInfo; DS_cCmdArchive: begin case UEDP.ArchiveAction of DS_cArchive: s := 'ARCHIVE'; DS_cRestore: s := 'RESTORE'; else s := '?' end; Result := VersionInfo+'Mode='+s; end; DS_cCmdQuery: Result := 'QS: "'+UEDP.QueryString+'"'; DS_cCmdReBuildIndex: if UEDP.isFullRebuild then Result := 'Mode=FULL.' else Result := 'Mode=UPDATE.'; DS_cCmdGetServerInfo: Result := ''; DS_cCmdUnLockVersion: Result := VersionInfo; else Result := 'CommandID='+IntToStr(UEDP.CommandID); end; Result := UserInfo+Result; end; {-----------------------------------------------------------------------------} function DS_ExecResultToStr(const UEDP: DS_RUnifiedExchangeDataPacket): DS_TString; function FileInfo: string; begin if (UEDP.StorageID=0) or (UEDP.FileName='') then Result := '' else Result := Format('FileName=%s. StorageID=%d. StorageTypeID=%d. ', [UEDP.FileName, UEDP.StorageID, Integer(UEDP.StorageType)]); end; begin case UEDP.CommandID of DS_cCmdPut, DS_cCmdGet, DS_cCmdDelete, DS_cCmdArchive: Result := FileInfo; DS_cCmdQuery: Result := Format('Total hit(s)=%d', [UEDP.QueryResultsCount]); DS_cCmdReBuildIndex: Result := ''; DS_cCmdGetServerInfo: Result := ''; DS_cCmdUnLockVersion: Result := ''; else Result := ''; end; if Result<>'' then Result:='. Details: '+Result; end; {-----------------------------------------------------------------------------} function DS_TAbstractDocumentServer.RErrorMessage: DS_TString; begin RErrorMessage:=FErrorMessage; end; END.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CTE_AEREO] 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 CteAereoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('CTE_AEREO')] TCteAereoVO = class(TVO) private FID: Integer; FID_CTE_CABECALHO: Integer; FNUMERO_MINUTA: Integer; FNUMERO_CONHECIMENTO: Integer; FDATA_PREVISTA_ENTREGA: TDateTime; FID_EMISSOR: String; FID_INTERNA_TOMADOR: String; FTARIFA_CLASSE: String; FTARIFA_CODIGO: String; FTARIFA_VALOR: Extended; FCARGA_DIMENSAO: String; FCARGA_INFORMACAO_MANUSEIO: Integer; FCARGA_ESPECIAL: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_CTE_CABECALHO', 'Id Cte Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCteCabecalho: Integer read FID_CTE_CABECALHO write FID_CTE_CABECALHO; [TColumn('NUMERO_MINUTA', 'Numero Minuta', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property NumeroMinuta: Integer read FNUMERO_MINUTA write FNUMERO_MINUTA; [TColumn('NUMERO_CONHECIMENTO', 'Numero Conhecimento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property NumeroConhecimento: Integer read FNUMERO_CONHECIMENTO write FNUMERO_CONHECIMENTO; [TColumn('DATA_PREVISTA_ENTREGA', 'Data Prevista Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataPrevistaEntrega: TDateTime read FDATA_PREVISTA_ENTREGA write FDATA_PREVISTA_ENTREGA; [TColumn('ID_EMISSOR', 'Id Emissor', 160, [ldGrid, ldLookup, ldCombobox], False)] property IdEmissor: String read FID_EMISSOR write FID_EMISSOR; [TColumn('ID_INTERNA_TOMADOR', 'Id Interna Tomador', 112, [ldGrid, ldLookup, ldCombobox], False)] property IdInternaTomador: String read FID_INTERNA_TOMADOR write FID_INTERNA_TOMADOR; [TColumn('TARIFA_CLASSE', 'Tarifa Classe', 8, [ldGrid, ldLookup, ldCombobox], False)] property TarifaClasse: String read FTARIFA_CLASSE write FTARIFA_CLASSE; [TColumn('TARIFA_CODIGO', 'Tarifa Codigo', 32, [ldGrid, ldLookup, ldCombobox], False)] property TarifaCodigo: String read FTARIFA_CODIGO write FTARIFA_CODIGO; [TColumn('TARIFA_VALOR', 'Tarifa Valor', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TarifaValor: Extended read FTARIFA_VALOR write FTARIFA_VALOR; [TColumn('CARGA_DIMENSAO', 'Carga Dimensao', 112, [ldGrid, ldLookup, ldCombobox], False)] property CargaDimensao: String read FCARGA_DIMENSAO write FCARGA_DIMENSAO; [TColumn('CARGA_INFORMACAO_MANUSEIO', 'Carga Informacao Manuseio', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CargaInformacaoManuseio: Integer read FCARGA_INFORMACAO_MANUSEIO write FCARGA_INFORMACAO_MANUSEIO; [TColumn('CARGA_ESPECIAL', 'Carga Especial', 24, [ldGrid, ldLookup, ldCombobox], False)] property CargaEspecial: String read FCARGA_ESPECIAL write FCARGA_ESPECIAL; //Transientes end; implementation initialization Classes.RegisterClass(TCteAereoVO); finalization Classes.UnRegisterClass(TCteAereoVO); end.
{ System-dependent routines. This module is intended to be rewritten for * different target operating systems. This version is for Windows 2000 * and later. } module picprg_sys; define picprg_sys_usbprog_enum; define picprg_sys_name_open; define picprg_sys_usb_write; define picprg_sys_usb_read; define picprg_sys_usbprog_close; %include 'picprg2.ins.pas'; { ******************************************************************************** * * Subroutine PICPRG_SYS_USBPROG_ENUM (DEVS) } procedure picprg_sys_usbprog_enum ( {add all USBProgs to devices list} in out devs: picprg_devs_t); {list to add devices to} val_param; var udevs: file_usbdev_list_t; {list of USB devices with our VID/PID} udev_p: file_usbdev_p_t; {pointer to current entry in UDEVS} stat: sys_err_t; begin file_embusb_list_get ( {make list of PICPRG USB devices} file_usbid(picprg_vid_k, picprg_pid_k), {USB unique ID of device} util_top_mem_context, {parent mem context for list context} udevs, {the returned list} stat); if sys_error(stat) then return; {couldn't get list, nothing to do ?} udev_p := udevs.list_p; {init pointer to first list entry} while udev_p <> nil do begin {loop thru all the USB devices list entries} picprg_devs_add (devs); {add new entry to end of DEVS list} string_copy (udev_p^.name, devs.last_p^.name); {copy data from UDEVS entry} devs.last_p^.devconn := picprg_devconn_usb_k; string_copy (udev_p^.path, devs.last_p^.path); udev_p := udev_p^.next_p; {advance to next entry in UDEVS list} end; file_usbdev_list_del (udevs); {deallocate temporary list resources} end; { ******************************************************************************** * * Subroutine PICPRG_SYS_NAME_OPEN (NAME, CONN, DEVCONN, STAT) * * Open a connection to a named PIC programmer. NAME is the user name of the * specific USBProg to open. * * If NAME is empty, then the first available programmer is opened. No * particular order is guaranteed, so if multiple programmers are available the * selection will be arbitrary. * * If NAME is not empty, then the first available programmer with that user * name is opened. It is intended that the user ensure that user names are * unique among all programmers connected to a machine. * * CONN is the returned I/O connection to the newly opened programmer. * Subsequent attempts to open that programmer will fail until CONN is closed. * DEVCONN is returned the type of I/O connection to the programmer. } procedure picprg_sys_name_open ( {open connection to named PIC programmer} in name: univ string_var_arg_t; {name of USBProg to open, opens first on empty} out conn: file_conn_t; {returned connection to the USBProg} out devconn: picprg_devconn_k_t; {type of connection to the programmer} out stat: sys_err_t); {completion status} val_param; begin devconn := picprg_devconn_usb_k; {this connection will always be via USB} file_open_embusb ( {open connection to the programmer} file_usbid(picprg_vid_k, picprg_pid_k), {USB unique ID of device} name, {user-defined name of the programmer} conn, {returned I/O connection} stat); end; { ******************************************************************************* * * Subroutine PICPRG_SYS_USB_WRITE (CONN, BUF, LEN, STAT) } procedure picprg_sys_usb_write ( {send data to a USBProg} in conn: file_conn_t; {existing connection to the USBProg} in buf: univ char; {data to write} in len: sys_int_adr_t; {number of machine adr increments to write} out stat: sys_err_t); {completion status code} val_param; begin file_write_embusb (buf, conn, len, stat); end; { ******************************************************************************* * * Subroutine PICPRG_SYS_USB_READ (CONN, ILEN, BUF, OLEN, STAT) * * Read the next chunk of data from the USB device. ILEN is the maximum number * of bytes to read into BUF. OLEN is returned the number of bytes actually * read, which will always be from 1 to 64 on no error. This routine blocks * indefinitely until at least one byte is available. } procedure picprg_sys_usb_read ( {read next chunk of bytes from USBProg} out conn: file_conn_t; {existing connection to the USBProg} in ilen: sys_int_adr_t; {max number of machine adr increments to read} out buf: univ char; {returned data} out olen: sys_int_adr_t; {number of machine adresses actually read} out stat: sys_err_t); {completion status code} val_param; begin file_read_embusb (conn, ilen, buf, olen, stat); end; { ******************************************************************************* * * Subroutine PICPRG_SYS_USBPROG_CLOSE (CONN_P) } procedure picprg_sys_usbprog_close ( {private close routine for USBProg connection} in conn_p: file_conn_p_t); {pointer to connection to close} val_param; begin file_close (conn_p^); end;
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Unit2; type TForm1 = class(TForm) Label1: TLabel; Panel1: TPanel; Label2: TLabel; Edit1: TEdit; Button1: TButton; procedure Button1Click(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure openMainPage(); begin end; procedure TForm1.Button1Click(Sender: TObject); var MainForm: TForm2; begin if (Length(Edit1.Text) < 1) then begin MessageBox(Handle, 'Поле с логином не может быть пустым!', 'Внимание!', MB_OK + MB_ICONWARNING); Exit; end; MainForm := TForm2.Create(self); MainForm.ClientUserName := AnsiToUtf8(Edit1.Text); MainForm.Show; Self.Hide; end; procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if Ord(Key) = VK_RETURN then begin Button1.Click; end; end; end.
unit BIORAD; // ----------------------------------- // BIORAD file format handling component // ----------------------------------- // 21.04.03 interface uses SysUtils, Classes, Dialogs ; const PICSignature = 12345 ; type TPICFileHeader = packed record FrameWidth : SmallInt ; // Image width (pixels) FrameHeight : SmallInt ; // Image height (pixels) NumFrames : SmallInt ; // No. images in file LUT1Min : SmallInt ; // Lower intensity limit of LUT map LUT1Max : SmallInt ; // Upper intensity limit of LUT map NotesOffset : Integer ; // Offset of notes lines in file ByteImage : SmallInt ; // 1=8 bit, 0=16 bit image ImageNumber : SmallInt ; // Image no. within file FileName : Array[1..32] of Char ; // File name Merged : SmallInt ; // Merged format?? LUT1Color : Word ; // LUT1 colour status Signature : SmallInt ; // PIC file signature = 12345 LUT2Min : SmallInt ; // Lower intensity limit of LUT2 map LUT2Max : SmallInt ; // Upper intensity limit of LUT2 map LUT2Color : Word ; // LUT2 colour status Edited : SmallInt ; // 1=file has been edited ILensMagnification : SmallInt ; // Integer lens magnfication factor FLensMagnification : Single ; // Floating point lens magnfication factor Free : Array[1..3] of SmallInt ; end ; TBIORAD = class(TComponent) private { Private declarations } PICHeader : TPICFileHeader ; // PIC file header block FileHandle : Integer ; // PIC file handle FFrameWidth : Integer ; // Image width FFrameHeight : Integer ; // Image height FPixelDepth : Integer ; // No. of bits per pixel FNumFrames : Integer ; // No. of images in file protected { Protected declarations } public { Public declarations } Constructor Create(AOwner : TComponent) ; override ; Destructor Destroy ; override ; function OpenFile( FileName : String ) : Boolean ; function CreateFile( FileName : String ; FrameWidth : Integer ; FrameHeight : Integer ; PixelDepth : Integer ) : Boolean ; function LoadFrame( FrameNum : Integer ; PFrameBuf : Pointer ) : Boolean ; function SaveFrame( FrameNum : Integer ; PFrameBuf : Pointer ) : Boolean ; published { Published declarations } Property FrameWidth : Integer Read FFrameWidth ; Property FrameHeight : Integer Read FFrameHeight ; Property PixelDepth : Integer Read FPixelDepth ; Property NumFrames : Integer Read FNumFrames ; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TBIORAD]); end; constructor TBIORAD.Create(AOwner : TComponent) ; { -------------------------------------------------- Initialise component's internal objects and fields -------------------------------------------------- } begin inherited Create(AOwner) ; FileHandle := -1 ; FFrameWidth := 0 ; FFrameHeight := 0 ; FPixelDepth := 0 ; FNumFrames := 0 ; end ; destructor TBIORAD.Destroy ; { ------------------------------------ Tidy up when component is destroyed ----------------------------------- } begin // Close PIC file if FileHandle >= 0 then FileClose( FileHandle ) ; { Call inherited destructor } inherited Destroy ; end ; function TBioRAD.OpenFile( FileName : String ) : Boolean ; // --------------------------- // Open BioRad PIC data file // --------------------------- var Done : Boolean ; // Loop done flag begin Result := False ; if FileHandle >= 0 then begin MessageDlg( 'BIORAD: A file is aready open ', mtWarning, [mbOK], 0 ) ; Exit ; end ; // Open file FileHandle := FileOpen( FileName, fmOpenRead ) ; if FileHandle < 0 then begin MessageDlg( 'BIORAD: Unable to open ' + FileName, mtWarning, [mbOK], 0 ) ; Exit ; end ; // Read PIC file header FileSeek(FileHandle,0,0) ; if FileRead(FileHandle, PICHeader, SizeOf(PICHeader)) <> SizeOf(PICHeader) then begin ; MessageDlg( 'BIORAD: Unable to read BioRad PIC file ' + FileName, mtWarning, [mbOK], 0 ) ; FileClose( FileHandle ) ; FileHandle := -1 ; Exit ; end ; // Check PIC file signature if PICHeader.Signature <> PICSignature then begin MessageDlg( 'BIORAD: ' + FileName + ' not a PIC file!', mtWarning, [mbOK], 0 ) ; FileClose( FileHandle ) ; FileHandle := -1 ; Exit ; end ; FFrameWidth := PICHeader.FrameWidth ; FFrameHeight := PICHeader.FrameHeight ; if PICHeader.ByteImage = 1 then FPixelDepth := 8 else FPixelDepth := 16 ; FNumFrames := PICHeader.NumFrames ; Result := True ; end ; function TBioRAD.CreateFile( FileName : String ; // Name of file to be created FrameWidth : Integer ; // Frame width FrameHeight : Integer ; // Frame height PixelDepth : Integer // No. of bits per pixel ) : Boolean ; // Returns TRUE if file created OK // --------------------------------- // Create empty BioRad PIC data file // --------------------------------- var Done : Boolean ; // Loop done flag begin Result := False ; if FileHandle >= 0 then begin MessageDlg( 'BIORAD: A file is aready open ', mtWarning, [mbOK], 0 ) ; Exit ; end ; // Open file FileHandle := FileCreate( FileName, fmOpenRead ) ; if FileHandle < 0 then begin MessageDlg( 'BIORAD: Unable to create ' + FileName, mtWarning, [mbOK], 0 ) ; Exit ; end ; // Initialise file header` FFrameWidth := FrameWidth ; FFrameHeight := FrameHeight ; FPixelDepth := PixelDepth ; PICHeader.FrameWidth := FFrameWidth ; PICHeader.FrameHeight := FFrameHeight ; if FPixelDepth <= 8 then PICHeader.ByteImage := 1 else PICHeader.ByteImage := 0 ; FNumFrames := 0 ; PICHeader.NumFrames := FNumFrames ; PICHeader.Signature := PICSignature ; Result := True ; end ; function TBioRAD.LoadFrame( FrameNum : Integer ; PFrameBuf : Pointer ) : Boolean ; // ---------------------------------------- // Load frame from BioRad PIC data file // ---------------------------------------- var NumBytesPerFrame : Integer ; // No. of bytes per image frame FilePointer : Integer ; // File offset begin if (FrameNum < 1) or (FrameNum > FNumFrames) then begin Result := False ; Exit ; end ; // Find file offset of start of frame NumBytesPerFrame := FFrameWidth*FFrameHeight ; if PICHeader.ByteImage <> 1 then NumBytesPerFrame := NumBytesPerFrame*2 ; FilePointer := SizeOf(TPICFileHeader) + (FrameNum-1)*NumBytesPerFrame ; // Read data from file FileSeek( FileHandle, FilePointer, 0 ) ; if FileRead(FileHandle, PFrameBuf^, NumBytesPerFrame) = NumBytesPerFrame then Result := True else Result := False ; end ; function TBioRAD.SaveFrame( FrameNum : Integer ; // No. of frame to write PFrameBuf : Pointer ) : Boolean ;// Pointer to image buffer // ---------------------------------------- // Save frame to BioRad PIC data file // ---------------------------------------- var NumBytesPerFrame : Integer ; // No. of bytes per image frame FilePointer : Integer ; // File offset begin if (FrameNum < 1) then begin Result := False ; Exit ; end ; // Find file offset of start of frame NumBytesPerFrame := FFrameWidth*FFrameHeight ; if PICHeader.ByteImage <> 1 then NumBytesPerFrame := NumBytesPerFrame*2 ; FilePointer := SizeOf(TPICFileHeader) + (FrameNum-1)*NumBytesPerFrame ; // Read data from file FileSeek( FileHandle, FilePointer, 0 ) ; if FileWrite(FileHandle, PFrameBuf^, NumBytesPerFrame) = NumBytesPerFrame then Result := True else Result := False ; end ; end.
unit Unit1; { String Exchange Server Demo INDY10.5.X It just shows how to send and receive String. No error handling Most of the code is bdlm's. Adnan Email: helloy72@yahoo.com compile and execute with DELPHI XE 2 is OK (bdlm 06.11.2011& 06.03.2012) add TEncoding (change according to your needs) } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IdContext, IdSync, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdGlobal; type TStringServerForm = class(TForm) CheckBox1: TCheckBox; Memo1: TMemo; IdTCPServer1: TIdTCPServer; procedure CheckBox1Click(Sender: TObject); procedure IdTCPServer1Execute(AContext: TIdContext); procedure IdTCPServer1Connect(AContext: TIdContext); procedure FormCreate(Sender: TObject); procedure IdTCPServer1Disconnect(AContext: TIdContext); procedure IdTCPServer1Exception(AContext: TIdContext; AException: Exception); private procedure ShowStartServerdMessage; procedure StopStartServerdMessage; { Private declarations } public { Public declarations } end; var StringServerForm: TStringServerForm; implementation {$R *.dfm} procedure TStringServerForm.CheckBox1Click(Sender: TObject); begin if ( CheckBox1.Checked = True ) then IdTCPServer1.Active := True else IdTCPServer1.Active := False; end; procedure TStringServerForm.FormCreate(Sender: TObject); begin IdTCPServer1.Bindings.Add.IP := '127.0.0.1'; IdTCPServer1.Bindings.Add.Port := 6000; end; procedure TStringServerForm.IdTCPServer1Connect(AContext: TIdContext); begin Memo1.Lines.Add('A client connected'); end; procedure TStringServerForm.IdTCPServer1Disconnect(AContext: TIdContext); begin Memo1.Lines.Add('A client disconnected'); end; procedure TStringServerForm.IdTCPServer1Exception(AContext: TIdContext; AException: Exception); begin Memo1.Lines.Add('A exception happend !'); end; procedure TStringServerForm.ShowStartServerdMessage; begin Memo1.Lines.Add('START SERVER @' + TimeToStr(now)); end; procedure TStringServerForm.StopStartServerdMessage; begin Memo1.Lines.Add('STOP SERVER @' + TimeToStr(now)); end; procedure TStringServerForm.IdTCPServer1Execute(AContext: TIdContext); var LLine: String; begin TIdNotify.NotifyMethod( ShowStartServerdMessage ); LLine := AContext.Connection.IOHandler.ReadLn(TIdTextEncoding.Default); Memo1.Lines.Add(LLine); AContext.Connection.IOHandler.WriteLn('OK'); TIdNotify.NotifyMethod( StopStartServerdMessage ); end; end.
{ *********************************************************************** } { } { Mineframe System } { dll to calc conditioned intervals } { } { use technique by } // ГКЗ { Create date: 08.07.2017} { Developer: Alisov A.Y. } { } { *********************************************************************** } unit IOTypes; interface type /// <summary> /// входной тип данных для библиотеки /// </summary> TInputSample = record _length, _grade: double; end; /// <summary> /// выходной тип данных для библиотеки /// </summary> TOutputSample = record ctype: byte; length, grade, metergrade: double; end; TISampleArray = array of TInputSample; TOSampleArray = array of TOutputSample; implementation end.
unit fileaccess; {$mode delphi} interface {$IFDEF windows} uses jwaWindows, windows,Classes, SysUtils; procedure MakePathAccessible(path: widestring); {$ENDIF} implementation {$IFDEF windows} resourcestring rsNoGetNamedSecurityInfo = 'no GetNamedSecurityInfo'; rsNoGetSecurityInfo = 'no GetSecurityInfo'; rsNoSetEntriesInAcl = 'no SetEntriesInAcl'; rsNoSetNamedSecurityInfo = 'no SetNamedSecurityInfo'; const SECURITY_WORLD_SID_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 1)); type PTRUSTEE_W=^TRUSTEE_W; TRUSTEE_W = record pMultipleTrustee: PTRUSTEE_W; MultipleTrusteeOperation: MULTIPLE_TRUSTEE_OPERATION; TrusteeForm: TRUSTEE_FORM; TrusteeType: TRUSTEE_TYPE; ptstrName: LPWCH; end; type EXPLICIT_ACCESS_W = record grfAccessPermissions: DWORD; grfAccessMode: ACCESS_MODE; grfInheritance: DWORD; Trustee: TRUSTEE_W; end; PEXPLICIC_ACCESS_W=^EXPLICIT_ACCESS_W; var SetNamedSecurityInfo: function(pObjectName: PWideChar; ObjectType: SE_OBJECT_TYPE; SecurityInfo: SECURITY_INFORMATION; ppsidOwner, ppsidGroup: PSID; ppDacl, ppSacl: PACL): DWORD; stdcall; var GetNamedSecurityInfo: function(pObjectName: PWidechar; ObjectType: SE_OBJECT_TYPE; SecurityInfo: SECURITY_INFORMATION; ppsidOwner, ppsidGroup: PPSID; ppDacl, ppSacl: PPACL; var ppSecurityDescriptor: PSECURITY_DESCRIPTOR): DWORD; stdcall; var GetSecurityInfo: function(handle: HANDLE; ObjectType: SE_OBJECT_TYPE; SecurityInfo: SECURITY_INFORMATION; ppsidOwner: PPSID; ppsidGroup: PPSID; ppDacl, ppSacl: PPACL; var ppSecurityDescriptor: PSECURITY_DESCRIPTOR): DWORD; stdcall; var SetEntriesInAcl: function(cCountOfExplicitEntries: ULONG; pListOfExplicitEntries: PEXPLICIT_ACCESS_W; OldAcl: PACL; var NewAcl: PACL): DWORD; stdcall; procedure MakePathAccessible(path: widestring); var l: tstringlist; z: SID_IDENTIFIER_AUTHORITY; sid: pointer; sec: PSECURITY_DESCRIPTOR; dacl: pacl; newdacl: pacl; i: dword; f: thandle; ea: EXPLICIT_ACCESS_W; cbName,cbDomain : Cardinal; advapi: thandle; begin advapi:=loadlibrary('Advapi32.dll'); GetNamedSecurityInfo:=getprocaddress(advapi, 'GetNamedSecurityInfoW'); GetSecurityInfo:=getprocaddress(advapi, 'GetSecurityInfo'); SetEntriesInAcl:=getprocaddress(advapi, 'SetEntriesInAclW'); SetNamedSecurityInfo:=getprocaddress(advapi, 'SetNamedSecurityInfoW'); if not assigned(GetNamedSecurityInfo) then raise exception.create(rsNoGetNamedSecurityInfo); if not assigned(GetSecurityInfo) then raise exception.create(rsNoGetSecurityInfo); if not assigned(SetEntriesInAcl) then raise exception.create(rsNoSetEntriesInAcl); if not assigned(SetNamedSecurityInfo) then raise exception.create(rsNoSetNamedSecurityInfo); // showmessage(advancedoptionsunit.strcouldntrestorecode); //function CreateFile(lpFileName:LPCSTR; dwDesiredAccess:DWORD; dwShareMode:DWORD; lpSecurityAttributes:LPSECURITY_ATTRIBUTES; dwCreationDisposition:DWORD;dwFlagsAndAttributes:DWORD; hTemplateFile:HANDLE):HANDLE; external 'kernel32' name 'CreateFileA'; // z:=0; //f:=CreateFile('C:\temp',0,0, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,0); //if f=INVALID_HANDLE_VALUE then raise exception.create('failed to open dir'); z:=SECURITY_WORLD_SID_AUTHORITY; sid:=nil; if AllocateAndInitializeSid(SECURITY_WORLD_SID_AUTHORITY,1,SECURITY_WORLD_RID,0,0,0,0,0,0,0,sid) then //the everyone group begin sec:=nil; dacl:=nil; i:=GetNamedSecurityInfo(pwidechar(path), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil,nil, @dacl, nil, sec); if i=ERROR_SUCCESS then begin zeromemory(@ea,sizeof(ea)); ea.grfAccessPermissions:=GENERIC_ALL; ea.grfAccessMode:=GRANT_ACCESS; ea.grfInheritance:=SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea.Trustee.TrusteeForm:=TRUSTEE_IS_SID; ea.Trustee.TrusteeType:=TRUSTEE_IS_UNKNOWN; PSID(ea.Trustee.ptstrName) := Sid; newdacl:=nil; i:=SetEntriesInAcl(1, @ea, dacl, newdacl); if i=ERROR_SUCCESS then begin i:=SetNamedSecurityInfo(pwidechar(path), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nil,nil, newdacl, nil); //if i<>error_success then // raise exception.create('SetNamedSecurityInfo failed: '+inttostr(i)); end; //else raise exception.create('SetEntriesInAcl failed: '+inttostr(i)); end;// else raise exception.create('GetNamedSecurityInfo failed: '+inttostr(i)); end; //else raise exception.create('AllocateAndInitializeSid failed'); end; {$ENDIF} end.
unit Theme; interface uses Registrator, BaseObjects, Classes, ComCtrls, Employee; type TTheme = class (TRegisteredIDObject) private FNumber: string; FFolder: string; FActualPeriodStart: TDateTime; FActualPeriodFinish: TDateTime; FPerformer: TEmployee; protected procedure AssignTo(Dest: TPersistent); override; public // номер темы property Number: string read FNumber write FNumber; // период актуальности темы property ActualPeriodStart: TDateTime read FActualPeriodStart write FActualPeriodStart; property ActualPeriodFinish: TDateTime read FActualPeriodFinish write FActualPeriodFinish; // ответсвтвенный исполнитель property Performer: TEmployee read FPerformer write FPerformer; // папка property Folder: string read FFolder write FFolder; constructor Create(ACollection: TIDObjects); override; end; TThemes = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TTheme; public procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override; property Items[Index: Integer]: TTheme read GetItems; constructor Create; override; end; implementation uses ThemePoster, Facade; { TTheme } procedure TTheme.AssignTo(Dest: TPersistent); var o: TTheme; begin inherited; o := Dest as TTheme; o.FNumber := Number; o.FFolder := Folder; o.FActualPeriodStart := ActualPeriodStart; o.FActualPeriodFinish := ActualPeriodFinish; o.FPerformer := Performer; end; constructor TTheme.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Тема документа'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TThemeDataPoster]; end; { TThemes } procedure TThemes.Assign(Sourse: TIDObjects; NeedClearing: boolean); begin inherited; end; constructor TThemes.Create; begin inherited; FObjectClass := TTheme; Poster := TMainFacade.GetInstance.DataPosterByClassType[TThemeDataPoster]; end; function TThemes.GetItems(Index: Integer): TTheme; begin Result := inherited Items[index] as TTheme; end; end.
unit ufrmBancos; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmDialogo, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, Data.DB, IBCustomDataSet, Vcl.Menus, System.Actions, Vcl.ActnList, IBTable, Vcl.ExtCtrls, Vcl.DBCtrls, JvDBControls, GridsEh, DBAxisGridsEh, DBGridEh, Vcl.ComCtrls, JvExComCtrls, JvComCtrls, FlatHeader, Vcl.StdCtrls, Vcl.Mask, FlatContainer, Vcl.ImgList; type TfrmBancos = class(TfrmDialogo) page1: TJvPageControl; tsCargos: TTabSheet; gridCargos: TDBGridEh; navCargos: TJvDBNavigator; tblBancos: TIBTable; dsBancos: TDataSource; actnlst1: TActionList; actExportarCSV: TAction; pm1: TPopupMenu; mnuExportarCSV: TMenuItem; tblBancosID: TLargeintField; tblBancosBANCO: TIBStringField; tblBancosDESCRIPCION: TIBStringField; tblBancosCUENTA_CORRIENTE: TIBStringField; tblBancosACTIVO: TIBStringField; actExportarHTML: TAction; mnuExportarHTML: TMenuItem; il1: TImageList; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actExportarCSVExecute(Sender: TObject); procedure tblBancosAfterPost(DataSet: TDataSet); procedure actExportarHTMLExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmBancos: TfrmBancos; implementation uses Datos, DanFW.Data.Export, DanFW.InterbaseDBExpress; {$R *.dfm} procedure TfrmBancos.actExportarCSVExecute(Sender: TObject); begin inherited; ExportarCSV(dsBancos.DataSet ); end; procedure TfrmBancos.actExportarHTMLExecute(Sender: TObject); begin inherited; exportarHTML(dsBancos.DataSet ); end; procedure TfrmBancos.FormClose(Sender: TObject; var Action: TCloseAction); begin cerrar(tblBancos); inherited; end; procedure TfrmBancos.FormCreate(Sender: TObject); begin inherited; Abrir(tblBancos ); end; procedure TfrmBancos.tblBancosAfterPost(DataSet: TDataSet); begin inherited; POSTING(tblBancos ); Actualizar(tblBancos ); end; end.
{ ****************************************************************************** } { * Status Library, writen by QQ 600585@qq.com * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zAnalysis * } { ****************************************************************************** } unit DoStatusIO; interface uses {$IF Defined(WIN32) or Defined(WIN64)} Windows, {$ELSEIF not Defined(Linux)} FMX.Types, {$ENDIF} Sysutils, Classes, PascalStrings, UPascalStrings, UnicodeMixedLib, CoreClasses, MemoryStream64; {$I zDefine.inc} type TDoStatusMethod = procedure(AText: SystemString; const ID: Integer) of object; TDoStatusCall = procedure(AText: SystemString; const ID: Integer); procedure DoStatus(Text: SystemString; const ID: Integer); overload; procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod); overload; procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusCall); overload; procedure DeleteDoStatusHook(TokenObj: TCoreClassObject); procedure DisableStatus; procedure EnabledStatus; procedure DoStatus(const v: Pointer; siz, width: NativeInt); overload; procedure DoStatus(prefix: SystemString; v: Pointer; siz, width: NativeInt); overload; procedure DoStatus(const v: TMemoryStream64); overload; procedure DoStatus(const v: TCoreClassStrings); overload; procedure DoStatus(const v: int64); overload; procedure DoStatus(const v: Integer); overload; procedure DoStatus(const v: Single); overload; procedure DoStatus(const v: Double); overload; procedure DoStatus(const v: Pointer); overload; procedure DoStatus(const v: SystemString; const Args: array of const); overload; procedure DoError(v: SystemString; const Args: array of const); overload; procedure DoStatus(const v: SystemString); overload; procedure DoStatus(const v: TPascalString); overload; procedure DoStatus(const v: TUPascalString); overload; procedure DoStatus(const v: TMD5); overload; procedure DoStatusNoLn(const v: TPascalString); overload; procedure DoStatusNoLn(const v: SystemString; const Args: array of const); overload; procedure DoStatusNoLn; overload; var LastDoStatus : SystemString; IDEOutput : Boolean; ConsoleOutput : Boolean; OnDoStatusHook: TDoStatusCall; implementation procedure bufHashToString(hash: Pointer; Size: NativeInt; var Output: TPascalString); const HexArr: array [0 .. 15] of SystemChar = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); var i: Integer; begin Output.Len := Size * 2; for i := 0 to Size - 1 do begin Output.buff[i * 2] := HexArr[(PByte(nativeUInt(hash) + i)^ shr 4) and $0F]; Output.buff[i * 2 + 1] := HexArr[PByte(nativeUInt(hash) + i)^ and $0F]; end; end; procedure DoStatus(const v: Pointer; siz, width: NativeInt); var s: TPascalString; i: Integer; n: SystemString; begin bufHashToString(v, siz, s); n := ''; for i := 1 to s.Len div 2 do begin if n <> '' then n := n + #32 + s[i * 2 - 1] + s[i * 2] else n := s[i * 2 - 1] + s[i * 2]; if i mod (width div 2) = 0 then begin DoStatus(n); n := ''; end; end; if n <> '' then DoStatus(n); end; procedure DoStatus(prefix: SystemString; v: Pointer; siz, width: NativeInt); var s: TPascalString; i: Integer; n: SystemString; begin bufHashToString(v, siz, s); n := ''; for i := 1 to s.Len div 2 do begin if n <> '' then n := n + #32 + s[i * 2 - 1] + s[i * 2] else n := s[i * 2 - 1] + s[i * 2]; if i mod (width div 2) = 0 then begin DoStatus(prefix + n); n := ''; end; end; if n <> '' then DoStatus(prefix + n); end; procedure DoStatus(const v: TMemoryStream64); var p: PByte; i: Integer; n: SystemString; begin p := v.Memory; for i := 0 to v.Size - 1 do begin if n <> '' then n := n + ',' + IntToStr(p^) else n := IntToStr(p^); inc(p); end; DoStatus(IntToHex(NativeInt(v), SizeOf(Pointer)) + ':' + n); end; procedure DoStatus(const v: TCoreClassStrings); var i: Integer; begin for i := 0 to v.Count - 1 do DoStatus(v[i]); end; procedure DoStatus(const v: int64); begin DoStatus(IntToStr(v)); end; procedure DoStatus(const v: Integer); begin DoStatus(IntToStr(v)); end; procedure DoStatus(const v: Single); begin DoStatus(FloatToStr(v)); end; procedure DoStatus(const v: Double); begin DoStatus(FloatToStr(v)); end; procedure DoStatus(const v: Pointer); begin DoStatus(Format('0x%p', [v])); end; procedure DoStatus(const v: SystemString; const Args: array of const); begin DoStatus(Format(v, Args)); end; procedure DoError(v: SystemString; const Args: array of const); begin DoStatus(Format(v, Args), 2); end; procedure DoStatus(const v: SystemString); begin DoStatus(v, 0); end; procedure DoStatus(const v: TPascalString); begin DoStatus(v.Text, 0); end; procedure DoStatus(const v: TUPascalString); begin DoStatus(v.Text, 0); end; procedure DoStatus(const v: TMD5); begin DoStatus(umlMD52String(v).Text); end; var LastDoStatusNoLn: TPascalString; procedure DoStatusNoLn(const v: TPascalString); var l, i: Integer; begin l := v.Len; i := 1; while i <= l do begin if CharIn(v[i], [#13, #10]) then begin if LastDoStatusNoLn.Len > 0 then begin DoStatus(LastDoStatusNoLn); LastDoStatusNoLn := ''; end; repeat inc(i); until (i > l) or (not CharIn(v[i], [#13, #10])); end else begin LastDoStatusNoLn.Append(v[i]); inc(i); end; end; end; procedure DoStatusNoLn(const v: SystemString; const Args: array of const); begin DoStatusNoLn(Format(v, Args)); end; procedure DoStatusNoLn; begin if LastDoStatusNoLn.Len > 0 then begin DoStatus(LastDoStatusNoLn); LastDoStatusNoLn := ''; end; end; type TDoStatusData = packed record TokenObj: TCoreClassObject; OnStatusNear: TDoStatusMethod; OnStatusFar: TDoStatusCall; end; PDoStatusData = ^TDoStatusData; TThreadSyncIntf = class public Text: SystemString; ID : Integer; th : TCoreClassThread; procedure DoSync; end; threadvar StatusActive: Boolean; var HookDoSatus: TCoreClassList = nil; procedure TThreadSyncIntf.DoSync; var i: Integer; p: PDoStatusData; begin try if (StatusActive) and (HookDoSatus.Count > 0) then begin LastDoStatus := Text; for i := HookDoSatus.Count - 1 downto 0 do begin p := HookDoSatus[i]; try if Assigned(p^.OnStatusNear) then p^.OnStatusNear(Text, ID) else if Assigned(p^.OnStatusFar) then p^.OnStatusFar(Text, ID); except end; end; end; {$IFNDEF FPC} if ((IDEOutput) or (ID = 2)) and (DebugHook <> 0) then begin {$IF Defined(WIN32) or Defined(WIN64)} OutputDebugString(PWideChar('"' + Text + '"')); {$ELSEIF not Defined(Linux)} FMX.Types.Log.d('"' + Text + '"'); {$ENDIF} end; {$ENDIF} if ((ConsoleOutput) or (ID = 2)) and (IsConsole) then Writeln(Text); finally end; end; procedure InternalDoStatus(Text: SystemString; const ID: Integer); var th: TCoreClassThread; ts: TThreadSyncIntf; i : Integer; p : PDoStatusData; begin th := TCoreClassThread.CurrentThread; if (th <> nil) and (th.ThreadID <> MainThreadID) then begin ts := TThreadSyncIntf.Create; ts.Text := Text; ts.ID := ID; ts.th := th; {$IFDEF FPC} TCoreClassThread.Synchronize(th, @ts.DoSync); {$ELSE} TCoreClassThread.Synchronize(th, ts.DoSync); {$ENDIF} DisposeObject(ts); exit; end; LockObject(HookDoSatus); try if (StatusActive) and (HookDoSatus.Count > 0) then begin LastDoStatus := Text; for i := HookDoSatus.Count - 1 downto 0 do begin p := HookDoSatus[i]; try if Assigned(p^.OnStatusNear) then p^.OnStatusNear(Text, ID) else if Assigned(p^.OnStatusFar) then p^.OnStatusFar(Text, ID); except end; end; end; {$IFNDEF FPC} if ((IDEOutput) or (ID = 2)) and (DebugHook <> 0) then begin {$IF Defined(WIN32) or Defined(WIN64)} OutputDebugString(PWideChar('"' + Text + '"')); {$ELSEIF not Defined(Linux)} FMX.Types.Log.d('"' + Text + '"'); {$ENDIF} end; {$ENDIF} if ((ConsoleOutput) or (ID = 2)) and (IsConsole) then Writeln(Text); finally UnLockObject(HookDoSatus); end; end; procedure DoStatus(Text: SystemString; const ID: Integer); begin OnDoStatusHook(Text, ID); end; procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusMethod); var _Data: PDoStatusData; begin new(_Data); _Data^.TokenObj := TokenObj; _Data^.OnStatusNear := CallProc; _Data^.OnStatusFar := nil; HookDoSatus.Add(_Data); end; procedure AddDoStatusHook(TokenObj: TCoreClassObject; CallProc: TDoStatusCall); var _Data: PDoStatusData; begin new(_Data); _Data^.TokenObj := TokenObj; _Data^.OnStatusNear := nil; _Data^.OnStatusFar := CallProc; HookDoSatus.Add(_Data); end; procedure DeleteDoStatusHook(TokenObj: TCoreClassObject); var i: Integer; p: PDoStatusData; begin i := 0; while i < HookDoSatus.Count do begin p := HookDoSatus[i]; if p^.TokenObj = TokenObj then begin Dispose(p); HookDoSatus.Delete(i); end else inc(i); end; end; procedure DisableStatus; begin StatusActive := False; end; procedure EnabledStatus; begin StatusActive := True; end; initialization HookDoSatus := TCoreClassList.Create; StatusActive := True; LastDoStatus := ''; IDEOutput := False; ConsoleOutput := True; {$IFDEF FPC} OnDoStatusHook := @InternalDoStatus; {$ELSE} OnDoStatusHook := InternalDoStatus; {$ENDIF} finalization while HookDoSatus.Count > 0 do begin Dispose(PDoStatusData(HookDoSatus[0])); HookDoSatus.Delete(0); end; DisposeObject(HookDoSatus); StatusActive := True; LastDoStatusNoLn := ''; end.
{$include kode.inc} unit kode_widget_timeline; { todo: - on_leave.. unselect hovertrack/segment } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_canvas, kode_color, //kode_const, kode_flags, kode_rect, kode_timeline, kode_widget; type KWidget_Timeline = class(KWidget) private FZoom : Single; FStartPos : Single; FPrevMouseX : LongInt; FPrevMouseY : LongInt; private FHoverTrack : KTimeline_Track; FHoverSegment : KTimeline_Segment; FHoverTime : Single; FHoverLeft : Boolean; FHoverRight : Boolean; private FDraggingSegment : KTimeline_Segment; FDraggingLeft : Boolean; FDraggingRight : Boolean; protected FTimeline : KTimeline; FBackColor : KColor; FTrackBackColor : KColor; FTrackTextColor : KColor; FSegmentBackColor : KColor; FSegmentTextColor : KColor; FBorderColor : KColor; FTextColor : KColor; public property zoom : Single read FZoom write FZoom; property startpos : Single read FStartPos write FStartPos; public constructor create(ARect:KRect; ATimeline:KTimeline; AAlignment:LongWord=kwa_none); //destructor destroy; override; function calcLength(APixels:LongInt) : Single; function calcPixels(ATime:LongInt) : LongInt; function calcTime(AXpos:LongInt) : Single; function calcTimeDiff(AXpos,APrev:LongInt) : Single; function calcXpos(ATime:Single) : LongINt; function findTrack(AYpos:LongInt) : KTimeline_Track; function findSegment(ATrack:KTimeline_Track; ATime:Single) : KTimeline_Segment; public procedure on_mouseDown(AXpos,AYpos,AButton,AState:LongInt); override; procedure on_mouseUp(AXpos,AYpos,AButton,AState:LongInt); override; procedure on_mouseMove(AXpos,AYpos,AState:LongInt); override; procedure on_leave(AWidget:KWidget); override; procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses {%H-}kode_const, {%H-}kode_debug, kode_list, kode_math; const TRACK_HEIGHT = 20; TRACK_WIDTH = 100; PIXELS_PER_SECOND = 10; SECONDS_PER_PIXEL = (1/PIXELS_PER_SECOND); DRAG_HANDLE_SIZE = 5; //---------- constructor KWidget_Timeline.create(ARect:KRect; ATimeline:KTimeline; AAlignment:LongWord); begin inherited create(ARect,AAlignment); FTimeline := ATimeline; FName := 'KWidget_Timeline'; FStartPos := 0; FBackColor := KGrey; FTrackBackColor := KDarkGrey; FTrackTextColor := KLightGrey; FSegmentBackColor := KLightGrey; FSegmentTextColor := KDarkGrey; FBorderColor := KBlack; FZoom := 1; FStartPos := 0; FPrevMouseX := 0; FPrevMouseY := 0; {} FHoverTrack := nil; FHoverSegment := nil; FHoverTime := -1; FHoverLeft := false; FHoverRight := false; {} FDraggingSegment := nil; FDraggingLeft := false; FDraggingRight := false; end; //---------- function KWidget_Timeline.calcLength(APixels:LongInt) : Single; var time : single; begin time := single( APixels * SECONDS_PER_PIXEL ); result := time / FZoom; end; //---------- function KWidget_Timeline.calcPixels(ATime:LongInt) : LongInt; var pixel : single; begin pixel := ATime * PIXELS_PER_SECOND; result := trunc( pixel*FZoom ); end; //---------- function KWidget_Timeline.calcTime(AXpos:LongInt) : Single; var time : single; begin if FZoom <= 0 then exit(-1); time := single( AXpos - TRACK_WIDTH ); if time < 0 then exit(-1); time *= SECONDS_PER_PIXEL; result := (FStartPos + time) / FZoom; end; //---------- function KWidget_Timeline.calcTimeDiff(AXpos,APrev:LongInt) : Single; var diff : single; begin if FZoom <= 0 then exit(0); diff := single( AXpos - APrev ); //if time < 0 then exit(0); diff *= SECONDS_PER_PIXEL; result := diff / FZoom; end; //---------- function KWidget_Timeline.calcXpos(ATime:Single) : LongInt; var pixel : Single; begin if ATime >= 0 then begin pixel := ((ATime*FZoom) * PIXELS_PER_SECOND); result := TRACK_WIDTH + trunc(pixel); end else result := -1; end; //---------- function KWidget_Timeline.findTrack(AYpos:LongInt) : KTimeline_Track; var y,t : longint; node : KListNode; begin y := AYpos - FRect.y; if y < 0 then exit(nil); t := y div TRACK_HEIGHT; result := nil; node := FTimeline.tracks.head; while Assigned(node) do begin if t = 0 then exit(node as KTimeline_Track); t -= 1; node := node.next; end; end; //---------- function KWidget_Timeline.findSegment(ATrack:KTimeline_Track; ATime:Single) : KTimeline_Segment; var node : KListNode; segment : KTimeline_Segment; begin result := nil; node := ATrack.segments.head; while Assigned(node) do begin segment := node as KTimeline_Segment; if (ATime >= segment.startpos) and (ATime <= segment.endpos) then exit(segment); node := node.next; end; end; //---------------------------------------------------------------------- // on_ //---------------------------------------------------------------------- procedure KWidget_Timeline.on_mouseDown(AXpos,AYpos,AButton,AState:LongInt); var changed : boolean; begin changed := false; if AButton = kmb_left then begin FPrevMouseX := AXpos; FPrevMouseY := AYpos; if not Assigned(FHoverSegment) then exit; FDraggingSegment := FHoverSegment; FDraggingLeft := FHoverLeft; FDraggingRight := FHoverRight; end; if changed then do_redraw(self,FRect); inherited; end; //---------- procedure KWidget_Timeline.on_mouseUp(AXpos,AYpos,AButton,AState:LongInt); var changed : boolean; begin changed := false; if AButton = kmb_left then begin //if not Assigned(FDraggingSegment) then exit; FDraggingSegment := nil; FDraggingLeft := false; FDraggingRight := false; end; if changed then do_redraw(self,FRect); inherited; end; //---------- procedure KWidget_Timeline.on_mouseMove(AXpos,AYpos,AState:LongInt); var track : KTimeline_Track; segment : KTimeline_Segment; prv,nxt : KTimeline_Segment; changed : boolean; leftx,rightx:longint; hoverleft,hoverright : boolean; diff : single; st,en,le,temp : single; mintime : single; begin changed := false; track := findTrack(AYpos); segment := nil; FHoverTime := calcTime(AXpos); if Assigned(FDraggingSegment) then begin mintime := calcLength(10); // minimum 10 pixels diff := calcTimeDiff(AXpos,FPrevMouseX); st := FDraggingSegment.startpos; en := FDraggingSegment.endpos; { dragging left } if FDraggingLeft then begin st += diff; st := KMax(st,0); if st > (en-mintime) then st := (en-mintime); end else { dragging right } if FDraggingRight then begin en += diff; if en < (st+mintime) then en := (st+mintime); end else { dragging segment } begin le := en - st; st += diff; st := KMax(st,0); en := st + le; end; prv := FDraggingSegment.prev as KTimeline_Segment; if Assigned(prv) then begin if st <= prv.endpos then begin le := en - st; st := prv.endpos {+ 0.0001}; if not FDraggingLeft then en := st + le; end; end; nxt := FDraggingSegment.next as KTimeline_Segment; if Assigned(nxt) then begin if en >= nxt.startpos then begin le := en - st; en := nxt.startpos {- 0.0001}; if not FDraggingRight then st := en - le; end; end; FDraggingSegment.startpos := st; FDraggingSegment.endpos := en; changed := true; end // dragging else begin // not dragging if Assigned(track) then begin segment := findSegment(track,FHoverTime); if Assigned(segment) then begin leftx := calcXpos(segment.startpos); rightx := calcXpos(segment.endpos); if AXpos < (leftx+DRAG_HANDLE_SIZE) then hoverleft := true else hoverleft := false; if AXpos >= (rightx-DRAG_HANDLE_SIZE) then hoverright := true else hoverright := false; end; end; if track <> FHoverTrack then begin FHoverTrack := track; changed := true; end; if segment <> FHoverSegment then begin FHoverSegment := segment; changed := true; end; if hoverleft <> FHoverLeft then begin FHoverLeft := hoverleft; changed := true; end; if hoverright <> FHoverRight then begin FHoverRight := hoverright; changed := true; end; end; // not dragging if changed then do_redraw(self,FRect); FPrevMouseX := AXpos; FPrevMouseY := AYpos; inherited; end; //---------- procedure KWidget_Timeline.on_leave(AWidget:KWidget); var changed : boolean; begin changed := false; if Assigned(FHoverTrack) then begin FHoverTrack := nil; changed := true; end; if Assigned(FHoverSegment) then begin FHoverSegment := nil; changed := true; end; if changed then do_redraw(self,FRect); inherited; end; //---------- procedure KWidget_Timeline.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); var tnode : KListNode; snode : KListNode; track : KTimeline_Track; segment : KTimeline_Segment; x1,y1 : longint; x2,y2 : longint; ss,se : single; cur : single; begin ACanvas.setFillColor(FBackColor); ACanvas.fillRect(FRect.x,FRect.y,FRect.x2,FRect.y2); ACanvas.setDrawColor(FBorderColor); ACanvas.drawLine(FRect.x,FRect.y,FRect.x2,FRect.y); x1 := FRect.x; //x2 := FRect.x2; y1 := FRect.y; tnode := FTimeline.tracks.head; while Assigned(tnode) do begin track := tnode as KTimeline_Track; x2 := x1 + TRACK_WIDTH - 1; y2 := y1 + TRACK_HEIGHT - 1; { track background } if track = FHoverTrack then ACanvas.setFillColor( color(0.3,0.3,0.3) ) else ACanvas.setFillColor(FTrackBackColor); ACanvas.fillRect(x1,y1,x2,y2); { track name } ACanvas.setTextColor(FTrackTextColor); ACanvas.drawText(x1+2,y1,x2-2,y2,track.name, kta_center); { track border } ACanvas.setDrawColor(FBorderColor); // below ACanvas.drawLine(x1,y2,FRect.x2,y2); // below ACanvas.drawLine(x2,y1,x2,y2); // right { track segments } snode := track.segments.head; while Assigned(snode) do begin segment := snode as KTimeline_Segment; ss := segment.startpos * FZoom * PIXELS_PER_SECOND; se := segment.endpos * FZoom * PIXELS_PER_SECOND; { back } if segment = FHoverSegment then ACanvas.setFillColor( color(0.7,0.7,0.7) ) else ACanvas.setFillColor(FSegmentBackColor); ACanvas.fillRect(x2+1+trunc(ss),y1,x2+1+trunc(se),y2-1); { name } ACanvas.setTextColor(FSegmentTextColor); ACanvas.drawText(x2+1+trunc(ss),y1,x2+1+trunc(se),y2,segment.name,kta_center); { border } ACanvas.setDrawColor(FBorderColor); //ACanvas.drawRect(x2+1+trunc(ss),y1,x2+1+trunc(se),y2); ACanvas.drawLine(x2+1+trunc(ss),y1,x2+1+trunc(ss),y2); ACanvas.drawLine(x2+1+trunc(se),y1,x2+1+trunc(se),y2); { resize indicators } if (segment = FHoverSegment) then begin ACanvas.setFillColor( KDarkGrey ); if FHoverLeft then ACanvas.fillRect(x2+1+trunc(ss),y1,x2+1+trunc(ss)+(DRAG_HANDLE_SIZE-1),y2); if FHoverRight then ACanvas.fillRect(x2+1+trunc(se)-(DRAG_HANDLE_SIZE-1),y1,x2+1+trunc(se),y2); end; snode := snode.next; end; y1 += TRACK_HEIGHT; tnode := tnode.next; end; cur := FTimeline.cursor * FZoom * PIXELS_PER_SECOND; ACanvas.setDrawColor( KLightRed ); ACanvas.drawLine( FRect.x + trunc(cur), FRect.y, FRect.x + trunc(cur), FRect.y2 ); inherited; end; //---------------------------------------------------------------------- end.
unit Utils.Time; interface uses WinApi.Windows; function GetDateFromDaylightRule(const AYear: Word; st: TSystemTime): TDateTime; implementation uses System.SysUtils, System.DateUtils; function GetDateFromDaylightRule(const AYear: Word; st: TSystemTime): TDateTime; const CReDoW: array [0 .. 6] of Integer = (7, 1, 2, 3, 4, 5, 6); var LExpDayOfWeek, LActualDayOfWeek: Word; AMonth, ADoW, ADoWIndex: Word; AToD: TTime; begin AMonth := st.wMonth; ADoW := st.wDayOfWeek; ADoWIndex := st.wDay; AToD := EncodeTime(st.wHour,st.wMinute,st.wSecond,0); { No actual rule } if (AMonth = 0) and (ADoW = 0) and (ADoWIndex = 0) then Exit(0); { Transform into ISO 8601 day of week } LExpDayOfWeek := CReDoW[ADoW]; { Generate a date in the form of: Year/Month/1st of month } Result := EncodeDate(AYear, AMonth, 1); { Get the day of week for this newly crafted date } LActualDayOfWeek := DayOfTheWeek(Result); { We're too far off now, let's decrease the number of days till we get to the desired one } if LActualDayOfWeek > LExpDayOfWeek then Result := IncDay(Result, DaysPerWeek - LActualDayOfWeek + LExpDayOfWeek) else if (LActualDayOfWeek < LExpDayOfWeek) Then Result := IncDay(Result, LExpDayOfWeek - LActualDayOfWeek); { Skip the required number of weeks } Result := IncDay(Result, DaysPerWeek * (ADoWIndex - 1)); { If we've skipped the day in this moth, go back a few weeks until we get it right again } while (MonthOf(Result) > AMonth) do Result := IncDay(Result, -DaysPerWeek); { Add the time part } Result := Result + AToD; end; end.
unit QueryProgress; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ActnList, Ora, BCDialogs.Dlg, System.Actions; const WM_AFTER_SHOW = WM_USER + 301; // custom message type TQueryProgressDialog = class(TDialog) ActionList: TActionList; CancelAction: TAction; CancelButton: TButton; ExecutionTimeLabel: TLabel; procedure CancelActionExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure Formshow(Sender: TObject); private { Private declarations } FOnProgress: Boolean; FOraQuery: TOraQuery; FStartTime: TDateTime; procedure SetExecutionTimeText(Value: string); procedure WMAfterShow(var Msg: TMessage); message WM_AFTER_SHOW; public { Public declarations } function Open(OraQuery: TOraQuery; StartTime: TDateTime): Boolean; property ExecutionTimeText: string write SetExecutionTimeText; property OnProgress: Boolean read FOnProgress; end; function QueryProgressDialog: TQueryProgressDialog; implementation {$R *.dfm} uses BCCommon.StyleUtils; var FQueryProgressDialog: TQueryProgressDialog; function QueryProgressDialog: TQueryProgressDialog; begin if not Assigned(FQueryProgressDialog) then Application.CreateForm(TQueryProgressDialog, FQueryProgressDialog); Result := FQueryProgressDialog; SetStyledFormSize(Result); end; procedure TQueryProgressDialog.CancelActionExecute(Sender: TObject); begin FOnProgress := False; ExecutionTimeLabel.Caption := 'Canceling...'; Application.ProcessMessages; end; procedure TQueryProgressDialog.WMAfterShow(var Msg: TMessage); var Success, UserCancel: Boolean; //Secs, Min: Integer; begin Success := False; UserCancel := False; if Assigned(FOraQuery) then begin while FOraQuery.Executing do begin {Min := StrToInt(FormatDateTime('n', Now - FStartTime)); Secs := Min * 60 + StrToInt(FormatDateTime('s', Now - FStartTime)); if Secs < 1 then ExecutionTimeText := FormatDateTime('"Execution time:" s.zzz "s."', Now - FStartTime) else if Secs < 60 then ExecutionTimeText := FormatDateTime('"Execution time:" s "s."', Now - FStartTime) else ExecutionTimeText := FormatDateTime('"Execution time:" n "min" s "s."', Now - FStartTime); } ExecutionTimeText := Format('Time Elapsed: %s', [System.SysUtils.FormatDateTime('hh:nn:ss.zzz', Now - FStartTime)]); if not OnProgress then begin UserCancel := True; Break; end; Application.ProcessMessages; end; Success := FOraQuery.Active; end; if Success and (not UserCancel) then ModalResult := mrOk else ModalResult := mrCancel; end; procedure TQueryProgressDialog.FormClose(Sender: TObject; var Action: TCloseAction); begin FOnProgress := False; Action := caFree; end; procedure TQueryProgressDialog.FormDestroy(Sender: TObject); begin FQueryProgressDialog := nil; end; procedure TQueryProgressDialog.Formshow(Sender: TObject); begin // Post the custom message WM_AFTER_SHOW to our form PostMessage(Self.Handle, WM_AFTER_SHOW, 0, 0); end; function TQueryProgressDialog.Open(OraQuery: TOraQuery; StartTime: TDateTime): Boolean; var Rslt: Integer; begin FOnProgress := True; ExecutionTimeText := ''; FOraQuery := OraQuery; FStartTime := StartTime; Rslt := ShowModal; Result := Rslt = mrOK; end; procedure TQueryProgressDialog.SetExecutionTimeText(Value: string); begin if FOnProgress then ExecutionTimeLabel.Caption := Value; end; end.
{u_main.pas - FASTA 36 Scan Copyright (C) 2018-2021 Olivier Friard (olivier.friard@unito.it) This file is part of FASTA 36 Scan software } unit u_main; {$MODE Delphi} interface uses inifiles,strutils, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, ComCtrls, ExtCtrls; type { TfrmMain } TfrmMain = class(TForm) MainMenu1: TMainMenu; mi_save_sequences_descriptions: TMenuItem; Sequences1: TMenuItem; LoadFASTAresults1: TMenuItem; N3: TMenuItem; mi_Saveselectedsequences: TMenuItem; N2: TMenuItem; Quit1: TMenuItem; Selection1: TMenuItem; SUS1: TMenuItem; Font1: TMenuItem; Help1: TMenuItem; Info1: TMenuItem; N4: TMenuItem; Contents1: TMenuItem; About1: TMenuItem; lv: TListView; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; lv_popupmenu: TPopupMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; sb: TStatusBar; N5: TMenuItem; Selectallsequences1: TMenuItem; Unselectallsequences1: TMenuItem; Invertselection1: TMenuItem; mi_SaveselectedsequencesinFASTACONVformat: TMenuItem; procedure About1Click(Sender: TObject); procedure Load(Sender: TObject); procedure mi_save_sequences_descriptionsClick(Sender: TObject); procedure Quit1Click(Sender: TObject); procedure mi_SaveselectedsequencesClick(Sender: TObject); procedure SUS1Click(Sender: TObject); procedure Info1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure MenuItem1Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure lvClick(Sender: TObject); procedure Selectallsequences1Click(Sender: TObject); procedure Unselectallsequences1Click(Sender: TObject); procedure Invertselection1Click(Sender: TObject); procedure mi_SaveselectedsequencesinFASTACONVformatClick( Sender: TObject); private { Private declarations } public { Public declarations } end; const maxseq = 1000000; version_number = '1.8'; version_date = '2021-10-01'; program_name = 'FASTA 36 Scan'; var frmMain: TfrmMain; nom_input,nq, query_id:string; f, f2, f3: Tstringlist; seq_list, query_seq_list: Tstringlist; fastatype, nseq, ls:integer; versionAlg:shortstring; posit:array[1..maxseq] of ^integer; itm:tlistitem; IniFile:TIniFile; flagparam:boolean; procedure count_checked_sequences; implementation uses u_about, u_warning, u_select, u_options; {$R *.lfm} function rev(s:string):string; var i:integer; s3:string; begin s3:=''; for i:=length(s) downto 1 do case s[i] of '-': s3 := s3 + '-'; ' ':s3 := s3 + ' '; 'A':s3 := s3 + 'T'; 'C':s3 := s3+'G'; 'G':s3 := s3+'C'; 'T':s3 := s3+'A'; 'M':s3 := s3+'K'; 'R':s3 := s3+'Y'; 'S':s3 := s3+'S'; 'V':s3 := s3+'B'; 'W':s3 := s3+'W'; 'Y':s3 := s3+'R'; 'H':s3 := s3+'D'; 'K':s3 := s3+'M'; 'D':s3 := s3+'H'; 'B':s3 := s3+'V'; 'N':s3 := s3+'N'; end; result:=s3; end; //rev procedure count_checked_sequences; //count number of checked sequences var w:integer; compt:integer; begin compt:=0; with frmMain do begin for w:=0 to lv.items.count-1 do if lv.items[w].checked then inc(compt); sb.Panels[1].Text:='Selected: '+inttostr(compt); end; end; //count number of checked sequences procedure TfrmMain.About1Click(Sender: TObject); //show About window begin frmabout.lb_version.caption := 'version ' + version_number; // frmabout.lb_exefilename.caption := extractfilename(application.exename); frmabout.showmodal; end; procedure TfrmMain.Load(Sender: TObject); //load file var s, s1, s2, mem_ac: string; align, init1, initn, opt, zscore, e, ac, id, de: shortstring; w,erreur:integer; flagHTML:boolean; procedure loadFASTA; //load FASTA output var w, n1, eliminate_repeated_ac: integer; homol_percent, short_query_id: shortstring; hp: Double; flag_seq, flag_revcomp: boolean; seq, query_seq, test: string; begin //check for FASTA file fastatype := 2; //extraction of FASTA version number versionAlg:=''; for w := 0 to f.count-1 do if pos('; pg_ver:', f[w]) <> 0 then begin versionAlg := copy(f[w], pos('; pg_ver:', f[w]) + 10, 255); break; end; // find query length for w := 0 to f.count-1 do if pos('; sq_len:', f[w]) <> 0 then begin s2 := copy(f[w], pos('; sq_len:', f[w]) + 10, 255); break; end; // query id for w := 0 to f.count-1 do if (pos('>>>', f[w]) = 1) and (pos(' vs ', f[w]) <> 0) then begin query_id := f[w]; query_id := stringreplace(query_id, '>>>', '', []); query_id := copy(query_id, 1, pos(', ', query_id) - 1); // first 12 char short_query_id := copy(query_id, 1, 12); end; for w := 0 to f.count-1 do if pos('; sq_len:', f[w]) <> 0 then begin s2 := copy(f[w], pos('; sq_len:', f[w]) + 10, 255); break; end; if s2 = '' then //unknown query length repeat s2 := inputbox('Query length','Input the query length',''); val(s2, ls, erreur); if (erreur <> 0) or (ls = 0) then showmessage('Input a numeric positive value!'); until ls <> 0; ls := strtoint(s2); if w = f.count-1 then begin Screen.Cursor:=crDefault; showmessage('First alignment not found!'+#10+'Check the FASTA output.'); exit; end; //sequences index creation nseq:=0; w := 0; while w <= f.count-1 do begin if (copy(f[w], 1, 2) = '>>') and (copy(f[w], 1, 3) <> '>>>') then begin inc(nseq); new(posit[nseq]); posit[nseq]^ := w; end; inc(w); end; new(posit[nseq + 1]); posit[nseq + 1]^ := f.count; //load sequences lv.items.clear; seq_list := TstringList.Create; query_seq_list := TstringList.Create; mem_ac := ''; eliminate_repeated_ac := -1; for n1 := 1 to nseq do begin test:= f[posit[n1]^]; s := f[posit[n1]^]; // '>>' //read first word from ID sequence //remove '>>' s := copy(s, 3, 255); //extract ACCESSION first word ac := copy(s, 1, pos(' ', s) - 1); // check if output from FASTA between a FASTA DB if ac = '' then begin if pos(';', s) <> 0 then begin ac := copy(s, 1, pos(';', s) - 1); end else begin ac := s; end; end; //remove ID delete(s, 1, length(ac)); //remove ; if present ac := stringreplace(ac, ';', '', []); if pos(ac, mem_ac) <> 0 then begin if eliminate_repeated_ac = -1 then begin eliminate_repeated_ac := MessageDlg('Eliminate the repeated accession codes?', mtCustom, [mbYes, mbNo], 0); end; if eliminate_repeated_ac = mrYes then continue; end; itm := lv.items.add; itm.caption := inttostr(n1); //seq number mem_ac := mem_ac + '*' + ac + '*'; //remove blank s := trim(s); de := s; itm.subitems.add(ac); //extract DEFINITION itm.subitems.add(de); // extract query seq w := 1; flag_seq := false; query_seq := ''; flag_revcomp := false; repeat //showmessage(f[posit[n1]^ + w]); // check sense of query if pos('; fa_frame: r', f[posit[n1]^ + w]) <> 0 then flag_revcomp := true; if pos('>' + short_query_id, f[posit[n1]^ + w]) = 1 then begin flag_seq := true; inc(w); end; if flag_seq and (pos(';', f[posit[n1]^ + w]) = 0) then begin query_seq := query_seq + f[posit[n1]^ + w] end; inc(w); if (pos('>', f[posit[n1]^ + w]) <> 0) and (pos('>' + short_query_id, f[posit[n1]^ + w]) = 0) then break; until (f[posit[n1]^ + w -1] = '>>><<<'); (* if flag_revcomp then query_seq_list.Add(rev(query_seq)) end else query_seq_list.Add(query_seq); *) // extract sequence w := 1; flag_seq := false; seq := ''; flag_revcomp := false; repeat test := f[posit[n1]^ + w]; if pos('; bs_ident: ', f[posit[n1]^ + w]) <> 0 then begin homol_percent := stringreplace(f[posit[n1]^ + w], '; bs_ident: ', '', []); hp := StrToFloat(homol_percent) * 100 ; itm.subitems.add(FloatToStr(hp)); end; if pos('; bs_overlap: ', f[posit[n1]^ + w]) <> 0 then begin itm.subitems.add(stringreplace(f[posit[n1]^ + w], '; bs_overlap: ', '', [])); end; if pos('; fa_frame: r', f[posit[n1]^ + w]) <> 0 then begin flag_revcomp := true; end; if pos('>' + ac, f[posit[n1]^ + w]) = 1 then begin flag_seq := true; inc(w); end; if flag_seq and (pos(';', f[posit[n1]^ + w]) <> 1) then begin seq := seq + f[posit[n1]^ + w]; end; inc(w); until (f[posit[n1]^ + w -1] = '>>><<<') or (pos('; al_cons:', f[posit[n1]^ + w -1 ]) <> 0); // remove gap from sequence (* while pos('-', seq)<>0 do delete(seq, pos('-', seq), 1); *) if flag_revcomp then begin // align length of query on length of aligned seq while length(query_seq) < length(seq) do query_seq := query_seq + '-'; query_seq_list.Add(rev(query_seq)); seq_list.Add(rev(seq)); end else begin query_seq_list.Add(query_seq); seq_list.Add(seq); end; if (f[posit[n1]^ + w -1] = '>>><<<') then break; end; // seq_list.savetofile('/tmp/test1.seq') end; //loadFASTA //========================================================================== begin //tfrmMain.load opendialog1.title:='Open FASTA output'; opendialog1.filter:='FASTA output (*.fas; *.fasta)|*.fas;*.fasta|Text file (*.txt)|*.txt|All files (*)|*'; if not flagparam then begin if opendialog1.execute then nom_input := opendialog1.filename else exit; end; flagparam := false; if nom_input = '' then exit; nseq:=0; Screen.Cursor := crHourglass; lv.items.BeginUpdate; //load file in memory f.loadfromfile(nom_input); f.text := AdjustLineBreaks(f.text); align := ''; for w := 0 to f.count-1 do begin if (pos('(Nucleotide) FASTA',f[w])<>0) or (pos('(Peptide) FASTA',f[w])<>0) or (pos('FASTA searches a protein or DNA sequence data bank',f[w])<>0) then begin align:='FASTA'; break; end; end; if align='FASTA' then loadFASTA; lv.Items.EndUpdate; Screen.Cursor:=crDefault; sb.panels[0].text:='Sequences number: '+inttostr(nseq); sb.panels[1].text:='Selected: 0'; caption:='FASTA Scan - version '+version_number+' ('+version_date+') - '+nom_input; mi_SaveSelectedSequences.enabled:=true; mi_SaveselectedsequencesinFASTACONVformat.enabled:=true; mi_save_sequences_descriptions.enabled := true; selection1.enabled:=true; end;//load file procedure TfrmMain.mi_save_sequences_descriptionsClick(Sender: TObject); // save sequences descriptions var w: integer; n1: word; seq_ac, descr_str: shortstring; flagadd: boolean; ft: textfile; begin //search for selected sequences for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin n1 := 1; break; end; if n1 = 0 then begin showmessage('No selected sequences!'); exit; end; f2 := Tstringlist.create; for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin seq_ac := lv.items[w].subitems.strings[0]; descr_str := lv.items[w].subitems.strings[1]; //DE f2.add(seq_ac + ' ' + descr_str); end; savedialog1.filename := changefileext(nom_input, '.txt'); if savedialog1.execute then begin flagadd := false; if fileexists(savedialog1.filename) then begin frmWarning.showmodal; if frmWarning.modalresult=mrcancel then exit; if frmWarning.modalresult=mrno then flagadd:=true else flagadd:=false; end; if not flagadd then f2.savetofile(savedialog1.filename) //overwrite f file already exists else begin assignfile(ft,savedialog1.filename); //add if file already exists append(ft); for n1 := 0 to f2.count-1 do writeln(ft,f2[n1]); closefile(ft); end; end; f2.free; end; procedure end_program; //ask user confirmation and close program var n1:word; begin if MessageDlg('Close FASTA Scan?',mtConfirmation,[mbYes,mbNo],0)=mrNo then exit; f.free; if (fastatype<>0) then for n1:=1 to nseq+1 do dispose(posit[n1]); IniFile:=TIniFile.create(extractFilePath(application.exename)+'FASTA_Scan.ini'); for n1:=0 to frmMain.lv.columns.count-1 do inifile.writeinteger('FASTA_Scan','col'+inttostr(n1),frmMain.lv.columns[n1].Width); inifile.free; application.terminate; end; //end_program procedure TfrmMain.Quit1Click(Sender: TObject); begin end_program; end; function checknumb(s:string):boolean; //check for number var t:byte; flag:boolean; begin flag:=true; for t:=1 to length(s) do if s[t] in ['a'..'z','A'..'Z','%','-','(',')'] then begin flag:=false; break; end; checknumb:=flag; end; //checknumb procedure TfrmMain.mi_SaveselectedsequencesClick(Sender: TObject); var flagseqloc, flagtotrev, flagname, flaggap, flagrev: boolean; deb,n1: word; w,w1,w2: integer; ss, nomseq, rev_str, seq_ac, descr_str: shortstring; mem, s, s2, s3, memseq: string; ft: textfile; flagadd, flagfirstgi, flag_incl_gi: boolean; label label1; begin //search for selected sequences for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin n1:=1; break; end; if n1 = 0 then begin showmessage('No selected sequences!'); exit; end; frmOptions.showmodal; if frmOptions.modalresult = mrCancel then exit; f2 := Tstringlist.create; for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin seq_ac := lv.items[w].subitems.strings[0]; if frmOptions.cbIncludeDescription.Checked then descr_str := lv.items[w].subitems.strings[1] //DE else descr_str := ''; if (frmOptions.cbSaveUniqueSequence.Checked) then begin if pos(seq_list[w], memseq) = 0 then begin //sequence name f2.add('>' + seq_ac + ' ' + descr_str); //nucleotide sequence f2.add(seq_list[w]); memseq := memseq + '*' + seq_list[w] + '*'; end; end else begin // sequence name f2.add('>' + seq_ac + ' ' + descr_str); //nucleotide sequence f2.add(seq_list[w]); end; //writeln(seq_list[w]) end; Screen.Cursor := crDefault; savedialog1.filename := changefileext(nom_input, '.fst'); if savedialog1.execute then begin flagadd:=false; if fileexists(savedialog1.filename) then begin frmWarning.showmodal; if frmWarning.modalresult=mrcancel then exit; if frmWarning.modalresult=mrno then flagadd:=true else flagadd:=false; end; if not flagadd then f2.savetofile(savedialog1.filename) //overwrite f file already exists else begin assignfile(ft,savedialog1.filename); //add if file already exists append(ft); for n1:=0 to f2.count-1 do writeln(ft,f2[n1]); closefile(ft); end; end; mem := ''; f2.free; end; //save selected seq. procedure TfrmMain.SUS1Click(Sender: TObject); begin frmSelect.Top:=0; frmSelect.left:=0; frmSelect.show; end; procedure TfrmMain.Info1Click(Sender: TObject); begin if (fastatype=0) then showmessage('No alignment!') else showmessage(copy('FASTA Output from GCG Package',1,255*byte(fastatype=1))+ copy('FASTA Output from Pearson Package',1,255*byte(fastatype=2))+ versionAlg+#10+ 'File name: ' + nom_input + #10+ 'Query name: '+nq+#10+ 'Query length: '+inttostr(ls)+#10+ 'Number of sequences: '+inttostr(nseq)); end; procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caNone; end_program; end; procedure TfrmMain.FormCreate(Sender: TObject); var i:integer; begin IniFile:=Tinifile.create(extractFilePath(application.exename) + 'FASTA_Scan.ini'); for i:=0 to lv.Columns.count-1 do lv.Columns[i].Width := inifile.readinteger('FASTA_Scan','col'+inttostr(i),100); inifile.free; decimalseparator := '.'; mi_saveselectedsequences.enabled := false; mi_SaveselectedsequencesinFASTACONVformat.enabled := false; mi_save_sequences_descriptions.enabled := false; flagparam := false; f := Tstringlist.create; caption:='FASTA 36 Scan - version ' + version_number + ' (' + version_date+')'; end; procedure TfrmMain.MenuItem1Click(Sender: TObject); var w:integer; begin if lv.Items.count > 0 then for w:=0 to lv.items.count-1 do if lv.Items[w].selected then lv.Items[w].Checked := true; end; procedure TfrmMain.MenuItem2Click(Sender: TObject); var w:integer; begin if lv.Items.count > 0 then for w:=0 to lv.items.count-1 do if lv.Items[w].selected then lv.Items[w].Checked:=false; end; procedure TfrmMain.FormShow(Sender: TObject); begin if paramcount <> 0 then begin flagparam := true; nom_input := paramstr(1); Load(self); end; end; procedure TfrmMain.lvClick(Sender: TObject); begin count_checked_sequences; end; procedure TfrmMain.Selectallsequences1Click(Sender: TObject); var w:integer; begin //select all if MessageDlg('Select all sequences?',mtConfirmation,[mbYes, mbNo],0)=mrYes then if lv.items.count>0 then for w:=0 to lv.items.count-1 do lv.items[w].checked:=true; sb.panels[1].text:='Selected: '+inttostr(nseq); end; procedure TfrmMain.Unselectallsequences1Click(Sender: TObject); var w:integer; begin //deselect all if MessageDlg('Deselect all sequences?',mtConfirmation,[mbYes, mbNo],0)=mrYes then if lv.items.count>0 then for w:=0 to lv.items.count-1 do lv.items[w].checked:=false; sb.panels[1].text:='Selected: 0'; end; procedure TfrmMain.Invertselection1Click(Sender: TObject); var w:integer; begin if lv.items.count>0 then for w:=0 to lv.items.count-1 do if lv.items[w].checked then lv.items[w].checked:=false else lv.items[w].checked:=true; count_checked_sequences; end; procedure Lalign(var s:string; b:byte); begin s := s + dupestring(' ', b - length(s)); end; procedure TfrmMain.mi_SaveselectedsequencesinFASTACONVformatClick( Sender: TObject); (* save sequence in query anchored format *) const validbase='ACGTUYRWSKMBDHVN-'; tabseq=104; var flagseqloc, flagtotrev, flagname, flaggap: boolean; deb, n1: word; s0, nomseq, nomquery, mem: string; s4,s5,q,seqquery, mem2, s,s2, new_seq, seq_ac, seq_def: string; ft: textfile; flagadd, flagfirstgi, flag_incl_gi, flagL, flagrev, flag_already_added, flag_query_added: boolean; w, w1, w2, w3, flag_different, i, query_seq_idx: integer; different_aligned_queries: Tstringlist; begin mem := '*'; n1 := 0; flagname := false; flaggap := false; //verify if sequences are selected for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin n1 := 1; break; end; if n1 = 0 then begin showmessage('No selected sequences'); exit; end; (* flag_different := 0; mem2 := ''; for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) then begin if mem2 = '' then mem2 := query_seq_list[w]; if mem2 <> query_seq_list[w] then begin flag_different := 1; break; end; end; //showmessage(inttostr(flag_different)); if (flag_different = 1) then exit; *) // all different aligned queries different_aligned_queries := Tstringlist.create; different_aligned_queries.add(query_seq_list[0]); for query_seq_idx := 1 to query_seq_list.count -1 do begin flag_already_added := false; // check if query seq already added for w:= 0 to different_aligned_queries.count - 1 do if query_seq_list[query_seq_idx] = different_aligned_queries[w] then begin flag_already_added := true; break; end; if not flag_already_added then different_aligned_queries.add(query_seq_list[query_seq_idx]) end; (* showmessage(inttostr(query_seq_list.count)); showmessage(inttostr(seq_list.count)); *) f2 := Tstringlist.create; for query_seq_idx := 0 to different_aligned_queries.count -1 do begin flag_query_added := false; for w := 0 to lv.items.count - 1 do if (lv.items[w].checked) and (different_aligned_queries[query_seq_idx] = query_seq_list[w]) then begin if not flag_query_added then begin f2.add(''); seq_ac := query_id; while length(seq_ac) < 100 do seq_ac := seq_ac + ' '; f2.add(seq_ac + ' ' + different_aligned_queries[query_seq_idx]); flag_query_added := true; end; new_seq := ''; for i := 1 to length(query_seq_list[w]) do begin // debugging showmessage(query_seq_list[w][i] + ' ' + seq_list[w][i]); if query_seq_list[w][i] = seq_list[w][i] then new_seq := new_seq + '.' else new_seq := new_seq + seq_list[w][i]; end; seq_ac := lv.items[w].subitems.strings[0]; seq_ac := seq_ac + ' ' +lv.items[w].subitems.strings[1]; while length(seq_ac) < 100 do seq_ac := seq_ac + ' '; f2.add(seq_ac + ' ' + new_seq); end; end; for w3 := 0 to f.Count - 1 do //search for database info if (pos(' residues ',f[w3])<>0) and (pos(' sequences',f[w3])<>0) and (pos(' in ',f[w3])<>0) then break; f2.insert(0, ''); f2.insert(0, ''); for w := w3+5 downto w3 do f2.Insert(0, f[w]); f2.insert(0, ''); for w:=6 downto 0 do //insert FASTA header f2.insert(0, f[w]); f2.insert(0, ''); f2.insert(0, 'FASTA scan ' + version_number + ' (output: query-anchored format)'); //end of file f2.add(''); for w:=f.Count-7 to f.Count-1 do f2.add(f[w]); // showmessage(inttostr(f2.count)); Screen.Cursor := crDefault; savedialog1.filename:=changefileext(nom_input,'.fbs'); if savedialog1.execute then begin flagadd:=false; if fileexists(savedialog1.filename) then begin frmWarning.showmodal; if frmWarning.modalresult=mrcancel then exit; if frmWarning.modalresult=mrno then flagadd:=true else flagadd:=false; end; if not flagadd then f2.savetofile(savedialog1.filename) //overwrite if file already exists else begin assignfile(ft,savedialog1.filename); //add if file already exists append(ft); for n1 := 0 to f2.count-1 do writeln(ft, f2[n1]); closefile(ft); end; end; mem := ''; f2.free; end; end. //u_main
unit uFoConfiguracao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, JvBaseDlg, JvSelectDirectory, uMetodosUteis, Configuracoes, Vcl.ToolWin, JvExComCtrls, JvToolBar, System.ImageList, Vcl.ImgList, Vcl.DBCtrls, uDMnfebkp,Usuarios,uFoPrincipal, Data.DB, Datasnap.DBClient,Datasnap.Provider, Atributos, ConfigPadrao, Vcl.Menus,uFoConfigPadrao; type TfoConfiguracao = class(TForm) pnlConfig: TPanel; pgcConfig: TPageControl; tsConfigBD: TTabSheet; btnGetDirBanco: TSpeedButton; edUsuarioBD: TLabeledEdit; edSenhaBD: TLabeledEdit; edArquivo: TLabeledEdit; tsConfigNFCe: TTabSheet; edNFCePathEnvio: TLabeledEdit; edNFCePathProcessado: TLabeledEdit; edNFCePathRejeitado: TLabeledEdit; edNFCePathRetornoLido: TLabeledEdit; edNFCePathPDFSalvo: TLabeledEdit; btnOpenNFCe1: TBitBtn; btnOpenNFCe2: TBitBtn; btnOpenNFCe3: TBitBtn; btnOpenNFCe4: TBitBtn; btnOpenNFCe5: TBitBtn; tsConfigNFSe: TTabSheet; edNFSePathEnvio: TLabeledEdit; edNFSePathProcessado: TLabeledEdit; edNFSePathRejeitado: TLabeledEdit; edNFSePathRetornoLido: TLabeledEdit; edNFSePathPDFSalvo: TLabeledEdit; btnOpenNFSe1: TBitBtn; btnOpenNFSe2: TBitBtn; btnOpenNFSe3: TBitBtn; btnOpenNFSe4: TBitBtn; btnOpenNFSe5: TBitBtn; jopdOpenDir: TJvSelectDirectory; dlgOpenDir: TOpenDialog; ilCadastro: TImageList; statMSg: TStatusBar; pnlRodape: TPanel; btn2: TBitBtn; btnOK: TBitBtn; pnlMenu: TPanel; jtobMenuConfig: TJvToolBar; btnAplicar: TBitBtn; edDescriConfig: TLabeledEdit; btn1: TToolButton; mm1: TMainMenu; mniAjuste1: TMenuItem; mniAjustarconfiguraopadro1: TMenuItem; btnIniFile: TToolButton; tsConfigNFe: TTabSheet; edNFePathEnvio: TLabeledEdit; edNFePathProcessado: TLabeledEdit; edNFePathRejeitado: TLabeledEdit; edNFePathRetornoLido: TLabeledEdit; edNFePathPDFSalvo: TLabeledEdit; btnOpen1: TBitBtn; btnOpen2: TBitBtn; btnOpen3: TBitBtn; btnOpen4: TBitBtn; btnOpen5: TBitBtn; procedure btnOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOpen1Click(Sender: TObject); procedure btnGetDirBancoClick(Sender: TObject); procedure btnOpen2Click(Sender: TObject); procedure btnOpen3Click(Sender: TObject); procedure btnOpen4Click(Sender: TObject); procedure btnOpen5Click(Sender: TObject); procedure btnOpenNFCe1Click(Sender: TObject); procedure btnOpenNFCe2Click(Sender: TObject); procedure btnOpenNFCe3Click(Sender: TObject); procedure btnOpenNFCe4Click(Sender: TObject); procedure btnOpenNFCe5Click(Sender: TObject); procedure btnOpenNFSe1Click(Sender: TObject); procedure btnOpenNFSe2Click(Sender: TObject); procedure btnOpenNFSe3Click(Sender: TObject); procedure btnOpenNFSe4Click(Sender: TObject); procedure btnOpenNFSe5Click(Sender: TObject); procedure btnInserirClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnAplicarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure edDescriConfigExit(Sender: TObject); procedure edUsuarioBDExit(Sender: TObject); procedure edSenhaBDExit(Sender: TObject); procedure edArquivoExit(Sender: TObject); procedure edNFePathEnvioExit(Sender: TObject); procedure btn2Click(Sender: TObject); procedure edNFePathProcessadoExit(Sender: TObject); procedure edNFePathRejeitadoExit(Sender: TObject); procedure edNFePathRetornoLidoExit(Sender: TObject); procedure edNFePathPDFSalvoExit(Sender: TObject); procedure edNFCePathEnvioExit(Sender: TObject); procedure edNFCePathProcessadoExit(Sender: TObject); procedure edNFCePathRejeitadoExit(Sender: TObject); procedure edNFCePathRetornoLidoExit(Sender: TObject); procedure edNFCePathPDFSalvoExit(Sender: TObject); procedure edNFSePathEnvioExit(Sender: TObject); procedure edNFSePathProcessadoExit(Sender: TObject); procedure edNFSePathRejeitadoExit(Sender: TObject); procedure edNFSePathRetornoLidoExit(Sender: TObject); procedure edNFSePathPDFSalvoExit(Sender: TObject); procedure btn1Click(Sender: TObject); procedure mniAjustarconfiguraopadro1Click(Sender: TObject); procedure btnIniFileClick(Sender: TObject); procedure pgcConfigChange(Sender: TObject); private { Private declarations } function validacampos(pForm : TForm): boolean; function LimpaCampos(pForm : TForm): boolean; procedure SalvarParametros; procedure AlteraEditaExcluiConfig; procedure LerParametros; procedure MsgStatus(pMsg : string; pCor : TColor = clBlack); function CarregaConfig(pTab : TConfiguracoes; pIdUsuario : integer): Boolean; overload; function CarregaConfig(pTab : TConfiguracoes; pIdUsuario : integer; pDescriConfig : string): Boolean; overload; function CarregaConfigPadrao(pTab : TConfigPadrao): Boolean; function CarregaIniFile: Boolean; procedure FormShowAlterar; procedure FormShowInserir; procedure FormShowDeletar; // function pOpenFileName(var prFileName:string): Boolean; // function pOpenPath(var prDirectory:string):boolean; procedure pEnableConfig(pForm : TForm;pEnable: boolean); procedure EditToTabela; procedure TabelaToEdit; public { Public declarations } IDConfig : Integer; //temporario FUsuarios : TUsuarios; ConfigId : integer; LastId : integer; published property Usuarios : TUsuarios read FUsuarios write FUsuarios; end; var foConfiguracao : TfoConfiguracao; wPathAux: string; SavStr : String; implementation {$R *.dfm} procedure TfoConfiguracao.AlteraEditaExcluiConfig; begin if wOpe = opNil then exit; with daoConfiguracoes, tabConfiguracoes do begin case wOpe of opExcluir: begin if MessageDlg('Deseja excluir a configuração '+ DescriConfig, mtConfirmation, mbYesNo,0) = mrYes then if fExcluirConfiguracoes(tabConfiguracoes) then begin statMSg.Panels[1].Text := 'Deletado!'; wOpe := opOK; end; end; opAlterar: begin tabUsuarios := TUsuarios.Create; tabUsuarios.ConfigSalva := tabConfiguracoes.id; if fSalvarConfiguracoes(tabConfiguracoes) then begin statMSg.Panels[1].Text := 'Salvo!'; daoUsuarios.fSalvar(tabUsuarios); wOpe := opOk; btnAplicar.Enabled := false; btnOK.Enabled := true; end; end; opInserir: begin if fInserirConfiguracoes(tabConfiguracoes) > 0 then begin statMSg.Panels[1].Text := 'Novo registo!'; wOpe := opOk; end; end; end; end; end; procedure TfoConfiguracao.btn1Click(Sender: TObject); begin if CarregaConfigPadrao(tabConfigpadrao) then MsgStatus('Configuração Padrão', clRed); end; procedure TfoConfiguracao.btn2Click(Sender: TObject); begin // end; procedure TfoConfiguracao.btnAplicarClick(Sender: TObject); begin if Validacampos(foConfiguracao) then begin EditToTabela; AlteraEditaExcluiConfig; end; end; procedure TfoConfiguracao.btnOKClick(Sender: TObject); begin if wOpe = opOK then ModalResult := mrOk end; procedure TfoConfiguracao.btnEditarClick(Sender: TObject); begin pgcConfig.Enabled := true; pnlRodape.Enabled := false; statMSg.Panels[1].Text := 'Alterando!'; end; procedure TfoConfiguracao.btnExcluirClick(Sender: TObject); begin wOpe := opExcluir; pEnableConfig(foConfiguracao, false); end; procedure TfoConfiguracao.btnGetDirBancoClick(Sender: TObject); begin // if fOpenFile('Selecione o Diretório do seu Banco de DADOS', wPathAux, ['FDB | *.*fdb'],1) then dlgOpenDir := TOpenDialog.Create(Application); dlgOpenDir.DefaultExt := 'FDB'; dlgOpenDir.InitialDir := GetCurrentDir; if dlgOpenDir.Execute then begin edArquivo.Text := dlgOpenDir.FileName; tabConfiguracoes.PathBD := dlgOpenDir.FileName; end; end; procedure TfoConfiguracao.btnIniFileClick(Sender: TObject); begin if CarregaIniFile then end; procedure TfoConfiguracao.btnInserirClick(Sender: TObject); begin statMSg.Panels[1].Text := 'Inserindo!'; end; procedure TfoConfiguracao.btnOpen1Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFePathEnvio.Text := wPathAux; tabConfiguracoes.NFePathEnvio := wPathAux; end; end; procedure TfoConfiguracao.btnOpen2Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFePathProcessado.Text := wPathAux; tabConfiguracoes.NFePathProcessado := wPathAux; end; end; procedure TfoConfiguracao.btnOpen3Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFePathRejeitado.Text := wPathAux; tabConfiguracoes.NFePathRejeitado := wPathAux; end; end; procedure TfoConfiguracao.btnOpen4Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFePathRetornoLido.Text := wPathAux; tabConfiguracoes.NFePathRetornoLido := wPathAux; end; end; procedure TfoConfiguracao.btnOpen5Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFePathPDFSalvo.Text := wPathAux; tabConfiguracoes.NFePathPDFSalvo := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFCe1Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFCePathEnvio.Text := wPathAux; tabConfiguracoes.NFCePathEnvio := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFCe2Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFCePathProcessado.Text := wPathAux; tabConfiguracoes.NFCePathProcessado := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFCe3Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFCePathRejeitado.Text := wPathAux; tabConfiguracoes.NFCePathRejeitado := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFCe4Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFCePathRetornoLido.Text := wPathAux; tabConfiguracoes.NFCePathRetornoLido := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFCe5Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFCePathPDFSalvo.Text := wPathAux; tabConfiguracoes.NFCePathPDFSalvo := wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFSe1Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFSePathEnvio.Text := wPathAux; tabConfiguracoes.NFSePathEnvio:= wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFSe2Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFSePathProcessado.Text := wPathAux; tabConfiguracoes.NFSePathProcessado:= wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFSe3Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFSePathRejeitado.Text := wPathAux; tabConfiguracoes.NFSePathRejeitado:= wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFSe4Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFSePathRetornoLido.Text := wPathAux; tabConfiguracoes.NFSePathRetornoLido:= wPathAux; end; end; procedure TfoConfiguracao.btnOpenNFSe5Click(Sender: TObject); begin if fOpenPath(wPathAux) then begin edNFSePathPDFSalvo.Text := wPathAux; tabConfiguracoes.NFSePathPDFSalvo:= wPathAux; end; end; function TfoConfiguracao.CarregaConfigPadrao(pTab: TConfigPadrao): Boolean; begin Result := false; try try pTab.IDusuario := 0; with pTab do begin daoConfigPadrao.fCarregaConfigPadrao(pTab, ['id']); with tabConfigpadrao do begin edUsuarioBD.Text := UsuarioBD; edSenhaBD.Text := SenhaBD; edArquivo.Text := PathBD+'\'+NameBD; //Aba Configura NFe edNFePathEnvio.Text := NFePathEnvio; edNFePathProcessado.Text := NFePathProcessado; edNFePathRejeitado.Text := NFePathRejeitado; edNFePathRetornoLido.Text := NFePathRetornoLido; edNFePathPDFSalvo.Text := NFePathPDFSalvo; //Aba Configura NFCe edNFCePathEnvio.Text := NFCePathEnvio; edNFCePathProcessado.Text := NFCePathProcessado; edNFCePathRejeitado.Text := NFCePathRejeitado; edNFCePathRetornoLido.Text := NFCePathRetornoLido; edNFCePathPDFSalvo.Text := NFCePathPDFSalvo; //Aba Configura NFSe edNFSePathEnvio.Text := NFSePathEnvio; edNFSePathProcessado.Text := NFSePathProcessado; edNFSePathRejeitado.Text := NFSePathRejeitado; edNFSePathRetornoLido.Text := NFSePathRetornoLido; edNFSePathPDFSalvo.Text := NFSePathPDFSalvo; Result := true; end; end; except end; finally end; end; function TfoConfiguracao.CarregaIniFile: Boolean; var wFilePathIni : string; begin //if fOpenFile('Localiza o INI File MAXWIN/MAXECV',wFilePathIni, ['INI | *.*ini'],1,'*.*ini') then dlgOpenDir := TOpenDialog.Create(Application); dlgOpenDir.DefaultExt := 'INI'; dlgOpenDir.InitialDir := GetCurrentDir; if dlgOpenDir.Execute then begin wFilePathIni := dlgOpenDir.FileName; edUsuarioBD.Text := 'sysdba'; edSenhaBD.Text := 'masterkey'; edArquivo.Text := ''; edDescriConfig.Text := fNomePC; //Aba Configura NFe edNFePathEnvio.Text := getINI(wFilePathIni,'NFe','Caminho',''); edNFePathProcessado.text := getINI(wFilePathIni,'NFe','Caminho','') + '\Processado'; edNFePathRejeitado.text := getINI(wFilePathIni,'NFe','Caminho','') + '\Rejeitado'; edNFePathRetornoLido.Text := getINI(wFilePathIni,'NFe','Retorno','') + '\lido'; edNFePathPDFSalvo.Text := getINI(wFilePathIni,'NFe','Caminho','') +'\PDF'; //Aba Configura NFCe edNFCePathEnvio.Text := getINI(wFilePathIni,'NFCe','Caminho',''); edNFCePathProcessado.Text := getINI(wFilePathIni,'NFCe','Caminho','')+'\Processado'; edNFCePathRejeitado.Text := getINI(wFilePathIni,'NFCe','Caminho','')+'\Rejeitado'; edNFCePathRetornoLido.Text := getINI(wFilePathIni,'NFCe','Retorno','')+ '\lido'; edNFCePathPDFSalvo.Text := getINI(wFilePathIni,'NFCe','Caminho','')+'\PDF'; //Aba Configura NFSe edNFSePathEnvio.Text := getINI(wFilePathIni,'NFSe','Caminho',''); edNFSePathProcessado.Text := getINI(wFilePathIni,'NFSe','Caminho','')+'\Processado'; edNFSePathRejeitado.Text := getINI(wFilePathIni,'NFSe','Caminho','')+'\Rejeitado'; edNFSePathRetornoLido.Text := getINI(wFilePathIni,'NFSe','Retorno','')+ '\lido'; edNFSePathPDFSalvo.Text := getINI(wFilePathIni,'NFSe','Caminho','')+'\PDF'; end; end; function TfoConfiguracao.CarregaConfig(pTab : TConfiguracoes; pIdUsuario : integer; pDescriConfig : string): Boolean; begin Result := false; try try pTab.DescriConfig := pDescriConfig; pTab.IDusuario := pIdUsuario; with pTab do begin daoConfiguracoes.fCarregaConfiguracoes(pTab, ['idusuario','DescriConfig']); with tabConfiguracoes do begin edUsuarioBD.Text := UsuarioBD; edSenhaBD.Text := SenhaBD; edArquivo.Text := PathBD+'\'+NameBD; //Aba Configura NFe edNFePathEnvio.Text := NFePathEnvio; edNFePathProcessado.Text := NFePathProcessado; edNFePathRejeitado.Text := NFePathRejeitado; edNFePathRetornoLido.Text := NFePathRetornoLido; edNFePathPDFSalvo.Text := NFePathPDFSalvo; //Aba Configura NFCe edNFCePathEnvio.Text := NFCePathEnvio; edNFCePathProcessado.Text := NFCePathProcessado; edNFCePathRejeitado.Text := NFCePathRejeitado; edNFCePathRetornoLido.Text := NFCePathRetornoLido; edNFCePathPDFSalvo.Text := NFCePathPDFSalvo; //Aba Configura NFSe edNFSePathEnvio.Text := NFSePathEnvio; edNFSePathProcessado.Text := NFSePathProcessado; edNFSePathRejeitado.Text := NFSePathRejeitado; edNFSePathRetornoLido.Text := NFSePathRetornoLido; edNFSePathPDFSalvo.Text := NFSePathPDFSalvo; Result := true; end; end; except end; finally end; end; function TfoConfiguracao.CarregaConfig(pTab : TConfiguracoes ; pIdUsuario : integer): Boolean; begin Result := false; try try pTab.ID := pIdUsuario; with pTab do begin if not Assigned(ptab) then daoConfiguracoes.fCarregaConfiguracoes(pTab, ['id']); with pTab do begin edUsuarioBD.Text := UsuarioBD; edSenhaBD.Text := SenhaBD; edArquivo.Text := PathBD+'\'+NameBD; //Aba Configura NFe edNFePathEnvio.Text := NFePathEnvio; edNFePathProcessado.Text := NFePathProcessado; edNFePathRejeitado.Text := NFePathRejeitado; edNFePathRetornoLido.Text := NFePathRetornoLido; edNFePathPDFSalvo.Text := NFePathPDFSalvo; //Aba Configura NFCe edNFCePathEnvio.Text := NFCePathEnvio; edNFCePathProcessado.Text := NFCePathProcessado; edNFCePathRejeitado.Text := NFCePathRejeitado; edNFCePathRetornoLido.Text := NFCePathRetornoLido; edNFCePathPDFSalvo.Text := NFCePathPDFSalvo; //Aba Configura NFSe edNFSePathEnvio.Text := NFSePathEnvio; edNFSePathProcessado.Text := NFSePathProcessado; edNFSePathRejeitado.Text := NFSePathRejeitado; edNFSePathRetornoLido.Text := NFSePathRetornoLido; edNFSePathPDFSalvo.Text := NFSePathPDFSalvo; edDescriConfig.Text := DescriConfig; Result := true; end; end; except end; finally end; end; procedure TfoConfiguracao.edArquivoExit(Sender: TObject); var bdPath, bdSource :string; begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if PathBD+'\'+NameBD <> Text then begin PathBD := ExtractFileDir(Trim(Text)); NameBD := ExtractFileName(Trim(Text)); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; pgcConfig.TabIndex := 1; end; procedure TfoConfiguracao.edDescriConfigExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if DescriConfig <> Text then begin DescriConfig := Trim(Text); end; ShowHint := False; if Length(Text) > 20 then if CanFocus then begin Hint := 'Este campo pode ter no máximo 20 caracteres.'; ShowHint := true; SetFocus; end; end; end; procedure TfoConfiguracao.EditToTabela; begin if NOT Assigned(tabConfiguracoes) then exit; with tabConfiguracoes do begin DescriConfig := edDescriConfig.Text; // IDusuario UsuarioBD := Trim(edUsuarioBD.Text); SenhaBD := edSenhaBD.Text; PathBD := ExtractFileDir(edArquivo.Text); NameBD := ExtractFileName(edArquivo.Text); //Aba Configura NFe NFePathEnvio := edNFePathEnvio.Text; NFePathProcessado := edNFePathProcessado.Text; NFePathRejeitado := edNFePathRejeitado.Text; NFePathRetornoLido := edNFePathRetornoLido.Text; NFePathPDFSalvo := edNFePathPDFSalvo.Text; //Aba Configura NFCe NFCePathEnvio := edNFCePathEnvio.Text; NFCePathProcessado := edNFCePathProcessado.Text; NFCePathRejeitado := edNFCePathRejeitado.Text; NFCePathRetornoLido := edNFCePathRetornoLido.Text; NFCePathPDFSalvo := edNFCePathPDFSalvo.Text; //Aba Configura NFSe NFSePathEnvio := edNFSePathEnvio.Text; NFSePathProcessado := edNFSePathProcessado.Text; NFSePathRejeitado := edNFSePathRejeitado.Text; NFSePathRetornoLido := edNFSePathRetornoLido.Text; NFSePathPDFSalvo := edNFSePathPDFSalvo.Text; end; end; procedure TfoConfiguracao.edNFCePathProcessadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFCePathProcessado <> Text then begin NFCePathProcessado := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFCePathEnvioExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFCePathEnvio <> Text then begin NFCePathEnvio := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFePathProcessadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFePathProcessado <> Text then begin NFePathProcessado := Trim(Text); end; // ShowHint := False; // if Length(Text) > 255 then // if CanFocus then // begin // Hint := 'Este campo pode ter no máximo 255 caracteres.'; // ShowHint := true; // SetFocus; // end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFePathEnvioExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFePathEnvio <> Text then begin NFePathEnvio := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFSePathProcessadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFSePathProcessado <> Text then begin NFSePathProcessado := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFSePathEnvioExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFSePathEnvio <> Text then begin NFSePathEnvio := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFCePathRetornoLidoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFCePathRetornoLido <> Text then begin NFCePathRetornoLido := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFePathRetornoLidoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFePathRetornoLido <> Text then begin NFePathRetornoLido := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFSePathRetornoLidoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFSePathRetornoLido <> Text then begin NFSePathRetornoLido := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFCePathRejeitadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFCePathRejeitado <> Text then begin NFCePathRejeitado := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFePathRejeitadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFePathRejeitado <> Text then begin NFePathRejeitado := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFSePathRejeitadoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFSePathRejeitado <> Text then begin NFSePathRejeitado := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFCePathPDFSalvoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFCePathPDFSalvo <> Text then begin NFCePathPDFSalvo := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFePathPDFSalvoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFePathPDFSalvo <> Text then begin NFePathPDFSalvo := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edNFSePathPDFSalvoExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if NFSePathPDFSalvo <> Text then begin NFSePathPDFSalvo := Trim(Text); end; if (Trim(Text) <> '') and not (DirectoryExists(Trim(ExtractFileDir(Text)))) then if CanFocus then begin MsgStatus('Diretório informado não existe', clRed); SetFocus; end; end; end; procedure TfoConfiguracao.edSenhaBDExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if SenhaBD <> Text then begin SenhaBD := Trim(Text); end; ShowHint := False; if Length(Text) > 10 then if CanFocus then begin Hint := 'Este campo pode ter no máximo 10 caracteres.'; ShowHint := true; SetFocus; end; end; end; procedure TfoConfiguracao.edUsuarioBDExit(Sender: TObject); begin with tabConfiguracoes, TLabeledEdit(Sender) do begin if UsuarioBD <> Text then begin UsuarioBD := Trim(Text); end; ShowHint := False; if Length(Text) > 15 then if CanFocus then begin Hint := 'Este campo pode ter no máximo 15 caracteres.'; ShowHint := true; SetFocus; end; end; end; procedure TfoConfiguracao.FormClose(Sender: TObject; var Action: TCloseAction); begin // end; procedure TfoConfiguracao.FormCreate(Sender: TObject); begin if not Assigned(tabConfiguracoes) then tabConfiguracoes := TConfiguracoes.Create; pgcConfig.TabIndex := 0; //validacampos(foConfiguracao); end; procedure TfoConfiguracao.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin {// key down } if (Shift = [ssCtrl]) and (key = vk_return) then begin btnAplicarClick(Self); btnOKClick(Self); end; //ShowMessage('Voce apertou Crtl + Enter'); end; procedure TfoConfiguracao.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then //Enter begin key := #0; perform(wm_nextdlgctl,0,0); end; end; procedure TfoConfiguracao.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin {// key up if (Shift = [ssCtrl]) and (key = vk_return) then ShowMessage('Voce apertou Crtl + Enter');} if key = VK_ESCAPE then begin if MessageDlg('Deseja cancelar a operação de inserir', mtConfirmation, mbYesNo,0) = mrNo then begin case wOpe of opInserir: begin end; opAlterar: begin end; end; end else ModalResult := mrCancel; end; end; procedure TfoConfiguracao.FormShow(Sender: TObject); begin LimpaCampos(foConfiguracao); pgcConfig.TabIndex := 0; case wOpe of opInserir: FormShowInserir; opAlterar: FormShowAlterar; end; end; procedure TfoConfiguracao.FormShowAlterar; begin btnOK.Enabled := not (CarregaConfig(tabConfiguracoes,tabConfiguracoes.Id)); end; procedure TfoConfiguracao.FormShowDeletar; begin end; procedure TfoConfiguracao.FormShowInserir; begin if edDescriConfig.CanFocus then begin edDescriConfig.SetFocus; end; end; procedure TfoConfiguracao.LerParametros; begin if FileExists(fArqIni) then begin edUsuarioBD.Text := getINI(fArqIni, 'BD', 'USUARIO', ''); edSenhaBD.Text := getINI(fArqIni, 'BD', 'SENHA', ''); edArquivo.Text := getINI(fArqIni, 'BD', 'ARQUIVO', ''); IDConfig := StrToIntDef (getINI(fArqIni, 'Config','id', ''),0); end; end; function TfoConfiguracao.LimpaCampos(pForm: TForm): boolean; var i: Integer; begin result := false; if not Assigned(pForm) then exit; for i:= 0 to pForm.ComponentCount-1 do //Percorre todos os componentes da tela begin if pForm.Components[i] is TLabeledEdit then TLabeledEdit(pForm.Components[i]).Clear; end; result := true; end; procedure TfoConfiguracao.mniAjustarconfiguraopadro1Click(Sender: TObject); begin foConfigPadrao := TfoConfigPadrao.Create(Application); try wOpe := opAlterar; daoConfigPadrao.fCarregaConfigPadrao(tabConfigPadrao,['id']); TabelaToEdit; foConfigPadrao.ShowModal; finally foConfigPadrao.Free; end; end; procedure TfoConfiguracao.MsgStatus(pMsg: string; pCor: TColor); begin statMSg.Font.Color := pCor; statMSg.Panels[1].Text := Trim(pMsg); end; procedure TfoConfiguracao.pEnableConfig(pForm : TForm; pEnable: boolean); var i : integer; begin if not Assigned(pForm) then exit; for i:= 0 to pForm.ComponentCount-1 do begin if pForm.Components[i] is TTabSheet then TTabSheet(pForm.Components[i]).Enabled := pEnable; end; end; procedure TfoConfiguracao.pgcConfigChange(Sender: TObject); begin end; //function TfoConfiguracao.pOpenFileName(var prFileName:string): Boolean; //begin // dlgOpenDir := TOpenDialog.Create(Application); // try // Result := dlgOpenDir.Execute; // if Result then // prFileName := dlgOpenDir.FileName // else // prFileName := ''; // finally // dlgOpenDir.Free; // end; //end; //function TfoConfiguracao.pOpenPath(var prDirectory: string): Boolean; //begin // Result := false; // jopdOpenDir := TJvSelectDirectory.Create(Application); // try // Result := jopdOpenDir.Execute; // if Result then // prDirectory := jopdOpenDir.Directory // else // prDirectory := ''; // finally // jopdOpenDir.Free; // end; //end; procedure TfoConfiguracao.SalvarParametros; var wINI : string; begin wINI := ExtractFileName(ChangeFileExt(Application.ExeName, 'INI')); wINI := GetCurrentDir +'\'+wIni; setINI(wINI, 'BD', 'USUARIO', Trim(edUsuarioBD.Text)); setINI(wINI, 'BD', 'SENHA', Trim(edSenhaBD.Text)); setINI(wINI, 'BD', 'ARQUIVO', Trim(edArquivo.Text)); end; procedure TfoConfiguracao.TabelaToEdit; begin LimpaCampos(foConfiguracao); with tabConfiguracoes do begin edUsuarioBD.Text := UsuarioBD; edSenhaBD.Text := SenhaBD; edArquivo.Text := PathBD+'\'+NameBD; //Aba Configura NFe edNFePathEnvio.Text := NFePathEnvio; edNFePathProcessado.Text := NFePathProcessado; edNFePathRejeitado.Text := NFePathRejeitado; edNFePathRetornoLido.Text := NFePathRetornoLido; edNFePathPDFSalvo.Text := NFePathPDFSalvo; //Aba Configura NFCe edNFCePathEnvio.Text := NFCePathEnvio; edNFCePathProcessado.Text := NFCePathProcessado; edNFCePathRejeitado.Text := NFCePathRejeitado; edNFCePathRetornoLido.Text := NFCePathRetornoLido; edNFCePathPDFSalvo.Text := NFCePathPDFSalvo; //Aba Configura NFSe edNFSePathEnvio.Text := NFSePathEnvio; edNFSePathProcessado.Text := NFSePathProcessado; edNFSePathRejeitado.Text := NFSePathRejeitado; edNFSePathRetornoLido.Text := NFSePathRetornoLido; edNFSePathPDFSalvo.Text := NFSePathPDFSalvo; end; end; function TfoConfiguracao.validacampos(pForm : TForm): boolean; var i,tabIdx,iTab : Integer; NameLabel, NameComp : string; begin result := True; if not Assigned(pForm) then exit; for i:= 0 to pForm.ComponentCount-1 do //Percorre todos os componentes da tela begin // NameComp := (pForm.Components[i]). if pForm.Components[i] is TTabSheet then // Verifica seé TabSheet begin tabIdx := TTabSheet(pForm.Components[i]).TabIndex; //Salva o tab order iTab := i; //Salva o index da tab atual end; if pForm.Components[i] is TLabeledEdit then if Trim(TLabeledEdit(pForm.Components[i]).Text) = '' then begin if pForm.Components[iTab] is TTabSheet then begin pgcConfig.TabIndex := tabIdx; // if TTabSheet(pForm.Components[iTab]).CanFocus then // begin // TTabSheet(pForm.Components[iTab]).SetFocus; if TLabeledEdit(pForm.Components[i]).CanFocus then begin NameLabel := TLabeledEdit(pForm.Components[i]).EditLabel.Caption; MsgStatus('O Campo '+ NameLabel + ' está vazio!', clRed); // ShowMessage('O Campo '+ NameLabel + ' está vazio!' ); TLabeledEdit(pForm.Components[i]).SetFocus; result := False; Break; end; // end; end; end else result := true; end; if result then MsgStatus('Validação OK', clBlack); end; end.
unit frmBusyUnit; {$mode objfpc}{$H+} interface uses {$ifdef windows} windows, {$endif} {$ifdef darwin} macport, {$endif} Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, memscan, syncobjs, betterControls,SyncObjs2; type { TfrmBusy } TfrmBusy = class(TForm) Label1: TLabel; Timer1: TTimer; procedure FormCloseQuery(Sender: TObject; var CanClose: boolean); procedure FormShow(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { private declarations } oktoclose: boolean; fReason: TPostScanState; procedure setReason(r: TPostScanState); public { public declarations } WaitForThread: TThread; memscan: TMemScan; property reason: TPostScanState read fReason write setReason; end; resourcestring rsBusy='The previous scan is still being processed. Please wait'; rsJustFinished = '(Just starting to process)'; rsOptimizingScanResults = '(Optimizing result list for improved speed)'; rsTerminatingThreads = '(Freeing scanner thread memory)'; rsSavingFirstScanResults = '(Copying results for first scan scanner option)'; rsShouldBeFinished = '(There''s no reason to wait)'; rsSavingFirstScanResults2 = '(Still copying the results for the first scan ' +'scanner option)'; implementation {$R *.lfm} { TfrmBusy } procedure TfrmBusy.setReason(r: TPostScanState); var reasonstr: string; begin if r<>fReason then begin freason:=r; reasonstr:=#13#10; case r of psJustFinished: reasonstr:=reasonstr+rsJustFinished; psOptimizingScanResults: reasonstr:=reasonstr+rsOptimizingScanResults; psTerminatingThreads: reasonstr:=reasonstr+rsTerminatingThreads; psSavingFirstScanResults: reasonstr:=reasonstr+rsSavingFirstScanResults; psShouldBeFinished: reasonstr:=reasonstr+rsShouldBeFinished; psSavingFirstScanResults2: reasonstr:=reasonstr+rsSavingFirstScanResults2 else reasonstr:=''; end; label1.caption:=rsBusy+reasonstr; end; end; procedure TfrmBusy.FormShow(Sender: TObject); begin timer1.enabled:=true; end; procedure TfrmBusy.FormCloseQuery(Sender: TObject; var CanClose: boolean); begin canclose:=oktoclose; end; procedure TfrmBusy.Timer1Timer(Sender: TObject); begin if (WaitForThread<>nil) then begin if WaitForThread.WaitTillDone(50) then begin oktoclose:=true; if fsModal in FFormState then modalresult:=mrok else close; end; end; if (memscan<>nil) and (reason<>memscan.postscanstate) then begin reason:=memscan.postScanState; end; end; initialization end.
unit ExeInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TMAGExeInfo = class(TDataModule) private { Private declarations } public { Public declarations } Signature : DWord; // EXE Signature HiVersion : Word; // Major version number LoVersion : Word; // Minor version number ReleaseVersion : Word; // Release version number BuildVersion : Word; // Build version number Debug : Boolean; // Debug info included PreRelease : Boolean; // Pre-release (beta) version PrivateBuild : Boolean; // Private Build SpecialBuild : Boolean; // Special Build FileDescription : String; // File Description FileVersion : String; // File Version InternalName : String; // Internal Name LegalCopyright : String; // Legal Copyright ProductDescription : String; // Product Name ProductVersion : String; // Product Version function GetEXEInfo(FileName : String) : Boolean; end; var MAGExeInfo: TMAGExeInfo; implementation {$R *.DFM} { Get's EXE information } function TMAGExeInfo.GetEXEInfo(FileName : String) : Boolean; var Size, Size2: DWord; Pt, Pt2: Pointer; begin { Initialize all variables } Signature := 0; HiVersion := 0; LoVersion := 0; ReleaseVersion := 0; BuildVersion := 0; Debug := FALSE; PreRelease := FALSE; PrivateBuild := FALSE; SpecialBuild := FALSE; FileDescription := ''; FileVersion := ''; InternalName := ''; LegalCopyright := ''; ProductDescription := ''; ProductVersion := ''; { Open file and get info } Size := GetFileVersionInfoSize(PChar(FileName), Size2); if Size > 0 then begin GetMem (Pt, Size); try GetFileVersionInfo(PChar(FileName), 0, Size, Pt); // Get the fixed information VerQueryValue (Pt, '\', Pt2, Size2); with TVSFixedFileInfo (Pt2^) do begin Signature := dwSignature; HiVersion := HiWord(dwFileVersionMS); LoVersion := LoWord(dwFileVersionMS); ReleaseVersion := HiWord(dwFileVersionLS); BuildVersion := LoWord(dwFileVersionLS); if (dwFileFlagsMask and dwFileFlags and VS_FF_DEBUG) <> 0 then Debug := TRUE; if (dwFileFlagsMask and dwFileFlags and VS_FF_PRERELEASE) <> 0 then PreRelease := TRUE; if (dwFileFlagsMask and dwFileFlags and VS_FF_PRIVATEBUILD) <> 0 then PrivateBuild := TRUE; if (dwFileFlagsMask and dwFileFlags and VS_FF_SPECIALBUILD) <> 0 then SpecialBuild := TRUE; end; // Get some strings VerQueryValue(Pt, '\StringFileInfo\040904E4\FileDescription', Pt2, Size2); FileDescription := PChar(Pt2); // VerQueryValue(Pt, '\StringFileInfo\040904E4\FileVersion', Pt2, Size2); FileVersion := PChar(pt2); // VerQueryValue(Pt, '\StringFileInfo\040904E4\InternalName', Pt2, Size2); InternalName := PChar(pt2); // VerQueryValue(Pt, '\StringFileInfo\040904E4\LegalCopyright', Pt2, Size2); LegalCopyright := PChar(pt2); // VerQueryValue(Pt, '\StringFileInfo\040904E4\ProductDescription', Pt2, Size2); ProductDescription := PChar(pt2); // VerQueryValue(Pt, '\StringFileInfo\040904E4\ProductVersion', Pt2, Size2); ProductVersion := PChar(pt2); finally FreeMem (Pt); end; Result := TRUE; end else Result := FALSE; end; end.
unit uOperationTypes; interface uses SysUtils; type TOperationType = ( otUnknown, otCashToCard, otHomeMoney, otPayoutTransfer, otPayoutRevokedTransfer, otCancelTransfer, otSwiftTransfer, otTransfer, otWireTransfer ); function TryToParseOperationType(const StrType: String): TOperationType; function OperationTypeAsText(operType: TOperationType): String; implementation function TryToParseOperationType(const StrType: String): TOperationType; var typeUpper: String; begin typeUpper := UpperCase(StrType); if typeUpper = 'CASHTOCARD' then Result := otCashToCard else if typeUpper = 'HOMEMONEY' then Result := otHomeMoney else if typeUpper = 'PAYOUTTRANSFER' then Result := otPayoutTransfer else if typeUpper = 'PAYOUTREVOKEDTRANSFER' then Result := otPayoutRevokedTransfer else if typeUpper = 'SWIFTTRANSFER' then Result := otSwiftTransfer else if typeUpper = 'TRANSFER' then Result := otTransfer else if typeUpper = 'WIRETRANSFER' then Result := otWireTransfer else raise Exception.Create('Unknown operation type: ' + StrType); end; function OperationTypeAsText(operType: TOperationType): String; begin case operType of otUnknown : Result := 'UNKNOWN'; otCashToCard : Result := 'CashToCard'; otHomeMoney : Result := 'HomeMoney'; otPayoutTransfer : Result := 'PayoutTransfer'; otSwiftTransfer : Result := 'SwiftTransfer'; otTransfer : Result := 'Transfer'; otWireTransfer : Result := 'WireTransfer'; otPayoutRevokedTransfer : Result := 'PayoutRevokedTransfer'; end; end; end.
unit FirmaDigitale; interface uses Classes, IInterface; type TFirmaDigitale = class protected FTipoFirma: Integer; FAttivata: Boolean; FSessioneAperta: Boolean; public constructor Create( tf: Integer ); virtual; abstract; function Firma(PassPhrase: string; Nominativo: string; MyStream: TMemoryStream; OutStream: TMemoryStream; var ErrString: string): TpResultFirma; virtual; abstract; procedure ApriSessione(PassPhrase: string); virtual; abstract; procedure ChiudiSessione; virtual; abstract; function LeggiOwner: string; virtual; abstract; function DecodeStream(MyStream: TMemoryStream; OutStream: TMemoryStream): integer; virtual; abstract; property TipoFirma: Integer read FTipoFirma write FTipoFirma; property Attivata: boolean read FAttivata; property SessioneAperta: Boolean read FSessioneAperta; end; implementation end.
unit BusinessObjectsU; interface type TPerson = class private FLastName: String; FDOB: TDate; FFirstName: String; FMarried: boolean; procedure SetDOB(const Value: TDate); procedure SetFirstName(const Value: String); procedure SetLastName(const Value: String); procedure SetMarried(const Value: boolean); public property FirstName: String read FFirstName write SetFirstName; property LastName: String read FLastName write SetLastName; property DOB: TDate read FDOB write SetDOB; property Married: boolean read FMarried write SetMarried; end; implementation { TPerson } procedure TPerson.SetDOB(const Value: TDate); begin FDOB := Value; end; procedure TPerson.SetFirstName(const Value: String); begin FFirstName := Value; end; procedure TPerson.SetLastName(const Value: String); begin FLastName := Value; end; procedure TPerson.SetMarried(const Value: boolean); begin FMarried := Value; end; end.
unit MediaFile; interface uses Generics.Collections, Artist, Aurelius.Mapping.Attributes, Aurelius.Types.Nullable, Aurelius.Types.Proxy; type TAlbum = class; [Entity] [Table('MEDIA_FILES')] [Sequence('SEQ_MEDIA_FILES')] [Inheritance(TInheritanceStrategy.SingleTable)] [DiscriminatorColumn('MEDIA_TYPE', TDiscriminatorType.dtString)] [Id('FId', TIdGenerator.IdentityOrSequence)] TMediaFile = class public [Column('ID', [TColumnProp.Unique, TColumnProp.Required, TColumnProp.NoUpdate])] FId: Integer; FMediaName: string; FFileLocation: string; FDuration: Nullable<integer>; [Association([TAssociationProp.Lazy], [])] [JoinColumn('ID_ALBUM', [])] FAlbum: Proxy<TAlbum>; [Association([TAssociationProp.Lazy], [])] [JoinColumn('ID_ARTIST', [])] FArtist: Proxy<TArtist>; function GetAlbum: TAlbum; function GetArtist: TArtist; procedure SetAlbum(const Value: TAlbum); procedure SetArtist(const Value: TArtist); function GetDurationAsString: string; public property Id: integer read FId; [Column('MEDIA_NAME', [TColumnProp.Required], 100)] property MediaName: string read FMediaName write FMediaName; [Column('FILE_LOCATION', [], 300)] property FileLocation: string read FFileLocation write FFileLocation; [Column('DURATION', [])] property Duration: Nullable<integer> read FDuration write FDuration; property Album: TAlbum read GetAlbum write SetAlbum; property Artist: TArtist read GetArtist write SetArtist; property DurationAsString: string read GetDurationAsString; end; [Entity] [Table('ALBUMS')] [Sequence('SEQ_ALBUMS')] [Id('FId', TIdGenerator.IdentityOrSequence)] TAlbum = class private [Column('ID', [TColumnProp.Unique, TColumnProp.Required, TColumnProp.NoUpdate])] FId: Integer; FAlbumName: string; FReleaseYear: Nullable<Integer>; FMediaFiles: TList<TMediaFile>; function GetDuration: Nullable<integer>; function GetDurationAsString: string; public property Id: integer read FId; [Column('ALBUM_NAME', [TColumnProp.Required], 100)] property AlbumName: string read FAlbumName write FAlbumName; [Column('RELEASE_YEAR', [])] property ReleaseYear: Nullable<Integer> read FReleaseYear write FReleaseYear; [ManyValuedAssociation([], CascadeTypeAll, 'FAlbum')] property MediaFiles: TList<TMediaFile> read FMediaFiles write FMediaFiles; property Duration: Nullable<integer> read GetDuration; property DurationAsString: string read GetDurationAsString; constructor Create; destructor Destroy; override; end; implementation uses SysUtils; { TMediaFile } function TMediaFile.GetAlbum: TAlbum; begin Result := FAlbum.Value; end; function TMediaFile.GetArtist: TArtist; begin Result := FArtist.Value; end; function TMediaFile.GetDurationAsString: string; begin if Duration.HasValue then Result := Format( '%s:%s', [FormatFloat('#0', Duration.Value div 60), FormatFloat('00', Duration.Value mod 60) ]) else Result := ''; end; procedure TMediaFile.SetAlbum(const Value: TAlbum); begin FAlbum.Value := Value; end; procedure TMediaFile.SetArtist(const Value: TArtist); begin FArtist.Value := Value; end; { TAlbum } constructor TAlbum.Create; begin FMediaFiles := TList<TMediaFile>.Create; end; destructor TAlbum.Destroy; begin FMediaFiles.Free; inherited; end; function TAlbum.GetDuration: Nullable<integer>; var I: Integer; begin if FMediaFiles.Count = 0 then Exit(SNULL); Result := 0; for I := 0 to FMediaFiles.Count - 1 do begin if FMediaFiles[I].Duration.IsNull then Exit(SNULL); Result := Result.Value + FMediaFiles[I].Duration.Value; end; end; function TAlbum.GetDurationAsString: string; begin if Duration.HasValue then Result := Format( '%s:%s', [FormatFloat('#0', Duration.Value div 60), FormatFloat('00', Duration.Value mod 60) ]) else Result := ''; end; end.
unit DataType; interface uses Classes, Types, Generics.Collections, CodeElement; type TRawType = (rtUInteger, rtBoolean, rtPointer, rtArray, rtRecord, rtString, rtNilType); TDataType = class(TCodeElement) private FRawType: TRawType; FSize: Integer; FBaseType: TDataType; FDimensions: TList<Integer>; function GetIsStaticArray: Boolean; public constructor Create(AName: string; ASize: Integer = 2; APrimitive: TRawType = rtUInteger; ABaseType: TDataType = nil); function GetRamWordSize(): Integer; property Size: Integer read FSize; property RawType: TRawType read FRawType; property BaseType: TDataType read FBaseType; property Dimensions: TList<Integer> read FDimensions; property IsStaticArray: Boolean read GetIsStaticArray; end; implementation { TDataType } constructor TDataType.Create(AName: string; ASize: Integer = 2; APrimitive: TRawType = rtUInteger; ABaseType: TDataType = nil); begin inherited Create(AName); FDimensions := TList<Integer>.Create(); FSize := ASize; FRawType := APrimitive; if Assigned(ABaseType) then begin FBaseType := ABaseType; end else begin FBaseType := Self; end; end; function TDataType.GetIsStaticArray: Boolean; begin Result := (RawType = rtArray) and (FDimensions.Count > 0); end; function TDataType.GetRamWordSize: Integer; var LArSize: Integer; LDimSize: Integer; begin if RawType = rtArray then begin LArSize := 1; for LDimSize in FDimensions do begin LArSize := LArSize * LDimSize; end; Result := LArSize * BaseType.GetRamWordSize(); end else begin Result := FSize div 2; end; end; end.
unit UTestParams; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TTestParams = class(TForm) ipList: TListBox; btOk: TButton; btCancel: TButton; procedure btCancelClick(Sender: TObject); function GetSelectedAddress: string; procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ipListDblClick(Sender: TObject); private { Private declarations } public { Public declarations } property SelectedAddress: string read GetSelectedAddress; end; implementation {$R *.DFM} procedure TTestParams.btCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TTestParams.FormCreate(Sender: TObject); begin ipList.Items.Clear(); ipList.Items.Add('127.0.0.1'); ipList.Items.Add('10.20.0.104'); ipList.Items.Add('10.20.5.72'); ipList.Items.Add('10.20.6.5'); ipList.ItemIndex := 0; end; procedure TTestParams.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then ModalResult := mrOk; if Key = VK_ESCAPE then ModalResult := mrCancel; end; function TTestParams.GetSelectedAddress: string; begin Result := ipList.Items[ipList.ItemIndex]; end; procedure TTestParams.ipListDblClick(Sender: TObject); begin ModalResult := mrOk; end; end.
unit aOPCDataObject; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, aCustomOPCSource, uDCObjects; type TOPCDirection = (vdLeft, vdRight, vdUp, vdDown); TOPCPosition = (vpHorizontal, vpVertical, vpLeftDiagonal, vpRightDiagonal); TaCustomOPCDataObject = class; TaOPCGraphicDataLink = class (TaCustomDataLink) private fOPCSource: TaCustomOPCDataObject; procedure SetOPCSource(const Value: TaCustomOPCDataObject); protected public property OPCSource : TaCustomOPCDataObject read fOPCSource write SetOPCSource; constructor Create(aControl : TObject);override; destructor Destroy; override; end; TaDCRangesCheckResult = ( rcrOk = 0 , rcrWarnLowLevel = 1 , rcrWarnHighLevel = 2 , rcrAlarmLowLevel = 3 , rcrAlarmHighLevel = 4 , rcrConvertError = 5 ); TaDCRanges = class(TPersistent) private FWarnLowLevel: Double; FAlarmHighLevel: Double; FWarnHighLevel: Double; FAlarmLowLevel: Double; FEnable: Boolean; procedure SetAlarmHighLevel(const Value: Double); procedure SetAlarmLowLevel(const Value: Double); procedure SetWarnHighLevel(const Value: Double); procedure SetWarnLowLevel(const Value: Double); procedure SetEnable(const Value: Boolean); protected procedure AssignTo(Dest: TPersistent); override; published function Check(aValue: string): TaDCRangesCheckResult; property WarnLowLevel: Double read FWarnLowLevel write SetWarnLowLevel; property WarnHighLevel: Double read FWarnHighLevel write SetWarnHighLevel; property AlarmLowLevel: Double read FAlarmLowLevel write SetAlarmLowLevel; property AlarmHighLevel: Double read FAlarmHighLevel write SetAlarmHighLevel; property Enable: Boolean read FEnable write SetEnable default False; end; TaCustomOPCDataObject = class {(TDrawObject)}(TGraphicControl) private FDragImages: TDragImageList; fDataLink: TaOPCDataLink; fGraphicDataLink: TaOPCGraphicDataLink; //FStairsOptions : TOPCStairsOptionsSet; FOnChange: TNotifyEvent; FInteractive: boolean; FMouseInSide: boolean; FOnMouseEnter: TNotifyEvent; FOnMouseLeave: TNotifyEvent; FHints: TStrings; FErrorHint: string; FParams: TStrings; FValueHint: string; FRanges: TaDCRanges; procedure SetInteractive(const Value: boolean); procedure SetGraphicOPCSource(const Value: TaCustomOPCDataObject); function GetOPCSource: TaCustomOPCSource; function GetGraphicOPCSource: TaCustomOPCDataObject; function GetErrorCode: integer; function GetErrorString: string; function GetPhysID: TPhysID; function GetDataLink: TaCustomDataLink; procedure AddDataLink(DataLink: TaOPCGraphicDataLink); procedure RemoveDataLink(DataLink: TaOPCGraphicDataLink); function GetStairsOptions: TDCStairsOptionsSet; procedure SetStairsOptions(const Value: TDCStairsOptionsSet); function GetMoment: TDateTime; function GetUpdateOnChangeMoment: boolean; procedure SetUpdateOnChangeMoment(const Value: boolean); procedure SetHints(const Value: TStrings); procedure SetParams(const Value: TStrings); procedure SetErrorHint(const Value: string); procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure SetValueHint(const Value: string); procedure SetErrorCode(const Value: integer); procedure SetErrorString(const Value: string); procedure SetRanges(const Value: TaDCRanges); protected Scale : extended; FDataLinks: TList; function CalcHint: string; function StoredValue: boolean; virtual; procedure UpdateOriginalPosition; virtual; procedure DoMouseEnter;virtual; procedure DoMouseLeave;virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; function GetDragImages: TDragImageList; override; procedure SetPhysID(const Value: TPhysID);virtual; procedure SetOPCSource(const Value: TaCustomOPCSource);virtual; function GetValue:string;virtual; procedure SetValue(const Value: string);virtual; procedure Loaded; override; procedure ChangeScale(M, D: Integer); override; procedure UpdateDataLinks; virtual; procedure ChangeData(Sender:TObject);virtual; procedure RepaintRequest(Sender:TObject);virtual; property Interactive:boolean read FInteractive write SetInteractive default false; property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; public OriginalLeft,OriginalTop,OriginalWidth,OriginalHeight:integer; OriginalFontSize:Integer; FMouseDownX, FMouseDownY: Integer; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; function IsActive:boolean;virtual; property DataLink : TaCustomDataLink read GetDataLink; constructor Create(aOwner : TComponent);override; destructor Destroy; override; property MouseInside: boolean read FMouseInSide; property Moment : TDateTime read GetMoment; published property OnChange: TNotifyEvent read FOnChange write FOnChange; // публикуем события родителя property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property PopupMenu; property Visible; property ShowHint; property Enabled; property Anchors; property OPCSource : TaCustomOPCSource read GetOPCSource write SetOPCSource; property GraphicOPCSource : TaCustomOPCDataObject read GetGraphicOPCSource write SetGraphicOPCSource; property UpdateOnChangeMoment : boolean read GetUpdateOnChangeMoment write SetUpdateOnChangeMoment default False; property StairsOptions : TDCStairsOptionsSet read GetStairsOptions write SetStairsOptions default []; property Value : string read GetValue write SetValue; // stored StoredValue; property PhysID : TPhysID read GetPhysID write SetPhysID; property ErrorCode : integer read GetErrorCode write SetErrorCode default 0;// stored false; property ErrorString : string read GetErrorString write SetErrorString;// stored false; property Hints: TStrings read FHints write SetHints; property ErrorHint: string read FErrorHint write SetErrorHint; property ValueHint: string read FValueHint write SetValueHint; property Params: TStrings read FParams write SetParams; property Ranges: TaDCRanges read FRanges write SetRanges; end; TaOPCDataObject = class (TaCustomOPCDataObject) private fColorNotActive: TColor; fColorActive: TColor; procedure SetColorActive(const Value: TColor); procedure SetColorNotActive(const Value: TColor); function GetActive: boolean; procedure SetActive(const Value: boolean); protected public published property ColorActive : TColor read fColorActive write SetColorActive default clBlue; property ColorNotActive : TColor read fColorNotActive write SetColorNotActive default clBlack; property Active : boolean read GetActive write SetActive stored false; end; implementation uses Math; { TaCustomOPCDataObject } constructor TaCustomOPCDataObject.Create(aOwner: TComponent); begin inherited; FInteractive := false; FDataLinks:=TList.Create; FDataLink := TaOPCDataLink.Create(Self); FDataLink.OnChangeData := ChangeData; FDataLink.StairsOptions := []; FGraphicDataLink := TaOPCGraphicDataLink.Create(Self); FGraphicDataLink.OnChangeData := ChangeData; FHints := TStringList.Create; FParams := TStringList.Create; FRanges := TaDCRanges.Create; end; destructor TaCustomOPCDataObject.Destroy; begin FOnChange := nil; OPCSource := nil; GraphicOPCSource := nil; FreeAndNil(FDataLink); FreeAndNil(FGraphicDataLink); while FDataLinks.Count > 0 do RemoveDataLink(FDataLinks.Last); FreeAndNil(FDataLinks); FreeAndNil(FDragImages); FreeAndNil(FHints); FreeAndNil(FParams); FreeAndNil(FRanges); inherited; end; procedure TaCustomOPCDataObject.DoMouseEnter; begin end; procedure TaCustomOPCDataObject.DoMouseLeave; begin end; function TaCustomOPCDataObject.GetErrorCode: integer; begin Result := DataLink.ErrorCode; end; function TaCustomOPCDataObject.GetErrorString: string; begin Result := DataLink.ErrorString; end; function TaCustomOPCDataObject.GetPhysID: TPhysID; begin Result := DataLink.PhysID; end; function TaCustomOPCDataObject.GetValue: string; begin Result := DataLink.Value; end; function TaCustomOPCDataObject.GetOPCSource: TaCustomOPCSource; begin Result := fDataLink.OPCSource; end; procedure TaCustomOPCDataObject.SetParams(const Value: TStrings); begin FParams.Assign(Value); end; procedure TaCustomOPCDataObject.SetPhysID(const Value: TPhysID); begin fDataLink.PhysID := Value; fGraphicDataLink.PhysID := Value; end; procedure TaCustomOPCDataObject.SetRanges(const Value: TaDCRanges); begin FRanges.AssignTo(Value); end; procedure TaCustomOPCDataObject.SetValue(const Value: string); begin if DataLink.Value <> Value then DataLink.Value := Value; end; procedure TaCustomOPCDataObject.SetValueHint(const Value: string); begin if FValueHint <> Value then begin FValueHint := Value; Hint := CalcHint; end; end; function TaCustomOPCDataObject.StoredValue: boolean; begin // сохраняем значение только если // (не задан источник данных или адрес) // и (не задан графический источник данных) Result := (not Assigned(OPCSource) or not (PhysID <> '')) and not Assigned(GraphicOPCSource); end; procedure TaCustomOPCDataObject.SetOPCSource(const Value: TaCustomOPCSource); begin if fDataLink.OPCSource <> Value then fDataLink.OPCSource := Value; if Value<>nil then fGraphicDataLink.OPCSource := nil; end; function TaCustomOPCDataObject.CalcHint: string; var i: integer; v: extended; Key, LastKey : extended; IsFound: boolean; begin Result := ''; if (ErrorHint <> '') and (ErrorString <> '') then Result := Format(ErrorHint,[ErrorString]) else if (ValueHint <> '') then begin if Pos('%s', ValueHint) > 0 then Result := Format(ValueHint, [Value]) else Result := ValueHint; end else if Hints.Count > 0 then begin try // если есть однозначное соответствие - возвращаем его i := Hints.IndexOfName(Value); if i >= 0 then begin Result := Hints.ValueFromIndex[i]; exit; end; // иначе ищем промежуточное значение //(записи должны быть упорядочены) //TStringList(Hints).Sorted := true; v := StrToFloat(Value); LastKey := StrToFloat(FHints.Names[0]); IsFound := false; for i:=1 to FHints.Count-1 do begin try Key := StrToFloat(FHints.Names[i]); if (LastKey >= Key) then begin IsFound := true; Result := 'значения для отображения подсказок должны быть отсортированы в порядке возрастания'; break; end; if (LastKey <= v) and (v < Key) then begin IsFound := true; Result := FHints.ValueFromIndex[i-1]; break; end; LastKey := Key; except on e:exception do; end; end; if (not IsFound) and (v >= LastKey) then Result := FHints.ValueFromIndex[FHints.Count-1]; except on e:exception do; end; end; // else // Result := Hint; end; procedure TaCustomOPCDataObject.ChangeData(Sender: TObject); begin UpdateDataLinks; Hint := CalcHint; if Assigned(FOnChange) and (not (csLoading in ComponentState)) and (not (csDestroying in ComponentState)) then FOnChange(Self); RepaintRequest(self); end; function TaCustomOPCDataObject.GetGraphicOPCSource: TaCustomOPCDataObject; begin Result := fGraphicDataLink.OPCSource; end; procedure TaCustomOPCDataObject.SetGraphicOPCSource( const Value: TaCustomOPCDataObject); begin if fGraphicDataLink.OPCSource <> Value then begin fGraphicDataLink.OPCSource := Value; if Assigned(fGraphicDataLink.OPCSource) then fGraphicDataLink.Value := fGraphicDataLink.OPCSource.Value; end; if Value <> nil then fDataLink.OPCSource := nil; end; procedure TaCustomOPCDataObject.SetHints(const Value: TStrings); begin FHints.Assign(Value); //TStringList(FHints).Sort; Hint := CalcHint; end; procedure TaCustomOPCDataObject.SetInteractive(const Value: boolean); begin FInteractive := Value; end; function TaCustomOPCDataObject.GetDataLink: TaCustomDataLink; begin if GraphicOPCSource<>nil then Result := fGraphicDataLink else Result := fDataLink; end; function TaCustomOPCDataObject.GetDragImages: TDragImageList; var i: integer; B: TBitmap; // aCanvas: TCanvas; begin if not Assigned(FDragImages) then FDragImages := TDragImageList.Create(nil); Result := FDragImages; Result.Clear; B := TBitmap.Create; try B.Height := Height ; B.Width := Width; B.Canvas.Brush.Color := clLime; //B.Canvas.Rectangle(B.Canvas.ClipRect); //B.Canvas.FillRect(B.Canvas.ClipRect); B.Canvas.CopyRect(Rect(0,0,Width,Height),Canvas,Rect(0,0,Width,Height)); //B.Canvas.Rectangle(0,0,Width,Height); Result.Width := B.Width; Result.Height := B.Height; i:= Result.AddMasked(B, clLime); Result.SetDragImage(i, FMouseDownX, FMouseDownY); finally B.Free; end end; procedure TaCustomOPCDataObject.AddDataLink(DataLink:TaOPCGraphicDataLink); begin FDataLinks.Add(DataLink); DataLink.fOPCSource := Self; end; procedure TaCustomOPCDataObject.RemoveDataLink(DataLink: TaOPCGraphicDataLink); begin DataLink.fOPCSource := nil; FDataLinks.Remove(DataLink); end; procedure TaCustomOPCDataObject.RepaintRequest(Sender: TObject); begin Invalidate; end; function TaCustomOPCDataObject.GetStairsOptions: TDCStairsOptionsSet; begin if GraphicOPCSource <> nil then Result := GraphicOPCSource.StairsOptions else Result := DataLink.StairsOptions; end; procedure TaCustomOPCDataObject.SetStairsOptions(const Value: TDCStairsOptionsSet); begin if GraphicOPCSource <> nil then GraphicOPCSource.StairsOptions := Value else FDataLink.StairsOptions := Value; end; procedure TaCustomOPCDataObject.UpdateDataLinks; var i: Integer; IsChanged:boolean; CrackDataLink:TaOPCGraphicDataLink; begin for I := 0 to FDataLinks.Count - 1 do begin CrackDataLink := TaOPCGraphicDataLink(FDataLinks.Items[i]); IsChanged:=(CrackDataLink.fValue<>Value) or (CrackDataLink.fErrorCode<>ErrorCode) or (CrackDataLink.fErrorString<>ErrorString); if IsChanged then begin CrackDataLink.fValue := Value; CrackDataLink.fErrorCode := ErrorCode; CrackDataLink.fErrorString := ErrorString; CrackDataLink.ChangeData; end; end; end; function TaCustomOPCDataObject.IsActive: boolean; begin Result := not ((Value='0') or (Value='') or (Pos('FALSE',UpperCase(Value))>0) or (StrToIntDef(Value,0)=0)); end; procedure TaCustomOPCDataObject.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; // if (csLoading in ComponentState) then // UpdateOriginalPosition; end; procedure TaCustomOPCDataObject.SetErrorCode(const Value: integer); begin DataLink.ErrorCode := Value; end; procedure TaCustomOPCDataObject.SetErrorHint(const Value: string); begin if FErrorHint <> Value then begin FErrorHint := Value; Hint := CalcHint; end; end; procedure TaCustomOPCDataObject.SetErrorString(const Value: string); begin DataLink.ErrorString := Value; end; procedure TaCustomOPCDataObject.UpdateOriginalPosition; begin OriginalLeft := Left; OriginalTop := Top; OriginalWidth := Width; OriginalHeight := Height; OriginalFontSize := Font.Size; Scale := 1; end; procedure TaCustomOPCDataObject.ChangeScale(M, D: Integer); begin { if Name = 'St1' then begin ShowMessageFmt('OriginalLeft = %d; Left = %d; csLoading = %s; csReading = %s', [OriginalLeft,Left,BoolToStr(csLoading in ComponentState), BoolToStr(csReading in ComponentState)]); end; } if M = 0 then exit; if (csLoading in ComponentState) or (OriginalWidth = 0) or (csReading in ComponentState) then begin inherited ChangeScale(M, D); exit; end; if M <> D then begin if SameValue(D/M,Scale,0.001) then begin Scale := 1; SetBounds(OriginalLeft,OriginalTop,OriginalWidth,OriginalHeight); Font.Size := OriginalFontSize; end else begin Scale := Scale * M/D; SetBounds(Round(OriginalLeft*Scale),Round(OriginalTop*Scale), Round(OriginalWidth*Scale),Round(OriginalHeight*Scale)); Font.Size := Round(OriginalFontSize*Scale); end; // if not ParentFont then // Font.Size := MulDiv(Font.Size, M, D); end; end; procedure TaCustomOPCDataObject.CMMouseEnter(var Message: TMessage); begin FMouseInSide := true; DoMouseEnter; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TaCustomOPCDataObject.CMMouseLeave(var Message: TMessage); begin FMouseInSide := false; DoMouseLeave; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; function TaCustomOPCDataObject.GetMoment: TDateTime; begin Result:=fDataLink.Moment; end; procedure TaCustomOPCDataObject.Loaded; begin inherited; UpdateOriginalPosition; end; procedure TaCustomOPCDataObject.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FMouseDownX := X; FMouseDownY := Y; inherited; end; function TaCustomOPCDataObject.GetUpdateOnChangeMoment: boolean; begin Result := DataLink.UpdateOnChangeMoment; end; procedure TaCustomOPCDataObject.SetUpdateOnChangeMoment( const Value: boolean); begin DataLink.UpdateOnChangeMoment := Value; end; { TaOPCDataObject } procedure TaOPCDataObject.SetActive(const Value: boolean); begin if Value then Self.Value:='1' else Self.Value:='0'; end; function TaOPCDataObject.GetActive: boolean; begin Result:=IsActive; end; procedure TaOPCDataObject.SetColorActive(const Value: TColor); begin if fColorActive<>Value then begin fColorActive := Value; RepaintRequest(self); end; end; procedure TaOPCDataObject.SetColorNotActive(const Value: TColor); begin if fColorNotActive<>Value then begin fColorNotActive := Value; RepaintRequest(self); end; end; { TaOPCGraphicDataLink } constructor TaOPCGraphicDataLink.Create(aControl: TObject); begin inherited; OPCSource := nil; end; destructor TaOPCGraphicDataLink.Destroy; begin OPCSource := nil; inherited; end; procedure TaOPCGraphicDataLink.SetOPCSource( const Value: TaCustomOPCDataObject); begin if (fOPCSource <> Value) and (Control <> Value) then begin if fOPCSource<>nil then fOPCSource.RemoveDataLink(Self); if Value<>nil then Value.AddDataLink(self); end; end; { TaDCRanges } procedure TaDCRanges.AssignTo(Dest: TPersistent); var d: TaDCRanges; begin if not (Dest is TaDCRanges) then begin inherited AssignTo(Dest); end else begin d := TaDCRanges(Dest); d.WarnLowLevel := WarnLowLevel; d.WarnHighLevel := WarnHighLevel; d.AlarmLowLevel := AlarmLowLevel; d.AlarmHighLevel := AlarmHighLevel; end; end; function TaDCRanges.Check(aValue: string): TaDCRangesCheckResult; var v: Double; begin // проверка выключена - выходим if not Enable then Exit(rcrOk); // об ошибках конвертации сообщаем if not TryStrToFloat(aValue, v) then Exit(rcrConvertError); // вначале проверяем аварийные пределы if v < AlarmLowLevel then Exit(rcrAlarmLowLevel); if v > AlarmHighLevel then Exit(rcrAlarmHighLevel); // аварий нет - проверяем предупреждения if v < WarnLowLevel then Exit(rcrWarnLowLevel); if v > WarnHighLevel then Exit(rcrWarnHighLevel); // прошли все проверки - порядок Result := rcrOk;; end; procedure TaDCRanges.SetAlarmHighLevel(const Value: Double); begin FAlarmHighLevel := Value; end; procedure TaDCRanges.SetAlarmLowLevel(const Value: Double); begin FAlarmLowLevel := Value; end; procedure TaDCRanges.SetEnable(const Value: Boolean); begin FEnable := Value; end; procedure TaDCRanges.SetWarnHighLevel(const Value: Double); begin FWarnHighLevel := Value; end; procedure TaDCRanges.SetWarnLowLevel(const Value: Double); begin FWarnLowLevel := Value; end; end.
unit controller.settings; {$mode delphi} interface uses Classes, SysUtils; type TAuthSvcActions = (aaAuth, aaValidate, aaLookup); const AUTH_ROUTE = 'controller/auth'; AUTH_ACTION_AUTH = '?a=authenticate'; AUTH_ACTION_VALIDATE = '?a=validate'; AUTH_ACTION_LOOKUP = '?a=lookup'; var //root IP address set by config AUTH_ADDRESS : String; function GetAuthSvcRoute(const AType : TAuthSvcActions) : String; implementation function GetAuthSvcRoute(const AType: TAuthSvcActions): String; begin case AType of aaAuth : Result := AUTH_ADDRESS + AUTH_ROUTE + AUTH_ACTION_AUTH; aaValidate : Result := AUTH_ADDRESS + AUTH_ROUTE + AUTH_ACTION_VALIDATE; aaLookup : Result := AUTH_ADDRESS + AUTH_ROUTE + AUTH_ACTION_LOOKUP; end; end; end.
unit Compute.Test; interface procedure RunTests; implementation uses System.SysUtils, System.DateUtils, Compute, Compute.Functions; function ReferenceTransform(const Input: TArray<double>): TArray<double>; var i: integer; x: double; begin SetLength(result, Length(input)); for i := 0 to High(input) do begin x := input[i]; result[i] := (1 / 256) * (((((46189 * x * x) - 109395) * x * x + 90090) * x * x - 30030) * x * x + 3465) * x * x - 63; end; end; function CompareOutputs(const data1, data2: TArray<double>): boolean; var i: integer; err: double; begin result := False; for i := 0 to High(data1) do begin err := Abs(data1[i] - data2[i]); if (err > 1e-6) then exit; end; result := True; end; procedure AsyncTransformTest; var st: TDateTime; i: integer; input, output, outputRef: TArray<double>; f: IFuture<TArray<double>>; P10: Expr; begin // load OpenCL platform InitializeCompute; // initialize input SetLength(input, 50000000); // input values are in [-1, 1] for i := 0 to High(input) do input[i] := 2 * i / High(input) - 1; WriteLn('start compute'); st := Now; // Legendre polynomial P_n(x) for n = 10 P10 := (1 / 256) * (((((46189 * _1*_1) - 109395) * _1*_1 + 90090) * _1*_1 - 30030) * _1*_1 + 3465) * _1*_1 - 63; // computes output[i] := P10(input[i]) // by default it tries to select a GPU device // so this can run async while the CPU does other things f := Compute.AsyncTransform(input, P10); // wait for computations to finish f.Wait; // and get the result output := f.Value; WriteLn(Format('done compute, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000])); WriteLn('start reference'); st := Now; outputRef := ReferenceTransform(input); WriteLn(Format('done reference, %.3f seconds', [MilliSecondsBetween(Now, st) / 1000])); if CompareOutputs(output, outputRef) then WriteLn('data matches') else WriteLn('======== DATA DIFFERS ========'); end; procedure RunTests; begin AsyncTransformTest; end; end.
unit uFrmCadCurso; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CheckLst, uCurso, Vcl.Mask, uSalaDAO, FireDac.Comp.client, ucursoDAO; type TFrmNovoCurso = class(TForm) EdtNome: TEdit; CLSalas: TCheckListBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; BtnCadastroCurso: TButton; BtnCancelar: TButton; Label4: TLabel; EdtPreco: TEdit; procedure FormCreate(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); procedure CriaCL(pQuery: TFDQuery); procedure BtnCadastroCursoClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private Procedure CreateCurso; public { Public declarations } end; var FrmNovoCurso: TFrmNovoCurso; Curso: TCurso; SalaDAO: TSalaDAO; CursoDAO: TcursoDAO; implementation {$R *.dfm} { TForm2 } procedure TFrmNovoCurso.BtnCadastroCursoClick(Sender: TObject); var I: Integer; begin CreateCurso; if CursoDAO.CadastraCurso(Curso) = true then begin if SalaDAO.CadastroCurso_sala(Curso) = false then begin showmessage('Erro ao cadastrar salas do curso'); abort end; MessageDlg('Curso cadastrado com sucesso', mtConfirmation, [mbok], 0); EdtNome.Clear; EdtPreco.Clear; for I := 0 to CLSalas.Count-1 do if CLSalas.State[i] = cbChecked then CLSalas.State[i] := cbUnchecked; FrmNovoCurso.Close; end else begin MessageDlg('Erro ao Cadastrar curso', mtError, [mbok], 0); EdtNome.SetFocus; abort; end; end; procedure TFrmNovoCurso.BtnCancelarClick(Sender: TObject); begin FrmNovoCurso.Close end; procedure TFrmNovoCurso.CreateCurso; var I, count: Integer; begin try if EdtNome.Text = '' then begin ShowMessage('Erro ao Cadastrar curso' + #13 + #13 + 'Certifique-se de preencher todos os campos'); abort end; count := 0; Curso := TCurso.Create; Curso.Nome := LowerCase(EdtNome.Text); Curso.Preco := StrToFloat(EdtPreco.Text); for I := 0 to CLSalas.Items.count - 1 do begin if CLSalas.State[I] = cbChecked then begin Curso.salas[count] := CLSalas.Items[I]; count := count + 1 end; end; if count = 0 then begin ShowMessage('Erro ao cadastrar curso' + #13 + #13 + 'Certifique-se de preencher todos os campos'); abort end; except ShowMessage('Erro ao Cadastrar curso' + #13 + #13 + 'Certifique-se de preencher todos os campos'); abort; end; Curso.Preco := StrToFloat(EdtPreco.Text); end; procedure TFrmNovoCurso.CriaCL(pQuery: TFDQuery); begin CLSalas.Clear; while not pQuery.Eof do begin CLSalas.Items.Add(pQuery.FieldByName('nome').AsString); pQuery.Next; end; end; procedure TFrmNovoCurso.FormCreate(Sender: TObject); begin left := (Screen.Width - Width) div 2; top := (Screen.Height - Height) div 2; SalaDAO := TSalaDAO.Create; CriaCL(SalaDAO.ListaSala); CursoDAO := TcursoDAO.Create; end; procedure TFrmNovoCurso.FormDestroy(Sender: TObject); begin try if Assigned(SalaDAO) then FreeAndNil(SalaDAO); if Assigned(CursoDAO) then FreeAndNil(CursoDAO); if Assigned(Curso) then FreeAndNil(Curso); except on e: exception do raise exception.Create(e.Message); end; end; end.
unit COMPortChooseFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, CheckLst, StdCtrls, LoggerItf, MBRTUMasterDispatcherTypes, COMPortInfoObj,COMPortParamTypes; type { TframCoosePort } TframCoosePort = class(TFrame) btnAply : TButton; btnCancel : TButton; gbPort : TGroupBox; chlPortList : TCheckListBox; btnPortListUpdate : TButton; gbPortParams : TGroupBox; lbPortBaudRate : TLabel; cbPortBaudRate : TComboBox; lbPortDataBits : TLabel; cbPortDataBits : TComboBox; lbPortStopBits : TLabel; cbPortStopBits : TComboBox; lbPortParity : TLabel; cbPortParity : TComboBox; lbPortList : TLabel; procedure btnAplyClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure btnPortListUpdateClick(Sender: TObject); procedure cbPortBaudRateChange(Sender: TObject); procedure cbPortDataBitsChange(Sender: TObject); procedure cbPortParityChange(Sender: TObject); procedure cbPortStopBitsChange(Sender: TObject); procedure chlPortListClickCheck(Sender: TObject); private FLogger : IDLogger; FOnCancelPort : TNotifyEvent; FOnSelectPort : TNotifyEvent; FPortParams : TMBDispPortParam; FPortsIfoObj : TCOMMPortInfoList; procedure OnFoundDevProc(Sender : TObject; APortInfo : TCOMMPortInfo); procedure OnLostDevProc(Sender : TObject; APortInfo : TCOMMPortInfo); procedure OnChangeDevProc(Sender : TObject; APortInfo : TCOMMPortInfo); procedure SetLogger(AValue: IDLogger); procedure SetPortParams(AValue: TMBDispPortParam); function SearchIndexOfPort(APortName : String): Integer; procedure UncheckOther(ACheckedIndex : Integer); procedure SetPortParamData(APortIndex : Integer); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure UpdatePortsList; procedure UpdatePortsStatus; property Logger : IDLogger read FLogger write SetLogger; property SelectedPortParams : TMBDispPortParam read FPortParams write SetPortParams; property OnSelectPort : TNotifyEvent read FOnSelectPort write FOnSelectPort; property OnCancelPort : TNotifyEvent read FOnCancelPort write FOnCancelPort; end; implementation {$R *.frm} uses COMPortResStr, COMPortConsts, Localize; { TframCoosePort } constructor TframCoosePort.Create(AOwner: TComponent); var i, TempLen : Integer; begin inherited Create(AOwner); TranslateAppObject(Self); TempLen := Length(ComPortBaudRateNames) - 2; for i := 0 to TempLen do cbPortBaudRate.AddItem(ComPortBaudRateNames[TComPortBaudRate(i)],nil); cbPortBaudRate.ItemIndex := Integer(br9600); TempLen := Length(ComPortDataBitsNames) - 2; for i := 0 to TempLen do cbPortDataBits.AddItem(ComPortDataBitsNames[TComPortDataBits(i)],nil); cbPortDataBits.ItemIndex := Integer(db8BITS); TempLen := Length(ComPortStopBitsNames) - 2; for i := 0 to TempLen do cbPortStopBits.AddItem(ComPortStopBitsNames[TComPortStopBits(i)],nil); cbPortStopBits.ItemIndex := Integer(sb1BITS); TempLen := Length(ComPortParityEngNames) - 2; for i := 0 to TempLen do cbPortParity.AddItem(ComPortParityEngNames[TComPortParity(i)],nil); cbPortParity.ItemIndex := Integer(ptEVEN); {$IFDEF LINUX} FPortParams.PortNum := 0; FPortParams.PortPrefix := csLinuxCOMMPrefix0; {$ENDIF} {$IFDEF WINDOWS} FPortParams.PortNum := 1; FPortParams.PortPrefix := csWindowsCOMMPrefix; {$ENDIF} FPortParams.BaudRate := br9600; FPortParams.DataBits := db8BITS; FPortParams.StopBits := sb1BITS; FPortParams.Parity := ptEVEN; FPortsIfoObj := TCOMMPortInfoList.Create; FPortsIfoObj.OnFoundNewDevice := @OnFoundDevProc; FPortsIfoObj.OnLostDevice := @OnLostDevProc; FPortsIfoObj.OnChangeDeviceStatus := @OnChangeDevProc; FPortsIfoObj.UpdeteDeviceList; end; destructor TframCoosePort.Destroy; begin FreeAndNil(FPortsIfoObj); inherited Destroy; end; procedure TframCoosePort.UpdatePortsList; begin FPortsIfoObj.UpdeteDeviceList; end; procedure TframCoosePort.UpdatePortsStatus; begin FPortsIfoObj.UpdateAllStatus; end; procedure TframCoosePort.chlPortListClickCheck(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; UncheckOther(TempIndex); if chlPortList.Checked[TempIndex] then btnAply.Enabled := True else btnAply.Enabled := False; SetPortParamData(TempIndex); end; procedure TframCoosePort.btnPortListUpdateClick(Sender: TObject); begin FPortsIfoObj.UpdeteDeviceList; end; procedure TframCoosePort.cbPortBaudRateChange(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; if not chlPortList.ItemEnabled[TempIndex] then Exit; FPortParams.BaudRate := TComPortBaudRate(cbPortBaudRate.ItemIndex); btnAply.Enabled := True; end; procedure TframCoosePort.cbPortDataBitsChange(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; if not chlPortList.ItemEnabled[TempIndex] then Exit; FPortParams.DataBits := TComPortDataBits(cbPortDataBits.ItemIndex); btnAply.Enabled := True; end; procedure TframCoosePort.cbPortParityChange(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; if not chlPortList.ItemEnabled[TempIndex] then Exit; FPortParams.Parity := TComPortParity(cbPortParity.ItemIndex); btnAply.Enabled := True; end; procedure TframCoosePort.cbPortStopBitsChange(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; if not chlPortList.ItemEnabled[TempIndex] then Exit; FPortParams.StopBits := TComPortStopBits(cbPortStopBits.ItemIndex); btnAply.Enabled := True; end; procedure TframCoosePort.btnAplyClick(Sender: TObject); var TempIndex : Integer; begin TempIndex := chlPortList.ItemIndex; if not chlPortList.ItemEnabled[TempIndex] then Exit; SetPortParamData(TempIndex); if Assigned(FOnSelectPort) then FOnSelectPort(Self); end; procedure TframCoosePort.btnCancelClick(Sender: TObject); begin if Assigned(FOnCancelPort) then FOnCancelPort(Self); end; procedure TframCoosePort.OnFoundDevProc(Sender: TObject; APortInfo: TCOMMPortInfo); var TempIndex : Integer; begin TempIndex := chlPortList.Items.AddObject(Format('%s - %s',[APortInfo.Name,rsCOMString4]),APortInfo); chlPortList.ItemEnabled[TempIndex] := APortInfo.IsExist; end; procedure TframCoosePort.OnLostDevProc(Sender: TObject; APortInfo: TCOMMPortInfo); var TempIndex : Integer; begin TempIndex := SearchIndexOfPort(APortInfo.Name); if TempIndex = -1 then Exit; chlPortList.Items.Objects[TempIndex] := nil; if TempIndex = chlPortList.ItemIndex then chlPortList.ItemIndex := 0; if chlPortList.Checked[TempIndex] then chlPortList.Checked[0] := True; chlPortList.Items.Delete(TempIndex); end; procedure TframCoosePort.OnChangeDevProc(Sender: TObject; APortInfo: TCOMMPortInfo); var TempIndex : Integer; begin TempIndex := SearchIndexOfPort(APortInfo.Name); if TempIndex = -1 then Exit; if APortInfo.IsExist then begin if APortInfo.IsAvailable then begin // свободен chlPortList.Items.Strings[TempIndex] := Format('%s - %s',[APortInfo.Name,rsCOMString2]); end else begin // занят chlPortList.Items.Strings[TempIndex] := Format('%s - %s',[APortInfo.Name,rsCOMString5]); end; end else begin // отсутствует chlPortList.Items.Strings[TempIndex] := Format('%s - %s',[APortInfo.Name,rsCOMString4]); end; chlPortList.ItemEnabled[TempIndex] := APortInfo.IsAvailable; end; procedure TframCoosePort.SetLogger(AValue: IDLogger); begin if FLogger = AValue then Exit; FLogger := AValue; FPortsIfoObj.Logger := FLogger; end; procedure TframCoosePort.SetPortParams(AValue: TMBDispPortParam); var TempIndex : Integer; TempName : String; begin FPortParams := AValue; TempName := Format('%s%d',[FPortParams.PortPrefix,FPortParams.PortNum]); TempIndex := SearchIndexOfPort(TempName); if TempIndex = -1 then Exit; UncheckOther(TempIndex); chlPortList.ItemIndex := TempIndex; chlPortList.Checked[TempIndex] := True; cbPortBaudRate.ItemIndex := Integer(FPortParams.BaudRate); cbPortDataBits.ItemIndex := Integer(FPortParams.DataBits); cbPortStopBits.ItemIndex := Integer(FPortParams.StopBits); cbPortParity.ItemIndex := Integer(FPortParams.Parity); end; function TframCoosePort.SearchIndexOfPort(APortName: String): Integer; var Res, i, Count : Integer; begin Result := -1; Count := chlPortList.Items.Count-1; for i := 0 to Count do begin Res:= pos(APortName,chlPortList.Items.Strings[i]); if Res > 0 then begin Result := i; Break; end; end; end; procedure TframCoosePort.UncheckOther(ACheckedIndex: Integer); var i, Count : Integer; begin Count := chlPortList.Count-1; for i:= 0 to Count do begin if i = ACheckedIndex then Continue; chlPortList.Checked[i] := False; end; end; procedure TframCoosePort.SetPortParamData(APortIndex: Integer); begin FPortParams.PortNum := TCOMMPortInfo(chlPortList.Items.Objects[APortIndex]).Num; FPortParams.PortPrefix := TCOMMPortInfo(chlPortList.Items.Objects[APortIndex]).Prefix; FPortParams.BaudRate := TComPortBaudRate(cbPortBaudRate.ItemIndex); FPortParams.DataBits := TComPortDataBits(cbPortDataBits.ItemIndex); FPortParams.StopBits := TComPortStopBits(cbPortStopBits.ItemIndex); FPortParams.Parity := TComPortParity(cbPortParity.ItemIndex); end; end.
{ Change FormID load order of selected records. Built-in xEdit function "Change FormID" available in menu assigns new formid, this script only changes load order part of formid. } unit UserScript; var NewLoadOrder: Cardinal; function Initialize: integer; var s: string; begin // set this to predefined value if you don't want the script to prompt you NewLoadOrder := -1; if NewLoadOrder = -1 then begin Result := 1; if not InputQuery('Enter', 'New hexadecimal load order', s) then Exit; if s = '' then Exit; NewLoadOrder := StrToInt64('$' + s); end; Result := 0; end; function Process(e: IInterface): integer; var OldFormID, NewFormID: Cardinal; m: IInterface; begin Result := 0; // file header doesn't have formid if Signature(e) = 'TES4' then Exit; OldFormID := GetLoadOrderFormID(e); // clear load order byte in oldformid and set new load order in high byte (shifted left by 24 bits) NewFormID := (OldFormID and $00FFFFFF) + (NewLoadOrder shl 24); if NewFormID = OldFormID then Exit; // here we shoud check for availability of NewFormID, but it will generate error and abort anyway if that happens // ... //AddMessage(Format('Changing FormID from [%s] to [%s] on %s', [IntToHex64(OldFormID, 8), IntToHex64(NewFormID, 8), Name(e)])); // the record in question might originate from master file m := MasterOrSelf(e); // skip overridden records, don't know what to do with them for now if not Equals(m, e) then Exit; // first change formid of references while ReferencedByCount(m) > 0 do CompareExchangeFormID(ReferencedByIndex(m, 0), OldFormID, NewFormID); // change formid of record SetLoadOrderFormID(e, NewFormID); end; end.
unit URepositorioMaterial; interface uses UMaterial , UEntidade , URepositorioDB , SqlExpr ; type TRepositorioMaterial = class (TRepositorioDB<TMATERIAL>) public constructor Create; procedure AtribuiDBParaEntidade (const coMATERIAL: TMATERIAL); override; procedure AtribuiEntidadeParaDB (const coMATERIAL: TMATERIAL; const coSQLQuery: TSQLQuery); override; end; implementation uses UDM , Math ; {TRepositorioMaterial} constructor TRepositorioMaterial.Create; begin inherited Create (TMATERIAL, TBL_MATERIAL, FLD_ENTIDADE_ID, STR_MATERIAL); end; procedure TRepositorioMaterial.AtribuiDBParaEntidade(const coMATERIAL: TMaterial); begin inherited; with FSQLSelect do begin coMATERIAL.DESCRICAO := FieldByName(FLD_MATERIAL_DESCRICAO).AsString; coMATERIAL.VALOR_UNITARIO := RoundTo(FieldByName(FLD_MATERIAL_VALOR_UNITARIO).AsFloat, -2); end; end; procedure TRepositorioMaterial.AtribuiEntidadeParaDB( const coMATERIAL: TMaterial; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_MATERIAL_DESCRICAO).AsString := coMATERIAL.DESCRICAO; ParamByName(FLD_MATERIAL_VALOR_UNITARIO).AsFloat := coMATERIAL.VALOR_UNITARIO; end; end; end.
unit uformula; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics; procedure setCanvas(canva: TCanvas); procedure DrawFormula(); function locateChainAtPos(point: TPoint): boolean; procedure AppendFormula(ch: char); procedure createNewChain(point: TPoint); function ConverttoString(): string; implementation const FONT_NAME = 'Courier New'; type { TFormula } TFormula = class h,w:integer; rect: TRect; font: Tfont; ch: char; next, parent, owner: TFormula; upperIdx: TFormula; function insert(what: char): TFormula; function add(what: char): TFormula; procedure prepareUpperIndex(); procedure upperIndex(); procedure DrawUpperIndex(); function getChainWidth(start: TFormula): integer; procedure wideRectRight(start: TFormula; space: integer); procedure Draw();virtual; function locate(point:TPoint): boolean;virtual; procedure prepare();virtual; constructor create(sym: char); destructor destroy; override; end; { TFormulaChar } TFormulaChar = class (TFormula) procedure prepare();override; procedure Draw();override; function locate(point:TPoint): boolean;override; constructor create(sym: char); end; { TFrac } TFrac = class (TFormula) numerator, denominator: TFormula; procedure prepare();override; procedure Draw();override; function locate(point:TPoint): boolean;override; constructor create(sym: char); end; { TParenthes } { TParenthes = class(TFormula) beginF, endF, value: TFormula; procedure prepare();override; procedure Draw();override; function locate(point:TPoint): boolean;override; constructor create(sym: char); end; } const FORM_INIT_LEN = 100; FONT_SIZE = 16; var fChains: array of Tformula; fix: integer = 0; selectedChain: TFormula = nil; canvas: TCanvas; flUp: boolean = false; flFrac: boolean = false; // используется для уменьшения значения входящих в дробь procedure setCanvas(canva: TCanvas); begin canvas := canva; end; procedure DrawFormula(); var i: integer; n: TFormula; begin i := 0; while assigned(fChains[i]) do begin n := fChains[i]; n.prepare(); n.Draw(); inc(i); end; end; function locateChainStart(from: TFormula): TFormula; begin while assigned(from.parent) do from := from.parent; result := from; end; function locateChainAtPos(point: TPoint): boolean; var i: integer; begin selectedChain := nil; result := false; i := 0; while assigned(fChains[i]) do begin if fChains[i].locate(point) then exit(true); inc(i); end; end; procedure AppendFormula(ch: char); begin if not assigned(selectedChain) then exit; if selectedChain.next = nil then selectedChain := selectedChain.add(ch) else selectedChain := selectedChain.insert(ch); end; procedure createNewChain(point: TPoint); begin if fix = length(fChains) then setLength(fChains, length(fChains) + FORM_INIT_LEN); fChains[fix] := TFormula.Create(#0); with fChains[fix] do begin rect.Top := point.y; rect.Left := point.x; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; end; selectedChain := fChains[fix]; inc(fix); end; function doToString(start: TFormula): string; begin result := ''; while assigned(start) do begin if start is TFormulaChar then begin result += start.ch; if assigned(start.upperIdx) then result += doToString(start.upperIdx); end else if start is TFrac then begin result += doToString(TFrac(start).numerator); result += '/'; result += doToString(TFrac(start).denominator); end; start := start.next; end; end; function ConverttoString: string; var i: integer; n: TFormula; begin result := ''; i := 0; n := fChains[i]; while assigned(n) do begin result += doToString(n) + ';'; inc(i); n := fChains[i]; end; end; { TFormula } function getFontSize():integer; begin result := FONT_SIZE; if flFrac then result := trunc(result / 1.2); if flUp then result := trunc(result / 1.5); end; function TFormula.insert(what: char): TFormula; var f: TFormula; begin case what of '/': begin f := TFrac.create(what); f.parent := self; f.next := next; if assigned(next) then next.parent := f; self.next := f; end; '^': begin upperIndex(); f := upperIdx; end; else begin f := TFormulaChar.create(what); f.parent := self; f.next := next; if assigned(next) then next.parent := f; self.next := f; end; end; result := f; end; function TFormula.add(what: char): TFormula; begin case what of '/': begin next := TFrac.create(what); next.parent := self; next.owner := self.owner; end; '^': begin upperIndex(); exit(upperIdx); end; else begin next := TFormulaChar.Create(what); next.parent := self; next.owner := self.owner; end; end; result := next; end; procedure TFormula.prepareUpperIndex; begin if upperIdx = nil then exit; flUp := true; upperIdx.font.Size := getFontSize(); canvas.Font := upperIdx.font; canvas.GetTextSize(upperIdx.ch, upperIdx.w, upperIdx.h); upperIdx.rect.Bottom := rect.Top; upperIdx.rect.Top := upperIdx.rect.Bottom - upperIdx.h div 2; upperIdx.rect.Left := rect.Right; upperIdx.rect.Right := upperIdx.rect.Left + upperIdx.w; if assigned(upperIdx.next) then upperIdx.next.prepare(); flUp := false; end; procedure TFormula.upperIndex; begin upperIdx := TFormula.create(#0); end; procedure TFormula.DrawUpperIndex; var n: TFormula; begin n := upperIdx; while assigned(n) do begin n.Draw(); n := n.next; end; end; function TFormula.getChainWidth(start: TFormula): integer; begin result := 0; while assigned(start) do begin if (start.ch <> #0) or (start.ch = #0) and (start.next = nil) then result += start.w; //canvas.GetTextWidth(ch); start := start.next; end; end; procedure TFormula.wideRectRight(start: TFormula; space: integer); var n: TFormula; begin if start = nil then exit; n := start; while assigned(n.next) do n := n.next; rect.Right := n.rect.Right + space; end; procedure TFormula.Draw; begin if (self = selectedChain) then begin canvas.Font := font; canvas.Pen.Color := clBlack; canvas.Pen.Width := 1; canvas.Pen.Style := psDot; canvas.Brush.Style:= bsClear; canvas.Rectangle(rect) end else if (ch = #0) and (next = nil) then begin canvas.Font := font; canvas.Pen.Color := clBlack; canvas.Pen.Width := 1; canvas.Pen.Style := psSolid; canvas.Brush.Style:= bsClear; canvas.Rectangle(rect) end; if assigned(next) then next.Draw(); end; function TFormula.locate(point: TPoint): boolean; begin result := (point.y >= rect.Top) and (point.y <= rect.Bottom) and (point.x >= rect.Left) and (point.x <= rect.Right); if result then begin if (ch = #0) and (self.next <> nil) then result := false else begin selectedChain := self; end; end; if not result and assigned(upperIdx) then result := upperIdx.locate(point); if not result and assigned(next) then result := next.locate(point); end; procedure TFormula.prepare; begin if assigned(upperIdx) then upperIdx.prepare(); if assigned(next) then next.prepare(); end; constructor TFormula.create(sym: char); begin owner := nil; parent := nil; next := nil; upperIdx := nil; ch := sym; Font := TFont.Create; Font.Name := FONT_NAME; font.Size := FONT_SIZE; canvas.Font := font; canvas.GetTextSize(ch, w, h); end; destructor TFormula.destroy; begin font.Free; inherited destroy; end; { TFormulaChar } procedure TFormulaChar.prepare; begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); if parent is TFrac then begin rect.Top := parent.rect.Top + (parent.h div 4); end else begin rect.Top := parent.rect.Top; end; if parent.ch = #0 then rect.Left := parent.rect.Left else rect.Left := parent.rect.Right; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; prepareUpperIndex(); wideRectRight(upperIdx, 0); inherited prepare(); end; procedure TFormulaChar.Draw(); begin canvas.Font := font; canvas.Pen.Color := clBlack; canvas.Pen.Width := 1; canvas.Brush.Style:= bsClear; canvas.Pen.Style := psSolid; canvas.TextOut(rect.Left, rect.Top, ch); DrawUpperIndex(); inherited Draw(); end; function TFormulaChar.locate(point: TPoint): boolean; begin result := false; if assigned(upperIdx) then result := upperIdx.locate(point); if not result then result := inherited locate(point); if not result and assigned(next) then result := next.locate(point); end; constructor TFormulaChar.create(sym: char); begin inherited create(sym); end; { TFrac } procedure TFrac.prepare; var nw, dw: integer; begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); h *= 2; if (parent is TFrac) then begin rect.Top := parent.rect.Top end else rect.Top := parent.rect.Top - (h div 4); if parent.ch = #0 then rect.Left := parent.rect.Left else rect.Left := parent.rect.Right; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; flFrac := true; with numerator do begin font.Size := self.font.Size;//trunc(FONT_SIZE / 1.2); canvas.Font := font; canvas.GetTextSize(ch, w, h); rect.Top := self.rect.Top; rect.Left := self.rect.Left; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; prepare(); end; with denominator do begin font.Size := self.font.Size;//trunc(FONT_SIZE / 1.2); w := numerator.w; h := numerator.h; rect.Bottom := self.rect.Bottom; rect.Top := rect.Bottom - h; rect.Left := self.rect.Left; rect.Right := rect.Left + w; prepare(); end; nw := getChainWidth(numerator); dw := getChainWidth(denominator); if dw >= nw then with numerator do begin self.rect.Right := self.rect.Left + dw; self.w := dw; rect.Left := rect.Left + ((dw - nw) div 2); rect.Right := rect.Left + w; prepare(); end else with denominator do begin self.rect.Right := self.rect.Left + nw; self.w := nw; rect.Left := rect.Left + ((nw - dw) div 2); rect.Right := rect.Left + w; prepare(); end; flFrac := false; prepareUpperIndex(); wideRectRight(upperIdx, 0); if assigned(next) then next.prepare() end; procedure TFrac.Draw; var n,d: TFormula; begin canvas.Pen.Color := clBlack; canvas.Pen.Width := 1; canvas.Brush.Style:= bsClear; canvas.Pen.Style := psSolid; canvas.Line(rect.Left, rect.Top - 2 + h div 2, rect.Left + w, rect.Top - 2 + h div 2); n := numerator; d := denominator; while assigned(n) or assigned(d) do begin if assigned(n) then begin n.Draw(); n := n.next; end; if assigned(d) then begin d.Draw(); d := d.next; end; end; DrawUpperIndex(); inherited Draw(); end; function TFrac.locate(point: TPoint): boolean; var n,d: TFormula; begin result := false; n := numerator; d := denominator; if assigned(n) then result := n.locate(point); if not result and assigned(d) then result := d.locate(point); if not result then result := inherited locate(point); if not result and assigned(next) then result := next.locate(point); end; constructor TFrac.create(sym: char); begin inherited create(sym); parent := nil; ch := sym; numerator := TFormula.create(#0); numerator.owner := self; denominator := TFormula.create(#0); denominator.owner := self; end; { TParenthes } { procedure TParenthes.prepare; begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); if parent is TFrac then begin rect.Top := parent.rect.Top + (parent.h div 4); end else begin rect.Top := parent.rect.Top; end; if parent.ch = #0 then rect.Left := parent.rect.Left else rect.Left := parent.rect.Right; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; with beginF do begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); rect.Top := self.rect.Top; rect.Left := self.rect.Left; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; end; with value do begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); rect.Top := beginF.rect.Top; rect.Left := beginF.rect.Right; rect.Right := rect.Left + w; rect.Bottom := rect.Top + h; prepare(); end; wideRectRight(value, 0); with endF do begin font.Size := getFontSize(); canvas.Font := font; canvas.GetTextSize(ch, w, h); rect.Right := self.rect.Right + w; rect.Bottom := self.rect.Bottom; rect.Top := rect.Bottom - h; rect.Left := rect.Right - w; end; wideRectRight(endF, 0); end; procedure TParenthes.Draw; var n: TFormula; begin beginF.Draw(); n := value; while assigned(n) do begin n.Draw(); n := n.next; end; endF.Draw(); DrawUpperIndex(); inherited Draw(); end; function TParenthes.locate(point: TPoint): boolean; begin result := false; if assigned(upperIdx) then result := upperIdx.locate(point); // if not result then result := beginF.locate(point); // if not result then result := endF.locate(point); if not result then result := value.locate(point); if not result then result := inherited locate(point); if not result and assigned(next) then result := next.locate(point); end; constructor TParenthes.create(sym: char); begin inherited create(sym); parent := nil; next := nil; ch := sym; beginF := TFormulaChar.create('('); endF := TFormulaChar.create(')'); value := TFormula.create(#0); end; } initialization setLength(fChains, FORM_INIT_LEN); // Нет поддержки дробей с вложеными дробями //ToDo: Сделать скобки отдельным классом // добавить поле владелец. // Например: дробь, для числ и знамен владелец яв дробь // при добавлении в числ или знамен вызывать проц после добавления владельца // но сначала вызывать собственную,если у владельца есть свой владелец то вызывать его проц, и только затем далее. end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OleCtnrs, StdCtrls, ActiveX, ComObj, ShellAPI, ComCtrls, ExtCtrls; type TForm1 = class(TForm,IDropTarget) Memo1: TMemo; Label1: TLabel; Edit1: TEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Déclarations privées } function DragEnter(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; stdcall; function DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; stdcall; function DragLeave: HResult; stdcall; function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; stdcall; Function GetComponentIndex(pt : TPoint) : Int64; public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.dfm} // Recherche du control se trouvant sous le curseur (Pt contien les coordonées écran du curseur) // Utilisation de la position absolue du composant Function TForm1.GetComponentIndex(pt : TPoint) : Int64; Var C : int64; K : boolean; begin C := Pred(ComponentCount); K := True; Result := -1; while K and (C >= 0) do // on cherche en premier les composants enfant -> comptage en décroissant begin with Tcontrol(Components[C]) do begin if (Pt.X >= ClientOrigin.X)and (Pt.X <= (ClientOrigin.X + Width)) and (Pt.Y >= ClientOrigin.Y) and (Pt.Y <= (ClientOrigin.Y + Height)) then begin result := C; K := False; end; end; dec(C); end; end; // Pour le momment, Beaucoup de choses m'échappent // Je n'ai pas encore tout analisé (Manque d'information sur ActiveX.Pas) procedure TForm1.FormCreate(Sender: TObject); begin OleInitialize(nil); OleCheck(RegisterDragDrop(Handle, Self)); end; procedure TForm1.FormDestroy(Sender: TObject); begin RevokeDragDrop(Handle); OleUninitialize; end; function TForm1.DragEnter(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; begin dwEffect := DROPEFFECT_NONE; // Ici on peux choisir si le drop est actif dès son entrée dans la Form (ici j'ai choisi de la désactiver) Result := S_OK; // à savoir que dans un même temps Dragover va prendre la main dessus end; // ici je sélectionne LEs composants qui vont accepter le Drop function TForm1.DragOver(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; Var n : int64; Begin dwEffect := DROPEFFECT_None; // on interdi l'importation des données N := GetComponentIndex(Pt); if N > -1 then begin if (Components[N].Name = 'Edit1') or // Autorisation d'importation des données (Components[N].Name = 'Memo1') or // Pour les composant choisis (Components[N].Name = 'Label1') then dwEffect := DROPEFFECT_COPY end; Result := S_OK; end; function TForm1.DragLeave: HResult; begin Result := S_OK; end; function TForm1.Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; var aFmtEtc: TFORMATETC; aStgMed: TSTGMEDIUM; pData: PChar; I : integer; begin // Les données suivantes se trouvent dans activeX.pas // DROPEFFECT_NONE => 0 rend inactif l'action // DROPEFFECT_COPY => 1 Autorise la copy // DROPEFFECT_MOVE => 2 Autorise le déplacement // DROPEFFECT_LINK => 3 ??? // DROPEFFECT_SCROLL => $80000000 ??? I := MessageDlg('Voullez vous Supprimer les données de la Zone de départ ?',mtInformation,mbYesNoCancel,-1); if I in [mrYes,mrNo] then begin Case I of mrYes : dwEffect:= DROPEFFECT_MOVE; // supprime de la zone de départ mrNo : dwEffect:= DROPEFFECT_COPY; // fait une simple copie end; if (dataObj = nil) then raise Exception.Create('IDataObject-Pointer is not valid!'); // préparation du format de réception ( TEXTE ) with aFmtEtc do begin cfFormat := CF_TEXT; ptd := nil; dwAspect := DVASPECT_CONTENT; lindex := -1; tymed := TYMED_HGLOBAL; end; // récupération des données OleCheck(dataObj.GetData(aFmtEtc, aStgMed)); try pData := GlobalLock(aStgMed.hGlobal); // pdata contien le texte à importer // gestion en fonction des différents contols if components[GetComponentIndex(Pt)].Name = 'Label1' then Label1.Caption := pData else if components[GetComponentIndex(Pt)].Name = 'Edit1' then Edit1.Text := pData else if components[GetComponentIndex(Pt)].Name = 'Memo1' then begin // Calcul de la position du pointeur de la souris pour positionner le texte à une position précise dans le TMemo I := (pt.Y - (Top + (Height - ClientHeight) + Memo1.Top)) shl 16 + (pt.X - (Left + (Width - ClientWidth) div 2 + Memo1.Left)); I := LoWord(Memo1.Perform(EM_CHARFROMPOS, 0, I)); Memo1.SelStart := I; // on positionne le curseur de selection sous le pointeur de la souris Memo1.SetSelTextBuf(pdata); // on insert le text là où est le curseur end; finally GlobalUnlock(aStgMed.hGlobal); ReleaseStgMedium(aStgMed); end; end else dwEffect := DROPEFFECT_NONE; Result := S_OK; end; end.
unit FMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.ExtCtrls, FMX.Layouts, Grijjy.TextToSpeech; type TFormMain = class(TForm) Memo: TMemo; MemoLog: TMemo; GridPanelLayout2: TGridPanelLayout; ButtonSpeak: TButton; ButtonStop: TButton; procedure FormCreate(Sender: TObject); procedure ButtonSpeakClick(Sender: TObject); procedure ButtonStopClick(Sender: TObject); private { Private declarations } FTextToSpeech: IgoTextToSpeech; procedure Log(const AMsg: String); procedure TextToSpeechAvailable(Sender: TObject); procedure TextToSpeechStarted(Sender: TObject); procedure TextToSpeechFinished(Sender: TObject); procedure UpdateControls; public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} procedure TFormMain.ButtonSpeakClick(Sender: TObject); begin if (not FTextToSpeech.Speak(Memo.Text)) then Log('Unable to speak text'); end; procedure TFormMain.ButtonStopClick(Sender: TObject); begin FTextToSpeech.Stop; end; procedure TFormMain.FormCreate(Sender: TObject); begin FTextToSpeech := TgoTextToSpeech.Create; FTextToSpeech.OnAvailable := TextToSpeechAvailable; FTextToSpeech.OnSpeechStarted := TextToSpeechStarted; FTextToSpeech.OnSpeechFinished := TextToSpeechFinished; end; procedure TFormMain.Log(const AMsg: String); begin MemoLog.Lines.Add(AMsg); end; procedure TFormMain.TextToSpeechAvailable(Sender: TObject); begin Log('Text-to-Speech engine is available'); UpdateControls; end; procedure TFormMain.TextToSpeechFinished(Sender: TObject); begin Log('Speech finished'); UpdateControls; end; procedure TFormMain.TextToSpeechStarted(Sender: TObject); begin Log('Speech started'); UpdateControls; end; procedure TFormMain.UpdateControls; begin ButtonSpeak.Enabled := (not FTextToSpeech.IsSpeaking); ButtonStop.Enabled := (not ButtonSpeak.Enabled); end; end.
program diez; const corte = 'zzzzzz'; dimF = 15; type rango = 1..dimF; arrValores = array [rango] of real; tEmpleado = record departamento : String; division : String; numEmpleado : integer; categoria : rango; horasExtras : integer; end; tResultado = record montoTotalDepartamento : real; horasTotalDepartamento : integer; montoTotalDivision : real; horasTotalDivision : integer; montoPorEmpleado : real; horasPorEmpleado : integer; end; archivoEmpleados = file of tEmpleado; procedure leerArchivo (var arc : archivoEmpleados; var reg : tEmpleado); begin if (not eof(arc)) then read(arc, reg) else reg.departamento := corte; end; procedure cargarVectorDeValores (var texto : Text; var vectorValores : arrValores); var valor : real; categoria : rango; begin reset(texto); while (not eof (texto)) do begin readln(texto, categoria, valor); vectorValores[categoria] := valor; end; close(texto); end; procedure corteDeControl (var archivo : archivoEmpleados; vectorValores : arrValores); var resultados : tResultado; empleadoActual : integer; categ : rango; divisionActual, departamentoActual : String; regM : tEmpleado; begin reset(archivo); leerArchivo(archivo, regM); while (regM.departamento <> corte) do begin //asigno el departamento actual departamentoActual := regM.departamento; writeln('Departamento: ',departamentoActual); //inicializo los valore del departamento actual (horas y monto total) resultados.montoTotalDepartamento := 0; resultados.horasTotalDepartamento := 0; while (departamentoActual = regM.departamento) do begin //asigno la division actual divisionActual := regM.division; writeln('Division: ',divisionActual); //inicializo los valore de la division actual (horas y monto total) resultados.montoTotalDivision := 0; resultados.horasTotalDivision := 0; writeln('Numero de empleado Total de hs. Importe a cobrar'); while ((departamentoActual = regM.departamento) and (divisionActual = regM.division)) do begin //asigno el empleado actual empleadoActual := regM.numEmpleado; //guardo la categoria actual para poder acceder al vector categ := regM.categoria; //inicializo los valore del empleado actual (horas y monto total) resultados.montoPorEmpleado := 0; resultados.horasPorEmpleado := 0; while ((departamentoActual = regM.departamento) and (divisionActual = regM.division) and (empleadoActual = regM.numEmpleado)) do begin {mientras el empleado sea igual al actual contabilizo las horas} resultados.horasPorEmpleado := resultados.horasPorEmpleado + regM.horasExtras; leerArchivo(archivo, regM); end;//end de empleados //el monto es igual al monto segun la categoria multiplicado por las horas extras resultados.montoPorEmpleado := (resultados.horasPorEmpleado * vectorValores[categ]); writeln(empleadoActual,' ',resultados.horasPorEmpleado,' ',resultados.montoPorEmpleado); //contabilizo los datos del empleado con los de la division actual resultados.horasTotalDivision := resultados.horasTotalDivision + resultados.horasPorEmpleado; resultados.montoTotalDivision := resultados.montoTotalDivision + resultados.montoPorEmpleado; end; //end de division writeln('Total de horas division: ',resultados.horasTotalDivision); writeln('Monto total por division: ',resultados.montoTotalDivision); //contabilizo los datos de la division con los del departamento actual resultados.montoTotalDepartamento := resultados.montoTotalDepartamento + resultados.montoTotalDivision; resultados.horasTotalDepartamento := resultados.horasTotalDepartamento + resultados.horasTotalDivision; end; //end de departamento writeln('Total horas departamento: ',resultados.horasTotalDepartamento); writeln('Monto total departamento: ',resultados.montoTotalDepartamento); end; //end del archivo close(archivo); end; //Programa principal var archivo : archivoEmpleados; vectorValores : arrValores; textoConLosMontosPorHora : Text; begin assign(textoConLosMontosPorHora,'montos_por_hora_segun_categoria.txt'); assign(archivo,'archivo_empleados'); cargarVectorDeValores(textoConLosMontosPorHora, vectorValores); corteDeControl(archivo, vectorValores); end.
unit NovusUtilities; interface uses SysUtils, Classes, Windows, Messages, typinfo; Const DosDelimSet : set of Char = ['\', ':', #0]; StMaxFileLen = 260; WM_CLOSEWINDOW = WM_USER + 1; WM_UPDATE = WM_USER + 1; Type TNovusUtilities = class(TObject) public class function CopyObject(Src,Dest : TObject; Related : Boolean = FALSE): Boolean; class function AppRootDirectory: String; class function GetExceptMess: String; class procedure FreeObject(q : TObject); class function FindStringListValue(const Strings: tstringlist; Name: String): String; class function FindFileSize(Afile: String): Integer; class function JustFilename(const PathName : String) : String; class function JustPathname(const PathName : ShortString) : String; class function GetPropertyasClass(aObject: TObject; aPropertyName: string): TObject; class function IsProperty(aObject: TObject; aPropertyName: string): boolean; class function GetParamValue(const aParamKey : string; var aValue : string ) : boolean; end; implementation Uses NovusWindows; class function TNovusUtilities.AppRootDirectory; begin Result := ExtractFilePath(ParamStr(0)); end; class function TNovusUtilities.GetExceptMess; begin Result := TNovusWindows.WindowsExceptMess; end; class procedure TNovusUtilities.FreeObject(Q : TObject); begin if Not Assigned(Q) then Exit; SysUtils.FreeandNil(Q); end; class function TNovusUtilities.FindStringListValue(const Strings: tstringlist; Name: String): String; Var I: integer; begin Result := ''; For I := 0 to Strings.Count -1 do begin If Uppercase(Strings.Names[i]) = Uppercase(Name) then begin Result := Strings.ValueFromIndex[i]; Break; end; end; end; class function TNovusUtilities.FindFileSize(Afile: String): Integer; var SR : TSearchRec; R : Integer; begin R := FindFirst(Afile, faAnyFile, SR); if R = 0 then Result := SR.Size; SysUtils.FindClose(SR); end; class function TNovusUtilities.JustFilename(const PathName : String) : String; var I : Longint; begin Result := ''; if PathName = '' then Exit; I := Succ(Length(PathName)); repeat Dec(I); until (I = 0) or (PathName[I] in DosDelimSet); Result := Copy(PathName, Succ(I), StMaxFileLen); end; class function TNovusUtilities.JustPathname(const PathName : ShortString) : String; Var I: Integer; begin I := Succ(Length(PathName)); repeat Dec(I); until (I = 0) or (PathName[I] in DosDelimSet); {!!.01} if I = 0 then {Had no drive or directory name} SetLength(Result, 0) else if I = 1 then {Either the root directory of default drive or invalid pathname} Result := PathName[1] else if (PathName[I] = '\') then begin if PathName[Pred(I)] = ':' then {Root directory of a drive, leave trailing backslash} Result := Copy(PathName, 1, I) else {Subdirectory, remove the trailing backslash} Result := Copy(PathName, 1, Pred(I)); end else {Either the default directory of a drive or invalid pathname} Result := Copy(PathName, 1, I); end; class function TNovusUtilities.CopyObject(Src,Dest : TObject; Related : Boolean = FALSE): Boolean; var Mem : Pointer; Size : Integer; begin { Source or Dest = NIL -> Exit } if(NOT Assigned(Src))OR (NOT Assigned(Dest)) then begin Result := FALSE; Exit; end; { Copy } if(NOT Related)OR { If Related = FALSE, copy object regardless of inheritance } (Src.InheritsFrom(Dest.ClassType))OR { Src descends from Dest } (Dest.InheritsFrom(Src.ClassType)) then { Dest descends from Src } begin if Src.InstanceSize < Dest.InstanceSize then Size := Src.InstanceSize else Size := Dest.InstanceSize; { Get the needed memory amount } Dec(Size,4); { Virtual method table occupies the first 4 bytes - leave it alone!!! } GetMem(Mem,Size); if Size < Dest.InstanceSize then System.FillChar(PByteArray(Dest)^[4],Size,0); System.Move(PByteArray(Src)^[4],PByteArray(Dest)^[4],Size); FreeMem(Mem); Result := TRUE; end else Result := FALSE; end; class function TNovusUtilities.GetPropertyasClass(aObject: TObject; aPropertyName: string): TObject; var i, Count: integer; PropList: PPropList; begin Result := nil; if aObject.Classinfo = nil then Exit; Count := GetTypeData(aObject.ClassInfo)^.PropCount; if Count > 0 then begin GetMem(PropList, Count * Sizeof(Pointer)); try GetPropInfos(aObject.ClassInfo, PropList); for i := 0 to Count - 1 do if ansicomparetext(PropList^[i].Name, aPropertyName) = 0 then begin case PropList^[i].PropType^.Kind of tkClass: Result := TObject(GetOrdProp(aObject, PropList^[i])); end; Break; end; finally FreeMem(PropList, Count * SizeOf(Pointer)); end; end; end; class function TNovusUtilities.IsProperty(aObject: TObject; aPropertyName: string): boolean; var i, Count: integer; PropList: PPropList; begin Result := false; Count := GetTypeData(aObject.ClassInfo)^.PropCount; if Count > 0 then begin GetMem(PropList, Count * Sizeof(Pointer)); try GetPropInfos(aObject.ClassInfo, PropList); for i := 0 to Count - 1 do {$IFDEF win32} if ansicomparetext(PropList^[i].Name, aPropertyName) = 0 then {$ELSE} if ansicomparetext(PropList^[i]^.Name, aPropertyName) = 0 then {$ENDIF} begin Result := true; Break; end; finally FreeMem(PropList, Count * SizeOf(Pointer)); end; end; end; (* class function TNovusUtilities.TwipsPerPixelX(Canvas : TCanvas) : Extended; begin result := (1440 / GetDeviceCaps(Canvas.Handle, LOGPIXELSX)); end; class function TNovusUtilities.TwipsPerPixelY(Canvas : TCanvas) : Extended; begin result := (1440 / GetDeviceCaps(Canvas.Handle, LOGPIXELSY)); end; *) class function TNovusUtilities.GetParamValue(const aParamKey : string; var aValue : string ) : boolean; var lparamloop : integer; i: Integer; liPos : integer; begin aValue := ''; if paramcount > 0 then for lparamloop := 1 to paramcount do begin liPos := pos(lowercase(aParamKey), lowercase(paramstr(lparamloop)) ); if (liPos > 0) then begin result := True; liPos := liPos+length(aParamKey); aValue := system.copy( paramstr(lparamloop), liPos, length( paramstr(lparamloop) ) ); break; end; end; end; end.
program image_service; {$mode delphi}{$H+} uses {$IFDEF UNIX} cthreads, {$ENDIF} SysUtils, fphttpapp, config.types, controller.base, controller.registration, controller.status, controller.image, controller.settings, controller.registration.dto; const CONFIG_NAME = 'image_service_config.json'; var LConfig : IJSONConfig; LError: String; begin CONTROLLER_LOG_TYPES := []; WriteLn('image service starting...'); //create and load config if one exists LConfig := CreateJSONConfig; if not FileExists(CONFIG_NAME) then begin LConfig.UpsertValue('port', '8083'); //set default port LConfig.UpsertValue('databaseName', 'image_service.sqlite3'); //default db name LConfig.UpsertValue('authServiceAddress', '127.0.0.1:8081'); //default db name LConfig.UpsertValue('maxImageWidth', '48'); LConfig.UpsertValue('maxImageHeight', '48'); LConfig.UpsertValue('useSSL', 'false'); LConfig.UpsertValue('sslPublicKeyFile', CERT_PUBLIC_FILE); LConfig.UpsertValue('sslPrivateKeyFile', CERT_PRIVATE_FILE); LConfig.UpsertValue('sslPrivateKeyPassphrase', CERT_PASSPHRASE); if not LConfig.SaveToFile(CONFIG_NAME, LError) then WriteLn(LError); end else if not LConfig.LoadFromFile(CONFIG_NAME, LError) then WriteLn(LError); //set the database name for the image service DEFAULT_DB_NAME := LConfig['databaseName']; //update the auth service address AUTH_ADDRESS := LConfig['authServiceAddress']; //update the max dimensions MAX_IMAGE_WIDTH := StrToIntDef(LConfig['maxImageWidth'], 48); MAX_IMAGE_HEIGHT := StrToIntDef(LConfig['maxImageHeight'], 48); //update ssl info CERT_PUBLIC_FILE := LConfig['sslPublicKeyFile']; CERT_PRIVATE_FILE := LConfig['sslPrivateKeyFile']; CERT_PASSPHRASE := LConfig['sslPrivateKeyPassphrase']; //init web app Application.Title:='image_service'; Application.UseSSL := StrToBoolDef(LConfig['useSSL'], False); Application.Port:=StrToIntDef(LConfig['port'], 8083); //shouldn't fail, but default here Application.Threaded:=True; //thread for every request Application.Initialize; Application.Run; end.
(* * Copyright (c) 2008, Susnea Andrei * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <copyright holder> ''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 <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit HelperLib.Collections.Map; interface uses SysUtils, HelperLib.Base, HelperLib.TypeSupport, HelperLib.Collections.Utils, HelperLib.Collections.KeyValuePair, HelperLib.Collections.Interfaces, HelperLib.Collections.Exceptions; type {Generic Map} HMap<TKey, TValue> = class(HRefCountedObject, ICollection<HKeyValuePair<TKey, TValue>>, IEnumerable<HKeyValuePair<TKey, TValue>>) private type { Map specific KV Pair } HMapKeyValuePair = class private FKey : TKey; FValue : TValue; FParent : HMapKeyValuePair; FLeft : HMapKeyValuePair; FRight : HMapKeyValuePair; FMap : HMap<TKey, TValue>; FShouldDelete : boolean; public { Constructors } constructor Create(const AKey : TKey; const AValue : TValue); overload; constructor Create(const APair : HMapKeyValuePair); overload; { Destructor } destructor Destroy(); override; { Assign value of another pair } procedure Assign(const APair : HMapKeyValuePair); { Properties } property Key : TKey read FKey; property Value : TValue read FValue; property Left : HMapKeyValuePair read FLeft; property Right : HMapKeyValuePair read FRight; end; var FComp : ITypeSupport<TKey>; FVer : Cardinal; FCount : Cardinal; FRoot : HMapKeyValuePair; FCurrentPosition : integer; FFound : boolean; function GetElementAt(Index: Cardinal): HKeyValuePair<TKey, TValue>; function FindPair(const AKey : TKey; const RaiseError : Boolean = true) : HMapKeyValuePair; procedure RecDelete(const APair : HMapKeyValuePair); procedure CopyTraverseTree(var APair : HMapKeyValuePair; var AArray : array of HKeyValuePair<TKey,TValue>; AHead : Cardinal); procedure DeleteAndBalance(var APair : HMapKeyValuePair); function FindInorderAncestor( APair : HMapKeyValuePair ) : HMapKeyValuePair; function TraverseTreeUpToPosition( APair : HMapKeyValuePair; DesiredPosition : Cardinal) : HMapKeyValuePair; procedure Remove(const APair: HMapKeyValuePair); overload; protected { ICollection support } function GetCount() : Cardinal; procedure Add(const AValue : HKeyValuePair<TKey, TValue>); public { Constructors } constructor Create(); overload; constructor Create(const AEnumerable : IEnumerable<HKeyValuePair<TKey, TValue>>); overload; constructor Create(const ASupport : ITypeSupport<TKey>); overload; constructor Create(const ASupport : ITypeSupport<TKey>; const AEnumerable : IEnumerable<HKeyValuePair<TKey, TValue>>); overload; { Modifying } procedure Clear(); procedure Insert(const AKey : TKey; const AValue : TValue); overload; procedure Insert(const APair : HKeyValuePair<TKey, TValue>); overload; procedure Remove(const AKey : TKey); overload; { Finding } function Contains(const AKey : TKey) : Boolean; function Find(const AKey : TKey) : TValue; { Properties } property Count : Cardinal read FCount; property Items[Index : Cardinal] : HKeyValuePair<TKey, TValue> read GetElementAt; default; { ICollection/IEnumerable Support } procedure CopyTo(var AArray : array of HKeyValuePair<TKey, TValue>); overload; procedure CopyTo(var AArray : array of HKeyValuePair<TKey, TValue>; const StartIndex : Cardinal); overload; function GetEnumerator() : IEnumerator<HKeyValuePair<TKey, TValue>>; end; HMapEnumerator<TKey, TValue> = class(HRefCountedObject, IEnumerator<HKeyValuePair<TKey, TValue>>) private FVer : Cardinal; FMap : HMap<TKey, TValue>; FCurrentIdx : Integer; public { Constructor } constructor Create(const AMap : HMap<TKey, TValue>); { Destructor } destructor Destroy(); override; function GetCurrent() : HKeyValuePair<TKey, TValue>; function MoveNext() : Boolean; property Current : HKeyValuePair<TKey, TValue> read GetCurrent; end; implementation { HMapKeyValuePair<TKey, TValue> } constructor HMap<TKey, TValue>.HMapKeyValuePair.Create(const AKey: TKey; const AValue: TValue); begin FKey := AKey; FValue := AValue; FLeft := nil; FRight := nil; FMap := nil; FParent := nil; FShouldDelete := true; end; constructor HMap<TKey, TValue>.HMapKeyValuePair.Create( const APair: HMapKeyValuePair); begin FKey := APair.Key; FValue := APair.Value; FLeft := nil; FRight := nil; FMap := nil; FParent := nil; FShouldDelete := true; end; procedure HMap<TKey, TValue>.HMapKeyValuePair.Assign( const APair: HMapKeyValuePair); begin FKey := APair.FKey; FValue := APair.FValue; end; destructor HMap<TKey, TValue>.HMapKeyValuePair.Destroy; begin //this happens incase we want to destroy an item //not connected to any Map. if FMap <> nil then Dec(FMap.FCount); inherited; end; { HMap<TKey, TValue> } procedure HMap<TKey, TValue>.Add(const AValue: HKeyValuePair<TKey, TValue>); begin { Pass to normal function } Insert(AValue); end; procedure HMap<TKey, TValue>.Clear; begin { Invoke recursive delete } RecDelete(FRoot); FRoot := nil; FCount :=0; Inc(FVer); end; function HMap<TKey, TValue>.Contains(const AKey: TKey): Boolean; begin { Simply check } Result := (FindPair(AKey, false) <> nil); end; procedure HMap<TKey, TValue>.CopyTo( var AArray: array of HKeyValuePair<TKey, TValue>); begin CopyTo(AArray, 0); end; procedure HMap<TKey, TValue>.CopyTo( var AArray: array of HKeyValuePair<TKey, TValue>; const StartIndex: Cardinal); begin { Check for indexes } if Range.OutOfBounds(Length(AArray), StartIndex, Count) then raise EArgumentOutOfRangeException.Create('Insuficient space in AArray!'); CopyTraverseTree(FRoot, AArray, StartIndex); end; procedure HMap<TKey, TValue>.CopyTraverseTree( var APair: HMapKeyValuePair; var AArray : array of HKeyValuePair<TKey,TValue>; AHead : Cardinal); begin if APair = nil then Exit(); AArray[AHead] := HKeyValuePair<TKey, TValue>.Create(APair.FKey, APair.FValue); if APair.FLeft <> nil then AHead := AHead + 1; APair.FMap.CopyTraverseTree(APair.FLeft, AArray, AHead); if APair.FRight <> nil then AHead := AHead + 1; APair.FMap.CopyTraverseTree(APair.FRight, AArray, AHead); end; constructor HMap<TKey, TValue>.Create(const ASupport: ITypeSupport<TKey>; const AEnumerable: IEnumerable<HKeyValuePair<TKey, TValue>>); var V : HKeyValuePair<TKey, TValue>; begin { Initialize instance } if (ASupport = nil) then raise EArgumentException.Create('ASupport parameter is nil'); { Initialize instance } if (AEnumerable = nil) then raise EArgumentException.Create('AEnumerable parameter is nil'); FComp := ASupport; FRoot := nil; FVer := 0; FCount := 0; FCurrentPosition := 0; FFound := false; { Try to copy the given Enumerable } for V in AEnumerable do begin { Perform a simple push } Insert(V.Key, V.Value); end; end; constructor HMap<TKey, TValue>.Create; begin Create(HTypeSupport<TKey>.Default); end; constructor HMap<TKey, TValue>.Create( const AEnumerable: IEnumerable<HKeyValuePair<TKey, TValue>>); begin FCurrentPosition := 0; FFound := false; Create(HTypeSupport<TKey>.Default, AEnumerable); end; procedure HMap<TKey, TValue>.DeleteAndBalance(var APair: HMapKeyValuePair); var temp : HMapKeyValuePair; parent : HMapKeyValuePair; begin if (APair.FLeft = nil) and (APair.FRight = nil) then if FRoot = APair then begin FRoot := nil; Exit(); end else if APair.FParent.FLeft = APair then begin APair.FParent.FLeft := nil; Exit(); end else begin APair.FParent.FRight := nil; Exit(); end; if APair.FLeft = nil then begin temp := APair; //APair := APair.FRight; if APair.FParent = nil then begin FRoot := APair.FRight; APair.FParent := nil; Exit(); end; if APair.FParent.FRight = APair then APair.FParent.FRight := APair.FRight else APair.FParent.FLeft := APair.FLeft; end else if APair.FRight = nil then begin temp := APair; //APair := APair.FLeft; if APair.FParent = nil then begin FRoot := APair.FLeft; Exit(); end; if APair.FParent.FRight = APair then APair.FParent.FRight := APair.FRight else APair.FParent.FLeft := APair.FLeft; end else begin temp:= APair.FMap.FindInorderAncestor(APair); APair.Assign(temp); APair.FShouldDelete := false; Remove(temp); end; end; constructor HMap<TKey, TValue>.Create(const ASupport: ITypeSupport<TKey>); begin { Initialize instance } if (ASupport = nil) then raise EArgumentException.Create('ASupport parameter is nil'); FComp := ASupport; FRoot := nil; FVer := 0; FCount := 0; FCurrentPosition := 0; FFound := false; end; function HMap<TKey, TValue>.Find(const AKey: TKey): TValue; var Pair : HMapKeyValuePair; begin Pair := FindPair(AKey, false); if Pair = nil then raise EKeyNotFoundException.Create('Key defined by AKey not found in the collection.'); Result := Pair.Value; end; function HMap<TKey, TValue>.FindPair( const AKey: TKey; const RaiseError: Boolean): HMapKeyValuePair; var hasSons : boolean; currentValue : HMapKeyValuePair; begin hasSons := true; if FRoot = nil then begin Result := nil; Exit(); end; currentValue := FRoot; while hasSons = true do begin hasSons := false; if FComp.AreEqual(currentValue.Key,AKey) then begin Result := currentValue; Exit(); end; if ( currentValue.FLeft <> nil ) and (FComp.Compare(currentValue.Key,AKey) > 0) then begin currentValue := currentValue.FLeft; hasSons := true; Continue; end; if ( currentValue.FRight <> nil ) and (FComp.Compare(currentValue.Key,AKey) < 0) then begin currentValue := currentValue.FRight; hasSons := true; Continue; end; if RaiseError then raise EArgumentException.Create('Key not found! Tree is created wrong!!!!') else begin Result := nil; Exit; end; end; end; function HMap<TKey, TValue>.FindInorderAncestor( APair: HMapKeyValuePair): HMapKeyValuePair; var currentNode : HMapKeyValuePair; hasSons : boolean; begin currentNode := APair.FRight; Result := currentNode; hasSons := true; while hasSons = true do hasSons := false; begin if (FComp.Compare(Result.Key, currentNode.Key) < 0) and (FComp.Compare(currentNode.Key, APair.Key) > 0 )then Result := currentNode; if currentNode.FLeft <> nil then begin hasSons := true; currentNode := currentNode.FLeft; end; end; end; function HMap<TKey, TValue>.GetCount: Cardinal; begin Result := FCount; end; function HMap<TKey, TValue>.GetElementAt( Index: Cardinal): HKeyValuePair<TKey, TValue>; var Pair : HMapKeyValuePair; begin FCurrentPosition := 0; FFound := false; if Index > FCount - 1 then raise EArgumentOutOfRangeException.Create('Index out of bounds'); Pair := TraverseTreeUpToPosition(FRoot, Index); Result := HKeyValuePair<TKey, TValue>.Create(Pair.FKey, Pair.FValue); end; function HMap<TKey, TValue>.GetEnumerator: IEnumerator<HKeyValuePair<TKey, TValue>>; begin Result := HMapEnumerator<TKey, TValue>.Create(Self); end; procedure HMap<TKey, TValue>.Insert(const AKey: TKey; const AValue: TValue); begin Insert(HKeyValuePair<TKey,TValue>.Create(AKey, AValue)); end; procedure HMap<TKey, TValue>.Insert(const APair: HKeyValuePair<TKey, TValue>); var currentValue : HMapKeyValuePair; hasSons : boolean; ObjPair : HMapKeyValuePair; begin if FRoot = nil then begin ObjPair := HMapKeyValuePair.Create(APair.Key, APair.Value); ObjPair.FMap := Self; FRoot := ObjPair; FCount := 1; Inc(FVer); Exit(); end; currentValue := FRoot; hasSons := true; // while (currentValue.FLeft <> nil) and (currentValue.FRight <> nil) do while (hasSons = true) do begin hasSons := false; if FComp.AreEqual(APair.Key, currentValue.Key) then raise EDuplicateKeyException.Create('Key already found'); if FComp.Compare(APair.Key,currentValue.Key) < 0 then begin if currentValue.FLeft = nil then begin ObjPair := HMapKeyValuePair.Create(APair.Key, APair.Value); ObjPair.FParent := currentValue; ObjPair.FMap := Self; FCount := FCount + 1; currentValue.FLeft := ObjPair; Inc(FVer); Exit(); end else currentValue := currentValue.FLeft; hasSons := true; end; if FComp.Compare(APair.Key,currentValue.Key) > 0 then begin if currentValue.FRight = nil then begin ObjPair := HMapKeyValuePair.Create(APair.Key, APair.Value); ObjPair.FParent := currentValue; ObjPair.FMap := Self; FCount := FCount + 1; currentValue.FRight := ObjPair; Inc(FVer); Exit(); end else currentValue := currentValue.FRight; hasSons := true; end; end; end; procedure HMap<TKey, TValue>.RecDelete(const APair: HMapKeyValuePair); begin if APair = nil then Exit(); if APair.FLeft <> nil then begin APair.FMap.RecDelete(APair.FLeft); APair.FLeft := nil; end; if APair.FRight <> nil then begin APair.FMap.RecDelete(APair.FRight); APair.FRight := nil; end; APair.Free; end; procedure HMap<TKey, TValue>.Remove(const AKey: TKey); var Pair : HMapKeyValuePair; begin Pair := FindPair(AKey, false); if Pair = nil then raise EKeyNotFoundException.Create('Key defined by AKey not found in the collection.'); Self.Remove(Pair); end; function HMap<TKey, TValue>.TraverseTreeUpToPosition( APair: HMapKeyValuePair; DesiredPosition: Cardinal): HMapKeyValuePair; begin if APair = nil then Exit(); if FCurrentPosition = DesiredPosition then begin Result := APair; FFound := true; Exit(); end; if APair.FLeft <> nil then begin if FFound = true then Exit(); FCurrentPosition := FCurrentPosition + 1; Result := APair.FMap.TraverseTreeUpToPosition(APair.FLeft, DesiredPosition); end; if APair.FRight <> nil then begin if FFound = true then Exit(); FCurrentPosition := FCurrentPosition + 1; Result := APair.FMap.TraverseTreeUpToPosition(APair.FRight, DesiredPosition); end; end; procedure HMap<TKey, TValue>.Remove( const APair: HMapKeyValuePair); var Temp : HMapKeyValuePair; begin if APair.FMap <> Self then raise EArgumentException.Create('APair is not a part of this map.'); Temp := APair; DeleteAndBalance(Temp); Inc(FVer); { Simply invoke destructor} if APair.FShouldDelete = true then APair.Free(); APair.FShouldDelete := true; end; { HMapEnumerator<TKey, TValue> } constructor HMapEnumerator<TKey, TValue>.Create(const AMap: HMap<TKey, TValue>); begin FVer := AMap.FVer; FMap := AMap; FCurrentIdx := -1; end; destructor HMapEnumerator<TKey, TValue>.Destroy; begin { Nothing } inherited; end; function HMapEnumerator<TKey, TValue>.GetCurrent: HKeyValuePair<TKey, TValue>; begin if FVer <> FMap.FVer then raise ECollectionChanged.Create('Parent collection has changed!'); if FCurrentIdx > -1 then Result := FMap[FCurrentIdx]; end; function HMapEnumerator<TKey, TValue>.MoveNext: Boolean; begin if FVer <> FMap.FVer then raise ECollectionChanged.Create('Parent collection has changed!'); Inc(FCurrentIdx); Result := (FCurrentIdx < FMap.Count); end; end.
{********************************************************} { } { Zeos Database Objects } { MySql Transaction component } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZMySqlTr; interface {$R *.dcr} uses {$IFNDEF LINUX}Windows, {$ENDIF} SysUtils, DB, Classes, ZDirSql, ZDirMySql, ZLibMySql, ZToken, ZMySqlCon, ZTransact, ZSqlTypes; {$IFNDEF LINUX} {$INCLUDE ..\Zeos.inc} {$ELSE} {$INCLUDE ../Zeos.inc} {$ENDIF} type { MySql transaction component (stub) } TZMySqlTransact = class(TZTransact) private function GetDatabase: TZMySqlDatabase; procedure SetDatabase(Value: TZMySqlDatabase); public constructor Create(AOwner: TComponent); override; {$IFDEF USE_GENERATORS} function GetGen(GenName: ShortString): LongInt; {$ENDIF} function GetHostInfo: ShortString; function GetProtoInfo: Cardinal; function GetClientInfo: ShortString; function GetServerInfo: ShortString; function GetServerStat: ShortString; procedure Kill(PID: Integer); procedure Ping; procedure Shutdown; procedure AddMonitor(Monitor: TZMonitor); override; procedure DeleteMonitor(Monitor: TZMonitor); override; published property Database: TZMySqlDatabase read GetDatabase write SetDatabase; property TransactSafe; end; implementation uses ZDbaseConst; {***************** TZMySqlTransact implementation *****************} { Class constructor } constructor TZMySqlTransact.Create(AOwner: TComponent); begin inherited Create(AOwner); FHandle := TDirMySqlTransact.Create(nil); FQuery := TDirMySqlQuery.Create(nil, TDirMySqlTransact(FHandle)); FDatabaseType := dtMySql; end; { Get database component } function TZMySqlTransact.GetDatabase: TZMySqlDatabase; begin Result := TZMySqlDatabase(FDatabase); end; { Set database component } procedure TZMySqlTransact.SetDatabase(Value: TZMySqlDatabase); begin inherited SetDatabase(Value); end; {$IFDEF USE_GENERATORS} { Get a generator value } function TZMySqlTransact.GetGen(GenName: ShortString): LongInt; begin if not Connected then DatabaseError(LoadStr(SNotConnected)); Result := StrToIntDef(ExecFunc('GETGEN("'+GenName+'")'),0); end; {$ENDIF} { Get host information } function TZMySqlTransact.GetHostInfo: ShortString; begin if Connected then Result := mysql_get_host_info(@TDirMySqlTransact(Handle).Handle) else Result := ''; end; { Get protocol information } function TZMySqlTransact.GetProtoInfo: Cardinal; begin if Connected then Result := mysql_get_proto_info(@TDirMySqlTransact(Handle).Handle) else Result := 0; end; { Get client information } function TZMySqlTransact.GetClientInfo: ShortString; begin Result := mysql_get_client_info; end; { Get server information } function TZMySqlTransact.GetServerInfo: ShortString; begin if Connected then Result := mysql_get_server_info(@TDirMySqlTransact(Handle).Handle) else Result := ''; end; { Get serve status } function TZMySqlTransact.GetServerStat: ShortString; begin if Connected then Result := mysql_stat(@TDirMySqlTransact(Handle).Handle) else Result := ''; end; { Kill server process } procedure TZMySqlTransact.Kill(PID: Integer); begin if mysql_kill(@TDirMySqlTransact(Handle).Handle, PID) <> 0 then DatabaseError(Handle.Error); end; { Check connection } procedure TZMySqlTransact.Ping; begin if mysql_ping(@TDirMySqlTransact(Handle).Handle) <> 0 then DatabaseError(Handle.Error); end; { Shutdown server } procedure TZMySqlTransact.Shutdown; begin if mysql_shutdown(@TDirMySqlTransact(Handle).Handle) <> 0 then DatabaseError(Handle.Error); end; { Add monitor into monitor list } procedure TZMySqlTransact.AddMonitor(Monitor: TZMonitor); begin ZDirMySql.MonitorList.AddMonitor(Monitor); end; { Delete monitor from monitor list } procedure TZMySqlTransact.DeleteMonitor(Monitor: TZMonitor); begin ZDirMySql.MonitorList.DeleteMonitor(Monitor); end; end.
unit Com; interface uses WinTypes, WinProcs, Classes, SysUtils; type TRTSMode = (RTS_DISABLED, RTS_ENABLED, RTS_HANDSHAKE, RTS_TOGGLE); TDTRMode = (DTR_DISABLED, DTR_ENABLED, DTR_HANDSHAKE); TParity = (NOPARITY, ODDPARITY, EVENPARITY, MARKPARITY, SPACEPARITY); TStopbits = (ONESTOPBIT, ONE5STOPBITS, TWOSTOPBITS); TCOM = class(TComponent) private FDCB: TDCB; FHandle: Cardinal; FTimeouts: TCommTimeouts; FError: Cardinal; FComNo: byte; FBaud: cardinal; FParity: TParity; FDatabits: byte; FStopbits: TStopbits; function GetRTS: boolean; procedure SetRTS(const Value: boolean); function GetDTR: boolean; procedure SetDTR(const Value: boolean); function GetDCD: boolean; function GetDSR: boolean; function GetRI: boolean; function GetCTS: boolean; function GetIsOpen: boolean; function GetInBufUsed: cardinal; function GetOutBufUsed: cardinal; function GetParity: String; function GetStopBits: String; function GetBaudRate: cardinal; function GetDataBits: byte; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function TestComPortAvailable(ComNo: integer): boolean; function Open(ComNo: integer; RTSMode: TRTSMode; DTRMode: TDTRMode): boolean; function RxFlush: boolean; function TxFlush: boolean; function Send(Data: Char): boolean; overload; function Send(Data: PChar; Len: cardinal): boolean; overload; function GetChar(var data: byte): boolean; procedure Close; procedure Reset; published property ComNo: byte read FComNo; property Baud: cardinal read GetBaudRate write FBaud; property Databits: byte read GetDatabits write FDatabits; property Stopbits: String read GetStopBits; property Parity: String read GetParity; property IsOpen: boolean read GetIsOpen; property InBufUsed: cardinal read GetInBufUsed; property OutBufUsed: cardinal read GetOutBufUsed; property Error: cardinal read FError; property RTS: boolean read GetRTS write SetRTS; property CTS: boolean read GetCTS; property DTR: boolean read GetDTR write SetDTR; property DSR: boolean read GetDSR; property RI: boolean read GetRI; property DCD: boolean read GetDCD; end; var FCOM: TCOM; implementation {----------------------------------------------------------------------------------------------} constructor TCOM.Create(AOwner: TComponent); begin inherited Create(AOwner); FHandle := INVALID_HANDLE_VALUE; Baud := CBR_9600; FDatabits := 8; FParity := NOPARITY; FStopBits := ONESTOPBIT; end; {----------------------------------------------------------------------------------------------} destructor TCOM.Destroy; begin if IsOpen then Close; { Port schließen falls geöffnet } inherited destroy; end; {----------------------------------------------------------------------------------------------} function TCOM.TestComPortAvailable(ComNo: integer): boolean; begin Result := Open(ComNo, RTS_DISABLED, DTR_DISABLED); end; {----------------------------------------------------------------------------------------------} function TCOM.Open(ComNo: integer; RTSMode: TRTSMode; DTRMode: TDTRMode): boolean; var init: string; begin if FHandle = INVALID_HANDLE_VALUE then begin init := '\\.\COM' + IntToStr(ComNo); FHandle := CreateFile(@init[1], GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if FHandle <> INVALID_HANDLE_VALUE then begin FComNo := ComNo; // aktuelle Einstellungen ermitteln if GetCommState(FHandle, FDCB) then begin // rudimentäre Parameter setzen FDCB.Baudrate := FBaud; FDCB.Bytesize := FDatabits; FDCB.Parity := Ord(FParity); FDCB.Stopbits := Ord(FStopbits); // RTS Modus setzen FDCB.flags := FDCB.flags and $CFFB; {RTS aus} case RTSMode of RTS_ENABLED: FDCB.flags := FDCB.flags or $1000; {RTS ein} RTS_HANDSHAKE: FDCB.flags := FDCB.flags or $2004; {RTS Handshake ein (gekoppelt an RX Buffer 0= Empfangspuffer zu 3/4 voll)} RTS_TOGGLE: FDCB.flags := FDCB.flags or $3000; {RTS gekoppelt an Tx Buffer (1=Daten im Sendepuffer)} end; // DTR Modus setzen FDCB.flags := FDCB.flags and $FFC7; {DTR aus (und bleibt aus)} case DTRMode of DTR_ENABLED: FDCB.flags := FDCB.flags or $0010; {DTR ein (und bleibt ein)} DTR_HANDSHAKE: FDCB.flags := FDCB.flags or $0028; {DTR Handshake ein} end; if SetCommState(FHandle, FDCB) then begin if SetupComm(FHandle, 1024, 1024) then {Rx-/Tx-Buffer-Einstellungen} begin FTimeouts.ReadIntervalTimeout := 0; {Timeoutzeiten setzen} FTimeouts.ReadTotalTimeoutMultiplier := 0; FTimeouts.ReadTotalTimeoutConstant := 1; FTimeouts.WriteTotalTimeoutMultiplier := 0; FTimeouts.WriteTotalTimeoutConstant := 0; SetCommTimeouts(FHandle, FTimeouts); end; end; end; end; end; FError := GetLastError; if Error <> 0 then begin Close; end; Result := Error = 0; { Ergebnis zurückgeben } end; {-----------------------------------------------------------------------------------------------} function TCOM.GetCTS: boolean; var nStatus: cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin if GetCommModemStatus(FHandle, nStatus) then Result := (nStatus and MS_CTS_ON) > 0; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetDSR: boolean; var nStatus: cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin if GetCommModemStatus(FHandle, nStatus) then Result := (nStatus and MS_DSR_ON) > 0; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetIsOpen: boolean; begin Result := FHandle <> INVALID_HANDLE_VALUE; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetInBufUsed: cardinal; var Comstat: _Comstat; Errors: DWord; begin if ClearCommError(FHandle, Errors, @Comstat) then Result := Comstat.cbInQue else Result := 0; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetOutBufUsed: cardinal; var Comstat: _Comstat; Errors: DWord; begin if ClearCommError(FHandle, Errors, @Comstat) then Result := Comstat.cbOutQue else Result := 0; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetRI: boolean; var nStatus: cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin if GetCommModemStatus(FHandle, nStatus) then Result := (nStatus and MS_RING_ON) > 0; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetRTS: boolean; begin Result := false; if GetCommState(FHandle, FDCB) then begin Result := (FDCB.Flags and $3000) > 0; end; end; {-----------------------------------------------------------------------------------------------} procedure TCOM.SetRTS(const Value: boolean); begin if (Value = True) then EscapeCommFunction(FHandle, WinTypes.SETRTS) else EscapeCommFunction(FHandle, WinTypes.CLRRTS); end; {-----------------------------------------------------------------------------------------------} function TCOM.GetDTR: boolean; begin Result := false; if GetCommState(FHandle, FDCB) then begin Result := (FDCB.Flags and $0010) > 0; end; end; {-----------------------------------------------------------------------------------------------} procedure TCOM.SetDTR(const Value: boolean); begin if (Value = True) then EscapeCommFunction(FHandle, WinTypes.SETDTR) else EscapeCommFunction(FHandle, WinTypes.CLRDTR); end; {-----------------------------------------------------------------------------------------------} function TCOM.GetDCD: boolean; var nStatus: cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin if GetCommModemStatus(FHandle, nStatus) then Result := (nStatus and MS_RLSD_ON) > 0; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetParity: String; begin case FDCB.Parity of 0: result := 'keine'; 1: result := 'ungerade'; 2: result := 'gerade'; 3: result := 'Markierung'; 4: result := 'Leerzeichen'; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetStopBits: String; begin case FDCB.Stopbits of 0: result := '1'; 1: result := '1,5'; 2: result := '2'; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetBaudRate: cardinal; begin result := FDCB.Baudrate; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetDataBits: byte; begin result := FDCB.ByteSize; end; {-----------------------------------------------------------------------------------------------} procedure TCOM.Close; begin if CloseHandle(FHandle) then { Schnittstelle schließen } FHandle := INVALID_HANDLE_VALUE; FError := GetLastError; end; {-----------------------------------------------------------------------------------------------} procedure TCOM.Reset; begin if not EscapeCommFunction(FHandle, WinTypes.RESETDEV) then FError := GetLastError; end; {-----------------------------------------------------------------------------------------------} function TCOM.RxFlush: boolean; begin if FHandle <> INVALID_HANDLE_VALUE then begin PurgeComm(FHandle, PURGE_RXCLEAR); FError := GetLastError; end; Result := FError = 0; end; {-----------------------------------------------------------------------------------------------} function TCOM.TxFlush: boolean; begin if FHandle <> INVALID_HANDLE_VALUE then begin PurgeComm(FHandle, PURGE_TXCLEAR); FError := GetLastError; end; Result := FError = 0; end; {-----------------------------------------------------------------------------------------------} function TCOM.Send(Data: Char): boolean; var nWritten, nCount: Cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin nCount := SizeOf(Data); if WriteFile(FHandle, Data, nCount, nWritten, nil) then begin Result := nCount = nWritten; end; FError := GetLastError; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.Send(Data: PChar; Len: cardinal): boolean; var nWritten, nCount: Cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin nCount := Len; if WriteFile(FHandle, Data^, nCount, nWritten, nil) then begin Result := nCount = nWritten; end; FError := GetLastError; end; end; {-----------------------------------------------------------------------------------------------} function TCOM.GetChar(var data: byte): boolean; var nCount, nRead: cardinal; begin Result := false; if FHandle <> INVALID_HANDLE_VALUE then begin nCount := SizeOf(data); if InBufUsed >= nCount then begin if ReadFile(FHandle, data, nCount, nRead, nil) then begin Result := nCount = nRead; end; end; FError := GetLastError; end; end; end.
unit Test.AsyncIO.Net.IP.Detail; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, AsyncIO.Net.IP.Detail, AsyncIO.Net.IP, AsyncIO.Detail, AsyncIO, NetTestCase; type // Test methods for class AsyncSocketStreamImpl TestAsyncSocketStreamImpl = class(TNetTestCase) strict private FService: IOService; FSocket: IPStreamSocket; FAsyncSocketStreamImpl: AsyncSocketStream; FHandlerExecuted: boolean; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetSocket; procedure TestAsyncReadSome; procedure TestAsyncWriteSome; end; implementation uses IPStreamSocketMock, AsyncIO.OpResults; procedure TestAsyncSocketStreamImpl.SetUp; begin FService := NewIOService; FSocket := TIPStreamSocketMock.Create(FService); FSocket.Bind(Endpoint(IPAddressFamily.v4, 0)); FSocket.Connect(Endpoint(IPv4Address.Loopback, 54321)); FAsyncSocketStreamImpl := NewAsyncSocketStream(FSocket); FHandlerExecuted := False; end; procedure TestAsyncSocketStreamImpl.TearDown; begin FAsyncSocketStreamImpl := nil; FSocket := nil; FService := nil; end; procedure TestAsyncSocketStreamImpl.TestGetSocket; var ReturnValue: IPStreamSocket; begin ReturnValue := FAsyncSocketStreamImpl.GetSocket; CheckSame(FSocket, ReturnValue); end; procedure TestAsyncSocketStreamImpl.TestAsyncReadSome; var Handler: IOHandler; Buffer: MemoryBuffer; data: TArray<Byte>; begin SetLength(data, 42); Buffer := data; Handler := procedure(const Res: OpResult; const BytesTransferred: UInt64) begin FHandlerExecuted := True; CheckTrue(Res.Success, 'Error: ' + Res.Message); CheckEquals(42, BytesTransferred, 'BytesTransferred incorrect'); end; FAsyncSocketStreamImpl.AsyncReadSome(Buffer, Handler); FService.Poll; CheckTrue(FHandlerExecuted, 'Handler failed to execute'); end; procedure TestAsyncSocketStreamImpl.TestAsyncWriteSome; var Handler: IOHandler; Buffer: MemoryBuffer; data: TArray<Byte>; begin SetLength(data, 42); Buffer := data; Handler := procedure(const Res: OpResult; const BytesTransferred: UInt64) begin FHandlerExecuted := True; CheckTrue(Res.Success, 'Error: ' + Res.Message); CheckEquals(42, BytesTransferred, 'BytesTransferred incorrect'); end; FAsyncSocketStreamImpl.AsyncWriteSome(Buffer, Handler); FService.Poll; CheckTrue(FHandlerExecuted, 'Handler failed to execute'); end; initialization // Register any test cases with the test runner RegisterTest(TestAsyncSocketStreamImpl.Suite); end.
unit RLDesign; interface uses Classes, TypInfo, Db, SysUtils, DesignEditors, DesignIntf, Forms, RLReport, RLConsts, RLUtils, RLTypes, RLAbout; type {$ifdef DELPHI5} IDesignerClass=IFormDesigner; {$else} IDesignerClass=IDesigner; {$endif} { TRLReportDesigner } TRLReportDesigner=class(TComponentEditor) protected // variables fReport:TRLReport; // custom methods procedure ShowAboutBox; virtual; public // constructors & destructors constructor Create(aComponent:TComponent; aDesigner:IDesignerClass); override; // override methods procedure Edit; override; procedure ExecuteVerb(Index:Integer); override; function GetVerb(Index:Integer):string; override; function GetVerbCount:integer; override; end; // property editors { TRLListEditor } TRLListEditor=class(TStringProperty) public function GetAttributes:TPropertyAttributes; override; procedure GetValues(Proc:TGetStrProc); override; // procedure GetValueList(List:TStrings); virtual; abstract; end; TRLDataEditor=class(TRLListEditor) public procedure GetValueList(List:TStrings); override; // function GetDataSource:TDataSource; virtual; abstract; end; TRLDataFieldEditor=class(TRLDataEditor) public function GetDataSource:TDataSource; override; end; TRLDataFieldsEditor=class(TRLDataEditor) public function GetDataSource:TDataSource; override; end; TRLPaperSizeEditor=class(TRLListEditor) public procedure GetValueList(List:TStrings); override; end; implementation { TRLReportDesigner } constructor TRLReportDesigner.Create(aComponent:TComponent; aDesigner:IDesignerClass); begin inherited; fReport:=TRLReport(aComponent); end; function TRLReportDesigner.GetVerb(Index:Integer):string; begin case Index of 0: result:=LS_AboutTheStr+' '+CS_ProductTitleStr+'...'; 1: result:='-'; 2: result:=LS_PreviewStr; end; end; function TRLReportDesigner.GetVerbCount:integer; begin result:=3; end; procedure TRLReportDesigner.ShowAboutBox; begin with TfrmRLAbout.Create(nil) do begin ShowModal; free; end; end; procedure TRLReportDesigner.Edit; begin fReport.Preview; TForm(fReport.Owner).Invalidate; end; procedure TRLReportDesigner.ExecuteVerb(Index:Integer); begin case Index of 0: ShowAboutBox; 1:; 2: Edit; end; end; function GetPropertyValue(Instance:TPersistent; const PropName:string):TPersistent; var PropInfo:PPropInfo; begin result :=nil; PropInfo:=TypInfo.GetPropInfo(Instance.ClassInfo,PropName); if (PropInfo<>nil) and (PropInfo^.PropType^.Kind=tkClass) then result:=TObject(GetOrdProp(Instance,PropInfo)) as TPersistent; end; { TRLListEditor } function TRLListEditor.GetAttributes:TPropertyAttributes; begin result:=[paValueList,paSortList,paMultiSelect]; end; procedure TRLListEditor.GetValues(Proc:TGetStrProc); var l:TStringList; i:integer; begin l:=TStringList.Create; try GetValueList(l); for i:=0 to l.Count-1 do Proc(l[i]); finally l.free; end; end; { TRLDataEditor } procedure TRLDataEditor.GetValueList(List:TStrings); var ds:TDataSource; begin ds:=GetDataSource; if (ds<>nil) and (ds.DataSet<>nil) then ds.DataSet.GetFieldNames(List); end; { TRLDataFieldEditor } function TRLDataFieldEditor.GetDataSource:TDataSource; begin result:=GetPropertyValue(GetComponent(0),'DataSource') as TDataSource; end; { TRLDataFieldsEditor } function TRLDataFieldsEditor.GetDataSource:TDataSource; var skipper:TRLCustomSkipper; begin skipper:=TRLGroup(GetComponent(0)).FindParentSkipper; if skipper<>nil then result:=skipper.DataSource else result:=nil; end; { TRLPaperSizeEditor } procedure TRLPaperSizeEditor.GetValueList(List:TStrings); var i:TRLPaperSize; v:string; begin for i:=low(TRLPaperSize) to high(TRLPaperSize) do begin v:=PaperInfoArray[i].Description; if PaperInfoArray[i].Emulated then v:=v+'*'; List.Add(v); end; end; end.
Uses Crt{,dos}; Const minyan:array [1..38] of byte=(50,40,27,36,34,24,21,31,24,22,25,66,52,48,14,4,9,1,4,7,3,3,3,2,14,3,150,31,42,8,4,5, 12,10,12,10,13,29); nums:array [1..9] of integer=(3814,5085,11440,12711,15253,16254,17795,21608,27963); engleter:string[28]=' TCDSVUZJYHFKNBXGPMERA,L;.OI'; hebleter:string[28]=' €‚ƒ„…†‡ˆ‰‹ŒŽ‘’”–—˜™šŠ“•'; // thanks to hebTx.html: const eng = "אבגדהוזחטיכלמנסעפצקרשתךףץםן"; Names:Array [1..39] Of String[13]=('תישארב','תומש','ארקיו','רבדמב','םירבד','עשוהי','םיטפוש','''א לאומש','''ב לאומש', '''א םיכלמ','''ב םיכלמ','היעשי','הימרי','לאקזחי','עשוה','לאוי','סומע','הידבוע','הנוי','הכימ','םוחנ','קוקבח','הינפצ', 'יגח','הירכז','יכאלמ','םילהת','ילשמ','בויא','םירישה ריש','תור','הכיא','תלהק','רתסא','לאינד','ארזע','הימחנ', '''א םימיה ירבד','''ב םימיה ירבד'); Posi:Array [1..40] Of Word=(0,1533,2743,3602,4890,5846,6502,7120,7931,8626,9443,10162,11453,12817,14090,14287,14360,14506, 14527,14575,14680,14727,14783,14836,14874,15085,15140,17667,18582,19652,19769,19854,20008,20230,20397,20754,21034,21439, 22382,23204); ZZ:Array [1..40] Of Integer=(1,2044,3712,4898,6614,8017,9033,10010,11295,12370,13653,14823,16550,18675,20560,20807,20905, 21110,21140,21210,21350,21408,21480,21559,21617,21931,22015,24568,25485,26583,26722,26851,27048,27335,27628,28222,28633, 29219,30431,31776); oo:array [#1..#2] of string[8]=('" š†…˜‡Ž',' Š˜’'); lessPsk:array [1..9] of string[45]=('ÿÕL§í>Åÿ@/Ç"»ì üd!HŸ¦gñ|á3‰ýCû%÷é?hÉ÷¸¿', 'ÿôü‰ÖŽïèù{±ßÐ ò''X‡ôÿ‰ýbþòÅeþ˜½|bÊ{°¿','jHÀ},ù3$ü‹þ|e䤿iROŒ²Úv|eôè¸ öÈŸbþ ¤¿', 'ÿÿÿ´‰…>É}¬( ò„øùµ9fKò¯ ùµ9qþLËíHÊéíaAý ¿','ÿÿüúÃŒ_µ0t¡ôÉúd}ëû%ýaføõ Nþ býRÊ~’0Ñן¥', 'ÿÈÃý+þ޶TúJ/…OÚŒàûJþ¸Ør¤Ÿ# ¿ú]ý ËüŸ¥ß','`Cõ1ߣ¬¡‡Æ—íHò²|iôøL‰ýïÔ>˜@Ÿ!HŸáÀù÷­Ÿ', 'ÿñ}¥I>÷3é’s¦|’ _µ8̾ҥß#$âü†''ÚT“ïwÚ°…Ÿ>W''?','ÿÀ}îû ˜÷‰ ð_{¾KÆgðà}€LÂý$+%ðEŸwÞ‘€?'); Type Recor=Record Perek,Pasuk:Byte; Txt:array [1..45] of byte; End; u=array [1..23204] of word; Var F,fil:File; value:^u; psukim,b,g,code,j,m,i,e,StPrk,StPsk,Stop,Place,Size2,X:Byte; a,s,w,p,xxx,find,Heb:String[72]; qw,prakim,k,l,s2,min,max,Count,Size,Demo:Integer; Reco:Recor; buf:array [1..1271] of recor; Fil2:File of recor; c:char; t:Text; { y,y2,y3,y4:word;} procedure decrypt2; begin m:=1; for i:=1 to 72 do begin s[i]:=chr(reco.txt[m] shr 3); {11111000} s[i+1]:=chr(reco.txt[m] and 7 shl 2 or reco.txt[m+1] shr 6); {00000111 + 11000000} s[i+2]:=chr(reco.txt[m+1] and 62 shr 1); {00111110} s[i+3]:=chr(reco.txt[m+1] and 1 shl 4 or reco.txt[m+2] shr 4); {00000001 + 11110000} s[i+4]:=chr(reco.txt[m+2] and 15 shl 1 or reco.txt[m+3] shr 7); {00001111 + 10000000} s[i+5]:=chr(reco.txt[m+3] and 124 shr 2); {01111100} s[i+6]:=chr(reco.txt[m+3] and 3 shl 3 or reco.txt[m+4] shr 5); {00000011 + 11100000} s[i+7]:=chr(reco.txt[m+4] and 31); {00011111} inc(m,5); inc(i,7); end; end; procedure decrypt; begin decrypt2; for i:=1 to 72 do if s[i]=#31 then inc(s[i]) else inc(s[i],128); end; procedure show; begin decrypt; place:=Pos(find,' '+s+' '); write(s:80); writeln(t,s:79); if place>0 then begin gotoxy(7+place,whereY-1); textattr:=white; write(find); gotoxy(1,wherey+byte(wherex>6)); textattr:=green; end; end; procedure error(s:string); begin textattr:=cyan; write(^j,'þ ',s,#7); textattr:=lightGray; writeln; halt; end; Procedure Adds(Ch:char;N:Byte); Begin Heb:=Ch+Heb; Inc(Code,N); End; Procedure FindNo; Begin Code:=31; Heb:=''; Repeat If Code+100<=Size2 Then Adds('—',100) Else If Code+90<=Size2 Then Adds('–',90) Else If Code+80<=Size2 Then Adds('”',80) Else If Code+70<=Size2 Then Adds('’',70) Else If Code+60<=Size2 Then Adds('‘',60) Else If Code+50<=Size2 Then Adds('',50) Else If Code+40<=Size2 Then Adds('Ž',40) Else If Code+30<=Size2 Then Adds('Œ',30) Else If Code+20<=Size2 Then Adds('‹',20) Else If size2-code in [15,16] Then Adds('ˆ',9) Else For X:=10 DownTo 1 Do If Code+X<=Size2 Then Adds(Chr(127+X),X); Until Code=Size2; If Length(Heb)>1 Then Insert('"',Heb,2) Else Heb:=''''+Heb; End; procedure writeInfo; begin Inc(Count); findno; textattr:=magenta; Write('(',heb,' ,'); write(t,'(',heb,' ,'); size2:=stprk; findno; WriteLn(heb,' ',Names[e],')'^j); writeln(t,heb,' ',names[e],')'^m^j); end; Begin If LastMode<2 Then TextMode(Co80); CheckBreak:=False; textattr:=lightgreen; textattr:=lightblue; for x:=1 to 8 do begin if x=8 then write(' ':18) else write(names[32+x]:13,32+x:3,' ³'); write(names[24+x]:11,24+x:3,' ³',names[16+x]:11,16+x:3,' ³',names[8+x]:11,8+x:3,' ³',names[x]:11,x:3); end; textattr:=lightred; WriteLn(^j'ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'); textattr:=lightmagenta; Writeln('מחרוזת או ערך מספרי לחיפוש -> '); repeat gotoxy(31,wherey-1); heb:=''; x:=wherex; repeat repeat c:=upcase(readkey); if c=#0 then begin c:=readkey; c:=#0; end; until c>#0; if c=#27 then begin heb:=''; clreol; end else if length(heb)<49 then if pos(c,engleter)>0 then heb:=hebleter[pos(c,engleter)]+heb else if c in ['0'..'9'] then heb:=heb+c; write(heb); gotoxy(x,wherey); if c=#8 then begin if heb[length(heb)] in ['0'..'9'] then dec(heb[0]) else delete(heb,1,1); write(heb,' '); gotoxy(x,wherey); end; until c=#13; writeln; until heb>''; w:=''; Val(Heb,Size,Demo); if demo>1 then val(copy(heb,1,demo-1),size,demo); find:=heb; c:=#2; If Demo>0 Then begin w:=heb; For X:=1 To Length(Heb) Do Case Heb[x] Of '€'..'‰':Inc(Size,Ord(Heb[X])-127); 'Š','‹':Inc(Size,20); 'Œ':Inc(Size,30); '','Ž':Inc(Size,40); '','':Inc(Size,50); '‘':Inc(Size,60); '’':Inc(Size,70); '“','”':Inc(Size,80); '•','–':Inc(Size,90); '—'..'š':Inc(Size,100*(Ord(Heb[X])-150)); End; textattr:=lightGreen; write(^j'חיפוש )מ(חרוזת או פסוק שווה )ע(רך'); repeat c:=upcase(readkey); until c in ['N','G','Ž','’']; if c in ['N','Ž'] then begin c:=#1; writeln('Žחרוזš'); while pos(' ',copy(find,2,length(find)-2))>0 do delete(find,pos(' ',copy(find,2,length(find)-2))+1,1); size:=0; { if find[length(find)] in ['0'..'9'] then error('אין לחפש ספרות');} for count:=1 to length(find) do if find[count]>='€' then inc(size); if size=0 then error('אין לחפש רווחים') else if size=1 then error('š‡€ š…€ ™”‡Œ ‰€'); (***) { size:=0; for count:=1 to length(find) do if find[count]=' ' then size:=0 else if size=10 then error('‰……š 11-Ž „‹…˜€„ „ŒŽ ™”‡Œ ‰€') else inc(size);} end else begin c:=#2; writeln('Š˜’ „……™ —…‘”'); end; gotoxy(31,wherey-3); clreol; textattr:=lightMagenta; if c=#2 then writeln(heb,^j^j) else writeln('"',find,'"'^j^j); end; if (c=#2) and (size<159) or (size>13639) then error('159-13639 הערך אינו בתחום'); writeln(^j); textattr:=lightcyan; Repeat GotoXY(1,WhereY-1); Write('˜”‘Ž ™”‡Œ -> '); ClrEol; ReadLn(Heb); Val(Heb,X,Demo); if demo>1 then val(copy(heb,1,demo-1),x,demo); Until x in [1..39]; GotoXY(14,WhereY-1); Writeln(names[x]); ClrEol; WriteLn(^j); textattr:=yellow; Repeat GotoXY(1,WhereY-1); Write(' ועד ספר )כולל( -> '); ClrEol; ReadLn(Heb); Val(Heb,Stop,Demo); if demo>1 then val(copy(heb,1,demo-1),stop,demo); Until stop in [1..39]; GotoXY(19,WhereY-1); Writeln(names[stop]); ClrEol; textattr:=red; if stop<x then error('טווח לא חוקי'); Count:=0; Assign(Fil2,'Bible.Txt'); assign(fil,'bible.txt'); if c=#2 then begin Assign(F,'Bible.Gim'); {$i-} Reset(F,46408); {$i+} if ioresult<>0 then error('Bible.Gim š‡‰š” š…’ˆ'); new(value); blockread(f,value^,1); {$i-} reset(fil2); {$i+} end else {$i-} Reset(Fil,59737); {$i+} if ioResult<>0 then error('Bible.Txt טעות בפתיחת'); writeln(^j'šŽ... àðà ä'^j); str(x,heb); str(stop,xxx); str(size,p); if c=#2 then assign(t,p+'-'+heb+'.'+xxx) else assign(t,'s-'+heb+'.'+xxx); xxx:=names[stop]; rewrite(t); writeln(t); s[0]:=#71; e:=1; { gettime(y,y2,y3,y4); settime(y,y2,0,0);} if c=#2 then begin prakim:=31; For Demo:=1 To 23204 Do begin if value^[demo]>16000 then begin psukim:=32; dec(value^[demo],16000); inc(prakim); end else inc(psukim); If (value^[demo]=Size) and (demo>posi[x]) and (demo<=posi[stop+1]) Then Begin while demo>posi[e+1] do inc(e); textAttr:=green; min:=ZZ[e]-1; max:=zz[e+1]-2; stprk:=prakim; for size2:=1 to e-1 do dec(stprk,minyan[size2]); size2:=psukim; repeat seek(fil2,(min+max) shr 1); read(fil2,reco); if (reco.perek>stprk) or (reco.perek=stprk) and (reco.pasuk>size2) then max:=(min+max) shr 1 else min:=(min+max) shr 1; until (reco.pasuk=size2) and (reco.perek=stprk); if filepos(fil2)>3 then begin seek(fil2,filepos(fil2)-4); repeat read(fil2,reco); until (reco.pasuk=size2) and (reco.perek=stprk); end; repeat decrypt; write(s:80); writeln(t,s:79); reco.pasuk:=253; if not eof(fil2) then read(fil2,reco); until reco.pasuk<>size2; writeInfo; End end end else begin seek(fil,(zz[x]-1) div 1271); l:=(filePOS(fil)-1)*1271; lessPsk[3,36]:=#9; lessPsk[3,43]:=#0; lessPsk[4,44]:=#0; lessPsk[4,25]:=#0; lessPsk[5,29]:=#26; lessPsk[6,32]:=#0; lessPsk[6,39]:=#0; lesspsk[8,17]:=#0; lessPsk[9,7]:=#0; a:=find; for i:=1 to length(find) do if a[i]=#32 then a[i]:=#31 else dec(a[i],128); b:=0; k:=1; blockRead(fil,buf,1); for j:=(zz[stop+1]-zz[x]+1271) div 1271 downto 0 do begin inc(l,1271); for k:=k to 1271 do begin reco:=buf[k]; decrypt2; qw:=1; while s[qw]=#31 do inc(qw); if (s[71]=chr(ord('‹')-128)) and (s[qw]=chr(ord('Œ')-128)) then begin { If Pos(a,''+s+'')>0 Then Begin} {*****} while l+k>=zz[e+1] do inc(e); if e in [x..stop] then begin stprk:=reco.perek; size2:=reco.pasuk; while (buf[k].pasuk=size2) and (buf[k].perek=stprk) and (k>0) do dec(k); inc(k); textattr:=green; if k=1 then begin {ä÷åã} for k:=1 to 9 do if nums[k]=l+1 then begin for g:=1 to 45 do reco.txt[g]:=byte(lesspsk[k,g]); show; k:=9; end; k:=1; end; repeat reco:=buf[k]; show; inc(k); until (buf[k].pasuk<>size2) or (k=1272); if k<>1272 then dec(k) else begin for k:=1 to 9 do if nums[k]=l+1272 then {€„} b:=k; k:=1271; end; if b=0 then writeInfo; end else b:=0; End; end; k:=1; if eof(fil) then j:=0 else blockRead(fil,buf,1); if b>0 then begin reco:=buf[1]; show; writeinfo; b:=0; k:=2; end; end; end; { gettime(y,y2,y3,y4); writeln(y3:4,y4:4);} textattr:=blue; heb:='ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ'; Writeln(heb,heb,heb,heb); if count>0 then WriteLn(t,heb,heb,heb,heb); textattr:=cyan; p:=find; if c=#1 then begin write('"'); if count>0 then write(t,'"'); end else str(size,find); write(find,oo[c],' הופעות ל'); If Count>0 Then begin writeln(t,find,oo[c],'Œäåôòåú',count); Write(Count); writeln(t,xxx,' ƒ’… ',names[x],'Ž'); if (c=#2) and (w>'') then writeln(t,'"',w,'הקטע השווה בערכו לפסוקים הנ"ל הוא "'); end Else Write('…€–ސ €Œ'); close(t); if count=0 then erase(t); textattr:=lightGray; writeln; End.
unit TextEditor.Caret.Offsets; interface uses System.Classes; type TTextEditorCaretOffsets = class(TPersistent) strict private FLeft: Integer; FOnChange: TNotifyEvent; FTop: Integer; procedure DoChange(const ASender: TObject); procedure SetLeft(const AValue: Integer); procedure SetTop(const AValue: Integer); public constructor Create; procedure Assign(ASource: TPersistent); override; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Left: Integer read FLeft write SetLeft default 0; property Top: Integer read FTop write SetTop default 0; end; implementation constructor TTextEditorCaretOffsets.Create; begin inherited; FLeft := 0; FTop := 0; end; procedure TTextEditorCaretOffsets.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCaretOffsets) then with ASource as TTextEditorCaretOffsets do begin Self.FLeft := FLeft; Self.FTop := FTop; Self.DoChange(Self); end else inherited Assign(ASource); end; procedure TTextEditorCaretOffsets.DoChange(const ASender: TObject); begin if Assigned(FOnChange) then FOnChange(ASender); end; procedure TTextEditorCaretOffsets.SetLeft(const AValue: Integer); begin if FLeft <> AValue then begin FLeft := AValue; DoChange(Self); end; end; procedure TTextEditorCaretOffsets.SetTop(const AValue: Integer); begin if FTop <> AValue then begin FTop := AValue; DoChange(Self); end; end; end.
unit UDBConnectionIntf; interface uses Data.SQLExpr, FireDAC.Comp.Client; type IDBConnection = Interface(IInterface) ['{83006FF8-A243-4D8D-825A-D04089C0CB2C}'] function getDefaultConnection: TFDConnection; End; implementation end.
program problem503; {Deklarasi konstanta} const {Nama file input} FNAME = 'result.txt'; {Deklarasi tipe variable} type {Matriks karakter yang dinamik} MatrixChar = array of array of char; {Kamus Global} var f: text; x: string; n, i, j: integer; map: MatrixChar; win: boolean; winner: char; function cekBaris(map: MatrixChar; length, baris: integer): boolean; {Menerima input berupa matriks karakter, length yang merupakan panjang sisi matriks, baris yang merupakan indeks baris yang akan dicek, indeks dimulai dari 0. Fungsi akan mengembalikan true jika baris yang dicek memiliki karakter yang sama dan mengembalikan false jika ada yang tidak sama.} {Kamus Lokal} var i: integer; diff: boolean; {Algoritma Lokal} begin i:= 0; diff:= false; while((not diff) and (i <= (length-2))) do begin if(map[baris][i] = map[baris][i+1]) then begin i:= i+1 end else begin diff := true; end; end; cekBaris := not diff; end; function cekKolom(map: MatrixChar; length, kolom: integer): boolean; {Menerima input berupa matriks karakter, length yang merupakan panjang sisi matriks, kolom yang merupakan indeks kolom yang akan dicek, indeks dimulai dari 0. Fungsi akan mengembalikan true jika kolom yang dicek memiliki karakter yang sama dan mengembalikan false jika ada yang tidak sama.} {Kamus Lokal} var i: integer; diff: boolean; {Algoritma Lokal} begin i:= 0; diff:= false; while((not diff) and (i <= (length-2))) do begin if(map[i][kolom] = map[i+1][kolom]) then begin i:= i+1 end else begin diff := true; end; end; cekKolom := not diff; end; function cekDiagonal(map: MatrixChar; length: integer): boolean; {Menerima input berupa matriks karakter, length yang merupakan panjang sisi matriks, Fungsi akan mengembalikan true jika diagonal matriks memiliki karakter yang sama dan mengembalikan false jika ada yang tidak sama.} {Kamus Lokal} var i: integer; diff1, diff2: boolean; {Algoritma Lokal} begin i:= 0; diff1:= false; while((not diff1) and (i <= (length-2))) do begin if(map[i][i] = map[i+1][i+1]) then begin i:= i+1 end else begin diff1 := true; end; end; i:=0; diff2:= false; while((not diff2) and (i <= (length-2))) do begin if(map[i][length-i-1] = map[i+1][length-i-2]) then begin i:= i+1 end else begin diff2 := true; end; end; cekDiagonal := (not diff1) or (not diff2); end; {Algoritma Utama} begin {Pembacaan File dan memasukkan ke dalam matriks} assign(f, FNAME); reset(f); readln(f, x); n := Integer(x[1])-48; if (n > 0) then begin SetLength(map, n); for i:= 0 to (n-1) do begin SetLength(map[i], n); end; i:=0; while not eof(f) do begin readln(f, x); for j:= 0 to (n-1) do begin map[i][j]:= x[j+1]; end; i := i+1; end; end; writeln('result loaded!'); close(f); {Pencarian dalam matriks} if (n > 0) then begin win:= false; i:=0; winner := '-'; if (cekDiagonal(map, n)) then begin winner:= map[1][1]; end else begin while ((not win) and (i < n)) do begin if (cekBaris(map, n, i)) then begin winner := map[i][1]; win := true; end else if (cekKolom(map, n, i)) then begin winner := map[1][i]; win:= true; end else begin i:= i+1; end; end; end; {Penentuan pemenang} if(winner = 'o') then begin writeln('Pemenangnya adalah Anda'); end else if (winner = 'x') then begin writeln('Pemenangnya adalah Tuan Krab'); end else begin writeln('Tidak ada pemenang'); end; end else begin writeln('Tidak ada pemenang'); end; end.