text
stringlengths
14
6.51M
{Ingresar M números naturales y luego a. Contar e informar cuántos elementos son pares, impares y nulos. b. Multiplicar todos los componentes de posición par por un número ingresado por teclado, validando que sea diferente de 0, mostrar por pantalla el conjunto de números resultante. c. Mostrar por pantalla cuál es el lugar donde aparece el máximo (en caso de que este valor aparezca más de una vez, considerar el primero). Ejemplo: números : 3 4 8 1 24 3 1 24 15 24  Máximo = 24 lugar= 5} Program naturales; Type TV = array[1..100] of byte; Var Vec:TV; M:byte; Procedure LugarMaximo(Vec:TV; M:byte); Var i,Max,MaxI:byte; begin Max:= 0; MaxI:= 0; For i:= 1 to M do begin if (Vec[i] > Max) then begin Max:= Vec[i]; MaxI:= i; end; end; writeln; writeln('El maximo numero es ',Max,' en el lugar: ',MaxI); end; Procedure Multiplica(M:byte; Var Vec:TV); Var i:byte; Num:word; begin write('Ingrese un numero para multiplicarlo con los de posiciones pares: ');readln(Num); //Para multiplicarlo con todos los numeros de posición par. i:= 2; while (Num <> 0) do begin If (i <= M) then begin writeln('El numero multiplicado es: ',Num* Vec[i]); i:= i + 2 end; end; {For i:= 1 to M do //Para multiplicarlo individualmente. begin if (i MOD 2 = 0) then begin write('Ingrese un numero para multiplicarlo con el de la posicion ',i,' : ');readln(Num); if (Num <> 0) then begin Num:= Vec[i] * Num; writeln(Num); end; end; end;} end; Procedure Informa(Vec:TV; M:byte); Var i,ContP,ContI,ContN:byte; begin ContP:= 0; ContI:= 0; ContN:= 0; For i:= 1 to M do begin If (Vec[i] = 0) then //Debe ir primera esta condición de nulo porque si lo ponemos al final puede contarlo mal. ContN:= ContN + 1 Else if (Vec[i] MOD 2 = 0) then ContP:= ContP + 1 Else ContI:= ContI + 1; end; writeln('La cantidad de pares es: ',ContP); writeln('La cantidad de impares es: ',ContI); writeln('La cantidad de nulos es: ',ContN); end; Procedure IngresaNumeros(Var Vec:TV); Var i,M:byte; begin write('Ingrese la cantidad de numeros: ');readln(M); For i:= 1 to M do begin write('Ingrese un numero: ');readln(Vec[i]); end; LugarMaximo(Vec,M); writeln; Informa(Vec,M); writeln; Multiplica(M,Vec); end; Begin IngresaNumeros(Vec); Informa(Vec,M); Multiplica(M,Vec); end.
unit uTranslateUtils; interface uses System.SysUtils, System.DateUtils, System.Math, Dmitry.Utils.System, uTranslate; function SizeInText(Size: Int64): string; function SpeedInText(Speed: Extended): string; function TimeIntervalInString(Time: TTime): string; function NumberToShortNumber(Number: Integer): string; implementation function SpeedInText(Speed: Extended): string; begin if Speed > 100 then Result := IntToStr(Round(Speed)) else if Speed > 10 then Result := FormatFloat('##.#', Speed) else Result := FormatFloat('0.##', Speed); end; function SizeInText(Size: Int64): string; begin if Size <= 1024 then Result := IntToStr(Size) + ' ' + TA('Bytes'); if (Size > 1024) and (Size <= 1024 * 999) then Result := FloatToStrEx(Size / 1024, 3) + ' ' + TA('Kb'); if (Size > 1024 * 999) and (Size <= 1024 * 1024 * 999) then Result := FloatToStrEx(Size / (1024 * 1024), 3) + ' ' + TA('Mb'); if (Size > 1024 * 1024 * 999) and ((Size div 1024) <= 1024 * 1024 * 999) then Result := FloatToStrEx(Size / (1024 * 1024 * 1024), 3) + ' ' + TA('Gb'); if (Size div 1024 > 1024 * 1024 * 999) then Result := FloatToStrEx((Size / (1024 * 1024)) / (1024 * 1024), 3) + ' ' + TA('Tb'); end; function TimeIntervalInString(Time: TTime): string; var Y, MM, Days, H, M, S, MS: Word; SD, SH, SM, SS: string; function RoundSeconds(Sec: Word): Word; begin Result := Ceil(S / 5) * 5; end; begin DecodeDateTime(Time, Y, MM, Days, H, M, S, MS); Days := Min(30, (Days - 1) + (Y - 1) * 12 * 365 + (MM - 1) * 30); S := RoundSeconds(S); SD := IntToStr(Days) + ' ' + IIF(Days <> 1, TA('days', 'Global'), TA('day', 'Global')); SH := IntToStr(H) + ' ' + IIF(H <> 1, TA('hours', 'Global'), TA('hour', 'Global')); SM := IntToStr(M) + ' ' + IIF(M <> 1, TA('minutes', 'Global'), TA('minute', 'Global')); SS := IntToStr(S) + ' ' + IIF(S <> 1, TA('seconds', 'Global'), TA('second', 'Global')); if Days > 0 then Result := SD + ', ' + SH else if H > 0 then Result := SH + ', ' + SM else if M > 0 then Result := SM + ', ' + SS else Result := SS; if Length(Result) > 0 then Result[1] := UpCase(Result[1]); end; function NumberToShortNumber(Number: Integer): string; begin if Number > 10000000 then Exit(IntToStr(Number div 1000000) + 'M+'); if Number > 10000 then Exit(IntToStr(Number div 1000) + 'K+'); Result := IntToStr(Number); end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Math, TeeProcs, TeEngine, Chart, DB, DBCtrls, DbChart, ADODB, Series, BubbleCh; type TForm1 = class(TForm) lbAtom: TLabel; Memo1: TMemo; ADOConnection1: TADOConnection; ADOTable1: TADOTable; DBChart1: TDBChart; DataSource1: TDataSource; DBLookupListBox1: TDBLookupListBox; ADOQuery1: TADOQuery; Series2: TLineSeries; Series1: TPointSeries; procedure DBLookupListBox1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DBChart1Click(Sender: TObject); private { Private declarations } function volume(varA: Real): real; function surface(varA: Real): real; function coulomb(varA: Real; varZ: integer): real; function asymmetry(varA: Real; varZ: integer): real; function pairing(varA: Real; varZ: integer): real; function getSEMF(varA: Real; varZ: Integer): real; procedure generateChart(); public { Public declarations } Z: Integer; A: Real; end; const av = 15.5; ass = 17.8; ac = 0.691; aa = 23; ap = 34; var Form1: TForm1; implementation {$R *.dfm} function TForm1.volume(varA: Real): real; var output: real; begin output := av * varA; volume := output; Memo1.Lines.Add('Volume : '+FloatToStr(output)); end; function TForm1.surface(varA: Real): real; var output: real; begin output := ass * power(varA, 2/3); surface := output; Memo1.Lines.Add('Surface : '+FloatToStr(output)); end; function TForm1.coulomb(varA: Real; varZ: integer): real; var output: real; begin output := ac * varZ * (varZ - 1) * power(varA,-1/3); coulomb := output; Memo1.Lines.Add('Coulomb : '+FloatToStr(output)); end; function TForm1.asymmetry(varA: Real; varZ: integer): real; var output: real; begin output := ass * power(varA-2*varZ,2) / varA; asymmetry := output; Memo1.Lines.Add('Asymmetry : '+FloatToStr(output)); end; function TForm1.getSEMF(varA: Real; varZ: Integer): real; var output: real; begin output := volume(A) - surface(A) - coulomb(A,Z) - asymmetry(A,Z) + pairing(A,Z); getSEMF := output; end; procedure TForm1.generateChart; var SEMF: real; begin DBChart1.Series[0].Clear; ADOTable1.First; while not ADOTable1.Eof do begin Z := ADOTable1.FieldByName('Z').AsInteger; A := ADOTable1.FieldByName('A').AsFloat; SEMF := getSEMF(A,Z); DBChart1.Series[0].AddXY(A, SEMF/A); ADOTable1.Next; end; end; function TForm1.pairing(varA: Real; varZ: integer): real; var p,n,pm,nm: integer; output: real; begin p := varZ; n := (floor(varA) - varZ); pm := p mod 2; nm := n mod 2; Memo1.Lines.Add('Proton : '+IntToStr(p)); Memo1.Lines.Add('Netron : '+IntToStr(n)); if(pm <> nm) then output := 0 else output := ap * power(varA, -3/4); if(pm = 1) then output := -output; pairing := output; Memo1.Lines.Add('Pairing : '+FloatToStr(output)); end; procedure TForm1.DBLookupListBox1Click(Sender: TObject); var id: integer; SEMF: real; begin id := DBLookupListBox1.KeyValue; ADOQuery1.SQL.Text := 'SELECT A,Z FROM Atom WHERE ID = '+IntToStr(id); ADOQuery1.Active := true; A := ADOQuery1.FieldByName('A').AsFloat; Z := ADOQuery1.FieldByName('Z').AsInteger; Memo1.Lines.Clear; Memo1.Lines.Add('Nomor Atom : '+IntToStr(Z)); Memo1.Lines.Add('Nomor Massa : '+FloatToStr(A)); SEMF := getSEMF(A,Z); Memo1.Lines.Add('SEMF : '+FloatToStr(SEMF)); Memo1.Lines.Add('B/A : '+FloatToStr(SEMF/A)); DBChart1.Series[1].Clear; DBChart1.Series[1].AddXY(A,SEMF/A); end; procedure TForm1.FormCreate(Sender: TObject); begin generateChart; Memo1.Lines.Clear; end; procedure TForm1.DBChart1Click(Sender: TObject); begin ShowMessage('Program ini dibugat dalam rangka iseng-iseng bersama Sahori setelah mengerjakan tugas orang.. :)'); end; end.
unit CFColorPad; interface uses Windows, Classes, Controls, Graphics, CFControl, CFButton, CFEdit; type TCFColorPad = class(TCFCustomControl) strict private FPad: TBitmap; FSelect, FNearColor1, FNearColor2, FNearColor3, FNearColor4: TColor; FOnChange: TNotifyEvent; procedure SetSelect(const Value: TColor); virtual; protected procedure DoChange; procedure PaintPad(const ACanvas: TCanvas); virtual; procedure CreateHandle; override; procedure DrawControl(ACanvas: TCanvas); override; procedure UpdateView; virtual; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; property Pad: TBitmap read FPad; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; //procedure DrawTo(const ACanvas: TCanvas); override; property Select: TColor read FSelect write SetSelect; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TCFRichColorPad = class(TCFColorPad) private FBtnOk: TCFButton; FEdtR, FEdtG, FEdtB: TCFEdit; FCircleWidth: Byte; // 色环大小 procedure PaintColorCircle(const ABitmap: TBitmap); protected procedure PaintPad(const ACanvas: TCanvas); override; public constructor Create(AOwner: TComponent); override; end; implementation { TCFColorPad } const PadWidth = 20; PadSpliter = 5; constructor TCFColorPad.Create(AOwner: TComponent); begin inherited Create(AOwner); Color := GBackColor; FSelect := clRed;// Color; FPad := TBitmap.Create; FNearColor1 := clBtnFace; FNearColor2 := clGrayText; FNearColor3 := clHighlight; FNearColor4 := clActiveBorder; Width := PadSpliter * 5 + PadWidth * 4; Height := Width + PadSpliter + PadWidth; end; procedure TCFColorPad.CreateHandle; begin inherited; UpdateView; end; destructor TCFColorPad.Destroy; begin FPad.Free; inherited Destroy; end; procedure TCFColorPad.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TCFColorPad.DrawControl(ACanvas: TCanvas); begin ACanvas.Draw(0, 0, FPad); end; //procedure TCFColorPad.DrawTo(const ACanvas: TCanvas); //begin // PaintPad(ACanvas); //end; procedure TCFColorPad.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; Select := FPad.Canvas.Pixels[X, Y]; DoChange; end; procedure TCFColorPad.PaintPad(const ACanvas: TCanvas); var vLeft, vTop: Integer; begin ACanvas.Brush.Color := Color; ACanvas.FillRect(Rect(0, 0, Width, Height)); if BorderVisible then begin ACanvas.Pen.Color := GBorderColor; with ACanvas do begin MoveTo(0, 0); LineTo(Width - 1, 0); LineTo(Width - 1, Height - 1); LineTo(0, Height - 1); LineTo(0, 0); end; end; // 第1行,4个近期使用 vLeft := PadSpliter; vTop := PadSpliter; ACanvas.Brush.Color := FNearColor1; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := FNearColor2; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := FNearColor3; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := FNearColor4; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); // 第2行 4个 vLeft := PadSpliter; vTop := vTop + PadWidth + PadSpliter; ACanvas.Brush.Color := clRed; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clGreen; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clBlue; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clYellow; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); // 第3行 4个 vLeft := PadSpliter; vTop := vTop + PadWidth + PadSpliter; ACanvas.Brush.Color := clBlack; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clWhite; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clOlive; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clLime; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); // 第4行 4个 vLeft := PadSpliter; vTop := vTop + PadWidth + PadSpliter; ACanvas.Brush.Color := clNavy; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clAqua; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clWebOrange; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clInfoBk; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); // 第5行 4个 vLeft := PadSpliter; vTop := vTop + PadWidth + PadSpliter; ACanvas.Brush.Color := $00400080; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := $00804000; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := clTeal; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); vLeft := vLeft + PadWidth + PadSpliter; ACanvas.Brush.Color := $008000FF; ACanvas.FillRect(Bounds(vLeft, vTop, PadWidth, PadWidth)); end; procedure TCFColorPad.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; UpdateView; end; procedure TCFColorPad.SetSelect(const Value: TColor); begin if FSelect <> Value then begin FSelect := Value; UpdateView; end; end; procedure TCFColorPad.UpdateView; begin if not HandleAllocated then Exit; if not Assigned(FPad) then Exit; FPad.SetSize(Width, Height); PaintPad(FPad.Canvas); end; { TCFRichColorPad } constructor TCFRichColorPad.Create(AOwner: TComponent); begin inherited Create(AOwner); FCircleWidth := Height; Width := Width + FCircleWidth - PadSpliter; Height := Height + PadSpliter + PadWidth + 20 + PadSpliter; FEdtR := TCFEdit.Create(Self); FEdtR.Width := 30; FEdtR.Parent := Self; FEdtR.Left := PadSpliter; FEdtR.Top := Height - PadSpliter - FEdtR.Height; FEdtG := TCFEdit.Create(Self); FEdtG.Width := 30; FEdtG.Parent := Self; FEdtG.Left := FEdtR.Left + FEdtR.Width + PadSpliter; FEdtG.Top := FEdtR.Top; FEdtB := TCFEdit.Create(Self); FEdtB.Width := 30; FEdtB.Parent := Self; FEdtB.Left := FEdtG.Left + FEdtG.Width + PadSpliter; FEdtB.Top := FEdtR.Top; FBtnOk := TCFButton.Create(Self); FBtnOk.Height := FEdtB.Height; FBtnOk.Width := 50; FBtnOk.Text := '确定'; FBtnOk.Parent := Self; FBtnOk.Left := FEdtB.Left + FEdtB.Width + PadSpliter; FBtnOk.Top := FEdtB.Top; end; procedure TCFRichColorPad.PaintColorCircle(const ABitmap: TBitmap); var i, j, x, y: Integer; vRadius: Integer; vPerimeter, vArc, vDegree, vStep: Double; vR, vG, vB: byte; vColor: TColor; begin vRadius := Round(ABitmap.Width / 2); vR := 255; vG := 0; vB := 0; with ABitmap do begin pixelFormat := pf24bit; Canvas.Brush.Color := RGB(vR,vG,vB); x := ABitmap.Width + 1; y := Round(vRadius) + 1; Canvas.FillRect(Rect(ABitmap.Width, Round(vRadius),x,y)); for j := 0 to ABitmap.Width do begin vPerimeter := (ABitmap.Width - j) * PI + 1; vArc := vPerimeter / 6; vStep := ( 255 * 6 ) / vPerimeter ; // 颜色渐变步长 for i := 0 to Round(vPerimeter) - 1 do begin vDegree := 360 / vPerimeter * i; x := Round(cos(vDegree * PI / 180) * (ABitmap.Width - j + 1) / 2) + vRadius; // 数学公式,最后加上的是圆心点 y := Round(sin(vDegree * PI / 180) * (ABitmap.Width - j + 1) / 2) + vRadius; if (vDegree > 0) and (vDegree <= 60) then begin vR := 255; vG := 0; vB := Round(vStep * i); end; if (vDegree > 60) and (vDegree <= 120) then begin if vPerimeter / 3 / 120 * (vDegree - 60) > 1.0 then vR := 255 - Round(vStep * (i - vArc)) else vR := 255 - Round(vStep * Abs(i - vArc)); vG := 0; vB := 255; end; if (vDegree > 120) and (vDegree <= 180) then begin vR := 0; if vPerimeter / 3 / 120 * (vDegree - 120) > 1.0 then vG := Round(vStep * (i - 2 * vArc)) else vG := Round(vStep * Abs(i - 2 * vArc)); vB := 255; end; if (vDegree > 180) and (vDegree <= 240) then begin vR := 0; vG := 255; if vPerimeter / 3 / 120 * (vDegree - 120) > 1.0 then vB := 255 - Round(vStep * (i - vPerimeter / 2)) else vB := 255 - Round(vStep * Abs(i - vPerimeter / 2)); end; if (vDegree > 240) and (vDegree <= 300) then begin if vPerimeter / 3 / 120 * (vDegree - 240) > 1.0 then vR := Round(vStep * (i - 4 * vArc)) else vR := Round(vStep * Abs(i - 4 * vArc)); vG := 255; vB := 0; end; if (vDegree > 300) and (vDegree <= 360) then begin vR := 255; if vPerimeter / 3 / 120 * (vDegree - 300) > 1.0 then vG := 255 - Round(vStep * (i - 5 * vArc)) else vG := 255 - Round(vStep * Abs(i - 5 * vArc)); vB := 0; end; vColor := RGB(Round(vR + (255 - vR) / ABitmap.Width * j), Round(vG + (255 - vG) / ABitmap.Width * j), Round(vB + (255 - vB) / ABitmap.Width * j)); Canvas.Brush.Color := vColor; //为了绘制出来的圆好看,分成四个部分进行绘制 if (vDegree >= 0) and (vDegree <= 45) then Canvas.FillRect(Rect(x, y, x - 2, y - 1)); if (vDegree > 45) and (vDegree <= 135) then Canvas.FillRect(Rect(x, y, x - 1, y - 2)); if (vDegree > 135) and (vDegree <= 225) then Canvas.FillRect(Rect(x, y, x + 2, y + 1)); if (vDegree > 215) and (vDegree <= 315) then Canvas.FillRect(Rect(x, y, x + 1, y + 2)); if (vDegree > 315) and (vDegree <= 360) then Canvas.FillRect(Rect(x, y, x - 2, y - 1)); end; end; end; end; procedure TCFRichColorPad.PaintPad(const ACanvas: TCanvas); var vBitmap: TBitmap; i, vW: Integer; vR: Byte; begin inherited PaintPad(ACanvas); // 色环 vBitmap := TBitmap.Create; try vBitmap.SetSize(FCircleWidth - PadSpliter - PadSpliter, FCircleWidth - PadSpliter - PadSpliter); PaintColorCircle(vBitmap); ACanvas.Draw(Width - FCircleWidth + PadSpliter, PadSpliter, vBitmap); finally vBitmap.Free; end; // 灰度 vW := Width - PadSpliter - PadSpliter; for i := PadSpliter to Width - PadSpliter do begin vR := 255 - Round((i - PadSpliter) / vW * 255); ACanvas.Pen.Color := RGB(vR, vR, vR); ACanvas.MoveTo(i, Height - PadSpliter - FEdtR.Height - PadSpliter - PadWidth); ACanvas.LineTo(i, Height - PadSpliter - FEdtR.Height - PadSpliter); end; FEdtR.PaintTo(ACanvas, FEdtR.Left, FEdtR.Top); FEdtG.PaintTo(ACanvas, FEdtG.Left, FEdtG.Top); FEdtB.PaintTo(ACanvas, FEdtB.Left, FEdtB.Top); end; end.
unit Response; interface uses Response.Intf, REST.Client, System.SysUtils, System.JSON, System.Classes, Character; type TResponse = class(TInterfacedObject, IResponse) private FRESTResponse: TRESTResponse; function Content: string; function ContentLength: Cardinal; function ContentType: string; function ContentEncoding: string; function StatusCode: Integer; function ErrorMessage: string; function RawBytes: TBytes; function JSONValue: TJSONValue; function Headers: TStrings; function JSONText:string; procedure RootElement(const PRootElement:String); function StripNonJson(s: string): string; public constructor Create(const ARESTResponse: TRESTResponse); end; implementation constructor TResponse.Create(const ARESTResponse: TRESTResponse); begin FRESTResponse := ARESTResponse; end; function TResponse.ErrorMessage: string; begin Result := ''; if (FRESTResponse.Status.ClientErrorBadRequest_400) or (FRESTResponse.Status.ClientErrorUnauthorized_401) or (FRESTResponse.Status.ClientErrorForbidden_403) or (FRESTResponse.Status.ClientErrorNotFound_404) or (FRESTResponse.Status.ClientErrorNotAcceptable_406) or (FRESTResponse.Status.ClientErrorDuplicate_409) then begin Result := FRESTResponse.StatusText; end; end; function TResponse.Content: string; begin Result := FRESTResponse.Content; end; function TResponse.Headers: TStrings; begin Result := FRESTResponse.Headers; end; function TResponse.ContentEncoding: string; begin Result := FRESTResponse.ContentEncoding; end; function TResponse.ContentLength: Cardinal; begin Result := FRESTResponse.ContentLength; end; function TResponse.ContentType: string; begin Result := FRESTResponse.ContentType; end; function TResponse.JSONText: string; begin Result := StripNonJson(FRESTResponse.JSONText); end; function TResponse.JSONValue: TJSONValue; begin Result := FRESTResponse.JSONValue; end; function TResponse.RawBytes: TBytes; begin Result := FRESTResponse.RawBytes; end; procedure TResponse.RootElement(const PRootElement:String); begin FRESTResponse.RootElement := PRootElement; end; function TResponse.StatusCode: Integer; begin Result := FRESTResponse.StatusCode; end; function TResponse.StripNonJson(s: string): string; var ch: char; inString: boolean; begin Result := ''; inString := false; for ch in s do begin if ch = '"' then inString := not inString; if ch.IsWhiteSpace and not inString then continue; Result := Result + ch; end; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2012 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls, System.Sensors; type TForm4 = class(TForm) lblLatitude: TLabel; etLatitude: TEdit; lblLongitude: TLabel; etLongitude: TEdit; chkActivateManager: TCheckBox; chkActivateSensor: TCheckBox; procedure chkActivateManagerChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkActivateSensorChange(Sender: TObject); private { Private declarations } FManager: TSensorManager; FSensor: TCustomLocationSensor; public { Public declarations } procedure LocationHandler(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); end; var Form4: TForm4; implementation {$R *.fmx} procedure TForm4.chkActivateManagerChange(Sender: TObject); var Sensors: TSensorArray; Sensor: TCustomLocationSensor; Activated: Boolean; Found: Boolean; begin Activated := chkActivateManager.IsChecked; FManager.Active := Activated; chkActivateSensor.Enabled := Activated; Found := Activated; if Activated then begin Sensors := FManager.GetSensorsByCategory(TSensorCategory.Location); Found := Length(Sensors) > 0; if Found then begin FSensor := Sensors[0] as TCustomLocationSensor; FSensor.OnLocationChanged := LocationHandler; FSensor.Optimize := True; end; end; if not Found then FSensor := nil; end; procedure TForm4.chkActivateSensorChange(Sender: TObject); begin if Assigned(FSensor) then if chkActivateSensor.IsChecked then FSensor.Start else FSensor.Stop; end; procedure TForm4.FormCreate(Sender: TObject); begin FManager := TSensorManager.Current; chkActivateManager.Enabled := FManager.CanActivate; end; procedure TForm4.LocationHandler(Sender: TObject; const OldLocation, NewLocation: TLocationCoord2D); begin etLatitude.Text := FloatToStr(NewLocation.Latitude); etLongitude.Text := FloatToStr(NewLocation.Longitude); end; end.
unit Objekt.DHLManifestResponse; interface uses System.SysUtils, System.Classes, Objekt.DHLVersionResponse, Objekt.DHLStatusinformation; type TDHLManifestResponse = class private fVersion: TDHLVersionResponse; fManifestData: string; fStatus: TDHLStatusinformation; public constructor Create; destructor Destroy; override; property Version: TDHLVersionResponse read fVersion write fVersion; property Status: TDHLStatusinformation read fStatus write fStatus; property ManifestData: string read fManifestData write fManifestData; end; implementation { TDHLManifestResponse } constructor TDHLManifestResponse.Create; begin fVersion := TDHLVersionResponse.Create; fStatus := TDHLStatusinformation.Create; fManifestData := ''; end; destructor TDHLManifestResponse.Destroy; begin FreeAndNil(fVersion); FreeAndNil(fStatus); inherited; end; end.
unit Gerenciador.form; interface uses System.Classes, Vcl.ExtCtrls, Vcl.Forms, System.Generics.Collections; Type IGerenciadorForm = interface ['{79805920-579A-45E8-9FB1-5B14FB69B694}'] function AddForm(key : String; Value : TComponentClass; const Parent : TPanel; Index : Boolean = false) : IGerenciadorForm; function GetForm(Value : String) : TForm; function GetFormIndex : TForm; function RemoveForm(Value : String) : IGerenciadorForm; end; TGerenciadorForm = class(TComponent, IGerenciadorForm) private { private declarations } FormIndex : TForm; ListaForm : TObjectDictionary<String, TForm>; protected { protected declarations } public { public declarations } constructor Create; destructor Destroy; override; function AddForm(key : String; Value : TComponentClass; const Parent : TPanel; Index : Boolean = false) : IGerenciadorForm; function GetForm(Value : String) : TForm; function GetFormIndex : TForm; function RemoveForm(Value : String) : IGerenciadorForm; class function New : IGerenciadorForm; published { published declarations } end; var _Gerenciador : iGerenciadorForm; implementation uses System.SysUtils; { TGerenciadorForm } function TGerenciadorForm.AddForm(key: String; Value: TComponentClass; const Parent: TPanel; Index: Boolean): IGerenciadorForm; var aForm :TForm; begin Result := Self; if not ListaForm.TryGetValue(key, aForm) then begin Application.CreateForm(Value, aForm); aForm.Caption := key; ListaForm.Add(key, aForm); end; aForm.Parent := Parent; aForm.Show; if Index then FormIndex := aForm; end; constructor TGerenciadorForm.Create; begin ListaForm := TObjectDictionary<String, TForm>.Create; end; destructor TGerenciadorForm.Destroy; begin FreeAndNil(ListaForm); inherited; end; function TGerenciadorForm.GetForm(Value: String): TForm; begin ListaForm.TryGetValue(Value, Result); end; function TGerenciadorForm.GetFormIndex: TForm; begin Result := FormIndex; end; class function TGerenciadorForm.New: IGerenciadorForm; begin Result := Self.Create; end; function TGerenciadorForm.RemoveForm(Value: String): IGerenciadorForm; var aForm :TForm; begin if ListaForm.TryGetValue(Value, aForm) then begin aForm.Destroy; ListaForm.Remove(Value); end; end; initialization _Gerenciador := TGerenciadorForm.New; end.
unit ProjectOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, dcedit, dcpedit, ComCtrls, Menus, Project, dcapi; type TProjectOptionsForm = class(TForm) PageControl1: TPageControl; PublishSheet: TTabSheet; Label2: TLabel; Label3: TLabel; PublishRootEdit: TDCEdit; Label1: TLabel; Label4: TLabel; Panel3: TPanel; OkButton: TButton; Button3: TButton; Button2: TButton; UrlRootEdit: TDCEdit; TabSheet1: TTabSheet; Label6: TLabel; DCEdit1: TDCEdit; Label7: TLabel; DCEdit2: TDCEdit; Label9: TLabel; DCEdit3: TDCEdit; Label11: TLabel; DCEdit4: TDCEdit; DCPathDialog1: TDCPathDialog; procedure FormCreate(Sender: TObject); procedure OkButtonClick(Sender: TObject); procedure PublishRootEditButton2Click(Sender: TObject); procedure RootEditChange(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FProject: TProject; procedure SetProject(const Value: TProject); procedure LoadHistory; procedure SaveHistory; public { Public declarations } PublishRootHistory: TPopupListBox; UrlRootHistory: TPopupListBox; property Project: TProject read FProject write SetProject; end; implementation uses IniFiles, LrFolderBrowseUnit, Config; const cHistoryFile = 'history.turbophp.cfg'; cHistorySection = 'History'; {$R *.dfm} procedure TProjectOptionsForm.FormCreate(Sender: TObject); begin PublishRootHistory := TPopupListBox(PublishRootEdit.PopupWindow); UrlRootHistory := TPopupListBox(UrlRootEdit.PopupWindow); LoadHistory; end; procedure TProjectOptionsForm.FormDestroy(Sender: TObject); begin SaveHistory; end; procedure TProjectOptionsForm.LoadHistory; begin with TIniFile.Create(ConfigFolder + cHistoryFile) do try PublishRootHistory.Items.Text := ReadString(cHistorySection, 'PublishRoot', ''); UrlRootHistory.Items.Text := ReadString(cHistorySection, 'UrlRoot', ''); finally Free; end; end; procedure TProjectOptionsForm.SaveHistory; begin with TIniFile.Create(ConfigFolder + cHistoryFile) do try WriteString(cHistorySection, 'PublishRoot', PublishRootHistory.Items.Text); WriteString(cHistorySection, 'UrlRoot', UrlRootHistory.Items.Text); finally Free; end; end; procedure TProjectOptionsForm.OkButtonClick(Sender: TObject); begin Project.PublishFolder := PublishRootEdit.Text; PublishRootHistory.Items.Add(PublishRootEdit.Text); // Project.Url := UrlRootEdit.Text; UrlRootHistory.Items.Add(UrlRootEdit.Text); end; procedure TProjectOptionsForm.PublishRootEditButton2Click(Sender: TObject); //var // p: string; begin if DCPathDialog1.Execute then PublishRootEdit.Text := DCPathDialog1.SelectedItem; // p := LrFolderBrowse('Select Publish Folder', PublishRootEdit.Text); // if p <> '' then // PublishRootEdit.Text := p; end; procedure TProjectOptionsForm.RootEditChange(Sender: TObject); begin //OkButton.Enabled := DirectoryExists(PublishRootEdit.Text); end; procedure TProjectOptionsForm.SetProject(const Value: TProject); begin FProject := Value; PublishRootEdit.Text := Project.PublishFolder; UrlRootEdit.Text := Project.Url; RootEditChange(Self); end; end.
unit glCustomObject; interface uses SysUtils, Classes, Controls, Graphics, {$IFDEF VER230} WinAPI.Messages {$ELSE} Messages {$ENDIF}; type TglCustomObject = class(TGraphicControl) private fCaption: TCaption; fReadOnlyBool, fEnabled: Boolean; FOnMouseLeave, FOnMouseEnter: TNotifyEvent; procedure CMMouseEnter(var msg: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var msg: TMessage); message CM_MOUSELEAVE; procedure SetCaption(value: TCaption); virtual; procedure SetMyEnabled(value: Boolean); protected procedure Paint; override; procedure DoMouseEnter; dynamic; procedure DoMouseLeave; dynamic; public constructor Create(AOwner: TComponent); override; published property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnClick; property Font; property Visible; property Align; property Anchors; property Enabled: Boolean read fEnabled write SetMyEnabled default true; property Caption: TCaption read fCaption write SetCaption; property HelpContext: Boolean read fReadOnlyBool; property HelpKeyword: Boolean read fReadOnlyBool; property HelpType: Boolean read fReadOnlyBool; end; implementation procedure TglCustomObject.CMMouseEnter(var msg: TMessage); begin DoMouseEnter; end; procedure TglCustomObject.CMMouseLeave(var msg: TMessage); begin DoMouseLeave; end; constructor TglCustomObject.Create(AOwner: TComponent); begin inherited; Width := 64; Height := 64; Canvas.Font := Font; Canvas.Brush.Style := bsClear; end; procedure TglCustomObject.DoMouseEnter; begin if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TglCustomObject.DoMouseLeave; begin if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; procedure TglCustomObject.Paint; begin inherited; if (csDesigning in ComponentState) then begin Canvas.Pen.Color := clGray; Canvas.Pen.Style := psDash; Canvas.Brush.Style := bsClear; Canvas.Rectangle(0, 0, Width, Height); end; Canvas.TextOut((Width - Canvas.TextWidth(fCaption)) div 2, (Height - Canvas.TextHeight(fCaption)) div 2, fCaption); end; procedure TglCustomObject.SetCaption(value: TCaption); begin fCaption := value; Invalidate; end; procedure TglCustomObject.SetMyEnabled(value: Boolean); begin fEnabled := value; Invalidate; end; end.
{ Search Elements by Path Hotkey: Ctrl+F } unit UserScript; var slResults: TStringList; sQueryNeedle, sQueryPath: String; bCaseSensitive: Boolean; // form variables SearchForm: TForm; lblQueryPath: TLabel; lblQueryNeedle: TLabel; edQueryPath: TEdit; edQueryNeedle: TEdit; btnSearch: TButton; btnCancel: TButton; function Initialize: Integer; begin ShowSearchForm; if Length(edQueryPath.Text) = 0 then SearchForm.ModalResult := mrCancel; if Length(edQueryNeedle.Text) = 0 then SearchForm.ModalResult := mrCancel; if SearchForm.ModalResult = mrCancel then exit; sQueryPath := edQueryPath.Text; sQueryNeedle := edQueryNeedle.Text; slResults := TStringList.Create; slResults.Sorted := True; slResults.Duplicates := dupIgnore; bCaseSensitive := CompareStr(sQueryNeedle, LowerCase(sQueryNeedle)) <> 0; end; function Process(e: IInterface): Integer; begin if SearchForm.ModalResult = mrCancel then exit; FindMatch(e, sQueryPath, sQueryNeedle, slResults); end; function Finalize: Integer; begin if SearchForm.ModalResult = mrCancel then begin SearchForm.Free; exit; end; SearchForm.Free; if slResults.Count > 0 then begin slResults.Sort(); AddMessage(slResults.Text); end; slResults.Free; end; procedure FindMatch(aRecord: IInterface; aQueryPath: String; aQueryNeedle: String; aResults: TStringList); var kQueryPath: IInterface; sFormID, sQueryHaystack: String; bMatched: Boolean; begin kQueryPath := GetElement(aRecord, aQueryPath); if not Assigned(kQueryPath) then exit; sQueryHaystack := GetEditValue(kQueryPath); if sQueryHaystack = '' then exit; sFormID := GetEditValue(GetElement(aRecord, 'Record Header\FormID')); if bCaseSensitive then bMatched := ContainsStr(sQueryHaystack, aQueryNeedle) else bMatched := ContainsText(sQueryHaystack, aQueryNeedle); if bMatched then aResults.Add(GetFileName(GetFile(aRecord)) + #9 + sFormID); end; function GetElement(const aElement: IInterface; const aPath: String): IInterface; begin if Pos('[', aPath) > 0 then Result := ElementByIP(aElement, aPath) else if Pos('\', aPath) > 0 then Result := ElementByPath(aElement, aPath) else if CompareStr(aPath, Uppercase(aPath)) = 0 then Result := ElementBySignature(aElement, aPath) else Result := ElementByName(aElement, aPath); end; function ElementByIP(aElement: IInterface; aIndexedPath: String): IInterface; var i, index, startPos: integer; path: TStringList; begin aIndexedPath := StringReplace(aIndexedPath, '/', '\', [rfReplaceAll]); path := TStringList.Create; path.Delimiter := '\'; path.StrictDelimiter := true; path.DelimitedText := aIndexedPath; for i := 0 to Pred(path.count) do begin startPos := Pos('[', path[i]); if not (startPos > 0) then begin aElement := ElementByPath(aElement, path[i]); continue; end; index := StrToInt(MidStr(path[i], startPos+1, Pos(']', path[i])-2)); aElement := ElementByIndex(aElement, index); end; Result := aElement; end; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then TForm(Sender).ModalResult := mrCancel else if Key = VK_RETURN then TForm(Sender).ModalResult := mrOk; end; procedure ShowSearchForm; var scaleFactor: Double; begin SearchForm := TForm.Create(nil); scaleFactor := Screen.PixelsPerInch / 96; lblQueryPath := TLabel.Create(SearchForm); lblQueryNeedle := TLabel.Create(SearchForm); edQueryPath := TEdit.Create(SearchForm); edQueryNeedle := TEdit.Create(SearchForm); btnSearch := TButton.Create(SearchForm); btnCancel := TButton.Create(SearchForm); SearchForm.Name := 'SearchForm'; SearchForm.BorderStyle := bsDialog; SearchForm.Caption := 'Search Selected Records'; SearchForm.ClientHeight := 109 * scaleFactor; SearchForm.ClientWidth := 280 * scaleFactor; SearchForm.Color := clBtnFace; SearchForm.Position := poScreenCenter; SearchForm.KeyPreview := True; SearchForm.OnKeyDown := FormKeyDown; lblQueryPath.Name := 'lblQueryPath'; lblQueryPath.Parent := SearchForm; lblQueryPath.Left := 31 * scaleFactor; lblQueryPath.Top := 11 * scaleFactor; lblQueryPath.Width := 55 * scaleFactor; lblQueryPath.Height := 13 * scaleFactor; lblQueryPath.Alignment := taRightJustify; lblQueryPath.Caption := 'Query Path'; lblQueryNeedle.Name := 'lblQueryNeedle'; lblQueryNeedle.Parent := SearchForm; lblQueryNeedle.Left := 21 * scaleFactor; lblQueryNeedle.Top := 43 * scaleFactor; lblQueryNeedle.Width := 65 * scaleFactor; lblQueryNeedle.Height := 13 * scaleFactor; lblQueryNeedle.Alignment := taRightJustify; lblQueryNeedle.Caption := 'Search Terms'; edQueryPath.Name := 'edQueryPath'; edQueryPath.Parent := SearchForm; edQueryPath.Left := 92 * scaleFactor; edQueryPath.Top := 8 * scaleFactor; edQueryPath.Width := 180 * scaleFactor; edQueryPath.Height := 21 * scaleFactor; edQueryPath.TabOrder := 0; edQueryPath.Text := 'FULL'; edQueryNeedle.Name := 'edQueryNeedle'; edQueryNeedle.Parent := SearchForm; edQueryNeedle.Left := 92 * scaleFactor; edQueryNeedle.Top := 40 * scaleFactor; edQueryNeedle.Width := 180 * scaleFactor; edQueryNeedle.Height := 21 * scaleFactor; edQueryNeedle.TabOrder := 1; edQueryNeedle.Text := 'leather'; btnSearch.Name := 'btnSearch'; btnSearch.Parent := SearchForm; btnSearch.Left := 197 * scaleFactor; btnSearch.Top := 75 * scaleFactor; btnSearch.Width := 75 * scaleFactor; btnSearch.Height := 25 * scaleFactor; btnSearch.Caption := 'Search'; btnSearch.TabOrder := 2; btnSearch.ModalResult := mrOk; btnCancel.Name := 'btnCancel'; btnCancel.Parent := SearchForm; btnCancel.Left := 116 * scaleFactor; btnCancel.Top := 76 * scaleFactor; btnCancel.Width := 75 * scaleFactor; btnCancel.Height := 25 * scaleFactor; btnCancel.Caption := 'Cancel'; btnCancel.TabOrder := 3; btnCancel.ModalResult := mrCancel; SearchForm.ShowModal; end; end.
unit InflatablesList_ItemShopTemplate_IO_00000000; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses Classes, AuxTypes, InflatablesList_ItemShopTemplate_IO; type TILItemShopTemplate_IO_00000000 = class(TILItemShopTemplate_IO) protected procedure InitSaveFunctions(Struct: UInt32); override; procedure InitLoadFunctions(Struct: UInt32); override; procedure SaveTemplate_00000000(Stream: TStream); virtual; procedure LoadTemplate_00000000(Stream: TStream); virtual; end; implementation uses SysUtils, BinaryStreaming, InflatablesList_ItemShopParsingSettings; procedure TILItemShopTemplate_IO_00000000.InitSaveFunctions(Struct: UInt32); begin If Struct = IL_SHOPTEMPLATE_STREAMSTRUCTURE_00000000 then fFNSaveToStream := SaveTemplate_00000000 else raise Exception.CreateFmt('TILItemShopTemplate_IO_00000000.InitSaveFunctions: Invalid stream structure (%.8x).',[Struct]); end; //------------------------------------------------------------------------------ procedure TILItemShopTemplate_IO_00000000.InitLoadFunctions(Struct: UInt32); begin If Struct = IL_SHOPTEMPLATE_STREAMSTRUCTURE_00000000 then fFNLoadFromStream := LoadTemplate_00000000 else raise Exception.CreateFmt('TILItemShopTemplate_IO_00000000.InitLoadFunctions: Invalid stream structure (%.8x).',[Struct]); end; //------------------------------------------------------------------------------ procedure TILItemShopTemplate_IO_00000000.SaveTemplate_00000000(Stream: TStream); begin Stream_WriteString(Stream,fName); Stream_WriteString(Stream,fShopName); Stream_WriteBool(Stream,fUntracked); Stream_WriteBool(Stream,fAltDownMethod); Stream_WriteString(Stream,fShopURL); fParsingSettings.SaveToStream(Stream); end; //------------------------------------------------------------------------------ procedure TILItemShopTemplate_IO_00000000.LoadTemplate_00000000(Stream: TStream); begin fName := Stream_ReadString(Stream); fShopName := Stream_ReadString(Stream); fUntracked := Stream_ReadBool(Stream); fAltDownMethod := Stream_ReadBool(Stream); fShopURL := Stream_ReadString(Stream); fParsingSettings.LoadFromStream(Stream); end; end.
unit Myloo.Phonetic.Metaphone; interface uses System.SysUtils, System.StrUtils, System.classes, Myloo.Phonetic.Interfaces, Myloo.Patterns.Singleton, Myloo.Strings.Utils, Myloo.Phonetic.Utils; type TMetaphoneBr = class(TInterfacedObject, IPhoneticMatching) public class function PhoneticMatching(AText:string):string; function Phonetic(AText:string):string; function Similar(const AText, AOther: string): Boolean; function Compare(const AText, AOther: string): Integer; function Proc(const AText, AOther: string): Boolean; end; TSMetaphoneBr = TSingleton<TMetaphoneBr>; implementation { TMetaphoneBr } class function TMetaphoneBr.PhoneticMatching(AText: string): string; var NewStr:string; begin Result := EmptyStr; NewStr := AnsiUpperCase(AText); NewStr := StrReplace(NewStr,['Ç'],'S'); NewStr := RemoveInitialChar(NewStr,['H']); NewStr := RemoveAccents(NewStr); NewStr := ReplaceInitialChar(NewStr,['R'],'2'); NewStr := ReplaceBetweenVowel(NewStr,['S'],'Z'); NewStr := StrReplace(NewStr,['PH'],'F'); NewStr := StrReplace(NewStr,['TH'],'T'); NewStr := StrReplace(NewStr,['GE'],'JE'); NewStr := StrReplace(NewStr,['GI'],'JI'); NewStr := StrReplace(NewStr,['GY'],'JY'); NewStr := StrReplace(NewStr,['GUE'],'GE'); NewStr := StrReplace(NewStr,['GUI'],'GI'); NewStr := StrReplace(NewStr,['CH'],'X'); NewStr := StrReplace(NewStr,['CK'],'K'); NewStr := StrReplace(NewStr,['CQ'],'K'); NewStr := StrReplace(NewStr,['CE'],'SE'); NewStr := StrReplace(NewStr,['CI'],'SI'); NewStr := StrReplace(NewStr,['CY'],'SY'); NewStr := StrReplace(NewStr,['CA'],'KA'); NewStr := StrReplace(NewStr,['CO'],'KO'); NewStr := StrReplace(NewStr,['CU'],'KU'); NewStr := StrReplace(NewStr,['C'],'K'); NewStr := StrReplace(NewStr,['LH'],'1'); NewStr := StrReplace(NewStr,['NH'],'3'); NewStr := StrReplace(NewStr,['RR'],'2'); NewStr := ReplaceFinalChar(NewStr,['R'],'2'); NewStr := StrReplace(NewStr,['XC'],'SS'); NewStr := ReplaceFinalChar(NewStr,['Z'],'S'); NewStr := ReplaceFinalChar(NewStr,['N'],'M'); NewStr := StrReplace(NewStr,['SS'],'S'); NewStr := StrReplace(NewStr,['SH'],'X'); NewStr := StrReplace(NewStr,['SCE'],'SE'); NewStr := StrReplace(NewStr,['SCI'],'SI'); NewStr := StrReplace(NewStr,['XCE'],'SE'); NewStr := StrReplace(NewStr,['XCI'],'SI'); NewStr := StrReplace(NewStr,['XA'],'KSA'); NewStr := StrReplace(NewStr,['XO'],'KS0'); NewStr := StrReplace(NewStr,['XU'],'KSU'); NewStr := StrReplace(NewStr,['W'],'V'); NewStr := StrReplace(NewStr,['Q'],'K'); NewStr := RemoveVowelLessStart(NewStr); NewStr := RemoveDuplicateStr(NewStr,['B','C','G','L','T','P','D','F','J','K','M','V','N','Z']); NewStr := RemoveSpecialCharacters(NewStr); Result := NewStr; end; function TMetaphoneBr.Phonetic(AText: string): string; var NewStr:string; begin Result := EmptyStr; NewStr := AnsiUpperCase(AText); NewStr := StrReplace(NewStr,['Ç'],'S'); NewStr := RemoveInitialChar(NewStr,['H']); NewStr := RemoveAccents(NewStr); NewStr := ReplaceInitialChar(NewStr,['R'],'2'); NewStr := ReplaceBetweenVowel(NewStr,['S'],'Z'); NewStr := StrReplace(NewStr,['PH'],'F'); NewStr := StrReplace(NewStr,['TH'],'T'); NewStr := StrReplace(NewStr,['GE'],'JE'); NewStr := StrReplace(NewStr,['GI'],'JI'); NewStr := StrReplace(NewStr,['GY'],'JY'); NewStr := StrReplace(NewStr,['GUE'],'GE'); NewStr := StrReplace(NewStr,['GUI'],'GI'); NewStr := StrReplace(NewStr,['CH'],'X'); NewStr := StrReplace(NewStr,['CK'],'K'); NewStr := StrReplace(NewStr,['CQ'],'K'); NewStr := StrReplace(NewStr,['CE'],'SE'); NewStr := StrReplace(NewStr,['CI'],'SI'); NewStr := StrReplace(NewStr,['CY'],'SY'); NewStr := StrReplace(NewStr,['CA'],'KA'); NewStr := StrReplace(NewStr,['CO'],'KO'); NewStr := StrReplace(NewStr,['CU'],'KU'); NewStr := StrReplace(NewStr,['C'],'K'); NewStr := StrReplace(NewStr,['LH'],'1'); NewStr := StrReplace(NewStr,['NH'],'3'); NewStr := StrReplace(NewStr,['RR'],'2'); NewStr := ReplaceFinalChar(NewStr,['R'],'2'); NewStr := StrReplace(NewStr,['XC'],'SS'); NewStr := ReplaceFinalChar(NewStr,['Z'],'S'); NewStr := ReplaceFinalChar(NewStr,['N'],'M'); NewStr := StrReplace(NewStr,['SS'],'S'); NewStr := StrReplace(NewStr,['SH'],'X'); NewStr := StrReplace(NewStr,['SCE'],'SE'); NewStr := StrReplace(NewStr,['SCI'],'SI'); NewStr := StrReplace(NewStr,['XCE'],'SE'); NewStr := StrReplace(NewStr,['XCI'],'SI'); NewStr := StrReplace(NewStr,['XA'],'KSA'); NewStr := StrReplace(NewStr,['XO'],'KS0'); NewStr := StrReplace(NewStr,['XU'],'KSU'); NewStr := StrReplace(NewStr,['W'],'V'); NewStr := StrReplace(NewStr,['Q'],'K'); NewStr := RemoveVowelLessStart(NewStr); NewStr := RemoveDuplicateStr(NewStr,['B','C','G','L','T','P','D','F','J','K','M','V','N','Z']); NewStr := RemoveSpecialCharacters(NewStr); Result := NewStr; end; function TMetaphoneBr.Similar(const AText, AOther: string): Boolean; begin Result := Phonetic(AText) = Phonetic(AOther); end; function TMetaphoneBr.Compare(const AText, AOther: string): Integer; begin Result := AnsiCompareStr(Phonetic(AText), Phonetic(AOther)); end; function TMetaphoneBr.Proc(const AText, AOther: string): Boolean; begin Result := Similar(LeftStr(AText,4), LeftStr(AOther,4)); end; end.
// ************************************************************************ // ***************************** CEF4Delphi ******************************* // ************************************************************************ // // CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based // browser in Delphi applications. // // The original license of DCEF3 still applies to CEF4Delphi. // // For more information about CEF4Delphi visit : // https://www.briskbard.com/index.php?lang=en&pageid=cef // // Copyright © 2017 Salvador Díaz Fau. All rights reserved. // // ************************************************************************ // ************ vvvv Original license and comments below vvvv ************* // ************************************************************************ (* * Delphi Chromium Embedded 3 * * Usage allowed under the restrictions of the Lesser GNU General Public License * or alternatively the restrictions of the Mozilla Public License 1.1 * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * Unit owner : Henri Gourvest <hgourvest@gmail.com> * Web site : http://www.progdigy.com * Repository : http://code.google.com/p/delphichromiumembedded/ * Group : http://groups.google.com/group/delphichromiumembedded * * Embarcadero Technologies, Inc is not permitted to use or redistribute * this source code without explicit permission. * *) unit uCEFCustomStreamReader; {$IFNDEF CPUX64} {$ALIGN ON} {$MINENUMSIZE 4} {$ENDIF} {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF} uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes; type TCefCustomStreamReader = class(TCefBaseRefCountedOwn, ICefCustomStreamReader) protected FStream: TStream; FOwned: Boolean; function Read(ptr: Pointer; size, n: NativeUInt): NativeUInt; virtual; function Seek(offset: Int64; whence: Integer): Integer; virtual; function Tell: Int64; virtual; function Eof: Boolean; virtual; function MayBlock: Boolean; virtual; public constructor Create(Stream: TStream; Owned: Boolean); overload; virtual; constructor Create(const filename: string); overload; virtual; destructor Destroy; override; end; implementation uses uCEFMiscFunctions, uCEFLibFunctions; function cef_stream_reader_read(self: PCefReadHandler; ptr: Pointer; size, n: NativeUInt): NativeUInt; stdcall; begin with TCefCustomStreamReader(CefGetObject(self)) do Result := Read(ptr, size, n); end; function cef_stream_reader_seek(self: PCefReadHandler; offset: Int64; whence: Integer): Integer; stdcall; begin with TCefCustomStreamReader(CefGetObject(self)) do Result := Seek(offset, whence); end; function cef_stream_reader_tell(self: PCefReadHandler): Int64; stdcall; begin with TCefCustomStreamReader(CefGetObject(self)) do Result := Tell; end; function cef_stream_reader_eof(self: PCefReadHandler): Integer; stdcall; begin with TCefCustomStreamReader(CefGetObject(self)) do Result := Ord(Eof); end; function cef_stream_reader_may_block(self: PCefReadHandler): Integer; stdcall; begin with TCefCustomStreamReader(CefGetObject(self)) do Result := Ord(MayBlock); end; constructor TCefCustomStreamReader.Create(Stream: TStream; Owned: Boolean); begin inherited CreateData(SizeOf(TCefReadHandler)); FStream := stream; FOwned := Owned; with PCefReadHandler(FData)^ do begin read := cef_stream_reader_read; seek := cef_stream_reader_seek; tell := cef_stream_reader_tell; eof := cef_stream_reader_eof; may_block := cef_stream_reader_may_block; end; end; constructor TCefCustomStreamReader.Create(const filename: string); begin Create(TFileStream.Create(filename, fmOpenRead or fmShareDenyWrite), True); end; destructor TCefCustomStreamReader.Destroy; begin if FOwned then FStream.Free; inherited Destroy; end; function TCefCustomStreamReader.Eof: Boolean; begin Result := FStream.Position = FStream.size; end; function TCefCustomStreamReader.MayBlock: Boolean; begin Result := False; end; function TCefCustomStreamReader.Read(ptr: Pointer; size, n: NativeUInt): NativeUInt; begin result := NativeUInt(FStream.Read(ptr^, n * size)) div size; end; function TCefCustomStreamReader.Seek(offset: Int64; whence: Integer): Integer; begin Result := FStream.Seek(offset, TSeekOrigin(whence)); end; function TCefCustomStreamReader.Tell: Int64; begin Result := FStream.Position; end; end.
unit RaschVedPrintDM; interface uses SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet, frxClass, frxDesgn, frxDBSet, IBase, ZMessages, IniFiles, ZProc, Forms,Unit_PrintAccList_Consts, Variants, Dates, Dialogs, ZSvodTypesUnit, frxExportXLS, frxExportHTML, frxExportPDF, FIBQuery, pFIBQuery, pFIBStoredProc, UnitZarplataConsts, frxExportTXT; type TPrintDM = class(TDataModule) Report: TfrxReport; frxDSetGlobalData: TfrxDBDataset; frxDSetShtatRas: TfrxDBDataset; frxDSetPrivileges: TfrxDBDataset; frxDesigner1: TfrxDesigner; frxUserDataSet: TfrxUserDataSet; ReadTransaction: TpFIBTransaction; DSetAccUdList: TpFIBDataSet; DSetPrivileges: TpFIBDataSet; DSetAccNarList: TpFIBDataSet; DSetShtatRas: TpFIBDataSet; DSetGlobalData: TpFIBDataSet; DB: TpFIBDatabase; DSourceGlobalData: TDataSource; DSetSystemData: TpFIBDataSet; frxDSetSystemData: TfrxDBDataset; DSetComingLeaving: TpFIBDataSet; frxUserDataSetComingLeaving: TfrxUserDataSet; DSetSmetaList: TpFIBDataSet; frxDSetSmetaList: TfrxDBDataset; DSetSheets: TpFIBDataSet; frxDSetSheets: TfrxDBDataset; frxXLSExport1: TfrxXLSExport; PDFExport: TfrxPDFExport; HTMLExport: TfrxHTMLExport; StProc: TpFIBStoredProc; WriteTransaction: TpFIBTransaction; DSetParent: TpFIBDataSet; DBDSetParent: TfrxDBDataset; DSourceParent: TDataSource; TXTExport: TfrxTXTExport; DSetGlobalData1: TpFIBDataSet; DSetAccNarList1: TpFIBDataSet; DSetAccUdList1: TpFIBDataSet; DSetSheets1: TpFIBDataSet; DSourceGlobalData1: TDataSource; DSetGlobalData0: TpFIBDataSet; DSetAccNarList0: TpFIBDataSet; DSetAccUdList0: TpFIBDataSet; DSetSheets0: TpFIBDataSet; DSetParent0: TpFIBDataSet; DSourceGlobalData0: TDataSource; frxDSetGlobalData1: TfrxDBDataset; UDSNarUderg1: TfrxUserDataSet; frxDSetSheets1: TfrxDBDataset; DBDSetParent0: TfrxDBDataset; frxDSetGlobalData0: TfrxDBDataset; UDSNarUderg0: TfrxUserDataSet; frxDSetSheets0: TfrxDBDataset; DSourceParent0: TDataSource; UDSMan: TfrxUserDataSet; UDSNarUderg: TfrxUserDataSet; UDSSheets: TfrxUserDataSet; procedure ReportGetValue(const VarName: String; var Value: Variant); procedure DataModuleDestroy(Sender: TObject); function DayClocks(Sender:TObject):String; private PComingLeavingText:string; PType:integer; PKod_Setup:integer; PLanguageIndex:byte; PParameter:TZAccListParameter; public function ReportCreate(AParameter:TZAccListParameter):variant; function ReportCreateShort(AParameter:TZAccListParameter):variant; end; implementation uses RaschVedMainDM; {$R *.dfm} const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini'; const SectionOfIniFile = 'AccList'; const FullNameReport = 'Reports\Zarplata\AccList.fr3'; const FullNameReportShort = 'Reports\Zarplata\AccListShort.fr3'; const FullNameReportShortAll = 'Reports\Zarplata\AccListShortAll.fr3'; const FullNameReportVUZ = 'Reports\Zarplata\AccListVUZ.fr3'; const FullNameReportTabulka = 'Reports\Zarplata\AccListTabulka.fr3'; const FullNameReportTabulkaNoDep = 'Reports\Zarplata\AccListTabulkaNoDep.fr3'; const FullNameReportShortAllAndOne = 'Reports\Zarplata\AccListShortAllAndOne.fr3'; function TPrintDM.ReportCreate(AParameter:TZAccListParameter):variant; var IniFile:TIniFile; ViewMode:byte; PathReport:string; IsUniver:variant; FIO:string; n:integer; begin PParameter :=AParameter; PLanguageIndex:=LanguageIndex; IsUniver:=ValueFieldZSetup(AParameter.DB_Handle,'IS_UNIVER'); if VarIsNull(IsUniver) then IsUniver:='F'; PType:=0; if((AParameter.Id_Group_Account=-1)and(AParameter.Id_Department=-1))then PType:=1; try DB.Handle:=AParameter.DB_handle; if AParameter.Id_Man<0 then begin DSetParent.SQLs.SelectSQL.Text := 'SELECT DISTINCT * FROM Z_RASCHVED_DEPARTMENT_FILTER_S('+IntToStr(AParameter.ID_Session) + ' , ' + IntToStr(AParameter.ID_SESSION_FILTER_DEP)+') ORDER BY KOD_DEPARTMENT'; //отфильтрованные записи и по выбранным DSetGlobalData.DataSource:=DSourceParent; DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S('+IntToStr(AParameter.Id_Session)+',?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S('+IntToStr(AParameter.Id_Session)+',?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetPrivileges.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_PRIV_S(?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+')'; DSetShtatRas.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_MAN_MOVING_S(?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+')'; if(AParameter.TypeData=3)then DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_SHIFR('+IfThen(AParameter.Id_Department<>-1,IntToStr(AParameter.Id_Department),'null')+','+ IntToStr(AParameter.Id_Session)+') order by tn' else DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE('+':ID_DEPARTMENT'+','+ IntToStr(AParameter.Id_Session)+') order by tn'; {DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_FILTER('+IntToStr(AParameter.Id_Session)+','+ IntToStr(AParameter.ID_SESSION_FILTER_DEP)+') order by tn';} DSetComingLeaving.SQLs.SelectSQL.Text :='SELECT * FROM Z_MAN_COMING_LEAVING(?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+') order by REAL_DATE'; DSetSmetaList.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_SMETA_S(?ID_GROUP_ACCOUNT,?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',0)'; // ORDER BY ID_DEPARTMENT,ID_SMETA'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET(?ID_MAN,?ID_GROUP_ACCOUNT)'; end else begin DSetGlobalData.DataSource:=nil; if((AParameter.Id_Group_Account=-1)and(AParameter.Id_Department<>-1))then begin DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetPrivileges.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_PRIV_S('+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1)'; DSetShtatRas.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_MAN_MOVING_S('+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1)'; DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_PERIOD('+IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_setup)+','+IntToStr(AParameter.Id_Department)+') order by tn'; DSetComingLeaving.SQLs.SelectSQL.Text :='SELECT * FROM Z_MAN_COMING_LEAVING('+IntToStr(AParameter.Id_Man)+','+'?KOD_SETUP1) order by REAL_DATE'; DSetSmetaList.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_SMETA_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE)'; // ORDER BY ID_DEPARTMENT,ID_SMETA'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET('+IntToStr(AParameter.Id_Man)+','+'?ID_GROUP_ACCOUNT)'; end else begin DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+','+ IntToStr(AParameter.TypeData)+') ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+','+ IntToStr(AParameter.TypeData)+') order by KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetPrivileges.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_PRIV_S('+IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+')'; DSetShtatRas.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_MAN_MOVING_S('+IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+')'; DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_GLOBALDATA_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+')'; DSetComingLeaving.SQLs.SelectSQL.Text :='SELECT * FROM Z_MAN_COMING_LEAVING('+IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+') order by REAL_DATE'; DSetSmetaList.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_SMETA_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+','+ IntToStr(AParameter.TypeData)+')'; // GROUP BY ID_DEPARTMENT,ID_SMETA, SMETA_TITLE, NAME_SHORT, P1'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET('+IntToStr(AParameter.Id_Man)+','+IntToStr(AParameter.Id_Group_Account)+')'; end; end; DSetSystemData.SQLs.SelectSQL.Text := 'SELECT SHORT_NAME FROM Z_SETUP'; if AParameter.Id_Man<0 then DSetParent.Open; DSetGlobalData.Open; DSetGlobalData.FetchAll; DSetAccNarList.Open; DSetAccNarList.FetchAll; DSetAccUdList.Open; DSetAccUdList.FetchAll; DSetPrivileges.Open; DSetPrivileges.FetchAll; DSetShtatRas.Open; DSetShtatRas.FetchAll; DSetSystemData.Open; DSetSystemData.FetchAll; DSetComingLeaving.Open; DSetComingLeaving.FetchAll; if IsUniver='T' then begin DSetSmetaList.Open; DSetSmetaList.FetchAll; DSetSheets.Open; DSetSheets.FetchAll; end; frxUserDataSet.Fields.Add('N_CODE_DEPARTMENT'); frxUserDataSet.Fields.Add('N_KOD_SETUP_3'); frxUserDataSet.Fields.Add('N_KOD_SM'); frxUserDataSet.Fields.Add('N_KOD_VIDOPL'); frxUserDataSet.Fields.Add('N_NAME_VIDOPL'); frxUserDataSet.Fields.Add('N_DAY_CLOCK'); frxUserDataSet.Fields.Add('N_PERCENT_SUMCLOCK'); frxUserDataSet.Fields.Add('N_SUMMA'); frxUserDataSet.Fields.Add('U_KOD_SETUP_3'); frxUserDataSet.Fields.Add('U_KOD_VIDOPL'); frxUserDataSet.Fields.Add('U_NAME_VIDOPL'); frxUserDataSet.Fields.Add('U_SUMMA'); frxUserDataSetComingLeaving.Fields.Add('P_COMING_LEAVING'); IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1); //if IsUniver='T' then //PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReportTabulka); if AParameter.Id_Man<0 then PathReport:=FullNameReportTabulka else PathReport:=FullNameReportTabulkaNoDep; //PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReport); IniFile.Free; Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True); if ((PathReport=FullNameReportTabulkaNoDep) and (AParameter.Id_Group_Account<>-1)) then Report.PreviewOptions.Zoom:=1.5 else Report.PreviewOptions.Zoom:=1; Report.Variables.Clear; Report.Variables['P_CODE_DEPARTMENT']:=''''+FZPrintAccList_P_CODE_DEPARTMENT_Text+''''; Report.Variables['P_KOD_SETUP_3']:=''''+FZPrintAccList_P_KOD_SETUP_3_Text+''''; Report.Variables['P_KOD_VIDOPL']:=''''+FZPrintAccList_P_KOD_VIDOPL_Text+''''; Report.Variables['P_NAME_VIDOPL']:=''''+FZPrintAccList_P_NAME_VIDOPL_Text+''''; Report.Variables['P_DAY_CLOCK']:=''''+FZPrintAccList_P_DAY_CLOCK_Text+''''; Report.Variables['P_PERCENT_SUMCLOCK']:=''''+FZPrintAccList_P_PERCENT_SUMCLOCK_Text+''''; Report.Variables['P_SUMMA']:=''''+FZPrintAccList_P_SUMMA_Text+''''; Report.Variables['P_NAR']:=''''+FZPrintAccList_P_Nar_Text+''''; Report.Variables['P_UD']:=''''+FZPrintAccList_P_Ud_Text+''''; Report.Variables['P_TARIFOKLAD']:=''''+FZPrintAccList_P_TarifOklad_Text+''''; Report.Variables['P_ACCLIST_TYPE']:=NULL; if(AParameter.Id_Man>=0) and (AParameter.Id_Group_Account=-1)then Report.Variables['P_ACCLIST']:=null else if(AParameter.Id_Man>0)then begin if(DSetGlobalData['KOD_SETUP1']<>AParameter.Kod_Setup)then Report.Variables['P_ACCLIST']:='''Перерахунок за '+AnsiLowerCase(KodSetupToPeriod(DSetGlobalData['KOD_SETUP1'],2))+'''' else Report.Variables['P_ACCLIST']:=''''+FZPrintAccList_P_AccList_Title+' '+AnsiLowerCase(KodSetupToPeriod(AParameter.Kod_Setup,2))+''''; end else Report.Variables['P_ACCLIST']:=''''+FZPrintAccList_P_AccList_Title+' '+AnsiLowerCase(KodSetupToPeriod(AParameter.Kod_Setup,2))+''''; Report.Variables['P_FROM']:=''''+FZPrintAccList_P_From_Text+''''; Report.Variables['P_SUMMARY']:=''''+FZPrintAccList_P_Summary_Text+''''; if((AParameter.Path<>'')and(AParameter.Path<>null))then begin try StProc.Transaction.StartTransaction; StProc.StoredProcName:='Z_FIO_BY_ID_MAN'; StProc.Prepare; StProc.ParamByName('ID_MAN').AsInteger:=AParameter.Id_Man; StProc.ExecProc; FIO:=StProc.ParamByName('FIO').AsString; StProc.Transaction.Commit; except on E:Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; AParameter.Path:=AParameter.Path+IntToSTr(YearMonthFromKodSetup(AParameter.Kod_setup,true))+'-' +IfThen(YearMonthFromKodSetup(AParameter.Kod_setup,false)<10,'0'+IntToSTr(YearMonthFromKodSetup(AParameter.Kod_setup,false)),IntToSTr(YearMonthFromKodSetup(AParameter.Kod_setup,false)))+' '; n:=Pos(' ',Fio); AParameter.Path:=AParameter.Path+TransliterationUkrEng(Copy(Fio,1,n-1))+'_'+TransliterationUkrEng(Copy(Fio,n+1,1))+'_'; Fio:=Copy(Fio,n+1,Length(Fio)); n:=Pos(' ',Fio); AParameter.Path:=AParameter.Path+TransliterationUkrEng(Copy(Fio,n+1,1))+'.pdf'; PDFExport.FileName:=AParameter.Path; HTMLExport.FileName:=AParameter.Path; Report.PrepareReport(true); if(AParameter.TypeOper=1)then Report.Export(PDFExport); if(AParameter.TypeOper=2)then Report.Export(HTMLExport); end else if zDesignReport then Report.DesignReport else Report.ShowReport; Report.Free; except on E:Exception do begin ZShowMessage(FZPrintAccList_Error_Caption,e.Message,mtError,[mbOK]); end; end; ReportCreate:=AParameter.Path; end; function TPrintDM.ReportCreateShort(AParameter:TZAccListParameter):variant; var IniFile:TIniFile; ViewMode:byte; PathReport:string; IsUniver:variant; FIO:string; n:integer; begin PParameter :=AParameter; PLanguageIndex:=LanguageIndex; IsUniver:=ValueFieldZSetup(AParameter.DB_Handle,'IS_UNIVER'); if VarIsNull(IsUniver) then IsUniver:='F'; {PType:=0; if((AParameter.Id_Group_Account=-1)and(AParameter.Id_Department=-1))then PType:=1; } try DB.Handle:=AParameter.DB_handle; if AParameter.Id_Man<0 then begin if(AParameter.TypeData=6)then begin DSetParent0.SQLs.SelectSQL.Text := 'SELECT DISTINCT * FROM Z_RASCHVED_DEPARTMENT_FILTER_S('+IntToStr(AParameter.ID_Session) + ' , ' + IntToStr(AParameter.ID_SESSION_FILTER_DEP)+') ORDER BY KOD_DEPARTMENT'; //отфильтрованные записи и по выбранным DSetGlobalData0.DataSource:=DSourceParent0; DSetAccNarList0.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) ORDER BY KOD_SETUP3 descending,NAME_VIDOPL'; DSetAccUdList0.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) order by KOD_SETUP3 descending,NAME_VIDOPL'; DSetGlobalData0.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_SHORT(?ID_DEPARTMENT,'+ IntToStr(AParameter.Id_Session)+' ,0) order by FIO'; DSetSheets0.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET_SHORT(?ID_MAN,?ID_GROUP_ACCOUNT)'; {DSetParent1.SQLs.SelectSQL.Text := 'SELECT DISTINCT * FROM Z_RASCHVED_DEPARTMENT_FILTER_S('+IntToStr(AParameter.ID_Session) + ' , ' + IntToStr(AParameter.ID_SESSION_FILTER_DEP)+') ORDER BY KOD_DEPARTMENT'; } //отфильтрованные записи и по выбранным DSetGlobalData1.DataSource:=DSourceParent0; DSetAccNarList1.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) ORDER BY KOD_SETUP3 descending,NAME_VIDOPL'; DSetAccUdList1.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) order by KOD_SETUP3 descending,NAME_VIDOPL'; DSetGlobalData1.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_SHORT(?ID_DEPARTMENT,'+ IntToStr(AParameter.Id_Session)+' ,1) order by FIO'; DSetSheets1.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET_SHORT(?ID_MAN,?ID_GROUP_ACCOUNT)'; end else begin DSetParent.SQLs.SelectSQL.Text := 'SELECT DISTINCT * FROM Z_RASCHVED_DEPARTMENT_FILTER_S('+IntToStr(AParameter.ID_Session) + ' , ' + IntToStr(AParameter.ID_SESSION_FILTER_DEP)+') ORDER BY KOD_DEPARTMENT'; //отфильтрованные записи и по выбранным DSetGlobalData.DataSource:=DSourceParent; DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) ORDER BY KOD_SETUP3 descending,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_SHORT_S('+IntToStr(AParameter.Id_Session)+','+ '?ID_MAN,'+ IntToStr(AParameter.Kod_Setup)+',2) order by KOD_SETUP3 descending,NAME_VIDOPL'; DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_SH_FULL(?ID_DEPARTMENT,'+ IntToStr(AParameter.Id_Session)+') order by FIO'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET_SHORT(?ID_MAN,?ID_GROUP_ACCOUNT)'; DSetParent.Open; DSetParent.FetchAll; end end else { if((AParameter.Id_Group_Account=-1)and(AParameter.Id_Department<>-1))then begin DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE) ORDER BY KOD_SETUP3 descending,KOD_VIDOPL,NAME_VIDOPL'; DSetPrivileges.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_PRIV_S('+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1)'; DSetShtatRas.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_MAN_MOVING_S('+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1)'; DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_RASCHVED_LISTPEOPLE_PERIOD('+IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_setup)+','+IntToStr(AParameter.Id_Department)+') order by tn'; DSetComingLeaving.SQLs.SelectSQL.Text :='SELECT * FROM Z_MAN_COMING_LEAVING('+IntToStr(AParameter.Id_Man)+','+'?KOD_SETUP1) order by REAL_DATE'; DSetSmetaList.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_SMETA_S(?ID_GROUP_ACCOUNT,'+IntToStr(AParameter.Id_Man)+','+ '?KOD_SETUP1,?TYPE_TABLE)'; // ORDER BY ID_DEPARTMENT,ID_SMETA'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET('+IntToStr(AParameter.Id_Man)+','+'?ID_GROUP_ACCOUNT)'; end else begin } begin DSetAccNarList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_NAR_SHORT_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+','+ IntToStr(AParameter.TypeData)+') ORDER BY KOD_SETUP3 descending,NAME_VIDOPL'; DSetAccUdList.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_ACC_UD_SHORT_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+','+ IntToStr(AParameter.TypeData)+') order by KOD_SETUP3 descending,NAME_VIDOPL'; DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_ACCOUNT_GLOBALDATA_SHORT_S('+IntToStr(AParameter.Id_Group_Account)+','+ IntToStr(AParameter.Id_Man)+','+ IntToStr(AParameter.Kod_Setup)+')'; DSetSheets.SQLs.SelectSQL.Text:='SELECT * FROM Z_ACCOUNT_ACC_S_SHEET_SHORT('+IntToStr(AParameter.Id_Man)+','+IntToStr(AParameter.Id_Group_Account)+')'; { end;} end; if(AParameter.TypeData=6)then begin //DSetParent1.Open; DSetParent0.Open; DSetParent0.fetchAll; DSetGlobalData0.Open; DSetGlobalData0.fetchAll; DSetAccNarList0.Open; DSetAccNarList0.fetchAll; DSetAccUdList0.Open; DSetAccUdList0.fetchAll; DSetSheets0.Open; DSetSheets0.fetchAll; DSetGlobalData1.Open; DSetGlobalData1.fetchAll; DSetAccNarList1.Open; DSetAccNarList1.fetchAll; DSetAccUdList1.Open; DSetAccUdList1.fetchAll; DSetSheets1.Open; DSetSheets1.fetchAll; UDSMan.Fields.Add('TN1'); UDSMan.Fields.Add('FIO1'); UDSMan.Fields.Add('BIRTH_DATE1'); UDSMan.Fields.Add('TN2'); UDSMan.Fields.Add('FIO2'); UDSMan.Fields.Add('BIRTH_DATE2'); UDSNarUderg.Fields.Add('N_KOD_SETUP_31'); UDSNarUderg.Fields.Add('N_KOD_SM1'); UDSNarUderg.Fields.Add('N_NAME_VIDOPL1'); UDSNarUderg.Fields.Add('N_DAY_CLOCK_SHORT1'); UDSNarUderg.Fields.Add('N_SUMMA1'); UDSNarUderg.Fields.Add('U_KOD_SETUP_31'); UDSNarUderg.Fields.Add('U_NAME_VIDOPL1'); UDSNarUderg.Fields.Add('U_SUMMA1'); UDSNarUderg.Fields.Add('N_KOD_SETUP_32'); UDSNarUderg.Fields.Add('N_KOD_SM2'); UDSNarUderg.Fields.Add('N_NAME_VIDOPL2'); UDSNarUderg.Fields.Add('N_DAY_CLOCK_SHORT2'); UDSNarUderg.Fields.Add('N_SUMMA2'); UDSNarUderg.Fields.Add('U_KOD_SETUP_32'); UDSNarUderg.Fields.Add('U_NAME_VIDOPL2'); UDSNarUderg.Fields.Add('U_SUMMA2'); UDSSheets.Fields.Add('TYPE_SHEET1'); UDSSheets.Fields.Add('SUMA_SHEET1'); UDSSheets.Fields.Add('SMETA_KOD1'); UDSSheets.Fields.Add('SMETA_NAME1'); UDSSheets.Fields.Add('TYPE_SHEET2'); UDSSheets.Fields.Add('SUMA_SHEET2'); UDSSheets.Fields.Add('SMETA_KOD2'); UDSSheets.Fields.Add('SMETA_NAME2'); end else begin DSetGlobalData.Open; DSetAccNarList.Open; DSetAccUdList.Open; DSetSheets.Open; frxUserDataSet.Fields.Add('N_KOD_SETUP_3'); frxUserDataSet.Fields.Add('N_KOD_SM'); frxUserDataSet.Fields.Add('N_NAME_VIDOPL'); frxUserDataSet.Fields.Add('N_DAY_CLOCK'); frxUserDataSet.Fields.Add('N_SUMMA'); frxUserDataSet.Fields.Add('U_KOD_SETUP_3'); frxUserDataSet.Fields.Add('U_NAME_VIDOPL'); frxUserDataSet.Fields.Add('U_SUMMA'); end; IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports); ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1); if(AParameter.TypeData=4)then PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReportShortAll) else if(AParameter.TypeData=6)then PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReportShortAllAndOne) else PathReport:=IniFile.ReadString(SectionOfIniFile,'NameReport',FullNameReportShort); IniFile.Free; Report.Clear; Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True); Report.Variables.Clear; Report.Variables['P_KOD_SETUP_3']:=''''+FZPrintAccList_P_KOD_SETUP_3_Text+''''; Report.Variables['P_NAME_VIDOPL']:=''''+FZPrintAccList_P_NAME_VIDOPL_Text+''''; Report.Variables['P_DAY_CLOCK']:='''Дні'''; Report.Variables['P_SUMMA']:=''''+FZPrintAccList_P_SUMMA_Text+''''; Report.Variables['P_NAR']:=''''+FZPrintAccList_P_Nar_Text+''''; Report.Variables['P_UD']:=''''+FZPrintAccList_P_Ud_Text+''''; Report.Variables['P_ACCLIST_TYPE']:=NULL; Report.Variables['FORCOUNTRECORDOFUDSMAN']:=null; Report.Variables['P_ACCLIST_SHORT']:='''Відомість аналітичного контролю за '+AnsiLowerCase(KodSetupToPeriod(AParameter.Kod_Setup,2))+''''; Report.Variables['P_FROM']:=''''+FZPrintAccList_P_From_Text+''''; Report.Variables['P_SUMMARY']:=''''+FZPrintAccList_P_Summary_Text+''''; if zDesignReport then Report.DesignReport else Report.ShowReport; Report.Free; except on E:Exception do begin ZShowMessage(FZPrintAccList_Error_Caption,e.Message,mtError,[mbOK]); end; end; ReportCreateShort:=AParameter.Path; end; procedure TPrintDM.ReportGetValue(const VarName: String; var Value: Variant); var PValue:Variant; Sum_Nar,Sum_Ud:Extended; Sign:string[1]; P_ACCLIST_SHORT1,P_ACCLIST_SHORT2:Integer; begin if(PParameter.TypeData=6)then begin if UpperCase(VarName)='TN1' then begin if DSetGlobalData0.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData0.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData0.FieldValues['TN']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='FIO1' then begin if DSetGlobalData0.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData0.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData0.FieldValues['FIO']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='BIRTH_DATE1' then begin if DSetGlobalData0.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData0.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData0.FieldValues['BIRTH_DATE']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='TN2' then begin if DSetGlobalData1.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData1.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData1.FieldValues['TN']; DSetSheets0.FetchAll; DSetSheets1.FetchAll; DSetAccNarList0.FetchAll; DSetAccNarList1.FetchAll; DSetAccUdList0.FetchAll; DSetAccUdList1.FetchAll; P_ACCLIST_SHORT1:=IfThen(DSetAccNarList0.RecordCount>DSetAccNarList1.RecordCount,DSetAccNarList0.RecordCount,DSetAccNarList1.RecordCount); P_ACCLIST_SHORT2:=IfThen(DSetAccUdList0.RecordCount>DSetAccUdList1.RecordCount,DSetAccUdList1.RecordCount,DSetAccUdList1.RecordCount); UDSNarUderg.RangeEndCount:=IfThen(P_ACCLIST_SHORT1>P_ACCLIST_SHORT2,P_ACCLIST_SHORT1,P_ACCLIST_SHORT2); UDSNarUderg.RangeEnd:=reCount; P_ACCLIST_SHORT1:=IfThen(DSetSheets0.RecordCount>DSetSheets1.RecordCount, DSetSheets0.RecordCount, DSetSheets1.RecordCount); P_ACCLIST_SHORT2:=IfThen(DSetSheets0.RecordCount>DSetSheets1.RecordCount, DSetSheets0.RecordCount, DSetSheets1.RecordCount); UDSSheets.RangeEndCount:=IfThen(P_ACCLIST_SHORT1>P_ACCLIST_SHORT2,P_ACCLIST_SHORT1,P_ACCLIST_SHORT2); UDSSheets.RangeEnd:=reCount; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='FIO2' then begin if DSetGlobalData1.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData1.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData1.FieldValues['FIO']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='BIRTH_DATE2' then begin if DSetGlobalData1.RecordCount-1>=UDSMan.RecNo then begin DSetGlobalData1.RecNo:=UDSMan.RecNo+1; Value:=DSetGlobalData1.FieldValues['BIRTH_DATE']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='FORCOUNTRECORDOFUDSMAN' then begin DSetGlobalData0.fetchAll; DSetGlobalData1.fetchAll; UDSMan.RangeEndCount:=IfThen(DSetGlobalData0.RecordCount>DSetGlobalData1.RecordCount,DSetGlobalData0.RecordCount,DSetGlobalData1.RecordCount); UDSMan.RangeEnd:=reCount; end; if UpperCase(VarName)='P_ACCLIST_SHORT' then begin { P_ACCLIST_SHORT1:=IfThen(DSetAccNarList0.RecordCount>DSetAccNarList1.RecordCount,DSetAccNarList0.RecordCount,DSetAccNarList1.RecordCount); P_ACCLIST_SHORT2:=IfThen(DSetAccUdList0.RecordCount>DSetAccUdList1.RecordCount,DSetAccUdList0.RecordCount,DSetAccUdList1.RecordCount); UDSNarUderg.RangeEndCount:=IfThen(P_ACCLIST_SHORT1>P_ACCLIST_SHORT2,P_ACCLIST_SHORT1,P_ACCLIST_SHORT2); UDSNarUderg.RangeEnd:=reCount; ShowMessage('UDSNarUderg.RangeEndCount'+' '+inttostr(UDSNarUderg.RangeEndCount)); P_ACCLIST_SHORT1:=IfThen(DSetSheets0.RecordCount>DSetSheets1.RecordCount, DSetSheets0.RecordCount, DSetSheets1.RecordCount); P_ACCLIST_SHORT2:=IfThen(DSetSheets0.RecordCount>DSetSheets1.RecordCount, DSetSheets0.RecordCount, DSetSheets1.RecordCount); UDSSheets.RangeEndCount:=IfThen(P_ACCLIST_SHORT1>P_ACCLIST_SHORT2,P_ACCLIST_SHORT1,P_ACCLIST_SHORT2); UDSSheets.RangeEnd:=reCount; ShowMessage('UDSSheets.RangeEndCount'+' '+inttostr(UDSSheets.RangeEndCount)); } end; if UpperCase(VarName)='N_KOD_SETUP_31' then begin if DSetAccNarList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList0.RecNo:=UDSNarUderg.RecNo+1; Value:=KodSetupToPeriod(DSetAccNarList0['KOD_SETUP3'],1); Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_KOD_SM1' then begin if DSetAccNarList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList0.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList0['KOD_SMETA']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_NAME_VIDOPL1' then begin if DSetAccNarList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList0.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList0.FieldValues['NAME_VIDOPL']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_DAY_CLOCK_SHORT1' then begin if DSetAccNarList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList0.RecNo:=UDSNarUderg.RecNo+1; if (DSetAccNarList0['NDAY']=0) or (VarIsNull(DSetAccNarList0['NDAY'])) then Value:='' else begin sign:=IfThen(DSetAccNarList0['NDAY']<0,'-',''); PValue:=Abs(DSetAccNarList0['NDAY']); Value:=Sign+ifThen(PValue<10,'0','')+VarToStr(PValue); end; end else Value:=NULL; end; if UpperCase(VarName)='N_SUMMA1' then begin if DSetAccNarList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList0.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList0.FieldValues['SUMMA'];; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_KOD_SETUP_31' then begin if DSetAccUdList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList0.RecNo:=UDSNarUderg.RecNo+1; Value:=KodSetupToPeriod(DSetAccUdList0['KOD_SETUP3'],1);;; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_NAME_VIDOPL1' then begin if DSetAccUdList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList0.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccUdList0.FieldValues['NAME_VIDOPL']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_SUMMA1' then begin if DSetAccUdList0.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList0.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccUdList0.FieldValues['SUMMA']; Exit; end else begin Value:=NULL; Exit; end end; ////2 if UpperCase(VarName)='N_KOD_SETUP_32' then begin if DSetAccNarList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList1.RecNo:=UDSNarUderg.RecNo+1; Value:=KodSetupToPeriod(DSetAccNarList1['KOD_SETUP3'],1); Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_KOD_SM2' then begin if DSetAccNarList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList1.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList1['KOD_SMETA']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_NAME_VIDOPL2' then begin if DSetAccNarList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList1.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList1.FieldValues['NAME_VIDOPL']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='N_DAY_CLOCK_SHORT2' then begin if DSetAccNarList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList1.RecNo:=UDSNarUderg.RecNo+1; if (DSetAccNarList1['NDAY']=0) or (VarIsNull(DSetAccNarList1['NDAY'])) then Value:='' else begin sign:=IfThen(DSetAccNarList1['NDAY']<0,'-',''); PValue:=Abs(DSetAccNarList1['NDAY']); Value:=Sign+ifThen(PValue<10,'0','')+VarToStr(PValue); end; end else Value:=NULL; end; if UpperCase(VarName)='N_SUMMA2' then begin if DSetAccNarList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccNarList1.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccNarList1.FieldValues['SUMMA'];; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_KOD_SETUP_32' then begin if DSetAccUdList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList1.RecNo:=UDSNarUderg.RecNo+1; Value:=KodSetupToPeriod(DSetAccUdList1['KOD_SETUP3'],1);;; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_NAME_VIDOPL2' then begin if DSetAccUdList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList1.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccUdList1.FieldValues['NAME_VIDOPL']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='U_SUMMA2' then begin if DSetAccUdList1.RecordCount-1>=UDSNarUderg.RecNo then begin DSetAccUdList1.RecNo:=UDSNarUderg.RecNo+1; Value:=DSetAccUdList1.FieldValues['SUMMA']; Exit; end else begin Value:=NULL; Exit; end end; ///footer if UpperCase(VarName)='P_SUM_NAR1' then begin Sum_Nar:=0; DSetAccNarList0.First; while not DSetAccNarList0.Eof do Begin Sum_Nar:=Sum_Nar+IfThen(DSetAccNarList0['SUMMA']<>NULL,DSetAccNarList0['SUMMA'],0); DSetAccNarList0.Next; end; Value:=FloatToStrF(Sum_Nar,ffFixed,16,2); end; if UpperCase(VarName)='P_SUM_UD1' then begin Sum_Ud:=0; DSetAccUdList0.First; while not DSetAccUdList0.Eof do Begin Sum_Ud:=Sum_Ud+IfThen(DSetAccUdList0['SUMMA']<>NULL,DSetAccUdList0['SUMMA'],0); DSetAccUdList0.Next; end; Value :=FloatToStrF(Sum_Ud,ffFixed,16,2); end; if UpperCase(VarName)='P_SUM_NAR2' then begin Sum_Nar:=0; DSetAccNarList1.First; while not DSetAccNarList1.Eof do Begin Sum_Nar:=Sum_Nar+IfThen(DSetAccNarList1['SUMMA']<>NULL,DSetAccNarList1['SUMMA'],0); DSetAccNarList1.Next; end; Value:=FloatToStrF(Sum_Nar,ffFixed,16,2); end; if UpperCase(VarName)='P_SUM_UD2' then begin Sum_Ud:=0; DSetAccUdList1.First; while not DSetAccUdList1.Eof do Begin Sum_Ud:=Sum_Ud+IfThen(DSetAccUdList1['SUMMA']<>NULL,DSetAccUdList1['SUMMA'],0); DSetAccUdList1.Next; end; Value :=FloatToStrF(Sum_Ud,ffFixed,16,2); end; //sheets if UpperCase(VarName)='TYPE_SHEET1' then begin if DSetSheets0.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets0.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets0.FieldValues['TYPE_SHEET']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SUMA_SHEET1' then begin if DSetSheets0.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets0.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets0.FieldValues['SUMMA']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SMETA_KOD1' then begin if DSetSheets0.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets0.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets0.FieldValues['SMETA_KOD']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SMETA_NAME1' then begin if DSetSheets0.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets0.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets0.FieldValues['SMETA_NAME']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='TYPE_SHEET2' then begin if DSetSheets1.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets1.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets1.FieldValues['TYPE_SHEET']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SUMA_SHEET2' then begin if DSetSheets1.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets1.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets1.FieldValues['SUMMA']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SMETA_KOD2' then begin if DSetSheets1.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets1.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets1.FieldValues['SMETA_KOD']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='SMETA_NAME2' then begin if DSetSheets1.RecordCount-1>=UDSSheets.RecNo then begin DSetSheets1.RecNo:=UDSSheets.RecNo+1; Value:=DSetSheets1.FieldValues['SMETA_NAME']; Exit; end else begin Value:=NULL; Exit; end end; if UpperCase(VarName)='P_VIPLATA1' then begin Sum_Nar:=0; DSetAccNarList0.First; while not DSetAccNarList0.Eof do Begin Sum_Nar:=Sum_Nar+IfThen(DSetAccNarList0['SUMMA']<>null,DSetAccNarList0['SUMMA'],0); DSetAccNarList0.Next; end; Sum_Ud:=0; DSetAccUdList0.First; while not DSetAccUdList0.Eof do Begin Sum_Ud:=Sum_Ud+DSetAccUdList0['SUMMA']; DSetAccUdList0.Next; end; Value:=FZPrintAccList_P_Viplata_Text+' '+FloatToStrF(Sum_Nar-Sum_Ud,ffFixed,16,2); end; if UpperCase(VarName)='P_VIPLATA2' then begin Sum_Nar:=0; DSetAccNarList1.First; while not DSetAccNarList1.Eof do Begin Sum_Nar:=Sum_Nar+IfThen(DSetAccNarList1['SUMMA']<>NULL,DSetAccNarList1['SUMMA'],0); DSetAccNarList1.Next; end; Sum_Ud:=0; DSetAccUdList1.First; while not DSetAccUdList1.Eof do Begin Sum_Ud:=Sum_Ud+IfThen(DSetAccUdList1['SUMMA']<>null,DSetAccUdList1['SUMMA'],0); DSetAccUdList1.Next; end; Value:=FZPrintAccList_P_Viplata_Text+' '+FloatToStrF(Sum_Nar-Sum_Ud,ffFixed,16,2); end; end else //////////// begin if UpperCase(VarName)='P_COMING_LEAVING' then begin Value:=PComingLeavingText; Exit; end; if UpperCase(VarName)='P_ACCLIST' then begin if(Report.Variables['P_ACCLIST']=null)then if(PType=0)then Value:=FZPrintAccList_P_AccList_Title+' '+AnsiLowerCase(KodSetupToPeriod(DSetGlobalData['KOD_SETUP1'],2)) else Value:='Відомість про фактичне нарахування за '+AnsiLowerCase(KodSetupToPeriod(DSetGlobalData['KOD_SETUP1'],2)) end; if UpperCase(VarName)='P_ACCLIST_SHORT' then begin frxUserDataSet.RangeEndCount:=IfThen(DSetAccNarList.RecordCount>DSetAccUdList.RecordCount,DSetAccNarList.RecordCount,DSetAccUdList.RecordCount); frxUserDataSet.RangeEnd:=reCount; end; if UpperCase(VarName)='P_TN' then begin frxUserDataSetComingLeaving.RangeEndCount:=IfThen(DSetComingLeaving.IsEmpty,0,1); frxUserDataSetComingLeaving.RangeEnd:=reCount; PComingLeavingText:=''; DSetComingLeaving.First; while not DSetComingLeaving.Eof do begin if VarToStrDef(DSetComingLeaving['IS_COMING'],'')='T' then PComingLeavingText:=PComingLeavingText+'Прийняття: '+VarToStr(DSetComingLeaving['REAL_DATE'])+' ' else PComingLeavingText:=PComingLeavingText+'Звільнення: '+VarToStr(DSetComingLeaving['REAL_DATE'])+' '; DSetComingLeaving.Next; end; frxUserDataSet.RangeEndCount:=IfThen(DSetAccNarList.RecordCount>DSetAccUdList.RecordCount,DSetAccNarList.RecordCount,DSetAccUdList.RecordCount); frxUserDataSet.RangeEnd:=reCount; Value:=FZPrintAccList_P_Tn_Text; Exit; end; if UpperCase(VarName)='P_SUM_NAR' then begin Sum_Nar:=0; DSetAccNarList.First; while not DSetAccNarList.Eof do Begin Sum_Nar:=Sum_Nar+IFTHEN(DSetAccNarList['SUMMA']<>NULL,DSetAccNarList['SUMMA'],0); DSetAccNarList.Next; end; Value:=FloatToStrF(Sum_Nar,ffFixed,16,2); end; if UpperCase(VarName)='P_SUM_UD' then begin Sum_Ud:=0; DSetAccUdList.First; while not DSetAccUdList.Eof do Begin Sum_Ud:=Sum_Ud+IFTHEN(DSetAccUdList['SUMMA']<>NULL,DSetAccUdList['SUMMA'],0); DSetAccUdList.Next; end; Value :=FloatToStrF(Sum_Ud,ffFixed,16,2); end; if UpperCase(VarName)='P_VIPLATA' then begin Sum_Nar:=0; DSetAccNarList.First; while not DSetAccNarList.Eof do Begin Sum_Nar:=Sum_Nar+IFTHEN(DSetAccNarList['SUMMA']<>NULL,DSetAccNarList['SUMMA'],0); DSetAccNarList.Next; end; Sum_Ud:=0; DSetAccUdList.First; while not DSetAccUdList.Eof do Begin Sum_Ud:=Sum_Ud+DSetAccUdList['SUMMA']; DSetAccUdList.Next; end; Value:=FZPrintAccList_P_Viplata_Text+' '+FloatToStrF(Sum_Nar-Sum_Ud,ffFixed,16,2); end; if UpperCase(VarName)='N_SUMMA' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccNarList.FieldValues['SUMMA']; end else Value:=NULL; end; if UpperCase(VarName)='N_CODE_DEPARTMENT' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccNarList.FieldValues['CODE_DEPARTMENT']; end else Value:=NULL; end; if UpperCase(VarName)='N_KOD_SETUP_3' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=KodSetupToPeriod(DSetAccNarList['KOD_SETUP3'],1); end else Value:=NULL; end; if UpperCase(VarName)='N_KOD_SM' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccNarList['KOD_SMETA']; end else Value:=NULL; end; if UpperCase(VarName)='N_KOD_VIDOPL' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccNarList.FieldValues['KOD_VIDOPL']; end else Value:=NULL; end; if UpperCase(VarName)='N_NAME_VIDOPL' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccNarList.FieldValues['NAME_VIDOPL']; end else Value:=NULL; end; if UpperCase(VarName)='N_DAY_CLOCK' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; Value:=DayClocks(self); end else Value:=NULL; end; if UpperCase(VarName)='N_DAY_CLOCK_SHORT' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; if (DSetAccNarList['NDAY']=0) or (VarIsNull(DSetAccNarList['NDAY'])) then Value:='' else begin sign:=IfThen(DSetAccNarList['NDAY']<0,'-',''); PValue:=Abs(DSetAccNarList['NDAY']); Value:=Sign+ifThen(PValue<10,'0','')+VarToStr(PValue); end; end else Value:=NULL; end; if UpperCase(VarName)='N_PERCENT_SUMCLOCK' then begin if DSetAccNarList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccNarList.RecNo:=frxUserDataSet.RecNo+1; if (ifthen(DSetAccNarList['PERCENT']<>NULL,DSetAccNarList['PERCENT'],0)<>0) then begin if (IfThen(DSetAccNarList['SUM_CLOCK']<>NULL, DSetAccNarList['SUM_CLOCK'], 0)<>0) then begin PValue:=DSetAccNarList['SUM_CLOCK']; Value:=FloatToStrF(PValue,ffFixed,5,2); end else Value := ''; PValue:=DSetAccNarList['PERCENT']; if Value<>'' then Value:=Value+'/'+FloatToStrF(PValue,ffFixed,4,2)+'%' else Value:=FloatToStrF(PValue,ffFixed,4,2)+'%'; end else begin if (IfThen(DSetAccNarList['SUM_CLOCK']<>NULL, DSetAccNarList['SUM_CLOCK'], 0)<>0) then begin PValue:=DSetAccNarList['SUM_CLOCK']; Value:=FloatToStrF(PValue,ffFixed,5,2); end else Value:=NULL; end; end else Value:=NULL; end; if UpperCase(VarName)='U_KOD_SETUP_3' then begin if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1; Value:=KodSetupToPeriod(DSetAccUdList['KOD_SETUP3'],1); end else Value:=NULL; end; if UpperCase(VarName)='U_KOD_VIDOPL' then begin if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccUdList.FieldValues['KOD_VIDOPL']; end else Value:=NULL; end; if UpperCase(VarName)='U_NAME_VIDOPL' then begin if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccUdList.FieldValues['NAME_VIDOPL']; end else Value:=NULL; end; if UpperCase(VarName)='U_SUMMA' then begin if DSetAccUdList.RecordCount-1>=frxUserDataSet.RecNo then begin DSetAccUdList.RecNo:=frxUserDataSet.RecNo+1; Value:=DSetAccUdList.FieldValues['SUMMA']; end else Value:=NULL; end; end end; procedure TPrintDM.DataModuleDestroy(Sender: TObject); begin if ReadTransaction.InTransaction then ReadTransaction.Commit; end; function TPrintDM.DayClocks(Sender:TObject):String; var PValue:Variant; Sign:string[1]; begin if (DSetAccNarList['NDAY']=0) or (VarIsNull(DSetAccNarList['NDAY'])) then Result:='--' else begin sign:=IfThen(DSetAccNarList['NDAY']<0,'-',''); PValue:=Abs(DSetAccNarList['NDAY']); Result:=Sign+ifThen(PValue<10,'0','')+VarToStr(PValue); end; Result:=Result+'/'; if (DSetAccNarList['CLOCK']=0) or (VarIsNull(DSetAccNarList['CLOCK'])) then Result:=Result+'---,--' else begin sign:=IfThen(DSetAccNarList['CLOCK']<0,'-',''); PValue:=Abs(DSetAccNarList['CLOCK']); Result:=Result+Sign+ifThen(PValue<10,'0'+FloatToStrF(PValue,ffFixed,5,3),FloatToStrF(PValue,ffFixed,6,3)); end; end; end.
unit AmccLib; Interface //////////////////////////////////////////////////////////////// // File - AMCCLIB.C // // Library for 'WinDriver for AMCC 5933' API. // The basic idea is to get a handle for the board // with AMCC_Open() and use it in the rest of the program // when calling WD functions. Call AMCC_Close() when done. // // Copyright (c) 2003 Jungo Ltd. http://www.jungo.com // Delphi Translation Gérard Sadoc 15-05-03 // //////////////////////////////////////////////////////////////// uses windows,util1, windrvr, pci_regs,bits, windrvr_int_thread, status_strings; type AMCC_MODE=integer; Const AMCC_MODE_BYTE=0; AMCC_MODE_WORD=1; AMCC_MODE_DWORD=2; type AMCC_ADDR=integer; Const AMCC_ADDR_REG = AD_PCI_BAR0; AMCC_ADDR_SPACE0 = AD_PCI_BAR1; AMCC_ADDR_SPACE1 = AD_PCI_BAR2; AMCC_ADDR_SPACE2 = AD_PCI_BAR3; AMCC_ADDR_SPACE3 = AD_PCI_BAR4; AMCC_ADDR_NOT_USED = AD_PCI_BAR5; type AMCC_INT_RESULT=record dwCounter: DWORD ; // number of interrupts received dwLost: DWORD ; // number of interrupts not yet dealt with fStopped: BOOL ; // was interrupt disabled during wait dwStatusReg: DWORD ; // value of status register when interrupt occurred end; AMCC_ADDR_DESC=record dwLocalBase: DWORD ; dwMask: DWORD ; dwBytes: DWORD ; dwAddr: DWORD ; dwAddrDirect:DWORD ; fIsMemory: BOOL ; end; AMCCHANDLE=^AMCC_STRUCT ; AMCC_INT_HANDLER= procedure ( hAmcc:AMCCHANDLE ; var intResult: AMCC_INT_RESULT );stdCall; AMCC_INTERRUPT=record Int: WD_INTERRUPT ; hThread: HANDLE ; Trans: array[0..1] of SWD_TRANSFER ; funcIntHandler: AMCC_INT_HANDLER ; end; AMCC_STRUCT= record hWD: THANDLE; cardLock: WD_CARD; pciSlot: WD_PCI_SLOT ; cardReg: WD_CARD_REGISTER ; addrDesc: array[0..AD_PCI_BARS-1] of AMCC_ADDR_DESC; Int: AMCC_INTERRUPT; end; function AMCC_CountCards (dwVendorID:Dword; dwDeviceID:Dword):Dword; function AMCC_Open (var phAmcc: AMCCHANDLE; dwVendorID, dwDeviceID, nCardNum:Dword):Bool; procedure AMCC_Close (hAmcc: AMCCHANDLE ); function AMCC_IsAddrSpaceActive(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ):Bool; procedure AMCC_WriteRegDWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ; data: DWORD ); function AMCC_ReadRegDWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ):Dword; procedure AMCC_WriteRegWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ; data: WORD ); function AMCC_ReadRegWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ):word; procedure AMCC_WriteRegByte (hAmcc: AMCCHANDLE ; dwReg: DWORD ; data: BYTE ); function AMCC_ReadRegByte (hAmcc: AMCCHANDLE ; dwReg: DWORD ):byte; procedure AMCC_WriteDWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: DWORD ); function AMCC_ReadDWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):Dword; procedure AMCC_WriteWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: WORD ); function AMCC_ReadWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):Word; procedure AMCC_WriteByte(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: BYTE ); function AMCC_ReadByte(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):byte; procedure AMCC_ReadWriteSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD ; buf:pointer; dwBytes: DWORD; fIsRead: BOOL; addrSpace: AMCC_ADDR ; mode: AMCC_MODE ); procedure AMCC_ReadSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD ; buf:pointer; dwBytes: DWORD; addrSpace: AMCC_ADDR ); procedure AMCC_WriteSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD ; buf:pointer; dwBytes: DWORD; addrSpace: AMCC_ADDR ); function AMCC_ReadNVByte(hAmcc: AMCCHANDLE ; dwAddr: DWORD ; var pbData:byte):Bool; // interrupt functions function AMCC_IntIsEnabled (hAmcc: AMCCHANDLE ):BOOL; function AMCC_IntEnable (hAmcc: AMCCHANDLE ; funcIntHandler: AMCC_INT_HANDLER ):BOOL; procedure AMCC_IntDisable (hAmcc: AMCCHANDLE ); // access pci configuration registers function AMCC_ReadPCIReg(hAmcc: AMCCHANDLE ; dwReg: DWORD ):Dword; procedure AMCC_WritePCIReg(hAmcc: AMCCHANDLE ; dwReg: DWORD ; dwData: DWORD ); // DMA functions function AMCC_DMAOpen(hAmcc: AMCCHANDLE ; var pDMA: WD_DMA ; dwBytes: DWORD ):BOOL; procedure AMCC_DMAClose(hAmcc: AMCCHANDLE ; var pDMA: WD_DMA ); function AMCC_DMAStart(hAmcc: AMCCHANDLE ;var pDMA: WD_DMA ; fRead: BOOL ; fBlocking: BOOL ; dwBytes: DWORD ; dwOffset: DWORD ):BOOL; function AMCC_DMAIsDone(hAmcc: AMCCHANDLE ; fRead: BOOL ):BOOL; // this string is set to an error message, if one occurs var AMCC_ErrorString:string; // Operation register offsets Const OMB1_ADDR = $00; OMB2_ADDR = $04; OMB3_ADDR = $08; OMB4_ADDR = $0c; IMB1_ADDR = $10; IMB2_ADDR = $14; IMB3_ADDR = $18; IMB4_ADDR = $1c; FIFO_ADDR = $20; MWAR_ADDR = $24; MWTC_ADDR = $28; MRAR_ADDR = $2c; MRTC_ADDR = $30; MBEF_ADDR = $34; INTCSR_ADDR = $38; BMCSR_ADDR = $3c; BMCSR_NVDATA_ADDR = BMCSR_ADDR + 2; BMCSR_NVCMD_ADDR = BMCSR_ADDR + 3; NVRAM_BUSY_BITS = BIT7 ; //* Bit 31 indicates if device busy NVCMD_LOAD_LOW_BITS = BIT7; // nvRAM Load Low command NVCMD_LOAD_HIGH_BITS = BIT5 OR BIT7; // nvRAM Load High command NVCMD_BEGIN_WRITE_BITS = BIT6 OR BIT7; // nvRAM Begin Write command NVCMD_BEGIN_READ_BITS = BIT5 OR BIT6 OR BIT7; // nvRAM Begin Read command AMCC_NVRAM_SIZE = $80 ; // size in bytes of nvRAM AIMB1 = $00; AIMB2 = $04; AIMB3 = $08; AIMB4 = $0c; AOMB1 = $10; AOMB2 = $14; AOMB3 = $18; AOMB4 = $1c; AFIFO = $20; AMWAR = $24; APTA = $28; APTD = $2c; AMRAR = $30; AMBEF = $34; AINT = $38; AGCSTS = $3c; Implementation const WD_PROD_NAME='WinDriver'; // internal function used by AMCC_Open() function AMCC_DetectCardElements(hAmcc: AMCCHANDLE ):BOOL;forward; function AMCC_CountCards (dwVendorID:Dword; dwDeviceID:Dword):Dword; var ver: SWD_VERSION ; pciScan: WD_PCI_SCAN_CARDS ; const hWD: HANDLE = INVALID_HANDLE_VALUE; var dwStatus: DWORD ; begin result:=0; AMCC_ErrorString:= ''; hWD := WD_Open(); // check if handle valid & version OK if (hWD=INVALID_HANDLE_VALUE) then begin AMCC_ErrorString:= 'Failed opening '+ WD_PROD_NAME +' device'; exit; end; fillchar(ver,sizeof(ver),0); WD_Version(hWD,ver); if (ver.dwVer<WD_VER) then begin AMCC_ErrorString:= 'Incorrect '+ WD_PROD_NAME +' version'; WD_Close (hWD); exit; end; fillchar(pciScan,sizeof(pciScan),0); pciScan.searchId.dwVendorId := dwVendorID; pciScan.searchId.dwDeviceId := dwDeviceID; dwStatus := WD_PciScanCards(hWD, pciScan); WD_Close(hWD); if dwStatus<>0 then AMCC_ErrorString:='WD_PciScanCards failed with status ='+Istr(dwStatus) else if (pciScan.dwCards=0) then AMCC_ErrorString:='no cards found'; result:= pciScan.dwCards; end; function AMCC_Open (var phAmcc: AMCCHANDLE; dwVendorID, dwDeviceID, nCardNum:Dword):Bool; var hAmcc:AMCCHANDLE; ver:SWD_VERSION ; pciScan: WD_PCI_SCAN_CARDS ; pciCardInfo: WD_PCI_CARD_INFO ; dwStatus: DWORD ; label exit0; begin new(hAmcc); phAmcc:=nil; AMCC_ErrorString:= ''; hAmcc^.hWD := WD_Open(); // check if handle valid & version OK if (hAmcc^.hWD=INVALID_HANDLE_VALUE) then begin AMCC_ErrorString:='Failed opening '+ WD_PROD_NAME +' device'; goto Exit0; end; fillchar(ver,sizeof(ver),0); WD_Version(hAmcc^.hWD,ver); if (ver.dwVer<WD_VER) then begin AMCC_ErrorString:='Incorrect '+ WD_PROD_NAME +' version'; goto Exit0; end; fillchar(pciScan,sizeof(pciScan),0); pciScan.searchId.dwVendorId := dwVendorID; pciScan.searchId.dwDeviceId := dwDeviceID; dwStatus := WD_PciScanCards (hAmcc^.hWD, pciScan); if (dwStatus<>0) then begin AMCC_ErrorString:='WD_PciScanCards() failed with status '+Istr(dwStatus); goto Exit0; end; if (pciScan.dwCards=0) then// Found at least one card begin AMCC_ErrorString:='Could not find PCI card'; goto Exit0; end; if (pciScan.dwCards<=nCardNum) then begin AMCC_ErrorString:='Card out of range of available cards'; goto Exit0; end; fillchar(pciCardInfo,sizeof(pciCardInfo),0); pciCardInfo.pciSlot := pciScan.cardSlot[nCardNum]; WD_PciGetCardInfo (hAmcc^.hWD, pciCardInfo); hAmcc^.pciSlot := pciCardInfo.pciSlot; hAmcc^.cardReg.Card := pciCardInfo.Card; hAmcc^.cardReg.fCheckLockOnly := 0; dwStatus := WD_CardRegister(hAmcc^.hWD, hAmcc^.cardReg); if (dwStatus<>0) then begin AMCC_ErrorString:='WD_CardRegister() failed with status '+Istr(dwStatus); end; if (hAmcc^.cardReg.hCard=0) then begin AMCC_ErrorString:='Failed locking device'; goto Exit0; end; if not AMCC_DetectCardElements(hAmcc) then begin AMCC_ErrorString:='Card does not have all items expected for AMCC'; goto Exit0; end; // Open finished OK phAmcc := hAmcc; result:=true; exit; Exit0: // Error during Open if (hAmcc^.cardReg.hCard<>0) then WD_CardUnregister(hAmcc^.hWD, hAmcc^.cardReg); if (hAmcc^.hWD <>INVALID_HANDLE_VALUE) then WD_Close(hAmcc^.hWD); dispose(hAmcc); result:= FALSE; end; function AMCC_ReadPCIReg(hAmcc: AMCCHANDLE ; dwReg: DWORD ):Dword; var pciCnf: WD_PCI_CONFIG_DUMP ; dwVal: DWORD ; begin fillchar(pciCnf,sizeof(pciCnf),0); pciCnf.pciSlot := hAmcc^.pciSlot; pciCnf.pBuffer := @dwVal; pciCnf.dwOffset := dwReg; pciCnf.dwBytes := 4; pciCnf.fIsRead := 1; WD_PciConfigDump(hAmcc^.hWD,pciCnf); result:= dwVal; end; procedure AMCC_WritePCIReg(hAmcc: AMCCHANDLE ; dwReg: DWORD ; dwData: DWORD ); var pciCnf: WD_PCI_CONFIG_DUMP ; begin fillchar (pciCnf,sizeof(pciCnf),0); pciCnf.pciSlot := hAmcc^.pciSlot; pciCnf.pBuffer := @dwData; pciCnf.dwOffset := dwReg; pciCnf.dwBytes := 4; pciCnf.fIsRead := 0; WD_PciConfigDump(hAmcc^.hWD,pciCnf); end; function AMCC_DetectCardElements(hAmcc: AMCCHANDLE ):BOOL; var i: DWORD ; ad_sp: DWORD ; pItem:^WD_ITEMS; begin fillchar(hAmcc^.Int,sizeof(hAmcc^.Int),0); fillchar(hAmcc^.addrDesc,sizeof(hAmcc^.addrDesc),0); for i:=0 to hAmcc^.cardReg.Card.dwItems-1 do begin pItem := @hAmcc^.cardReg.Card.Item[i]; case pItem^.item of ITEM_MEMORY: begin ad_sp := pItem^.Memory.dwBar; hAmcc^.addrDesc[ad_sp].fIsMemory := TRUE; hAmcc^.addrDesc[ad_sp].dwBytes := pItem^.Memory.dwMBytes; hAmcc^.addrDesc[ad_sp].dwAddr := pItem^.Memory.dwTransAddr; hAmcc^.addrDesc[ad_sp].dwAddrDirect := pItem^.Memory.dwUserDirectAddr; hAmcc^.addrDesc[ad_sp].dwMask := Not hAmcc^.addrDesc[ad_sp].dwBytes; {Tilde avant hAmcc} end; ITEM_IO: begin ad_sp := pItem^.IO.dwBar; hAmcc^.addrDesc[ad_sp].fIsMemory := FALSE; hAmcc^.addrDesc[ad_sp].dwBytes := pItem^.Memory.dwMBytes; hAmcc^.addrDesc[ad_sp].dwAddr := pItem^.IO.dwAddr; hAmcc^.addrDesc[ad_sp].dwMask := Not hAmcc^.addrDesc[ad_sp].dwBytes; {Tilde avant hAmcc} end; ITEM_INTERRUPT: begin if (hAmcc^.Int.Int.hInterrupt<>0) then begin result:= FALSE; exit; end; hAmcc^.Int.Int.hInterrupt := pItem^.Interrupt.hInterrupt; end; end; end; // check that the registers space was found if not AMCC_IsAddrSpaceActive(hAmcc, AMCC_ADDR_REG) then begin result:= FALSE; exit; end; // check that at least one memory space was found //for (i = AMCC_ADDR_SPACE0; i<=AMCC_ADDR_NOT_USED; i++) // if (AMCC_IsAddrSpaceActive(hAmcc, i)) break; //if (i>AMCC_ADDR_NOT_USED) return FALSE; result:= TRUE; end; procedure AMCC_Close (hAmcc: AMCCHANDLE ); begin // disable interrupts if (AMCC_IntIsEnabled(hAmcc)) then AMCC_IntDisable(hAmcc); // unregister card if (hAmcc^.cardReg.hCard<>0) then WD_CardUnregister(hAmcc^.hWD, hAmcc^.cardReg); // close WinDriver WD_Close(hAmcc^.hWD); dispose (hAmcc); end; function AMCC_IsAddrSpaceActive(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ):Bool; begin result:= (hAmcc^.addrDesc[addrSpace].dwAddr<>0); end; procedure AMCC_WriteRegDWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ; data: DWORD ); begin AMCC_WriteDWord (hAmcc, AMCC_ADDR_REG, dwReg, data); end; function AMCC_ReadRegDWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ):Dword; begin result:= AMCC_ReadDWord (hAmcc, AMCC_ADDR_REG, dwReg); end; procedure AMCC_WriteRegWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ; data: WORD ); begin AMCC_WriteWord (hAmcc, AMCC_ADDR_REG, dwReg, data); end; function AMCC_ReadRegWord (hAmcc: AMCCHANDLE ; dwReg: DWORD ):word; begin result:= AMCC_ReadWord (hAmcc, AMCC_ADDR_REG, dwReg); end; procedure AMCC_WriteRegByte (hAmcc: AMCCHANDLE ;dwReg: DWORD ; data: BYTE ); begin AMCC_WriteByte (hAmcc, AMCC_ADDR_REG, dwReg, data); end; function AMCC_ReadRegByte (hAmcc: AMCCHANDLE ; dwReg: DWORD ):byte; begin result:= AMCC_ReadByte (hAmcc, AMCC_ADDR_REG, dwReg); end; // performs a single 32 bit write from address space procedure AMCC_WriteDWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: DWORD ); var dwAddr: DWORD ; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; PDword(dwAddr)^:=data; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := WP_DWORD; trans.dwPort := dwAddr; trans.ADword := data; WD_Transfer (hAmcc^.hWD, trans); end; end; // performs a single 32 bit read from address space function AMCC_ReadDWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):Dword; var dwAddr: DWORD; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; result:=PDword(dwAddr)^; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := RP_DWORD; trans.dwPort := dwAddr; WD_Transfer (hAmcc^.hWD, trans); result:= trans.ADword; end; end; // performs a single 16 bit write from address space procedure AMCC_WriteWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: WORD ); var dwAddr: DWORD ; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; Pword(dwAddr)^:=data; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := WP_WORD; trans.dwPort := dwAddr; trans.ADword := data; WD_Transfer (hAmcc^.hWD, trans); end; end; // performs a single 16 bit read from address space function AMCC_ReadWord(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):word; var dwAddr: DWORD; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; result:=Pword(dwAddr)^; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := RP_WORD; trans.dwPort := dwAddr; WD_Transfer (hAmcc^.hWD, trans); result:= trans.Aword; end; end; // performs a single 8 bit write from address space procedure AMCC_WriteByte(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ; data: BYTE ); var dwAddr: DWORD ; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; Pbyte(dwAddr)^:=data; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := WP_BYTE; trans.dwPort := dwAddr; trans.ADword := data; WD_Transfer (hAmcc^.hWD, trans); end; end; // performs a single 8 bit read from address space function AMCC_ReadByte(hAmcc: AMCCHANDLE ; addrSpace: AMCC_ADDR ; dwLocalAddr: DWORD ):BYTE; var dwAddr: DWORD; trans: SWD_TRANSFER ; begin if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddrDirect + dwLocalAddr; result:=Pbyte(dwAddr)^; end else begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + dwLocalAddr; fillchar(trans,sizeof(trans),0); trans.cmdTrans := RP_BYTE; trans.dwPort := dwAddr; WD_Transfer (hAmcc^.hWD, trans); result:= trans.Abyte; end; end; procedure AMCC_ReadWriteSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD; buf: Pointer ; dwBytes: DWORD ; fIsRead: BOOL; addrSpace: AMCC_ADDR; mode: AMCC_MODE ); var trans: SWD_TRANSFER ; dwAddr: DWORD; begin dwAddr := hAmcc^.addrDesc[addrSpace].dwAddr + (hAmcc^.addrDesc[addrSpace].dwMask AND dwOffset); fillchar(trans,sizeof(trans),0); if (hAmcc^.addrDesc[addrSpace].fIsMemory) then begin if fIsRead then begin if (mode=AMCC_MODE_BYTE) then trans.cmdTrans := RM_SBYTE else if (mode=AMCC_MODE_WORD) then trans.cmdTrans := RM_SWORD else trans.cmdTrans := RM_SDWORD; end else begin if (mode=AMCC_MODE_BYTE) then trans.cmdTrans := WM_SBYTE else if (mode=AMCC_MODE_WORD) then trans.cmdTrans := WM_SWORD else trans.cmdTrans := WM_SDWORD; end end else begin if (fIsRead) then begin if (mode=AMCC_MODE_BYTE) then trans.cmdTrans := RP_SBYTE else if (mode=AMCC_MODE_WORD) then trans.cmdTrans := RP_SWORD else trans.cmdTrans := RP_SDWORD; end else begin if (mode=AMCC_MODE_BYTE) then trans.cmdTrans := WP_SBYTE else if (mode=AMCC_MODE_WORD) then trans.cmdTrans := WP_SWORD else trans.cmdTrans := WP_SDWORD; end; end; trans.dwPort := dwAddr; trans.fAutoinc := 1; trans.dwBytes := dwBytes; trans.dwOptions := 0; trans.pBuffer := buf; WD_Transfer (hAmcc^.hWD, trans); end; procedure AMCC_ReadSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD ; buf: Pointer ; dwBytes: DWORD ; addrSpace: AMCC_ADDR ); begin AMCC_ReadWriteSpaceBlock (hAmcc, dwOffset, buf, dwBytes, TRUE, addrSpace, AMCC_MODE_DWORD); end; procedure AMCC_WriteSpaceBlock (hAmcc: AMCCHANDLE ; dwOffset: DWORD ; buf: Pointer ; dwBytes: DWORD ; addrSpace: AMCC_ADDR ); begin AMCC_ReadWriteSpaceBlock (hAmcc, dwOffset, buf, dwBytes, FALSE, addrSpace, AMCC_MODE_DWORD); end; ////////////////////////////////////////////////////////////////////////////// // Interrupts ////////////////////////////////////////////////////////////////////////////// function AMCC_IntIsEnabled (hAmcc: AMCCHANDLE ):BOOL; begin result:=hAmcc^.Int.hThread<>0; end; procedure AMCC_IntHandler (pData: Pointer ); var hAmcc: AMCCHANDLE; intResult: AMCC_INT_RESULT ; begin hAmcc := pData; intResult.dwCounter := hAmcc^.Int.Int.dwCounter; intResult.dwLost := hAmcc^.Int.Int.dwLost; intResult.fStopped := hAmcc^.Int.Int.fStopped<>0; intResult.dwStatusReg := hAmcc^.Int.Trans[0].ADword; hAmcc^.Int.funcIntHandler(hAmcc, intResult); end; function AMCC_IntEnable (hAmcc: AMCCHANDLE ; funcIntHandler: AMCC_INT_HANDLER ):BOOL; var dwAddr: DWORD ; dwStatus: DWORD ; begin // check if interrupt is already enabled if (hAmcc^.Int.hThread<>0) then begin result:=FALSE; exit; end; fillchar(hAmcc^.Int.Trans,sizeof(hAmcc^.Int.Trans),0); // This is a sample of handling interrupts: // Two transfer commands are issued. First the value of the interrupt control/status // register is read. Then, a value of ZERO is written. // This will cancel interrupts after the first interrupt occurs. // When using interrupts, this section will have to change: // you must put transfer commands to CANCEL the source of the interrupt, otherwise, the // PC will hang when an interrupt occurs! dwAddr := hAmcc^.addrDesc[AMCC_ADDR_REG].dwAddr + INTCSR_ADDR; if hAmcc^.addrDesc[AMCC_ADDR_REG].fIsMemory then begin hAmcc^.Int.Trans[0].cmdTrans := RM_DWORD; hAmcc^.Int.Trans[1].cmdTrans := WM_DWORD; end else begin hAmcc^.Int.Trans[0].cmdTrans := RP_DWORD; hAmcc^.Int.Trans[1].cmdTrans := WP_DWORD; end; hAmcc^.Int.Trans[0].dwPort := dwAddr; hAmcc^.Int.Trans[1].dwPort := dwAddr; hAmcc^.Int.Trans[1].ADword := $8cc000; // put here the data to write to the control register hAmcc^.Int.Int.dwCmds := 2; hAmcc^.Int.Int.Cmd := @hAmcc^.Int.Trans; hAmcc^.Int.Int.dwOptions := hAmcc^.Int.Int.dwOptions OR INTERRUPT_CMD_COPY; // this calls WD_IntEnable() and creates an interrupt handler thread hAmcc^.Int.funcIntHandler := funcIntHandler; dwStatus := InterruptEnable(hAmcc^.Int.hThread, hAmcc^.hWD, hAmcc^.Int.Int, AMCC_IntHandler, hAmcc); if (dwStatus) { sprintf(AMCC_ErrorString, "WD_DMALock() failed with status 0x%x - %s\n", dwStatus, Stat2Str(dwStatus)); return FALSE; } // add here code to physically enable interrupts, // by setting bits in the INTCSR_ADDR register return TRUE; } procedure AMCC_IntDisable (AMCCHANDLE hAmcc) { if (!hAmcc^.Int.hThread) return; // add here code to physically disable interrupts, // by clearing bits in the INTCSR_ADDR register // this calls WD_IntDisable() InterruptDisable(hAmcc^.Int.hThread); hAmcc^.Int.hThread = NULL; } ////////////////////////////////////////////////////////////////////////////// // NVRam ////////////////////////////////////////////////////////////////////////////// BOOL AMCC_WaitForNotBusy(AMCCHANDLE hAmcc) { BOOL fReady = FALSE; time_t timeStart = time(NULL); for (; !fReady; ) { if ((AMCC_ReadRegByte(hAmcc, BMCSR_NVCMD_ADDR) & NVRAM_BUSY_BITS) != NVRAM_BUSY_BITS) { fReady = TRUE; } else { if ((time(NULL) - timeStart) > 1) /* More than 1 second? */ break; } } return fReady; } BOOL AMCC_ReadNVByte(AMCCHANDLE hAmcc, DWORD dwAddr, BYTE *pbData) { if (dwAddr >= AMCC_NVRAM_SIZE) return FALSE; /* Access non-volatile memory */ /* Wait for nvRAM not busy */ if (!AMCC_WaitForNotBusy(hAmcc)) return FALSE; /* Load Low address */ AMCC_WriteRegByte(hAmcc, BMCSR_NVCMD_ADDR, NVCMD_LOAD_LOW_BITS); AMCC_WriteRegByte(hAmcc, BMCSR_NVDATA_ADDR, (BYTE) (dwAddr & $ff)); /* Load High address */ AMCC_WriteRegByte(hAmcc, BMCSR_NVCMD_ADDR, NVCMD_LOAD_HIGH_BITS); AMCC_WriteRegByte(hAmcc, BMCSR_NVDATA_ADDR, (BYTE) (dwAddr >> 8)); /* Send Begin Read command */ AMCC_WriteRegByte(hAmcc, BMCSR_NVCMD_ADDR, NVCMD_BEGIN_READ_BITS); /* Wait for nvRAM not busy */ if (!AMCC_WaitForNotBusy(hAmcc)) return FALSE; /* Get data from nvRAM Data register */ *pbData = AMCC_ReadRegByte(hAmcc, BMCSR_NVDATA_ADDR); return TRUE; } ////////////////////////////////////////////////////////////////////////////// // DMA ////////////////////////////////////////////////////////////////////////////// BOOL AMCC_DMAOpen(AMCCHANDLE hAmcc, WD_DMA *pDMA, DWORD dwBytes) { DWORD dwStatus; AMCC_ErrorString[0] = '\0'; fillchar(*pDMA); pDMA^.pUserAddr = NULL; // the kernel will allocate the buffer pDMA^.dwBytes = dwBytes; // size of buffer to allocate pDMA^.dwOptions = DMA_KERNEL_BUFFER_ALLOC; dwStatus = WD_DMALock(hAmcc^.hWD, pDMA); if (dwStatus) { sprintf(AMCC_ErrorString, "WD_DMALock() failed with status 0x%x - %s\n", dwStatus, Stat2Str(dwStatus)); return FALSE; } return TRUE; } procedure AMCC_DMAClose(AMCCHANDLE hAmcc, WD_DMA *pDMA) { WD_DMAUnlock (hAmcc^.hWD, pDMA); } BOOL AMCC_DMAStart(AMCCHANDLE hAmcc, WD_DMA *pDMA, BOOL fRead, BOOL fBlocking, DWORD dwBytes, DWORD dwOffset) { DWORD dwBMCSR; // Important note: // fRead - if TRUE, data moved from the AMCC-card to the PC memory // fRead - if FALSE, data moved from the PC memory to the AMCC card // the terms used by AMCC are opposite! // in AMCC terms - read operation is from PC memory to AMCC card AMCC_WriteRegDWord(hAmcc, fRead ? MWAR_ADDR : MRAR_ADDR, (DWORD) pDMA^.Page[0].pPhysicalAddr + dwOffset); AMCC_WriteRegDWord(hAmcc, fRead ? MWTC_ADDR : MRTC_ADDR, dwBytes); dwBMCSR = AMCC_ReadRegDWord(hAmcc, BMCSR_ADDR); dwBMCSR |= fRead ? BIT10 : BIT14; AMCC_WriteRegDWord(hAmcc, BMCSR_ADDR, dwBMCSR); // if blocking then wait for transfer to complete if (fBlocking) while (!AMCC_DMAIsDone(hAmcc, fRead)); return TRUE; } BOOL AMCC_DMAIsDone(AMCCHANDLE hAmcc, BOOL fRead) { DWORD dwBIT = fRead ? BIT18 : BIT19; DWORD dwINTCSR = AMCC_ReadRegDWord(hAmcc, INTCSR_ADDR); if (dwINTCSR & dwBIT) { AMCC_WriteRegDWord(hAmcc, INTCSR_ADDR, dwBIT); return TRUE; } return FALSE; }
unit uProcedure; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; procedure FindFiles(StartFolder, Mask: string; List: TStrings; ScanSubFolders: Boolean = True); implementation uses ShellApi, Masks; procedure FindFiles(StartFolder, Mask: string; List: TStrings; ScanSubFolders: Boolean = True); var SearchRec : TSearchRec; FindResult : Integer; begin List.BeginUpdate; try StartFolder := IncludeTrailingPathDelimiter(StartFolder); FindResult := FindFirst(StartFolder + Mask, faAnyFile, SearchRec); try while FindResult = 0 do with SearchRec do begin if (Attr and faDirectory) <> 0 then begin if ScanSubFolders and (Name <> '.') and (Name <> '..') then FindFiles(StartFolder + Name, Mask, List, ScanSubFolders); end else begin if MatchesMask(Name, Mask) then List.Add(StartFolder + Name); end; FindResult := FindNext(SearchRec); end; finally FindClose(SearchRec); end; finally List.EndUpdate; end; end; end.
unit Chapter07._04_Solution1; {$mode objfpc}{$H+} {$WARN 4104 off : Implicit string type conversion from "$1" to "$2"} interface uses Classes, SysUtils, AI.TreeNode, DeepStar.Utils; /// 257. Binary Tree Paths /// https://leetcode.com/problems/binary-tree-paths/description/ /// 时间复杂度: O(n), n为树中的节点个数 /// 空间复杂度: O(h), h为树的高度 type TSolution = class(TObject) public function binaryTreePaths(root: TTreeNode): TList_str; end; procedure Main; implementation procedure Main; var a: TArr_int; t: TTreeNode; listStr: TList_str; i: integer; begin a := [9, 3, 20, 15, 7]; t := TTreeNode.Create(a); with TSolution.Create do begin listStr := binaryTreePaths(t); for i := 0 to listStr.Count-1 do WriteLn(listStr[i]); listStr.Free; Free; end; t.ClearAndFree; end; { TSolution } function TSolution.binaryTreePaths(root: TTreeNode): TList_str; var res, lstr, rstr: TList_str; i: integer; begin res := TList_str.Create; if root = nil then Exit(res); if (root.Left = nil) and (root.Right = nil) then res.AddLast(root.Val.ToString); lstr := binaryTreePaths(root.Left); for i := 0 to lstr.Count - 1 do res.AddLast(root.Val.ToString + '->' + lstr[i]); lstr.Free; rstr := binaryTreePaths(root.Right); for i := 0 to rstr.Count - 1 do res.AddLast(root.Val.ToString + '->' + rstr[i]); rstr.Free; Result := res; end; end.
unit MainReportsPrintVip; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, FIBQuery, pFIBQuery, pFIBStoredProc, ActnList, frxDesgn, frxClass, DB, FIBDataSet, pFIBDataSet, frxDBSet, FIBDatabase, pFIBDatabase, ComCtrls, StdCtrls, cxButtons, IBase, frxExportRTF, cxControls, cxContainer, cxEdit, cxLabel; type TfrmMainReportsPrintVip = class(TForm) cxButton1: TcxButton; cxButton2: TcxButton; StatusBar1: TStatusBar; pFIBDatabase: TpFIBDatabase; WriteTransaction: TpFIBTransaction; ReadTransaction: TpFIBTransaction; frxDBDataset: TfrxDBDataset; pFIBDataSet: TpFIBDataSet; frxDesigner1: TfrxDesigner; ActionList1: TActionList; Designer: TAction; pFIBStoredProc: TpFIBStoredProc; frxRTFExport1: TfrxRTFExport; frxReport: TfrxReport; cxLabel1: TcxLabel; procedure cxButton2Click(Sender: TObject); procedure DesignerExecute(Sender: TObject); procedure cxButton1Click(Sender: TObject); procedure frxReportGetValue(const VarName: String; var Value: Variant); private print_page : integer; constructor Create (Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64);overload; { Private declarations } public { Public declarations } end; function ReportsPrintVip(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64):Integer;stdcall; exports ReportsPrintVip; var frmMainReportsPrintVip: TfrmMainReportsPrintVip; id_people_print:Int64; designer_rep:integer; implementation {$R *.dfm} function ReportsPrintVip(AOwner:TComponent;DB:TISC_DB_HANDLE;id_people:Int64):Integer; var PrProp:TfrmMainReportsPrintVip; begin PrProp:=TfrmMainReportsPrintVip.Create(AOwner,DB,id_people); PrProp.ShowModal; PrProp.Free; end; constructor TfrmMainReportsPrintVip.Create (Aowner:Tcomponent;DBL:TISC_DB_HANDLE;id_people:Int64); begin Inherited Create(Aowner); pFIBDatabase.Handle:=DBL; id_people_print:=id_people; print_page := 1; end; procedure TfrmMainReportsPrintVip.cxButton2Click(Sender: TObject); begin Close; end; procedure TfrmMainReportsPrintVip.DesignerExecute(Sender: TObject); begin if designer_rep=0 then begin designer_rep:=1; StatusBar1.Panels[0].Text:='Режим отладки отчетов'; end else begin designer_rep:=0; StatusBar1.Panels[0].Text:=''; end; end; procedure TfrmMainReportsPrintVip.cxButton1Click(Sender: TObject); begin pFIBDataSet.Database:=pFIBDatabase; pFIBDataSet.Transaction:=ReadTransaction; pFIBDataSet.Active:=false; pFIBDataSet.ParamByName('param_people').AsInt64:=id_people_print; pFIBDataSet.Active:=true; frxReport.Clear; if print_page = 1 then begin frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\PeopleN35_VIP.fr3'); cxLabel1.Caption := 'Друк другої сторінки'; print_page := 2; End else begin frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\PeopleN35_VIP_Page2.fr3'); print_page := 3; end; frxReport.Variables.Clear; if designer_rep=1 then frxReport.DesignReport else begin frxReport.PrepareReport(); frxReport.PrintOptions.ShowDialog:=false; frxReport.Print; if print_page = 3 then Close; end; end; procedure TfrmMainReportsPrintVip.frxReportGetValue(const VarName: String; var Value: Variant); var q: TpFIBDataSet; begin if VarName='NA4ALNIK' then begin q:=TpFIBDataSet.Create(nil); q.Database:=pFIBDatabase; q.SelectSQL.Text:='select d.ST_MAIN_PASP_UKR from ST_INI d'; q.Open; Value:=q.FBN('ST_MAIN_PASP_UKR').AsString; end; end; end.
unit uMain_frm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.TabControl, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView, FMX.Memo, REST.Backend.MetaTypes, REST.Backend.ServiceTypes, MDB.BusinessObjects, FMX.Edit; type Tfrm_Main = class(TForm) tc_main: TTabControl; ti_ListRecipes: TTabItem; ti_EditRecipe: TTabItem; tb_HdrList: TToolBar; lbl_HdrList: TLabel; lv_Recipes: TListView; btn_AddRecipe: TButton; btn_RefreshList: TButton; ti_ViewRecipe: TTabItem; tb_HdrView: TToolBar; tb_Hdr_Edit: TToolBar; lbl_HdrView: TLabel; btn_EditRecipe: TButton; btn_Back2List: TButton; lbl_HdrEdit: TLabel; btn_Back2View: TButton; lbl_RecipeTitle: TLabel; memo_ViewRecipeBody: TMemo; edt_EditReceipeTitle: TEdit; memo_EditReceipeBody: TMemo; btn_SaveRecipe: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btn_AddRecipeClick(Sender: TObject); procedure btn_RefreshListClick(Sender: TObject); procedure lv_RecipesDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); procedure lv_RecipesItemClick(const Sender: TObject; const AItem: TListViewItem); procedure btn_Back2ListClick(Sender: TObject); procedure btn_Back2ViewClick(Sender: TObject); procedure btn_EditRecipeClick(Sender: TObject); procedure btn_SaveRecipeClick(Sender: TObject); private { Private declarations } FActiveRecipe : TRecipe; FRecipesList : TBackendObjectList<TRecipe>; function ObjectIDFromRecipe( const ARecipe : TRecipe ) : string; procedure DoAddRecipe; procedure DoEditRecipe( const ARecipe : TRecipe ); procedure DoDisplayRecipe; procedure DoSaveRecipe; procedure DoDeleteRecipe( const AObjectID : string ); procedure DoListRecipes; public { Public declarations } end; var frm_Main: Tfrm_Main; implementation uses MBD.DataModule; {$R *.fmx} procedure Tfrm_Main.btn_AddRecipeClick(Sender: TObject); begin DoAddRecipe; end; procedure Tfrm_Main.btn_Back2ListClick(Sender: TObject); begin tc_main.SetActiveTabWithTransition( ti_ListRecipes, TTabTransition.Slide, TTabTransitionDirection.Reversed ); end; procedure Tfrm_Main.btn_Back2ViewClick(Sender: TObject); begin tc_main.SetActiveTabWithTransition( ti_ViewRecipe, TTabTransition.Slide, TTabTransitionDirection.Reversed ); end; procedure Tfrm_Main.btn_EditRecipeClick(Sender: TObject); begin DoEditRecipe( FActiveRecipe ); end; procedure Tfrm_Main.btn_RefreshListClick(Sender: TObject); begin DoListRecipes; end; procedure Tfrm_Main.btn_SaveRecipeClick(Sender: TObject); begin if NOT Assigned(FActiveRecipe) then FActiveRecipe := TRecipe.Create; FActiveRecipe.Title := edt_EditReceipeTitle.Text; FActiveRecipe.Body := memo_EditReceipeBody.Text; DoSaveRecipe; DoDisplayRecipe; end; procedure Tfrm_Main.DoAddRecipe; begin FActiveRecipe := nil; edt_EditReceipeTitle.Text := ''; memo_EditReceipeBody.Text := ''; tc_main.SetActiveTabWithTransition( ti_EditRecipe, TTabTransition.Slide, TTabTransitionDirection.Normal ); end; procedure Tfrm_Main.DoDeleteRecipe( const AObjectID : string ); begin dm.BackendStorage.Storage.DeleteObject(BaasSCollectionIdentifier, AObjectID); end; procedure Tfrm_Main.DoDisplayRecipe; begin lbl_RecipeTitle.Text := FActiveRecipe.Title; memo_ViewRecipeBody.Text := FActiveRecipe.Body; tc_main.SetActiveTabWithTransition( ti_ViewRecipe, TTabTransition.Slide, TTabTransitionDirection.Normal ); end; procedure Tfrm_Main.DoEditRecipe(const ARecipe: TRecipe); begin edt_EditReceipeTitle.Text := ARecipe.Title; memo_EditReceipeBody.Text := ARecipe.Body; tc_main.SetActiveTabWithTransition( ti_EditRecipe, TTabTransition.Slide, TTabTransitionDirection.Normal ); end; procedure Tfrm_Main.DoListRecipes; var LQuery : TArray<string>; LItem : TListViewItem; LRecipe : TRecipe; LEntity : TBackendEntityValue; begin /// somehow there is a .clear missing ... ? FRecipesList.Free; FRecipesList := TBackendObjectList<TRecipe>.Create; LQuery := TArray<string>.Create('sort=name'); dm.BackendStorage.Storage.QueryObjects<TRecipe>(BaasSCollectionIdentifier, LQuery, FRecipesList); lv_Recipes.BeginUpdate; TRY lv_Recipes.Items.Clear; for LRecipe IN FRecipesList do begin LEntity := FRecipesList.EntityValues[ LRecipe ]; LItem := lv_Recipes.Items.Add; LItem.Text := LRecipe.Title; LItem.Data['objectid'] := LEntity.ObjectID; end; FINALLY lv_Recipes.EndUpdate; END; end; procedure Tfrm_Main.DoSaveRecipe; var LEntity : TBackendEntityValue; begin if ObjectIDFromRecipe(FActiveRecipe) <> '' then begin dm.BackendStorage.Storage.UpdateObject( FRecipesList.EntityValues[FActiveRecipe], FActiveRecipe, LEntity ); end else begin dm.BackendStorage.Storage.CreateObject<TRecipe>(BaasSCollectionIdentifier, FActiveRecipe, LEntity); FRecipesList.Add( FActiveRecipe, LEntity ); end; end; procedure Tfrm_Main.FormCreate(Sender: TObject); begin FActiveRecipe := nil; FRecipesList := TBackendObjectList<TRecipe>.Create; tc_main.ActiveTab := ti_ListRecipes; tc_main.TabPosition := TTabPosition.None; end; procedure Tfrm_Main.FormDestroy(Sender: TObject); begin FreeAndNil( FRecipesList ); end; procedure Tfrm_Main.lv_RecipesDeletingItem(Sender: TObject; AIndex: Integer; var ACanDelete: Boolean); begin FActiveRecipe := FRecipesList[ AIndex ]; if MessageDlg('Delete recipe "'+FActiveRecipe.Title+'"', TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0, TMsgDlgBtn.mbNo) = mrYes then begin DoDeleteRecipe( ObjectIDFromRecipe(FActiveRecipe) ); end; end; procedure Tfrm_Main.lv_RecipesItemClick(const Sender: TObject; const AItem: TListViewItem); begin FActiveRecipe := FRecipesList[ AItem.Index ]; DoDisplayRecipe; end; function Tfrm_Main.ObjectIDFromRecipe( const ARecipe : TRecipe ) : string; begin if Assigned(ARecipe) and (FRecipesList.IndexOf( ARecipe ) > -1) then result := FRecipesList.EntityValues[ ARecipe ].ObjectID else result := ''; end; end.
unit Objekt.DHLVersion; interface uses SysUtils, Classes, geschaeftskundenversand_api_2; type TDHLVersion = class private fVersionAPI: Version; fminorRelease: Integer; fmajorRelease: Integer; procedure setmajorRelease(const Value: Integer); procedure setminorRelease(const Value: Integer); public constructor Create; destructor Destroy; override; function VersionAPI: Version; property majorRelease: Integer read fmajorRelease write setmajorRelease; property minorRelease: Integer read fminorRelease write setminorRelease; end; implementation { TDHLVersion } constructor TDHLVersion.Create; begin fVersionAPI := Version.Create; setmajorRelease(2); setminorRelease(2); end; destructor TDHLVersion.Destroy; begin FreeAndNil(fVersionAPI); inherited; end; procedure TDHLVersion.setmajorRelease(const Value: Integer); begin fmajorRelease := Value; //fVersionAPI.majorRelease := IntToStr(Value); fVersionAPI.majorRelease := ''; end; procedure TDHLVersion.setminorRelease(const Value: Integer); begin fminorRelease := Value; //fVersionAPI.minorRelease := IntToStr(Value); fVersionAPI.minorRelease := ''; end; function TDHLVersion.VersionAPI: Version; begin Result := fVersionAPI; end; end.
unit Serialize.Attributes; interface uses Serialialize.Types; type ArrayObjects = class(TCustomAttribute) private FTypeArray: TEnumTypeDelphiGenerics; procedure SetTypeArray(const Value: TEnumTypeDelphiGenerics); public constructor Create(AType: TEnumTypeDelphiGenerics); destructor destroy; override; property TypeArray: TEnumTypeDelphiGenerics read FTypeArray write SetTypeArray; end; JsonNameAttribute = class(TCustomAttribute) private FName: string; public constructor Create(AName: string); property Name: String read FName; end; JSONBooleanAttribute = class(TCustomAttribute) private FValue: Boolean; public constructor Create(val: Boolean = true); property Value: Boolean read FValue; end; implementation { ArrayObjects } constructor ArrayObjects.Create(AType: TEnumTypeDelphiGenerics); begin TypeArray := AType; end; destructor ArrayObjects.destroy; begin inherited; end; procedure ArrayObjects.SetTypeArray(const Value: TEnumTypeDelphiGenerics); begin FTypeArray := Value; end; { JSONBooleanAttribute } constructor JSONBooleanAttribute.Create(val: Boolean); begin FValue := val; end; { JsonNameAttribute } constructor JsonNameAttribute.Create(AName: string); begin FName := AName; end; end.
unit UnitWelcome; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, UnitGlobal, UnitConsts, UnitTypesAndVars, ShellAPI; type TFormWelcome = class(TForm) cmbGameList: TComboBox; btnOK: TButton; lblUpdateTime: TLabel; lblSelectID: TLabel; lblEditer: TLabel; lblLinkBBS: TLabel; lblThank: TLabel; btnExit: TButton; btnRefresh: TButton; procedure FormCreate(Sender: TObject); procedure lblLinkBBSClick(Sender: TObject); procedure cmbGameListChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnRefreshClick(Sender: TObject); procedure cmbGameListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure RefreshList; public { Public declarations } end; var FormWelcome: TFormWelcome; function ShowMe(AOwner: TComponent): boolean; implementation uses tlhelp32, ClsGames; resourcestring rsErr_NotFindHL = 'Could not find Monster and Me Client. Closing program.'; {$R *.dfm} procedure GetHLInfo(); var s: string; ok: Bool; ProcessListHandle, ProcessHandle: THandle; ProcessStruct: TProcessEntry32; lpBuffer: PAnsiChar; lpNumberOfBytes: SIZE_T; myhl: THLInfo; begin ProcessListHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); try ProcessStruct.dwSize := Sizeof(ProcessStruct); ok := Process32First(ProcessListHandle, ProcessStruct); while ok do begin s := ExtractFileName(ProcessStruct.szExeFile); if AnsiCompareText(Trim(s), HL_EXE_Name) = 0 then begin ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, false, ProcessStruct.th32ProcessID); try myhl := THLInfo.Create; myhl.ProcessID := ProcessStruct.th32ProcessID; lpBuffer := AllocMem(UserNameSize); ReadProcessMemory(ProcessHandle, Pointer(UserNameAddress), lpBuffer, UserNameSize, lpNumberOfBytes); myhl.UserName := lpBuffer; ReadProcessMemory(ProcessHandle, Pointer(UserNickAddress), lpBuffer, UserNameSize, lpNumberOfBytes); myhl.UserNick := lpBuffer; ReadProcessMemory(ProcessHandle, Pointer(UserSpouseAddress), lpBuffer, UserNameSize, lpNumberOfBytes); myhl.UserSpouse := lpBuffer; FreeMem(lpBuffer, UserNameSize); if myhl.ReCalWin > 0 then HLInfoList.Add(myhl) else myhl.Free; finally CloseHandle(ProcessHandle); end; end; ok := Process32Next(ProcessListHandle, ProcessStruct); end; finally CloseHandle(ProcessListHandle); end; end; function FindHL: Boolean; begin HLInfoList.Clear; GetHLInfo(); Result := HLInfoList.Count > 0; if Result then begin InitNPCs; ThisWGAttrs.MC := 'HLHLReborn'; ThisWGAttrs.XS := '1'; ThisWGAttrs.NL := '100'; ThisWGAttrs.QS := '1'; ThisWGAttrs.GJ := '1'; ThisWGAttrs.BZ := '1'; end; end; function ShowMe(AOwner: TComponent): boolean; begin Result := False; if FindHL = False then begin ShowMessage(rsErr_NotFindHL); Exit; end; with TFormWelcome.Create(AOwner) do try if ParamCount > 0 then if LowerCase(ParamStr(1)) = '-d' then btnOK.Enabled := True; Result := ShowModal = mrOK; finally Release; end; end; procedure TFormWelcome.RefreshList; var i: integer; myhl: THLInfo; begin for i := HLInfoList.Count - 1 downto 0 do begin myhl := HLInfoList.Items[i]; if Length(myhl.UserName) <> 0 then cmbGameList.Items.Add(myhl.UserName); end; btnOK.Enabled := cmbGameList.Items.Count > 0; if btnOK.Enabled then begin cmbGameList.ItemIndex := 0; end; end; procedure TFormWelcome.btnRefreshClick(Sender: TObject); begin cmbGameList.Clear; if FindHL then RefreshList; end; procedure TFormWelcome.FormCreate(Sender: TObject); begin self.Caption := 'HLHLReborn Ver ' + GetHLHLVer; lblUpdateTime.Caption := 'Updated: ' + RS_UpDateTime; RefreshList; end; procedure TFormWelcome.lblLinkBBSClick(Sender: TObject); // 连接到BBS论坛 begin ShellApi.ShellExecute(Handle, 'Open', 'Http://www.google.com', nil, nil, SW_SHOWNORMAL) end; procedure TFormWelcome.cmbGameListChange(Sender: TObject); begin if btnOK.CanFocus then btnOK.SetFocus; end; procedure TFormWelcome.FormShow(Sender: TObject); begin cmbGameList.SetFocus; end; procedure TFormWelcome.FormClose(Sender: TObject; var Action: TCloseAction); var i, ID: integer; myhl: THLInfo; sName: string; begin case self.ModalResult of mrOK: begin sName := cmbGameList.Items[cmbGameList.ItemIndex]; ID := -1; for i := HLInfoList.Count - 1 downto 0 do begin myhl := HLInfoList.Items[i]; if myhl.UserName = sName then HLInfoList.SelectIndex := i // 保留 else myhl.Clear; // 清空窗口信息 end; HLInfoList.GlobalHL.ReCalWin; Application.Title := 'HLHLReborn - ' + HLInfoList.GlobalHL.UserName; end; mrCancel: HLInfoList.SelectIndex := -1; end; end; procedure TFormWelcome.cmbGameListKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then if self.btnOK.CanFocus then btnOK.Click else if self.btnRefresh.CanFocus then btnRefresh.Click; end; end.
{: "Earth" Demo.<p> See accompanying Readme.txt for user instructions.<p> The atmospheric effect is rendered in GLDirectOpenGL1Render, which essentially renders a disk, with color of the vertices computed via ray-tracing. Not that the tesselation of the disk has been hand-optimized so as to reduce CPU use while retaining quality. On anything >1 GHz, the rendering is fill-rate limited on a GeForce 4 Ti 4200.<p> Stars support is built into the TGLSkyDome, but constellations are rendered via a TGLLines, which is filled in the LoadConstellationLines method.<p> Eric Grange<br> http://glscene.org } unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, GLScene, GLObjects, GLWin32Viewer, GLSkydome, GLTexture, ExtCtrls, GLCadencer, GLLensFlare, GLTexCombineShader, GLMaterial, GLCoordinates, GLCrossPlatform, BaseClasses, GLRenderContextInfo, GLColor, GLState; type TForm1 = class(TForm) GLScene: TGLScene; GLSceneViewer: TGLSceneViewer; GLCamera: TGLCamera; SPEarth: TGLSphere; LSSun: TGLLightSource; GLDirectOpenGL1: TGLDirectOpenGL; GLCadencer: TGLCadencer; Timer1: TTimer; SPMoon: TGLSphere; DCEarthSystem: TGLDummyCube; DCMoon: TGLDummyCube; GLLensFlare1: TGLLensFlare; GLMaterialLibrary: TGLMaterialLibrary; EarthCombiner: TGLTexCombineShader; GLCameraControler: TGLCamera; GLSkyDome: TGLSkyDome; ConstellationLines: TGLLines; procedure FormCreate(Sender: TObject); procedure GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo); procedure Timer1Timer(Sender: TObject); procedure GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); procedure GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); procedure GLSceneViewerDblClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure GLSceneViewerBeforeRender(Sender: TObject); private { Private declarations } procedure LoadConstellationLines; public { Public declarations } constellationsAlpha : Single; timeMultiplier : Single; mx, my, dmx, dmy : Integer; highResResourcesLoaded : Boolean; cameraTimeSteps : Single; end; var Form1: TForm1; implementation {$R *.dfm} {$IFNDEF VER130} {$WARN UNIT_PLATFORM OFF} {$ENDIF} uses FileCtrl, Jpeg, OpenGL1x, VectorGeometry, GLContext, GLTextureFormat; // accurate movements left for later... or the astute reader // USolarSystem; procedure TForm1.FormCreate(Sender: TObject); begin SetCurrentDir(ExtractFilePath(Application.ExeName)); GLSkyDome.Bands.Clear; if FileExists('Yale_BSC.stars') then GLSkyDome.Stars.LoadStarsFile('Yale_BSC.stars'); LoadConstellationLines; timeMultiplier:=1; end; procedure TForm1.GLSceneViewerBeforeRender(Sender: TObject); begin GLLensFlare1.PreRender(Sender as TGLSceneBuffer); // if no multitexturing or no combiner support, turn off city lights if GL_ARB_multitexture and GL_ARB_texture_env_combine then begin GLMaterialLibrary.Materials[0].Shader:=EarthCombiner; GLMaterialLibrary.Materials[0].Texture2Name:='earthNight'; end else begin GLMaterialLibrary.Materials[0].Shader:=nil; GLMaterialLibrary.Materials[0].Texture2Name:=''; end; end; procedure TForm1.GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo); const // unrealisticly thick atmospheres look better :) cAtmosphereRadius : Single = 0.55; // use value slightly lower than actual radius, for antialiasing effect cPlanetRadius : Single = 0.495; cLowAtmColor : TColorVector = (1, 1, 1, 1); cHighAtmColor : TColorVector = (0, 0, 1, 1); cOpacity : Single = 5; cIntDivTable : array [2..20] of Single = (1/2, 1/3, 1/4, 1/5, 1/6, 1/7, 1/8, 1/9, 1/10, 1/11, 1/12, 1/13, 1/14, 1/15, 1/16, 1/17, 1/18, 1/19, 1/20); var radius, invAtmosphereHeight : Single; sunPos, eyePos, lightingVector : TVector; diskNormal, diskRight, diskUp : TVector; function AtmosphereColor(const rayStart, rayEnd : TVector) : TColorVector; var i, n : Integer; atmPoint, normal : TVector; altColor : TColorVector; alt, rayLength, contrib, decay, intensity, invN : Single; begin Result:=clrTransparent; rayLength:=VectorDistance(rayStart, rayEnd); n:=Round(3*rayLength*invAtmosphereHeight)+2; if n>10 then n:=10; invN:=cIntDivTable[n];//1/n; contrib:=rayLength*invN*cOpacity; decay:=1-contrib*0.5; contrib:=contrib*(1/1.1); for i:=n-1 downto 0 do begin VectorLerp(rayStart, rayEnd, i*invN, atmPoint); // diffuse lighting normal normal:=VectorNormalize(atmPoint); // diffuse lighting intensity intensity:=VectorDotProduct(normal, lightingVector)+0.1; if PInteger(@intensity)^>0 then begin // sample on the lit side intensity:=intensity*contrib; alt:=(VectorLength(atmPoint)-cPlanetRadius)*invAtmosphereHeight; VectorLerp(cLowAtmColor, cHighAtmColor, alt, altColor); Result[0]:=Result[0]*decay+altColor[0]*intensity; Result[1]:=Result[1]*decay+altColor[1]*intensity; Result[2]:=Result[2]*decay+altColor[2]*intensity; end else begin // sample on the dark sid Result[0]:=Result[0]*decay; Result[1]:=Result[1]*decay; Result[2]:=Result[2]*decay; end; end; Result[3]:=n*contrib*cOpacity*0.1; end; function ComputeColor(var rayDest : TVector; mayHitGround : Boolean) : TColorVector; var ai1, ai2, pi1, pi2 : TVector; rayVector : TVector; begin rayVector:=VectorNormalize(VectorSubtract(rayDest, eyePos)); if RayCastSphereIntersect(eyePos, rayVector, NullHmgPoint, cAtmosphereRadius, ai1, ai2)>1 then begin // atmosphere hit if mayHitGround and (RayCastSphereIntersect(eyePos, rayVector, NullHmgPoint, cPlanetRadius, pi1, pi2)>0) then begin // hit ground Result:=AtmosphereColor(ai1, pi1); end else begin // through atmosphere only Result:=AtmosphereColor(ai1, ai2); end; rayDest:=ai1; end else Result:=clrTransparent; end; const cSlices = 60; var i, j, k0, k1 : Integer; cosCache, sinCache : array [0..cSlices] of Single; pVertex, pColor : PVectorArray; begin sunPos:=LSSun.AbsolutePosition; eyepos:=GLCamera.AbsolutePosition; diskNormal:=VectorNegate(eyePos); NormalizeVector(diskNormal); diskRight:=VectorCrossProduct(GLCamera.AbsoluteUp, diskNormal); NormalizeVector(diskRight); diskUp:=VectorCrossProduct(diskNormal, diskRight); NormalizeVector(diskUp); invAtmosphereHeight:=1/(cAtmosphereRadius-cPlanetRadius); lightingVector:=VectorNormalize(sunPos); // sun at infinity PrepareSinCosCache(sinCache, cosCache, 0, 360); GetMem(pVertex, 2*(cSlices+1)*SizeOf(TVector)); GetMem(pColor, 2*(cSlices+1)*SizeOf(TVector)); rci.GLStates.PushAttrib([sttEnable]); rci.GLStates.DepthWriteMask := False; rci.GLStates.Disable(stLighting); rci.GLStates.Enable(stBlend); rci.GLStates.SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha); for i:=0 to 13 do begin if i<5 then radius:=cPlanetRadius*Sqrt(i*(1/5)) else radius:=cPlanetRadius+(i-5.1)*(cAtmosphereRadius-cPlanetRadius)*(1/6.9); radius:=SphereVisibleRadius(VectorLength(eyePos), radius); k0:=(i and 1)*(cSlices+1); k1:=(cSlices+1)-k0; for j:=0 to cSlices do begin VectorCombine(diskRight, diskUp, cosCache[j]*radius, sinCache[j]*radius, pVertex[k0+j]); if i<13 then pColor[k0+j]:=ComputeColor(pVertex[k0+j], i<=7); if i=0 then Break; end; if i>1 then begin if i=13 then begin glBegin(GL_QUAD_STRIP); for j:=cSlices downto 0 do begin glColor4fv(@pColor[k1+j]); glVertex3fv(@pVertex[k1+j]); glColor4fv(@clrTransparent); glVertex3fv(@pVertex[k0+j]); end; glEnd; end else begin glBegin(GL_QUAD_STRIP); for j:=cSlices downto 0 do begin glColor4fv(@pColor[k1+j]); glVertex3fv(@pVertex[k1+j]); glColor4fv(@pColor[k0+j]); glVertex3fv(@pVertex[k0+j]); end; glEnd; end; end else if i=1 then begin glBegin(GL_TRIANGLE_FAN); glColor4fv(@pColor[k1]); glVertex3fv(@pVertex[k1]); for j:=k0+cSlices downto k0 do begin glColor4fv(@pColor[j]); glVertex3fv(@pVertex[j]); end; glEnd; end; end; rci.GLStates.DepthWriteMask := True; rci.GLStates.PopAttrib; FreeMem(pVertex); FreeMem(pColor); end; procedure TForm1.LoadConstellationLines; var sl, line : TStrings; pos1, pos2 : TAffineVector; function LonLatToPos(lon, lat : Single) : TAffineVector; var f : Single; begin SinCos(lat*(PI/180), Result[1], f); SinCos(lon*(360/24*PI/180), f, Result[0], Result[2]); end; var i : Integer; begin sl:=TStringList.Create; line:=TStringList.Create; sl.LoadFromFile('Constellations.dat'); for i:=0 to sl.Count-1 do begin line.CommaText:=sl[i]; pos1:=LonLatToPos(StrToFloatDef(line[0], 0), StrToFloatDef(line[1], 0)); ConstellationLines.AddNode(pos1); pos2:=LonLatToPos(StrToFloatDef(line[2], 0), StrToFloatDef(line[3], 0)); ConstellationLines.AddNode(pos2); end; sl.Free; line.Free; end; procedure TForm1.Timer1Timer(Sender: TObject); begin Caption:=Format('%.1f FPS', [GLSceneViewer.FramesPerSecond]); GLSceneViewer.ResetPerformanceMonitor; end; procedure TForm1.GLCadencerProgress(Sender: TObject; const deltaTime, newTime: Double); //var // d : Double; // p : TAffineVector; begin // d:=GMTDateTimeToJulianDay(Now-2+newTime*timeMultiplier); // make earth rotate SPEarth.TurnAngle:=SPEarth.TurnAngle+deltaTime*timeMultiplier; { p:=ComputePlanetPosition(cSunOrbitalElements, d); ScaleVector(p, 0.5*cAUToKilometers*(1/cEarthRadius)); LSSun.Position.AsAffineVector:=p; } // moon rotates on itself and around earth (not sure about the rotation direction!) { p:=ComputePlanetPosition(cMoonOrbitalElements, d); ScaleVector(p, 0.5*cAUToKilometers*(1/cEarthRadius)); } DCMoon.TurnAngle:=DCMoon.TurnAngle+deltaTime*timeMultiplier/29.5; SPMoon.TurnAngle:=180-DCMoon.TurnAngle; // honour camera movements if (dmy<>0) or (dmx<>0) then begin GLCameraControler.MoveAroundTarget(ClampValue(dmy*0.3, -5, 5), ClampValue(dmx*0.3, -5, 5)); dmx:=0; dmy:=0; end; // this gives us smoother camera movements cameraTimeSteps:=cameraTimeSteps+deltaTime; while cameraTimeSteps>0.005 do begin GLCamera.Position.AsVector:=VectorLerp(GLCamera.Position.AsVector, GLCameraControler.Position.AsVector, 0.05); cameraTimeSteps:=cameraTimeSteps-0.005; end; // smooth constellation appearance/disappearance with ConstellationLines.LineColor do if Alpha<>constellationsAlpha then begin Alpha:=ClampValue(Alpha+Sign(constellationsAlpha-Alpha)*deltaTime, 0, 0.5); ConstellationLines.Visible:=(Alpha>0); end; end; procedure TForm1.GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx:=x; my:=y; end; procedure TForm1.GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Shift=[ssLeft] then begin dmx:=dmx+(mx-x); dmy:=dmy+(my-y); end else if Shift=[ssRight] then GLCamera.FocalLength:=GLCamera.FocalLength*Power(1.05, (my-y)*0.1); mx:=x; my:=y; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); var f : Single; begin if (WheelDelta>0) or (GLCameraControler.Position.VectorLength>0.90) then begin f:=Power(1.05, WheelDelta*(1/120)); GLCameraControler.AdjustDistanceToTarget(f); end; Handled:=True; end; procedure TForm1.GLSceneViewerDblClick(Sender: TObject); begin GLSceneViewer.OnMouseMove:=nil; if WindowState=wsMaximized then begin WindowState:=wsNormal; BorderStyle:=bsSizeToolWin; end else begin BorderStyle:=bsNone; WindowState:=wsMaximized; end; GLSceneViewer.OnMouseMove:=GLSceneViewerMouseMove; end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); procedure LoadHighResTexture(libMat : TGLLibMaterial; const fileName : String); begin if FileExists(fileName) then begin libMat.Material.Texture.Compression:=tcStandard; libMat.Material.Texture.Image.LoadFromFile(fileName); end; end; begin case Key of #27 : Close; 'm', 'M' : begin GLCamera.MoveTo(SPMoon); GLCameraControler.MoveTo(SPMoon); GLCamera.TargetObject:=SPMoon; GLCameraControler.TargetObject:=SPMoon; end; 'e', 'E' : begin GLCamera.MoveTo(DCEarthSystem); GLCameraControler.MoveTo(DCEarthSystem); GLCamera.TargetObject:=DCEarthSystem; GLCameraControler.TargetObject:=DCEarthSystem; end; 'h' : if not highResResourcesLoaded then begin GLSceneViewer.Cursor:=crHourGlass; try if DirectoryExists('HighResPack') then ChDir('HighResPack'); with GLMaterialLibrary do begin LoadHighResTexture(Materials[0], 'land_ocean_ice_4096.jpg'); LoadHighResTexture(Materials[1], 'land_ocean_ice_lights_4096.jpg'); LoadHighResTexture(Materials[2], 'moon_2048.jpg'); end; if FileExists('Hipparcos_9.0.stars') then begin GLSkyDome.Stars.Clear; GLSkyDome.Stars.LoadStarsFile('Hipparcos_9.0.stars'); GLSkyDome.StructureChanged; end; GLSceneViewer.Buffer.AntiAliasing:=aa2x; finally GLSceneViewer.Cursor:=crDefault; end; highResResourcesLoaded:=True; end; 'c' : constellationsAlpha:=0.5-constellationsAlpha; '0'..'9' : timeMultiplier:=Power(Integer(Key)-Integer('0'), 3); end; end; end.
unit ConstructorTest; interface uses DUnitX.TestFramework, uIntXLibTypes, uIntX, uConstants; type [TestFixture] TConstructorTest = class(TObject) public [Test] procedure DefaultCtor(); [Test] procedure IntCtor(); [Test] procedure UInt32Ctor(); [Test] procedure IntArrayCtor(); procedure IntArrayNullCtor(); [Test] procedure CallIntArrayNullCtor(); end; implementation [Test] procedure TConstructorTest.DefaultCtor(); begin TIntX.Create(0); end; [Test] procedure TConstructorTest.IntCtor(); begin TIntX.Create(7); end; [Test] procedure TConstructorTest.UInt32Ctor(); begin TIntX.Create(TConstants.MaxUInt32Value); end; [Test] procedure TConstructorTest.IntArrayCtor(); var temp: TIntXLibUInt32Array; begin SetLength(temp, 3); temp[0] := 1; temp[1] := 2; temp[2] := 3; TIntX.Create(temp, True); end; procedure TConstructorTest.IntArrayNullCtor(); var temp: TIntXLibUInt32Array; begin temp := Nil; TIntX.Create(temp, False); end; [Test] procedure TConstructorTest.CallIntArrayNullCtor(); var TempMethod: TTestLocalMethod; begin TempMethod := IntArrayNullCtor; Assert.WillRaise(TempMethod, EArgumentNilException); end; initialization TDUnitX.RegisterTestFixture(TConstructorTest); end.
unit IdResourceStringsOpenSSL; interface resourcestring {IdOpenSSL} RSOSSFailedToLoad = 'Le chargement de %s a échoué.'; RSOSSLModeNotSet = 'Le mode n'#39'a pas été défini.'; RSOSSLCouldNotLoadSSLLibrary = 'Impossible de charger la bibliothèque SSL.'; RSOSSLStatusString = 'Etat SSL : "%s"'; RSOSSLConnectionDropped = 'La connexion SSL s'#39'est interrompue.'; RSOSSLCertificateLookup = 'Erreur de requête de certificat SSL.'; RSOSSLInternal = 'Erreur interne de la bibliothèque SSL.'; //callback where strings RSOSSLAlert = 'Alerte %s'; RSOSSLReadAlert = 'Alerte Lecture %s'; RSOSSLWriteAlert = 'Alerte Ecriture %s'; RSOSSLAcceptLoop = 'Boucle d'#39'acceptation'; RSOSSLAcceptError = 'Erreur d'#39'acceptation'; RSOSSLAcceptFailed = 'Echec de l'#39'acceptation'; RSOSSLAcceptExit = 'Sortie d'#39'acceptation'; RSOSSLConnectLoop = 'Boucle de connexion'; RSOSSLConnectError = 'Erreur de connexion'; RSOSSLConnectFailed = 'Echec de la connexion'; RSOSSLConnectExit = 'Sortie de la connexion'; RSOSSLHandshakeStart = 'Négociation démarrée'; RSOSSLHandshakeDone = 'Négociation effectuée'; implementation end.
// Copyright (c) 2009, ConTEXT Project Ltd // 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 ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unit fHistory; interface {$I ConTEXT.inc} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, ImgList, ActnList, ComCtrls, uMultiLanguage, TB2MRU, Registry, uCommon, uCommonClass, TB2Item, TBX, TB2Dock, TB2Toolbar; type TfmHistory = class(TForm) lv: TListView; acHistory: TActionList; acRemove: TAction; acOpen: TAction; acShowPath: TAction; acRemoveAll: TAction; TBXDock1: TTBXDock; TBXToolbar1: TTBXToolbar; TBItemContainer1: TTBItemContainer; TBXSubmenuItem1: TTBXSubmenuItem; TBXItem3: TTBXItem; TBXItem2: TTBXItem; TBXItem1: TTBXItem; TBXSeparatorItem1: TTBXSeparatorItem; TBXItem4: TTBXItem; TBXPopupMenu1: TTBXPopupMenu; procedure FormDeactivate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormCreate(Sender: TObject); procedure acHistoryUpdate(Action: TBasicAction; var Handled: Boolean); procedure acOpenExecute(Sender: TObject); procedure acRemoveExecute(Sender: TObject); procedure acShowPathExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure acRemoveAllExecute(Sender: TObject); procedure lvStartDrag(Sender: TObject; var DragObject: TDragObject); private FPathVisible: boolean; FLockUpdate: boolean; procedure SetPathVisible(const Value: boolean); procedure SetLockUpdate(const Value: boolean); private fFilesMRU: TTBMRUList; procedure ClearList; procedure SetFilesMRU(const Value: TTBMRUList); procedure LoadConfig; procedure SaveConfig; property PathVisible :boolean read FPathVisible write SetPathVisible; public procedure UpdateList; property FilesMRU :TTBMRUList read fFilesMRU write SetFilesMRU; property LockUpdate :boolean read FLockUpdate write SetLockUpdate; end; implementation {$R *.DFM} uses fFilePane, fMain; //////////////////////////////////////////////////////////////////////////////////////////// // Property functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmHistory.SetFilesMRU(const Value: TTBMRUList); begin fFilesMRU:=Value; UpdateList; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.SetPathVisible(const Value: boolean); var i :integer; rec :TFileData; begin if (FPathVisible<>Value) then begin FPathVisible:=Value; lv.Items.BeginUpdate; try for i:=0 to lv.Items.Count-1 do begin rec:=TFileData(lv.Items[i].Data); if Value then lv.Items[i].Caption:=rec.FileName else lv.Items[i].Caption:=ExtractFileName(rec.FileName); end; finally lv.Items.EndUpdate; end; end; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.SetLockUpdate(const Value: boolean); begin if (FLockUpdate<>Value) then begin FLockUpdate:=Value; if not Value then UpdateList; end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Functions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmHistory.ClearList; var i :integer; begin lv.Items.BeginUpdate; try lv.Items.Clear; for i:=0 to lv.Items.Count-1 do if Assigned(lv.Items[i].Data) then TFileData(lv.Items[i].Data).Free; finally lv.Items.EndUpdate; end; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.UpdateList; var SelectedFile :string; rec :TFileData; i :integer; Item :TListItem; begin if LockUpdate then EXIT; if Assigned(lv.Selected) then SelectedFile:=UpperCase(TFileData(lv.Selected.Data).FileName) else SelectedFile:=''; lv.Items.BeginUpdate; ClearList; if Assigned(FFilesMRU) then begin for i:=0 to FFilesMRU.Items.Count-1 do begin rec:=TFileData.Create(FFilesMRU.Items[i]); Item:=lv.Items.Add; with Item do begin if PathVisible then Caption:=rec.FileName else Caption:=ExtractFileName(rec.FileName); ImageIndex:=rec.IconIndex; Data:=rec; end; if (UpperCase(rec.FileName)=SelectedFile) then lv.Selected:=Item; end; end; lv.Items.EndUpdate; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.LoadConfig; var reg :TRegistry; begin reg:=TRegistry.Create; with reg do begin OpenKey(CONTEXT_REG_KEY+'FileHistory',TRUE); PathVisible:=ReadRegistryBool(reg,'ShowPath',TRUE); Free; end; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.SaveConfig; var reg :TRegistry; begin reg:=TRegistry.Create; with reg do begin OpenKey(CONTEXT_REG_KEY+'FileHistory',TRUE); WriteBool('ShowPath', PathVisible); Free; end; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Actions //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmHistory.acHistoryUpdate(Action: TBasicAction; var Handled: Boolean); begin acOpen.Enabled:=Assigned(lv.Selected); acRemove.Enabled:=Assigned(lv.Selected); acRemoveAll.Enabled:=lv.Items.Count>0; acShowPath.Checked:=fPathVisible; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.acOpenExecute(Sender: TObject); var i :integer; str :TStringList; rec :TFileData; begin str:=TStringList.Create; try for i:=0 to lv.Items.Count-1 do if (lv.Items[i].Selected) then begin rec:=TFileData(lv.Items[i].Data); if Assigned(rec) then str.Add(rec.FileName); end; fmMain.OpenMultipleFiles(str); finally str.Free; end; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.acRemoveExecute(Sender: TObject); var i :integer; begin if not Assigned(FFilesMRU) then EXIT; for i:=0 to lv.Items.Count-1 do if lv.Items[i].Selected then FFilesMRU.Remove(TFileData(lv.Items[i].Data).FileName); UpdateList; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.acRemoveAllExecute(Sender: TObject); var i :integer; begin if not Assigned(FFilesMRU) then EXIT; for i:=0 to lv.Items.Count-1 do FFilesMRU.Remove(TFileData(lv.Items[i].Data).FileName); ClearList; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.acShowPathExecute(Sender: TObject); begin PathVisible:=not PathVisible; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // lv events //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmHistory.lvStartDrag(Sender: TObject; var DragObject: TDragObject); var str :TStringList; rec :TFileData; i :integer; begin with lv do begin if (SelCount>1) then DragCursor:=crMultiDrag else DragCursor:=crDrag; end; str:=TStringList.Create; for i:=0 to lv.Items.Count-1 do if lv.Items[i].Selected then begin rec:=TFileData(lv.Items[i].Data); if not rec.IsDirectory then str.Add(rec.FileName); end; TFilePanelDragFiles.Create(fmMain.FilePanel, lv, str); str.Free; end; //------------------------------------------------------------------------------------------ //////////////////////////////////////////////////////////////////////////////////////////// // Form events //////////////////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------------------ procedure TfmHistory.FormCreate(Sender: TObject); begin lv.SmallImages:=fmMain.FileIconPool.ImageList; LoadConfig; acOpen.Hint:=mlStr(ML_EXPL_HINT_OPEN,'Open selected files'); acRemove.Hint:=mlStr(ML_EXPL_HINT_REMOVE,'Remove selected files from list'); acRemoveAll.Hint:=mlStr(ML_EXPL_HINT_REMOVE_ALL,'Remove all files from list'); acShowPath.Hint:=mlStr(ML_EXPL_HINT_TOGGLEPATH,'Toggle show/hide path'); acOpen.Caption:=mlStr(ML_FAV_OPEN,'&Open'); acRemove.Caption:=mlStr(ML_FAV_REMOVE,'&Remove'); acRemoveAll.Caption:=mlStr(ML_FAV_REMOVE_ALL,'Remove A&ll'); acShowPath.Caption:=mlStr(ML_FAV_SHOW_PATH,'&Show Path'); end; //------------------------------------------------------------------------------------------ procedure TfmHistory.FormActivate(Sender: TObject); begin acHistory.State := asNormal; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.FormDeactivate(Sender: TObject); begin acHistory.State := asSuspended; end; //------------------------------------------------------------------------------------------ procedure TfmHistory.FormDestroy(Sender: TObject); begin SaveConfig; ClearList; end; //------------------------------------------------------------------------------------------ end.
unit CustomSchemeControl; interface uses Menus, BasicProgramTypes, CustomScheme, Classes; type TCustomSchemeControl = class private MenuItems: array [1..19] of TMenuItem; CurrentSubMenu: TMenuItem; Owner: TComponent; function IsFileInUse(const _FileName: string): Boolean; procedure ClearSubMenu(var _MenuItem: TMenuItem); function FindSubMenuItemFromCaption(var _BaseMenuItem: TMenuItem; const _Caption: string):TMenuItem; function CreateSplitterMenuItem: TMenuItem; procedure InsertItemAtMenu(var _item,_menu: TMenuItem; _GameType: integer; Split: boolean); procedure AddScheme(const _Filename: string); procedure SetupSubMenu; public ColourSchemes : TColourSchemesInfo; OnClickEvent: TNotifyEvent; constructor Create(const _Owner: TComponent; _OnClickEvent: TNotifyEvent); destructor Destroy; override; procedure ResetColourSchemes; function UpdateCSchemes(var _BaseItem: TMenuItem; _Dir : string; _c : integer) : Integer; overload; function UpdateCSchemes(var _BaseItem: TMenuItem; _Dir : string; _c : integer; _UseBaseItem, _ClearBaseMenu: boolean) : Integer; overload; function LoadCSchemes(var _BaseItem: TMenuItem; _Dir: string; _c: integer): integer; overload; function LoadCSchemes(var _BaseItem: TMenuItem; _Dir: string; _c: integer; _CreateSubMenu: boolean): integer; overload; end; implementation uses BasicFunctions, Windows, SysUtils; constructor TCustomSchemeControl.Create(const _Owner: TComponent; _OnClickEvent: TNotifyEvent); begin Owner := _Owner; OnClickEvent := _OnClickEvent; end; destructor TCustomSchemeControl.Destroy; begin ResetColourSchemes; inherited Destroy; end; procedure TCustomSchemeControl.ResetColourSchemes; begin SetLength(ColourSchemes, 0); end; procedure TCustomSchemeControl.ClearSubMenu(var _MenuItem: TMenuItem); var i: integer; item: TMenuItem; begin if _MenuItem.Count > 0 then begin i := _MenuItem.Count - 1; while i >= 0 do begin item := _MenuItem.Items[i]; if Item.Count > 0 then begin if (Item.Tag >= 0) then begin ClearSubMenu(Item); _MenuItem.Delete(i); end; end else begin if (Item.Tag > 0) and (CompareStr(Item.Caption,'-') <> 0) then begin _MenuItem.Delete(i); end; end; dec(i); end; end; end; function TCustomSchemeControl.FindSubMenuItemFromCaption(var _BaseMenuItem: TMenuItem; const _Caption: string):TMenuItem; var i: integer; begin i := 0; while i < _BaseMenuItem.Count do begin if CompareText(_BaseMenuItem.Items[i].Caption, _Caption) = 0 then begin Result := _BaseMenuItem.Items[i]; exit; end; inc(i); end; Result := TMenuItem.Create(Owner); Result.Caption := CopyString(_Caption); _BaseMenuItem.Insert(_BaseMenuItem.Count, Result); end; function TCustomSchemeControl.CreateSplitterMenuItem: TMenuItem; begin Result := TMenuItem.Create(Owner); Result.Caption := '-'; end; procedure TCustomSchemeControl.InsertItemAtMenu(var _item,_menu: TMenuItem; _GameType: integer; Split: boolean); var i, pos: integer; begin if _Menu = nil then begin _Menu := TMenuItem.Create(Owner); case (_GameType) of 1: _Menu.Caption := 'Tiberian Sun'; 2: _Menu.Caption := 'Red Alert 2'; 3: _Menu.Caption := 'Yuri''s Revenge'; 4: _Menu.Caption := 'Allied'; 5: _Menu.Caption := 'Soviet'; 6: _Menu.Caption := 'Yuri'; 7: _Menu.Caption := 'Brick'; 8: _Menu.Caption := 'Grayscale'; 9: _Menu.Caption := 'Remap'; 10: _Menu.Caption := 'Brown 1'; 11: _Menu.Caption := 'Brown 2'; 12: _Menu.Caption := 'Blue'; 13: _Menu.Caption := 'Green'; 14: _Menu.Caption := 'No Unlit'; 15: _Menu.Caption := 'Red'; 16: _Menu.Caption := 'Yellow'; 17: _Menu.Caption := 'Others'; 18: _Menu.Caption := 'Tiberian Dawn'; 19: _Menu.Caption := 'Red Alert 1'; end; case (_GameType) of 18: _Menu.Tag := 0; 19: _Menu.Tag := 1; else _Menu.Tag := _GameType + 1; end; pos := 0; if CurrentSubMenu.Count > 0 then begin i := 1; if _Menu.Tag > CurrentSubMenu.Items[0].Tag then begin while (i < CurrentSubMenu.Count) and (pos = 0) do begin if _Menu.Tag < CurrentSubMenu.Items[i].Tag then begin pos := i; end else inc(i); end; if i = CurrentSubMenu.Count then pos := i; end; end; CurrentSubMenu.Insert(pos, _Menu); MenuItems[_GameType] := _Menu; end; if Split then _Menu.Insert(_Menu.Count, CreateSplitterMenuItem()); _Menu.Insert(_Menu.Count, _Item); _Menu.Visible := True; end; procedure TCustomSchemeControl.AddScheme(const _Filename: string); var item: TMenuItem; Scheme : TCustomScheme; c : integer; begin c := High(ColourSchemes)+2; SetLength(ColourSchemes, c + 1); Scheme := TCustomScheme.CreateForVXLSE(_Filename); ColourSchemes[c].FileName := CopyString(_Filename); item := TMenuItem.Create(Owner); item.Caption := Scheme.Name; item.Tag := c; // so we know which it is item.OnClick := OnClickEvent; item.ImageIndex := Scheme.ImageIndex; if Scheme.GameType = 0 then Scheme.GameType := 17; InsertItemAtMenu(item,MenuItems[Scheme.GameType],Scheme.GameType,Scheme.Split); // TS Scheme.Free; end; // copied from: http://stackoverflow.com/questions/16287983/why-do-i-get-i-o-error-32-even-though-the-file-isnt-open-in-any-other-program function TCustomSchemeControl.IsFileInUse(const _FileName: string): Boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(_FileName) then Exit; HFileRes := CreateFile(PChar(_FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not Result then CloseHandle(HFileRes); end; function TCustomSchemeControl.UpdateCSchemes(var _BaseItem: TMenuItem; _Dir : string; _c : integer) : Integer; begin Result := UpdateCSchemes(_BaseItem, _Dir, _c, true, true); end; function TCustomSchemeControl.UpdateCSchemes(var _BaseItem: TMenuItem; _Dir : string; _c : integer; _UseBaseItem, _ClearBaseMenu: boolean) : Integer; var f: TSearchRec; Name, path: string; i : integer; MySubMenu: TMenuItem; begin if not DirectoryExists(IncludeTrailingPathDelimiter(_Dir)) then exit; if not _UseBaseItem then begin CurrentSubMenu := FindSubMenuItemFromCaption(_BaseItem, ExtractFileName(ExcludeTrailingPathDelimiter(_Dir))); end else begin CurrentSubMenu := _BaseItem; end; if _ClearBaseMenu then begin ClearSubMenu(CurrentSubMenu); end; MySubMenu := CurrentSubMenu; // Reset submenus. for i := 1 to 19 do begin MenuItems[i] := nil; end; // Find submenu subitems SetupSubMenu; // prepare path := Concat(_Dir, '*.cscheme'); // find files if FindFirst(path, faAnyFile, f) = 0 then repeat Name := IncludeTrailingPathDelimiter(_Dir) + f.Name; if FileExists(Name) and (not IsFileInUse(Name)) then begin AddScheme(Concat(_Dir, f.Name)); inc(_c); end; until FindNext(f) <> 0; FindClose(f); // Check all subdirectories. Path := IncludeTrailingPathDelimiter(_Dir) + '*'; if FindFirst(path,faDirectory,f) = 0 then begin repeat if (CompareStr(f.Name,'.') <> 0) and (CompareStr(f.Name, '..') <> 0) then begin Name := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(_Dir) + f.Name); if DirectoryExists(Name) then // It sounds unnecessary, but for some reason, it may catch some weird dirs sometimes. begin UpdateCSchemes(MySubMenu, Name, _c, false, true); end; end; until FindNext(f) <> 0; end; FindClose(f); Result := _c; end; { // Old code. The old approach could have ordering failures and issues with the time detection. function TCustomSchemeControl.UpdateCSchemes(var _BaseItem: TMenuItem; _Latest: integer; _Dir : string; _c : integer; _UseBaseItem: boolean) : Integer; var f: TSearchRec; Name, path: string; i : integer; MySubMenu: TMenuItem; begin if not DirectoryExists(IncludeTrailingPathDelimiter(_Dir)) then exit; if not _UseBaseItem then begin CurrentSubMenu := FindSubMenuItemFromCaption(_BaseItem, ExtractFileName(ExcludeTrailingPathDelimiter(_Dir))); end else begin CurrentSubMenu := _BaseItem; end; MySubMenu := CurrentSubMenu; // Reset submenus. for i := 1 to 19 do begin MenuItems[i] := nil; end; // Find submenu subitems SetupSubMenu; // prepare path := Concat(_Dir, '*.cscheme'); // find files if FindFirst(path, faAnyFile, f) = 0 then repeat Name := IncludeTrailingPathDelimiter(_Dir) + f.Name; if FileExists(Name) and (not IsFileInUse(Name)) then begin if f.Time > _Latest then begin AddScheme(Concat(_Dir, f.Name)); if f.Time > LatestScheme then begin LatestScheme := f.Time; end; inc(_c); end; end; until FindNext(f) <> 0; FindClose(f); // Check all subdirectories. Path := IncludeTrailingPathDelimiter(_Dir) + '*'; if FindFirst(path,faDirectory,f) = 0 then begin repeat if (CompareStr(f.Name,'.') <> 0) and (CompareStr(f.Name, '..') <> 0) then begin Name := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(_Dir) + f.Name); if DirectoryExists(Name) then // It sounds unnecessary, but for some reason, it may catch some weird dirs sometimes. begin UpdateCSchemes(MySubMenu, _Latest, Name, _c, false); end; end; until FindNext(f) <> 0; end; FindClose(f); Result := _c; end; } procedure TCustomSchemeControl.SetupSubMenu; var i : integer; begin // Reset submenus. for i := 1 to 19 do begin MenuItems[i] := nil; end; // Find submenu subitems if CurrentSubMenu.Count > 0 then begin i := 0; while i < CurrentSubMenu.Count do begin if CompareText(CurrentSubMenu.Items[i].Caption, 'Tiberian Sun') = 0 then begin MenuItems[1] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 2; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Red Alert 2') = 0 then begin MenuItems[2] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 3; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Yuri''s Revenge') = 0 then begin MenuItems[3] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 4; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Allied') = 0 then begin MenuItems[4] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 5; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Soviet') = 0 then begin MenuItems[5] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 6; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Yuri') = 0 then begin MenuItems[6] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 7; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Brick') = 0 then begin MenuItems[7] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 8; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Grayscale') = 0 then begin MenuItems[8] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 9; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Remap') = 0 then begin MenuItems[9] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 10; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Brown 1') = 0 then begin MenuItems[10] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 11; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Brown 2') = 0 then begin MenuItems[11] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 12; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Blue') = 0 then begin MenuItems[12] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 13; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Green') = 0 then begin MenuItems[13] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 14; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'No Unlit') = 0 then begin MenuItems[14] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 15; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Red') = 0 then begin MenuItems[15] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 16; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Yellow') = 0 then begin MenuItems[16] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 17; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Others') = 0 then begin MenuItems[17] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 18; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Tiberian Dawn') = 0 then begin MenuItems[18] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 0; end else if CompareText(CurrentSubMenu.Items[i].Caption, 'Red Alert 1') = 0 then begin MenuItems[19] := CurrentSubMenu.Items[i]; CurrentSubMenu.Items[i].Tag := 1; end; inc(i); end; end; end; function TCustomSchemeControl.LoadCSchemes(var _BaseItem: TMenuItem; _Dir: string; _c: integer): integer; begin Result := LoadCSchemes(_BaseItem, _Dir, _c, false); end; function TCustomSchemeControl.LoadCSchemes(var _BaseItem: TMenuItem; _Dir: string; _c: integer; _CreateSubMenu: boolean): integer; var f: TSearchRec; Name, path: string; Item: TMenuItem; MySubMenu: TMenuItem; begin if not DirectoryExists(IncludeTrailingPathDelimiter(_Dir)) then exit; if _CreateSubMenu then begin Item := TMenuItem.Create(Owner); item.Caption := ExtractFileName(ExcludeTrailingPathDelimiter(_Dir)); // item.OnClick := FrmMain.blank2Click; _BaseItem.Insert(_BaseItem.Count, Item); CurrentSubMenu := Item; end else begin if _BaseItem = nil then exit; CurrentSubMenu := _BaseItem; end; MySubMenu := CurrentSubMenu; // Find submenu subitems SetupSubMenu; // prepare path := Concat(_Dir, '*.cscheme'); // find files if FindFirst(path, faAnyFile, f) = 0 then repeat Name := IncludeTrailingPathDelimiter(_Dir) + f.Name; if FileExists(Name) and (not IsFileInUse(Name)) then begin AddScheme(Concat(_Dir, f.Name)); end; until FindNext(f) <> 0; FindClose(f); Path := IncludeTrailingPathDelimiter(_Dir) + '*'; if FindFirst(path,faDirectory,f) = 0 then begin repeat if (CompareStr(f.Name,'.') <> 0) and (CompareStr(f.Name, '..') <> 0) then begin Name := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(_Dir) + f.Name); if DirectoryExists(Name) then // It sounds unnecessary, but for some reason, it may catch some weird dirs sometimes. begin LoadCSchemes(MySubMenu, Name, _c, true); end; end; until FindNext(f) <> 0; end; FindClose(f); Result := High(ColourSchemes)+1; if Result > _c then begin CurrentSubMenu.Visible := true; end; end; end.
unit uFrmOKOF; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_SelectForm, Menus, cxLookAndFeelPainters, cxGraphics, cxCustomData, cxStyles, cxTL, cxInplaceContainer, cxTLData, cxDBTL, StdCtrls, cxButtons, ExtCtrls, cxClasses, dxRibbon, cxControls, DB, ADODB, cxMaskEdit, cxCurrencyEdit, uFrameOKOF; type TfrmOKOF = class(TBASE_SelectForm) Frame: TFrameOKOF; procedure FormCreate(Sender: TObject); procedure TreeCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas; AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean); procedure btnOKClick(Sender: TObject); private { Private declarations } protected procedure SetFontParams(ACanvas: TcxCanvas; FontStyle: TFontStyles; FontColor: TColor); virtual; procedure Check; override; public procedure ApplyParamsAfterOpen; override; procedure OpenData; override; end; var frmOKOF: TfrmOKOF; implementation uses uMain, uCommonUtils; {$R *.dfm} procedure TfrmOKOF.ApplyParamsAfterOpen; begin with Frame.Query do if not VarIsNullMy(Params['код_ОКОФ'].Value) then Locate(Fields[0].FieldName, Params['код_ОКОФ'].Value, []); end; procedure TfrmOKOF.Check; begin // end; procedure TfrmOKOF.FormCreate(Sender: TObject); begin inherited; Frame.Query.Open; end; procedure TfrmOKOF.SetFontParams(ACanvas: TcxCanvas; FontStyle: TFontStyles; FontColor: TColor); begin ACanvas.Font.Style:=FontStyle; ACanvas.Font.Color:=FontColor; end; procedure TfrmOKOF.TreeCustomDrawCell(Sender: TObject; ACanvas: TcxCanvas; AViewInfo: TcxTreeListEditCellViewInfo; var ADone: Boolean); begin inherited; case AViewInfo.Node.Level of 0: SetFontParams(ACanvas, [fsBold, fsUnderline], clNavy); 1: SetFontParams(ACanvas, [fsBold], clTeal); 2: SetFontParams(ACanvas, [fsBold, fsUnderline], clWindowText); 3: SetFontParams(ACanvas, [fsBold], clWindowText); 4: SetFontParams(ACanvas, [], clWindowText); end end; procedure TfrmOKOF.btnOKClick(Sender: TObject); begin Check; Params['код_ОКОФ'].Value:=Frame.Query['код_ОКОФ']; Params['Код'].Value:=Frame.Query['Код']; Params['Наименование'].Value:=Frame.Query['Наименование']; Params['Норма амортизации'].Value:=Frame.Query['Амортизация.Норма амортизации']; Params['Срок полезного использования'].Value:=Frame.Query['Амортизация.Срок полезного использования']; ModalResult:=mrOK; end; procedure TfrmOKOF.OpenData; begin if not VarIsNull(Params['код_ОКОФ_Родитель'].Value) then Frame.Query.SQL.Text:='sp_ОКОФ_получить @Родитель = '+IntToStr(Params['код_ОКОФ_Родитель'].Value); self.Frame.Query.Open; end; end.
unit uDevExpressGridPrint; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, dxDBGrid, DB, ppCtrls; type TDevExpressGridPrint = class(TComponent) private { Private declarations } FSeparatorSpace : integer; FTitleBackColor : TColor; ImpDataSource : TDataSource; FGridPrint : TdxDBGrid; FTitleFont, FItemFont : TFont; FFiltro, FTitle, FUsuario : String; procedure SetTitleFont(Value : TFont); procedure SetItemFont(Value : TFont); protected { Protected declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; public { Public declarations } procedure Print; published property GridPrint : TdxDBGrid read FGridPrint write FGridPrint; property ItemFont : TFont read FItemFont write SetItemFont; property TitleFont : TFont read FTitleFont write SetTitleFont; property TitleBackColor : TColor read FTitleBackColor write FTitleBackColor default clGray; property SeparatorSpace : Integer read FSeparatorSpace write FSeparatorSpace default 4; property Title : String read FTitle write FTitle; property Usuario : String read FUsuario write FUsuario; property Filtro : String read FFiltro write FFiltro; end; procedure Register; implementation uses uRptBuildPrintGrid; constructor TDevExpressGridPrint.Create(AOwner : TComponent); begin inherited Create(AOwner); FTitleFont := TFont.Create; FItemFont := TFont.Create; FSeparatorSpace := 4; FTitleBackColor := clGray; end; destructor TDevExpressGridPrint.Destroy; begin FTitleFont.Free; FItemFont.Free; inherited Destroy; end; procedure TDevExpressGridPrint.SetTitleFont(Value : TFont); begin if FTitleFont <> Value then FTitleFont.Assign(Value); end; procedure TDevExpressGridPrint.SetItemFont(Value : TFont); begin if FItemFont <> Value then FItemFont.Assign(Value); end; procedure TDevExpressGridPrint.Print; var i : Integer; LeftPos, AdjsutSpace, TotWidth : Double; OldBM : TBookMarkStr; MyRptBuildPrintGrid : TFrmRptBuildPrintGrid; begin try ImpDataSource := FGridPrint.DataSource; except raise exception.create('GridPrint not declared'); end; // Calcula o tamanho total dos campos para usar no calculo do media ponderada TotWidth := 0; with FGridPrint do begin for i := 0 to VisibleColumnCount- 1 do TotWidth := TotWidth + VisibleColumns[i].Width; // Diminui o espacamento entre campos AdjsutSpace := FSeparatorSpace * (VisibleColumnCount - 1); end; try // Cria formulario de relatorio // Guarda posicao atual OldBM := ImpDataSource.DataSet.Bookmark; ImpDataSource.DataSet.DisableControls; ImpDataSource.DataSet.First; // Cria formulario de relatorio MyRptBuildPrintGrid := TFrmRptBuildPrintGrid.Create(Self); with MyRptBuildPrintGrid do begin // Seta o Title e Usuario lbTitle.Caption := FTitle; lbUser.Caption := FUsuario; // Seta o DataSet DBPipeline.DataSource := ImpDataSource; DBPipeline.First; // Cria os cabecalhos / Colunas LeftPos := 0; with FGridPrint do begin for i := 0 to VisibleColumnCount - 1 do begin // Column Title with TppLabel.Create(MyRptBuildPrintGrid) do begin Band := RptGrid.HeaderBand; Left := LeftPos; Height := RptGrid.HeaderBand.Height; Alignment := VisibleColumns[i].Alignment; Color := FTitleBackColor; Font.Assign(FTitleFont); AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( shpDetail.Width - AdjsutSpace ) ); Caption := VisibleColumns[i].Caption; end; // Nodes with TppDBText.Create(MyRptBuildPrintGrid) do begin Band := RptGrid.DetailBand; Left := LeftPos; Height := RptGrid.DetailBand.Height; Alignment := VisibleColumns[i].Alignment; Font.Assign(FItemFont); AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( shpDetail.Width - AdjsutSpace ) ); Transparent := True; DataPipeLine := DBPipeline; DataField := VisibleColumns[i].FieldName; end; // Total if (VisibleColumns[i].Field.DataType in [ftCurrency, ftFloat, ftInteger, ftSmallInt]) and (VisibleColumns[i].Field.Index > 0) then begin with TppDBCalc.Create(MyRptBuildPrintGrid) do begin Band := RptGrid.SummaryBand; Left := LeftPos; Height := RptGrid.DetailBand.Height; Alignment := VisibleColumns[i].Alignment; Font.Assign(FItemFont); Font.Style := Font.Style + [fsBold]; if VisibleColumns[i].Field.DataType = ftCurrency then begin if TCurrencyField(VisibleColumns[i].Field).Currency then DisplayFormat := '#,#00.00' else DisplayFormat := TNumericField(VisibleColumns[i].Field).DisplayFormat end else DisplayFormat := TNumericField(VisibleColumns[i].Field).DisplayFormat; AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( shpDetail.Width - AdjsutSpace ) ); Transparent := True; DataPipeLine := DBPipeline; //DBCalcType := dcSum; DataField := VisibleColumns[i].FieldName; end; end; // Incrementa a posicao a esquerda LeftPos := LeftPos + Round( (VisibleColumns[i].Width/TotWidth) * ( shpDetail.Width - AdjsutSpace )) + FSeparatorSpace; end; end; Start(False); Free; end; { //Antigo no QuRep with MyRptPowerGridPrint do begin // Seta o Title e Usuario ReportTitle := FTitle; lblUsuario.Caption := FUsuario; lblFiltro.Caption := FFiltro; // Seta o DataSet DataSet := ImpDataSet; // Cria os cabecalhos / Colunas LeftPos := 0; with FGridPrint do begin for i := 0 to VisibleColumnCount - 1 do begin // Column Title with TQRLabel.Create(MyRptPowerGridPrint) do begin Parent := ColumnHeaderBand; Left := LeftPos; Height := ColumnHeaderBand.Height; Alignment := VisibleColumns[i].Alignment; Color := FTitleBackColor; Font.Assign(FTitleFont); AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( ColumnHeaderBand.Width - AdjsutSpace ) ); Caption := VisibleColumns[i].Caption; end; // Nodes with TQRDBText.Create(MyRptPowerGridPrint) do begin Parent := DetailBand; Left := LeftPos; Height := DetailBand.Height-3; Alignment := VisibleColumns[i].Alignment; Font.Assign(FItemFont); AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( DetailBand.Width - AdjsutSpace ) ); Transparent := True; DataSet := ImpDataSet; DataField := VisibleColumns[i].FieldName; end; // Total if (VisibleColumns[i].Field.DataType in [ftCurrency, ftFloat, ftInteger, ftSmallInt]) and (VisibleColumns[i].Field.Index > 0) then begin with TQRExpr.Create(MyRptPowerGridPrint) do begin Parent := SummaryBand; Left := LeftPos; Height := DetailBand.Height-3; Alignment := VisibleColumns[i].Alignment; Font.Assign(FItemFont); Font.Style := Font.Style + [fsBold]; if VisibleColumns[i].Field.DataType = ftCurrency then begin if TCurrencyField(VisibleColumns[i].Field).Currency then Mask := '#,#00.00' else Mask := TNumericField(VisibleColumns[i].Field).DisplayFormat end else Mask := TNumericField(VisibleColumns[i].Field).DisplayFormat; AutoSize := False; Width := Round( (VisibleColumns[i].Width/TotWidth) * ( DetailBand.Width - AdjsutSpace ) ); Transparent := True; Expression := 'SUM(' + VisibleColumns[i].FieldName + ')'; end; end; // Incrementa a posicao a esquerda LeftPos := LeftPos + Round( (VisibleColumns[i].Width/TotWidth) * ( DetailBand.Width - AdjsutSpace )) + FSeparatorSpace; end; end; Preview; Free; end; } finally // Restaura posicao //ImpDataSet.BookMark := OldBM; #Antigo ImpDataSource.DataSet.Bookmark := OldBM; //ImpDataSet.EnableControls; #Antigo ImpDataSource.DataSet.EnableControls; end; end; procedure Register; begin RegisterComponents('NewPower', [TDevExpressGridPrint]); end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, frxDock, Vcl.StdCtrls, Math, //RandomRange Services, WorkerThreads ; type TMainForm = class(TForm) btnAssignResource: TButton; memoOutput: TMemo; frxDockSite1: TfrxDockSite; frxDockSite2: TfrxDockSite; btnCreateSingleton: TButton; btnStartThreads: TButton; btnStopThreads: TButton; procedure btnAssignResourceClick(Sender: TObject); procedure btnCreateSingletonClick(Sender: TObject); procedure btnStartThreadsClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnStopThreadsClick(Sender: TObject); private fChangeThread: TChangeResourceWorkerThread; fWriteToMemoThread: TWriteResourceToMemoWorkerThread; procedure StopThreads; public end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.btnAssignResourceClick(Sender: TObject); var lRandomInt : Integer; begin lRandomInt := RandomRange(0, 9999); TServices.Ton().SingletonResource := 'This is my new singleton resource string. ' + IntToStr(lRandomInt); memoOutput.Lines.Add(TServices.Ton().SingletonResource); memoOutput.Lines.Add('This was not necessary. Just had the button here. The singleton is created the first time it is called.'); end; procedure TMainForm.btnCreateSingletonClick(Sender: TObject); begin TServices.Ton(); memoOutput.Lines.Add('Singleton created (if it wasn''t already)'); end; procedure TMainForm.btnStartThreadsClick(Sender: TObject); begin //IF THE CHANGE THREAD IS NIL, THEN WE CREATE AND START IT if fChangeThread = nil then begin fChangeThread := TChangeResourceWorkerThread.Create(true); fChangeThread.Start(); end //ELSE IF IT'S FINISHED, THEN WE JUST FREE IT UP AND THEN CREATE AND START IT. else if fChangeThread.Finished then begin FreeAndNil(fChangeThread); fChangeThread := TChangeResourceWorkerThread.Create(true); fChangeThread.Start(); end //ELSE THE THREAD IS STILL RUNNING else begin memoOutput.Lines.Add('Change Thread Still Running...'); end; //IF THE THREAD IS NIL, THEN WE CREATE AND START IT if fWriteToMemoThread = nil then begin fWriteToMemoThread := TWriteResourceToMemoWorkerThread.Create(memoOutput, true); fWriteToMemoThread.Start(); end //ELSE IF IT'S FINISHED, THEN WE JUST FREE IT UP AND THEN CREATE AND START IT. else if fWriteToMemoThread.Finished then begin FreeAndNil(fWriteToMemoThread); fWriteToMemoThread := TWriteResourceToMemoWorkerThread.Create(memoOutput, true); fWriteToMemoThread.Start(); end //ELSE THE THREAD IS STILL RUNNING else begin memoOutput.Lines.Add('WriteResourceToMemoThread Still Running...'); end; end; procedure TMainForm.btnStopThreadsClick(Sender: TObject); begin StopThreads(); end; procedure TMainForm.FormDestroy(Sender: TObject); begin StopThreads(); end; procedure TMainForm.StopThreads; var lWaitResult: Cardinal; lTimeoutInMs: Integer; begin lTimeoutInMs := 10000; //IF THREAD IS ALREADY NIL, OBVIOUSLY WE DON'T NEED TO STOP IT if fWriteToMemoThread <> nil then begin //SIGNAL THE TERMINATE (DOES NOT KILL THREAD) fWriteToMemoThread.Terminate; //WAIT FOR THREAD TO TERMINATE lWaitResult := WaitForSingleObject(fWriteToMemoThread.Handle, lTimeoutInMs); //WAIT RESULT IS SUCCESSFUL (THREAD TERMINATED) if (lWaitResult = WAIT_OBJECT_0) and (fWriteToMemoThread <> nil) then begin fWriteToMemoThread := nil; memoOutput.Lines.Add('WriteToMemoThread stopped.'); end //WAIT TIMED OUT else if lWaitResult = WAIT_TIMEOUT then raise Exception.Create('WriteToMemoThread Wait Timeout Reached'); end; //IF THREAD IS ALREADY NIL, OBVIOUSLY WE DON'T NEED TO STOP IT if fChangeThread <> nil then begin //SIGNAL THE TERMINATE (DOES NOT KILL THREAD) fChangeThread.Terminate; //WAIT FOR THREAD TO TERMINATE lWaitResult := WaitForSingleObject(fChangeThread.Handle, lTimeoutInMs); //WAIT RESULT IS SUCCESSFUL (THREAD TERMINATED) if (lWaitResult = WAIT_OBJECT_0) and (fChangeThread <> nil) then begin fChangeThread := nil; memoOutput.Lines.Add('ChangeThread stopped.'); end //WAIT TIMED OUT else if lWaitResult = WAIT_TIMEOUT then raise Exception.Create('ChangeThread Wait Timeout Reached'); end; end; end.
unit HlpPBKDF_ScryptNotBuildInAdapter; {$I ..\Include\HashLib.inc} interface uses {$IFDEF HAS_DELPHI_PPL} System.Classes, System.SysUtils, System.Threading, {$ENDIF HAS_DELPHI_PPL} {$IFDEF DELPHI} HlpBitConverter, {$ENDIF DELPHI} HlpIHash, HlpKDF, HlpBits, HlpSHA2_256, HlpIHashInfo, HlpPBKDF2_HMACNotBuildInAdapter, HlpConverters, HlpArrayUtils, HlpHashLibTypes; resourcestring SInvalidByteCount = '"bc (ByteCount)" Argument must be a value greater than zero.'; SInvalidCost = 'Cost parameter must be > 1 and a power of 2.'; SBlockSizeAndCostIncompatible = 'Cost parameter must be > 1 and < 65536.'; SBlockSizeTooSmall = 'Block size must be >= 1.'; SInvalidParallelism = 'Parallelism parameter must be >= 1 and <= %d (based on block size of %d)'; SRoundsMustBeEven = 'Number of Rounds Must be Even'; type /// <summary>Implementation of the scrypt a password-based key derivation function.</summary> /// <remarks> /// Scrypt was created by Colin Percival and is specified in /// <a href="http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01">draft-josefsson-scrypt-kd</a>. /// </remarks> TPBKDF_ScryptNotBuildInAdapter = class sealed(TKDF, IPBKDF_Scrypt, IPBKDF_ScryptNotBuildIn) strict private var FPasswordBytes, FSaltBytes: THashLibByteArray; FCost, FBlockSize, FParallelism: Int32; class procedure ClearArray(const AInput: THashLibByteArray); overload; static; inline; class procedure ClearArray(const AInput: THashLibUInt32Array); overload; static; inline; class procedure ClearAllArrays(const AInputs : THashLibMatrixUInt32Array); static; class function IsPowerOf2(x: Int32): Boolean; static; inline; class function SingleIterationPBKDF2(const APasswordBytes, ASaltBytes: THashLibByteArray; AOutputLength: Int32) : THashLibByteArray; static; /// <summary> /// Rotate left /// </summary> /// <param name="x"> /// value to rotate /// </param> /// <param name="y"> /// amount to rotate x /// </param> /// <returns> /// rotated x /// </returns> class function R(x: UInt32; y: Int32): UInt32; static; inline; /// <summary> /// lifted from <c>ClpSalsa20Engine.pas</c> in CryptoLib4Pascal with /// minor modifications. /// </summary> class procedure SalsaCore(rounds: Int32; const input, x: THashLibUInt32Array); static; class procedure &Xor(const a, b: THashLibUInt32Array; bOff: Int32; const output: THashLibUInt32Array); static; class procedure SMix(const b: THashLibUInt32Array; bOff, N, R: Int32); static; class procedure BlockMix(const b, X1, X2, y: THashLibUInt32Array; R: Int32); static; class procedure DoSMix(const b: THashLibUInt32Array; AParallelism, ACost, ABlockSize: Int32); static; class function MFcrypt(const APasswordBytes, ASaltBytes: THashLibByteArray; ACost, ABlockSize, AParallelism, AOutputLength: Int32) : THashLibByteArray; static; public class procedure ValidatePBKDF_ScryptInputs(ACost, ABlockSize, AParallelism: Int32); static; constructor Create(const APasswordBytes, ASaltBytes: THashLibByteArray; ACost, ABlockSize, AParallelism: Int32); destructor Destroy; override; procedure Clear(); override; /// <summary> /// Returns the pseudo-random bytes for this object. /// </summary> /// <param name="bc">The number of pseudo-random key bytes to generate.</param> /// <returns>A byte array filled with pseudo-random key bytes.</returns> /// /// <exception cref="EArgumentOutOfRangeHashLibException">bc must be greater than zero.</exception> function GetBytes(bc: Int32): THashLibByteArray; override; end; implementation { TPBKDF_ScryptNotBuildInAdapter } class procedure TPBKDF_ScryptNotBuildInAdapter.ClearArray (const AInput: THashLibByteArray); begin TArrayUtils.ZeroFill(AInput); end; class procedure TPBKDF_ScryptNotBuildInAdapter.ClearArray (const AInput: THashLibUInt32Array); begin TArrayUtils.ZeroFill(AInput); end; class procedure TPBKDF_ScryptNotBuildInAdapter.ClearAllArrays (const AInputs: THashLibMatrixUInt32Array); var Idx: Int32; begin for Idx := System.Low(AInputs) to System.High(AInputs) do begin ClearArray(AInputs[Idx]); end; end; class function TPBKDF_ScryptNotBuildInAdapter.IsPowerOf2(x: Int32): Boolean; begin result := (x > 0) and ((x and (x - 1)) = 0); end; class function TPBKDF_ScryptNotBuildInAdapter.SingleIterationPBKDF2 (const APasswordBytes, ASaltBytes: THashLibByteArray; AOutputLength: Int32) : THashLibByteArray; begin result := (TPBKDF2_HMACNotBuildInAdapter.Create(TSHA2_256.Create() as IHash, APasswordBytes, ASaltBytes, 1) as IPBKDF2_HMAC).GetBytes(AOutputLength); end; class procedure TPBKDF_ScryptNotBuildInAdapter.&Xor(const a, b: THashLibUInt32Array; bOff: Int32; const output: THashLibUInt32Array); var i: Int32; begin i := System.Length(output) - 1; while i >= 0 do begin output[i] := a[i] xor b[bOff + i]; System.Dec(i); end; end; class function TPBKDF_ScryptNotBuildInAdapter.R(x: UInt32; y: Int32): UInt32; begin result := TBits.RotateLeft32(x, y); end; class procedure TPBKDF_ScryptNotBuildInAdapter.SalsaCore(rounds: Int32; const input, x: THashLibUInt32Array); var x00, x01, x02, x03, x04, x05, x06, x07, x08, x09, x10, x11, x12, x13, x14, x15: UInt32; Idx: Int32; begin if (System.Length(input) <> 16) then begin raise EArgumentHashLibException.Create(''); end; if (System.Length(x) <> 16) then begin raise EArgumentHashLibException.Create(''); end; if ((rounds mod 2) <> 0) then begin raise EArgumentHashLibException.CreateRes(@SRoundsMustBeEven); end; x00 := input[0]; x01 := input[1]; x02 := input[2]; x03 := input[3]; x04 := input[4]; x05 := input[5]; x06 := input[6]; x07 := input[7]; x08 := input[8]; x09 := input[9]; x10 := input[10]; x11 := input[11]; x12 := input[12]; x13 := input[13]; x14 := input[14]; x15 := input[15]; Idx := rounds; while Idx > 0 do begin x04 := x04 xor (R((x00 + x12), 7)); x08 := x08 xor (R((x04 + x00), 9)); x12 := x12 xor (R((x08 + x04), 13)); x00 := x00 xor (R((x12 + x08), 18)); x09 := x09 xor (R((x05 + x01), 7)); x13 := x13 xor (R((x09 + x05), 9)); x01 := x01 xor (R((x13 + x09), 13)); x05 := x05 xor (R((x01 + x13), 18)); x14 := x14 xor (R((x10 + x06), 7)); x02 := x02 xor (R((x14 + x10), 9)); x06 := x06 xor (R((x02 + x14), 13)); x10 := x10 xor (R((x06 + x02), 18)); x03 := x03 xor (R((x15 + x11), 7)); x07 := x07 xor (R((x03 + x15), 9)); x11 := x11 xor (R((x07 + x03), 13)); x15 := x15 xor (R((x11 + x07), 18)); x01 := x01 xor (R((x00 + x03), 7)); x02 := x02 xor (R((x01 + x00), 9)); x03 := x03 xor (R((x02 + x01), 13)); x00 := x00 xor (R((x03 + x02), 18)); x06 := x06 xor (R((x05 + x04), 7)); x07 := x07 xor (R((x06 + x05), 9)); x04 := x04 xor (R((x07 + x06), 13)); x05 := x05 xor (R((x04 + x07), 18)); x11 := x11 xor (R((x10 + x09), 7)); x08 := x08 xor (R((x11 + x10), 9)); x09 := x09 xor (R((x08 + x11), 13)); x10 := x10 xor (R((x09 + x08), 18)); x12 := x12 xor (R((x15 + x14), 7)); x13 := x13 xor (R((x12 + x15), 9)); x14 := x14 xor (R((x13 + x12), 13)); x15 := x15 xor (R((x14 + x13), 18)); System.Dec(Idx, 2); end; x[0] := x00 + input[0]; x[1] := x01 + input[1]; x[2] := x02 + input[2]; x[3] := x03 + input[3]; x[4] := x04 + input[4]; x[5] := x05 + input[5]; x[6] := x06 + input[6]; x[7] := x07 + input[7]; x[8] := x08 + input[8]; x[9] := x09 + input[9]; x[10] := x10 + input[10]; x[11] := x11 + input[11]; x[12] := x12 + input[12]; x[13] := x13 + input[13]; x[14] := x14 + input[14]; x[15] := x15 + input[15]; end; class procedure TPBKDF_ScryptNotBuildInAdapter.BlockMix(const b, X1, X2, y: THashLibUInt32Array; R: Int32); var bOff, YOff, halfLen, i: Int32; begin System.Move(b[System.Length(b) - 16], X1[0], 16 * System.SizeOf(UInt32)); bOff := 0; YOff := 0; halfLen := System.Length(b) div 2; i := 2 * R; while i > 0 do begin &Xor(X1, b, bOff, X2); SalsaCore(8, X2, X1); System.Move(X1[0], y[YOff], 16 * System.SizeOf(UInt32)); YOff := halfLen + bOff - YOff; bOff := bOff + 16; System.Dec(i); end; end; class procedure TPBKDF_ScryptNotBuildInAdapter.SMix (const b: THashLibUInt32Array; bOff, N, R: Int32); var BCount, i, j, off: Int32; mask: UInt32; blockX1, blockX2, blockY, x, V: THashLibUInt32Array; begin BCount := R * 32; System.SetLength(blockX1, 16); System.SetLength(blockX2, 16); System.SetLength(blockY, BCount); System.SetLength(x, BCount); System.SetLength(V, N * BCount); try System.Move(b[bOff], x[0], BCount * System.SizeOf(UInt32)); off := 0; i := 0; while i < N do begin System.Move(x[0], V[off], BCount * System.SizeOf(UInt32)); off := off + BCount; BlockMix(x, blockX1, blockX2, blockY, R); System.Move(blockY[0], V[off], BCount * System.SizeOf(UInt32)); off := off + BCount; BlockMix(blockY, blockX1, blockX2, x, R); System.Inc(i, 2); end; mask := UInt32(N) - 1; i := 0; while i < N do begin j := x[BCount - 16] and mask; System.Move(V[j * BCount], blockY[0], BCount * System.SizeOf(UInt32)); &Xor(blockY, x, 0, blockY); BlockMix(blockY, blockX1, blockX2, x, R); System.Inc(i); end; System.Move(x[0], b[bOff], BCount * System.SizeOf(UInt32)); finally ClearArray(V); ClearAllArrays(THashLibMatrixUInt32Array.Create(x, blockX1, blockX2, blockY)); end; end; {$IFDEF HAS_DELPHI_PPL} class procedure TPBKDF_ScryptNotBuildInAdapter.DoSMix (const b: THashLibUInt32Array; AParallelism, ACost, ABlockSize: Int32); function CreateTask(AOffset: Int32): ITask; begin result := TTask.Create( procedure() begin SMix(b, AOffset, ACost, ABlockSize); end); end; var LIdx, LTaskIdx: Int32; LArrayTasks: array of ITask; begin System.SetLength(LArrayTasks, AParallelism); for LIdx := 0 to System.Pred(AParallelism) do begin LArrayTasks[LIdx] := CreateTask(LIdx * 32 * ABlockSize); end; for LTaskIdx := System.Low(LArrayTasks) to System.High(LArrayTasks) do begin LArrayTasks[LTaskIdx].Start; end; TTask.WaitForAll(LArrayTasks); end; {$ELSE} class procedure TPBKDF_ScryptNotBuildInAdapter.DoSMix (const b: THashLibUInt32Array; AParallelism, ACost, ABlockSize: Int32); var i: Int32; begin for i := 0 to System.Pred(AParallelism) do begin SMix(b, i * 32 * ABlockSize, ACost, ABlockSize); end; end; {$ENDIF HAS_DELPHI_PPL} class function TPBKDF_ScryptNotBuildInAdapter.MFcrypt(const APasswordBytes, ASaltBytes: THashLibByteArray; ACost, ABlockSize, AParallelism, AOutputLength: Int32): THashLibByteArray; var MFLenBytes, BLen: Int32; bytes: THashLibByteArray; b: THashLibUInt32Array; begin MFLenBytes := ABlockSize * 128; bytes := SingleIterationPBKDF2(APasswordBytes, ASaltBytes, AParallelism * MFLenBytes); try BLen := System.Length(bytes) div 4; System.SetLength(b, BLen); TConverters.le32_copy(PByte(bytes), 0, PCardinal(b), 0, System.Length(bytes) * System.SizeOf(Byte)); DoSMix(b, AParallelism, ACost, ABlockSize); TConverters.le32_copy(PCardinal(b), 0, PByte(bytes), 0, System.Length(b) * System.SizeOf(UInt32)); result := SingleIterationPBKDF2(APasswordBytes, bytes, AOutputLength); finally ClearArray(b); ClearArray(bytes); end; end; class procedure TPBKDF_ScryptNotBuildInAdapter.ValidatePBKDF_ScryptInputs(ACost, ABlockSize, AParallelism: Int32); var maxParallel: Int32; begin if ((ACost <= 1) or (not IsPowerOf2(ACost))) then raise EArgumentHashLibException.CreateRes(@SInvalidCost); // Only value of ABlockSize that cost (as an int) could be exceeded for is 1 if ((ABlockSize = 1) and (ACost >= 65536)) then raise EArgumentHashLibException.CreateRes(@SBlockSizeAndCostIncompatible); if (ABlockSize < 1) then raise EArgumentHashLibException.CreateRes(@SBlockSizeTooSmall); maxParallel := System.High(Int32) div (128 * ABlockSize * 8); if ((AParallelism < 1) or (AParallelism > maxParallel)) then raise EArgumentHashLibException.CreateResFmt(@SInvalidParallelism, [maxParallel, ABlockSize]); end; procedure TPBKDF_ScryptNotBuildInAdapter.Clear(); begin TArrayUtils.ZeroFill(FPasswordBytes); TArrayUtils.ZeroFill(FSaltBytes); end; constructor TPBKDF_ScryptNotBuildInAdapter.Create(const APasswordBytes, ASaltBytes: THashLibByteArray; ACost, ABlockSize, AParallelism: Int32); begin Inherited Create(); ValidatePBKDF_ScryptInputs(ACost, ABlockSize, AParallelism); FPasswordBytes := System.Copy(APasswordBytes); FSaltBytes := System.Copy(ASaltBytes); FCost := ACost; FBlockSize := ABlockSize; FParallelism := AParallelism; end; destructor TPBKDF_ScryptNotBuildInAdapter.Destroy; begin Clear(); inherited Destroy; end; function TPBKDF_ScryptNotBuildInAdapter.GetBytes(bc: Int32): THashLibByteArray; begin if (bc <= 0) then raise EArgumentHashLibException.CreateRes(@SInvalidByteCount); result := MFcrypt(FPasswordBytes, FSaltBytes, FCost, FBlockSize, FParallelism, bc); end; end.
unit frmDocs_AE_Unit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxGroupBox, cxLookAndFeelPainters, StdCtrls, cxButtons, cxMaskEdit, cxDropDownEdit, cxCalendar, cxContainer, cxEdit, cxTextEdit, cxButtonEdit, Ibase, cn_Common_Types, cn_Common_Loader, cnConsts, cnConsts_Messages, cn_Common_Funcs; type TfrmDocs_AE = class(TForm) cxGroupBox1: TcxGroupBox; OKButton: TcxButton; CancelButton: TcxButton; Num_Doc_Edit: TcxTextEdit; Date_Doc_Edit: TcxDateEdit; Status_Label: TLabel; Date_Doc_Label: TLabel; Status_Edit: TcxButtonEdit; TypeDocum_Edit: TcxButtonEdit; DateDept_Edit: TcxDateEdit; TypeDocum_Label: TLabel; Num_Doc_Label: TLabel; DateDept_Label: TLabel; Order_Date_Edit: TcxDateEdit; Date_Order_Label: TLabel; Order_Num_Edit: TcxTextEdit; Num_Order_Label: TLabel; procedure CancelButtonClick(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Num_Doc_EditKeyPress(Sender: TObject; var Key: Char); procedure Date_Doc_EditKeyPress(Sender: TObject; var Key: Char); procedure Status_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure TypeDocum_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure Status_EditKeyPress(Sender: TObject; var Key: Char); procedure TypeDocum_EditKeyPress(Sender: TObject; var Key: Char); procedure DateDept_EditKeyPress(Sender: TObject; var Key: Char); procedure Order_Num_EditKeyPress(Sender: TObject; var Key: Char); procedure Order_Date_EditKeyPress(Sender: TObject; var Key: Char); private PLanguageIndex :byte; DB_Handle : TISC_DB_HANDLE; procedure FormIniLanguage(); public ID_STATUS, ID_TYPE_DOCUM : int64; constructor Create(Owner: TComponent ; LangIndex : byte; DBHandle: TISC_DB_HANDLE; ViewMode: boolean); reintroduce; end; var frmDocs_AE: TfrmDocs_AE; implementation {$R *.dfm} constructor TfrmDocs_AE.Create(Owner: TComponent ; LangIndex : byte; DBHandle: TISC_DB_HANDLE; ViewMode: boolean ); begin inherited Create(Owner); PLanguageIndex := LangIndex; DB_Handle:= DBHandle; if ViewMode then begin Num_Doc_Edit.Enabled := false; Date_Doc_Edit.Enabled := false; DateDept_Edit.Enabled := false; OKButton.Visible:= false; end; end; procedure TfrmDocs_AE.FormIniLanguage(); begin // индекс языка (1-укр, 2 - рус) NUM_DOC_Label.Caption := cn_Name_Column[PLanguageIndex]; DATE_DOC_Label.Caption := cn_DateDoc_Pay[PLanguageIndex]; Status_Label.Caption := cn_Status[PLanguageIndex]; TypeDocum_Label.Caption := cn_Type[PLanguageIndex]; DateDept_Label.Caption := cn_DateCalc[PLanguageIndex]; Date_Order_Label.Caption := cn_DatePrikaz[PLanguageIndex]; Num_Order_Label.Caption := cn_NomPrikaz[PLanguageIndex]; OKButton.Caption := cn_Accept[PLanguageIndex]; CancelButton.Caption := cn_Cancel[PLanguageIndex]; end; procedure TfrmDocs_AE.CancelButtonClick(Sender: TObject); begin close; end; procedure TfrmDocs_AE.OKButtonClick(Sender: TObject); begin if CheckControls(self, PLanguageIndex) then exit; ModalResult := MrOk; end; procedure TfrmDocs_AE.FormShow(Sender: TObject); begin FormIniLanguage(); end; procedure TfrmDocs_AE.Num_Doc_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Date_Doc_Edit.SetFocus; end; procedure TfrmDocs_AE.Date_Doc_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then DateDept_Edit.SetFocus; end; procedure TfrmDocs_AE.Status_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var AParameter:TcnSimpleParams; res: Variant; begin AParameter:= TcnSimpleParams.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DB_Handle; AParameter.Formstyle:=fsNormal; AParameter.WaitPakageOwner:=self; res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_RaportStatus.bpl','ShowSPRapStatus'); if VarArrayDimCount(Res)>0 then begin ID_STATUS := res[0]; Status_Edit.Text := res[1]; end; AParameter.Free; end; procedure TfrmDocs_AE.TypeDocum_EditPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var AParameter:TcnSimpleParams; res: Variant; begin AParameter:= TcnSimpleParams.Create; AParameter.Owner:=self; AParameter.Db_Handle:= DB_Handle; AParameter.Formstyle:=fsNormal; AParameter.WaitPakageOwner:=self; res:= RunFunctionFromPackage(AParameter, 'Contracts\cn_sp_TypeDocum.bpl','ShowSPTypeDocum'); if VarArrayDimCount(Res)>0 then begin ID_TYPE_DOCUM := res[0]; TypeDocum_Edit.Text := res[1]; end; AParameter.Free; end; procedure TfrmDocs_AE.Status_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then TypeDocum_Edit.SetFocus; end; procedure TfrmDocs_AE.TypeDocum_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then DateDept_Edit.SetFocus; end; procedure TfrmDocs_AE.DateDept_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Order_Date_Edit.SetFocus; end; procedure TfrmDocs_AE.Order_Num_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then OKButton.SetFocus; end; procedure TfrmDocs_AE.Order_Date_EditKeyPress(Sender: TObject; var Key: Char); begin if key = #13 then Order_Num_Edit.SetFocus; end; end.
unit uFrAdvancedOptions; {$WARN SYMBOL_PLATFORM OFF} interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Win.Registry, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CheckLst, Vcl.Menus, Vcl.AppEvnts, UnitDBFileDialogs, uInstallFrame, uShellUtils, uInstallScope, uInstallUtils, uAssociations, uMemory; type TFrAdvancedOptions = class(TInstallFrame) CbFileExtensions: TCheckListBox; EdPath: TEdit; LbInstallPath: TLabel; CbInstallTypeChecked: TCheckBox; LblUseExt: TLabel; CbInstallTypeGrayed: TCheckBox; LblAddSubmenuItem: TLabel; CbInstallTypeNone: TCheckBox; LblSkipExt: TLabel; BtnSelectDirectory: TButton; PmAssociations: TPopupMenu; SelectDefault1: TMenuItem; SelectAll1: TMenuItem; SelectNone1: TMenuItem; AppEvents: TApplicationEvents; procedure BtnSelectDirectoryClick(Sender: TObject); procedure SelectDefault1Click(Sender: TObject); procedure SelectAll1Click(Sender: TObject); procedure SelectNone1Click(Sender: TObject); procedure AppEventsMessage(var Msg: tagMSG; var Handled: Boolean); private { Private declarations } procedure LoadExtensionList; procedure LoadDefault; procedure LoadNone; procedure LoadAll; public { Public declarations } procedure Init; override; procedure LoadLanguage; override; function ValidateFrame : Boolean; override; procedure InitInstall; override; end; implementation {$R *.dfm} procedure TFrAdvancedOptions.AppEventsMessage(var Msg: tagMSG; var Handled: Boolean); begin inherited; if (Msg.message = WM_LBUTTONDOWN) or (Msg.message = WM_LBUTTONDBLCLK) or (Msg.message = WM_MOUSEMOVE) then begin if (Msg.hwnd = CbInstallTypeChecked.Handle) or (Msg.hwnd = CbInstallTypeGrayed.Handle) or (Msg.hwnd = CbInstallTypeNone.Handle) then Msg.message := 0; end; end; procedure TFrAdvancedOptions.BtnSelectDirectoryClick(Sender: TObject); var Dir: string; begin Dir := DBSelectDir(Handle, L('Please, select directory to install Photo Database.')); if DirectoryExists(Dir) then begin Dir := IncludeTrailingBackslash(Dir); EdPath.Text := Dir + 'Photo DataBase'; end; end; procedure TFrAdvancedOptions.Init; begin inherited; LoadExtensionList; LoadDefault; EdPath.Enabled := not IsApplicationInstalled; BtnSelectDirectory.Enabled := not IsApplicationInstalled; if not EdPath.Enabled then EdPath.Text := ExtractFileDir(GetInstalledFileName) else EdPath.Text := IncludeTrailingBackslash(GetProgramFilesPath) + 'Photo DataBase'; end; procedure TFrAdvancedOptions.InitInstall; var I: Integer; begin inherited; for I := 0 to CbFileExtensions.Items.Count - 1 do TFileAssociations.Instance.Exts[TFileAssociation(CbFileExtensions.Items.Objects[I]).Extension].State := CheckboxStateToAssociationState(CbFileExtensions.State[I]); CurrentInstall.DestinationPath := EdPath.Text; end; procedure TFrAdvancedOptions.LoadAll; var I: Integer; begin for I := 0 to CbFileExtensions.Items.Count - 1 do CbFileExtensions.State[I] := CbChecked; end; procedure TFrAdvancedOptions.LoadDefault; var I: Integer; begin for I := 0 to CbFileExtensions.Items.Count - 1 do CbFileExtensions.State[I] := AssociationStateToCheckboxState(TFileAssociations.Instance.GetCurrentAssociationState(TFileAssociation(CbFileExtensions.Items.Objects[I]).Extension), IsApplicationInstalled); end; procedure TFrAdvancedOptions.LoadExtensionList; var I : Integer; begin CbFileExtensions.Items.Clear; for I := 0 to TFileAssociations.Instance.Count - 1 do CbFileExtensions.Items.AddObject(Format('%s (%s)', [TFileAssociations.Instance[I].Extension, TFileAssociations.Instance[I].Description]), TFileAssociations.Instance[I]); end; procedure TFrAdvancedOptions.LoadLanguage; begin inherited; LbInstallPath.Caption := L('Install path') + ':'; SelectDefault1.Caption := L('Select default associations'); SelectAll1.Caption := L('Select all'); SelectNone1.Caption := L('Select none'); LblUseExt.Caption := L('Use PhotoDB as default association'); LblAddSubmenuItem.Caption := L('Add menu item'); LblSkipExt.Caption := L('Don''t use this extension'); end; procedure TFrAdvancedOptions.LoadNone; var I: Integer; begin for I := 0 to CbFileExtensions.Items.Count - 1 do CbFileExtensions.State[I] := cbUnchecked; end; procedure TFrAdvancedOptions.SelectAll1Click(Sender: TObject); begin inherited; LoadAll; end; procedure TFrAdvancedOptions.SelectDefault1Click(Sender: TObject); begin inherited; LoadDefault; end; procedure TFrAdvancedOptions.SelectNone1Click(Sender: TObject); begin inherited; LoadNone; end; function TFrAdvancedOptions.ValidateFrame: Boolean; begin Result := True; end; end.
program HowToUseListBox; uses SwinGame, sgTypes, sgUserInterface; procedure Main(); var p1,p2 : Panel; lst : GUIList; begin OpenAudio(); OpenGraphicsWindow('How To Use ListBox ', 320, 240); LoadDefaultColors(); GUISetBackgroundColor(ColorWhite); GUISetForegroundColor(ColorGreen); LoadResourceBundle('MainMenu.txt'); //LoadMusic LoadMusic('game.ogg'); LoadMusic('diving-turtle.mp3'); LoadMusic('fast.mp3'); LoadMusic('gentle-thoughts-1.mp3'); LoadMusic('morning-workout.mp3'); LoadMusic('saber.ogg'); LoadMusic('chipmunk.ogg'); LoadMusic('bells.ogg'); LoadMusic('camera.ogg'); LoadMusic('comedy_boing.ogg'); LoadMusic('dinosaur.ogg'); LoadMusic('dog_bark.ogg'); p1 := LoadPanel('lstBoxPanel.txt'); ShowPanel(p1); lst := ListFromRegion(RegionWithID(p1, 'List1')); ListAddItem(lst, 'Game'); ListAddItem(lst, 'Diving Turtle'); ListAddItem(lst, 'Fast'); ListAddItem(lst, 'Gentle Thoughts'); ListAddItem(lst, 'Morning Workout'); ListAddItem(lst, 'Saber'); ListAddItem(lst, 'Chipmunk'); ListAddItem(lst, 'Bells'); ListAddItem(lst, 'Camera'); ListAddItem(lst, 'Comedy Boing'); ListAddItem(lst, 'Dinosaur'); ListAddItem(lst, 'Dog Bark'); p2 := LoadPanel('lstBoxPanel2.txt'); ShowPanel(p2); PanelSetDraggable(p1, false); PanelSetDraggable(p2, false); repeat // The game loop... ProcessEvents(); if RegionClickedId() = 'Button1' then begin if ListActiveItemIndex(lst) = 0 then PlayMusic('game.ogg'); if ListActiveItemIndex(lst) = 1 then PlayMusic('diving-turtle.mp3'); if ListActiveItemIndex(lst) = 2 then PlayMusic('fast.mp3'); if ListActiveItemIndex(lst) = 3 then PlayMusic('gentle-thoughts-1.mp3'); if ListActiveItemIndex(lst) = 4 then PlayMusic('morning-workout.mp3'); if ListActiveItemIndex(lst) = 5 then PlayMusic('saber.ogg'); if ListActiveItemIndex(lst) = 6 then PlayMusic('chipmunk.ogg'); if ListActiveItemIndex(lst) = 7 then PlayMusic('bells.ogg'); if ListActiveItemIndex(lst) = 8 then PlayMusic('camera.ogg'); if ListActiveItemIndex(lst) = 9 then PlayMusic('comedy_boing.ogg'); if ListActiveItemIndex(lst) = 10 then PlayMusic('dinosaur.ogg'); if ListActiveItemIndex(lst) = 11 then PlayMusic('dog_bark.ogg'); end; if RegionClickedId() = 'Button2' then if MusicPlaying() then PauseMusic(); if RegionClickedId() = 'Button3' then ResumeMusic(); if RegionClickedId() = 'Button4' then if MusicPlaying() then StopMusic(); DrawInterface(); UpdateInterface(); RefreshScreen(); until WindowCloseRequested() or (RegionClickedId() = 'Button5'); CloseAudio(); ReleaseAllResources(); end; begin Main(); end.
// // Generated by JavaToPas v1.5 20171018 - 170928 //////////////////////////////////////////////////////////////////////////////// unit android.print.PrinterInfo; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.os, android.print.PrinterId, android.print.PrinterCapabilitiesInfo; type JPrinterInfo = interface; JPrinterInfoClass = interface(JObjectClass) ['{3D41F71A-E4AB-469B-AE43-E36F67EFDF0E}'] function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19 function _GetSTATUS_BUSY : Integer; cdecl; // A: $19 function _GetSTATUS_IDLE : Integer; cdecl; // A: $19 function _GetSTATUS_UNAVAILABLE : Integer; cdecl; // A: $19 function describeContents : Integer; cdecl; // ()I A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getCapabilities : JPrinterCapabilitiesInfo; cdecl; // ()Landroid/print/PrinterCapabilitiesInfo; A: $1 function getDescription : JString; cdecl; // ()Ljava/lang/String; A: $1 function getId : JPrinterId; cdecl; // ()Landroid/print/PrinterId; A: $1 function getName : JString; cdecl; // ()Ljava/lang/String; A: $1 function getStatus : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19 property STATUS_BUSY : Integer read _GetSTATUS_BUSY; // I A: $19 property STATUS_IDLE : Integer read _GetSTATUS_IDLE; // I A: $19 property STATUS_UNAVAILABLE : Integer read _GetSTATUS_UNAVAILABLE; // I A: $19 end; [JavaSignature('android/print/PrinterInfo$Builder')] JPrinterInfo = interface(JObject) ['{7F77DDC1-FC0D-47FC-A766-8EB8DAD24674}'] function describeContents : Integer; cdecl; // ()I A: $1 function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1 function getCapabilities : JPrinterCapabilitiesInfo; cdecl; // ()Landroid/print/PrinterCapabilitiesInfo; A: $1 function getDescription : JString; cdecl; // ()Ljava/lang/String; A: $1 function getId : JPrinterId; cdecl; // ()Landroid/print/PrinterId; A: $1 function getName : JString; cdecl; // ()Ljava/lang/String; A: $1 function getStatus : Integer; cdecl; // ()I A: $1 function hashCode : Integer; cdecl; // ()I A: $1 function toString : JString; cdecl; // ()Ljava/lang/String; A: $1 procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1 end; TJPrinterInfo = class(TJavaGenericImport<JPrinterInfoClass, JPrinterInfo>) end; const TJPrinterInfoSTATUS_BUSY = 2; TJPrinterInfoSTATUS_IDLE = 1; TJPrinterInfoSTATUS_UNAVAILABLE = 3; implementation end.
unit OthelloGame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Controls, FMX.StdCtrls, FMX.Controls3D, FMX.Objects3D,FMX.Forms3D ,FMX.Types, FMX.Ani, FMX.MaterialSources, OthelloCounters, OthelloBoard, OthelloCounterSet, FMX.Layers3D, FMX.Media, FMX.Objects, FMX.Dialogs; type TOthello = class(TForm3D) TileColorDark: TColorMaterialSource; TileColorLight: TColorMaterialSource; Dummy1: TDummy; CameraComponent1: TCameraComponent; Light1: TLight; Camera1: TCamera; CurrentTurnTXT: TText3D; CurrentTurnColorSource: TColorMaterialSource; CurrentTurnColorShaftSource: TColorMaterialSource; BottomBar: TLayer3D; WhiteScore: TText; BlackScore: TText; NewGameBTN: TButton; TopBar: TLayer3D; Background: TLayer3D; Text1: TText; Button1: TButton; procedure Form3DCreate(Sender: TObject); procedure NewGameBTNClick(Sender: TObject); procedure Button1Click(Sender: TObject); private FCounterColorDark: TMaterialSource; FCounterColorLight: TMaterialSource; Board: TOthelloBoard; CounterSet: TOthelloCounterSet; procedure CreateCounterSet; { Private declarations } public procedure OnTileClick(Sender : TOthelloTile); end; var Othello: TOthello; const GridSize = 8; const TileSize = 1; implementation {$R *.fmx} procedure TOthello.Form3DCreate(Sender: TObject); begin FCounterColorDark := TOthelloBlackMaterial.Create(Self); FCounterColorLight:= TOthelloWhiteMaterial.Create(Self); Board := TOthelloBoard.Create(Self,GridSize,TileSize,TileColorLight,TileColorDark); Board.Parent := Dummy1; Board.Position.X := -3.5; Board.Position.Y := -3; Board.Position.Z := 0.7; Board.OnTileClick := OnTileClick; Dummy1.RotationAngle.X := -35; CreateCounterSet; end; procedure TOthello.NewGameBTNClick(Sender: TObject); begin CreateCounterSet; CounterSet.CurrentTurn := Black; CurrentTurnTXT.Text := 'Blacks Turn'; CurrentTurnColorSource.Color := TAlphaColor($FF202020); CurrentTurnColorShaftSource.Color := TAlphaColor($FFEEEEEEE); WhiteScore.Text := 'White 2'; BlackScore.Text := 'Black 2'; end; procedure TOthello.Button1Click(Sender: TObject); begin Othello.Close; end; procedure TOthello.CreateCounterSet; begin if Assigned(CounterSet) then begin {$IFDEF NEXTGEN} CounterSet.DisposeOf(); {$ENDIF} FreeAndNil(CounterSet); end; CounterSet := TOthelloCounterSet.Create(Self,GridSize,TileSize,FCounterColorDark,FCounterColorLight); CounterSet.Parent := Dummy1; CounterSet.Position.X := -3.5; CounterSet.Position.Y := -3; end; procedure TOthello.OnTileClick(Sender: TOthelloTile); var TotalWhiteCounters, TotalBlackCounters: Integer; begin CounterSet.AddCounter(Sender.X, Sender.Y); TotalWhiteCounters := CounterSet.GetScore(TOthelloState.White); TotalBlackCounters := CounterSet.GetScore(TOthelloState.Black); WhiteScore.Text := 'White '+IntToStr(TotalWhiteCounters); BlackScore.Text := 'Black '+IntToStr(TotalBlackCounters); //CurrentTurnTXT.AnimateFloat('RotationAngle.Y', 360, 1, TAnimationType.atInOut, TInterpolationType.itBack); if CounterSet.CurrentTurn = Black then begin CurrentTurnColorSource.Color := TAlphaColor($FF202020); CurrentTurnColorShaftSource.Color := TAlphaColor($FFEEEEEEE); CurrentTurnTXT.Text := 'Blacks Turn'; end else begin CurrentTurnColorSource.Color := TAlphaColor($FFEEEEEE); CurrentTurnColorShaftSource.Color := TAlphaColor($FF202020); CurrentTurnTXT.Text := 'Whites Turn'; end; if TotalWhiteCounters + TotalBlackCounters = 64 then begin CurrentTurnColorSource.Color := TAlphaColor($FFEEEEEE); CurrentTurnColorShaftSource.Color := TAlphaColor($FF202020); CurrentTurnTXT.AnimateFloat('RotationAngle.Y', 360, 1, TAnimationType.atInOut, TInterpolationType.itBack); if TotalWhiteCounters > TotalBlackCounters then begin CurrentTurnTXT.Text := 'White Wins!'; end else if TotalBlackCounters > TotalWhiteCounters then begin CurrentTurnTXT.Text := 'Black Wins!'; end else begin CurrentTurnTXT.Text := 'A Draw!'; end; end; end; end.
{---------------------------------------------------------------- Nome: UntComandos Descrição: Unit que contém 'automatizações' dos comandos de saída do IRC(Comunicação externa. Métodos: -procedure PvtMsg(Destino, Menssagem: string); Envia menssagem para um canal ou usuário. -procedure PartCha(Canal: string); Sai de um canal que esteja conectado. ----------------------------------------------------------------} unit UntComandos; interface procedure PvtMsg(Destino, Menssagem: string); procedure PartCha(Canal: string); const cStrPvt = 'PRIVMSG %s :%s'; cStrPart = 'PART %s'; cStrJoin = 'JOIN %s'; cStrDccSend = #1 + 'DCC SEND %s 2130706433 4493 1719808' + #1; {TEMP} implementation uses SysUtils, UntPrincipal, WinSock; procedure PvtMsg(Destino, Menssagem: string); begin FrmPrincipal.ClientePrincipal.Socket.SendText(Format(cStrPvt, [Destino, Menssagem]) + #13 + #10); end; procedure PartCha(canal: string); begin FrmPrincipal.ClientePrincipal.Socket.SendText(Format(cStrPart, [Canal]) + #13 + #10); end; end.
// // This unit is part of the VXScene Project, http://glscene.org // { Some useful methods for setting up bump maps. } unit VXS.BumpMapping; interface uses System.UITypes, FMX.Graphics, VXS.Color, VXS.VectorGeometry, VXS.VectorLists, VXS.VectorTypes; type TNormalMapSpace = (nmsObject, nmsTangent); procedure CalcObjectSpaceLightVectors(Light : TAffineVector; Vertices: TAffineVectorList; Colors: TVectorList); procedure SetupTangentSpace(Vertices, Normals, TexCoords, Tangents, BiNormals : TAffineVectorList); procedure CalcTangentSpaceLightVectors(Light : TAffineVector; Vertices, Normals, Tangents, BiNormals : TAffineVectorList; Colors: TVectorList); function CreateObjectSpaceNormalMap(Width, Height : Integer; HiNormals,HiTexCoords : TAffineVectorList) : TBitmap; function CreateTangentSpaceNormalMap(Width, Height : Integer; HiNormals, HiTexCoords, LoNormals, LoTexCoords, Tangents, BiNormals : TAffineVectorList) : TBitmap; //------------------------------------------------------------ implementation //------------------------------------------------------------ procedure CalcObjectSpaceLightVectors(Light: TAffineVector; Vertices: TAffineVectorList; Colors: TVectorList); var i: Integer; vec: TAffineVector; begin Colors.Count := Vertices.Count; for i := 0 to Vertices.Count - 1 do begin vec := VectorNormalize(VectorSubtract(Light, Vertices[i])); Colors[i] := VectorMake(VectorAdd(VectorScale(vec, 0.5), 0.5), 1); end; end; procedure SetupTangentSpace(Vertices, Normals, TexCoords, Tangents, BiNormals: TAffineVectorList); var i, j: Integer; v, n, t: TAffineMatrix; vt, tt: TAffineVector; interp, dot: Single; procedure SortVertexData(sortidx: Integer); begin if t.X.v[sortidx] < t.Y.v[sortidx] then begin vt := v.X; tt := t.X; v.X := v.Y; t.X := t.Y; v.Y := vt; t.Y := tt; end; if t.X.v[sortidx] < t.Z.v[sortidx] then begin vt := v.X; tt := t.X; v.X := v.Z; t.X := t.Z; v.Z := vt; t.Z := tt; end; if t.Y.v[sortidx] < t.Z.v[sortidx] then begin vt := v.Y; tt := t.Y; v.Y := v.Z; t.Y := t.Z; v.Z := vt; t.Z := tt; end; end; begin for i := 0 to (Vertices.Count div 3) - 1 do begin // Get triangle data for j := 0 to 2 do begin v.v[j] := Vertices[3 * i + j]; n.v[j] := Normals[3 * i + j]; t.v[j] := TexCoords[3 * i + j]; end; for j := 0 to 2 do begin // Compute tangent SortVertexData(1); if (t.Z.Y - t.X.Y) = 0 then interp := 1 else interp := (t.Y.Y - t.X.Y) / (t.Z.Y - t.X.Y); vt := VectorLerp(v.X, v.Z, interp); interp := t.X.X + (t.Z.X - t.X.X) * interp; vt := VectorSubtract(vt, v.Y); if t.Y.X < interp then vt := VectorNegate(vt); dot := VectorDotProduct(vt, n.v[j]); vt.X := vt.X - n.v[j].X * dot; vt.Y := vt.Y - n.v[j].Y * dot; vt.Z := vt.Z - n.v[j].Z * dot; Tangents.Add(VectorNormalize(vt)); // Compute Bi-Normal SortVertexData(0); if (t.Z.X - t.X.X) = 0 then interp := 1 else interp := (t.Y.X - t.X.X) / (t.Z.X - t.X.X); vt := VectorLerp(v.X, v.Z, interp); interp := t.X.Y + (t.Z.Y - t.X.Y) * interp; vt := VectorSubtract(vt, v.Y); if t.Y.Y < interp then vt := VectorNegate(vt); dot := VectorDotProduct(vt, n.v[j]); vt.X := vt.X - n.v[j].X * dot; vt.Y := vt.Y - n.v[j].Y * dot; vt.Z := vt.Z - n.v[j].Z * dot; BiNormals.Add(VectorNormalize(vt)); end; end; end; procedure CalcTangentSpaceLightVectors(Light: TAffineVector; Vertices, Normals, Tangents, BiNormals: TAffineVectorList; Colors: TVectorList); var i: Integer; mat: TAffineMatrix; vec: TAffineVector; begin Colors.Count := Vertices.Count; for i := 0 to Vertices.Count - 1 do begin mat.X := Tangents[i]; mat.Y := BiNormals[i]; mat.Z := Normals[i]; TransposeMatrix(mat); vec := VectorNormalize(VectorTransform(VectorSubtract(Light, Vertices[i]), mat)); vec.X := -vec.X; Colors[i] := VectorMake(VectorAdd(VectorScale(vec, 0.5), 0.5), 1); end; end; // ------------------------------------------------------------------------ // Local functions used for creating normal maps // ------------------------------------------------------------------------ function ConvertNormalToColor(normal: TAffineVector): TColor; var r, g, b: Byte; begin r := Round(255 * (normal.X * 0.5 + 0.5)); g := Round(255 * (normal.Y * 0.5 + 0.5)); b := Round(255 * (normal.Z * 0.5 + 0.5)); Result := RGB2Color(r, g, b); end; procedure GetBlendCoeffs(X, Y, x1, y1, x2, y2, x3, y3: Integer; var f1, f2, f3: Single); var m1, m2, d1, d2, px, py: Single; begin if (x1 = X) and (x2 = x3) then f1 := 0 else begin if x1 = X then begin m2 := (y3 - y2) / (x3 - x2); d2 := y2 - m2 * x2; px := X; py := m2 * px + d2; end else if x2 = x3 then begin m1 := (y1 - Y) / (x1 - X); d1 := y1 - m1 * x1; px := x2; py := m1 * px + d1; end else begin m1 := (y1 - Y) / (x1 - X); d1 := y1 - m1 * x1; m2 := (y3 - y2) / (x3 - x2); d2 := y2 - m2 * x2; px := (d1 - d2) / (m2 - m1); py := m2 * px + d2; end; f1 := sqrt((X - x1) * (X - x1) + (Y - y1) * (Y - y1)) / sqrt((px - x1) * (px - x1) + (py - y1) * (py - y1)); end; if (x2 = X) and (x1 = x3) then f2 := 0 else begin if x2 = X then begin m2 := (y3 - y1) / (x3 - x1); d2 := y1 - m2 * x1; px := X; py := m2 * px + d2; end else if x3 = x1 then begin m1 := (y2 - Y) / (x2 - X); d1 := y2 - m1 * x2; px := x1; py := m1 * px + d1; end else begin m1 := (y2 - Y) / (x2 - X); d1 := y2 - m1 * x2; m2 := (y3 - y1) / (x3 - x1); d2 := y1 - m2 * x1; px := (d1 - d2) / (m2 - m1); py := m2 * px + d2; end; f2 := sqrt((X - x2) * (X - x2) + (Y - y2) * (Y - y2)) / sqrt((px - x2) * (px - x2) + (py - y2) * (py - y2)); end; if (x3 = X) and (x1 = x2) then f3 := 0 else begin if X = x3 then begin m2 := (y2 - y1) / (x2 - x1); d2 := y1 - m2 * x1; px := X; py := m2 * px + d2; end else if x2 = x1 then begin m1 := (y3 - Y) / (x3 - X); d1 := y3 - m1 * x3; px := x1; py := m1 * px + d1; end else begin m1 := (y3 - Y) / (x3 - X); d1 := y3 - m1 * x3; m2 := (y2 - y1) / (x2 - x1); d2 := y1 - m2 * x1; px := (d1 - d2) / (m2 - m1); py := m2 * px + d2; end; f3 := sqrt((X - x3) * (X - x3) + (Y - y3) * (Y - y3)) / sqrt((px - x3) * (px - x3) + (py - y3) * (py - y3)); end; end; function BlendNormals(X, Y, x1, y1, x2, y2, x3, y3: Integer; n1, n2, n3: TAffineVector): TAffineVector; var f1, f2, f3: Single; begin GetBlendCoeffs(X, Y, x1, y1, x2, y2, x3, y3, f1, f2, f3); Result := VectorScale(n1, 1 - f1); AddVector(Result, VectorScale(n2, 1 - f2)); AddVector(Result, VectorScale(n3, 1 - f3)); end; procedure CalcObjectSpaceNormalMap(Width, Height: Integer; NormalMap, Normals, TexCoords: TAffineVectorList); var i, X, Y, xs, xe, x1, y1, x2, y2, x3, y3: Integer; n, n1, n2, n3: TAffineVector; begin for i := 0 to (TexCoords.Count div 3) - 1 do begin x1 := Round(TexCoords[3 * i].X * (Width - 1)); y1 := Round((1 - TexCoords[3 * i].Y) * (Height - 1)); x2 := Round(TexCoords[3 * i + 1].X * (Width - 1)); y2 := Round((1 - TexCoords[3 * i + 1].Y) * (Height - 1)); x3 := Round(TexCoords[3 * i + 2].X * (Width - 1)); y3 := Round((1 - TexCoords[3 * i + 2].Y) * (Height - 1)); n1 := Normals[3 * i]; n2 := Normals[3 * i + 1]; n3 := Normals[3 * i + 2]; if y2 < y1 then begin X := x1; Y := y1; n := n1; x1 := x2; y1 := y2; n1 := n2; x2 := X; y2 := Y; n2 := n; end; if y3 < y1 then begin X := x1; Y := y1; n := n1; x1 := x3; y1 := y3; n1 := n3; x3 := X; y3 := Y; n3 := n; end; if y3 < y2 then begin X := x2; Y := y2; n := n2; x2 := x3; y2 := y3; n2 := n3; x3 := X; y3 := Y; n3 := n; end; if y1 < y2 then for Y := y1 to y2 do begin xs := Round(x1 + (x2 - x1) * ((Y - y1) / (y2 - y1))); xe := Round(x1 + (x3 - x1) * ((Y - y1) / (y3 - y1))); if xe < xs then begin X := xs; xs := xe; xe := X; end; for X := xs to xe do NormalMap[X + Y * Width] := BlendNormals(X, Y, x1, y1, x2, y2, x3, y3, n1, n2, n3); end; if y2 < y3 then for Y := y2 to y3 do begin xs := Round(x2 + (x3 - x2) * ((Y - y2) / (y3 - y2))); xe := Round(x1 + (x3 - x1) * ((Y - y1) / (y3 - y1))); if xe < xs then begin X := xs; xs := xe; xe := X; end; for X := xs to xe do NormalMap[X + Y * Width] := BlendNormals(X, Y, x1, y1, x2, y2, x3, y3, n1, n2, n3); end; end; end; function CreateObjectSpaceNormalMap(Width, Height: Integer; HiNormals, HiTexCoords: TAffineVectorList): TBitmap; var i: Integer; NormalMap: TAffineVectorList; begin NormalMap := TAffineVectorList.Create; NormalMap.AddNulls(Width * Height); CalcObjectSpaceNormalMap(Width, Height, NormalMap, HiNormals, HiTexCoords); // Creates the bitmap Result := TBitmap.Create; { TODO : E2129 Cannot assign to a read-only property } (* Result.Image.Width := Width; Result.Image.Height := Height; Result.PixelFormat := TPixelFormat.RGBA; *) // Paint bitmap with normal map normals (X,Y,Z) -> (R,G,B) for i := 0 to NormalMap.Count - 1 do { TODO : E2003 Undeclared identifier: 'Pixels' } (* Result.Canvas.Pixels[i mod Width, i div Height]:= ConvertNormalToColor(NormalMap[i]); *) NormalMap.Free; end; function CreateTangentSpaceNormalMap(Width, Height: Integer; HiNormals, HiTexCoords, LoNormals, LoTexCoords, Tangents, BiNormals: TAffineVectorList): TBitmap; function NormalToTangentSpace(normal: TAffineVector; X, Y, x1, y1, x2, y2, x3, y3: Integer; m1, m2, m3: TAffineMatrix) : TAffineVector; var n1, n2, n3: TAffineVector; begin n1 := VectorTransform(normal, m1); n2 := VectorTransform(normal, m2); n3 := VectorTransform(normal, m3); Result := BlendNormals(X, Y, x1, y1, x2, y2, x3, y3, n1, n2, n3); NormalizeVector(Result); end; var i, X, Y, xs, xe, x1, y1, x2, y2, x3, y3: Integer; NormalMap: TAffineVectorList; n: TAffineVector; m, m1, m2, m3: TAffineMatrix; begin NormalMap := TAffineVectorList.Create; NormalMap.AddNulls(Width * Height); CalcObjectSpaceNormalMap(Width, Height, NormalMap, HiNormals, HiTexCoords); // Transform the object space normals into tangent space for i := 0 to (LoTexCoords.Count div 3) - 1 do begin x1 := Round(LoTexCoords[3 * i].X * (Width - 1)); y1 := Round((1 - LoTexCoords[3 * i].Y) * (Height - 1)); x2 := Round(LoTexCoords[3 * i + 1].X * (Width - 1)); y2 := Round((1 - LoTexCoords[3 * i + 1].Y) * (Height - 1)); x3 := Round(LoTexCoords[3 * i + 2].X * (Width - 1)); y3 := Round((1 - LoTexCoords[3 * i + 2].Y) * (Height - 1)); m1.X := Tangents[3 * i]; m1.Y := BiNormals[3 * i]; m1.Z := LoNormals[3 * i]; m2.X := Tangents[3 * i + 1]; m2.Y := BiNormals[3 * i + 1]; m2.Z := LoNormals[3 * i + 1]; m3.X := Tangents[3 * i + 2]; m3.Y := BiNormals[3 * i + 2]; m3.Z := LoNormals[3 * i + 2]; TransposeMatrix(m1); TransposeMatrix(m2); TransposeMatrix(m3); InvertMatrix(m1); InvertMatrix(m2); InvertMatrix(m3); if y2 < y1 then begin X := x1; Y := y1; m := m1; x1 := x2; y1 := y2; m1 := m2; x2 := X; y2 := Y; m2 := m; end; if y3 < y1 then begin X := x1; Y := y1; m := m1; x1 := x3; y1 := y3; m1 := m3; x3 := X; y3 := Y; m3 := m; end; if y3 < y2 then begin X := x2; Y := y2; m := m2; x2 := x3; y2 := y3; m2 := m3; x3 := X; y3 := Y; m3 := m; end; if y1 < y2 then for Y := y1 to y2 do begin xs := Round(x1 + (x2 - x1) * ((Y - y1) / (y2 - y1))); xe := Round(x1 + (x3 - x1) * ((Y - y1) / (y3 - y1))); if xe < xs then begin X := xs; xs := xe; xe := X; end; for X := xs to xe - 1 do begin n := NormalToTangentSpace(NormalMap[X + Y * Width], X, Y, x1, y1, x2, y2, x3, y3, m1, m2, m3); NormalizeVector(n); n.X := -n.X; NormalMap[X + Y * Width] := n; end; end; if y2 < y3 then for Y := y2 + 1 to y3 do begin xs := Round(x2 + (x3 - x2) * ((Y - y2) / (y3 - y2))); xe := Round(x1 + (x3 - x1) * ((Y - y1) / (y3 - y1))); if xe < xs then begin X := xs; xs := xe; xe := X; end; for X := xs to xe - 1 do begin n := NormalToTangentSpace(NormalMap[X + Y * Width], X, Y, x1, y1, x2, y2, x3, y3, m1, m2, m3); NormalizeVector(n); n.X := -n.X; NormalMap[X + Y * Width] := n; end; end; end; // Create the bitmap Result := TBitmap.Create; Result.Width := Width; Result.Height := Height; { TODO : E2129 Cannot assign to a read-only property } (* Result.PixelFormat:=glpf24bit; *) // Paint bitmap with normal map normals (X,Y,Z) -> (R,G,B) for i := 0 to NormalMap.Count - 1 do { TODO : E2003 Undeclared identifier: 'Pixels' } (* Result.Canvas.Pixels[i mod Width, i div Height]:=ConvertNormalToColor(NormalMap[i]); *) NormalMap.Free; end; end.
unit indyhttpclientbroker; {$mode objfpc}{$H+} interface uses Classes, SysUtils, basehttpclient, IdHTTP, IdMultipartFormData, IdSSL, IdSSLOpenSSL; type { TIndyHTTPClient } TIndyHTTPClient = class(TBaseHTTPClient) private FCookies: TStrings; FHTTPClient: TIdHTTP; FIDSSL: TIdSSLIOHandlerSocketOpenSSL; FData: TIdMultiPartFormDataStream; FRequestHeaders: TStrings; FResponseHeaders: TStrings; protected function GetAllowRedirect: Boolean; override; function GetCookies: TStrings; override; function GetHTTPProxyHost: String; override; function GetHTTPProxyPassword: String; override; function GetHTTPProxyPort: Word; override; function GetHTTPProxyUsername: String; override; function GetInternalHTTPClient: TObject; override; function GetRequestHeaders: TStrings; override; function GetResponseHeaders: TStrings; override; function GetResponseStatusCode: Integer; override; function GetResponseStatusText: String; override; procedure SetAllowRedirect(AValue: Boolean); override; procedure SetCookies(AValue: TStrings); override; procedure SetHTTPProxyHost(AValue: String); override; procedure SetHTTPProxyPassword(AValue: String); override; procedure SetHTTPProxyPort(AValue: Word); override; procedure SetHTTPProxyUsername(AValue: String); override; procedure SetRequestHeaders(AValue: TStrings); override; public procedure AddHeader(const AHeader, AValue: String); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function EncodeUrlElement(S: String): String; override; function FormPost(const URL: string; FormData: TStrings): String; override; function Get(const AUrl: String): String; override; end; implementation uses IdURI, IdException ; { TIndyHTTPClient } procedure TIndyHTTPClient.AddHeader(const AHeader, AValue: String); begin FRequestHeaders.Add(AHeader+': '+AValue); end; constructor TIndyHTTPClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FHTTPClient:=TIdHTTP.Create; FIDSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil); FHTTPClient.IOHandler:=FIDSSL; FIDSSL.ConnectTimeout:=10000; FIDSSL.ReadTimeout:=16000; FHTTPClient.ReadTimeout:=16000; FHTTPClient.ConnectTimeout:=10000; // FHTTPClient.CookieManager:=TIdCookieManager.Create(nil); FRequestHeaders:=TStringList.Create; FRequestHeaders.NameValueSeparator:=':'; FResponseHeaders:=TStringList.Create; FResponseHeaders.NameValueSeparator:=':'; FCookies:=TStringList.Create; end; destructor TIndyHTTPClient.Destroy; begin FreeAndNil(FCookies); FreeAndNil(FIDSSL); FreeAndNil(FData); // FHTTPClient.CookieManager.Free; // FHTTPClient.CookieManager:=nil; FreeAndNil(FResponseHeaders); FreeAndNil(FRequestHeaders); FreeAndNil(FHTTPClient); inherited Destroy; end; class function TIndyHTTPClient.EncodeUrlElement(S: String): String; begin Result:=TIdURI.URLEncode(S); end; function TIndyHTTPClient.FormPost(const URL: string; FormData: TStrings ): String; var i: Integer; AData: TIdMultiPartFormDataStream; begin // FHTTPClient.Document.Clear; FHTTPClient.Request.CustomHeaders.AddStrings(FRequestHeaders); FResponseHeaders.Clear; AData:=TIdMultiPartFormDataStream.Create; try for i:=0 to FormData.Count-1 do FData.AddFormField(FormData.Names[i], FormData.ValueFromIndex[i]); Result:=FHTTPClient.Post(URL, FData); finally FreeAndNil(AData); end; if FHTTPClient.ResponseCode=200 then begin FResponseHeaders.AddStrings(FHTTPClient.Response.CustomHeaders, True); {$IFDEF DEBUG}FResponseHeaders.SaveToFile('~ResponseHeaders.txt');{$ENDIF} end else begin Result:=EmptyStr; end; end; function TIndyHTTPClient.Get(const AUrl: String): String; begin FHTTPClient.Request.CustomHeaders.AddStrings(FRequestHeaders); FResponseHeaders.Clear; try try Result:=FHTTPClient.Get(AUrl); except on E: EIdException do raise EHTTPClient.Create(E.ClassName+': '+E.Message); end; finally if FHTTPClient.ResponseCode=200 then begin FResponseHeaders.AddStrings(FHTTPClient.Response.CustomHeaders, True); {$IFDEF DEBUG}FResponseHeaders.SaveToFile('~ResponseHeaders.txt');{$ENDIF} end else Result:=EmptyStr; end; end; function TIndyHTTPClient.GetAllowRedirect: Boolean; begin Result:=FHTTPClient.HandleRedirects; end; function TIndyHTTPClient.GetCookies: TStrings; begin Result:=FCookies; end; function TIndyHTTPClient.GetHTTPProxyHost: String; begin Result:=FHTTPClient.ProxyParams.ProxyServer; end; function TIndyHTTPClient.GetHTTPProxyPassword: String; begin Result:=FHTTPClient.ProxyParams.ProxyPassword; end; function TIndyHTTPClient.GetHTTPProxyPort: Word; begin Result:=FHTTPClient.ProxyParams.ProxyPort; end; function TIndyHTTPClient.GetHTTPProxyUsername: String; begin Result:=FHTTPClient.ProxyParams.ProxyUsername; end; function TIndyHTTPClient.GetInternalHTTPClient: TObject; begin Result:=FHTTPClient; end; function TIndyHTTPClient.GetRequestHeaders: TStrings; begin Result:=FRequestHeaders; end; function TIndyHTTPClient.GetResponseHeaders: TStrings; begin Result:=FResponseHeaders; end; function TIndyHTTPClient.GetResponseStatusCode: Integer; begin Result:=FHTTPClient.ResponseCode; end; function TIndyHTTPClient.GetResponseStatusText: String; begin Result:=FHTTPClient.ResponseText; end; procedure TIndyHTTPClient.SetAllowRedirect(AValue: Boolean); begin FHTTPClient.HandleRedirects:=AValue; end; procedure TIndyHTTPClient.SetCookies(AValue: TStrings); begin FCookies.AddStrings(AValue, True); end; procedure TIndyHTTPClient.SetHTTPProxyHost(AValue: String); begin FHTTPClient.ProxyParams.ProxyServer:=AValue; end; procedure TIndyHTTPClient.SetHTTPProxyPassword(AValue: String); begin FHTTPClient.ProxyParams.ProxyPassword:=AValue; end; procedure TIndyHTTPClient.SetHTTPProxyPort(AValue: Word); begin FHTTPClient.ProxyParams.ProxyPort:=AValue; end; procedure TIndyHTTPClient.SetHTTPProxyUsername(AValue: String); begin FHTTPClient.ProxyParams.ProxyUsername:=AValue; end; procedure TIndyHTTPClient.SetRequestHeaders(AValue: TStrings); begin FRequestHeaders.Assign(AValue); end; end.
unit RGBALongDataSet; interface uses LongDataSet; type TRGBALongDataSet = class (TLongDataSet) private FLength : integer; // Gets function GetData(_pos: integer): longword; reintroduce; function GetRed(_pos: integer): longword; function GetGreen(_pos: integer): longword; function GetBlue(_pos: integer): longword; function GetAlpha(_pos: integer): longword; // Sets procedure SetData(_pos: integer; _data: longword); reintroduce; procedure SetRed(_pos: integer; _data: longword); procedure SetGreen(_pos: integer; _data: longword); procedure SetBlue(_pos: integer; _data: longword); procedure SetAlpha(_pos: integer; _data: longword); protected // Gets function GetDataLength: integer; override; function GetLength: integer; override; function GetLast: integer; override; // Sets procedure SetLength(_size: integer); override; public // properties property Data[_pos: integer]:longword read GetData write SetData; property Red[_pos: integer]:longword read GetRed write SetRed; property Green[_pos: integer]:longword read GetGreen write SetGreen; property Blue[_pos: integer]:longword read GetBlue write SetBlue; property Alpha[_pos: integer]:longword read GetAlpha write SetAlpha; end; implementation // Gets function TRGBALongDataSet.GetData(_pos: integer): longword; begin Result := FData[_pos]; end; function TRGBALongDataSet.GetRed(_pos: integer): longword; begin Result := FData[4*_pos]; end; function TRGBALongDataSet.GetGreen(_pos: integer): longword; begin Result := FData[(4*_pos)+1]; end; function TRGBALongDataSet.GetBlue(_pos: integer): longword; begin Result := FData[(4*_pos)+2]; end; function TRGBALongDataSet.GetAlpha(_pos: integer): longword; begin Result := FData[(4*_pos)+3]; end; function TRGBALongDataSet.GetLength: integer; begin Result := FLength; end; function TRGBALongDataSet.GetDataLength: integer; begin Result := High(FData) + 1; end; function TRGBALongDataSet.GetLast: integer; begin Result := FLength - 1; end; // Sets procedure TRGBALongDataSet.SetData(_pos: integer; _data: longword); begin FData[_pos] := _data; end; procedure TRGBALongDataSet.SetRed(_pos: integer; _data: longword); begin FData[4*_pos] := _data; end; procedure TRGBALongDataSet.SetGreen(_pos: integer; _data: longword); begin FData[(4*_pos)+1] := _data; end; procedure TRGBALongDataSet.SetBlue(_pos: integer; _data: longword); begin FData[(4*_pos)+2] := _data; end; procedure TRGBALongDataSet.SetAlpha(_pos: integer; _data: longword); begin FData[(4*_pos)+3] := _data; end; procedure TRGBALongDataSet.SetLength(_size: Integer); begin FLength := _size; System.SetLength(FData,_size*4); end; end.
unit uMainSrv; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ScktComp, StdCtrls, RXShell, Menus, IniFiles, uCommon, ImgList; type TfMain = class(TForm) sktServidor: TServerSocket; TrayIcon: TRxTrayIcon; PopupMenu: TPopupMenu; N1: TMenuItem; Sair1: TMenuItem; Pausar1: TMenuItem; Continuar1: TMenuItem; ImageList: TImageList; procedure Sair1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TrayIconDblClick(Sender: TObject); procedure Continuar1Click(Sender: TObject); procedure Pausar1Click(Sender: TObject); procedure sktServidorClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure TrayIconMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure sktServidorClientConnect(Sender: TObject; Socket: TCustomWinSocket); private { Private declarations } TodasApp: TStringList; NomeArquivoINI: string; procedure AtivarServidor; procedure SuspenderServidor; function GetAppInfo(FName: string; SectionName: string): TAppInfo; procedure UpdateHint; procedure TrataErro(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); public { Public declarations } end; var fMain: TfMain; implementation {$R *.DFM} procedure TfMain.FormCreate(Sender: TObject); var ArquivoINI: TIniFile; Porta: integer; begin // Recupera (ou grava) as configuracoes num arquivo .INI NomeArquivoINI := ChangeFileExt(ParamStr(0), '.INI'); ArquivoINI := TIniFile.Create(NomeArquivoINI); // Le as configuracoes do servidor Porta := ArquivoINI.ReadInteger('Geral', 'Porta', -1); if Porta = -1 then begin Porta := SRV_PORTA; ArquivoINI.WriteInteger('Geral', 'Porta', Porta); end; // carrega a lista com as aplicacoes atendidas (todas as secoes menos GERAL) TodasApp := TStringList.Create; ArquivoINI.ReadSections(TodasApp); TodasApp.Delete(TodasApp.IndexOf('Geral')); // fecha o arquivo .INI ArquivoINI.Free; // configura o servidor sktServidor.Close; sktServidor.Port := Porta; sktServidor.Open; // exibe o icone correto ImageList.GetIcon(0, TrayIcon.Icon); end; procedure TfMain.TrataErro(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin // para evitar mensagens de erro no servidor // desenvolver depois uma rotina de "log de erros" case ErrorCode of SKT_ERR_RESET_BY_PEER: Socket.Close; end; ErrorCode := 0; Application.ProcessMessages; end; procedure TfMain.sktServidorClientConnect(Sender: TObject; Socket: TCustomWinSocket); begin Socket.OnErrorEvent := TrataErro; end; procedure TfMain.AtivarServidor; begin // reinicia a execucao do servidor sktServidor.Open; // atualiza as opcoes de menu Pausar1.Enabled := True; Pausar1.Default := True; Continuar1.Enabled := False; // exibe o icone correto ImageList.GetIcon(0, TrayIcon.Icon); end; procedure TfMain.SuspenderServidor; begin // suspende execucao do servidor sktServidor.Close; // atualiza as opcoes de menu Pausar1.Enabled := False; Continuar1.Enabled := True; Continuar1.Default := True; // exibe o icone correto ImageList.GetIcon(1, TrayIcon.Icon); end; procedure TfMain.Continuar1Click(Sender: TObject); begin AtivarServidor; end; procedure TfMain.Pausar1Click(Sender: TObject); begin SuspenderServidor; end; procedure TfMain.TrayIconDblClick(Sender: TObject); begin if sktServidor.Active then SuspenderServidor else AtivarServidor; end; procedure TfMain.Sair1Click(Sender: TObject); begin // desativa o servidor sktServidor.Close; Close; end; procedure TfMain.sktServidorClientRead(Sender: TObject; Socket: TCustomWinSocket); var Buffer: string; MsgLen, LenReceived: integer; Header: TMsgHeader; AppInfo: TAppInfo; begin // tamanho aproximado da mensagem MsgLen := Socket.ReceiveLength; // prepara o tamanho do buffer e recebe a mensagem em si SetLength(Buffer, MsgLen); LenReceived := Socket.ReceiveBuf(Buffer[1], MsgLen); // ajusta para o numero correto de bytes Buffer := Copy(Buffer, 1, LenReceived); // verifica validade da mensagem (no minimo eh um cabecalho vazio, sem dados) if Length(Buffer) < SizeOf(Header) then // fecha conexao, provavelmente nao eh o cliente correto! Socket.Close else begin // extrai o cabecalho da mensagem Move(Buffer[1], Header, SizeOf(Header)); Delete(Buffer, 1, SizeOf(Header)); // procura a aplicacao solicitada entre as atendidas if TodasApp.IndexOf(Buffer) < 0 then SendError(Socket, MSG_ERR_APP_NOT_FOUND) else begin // carrega os dados da aplicacao AppInfo := GetAppInfo(NomeArquivoINI, Buffer); // age de acordo com o TIPO de mensagem recebida case Header.MsgKind of MSG_REQUEST_APP_INFO: SendInfo(Socket, AppInfo); MSG_REQUEST_FILE : SendFile(Socket, AppInfo.Arquivo); else SendError(Socket, MSG_ERR_ILLEGAL_CODE); end; end; end; end; function TfMain.GetAppInfo(FName: string; SectionName: string): TAppInfo; var ArquivoINI: TIniFile; begin // abre o arquivo .INI ArquivoINI := TIniFile.Create(FName); // carrega os dados da aplicacao mandada como parametro (nome da secao) with ArquivoINI do begin Result.Nome := ReadString(SectionName, 'Aplicacao', NO_DATA); Result.Arquivo := ReadString(SectionName, 'Arquivo', NO_DATA); Result.Versao := DataArquivo(Result.Arquivo); Result.Status := ReadString(SectionName, 'Status', '0'); Result.Comment := ReadString(SectionName, 'Comment', ''); end; end; procedure TfMain.UpdateHint; var s: string; begin if not sktServidor.Active then s := 'Suspenso' else begin case sktServidor.Socket.ActiveConnections of 0: s := 'Ocioso'; 1: s := '1 usuário'; else s := Format('%d usuários', [sktServidor.Socket.ActiveConnections]); end; end; TrayIcon.Hint := Application.Title + ' (' + s + ')'; end; procedure TfMain.TrayIconMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin // atualiza os Hints UpdateHint; end; end.
Function BooleanToString (Value : LongBool) : String; Begin Result := 'True'; If Value = True Then Result := 'True' Else Result := 'False'; End; {..................................................................................................} {..................................................................................................} Procedure ReportClientServerInterfaces; Var CSData : TStringList; I,J,K,L,M : Integer; FileName : AnsiString; ReportDocument : IServerDocument; RecordCount : Integer; ServerRecord : IServerRecord; OwnerDocument : IServerDocument; CurrentView : IServerDocumentView; WindowKind : IServerWindowKind; ServerProcess : IServerProcess; ServerPanelInfo : IServerPanelInfo; Begin If Client = Nil Then Exit; CSData := TStringList.Create; Try CSData.Add('Client Interface information:'); CSData.Add('============================='); CSData.Add(''); CSData.Add('Application Handle ' + IntToStr(Client.ApplicationHandle)); CSData.Add('Main Window Handle ' + IntToStr(Client.MainWindowHandle)); // Log(' CommandLauncher',Client.CommandLauncher); CSData.Add(''); CurrentView := Client.CurrentView; If CurrentView <> Nil Then Begin OwnerDocument := Client.CurrentView.OwnerDocument; CSData.Add('Current Document View''s server ' + OwnerDocument.ServerModule.ModuleName); CSData.Add('Current Document View Name ' + CurrentView.ViewName); // Log('Current Document View Kind ' ,CurrentView.Kind); CSData.Add('Current Document View Caption ' + CurrentView.Caption); End; CSData.Add(''); CSData.Add('Current process depth ' + IntToStr(Client.ProcessControl.ProcessDepth)); CSData.Add('Status Bar Index 0 ' + Client.GUIManager.StatusBar_GetState(0)); CSData.Add(''); K := Client.Count; CSData.Add('Number of active servers in DXP : ' + IntToStr(K)); // number of servers. For K := 0 to K - 1 Do CSData.Add('Server module name' + Client.ServerModule[K].ModuleName); CSData.Add(''); RecordCount := Client.GetServerRecordCount; CSData.Add(' Server Record Count : ' + IntToStr(RecordCount)); CSData.Add(' ========================='); CSData.Add(''); For I := 0 to RecordCount - 1 Do Begin ServerRecord := Client.GetServerRecord(I); CSData.Add(' Server Name = ' + ServerRecord.GetName + ' #' + IntToStr(I + 1)); CSData.Add(' ==============================================================='); CSData.Add(' Server Version ' + ServerRecord.GetVersion); CSData.Add(' Server Copyright info ' + ServerRecord.GetCopyRight); CSData.Add(' Server Date ' + ServerRecord.GetDate); CSData.Add(' Server Info ' + ServerRecord.GetGeneralInfo); CSData.Add(' DDB Read Supported? ' + BooleanToString(ServerRecord.GetSupportsDDBRead)); CSData.Add(' DDB Write Supported? ' + BooleanToString(ServerRecord.GetSupportsDDBWrite)); CSData.Add(' System Extension? ' + BooleanToString(ServerRecord.GetSystemExtension)); CSData.Add(' INS Path ' + ServerRecord.GetInsPath); CSData.Add(' RCS path ' + ServerRecord.GetRCSFilePath); CSData.Add(' Description ' + ServerRecord.GetDescription); CSData.Add(' Server File Exists? ' + BooleanToString(ServerRecord.GetServerFileExist)); CSData.Add(' Is server a document wizard? ' + BooleantoString(ServerRecord.GetIsDocumentWizard)); // Infomration about WIndow Kinds CSData.Add(' Number of document types ' + IntToStr(ServerRecord.GetWindowKindCount)); For J := 0 to ServerRecord.GetWindowKindCount - 1 Do Begin WindowKind := ServerRecord.GetWindowKind(J); CSData.Add(' Window Kind Name ' + WindowKind.GetName); CSData.Add(' New Window Caption ' + WindowKind.GetNewWindowCaption); CSData.Add(' New Window Extension ' + WindowKind.GetNewWindowExtension); CSData.Add(' Window Kind Description ' + WindowKind.GetWindowKindDescription); CSData.Add(' Icon Name ' + WindowKind.GetIconName); CSData.Add(' Is Domain? ' + BooleanToString(WindowKind.GetIsDomain)); CSData.Add(' Is Document Editor? ' + BooleanToString(WindowKind.GetIsDocumentEditor)); CSData.Add(''); CSData.Add(' Window Kind Class Count ' + IntToStr(WindowKind.GetWindowKindClassCount)); For L := 0 to WindowKind.GetWindowKindClassCount - 1 Do CSData.Add(' Window Kind Class ' + WindowKind.GetWindowKindClass(L)); CSData.Add(''); End; // Information about commands CSData.Add(' Number of commands ' + IntToStr(ServerRecord.GetCommandCount)); For J := 0 to ServerRecord.GetCommandCount - 1 Do Begin // IServerProcess = Server's commands ServerProcess := ServerRecord.GetCommand(J); CSData.Add(' Original Command Id: ' + ServerProcess.GetOriginalId); CSData.Add(' Get Long Summary: ' + ServerProcess.GetLongSummary); For M := 0 to ServerProcess.GetParameterCount - 1 Do CSData.Add(' Server Parameter' + ServerProcess.GetParameter(M)); CSData.Add(''); End; // Informaiton about panels CSData.Add(' Number of Panels ' + IntToStr(ServerRecord.GetPanelInfoCount)); For J := 0 to ServerRecord.GetPanelInfoCount - 1 Do Begin // IServerPanelInfo ServerPanelInfo := ServerRecord.GetPanelInfo(J); CSData.Add(' Panel Name ' + ServerPanelInfo.GetName); CSData.Add(' Panel Category ' + ServerPanelInfo.GetCategory); CSData.Add(' Panel Bitmap ' + ServerPanelInfo.GetBitmap); CSData.Add(' Panel Hot Key ' + ServerPanelInfo.GetHotkey); CSData.Add(' Panel Button Visible ' + BooleanToString(ServerPanelInfo.GetButtonVisible)); CSData.Add(' Panel Multiple Creation ' + BooleanToString(ServerPanelInfo.GetMultipleCreation)); CSData.Add(' Panel Creation Class Name ' + ServerPanelInfo.GetCreationClassName); CSData.Add(' Panel Dock Vertical? ' + BooleanToString(ServerPanelInfo.GetCanDockVertical)); CSData.Add(' Panel Dock Horizontal? ' + BooleanToString(ServerPanelInfo.GetCanDockHorizontal)); CSData.Add(''); End; CSData.Add(' ====================================='); CSData.Add(''); End; FileName := SpecialFolder_MyDesigns + '\Project_Report.Txt'; Finally CSData.SaveToFile(FileName); CSData.Free; End; ReportDocument := Client.OpenDocument('Text', FileName); If ReportDocument <> Nil Then Client.ShowDocument(ReportDocument); End; {..................................................................................................} {..................................................................................................}
unit UProduto; interface uses classes; type TProduto = class (TObject) protected FIdProduto:String; FCodBarrasProduto:String; FDescricaoProduto:string; FQtdeProduto:Double; FValorVendaProduto:Double; FValorCompra:Double; FMarca:String; FModelo:String; FIPI:Double; FICMS:Double; FLocalizacao:String; FTipoMedida:String; FObs:String; public constructor Criar; destructor Destroy; procedure setIdProduto(vIdProduto:String); procedure setCodBarrasProduto(vCodBarrasProduto:String); procedure setDescricaoProduto(vDescricaoProduto:String); procedure setValorVendaProduto(vValorVendaProduto:Double); procedure setQtdeProduto(vQtdeProduto:Double); procedure setValorCompra(vValorCompra:Double); procedure setMarca(vMarca:String); procedure setModelo(vModelo:String); procedure setIPI(vIPI:Double); procedure setICMS(vICMS:Double); procedure setLocalizacao(vLocalizacao:String); procedure setTipoMedida(vTipoMedida:String); procedure setObs(vObs:String); function getIdProduto:String; function getCodBarrasProduto:String; function getDescricaoProduto:String; function getValorvendaProduto:Double; function getQtdeProduto:Double; function getObs:String; function getValorCompra:Double; function getMarca:String; function getModelo:String; function getIPI:Double; function getICMS:Double; function getLocalizacao:String; function getTipoMedida:String; property IdProduto:String read getIdProduto write setIdProduto; property CodBarrasProduto:String read getCodBarrasProduto write setCodBarrasProduto; property DescricaoProduto:String read getDescricaoProduto write setDescricaoProduto; property ValorVendaProduto:Double read getValorVendaProduto write setValorVendaProduto; property QtdeProduto:Double read getQtdeProduto write setQtdeProduto; property ValorCompra:Double read getValorCompra write setValorCompra ; property Marca:String read getMarca write setMarca; property Modelo:String read getModelo write setModelo; property IPI:Double read getIPI write setIPI; property ICMS:Double read getICMS write setICMS; property Localizacao:String read getLocalizacao write setLocalizacao; property TipoMedida:String read getTipoMedida write setTipoMedida; property Obs:String read getObs write setObs; end; implementation { TProduto } constructor TProduto.Criar; begin FIdProduto:= ''; FCodBarrasProduto:=''; FDescricaoProduto:=''; FQtdeProduto:=0; FValorVendaProduto:=0; FValorCompra:=0; FMarca:=''; FModelo:=''; FIPI:=0; FICMS:=0; FLocalizacao:=''; FTipoMedida:=''; FObs:=''; end; destructor TProduto.Destroy; begin end; function TProduto.getCodBarrasProduto: String; begin Result:= FCodBarrasProduto; end; function TProduto.getDescricaoProduto: String; begin Result:= FDescricaoProduto; end; function TProduto.getICMS: Double; begin Result:=FICMS; end; function TProduto.getIdProduto: String; begin Result:= FIdProduto; end; function TProduto.getIPI: Double; begin Result:= FIPI; end; function TProduto.getLocalizacao: String; begin Result:=FLocalizacao; end; function TProduto.getMarca: String; begin Result:=FMarca; end; function TProduto.getModelo: String; begin Result:=FModelo; end; function TProduto.getObs: String; begin Result:=FObs; end; function TProduto.getQtdeProduto: Double; begin Result:= FQtdeProduto; end; function TProduto.getTipoMedida: String; begin Result:=FTipoMedida; end; function TProduto.getValorCompra: Double; begin Result:=FValorCompra; end; function TProduto.getValorvendaProduto: Double; begin Result:= FValorVendaProduto; end; procedure TProduto.setCodBarrasProduto(vCodBarrasProduto: String); begin FCodBarrasProduto:= vCodBarrasProduto; end; procedure TProduto.setDescricaoProduto(vDescricaoProduto: String); begin FDescricaoProduto:= vDescricaoProduto; end; procedure TProduto.setICMS(vICMS: Double); begin FICMS:= vICMS; end; procedure TProduto.setIdProduto(vIdProduto: String); begin FIdProduto:= vIdProduto; end; procedure TProduto.setIPI(vIPI: Double); begin FIPI:=vIPI; end; procedure TProduto.setLocalizacao(vLocalizacao: String); begin FLocalizacao:=vLocalizacao; end; procedure TProduto.setMarca(vMarca: String); begin FMarca:=vMarca; end; procedure TProduto.setModelo(vModelo: String); begin FModelo:=vModelo; end; procedure TProduto.setObs(vObs: String); begin FObs:=vObs; end; procedure TProduto.setQtdeProduto(vQtdeProduto: Double); begin FQtdeProduto:= vQtdeProduto; end; procedure TProduto.setTipoMedida(vTipoMedida: String); begin FTipoMedida:=vTipoMedida; end; procedure TProduto.setValorCompra(vValorCompra: Double); begin FValorCompra:=vValorCompra; end; procedure TProduto.setValorVendaProduto(vValorVendaProduto: Double); begin FValorVendaProduto:=vValorVendaProduto; end; end.
//------------------------------------------------------------------------------ //LuaVarConstants UNIT //------------------------------------------------------------------------------ // What it does- // Used in lua script for getvar function. // // Changes - // [2007/12/30] Aeomin - Created. // //------------------------------------------------------------------------------ unit LuaVarConstants; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface const // 0 is reserved for default string based getvar. VAR_SPEED = 1; VAR_EXP = 2; VAR_JOBEXP = 3; VAR_VIRTUE = 4; VAR_HONOR = 5; VAR_HP = 6; VAR_MAXHP = 7; VAR_SP = 8; VAR_MAXSP = 9; VAR_POINT = 10; VAR_HAIRCOLOR = 11; VAR_CLEVEL = 12; VAR_SPPOINT = 13; VAR_STR = 14; VAR_AGI = 15; VAR_VIT = 16; VAR_INT = 17; VAR_DEX = 18; VAR_LUK = 19; VAR_JOB = 20; VAR_MONEY = 21; VAR_SEX = 22; VAR_MAXEXP = 23; VAR_MAXJOBEXP = 24; VAR_WEIGHT = 25; VAR_MAXWEIGHT = 26; VAR_POISON = 27; VAR_STONE = 28; VAR_CURSE = 29; VAR_FREEZING = 30; VAR_SILENCE = 31; VAR_CONFUSION = 32; VAR_STANDARD_STR = 33; VAR_STANDARD_AGI = 34; VAR_STANDARD_VIT = 35; VAR_STANDARD_INT = 36; VAR_STANDARD_DEX = 37; VAR_STANDARD_LUK = 38; VAR_ATTACKMT = 39; VAR_ATTACKEDMT = 40; VAR_NV_BASIC = 41; VAR_ATTPOWER = 42; VAR_REFININGPOWER = 43; VAR_MAX_MATTPOWER = 44; VAR_MIN_MATTPOWER = 45; VAR_ITEMDEFPOWER = 46; VAR_PLUSDEFPOWER = 47; VAR_MDEFPOWER = 48; VAR_PLUSMDEFPOWER = 49; VAR_HITSUCCESSVALUE = 50; VAR_AVOIDSUCCESSVALUE = 51; VAR_PLUSAVOIDSUCCESSVALUE = 52; VAR_CRITICALSUCCESSVALUE = 53; VAR_ASPD = 54; VAR_PLUSASPD = 55; VAR_JOBLEVEL = 56; VAR_ACCESSORY2 = 57; VAR_ACCESSORY3 = 58; VAR_HEADPALETTE = 59; VAR_BODYPALETTE = 60; VAR_SHIELD = 61; VAR_CURXPOS = 62; VAR_CURYPOS = 63; VAR_CURDIR = 64; VAR_CHARACTERID = 65; VAR_ACCOUNTID = 66; VAR_MAPID = 67; VAR_MAPNAME = 68; VAR_ACCOUNTNAME = 69; VAR_CHARACTERNAME = 70; VAR_ITEM_COUNT = 71; VAR_ITEM_ITID = 72; VAR_ITEM_SLOT1 = 73; VAR_ITEM_SLOT2 = 74; VAR_ITEM_SLOT3 = 75; VAR_ITEM_SLOT4 = 76; VAR_HEAD = 77; VAR_WEAPON = 78; VAR_ACCESSORY = 79; VAR_STATE = 80; VAR_MOVEREQTIME = 81; VAR_GROUPID = 82; VAR_ATTPOWERPLUSTIME = 83; VAR_ATTPOWERPLUSPERCENT = 84; VAR_DEFPOWERPLUSTIME = 85; VAR_DEFPOWERPLUSPERCENT = 86; VAR_DAMAGENOMOTIONTIME = 87; VAR_BODYSTATE = 88; VAR_HEALTHSTATE = 89; VAR_RESETHEALTHSTATE = 90; VAR_CURRENTSTATE = 91; VAR_RESETEFFECTIVE = 92; VAR_GETEFFECTIVE = 93; VAR_EFFECTSTATE = 94; VAR_SIGHTABILITYEXPIREDTIME = 95; VAR_SIGHTRANGE = 96; VAR_SIGHTPLUSATTPOWER = 97; VAR_STREFFECTIVETIME = 98; VAR_AGIEFFECTIVETIME = 99; VAR_VITEFFECTIVETIME = 100; VAR_INTEFFECTIVETIME = 101; VAR_DEXEFFECTIVETIME = 102; VAR_LUKEFFECTIVETIME = 103; VAR_STRAMOUNT = 104; VAR_AGIAMOUNT = 105; VAR_VITAMOUNT = 106; VAR_INTAMOUNT = 107; VAR_DEXAMOUNT = 108; VAR_LUKAMOUNT = 109; VAR_MAXHPAMOUNT = 110; VAR_MAXSPAMOUNT = 111; VAR_MAXHPPERCENT = 112; VAR_MAXSPPERCENT = 113; VAR_HPACCELERATION = 114; VAR_SPACCELERATION = 115; VAR_SPEEDAMOUNT = 116; VAR_SPEEDDELTA = 117; VAR_SPEEDDELTA2 = 118; VAR_PLUSATTRANGE = 119; VAR_DISCOUNTPERCENT = 120; VAR_AVOIDABLESUCCESSPERCENT = 121; VAR_STATUSDEFPOWER = 122; VAR_PLUSDEFPOWERINACOLYTE = 123; VAR_MAGICITEMDEFPOWER = 124; VAR_MAGICSTATUSDEFPOWER = 125; VAR_CLASS = 126; VAR_PLUSATTACKPOWEROFITEM = 127; VAR_PLUSDEFPOWEROFITEM = 128; VAR_PLUSMDEFPOWEROFITEM = 129; VAR_PLUSARROWPOWEROFITEM = 130; VAR_PLUSATTREFININGPOWEROFITEM = 131; VAR_PLUSDEFREFININGPOWEROFITEM = 132; VAR_IDENTIFYNUMBER = 133; VAR_ISDAMAGED = 134; VAR_ISIDENTIFIED = 135; VAR_REFININGLEVEL = 136; VAR_WEARSTATE = 137; VAR_ISLUCKY = 138; VAR_ATTACKPROPERTY = 139; VAR_STORMGUSTCNT = 140; VAR_MAGICATKPERCENT = 141; VAR_MYMOBCOUNT = 142; VAR_ISCARTON = 143; VAR_GDID = 144; VAR_NPCXSIZE = 145; VAR_NPCYSIZE = 146; VAR_RACE = 147; VAR_SCALE = 148; VAR_PROPERTY = 149; VAR_PLUSATTACKPOWEROFITEM_RHAND = 150; VAR_PLUSATTACKPOWEROFITEM_LHAND = 151; VAR_PLUSATTREFININGPOWEROFITEM_RHAND = 152; VAR_PLUSATTREFININGPOWEROFITEM_LHAND = 153; VAR_TOLERACE = 154; VAR_ARMORPROPERTY = 155; VAR_ISMAGICIMMUNE = 156; VAR_ISFALCON = 157; VAR_ISRIDING = 158; VAR_MODIFIED = 159; VAR_FULLNESS = 160; VAR_RELATIONSHIP = 161; VAR_ACCESSARY = 162; VAR_SIZETYPE = 163; VAR_SHOES = 164; VAR_STATUSATTACKPOWER = 165; VAR_BASICAVOIDANCE = 166; VAR_BASICHIT = 167; VAR_PLUSASPDPERCENT = 168; VAR_CPARTY = 169; VAR_ISMARRIED = 170; VAR_ISGUILD = 171; VAR_ISFALCONON = 172; VAR_ISPECOON = 173; VAR_ISPARTYMASTER = 174; VAR_ISGUILDMASTER = 175; VAR_BODYSTATENORMAL = 176; VAR_HEALTHSTATENORMAL = 177; VAR_STUN = 178; VAR_SLEEP = 179; VAR_UNDEAD = 180; VAR_BLIND = 181; VAR_BLOODING = 182; VAR_BSPOINT = 183; VAR_ACPOINT = 184; VAR_BSRANK = 185; VAR_ACRANK = 186; VAR_CHANGESPEED = 187; VAR_CHANGESPEEDTIME = 188; VAR_MAGICATKPOWER = 189; implementation end.
unit ufrmSearchSupplier; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, StdCtrls, ufraFooterDialog2Button, ExtCtrls, uConn, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, Vcl.Menus, cxButtons, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, System.Actions, Vcl.ActnList, ufraFooterDialog3Button; type TsearchFor = (sfProductSup, sfMasterSup); TfrmDialogSearchSupplier = class(TfrmMasterDialog) pnl1: TPanel; lbl1: TLabel; lbl2: TLabel; edtSupCode: TEdit; edtSupName: TEdit; pnl2: TPanel; cxGrid: TcxGrid; cxGridViewSearchSupplier: TcxGridDBTableView; cxGridViewSearchSupplierColumn1: TcxGridDBColumn; cxGridViewSearchSupplierColumn2: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; btnSearch: TcxButton; procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure edtSupCodeChange(Sender: TObject); procedure edtSupNameChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure strgGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtSupCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtSupNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FIsProcessSuccessfull: boolean; FSupplierCode: string; FSupplierName: string; data : TDataSet; procedure SetIsProcessSuccessfull(const Value: boolean); procedure FindDataOnGrid(AText: String); procedure SetSupplierCode(const Value: string); procedure SetSupplierName(const Value: string); procedure ParserGrid(jmlData: Integer); { Private declarations } public { Public declarations } searchFor: TsearchFor; published property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; property SupplierCode: string read FSupplierCode write SetSupplierCode; property SupplierName: string read FSupplierName write SetSupplierName; end; var frmDialogSearchSupplier: TfrmDialogSearchSupplier; implementation uses ufrmMain, ufrmProduct; {$R *.dfm} procedure TfrmDialogSearchSupplier.footerDialogMasterbtnSaveClick( Sender: TObject); begin //initiate SupplierCode := ''; SupplierName := ''; IsProcessSuccessfull := False; // if(strgGrid.Cells[0,strgGrid.Row])='' then Exit // else // begin // SupplierCode := strgGrid.Cells[0,strgGrid.Row]; // SupplierName := strgGrid.Cells[1,strgGrid.Row]; // IsProcessSuccessfull := True; // end; Close; end; procedure TfrmDialogSearchSupplier.SetIsProcessSuccessfull( const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogSearchSupplier.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogSearchSupplier.FormDestroy(Sender: TObject); begin inherited; frmDialogSearchSupplier := nil; end; procedure TfrmDialogSearchSupplier.FindDataOnGrid(AText: String); //var // resPoint: TPoint; begin if (AText <> '') then begin // resPoint := strgGrid.Find(Point(0,0),AText,[fnIncludeFixed]); // if (resPoint.Y <> -1) then // begin // strgGrid.ScrollInView(resPoint.X, resPoint.Y); // strgGrid.SelectRows(resPoint.Y, 1); // end; end; end; procedure TfrmDialogSearchSupplier.edtSupCodeChange(Sender: TObject); begin if Length(edtSupCode.Text) = 1 then begin // if not Assigned(SearchSupplier) then SearchSupplier := TSearchSupplier.Create; // // if searchFor = sfProductSup then // begin // data := SearchSupplier.GetListSup4ProductSupByCode // (frmMain.UnitId, frmProduct.edtMerchandCode.Text, edtSupCode.Text + '%'); // ParserGrid(data.RecordCount); // end // product sup // else if searchFor = sfMasterSup then // begin // data := SearchSupplier.GetListSup4MasterSupByCode(frmMain.UnitId, edtSupCode.Text + '%'); // ParserGrid(data.RecordCount); // end; // master sup end // length = 1 else FindDataOnGrid(edtSupCode.Text); end; procedure TfrmDialogSearchSupplier.edtSupNameChange(Sender: TObject); begin if Length(edtSupName.Text) = 1 then begin // if not Assigned(SearchSupplier) then SearchSupplier := TSearchSupplier.Create; if searchFor = sfProductSup then begin // data := SearchSupplier.GetListSup4ProductSupByName // (frmMain.UnitId, frmProduct.edtMerchandCode.Text, edtSupName.Text + '%'); ParserGrid(data.RecordCount); end // product sup else if searchFor = sfMasterSup then begin // data := SearchSupplier.GetListSup4MasterSupByName(frmMain.UnitId, edtSupName.Text + '%'); ParserGrid(data.RecordCount); end; // master sup end // length = 1 else FindDataOnGrid(edtSupName.Text); end; procedure TfrmDialogSearchSupplier.SetSupplierCode(const Value: string); begin FSupplierCode := Value; end; procedure TfrmDialogSearchSupplier.SetSupplierName(const Value: string); begin FSupplierName := Value; end; procedure TfrmDialogSearchSupplier.FormShow(Sender: TObject); //var i, countData : integer; begin {if not Assigned(SearchSupplier) then SearchSupplier := TSearchSupplier.Create; if searchFor = sfProductSup then data := SearchSupplier.GetListSupplier4ProductSup(frmMain.UnitId,frmProduct.edtGroupCode.Text) //modif by didit: edtMerchandCode->edtGroupCode else if searchFor = sfMasterSup then data := SearchSupplier.GetListSup4MasterSup(frmMain.UnitId); if data.RecordCount > 22 then countData := 22 else countData := data.RecordCount; with strgGrid do begin Clear; RowCount := countData + 1; ColCount := 2; Cells[0,0] := 'SUPPLIER CODE'; Cells[1,0] := 'SUPPLIER NAME'; if RowCount > 1 then begin i := 1; while not data.Eof do begin Cells[0, i] := data.FieldByName('SUP_CODE').AsString; Cells[1, i] := data.FieldByName('SUP_NAME').AsString; if searchFor = sfProductSup then begin Cells[2, i] := data.FieldByName('TOP').AsString; Cells[3, i] := data.FieldByName('SUB_CODE').AsString; end; if i > 22 then Exit; Inc(i); data.Next; end; end else begin RowCount := 2; Cells[0, 1] := ' '; Cells[1, 1] := ' '; Cells[2, 1] := '0'; Cells[3, 1] := '0'; end; AutoSize := true; end; edtSupCode.SetFocus; strgGrid.FixedRows := 1; } end; procedure TfrmDialogSearchSupplier.ParserGrid(jmlData: Integer); //var i: Integer; begin { with strgGrid do begin Clear; RowCount := jmlData + 1; ColCount := 2; Cells[0,0] := 'SUPPLIER CODE'; Cells[1,0] := 'SUPPLIER NAME'; if RowCount > 1 then begin i := 1; while not data.Eof do begin Cells[0, i] := data.FieldByName('SUP_CODE').AsString; Cells[1, i] := data.FieldByName('SUP_NAME').AsString; if searchFor = sfProductSup then begin Cells[2, i] := data.FieldByName('TOP').AsString; Cells[3, i] := data.FieldByName('SUB_CODE').AsString; end; Inc(i); data.Next; end; end else begin RowCount := 2; Cells[0, 1] := ' '; Cells[1, 1] := ' '; Cells[2, 1] := '0'; Cells[3, 1] := '0'; end; AutoSize := true; end; edtSupCode.SetFocus; strgGrid.FixedRows := 1; } end; procedure TfrmDialogSearchSupplier.strgGridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // if (Key = Ord(VK_UP)) then // if (strgGrid.Row = 1) then // begin // edtSupCode.SetFocus; // edtSupCode.SelectAll; // end; end; procedure TfrmDialogSearchSupplier.edtSupCodeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // if (Key = Ord(VK_DOWN)) then // strgGrid.SetFocus; end; procedure TfrmDialogSearchSupplier.edtSupNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // if (Key = Ord(VK_DOWN)) then // strgGrid.SetFocus; end; end.
//------------------------------------------------------------------------------ //TCPServerRoutines UNIT //------------------------------------------------------------------------------ // What it does- // Holds our Common Server Routines. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ unit TCPServerRoutines; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses IdTCPServer, CommClient; function ActivateServer(Name : string; var AServer : TIdTCPServer; SchedulerType : Byte = 0; ThreadPoolSize : Word = 0) : boolean; procedure DeActivateServer(const Name : String; var AServer : TIdTCPServer); function ActivateClient(var AClient : TInterClient) : Boolean; procedure DeActivateClient(var AClient : TInterClient); implementation uses SysUtils, IdException, Classes, Globals, Packets, Main, IdSchedulerOfThreadDefault, IdSchedulerOfThreadPool; //------------------------------------------------------------------------------ //ActivateServer FUNCTION //------------------------------------------------------------------------------ // What it does- // Activates a TCP server. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function ActivateServer(Name : string; var AServer : TIdTCPServer; SchedulerType : Byte = 0; ThreadPoolSize : Word = 0) : boolean; Const PORT_ERR = 'The %s port (%d) is in use. Please correct and restart.'; LOADING = ' **Activating %s Server Component'; LOADED = ' --%s Server Component Now Running'; begin if not Assigned(AServer) then begin AServer := TIdTCPServer.Create; end; //Set up the thread scheduler AServer.Scheduler.Free; case SchedulerType of 0 : begin //Create thread scheduler AServer.Scheduler := TIdSchedulerOfThreadDefault.Create(AServer); end; 1 : begin //create thread pool scheduler. AServer.Scheduler := TIdSchedulerOfThreadPool.Create(AServer); TIdSchedulerOfThreadPool(AServer.Scheduler).PoolSize := ThreadPoolSize; end; end; Result := true; Console.WriteLn(Format(LOADING, [Name])); try AServer.Active := True; except on EIdCouldNotBindSocket do begin Console.WriteLn(Format(PORT_ERR, [Name, AServer.DefaultPort])); Result := false; Exit; end; end; Console.WriteLn(Format(LOADED, [Name])); end;{ActivateServer} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DeActivateServer PROCEDURE //------------------------------------------------------------------------------ // What it does- // Deactivates a server. // // Changes - // December 22nd, 2006 - RaX - Created Header. // January 3rd, 2006 - Tsusai - Added console strings. // //------------------------------------------------------------------------------ procedure DeActivateServer(const Name : String; var AServer : TIdTCPServer); const TERMINATING = ' **Deactivating %s Server Component'; TERMINATED = ' --%s Server Component Offline'; begin If Assigned(AServer) then begin if AServer.Active then begin Console.WriteLn(Format(TERMINATING, [Name])); AServer.Active := false; end; AServer.Bindings.Clear; Console.WriteLn(Format(TERMINATED, [Name])); end; end;{DeActivateServer} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ActivateClient FUNCTION //------------------------------------------------------------------------------ // What it does- // Activates a client. // // Changes - // December 22nd, 2006 - RaX - Created Header. // January 14th, 2007 - Tsusai - Updated the Create call // //------------------------------------------------------------------------------ function ActivateClient(var AClient : TInterClient) : boolean; begin if not Assigned(AClient) then begin AClient := TInterClient.Create('Unknown','Unknown', true, MainProc.Options.ReconnectDelay); end; AClient.Active := true; Result := true; end;{ActivateClient} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DeactivateClient FUNCTION //------------------------------------------------------------------------------ // What it does- // Deactivates a client. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ procedure DeActivateClient(var AClient : TInterClient); begin If Assigned(AClient) then begin AClient.Active := false; end; end;{DeActivateClient} //------------------------------------------------------------------------------ end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFCE_RESOLUCAO] The MIT License Copyright: Copyright (C) 2014 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 NfceResolucaoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, NfcePosicaoComponentesVO; type TNfceResolucaoVO = class(TVO) private FID: Integer; FRESOLUCAO_TELA: String; FLARGURA: Integer; FALTURA: Integer; FIMAGEM_TELA: String; FIMAGEM_MENU: String; FIMAGEM_SUBMENU: String; FListaNfcePosicaoComponentesVO: TListaNfcePosicaoComponentesVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property ResolucaoTela: String read FRESOLUCAO_TELA write FRESOLUCAO_TELA; property Largura: Integer read FLARGURA write FLARGURA; property Altura: Integer read FALTURA write FALTURA; property ImagemTela: String read FIMAGEM_TELA write FIMAGEM_TELA; property ImagemMenu: String read FIMAGEM_MENU write FIMAGEM_MENU; property ImagemSubmenu: String read FIMAGEM_SUBMENU write FIMAGEM_SUBMENU; property ListaNfcePosicaoComponentesVO: TListaNfcePosicaoComponentesVO read FListaNfcePosicaoComponentesVO write FListaNfcePosicaoComponentesVO; end; TListaNfceResolucaoVO = specialize TFPGObjectList<TNfceResolucaoVO>; implementation constructor TNfceResolucaoVO.Create; begin inherited; FListaNfcePosicaoComponentesVO := TListaNfcePosicaoComponentesVO.Create; end; destructor TNfceResolucaoVO.Destroy; begin FreeAndNil(FListaNfcePosicaoComponentesVO); inherited; end; initialization Classes.RegisterClass(TNfceResolucaoVO); finalization Classes.UnRegisterClass(TNfceResolucaoVO); end.
unit ServerContainerUnit; interface uses System.SysUtils, System.Classes, Vcl.Dialogs, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSClientMetadata, Datasnap.DSHTTPServiceProxyDispatcher, Datasnap.DSProxyJavaAndroid, Datasnap.DSProxyJavaBlackBerry, Datasnap.DSProxyObjectiveCiOS, Datasnap.DSProxyCsharpSilverlight, Datasnap.DSProxyFreePascal_iOS, Datasnap.DSAuth, Datasnap.DSNames, uServerDSProvider, uServerPOS; type TServerContainer = class(TDataModule) DSServer: TDSServer; DSServerClass: TDSServerClass; procedure DataModuleCreate(Sender: TObject); procedure DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RegisterServerClasses; end; function DSServer: TDSServer; implementation {$R *.dfm} uses Winapi.Windows, uDSUtils, ServerMethodsUnit, uServerClasses; var FModule: TComponent; FDSServer: TDSServer; function DSServer: TDSServer; begin Result := FDSServer; end; constructor TServerContainer.Create(AOwner: TComponent); begin inherited; FDSServer := DSServer; end; procedure TServerContainer.DataModuleCreate(Sender: TObject); begin RegisterServerClasses; end; destructor TServerContainer.Destroy; begin inherited; FDSServer := nil; end; procedure TServerContainer.DSServerClassGetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := ServerMethodsUnit.TServerMethods; end; procedure TServerContainer.RegisterServerClasses; begin Assert(DSServer.Started = false, 'Server Active.' + #13 + 'Can''t add class to Active Server.'); TCustServerClass.Create(Self, DSServer, TTestMethod, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrud, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TDSProvider, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TDSReport, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TJSONCRUD, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TPOS, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDPOS, DSServerClass.LifeCycle); //custom class here : TCustServerClass.Create(Self, DSServer, TSuggestionOrder, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudSupplier, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudPO, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudDO, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudCNRecv, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudDNRecv, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudSettingApp, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudQuotation, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudAdjFaktur, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudBankCashOut, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDClaimFaktur, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudUpdatePOS, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudContrabonSales, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudCustomerInvoice, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudBarangHargaJual, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudKuponBotol, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDJurnal, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudCrazyPrice, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDBarang, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudPOTrader, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudTransferBarang, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCRUDDOTrader, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudBarcodeRequest, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudBankCashIN, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudReturTrader, DSServerClass.LifeCycle); TCustServerClass.Create(Self, DSServer, TCrudBarcodeUsage, DSServerClass.LifeCycle); end; initialization FModule := TServerContainer.Create(nil); finalization FModule.Free; end.
program lab8; uses graph; type {класс point по созданию точки на экране и его перемещению} point=object {координаты точки на экране} x,y:integer; {видимость точки на экране} visible:boolean; {конструктор create создания точки на экране} constructor create(a,b:integer); {виртуальный метод switchon для отображения точки на экране} procedure switchon; // virtual; {виртуальный метод switchoff для скрытия точки на экрана} procedure switchoff; //virtual; {метод move перемещения точки по экрану} procedure move(dx,dy:integer); virtual; end; {класс Rectangle по созданию прямоугольника на экране и его перемещению} Rectangle=object(point) {координаты второй точки прямоугольника} x2,y2:integer; {конструктор create создания прямоугольника на экране} constructor create(a,b,c,d:integer); {виртуальный метод switchon для отображения прямоугольника на экране} procedure switchon; //virtual; {виртуальный метод switchoff для скрытия прямоугольника на экранe} procedure switchoff;// virtual; {метод move перемещения прямоугольника по экрану} // procedure move(dx,dy:integer); //virtual; end; constructor point.create(a,b:integer); begin {задание x значения а} x:=a; {задание y значения b} y:=b; {задание visible значения false} visible:=false; end; procedure point.switchon; begin {задание visible значения true} visible:=true; {вызов процедуры putpixel с цветом white} putpixel(x,y,white); end; procedure point.switchoff; begin {задание visible значения false} visible:=false; {вызов процедуры putpixel с цветом фона black} putpixel(x,y,black); end; procedure point.move(dx,dy:integer); begin {задание visible значения false} switchoff; {перемещение х первой точки на dx} x:=x+dx; {перемещение y первой точки на dy} y:=y+dy; {задание visible значения true} switchon; end; constructor Rectangle.create(a,b,c,d:integer); begin {вызов метода create класса point} point.create(a,b); {задание координат x2,y2 2-ой точки значений c,d} x2:=c; y2:=d; {задание visible значения false} visible:=false; end; procedure Rectangle.switchon; begin {задание visible значения true} visible:=true; {установка цвета на blue} setcolor(blue); {отрисовка прямоугольника x,y,x2,y2} graph.Rectangle(x,y,x2,y2) end; procedure Rectangle.switchoff; begin {задание visible значения false} visible:=false; {установка цвета на black} setcolor(black); {отрисовка прямоугольника x,y,x2,y2} graph.Rectangle(x,y,x2,y2) end; // procedure Rectangle.move(dx,dy:integer); // begin // {задание visible значения false} // switchoff; // {перемещение х первой точки на dx} // x:=x+dx; // {перемещение y первой точки на dy} // y:=y+dy; // {перемещение х2 второй точки на dx} // x2:=x2+dx; // {перемещение y2 второй точки на dy} // y2:=y2+dy; // {задание visible значения true} // switchon; // end; var grdriver,grmode:integer; onepoint:point; oneRectangle:Rectangle; begin {задание grdriver значения detect} grdriver:=detect; {инициализация графического окна} initgraph(grdriver,grmode,''); {cоздание объекта onepoint в графическом окне} with onepoint do begin {вызов конструктора create класса point} create(150,150); {становится видимым после перемещения класса point} switchon; {enter} readln; {вызов метода move класса point} move(120,120); end; {enter} readln; {cоздание объекта oneRectangle в графическом окне} with oneRectangle do begin {вызов конструктора create класса Rectangle} create(150,200,450,350); {становится видимым после перемещения класса Rectangle} switchon; {enter} readln; {вызов метода move класса Rectangle} move(120,120); end; {enter} readln; closegraph; end.
unit fxBroker; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DateUtils, ORNet, ORFn, rMisc, ComCtrls, Buttons, ExtCtrls, ORCtrls, ORSystem, fBase508Form, VA508AccessibilityManager, Winapi.RichEdit; type TRpcRecord = record RpcName: String; UCallListIndex: Integer; ResultListIndex: Integer; RPCText: TStringList; end; TLogActions = (ShowFlag, ShowSearch); TfrmBroker = class(TfrmBase508Form) pnlTop: TORAutoPanel; lblMaxCalls: TLabel; txtMaxCalls: TCaptionEdit; cmdPrev: TBitBtn; cmdNext: TBitBtn; udMax: TUpDown; memData: TRichEdit; lblCallID: TStaticText; cmdSearch: TBitBtn; btnFlag: TBitBtn; btnRLT: TBitBtn; pnlMain: TPanel; PnlDebug: TPanel; SplDebug: TSplitter; PnlSearch: TPanel; lblSearch: TLabel; pnlSubSearch: TPanel; SearchTerm: TEdit; btnSearch: TButton; PnlDebugResults: TPanel; lblDebug: TLabel; ResultList: TListView; ScrollBox1: TScrollBox; procedure cmdPrevClick(Sender: TObject); procedure cmdNextClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormResize(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnRLTClick(Sender: TObject); procedure cmdSearchClick(Sender: TObject); procedure btnFlagClick(Sender: TObject); function FindPriorFlag: Integer; procedure btnSearchClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ResultListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure SearchTermChange(Sender: TObject); procedure SearchTermKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FRetained: Integer; FCurrent: Integer; fFlagRPC: Integer; fFlagDateTime: TDateTime; RPCArray: Array of TRpcRecord; RPCLogAction: TLogActions; procedure CloneRPCList(); procedure InitalizeCloneArray(); procedure HighlightRichEdit(StartChar, EndChar: Integer; HighLightColor: TColor); public { Public declarations } end; procedure ShowBroker; implementation const Flaghint = 'Mark any additional RPCs as flaged'; {$R *.DFM} procedure ShowBroker; var frmBroker: TfrmBroker; begin frmBroker := TfrmBroker.Create(Application); try ResizeAnchoredFormToFont(frmBroker); with frmBroker do begin FRetained := RetainedRPCCount - 1; FCurrent := FRetained; LoadRPCData(memData.Lines, FCurrent); fFlagRPC := FindPriorFlag; memData.SelStart := 0; lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); ShowModal; end; finally frmBroker.Release; end; end; procedure TfrmBroker.cmdPrevClick(Sender: TObject); begin FCurrent := HigherOf(FCurrent - 1, 0); LoadRPCData(memData.Lines, FCurrent); memData.SelStart := 0; lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); end; procedure TfrmBroker.cmdNextClick(Sender: TObject); begin FCurrent := LowerOf(FCurrent + 1, FRetained); LoadRPCData(memData.Lines, FCurrent); memData.SelStart := 0; lblCallID.Caption := 'Last Call Minus: ' + IntToStr(FRetained - FCurrent); end; procedure TfrmBroker.cmdSearchClick(Sender: TObject); begin if not PnlDebug.Visible then Width := Width + PnlDebug.Width + SplDebug.Width; PnlDebug.Visible := true; lblDebug.Caption := 'Search Results'; SplDebug.Visible := true; SplDebug.Left := PnlDebug.Width + 10; RPCLogAction := ShowSearch; PnlSearch.Visible := true; SearchTerm.SetFocus; InitalizeCloneArray; end; procedure TfrmBroker.FormClose(Sender: TObject; var Action: TCloseAction); begin SetRetainedRPCMax(StrToIntDef(txtMaxCalls.Text, 5)) end; procedure TfrmBroker.FormResize(Sender: TObject); begin Refresh; end; procedure TfrmBroker.FormCreate(Sender: TObject); begin udMax.Position := GetRPCMax; Width := Width - PnlDebug.Width + SplDebug.Width; end; procedure TfrmBroker.FormDestroy(Sender: TObject); Var I: integer; begin for I := Low(RPCArray) to High(RPCArray) do RPCArray[I].RPCText.Free; SetLength(RPCArray, 0); end; procedure TfrmBroker.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; procedure TfrmBroker.btnFlagClick(Sender: TObject); Var LastText: TStringList; LastRPCText: String; i: Integer; begin // flag by date if btnFlag.Tag = 1 then begin if fFlagRPC > -1 then SetRPCFlaged(''); btnFlag.Tag := 0; btnFlag.Caption := 'Flag'; end else begin LastText := TStringList.Create; try LoadRPCData(LastText, FRetained); for i := 0 to 2 do LastRPCText := LastRPCText + LastText.Strings[i] + #13#10; SetRPCFlaged(LastRPCText); fFlagDateTime := Now; btnFlag.Caption := 'Flag (set)'; // btnFlag.Hint := Flaghint + ' (after ' + FormatDateTime('hh:nn:ss.z a/p', fFlagDateTime) +')'; finally LastText.Free; end; end; end; procedure TfrmBroker.HighlightRichEdit(StartChar, EndChar: Integer; HighLightColor: TColor); var Format: CHARFORMAT2; begin memData.SelStart := StartChar; memData.SelLength := EndChar; // Set the background color FillChar(Format, SizeOf(Format), 0); Format.cbSize := SizeOf(Format); Format.dwMask := CFM_BACKCOLOR; Format.crBackColor := HighLightColor; memData.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format)); end; function TfrmBroker.FindPriorFlag: Integer; var i, ReturnCursor: Integer; StrToCheck, Temp: string; TextToCheck: TStringList; Found: Boolean; ListItem: TListItem; begin Result := -1; StrToCheck := GetRPCFlaged; if StrToCheck <> '' then begin TextToCheck := TStringList.Create; try for i := FRetained downto 0 do begin LoadRPCData(TextToCheck, i); if Pos(StrToCheck, TextToCheck.Text) > 0 then begin Result := i; break; end; end; finally TextToCheck.Free; end; if Result = -1 then SetRPCFlaged('') else begin Temp := Copy(StrToCheck, Pos('Ran at:', StrToCheck) + 7, Length(StrToCheck)); Temp := Trim(copy(Temp, 1, Pos(#10, Temp))); btnFlag.Caption := 'Flag (set)'; btnFlag.Tag := 1; // btnFlag.Hint := Flaghint + ' (after ' + Temp +')'; InitalizeCloneArray; RPCLogAction := ShowFlag; lblDebug.Caption := 'RPCs ran after ' + Temp; ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try PnlDebug.Visible := true; Width := Width + PnlDebug.Width + SplDebug.Width; SplDebug.Visible := true; PnlSearch.Visible := false; // Clear all ResultList.Clear; Found := false; for I := Low(RPCArray) to High(RPCArray) do begin RPCArray[I].ResultListIndex := -1; if I < Result then Continue; ListItem := ResultList.Items.Add; ListItem.Caption := IntToStr((RPCArray[I].UCallListIndex - RetainedRPCCount) + 1); ListItem.SubItems.Add(RPCArray[I].RpcName); RPCArray[I].ResultListIndex := ListItem.Index; if not Found then begin ResultList.Column[1].Width := -1; Found := True; end; end; finally Screen.Cursor := ReturnCursor; end; end; end; end; procedure TfrmBroker.btnRLTClick(Sender: TObject); var startTime, endTime: tDateTime; clientVer, serverVer, diffDisplay: string; theDiff: Integer; const TX_OPTION = 'OR CPRS GUI CHART'; disclaimer = 'NOTE: Strictly relative indicator:'; begin clientVer := clientVersion(Application.ExeName); // Obtain before starting. // Check time lapse between a standard RPC call: startTime := now; serverVer := serverVersion(TX_OPTION, clientVer); endTime := now; theDiff := milliSecondsBetween(endTime, startTime); diffDisplay := IntToStr(theDiff); // Show the results: infoBox('Lapsed time (milliseconds) = ' + diffDisplay + '.', disclaimer, MB_OK); end; procedure TfrmBroker.btnSearchClick(Sender: TObject); var I, ReturnCursor: Integer; Found: Boolean; ListItem: TListItem; begin ReturnCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try // Clear all ResultList.Clear; Found := false; for I := Low(RPCArray) to High(RPCArray) do begin RPCArray[I].ResultListIndex := -1; if Pos(UpperCase(SearchTerm.Text), UpperCase(RPCArray[I].RPCText.Text)) > 0 then begin ListItem := ResultList.Items.Add; ListItem.Caption := IntToStr((RPCArray[I].UCallListIndex - RetainedRPCCount) + 1); ListItem.SubItems.Add(RPCArray[I].RpcName); RPCArray[I].ResultListIndex := ListItem.Index; if not Found then begin ResultList.Column[1].Width := -1; Found := True; end; end; end; if not Found then ShowMessage('no matches found'); finally Screen.Cursor := ReturnCursor; end; end; procedure TfrmBroker.SearchTermChange(Sender: TObject); begin btnSearch.Enabled := (Trim(SearchTerm.Text) > ''); end; procedure TfrmBroker.SearchTermKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // inherited; if (Key = VK_RETURN) then btnSearchClick(Self); end; procedure TfrmBroker.CloneRPCList(); Var I: Integer; begin for I := 0 to RetainedRPCCount - 1 do begin SetLength(RPCArray, Length(RPCArray) + 1); RPCArray[High(RPCArray)].RPCText := TStringList.Create; try LoadRPCData(RPCArray[High(RPCArray)].RPCText, I); RPCArray[High(RPCArray)].RpcName := RPCArray[High(RPCArray)].RPCText[0]; RPCArray[High(RPCArray)].UCallListIndex := I; except RPCArray[High(RPCArray)].RPCText.Free; end; end; end; procedure TfrmBroker.InitalizeCloneArray(); begin if Length(RPCArray) = 0 then begin CloneRPCList; ResultList.Column[0].Width := -2; ResultList.Column[1].Width := -2; end; end; procedure TfrmBroker.ResultListSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); Var I: Integer; SearchString: string; CharPos, CharPos2: Integer; begin if Selected then begin for I := Low(RPCArray) to High(RPCArray) do if ResultList.Selected.Index = RPCArray[I].ResultListIndex then begin LoadRPCData(memData.Lines, RPCArray[I].UCallListIndex); memData.SelStart := 0; lblCallID.Caption := 'Last Call Minus: ' + IntToStr((RetainedRPCCount - RPCArray[I].UCallListIndex) - 1); FCurrent := RPCArray[I].UCallListIndex; break; end; if RPCLogAction = ShowSearch then begin SearchString := StringReplace(Trim(SearchTerm.Text), #10, '', [rfReplaceAll]); CharPos := 0; repeat // find the text and save the position CharPos2 := memData.FindText(SearchString, CharPos, Length(memData.Text), []); CharPos := CharPos2 + 1; if CharPos = 0 then break; HighlightRichEdit(CharPos2, Length(SearchString), clYellow); until CharPos = 0; end; if RPCLogAction = ShowFlag then begin HighlightRichEdit(0, Length(memData.Lines[0]), clYellow); end; end; end; end.
unit ProgressDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; Const PD_TooLong=2000; {the number of Msec after which progress dialog will appear. Anything that takes less time won't bring up a dialog} type TProgress = class(TForm) ProgressBar: TProgressBar; Pmsg: TLabel; procedure FormHide(Sender: TObject); private sec,msec:word; shown:boolean; Lpos:Longint; lMax:Longint; LargeMax:Boolean; { Private declarations } procedure SetMsg(const s:String); Function ItIsTime:Boolean; public Procedure Reset(steps:Integer); Procedure Step; Procedure StepBy(steps:Integer); Property Msg:String write SetMsg; end; var Progress: TProgress; implementation {$R *.DFM} procedure TProgress.SetMsg(const s:String); begin Caption:='Progress - '+s; { Pmsg.Caption:=s; Update;} end; Function TProgress.ItIsTime:Boolean; var nhr,nmin,nsec,nmsec:word; minpassed,secpassed,msecpassed:integer; begin DecodeTime(Time,nhr,nmin,nsec,nmsec); Secpassed:=nsec-sec; if secpassed<0 then Inc(secpassed,60); msecpassed:=nmsec-msec; if msecpassed<0 then inc(msecpassed,1000); Result:=secpassed*1000+msecpassed>PD_TooLong; end; Procedure TProgress.Reset(steps:Integer); var hr,min:word; begin ProgressBar.Min:=0; ProgressBar.Step:=1; ProgressBar.Position:=0; if Steps<=5000 then begin Progressbar.Max:=steps-1; LargeMax:=false; end else begin Progressbar.Max:=300; LMax:=steps; LargeMax:=true; end; Lpos:=0; DecodeTime(Time,hr,min,sec,msec); Shown:=false; Hide; end; Procedure TProgress.Step; begin if not Shown then if ItIsTime then begin Show; Shown:=true; end; ProgressBar.StepIt; end; Procedure TProgress.StepBy(steps:Integer); var Npos:Integer; begin if not Shown then if ItIsTime then begin Show; Shown:=true; end; if LargeMax then begin Inc(Lpos,steps); NPos:=Round(Lpos/Lmax*300); if nPos<>ProgressBar.Position then ProgressBar.Position:=Npos; end else ProgressBar.Position:=ProgressBar.Position+steps; end; procedure TProgress.FormHide(Sender: TObject); begin Msg:=''; end; end.
unit rtti_idebinder_uBinders; interface uses Classes, SysUtils, rtti_broker_iBroker, Controls, StdCtrls, ExtCtrls, fgl, Graphics, Grids, MaskEdit, lmessages, LCLProc, LCLType, rtti_broker_uData, Menus, SynEdit; type TBinderChangeEvent = procedure of object; TBinderChangeEvents = specialize TFPGList<TBinderChangeEvent>; { TEditBinder } TEditBinder = class private fControl: TWinControl; fDataItem: IRBDataItem; fListIndex: integer; fDataQuery: IRBDataQuery; fChangeEvents: TBinderChangeEvents; protected property ListIndex: integer read fListIndex; property DataQuery: IRBDataQuery read fDataQuery; procedure BindControl; virtual; abstract; procedure UnbindControl; virtual; procedure NotifyChangeEvents; public constructor Create; destructor Destroy; override; procedure DataToControl; virtual; abstract; procedure Bind(const AControl: TWinControl; const ADataItem: IRBDataItem; const ADataQuery: IRBDataQuery); overload; procedure Bind(const AControl: TWinControl; const ADataItem: IRBDataItem; AListIndex: integer; const ADataQuery: IRBDataQuery); overload; procedure RegisterChangeEvent(AEvent: TBinderChangeEvent); procedure UnregisterChangeEvent(AEvent: TBinderChangeEvent); property Control: TWinControl read fControl; property DataItem: IRBDataItem read fDataItem; end; { TTextBinder } TTextBinder = class(TEditBinder) private function GetControl: TCustomEdit; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; procedure UnbindControl; override; property Control: TCustomEdit read GetControl; public procedure DataToControl; override; end; { TMemoBinder } TMemoBinder = class(TEditBinder) private function GetControl: TCustomSynEdit; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; property Control: TCustomSynEdit read GetControl; public procedure DataToControl; override; end; { TBoolBinder } TBoolBinder = class(TEditBinder) private function GetControl: TCustomCheckBox; procedure OnChangeHandler(Sender: TObject); protected procedure BindControl; override; property Control: TCustomCheckBox read GetControl; public procedure DataToControl; override; end; { TOfferBinder } TOfferBinder = class(TEditBinder) private fKeyDownItemIndex: integer; fOldWndProc: TWndMethod; function GetControl: TCustomComboBox; procedure OnChangeHandler(Sender: TObject); procedure ControlWndProc(var TheMessage: TLMessage); protected procedure FillOffer; virtual; abstract; procedure OfferToData; virtual; abstract; procedure DataToOffer; virtual; abstract; protected procedure BindControl; override; property Control: TCustomComboBox read GetControl; public procedure DataToControl; override; end; { TOfferObjectRefBinder } TOfferObjectRefBinder = class(TOfferBinder) private fOffer: IRBDataList; protected procedure FillOffer; override; procedure OfferToData; override; procedure DataToOffer; override; protected procedure FillControlItems; end; { TOfferEnumBinder } TOfferEnumBinder = class(TOfferBinder) protected procedure FillOffer; override; procedure OfferToData; override; procedure DataToOffer; override; end; { TListBinder } TListBinder = class(TEditBinder) protected type { TGridEditorSupport } TGridEditorSupport = class private fEditor: TWinControl; fOldWndProc: TWndMethod; fGrid: TCustomGrid; fCol, fRow:Integer; fff: integer; protected procedure EditorWndProc(var TheMessage: TLMessage); procedure KeyDown(var Key : Word; Shift : TShiftState); procedure EditingDone; function GetRect: TRect; procedure SetGrid(var Msg: TGridMessage); procedure SetPos(var Msg: TGridMessage); procedure GetGrid(var Msg: TGridMessage); public constructor Create(AEditor: TWinControl); end; { TOfferEditor } TOfferEditor = class(TCustomComboBox) private fSupport: TGridEditorSupport; protected procedure KeyDown(var Key : Word; Shift : TShiftState); override; procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); override; procedure msg_SetGrid(var Msg: TGridMessage); message GM_SETGRID; procedure msg_SetPos(var Msg: TGridMessage); message GM_SETPOS; procedure msg_GetGrid(var Msg: TGridMessage); message GM_GETGRID; procedure msg_SetValue(var Msg: TGridMessage); message GM_SETVALUE; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure EditingDone; override; end; { TTextEditor } TTextEditor = class(TCustomMaskEdit) private fSupport: TGridEditorSupport; protected procedure KeyDown(var Key : Word; Shift : TShiftState); override; procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); override; procedure msg_SetGrid(var Msg: TGridMessage); message GM_SETGRID; procedure msg_SetPos(var Msg: TGridMessage); message GM_SETPOS; procedure msg_GetGrid(var Msg: TGridMessage); message GM_GETGRID; procedure msg_SetValue(var Msg: TGridMessage); message GM_SETVALUE; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure EditingDone; override; end; private fCellEditor: TWinControl; fCellValueData: IRBData; fCellBinder: TEditBinder; fObjectData: IRBData; function GetControl: TCustomStringGrid; procedure FillRowFromObject(ARow: integer; AObjectData: IRBData); procedure EmptyRow(ARow: integer); function CreateEditor(const ADataItem: IRBDataItem): TWinControl; function CreateBinder(const ADataItem: IRBDataItem): TEditBinder; procedure OnColRowDeletedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); procedure OnColRowInsertedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); procedure OnEditingDoneHandler(Sender: TObject); procedure OnSelectEditorHandler(Sender: TObject; aCol, aRow: Integer; var Editor: TWinControl); procedure OnKeyDownHandler(Sender: TObject; var Key: Word; Shift: TShiftState); protected procedure BindControl; override; property Control: TCustomStringGrid read GetControl; public procedure DataToControl; override; end; implementation type { TControlHelper } TControlHelper = class helper for TControl private function GetH_OnEditingDone: TNotifyEvent; procedure SetH_OnEditingDone(AValue: TNotifyEvent); public property H_OnEditingDone: TNotifyEvent read GetH_OnEditingDone write SetH_OnEditingDone; end; { TGridHelper } TGridHelper = class helper for TCustomGrid private function GetH_FastEditing: boolean; procedure SetH_FastEditing(AValue: boolean); public procedure H_EditorTextChanged(const aCol,aRow: Integer; const aText:string); function H_EditorIsReadOnly: boolean; procedure H_SetEditText(ACol, ARow: Longint; const Value: string); procedure H_KeyDown(var Key : Word; Shift : TShiftState); procedure H_DoOPDeleteColRow(IsColumn: Boolean; index: Integer); property H_FastEditing: boolean read GetH_FastEditing write SetH_FastEditing; end; { TCustomComboBoxHelper } TCustomComboBoxHelper = class helper for TCustomComboBox private function GetOnChange: TNotifyEvent; procedure SetOnChange(AValue: TNotifyEvent); public property OnChange: TNotifyEvent read GetOnChange write SetOnChange; end; { TControlHelper } function TControlHelper.GetH_OnEditingDone: TNotifyEvent; begin Result := OnEditingDone; end; procedure TControlHelper.SetH_OnEditingDone(AValue: TNotifyEvent); begin OnEditingDone := AValue; end; { TMemoBinder } function TMemoBinder.GetControl: TCustomSynEdit; begin Result := inherited Control as TCustomSynEdit; end; procedure TMemoBinder.OnChangeHandler(Sender: TObject); begin if ListIndex = -1 then DataItem.AsString := Control.Text else DataItem.AsStringList[ListIndex] := Control.Text; NotifyChangeEvents; end; procedure TMemoBinder.BindControl; begin Control.OnChange := @OnChangeHandler; end; procedure TMemoBinder.DataToControl; begin if ListIndex = -1 then Control.Text := DataItem.AsString else Control.Text := DataItem.AsStringList[ListIndex]; end; { TBoolBinder } function TBoolBinder.GetControl: TCustomCheckBox; begin Result := inherited Control as TCustomCheckBox; end; procedure TBoolBinder.OnChangeHandler(Sender: TObject); begin if ListIndex = -1 then DataItem.AsBoolean := Control.State = cbChecked else DataItem.AsBooleanList[ListIndex] := Control.State = cbChecked; NotifyChangeEvents; end; procedure TBoolBinder.BindControl; begin Control.OnChange := @OnChangeHandler; end; procedure TBoolBinder.DataToControl; begin if ListIndex = -1 then begin if DataItem.AsBoolean then Control.State := cbChecked else Control.State := cbUnchecked; end else begin if DataItem.AsBooleanList[ListIndex] then Control.State := cbChecked else Control.State := cbUnchecked; end; end; { TOfferEnumBinder } procedure TOfferEnumBinder.FillOffer; var i: integer; begin Control.Items.Clear; for i := 0 to DataItem.EnumNameCount - 1 do begin Control.Items.Add(DataItem.EnumName[i]); end; end; procedure TOfferEnumBinder.OfferToData; begin if Control.ItemIndex <> -1 then begin DataItem.AsString := Control.Items[Control.ItemIndex]; end; end; procedure TOfferEnumBinder.DataToOffer; var i: integer; begin for i := 0 to Control.Items.Count - 1 do begin if DataItem.AsString = Control.Items[i] then begin Control.ItemIndex := i; Exit; end; end; Control.ItemIndex := -1; end; { TListBinder.TTextEditor } procedure TListBinder.TTextEditor.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key,Shift); fSupport.KeyDown(Key, Shift); end; procedure TListBinder.TTextEditor.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); var m: TRect; begin m := fSupport.GetRect; inherited DoSetBounds(m.Left, m.Top, m.Right - m.Left + 1, m.Bottom - m.Top + 1); end; procedure TListBinder.TTextEditor.msg_SetGrid(var Msg: TGridMessage); begin fSupport.SetGrid(Msg); end; procedure TListBinder.TTextEditor.msg_SetPos(var Msg: TGridMessage); begin fSupport.SetPos(Msg); end; procedure TListBinder.TTextEditor.msg_GetGrid(var Msg: TGridMessage); begin fSupport.GetGrid(Msg); end; procedure TListBinder.TTextEditor.msg_SetValue(var Msg: TGridMessage); begin Text := Msg.Value; end; constructor TListBinder.TTextEditor.Create(AOwner: TComponent); begin fSupport := TGridEditorSupport.Create(Self); inherited Create(AOwner); AutoSize := false; BorderStyle := bsNone; end; destructor TListBinder.TTextEditor.Destroy; begin FreeAndNil(fSupport); inherited Destroy; end; procedure TListBinder.TTextEditor.EditingDone; begin inherited EditingDone; fSupport.EditingDone; end; { TListBinder.TGridEditorSupport } procedure TListBinder.TGridEditorSupport.EditorWndProc(var TheMessage: TLMessage ); begin case TheMessage.Msg of LM_KEYDOWN: begin Exit; end; LM_CLEAR, LM_CUT, LM_PASTE: begin if (fGrid <> nil) and (fGrid.H_EditorIsReadOnly) then exit; end; end; fOldWndProc(TheMessage); end; procedure TListBinder.TGridEditorSupport.KeyDown(var Key: Word; Shift: TShiftState); procedure doEditorKeyDown; begin if FGrid<>nil then FGrid.EditorkeyDown(Self, key, shift); end; procedure doGridKeyDown; begin if FGrid<>nil then FGrid.H_KeyDown(Key, shift); end; function GetFastEntry: boolean; begin if FGrid<>nil then Result := FGrid.H_FastEditing else Result := False; end; procedure CheckEditingKey; begin if (FGrid=nil) or FGrid.H_EditorIsReadOnly then Key := 0; end; var IntSel: boolean; begin case Key of VK_DELETE: CheckEditingKey; VK_BACK: CheckEditingKey; VK_UP: doGridKeyDown; VK_DOWN: begin EditingDone; doGridKeyDown; end; VK_LEFT, VK_RIGHT:; //if GetFastEntry then begin { IntSel:= ((Key=VK_LEFT) and not AtStart) or ((Key=VK_RIGHT) and not AtEnd); if not IntSel then begin} VK_END, VK_HOME: ; else doEditorKeyDown; end; end; procedure TListBinder.TGridEditorSupport.EditingDone; begin if fGrid <> nil then fGrid.EditingDone; end; function TListBinder.TGridEditorSupport.GetRect: TRect; begin if (FGrid <> nil) and (fCol >= 0) and (fRow >= 0) then Result := FGrid.CellRect(fCol, fRow) else begin Result := Bounds(fEditor.Left, fEditor.Top, fEditor.Width, fEditor.Height); end; //InflateRect(Result, -2, -2); Result.Top := Result.Top; Result.Left := Result.Left; Result.Bottom := Result.Bottom - 2; Result.Right := Result.Right - 2; end; procedure TListBinder.TGridEditorSupport.SetGrid(var Msg: TGridMessage); begin fGrid := Msg.Grid; Msg.Options := EO_AUTOSIZE or EO_SELECTALL {or EO_HOOKKEYPRESS or EO_HOOKKEYUP}; end; procedure TListBinder.TGridEditorSupport.SetPos(var Msg: TGridMessage); begin fCol := Msg.Col; fRow := Msg.Row; end; procedure TListBinder.TGridEditorSupport.GetGrid(var Msg: TGridMessage); begin Msg.Grid := FGrid; Msg.Options:= EO_IMPLEMENTED; end; constructor TListBinder.TGridEditorSupport.Create(AEditor: TWinControl); begin fEditor := AEditor; fOldWndProc := fEditor.WindowProc; fEditor.WindowProc := @EditorWndProc; end; { TListBinder.TOfferEditor } procedure TListBinder.TOfferEditor.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key,Shift); fSupport.KeyDown(Key, Shift); end; procedure TListBinder.TOfferEditor.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); var m: TRect; begin m := fSupport.GetRect; inherited DoSetBounds(m.Left, m.Top, m.Right - m.Left + 1, m.Bottom - m.Top + 1); end; procedure TListBinder.TOfferEditor.msg_SetGrid(var Msg: TGridMessage); begin fSupport.SetGrid(Msg); end; procedure TListBinder.TOfferEditor.msg_SetPos(var Msg: TGridMessage); begin fSupport.SetPos(Msg); end; procedure TListBinder.TOfferEditor.msg_GetGrid(var Msg: TGridMessage); begin fSupport.GetGrid(Msg); end; procedure TListBinder.TOfferEditor.msg_SetValue(var Msg: TGridMessage); begin Text := Msg.Value; end; constructor TListBinder.TOfferEditor.Create(AOwner: TComponent); begin fSupport := TGridEditorSupport.Create(Self); inherited Create(AOwner); AutoSize := false; BorderStyle := bsNone; end; destructor TListBinder.TOfferEditor.Destroy; begin FreeAndNil(fSupport); inherited Destroy; end; procedure TListBinder.TOfferEditor.EditingDone; begin inherited EditingDone; fSupport.EditingDone; end; { TOfferObjectRefBinder } procedure TOfferObjectRefBinder.FillOffer; begin fOffer := DataQuery.Retrive(DataItem.ClassName); Control.Items.Clear; FillControlItems; end; procedure TOfferObjectRefBinder.OfferToData; var mOfferIndex: NativeInt; begin if Control.ItemIndex <> -1 then begin mOfferIndex := NativeInt(Control.Items.Objects[Control.ItemIndex]); if ListIndex = -1 then DataItem.AsObject := fOffer[mOfferIndex] else DataItem.AsObjectList[ListIndex] := fOffer[mOfferIndex]; end; end; procedure TOfferObjectRefBinder.DataToOffer; var i: integer; mO, mOffErO: TObject; begin if ListIndex = -1 then mO := DataItem.AsObject else mO := DataItem.AsObjectList[ListIndex]; for i := 0 to fOffer.Count - 1 do begin mOffErO := fOffer[i]; if mOfferO = mO then begin Control.ItemIndex := i; Exit; end; end; Control.ItemIndex := -1; end; procedure TOfferObjectRefBinder.FillControlItems; var i: NativeInt; mData: IRBData; begin for i := 0 to fOffer.Count - 1 do begin mData := fOffer.AsData[i]; if not SameText(mData[0].Name, 'id') or (mData.Count = 1) then Control.Items.AddObject(fOffer.AsData[i][0].AsString, TObject(i)) else Control.Items.AddObject(fOffer.AsData[i][1].AsString, TObject(i)); end; end; { TCustomComboBoxHelper } function TCustomComboBoxHelper.GetOnChange: TNotifyEvent; begin Result := inherited OnChange; end; procedure TCustomComboBoxHelper.SetOnChange(AValue: TNotifyEvent); begin inherited OnChange := AValue; end; { TOfferBinder } function TOfferBinder.GetControl: TCustomComboBox; begin Result := inherited Control as TCustomComboBox; end; procedure TOfferBinder.OnChangeHandler(Sender: TObject); begin OfferToData; NotifyChangeEvents; end; procedure TOfferBinder.ControlWndProc(var TheMessage: TLMessage); begin case TheMessage.Msg of LM_KEYDOWN: fKeyDownItemIndex := Control.ItemIndex; LM_KEYUP: if fKeyDownItemIndex <> Control.ItemIndex then begin // key can cause autcomplete and via that change of ItemIndex // and this is not reported via OnChange event OnChangeHandler(Control); end; end; fOldWndProc(TheMessage); end; procedure TOfferBinder.BindControl; begin FillOffer; Control.OnChange := @OnChangeHandler; fOldWndProc := Control.WindowProc; Control.WindowProc := @ControlWndProc; Control.AutoComplete := True; end; procedure TOfferBinder.DataToControl; begin DataToOffer; end; function TGridHelper.GetH_FastEditing: boolean; begin Result := FastEditing; end; procedure TGridHelper.SetH_FastEditing(AValue: boolean); begin FastEditing := AValue; end; procedure TGridHelper.H_EditorTextChanged(const aCol, aRow: Integer; const aText: string); begin EditorTextChanged(aCol, aRow, aText); end; function TGridHelper.H_EditorIsReadOnly: boolean; begin Result := EditorIsReadOnly; end; procedure TGridHelper.H_SetEditText(ACol, ARow: Longint; const Value: string); begin SetEditText(ACol, ARow, Value); end; procedure TGridHelper.H_KeyDown(var Key: Word; Shift: TShiftState); begin KeyDown(Key, Shift); end; procedure TGridHelper.H_DoOPDeleteColRow(IsColumn: Boolean; index: Integer); begin DoOPDeleteColRow(IsColumn, index); end; { TListBinder } function TListBinder.GetControl: TCustomStringGrid; begin Result := inherited Control as TCustomStringGrid; end; procedure TListBinder.FillRowFromObject(ARow: integer; AObjectData: IRBData); var i: integer; begin if AObjectData = nil then EmptyRow(ARow) else begin if Control.ColCount <> AObjectData.Count then begin Control.ColCount := AObjectData.Count; end; for i := 0 to AObjectData.Count - 1 do begin if AObjectData[i].IsObject then begin Control.Cells[i, ARow] := '[Object]'; end else if AObjectData[i].IsList then begin Control.Cells[i, ARow] := '[List]'; end else begin Control.Cells[i, ARow] := AObjectData[i].AsString; end; end; end; end; procedure TListBinder.EmptyRow(ARow: integer); var i: integer; begin for i := 0 to Control.ColCount - 1 do Control.Cells[i, ARow] := ''; end; function TListBinder.CreateEditor(const ADataItem: IRBDataItem): TWinControl; begin Result := nil; if ADataItem.IsObject and ADataItem.IsReference then begin Result := TOfferEditor.Create(Control); end else begin if ADataItem.EnumNameCount > 0 then begin Result := TOfferEditor.Create(Control); end else begin Result := TTextEditor.Create(Control); end; end; end; function TListBinder.CreateBinder(const ADataItem: IRBDataItem): TEditBinder; begin Result := nil; if ADataItem.IsObject and ADataItem.IsReference then begin Result := TOfferObjectRefBinder.Create; end else if ADataItem.EnumNameCount > 0 then begin Result := TOfferEnumBinder.Create; end else begin Result := TTextBinder.Create; end; end; procedure TListBinder.OnColRowDeletedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); begin if DataItem.ListCount = 0 then Exit; DataItem.ListCount := DataItem.ListCount - 1; end; procedure TListBinder.OnColRowInsertedHandler(Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer); begin DataItem.ListCount := DataItem.ListCount + 1; end; procedure TListBinder.OnEditingDoneHandler(Sender: TObject); begin if fCellBinder = nil then Exit; if fCellBinder.DataItem = nil then Exit; if fCellBinder.DataItem.IsObject then DataToControl else Control.Cells[Control.Col, Control.Row] := fCellBinder.DataItem.AsString; end; procedure TListBinder.OnSelectEditorHandler(Sender: TObject; aCol, aRow: Integer; var Editor: TWinControl); var mOldEd: TWinControl; mDataItem: IRBDataItem; begin mOldEd := fCellEditor; FreeAndNil(fCellBinder); if fDataItem.IsObject and not fDataItem.IsReference then begin fObjectData := TRBData.Create(fDataItem.AsObjectList[aRow - 1]); mDataItem := fObjectData[aCol]; fCellEditor := CreateEditor(mDataItem); fCellBinder := CreateBinder(mDataItem); fCellBinder.Bind(fCellEditor, mDataItem, fDataQuery); end else begin mDataItem := fDataItem; fCellEditor := CreateEditor(mDataItem); fCellBinder := CreateBinder(mDataItem); fCellBinder.Bind(fCellEditor, mDataItem, aRow - 1, fDataQuery); end; Editor := fCellEditor; mOldEd.Free; end; procedure TListBinder.OnKeyDownHandler(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) and (Shift = [ssCtrl]) then begin if Control.Row = Control.RowCount - Control.FixedRows then begin Control.H_DoOPDeleteColRow(False, Control.Row); end; Key := 0; end else inherited; end; procedure TListBinder.BindControl; var mData: IRBData; i: integer; begin Control.RowCount := 1 + DataItem.ListCount; Control.FixedRows := 1; Control.FixedCols := 0; if DataItem.IsObject then begin mData := TRBData.Create(DataItem.AsClass); Control.ColCount := mData.Count; for i := 0 to mData.Count - 1 do begin Control.Cells[i,0] := mData[i].Name; end; end else begin Control.ColCount := 1; Control.Cells[0,0] := 'Value'; end; // on the end, otherway are called when assign collcount - rowcount Control.AutoFillColumns := True; Control.Options := [goFixedVertLine, goFixedHorzLine, goVertLine, goHorzLine, goRangeSelect, goEditing, goAutoAddRows, goTabs, {goAlwaysShowEditor,} goSmoothScroll]; Control.OnColRowInserted := @OnColRowInsertedHandler; Control.OnColRowDeleted := @OnColRowDeletedHandler; Control.OnSelectEditor := @OnSelectEditorHandler; Control.OnKeyDown := @OnKeyDownHandler; Control.H_OnEditingDone := @OnEditingDoneHandler; end; procedure TListBinder.DataToControl; var i: integer; begin for i := 0 to DataItem.ListCount - 1 do begin if DataItem.IsObject then begin FillRowFromObject(i + 1, DataItem.AsObjectList[i] as IRBData); end else begin Control.Cells[0, i + 1] := DataItem.AsStringList[i]; end; end; end; { TTextBinder } function TTextBinder.GetControl: TCustomEdit; begin Result := inherited Control as TCustomEdit; end; procedure TTextBinder.OnChangeHandler(Sender: TObject); begin if ListIndex = -1 then DataItem.AsString := Control.Text else DataItem.AsStringList[ListIndex] := Control.Text; NotifyChangeEvents; end; procedure TTextBinder.BindControl; begin Control.OnChange := @OnChangeHandler; end; procedure TTextBinder.UnbindControl; begin //Control.OnChange := nil; inherited UnbindControl; end; procedure TTextBinder.DataToControl; begin if ListIndex = -1 then Control.Text := DataItem.AsString else Control.Text := DataItem.AsStringList[ListIndex]; end; { TEditBinder } procedure TEditBinder.UnbindControl; begin end; procedure TEditBinder.NotifyChangeEvents; var mEvent: TBinderChangeEvent; begin for mEvent in fChangeEvents do mEvent; end; constructor TEditBinder.Create; begin fChangeEvents := TBinderChangeEvents.Create; end; destructor TEditBinder.Destroy; begin UnbindControl; FreeAndNil(fChangeEvents); inherited Destroy; end; procedure TEditBinder.Bind(const AControl: TWinControl; const ADataItem: IRBDataItem; const ADataQuery: IRBDataQuery); begin Bind(AControl, ADataItem, -1, ADataQuery); end; procedure TEditBinder.Bind(const AControl: TWinControl; const ADataItem: IRBDataItem; AListIndex: integer; const ADataQuery: IRBDataQuery); begin fControl := AControl; fDataItem := ADataItem; fListIndex := AListIndex; fDataQuery := ADataQuery; BindControl; DataToControl; end; procedure TEditBinder.RegisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fChangeEvents.IndexOf(AEvent); if mIndex = -1 then fChangeEvents.Add(AEvent); end; procedure TEditBinder.UnregisterChangeEvent(AEvent: TBinderChangeEvent); var mIndex: integer; begin mIndex := fChangeEvents.IndexOf(AEvent); if mIndex <> -1 then fChangeEvents.Delete(mIndex); end; end.
unit uUninstallTypes; interface uses uConstants; // [BEGIN] Short install section oldest version const TEXT_MES_HELP = 'Справка'; // 1.75 ProductName_1_75 = 'Photo DataBase 1.75'; StartMenuProgramsPath_1_75 = 'Photo DB v1.75'; ProductVersion_1_75 = '1.75'; ProgramShortCutFile_1_75 = ProductName_1_75 + '.lnk'; HelpShortCutFile_1_75 = TEXT_MES_HELP + '.lnk'; // 1.8 ProductName_1_8 = 'Photo DataBase 1.8'; StartMenuProgramsPath_1_8 = 'Photo DB v1.8'; ProductVersion_1_8 = '1.8'; ProgramShortCutFile_1_8 = ProductName_1_8 + '.lnk'; HelpShortCutFile_1_8 = TEXT_MES_HELP + '.lnk'; // 1.9 ProductName_1_9 = 'Photo DataBase 1.9'; StartMenuProgramsPath_1_9 = 'Photo DB v1.9'; ProductVersion_1_9 = '1.9'; ProgramShortCutFile_1_9 = ProductName_1_9 + '.lnk'; HelpShortCutFile_1_9 = TEXT_MES_HELP + '.lnk'; // 2.0 ProductName_2_0 = 'Photo DataBase 2.0'; StartMenuProgramsPath_2_0 = 'Photo DB v2.0'; ProductVersion_2_0 = '2.0'; ProgramShortCutFile_2_0 = ProductName_2_0 + '.lnk'; HelpShortCutFile_2_0 = TEXT_MES_HELP + '.lnk'; // 2.1 ProductName_2_1 = 'Photo DataBase 2.1'; StartMenuProgramsPath_2_1 = 'Photo DB v2.1'; ProductVersion_2_1 = '2.1'; ProgramShortCutFile_2_1 = ProductName_2_1 + '.lnk'; HelpShortCutFile_2_1 = TEXT_MES_HELP + '.lnk'; // 2.2 ProductName_2_2 = 'Photo DataBase 2.2'; StartMenuProgramsPath_2_2 = 'Photo DB v2.2'; ProductVersion_2_2 = '2.2'; ProgramShortCutFile_2_2 = ProductName_2_2 + '.lnk'; HelpShortCutFile_2_2 = TEXT_MES_HELP + '.lnk'; // 2.3 ProductName_2_3 = 'Photo DataBase 2.3'; StartMenuProgramsPath_2_3 = 'Photo DB v2.3'; ProductVersion_2_3 = '2.2'; ProgramShortCutFile_2_3 = ProductName_2_3 + '.lnk'; HelpShortCutFile_2_3 = '*|LNK|'; // 3.0 ProductName_3_0 = 'Photo DataBase 3.0'; StartMenuProgramsPath_3_0 = 'Photo DB v3.0'; ProductVersion_3_0 = '3.0'; ProgramShortCutFile_3_0 = ProductName_3_0 + '.lnk'; HelpShortCutFile_3_0 = '*|LNK|'; // 3.1 ProductName_3_1 = 'Photo DataBase 3.1'; StartMenuProgramsPath_3_1 = 'Photo DB v3.1'; ProductVersion_3_1 = '3.1'; ProgramShortCutFile_3_1 = ProductName_3_1 + '.lnk'; HelpShortCutFile_3_1 = '*|LNK|'; // 4.0 ProductName_4_0 = 'Photo DataBase 4.0'; StartMenuProgramsPath_4_0 = 'Photo DB v4.0'; ProductVersion_4_0 = '4.0'; ProgramShortCutFile_4_0 = ProductName_4_0 + '.lnk'; HelpShortCutFile_4_0 = '*|LNK|'; // 4.5 ProductName_4_5 = 'Photo DataBase 4.5'; StartMenuProgramsPath_4_5 = 'Photo DB v4.5'; ProductVersion_4_5 = '4.5'; ProgramShortCutFile_4_5 = ProductName_4_5 + '.lnk'; HelpShortCutFile_4_5 = '*|LNK|'; // [END] implementation end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, GLVectorTypes, GLCadencer, GLScene, GLWin32Viewer, GLTexture, GLFileTGA, GLObjects, GLShadowVolume, GLVectorGeometry, GLProjectedTextures, GLMaterial, GLCoordinates, GLCrossPlatform, GLBaseClasses; type TForm1 = class(TForm) viewer: TGLSceneViewer; scene: TGLScene; GLCadencer1: TGLCadencer; camera: TGLCamera; GLPlane1: TGLPlane; GLPlane2: TGLPlane; GLPlane3: TGLPlane; scenery: TGLDummyCube; GLSphere1: TGLSphere; matLib: TGLMaterialLibrary; Timer1: TTimer; Light: TGLDummyCube; GLLightSource1: TGLLightSource; ShadowVol: TGLShadowVolume; GLCube1: TGLCube; GLCube2: TGLCube; light2: TGLDummyCube; GLSphere2: TGLSphere; GLSphere3: TGLSphere; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ViewerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); private public end; var Form1: TForm1; projLight: TGLProjectedTextures; ang: single; mx, my, mk: integer; emitter1, emitter2: TGLTextureEmitter; implementation {$R *.DFM} procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin ang:= ang + deltatime*20; //Move or rotate? Light.Position.Y:= sin(DegToRadian(ang)); light.position.x:= cos(DegToRadian(ang)); //!!! why is this happening? (if this line is removed, matrix is not updated) if light2.AbsoluteMatrix.X.X = 666 then exit; light2.pitch(deltatime*20); viewer.invalidate; end; procedure TForm1.FormCreate(Sender: TObject); begin matLib.Materials[0].Material.Texture.Image.LoadFromFile('projector.tga'); matLib.Materials[1].Material.Texture.Image.LoadFromFile('flare.bmp'); projLight:= TGLProjectedTextures(scene.Objects.AddNewChild(TGLProjectedTextures)); emitter1:= TGLTextureEmitter(Light.AddNewChild(TGLTextureEmitter)); emitter1.Material.MaterialLibrary:= matLib; emitter1.Material.LibMaterialName:= 'spot'; emitter1.Name:= 'emitter1'; emitter2:= TGLTextureEmitter(Light2.AddNewChild(TGLTextureEmitter)); emitter2.Material.MaterialLibrary:= matLib; emitter2.Material.LibMaterialName:= 'spot2'; emitter2.name:= 'emitter2'; projLight.Emitters.AddEmitter(emitter1); projLight.Emitters.AddEmitter(emitter2); //play around with the rendering order scenery.MoveTo(ShadowVol); shadowVol.MoveTo(projLight); end; procedure TForm1.Timer1Timer(Sender: TObject); begin form1.caption:= format('Projected Textures %f', [viewer.framespersecond]); viewer.resetperformancemonitor; end; procedure TForm1.ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mk:= 1; mx:= x; my:= y; end; procedure TForm1.ViewerMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mk:= 0; end; procedure TForm1.ViewerMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if mk <> 1 then exit; if shift = [ssLeft] then Camera.MoveAroundTarget(my-y, mx-x) else if shift = [ssRight] then Camera.AdjustDistanceToTarget(1.0 + (y - my) / 100); mx:= x; my:= y; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin Camera.AdjustDistanceToTarget(Power(1.1, WheelDelta/120)); end; end.
{*******************************************************} { } { Tachyon Unit } { Vector Raster Geographic Information Synthesis } { VOICE .. Tracer } { GRIP ICE .. Tongs } { Digital Terrain Mapping } { Image Locatable Holographics } { SOS MAP } { Surreal Object Synthesis Multimedia Analysis Product } { Fractal3D Life MOW } { Copyright (c) 1995,2006 Ivan Lee Herring } { } {*******************************************************} unit fSysInfo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TSystemInfoForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Edit4: TEdit; Edit5: TEdit; Edit6: TEdit; Edit7: TEdit; Edit8: TEdit; Edit9: TEdit; Edit10: TEdit; Edit11: TEdit; Edit12: TEdit; Label16: TLabel; Edit13: TEdit; Edit14: TEdit; Edit15: TEdit; Edit16: TEdit; Edit17: TEdit; Edit18: TEdit; Label17: TLabel; Label18: TLabel; Label19: TLabel; Label20: TLabel; Label21: TLabel; Label22: TLabel; Label23: TLabel; Label24: TLabel; Label25: TLabel; Label26: TLabel; Edit19: TEdit; Edit20: TEdit; Edit21: TEdit; Edit22: TEdit; SIHelpBtn: TBitBtn; SICloseBtn: TBitBtn; SIReLoadBtn: TBitBtn; Label27: TLabel; Label28: TLabel; Label29: TLabel; Label30: TLabel; Edit23: TEdit; Label31: TLabel; Edit24: TEdit; Edit25: TEdit; Edit26: TEdit; Label32: TLabel; SIDDCBox: TComboBox; Label33: TLabel; Label34: TLabel; Label35: TLabel; Edit27: TEdit; Edit28: TEdit; SIDDReloadBtn: TBitBtn; Label37: TLabel; Label38: TLabel; Label39: TLabel; Edit29: TEdit; Edit30: TEdit; Edit31: TEdit; Label40: TLabel; Edit32: TEdit; procedure FormShow(Sender: TObject); procedure SIReLoadBtnClick(Sender: TObject); function HasCoProcesser: bool; procedure LoadEdits; function ShowDriveType(PRoot: Pchar): string; { procedure GetDiskSizeAvail(TheDrive : PChar; var TotalBytes : double; var TotalFree : double); } procedure SIHelpBtnClick(Sender: TObject); procedure SICloseBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var SystemInfoForm: TSystemInfoForm; implementation uses fUGlobal,Registry, aclass5, fMain; {$R *.DFM} procedure TSystemInfoForm.FormCreate(Sender: TObject); begin left := SystemInfoFormX; top := SystemInfoFormY; end; procedure TSystemInfoForm.SIHelpBtnClick(Sender: TObject); begin Application.HelpContext(13000); end; procedure TSystemInfoForm.SICloseBtnClick(Sender: TObject); begin Close; end; procedure TSystemInfoForm.FormClose(Sender: TObject; var Action: TCloseAction); begin SystemInfoFormX := SystemInfoForm.left; SystemInfoFormY := SystemInfoForm.top; DoSaver; end; var UI: TUserInfo; DrivePChar: array[0..3] of Char; {WhataName:array[0..99]of Char;} {function GetDiskFreeSpaceEx(lpDirectoryName: PAnsiChar; var lpFreeBytesAvailableToCaller : Integer; var lpTotalNumberOfBytes: Integer; var lpTotalNumberOfFreeBytes: Integer) : bool; stdcall; external kernel32 name 'GetDiskFreeSpaceExA'; } procedure TSystemInfoForm.SIReLoadBtnClick(Sender: TObject); begin LoadEdits; end; procedure TSystemInfoForm.FormShow(Sender: TObject); begin LoadEdits; end; function TSystemInfoForm.HasCoProcesser: bool; {$IFDEF WIN32} var TheKey: hKey; {$ENDIF} begin Result := true; {$IFNDEF WIN32} if GetWinFlags and Wf_80x87 = 0 then Result := false; {$ELSE} if RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'HARDWARE\DESCRIPTION\System\FloatingPointProcessor', 0, KEY_EXECUTE, TheKey) <> ERROR_SUCCESS then result := false; RegCloseKey(TheKey); {$ENDIF} end; procedure TSystemInfoForm.LoadEdits; var {UserPChar:array[0..99]of Char;} MyStats: THeapStatus; DriveString, sString: string; {TotalBytes, TotalFree : double;} DriveChar: Char; {iInput:Integer;} {nSize:DWord;pnSize,pBuf:pointer;Buf:PChar;} {MyMem:MEMORYSTATUS;pMyMem:Pointer; Buff: Array[0..144] OF Char;PCstr:PChar;} MemoryStatus: TMemoryStatus; SystemInfo: TSystemInfo; OsVersionInfo: TOsVersionInfo; dc: HDC; begin try try UI := TUserInfo.create; Edit1.Text := UI.UserName; Edit2.Text := UI.CompanyName; except on ERegInfoNotFound do DoMessages(39976); end; finally UI.Free; end; OsVersionInfo.dwOSVersionInfoSize := sizeof(OsVersionInfo); GetVersionEx(OsVersionInfo); with OsVersionInfo do begin Edit3.Text := (IntToStr(dwMajorVersion) + '.' + IntToStr(dwMinorVersion)); {WORD HIWORD(DWORD dwValue ); // value from which high-order word is retrieved LOWORD...} end; GetSystemInfo(SystemInfo); with SystemInfo do begin Edit4.Text := (IntToStr(dwProcessorType)); Edit5.Text := (IntToStr(dwNumberOfProcessors)); end; if HasCoProcesser then Edit26.Text := ('Has CoProcessor') else Edit26.Text := ('None:Emulation Mode'); MemoryStatus.dwLength := SizeOf(MemoryStatus); GlobalMemoryStatus(MemoryStatus); with MemoryStatus do begin // Size of MemoryStatus record Edit6.Text := (IntToStr(dwLength)); // Per-Cent of Memory in use by your system Edit7.Text := (IntToStr(dwMemoryLoad)); // The amount of Total Physical memory allocated to your system. Edit8.Text := (IntToStr(dwTotalPhys)); // The amount available of physical memory in your system. { Edit9.Text := (IntToStr(dwAvailPhys));} MemoryAvailable:= Round(dwTotalPhys - ((dwMemoryLoad / 100)*dwTotalPhys)); {dwAvailPhys;} Edit9.Text := (IntToStr(MemoryAvailable)); // The amount of Total Bytes allocated to your page file. Edit10.Text := (IntToStr(dwTotalPageFile)); // The amount of available bytes in your page file. Edit11.Text := (IntToStr(dwAvailPageFile)); // The amount of Total bytes allocated to this program // (generally 2 gigabytes of virtual space). Edit12.Text := (IntToStr(dwTotalVirtual)); // The amount of avalable bytes that is left to your program to use. Edit23.Text := (IntToStr(dwAvailVirtual)); end; // with (*Sample Output of what is contained in Memo1.Lines: 32: Size of 'MemoryStatus' record in bytes 76%: memory in use 33054720: Total Physical Memory in bytes 499712: Available Physical Memory in bytes 53608448: Total Bytes of Paging File 36372480: Available bytes in paging file 2143289344: User Bytes of Address space 2135556096: Available User bytes of address space *) DriveString := SIDDCBox.Text; DriveChar := DriveString[1]; StrPCopy(DrivePChar, DriveString); Edit31.Text := ShowDriveType(DrivePChar); {GetDiskSizeAvail(DrivePChar,TotalBytes,TotalFree);} Edit27.Text := IntToStr(DiskSize(ord(DriveChar) - 64)); {IntToStr(DiskSize(0) div 1024) + ' Kbytes capacity.';} {(FloatToStr(TotalBytes));} Edit28.Text := IntToStr(DiskFree(ord(DriveChar) - 64)); {(FloatToStr(TotalFree));} MyStats := GetHeapStatus; Str(MyStats.TotalAddrSpace, sString); Edit13.Text := sString; Str(MyStats.TotalUncommitted, sString); Edit14.Text := sString; Str(MyStats.TotalCommitted, sString); Edit15.Text := sString; Str(MyStats.TotalAllocated, sString); Edit16.Text := sString; Str(MyStats.TotalFree, sString); Edit17.Text := sString; Str(MyStats.FreeSmall, sString); Edit18.Text := sString; Str(MyStats.FreeBig, sString); Edit19.Text := sString; Str(MyStats.Unused, sString); Edit20.Text := sString; Str(MyStats.Overhead, sString); Edit21.Text := sString; Str(MyStats.HeapErrorCode, sString); Edit22.Text := sString; Edit24.Text := (IntToStr(GetSystemMetrics(SM_CXSCREEN))); Edit32.Text := (IntToStr(GetSystemMetrics(SM_CYSCREEN))); dc := GetDc(0); Edit25.Text := (IntToStr(GetDeviceCaps(dc, BITSPIXEL))); { dc := } ReleaseDc(0, dc); {Give back the screen dc} if (GetSystemMetrics(SM_MOUSEPRESENT) > 0) then Edit29.Text := 'Moused' else Edit29.Text := 'Cat got the Mouse'; if (GetSystemMetrics(SM_SLOWMACHINE) > 0) then Edit30.Text := 'Slow Machine' else Edit30.Text := 'OK'; {Printer 29 30} end; {Of Getting ... Load} function TSystemInfoForm.ShowDriveType(PRoot: Pchar): string; var i: word; begin {Make it lower case.} { if DriveLetter in ['A'..'Z'] then DriveLetter := chr(ord(DriveLetter) + $20); i := GetDriveType(chr(ord(DriveLetter) - ord('a')));} i := GetDriveType(PRoot); case i of 0: result := 'Undetermined'; 1: result := 'Root does not exist'; DRIVE_REMOVABLE: result := 'Floppy'; DRIVE_FIXED: result := 'Hard disk'; DRIVE_REMOTE: result := 'Network drive'; DRIVE_CDROM: result := 'CD-ROM'; DRIVE_RAMDISK: result := 'RAM disk'; else result := 'Does not exist'; end; end; (* function GetDiskFreeSpaceEx(lpDirectoryName: PAnsiChar; var lpFreeBytesAvailableToCaller : Integer; var lpTotalNumberOfBytes: Integer; var lpTotalNumberOfFreeBytes: Integer) : bool; stdcall; external kernel32 name 'GetDiskFreeSpaceExA'; *) (* procedure TSystemInfoForm.GetDiskSizeAvail(TheDrive : PAnsiChar; var TotalBytes : double; var TotalFree : double); var AvailToCall : integer; TheSize : integer; FreeAvail : integer; begin { GetDiskFreeSpaceEx(TheDrive, AvailToCall, TheSize, FreeAvail); } {$IFOPT Q+} {$DEFINE TURNOVERFLOWON} {$Q-} {$ENDIF} if TheSize >= 0 then TotalBytes := TheSize else if TheSize = -1 then begin TotalBytes := $7FFFFFFF; TotalBytes := TotalBytes * 2; TotalBytes := TotalBytes + 1; end else begin TotalBytes := $7FFFFFFF; TotalBytes := TotalBytes + abs($7FFFFFFF - TheSize); end; if AvailToCall >= 0 then TotalFree := AvailToCall else if AvailToCall = -1 then begin TotalFree := $7FFFFFFF; TotalFree := TotalFree * 2; TotalFree := TotalFree + 1; end else begin TotalFree := $7FFFFFFF; TotalFree := TotalFree + abs($7FFFFFFF - AvailToCall); end; end; *) end.
// RemObjects CS to Pascal 0.1 namespace UT3Bots.UTItems; interface uses System, System.Collections.Generic, System.Linq, System.Text, UT3Bots.Communications; type UTItem = public class private var _id: UTIdentifier; var _itemType: ItemType; var _actualClass: Integer; assembly method get_Id: UTIdentifier; property Id: UTIdentifier read get_Id; public method IsItem(&type: ItemType): Boolean; method IsItem(&type: WeaponType): Boolean; method IsItem(&type: HealthType): Boolean; method IsItem(&type: ArmorType): Boolean; method IsItem(&type: AmmoType): Boolean; constructor(Id: String; &Type: String); constructor(invMessage: Message); method ToString(): String; override; /// <summary> /// The actual item as an int, you might want to cast it to the correct (Weapon/Ammo/Health/Armor)Type Enum /// </summary> property ActualClass: Integer read get_ActualClass; /// <summary> /// The type of item /// </summary> property ItemType: ItemType read get_ItemType; method get_ActualClass: Integer; method get_ItemType: ItemType; end; implementation method UTItem.IsItem(&type: ItemType): Boolean; begin if (Self._itemType = &type) then begin exit true end; exit false; end; method UTItem.IsItem(&type: WeaponType): Boolean; begin if ((Self._itemType = ItemType.Weapon) and (Self._actualClass = Integer(&type))) then begin exit true end; exit false end; method UTItem.IsItem(&type: HealthType): Boolean; begin if ((Self._itemType = ItemType.Health) and (Self._actualClass = Integer(&type))) then begin exit true end; exit false end; method UTItem.IsItem(&type: ArmorType): Boolean; begin if ((Self._itemType = ItemType.Armor) and (Self._actualClass = Integer(&type))) then begin exit true end; exit false end; method UTItem.IsItem(&type: AmmoType): Boolean; begin if ((Self._itemType = ItemType.Ammo) and (Self._actualClass = Integer(&type))) then begin exit true end; exit false end; method UTItem.ToString(): String; begin case Self.ItemType of ItemType.Ammo: case (AmmoType(Self.ActualClass)) of AmmoType.Avril: Result := 'Anvil ammo'; AmmoType.BioRifle: Result := 'Bio rifle ammo'; AmmoType.Enforcer: Result := 'Enforcer ammo'; AmmoType.FlakCannon: Result := 'Flak Cannon ammo'; AmmoType.LinkGun: Result := 'Link gun ammo'; AmmoType.RocketLauncher: Result := 'Rocket Launcher ammo'; AmmoType.ShockRifle: Result := 'Shock Rifle ammo'; AmmoType.SniperRifle: Result := 'Sniper Rifle ammo'; AmmoType.Stinger: Result := 'Stinger ammo'; else Result := 'Unknown'; end; // case ItemType.Armor: case (ArmorType(Self.ActualClass)) of ArmorType.Berserk: Result := 'Beserk Powerup'; ArmorType.ChestArmour: Result := 'Chest Armour'; ArmorType.Helmet: Result := 'Helmet'; ArmorType.Invisibility: Result := 'Invisibility Powerup'; ArmorType.Invulnerability: Result := 'Invulnerability Powerup'; ArmorType.JumpBoots: Result := 'Jump Boots'; ArmorType.MultiplyDamage: Result := 'Damage Multiplier powerup'; ArmorType.ShieldBelt: Result := 'Shield belt'; ArmorType.ThighPads: Result := 'Thigh Pad Armour'; else Result := 'Unknown'; end; // case ItemType.Health: case (HealthType(Self.ActualClass)) of HealthType.BigKegOHealth: Result := 'Big Keg o Health'; HealthType.HealthVial: Result := 'Health Vial'; HealthType.MediBox: Result := 'Medi box'; HealthType.SuperHealth: Result := 'Super Health'; else Result := 'Unknown'; end; // case ItemType.Weapon: case (WeaponType(Self.ActualClass)) of WeaponType.Avril: Result := 'Avril'; WeaponType.BioRifle: Result := 'Bio Rifle'; WeaponType.Enforcer: Result := 'Enforcer'; WeaponType.FlakCannon: Result := 'Flack Cannon'; WeaponType.ImpactHammer: Result := 'Impact Hammer'; WeaponType.InstaGibRifle: Result := 'Insta Gib Rifle'; WeaponType.LinkGun: Result := 'Link Gun'; WeaponType.Redeemer: Result := 'Redeemer'; WeaponType.RocketLauncher: Result := 'Rocket Launcher'; WeaponType.ShockRifle: Result := 'Shock Rifle'; WeaponType.SniperRifle: Result := 'Sniper Rifle'; WeaponType.Stinger: Result := 'Stinger'; WeaponType.Translocator: Result := 'Translocator'; else Result := 'Unknown'; end; // case else Result := 'Unknown'; end; // case Self.ItemType of end; constructor UTItem(Id: String; &Type: String); begin Self._id := new UTIdentifier(Id); var weaponType: WeaponType := &Type.GetAsWeaponType(); var ammoType: AmmoType := &Type.GetAsAmmoType(); var healthType: HealthType := &Type.GetAsHealthType(); var armorType: ArmorType := &Type.GetAsArmorType(); if weaponType <> WeaponType.None then begin Self._itemType := ItemType.Weapon; Self._actualClass := Integer(weaponType) end; if ammoType <> AmmoType.None then begin Self._itemType := ItemType.Ammo; Self._actualClass := Integer(ammoType) end; if healthType <> HealthType.None then begin Self._itemType := ItemType.Health; Self._actualClass := Integer(healthType) end; if armorType <> ArmorType.None then begin Self._itemType := ItemType.Armor; Self._actualClass := Integer(armorType) end; end; constructor UTItem(invMessage: Message); begin constructor(invMessage.Arguments[0], invMessage.Arguments[1]); end; method UTItem.get_Id: UTIdentifier; begin Result := Self._id; end; method UTItem.get_ItemType: ItemType; begin Result := Self._itemType; end; method UTItem.get_ActualClass: Integer; begin Result := Self._actualClass; end; end.
//Core routine for setting up the lua system. All scripts are loaded, but //multiple runtime environments are setup per character and removed after //completion. Each of these individual runtime environments reads global vars //which are script related, but have their own pointer as as a global variable, //so each command can access the character runing it. unit LuaNPCCore; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Character, LuaCoreRoutines, LuaTypes; procedure ResumeLuaNPCScript( var AChara : TCharacter; const ReturnAValue : Boolean = false ); procedure ResumeLuaNPCScriptWithString( var AChara : TCharacter; const ReturnString : string ); procedure ResumeLuaNPCScriptWithInteger( var AChara : TCharacter; const ReturnInteger : integer ); procedure ResumeLuaNPCScriptWithDouble( var AChara : TCharacter; const ReturnDouble : double ); implementation uses Main, Globals, LuaPas; procedure ResumeLuaNPCScript( var AChara : TCharacter; const ReturnAValue : Boolean = false ); begin SetCharaToLua(AChara); //put the global back on the stack if lua_resume(AChara.LuaInfo.Lua, Byte(ReturnAValue)) <> 0 then begin if Length(lua_tostring(AChara.LuaInfo.Lua, -1)) > 0 then begin //If something went wrong, get the error message off the stack Console.Message(lua_tostring(AChara.LuaInfo.Lua, -1), 'Zone Server - Lua', MS_ERROR); end; lua_pop(AChara.LuaInfo.Lua, 1); //Remove the error string end; end; procedure ResumeLuaNPCScriptWithString( var AChara : TCharacter; const ReturnString : string ); begin lua_pushstring(AChara.LuaInfo.Lua, PChar(ReturnString)); ResumeLuaNPCScript(AChara,true); end; procedure ResumeLuaNPCScriptWithInteger( var AChara : TCharacter; const ReturnInteger : integer ); begin lua_pushinteger(AChara.LuaInfo.Lua, ReturnInteger); ResumeLuaNPCScript(AChara,true); end; procedure ResumeLuaNPCScriptWithDouble( var AChara : TCharacter; const ReturnDouble : Double ); begin lua_pushnumber(AChara.LuaInfo.Lua, ReturnDouble); ResumeLuaNPCScript(AChara,true); end; end.
unit uDlgObjectFilterTypeSelector; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uBASE_DialogForm, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxGraphics, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxCheckBox, cxInplaceContainer, cxDBTL, cxControls, cxTLData, DB, ADODB, cxClasses, cxTextEdit; type TImageIndex = integer; TdlgObjectFilterTypeSelector = class(TBASE_DialogForm) Query: TADOQuery; TreeList: TcxTreeList; colCheckBox: TcxTreeListColumn; colID: TcxTreeListColumn; colName: TcxTreeListColumn; procedure colCheckBoxPropertiesChange(Sender: TObject); private FSelectedName: string; FSelectedCount: integer; function GetSelectedIDs: string; { Private declarations } protected procedure LoadTree(ParentID: variant; ParentNode: TcxTreeListNode); virtual; public property SelectedIDs: string read GetSelectedIDs; property SelectedName: string read FSelectedName; property SelectedCount: integer read FSelectedCount; constructor Create(AOwner: TComponent); override; end; var dlgObjectFilterTypeSelector: TdlgObjectFilterTypeSelector; implementation uses uMain; {$R *.dfm} { TdlgObjectFilterTypeSelector } constructor TdlgObjectFilterTypeSelector.Create(AOwner: TComponent); var i: integer; id: integer; begin inherited; Query.Connection:=frmMain.ADOConnection; Query.Open; LoadTree(null, nil); Query.Close; end; function TdlgObjectFilterTypeSelector.GetSelectedIDs: string; var i: integer; begin result:=''; FSelectedCount:=0; for i:=0 to TreeList.Nodes.Count-1 do if TreeList.Nodes[i].Values[1] then begin result:=result+IntToStr(TreeList.Nodes[i].Values[0])+','; FSelectedName:=trim(TreeList.Nodes[i].Values[2]); inc(FSelectedCount); end; if result<>'' then delete(result, length(result), 1); end; procedure TdlgObjectFilterTypeSelector.LoadTree(ParentID: variant; ParentNode: TcxTreeListNode); function Spaces(ACount: integer): string; var i: integer; begin result:=''; for i:=1 to ACount do result:=result+' '; end; var node: TcxTreeListNode; qry: TAdoQuery; begin if VarIsNull(ParentID) then Query.Filter:='вк_Родитель = null' else Query.Filter:='вк_Родитель = '+IntToStr(ParentID); Query.Sort:='Псевдоним'; Query.First; qry:=TAdoQuery.Create(nil); qry.Clone(Query); qry.Filtered:=true; qry.Filter:=Query.Filter; qry.Sort:=Query.Sort; try while not qry.Eof do begin if Assigned(ParentNode) then node:=TreeList.AddChild(ParentNode) else node:=TreeList.Add; node.Values[0]:=qry['код_Объект']; node.Values[1]:=false; node.Values[2]:=Spaces(node.Level*2)+qry['Псевдоним']; LoadTree(qry['код_Объект'], node); qry.Next; end; finally qry.Free; end; end; procedure TdlgObjectFilterTypeSelector.colCheckBoxPropertiesChange( Sender: TObject); var NewValue: boolean; procedure SetNewValue(ANode: TcxTreeListNode); var i: integer; begin for i:=0 to ANode.Count-1 do begin ANode[i].Values[1]:=NewValue; SetNewValue(ANode[i]); end; end; var node: TcxTreeListNode; i: integer; begin inherited; TreeList.BeginUpdate; try NewValue:=(Sender as TcxCheckBox).Checked; SetNewValue(TreeList.FocusedNode); finally TreeList.EndUpdate; end; end; 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, Vcl.Buttons, IniFiles, Vcl.ComCtrls, System.DateUtils; type TForm1 = class(TForm) Panel1: TPanel; btConnect: TSpeedButton; btDisconnect: TSpeedButton; btSendCmd: TSpeedButton; Label1: TLabel; cbCommand: TComboBox; edHost: TLabeledEdit; edPort: TLabeledEdit; Panel2: TPanel; Memo1: TMemo; Panel3: TPanel; btClearLog: TSpeedButton; btExit: TSpeedButton; TimePicker: TDateTimePicker; DatePicker: TDateTimePicker; procedure FormCreate(Sender: TObject); procedure btExitClick(Sender: TObject); procedure btClearLogClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btConnectClick(Sender: TObject); procedure btSendCmdClick(Sender: TObject); procedure btDisconnectClick(Sender: TObject); procedure cbCommandChange(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetControlsStatus(Connected: boolean); function ReadIniFile: boolean; end; var Form1: TForm1; const KeyCmd = 'cmd'; KeyArg = 'arg'; KeyAnswer = 'answer'; KeyBody = 'body'; KeyAdres = 'address'; KeySMS = 'sms'; KeyDate = 'date'; KeyCommand = 'command'; Keydescription = 'description'; KeyID = '_id'; KeyContacts = 'contacts'; KeyPhones = 'phones'; CmdGetSmsCount = 'getsmscount'; CmdGetSMS = 'getsms'; CmdGetSMSLast = 'getsmslast'; CmdGetCallCount = 'getcallcount'; CmdGetCall = 'getcall'; CmdGetCallLast = 'getcalllast'; CmdSendSMS = 'sendsms'; CmdMakeCall = 'makecall'; CmdGetCmdList = 'cmdlist'; // полный список команд CmdGetContact = 'getcontact'; CmdGetSMSAfter = 'getsmsafter'; CmdGetCallAfter = 'getcallafter'; SmsTypeDraft = 'draft'; SmsTypeFailed = 'failed'; SmsTypeInbox = 'inbox'; SmsTypeOutBox = 'outbox'; SmsTypeQueued = 'queued'; SmsTypeSent = 'sent'; CallTypeIncoming = 'incoming'; CallTypeOutgoing = 'outgoing'; CallTypeMissed = 'missed'; CallTypeVoiceMail = 'voicemail'; procedure LogOut(LogStr:string); implementation {$R *.dfm} uses Unit2; procedure LogOut(LogStr:string); var log_f:TextFile; begin LogStr := DateTimeToStr(now) + ' ' + LogStr; Form1.Memo1.Lines.Add(LogStr); end; procedure TForm1.btClearLogClick(Sender: TObject); begin Memo1.Clear; end; procedure TForm1.btConnectClick(Sender: TObject); var Host: string; Port: word; begin Host := edHost.Text; Port := StrToInt(edPort.Text); Manager.ConnectToPhone(Host, Port); end; procedure TForm1.btDisconnectClick(Sender: TObject); begin Manager.DisconnectFromPhone; end; procedure TForm1.btExitClick(Sender: TObject); begin Close; end; procedure TForm1.btSendCmdClick(Sender: TObject); var Cmd: string; DT : TDateTime; UMSec: int64; begin if (cbCommand.Text = CmdGetSMSAfter) or (cbCommand.Text = CmdGetCallAfter) then begin DT := Trunc(DatePicker.Date) + TimeOf(TimePicker.Time); UMSec := DateTimeToUnix(DT) * 1000; // time in millisecond Cmd := cbCommand.Text + ' ' + IntToStr(UMSec); end else Cmd := cbCommand.Text; Manager.SendToPhone(Cmd); end; procedure TForm1.cbCommandChange(Sender: TObject); begin if (cbCommand.Text = CmdGetSMSAfter) or (cbCommand.Text = CmdGetCallAfter) then begin DatePicker.Visible := True; TimePicker.Visible := True; end else begin DatePicker.Visible := False; TimePicker.Visible := False; end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); var FileName: string; IniFile: TIniFile; begin FileName := ExtractFilePath(Application.ExeName) + 'Config.ini'; try IniFile := TIniFile.Create(FileName); IniFile.WriteString('Phone', 'Host', edHost.Text); IniFile.WriteInteger('Phone', 'Port', StrToInt(edPort.Text)); except LogOut('Error write settings to ini file'); Exit; end; end; procedure TForm1.FormCreate(Sender: TObject); begin SetControlsStatus(False); cbCommand.Items.Add(CmdGetCmdList); cbCommand.Items.Add(CmdGetSmsCount); cbCommand.Items.Add(CmdGetSMS); cbCommand.Items.Add(CmdGetSMSLast); cbCommand.Items.Add(CmdGetSMSAfter); cbCommand.Items.Add(CmdGetCallCount); cbCommand.Items.Add(CmdGetCall); cbCommand.Items.Add(CmdGetCallLast); cbCommand.Items.Add(CmdGetCallAfter); cbCommand.Items.Add(CmdSendSMS); cbCommand.Items.Add(CmdMakeCall); cbCommand.Items.Add(CmdGetContact); cbCommand.ItemIndex := 0; ReadIniFile; Manager := TManager.Create; DatePicker.Visible := False; TimePicker.Visible := False; DatePicker.DateTime := Now; TimePicker.DateTime := Now; end; function TForm1.ReadIniFile: boolean; var IniFile : TIniFile; FileName:string; Port: word; begin Result := False; FileName := ExtractFilePath(Application.ExeName) + 'Config.ini'; if FileExists(FileName) then begin IniFile := TIniFile.Create(FileName); edHost.Text := IniFile.ReadString('Phone','Host',''); Port := IniFile.ReadInteger('Phone','Port',0); edPort.Text := IntToStr(Port); IniFile.Free; end; Result := True; end; procedure TForm1.SetControlsStatus(Connected: boolean); begin if Connected then begin btDisconnect.Enabled := True; btConnect.Enabled := False; btSendCmd.Enabled := True; end else begin btDisconnect.Enabled := False; btConnect.Enabled := True; btSendCmd.Enabled := False; end; end; end.
(* Category: SWAG Title: MATH ROUTINES Original name: 0008.PAS Description: MATHSPD.PAS Author: SWAG SUPPORT TEAM Date: 05-28-93 13:50 *) { > I was just wondering how to speed up some math-intensive > routines I've got here. For example, I've got a Function > that returns the distance between two Objects: > Function Dist(X1,Y1,X2,Y2 : Integer) : Real; > begin > Dist := Round(Sqrt(Sqr(X1-X2)+Sqr(Y1-Y2))); > end; > This is way to slow. I know assembly can speed it up, but > I know nothing about as. so theres the problem. Please > help me out, any and all source/suggestions welcome! X1, Y1, X2, Y2 are all Integers. Integer math is faster than Real (just about anything is). Sqr and Sqrt are not Integer Functions. Try for fun... } Function Dist( X1, Y1, X2, Y2 : Integer) : Real; Var XTemp, YTemp : Integer; { the allocation of these takes time. if you don't want that time taken, make them global With care} begin XTemp := X1 - X2; YTemp := Y1 - Y2; Dist := Sqrt(XTemp * XTemp + YTemp * YTemp); end; { if you have a math coprocessor or a 486dx, try using DOUBLE instead of Real, and make sure your compiler is set to compile For 287 (or 387). } begin Writeln('Distance Between (3,9) and (-2,-3) is: ', Dist(3,9,-2,-3) : 6 : 2); end.
unit frmMain; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.FreeOTFE.org/ // // ----------------------------------------------------------------------------- // interface uses ActnList, Buttons, Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, Graphics, Grids, ImgList, Menus, Messages, Spin64, StdCtrls, SysUtils, ToolWin, Windows, XPMan, //sdu SDUSystemTrayIcon, Shredder, //LibreCrypt/freeotfe OTFE_U, MainSettings, frmCommonMain, CommonSettings, DriverControl, OTFEFreeOTFE_U, OTFEFreeOTFEBase_U, pkcs11_library, lcDialogs, SDUForms, SDUGeneral, SDUMRUList, SDUMultimediaKeys, SDUDialogs; type TPortableModeAction = (pmaStart, pmaStop, pmaToggle); TfrmMain = class (TfrmCommonMain) ToolBar1: TToolBar; pnlTopSpacing: TPanel; ilDriveIcons: TImageList; lvDrives: TListView; pmDrives: TPopupMenu; miPopupDismount: TMenuItem; N2: TMenuItem; miPopupProperties: TMenuItem; N3: TMenuItem; miProperties: TMenuItem; N1: TMenuItem; miDismountAllMain: TMenuItem; miPopupDismountAll: TMenuItem; miFreeOTFEDrivers: TMenuItem; miOverwriteFreeSpace: TMenuItem; miFormat: TMenuItem; N6: TMenuItem; miPopupFormat: TMenuItem; miPopupOverwriteFreeSpace: TMenuItem; N7: TMenuItem; miPortableModeDrivers: TMenuItem; N8: TMenuItem; actDismountAll: TAction; actProperties: TAction; pmSystemTray: TPopupMenu; open1: TMenuItem; open2: TMenuItem; mountfile1: TMenuItem; mountpartition1: TMenuItem; dismountall1: TMenuItem; N10: TMenuItem; miOptions: TMenuItem; actConsoleDisplay: TAction; N11: TMenuItem; N12: TMenuItem; SDUSystemTrayIcon1: TSDUSystemTrayIcon; tbbNew: TToolButton; tbbMountFile: TToolButton; tbbMountPartition: TToolButton; tbbDismount: TToolButton; tbbDismountAll: TToolButton; actTogglePortableMode: TAction; actFormat: TAction; actOverwriteFreeSpace: TAction; tbbTogglePortableMode: TToolButton; actDrivers: TAction; ilDriveIconOverlay: TImageList; actOverwriteEntireDrive: TAction; Overwriteentiredrive1: TMenuItem; Overwriteentiredrive2: TMenuItem; N17: TMenuItem; mmRecentlyMounted: TMenuItem; actFreeOTFEMountPartition: TAction; actLinuxMountPartition: TAction; miFreeOTFEMountPartition: TMenuItem; miLinuxMountPartition: TMenuItem; actConsoleHide: TAction; actInstall: TAction; InstallDoxBox1: TMenuItem; actTestModeOn: TAction; SetTestMode1: TMenuItem; actTestModeOff: TAction; DisallowTestsigneddrivers1: TMenuItem; tbbSettings: TToolButton; pmOpen: TPopupMenu; miMountfile: TMenuItem; miOpenpartition: TMenuItem; miOpenLUKSBox: TMenuItem; miOpenBoxforcedmcrypt: TMenuItem; pmNew: TPopupMenu; miNew: TMenuItem; Newdmcryptcontainer1: TMenuItem; actLUKSNew: TAction; NewLUKS1: TMenuItem; procedure actDriversExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure actRefreshExecute(Sender: TObject); procedure lvDrivesResize(Sender: TObject); procedure FormResize(Sender: TObject); procedure lvDrivesClick(Sender: TObject); procedure lvDrivesDblClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure actDismountExecute(Sender: TObject); procedure actDismountAllExecute(Sender: TObject); procedure actPropertiesExecute(Sender: TObject); procedure actExitExecute(Sender: TObject); procedure actConsoleDisplayExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actTogglePortableModeExecute(Sender: TObject); procedure lvDrivesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure actFormatExecute(Sender: TObject); procedure actOverwriteFreeSpaceExecute(Sender: TObject); procedure tbbTogglePortableModeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure actOverwriteEntireDriveExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actAboutExecute(Sender: TObject); procedure actFreeOTFEMountPartitionExecute(Sender: TObject); procedure actLinuxMountPartitionExecute(Sender: TObject); procedure actFreeOTFENewExecute(Sender: TObject); procedure actOptionsExecute(Sender: TObject); procedure SDUSystemTrayIcon1DblClick(Sender: TObject); procedure SDUSystemTrayIcon1Click(Sender: TObject); procedure actConsoleHideExecute(Sender: TObject); procedure actInstallExecute(Sender: TObject); procedure actTestModeOnExecute(Sender: TObject); procedure actTestModeOffExecute(Sender: TObject); procedure miToolsClick(Sender: TObject); procedure actLUKSNewExecute(Sender: TObject); private function IsTestModeOn: Boolean; protected ftempCypherDriver: Ansistring; ftempCypherGUID: TGUID; ftempCypherDetails: TFreeOTFECypher_v3; ftempCypherKey: TSDUBytes; ftempCypherEncBlockNo: Int64; fIconMounted: TIcon; fIconUnmounted: TIcon; // We cache this information as it take a *relativly* long time to get it // from the OTFE component. fcountPortableDrivers: Integer; fallowUACEsclation: Boolean; // fCanSaveSettings : Boolean; function HandleCommandLineOpts_Portable(): eCmdLine_Exit; function HandleCommandLineOpts_DriverControl(): eCmdLine_Exit; function HandleCommandLineOpts_DriverControl_GUI(): eCmdLine_Exit; function HandleCommandLineOpts_DriverControl_Install(driverControlObj: TDriverControl): eCmdLine_Exit; function HandleCommandLineOpts_DriverControl_Uninstall(driverControlObj: TDriverControl): eCmdLine_Exit; function HandleCommandLineOpts_DriverControl_Count(driverControlObj: TDriverControl): Integer; function HandleCommandLineOpts_Count(): eCmdLine_Exit; function HandleCommandLineOpts_Create(): eCmdLine_Exit; override; function HandleCommandLineOpts_Dismount(): eCmdLine_Exit; function HandleCommandLineOpts_SetTestMode(): eCmdLine_Exit; // function HandleCommandLineOpts_SetInstalled(): eCmdLine_Exit; //true = set OK function SetTestMode(silent, SetOn: Boolean): Boolean; //sets 'installed' flag in ini file - returns false if fails (ini file must exist or be set as custom) // function SetInstalled(): Boolean; function InstallAllDrivers(driverControlObj: TDriverControl; silent: Boolean): eCmdLine_Exit; procedure ReloadSettings(); override; procedure SetupOTFEComponent(); override; function ActivateFreeOTFEComponent(suppressMsgs: Boolean): Boolean; override; procedure DeactivateFreeOTFEComponent(); override; procedure ShowOldDriverWarnings(); override; procedure PKCS11TokenRemoved(SlotID: Integer); override; procedure RefreshMRUList(); override; procedure MRUListItemClicked(mruList: TSDUMRUList; idx: Integer); override; procedure InitializeDrivesDisplay(); procedure RefreshDrives(); function DetermineDriveOverlay(volumeInfo: TOTFEFreeOTFEVolumeInfo): Integer; function AddIconForDrive(driveLetter: DriveLetterChar; overlayIdx: Integer): Integer; procedure SetStatusBarTextNormal(); procedure EnableDisableControls(); override; function GetDriveLetterFromLVItem(listItem: TListItem): DriveLetterChar; procedure ResizeWindow(); function GetSelectedDrives(): DriveLetterString; procedure OverwriteDrives(drives: DriveLetterString; overwriteEntireDrive: Boolean); procedure MountFiles(mountAsSystem: TDragDropFileType; filenames: TStringList; ReadOnly, forceHidden: Boolean); overload; override; procedure DriveProperties(); function DismountSelected(): Boolean; function DismountAll(isEmergency: Boolean = False): Boolean; function DismountDrives(dismountDrives: DriveLetterString; isEmergency: Boolean): Boolean; procedure ReportDrivesNotDismounted(drivesRemaining: DriveLetterString; isEmergency: Boolean); procedure GetAllDriversUnderCWD(driverFilenames: TStringList); function PortableModeSet(setTo: TPortableModeAction; suppressMsgs: Boolean): Boolean; function _PortableModeStart(suppressMsgs: Boolean): Boolean; function _PortableModeStop(suppressMsgs: Boolean): Boolean; function _PortableModeToggle(suppressMsgs: Boolean): Boolean; // System tray icon related... procedure SystemTrayIconDismount(Sender: TObject); procedure DestroySysTrayIconMenuitems(); // Hotkey related... procedure SetupHotKeys(); procedure EnableHotkey(hotKey: TShortCut; hotKeyIdent: Integer); procedure DisableHotkey(hotKeyIdent: Integer); procedure RecaptionToolbarAndMenuIcons(); override; procedure SetIconListsAndIndexes(); override; procedure SetupToolbarFromSettings(); override; procedure DoSystemTrayAction(Sender: TObject; doAction: TSystemTrayClickAction); procedure UACEscalateForDriverInstallation(); procedure UACEscalateForPortableMode(portableAction: TPortableModeAction; suppressMsgs: Boolean); procedure UACEscalate(cmdLineParams: String; suppressMsgs: Boolean); function DoTests: Boolean; override; public procedure WMDropFiles(var Msg: TWMDropFiles); message WM_DROPFILES; procedure WMDeviceChange(var Msg: TMessage); message WM_DEVICECHANGE; procedure WMQueryEndSession(var msg: TWMQueryEndSession); message WM_QUERYENDSESSION; procedure WMEndSession(var msg: TWMEndSession); message WM_ENDSESSION; procedure GenerateOverwriteData(Sender: TObject; passNumber: Integer; bytesRequired: Cardinal; var generatedOK: Boolean; var outputBlock: TShredBlock); procedure InitApp(); override; function MessageHook(var msg: TMessage): Boolean; procedure DisplayDriverControlDlg(); // Handle any command line options; returns TRUE if command line options // were passed through function HandleCommandLineOpts(out cmdExitCode: eCmdLine_Exit): Boolean; override; end; var GfrmMain: TfrmMain; GLOBAL_VAR_WM_FREEOTFE_RESTORE: Cardinal; GLOBAL_VAR_WM_FREEOTFE_REFRESH: Cardinal; implementation {$R *.DFM} { TODO -otdk -crefactor : editing dcr files is awkward - use imagelist instead } {$R FreeOTFESystemTrayIcons.dcr} uses // delphi units ShellApi, // Required for SHGetFileInfo Commctrl, // Required for ImageList_GetIcon ComObj, // Required for StringToGUID Math, // Required for min strutils, //sdu units pkcs11_slot, SDUFileIterator_U, SDUi18n,//for format drive SDUGraphics, //LibreCrypt units MouseRNGDialog_U, // SDUWinSvc, frmAbout, CommonfrmCDBBackupRestore, lcConsts, FreeOTFEfrmOptions, FreeOTFEfrmSelectOverwriteMethod, frmVolProperties, OTFEConsts_U, DriverAPI, frmWizardCreateVolume, PKCS11Lib; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} resourcestring AUTORUN_POST_MOUNT = 'post mount'; AUTORUN_PRE_MOUNT = 'pre dismount'; AUTORUN_POST_DISMOUNT = 'post dismount'; const AUTORUN_TITLE: array [TAutorunType] of String = ( AUTORUN_POST_MOUNT, AUTORUN_PRE_MOUNT, AUTORUN_POST_DISMOUNT ); resourcestring TEXT_NEED_ADMIN = 'You need administrator privileges in order to carry out this operation.'; // Toolbar captions... RS_TOOLBAR_CAPTION_MOUNTPARTITION = 'Open partition container'; RS_TOOLBAR_CAPTION_DISMOUNTALL = 'Lock all'; RS_TOOLBAR_CAPTION_PORTABLEMODE = 'Portable mode'; // Toolbar hints... RS_TOOLBAR_HINT_MOUNTPARTITION = 'Open a partition based container'; RS_TOOLBAR_HINT_DISMOUNTALL = 'Lock all open containers'; RS_TOOLBAR_HINT_PORTABLEMODE = 'Toggle portable mode on/off'; POPUP_DISMOUNT = 'Dismount %1: %2'; const R_ICON_MOUNTED = 'MOUNTED'; R_ICON_UNMOUNTED = 'UNMOUNTED'; TAG_SYSTRAYICON_POPUPMENUITEMS = $5000; // Note: LSB will be the drive letter TAG_SYSTRAYICON_POPUPMENUITEMS_DRIVEMASK = $FF; // LSB mask for drive letter HOTKEY_TEXT_NONE = '(None)'; HOTKEY_IDENT_DISMOUNT = 1; HOTKEY_IDENT_DISMOUNTEMERG = 2; // Overlay icons; these MUST be kept in sync with the icons in // ilDriveIconOverlay OVERLAY_IMGIDX_NONE = -1; OVERLAY_IMGIDX_PKCS11TOKEN = 0; OVERLAY_IMGIDX_LINUX = 1; AUTORUN_SUBSTITUTE_DRIVE = '%DRIVE'; // Command line parameters. case insensitive. generally only one action per invocation //swithces only CMDLINE_NOUACESCALATE = 'noUACescalate'; CMDLINE_GUI = 'gui'; CMDLINE_FORCE = 'force'; CMDLINE_SET_INSTALLED = 'SetInstalled'; //sets 'installed' flag in ini file, creating if nec. - usually used with CMDLINE_SETTINGSFILE // cmds with params CMDLINE_DRIVERCONTROL = 'driverControl'; CMDLINE_PORTABLE = 'portable'; CMDLINE_TOGGLE = 'toggle'; CMDLINE_DISMOUNT = 'dismount'; // CMDLINE_MOUNTED = 'mounted'; unused CMDLINE_SET_TESTMODE = 'SetTestMode'; // args to Command line parameters... CMDLINE_COUNT = 'count'; CMDLINE_START = 'start'; CMDLINE_ON = 'on'; CMDLINE_STOP = 'stop'; CMDLINE_OFF = 'off'; CMDLINE_ALL = 'all'; CMDLINE_INSTALL = 'install'; CMDLINE_UNINSTALL = 'uninstall'; CMDLINE_DRIVERNAME = 'drivername'; CMDLINE_TOTAL = 'total'; CMDLINE_DRIVERSPORTABLE = 'portable'; CMDLINE_DRIVERSINSTALLED = 'installed'; // Online user manual URL... { DONE -otdk -cenhancement : set project homepage } URL_USERGUIDE_MAIN = 'http://LibreCrypt.eu/LibreCrypt/getting_started.html'; // PAD file URL... URL_PADFILE_MAIN = 'https://raw.githubusercontent.com/t-d-k/LibreCrypt/master/PAD.xml'; // Download URL... // URL_DOWNLOAD_MAIN = 'http://LibreCrypt.eu/download.html'; // This procedure is called after OnCreate, and immediately before the // Application.Run() is called procedure TfrmMain.InitApp(); var goForStartPortable, errLastRun: Boolean; begin inherited; // if appRunning set when app started, that means it didnt shut down properly last time errLastRun := gSettings.feAppRunning = arRunning; gSettings.feAppRunning := arRunning; // save immediately in case any errors starting drivers etc. // fCanSaveSettings := gSettings.Save(false); // don't show warnings as user hasn't changed settings // Hook Windows messages first; if we're running under Vista and the user UAC // escalates to start portable mode (below), we don't want to miss any // refresh messages the escalated process may send us! Application.HookMainWindow(MessageHook); InitializeDrivesDisplay(); // We call EnableDisableControls(...) at this point, to display the // toolbar/statusbar as needed EnableDisableControls(); // EnableDisableControls(...) calls SetupToolbarFromSettings(...) which can // change the window's width if large icons are being used // We recenter the window here so it looks right // // !!! WARNING !!! // DON'T USE self.Position HERE! // This causes the Window to be destroyed and recreated - which messes up // the system tray icon code as it's monitoring the window's messages // self.Position := poScreenCenter; // Instead, position window manually... self.Top := ((Screen.Height - self.Height) div 2); self.Left := ((Screen.Width - self.Width) div 2); if not (ActivateFreeOTFEComponent(True)) then begin goForStartPortable := gSettings.OptAutoStartPortable; if not (goForStartPortable) then begin // if 'installed' then install drivers and prompt reboot else prompt portable as below // if not gSettings.OptInstalled then goForStartPortable := SDUConfirmYN( _('The main LibreCrypt driver does not appear to be installed and running on this computer') + SDUCRLF + SDUCRLF + _('Would you like to start LibreCrypt in portable mode?')); end; if goForStartPortable then begin if errLastRun then MessageDlg(_( 'Portable mode will not be started automatically because LibreCrypt shut down last time it was run.'), mtWarning, [mbOK], 0) else PortableModeSet(pmaStart, False); end else begin if not errLastRun then begin actInstallExecute(nil); end else begin if errLastRun {and gSettings.OptInstalled} then MessageDlg(_( 'The drivers will not be installed automatically because LibreCrypt shut down last time it was run.'), mtWarning, [mbOK], 0); SDUMessageDlg( _( 'Please see the "installation" section of the accompanying documentation for instructions on how to install the LibreCrypt drivers.'), mtInformation, [mbOK], 0 ); end; end; end; RefreshDrives(); EnableDisableControls(); SetupHotKeys(); SetupPKCS11(False); // actLUKSNewExecute(nil); //actTestExecute(nil); end; procedure TfrmMain.RefreshDrives(); var ListItem: TListItem; driveIconNum: Integer; i: Integer; volumeInfo: TOTFEFreeOTFEVolumeInfo; mounted: DriveLetterString; miTmp: TMenuItem; strVolID: String; overlayIdx: Integer; begin // Flush any caches in case a separate instance of FreeOTFE running from the // commandline, with escalated UAC changed the drivers installed/running GetFreeOtfeBase.CachesFlush(); // Cleardown all... // ...Main FreeOTFE window list... lvDrives.Items.Clear(); ilDriveIcons.Clear(); // ...System tray icon drives list... DestroySysTrayIconMenuitems(); // In case the drivers have been stopped/started recently, we bounce the // FreeOTFE component up and down (silently!) DeactivateFreeOTFEComponent(); ActivateFreeOTFEComponent(True); /// ...and repopulate if GetFreeOTFE().Active then begin mounted := GetFreeOTFE().DrivesMounted(); for i := 1 to length(mounted) do begin // ...Main FreeOTFE window list... if GetFreeOTFE().GetVolumeInfo(mounted[i], volumeInfo) then begin ListItem := lvDrives.Items.Add; ListItem.Caption := ' ' + mounted[i] + ':'; ListItem.SubItems.Add(volumeInfo.Filename); overlayIdx := DetermineDriveOverlay(volumeInfo); driveIconNum := AddIconForDrive(mounted[i], overlayIdx); if (driveIconNum >= 0) then begin ListItem.ImageIndex := driveIconNum; end; end else begin // Strange... The drive probably got dismounted between getting the // list of mounted drives, and querying them for more information... end; // The volume ID/label // Cast to prevent compiler error strVolID := SDUVolumeID(DriveLetterChar(mounted[i])); if strVolID <> '' then begin strVolID := '[' + strVolID + ']'; end; // ...System tray icon popup menu... miTmp := TMenuItem.Create(nil); miTmp.Tag := TAG_SYSTRAYICON_POPUPMENUITEMS or Ord(mounted[i]); // We tag our menuitems // in order that we can // know which ones to // remove later miTmp.OnClick := SystemTrayIconDismount; miTmp.AutoHotkeys := maManual; // Otherwise the hotkeys added // automatically can interfere with // examing the caption to get the drive // letter when clicked on miTmp.Caption := SDUParamSubstitute(POPUP_DISMOUNT, [mounted[i], strVolID]); pmSystemTray.Items.Insert((i - 1), miTmp); end; // Insert a divider into the system tray icon's popup menu after the // drives are listed if (length(mounted) > 0) then begin miTmp := TMenuItem.Create(nil); miTmp.Caption := '-'; pmSystemTray.Items.Insert(length(mounted), miTmp); end; end; fcountPortableDrivers := GetFreeOTFE().DriversInPortableMode(); EnableDisableControls(); end; // Tear down system tray icon popup menu menuitems previously added procedure TfrmMain.DestroySysTrayIconMenuitems(); var i: Integer; miTmp: TMenuItem; begin for i := (pmSystemTray.Items.Count - 1) downto 0 do begin if ((pmSystemTray.Items[i].Tag and TAG_SYSTRAYICON_POPUPMENUITEMS) = TAG_SYSTRAYICON_POPUPMENUITEMS) then begin miTmp := pmSystemTray.Items[i]; pmSystemTray.Items.Delete(i); miTmp.Free(); end; end; end; procedure TfrmMain.SystemTrayIconDismount(Sender: TObject); var miDismount: TMenuItem; drive: DriveLetterChar; begin miDismount := TMenuItem(Sender); drive := DriveLetterChar(miDismount.Tag and TAG_SYSTRAYICON_POPUPMENUITEMS_DRIVEMASK); DismountDrives(drive, False); end; function TfrmMain.DetermineDriveOverlay(volumeInfo: TOTFEFreeOTFEVolumeInfo): Integer; begin Result := OVERLAY_IMGIDX_NONE; if volumeInfo.MetaDataStructValid then begin if (volumeInfo.MetaDataStruct.PKCS11SlotID <> PKCS11_NO_SLOT_ID) then begin Result := OVERLAY_IMGIDX_PKCS11TOKEN; end else if volumeInfo.MetaDataStruct.LinuxVolume then begin Result := OVERLAY_IMGIDX_LINUX; end; end; end; { TODO : use diff icons for eg freeotfe/luks/dmcrypt , instead of overlays } // Add an icon to represent the specified drive // overlayIdx - Set to an image index within ilDriveIconOverlay, or -1 for no // overlay // Returns: The icon's index in ilDriveIcons, or -1 on error function TfrmMain.AddIconForDrive(driveLetter: DriveLetterChar; overlayIdx: Integer): Integer; var iconIdx: Integer; anIcon: TIcon; shfi: SHFileInfo; imgListHandle: THandle; iconHandle: HICON; tmpDrivePath: String; overlayIcon: TIcon; listBkColor: TColor; begin iconIdx := -1; // Create a suitable icon to represent the drive tmpDrivePath := driveLetter + ':\'; imgListHandle := SHGetFileInfo(PChar(tmpDrivePath), 0, shfi, sizeof(shfi), SHGFI_SYSICONINDEX or SHGFI_LARGEICON); // SHGFI_DISPLAYNAME if imgListHandle <> 0 then begin iconHandle := ImageList_GetIcon(imgListHandle, shfi.iIcon, ILD_NORMAL); if (iconHandle <> 0) then begin anIcon := TIcon.Create(); try anIcon.ReleaseHandle(); anIcon.handle := iconHandle; if (ilDriveIcons.Width < anIcon.Width) then begin ilDriveIcons.Width := anIcon.Width; end; if (ilDriveIcons.Height < anIcon.Height) then begin ilDriveIcons.Height := anIcon.Height; end; if (overlayIdx >= 0) then begin overlayIcon := TIcon.Create(); try ilDriveIconOverlay.GetIcon(overlayIdx, overlayIcon); SDUOverlayIcon(anIcon, overlayIcon); finally overlayIcon.Free(); end; end; // We switch the background colour so that (Under Windows XP, unthemed, // at least) the icons don't appear to have a black border around them listBkColor := ilDriveIcons.BkColor; ilDriveIcons.BkColor := lvDrives.Color; iconIdx := ilDriveIcons.addicon(anIcon); ilDriveIcons.BkColor := listBkColor; anIcon.ReleaseHandle(); DestroyIcon(iconHandle); finally anIcon.Free(); end; end; end; Result := iconIdx; end; procedure TfrmMain.InitializeDrivesDisplay(); var tmpColumn: TListColumn; begin // Listview setup... lvDrives.SmallImages := ilDriveIcons; lvDrives.RowSelect := True; lvDrives.MultiSelect := True; lvDrives.showcolumnheaders := True; lvDrives.ReadOnly := True; lvDrives.ViewStyle := vsReport; // lvDrives.ViewStyle := vsIcon; // lvDrives.ViewStyle := vsList; lvDrives.IconOptions.Arrangement := TIconArrangement.iaTop; // Listview columns... tmpColumn := lvDrives.Columns.Add; tmpColumn.Caption := _('Drive'); tmpColumn.Width := 100; // tmpColumn.minwidth := lvDrives.width; tmpColumn := lvDrives.Columns.Add; tmpColumn.Caption := _('Container'); tmpColumn.Width := lvDrives.clientwidth - lvDrives.columns[0].Width - ilDriveIcons.Width; // xxx - shouldn't this work? NewColumn.autosize := TRUE; // xxx - shouldn't this work? NewColumn.minwidth := lvDrives.clientwidth - lvDrives.columns[0].width - ilDriveIcons.width; // xxx - use destroyimage or whatever it was to cleardown the **imagelist** end; procedure TfrmMain.RecaptionToolbarAndMenuIcons(); begin inherited; // // Change toolbar captions to shorter captions // tbbNew.Caption := RS_TOOLBAR_CAPTION_NEW; //// tbbMountFile.Caption := RS_TOOLBAR_CAPTION_MOUNTFILE; // tbbMountPartition.Caption := RS_TOOLBAR_CAPTION_MOUNTPARTITION; // tbbDismount.Caption := RS_TOOLBAR_CAPTION_DISMOUNT; // tbbDismountAll.Caption := RS_TOOLBAR_CAPTION_DISMOUNTALL; // tbbTogglePortableMode.Caption := RS_TOOLBAR_CAPTION_PORTABLEMODE; // // // Setup toolbar hints // tbbNew.Hint := RS_TOOLBAR_HINT_NEW; //// tbbMountFile.Hint := RS_TOOLBAR_HINT_MOUNTFILE; // tbbMountPartition.Hint := RS_TOOLBAR_HINT_MOUNTPARTITION; // tbbDismount.Hint := RS_TOOLBAR_HINT_DISMOUNT; // tbbDismountAll.Hint := RS_TOOLBAR_HINT_DISMOUNTALL; // tbbTogglePortableMode.Hint := RS_TOOLBAR_HINT_PORTABLEMODE; end; procedure TfrmMain.SDUSystemTrayIcon1Click(Sender: TObject); begin inherited; DoSystemTrayAction(Sender, gSettings.OptSystemTrayIconActionSingleClick); end; procedure TfrmMain.SDUSystemTrayIcon1DblClick(Sender: TObject); begin inherited; DoSystemTrayAction(Sender, gSettings.OptSystemTrayIconActionDoubleClick); end; procedure TfrmMain.DoSystemTrayAction(Sender: TObject; doAction: TSystemTrayClickAction); begin case doAction of stcaDoNothing: begin // Do nothing... end; stcaDisplayConsole: begin actConsoleDisplay.Execute(); end; stcaDisplayHideConsoleToggle: begin if self.Visible then begin actConsoleHide.Execute(); end else begin actConsoleDisplay.Execute(); end; end; stcaMountFile: begin actFreeOTFEMountFile.Execute(); end; stcaMountPartition: begin actFreeOTFEMountPartition.Execute(); end; stcaMountLinuxFile: begin actLinuxMountFile.Execute(); end; stcaMountLinuxPartition: begin actLinuxMountPartition.Execute(); end; stcaDismountAll: begin actDismountAll.Execute(); end; end; end; { tests system tests opens volumes created with old versions and checks contents as expected regression testing only see testing.jot for more details of volumes to test LUKS keyfile LUKS at offset (ever used?) creating vol creating keyfile creating .les file partition operations overwrite ops pkcs11 ops cdb at offset salt <> default value } function TfrmMain.DoTests: Boolean; var mountList: TStringList; mountedAs: DriveLetterString; vol_path, key_file, les_file: String; vl: Integer; arr, arrB, arrC: TSDUBytes; parr: PByteArray; i: Integer; buf: Ansistring; const MAX_TEST_VOL = 12; {this last dmcrypt_dx.box with dmcrypt_hid.les can cause BSoD } TEST_VOLS: array[0..MAX_TEST_VOL] of String = ('a.box', 'b.box', 'c.box', 'd.box', 'e.box', 'e.box', 'f.box', 'luks.box', 'luks_essiv.box', 'a.box', 'b.box', 'dmcrypt_dx.box', 'dmcrypt_dx.box'); PASSWORDS: array[0..MAX_TEST_VOL] of Ansistring = ('password', 'password', '!"£$%^&*()', 'password', 'password', '5ekr1t', 'password', 'password', 'password', 'secret', 'secret', 'password', '5ekr1t'); ITERATIONS: array[0..MAX_TEST_VOL] of Integer = (2048, 2048, 2048, 2048, 10240, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048); OFFSET: array[0..MAX_TEST_VOL] of Integer = (0, 0, 0, 0, 0, 2097152, 0, 0, 0, 0, 0, 0, 0); KEY_FILES: array[0..MAX_TEST_VOL] of String = ('', '', '', '', '', '', '', '', '', 'a.cdb', 'b.cdb', '', ''); LES_FILES: array[0..MAX_TEST_VOL] of String = ('', '', '', '', '', '', '', '', '', '', '', 'dmcrypt_dx.les', 'dmcrypt_hid.les'); { test MAX_TEST_VOL = 0; TEST_VOLS: array[0..MAX_TEST_VOL] of String = ('dmcrypt_dx.box'); PASSWORDS: array[0..MAX_TEST_VOL] of String = ( '5ekr1t'); ITERATIONS: array[0..MAX_TEST_VOL] of Integer = ( 2048); OFFSET: array[0..MAX_TEST_VOL] of Integer = (0); KEY_FILES: array[0..MAX_TEST_VOL] of String = (''); LES_FILES: array[0..MAX_TEST_VOL] of String = ( 'dmcrypt_hid.les'); } procedure CheckMountedOK; begin RefreshDrives(); // Mount successful // prettyMountedAs := prettyPrintDriveLetters(mountedAs); if (CountValidDrives(mountedAs) <> 1) then begin SDUMessageDlg(Format('The container %s has NOT been opened as drive: %s', [TEST_VOLS[vl], mountedAs])); Result := False; end else begin //done: test opened OK & file exists if not FileExists(mountedAs + ':\README.txt') then begin SDUMessageDlg(Format('File: %s:\README.txt not found', [mountedAs])); Result := False; end; end; end; procedure UnMountAndCheck; begin Application.ProcessMessages; DismountAll(True); Application.ProcessMessages; RefreshDrives(); Application.ProcessMessages; if CountValidDrives(GetFreeOTFE().DrivesMounted) > 0 then begin SDUMessageDlg(Format('Drive(s) %s not unmounted', [GetFreeOTFE().DrivesMounted])); Result := False; end; end; begin inherited; Result := True; (********************************** first some simple unit tests of sdu units to make sure are clearing memory main tests of operation is by functional tests, but we also need to check security features, e.g. that mem is cleared, separately *) // test fastMM4 clears mem, or SafeSetLength if AlwaysClearFreedMemory not defd {$IFDEF FullDebugMode} //this overrides AlwaysClearFreedMemory {$IFDEF AlwaysClearFreedMemory} SDUMessageDlg('Freed memory wiping test will fail because FullDebugMode set'); {$ENDIF} {$ENDIF} SafeSetLength(arr, 100); for i := low(arr) to High(arr) do arr[i] := i; parr := @arr[0]; { setlength(arr,10); AlwaysClearFreedMemory doesnt clear this mem - make sure cleared in sduutils for TSDUBytes using SafeSetLength for i := 10 to 99 do if parr[i] <> 0 then result := false; - } SafeSetLength(arr, 0); for i := 0 to 99 do if parr[i] <> 0 then Result := False; SafeSetLength(arr, 100); for i := low(arr) to High(arr) do arr[i] := i; parr := @arr[0]; // increasing size can reallocate // resize more till get new address // call SafeSetLength in case AlwaysClearFreedMemory not defed while parr = @arr[0] do SafeSetLength(arr, length(arr) * 2); for i := 0 to 99 do if parr[i] <> 0 then Result := False; //this will fail if AlwaysClearFreedMemory not set if not Result then SDUMessageDlg('Freed memory wiping failed'); if not Result then exit; // now test TSDUBytes fns for copying resizing etc. ... SafeSetLength(arr, 0); SafeSetLength(arr, 90); //this should zero any new data (done by delphi runtime) for i := low(arr) to high(arr) do if arr[i] <> 0 then Result := False; //and test if increasing size SafeSetLength(arr, 100); for i := 90 to high(arr) do if arr[i] <> 0 then Result := False; for i := low(arr) to High(arr) do arr[i] := i; SDUZeroBuffer(arr); // zeroises for i := 0 to 99 do if arr[i] <> 0 then Result := False; SafeSetLength(arr, 100); for i := low(arr) to High(arr) do arr[i] := i; parr := @arr[0]; SDUInitAndZeroBuffer(1, arr); // sets length and zeroises for i := 0 to 99 do if parr[i] <> 0 then Result := False; SafeSetLength(arr, 100); for i := low(arr) to High(arr) do arr[i] := i; parr := @arr[0]; SafeSetLength(arr, 10);// changes len - what fastmm doesnt do for i := 10 to 99 do if parr[i] <> 0 then Result := False; setlength(buf, 100); for i := 1 to length(buf) do buf[i] := AnsiChar(i - 1); parr := @buf[1]; SDUZeroString(buf); for i := 0 to 99 do if parr[i] <> 0 then Result := False; setlength(arr, 100); for i := low(arr) to High(arr) do arr[i] := i; parr := @arr[0]; i := 100; // resize more till get new address while parr = @arr[0] do begin SDUAddByte(arr, i); Inc(i); end; //check old data zero for i := 0 to 99 do if parr[i] <> 0 then Result := False; //check added ok for i := low(arr) to High(arr) do if arr[i] <> i then Result := False; //test SDUAddArrays setlength(arr, 100); parr := @arr[0]; setlength(arrB, 50); for i := low(arrB) to High(arrB) do arrB[i] := i + 100; SDUAddArrays(arr, arrB); // if reallocated - test zerod old array if parr <> @arr[0] then for i := 0 to 99 do if parr[i] <> 0 then Result := False; //check added ok if length(arr) <> 150 then Result := False; for i := low(arr) to High(arr) do if arr[i] <> i then Result := False; //test SDUAddLimit setlength(arr, 100); parr := @arr[0]; SDUAddLimit(arr, arrB, 10); // if reallocated - test zerod old array if parr <> @arr[0] then for i := 0 to 99 do if parr[i] <> 0 then Result := False; //check added ok if length(arr) <> 110 then Result := False; for i := low(arr) to High(arr) do if arr[i] <> i then Result := False; // test SDUDeleteFromStart parr := @arr[0]; SDUDeleteFromStart(arr, 5); // if reallocated - test zerod old array if parr <> @arr[0] then for i := 0 to 109 do if parr[i] <> 0 then Result := False; // check deleted if length(arr) <> 105 then Result := False; for i := low(arr) to High(arr) do if arr[i] <> i + 5 then Result := False; // SDUCopy // as length increasing - likely to reallocate setlength(arr, 10); parr := @arr[0]; setlength(arrB, 100); SDUCopy(arr, arrB); if parr <> @arr[0] then for i := 0 to 9 do if parr[i] <> 0 then Result := False; // check worked if length(arr) <> length(arrB) then Result := False; for i := low(arr) to High(arr) do if arr[i] <> arrB[i] then Result := False; //check length decreasing, zeros unallocated bytes setlength(arr, 100); parr := @arr[0]; setlength(arrB, 10); for i := low(arr) to High(arr) do arr[i] := i; SDUCopy(arr, arrB); //zeros newly unused bytes for i := 10 to 99 do if parr[i] <> 0 then Result := False; // check worked if length(arr) <> length(arrB) then Result := False; for i := low(arr) to High(arr) do if arr[i] <> arrB[i] then Result := False; // SDUCopyLimit is called from SDUCopy so no need to test directly if not Result then SDUMessageDlg('Freed memory wiping with TSDUBytes failed'); if not Result then exit; // test SDUXOR using diverse implementation SDUXORStr Randomize; setlength(arr, 100); setlength(arrB, 100); for i := low(arr) to High(arr) do begin arr[i] := Random(High(Byte) + 1); arrB[i] := Random(High(Byte) + 1); end; arrC := SDUXOR(arr, arrB); buf := SDUXOrStr(SDUBytesToString(arr), SDUBytesToString(arrB)); if SDUBytesToString(arrC) <> buf then Result := False; if not Result then SDUMessageDlg('SDUXOR test failed'); //timing - uses freeotfe vol with 100K iterations Result := True; //test byte array fns assert('1234' = SDUBytesToString(SDUStringToSDUBytes('1234'))); // exit; mountList := TStringList.Create(); try //for loop is optimised into reverse order, but want to process forwards vl := 0; {$IFDEF DEBUG} vol_path := ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\..\..\test_vols\'); {$ELSE} vol_path := ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\test_vols\'); {$ENDIF} while vl <= high(TEST_VOLS) do begin //test one at a time as this is normal use mountList.Clear; mountList.Add(vol_path + TEST_VOLS[vl]); mountedAs := ''; key_file := ''; if KEY_FILES[vl] <> '' then key_file := vol_path + KEY_FILES[vl]; if LES_FILES[vl] <> '' then les_file := vol_path + LES_FILES[vl]; if GetFreeOTFE().IsLUKSVolume(vol_path + TEST_VOLS[vl]) or (LES_FILES[vl] <> '') then begin if not GetFreeOTFE().MountLinux(mountList, mountedAs, True, les_file, SDUStringToSDUBytes(PASSWORDS[vl]), key_file, False, nlLF, 0, True) then Result := False; end else begin //call silently if not GetFreeOTFE().MountFreeOTFE(mountList, mountedAs, True, key_file, SDUStringToSDUBytes(PASSWORDS[vl]), OFFSET[vl], False, True, 256, ITERATIONS[vl]) then Result := False; end; if not Result then begin SDUMessageDlg( _('Unable to open ') + TEST_VOLS[vl] + '.', mtError); break; end else begin CheckMountedOK; UnMountAndCheck; end; Inc(vl); end; {test changing password backup freeotfe header ('cdb') change password open with new password restore header open with old password -tested on next test run this tests most of code for creating volume as well } //don't fail if doesnt exist SysUtils.DeleteFile(vol_path + 'a_test.cdbBackup'); if Result then BackupRestore(opBackup, vol_path + TEST_VOLS[0], vol_path + 'a_test.cdbBackup', True); Result := Result and GetFreeOTFE().WizardChangePassword(vol_path + TEST_VOLS[0], PASSWORDS[0], 'secret4', True); if Result then begin mountList.Clear; mountList.Add(vol_path + TEST_VOLS[0]); if not GetFreeOTFE().MountFreeOTFE(mountList, mountedAs, True, '', SDUStringToSDUBytes('secret4'), 0, False, True, 256, 2048) then Result := False; end; if Result then CheckMountedOK; UnmountAndCheck; if Result then BackupRestore(opRestore, vol_path + TEST_VOLS[0], vol_path + 'a_test.cdbBackup', True); { TODO -otdk -cenhance : use copied file to check is same as orig file } // no need to check mount again as will be checked with next test run Result := Result and SysUtils.DeleteFile(vol_path + 'a_test.cdbBackup'); finally mountList.Free(); end; if Result then SDUMessageDlg('All functional tests passed') else SDUMessageDlg('At least one functional test failed'); end; procedure TfrmMain.SetIconListsAndIndexes(); begin inherited; if gSettings.OptDisplayToolbarLarge then begin ToolBar1.Images := ilToolbarIcons_Large; (* tbbNew.ImageIndex := FIconIdx_Large_New; tbbMountFile.ImageIndex := FIconIdx_Large_MountFile; tbbMountPartition.ImageIndex := FIconIdx_Large_MountPartition; tbbDismount.ImageIndex := FIconIdx_Large_Dismount; tbbDismountAll.ImageIndex := FIconIdx_Large_DismountAll; tbbTogglePortableMode.ImageIndex := FIconIdx_Large_PortableMode; *) end else begin ToolBar1.Images := ilToolbarIcons_Small; //resets 'indeterminate' prop of drop downs (* tbbNew.ImageIndex := FIconIdx_Small_New; tbbMountFile.ImageIndex := FIconIdx_Small_MountFile; tbbMountPartition.ImageIndex := FIconIdx_Small_MountPartition; tbbDismount.ImageIndex := FIconIdx_Small_Dismount; tbbDismountAll.ImageIndex := FIconIdx_Small_DismountAll; tbbTogglePortableMode.ImageIndex := FIconIdx_Small_PortableMode; *) end; (* actDismountAll.ImageIndex := FIconIdx_Small_DismountAll; actFreeOTFEMountPartition.ImageIndex := FIconIdx_Small_MountPartition; actTogglePortableMode.ImageIndex := FIconIdx_Small_PortableMode; actProperties.ImageIndex := FIconIdx_Small_Properties; *) // Set icons on menuitems if (FIconIdx_Small_VistaUACShield >= 0) then begin miFreeOTFEDrivers.ImageIndex := FIconIdx_Small_VistaUACShield; miPortableModeDrivers.ImageIndex := FIconIdx_Small_VistaUACShield; actFormat.ImageIndex := FIconIdx_Small_VistaUACShield; // Splat small Vista UAC shield icon onto large *portable mode* icon // lplp - todo - Note: 22x22 "World" icon may be too small to have UAC icon on top of it? end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin OTFEFreeOTFEBase_U.SetFreeOTFEType(TOTFEFreeOTFE); // Prevent endless loops of UAC escalation... fallowUACEsclation := False; inherited; fendSessionFlag := False; fIsAppShuttingDown := False; fIconMounted := TIcon.Create(); fIconMounted.Handle := LoadImage(hInstance, PChar(R_ICON_MOUNTED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); fIconUnmounted := TIcon.Create(); fIconUnmounted.Handle := LoadImage(hInstance, PChar(R_ICON_UNMOUNTED), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); fcountPortableDrivers := -1; StatusBar_Status.SimplePanel := True; // We set these to invisible so that if they're disabled by the user // settings, it doens't flicker on them off ToolBar1.Visible := False; // Give the user a clue ToolBar1.ShowHint := True; ToolBar1.Indent := 5; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin inherited; // Note: If Settings is *not* set, this will be free'd off // in FreeOTFE.dpr if Application.ShowMainForm then begin gSettings.Free(); end; // dont need to call DestroyIcon fIconMounted.Free(); fIconUnmounted.Free(); end; procedure TfrmMain.actRefreshExecute(Sender: TObject); begin RefreshDrives(); end; procedure TfrmMain.lvDrivesResize(Sender: TObject); begin ResizeWindow(); end; procedure TfrmMain.FormResize(Sender: TObject); begin // Don't call ResizeWindow() here - it causes Windows 7 to give an error // ("System Error. Code 87") on startup if both FormResize(...) and // lvDrivesResize(...) call this, which prevents the application from // initializing properly (e.g. it won't accept drag dropped files on the GUI, // because it silently aborts before initializing that functionality) // ResizeWindow(); end; // Resize the columns in the drives list so the 2nd column fills out... procedure TfrmMain.ResizeWindow(); var tmpColumn: TListColumn; begin if lvDrives.columns.Count > 1 then begin tmpColumn := lvDrives.columns[1]; tmpColumn.Width := lvDrives.clientwidth - lvDrives.columns[0].Width - ilDriveIcons.Width; end; end; procedure TfrmMain.SetupOTFEComponent(); begin inherited; GetFreeOTFE().DefaultDriveLetter := gSettings.OptDefaultDriveLetter; GetFreeOTFE().DefaultMountAs := gSettings.OptDefaultMountAs; end; // Reload settings, setting up any components as needed procedure TfrmMain.ReloadSettings(); begin inherited; SDUSystemTrayIcon1.Tip := Application.Title; SDUClearPanel(pnlTopSpacing); SDUSystemTrayIcon1.Active := gSettings.OptSystemTrayIconDisplay; SDUSystemTrayIcon1.MinimizeToIcon := gSettings.OptSystemTrayIconMinTo; SetupHotKeys(); RefreshMRUList(); end; procedure TfrmMain.MountFiles(mountAsSystem: TDragDropFileType; filenames: TStringList; ReadOnly, forceHidden: Boolean); var i: Integer; mountedAs: DriveLetterString; msg: String; mountedOK: Boolean; prettyMountedAs: String; begin // Why was this in here?! // ReloadSettings(); AddToMRUList(filenames); if (mountAsSystem = ftFreeOTFE) then begin mountedOK := GetFreeOTFE().MountFreeOTFE(filenames, mountedAs, ReadOnly); end else if (mountAsSystem = ftLinux) then begin mountedOK := GetFreeOTFE().MountLinux(filenames, mountedAs, ReadOnly, '', nil, '', False, LINUX_KEYFILE_DEFAULT_NEWLINE, 0, False, forceHidden); end else begin mountedOK := GetFreeOTFE().Mount(filenames, mountedAs, ReadOnly); end; if not (mountedOK) then begin if (GetFreeOTFE().LastErrorCode <> OTFE_ERR_USER_CANCEL) then begin SDUMessageDlg( _('Unable to open container.') + SDUCRLF + SDUCRLF + _('Please check your keyphrase and settings, and try again.'), mtError ); end; end else begin // Mount successful prettyMountedAs := PrettyPrintDriveLetters(mountedAs); if (CountValidDrives(mountedAs) = 1) then begin msg := SDUParamSubstitute(_('Your container has been opened as drive: %1'), [prettyMountedAs]); end else begin msg := SDUParamSubstitute(_('Your containers have been opened as drives: %1'), [prettyMountedAs]); end; RefreshDrives(); if gSettings.OptPromptMountSuccessful then begin SDUMessageDlg(msg, mtInformation); end; for i := 1 to length(mountedAs) do begin if (mountedAs[i] <> #0) then begin if gSettings.OptExploreAfterMount then begin ExploreDrive(mountedAs[i]); end; AutoRunExecute(arPostMount, mountedAs[i], False); end; end; end; end; procedure TfrmMain.RefreshMRUList(); begin inherited; // Refresh menuitems... gSettings.OptMRUList.RemoveMenuItems(mmMain); gSettings.OptMRUList.InsertAfter(miFreeOTFEDrivers); gSettings.OptMRUList.RemoveMenuItems(pmSystemTray); gSettings.OptMRUList.InsertUnder(mmRecentlyMounted); mmRecentlyMounted.Visible := ((gSettings.OptMRUList.MaxItems > 0) and (gSettings.OptMRUList.Items.Count > 0)); end; procedure TfrmMain.MRUListItemClicked(mruList: TSDUMRUList; idx: Integer); begin MountFilesDetectLUKS(mruList.Items[idx], False, gSettings.OptDragDropFileType); end; // Handle files being dropped onto the form from (for example) Windows Explorer. // Files dropped onto the form should be treated as though the user is trying // to mount them as volume files procedure TfrmMain.WMDropFiles(var Msg: TWMDropFiles); var buffer: array[0..MAX_PATH] of Char; numFiles: Longint; i: Integer; filesToMount: TStringList; begin try // Bring our window to the foreground SetForeGroundWindow(self.handle); // Handle the dropped files numFiles := DragQueryFile(Msg.Drop, $FFFFFFFF, nil, 0); filesToMount := TStringList.Create(); try for i := 0 to (numFiles - 1) do begin DragQueryFile(msg.Drop, i, @buffer, sizeof(buffer)); filesToMount.Add(buffer); end; MountFilesDetectLUKS(filesToMount, False, gSettings.OptDragDropFileType); Msg.Result := 0; finally filesToMount.Free(); end; finally DragFinish(Msg.Drop); end; end; procedure TfrmMain.WMDeviceChange(var Msg: TMessage); begin RefreshDrives(); end; // Function required for close to system tray icon procedure TfrmMain.WMQueryEndSession(var msg: TWMQueryEndSession); begin // Default to allowing shutdown msg.Result := 1; fendSessionFlag := (msg.Result = 1); inherited; fendSessionFlag := (msg.Result = 1); end; // Function required for close to system tray icon procedure TfrmMain.WMEndSession(var msg: TWMEndSession); begin fendSessionFlag := msg.EndSession; end; procedure TfrmMain.DriveProperties(); var propertiesDlg: TfrmVolProperties; i: Integer; selDrives: DriveLetterString; begin selDrives := GetSelectedDrives(); for i := 1 to length(selDrives) do begin propertiesDlg := TfrmVolProperties.Create(self); try propertiesDlg.DriveLetter := selDrives[i]; // propertiesDlg.OTFEFreeOTFE := GetFreeOTFE() reeOTFE); propertiesDlg.ShowModal(); finally propertiesDlg.Free(); end; end; end; // If "isEmergency" is TRUE, the user will *not* be informed of any drives // which couldn't be dismounted function TfrmMain.DismountAll(isEmergency: Boolean = False): Boolean; var drivesRemaining: DriveLetterString; initialDrives: DriveLetterString; i: Integer; begin // Change CWD to anywhere other than a mounted drive ChangeCWDToSafeDir(); // Launch any pre-dismount executable initialDrives := GetFreeOTFE().DrivesMounted; for i := 1 to length(initialDrives) do begin AutoRunExecute(arPreDismount, initialDrives[i], isEmergency); end; GetFreeOTFE().DismountAll(isEmergency); // If it wasn't an emergency dismount, and drives are still mounted, report. drivesRemaining := GetFreeOTFE().DrivesMounted(); for i := 1 to length(initialDrives) do begin // If the drive is no longer mounted, run any post-dismount executable if (Pos(initialDrives[i], drivesRemaining) <= 0) then begin AutoRunExecute(arPostDismount, initialDrives[i], isEmergency); end; end; if (drivesRemaining <> '') then begin if not (isEmergency) then begin RefreshDrives(); ReportDrivesNotDismounted(drivesRemaining, False); end else begin // Just give it another go... Best we can do. GetFreeOTFE().DismountAll(isEmergency); end; end; RefreshDrives(); Result := (GetFreeOTFE().CountDrivesMounted <= 0); end; function TfrmMain.DismountSelected(): Boolean; var toDismount: DriveLetterString; begin // First we build up a list of drives to dismount, then we dismount them. // This is done since we can't just run through the lvDrives looking for // selected items, as they're getting removed while we walk though the list! toDismount := GetSelectedDrives(); Result := DismountDrives(toDismount, False); end; // Dismount the drives specified // This procedure *will* report drives which couldn't be mounted - regardless // of "isEmergency" function TfrmMain.DismountDrives(dismountDrives: DriveLetterString; isEmergency: Boolean): Boolean; var i: Integer; j: Integer; subVols: DriveLetterString; tmpDrv: DriveLetterChar; drivesRemaining: DriveLetterString; begin Result := True; drivesRemaining := ''; // Change CWD to anywhere other than a mounted drive ChangeCWDToSafeDir(); // Skip processing if no drives to dismount - otherwise it'll just flicker // the display if (dismountDrives <> '') then begin // Ensure that none of the drives to be dismounted contain one of the other // mounted drives // Although FreeOTFE wouldn't be able to dismount such a drive (it would // the mounted volume stored on it would have an open filehandles, so // preventing the dismount), it's clearly better to warn the user in a more // meaningful way than just "can't do it - files open" for i := 1 to length(dismountDrives) do begin tmpDrv := dismountDrives[i]; subVols := GetFreeOTFE().VolsMountedOnDrive(tmpDrv); for j := 1 to length(subVols) do begin if (Pos(subVols[j], dismountDrives) = 0) then begin // At least one of the currently mounted drives is stored on one of // the drives to be dismounted - and we're not dismounting that drive SDUMessageDlg( SDUParamSubstitute(_( 'The container currently opened as %1: must be locked before %2: can be locked'), [subVols[j], tmpDrv]), mtError ); Result := False; end; end; end; if Result then begin // Sort out dismount order, in case one drive nested within another dismountDrives := GetFreeOTFE().DismountOrder(dismountDrives); for i := 1 to length(dismountDrives) do begin tmpDrv := dismountDrives[i]; // Pre-dismount... AutoRunExecute(arPreDismount, tmpDrv, isEmergency); if GetFreeOTFE().Dismount(tmpDrv, isEmergency) then begin // Dismount OK, execute post-dismount... AutoRunExecute(arPostDismount, tmpDrv, isEmergency); end else begin drivesRemaining := drivesRemaining + tmpDrv; Result := False; end; end; if (drivesRemaining <> '') then begin RefreshDrives(); ReportDrivesNotDismounted(drivesRemaining, isEmergency); end; RefreshDrives(); end; end; end; // Warn the user that some drives remain mounted, and if the dismount attempted // wasn't an emergency dismount, then prompt the user if they want to attempt // an emergency dismount procedure TfrmMain.ReportDrivesNotDismounted(drivesRemaining: DriveLetterString; isEmergency: Boolean); var msg: String; warningOK: Boolean; forceOK: Boolean; begin msg := SDUPluralMsg(length(drivesRemaining), SDUParamSubstitute( _('Unable to dismount drive: %1'), [PrettyPrintDriveLetters(drivesRemaining)]), SDUParamSubstitute(_('Unable to dismount drives: %1'), [PrettyPrintDriveLetters(drivesRemaining)])); // If the dismount attempted was a non-emergency dismount; prompt user if // they want to attempt an emergency dismount if not (isEmergency) then begin forceOK := False; if (gSettings.OptOnNormalDismountFail = ondfPromptUser) then begin msg := msg + SDUCRLF + SDUCRLF + SDUPluralMsg( length(drivesRemaining), _('Do you wish to force a dismount on this drive?'), _('Do you wish to force a dismount on these drives?')); forceOK := SDUConfirmYN(msg); end else if (gSettings.OptOnNormalDismountFail = ondfForceDismount) then begin forceOK := True; end else // ondfCancelDismount begin // Do nothing - forceOK already set to FALSE end; if forceOK then begin warningOK := True; if gsettings.OptWarnBeforeForcedDismount then begin warningOK := SDUWarnYN(_('Warning: Emergency dismounts are not recommended') + SDUCRLF + SDUCRLF + _('Are you sure you wish to proceed?')); end; if warningOK then begin DismountDrives(drivesRemaining, True); end; end; end else begin // Dismount reporting on *was* an emergency dismount; just report remaining // drives still mounted SDUMessageDlg(msg, mtInformation, [mbOK], 0); end; end; procedure TfrmMain.lvDrivesClick(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmMain.EnableDisableControls(); var drivesSelected: Boolean; drivesMounted: Boolean; begin inherited; // The FreeOTFE object may not be active... actFreeOTFEMountPartition.Enabled := (GetFreeOTFE().Active and GetFreeOTFE().CanMountDevice()); // Linux menuitem completely disabled if not active... actLinuxMountPartition.Enabled := (miLinuxVolume.Enabled and GetFreeOTFE().CanMountDevice()); // Flags used later drivesSelected := (lvDrives.selcount > 0); drivesMounted := (lvDrives.Items.Count > 0); // Actions & menuitems to be enabled/disabled, depending on whether a drive // is selected actDismount.Enabled := drivesSelected; actProperties.Enabled := drivesSelected; miFormat.Enabled := drivesSelected; miPopupFormat.Enabled := drivesSelected; actOverwriteFreeSpace.Enabled := drivesSelected; // Note: Implies FreeOTFE drivers are running actOverwriteEntireDrive.Enabled := drivesSelected; // Note: Implies FreeOTFE drivers are running // Action item to be enabled/disabled, as long as one or more drives are // mounted actDismountAll.Enabled := drivesMounted; // Driver handling... actTogglePortableMode.Checked := (fcountPortableDrivers > 0); actTogglePortableMode.Enabled := (GetFreeOTFE().CanUserManageDrivers() or // If we're on Vista, always allow the // toggle portable mode option; the // user can escalate UAC if needed SDUOSVistaOrLater()); // If the portable mode control is enabled, but we don't know how many // drivers there are in portable mode, presumably we're running under // Vista without admin access - in which case this control just toggles the // portable mode status - and DOESN'T turn it on/off if (actTogglePortableMode.Enabled and (fcountPortableDrivers < 0)) then begin actTogglePortableMode.Caption := _('Toggle portable mode drivers'); end else begin actTogglePortableMode.Caption := _('Use portable mode drivers'); // Ensure NO ICON FOR PORTABLE MODE DRIVERS if the user is admin; it shows // a checkbox instead, depending on whether the drivers are running or not miPortableModeDrivers.ImageIndex := -1; end; // Misc display related... if drivesMounted then begin SDUSystemTrayIcon1.Icon := fIconMounted; end else begin SDUSystemTrayIcon1.Icon := fIconUnmounted; end; StatusBar_Status.Visible := gSettings.OptDisplayStatusbar; StatusBar_Hint.Visible := False; SetStatusBarTextNormal(); SetupToolbarFromSettings(); end; procedure TfrmMain.SetStatusBarTextNormal(); var drvLetter: DriveLetterChar; freeSpace: Int64; totalSpace: Int64; statusText: String; selDrives: DriveLetterString; begin statusText := ''; selDrives := GetSelectedDrives(); // Update status bar text, if visible if (StatusBar_Status.Visible or StatusBar_Hint.Visible) then begin statusText := ''; if not (GetFreeOTFE().Active) then begin statusText := _('FreeOTFE main driver not connected.'); end else if (length(selDrives) = 0) then begin statusText := SDUPluralMsg(lvDrives.Items.Count, SDUParamSubstitute(_('%1 drive mounted.'), [lvDrives.Items.Count]), SDUParamSubstitute(_('%1 drives mounted.'), [lvDrives.Items.Count])); end else if (length(selDrives) > 0) then begin if (length(selDrives) = 1) then begin drvLetter := selDrives[1]; freeSpace := DiskFree(Ord(drvLetter) - 64); totalSpace := DiskSize(Ord(drvLetter) - 64); if ((freeSpace > -1) and (totalSpace > -1)) then begin statusText := SDUParamSubstitute(_('%1: Free Space: %2; Total size: %3'), [drvLetter, SDUFormatUnits(freeSpace, SDUUnitsStorageToTextArr(), UNITS_BYTES_MULTIPLIER, 1), SDUFormatUnits(totalSpace, SDUUnitsStorageToTextArr(), UNITS_BYTES_MULTIPLIER, 1)]); end; end; if (statusText = '') then begin statusText := SDUPluralMsg(lvDrives.SelCount, SDUParamSubstitute(_('%1 drive selected.'), [length(selDrives)]), SDUParamSubstitute(_('%1 drives selected.'), [length(selDrives)])); end; end; end; SetStatusBarText(statusText); end; // Set the toolbar size procedure TfrmMain.SetupToolbarFromSettings(); //var //// toolbarWidth: Integer; // i: Integer; begin SetIconListsAndIndexes(); ToolBar1.Visible := gSettings.OptDisplayToolbar; // Toolbar captions... if gSettings.OptDisplayToolbarLarge then begin ToolBar1.ShowCaptions := gSettings.OptDisplayToolbarCaptions; end else begin ToolBar1.ShowCaptions := False; end; ToolBar1.Height := ToolBar1.Images.Height + TOOLBAR_ICON_BORDER; ToolBar1.ButtonHeight := ToolBar1.Images.Height; ToolBar1.ButtonWidth := ToolBar1.Images.Width; // if gSettings.OptDisplayToolbar then begin // // Turning captions on can cause the buttons to wrap if the window isn't big // // enough. // // This looks pretty poor, so resize the window if it's too small // toolbarWidth := 0; // for i := 0 to (Toolbar1.ButtonCount - 1) do begin // toolbarWidth := toolbarWidth + Toolbar1.Buttons[i].Width; // end; // if (toolbarWidth > self.Width) then begin // self.Width := toolbarWidth; // end; // // Adjusting the width to the sum of the toolbar buttons doens't make it wide // // enough to prevent wrapping (presumably due to window borders); nudge the // // size until it does // // (Crude, but effective) // while (Toolbar1.RowCount > 1) do begin // self.Width := self.Width + 10; // end; // end; end; function TfrmMain.GetDriveLetterFromLVItem(listItem: TListItem): DriveLetterChar; var tmpDrv: String; begin // Trim the padding whitespace off the drive letter + colon tmpDrv := listItem.Caption; tmpDrv := TrimLeft(tmpDrv); // The first letter of the item's caption is the drive letter Result := DriveLetterChar(tmpDrv[1]); end; procedure TfrmMain.lvDrivesDblClick(Sender: TObject); var driveLetter: DriveLetterChar; begin if (lvDrives.selcount > 0) then begin driveLetter := GetDriveLetterFromLVItem(lvDrives.selected); ExploreDrive(driveLetter); end; end; procedure TfrmMain.DisplayDriverControlDlg(); var UACEscalateAttempted: Boolean; begin UACEscalateAttempted := False; DeactivateFreeOTFEComponent(); try try // This is surrounded by a try...finally as it may throw an exception if // the user doesn't have sufficient privs to do this GetFreeOTFE().ShowDriverControlDlg(); // Send out a message to any other running instances of FreeOTFE to // refresh; the drivers may have changed. // Note that if we had to UAC escalate (see exception below), the UAC // escalated process will send out this windows message {$IF CompilerVersion >= 18.5} //SendMessage(HWND_BROADCAST, GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); PostMessage(HWND_BROADCAST, GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); {$ELSE} SDUPostMessageExistingApp(GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); {$IFEND} except on EFreeOTFENeedAdminPrivs do begin UACEscalateForDriverInstallation(); UACEscalateAttempted := True; end; end; finally // Note: We supress any messages that may be the result of failing to // activate the GetFreeOTFE() component activating the if we had to // UAC escalate. // In that situation, the UAC escalated process will sent out a // refresh message when it's done. ActivateFreeOTFEComponent(UACEscalateAttempted); EnableDisableControls(); end; end; procedure TfrmMain.actDriversExecute(Sender: TObject); begin DisplayDriverControlDlg(); end; function TfrmMain.ActivateFreeOTFEComponent(suppressMsgs: Boolean): Boolean; begin inherited ActivateFreeOTFEComponent(suppressMsgs); // Let Windows know whether we accept dropped files or not DragAcceptFiles(self.Handle, GetFreeOTFE().Active); Result := GetFreeOTFE().Active; end; procedure TfrmMain.ShowOldDriverWarnings(); begin { TODO 1 -otdk -cclean : dont support old drivers } // No warnings to be shown in base class if (GetFreeOTFE().Version() < FREEOTFE_ID_v03_00_0000) then begin SDUMessageDlg( SDUParamSubstitute(_( 'The main LibreCrypt driver installed on this computer dates back to FreeOTFE %1'), [GetFreeOTFE().VersionStr()]) + SDUCRLF + SDUCRLF + _( 'It is highly recommended that you upgrade your LibreCrypt drivers to v3.00 or later as soon as possible, in order to allow the use of LRW and XTS based volumes.') + SDUCRLF + SDUCRLF + _('See documentation (installation section) for instructions on how to do this.'), mtWarning ); end else if (GetFreeOTFE().Version() < FREEOTFE_ID_v04_30_0000) then begin SDUMessageDlg( SDUParamSubstitute(_( 'The main LibreCrypt driver installed on this computer dates back to FreeOTFE %1'), [GetFreeOTFE().VersionStr()]) + SDUCRLF + SDUCRLF + _( 'It is highly recommended that you upgrade your LibreCrypt drivers to those included in v4.30 or later as soon as possible, due to improvements in the main driver.') + SDUCRLF + SDUCRLF + _('See documentation (installation section) for instructions on how to do this.'), mtWarning ); end else begin inherited; end; end; procedure TfrmMain.DeactivateFreeOTFEComponent(); begin inherited; // Let Windows know we accept dropped files or not DragAcceptFiles(self.Handle, GetFreeOTFE().Active); end; // The array passed in is zero-indexed; populate elements zero to "bytesRequired" procedure TfrmMain.GenerateOverwriteData(Sender: TObject; passNumber: Integer; bytesRequired: Cardinal; var generatedOK: Boolean; var outputBlock: TShredBlock); var i: Integer; tempArraySize: Cardinal; blocksizeBytes: Cardinal; plaintext: Ansistring; cyphertext: Ansistring; IV: Ansistring; localIV: Int64; sectorID: LARGE_INTEGER; begin // Generate an array of random data containing "bytesRequired" bytes of data, // plus additional random data to pad out to the nearest multiple of the // cypher's blocksize bits // Cater for if the blocksize was -ve or zero if (ftempCypherDetails.BlockSize < 1) then begin blocksizeBytes := 1; end else begin blocksizeBytes := (ftempCypherDetails.BlockSize div 8); end; tempArraySize := bytesRequired + (blocksizeBytes - (bytesRequired mod blocksizeBytes)); // SDUInitAndZeroBuffer(tempArraySize, plaintext); plaintext := ''; for i := 1 to tempArraySize do begin plaintext := plaintext + Ansichar(random(256)); { DONE 2 -otdk -csecurity : This is not secure PRNG - but key is random, so result is CSPRNG -see faq } end; Inc(ftempCypherEncBlockNo); // Adjust the IV so that this block of encrypted pseudorandom data should be // reasonably unique IV := ''; // SDUInitAndZeroBuffer(0, IV); if (ftempCypherDetails.BlockSize > 0) then begin // SDUInitAndZeroBuffer((ftempCypherDetails.BlockSize div 8), IV); IV := StringOfChar(AnsiChar(#0), (ftempCypherDetails.BlockSize div 8)); localIV := ftempCypherEncBlockNo; for i := 1 to min(sizeof(localIV), length(IV)) do begin IV[i] := Ansichar((localIV and $FF)); localIV := localIV shr 8; end; end; // Adjust the sectorID so that this block of encrypted pseudorandom data // should be reasonably unique sectorID.QuadPart := ftempCypherEncBlockNo; // Encrypt the pseudorandom data generated if not (GetFreeOTFE().EncryptSectorData(ftempCypherDriver, ftempCypherGUID, sectorID, FREEOTFE_v1_DUMMY_SECTOR_SIZE, ftempCypherKey, IV, plaintext, cyphertext)) then begin SDUMessageDlg( _('Unable to encrypt pseudorandom data before using for overwrite buffer?!') + SDUCRLF + SDUCRLF + SDUParamSubstitute(_('Error #: %1'), [GetFreeOTFE().LastErrorCode]), mtError ); generatedOK := False; end else begin // Copy the encrypted data into the outputBlock for i := 0 to (bytesRequired - 1) do begin outputBlock[i] := Byte(cyphertext[i + 1]); end; generatedOK := True; end; end; function TfrmMain.PortableModeSet(setTo: TPortableModeAction; suppressMsgs: Boolean): Boolean; begin Result := False; if not (GetFreeOTFE().CanUserManageDrivers()) then begin // On Vista, escalate UAC if SDUOSVistaOrLater() then begin UACEscalateForPortableMode(setTo, suppressMsgs); end else begin // On pre-Vista, just let user know they can't do it if not (suppressMsgs) then begin SDUMessageDlg( TEXT_NEED_ADMIN, mtWarning, [mbOK], 0 ); end; end; end else begin case setTo of pmaStart: begin Result := _PortableModeStart(suppressMsgs); end; pmaStop: begin Result := _PortableModeStop(suppressMsgs); end; pmaToggle: begin Result := _PortableModeToggle(suppressMsgs); end; end; // In case we UAC escalated (i.e. ran a separate process to handle the // drivers), we send out a message to any other running instances of // FreeOTFE to refresh {$IF CompilerVersion >= 18.5} //SendMessage(HWND_BROADCAST, GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); PostMessage(HWND_BROADCAST, GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); {$ELSE} SDUPostMessageExistingApp(GLOBAL_VAR_WM_FREEOTFE_REFRESH, 0, 0); {$IFEND} end; end; procedure TfrmMain.GetAllDriversUnderCWD(driverFilenames: TStringList); const // Subdirs which should be searched for drivers DRIVERS_SUBDIR_32_BIT = '\x86'; DRIVERS_SUBDIR_64_BIT = '\amd64'; DRIVERS_SUBDIR_XP = '\xp_86'; var fileIterator: TSDUFileIterator; filename: String; driversDir: String; begin // Compile a list of drivers in the CWD fileIterator := TSDUFileIterator.Create(nil); try driversDir := ExtractFilePath(Application.ExeName); if SDUOS64bit() then begin driversDir := driversDir + DRIVERS_SUBDIR_64_BIT; end else begin if (SDUInstalledOS <= osWindowsXP) then begin driversDir := driversDir + DRIVERS_SUBDIR_XP; end else begin driversDir := driversDir + DRIVERS_SUBDIR_32_BIT; end; end; fileIterator.Directory := driversDir; fileIterator.FileMask := '*.sys'; fileIterator.RecurseSubDirs := False; fileIterator.OmitStartDirPrefix := False; fileIterator.IncludeDirNames := False; fileIterator.Reset(); filename := fileIterator.Next(); while (filename <> '') do begin driverFilenames.Add(filename); filename := fileIterator.Next(); end; finally fileIterator.Free(); end; end; function TfrmMain._PortableModeStart(suppressMsgs: Boolean): Boolean; var driverFilenames: TStringList; begin Result := False; driverFilenames := TStringList.Create(); try GetAllDriversUnderCWD(driverFilenames); if (driverFilenames.Count < 1) then begin if not (suppressMsgs) then begin SDUMessageDlg( _('Unable to locate any portable LibreCrypt drivers.') + SDUCRLF + SDUCRLF + _( 'Please ensure that the a copy of the LibreCrypt drivers (".sys" files) you wish to use are located in the correct directory.'), mtWarning ); end; end else begin DeactivateFreeOTFEComponent(); if GetFreeOTFE().PortableStart(driverFilenames, not (suppressMsgs)) then begin // Message commented out - it's pointless as user will know anyway because // either: // a) They started it, or // b) It's started automatically on FreeOTFE startup - in which case, it's // just annoying // if not(suppressMsgs) then // begin // SDUMessageDlg('Portable mode drivers installed and started.', mtInformation, [mbOK], 0); // end; Result := True; end else begin if not (suppressMsgs) then begin SDUMessageDlg( _('One or more of your portable LibreCrypt drivers could not be installed/started.') + SDUCRLF + SDUCRLF + TEXT_NEED_ADMIN + SDUCRLF + SDUCRLF + _( 'Please select "File | Drivers..." to check which drivers are currently operating.'), mtWarning ); end; end; end; finally driverFilenames.Free(); ActivateFreeOTFEComponent(suppressMsgs); end; end; function TfrmMain._PortableModeStop(suppressMsgs: Boolean): Boolean; var stopOK: Boolean; begin Result := False; // Note that if the component was *not* active, then we can shutdown all // portable mode drivers; if we aren't active, this implies the main driver // isn't installed/running - in which case we don't need the user to confirm // as no drives can be mounted stopOK := True; if GetFreeOTFE().Active then begin if (GetFreeOTFE().CountDrivesMounted() > 0) then begin if suppressMsgs then begin stopOK := False; end else begin stopOK := (SDUMessageDlg(_('You have one or more volumes mounted.') + SDUCRLF + SDUCRLF + _( 'If any of the currently mounted volumes makes use of any of the LibreCrypt drivers which are currently in portable mode, stopping portable mode is not advisable.') + SDUCRLF + SDUCRLF + _('It is recommended that you dismount all volumes before stopping portable mode.') + SDUCRLF + SDUCRLF + _('Do you wish to continue stopping portable mode?'), mtWarning, [mbYes, mbNo], 0) = mrYes); end; end; end; if stopOK then begin DeactivateFreeOTFEComponent(); if GetFreeOTFE().PortableStop() then begin // No point in informing user; they would have been prompted if they // wanted to do this, and they can tell they've stopped as the // application will just exit; only popping up a messagebox if there's a // problem if not fIsAppShuttingDown then begin if not (suppressMsgs) then begin SDUMessageDlg(_('Portable mode drivers stopped and uninstalled.'), mtInformation, [mbOK], 0); end; end; Result := True; end else begin if not (suppressMsgs) then begin SDUMessageDlg( _('One or more of your portable LibreCrypt drivers could not be stopped/uninstalled.') + SDUCRLF + SDUCRLF + TEXT_NEED_ADMIN + SDUCRLF + SDUCRLF + _( 'Please select "File | Drivers..." to check which drivers are currently operating.'), mtWarning ); end; end; ActivateFreeOTFEComponent(suppressMsgs); end; end; function TfrmMain._PortableModeToggle(suppressMsgs: Boolean): Boolean; var cntPortable: Integer; begin Result := False; cntPortable := GetFreeOTFE().DriversInPortableMode(); if (cntPortable < 0) then begin // We *should* be authorised to do this by the time we get here... // Do nothing; Result already set to FALSE end else if (cntPortable > 0) then begin Result := PortableModeSet(pmaStop, suppressMsgs); end else begin Result := PortableModeSet(pmaStart, suppressMsgs); end; end; procedure TfrmMain.actDismountExecute(Sender: TObject); begin DismountSelected(); end; procedure TfrmMain.actAboutExecute(Sender: TObject); var dlg: TfrmAbout; begin dlg := TfrmAbout.Create(self); try dlg.ShowModal(); finally dlg.Free(); end; end; procedure TfrmMain.actConsoleHideExecute(Sender: TObject); begin inherited; SDUSystemTrayIcon1.DoMinimizeToIcon(); end; procedure TfrmMain.actDismountAllExecute(Sender: TObject); begin DismountAll(); end; procedure TfrmMain.actPropertiesExecute(Sender: TObject); begin DriveProperties(); end; // Function required for both close and minimize to system tray icon procedure TfrmMain.actExitExecute(Sender: TObject); begin // Either: // Application.Terminate(); // Or: fendSessionFlag := True; Close(); end; // Function required for both close and minimize to system tray icon procedure TfrmMain.actConsoleDisplayExecute(Sender: TObject); begin SDUSystemTrayIcon1.DoRestore(); end; procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var userConfirm: Word; oldActive: Boolean; closingDrivesMounted: Integer; begin CanClose := True; closingDrivesMounted := 0; // This code segment is required to handle the case when Close() is called // programatically // Only carry out this action if closing to SystemTrayIcon // Note the MainForm test; if it was not the main form, setting Action would // in FormClose would do the minimise if (not (fendSessionFlag) and gSettings.OptSystemTrayIconDisplay and gSettings.OptSystemTrayIconCloseTo and {$IF CompilerVersion >= 18.5} ( // If Application.MainFormOnTaskbar is set, use the form name, // otherwise check exactly (Application.MainFormOnTaskbar and (application.mainform <> nil) and (application.mainform.Name = self.Name)) or (not (Application.MainFormOnTaskbar) and // (application.mainform = self) (application.mainform <> nil) and (application.mainform.Name = self.Name))) {$ELSE} (Application.MainForm = self) {$IFEND} ) then begin CanClose := False; actConsoleHide.Execute(); end; if (CanClose) then begin oldActive := GetFreeOTFE().Active; // We (quite reasonably) assume that if the FreeOTFE component is *not* // active, and we can't activate it, then no FreeOTFE volumes are mounted if not (GetFreeOTFE().Active) then begin // Prevent any warnings... fIsAppShuttingDown := True; ActivateFreeOTFEComponent(False); // Reset flag fIsAppShuttingDown := False; end; if (GetFreeOTFE().Active) then begin if (GetFreeOTFE().CountDrivesMounted() > 0) then begin userConfirm := mrNo; if (gSettings.OptOnExitWhenMounted = oewmPromptUser) then begin userConfirm := SDUMessageDlg(_('One or more volumes are still mounted.') + SDUCRLF + SDUCRLF + _( 'Do you wish to dismount all volumes before exiting?'), mtConfirmation, [mbYes, mbNo, mbCancel], 0); end else if (gSettings.OptOnExitWhenMounted = oewmDismount) then begin userConfirm := mrYes; end else // oewmLeaveMounted begin // Do nothing - userConfirm already set to mrNo end; if (userConfirm = mrCancel) then begin CanClose := False; end else if (userConfirm = mrYes) then begin CanClose := DismountAll(); end else begin // CanClose already set to TRUE; do nothing end; end; closingDrivesMounted := GetFreeOTFE().CountDrivesMounted(); end; // if (GetFreeOTFE().Active) then if not (oldActive) then begin // Prevent any warnings... fIsAppShuttingDown := True; DeactivateFreeOTFEComponent(); // Reset flag fIsAppShuttingDown := False; end; end; if (CanClose) then begin // If there's no drives mounted, and running in portable mode, prompt for // portable mode shutdown if ((closingDrivesMounted <= 0) and (GetFreeOTFE().DriversInPortableMode() > 0)) then begin userConfirm := mrNo; if (gSettings.OptOnExitWhenPortableMode = oewpPromptUser) then begin userConfirm := SDUMessageDlg( _('One or more of the LibreCrypt drivers are running in portable mode.') + SDUCRLF + SDUCRLF + _('Do you wish to shutdown portable mode before exiting?'), mtConfirmation, [mbYes, mbNo, mbCancel], 0); end else if (gSettings.OptOnExitWhenPortableMode = owepPortableOff) then begin userConfirm := mrYes; end else // oewpDoNothing begin // Do nothing - userConfirm already set to mrNo end; if (userConfirm = mrCancel) then begin CanClose := False; end else if (userConfirm = mrYes) then begin fIsAppShuttingDown := True; CanClose := PortableModeSet(pmaStop, False); fIsAppShuttingDown := CanClose; end else begin CanClose := True; end; end; end; // if (CanClose) then if CanClose then begin ShutdownPKCS11(); SDUSystemTrayIcon1.Active := False; DestroySysTrayIconMenuitems(); Application.ProcessMessages(); Application.UnhookMainWindow(MessageHook); GetFreeOTFE().Active := False; end else begin // Reset flag in case user clicked "Cancel" on tany of the above prompts... fendSessionFlag := False; end; end; // Function required for close to system tray icon // Note: This is *only* required in your application is you intend to call // Close() to hide/close the window. Calling Hide() instead is preferable procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin // This code segment is required to handle the case when Close() is called // programatically // Only carry out this action if closing to SystemTrayIcon // Note the MainForm test; if it was the main form, setting Action would have // no effect if (not (fendSessionFlag) and gSettings.OptSystemTrayIconDisplay and gSettings.OptSystemTrayIconCloseTo and {$IF CompilerVersion >= 18.5} ( // If Application.MainFormOnTaskbar is set, use the form name, // otherwise check exactly (Application.MainFormOnTaskbar and (application.mainform <> nil) and (application.mainform.Name = self.Name)) or (not (Application.MainFormOnTaskbar) and // (application.mainform <> self) (application.mainform <> nil) and (application.mainform.Name = self.Name))) {$ELSE} (Application.MainForm <> self) {$IFEND} ) then begin Action := caMinimize; end; // log closed OK if Action in [caHide, caFree] then begin gSettings.feAppRunning := arClosed; gSettings.Save(false); end; end; // This is used to ensure that only one copy of FreeOTFE is running at any // given time function TfrmMain.MessageHook(var msg: TMessage): Boolean; var hotKeyMsg: TWMHotKey; begin Result := False; if (msg.Msg = GLOBAL_VAR_WM_FREEOTFE_RESTORE) then begin // Restore application actConsoleDisplay.Execute(); msg.Result := 0; Result := True; end else if (msg.Msg = GLOBAL_VAR_WM_FREEOTFE_REFRESH) then begin actRefreshExecute(nil); msg.Result := 0; Result := True; end else if (msg.Msg = WM_HOTKEY) then begin // Hotkey window message handler hotKeyMsg := TWMHotKey(msg); if GetFreeOTFE().Active then begin if (hotKeyMsg.HotKey = HOTKEY_IDENT_DISMOUNT) then begin // We'll allow errors in dismount to be reported to the user; it's just // a normal dismount DismountAll(False); end else if (hotKeyMsg.HotKey = HOTKEY_IDENT_DISMOUNTEMERG) then begin // Panic! The user pressed the emergency dismount hotkey! Better not // report any errors to the user DismountAll(True); end; end; if ((hotKeyMsg.HotKey = HOTKEY_IDENT_DISMOUNT) or (hotKeyMsg.HotKey = HOTKEY_IDENT_DISMOUNTEMERG)) then begin msg.Result := 0; Result := True; end; end; end; procedure TfrmMain.miToolsClick(Sender: TObject); begin inherited; end; // Cleardown and setup hotkeys procedure TfrmMain.SetupHotKeys(); begin // Don't attempt to setup hotkeys until *after* InitApp(...) is called - this // prevents any attempt at registering the hotkeys until FreeOTFE is going to // continue running (i.e. it's not just been started with commandline // options, and will exit shortly once they've been processed) if finitAppCalled then begin // Cleardown any existing hotkeys... DisableHotkey(HOTKEY_IDENT_DISMOUNT); DisableHotkey(HOTKEY_IDENT_DISMOUNTEMERG); // ...And setup hotkeys again if gSettings.OptHKeyEnableDismount then begin EnableHotkey( gSettings.OptHKeyKeyDismount, HOTKEY_IDENT_DISMOUNT ); end; if gSettings.OptHKeyEnableDismountEmerg then begin EnableHotkey( gSettings.OptHKeyKeyDismountEmerg, HOTKEY_IDENT_DISMOUNTEMERG ); end; end; end; // Enable the specified shortcut as a hotkey, which will callback using the // given identifier procedure TfrmMain.EnableHotkey(hotKey: TShortCut; hotKeyIdent: Integer); var modifiers: Integer; vk: Word; shiftState: TShiftState; toEarlyToDetectOtherInstance: Boolean; msg: String; msgType: TMsgDlgType; begin if (hotkey = TextToShortCut(HOTKEY_TEXT_NONE)) then begin DisableHotkey(hotkeyIdent); end else begin // Obtain the virtual keycode and shiftState ShortCutToKey(hotkey, vk, shiftState); // Convet TShiftState into a modifier value for RegisterHotKey modifiers := 0; if (ssCtrl in shiftState) then begin modifiers := modifiers or MOD_CONTROL; end; if (ssAlt in shiftState) then begin modifiers := modifiers or MOD_ALT; end; if (ssShift in shiftState) then begin modifiers := modifiers or MOD_SHIFT; end; DisableHotkey(hotkeyIdent); if not (RegisterHotkey(Application.Handle, hotkeyIdent, modifiers, vk)) then begin // If FreeOTFE's already running, assume that the other instance has // already registered (taken) the hotkey {$IF CompilerVersion >= 18.5} // See SDUGeneral._SDUDetectExistWindowDetails_ThisClassHandle(...) // - if this is set, then SDUDetectExistingApp(...) don't be able to // detect any other running instance yet // Vista fix for Delphi 2007 and later toEarlyToDetectOtherInstance := False; if ((Application.Mainform = nil) and // Yes, "=" is correct here Application.MainFormOnTaskbar) then begin toEarlyToDetectOtherInstance := True; end; {$ELSE} toEarlyToDetectOtherInstance := False; {$IFEND} if not (toEarlyToDetectOtherInstance) then begin msg := Format(_('Error: Unable to assign hotkey %s'), [ShortCutToText(hotkey)]); msgType := mtError; // It's not too early to detect other running instances, and there's // no other instances detected - so warn user the hotkey couldn't be // registered // // NOTE: THIS IS DEBATABLE - If *this* instance can't registered the // hotkey due to another instance having already registered it, // then the first instance is exited - the user has no hotkey // support. On that basis, the user *should* be warned here - // and the other instance detection should be removed. // // Because of this, we add a message to the warning if another instance // was running if (SDUDetectExistingApp() > 0) then begin msg := msg + SDUCRLF + SDUCRLF + _('Another instance of LibreCrypt is running - the hotkey may already be assigned to that instance.'); msgType := mtWarning; end; SDUMessageDlg(msg, msgType); end; end; end; end; // Disable the hotkey with the specifid identifier procedure TfrmMain.DisableHotkey(hotKeyIdent: Integer); begin UnRegisterHotkey(Application.Handle, hotkeyIdent); end; function TfrmMain.IsTestModeOn: Boolean; var s: TStringList; r: Cardinal; begin Result := False; s := TStringList.Create(); try r := SDUWinExecAndWaitOutput(SDUGetWindowsDirectory() + '\sysnative\bcdedit.exe', s, SDUGetWindowsDirectory()); if r <> $FFFFFFFF then begin Result := s.IndexOf('testsigning Yes') <> -1; end else begin SDUMessageDlg(_('Getting Test Mode status failed: ') + SysErrorMessage(GetLastError), mtError, [mbOK], 0); end; finally s.Free; end; end; function TfrmMain.SetTestMode(silent, setOn: Boolean): Boolean; begin inherited; { run bcdedit.exe /set TESTSIGNING ON see https://stackoverflow.com/questions/16827229/file-not-found-error-launching-system32-winsat-exe-using-process-start for 'sysnative' this will change if built as 64 bit exe "Alternatively, if you build your program as x64, you can leave the path as c:\windows\system32" } // could also use SDUWow64DisableWow64FsRedirection Result := SDUWinExecAndWait32(SDUGetWindowsDirectory() + '\sysnative\bcdedit.exe /set TESTSIGNING ' + IfThen(setOn, 'ON', 'OFF'), SW_SHOWNORMAL) <> $FFFFFFFF; //is this necesary? if Result and setOn then Result := SDUWinExecAndWait32(SDUGetWindowsDirectory() + '\sysnative\bcdedit.exe /set loadoptions DDISABLE_INTEGRITY_CHECKS', SW_SHOWNORMAL) <> $FFFFFFFF; if Result and not setOn then Result := SDUWinExecAndWait32(SDUGetWindowsDirectory() + '\sysnative\bcdedit.exe /deletevalue loadoptions', SW_SHOWNORMAL) <> $FFFFFFFF; if not silent then begin if not Result then begin SDUMessageDlg(_('Set Test Mode failed: ') + SysErrorMessage(GetLastError), mtError, [mbOK], 0); end else begin if setOn then SDUMessageDlg(_('Please reboot. After rebooting the LibreCrypt drivers may be loaded'), mtInformation, [mbOK], 0) else SDUMessageDlg(_('After rebooting Test Mode will be off'), mtInformation, [mbOK], 0); end; end; end; //function TfrmMain.SetInstalled(): Boolean; //begin // inherited; // //needs to be place to save to // if gSettings.OptSaveSettings = slNone then // gSettings.OptSaveSettings := slProfile;//exe not supported in win >NT // // gSettings.OptInstalled := True; // Result := gSettings.Save();//todo:needed? //end; procedure TfrmMain.actTestModeOffExecute(Sender: TObject); var SigningOS: Boolean; begin inherited; SigningOS := (SDUOSVistaOrLater() and SDUOS64bit()); if SigningOS then SetTestMode(False, False) else SDUMessageDlg(_('This version of Windows does not support test mode'), mtError, [mbOK], 0); end; procedure TfrmMain.actTestModeOnExecute(Sender: TObject); var SigningOS: Boolean; begin inherited; SigningOS := (SDUOSVistaOrLater() and SDUOS64bit()); if SigningOS then SetTestMode(False, True) else SDUMessageDlg(_('There is no need to set test mode on this version of Windows'), mtError, [mbOK], 0); end; procedure TfrmMain.actTogglePortableModeExecute(Sender: TObject); begin if (actTogglePortableMode.Enabled and (fcountPortableDrivers < 0)) then begin PortableModeSet(pmaToggle, False); end else if actTogglePortableMode.Checked then begin PortableModeSet(pmaStop, False); end else begin PortableModeSet(pmaStart, False); end; fcountPortableDrivers := GetFreeOTFE().DriversInPortableMode(); EnableDisableControls(); end; procedure TfrmMain.lvDrivesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin EnableDisableControls(); end; procedure TfrmMain.actFormatExecute(Sender: TObject); var selDrives: DriveLetterString; begin selDrives := GetSelectedDrives(); Format_drive(selDrives, self); RefreshDrives(); end; procedure TfrmMain.actOptionsExecute(Sender: TObject); var dlg: TfrmOptions; begin inherited; dlg := TfrmOptions.Create(self); try if (dlg.ShowModal() = mrOk) then begin ReloadSettings(); EnableDisableControls(); end; finally dlg.Free(); end; end; procedure TfrmMain.actOverwriteEntireDriveExecute(Sender: TObject); var selectedDrive: DriveLetterString; selDrives: DriveLetterString; begin selDrives := GetSelectedDrives(); if (length(selDrives) > 1) then begin SDUMessageDlg( _('Due to the destructive nature of overwriting entire drives, only one drive may be selected when this option is chosen.') + SDUCRLF + SDUCRLF + _('Please ensure that only one mounted drive is selected, and retry.') ); end else begin selectedDrive := selDrives[1]; if SDUWarnYN(_('WARNING!') + SDUCRLF + SDUCRLF + SDUParamSubstitute( _('You are attempting to overwrite drive: %1:'), [selectedDrive]) + SDUCRLF + SDUCRLF + SDUParamSubstitute( _('THIS WILL DESTROY ALL INFORMATION STORED ON DRIVE %1:, and require it to be reformatted'), [selectedDrive]) + SDUCRLF + SDUCRLF + _( 'Are you ABSOLUTELY SURE you want to do this?')) then begin OverwriteDrives(selectedDrive, True); end; end; end; procedure TfrmMain.actOverwriteFreeSpaceExecute(Sender: TObject); var selDrives: DriveLetterString; begin selDrives := GetSelectedDrives(); OverwriteDrives(selDrives, False); end; // overwriteEntireDrive - Set to TRUE to overwrite the entire drive; this will // destroy all data on the drive, and requiring it to be // reformatted. Set to FALSE to simply overwrite the // free space on the drive procedure TfrmMain.OverwriteDrives(drives: DriveLetterString; overwriteEntireDrive: Boolean); var shredder: TShredder; i: Integer; currDrive: DriveLetterChar; frmOverWriteMethod: TfrmSelectOverwriteMethod; overwriteWithEncryptedData: Boolean; allOK: Boolean; getRandomBits: Integer; randomBuffer: array of Byte; overwriteOK: TShredResult; currDriveDevice: String; failMsg: String; MouseRNGDialog1: TMouseRNGDialog; begin overwriteOK := srSuccess; allOK := False; overwriteWithEncryptedData := False; frmOverWriteMethod := TfrmSelectOverwriteMethod.Create(self); try frmOverWriteMethod.OTFEFreeOTFEObj := GetFreeOTFE(); if (frmOverWriteMethod.ShowModal() = mrOk) then begin allOK := True; overwriteWithEncryptedData := frmOverWriteMethod.OverwriteWithEncryptedData; if (overwriteWithEncryptedData) then begin ftempCypherDriver := frmOverWriteMethod.CypherDriver; ftempCypherGUID := frmOverWriteMethod.CypherGUID; GetFreeOTFE().GetSpecificCypherDetails(ftempCypherDriver, ftempCypherGUID, ftempCypherDetails); // Initilize zeroed IV for encryption ftempCypherEncBlockNo := 0; // Get *real* random data for encryption key getRandomBits := 0; if (ftempCypherDetails.KeySizeRequired < 0) then begin // -ve keysize = arbitary keysize supported - just use 512 bits getRandomBits := 512; end else if (ftempCypherDetails.KeySizeRequired > 0) then begin // +ve keysize = specific keysize - get sufficient bits getRandomBits := ftempCypherDetails.KeySizeRequired; end; MouseRNGDialog1 := TMouseRNGDialog.Create(); try { TODO 1 -otdk -cenhance : use cryptoapi etc if avail } if (getRandomBits > 0) then begin MouseRNGDialog1.RequiredBits := getRandomBits; allOK := MouseRNGDialog1.Execute(); end; if (allOK) then begin SetLength(randomBuffer, (getRandomBits div 8)); MouseRNGDialog1.RandomData(getRandomBits, randomBuffer); for i := low(randomBuffer) to high(randomBuffer) do begin SDUAddByte(ftempCypherKey, randomBuffer[i]); // Overwrite the temp buffer... randomBuffer[i] := random(256); end; SetLength(randomBuffer, 0); end; finally MouseRNGDialog1.Free; end; end; end; finally frmOverWriteMethod.Free(); end; if (allOK) then begin if SDUConfirmYN(_('Overwriting on a large container may take a while.') + SDUCRLF + SDUCRLF + _('Are you sure you wish to proceed?')) then begin shredder := TShredder.Create(nil); try shredder.IntMethod := smPseudorandom; shredder.IntPasses := 1; if overwriteWithEncryptedData then begin // Note: Setting this event overrides shredder.IntMethod shredder.OnOverwriteDataReq := GenerateOverwriteData; end else begin shredder.OnOverwriteDataReq := nil; end; for i := 1 to length(drives) do begin currDrive := drives[i]; if overwriteEntireDrive then begin currDriveDevice := '\\.\' + currDrive + ':'; shredder.DestroyDevice(currDriveDevice, False, False); overwriteOK := shredder.LastIntShredResult; end else begin overwriteOK := shredder.OverwriteDriveFreeSpace(currDrive, False); end; end; if (overwriteOK = srSuccess) then begin SDUMessageDlg(_('Overwrite operation complete.'), mtInformation); if overwriteEntireDrive then begin SDUMessageDlg(_( 'Please reformat the drive just overwritten before attempting to use it.'), mtInformation); end; end else if (overwriteOK = srError) then begin failMsg := _('Overwrite operation FAILED.'); if not (overwriteEntireDrive) then begin failMsg := failMsg + SDUCRLF + SDUCRLF + _('Did you remember to format this drive first?'); end; SDUMessageDlg(failMsg, mtError); end else if (overwriteOK = srUserCancel) then begin SDUMessageDlg(_('Overwrite operation cancelled by user.'), mtInformation); end else begin SDUMessageDlg(_('No drives selected to overwrite?'), mtInformation); end; finally shredder.Free(); end; end; // if (SDUMessageDlg( end; // if (allOK) then ftempCypherDriver := ''; ftempCypherGUID := StringToGUID('{00000000-0000-0000-0000-000000000000}'); SDUZeroBuffer(ftempCypherKey); // ftempCypherKey := ''; ftempCypherEncBlockNo := 0; end; procedure TfrmMain.tbbTogglePortableModeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // This is ugly, but required since if the button is clicked on, and the // operation cancelled, the button pops up - even though it shouldn't! tbbTogglePortableMode.down := (fcountPortableDrivers > 0); end; // Handle "/portable" command line // Returns: Exit code function TfrmMain.HandleCommandLineOpts_Portable(): eCmdLine_Exit; var paramValue: String; begin Result := ceSUCCESS; if SDUCommandLineParameter(CMDLINE_PORTABLE, paramValue) then begin Result := ceINVALID_CMDLINE; if (uppercase(paramValue) = uppercase(CMDLINE_TOGGLE)) then begin if PortableModeSet(pmaToggle, SDUCommandLineSwitch(CMDLINE_SILENT)) then begin Result := ceSUCCESS; end else begin Result := ceUNABLE_TO_START_PORTABLE_MODE; end; end else if ((uppercase(paramValue) = uppercase(CMDLINE_START)) or (uppercase(paramValue) = uppercase(CMDLINE_ON)) or (paramValue = '1')) then begin if PortableModeSet(pmaStart, SDUCommandLineSwitch(CMDLINE_SILENT)) then begin Result := ceSUCCESS; end else begin Result := ceUNABLE_TO_START_PORTABLE_MODE; end; end else if ((uppercase(paramValue) = uppercase(CMDLINE_STOP)) or (uppercase(paramValue) = uppercase(CMDLINE_OFF)) or (paramValue = '0')) then begin if PortableModeSet(pmaStop, SDUCommandLineSwitch(CMDLINE_SILENT)) then begin Result := ceSUCCESS; end else begin Result := ceUNABLE_TO_STOP_PORTABLE_MODE; end; end; end; end; // install all drivers // // !! IMPORTANT !! // NOTICE: THIS DOES NOT CARRY OUT ANY UAC ESCALATION! // User should use "runas LibreCrypt.exe ..." if UAC escalation // required // !! IMPORTANT !! // // Returns: exit code function TfrmMain.InstallAllDrivers(driverControlObj: TDriverControl; silent: Boolean): eCmdLine_Exit; var driverFilenames: TStringList; begin try Result := ceUNKNOWN_ERROR; if not IsTestModeOn then begin SDUMessageDlg( _('The LibreCrypt drivers canot be installed as ''Test Mode'' is not enabled, please see the documentation on manually enabling Windows Test Mode.'), mtError ); end else begin driverFilenames := TStringList.Create(); try GetAllDriversUnderCWD(driverFilenames); if (driverFilenames.Count <= 0) then begin Result := ceFILE_NOT_FOUND; end else begin Result := ceSUCCESS; { from delphi 7 project:"If under Vista x64, don't autostart the drivers after installing - this could cause a bunch of *bloody* *stupid* warning messages about "unsigned drivers" to be displayed by the OS" apparently on vista is not necesary to set test mode - but need to start drivers on os start. test mode is set anyway for all OS's so start drivers now whatever // vista64Bit := (SDUOSVistaOrLater() and SDUOS64bit()); } if driverControlObj.InstallMultipleDrivers(driverFilenames, False, not silent, True// not(vista64Bit) ) then begin { from delphi 7 project:"If Vista x64, we tell the user to reboot. That way, the drivers will be started up on boot - and the user won't actually see any stupid warning messages about "unsigned drivers" " } if ( // vista64Bit and not (silent)) then begin SDUMessageDlg( _('LibreCrypt drivers have been installed successfully.'), mtInformation ); end; end else begin Result := ceUNKNOWN_ERROR; end; end; finally driverFilenames.Free(); end; end; except on EFreeOTFENeedAdminPrivs do begin Result := ceADMIN_PRIVS_NEEDED; end; end; end; // Handle "/install" command line // // !! IMPORTANT !! // NOTICE: THIS DOES NOT CARRY OUT ANY UAC ESCALATION! // User should use "runas LibreCrypt.exe ..." if UAC escalation // required // !! IMPORTANT !! // // Returns: Exit code function TfrmMain.HandleCommandLineOpts_DriverControl_Install( driverControlObj: TDriverControl): eCmdLine_Exit; var paramValue: String; driverPathAndFilename: String; silent: Boolean; // vista64Bit: boolean; begin Result := ceINVALID_CMDLINE; if SDUCommandLineParameter(CMDLINE_FILENAME, paramValue) then begin silent := SDUCommandLineSwitch(CMDLINE_SILENT); if (uppercase(trim(paramValue)) = uppercase(CMDLINE_ALL)) then begin Result := InstallAllDrivers(driverControlObj, silent); end else begin // Convert any relative path to absolute driverPathAndFilename := SDURelativePathToAbsolute(paramValue); // Ensure driver file actually exists(!) if not (fileexists(driverPathAndFilename)) then begin Result := ceFILE_NOT_FOUND; end else begin Result := ceUNKNOWN_ERROR; if driverControlObj.InstallSetAutoStartAndStartDriver(paramValue) then begin Result := ceSUCCESS; end; end; end; end; end; // Handle "/uninstall" command line // // !! IMPORTANT !! // NOTICE: THIS DOES NOT CARRY OUT ANY UAC ESCALATION! // User should use "runas LibreCrypt.exe ..." if UAC escalation // required // !! IMPORTANT !! // // Returns: Exit code function TfrmMain.HandleCommandLineOpts_DriverControl_Uninstall( driverControlObj: TDriverControl): eCmdLine_Exit; var paramValue: String; driveUninstallResult: DWORD; // vista64Bit: boolean; begin Result := ceINVALID_CMDLINE; if SDUCommandLineParameter(CMDLINE_DRIVERNAME, paramValue) then begin Result := ceUNKNOWN_ERROR; if (uppercase(trim(paramValue)) = uppercase(CMDLINE_ALL)) then begin Result := ceSUCCESS; // vista64Bit := (SDUOSVistaOrLater() and SDUOS64bit()); // set test mode off // if vista64Bit then if not SetTestMode(true,false) then cmdExitCode := ceUNKNOWN_ERROR; if not driverControlObj.UninstallAllDrivers(False) then begin Result := ceUNKNOWN_ERROR; end; end else begin driveUninstallResult := driverControlObj.UninstallDriver(paramValue); if ((driveUninstallResult and DRIVER_BIT_SUCCESS) = DRIVER_BIT_SUCCESS) then begin Result := ceSUCCESS; end; end; end; end; // Returns: Exit code function TfrmMain.HandleCommandLineOpts_DriverControl_GUI(): eCmdLine_Exit; begin actDriversExecute(nil); Result := ceSUCCESS; end; function TfrmMain.HandleCommandLineOpts_DriverControl(): eCmdLine_Exit; var paramValue: String; driverControlObj: TDriverControl; begin Result := ceSUCCESS; try if SDUCommandLineParameter(CMDLINE_DRIVERCONTROL, paramValue) then begin Result := ceINVALID_CMDLINE; // Special case; this one can UAC escalate if (uppercase(paramValue) = uppercase(CMDLINE_GUI)) then begin Result := HandleCommandLineOpts_DriverControl_GUI(); end else begin // Creating this object needs admin privs; if the user doesn't have // these, it'll raise an exception driverControlObj := TDriverControl.Create(); try driverControlObj.Silent := SDUCommandLineSwitch(CMDLINE_SILENT); // This first test is redundant if (uppercase(paramValue) = uppercase(CMDLINE_GUI)) then begin Result := HandleCommandLineOpts_DriverControl_GUI(); end else if (uppercase(paramValue) = uppercase(CMDLINE_COUNT)) then begin Result := eCmdLine_Exit(HandleCommandLineOpts_DriverControl_Count(driverControlObj)); end else if (uppercase(paramValue) = uppercase(CMDLINE_INSTALL)) then begin Result := HandleCommandLineOpts_DriverControl_Install(driverControlObj); end else if (uppercase(paramValue) = uppercase(CMDLINE_UNINSTALL)) then begin Result := HandleCommandLineOpts_DriverControl_Uninstall(driverControlObj); end; finally driverControlObj.Free(); end; end; end; except on E: EFreeOTFENeedAdminPrivs do begin Result := ceADMIN_PRIVS_NEEDED; end; end; end; // Handle "/install" command line // Returns: Exit code function TfrmMain.HandleCommandLineOpts_DriverControl_Count( driverControlObj: TDriverControl): Integer; var paramValue: String; begin Result := Integer(ceINVALID_CMDLINE); // If "/type" not specified, default to the total if not (SDUCommandLineParameter(CMDLINE_TYPE, paramValue)) then begin paramValue := CMDLINE_TOTAL; end; if (uppercase(paramValue) = uppercase(CMDLINE_TOTAL)) then begin Result := driverControlObj.CountDrivers(); end else if (uppercase(paramValue) = uppercase(CMDLINE_DRIVERSPORTABLE)) then begin Result := driverControlObj.CountDrivers(True); end else if (uppercase(paramValue) = uppercase(CMDLINE_DRIVERSINSTALLED)) then begin Result := driverControlObj.CountDrivers(False); end; end; // Handle "/count" command line // Returns: Exit code function TfrmMain.HandleCommandLineOpts_Count(): eCmdLine_Exit; begin Result := ceSUCCESS; if SDUCommandLineSwitch(CMDLINE_COUNT) then begin if not (EnsureOTFEComponentActive) then Result := ceUNABLE_TO_CONNECT else Result := eCmdLine_Exit(GetFreeOTFE().CountDrivesMounted()); end; end; { Handle "/settestmode" command line // Returns: Exit code // call if CMDLINE_SET_TESTMODE is set or not - does check itself } function TfrmMain.HandleCommandLineOpts_SetTestMode(): eCmdLine_Exit; var setOn: Boolean; SigningOS, silent: Boolean; paramValue: String; begin Result := ceSUCCESS; if SDUCommandLineParameter(CMDLINE_SET_TESTMODE, paramValue) then begin setOn := False; if (uppercase(paramValue) = uppercase(CMDLINE_ON)) then setOn := True else if (uppercase(paramValue) <> uppercase(CMDLINE_OFF)) then Result := ceINVALID_CMDLINE; if Result = ceSUCCESS then begin SigningOS := (SDUOSVistaOrLater() and SDUOS64bit()); silent := SDUCommandLineSwitch(CMDLINE_SILENT); if SigningOS then begin if not SetTestMode(silent, setOn) then Result := ceUNABLE_TO_SET_TESTMODE; end else begin if not silent then SDUMessageDlg(_('This version of Windows does not support test mode'), mtError, [mbOK], 0); end; end; end; end; { Handle "/SetInstalled" command // Returns: Exit code } //function TfrmMain.HandleCommandLineOpts_SetInstalled(): eCmdLine_Exit; //begin // Result := ceSUCCESS; // // if SDUCommandLineSwitch(CMDLINE_SET_INSTALLED) then begin // // if not SetInstalled() then // Result := ceUNABLE_TO_SET_INSTALLED; // end; //end; // Handle "/create" command line // Returns: Exit code function TfrmMain.HandleCommandLineOpts_Create(): eCmdLine_Exit; begin Result := ceSUCCESS; if SDUCommandLineSwitch(CMDLINE_CREATE) then begin if not (EnsureOTFEComponentActive) then Result := ceUNABLE_TO_CONNECT else if GetFreeOTFE().CreateFreeOTFEVolumeWizard() then Result := ceSUCCESS else Result := ceUNKNOWN_ERROR; end; end; // Handle "/unmount" command line // Returns: Exit code function TfrmMain.HandleCommandLineOpts_Dismount(): eCmdLine_Exit; var paramValue: String; force: Boolean; drive: Char; dismountOK: Boolean; begin Result := ceSUCCESS; if SDUCommandLineParameter(CMDLINE_DISMOUNT, paramValue) then begin if not (EnsureOTFEComponentActive) then Result := ceUNABLE_TO_CONNECT else begin force := SDUCommandLineSwitch(CMDLINE_FORCE); if (uppercase(paramValue) = uppercase(CMDLINE_ALL)) then begin dismountOK := (GetFreeOTFE().DismountAll(force) = ''); end else begin // Only use the 1st char... drive := paramValue[1]; dismountOK := GetFreeOTFE().Dismount(drive, force); end; if dismountOK then begin Result := ceSUCCESS; end else begin Result := ceUNABLE_TO_DISMOUNT; end; end; end; end; // Handle any command line options; returns TRUE if command line options // were passed through, and "/noexit" wasn't specified as a command line // parameter function TfrmMain.HandleCommandLineOpts(out cmdExitCode: eCmdLine_Exit): Boolean; var ignoreParams: Integer; settingsFile: String; begin cmdExitCode := ceSUCCESS; fallowUACEsclation := not (SDUCommandLineSwitch(CMDLINE_NOUACESCALATE)); // todo: a lot of repetition here bc HandleCommandLineOpts_ fns also call SDUCommandLineParameter //todo -otdk: 'else' statements mean one cmd per call - allow compatible ones at same time //these cmds at least are independent of others cmdExitCode := HandleCommandLineOpts_SetTestMode(); if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_EnableDevMenu(); // // if cmdExitCode = ceSUCCESS then // cmdExitCode := HandleCommandLineOpts_SetInstalled(); // Driver control dialog if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_DriverControl(); // Portable mode on/off... if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_Portable(); // All command line options below require FreeOTFE to be active before they // can be used if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_Count(); if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_Create(); if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_Mount(); if cmdExitCode = ceSUCCESS then cmdExitCode := HandleCommandLineOpts_Dismount(); if GetFreeOTFE().Active then DeactivateFreeOTFEComponent(); if cmdExitCode = ceADMIN_PRIVS_NEEDED then MessageDlg('Administrator privileges are needed. Please run again as adminisrator', mtError, [mbOK], 0); // Notice: CMDLINE_MINIMIZE handled in the .dpr // Return TRUE if there were no parameters specified on the command line // and "/noexit" wasn't specified // Note: Disregard any CMDLINE_SETTINGSFILE and parameter // Note: Also disregard any CMDLINE_MINIMIZE and parameter Result := False; if not (SDUCommandLineSwitch(CMDLINE_NOEXIT)) then begin ignoreParams := 0; if SDUCommandLineParameter(CMDLINE_SETTINGSFILE, settingsFile) then begin Inc(ignoreParams); if (settingsFile <> '') then Inc(ignoreParams); end; if SDUCommandLineSwitch(CMDLINE_MINIMIZE) then Inc(ignoreParams); Result := (ParamCount > ignoreParams); end; end; procedure TfrmMain.UACEscalateForDriverInstallation(); begin UACEscalate(CMDLINE_SWITCH_IND + CMDLINE_DRIVERCONTROL + ' ' + CMDLINE_GUI, False); end; procedure TfrmMain.UACEscalateForPortableMode(portableAction: TPortableModeAction; suppressMsgs: Boolean); var cmdLinePortableSwitch: String; begin case portableAction of pmaStart: begin cmdLinePortableSwitch := CMDLINE_START; end; pmaStop: begin cmdLinePortableSwitch := CMDLINE_STOP; end; pmaToggle: begin cmdLinePortableSwitch := CMDLINE_TOGGLE; end; end; UACEscalate( CMDLINE_SWITCH_IND + CMDLINE_PORTABLE + ' ' + cmdLinePortableSwitch, suppressMsgs ); end; procedure TfrmMain.UACEscalate(cmdLineParams: String; suppressMsgs: Boolean); const VERB_RUNAS = 'runas'; var filenameAndPath: String; cwd: String; begin // Only applicable in Windows Vista; simply warn user they can't continue on // earlier OSs if (not (SDUOSVistaOrLater()) or not (fallowUACEsclation)) then begin if not (suppressMsgs) then begin SDUMessageDlg(TEXT_NEED_ADMIN, mtError, [mbOK], 0); end; end else begin // Prevent endless loops of UAC escalation... cmdLineParams := CMDLINE_SWITCH_IND + CMDLINE_NOUACESCALATE + ' ' + cmdLineParams; // Message supression if suppressMsgs then begin cmdLineParams := CMDLINE_SWITCH_IND + CMDLINE_SILENT + ' ' + cmdLineParams; end; filenameAndPath := ParamStr(0); cwd := ExtractFilePath(filenameAndPath); ShellExecute( self.Handle, VERB_RUNAS, PChar(filenameAndPath), PChar(cmdLineParams), PChar(cwd), SW_SHOW ); // The UAC escalation/reexecution of FreeOTFE as UAC may have changed the // drivers installed/running; flush any caches in the FreeOTFE object GetFreeOTFE().CachesFlush(); end; end; procedure TfrmMain.PKCS11TokenRemoved(SlotID: Integer); var i: Integer; volumeInfo: TOTFEFreeOTFEVolumeInfo; drivesToDismount: DriveLetterString; mounted: DriveLetterString; begin SetStatusBarText(SDUParamSubstitute(_('Detected removal of token from slot ID: %1'), [SlotID])); if gSettings.OptPKCS11AutoDismount then begin drivesToDismount := ''; mounted := GetFreeOTFE().DrivesMounted(); for i := 1 to length(mounted) do begin // ...Main FreeOTFE window list... if GetFreeOTFE().GetVolumeInfo(mounted[i], volumeInfo) then begin if volumeInfo.MetaDataStructValid then begin if (volumeInfo.MetaDataStruct.PKCS11SlotID = SlotID) then begin drivesToDismount := drivesToDismount + mounted[i]; end; end; end; end; SetStatusBarText(SDUParamSubstitute(_('Autodismounting drives: %1'), [PrettyPrintDriveLetters(drivesToDismount)])); DismountDrives(drivesToDismount, False); end; end; function TfrmMain.GetSelectedDrives(): DriveLetterString; var i: Integer; begin Result := ''; for i := 0 to (lvDrives.items.Count - 1) do begin if lvDrives.Items[i].Selected then begin Result := Result + GetDriveLetterFromLVItem(lvDrives.Items[i]); end; end; end; procedure TfrmMain.actFreeOTFEMountPartitionExecute(Sender: TObject); var selectedPartition: String; begin if GetFreeOTFE().WarnIfNoHashOrCypherDrivers() then begin selectedPartition := GetFreeOTFE().SelectPartition(); if (selectedPartition <> '') then begin MountFilesDetectLUKS( selectedPartition, False, ftFreeOTFE ); end; end; end; procedure TfrmMain.actFreeOTFENewExecute(Sender: TObject); var prevMounted: DriveLetterString; newMounted: DriveLetterString; createdMountedAs: DriveLetterString; msg: WideString; i: Integer; begin inherited; prevMounted := GetFreeOTFE().DrivesMounted; if not (GetFreeOTFE().CreateFreeOTFEVolumeWizard()) then begin if (GetFreeOTFE().LastErrorCode <> OTFE_ERR_USER_CANCEL) then begin SDUMessageDlg(_('LibreCrypt container could not be created'), mtError); end; end else begin newMounted := GetFreeOTFE().DrivesMounted; // If the "drive letters" mounted have changed, the new volume was // automatically mounted; setup for this if (newMounted = prevMounted) then begin msg := _('LibreCrypt container created successfully.') + SDUCRLF + SDUCRLF + _('Please mount, and format this container''s free space before use.'); end else begin // Get new drive on display... RefreshDrives(); createdMountedAs := ''; for i := 1 to length(newMounted) do begin if (Pos(newMounted[i], prevMounted) = 0) then begin if (createdMountedAs <> '') then begin // If the user mounted another volume during volume creation, we // can't tell from here which was the new volume createdMountedAs := createdMountedAs + ' / '; end; createdMountedAs := createdMountedAs + newMounted[i] + ':'; end; end; msg := Format(_('FreeOTFE container created successfully and opened as: %s.'), [createdMountedAs]); end; SDUMessageDlg(msg, mtInformation); end; end; procedure TfrmMain.actLUKSNewExecute(Sender: TObject); var prevMounted: DriveLetterString; newMounted: DriveLetterString; createdMountedAs: DriveLetterString; msg: WideString; i: Integer; res :boolean; vol_path: String; begin inherited; prevMounted := GetFreeOTFE().DrivesMounted; vol_path := ExpandFileName(ExtractFileDir(Application.ExeName) + '\..\..\..\..\test_vols\'); res:= GetFreeOTFE().CreateLUKS(vol_path+'luks.new.vol',SDUStringToSDUBytes('password')); if not res then begin if (GetFreeOTFE().LastErrorCode <> OTFE_ERR_USER_CANCEL) then begin SDUMessageDlg(_('LUKS container could not be created'), mtError); end; end else begin newMounted := GetFreeOTFE().DrivesMounted; // If the "drive letters" mounted have changed, the new volume was // automatically mounted; setup for this if (newMounted = prevMounted) then begin msg := _('LUKS container created successfully.') + SDUCRLF + SDUCRLF + _('Please mount, and format this container''s free space before use.'); end else begin // Get new drive on display... RefreshDrives(); createdMountedAs := ''; for i := 1 to length(newMounted) do begin if (Pos(newMounted[i], prevMounted) = 0) then begin if (createdMountedAs <> '') then begin // If the user mounted another volume during volume creation, we // can't tell from here which was the new volume createdMountedAs := createdMountedAs + ' / '; end; createdMountedAs := createdMountedAs + newMounted[i] + ':'; end; end; msg := format(_('LUKS container created successfully and opened as: %s.'), [createdMountedAs]); end; SDUMessageDlg(msg, mtInformation); end; end; procedure TfrmMain.actInstallExecute(Sender: TObject); begin inherited; //escalate priv and run all UACEscalate('/' + CMDLINE_DRIVERCONTROL + ' ' + CMDLINE_INSTALL + ' /' + CMDLINE_FILENAME + ' ' + CMDLINE_ALL, SDUCommandLineSwitch(CMDLINE_SILENT)); end; procedure TfrmMain.actLinuxMountPartitionExecute(Sender: TObject); var selectedPartition: String; mountList: TStringList; begin if GetFreeOTFE().WarnIfNoHashOrCypherDrivers() then begin selectedPartition := GetFreeOTFE().SelectPartition(); if (selectedPartition <> '') then begin mountList := TStringList.Create(); try mountList.Add(selectedPartition); MountFiles(ftLinux, mountList, False, False); finally mountList.Free(); end; end; end; end; end.
unit uGlobal; interface uses Winapi.Windows, System.Classes, System.Types, System.SysUtils, Vcl.Graphics, Vcl.Printers; const piCalc = 0; { just calculate the integral area } piShow = 1; { calculate area & plot the integral } piArea = 2; { calculate & shade area } piBoth = 3; { calculate area, plot the integral & shade area } Pi: extended = 3.1415926535897932385; PiOn2: extended = 1.5707963267948966192; twoPi: extended = 6.2831853071795864769; NewFName: TFileName = 'New Graph'; type TAxisStyle = (asLinear, asLog); TGridStyle = (gsNone, gsAxes, gsCartesian, gsPolar); TPrinterInfo = record Index: integer; { Printer.PrinterIndex } PaperID: SmallInt; { default = DMPAPER_A4 } Orientation: TPrinterOrientation; xOffset: integer; { paper print area horizontal offset pixels } yOffset: integer; { paper print area vertical offset pixels } xRes: integer; { paper print area horizontal pixels } yRes: integer; { paper print area vertical pixels } xPixPerInch: integer; { these are equal } yPixPerInch: integer; end; TPlotData = record FunctStr: string; { same font as grid except color = PlotColor } TextStr: string; { edit field text } xInc: single; { cartesian plot increment } PlotWidth: integer; { pen width for function plot } PlotColor: TColor; { pen color for function plot } PhiInc: single; { polar plot increment } SegMin: extended; { max and min for segment plot } SegMax: extended; xLabel: extended; { plot label location } yLabel: extended; ShowLabel: Boolean; PlotAsFx: Boolean; { true if cartesian plot } IsSegment: Boolean; { true for segment plot } IsContinuous: Boolean; { when false app looks for discontinuities } end; TGrid = record xAxisStyle: TAxisStyle; yAxisStyle: TAxisStyle; GridStyle: TGridStyle; end; TGraphData = record xMin: extended; { plot area view } yMin: extended; xMax: extended; yMax: extended; SavexMin: extended; { saved plot area view } SaveyMin: extended; SavexMax: extended; SaveyMax: extended; AreaAlpha: single; { transparency of integration area } FontName: string; FontStyle: TFontStyles; FontSize: integer; AxisWidth: integer; { axes line pen width } xMinorGrad: integer; { minor X axis graduation lengths } yMinorGrad: integer; { minor Y axis graduation lengths } xMajorGrad: integer; { major X axis graduation lengths } yMajorGrad: integer; { major Y axis graduation lengths } MinorWidth: integer; { minor graduation & grid line width } MajorWidth: integer; { major graduation & grid line width } CoordWidth: integer; { coordinate line width } dydxWidth: integer; { derivative line width } d2ydx2Width: integer; { 2ndderivative line width } IntegCount: integer; { number of integration intervals } ydxWidth: integer; { integral line width } BackColor: TColor; { paper or background color } GridColor: TColor; { grid color } xAxisColor: TColor; { xAxis color } yAxisColor: TColor; { yAxis color} CoordColor: TColor; { coordinate line color } dydxColor: TColor; { derivative line color } d2ydx2Color: TColor; { 2ndderivative line color } ydxColor: TColor; { integral line color } PosAreaColor: TColor; { positive integral area color } NegAreaColor: TColor; { negative integral area color } Grid: TGrid; PlotData: TPlotData; end; TPlotDataObject = class(TObject) constructor Create(D: TPlotData); destructor Destroy; override; private public Data: TPlotData; end; TGraphPoint = record PlotPoint: TPoint; x, y: extended; end; TGraphPointObject = class(TObject) { in uCanvas; drawing differenttial etc. } constructor Create(vx_phi, vy_r: extended); destructor Destroy; override; private public PlotPoint: TPoint; x_phi: extended; y_r: extended; DrawLine: Boolean; end; TGraphLine = record { in uCanvas; drawing integral etc. } P1, P2: TPoint; x, y1, y2: extended; end; TGraphLineObject = class(TObject) constructor Create(vx, vy: extended); destructor Destroy; override; private public GraphLine: TGraphLine; end; TPenStyle = record PenWidth: integer; { pen width for function plot } PenColor: TColor; { pen color for function plot } end; TPlotStyle = record AreaAlpha: single; { transparency of integration area } StyleName: string[30]; FontName: string[100]; FontStyle: TFontStyles; FontSize: integer; AxisWidth: integer; { axes line pen width } xMinorGrad: integer; { minor X axis graduation lengths } yMinorGrad: integer; { minor Y axis graduation lengths } xMajorGrad: integer; { major X axis graduation lengths } yMajorGrad: integer; { major Y axis graduation lengths } MinorWidth: integer; { minor graduation & grid line width } MajorWidth: integer; { major graduation & grid line width } CoordWidth: integer; { coordinate line width } dydxWidth: integer; { derivative line width } d2ydx2Width: integer; { 2ndderivative line width } IntegCount: integer; { number of integration intervals } ydxWidth: integer; { integral line width } BackColor: TColor; { paper or background color } GridColor: TColor; { grid color } xAxisColor: TColor; { xAxis color } yAxisColor: TColor; { yAxis color} CoordColor: TColor; { coordinate line color } dydxColor: TColor; { derivative line color } d2ydx2Color: TColor; { 2ndderivative line color } ydxColor: TColor; { integral line color } PosAreaColor: TColor; { positive integral area color } NegAreaColor: TColor; { negative integral area color } Grid: TGrid; Pens: Array[0..11] of TPenStyle; NumLines: Array[0..11] of TPenStyle; { PlotWidth, PlotColor } NumPoints: Array[0..11] of TPenStyle; { PointSize, PointColor } end; TPlotStyleObject = class(TObject) constructor Create(S: TPlotStyle); destructor Destroy; override; private public Style: TPlotStyle; end; TFoundPointObject = class(TObject) { used by Interpolate procedure } constructor Create(x, m, y: extended; c, mc: TColor); destructor Destroy; override; private public xValue, mValue, yValue: extended; Color, mColor: TColor; end; TTextData = record Caption: string; { in CheckListBox } xLoc, yLoc: extended; { text block left, top } yInc: integer; { default, wbf.CharHeight } FontName: string; { wbf font } FontStyle: TFontStyles; { style } FontSize: integer; { size } FontColor: TColor; { color } end; TTextLineObject = class(TObject) constructor Create(T: string; C: TColor); destructor Destroy; override; private public Text: string; Color: TColor; end; TTextDataObject = class(TObject) constructor Create(D: TTextData); destructor Destroy; override; private public Data: TTextData; TextLines: TList; { TTextLineObject list } end; TNumericStyle = (nsNone, nsLinear, nsLagrange, nsHermite); TPointStyle = (psSquare, psPlus, psCross, psCircle); TNumericData = record Name: string; { descriptive name } NumericStyle: TNumericStyle; { nsNone, nsLinear, nsLagrange, nsHermite } ShowPoints: Boolean; { points visible if true } PointStyle: TPointStyle; { psSquare, psPlus, psCross, psCircle } PointSize: integer; { } PointColor: TColor; { } PlotWidth: integer; { pen width for plot } PlotColor: TColor; { pen color for plot } SortXValue: Boolean; { x values sorted if true } Extrapolate: Boolean; { extrapolate graph if true } CoordsIdx: integer; { enter coords as x, y or phi, r or vector } CurveRate: integer; { was k0 factor k0 = CurveRate/100 } end; TNumericObject = class(TObject) constructor Create(D: TNumericData); destructor Destroy; override; private public Data: TNumericData; ControlPoints: TList; { list of TGraphPointObject } end; TLayout = record IsMaximize: Boolean; { is true if MainForm.WindowState = wsMaximized } MainLeft: integer; MainTop: integer; MainWidth: integer; MainHeight: integer; CurrentGraphFName: String[255]; CurrentDataPath: String[255]; CurrentImagePath: String[255]; CurrentPrinterInfo: TPrinterInfo; GridsVisible: Boolean; GridsLeft: integer; GridsTop: integer; NumericVisible: Boolean; NumericLeft: integer; NumericTop: integer; TextVisible: Boolean; TextLeft: integer; TextTop: integer; TextWidth: integer; TextHeight: integer; FuncLeft: integer; FuncTop: integer; DerivLeft: integer; DerivTop: integer; IntegXLeft: integer; IntegXTop: integer; IntegYLeft: integer; IntegYTop: integer; BetweenLeft: integer; BetweenTop: integer; VolumeXLeft: integer; VolumeXTop: integer; VolumeYLeft: integer; VolumeYTop: integer; fxLeft: integer; fxTop: integer; fx1Left: integer; fx1Top: integer; fx2Left: integer; fX2Top: integer; PrintLeft: integer; PrintTop: integer; PrintScale: double; PrintBorderColor: integer; PrintBorderWidth: integer; PrintUnit: integer; BitmapLeft: integer; BitmapTop: integer; BitmapScale: double; BitmapBorderColor: integer; BitmapBorderWidth: integer; BitmapUnit: integer; StyleLeft: integer; StyleTop: integer; end; var GraphData: TGraphData; Altered: Boolean; { any alteration to the plot } LabelRect: TRect; BinPath: TFileName; PlotPath: TFileName; DataPath: TFileName; ImagePath: TFileName; GraphFName: TFileName; StyleFName: TFileName; LayoutFName: TFileName; { Miscellaneous Parameters } PhiIncMin: single = 0.00001; xEvaluate: extended = 0; yEvaluate: extended = 0; yCosxEval: extended = 0; ySinxEval: extended = 0; IntegCountMax: integer = 256000; IntegMin: extended; IntegMax: extended; KeptMin: extended; KeptMax: extended; KeepRange: Boolean; IntegConst: extended; IntegCountPos: integer; PrinterInfo: TPrinterInfo; Layout: TLayout; procedure GetPrinterInfo(var Info: TPrinterInfo); procedure SetPrinterInfo(const Info: TPrinterInfo); function GetPaperType: string; //======================================================================== implementation //======================================================================== constructor TPlotDataObject.Create(D: TPlotData); begin inherited Create; Data := D; end; destructor TPlotDataObject.Destroy; begin inherited Destroy; end; constructor TGraphPointObject.Create(vx_phi, vy_r: extended); begin inherited Create; x_phi := vx_phi; y_r := vy_r; end; destructor TGraphPointObject.Destroy; begin inherited Destroy; end; constructor TGraphLineObject.Create(vx, vy: extended); begin inherited Create; with GraphLine do begin x := vx; y1 := vy; end; end; { TGraphLineObject.Create } destructor TGraphLineObject.Destroy; begin inherited Destroy; end; { TGraphLineObject.Destroy } constructor TPlotStyleObject.Create(S: TPlotStyle); begin inherited Create; Style := S; end; { TPlotStyleObject.Create } destructor TPlotStyleObject.Destroy; begin inherited Destroy; end; { TPlotStyleObject.Destroy } constructor TFoundPointObject.Create(x, m, y: extended; c, mc: TColor); begin inherited Create; xValue := x; mValue := m; yValue := y; Color := c; mColor := mc; end; destructor TFoundPointObject.Destroy; begin inherited Destroy; end; constructor TTextLineObject.Create(T: string; C: TColor); begin inherited Create; Text := T; Color := C; end; destructor TTextLineObject.Destroy; begin inherited Destroy; end; constructor TTextDataObject.Create(D: TTextData); begin inherited Create; Data := D; TextLines := TList.Create; end; destructor TTextDataObject.Destroy; var i: integer; begin for i := 0 to TextLines.Count -1 do TTextLineObject(TextLines.Items[i]).Free; TextLines.Free; inherited Destroy; end; constructor TNumericObject.Create(D: TNumericData); begin inherited Create; Data := D; ControlPoints := TList.Create; end; destructor TNumericObject.Destroy; var i: integer; begin for i := 0 to ControlPoints.Count -1 do TObject(ControlPoints.Items[i]).Free; ControlPoints.Free; inherited Destroy; end; procedure GetPrinterInfo(var Info: TPrinterInfo); var Device: array [0..255] of char; Driver: array [0..255] of char; Port: array [0..255] of char; hDMode: THandle; pDMode: PDevMode; begin { GetPrinterInfo } Printer.GetPrinter(Device, Driver, Port, hDMode); if hDMode <> 0 then begin pDMode := GlobalLock(hDMode); if pDMode <> nil then begin with Info do PaperID := pDMode.dmPaperSize; { default = DMPAPER_A4 } GlobalUnlock(hDMode); with Info do begin Index := Printer.PrinterIndex; xPixPerInch := GetDeviceCaps(Printer.Handle, LOGPIXELSX); yPixPerInch := GetDeviceCaps(Printer.Handle, LOGPIXELSY); xOffset := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETX); yOffset := GetDeviceCaps(Printer.Handle, PHYSICALOFFSETY); xRes := GetDeviceCaps(Printer.Handle, HORZRES); yRes := GetDeviceCaps(Printer.Handle, VERTRES); Orientation := Printer.Orientation; end; end; end; end; { GetPrinterInfo } procedure SetPrinterInfo(const Info: TPrinterInfo); var Device: array [0..255] of char; Driver: array [0..255] of char; Port: array [0..255] of char; hDMode: THandle; pDMode: PDevMode; begin { SetPrinterInfo } Printer.GetPrinter(Device, Driver, Port, hDMode); if (PrinterInfo.Index < -1) or (PrinterInfo.Index > Printer.Printers.Count -1) then PrinterInfo.Index := -1; Printer.PrinterIndex := PrinterInfo.Index; Printer.Orientation := PrinterInfo.Orientation; if hDMode <> 0 then begin pDMode := GlobalLock(hDMode); if pDMode <> nil then begin pDMode.dmPaperSize := PrinterInfo.PaperID; { default = DMPAPER_A4 } pDMode^.dmFields := pDMode^.dmFields or DM_PAPERSIZE; pDMode^.dmFields := pDMode^.dmFields or DM_ORIENTATION; pDMode^.dmFields := pDMode^.dmFields or DM_DEFAULTSOURCE; GlobalUnlock(hDMode); end; end; end; { SetPrinterInfo } function GetPaperType: string; var s: string; begin { GetPaperType } case PrinterInfo.PaperID of DMPAPER_LETTER: s := 'Letter, 8½" x 11"'; DMPAPER_LEGAL: s := 'Legal, 8½" x 14"'; DMPAPER_A4: s := 'A4, 210mm x 297mm'; DMPAPER_CSHEET: s := 'C, 17" x 22"'; DMPAPER_DSHEET: s := 'D, 22" x 34"'; DMPAPER_ESHEET: s := 'E, 34" x 44"'; DMPAPER_LETTERSMALL: s := 'Letter, 8½" x 11"'; DMPAPER_TABLOID: s := 'Tabloid, 11" x 17"'; DMPAPER_LEDGER: s := 'Ledger, 17" x 11"'; DMPAPER_STATEMENT: s := 'Statement, 5½" x 8½"'; DMPAPER_EXECUTIVE: s := 'Executive, 7¼" x 10½"'; DMPAPER_A3: s := 'A3, 297mm x 420mm'; DMPAPER_A4SMALL: s := 'A4, 210mm x 297mm'; DMPAPER_A5: s := 'A5, 148mm x 210mm'; DMPAPER_B4: s := 'B4, 250mm x 354mm'; DMPAPER_B5: s := 'B5, 182mm x 257mm'; DMPAPER_FOLIO: s := 'Folio, 8½" x 13"'; DMPAPER_QUARTO: s := 'Quarto, 215mm x 275mm'; DMPAPER_10X14: s := 'Sheet, 10" x 14"'; DMPAPER_11X17: s := 'Sheet, 11" x 17"'; DMPAPER_NOTE: s := 'Note, 8½" x 11"'; DMPAPER_ENV_9: s := 'Envelope 3 7/8" x 8 7/8"'; DMPAPER_ENV_10: s := 'Envelope 4 1/8" x 9½"'; DMPAPER_ENV_11: s := 'Envelope 4½" x 10 3/8"'; DMPAPER_ENV_12: s := 'Envelope 4¾" x 11"'; DMPAPER_ENV_14: s := 'Envelope 5" x 11½"'; DMPAPER_ENV_DL: s := 'Envelope 110mm x 220mm'; DMPAPER_ENV_C5: s := 'Envelope 162mm x 229mm'; DMPAPER_ENV_C3: s := 'Envelope 324mm x 458mm'; DMPAPER_ENV_C4: s := 'Envelope 229mm x 324mm'; DMPAPER_ENV_C6: s := 'Envelope 114mm x 162mm'; DMPAPER_ENV_C65: s := 'Envelope 114mm x 229mm'; DMPAPER_ENV_B4: s := 'Envelope 250mm x 353mm'; DMPAPER_ENV_B5: s := 'Envelope 176mm x 250mm'; DMPAPER_ENV_B6: s := 'Envelope 176mm x 125mm'; DMPAPER_ENV_ITALY: s := 'Envelope 110mm x 230mm'; DMPAPER_ENV_MONARCH: s := 'Envelope 3 7/8" x 7½"'; DMPAPER_ENV_PERSONAL:s := 'Envelope 3 5/8" x 6½"'; DMPAPER_FANFOLD_US: s := 'Fanfold, 14 7/8" x 11"'; DMPAPER_FANFOLD_STD_GERMAN:s := 'Fanfold, 8½" x 12"'; DMPAPER_FANFOLD_LGL_GERMAN:s := 'Fanfold, 8½" x 13"'; 260: s := '8" x 6"'; 262: s := 'Fanfold, 210mm x 12"'; else s := 'Custom '; end; Result := s; end; { GetPaperType } end.
{ PERFIL = 2 REQUISICAO DE AASTECIMENTO PERFIL = 1 REQUISICAO DE VENDA PERFIL = 3 TELA DE APROVAÇÃO } unit uOsDeposito; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, SoftDBGrid, TFlatButtonUnit, Math, StdCtrls, fCtrls, ADODB, DB, ExtCtrls, adLabelComboBox; type TfmOsDeposito = class(TForm) grid: TSoftDBGrid; tb: TADOTable; DataSource1: TDataSource; Panel1: TPanel; btNova: TFlatButton; FlatButton2: TFlatButton; Query: TADOQuery; cbCritica: TfsCheckBox; cbLojas: TadLabelComboBox; procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btNovaClick(Sender: TObject); procedure GetDadosProdutos(cod:string); procedure gridColExit(Sender: TObject); procedure travaGrid(Sender:Tobject); procedure destravaGrid(Sender:Tobject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); function criticaQuantidade(Sender:TObject):String; procedure tbPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure tbAfterPost(DataSet: TDataSet); procedure gridDblClick(Sender: TObject); procedure FlatButton2Click(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure gridKeyDown(Sender: TObject; var Key: Word;Shift: TShiftState); procedure tbBeforePost(DataSet: TDataSet); procedure cbCriticaClick(Sender: TObject); procedure tbAfterCancel(DataSet: TDataSet); function existeQuantidadePendente(uo, is_ref:String; showErro:boolean): Boolean; function isEmSeparacao(is_ref:String; mostraMsgErro:boolean):Boolean; procedure preparaParaRequisicaoNormal(Sender:Tobject); procedure preparaParaLiberarRequisicao(Sender:Tobject); procedure criaTabela(Sender:Tobject; var table:TADOTable); procedure carregaTabelaRequisicao(Sender: TObject; uo:String); procedure formatarGrid(Sender:Tobject); procedure salvaReqVenda(Sender:Tobject); procedure salvaReqAbastecimento(Sender:Tobject); procedure cbLojasClick(Sender: TObject); procedure geraRequisicaoReabastecimento(Sender:Tobject); procedure SetPerfil(P:integer; uoCD:String); procedure emailParaCD(nReq,de:String); function getValorMaxPedReabatecimento():Integer; function verificaRequisicaoAberta():Boolean; procedure fechaSessaoRequisicao(uo:String); procedure bloqueiaSessaoRequisicao(uo:String); private { Private declarations } public { Public declarations } end; var fmOsDeposito: TfmOsDeposito; DUR_ESTOQUE, MESES_VD_MEDIA, MAX_ITENS_REQ, PERFIL, QT_DIAS_PEND: integer; IS_VERIFICA_SEPARACAO, USA_QT_MAX_REQ, PEDE_PROD_MAISON,IS_REQ_SALVA:Boolean; IS_CRITICA_VD_MEDIA, UO_CD, PC_VAREJO, COL_UO_MAPA_SEPARACAO:String; implementation uses umain, funcoes, funcSQL, verificaSenhas, funcDatas, cf; {$R *.dfm} procedure TfmOsDeposito.bloqueiaSessaoRequisicao(uo: String); var cmd:String; begin cmd := 'if not exists (select * from zcf_paramGerais where nm_param = ''osDeposito.reqAberta'' and uo = ' + uo + ' ) ' + #13+ 'insert zcf_paramGerais values (''osDeposito.reqAberta'',' + uo + ', ' + quotedStr(fmMain.getNomeUsuario()) + ', ''-'' )'; funcsql.execSQL( cmd, fmMain.Conexao ); end; procedure TfmOsDeposito.fechaSessaoRequisicao(uo: String); begin funcsql.execSQL('delete from zcf_paramGerais where nm_param = ''osDeposito.reqAberta'' and uo = ' + uo, fmMain.Conexao ); end; function TfmOsDeposito.verificaRequisicaoAberta: Boolean; var uo:String; begin if (PERFIL = 2) then uo := fmMain.getUoLogada(); if ( PERFIL = 3 ) then uo := funcoes.getNumUO(cbLojas); uo := funcSql.openSQL('Select valor from zcf_paramGerais where nm_param = ''osDeposito.reqAberta'' and uo = ' + uo, 'valor', fmMain.Conexao ); if (uo <> '') and (uo <> fmMain.getNomeUsuario()) then begin msgTela('', 'A lista de requisição dessa loja está aberta por: '+#13 + uo + #13+ 'Você não pode trabalhar com essa requisição enquanto esse usuário '+#13+'a estiver usando.', MB_OK + MB_ICONERROR); Result := true; end else result := false; end; function TfmOsDeposito.getValorMaxPedReabatecimento():Integer; var datai,dataf:Tdate; qtVenda,qtVendaSemestre, qtVendaMes: Real; diasDesdePrimVenda:integer; cmd:String; begin if ( IS_CRITICA_VD_MEDIA <> '0' ) then begin funcoes.gravaLog ('Loja critica venda media' ); fmMain.MsgStatus('Obtendo venda média...'); dataf := now(); //pega quantos dias desde a primeira venda cmd := ' select isNull( (select top 01 datediff( day, dt_mov, getdate()) from zcf_dsdsi (noLock) where is_ref = ' + tb.fieldByname('is_ref').AsString + 'and is_estoque= ' + fmMain.getUoLogada() + '),1) as diasDesdePrimVenda'; diasDesdePrimVenda := strToInt( funcsql.openSQL(cmd,'diasDesdePrimVenda', fmMain.Conexao) ) ; if (diasDesdePrimVenda > (MESES_VD_MEDIA * 30)) then begin datai := now - (MESES_VD_MEDIA * 30); diasDesdePrimVenda := (MESES_VD_MEDIA * 30); end else datai := now - diasDesdePrimVenda ; //pegar a venda do ultimo semestre (ou antes, se houver) qtVendaSemestre := strToInt( cf.getVendaProduto(tb.fieldByname('is_ref').asString, fmMain.getUoLogada(), UO_CD, datai, dataf)) ; funcoes.gravaLog ( tb.fieldByname('codigo').asString + ' qtVendaUltimoSemestre: ' + floatToStr(qtVendaSemestre) ); qtVendaSemestre := ( qtVendaSemestre / diasDesdePrimVenda ) * DUR_ESTOQUE; funcoes.gravaLog ( tb.fieldByname('codigo').asString + ' Venda Media semestre: ' + floatToStr(qtVendaSemestre) ); //pegar a venda do ultimo mes qtVendaMes := strToInt( cf.getVendaProduto(tb.fieldByname('is_ref').asString, fmMain.getUoLogada(), UO_CD, datai-30, dataf)) ; funcoes.gravaLog ( tb.fieldByname('codigo').asString + ' qtVendaUltimoMes: ' + floatToStr(qtVendaMes) ); qtVendaMes := ( qtVendaSemestre / 30 ) * DUR_ESTOQUE; funcoes.gravaLog ( tb.fieldByname('codigo').asString + ' Venda Media mes: ' + floatToStr(qtVendaMes) ); if (qtVendaSemestre > qtVendaMes) then qtVenda := qtVendaSemestre else qtVenda := qtVendaMes; if (qtVenda = 0) then qtVenda := 1; result := ( ceil( ( qtVenda / tb.fieldByname('Qt caixa').AsInteger))) * tb.fieldByname('Qt caixa').AsInteger ; end else begin funcoes.gravaLog ('Loja sem critica de venda para requisicao.' ); result := tb.fieldByname('Est CD').AsInteger; end; fmMain.MsgStatus(''); end; function TfmOsDeposito.isEmSeparacao(is_ref:String; mostraMsgErro:boolean):Boolean; var cmd : String; ds:TDataSet; res:boolean; begin res := false; fmMain.MsgStatus('Consultando mapa dse separação.'); cmd := 'select i.num, isNull(i.' + COL_UO_MAPA_SEPARACAO + ',0) as qtMapa from zcf_MapaSeparacaoI i (nolock) ' + 'inner join zcf_MapaSeparacao m (nolock) on i.num = m.num where m.ehFinalizada <> 1 and i.is_ref = ' + is_ref; ds:= funcsql.getDataSetQ(cmd, fmMain.Conexao); if (ds.IsEmpty = false ) then if (ds.fieldByname('qtMapa').AsInteger > 0) then begin cmd := ' Você não pode pedir esse item agora, pois existe ' +#13+ ' um mapa de separação aberto para essa loja. ' +#13+ ' Dados do mapa: ' + #13+ ' Numero do mapa: ' + ds.fieldByname('num').AsString + '.' + #13+ ' Quantidade: '+ ds.fieldByname('qtMapa').AsString + '.'; funcoes.msgTela('',cmd , MB_OK + MB_ICONERROR); res := true; end; ds.free(); fmMain.MsgStatus(''); result := res; end; function TfmOsDeposito.existeQuantidadePendente(uo, is_ref:String; showErro:boolean): Boolean; var ds:TdataSet; cmd:String; begin fmMain.MsgStatus('Verificando requisição pendente.'); ds:= funcSQL.isReqPendProduto(fmMain.Conexao, fmMain.getUoLogada, is_ref, QT_DIAS_PEND ); if (ds.IsEmpty = false) then begin cmd := ' Atenção ' +#13+ ' Já existe quantidade pedida e não transferida desse produto '+#13+ ' a menos de ' + IntToStr(QT_DIAS_PEND) + ' dias. ' +#13+ ' Requisição: ' + ds.fieldByName('is_planod').AsString + #13+ ' Quantidade: ' + ds.fieldByName('qt_ped').AsString + #13 + ' Data: ' + ds.fieldByName('dt_movpd').AsString + #13; if (showErro = true) then msgTela('',cmd, MB_OK+MB_ICONERROR); ds.free();; if (PERFIL = 2) then result:= true else result:= false; end else begin ds.Destroy; result := false; end; fmMain.MsgStatus(''); end; function TfmOsDeposito.criticaQuantidade(Sender: TObject):String; var aux, erro:String; begin aux := Query.fieldbyname('fornecedor').AsString; if aux = '' then aux := '0'; aux := funcsql.GetValorWell( 'O','select codFornecedor from zcf_FornCritReq where codfornecedor = ' + aux, 'codFornecedor' , fmMain.conexao ); if aux = '' then begin if (Query.fieldbyname('embalagem').AsInteger <> 0) and ( Query.fieldbyname('embalagem').AsInteger <> 1 ) then if (cbCritica.Checked = false) then if ( tb.FieldByName('Qt Pedida').AsInteger mod Query.fieldbyname('embalagem').AsInteger > 0 ) then erro := ' - Esse produto deve ser pedido em caixa fechada. ' + #13+ ' A caixa dele tem ' + Query.fieldbyname('embalagem').AsString + ' unidades.' + #13; end; if (tb.Fields[1].asString = '0') then erro := erro +' - Falta a quantidade. '+ #13 else if ( tb.FieldByName('Qt Pedida').AsInteger > tb.FieldByName('Est CD').AsInteger) then erro := erro +' - Quantidade pedida maior que a disponivel. '+ #13 else if ( tb.FieldByName('Qt Pedida').AsInteger > (tb.FieldByName('Est CD').AsFloat/2) ) then if cbCritica.Checked = false then msgTela('',' AVISO'+#13+ 'A quantidade pedida é mais da metade do que consta no CD.' +#13+ 'Tenha certeza de que essa quantidade é mesmo necessária.', MB_ICONEXCLAMATION+MB_OK); if PERFIL = 2 then if ( tb.FieldByName('Qt Pedida').AsInteger > tb.FieldByName('Pedido Maximo').AsInteger) then erro := erro +' - Quantidade pedida é maior maior que o que o pedido máximo. '+ #13; if PERFIL = 1 then if (tb.RecordCount > MAX_ITENS_REQ) then erro := erro +' - A requisição só pode ter até ' + intToStr(MAX_ITENS_REQ) +' itens.'+ #13; if (erro <> '') then msgTela('', erro, mb_iconerror + mb_ok ); result := erro; end; procedure TfmOsDeposito.GetDadosProdutos(cod:string); var cmd:string; begin fmMain.MsgStatus('Consultando codigo.'); cmd :=' exec Z_CF_getInformacoesProduto ' + quotedStr(cod) + ' , '+ UO_CD +' , '+ '-1'; destravaGrid(nil); query.Connection := fmMain.Conexao; query.SQL.Clear; query.SQL.add(cmd); funcoes.gravaLog(cmd); query.Open; if (query.IsEmpty = true) then begin msgTela('','Este código não é cadastrado', mb_iconError+mb_ok); tb.Cancel; end else if (PEDE_PROD_MAISON = false) and (query.FieldByName('categoria').AsString = '15') then begin msgTela('', ' O produto: ' +#13+ query.fieldByname('codigo').asString + ' ' + query.fieldByname('descricao').asString +#13+ 'não pode ser pedido por essa loja ,pois é um produto da linha maison.', MB_OK + MB_ICONERROR); tb.Cancel; end else begin if (perfil = 2) and (IS_VERIFICA_SEPARACAO = true) then begin if isEmSeparacao( query.FieldByName('is_ref').AsString, true ) = true then begin grid.SelectedIndex := 0; tb.Cancel(); end; end; if (existeQuantidadePendente(fmMain.getUoLogada(), query.FieldByName('is_ref').AsString, true ) = false) then begin tb.FieldByName('codigo').AsString := query.fieldByName('codigo').AsString; tb.FieldByName('Descricao').AsString := query.fieldByName('descricao').AsString; tb.FieldByName('Est CD').AsString := query.fieldByName('estoqueDisponivel').AsString; tb.FieldByName('qt caixa').AsString := query.fieldByName('embalagem').AsString; tb.FieldByName('is_ref').AsString := query.fieldByName('is_ref').AsString; // pegar as informacoes do preco e estoque local fmMain.MsgStatus('Consultando dados de saldos...'); cmd :=' exec Z_CF_getInformacoesProduto ' + QuotedStr(cod) + ' , '+ fmMain.getUoLogada() + ' , 101'; destravaGrid(nil); query.Connection := fmMain.Conexao; query.SQL.Clear; query.SQL.add(cmd); query.Open; tb.FieldByName('Est Loja').AsString := query.fieldByName('EstoqueDisponivel').AsString; tb.FieldByName('Pc Loja').AsString := query.fieldByName('PRECO').AsString; if (perfil = 2) then begin if (USA_QT_MAX_REQ = true) then tb.FieldByName('Pedido Maximo').AsInteger := getValorMaxPedReabatecimento() else tb.FieldByName('Pedido Maximo').AsInteger := tb.FieldByName('Est CD').asInteger; end; end; end; travaGrid(nil); end; procedure TfmOsDeposito.criaTabela(Sender: Tobject; var table:TADOTable); var cmd:String; nTable:string; begin if tb.Active = true then tb.Close(); nTable := funcSQl.getNomeTableTemp; cmd := 'Create table ' + ntable + '( Codigo varchar(13) PRIMARY KEY, [Qt Pedida] integer not null default 0, Descricao varchar(50), [Est CD] integer, [Est Loja] integer,[Pc Loja] money, [Qt caixa] integer, is_ref integer, [Pedido Maximo] int )'; funcSql.execSQL(cmd , fmMain.Conexao); table.TableName := nTable; end; procedure TfmOsDeposito.FormActivate(Sender: TObject); begin IS_REQ_SALVA:=TRUE; QT_DIAS_PEND := strToInt( fmMain.GetParamBD('periodoParaReqPendentes','')); if funcsql.getParamBD('PedeCat15DoCd', fmMain.getUoLogada(), fmMain.Conexao) <> '' then PEDE_PROD_MAISON := true else PEDE_PROD_MAISON := false; COL_UO_MAPA_SEPARACAO := 'l' + funcsql.openSQL('Select top 01 cd_uo from zcf_tbuo where is_uo = ' + fmMain.getUoLogada(), 'cd_uo', fmMain.Conexao); PC_VAREJO := fmMain.GetParamBD('pcVarejo', fmMain.getUoLogada() ); MAX_ITENS_REQ := strToInt(funcsql.getParamBD('maxItensReqVenda', '' , fmMain.Conexao)); MESES_VD_MEDIA := strToInt(fmMain.GetParamBD('mesesVendaMedia', '') ); DUR_ESTOQUE := strToInt(fmMain.GetParamBD('osDeposito.qtDiasDurEstoque', '') ); IS_CRITICA_VD_MEDIA := fmMain.GetParamBD('osDeposito.uosCriticaReq', fmMain.getUoLogada() ) ; IS_VERIFICA_SEPARACAO := (fmMain.GetParamBD('osDeposito.verificaSeparacao', '') <> '0'); USA_QT_MAX_REQ := (fmMain.GetParamBD('osDeposito.usaQtMaxDeReq', '') <> '0'); end; procedure TfmOsDeposito.FormClose(Sender: TObject; var Action: TCloseAction); begin if (perfil = 2) and (tb.IsEmpty = false) then fechaSessaoRequisicao( fmMain.getUoLogada()); if (perfil = 3 ) and (tb.IsEmpty = false) then fechaSessaoRequisicao( funcoes.getNumUO(cbLojas) ); fmMain.MsgStatus (''); fmOsDeposito := nil; action := caFree; end; procedure TfmOsDeposito.gridColExit(Sender: TObject); begin if (PERFIL <> 3) then begin if ( grid.SelectedIndex = 0) and ( grid.SelectedField.AsString <> '' ) then GetDadosProdutos( grid.SelectedField.AsString); if ( grid.SelectedIndex = 1) then if ( tb.FieldByName('Descricao').AsString <> '' ) then if (criticaQuantidade(nil) <> '') then begin grid.SelectedIndex := 1; tb.FieldByName('Qt Pedida').AsInteger := 0; end else begin tb.Post; tb.Append; grid.SelectedIndex := 0; end; end else tb.cancel(); fmMain.MsgStatus(''); end; procedure TfmOsDeposito.travaGrid(Sender: Tobject); begin grid.Columns[2].ReadOnly := true; grid.Columns[3].ReadOnly := true; end; procedure TfmOsDeposito.destravaGrid(Sender: Tobject); begin grid.Columns[2].ReadOnly := false; grid.Columns[3].ReadOnly := false; end; procedure TfmOsDeposito.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (key = vk_return) or (key = vk_DOWN)then key := vk_TaB; end; procedure TfmOsDeposito.tbPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin if pos( 'Violation', e.Message ) > 0 then begin msgTela('','Esse código já consta na requisição', mb_IconError + mb_ok); action := daAbort; tb.Delete; end; end; procedure TfmOsDeposito.tbAfterPost(DataSet: TDataSet); begin fmMain.MsgStatus('Itens na requisição: ' + intTostr(tb.RecordCount) ); IS_REQ_SALVA := false; end; procedure TfmOsDeposito.gridDblClick(Sender: TObject); begin if (PERFIL <> 3) then if MsgTela('',' Remover esse item?' , mb_iconquestion + mb_yesNo) = mrYes then begin tb.Delete; tb.edit; end; end; procedure TfmOsDeposito.salvaReqVenda(Sender: Tobject); var str:String; ocoItens:TStringList; begin ocoItens:= TStringList.create(); if tb.IsEmpty = false then str := funcSQl.gerarRequisicao( fmMain.Conexao, tb, fmMain.getUoLogada(), fmMain.getUserLogado(), true, true, ocoItens, QT_DIAS_PEND); if (str <> '') then begin gravaLog(str); emailParaCD(str, fmMain.getUoLogada() ); end; while (tb.IsEmpty = false) do tb.Delete; tb.close; // cbCritica.enabled := false; ocoItens.free; end; procedure TfmOsDeposito.salvaReqAbastecimento(Sender: Tobject); var cmd:String; begin cmd := 'delete from zcf_dspd where is_uo = ' + fmMain.getUoLogada(); funcSql.execSQL(cmd, fmMain.Conexao); tb.First(); while tb.Eof = false do begin cmd :='insert zcf_dspd values(' + fmMain.getUoLogada() +', '+ tb.fieldByName('is_ref').asString +', '+ tb.fieldByName('Qt pedida').asString +', '+ tb.fieldByName('Pedido Maximo').asString +')'; funcsql.execSQL(cmd, fmMain.Conexao); tb.Next(); end; msgTela('','Requisição foi salva, a efetiva inclusão dessa requisição será feita pelo CD.', MB_OK + MB_ICONWARNING); end; procedure TfmOsDeposito.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (tb.IsEmpty = false) then if (IS_REQ_SALVA = false) then if (MsgTela('','Deseja sair sem salvar ?', MB_ICONQUESTION + MB_YESNO) = mrNo) then canclose := false end; procedure TfmOsDeposito.gridKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = VK_down then key := 0; end; procedure TfmOsDeposito.tbBeforePost(DataSet: TDataSet); begin if (tb.FieldByName('Qt Pedida').AsInteger = 0) then begin raise Exception.Create(' Falta a quantidade '); tb.Edit; end; end; procedure TfmOsDeposito.cbCriticaClick(Sender: TObject); var grupos, users:String; begin grupos:= fmMain.getParamBD('osDeposito.grupoAutorizador', '0'); users := fmMain.getParamBD('osDeposito.usersAutorizador', '0'); if (cbCritica.Enabled = true) then begin if cbCritica.Checked = true then if (verificaSenhas.TelaAutorizacao2( fmMain.Conexao, grupos, users) <> '' )then cbCritica.Checked := true else cbCritica.Checked := false; end; end; procedure TfmOsDeposito.tbAfterCancel(DataSet: TDataSet); begin tb.Edit; end; procedure TfmOsDeposito.carregaTabelaRequisicao(Sender: TObject; uo:String); var cmd :String; begin cmd := 'Insert ' + tb.TableName + ' select c.cd_ref as Codigo, i.qt_mov [Qt Pedida], c.ds_ref as Descricao' + ', dbo.zcf_EstLojaParaReq(c.is_ref, ' + uo_cd + ' , 1) as [Est CD]' + ', dbo.Z_CF_EstoqueNaLoja ( c.is_ref, ' + uo + ' , 1 ) ' + ', dbo.z_cf_funObterPrecoProduto_CF( '+ PC_VAREJO + ' , i.is_ref, '+ uo + ' ,0)as [Pc Loja]' + ' , c.qt_emb, c.is_ref, i.qtMaxPedido ' + ' from zcf_dspd i (nolock) ' + ' inner join crefe c (nolock) on c.is_ref = i.is_ref ' + ' where is_uo = ' + uo; funcsql.execSQL(cmd, fmMain.Conexao); tb.Open(); tb.Refresh(); if (grid.Enabled = true) then begin formatarGrid(nil); tb.Append(); end; if tb.IsEmpty = true then begin MsgTela('','Não há itens para essa loja.', MB_OK + MB_ICONWARNING); tb.Close(); fechaSessaoRequisicao(uo); end; end; procedure TfmOsDeposito.preparaParaRequisicaoNormal(Sender: Tobject); begin if (verificaRequisicaoAberta() = false) then begin bloqueiaSessaoRequisicao( fmMain.getUoLogada()) ; btNova.Enabled := false; criaTabela(nil, tb); carregaTabelaRequisicao(nil, fmMain.getUoLogada() ); end else fmOsDeposito.Close(); end; procedure TfmOsDeposito.formatarGrid(Sender: Tobject); var i: integer; begin for i:=0 to grid.Columns.Count -1 do grid.Columns[i].Title.Font.Style := [fsbold]; grid.SetFocus; grid.Columns[tb.FieldByname('is_ref').Index].Visible := false; grid.Columns[0].Width := 70; grid.Columns[1].Width := 70; grid.Columns[2].Width := 200; grid.Columns[3].Width := 70; grid.Columns[4].Width := 70; grid.Columns[5].Width := 70; grid.Columns[6].Width := 70; fmMain.MsgStatus(''); cbCritica.Enabled := (USA_QT_MAX_REQ); if perfil <> 2 then grid.Columns[tb.FieldByname('pedido maximo').Index].Visible := false; end; procedure TfmOsDeposito.preparaParaLiberarRequisicao(Sender: Tobject); begin PERFIL := 3; cf.getListaLojas(cbLojas, false, false, ''); cbLojas.Visible := true; btNova.Visible := false; grid.Enabled := false; end; procedure TfmOsDeposito.cbLojasClick(Sender: TObject); begin if (verificaRequisicaoAberta() = false) then begin bloqueiaSessaoRequisicao( funcoes.getNumUO(cbLojas) ); criaTabela(nil, tb); carregaTabelaRequisicao(nil, funcoes.getNumUO(cbLojas) ); end; end; procedure TfmOsDeposito.geraRequisicaoReabastecimento(Sender: Tobject); var tbAux:TADOTable; uo, aux,nGerados:String; i:integer; ocoReq, msgDeReq:Tstringlist; begin funcoes.gravaLog('------Requisicao-------------'); ocoReq := TStringList.Create(); uo := funcoes.getNumUO(cbLojas); nGerados := ''; tb.First(); while (tb.Eof = false) do begin tbAux := TADOTable.Create(nil); tbAux.Connection := fmMain.Conexao; tbAux.TableName := funcsql.criaTabelaTemporaria( fmMain.Conexao, '( is_ref int, codigo varchar(08), descricao varchar(50), [qt Pedida] int )'); tbAux.Open(); for i:= 1 to MAX_ITENS_REQ do if (tb.Eof = false) then begin tbAux.AppendRecord( [ tb.FieldByName('is_ref').asString, tb.FieldByName('codigo').asString, tb.FieldByName('descricao').asString, tb.FieldByName('Qt pedida').asString ]); tb.Next(); end; aux := ''; aux := cf.gerarRequisicao( tbAux, funcoes.getCodPc(cbLojas), UO_CD, fmMain.getUserLogado(), false, false, ocoReq, QT_DIAS_PEND ); if (aux <> '') then nGerados := nGerados + aux + ' '; tbAux.free(); end; if (nGerados <> '') then begin msgTela('',' Foram geradas as requisições: ' + nGerados + #13+' Vou mandar um email para a loja, avisando.', MB_OK + MB_ICONWARNING ); msgDeReq := TStringList.Create(); msgDeReq.Add('Segue a lista das requisições geradas para reabastecimento da loja' ); msgDeReq.add('geradas em: ' + funcDatas.dataSqlToData(funcsql.getDataBd(fmMain.Conexao,0)) ); msgDeReq.Add('Os numero são: ' + nGerados); msgDeReq.Add('As requisições foram liberadas por: ' + fmMain.getNomeUsuario() ); if (ocoReq.Count > 0) then begin msgDeReq.Add(''); msgDeReq.Add(''); msgDeReq.Add('Alguns produtos não foram pedidos, segue a lista:'); for i:=0 to ocoReq.Count-1 do msgDeReq.Add(ocoReq[i]); end; if (ocoReq.Count > 0) then begin msgDeReq.Add(''); msgDeReq.Add('Alguns produtos não foram requisitado, veja a lista abaixo:'); for i := 0 to ocoReq.Count -1 do msgDeReq.add(ocoReq[i]); end; fmMain.EnviarEmail( funcsql.getEmail( getCodUo(cbLojas), fmmain.Conexao) ,'Requisições geradas para reabastecimento em ' + dateToStr(now),'', msgDeReq,'Requisições reabastecimento para: ' + funcoes.getNomeUO(cbLojas) ); end else MsgTela('','Não foi gerada nehuma requisição.' , MB_OK + MB_ICONERROR ); funcSql.execSQL('delete from zcf_dspd where is_uo=' + funcoes.getNumUO(cbLojas) , fmMain.Conexao ); fechaSessaoRequisicao(uo); tb.close(); ocoReq.Free(); msgDeReq.Free(); end; procedure TfmOsDeposito.FlatButton2Click(Sender: TObject); begin case PERFIL of 1:salvaReqVenda(nil); 2:salvaReqAbastecimento(nil); 3:geraRequisicaoReabastecimento(nil); end; IS_REQ_SALVA := true; end; procedure TfmOsDeposito.emailParaCD(nReq, de: String); var bodyEmail: TStringList; aux:String; begin bodyEmail := TStringList.Create(); bodyEmail.Add('Olá'); bodyEmail.Add('Foi gerada uma requisição de venda/abastecimento para o cd.'); bodyEmail.Add('Pela loja: ' + fmMain.getNomeLojaLogada() ); bodyEmail.Add('Os numeros da requisição é: ' + nreq); bodyEmail.add('Feita por: ' + fmMain.getNomeUsuario() + ' em: '+ funcSQl.getDataBd(fmMain.Conexao) ); fmMain.EnviarEmail( funcsql.getEmail( fmMain.getUoLogada() , fmMain.Conexao) , 'Requisições venda/encarte geradas em ' + dateToStr(now), '', bodyEmail, 'Enviando email para a loja geradora...' ); aux := fmMain.GetParamBD('emailDeRequisicao1',''); if aux <> '' then fmMain.EnviarEmail( aux , 'Requisições venda/encarte geradas em ' + dateToStr(now), '', bodyEmail, 'Email para ' + aux ); aux := fmMain.GetParamBD('emailDeRequisicao2',''); if aux <> '' then fmMain.EnviarEmail( aux , 'Requisições venda/encarte geradas em ' + dateToStr(now), '', bodyEmail, 'Email para: ' + aux ); end; procedure TfmOsDeposito.btNovaClick(Sender: TObject); begin if tb.Active = false then criaTabela(nil, tb); if tb.IsEmpty = true then tb.Open else begin if msgTela('','Deseja abandonar as alterações ? ' , mb_yesNo + mb_iconQuestion) = mrYes then while tb.IsEmpty = false do tb.Delete; end; formatarGrid(nil); end; procedure TfmOsDeposito.SetPerfil(P: integer; uoCD:String); begin UO_CD := uoCD; PERFIL := P; case perfil of 2:fmOsDeposito.preparaParaRequisicaoNormal(nil); 3:preparaParaLiberarRequisicao(nil); end; end; end.
unit ViewReportsPayOnDay; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,IBase, RxMemDS, ExtCtrls, frxClass, frxDesgn, frxDBSet, DB, FIBDataSet, pFIBDataSet, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxCheckBox, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxControls, cxGridCustomView, cxGrid, cxClasses, ComCtrls, cxLookAndFeelPainters, StdCtrls, cxButtons,StudcityConst,St_ser_function, frxExportRTF, frxExportPDF, frxExportImage, frxExportXLS, frxExportTXT; type TfrmMainPayOnDay = class(TForm) Database: TpFIBDatabase; WriteTransaction: TpFIBTransaction; Transaction: TpFIBTransaction; pFIBStoredProcSaveRX: TpFIBStoredProc; DataSourceMaster: TDataSource; pFIBDataSetPrintMaster: TpFIBDataSet; frxDBDatasetMaster: TfrxDBDataset; pFIBDataSetPrintDetail: TpFIBDataSet; frxDBDatasetDetails: TfrxDBDataset; frxDesigner1: TfrxDesigner; TimerReports: TTimer; RxMemoryData: TRxMemoryData; frxDBDatasetMasterRX: TfrxDBDataset; pFIBDataSetPrintMasterRX: TpFIBDataSet; pFIBDataSetSchDB: TpFIBDataSet; pFIBDataSetSchCR: TpFIBDataSet; pFIBDataSetSM: TpFIBDataSet; StyleRepository: TcxStyleRepository; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxStyle16: TcxStyle; cxStyle17: TcxStyle; cxStyleYellow: TcxStyle; cxStyleFontBlack: TcxStyle; cxStyleMalin: TcxStyle; cxStyleBorder: TcxStyle; cxStylemalinYellow: TcxStyle; cxStyleGrid: TcxStyle; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxGridDB: TcxGrid; cxGridDBDBTableView1: TcxGridDBTableView; CxSelectField: TcxGridDBColumn; CxNameField: TcxGridDBColumn; cxGridDBLevel1: TcxGridLevel; RxMemoryDataDB: TRxMemoryData; DataSourceDB: TDataSource; RxNameVariant: TcxGridDBColumn; cxGridCR: TcxGrid; cxGridDBTableView1: TcxGridDBTableView; cxGridDBColumn1: TcxGridDBColumn; cxGridDBColumn2: TcxGridDBColumn; cxGridDBColumn3: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; RxMemoryDataCR: TRxMemoryData; DataSourceCR: TDataSource; cxGridSM: TcxGrid; cxGridDBTableView2: TcxGridDBTableView; cxGridDBColumn4: TcxGridDBColumn; cxGridDBColumn5: TcxGridDBColumn; cxGridDBColumn6: TcxGridDBColumn; cxGridLevel2: TcxGridLevel; DataSourceSM: TDataSource; RxMemoryDataSM: TRxMemoryData; StatusBar1: TStatusBar; cxButtonOK: TcxButton; cxButtonCancel: TcxButton; frxReport: TfrxReport; frxTXTExport1: TfrxTXTExport; frxXLSExport2: TfrxXLSExport; frxTIFFExport1: TfrxTIFFExport; frxPDFExport1: TfrxPDFExport; frxRTFExport1: TfrxRTFExport; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cxButtonCancelClick(Sender: TObject); procedure cxButtonOKClick(Sender: TObject); private private Constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer; Sql_Master,sql_master_add,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer);overload; { Private declarations } public Lang:Integer; { Public declarations } end; function ReportsViewOnDay(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer; Sql_Master,sql_master_add,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer):Integer;stdcall; exports ReportsViewOnDay; var frmMainPayOnDay: TfrmMainPayOnDay; ReportName:String; LastIg:Integer; Type_R:Integer; FV,NFV,FNR:Variant; Sql_Master_l,sql_master_add_l,Sql_Detail_l:String; implementation {$R *.dfm} function ReportsViewOnDay(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer; Sql_Master,sql_master_add,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer):Integer; var View:TfrmMainPayOnDay; begin View:=TfrmMainPayOnDay.Create(AOwner,DB,Type_Report,Sql_Master,sql_master_add,Sql_Detail,FieldView,NotFieldView,FieldNameReport,Report_Name,LastIgnor);; View.ShowModal; View.free; end; Constructor TfrmMainPayOnDay.Create(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer; Sql_Master,sql_master_add,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer); var i,j:Integer; FieldCount:Integer; MFR:TfrxMemoView; CountVisible:Integer; begin Inherited Create(AOwner); Lang:=ST_serLanguageIndex(DB); RxNameVariant.Caption:=StudcityConst.ST_DB_EX[lang]; cxGridDBColumn3.Caption:=StudcityConst.ST_CR_EX[lang]; cxGridDBColumn5.Caption:=StudcityConst.ST_SM_RZ_ST_EX[lang]; cxGridDBColumn6.Caption:=StudcityConst.ST_SM_EX[lang]; cxButtonOK.Caption:=StudcityConst.Studcity_ACTION_VIEW_CONST_EX[lang]; cxButtonCancel.Caption:=StudcityConst.Studcity_ACTION_CANCEL_CONST_EX[lang]; Sql_Master_l:=Sql_Master; Sql_Detail_l:=Sql_Detail; sql_master_add_l:=sql_master_add; Database.Handle:=DB; Type_R:=Type_Report; FV:=FieldView; NFV:=NotFieldView; FNR:=FieldNameReport; ReportName:=Report_Name; LastIg:=LastIgnor; TimerReports.Enabled:=true; pFIBDataSetSchDB.Database:=Database; pFIBDataSetSchDB.Transaction:=Transaction; pFIBDataSetSchDB.Active:=false; pFIBDataSetSchDB.ParamByName('ID_SESSION').AsVariant:=FNR[2][0]; pFIBDataSetSchDB.Active:=true; pFIBDataSetSchDB.FetchAll; RxMemoryDataDB.EmptyTable; for i:=0 to pFIBDataSetSchDB.RecordCount-1 do begin RxMemoryDataDB.Open; RxMemoryDataDB.Insert; RxMemoryDataDB.FieldByName('RxSelectField').Value:=1; RxMemoryDataDB.FieldByName('RxNameField').Value:=pFIBDataSetSchDB.FieldByName('sch_number_db').AsString; RxMemoryDataDB.FieldByName('RxNameVariant').Value:=pFIBDataSetSchDB.FieldByName('sch_title_db').AsString; RxMemoryDataDB.Post; pFIBDataSetSchDB.Next; end; pFIBDataSetSchCR.Database:=Database; pFIBDataSetSchCR.Transaction:=Transaction; pFIBDataSetSchCR.Active:=false; pFIBDataSetSchCR.ParamByName('ID_SESSION').AsInt64:=FNR[2][0]; pFIBDataSetSchCR.Active:=true; pFIBDataSetSchCR.FetchAll; RxMemoryDataCR.EmptyTable; for i:=0 to pFIBDataSetSchCR.RecordCount-1 do begin RxMemoryDataCR.Open; RxMemoryDataCR.Insert; RxMemoryDataCR.FieldByName('RxSelectField').Value:=1; RxMemoryDataCR.FieldByName('RxNameField').Value:=pFIBDataSetSchCR.FieldByName('sch_number_kd').AsString; RxMemoryDataCR.FieldByName('RxNameVariant').Value:=pFIBDataSetSchCR.FieldByName('sch_title_kd').AsString; RxMemoryDataCR.Post; pFIBDataSetSchCR.Next; end; pFIBDataSetSM.Database:=Database; pFIBDataSetSM.Transaction:=Transaction; pFIBDataSetSM.Active:=false; pFIBDataSetSM.ParamByName('ID_SESSION').AsInt64:=FNR[2][0]; pFIBDataSetSM.Active:=true; pFIBDataSetSM.FetchAll; RxMemoryDataSM.EmptyTable; for i:=0 to pFIBDataSetSM.RecordCount-1 do begin RxMemoryDataSM.Open; RxMemoryDataSM.Insert; RxMemoryDataSM.FieldByName('RxSelectField').Value:=1; RxMemoryDataSM.FieldByName('RxNameField').Value:=pFIBDataSetSM.FieldByName('SMETA_KOD').AsString+'.'+pFIBDataSetSM.FieldByName('RAZD_KOD').AsString+'.'+pFIBDataSetSM.FieldByName('ST_KOD').AsString+'.'+pFIBDataSetSM.FieldByName('KEKV_KOD').AsString; RxMemoryDataSM.FieldByName('RxNameVariant').Value:=pFIBDataSetSM.FieldByName('SMETA_TITLE').AsString; RxMemoryDataSM.FieldByName('RxMemoryDataSM').Value:=pFIBDataSetSM.FieldByName('SMETA_KOD').AsVariant; RxMemoryDataSM.FieldByName('RxMemoryDataRAZD').Value:=pFIBDataSetSM.FieldByName('RAZD_KOD').AsVariant; RxMemoryDataSM.FieldByName('RxMemoryDataST').Value:=pFIBDataSetSM.FieldByName('ST_KOD').AsVariant; RxMemoryDataSM.FieldByName('RxMemoryDataKEKV').Value:=pFIBDataSetSM.FieldByName('KEKV_KOD').AsVariant; RxMemoryDataSM.Post; pFIBDataSetSM.Next; end; end; procedure TfrmMainPayOnDay.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure TfrmMainPayOnDay.cxButtonCancelClick(Sender: TObject); begin Close; end; procedure TfrmMainPayOnDay.cxButtonOKClick(Sender: TObject); var sql_where_db,sql_where_cr,sql_where_sm,sql_master_result,sql_detail_result:String; i:Integer; MFR:TfrxMemoView; begin sql_where_db:=''; RxMemoryDataDB.First; for i:=0 to RxMemoryDataDB.RecordCount-1 do begin if RxMemoryDataDB.FieldByName('RxSelectField').Value=1 then begin if sql_where_db<>'' then begin sql_where_db:=sql_where_db+' or '; end; sql_where_db:=sql_where_db+ ' ST_DT_REPORT_PAY_DOC_PROV.SCH_NUMBER_DB='+''''+RxMemoryDataDB.FieldByName('RxNameField').AsString+''''; end; RxMemoryDataDB.next; end; sql_where_db:='('+sql_where_db+')'; sql_where_cr:=''; RxMemoryDataCR.First; for i:=0 to RxMemoryDataCR.RecordCount-1 do begin if RxMemoryDataCR.FieldByName('RxSelectField').Value=1 then begin if sql_where_cr<>'' then begin sql_where_cr:=sql_where_cr+' or '; end; sql_where_cr:=sql_where_cr+ ' ST_DT_REPORT_PAY_DOC_PROV.SCH_NUMBER_KD='+''''+RxMemoryDataCR.FieldByName('RxNameField').AsString+''''; end; RxMemoryDataCR.next; end; sql_where_cr:='('+sql_where_cr+')'; sql_where_sm:=''; RxMemoryDataSM.First; for i:=0 to RxMemoryDataSM.RecordCount-1 do begin if RxMemoryDataSM.FieldByName('RxSelectField').Value=1 then begin if sql_where_sm<>'' then begin sql_where_sm:=sql_where_sm+' or '; end; sql_where_sm:=sql_where_sm+ '(ST_DT_REPORT_PAY_DOC_PROV.SMETA_KOD='+''''+RxMemoryDataSM.FieldByName('RxMemoryDataSM').asString+''''; sql_where_sm:=sql_where_sm+ ' and ST_DT_REPORT_PAY_DOC_PROV.RAZD_KOD='+''''+RxMemoryDataSM.FieldByName('RxMemoryDataRAZD').asString+''''; sql_where_sm:=sql_where_sm+ ' and ST_DT_REPORT_PAY_DOC_PROV.ST_KOD='+''''+RxMemoryDataSM.FieldByName('RxMemoryDataST').asString+''''; sql_where_sm:=sql_where_sm+ ' and ST_DT_REPORT_PAY_DOC_PROV.KEKV_KOD='+''''+RxMemoryDataSM.FieldByName('RxMemoryDataKEKV').asString+''''+')'; end; RxMemoryDataSM.next; end; sql_where_sm:='('+sql_where_sm+')'; // FNR sql_master_result:=Sql_Master_l+' and '+sql_where_db+' and '+sql_where_cr+' and '+sql_where_sm+sql_master_add_l; sql_detail_result:=Sql_Detail_l+' and '+sql_where_db+' and '+sql_where_cr+' and '+sql_where_sm+' ORDER BY FAMILIA,IMYA,OTCHESTVO'; if (sql_where_db='()') then begin messageBox(Handle,PChar('Не выбран дебетовый счет'), PChar(StudcityConst.Studcity_MESSAGE_WARNING_CONST),MB_ICONWARNING or MB_OK); exit; end; if (sql_where_cr='()') then begin messageBox(Handle,PChar('Не выбран кредитовый счет'), PChar(StudcityConst.Studcity_MESSAGE_WARNING_CONST),MB_ICONWARNING or MB_OK); exit; end; if (sql_where_sm='()') then begin messageBox(Handle,PChar('Не выбрана смета '), PChar(StudcityConst.Studcity_MESSAGE_WARNING_CONST),MB_ICONWARNING or MB_OK); exit; end; if Type_R=0 then begin pFIBDataSetPrintMaster.Active:=false; pFIBDataSetPrintMaster.SQLs.SelectSQL.Clear; pFIBDataSetPrintMaster.SQLs.SelectSQL.Add(sql_master_result); pFIBDataSetPrintMaster.Active:=true; pFIBDataSetPrintDetail.Active:=false; pFIBDataSetPrintDetail.SQLs.SelectSQL.Clear; pFIBDataSetPrintDetail.SQLs.SelectSQL.Add(sql_detail_result); end; frxReport.Clear; frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'RPayOnDay'+'.fr3'); frxReport.Variables.Clear; frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+''''; frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+''''; frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+''''; frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+''''; frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+''''; frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+''''; frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+''''; frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+''''; frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+''''; frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+''''; frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+''''; frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+''''; frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+''''; frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+''''; frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+''''; frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+''''; frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+''''; for i:=0 to VarArrayHighBound(FV,1) do begin MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView; MFR.Visible:=true; end; for i:=0 to VarArrayHighBound(NFV,1) do begin MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView; MFR.Visible:=false; MFR.DataSet:=nil; end; // frxReport.DesignReport; frxReport.PrepareReport(true); frxReport.ShowPreparedReport; end; end.
unit sgDriverAudioSDL2; interface // Loads the AudioDriver with the procedures required to access SDL_Mixer procedure LoadSDL2MixerAudioDriver(); implementation uses sgDriverAudio, sgTypes, sgShared, sysUtils, sgDriverSDL2Types, sgBackendTypes; function OpenAudioProcedure() : Boolean; begin _sg_functions^.audio.open_audio(); result := true; end; procedure CloseAudioProcedure(); begin _sg_functions^.audio.close_audio(); end; // GetErrorProcedure gets an audio error and returns the error as // a pascal string function GetErrorProcedure() : String; begin result := 'TODO: ERROR MESSAGE'; //TODO: add error message end; //============================================================================= // Sound Effects //============================================================================= function _LoadSoundData(const filename, name: String; kind: sg_sound_kind) : Pointer; var sndData: ^sg_sound_data; begin New(sndData); result := sndData; sndData^ := _sg_functions^.audio.load_sound_data(PChar(filename), kind); if sndData^._data = nil then begin Dispose(sndData); result := nil; RaiseWarning('Error loading sound data for ' + name + ' (' + filename + ')'); end; end; //TODO: most of this can be moved to sgAudio function LoadSoundEffectProcedure(const filename, name: String) : SoundEffect; var s: SoundEffectPtr; begin //TODO: Move some of this to Audio unit New(s); s^.effect := _LoadSoundData(filename, name, SGSD_SOUND_EFFECT); if s^.effect = nil then begin s^.id := NONE_PTR; Dispose(s); s := nil; end else begin s^.id := AUDIO_PTR; s^.filename := filename; s^.name := name; end; result := s; end; function _Effect(sound: SoundEffect): Pointer; var s: SoundEffectPtr; begin s := ToSoundEffectPtr(sound); if Assigned(s) then result := s^.effect else result := nil; end; procedure StopSoundEffectProcedure(sound : SoundEffect); begin _sg_functions^.audio.stop_sound(_Effect(sound)); end; procedure FreeSoundEffectProcedure(sound : SoundEffect); var sndData: ^sg_sound_data; s: SoundEffectPtr; begin s := ToSoundEffectPtr(sound); sndData := s^.effect; _sg_functions^.audio.close_sound_data(sndData); Dispose(sndData); s^.effect := nil; s^.id := NONE_PTR; end; function PlaySoundEffectProcedure(sound : SoundEffect; loops : Integer; volume : Single) : Boolean; begin _sg_functions^.audio.play_sound(_Effect(sound), loops, volume); result := true; end; // Gets the volume of a sound effect, returns a negative single if // the effect isn't playing. function GetSoundEffectVolumeProcedure(sound : SoundEffect) : Single; begin result := _sg_functions^.audio.sound_volume(_Effect(sound)); end; procedure SetSoundEffectVolumeProcedure(sound : SoundEffect; newVolume : Single); begin _sg_functions^.audio.set_sound_volume(_Effect(sound), newVolume); end; function SoundEffectPlayingProcedure(sound : SoundEffect) : Boolean; begin result := _sg_functions^.audio.sound_playing(_Effect(sound)) <> 0; end; //============================================================================= // Music //============================================================================= // MusicPlaying returns true if music is currently being played function MusicPlayingProcedure() : Boolean; begin result := _sg_functions^.audio.music_playing() <> 0; end; procedure PauseMusicProcedure(); begin _sg_functions^.audio.pause_music(); end; procedure ResumeMusicProcedure(); begin _sg_functions^.audio.resume_music(); end; procedure StopMusicProcedure(); begin _sg_functions^.audio.stop_music(); end; //TODO: Move this to Audio unit function LoadMusicProcedure(const filename, name: String): Music; var m: MusicPtr; begin New(m); m^.effect := _LoadSoundData(filename, name, SGSD_MUSIC); if m^.effect = nil then begin m^.id := NONE_PTR; Dispose(m); m := nil; end else begin m^.id := MUSIC_PTR; m^.filename := filename; m^.name := name; end; result := m; end; function _Music(music: Music): Pointer; var m: MusicPtr; begin m := ToMusicPtr(music); if Assigned(m) then result := m^.effect else result := nil; end; procedure FreeMusicProcedure(music : Music); var m: MusicPtr; sndData: ^sg_sound_data; begin m := ToMusicPtr(music); sndData := m^.effect; _sg_functions^.audio.close_sound_data(sndData); Dispose(sndData); m^.effect := nil; m^.id := NONE_PTR; end; procedure SetMusicVolumeProcedure(newVolume : Single); begin _sg_functions^.audio.set_music_vol(newVolume); end; function GetMusicVolumeProcedure() : Single; begin result := _sg_functions^.audio.music_vol(); end; function PlayMusicProcedure(music : Music; loops : Integer) : Boolean; var pct: Single; begin pct := GetMusicVolumeProcedure(); _sg_functions^.audio.play_sound(_Music(music), loops, pct); result := true; end; function FadeMusicInProcedure(music : Music; loops, ms : Integer) : Boolean; begin _sg_functions^.audio.fade_in(_Music(music), loops, ms); result := true; end; function FadeMusicOutProcedure(ms : Integer) : Boolean; begin WriteLn('fade out'); _sg_functions^.audio.fade_out(_sg_functions^.audio.current_music(), ms); result := true; end; //============================================================================= // Loads the procedures and functions into the audio driver //============================================================================= procedure LoadSDL2MixerAudioDriver(); begin //WriteLn('Loading SDL_Mixer Audio Driver...'); AudioDriver.LoadSoundEffect := @LoadSoundEffectProcedure; // # AudioDriver.OpenAudio := @OpenAudioProcedure; // # AudioDriver.CloseAudio := @CloseAudioProcedure; // # AudioDriver.SetMusicVolume := @SetMusicVolumeProcedure; // # AudioDriver.GetMusicVolume := @GetMusicVolumeProcedure; // # AudioDriver.GetError := @GetErrorProcedure; AudioDriver.FreeSoundEffect := @FreeSoundEffectProcedure; // # AudioDriver.LoadMusic := @LoadMusicProcedure; // # AudioDriver.FreeMusic := @FreeMusicProcedure; // # AudioDriver.PlaySoundEffect := @PlaySoundEffectProcedure; // # AudioDriver.PlayMusic := @PlayMusicProcedure; // # AudioDriver.FadeMusicIn := @FadeMusicInProcedure; // # AudioDriver.FadeMusicOut := @FadeMusicOutProcedure; // # + all snd effects //TODO: Use this! AudioDriver.SetSoundEffectVolume := @SetSoundEffectVolumeProcedure; // # AudioDriver.GetSoundEffectVolume := @GetSoundEffectVolumeProcedure; // # AudioDriver.SoundEffectPlaying := @SoundEffectPlayingProcedure; // # AudioDriver.MusicPlaying := @MusicPlayingProcedure; // # AudioDriver.PauseMusic := @PauseMusicProcedure; // # AudioDriver.ResumeMusic := @ResumeMusicProcedure; // # AudioDriver.StopMusic := @StopMusicProcedure; // # AudioDriver.StopSoundEffect := @StopSoundEffectProcedure; // # end; end.
/////////////////////////////////////////////////////////////////////////////// Function LookupSetting(const SettingTable : TStringList; const Section : TDynamicString; const SettingType : TDynamicString; var Setting : TDyanmicString) : Boolean; Var index : Integer; i : Integer; str_list : TStringList; str : TDynamicString; prefix : TDynamicString; Begin Result := False; If SettingTable.Find(Section, index) Then Begin str_list := SettingTable.Objects[index]; For i := 0 To (str_list.Count - 1) Do Begin str := str_list[i]; prefix := Section + SettingType; If (1 = Pos(prefix, str)) Then Begin Setting := Copy(str, Length(prefix) + 1, Length(str) - Length(prefix)); Result := True; Exit; End; End; End; End; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Function ReadDesignSettings(const InputFile : TDynamicString; SettingTable : TStringList) : Boolean; Var in_file : Text; str : TDynamicString; section : TDynamicString; str_list : TStringList; Var index : Integer; Begin Result := False; AssignFile(in_file, InputFile); Reset(in_file); While Not Eof(in_file) Do Begin ReadLn(in_file, str); If str <> Null Then Begin str := Trim(str); If Length(str) > 0 Then Begin If (str[1] >= Chr('0')) and (str[1] <= Chr('9')) Then // Is digit Begin Break; End; section := Copy(str, 1, 2); If SettingTable.Find(section, index) Then Begin str_list := SettingTable.Objects[index]; str_list.Add(str); End; End; End; End; CloseFile(in_file); Result := True; End; ///////////////////////////////////////////////////////////////////////////////
(* Category: SWAG Title: OOP/TURBO VISION ROUTINES Original name: 0033.PAS Description: TVision Backgrounds Author: MARTIN WERNER Date: 01-27-94 12:23 *) { > I'm starting to play with TVision 1 and I would like to know how > to change the background fill character. Working example: } program otherbackground; uses app, objects; type pmyapp=^tmyapp; tmyapp=object(tapplication) constructor init; end; constructor tmyapp. init; var r: trect; begin tapplication. init; desktop^. getextent(r); dispose(desktop^. background, done); desktop^. background:=new(pbackground, init(r, '.')); desktop^. insert(desktop^. background); end; var myapp: tmyapp; begin myapp. init; myapp. run; myapp. done; end.
unit skinDropFileListBox; interface uses Classes,bsfilectrl,Messages,Windows,ShellAPI; type TDropFileNotifyEvent = procedure (Sender:TObject;FileNames:TStringList) of object; TskinDropFileListBox = class(TbsSkinFileListBox) private FEnabled:Boolean; FDropFile:TDropFileNotifyEvent; procedure DropFiles(var Msg:Tmessage); message WM_DROPFILES; procedure SetDropEnabled(bEnabled:Boolean); public constructor Create(AOwner:TComponent);override; published property OnDropFiles: TDropFileNotifyEvent read FDropFile write FDropFile; property DropEnabled: Boolean read FEnabled write SetDropEnabled; end; procedure Register; implementation { TskinDropFileListBox } procedure Register; begin RegisterComponents('myDropFileList',[TskinDropFileListBox]); end; constructor TskinDropFileListBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FEnabled := True; end; procedure TskinDropFileListBox.DropFiles(var Msg: Tmessage); var FileNames:TStringList; FileName:array [0..MAX_PATH - 1] of Char; i,nCount:integer; begin try FileNames := TStringList.Create; nCount := DragQueryFile(Msg.WParam,$FFFFFFFF,@FileName,MAX_PATH); for I := 0 to nCount - 1 do begin DragQueryFile(Msg.WParam,i,FileName,MAX_PATH); FileNames.Add(FileName); end; DragFinish(Msg.WParam); if Assigned(FDropFile) then FDropFile(Self,FileNames); finally FileNames.Free; end; end; procedure TskinDropFileListBox.SetDropEnabled(bEnabled: Boolean); begin FEnabled := bEnabled; DragAcceptFiles(Handle,bEnabled); end; end.
{************************************************************ This Unit contains: - The class/component TDirLabel. - The property editor TAbout. Suitable for Delphi 1, Delphi 2 and Delphi 3. Main purpose off the component TDirLabel: - Displaying a filename with path in a label which has a fixed width. Therefore the path has to be made shorter if necessary and possible, e.g.: c:\program\delphi\testen1\testen2\filenaam.pas can become something like: c:\...\testen1\testen2\filenaam.pas Programmer : Frank Millenaar Ir. Place : Utrecht Date Start : 5- 1-1998 Latest change : 10- 1-1998 ************************************************************} unit DirLabel; interface uses {$IFDEF WIN32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, Menus; type TDirLabel = class(TCustomLabel) private { Private declarations } FDirName: String; procedure SetDirName(Value: String); function MakePathShorterByOneDir(Var Pad: String): Boolean; function KortPadIn(Pad: String; maxL: Integer): String; protected { Protected declarations } procedure Paint; override; procedure DoDrawText(var Rect: TRect; Flags: LongInt); override; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; published { Published declarations } property DirName: String read FDirName write SetDirName; property Align; property Alignment; {property AutoSize; You don't wand AutoSize.} {property Caption; Caption is replaced by DirName.} property Color; property DragCursor; property DragMode; property Enabled; property FocusControl; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowAccelChar; property ShowHint; property Transparent; {property Layout; Delphi 3 only} property Visible; {property WordWrap; You don't wand wordwrap.} property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; {$IFDEF WIN32} property OnStartDrag; {$ENDIF} end; procedure Register; implementation uses Types; procedure Register; begin RegisterComponents('ConTEXT Components', [TDirLabel]); end; constructor TDirLabel.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 65; Height := 17; AutoSize := False; WordWrap := False; FDirName := Caption; end; procedure TDirLabel.SetDirName(Value: String); begin if FDirName <> Value then begin FDirName := Value; Caption := Value; Invalidate; end; end; procedure TDirLabel.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin {Design time changing the width of DirLabel, will give automaticly adjustment of the path and filename.} if not (csLoading in ComponentState) then if (AWidth <> Width) then if FDirName = '' then FDirName := Caption {some how necessary} else Caption := FDirName; {This couses the proper adjustment.} inherited SetBounds(ALeft, ATop, AWidth, AHeight); end; procedure TDirLabel.DoDrawText(var Rect: TRect; Flags: LongInt); var Text: string; PText: array[0..255] of char; begin Text := Caption; {GetLabelText; not compatible with D1} if (Flags and DT_CALCRECT <> 0) and (Text = '') then Text := Text + ' '; Canvas.Font := Font; StrPCopy(PText, Text); {PChar(Text) is not compatible with D1} if not Enabled then begin OffsetRect(Rect, 1, 1); Canvas.Font.Color := clBtnHighlight; DrawText(Canvas.Handle, PText, Length(Text), Rect, Flags); OffsetRect(Rect, -1, -1); Canvas.Font.Color := clBtnShadow; DrawText(Canvas.Handle, PText, Length(Text), Rect, Flags); end else DrawText(Canvas.Handle, PText, Length(Text), Rect, Flags); end; procedure TDirLabel.Paint; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect, CalcRect: TRect; DrawStyle: Integer; Text: String; WidthToLong: Integer; begin with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; Rect := ClientRect; DrawStyle := DT_EXPANDTABS or DT_SINGLELINE or DT_LEFT or Alignments[Alignment]; {Calculate with} Text := Caption; {With DT_CALCRECT there will be no drawing, you get back the demension of the text ractangle.} DoDrawText(CalcRect, DrawStyle or DT_CALCRECT); {CalcRect.left and right are negative numbers! Therefore WidthToLong := width - (-CalcRect.left - -CalcRect.right) - 1; becoms like the next line.} WidthToLong := width + CalcRect.left -CalcRect.right - 1; while (widthToLong < 0) and (Text <> '') do begin {Try to remove the most left directory in the 'Pad'.} if MakePathShorterByOneDir(Text) then begin {calculate new width} Caption := Text; DoDrawText(CalcRect, DrawStyle or DT_CALCRECT); WidthToLong := width + CalcRect.left -CalcRect.right - 1; end else begin Text := ''; end; end; DoDrawText(Rect, DrawStyle); end; end; function TDirLabel.MakePathShorterByOneDir(Var Pad: String): Boolean; {Try to remove the most left directory in the 'Pad'.} var LengthPadIn: Integer; i: Integer; NewPad: String; begin LengthPadIn := length(Pad); NewPad := Pad; i:= LengthPadIn; while (length(NewPad) = LengthPadIn) and (i > 18) do begin NewPad := KortPadIn(NewPad, i); dec(i); end; Pad := NewPad; if (length(NewPad) = LengthPadIn) then Result := False else Result := True; end; function TDirLabel.KortPadIn(Pad: String; maxL: Integer): String; { Tested for: E:\dcode\remainde\rem.db 19 -> E:\..rem.db E:\dcode\remainde\rem.db 20 -> E:\..\remainde\rem.db E:\dcode\remainde\test\a 19 -> E:\..\test\a E:\dcode\remainde\test\a 20 -> E:\..\remainde\test\a 1995, Turbo Pascal } const start = 6; {for e.g. 'c:\...' } MinFileL = 12; {8 characters for the name bevore the point 3 characters for the extention and 1 for the point.} var TempPad: String; Lfile: Integer; {lengte filenaam} i: Integer; begin If (length(Pad) > maxL) and (maxL > (start+MinFileL) ) then {stop if: -path is short enaugh or -The new to make path lenght is shorter then (start+MinFileL) characters (6 + 12). } begin Lfile := Length(Pad); for i := Length(Pad) downto 0 do {Determen length filename} begin If Pad[i] = '\' then begin Lfile := Length(Pad)-i; Break; end; end; if (Lfile + start) >= maxL then TempPad := copy(Pad, length(Pad)-Lfile, 255) else TempPad := copy(Pad, length(Pad)-maxL+start, 255); if (length(TempPad)-Lfile) > 1 then begin {find the first '\' from the left} for i := 1 to (length(TempPad)-Lfile) do begin If TempPad[i] = '\' then begin {copy everything after the first '\' from the left} TempPad := copy(TempPad, i, 255); Break; end; end; end; TempPad := copy(Pad, 1, 3) + '...' + TempPad; KortPadIn := TempPad; end else KortPadIn := Pad; end; end.
unit Form.TestPrg; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type Tfrm_TestCopyFile = class(TForm) Label1: TLabel; Label2: TLabel; edt_Datei: TEdit; edt_Ziel: TEdit; btn_Copy: TButton; procedure FormCreate(Sender: TObject); procedure btn_CopyClick(Sender: TObject); private // FrmCopyFile: Tfrm_CopyFile; procedure KopiereDatei(aSource, aDest: String); procedure AfterCopy(Sender: TObject); public end; var frm_TestCopyFile: Tfrm_TestCopyFile; implementation {$R *.dfm} uses Form.CopyFile; procedure Tfrm_TestCopyFile.FormCreate(Sender: TObject); begin edt_Datei.Text := 'g:\OPTIMA\Update\DLL.Ticket64.dll'; edt_Ziel.Text := 'c:\Users\tbachmann.GB\AppData\Roaming\Optima\DLL.Ticket64.dll'; end; procedure Tfrm_TestCopyFile.btn_CopyClick(Sender: TObject); begin KopiereDatei(edt_Datei.Text, edt_Ziel.Text); end; procedure Tfrm_TestCopyFile.KopiereDatei(aSource, aDest: String); var Form: Tfrm_CopyFile; begin Form := Tfrm_CopyFile.Create(Self); Form.OnAfterCopy := AfterCopy; Form.Show; Form.CopyFile(aSource, aDest); end; procedure Tfrm_TestCopyFile.AfterCopy(Sender: TObject); begin Tfrm_CopyFile(Sender).Close; FreeAndNil(Sender); end; end.
unit DXPColors; interface uses Classes, Graphics, DXPConsts, DXPControl; type TDXPColors = class(TPersistent) private { Private declarations } FBackGroundFrom: TColor; FBackGroundTo: TColor; FBorderEdges: TColor; FBorderLine: TColor; FClickedFrom: TColor; FClickedTo: TColor; FFocusedFrom: TColor; FFocusedTo: TColor; FHighlightFrom: TColor; FHighlightTo: TColor; FHotTrack: TColor; FBorderLineDisabled: TColor; FBorderEdgesDisabled: TColor; procedure SetBorderLineDisabled(const Value: TColor); protected { Protected declarations } FOwner: TObject; procedure RepaintOwner; procedure SetBackGroundFrom(Value: TColor); virtual; procedure SetBackGroundTo(Value: TColor); virtual; procedure SetBorderEdges(Value: TColor); virtual; procedure SetBorderLine(Value: TColor); virtual; procedure SetClickedFrom(Value: TColor); virtual; procedure SetClickedTo(Value: TColor); virtual; procedure SetFocusedFrom(Value: TColor); virtual; procedure SetFocusedTo(Value: TColor); virtual; procedure SetHighlightFrom(Value: TColor); virtual; procedure SetHighlightTo(Value: TColor); virtual; procedure SetHotTrack(Value: TColor); virtual; public { Public declarations } constructor Create(AOwner: TComponent); published { Published declarations } property BackGroundFrom: TColor read FBackGroundFrom write SetBackGroundFrom default DXPColor_Enb_BgFrom_WXP; property BackGroundTo: TColor read FBackGroundTo write SetBackGroundTo default DXPColor_Enb_BgTo_WXP; //property BorderEdges: TColor read FBorderEdges write SetBorderEdges default DXPColor_Enb_Edges_WXP; //property BorderEdgesDisabled: TColor read FBorderEdgesDisabled write SetBorderEdgesDisabled default DXPColor_Dis_Edges_WXP; property BorderLine: TColor read FBorderLine write SetBorderLine default DXPColor_Enb_Border_WXP; property BorderLineDisabled: TColor read FBorderLineDisabled write SetBorderLineDisabled default DXPColor_Dis_Border_WXP; property ClickedFrom: TColor read FClickedFrom write SetClickedFrom default DXPColor_Enb_CkFrom_WXP; property ClickedTo: TColor read FClickedTo write SetClickedTo default DXPColor_Enb_CkTo_WXP; property FocusedFrom: TColor read FFocusedFrom write SetFocusedFrom default DXPColor_Enb_FcFrom_WXP; property FocusedTo: TColor read FFocusedTo write SetFocusedTo default DXPColor_Enb_FcTo_WXP; property HighlightFrom: TColor read FHighlightFrom write SetHighlightFrom default DXPColor_Enb_HlFrom_WXP; property HighlightTo: TColor read FHighlightTo write SetHighlightTo default DXPColor_Enb_HlTo_WXP; //property HotTrack: TColor read FHotTrack write SetHotTrack default DXPColor_Enb_HotTrack_WXP; end; implementation { TDXPColors } constructor TDXPColors.Create(AOwner: TComponent); begin inherited Create; // FOwner := AOwner; FBackGroundFrom := DXPColor_Enb_BgFrom_WXP; FBackGroundTo := DXPColor_Enb_BgTo_WXP; FBorderEdges := DXPColor_Enb_Edges_WXP; FBorderEdgesDisabled := DXPColor_Dis_Edges_WXP; FBorderLine := DXPColor_Enb_Border_WXP; FBorderLineDisabled := DXPColor_Dis_Border_WXP; FClickedFrom := DXPColor_Enb_CkFrom_WXP; FClickedTo := DXPColor_Enb_CkTo_WXP; FFocusedFrom := DXPColor_Enb_FcFrom_WXP; FFocusedTo := DXPColor_Enb_FcTo_WXP; FHighlightFrom := DXPColor_Enb_HlFrom_WXP; FHighlightTo := DXPColor_Enb_HlTo_WXP; FHotTrack := DXPColor_Enb_HotTrack_WXP; end; procedure TDXPColors.RepaintOwner; begin if FOwner is TDXPCustomControl then ( FOwner as TDXPCustomControl ).Redraw; end; procedure TDXPColors.SetBackGroundFrom(Value: TColor); begin if FBackGroundFrom <> Value then FBackGroundFrom := Value; // RepaintOwner; end; procedure TDXPColors.SetBackGroundTo(Value: TColor); begin if FBackGroundTo <> Value then FBackGroundTo := Value; end; procedure TDXPColors.SetBorderEdges(Value: TColor); begin if FBorderEdges <> Value then FBorderEdges := Value; end; procedure TDXPColors.SetBorderLine(Value: TColor); begin if FBorderLine <> Value then FBorderLine := Value; end; procedure TDXPColors.SetBorderLineDisabled(const Value: TColor); begin if FBorderLineDisabled <> Value then FBorderLineDisabled := Value; end; procedure TDXPColors.SetClickedFrom(Value: TColor); begin if FClickedFrom <> Value then FClickedFrom := Value; end; procedure TDXPColors.SetClickedTo(Value: TColor); begin if FClickedTo <> Value then FClickedTo := Value; end; procedure TDXPColors.SetFocusedFrom(Value: TColor); begin if FFocusedFrom <> Value then FFocusedFrom := Value; end; procedure TDXPColors.SetFocusedTo(Value: TColor); begin if FFocusedTo <> Value then FFocusedTo := Value; end; procedure TDXPColors.SetHighlightFrom(Value: TColor); begin if FHighlightFrom <> Value then FHighlightFrom := Value; end; procedure TDXPColors.SetHighlightTo(Value: TColor); begin if FHighlightTo <> Value then FHighlightTo := Value; end; procedure TDXPColors.SetHotTrack(Value: TColor); begin if FHotTrack <> Value then FHotTrack := Value; end; end.
unit DeviceDetect; interface uses Windows, Classes; type PDetectedDevice = ^TDetectedDevice; TDetectedDevice = record friendlyName : string; hardwareID : string; portStart : Int64; portLength : LongWord; irq : Boolean; irqLevel : LongWord; dma : Boolean; dmaChannel : LongWord; end; TDetectedDeviceList = class(TList) private function Get(Index: Integer): PDetectedDevice; public destructor Destroy; override; function Add(Value: PDetectedDevice): Integer; property Items[Index: Integer]: PDetectedDevice read Get; default; end; function getDevicesWDM(DevList: TDetectedDeviceList; DeviceID: String; const Enumerator: PAnsiChar = nil): Boolean;//(var ports: array of TDetectedPort; guid1: TGUID; portPrefix: string): Boolean; implementation uses SysUtils; { TDetectedDeviceList } function TDetectedDeviceList.Add(Value: PDetectedDevice): Integer; begin Result := inherited Add(Value); end; destructor TDetectedDeviceList.Destroy; var i: Integer; begin for i := 0 to Count - 1 do FreeMem(Items[i]); inherited; end; function TDetectedDeviceList.Get(Index: Integer): PDetectedDevice; begin Result := PDetectedDevice(inherited Get(Index)); end; {$ALIGN 1} const setupapi = 'setupapi.dll'; const DIGCF_DEFAULT = $00000001; // only valid with DIGCF_DEVICEINTERFACE DIGCF_PRESENT = $00000002; DIGCF_ALLCLASSES = $00000004; DIGCF_PROFILE = $00000008; DIGCF_DEVICEINTERFACE = $00000010; type GUID = TGUID; ULONG_PTR = PULONG; HDEVINFO = THandle; PVOID = Pointer; SP_DEVINFO_DATA = record cbSize: DWORD; ClassGuid: GUID; DevInst: DWORD; // DEVINST handle Reserved: ULONG_PTR; end; PSP_DEVINFO_DATA = ^SP_DEVINFO_DATA; SP_DEVICE_INTERFACE_DATA = record cbSize: DWORD; InterfaceClassGuid: GUID; Flags: DWORD; Reserved: ULONG_PTR; end; PSP_DEVICE_INTERFACE_DATA = ^SP_DEVICE_INTERFACE_DATA; const SPINT_ACTIVE = $00000001; SPINT_DEFAULT = $00000002; SPINT_REMOVED = $00000004; type SP_DEVICE_INTERFACE_DETAIL_DATA_A = record cbSize: DWORD; //DevicePath: array of CHAR; end; PSP_DEVICE_INTERFACE_DETAIL_DATA_A = ^SP_DEVICE_INTERFACE_DETAIL_DATA_A; const SPDRP_DEVICEDESC = $00000000; SPDRP_HARDWAREID = $00000001; SPDRP_COMPATIBLEIDS = $00000002; SPDRP_UNUSED0 = $00000003; SPDRP_SERVICE = $00000004; SPDRP_UNUSED1 = $00000005; SPDRP_UNUSED2 = $00000006; SPDRP_CLASS = $00000007; SPDRP_CLASSGUID = $00000008; SPDRP_DRIVER = $00000009; SPDRP_CONFIGFLAGS = $0000000A; SPDRP_MFG = $0000000B; SPDRP_FRIENDLYNAME = $0000000C; SPDRP_LOCATION_INFORMATION = $0000000D; SPDRP_PHYSICAL_DEVICE_OBJECT_NAME = $0000000E; SPDRP_CAPABILITIES = $0000000F; SPDRP_UI_NUMBER = $00000010; SPDRP_UPPERFILTERS = $00000011; SPDRP_LOWERFILTERS = $00000012; SPDRP_BUSTYPEGUID = $00000013; SPDRP_LEGACYBUSTYPE = $00000014; SPDRP_BUSNUMBER = $00000015; SPDRP_ENUMERATOR_NAME = $00000016; SPDRP_SECURITY = $00000017; SPDRP_SECURITY_SDS = $00000018; SPDRP_DEVTYPE = $00000019; SPDRP_EXCLUSIVE = $0000001A; SPDRP_CHARACTERISTICS = $0000001B; SPDRP_ADDRESS = $0000001C; SPDRP_UI_NUMBER_DESC_FORMAT = $0000001D; SPDRP_DEVICE_POWER_DATA = $0000001E; SPDRP_REMOVAL_POLICY = $0000001F; SPDRP_REMOVAL_POLICY_HW_DEFAULT = $00000020; SPDRP_REMOVAL_POLICY_OVERRIDE = $00000021; SPDRP_INSTALL_STATE = $00000022; SPDRP_LOCATION_PATHS = $00000023; SPDRP_MAXIMUM_PROPERTY = $00000024; DICS_ENABLE = $00000001; DICS_DISABLE = $00000002; DICS_PROPCHANGE = $00000003; DICS_START = $00000004; DICS_STOP = $00000005; DICS_FLAG_GLOBAL = $00000001; DICS_FLAG_CONFIGSPECIFIC = $00000002; DICS_FLAG_CONFIGGENERAL = $00000004; DIREG_DEV = $00000001; DIREG_DRV = $00000002; DIREG_BOTH = $00000004; DIOCR_INSTALLER = $00000001; DIOCR_INTERFACE = $00000002; var hSetupapi: HINST; SetupDiClassGuidsFromNameA: function( ClassName: LPCTSTR; ClassGuidList: PGUID; ClassGuidListSize: DWORD; RequiredSize: PDWORD ): LongBool; stdcall; SetupDiGetClassDevsA: function( ClassGuid: PGUID; Enumerator: LPCSTR; hwndParent: HWND; Flags: DWORD ): HDEVINFO; stdcall; SetupDiDestroyDeviceInfoList: function( DeviceInfoSet: HDEVINFO ): LongBool; stdcall; SetupDiEnumDeviceInfo: function( DeviceInfoSet: HDEVINFO; MemberIndex: DWORD; DeviceInfoData: PSP_DEVINFO_DATA ): LongBool; stdcall; SetupDiEnumDeviceInterfaces: function( DeviceInfoSet: HDEVINFO; DeviceInfoData: PSP_DEVINFO_DATA; InterfaceClassGuid: PGUID; MemberIndex: DWORD; DeviceInterfaceData: PSP_DEVICE_INTERFACE_DATA ): LongBool; stdcall; SetupDiGetDeviceInterfaceDetailA: function( DeviceInfoSet: HDEVINFO; DeviceInterfaceData: PSP_DEVICE_INTERFACE_DATA; DeviceInterfaceDetailData: PSP_DEVICE_INTERFACE_DETAIL_DATA_A; DeviceInterfaceDetailDataSize: DWORD; RequiredSize: PDWORD; DeviceInfoData: PSP_DEVINFO_DATA ): LongBool; stdcall; SetupDiGetDeviceInstanceIdA: function( DeviceInfoSet: HDEVINFO; DeviceInfoData: PSP_DEVINFO_DATA; DeviceInstanceId: LPSTR; DeviceInstanceIdSize: DWORD; RequiredSize: PDWORD ): LongBool; stdcall; SetupDiGetDeviceRegistryPropertyA: function( DeviceInfoSet: HDEVINFO; DeviceInfoData: PSP_DEVINFO_DATA; Property1: DWORD; PropertyRegDataType: PDWORD; PropertyBuffer: PBYTE; PropertyBufferSize: DWORD; RequiredSize: PDWORD ): LongBool; stdcall; SetupDiOpenClassRegKeyExA: function( ClassGuid: PGUID; samDesired: REGSAM; Flags: DWORD; MachineName: LPCTSTR; Reserved: PVOID ): HKEY; stdcall; SetupDiOpenDevRegKey: function( DeviceInfoSet: HDEVINFO; DeviceInfoData: PSP_DEVINFO_DATA; Scope: DWORD; HwProfile: DWORD; KeyType: DWORD; samDesired: REGSAM ): HKEY; stdcall; {$ALIGN 8} {$ALIGN 1} const cfgmgr32 = 'cfgmgr32.dll'; const BASIC_LOG_CONF = $00000000; FILTERED_LOG_CONF = $00000001; ALLOC_LOG_CONF = $00000002; BOOT_LOG_CONF = $00000003; FORCED_LOG_CONF = $00000004; OVERRIDE_LOG_CONF = $00000005; NUM_LOG_CONF = $00000006; LOG_CONF_BITS = $00000007; CR_SUCCESS = $00000000; CR_DEFAULT = $00000001; CR_OUT_OF_MEMORY = $00000002; CR_INVALID_POINTER = $00000003; CR_INVALID_FLAG = $00000004; CR_INVALID_DEVNODE = $00000005; CR_INVALID_DEVINST = CR_INVALID_DEVNODE; CR_INVALID_RES_DES = $00000006; CR_INVALID_LOG_CONF = $00000007; CR_INVALID_ARBITRATOR = $00000008; CR_INVALID_NODELIST = $00000009; CR_DEVNODE_HAS_REQS = $0000000A; CR_DEVINST_HAS_REQS = CR_DEVNODE_HAS_REQS; CR_INVALID_RESOURCEID = $0000000B; CR_DLVXD_NOT_FOUND = $0000000C; CR_NO_SUCH_DEVNODE = $0000000D; CR_NO_SUCH_DEVINST = CR_NO_SUCH_DEVNODE; CR_NO_MORE_LOG_CONF = $0000000E; CR_NO_MORE_RES_DES = $0000000F; CR_ALREADY_SUCH_DEVNODE = $00000010; CR_ALREADY_SUCH_DEVINST = CR_ALREADY_SUCH_DEVNODE; CR_INVALID_RANGE_LIST = $00000011; CR_INVALID_RANGE = $00000012; CR_FAILURE = $00000013; CR_NO_SUCH_LOGICAL_DEV = $00000014; CR_CREATE_BLOCKED = $00000015; CR_NOT_SYSTEM_VM = $00000016; CR_REMOVE_VETOED = $00000017; CR_APM_VETOED = $00000018; CR_INVALID_LOAD_TYPE = $00000019; CR_BUFFER_SMALL = $0000001A; CR_NO_ARBITRATOR = $0000001B; CR_NO_REGISTRY_HANDLE = $0000001C; CR_REGISTRY_ERROR = $0000001D; CR_INVALID_DEVICE_ID = $0000001E; CR_INVALID_DATA = $0000001F; CR_INVALID_API = $00000020; CR_DEVLOADER_NOT_READY = $00000021; CR_NEED_RESTART = $00000022; CR_NO_MORE_HW_PROFILES = $00000023; CR_DEVICE_NOT_THERE = $00000024; CR_NO_SUCH_VALUE = $00000025; CR_WRONG_TYPE = $00000026; CR_INVALID_PRIORITY = $00000027; CR_NOT_DISABLEABLE = $00000028; CR_FREE_RESOURCES = $00000029; CR_QUERY_VETOED = $0000002A; CR_CANT_SHARE_IRQ = $0000002B; CR_NO_DEPENDENT = $0000002C; CR_SAME_RESOURCES = $0000002D; CR_NO_SUCH_REGISTRY_KEY = $0000002E; CR_INVALID_MACHINENAME = $0000002F; CR_REMOTE_COMM_FAILURE = $00000030; CR_MACHINE_UNAVAILABLE = $00000031; CR_NO_CM_SERVICES = $00000032; CR_ACCESS_DENIED = $00000033; CR_CALL_NOT_IMPLEMENTED = $00000034; CR_INVALID_PROPERTY = $00000035; CR_DEVICE_INTERFACE_ACTIVE = $00000036; CR_NO_SUCH_DEVICE_INTERFACE = $00000037; CR_INVALID_REFERENCE_STRING = $00000038; CR_INVALID_CONFLICT_LIST = $00000039; CR_INVALID_INDEX = $0000003A; CR_INVALID_STRUCTURE_SIZE = $0000003B; NUM_CR_RESULTS = $0000003C; ResType_All = $00000000; ResType_None = $00000000; ResType_Mem = $00000001; ResType_IO = $00000002; ResType_DMA = $00000003; ResType_IRQ = $00000004; ResType_DoNotUse = $00000005; ResType_BusNumber = $00000006; ResType_MAX = $00000006; ResType_Ignored_Bit = $00008000; ResType_ClassSpecific = $0000FFFF; ResType_Reserved = $00008000; ResType_DevicePrivate = $00008001; ResType_PcCardConfig = $00008002; ResType_MfCardConfig = $00008003; type DWORD_PTR = DWORD; LOG_CONF = DWORD_PTR; PLOG_CONF = ^LOG_CONF; DEVNODE = DWORD; PDEVNOD = ^DEVNODE; DEVINST = DWORD; PDEVINST = ^DEVINST; RETURN_TYPE = DWORD; CONFIGRET = RETURN_TYPE; RES_DES = DWORD_PTR; PRES_DES = ^RES_DES; RESOURCEID = ULONG; PRESOURCEID = ^RESOURCEID; DWORDLONG = Int64; ULONG32 = ULONG; IO_DES = record IOD_Count: DWORD; IOD_Type: DWORD; IOD_Alloc_Base: DWORDLONG; IOD_Alloc_End: DWORDLONG; IOD_DesFlags: DWORD; end; PIO_DES = ^IO_DES; IO_RANGE = record IOR_Align: DWORDLONG; IOR_nPorts: DWORD; IOR_Min: DWORDLONG; IOR_Max: DWORDLONG; IOR_RangeFlags: DWORD; IOR_Alias: DWORDLONG; end; PIO_RANGE = ^IO_RANGE; IO_RESOURCE = record IO_Header: IO_DES; IO_Data: array of IO_RANGE; end; PIO_RESOURCE = ^IO_RESOURCE; DMA_RANGE = record DR_Min: ULONG; DR_Max: ULONG; DR_Flags: ULONG; end; PDMA_RANGE = ^DMA_RANGE; DMA_DES = record DD_Count: DWORD; DD_Type: DWORD; DD_Flags: DWORD; DD_Alloc_Chan: ULONG; end; PDMA_DES = ^DMA_DES; DMA_RESOURCE = record DMA_Header: DMA_DES; DMA_Data: array of DMA_RANGE; end; PDMA_RESOURCE = ^DMA_RESOURCE; IRQ_RANGE = record IRQR_Min: ULONG; IRQR_Max: ULONG; IRQR_Flags: ULONG; end; PIRQ_RANGE = ^IRQ_RANGE; IRQ_DES_32 = record IRQD_Count: DWORD; IRQD_Type: DWORD; IRQD_Flags: DWORD; IRQD_Alloc_Num: ULONG; IRQD_Affinity: ULONG32; end; PIRQ_DES_32 = ^IRQ_DES_32; IRQ_RESOURCE_32 = record IRQ_Header: IRQ_DES_32; IRQ_Data: array of IRQ_RANGE; end; PIRQ_RESOURCE_32 = ^IRQ_RESOURCE_32; var hCfgmgr32: HINST; CM_Get_First_Log_Conf: function( plcLogConf: PLOG_CONF; dnDevInst: DEVINST; ulFlags: ULONG ): CONFIGRET; stdcall; CM_Free_Log_Conf_Handle: function( lcLogConf: LOG_CONF ): CONFIGRET; stdcall; CM_Get_Next_Res_Des: function( prdResDes: PRES_DES; rdResDes: RES_DES; ForResource: RESOURCEID; pResourceID: PRESOURCEID; ulFlags: ULONG ): CONFIGRET; stdcall; CM_Free_Res_Des_Handle: function( rdResDes: RES_DES ): CONFIGRET; stdcall; CM_Get_Res_Des_Data_Size: function( pulSize: PULONG; rdResDes: RES_DES; ulFlags: ULONG ): CONFIGRET; stdcall; CM_Get_Res_Des_Data: function( rdResDes: RES_DES; Buffer: Pointer; BufferLen: ULONG; ulFlags: ULONG ): CONFIGRET; stdcall; {$ALIGN 8} function extractResourceDesc(PDevice: PDetectedDevice;{var port: TDetectedPort; }resId: RESOURCEID; buffer: PChar; length: Integer): Boolean; var ioResource: IO_RESOURCE; dmaResource: DMA_RESOURCE; irqResource: IRQ_RESOURCE_32; i, p, l: Integer; begin Result := False; case resId of ResType_IO: begin p := 0; l := SizeOf(ioResource) - SizeOf(ioResource.IO_Data); if length >= p + l then begin Move((buffer + p)^, ioResource, l); Inc(p, l); SetLength(ioResource.IO_Data, ioResource.IO_Header.IOD_Count); for i := 0 to ioResource.IO_Header.IOD_Count - 1 do begin l := SizeOf(ioResource.IO_Data[i]); if length >= p + l then begin Move((buffer + p)^, ioResource.IO_Data[i], l); Inc(p, l); end; end; if PDevice.portLength = 0 then begin PDevice.portStart := ioResource.IO_Header.IOD_Alloc_Base; PDevice.portLength := ioResource.IO_Header.IOD_Alloc_End - ioResource.IO_Header.IOD_Alloc_Base + 1; end; Result := True; end; end; ResType_DMA: begin p := 0; l := SizeOf(dmaResource) - SizeOf(dmaResource.DMA_Data); if length >= p + l then begin Move((buffer + p)^, dmaResource, l); Inc(p, l); SetLength(dmaResource.DMA_Data, dmaResource.DMA_Header.DD_Count); for i := 0 to dmaResource.DMA_Header.DD_Count - 1 do begin l := SizeOf(dmaResource.DMA_Data[i]); if length >= p + l then begin Move((buffer + p)^, dmaResource.DMA_Data[i], l); Inc(p, l); end; end; if not(PDevice.dma) then begin PDevice.dma := True; PDevice.dmaChannel := dmaResource.DMA_Header.DD_Alloc_Chan; end; Result := True; end; end; ResType_IRQ: begin p := 0; l := SizeOf(irqResource) - SizeOf(irqResource.IRQ_Data); if length >= p + l then begin Move((buffer + p)^, irqResource, l); Inc(p, l); SetLength(irqResource.IRQ_Data, irqResource.IRQ_Header.IRQD_Count); for i := 0 to irqResource.IRQ_Header.IRQD_Count - 1 do begin l := SizeOf(irqResource.IRQ_Data[i]); if length >= p + l then begin Move((buffer + p)^, irqResource.IRQ_Data[i], l); Inc(p, l); end; end; if not(PDevice.irq) then begin PDevice.irq := True; PDevice.irqLevel := irqResource.IRQ_Header.IRQD_Alloc_Num; end; Result := True; end; end; end; end; procedure getPortResourcesWDMConfigManager(PDevice: PDetectedDevice; devInst1: DEVINST); var logConf: LOG_CONF; resDesc, resDescPrev: RES_DES; resId: RESOURCEID; size, resDescBufferSize: ULONG; resDescBuffer: PChar; begin if (@CM_Get_First_Log_Conf <> nil) and (@CM_Free_Log_Conf_Handle <> nil) and (@CM_Get_Next_Res_Des <> nil) and (@CM_Free_Res_Des_Handle <> nil) and (@CM_Get_Res_Des_Data_Size <> nil) and (@CM_Get_Res_Des_Data <> nil) then begin if CM_Get_First_Log_Conf(@logConf, devInst1, ALLOC_LOG_CONF) = CR_SUCCESS then begin resDescPrev := INVALID_HANDLE_VALUE; if CM_Get_Next_Res_Des(@resDesc, logConf, ResType_All, @resId, 0) = CR_SUCCESS then begin resDescBufferSize := 100; GetMem(resDescBuffer, resDescBufferSize); try repeat if resDescPrev <> INVALID_HANDLE_VALUE then CM_Free_Res_Des_Handle(resDescPrev); if CM_Get_Res_Des_Data_Size(@size, resDesc, 0) = CR_SUCCESS then begin if size > 0 then begin if size > resDescBufferSize then begin ReallocMem(resDescBuffer, size); resDescBufferSize := size; end; if CM_Get_Res_Des_Data(resDesc, resDescBuffer, size, 0) = CR_SUCCESS then extractResourceDesc(PDevice, resId, resDescBuffer, size); end; end; resDescPrev := resDesc; until CM_Get_Next_Res_Des(@resDesc, resDesc, ResType_All, @resId, 0) <> CR_SUCCESS; if resDescPrev <> INVALID_HANDLE_VALUE then CM_Free_Res_Des_Handle(resDescPrev); finally FreeMem(resDescBuffer); end; end; CM_Free_Log_Conf_Handle(logConf); end end; end; function getDevicesWDM(DevList: TDetectedDeviceList; DeviceID: String; const Enumerator: PAnsiChar = nil): Boolean; var i, n: Integer; devInfoList: HDEVINFO; devInfoData: SP_DEVINFO_DATA; buffer: array[0..255] of Char; instanceId, friendlyName, hardwareID, portName: string; // key: HKEY; // type1, size: DWORD; PDevice: PDetectedDevice; begin Result := False; if (DevList <> nil) and (@SetupDiClassGuidsFromNameA <> nil) and (@SetupDiGetClassDevsA <> nil) and (@SetupDiDestroyDeviceInfoList <> nil) and (@SetupDiEnumDeviceInfo <> nil) and (@SetupDiEnumDeviceInterfaces <> nil) and (@SetupDiGetDeviceInterfaceDetailA <> nil) and (@SetupDiGetDeviceInstanceIdA <> nil) and (@SetupDiGetDeviceRegistryPropertyA <> nil) and (@SetupDiOpenClassRegKeyExA <> nil) and (@SetupDiOpenDevRegKey <> nil) then begin DevList.Clear; devInfoList := SetupDiGetClassDevsA( nil,{@guid1,} Enumerator, 0, DIGCF_PRESENT or DIGCF_ALLCLASSES ); if devInfoList <> INVALID_HANDLE_VALUE then begin devInfoData.cbSize := sizeof(SP_DEVINFO_DATA); i := 0; while SetupDiEnumDeviceInfo(devInfoList, i, @devInfoData) do begin if SetupDiGetDeviceInstanceIdA(devInfoList, @devInfoData, @buffer, sizeof(buffer), nil) then begin instanceId := buffer; if SetupDiGetDeviceRegistryPropertyA(devInfoList, @devInfoData, SPDRP_FRIENDLYNAME, nil, @buffer, sizeof(buffer), nil) then friendlyName := buffer else if SetupDiGetDeviceRegistryPropertyA(devInfoList, @devInfoData, SPDRP_DEVICEDESC, nil, @buffer, sizeof(buffer), nil) then friendlyName := buffer else friendlyName := ''; if SetupDiGetDeviceRegistryPropertyA(devInfoList, @devInfoData, SPDRP_HARDWAREID, nil, @buffer, sizeof(buffer), nil) then hardwareID := buffer; if Pos(UpperCase(DeviceID), hardwareID) > 0 then begin Result := True; GetMem(PDevice, SizeOf(TDetectedDevice)); PDevice.friendlyName := friendlyName; PDevice.hardwareID := hardwareID; getPortResourcesWDMConfigManager(PDevice, {ports[n],} devInfoData.DevInst); DevList.Add(PDevice); // write('->'); end; // Writeln(' ',friendlyname, #9, hardwareID); // retrieve port name from registry, for example: LPT1, LPT2, COM1, COM2 // key := // SetupDiOpenDevRegKey( // devInfoList, // @devInfoData, // DICS_FLAG_GLOBAL, // 0, // DIREG_DEV, // KEY_READ // ); // if key <> INVALID_HANDLE_VALUE then // begin // size := 255; // if RegQueryValueEx(key, 'PortName', nil, @type1, @buffer, @size) = ERROR_SUCCESS then // begin // buffer[size] := #0; // portName := buffer; // RegCloseKey(key); // end; // if (Copy(portName, 1, Length(portPrefix)) = portPrefix) then // begin // n := StrToIntDef(Copy(portName, Length(portPrefix) + 1, Length(portName)), 0) - 1; // if (n >= 0) and (n < Length(ports)) then // begin // Result := True; // if ports[n].friendlyName = '' then // if friendlyName <> '' then // ports[n].friendlyName := friendlyName // else // friendlyName := portName; // // retrieve port hardware address // getPortResourcesWDMConfigManager({ports[n],} devInfoData.DevInst); // end; // end; // end; end; Inc(i); end; SetupDiDestroyDeviceInfoList(devInfoList); end; end; end; initialization // dynamically load all optional libraries // @toolhelp32ReadProcessMemory := nil; @SetupDiClassGuidsFromNameA := nil; @SetupDiGetClassDevsA := nil; @SetupDiDestroyDeviceInfoList := nil; @SetupDiEnumDeviceInfo := nil; @SetupDiEnumDeviceInterfaces := nil; @SetupDiGetDeviceInterfaceDetailA := nil; @SetupDiGetDeviceInstanceIdA := nil; @SetupDiGetDeviceRegistryPropertyA := nil; @SetupDiOpenClassRegKeyExA := nil; @SetupDiOpenDevRegKey := nil; @CM_Get_First_Log_Conf := nil; @CM_Free_Log_Conf_Handle := nil; @CM_Get_Next_Res_Des := nil; @CM_Free_Res_Des_Handle := nil; @CM_Get_Res_Des_Data_Size := nil; @CM_Get_Res_Des_Data := nil; // hKernel32 := LoadLibrary('kernel32.dll'); // if hKernel32 <> 0 then // @toolhelp32ReadProcessMemory := GetProcAddress(hKernel32, 'Toolhelp32ReadProcessMemory'); hSetupapi := LoadLibrary('setupapi.dll'); if hSetupapi <> 0 then begin @SetupDiClassGuidsFromNameA := GetProcAddress(hSetupapi, 'SetupDiClassGuidsFromNameA'); @SetupDiGetClassDevsA := GetProcAddress(hSetupapi, 'SetupDiGetClassDevsA'); @SetupDiDestroyDeviceInfoList := GetProcAddress(hSetupapi, 'SetupDiDestroyDeviceInfoList'); @SetupDiEnumDeviceInfo := GetProcAddress(hSetupapi, 'SetupDiEnumDeviceInfo'); @SetupDiEnumDeviceInterfaces := GetProcAddress(hSetupapi, 'SetupDiEnumDeviceInterfaces'); @SetupDiGetDeviceInterfaceDetailA := GetProcAddress(hSetupapi, 'SetupDiGetDeviceInterfaceDetailA'); @SetupDiGetDeviceInstanceIdA := GetProcAddress(hSetupapi, 'SetupDiGetDeviceInstanceIdA'); @SetupDiGetDeviceRegistryPropertyA := GetProcAddress(hSetupapi, 'SetupDiGetDeviceRegistryPropertyA'); @SetupDiOpenClassRegKeyExA := GetProcAddress(hSetupapi, 'SetupDiOpenClassRegKeyExA'); @SetupDiOpenDevRegKey := GetProcAddress(hSetupapi, 'SetupDiOpenDevRegKey'); end; hCfgmgr32 := LoadLibrary('cfgmgr32.dll'); if hCfgmgr32 <> 0 then begin @CM_Get_First_Log_Conf := GetProcAddress(hCfgmgr32, 'CM_Get_First_Log_Conf'); @CM_Free_Log_Conf_Handle := GetProcAddress(hCfgmgr32, 'CM_Free_Log_Conf_Handle'); @CM_Get_Next_Res_Des := GetProcAddress(hCfgmgr32, 'CM_Get_Next_Res_Des'); @CM_Free_Res_Des_Handle := GetProcAddress(hCfgmgr32, 'CM_Free_Res_Des_Handle'); @CM_Get_Res_Des_Data_Size := GetProcAddress(hCfgmgr32, 'CM_Get_Res_Des_Data_Size'); @CM_Get_Res_Des_Data := GetProcAddress(hCfgmgr32, 'CM_Get_Res_Des_Data'); end; finalization FreeLibrary(hCfgmgr32); FreeLibrary(hSetupapi); // FreeLibrary(hKernel32); end.
unit uIDECode; interface uses uPerson, sysutils, rtti_broker_iBroker, rtti_broker_uData, rtti_idebinder_Lib, rtti_serializer_iManager, Forms, Controls, rtti_idebinder_iBindings; type { TIDEPersons } TIDEPersons = class private fStore: ISerialStore; fFactory: ISerialFactory; fActualPerson: TPerson; fForm: TForm; fLister: TWinControl; //fListContext: IIDEContext; fEdit: TWinControl; public class function NewEditPerson(AStore: ISerialStore): TPerson; procedure AttachStore(const AStore: ISerialStore); procedure AttachFactory(const AFactory: ISerialFactory); procedure AttachForm(const AForm: TForm); end; implementation { TIDEPersons } class function TIDEPersons.NewEditPerson(AStore: ISerialStore): TPerson; var mPC: TIDEPersons; mData: IRBData; begin mPC := TIDEPersons.Create; try mPC.fStore := AStore; mPC.fActualPerson := TPerson.Create; mData := TRBData.Create(mPC.fActualPerson); //TLib.ModalEdit(mData, mCommands); Result := mPC.fActualPerson; finally mPC.Free; end; end; procedure TIDEPersons.AttachStore(const AStore: ISerialStore); begin fStore := AStore; end; procedure TIDEPersons.AttachFactory(const AFactory: ISerialFactory); begin fFactory := AFactory; end; procedure TIDEPersons.AttachForm(const AForm: TForm); begin fForm := AForm; //fLister := TIDEFactory.CreateDataListControl(fStore.LoadList('TPerson'), NewListCommands); fLister.Parent := fForm; fLister.Align := alClient; end; end.
unit Chapter02._06_MyVector; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Math; type generic TMyVector<T> = class(TObject) private type TArr_T = array of T; private _data: TArr_T; _size: integer; _capacity: integer; // 复杂度为 O(n) procedure __resize(newCapacity: integer); public constructor Create(n: integer = 100); destructor Destroy; override; // 平均复杂度为 O(1) procedure push_back(e: T); // 平均复杂度为 O(1) function pop_back(): T; end; procedure Main; implementation type TVector = specialize TMyVector<integer>; procedure Main; var n: integer; vec: TVector; i, num: integer; startTime, endTime: cardinal; begin for i := 10 to 26 do begin n := 2 ** i; startTime := TThread.GetTickCount64; vec := TVector.Create; for num := 0 to n - 1 do vec.push_back(num); endTime := TThread.GetTickCount64; Write(n, ' operations: '#9); WriteLn(endTime - startTime, ' ms'); end; end; { TMyVector } constructor TMyVector.Create(n: integer); begin SetLength(_data, n); _size := 0; _capacity := n; end; destructor TMyVector.Destroy; begin inherited Destroy; end; function TMyVector.pop_back(): T; begin if _size <= 0 then raise Exception.Create('can not pop back for empty vector.'); _size -= 1; Result := _data[_size]; end; procedure TMyVector.push_back(e: T); begin if _size = _capacity then __resize(2 * _capacity); _data[_size] := e; _size += 1; end; procedure TMyVector.__resize(newCapacity: integer); var newData: TArr_T; i: integer; begin Assert(newCapacity >= _size); SetLength(newData, newCapacity); for i := 0 to _size - 1 do newData[i] := _data[i]; _data := newData; _capacity := newCapacity; end; end.
unit SmsObj; interface uses Classes,Common; type TSms = class(TObject) public Index : string; Tel : string; Text : string; SmsType: string; end; TSmsList = class(TPersistent) private function GetItems(Key: string): TSms; function GetCount: Integer; public Keys: TStrings; Values: array of TSms; property Items[Key: string]: TSms read GetItems; default; //获取其单一元素 property Count: Integer read GetCount; //获取个数 function Add(Key: string; Value: TSms): Integer; //添加元素 procedure clear; function Remove(Key: string): Integer; //移除 constructor Create; overload; end; procedure getSmsListFromString(source:String;var SmsList :TSmsList); implementation constructor TSmsList.Create; begin Keys := TStringList.Create; SetLength(Values, 0); end; procedure TSmsList.clear; begin SetLength(Values, 0); Keys.Clear; end; function TSmsList.GetItems(Key: string): TSms; var KeyIndex: Integer; begin KeyIndex := Keys.IndexOf(Key); if KeyIndex <> -1 then Result := Values[KeyIndex] else Result := nil; end; function TSmsList.Add(Key: string; Value: TSms): Integer; begin if Keys.IndexOf(Key) = -1 then begin Keys.Add(Key); SetLength(Values, Length(Values) + 1); Values[Length(Values) - 1] := Value; end else Values[Keys.IndexOf(Key)] := Value; Result := Length(Values) - 1; end; function TSmsList.GetCount: Integer; begin Result := Keys.Count; end; function TSmsList.Remove(Key: string): Integer; var Index, Count: Integer; begin Index := Keys.IndexOf(Key); Count := Length(Values); if Index <> -1 then begin Keys.Delete(Index); Move(Values[Index + 1], Values[Index], (Count - Index) * SizeOf(Values[0])); SetLength(Values, Count - 1); end; Result := Count - 1; end; procedure getSmsListFromString(source:String;var SmsList :TSmsList); var SmsStrings :TStrings; SmsPrototypes:TStrings; Sms :TSms; I :Integer; begin SmsStrings := Common.SplitToStrings(source,'|'); if not Assigned(SmsList) then SmsList := TSmsList.Create; for I := 0 to SmsStrings.Count - 1 do begin SmsPrototypes := Common.SplitToStrings(SmsStrings[I],'#'); Sms := TSms.Create; Sms.Index := SmsPrototypes[0]; Sms.SmsType := SmsPrototypes[1]; Sms.Tel := SmsPrototypes[2]; Sms.Text := SmsPrototypes[3]; SmsList.Add(Sms.Index,Sms); end; end; end.
(* Category: SWAG Title: DATE & TIME ROUTINES Original name: 0052.PAS Description: Show Date/Time Author: TANSIN DARCOS Date: 02-28-95 09:58 *) program dt; uses Dos; const id = 'Tansin A Darcos & Company, P O Box 70970, SW DC 20024-0970 ' + '"Ask about our software catalog."'+ '░░▒▒▓▓██ In Stereo Where Available ██▓▓▒▒░░ '+ 'Stolen tagline: "Special favors come in 31 flavors... Pass ' + 'the mints... I''m out of Life Savers." Just don''t sue us ' + 'if you use this. '; var i, y, m, d, h, s, hund, dow : Word; ch : char; cc : string[2]; procedure date; begin GetDate(y,m,d,dow); WriteLn(m:0, '/', d:0, '/', y:0); end; procedure time; begin GetTime(h,m,s,hund); WriteLn(h,':',m,':',s); end; procedure help; begin writeln(' Shows Date and / or time [TDR]'); writeln('DT [ dt | d | t | td | /? ] [>file.txt]'); writeln(' dt - (or no arguments) Shows date, then time'); writeln(' d - show date only'); writeln(' t - show time'); writeln(' td - show time then date'); writeln(' /? - show this message'); writeln(' >file.txt - optionally send output to file.txt'); end; begin cc := 'DT'; if paramcount<>0 then cc := paramstr(1); for i := 1 to Length(cc) do cc[i] := UpCase(cc[i]); ch := cc[1]; if cc = '/?' then help else if length(cc) = 1 then if ch = 'D' then date else time else if (cc = 'TD') then begin time; date end else begin date; time end end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // unit FGUILayoutEditor; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Rtti, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Grid, FMX.Controls.Presentation, FMX.Edit, FMX.EditBox, FMX.SpinBox, FMX.Objects, VXS.Gui, FMX.Grid.Style, FMX.ScrollBox; type TLayouts_Form = class(TForm) Panel1: TPanel; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; Panel2: TPanel; Items_List: TListBox; Open_Image_Button: TButton; Open_Button: TButton; Save_Button: TButton; Done_Button: TButton; ButtonZoomIn: TButton; Add_Button: TButton; Delete_Button: TButton; Name_Edit: TEdit; LabelName: TLabel; Elements_Grid: TStringGrid; LabelX: TLabel; LabelY: TLabel; LabelHeight: TLabel; LabelWidth: TLabel; Left_Edit: TSpinBox; Top_Edit: TSpinBox; Width_Edit: TSpinBox; Height_Edit: TSpinBox; ScrollBox1: TScrollBox; PaintBox1: TPaintBox; Image1: TImage; Image2: TImage; X_Label: TLabel; Y_Label: TLabel; ImageZoomIn: TImage; ButtonZoomOut: TButton; ImageZoomOut: TImage; ButtonShow: TButton; ImageShow: TImage; ImageDone: TImage; ImageOpen: TImage; ImageSave: TImage; ImageLoadSkin: TImage; ImageAdd: TImage; ImageDelete: TImage; procedure Items_ListClick(Sender: TObject); private Rect_point1, Rect_point2: TPoint; Sorted_Elements: array[0..9] of TVXGuiElement; procedure SyncImages; procedure DrawCurrentElement; procedure RefreshComponentBox; function GetEnabledSpins: Boolean; procedure SetEnabledSpins(Value: Boolean); public end; var Layouts_Form: TLayouts_Form; //====================================================================== implementation //====================================================================== {$R *.fmx} var vGUILayoutEditor: Tlayouts_form; Zoom: integer = 1; //--------------------------------------------------------------- { TLayouts_Form } //--------------------------------------------------------------- procedure TLayouts_Form.DrawCurrentElement; begin with Elements_Grid do if (Items_List.ItemIndex > -1) and (Sorted_elements[ColumnIndex + 3 * Selected] <> nil) then with Sorted_Elements[ColumnIndex + 3 * Selected], Image2.Canvas do begin { TODO : E2250 There is no overloaded version of 'FillRect' not enouph arguments } (*FillRect(ClipRect);*) Rect(zoom * Round(TopLeft.X), zoom * Round(TopLeft.Y), zoom * Round(BottomRight.X), zoom * Round(BottomRight.Y)); end; end; function TLayouts_Form.GetEnabledSpins: Boolean; begin Result := Left_Edit.Enabled; end; procedure TLayouts_Form.Items_ListClick(Sender: TObject); var i, p: integer; begin if Items_list.ItemIndex = -1 then Exit; { TODO : E2003 Undeclared identifier: 'VKGuiLayout1' - VXScene not installed} (*Name_edit.Text := VKGuiLayout1.GuiComponents[Items_list.ItemIndex].Name;*) Elements_grid.Selected := 0; //in VCL Row Elements_grid.ColumnIndex := 0; //in VCL Col for i := 0 to Length(Sorted_elements) - 1 do begin sorted_elements[i] := nil; if I < 9 then Elements_grid.Cells[i mod 3, i div 3] := #32; end; { TODO : E2003 Undeclared identifier: 'GLGuiLayout1' - GLScene not installed} (* with GLGuiLayout1.GuiComponents[Items_list.ItemIndex] do for i := 0 to Elements.Count - 1 do begin p := Integer(Elements[i].Align); Sorted_elements[p] := Elements[i]; Elements_grid.Cells[p mod 3, p div 3] := '+'; end; Elements_gridClick(nil); *) end; procedure TLayouts_Form.RefreshComponentBox; var i: integer; begin Items_List.Clear; { TODO : E2003 Undeclared identifier: 'GLGuiLayout1' - GLScene not installed} (* for i := 0 to GLGuiLayout1.GuiComponents.Count - 1 do Items_List.Items.Add(GLGuiLayout1.GuiComponents[i].Name); *) Items_List.ItemIndex := 0; Items_ListClick(nil); end; procedure TLayouts_Form.SetEnabledSpins(Value: Boolean); begin Left_Edit.Enabled := Value; Top_Edit.Enabled := Value; Height_Edit.Enabled := Value; Width_Edit.Enabled := Value; end; procedure TLayouts_Form.SyncImages; begin Image2.Width := Image1.Width; Image2.Height := Image1.Height; Image2.Bitmap.Width := Round(Image1.Width); Image2.Bitmap.Height := Round(Image1.Height); PaintBox1.Width := Image1.Width; PaintBox1.Height := Image1.Height; { TODO : E2003 Undeclared identifier: 'HorzScrollBar' } (* ScrollBox1.HorzScrollBar.Range := Image1.Width; ScrollBox1.VertScrollBar.Range := Image1.Height; PaintBox1.Canvas.CopyRect(PaintBox1.Canvas.ClipRect, Image1.Canvas, Image1.Canvas.ClipRect); *) end; end.
unit CarControl; interface uses Math, TypeControl, CarTypeControl, RectangularUnitControl; type TCar = class(TRectangularUnit) private FPlayerId: Int64; FTeammateIndex: LongInt; FIsTeammate: Boolean; FCarType: TCarType; FProjectileCount: LongInt; FNitroChargeCount: LongInt; FOilCanisterCount: LongInt; FRemainingProjectileCooldownTicks: LongInt; FRemainingNitroCooldownTicks: LongInt; FRemainingOilCooldownTicks: LongInt; FRemainingNitroTicks: LongInt; FRemainingOiledTicks: LongInt; FDurability: Double; FEnginePower: Double; FWheelTurn: Double; FNextWaypointX: LongInt; FNextWaypointY: LongInt; FIsFinishedTrack: Boolean; function GetPlayerId: Int64; function GetTeammateIndex: LongInt; function GetIsTeammate: Boolean; function GetCarType: TCarType; function GetProjectileCount: LongInt; function GetNitroChargeCount: LongInt; function GetOilCanisterCount: LongInt; function GetRemainingProjectileCooldownTicks: LongInt; function GetRemainingNitroCooldownTicks: LongInt; function GetRemainingOilCooldownTicks: LongInt; function GetRemainingNitroTicks: LongInt; function GetRemainingOiledTicks: LongInt; function GetDurability: Double; function GetEnginePower: Double; function GetWheelTurn: Double; function GetNextWaypointX: LongInt; function GetNextWaypointY: LongInt; function GetIsFinishedTrack: Boolean; public property PlayerId: Int64 read GetPlayerId; property TeammateIndex: LongInt read GetTeammateIndex; property IsTeammate: Boolean read GetIsTeammate; property CarType: TCarType read GetCarType; property ProjectileCount: LongInt read GetProjectileCount; property NitroChargeCount: LongInt read GetNitroChargeCount; property OilCanisterCount: LongInt read GetOilCanisterCount; property RemainingProjectileCooldownTicks: LongInt read GetRemainingProjectileCooldownTicks; property RemainingNitroCooldownTicks: LongInt read GetRemainingNitroCooldownTicks; property RemainingOilCooldownTicks: LongInt read GetRemainingOilCooldownTicks; property RemainingNitroTicks: LongInt read GetRemainingNitroTicks; property RemainingOiledTicks: LongInt read GetRemainingOiledTicks; property Durability: Double read GetDurability; property EnginePower: Double read GetEnginePower; property WheelTurn: Double read GetWheelTurn; property NextWaypointX: LongInt read GetNextWaypointX; property NextWaypointY: LongInt read GetNextWaypointY; property IsFinishedTrack: Boolean read GetIsFinishedTrack; constructor Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double; const APlayerId: Int64; const ATeammateIndex: LongInt; const AIsTeammate: Boolean; const ACarType: TCarType; const AProjectileCount: LongInt; const ANitroChargeCount: LongInt; const AOilCanisterCount: LongInt; const ARemainingProjectileCooldownTicks: LongInt; const ARemainingNitroCooldownTicks: LongInt; const ARemainingOilCooldownTicks: LongInt; const ARemainingNitroTicks: LongInt; const ARemainingOiledTicks: LongInt; const ADurability: Double; const AEnginePower: Double; const AWheelTurn: Double; const ANextWaypointX: LongInt; const ANextWaypointY: LongInt; const AIsFinishedTrack: Boolean); destructor Destroy; override; end; TCarArray = array of TCar; implementation function TCar.GetPlayerId: Int64; begin Result := FPlayerId; end; function TCar.GetTeammateIndex: LongInt; begin Result := FTeammateIndex; end; function TCar.GetIsTeammate: Boolean; begin Result := FIsTeammate; end; function TCar.GetCarType: TCarType; begin Result := FCarType; end; function TCar.GetProjectileCount: LongInt; begin Result := FProjectileCount; end; function TCar.GetNitroChargeCount: LongInt; begin Result := FNitroChargeCount; end; function TCar.GetOilCanisterCount: LongInt; begin Result := FOilCanisterCount; end; function TCar.GetRemainingProjectileCooldownTicks: LongInt; begin Result := FRemainingProjectileCooldownTicks; end; function TCar.GetRemainingNitroCooldownTicks: LongInt; begin Result := FRemainingNitroCooldownTicks; end; function TCar.GetRemainingOilCooldownTicks: LongInt; begin Result := FRemainingOilCooldownTicks; end; function TCar.GetRemainingNitroTicks: LongInt; begin Result := FRemainingNitroTicks; end; function TCar.GetRemainingOiledTicks: LongInt; begin Result := FRemainingOiledTicks; end; function TCar.GetDurability: Double; begin Result := FDurability; end; function TCar.GetEnginePower: Double; begin Result := FEnginePower; end; function TCar.GetWheelTurn: Double; begin Result := FWheelTurn; end; function TCar.GetNextWaypointX: LongInt; begin Result := FNextWaypointX; end; function TCar.GetNextWaypointY: LongInt; begin Result := FNextWaypointY; end; function TCar.GetIsFinishedTrack: Boolean; begin Result := FIsFinishedTrack; end; constructor TCar.Create(const AId: Int64; const AMass: Double; const AX: Double; const AY: Double; const ASpeedX: Double; const ASpeedY: Double; const AAngle: Double; const AAngularSpeed: Double; const AWidth: Double; const AHeight: Double; const APlayerId: Int64; const ATeammateIndex: LongInt; const AIsTeammate: Boolean; const ACarType: TCarType; const AProjectileCount: LongInt; const ANitroChargeCount: LongInt; const AOilCanisterCount: LongInt; const ARemainingProjectileCooldownTicks: LongInt; const ARemainingNitroCooldownTicks: LongInt; const ARemainingOilCooldownTicks: LongInt; const ARemainingNitroTicks: LongInt; const ARemainingOiledTicks: LongInt; const ADurability: Double; const AEnginePower: Double; const AWheelTurn: Double; const ANextWaypointX: LongInt; const ANextWaypointY: LongInt; const AIsFinishedTrack: Boolean); begin inherited Create(AId, AMass, AX, AY, ASpeedX, ASpeedY, AAngle, AAngularSpeed, AWidth, AHeight); FPlayerId := APlayerId; FTeammateIndex := ATeammateIndex; FIsTeammate := AIsTeammate; FCarType := ACarType; FProjectileCount := AprojectileCount; FNitroChargeCount := ANitroChargeCount; FOilCanisterCount := AOilCanisterCount; FRemainingProjectileCooldownTicks := ARemainingProjectileCooldownTicks; FRemainingNitroCooldownTicks := ARemainingNitroCooldownTicks; FRemainingOilCooldownTicks := ARemainingOilCooldownTicks; FRemainingNitroTicks := ARemainingNitroTicks; FRemainingOiledTicks := ARemainingOiledTicks; FDurability := ADurability; FEnginePower := AEnginePower; FWheelTurn := AWheelTurn; FNextWaypointX := ANextWaypointX; FNextWaypointY := ANextWaypointY; FIsFinishedTrack := AIsFinishedTrack; end; destructor TCar.Destroy; begin inherited; end; end.
// // Generated by JavaToPas v1.5 20150830 - 103139 //////////////////////////////////////////////////////////////////////////////// unit android.graphics.Paint_Style; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes; type JPaint_Style = interface; JPaint_StyleClass = interface(JObjectClass) ['{F7000BF9-9E76-4C7C-827A-1803A30F840B}'] function _GetFILL : JPaint_Style; cdecl; // A: $4019 function _GetFILL_AND_STROKE : JPaint_Style; cdecl; // A: $4019 function _GetSTROKE : JPaint_Style; cdecl; // A: $4019 function valueOf(&name : JString) : JPaint_Style; cdecl; // (Ljava/lang/String;)Landroid/graphics/Paint$Style; A: $9 function values : TJavaArray<JPaint_Style>; cdecl; // ()[Landroid/graphics/Paint$Style; A: $9 property FILL : JPaint_Style read _GetFILL; // Landroid/graphics/Paint$Style; A: $4019 property FILL_AND_STROKE : JPaint_Style read _GetFILL_AND_STROKE; // Landroid/graphics/Paint$Style; A: $4019 property STROKE : JPaint_Style read _GetSTROKE; // Landroid/graphics/Paint$Style; A: $4019 end; [JavaSignature('android/graphics/Paint_Style')] JPaint_Style = interface(JObject) ['{A4781423-B139-4E6C-BD38-3CB997F19086}'] end; TJPaint_Style = class(TJavaGenericImport<JPaint_StyleClass, JPaint_Style>) end; implementation end.
unit gcobj; {$ifdef FPC} {$mode delphi}{$H+} {$warn 5024 off param not used} {$endif} interface uses Classes; type PGCData = ^TGCData; TGCData = record Prev, Next: PGCData; RefCnt, GCRefs: Integer; This: TInterfacedObject; end; IGCSupport = interface ['{26ABD806-7C56-4B6E-9696-B2E7E674330F}'] function GetGCData: PGCData; end; TGCObject = class(TInterfacedObject, IGCSupport) private FGCData: TGCData; function GetGCData: PGCData; public procedure AfterConstruction; override; procedure BeforeDestruction; override; end; procedure Collect; procedure GetTotals(out objCnt, objSizes: Integer); implementation uses TypInfo; threadvar Root: TGCData; type TVisitProc = procedure (FieldPtr: Pointer; const Intf: IGCSupport; Data: Pointer); {$ifdef FPC} {$I gcrtti.inc} procedure TraverseObj(obj: TObject; cb: TVisitProc; data: Pointer); var vmt: PVmt; temp: pointer; begin vmt := PVmt(obj.ClassType); while vmt <> nil do begin Temp := vmt^.vInitTable; { The RTTI format matches one for records, except the type is tkClass. Since RecordRTTI does not check the type, calling it yields the desired result. } if Assigned(Temp) then VisitRecord(obj, temp, cb); vmt:= vmt^.vParent; end; end; {$ELSE} procedure TraverseObj(obj: TObject; cb: TVisitProc; data: Pointer); type TFieldInfo = packed record TypeInfo: PPTypeInfo; Offset: Cardinal; end; PFieldTable = ^TFieldTable; TFieldTable = packed record X: Word; Size: Cardinal; Count: Cardinal; Fields: array [0..0] of TFieldInfo; end; PDynArrayTypeInfo = ^TDynArrayTypeInfo; TDynArrayTypeInfo = packed record X: Word; elSize: Longint; elType: ^PDynArrayTypeInfo; varType: Integer; end; TDummyDynArray = array of Pointer; procedure VisitArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal); forward; procedure VisitRecord(p: Pointer; typeInfo: Pointer); forward; procedure VisitDynArray(P: PPointer; typeInfo: Pointer); var TD: PDynArrayTypeInfo; begin if P^ = nil then Exit; TD := PDynArrayTypeInfo(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0])); if TD^.elType = nil then Exit; // elType = nil if no require cleanup VisitArray(P^, TD^.elType^, Length(TDummyDynArray(P^))); end; procedure VisitArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal); var gcIntf: IGCSupport; FT: PFieldTable; begin case PTypeInfo(typeInfo).Kind of tkVariant: while elemCount > 0 do begin if TVarData(P^).VType in [varUnknown, varDispatch] then begin if Assigned(TVarData(P^).VUnknown) and (IUnknown(TVarData(P^).VUnknown) .QueryInterface(IGCSupport, gcIntf) = S_OK) then begin cb(@TVarData(P^).VUnknown, gcIntf, data); gcIntf := nil; end; end; Inc(PByte(P), sizeof(Variant)); Dec(elemCount); end; tkArray: begin FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0])); while elemCount > 0 do begin VisitArray(P, FT.Fields[0].TypeInfo^, FT.Count); Inc(PByte(P), FT.Size); Dec(elemCount); end; end; tkInterface: while elemCount > 0 do begin if Assigned(Pointer(P^)) and (IInterface(P^).QueryInterface(IGCSupport, gcIntf) = S_OK) then begin cb(P, gcIntf, data); gcIntf := nil; end; Inc(PPointer(P), 1); Dec(elemCount); end; tkDynArray: while elemCount > 0 do begin VisitDynArray(P, typeInfo); Inc(PPointer(P), 1); Dec(elemCount); end; tkRecord: begin FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0])); while elemCount > 0 do begin VisitRecord(P, typeInfo); Inc(PByte(P), FT^.Size); Dec(elemCount); end; end; end; end; procedure VisitRecord(p: Pointer; typeInfo: Pointer); var FT: PFieldTable; I: Cardinal; begin FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0])); for I := 0 to FT.Count-1 do VisitArray(PPointer(Cardinal(P) + FT.Fields[I].Offset), FT.Fields[I].TypeInfo^, 1); end; var ClassPtr: TClass; InitTable: Pointer; begin ClassPtr := Obj.ClassType; InitTable := PPointer(Integer(ClassPtr) + vmtInitTable)^; while (ClassPtr <> nil) and (InitTable <> nil) do begin VisitRecord(Obj, InitTable); ClassPtr := ClassPtr.ClassParent; if ClassPtr <> nil then InitTable := PPointer(Integer(ClassPtr) + vmtInitTable)^; end; end; {$ENDIF} procedure VisitDecRefs(P: Pointer; const Intf: IGCSupport; data: Pointer); var gc: PGCData; begin gc := intf.GetGCData; Assert(gc^.GCRefs > 0, 'Has some errors if gc^.GCRefs < 1'); if gc^.GCRefs > 0 then Dec(gc^.GCRefs); end; procedure VisitCleanup(P: Pointer; const Intf: IGCSupport; data: Pointer); var gc: PGCData; begin gc := intf.GetGCData; if gc^.GCRefs = 0 then IInterface(P^) := nil; end; procedure RemoveFromLink(var gc: TGCData); begin if gc.Next <> nil then gc.Next.Prev := gc.Prev; gc.Prev.Next := gc.Next; gc.Next := nil; gc.Prev := nil; end; procedure GetCleanupList(list: TList); var gc: PGCData; begin gc := Root.Next; while gc <> nil do begin if gc^.GCRefs = 0 then list.Add(gc); gc := gc.Next; end; end; procedure Collect; var gc: PGCData; list: TList; i: Integer; begin gc := Root.Next; while gc <> nil do begin gc.RefCnt := gc.This.RefCount; gc.GCRefs := gc.RefCnt; gc := gc.Next; end; // 减去循环引用,得到真实被引用的计数 gc := Root.Next; while gc <> nil do begin TraverseObj(gc^.This, @VisitDecRefs, nil); gc := gc.Next; end; // 遍历所有的对象,将真实引用计数为0的接口释放 list := TList.Create; try GetCleanupList(list); for i := 0 to list.Count - 1 do TraverseObj(PGCData(list[i])^.This, @VisitCleanup, nil); finally list.Free; end; end; procedure GetTotals(out objCnt, objSizes: Integer); var gc: PGCData; begin objCnt := 0; objSizes := 0; gc := Root.Next; while gc <> nil do begin Inc(objCnt); Inc(objSizes, gc.This.InstanceSize); gc := gc.Next; end; end; { TGCObject } procedure TGCObject.AfterConstruction; begin inherited; FGCData.This := Self; FGCData.Next := Root.Next; FGCData.Prev := @Root; if Root.Next <> nil then Root.Next.Prev := @FGCData; Root.Next := @FGCData; end; procedure TGCObject.BeforeDestruction; begin inherited; RemoveFromLink(FGCData); end; function TGCObject.GetGCData: PGCData; begin Result := @FGCData; end; end.
unit uPrintReceipt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Db, DBTables, ComCtrls, ADODB, PaidePrinter, siComp, siLangRT, uPreSale, uPayments; const RECEIPT_TYPE_HOLD = 1; RECEIPT_TYPE_INVOICE = 2; RECEIPT_TYPE_TICKET = 3; RECEIPT_TYPE_TAXISEMPTION = 4; RECEIPT_TYPE_LAYAWAY_RECEIVE = 5; type TPrintReceipt = class(TFrmParentPrint) lblPrint: TLabel; pnlPrinter: TPanel; quBarCode: TADOQuery; quBarCodeBarCode: TStringField; quPreSaleValue: TADOStoredProc; quPreSaleValueTaxIsent: TBooleanField; quPreSaleValueSubTotal: TFloatField; quPreSaleValueItemDiscount: TFloatField; quPreSaleValueTax: TFloatField; quPreSaleValueTaxPrc: TFloatField; quPreSaleValueDiscountPrc: TFloatField; quPreSaleValueTotalInvoice: TFloatField; quPreSaleValueSpecialPriceID: TIntegerField; quPreSaleValueSpecialPrice: TStringField; quPreSaleValuenOpenUser: TIntegerField; quPreSaleValueShowOpenUser: TIntegerField; quPreSaleInfo: TADOQuery; quPreSaleInfoIDPreSale: TIntegerField; quPreSaleInfoIDMeioPag: TIntegerField; quPreSaleInfoIDTouristGroup: TIntegerField; quPreSaleInfoPreSaleDate: TDateTimeField; quPreSaleInfoOtherComissionID: TIntegerField; quPreSaleInfoIDCustomer: TIntegerField; quPreSaleInfoDeliverTypeID: TIntegerField; quPreSaleInfoDeliverDate: TDateTimeField; quPreSaleInfoDeliverAddress: TStringField; quPreSaleInfoPassportDate: TDateTimeField; quPreSaleInfoAirLine: TStringField; quPreSaleInfoCompanyName: TStringField; quPreSaleInfoCompanyCGC: TStringField; quPreSaleInfoDepositDate: TDateTimeField; quPreSaleInfoNote: TStringField; quPreSaleInfoInvoiceDate: TDateTimeField; quPreSaleInfoIDInvoice: TIntegerField; quPreSaleInfoPassport: TStringField; quPreSaleInfoTicket: TStringField; quPreSaleInfoMediaID: TIntegerField; quPreSaleItem: TADOStoredProc; quPreSaleItemModelID: TIntegerField; quPreSaleItemModel: TStringField; quPreSaleItemDescription: TStringField; quPreSaleItemSalePrice: TFloatField; quPreSaleItemDiscount: TFloatField; quPreSaleItemIDInventoryMov: TIntegerField; quPreSaleItemTotalItem: TFloatField; quPreSaleItemSalesPerson: TStringField; quPreSaleItemIDComission: TIntegerField; quPreSaleItemCostPrice: TFloatField; quPreSaleInfoCashReceived: TFloatField; AniPrint: TAnimate; btOk: TButton; quPreSaleInfoCashRegMovID: TIntegerField; quDescCashier: TADOQuery; quDescCashierSystemUser: TStringField; quPreSaleInfoPrinted: TBooleanField; quPreSaleItemIDUser: TIntegerField; quPreSaleItemExchangeInvoice: TIntegerField; quPreSaleInfoTaxIsent: TBooleanField; quPreSaleInfoCardNumber: TStringField; quPreSaleInfoAddress: TStringField; quSerial: TADOQuery; quSerialDocumentID: TIntegerField; quSerialSerialNumber: TStringField; quSerialInventoryMovID: TIntegerField; quPreSaleValueTaxIsemptValue: TFloatField; quPreSaleValueSubTotalTaxable: TFloatField; quPreSaleValueTaxIsemptItemDiscount: TFloatField; quPreSaleValueTotalDiscount: TCurrencyField; quPreSaleParc: TADOQuery; quPreSaleParcIDDocumentoTipo: TIntegerField; quPreSaleParcNumDocumento: TStringField; quPreSaleParcDataVencimento: TDateTimeField; quPreSaleParcValorNominal: TFloatField; quPreSaleParcMeioPag: TStringField; quPreSaleParcIDMeioPag: TIntegerField; quStore: TADOQuery; quStoreTicketHeader: TMemoField; quPreSaleInfoFirstName: TStringField; quPreSaleInfoLastName: TStringField; quStoreTicketLayawayFooter: TMemoField; quStoreTicketTaxIsemptFooter: TMemoField; quStoreTicketFooter: TMemoField; quStorePrintTicketHeader: TBooleanField; quStorePrintLayawayFooter: TBooleanField; quStorePrintTaxInsemptFooter: TBooleanField; quStorePrintTicketFooter: TBooleanField; quPreSaleInfoPrintNotes: TBooleanField; quStoreTicketDetail: TMemoField; quStoreTicketTotals: TMemoField; quPreSaleInfoMedia: TStringField; quPreSaleItemQty: TFloatField; tmrTimer: TTimer; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure tmrTimerTimer(Sender: TObject); private { Private declarations } //Translation sEndereco, sNoTaxAble, sTaxAble, sTax, sSubTotal, sTotal, sDiscount, sHold, sTaxExpHeadr, sIInvNum, sIInvDate, sICustomer, sIPassPort, sIPassPrtNum, sITicketNum, sIAirLine, sIArrivalNum, sIBusName, sILicencNum, sIAddress, sRecImpresso, sClickOK : String; MyIDPreSale, MyIDInvoice : Integer; MyTotCash : Currency; MyCashReceived : Currency; ActualTime : TDateTime; Quit : Boolean; FReceiptType: Integer; FOpenCashier: String; FTaxable, FExempt: Currency; FPaymentTotal: Currency; FPreSale: TPreSale; FPayments: TPayments; procedure ImpTicketHeader(PrintDate: TDateTime; InvoiceCode, SaleCode: String ; Customer: String ; Cashier: String; IDTouristGroup : Integer; Printed : Boolean; Media : String); procedure ImpTicketDeliverHeader(PrintDate: TDateTime ; SaleCode, InvoiceCode: String ; Customer: String ; Hotel: String; IDTouristGroup : Integer; Media:String); procedure ImpTicketLine(Qty: Double ; Desc: String ; Model: String ; Val: Double ; BarCode: String; IDUser : integer; SalesPerson:String); procedure ImpTicketTotals(SubTotalTaxable, TaxIsemptValue, SubTotal: Double ; Tax: Double ; Total: Double ; Received: Double ; Change, ItemDiscount, InvoiceDiscount, Refund: Double; IsRefund: Boolean); procedure ImpTicketPaymentLine(Date: TDateTime ; PType: String ; Val: Double); procedure ImpTicketNotes; procedure ImpTicketTaxExemption; procedure ImpFooterLayaway(AInvoiceTotal, APaymentTotal: Currency ); procedure ImpTicketFooter; //Falta fazer procedure ImpTicketHoldTotals(SubTotalTaxable, TaxIsemptValue, SubTotal: Double ; Tax: Double ; Total: Double ; Received: Double ; Change: Double; ReceiptType : integer; Discount: Double; IsRefund: Boolean); public { Public declarations } procedure Start(APreSale: TPreSale; APayments: TPayments; IDPreSale : Integer; ReceiptType: Integer; CashRegMov: Integer); end; implementation uses uDM, XBase, uMsgBox, uMsgConstant, uDMGlobal, uSystemConst, uStringFunctions, uTXTCashInfo, uDMPDV; {$R *.DFM} procedure TPrintReceipt.Start(APreSale: TPreSale; APayments: TPayments; IDPreSale : Integer; ReceiptType: Integer; CashRegMov: Integer); var NotOk: Boolean; FExempt: Currency; iDummy: Integer; sDummy: String; dtDummy: TDateTime; begin Exit; DM.fPOS.GetCashRegisterInfo(CashRegMov, sDummy, FOpenCashier, iDummy, dtDummy); FPreSale := APreSale; FPayments := APayments; MyCashReceived := FPayments.CashReceivedTotal + FPayments.ChangeTotal; MyTotCash := FPayments.GetPaymentsAmount(PAYMENT_TYPE_CASH); fPaymentTotal := FPayments.GetPaymentsAmount(); if FPreSale.TaxExempt then begin FTaxable := 0; FExempt := FPreSale.TaxTotal; end else begin FTaxable := FPreSale.TaxTotal; FExempt := 0; end; FReceiptType := ReceiptType; tmrTimer.Enabled := True; ShowModal; end; procedure TPrintReceipt.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TPrintReceipt.ImpTicketPaymentLine(Date: TDateTime ; PType: String ; Val: Double); var fText : string; fPayment : string; begin if Length(PType) > 14 then PType := Copy(PType,1,14); fText := DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketTotals'); fPayment := (Pad(FormatDateTime('ddddd', Date), 11) + Pad(PType, 14) + LPad(FormatFloat('###,###,##0.00', Val), 14)); if Pos(TICKET_PAYDATE_TYPE, fText) > 0 then DM.PrintLine(fPayment); end; procedure TPrintReceipt.ImpTicketHeader(PrintDate: TDateTime ; InvoiceCode, SaleCode: String; Customer: String ; Cashier: String; IDTouristGroup : Integer; Printed : Boolean; Media : String); var fText : string; begin //Print Header if it is checkedto Print if not StrToBoolDef(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'PrintTicketHeader'), False) then Exit; fText := DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketHeader'); fText := StringReplace(fText, TICKET_DATE, DateToStr(PrintDate), [rfReplaceAll]); fText := StringReplace(fText, TICKET_TIME, TimeToStr(PrintDate), [rfReplaceAll]); fText := StringReplace(fText, TICKET_CUSTOMER, Customer, [rfReplaceAll]); fText := StringReplace(fText, TICKET_MEDIA, Media, [rfReplaceAll]); fText := StringReplace(fText, TICKET_CASHIER, Cashier, [rfReplaceAll]); fText := StringReplace(fText, TICKET_HOLD, SaleCode, [rfReplaceAll]); fText := StringReplace(fText, TICKET_INVOICE, InvoiceCode, [rfReplaceAll]); ImpMemoDBInfo(fText); end; procedure TPrintReceipt.ImpTicketNotes; begin DM.PrintLine('----------------------------------------'); ImpMemoDBInfo(FPreSale.InvObs); DM.PrintLine('----------------------------------------'); DM.PrintLine(''); end; procedure TPrintReceipt.ImpTicketDeliverHeader(PrintDate: TDateTime ; SaleCode, InvoiceCode: String; Customer: String ; Hotel: String; IDTouristGroup : Integer; Media:String); begin //Print Header if it is checked ImpTicketHeader(PrintDate, InvoiceCode, SaleCode, Customer, '', IDTouristGroup, False, Media); DM.PrintLine('--------------------------------'); DM.PrintLine(sEndereco + Hotel); DM.PrintLine('--------------------------------'); end; procedure TPrintReceipt.ImpTicketLine(Qty: Double ; Desc: String ; Model: String ; Val: Double ; BarCode: String; IDUser : Integer; SalesPerson:String); var fText, fSerial, fTemp : string; iRgh, i : Integer; begin fSerial := ''; (* // Imprime os seriais do item with quSerial do begin if Active AND Locate('InventoryMovID', quPreSaleItemIDInventoryMov.AsString, []) then begin // vou percorrendo até o IDInventoryMov mudar while (not EOF) AND (quSerialInventoryMovID.AsInteger = quPreSaleItemIDInventoryMov.AsInteger) do begin //colocar o serial na outra linha se nao der no ticket fTemp := fSerial + Trim(quSerialSerialNumber.AsString); If Length(fTemp) > DM.fPrintReceipt.PrinterLineWidth then fSerial := fSerial + #13#10 + Trim(quSerialSerialNumber.AsString) else fSerial := fTemp; Next; if not EOF then fSerial := fSerial + ' ,'; end; fSerial := '('+fSerial+')'; end; end; *) fText := DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketDetail'); fText := StringReplace(fText, TICKET_MODEL, Model, [rfReplaceAll]); fText := StringReplace(fText, TICKET_DESCRIPTION, Desc, [rfReplaceAll]); fText := StringReplace(fText, TICKET_SP, SalesPerson, [rfReplaceAll]); fText := StringReplace(fText, TICKET_SPN, IntToStr(IDUser), [rfReplaceAll]); fText := StringReplace(fText, TICKET_BARCODE, BarCode, [rfReplaceAll]); fText := StringReplace(fText, TICKET_SERIALNUMBER, fSerial, [rfReplaceAll]); fText := StringReplace(fText, TICKET_QTY, FormatFloat('0.#####', Qty), [rfReplaceAll]); fText := StringReplace(fText, TICKET_UNIT_PRICE, FormatCurr('###,###,##0.00',Val), [rfReplaceAll]); fText := StringReplace(fText, TICKET_UNIT_TOTAL, IncLeftSpaces(FormatCurr('###,###,##0.00',Qty * Val),14), [rfReplaceAll]); iRgh := CountStr(fText, '{>'); for i:=1 to iRgh do fText := IncLeftStringFlage('{>','<}', fText,DM.fPrintReceipt.PrinterLineWidth); ImpMemoNoEmptyLine(fText); end; procedure TPrintReceipt.ImpTicketTotals(SubTotalTaxable, TaxISemptValue, SubTotal: Double ; Tax: Double ; Total: Double ; Received: Double ; Change, ItemDiscount, InvoiceDiscount, Refund: Double; IsRefund: Boolean); var fText : string; iRgh, i : Integer; begin fText := DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketTotals'); //Error quando e Layaway if (Received = 0) or (Change<0) then Change := 0; fText := StringReplace(fText, TICKET_NO_TAXABLE, IncLeftSpaces(FormatCurr('###,###,##0.00',TaxIsemptValue), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_SUBTOTAL, IncLeftSpaces(FormatCurr('###,###,##0.00',SubTotal), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_TAXABLE, IncLeftSpaces(FormatCurr('###,###,##0.00',SubTotalTaxable), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_TAX, IncLeftSpaces(FormatCurr('###,###,##0.00',Tax), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_TOTAL, IncLeftSpaces(FormatCurr('###,###,##0.00',Total), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_CASH_RECEIVED, IncLeftSpaces(FormatCurr('###,###,##0.00',Received), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_CHANGE, IncLeftSpaces(FormatCurr('###,###,##0.00',Change), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_ITEM_DISCOUNT, IncLeftSpaces(FormatCurr('###,###,##0.00',ItemDiscount), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_DISCOUNT, IncLeftSpaces(FormatCurr('###,###,##0.00',InvoiceDiscount), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_REFUND, IncLeftSpaces(FormatCurr('###,###,##0.00',Refund), 14), [rfReplaceAll]); fText := StringReplace(fText, TICKET_PAYDATE_TYPE, '', [rfReplaceAll]); if TaxIsemptValue <> 0 then fText := CopyStringFlage('{TA','TA}', fText, False) else fText := CopyStringFlage('{TA','TA}', fText, True); if ((ItemDiscount > 0) and not IsRefund) or ((ItemDiscount < 0) and IsRefund) then fText := CopyStringFlage('{ID','ID}', fText, False) else fText := CopyStringFlage('{ID','ID}', fText, True); if ((InvoiceDiscount > 0) and not IsRefund) or ((InvoiceDiscount < 0) and IsRefund) then fText := CopyStringFlage('{D','D}', fText, False) else fText := CopyStringFlage('{D','D}', fText, True); if Refund > 0 then fText := CopyStringFlage('{R','R}', fText, False) else fText := CopyStringFlage('{R','R}', fText, True); iRgh := CountStr(fText, '{>'); for i:=1 to iRgh do fText := IncLeftStringFlage('{>','<}', fText,DM.fPrintReceipt.PrinterLineWidth); ImpMemoDBInfo(fText); end; procedure TPrintReceipt.ImpTicketHoldTotals(SubTotalTaxable, TaxIsemptValue, SubTotal: Double ; Tax: Double ; Total: Double ; Received: Double ; Change: Double; ReceiptType : integer; Discount: Double; IsRefund: Boolean); begin case ReceiptType of RECEIPT_TYPE_HOLD: begin DM.PrintLine(' '); DM.PrintLine(Space(14) + sSubTotal + RightStr(Space(12) + sHold,12)); DM.PrintLine(Space(14) + sTax + RightStr(Space(12) + sHold,12)); DM.PrintLine(Space(14) + sTotal + RightStr(Space(12) + sHold,12)); DM.PrintLine(' '); DM.PrintLine(Space(14) + sDiscount + RightStr(Space(12) + sHold,12)); end; ELSE begin DM.PrintLine(' '); if TaxIsemptValue <> 0 then begin DM.PrintLine(Space(14) + sNoTaxAble + RightStr(Space(12) + FormatFloat('#,###,##0.00',TaxIsemptValue),12)); DM.PrintLine(Space(14) + sTaxAble + RightStr(Space(12) + FormatFloat('#,###,##0.00',SubTotalTaxable),12)); DM.PrintLine(Space(14) + sTax + RightStr(Space(12) + FormatFloat('#,###,##0.00',Tax),12)); end else begin DM.PrintLine(Space(14) + sSubTotal + RightStr(Space(12) + FormatFloat('#,###,##0.00',SubTotal),12)); DM.PrintLine(Space(14) + sTax + RightStr(Space(12) + FormatFloat('#,###,##0.00',Tax),12)); end; DM.PrintLine(Space(14) + sTotal + RightStr(Space(12) + FormatFloat('#,###,##0.00',Total),12)); if ((Discount > 0) and not IsRefund) or ((Discount < 0) and IsRefund) then begin DM.PrintLine(' '); DM.PrintLine(Space(14) + sDiscount + RightStr(Space(12) + FormatFloat('#,###,##0.00',Discount),12)); end; end; end; end; procedure TPrintReceipt.ImpTicketFooter(); begin //Print the ticket footer if it is checked if StrToBoolDef(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'PrintTicketFooter'), False) then ImpMemoDBInfo(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketFooter')); end; procedure TPrintReceipt.ImpFooterLayaway(AInvoiceTotal, APaymentTotal: Currency); var sText: String; begin if not StrToBoolDef(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'LayawayFooter'), False) then Exit; sText := DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketLayawayFooter'); sText := StringReplace(sText, TICKET_PAYMENT_TOTAL, IncLeftSpaces(FormatCurr('###,###,##0.00', APaymentTotal), 14), [rfReplaceAll]); sText := StringReplace(sText, TICKET_PAYMENT_BALANCE, IncLeftSpaces(FormatCurr('###,###,##0.00', APaymentTotal - AInvoiceTotal), 14), [rfReplaceAll]); ImpMemoDBInfo(sText); end; procedure TPrintReceipt.FormShow(Sender: TObject); begin AniPrint.Active := True; btOk.Visible := False; end; procedure TPrintReceipt.btOkClick(Sender: TObject); begin Quit := True; Close; end; procedure TPrintReceipt.ImpTicketTaxExemption; begin // Imprime o documento de isenção de taxa //Print Tax Isemption if it is checked if StrToBoolDef(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'PrintTaxInsemptFooter'), False) then begin DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(sTaxExpHeadr); DM.PrintLine(''); DM.PrintLine(sIInvNum + FPreSale.SaleCode); DM.PrintLine(sIInvDate + DateToStr(FPreSale.PreSaleDate)); DM.PrintLine(sICustomer + FPreSale.PreSaleInfo.CustomerInfo.FirstName +' '+ FPreSale.PreSaleInfo.CustomerInfo.LastName); DM.PrintLine(sIPassPort {+ quPreSaleInfoPassport.AsString}); DM.PrintLine(sIPassPrtNum {+ DateToStr(quPreSaleInfoPassportDate.AsDateTime)}); DM.PrintLine(sITicketNum {+ quPreSaleInfoTicket.AsString}); DM.PrintLine(sIAirLine {+ quPreSaleInfoAirLine.AsString}); DM.PrintLine(sIArrivalNum {+ quPreSaleInfoCardNumber.AsString}); DM.PrintLine(sIBusName {+ quPreSaleInfoCompanyName.AsString}); DM.PrintLine(sILicencNum {+ quPreSaleInfoCompanyCGC.AsString}); DM.PrintLine(sIAddress {+ quPreSaleInfoAddress.AsString}); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); ImpMemoDBInfo(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'TicketTaxIsemptFooter')); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); end; end; procedure TPrintReceipt.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sEndereco := ' Address:'; sNoTaxAble := ' Non taxable:'; sTaxAble := ' Taxable:'; sTax := ' Tax:'; sSubTotal := ' SubTotal:'; sTotal := ' Total:'; sDiscount := ' Discount:'; sHold := 'HOLD'; sTaxExpHeadr := '======= T A X E X E M P T I O N ======'; sIInvNum := 'Invoice # : '; sIInvDate := 'Invoice Date : '; sICustomer := 'Customer : '; sIPassPort := 'Passport # : '; sIPassPrtNum := 'Passport Date : '; sITicketNum := 'Ticket # : '; sIAirLine := 'AirLine : '; sIArrivalNum := 'Arrival Number: '; sIBusName := 'Business Name : '; sILicencNum := 'Licence # : '; sIAddress := 'Address : '; sRecImpresso := 'Receipt Printed'; sClickOK := 'Click OK to continue'; end; LANG_PORTUGUESE : begin sEndereco := ' Endereço:'; sNoTaxAble := 'Não Tributável:'; sTaxAble := ' Tributável:'; sTax := ' Taxa:'; sSubTotal := ' SubTotal:'; sTotal := ' Total:'; sDiscount := ' Desconto:'; sHold := 'PEND'; sTaxExpHeadr := '=== I S E N Ç Ã O D E T A X A ===='; sIInvNum := 'N. da Nota : '; sIInvDate := 'Data da Nota : '; sICustomer := 'Cliente : '; sIPassPort := 'N. Passaporte : '; sIPassPrtNum := 'Data Passporte: '; sITicketNum := 'N. do Bilhete : '; sIAirLine := 'Linha Aérea : '; sIArrivalNum := 'N. da Chegada : '; sIBusName := 'Empresa : '; sILicencNum := 'N. Taxa ID : '; sIAddress := 'Endereço : '; sRecImpresso := 'Recibo Impresso'; sClickOK := 'Clique OK para continuar'; end; LANG_SPANISH : begin sEndereco := ' Dirección:'; sNoTaxAble := 'No Tributable:'; sTaxAble := ' Tributable:'; sTax := ' Impuesto:'; sSubTotal := ' SubTotal:'; sTotal := ' Total:'; sDiscount := ' Descuento:'; sHold := 'PEND'; sTaxExpHeadr := '========= EXENCIÒN DE IMPUESTO ========='; sIInvNum := 'Boleta # : '; sIInvDate := 'Fecha Boleta : '; sICustomer := 'Cliente : '; sIPassPort := 'Pasaporte : '; sIPassPrtNum := 'Fecha Pasaporte : '; sITicketNum := 'Pasaje # : '; sIAirLine := 'Linea Aérea : '; sIArrivalNum := 'Número Vuelo : '; sIBusName := 'Empresa : '; sILicencNum := 'Impuesto ID # : '; sIAddress := 'Dirección : '; sRecImpresso := 'Recibo Imprimido'; sClickOK := 'Clic OK para continuar'; end; end; end; procedure TPrintReceipt.tmrTimerTimer(Sender: TObject); var NotOk: Boolean; I, J: Integer; PSI : TPreSaleItem; dDiscountToPrint, dItemDiscount, dInvoiceDiscount, dTotalToPrint: Currency; PMT: TPayment; PPay: TPartialPay; begin inherited; tmrTimer.Enabled := False; Update; Application.ProcessMessages; // Open CashRegister NotOk := True; while NotOk do try DM.OpenCashRegister; DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else begin MsgBox(MSG_INF_REPRINT_INVOICE, vbInformation + vbOkOnly); Exit; end; end; // ----------------------------------------------------------------- // Impressão do cabecalho do ticket case FReceiptType of RECEIPT_TYPE_INVOICE, RECEIPT_TYPE_LAYAWAY_RECEIVE: // INVOICE begin // Tem que descobrir quem pagou o Invoice ImpTicketHeader(FPresale.PreSaleDate,//quPreSaleInfoInvoiceDate.AsDateTime, FPresale.COO, FPresale.SaleCode, FPresale.PreSaleInfo.CustomerInfo.FirstName + ' ' + FPresale.PreSaleInfo.CustomerInfo.LastName, FOpenCashier, FPresale.PreSaleInfo.TouristGroup.IDTouristGroup, False, FPresale.PreSaleInfo.MediaInfo.MediaName); end; RECEIPT_TYPE_HOLD: // HOLD begin ImpTicketHeader(FPresale.PreSaleDate,//quPreSaleInfoInvoiceDate.AsDateTime, '0', FPresale.SaleCode, FPresale.PreSaleInfo.CustomerInfo.FirstName + ' ' + FPresale.PreSaleInfo.CustomerInfo.LastName, '', FPresale.PreSaleInfo.TouristGroup.IDTouristGroup, False, FPresale.PreSaleInfo.MediaInfo.MediaName); end; RECEIPT_TYPE_TICKET: // HOTEL TICKET begin ImpTicketDeliverHeader(FPresale.PreSaleDate,//quPreSaleInfoPreSaleDate.AsDateTime, FPresale.SaleCode, '0', FPresale.PreSaleInfo.CustomerInfo.FirstName + ' ' + FPresale.PreSaleInfo.CustomerInfo.LastName, ''{quPreSaleInfoDeliverAddress.AsString}, FPresale.PreSaleInfo.TouristGroup.IDTouristGroup, FPresale.PreSaleInfo.MediaInfo.MediaName); end; end; // ----------------------------------------------------------------- // Impressão dos itens do Ticket for I := 0 to FPreSale.Count - 1 do begin PSI := FPreSale.Items[I]; if FPreSale.DiscountKind in [dkNone, dkInvoice] then dDiscountToPrint := 0 else dDiscountToPrint := PSI.Discount; ImpTicketLine(PSI.Qty, PSI.Description, PSI.Model, PSI.Sale - (dDiscountToPrint / PSI.Qty), PSI.BarCode, PSI.IDUser, DM.fPOS.TXTDescSystemUser(PSI.IDUser)); end; // ----------------------------------------------------------------- // Impressão dos Totais if (FPreSale.DiscountKind in [dkItem, dkInvoice]) then begin dItemDiscount := FPreSale.DiscountTotal; dInvoiceDiscount := FPreSale.InvoiceDiscount; end else begin dItemDiscount := 0; dInvoiceDiscount := 0; end; case FReceiptType of RECEIPT_TYPE_INVOICE, RECEIPT_TYPE_LAYAWAY_RECEIVE: // INVOICE begin ImpTicketTotals(FTaxable, FExempt, FPreSale.SaleTotal, FPreSale.TaxTotal, FPayments.InvoiceTotal, MyCashReceived, FPayments.ChangeTotal, dItemDiscount, dInvoiceDiscount, FPreSale.RefundTotal, FPreSale.PreSaleType = tptRefund); end; RECEIPT_TYPE_HOLD, RECEIPT_TYPE_TICKET: // HOLD AND HOTEL TICKET begin ImpTicketHoldTotals(FTaxable, FExempt, FPayments.InvoiceTotal, FPreSale.TaxTotal, FPreSale.SaleTotal, MyCashReceived, MyCashReceived - MyTotCash, FReceiptType, FPreSale.DiscountTotal + FPreSale.InvoiceDiscount, FPreSale.PreSaleType = tptRefund); end; end; // ----------------------------------------------------------------- // Impressão das parcelas case FReceiptType of RECEIPT_TYPE_INVOICE, RECEIPT_TYPE_LAYAWAY_RECEIVE: // INVOICE & LAYAWAY begin for I := 0 to FPayments.Count - 1 do begin PMT := FPayments.Items[I]; for J := 0 to PMT.Count - 1 do begin PPay := PMT.Items[J]; ImpTicketPaymentLine(PPay.ExpireDate, DM.fPOS.DescCodigoCDS(DMPDV.cdsMeioPag, 'IDMeioPag', IntToStr(PMT.IDMeioPag), 'MeioPag'), PPay.Value); end; end; end; RECEIPT_TYPE_HOLD, RECEIPT_TYPE_TICKET: // HOLD & HOTEL TICKET begin // Não tem impressao de parcelas end; end; // ----------------------------------------------------------------- // Impressão do notes // if (DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'PrintNotes') = '1') then if (FPreSale.InvObs <> '') then ImpTicketNotes; // ----------------------------------------------------------------- // Impressão do rodape case FReceiptType of RECEIPT_TYPE_INVOICE, RECEIPT_TYPE_TICKET, RECEIPT_TYPE_HOLD: // INVOICE, HOTEL TICKET, HOLD ImpTicketFooter(); RECEIPT_TYPE_LAYAWAY_RECEIVE: //LAYAWAY + Total and balance ImpFooterLayaway(FPayments.InvoiceTotal, fPaymentTotal); end; // Caso o Invoice tenha recebido uma isenção de taxa, devo incluir // a impressao de um documento de conhecimento de isenção. if ((FReceiptType = RECEIPT_TYPE_INVOICE) AND FPreSale.TaxExempt) and (StrToBoolDef(DM.fPOS.DescCodigoCDS(DM.cdsStore, 'IDStore', IntToStr(DM.fStore.ID), 'PrintTaxInsemptFooter'), False)) then begin ImpTicketTaxExemption(); end; DM.PrinterStop; DM.SendAfterPrintCode(True); lblPrint.Caption := sRecImpresso; btOk.Visible := True; AniPrint.Active := False; AniPrint.Visible := False; pnlPrinter.Caption := sClickOK; end; end.
unit rtti_idebinder_uDataSlots; interface uses Classes, SysUtils, rtti_broker_iBroker, Controls, StdCtrls, ExtCtrls, fgl, Graphics, rtti_idebinder_uBinders, Grids, SynEdit; type { TDataSlotsItem } TDataSlotsItem = class fBinder: TEditBinder; fDataItem: IRBDataItem; fDataQuery: IRBDataQuery; private function NewBinder(AContainer: TWinControl): TEditBinder; function FindControl(AContainer: TWinControl): TWinControl; public destructor Destroy; override; procedure Bind(const AContainer: TWinControl; const ADataItem: IRBDataItem; const ADataQuery: IRBDataQuery); procedure DataChange; end; { TDataSlots } TDataSlots = class private type TDataEditItems = specialize TFPGObjectList<TDataSlotsItem>; private fItems: TDataEditItems; fData: IRBData; fDataQuery: IRBDataQuery; fContainer: TWinControl; procedure ActualizeItems; function GetData: IRBData; procedure SetData(AValue: IRBData); private function GetItems(AIndex: Integer; APropIndex: integer): TDataSlotsItem; procedure SetItems(AIndex: Integer; APropIndex: integer; AValue: TDataSlotsItem); function GetItemsCount(AIndex: Integer): integer; procedure SetItemsCount(AIndex: Integer; AValue: integer); public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure Bind(const AContainer: TWinControl; const AData: IRBData; const ADataQuery: IRBDataQuery); procedure DataChange; property Data: IRBData read GetData write SetData; public //for now not persist property Items[AIndex: integer]: TDataSlotsItem index crbList + crbObject read GetItems write SetItems; default; property ItemsCount: integer index crbListCounter read GetItemsCount write SetItemsCount; end; implementation { TDataSlotsItem } function TDataSlotsItem.NewBinder(AContainer: TWinControl): TEditBinder; var mText: IRBDataText; mControl: TWinControl; begin Result := nil; mControl := FindControl(AContainer); if Assigned(mControl) then begin if mControl is TCustomEdit then Result := TTextBinder.Create else if mControl is TCustomComboBox then begin if fDataItem.IsObject and fDataItem.IsReference then begin Result := TOfferObjectRefBinder.Create; end else if fDataItem.EnumNameCount > 0 then begin Result := TOfferEnumBinder.Create; end; end else if mControl is TCustomStringGrid then Result := TListBinder.Create else if mControl is TCustomCheckBox then Result := TBoolBinder.Create else if mControl is TCustomSynEdit then Result := TMemoBinder.Create; end; if Assigned(Result) then Result.Bind(mControl, fDataItem, fDataQuery); end; function TDataSlotsItem.FindControl(AContainer: TWinControl): TWinControl; var i: integer; begin Result := nil; for i := 0 to AContainer.ControlCount - 1 do begin if not (AContainer.Controls[i] is TWinControl) then Continue; Result := FindControl(AContainer.Controls[i] as TWinControl); if Assigned(Result) then Exit; if SameText(fDataItem.Name + '_bind', AContainer.Controls[i].Name) then begin Result := AContainer.Controls[i] as TWinControl; Exit; end; end; end; destructor TDataSlotsItem.Destroy; begin FreeAndNil(fBinder); inherited Destroy; end; procedure TDataSlotsItem.DataChange; begin if Assigned(fBinder) then fBinder.DataToControl; end; procedure TDataSlotsItem.Bind(const AContainer: TWinControl; const ADataItem: IRBDataItem; const ADataQuery: IRBDataQuery); begin FreeAndNil(fBinder); fDataItem := ADataItem; fDataQuery := ADataQuery; fBinder := NewBinder(AContainer); DataChange; end; { TDataSlots } function TDataSlots.GetItems(AIndex: Integer; APropIndex: integer): TDataSlotsItem; begin Result := fItems[AIndex]; end; procedure TDataSlots.SetData(AValue: IRBData); begin fData := AValue; DataChange; end; function TDataSlots.GetItemsCount(AIndex: Integer): integer; begin Result := fItems.Count; end; procedure TDataSlots.ActualizeItems; var i: integer; begin fItems.Clear; ItemsCount := fData.Count; for i := 0 to fData.Count - 1 do begin Items[i] := TDataSlotsItem.Create; Items[i].Bind(fContainer, fData[i], fDataQuery); end; end; function TDataSlots.GetData: IRBData; begin Result := fData; end; procedure TDataSlots.SetItems(AIndex: Integer; APropIndex: integer; AValue: TDataSlotsItem); begin fItems[AIndex] := AValue; end; procedure TDataSlots.SetItemsCount(AIndex: Integer; AValue: integer); begin fItems.Count := AValue; end; procedure TDataSlots.AfterConstruction; begin inherited AfterConstruction; fItems := TDataEditItems.Create; end; procedure TDataSlots.BeforeDestruction; begin FreeAndNil(fItems); inherited BeforeDestruction; end; procedure TDataSlots.Bind(const AContainer: TWinControl; const AData: IRBData; const ADataQuery: IRBDataQuery); begin fContainer := AContainer; fData := AData; fDataQuery := ADataQuery; ActualizeItems; end; procedure TDataSlots.DataChange; var i: Integer; begin for i := 0 to ItemsCount - 1 do Items[i].DataChange; end; end.
unit FindEOI; interface uses System.Classes; function HasEOI(ABuffer: TStringStream): Integer; implementation function HasEOI(ABuffer: TStringStream): Integer; const FF = $FF; D9 = $D9; var i : Integer; begin Result := -1; for i := 0 to Pred(Length(ABuffer.Bytes)) do begin if ABuffer.Bytes[i] = FF then begin if ABuffer.Bytes[i + 1] = D9 then begin Result := Succ(i); Break; end; end; end; end; end.
unit MainForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, SynCompletion, Forms, Controls, Graphics, Dialogs, Menus, ComCtrls, ExtCtrls, StdCtrls, Buttons, Editor, Global, AboutForm, dbgframe, Process, LazUTF8, debugger, Windows; type { TMainFrm } TMainFrm = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; DbgMakeDumpButton: TButton; DbgStartStopButton: TButton; Button4: TButton; DebuggerFrame1: TDebuggerFrame; Image1: TImage; Image2: TImage; ImageList1: TImageList; Label2: TLabel; Label3: TLabel; LogsPanel: TPanel; MainMenu1: TMainMenu; LogMemo: TMemo; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem11: TMenuItem; MenuItem12: TMenuItem; MenuItem13: TMenuItem; MenuItem14: TMenuItem; MenuItem15: TMenuItem; MenuItem16: TMenuItem; MenuItem17: TMenuItem; MenuItem18: TMenuItem; MenuItem19: TMenuItem; MenuItem2: TMenuItem; MenuItem20: TMenuItem; MenuItem21: TMenuItem; MenuItem22: TMenuItem; MenuItem23: TMenuItem; MenuItem24: TMenuItem; MenuItem25: TMenuItem; MenuItem26: TMenuItem; MenuItem27: TMenuItem; MenuItem28: TMenuItem; MenuItem29: TMenuItem; MenuItem3: TMenuItem; MenuItem30: TMenuItem; MenuItem31: TMenuItem; MenuItem32: TMenuItem; MenuItem33: TMenuItem; MenuItem34: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; OpenDialog: TOpenDialog; PageControl: TPageControl; DebuggerPanel: TPanel; Panel4: TPanel; PreviewControlsPanel: TPanel; PreviewPanel: TPanel; Panel2: TPanel; Panel3: TPanel; SaveDialog: TSaveDialog; Splitter1: TSplitter; Splitter2: TSplitter; StatusBar: TStatusBar; PreviewPanelTimer: TTimer; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure MenuItem10Click(Sender: TObject); procedure MenuItem12Click(Sender: TObject); procedure MenuItem13Click(Sender: TObject); procedure MenuItem14Click(Sender: TObject); procedure MenuItem17Click(Sender: TObject); procedure MenuItem18Click(Sender: TObject); procedure MenuItem19Click(Sender: TObject); procedure MenuItem22Click(Sender: TObject); procedure MenuItem23Click(Sender: TObject); procedure MenuItem25Click(Sender: TObject); procedure MenuItem26Click(Sender: TObject); procedure MenuItem28Click(Sender: TObject); procedure MenuItem29Click(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem30Click(Sender: TObject); procedure MenuItem31Click(Sender: TObject); procedure MenuItem32Click(Sender: TObject); procedure MenuItem33Click(Sender: TObject); procedure MenuItem34Click(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem6Click(Sender: TObject); procedure MenuItem7Click(Sender: TObject); procedure MenuItem9Click(Sender: TObject); procedure OpenTab(FilePath, TabName: string; Operation: TOpenOp); procedure PageControlChange(Sender: TObject); procedure PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure BuildFile(fp, flags: string); procedure BuildFileAndRun(fp, flags, svm: string); procedure PreviewPanelClick(Sender: TObject); procedure PreviewPanelTimerTimer(Sender: TObject); procedure ShowPreviewPanel; private { private declarations } public { public declarations } end; var MainFrm: TMainFrm; NewTabsCnt: cardinal = 0; ActivePageIndex: cardinal; implementation {$R *.lfm} procedure TMainFrm.ShowPreviewPanel; begin PreviewPanel.Left := PageControl.Left; PreviewPanel.Top := PageControl.Top; PreviewPanel.Width := PageControl.Width; PreviewPanel.Height := PageControl.Height; PreviewControlsPanel.Left := (PreviewPanel.Width - PreviewControlsPanel.Width) div 2; PreviewControlsPanel.Top := (PreviewPanel.Height - PreviewControlsPanel.Height) div 2; PreviewPanel.Visible := True; end; function GetEditor(Tab: TTabSheet): TEditorFrame; var j: cardinal; begin j := 0; Result := nil; while j < Tab.ControlCount do begin if (Tab.Controls[j] is TEditorFrame) then begin Result := TEditorFrame(Tab.Controls[j]); break; end; Inc(j); end; end; procedure TMainFrm.OpenTab(FilePath, TabName: string; Operation: TOpenOp); var Editor: TEditorFrame; Tab: TTabSheet; begin Tab := TTabSheet.Create(PageControl); Tab.Caption := TabName + ' [X]'; if LowerCase(Trim(ExtractFileExt(TabName))) = '.mash' then Tab.ImageIndex := 0 else Tab.ImageIndex := 2; Tab.PageControl := PageControl; Editor := TEditorFrame.CreateEditor(Tab, StatusBar, Operation, FilePath); Editor.Visible := True; Editor.Parent := Tab; ActivePageIndex := PageControl.PageCount - 1; PageControl.ActivePageIndex := ActivePageIndex; end; procedure TMainFrm.PageControlChange(Sender: TObject); begin PageControl.ActivePageIndex := ActivePageIndex; end; function InRect(R: TRect; P: TPoint): boolean; begin Result := (R.Left <= P.X) and (R.Right >= P.X) and (R.Top <= P.Y) and (R.Bottom >= P.Y); end; procedure TMainFrm.PageControlMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); var TabIndex: integer; TabRect: TRect; begin if Button = mbLeft then begin TabIndex := PageControl.IndexOfTabAt(X, Y); ActivePageIndex := TabIndex; TabRect := PageControl.TabRect(TabIndex); if InRect(Classes.Rect(TabRect.Right - 16 - 2, TabRect.Top + 2, TabRect.Right - 6, TabRect.Bottom - 4), Classes.Point(X, Y)) then begin ActivePageIndex := PageControl.ActivePageIndex; PageControl.Pages[TabIndex].Free; if PageControl.PageCount > 0 then begin if ActivePageIndex > TabIndex then Dec(ActivePageIndex); if ActivePageIndex >= 0 then PageControl.ActivePageIndex := ActivePageIndex; end; end; PageControl.ActivePageIndex := ActivePageIndex; end; end; procedure TMainFrm.MenuItem2Click(Sender: TObject); begin Inc(NewTabsCnt); OpenTab('', 'New ' + IntToStr(NewTabsCnt), opopNew); end; procedure TMainFrm.MenuItem30Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.PasteFromClipboard; end; procedure TMainFrm.MenuItem31Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.SelectAll; end; procedure TMainFrm.MenuItem32Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFileAndRun(EdtFrm.DefFile, 'console', 'svmc.exe'); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFileAndRun(EdtFrm.DefFile, 'console', 'svmc.exe'); end; end; end; end; procedure TMainFrm.MenuItem33Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, '/bin /mdbg+ /o+ /olvl 3'); DebugFile(MainFrm, ChangeFileExt(EdtFrm.DefFile, '.vmc'), ChangeFileExt(EdtFrm.DefFile, '.mdbg')); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, '/bin /mdbg+ /o+ /olvl 3'); DebugFile(MainFrm, ChangeFileExt(EdtFrm.DefFile, '.vmc'), ChangeFileExt(EdtFrm.DefFile, '.mdbg')); end; end; end; end; procedure TMainFrm.MenuItem34Click(Sender: TObject); begin DebuggerPanel.Width := 385; end; procedure TMainFrm.MenuItem3Click(Sender: TObject); begin if OpenDialog.Execute then begin OpenTab(OpenDialog.FileName, ExtractFileName(OpenDialog.FileName), opopOpen); end; end; procedure TMainFrm.MenuItem5Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFileName(SaveDialog.FileName) + ' [X]'; EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; end; end; end; end; procedure TMainFrm.MenuItem6Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFileName(SaveDialog.FileName) + ' [X]'; EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; end; end; end; procedure TMainFrm.MenuItem7Click(Sender: TObject); var j: cardinal; begin j := 0; while j < PageControl.PageCount do begin PageControl.ActivePageIndex := j; MenuItem5Click(Sender); Inc(j); end; PageControl.ActivePageIndex := ActivePageIndex; end; procedure TMainFrm.MenuItem9Click(Sender: TObject); begin Close; end; procedure TMainFrm.FormCreate(Sender: TObject); begin DebuggerPanel.Width := 0; LogsPanel.Height := 0; ShowPreviewPanel; end; procedure TMainFrm.FormResize(Sender: TObject); begin if PageControl.PageCount = 0 then ShowPreviewPanel; end; function BuildThread(p: pointer): Int64; begin Result := 0; TProcess(p).Execute; end; procedure TMainFrm.BuildFile(fp, flags: string); var AProcess: TProcess; sl: TStringList; thr: QWord; s: string; begin LogMemo.Lines.Clear; LogMemo.Repaint; sl := TStringList.Create; s := fp; if Pos(ExtractFilePath(ParamStr(0)), s) > 0 then Delete(s, 1, length(ExtractFilePath(ParamStr(0)))); LogMemo.Lines.Add('Start building file: "' + s + '"'); try AProcess := TProcess.Create(Self); AProcess.Executable := 'mashc.exe'; AProcess.Parameters.Add(UTF8ToWinCP(s)); AProcess.Parameters.Add(UTF8ToWinCP(ChangeFileExt(s, '.asm'))); {while pos(' ', flags) > 0 do begin AProcess.Parameters.Add(copy(flags, 1, pos(' ', flags) - 1)); Delete(flags, 1, pos(' ', flags)); end; if Length(flags) > 0 then AProcess.Parameters.Add(flags);} AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole, poStderrToOutPut]; AProcess.PipeBufferSize := 1024 * 1024; BeginThread(nil, 0, @BuildThread, Pointer(AProcess), 0, thr); Sleep(10); while AProcess.Running do begin Application.ProcessMessages; Sleep(10); end; sl.LoadFromStream(AProcess.Output); LogMemo.Lines.AddStrings(sl); FreeAndNil(AProcess); AProcess := TProcess.Create(Self); AProcess.Executable := 'asm.exe'; AProcess.Parameters.Add(UTF8ToWinCP(flags)); AProcess.Parameters.Add(UTF8ToWinCP(ChangeFileExt(s, '.asm'))); AProcess.Parameters.Add(UTF8ToWinCP(ChangeFileExt(s, '.vmc'))); AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes, poNoConsole, poStderrToOutPut]; AProcess.PipeBufferSize := 1024 * 1024; BeginThread(nil, 0, @BuildThread, Pointer(AProcess), 0, thr); Sleep(10); while AProcess.Running do begin Application.ProcessMessages; Sleep(10); end; sl.LoadFromStream(AProcess.Output); LogMemo.Lines.AddStrings(sl); FreeAndNil(AProcess); except on E: Exception do begin LogMemo.Lines.Add('Building failed, exception: "' + E.Message + '".'); end; end; FreeAndNil(AProcess); FreeAndNil(sl); end; procedure TMainFrm.BuildFileAndRun(fp, flags, svm: string); var fp_vmc: string; AProcess: TProcess; begin fp_vmc := ExtractFilePath(fp) + ChangeFileExt(ExtractFileName(fp), '.vmc'); if FileExists(fp_vmc) then SysUtils.DeleteFile(fp_vmc); BuildFile(fp, flags); Sleep(300); if FileExists(fp_vmc) then begin try AProcess := TProcess.Create(Self); AProcess.Executable := svm; AProcess.Parameters.Add(UTF8ToWinCP(fp_vmc)); AProcess.Execute; except on E: Exception do begin LogMemo.Lines.Add('Failed to launch, exception: "' + E.Message + '".'); end; end; FreeAndNil(AProcess); end else LogMemo.Lines.Add('Failed to launch .vmc file.'); end; procedure TMainFrm.PreviewPanelClick(Sender: TObject); begin end; procedure TMainFrm.PreviewPanelTimerTimer(Sender: TObject); begin //show it if (PageControl.PageCount = 0) and (not PreviewPanel.Visible) then ShowPreviewPanel; //hide it if PreviewPanel.Visible and (PageControl.PageCount > 0) then PreviewPanel.Visible := False; end; procedure TMainFrm.MenuItem10Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, 'console'); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, 'console'); end; end; end; end; procedure TMainFrm.Button1Click(Sender: TObject); begin LogsPanel.Height := 0; end; procedure TMainFrm.Button2Click(Sender: TObject); begin MenuItem2Click(Sender); end; procedure TMainFrm.Button3Click(Sender: TObject); begin MenuItem3Click(Sender); end; procedure TMainFrm.Button4Click(Sender: TObject); begin DebuggerPanel.Width := 0; end; procedure TMainFrm.MenuItem12Click(Sender: TObject); begin LogsPanel.Height := 196; end; procedure TMainFrm.MenuItem13Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFileAndRun(EdtFrm.DefFile, 'gui', 'svmg.exe'); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFileAndRun(EdtFrm.DefFile, 'gui', 'svmg.exe'); end; end; end; end; procedure TMainFrm.MenuItem14Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, 'gui'); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, 'gui'); end; end; end; end; procedure TMainFrm.MenuItem17Click(Sender: TObject); var EdtFrm: TEditorFrame; begin if LogsPanel.Height = 0 then LogsPanel.Height := 196; Self.Repaint; if PageControl.ActivePageIndex >= 0 then begin EdtFrm := GetEditor(PageControl.ActivePage); if FileExists(EdtFrm.DefFile) then begin EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, '/bin /o-'); DebugFile(MainFrm, ChangeFileExt(EdtFrm.DefFile, '.vmc'), ChangeFileExt(EdtFrm.DefFile, '.mdbg')); end else begin if SaveDialog.Execute then begin EdtFrm.DefFile := SaveDialog.FileName; PageControl.ActivePage.Caption := ExtractFilePath(SaveDialog.FileName); EdtFrm.SynEdit.Lines.SaveToFile(EdtFrm.DefFile); EdtFrm.Saved := True; EdtFrm.UpdateState; BuildFile(EdtFrm.DefFile, '/bin /mdbg+ /o-'); DebugFile(MainFrm, ChangeFileExt(EdtFrm.DefFile, '.vmc'), ChangeFileExt(EdtFrm.DefFile, '.mdbg')); end; end; end; end; procedure TMainFrm.MenuItem18Click(Sender: TObject); var dest, inf: string; begin if OpenDialog.Execute then begin dest := OpenDialog.FileName; inf := ''; case MessageBox(0, 'Is have debug information file?', 'Prepare debugger...', MB_YESNO) of idYes: if OpenDialog.Execute then inf := OpenDialog.FileName; idNo: ; end; DebugFile(MainFrm, dest, inf); end; end; procedure TMainFrm.MenuItem19Click(Sender: TObject); begin AboutFrm.ShowModal; end; procedure TMainFrm.MenuItem22Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.Undo; end; procedure TMainFrm.MenuItem23Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.Redo; end; procedure TMainFrm.MenuItem25Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).FindDlg; end; procedure TMainFrm.MenuItem26Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).ReplaceDlg; end; procedure TMainFrm.MenuItem28Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.CutToClipboard; end; procedure TMainFrm.MenuItem29Click(Sender: TObject); begin if PageControl.ActivePageIndex >= 0 then GetEditor(PageControl.ActivePage).SynEdit.CopyToClipboard; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [FIN_EXTRATO_CONTA_BANCO] 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 FinExtratoContaBancoController; {$MODE Delphi} interface uses Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller, VO, ZDataset, FinExtratoContaBancoVO; type TFinExtratoContaBancoController = class(TController) private public class function Consulta(pFiltro: String; pPagina: String): TZQuery; class function ConsultaLista(pFiltro: String): TListaFinExtratoContaBancoVO; class function ConsultaObjeto(pFiltro: String): TFinExtratoContaBancoVO; class procedure Insere(pObjeto: TFinExtratoContaBancoVO); class function Altera(pObjeto: TFinExtratoContaBancoVO): Boolean; class function Exclui(pId: Integer): Boolean; end; implementation uses UDataModule, T2TiORM; var ObjetoLocal: TFinExtratoContaBancoVO; class function TFinExtratoContaBancoController.Consulta(pFiltro: String; pPagina: String): TZQuery; begin try ObjetoLocal := TFinExtratoContaBancoVO.Create; Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina); finally ObjetoLocal.Free; end; end; class function TFinExtratoContaBancoController.ConsultaLista(pFiltro: String): TListaFinExtratoContaBancoVO; begin try ObjetoLocal := TFinExtratoContaBancoVO.Create; Result := TListaFinExtratoContaBancoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True)); finally ObjetoLocal.Free; end; end; class function TFinExtratoContaBancoController.ConsultaObjeto(pFiltro: String): TFinExtratoContaBancoVO; begin try Result := TFinExtratoContaBancoVO.Create; Result := TFinExtratoContaBancoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True)); finally end; end; class procedure TFinExtratoContaBancoController.Insere(pObjeto: TFinExtratoContaBancoVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class function TFinExtratoContaBancoController.Altera(pObjeto: TFinExtratoContaBancoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TFinExtratoContaBancoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TFinExtratoContaBancoVO; begin try ObjetoLocal := TFinExtratoContaBancoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal) end; end; initialization Classes.RegisterClass(TFinExtratoContaBancoController); finalization Classes.UnRegisterClass(TFinExtratoContaBancoController); end.
unit GrammarChecker; interface type IGrammarChecker = interface ['{11F35265-4CFE-4920-9AAF-0EB69B0A7A91}'] procedure CheckGrammar; end; TDefaultGrammarChecker = class(TInterfacedObject, IGrammarChecker) procedure CheckGrammar; end; TRealGrammarChecker = class(TInterfacedObject, IGrammarChecker) procedure CheckGrammar; end; implementation { TRealGrammarChecker } procedure TDefaultGrammarChecker.CheckGrammar; begin Writeln('Do nothing'); end; procedure TRealGrammarChecker.CheckGrammar; begin Writeln('Grammar has been checked'); end; end.
// // Generated by JavaToPas v1.5 20150830 - 103231 //////////////////////////////////////////////////////////////////////////////// unit org.apache.http.impl.conn.tsccm.AbstractConnPool; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, org.apache.http.impl.conn.IdleConnectionHandler, java.util.concurrent.locks.Lock, java.lang.ref.ReferenceQueue, org.apache.http.impl.conn.tsccm.BasicPoolEntry, org.apache.http.conn.routing.HttpRoute, java.util.concurrent.TimeUnit, org.apache.http.impl.conn.tsccm.PoolEntryRequest, java.lang.ref.Reference, org.apache.http.conn.OperatedClientConnection; type JAbstractConnPool = interface; JAbstractConnPoolClass = interface(JObjectClass) ['{A0EAD087-56F8-49F1-AF90-2E5DB3DFF72D}'] function getEntry(route : JHttpRoute; state : JObject; timeout : Int64; tunit : JTimeUnit) : JBasicPoolEntry; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;JLjava/util/concurrent/TimeUnit;)Lorg/apache/http/impl/conn/tsccm/BasicPoolEntry; A: $11 function requestPoolEntry(JHttpRouteparam0 : JHttpRoute; JObjectparam1 : JObject) : JPoolEntryRequest; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/impl/conn/tsccm/PoolEntryRequest; A: $401 procedure closeExpiredConnections ; cdecl; // ()V A: $1 procedure closeIdleConnections(idletime : Int64; tunit : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $1 procedure deleteClosedConnections ; cdecl; // ()V A: $401 procedure enableConnectionGC ; cdecl; // ()V A: $1 procedure freeEntry(JBasicPoolEntryparam0 : JBasicPoolEntry; booleanparam1 : boolean; Int64param2 : Int64; JTimeUnitparam3 : JTimeUnit) ; cdecl;// (Lorg/apache/http/impl/conn/tsccm/BasicPoolEntry;ZJLjava/util/concurrent/TimeUnit;)V A: $401 procedure handleReference(ref : JReference) ; cdecl; // (Ljava/lang/ref/Reference;)V A: $1 procedure shutdown ; cdecl; // ()V A: $1 end; [JavaSignature('org/apache/http/impl/conn/tsccm/AbstractConnPool')] JAbstractConnPool = interface(JObject) ['{ADD1231D-7D0D-4143-8B02-D54FD7570472}'] function requestPoolEntry(JHttpRouteparam0 : JHttpRoute; JObjectparam1 : JObject) : JPoolEntryRequest; cdecl;// (Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Object;)Lorg/apache/http/impl/conn/tsccm/PoolEntryRequest; A: $401 procedure closeExpiredConnections ; cdecl; // ()V A: $1 procedure closeIdleConnections(idletime : Int64; tunit : JTimeUnit) ; cdecl;// (JLjava/util/concurrent/TimeUnit;)V A: $1 procedure deleteClosedConnections ; cdecl; // ()V A: $401 procedure enableConnectionGC ; cdecl; // ()V A: $1 procedure freeEntry(JBasicPoolEntryparam0 : JBasicPoolEntry; booleanparam1 : boolean; Int64param2 : Int64; JTimeUnitparam3 : JTimeUnit) ; cdecl;// (Lorg/apache/http/impl/conn/tsccm/BasicPoolEntry;ZJLjava/util/concurrent/TimeUnit;)V A: $401 procedure handleReference(ref : JReference) ; cdecl; // (Ljava/lang/ref/Reference;)V A: $1 procedure shutdown ; cdecl; // ()V A: $1 end; TJAbstractConnPool = class(TJavaGenericImport<JAbstractConnPoolClass, JAbstractConnPool>) end; implementation end.
unit frmVersionCheck; interface uses Classes, ComCtrls, CommonSettings, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, OTFEFreeOTFE_InstructionRichEdit, SDUForms, SDUStdCtrls, StdCtrls, SysUtils, Variants, Windows; type TfrmVersionCheck = class (TSDUForm) Label2: TLabel; Label3: TLabel; lblVersionCurrent: TLabel; pbClose: TButton; SDUURLLabel1: TSDUURLLabel; ckSuppressNotifyingThisVersion: TCheckBox; lblVersionLatest: TLabel; procedure pbCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); PRIVATE FLatestMajorVersion, FLatestMinorVersion: Integer; PROTECTED procedure SetAllowSuppress(allow: Boolean); function GetSuppressNotifyingThisVersion(): Boolean; PUBLIC property AllowSuppress: Boolean Write SetAllowSuppress; property LatestMajorVersion: Integer Read FLatestMajorVersion Write FLatestMajorVersion; property LatestMinorVersion: Integer Read FLatestMinorVersion Write FLatestMinorVersion; property SuppressNotifyingThisVersion: Boolean Read GetSuppressNotifyingThisVersion; end; procedure CheckForUpdates_UserCheck(PADURL: String); procedure CheckForUpdates_AutoCheck(PADURL: String; var Frequency: TUpdateFrequency; var LastChecked: TDate; var SuppressNotifyVerMajor: Integer; var SuppressNotifyVerMinor: Integer); implementation {$R *.dfm} uses ShellAPI, // Required for ShellExecute CommonConsts, lcConsts, {$IFDEF FREEOTFE_MAIN} MainSettings, {$ENDIF} {$IFDEF FREEOTFE_EXPLORER} ExplorerSettings, {$ENDIF} lcDialogs, SDUGeneral, SDUi18n, SDUWinHttp; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} resourcestring RS_CHECKING = '<checking...>'; RS_CONFIRM_AUTOCHECK = 'Do you want to automatically check for updates in the future?'; RS_UNABLE_TO_DETERMINE_THIS_VERSION = 'Unable to determine which version this software is.'; // Manual check algorithm: // // if user forced check: // hit WWW site for latest version // - if user cancel, exit // - if can't connect, tell user then exit // - if got data: // - report version in use and latest version procedure CheckForUpdates_UserCheck(PADURL: String); var dlg: TfrmVersionCheck; wwwResult: TTimeoutGet; latestMajorVersion: Integer; latestMinorVersion: Integer; begin if not (SDUWinHTTPSupported) then begin // Just open homepage; user can check manually... ShellExecute( 0, PChar('open'), PChar(URL_HOMEPAGE), PChar(''), PChar(''), SW_SHOW ); exit; end; wwwResult := SDUGetPADFileVersionInfo(PADURL, latestMajorVersion, latestMinorVersion, Application.Title + '/' + SDUGetVersionInfoString(''), True); if (wwwResult = tgCancel) then begin // Do nothing; just fall out of procedure end else if (wwwResult <> tgOK) then begin SDUMessageDlg( SDUParamSubstitute(_('Unable to determine latest release of %1.'), [Application.Title]), mtError ); end else begin dlg := TfrmVersionCheck.Create(nil); try dlg.LatestMajorVersion := latestMajorVersion; dlg.LatestMinorVersion := latestMinorVersion; dlg.AllowSuppress := False; dlg.ShowModal(); finally dlg.Free(); end; end; end; // Automatic check algorithm: // // if time to check again: // hit WWW site for latest version // - if user cancel, prompt if want to check again in future // - if don't, update to never check again // - if can't connect, prompt if want to check again in future // - if don't, update to never check again // - if got data: // - if no newer version available // - update date last checked // - if newer version available, display dialog // - if user doens't want to be informed of this version again // - update date last checked // - if user still want to be informed // - (DO NOT update date last checked) procedure CheckForUpdates_AutoCheck(PADURL: String; var Frequency: TUpdateFrequency; var LastChecked: TDate; var SuppressNotifyVerMajor: Integer; var SuppressNotifyVerMinor: Integer); var dlg: TfrmVersionCheck; wwwResult: TTimeoutGet; latestMajorVersion: Integer; latestMinorVersion: Integer; currMajorVersion: Integer; currMinorVersion: Integer; compareResult: Integer; begin if not (SDUWinHTTPSupported) then begin // No changes to var parameters - just exit exit; end; //prompt to connect to net { DONE 1 -otdk -cenhance : remember result } if not (SDUConfirmYN(_( 'A check for an update is due, which requires a connection to the internet. Continue?'))) then wwwResult := tgCancel else wwwResult := SDUGetPADFileVersionInfo(PADURL, latestMajorVersion, latestMinorVersion, Application.Title + '/' + SDUGetVersionInfoString(''), True); if (wwwResult = tgCancel) then begin // if can't save settings then no point in asking whether to check again (will automatically) if gSettings.OptSaveSettings = slNone then begin SDUMessageDlg(_('Canceled checking for updated version'),mtInformation); end else begin if not (SDUConfirmYN(_('Canceled checking for updated version') + SDUCRLF + SDUCRLF + RS_CONFIRM_AUTOCHECK)) then Frequency := ufNever; end; end else if (wwwResult <> tgOK) then begin if not (SDUErrorYN(SDUParamSubstitute(_('Unable to determine latest release of %1.'), [Application.Title]) + SDUCRLF + SDUCRLF + RS_CONFIRM_AUTOCHECK)) then begin Frequency := ufNever; end; end else begin // If user doesn't want to be informed of this version... if (SDUVersionCompare(latestMajorVersion, latestMinorVersion, SuppressNotifyVerMajor, SuppressNotifyVerMinor) >= 0) then begin // Do nothing; just update last checked LastChecked := now; end else begin if not (SDUGetVersionInfo('', currMajorVersion, currMinorVersion)) then begin SDUMessageDlg(RS_UNABLE_TO_DETERMINE_THIS_VERSION, mtError); end; compareResult := SDUVersionCompareWithBetaFlag(currMajorVersion, currMinorVersion, APP_BETA_BUILD, latestMajorVersion, latestMinorVersion); if (compareResult = 0) then begin // This software is the latest version LastChecked := now; end else if (compareResult < 0) then begin // This software is the prerelease version LastChecked := now; end else begin // This software is an old version dlg := TfrmVersionCheck.Create(nil); try dlg.LatestMajorVersion := latestMajorVersion; dlg.LatestMinorVersion := latestMinorVersion; dlg.AllowSuppress := True; dlg.ShowModal(); if dlg.SuppressNotifyingThisVersion then begin SuppressNotifyVerMajor := latestMajorVersion; SuppressNotifyVerMinor := latestMinorVersion; LastChecked := now; end; finally dlg.Free(); end; end; end; end; end; procedure TfrmVersionCheck.pbCloseClick(Sender: TObject); begin Close(); end; procedure TfrmVersionCheck.FormCreate(Sender: TObject); begin lblVersionCurrent.Caption := RS_CHECKING; lblVersionLatest.Caption := RS_CHECKING; SDUURLLabel1.URL := URL_DOWNLOAD; SDUURLLabel1.Visible := False; end; procedure TfrmVersionCheck.SetAllowSuppress(allow: Boolean); begin ckSuppressNotifyingThisVersion.Visible := allow; ckSuppressNotifyingThisVersion.Checked := False; end; function TfrmVersionCheck.GetSuppressNotifyingThisVersion(): Boolean; begin Result := ckSuppressNotifyingThisVersion.Checked; end; procedure TfrmVersionCheck.FormShow(Sender: TObject); var compareResult: Integer; currMajorVersion: Integer; currMinorVersion: Integer; begin lblVersionLatest.Caption := 'v' + SDUVersionInfoToString(FLatestMajorVersion, FLatestMinorVersion); if not (SDUGetVersionInfo('', currMajorVersion, currMinorVersion)) then begin lblVersionCurrent.Caption := RS_UNKNOWN; SDUMessageDlg(RS_UNABLE_TO_DETERMINE_THIS_VERSION, mtError); end else begin compareResult := SDUVersionCompareWithBetaFlag(currMajorVersion, currMinorVersion, APP_BETA_BUILD, FLatestMajorVersion, FLatestMinorVersion); lblVersionCurrent.Caption := 'v' + SDUVersionInfoToString(currMajorVersion, currMinorVersion, APP_BETA_BUILD); if (compareResult > 0) then begin SDUURLLabel1.Visible := True; end; end; end; end.
unit uModPOTrader; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, uModApp, System.Generics.Collections, uModOrganization, uModUnit, uModBarang, uModSatuan; type TModPOTraderItem = class; TModPOTrader = class(TModApp) private FPOTraderItems: TObjectList<TModPOTraderItem>; FPOT_DATE: TDatetime; FPOT_DELIVER_DATE: TDatetime; FPOT_DESCRIPTION: string; FPOT_DISC: Double; FPOT_DISC_MEMBER: Double; FPOT_LEAD_TIME: Double; FPOT_NO: string; FPOT_Organization: TModOrganization; FPOT_PPN: Double; FPOT_PPNBM: Double; FPOT_STATUS: string; FPOT_SUBTOTAL: Double; FPOT_TOP: Integer; FPOT_TOTAL: Double; FPOT_UNIT: TModUnit; FPOT_VALID_DATE: TDatetime; function GetPOTraderItems: TObjectList<TModPOTraderItem>; public property POTraderItems: TObjectList<TModPOTraderItem> read GetPOTraderItems write FPOTraderItems; published property POT_DATE: TDatetime read FPOT_DATE write FPOT_DATE; property POT_DELIVER_DATE: TDatetime read FPOT_DELIVER_DATE write FPOT_DELIVER_DATE; property POT_DESCRIPTION: string read FPOT_DESCRIPTION write FPOT_DESCRIPTION; property POT_DISC: Double read FPOT_DISC write FPOT_DISC; property POT_DISC_MEMBER: Double read FPOT_DISC_MEMBER write FPOT_DISC_MEMBER; property POT_LEAD_TIME: Double read FPOT_LEAD_TIME write FPOT_LEAD_TIME; [AttributeOfCode] property POT_NO: string read FPOT_NO write FPOT_NO; [AttributeOfForeign] property POT_Organization: TModOrganization read FPOT_Organization write FPOT_Organization; property POT_PPN: Double read FPOT_PPN write FPOT_PPN; property POT_PPNBM: Double read FPOT_PPNBM write FPOT_PPNBM; property POT_STATUS: string read FPOT_STATUS write FPOT_STATUS; property POT_SUBTOTAL: Double read FPOT_SUBTOTAL write FPOT_SUBTOTAL; property POT_TOP: Integer read FPOT_TOP write FPOT_TOP; property POT_TOTAL: Double read FPOT_TOTAL write FPOT_TOTAL; [AttributeOfForeign] property POT_UNIT: TModUnit read FPOT_UNIT write FPOT_UNIT; property POT_VALID_DATE: TDatetime read FPOT_VALID_DATE write FPOT_VALID_DATE; end; TModPOTraderItem = class(TModApp) private FPOTITEM_BARANG: TModBarang; FPOTITEM_COGS: Double; FPOTITEM_DISC: Double; FPOTITEM_DISCRP: Double; FPOTITEM_NETSALE: Double; FPOTITEM_POTRADER: TModPOTrader; FPOTITEM_PPN: Double; FPOTITEM_PPNRP: Double; FPOTITEM_QTY: Double; FPOTITEM_SATUAN: TModSatuan; FPOTITEM_SELLPRICE: Double; FPOTITEM_TOTAL: Double; public destructor Destroy; override; published [AttributeOfForeign] property POTITEM_BARANG: TModBarang read FPOTITEM_BARANG write FPOTITEM_BARANG; property POTITEM_COGS: Double read FPOTITEM_COGS write FPOTITEM_COGS; property POTITEM_DISC: Double read FPOTITEM_DISC write FPOTITEM_DISC; property POTITEM_DISCRP: Double read FPOTITEM_DISCRP write FPOTITEM_DISCRP; property POTITEM_NETSALE: Double read FPOTITEM_NETSALE write FPOTITEM_NETSALE; [AttributeOfHeader] property POTITEM_POTRADER: TModPOTrader read FPOTITEM_POTRADER write FPOTITEM_POTRADER; property POTITEM_PPN: Double read FPOTITEM_PPN write FPOTITEM_PPN; property POTITEM_PPNRP: Double read FPOTITEM_PPNRP write FPOTITEM_PPNRP; property POTITEM_QTY: Double read FPOTITEM_QTY write FPOTITEM_QTY; [AttributeOfForeign] property POTITEM_SATUAN: TModSatuan read FPOTITEM_SATUAN write FPOTITEM_SATUAN; property POTITEM_SELLPRICE: Double read FPOTITEM_SELLPRICE write FPOTITEM_SELLPRICE; property POTITEM_TOTAL: Double read FPOTITEM_TOTAL write FPOTITEM_TOTAL; end; implementation function TModPOTrader.GetPOTraderItems: TObjectList<TModPOTraderItem>; begin if not Assigned(FPOTraderItems) then FPOTraderItems := TObjectList<TModPOTraderItem>.Create(); Result := FPOTraderItems; end; destructor TModPOTraderItem.Destroy; begin inherited; if FPOTITEM_BARANG <> nil then FreeAndNil(FPOTITEM_BARANG); if FPOTITEM_SATUAN <> nil then FreeAndNil(FPOTITEM_SATUAN); end; Initialization TModPOTrader.RegisterRTTI; TModPOTraderItem.RegisterRTTI; end.
// Conversion code adapted from the freeware package BConvert // Copyright (c) 1999 Branko Dimitrijevic unit roman; interface function ToRoman(Value: cardinal) : String; implementation const br=13; type RomanNumbers=array[0..br-1] of string; DeximalNumbers= array[0..br-1] of Cardinal; const (* I V X L C D M *) Romans: RomanNumbers = ( 'I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M' ); Decimals: DeximalNumbers = (1, 4, 5, 9, 10, 40, 50, 90, 100,400, 500,900, 1000); function ToRoman(Value: cardinal) : String; var index: 0..br-1; a: cardinal; function FindMaximumDecimal(const max: Cardinal): Cardinal; var curr: Cardinal; begin curr := Low(Decimals); while curr < High(Decimals) do begin if Decimals[curr+1] <= max then Inc(curr) else begin if Decimals[curr] <= max then begin result := curr; exit end end end; result := High(Decimals) end; begin a:=Value; result := ''; while a > 0 do begin index := FindMaximumDecimal(a); Dec(a,Decimals[index]); result := result + Romans[index]; end; end; end.
{ Catarinka TCatProgress Copyright (c) 2010-2020 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details A custom progress tracker for when the flow is not so linear and you may skip steps Usage example: p := TCatProgress.Create; // register your stage names p.Add('stage.one'); p.Add('stage.two'); p.Add('stage.three'); p.Add('stage.four'); // sets the current stage p.SetStage('stage.two'); print(IntToStr(p.Pos)); will print 2 print(IntToStr(p.Max)); will print 4 p.free; } unit CatProgress; interface uses Windows, Classes, SysUtils, CatJSON, CatLogger; type TCatProgressOnStageChanged = procedure(const NewStage, LastStage, Duration: string) of object; type TCatProgress = class private fList: TCatJSON; fLog: TStringList; fMax: integer; fPos: integer; fStage: string; fStageStartTime: TDateTime; fStageWatch: TCatStopWatch; fOnStageChange: TCatProgressOnStageChanged; function GetLog:string; public procedure Add(const s: string); procedure Clear; procedure Reset; procedure SetStage(const s: string); constructor Create; destructor Destroy; override; // properties property Current: string read fStage write SetStage; property Log: string read GetLog; property Max: integer read fMax; property Pos: integer read fPos; property OnStageChanged: TCatProgressOnStageChanged read fOnStageChange write fOnStageChange; end; implementation function TCatProgress.GetLog:string; begin result := fLog.text; end; procedure TCatProgress.SetStage(const s: string); var i: integer; desc:string; begin // check if a stage with this name has been added i := fList.GetValue(s, -1); if i <> -1 then begin if (fStage <> EmptyStr) then begin desc := ElapsedTimeToFriendlyTime(fStageWatch.Elapsed); fLog.Add(fStage+': '+desc); if Assigned(fOnStageChange) then fOnStageChange(s, fStage, desc); end; fStageWatch := CatStopWatchNew; fStageStartTime := Now; fStage := s; fPos := i; end; end; procedure TCatProgress.Add(const s: string); begin Inc(fMax); fList.sObject.i[s] := fMax; end; procedure TCatProgress.Reset; begin fPos := 0; fStage := EmptyStr; fLog.Clear; fStageWatch.Stop; end; procedure TCatProgress.Clear; begin fMax := 0; fList.Clear; fLog.Clear; fStageWatch.Stop; end; constructor TCatProgress.Create; begin fMax := 0; fList := TCatJSON.Create; fLog := TStringList.Create; Reset; end; destructor TCatProgress.Destroy; begin fList.Free; FLog.Free; inherited; end; end.
unit FormTesseractOCRImage; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.UITypes, System.Types, System.IOUtils, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Samples.Spin, tesseractocr; type TTesseractOCRImageForm = class(TForm) btnOpenFile: TButton; OpenDialogImage: TOpenDialog; StatusBar: TStatusBar; panTop: TPanel; btnRecognize: TButton; pbImage: TPaintBox; pbRecognizeProgress: TProgressBar; pgTabs: TPageControl; tabImage: TTabSheet; tabText: TTabSheet; tabHOCR: TTabSheet; tabLayout: TTabSheet; btnCancel: TButton; memText: TMemo; memHOCR: TMemo; cbPageSegMode: TComboBox; labAnalysisMode: TLabel; panLayoutLeft: TPanel; pbLayout: TPaintBox; tvLayoutItems: TTreeView; labOrientation: TLabel; labWritingDirect: TLabel; labMeanWordConf: TLabel; gbPage: TGroupBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOpenFileClick(Sender: TObject); procedure btnRecognizeClick(Sender: TObject); procedure pbImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure pbImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pbImagePaint(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); procedure FormResize(Sender: TObject); procedure pbLayoutPaint(Sender: TObject); procedure pbLayoutMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure tvLayoutItemsChange(Sender: TObject; Node: TTreeNode); procedure pbLayoutMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } FSelectingROI: Boolean; FSelectionROI: TRect; FImageROI: TRect; FStretchDrawRect: TRect; FSourceImage: TBitmap; FSourceImageFileName: String; FSelectedLayoutItem: TObject; procedure OnRecognizeBegin(Sender: TObject); procedure OnRecognizeProgress(Sender: TObject; AProgress: Integer; var ACancel: Boolean); procedure OnRecognizeEnd(Sender: TObject; ACanceled: Boolean); public { Public declarations } end; var TesseractOCRImageForm: TTesseractOCRImageForm; implementation uses tesseractocr.pagelayout, tesseractocr.utils, tesseractocr.capi; {$R *.dfm} { TTesseractOCRImageForm } procedure TTesseractOCRImageForm.FormCreate(Sender: TObject); var progressBarStyle: Integer; begin FSelectingROI := False; pbRecognizeProgress.Parent := StatusBar; progressBarStyle := GetWindowLong(pbRecognizeProgress.Handle, GWL_EXSTYLE); progressBarStyle := progressBarStyle and not WS_EX_STATICEDGE; SetWindowLong(pbRecognizeProgress.Handle, GWL_EXSTYLE, progressBarStyle); cbPageSegMode.ItemIndex := Ord(PSM_AUTO_OSD); Tesseract := TTesseractOCR4.Create; Tesseract.OnRecognizeBegin := OnRecognizeBegin; Tesseract.OnRecognizeProgress := OnRecognizeProgress; Tesseract.OnRecognizeEnd := OnRecognizeEnd; if not Tesseract.Initialize('tessdata' + PathDelim, 'eng', oemDefault) then begin MessageDlg('Error loading Tesseract data', mtError, [mbOk], 0); Application.ShowMainForm := False; Application.Terminate; end; end; procedure TTesseractOCRImageForm.FormDestroy(Sender: TObject); begin Tesseract.Free; if Assigned(FSourceImage) then FSourceImage.Free; end; procedure TTesseractOCRImageForm.FormResize(Sender: TObject); begin FSelectionROI.Width := 0; FSelectionROI.Height := 0; FImageROI.Width := 0; FImageROI.Height := 0; end; procedure TTesseractOCRImageForm.pbImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FStretchDrawRect.Contains(Point(X, Y)) then begin FSelectionROI.Left := X; FSelectionROI.Top := Y; FSelectingROI := True; end; end; procedure TTesseractOCRImageForm.pbImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if FSelectingROI and FStretchDrawRect.Contains(Point(X, Y)) then begin FSelectionROI.Right := X; FSelectionROI.Bottom := Y; pbImage.Invalidate; end; end; procedure TTesseractOCRImageForm.pbImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FStretchDrawRect.Contains(Point(X, Y)) then begin FSelectingROI := False; FSelectionROI.Right := X; FSelectionROI.Bottom := Y; FSelectionROI.NormalizeRect; FImageROI.Create(FSelectionROI, False); FImageROI.Offset(-FStretchDrawRect.Left, -FStretchDrawRect.Top); FImageROI.Left := Round(FImageROI.Left * (FSourceImage.Width / FStretchDrawRect.Width)); FImageROI.Top := Round(FImageROI.Top * (FSourceImage.Height / FStretchDrawRect.Height)); FImageROI.Right := Round(FImageROI.Right * (FSourceImage.Width / FStretchDrawRect.Width)); FImageROI.Bottom := Round(FImageROI.Bottom * (FSourceImage.Height / FStretchDrawRect.Height)); pbImage.Invalidate; end; end; procedure TTesseractOCRImageForm.pbImagePaint(Sender: TObject); function ProportionalResize(AX, AY, AOrgWidth, AOrgHeight, AMaxWidth, AMaxHeight: Integer): TRect; var w, h: Single; x, y: Single; begin x := AX; y := AY; if (AOrgWidth > AOrgHeight) then begin w := AMaxWidth; h := (AMaxWidth * AOrgHeight) / AOrgWidth; if (h > AMaxHeight) then begin w := (AMaxHeight * AOrgWidth) / AOrgHeight; h := AMaxHeight; end; end else begin w := (AMaxHeight * AOrgWidth) / AOrgHeight; h := AMaxHeight; if (w > AMaxWidth) then begin w := AMaxWidth; h := (AMaxWidth * AOrgHeight) / AOrgWidth; end; end; y := y + (Abs(AMaxHeight - h) / 2); x := x + (Abs(AMaxWidth - w) / 2); Result := Rect(Trunc(x), Trunc(y), Trunc(w+x), Trunc(h+y)); end; begin if not Assigned(FSourceImage) then Exit; FStretchDrawRect := ProportionalResize(0, 0, FSourceImage.Width, FSourceImage.Height, pbImage.BoundsRect.Width, pbImage.BoundsRect.Height); pbImage.Canvas.StretchDraw(FStretchDrawRect, FSourceImage); pbImage.Canvas.Brush.Style := bsClear; pbImage.Canvas.Pen.Style := psDash; pbImage.Canvas.Pen.Color := clRed; pbImage.Canvas.Rectangle(FSelectionROI); end; procedure TTesseractOCRImageForm.pbLayoutMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var node: TTreeNode; begin node := tvLayoutItems.Items[0]; while node <> nil do begin if node.Data = FSelectedLayoutItem then begin tvLayoutItems.Select(node); Break; end; node := node.GetNext; end; end; procedure TTesseractOCRImageForm.pbLayoutMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var para: TTesseractParagraph; textLine: TTesseractTextLine; word: TTesseractWord; begin if not Assigned(FSourceImage) then Exit; if not Tesseract.PageLayout.DataReady then Exit; for word in Tesseract.PageLayout.Words do begin if word.BoundingRect.Contains(Point(X, Y)) then begin FSelectedLayoutItem := word; pbLayout.Invalidate; Exit; end; end; for textLine in Tesseract.PageLayout.TextLines do begin if textLine.BoundingRect.Contains(Point(X, Y)) then begin FSelectedLayoutItem := textLine; pbLayout.Invalidate; Exit; end; end; for para in Tesseract.PageLayout.Paragraphs do begin if para.BoundingRect.Contains(Point(X, Y)) then begin FSelectedLayoutItem := para; pbLayout.Invalidate; Exit; end; end; end; procedure TTesseractOCRImageForm.pbLayoutPaint(Sender: TObject); procedure DrawRectAndTextAbove(ACanvas: TCanvas; AText: String; AColor: TColor; ARect: TRect); var textSize: TSize; begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Color := AColor; ACanvas.Rectangle(ARect); ACanvas.Brush.Color := clGray; ACanvas.Pen.Color := clGray; ACanvas.Brush.Style := bsSolid; textSize := ACanvas.TextExtent(AText); ACanvas.Rectangle(Rect(ARect.Left, ARect.Top - textSize.Height - 4, ARect.Left + textSize.Width + 4, ARect.Top)); ACanvas.TextOut(ARect.Left + 2, ARect.Top - textSize.Height - 2, AText); end; var block: TTesseractBlock; para: TTesseractParagraph; textLine: TTesseractTextLine; word: TTesseractWord; symbol: TTesseractSymbol; text: String; begin if not Assigned(FSourceImage) then Exit; if not Tesseract.PageLayout.DataReady then Exit; pbLayout.Canvas.Brush.Color := clWhite; pbLayout.Canvas.FillRect(pbLayout.ClientRect); pbLayout.Canvas.Draw(0, 0, FSourceImage); pbLayout.Canvas.Pen.Style := psSolid; pbLayout.Canvas.Font.Size := 10; pbLayout.Canvas.Font.Name := 'Verdana'; pbLayout.Canvas.Font.Color := clWhite; if Assigned(FSelectedLayoutItem) then begin if FSelectedLayoutItem is TTesseractBlock then begin block := TTesseractBlock(FSelectedLayoutItem); text := 'Block (' + BlockTypeToString(block.BlockType) + ')'; DrawRectAndTextAbove(pbLayout.Canvas, text, clBlack, block.BoundingRect); end else if FSelectedLayoutItem is TTesseractParagraph then begin para := TTesseractParagraph(FSelectedLayoutItem); text := 'Paragraph (Justification: ' + ParagraphJustificationToString(para.Justification) + ')'; DrawRectAndTextAbove(pbLayout.Canvas, text, clGreen, para.BoundingRect); end else if FSelectedLayoutItem is TTesseractTextLine then begin textLine := TTesseractTextLine(FSelectedLayoutItem); text := 'Text line'; DrawRectAndTextAbove(pbLayout.Canvas, text, clBlue, textLine.BoundingRect); end else if FSelectedLayoutItem is TTesseractWord then begin word := TTesseractWord(FSelectedLayoutItem); text := Format('%s (Confidence: %.2f%%, Language: %s, In dictionary: %s)', [word.Text, word.Confidence, word.Language, BoolToStr(word.InDictionary, True)]); DrawRectAndTextAbove(pbLayout.Canvas, text, clRed, word.BoundingRect); end else if FSelectedLayoutItem is TTesseractSymbol then begin symbol := TTesseractSymbol(FSelectedLayoutItem); text := Format('%s (Confidence: %.2f%%)', [symbol.Character, symbol.Confidence]); DrawRectAndTextAbove(pbLayout.Canvas, text, clRed, symbol.BoundingRect); end; end; end; procedure TTesseractOCRImageForm.StatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); begin if (Panel.Index = 0) then begin pbRecognizeProgress.Top := Rect.Top; pbRecognizeProgress.Left := Rect.Left; pbRecognizeProgress.Width := Rect.Right - Rect.Left; pbRecognizeProgress.Height := Rect.Bottom - Rect.Top; end; end; procedure TTesseractOCRImageForm.tvLayoutItemsChange(Sender: TObject; Node: TTreeNode); begin FSelectedLayoutItem := TObject(tvLayoutItems.Selected.Data); pbLayout.Invalidate; end; procedure TTesseractOCRImageForm.btnOpenFileClick(Sender: TObject); begin if Tesseract.Busy then Exit; if OpenDialogImage.Execute then begin if Assigned(FSourceImage) then FreeAndNil(FSourceImage); if Tesseract.SetImage(OpenDialogImage.FileName) then begin FSourceImageFileName := OpenDialogImage.FileName; StatusBar.Panels[1].Text := FSourceImageFileName; FSourceImage := Tesseract.GetSourceImageBMP; FSelectionROI := Rect(0, 0, 0, 0); btnRecognize.Enabled := True; pgTabs.ActivePage := tabImage; pbImage.Invalidate; end; end; end; procedure TTesseractOCRImageForm.btnRecognizeClick(Sender: TObject); begin if not Assigned(FSourceImage) then Exit; if (FImageROI.Width > 0) and (FImageROI.Height > 0) then begin Tesseract.SetRectangle(FImageROI); end else Tesseract.SetRectangle(Rect(0, 0, FSourceImage.Width, FSourceImage.Height)); Tesseract.PageSegMode := TessPageSegMode(cbPageSegMode.ItemIndex); Tesseract.Recognize; end; procedure TTesseractOCRImageForm.btnCancelClick(Sender: TObject); begin Tesseract.CancelRecognize; end; procedure TTesseractOCRImageForm.OnRecognizeBegin(Sender: TObject); begin memText.Clear; memHOCR.Clear; tvLayoutItems.Items.Clear; FSelectedLayoutItem := nil; btnCancel.Enabled := True; btnRecognize.Enabled := False; end; procedure TTesseractOCRImageForm.OnRecognizeProgress(Sender: TObject; AProgress: Integer; var ACancel: Boolean); begin pbRecognizeProgress.Position := AProgress; end; procedure TTesseractOCRImageForm.OnRecognizeEnd(Sender: TObject; ACanceled: Boolean); var symbol: TTesseractSymbol; word: TTesseractWord; textLine: TTesseractTextLine; para: TTesseractParagraph; block: TTesseractBlock; blockTree, paraTree, textLineTree, wordTree: TTreeNode; begin btnCancel.Enabled := False; btnRecognize.Enabled := True; if not ACanceled then begin pbRecognizeProgress.Position := 100; memText.Text := Tesseract.UTF8Text; memHOCR.Text := Tesseract.HOCRText; labOrientation.Caption := Format('Orientation: %s', [PageOrientationToString(Tesseract.PageLayout.Orientation)]); labWritingDirect.Caption := Format('Writing direction: %s', [WritingDirectionToString(Tesseract.PageLayout.WritingDirection)]); labMeanWordConf.Caption := Format('Mean word confidence: %d%%', [Tesseract.PageLayout.MeanWordConfidence]); pbLayout.Invalidate; tvLayoutItems.Items.Clear; for block in Tesseract.PageLayout.Blocks do begin blockTree := tvLayoutItems.Items.AddObject(nil, 'Block (' + BlockTypeToString(block.BlockType) + ')', block); for para in block.Paragraphs do begin paraTree := tvLayoutItems.Items.AddChildObject(blockTree, 'Paragraph', para); for textLine in para.TextLines do begin textLineTree := tvLayoutItems.Items.AddChildObject(paraTree, 'Text Line', textLine); for word in textLine.Words do begin wordTree := tvLayoutItems.Items.AddChildObject(textLineTree, word.Text, word); for symbol in word.Symbols do begin tvLayoutItems.Items.AddChildObject(wordTree, symbol.Character, symbol); end; end; end; end; end; if pgTabs.ActivePage = tabImage then pgTabs.ActivePage := tabText; end else pbRecognizeProgress.Position := 0; end; end.
namespace CircularSlider; interface uses UIKit; type [IBObject] RootViewController = public class(UIViewController) private public method init: id; override; property preferredStatusBarStyle: UIStatusBarStyle read UIStatusBarStyle.UIStatusBarStyleLightContent; override; method viewDidLoad; override; method didReceiveMemoryWarning; override; [IBAction] method newValue(aSlider: TBCircularSlider); end; implementation method RootViewController.init: id; begin self := inherited initWithNibName('RootViewController') bundle(nil); if assigned(self) then begin // Custom initialization end; result := self; end; method RootViewController.viewDidLoad; begin inherited; view.backgroundColor := UIColor.colorWithRed(0.1) green(0.1) blue(0.1) alpha(1); //Create the Circular Slider var slider := new TBCircularSlider withFrame(CGRectMake(0, 60, TBCircularSlider.TB_SLIDER_SIZE, TBCircularSlider.TB_SLIDER_SIZE)); //Define Target-Action behaviour slider.addTarget(self) action(selector(newValue:)) forControlEvents(UIControlEvents.UIControlEventValueChanged); view.addSubview(slider); end; method RootViewController.didReceiveMemoryWarning; begin inherited didReceiveMemoryWarning; // Dispose of any resources that can be recreated. end; method RootViewController.newValue(aSlider: TBCircularSlider); begin // handle the slider event end; end.
unit UMixer; interface uses UFlow, URegularFunctions, UConst; type Mixer = class function calculate(flows: array of Flow): Flow; end; implementation function Mixer.calculate(flows: array of Flow): Flow; begin var mass_flow_rate := 0.0; var mass_fractions := ArrFill(flows[0].mass_fractions.Length, 0.0); var temperature := 0.0; foreach var flow in flows do mass_flow_rate += flow.mass_flow_rate; foreach var i in mass_fractions.Indices do begin foreach var j in flows.Indices do mass_fractions[i] += flows[j].mass_fractions[i] * flows[j].mass_flow_rate; mass_fractions[i] /= mass_flow_rate end; var cp := 0.0; foreach var i in flows.Indices do cp += flows[i].mass_flow_rate * flows[i].heat_capacity / mass_flow_rate; var s := 0.0; foreach var i in flows.Indices do s += flows[i].mass_flow_rate * flows[i].heat_capacity * flows[i].temperature; temperature := s / mass_flow_rate / cp; result := new Flow(mass_flow_rate, mass_fractions, temperature) end; end.
unit CINIFilesData; //------------------------------------------------------------------------------ // модуль описания ini-файлов //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ interface const //------------------------------------------------------------------------------ //! расширение файла конфигурации //------------------------------------------------------------------------------ CIniDefExtDotted = '.ini'; //------------------------------------------------------------------------------ //! расширение файла стандартных watermark'ов //------------------------------------------------------------------------------ CWMDefExtDotted = '.wm'; //------------------------------------------------------------------------------ //! расширение файла индексов kafka //------------------------------------------------------------------------------ CKafkaIdxDefExtDotted = '.kafka.offset'; //------------------------------------------------------------------------------ //! секции файла конфигурации //------------------------------------------------------------------------------ CIniMainParamsSection = 'Main Params'; CIniControlSection = 'Control'; CIniMySqlSection = 'MySQL'; CIniKafkaSection = 'Kafka'; CIniKafkaOffsetSection = 'Kafka'; CIniStatSection = 'stat'; CIniKafkaSectionDefName = 'config'; //------------------------------------------------------------------------------ //! список параметров //------------------------------------------------------------------------------ CIniDBAddr = 'host'; CIniDBPort = 'port'; CIniDBLogin = 'login'; CIniDBPass = 'password'; CIniDBName = 'database'; CIniDBProtocol = 'protocol'; CIniKafkaBootstrap = 'bootstrap'; CIniDBUpdate = 'FromDBUpdateInterval'; CIniStatPPS = 'PointPerSec'; CIniKafkaOffset = 'offset'; CIniKafkaGroup = 'group'; CIniKafkaTopic = 'topic'; CIniKafkaBackupPath = 'backup'; CIniKafkaBackupTimeout = 'backuptimeout'; CIniKafkaTopicEnabled = 'enabled'; //------------------------------------------------------------------------------ //! значения параметров по умолчанию //------------------------------------------------------------------------------ CIniDBAddrDef = '127.0.0.1'; CIniDBPortDef = 3306; CIniDBLoginDef = 'root'; CIniDBPassDef = 'password'; CIniDBNameDef = 'saas'; CIniDBProtocolDef = 'mysql-5'; CIniKafkaBootstrapDef = '127.0.0.1'; CIniDBUpdateDef = 30; //------------------------------------------------------------------------------ implementation end.
//------------------------------------------------------------------------------ //Globals UNIT //------------------------------------------------------------------------------ // // // Changes - // December 22nd, 2006 - RaX - Created Header. // [2007/03/28] CR - Cleaned up uses clauses, using Icarus as a guide. // //------------------------------------------------------------------------------ unit Globals; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {RTL/VCL} //none {Project} Packets, Terminal {3rd Party} //none ; function InitGlobals : boolean; procedure DestroyGlobals; procedure TerminateApplication; function GetMD5(const Input : string) : string; function MakeRNDString(Count: Integer): string; function ConvertMySQLTime(DateString: string) : TDateTime; function IncSecond(const AValue: TDateTime; const ANumberOfSeconds: Int64): TDateTime; function IncMinute(const AValue: TDateTime; const ANumberOfMinutes: Int64): TDateTime; //------------------------------------------------------------------------------ // Global Variables //------------------------------------------------------------------------------ var Console : TConsole; AppPath : String; ExeName : String; LastAccountID : Integer; //Our Global Packet Database PacketDB : TPacketDB; //------------------------------------------------------------------------------ const //message types MS_INFO = 0; MS_NOTICE = 1; MS_WARNING = 2; MS_ERROR = 3; MS_DEBUG = 4; MS_ALERT = 5; implementation uses {RTL/VCL} DateUtils, SysUtils, WinLinux, {Project} Main, {3rd Party} IdHashMessageDigest ; Const HoursPerDay = 24; MinsPerHour = 60; MinsPerDay = HoursPerDay * MinsPerHour; //------------------------------------------------------------------------------ //GetMD5 FUNCTION //------------------------------------------------------------------------------ // What it does- // Creates a MD5 Hash from a string. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function GetMD5(const Input : string) : String; var Hash : TIdHashMessageDigest5; begin Hash := TIdHashMessageDigest5.Create; {$IFDEF FPC} Result := Hash.HashStringAsHex(Input); {$ELSE} Result := Hash.AsHex(Hash.HashValue(Input)); {$ENDIF} Hash.Free; end;{GetMD5} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //InitGlobals PROCEDURE //------------------------------------------------------------------------------ // What it does- // Initializes our global variables. // // Changes - // December 22nd, 2006 - RaX - Created Header. // January 20th, 2007 - Tsusai - Now a function that returns success of // Database connecting and packet_db // June 28th, 2008 - Tsusai - Inits the Packet Database object, and loads // //------------------------------------------------------------------------------ function InitGlobals : boolean; begin PacketDB := TPacketDB.Create; Result := PacketDB.Load; end; {InitGlobals} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //DestroyGlobals PROCEDURE //------------------------------------------------------------------------------ // What it does- // Free's up our Globals variables. // // Changes - // December 22nd, 2006 - RaX - Created Header. // June 28th, 2008 - Tsusai - Inits the Packet Database object, and loads // //------------------------------------------------------------------------------ procedure DestroyGlobals; begin PacketDB.Unload; PacketDB.Free; end;{DestroyGlobals} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //TerminateApplication PROCEDURE //------------------------------------------------------------------------------ // What it does- // Kills our main process and free's it. // // Changes - // December 22nd, 2006 - RaX - Created Header. // [2007/06/21] Tsusai - Replaced KillProcess with Halt. Halt does the job // better. // //------------------------------------------------------------------------------ procedure TerminateApplication; begin if MainProc.Loaded then begin //remove the hooks for Ctrl-C, etc KillTerminationCapturing; //Start shutting down the server MainProc.Shutdown; FreeAndNil(MainProc); //Free up console handler. Console.Free; //Exit the program PROPERYLY Halt; end else begin Console.Message('Please wait to shutdown helios until after it has finished starting/stopping', 'System', MS_ALERT); end; end;{TerminateApplication} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //MakeRNDString FUNCTION //------------------------------------------------------------------------------ // What it does- // Makes a random string of length Count. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function MakeRNDString(Count: Integer): string; const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/'; var i, x: integer; begin Result := ''; for i := 1 to Count do begin x := Length(chars) - Random(Length(chars)); Result := Result + chars[x]; end; end;{MakeRNDString} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //ConvertMySQLTime FUNCTION //------------------------------------------------------------------------------ // What it does- // Converts a MySQL Formatted Time into a TDateTime. // // Changes - // December 22nd, 2006 - RaX - Created Header. // //------------------------------------------------------------------------------ function ConvertMySQLTime(DateString: string) : TDateTime; var Year, Month, Day, Hour, Min, Sec : word; Code : integer; begin Result := 2; //01 Jan 1900 if Length(DateString) = 19 then begin if not (DateString = '0000-00-00 00:00:00') then begin Val(copy(DateString, 1, 4), Year, Code); Val(copy(DateString, 6, 2), Month, Code); Val(copy(DateString, 9, 2), Day, Code); Val(copy(DateString, 12, 2), Hour, Code); Val(copy(DateString, 15, 2), Min, Code); Val(copy(DateString, 18, 2), Sec, Code); Result := EncodeDateTime(Year, Month, Day, Hour, Min, Sec, 0); end; end; end;{ConvertMySQLTime} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IncSecond FUNCTION //------------------------------------------------------------------------------ // What it does- // Adds a second to a TDateTime type. // // Changes - // January 4th, 2007 - RaX - Created Header. // //------------------------------------------------------------------------------ function IncSecond(const AValue: TDateTime; const ANumberOfSeconds: Int64): TDateTime; begin Result := ((AValue * SecsPerDay) + ANumberOfSeconds) / SecsPerDay; end;{IncSecond} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //IncMinute FUNCTION //------------------------------------------------------------------------------ // What it does- // Adds a minute to a TDateTime type. // // Changes - // January 4th, 2007 - RaX - Created Header. // March 13th, 2007 - Aeomin - Fix type. // //------------------------------------------------------------------------------ function IncMinute(const AValue: TDateTime; const ANumberOfMinutes: Int64): TDateTime; begin Result := ((AValue * MinsPerDay) + ANumberOfMinutes) / MinsPerDay; end;{IncMinute} //------------------------------------------------------------------------------ end.
unit UnitViewer; // ------------------------------------------------------------------------------ // // SVG Control 2.0 // Copyright (c) 2015 Bruno Verhue // // ------------------------------------------------------------------------------ // [The "BSD licence"] // // Copyright (c) 2013 Bruno Verhue // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. 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. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. // ----------------------------------------------------------------------------- // // Demo application "SVG viewer" // // Demonstrates: // // - Loading and parsing SVG documents // - Copying SVG control // - Finding rendering elements and changing properties // When loading the "animatied clock", it will have some interactive // functionality: it will be set and updated to the current time, and you // can move the clock hands by mouse. // // ----------------------------------------------------------------------------- interface uses Winapi.Windows, Winapi.Messages, System.Types, System.SysUtils, System.Variants, System.Classes, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ToolWin, Vcl.ComCtrls, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.StdCtrls, Vcl.ActnCtrls, Vcl.ExtCtrls, Vcl.ImgList, Vcl.Clipbrd, Vcl.ExtDlgs, BVE.ViewerCore.Vcl, BVE.SVG2ImageList.Vcl; type TForm1 = class(TSVGViewerForm) ScrollBox1: TScrollBox; ActionManager1: TActionManager; aOpen: TAction; aEdit: TAction; ActionToolBar1: TActionToolBar; aCopy: TAction; SVG2ImageList1: TSVG2ImageList; aNew: TAction; aPaste: TAction; aCopyDirect: TAction; aAbout: TAction; aEnableFilters: TAction; aRemove: TAction; aAutoViewBox: TAction; StatusBar1: TStatusBar; aExport: TAction; OpenPictureDialog1: TOpenPictureDialog; SavePictureDialog1: TSavePictureDialog; SVG2LinkedImageList1: TSVG2LinkedImageList; SVG2LinkedImageList2: TSVG2LinkedImageList; procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin ConnectControls( aOpen, aEdit, aCopy, aNew, aPaste, aCopyDirect, aAbout, aEnableFilters, aRemove, aAutoViewBox, aExport, SVG2ImageList1, OpenPictureDialog1, Scrollbox1, Statusbar1); end; end.
unit Frame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, Buttons, LCLType, ColorBox, Dialogs, TAGraph, TAFuncSeries, ParseMath, Graphics, ExtCtrls, Math; type { TFrameFunc } TFrameFunc = class(TFrame) ColorButton1: TColorButton; Edit1: TEdit; Panel1: TPanel; procedure ColorButton1ColorChanged(Sender: TObject); procedure Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FrameClick(Sender: TObject); procedure CalculateFunc(const AX: Double; out AY: Double); private Parse: TParseMath; function f( x : Real ) : Real; public FuncColor: TColor; FuncSeries: TFuncSeries; end; implementation uses main; {$R *.lfm} { TFrameFunc } function TFrameFunc.f( x : Real ) : Real; begin Parse.NewValue('x',x); Result := Parse.Evaluate(); end; procedure TFrameFunc.CalculateFunc(const AX: Double; out AY: Double); begin AY := f(AX); end; procedure TFrameFunc.Edit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var limit : String; begin if (Key <> VK_RETURN) or (Edit1.Caption = '') then exit; with Form1 do begin if not Assigned( FuncSeries ) then begin FuncSeries:= TFuncSeries.Create( Chart1 ); Chart1.AddSeries( FuncSeries ); end; FuncSeries.Pen.color := FuncColor; FuncSeries.Pen.width := 2; FuncSeries.Active := False; Parse := TParseMath.create; Parse.Expression := Edit1.Text; limit := Copy(Parse.Expression,Pos('l',Parse.Expression),2); if limit <> 'ln' then limit := Copy(Parse.Expression,Pos('s',Parse.Expression),4); if (limit = 'ln') or (limit = 'sqrt') then begin with FuncSeries.DomainExclusions do begin AddRange(NegInfinity,0); end; end; Parse.AddVariable('x',0); Parse.AddVariable('e',2.7182818284); FuncSeries.onCalculate := @CalculateFunc; FuncSeries.Tag := Form1.MaxPos; FuncSeries.Active := True; if Self.Tag = Form1.MaxPos then Form1.AddGraphic; end; end; procedure TFrameFunc.FrameClick(Sender: TObject); begin Form1.ActualPos := Self.Tag; Panel1.Color:= clGray; end; procedure TFrameFunc.ColorButton1ColorChanged(Sender: TObject); begin FuncColor:= ColorButton1.ButtonColor; if Assigned( FuncSeries ) then FuncSeries.Pen.Color:= FuncColor; end; end.
{ Purpose: - Global find and replace keywords - Add keywords where record matches criteria - Delete keywords where record matches criteria - Remove duplicate keywords Author: fireundubh <fireundubh@gmail.com> Version: 0.1 } unit UserScript; uses dubhFunctions; var bReplace, bAdd, bDelete, bNoInput: Boolean; sQueryPath: String; lsKeywordsToReplace, lsKeywordsToAdd, lsKeywordsToDelete: TStringList; function Initialize: Integer; var sPathReplace, sPathAdd, sPathDelete: String; begin sPathReplace := ScriptsPath + 'Keymaster\lsKeywordsToReplace.csv'; sPathAdd := ScriptsPath + 'Keymaster\lsKeywordsToAdd.csv'; sPathDelete := ScriptsPath + 'Keymaster\lsKeywordsToDelete.csv'; // create list for replacing keywords lsKeywordsToReplace := TStringList.Create; lsKeywordsToReplace.NameValueSeparator := '='; lsKeywordsToReplace.Duplicates := dupAccept; lsKeywordsToReplace.Sorted := False; bReplace := True; if FileExists(sPathReplace) then lsKeywordsToReplace.LoadFromFile(sPathReplace) else bReplace := False; // create list for adding keywords lsKeywordsToAdd := TStringList.Create; lsKeywordsToAdd.NameValueSeparator := '+'; lsKeywordsToAdd.Duplicates := dupAccept; lsKeywordsToAdd.Sorted := False; bAdd := True; if FileExists(sPathAdd) then lsKeywordsToAdd.LoadFromFile(sPathAdd) else bAdd := False; // create list for deleting keywords lsKeywordsToDelete := TStringList.Create; lsKeywordsToDelete.NameValueSeparator := '-'; lsKeywordsToDelete.Duplicates := dupAccept; lsKeywordsToDelete.Sorted := False; bDelete := True; if FileExists(sPathDelete) then lsKeywordsToDelete.LoadFromFile(sPathDelete) else bDelete := False; // clear messages tab ClearMessages(); // prompt for path if not InputQuery('Keywords Path/Signature', 'Keywords Path/Signature:', sQueryPath) then begin bNoInput := True; exit; end; Log(#13#10 + '-------------------------------------------------------------------------------'); Log('Keymaster by fireundubh <fireundubh@gmail.com>'); Log('-------------------------------------------------------------------------------' + #13#10); Log('Processing... ' + sQueryPath + #13#10); end; function Process(e: IInterface): Integer; var aParent: IInterface; i: Integer; begin if bNoInput then exit; Log(SmallNameEx(e)); aParent := GetElement(e, sQueryPath); if bReplace and (lsKeywordsToReplace.Count > 0) then for i := 0 to Pred(ElementCount(aParent)) do ReplaceKeywordWithNameValuePair(ElementByIndex(aParent, i), lsKeywordsToReplace, True); if bAdd and (lsKeywordsToAdd.Count > 0) then AddKeywordWithNameValuePair(aParent, lsKeywordsToAdd, True); if bDelete and (lsKeywordsToDelete.Count > 0) then for i := 0 to Pred(ElementCount(aParent)) do DeleteKeywordWithNameValuePair(ElementByIndex(aParent, i), lsKeywordsToDelete, True); RemoveDuplicateKeywords(aParent, sQueryPath); Log(''); end; function Finalize: Integer; begin lsKeywordsToReplace.Free; lsKeywordsToAdd.Free; lsKeywordsToDelete.Free; end; // ---------------------------------------------------------------------------------------------------------------------------- // lsKeywordsToReplace.csv Structure: name=value // - Name: Form ID of keyword to find // - Value: Form ID of keyword to replace // ---------------------------------------------------------------------------------------------------------------------------- // NOTE: This function is a global find and replace. // ---------------------------------------------------------------------------------------------------------------------------- procedure ReplaceKeywordWithNameValuePair(e: IInterface; lsHaystack: TStringList; bCaseSensitive: Boolean); var i: Integer; begin for i := 0 to lsHaystack.Count - 1 do if HasString(HexFormID(LinksTo(e)), lsHaystack.Names[i], bCaseSensitive) then begin SetEditValue(e, lsHaystack.Values[lsHaystack.Names[i]]); Log(' -- Replaced keyword [KYWD:' + lsHaystack.Names[i] + '] with [KYWD:' + lsHaystack.Values[lsHaystack.Names[i]] + ']'); end; end; // ---------------------------------------------------------------------------------------------------------------------------- // lsKeywordsToAdd.csv Structure: name+value // - Name: Form ID of record to modify // - Value: Form ID of keyword to add // ---------------------------------------------------------------------------------------------------------------------------- // NOTE: This function will check whether the current record should be modified. // ---------------------------------------------------------------------------------------------------------------------------- procedure AddKeywordWithNameValuePair(e: IInterface; lsHaystack: TStringList; bCaseSensitive: Boolean); var i: Integer; aKeyword: IInterface; begin for i := 0 to lsHaystack.Count - 1 do begin if HasString(HexFormID(ContainingMainRecord(e)), lsHaystack.Names[i], bCaseSensitive) then begin aKeyword := ElementAssign(e, HighInteger, nil, False); SetEditValue(aKeyword, lsHaystack.Values[lsHaystack.Names[i]]); Log(' -- Added keyword: [KYWD:' + lsHaystack.Values[lsHaystack.Names[i]] + ']'); end; end; end; // ---------------------------------------------------------------------------------------------------------------------------- // lsKeywordsToDelete.csv Structure: name-value // - Name: Form ID of record to modify // - Value: Form ID of record to delete // ---------------------------------------------------------------------------------------------------------------------------- // NOTE: This function will check whether the current record should be modified. // ---------------------------------------------------------------------------------------------------------------------------- procedure DeleteKeywordWithNameValuePair(e: IInterface; lsHaystack: TStringList; bCaseSensitive: Boolean); var i: Integer; begin for i := 0 to lsHaystack.Count - 1 do if HasString(HexFormID(ContainingMainRecord(e)), lsHaystack.Names[i], bCaseSensitive) then if HasString(HexFormID(LinksTo(e)), lsHaystack.Values[lsHaystack.Names[i]], bCaseSensitive) then begin Remove(e); Log(' -- Deleted keyword: [KYWD:' + lsHaystack.Values[lsHaystack.Names[i]] + ']'); end; end; procedure RemoveDuplicateKeywords(e: IInterface; sParent: String); var i, iKeywordCount: Integer; aMaster, aParent, aChild: IInterface; lsKeywords: TStringList; begin lsKeywords := TStringList.Create; lsKeywords.Duplicates := dupIgnore; lsKeywords.Sorted := True; iKeywordCount := ElementCount(e); for i := 0 to Pred(iKeywordCount) do lsKeywords.Add(HexFormID(LinksTo(ElementByIndex(e, i)))); iKeywordCount := iKeywordCount - lsKeywords.Count; if iKeywordCount > 0 then begin if iKeywordCount > 1 then Log(' -- Removed ' + IntToStr(iKeywordCount) + ' duplicates.') else Log(' -- Removed ' + IntToStr(iKeywordCount) + ' duplicate.'); aMaster := ContainingMainRecord(e); Remove(e); aParent := GetElement(aMaster, sParent); if not Assigned(aParent) then aParent := AddElementByString(aMaster, sParent); for i := 0 to lsKeywords.Count - 1 do begin aChild := ElementAssign(aParent, HighInteger, nil, False); SetEditValue(aChild, lsKeywords[i]); end; end; lsKeywords.Free; end; end.