text
stringlengths
14
6.51M
unit TBGZeosDriver.Model.DataSet; interface uses TBGConnection.Model.DataSet.Interfaces, Data.DB, TBGConnection.Model.DataSet.Observer, ZDataset; Type TConnectionModelZeosDataSet = class(TInterfacedObject, iDataSet, ICacheDataSetObserver) private FDataSet : TZQuery; FObserver : ICacheDataSetSubject; FGUUID : String; FSQL : String; public constructor Create(Observer : ICacheDataSetSubject); destructor Destroy; override; class function New(Observer : ICacheDataSetSubject) : iDataSet; function DataSet : TDataSet; overload; function DataSet (Value : TDataSet) : iDataSet; overload; function GUUID : String; function SQL : String; overload; function SQL (Value : String) : iDataSet; overload; function Update(Value : String) : ICacheDataSetObserver; end; implementation uses System.SysUtils; { TConnectionModelZeosDataSet } constructor TConnectionModelZeosDataSet.Create(Observer : ICacheDataSetSubject); begin FDataSet := TZQuery.Create(nil); FGUUID := TGUID.NewGuid.ToString; FObserver := Observer; FObserver.AddObserver(Self); end; function TConnectionModelZeosDataSet.DataSet: TDataSet; begin Result := FDataSet; end; function TConnectionModelZeosDataSet.DataSet(Value: TDataSet): iDataSet; begin Result := Self; if Assigned(FDataSet) then FreeAndNil(FDataSet); FDataSet := TZQuery(Value); end; destructor TConnectionModelZeosDataSet.Destroy; begin FObserver.RemoveObserver(Self); FreeAndNil(FDataSet); inherited; end; function TConnectionModelZeosDataSet.GUUID: String; begin Result := FGUUID; end; class function TConnectionModelZeosDataSet.New(Observer : ICacheDataSetSubject) : iDataSet; begin Result := Self.Create(Observer); end; function TConnectionModelZeosDataSet.SQL: String; begin Result := FSQL; end; function TConnectionModelZeosDataSet.SQL(Value: String): iDataSet; begin Result := Self; FSQL := Value; end; function TConnectionModelZeosDataSet.Update(Value: String): ICacheDataSetObserver; begin Result := Self; if FGUUID <> Value then if FDataSet.State in [dsBrowse] then FDataSet.Refresh; end; end.
PROGRAM WorkWithQueryString(INPUT, OUTPUT); USES DOS; FUNCTION GetQueryStringParameter(Key: STRING): STRING; VAR Query, Param, Cropped: STRING; Position, AmperPosition: INTEGER; BEGIN {PrintHello} Query := GetEnv('QUERY_STRING'); Position := Pos(Key, Query); Cropped := Copy(Query, Position, Length(Query) - Position + 1); AmperPosition := Pos('&', Cropped); IF (Position <> 0) THEN BEGIN IF (AmperPosition = 0) THEN BEGIN Param := Copy(Cropped, Length(Key) + 2, Length(Cropped) - Length(Key)); END ELSE BEGIN Param := Copy(Cropped, Length(Key) + 2, AmperPosition - Length(Key) - 2); END; END; GetQueryStringParameter := Param; END; {PrintHello} BEGIN {WorkWithQueryString} WRITELN('Content-Type: text/plain'); WRITELN; WRITELN('First Name: ', GetQueryStringParameter('first_name')); WRITELN('Last Name: ', GetQueryStringParameter('last_name')); WRITELN('Age: ', GetQueryStringParameter('age')) END. {WorkWithQueryString}
{----------------------------------------------------------------------------- Unit Name: RbSplitter Purpose: gradient animated splitter Author/Copyright: NathanaŽl VERON - r.b.a.g@free.fr - http://r.b.a.g.free.fr Feel free to modify and improve source code, mail me (r.b.a.g@free.fr) if you make any big fix or improvement that can be included in the next versions. If you use the RbControls in your project please mention it or make a link to my website. =============================================== /* 04/10/2003 */ Creation -----------------------------------------------------------------------------} unit RbSplitter; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, ExtCtrls, RbDrawCore, Buttons, Forms; type TRbSplitter = class(TSplitter) private FGrBitmap: TBitmap; FGrMouseOver: TBitmap; FDrawStates: TDrawStates; FGradientType : TGradientType; FGripAlign: TGripAlign; FOverBlendPercent: integer; FColors: TRbSplitterColors; FFadeSpeed: TFadeSpeed; FShowGrip: boolean; FOnFade : TNotifyEvent; Handle : HWND; FRbStyleManager: TRbStyleManager; FDrawAll : boolean; FVAbout : string; procedure DrawPicksBt(ACanvas: TCanvas; BLeft, BTop : integer); procedure SetGradientType(const Value: TGradientType); procedure SetGripAlign(const Value: TGripAlign); procedure UpdateTimer; procedure SetFadeSpeed(const Value: TFadeSpeed); procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure SetShowGrip(const Value: boolean); procedure SetRbStyleManager(const Value: TRbStyleManager); procedure SetDrawAll(const Value: boolean); procedure SetAbout(const Value: string); protected procedure Paint; override; procedure Loaded; override; procedure DoBlendMore(Sender: TObject); virtual; procedure DoBlendLess(Sender: TObject); virtual; procedure WndProc(var Msg: TMessage); override; procedure Resize; override; procedure RequestAlign; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateGradients; procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property GradientType : TGradientType read FGradientType write SetGradientType; property GripAlign: TGripAlign read FGripAlign write SetGripAlign; property FadeSpeed : TFadeSpeed read FFadeSpeed write SetFadeSpeed; property Colors: TRbSplitterColors read FColors write FColors; property ShowGrip: boolean read FShowGrip write SetShowGrip; property RbStyleManager: TRbStyleManager read FRbStyleManager write SetRbStyleManager; property DrawAll : boolean read FDrawAll write SetDrawAll; property About : string read FVAbout write SetAbout stored False; end; procedure Register; implementation procedure Register; begin RegisterComponents('RbControls', [TRbSplitter]); end; { TRbSplitter } procedure TRbSplitter.CMMouseEnter(var Message: TMessage); begin Include(FDrawStates, dsMouseOver); FOnFade := DoBlendMore; UpdateTimer; end; procedure TRbSplitter.CMMouseLeave(var Message: TMessage); begin Exclude(FDrawStates, dsMouseOver); FOnFade := DoBlendLess; UpdateTimer; end; constructor TRbSplitter.Create(AOwner: TComponent); begin inherited; FColors := TRBSplitterColors.Create(Self); FGrBitmap := TBitmap.Create; FGrBitmap.PixelFormat := pf24bit; FGrMouseOver := TBitmap.Create; FGrMouseOver.PixelFormat := pf24bit; FDrawStates := []; FOverBlendPercent := 0; FGradientType := gtHorizontal; FGripAlign := gaVertical; FShowGrip := true; FFadeSpeed := fsMedium; {$IFDEF VER130} Handle := Forms.AllocateHWnd(WndProc); {$ELSE} Handle := Classes.AllocateHWnd(WndProc); {$ENDIF} FDrawAll := true; FVAbout := sAboutString; Width := 5; end; destructor TRbSplitter.Destroy; begin if FRbStyleManager <> nil then FRbStyleManager.UnRegisterControl(Self); FGrBitmap.Free; FGrMouseOver.Free; Colors.Free; {$IFDEF VER130} Forms.DeallocateHWnd(Handle); {$ELSE} Classes.DeallocateHWnd(Handle); {$ENDIF} inherited; end; procedure TRbSplitter.DoBlendLess(Sender: TObject); begin if (FOverBlendPercent <= 0) then begin FOverBlendPercent := 0; KillTimer(Handle, 1); end else Dec(FOverBlendPercent, OverBlendInterval); Invalidate; end; procedure TRbSplitter.DoBlendMore(Sender: TObject); begin if FOverBlendPercent >= 100 then begin FOverBlendPercent := 100; end else Inc(FOverBlendPercent, OverBlendInterval); if FOverBlendPercent >= 100 then begin Invalidate; KillTimer(Handle, 1); Exit; end; Invalidate; end; procedure TRbSplitter.DrawPicksBt(ACanvas: TCanvas; BLeft, BTop: integer); procedure DrawPickBt(ACanvas: TCanvas; BLeft, BTop: integer; BigDots : boolean); begin if BigDots then begin ACanvas.Brush.Color := clGray; ACanvas.FillRect(Rect(BLeft, BTop, BLeft + 2, BTop + 2)); ACanvas.Brush.Color := clWhite; ACanvas.FillRect(Rect(BLeft + 1, BTop + 1, BLeft + 3, BTop + 3)); ACanvas.Pixels[BLeft + 1, BTop +2] := clSilver; ACanvas.Pixels[BLeft + 1 , BTop + 1] := clGray; ACanvas.Pixels[BLeft , BTop] := clWhite; end else begin ACanvas.Pixels[BLeft + 1, BTop + 1] := clGray; ACanvas.Pixels[BLeft, BTop + 1] := clWhite; end; end; var i : integer; begin i := -40; while i <= 40 do begin if GripAlign = gaVertical then DrawPickBt(ACanvas, BLeft, BTop + i, true) else DrawPickBt(ACanvas, BLeft + i, BTop, true); Inc(i, 3); end; end; procedure TRbSplitter.Loaded; begin inherited; //Activate double buffering for parent control if (Parent <> nil) and Parent.InheritsFrom(TWinControl) then Parent.DoubleBuffered := true; end; procedure TRbSplitter.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent is TRbStyleManager) then FRbStyleManager := nil; inherited Notification(AComponent, Operation); end; procedure TRbSplitter.Paint; var FinalBitmap : TBitmap; begin inherited; if FGrBitmap.Height <> Height then UpdateGradients; FinalBitmap := TBitmap.Create; try FinalBitmap.PixelFormat := pf24bit; FinalBitmap.Width := Width; FinalBitmap.Height := Height; BlendBitmaps(FinalBitmap, FGrBitmap, FGrMouseOver, FOverBlendPercent, Canvas.ClipRect, 0); BitBlt(Canvas.Handle, 0, 0, Width, Height, FinalBitmap.Canvas.Handle, 0, 0, SRCCOPY); finally FinalBitmap.Free; end; end; procedure TRbSplitter.RequestAlign; begin inherited; if Align in [alLeft, alRight] then GripAlign := gaVertical else if Align in [alTop, alBottom] then GripAlign := gaHorizontal; end; procedure TRbSplitter.Resize; begin inherited; UpdateGradients; end; procedure TRbSplitter.SetAbout(const Value: string); begin end; procedure TRbSplitter.SetDrawAll(const Value: boolean); begin if FDrawAll <> Value then begin FDrawAll := Value; UpdateGradients; end; end; procedure TRbSplitter.SetFadeSpeed(const Value: TFadeSpeed); begin if FFadeSpeed <> Value then FFadeSpeed := Value; end; procedure TRbSplitter.SetGradientType(const Value: TGradientType); begin if FGradientType <> Value then begin FGradientType := Value; UpdateGradients; end; end; procedure TRbSplitter.SetGripAlign(const Value: TGripAlign); begin if FGripAlign <> Value then begin FGripAlign := Value; UpdateGradients; end; end; procedure TRbSplitter.SetRbStyleManager(const Value: TRbStyleManager); begin if Value <> FRbStyleManager then begin if Value <> nil then Value.RegisterControl(Self) else FRbStyleManager.UnregisterControl(Self); FRbStyleManager := Value; end; end; procedure TRbSplitter.SetShowGrip(const Value: boolean); begin if FShowGrip <> Value then begin FShowGrip := Value; UpdateGradients; end; end; procedure TRbSplitter.UpdateGradients; var BtLeft, BtTop : integer; R : TRect; begin inherited; if (FGrBitmap = nil) or (FGrMouseOver = nil) then Exit; FGrBitmap.Width := Width; FGrBitmap.Height := Height; FGrBitmap.Canvas.Brush.Color := Color; FGrBitmap.Canvas.FillRect(FGrBitmap.Canvas.ClipRect); FGrMouseOver.Canvas.Brush.Color := Color; FGrMouseOver.Canvas.FillRect(FGrBitmap.Canvas.ClipRect); if GripAlign = gaVertical then begin BtTop := FGrBitmap.Height div 2; BtLeft := (FGrBitmap.Width - 3) div 2; end else begin BtTop := (FGrBitmap.Height - 3) div 2; BtLeft := FGrBitmap.Width div 2; end; R := FGrBitmap.Canvas.ClipRect; if not DrawAll then if GripAlign = gaVertical then begin R.Top := BtTop - 40; R.Bottom := BtTop + 40; end else begin R.Left := BtLeft - 40; R.Right := BtLeft + 40; end; DoBitmapGradient(FGrBitmap, R, Colors.DefaultFrom, Colors.DefaultTo, FGradientType, 0); if ShowGrip then DrawPicksBt(FGrBitmap.Canvas, BtLeft, BtTop); FGrMouseOver.Width := Width; FGrMouseOver.Height := Height; DoBitmapGradient(FGrMouseOver, R, Colors.OverFrom, Colors.OverTo, FGradientType, 0); if ShowGrip then DrawPicksBt(FGrMouseOver.Canvas, BtLeft, BtTop); Invalidate; end; procedure TRbSplitter.UpdateTimer; begin KillTimer(Handle, 1); SetTimer(Handle, 1, AFadeSpeed[FFadeSpeed], nil); end; procedure TRbSplitter.WndProc(var Msg: TMessage); begin with Msg do if Msg = WM_TIMER then try FOnFade(Self); except end; inherited; end; end.
unit FrmDisplayDetails; {显示归属信息} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, DBGridEhGrouping, GridsEh, DBGridEh, FrmBase, Grids, StdCtrls, ActiveX; type TDisplayDetailsForm = class(TBaseForm) pnl1: TPanel; pnl2: TPanel; strngrdHistory: TStringGrid; pnl3: TPanel; lblDeviceName: TLabel; lbl1: TLabel; lbl2: TLabel; lblStatus: TLabel; lbl3: TLabel; lblUserName: TLabel; lbl4: TLabel; lblLocation: TLabel; lbl5: TLabel; lblOutDateTime: TLabel; procedure FormShow(Sender: TObject); private { Private declarations } FDeviceGrid: TStringGrid; procedure RefreshStringGridFromDB; procedure InitUIContent; public { Public declarations } class function DisplayOutForm(AHandle: THandle; ADeviceGrid: TStringGrid): Boolean; property DeviceGrid: TStringGrid write FDeviceGrid; end; implementation uses uControlInf, uDBFieldData, uDefine, uTransform; {$R *.dfm} { TDisplayDetailsForm } class function TDisplayDetailsForm.DisplayOutForm( AHandle: THandle; ADeviceGrid: TStringGrid): Boolean; var DisplayDetailsForm: TDisplayDetailsForm; begin DisplayDetailsForm := TDisplayDetailsForm.Create(Application, AHandle); try DisplayDetailsForm.DeviceGrid := ADeviceGrid; if DisplayDetailsForm.ShowModal = mrOk then begin Result := True; end else Result := False; finally if Assigned(DisplayDetailsForm) then FreeAndNil(DisplayDetailsForm); end; end; procedure TDisplayDetailsForm.FormShow(Sender: TObject); begin SetStringGridStyle(strngrdHistory); strngrdHistory.ColWidths[0] := 20; strngrdHistory.ColWidths[1] := 50; strngrdHistory.ColWidths[2] := 200; strngrdHistory.ColWidths[3] := 200; strngrdHistory.ColWidths[4] := 100; strngrdHistory.ColWidths[6] := 300; //界面显示内容初始化 InitUIContent; //加载此设备的历史借用情况 RefreshStringGridFromDB; end; procedure TDisplayDetailsForm.InitUIContent; var iDeviceId: Integer; begin iDeviceId := StrToInt(FDeviceGrid.Cells[1, FDeviceGrid.Row]); lblDeviceName.Caption := FDeviceGrid.Cells[3, FDeviceGrid.Row]; //判断选中的设备是否为在库设备,未借用的设备不能执行下面的归还函数 if gDatabaseControl.IsExistInDeviceLocationDB(iDeviceId) then begin lblStatus.Caption := '借出'; lblStatus.Font.Color := clRed; lblOutDateTime.Caption := gDatabaseControl.GetOutTimeByDeviceId(iDeviceId); end else begin lblStatus.Caption := '在库'; lblStatus.Font.Color := clLime; lblOutDateTime.Caption := EmptyStr; end; lblUserName.Caption := FDeviceGrid.Cells[12, FDeviceGrid.Row]; lblLocation.Caption := FDeviceGrid.Cells[11, FDeviceGrid.Row]; end; procedure TDisplayDetailsForm.RefreshStringGridFromDB; var IXMLDBData: IXMLGuoSenDeviceSystemType; iDeviceId: Integer; begin iDeviceId := StrToInt(FDeviceGrid.Cells[1, FDeviceGrid.Row]); CoInitialize(nil); IXMLDBData := NewGuoSenDeviceSystem; try IXMLDBData.DBData.OperaterType := 'Read'; IXMLDBData.DBData.DBTable := CSUserDBName; IXMLDBData.DBData.SQL := Format('Select a.Id, a.StartDateTime, a.EndDateTime, a.Memo, b.Name as LocationName, c.UserName ' + ' From (DeviceHistoryInfo a left join LocationInfo b on (a.LocationId = b.Id)) left join UserInfo c on (a.UserId = c.Id) ' + ' where (a.DeviceId = %d) ', [iDeviceId]); //装载ColData的内容 AddDeviceHistoryInfoColData(IXMLDBData); //从数据库中加载数据到RowData中 gDatabaseControl.QueryDataByXMLData(IXMLDBData); //显示到StringGrid DisXMLDataToStringGrid(IXMLDBData, strngrdHistory); finally IXMLDBData := nil; CoUninitialize; end; end; end.
unit Main; interface uses Winapi.Windows, Winapi.Messages, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TForm2 = class(TForm) Timer1: TTimer; lblCurrentTime: TLabel; Edit1: TEdit; procedure Timer1Timer(Sender: TObject); procedure Edit1Change(Sender: TObject); private procedure UpdateTime; public procedure AfterConstruction; override; end; var Form2: TForm2; implementation {$R *.dfm} uses System.SysUtils; procedure TForm2.AfterConstruction; begin Edit1.Text := '1000'; UpdateTime; end; procedure TForm2.Edit1Change(Sender: TObject); begin Timer1.Interval := StrToInt(Edit1.Text); end; procedure TForm2.Timer1Timer(Sender: TObject); begin UpdateTime; end; procedure TForm2.UpdateTime; var vCurrentTime: TDateTime; begin vCurrentTime := Now; lblCurrentTime.Caption := FormatdateTime('dd.mm.yyyy hh:nn:ss zzz', vCurrentTime); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.session.abstract; interface uses DB, Rtti, TypInfo, SysUtils, Generics.Collections, /// ORMBr ormbr.objects.manager.abstract, ormbr.core.consts, ormbr.rtti.helper, ormbr.types.blob, dbcbr.mapping.attributes; type // M - Sessão Abstract TSessionAbstract<M: class, constructor> = class abstract protected FPageSize: Integer; FPageNext: Integer; FModifiedFields: TDictionary<string, TDictionary<string, string>>; FDeleteList: TObjectList<M>; FManager: TObjectManagerAbstract<M>; FResultParams: TParams; FFindWhereUsed: Boolean; FFindWhereRefreshUsed: Boolean; FFetchingRecords: Boolean; FWhere: String; FOrderBy: String; {$IFDEF DRIVERRESTFUL} function Find(const AMethodName: String; const AParams: array of string): TObjectList<M>; overload; virtual; abstract; {$ENDIF} public constructor Create(const APageSize: Integer = -1); overload; virtual; destructor Destroy; override; function ExistSequence: Boolean; virtual; function ModifiedFields: TDictionary<string, TDictionary<string, string>>; virtual; // ObjectSet procedure Insert(const AObject: M); overload; virtual; procedure Insert(const AObjectList: TObjectList<M>); overload; virtual; abstract; procedure Update(const AObject: M; const AKey: string); overload; virtual; procedure Update(const AObjectList: TObjectList<M>); overload; virtual; abstract; procedure Delete(const AObject: M); overload; virtual; procedure Delete(const AID: Integer); overload; virtual; abstract; procedure LoadLazy(const AOwner, AObject: TObject); virtual; procedure NextPacketList(const AObjectList: TObjectList<M>); overload; virtual; abstract; function NextPacketList: TObjectList<M>; overload; virtual; abstract; function NextPacketList(const APageSize, APageNext: Integer): TObjectList<M>; overload; virtual; abstract; function NextPacketList(const AWhere, AOrderBy: String; const APageSize, APageNext: Integer): TObjectList<M>; overload; virtual; abstract; // DataSet procedure Open; virtual; procedure OpenID(const AID: Variant); virtual; procedure OpenSQL(const ASQL: string); virtual; procedure OpenWhere(const AWhere: string; const AOrderBy: string = ''); virtual; procedure NextPacket; overload; virtual; procedure RefreshRecord(const AColumns: TParams); virtual; function SelectAssociation(const AObject: TObject): String; virtual; function ResultParams: TParams; // DataSet e ObjectSet procedure ModifyFieldsCompare(const AKey: string; const AObjectSource, AObjectUpdate: TObject); virtual; function Find: TObjectList<M>; overload; virtual; function Find(const AID: Integer): M; overload; virtual; function Find(const AID: string): M; overload; virtual; function FindWhere(const AWhere: string; const AOrderBy: string): TObjectList<M>; virtual; function DeleteList: TObjectList<M>; virtual; // property FetchingRecords: Boolean read FFetchingRecords write FFetchingRecords; end; implementation uses ormbr.objects.helper, dbcbr.mapping.explorer, dbcbr.mapping.classes; { TSessionAbstract<M> } constructor TSessionAbstract<M>.Create(const APageSize: Integer = -1); begin FPageSize := APageSize; FModifiedFields := TObjectDictionary<string, TDictionary<string, string>>.Create([doOwnsValues]); FDeleteList := TObjectList<M>.Create; FResultParams := TParams.Create; FFetchingRecords := False; // Inicia uma lista interna para gerenciar campos alterados FModifiedFields.Clear; FModifiedFields.TrimExcess; FModifiedFields.Add(M.ClassName, TDictionary<string, string>.Create); end; destructor TSessionAbstract<M>.Destroy; begin FDeleteList.Clear; FDeleteList.Free; FModifiedFields.Clear; FModifiedFields.Free; FResultParams.Clear; FResultParams.Free; inherited; end; function TSessionAbstract<M>.ModifiedFields: TDictionary<string, TDictionary<string, string>>; begin Result := FModifiedFields; end; procedure TSessionAbstract<M>.Delete(const AObject: M); begin FManager.DeleteInternal(AObject); end; function TSessionAbstract<M>.DeleteList: TObjectList<M>; begin Result := FDeleteList; end; function TSessionAbstract<M>.ExistSequence: Boolean; begin Result := FManager.ExistSequence; end; function TSessionAbstract<M>.Find(const AID: string): M; begin FFindWhereUsed := False; FFetchingRecords := False; Result := FManager.Find(AID); end; function TSessionAbstract<M>.FindWhere(const AWhere, AOrderBy: string): TObjectList<M>; begin FFindWhereUsed := True; FFetchingRecords := False; FWhere := AWhere; FOrderBy := AOrderBy; if FPageSize > -1 then begin Result := NextPacketList(FWhere, FOrderBy, FPageSize, FPageNext); Exit; end; Result := FManager.FindWhere(FWhere, FOrderBy); end; function TSessionAbstract<M>.Find(const AID: Integer): M; begin FFindWhereUsed := False; FFetchingRecords := False; Result := FManager.Find(AID); end; function TSessionAbstract<M>.Find: TObjectList<M>; begin FFindWhereUsed := False; FFetchingRecords := False; Result := FManager.Find; end; procedure TSessionAbstract<M>.Insert(const AObject: M); begin FManager.InsertInternal(AObject); end; procedure TSessionAbstract<M>.ModifyFieldsCompare(const AKey: string; const AObjectSource, AObjectUpdate: TObject); var LColumn: TColumnMapping; LColumns: TColumnMappingList; LProperty: TRttiProperty; begin LColumns := TMappingExplorer.GetMappingColumn(AObjectSource.ClassType); for LColumn in LColumns do begin LProperty := LColumn.ColumnProperty; if LProperty.IsVirtualData then Continue; if LProperty.IsNoUpdate then Continue; if LProperty.PropertyType.TypeKind in cPROPERTYTYPES_1 then Continue; if not FModifiedFields.ContainsKey(AKey) then FModifiedFields.Add(AKey, TDictionary<string, string>.Create); // Se o tipo da property for tkRecord provavelmente tem Nullable nela // Se não for tkRecord entra no ELSE e pega o valor de forma direta if LProperty.PropertyType.TypeKind in [tkRecord] then // Nullable ou TBlob begin if LProperty.IsBlob then begin if LProperty.GetValue(AObjectSource).AsType<TBlob>.ToSize <> LProperty.GetValue(AObjectUpdate).AsType<TBlob>.ToSize then begin FModifiedFields.Items[AKey].Add(LProperty.Name, LColumn.ColumnName); end; end else begin if LProperty.GetNullableValue(AObjectSource).AsType<Variant> <> LProperty.GetNullableValue(AObjectUpdate).AsType<Variant> then begin FModifiedFields.Items[AKey].Add(LProperty.Name, LColumn.ColumnName); end; end; end else begin if LProperty.GetValue(AObjectSource).AsType<Variant> <> LProperty.GetValue(AObjectUpdate).AsType<Variant> then begin FModifiedFields.Items[AKey].Add(LProperty.Name, LColumn.ColumnName); end; end; end; end; procedure TSessionAbstract<M>.NextPacket; begin end; procedure TSessionAbstract<M>.Open; begin FFetchingRecords := False; end; procedure TSessionAbstract<M>.OpenID(const AID: Variant); begin FFetchingRecords := False; end; procedure TSessionAbstract<M>.OpenSQL(const ASQL: string); begin FFetchingRecords := False; end; procedure TSessionAbstract<M>.OpenWhere(const AWhere, AOrderBy: string); begin FFetchingRecords := False; end; procedure TSessionAbstract<M>.RefreshRecord(const AColumns: TParams); begin end; function TSessionAbstract<M>.ResultParams: TParams; begin Result := FResultParams; end; function TSessionAbstract<M>.SelectAssociation(const AObject: TObject): String; begin Result := '' end; procedure TSessionAbstract<M>.Update(const AObject: M; const AKey: string); begin FManager.UpdateInternal(AObject, FModifiedFields.Items[AKey]); end; procedure TSessionAbstract<M>.LoadLazy(const AOwner, AObject: TObject); begin end; end.
unit untFrmExercicio1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, untFrmBase, Vcl.ExtCtrls, Vcl.Buttons, Vcl.StdCtrls, System.StrUtils, System.Generics.Collections; type TOperacao = (eOperacaoInvalida, eSoma, eSubtracao, eDivisao, eMultiplicacao); TFrmExercicio1 = class(TFrmBase) pnlVisor: TPanel; pnlOperacoes: TPanel; pnlNumeros: TPanel; btn1: TSpeedButton; btn2: TSpeedButton; btn3: TSpeedButton; btn4: TSpeedButton; btn5: TSpeedButton; btn6: TSpeedButton; btn7: TSpeedButton; btn8: TSpeedButton; btn9: TSpeedButton; btn0: TSpeedButton; btnDivisao: TSpeedButton; btnMultiplicacao: TSpeedButton; btnSubtracao: TSpeedButton; btnSoma: TSpeedButton; btnIgual: TSpeedButton; edtVisor: TEdit; btnCE: TSpeedButton; btnBackspace: TSpeedButton; pnlImpostos: TPanel; btnImpostoA: TSpeedButton; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; lblImpostos: TLabel; procedure FormCreate(Sender: TObject); procedure btnClick(Sender: TObject); procedure btnImpostoAClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } FValorAuxiliar: Real; FResultado: Real; FValorTextoVisor: String; FUltimoCaracterInformado: String; FOperacaoAuxiliar: TOperacao; procedure prLimpar; procedure prAtualizarValorTexto(const pCaracter: String); procedure prAtualizarTextoVisor; procedure prExecutarOperacao(const pCaracter: String); procedure prExecutarIgual; function fcRetornarCaracterBotao(pBotao: TObject): String; function fcRemoverUltimoCaracter(const pTexto: String): String; public { Public declarations } end; var FrmExercicio1: TFrmExercicio1; implementation {$R *.dfm} uses untCalculoImposto; const cTEXTOBOTOES: TArray<String> = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '/', '*', '-', '+', '=', 'CE', '<-']; cOPERACOES: TArray<String> = ['/', '*', '-', '+']; procedure TFrmExercicio1.btnClick(Sender: TObject); var vCaracter: String; begin inherited; vCaracter := fcRetornarCaracterBotao(Sender); case AnsiIndexStr(vCaracter, cTEXTOBOTOES) of 0..9: prAtualizarValorTexto(vCaracter); 10..13: prExecutarOperacao(vCaracter); 14: prExecutarIgual; 15: prLimpar; 16: FValorTextoVisor := fcRemoverUltimoCaracter(FValorTextoVisor); end; FUltimoCaracterInformado := vCaracter; prAtualizarTextoVisor; end; function TFrmExercicio1.fcRetornarCaracterBotao(pBotao: TObject): String; begin Result := ''; if not Assigned(pBotao) then Exit; if not (pBotao is TSpeedButton) then Exit; Result := TSpeedButton(pBotao).Caption; end; procedure TFrmExercicio1.btnImpostoAClick(Sender: TObject); var vImpostoA: TImpostoA; begin inherited; vImpostoA := TImpostoA.Create; try vImpostoA.BaseCalculo := StrToFloat(edtVisor.Text); FResultado := vImpostoA.fcCalcular; FValorTextoVisor := FloatToStr(FResultado); prAtualizarTextoVisor; finally FreeAndNil(vImpostoA); end; end; function TFrmExercicio1.fcRemoverUltimoCaracter(const pTexto: String): String; var vQtdCaracteres: Integer; begin vQtdCaracteres := Length(pTexto); if vQtdCaracteres = 1 then Result := '0' else Result := Copy(pTexto, 1, vQtdCaracteres - 1); end; procedure TFrmExercicio1.FormCreate(Sender: TObject); begin inherited; Self.KeyPreview := True; prLimpar; end; procedure TFrmExercicio1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if Key = VK_BACK then btnBackspace.Click; if Key = VK_NUMPAD1 then btn1.Click; if Key = VK_NUMPAD2 then btn2.click; if Key = VK_NUMPAD3 then btn3.click; if Key = VK_NUMPAD4 then btn4.click; if Key = VK_NUMPAD5 then btn5.click; if Key = VK_NUMPAD6 then btn6.click; if Key = VK_NUMPAD7 then btn7.click; if Key = VK_NUMPAD8 then btn8.click; if Key = VK_NUMPAD9 then btn9.click; if Key = VK_NUMPAD0 then btn0.click; if Key = VK_ADD then btnSoma.click; if Key = VK_SUBTRACT then btnSubtracao.click; if Key = VK_MULTIPLY then btnMultiplicacao.click; if Key = VK_DIVIDE then btnDivisao.click; if Key = VK_RETURN then btnIgual.click; if Key = VK_DELETE then btnCE.click; end; procedure TFrmExercicio1.prAtualizarTextoVisor; begin edtVisor.ReadOnly := False; edtVisor.Text := FValorTextoVisor; edtVisor.ReadOnly := True; edtVisor.SelStart := Length(FValorTextoVisor); end; procedure TFrmExercicio1.prAtualizarValorTexto(const pCaracter: String); begin if AnsiIndexStr(FUltimoCaracterInformado, cOPERACOES) <> -1 then FValorTextoVisor := '0'; if FValorTextoVisor = '0' then FValorTextoVisor := pCaracter else FValorTextoVisor := FValorTextoVisor + pCaracter; end; procedure TFrmExercicio1.prExecutarIgual; var vValorAux: Real; begin vValorAux := StrToFloat(FValorTextoVisor); case FOperacaoAuxiliar of eSoma: FResultado := FValorAuxiliar + vValorAux; eSubtracao: FResultado := FValorAuxiliar - vValorAux; eMultiplicacao: FResultado := FValorAuxiliar * vValorAux; eDivisao: begin if vValorAux <> 0 then FResultado := FValorAuxiliar / vValorAux else begin ShowMessage('Não é possível efetuar divisão por zero.'); btnCE.Click; Exit; end; end; else FResultado := vValorAux; end; FValorTextoVisor := FloatToStr(FResultado); FOperacaoAuxiliar := eOperacaoInvalida; end; procedure TFrmExercicio1.prExecutarOperacao(const pCaracter: String); var vValorAux: Real; begin vValorAux := StrToFloat(FValorTextoVisor); if (FOperacaoAuxiliar <> eOperacaoInvalida) and (AnsiIndexStr(FUltimoCaracterInformado, cOPERACOES) < 0) then begin case FOperacaoAuxiliar of eSoma: FResultado := FValorAuxiliar + vValorAux; eSubtracao: FResultado := FValorAuxiliar - vValorAux; eMultiplicacao: FResultado := FValorAuxiliar * vValorAux; eDivisao: begin if vValorAux <> 0 then FResultado := FValorAuxiliar / vValorAux else begin ShowMessage('Não é possível efetuar divisão por zero.'); btnCE.Click; Exit; end; end; end; vValorAux := FResultado; FValorTextoVisor := FloatToStr(vValorAux); end; FValorAuxiliar := vValorAux; case AnsiIndexStr(pCaracter, cOPERACOES) of 0: FOperacaoAuxiliar := eDivisao; 1: FOperacaoAuxiliar := eMultiplicacao; 2: FOperacaoAuxiliar := eSubtracao; 3: FOperacaoAuxiliar := eSoma; else FOperacaoAuxiliar := eOperacaoInvalida; end; end; procedure TFrmExercicio1.prLimpar; begin FValorTextoVisor := '0'; FUltimoCaracterInformado := ''; FResultado := 0; FValorAuxiliar := 0; FOperacaoAuxiliar := eOperacaoInvalida; prAtualizarTextoVisor; end; procedure TFrmExercicio1.SpeedButton1Click(Sender: TObject); var vImpostoA: TImpostoA; vImpostoB: TImpostoB; begin inherited; vImpostoA := TImpostoA.Create; vImpostoB := TImpostoB.Create; try vImpostoA.BaseCalculo := StrToFloat(edtVisor.Text); vImpostoB.ImpostoA := vImpostoA; FResultado := vImpostoB.fcCalcular; FValorTextoVisor := FloatToStr(FResultado); prAtualizarTextoVisor; finally FreeAndNil(vImpostoA); FreeAndNil(vImpostoB); end; end; procedure TFrmExercicio1.SpeedButton2Click(Sender: TObject); var vImpostoA: TImpostoA; vImpostoB: TImpostoB; vImpostoC: TImpostoC; begin inherited; vImpostoA := TImpostoA.Create; vImpostoB := TImpostoB.Create; vImpostoC := TImpostoC.Create; try vImpostoA.BaseCalculo := StrToFloat(edtVisor.Text); vImpostoB.ImpostoA := vImpostoA; vImpostoC.ImpostoB := vImpostoB; FResultado := vImpostoC.fcCalcular; FValorTextoVisor := FloatToStr(FResultado); prAtualizarTextoVisor; finally FreeAndNil(vImpostoA); FreeAndNil(vImpostoB); FreeAndNil(vImpostoC); end; end; end.
unit frmNovusForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, NovusUtilities,StdCtrls ; type ThiNovusForm = class(TForm) procedure FormShow(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); private { Private declarations } fParentWinControl: TWinControl; fbIgnoreInitWindow: Boolean; fbUseFormKeyPress: Boolean; public { Public declarations } procedure Handle_WM_CLOSEWINDOW(var msg: TMessage); message WM_CLOSEWINDOW; function InitWindow: Boolean; virtual; procedure SetupWindow; virtual; property ParentWinControl: TWinControl read fParentWinControl write fParentWinControl; property IgnoreInitWindow: Boolean read fbIgnoreInitWindow write fbIgnoreInitWindow; property UseFormKeyPress: Boolean read fbUseFormKeyPress write fbUseFormKeyPress; end; ThiNovusFormClass = class of ThiNovusForm; var hiNovusForm: ThiNovusForm; implementation procedure ThiNovusForm.FormCreate(Sender: TObject); begin IgnoreInitWindow := false; end; procedure ThiNovusForm.FormKeyPress(Sender: TObject; var Key: Char); begin if UseFormKeyPress = false then Exit; if Sender Is TCustomMemo then Exit; If Key = #13 Then begin SelectNext(ActiveControl as tWinControl, True, True ); Key := #0; end; end; procedure ThiNovusForm.FormShow(Sender: TObject); begin if not fbIgnoreInitWindow then InitWindow; end; function ThiNovusForm.InitWindow: Boolean; begin Result := True; end; procedure ThiNovusForm.SetupWindow; begin // end; procedure ThiNovusForm.Handle_WM_CLOSEWINDOW(var msg: TMessage); begin {} end; {$R *.dfm} end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.dataset.events; interface uses DB, Rtti, TypInfo; type TDataSetEvents = class abstract private FBeforeScroll: TDataSetNotifyEvent; FAfterScroll: TDataSetNotifyEvent; FBeforeOpen: TDataSetNotifyEvent; FAfterOpen: TDataSetNotifyEvent; FBeforeClose: TDataSetNotifyEvent; FAfterClose: TDataSetNotifyEvent; FBeforeInsert: TDataSetNotifyEvent; FAfterInsert: TDataSetNotifyEvent; FBeforeEdit: TDataSetNotifyEvent; FAfterEdit: TDataSetNotifyEvent; FBeforeDelete: TDataSetNotifyEvent; FAfterDelete: TDataSetNotifyEvent; FBeforePost: TDataSetNotifyEvent; FAfterPost: TDataSetNotifyEvent; FBeforeCancel: TDataSetNotifyEvent; FAfterCancel: TDataSetNotifyEvent; FOnNewRecord: TDataSetNotifyEvent; public property BeforeScroll: TDataSetNotifyEvent read FBeforeScroll write FBeforeScroll; property AfterScroll: TDataSetNotifyEvent read FAfterScroll write FAfterScroll; property BeforeOpen: TDataSetNotifyEvent read FBeforeOpen write FBeforeOpen; property AfterOpen: TDataSetNotifyEvent read FAfterOpen write FAfterOpen; property BeforeClose: TDataSetNotifyEvent read FBeforeClose write FBeforeClose; property AfterClose: TDataSetNotifyEvent read FAfterClose write FAfterClose; property BeforeInsert: TDataSetNotifyEvent read FBeforeInsert write FBeforeInsert; property AfterInsert: TDataSetNotifyEvent read FAfterInsert write FAfterInsert; property BeforeEdit: TDataSetNotifyEvent read FBeforeEdit write FBeforeEdit; property AfterEdit: TDataSetNotifyEvent read FAfterEdit write FAfterEdit; property BeforeDelete: TDataSetNotifyEvent read FBeforeDelete write FBeforeDelete; property AfterDelete: TDataSetNotifyEvent read FAfterDelete write FAfterDelete; property BeforePost: TDataSetNotifyEvent read FBeforePost write FBeforePost; property AfterPost: TDataSetNotifyEvent read FAfterPost write FAfterPost; property BeforeCancel: TDataSetNotifyEvent read FBeforeCancel write FBeforeCancel; property AfterCancel: TDataSetNotifyEvent read FAfterCancel write FAfterCancel; property OnNewRecord: TDataSetNotifyEvent read FOnNewRecord write FOnNewRecord; end; implementation end.
unit UpdateCheck; interface uses SimpHttp, SysUtils, Classes, Common; type EUpdCheck = class(EAbort); TucEventType = (ucNoNew,ucNewVersion,ucError); TUpdCheckerEvent = procedure(Sender: TObject; EventType: TucEventType) of object; TUpdChecker = class(TThread) private fOwner: TComponent; fSimpleHTTP: TSimpleHTTP; fOnStatus: TUpdCheckerEvent; fEventType: TucEventType; procedure DoStatus; function IsNewerVersion(CurrentVersion: string): Boolean; procedure CheckVersion; protected procedure Execute; override; public fGetResult: TStringStream; PostValues: TStringList; ScriptURL: string; Referrer: string; ThisVersion: string; MoopsID: string; Changes: string; constructor Create(aOwner: TComponent); destructor Destroy; override; procedure StartCheck; property OnStatus: TUpdCheckerEvent read fOnStatus write fOnStatus; property Owner: TComponent read fOwner; end; var UpdChecker: TUpdChecker; implementation uses MainFrm; constructor TUpdChecker.Create(aOwner: TComponent); begin inherited Create(True); fOwner:=aOwner; PostValues:=TStringList.Create; fSimpleHTTP:=TSimpleHTTP.Create(aOwner); fSimpleHTTP.SilentExceptions:=True; fGetResult:=TStringStream.Create(''); fOnStatus:=nil; ScriptURL:=''; ThisVersion:=''; end; destructor TUpdChecker.Destroy; begin fGetResult.Free; fSimpleHTTP.Abort; fSimpleHTTP.Free; PostValues.Free; inherited; end; procedure TUpdChecker.DoStatus; begin if Assigned(fOnStatus) then fOnStatus(Self,fEventType); end; function TUpdChecker.IsNewerVersion(CurrentVersion: string): Boolean; var CurVer: array[1..4] of string; ThisVer: array[1..4] of string; procedure SplitVersion(Version: string; var VerArray: array of string); var I, P: Integer; begin I:=0; while I<4 do begin P:=Pos('.',Version); if P=0 then P:=Length(Version)+1; VerArray[I]:=Copy(Version,1,P-1); Delete(Version,1,P); Inc(I); end; end; var I: Integer; begin Result:=False; SplitVersion(CurrentVersion,CurVer); SplitVersion(ThisVersion,ThisVer); for I:=1 to 4 do if StrToInt(CurVer[I])>StrToInt(ThisVer[I]) then begin Result:=True; Exit; end; end; procedure TUpdChecker.CheckVersion; var SL: TStringList; CurrentVersion: string; begin SL:=TStringList.Create; try SL.Text:=fGetResult.DataString; if SL.Values['error']='1' then raise EUpdCheck.Create('Returned errorcode 1'); MoopsID:=SL.Values['id']; CurrentVersion:=SL.Values['currentversion']; if CurrentVersion='' then raise EUpdCheck.Create('No currentversion returned'); if IsNewerversion(CurrentVersion) then fEventType:=ucNewVersion else fEventType:=ucNoNew; Changes:=DecodeURLVar(SL.Values['changes']); Synchronize(DoStatus); finally SL.Free; end; end; procedure TUpdChecker.Execute; {var Params: string;} begin repeat try { PostValues.Insert(0,''); PostValues.Insert(0,''); PostValues.Insert(0,'Content-type: text/html'); fSimpleHTTP.PostData:=PostValues; fSimpleHTTP.Post(ScriptURL, fGetResult); fEventType:=ucNoNew; Synchronize(DoStatus);} //Params:='id=&moopsversion='+ThisVersion; // Params:='name=Martin Poelstra&email=martin@beryllium.nu&country=NL&how=Zelf geprogd&version='+ThisVersion; { id= } //Params:='id=&version='+ThisVersion; { currentversion= changes= } fSimpleHTTP.Referrer:=Referrer; fSimpleHTTP.Get(ScriptURL{+'?'+Params}, fGetResult); CheckVersion; except if Assigned(MainForm) and MainForm.BetaMode and Assigned(MainForm.StatusPage) then begin MainForm.StatusPage.AddToLog('Version check: Exception "'+Exception(ExceptObject).Message+'"'); MainForm.StatusPage.ReceiveLine('Data was: '#10+fGetResult.DataString+#10); end; fEventType:=ucError; Synchronize(DoStatus); end; if Terminated then Exit; Suspend; until Terminated; end; procedure TUpdChecker.StartCheck; begin while Suspended do Resume; end; end.
unit Lenin_Controls; (***************************************) (* LENIN INC *) (* Online: http://www.lenininc.com/ *) (* E-Mail: lenin@zeos.net *) (* Free for non commercial use. *) (***************************************) interface uses Windows, Messages, RichEdit, Lenin_Commctrl, Lenin_SysUtils, ShellAPI; { Window } function SetNewFont(hWindow: HWND; FontSize, Weight: Integer; FontName: String): Boolean; function EnableDlgItem(Dlg: HWND; ctrlID: Integer; bEnable: boolean): BOOL; function Static_SetBitmap(hControl: HWND; ResId: Integer): Boolean; function GetAssociatedIcon(FileName: String; IconIndex: Word): hIcon; function GetAssociatedIconExt(const Extension: string; Small: Boolean): hIcon; { Menu } function Menu_GetChecked(menu: HMENU; id: DWORD): Boolean; procedure Menu_SetChecked(menu: HMENU; id: DWORD; check: Boolean); function Menu_IsEnabled(menu: HMENU; id: DWORD): Boolean; procedure Menu_SetEnabled(menu: HMENU; id: DWORD; enable: Boolean); { Edit } //Определение текста в Edit function Edit_GetText(hEdit: HWND): String; //Установка текста в Edit procedure Edit_SetText(hEdit: HWND; Text: String); //Установка лимита текста procedure Edit_SetLimitText(hEdit: HWND; Limit: Integer); //Установка ввода пароля, маски пароля procedure Edit_SetPassword(hEdit: HWND; Character: Char); //Делаем компонент активным или не активным function Edit_SetReadOnly(hEdit: HWND; ReadOnly: BOOL): Integer; { Resources } //Установка значка на Button из ресурсов программы //window style = BS_ICON function Button_SetIcon(hButton: HWND; ResId, Width, Height: Integer): HWND; //Установка картинки на Button из ресурсов программы //window style = BS_BITMAP function Button_SetBitmap(hButton: HWND; ResId, Width, Height: Integer): HWND; { CheckBox } //Определяем состояние CheckBox //0 = UnCheck; 1 = Check; 2 = Check and Grayed function CheckBox_GetCheck(hCheckBox: HWND): Integer; //Устанавливаем состояние CheckBox //UnCheck = 0; Check = 1; Check and Grayed = 2 procedure CheckBox_SetCheck(hCheckBox: HWND; Check: Integer); { ListView } //Получаем имя выбранного пункта ListView function ListView_GetItemName(hListView: HWND): String; //Разрешаем редактировать выбранный пункт ListView procedure ListView_SetEditItem(hListView: HWND); //Выбираем все файлы в ListView. Если fTurnSelection = True, уже отмеченные файлы не выбираем. procedure ListView_SelectAllItems(hListView: HWND; fTurnSelection: boolean); { ListBox } //Определение колличества пунктов в ListBox function ListBox_GetItemCount(hListBox: HWND): Integer; //Удаление определенного пункта в ListBox procedure ListBox_DeleteItem(hListBox: HWND; Index: Integer); //Удаление всех пунктов в ListBox procedure ListBox_ClearItems(hListBox: HWND); //Добавление пункта в ListBox procedure ListBox_AddItem(hListBox: HWND; NewItem: String); //Добавление пункта в определенное место в ListBox procedure ListBox_InsertItem(hListBox: HWND; Index: Integer; NewItem: String); //Определение имени выделеного пункта в ListBox function ListBox_GetSelectedItem(hListBox: HWND): string; //Определение номера выделеного пункта в ListBox function ListBox_GetCountSelectedItem(hListBox: HWND): Integer; //Определение имени пункта по номеру в ListBox function ListBox_GetItem(hListBox: HWND; LbItem: Integer): string; //Выделение всех пунктов в ListBox procedure ListBox_SelAllItems(hListBox: HWND); //Выбор пункта в ListBox procedure ListBox_SelectedItem(hListBox: HWND; Index: Integer); { ComboBox } //Определение колличества пунктов в ComboBox function ComboBox_GetItemCount(hComboBox: HWND): Integer; //Удаление определенного пункта в ComboBox procedure ComboBox_DeleteItem(hComboBox: HWND; Index: Integer); //Удаление всех пунктов в ComboBox procedure ComboBox_ClearItems(hComboBox: HWND); //Добавление пункта в ComboBox procedure ComboBox_AddItem(hComboBox: HWND; NewItem: String); //Добавление пункта в определенное место в ComboBox procedure ComboBox_InsertItem(hComboBox: HWND; Index: Integer; NewItem: String); //Определение имени выбранного пункта в ComboBox function ComboBox_GetSelectedItem(hComboBox: HWND): string; //Определение номера выбранного пункта в ComboBox function ComboBox_GetCountSelectedItem(hComboBox: HWND): Integer; //Определение имени пункта по номеру в ComboBox function ComboBox_GetItem(hComboBox: HWND; LbItem: Integer): string; //Выбор пункта в ComboBox по счету procedure ComboBox_SelectedItem(hComboBox: HWND; Index: Integer); //Выбор пункта в ComboBox по имени procedure ComboBox_SelectedString(hComboBox: HWND; Text: String); //Открытие пунктов ComboBox procedure ComboBox_OpenItems(hComboBox: HWND); { Hot-Key } procedure HotKey_SetHotKey(hHotKey: HWND; bVKHotKey: wParam; bfMods: lParam); function HotKey_GetHotKey(hHotKey: HWND): WORD; procedure HotKey_SetRules(hHotKey: HWND; fwCombInv: wParam; fwModInv: lParam); { Progress Bar } //Установка минимальной и максимальной позиции ProgressBar function Progress_SetRange(hProgress: HWND; nMinRange: wParam; nMaxRange: lParam): DWORD; //Устанавливаем позицию ProgressBar function Progress_SetPos(hProgress: HWND; nNewPos: wParam): Integer; //Получаем позицию ProgressBar function Progress_GetPos(hProgress: HWND): Integer; function Progress_DeltaPos(hProgress: HWND; nIncrement: wParam): Integer; //Установка шага продвижения ProgressBar function Progress_SetStep(hProgress: HWND; nStepInc: wParam): Integer; function Progress_StepIt(hProgress: HWND): Integer; procedure Progress_SetLineColor(hProgress: HWND; Color: tCOLORREF); procedure Progress_SetBarColor(hProgress: HWND; Color: tCOLORREF); { Rich Edit } function RichEdit_Enable(hRichEdit: HWND; fEnable: Bool): BOOL; function RichEdit_GetText(hRichEdit: HWND): String; function RichEdit_GetTextLength(hRichEdit: HWND): Integer; function RichEdit_SetText(hRichEdit: HWND; lpsz: PChar): BOOL; procedure RichEdit_LimitText(hRichEdit: HWND; cchMax: wParam); function RichEdit_GetLineCount(hRichEdit: HWND): Integer; function RichEdit_GetLine(hRichEdit: HWND; line: wParam; lpch: LPCSTR): Integer; procedure RichEdit_GetRect(hRichEdit: HWND; lprc: tRECT); procedure RichEdit_SetRect(hRichEdit: HWND; lprc: tRECT); function RichEdit_GetSel(hRichEdit: HWND): DWORD; procedure RichEdit_SetSel(hRichEdit: HWND; ichStart, ichEnd: Integer); procedure RichEdit_ReplaceSel(hRichEdit: HWND; lpszReplace: LPCSTR); function RichEdit_GetModify(hRichEdit: HWND): BOOL; procedure RichEdit_SetModify(hRichEdit: HWND; fModified: UINT); function RichEdit_ScrollCaret(hRichEdit: HWND): BOOL; function RichEdit_LineFromChar(hRichEdit: HWND; ich: Integer): Integer; function RichEdit_LineIndex(hRichEdit: HWND; line: Integer): Integer; function RichEdit_LineLength(hRichEdit: HWND; line: Integer): Integer; procedure RichEdit_Scroll(hRichEdit: HWND; dv: wParam; dh: lParam); function RichEdit_CanUndo(hRichEdit: HWND): BOOL; function RichEdit_Undo(hRichEdit: HWND): BOOL; procedure RichEdit_EmptyUndoBuffer(hRichEdit: HWND); function RichEdit_GetFirstVisibleLine(hRichEdit: HWND): Integer; function RichEdit_SetReadOnly(hRichEdit: HWND; fReadOnly: Boolean): BOOL; procedure RichEdit_SetWordBreakProc(hRichEdit: HWND; lpfnWordBreak: Pointer); function RichEdit_GetWordBreakProc(hRichEdit: HWND): Pointer; function RichEdit_CanPaste(hRichEdit: HWND; uFormat: UINT): BOOL; function RichEdit_CharFromPos(hRichEdit: HWND; x, y: Integer): DWORD; function RichEdit_DisplayBand(hRichEdit: HWND; lprc: tRECT): BOOL; procedure RichEdit_ExGetSel(hRichEdit: HWND; lpchr: TCharRange); procedure RichEdit_ExLimitText(hRichEdit: HWND; cchTextMax: Dword); function RichEdit_ExLineFromChar(hRichEdit: HWND; ichCharPos: Dword): Integer; function RichEdit_ExSetSel(hRichEdit: HWND; ichCharRange: TCharRange): Integer; function RichEdit_FindText(hRichEdit: HWND; fuFlags: UINT; lpFindText: tFINDTEXT): Integer; function RichEdit_FindTextEx(hRichEdit: HWND; fuFlags: UINT; lpFindText: tFINDTEXT): Integer; function RichEdit_FindWordBreak(hRichEdit: HWND; code: UINT; ichStart: Dword): Integer; function RichEdit_FormatRange(hRichEdit: HWND; fRender: Boolean; lpFmt: tFORMATRANGE): Integer; function RichEdit_GetCharFormat(hRichEdit: HWND; fSelection: Boolean; lpFmt: tCHARFORMAT): DWORD; function RichEdit_GetEventMask(hRichEdit: HWND): DWORD; function RichEdit_GetLimitText(hRichEdit: HWND): Integer; function RichEdit_GetOleInterface(hRichEdit: HWND; ppObject: lParam): BOOL; function RichEdit_GetOptions(hRichEdit: HWND): UINT; function RichEdit_GetParaFormat(hRichEdit: HWND; lpFmt: tPARAFORMAT): DWORD; function RichEdit_GetSelText(hRichEdit: HWND; lpBuf: LPSTR): Integer; function RichEdit_GetTextRange(hRichEdit: HWND; lpRange: tTEXTRANGE): Integer; function RichEdit_GetWordBreakProcEx(hRichEdit: HWND): Integer; procedure RichEdit_HideSelection(hRichEdit: HWND; fHide: Boolean; fChangeStyle: Boolean); procedure RichEdit_PasteSpecial(hRichEdit: HWND; uFormat: UINT); function RichEdit_PosFromChar(hRichEdit: HWND; wCharIndex: wParam): DWORD; procedure RichEdit_RequestResize(hRichEdit: HWND); function RichEdit_SelectionType(hRichEdit: HWND): Integer; function RichEdit_SetBkgndColor(hRichEdit: HWND; fUseSysColor: Boolean; clr: tCOLORREF): tCOLORREF; function RichEdit_SetCharFormat(hRichEdit: HWND; uFlags: UINT; lpFmt: tCHARFORMAT): BOOL; function RichEdit_SetEventMask(hRichEdit: HWND; dwMask: Dword): DWORD; function RichEdit_SetOleCallback(hRichEdit: HWND; lpObj: lParam): BOOL; function RichEdit_SetOptions(hRichEdit: HWND; fOperation: UINT; fOptions: UINT): UINT; function RichEdit_SetParaFormat(hRichEdit: HWND; lpFmt: tPARAFORMAT): BOOL; function RichEdit_SetTargetDevice(hRichEdit: HWND; hdcTarget: HDC; cxLineWidth: Integer): BOOL; function RichEdit_SetWordBreakProcEx(hRichEdit: HWND; pfnWordBreakProcEx: Integer): Integer; function RichEdit_StreamIn(hRichEdit: HWND; uFormat: UINT; lpStream: tEDITSTREAM): Integer; function RichEdit_StreamOut(hRichEdit: HWND; uFormat: UINT; lpStream: tEDITSTREAM): Integer; { Status Bar } function Status_GetBorders(hStatus: HWND; aBorders: lParam): BOOL; function Status_GetParts(hStatus: HWND; nParts: wParam; aRightCoord: lParam): Integer; function Status_GetRect(hStatus: HWND; iPart: wParam; lprc: lParam): BOOL; function Status_GetText(hStatus: HWND; iPart: wParam): String; function Status_GetTextLength(hStatus: HWND; iPart: wParam): DWORD; procedure Status_SetMinHeight(hStatus: HWND; minHeight: wParam); function Status_SetParts(hStatus: HWND; nParts: wParam; aWidths: lParam): BOOL; function Status_SetText(hStatus: HWND; iPart: wParam; szText: LPSTR): BOOL; function Status_Simple(hStatus: HWND; fSimple: Boolean): BOOL; { Tool Bar } function ToolBar_AddBitmap(hToolBar: HWND; nButtons: wParam; lptbab: tTBADDBITMAP): Integer; function ToolBar_AddButtons(hToolBar: HWND; uNumButtons: UINT; lpButtons: tTBBUTTON): BOOL; function ToolBar_AddString(hToolBar: HWND; hst: HInst; idString: Word): Integer; procedure ToolBar_AutoSize(hToolBar: HWND); function ToolBar_ButtonCount(hToolBar: HWND): Integer; procedure ToolBar_ButtonStructSize(hToolBar: HWND); function ToolBar_ChangeBitmap(hToolBar: HWND; idButton: wParam; iBitmap: lParam): BOOL; function ToolBar_CheckButton(hToolBar: HWND; idButton: wParam; fCheck: lParam): BOOL; function ToolBar_CommandToIndex(hToolBar: HWND; idButton: wParam): Integer; procedure ToolBar_Customize(hToolBar: HWND); function ToolBar_DeleteButton(hToolBar: HWND; idButton: wParam): BOOL; function ToolBar_EnableButton(hToolBar: HWND; idButton: wParam; fEnable: lParam): BOOL; function ToolBar_GetBitmap(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_GetBitmapFlags(hToolBar: HWND): Integer; function ToolBar_GetButton(hToolBar: HWND; idButton: wParam; lpButton: tTBBUTTON): BOOL; function ToolBar_GetButtonText(hToolBar: HWND; idButton: wParam; lpszText: LPSTR): Integer; function ToolBar_GetItemRect(hToolBar: HWND; idButton: wParam; lprc: tRECT): BOOL; function ToolBar_GetRows(hToolBar: HWND): Integer; function ToolBar_GetState(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_GetToolTips(hToolBar: HWND): HWND; function ToolBar_HideButton(hToolBar: HWND; idButton: wParam; fShow: lParam): BOOL; function ToolBar_Indeterminate(hToolBar: HWND; idButton: wParam; fIndeterminate: lParam): BOOL; function ToolBar_InsertButton(hToolBar: HWND; idButton: wParam; lpButton: tTBBUTTON): BOOL; function ToolBar_IsButtonChecked(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_IsButtonEnabled(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_IsButtonHidden(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_IsButtonIndeterminate(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_IsButtonPressed(hToolBar: HWND; idButton: wParam): Integer; function ToolBar_PressButton(hToolBar: HWND; idButton: wParam; fPress: lParam): BOOL; procedure ToolBar_SaveRestore(hToolBar: HWND; fSave: Boolean; ptbsp: tTBSAVEPARAMS); function ToolBar_SetBitmapSize(hToolBar: HWND; dxBitmap, dyBitmap: Integer): BOOL; function ToolBar_SetButtonSize(hToolBar: HWND; dxBitmap, dyBitmap: Integer): BOOL; function ToolBar_SetCmdID(hToolBar: HWND; index, cmdId: UINT): BOOL; procedure ToolBar_SetParent(hToolBar: HWND; hwndParent: HWND); procedure ToolBar_SetRows(hToolBar: HWND; cRows: Integer; fLarger: Boolean; lprc: TRECT); function ToolBar_SetState(hToolBar: HWND; idButton: wParam; fState: lParam): BOOL; procedure ToolBar_SetToolTips(hToolBar: HWND; hwndToolTip: HWND); { Tool Tip } procedure ToolTip_Activate(hToolTip: HWND; fActivate: Boolean); function ToolTip_AddTool(hToolTip: HWND; lpti: pTOOLINFO): BOOL; procedure ToolTip_DelTool(hToolTip: HWND; lpti: pTOOLINFO); function ToolTip_EnumTools(hToolTip: HWND; iTool: wParam; lpti: pTOOLINFO): BOOL; function ToolTip_GetCurrentTool(hToolTip: HWND; lpti: pTOOLINFO): BOOL; procedure ToolTip_GetText(hToolTip: HWND; lpti: pTOOLINFO); function ToolTip_GetToolCount(hToolTip: HWND): Integer; function ToolTip_GetToolInfo(hToolTip: HWND; lpti: pTOOLINFO): BOOL; function ToolTip_HitText(hToolTip: HWND; lphti: pTTHITTESTINFO): BOOL; procedure ToolTip_NewToolRect(hToolTip: HWND; lpti: pTOOLINFO); procedure ToolTip_RelayEvent(hToolTip: HWND; lpmsg: pMSG); procedure ToolTip_SetDelayTime(hToolTip: HWND; uFlag: wParam; iDelay: lParam); procedure ToolTip_SetToolInfo(hToolTip: HWND; lpti: pTOOLINFO); procedure ToolTip_UpdateTipText(hToolTip: HWND; lpti: pTOOLINFO); function ToolTip_WindowFromPoint(hToolTip: HWND; lppt: pPOINT): HWND; { Track Bar } procedure TrackBar_ClearSel(hTrackBar: HWND; fRedraw: Boolean); procedure TrackBar_ClearTics(hTrackBar: HWND; fRedraw: Boolean); procedure TrackBar_GetChannelRect(hTrackBar: HWND; lprc: tRECT); function TrackBar_GetLineSize(hTrackBar: HWND): Integer; function TrackBar_GetNumTics(hTrackBar: HWND): Integer; function TrackBar_GetPageSize(hTrackBar: HWND): Integer; function TrackBar_GetPos(hTrackBar: HWND): Integer; function TrackBar_GetPTics(hTrackBar: HWND): Integer; function TrackBar_GetRangeMax(hTrackBar: HWND): Integer; function TrackBar_GetRangeMin(hTrackBar: HWND): Integer; function TrackBar_GetSelEnd(hTrackBar: HWND): Integer; function TrackBar_GetSelStart(hTrackBar: HWND): Integer; function TrackBar_GetThumbLength(hTrackBar: HWND): UINT; procedure TrackBar_GetThumbRect(hTrackBar: HWND; lprc: tRECT); function TrackBar_GetTic(hTrackBar: HWND; iTic: wParam): Integer; function TrackBar_GetTicPos(hTrackBar: HWND; iTic: wParam): Integer; function TrackBar_SetLineSize(hTrackBar: HWND; lLineSize: lParam): Integer; function TrackBar_SetPageSize(hTrackBar: HWND; lPageSize: lParam): Integer; procedure TrackBar_SetPos(hTrackBar: HWND; bPosition: Boolean; lPosition: Integer); procedure TrackBar_SetRange(hTrackBar: HWND; bRedraw: Boolean; lMinimum, lMaximum: Integer); procedure TrackBar_SetRangeMax(hTrackBar: HWND; bRedraw: Boolean; lMaximum: Integer); procedure TrackBar_SetRangeMin(hTrackBar: HWND; bRedraw: Boolean; lMinimum: Integer); procedure TrackBar_SetSel(hTrackBar: HWND; bRedraw: Boolean; lMinimum, lMaximum: Integer); procedure TrackBar_SetSelEnd(hTrackBar: HWND; bRedraw: Boolean; lEnd: lParam); procedure TrackBar_SetSelStart(hTrackBar: HWND; bRedraw: Boolean; lStart: lParam); procedure TrackBar_SetThumbLength(hTrackBar: HWND; iLength: UINT); function TrackBar_SetTic(hTrackBar: HWND; lPosition: Integer): BOOL; procedure TrackBar_SetTicFreq(hTrackBar: HWND; wFreq: wParam; lPosition: Integer); { Up-Down} function UpDown_CreateControl(hWin, hControl: HWND; ID, Min, Max, Value: Integer): HWND; function UpDown_GetAccel(hUpDown: HWND; wAccels: WParam; lAccels: LParam): Integer; function UpDown_GetBase(hUpDown: HWND): Integer; function UpDown_GetBuddy(hUpDown: HWND): HWND; function UpDown_GetPos(hUpDown: HWND): DWORD; function UpDown_GetRange(hUpDown: HWND): DWORD; function UpDown_SetAccel(hUpDown: HWND; wAccels: WParam; lAccels: LParam): BOOL; function UpDown_SetBase(hUpDown: HWND; wBase: WParam): Integer; function UpDown_SetBuddy(hUpDown, hBuddy: HWND): HWND; function UpDown_SetPos(hUpDown: HWND; nPos: LParam): short; //Установка минимальной и максимальной позиции UpDown function UpDown_SetRange(hUpDown: HWND; nUpper, nLower: short): short; implementation //------------------------------------------------------------------- // Menu Helper Macros //------------------------------------------------------------------- function Menu_GetChecked(menu: HMENU; id: DWORD): Boolean; begin Result := (GetMenuState(menu, id, MF_BYCOMMAND) and MF_CHECKED) = MF_CHECKED; end; procedure Menu_SetChecked(menu: HMENU; id: DWORD; check: Boolean); begin case check of True: CheckMenuItem(menu, id, MF_BYCOMMAND or MF_CHECKED); else CheckMenuItem(menu, id, MF_BYCOMMAND or MF_UNCHECKED); end; end; function Menu_IsEnabled(menu: HMENU; id: DWORD): Boolean; begin result := (GetMenuState(menu, id, MF_BYCOMMAND) and MF_ENABLED) = MF_ENABLED; end; procedure Menu_SetEnabled(menu: HMENU; id: DWORD; enable: Boolean); var mii: TMENUITEMINFO; begin mii.cbSize := sizeof(mii); mii.fMask := MIIM_STATE; GetMenuItemInfo(menu, id, False, mii); case enable of True: mii.fState := mii.fState and (not MFS_DISABLED); else mii.fState := mii.fState or (MFS_DISABLED); end; mii.fMask := MIIM_STATE; SetMenuItemInfo(menu, id, False, mii); end; //------------------------------------------------------------------- // Other Helper Macros //------------------------------------------------------------------- function GetAssociatedIconExt(const Extension: string; Small: Boolean): hIcon; var Info: TSHFileInfo; Flags: Cardinal; begin if Small then Flags := SHGFI_ICON or SHGFI_SMALLICON or SHGFI_USEFILEATTRIBUTES else Flags := SHGFI_ICON or SHGFI_LARGEICON or SHGFI_USEFILEATTRIBUTES; SHGetFileInfo(PChar(Extension), FILE_ATTRIBUTE_NORMAL, Info, SizeOf(TSHFileInfo), Flags); Result := Info.hIcon; end; function GetAssociatedIcon(FileName: String; IconIndex: Word): hIcon; begin Result := ExtractAssociatedIcon(HInstance, PChar(FileName), IconIndex); end; function Static_SetBitmap(hControl: HWND; ResId: Integer): Boolean; var hBmp: hBitmap; begin hBmp := LoadBitmap(hInstance, MAKEINTRESOURCE(ResId)); Result := BOOL(SendMessage(hControl, STM_SETIMAGE, IMAGE_BITMAP, hBmp)); end; function SetNewFont(hWindow: HWND; FontSize, Weight: Integer; FontName: String): Boolean; var Fnt: hFont; DC: HDC; begin DC := GetWindowDC(hWindow); Fnt := CreateFont(-MulDiv(FontSize, GetDeviceCaps(DC, LOGPIXELSY), 72), 0, 0, 0, Weight, 0, 0, 0, ANSI_CHARSET or RUSSIAN_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH or FF_MODERN, PChar(FontName)); Result := BOOL(SendMessage(hWindow, WM_SETFONT, Fnt, Ord(True))); end; function EnableDlgItem(Dlg: HWND; ctrlID: Integer; bEnable: boolean): BOOL; begin Result := EnableWindow(GetDlgItem(Dlg, ctrlID), bEnable); end; //------------------------------------------------------------------- // Edit Helper Macros //------------------------------------------------------------------- //Определение текста в Edit function Edit_GetText(hEdit: HWND): String; var buffer: array[0..1024] of Char; begin SendMessage(hEdit, WM_GETTEXT, SizeOf(buffer), Integer(@buffer)); Result := buffer; end; //Установка текста в Edit procedure Edit_SetText(hEdit: HWND; Text: String); begin SendMessage(hEdit, WM_SETTEXT, 0, Integer(PChar(@Text[1]))); end; procedure Edit_SetLimitText(hEdit: HWND; Limit: Integer); begin SendMessage(hEdit, EM_SETLIMITTEXT, Limit, 0); end; procedure Edit_SetPassword(hEdit: HWND; Character: Char); begin SendMessage(hEdit, EM_SETPASSWORDCHAR, Integer(Character), 0); end; function Edit_SetReadOnly(hEdit: HWND; ReadOnly: BOOL): Integer; begin Result := SendMessage(hEdit, EM_SETREADONLY, Integer(ReadOnly), 0); end; //------------------------------------------------------------------- // Resources Helper Macros //------------------------------------------------------------------- //Установка значка на Button из ресурсов программы //window style = BS_ICON function Button_SetIcon(hButton: HWND; ResId, Width, Height: Integer): HWND; var Ico: hIcon; begin Ico := LoadImage(hInstance, MAKEINTRESOURCE(ResId), IMAGE_ICON, Width, Height, LR_DEFAULTCOLOR); Result := SendMessage(hButton, BM_SETIMAGE, IMAGE_ICON, Ico); end; //Установка картинки на Button из ресурсов программы //window style = BS_BITMAP function Button_SetBitmap(hButton: HWND; ResId, Width, Height: Integer): HWND; var Bmp: hBitmap; begin Bmp := LoadImage(hInstance, MAKEINTRESOURCE(ResId), IMAGE_BITMAP, Width, Height, LR_DEFAULTCOLOR); Result := SendMessage(hButton, BM_SETIMAGE, IMAGE_BITMAP, Bmp); end; //------------------------------------------------------------------- // CheckBox Helper Macros //------------------------------------------------------------------- //Определяем состояние CheckBox //0 = UnCheck; 1 = Check; 2 = Check and Grayed function CheckBox_GetCheck(hCheckBox: HWND): Integer; begin Result := SendMessage(hCheckBox, BM_GETCHECK, 0, 0); end; //Устанавливаем состояние CheckBox //UnCheck = 0; Check = 1; Check and Grayed = 2 procedure CheckBox_SetCheck(hCheckBox: HWND; Check: Integer); begin SendMessage(hCheckBox, BM_SETCHECK, Check, 0); end; //------------------------------------------------------------------- // ListView Helper Macros //------------------------------------------------------------------- //Получаем имя выбранного пункта ListView function ListView_GetItemName(hListView: HWND): String; var buf: array [0..MAX_PATH] of char; i: Integer; begin i := ListView_GetNextItem(hListView, -1, LVNI_FOCUSED); if (i > -1) then begin ZeroMemory(@buf, sizeof(buf)); ListView_GetItemText(hListView, i, 0, buf, sizeof(buf)); if buf[0] <> #0 then Result := buf; end; end; //Разрешаем редактировать выбранный пункт ListView procedure ListView_SetEditItem(hListView: HWND); var i: Integer; begin i := ListView_GetNextItem(hListView, -1, LVNI_FOCUSED); if (i > -1) then begin SetFocus(hListView); ListView_EditLabel(hListView, i); end; end; //Выбираем все файлы в ListView. Если fTurnSelection = True, уже отмеченные файлы не выбираем. procedure ListView_SelectAllItems(hListView: HWND; fTurnSelection: boolean); const fStateState : array [boolean] of cardinal = (0, LVIS_SELECTED); var i: integer; uRes: UINT; begin for i := 0 to ListView_GetItemCount(hListView) - 1 do begin uRes := ListView_GetItemState(hListView, i, LVIS_SELECTED); ListView_SetItemState(hListView, i, fStateState[(uRes and LVIS_SELECTED = 0) or not fTurnSelection], LVIS_SELECTED); end; end; //------------------------------------------------------------------- // ListBox Helper Macros //------------------------------------------------------------------- //Определение колличества пунктов в ListBox function ListBox_GetItemCount(hListBox: HWND): Integer; begin Result := SendMessage(hListBox, LB_GETCOUNT, 0, 0); end; //Удаление определенного пункта в ListBox procedure ListBox_DeleteItem(hListBox: HWND; Index: Integer); begin SendMessage(hListBox, LB_DELETESTRING, Index, 0); end; //Удаление всех пунктов в ListBox procedure ListBox_ClearItems(hListBox: HWND); begin SendMessage(hListBox, LB_RESETCONTENT, 0, 0); end; //Добавление пункта в ListBox procedure ListBox_AddItem(hListBox: HWND; NewItem: String); begin SendMessage(hListBox, LB_ADDSTRING, 0, Integer(NewItem)); end; //Добавление пункта в определенное место в ListBox procedure ListBox_InsertItem(hListBox: HWND; Index: Integer; NewItem: String); begin SendMessage(hListBox, LB_INSERTSTRING, Index, Integer(NewItem)); end; //Определение имени выделеного пункта в ListBox function ListBox_GetSelectedItem(hListBox: HWND): string; var Index, len: Integer; s: string; buffer: PChar; begin Index := SendMessage(hListBox, LB_GETCURSEL, 0, 0); len := SendMessage(hListBox, LB_GETTEXTLEN, wParam(Index), 0); GetMem(buffer, len + 1); SendMessage(hListBox, LB_GETTEXT, wParam(Index), lParam(buffer)); SetString(s, buffer, len); FreeMem(buffer); Result := s; end; //Определение номера выделеного пункта в ListBox function ListBox_GetCountSelectedItem(hListBox: HWND): Integer; var Index, len: Integer; s: string; buffer: PChar; begin Index := SendMessage(hListBox, LB_GETCURSEL, 0, 0); len := SendMessage(hListBox, LB_GETTEXTLEN, wParam(Index), 0); GetMem(buffer, len + 1); SendMessage(hListBox, LB_GETTEXT, wParam(Index), lParam(buffer)); SetString(s, buffer, len); FreeMem(buffer); Result := Index; end; //Определение имени пункта по номеру в ListBox function ListBox_GetItem(hListBox: HWND; LbItem: Integer): string; var l: Integer; buffer: PChar; begin l := SendMessage(hListBox, LB_GETTEXTLEN, LbItem, 0); GetMem(buffer, l + 1); SendMessage(hListBox, LB_GETTEXT, LbItem, Integer(buffer)); Result := StrPas(buffer); FreeMem(buffer); end; //Выделение всех пунктов в ListBox procedure ListBox_SelAllItems(hListBox: HWND); var CountItems, i: Integer; begin CountItems := SendMessage(hListBox, LB_GETCOUNT, 0, 0); if CountItems = 0 then exit; for i := 0 to CountItems do SendMessage(hListBox, LB_SETSEL, Integer(true), i); end; //Выбор пункта procedure ListBox_SelectedItem(hListBox: HWND; Index: Integer); begin SendMessage(hListBox, LB_SETCURSEL, Index, 0); end; //------------------------------------------------------------------- // ComboBox Helper Macros //------------------------------------------------------------------- //Определение колличества пунктов в ComboBox function ComboBox_GetItemCount(hComboBox: HWND): Integer; begin Result := SendMessage(hComboBox, CB_GETCOUNT, 0, 0); end; //Удаление определенного пункта в ComboBox procedure ComboBox_DeleteItem(hComboBox: HWND; Index: Integer); begin SendMessage(hComboBox, CB_DELETESTRING, Index, 0); end; //Удаление всех пунктов в ComboBox procedure ComboBox_ClearItems(hComboBox: HWND); begin SendMessage(hComboBox, CB_RESETCONTENT, 0, 0); end; //Добавление пункта в ComboBox procedure ComboBox_AddItem(hComboBox: HWND; NewItem: String); begin SendMessage(hComboBox, CB_ADDSTRING, 0, Integer(NewItem)); end; //Добавление пункта в определенное место в ComboBox procedure ComboBox_InsertItem(hComboBox: HWND; Index: Integer; NewItem: String); begin SendMessage(hComboBox, CB_INSERTSTRING, Index, Integer(NewItem)); end; //Определение имени выбранного пункта в ComboBox function ComboBox_GetSelectedItem(hComboBox: HWND): string; var Index, len: Integer; s: string; buffer: PChar; begin Index := SendMessage(hComboBox, CB_GETCURSEL, 0, 0); len := SendMessage(hComboBox, CB_GETLBTEXTLEN, wParam(Index), 0); GetMem(buffer, len + 1); SendMessage(hComboBox, CB_GETLBTEXT, wParam(Index), lParam(buffer)); SetString(s, buffer, len); FreeMem(buffer); Result := s; end; //Определение номера выбранного пункта в ComboBox function ComboBox_GetCountSelectedItem(hComboBox: HWND): Integer; var Index, len: Integer; s: string; buffer: PChar; begin Index := SendMessage(hComboBox, CB_GETCURSEL, 0, 0); len := SendMessage(hComboBox, CB_GETLBTEXTLEN, wParam(Index), 0); GetMem(buffer, len + 1); SendMessage(hComboBox, CB_GETLBTEXT, wParam(Index), lParam(buffer)); SetString(s, buffer, len); FreeMem(buffer); Result := Index; end; //Определение имени пункта по номеру в ComboBox function ComboBox_GetItem(hComboBox: HWND; LbItem: Integer): string; var l: Integer; buffer: PChar; begin l := SendMessage(hComboBox, CB_GETLBTEXTLEN, LbItem, 0); GetMem(buffer, l + 1); SendMessage(hComboBox, CB_GETLBTEXT, LbItem, Integer(buffer)); Result := StrPas(buffer); FreeMem(buffer); end; //Выбор пункта в ComboBox по счету procedure ComboBox_SelectedItem(hComboBox: HWND; Index: Integer); begin SendMessage(hComboBox, CB_SETCURSEL, Index, 0); end; //Выбор пункта в ComboBox по имени procedure ComboBox_SelectedString(hComboBox: HWND; Text: String); begin SendMessage(hComboBox, CB_SELECTSTRING, 0, Integer(Text)); end; //Открытие пунктов ComboBox procedure ComboBox_OpenItems(hComboBox: HWND); begin SendMessage(hComboBox, CB_SHOWDROPDOWN, Integer(True), 0); end; //------------------------------------------------------------------- // Hot-Key Helper Macros //------------------------------------------------------------------- procedure HotKey_SetHotKey(hHotKey: HWND; bVKHotKey: wParam; bfMods: lParam); begin SendMessage(hHotKey, HKM_SETHOTKEY, MAKEWORD(bVKHotKey, bfMods), 0); end; function HotKey_GetHotKey(hHotKey: HWND): WORD; begin Result := SendMessage(hHotKey, HKM_GETHOTKEY, 0, 0); end; procedure HotKey_SetRules(hHotKey: HWND; fwCombInv: wParam; fwModInv: lParam); begin SendMessage(hHotKey, HKM_SETRULES, fwCombInv, MAKELPARAM(fwModInv, 0)); end; //------------------------------------------------------------------- // Progress Bar Helper Macros //------------------------------------------------------------------- //Установка минимальной и максимальной позиции ProgressBar function Progress_SetRange(hProgress: HWND; nMinRange: wParam; nMaxRange: lParam): DWORD; begin Result := SendMessage(hProgress, PBM_SETRANGE, 0, MAKELPARAM(nMinRange, nMaxRange)); end; //Устанавливаем позицию ProgressBar function Progress_SetPos(hProgress: HWND; nNewPos: wParam): Integer; begin Result := SendMessage(hProgress, PBM_SETPOS, nNewPos, 0); end; //Получаем позицию ProgressBar function Progress_GetPos(hProgress: HWND): Integer; begin Result := SendMessage(hProgress, PBM_GETPOS, 0, 0); end; function Progress_DeltaPos(hProgress: HWND; nIncrement: wParam): Integer; begin Result := SendMessage(hProgress, PBM_DELTAPOS, nIncrement, 0); end; //Установка шага продвижения ProgressBar function Progress_SetStep(hProgress: HWND; nStepInc: wParam): Integer; begin Result := SendMessage(hProgress, PBM_SETSTEP, nStepInc, 0); end; function Progress_StepIt(hProgress: HWND): Integer; begin Result := SendMessage(hProgress, PBM_STEPIT, 0, 0); end; procedure Progress_SetLineColor(hProgress: HWND; Color: COLORREF); begin SendMessage(hProgress, PBM_SETBKCOLOR, 0, Color); end; //Progress_SetBarColor(ProgressBar1.Handle, RGB(0, 100, 208)); procedure Progress_SetBarColor(hProgress: HWND; Color: COLORREF); begin SendMessage(hProgress, PBM_SETBARCOLOR, 0, Color); end; //------------------------------------------------------------------- // Rich Edit Control Helper Macros //------------------------------------------------------------------- function RichEdit_Enable(hRichEdit: HWND; fEnable: Bool): BOOL; begin Result := EnableWindow(hRichEdit, fEnable); end; function RichEdit_GetText(hRichEdit: HWND): String; var lpch: String; begin GetWindowText(hRichEdit, PChar(lpch), SizeOf(lpch)); Result := lpch; end; function RichEdit_GetTextLength(hRichEdit: HWND): Integer; begin Result := GetWindowTextLength(hRichEdit); end; function RichEdit_SetText(hRichEdit: HWND; lpsz: PChar): BOOL; begin Result := SetWindowText(hRichEdit, lpsz); end; procedure RichEdit_LimitText(hRichEdit: HWND; cchMax: wParam); begin SendMessage(hRichEdit, EM_LIMITTEXT, cchMax, 0); end; function RichEdit_GetLineCount(hRichEdit: HWND): Integer; begin Result := SendMessage(hRichEdit, EM_GETLINECOUNT, 0, 0); end; function RichEdit_GetLine(hRichEdit: HWND; line: wParam; lpch: LPCSTR): Integer; begin Result := SendMessage(hRichEdit, EM_GETLINE, line, Integer(PChar(lpch))); end; procedure RichEdit_GetRect(hRichEdit: HWND; lprc: tRECT); begin SendMessage(hRichEdit, EM_GETRECT, 0, Integer(@lprc)); end; procedure RichEdit_SetRect(hRichEdit: HWND; lprc: tRECT); begin SendMessage(hRichEdit, EM_SETRECT, 0, Integer(@lprc)); end; function RichEdit_GetSel(hRichEdit: HWND): DWORD; begin Result := SendMessage(hRichEdit, EM_GETSEL, 0, 0); end; procedure RichEdit_SetSel(hRichEdit: HWND; ichStart, ichEnd: Integer); begin SendMessage(hRichEdit, EM_SETSEL, ichStart, ichEnd); end; procedure RichEdit_ReplaceSel(hRichEdit: HWND; lpszReplace: LPCSTR); begin SendMessage(hRichEdit, EM_REPLACESEL, 0, Integer(PChar(lpszReplace))); end; function RichEdit_GetModify(hRichEdit: HWND): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_GETMODIFY, 0, 0)); end; procedure RichEdit_SetModify(hRichEdit: HWND; fModified: UINT); begin SendMessage(hRichEdit, EM_SETMODIFY, fModified, 0); end; function RichEdit_ScrollCaret(hRichEdit: HWND): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SCROLLCARET, 0, 0)); end; function RichEdit_LineFromChar(hRichEdit: HWND; ich: Integer): Integer; begin Result := SendMessage(hRichEdit, EM_LINEFROMCHAR, ich, 0); end; function RichEdit_LineIndex(hRichEdit: HWND; line: Integer): Integer; begin Result := SendMessage(hRichEdit, EM_LINEINDEX, line, 0); end; function RichEdit_LineLength(hRichEdit: HWND; line: Integer): Integer; begin Result := SendMessage(hRichEdit, EM_LINELENGTH, line, 0); end; procedure RichEdit_Scroll(hRichEdit: HWND; dv: wParam; dh: lParam); begin SendMessage(hRichEdit, EM_LINESCROLL, dh, dv); end; function RichEdit_CanUndo(hRichEdit: HWND): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_CANUNDO, 0, 0)); end; function RichEdit_Undo(hRichEdit: HWND): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_UNDO, 0, 0)); end; procedure RichEdit_EmptyUndoBuffer(hRichEdit: HWND); begin SendMessage(hRichEdit, EM_EMPTYUNDOBUFFER, 0, 0); end; function RichEdit_GetFirstVisibleLine(hRichEdit: HWND): Integer; begin Result := SendMessage(hRichEdit, EM_GETFIRSTVISIBLELINE, 0, 0); end; function RichEdit_SetReadOnly(hRichEdit: HWND; fReadOnly: Boolean): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SETREADONLY, Integer(fReadOnly), 0)); end; procedure RichEdit_SetWordBreakProc(hRichEdit: HWND; lpfnWordBreak: Pointer); begin SendMessage(hRichEdit, EM_SETWORDBREAKPROC, 0, Integer(lpfnWordBreak)); end; function RichEdit_GetWordBreakProc(hRichEdit: HWND): Pointer; begin Result := Pointer(SendMessage(hRichEdit, EM_GETWORDBREAKPROC, 0, 0)); end; function RichEdit_CanPaste(hRichEdit: HWND; uFormat: UINT): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_CANPASTE, uFormat, 0)); end; function RichEdit_CharFromPos(hRichEdit: HWND; x, y: Integer): DWORD; begin Result := SendMessage(hRichEdit, EM_CHARFROMPOS, 0, MAKELPARAM(x, y)); end; function RichEdit_DisplayBand(hRichEdit: HWND; lprc: tRECT): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_DISPLAYBAND, 0, Integer(@lprc))); end; procedure RichEdit_ExGetSel(hRichEdit: HWND; lpchr: TCharRange); begin SendMessage(hRichEdit, EM_EXGETSEL, 0, LPARAM(@lpchr)); end; procedure RichEdit_ExLimitText(hRichEdit: HWND; cchTextMax: Dword); begin SendMessage(hRichEdit, EM_EXLIMITTEXT, 0, cchTextMax); end; function RichEdit_ExLineFromChar(hRichEdit: HWND; ichCharPos: Dword): Integer; begin Result := SendMessage(hRichEdit, EM_EXLINEFROMCHAR, 0, ichCharPos); end; function RichEdit_ExSetSel(hRichEdit: HWND; ichCharRange: TCharRange): Integer; begin Result := SendMessage(hRichEdit, EM_EXSETSEL, 0, LPARAM(@ichCharRange)); end; function RichEdit_FindText(hRichEdit: HWND; fuFlags: UINT; lpFindText: tFINDTEXT): Integer; begin Result := SendMessage(hRichEdit, EM_FINDTEXT, fuFlags, LPARAM(@lpFindText)); end; function RichEdit_FindTextEx(hRichEdit: HWND; fuFlags: UINT; lpFindText: tFINDTEXT): Integer; begin Result := SendMessage(hRichEdit, EM_FINDTEXTEX, fuFlags, LPARAM(@lpFindText)); end; function RichEdit_FindWordBreak(hRichEdit: HWND; code: UINT; ichStart: Dword): Integer; begin Result := SendMessage(hRichEdit, EM_FINDWORDBREAK, code, ichStart); end; function RichEdit_FormatRange(hRichEdit: HWND; fRender: Boolean; lpFmt: tFORMATRANGE): Integer; begin Result := SendMessage(hRichEdit, EM_FORMATRANGE, Integer(fRender), Integer(@lpFmt)); end; function RichEdit_GetCharFormat(hRichEdit: HWND; fSelection: Boolean; lpFmt: tCHARFORMAT): DWORD; begin Result := SendMessage(hRichEdit, EM_GETCHARFORMAT, Integer(fSelection), Integer(@lpFmt)); end; function RichEdit_GetEventMask(hRichEdit: HWND): DWORD; begin Result := SendMessage(hRichEdit, EM_GETEVENTMASK, 0, 0); end; function RichEdit_GetLimitText(hRichEdit: HWND): Integer; begin Result := SendMessage(hRichEdit, EM_GETLIMITTEXT, 0, 0); end; function RichEdit_GetOleInterface(hRichEdit: HWND; ppObject: lParam): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_GETOLEINTERFACE, 0, ppObject)); end; function RichEdit_GetOptions(hRichEdit: HWND): UINT; begin Result := SendMessage(hRichEdit, EM_GETOPTIONS, 0, 0); end; function RichEdit_GetParaFormat(hRichEdit: HWND; lpFmt: tPARAFORMAT): DWORD; begin Result := SendMessage(hRichEdit, EM_GETPARAFORMAT, 0, Integer(@lpFmt)); end; function RichEdit_GetSelText(hRichEdit: HWND; lpBuf: LPSTR): Integer; begin Result := SendMessage(hRichEdit, EM_GETSELTEXT, 0, Integer(@lpBuf)); end; function RichEdit_GetTextRange(hRichEdit: HWND; lpRange: tTEXTRANGE): Integer; begin Result := SendMessage(hRichEdit, EM_GETTEXTRANGE, 0, Integer(@lpRange)); end; function RichEdit_GetWordBreakProcEx(hRichEdit: HWND): Integer; begin Result := SendMessage(hRichEdit, EM_GETWORDBREAKPROCEX, 0, 0); end; //----------------- End Macros Copied from windowsx.h---------------- procedure RichEdit_HideSelection(hRichEdit: HWND; fHide: Boolean; fChangeStyle: Boolean); begin SendMessage(hRichEdit, EM_HIDESELECTION, Integer(fHide), Integer(fChangeStyle)); end; procedure RichEdit_PasteSpecial(hRichEdit: HWND; uFormat: UINT); begin SendMessage(hRichEdit, EM_PASTESPECIAL, uFormat, 0); end; function RichEdit_PosFromChar(hRichEdit: HWND; wCharIndex: wParam): DWORD; begin Result := SendMessage(hRichEdit, EM_POSFROMCHAR, wCharIndex, 0); end; procedure RichEdit_RequestResize(hRichEdit: HWND); begin SendMessage(hRichEdit, EM_REQUESTRESIZE, 0, 0); end; function RichEdit_SelectionType(hRichEdit: HWND): Integer; begin Result := SendMessage(hRichEdit, EM_SELECTIONTYPE, 0, 0); end; function RichEdit_SetBkgndColor(hRichEdit: HWND; fUseSysColor: Boolean; clr: tCOLORREF): tCOLORREF; begin Result := SendMessage(hRichEdit, EM_SETBKGNDCOLOR, Integer(fUseSysColor), clr); end; function RichEdit_SetCharFormat(hRichEdit: HWND; uFlags: UINT; lpFmt: tCHARFORMAT): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SETCHARFORMAT, uFlags, Integer(@lpFmt))); end; function RichEdit_SetEventMask(hRichEdit: HWND; dwMask: Dword): DWORD; begin Result := SendMessage(hRichEdit, EM_SETEVENTMASK, 0, dwMask); end; function RichEdit_SetOleCallback(hRichEdit: HWND; lpObj: lParam): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SETOLECALLBACK, 0, lpObj)); end; function RichEdit_SetOptions(hRichEdit: HWND; fOperation: UINT; fOptions: UINT): UINT; begin Result := SendMessage(hRichEdit, EM_SETOPTIONS, fOperation, fOptions); end; function RichEdit_SetParaFormat(hRichEdit: HWND; lpFmt: tPARAFORMAT): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SETPARAFORMAT, 0, Integer(@lpFmt))); end; function RichEdit_SetTargetDevice(hRichEdit: HWND; hdcTarget: HDC; cxLineWidth: Integer): BOOL; begin Result := LongBool(SendMessage(hRichEdit, EM_SETTARGETDEVICE, hdcTarget, cxLineWidth)); end; function RichEdit_SetWordBreakProcEx(hRichEdit: HWND; pfnWordBreakProcEx: Integer): Integer; begin Result := SendMessage(hRichEdit, EM_SETWORDBREAKPROCEX, 0, pfnWordBreakProcEx); end; function RichEdit_StreamIn(hRichEdit: HWND; uFormat: UINT; lpStream: tEDITSTREAM): Integer; begin Result := SendMessage(hRichEdit, EM_STREAMIN, uFormat, Integer(@lpStream)); end; function RichEdit_StreamOut(hRichEdit: HWND; uFormat: UINT; lpStream: tEDITSTREAM): Integer; begin Result := SendMessage(hRichEdit, EM_STREAMOUT, uFormat, Integer(@lpStream)); end; //------------------------------------------------------------------- // Status Bar Helper Macros //------------------------------------------------------------------- function Status_GetBorders(hStatus: HWND; aBorders: lParam): BOOL; begin Result := LongBool(SendMessage(hStatus, SB_GETBORDERS, 0, aBorders)); end; function Status_GetParts(hStatus: HWND; nParts: wParam; aRightCoord: lParam): Integer; begin Result := SendMessage(hStatus, SB_GETPARTS, nParts, aRightCoord); end; function Status_GetRect(hStatus: HWND; iPart: wParam; lprc: lParam): BOOL; begin Result := LongBool(SendMessage(hStatus, SB_GETRECT, iPart, lprc)); end; function Status_GetText(hStatus: HWND; iPart: wParam): String; var buffer: array[0..1024] of Char; begin SendMessage(hStatus, SB_GETTEXT, iPart, Longint(@buffer)); Result := buffer; end; function Status_GetTextLength(hStatus: HWND; iPart: wParam): DWORD; begin Result := SendMessage(hStatus, SB_GETTEXTLENGTH, iPart, 0); end; procedure Status_SetMinHeight(hStatus: HWND; minHeight: wParam); begin SendMessage(hStatus, SB_SETMINHEIGHT, minHeight, 0); end; function Status_SetParts(hStatus: HWND; nParts: wParam; aWidths: lParam): BOOL; begin Result := LongBool(SendMessage(hStatus, SB_SETPARTS, nParts, aWidths)); end; function Status_SetText(hStatus: HWND; iPart: wParam; szText: LPSTR): BOOL; begin Result := LongBool(SendMessage(hStatus, SB_SETTEXT, iPart, Integer(szText))); end; function Status_Simple(hStatus: HWND; fSimple: Boolean): BOOL; begin Result := LongBool(SendMessage(hStatus, SB_SIMPLE, Integer(fSimple), 0)); end; //------------------------------------------------------------------- // Tool Bar Helper Macros //------------------------------------------------------------------- function ToolBar_AddBitmap(hToolBar: HWND; nButtons: wParam; lptbab: tTBADDBITMAP): Integer; begin Result := SendMessage(hToolBar, TB_ADDBITMAP, nButtons, Integer(@lptbab)); end; function ToolBar_AddButtons(hToolBar: HWND; uNumButtons: UINT; lpButtons: tTBBUTTON): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_ADDBUTTONS, uNumButtons, Integer(@lpButtons))); end; function ToolBar_AddString(hToolBar: HWND; hst: HInst; idString: Word): Integer; begin Result := SendMessage(hToolBar, TB_ADDSTRING, hst, MAKELONG(idString, 0)); end; procedure ToolBar_AutoSize(hToolBar: HWND); begin SendMessage(hToolBar, TB_AUTOSIZE, 0, 0); end; function ToolBar_ButtonCount(hToolBar: HWND): Integer; begin Result := SendMessage(hToolBar, TB_BUTTONCOUNT, 0, 0); end; procedure ToolBar_ButtonStructSize(hToolBar: HWND); begin SendMessage(hToolBar, TB_BUTTONSTRUCTSIZE, sizeof(tTBBUTTON), 0); end; function ToolBar_ChangeBitmap(hToolBar: HWND; idButton: wParam; iBitmap: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_CHANGEBITMAP, idButton, iBitmap)); end; function ToolBar_CheckButton(hToolBar: HWND; idButton: wParam; fCheck: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_CHECKBUTTON, idButton, MAKELONG(fCheck, 0))); end; function ToolBar_CommandToIndex(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_COMMANDTOINDEX, idButton, 0); end; procedure ToolBar_Customize(hToolBar: HWND); begin SendMessage(hToolBar, TB_CUSTOMIZE, 0, 0); end; function ToolBar_DeleteButton(hToolBar: HWND; idButton: wParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_DELETEBUTTON, idButton, 0)); end; function ToolBar_EnableButton(hToolBar: HWND; idButton: wParam; fEnable: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_ENABLEBUTTON, idButton, MAKELONG(fEnable, 0))); end; function ToolBar_GetBitmap(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_GETBITMAP, idButton, 0); end; function ToolBar_GetBitmapFlags(hToolBar: HWND): Integer; begin Result := SendMessage(hToolBar, TB_GETBITMAPFLAGS, 0, 0); end; function ToolBar_GetButton(hToolBar: HWND; idButton: wParam; lpButton: tTBBUTTON): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_GETBUTTON, idButton, Integer(@lpButton))); end; function ToolBar_GetButtonText(hToolBar: HWND; idButton: wParam; lpszText: LPSTR): Integer; begin Result := SendMessage(hToolBar, TB_GETBUTTONTEXT, idButton, Integer(lpszText)); end; function ToolBar_GetItemRect(hToolBar: HWND; idButton: wParam; lprc: tRECT): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_GETITEMRECT, idButton, Integer(@lprc))); end; function ToolBar_GetRows(hToolBar: HWND): Integer; begin Result := SendMessage(hToolBar, TB_GETROWS, 0, 0); end; function ToolBar_GetState(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_GETSTATE, idButton, 0); end; function ToolBar_GetToolTips(hToolBar: HWND): HWND; begin Result := SendMessage(hToolBar, TB_GETTOOLTIPS, 0, 0); end; function ToolBar_HideButton(hToolBar: HWND; idButton: wParam; fShow: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_HIDEBUTTON, idButton, MAKELONG(fShow, 0))); end; function ToolBar_Indeterminate(hToolBar: HWND; idButton: wParam; fIndeterminate: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_INDETERMINATE, idButton, MAKELONG(fIndeterminate, 0))); end; function ToolBar_InsertButton(hToolBar: HWND; idButton: wParam; lpButton: tTBBUTTON): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_INSERTBUTTON, idButton, Integer(@lpButton))); end; function ToolBar_IsButtonChecked(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_ISBUTTONCHECKED, idButton, 0); end; function ToolBar_IsButtonEnabled(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_ISBUTTONENABLED, idButton, 0); end; function ToolBar_IsButtonHidden(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_ISBUTTONHIDDEN, idButton, 0); end; function ToolBar_IsButtonIndeterminate(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_ISBUTTONINDETERMINATE, idButton, 0); end; function ToolBar_IsButtonPressed(hToolBar: HWND; idButton: wParam): Integer; begin Result := SendMessage(hToolBar, TB_ISBUTTONPRESSED, idButton, 0); end; function ToolBar_PressButton(hToolBar: HWND; idButton: wParam; fPress: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_PRESSBUTTON, idButton, MAKELONG(fPress, 0))); end; procedure ToolBar_SaveRestore(hToolBar: HWND; fSave: Boolean; ptbsp: tTBSAVEPARAMS); begin SendMessage(hToolBar, TB_SAVERESTORE, Integer(fSave), Integer(@ptbsp)); end; function ToolBar_SetBitmapSize(hToolBar: HWND; dxBitmap, dyBitmap: Integer): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_SETBITMAPSIZE, 0, MAKELONG(dxBitmap, dyBitmap))); end; function ToolBar_SetButtonSize(hToolBar: HWND; dxBitmap, dyBitmap: Integer): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_SETBUTTONSIZE, 0, MAKELONG(dxBitmap, dyBitmap))); end; function ToolBar_SetCmdID(hToolBar: HWND; index, cmdId: UINT): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_SETCMDID, index, cmdId)); end; procedure ToolBar_SetParent(hToolBar: HWND; hwndParent: HWND); begin SendMessage(hToolBar, TB_SETPARENT, hwndParent, 0); end; procedure ToolBar_SetRows(hToolBar: HWND; cRows: Integer; fLarger: Boolean; lprc: TRECT); begin SendMessage(hToolBar, TB_SETROWS, MAKEWPARAM(cRows, Integer(fLarger)), Integer(@lprc)); end; function ToolBar_SetState(hToolBar: HWND; idButton: wParam; fState: lParam): BOOL; begin Result := LongBool(SendMessage(hToolBar, TB_SETSTATE, idButton, MAKELONG(fState, 0))); end; procedure ToolBar_SetToolTips(hToolBar: HWND; hwndToolTip: HWND); begin SendMessage(hToolBar, TB_SETTOOLTIPS, hwndToolTip, 0); end; //------------------------------------------------------------------- // Tool Tip Helper Macros //------------------------------------------------------------------- procedure ToolTip_Activate(hToolTip: HWND; fActivate: Boolean); begin SendMessage(hToolTip, TTM_ACTIVATE, Integer(fActivate), 0); end; function ToolTip_AddTool(hToolTip: HWND; lpti: pTOOLINFO): BOOL; begin Result := LongBool(SendMessage(hToolTip, TTM_ADDTOOL, 0, Integer(lpti))); end; procedure ToolTip_DelTool(hToolTip: HWND; lpti: pTOOLINFO); begin SendMessage(hToolTip, TTM_DELTOOL, 0, Integer(lpti)); end; function ToolTip_EnumTools(hToolTip: HWND; iTool: wParam; lpti: pTOOLINFO): BOOL; begin Result := LongBool(SendMessage(hToolTip, TTM_ENUMTOOLS, iTool, Integer(lpti))); end; function ToolTip_GetCurrentTool(hToolTip: HWND; lpti: pTOOLINFO): BOOL; begin Result := LongBool(SendMessage(hToolTip, TTM_GETCURRENTTOOL, 0, Integer(@lpti))); end; procedure ToolTip_GetText(hToolTip: HWND; lpti: pTOOLINFO); begin SendMessage(hToolTip, TTM_GETTEXT, 0, Integer(@lpti)); end; function ToolTip_GetToolCount(hToolTip: HWND): Integer; begin Result := SendMessage(hToolTip, TTM_GETTOOLCOUNT, 0, 0); end; function ToolTip_GetToolInfo(hToolTip: HWND; lpti: pTOOLINFO): BOOL; begin Result := LongBool(SendMessage(hToolTip, TTM_GETTOOLINFO, 0, Integer(@lpti))); end; function ToolTip_HitText(hToolTip: HWND; lphti: pTTHITTESTINFO): BOOL; begin Result := LongBool(SendMessage(hToolTip, TTM_HITTEST, 0, Integer(lphti))); end; procedure ToolTip_NewToolRect(hToolTip: HWND; lpti: pTOOLINFO); begin SendMessage(hToolTip, TTM_NEWTOOLRECT, 0, Integer(lpti)); end; procedure ToolTip_RelayEvent(hToolTip: HWND; lpmsg: pMSG); begin SendMessage(hToolTip, TTM_RELAYEVENT, 0, Integer(lpmsg)); end; procedure ToolTip_SetDelayTime(hToolTip: HWND; uFlag: wParam; iDelay: lParam); begin SendMessage(hToolTip, TTM_SETDELAYTIME, uFlag, iDelay); end; procedure ToolTip_SetToolInfo(hToolTip: HWND; lpti: pTOOLINFO); begin SendMessage(hToolTip, TTM_SETTOOLINFO, 0, Integer(lpti)); end; procedure ToolTip_UpdateTipText(hToolTip: HWND; lpti: pTOOLINFO); begin SendMessage(hToolTip, TTM_UPDATETIPTEXT, 0, Integer(lpti)); end; function ToolTip_WindowFromPoint(hToolTip: HWND; lppt: pPOINT): HWND; begin Result := SendMessage(hToolTip, TTM_WINDOWFROMPOINT, 0, Integer(@lppt)); end; //------------------------------------------------------------------- // Track Bar Helper Macros //------------------------------------------------------------------- procedure TrackBar_ClearSel(hTrackBar: HWND; fRedraw: Boolean); begin SendMessage(hTrackBar, TBM_CLEARSEL, Integer(fRedraw), 0); end; procedure TrackBar_ClearTics(hTrackBar: HWND; fRedraw: Boolean); begin SendMessage(hTrackBar, TBM_CLEARTICS, Integer(fRedraw), 0); end; procedure TrackBar_GetChannelRect(hTrackBar: HWND; lprc: tRECT); begin SendMessage(hTrackBar, TBM_GETCHANNELRECT, 0, Integer(@lprc)); end; function TrackBar_GetLineSize(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETLINESIZE, 0, 0); end; function TrackBar_GetNumTics(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETNUMTICS, 0, 0); end; function TrackBar_GetPageSize(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETPAGESIZE, 0, 0); end; function TrackBar_GetPos(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETPOS, 0, 0); end; function TrackBar_GetPTics(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETPTICS, 0, 0); end; function TrackBar_GetRangeMax(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETRANGEMAX, 0, 0); end; function TrackBar_GetRangeMin(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETRANGEMIN, 0, 0); end; function TrackBar_GetSelEnd(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETSELEND, 0, 0); end; function TrackBar_GetSelStart(hTrackBar: HWND): Integer; begin Result := SendMessage(hTrackBar, TBM_GETSELSTART, 0, 0); end; function TrackBar_GetThumbLength(hTrackBar: HWND): UINT; begin Result := SendMessage(hTrackBar, TBM_GETTHUMBLENGTH, 0, 0); end; procedure TrackBar_GetThumbRect(hTrackBar: HWND; lprc: tRECT); begin SendMessage(hTrackBar, TBM_GETTHUMBRECT, 0, Integer(@lprc)); end; function TrackBar_GetTic(hTrackBar: HWND; iTic: wParam): Integer; begin Result := SendMessage(hTrackBar, TBM_GETTIC, iTic, 0); end; function TrackBar_GetTicPos(hTrackBar: HWND; iTic: wParam): Integer; begin Result := SendMessage(hTrackBar, TBM_GETTICPOS, iTic, 0); end; function TrackBar_SetLineSize(hTrackBar: HWND; lLineSize: lParam): Integer; begin Result := SendMessage(hTrackBar, TBM_SETLINESIZE, 0, lLineSize); end; function TrackBar_SetPageSize(hTrackBar: HWND; lPageSize: lParam): Integer; begin Result := SendMessage(hTrackBar, TBM_SETPAGESIZE, 0, lPageSize); end; procedure TrackBar_SetPos(hTrackBar: HWND; bPosition: Boolean; lPosition: Integer); begin SendMessage(hTrackBar, TBM_SETPOS, Integer(bPosition), lPosition); end; procedure TrackBar_SetRange(hTrackBar: HWND; bRedraw: Boolean; lMinimum, lMaximum: Integer); begin SendMessage(hTrackBar, TBM_SETRANGE, Integer(bRedraw), MAKELONG(lMinimum, lMaximum)); end; procedure TrackBar_SetRangeMax(hTrackBar: HWND; bRedraw: Boolean; lMaximum: Integer); begin SendMessage(hTrackBar, TBM_SETRANGEMAX, Integer(bRedraw), lMaximum); end; procedure TrackBar_SetRangeMin(hTrackBar: HWND; bRedraw: Boolean; lMinimum: Integer); begin SendMessage(hTrackBar, TBM_SETRANGEMIN, Integer(bRedraw), lMinimum); end; procedure TrackBar_SetSel(hTrackBar: HWND; bRedraw: Boolean; lMinimum, lMaximum: Integer); begin SendMessage(hTrackBar, TBM_SETSEL, Integer(bRedraw), MAKELONG(lMinimum, lMaximum)); end; procedure TrackBar_SetSelEnd(hTrackBar: HWND; bRedraw: Boolean; lEnd: lParam); begin SendMessage(hTrackBar, TBM_SETSELEND, Integer(bRedraw), lEnd); end; procedure TrackBar_SetSelStart(hTrackBar: HWND; bRedraw: Boolean; lStart: lParam); begin SendMessage(hTrackBar, TBM_SETSELSTART, Integer(bRedraw), lStart); end; procedure TrackBar_SetThumbLength(hTrackBar: HWND; iLength: UINT); begin SendMessage(hTrackBar, TBM_SETTHUMBLENGTH, iLength, 0); end; function TrackBar_SetTic(hTrackBar: HWND; lPosition: Integer): BOOL; begin Result := BOOL(SendMessage(hTrackBar, TBM_SETTIC, 0, lPosition)); end; procedure TrackBar_SetTicFreq(hTrackBar: HWND; wFreq: wParam; lPosition: Integer); begin SendMessage(hTrackBar, TBM_SETTICFREQ, wFreq, lPosition); end; //------------------------------------------------------------------- // Up / Down Control Helper Macros //------------------------------------------------------------------- function UpDown_CreateControl(hWin, hControl: HWND; ID, Min, Max, Value: Integer): HWND; begin Result := CreateUpDownControl(WS_CHILD or WS_BORDER or WS_VISIBLE or UDS_WRAP or UDS_ARROWKEYS or UDS_ALIGNRIGHT or UDS_SETBUDDYINT, 0, 0, 0, 0, hWin, ID, hInstance, hControl, Max, Min, Value); end; function UpDown_GetAccel(hUpDown: HWND; wAccels: WParam; lAccels: LParam): Integer; begin Result := SendMessage(hUpDown, UDM_GETACCEL, wAccels, lAccels); end; function UpDown_GetBase(hUpDown: HWND): Integer; begin Result := SendMessage(hUpDown, UDM_GETBASE, 0, 0); end; function UpDown_GetBuddy(hUpDown: HWND): HWND; begin Result := SendMessage(hUpDown, UDM_GETBUDDY, 0, 0); end; function UpDown_GetPos(hUpDown: HWND): DWORD; begin Result := LOWORD(SendMessage(hUpDown, UDM_GETPOS, 0, 0)); end; function UpDown_GetRange(hUpDown: HWND): DWORD; begin Result := DWORD(SendMessage(hUpDown, UDM_GETRANGE, 0, 0)); end; function UpDown_SetAccel(hUpDown: HWND; wAccels: WParam; lAccels: LParam): BOOL; begin Result := BOOL(SendMessage(hUpDown, UDM_SETACCEL, wAccels, lAccels)); end; function UpDown_SetBase(hUpDown: HWND; wBase: WParam): Integer; begin Result := SendMessage(hUpDown, UDM_SETBASE, wBase, 0); end; function UpDown_SetBuddy(hUpDown, hBuddy: HWND): HWND; begin Result := SendMessage(hUpDown, UDM_SETBUDDY, hBuddy, 0); end; function UpDown_SetPos(hUpDown: HWND; nPos: LParam): short; begin Result := SendMessage(hUpDown, UDM_SETPOS, 0, MAKELONG(nPos, 0)); end; //Установка минимальной и максимальной позиции UpDown function UpDown_SetRange(hUpDown: HWND; nUpper, nLower: short): short; begin Result := SendMessage(hUpDown, UDM_SETRANGE, 0, MAKELONG(nUpper, nLower)) end; end.
unit helper.image; interface uses FMX.Forms, FMX.StdCtrls, FMX.Objects; type TImageHelper = class helper for TImage procedure DownloadPNG(const AURL: string); end; implementation uses System.Classes, System.Threading, System.Net.URLClient, System.Net.HttpClient, System.Net.HttpClientComponent; procedure TImageHelper.DownloadPNG(const AURL: string); begin Self.Bitmap := nil; TThread.CreateAnonymousThread( procedure var Ms: TMemoryStream; HttpClient: TNetHTTPClient; begin HttpClient := TNetHTTPClient.Create(nil); try Ms := TMemoryStream.Create; try HttpClient.Get(AURL, Ms); TThread.Synchronize(nil, procedure begin Self.Bitmap.LoadFromStream(Ms); end ); finally Ms.DisposeOf; end; finally HttpClient.DisposeOf; end; end ).Start; end; end.
unit ProdutosConsulta; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IBDatabase, DB, DBClient, Menus, DBXpress, FMTBcd, SqlExpr, ConsultaSql, Provider, Grids, DBGrids, UDMConexaoDB, Buttons, ExtCtrls, StdCtrls, ORMUtils, ProdutosORM, uPrincipal; type TFProdutosConsulta = class(TForm) dsProdutos: TDataSource; dspProdutos: TDataSetProvider; sdsProdutos: TSQLDataSet; gridProdutos: TDBGrid; cdsProdutos: TClientDataSet; Panel1: TPanel; btAdicionar: TSpeedButton; btExcluir: TSpeedButton; btRefresh: TSpeedButton; btEditar: TSpeedButton; pnlDivisor: TPanel; grbFiltro: TGroupBox; lbDescricao: TLabel; edDescricao: TEdit; btnFiltrar: TButton; sdsProdutosPRODUTO_ID: TIntegerField; sdsProdutosDESCRICAO: TStringField; sdsProdutosUNIDADE: TStringField; sdsProdutosPRECO_VENDA: TFloatField; cdsProdutosPRODUTO_ID: TIntegerField; cdsProdutosDESCRICAO: TStringField; cdsProdutosUNIDADE: TStringField; cdsProdutosPRECO_VENDA: TFloatField; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnFiltrarClick(Sender: TObject); procedure btRefreshClick(Sender: TObject); procedure btAdicionarClick(Sender: TObject); procedure btEditarClick(Sender: TObject); procedure AtualizaLinhaGrid(produto: TProduto; acao: TAcao); procedure btExcluirClick(Sender: TObject); procedure gridProdutosDblClick(Sender: TObject); private { Private declarations } FiltroSql: TLayoutQuery; procedure CriaSqlQuery; procedure CarregaSql; procedure AplicaFiltro; public { Public declarations } end; var FProdutosConsulta: TFProdutosConsulta; implementation uses MyStrUtils, Constantes, ProdutosCadastro; {$R *.dfm} procedure TFProdutosConsulta.FormCreate(Sender: TObject); begin CriaSqlQuery; CarregaSql; end; procedure TFProdutosConsulta.FormClose(Sender: TObject; var Action: TCloseAction); begin Free; end; procedure TFProdutosConsulta.btnFiltrarClick(Sender: TObject); begin AplicaFiltro; CarregaSql; end; procedure TFProdutosConsulta.CriaSqlQuery; begin FiltroSql := TLayoutQuery.Create; FiltroSql.Query := 'SELECT PRODUTO.PRODUTO_ID, '+ 'PRODUTO.DESCRICAO, '+ 'PRODUTO.UNIDADE, '+ 'PRODUTO.PRECO_VENDA '+ 'FROM PRODUTOS PRODUTO ' ; FiltroSql.OrderBy := 'PRODUTO.DESCRICAO'; end; procedure TFProdutosConsulta.CarregaSql; begin cdsProdutos.Close; sdsProdutos.CommandText := FiltroSql.SqlQuery; cdsProdutos.Open; TNumericField(cdsProdutos.FieldByName('PRECO_VENDA')).DisplayFormat := ',0.00;-,0.00'; end; procedure TFProdutosConsulta.AplicaFiltro; var sqlFiltro: string; begin sqlFiltro := ''; if (not IsEmpty(edDescricao.Text)) then sqlFiltro := sqlFiltro + format(' AND UPPER(PRODUTO.DESCRICAO) LIKE UPPER(''%%%s%%'')', [edDescricao.Text]); FiltroSql.Conditions := Copy(sqlFiltro, 6, Length(sqlFiltro)); end; procedure TFProdutosConsulta.btRefreshClick(Sender: TObject); begin cdsProdutos.Close; cdsProdutos.Open; end; procedure TFProdutosConsulta.AtualizaLinhaGrid(produto: TProduto; acao: TAcao); begin if (acao = paInclusao) then begin cdsProdutos.Append; cdsProdutos.FieldByName('PRODUTO_ID').AsInteger := Produto.ProdutoID; end else cdsProdutos.Edit; cdsProdutos.FieldByName('DESCRICAO').AsString := Produto.Descricao; cdsProdutos.FieldByName('UNIDADE').AsString := Produto.Unidade; cdsProdutos.FieldByName('PRECO_VENDA').AsFloat := Produto.PrecoVenda; end; procedure TFProdutosConsulta.btAdicionarClick(Sender: TObject); var produto: TProduto; begin if ProdutosCadastro.AbreCadastro(0, paInclusao, produto) then AtualizaLinhaGrid(produto, paInclusao); end; procedure TFProdutosConsulta.btEditarClick(Sender: TObject); var produto: TProduto; begin if ProdutosCadastro.AbreCadastro(cdsProdutosPRODUTO_ID.Value, paEdicao, produto) then AtualizaLinhaGrid(produto, paEdicao); end; procedure TFProdutosConsulta.btExcluirClick(Sender: TObject); var produto : TProduto; begin if Application.MessageBox(mensagemConfirmacaoDeExclusao, 'Application.Title', MB_YESNO) = IDYES then begin produto := TProduto.Create(cdsProdutosPRODUTO_ID.Value); if produto.Excluir then cdsProdutos.Delete else raise Exception.Create('Não foi possível excluir o registro'); end; end; procedure TFProdutosConsulta.gridProdutosDblClick(Sender: TObject); begin btEditar.Click; end; end.
unit Overbyte.Ics.Component platform; interface uses Borland.Vcl.Windows, Borland.Vcl.Messages, Borland.Vcl.WinUtils, Borland.Vcl.Classes {$IFNDEF NOFORMS} , Borland.Vcl.Forms {$ENDIF} ; type TIcsBgExceptionEvent = procedure (Sender : TObject; E : Exception; var CanClose : Boolean) of object; EIcsException = class(Exception); {$IFDEF ICS_COMPONENT} TIcsComponent = class(TComponent) {$ELSE} TIcsComponent = class(TObject) {$ENDIF} protected {$IFNDEF ICS_COMPONENT} FName : String; {$ENDIF} FWindowHandle : HWND; FThreadId : DWORD; FTerminated : Boolean; FMultiThreaded : Boolean; FOnBgException : TIcsBgExceptionEvent; FOnMessagePump : TNotifyEvent; procedure WndProc(var MsgRec: TMessage); virtual; procedure HandleBackGroundException(E: Exception); virtual; procedure AllocateHWnd; virtual; procedure DeallocateHWnd; virtual; {$IFNDEF ICS_COMPONENT} procedure Notification(AComponent: TIcsComponent; Operation: TOperation); virtual; {$ELSE} procedure Notification(AComponent: TComponent; Operation: TOperation); override; {$ENDIF} procedure AbortComponent; virtual; //abstract; property MultiThreaded : Boolean read FMultiThreaded write FMultiThreaded; public constructor Create(AOwner: {$IFDEF ICS_COMPONENT}TComponent); override; {$ELSE}TObject); virtual;{$ENDIF} destructor Destroy; override; procedure ThreadAttach; virtual; procedure ThreadDetach; virtual; procedure MessageLoop; virtual; function ProcessMessage : Boolean; virtual; procedure ProcessMessages; virtual; procedure MessagePump; virtual; {$IFNDEF ICS_COMPONENT} property Name : String read FName write FName; {$ELSE} //property Name; {$ENDIF} property Handle : HWND read FWindowHandle; property OnBgException : TIcsBgExceptionEvent read FOnBgException write FOnBgException; end; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsComponent.Create( AOwner: {$IFDEF ICS_COMPONENT}TComponent {$ELSE}TObject{$ENDIF}); begin inherited Create{$IFDEF ICS_COMPONENT}(AOwner){$ENDIF}; Self.AllocateHWnd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsComponent.Destroy; begin Self.DeallocateHWnd; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.Notification( AComponent : {$IFDEF ICS_COMPONENT}TComponent{$ELSE}TIcsComponent{$ENDIF}; Operation : TOperation); begin {$IFDEF ICS_COMPONENT} inherited; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.WndProc(var MsgRec: TMessage); begin try MsgRec.Result := DefWindowProc(FWindowHandle, MsgRec.Msg, MsgRec.wParam, MsgRec.lParam); except on E:Exception do HandleBackGroundException(E); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { All exceptions *MUST* be handled. If an exception is not handled, the } { application will be shut down ! } procedure TIcsComponent.HandleBackGroundException(E: Exception); var CanAbort : Boolean; begin CanAbort := TRUE; { First call the error event handler, if any } if Assigned(FOnBgException) then begin try FOnBgException(Self, E, CanAbort); except end; end; { Then abort the component } if CanAbort then begin try Self.AbortComponent; except end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.AllocateHWnd; begin FThreadId := GetCurrentThreadId; FWindowHandle := Borland.Vcl.WinUtils.AllocateHWnd(Self.WndProc); if FWindowHandle = 0 then raise EIcsException.Create( 'Cannot create a hidden window for ICS component'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.DeallocateHWnd; begin if FWindowHandle = 0 then Exit; Borland.Vcl.WinUtils.DeallocateHWnd(FWindowHandle); FWindowHandle := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.ThreadAttach; begin if FWindowHandle <> 0 then raise EIcsException.Create('Cannot attach when not detached'); Self.AllocateHWnd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.ThreadDetach; begin if GetCurrentThreadID <> FThreadID then raise EIcsException.Create('Cannot detach from another thread'); Self.DeallocateHWnd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Loop thru message processing until the WM_QUIT message is received } { This is intended for multithreaded application using TWSocket. } { MessageLoop is different from ProcessMessages because it actually block } { if no message is available. The loop is broken when WM_QUIT is retrieved. } procedure TIcsComponent.MessageLoop; var MsgRec : TMsg; begin { If GetMessage retrieves the WM_QUIT, the return value is FALSE and } { the message loop is broken. } while GetMessage(MsgRec, 0, 0, 0) do begin TranslateMessage(MsgRec); DispatchMessage(MsgRec) end; FTerminated := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This function is very similar to TApplication.ProcessMessage } { You can also use it if your application has no TApplication object (Forms } { unit not referenced at all). } function TIcsComponent.ProcessMessage : Boolean; var Msg : TMsg; begin Result := FALSE; if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then begin Result := TRUE; if Msg.Message = WM_QUIT then FTerminated := TRUE else begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Loop thru message processing until all messages are processed. } { This function is very similar to TApplication.ProcessMessage } { This is intended for multithreaded application using TWSocket. } { You can also use it if your application has no TApplication object (Forms } { unit not referenced at all). } procedure TIcsComponent.ProcessMessages; begin while Self.ProcessMessage do { loop }; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.MessagePump; begin {$IFDEF NOFORMS} { The Forms unit (TApplication object) has not been included. } { We used either an external message pump or our internal message pump. } { External message pump has to set Terminated property to TRUE when the } { application is terminated. } if Assigned(FOnMessagePump) then FOnMessagePump(Self) else Self.ProcessMessages; {$ELSE} if FMultiThreaded then Self.ProcessMessages else Application.ProcessMessages; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsComponent.AbortComponent; begin // To be overriden in derived classes end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Model relacionado à tabela [FIN_LANCAMENTO_PAGAR] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit FinLancamentoPagar; interface uses Generics.Collections, System.SysUtils, FinParcelaPagar, FinDocumentoOrigem, FinNaturezaFinanceira, Fornecedor, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TFinLancamentoPagar = class(TModelBase) private FId: Integer; FIdFinDocumentoOrigem: Integer; FIdFinNaturezaFinanceira: Integer; FIdFornecedor: Integer; FQuantidadeParcela: Integer; FValorTotal: Extended; FValorAPagar: Extended; FDataLancamento: TDateTime; FNumeroDocumento: string; FImagemDocumento: string; FPrimeiroVencimento: TDateTime; FIntervaloEntreParcelas: Integer; FDiaFixo: string; FFinDocumentoOrigem: TFinDocumentoOrigem; FFinNaturezaFinanceira: TFinNaturezaFinanceira; FFornecedor: TFornecedor; FListaFinParcelaPagar: TObjectList<TFinParcelaPagar>; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_FIN_DOCUMENTO_ORIGEM')] [MVCNameAsAttribute('idFinDocumentoOrigem')] property IdFinDocumentoOrigem: Integer read FIdFinDocumentoOrigem write FIdFinDocumentoOrigem; [MVCColumnAttribute('ID_FIN_NATUREZA_FINANCEIRA')] [MVCNameAsAttribute('idFinNaturezaFinanceira')] property IdFinNaturezaFinanceira: Integer read FIdFinNaturezaFinanceira write FIdFinNaturezaFinanceira; [MVCColumnAttribute('ID_FORNECEDOR')] [MVCNameAsAttribute('idFornecedor')] property IdFornecedor: Integer read FIdFornecedor write FIdFornecedor; [MVCColumnAttribute('QUANTIDADE_PARCELA')] [MVCNameAsAttribute('quantidadeParcela')] property QuantidadeParcela: Integer read FQuantidadeParcela write FQuantidadeParcela; [MVCColumnAttribute('VALOR_TOTAL')] [MVCNameAsAttribute('valorTotal')] property ValorTotal: Extended read FValorTotal write FValorTotal; [MVCColumnAttribute('VALOR_A_PAGAR')] [MVCNameAsAttribute('valorAPagar')] property ValorAPagar: Extended read FValorAPagar write FValorAPagar; [MVCColumnAttribute('DATA_LANCAMENTO')] [MVCNameAsAttribute('dataLancamento')] property DataLancamento: TDateTime read FDataLancamento write FDataLancamento; [MVCColumnAttribute('NUMERO_DOCUMENTO')] [MVCNameAsAttribute('numeroDocumento')] property NumeroDocumento: string read FNumeroDocumento write FNumeroDocumento; [MVCColumnAttribute('IMAGEM_DOCUMENTO')] [MVCNameAsAttribute('imagemDocumento')] property ImagemDocumento: string read FImagemDocumento write FImagemDocumento; [MVCColumnAttribute('PRIMEIRO_VENCIMENTO')] [MVCNameAsAttribute('primeiroVencimento')] property PrimeiroVencimento: TDateTime read FPrimeiroVencimento write FPrimeiroVencimento; [MVCColumnAttribute('INTERVALO_ENTRE_PARCELAS')] [MVCNameAsAttribute('intervaloEntreParcelas')] property IntervaloEntreParcelas: Integer read FIntervaloEntreParcelas write FIntervaloEntreParcelas; [MVCColumnAttribute('DIA_FIXO')] [MVCNameAsAttribute('diaFixo')] property DiaFixo: string read FDiaFixo write FDiaFixo; [MVCNameAsAttribute('finDocumentoOrigem')] property FinDocumentoOrigem: TFinDocumentoOrigem read FFinDocumentoOrigem write FFinDocumentoOrigem; [MVCNameAsAttribute('finNaturezaFinanceira')] property FinNaturezaFinanceira: TFinNaturezaFinanceira read FFinNaturezaFinanceira write FFinNaturezaFinanceira; [MVCNameAsAttribute('fornecedor')] property Fornecedor: TFornecedor read FFornecedor write FFornecedor; [MapperListOf(TFinParcelaPagar)] [MVCNameAsAttribute('listaFinParcelaPagar')] property ListaFinParcelaPagar: TObjectList<TFinParcelaPagar> read FListaFinParcelaPagar write FListaFinParcelaPagar; end; implementation { TFinLancamentoPagar } constructor TFinLancamentoPagar.Create; begin FListaFinParcelaPagar := TObjectList<TFinParcelaPagar>.Create; FFinDocumentoOrigem := TFinDocumentoOrigem.Create; FFinNaturezaFinanceira := TFinNaturezaFinanceira.Create; FFornecedor := TFornecedor.Create; end; destructor TFinLancamentoPagar.Destroy; begin FreeAndNil(FListaFinParcelaPagar); FreeAndNil(FFinDocumentoOrigem); FreeAndNil(FFinNaturezaFinanceira); FreeAndNil(FFornecedor); inherited; end; procedure TFinLancamentoPagar.ValidarInsercao; begin inherited; end; procedure TFinLancamentoPagar.ValidarAlteracao; begin inherited; end; procedure TFinLancamentoPagar.ValidarExclusao; begin inherited; end; end.
program hello; uses Windows, Messages; type COLOR16 = USHORT; PTriVertex = ^TTriVertex; _TRIVERTEX = record x: LONG; y: LONG; Red: COLOR16; Green: COLOR16; Blue: COLOR16; Alpha: COLOR16; end; TRIVERTEX = _TRIVERTEX; LPTRIVERTEX = ^TRIVERTEX; TTriVertex = _TRIVERTEX; PGradientTriangle = ^TGradientTriangle; _GRADIENT_TRIANGLE = record Vertex1: ULONG; Vertex2: ULONG; Vertex3: ULONG; end; GRADIENT_TRIANGLE = _GRADIENT_TRIANGLE; LPGRADIENT_TRIANGLE = ^GRADIENT_TRIANGLE; PGRADIENT_TRIANGLE = ^GRADIENT_TRIANGLE; TGradientTriangle = _GRADIENT_TRIANGLE; TGradientFill = function(hdc: HDC; pVertex: PTRIVERTEX; dwNumVertex: ULONG; pMesh: PVOID; dwNumMesh, dwMode: ULONG): BOOL; stdcall; var GradientFill: TGradientFill; const GRADIENT_FILL_TRIANGLE = $00000002; procedure DrawTriangle(hdc: HDC); var vertex: array [0..2] of TRIVERTEX; gTriangle: GRADIENT_TRIANGLE; const WIDTH = 640; HEIGHT = 480; begin vertex[0].x := Round(WIDTH * 1 / 2); vertex[0].y := Round(HEIGHT * 1 / 4); vertex[0].Red := $ffff; vertex[0].Green := $0000; vertex[0].Blue := $0000; vertex[0].Alpha := $0000; vertex[1].x := Round(WIDTH * 3 / 4); vertex[1].y := Round(HEIGHT * 3 / 4); vertex[1].Red := $0000; vertex[1].Green := $ffff; vertex[1].Blue := $0000; vertex[1].Alpha := $0000; vertex[2].x := Round(WIDTH * 1 / 4); vertex[2].y := Round(HEIGHT * 3 / 4); vertex[2].Red := $0000; vertex[2].Green := $0000; vertex[2].Blue := $ffff; vertex[2].Alpha := $0000; gTriangle.Vertex1 := 0; gTriangle.Vertex2 := 1; gTriangle.Vertex3 := 2; GradientFill(hdc, vertex, 3, @gTriangle, 1, GRADIENT_FILL_TRIANGLE); end; procedure OnPaint(hdc: HDC); begin DrawTriangle(hdc); end; function WindowProc(hWindow:HWnd; message:Cardinal; wParam:Word; lParam:Longint):LongWord; stdcall; var hdc: THandle; ps: TPaintStruct; begin case message of WM_PAINT: begin hdc := BeginPaint(hWindow, ps ); OnPaint(hdc); EndPaint( hWindow, ps ); end; WM_DESTROY: PostQuitMessage(0); else WindowProc := DefWindowProc(hWindow, message, wParam, lParam); exit; end; WindowProc := 0; end; function WinMain(hInstance, hPrevInstance:THandle; lpCmdLine:PAnsiChar; nCmdShow:Integer):Integer; stdcall; var wcex: TWndClassEx; hWindow: HWnd; msg: TMsg; LibHandle : THandle; const ClassName = 'helloWindow'; WindowName = 'Hello, World!'; begin LibHandle := LoadLibrary(PChar('msimg32.dll')); Pointer(GradientFill) := GetProcAddress(LibHandle, 'GradientFill'); wcex.cbSize := SizeOf(TWndclassEx); wcex.style := CS_HREDRAW or CS_VREDRAW; wcex.lpfnWndProc := WndProc(@WindowProc); wcex.cbClsExtra := 0; wcex.cbWndExtra := 0; wcex.hInstance := hInstance; wcex.hIcon := LoadIcon(0, IDI_APPLICATION); wcex.hCursor := LoadCursor(0, IDC_ARROW); wcex.hbrBackground := COLOR_WINDOW +1; wcex.lpszMenuName := nil; wcex.lpszClassName := ClassName; RegisterClassEx(wcex); hWindow := CreateWindowEX( 0, ClassName, WindowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, 0, 0, hInstance, nil ); ShowWindow(hWindow, SW_SHOWDEFAULT); UpdateWindow(hWindow); while GetMessage(msg, 0, 0, 0) do begin TranslateMessage(msg); DispatchMessage(msg); end; GradientFill := nil; FreeLibrary(LibHandle); WinMain := msg.wParam; end; begin WinMain( hInstance, 0, nil, cmdShow ); end.
unit BDEActivityLog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ThreadedBDEQuery, seqnum, DB, DBTables,ThreadedQueryDef; type TErrorProc = procedure (Sender : TObject; ErrorMsg : string) of object; TBDEActivityLog = class(TComponent) private FError: TErrorProc; // when an error occurs in the thread. FOnComplete: TNotifyEvent; { Private declarations } fActive:boolean; fThreaded:boolean; fAppName: string; fIPAddress: string; fSequence: string; fSequenceNumber: TSequenceNumber; fNTUser: string; fComputerName:string; fDTSender:string; fDBTime:extended; fTrans: string; fDescription: string; fSendError:boolean; fBDEQuery:TQuery; fDatabase: TDatabase; fThreadedQuery: TThreadedBDEQuery; //fQueryList:TStringList; fQueryCount:integer; fAlias:string; fUsername:string; fPassword:string; msglist: array [0..1000] of string; ftop:integer; fbottom:integer; function GetSequence: string; procedure SetSequence( Sequence: string ); procedure SetOnComplete(Value: TNotifyEvent); procedure SetError(value : TErrorProc); procedure SendError (msg : string); procedure BeforeRun(Sender: TObject; Dataset: TQuery); procedure BDEQueryComplete(Sender: TObject; Dataset: TDataset); procedure BDEQueryError(Sender: TObject; ErrorMsg: String); procedure INIT; protected { Protected declarations } public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Send; published { Published declarations } property Active: boolean read fActive write fActive; property Threaded: boolean read fThreaded write fThreaded; property AppName: string read fAppName write fAppName; property IPAddress: string read fIPAddress write fIPAddress; property Sequence: string read GetSequence write SetSequence; property NTUser: string read fNTUser write fNTUser; property ComputerName: string read fComputerName write fComputerName; property DTSender: string read fDTSender write fDTSender; property DBTime: extended read fDBTime write fDBTime; property Trans: string read fTrans Write fTrans; property Description: string read fDescription write fDescription; property OnError : TErrorProc read FError write SetError; property OnComplete: TNotifyEvent read fOnComplete write SetOnComplete; property QueryCount: integer read fquerycount write fQueryCount; property Alias:string read fAlias write fAlias; property UserName:string read fUsername write fUsername; property Password:string read fPassword write fPassword; end; const ProcedureName='EXEC InsertDetailedAct_Log ''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',''%s'',%f'; msglistsize = 1000; implementation //Get current NT User name to fill in login box function CurrentUserName:String; var u: array[0..127] of Char; sz:DWord; begin sz:=SizeOf(u); GetUserName(u,sz); Result:=u; end; //Get current NT User name to fill in login box function CurrentComputerName:String; var u: array[0..127] of Char; sz:DWord; begin sz:=SizeOf(u); GetComputerName(u,sz); Result:=u; end; constructor TBDEActivityLog.Create(AOwner: TComponent); begin inherited Create(AOwner); fSequenceNumber:=TSequenceNumber.Create(self); fSequenceNumber.SequenceValue:=1; fComputerName:=CurrentComputerName; fNTUser:=CurrentUserName; fSequence:=fSequenceNumber.SequenceNumber; //fQueryList:=TstringList.Create; ftop:=0; fbottom:=0; fQueryCount:=0; fSendError:=False; end; destructor TBDEActivityLog.Destroy; begin fSequenceNumber.Free; fBDEQuery.Free; fDatabase.Free; fThreadedQuery.Free; //fQueryList.Free; inherited destroy; end; procedure TBDEActivityLog.INIT; begin //Non Threaded fDatabase:=TDatabase.Create(self); fDatabase.LoginPrompt:=False; fDatabase.AliasName:=fAlias; fDatabase.DatabaseName := 'DB_' + inttostr (integer (fDatabase)); fDatabase.Params.Clear; fDatabase.Params.Add('USER NAME='+fUsername); fDatabase.Params.Add('PASSWORD='+fPassword); fBDEQuery:=TQuery.Create(self); fBDEQuery.DatabaseName:=fDatabase.DatabaseName; //Threaded fThreadedQuery:=TThreadedBDEQuery.Create(self); fThreadedQuery.AliasName:=fAlias; fThreadedQuery.LoginParams.Add('USER NAME='+fUsername); fThreadedQuery.LoginParams.Add('PASSWORD='+fPassword); fThreadedQuery.RunMode:=runContinuous; fThreadedQuery.QryCommand:=qryExec; fThreadedQuery.KeepConnection:=False; fThreadedQuery.TimerInitial:=50; fThreadedQuery.TimerRestart:=200; fThreadedQuery.OnBeforeRun:=BeforeRun; fThreadedQuery.OnComplete:=BDEQueryComplete; fThreadedQuery.OnError:=BDEQueryError; end; procedure TBDEActivityLog.Send; var sdesc,desc:string; begin desc:=fDescription; while length(desc) > 0 do begin if length(desc) > 100 then begin sdesc:=copy(desc,1,100); desc:=copy(desc,101,length(desc)-100); end else begin sdesc:=desc; desc:=''; end; if fThreaded then begin if not assigned(fThreadedQuery) then INIT; try //fQueryList.Add('EXEC InsertDetailedAct_Log '''+fAppName+''','''+fIPAddress+''','''+fTrans+''','''+fDTSender+''','''+fComputerName+''','''+sdesc+''','''+fNTUser+''','+FloatToStr(fDBTime)); msglist[fbottom]:='EXEC InsertDetailedAct_Log '''+fAppName+''','''+fIPAddress+''','''+fTrans+''','''+fDTSender+''','''+fComputerName+''','''+sdesc+''','''+fNTUser+''','+FloatToStr(fDBTime); INC(fbottom); if fbottom>msglistsize then fbottom:=0; INC(fQueryCount); if (not fThreadedQuery.Active) and fActive then begin fThreadedQuery.Active:=True; end; except on e:exception do begin SendError('Send ERROR:: '+e.message); end; end; end else begin if not assigned(fDatabase) then INIT; try if fActive then begin fDatabase.Connected:=True; fBDEquery.SQL.Clear; if DTSender = '' then DTSender:=formatdatetime('yyyymmddhhmmss00',now); FBDEQuery.SQL.Add(format(ProcedureName,[fAppName,IPAddress,fTrans,fDTSender,fComputerName,sdesc,fNTUser,fDBTime])); fBDEQuery.ExecSQL; fDatabase.Connected:=False; if (Assigned (fOnComplete)) then fOnComplete(self); end; except on e:exception do begin fDatabase.Connected:=False; SendError('Send ERROR:: '+e.message); end; end; end; end; end; procedure TBDEActivityLog.BeforeRun(Sender: TObject; Dataset: TQuery); begin Dataset.SQL.Clear; //Dataset.SQL.Add(fQueryList.Strings[0]); Dataset.SQL.Add(msglist[ftop]); end; procedure TBDEActivityLog.BDEQueryComplete(Sender: TObject; Dataset: TDataset); begin // delete after run, save if error //fQueryList.Delete(0); INC(fTop); if fTop>msglistsize then fTop:=0; DEC(fQueryCount); // stop query if no more, if not pull next and send if fQueryCount <= 0 then fThreadedQuery.Active:=False; //else //begin //fThreadedQuery.SQL.Clear; //fThreadedQuery.SQL.Add(fQueryList.Strings[0]); //fThreadedQuery.SQL.Add(msglist[ftop]); //end; if (Assigned (fOnComplete)) then fOnComplete(self); end; procedure TBDEActivityLog.BDEQueryError(Sender: TObject; ErrorMsg: String); begin // shutdown query if error fThreadedQuery.Active:=False; SendError(ErrorMsg); end; function TBDEActivityLog.GetSequence: string; begin result:=fSequence; end; procedure TBDEActivityLog.SetSequence( Sequence: string ); begin if Sequence <> '' then begin try fSequenceNumber.SequenceNumber:=Sequence; fSequence:=fSequenceNumber.SequenceNumber; except fSequence:='0001'; SendError('Invalid sequence number'); end; end else begin fSequence:='0001'; end end; procedure TBDEActivityLog.SetError(value : TErrorProc ); begin FError:= value; end; procedure TBDEActivityLog.SetOnComplete(Value: TNotifyEvent); begin FOnComplete := Value; end; procedure TBDEActivityLog.SendError (msg : string); begin if (Assigned (FError)) then FError (self, msg); end; end.
{$include kode.inc} unit kode_widget_color; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_canvas, kode_color, //kode_const, kode_flags, kode_rect, kode_widget; type KWidget_Color = class(KWidget) protected FColor : KColor; public constructor create(ARect:KRect; AColor:KColor; AAlignment:LongWord=kwa_none); public procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses kode_const, kode_debug; //---------- constructor KWidget_Color.create(ARect:KRect; AColor:KColor; AAlignment:LongWord); begin inherited create(ARect,AAlignment); FName := 'KWidget_Color'; FColor := AColor; //FCursor := kmc_Cross; end; //---------- procedure KWidget_Color.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); begin //KTrace(['KWidget_Color.on_paint ', FRect.x,',', FRect.y,',', FRect.w,',', FRect.h,',', KODE_CR]); ACanvas.setFillColor(FColor); ACanvas.fillRect(FRect.x,FRect.y,FRect.x2,FRect.y2); inherited; end; //---------------------------------------------------------------------- end.
unit XmlCertVault; interface type HCkXmlCertVault = Pointer; HCkByteData = Pointer; HCkString = Pointer; HCkPfx = Pointer; HCkCertChain = Pointer; HCkCert = Pointer; function CkXmlCertVault_Create: HCkXmlCertVault; stdcall; procedure CkXmlCertVault_Dispose(handle: HCkXmlCertVault); stdcall; procedure CkXmlCertVault_getDebugLogFilePath(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; procedure CkXmlCertVault_putDebugLogFilePath(objHandle: HCkXmlCertVault; newPropVal: PWideChar); stdcall; function CkXmlCertVault__debugLogFilePath(objHandle: HCkXmlCertVault): PWideChar; stdcall; procedure CkXmlCertVault_getLastErrorHtml(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; function CkXmlCertVault__lastErrorHtml(objHandle: HCkXmlCertVault): PWideChar; stdcall; procedure CkXmlCertVault_getLastErrorText(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; function CkXmlCertVault__lastErrorText(objHandle: HCkXmlCertVault): PWideChar; stdcall; procedure CkXmlCertVault_getLastErrorXml(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; function CkXmlCertVault__lastErrorXml(objHandle: HCkXmlCertVault): PWideChar; stdcall; function CkXmlCertVault_getLastMethodSuccess(objHandle: HCkXmlCertVault): wordbool; stdcall; procedure CkXmlCertVault_putLastMethodSuccess(objHandle: HCkXmlCertVault; newPropVal: wordbool); stdcall; procedure CkXmlCertVault_getMasterPassword(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; procedure CkXmlCertVault_putMasterPassword(objHandle: HCkXmlCertVault; newPropVal: PWideChar); stdcall; function CkXmlCertVault__masterPassword(objHandle: HCkXmlCertVault): PWideChar; stdcall; function CkXmlCertVault_getVerboseLogging(objHandle: HCkXmlCertVault): wordbool; stdcall; procedure CkXmlCertVault_putVerboseLogging(objHandle: HCkXmlCertVault; newPropVal: wordbool); stdcall; procedure CkXmlCertVault_getVersion(objHandle: HCkXmlCertVault; outPropVal: HCkString); stdcall; function CkXmlCertVault__version(objHandle: HCkXmlCertVault): PWideChar; stdcall; function CkXmlCertVault_AddCert(objHandle: HCkXmlCertVault; cert: HCkCert): wordbool; stdcall; function CkXmlCertVault_AddCertBinary(objHandle: HCkXmlCertVault; certBytes: HCkByteData): wordbool; stdcall; function CkXmlCertVault_AddCertChain(objHandle: HCkXmlCertVault; certChain: HCkCertChain): wordbool; stdcall; function CkXmlCertVault_AddCertEncoded(objHandle: HCkXmlCertVault; encodedBytes: PWideChar; encoding: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddCertFile(objHandle: HCkXmlCertVault; path: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddCertString(objHandle: HCkXmlCertVault; certData: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddPemFile(objHandle: HCkXmlCertVault; path: PWideChar; password: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddPfx(objHandle: HCkXmlCertVault; pfx: HCkPfx): wordbool; stdcall; function CkXmlCertVault_AddPfxBinary(objHandle: HCkXmlCertVault; pfxBytes: HCkByteData; password: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddPfxEncoded(objHandle: HCkXmlCertVault; encodedBytes: PWideChar; encoding: PWideChar; password: PWideChar): wordbool; stdcall; function CkXmlCertVault_AddPfxFile(objHandle: HCkXmlCertVault; path: PWideChar; password: PWideChar): wordbool; stdcall; function CkXmlCertVault_GetXml(objHandle: HCkXmlCertVault; outStr: HCkString): wordbool; stdcall; function CkXmlCertVault__getXml(objHandle: HCkXmlCertVault): PWideChar; stdcall; function CkXmlCertVault_LoadXml(objHandle: HCkXmlCertVault; xml: PWideChar): wordbool; stdcall; function CkXmlCertVault_LoadXmlFile(objHandle: HCkXmlCertVault; path: PWideChar): wordbool; stdcall; function CkXmlCertVault_SaveLastError(objHandle: HCkXmlCertVault; path: PWideChar): wordbool; stdcall; function CkXmlCertVault_SaveXml(objHandle: HCkXmlCertVault; path: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkXmlCertVault_Create; external DLLName; procedure CkXmlCertVault_Dispose; external DLLName; procedure CkXmlCertVault_getDebugLogFilePath; external DLLName; procedure CkXmlCertVault_putDebugLogFilePath; external DLLName; function CkXmlCertVault__debugLogFilePath; external DLLName; procedure CkXmlCertVault_getLastErrorHtml; external DLLName; function CkXmlCertVault__lastErrorHtml; external DLLName; procedure CkXmlCertVault_getLastErrorText; external DLLName; function CkXmlCertVault__lastErrorText; external DLLName; procedure CkXmlCertVault_getLastErrorXml; external DLLName; function CkXmlCertVault__lastErrorXml; external DLLName; function CkXmlCertVault_getLastMethodSuccess; external DLLName; procedure CkXmlCertVault_putLastMethodSuccess; external DLLName; procedure CkXmlCertVault_getMasterPassword; external DLLName; procedure CkXmlCertVault_putMasterPassword; external DLLName; function CkXmlCertVault__masterPassword; external DLLName; function CkXmlCertVault_getVerboseLogging; external DLLName; procedure CkXmlCertVault_putVerboseLogging; external DLLName; procedure CkXmlCertVault_getVersion; external DLLName; function CkXmlCertVault__version; external DLLName; function CkXmlCertVault_AddCert; external DLLName; function CkXmlCertVault_AddCertBinary; external DLLName; function CkXmlCertVault_AddCertChain; external DLLName; function CkXmlCertVault_AddCertEncoded; external DLLName; function CkXmlCertVault_AddCertFile; external DLLName; function CkXmlCertVault_AddCertString; external DLLName; function CkXmlCertVault_AddPemFile; external DLLName; function CkXmlCertVault_AddPfx; external DLLName; function CkXmlCertVault_AddPfxBinary; external DLLName; function CkXmlCertVault_AddPfxEncoded; external DLLName; function CkXmlCertVault_AddPfxFile; external DLLName; function CkXmlCertVault_GetXml; external DLLName; function CkXmlCertVault__getXml; external DLLName; function CkXmlCertVault_LoadXml; external DLLName; function CkXmlCertVault_LoadXmlFile; external DLLName; function CkXmlCertVault_SaveLastError; external DLLName; function CkXmlCertVault_SaveXml; external DLLName; end.
PROGRAM Task4(INPUT, OUTPUT); USES DOS; FUNCTION ReadQueryString(Key: STRING): STRING; VAR Str, Val: STRING; KeyNum, I: INTEGER; BEGIN Val := ''; Str := GetEnv('QUERY_STRING'); KeyNum := POS(Key, Str) + Length(Key) + 1; FOR I := KeyNum TO Length(Str) DO BEGIN IF Str[I] = '&' THEN BREAK; Val := Val + Str[I] END; ReadQueryString := Val END; BEGIN WRITELN('Content-Type: text/plain'); WRITELN; WRITELN('First Name: ', ReadQueryString('first_name')); WRITELN('Last Name: ', ReadQueryString('last_name')); WRITELN('Age: ', ReadQueryString('age')) END.
unit UUtilidades; interface uses UdmPersistenceQueryClient; type TUtilidades = class(TObject) public class procedure callActiveDirectory(AUUID, AUser, APassword: String; out AStatusCode, AStatusDesc : String); static; class procedure sendEmail(AUUID, ACorreoOrigen, ACorreoDestino, AAsuntoCorreo, AMensajeCorreo : String; out AStatusCode,AStatusDesc : String); static; class procedure sendEmailTemplate(AUUID, ATransaccion, ADatosCorreo : String; out AStatusCode, AStatusDesc: String); static; class procedure sendEmailAdmin(AUUID, ATransaccion, AEstadoServicio : String); static; class procedure sendEmailError(AUUID, ANombreTransaccion, AMensajeError : String); static; class procedure reportLogError(AMensaje : String); static; class procedure ReportarExcepcionCorreo(AUUID, AMensaje : String); static; class function base64Decode(AMessage : String) : String; static; class function base64Encode(AMessage : String) : String; static; class function callJanua(AUUIDTransaccion, ATxTransaccion, ADatosTransaccion : String) : String; static; class function callJanuaTest : Boolean; static; class function getGUID : String; static; class function getDateTime : String; static; class function getHostName : String; static; class function getIpAddress : String; static; class function getTemplate(AUUID, AtxPlantilla: String; out AStatusDesc, APlantilla : String): Boolean; static; class function getTime() : String; static; class function getElapsedTime(AInitTime : String) : String; static; class function pageProducer(ATemplate, AValues: String; out ARespuesta : String): Boolean; static; {CRUD} class function crudInsert(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro : String; out ARespuestaCRUD: String): Boolean; static; class function crudUpdate(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro : String; out ARespuestaCRUD: String): Boolean; static; class function crudDelete(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro : String; out ARespuestaCRUD: String): Boolean; static; class function crudSelectOne(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro : String; out ARespuestaCRUD: String): Boolean; static; private class function callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, ATipoTransaccion : String; out ARespuestaCRUD: String): Boolean; static; end; (** Monitor **) type TMonitor = class(TObject) public class procedure sendInfoMessage (AUUIDTransaccion, ATransaccion, AProceso, AMensaje: String); static; class procedure sendWarningMessage (AUUIDTransaccion, ATransaccion, AProceso, AMensaje: String); static; class procedure sendErrorMessage (AUUIDTransaccion, ATransaccion, AProceso, AMensaje : String); static; class procedure endMonitorProcess (AUUIDTransaccion : String); static; end; (** JSON **) type TProcesarMensaje <T : class, constructor> = class public class function cadenaAObjeto(ACadena : String) : T; static; class function objetoACadena(AObjeto : T) : String; static; end; (** Medir Tiempo **) type TMedirTiempo = class(TObject) private startTime64 : Int64; endTime64 : Int64; frequency64 : Int64; public constructor beginProcess; function getProcessTime : String; end; (** Constantes **) const MIL_MILISEGUNDOS = 1000; INICIO_GUID = 2; FINAL_GUID = 36; TX_REGEX = 'TX800'; TRAER_TODOS_LOS_CAMPOS = '*'; SIN_FILTRO = ''; SIN_ORDEN = ''; FORMATO_BINARIO = 'BINARY'; INDICE_REGEX = 'id_validation'; JANUA_PORT = 31020; CRUD_INSERT = 'CREAR'; CRUD_UPDATE = 'ACTUALIZAR'; CRUD_DELETE = 'BORRAR'; CRUD_SELECT_ONE = 'LEER_LISTA_KEYVALUES'; TX_DIRECTORIO_ACTIVO = 'TX305'; TX_CORREO = 'TX939'; TX_CORREO_PLANTILLA = 'TX938'; INFO_MESSAGE = 'INFO'; WARNING_MESSAGE = 'WARNING'; ERROR_MESSAGE = 'ERROR'; CORREO_ERROR = 'EC003'; implementation uses Rest.Json, Winapi.Windows, System.SysUtils, System.StrUtils, Winapi.Winsock, IdBaseComponent, IdCoder, IdCoder3to4, IdCoderMIME, UdmPageProducer, RegularExpressions, fServerDataModule, UCRUD, System.Classes, UdmConfiguracion, UdmMonitor, UdmJanua, System.IOUtils; { TUtilidades } {Encapsula el Consumo de Janua} class function TUtilidades.callJanuaTest : Boolean; var BoolRespuesta : Boolean; xdmJanuaClient : TdmJanua; begin BoolRespuesta := False; try xdmJanuaClient := TdmJanua.Create(Nil); //BoolRespuesta := xdmJanuaClient.TestJanua; BoolRespuesta := True; finally FreeAndNil(xdmJanuaClient); end; result := BoolRespuesta; end; class function TUtilidades.callJanua(AUUIDTransaccion, ATxTransaccion, ADatosTransaccion: String): String; var xdmJanua : TdmJanua; strRespuestaJanua : String; strMensajeCorreo : String; lstRespuesta : TStringList; begin try lstRespuesta := TStringList.Create; try xdmJanua := TdmJanua.Create(Nil); strRespuestaJanua := xdmJanua.consumirTransaccion(AUUIDTransaccion, ATxTransaccion,ADatosTransaccion); except on e : exception do begin lstRespuesta.Text := strRespuestaJanua; lstRespuesta.Values[STATUS_CODE] := '404'; lstRespuesta.Values[STATUS_DESC] := e.Message; strRespuestaJanua := lstRespuesta.Text; ServerDataModule.EntrarModoStandBy; //Es necesario validar si en memoria estan las configuraciones de Janua //si no estan se entra en un loop infinito de excepciones if (ATxTransaccion <> TX_CORREO) and (ATxTransaccion <> TX_CORREO_PLANTILLA) and (ServerDataModule.FDMemJanuaConfig.RecordCount > 0) then begin strMensajeCorreo := 'nombre_aplicacion=' + strApplication + ',' + 'nombre_transaccion=' + ATxTransaccion + '-' + ServerDataModule.ObtenerDescripcionTxJanua(ATxTransaccion) + ',' + 'mensaje_error=' + String(e.Message) + ',' + 'servidor_origen=' + String(getHostName) + ',' + 'fecha_error=' + DateTimeToStr(Now); ReportarExcepcionCorreo(AUUIDTransaccion, String(strMensajeCorreo)); end else begin TMonitor.sendErrorMessage(UUID_PROCESO_DEFAULT, INICIALIZACION, 'Janua', 'Janua no inicializado.'); end; end; end; finally lstRespuesta.Clear; FreeAndNil(lstRespuesta); FreeAndNil(xdmJanua); end; result := strRespuestaJanua end; {Encapsula el consumo del CRUD} class function TUtilidades.crudDelete(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro : String; out ARespuestaCRUD: String): Boolean; var transaccionExitosa : Boolean; begin transaccionExitosa := callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, CRUD_DELETE, ARespuestaCRUD); result := transaccionExitosa; end; class function TUtilidades.crudInsert(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro: String; out ARespuestaCRUD: String): Boolean; begin result := callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, CRUD_INSERT, ARespuestaCRUD); end; class function TUtilidades.crudUpdate(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro: String; out ARespuestaCRUD: String): Boolean; begin result := callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, CRUD_UPDATE, ARespuestaCRUD); end; class function TUtilidades.crudSelectOne(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro: String; out ARespuestaCRUD: String): Boolean; begin result := callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, CRUD_SELECT_ONE, ARespuestaCRUD); end; class procedure TUtilidades.callActiveDirectory(AUUID, AUser, APassword: String; out AStatusCode, AStatusDesc : String); var lstSolicitud : TStringList; lstRespuesta : TStringList; begin try lstSolicitud := TStringList.Create; lstRespuesta := TStringList.Create; lstSolicitud.Values['dominio'] := 'BANCODEBOGOTA'; lstSolicitud.Values['extension'] := 'NET'; lstSolicitud.Values['usuario'] := AUser; lstSolicitud.Values['clave'] := APassword; //lstRespuesta.Text := TUtilidades.callJanua(TX_DIRECTORIO_ACTIVO, lstSolicitud.Text); lstRespuesta.Text := TUtilidades.callJanua(AUUID, TX_DIRECTORIO_ACTIVO, lstSolicitud.Text); AStatusCode := lstRespuesta.Values[STATUS_CODE]; AStatusDesc := lstRespuesta.Values[STATUS_DESC]; finally lstSolicitud.Clear; lstRespuesta.Clear; FreeAndNil(lstSolicitud); FreeAndNil(lstRespuesta); end; end; class function TUtilidades.callCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, ATipoTransaccion : String; out ARespuestaCRUD: String): Boolean; var transaccionExitosa : Boolean; xCRUD : TCRUD; begin transaccionExitosa := false; try try ARespuestaCRUD := 'Error al crear clase CRUD. '; xCRUD := TCRUD.create; ARespuestaCRUD := 'Error al consumir CRUD. '; transaccionExitosa := xCRUD.consumirCRUD(AUUID, ANombreBase, ANombreEntidad, ADatos, AFiltro, ATipoTransaccion); if transaccionExitosa then ARespuestaCRUD := xCRUD.FDatosRespuesta else ARespuestaCRUD := xCRUD.FMensajeRespuesta; except on e : exception do ARespuestaCRUD := ARespuestaCRUD + e.Message; end; finally FreeAndNil(xCRUD); end; result := transaccionExitosa; end; {Encapsula Uso de Page Producer} class function TUtilidades.pageProducer(ATemplate, AValues: String; out ARespuesta : String): Boolean; var xdmPageProducer : TdmPageProducer; transaccionExitosa : Boolean; begin transaccionExitosa := false; try try xdmPageProducer := TdmPageProducer.Create(nil); ARespuesta := xdmPageProducer.getContent(ATemplate, AValues, false); transaccionExitosa := True; except on e : exception do ARespuesta := 'Error al realizar page producer. ' + e.Message; end; finally xdmPageProducer.Destroy; end; result := transaccionExitosa; end; class procedure TUtilidades.ReportarExcepcionCorreo(AUUID, AMensaje: String); var StrStatusCode : String; StrStatusDesc : String; begin AMensaje := AnsiReplaceStr(AMensaje,',',#13#10); TUtilidades.sendEmailTemplate(AUUID, CORREO_ERROR, AMensaje, StrStatusCode, StrStatusDesc); end; class procedure TUtilidades.reportLogError(AMensaje: String); var lstError : TStringList; strNombreArchivo : String; begin lstError := TStringList.Create; strNombreArchivo := ExtractFilePath(ParamStr(0)) + 'ERROR_' + formatdatetime('yyyy_mm_dd', now) + '.txt'; if FileExists(strNombreArchivo) then lstError.LoadFromFile(strNombreArchivo); lstError.Add(formatdatetime('yyyy-mm-dd hh:nn:ss.zzz - ', now) + AMensaje); lstError.SaveToFile(strNombreArchivo); lstError.Clear; FreeAndNil(lstError); end; class procedure TUtilidades.SendEmail(AUUID, ACorreoOrigen, ACorreoDestino, AAsuntoCorreo, AMensajeCorreo: String; out AStatusCode, AStatusDesc: String); var lstSolicitud : TStringList; lstRespuesta : TStringList; begin try lstSolicitud := TStringList.Create; lstRespuesta := TStringList.Create; lstSolicitud.Values['correoOrigen'] := ACorreoOrigen; lstSolicitud.Values['correoDestino'] := ACorreoDestino; lstSolicitud.Values['asuntoCorreo'] := AAsuntoCorreo; lstSolicitud.Values['mensajeCorreo'] := AMensajeCorreo; //lstRespuesta.Text := TUtilidades.callJanua(TX_CORREO, lstSolicitud.Text); lstRespuesta.Text := TUtilidades.callJanua(AUUID, TX_CORREO, lstSolicitud.Text); AStatusCode := lstRespuesta.Values[STATUS_CODE]; AStatusDesc := lstRespuesta.Values[STATUS_DESC]; finally lstSolicitud.Clear; lstRespuesta.Clear; FreeAndNil(lstSolicitud); FreeAndNil(lstRespuesta); end; end; class procedure TUtilidades.sendEmailAdmin(AUUID, ATransaccion, AEstadoServicio : String); var strStatusCode : String; strStatusDesc : String; strNombreServicio : String; lstDatos : TStringList; begin strNombreServicio := TPath.GetFileNameWithoutExtension(ParamStr(0)); lstDatos := TStringList.create; lstDatos.Values['nombre_servicio'] := strNombreServicio; lstDatos.Values['nombre_servidor'] := getHostName; lstDatos.Values['estado_servicio'] := AEstadoServicio; lstDatos.Values['asuntoCorreo'] := 'Se ' + AEstadoServicio + ' ' + strNombreServicio; lstDatos.Values['fecha_hora'] := DateTimeToStr(now); sendEmailTemplate(AUUID, ATransaccion, lstDatos.Text, strStatusCode, strStatusDesc); lstDatos.Clear; FreeAndNil(lstDatos); end; class procedure TUtilidades.sendEmailError(AUUID, ANombreTransaccion, AMensajeError: String); var strMensajeCorreo : String; StrStatusCode : String; StrStatusDesc : String; begin strMensajeCorreo := 'nombre_aplicacion=' + strApplication + ',' + 'nombre_transaccion=' + ANombreTransaccion + ',' + 'mensaje_error=' + AMensajeError + ',' + 'servidor_origen=' + String(TUtilidades.getHostName) + ',' + 'fecha_error=' + DateTimeToStr(Now); strMensajeCorreo := AnsiReplaceStr(StrMensajeCorreo,',',#13#10); sendEmailTemplate(AUUID, CORREO_ERROR, strMensajeCorreo, StrStatusCode, StrStatusDesc); end; class procedure TUtilidades.sendEmailTemplate(AUUID, ATransaccion, ADatosCorreo: String; out AStatusCode, AStatusDesc: String); var lstSolicitud : TStringList; lstRespuesta : TStringList; begin try lstSolicitud := TStringList.Create; lstSolicitud.Values['txTransaccion'] := ATransaccion; lstSolicitud.Values['datosTransaccion'] := TUtilidades.base64Encode(ADatosCorreo); lstRespuesta := TStringList.Create; lstRespuesta.Text := TUtilidades.callJanua(AUUID, TX_CORREO_PLANTILLA, lstSolicitud.Text); AStatusCode := lstRespuesta.Values[STATUS_CODE]; AStatusDesc := lstRespuesta.Values[STATUS_DESC]; finally lstSolicitud.Clear; lstRespuesta.Clear; FreeAndNil(lstSolicitud); FreeAndNil(lstRespuesta); end; end; class procedure TMonitor.sendErrorMessage(AUUIDTransaccion, ATransaccion, AProceso, AMensaje : String); begin dmMonitor.SendInfo(AUUIDTransaccion, AProceso, ATransaccion, ERROR_MESSAGE, AMensaje); end; class procedure TMonitor.sendInfoMessage(AUUIDTransaccion, ATransaccion, AProceso, AMensaje : String); begin dmMonitor.SendInfo(AUUIDTransaccion, AProceso, ATransaccion, INFO_MESSAGE, AMensaje); end; class procedure TMonitor.sendWarningMessage(AUUIDTransaccion, ATransaccion, AProceso, AMensaje : String); begin dmMonitor.SendInfo(AUUIDTransaccion, AProceso, ATransaccion, WARNING_MESSAGE, AMensaje); end; class procedure TMonitor.endMonitorProcess(AUUIDTransaccion : String); begin dmMonitor.endMonitorProcess(AUUIDTransaccion); end; {Utilitarios Generales} class function TUtilidades.base64Decode(AMessage: String): String; var base64Decoder : TIdDecoderMIME; strResult : String; begin try base64Decoder := TIdDecoderMIME.Create(nil); strResult := base64Decoder.DecodeString(AMessage); result := strResult; finally FreeAndNil(base64Decoder); end; end; class function TUtilidades.base64Encode(AMessage: String): String; var base64Encoder : TIdEncoderMIME; strResult : String; begin try base64Encoder := TIdEncoderMIME.Create(nil); strResult := base64Encoder.EncodeString(AMessage); result := strResult; finally FreeAndNil(base64Encoder); end; end; class function TUtilidades.getGUID: String; var resultGUID : HResult; strGUID : String; GUID : TGuid; begin resultGUID := CreateGUID(GUID); if resultGUID = S_OK then strGUID := MidStr(GuidToString(GUID), INICIO_GUID, FINAL_GUID); result := strGUID; end; class function TUtilidades.getHostName: String; var buffer : Array[0 .. MAX_COMPUTERNAME_LENGTH] of Char; maxSize : Cardinal; strHostName : String; index : Integer; begin index := 0; maxSize := SizeOf(buffer); try if not GetComputerName(@buffer, maxSize) then strHostName := ''; while Cardinal(index) < Cardinal(Maxsize) do begin strHostName := strHostName + Buffer[index] ; inc(index); end; except on e : exception do strHostName := ''; end; result := strHostName; end; class function TUtilidades.getIpAddress: String; var strIp : String; buffer : Array[0 .. MAX_COMPUTERNAME_LENGTH] of Char; maxSize : Cardinal; wsaData : TWSAData; hostEnt : PHostEnt; begin try if WSAStartup(MakeWord(1,1), wsaData) = 0 then begin HostEnt := gethostbyname(PAnsiChar(GetComputerName(@Buffer, MaxSize))); if HostEnt <> nil then strIP := String(inet_ntoa(PInAddr(HostEnt.h_addr_list^)^)); WSACleanup; end; except on e : exception do strIp := ''; end; result := strIp; end; class function TUtilidades.GetTemplate(AUUID, AtxPlantilla: String; out AStatusDesc, APlantilla : String): Boolean; var consumoExitoso : Boolean; xdmPersistenceQuery : TdmPersistenceQueryClient; transaccionExitosa : Boolean; begin try transaccionExitosa := false; xdmPersistenceQuery := TdmPersistenceQueryClient.create_(ServerDataModule.FCallIntegrationHost, ServerDataModule.FCallIntegrationPersistencePort); //Parametros de consumo (tx) (campos) (filtro) (orden) (tipo respuesta) (index) consumoExitoso := xdmPersistenceQuery.query(AUUID, 'TX006', 'tx_mensaje,plantilla_respuesta','tx_mensaje='+QuotedStr(AtxPlantilla),'', 'BINARY', 'tx_mensaje'); if consumoExitoso then begin APlantilla := xdmPersistenceQuery.MemConsulta.FieldByName('plantilla_respuesta').AsString; if APlantilla <> '' then begin APlantilla := TUtilidades.base64Decode(APlantilla); AStatusDesc := xdmPersistenceQuery.FMensajeAlerta; transaccionExitosa := true; end else AStatusDesc := 'Transaccion o plantilla NO configurada'; end else begin AStatusDesc := xdmPersistenceQuery.FMensajeAlerta; end; finally FreeAndNil(xdmPersistenceQuery); end; result := transaccionExitosa; end; { TProcesarMensaje<T> } class function TProcesarMensaje<T>.cadenaAObjeto(ACadena : String): T; begin result := TJson.JsonToObject<T>(ACadena); end; class function TProcesarMensaje<T>.objetoACadena(AObjeto : T): String; begin result := TJson.ObjectToJsonString(AObjeto); end; { TMedirTiempo } constructor TMedirTiempo.beginProcess; begin QueryPerformanceFrequency(frequency64); QueryPerformanceCounter(startTime64); end; function TMedirTiempo.getProcessTime: String; var strResult : String; elapsedMilliSeconds : single; begin QueryPerformanceCounter(endTime64); elapsedMilliSeconds := ( (endTime64 - startTime64) / frequency64 ) * MIL_MILISEGUNDOS; strResult := FloatToStr(elapsedMilliSeconds); result := strResult; end; class function TUtilidades.getTime: String; var startTime64 : Int64; strResult : String; begin QueryPerformanceCounter(startTime64); strResult := startTime64.toString; result := strResult; end; class function TUtilidades.getDateTime: String; var strDate : String; strTime : String; strDateTime : String; begin DateTimeToString(strDate, 'yyyy-mm-dd', now); DateTimeToString(strTime, 'hh:nn:ss', now); strDateTime := strDate + 'T' + strTime; result := strDateTime; end; class function TUtilidades.getElapsedTime(AInitTime: String): String; var startTime64 : Int64; endTime64 : Int64; frequency64 : Int64; strResult : String; elapsedMilliSeconds : single; begin startTime64 := StrToInt64(AInitTime); QueryPerformanceFrequency(frequency64); QueryPerformanceCounter(endTime64); elapsedMilliSeconds := ( (endTime64 - startTime64) / frequency64 ) * MIL_MILISEGUNDOS; strResult := FloatToStr(elapsedMilliSeconds); result := strResult; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.metadata.sqlite; interface uses DB, SysUtils, Variants, Generics.Collections, dbcbr.metadata.register, dbcbr.metadata.extract, dbcbr.database.mapping, dbebr.factory.interfaces; type TCatalogMetadataSQLite = class(TCatalogMetadataAbstract) private procedure ResolveFieldType(AColumn: TColumnMIK; ATypeName: string); protected function GetSelectTables: string; override; function GetSelectTableColumns(ATableName: string): string; override; function GetSelectPrimaryKey(ATableName: string): string; override; function GetSelectForeignKey(ATableName: string): string; override; function GetSelectIndexe(ATableName: string): string; override; function GetSelectIndexeColumns(AIndexeName: string): string; override; function GetSelectTriggers(ATableName: string): string; override; function GetSelectViews: string; function GetSelectSequences: string; override; function Execute: IDBResultSet; public procedure CreateFieldTypeList; override; procedure GetCatalogs; override; procedure GetSchemas; override; procedure GetTables; override; procedure GetColumns(ATable: TTableMIK); override; procedure GetPrimaryKey(ATable: TTableMIK); override; procedure GetIndexeKeys(ATable: TTableMIK); override; procedure GetForeignKeys(ATable: TTableMIK); override; procedure GetTriggers(ATable: TTableMIK); override; procedure GetChecks(ATable: TTableMIK); override; procedure GetSequences; override; procedure GetProcedures; override; procedure GetFunctions; override; procedure GetViews; override; procedure GetDatabaseMetadata; override; end; implementation { TSchemaExtractSQLite } procedure TCatalogMetadataSQLite.CreateFieldTypeList; begin if Assigned(FFieldType) then begin FFieldType.Clear; FFieldType.Add('INTEGER', ftInteger); FFieldType.Add('DATE', ftDate); FFieldType.Add('INT', ftInteger); FFieldType.Add('BIGINT', ftLargeint); FFieldType.Add('SMALLINT', ftSmallint); FFieldType.Add('CHAR', ftFixedChar); FFieldType.Add('VARCHAR', ftString); FFieldType.Add('NVARCHAR', ftWideString); FFieldType.Add('CLOB', ftMemo); FFieldType.Add('BLOB', ftMemo); FFieldType.Add('TEXT', ftMemo); FFieldType.Add('FLOAT', ftFloat); FFieldType.Add('REAL', ftFloat); FFieldType.Add('BOOLEAN', ftBoolean); FFieldType.Add('TIME', ftTime); FFieldType.Add('DATETIME', ftDateTime); FFieldType.Add('TIMESTAMP', ftTimeStamp); FFieldType.Add('NUMERIC', ftBCD); FFieldType.Add('DECIMAL', ftBCD); FFieldType.Add('GUID', ftGuid); end; end; function TCatalogMetadataSQLite.Execute: IDBResultSet; var oSQLQuery: IDBQuery; begin inherited; oSQLQuery := FConnection.CreateQuery; try oSQLQuery.CommandText := FSQLText; Exit(oSQLQuery.ExecuteQuery); except raise end; end; procedure TCatalogMetadataSQLite.GetDatabaseMetadata; begin inherited; GetCatalogs; end; procedure TCatalogMetadataSQLite.GetCatalogs; begin inherited; FCatalogMetadata.Name := ''; GetSchemas; end; procedure TCatalogMetadataSQLite.GetChecks(ATable: TTableMIK); begin /// Not Suported. end; procedure TCatalogMetadataSQLite.GetSchemas; begin inherited; FCatalogMetadata.Schema := ''; GetTables; end; procedure TCatalogMetadataSQLite.GetTables; var oDBResultSet: IDBResultSet; oTable: TTableMIK; begin inherited; FSQLText := GetSelectTables; oDBResultSet := Execute; while oDBResultSet.NotEof do begin oTable := TTableMIK.Create(FCatalogMetadata); oTable.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oTable.Description := ''; /// <summary> /// Extrair colunas da tabela /// </summary> GetColumns(oTable); /// <summary> /// Extrair Primary Key da tabela /// </summary> GetPrimaryKey(oTable); /// <summary> /// Extrair Foreign Keys da tabela /// </summary> GetForeignKeys(oTable); /// <summary> /// Extrair Indexes da tabela /// </summary> GetIndexeKeys(oTable); /// <summary> /// Extrair Checks da tabela /// </summary> GetChecks(oTable); /// <summary> /// Adiciona na lista de tabelas extraidas /// </summary> FCatalogMetadata.Tables.Add(UpperCase(oTable.Name), oTable); end; end; procedure TCatalogMetadataSQLite.GetColumns(ATable: TTableMIK); var oDBResultSet: IDBResultSet; oColumn: TColumnMIK; begin inherited; FSQLText := GetSelectTableColumns(ATable.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oColumn.Description := oColumn.Name; oColumn.Position := VarAsType(oDBResultSet.GetFieldValue('cid'), varInteger); /// <summary> /// O método ResolveTypeField() extrai e popula as propriedades relacionadas abaixo /// </summary> /// <param name="AColumn: TColumnMIK">Informar [oColumn] para receber informações adicionais /// </param> /// <param name="ATypeName: String">Campo com descriçao do tipo que veio na extração do metadata /// </param> /// <remarks> /// Relação das propriedades que serão alimentadas no método ResolveTypeField() /// oColumn.TypeName: string; /// oColumn.FieldType: TTypeField; /// oColumn.Size: Integer; /// oColumn.Precision: Integer; /// oColumn.Scale: Integer; /// </remarks> ResolveFieldType(oColumn, VarToStr(oDBResultSet.GetFieldValue('type'))); /// oColumn.NotNull := oDBResultSet.GetFieldValue('notnull') = 1; oColumn.DefaultValue := VarToStr(oDBResultSet.GetFieldValue('dflt_value')); ATable.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn); end; end; procedure TCatalogMetadataSQLite.GetPrimaryKey(ATable: TTableMIK); function GetPrimaryKeyName(ATableName: string): string; begin Exit('PK_' + ATableName); end; function GetColumnAutoIncrement(ATableName: string): Integer; var oDBResultSet: IDBResultSet; begin FSQLText := ' select count(*) as autoinc ' + ' from sqlite_sequence ' + ' where name = ''' + ATableName + ''' ' + ' order by name'; try oDBResultSet := Execute; except Exit(0); end; Exit(oDBResultSet.GetFieldValue('autoinc')); end; procedure GetPrimaryKeyColumns(APrimaryKey: TPrimaryKeyMIK); var oDBResultSet: IDBResultSet; oColumn: TColumnMIK; begin FSQLText := Format('PRAGMA table_info("%s")', [ATable.Name]); oDBResultSet := Execute; while oDBResultSet.NotEof do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oColumn.NotNull := oDBResultSet.GetFieldValue('notnull') = 1; oColumn.Position := VarAsType(oDBResultSet.GetFieldValue('cid'), varInteger); APrimaryKey.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn); end; end; var oDBResultSet: IDBResultSet; begin inherited; FSQLText := GetSelectPrimaryKey(ATable.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin if VarAsType(oDBResultSet.GetFieldValue('pk'), varInteger) = 1 then begin ATable.PrimaryKey.Name := GetPrimaryKeyName(ATable.Name); ATable.PrimaryKey.Description := ''; ATable.PrimaryKey.AutoIncrement := GetColumnAutoIncrement(ATable.Name) > 0; /// <summary> /// Estrai as columnas da primary key /// </summary> GetPrimaryKeyColumns(ATable.PrimaryKey); Break end; end; end; procedure TCatalogMetadataSQLite.GetForeignKeys(ATable: TTableMIK); var oDBResultSet: IDBResultSet; oForeignKey: TForeignKeyMIK; oFromField: TColumnMIK; oToField: TColumnMIK; iID: Integer; begin inherited; iID := -1; /// <summary> /// No FireDAC ao executar o comando de extração das FKs de um table, e essa /// table não tiver FKs, ocorre um erro de Not ResultSet, mas se tiver, tudo /// ocorre normalmente, por isso o tratamento com try except /// </summary> try FSQLText := GetSelectForeignKey(ATable.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin if iID <> VarAsType(oDBResultSet.GetFieldValue('id'), varInteger) then begin oForeignKey := TForeignKeyMIK.Create(ATable); oForeignKey.Name := Format('FK_%s_%s', [VarToStr(oDBResultSet.GetFieldValue('table')), VarToStr(oDBResultSet.GetFieldValue('from'))]); oForeignKey.FromTable := VarToStr(oDBResultSet.GetFieldValue('table')); oForeignKey.OnUpdate := GetRuleAction(VarToStr(oDBResultSet.GetFieldValue('on_update'))); oForeignKey.OnDelete := GetRuleAction(VarToStr(oDBResultSet.GetFieldValue('on_delete'))); iID := VarAsType(oDBResultSet.GetFieldValue('id'), varInteger); ATable.ForeignKeys.Add(oForeignKey.Name, oForeignKey); end; /// <summary> /// Coluna tabela master /// </summary> oFromField := TColumnMIK.Create(ATable); oFromField.Name := VarToStr(oDBResultSet.GetFieldValue('from')); oForeignKey.FromFields.Add(oFromField.Name, oFromField); /// <summary> /// Coluna tabela filha /// </summary> oToField := TColumnMIK.Create(ATable); oToField.Name := VarToStr(oDBResultSet.GetFieldValue('to')); oForeignKey.ToFields.Add(oToField.Name, oToField); end; except end; end; procedure TCatalogMetadataSQLite.GetFunctions; begin inherited; end; procedure TCatalogMetadataSQLite.GetProcedures; begin inherited; end; procedure TCatalogMetadataSQLite.GetSequences; var oDBResultSet: IDBResultSet; oSequence: TSequenceMIK; begin inherited; FSQLText := GetSelectSequences; oDBResultSet := Execute; while oDBResultSet.NotEof do begin oSequence := TSequenceMIK.Create(FCatalogMetadata); oSequence.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oSequence.Description := VarToStr(oDBResultSet.GetFieldValue('description'));; FCatalogMetadata.Sequences.Add(UpperCase(oSequence.Name), oSequence); end; end; procedure TCatalogMetadataSQLite.GetTriggers(ATable: TTableMIK); var oDBResultSet: IDBResultSet; oTrigger: TTriggerMIK; begin inherited; FSQLText := GetSelectTriggers(ATable.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin oTrigger := TTriggerMIK.Create(ATable); oTrigger.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oTrigger.Description := ''; oTrigger.Script := VarToStr(oDBResultSet.GetFieldValue('sql')); ATable.Triggers.Add(UpperCase(oTrigger.Name), oTrigger); end; end; procedure TCatalogMetadataSQLite.GetIndexeKeys(ATable: TTableMIK); var oDBResultSet: IDBResultSet; oIndexeKey: TIndexeKeyMIK; procedure GetIndexeKeyColumns(AIndexeKey: TIndexeKeyMIK); var oDBResultSet: IDBResultSet; oColumn: TColumnMIK; begin FSQLText := GetSelectIndexeColumns(AIndexeKey.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin oColumn := TColumnMIK.Create(ATable); oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('name')); AIndexeKey.Fields.Add(oColumn.Name, oColumn); end; end; begin inherited; FSQLText := GetSelectIndexe(ATable.Name); oDBResultSet := Execute; while oDBResultSet.NotEof do begin if VarAsType(oDBResultSet.GetFieldValue('origin'), varString) = 'pk' then Continue; oIndexeKey := TIndexeKeyMIK.Create(ATable); oIndexeKey.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oIndexeKey.Unique := VarAsType(oDBResultSet.GetFieldValue('unique'), varInteger) = 1; ATable.IndexeKeys.Add(UpperCase(oIndexeKey.Name), oIndexeKey); /// <summary> /// Gera a lista de campos do indexe /// </summary> GetIndexeKeyColumns(oIndexeKey); end; end; procedure TCatalogMetadataSQLite.GetViews; var oDBResultSet: IDBResultSet; oView: TViewMIK; begin inherited; FSQLText := GetSelectViews; oDBResultSet := Execute; while oDBResultSet.NotEof do begin oView := TViewMIK.Create(FCatalogMetadata); oView.Name := VarToStr(oDBResultSet.GetFieldValue('name')); oView.Description := ''; oView.Script := VarToStr(oDBResultSet.GetFieldValue('sql')); FCatalogMetadata.Views.Add(UpperCase(oView.Name), oView); end; end; procedure TCatalogMetadataSQLite.ResolveFieldType(AColumn: TColumnMIK; ATypeName: string); var iPos1, iPos2: Integer; sDefArgs: string; procedure SetPrecScale(ADefPrec, ADefScale: Integer); var sSize, sPrecision, sCale: string; iPos: Integer; begin iPos := Pos(',', sDefArgs); if iPos = 0 then AColumn.Size := StrToIntDef(sDefArgs, ADefPrec) else begin sPrecision := Copy(sDefArgs, 1, iPos - 1); sCale := Copy(sDefArgs, iPos + 1, Length(sDefArgs)); AColumn.Precision := StrToIntDef(sPrecision, ADefScale); AColumn.Scale := StrToIntDef(sCale, ADefPrec); end; end; begin AColumn.FieldType := ftUnknown; AColumn.Size := 0; AColumn.Precision := 0; ATypeName := Trim(UpperCase(ATypeName)); sDefArgs := ''; iPos1 := Pos('(', ATypeName); iPos2 := Pos(')', ATypeName); if iPos1 > 0 then begin sDefArgs := Copy(ATypeName, iPos1 + 1, iPos2 - iPos1 - 1); ATypeName := Copy(ATypeName, 1, iPos1 - 1); SetPrecScale(0, 0); end; AColumn.TypeName := ATypeName; SetFieldType(AColumn); /// <summary> /// Resolve Field Type /// </summary> GetFieldTypeDefinition(AColumn); end; function TCatalogMetadataSQLite.GetSelectForeignKey(ATableName: string): string; begin Result := Format('PRAGMA foreign_key_list("%s")', [ATableName]); end; function TCatalogMetadataSQLite.GetSelectIndexe(ATableName: string): string; begin Result := Format('PRAGMA index_list("%s")', [ATableName]); end; function TCatalogMetadataSQLite.GetSelectIndexeColumns(AIndexeName: string): string; begin Result := Format('PRAGMA index_info("%s")', [AIndexeName]); end; function TCatalogMetadataSQLite.GetSelectPrimaryKey(ATableName: string): string; begin Result := Format('PRAGMA table_info("%s")', [ATableName]); end; function TCatalogMetadataSQLite.GetSelectSequences: string; begin Result := ' select name ' + ' from sqlite_sequence ' + ' order by name'; end; function TCatalogMetadataSQLite.GetSelectTableColumns(ATableName: string): string; begin Result := Format('PRAGMA table_info("%s")', [ATableName]); end; function TCatalogMetadataSQLite.GetSelectTables: string; begin Result := ' select name ' + ' from sqlite_master ' + ' where type = ''table'' ' + ' and tbl_name not like ''sqlite_%'' ' + ' order by name '; end; function TCatalogMetadataSQLite.GetSelectTriggers(ATableName: string): string; begin Result := ' select name ' + ' from sqlite_master ' + ' where type = ''trigger'' ' + ' and tbl_name = ''' + ATableName + ''' ' + ' order by name '; end; function TCatalogMetadataSQLite.GetSelectViews: string; begin Result := ' select name ' + ' from sqlite_master ' + ' where type = ''view'' ' + ' and tbl_name not like ''sqlite_%'' ' + ' order by name '; end; initialization TMetadataRegister.GetInstance.RegisterMetadata(dnSQLite, TCatalogMetadataSQLite.Create); end.
unit _util; interface function StrToFloatDef(strValue : String; defValue : Single{Extended}) : Single{Extended}; implementation uses strings; function StrToFloatDef(strValue : String; defValue : Single{Extended}) : Single{Extended}; var i, divider, lLen : Integer; c : Char; begin Result:=0; if strValue='' then Exit; divider:=MaxInt; strValue:=Trim(StrValue); lLen:=length(strValue); for i:=1 to lLen do begin c:=strValue[i]; case c of '0'..'9' : Result:=(Result*10)+Integer(c)-Integer('0'); ',', '.' : begin if (divider=MaxInt) then divider:=i else begin Result:=defValue; Exit; end; end; '-', '+' : if i>1 then begin Result:=defValue; Exit; end; else if (c<>' ') or (divider<>MaxInt) then begin Result:=defValue; Exit; end; end; end; divider:=lLen-divider; if divider>0 then Result:=Result*Exp(-divider*Ln(10)); if (strValue[1]='-') then Result:=-Result; end; end.
(* Модуль : DBTV Категория : .. Версия: 3.0 Автор : Маракасов Ф. В. 22/07/09 +Поддержка IActionsProvider *) { --- Последняя модификация: 01.05.2009 23:20:20 --- } {#Author fmarakasov@ugtu.net} unit DBTV; interface uses Windows, comctrls, classes, db, ShEvent, Graphics, Variants, ActnList, Menus, CoreInterfaces, Contnrs; type TDBTreeView = class; TDBNodeObject = class; TDBNodeObjectList = class; // Типы операций над узлом TNodeAction = (taAdd, taDelete, taUpdate, taCopy, taPaste, taCut); // Класс типа узла TDBNodeClass = class of TDBNodeObject; // Делегат функции фильтрации узла дерева. TNodeFilterFunc = function(NodeObject : TDBNodeObject) : Boolean; TActionObjectList = class(TObjectList) private function GetItems(Index: integer): TAction; public property Items[Index: integer]: TAction read GetItems; constructor Create; end; /// /// Класс, объекты которого сопоставляются /// с узлами дерева и /// управляют загрузкой /// дочерних узлов по требованию и /// обработкой событий. /// TDBNodeObject = class (TInterfacedObject, IActionsProvider) private FDataSet: TDataSet; FFont: TFont; FID: Integer; FNode: TTreeNode; FParent: TDBNodeObject; FTreeView: TDBTreeView; FValue: Variant; FTerminal : Boolean; FAssosiatedClass : TClass; FFilter : TNodeFilterFunc; FPopupMenu : TPopupMenu; FLazyLoaded : Boolean; FActionCatigories : TStrings; function GetCanAddExecute: Boolean; function GetCanCopyExecute: Boolean; function GetCanCutExecute: Boolean; function GetCanDeleteExecute: Boolean; function GetCanPasteExecute: Boolean; function GetCanUpdateExecute: Boolean; function GetNodeActionCaption(NodeAction:TNodeAction): string; function GetNodeActions : TActionObjectList; function GetLogger : ILogger; procedure BuildPopupMenu; protected FChildAdded: Boolean; FName: string; function DoAddChildNodes:Boolean;virtual; function DoCanAddExecute: Boolean; virtual; function DoCanCopyExecute: Boolean; virtual; function DoCanCutExecute: Boolean; virtual; function DoCanDeleteExecute: Boolean; virtual; function DoCanPasteExecute: Boolean; virtual; function DoCanUpdateExecute: Boolean; virtual; function DoNodeActionCaption(NodeAction:TNodeAction): string; virtual; function GetActionList : TActionList;virtual; function CreateTreeNode(Caption:String; TNodeClass:TDBNodeClass; TerminalNode : Boolean = false) : TTreeNode; overload; function GetNodeObjects : TDBNodeObjectList; function GetPopupMenu : TPopupMenu; procedure SetFont(const Font: TFont); procedure SetFiltered(Value : TNodeFilterFunc); property ActionList : TActionList read GetActionList; // Реализация IActionProvider function GetMyActions : TActionList; function GetMyCategories : TStrings; property ActionCategories : TStrings read GetMyCategories; public class function GetNodeObject(Node : TTreeNode) : TDBNodeObject;overload; /// Создаёт экземпляр класса /// Node - узел дерева, с которым связан экземпляр /// TreeView - дерево, с которым связан экземпляр /// TerminalNode - истина, если узул является терминальным в дереве constructor Create(Node:TTreeNode; TreeView:TDBTreeView; TerminalNode:Boolean); virtual; destructor Destroy; override; function AddChildNodes: Boolean; function ToString : String; procedure AddExecute(Sender:TObject); virtual; procedure CopyExecute(Sender:TObject); virtual; procedure CutExecute(Sender:TObject); virtual; procedure DeleteExecute(Sender:TObject); virtual; procedure PasteExecute(Sender:TObject); virtual; procedure Refresh; procedure Invalidate; procedure UpdateExecute(Sender:TObject); virtual; property CanAddExecute: Boolean read GetCanAddExecute; property CanCopyExecute: Boolean read GetCanCopyExecute; property CanCutExecute: Boolean read GetCanCutExecute; property CanDeleteExecute: Boolean read GetCanDeleteExecute; property CanPasteExecute: Boolean read GetCanPasteExecute; property CanUpdateExecute: Boolean read GetCanUpdateExecute; property DataSet: TDataSet read FDataSet write FDataSet; property Font: TFont read FFont write SetFont; property ID: Integer read FID write FID; property Name: string read FName write FName; property Node: TTreeNode read FNode write FNode; property NodeActionCaption[NodeAction:TNodeAction]: string read GetNodeActionCaption; property Parent: TDBNodeObject read FParent write FParent; property TreeView: TDBTreeView read FTreeView write FTreeView; property Value: Variant read FValue write FValue; property IsTerminal : Boolean read FTerminal; property AssosiatedClass : TClass read FAssosiatedClass write FAssosiatedClass; property NodeActions : TActionObjectList read GetNodeActions; property Filter : TNodeFilterFunc read FFilter write SetFiltered; property NodeObjects : TDBNodeObjectList read GetNodeObjects; property PopupMenu : TPopupMenu read GetPopupMenu; property Logger : ILogger read GetLogger; property LazyLoad : Boolean read FLazyLoaded write FLazyLoaded; end; TDBNodeObjectList = class(TObjectList) private function GetItems(Index: integer): TDBNodeObject; public property Items[Index: integer]: TDBNodeObject read GetItems; constructor Create; end; // Событие до вызова AddChildNodes TBeforeAddChildEvent = procedure (Sender : TDBNodeObject; var Allow:Boolean) of object; // Событие после вызова AddChildNodes TAfterAddChildEvent = procedure (Sender:TDBNodeObject) of object; TDBActionsDictionaryItem = class private FActionObjectList: TActionObjectList; FNodeClass: TDBNodeClass; public property NodeClass: TDBNodeClass read FNodeClass write FNodeClass; property ActionObjectList: TActionObjectList read FActionObjectList write FActionObjectList; end; TDBActionsDictionary = class(TObjectList) private FActionsDictionary: TDBActionsDictionary; constructor Create; function GetItemsByIndex(Index: integer): TDBActionsDictionaryItem; public class function GetInstance : TDBActionsDictionary; destructor Destroy;override; function ContainsKey(Key : TDBNodeClass): boolean; function GetItem(Key : TDBNodeClass): TActionObjectList; function Add(Key: TDBNodeClass; AActionList: TActionObjectList): TDBActionsDictionaryItem; property ItemsByIndex[Index: integer]: TDBActionsDictionaryItem read GetItemsByIndex; property Items[Key : TDBNodeClass] : TActionObjectList read GetItem; default; end; /// /// Базовый класс деревьев, поддерживающих /// узлы, сопоставленные с типом TDBNodeObject /// с загрузкой дочерних узлов в /// режиме "по требованию" /// TDBTreeView = class (TTreeView) private FAfterAdd: TAfterAddChildEvent; FBeforeAdd: TBeforeAddChildEvent; FOnCanAddExecute: TCanActionEvent; FOnCanCopyExecute: TCanActionEvent; FOnCanCutExecute: TCanActionEvent; FOnCanDeleteExecute: TCanActionEvent; FOnCanPasteExecute: TCanActionEvent; FOnCanSelectAllExecute: TCanActionEvent; FOnCanUpdateExecute: TCanActionEvent; FLogger : ILogger; FSuspendDeletion : Boolean; //FNodeObjects : TObjectList<TDBNodeObject>; FActionList : TActionList; FOnActivate : TNotifyEvent; FActive : Boolean; procedure SetActive(Value : Boolean); function GetCanActionEvent(FEvent:TCanActionEvent; bCan:boolean): Boolean; function GetCanAdd: Boolean; function GetCanCopy: Boolean; function GetCanCut: Boolean; function GetCanDelete: Boolean; function GetCanPaste: Boolean; function GetCanSelectAll: Boolean; function GetCanUpdate: Boolean; function GetNodeActionCaption(NodeAction:TNodeAction): string; class function GetNodeActions(NodeClass : TDBNodeClass) : TActionObjectList; function GetMainOfSelectedObject: TDBNodeObject; protected function GetLogger : ILogger; procedure OnActivate;virtual; function CanExpand(Node: TTreeNode): Boolean; override; function GetObject: TDBNodeObject; virtual; function GetNodeObjects : TDBNodeObjectList; procedure Delete(Node: TTreeNode);override; public constructor Create(AOwner:TComponent); override; destructor Destroy;override; procedure AddExecute(Sender:TObject); virtual; procedure CopyExecute(Sender:TObject); virtual; function CreateTreeNode(ParentNode:TTreeNode; Caption:String; TNodeClass:TDBNodeClass; TerminalNode:Boolean = false) : TTreeNode; overload; function GetNodeObject(Node:TTreeNode): TDBNodeObject; overload; function GetNodeObjectByName(AName: string; FirstNode: TTreeNode = nil; Expand: Boolean = false): TDBNodeObject; overload; procedure CutExecute(Sender:TObject); virtual; procedure DeleteExecute(Sender:TObject); virtual; procedure PasteExecute(Sender:TObject); virtual; procedure RefreshExecute(Sender:TObject); virtual; procedure SelectAllExecute(Sender:TObject); virtual; procedure UpdateExecute(Sender:TObject); virtual; procedure TryShowPopupMenuOnSelectedNode; procedure InvalidateRoots; property CanAdd: Boolean read GetCanAdd; property CanCopy: Boolean read GetCanCopy; property CanCut: Boolean read GetCanCut; property CanDelete: Boolean read GetCanDelete; property CanPaste: Boolean read GetCanPaste; property CanSelectAll: Boolean read GetCanSelectAll; property CanUpdate: Boolean read GetCanUpdate; property NodeActionCaption[NodeAction:TNodeAction]: string read GetNodeActionCaption; property NodeObject[Node:TTreeNode]: TDBNodeObject read GetNodeObject; property SelectedObject: TDBNodeObject read GetObject; property MainOfSelectedObject: TDBNodeObject read GetMainOfSelectedObject; property NodeObjects : TDBNodeObjectList read GetNodeObjects; property ActionList : TActionList read FActionList write FActionList; property Active : Boolean read FActive write SetActive; property Logger : ILogger read GetLogger write FLogger; property SuspendDeletion : Boolean read FSuspendDeletion write FSuspendDeletion; published property OnAfterAddChild: TAfterAddChildEvent read FAfterAdd write FAfterAdd; property OnBeforeAddChild: TBeforeAddChildEvent read FBeforeAdd write FBeforeAdd; property OnCanAddExecute: TCanActionEvent read FOnCanAddExecute write FOnCanAddExecute; property OnCanCopyExecute: TCanActionEvent read FOnCanCopyExecute write FOnCanCopyExecute; property OnCanCutExecute: TCanActionEvent read FOnCanCutExecute write FOnCanCutExecute; property OnCanDeleteExecute: TCanActionEvent read FOnCanDeleteExecute write FOnCanDeleteExecute; property OnCanPasteExecute: TCanActionEvent read FOnCanPasteExecute write FOnCanPasteExecute; property OnCanSelectAllExecute: TCanActionEvent read FOnCanSelectAllExecute write FOnCanSelectAllExecute; property OnCanUpdateExecute: TCanActionEvent read FOnCanUpdateExecute write FOnCanUpdateExecute; property Activated : TNotifyEvent read FOnActivate write FOnActivate; end; implementation uses Controls, SysUtils, ExceptionExt, LoggerImpl; /////////////////////////////////////////////////////////////////////////// { ********************************* TDBTreeView ********************************** } constructor TDBTreeView.Create(AOwner:TComponent); begin inherited Create(AOwner); ChangeDelay := 0; ReadOnly:=true; FActive := false; //FNodeObjects := TObjectList<TDBNodeObject>.Create(true); end; procedure TDBTreeView.AddExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.AddExecute(Sender); end; function TDBTreeView.CanExpand(Node: TTreeNode): Boolean; var Obj: TDBNodeObject; Allow: Boolean; begin // Получаем ссылку на объект узла Obj:=TDBNodeObject(Node.Data); Cursor:=crHourGlass; // По умолчанию позволяем вызов функции AddChildNodes Allow:=true; try if Assigned(Obj) then begin // Событие до добавления if Assigned (FBeforeAdd) then FBeforeAdd(Obj, Allow); // Если позволено вызывать AddChildNodes if (Allow) then begin Obj.AddChildNodes; // Событие после добавления if Assigned (FAfterAdd) then FAfterAdd(Obj); end; end; Result:=inherited CanExpand(Node); finally Node.HasChildren:=(Node.Count >0); Cursor:=crDefault; end; end; procedure TDBTreeView.CopyExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.CopyExecute(Sender); end; function TDBTreeView.CreateTreeNode(ParentNode:TTreeNode; Caption:String; TNodeClass:TDBNodeClass; TerminalNode:Boolean): TTreeNode; begin Assert(TNodeClass <> nil, 'TDBTreeView.CreateTreeNode: TNodeClass can not be null!'); Result := Items.AddChild(ParentNode, Caption); Result.Data := TNodeClass.Create(Result, Self, TerminalNode); //TDBNodeObject(Result.Data)._AddRef; end; procedure TDBTreeView.CutExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.CutExecute(Sender); end; procedure TDBTreeView.Delete(Node: TTreeNode); var NodeObj : TDBNodeObject; begin if SuspendDeletion then Exit; if (Assigned(Node)) then begin NodeObj := TDBNodeObject(Node.Data); if Assigned(NodeObj) then begin Logger.LogMessage('Deleting ' + NodeObj.ClassName + ' of TreeNode ' + Node.Text); //NodeObj.Free; Node.Data := nil; end; end; inherited; end; procedure TDBTreeView.DeleteExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.DeleteExecute(Sender); end; destructor TDBTreeView.Destroy; begin Logger.LogMessage(Self.ClassName + ' destructor called!'); inherited; end; function TDBTreeView.GetCanActionEvent(FEvent:TCanActionEvent; bCan:boolean): Boolean; begin if Assigned(FEvent) then FEvent(Self, bCan); Result:=bCan; end; function TDBTreeView.GetCanAdd: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanAddExecute else Result:=true; Result:=GetCanActionEvent(FOnCanAddExecute, Result); end; function TDBTreeView.GetCanCopy: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanCopyExecute else Result:=true; Result:=GetCanActionEvent(FOnCanCopyExecute, Result); end; function TDBTreeView.GetCanCut: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanCutExecute else Result:=true; Result:=GetCanActionEvent(FOnCanCutExecute, Result); end; function TDBTreeView.GetCanDelete: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanDeleteExecute else Result:=true; Result:=GetCanActionEvent(FOnCanDeleteExecute, Result); end; function TDBTreeView.GetCanPaste: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanPasteExecute else Result:=true; Result:=GetCanActionEvent(FOnCanPasteExecute, Result); end; function TDBTreeView.GetCanSelectAll: Boolean; begin Result:=Selected<>nil; end; function TDBTreeView.GetCanUpdate: Boolean; begin if Selected <> nil then Result:=SelectedObject.CanUpdateExecute else Result:=true; Result:=GetCanActionEvent(FOnCanUpdateExecute, Result); end; function TDBTreeView.GetLogger: ILogger; begin if FLogger = nil then FLogger := TNullLogger.GetInstance; Result := FLogger; end; function TDBTreeView.GetNodeActionCaption(NodeAction:TNodeAction): string; begin if Assigned(Selected) then Result:=SelectedObject.NodeActionCaption[NodeAction] else Result:=''; end; class function TDBTreeView.GetNodeActions( NodeClass: TDBNodeClass): TActionObjectList; begin Result := TDBActionsDictionary.GetInstance[NodeClass]; end; function TDBTreeView.GetNodeObject(Node:TTreeNode): TDBNodeObject; begin Result:=nil; if Assigned(Node) then if Assigned(Node.Data) then Result:=TDBNodeObject(Node.Data); end; function TDBTreeView.GetNodeObjects: TDBNodeObjectList; begin raise ENotImplemented.Create; end; function TDBTreeView.GetObject: TDBNodeObject; begin Result:=nil; if Assigned(Selected) then if Assigned(Selected.Data) then Result:=TDBNodeObject(Selected.Data); end; procedure TDBTreeView.OnActivate; begin if Assigned(FOnActivate) then FOnActivate(Self); end; procedure TDBTreeView.PasteExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.PasteExecute(Sender); end; procedure TDBTreeView.RefreshExecute(Sender:TObject); var NodeObj: TDBNodeObject; NodeText: string; NodeIndex: Integer; Expanded: Boolean; begin if Selected <> nil then begin // Запомним текст и индекс обновляемого узла NodeText:=Selected.Text; NodeIndex:=Selected.Index; // Определяем, что будет обновляемым узлом: текущий или родительский if (Selected.Expanded) or (Selected.Parent = nil) then NodeObj:=SelectedObject else NodeObj:=SelectedObject.Parent; // Запомним состояние узла до обновления Expanded:=NodeObj.Node.Expanded; NodeObj.Refresh; if Expanded then begin NodeObj.Node.Expand(false); // Переход к запомненному узлу (если он существует) if NodeObj.Node.Count > NodeIndex then if CompareStr(NodeObj.Node[NodeIndex].Text, NodeText) = 0 then NodeObj.Node[NodeIndex].Selected:=true; end; end; end; procedure TDBTreeView.InvalidateRoots; var I: Integer; ListToInvalidate : TList; begin ListToInvalidate := TList.Create; for I := 0 to Items.Count - 1 do begin if (Self.Items[I].Parent = nil) then ListToInvalidate.Add(Self.Items[I]); end; for I := 0 to ListToInvalidate.Count - 1 do GetNodeObject(TTreeNode(ListToInvalidate[I])).Invalidate; end; procedure TDBTreeView.SelectAllExecute(Sender:TObject); var i: Integer; Node: TTreeNode; begin if MultiSelect then begin if Selected <> nil then begin if Selected.Expanded then Node:=Selected else if Selected.Parent <> nil then Node:=Selected.Parent else Node:=nil; if Assigned(Node) then begin for i:=0 to Node.Count - 1 do Subselect(Node.Item[i]); end else for i:=0 to Items.Count - 1 do Subselect(Items[i]); end; end; end; procedure TDBTreeView.SetActive(Value: Boolean); begin if (Value = FActive)then Exit; Self.Items.Clear; if Value then OnActivate; FActive := Value; end; procedure TDBTreeView.TryShowPopupMenuOnSelectedNode; var PopupMenu : TPopupMenu; Point : TPoint; begin if SelectedObject = nil then Exit; PopupMenu := SelectedObject.GetPopupMenu; if (PopupMenu <> nil) then begin Selected.MakeVisible; Point := Mouse.CursorPos; PopupMenu.Popup(Point.X, Point.Y); end; end; procedure TDBTreeView.UpdateExecute(Sender:TObject); begin if Selected <> nil then SelectedObject.UpdateExecute(Sender); end; { ******************************** TDBNodeObject ********************************* } procedure TDBNodeObject.CopyExecute(Sender: TObject); begin end; constructor TDBNodeObject.Create(Node: TTreeNode; TreeView: TDBTreeView; TerminalNode: Boolean); begin inherited Create; Assert(Assigned(Node), 'TDBNodeObject.Create: Node can not be null!'); Assert(Assigned(TreeView), 'TDBNodeObject.Create: TreeView cant be null!'); FID:=-1; FNode:=Node; FDataSet:=nil; FChildAdded:=false; FValue:=Unassigned; FFont:=TFont.Create; FTreeView:=TreeView; FName:=Node.Text; if Assigned(Node.Parent) then FParent:=TDBNodeObject(Node.Parent.Data); FTerminal := TerminalNode; Node.HasChildren := not TerminalNode; if not TerminalNode then TreeView.Items.AddChild(Node, 'Идет загрузка подчиненных узлов'); FActionCatigories := TStringList.Create; Logger.LogMessage(Format('constructor %s.Create(Node=%s, TreeView=%s, TerminalNode=%s', [Self.ClassName, Node.Text, TreeView.Name, BoolToStr(TerminalNode)])); end; function TDBNodeObject.CreateTreeNode(Caption: String; TNodeClass: TDBNodeClass; TerminalNode : Boolean): TTreeNode; begin Assert(TNodeClass <> nil, TDBNodeClass.ClassName + 'Can not be null!'); Result := TreeView.CreateTreeNode(Self.Node, Caption, TNodeClass, TerminalNode); end; procedure TDBNodeObject.CutExecute(Sender: TObject); begin end; destructor TDBNodeObject.Destroy; begin Logger.LogMessage(Format('destructor %s.Destroy', [Self.ClassName])); FreeAndNil(FFont); FreeAndNil(FActionCatigories); inherited; end; function TDBNodeObject.AddChildNodes: Boolean; begin Result := FChildAdded; if Result then Exit; FChildAdded := DoAddChildNodes; Result := FChildAdded; end; procedure TDBNodeObject.DeleteExecute(Sender:TObject); begin end; function TDBNodeObject.DoCanAddExecute: Boolean; begin Result:=true; end; function TDBNodeObject.DoCanCopyExecute: Boolean; begin Result:=true; end; function TDBNodeObject.DoCanCutExecute: Boolean; begin Result:=true; end; function TDBNodeObject.DoCanDeleteExecute: Boolean; begin Result:=true; end; function TDBNodeObject.DoCanPasteExecute: Boolean; begin Result:=true; end; function TDBNodeObject.DoCanUpdateExecute: Boolean; begin Result:=true; end; {{ Возвращает символьные имена операций над узлом дерева. --- Переопределите массив в производных классах --- } function TDBNodeObject.DoNodeActionCaption(NodeAction:TNodeAction): string; const NodeCaptionArray:array[Low(TNodeAction)..High(TNodeAction)] of string = ('Добавить объект', 'Удалить объект', 'Редактировать объект', 'Копировать объект', 'Вырезать объект', 'Вставить объект'); begin Result:=NodeCaptionArray[NodeAction]; end; function TDBNodeObject.GetActionList: TActionList; begin Result := nil; end; function TDBNodeObject.GetCanAddExecute: Boolean; begin Result:=DoCanAddExecute; end; function TDBNodeObject.GetCanCopyExecute: Boolean; begin Result:=DoCanCopyExecute; end; function TDBNodeObject.GetCanCutExecute: Boolean; begin Result:=DoCanCutExecute; end; function TDBNodeObject.GetCanDeleteExecute: Boolean; begin Result:=DoCanDeleteExecute; end; function TDBNodeObject.GetCanPasteExecute: Boolean; begin Result:=DoCanPasteExecute; end; function TDBNodeObject.GetCanUpdateExecute: Boolean; begin Result:=DoCanUpdateExecute; end; function TDBNodeObject.GetLogger: ILogger; begin Assert(Assigned(TreeView), 'Объект TreeView не может быть null!'); Result := TreeView.Logger; end; function TDBNodeObject.GetMyActions: TActionList; begin Result := ActionList; end; function TDBNodeObject.GetMyCategories: TStrings; begin Result := FActionCatigories; end; function TDBNodeObject.GetNodeActionCaption(NodeAction:TNodeAction): string; begin Result:=DoNodeActionCaption(NodeAction); end; function TDBNodeObject.GetNodeActions: TActionObjectList; begin Result := TDBTreeView.GetNodeActions(TDBNodeClass(Self.ClassType)); end; class function TDBNodeObject.GetNodeObject(Node: TTreeNode): TDBNodeObject; begin Assert(Node<>nil, 'TDBNodeObject.GetNodeObject: Node parameter can not be null!'); Result := TDBNodeObject(Node.Data); end; function TDBNodeObject.GetNodeObjects: TDBNodeObjectList; begin raise ENotImplemented.Create; end; function TDBNodeObject.GetPopupMenu: TPopupMenu; begin Result := nil; if ActionList = nil then Exit; if not Assigned(FPopupMenu) then FPopupMenu := TPopupMenu.Create(TreeView); BuildPopupMenu; Result := FPopupMenu; end; procedure TDBNodeObject.Invalidate; begin if Assigned(Node) then begin Node.DeleteChildren; if not IsTerminal then TreeView.Items.AddChild(Node, 'Идет загрузка'); Node.Expanded := false; end; FChildAdded:=false; end; procedure TDBNodeObject.PasteExecute(Sender:TObject); begin end; procedure TDBNodeObject.Refresh; begin Invalidate; AddChildNodes; end; procedure TDBNodeObject.SetFiltered(Value: TNodeFilterFunc); begin raise ENotImplemented.Create; //if Value = FFilter then Exit; FFilter := Value; Self.Refresh; end; procedure TDBNodeObject.SetFont(const Font: TFont); begin if Assigned(FFont) then FFont.Assign(Font); end; function TDBNodeObject.ToString: String; begin Result := Node.Text; end; procedure TDBNodeObject.UpdateExecute(Sender:TObject); begin end; procedure TDBNodeObject.AddExecute(Sender: TObject); begin end; procedure TDBNodeObject.BuildPopupMenu; var MenuItem: TMenuItem; Action: TBasicAction; I: Integer; begin FPopupMenu.Items.Clear; for I := 0 to ActionList.ActionCount - 1 do begin Action := nil; begin if Self.ActionCategories.IndexOf(ActionList[I].Category) > -1 then Action := ActionList[I]; end; if Action <> nil then begin MenuItem := TMenuItem.Create(FPopupMenu); MenuItem.Action := Action; FPopupMenu.Items.Add(MenuItem); end; end; end; { TDBActionsDictionary } function TDBActionsDictionary.Add(Key: TDBNodeClass; AActionList: TActionObjectList): TDBActionsDictionaryItem; begin Result := TDBActionsDictionaryItem.Create; Result.NodeClass := Key; Result.ActionObjectList := AActionList; inherited Add(Result); end; function TDBActionsDictionary.ContainsKey(Key: TDBNodeClass): boolean; var i: integer; begin Result := false; for i := 0 to Count - 1 do if ItemsByIndex[i].NodeClass = Key then begin Result := true; break; end; end; constructor TDBActionsDictionary.Create; begin FActionsDictionary := TDBActionsDictionary.Create; end; destructor TDBActionsDictionary.Destroy; begin FActionsDictionary.Free; inherited; end; class function TDBActionsDictionary.GetInstance: TDBActionsDictionary; const inst : TDBActionsDictionary = nil; begin if (inst = nil) then inst := TDBActionsDictionary.Create; Result := inst; end; function TDBActionsDictionary.GetItem(Key: TDBNodeClass): TActionObjectList; begin if not FActionsDictionary.ContainsKey(Key) then FActionsDictionary.Add(Key, TActionObjectList.Create); Result := FActionsDictionary[Key]; end; function TDBActionsDictionary.GetItemsByIndex( Index: integer): TDBActionsDictionaryItem; begin Result := inherited Items[Index] as TDBActionsDictionaryItem; end; { TActionObjectList } constructor TActionObjectList.Create; begin inherited Create(False); end; function TActionObjectList.GetItems(Index: integer): TAction; begin Result := inherited Items[Index] as TAction; end; { TDBNodeObjectList } constructor TDBNodeObjectList.Create; begin inherited Create(false); end; function TDBNodeObjectList.GetItems(Index: integer): TDBNodeObject; begin Result := TDBNodeObject(inherited Items[Index]); end; function TDBNodeObject.DoAddChildNodes: Boolean; begin Result := true; Self.Node.DeleteChildren; end; function TDBTreeView.GetNodeObjectByName(AName: string; FirstNode: TTreeNode = nil; Expand: Boolean = false): TDBNodeObject; var Node: TTreeNode; begin Result := nil; if not Assigned(FirstNode) then Node := Items.GetFirstNode else Node := FirstNode; while Assigned(Node) do begin if trim(Node.Text) = AName then begin Result := TDBNodeObject(Node.Data); break; end; if Expand then Node.Expand(false); Node := Node.GetNext; end; end; function TDBTreeView.GetMainOfSelectedObject: TDBNodeObject; var Node, NodeParent: TTreeNode; begin Node := SelectedObject.Node; while Assigned(Node) do begin NodeParent := Node; Node := Node.Parent; end; Result := TDBNodeObject(NodeParent.Data); end; end.
unit KiFill; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, Graphics, BCTypes; type { TFill } TFill = class(TPersistent) private FColor: TColor; FColorActive: TColor; FGradient: TBCGradient; FOpacity: Byte; FOwner: TPersistent; FUseGradient: Boolean; procedure SetGradient(const aValue: TBCGradient); procedure SetOpacity(const aValue: Byte); procedure SetColor(const aValue: TColor); procedure SetColorActive(const aValue: TColor); procedure SetUseGradient(const aValue: Boolean); public constructor Create(AOwner: TComponent); destructor Destroy; override; procedure Assign(Source: TPersistent); override; function GetOwner: TPersistent; override; published property Color: TColor read FColor write SetColor default clWhite; property ColorActive: TColor read FColorActive write SetColorActive default $00FFF2E7; //azul bem clarinho property Gradient: TBCGradient read FGradient write SetGradient; property Opacity: Byte read FOpacity write SetOpacity default 255; property UseGradient: Boolean read FUseGradient write SetUseGradient default False; end; implementation { TFill } procedure TFill.SetGradient(const aValue: TBCGradient); begin if FGradient = aValue then Exit; FGradient := aValue; TCustomControl(GetOwner).Invalidate; end; procedure TFill.SetOpacity(const aValue: Byte); begin if FOpacity = aValue then Exit; FOpacity := aValue; TCustomControl(GetOwner).Invalidate; end; procedure TFill.SetColor(const aValue: TColor); begin if FColor = aValue then Exit; FColor := aValue; TCustomControl(GetOwner).Invalidate; end; procedure TFill.SetColorActive(const aValue: TColor); begin if FColorActive = aValue then Exit; FColorActive := aValue; end; procedure TFill.SetUseGradient(const aValue: Boolean); begin if FUseGradient = aValue then Exit; FUseGradient := aValue; TCustomControl(GetOwner).Invalidate; end; constructor TFill.Create(AOwner: TComponent); begin inherited Create; FOwner := AOwner; FColor := clWhite; FColorActive := $00FFF2E7; FOpacity := 255; FUseGradient := False; FGradient := TBCGradient.Create(TCustomControl(GetOwner)); FGradient.Point2XPercent := 100; FGradient.StartColor := clWhite; FGradient.EndColor := clBlack; end; destructor TFill.Destroy; begin FreeAndNil(FGradient); inherited Destroy; end; procedure TFill.Assign(Source: TPersistent); begin if Source is TFill then with TFill(Source) do begin Self.FColor := Color; Self.FColorActive := ColorActive; Self.FOpacity := Opacity; Self.FUseGradient := UseGradient; Self.FGradient := Gradient; end else inherited Assign(Source); end; function TFill.GetOwner: TPersistent; begin Result := FOwner; end; end.
unit Grijjy.MongoDB.Protocol; {< Implements the MongoDB Wire Protocol. This unit is only used internally. } {$INCLUDE 'Grijjy.inc'} interface uses System.SyncObjs, System.SysUtils, System.Generics.Collections, {$IF Defined(MSWINDOWS)} Grijjy.SocketPool.Win, {$ELSEIF Defined(LINUX)} Grijjy.SocketPool.Linux, {$ELSE} {$MESSAGE Error 'The MongoDB driver is only supported on Windows and Linux'} {$ENDIF} Grijjy.Bson; type { Base class for MongoDB errors } EgoMongoDBError = class(Exception); { Is raised when a connection error (or timeout) occurs. } EgoMongoDBConnectionError = class(EgoMongoDBError); { Query flags as used by TgoMongoProtocol.OpQuery } TgoMongoQueryFlag = ( { Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object’s position. You can resume using the cursor later, from where it was located, if more data were received. Like any “latent cursor”, the cursor may become invalid at some point (CursorNotFound) – for example if the final object it references were deleted. } TailableCursor = 1, { Allow query of replica slave. Normally these return an error except for namespace “local”. } SlaveOk = 2, { Internal replication use only - driver should not set. } OplogRelay = 3, { The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. } NoCursorTimeout = 4, { Use with TailableCursor. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal. } AwaitData = 5, { Stream the data down full blast in multiple “more” packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection. } Exhaust = 6, { Get partial results from a mongos if some shards are down (instead of throwing an error) } Partial = 7); TgoMongoQueryFlags = set of TgoMongoQueryFlag; type { Possible reponse flags as returned in IgoMongoReply.ReponseFlags. } TgoMongoResponseFlag = ( { Is set when GetMore is called but the cursor id is not valid at the server. Returned with zero results. } CursorNotFound = 0, { Is set when query failed. Results consist of one document containing an “$err” field describing the failure. } QueryFailure = 1, { Drivers should ignore this. Only mongos will ever see this set, in which case, it needs to update config from the server. } ShardConfigStale = 2, { Is set when the server supports the AwaitData Query option. If it doesn’t, a client should sleep a little between getMore’s of a Tailable cursor. Mongod version 1.6 supports AwaitData and thus always sets AwaitCapable. } AwaitCapable = 3); TgoMongoResponseFlags = set of TgoMongoResponseFlag; type { A reply to a query (see TgoMongoProtocol.OpQuery) } IgoMongoReply = interface ['{25CEF8E1-B023-4232-BE9A-1FBE9E51CE57}'] {$REGION 'Internal Declarations'} function _GetResponseFlags: TgoMongoResponseFlags; function _GetCursorId: Int64; function _GetStartingFrom: Integer; function _GetResponseTo: Integer; function _GetDocuments: TArray<TBytes>; {$ENDREGION 'Internal Declarations'} { Various reponse flags } property ReponseFlags: TgoMongoResponseFlags read _GetResponseFlags; { The cursorID that this reply is a part of. In the event that the result set of the query fits into one reply message, cursorID will be 0. This cursorID must be used in any GetMore messages used to get more data. } property CursorId: Int64 read _GetCursorId; { Starting position in the cursor.} property StartingFrom: Integer read _GetStartingFrom; { The identifier of the message that this reply is response to. } property ResponseTo: Integer read _GetResponseTo; { Raw BSON documents in the reply. } property Documents: TArray<TBytes> read _GetDocuments; end; type { Mongo authentication mechanism } TgoMongoAuthMechanism = (None, SCRAM_SHA_1, SCRAM_SHA_256); { Customizable protocol settings. } TgoMongoProtocolSettings = record public { Timeout waiting for connection, in milliseconds. Defaults to 5000 (5 seconds) } ConnectionTimeout: Integer; { Timeout waiting for partial or complete reply events, in milliseconds. Defaults to 5000 (5 seconds) } ReplyTimeout: Integer; { Default query flags } QueryFlags: TgoMongoQueryFlags; { Tls enabled } Secure: Boolean; { X.509 Certificate in PEM format, if any } Certificate: TBytes; { X.509 Private key in PEM format, if any } PrivateKey: TBytes; { Password for private key, optional } PrivateKeyPassword: String; { Authentication mechanism } AuthMechanism: TgoMongoAuthMechanism; { Authentication database } AuthDatabase: String; { Authentication username } Username: String; { Authentication password } Password: String; end; type TgoMongoProtocol = class {$REGION 'Internal Declarations'} private const OP_QUERY = 2004; OP_GET_MORE = 2005; OP_KILL_CURSORS=2007; RECV_BUFFER_SIZE = 32768; EMPTY_DOCUMENT: array [0..4] of Byte = (5, 0, 0, 0, 0); private class var FClientSocketManager: TgoClientSocketManager; private FHost: String; FPort: Integer; FSettings: TgoMongoProtocolSettings; FNextRequestId: Integer; FConnection: TgoSocketConnection; FConnectionLock: TCriticalSection; FCompletedReplies: TDictionary<Integer, IgoMongoReply>; FPartialReplies: TDictionary<Integer, TDateTime>; FRepliesLock: TCriticalSection; FRecvBuffer: TBytes; FRecvSize: Integer; FRecvBufferLock: TCriticalSection; FAuthErrorMessage: String; FAuthErrorCode: Integer; private procedure Send(const AData: TBytes); function WaitForReply(const ARequestId: Integer; AForceWaitTimeout : Boolean = false): IgoMongoReply; function TryGetReply(const ARequestId: Integer; out AReply: IgoMongoReply): Boolean; inline; function LastPartialReply(const ARequestID: Integer; out ALastRecv: TDateTime): Boolean; function OpReplyValid(out AIndex: Integer): Boolean; function OpReplyMsgHeader(out AMsgHeader): Boolean; private { Authentication } function saslStart(const APayload: String): IgoMongoReply; function saslContinue(const AConversationId: Integer; const APayload: String): IgoMongoReply; function Authenticate: Boolean; { Connection } function Connect: Boolean; function IsConnected: Boolean; function ConnectionState: TgoConnectionState; inline; private { Socket events } procedure SocketConnected; procedure SocketDisconnected; procedure SocketRecv(const ABuffer: Pointer; const ASize: Integer); public class constructor Create; class destructor Destroy; {$ENDREGION 'Internal Declarations'} public { Creates the protocol. Parameters: AHost: host address of the MongoDB server to connect to. APort: connection port. ASettings: custom protocol settings. } constructor Create(const AHost: String; const APort: Integer; const ASettings: TgoMongoProtocolSettings); destructor Destroy; override; { Implements the OP_QUERY opcode, used to query the database for documents in a collection. Parameters: AFullCollectionName: the fully qualified name of the collection in the database to query (in <DatabaseName>.<CollectionName> form). AFlags: various query flags. ANumberToSkip: the number of documents to omit - starting from the first document in the resulting dataset - when returning the result of the query. ANumberToReturn: limits the number of documents in the first reply to the query. However, the database will still establish a cursor and return the cursorID to the client if there are more results than ANumberToReturn. If ANumberToReturn is 0, the db will use the default return size. If the number is negative, then the database will return that number and close the cursor. No further results for that query can be fetched. If ANumberToReturn is 1 the server will treat it as -1 (closing the cursor automatically). AQuery: raw BSON data with the document that represents the query. The query will contain one or more elements, all of which must match for a document to be included in the result set. Possible elements include $query, $orderby, $hint, $explain, and $snapshot. AReturnFieldsSelector: (optional) raw BSON data with a document that limits the fields in the returned documents. The AReturnFieldsSelector contains one or more elements, each of which is the name of a field that should be returned, and and the integer value 1. Returns: The reply to the query, or nil if the request timed out. } function OpQuery(const AFullCollectionName: UTF8String; const AFlags: TgoMongoQueryFlags; const ANumberToSkip, ANumberToReturn: Integer; const AQuery: TBytes; const AReturnFieldsSelector: TBytes = nil; const AForceWaitTimeout : Boolean = false): IgoMongoReply; { Implements the OP_GET_MORE opcode, used to get an additional page of documents from the database. Parameters: AFullCollectionName: the fully qualified name of the collection in the database to query (in <DatabaseName>.<CollectionName> form). ANumberToReturn: limits the number of documents in the first reply to the query. However, the database will still establish a cursor and return the cursorID to the client if there are more results than ANumberToReturn. If ANumberToReturn is 0, the db will use the default return size. ACursorId: cursor identifier as returned in the reply from a previous call to OpQuery or OpGetMore. Returns: The reply to the query, or nil if the request timed out. } function OpGetMore(const AFullCollectionName: UTF8String; const ANumberToReturn: Integer; const ACursorId: Int64): IgoMongoReply; { Implements the OP_KILL_CURSORS opcode, used to free open cursors on the server. (wire protocol 3.0) Use case: Called by the destructor of tgoMongoCursor.tEnumerator. If the enumeration loop was exited prematurely without enumerating all elements, that would sometimes result in a resource leak on the server (orphaned cursor). Parameters: ACursorIds An array with the cursor ID's to release. The values should not be 0. See also: https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-kill_cursors} Procedure OpKillCursors(const ACursorIds: Tarray<Int64>); public { Authenticate error message if failed } property AuthErrorMessage: String read FAuthErrorMessage; { Authenticate error code if failed } property AuthErrorCode: Integer read FAuthErrorCode; end; resourcestring RS_MONGODB_AUTHENTICATION_ERROR = 'Error authenticating [%d] %s'; implementation uses System.DateUtils, Grijjy.SysUtils, Grijjy.Bson.IO, Grijjy.Scram; type TMsgHeader = packed record MessageLength: Int32; RequestID: Int32; ResponseTo: Int32; OpCode: Int32; end; PMsgHeader = ^TMsgHeader; type TOpReplyHeader = packed record Header: TMsgHeader; ResponseFlags: Int32; CursorId: Int64; StartingFrom: Int32; NumberReturned: Int32; { Documents: Documents } end; POpReplyHeader = ^TOpReplyHeader; type { Implements IgoMongoReply } TgoMongoReply = class(TInterfacedObject, IgoMongoReply) private FHeader: TOpReplyHeader; FDocuments: TArray<TBytes>; protected { IgoMongoReply } function _GetResponseFlags: TgoMongoResponseFlags; function _GetCursorId: Int64; function _GetStartingFrom: Integer; function _GetResponseTo: Integer; function _GetDocuments: TArray<TBytes>; public constructor Create(const ABuffer: TBytes; const ASize: Integer); end; { TgoMongoProtocol } class constructor TgoMongoProtocol.Create; begin FClientSocketManager := TgoClientSocketManager.Create( TgoSocketOptimization.Scale, TgoSocketPoolBehavior.PoolAndReuse); end; class destructor TgoMongoProtocol.Destroy; begin FreeAndNil(FClientSocketManager); end; function TgoMongoProtocol.saslStart(const APayload: String): IgoMongoReply; var Writer: IgoBsonWriter; begin Writer := TgoBsonWriter.Create; Writer.WriteStartDocument; Writer.WriteInt32('saslStart', 1); if FSettings.AuthMechanism = TgoMongoAuthMechanism.SCRAM_SHA_1 then Writer.WriteString('mechanism', 'SCRAM-SHA-1') else Writer.WriteString('mechanism', 'SCRAM-SHA-256'); Writer.WriteName('payload'); Writer.WriteBinaryData(TgoBsonBinaryData.Create(TEncoding.Utf8.GetBytes(APayload))); Writer.WriteInt32('autoAuthorize', 1); Writer.WriteEndDocument; Result := OpQuery(Utf8String(FSettings.AuthDatabase + '.$cmd'), [], 0, -1, Writer.ToBson, nil); end; function TgoMongoProtocol.saslContinue(const AConversationId: Integer; const APayload: String): IgoMongoReply; var Writer: IgoBsonWriter; begin Writer := TgoBsonWriter.Create; Writer.WriteStartDocument; Writer.WriteInt32('saslContinue', 1); Writer.WriteInt32('conversationId', AConversationId); Writer.WriteName('payload'); Writer.WriteBinaryData(TgoBsonBinaryData.Create(TEncoding.Utf8.GetBytes(APayload))); Writer.WriteEndDocument; Result := OpQuery(Utf8String(FSettings.AuthDatabase + '.$cmd'), [], 0, -1, Writer.ToBson, nil); end; function TgoMongoProtocol.Authenticate: Boolean; var Scram: TgoScram; ServerFirstMsg, ServerSecondMsg: String; ConversationDoc: TgoBsonDocument; PayloadBinary: TgoBsonBinaryData; ConversationId: Integer; Ok: Boolean; MongoReply: IgoMongoReply; begin { Reset auth error code } FAuthErrorMessage := ''; FAuthErrorCode := 0; { Initialize our Scram helper } case FSettings.AuthMechanism of TgoMongoAuthMechanism.SCRAM_SHA_1: Scram := TgoScram.Create(TgoScramMechanism.SCRAM_SHA_1, FSettings.Username, FSettings.Password); else Scram := TgoScram.Create(TgoScramMechanism.SCRAM_SHA_256, FSettings.Username, FSettings.Password); end; try { Step 1 } Scram.CreateFirstMsg; { Start the initial sasl handshake } MongoReply := saslStart(SCRAM_GS2_HEADER + Scram.ClientFirstMsg); if MongoReply = nil then Exit(False); if MongoReply.Documents = nil then Exit(False); ConversationDoc := TgoBsonDocument.Load(MongoReply.Documents[0]); Ok := ConversationDoc['ok']; if not Ok then begin // { // "ok" : 0.0, // "errmsg" : "Authentication failed.", // "code" : 18, // "codeName" : "AuthenticationFailed" // } FAuthErrorMessage := ConversationDoc['errmsg']; FAuthErrorCode := ConversationDoc['code']; Exit(False); end; // { // "conversationId" : 1, // "done" : false, // "payload" : { "$binary" : "a=b,c=d", "$type" : "00" }, // "ok" : 1.0 // } { The first message from the server to the client } PayloadBinary := ConversationDoc['payload'].AsBsonBinaryData; ServerFirstMsg := TEncoding.Utf8.GetString(PayloadBinary.AsBytes); ConversationId := ConversationDoc['conversationId']; { Process the first message from the server to the client } Scram.HandleServerFirstMsg(ConversationId, ServerFirstMsg); { Step 2 - Send the final client message } MongoReply := saslContinue(Scram.ConversationId, Scram.ClientFinalMsg); if MongoReply = nil then Exit(False); if MongoReply.Documents = nil then Exit(False); ConversationDoc := TgoBsonDocument.Load(MongoReply.Documents[0]); Ok := ConversationDoc['ok']; if not Ok then begin FAuthErrorMessage := ConversationDoc['errmsg']; FAuthErrorCode := ConversationDoc['code']; Exit(False); end; { The second message from the server to the client } PayloadBinary := ConversationDoc['payload'].AsBsonBinaryData; ServerSecondMsg := TEncoding.Utf8.GetString(PayloadBinary.AsBytes); { Process the second message from the server to the client } Scram.HandleServerSecondMsg(ServerSecondMsg); { Verify that the actual signature matches the servers expected signature } if not Scram.ValidSignature then begin FAuthErrorMessage := 'Server signature does not match'; FAuthErrorCode := -1; Exit(False); end; { Step 3 - Acknowledge with an empty payload } MongoReply := saslContinue(Scram.ConversationId, ''); if MongoReply = nil then Exit(False); if MongoReply.Documents = nil then Exit(False); ConversationDoc := TgoBsonDocument.Load(MongoReply.Documents[0]); Ok := ConversationDoc['ok']; if not Ok then begin FAuthErrorMessage := ConversationDoc['errmsg']; FAuthErrorCode := ConversationDoc['code']; Exit(False); end; Result := (ConversationDoc['done'] = True); finally Scram.Free; end; end; function TgoMongoProtocol.Connect: Boolean; var Connection: TgoSocketConnection; procedure WaitForConnected; var Start: TDateTime; begin Start := Now; while (MillisecondsBetween(Now, Start) < FSettings.ConnectionTimeout) and (FConnection.State <> TgoConnectionState.Connected) do Sleep(5); end; begin FConnectionLock.Acquire; try Connection := FConnection; FConnection := FClientSocketManager.Request(FHost, FPort); if Assigned(FConnection) then begin FConnection.OnConnected := SocketConnected; FConnection.OnDisconnected := SocketDisconnected; FConnection.OnRecv := SocketRecv; end; finally FConnectionLock.Release; end; { Release the last connection } if (Connection <> nil) then FClientSocketManager.Release(Connection); { Shutting down } if not Assigned(FConnection) then Exit(False); Result := (ConnectionState = TgoConnectionState.Connected); if (not Result) then begin FConnectionLock.Acquire; try { Enable or disable Tls support } FConnection.SSL := FSettings.Secure; { Pass host name for Server Name Indication (SNI) for Tls } if FConnection.SSL then begin FConnection.OpenSSL.Host := FHost; FConnection.OpenSSL.Port := FPort; end; { Apply X.509 certificate } FConnection.Certificate := FSettings.Certificate; FConnection.PrivateKey := FSettings.PrivateKey; FConnection.Password := FSettings.PrivateKeyPassword; if FConnection.Connect then WaitForConnected; finally FConnectionLock.Release; end; if ConnectionState <> TgoConnectionState.Connected then Exit(False); Result := True; end; { Always check this, because credentials may have changed } if FSettings.AuthMechanism <> TgoMongoAuthMechanism.None then begin { SCRAM Authenticate } if not Authenticate then raise EgoMongoDBConnectionError.Create(Format(RS_MONGODB_AUTHENTICATION_ERROR, [FAuthErrorCode, FAuthErrorMessage])); end; end; function TgoMongoProtocol.ConnectionState: TgoConnectionState; begin FConnectionLock.Acquire; try if (FConnection <> nil) then Result := FConnection.State else Result := TgoConnectionState.Disconnected; finally FConnectionLock.Release; end; end; constructor TgoMongoProtocol.Create(const AHost: String; const APort: Integer; const ASettings: TgoMongoProtocolSettings); begin Assert(AHost <> ''); Assert(APort <> 0); inherited Create; FHost := AHost; FPort := APort; FSettings := ASettings; FConnectionLock := TCriticalSection.Create; FRepliesLock := TCriticalSection.Create; FRecvBufferLock := TCriticalSection.Create; FCompletedReplies := TDictionary<Integer, IgoMongoReply>.Create; FPartialReplies := TDictionary<Integer, TDateTime>.Create; SetLength(FRecvBuffer, RECV_BUFFER_SIZE); end; destructor TgoMongoProtocol.Destroy; var Connection: TgoSocketConnection; begin if (FConnectionLock <> nil) then begin FConnectionLock.Acquire; try Connection := FConnection; FConnection := nil; finally FConnectionLock.Release; end; end else begin Connection := FConnection; FConnection := nil; end; if (Connection <> nil) and (FClientSocketManager <> nil) then FClientSocketManager.Release(Connection); if (FRepliesLock <> nil) then begin FRepliesLock.Acquire; try FCompletedReplies.Free; FPartialReplies.Free; finally FRepliesLock.Release; end; end; FRepliesLock.Free; FConnectionLock.Free; FRecvBufferLock.Free; inherited; end; function TgoMongoProtocol.IsConnected: Boolean; begin Result := (ConnectionState = TgoConnectionState.Connected); if (not Result) then Result := Connect; end; function TgoMongoProtocol.LastPartialReply(const ARequestID: Integer; out ALastRecv: TDateTime): Boolean; begin FRepliesLock.Acquire; try Result := FPartialReplies.TryGetValue(ARequestID, ALastRecv); finally FRepliesLock.Release; end; end; function TgoMongoProtocol.OpGetMore(const AFullCollectionName: UTF8String; const ANumberToReturn: Integer; const ACursorId: Int64): IgoMongoReply; { https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-get-more } var Header: TMsgHeader; Data: TgoByteBuffer; I: Integer; begin Header.MessageLength := SizeOf(TMsgHeader) + 16 + Length(AFullCollectionName) + 1; Header.RequestID := AtomicIncrement(FNextRequestId); Header.ResponseTo := 0; Header.OpCode := OP_GET_MORE; Data := TgoByteBuffer.Create(Header.MessageLength); try Data.AppendBuffer(Header, SizeOf(TMsgHeader)); I := 0; Data.AppendBuffer(I, SizeOf(Int32)); // Reserved Data.AppendBuffer(AFullCollectionName[Low(UTF8String)], Length(AFullCollectionName) + 1); Data.AppendBuffer(ANumberToReturn, SizeOf(Int32)); Data.AppendBuffer(ACursorId, SizeOf(Int64)); Send(Data.ToBytes); finally Data.Free; end; Result := WaitForReply(Header.RequestID); end; Procedure TgoMongoProtocol.OpKillCursors(const ACursorIds: TArray<Int64>); {https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-kill_cursors} var Header: TMsgHeader; Data: TgoByteBuffer; I: Int32; begin if Length(ACursorIds) <> 0 then begin Header.MessageLength := SizeOf(TMsgHeader) + 2 * SizeOf(Int32) + Length(ACursorIds) * SizeOf(Int64); Header.RequestID := AtomicIncrement(FNextRequestId); Header.ResponseTo := 0; Header.OpCode := OP_KILL_CURSORS; Data := TgoByteBuffer.Create(Header.MessageLength); try Data.AppendBuffer(Header, SizeOf(TMsgHeader)); I := 0; Data.AppendBuffer(I, SizeOf(Int32)); // Reserved I := Length(ACursorIds); Data.AppendBuffer(I, SizeOf(Int32)); // Number of cursors to delete for I := 0 to high(ACursorIds) do Data.AppendBuffer(ACursorIds[I], SizeOf(Int64)); Send(Data.ToBytes); finally Data.Free; end; // The OP_KILL_CURSORS from wire protocol 3.0 does NOT return a result. end; end; function TgoMongoProtocol.OpQuery(const AFullCollectionName: UTF8String; const AFlags: TgoMongoQueryFlags; const ANumberToSkip, ANumberToReturn: Integer; const AQuery, AReturnFieldsSelector: TBytes; const AForceWaitTimeout : Boolean): IgoMongoReply; { https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-query } var Header: TMsgHeader; Data: TgoByteBuffer; I: Int32; begin Header.MessageLength := SizeOf(TMsgHeader) + 12 + Length(AFullCollectionName) + 1 + Length(AQuery) + Length(AReturnFieldsSelector); if (AQuery = nil) then Inc(Header.MessageLength, Length(EMPTY_DOCUMENT)); Header.RequestID := AtomicIncrement(FNextRequestId); Header.ResponseTo := 0; Header.OpCode := OP_QUERY; Data := TgoByteBuffer.Create(Header.MessageLength); try Data.AppendBuffer(Header, SizeOf(TMsgHeader)); I := Byte(AFlags) or Byte(FSettings.QueryFlags); Data.AppendBuffer(I, SizeOf(Int32)); Data.AppendBuffer(AFullCollectionName[Low(UTF8String)], Length(AFullCollectionName) + 1); Data.AppendBuffer(ANumberToSkip, SizeOf(Int32)); Data.AppendBuffer(ANumberToReturn, SizeOf(Int32)); if (AQuery <> nil) then Data.Append(AQuery) else Data.Append(EMPTY_DOCUMENT); if (AReturnFieldsSelector <> nil) then Data.Append(AReturnFieldsSelector); Send(Data.ToBytes); finally Data.Free; end; Result := WaitForReply(Header.RequestID, AForceWaitTimeout); end; function TgoMongoProtocol.OpReplyMsgHeader(out AMsgHeader): Boolean; begin Result := (FRecvSize >= SizeOf(TMsgHeader)); if (Result) then Move(FRecvBuffer[0], AMsgHeader, SizeOf(TMsgHeader)); end; function TgoMongoProtocol.OpReplyValid(out AIndex: Integer): Boolean; // https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply var Header: POpReplyHeader; Size: Int32; NumberReturned: Integer; begin AIndex := 0; if (FRecvSize >= SizeOf(TOpReplyHeader)) then { minimum size } begin Header := @FRecvBuffer[0]; if (Header.NumberReturned = 0) then begin AIndex := SizeOf(TOpReplyHeader); Result := True; { no documents, ok } end else begin { Make sure we have all the documents } NumberReturned := Header.NumberReturned; AIndex := SizeOf(TOpReplyHeader); repeat if (FRecvSize >= (AIndex + SizeOf(Int32))) then begin Move(FRecvBuffer[AIndex], Size, SizeOf(Int32)); if (FRecvSize >= (AIndex + Size)) then begin Dec(NumberReturned); AIndex := AIndex + Size; { next } end else Break; end else Break; until (NumberReturned = 0); Result := (NumberReturned = 0); { all documents, ok } end; end else Result := False; end; procedure TgoMongoProtocol.Send(const AData: TBytes); begin if IsConnected then begin FConnectionLock.Acquire; try if (FConnection <> nil) then FConnection.Send(AData); finally FConnectionLock.Release; end; end; end; procedure TgoMongoProtocol.SocketConnected; begin { Not interested (yet) } end; procedure TgoMongoProtocol.SocketDisconnected; begin { Not interested (yet) } end; procedure TgoMongoProtocol.SocketRecv(const ABuffer: Pointer; const ASize: Integer); var MongoReply: IgoMongoReply; Index: Integer; MsgHeader: TMsgHeader; begin FRecvBufferLock.Enter; try { Expand the buffer if we are at capacity } if (FRecvSize + ASize >= Length(FRecvBuffer)) then SetLength(FRecvBuffer, (FRecvSize + ASize) * 2); { Append the new buffer } Move(ABuffer^, FRecvBuffer[FRecvSize], ASize); FRecvSize := FRecvSize + ASize; { Is there one or more valid replies pending? } while True do begin if OpReplyValid(Index) then begin MongoReply := TgoMongoReply.Create(FRecvBuffer, FRecvSize); FRepliesLock.Acquire; try { Remove the partial reply timestamp } FPartialReplies.Remove(MongoReply.ResponseTo); { Add the completed reply to the dictionary } FCompletedReplies.Add(MongoReply.ResponseTo, MongoReply); finally FRepliesLock.Release; end; { Shift the receive buffer, if needed } if (Index = FRecvSize) then FRecvSize := 0 else Move(FRecvBuffer[Index], FRecvBuffer[0], FRecvSize - Index); end else begin { Update the partial reply timestamp } if OpReplyMsgHeader(MsgHeader) then begin FRepliesLock.Acquire; try FPartialReplies.AddOrSetValue(MsgHeader.ResponseTo, Now); finally FRepliesLock.Release; end; end; Break; end; end; finally FRecvBufferLock.Leave; end; end; function TgoMongoProtocol.TryGetReply(const ARequestId: Integer; out AReply: IgoMongoReply): Boolean; begin FRepliesLock.Acquire; try Result := FCompletedReplies.TryGetValue(ARequestId, AReply); finally FRepliesLock.Release; end; end; function TgoMongoProtocol.WaitForReply( const ARequestId: Integer; AForceWaitTimeout : Boolean = false): IgoMongoReply; var LastRecv: TDateTime; InitRecv: TDateTime; begin Result := nil; InitRecv := Now; while (ConnectionState = TgoConnectionState.Connected) and (not TryGetReply(ARequestID, Result)) do begin if LastPartialReply(ARequestID, LastRecv) and (MillisecondsBetween(Now, LastRecv) > FSettings.ReplyTimeout) then Break; // in case we didn't receive any response, stop if timout // is reached and AForceWaitTimeout=true is passed if ((Int(LastRecv) = 0) and (AForceWaitTimeout = true) and (MillisecondsBetween(Now, InitRecv) > FSettings.ReplyTimeout)) then Break; Sleep(5); end; if (Result = nil) then TryGetReply(ARequestId, Result); FRepliesLock.Acquire; try FPartialReplies.Remove(ARequestId); FCompletedReplies.Remove(ARequestId); finally FRepliesLock.Release; end; end; { TgoMongoReply } constructor TgoMongoReply.Create(const ABuffer: TBytes; const ASize: Integer); var I, Index, Count: Integer; Size: Int32; Document: TBytes; begin inherited Create; if (ASize >= SizeOf(TOpReplyHeader)) then begin FHeader := POpReplyHeader(@ABuffer[0])^; if (FHeader.NumberReturned > 0) then begin Index := SizeOf(TOpReplyHeader); Count := 0; SetLength(FDocuments, FHeader.NumberReturned); for I := 0 to FHeader.NumberReturned - 1 do begin Move(ABuffer[Index], Size, SizeOf(Int32)); if (ASize < (Index + Size)) then Break; SetLength(Document, Size); Move(ABuffer[Index], Document[0], Size); FDocuments[Count] := Document; Inc(Index, Size); Inc(Count); end; SetLength(FDocuments, Count); end; end else FHeader.CursorId := -1; end; function TgoMongoReply._GetCursorId: Int64; begin Result := FHeader.CursorId; end; function TgoMongoReply._GetDocuments: TArray<TBytes>; begin Result := FDocuments; end; function TgoMongoReply._GetResponseFlags: TgoMongoResponseFlags; begin Byte(Result) := FHeader.ResponseFlags; end; function TgoMongoReply._GetResponseTo: Integer; begin Result := FHeader.Header.ResponseTo; end; function TgoMongoReply._GetStartingFrom: Integer; begin Result := FHeader.StartingFrom; end; end.
{ // main form // A Lazarus Android ORM Demo // https://github.com/shenxh/LazAndroidOrmDemo // Shen Xue Hua , 1339838080@qq.com } unit umain; {$mode delphi} interface uses Classes, SysUtils, AndroidWidget, Laz_And_Controls, imagefilemanager; type { TfrmMain } TfrmMain = class(jForm) jDialogYN1: jDialogYN; jImageFileManager1: jImageFileManager; jImageHome: jImageView; jImageMine: jImageView; jImageView1: jImageView; jImageView2: jImageView; jListViewHome: jListView; jListViewMine: jListView; jPanel1: jPanel; jPanelMine: jPanel; jPanelHome: jPanel; jPanel2: jPanel; jPanelMainMenu: jPanel; jTextView1: jTextView; jTextView2: jTextView; procedure frmMainCloseQuery(Sender: TObject; var CanClose: boolean); procedure frmMainJNIPrompt(Sender: TObject); procedure jDialogYN1ClickYN(Sender: TObject; YN: TClickYN); procedure jImageHomeClick(Sender: TObject); procedure jImageMineClick(Sender: TObject); procedure jListViewHomeClickItem(Sender: TObject; itemIndex: integer; itemCaption: string); procedure jListViewMineClickItem(Sender: TObject; itemIndex: integer; itemCaption: string); private {private declarations} iClose:Boolean; public {public declarations} end; var frmMain: TfrmMain; implementation uses ucommon,uabout,umysettings,uinputinfo,upersonnel,uother,umyphoto; {$R *.lfm} { TfrmMain } procedure TfrmMain.frmMainJNIPrompt(Sender: TObject); begin //Init if Not(gInitOk) then begin jImageHome.ImageIdentifier:='home2'; jImageMine.ImageIdentifier:='mine1'; jPanelHome.Height:=Self.Height - jPanelMainMenu.Height; jPanelHome.Visible:=true; jPanelMine.Height:=Self.Height - jPanelMainMenu.Height; jPanelMine.Visible:=false; //Home - Menu List jListViewHome.Clear; jListViewHome.Add('Input Info','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('edit1.png')); jListViewHome.Add('Personnel','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('personnel1.png')); jListViewHome.Add('Other','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('otherlist1.png')); //Mine - Menu List jListViewMine.Clear; jListViewMine.Add('My Photo','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('picture1.png')); jListViewMine.Add('My Settings','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('setting1.png')); jListViewMine.Add('About APP','|',colbrDefault,18,wgNone,'',jImageFileManager1.LoadFromAssets('about1.png')); end; gInitOk:=true; end; procedure TfrmMain.frmMainCloseQuery(Sender: TObject; var CanClose: boolean); begin //Exit jDialogYN1.Show; if iClose then CanClose:=true else CanClose:=false; end; procedure TfrmMain.jDialogYN1ClickYN(Sender: TObject; YN: TClickYN); begin //Exit App ? case YN of ClickYes:begin iClose:=true; gApp.Finish; end; ClickNo:begin iClose:=false; exit; end; end; end; procedure TfrmMain.jImageHomeClick(Sender: TObject); begin //Home Click jImageHome.ImageIdentifier:='home2'; jImageMine.ImageIdentifier:='mine1'; jPanelMine.Visible:=false; jPanelHome.Visible:=true; end; procedure TfrmMain.jImageMineClick(Sender: TObject); begin //Mine Click jImageHome.ImageIdentifier:='home1'; jImageMine.ImageIdentifier:='mine2'; jPanelMine.Visible:=true; jPanelHome.Visible:=false; end; procedure TfrmMain.jListViewHomeClickItem(Sender: TObject; itemIndex: integer; itemCaption: string); begin //Click Home Menu //ShowMessage(itemCaption); case itemIndex of 0:begin //Input Info if frmInputInfo = nil then begin gApp.CreateForm(TfrmInputInfo, frmInputInfo); frmInputInfo.Init(gApp); end else begin frmInputInfo.Show; end; end; 1:begin //Personnel if frmPersonnel = nil then begin gApp.CreateForm(TfrmPersonnel, frmPersonnel); frmPersonnel.Init(gApp); end else begin frmPersonnel.Show; end; end; 2:begin //Other if frmOther = nil then begin gApp.CreateForm(TfrmOther, frmOther); frmOther.Init(gApp); end else begin frmOther.Show; end; end; end; end; procedure TfrmMain.jListViewMineClickItem(Sender: TObject; itemIndex: integer; itemCaption: string); begin //Click Mine Menu //ShowMessage(itemCaption); Case itemIndex of 0:begin //My Photo if frmMyPhoto = nil then begin gApp.CreateForm(TfrmMyPhoto, frmMyPhoto); frmMyPhoto.Init(gApp); end else begin frmMyPhoto.Show; end; end; 1:begin //My Settings if frmSettings = nil then begin gApp.CreateForm(TfrmSettings, frmSettings); frmSettings.Init(gApp); end else begin frmSettings.Show; end; end; 2:begin //About APP if frmAbout = nil then begin gApp.CreateForm(TfrmAbout, frmAbout); frmAbout.Init(gApp); end else begin frmAbout.Show; end; end; end; end; end.
unit dbebr.connection.fibplus; interface uses DB, Classes, FIBQuery, FIBDataSet, FIBDatabase, dbebr.connection.base, ormbr.factory.fibplus, ormbr.factory.interfaces; type {$IF CompilerVersion > 23} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)] {$IFEND} TDBEBrConnectionFIBPlus = class(TDBEBrConnectionBase) private FConnection: TFIBDatabase; public function GetDBConnection: IDBConnection; override; published constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Connetion: TFIBDatabase read FConnection write FConnection; end; implementation { TDBEBrConnectionFIBPlus } constructor TDBEBrConnectionFIBPlus.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TDBEBrConnectionFIBPlus.Destroy; begin inherited; end; function TDBEBrConnectionFIBPlus.GetDBConnection: IDBConnection; begin if not Assigned(FDBConnection) then FDBConnection := TFactoryFIBPlus.Create(FConnection, FDriverName); Result := FDBConnection; end; end.
{******************************************************************************* 作者: dmzn@163.com 2008-8-9 描述: 字典编辑器主单元 *******************************************************************************} unit UFormMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxCustomData, cxEdit, cxSplitter, Menus, cxLookAndFeels, ExtCtrls, ImgList, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridBandedTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, ComCtrls, cxPC, ToolWin, cxStyles, cxGraphics, cxFilter, cxData, cxDataStorage; type TfFormMain = class(TForm) ImageList1: TImageList; sBar: TStatusBar; ToolBar1: TToolBar; Btn_ConnDB: TToolButton; Btn_AddDetail: TToolButton; ToolButton1: TToolButton; Btn_AddEntity: TToolButton; Btn_DelDetail: TToolButton; ToolButton2: TToolButton; Btn_Exit: TToolButton; Timer1: TTimer; cxLook1: TcxLookAndFeelController; wPage: TcxPageControl; Sheet1: TcxTabSheet; ToolButton3: TToolButton; Btn_DelEntity: TToolButton; LeftPanel: TPanel; LTv1: TTreeView; Level1: TcxGridLevel; GridDict: TcxGrid; PMenu1: TPopupMenu; mRefresh: TMenuItem; mEdit: TMenuItem; TableView1: TcxGridBandedTableView; ableView1Column1: TcxGridBandedColumn; ableView1Column2: TcxGridBandedColumn; ableView1Column3: TcxGridBandedColumn; ableView1Column4: TcxGridBandedColumn; ableView1Column5: TcxGridBandedColumn; ableView1Column6: TcxGridBandedColumn; ableView1Column7: TcxGridBandedColumn; ableView1Column8: TcxGridBandedColumn; ableView1Column9: TcxGridBandedColumn; ableView1Column10: TcxGridBandedColumn; ableView1Column11: TcxGridBandedColumn; ableView1Column12: TcxGridBandedColumn; ableView1Column13: TcxGridBandedColumn; ableView1Column14: TcxGridBandedColumn; ableView1Column15: TcxGridBandedColumn; ableView1Column16: TcxGridBandedColumn; ableView1Column17: TcxGridBandedColumn; ableView1Column18: TcxGridBandedColumn; ableView1Column19: TcxGridBandedColumn; ableView1Column20: TcxGridBandedColumn; cxSplitter1: TcxSplitter; ableView1Column21: TcxGridBandedColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure Btn_ExitClick(Sender: TObject); procedure Btn_AddEntityClick(Sender: TObject); procedure Btn_ConnDBClick(Sender: TObject); procedure Btn_AddDetailClick(Sender: TObject); procedure Btn_DelDetailClick(Sender: TObject); procedure Btn_DelEntityClick(Sender: TObject); procedure mRefreshClick(Sender: TObject); procedure mEditClick(Sender: TObject); procedure LTv1DblClick(Sender: TObject); procedure TableView1DblClick(Sender: TObject); procedure ToolBar1DblClick(Sender: TObject); private { Private declarations } FActiveEntity: string; {*活动实体*} protected procedure FormLoadConfig; procedure FormSaveConfig; procedure LoadGridColumn(const nView: TcxGridTableView; const nWidth: string); function BuildGridColumn(const nView: TcxGridTableView): string; {*载入,保存配置*} procedure LockMainForm(const nLock: Boolean); {*锁定界面*} function GetProgNode(const nProgID: string): TTreeNode; {*实体节点*} procedure BuildEntityTree; {*实体列表*} procedure LoadEntityItemList(const nEntity: string); {*载入字典*} function ActiveEntity(var nProg,nEntity: string): Boolean; {*活动实体*} public { Public declarations } end; var fFormMain: TfFormMain; implementation {$R *.dfm} uses IniFiles, UMgrVar, UMgrThemeCX, UMgrDataDict, UcxChinese, ULibFun, USysConst, USysFun, USysDict, USysDataSet, UDataModule, UFormWait, UFormConn, UFormEntity, UFormDict; //------------------------------------------------------------------------------ //Desc: 载入窗体配置 procedure TfFormMain.FormLoadConfig; var nStr: string; nIni: TIniFile; begin Application.Title := gSysParam.FAppTitle; nStr := GetFileVersionStr(Application.ExeName); if nStr <> '' then begin nStr := Copy(nStr, 1, Pos('.', nStr) - 1); Caption := gSysParam.FMainTitle + ' V' + nStr; end else Caption := gSysParam.FMainTitle; gStatusBar := sBar; nStr := Format(sDate, [DateToStr(Now)]); StatusBarMsg(nStr, cSBar_Date); nStr := Format(sTime, [TimeToStr(Now)]); StatusBarMsg(nStr, cSBar_Time); nIni := TIniFile.Create(gPath + sFormConfig); try LoadFormConfig(Self, nIni); nStr := nIni.ReadString(Name, 'GridColumn', ''); if nStr <> '' then LoadGridColumn(TableView1, nStr); nStr := nIni.ReadString(Name, 'LeftPanel', ''); if IsNumber(nStr, False) and (StrToInt(nStr) > 100) then LeftPanel.Width := StrToInt(nStr); nStr := nIni.ReadString(sSetupSec, 'Theme', ''); if (nStr <> '') and gCxThemeManager.LoadTheme(nStr) then begin gCxThemeManager.ApplyTheme(Self); end; finally nIni.Free; end; end; //Desc: 保存窗体配置 procedure TfFormMain.FormSaveConfig; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveFormConfig(Self, nIni); nIni.WriteString(Name, 'GridColumn', BuildGridColumn(TableView1)); if cxSplitter1.State = ssClosed then cxSplitter1.State := ssOpened; nIni.WriteInteger(Name, 'LeftPanel', LeftPanel.Width); finally nIni.Free; end; end; procedure TfFormMain.FormCreate(Sender: TObject); begin InitSystemEnvironment; LoadSysParameter; InitGlobalVariant(gPath, gPath + sConfigFile, gPath + sFormConfig, gPath + sDBConfig); if not IsValidConfigFile(gPath + sConfigFile, gSysParam.FProgID) then begin ShowDlg(sInvalidConfig, sHint); Application.Terminate; end; FormLoadConfig; LockMainForm(True); TableView1.DataController.CustomDataSource := gSysDataSet; end; procedure TfFormMain.FormClose(Sender: TObject; var Action: TCloseAction); begin if QueryDlg(sCloseQuery, sAsk) then begin Action := caFree; FormSaveConfig; end else Action := caNone; end; //------------------------------------------------------------------------------ //Desc: 构建nView表头宽度字符串 function TfFormMain.BuildGridColumn(const nView: TcxGridTableView): string; var i,nCount: integer; begin Result := ''; nCount := nView.ColumnCount - 1; for i:=0 to nCount do begin Result := Result + IntToStr(nView.Columns[i].Width); if i < nCount then Result := Result + ';'; end; end; //Desc: 载入nView的宽度配置nWidth procedure TfFormMain.LoadGridColumn(const nView: TcxGridTableView; const nWidth: string); var nList: TStrings; i,nCount: integer; begin nList := TStringList.Create; try if not SplitStr(nWidth, nList, nView.ColumnCount) then Exit; nCount := nView.ColumnCount - 1; for i:=0 to nCount do if IsNumber(nList[i], False) then nView.Columns[i].Width := StrToInt(nList[i]); //xxxxx finally nList.Free; end; end; procedure TfFormMain.Timer1Timer(Sender: TObject); begin sBar.Panels[cSBar_Date].Text := Format(sDate, [DateToStr(Now)]); sBar.Panels[cSBar_Time].Text := Format(sTime, [TimeToStr(Now)]); end; //Desc: 锁定界面 procedure TfFormMain.LockMainForm(const nLock: Boolean); var i,nCount: integer; begin nCount := ToolBar1.ButtonCount - 1; for i:=0 to nCount do if (ToolBar1.Buttons[i] <> Btn_Exit) and (ToolBar1.Buttons[i] <> Btn_ConnDB) then ToolBar1.Buttons[i].Enabled := not nLock; LTv1.Enabled := not nLock; GridDict.Enabled := not nLock; end; //Desc: 搜索ProgID为nProgID的节点 function TfFormMain.GetProgNode(const nProgID: string): TTreeNode; var nList: TList; nInt: integer; i,nCount: integer; begin Result := nil; nCount := LTv1.Items.Count - 1; nList := gSysEntityManager.ProgList; for i:=0 to nCount do begin nInt := LTv1.Items[i].StateIndex; with PEntityItemData(nList[nInt])^ do if CompareText(nProgID, FProgID) = 0 then begin Result := LTv1.Items[i]; Break; end; end; end; //Desc: 构建实体列表 procedure TfFormMain.BuildEntityTree; var nStr: string; nList: TList; nNode: TTreeNode; i,nCount: integer; begin LTv1.Items.BeginUpdate; try LTv1.Items.Clear; if not gSysEntityManager.LoadProgList then Exit; nList := gSysEntityManager.ProgList; nCount := nList.Count - 1; for i:=0 to nCount do with PEntityItemData(nList[i])^ do begin nStr := '%s[ %s ]'; if FEntity = '' then begin nNode := nil; nStr := Format(nStr, [FTitle, FProgID]); end else begin nNode := GetProgNode(FProgID); nStr := Format(nStr, [FTitle, FEntity]); end; with LTv1.Items.AddChild(nNode, nStr) do begin StateIndex := i; if nNode = nil then ImageIndex := 7 else ImageIndex := 8; SelectedIndex := ImageIndex; end; end; finally if LTv1.Items.Count < 1 then begin LockMainForm(False); with LTv1.Items.AddChild(nil, '没有实体') do begin ImageIndex := 7; SelectedIndex := ImageIndex; end; end else begin LockMainForm(False); LTv1.FullExpand; end; LTv1.Items.EndUpdate; end; end; //Desc: 获取活动实体标识 function TfFormMain.ActiveEntity(var nProg,nEntity: string): Boolean; var nIdx: integer; begin nProg := ''; nEntity := ''; if Assigned(LTv1.Selected) then begin nIdx := LTv1.Selected.StateIndex; if (nIdx > -1) and (nIdx < gSysEntityManager.ProgList.Count) then with PEntityItemData(gSysEntityManager.ProgList[nIdx])^ do begin nProg := FProgID; nEntity := FEntity; end; end; Result := nProg <> ''; end; //Desc: 载入nEntity的所有字典项 procedure TfFormMain.LoadEntityItemList(const nEntity: string); begin if nEntity = FActiveEntity then Exit else FActiveEntity := nEntity; gSysEntityManager.LoadEntity(nEntity, True); gSysDataSet.DataChanged; end; //------------------------------------------------------------------------------ //Desc: 退出 procedure TfFormMain.Btn_ExitClick(Sender: TObject); begin Close; end; //Desc: 连接测试回调 function TestConn(const nConnStr: string): Boolean; begin FDM.ADOConn.Close; FDM.ADOConn.ConnectionString := nConnStr; FDM.ADOConn.Open; Result := FDM.ADOConn.Connected; end; //Desc: 连接数据库 procedure TfFormMain.Btn_ConnDBClick(Sender: TObject); var nStr: string; begin if ShowConnectDBSetupForm(TestConn) then nStr := BuildConnectDBStr else Exit; ShowWaitForm(Self, '连接数据库'); try try FDM.ADOConn.Connected := False; FDM.ADOConn.ConnectionString := nStr; FDM.ADOConn.Connected := True; if not gSysEntityManager.CreateTable then raise Exception.Create(''); BuildEntityTree; except ShowDlg('连接数据库失败,配置错误或远程无响应', sWarn, Handle); Exit; end; finally CloseWaitForm; end; end; //Decc: 添加实体 procedure TfFormMain.Btn_AddEntityClick(Sender: TObject); begin if ShowAddEntityForm then BuildEntityTree; end; //Desc: 编辑实体 procedure TfFormMain.mEditClick(Sender: TObject); var nInt: integer; nProg,nEntity: string; begin if LTv1.Focused then begin if ActiveEntity(nProg, nEntity) and ShowEditEntityForm(nProg, nEntity) then BuildEntityTree; end else if TableView1.Site.Focused then with gSysDataSet do begin nInt := DataController.FocusedRecordIndex; if nInt < 0 then Exit; nProg := DataController.Values[nInt, 0]; if IsNumber(nProg, False) then ShowEditDictItemForm(FActiveEntity, StrToInt(nProg)); //xxxxx end; end; //Desc: 删除实体 procedure TfFormMain.Btn_DelEntityClick(Sender: TObject); var nProg,nEntity: string; begin if ActiveEntity(nProg, nEntity) and QueryDlg('确定要删除选中的实体吗?', sAsk, Handle) and ((nEntity = '') or gSysEntityManager.DelDictEntityItem(nEntity)) then begin if (FActiveEntity <> '') and (nEntity = FActiveEntity) then begin FActiveEntity := ''; gSysDataSet.DataChanged; ShowMsgOnLastPanelOfStatusBar(''); end; if gSysEntityManager.DelEntityFromDB(nProg, nEntity) then BuildEntityTree; end; end; //Desc: 刷新实体列表 procedure TfFormMain.mRefreshClick(Sender: TObject); begin if GridDict.Focused then gSysDataSet.DataChanged else if LTv1.Focused then BuildEntityTree; end; //Desc: 增加明细 procedure TfFormMain.Btn_AddDetailClick(Sender: TObject); begin if FActiveEntity <> '' then begin ShowAddDictItemForm(FActiveEntity); end; end; //Desc: 删除明细 procedure TfFormMain.Btn_DelDetailClick(Sender: TObject); var nInt: integer; nItemID: integer; begin with gSysDataSet do begin nInt := DataController.GetSelectedCount; if nInt > 0 then begin nInt := DataController.FocusedRecordIndex; if nInt < 0 then Exit; nItemID := DataController.Values[nInt, 0]; if gSysEntityManager.DelDictItemFromDB(FActiveEntity, nItemID) then gSysDataSet.DataChanged; end; end; end; //Desc: 切换实体 procedure TfFormMain.LTv1DblClick(Sender: TObject); var nProg,nEntity: string; begin if ActiveEntity(nProg, nEntity) and (nEntity <> '') then begin gSysParam.FProgID := nProg; gSysEntityManager.ProgID := nProg; LoadEntityItemList(nEntity); UpdateDictItemFormEntity(nEntity); nProg := '当前数据: ' + LTv1.Selected.Text; ShowMsgOnLastPanelOfStatusBar(nProg); end; end; //Desc: 带入参数到编辑窗口 procedure TfFormMain.TableView1DblClick(Sender: TObject); var nInt: integer; nItemID: integer; begin with gSysDataSet do begin nInt := DataController.GetSelectedCount; if nInt > 0 then begin nInt := DataController.FocusedRecordIndex; if nInt < 0 then Exit; nItemID := DataController.Values[nInt, 0]; SetDictItemFormData(nItemID); end; end; end; //Desc: 控制实体列表显隐 procedure TfFormMain.ToolBar1DblClick(Sender: TObject); begin if cxSplitter1.State = ssClosed then cxSplitter1.State := ssOpened else cxSplitter1.State := ssClosed; end; end.
// ---------------------------------------------------------------------------- // Unit : PxNetwork.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2004-12-03 // Version : 1.0 // Description : Network routines that cannot be qualified elswhere. // Changes log : 2004-12-03 - initial version // 2004-12-22 - moved from PxUtils to PxNetUtils // 2005-03-05 - function GetLastErrorStr moved to PxUtils // 2005-03-15 - added KnockPorts (port knocking client // implementation). // 2005-05-04 - added basic classes to support server-side // of simple TCP connections. // - changed name to PxNetwork.pas // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxNetwork; {$I PxDefines.inc} interface uses Windows, Winsock, SysUtils, Classes, PxBase, PxLog, PxThread, PxGetText, PxResources; type TPxTCPServer = class; // // Basic TCP client connection on the server side // TPxTCPServerClient = class (TPxThread) private FServer: TPxTCPServer; FSocket: TSocket; FAddr : TSockAddrIn; function GetIP: String; function GetPort: Word; procedure Close; protected // reserved - don't use procedure Execute; override; // override this method to implement application-specific // processing of network traffic. procedure Main; virtual; // hidden properties (publish only if neccecery) property Server: TPxTCPServer read FServer; property Socket: TSocket read FSocket; public constructor Create(AServer: TPxTCPServer; ASocket: TSocket; AAddr: TSockAddrIn); virtual; destructor Destroy; override; // this objects dispose itself automatically, but if you really must // do it by yourself do it using Terminate - not Destroy! procedure Terminate; property IP: String read GetIP; property Port: Word read GetPort; end; TPxTCPServerClientClass = class of TPxTCPServerClient; // // Mutex-synchronized list of TCP client connections. For internal use only! // TPxTCPServerClientList = class (TList) private FMutex: THandle; function GetItem(Index: Integer): TPxTCPServerClient; public constructor Create; destructor Destroy; override; function Add(Item: TPxTCPServerClient): Integer; function Remove(Item: TPxTCPServerClient): Integer; procedure Delete(Index: Integer); property Items[Index: Integer]: TPxTCPServerClient read GetItem; default; end; TPxTCPServerClientNotify = procedure (Sender: TPxTCPServerClient) of object; // // Basic (but fully implemented) TCP server with some synchronized events // Synchronized events require CheckSynchronize in the main thread context, // which is done automatically for VCL GUI applications, but console applications // must call it explicite. For further informations see VCL manual. // TPxTCPServer = class (TPxThread) private FClientClass: TPxTCPServerClientClass; FClients: TPxTCPServerClientList; FSocket: TSocket; FClient: TPxTCPServerClient; FSynchronize: Boolean; FOnClientConnected: TPxTCPServerClientNotify; FOnClientDisconnected: TPxTCPServerClientNotify; procedure DoClientConnected(Client: TPxTCPServerClient); procedure InternalDoClientConnected; procedure DoClientDisconnected(Client: TPxTCPServerClient); procedure InternalDoClientDisconnected; protected function CreateSocket(Port: Word): TSocket; virtual; procedure Execute; override; public constructor Create(APort: Word; AClientClass: TPxTCPServerClientClass; ASynchronize: Boolean = True); destructor Destroy; override; // Never call Destroy on this object - call Terminate procedure Terminate; property Clients: TPxTCPServerClientList read FClients; property Socket: TSocket read FSocket; property OnClientConnected: TPxTCPServerClientNotify read FOnClientConnected write FOnClientConnected; property OnClientDisconnected: TPxTCPServerClientNotify read FOnClientDisconnected write FOnClientDisconnected; end; EPxTCPServerClientListException = class (Exception); EPxTCPServerException = class (Exception); // Creates a TCP socket and connect it to the specified host:port // Returns INVALID_SOCKET if no socket is avaible or if connection // could not have been established function Connect(IP: String; Port: Word; SendTimeout: Integer = -1; RecvTimeout: Integer = -1; KeepAlive: Boolean = True): TSocket; // Creates a TCP socket that is ready for receiving connections // Returns INVALID_SOCKET if no socket is avaible or if another application // is already listening on this socket function CreateServer(Port: Word): TSocket; // Client implementation of port knocking. This one works only with TCP locks. // See http://www.zeroflux.org/knock for more details and knockd for Linux. function KnockPorts(IP: String; Ports: array of Word): Boolean; implementation { TPxTCPServerClient } { Private declarations } function TPxTCPServerClient.GetIP: String; begin Result := inet_ntoa(FAddr.sin_addr); end; function TPxTCPServerClient.GetPort: Word; begin Result := ntohs(FAddr.sin_port); end; procedure TPxTCPServerClient.Close; begin if FSocket <> INVALID_SOCKET then begin closesocket(FSocket); FSocket := INVALID_SOCKET; end; end; { Protected declarations } procedure TPxTCPServerClient.Execute; begin Log('%s client connected', [ClassName]); if Assigned(FServer) then FServer.DoClientConnected(Self); Main; if Assigned(FServer) then FServer.DoClientDisconnected(Self); Log('%s client disconnected', [ClassName]); end; procedure TPxTCPServerClient.Main; begin end; { Public declarations } constructor TPxTCPServerClient.Create(AServer: TPxTCPServer; ASocket: TSocket; AAddr: TSockAddrIn); begin inherited Create(True); FreeOnTerminate := True; FServer := AServer; FSocket := ASocket; FAddr := AAddr; if Assigned(FServer) then // mutex-synchronized list cares about racing conditions FServer.Clients.Add(Self); Resume; end; destructor TPxTCPServerClient.Destroy; begin Close; if Assigned(FServer) then // mutex-synchronized list cares about racing conditions FServer.Clients.Remove(Self); inherited Destroy; end; procedure TPxTCPServerClient.Terminate; begin inherited Terminate; Close; end; { TPxTCPServerClientList } { Private declarations } function TPxTCPServerClientList.GetItem(Index: Integer): TPxTCPServerClient; begin Result := TObject(Get(Index)) as TPxTCPServerClient; end; { Public declarations } constructor TPxTCPServerClientList.Create; begin inherited Create; FMutex := CreateMutex(nil, False, ''); end; destructor TPxTCPServerClientList.Destroy; begin CloseHandle(FMutex); inherited Destroy; end; function TPxTCPServerClientList.Add(Item: TPxTCPServerClient): Integer; begin if WaitForSingleObject(FMutex, 1000) <> WAIT_OBJECT_0 then raise EPxTCPServerClientListException.Create('Error while aquiring mutex'); try Result := inherited Add(Item); finally ReleaseMutex(FMutex); end; end; function TPxTCPServerClientList.Remove(Item: TPxTCPServerClient): Integer; begin if WaitForSingleObject(FMutex, 1000) <> WAIT_OBJECT_0 then raise EPxTCPServerClientListException.Create('Error while aquiring mutex'); try Result := IndexOf(Item); if Result >= 0 then Delete(Result); finally ReleaseMutex(FMutex); end; end; procedure TPxTCPServerClientList.Delete(Index: Integer); begin if WaitForSingleObject(FMutex, 1000) <> WAIT_OBJECT_0 then raise EPxTCPServerClientListException.Create('Error while aquiring mutex'); try inherited Delete(Index); finally ReleaseMutex(FMutex); end; end; { TPxTCPServer } { Private declarations } procedure TPxTCPServer.DoClientConnected(Client: TPxTCPServerClient); begin if Assigned(FOnClientConnected) then begin FClient := Client; if FSynchronize then Synchronize(InternalDoClientConnected) else InternalDoClientConnected; end; end; procedure TPxTCPServer.InternalDoClientConnected; begin FOnClientConnected(FClient); end; procedure TPxTCPServer.DoClientDisconnected(Client: TPxTCPServerClient); begin if Assigned(FOnClientDisconnected) then begin FClient := Client; if FSynchronize then Synchronize(InternalDoClientDisconnected) else InternalDoClientDisconnected; end; end; procedure TPxTCPServer.InternalDoClientDisconnected; begin FOnClientDisconnected(FClient); end; { Protected declarations } function TPxTCPServer.CreateSocket(Port: Word): TSocket; var Addr: TSockAddrIn; begin Result := Winsock.socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if Result = INVALID_SOCKET then raise EPxTCPServerException.Create(GetText(SErrorWhileCreatingServerSocket)); FillChar(Addr, SizeOf(Addr), 0); Addr.sin_family := AF_INET; Addr.sin_port := htons(Port); Addr.sin_addr.S_addr := INADDR_ANY; if bind(Result, Addr, SizeOf(Addr)) <> 0 then begin closesocket(Result); raise EPxTCPServerException.Create(GetText(SErrorWhileBindingServerSocket)); end; if listen(Result, 5) <> 0 then begin closesocket(Result); raise EPxTCPServerException.Create(GetText(SErrorWhileListeningOnServerSocket)); end; end; procedure TPxTCPServer.Execute; var CS: TSocket; CA: TSockAddrIn; CL: Integer; begin repeat FillChar(CA, SizeOf(CA), 0); CL := SizeOf(CA); CS := accept(FSocket, @CA, @CL); if CS <> INVALID_SOCKET then FClientClass.Create(Self, CS, CA); until Terminated; end; { Public declarations } constructor TPxTCPServer.Create(APort: Word; AClientClass: TPxTCPServerClientClass; ASynchronize: Boolean = True); begin inherited Create(True); FreeOnTerminate := True; FSocket := CreateSocket(APort); FClientClass := AClientClass; FClients := TPxTCPServerClientList.Create; FSynchronize := ASynchronize; Resume; end; destructor TPxTCPServer.Destroy; var OldCount: Integer; begin closesocket(FSocket); FSocket := INVALID_SOCKET; while Clients.Count > 0 do begin OldCount := Clients.Count; Clients[Clients.Count - 1].Terminate; while Clients.Count = OldCount do Sleep(10); end; FClients.Free; inherited Destroy; end; procedure TPxTCPServer.Terminate; begin inherited Terminate; closesocket(FSocket); FSocket := INVALID_SOCKET; end; { *** } function Connect(IP: String; Port: Word; SendTimeout: Integer = -1; RecvTimeout: Integer = -1; KeepAlive: Boolean = True): TSocket; var Addr: TSockAddrIn; begin Result := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if Result <> TSocket(INVALID_SOCKET) then begin Addr.sin_family := AF_INET; Addr.sin_port := ntohs(Port); Addr.sin_addr.S_addr := inet_addr(PChar(IP)); if Winsock.connect(Result, Addr, SizeOf(Addr)) <> 0 then begin closesocket(Result); Result := TSocket(INVALID_SOCKET); end else begin if SendTimeout <> -1 then if setsockopt(Result, SOL_SOCKET, SO_SNDTIMEO, @SendTimeout, SizeOf(SendTimeout)) <> S_OK then Beep; if RecvTimeout <> -1 then if setsockopt(Result, SOL_SOCKET, SO_RCVTIMEO, @RecvTimeout, SizeOf(RecvTimeout)) <> S_OK then Beep; // enable/disable sending of keep-alive packets if setsockopt(Result, SOL_SOCKET, SO_KEEPALIVE, @KeepAlive, SizeOf(KeepAlive)) <> S_OK then Beep; end; end; end; function CreateServer(Port: Word): TSocket; var Addr: TSockAddrIn; begin Result := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if Result <> TSocket(INVALID_SOCKET) then begin Addr.sin_family := AF_INET; Addr.sin_port := htons(Port); Addr.sin_addr.S_addr := INADDR_ANY; if bind(Result, Addr, SizeOf(Addr)) <> 0 then begin Result := TSocket(INVALID_SOCKET); Exit; end; if listen(Result, 5) <> 0 then begin Result := TSocket(INVALID_SOCKET); Exit; end; end; end; function KnockPorts(IP: String; Ports: array of Word): Boolean; var A: TSockAddrIn; S: TSocket; b: Integer ; I: Integer; begin Result := True; for I := 0 to Length(Ports) - 1 do begin S := socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if S = TSocket(INVALID_SOCKET) then begin Result := False; Exit; end; B := 1; {$IFDEF DELPHI} if ioctlsocket(s, FIONBIO, b) <> 0 then {$ENDIF} {$IFDEF FPC} if ioctlsocket(s, Longint(FIONBIO), b) <> 0 then {$ENDIF} begin Result := False; Exit; end; A.sin_family := AF_INET; A.sin_port := htons(Ports[I]); A.sin_addr.S_addr := inet_addr(PChar(IP)); Winsock.connect(S, A, SizeOf(A)); closesocket(S); end; end; { *** } procedure Initialize; var WSAData: TWSAData; begin WSAStartup($101, WSAData); end; procedure Finalize; begin WSACleanup; end; initialization Initialize; finalization Finalize; end.
unit byte_Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TmainForm = class(TForm) Label4ask: TLabel; byteTXTvalue: TEdit; byteBits: TLabel; LabelBitsInfo: TLabel; LabelNOB: TLabel; LabelInfo: TLabel; ButtonCloseForm: TButton; procedure byteTXTvalueChange(Sender: TObject); procedure errorMessage; procedure byte2bit(inputValue:byte); procedure ShowResult; procedure ButtonCloseFormClick(Sender: TObject); private { Private declarations } public { Public declarations } byteValue, numberOfBits:byte; bitArray:array[0..7] of byte; end; var mainForm: TmainForm; implementation {$R *.dfm} {Процедура отоброжения результата вычислений} procedure TmainForm.ShowResult; var n0:byte; begin {Очищаем метку с битовым представлением числа} bytebits.Caption:=''; {В цикле считываем результат битового представления числа и присваиваем метке} for n0:=0 to 7 do bytebits.Caption:=bytebits.Caption+IntToStr(bitArray[n0]); {Присваиваем метке значение КОЛИЧЕСТВО БИТ} LabelNOB.Caption:=IntToStr(numberOfBits); end; {Процедура превода байта в битовое представление и подсчет битов входной параметр - значение байта 0-255} procedure TmainForm.byte2bit(inputValue:byte); {Определяем маску для перевода байта в битовое представление, такой подход исключает необходимость множественности условий и позволят произвести преобразование байта в биты (двоичную систему) за один проход в цикле} const maskBitArray:array[0..7] of byte = (1,2,4,8,16,32,64,128); var n0, nn:byte; begin nn:=0; numberOfBits:=0; for n0:=0 to 7 do begin if (inputValue-nn) div maskBitArray[7-n0] >= 1 then begin bitArray[7-n0]:=1; nn:=nn+maskBitArray[7-n0]; inc(numberOfBits); {Инкримент переменной подсчета количества битов} end else bitArray[7-n0]:=0; end; end; {Процедура вывода сообщения об ошибке. Выведена в отдельную процедуру так как вызывается не однократно в процессе проверки} procedure TmainForm.errorMessage(); begin ShowMessage('Значение должно быть числовым и не превышать 255!'); byteTXTvalue.Text:=IntToStr(byteValue); end; {Процедура отслеживает на событии ввода данных (изменении) и производит расчет} procedure TmainForm.byteTXTvalueChange(Sender: TObject); var tempValue:integer; begin if Length(byteTXTvalue.Text)>0 then {если текстовое поле не пустое} try {пытаемся преоброзовать текст в число исключая ошибку ввода} tempValue:=StrToInt(byteTXTvalue.Text); if tempValue>255 then errorMessage else {проверяем значение введенного числа на превышение допустимого} begin byteValue:=tempValue; {если все в порядке, производим расчет и выводим результат} byte2bit(byteValue); ShowResult; end; except {иначе сообщение об ошибке} errorMessage; end else begin {если поле ввода очищено - устанавливаем 0 значения} bytebits.Caption:='00000000'; LabelNOB.Caption:='0'; end; end; procedure TmainForm.ButtonCloseFormClick(Sender: TObject); begin Close; {закрываем форму} end; {При вводе значения числа можно было реализовать алгоритм исключения ошибок ввода, т.е. исключить возможность ввода символов отличных от числовых и в случае превышения вводимого числа устанавливать в значение 255, но это бы "утяжелило" код.} end.
unit TextEditor.Minimap.Colors; interface uses System.Classes, Vcl.Graphics, TextEditor.Consts; type TTextEditorMinimapColors = class(TPersistent) strict private FBackground: TColor; FBookmark: TColor; FVisibleLines: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write FBackground default clNone; property Bookmark: TColor read FBookmark write FBookmark default clMinimapBookmark; property VisibleLines: TColor read FVisibleLines write FVisibleLines default clMinimapVisibleLines; end; implementation constructor TTextEditorMinimapColors.Create; begin inherited; FBackground := clNone; FBookmark := clMinimapBookmark; FVisibleLines := clMinimapVisibleLines; end; procedure TTextEditorMinimapColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorMinimapColors) then with ASource as TTextEditorMinimapColors do begin Self.FBackground := FBackground; Self.FBookmark := FBookmark; Self.FVisibleLines := FVisibleLines; end else inherited Assign(ASource); end; end.
unit Singletn; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; {TMemo} type TMemoSingleton = class(TMemo) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TCSingleton = class(TComponent) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TOSingleton = class(TObject) public constructor Create; destructor Destroy; override; end; var Global_CSingleton: TCSingleton; Global_MemoSingleton: TMemoSingleton; Global_OSingleton: TOSingleton; procedure Register; implementation uses Windows; procedure Register; begin RegisterComponents('Design Patterns', [TCSingleton]); end; { TCSingleton } constructor TCSingleton.Create(AOwner: TComponent); begin if Global_CSingleton <> nil then {NB could show a message or raise a different exception here} Abort else begin inherited Create(AOwner); Global_CSingleton := Self; end; end; destructor TCSingleton.Destroy; begin if Global_CSingleton = Self then Global_CSingleton := nil; inherited Destroy; end; { TOSingleton } constructor TOSingleton.Create; begin if Global_OSingleton <> nil then {NB could show a message or raise a different exception here} Abort else Global_OSingleton := Self; end; destructor TOSingleton.Destroy; begin if Global_OSingleton = Self then Global_OSingleton := nil; inherited Destroy; end; procedure FreeGlobalObjects; far; begin if Global_CSingleton <> nil then Global_CSingleton.Free; if Global_OSingleton <> nil then Global_OSingleton.Free; end; { TMemoSingleton } constructor TMemoSingleton.Create(AOwner: TComponent); begin if Global_MemoSingleton <> nil then begin {NB could show a message or raise a different exception here} Raise Exception.Create('OOPs só pode ter um!!!'); end else begin inherited Create(AOwner); Global_MemoSingleton := Self; end; end; destructor TMemoSingleton.Destroy; begin if Global_MemoSingleton = Self then Global_MemoSingleton := nil; inherited Destroy; end; begin AddExitProc(FreeGlobalObjects); end.
unit GerarClasseController; interface uses Classes, FireDAC.Comp.Client, FireDAC.Stan.Intf, Data.DB, FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Stan.Async, //CursorWait FireDAC.UI.Intf, FireDAC.FMXUI.Wait, FireDAC.Comp.UI, //Firebird FireDAC.Phys.FBDef, FireDAC.Phys, FireDAC.Phys.IBBase, FireDAC.Phys.FB ; type TTipoGetSet = (tgsGetCabecalho, tgsSetCabecalho, tgsGetImplementation, tgsSetImplementation); TGerarClasse = class private FConexao: TFDConnection; FQuery: TFDQuery; FTabela: String; FPrefixo: string; FSufixo: string; FGerarGetSet: boolean; FGerarGettersAndSetters: boolean; FConteudoClasse: TStringList; FHeranca: string; FUsesInterface: string; FUsesImplementation: string; procedure CriarConexao(psArquivoConfiguracaoConexao: string); procedure CriarQuery; procedure AbrirQuery; function PegarTipoCampo(pfCampo: TField): string; function FormatarLinhaCampoPrivate(pfCampo: TField): string; function FormatarLinhaCampoPropriedade(pfCampo: TField): string; function FormatarCampoTipo(pfCampo: TField): string; function GetCaminhoArquivoFormatado(psCaminhoArquivo: string): string; procedure IncluirCamposEstrutura(psCamposPrivate, psCamposPropriedades: string); function FormatarPrimeiraLetraMaiuscula(psTexto: string): string; procedure IncluirGetSetEstrutura(psGettersCab, psSettersCab, psGettersImp, psSettersImp: string); function FormatarGetSetCab(ptgsTipo: TTipoGetSet; pfCampo: TField): string; function FormatarGetSetImp(ptgsTipo: TTipoGetSet; pfCampo: TField): string; public constructor Create(psArquivoConfiguracaoConexao: string); destructor Destroy; override; function GerarClasse(psTabela: string): boolean; function PegarConteudoArquivoGerado: string; procedure SalvarArquivo(psCaminhoArquivo: string = ''); property Prefixo: string read FPrefixo write FPrefixo; property Sufixo: string read FSufixo write FSufixo; property GerarGettersAndSetters: boolean read FGerarGettersAndSetters write FGerarGettersAndSetters; property GerarGetSet: boolean read FGerarGetSet write FGerarGetSet; property Heranca: string read FHeranca write FHeranca; property UsesInterface: string read FUsesInterface write FUsesInterface; property UsesImplementation: string read FUsesImplementation write FUsesImplementation; end; implementation uses SysUtils, Constantes, StrUtils; { TGerarClasse } {$REGION 'Construtores'} constructor TGerarClasse.Create(psArquivoConfiguracaoConexao: string); begin CriarConexao(psArquivoConfiguracaoConexao); FConteudoClasse := TStringList.Create; end; destructor TGerarClasse.Destroy; begin if Assigned(FQuery) then begin FreeAndNil(FQuery); FreeAndNil(FConexao); end; FreeAndNil(FConteudoClasse); inherited; end; {$ENDREGION} {$REGION 'Conexão com o banco'} procedure TGerarClasse.CriarConexao(psArquivoConfiguracaoConexao: string); begin FConexao := TFDConnection.Create(nil); FConexao.Params.LoadFromFile(psArquivoConfiguracaoConexao); FConexao.Open; end; procedure TGerarClasse.CriarQuery; begin if not Assigned(FQuery) then begin FQuery := TFDQuery.Create(nil); FQuery.Connection := FConexao; end; end; procedure TGerarClasse.AbrirQuery; begin CriarQuery; if FQuery.Active then FQuery.Close; FQuery.Open(Format(cSQL_METADADOS, [FTabela])); end; {$ENDREGION} {$REGION 'Construção da estrutura'} function TGerarClasse.PegarTipoCampo(pfCampo: TField): string; begin case pfCampo.DataType of ftString, ftMemo, ftWord: Result := 'string'; ftWideString, ftWideMemo: Result := 'WideString'; ftExtended: Result := 'Extended'; ftFloat: Result := 'Double'; ftCurrency: Result := 'Currency'; ftSmallInt: Result := 'SmallInt'; ftInteger, ftAutoInc, ftSingle: Result := 'Integer'; ftTimeStamp: Result := 'TDateTime'; ftLargeint: Result := 'Int64'; ftShortInt: Result := 'ShortInt'; ftBoolean: Result := 'Boolean'; end; end; function TGerarClasse.FormatarCampoTipo(pfCampo: TField): string; begin Result := FormatarPrimeiraLetraMaiuscula(pfCampo.FieldName) + ': ' + PegarTipoCampo(pfCampo); end; function TGerarClasse.FormatarLinhaCampoPrivate(pfCampo: TField): string; begin Result := cTABULACAO_6 + 'F' + FormatarCampoTipo(pfCampo) + ';'; end; function TGerarClasse.FormatarLinhaCampoPropriedade(pfCampo: TField): string; var sGet, sSet: string; begin sGet := IfThen(FGerarGettersAndSetters, 'Get', 'F'); sSet := IfThen(FGerarGettersAndSetters, 'Set', 'F'); Result := cTABULACAO_6 + 'property ' + FormatarCampoTipo(pfCampo) + ' read ' + sGet + FormatarPrimeiraLetraMaiuscula(pfCampo.FieldName) + ' write ' + sSet + FormatarPrimeiraLetraMaiuscula(pfCampo.FieldName) +';'; end; function TGerarClasse.FormatarGetSetCab(ptgsTipo: TTipoGetSet; pfCampo: TField): string; var sTipoEsqueleto: string; begin case ptgsTipo of tgsGetCabecalho: sTipoEsqueleto := cESQUELETO_GET_CABECALHO; tgsSetCabecalho: sTipoEsqueleto := cESQUELETO_SET_CABECALHO; end; Result := sTipoEsqueleto .Replace('@Campo', FormatarPrimeiraLetraMaiuscula(pfCampo.FieldName)) .Replace('@TipoCampo', PegarTipoCampo(pfCampo)); end; function TGerarClasse.FormatarGetSetImp(ptgsTipo: TTipoGetSet; pfCampo: TField): string; var sTipoEsqueleto: string; begin case ptgsTipo of tgsGetImplementation: sTipoEsqueleto := cESQUELETO_GET_IMPLEMENTATION; tgsSetImplementation: sTipoEsqueleto := cESQUELETO_SET_IMPLEMENTATION; end; Result := sTipoEsqueleto .Replace('@Tabela', FTabela) .Replace('@Campo', FormatarPrimeiraLetraMaiuscula(pfCampo.FieldName)) .Replace('@TipoCampo', PegarTipoCampo(pfCampo)) + sLineBreak; end; procedure TGerarClasse.IncluirCamposEstrutura(psCamposPrivate, psCamposPropriedades: string); var sHeranca, sUsesInterface, sUsesImplementation: string; begin sHeranca := IfThen(FHeranca.Length > 0, '(' + FHeranca + ')'); sUsesInterface := IfThen(FUsesInterface.Length > 0, cUSES + FUsesInterface + ';'); sUsesImplementation := IfThen(FUsesImplementation.Length > 0, cUSES + FUsesImplementation + ';'); FConteudoClasse.Text := cESQUELETO_UNIT .Replace('@Prefixo', FPrefixo) .Replace('@Tabela', FTabela) .Replace('@Sufixo', FSufixo) .Replace('@Heranca', sHeranca) .Replace('@Private', Trim(psCamposPrivate)) .Replace('@Public', Trim(psCamposPropriedades)) .Replace('@UsesInterface', sUsesInterface) .Replace('@UsesImplementation', sUsesImplementation); end; procedure TGerarClasse.IncluirGetSetEstrutura(psGettersCab, psSettersCab, psGettersImp, psSettersImp: string); var sCabGettersAndSetters, sImpGettersAndSetters: string; begin if FGerarGettersAndSetters then begin sImpGettersAndSetters := cESQUELETO_GETTERS_AND_SETTERS_IMPLEMENTATION .Replace('@Getters', Trim(psGettersImp)) .Replace('@Setters', Trim(psSettersImp)); sCabGettersAndSetters := psGettersCab + sLineBreak + psSettersCab; end; FConteudoClasse.Text := FConteudoClasse.Text .Replace('@GettersAndSettersCab', sCabGettersAndSetters) .Replace('@GettersAndSettersImp', sImpGettersAndSetters); end; {$ENDREGION} {$REGION 'Métodos públicos'} function TGerarClasse.GerarClasse(psTabela: string): boolean; var fCampo: TField; sCamposPrivate, sCamposPropriedades, sGettersCab, sSettersCab, sGettersImp, sSettersImp: string; begin try FTabela := FormatarPrimeiraLetraMaiuscula(psTabela); AbrirQuery; for fCampo in FQuery.Fields do begin sCamposPrivate.Insert(sCamposPrivate.Length, FormatarLinhaCampoPrivate(fCampo)); sCamposPropriedades.Insert(sCamposPropriedades.Length, FormatarLinhaCampoPropriedade(fCampo)); if GerarGettersAndSetters then begin sGettersCab.Insert(sGettersCab.Length, FormatarGetSetCab(tgsGetCabecalho, fCampo)); sSettersCab.Insert(sSettersCab.Length, FormatarGetSetCab(tgsSetCabecalho, fCampo)); sGettersImp.Insert(sGettersImp.Length, FormatarGetSetImp(tgsGetImplementation, fCampo)); sSettersImp.Insert(sSettersImp.Length, FormatarGetSetImp(tgsSetImplementation, fCampo)); end; end; FConteudoClasse.Clear; IncluirCamposEstrutura(sCamposPrivate, sCamposPropriedades); IncluirGetSetEstrutura(sGettersCab, sSettersCab, sGettersImp, sSettersImp); Result := True; except Result := False; end; end; function TGerarClasse.PegarConteudoArquivoGerado: string; begin Result := FConteudoClasse.Text; end; procedure TGerarClasse.SalvarArquivo(psCaminhoArquivo: string = ''); begin if FConteudoClasse.Text.Length = 0 then raise Exception.Create('Gere o arquivo antes de salvar!'); FConteudoClasse.SaveToFile(GetCaminhoArquivoFormatado(psCaminhoArquivo)); end; {$ENDREGION} {$REGION 'Métodos auxiliares'} function TGerarClasse.GetCaminhoArquivoFormatado(psCaminhoArquivo: string): string; var sPasta: string; begin sPasta := IfThen(psCaminhoArquivo.Length > 0, psCaminhoArquivo, ExtractFilePath(ParamStr(0))); Result := sPasta + FPrefixo + FTabela + FSufixo + '.pas'; end; function TGerarClasse.FormatarPrimeiraLetraMaiuscula(psTexto: string): string; begin if psTexto.Length > 1 then Result := UpperCase(psTexto.Chars[0]) + LowerCase(psTexto.Substring(1)) else Result := UpperCase(psTexto); end; {$ENDREGION} end.
{------------------------------------------------------------------------------} { FileName : } { VP500lib.pas } { Description : } { 32-bit Delphi language interface for accessing the library BLVP500.DLL. } { This file contains functions prototypes, variables and constants } { defined for controlling a VP500 from a Windows® application. } { Author: } { Franck GARNIER } { } { (c) Bio-Logic compagny } { August 2003 } { } {------------------------------------------------------------------------------} // 17.2.04 ... Modified to make BLVP500.dll functions dynamically loaded (J. Dempster) // 22.3.04 ... Modified to supporr BVLP500 V1.1 unit VP500lib; INTERFACE {==============================================================================} { Error codes returned by the functions. } {==============================================================================} const //General error codes RSP_NO_ERROR = 0; { Function succeeded } RSP_BLVP500_LIB_NOT_INIT = -1; { BLVP500 library not initialized } RSP_PARAMETERS_ERROR = -2; { Invalid parameters to function call } RSP_COMM_FAILED = -3; { Communication between the VP500 and the GPIB board failed } RSP_UNEXPECTED_ERROR = -4; { Unexpected error } RSP_NOT_ALLOWED_CONT_ACQ_MODE = -5; { Function not allowed in continuous acquisition mode } RSP_NOT_VCLAMP_MODE = -6; { Function only allowed in V-Clamp and V-Track mode } //GPIB library error codes RSP_GPIB32_LOAD_LIB_FAILED = -10; { gpib-32.dll : LoadLibrary failed } RSP_GPIB32_GET_PROC_ADDR_FAILED = -11; { gpib-32.dll : GetProcAddress failed } RSP_GPIB32_FREE_LIB_FAILED = -12; { gpib-32.dll : FreeLibrary failed } //VP500 & GPIB board error codes RSP_UNABLE_FIND_GPIB_BOARD = -20; { Unable to find the GPIB board } RSP_UNABLE_FIND_VP500 = -21; { Unable to find the VP500 device } RSP_UNABLE_INIT_GPIB_BOARD = -22; { Unable to initialize the GPIB board } RSP_UNABLE_INIT_VP500 = -23; { Unable to initialize the VP500 device } //Load firmware error codes RSP_UNABLE_CFG_VP500 = -30; { Unable to configure VP500 } RSP_BAD_VP500_IDENT = -31; { Wrong VP500 identifier } RSP_LOAD_FIRMWARE_ERR = -32; { Error during the downloading of the firmware } RSP_CODE_SEG_ERR = -33; { Wrong VP500 code segment } RSP_FILE_NOT_FOUND = -34; { "VP500.bin" not found } RSP_FILE_ACCESS_ERR = -35; { "VP500.bin" access error } //Acquisition error codes RSP_ACQ_IN_PROGRESS = -40; { An acquisition is already in progress } RSP_ACQ_DATA_FAILED = -41; { Data acquisition on VP500 failed } RSP_GET_ADC1_DATA_FAILED = -42; { Get ADC1 data failed } RSP_GET_ADC2_DATA_FAILED = -43; { Get ADC2 data failed } RSP_ADC1_DATA_EXCEPTION = -44; { Exception occurred during treatment of ADC1 data } RSP_ADC2_DATA_EXCEPTION = -45; { Exception occurred during treatment of ADC2 data } //Stimulation error codes RSP_STIM_LOAD_FAILED = -50; { Can not load programmed stimulation in the VP500 } RSP_STIM_TRANSFER_FAILED = -51; { Can not transfer programmed stimulation in the RAM of the VP500 } RSP_STIM_NOT_TRANSFERRED = -52; { Programmed stimulation not transferred in the RAM of the VP500 } RSP_NOT_ENOUGH_MEMORY = -53; { Not enough memory in the VP500 (too many points to acquire) } RSP_ACQ_TIME_OUT = -54; { Acquisition time out } {==============================================================================} { Integer and real data types. } {==============================================================================} Type int8 = ShortInt; { signed 8-bit } int16 = SmallInt; { signed 16-bit } int32 = LongInt; { signed 32-bit } uint8 = byte; { unsigned 8-bit } uint16 = Word; { unsigned 16-bit } uint32 = Longword; { unsigned 32-bit } Ptrint8 = ^int8; Ptrint16 = ^int16; Ptrint32 = ^int32; PtrUint8 = ^uint8; PtrUint16 = ^uint16; PtrUint32 = ^uint32; PtrSingle = ^single; {==============================================================================} { Initialization and release of the library. } {==============================================================================} {$IFNDEF BLVP500LIB} TVP500_InitLib = function : int32; stdcall ; TVP500_FreeLib = procedure ; stdcall ; {$ENDIF} {==============================================================================} { Test of the communication between the library and the VP500. } {==============================================================================} {$IFNDEF BLVP500LIB} TVP500_TestTransfer = function : int32; stdcall ; {$ENDIF} {==============================================================================} { VP500 informations. } {==============================================================================} Type TBLVP500Infos = packed record LibVersion : array [0..7] of Char; { Library version } FirmwareVersion : array [0..7] of Char; { Firmware version } CodeSegment : uint16; { VP500 code segment } NMIInterruptMode : boolean; { NMI Interrupt Mode } Switch : int32; { VP500 switch } Checksum : int32; { VP500 checksum } end; PtrTBLVP500Infos = ^TBLVP500Infos; {$IFNDEF BLVP500LIB} TVP500_GetInfos = function(pInfos: PtrTBLVP500Infos): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 wave stimulator. } {==============================================================================} const //Wave direction : constants used by the field "Direction" in the record "TWStimParams" WS_UP = 0; { Wave direction : UP } WS_DOWN = 1; { Wave direction : DOWN } WS_BOTH = 2; { Wave direction : BOTH } //Filter : constants used by the field "Filter" in the record "TWStimParams" WS_FILTER_FULL = 0; WS_FILTER_10_KHZ = 1; WS_FILTER_1_KHZ = 2; Type TWStimParams = packed record Ramp : boolean; { Wave type : TRUE->ramp FALSE->pulse} Amplitude : single; { Signal amplitude -> mV in potential clamp mode } { ................ -> nA in current clamp mode } Period : uint32; { Signal period (20µs) } TriggerOut : boolean; { Trigger out (BNC connector "[Stimulation] Trigger Out") } Direction : uint8; { Wave direction } Filter : uint8; { stimulation filter } ExternalStim : boolean; { External stimulation on BNC connector "[Command] Vin/Iin") } SendStimOut : boolean; { Send stimulation to the BNC connector "[Stimulation] Out" } end; PtrTWStimParams = ^TWStimParams; TSingleRamp = packed record Amplitude : single; { Signal amplitude -> mV in potential clamp mode } { ................ -> nA in current clamp mode } Length : uint32; { Signal length (10µs) } end; PtrTSingleRamp = ^TSingleRamp; {$IFNDEF BLVP500LIB} //Set wave stimulator parameters : TVP500_SetWaveStimParams = function( pWStimParams: PtrTWStimParams): int32 ; stdcall; //Get wave stimulator parameters : TVP500_GetWaveStimParams = function(pWStimParams: PtrTWStimParams): int32; stdcall; //Start wave stimulator : TVP500_StartWaveStim = function : int32; stdcall; //Stop wave stimulator : TVP500_StopWaveStim = function : int32; stdcall; //Generate a single ramp : TVP500_SingleRamp = function(pSRamp: PtrTSingleRamp): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 holding potential/current. } {==============================================================================} {$IFNDEF BLVP500LIB} //Set VIHold value (mV in potential clamp mode ; nA in current clamp mode) TVP500_SetVIHold = function(VIHold: single): int32; stdcall; //Get VIHold value (mV in potential clamp mode ; nA in current clamp mode) TVP500_GetVIHold = function(pVIHold: PtrSingle): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 hardware configuration. } {==============================================================================} const //Clamp modes : constants used by the field "ClampMode" in the record "THardwareConf" VIMODE_V_CLAMP = 0; { V-Clamp = Voltage clamp mode } VIMODE_IO = 1; { Io = voltage follower mode of the amplifier } VIMODE_I_CLAMP = 2; { I-Clamp = Current clamp mode } VIMODE_V_TRACK = 3; { V-Track = zero current voltage clamp } //Clamp speed (in current clamp mode): constants used by the field "ClampSpeed" //in the record "THardwareConf" VIMODE_SPEED_SLOW = 0; { Slow time constant } VIMODE_SPEED_MEDIUM = 1; { Medium time constant } VIMODE_SPEED_FAST = 2; { Fast time constant } //Amplifier stage filter : constants used by the field "AmplifierStageFilter" //in the record "THardwareConf" //WARNING : in VTrack mode, the amplifier stage filter is forced to AMPL_FILTER_100_HZ AMPL_FILTER_100_HZ = 0; { cut-off frequency = 100 Hz } AMPL_FILTER_200_HZ = 1; { cut-off frequency = 200 Hz } AMPL_FILTER_500_HZ = 2; { cut-off frequency = 500 Hz } AMPL_FILTER_1_KHZ = 3; { cut-off frequency = 1 kHz } AMPL_FILTER_2_KHZ = 4; { cut-off frequency = 2 kHz } AMPL_FILTER_5_KHZ = 5; { cut-off frequency = 5 kHz } AMPL_FILTER_10_KHZ = 6; { cut-off frequency = 10 kHz } AMPL_FILTER_20_KHZ = 7; { cut-off frequency = 20 kHz } AMPL_FILTER_50_KHZ = 8; { cut-off frequency = 50 kHz } //Amplifier stage gain : constants used by the field "AmplifierStageGain" in //the record "THardwareConf" AMPL_GAIN_1 = 0; { Amplifier gain: x1 } AMPL_GAIN_2 = 1; { Amplifier gain: x2 } AMPL_GAIN_5 = 2; { Amplifier gain: x5 } AMPL_GAIN_10 = 3; { Amplifier gain: x10 } AMPL_GAIN_20 = 4; { Amplifier gain: x20 } AMPL_GAIN_50 = 5; { Amplifier gain: x50 } AMPL_GAIN_100 = 6; { Amplifier gain: x100 } AMPL_GAIN_200 = 7; { Amplifier gain: x200 } AMPL_GAIN_500 = 8; { Amplifier gain: x500 } Type THardwareConf = packed record ClampMode : uint8; { Clamp mode } ClampSpeed : uint8; { Clamp speed } AmplifierStageFilter : uint8; { Amplifier stage filter } AmplifierStageGain : uint8; { Amplifier stage gain } HeadGainH : boolean; { High (TRUE) or low head gain (FALSE) } HeadGainHigh : double; { High head gain value (Gohm) - READ ONLY } HeadGainLow : double; { Low head gain value (Gohm) - READ ONLY } TotalGain : double; { Total gain (mV/pA) = head gain x amplifier stage gain - READ ONLY } AmplitudeMax : single; { Signal amplitude max -> mV in potential clamp mode - READ ONLY } { .................... -> nA in current clamp mode - READ ONLY } GPIBTimeOut : uint8; { GPIB timeout period } end; PtrTHardwareConf = ^THardwareConf; {$IFNDEF BLVP500LIB} TVP500_SetHardwareConf = function(pHardwareConf: PtrTHardwareConf): int32; stdcall; TVP500_GetHardwareConf = function(pHardwareConf: PtrTHardwareConf): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 status flags. } {==============================================================================} Type //VP500 status structure TVP500Status = packed record //Status flags: IHeadOverload : boolean; { IHead overload } VmOverload : boolean; { Vm overload } ADC1Overload : boolean; { ADC1 overload } ADC2Overload : boolean; { ADC2 overload } AcqADC1 : boolean; { Acquisition on ADC1 } AcqADC2 : boolean; { Acquisition on ADC2 } WaveStim : boolean; { Wave stimulator ON } TestSignal : boolean; { Test signal } InputTTL0 : boolean; { Input TTL0 } InputTTL1 : boolean; { Input TTL1 } InputTTL2 : boolean; { Input TTL2 } //Memory status: TotalBlocksNb : int32; { Number of memory blocks shared by ADC1 and ADC2 (1 block = 1024 points) } ADC1FullBlocksNb : int32; { ADC1 : number of full blocks } ADC2FullBlocksNb : int32; { ADC2 : number of full blocks } end; PtrTVP500Status = ^TVP500Status; {$IFNDEF BLVP500LIB} TVP500_GetVP500Status = function(pStatus : PtrTVP500Status): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 ADC buffers. } {==============================================================================} const //Sampling rate : constants used by the field "SamplingRate" in the record "TData" SAMPLING_RATE_100_KHZ = 0; { 100 kHz } SAMPLING_RATE_50_KHZ = 1; { 50 kHz } SAMPLING_RATE_20_KHZ = 2; { 20 kHz } SAMPLING_RATE_10_KHZ = 3; { 10 kHz } SAMPLING_RATE_5_KHZ = 4; { 5 kHz } SAMPLING_RATE_2_KHZ = 5; { 2 kHz } SAMPLING_RATE_1_KHZ = 6; { 1 kHz } SAMPLING_RATE_500_HZ = 7; { 500 Hz } //Data Selection of ADC1 buffer : constants used by the field "ADC1Selection" //in the record "TData". //In potential clamp mode VI=Vm (mV) ; in current clamp mode VI=Iout (pA) READ_VI = 0; { Read VI } READ_AUX1 = 1; { Read AUX1 } READ_AUX2 = 2; { Read AUX2 } READ_AUX3 = 3; { Read AUX3 } READ_AUX4 = 4; { Read AUX4 } READ_VI_AUX1 = 5; { Read VI and AUX1 } READ_VI_AUX2 = 6; { Read VI and AUX2 } READ_VI_AUX3 = 7; { Read VI and AUX3 } READ_VI_AUX4 = 8; { Read VI and AUX4 } READ_AUX1_AUX2 = 9; { Read AUX1 and AUX2 } READ_AUX1_AUX3 = 10; { Read AUX1 and AUX3 } READ_AUX1_AUX4 = 11; { Read AUX1 and AUX4 } READ_AUX2_AUX3 = 12; { Read AUX2 and AUX3 } READ_AUX2_AUX4 = 13; { Read AUX2 and AUX4 } READ_AUX3_AUX4 = 14; { Read AUX3 and AUX4 } Type //Acquisition parameters structure TAcqParams = packed record SamplingRate : uint8; { Sampling rate (100kHz -> 500Hz) } ADC1Selection : uint8; { Data acquired by ADC1 } AuxAInput : boolean; { Auxiliary input selection : Aux A (TRUE) or Aux B (FALSE) } end; PtrTAcqParams = ^TAcqParams; //Acquisition structure TData = packed record //Parameters: LengthBufADC : uint32; { Length of the buffers "BufADC1" and "BufADC2" } SynchData : boolean; { Synchronise data in ADC buffers (only available if } { the continuous acquisition is NOT active and the } { wave stimulator is ON). Only 1 block will be acquired. } //Result: BufADC1 : PtrSingle; { ADC1 buffer : contains multiplexed data (depending of "ADC1Selection") } BufADC2 : PtrSingle; { ADC2 buffer : Iout (pA) in potential clamp mode } { ........... Vm (mV) in current clamp mode } NbPtsBufADC1 : uint32; { Number of points put in the buffer "BufADC1" } NbPtsBufADC2 : uint32; { Number of points put in the buffer "BufADC2" } end; PtrTData = ^TData; {$IFNDEF BLVP500LIB} //Set acquisition parameters TVP500_SetAcqParams = function(pAcqParams: PtrTAcqParams) : int32; stdcall; //Get ADC buffers TVP500_GetADCBuffers = function(pData: PtrTData): int32; stdcall; //Start continuous acquisition TVP500_StartContinuousAcq = function : int32; stdcall; //Stop continuous acquisition TVP500_StopContinuousAcq = function: int32; stdcall; {$ENDIF} {==============================================================================} { VP500 progammed stimulations. } {==============================================================================} type TDigitalOutput = packed record Duration : uint32; { Duration of the "true" level (ms) } Output : uint16; { Digital outputs to activate : bit0 -> digital output 1 } { ........................... bit1 -> digital output 2 } { ........................... ........................ } { ........................... bit8 -> digital output 9 } end; TBasicStim = packed record Ramp : boolean; { TRUE->Ramp ; FALSE->Pulse } Duration : uint32; { Duration of the basic stimulation (µs) } Amplitude : single; { PULSE : Amplitude of the basic stimulation } { RAMP : Amplitude to reach by the basic stimulation } { -> mV in potential clamp mode } { -> nA in current clamp mode } end; TBasicStimTab = array[0..99] of TBasicStim; PtrTBasicStimTab = ^TBasicStimTab; //Programmed stimulations structure TStim = packed record //Stimlations : StimTab : TBasicStimTab; { Array of basic stimulations } StimTabNb : uint8; { Number of valid basic stimulations in the array "StimTab" } RecDuration : uint32; { Total recording duration (10µs), included InitialDelay } InitialDelay : uint32; { Initial delay before stimulations (10µs) } //Digital outputs : DigitalOutput : TDigitalOutput; { Digital outputs } //Result NbBlocksToAcq : uint32; { Number of blocks to acquire for each ADC } end; PtrTStim = ^TStim; {$IFNDEF BLVP500LIB} //Start programmed stimulations TVP500_StartStim = function (pStim: PtrTStim): int32; stdcall; //Stop programmed stimulations TVP500_StopStim = function : Int32 ; stdcall; {$ENDIF} {==============================================================================} { VP500 seal (only available in potential clamp mode). } {==============================================================================} type //Seal impedance structure TSealImpedance = packed record //Parameters: Amplitude : single; { Signal amplitude (mV) } Period : uint32; { Signal period (20µs) } DirectionUp : boolean; { Signal direction: up (TRUE) or down (FALSE) } //Result: SealImpedance : single; { Seal impedance (Mohm) - READ ONLY } end; PtrTSealImpedance = ^TSealImpedance; {$IFNDEF BLVP500LIB} //Apply zap -> ZapDuration (10µs) [min = 10µs; max = 1500µs] TVP500_DoZap = function(ZapDuration: uint16): int32; stdcall; //Set junction potential compensation (mV) TVP500_SetJunction = function(val: single): int32; stdcall; //Get junction potential compensation (mV) TVP500_GetJunction = function(pVal: PtrSingle): int32; stdcall; //Determination of the seal impedance TVP500_CalcSealImpedance = function(pSealImpedance: PtrTSealImpedance): int32; stdcall; {$ENDIF} {==============================================================================} { VP500 compensations and neutralizations. } {==============================================================================} const //Delay of series resistance compensation loop: constants used by the field //"TauPercentRs" in the record "TCompensations" : DELAY_1_MICROS = 0; { delay 1 µs } DELAY_3_MICROS = 1; { delay 3 µs } DELAY_7_MICROS = 2; { delay 7 µs } DELAY_10_MICROS = 3; { delay 10 µs } DELAY_20_MICROS = 4; { delay 20 µs } DELAY_30_MICROS = 5; { delay 30 µs } DELAY_60_MICROS = 6; { delay 60 µs } DELAY_100_MICROS = 7; { delay 100 µs } type TCompensations = packed record PercentBoost : uint8; { Cell capacitance compensation (%) : precharging circuit (boost) } PercentRs : uint8; { Pipette resistance compensation (%) : series resistance compensation } TauPercentRs : uint8; { Series resistance lag } end; PtrTCompensations = ^TCompensations; TLimits = packed record Max : single; Min : single; end; TNeutralization = packed record CFast : single; { Fast capacitance neutralization (pF) } TauFast : single; { (µs) } CSlow : single; { Slow capacitance neutralization (pF) } TauSlow : single; { (ms) } CCell : single; { Cell capacitance neutralization (pF) } TauCell : single; { (ms) } Leak : single; { Leak neutralization (nS) } //Read only fields : CFast_L : TLimits; { CFast limits (pF) - READ ONLY } TauFast_L : TLimits; { TauFast limits (µs) - READ ONLY } CSlow_L : TLimits; { CSlow limits (pF) - READ ONLY } TauSlow_L : TLimits; { TauSlow limits (ms) - READ ONLY } CCell_L : TLimits; { CCell limits (pF) - READ ONLY } TauCell_L : TLimits; { TauCell limits (ms) - READ ONLY } Leak_L : TLimits; { Leak limits (nS) - READ ONLY } end; PtrTNeutralization = ^TNeutralization; TNeutralizationParams = packed record MaxPassNb_CFast_CSlow : uint32; { Number of iterations in the hybrid algorithms } { of C-Fast and C_Slow } MaxPassNb_CCell_COpt : uint32; { Number of iterations in the hybrid algorithms } { of C-Cell and C_Opt } PercentLeakComp : uint8; { %leak compensation } AutoOff_AccessR : boolean; { Automatic reset the series resistance compensation } { when the amplifier starts to oscillate } ClampRatio : single; { Clamp ratio : Rs/(Rs + Rm) } { Proportion of the command voltage lost in the } { series resistance before the preparation. } EquivalentRes : single; { Equivalent resistance (Mohm) : Rs.Rm/(Rs+Rm) } { Ratio of the capacitive current time constant } { to the condenser capacity. } end; PtrTNeutralizationParams = ^TNeutralizationParams; {$IFNDEF BLVP500LIB} //Reinitialization of compensations and neutralizations TVP500_Reinitialization = function: int32; stdcall; //Manual compensations : TVP500_SetCompensations = function(pComp: PtrTCompensations): int32; stdcall; TVP500_GetCompensations = function(pComp: PtrTCompensations): int32; stdcall; //Manual neutralizations : TVP500_SetNeutralization = function(pNeutr: PtrTNeutralization): int32; stdcall; TVP500_GetNeutralization = function(pNeutr: PtrTNeutralization): int32; stdcall; //Neutralization parameters : TVP500_SetNeutralizationParams = function(pNParams: PtrTNeutralizationParams): int32; stdcall; TVP500_GetNeutralizationParams = function(pNParams: PtrTNeutralizationParams): int32; stdcall; //Automatic neutralization of Cfast : TVP500_CFastNeutralization = function: int32; stdcall; //Automatic neutralization of Cslow : TVP500_CSlowNeutralization = function: int32; stdcall; //Automatic neutralization of Ccell and leak : TVP500_CCellNeutralization = function: int32; stdcall; //Automatic neutralization of leak: TVP500_LeakNeutralization = function: int32; stdcall; //Automatic optimisation of neutralization of Ccell and leak : TVP500_OptimizeNeutralization = function: int32; stdcall; {$ENDIF} {==============================================================================} { VP500 cell parameters. } {==============================================================================} type TCellParameters = packed record Rs : single; { Serial resistance (Mohm) } Cm : single; { Membrane capacitance (pF) } Rm : single; { Membrane resistance (Mohm) } end; PtrTCellParameters = ^TCellParameters; {$IFNDEF BLVP500LIB} //Detection of cell parameters : TVP500_CellParameters = function(pCellParameters: PtrTCellParameters): int32; stdcall; {$ENDIF} IMPLEMENTATION end.
unit LookupUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGridEh, StdCtrls, ExtCtrls, DB, DbGridUnit, StorageUnit, MaximizedUnit, DataUnit; type { TLookupForm } TLookupForm = class(TMaximizedForm, IRememberable) BottomPanel: TPanel; OKBtn: TButton; CancelBtn: TButton; LookupFrame: TDbGridFrame; Bevel1: TBevel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure LookupFrameGridDblClick(Sender: TObject); private FLocateField: string; FLocateValue: Variant; FSection: string; protected function SelectRecord(const FieldName: string; Value: Variant): Variant; overload; function SelectRecord(const FieldName: string; var Value: Variant; var Values: Variant): Boolean; overload; function SelectRecordEx(const FieldNames: string; Values: Variant): Boolean; procedure Loaded; override; function DoLookupRecord(const Caption, StorageSection: string; ColumnInfos: array of TColumnInfo; const FieldName: string; var Value: Variant; var Values: Variant): Boolean; protected { IRememberable } procedure SaveState(Storage: TStorage; const SectionName, Prefix: string); virtual; procedure LoadState(Storage: TStorage; const SectionName, Prefix: string); virtual; public property Section: string read FSection write FSection; class function LookupDataSetRecord(DataSet: TDataSet; const Caption, StorageSection: string; ColumnInfos: array of TColumnInfo; const FieldName: string; var Value: Variant; var Values: Variant): Boolean; end; var LookupForm: TLookupForm; implementation {$R *.dfm} { TLookupForm } function TLookupForm.SelectRecord(const FieldName: string; Value: Variant): Variant; var Values: Variant; begin Result := Value; SelectRecord(FieldName, Result, Values); end; function TLookupForm.SelectRecord(const FieldName: string; var Value: Variant; var Values: Variant): Boolean; var Count, I: Integer; AlreadyActive: Boolean; begin AlreadyActive := LookupFrame.DataSource.DataSet.Active; if not AlreadyActive then LookupFrame.DataSource.DataSet.Open; try FLocateField := FieldName; FLocateValue := Value; Result := ShowModal = mrOK; if Result then begin Value := LookupFrame.DataSource.DataSet.FieldValues[FieldName]; Count := LookupFrame.DataSource.DataSet.FieldCount; Values := VarArrayCreate([0, Count], varVariant); for I := 0 to Count - 1 do Values[I] := LookupFrame.DataSource.DataSet.Fields[I].Value; end; finally if not AlreadyActive then LookupFrame.DataSource.DataSet.Close; end; end; function TLookupForm.SelectRecordEx(const FieldNames: string; Values: Variant): Boolean; begin if not LookupFrame.DataSource.DataSet.Active then LookupFrame.DataSource.DataSet.Open; if FieldNames <> '' then LookupFrame.DataSource.DataSet.Locate(FieldNames, Values, []); Result := ShowModal = mrOK; end; procedure TLookupForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_F3) and (Shift = []) then begin ModalResult := mrCancel; Key := 0; end; end; procedure TLookupForm.FormShow(Sender: TObject); begin LoadFormState(Self, Section, ''); if (FLocateField <> '') and not VarIsEmpty(FLocateValue) then LookupFrame.DataSource.DataSet.Locate(FLocateField, FLocateValue, []); LookupFrame.Grid.SetFocus; end; procedure TLookupForm.FormHide(Sender: TObject); begin SaveFormState(Self, Section, ''); end; procedure TLookupForm.Loaded; begin inherited Loaded; if Section = '' then Section := Name; end; { IRememberable } procedure TLookupForm.SaveState(Storage: TStorage; const SectionName, Prefix: string); begin if FLocateField <> '' then begin Storage.WriteString(SectionName, Prefix + Name + '.SavedField', LookupFrame.DataSource.DataSet.FieldByName(FLocateField).AsString); end; end; procedure TLookupForm.LoadState(Storage: TStorage; const SectionName, Prefix: string); var SavedField: string; begin if FLocateField <> '' then begin SavedField := Storage.ReadString(SectionName, Prefix + Name + '.SavedField', ''); LookupFrame.DataSource.DataSet.Locate(FLocateField, SavedField, []); end; end; function TLookupForm.DoLookupRecord(const Caption, StorageSection: string; ColumnInfos: array of TColumnInfo; const FieldName: string; var Value, Values: Variant): Boolean; var I: Integer; Column: TColumnEh; begin Self.Caption := Caption; Section := StorageSection; for I := Low(ColumnInfos) to High(ColumnInfos) do begin Column := LookupFrame.Grid.Columns.Add; Column.FieldName := ColumnInfos[I].FieldName; Column.Title.Caption := ColumnInfos[I].Title; Column.Width := ColumnInfos[I].Width; Column.DisplayFormat := ColumnInfos[I].Format; end; LookupFrame.UpdateFieldList; Result := SelectRecord(FieldName, Value, Values); end; class function TLookupForm.LookupDataSetRecord(DataSet: TDataSet; const Caption, StorageSection: string; ColumnInfos: array of TColumnInfo; const FieldName: string; var Value: Variant; var Values: Variant): Boolean; var Form: TLookupForm; begin Form := TLookupForm.Create(Application); try Form.LookupFrame.DataSource.DataSet := DataSet; Result := Form.DoLookupRecord(Caption, StorageSection, ColumnInfos, FieldName, Value, Values); finally Form.Free; end; end; procedure TLookupForm.LookupFrameGridDblClick(Sender: TObject); begin inherited; ModalResult:=mrOK; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,System.Win.WinRt, WinApi.WinRt, WinApi.Foundation, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Math, Vcl.ExtCtrls, Vcl.WindowsStore, WinApi.WindowsStore, WinApi.CommonTypes, Vcl.Grids, Winapi.Storage, WinApi.ServicesRt.Store, WinApi.WinRt.Utils; type TForm1 = class(TForm) Label20: TLabel; WindowsStore1: TWindowsStore; PageControl1: TPageControl; TabSheet3: TTabSheet; Label11: TLabel; Label13: TLabel; Label14: TLabel; Label15: TLabel; FvPresentValue: TEdit; IrPresentValue: TEdit; PvPresentValue: TEdit; NpPresentValue: TEdit; TabSheet4: TTabSheet; Label9: TLabel; Label16: TLabel; Label12: TLabel; Label10: TLabel; PvFutureValue: TEdit; IrFutureValue: TEdit; FvFutureValue: TEdit; NpFutureValue: TEdit; Panel1: TPanel; Label17: TLabel; Button1: TButton; TabSheet1: TTabSheet; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; PvPayment: TEdit; IRPayment: TEdit; NpPayment: TEdit; PmtPayment: TEdit; Panel2: TPanel; Label18: TLabel; Button2: TButton; TabSheet2: TTabSheet; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; PvIRR: TEdit; PmtIRR: TEdit; NpIRR: TEdit; IRIRR: TEdit; Panel3: TPanel; Label19: TLabel; Button3: TButton; TabSheet6: TTabSheet; Memo1: TMemo; procedure PaymentChange(Sender: TObject); procedure IRRChange(Sender: TObject); procedure PresentValueChange(Sender: TObject); procedure PvFutureValueChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } procedure RecalcPayment(); procedure CalculateIRR(); procedure CalculatePV(); procedure CalculateFV(); procedure CheckIfTrial(); procedure EnableFullVersion(); procedure CheckBoughtCalculators(); function PurchaseItem(Item : string) : String; procedure UpdateProducts(); procedure BuyProduct(Product: IStoreProduct); procedure LogMessage(Msg : String); function BuyProductById(IdProduct: String) : String; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} function Purchase(StoreId : PAnsiChar) : PAnsiChar; stdcall; external 'IAPWrapper.dll'; procedure TForm1.CheckBoughtCalculators; begin LogMessage('FutureCalc: ' + WindowsStore1.UserHasBought('FutureCalc').ToString(TUseBoolStrs.True)); LogMessage('PaymentCalc: ' + WindowsStore1.UserHasBought('PaymentCalc').ToString(TUseBoolStrs.True)); LogMessage('RateCalc: ' + WindowsStore1.UserHasBought('RateCalc').ToString(TUseBoolStrs.True)); Panel1.Visible := not WindowsStore1.UserHasBought('FutureCalc'); Panel2.Visible := not WindowsStore1.UserHasBought('PaymentCalc'); Panel3.Visible := not WindowsStore1.UserHasBought('RateCalc'); end; procedure TForm1.CheckIfTrial; begin LogMessage('IsActive: ' + WindowsStore1.AppLicense.IsActive.ToString(TUseBoolStrs.True)); LogMessage('IsIsTrial: ' + WindowsStore1.AppLicense.IsTrial.ToString(TUseBoolStrs.True)); if WindowsStore1.AppLicense.IsActive then begin if WindowsStore1.AppLicense.IsTrial then begin var RemainingDays := WindowsStore1.AppLicense.TrialTimeRemaining.Days; LogMessage('Remaining days: ' + WindowsStore1.AppLicense.TrialTimeRemaining.Days.ToString()); EnableFullVersion; end else CheckBoughtCalculators; end; end; procedure TForm1.EnableFullVersion; begin Panel1.Visible := False; Panel2.Visible := False; Panel3.Visible := False; end; procedure TForm1.FormCreate(Sender: TObject); begin CheckIfTrial(); UpdateProducts(); end; procedure TForm1.CalculatePV; begin try var FutureValue := StrToFloat(FvPresentValue.Text); var InterestRate := StrToFloat(IrPresentValue.Text) / 100.0; var NumPeriods := StrToInt(NpPresentValue.Text); var PresentValue := FutureValue / Power((1 + InterestRate), NumPeriods); PvPresentValue.Text := FormatFloat('0.00', PresentValue); except On EConvertError do PvPresentValue.Text := ''; end; end; procedure TForm1.PvFutureValueChange(Sender: TObject); begin CalculateFV(); end; procedure TForm1.Button1Click(Sender: TObject); begin PurchaseItem('FutureCalc'); end; procedure TForm1.Button2Click(Sender: TObject); begin PurchaseItem('PaymentCalc'); end; procedure TForm1.Button3Click(Sender: TObject); begin PurchaseItem('RateCalc'); end; procedure TForm1.CalculateFV; begin try var PresentValue := StrToFloat(PvFutureValue.Text); var InterestRate := StrToFloat(IrFutureValue.Text) / 100.0; var NumPeriods := StrToInt(NpFutureValue.Text); var FutureValue := PresentValue * Power((1 + InterestRate), NumPeriods); FvFutureValue.Text := FormatFloat('0.00', FutureValue); except On EConvertError do FvFutureValue.Text := ''; end; end; procedure TForm1.CalculateIRR; begin try var NumPayments := StrToInt(NpIRR.Text); var PresentValue := StrToFloat(PvIRR.Text); var Payment := StrToFloat(PmtIRR.Text); var FoundRate := False; var MinRate := 0.0; var MaxRate := 1.0; if Payment * NumPayments < PresentValue then begin IRIRR.Text := 'Rate Less than 0'; exit; end; if Payment * NumPayments = PresentValue then begin IRIRR.Text := '0.00'; exit; end; if Payment > PresentValue then begin IRIRR.Text := 'Payment greater than Present Value'; exit; end; while not FoundRate do begin var Rate := (MaxRate + MinRate) / 2.0; var SumPayments := 0.0; for var I := 1 to NumPayments do SumPayments := SumPayments + Payment / Power((1 + Rate), I); if Abs(SumPayments - PresentValue) > 0.01 then begin if PresentValue < SumPayments then begin MinRate := Rate; end else begin MaxRate := Rate; end; end else begin FoundRate := True; IRIRR.Text := FormatFloat('0.00', Rate * 100.0); end; end; except On EConvertError do IRIRR.Text := ''; end; end; procedure TForm1.PaymentChange(Sender: TObject); begin RecalcPayment(); end; procedure TForm1.PresentValueChange(Sender: TObject); begin CalculatePV(); end; function TForm1.PurchaseItem(Item: string) : string; begin LogMessage('Will purchase item: ' +Item); for var i := 0 to WindowsStore1.AppProducts.Count - 1 do if TWindowsString.HStringToString(WindowsStore1.AppProducts[i].InAppOfferToken) = Item then begin BuyProduct(WindowsStore1.AppProducts[i]); exit; end; LogMessage('Item not found: ' +Item); end; function TForm1.BuyProductById(IdProduct: String) : String; begin Result := ''; try Result := Purchase(PAnsiChar(AnsiString(IdProduct))); except On e : Exception do LogMessage('Exception while buying item.'+Chr(13)+ E.ClassName+', with message : '+E.Message); end; end; procedure TForm1.BuyProduct(Product: IStoreProduct); begin try //var status := WindowsStore1.PurchaseProduct(Product); //LogMessage('Got status: '+Integer(status).ToString); //if status = StorePurchaseStatus.Succeeded then begin var status := Purchase(PAnsiChar(AnsiString(TWindowsString.HStringToString(Product.StoreId)))); LogMessage('Got status: '+status); if status = 'Succeeded' then begin LogMessage('Item ' +TWindowsString.HStringToString(Product.Title)+' bought'); CheckBoughtCalculators(); end else begin ShowMessage('Item could not be purchased. Error: '+Integer(status).ToString); end; except On e : Exception do LogMessage('Exception while buying item.'+Chr(13)+ E.ClassName+', with message : '+E.Message); end; end; procedure TForm1.IRRChange(Sender: TObject); begin CalculateIRR(); end; procedure TForm1.LogMessage(Msg: String); begin Memo1.Lines.Add(Msg); OutputDebugString(PWideChar(Msg)); end; procedure TForm1.RecalcPayment; begin try var PresentValue := StrToFloat(PvPayment.Text); var InterestRate := StrToFloat(IRPayment.Text) / 100.0; var NumPayments := StrToInt(NpPayment.Text); var Payment := (PresentValue * InterestRate) * Power((1 + InterestRate), NumPayments) / (Power((1 + InterestRate), NumPayments) - 1); PmtPayment.Text := FormatFloat('0.00', Payment); except On EConvertError do PmtPayment.Text := ''; end; end; procedure TForm1.UpdateProducts; var LProdsCount: Integer; I: Integer; begin LProdsCount := WindowsStore1.AppProducts.Count; LogMessage('Total products:'+LProdsCount.ToString()); for I := 0 to LProdsCount - 1 do begin LogMessage(WindowsStore1.AppProducts[I].InAppOfferToken.ToString+Chr(9)+ WindowsStore1.AppProducts[I].StoreId.ToString+Chr(9)+ WindowsStore1.AppProducts[I].Title.ToString+Chr(9)+ WindowsStore1.AppProducts[I].Price.FormattedBasePrice.ToString+Chr(9)+ WindowsStore1.AppProducts[I].ProductKind.ToString+Chr(9)+ WindowsStore1.AppProducts[I].Price.IsOnSale.ToString(TUseBoolStrs.True)+Chr(9)+ WindowsStore1.AppProducts[I].IsInUserCollection.ToString(TUseBoolStrs.True)); end; LogMessage('----------------') end; end.
unit uPrjInstalador; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, ComCtrls; type { TfrmInstaladorSistema } TfrmInstaladorSistema = class(TForm) btnGerarScript: TButton; btnGerarScript1: TButton; Button1: TButton; Button2: TButton; chkNulo01: TCheckBox; cmbTabela1: TComboBox; cmbTabela: TComboBox; cmbVariavel01: TComboBox; edtContadorCombo: TEdit; edtcampo01: TEdit; edtContadorCampo: TEdit; edtContadorAlturaTop: TEdit; edtDecimal01: TEdit; edtNomeTabela: TEdit; edtquantidadecampos: TEdit; edttamanho01: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label7: TLabel; lblCampo01: TLabel; lblDecimal01: TLabel; lblTamanho01: TLabel; lblVariavel01: TLabel; ListBox1: TListBox; ListBox2: TListBox; Memo1: TMemo; memoFirebird: TMemo; memoMySQL: TMemo; memoSQLite: TMemo; PageControl1: TPageControl; PageControl2: TPageControl; RadioGroup1: TRadioGroup; ScrollBox1: TScrollBox; TabSheet1: TTabSheet; tabCampoDaTabela: TTabSheet; TabSheet3: TTabSheet; TabSheet4: TTabSheet; procedure btnGerarScriptClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure PageControl1Change(Sender: TObject); private public end; var frmInstaladorSistema: TfrmInstaladorSistema; implementation {$R *.lfm} { TfrmInstaladorSistema } procedure TfrmInstaladorSistema.btnGerarScriptClick(Sender: TObject); var gerastring : string; begin If (Trim(edtNomeTabela.text) = '') Then Begin ShowMessage('O campo não pode estar vazio'); edtNomeTabela.SetFocus; end Else Begin gerastring := ''; gerastring := gerastring + 'CREATE TABLE ' + edtNomeTabela.text + ' ( '; gerastring := gerastring + 'id int not null primary key'; gerastring := gerastring + ')'; memoFirebird.Lines.Clear; memoFirebird.Lines.Add('Script de Criação de Tabelas - FIREBIRD'); memoFirebird.Lines.Add(''); memoFirebird.Lines.Add(gerastring); end; end; procedure TfrmInstaladorSistema.Button1Click(Sender: TObject); var EditCampoTempoReal : TEdit; cmbVariavelTempoReal : TComboBox; intAlturaTop, I, ContadorCampo : Integer; strNomeCampo : String; begin //============================================================================ intAlturaTop := StrToInt(edtContadorAlturaTop.Text); I := 0; ContadorCampo := StrToInt(edtContadorCampo.Text); While I < StrToInt(edtquantidadecampos.Text) Do Begin //ShowMessage('Inicialização do I: ' + IntToStr(i) + 'Inicialização do Quantidade de Campos: ' + edtquantidadecampos.Text); strNomeCampo := 'edtCampo' + IntToStr(ContadorCampo); intAlturaTop := intAlturaTop + 26; //=====Criação do nome do campo em tempo real EditCampoTempoReal := TEdit.Create(nil); EditCampoTempoReal.Parent := ScrollBox1; EditCampoTempoReal.Height := 23; EditCampoTempoReal.Width := 192; EditCampoTempoReal.Top := intAlturaTop; EditCampoTempoReal.Left := 8; EditCampoTempoReal.Name := strNomeCampo; EditCampoTempoReal.Caption := ''; EditCampoTempoReal.CharCase := ecLowerCase; EditCampoTempoReal.MaxLength := 20; EditCampoTempoReal.TabOrder := 3; Memo1.Lines.Add(strNomeCampo + ' Altura: ' + IntToStr(EditCampoTempoReal.Top)); //=====Criação do Tipo de variável em tempo real strNomeCampo := 'cmbVariavel' + IntToStr(ContadorCampo); cmbVariavelTempoReal := TComboBox.Create(nil); cmbVariavelTempoReal.Parent := ScrollBox1; cmbVariavelTempoReal.Left := 216; cmbVariavelTempoReal.Height := 23; cmbVariavelTempoReal.Top := intAlturaTop; cmbVariavelTempoReal.Width := 176; cmbVariavelTempoReal.Name := strNomeCampo; cmbVariavelTempoReal.Caption := ''; cmbVariavelTempoReal.ItemHeight := 15; cmbVariavelTempoReal.Items.Add('VARCHAR'); cmbVariavelTempoReal.Items.Add('INT'); cmbVariavelTempoReal.Items.Add('DECIMAL'); cmbVariavelTempoReal.Items.Add('BLOB'); cmbVariavelTempoReal.Items.Add('LONGTEXT'); cmbVariavelTempoReal.Items.Add('DATE'); cmbVariavelTempoReal.Items.Add('TIMESTAMP'); cmbVariavelTempoReal.ItemIndex := 0; Memo1.Lines.Add(strNomeCampo + ' Altura: ' + IntToStr(cmbVariavelTempoReal.Top)); I := I + 1; ContadorCampo := ContadorCampo + 1; End; edtContadorCampo.Text := IntToStr(ContadorCampo); edtContadorAlturaTop.Text := IntTostr(intAlturaTop); end; procedure TfrmInstaladorSistema.PageControl1Change(Sender: TObject); begin end; end.
unit QExport4DBFPATCH; {$I QExport4VerCtrl.inc} interface uses QExport4, Classes, SysUtils, QExport4IniFiles; const dBaseIII = $03; dBaseIIIMemo = $83; dBaseIVMemo = $8B; dBaseIVSQL = $63; FoxPro = $05; FoxProMemo = $F5; dftString = 'C'; // char (symbol(s)) dftBoolean = 'L'; // boolean dftNumber = 'N'; // number dftDate = 'D'; // date dftMemo = 'M'; // memo dftFloat = 'F'; // float -- not in DBaseIII MAX_FIELD_NAME_LEN = 10; type TFieldName = array [1 .. MAX_FIELD_NAME_LEN] of AnsiChar; TDBFHeader = packed record { *** First record *** L=32 } { +0 } DBType, { +1 } Year, { +2 } Month, { +3 } Day: Byte; { +4 } RecCount: LongInt; { +8 } HeaderSize: Word; { +10 } RecordSize: LongInt; { +14 } FDelayTrans: Byte; { +15 } Reserve2: array [1 .. 13] of Byte; { +28 } FlagMDX: Byte; { +29 } Reserve3: array [1 .. 3] of Byte; end; PDBFFieldDescriptor = ^TDBFFieldDescriptor; TDBFFieldDescriptor = packed record { *** Field Descriptor *** L= 32 } { +0 } FieldName: TFieldName; (* dee {+10} FieldEnd: Char; {+11} FieldType: Char; *) { +10 } FieldEnd: AnsiChar; { +11 } FieldType: AnsiChar; { +12 } FieldDisp: LongInt; { +16 } FieldLen, { +17 } FieldDec: Byte; { +18 } A1: array [1 .. 13] of Byte; { +31 } FlagTagMDX: Byte; end; // TMemoType = (mtNone, mtDBT, mtFPT); TQExport4DBF = class; TQDBFWriter = class(TQExportWriter) private DBFHeader: TDBFHeader; DList: TList; {$IFDEF QE_UNICODE} FExportCharsetType: TQExportCharsetType; {$ENDIF} MemoStream: TFileStream; MemoRecord: PByteArray; NextMemoRecord: integer; function GetDBFExport: TQExport4DBF; protected property DBFExport: TQExport4DBF read GetDBFExport; public constructor Create(AOwner: TQExport4; AStream: TStream); override; destructor Destroy; override; procedure AddFieldDef(Descriptor: PDBFFieldDescriptor); procedure CreateDBF; procedure DestroyDBF; {$IFDEF VCL12} procedure WriteData(Num: integer; const AData: string); {$ELSE} procedure WriteData(Num: integer; const Data: string); {$ENDIF} function WriteMemo(Index: integer): integer; {$IFDEF QE_UNICODE} property ExportCharsetType: TQExportCharsetType read FExportCharsetType write FExportCharsetType; {$ENDIF} end; TQExport4DBF = class(TQExport4Text) private FColumnsPrecision: TStrings; FOldDecimalSeparator: char; FDefaultFloatSize: integer; FDefaultFloatDecimal: integer; FExportTimeAsStr: Boolean; function GetMemoFileName: string; function GetNullValue: string; procedure SetNullValue(const Value: string); procedure SetColumnsPrecision(Value: TStrings); procedure GetColumnSizeDecimal(const ColumnName: string; var Size, Decimal: integer); protected function GetWriterClass: TQExportWriterClass; override; function GetWriter: TQDBFWriter; procedure BeginExport; override; procedure EndExport; override; procedure BeforeExport; override; procedure AfterExport; override; procedure WriteDataRow; override; procedure SaveProperties(IniFile: TQIniFile); override; procedure LoadProperties(IniFile: TQIniFile); override; property MemoFileName: string read GetMemoFileName; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Captions; property ColumnsLength; property ColumnsPrecision: TStrings read FColumnsPrecision write SetColumnsPrecision; property DefaultFloatSize: integer read FDefaultFloatSize write FDefaultFloatSize default 15; property DefaultFloatDecimal: integer read FDefaultFloatDecimal write FDefaultFloatDecimal default 4; property ExportTimeAsStr: Boolean read FExportTimeAsStr write FExportTimeAsStr; property NullValue: string read GetNullValue write SetNullValue; end; TShortFieldNameGenerator = class private FFieldNames: TStringList; function GetNumberString(const AValue: integer): string; function IncNumberString(const AValue: string): string; public constructor Create; destructor Destroy; override; function GetShortFieldName(AFieldName: string): string; end; implementation uses QExport4Common, DB, QExport4Types{$IFDEF VCL9}, Windows{$ENDIF}, Math; { TQDBFWriter } procedure TQDBFWriter.AddFieldDef(Descriptor: PDBFFieldDescriptor); begin DList.Add(Descriptor); end; constructor TQDBFWriter.Create(AOwner: TQExport4; AStream: TStream); begin inherited; DList := TList.Create; end; procedure TQDBFWriter.CreateDBF; var B: Byte; I: integer; Y, M, D: Word; begin FillChar(DBFHeader, 32, #0); DecodeDate(Date, Y, M, D); with DBFHeader do begin if (Owner as TQExport4DBF).Columns.ContainsBLOB and (Stream is TFileStream) then begin DBType := dBaseIIIMemo; MemoStream := TFileStream.Create((Owner as TQExport4DBF).MemoFileName, fmCreate); GetMem(MemoRecord, 512); FillChar(MemoRecord^, 512, #0); MemoStream.WriteBuffer(MemoRecord^, 512); NextMemoRecord := 1; end else DBType := dBaseIII; Year := Y - 2000; Month := M; Day := D; HeaderSize := (DList.Count + 1) * 32 + 1; RecordSize := 1; for I := 0 to DList.Count - 1 do RecordSize := RecordSize + PDBFFieldDescriptor(DList[I])^.FieldLen; end; Stream.WriteBuffer(DBFHeader, SizeOf(DBFHeader)); for I := 0 to DList.Count - 1 do Stream.WriteBuffer(PDBFFieldDescriptor(DList[I])^, 32); B := $0D; // End of DBF Header Stream.WriteBuffer(B, SizeOf(B)); end; destructor TQDBFWriter.Destroy; var I: integer; begin for I := 0 to DList.Count - 1 do if Assigned(DList.Items[I]) then Dispose(PDBFFieldDescriptor(DList.Items[I])); DList.Free; inherited; end; procedure TQDBFWriter.DestroyDBF; begin if Assigned(MemoStream) then begin MemoStream.Seek(0, soFromBeginning); MemoStream.Write(NextMemoRecord, SizeOf(integer)); MemoStream.Free; end; end; function TQDBFWriter.GetDBFExport: TQExport4DBF; begin Result := Owner as TQExport4DBF; end; {$IFDEF VCL12} procedure TQDBFWriter.WriteData(Num: integer; const AData: string); {$ELSE} procedure TQDBFWriter.WriteData(Num: integer; const Data: string); {$ENDIF} {$IFDEF QE_UNICODE} procedure WriteUsingCharset(WS: WideString); var s: AnsiString; begin if not Assigned(Owner) then Exit; if WS = EmptyStr then Exit; case ExportCharsetType of ectLocalANSI, ectLocalOEM, ectLocalMAC: begin s := WideStringToString(WS, integer(ExportCharsetType)); if length(s) > length(WS) then SetLength(s, length(WS)); Stream.WriteBuffer(s[1], length(s)); end; ectUTF8: begin s := UTF8Encode(WS); if length(s) > length(WS) then SetLength(s, length(WS)); Stream.WriteBuffer(s[1], length(s)); end; end; end; {$ENDIF} const NewRecordMarker: Byte = $20; STrue = 'TRUE'; SFalse = 'FALSE'; SDBFTrue = 'T'; SDBFFalse = 'F'; var CurPos, RCount: integer; {$IFDEF VCL12} Data: AnsiString; {$ENDIF} _Data: AnsiString; DD: TDateTime; begin {$IFDEF VCL12} Data := AnsiString(AData); {$ENDIF} SetLength(_Data, PDBFFieldDescriptor(DList[Num])^.FieldLen); FillChar(_Data[1], length(_Data), ' '); if string(Data) <> EmptyStr then begin case PDBFFieldDescriptor(DList[Num])^.FieldType of dftString: if length(Data) > 254 // !!! then Move(Data[1], _Data[1], 254) // !!! else Move(Data[1], _Data[1], length(Data)); dftNumber: begin Move(Data[1], _Data[Max(length(_Data) - length(Data) + 1, 1)], length(Data)); end; dftDate: begin DD := StrToDateTime(string(Data)); _Data := AnsiString(FormatDateTime('yyyymmdd', DD)); if string(_Data) = EmptyStr then begin SetLength(_Data, 8); FillChar(_Data[1], 8, ' '); end; end; dftBoolean: begin if Pos(STrue, UpperCase(string(Data))) > 0 then _Data[1] := SDBFTrue else if Pos(SFalse, UpperCase(string(Data))) > 0 then _Data[1] := SDBFFalse else _Data[1] := ' '; end; end; end; if Num = 0 then begin Stream.WriteBuffer(NewRecordMarker, 1); // it's new record // update record count CurPos := Stream.Position; // save current position Stream.Position := 4; Stream.ReadBuffer(RCount, 4); Inc(RCount); Stream.Position := 4; Stream.WriteBuffer(RCount, 4); Stream.Position := CurPos; // restore current position end; {$IFDEF QE_UNICODE} WriteUsingCharset(string(_Data)); // alex c - используется локальная функция, иначе при перекодировке идет смещение поля {$ELSE} write(_Data); {$ENDIF} RCount := length(_Data); if RCount = 0 then SysUtils.Beep; end; function TQDBFWriter.WriteMemo(Index: integer): integer; var Field: TField; FieldBuffer: TMemoryStream; Size, Position: integer; Finish: Byte; begin Result := -1; if not((Owner as TQExport4DBF).ExportSource in [esDataSet, esDBGrid]) then Exit; Field := nil; case (Owner as TQExport4DBF).ExportSource of esDataSet: Field := DBFExport.DataSet.FindField(DBFExport.Columns.Items[index].Name); {$IFNDEF NOGUI} esDBGrid: Field := DBFExport.DBGrid.DataSource.DataSet.FindField (DBFExport.Columns[index].Name); {$ENDIF} end; if not Assigned(Field) or not(Field is TBlobField) then Exit; Size := (Field as TBlobField).BlobSize; if (Size <= 0) or (Size > 65536) then Exit; FieldBuffer := TMemoryStream.Create; try {$IFDEF QE_UNICODE} {$IFDEF VER180} // temporary fix WriteToStreamUsingCharset(FieldBuffer, Field.AsWideString, ExportCharsetType); {$ELSE} (Field as TBlobField).SaveToStream(FieldBuffer); {$ENDIF} {$ELSE} (Field as TBlobField).SaveToStream(FieldBuffer); {$ENDIF} Finish := $1A; FieldBuffer.WriteBuffer(Finish, SizeOf(Byte)); FieldBuffer.WriteBuffer(Finish, SizeOf(Byte)); FieldBuffer.Position := 0; Result := NextMemoRecord; while (FieldBuffer.Size - FieldBuffer.Position) > 512 do begin FillChar(MemoRecord^, 512, #0); FieldBuffer.ReadBuffer(MemoRecord^, 512); MemoStream.Write(MemoRecord^, 512); Inc(NextMemoRecord); end; Size := FieldBuffer.Size; Position := FieldBuffer.Position; if (Size - Position) > 0 then begin FillChar(MemoRecord^, 512, #0); FieldBuffer.ReadBuffer(MemoRecord^, Size - Position); MemoStream.WriteBuffer(MemoRecord^, 512); Inc(NextMemoRecord); end; finally FieldBuffer.Free; end; end; { TQExport4DBF } constructor TQExport4DBF.Create(AOwner: TComponent); begin inherited; FColumnsPrecision := TStringList.Create; FDefaultFloatSize := 15; FDefaultFloatDecimal := 4; Formats.NullString := S_NULL_STRING; {$IFDEF QE_UNICODE} CharsetType := ectLocalANSI; {$ENDIF} end; destructor TQExport4DBF.Destroy; begin FColumnsPrecision.Free; inherited; end; procedure TQExport4DBF.AfterExport; begin SysUtils.FormatSettings.DecimalSeparator := FOldDecimalSeparator; inherited; end; procedure TQExport4DBF.BeforeExport; begin inherited; FOldDecimalSeparator := SysUtils.FormatSettings.DecimalSeparator; SysUtils.FormatSettings.DecimalSeparator := '.'; end; procedure TQExport4DBF.BeginExport; var sfnGen: TShortFieldNameGenerator; I, CurrDisp: integer; FD: PDBFFieldDescriptor; str: string; s, D: integer; begin inherited; CurrDisp := 0; sfnGen := TShortFieldNameGenerator.Create; try for I := 0 to Columns.Count - 1 do begin // if Columns[i].IsBlob and not Columns[i].IsMemo then Continue; New(FD); FillChar(FD^, 32, #0); str := GetColCaption(I); if length(str) > 10 then str := sfnGen.GetShortFieldName(str); Move(AnsiString(UpperCase(str))[1], FD^.FieldName, length(str)); FD^.FieldEnd := #0; if Columns[I].IsBlob then begin FD^.FieldType := dftMemo; FD^.FieldLen := 10; FD^.FieldDec := 0; end else begin case Columns[I].ColType of ectInteger: begin FD^.FieldType := dftNumber; FD^.FieldLen := 11; FD^.FieldDec := 0; end; ectBigint: begin FD^.FieldType := dftNumber; FD^.FieldLen := 20; FD^.FieldDec := 0; end; (* ftInteger, ftAutoInc: begin FD^.FieldType := dftNumber; FD^.FieldLen := 11; FD^.FieldDec := 0; end; ftSmallint: begin FD^.FieldType := dftNumber; FD^.FieldLen := 6; FD^.FieldDec := 0; end; ftWord: begin FD^.FieldType := dftNumber; FD^.FieldLen := 5; FD^.FieldDec := 0; end; *) ectString: begin FD^.FieldType := dftString; if Columns[I].length > 254 then FD^.FieldLen := 254 else FD^.FieldLen := Columns[I].length; FD^.FieldDec := 0; end; (* ftString{$IFDEF VCL4}, ftWideString{$ENDIF}: begin FD^.FieldType := dftString; if Dataset.Fields[I].Size > 254 then FD^.FieldLen := 254 else FD^.FieldLen := Dataset.Fields[I].Size - 1; FD^.FieldDec := 0; end; *) ectFloat, ectCurrency: begin s := FDefaultFloatSize; D := FDefaultFloatDecimal; GetColumnSizeDecimal(Columns[I].Name, s, D); FD^.FieldType := dftNumber; FD^.FieldLen := s; FD^.FieldDec := D; end; ectDate, ectTime, ectDateTime: begin if ExportTimeAsStr and (Columns[I].ColType in [ectTime, ectDateTime]) then begin FD^.FieldType := dftString; if not Columns[I].length > 25 then FD^.FieldLen := Columns[I].length else FD^.FieldLen := 25; Columns[I].ColType := ectString; FD^.FieldDec := 0; end else begin FD^.FieldType := dftDate; FD^.FieldLen := 8; FD^.FieldDec := 0; end; end; ectBoolean: begin FD^.FieldType := dftBoolean; FD^.FieldLen := 1; FD^.FieldDec := 0; end else begin FD^.FieldType := dftString; FD^.FieldLen := 50; // 10; igorp при неопознанных > 10 (например GUID) вываливается AV FD^.FieldDec := 0; end; end; end; FD^.FieldDisp := CurrDisp; CurrDisp := CurrDisp + FD^.FieldLen; GetWriter.AddFieldDef(FD); end; finally sfnGen.Free; end; GetWriter.CreateDBF; end; procedure TQExport4DBF.EndExport; begin GetWriter.Write(Chr($1A)); GetWriter.DestroyDBF; inherited; end; function TQExport4DBF.GetMemoFileName: string; begin Result := ChangeFileExt(FileName, '.dbt'); end; function TQExport4DBF.GetNullValue: string; begin Result := Formats.NullString; end; procedure TQExport4DBF.SetNullValue(const Value: string); begin if Formats.NullString <> Value then Formats.NullString := Value; end; procedure TQExport4DBF.SetColumnsPrecision(Value: TStrings); begin FColumnsPrecision.Assign(Value); end; procedure TQExport4DBF.GetColumnSizeDecimal(const ColumnName: string; var Size, Decimal: integer); var j: integer; str: string; begin Size := FDefaultFloatSize; Decimal := FDefaultFloatDecimal; if ColumnName = 'CURRATE' then begin Size := 12; Decimal := 5; end; if ColumnName = 'REMINDLEV' then begin Size := 1; Decimal := 0; end; j := FColumnsPrecision.IndexOfName(ColumnName); if j > -1 then begin str := FColumnsPrecision.Values[FColumnsPrecision.Names[j]]; j := Pos(',', str); if j > 0 then begin Size := StrToIntDef(Copy(str, 1, j - 1), 0); Decimal := StrToIntDef(Copy(str, j + 1, length(str) - j), 0); if (Size <= 0) and (Decimal <= 0) then begin Size := FDefaultFloatSize; Decimal := FDefaultFloatDecimal; end; end; end; end; function TQExport4DBF.GetWriter: TQDBFWriter; begin Result := TQDBFWriter(inherited GetWriter); end; function TQExport4DBF.GetWriterClass: TQExportWriterClass; begin Result := TQDBFWriter; end; procedure TQExport4DBF.LoadProperties(IniFile: TQIniFile); begin inherited; with IniFile do begin ColumnsLength.Clear; ReadSectionValues(S_LENGTH, ColumnsLength); end; end; procedure TQExport4DBF.SaveProperties(IniFile: TQIniFile); var I: integer; begin inherited; with IniFile do begin EraseSection(S_LENGTH); for I := 0 to ColumnsLength.Count - 1 do WriteString(S_LENGTH, Format('%s%d', [S_Line, I]), ColumnsLength[I]); end; end; procedure TQExport4DBF.WriteDataRow; var I, Address: integer; fmtstr, str: string; s, D: integer; begin for I := 0 to ExportRow.Count - 1 do begin // if Columns[i].IsBlob and not Columns[i].IsMemo then Continue; // alex c {$IFDEF QE_UNICODE} TQDBFWriter(GetWriter).ExportCharsetType := CharsetType; {$ENDIF} str := GetExportedValue(ExportRow[I]); if AnsiCompareText(str, 'null') = 0 then str := EmptyStr; if Columns[I].ColType in [ectFloat, ectCurrency] then begin if str = EmptyStr then begin str := Formats.NullString; GetWriter.WriteData(I, str); end else begin s := FDefaultFloatSize; D := FDefaultFloatDecimal; GetColumnSizeDecimal(ExportRow[I].Name, s, D); fmtstr := Format('%%%d.%df', [s, D]); str := ExportRow[I].Data; str := Format(fmtstr, [StrToFloat(str)]); { [ExportRow[i].Data] - Format '%15.4f' invalid or incompatible with argument } if Pos(',', str) > 0 then str := Replace(str, ',', '.'); GetWriter.WriteData(I, str) end; end else if Columns[I].IsBlob then begin if (GetWriter.Stream is TFileStream) then begin Address := GetWriter.WriteMemo(I); str := ' '; if Address > -1 then begin str := IntToStr(Address); while length(str) < 10 do str := ' ' + str; end; GetWriter.Stream.Write(str[1], 10); end end else GetWriter.WriteData(I, str); end; end; { TShortFieldNameGenerator } constructor TShortFieldNameGenerator.Create; begin inherited; FFieldNames := TStringList.Create; FFieldNames.Sorted := True; FFieldNames.Duplicates := dupIgnore; end; destructor TShortFieldNameGenerator.Destroy; begin FFieldNames.Free; inherited; end; function TShortFieldNameGenerator.GetNumberString(const AValue : integer): string; begin Result := Format('~%d', [AValue]); end; function TShortFieldNameGenerator.GetShortFieldName(AFieldName: string): string; var I: integer; ns: string; begin Delete(AFieldName, MAX_FIELD_NAME_LEN + 1, MaxInt); Result := AFieldName; if FFieldNames.Find(AFieldName, I) then begin FFieldNames.Objects[I] := TObject(integer(FFieldNames.Objects[I]) + 1); ns := GetNumberString(integer(FFieldNames.Objects[I])); Delete(AFieldName, MAX_FIELD_NAME_LEN - length(ns) + 1, length(ns)); Result := AFieldName + ns; if FFieldNames.Find(Result, I) then Result := IncNumberString(Result); FFieldNames.AddObject(Result, TObject(0)); end else FFieldNames.AddObject(AFieldName, TObject(0)); end; function TShortFieldNameGenerator.IncNumberString(const AValue: string): string; var p, n: integer; s, ns: string; begin Result := AValue; p := Pos('~', AValue); if p = 0 then Exit; s := Copy(AValue, p + 1, MaxInt); n := StrToIntDef(s, -1); if n = -1 then Exit; Inc(n); ns := GetNumberString(n); Delete(Result, MAX_FIELD_NAME_LEN - length(ns) + 1, length(ns)); Result := Result + ns; end; end.
{ C = [5 * (F - 32)] / 9 } Program FahrenheitToCelsius (input, output); { Übersetzt Fahrenheit in Celsius. } var Fahrenheit : integer; Celsius : real; begin writeln('Bitte geben Sie eine Temperatur in Fahrenheit an. '); readln(Fahrenheit); writeln('Diese Temperatur enspricht in Celsius: '); Celsius := (5 * (Fahrenheit - 32)) / 9; writeln(Celsius); end. { FahrenheitToCelsius }
unit LuaTableFile; {$mode delphi} interface uses Classes, SysUtils,lua, lauxlib, lualib; procedure initializeLuaTableFile; implementation uses LuaClass, LuaHandler, LuaObject, MainUnit, luafile; resourcestring rsErrorRaisedWithMessage = ' error raised with message: '; rsTableDileEntryAlreadyExistsForFilename = 'Table file entry already exists for filename: '; rsCreateTableFileRequiresAtLeastOneParameter = 'createTableFile requires at least one parameter'; function indexOfLuaFileByName(filename: string; internal: boolean=false): integer; var i: integer; luaFiles: TLuaFileList; begin if internal then luaFiles:=mainForm.InternalLuaFiles else luaFiles:=mainform.LuaFiles; result:=-1; for i:=0 to luaFiles.count-1 do if luaFiles[i].name=filename then begin result:=i; break; end; end; function pushLuaTableFile(L: Plua_State; index: integer; internal: boolean=false): integer; var lf: TLuafile; s: TMemoryStream; begin if internal then lf:=MainForm.InternalLuaFiles[index] else lf:=MainForm.LuaFiles[index]; s:=lf.stream; s.Position:=0; result:=1; luaclass_newClass(L, lf); end; function addLuaTableFile(L: Plua_State; filename: string; filepath: string=''): integer; var i: integer; lf: TLuafile; s: TMemoryStream; begin result:=0; if (indexOfLuaFileByName(filename)=-1) and (indexOfLuaFileByName(filename, true)=-1) then begin try s:=TMemorystream.Create; try if filepath<>'' then s.LoadFromFile(filepath); lf:=TLuaFile.Create(filename, s); finally s.Free; end; i:=mainform.LuaFiles.add(lf); result:=pushLuaTableFile(L, i); mainform.editedsincelastsave:=true; except on e : Exception do begin lua_pushstring(L, e.className + rsErrorRaisedWithMessage + e.message); lua_error(L); end; end; end else begin lua_pushstring(L, rsTableDileEntryAlreadyExistsForFilename + filename); lua_error(L); end; end; function createTableFile(L: Plua_State): integer; cdecl; var parameters: integer; filename, filepath: string; begin result:=0; parameters:=lua_gettop(L); if parameters>=1 then begin filepath:=''; filename:=Lua_ToString(L, 1); if parameters>=2 then filepath:=Lua_ToString(L, 2); result:=addLuaTableFile(L, filename, filepath); end else begin lua_pushstring(L, rsCreateTableFileRequiresAtLeastOneParameter); lua_error(L); end; end; function findTableFile(L: Plua_State): integer; cdecl; var parameters: integer; f: string; i: integer; begin result:=0; parameters:=lua_gettop(L); if parameters>=1 then begin f:=Lua_ToString(L, -1); lua_pop(L, lua_gettop(L)); i:=indexOfLuaFileByName(f); if i<>-1 then result:=pushLuaTableFile(L, i) //return the tableFile, not the stream. To get the stream, use tablefile_getData else begin i:=indexOfLuaFileByName(f, true); //internal file if i<>-1 then result:=pushLuaTableFile(L, i, true); end; end else lua_pop(L, lua_gettop(L)); end; function tablefile_delete(L: Plua_State): integer; cdecl; var lf: TLuaFile; begin result:=0; lf:=luaclass_getClassObject(L); mainform.LuaFiles.Remove(lf); mainform.UpdateMenu; lf.Free; mainform.editedsincelastsave:=true; end; function tablefile_saveToFile(L: Plua_State): integer; cdecl; var lf: TLuaFile; f: string; begin result:=0; lf:=luaclass_getClassObject(L); f:=lf.name; if lua_gettop(L)>=1 then f:=Lua_ToString(L, 1); lf.stream.Position:=0; lf.stream.SaveToFile(f); end; function tablefile_getData(L: Plua_State): integer; cdecl; var lf: TLuaFile; begin result:=1; lf:=luaclass_getClassObject(L); luaclass_newClass(L, lf.stream); end; procedure tablefile_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'delete', tablefile_delete); luaclass_addClassFunctionToTable(L, metatable, userdata, 'saveToFile', tablefile_saveToFile); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getData', tablefile_getData); end; procedure initializeLuaTableFile; begin Lua_register(LuaVM, 'createTableFile', createTableFile); Lua_register(LuaVM, 'findTableFile', findTableFile); Lua_register(LuaVM, 'tablefile_delete', tablefile_delete); Lua_register(LuaVM, 'tablefile_saveToFile', tablefile_saveToFile); Lua_register(LuaVM, 'tablefile_getData', tablefile_getData); end; initialization luaclass_register(TLuafile, tablefile_addMetaData); end.
unit View.Board; interface type IBoardView = interface ['{8734291B-DA8D-4569-8AEC-A9741DE778B7}'] procedure DrawBoard; procedure DrawItem(AIndex: Integer); function CountVisibleItems: Integer; end; implementation end.
unit LayoutManagerReg; interface uses Classes, LayoutManager, DesignEditors, DesignIntf; type TLayoutManagerTabOrder = class(TComponentEditor) public procedure Edit; override; procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): string; override; function GetVerbCount: Integer; override; end; procedure Register; implementation uses TabOrderForm; procedure Register; begin RegisterComponents('Infra', [TLayoutManager]); RegisterComponentEditor(TLayoutManager, TLayoutManagerTabOrder); RegisterClasses([TLayoutManagerItem]); end; { TLayoutManagerTabOrder } procedure TLayoutManagerTabOrder.Edit; begin ExecuteVerb(0); end; procedure TLayoutManagerTabOrder.ExecuteVerb(Index: Integer); var TabOrderForm: TTabOrderForm; begin if Index = 0 then begin TabOrderForm := TTabOrderForm.Create(nil); try TabOrderForm.ItemList := (Component as TLayoutManager).ItemList; if TabOrderForm.Execute then (Component as TLayoutManager).ResizeItems; finally TabOrderForm.Free; end; end; end; function TLayoutManagerTabOrder.GetVerb(Index: Integer): string; begin case Index of 0: Result := 'Edit Item Order'; end; end; function TLayoutManagerTabOrder.GetVerbCount: Integer; begin Result := 1; end; end.
unit texteditor; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Menus, ShellAPI, ExtCtrls; type TMDITextEditor = class(TForm) MainMenu1: TMainMenu; Document1: TMenuItem; Save: TMenuItem; N2: TMenuItem; ExternalOpen: TMenuItem; Delete: TMenuItem; N4: TMenuItem; DocumentClose1: TMenuItem; Memo1: TMemo; AutoSaveTimer: TTimer; procedure DocumentClose1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure SaveClick(Sender: TObject); procedure DeleteClick(Sender: TObject); procedure ExternalOpenClick(Sender: TObject); procedure Memo1Change(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure AutoSaveTimerTimer(Sender: TObject); private fcat: string; fprefix: string; fautosave: boolean; changed: boolean; function DoSave: boolean; procedure UpdateCaption; public property folder: string read fprefix; property cat: string read fcat; property autosave: boolean read fautosave; constructor Create(AOwner: TComponent; Folder, Category: string); reintroduce; end; var MDITextEditor: TMDITextEditor; implementation {$R *.dfm} uses main, categories, global; constructor TMDITextEditor.Create(AOwner: TComponent; Folder, Category: string); begin inherited Create(AOwner); fautosave := true; fcat := category; fprefix := MyAddTrailingPathDelimiter(folder); end; procedure TMDITextEditor.DeleteClick(Sender: TObject); var fn: string; i: integer; begin fn := getTextFileName(folder, cat); if commonDelete(fn) then begin Close; // TODO: Eigentlich sollte das innerhalb von commonDelete() stattfinden for i := Screen.FormCount - 1 downto 0 do begin if Screen.Forms[i] is TMDICategories then begin TMDICategories(Screen.Forms[i]).DeleteNode(folder, cat); end end; end; end; procedure TMDITextEditor.DocumentClose1Click(Sender: TObject); begin Close; end; function TMDITextEditor.DoSave: boolean; begin //if changed then //begin result := true; AddToJournal(Format(lng_jnl_textchange, [folder + cat])); try Memo1.Lines.SaveToFile(getTextFileName(folder, cat)); except result := false; end; changed := false; AutoSaveTimer.Enabled := false; UpdateCaption; //end //else result := true; end; procedure TMDITextEditor.ExternalOpenClick(Sender: TObject); var fn: string; begin fn := getTextFileName(folder, cat); commonExternalOpen(fn); end; procedure TMDITextEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TMDITextEditor.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var userResponse: integer; begin if changed then begin if not AUTOSAVE then begin BringToFront; WindowState := wsNormal; userResponse := MessageDlg(Format(lng_savefirst, [folder + cat]), mtConfirmation, mbYesNoCancel, 0); case userResponse of idYes: CanClose := DoSave; idNo: CanClose := true; idCancel: begin CanClose := false; Exit; end; end; end else CanClose := DoSave; end; end; procedure TMDITextEditor.FormShow(Sender: TObject); begin Memo1.Lines.Clear; Memo1.Lines.LoadFromFile(getTextFileName(folder, cat)); changed := false; AutoSaveTimer.Enabled := false; UpdateCaption; Memo1.SetFocus; end; procedure TMDITextEditor.Memo1Change(Sender: TObject); begin changed := true; AutoSaveTimer.Enabled := true; UpdateCaption; end; procedure TMDITextEditor.SaveClick(Sender: TObject); begin DoSave; end; procedure TMDITextEditor.AutoSaveTimerTimer(Sender: TObject); begin if AUTOSAVE and Changed then begin DoSave; end; end; procedure TMDITextEditor.UpdateCaption; var capname: string; begin capname := Format(lng_texteditor_title, [folder + cat]); if changed then capname := capname + ' *'; if Caption <> capname then Caption := capname; // Kein Aufblitzen end; end.
unit uFtpHandler; interface uses Classes, uTcpHandler, IdExplicitTLSClientServerBase, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP; type // ftp handler TFtpHandler = class(TDefaultTcpHandler, ITcpHandler) private fFtp: TIdFTP; public constructor Create(host: String; port: Integer; uid, pwd: String); destructor Destroy; override; procedure ChangeWorkingDir(dir: String); procedure SendFile(localFile: TTcpLocalFile); override; end; implementation { TCar } procedure TFtpHandler.ChangeWorkingDir(dir: String); begin if fFtp.Connected then fFtp.ChangeDir(dir); end; constructor TFtpHandler.Create(host: String; port: Integer; uid, pwd: String); begin fFtp:= TIdFTP.Create(nil); fFtp.Host:= host; fFtp.Port:= port; fFtp.Username:= uid; fFtp.Password:= pwd; fFtp.Connect; end; destructor TFtpHandler.Destroy; begin try if fFtp.Connected then fFtp.Quit; finally fFtp.Free; end; inherited; end; procedure TFtpHandler.SendFile(localFile: TTcpLocalFile); var stream: TStream; begin stream:= localFile.CreateStream(); try fFtp.Put(stream, localFile.name); finally stream.Free; end; end; end.
{ Encoder / Decoder Base64 } unit Xe_EDBase64; interface { Base64encode Base64decode Base64URLencode } function Base64encode(const Data: PAnsiChar; const DataSize: integer): AnsiString; function Base64URLencode(const Data: PAnsiChar; const DataSize: integer): AnsiString; function Base64decode(const Data: PAnsiChar; const DataSize: integer): AnsiString; implementation const Base64Table : array[0..63] of AnsiChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64URLTable : array[0..63] of AnsiChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; b64FillChar = '='; b64Mask1 = $FC000000; b64Mask2 = $03F00000; b64Mask3 = $000FC000; b64Mask4 = $00003F00; type PBytes = ^TBytes; TBytes = packed array[0..0] of byte; b64IntChar = packed record case integer of 0: (l : integer); 1: (c : array[0..3] of AnsiChar); end; const _FI1 : packed array['A'..'Z'] of byte = (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25); _FI2 : packed array['a'..'z'] of byte = (26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51); _FI3 : packed array['0'..'9'] of byte = (52,53,54,55,56,57,58,59,60,61); function FastIndexOf(const C: AnsiChar): integer; begin case byte(C) of $2B,$2D {+-} : result := 62; $2F,$5F {/_} : result := 63; $30..$39 {'0'..'9'} : result := _FI3[C]; $41..$5A {'A'..'Z'} : result := _FI1[C]; $61..$7A {'a'..'z'} : result := _FI2[C]; end; end; function Base64encode(const Data: PAnsiChar; const DataSize: integer): AnsiString; var trail, sz, i, k : integer; b64 : b64IntChar; pR : PAnsiChar; begin sz := (DataSize div 3) shl 2; trail := DataSize mod 3; if trail <> 0 then inc(sz, 4); SetLength(result, sz); pR := PAnsiChar(result); i := 0; k := 0; while (i < (DataSize-trail)) do begin b64.c[3] := Data[i]; b64.c[2] := Data[i+1]; b64.c[1] := Data[i+2]; inc(i, 3); pR[k] := Base64Table[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64Table[(b64.l and b64Mask2) shr 20]; pR[k+2] := Base64Table[(b64.l and b64Mask3) shr 14]; pR[k+3] := Base64Table[(b64.l and b64Mask4) shr 8]; inc(k,4); end; b64.l := 0; case trail of 1 : begin b64.c[3] := Data[i]; pR[k] := Base64Table[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64Table[(b64.l and b64Mask2) shr 20]; pR[k+2] := b64FillChar; pR[k+3] := b64FillChar; end; 2 : begin b64.c[3] := Data[i]; b64.c[2] := Data[i+1]; pR[k] := Base64Table[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64Table[(b64.l and b64Mask2) shr 20]; pR[k+2] := Base64Table[(b64.l and b64Mask3) shr 14]; pR[k+3] := b64FillChar; end; end; end; function Base64URLencode(const Data: PAnsiChar; const DataSize: integer): AnsiString; var trail, sz, i, k : integer; b64 : b64IntChar; pR : PAnsiChar; begin sz := (DataSize div 3) shl 2; trail := DataSize mod 3; if trail <> 0 then inc(sz, 4); SetLength(result, sz); pR := PAnsiChar(result); i := 0; k := 0; while (i < (DataSize-trail)) do begin b64.c[3] := Data[i]; b64.c[2] := Data[i+1]; b64.c[1] := Data[i+2]; inc(i, 3); pR[k] := Base64URLTable[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64URLTable[(b64.l and b64Mask2) shr 20]; pR[k+2] := Base64URLTable[(b64.l and b64Mask3) shr 14]; pR[k+3] := Base64URLTable[(b64.l and b64Mask4) shr 8]; inc(k,4); end; b64.l := 0; case trail of 1 : begin b64.c[3] := Data[i]; pR[k] := Base64URLTable[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64URLTable[(b64.l and b64Mask2) shr 20]; pR[k+2] := b64FillChar; pR[k+3] := b64FillChar; end; 2 : begin b64.c[3] := Data[i]; b64.c[2] := Data[i+1]; pR[k] := Base64URLTable[(b64.l and b64Mask1) shr 26]; pR[k+1] := Base64URLTable[(b64.l and b64Mask2) shr 20]; pR[k+2] := Base64URLTable[(b64.l and b64Mask3) shr 14]; pR[k+3] := b64FillChar; end; end; end; function Base64decode(const Data: PAnsiChar; const DataSize: integer): AnsiString; var trail, szin, szout, i, k : integer; b64 : b64IntChar; pR : PAnsiChar; begin if Data[DataSize-1] = b64FillChar then begin if Data[DataSize-2] = b64FillChar then trail := 2 else trail := 1; end else trail := 0; if trail = 0 then szin := DataSize else szin := DataSize-4; szout := (szin shr 2) * 3; if Trail <> 0 then if Trail = 1 then inc(szout, 2) else inc(szout, 1); SetLength(result, szout); pR := PAnsiChar(result); i := 0; k := 0; while i < szin do begin b64.l := 0; b64.l := (FastIndexOf(Data[i]) shl 26) + (FastIndexOf(Data[i+1]) shl 20) + (FastIndexOf(Data[i+2]) shl 14) + (FastIndexOf(Data[i+3]) shl 8); inc(i, 4); pR[k] := b64.c[3]; pR[k+1] := b64.c[2]; pR[K+2] := b64.c[1]; inc(k, 3); end; b64.l := 0; case trail of 1 : begin b64.l := (FastIndexOf(Data[i]) shl 26) + (FastIndexOf(Data[i+1]) shl 20) + (FastIndexOf(Data[i+2]) shl 14); pR[k] := b64.c[3]; pR[K+1] := b64.c[2]; end; 2 : begin b64.l := (FastIndexOf(Data[i]) shl 26) + (FastIndexOf(Data[i+1]) shl 20); pR[k] := b64.c[3]; end; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, uParserPL0; type TForm1 = class(TForm) Memo1: TMemo; Memo2: TMemo; Splitter1: TSplitter; Panel1: TPanel; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Parser: TParserPL0; SrcStream: TMemoryStream; DstStream: TMemoryStream; begin Parser := TParserPL0.Create; SrcStream := TMemoryStream.Create; DstStream := TMemoryStream.Create; try Memo2.Clear; Memo1.Lines.SaveToStream(SrcStream); SrcStream.Seek(0,soFromBeginning); if not Parser.Execute(SrcStream,DstStream) then Memo2.Lines.Text := Parser.ErrorMsg else Memo2.Lines.Text := 'Parse complete :)'; finally Parser.Free; SrcStream.Free; DstStream.Free; end; end; end.
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ShellAPI, Dialogs, StdCtrls, ExtCtrls, PNGExtra, PNGImage, WImageButton, Imaging, WNineSlicesPanel, FileSystemUtils, WFileIcon, Menus, WComponent, WImage, MathUtils, Logger, IconPanel, xmldom, XMLIntf, msxmldom, XMLDoc, StringUtils, WNineSlicesButton; const Wm_CallBackMessage = wm_user + 1; APPLICATION_TITLE = 'Mini Launch Bar'; type TDragData = record dragging: Boolean; draggingType: String; startMousePos: TPoint; startWindowPos: TPoint; startPanelWidth: Integer; startPanelHeight: Integer; end; TOptionButtonDatum = class public ID: Integer; Name: String; IconFilePath: String; Separator: Boolean; SeparatorObject: TWNineSlicesPanel; end; TMainForm = class(TForm) trayIconPopupMenu: TPopupMenu; trayIconPopupMenuClose: TMenuItem; procedure FormCreate(Sender: TObject); procedure barBackground_down(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure barBackground_up(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure barBackground_move(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure UpdateLayout(); procedure arrowButton_click(sender: TObject); procedure OpenOptionPanel(); procedure OpenCloseOptionPanel(const iOpen: Boolean); procedure optionPanelAnimTimer_timer(sender: TObject); procedure SetOptionPanelWidth(const iWidth: Integer); procedure UpdateFormMask(); procedure ToggleOptionPanel(); procedure UpdateOptionPanel(); procedure optionButton_Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure trayIconPopupMenuCloseClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } resizer: TWImage; optionPanelOpen: Boolean; optionPanelAnimTimer: TTimer; optionPanelOpenWidth: Integer; optionPanelCloseWidth: Integer; optionPanelAnimationStartTime: Int64; optionPanelAnimationDuration: Int64; optionPanelCurrentWidth: Integer; optionButtons: Array of TWImageButton; optionButtonGap: Byte; optionButtonData: Array of TOptionButtonDatum; pOptionButtonDataID: Integer; pFirstShown: Boolean; pNotifyIconData : TNotifyIconData; procedure ShowPopupMenu(f : TForm; p : TPopupMenu); procedure AppHideInTrayIcon(sender: TObject); function OptionPanelTotalWidth():Word; function AddOptionButtonData():TOptionButtonDatum; function GetButtonDataByID(ID: Integer): TOptionButtonDatum; procedure UpdateOptionButtonsLayout(const cornerX, cornerY: Integer); procedure CalculateOptionPanelOpenWidth(); procedure barInnerPanel_Resize(Sender: TObject); function GetMaxWidth():Integer; function GetIconPanelMaxWidth(): Integer; procedure WMCallBackMessage(var msg : TMessage); message Wm_CallBackMessage; procedure Resizer_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Resizer_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Resizer_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); public { Public declarations } property MaxWidth: Integer read GetMaxWidth; property IconPanelMaxWidth: Integer read GetIconPanelMaxWidth; end; var theMainForm: TMainForm; barBackground: TWNineSlicesPanel; barInnerPanel: TIconPanel; optionPanel: TWNineSlicesPanel; arrowButton: TWNineSlicesButton; button: TWImageButton; windowDragData: TDragData; implementation {$R *.dfm} uses Main, DebugWindow; procedure TMainForm.Resizer_MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button <> mbLeft then Exit; ilog('Form resizing started'); mouse := TMouse.Create(); windowDragData.dragging := true; windowDragData.draggingType := 'resize'; windowDragData.startMousePos.X := mouse.CursorPos.X; windowDragData.startMousePos.Y := mouse.CursorPos.Y; windowDragData.startWindowPos.X := Left; windowDragData.startWindowPos.Y := Top; windowDragData.startPanelWidth := barInnerPanel.Width; windowDragData.startPanelHeight := barInnerPanel.Height; end; procedure TMainForm.Resizer_MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var newWidth, newHeight: Integer; begin if (windowDragData.dragging) and (windowDragData.draggingType = 'resize') then begin mouse := TMouse.Create(); barInnerPanel.Width := windowDragData.startPanelWidth + (mouse.CursorPos.X - windowDragData.startMousePos.X); barInnerPanel.Height := windowDragData.startPanelHeight + (mouse.CursorPos.y - windowDragData.startMousePos.Y); UpdateLayout(); Repaint(); end; end; procedure TMainForm.Resizer_MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button <> mbLeft then Exit; ilog('Dragging stopped'); windowDragData.dragging := false; end; procedure TMainForm.barBackground_down(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var mouse: TMouse; begin if Button <> mbLeft then Exit; ilog('Form dragging started'); mouse := TMouse.Create(); windowDragData.dragging := true; windowDragData.draggingType := 'move'; windowDragData.startMousePos.X := mouse.CursorPos.X; windowDragData.startMousePos.Y := mouse.CursorPos.Y; windowDragData.startWindowPos.X := Left; windowDragData.startWindowPos.Y := Top; end; procedure TMainForm.barBackground_up(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button <> mbLeft then Exit; ilog('Dragging stopped'); windowDragData.dragging := false; end; procedure TMainForm.barBackground_move(Sender: TObject; Shift: TShiftState; X, Y: Integer); var mouse: TMouse; begin if (windowDragData.dragging) and (windowDragData.draggingType = 'move') then begin mouse := TMouse.Create(); Left := windowDragData.startWindowPos.X + (mouse.CursorPos.X - windowDragData.startMousePos.X); Top := windowDragData.startWindowPos.Y + (mouse.CursorPos.Y - windowDragData.startMousePos.Y); end; end; procedure TMainForm.UpdateFormMask(); var bmp: TBitmap; region: THandle; rect: TRect; begin ilog('Updating form mask...'); if (csDestroying in ComponentState) then Exit; Width := barBackground.Width + OptionPanelTotalWidth; Height := barBackground.Height; bmp := TBitmap.Create(); try bmp.Width := Width; bmp.Height := Height; rect.Top := 0; rect.Left := 0; rect.Bottom := bmp.Height; rect.Right := bmp.Width; bmp.Canvas.Brush := TBrush.Create(); bmp.Canvas.Brush.Color := RGB(255, 0, 255); bmp.Canvas.FillRect(rect); DrawNineSlices(bmp.Canvas, TMain.Instance.FilePaths.SkinDirectory + '\BarBackgroundRegion', optionPanelOpenWidth - optionPanelCurrentWidth, 0, bmp.Width - optionPanelOpenWidth + optionPanelCurrentWidth, bmp.Height); region := CreateRegion(Bmp); SetWindowRGN(Handle, region, True); finally bmp.Free; end; end; function TMainForm.OptionPanelTotalWidth():Word; begin result := optionPanelOpenWidth + arrowButton.Width; end; procedure TMainForm.barInnerPanel_Resize; begin // if (csDestroying in ComponentState) then Exit; // // barBackground.Width := barInnerPanel.Width + TMain.instance.Style.barMainPanel.paddingH; // barBackground.Height := barInnerPanel.Height + TMain.instance.Style.barMainPanel.paddingV; // // barBackground.Left := OptionPanelTotalWidth; // // barInnerPanel.Left := TMain.instance.Style.barMainPanel.paddingLeft; // barInnerPanel.Top := TMain.instance.Style.barMainPanel.paddingTop; // // optionPanel.Height := barBackground.Height; // // UpdateOptionPanel(); // UpdateFormMask(); end; procedure TMainForm.UpdateLayout(); begin ilog('Updating layout...'); if (csDestroying in ComponentState) then Exit; barInnerPanel.UpdateLayout(); barBackground.Width := barInnerPanel.Width + TMain.instance.Style.barMainPanel.paddingH; barBackground.Height := barInnerPanel.Height + TMain.instance.Style.barMainPanel.paddingV; barBackground.Left := OptionPanelTotalWidth; barInnerPanel.Left := TMain.instance.Style.barMainPanel.paddingLeft; barInnerPanel.Top := TMain.instance.Style.barMainPanel.paddingTop; resizer.Left := barBackground.Width - resizer.Width; resizer.Top := barBackground.Height - resizer.Height; optionPanel.Height := barBackground.Height; UpdateOptionPanel(); UpdateFormMask(); end; function TMainForm.GetButtonDataByID(ID: Integer): TOptionButtonDatum; var i: Byte; begin result := nil; for i := 0 to Length(optionButtonData) - 1 do begin if optionButtonData[i].ID = ID then begin result := optionButtonData[i]; break; end; end; end; function TMainForm.GetIconPanelMaxWidth: Integer; begin result := MaxWidth; result := result - arrowButton.Width; result := result - TMain.Instance.Style.barMainPanel.paddingH; end; function TMainForm.GetMaxWidth: Integer; begin result := Screen.WorkAreaWidth; result := result - optionPanelOpenWidth - arrowButton.Width; end; procedure TMainForm.optionButton_Click(Sender: TObject); var d: TOptionButtonDatum; button: TWImageButton; begin button := sender as TWImageButton; d := GetButtonDataByID(button.Tag); if d = nil then Exit; ilog('Option button click: ' + d.Name); if d.Name = 'Close' then begin Close(); Exit; end; if d.Name = 'Eject' then begin TMain.Instance.EjectDrive(); Close(); Exit; end; end; procedure TMainForm.SetOptionPanelWidth(const iWidth: Integer); begin if iWidth = optionPanelCurrentWidth then Exit; optionPanelCurrentWidth := iWidth; UpdateOptionPanel(); UpdateFormMask(); end; procedure TMainForm.CalculateOptionPanelOpenWidth(); var buttonX: Integer; buttonData: TOptionButtonDatum; button: TWImageButton; i: Byte; vButtonCount: Integer; begin buttonX := 0; vButtonCount := 0; for i := 0 to Length(optionButtons) - 1 do begin button := optionButtons[i]; buttonData := GetButtonDataByID(button.Tag); if buttonData = nil then continue; if buttonData.Separator then begin buttonX := buttonX + optionButtons[i - 1].Width + optionButtonGap * 4; vButtonCount := 0; end else begin vButtonCount := vButtonCount + 1; if vButtonCount > 3 then begin buttonX := buttonX + button.Width + optionButtonGap; vButtonCount := 0; end; end; optionPanelOpenWidth := buttonX + button.Width; end; optionPanelOpenWidth := optionPanelOpenWidth + TMain.Instance.Style.OptionPanel.PaddingH; end; procedure TMainForm.trayIconPopupMenuCloseClick(Sender: TObject); begin Close(); end; procedure TMainForm.UpdateOptionButtonsLayout(const cornerX, cornerY: Integer); var buttonX, buttonY: Integer; buttonData: TOptionButtonDatum; button: TWImageButton; i: Byte; begin buttonX := cornerX; buttonY := cornerY; for i := 0 to Length(optionButtons) - 1 do begin button := optionButtons[i]; buttonData := GetButtonDataByID(button.Tag); if buttonData = nil then continue; if buttonData.Separator then begin buttonY := optionPanel.Top + TMain.Instance.Style.OptionPanel.PaddingTop; buttonData.SeparatorObject.Left := buttonX + optionButtons[i - 1].Width; buttonData.SeparatorObject.Top := buttonY; buttonData.SeparatorObject.Width := 4; buttonData.SeparatorObject.Height := optionPanel.Height - TMain.Instance.Style.optionPanel.paddingV; buttonX := buttonX + optionButtons[i - 1].Width + optionButtonGap * 4; buttonData.SeparatorObject.Left := Round(buttonData.SeparatorObject.Left + (buttonX - buttonData.SeparatorObject.Left) / 2) - 1; buttonData.SeparatorObject.Visible := true; end else begin button.Visible := true; button.Left := buttonX; button.Top := buttonY; if button.Top + button.Height >= optionPanel.Height then begin buttonY := optionPanel.Top + TMain.Instance.Style.OptionPanel.PaddingTop; buttonX := buttonX + button.Width + optionButtonGap; button.Left := buttonX; button.Top := buttonY; end; buttonY := buttonY + optionButtons[i].Height + optionButtonGap; end; end; end; procedure TMainForm.UpdateOptionPanel(); begin ilog('Updating option panel'); arrowButton.Height := barBackground.Height; if optionPanel.Visible then begin optionPanel.Left := optionPanelOpenWidth - optionPanelCurrentWidth + arrowButton.Width; arrowButton.Left := optionPanel.Left - arrowButton.Width; optionPanel.Height := arrowButton.Height; UpdateOptionButtonsLayout( TMain.Instance.Style.OptionPanel.PaddingLeft, TMain.Instance.Style.OptionPanel.PaddingTop ); end else begin arrowButton.Left := optionPanelOpenWidth - optionPanelCurrentWidth; end; end; procedure TMainForm.optionPanelAnimTimer_timer(sender: TObject); var percent: Real; i: Byte; begin if optionPanelAnimationDuration > 0 then percent := (GetTickCount() - optionPanelAnimationStartTime) / optionPanelAnimationDuration else percent := 1.0; if percent >= 1.0 then begin ilog('Panel animation complete'); percent := 1.0; optionPanelAnimTimer.Enabled := false; if not optionPanelOpen then optionPanel.Visible := false; if optionPanelOpen then begin arrowButton.IconImagePath := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButtonIconRight.png'; end else begin arrowButton.IconImagePath := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButtonIconLeft.png'; for i := 0 to Length(optionButtons) - 1 do begin optionButtons[i].Visible := false; end; end; end; if optionPanelOpen then begin SetOptionPanelWidth(Round(percent * (optionPanelCloseWidth + (optionPanelOpenWidth - optionPanelCloseWidth)))); end else begin SetOptionPanelWidth(Round((1.0 - percent) * (optionPanelCloseWidth + (optionPanelOpenWidth - optionPanelCloseWidth)))); end; end; procedure TMainForm.OpenCloseOptionPanel(const iOpen: Boolean); begin if iOpen and optionPanelOpen then Exit; if (not iOpen) and (not optionPanelOpen) then Exit; optionPanelOpen := iOpen; optionPanel.Visible := true; if TMain.Instance.User.GetUserSetting('AnimationsEnabled') <> 'true' then begin if iOpen then begin SetOptionPanelWidth(Round(optionPanelCloseWidth + (optionPanelOpenWidth - optionPanelCloseWidth))); optionPanel.Visible := true; arrowButton.IconImagePath := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButtonIconRight.png'; end else begin SetOptionPanelWidth(0); optionPanel.Visible := false; arrowButton.IconImagePath := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButtonIconLeft.png'; end; Exit; end; if optionPanelAnimTimer = nil then begin ilog('Creating option panel timer'); optionPanelAnimTimer := TTimer.Create(self); optionPanelAnimTimer.Interval := 1; optionPanelAnimTimer.Enabled := false; optionPanelAnimTimer.OnTimer := optionPanelAnimTimer_timer; end else begin if optionPanelAnimTimer.Enabled then Exit; end; ilog('Opening / Closing timer'); optionPanelAnimTimer.Enabled := true; optionPanelAnimationStartTime := GetTickCount(); if TMain.Instance.User.GetUserSetting('AnimationsEnabled') <> 'true' then optionPanelAnimationDuration := 0 else optionPanelAnimationDuration := 200; end; procedure TMainForm.OpenOptionPanel(); begin OpenCloseOptionPanel(true); end; procedure TMainForm.ToggleOptionPanel(); begin OpenCloseOptionPanel(not optionPanelOpen); end; procedure TMainForm.arrowButton_click(sender: TObject); begin ToggleOptionPanel(); end; function TMainForm.AddOptionButtonData():TOptionButtonDatum; begin SetLength(optionButtonData, Length(optionButtonData) + 1); result := TOptionButtonDatum.Create(); result.ID := pOptionButtonDataID; result.Separator := false; pOptionButtonDataID := pOptionButtonDataID + 1; optionButtonData[Length(optionButtonData) - 1] := result; end; procedure TMainForm.AppHideInTrayIcon; begin Visible := FALSE; end; procedure TMainForm.ShowPopupMenu(f : TForm; p : TPopupMenu); var pt : TPoint; begin GetCursorPos(pt); SetForegroundWindow(f.handle); p.Popup(pt.x, pt.y); end; procedure TMainForm.WMCallBackMessage; var Owner : HWND; begin case msg.lParam of Wm_RButtonDown : begin ShowPopupMenu(self, trayIconPopupMenu); end; Wm_LButtonDown : begin Application.BringToFront(); //Visible := not Visible; //if Visible then Application.BringToFront(); // ilog(StringConv(Application.Active)); // // if not Application.Active then begin // Visible := true; // Application.BringToFront; // end else begin // Visible := not Visible; // if Visible then begin // //Application.BringToFront; // end else begin // //Visible := false; // end; // end; Owner := GetWindow(Handle, GW_OWNER); ShowWindow(Owner, SW_HIDE); end; Wm_LButtonDblClk : ; Wm_MouseMove : ; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Shell_NotifyIcon(NIM_DELETE, @pNotifyIconData); TMain.Instance.User.SetUserSetting('LastWindowSettings', IntToStr(Left) + ',' + IntToStr(Top) + ',' + IntToStr(BarInnerPanel.Width) + ',' + IntToStr(BarInnerPanel.Height)); TMain.Instance.User.Save(); end; procedure TMainForm.FormCreate(Sender: TObject); var optionButton: TWImageButton; i: Word; d: TOptionButtonDatum; applicationIcon: TIcon; lastWindowSettings: TStringList; begin // --------------------------------------------------------------------------- // Initialize form settings // --------------------------------------------------------------------------- TMain.Instance.MainForm := self; ilog('Initializing form settings'); pFirstShown := true; DoubleBuffered := true; windowDragData.dragging := false; pOptionButtonDataID := 1; optionPanelOpen := false; optionPanelCloseWidth := 0; optionPanelAnimationStartTime := 0; optionPanelAnimationDuration := 200; optionPanelCurrentWidth := optionPanelCloseWidth; optionButtonGap := 3; applicationIcon := TIcon.Create(); applicationIcon.LoadFromFile(TMain.Instance.FilePaths.IconsDirectory + '\Application.ico'); Icon := applicationIcon; Application.Icon := applicationIcon; // --------------------------------------------------------------------------- // Hide form in tray // --------------------------------------------------------------------------- Application.OnMinimize := AppHideInTrayIcon; // on initialise la structure TNotifyIconData with pNotifyIconData do begin cbSize := sizeof(pNotifyIconData); // taille de la structure wnd := handle; // fenêtre du Tray Icon uID := 1; uCallBackMessage := wm_CallBackMessage; // message envoyé par le système hIcon := applicationIcon.handle; // l'îcône du Tray Icon szTip := APPLICATION_TITLE; // Message d'aide uFlags := nif_message or nif_Icon or nif_tip;// Indique que notre Tray Icon // reçoit un message, // a une icône et un conseil end; // enregistre le Tray Icon Shell_NotifyIcon(NIM_ADD, @pNotifyIconData); // --------------------------------------------------------------------------- // Localization // --------------------------------------------------------------------------- trayIconPopupMenuClose.Caption := TMain.Instance.Loc.GetString('Global.Close'); // --------------------------------------------------------------------------- // Initialize option buttons' data // --------------------------------------------------------------------------- d := AddOptionButtonData(); d.Name := 'Close'; d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Close.png'; d := AddOptionButtonData(); d.Name := 'Eject'; d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Eject.png'; // d := AddOptionButtonData(); // d.Name := 'Close'; // d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Close.png'; // // d := AddOptionButtonData(); // d.Name := 'Close'; // d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Close.png'; // d := AddOptionButtonData(); // d.Separator := true; // d := AddOptionButtonData(); // d.Name := 'Encrypt'; // d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Key.png'; // d := AddOptionButtonData(); // d.Name := 'Config'; // d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Config.png'; // d := AddOptionButtonData(); // d.Name := 'Help'; // d.IconFilePath := TMain.Instance.FilePaths.SkinDirectory + '\ButtonIcon_Help.png'; // --------------------------------------------------------------------------- // Create form controls // --------------------------------------------------------------------------- ilog('Creating option panel'); { OPTION PANEL } optionPanel := TWNineSlicesPanel.Create(self); optionPanel.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\OptionPanel'; optionPanel.Width := optionPanelOpenWidth; optionPanel.Visible := false; optionPanel.Parent := self; optionPanel.OnMouseDown := barBackground_down; optionPanel.OnMouseUp := barBackground_up; optionPanel.OnMouseMove := barBackground_move; { OPTION BUTTONS } for i := 0 to Length(optionButtonData) - 1 do begin optionButton := TWImageButton.Create(self); optionButton.Tag := optionButtonData[i].ID; if not optionButtonData[i].Separator then begin optionButton := TWImageButton.Create(self); optionButton.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\OptionButton'; optionButton.Visible := false; optionButton.IconImagePath := optionButtonData[i].IconFilePath; optionButton.Cursor := crHandPoint; optionButton.Tag := optionButtonData[i].ID; optionButton.OnClick := optionButton_Click; optionPanel.AddChild(optionButton); end else begin optionButtonData[i].SeparatorObject := TWNineSlicesPanel.Create(self); optionButtonData[i].SeparatorObject.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\VerticalSeparator'; optionButtonData[i].SeparatorObject.Visible := false; optionPanel.AddChild(optionButtonData[i].SeparatorObject); end; SetLength(optionButtons, Length(optionButtons) + 1); optionButtons[Length(optionButtons) - 1] := optionButton; end; CalculateOptionPanelOpenWidth(); optionPanel.Width := optionPanelOpenWidth; { BAR BACKGROUND PANEL } ilog('Creating background panel'); barBackground := TWNineSlicesPanel.Create(self); barBackground.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\BarBackground'; barBackground.Visible := true; barBackground.Parent := self; barBackground.OnMouseDown := barBackground_down; barBackground.OnMouseUp := barBackground_up; barBackground.OnMouseMove := barBackground_move; { BAR INNER PANEL } ilog('Creating inner panel'); barInnerPanel := TIconPanel.Create(self); barBackground.AddChild(barInnerPanel); barInnerPanel.Visible := true; barInnerPanel.Width := 200; barInnerPanel.Height := 50; barInnerPanel.OnResize := barInnerPanel_Resize; ilog('BAR INNER PANEL: ' + IntToStr(barInnerPanel.ID)); { ARROW BUTTON } ilog('Creating arrow button'); arrowButton := TWNineSlicesButton.Create(self); arrowButton.ImagePathPrefix := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButton'; arrowButton.Visible := true; arrowButton.Parent := self; arrowButton.Width := 16; arrowButton.Height := 64; arrowButton.IconImagePath := TMain.Instance.FilePaths.SkinDirectory + '\ArrowButtonIconLeft.png'; arrowButton.Cursor := crHandPoint; arrowButton.OnClick := arrowButton_click; resizer := TWImage.Create(Self); resizer.FilePath := TMain.Instance.FilePaths.SkinDirectory + '\Resizer.png'; resizer.StretchToFit := false; resizer.MaintainAspectRatio := true; resizer.FitToContent(); resizer.OnMouseDown := Resizer_MouseDown; resizer.OnMouseUp := Resizer_MouseUp; resizer.OnMouseMove := Resizer_MouseMove; barBackground.AddChild(resizer); // --------------------------------------------------------------------------- // Draw and update layout // --------------------------------------------------------------------------- lastWindowSettings := SplitString(',', TMain.Instance.User.GetUserSetting('LastWindowSettings')); if lastWindowSettings.Count = 4 then begin try Left := StrToInt(lastWindowSettings[0]); Top := StrToInt(lastWindowSettings[1]); BarInnerPanel.Width := StrToInt(lastWindowSettings[2]); BarInnerPanel.Height := StrToInt(lastWindowSettings[3]); except on E: Exception do begin Left := 0; Top := 0; end; end; end; // Make sure that the bar is not off-screen if Left >= Screen.DesktopWidth - 64 then Left := Screen.DesktopWidth - 64; if Top >= Screen.DesktopHeight - 64 then Top := Screen.DesktopHeight - 64; TMain.Instance.User.AutomaticallyAddNewApps(); barInnerPanel.LoadFolderItems(); UpdateLayout(); TMain.Instance.User.DoQuickLaunch(); Visible := true; ShowWindow(Application.Handle, SW_HIDE); end; procedure TMainForm.FormShow(Sender: TObject); var lastWindowSettings: TStringList; begin if pFirstShown then begin pFirstShown := false; end; end; end.
unit Encoder; interface uses SysUtils, Classes, Contnrs; type TReplacement = class private FForWhat: string; FWhat: string; FField: string; public property Field: string read FField write FField; property What: string read FWhat write FWhat; property ForWhat: string read FForWhat write FForWhat; end; TEncoding = (encAnsi, encAscii); TEncoder = class private FFolder: string; FOnEncodingStarted: TNotifyEvent; FOnEncodingInProgress: TNotifyEvent; FOnEncodingFinished: TNotifyEvent; FFileList: TStringList; FOutFolder: string; FCurrentFile: string; procedure ReadFileList; function GetFileCount: integer; public procedure EncodeFile(AFileName: string; AOutFileName: string); // в DOS procedure DecodeFile(AFileName: string; AOutFileName: string); // в Win property OnEncodingStarted: TNotifyEvent read FOnEncodingStarted write FOnEncodingStarted; property OnEncodingFinished: TNotifyEvent read FOnEncodingFinished write FOnEncodingFinished; property OnEncodingInProgress: TNotifyEvent read FOnEncodingInProgress write FOnEncodingInProgress; property Folder: string read FFolder; property OutFolder: string read FOutFolder; property CurrentFile: string read FCurrentFile; property FileCount: integer read GetFileCount; procedure Execute; class function IsOemStr(S: string): boolean; class function GetInstance: TEncoder; constructor Create(AFolder, AOutFolder: string); destructor Destroy; override; end; implementation uses rxStrUtils, Math, FileUtils, Windows, JclWideStrings; { TEncoder } constructor TEncoder.Create(AFolder, AOutFolder: string); begin inherited Create; FFolder := AFolder; FOutFolder := AOutFolder; end; procedure TEncoder.DecodeFile(AFileName, AOutFileName: string); var lstIn: TStringList; i: integer; sDir: string; T: TextFile; begin lstIn := TStringList.Create; lstIn.LoadFromFile(AFileName); sDir := ExtractFilePath(AOutFileName); if not DirectoryExists(sDir) then CreateDir(sDir); AssignFile(T, AOutFileName); // начинаем работать с файлом ReWrite(T); // создаём новый пустой файл for i := 0 to lstIn.Count - 1 do begin Writeln(T, OemToAnsiStr(lstIn[i])); // вторую строку в досовской end; CloseFile(T); // закрываем файл FreeAndNil(lstIn); end; destructor TEncoder.Destroy; begin FreeAndNil(FFileList); inherited; end; procedure TEncoder.EncodeFile(AFileName, AOutFileName: string); var lstIn, lstOut: TStringList; i: integer; sDir: string; begin lstIn := TStringList.Create; lstOut := TStringList.Create; lstIn.LoadFromFile(AFileName); for i := 0 to lstIn.Count - 1 do lstOut.Add(StrToOem(lstIn[i])); sDir := ExtractFilePath(AOutFileName); if not DirectoryExists(sDir) then CreateDir(sDir); lstOut.SaveToFile(AOutFileName); FreeAndNil(lstIn); FreeAndNil(lstOut); end; procedure TEncoder.Execute; var i: integer; begin // читаем список файлов ReadFileList; if Assigned(FOnEncodingStarted) then FOnEncodingStarted(Self); // перекодируем каждый файл for i := 0 to FFileList.Count - 1 do begin FCurrentFile := StringReplace(FFileList[i], FFolder, FOutFolder, [rfIgnoreCase]); if Assigned(FOnEncodingInProgress) then FOnEncodingInProgress(Self); EncodeFile(FFileList[i], FCurrentFile); end; if Assigned(FOnEncodingFinished) then FOnEncodingFinished(Self); end; function TEncoder.GetFileCount: integer; begin Assert(Assigned(FFileList), 'Список файлов не сформирован'); Result := FFileList.Count; end; class function TEncoder.GetInstance: TEncoder; const enc: TEncoder = nil; begin if not Assigned(enc) then enc := TEncoder.Create('', ''); Result := enc; end; class function TEncoder.IsOemStr(S: string): boolean; var i: integer; begin Result := False; for i := 1 to Length(S) do Result := Result or ((Ord(S[i]) >= 128) and (Ord(S[i]) <= 175)); end; procedure TEncoder.ReadFileList; procedure ReadDirectoryList(ABaseFolder: string; ADirectoryList: TStrings); var f, i: Integer; Found: TSearchRec; begin f:=FindFirst(ABaseFolder + '\*.*', faDirectory, Found); while f=0 do begin if ADirectoryList.IndexOf(ABaseFolder + '\' + Found.Name) = -1 then begin if (Found.Name <> '.') and (Found.Name <> '..') and ((Found.Attr and faDirectory) <> 0) then begin i := ADirectoryList.Add(ABaseFolder + '\' + Found.Name); ReadDirectoryList(ADirectoryList[i], ADirectoryList); end; end; f := SysUtils.FindNext(Found); end; SysUtils.FindClose(Found); end; var f: integer; Found: TSearchRec; lstDir: TStringList; i: Integer; begin FFileList := TStringList.Create; lstDir := TStringList.Create; ReadDirectoryList(Folder, lstDir); lstDir.Insert(0, Folder); for i := 0 to lstDir.Count - 1 do begin f := SysUtils.FindFirst(lstDir[i] + '\*.las', faAnyFile, Found); while (f = 0) do begin FFileList.Add(lstDir[i] + '\' + Found.Name); f := SysUtils.FindNext(Found); end; SysUtils.FindClose(Found); end; end; { TReplacementList } end.
//***************************************************************************** // File : lmsfilter.pas // Author : Mazen NEIFER // Creation date : 2000-10-20 // Last modification date : 2010-07-21 // Licence : GPL // Bug report : mazen.neifer@supaero.org //***************************************************************************** unit LMSfilter; interface uses RealVectors; function FastConv(x, h: TVector): TVectorBase; {This function makes a very fast convolution of two Vector. The first "x" is supposed to be the signal to be convoluted and the second "h" is supposed to be the filter to convoluate with. It supposes implicetly that Dim(h) is below or equal to than Dim(x) but it doesn't make a test <SMALL>(it is a fast rooutine, it do its job without testing entries)</SMALL>. Please notice that it gives one value only which corresponds to the last output of the filter when exited by the given signal. Code <CODE>y:=FastConv(x,h)</CODE> results in y=h*x(Dim(x)).} function Wiener(var h: TVector; x, d: TVector; mu: Real): TVector; {This function applies an adaptative Wiener filter to signal "x", desired to be "d" and gives "y:=h[n]*x[n]" as result. The filter is initialize using h, and is corrected depending on parameter "mu". The filter is finally returned in "h" so you have to ensure you will no more need this vector before you call this function and you have to destroy it once you don't need it any more.} procedure LMS(out y ,e: Real;var h: TVector; x: TVector; d, mu: Real); implementation function FastConv(x, h: TVector): TVectorBase; var i: Word; begin with h do begin FastConv := 0; for i := 0 to n do FastConv += Values[i] * x.Values[n - i]; end; end; procedure LMS(out y, e: Real; var h: TVector; x: TVector; d, mu: Real); begin y := FastConv(h, x);{We begin by estimating the "x" at current instant!} e := d - y;{Then we calculate the error. Estimation doesn't give us the correct value but just a very close value for good estimations} Acc(h, 2 * mu * e, x);{"h:=h+2*mu*e*x" : Then we applay LMS algorithme to correct the "h" value using error. We try to not use operators du to some memory problems with function that return pointer when called one as a transmitted parameter to an other. for more details see <A HREF="realVector.pas.html">realVector</A>.} end; function Wiener(var h: TVector; x, d: TVector; mu: Real): TVector; var i: Word; e: TVectorBase; begin Wiener := Vector(Dim(x) - Dim(h)); with Wiener do for i := 0 TO n do LMS(Values[i], e, h, SubVector(x, h. n + 1, i), d. Values[h.n + i + 1], mu); end; end.
unit ppi8255; interface uses dialogs,sysutils; type read_port_8255=function:byte; write_port_8255=procedure (valor:byte); tpia8255=record control:byte; m_group_a_mode:byte; m_group_b_mode:byte; m_port_a_dir:byte; m_port_b_dir:byte; m_port_ch_dir:byte; m_port_cl_dir:byte; m_obf_a:byte; m_ibf_a:byte; m_obf_b:byte; m_ibf_b:byte; m_inte_a:byte; m_inte_b:byte; m_inte_1:byte; m_inte_2:byte; m_control:byte; m_in_mask,m_out_mask,m_read,m_latch,m_output:array[0..2] of byte; read_port:array[0..2] of read_port_8255; write_port:array[0..2] of write_port_8255; end; ptpia8255=^tpia8255; var pia_8255:array[0..1] of ptpia8255; procedure reset_ppi8255(num:byte); procedure close_ppi8255(num:byte); procedure init_ppi8255(num:byte;pread_port_a,pread_port_b,pread_port_c:read_port_8255;pwrite_port_a,pwrite_port_b,pwrite_port_c:write_port_8255); function ppi8255_r(num,port:byte):byte; procedure ppi8255_w(num,port,data:byte); function ppi8255_get_port(num,port:byte):byte; procedure ppi8255_set_port(num,port,data:byte); implementation procedure ppi8255_get_handshake_signals(num:byte;val:pbyte); var pia:ptpia8255; handshake,mask:byte; begin pia:=pia_8255[num]; handshake:=$00; mask:=$00; // group A */ if (pia.m_group_a_mode=1) then begin if (pia.m_port_a_dir<>0) then begin if (pia.m_ibf_a)<>0 then handshake:=handshake or $20 else handshake:=handshake or $0; if ((pia.m_ibf_a<>0) and (pia.m_inte_a<>0)) then handshake:=handshake or $08; mask:=mask or $28; end else begin if (pia.m_obf_a=0) then handshake:=handshake or $80 else handshake:=handshake or $0; if ((pia.m_obf_a<>0) and (pia.m_inte_a<>0)) then handshake:=handshake or $08 else handshake:=handshake or $0; mask:=mask or $88; end; end else if (pia.m_group_a_mode=2) then begin if (pia.m_obf_a<>0) then handshake:=handshake or $0 else handshake:=handshake or $80; if (pia.m_ibf_a<>0) then handshake:=handshake or $20 else handshake:=handshake or $0; if (((pia.m_obf_a<>0) and (pia.m_inte_1<>0)) or ((pia.m_ibf_a<>0) and (pia.m_inte_2<>0))) then handshake:=handshake or $08 else handshake:=handshake or $0; mask:=mask or $a8; end; // group B */ if (pia.m_group_b_mode=1) then begin if (pia.m_port_b_dir<>0) then begin if (pia.m_ibf_b<>0) then handshake:=handshake or $02; if ((pia.m_ibf_b<>0) and (pia.m_inte_b<>0)) then handshake:=handshake or $01; mask:=mask or $03; end else begin if (pia.m_obf_b=0) then handshake:=handshake or $02; if ((pia.m_obf_b<>0) and (pia.m_inte_b<>0)) then handshake:=handshake or $01; mask:=mask or $03; end; end; val^:=val^ and not(mask); val^:=val^ or (handshake and mask); end; procedure ppi8255_write_port(num,port:byte); var pia:ptpia8255; write_data:byte; begin pia:=pia_8255[num]; write_data:=pia.m_latch[port] and pia.m_out_mask[port]; write_data:=write_data or ($FF and not(pia.m_out_mask[port])); // write out special port 2 signals */ if (port=2) then ppi8255_get_handshake_signals(num,@write_data); pia.m_output[port]:=write_data; if @pia.write_port[port]<>nil then pia.write_port[port](write_data); end; procedure ppi8255_input(num,port,data:byte); var pia:ptpia8255; changed:boolean; begin pia:=pia_8255[num]; changed:=false; pia.m_read[port]:=data; // port C is special */ if (port=2) then begin if (((pia.m_group_a_mode=1) and (pia.m_port_a_dir=0)) or (pia.m_group_a_mode=2)) then begin // is !ACKA asserted? */ if ((pia.m_obf_a<>0) and ((not(data and $40))<>0)) then begin pia.m_obf_a:=0; changed:=true; end; end; if (((pia.m_group_a_mode=1) and (pia.m_port_a_dir=1)) or (pia.m_group_a_mode=2)) then begin // is !STBA asserted? */ if ((pia.m_ibf_a=0) and ((not(data and $10))<>0)) then begin pia.m_ibf_a:=1; changed:=true; end; end; if ((pia.m_group_b_mode=1) and (pia.m_port_b_dir=0)) then begin // is !ACKB asserted? */ if ((pia.m_obf_b<>0) and ((not(data and $04))<>0)) then begin pia.m_obf_b:=0; changed:=true; end; end; if ((pia.m_group_b_mode=1) and (pia.m_port_b_dir=1)) then begin // is !STBB asserted? */ if ((pia.m_ibf_b=0) and ((not(data and $04))<>0)) then begin pia.m_ibf_b:=1; changed:=true; end; end; if changed then begin ppi8255_write_port(num,2); end; end; //del if port2 end; function ppi8255_read_port(num,port:byte):byte; var pia:ptpia8255; res:byte; begin pia:=pia_8255[num]; res:=$00; if (pia.m_in_mask[port]<>0) then begin if @pia.read_port[port]<>nil then ppi8255_input(num,port,pia.read_port[port]); res:=res or (pia.m_read[port] and pia.m_in_mask[port]); end; res:=res or (pia.m_latch[port] and pia.m_out_mask[port]); case port of 0:pia.m_ibf_a:=0; // clear input buffer full flag */ 1:pia.m_ibf_b:=0; // clear input buffer full flag */ 2:ppi8255_get_handshake_signals(num,@res); // read special port 2 signals end; ppi8255_read_port:=res; end; procedure set_mode(num,data:byte;call_handlers:boolean); var pia:ptpia8255; f:byte; begin pia:=pia_8255[num]; // parse out mode */ pia.m_group_a_mode:=(data shr 5) and 3; pia.m_group_b_mode:=(data shr 2) and 1; pia.m_port_a_dir:=(data shr 4) and 1; pia.m_port_b_dir:=(data shr 1) and 1; pia.m_port_ch_dir:=(data shr 3) and 1; pia.m_port_cl_dir:=(data shr 0) and 1; // normalize group_a_mode */ if (pia.m_group_a_mode=3) then pia.m_group_a_mode:=2; // Port A direction */ if (pia.m_group_a_mode=2) then begin pia.m_in_mask[0]:=$FF; pia.m_out_mask[0]:=$FF; //bidirectional */ end else begin if (pia.m_port_a_dir<>0) then begin pia.m_in_mask[0]:=$FF; pia.m_out_mask[0]:=$00; // input */ end else begin pia.m_in_mask[0]:=$00; pia.m_out_mask[0]:=$FF; // output */ end; end; // Port B direction */ if (pia.m_port_b_dir<>0) then begin pia.m_in_mask[1]:=$FF; pia.m_out_mask[1]:=$00; // input */ end else begin pia.m_in_mask[1]:=$00; pia.m_out_mask[1]:=$FF; // output */ end; // Port C upper direction */ if (pia.m_port_ch_dir<>0) then begin pia.m_in_mask[2]:=$F0; pia.m_out_mask[2]:=$00; // input */ end else begin pia.m_in_mask[2]:=$00; pia.m_out_mask[2]:=$F0; // output */ end; // Port C lower direction */ if (pia.m_port_cl_dir<>0) then pia.m_in_mask[2]:=pia.m_in_mask[2] or $0F // input */ else pia.m_out_mask[2]:=pia.m_out_mask[2] or $0F; // output */ // now depending on the group modes, certain Port C lines may be replaced // * with varying control signals case pia.m_group_a_mode of 0:; // Group A mode 0 no changes */ 1:begin // Group A mode 1 bits 5-3 are reserved by Group A mode 1 pia.m_in_mask[2]:=pia.m_in_mask[2] and $c7; pia.m_out_mask[2]:=pia.m_out_mask[2] and $c7; end; 2:begin // Group A mode 2 bits 7-3 are reserved by Group A mode 2 pia.m_in_mask[2]:=pia.m_in_mask[2] and $07; pia.m_out_mask[2]:=pia.m_out_mask[2] and $07; end; end; case pia.m_group_b_mode of 0:; // Group B mode 0 no changes */ 1:begin // Group B mode 1 bits 2-0 are reserved by Group B mode 1 */ pia.m_in_mask[2]:=pia.m_in_mask[2] and $F8; pia.m_out_mask[2]:=pia.m_out_mask[2] and $F8; end; end; // KT: 25-Dec-99 - 8255 resets latches when mode set */ pia.m_latch[0]:=0; pia.m_latch[1]:=0; pia.m_latch[2]:=0; if call_handlers then for f:=0 to 2 do ppi8255_write_port(num,f); // reset flip-flops */ pia.m_obf_a:=0; pia.m_ibf_a:=0; pia.m_obf_b:=0; pia.m_ibf_b:=0; pia.m_inte_a:=0; pia.m_inte_b:=0; pia.m_inte_1:=0; pia.m_inte_2:=0; // store control word */ pia.m_control:=data; end; procedure reset_ppi8255(num:byte); var pia:ptpia8255; f:byte; begin pia:=pia_8255[num]; pia.m_group_a_mode:=0; pia.m_group_b_mode:=0; pia.m_port_a_dir:=0; pia.m_port_b_dir:=0; pia.m_port_ch_dir:=0; pia.m_port_cl_dir:=0; pia.m_obf_a:=0; pia.m_ibf_a:=0; pia.m_obf_b:=0; pia.m_ibf_b:=0; pia.m_inte_a:=0; pia.m_inte_b:=0; pia.m_inte_1:=0; pia.m_inte_2:=0; for f:=0 to 2 do begin pia.m_in_mask[f]:=0; pia.m_out_mask[f]:=0; pia.m_read[f]:=0; pia.m_latch[f]:=0; pia.m_output[f]:=0; end; set_mode(num,$9b,false); end; procedure close_ppi8255(num:byte); var pia:ptpia8255; begin if pia_8255[num]=nil then exit; pia:=pia_8255[num]; pia.read_port[0]:=nil; pia.read_port[1]:=nil; pia.read_port[2]:=nil; pia.write_port[0]:=nil; pia.write_port[1]:=nil; pia.write_port[2]:=nil; freemem(pia_8255[num]); pia_8255[num]:=nil; end; procedure init_ppi8255(num:byte;pread_port_a,pread_port_b,pread_port_c:read_port_8255;pwrite_port_a,pwrite_port_b,pwrite_port_c:write_port_8255); var pia:ptpia8255; begin getmem(pia_8255[num],sizeof(tpia8255)); pia:=pia_8255[num]; fillchar(pia^,sizeof(tpia8255),0); pia.read_port[0]:=pread_port_a; pia.read_port[1]:=pread_port_b; pia.read_port[2]:=pread_port_c; pia.write_port[0]:=pwrite_port_a; pia.write_port[1]:=pwrite_port_b; pia.write_port[2]:=pwrite_port_c; end; function ppi8255_r(num,port:byte):byte; var pia:ptpia8255; res:byte; begin pia:=pia_8255[num]; res:=0; port:=port and $3; case port of 0,1,2:res:=ppi8255_read_port(num,port); // Port A,B,C read */ 3:res:=pia.m_control; // Control word */ end; ppi8255_r:=res; end; procedure ppi8255_w(num,port,data:byte); var pia:ptpia8255; bit:byte; begin pia:=pia_8255[num]; port:=port mod 4; case port of 0,1,2:begin // Port A,B,C write pia.m_latch[port]:=data; ppi8255_write_port(num,port); case port of 0:if ((pia.m_port_a_dir=0) and (pia.m_group_a_mode<>0)) then begin pia.m_obf_a:=1; ppi8255_write_port(num,2); end; 1:if ((pia.m_port_b_dir=0) and (pia.m_group_b_mode<>0)) then begin pia.m_obf_b:=1; ppi8255_write_port(num,2); end; end; end; 3:begin // Control word */ pia.control:=data; if (data and $80)<>0 then begin set_mode(num,data and $7f,true); end else begin // bit set/reset */ bit:=(data shr 1) and $07; if (data and 1)<>0 then pia.m_latch[2]:=pia.m_latch[2] or (1 shl bit) // set bit */ else pia.m_latch[2]:=pia.m_latch[2] and (not(1 shl bit)); // reset bit */ if (pia.m_group_b_mode=1) then if (bit=2) then pia.m_inte_b:=data and 1; if (pia.m_group_a_mode=1) then begin if ((bit=4) and (pia.m_port_a_dir<>0)) then pia.m_inte_a:=data and 1; if ((bit=6) and (pia.m_port_a_dir=0)) then pia.m_inte_a:=data and 1; end; if (pia.m_group_a_mode=2) then begin if (bit=4) then pia.m_inte_2:=data and 1; if (bit=6) then pia.m_inte_1:=data and 1; end; ppi8255_write_port(num,2); end; end; end; //del case end; function ppi8255_get_port(num,port:byte):byte; begin ppi8255_get_port:=pia_8255[num].m_output[port]; end; procedure ppi8255_set_port(num,port,data:byte); begin ppi8255_input(num,port,data); end; end.
unit uMunicipioControlerInserirAlterar; interface Uses System.SysUtils, Data.DB, System.Generics.Collections, uMunicipioDto, uMunicipioModel, uEstadoDto, uEstadoModel; type TMunicipioControlerInserirAlterar = class private oListaEstados: TDictionary<string, TEstadoDto>; oModelEstado: TEstadoModel; oModelMunicipio: TMunicipioModel; public function ADDListaHash(var oEstado: TObjectDictionary<string, TEstadoDto>): Boolean; procedure Limpar(var AMunicipio: TMunicipioDto); function Salvar(var AMunicipio: TMunicipioDto): Boolean; function Alterar(var AMunicipio: TMunicipioDto): Boolean; function VerificarMunicipio(AMunicipio: TMunicipioDto):Boolean; constructor Create; destructor Destroy; override; end; implementation { TMunicipioControlerInserirAlterar } function TMunicipioControlerInserirAlterar.ADDListaHash (var oEstado: TObjectDictionary<string, TEstadoDto>): Boolean; begin Result := oModelEstado.ADDListaHash(oEstado); end; function TMunicipioControlerInserirAlterar.Alterar(var AMunicipio : TMunicipioDto): Boolean; begin Result := oModelMunicipio.Alterar(AMunicipio); end; constructor TMunicipioControlerInserirAlterar.Create; begin oModelMunicipio := TMunicipioModel.Create; oModelEstado := TEstadoModel.Create; oListaEstados := TDictionary<string, TEstadoDto>.Create; end; destructor TMunicipioControlerInserirAlterar.Destroy; begin if Assigned(oModelMunicipio) then FreeAndNil(oModelMunicipio); if Assigned(oModelEstado) then FreeAndNil(oModelEstado); if Assigned(oListaEstados) then begin oListaEstados.Clear; FreeAndNil(oListaEstados); end; inherited; end; procedure TMunicipioControlerInserirAlterar.Limpar(var AMunicipio : TMunicipioDto); begin AMunicipio.idMunicipio := 0; AMunicipio.Nome := EmptyStr; AMunicipio.idUf := 0; end; function TMunicipioControlerInserirAlterar.Salvar(var AMunicipio : TMunicipioDto): Boolean; begin AMunicipio.idMunicipio := oModelMunicipio.BuscarID; Result := oModelMunicipio.Inserir(AMunicipio); end; function TMunicipioControlerInserirAlterar.VerificarMunicipio( AMunicipio: TMunicipioDto): Boolean; begin Result := oModelMunicipio.VerificarMunicipio(AMunicipio); end; end.
unit uGnFormProgress; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls; type TGnFormProgress = class(TForm) ProgressBar1: TProgressBar; bCancel: TButton; lMessage: TLabel; procedure bCancelClick(Sender: TObject); private FCancelFlag: Boolean; function GetCancelFlag: Boolean; procedure SetMsg(const AMsg: string); public constructor Create(const AForm: TForm); reintroduce; procedure Show(const ANumberTic: Integer; const ACaption: string); reintroduce; procedure Restart(const ANumberTic: Integer); procedure IncProgress; overload; procedure IncProgress(const AMsg: string); overload; property Msg: string write SetMsg; property CancelFlag: Boolean read GetCancelFlag; end; implementation {$R *.dfm} procedure TGnFormProgress.bCancelClick(Sender: TObject); begin FCancelFlag := True; end; constructor TGnFormProgress.Create(const AForm: TForm); begin inherited Create(AForm); PopupMode := pmAuto; PopupParent := AForm; end; function TGnFormProgress.GetCancelFlag: Boolean; begin Application.ProcessMessages; Result := FCancelFlag; end; procedure TGnFormProgress.IncProgress(const AMsg: string); begin ProgressBar1.Position := ProgressBar1.Position + 1; lMessage.Caption := AMsg; Application.ProcessMessages; end; procedure TGnFormProgress.IncProgress; begin ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; procedure TGnFormProgress.Restart(const ANumberTic: Integer); begin ProgressBar1.Position := 2; ProgressBar1.Max := ANumberTic + 1; FCancelFlag := False; end; procedure TGnFormProgress.SetMsg(const AMsg: string); begin lMessage.Caption := AMsg; Application.ProcessMessages; end; procedure TGnFormProgress.Show(const ANumberTic: Integer; const ACaption: string); begin Restart(ANumberTic); Caption := ACaption; inherited Show; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(12 Out 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.types.database; interface uses ormbr.factory.interfaces; const TStrDriverName: array[dnMSSQL..dnMongoDB] of string = ('MSSQL','MySQL','Firebird','SQLite','Interbase','DB2', 'Oracle','Informix','PostgreSQL','ADS','ASA', 'AbsoluteDB','MongoDB'); implementation end.
unit dm_EntranceMethodsMikko; interface uses SysUtils, Classes, rtcDataSrv, rtcSrvModule, rtcLink, rtcInfo, rtcConn, rtcFunction, dm_mikkoads, dm_entrance, SyncObjs, Windows, dateVk, RtcDb, hostdate,Generics.Collections, Dialogs, RtcLog; const FLD_KODKLI = 'kodkli'; FLD_NAME = 'name'; FLD_GRTIMEOUT = 'grTimeOut'; FLD_ISVALIDGROUP = 'isValidGroup'; FLD_DATEFIRE = 'dateFire'; FLD_ISBARCODEACCESS = 'isBarCodeAccess'; FLD_INN = 'INN'; type PDmEntranceListItem = ^RDmEntranceListItem; RDmEntranceListItem = record rtcCon: TRtcConnection; dm: TDmEntrance; end; TDmEntranceMethodsMikko = class(TDataModule) RtcEntranceGroup: TRtcFunctionGroup; RtcServModuleEntrance: TRtcServerModule; RtcDataServerLink1: TRtcDataServerLink; RtcFunction1: TRtcFunction; WebSockProvider: TRtcDataProvider; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure fillSotrudInfo(Sender: TRtcConnection; var ARec:TRtcRecord); procedure WebSockProviderWSConnect(Sender: TRtcConnection); procedure WebSockProviderCheckRequest(Sender: TRtcConnection); procedure WebSockProviderWSDataReceived(Sender: TRtcConnection); private { Private declarations } ListDmEntrance: TList<PDmEntranceListItem>; CritSection: TCriticalSection; // FDmMikkoAds: TDmMikkoAds; // FDmEntrance: TDmEntrance; procedure ClearDmEntranceList; function GetDmEntrance(aCon: TRtcConnection):TDmEntrance; procedure LockCritsection; procedure RegisterEntranceFunction(const aname:String; fExecute: TRtcFunctionCallEvent); procedure RtcFunConnect(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcAddFingerUser(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcDeleteFingerUser(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcDtFromXbase(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcEditEntrance(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetDataUvl(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetKodkliByFinger(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetKodkliByBarcode(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetServerTime(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetSystemTime(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcSetFilterOnDc162(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); // function EchoString(Value: string): string; // function ReverseString(Value: string): string; procedure RtcClearOldData(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcSetFilter(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetClientDataSetDc167(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Проверка связи </summary> procedure RtcCheckConnect(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Возвращает результат запроса cQuery </summary> procedure RtcQueryValue(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Проверка графика </summary> procedure RtcValidGraphic(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Проверка отпуска </summary> procedure RtcValidHoliday(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Проверка ОМК </summary> procedure RtcValidOmk(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); ///<summary> Проверка группы </summary> procedure RtcValidGroup(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); procedure RtcGetGrTimeOut(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); public { Public declarations } procedure DeleteDmEntrance(Sender: TRtcConnection); end; var DmEntranceMethodsMikko: TDmEntranceMethodsMikko; handle_connection: Integer; implementation {$R *.dfm} { TDataModule1 } procedure TDmEntranceMethodsMikko.ClearDmEntranceList; begin while ListDmEntrance.Count>0 do begin FreeAndNil(ListDmEntrance[0].dm); Dispose(ListDmEntrance[0]); ListDmEntrance.Delete(0); end; end; procedure TDmEntranceMethodsMikko.DataModuleCreate(Sender: TObject); begin //FDmMikkoAds := nil; //FDmEntrance := nil; ListDmEntrance := TList<PDmEntranceListItem>.Create; RegisterEntranceFunction('Connect',RtcFunConnect); RegisterEntranceFunction('AddFingerUser',RtcAddFingerUser); RegisterEntranceFunction('DeleteFingerUser',RtcDeleteFingerUser); RegisterEntranceFunction('DtFromXbase',RtcDtFromXbase); RegisterEntranceFunction('GetDataUvl',RtcGetDataUvl); RegisterEntranceFunction('GetKodkliByFinger',RtcGetKodkliByFinger); RegisterEntranceFunction('GetKodkliByBarcode',RtcGetKodkliByBarcode); RegisterEntranceFunction('GetServerTime', RtcGetServerTime); RegisterEntranceFunction('SetFilter', RtcSetFilter); RegisterEntranceFunction('SetFilterOnDc162', RtcSetFilterOnDc162); RegisterEntranceFunction('ClearOldData', RtcClearOldData); RegisterEntranceFunction('RtcSetFilter', RtcSetFilter); RegisterEntranceFunction('GetClientDataSetDc167', RtcGetClientDataSetDc167); RegisterEntranceFunction('CheckConnect', RtcCheckConnect); RegisterEntranceFunction('QueryValue', RtcQueryValue); RegisterEntranceFunction('ValidGraphic', RtcValidGraphic); RegisterEntranceFunction('ValidHoliday', RtcValidHoliday); RegisterEntranceFunction('ValidOmk', RtcValidOmk); RegisterEntranceFunction('EditEntrance', RtcEditEntrance); RegisterEntranceFunction('ValidGroup', RtcValidGroup); RegisterEntranceFunction('GetSystemTime', RtcGetSystemTime); RegisterEntranceFunction('GetGrTimeOut', RtcGetGrTimeOut); CritSection := TCriticalSection.Create; WebSockProvider.Server := RtcDataServerLink1.Server; end; procedure TDmEntranceMethodsMikko.DataModuleDestroy(Sender: TObject); begin CritSection.Release; CritSection.Free; ClearDmEntranceList; end; procedure TDmEntranceMethodsMikko.DeleteDmEntrance(Sender: TRtcConnection); var i: Integer; begin for I := 0 to ListDmEntrance.Count-1 do begin if ListDmEntrance[i].rtcCon=Sender then begin FreeAndNil(ListDmEntrance[i].dm); Dispose(ListDmEntrance[i]); ListDmEntrance.Delete(i); Break; end; end; end; procedure TDmEntranceMethodsMikko.fillSotrudInfo(Sender: TRtcConnection; var ARec: TRtcRecord); var kodkli: Integer; sAccess: String; begin kodkli := ARec.asInteger[FLD_KODKLI]; if kodkli>0 then begin ARec.asFloat[FLD_GRTIMEOUT] := GetDmEntrance(Sender).GetGrTimeOut(kodkli); ARec.asWidestring[FLD_NAME] := CoalEsce(GetDmEntrance(Sender).DmMikkoads.QueryValue('SELECT name FROM client WHERE kodkli='+IntToStr(kodkli)),''); ARec.asBoolean[FLD_ISVALIDGROUP] := GetDmEntrance(Sender).ValidGroup(kodkli); sAccess := CoalEsce(GetDmEntrance(Sender).DmMikkoAds.QueryValue('SELECT value FROM par_obj\par_obj WHERE kodobj='+ IntToStr(kodkli)+' AND kodparobj=258470'),''); ARec.asBoolean[FLD_ISBARCODEACCESS] := Trim(sAccess) = '1'; ARec.asDateTime[FLD_DATEFIRE] := GetDmEntrance(Sender).GetDataUvl(kodkli); ARec.asString[FLD_INN] := CoalEsce(GetDmEntrance(Sender).DmMikkoAds.QueryValue('SELECT value FROM par_obj\par_obj WHERE kodobj='+IntToStr(KodKli)+' AND kodparobj=31'),''); XLog(ARec.toJSON); end else XLog(' kodkli = 0'); end; function TDmEntranceMethodsMikko.GetDmEntrance(aCon: TRtcConnection): TDmEntrance; var p: PDmEntranceListItem; begin Result := nil; for p in ListDmEntrance do begin if p.rtcCon= aCon then Result := p.Dm; end; if not Assigned(Result) then end; procedure TDmEntranceMethodsMikko.LockCritsection; var t1: Int64; begin t1 := GetTickCount; while not CritSection.TryEnter do if GetTickCount-t1>10 then raise Exception.Create(' Error lock IdHandle'); end; procedure TDmEntranceMethodsMikko.RegisterEntranceFunction(const aname: String; fExecute: TRtcFunctionCallEvent); var mRtcFunction: TRtcFunction; begin mRtcFunction := TRtcFunction.Create(self); with mRtcFunction do begin FunctionName := aname; Group := RtcEntranceGroup; OnExecute := fExecute; end; end; procedure TDmEntranceMethodsMikko.RtcAddFingerUser(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var dwSize:integer; // p: Pointer; // i: Integer; buf: TBytes; UserID: Integer; // aData: AnsiString; IdFinger:Integer; //): Integer; mDmEntrance: TDmEntrance; begin try Result.asInteger := 0; UserId := Param.asInteger['UserId']; buf := BytesOf(Param.asWideString['aData']); IdFinger := Param.asInteger['IdFinger']; mDmEntrance := GetDmEntrance(Sender); dwSize := length(buf); //getMem(p,bs.Size); try { for I := 0 to bs.Size-1 do begin PAnsiChar(p)[i] := AnsiChar(bs.Bytes[i]); end;} Result.asInteger := mDmEntrance.AddFingerUser(UserId,dwSize,PAnsiChar(buf),IdFinger,0); if Result.asInteger=0 then Result.asInteger := mDmEntrance.AddFingerUser(UserId,dwSize,PAnsiChar(buf),IdFinger,1); finally //FreeMem(p); //bs.Free; end; except on E: exception do begin XLog('RtcFunAddUser'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcCheckConnect(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try if Assigned(GetDmEntrance(Sender)) then Result.asInteger := 1 else Result.asInteger := -1; except on E: exception do begin XLog('RtcFunCheckConnect'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcClearOldData(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try GetDmEntrance(Sender).ClearProtocol; GetDmEntrance(Sender).ClearOpenEntrace; except on E: exception do begin XLog('RtcFunClearOldData'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcDeleteFingerUser(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var UserId: Integer; begin try UserId := Param.asInteger['UserId']; GetDmEntrance(Sender).DeleteFingerUser(UserId,0); GetDmEntrance(Sender).DeleteFingerUser(UserId,1); except on E: exception do begin XLog('RtcFunDeleteUser'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcDtFromXbase(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asDateTime := GetDmEntrance(Sender).DmMikkoads.DtFromXbase(Param.asDateTime['aDt']); except on E: exception do begin XLog('RtcFunDtFromXBase'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcEditEntrance(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var chg:TRtcDataSetChanges; koddoc: Integer; response: TRtcArray; begin try if Param.isNull['delta_data'] then raise Exception.Create('Change_Data parameter is required'); chg := TRtcDataSetChanges.Create(Param.AsObject['delta_data']); response := Result.NewArray; try GetDmEntrance(Sender).EditEntrance(chg, response); finally Result.asArray := response; FreeAndNil(chg); end; except on E: exception do begin XLog('RtcFunEditEntrance'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcFunConnect(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var aUserName, aPassword: string; aIdOffice: Integer; mDmEntrance: TDmEntrance; p: PDmEntranceListItem; begin if Assigned(GetDmEntrance(Sender)) then Exit; LockCritSection; Inc(handle_connection) ; //FHandleConnection := handle_connection; CritSection.Release; try aUserName := Param.AsWideString['username']; aPassword := Param.AsWideString['password']; aIdOffice := Param.AsInteger['kodentrance']; //FDmMikkoAds := TDmMikkoAds.Create(self); mDmEntrance := TDmEntrance.Create(self); New(p); p.rtcCon := Sender; p.dm := mDmEntrance; ListDmEntrance.Add(p); //FDmEntrance.DmMikkoAds := FDmMikkoAds; mDmEntrance.handle_connection := handle_connection; if mDmEntrance.DmMikkoAds.ServerLogin(aUserName,aPassword) then Result.asInteger := handle_connection else Result.asInteger := 0; mDmEntrance.kodEntrance := aIdOffice; //DataSetProviderDc162.DataSet := FDmEntrance.AdsQueryDc162; //DataSetProviderDc167.DataSet := FDmEntrance.AdsQueryDc167; mDmEntrance.OpenRegistration; //ClearOldData; except On E: exception do begin XLog('RtcFunConnect'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetClientDataSetDc167(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var mDmEntrance: TDmEntrance; begin try mDmEntrance := GetDmEntrance(Sender); if not mDmEntrance.AdsQueryDc167.Active then mDmEntrance.OpenRegistration else begin mDmEntrance.AdsQueryDc167.Close; mDmEntrance.AdsQueryDc167.Open; end; DelphiDataSetToRtc(mDmEntrance.AdsQueryDc167, Result.NewDataSet); // Result.asDataSet := except on E: exception do begin XLog('RtcFunDc167'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetDataUvl(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asDateTime := GetDmEntrance(Sender).GetDataUvl(Param.asInteger['aKodkli']); except on E: exception do begin XLog('RtcFunDataUvl'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetKodkliByBarcode(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var rec: TRtcRecord; begin rec := Result.NewRecord; rec.asInteger['kodkli'] := Param.asInteger['kodkli']; try fillSotrudInfo(Sender,rec); except on E: exception do begin XLog('RtcFunKodKliByBarcode'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetKodkliByFinger(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var UserID: String; aData:String; rCode: Integer; dwSize:integer; buf: TBytes; // bs: TBytesStream; rec: TRtcRecord; begin try rec := Result.NewRecord; rec.asInteger['kodkli'] := 0; UserId := Param.asWideString['UserId']; //bs:= TBytesStream.Create; try rCode := param.asInteger['rCode']; //------------ Stream -------------------- if Param.isType['adata']=rtc_ByteArray then begin //bs.LoadFromStream(Param.asByteStream['adata']); buf := TBytes(MIME_decodeex(Param.asByteArray['adata'])); rec.asInteger[FLD_KODKLI] := GetDmEntrance(Sender).GetKodkliByFinger(UserId,length(buf),PAnsiChar(buf),rCode); fillSotrudInfo(Sender,rec); end else begin //----------- String ---------------------- adata := Param.asWideString['adata']; buf := BytesOf(adata); dwSize := length(buf); rec.asInteger[FLD_KODKLI] := GetDmEntrance(Sender).GetKodkliByFinger(UserId,dwSize,PAnsiChar(buf),rCode); fillSotrudInfo(Sender,rec); end; XLog('kodkli = '+IntToStr(rec.asInteger['kodkli'])); finally // FreeAndNil(bs); end; except on E: exception do begin XLog('RtcFunKodKliByFinger'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetServerTime(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asDateTime := Now; except on E: exception do begin XLog('RtcFunServerTime'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetSystemTime(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asDateTime := DtToSysDt(Now); except on E: exception do begin XLog('RtcFunSysytemTyme'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcQueryValue(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asWideString := CoalEsce(GetDmEntrance(Sender).DmMikkoads.QueryValue(Param.asWideString['cQuery']),''); except on E: exception do begin XLog('RtcFunQueryValue'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcSetFilter(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var mDmEntrance: TDmEntrance; begin try mDmEntrance := GetDmEntrance(Sender); mDmEntrance.SetFilter(Param.AsInteger['aIndex']); DelphiDataSetToRtc(mDmEntrance.AdsQueryDc162, Result.NewDataSet); except on E: exception do begin XLog('RtcFunSetFilter'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcSetFilterOnDc162(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); var mDmEntrance: TDmEntrance; begin mDmEntrance := GetDmEntrance(Sender); try mDmEntrance.ClearProtocol; mDmEntrance.ClearOpenEntrace; except // Глушим ошибку т.к. это вспомагательные действия. end; mDmEntrance.SetFilter(Param.AsInteger['aIndex']); DelphiDataSetToRtc(mDmEntrance.AdsQueryDc162, Result.NewDataSet); end; procedure TDmEntranceMethodsMikko.RtcValidGraphic(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asBoolean := GetDmEntrance(Sender).ValidGraphic(Param.AsInteger['aKodSotrud']); except on E: exception do begin XLog('RtcFunValidGrafic'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcGetGrTimeOut(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asFloat := GetDmEntrance(Sender).GetGrTimeOut(Param.AsInteger['aKodSotrud']); except on E: exception do begin XLog('RtcGetGrTimeOut'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcValidGroup(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asBoolean := GetDmEntrance(Sender).ValidGroup(Param.AsInteger['aKodSotrud']); except on E: exception do begin XLog('RtcFunValidGroup'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcValidHoliday(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asBoolean := GetDmEntrance(Sender).ValidHoliday(Param.AsInteger['aKodSotrud']); except on E: exception do begin XLog('RtcFunValidHoliday'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.RtcValidOmk(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue); begin try Result.asBoolean := GetDmEntrance(Sender).ValidOmk(Param.AsInteger['aKodSotrud']); except on E: exception do begin XLog('RtcFunValidOmk'); XLog(E.Message); Raise; end; end; end; procedure TDmEntranceMethodsMikko.WebSockProviderCheckRequest(Sender: TRtcConnection); begin if Sender.Request.FileName='/ws' then begin Sender.Accept; Sender.Response.WSUpgrade:=True; // Prepare Upgrade Response Sender.Write; // Send Upgrade Response end; end; procedure TDmEntranceMethodsMikko.WebSockProviderWSConnect(Sender: TRtcConnection); begin XLog(' WS connect:' +Sender.PeerAddr); end; procedure TDmEntranceMethodsMikko.WebSockProviderWSDataReceived(Sender: TRtcConnection); var wf:TRtcWSFrame; s:RtcString; begin wf:=Sender.wsFrameIn; // <- Web Socket Frame currenty being received //if wf.wfStarted and (wf.wfOpcode=wf.waOpcode) then // Started receiving a new Frame set // MemoAdd(2,'---> IN: '+wf.wfHeadInfo, Sender); // We want to analyze all text message with less than 500 characters total ... if wf.waFinal and (wf.waOpcode=wf_Text) and (wf.waPayloadLength<500) then begin // wait until the entire Payload has been received. // This should NOT be more than 500 bytes (see above) ... if wf.wfComplete then begin s:=wf.wfRead; // We have received a text message we want to respond to ... if s='WebSocket rocks' then { We can send a new Frame as a response to the Client that sent us the Web Socket Frame, by using the "Sender.wSend" method like this ... } Sender.wSend(wf_Text,'Absolutely!'); end; end else begin s:=wf.wfRead; // <- reading Frame's "Payload" data ... //if wf.wfOpcode=wf_Text then // MemoAdd(3,'IN ('+ // IntToStr(wf.wfTotalInOut)+'/'+ // IntToStr(wf.wfTotalLength)+') TXT >>> '+ // s, Sender) //else // MemoAdd(3,'IN ('+ // IntToStr(wf.wfTotalInOut)+'/'+ // IntToStr(wf.wfTotalLength)+') BIN('+IntToStr(length(s))+') >>>', Sender); end; if wf.wfDone then // <- Frame Done (all read) begin if wf.waFinal then // <- final Frame? //MemoAdd(2,'IN DONE, '+ // IntToStr(wf.wfTotalInOut)+'/'+IntToStr(wf.wfTotalLength)+' bytes <-----', Sender) else // More data shoud arrive in the next Frame ... //MemoAdd(3,'<--- IN ... MORE --->', Sender); end; end; Initialization; handle_connection := 0; end.
unit skushell; {********************************************************* Sanjay Kanade's Utility Functions for Delphi Shell functions SKUUTILS Copyright (C) 1999, Sanjay Kanade ***********************************************************} interface uses windows, sysutils, dialogs, controls, forms, shlobj, activex, comobj, shellapi, classes; type TRootFolder = (rtStartMenu, rtPrograms, rtDrives, rtDesktopDir, rtPersonal, rtAppData, rtFavorites, rtTemplates, rtDesktop, rtCommonAppData, rtCommonDocuments); {IMPORTANT: You can easily extend this list by adding your own constants. Note that they are not same as CSIDL constants. Rather, we have shortlisted our own list of constants. The idea is not to get confused by too many CSIDL constants and what each one represents. We only use a few of them.} //****************************************************** function getSpecialFolder(rootType: TRootFolder): string; {Gets a special location from the shell. Pass one of the roottypes given at the top of this unit. Example: getSpecialFolder(rtPrograms) would return the location of 'C:\Program Files' folder. ******************************************************} //***************************************************** function browseFolderDialog(dlgTitle: string; rootType: TRootFolder; setInitialDir: string): string; {Displays the folder selection dialog and allows you to preselect an existing folder. Returns the folder which the user selects. Example: browseFolderDialog('Select a folder', rtDrives, 'C:\Windows\Start Menu'); ******************************************************} //****************************************************** function createShortcut(exePath, shortcutPath, descr: string): boolean; {Creates a shortcut for you. exePath is the path of the target file which can be any file (not necessarily an EXE). Descr is the description that appears with the shortcut. shortcutPath is the path name of the .LNK file which you want to create. Returns true on success. Example: to create a desktop folder for a file, you would use: shortcutPath := getSpecialFolder(rtDesktopDir); if (shortcutPath <> '') and (AnsiLastChar(shortcutPath) <> '\') then shortcutPath := Concat(shortcutPath, '\'); createShortcut('C:\Program Files\myprog.exe', shortcutPath + 'myprog.lnk', 'My program'); ******************************************************} var SHGetFolderPath: FUNCTION (hwndOwner: HWND; nFolder: integer; hToken: THandle; dwFlags: DWORD; lpszPath: PChar): HRESULT; StDCall = NIL; implementation {****************************************************** For internal use ******************************************************} Procedure FreePidl( pidl: PItemIDList ); Var alloc: IMalloc; Begin If Succeeded(SHGetMalloc(alloc)) Then Begin alloc.Free(pidl); End; End; {****************************************************** function getSpecialFolder(rootType: TRootFolder): string; Gets a special location from the shell. Pass one of the roottypes given at the top of this unit. Example: getSpecialFolder(rtPrograms) would return the location of 'C:\Program Files' folder. ******************************************************} function getSpecialFolder(rootType: TRootFolder): string; var pidl: pItemIDList; nameBuf: Array [0..MAX_PATH] of Char; csidlValue: Integer; begin case rootType of rtDrives: csidlValue := CSIDL_DRIVES; rtPrograms: csidlValue := CSIDL_PROGRAMS; rtStartMenu: csidlValue := CSIDL_STARTMENU; rtDesktopDir: csidlValue := CSIDL_DESKTOPDIRECTORY; rtDesktop: csidlValue := CSIDL_DESKTOP; rtPersonal: csidlValue := CSIDL_PERSONAL; rtAppData: csidlValue := CSIDL_APPDATA; rtFavorites: csidlValue := CSIDL_FAVORITES; rtTemplates: csidlValue := CSIDL_TEMPLATES; rtCommonAppData: csidlValue := CSIDL_COMMON_APPDATA; rtCommonDocuments: csidlValue := CSIDL_COMMON_DOCUMENTS; else exit; end; result := ''; if SUCCEEDED(SHGetSpecialFolderLocation( Application.handle, csidlValue, pidl)) then begin If pidl <> Nil Then Begin If SHGetPathFromIDList(pidl, namebuf) Then Result := StrPas(namebuf); FreePidl( pidl ); End; end else //Fix: if assigned(SHGetFolderPath) and ((csidlvalue=CSIDL_APPDATA) or (csidlvalue=CSIDL_PERSONAL) or (csidlvalue=CSIDL_COMMON_APPDATA) or (csidlvalue=CSIDL_COMMON_DOCUMENTS)) then begin if SUCCEEDED(SHGetFolderPath( Application.handle, csidlValue, 0, 0, namebuf)) then Result := StrPas(namebuf); end; end; {****************************************************** For internal use ******************************************************} function BrowseCallBack(hwnd: HWND; msg: UINT; lParam, lpData: LPARAM): Integer stdcall; begin if (msg=BFFM_INITIALIZED) and (lpData <> 0) then SendMessage(hwnd, BFFM_SETSELECTION, integer(TRUE), lpData); result := 0; end; {****************************************************** function browseFolderDialog(dlgTitle: string; rootType: TRootFolder; setInitialDir: string): string; Displays the folder selection dialog and allows you to preselect an existing folder. Returns the folder which the user selects. Example: browseFolderDialog('Select a folder', rtDrives, 'C:\Windows\Start Menu'); ******************************************************} function browseFolderDialog(dlgTitle: string; rootType: TRootFolder; setInitialDir: string): string; var csidlValue: Integer; nameBuf: Array [0..MAX_PATH] of Char; bi: TBrowseInfo; pidl, pidlBrowse: pItemIDList; begin Result := ''; case rootType of rtDrives: csidlValue := CSIDL_DRIVES; rtPrograms: csidlValue := CSIDL_PROGRAMS; rtStartMenu: csidlValue := CSIDL_STARTMENU; rtDesktopDir: csidlValue := CSIDL_DESKTOPDIRECTORY; rtDesktop: csidlValue := CSIDL_DESKTOP; rtPersonal: csidlValue := CSIDL_PERSONAL; rtAppData: csidlValue := CSIDL_APPDATA; rtFavorites: csidlValue := CSIDL_FAVORITES; rtTemplates: csidlValue := CSIDL_TEMPLATES; rtCommonAppData: csidlValue := CSIDL_COMMON_APPDATA; else exit; end; if SUCCEEDED(SHGetSpecialFolderLocation( Application.handle, csidlValue, pidl)) then begin If pidl <> Nil Then Begin With bi Do Begin hwndOwner := Application.handle; pidlRoot := pidl; pszDisplayName := @nameBuf; lpszTitle := pchar(dlgTitle); ulFlags := BIF_RETURNONLYFSDIRS; lpfn := BrowseCallBack; lParam := 0; if setInitialDir <> '' then lParam := integer(pchar(setInitialDir)); pidlBrowse := SHBrowseForFolder(bi); If pidlBrowse <> Nil Then begin If SHGetPathFromIDList(pidlBrowse, namebuf) Then Result := StrPas(namebuf); FreePidl(pidlBrowse); end; FreePidl( pidl ); end; End; end; end; {****************************************************** function createShortcut(exePath, shortcutPath, descr: string): boolean; Creates a shortcut for you. exePath is the path of the target file which can be any file (not necessarily an EXE). Descr is the description that appears with the shortcut. shortcutPath is the path name of the .LNK file which you want to create. Returns true on success. Example: to create a desktop folder for a file, you would use: shortcutPath := getSpecialFolder(rtDesktopDir); if (shortcutPath <> '') and (AnsiLastChar(shortcutPath) <> '\') then shortcutPath := Concat(shortcutPath, '\'); createShortcut('C:\Program Files\myprog.exe', shortcutPath + 'myprog.lnk', 'My program'); ******************************************************} function createShortcut(exePath, shortcutPath, descr: string): boolean; var aComObj: IUnknown; aShellLink: IShellLink; iFile: IPersistFile; wideFileName: wideString; begin result := false; try aComObj := createComObject(CLSID_ShellLink); aShellLink := aComObj as IShellLink; iFile := aComObj as IPersistFile; aShellLink.setPath(pchar(exePath)); aShellLink.setDescription(pchar(descr)); aShellLink.setWorkingDirectory(pchar(ExtractFileDir(exePath))); wideFileName := shortCutPath; iFile.save(PWChar(wideFileName), false); result := true; except end; end; var OldError: Longint; FLibHandle: THandle; INITIALIZATION OldError := SetErrorMode(SEM_NOOPENFILEERRORBOX); try FLibHandle := LoadLibrary('shfolder'); if FLibHandle = 0 then exit; SHGetFolderPath := GetProcAddress(FLibHandle, 'SHGetFolderPathA'); finally SetErrorMode(OldError); end; finalization if FLibHandle <> 0 then FreeLibrary(FLibHandle); end.
program MPMP16; Uses Math; function countPascalOdd(line: longint) : longint; var count, n : longint; begin count := 0; n := line; while (n > 0) do begin count := count + (n and 1); n := n >> 1; end; countPascalOdd := 2 ** count; end; var i, sum, total: longint; per : float; begin sum := 0; total := 0; for i := 0 to 127 do begin sum := sum + countPascalOdd(i); total := total + i + 1; end; per := sum/total*100; write ('Total odd numbers: '); writeln (sum); write ('Total numbers: '); writeln (total); write ('Percentage of odd numbers: '); write (per:3:10); writeln ('%'); readln; end.
unit TNT_Console; interface const NB_LINES = 32; PROMPT = 'TNT> '; LOG_NAME = 'TNT.log'; type LogProc = procedure; TConsole = class private LogFlag: Boolean; LogFile: Text; Prompt: String; CurrLine: String; public Lines: array of String; Cursor: Integer; constructor Create(NumLines: Integer; PromptStr, LogName: String); procedure Log(Str: String); procedure SendChar(Ch: Char); procedure DelChar; function GetParam(n: Integer): String; function Execute: String; procedure NewLine; destructor Destroy; override; end; implementation uses OpenGL12, SysUtils, TNT_Skybox, TNT_Landscape, TNT_3D, TNT_Object, TNT_Vector, SDL, TNT_Font; constructor TConsole.Create(NumLines: Integer; PromptStr, LogName: String); begin inherited Create; SetLength(Lines, NumLines); Prompt := PromptStr; Lines[Cursor] := Prompt; LogFlag := LogName <> ''; if LogFlag then begin AssignFile(LogFile, LogName); ReWrite(LogFile); CloseFile(LogFile); end; Log('TNT Console running...'); if LogFlag then Log('Log enabled -> ' + LogName); end; procedure TConsole.SendChar(Ch: Char); begin Lines[Cursor] := Lines[Cursor] + Ch; end; procedure TConsole.DelChar; begin if Length(Lines[Cursor]) > Length(Prompt) then SetLength(Lines[Cursor], Length(Lines[Cursor])-1); end; procedure TConsole.Log(Str: String); var t: String; begin if LogFlag then begin Append(LogFile); WriteLn(LogFile, Str); CloseFile(LogFile); end; t := Lines[Cursor]; Lines[Cursor] := Str; NewLine; Lines[Cursor] := t; end; procedure TConsole.NewLine; begin Cursor := (Cursor+1) and (Length(Lines)-1); Lines[Cursor] := Prompt; end; function TConsole.GetParam(n: Integer): String; var i, j, k: Integer; begin if n = 0 then begin CurrLine := Copy(Lines[Cursor], 6, 255) + ' '; NewLine; i := Pos(' ', CurrLine); if i = 0 then Result := CurrLine else Result := Copy(CurrLine, 1, i-1); end else begin j := 0; k := 0; for i := 0 to n do begin j := j+k+1; k := 1; while CurrLine[j+k] <> ' ' do Inc(k); end; Result := Copy(CurrLine, j, k); end; Result := UpperCase(Result); end; function TConsole.Execute: String; var Str: String; begin Str := GetParam(0); if Str = 'OPENGL' then begin Log('OpenGL implementation informations:'); Log('Version: ' + glGetString(GL_VERSION)); Log('Renderer: ' + glGetString(GL_RENDERER)); Log('Vendor: ' + glGetString(GL_VENDOR)); Log('Available extensions:'); Str := glGetString(GL_EXTENSIONS); while Str <> '' do begin Log(Copy(Str, 1, Pos(' ', Str)-1)); Delete(Str, 1, Pos(' ', Str)); end; end; if Str = 'BSPHERE' then begin Str := GetParam(1); if Str = 'ON' then begin ShowBSpheres := True; Str := ''; end; if Str = 'OFF' then begin ShowBSpheres := False; Str := ''; end; end; if Str = 'LOAD' then begin Str := GetParam(1); if Str = 'SKYBOX' then begin TSkybox.Create(GetParam(2)); Str := ''; end; if Str = 'LANDSCAPE' then begin TLandscape.Create(GetParam(2), GetParam(3)); Str := ''; end; if Str = 'MODEL' then begin Scene.LoadModel(GetParam(2)); Str := ''; end; if Str = 'OBJECT' then begin TObj.Create(StrToInt(GetParam(2)), Vector(StrToFloat(GetParam(3)), StrToFloat(GetParam(4)), StrToFloat(GetParam(5)))); Str := ''; end; end; Result := Str; end; destructor TConsole.Destroy; begin Log('TNT Console closed'); Lines := nil; inherited Destroy; end; end.
unit uSchoolNTService; interface uses Windows, Messages, SysUtils, Classes, Graphics, Dialogs, Controls, SvCom_NTService, ActiveX, Vcl.ExtCtrls; type TSchoolNTService = class(TNtService) ActivateTimer: TTimer; procedure ActivateTimerTimer(Sender: TObject); procedure NtServiceStart(Sender: TNtService; var DoAction: Boolean); procedure NtServiceStop(Sender: TNtService; var DoAction: Boolean); procedure NtServiceShutdown(Sender: TObject); procedure NtServicePause(Sender: TNtService; var DoAction: Boolean); procedure NtServiceContinue(Sender: TNtService; var DoAction: Boolean); private { Private declarations } public { Public declarations } procedure ActivateService; procedure DeactivateService; end; var SchoolNTService: TSchoolNTService; implementation uses uTransportServer; {$R *.DFM} { TSchoolNTService } procedure TSchoolNTService.ActivateService; begin CoInitializeEx(nil, COINIT_MULTITHREADED); ActivateTimer.Enabled := True; end; procedure TSchoolNTService.ActivateTimerTimer(Sender: TObject); begin ActivateTimer.Enabled := False; try TransportServer.Start; except on E: Exception do begin //Logger.Error('OnActivate: %s', [E.Message]); ActivateTimer.Interval := 1000; ActivateTimer.Enabled := True; end; end; end; procedure TSchoolNTService.DeactivateService; begin TransportServer.Stop; CoUninitialize; end; procedure TSchoolNTService.NtServiceContinue(Sender: TNtService; var DoAction: Boolean); begin ActivateService; ReportStatus; end; procedure TSchoolNTService.NtServicePause(Sender: TNtService; var DoAction: Boolean); begin DeactivateService; ReportStatus; end; procedure TSchoolNTService.NtServiceShutdown(Sender: TObject); begin DeactivateService; ReportStatus; end; procedure TSchoolNTService.NtServiceStart(Sender: TNtService; var DoAction: Boolean); begin ActivateService; ReportStatus; end; procedure TSchoolNTService.NtServiceStop(Sender: TNtService; var DoAction: Boolean); begin DeactivateService; ReportStatus; end; end.
unit frmFutureDemo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Threading; type TFuturesDemoForm = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); private { Private declarations } Result200000: IFuture<integer>; Result250000: IFuture<integer>; Result300000: IFuture<integer>; Futures: array[0..2] of ITask; public { Public declarations } end; var FuturesDemoForm: TFuturesDemoForm; implementation {$R *.dfm} uses uSlowCode ; procedure TFuturesDemoForm.Button1Click(Sender: TObject); begin Memo1.Clear; Result200000 := TTask.Future<integer>(function: integer begin Result := PrimesBelow(200000); end); Memo1.Lines.Add('200000 Started'); Futures[0] := Result200000; Result250000 := TTask.Future<integer>(function: integer begin Result := PrimesBelow(250000); end); Memo1.Lines.Add('250000 Started'); Futures[1] := Result250000; Result300000 := TTask.Future<integer>(function: integer begin Result := PrimesBelow(300000); end); Memo1.Lines.Add('300000 Started'); Futures[2] := Result300000; end; procedure TFuturesDemoForm.Button2Click(Sender: TObject); begin TFuture<integer>.WaitForAll(Futures); Memo1.Lines.Add('Done Waiting. This should appear with all the results.'); Memo1.Lines.Add('There are ' + Result200000.GetValue.ToString + ' prime numbers under 200,000'); Memo1.Lines.Add('There are ' + Result250000.GetValue.ToString + ' prime numbers under 250,000'); Memo1.Lines.Add('There are ' + Result300000.GetValue.ToString + ' prime numbers under 300,000'); end; procedure TFuturesDemoForm.Button3Click(Sender: TObject); begin Memo1.Lines.Add('There are ' + Result200000.GetValue.ToString + ' prime numbers under 200,000'); Memo1.Lines.Add('Done Waiting. This should appear with the first result.'); Memo1.Lines.Add('There are ' + Result250000.GetValue.ToString + ' prime numbers under 250,000'); Memo1.Lines.Add('There are ' + Result300000.GetValue.ToString + ' prime numbers under 300,000'); end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [FIN_CHEQUE_RECEBIDO] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit FinChequeRecebidoService; interface uses FinChequeRecebido, Pessoa, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TFinChequeRecebidoService = class(TServiceBase) private class procedure AnexarObjetosVinculados(AListaFinChequeRecebido: TObjectList<TFinChequeRecebido>); overload; class procedure AnexarObjetosVinculados(AFinChequeRecebido: TFinChequeRecebido); overload; public class function ConsultarLista: TObjectList<TFinChequeRecebido>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TFinChequeRecebido>; class function ConsultarObjeto(AId: Integer): TFinChequeRecebido; class procedure Inserir(AFinChequeRecebido: TFinChequeRecebido); class function Alterar(AFinChequeRecebido: TFinChequeRecebido): Integer; class function Excluir(AFinChequeRecebido: TFinChequeRecebido): Integer; end; var sql: string; implementation { TFinChequeRecebidoService } class procedure TFinChequeRecebidoService.AnexarObjetosVinculados(AFinChequeRecebido: TFinChequeRecebido); begin // Pessoa sql := 'SELECT * FROM PESSOA WHERE ID = ' + AFinChequeRecebido.IdPessoa.ToString; AFinChequeRecebido.Pessoa := GetQuery(sql).AsObject<TPessoa>; end; class procedure TFinChequeRecebidoService.AnexarObjetosVinculados(AListaFinChequeRecebido: TObjectList<TFinChequeRecebido>); var FinChequeRecebido: TFinChequeRecebido; begin for FinChequeRecebido in AListaFinChequeRecebido do begin AnexarObjetosVinculados(FinChequeRecebido); end; end; class function TFinChequeRecebidoService.ConsultarLista: TObjectList<TFinChequeRecebido>; begin sql := 'SELECT * FROM FIN_CHEQUE_RECEBIDO ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TFinChequeRecebido>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TFinChequeRecebidoService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TFinChequeRecebido>; begin sql := 'SELECT * FROM FIN_CHEQUE_RECEBIDO where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TFinChequeRecebido>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TFinChequeRecebidoService.ConsultarObjeto(AId: Integer): TFinChequeRecebido; begin sql := 'SELECT * FROM FIN_CHEQUE_RECEBIDO WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TFinChequeRecebido>; AnexarObjetosVinculados(Result); end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TFinChequeRecebidoService.Inserir(AFinChequeRecebido: TFinChequeRecebido); begin AFinChequeRecebido.ValidarInsercao; AFinChequeRecebido.Id := InserirBase(AFinChequeRecebido, 'FIN_CHEQUE_RECEBIDO'); end; class function TFinChequeRecebidoService.Alterar(AFinChequeRecebido: TFinChequeRecebido): Integer; begin AFinChequeRecebido.ValidarAlteracao; Result := AlterarBase(AFinChequeRecebido, 'FIN_CHEQUE_RECEBIDO'); end; class function TFinChequeRecebidoService.Excluir(AFinChequeRecebido: TFinChequeRecebido): Integer; begin AFinChequeRecebido.ValidarExclusao; Result := ExcluirBase(AFinChequeRecebido.Id, 'FIN_CHEQUE_RECEBIDO'); end; end.
unit DmSrvDoc; interface uses System.SysUtils, System.Classes, rtcFunction, rtcInfo,ServerDocSqlmanager,FB30Statement, fbapidatabase, fbapiquery, commoninterface, vkvariable, QueryUtils, DmMain; type TSrvDocDm = class(TDataModule) procedure DataModuleCreate(Sender: TObject); private { Private declarations } FEventLogSqlManager: TServerDocSqlManager; // FMainDm: TMainDm; // procedure SetMainDm(const Value: TMainDm); public { Public declarations } procedure RtcDocEdit(AMainDm:TMainDm;FnParams: TRtcFunctionInfo; Result: TRtcValue); // property MainDm: TMainDm read FMainDm write SetMainDm; end; var SrvDocDm: TSrvDocDm; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TSrvDocDm.DataModuleCreate(Sender: TObject); begin //FEventLogSqlManager := MainDm.ServerDocSqlManager['EVENTLOG']; end; procedure TSrvDocDm.RtcDocEdit(AMainDm:TMainDm;FnParams: TRtcFunctionInfo; Result: TRtcValue); var fbQuery: TFbApiQuery; fbQueryLock: TFbApiQuery; tr: TFbApiTransaction; sqlmanager: TServerDocSqlManager; tablename: String; new_params: TVkVariableCollection; old_params: TVkVariableCollection; key_params: TVkVariableCollection; operation: TDocOperation; i:Integer; procedure LockDoc; begin if operation <> docInsert then begin fbQueryLock := AMainDm.GetNewQuery(tr); fbQueryLock.SQL.Text := sqlManager.GenerateLockSQL; TQueryUtils.SetQueryParams(fbQueryLock, key_params); fbQueryLock.ExecQuery; end; end; procedure UnLockDoc; begin if (operation <> docInsert) and Assigned(fbQueryLock) then begin fbQueryLock.Close; fbQueryLock.Free; end; end; begin tr := AMainDm.GetNewTransaction(AMainDm.StabilityTransactionOptions); fbQuery := AMainDm.GetNewQuery(tr); tablename:= FnParams.asString['TABLENAME']; operation := TUtils.getDocOperation(FnParams.asString['COMMAND']); sqlmanager := AMainDm.GetServerDocSqlManager(tablename); new_params := TVkVariableCollection.Create(self); old_params := TVkVariableCollection.Create(self); key_params := TVkVariableCollection.Create(self); try try if (operation = docUpdate) then begin TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['NEW'], new_params); TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['OLD'], old_params); TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['KEY'], key_params); end else if (operation = docDelete) then begin //TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['OLD'], old_params); TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['KEY'], key_params); end else TUtils.RtcToVkVariableColections(FnParams.asRecord['PARAMS'].asRecord['NEW'], new_params); fbQuery.SQL.Text := sqlManager.GenerateSQL(operation, new_params); { case (operation) of docInsert: fbQuery.SQL.Text := sqlmanager.GenerateSQLInsert(new_params); docUpdate: fbQuery.SQL.Text := sqlmanager.GenerateSQLUpdate(new_params); docDelete: fbQuery.SQL.Text := sqlmanager.GenerateSQLDelete(new_params); end;} LockDoc; TQueryUtils.SetQueryParams(fbQuery, new_params); TQueryUtils.SetQueryParams(fbQuery, key_params); fbQuery.ExecQuery; if Assigned(fbQuery.Current) then begin result.NewRecord.NewRecord('RESULT'); for i := 0 to fbQuery.Current.Count-1 do begin Result.asRecord.asRecord['RESULT'].asValue[fbQuery.Current.Data[i].Name] := fbQuery.Current.Data[i].AsVariant; end; end; if (operation = docInsert) then begin AMainDm.WriteEventLog(sqlManager, tr, operation, FnParams.asRecord['PARAMS'].asRecord['NEW'], FnParams.asRecord['PARAMS'].asRecord['OLD'], Result.asRecord.asRecord['RESULT']); end else begin AMainDm.WriteEventLog(sqlManager, tr, operation, FnParams.asRecord['PARAMS'].asRecord['NEW'], FnParams.asRecord['PARAMS'].asRecord['OLD'], FnParams.asRecord['PARAMS'].asRecord['KEY']); end; tr.Commit; UnLockDoc; except on ex:Exception do begin if tr.Active then tr.Rollback; AMainDm.registerError(fbQuery.SQL.Text, ex.Message); raise; end; end; finally FreeAndNil(sqlManager); FreeAndNil(fbQuery); FreeAndNil(tr); FreeAndNil(new_params); FreeAndNil(old_params); end; end; {procedure TSrvDocDm.SetMainDm(const Value: TMainDm); begin FMainDm := Value; end;} end.
{==============================================================================} { ----------------------- Copy Angle to Component -----------------------------} {------------------------------------------------------------------------------} {- -} {==============================================================================} Procedure CopyAngleToComponent; var Board : IPCB_Board; // document board object Track : IPCB_Track; // track object Component : IPCB_Component; // component object Angle : Extended; // Angle of selected segment Length : Extended; // Length of selected segment BoardUnits : String; // Current unit string mm/mils Begin Try Board := PCBServer.GetCurrentPCBBoard; If Not Assigned(Board) Then // check of active document Begin ShowMessage('The Current Document is not a PCB Document.'); Exit; End; // User is asked to select track segment Track := Board.GetObjectAtCursor(MkSet(eTrackObject),AllLayers, eEditAction_Select); If Not Assigned(Track) Then Begin ShowMessage('Not a track object was selected.'); Exit; End; Track.Selected := True; // The selected segment is used as a first two Angle := (ArcTan( (Track.Y2-Track.Y1)/(Track.X2-Track.X1))/(Pi)*180); Length := Power(( Power(Abs((Track.X2-Track.X1)),2) + Power(Abs((Track.Y2-Track.Y1)),2) ), 1/2 ) / 10000; if ( (Board.DisplayUnit) = 0) then BoardUnits := 'mm' else BoardUnits := 'mils'; ShowMessage('Uhel je ' + FloatToStrF(Angle,ffFixed, 3, 1) +'° a delka ' + FloatToStrF(Length,ffFixed, 10, 3) + BoardUnits ); Component := Board.GetObjectAtCursor(MkSet(eComponentObject),AllLayers, eEditAction_Select); If Not Assigned(Component) Then Begin ShowMessage('Not a component was selected.'); Exit; End; Try PCBServer.PreProcess; PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_BeginModify , c_NoEventData); Component.Rotation := Angle; Board.NewUndo(); // Update the Undo System PCBServer.SendMessageToRobots(Component.I_ObjectAddress, c_Broadcast, PCBM_EndModify , c_NoEventData); PCBServer.SendMessageToRobots(Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Component.I_ObjectAddress); Finally // Finalize the systems in the PCB Editor. PCBServer.PostProcess; End; Finally //Full PCB system update Board.ViewManager_FullUpdate; // Refresh PCB screen Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView); End; End;
unit uFractions; interface uses System.SysUtils; type TFraction = record strict private FNumerator: Integer; FDenominator: Integer; class function GCD(a, b: Integer): Integer; static; function Reduced: TFraction; public class function CreateFrom(aNumerator: Integer; aDenominator: Integer): TFraction; static; function ToString: string; property Numerator: Integer read FNumerator; property Denominator: Integer read FDenominator; class operator Add(const Left, Right: TFraction): TFraction; class operator Add(const Left: TFraction; const Right: double): double; class operator Subtract(const Left, Right: TFraction): TFraction; class operator Subtract(const Left: TFraction; const Right: Integer): TFraction; class operator Subtract(const Left: Integer; const Right: TFraction): TFraction; class operator Multiply(const Left, Right: TFraction): TFraction; class operator Multiply(const Left: TFraction; const Right: Integer): TFraction; class operator Multiply(const Left: Integer; const Right: TFraction): TFraction; class operator Divide(const Left, Right: TFraction): TFraction; class operator Divide(const Left: TFraction; const Right: Integer): TFraction; class operator Divide(const Left: Integer; const Right: TFraction): TFraction; class operator Positive(const AValue: TFraction): TFraction; class operator Negative(const AValue: TFraction): TFraction; class operator Equal(const Left, Right: TFraction): Boolean; class operator NotEqual(const Left, Right: TFraction): Boolean; class operator LessThan(const Left, Right: TFraction): Boolean; class operator GreaterThan(const Left, Right: TFraction): Boolean; class operator LessThanOrEqual(const Left, Right: TFraction): Boolean; class operator GreaterThanOrEqual(const Left, Right: TFraction): Boolean; class operator Implicit(const aValue: Integer): TFraction; class operator Implicit(const aValue: TFraction): Double; class operator Explicit(const aValue: TFraction): string; end; implementation { TFraction } class function TFraction.GCD(a, b: Integer): Integer; var rem: Integer; begin rem := a mod b; if rem <> 0 then Result := GCD(b, rem) else Result := b; end; function TFraction.Reduced: TFraction; var LGCD: Integer; begin LGCD := GCD(Numerator, Denominator); Result := CreateFrom(Numerator div LGCD, Denominator div LGCD); end; class operator TFraction.Add(const Left: TFraction; const Right: double): double; var LDouble: Double; begin LDouble := Left; Result := LDouble + Right; end; class function TFraction.CreateFrom(aNumerator, aDenominator: Integer): TFraction; begin if aDenominator = 0 then begin raise EZeroDivide.CreateFmt('Invalid fraction %d/%d, numerator cannot be zero', [aNumerator, aDenominator]); end; if (aDenominator < 0) then begin Result.FNumerator := -aNumerator; Result.FDenominator := -aDenominator; end else begin Result.FNumerator := aNumerator; Result.FDenominator := aDenominator; end; Assert(Result.Denominator > 0); // needed for comparisons end; function TFraction.ToString: string; begin Result := Format('%d/%d', [Numerator, Denominator]); end; class operator TFraction.Add(const Left, Right: TFraction): TFraction; begin Result := CreateFrom(Left.Numerator * Right.Denominator + Left.Denominator * Right.Numerator, Left.Denominator * Right.Denominator).Reduced; end; class operator TFraction.Subtract(const Left, Right: TFraction): TFraction; begin Result := Left + (-Right); end; class operator TFraction.Subtract(const Left: TFraction; const Right: Integer): TFraction; begin // Needed because the implicit Double coversion won't allow: Result := Left + (-Right); Result := Left + TFraction.CreateFrom(-Right, 1); end; class operator TFraction.Subtract(const Left: Integer; const Right: TFraction): TFraction; begin Result := Left + (-Right); end; class operator TFraction.Multiply(const Left, Right: TFraction): TFraction; begin Result := CreateFrom(Left.Numerator * Right.Numerator, Left.Denominator*Right.Denominator).Reduced; end; class operator TFraction.Multiply(const Left: TFraction; const Right: Integer): TFraction; begin Result := CreateFrom(Left.Numerator * Right, Left.Denominator).Reduced; end; class operator TFraction.Multiply(const Left: Integer; const Right: TFraction): TFraction; begin Result := CreateFrom(Left * Right.Numerator, Right.Denominator).Reduced; end; class operator TFraction.Divide(const Left, Right: TFraction): TFraction; begin Result := CreateFrom(Left.Numerator * Right.Denominator, Left.Denominator*Right.Numerator).Reduced; end; class operator TFraction.Divide(const Left: TFraction; const Right: Integer): TFraction; begin Result := CreateFrom(Left.Numerator, Left.Denominator * Right).Reduced; end; class operator TFraction.Divide(const Left: Integer; const Right: TFraction): TFraction; begin Result := CreateFrom(Left * Right.Denominator, Right.Numerator).Reduced; end; class operator TFraction.Positive(const AValue: TFraction): TFraction; begin Result := AValue; end; class operator TFraction.Negative(const AValue: TFraction): TFraction; begin Result := CreateFrom(-aValue.Numerator, AValue.Denominator); end; class operator TFraction.Equal(const Left, Right: TFraction): Boolean; begin Result := Left.Numerator * Right.Denominator = Right.Numerator * Left.Denominator; end; class operator TFraction.Explicit(const aValue: TFraction): string; begin Result := aValue.ToString; end; class operator TFraction.NotEqual(const Left, Right: TFraction): Boolean; begin Result := not (Left = Right); end; class operator TFraction.LessThan(const Left, Right: TFraction): Boolean; begin Result := Left.Numerator * Right.Denominator < Right.Numerator * Left.Denominator; end; class operator TFraction.GreaterThan(const Left, Right: TFraction): Boolean; begin Result := Left.Numerator*Right.Denominator > Right.Numerator*Left.Denominator; end; class operator TFraction.LessThanOrEqual(const Left, Right: TFraction): Boolean; begin Result := (Left < Right) or (Left = Right); end; class operator TFraction.GreaterThanOrEqual(const Left, Right: TFraction): Boolean; begin Result := (Left = Right) or (Left > Right); end; class operator TFraction.Implicit(const AValue: Integer): TFraction; begin Result := TFraction.CreateFrom(aValue, 1); end; class operator TFraction.Implicit(const aValue: TFraction): Double; begin Result := aValue.Numerator/aValue.Denominator; end; end.
unit fMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.Grids, Vcl.StdCtrls , Core.Interfaces , Core.BowlingGame ; type TfrmMain = class(TForm) alMain: TActionList; actStartGame: TAction; actRollBall: TAction; pScoreBoard: TPanel; pGameInputs: TPanel; Panel1: TPanel; actGetFrameScore: TAction; GroupBox1: TGroupBox; Button2: TButton; GroupBox3: TGroupBox; Label3: TLabel; edPinCount: TEdit; Button1: TButton; Label1: TLabel; edFrameNo: TEdit; GroupBox2: TGroupBox; Button3: TButton; edPlayerName: TEdit; Label2: TLabel; lblScoreRoll1: TLabel; edScoreRoll1: TEdit; lblScoreRoll2: TLabel; edScoreRoll2: TEdit; lblScoreRoll3: TLabel; edScoreRoll3: TEdit; lblScoreFrame: TLabel; procedure actStartGameExecute(Sender: TObject); procedure actRollBallExecute(Sender: TObject); procedure actGetFrameScoreExecute(Sender: TObject); private { Private declarations } FScoreBoardFrame: TFrame; FGame: IBowlingGame; public { Public declarations } constructor Create( AOwner: TComponent ); override; destructor Destroy; override; end; var frmMain: TfrmMain; implementation uses frmGameScoreBoard , Spring.Services ; {$R *.dfm} constructor TfrmMain.Create(AOwner: TComponent); begin inherited; FGame := ServiceLocator.GetService< IBowlingGame >; FScoreBoardFrame := TGameScoreBoardFrame.Create(Self, FGame); FScoreBoardFrame.Parent := pScoreBoard; FScoreBoardFrame.Align := alClient; end; destructor TfrmMain.Destroy; begin inherited; end; procedure TfrmMain.actStartGameExecute(Sender: TObject); begin FGame.StartGame(edPlayerName.Text); end; procedure TfrmMain.actRollBallExecute(Sender: TObject); begin FGame.RollBall(StrToIntDef(edPinCount.Text,0)); end; procedure TfrmMain.actGetFrameScoreExecute(Sender: TObject); var info: TFrameInfo; begin edScoreRoll1.Text := EmptyStr; edScoreRoll2.Text := EmptyStr; edScoreRoll3.Text := EmptyStr; info := FGame.GetScoreByFrame(StrToIntDef(edFrameNo.Text,1)); if info.Rolls.Count > 0 then edScoreRoll1.Text := info.Rolls[0].Pins.ToString; if info.Rolls.Count > 1 then edScoreRoll2.Text := info.Rolls[1].Pins.ToString; if info.Rolls.Count > 2 then edScoreRoll3.Text := info.Rolls[2].Pins.ToString; lblScoreFrame.Caption := info.FrameTotal.ToString; end; end.
{ Routines that handle BASE64 encoded data. } module string_base64; define string_t_base64; define string_f_base64; %include 'string2.ins.pas'; type b64chunk_t = array [1 .. 4] of char; {one chunk of BASE64 encoded characters} { ***************************************************************************** * * Local function ENCODE6 (I6) * * Return the low 6 bits of I6 as a single BASE64 encoded character. } function encode6 ( {encode 6 bits into one BASE64 character} in i6: sys_int_conv6_t) {low 6 bits will be encoded} :char; {BASE64 encoded character representing I6} val_param; internal; var v: sys_int_conv6_t; {the 0-63 integer value to encode} begin v := i6 & 63; {extract the 0-63 integer value to encode} if (v >= 0) and (v <= 25) then begin {0 - 25, upper case letter ?} encode6 := chr(ord('A') + v); return; end; if (v >= 26) and (v <= 51) then begin {26 - 51, lower case letter ?} encode6 := chr(ord('a') + v - 26); return; end; if (v >= 52) and (v <= 61) then begin {52 - 61, digit 0-9 ?} encode6 := chr(ord('0') + v - 52); return; end; if v = 62 then begin {62, "+"} encode6 := '+'; return; end; encode6 := '/'; {63, "?"} end; { ***************************************************************************** * * Local subroutine ENCODE24 (I24, SO) * * Encode the 24 bit value in I24 to the 4 character BASE64 string SO. } procedure encode24 ( {encode 24 bits into BASE64 format} in i24: sys_int_conv24_t; {24 bit input value} out so: b64chunk_t); {BASE64 output characters} val_param; internal; begin so[1] := encode6 (rshft(i24, 18)); so[2] := encode6 (rshft(i24, 12)); so[3] := encode6 (rshft(i24, 6)); so[4] := encode6 (i24); end; { ***************************************************************************** * * Subroutine STRING_T_BASE64 (SI, SO) * * Perform BASE64 encoding of a single string. SI is the input string * in clear text. SO is returned the value of the input string BASE64 * encoded. } procedure string_t_base64 ( {encode clear text string to BASE64} in si: univ string_var_arg_t; {input string, clear text} out so: univ string_var_arg_t); {output string, BASE64 encoded} val_param; var ch: b64chunk_t; {one chunk of 4 BASE64 encoded characters} i24: sys_int_conv24_t; {binary data for one chunk of BASE64 chars} nc: sys_int_machine_t; {number of input bytes in this chunk} il: sys_int_machine_t; {total number of input bytes remaining} p: string_index_t; {index of next input string character} i: sys_int_machine_t; {scratch loop counter} begin so.len := 0; {init output string to empty} i24 := 0; {prevent compiler warn about uninit var} il := si.len; {init num of input bytes left to be processed} p := 1; {init index of next input string character} while il > 0 do begin {loop until all input bytes exhausted} nc := 0; {init number of input bytes in this chunk} for i := 1 to 3 do begin {once for each input byte in this chunk} i24 := lshft(i24, 8); {make room for this new input byte} if p <= si.len then begin {an input byte exists for this slot ?} i24 := i24 ! ord(si.str[p]); {merge char into value for this chunk} p := p + 1; {advance index to next input byte} nc := nc + 1; {count one more input byte in this chunk} end; end; {back for next input byte in this chunk} encode24 (i24, ch); {encode 24 bit chunk into 4 characters} case nc of {how many input bytes in this chunk ?} 1: begin {1 input byte in this chunk} string_appendn (so, ch, 2); {2 encoded output characters} string_appendn (so, '==', 2); {2 pad characters} return; end; 2: begin {2 input bytes in this chunk} string_appendn (so, ch, 3); {3 encoded output characters} string_append1 (so, '='); {1 pad character} return; end; otherwise {assume all 3 input bytes valid this chunk} string_appendn (so, ch, 4); {4 encoded output characters} end; il := il - 3; {count less input characters left to process} end; {back to do next chunk} end; { ***************************************************************************** * * Local subroutine DECODE8 (E, D, VALID) * * Decode one BASE64 encoded character. E is the encoded character. D * is its returned 0 - 63 value. VALID is returned TRUE when E is a valid * BASE64 character representing a 0 to 63 value. D is returned 0 whenever * VALID is returned FALSE. } procedure decode8 ( {decode one BASE64 encoded character} in e: char; {BASE64 encoded input character} out d: sys_int_conv6_t; {returned 6 bit value for this character} out valid: boolean); {TRUE if E was valid 0 to 63 BASE64 character} val_param; internal; begin valid := true; {init to input characte is valid} if (e >= 'A') and (e <= 'Z') then begin {upper case letter, 0 - 25 ?} d := ord(e) - ord('A'); return; end; if (e >= 'a') and (e <= 'z') then begin {lower case letter, 26 - 51 ?} d := ord(e) - ord('a') + 26; return; end; if (e >= '0') and (e <= '9') then begin {decimal digit, 52 - 61 ?} d := ord(e) - ord('0') + 52; return; end; case ord(e) of {check for remaining individual cases} ord('+'): d := 62; ord('/'): d := 63; otherwise {not a valid BASE64 0-63 character} d := 0; valid := false; end; end; { ***************************************************************************** * * Subroutine STRING_F_BASE64 (SI, SO) * * Perform BASE64 decoding on a single string. SI is the input string in * BASE64 encoded format. SO is returned the decoded clear text string * represented by SI. * * All invalid characters in SI are silently ignored. } procedure string_f_base64 ( {decode BASE64 string to clear text} in si: univ string_var_arg_t; {input string, one BASE64 encoded line} out so: univ string_var_arg_t); {output string, clear text} val_param; var p: string_index_t; {input string reading index} i24: sys_int_conv24_t; {value for one BASE64 chunk of 4 chars} nc: sys_int_machine_t; {number of input chars found in curr chunk} i6: sys_int_conv6_t; {value of one decoded BASE64 character} c: char; {scratch character} valid: boolean; {was valid 0-63 BASE64 character} label loop_chunk; begin so.len := 0; {init output string to empty} p := 1; {init input string read index} loop_chunk: {back here each new BASE64 chunk of 4 chars} nc := 0; {init number of input chars in this chunk} while nc < 4 do begin {loop until get all input chars this chunk} if p > si.len then exit; {input string exhausted ?} c := si.str[p]; {get this input character} p := p + 1; {advance index to next input character} decode8 (c, i6, valid); {decode this input character} if valid then begin {input char was valid BASE64 0-63} i24 := lshft(i24, 6) ! i6; {merge result of this char into 24 bit value} nc := nc + 1; {count one more valid input character} end else begin {input char was not valid BASE64 0-63} if c = '=' then exit; {end chunk on special BASE64 pad character} end ; end; {back to get next input char this chunk} case nc of {how many input characters in this chunk ?} 2: begin {2 valid input characters, 12 bits decoded} string_append1 (so, chr(rshft(i24, 4) & 255)); {one decoded byte this chunk} end; 3: begin {3 valid input characters, 18 bits decoded} string_append1 (so, chr(rshft(i24, 10) & 255)); {two decoded bytes this chunk} string_append1 (so, chr(rshft(i24, 2) & 255)); end; 4: begin {full input chunk, 24 bits decoded} string_append1 (so, chr(rshft(i24, 16) & 255)); {three decoded bytes this chunk} string_append1 (so, chr(rshft(i24, 8) & 255)); string_append1 (so, chr(i24 & 255)); goto loop_chunk; {back and try to decode another chunk} end; end; {end of number of input chars in chunk cases} end;
{ DocuGes - Gestion Documental Autor: Fco. Javier Perez Vidal <developer at f-javier dot es> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit menu; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, Menus, PrintersDlgs, Process; type { Tfmenu } Tfmenu = class(TForm) MainMenu1: TMainMenu; MenuArchivo: TMenuItem; MenuAyuda: TMenuItem; Linea11: TMenuItem; MenuConfigurarImpresora: TMenuItem; MenuAcercaDe: TMenuItem; MenuGrupos: TMenuItem; MenuConexion: TMenuItem; Menuconectar: TMenuItem; MenuActBBDD: TMenuItem; MenuCopiaSeg: TMenuItem; MenuUtilidades: TMenuItem; MenuTipos: TMenuItem; MenuSubGrupos: TMenuItem; Linea21: TMenuItem; MenuDocumentos: TMenuItem; MenuMaestros: TMenuItem; MenuSalir: TMenuItem; Linea12: TMenuItem; Linea13: TMenuItem; PrinterSetupDialog1: TPrinterSetupDialog; procedure FormCreate(Sender: TObject); procedure MenuAcercaDeClick(Sender: TObject); procedure MenuActBBDDClick(Sender: TObject); procedure MenuConexionClick(Sender: TObject); procedure MenuConfigurarImpresoraClick(Sender: TObject); procedure MenuCopiaSegClick(Sender: TObject); procedure MenuDocumentosClick(Sender: TObject); procedure MenuGruposClick(Sender: TObject); procedure MenuconectarClick(Sender: TObject); procedure MenuSalirClick(Sender: TObject); procedure MenuSubGruposClick(Sender: TObject); procedure MenuTiposClick(Sender: TObject); private { private declarations } public { public declarations } end; var fmenu: Tfmenu; implementation { Tfmenu } uses aboutbox, conexion, grupos, subgrupos, tipos, documentos, recursostexto, datos, copiaseg; procedure Tfmenu.MenuSalirClick(Sender: TObject); begin Application.Terminate; end; procedure Tfmenu.MenuSubGruposClick(Sender: TObject); begin fSubGrupos := TfSubGrupos.Create(Application); fSubGrupos.ShowModal; end; procedure Tfmenu.MenuTiposClick(Sender: TObject); begin fTipos := TfTipos.Create(Application); fTipos.ShowModal; end; procedure Tfmenu.MenuGruposClick(Sender: TObject); begin fGrupos := TfGrupos.Create(Application); fGrupos.ShowModal; end; procedure Tfmenu.MenuconectarClick(Sender: TObject); begin conectarservidor; end; procedure Tfmenu.MenuDocumentosClick(Sender: TObject); begin fDocumentos := TfDocumentos.Create(Application); fDocumentos.ShowModal; end; procedure Tfmenu.MenuConfigurarImpresoraClick(Sender: TObject); begin PrinterSetupDialog1.Execute; end; procedure Tfmenu.MenuCopiaSegClick(Sender: TObject); begin fCopiaSeg := TfCopiaSeg.Create(Application); fCopiaSeg.ShowModal; end; procedure Tfmenu.MenuAcercaDeClick(Sender: TObject); begin fAboutBox := TfAboutBox.Create(Application); fAboutBox.ShowModal; end; procedure Tfmenu.MenuActBBDDClick(Sender: TObject); var Aprocess: TProcess; begin AProcess := TProcess.Create(nil); {$IFDEF LINUX} AProcess.CommandLine := 'gksu '+ExtractFilePath(ParamStr(0))+'actbbdd'; {$ELSE} AProcess.CommandLine := ExtractFilePath(ParamStr(0))+'actbbdd'; {$ENDIF} AProcess.Execute; AProcess.Free; end; procedure Tfmenu.FormCreate(Sender: TObject); begin ShortDateFormat:='DD/MM/YYYY'; DecimalSeparator:='.'; DirectorioAplicacion:=ExtractFilePath(ParamStr(0)); DirectorioFicheroINI:=DirectorioAplicacion + 'opciones.ini'; DirectorioDocumentos:=DirectorioAplicacion + 'documentos'; end; procedure Tfmenu.MenuConexionClick(Sender: TObject); begin fConexion:=TfConexion.Create(Application); fConexion.ShowModal; end; initialization {$I menu.lrs} end.
unit UnitTVAMSignUp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, jpeg, ExtCtrls; type TFrmRegister = class(TForm) ImgLogo: TImage; LblRegisterTtl: TLabel; BtnNewStudent: TButton; btnExistingStudent: TButton; lblStudMemb: TLabel; lblStudName: TLabel; lblStudTag: TLabel; edtStudMemb: TEdit; edtStudName: TEdit; edtStudTag: TEdit; lblStudDet: TLabel; btnCheckSlots: TButton; procedure BtnNewStudentClick(Sender: TObject); procedure btnExistingStudentClick(Sender: TObject); procedure btnCheckSlotsClick(Sender: TObject); private { Private declarations } public end; Type Lesson = Record LessonNumber : Integer; StartTime : String[5]; LessonDate : String[8]; Instructor : Integer; Student : Integer; end; type Student = Record MembershipNumber : Integer; Name : String[25]; TagName : String[25]; Age : Integer; Experience : Integer; RegistrationNumber : String[7]; Gender : String[6]; NumberofReturnVisits : Integer; NumberOfBikesRecorded : Integer; End; var FrmRegister: TFrmRegister; StudentFile : file of Student; LessonFile : file of Lesson; Identity : Student; TimeSlot : Lesson; implementation uses UnitNewStudent; {$R *.dfm} procedure TFrmRegister.btnCheckSlotsClick(Sender: TObject); Type LessonTime = Record LessonNumber : Integer; LessonDate : String[8]; StartTime : String[5]; Instructor : Integer; Student : Integer; end; Var LessonFile : file of LessonTime; TimeSlot : LessonTime; SlotFound : Boolean; LessonSearch, DateSearch : String; Str, dt : String; begin if EdtStudMemb.Text <> '' then begin SlotFound := False; Assignfile (LessonFile, 'LessonData.dat'); reset (LessonFile); str := '09:00'; dt := '00/00/00'; DateSearch := InputBox('Desired Lesson Date', 'Please enter the date on which you would like to have your lesson:', dt); ShowMessage('Lessons occur at thirty minute intervals between 9 am and Noon'); LessonSearch := InputBox('Desired Lesson Time', 'Please enter the timeslot in which you would like to have your lesson:', str); while not eof (LessonFile) and not SlotFound do begin read(lessonFile,timeslot); with TimeSlot do begin if (StartTime = LessonSearch) and (LessonDate = DateSearch) then begin SlotFound := True; if Student = 00000000 then Begin ShowMessage('This slot is free, we look forward to seeing you at the time of the lesson.'); Student := StrtoInt(edtStudMemb.Text); End else ShowMessage('We are sorry, but this time slot is currently occupied, please try again with a different time slot.'); end; end; end; if not SlotFound then ShowMessage('We are sorry, but this time slot is unavilable, please try again with a different time slot.'); closefile(LessonFile); end else ShowMessage('You have yet to declare your student details, please refer to either the existing student or new student sections of this page to declare your details before signing up for a lesson.'); end; procedure TFrmRegister.btnExistingStudentClick(Sender: TObject); Type Student = Record MembershipNumber : Integer; Name : String[25]; TagName : String[25]; Age : Integer; Experience : Integer; RegistrationNumber : String[7]; Gender : String[6]; NumberofReturnVisits : Integer; NumberOfBikesRecorded : Integer; end; var StudentSearch : Integer; StudentFile : file of Student; Identity : Student; Found : Boolean; s : String; begin Found := False; Assignfile (StudentFile, 'StudentData.dat'); reset (StudentFile); s := '00000000'; StudentSearch := StrtoInt(InputBox('Identity Input', 'Please enter your membership number:', s)); while not eof (StudentFile) and not found do begin read(StudentFile,Identity); with Identity do begin if MembershipNumber = StudentSearch then begin Found := true; edtStudMemb.Text := InttoStr(MembershipNumber); edtStudName.Text := Name; edtStudTag.Text := TagName; end; end; end; if not found then ShowMessage('There is no record of that membership number.'); closefile(StudentFile); end; procedure TFrmRegister.BtnNewStudentClick(Sender: TObject); begin FrmNewStudent.ShowModal; end; end.
{ Copyright 2020 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2020-June-26 Darian Miller: Unit created } unit iaVCL.StyleFileList; interface uses System.Generics.Collections; type TiaVCLStyleFile = class private fSourceFileName:string; fStyleName:string; fAuthor:string; fAuthorEMail:string; fAuthorURL:string; fVersion:string; public property SourceFileName:string read fSourceFileName write fSourceFileName; property StyleName:string read fStyleName write fStyleName; property Author:string read fAuthor write fAuthor; property AuthorEMail:string read fAuthorEMail write fAuthorEMail; property AuthorURL:string read fAuthorURL write fAuthorURL; property Version:string read fVersion write fVersion; end; TiaVCLStyleFileList = class(TObjectList<TiaVCLStyleFile>) public const defVCLStyleSearchPattern = '*.vsf'; public procedure SetListFromPath(const pPath:string; const pSearchPattern:string=defVCLStyleSearchPattern); end; implementation uses System.IOUtils, System.SysUtils, System.Types, VCL.Themes; procedure TiaVCLStyleFileList.SetListFromPath(const pPath:string; const pSearchPattern:string=defVCLStyleSearchPattern); var vFiles:TStringDynArray; vStyleFileName:string; vStyleFile:TiaVCLStyleFile; vStyleInfo:TStyleInfo; begin Clear; if TDirectory.Exists(pPath) then begin vFiles := TDirectory.GetFiles(pPath, pSearchPattern); for vStyleFileName in vFiles do begin if TStyleManager.IsValidStyle(vStyleFileName, vStyleInfo) then begin vStyleFile := TiaVCLStyleFile.Create(); vStyleFile.SourceFileName := vStyleFileName; vStyleFile.StyleName := vStyleInfo.Name; vStyleFile.Author := vStyleInfo.Author; vStyleFile.AuthorEMail := vStyleInfo.AuthorEMail; vStyleFile.AuthorURL := vStyleInfo.AuthorURL; vStyleFile.Version := vStyleInfo.Version; Add(vStyleFile); end; end; end; end; end.
unit Unit2; interface uses Windows, SysUtils, Graphics, ExtCtrls; type TRectangle = class procedure MoveTo(dx, dy, dr: integer); constructor Create(x0, y0, r0: word; Image0: TImage; ColorLine0: TColor); private ColorLine: TColor; Image: TImage; x, y, r: word; procedure Show; procedure Hide; procedure Draw; virtual; end; TExtremity = class(TRectangle) constructor Create(x0, y0, r0: word; Image0: TImage; ColorLine0: TColor); private point: array of TPoint; procedure Draw; override; end; TArms = class(TExtremity) constructor Create(x0, y0, r0: word; Image0: TImage; ColorLine0: TColor); procedure Honor; private procedure Draw; override; procedure ArmsDraw(bl: Boolean = false); end; implementation procedure TRectangle.Show; begin Image.Canvas.Pen.Color := clBlack; Draw; end; procedure TRectangle.Hide; begin Image.Canvas.Pen.Color := clWhite; Draw; end; procedure TRectangle.MoveTo; begin Hide; x := x + dx; y := y + dy; r := r + dr; Show; end; procedure TRectangle.Draw; begin Image.Canvas.Rectangle(x - r, y - 2*r, x + r + 1, y + 2*r); end; procedure TExtremity.Draw; begin inherited Draw; with Image.Canvas do begin Brush.Color:=clYellow; Ellipse(x - r, y - 4*r, x + r, y - 2*r); Brush.Color:=clWhite; point[0].X := x - 2*r; point[0].Y := y + 6*r; point[1].X := x - r; point[1].Y := y + 6 * r; point[2].X := x - r; point[2].Y := y + 2 * r; point[3].X := x + r; point[3].Y := y + 2 * r; point[4].X := x + r; point[4].Y := y + 6 * r; point[5].X := x + 2 * r; point[5].Y := y + 6 * r; Polyline(point); end; end; procedure TArms.ArmsDraw; var t: byte; begin point[0].X := x - r - 1; point[0].Y := y; point[1].X := x - 2*r - 1; point[1].Y := y - r; point[2].X := x - r; point[2].Y := y - 2*r; point[3].X := x + r; point[3].Y := y - 2*r; point[4].X := x + 2*r; point[4].Y := y - r; point[5].X := x + r; point[5].Y := y; Image.Canvas.Polyline(point); if bl then begin t := trunc(r/10); while point[0].Y > (y - 3*r) do begin Image.Canvas.Pen.Color := clWhite; Image.Canvas.Polyline(point); point[0].Y := point[0].Y - 2*t; //Не работает! point[1].Y := point[1].Y - t; Image.Canvas.Pen.Color := clBlack; Image.Canvas.Polyline(point); Image.Update; sleep(100); end; sleep(500); while point[0].Y < y do //нехватка времени и фантазии заставляет выбирать наибыстрейшие пути решения проблемы. begin Image.Canvas.Pen.Color := clWhite; Image.Canvas.Polyline(point); point[0].Y := point[0].Y + 2*t; //Не работает! point[1].Y := point[1].Y + t; Image.Canvas.Pen.Color := clBlack; Image.Canvas.Polyline(point); Image.Update; sleep(100); end; ArmsDraw; end; end; procedure TArms.Draw; begin inherited Draw; ArmsDraw; end; procedure TArms.Honor; begin ArmsDraw(true); end; constructor TRectangle.Create; begin inherited Create; x := x0; y := y0; r := r0; Image := Image0; ColorLine := ColorLine0; end; constructor TExtremity.Create; begin inherited Create(x0, y0, r0, Image0, ColorLine0); SetLength(point, 6); end; constructor TArms.Create; begin inherited Create(x0, y0, r0, Image0, ColorLine0); Draw; end; end.
unit uCefRenderProcessMessageReceiver; interface uses System.SysUtils, System.Generics.Collections, // uCEFApplication, uCefTypes, uCefInterfaces; type TCefRenderProcessMessageReceiver = class private protected FName: string; //--- procedure Receive(const ABrowser: ICefBrowser; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; var AHandled: boolean); virtual; public constructor Create(const AName: string); destructor Destroy; override; end; procedure CefAppRenderProcessMessageInit; procedure CefAppRenderProcessMessageReceiverAdd(const A: TCefRenderProcessMessageReceiver); implementation type TCefRenderProcessMessageReceiverOwner = class private FHandlers: TObjectList<TCefRenderProcessMessageReceiver>; //--- procedure Receive(const ABrowser: ICefBrowser; const AFrame: ICefFrame; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; var AHandled : boolean); public constructor Create; destructor Destroy; override; //--- procedure InitCefGlobalApp; procedure AddRceiver(const A: TCefRenderProcessMessageReceiver); end; var gReceiver: TCefRenderProcessMessageReceiverOwner; procedure CefAppRenderProcessMessageInit; begin gReceiver.InitCefGlobalApp() end; procedure CefAppRenderProcessMessageReceiverAdd(const A: TCefRenderProcessMessageReceiver); begin gReceiver.AddRceiver(A) end; { TCefRenderProcessMessageReceiverOwner } procedure TCefRenderProcessMessageReceiverOwner.AddRceiver( const A: TCefRenderProcessMessageReceiver); begin FHandlers.Add(A) end; constructor TCefRenderProcessMessageReceiverOwner.Create; begin FHandlers := TObjectList<TCefRenderProcessMessageReceiver>.Create(True); InitCefGlobalApp(); end; destructor TCefRenderProcessMessageReceiverOwner.Destroy; begin if Assigned(GlobalCEFApp) then GlobalCEFApp.OnProcessMessageReceived := nil; FHandlers.Free; inherited; end; procedure TCefRenderProcessMessageReceiverOwner.InitCefGlobalApp; begin if Assigned(GlobalCEFApp) then begin GlobalCEFApp.OnProcessMessageReceived := Self.Receive; //TODO: release callback list uCefCallbackList.pas // GlobalCEFApp.OnContextReleased := release callback list ? end; end; procedure TCefRenderProcessMessageReceiverOwner.Receive(const ABrowser: ICefBrowser; const AFrame: ICefFrame; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; var AHandled : boolean); var H: TCefRenderProcessMessageReceiver; begin for H in FHandlers do begin if H.FName = AMessage.Name then begin H.Receive(ABrowser, ASourceProcess, AMessage, AHandled); if AHandled then Exit() end; end; AHandled := False end; { TCefRenderProcessMessageReceiver } constructor TCefRenderProcessMessageReceiver.Create(const AName: string); begin FName := AName end; destructor TCefRenderProcessMessageReceiver.Destroy; begin inherited; end; procedure TCefRenderProcessMessageReceiver.Receive(const ABrowser: ICefBrowser; ASourceProcess: TCefProcessId; const AMessage: ICefProcessMessage; var AHandled: boolean); begin AHandled := False; end; initialization gReceiver := TCefRenderProcessMessageReceiverOwner.Create; finalization FreeAndNil(gReceiver) end.
unit SetArrg; interface uses Windows, Messages, Classes, SetBtn, SLBtns, SysUtils, SetPlug, Forms; type // ボタンコントロールとデータ TButtonItem = class(TObject) ButtonData: TButtonData; SLButton: TSLNormalButton; Line: TList; destructor Destroy; override; end; // ボタン配置 TButtonArrangement = class(TObject) private FOwner: TForm; FLines: TList; FItems: TList; FButtonGroup: TButtonGroup; FCols: Integer; FActive: Boolean; FOnArranged: TNotifyEvent; FCurrentIndex: Integer; FCurrentSLButton: TSLNormalButton; function GetGrid(ACol, ARow: Integer): TButtonItem; function GetItem(Index: Integer): TButtonItem; procedure SetButtonGroup(Value: TButtonGroup); procedure SetCols(Value: Integer); function GetRows: Integer; procedure SetActive(Value: Boolean); procedure IndexRevision; procedure SetCurrentIndex(Value: Integer); function GetCurrentIndex: Integer; function GetCurrentItem: TButtonItem; function GetCurrentCol: Integer; function GetCurrentRow: Integer; public property Owner: TForm read FOwner write FOwner; property Grid[ACol, ARow: Integer]: TButtonItem read GetGrid; default; property Items[Index: Integer]: TButtonItem read GetItem; property ButtonGroup: TButtonGroup read FButtonGroup write SetButtonGroup; property Cols: Integer read FCols write SetCols; property Rows: Integer read GetRows; property Active: Boolean read FActive write SetActive; property CurrentIndex: Integer read GetCurrentIndex write SetCurrentIndex; property CurrentItem: TButtonItem read GetCurrentItem; property CurrentCol: Integer read GetCurrentCol; property CurrentRow: Integer read GetCurrentRow; property OnArranged: TNotifyEvent read FOnArranged write FOnArranged; constructor Create; destructor Destroy; override; procedure Clear; procedure Arrange; function IndexOfItem(Item: TButtonItem): Integer; end; implementation // // TButtonItem ///////////////////////////////// // デストラクタ destructor TButtonItem.Destroy; begin SLButton.Free; inherited; end; // // TButtonArrangement ///////////////////////////////// // コンストラクタ constructor TButtonArrangement.Create; begin inherited; FLines := TList.Create; FItems := TList.Create; FButtonGroup := nil; FCurrentIndex := -1; FCurrentSLButton := nil; end; // デストラクタ destructor TButtonArrangement.Destroy; begin Clear; FLines.Free; FItems.Free; inherited; end; // ボタングループセット procedure TButtonArrangement.SetButtonGroup(Value: TButtonGroup); begin if Value = FButtonGroup then Exit; FButtonGroup := Value; Arrange; CurrentIndex := 0; end; // 幅セット procedure TButtonArrangement.SetCols(Value: Integer); begin if Value = FCols then Exit; if Value < 0 then Value := 0; FCols := Value; Arrange; end; // 行数ゲット function TButtonArrangement.GetRows: Integer; begin Result := FLines.Count; end; // 指定座標のButtonItemを取得 function TButtonArrangement.GetGrid(ACol, ARow: Integer): TButtonItem; var Line: TList; begin Result := nil; if (ARow >= 0) and (ARow < FLines.Count) then begin Line := FLines[ARow]; if (ACol >= 0) and (ACol < Line.Count) then Result := Line[ACol]; end; end; // 指定インデックスのButtonItemを取得 function TButtonArrangement.GetItem(Index: Integer): TButtonItem; begin Result := nil; if (Index >= 0) and (Index < FItems.Count) then Result := FItems[Index]; end; // アクティブになる procedure TButtonArrangement.SetActive(Value: Boolean); var i, j: Integer; Line: TList; Item: TButtonItem; begin if FActive = Value then Exit; FActive := Value; for i := 0 to FLines.Count - 1 do begin Line := FLines[i]; for j := 0 to Line.Count - 1 do begin Item := Line[j]; if Item.SLButton <> nil then Item.SLButton.Active := Value; end; end; end; // クリア procedure TButtonArrangement.Clear; var i: Integer; Plugin: TPlugin; begin // プラグインに開放を通知 for i := 0 to FItems.Count - 1 do begin if Items[i].ButtonData is TPluginButton then begin Plugin := Plugins.FindPlugin(TPluginButton(Items[i].ButtonData).PluginName); if Plugin <> nil then if @Plugin.SLXButtonDestroy <> nil then Plugin.SLXButtonDestroy(TPluginButton(Items[i].ButtonData).No, Owner.Handle, i); end; end; FCurrentSLButton := nil; for i := 0 to FItems.Count - 1 do Items[i].Free; FItems.Clear; for i := 0 to FLines.Count - 1 do TList(FLines[i]).Free; FLines.Clear; end; // 再配置 procedure TButtonArrangement.Arrange; function ItemCreate(Index: Integer; ButtonData: TButtonData): TButtonItem; begin Result := TButtonItem.Create; Result.ButtonData := ButtonData; if ButtonData is TNormalButton then begin Result.SLButton := TSLNormalButton.Create(nil); Result.SLButton.Tag := Index; end else if ButtonData is TPluginButton then begin Result.SLButton := TSLPluginButton.Create(nil); Result.SLButton.Tag := Index; end else Result.SLButton := nil; end; var i: Integer; ButtonData: TButtonData; Line: TList; Item: TButtonItem; Plugin: TPlugin; begin Clear; if (FButtonGroup <> nil) and (FCols > 0) then begin Line := nil; for i := 0 to FButtonGroup.Count - 1 do begin ButtonData := FButtonGroup[i]; Item := ItemCreate(i, ButtonData); FItems.Add(Item); if Line = nil then begin Line := TList.Create; FLines.Add(Line); end; if ButtonData is TReturnButton then begin Line.Add(Item); Item.Line := Line; Line := nil; end else begin if Line.Count >= FCols then begin Line := TList.Create; FLines.Add(Line); end; Line.Add(Item); Item.Line := Line; end; end; // プラグインに作成を通知 for i := 0 to FItems.Count - 1 do begin if Items[i].ButtonData is TPluginButton then begin Plugin := Plugins.FindPlugin(TPluginButton(Items[i].ButtonData).PluginName); if Plugin <> nil then begin if @Plugin.SLXButtonCreate <> nil then Plugin.SLXButtonCreate(TPluginButton(Items[i].ButtonData).No, Owner.Handle, i); end; end; end; end; CurrentIndex := CurrentIndex; if Assigned(FOnArranged) then FOnArranged(Self); end; // インデックスを修正する procedure TButtonArrangement.IndexRevision; var i, NewIndex: Integer; begin NewIndex := -1; if FButtonGroup = nil then Exit; // 前方へ修正 i := FCurrentIndex; while (i >= 0) and (NewIndex = -1) do begin if i < FButtonGroup.Count then if (FButtonGroup[i] is TNormalButton) or (FButtonGroup[i] is TPluginButton) then NewIndex := i; Dec(i); end; // 後方へ修正 i := FCurrentIndex + 1; while (i < FButtonGroup.Count) and (NewIndex = -1) do begin if i >= 0 then if (FButtonGroup[i] is TNormalButton) or (FButtonGroup[i] is TPluginButton) then NewIndex := i; Inc(i); end; FCurrentIndex := NewIndex; end; // カレントインデックスセット procedure TButtonArrangement.SetCurrentIndex(Value: Integer); var Item: TButtonItem; begin FCurrentIndex := Value; IndexRevision; if FCurrentSLButton <> nil then FCurrentSLButton.Selected := False; FCurrentSLButton := nil; Item := CurrentItem; if Item <> nil then if Item.SLButton <> nil then begin FCurrentSLButton := Item.SLButton; FCurrentSLButton.Selected := True; end; end; // カレントインデックス取得 function TButtonArrangement.GetCurrentIndex: Integer; begin IndexRevision; Result := FCurrentIndex; end; // カレントアイテム取得 function TButtonArrangement.GetCurrentItem: TButtonItem; begin Result := Items[CurrentIndex]; end; // カレント列取得 function TButtonArrangement.GetCurrentCol: Integer; var Item: TButtonItem; begin Item := CurrentItem; if Item = nil then Result := -1 else Result := Item.Line.IndexOf(Item); end; // カレント行取得 function TButtonArrangement.GetCurrentRow: Integer; var Item: TButtonItem; begin Item := CurrentItem; if Item = nil then Result := -1 else Result := FLines.IndexOf(Item.Line); end; // 指定のアイテムのインデックスを返す function TButtonArrangement.IndexOfItem(Item: TButtonItem): Integer; begin Result := FItems.IndexOf(Item); end; end.
unit DMCommon; interface uses IIConsts, System.Classes, dxLayoutLookAndFeels, System.ImageList, Vcl.ImgList, {$IFDEF VIRTUALUI} VirtualUI_SDK, {$ENDIF} Vcl.Controls, cxControls, cxGraphics, WUpdate, cxLookAndFeels, dxSkinsForm, cxClasses, cxLocalization, RemoteDB.Client.Dataset, RemoteDB.Client.Database, gmClientDataset, cxGridDBDataDefinitions, cxRichEdit, cxProgressBar, cxGridDBTableView, Vcl.ExtCtrls, cxCustomData, Generics.Collections, cxGridCustomView, Winapi.Windows, Data.DB, CustomDataSetParams, dxSkinsCore, FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.UI.Intf, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.Phys.SQLite, dxPSGlbl, dxPSUtl, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPgsDlg, dxPSCore, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, IdHTTPWebsocketClient, gmWebSocket, cxDBPivotGrid; type {.$DEFINE SKIN1} {$DEFINE SKIN2} TFDMCommon = class; TDataSetParams = class(TCustomDataSetParams) private FParams: TFDMCommon; // DataModule where the dataset is located public function DataSet: TDataSet; override; function CompanyField: TField; override; function UserField: TField; override; function BlobField: TBlobField; override; function NameField: TField; override; function ValueField: TField; override; {JRT} function WorkstationField: TField; override; {} procedure Open; override; end; TFDMCommon = class(TDataModule) cxLocalizer1: TcxLocalizer; dxSkinController: TdxSkinController; WebUpdate1: TWebUpdate; cxImageFlatMenu: TcxImageList; cxImageNavigator16: TcxImageList; dxLayoutLookAndFeelList: TdxLayoutLookAndFeelList; dxLayoutSkinLookAndFeel1: TdxLayoutSkinLookAndFeel; gmDatabase: TgmDatabase; qParamDataset: TgmClientDataset; qReportId: TgmClientDataset; qReportIditem_id: TAutoIncField; cxImageNavigator32: TcxImageList; qParamDatasetNome: TStringField; qParamDatasetValore: TStringField; qParamDatasetCompany: TGuidField; qParamDatasetUser_Id: TGuidField; qParamDatasetData: TBlobField; qParamDatasetpkParam: TAutoIncField; qParamDatasetWorkstation: TStringField; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; dxPrintStyleManager1: TdxPrintStyleManager; dxPrintStyleManager1Style1: TdxPSPrintStyle; dxPageSetupDialog1: TdxPageSetupDialog; gmWebsocketClient: TgmWebsocketClient; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure WebUpdate1AppDoClose(Sender: TObject); procedure WebUpdate1AppRestart(Sender: TObject; var Allow: Boolean); procedure WebUpdate1FileProgress(Sender: TObject; FileName: string; Pos, Size: Integer); procedure WebUpdate1Status(Sender: TObject; StatusStr: string; StatusCode, ErrCode: Integer); procedure WebUpdate1Success(Sender: TObject); procedure WebUpdate1Progress(Sender: TObject; Action: string); procedure WebUpdate1BeforeFileDownload(Sender: TObject; FileIdx: Integer; FileDescription: string; var URL: string); private { Private declarations } // FIniFile: TIniFile; FIsConnected: boolean; FSkinSelected: string; // FmMenu: TfrmBaseMainMenu; FDataController: TcxGridDBDataController; // FManager: TObjectManager; FpnlUpgrade: TPanel; FreUpgrade: TcxRichEdit; FcxProgressUpdate: TcxProgressBar; // FBaseController: TdmTabelleBaseController; // FBaseControllerLoaded: boolean; FImgList: TcxImageList; FRealDPI: integer; {$IFDEF VIRTUALUI} FVirtualUI: TVirtualUI; function GetVirtualUI: TVirtualUI; {$ENDIF} procedure GetSelectedKeyValues(ADataController: TcxGridDBDataController); procedure AddKeyFieldValueToList(ARowIndex: Integer; ARowInfo: TcxRowInfo); function CheckConnect: boolean; procedure Connect; public { Public declarations } FKeyFieldList: TList<string>; // TStringList; procedure GetSelectedIDs(Grid: TcxGridDBTableView); function GetRealDragSourceGridView(const aSource: TObject): TcxGridDBTableView; function GetDragSourceGridView(const aSource: TObject): TcxGridDBTableView; function vLocate(Grid: TcxGridDBTableView; pkKey: Integer): boolean; function GetMasterRecordID(AView: TcxCustomGridView): Integer; procedure Update; procedure SelectSkin(pSkin: integer); function VarIsNumericZero(const AValue: Variant): Boolean; function GetReportId(const repName: string): string; function VarToInt(const AVariant: Variant): integer; procedure DetailFirst(ADataSet: TDataSet; const AMasterDetailKeyFieldNames: String; const AMasterDetailKeyValues: Variant; var AReopened: Boolean); function DetailIsCurrentQuery(ADataSet: TDataSet; const AMasterDetailKeyFieldNames: String; const AMasterDetailKeyValues: Variant): Boolean; procedure ApplicaDataFine(xView: TcxGridDBTableView; xColumn: TcxGridDBColumn); function gmStrToFloat(const S: string): Extended; procedure SaveDevExObjConfiguration(pDevExObj: TcxControl); procedure RestoreDevExObjConfiguration(pDevExObj: TcxControl); procedure PivotGridExpandAll(pPivotGrid: TcxDBPivotGrid); const {$IFDEF SKIN1} SkinNames: array[0..1] of string = ('Metropolis', 'MetropolisDark'); {$ENDIF} {$IFDEF SKIN2} SkinNames: array[0..1] of string = ('VisualStudio2013Blue','Office2016Colorful'); {$ENDIF} // property Manager: TObjectManager read FManager; property pnlUpgrade: TPanel read FpnlUpgrade write FpnlUpgrade; property reUpgrade: TcxRichEdit read FreUpgrade write FreUpgrade; property cxProgressUpdate: TcxProgressBar read FcxProgressUpdate write FcxProgressUpdate; // property BaseController: TdmTabelleBaseController read FBaseController write FBaseController; // property BaseControllerLoaded: boolean read FBaseControllerLoaded write FBaseControllerLoaded; // property mMenu: TfrmBaseMainMenu read FmMenu write FmMenu; property SkinSelected: string read FSkinSelected write FSkinSelected; property IsConnected: boolean read FIsConnected; property ImgList: TcxImageList read FImgList; property RealDPI: integer read FRealDPI; {$IFDEF VIRTUALUI} property IVirtualUI: TVirtualUI read GetVirtualUI; {$ENDIF} end; var FDMCommon: TFDMCommon; procedure PostKeyEx( hWindow: HWnd; key: Word; Const shift: TShiftState; specialkey: Boolean ); function StrToWord(const Value: String): Word; function IIfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; overload; function IIfThen(AValue: Boolean; const ATrue: integer; const AFalse: integer): integer; overload; resourcestring nfsConfermaRicreazioneDibaProd = 'Confermi il ricalcolo della Distinta Base di produzione ?'; nfsCancellareTuttiValori = 'Confermi la cancellazione di tutti i valori ?'; nfsSalvareAanagrafica = 'E'' necessario salvare l''anagrafica prima di poter inserire degli articoli.'; nfsEsportazioneEseguita = 'Esportazione eseguita'; nfsAnnullaDocumento = 'Annulla documento'; RS_AV = 'Si è verificato un problema.'#13'L''applicazione verrà chiusa'; RS_ErroreForeign = 'La cancellazione non e'' possibile. Esistono delle registrazioni nella tabella %s.'; RS_ErroreChiaveDuplicata = 'Valore già presente.'; RS_RigaDuplicata = 'Articolo %s duplicato'; nfsDocNonModif = 'Documento non modificabile'; nfsRigaNonModif = 'Riga non modificabile'; nfsOperazioneCompletata = 'Operazione completata.'; nfsArticoloNonTrovato = 'Articolo %d non trovato nell''anagrafica %d'; nfsNumeroDuplicato = 'Il numero del documento è già presente in archivio.'; nfsConfermiCreaOrdine = 'creazione dell'' ordine %s'; nfsCancellaAnag = 'Confermi la cancellazione dell''anagrafica ?'; nfsCancellaDoc = 'Confermi la cancellazione del documento ?'; nfsCancellaRiga = 'Confermi la cancellazione della riga ?'; nfsConfermaCancel = 'Ci sono dati modificati.'#13'Abbandoni l''operazione ?'; nfsPswdErrata = 'Password errata !'; nfsPswdScaduta = 'Password scaduta !'; // DB_ErroreForeign = 'La cancellazione non e'' possibile. Esistono delle registrazioni nella tabella %s'; DB_ServerNonDisponibile = 'Il collegamento non e'' attualmente disponibile. Riprovare più tardi.(SY003)'; nfsConfermaEsecuzione = 'Confermi %s ?'; nfsEsecuzioneEseguita = '%s eseguita'; nfsAnagraficaIncompleta = 'Attenzione, l''anagrafica è incompleta.'; nfsAnagraficaStampaIncompleta = 'Attenzione, l''anagrafica è incompleta.'+#13+'Stampa non possibile.'; nfsAnagraficaRegIncompleta = 'Attenzione, l''anagrafica è incompleta.'+#13+ 'Non sarà possibile utilizzarla nelle ricerche e nelle stampe.'#13+'Vuoi continuare lo stesso ?'; nfsErrMailIndirizzo = 'E'' obbligatorio inserire almeno un valore tra email, telefono, fax o indirizzo'; nfsErrMailDestinazione = 'E'' obbligatorio inserire almeno un valore tra email, telefono, fax o cellulare'; nfsErrIndirizzoCompleto = 'E'' obbligatorio inserire l''indirizzo completo'; nfsAnagIvaoCF = 'Attenzione: manca la Partita Iva o il Codice Fiscale.'#13+'Vuoi continuare lo stesso ?'; nfsSedeLegale = 'Attenzione: manca la Sede Legale nei contatti.'#13+'Vuoi continuare lo stesso ?'; nfsSettore = 'Attenzione: manca almeno un settore di appartenenza del fornitore.'#13+'Vuoi continuare lo stesso ?'; nfsPIvaErrata = 'La partita Iva non è stata riconosciuta'#13+'Vuoi continuare lo stesso ?'; nfsErroreInControlloPIva = 'C''è stato un errore nel controllo della Partita Iva.'#13+'Vuoi continuare lo stesso ?'; sgmValoreObbligatorio = 'Valore obbligatorio !'; sgmPrimaryKeyRequired = 'Primary Key and UpdatingTable Required for Live Updates'#13#10'(%s)'; sgmQuantitaObbligatoria = 'Non sono state inserite quantità !'; implementation uses System.Variants, System.Threading, cxDBData, Vcl.Forms, Vcl.Dialogs, cxGridInplaceEditForm, RibbonPreviewForm, dxPSEngn, {$IFDEF SKIN1} Metropolis_GM, MetropolisDark, {$ENDIF} {$IFDEF SKIN2} Office2016Colorful, VisualStudio2013Blue, {$ENDIF} VSoft.CommandLine.Parser, VSoft.CommandLIne.Options, cxFilter, uCMDLineOptions, System.UITypes, DBConnection, ParamManager, gtMultiMonitorAwareness, madExcept, madTypes, madStrings, cxEdit, //Mask, Winapi.Messages, Sparkle.WinHttp.Api, IdSocketIOHandling, superobject, EventBus, System.SysUtils, Aurelius.Sql.gmRegister; {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} {$R grid6_ita.RES} procedure TFDMCommon.Connect; begin try TDBConnection.CreateConnection( gmDatabase ); gmWebsocketClient.Host := gmDatabase.WebSocketServer; gmWebsocketClient.Port := gmDatabase.WebSocketPort; gmWebsocketClient.TryConnect; FIsConnected := True; except on E: Exception do begin MessageDlg(format('Collegamento a %s non disponibile'#13#10'%s',[TCMDLineOptions.Server,E.Message]),mtError,[mbOK],0); FIsConnected := False; end; end; end; procedure ProcessMessageInMainthread(const aMsg: string); begin // TThread.Synchronize(nil, TThread.Queue(nil, procedure var obj: ISuperObject; Event: TDBChangeEvent; begin obj := SO(aMsg); Event := TDBChangeEvent.Create; Event.Table := UpperCase(obj.S['Table']); Event.Op := obj.S['Op']; Event.pkField := obj.S['pkField']; Event.pkValue := obj.S['pkValue']; Event.ValueField := obj.S['ValueField']; Event.Value := obj.S['Value']; TEventBus.GetDefault.Post(Event); end); end; procedure TFDMCommon.DataModuleCreate(Sender: TObject); //var // skin: string; begin (* {$IFDEF SKIN1} SkinNames[0] := : array[0..1] of string = ('Metropolis', 'MetropolisDark'); // 'MetroWhite.skinres', {$ENDIF} {$IFDEF SKIN2} SkinNames: array[0..1] of string = ('Office2016Colorful', 'VisualStudio2013Blue'); {$ENDIF} *) // FBaseControllerLoaded := false; // dxPSEngine.PreviewDialogStyle := 'MyRibbon'; dxPSPreviewDialogManager.CurrentPreviewDialogStyle := 'MyRibbon'; {$IFDEF VIRTUALUI} FVirtualUI := nil; {$ENDIF} cxLocalizer1.Active:= True; cxLocalizer1.Locale:= 1040; {$IFDEF VIRTUALUI} if self.IVirtualUI.Active then begin FRealDPI := 96; //self.IVirtualUI.BrowserInfo.ScreenResolution self.IVirtualUI.StdDialogs := False; // -- gestione download file dal browser end else {$ENDIF} FRealDPI := gtMultiMonitorAwareness.GetWindowMonitorDPI(Application.Handle); // cxDPI := FRealDPI; cxGridInplaceEditFormLayoutItemEditDefaultMinValueWidth := MulDiv(160, cxDPI, 96); // if (FRealDPI>96) then FImgList := cxImageNavigator32 { else FImgList := cxImageNavigator16}; // FManager := TDBConnection.GetInstance.CreateObjectManager; FKeyFieldList := TList<string>.Create; dxSkinController.NativeStyle := False; dxLayoutSkinLookAndFeel1.LookAndFeel.NativeStyle := False; {$IFDEF VIRTUALUI} dxSkinController.UseImageSet := imsAlternate; {$ENDIF} SelectSkin(0); gmWebsocketClient.SocketIOCompatible := True; gmWebsocketClient.SocketIO.OnEvent(C_SERVER_EVENT, procedure(const ASocket: ISocketIOContext; const aArgument: TSuperArray; const aCallback: ISocketIOCallback) var pUser: string; begin // ToDo: bloccare l'invio dal Server al client che ha fatto le modifiche pUser := SO(aArgument[0].AsJSon).S['UserId']; {$ifdef INTERNALREFRESH} if (pUser='') or (pUser<>TgmSQLGeneratorRegister.sUserId) then {$endif} ProcessMessageInMainthread(aArgument[0].AsJSon); (* //server wants a response? if aCallback <> nil then aCallback.SendResponse('thank for the push!'); *) end ); CheckConnect; if not FIsConnected then Application.Terminate; end; procedure TFDMCommon.DataModuleDestroy(Sender: TObject); begin // FManager.Free; FKeyFieldList.Free; // FBaseController.Free; end; function TFDMCommon.CheckConnect: boolean; begin result := TCMDLineOptions.ReadCMDParameters; if result then begin Connect; end; end; procedure TFDMCommon.GetSelectedIDs(Grid: TcxGridDBTableView); //var // I: Integer; // sWhere: string; begin // sWhere := ''; FKeyFieldList.Clear; try //screen.Cursor := crHourglass; Grid.DataController.DataSource.DataSet.DisableControls; GetSelectedKeyValues(Grid.DataController); { if (FKeyFieldList.Count > 0) then begin sWhere := ''''; //Iterate selected records for I := 0 to FKeyFieldList.Count - 1 do begin if (i < (FKeyFieldList.Count - 1)) then sWhere := sWhere + string(FKeyFieldList[i]) + ''',''' else sWhere := sWhere + string(FKeyFieldList[i]) + ''''; end; end; } finally Grid.DataController.DataSource.DataSet.EnableControls; end; end; {$IFDEF VIRTUALUI} function TFDMCommon.GetVirtualUI: TVirtualUI; begin if FVirtualUI=nil then FVirtualUI := VirtualUI; result := FVirtualUI; end; {$ENDIF} procedure TFDMCommon.GetSelectedKeyValues(ADataController: TcxGridDBDataController); begin FDataController := ADataController; ADataController.ForEachRow(True, AddKeyFieldValueToList); end; procedure TFDMCommon.AddKeyFieldValueToList(ARowIndex: Integer; ARowInfo: TcxRowInfo); var AKeyFieldValue: Variant; begin with FDataController do begin //test whether a row is a data record if ARowInfo.Level = Groups.GroupingItemCount then begin AKeyFieldValue := GetRecordId(ARowInfo.RecordIndex); if not VarIsNull(AKeyFieldValue) then FKeyFieldList.Add(string(AKeyFieldValue)); end; end; end; function TFDMCommon.GetRealDragSourceGridView(const aSource: TObject): TcxGridDBTableView; begin result := nil; if (TcxDragControlObject (aSource).Control is TcxGridSite) then begin result := TcxGridSite (TcxDragControlObject (aSource).Control).GridView as TcxGridDBTableView; end; end; function TFDMCommon.GetDragSourceGridView(const aSource: TObject): TcxGridDBTableView; begin result := GetRealDragSourceGridView (aSource); if (result<>nil) and result.IsDetail then result := result.PatternGridView as TcxGridDBTableView; end; function TFDMCommon.vLocate(Grid: TcxGridDBTableView; pkKey: Integer): boolean; var RecIdx: integer; begin if (Grid=nil) then result := false else if not Grid.DataController.DataModeController.SyncMode then result := Grid.DataController.LocateByKey(pkKey) else begin result := Grid.DataController.LocateByKey(pkKey); if result then begin RecIdx := Grid.DataController.FindRecordIndexByKey(pkKey); if RecIdx<>-1 then begin if Grid.OptionsSelection.MultiSelect then Grid.DataController.ClearSelection; Grid.DataController.FocusedRecordIndex := RecIdx; Grid.Controller.FocusedRecord.Selected := true; end; end; end; end; procedure TFDMCommon.WebUpdate1AppDoClose(Sender: TObject); begin Application.Terminate; end; procedure TFDMCommon.WebUpdate1AppRestart(Sender: TObject; var Allow: Boolean); begin // Allow := MessageDlg('Confermi la chiusura del programma per effettuare l''aggiornamento ?',mtConfirmation,[mbYes,mbNo],0)=mrYes; Allow := True; end; procedure TFDMCommon.WebUpdate1BeforeFileDownload(Sender: TObject; FileIdx: Integer; FileDescription: string; var URL: string); begin // if (pnlUpgrade<>nil) then pnlUpgrade.Visible := True; end; procedure TFDMCommon.WebUpdate1FileProgress(Sender: TObject; FileName: string; Pos, Size: Integer); begin if cxProgressUpdate<>nil then begin cxProgressUpdate.Properties.Max := size; cxProgressUpdate.Position := pos; end; end; procedure TFDMCommon.WebUpdate1Progress(Sender: TObject; Action: string); begin // end; procedure TFDMCommon.WebUpdate1Status(Sender: TObject; StatusStr: string; StatusCode, ErrCode: Integer); begin if (FpnlUpgrade<>nil) {and FpnlUpgrade.Visible} then case StatusCode of WebUpdateNoNewVersion: FreUpgrade.Lines.Add( 'Nessuna nuova versione disponibile' ); WebUpdateNotFound: FreUpgrade.Lines.Add( 'Sito di aggiornamento non disponibile' ); else FreUpgrade.Lines.Add( StatusStr ); end; end; procedure TFDMCommon.WebUpdate1Success(Sender: TObject); begin // end; function TFDMCommon.GetMasterRecordID(AView: TcxCustomGridView): Integer; begin Result := TcxDBDataRelation(AView.DataController.GetMasterRelation).GetMasterRecordID(AView.MasterGridRecordIndex); end; procedure TFDMCommon.Update; var VerInfo: TOSVersionInfo; OSVersion: string; begin // pnlUpgrade.Visible := True; VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(verinfo); OSVersion := IntToStr(verinfo.dwMajorVersion)+':'+IntToStr(verinfo.dwMinorVersion); { ??? WebUpdate1.PostUpdateInfo.Data := WebUpdate1.PostUpdateInfo.Data + '&TIME='+FormatDateTime('dd/mm/yyyy@hh:nn',Now)+'&OS='+OSVersion; } if TCMDLineOptions.UrlUpd<>'' then begin WebUpdate1.URL := TCMDLineOptions.UrlUpd + '/'+ChangeFileExt(ExtractFileName(paramstr(0)),'.inf'); // WebUpdate1.DoThreadupdate WebUpdate1.DoUpdate; if (pnlUpgrade<>nil) then pnlUpgrade.Visible := False; end else begin if (FpnlUpgrade<>nil) {and FpnlUpgrade.Visible} then FreUpgrade.Lines.Add( 'Sito di aggiornamento non definito' ); end; end; procedure TFDMCommon.SelectSkin(pSkin: integer); begin FSkinSelected := SkinNames[pSkin]; dxSkinController.Kind := lfUltraFlat; dxSkinController.NativeStyle := False; dxSkinController.SkinName := FSkinSelected; dxSkinController.UseSkins := True; dxLayoutSkinLookAndFeel1.LookAndFeel.Kind := lfUltraFlat; dxLayoutSkinLookAndFeel1.LookAndFeel.NativeStyle := False; dxLayoutSkinLookAndFeel1.LookAndFeel.SkinName := FSkinSelected; end; function TFDMCommon.VarIsNumericZero(const AValue: Variant): Boolean; begin Result := VarIsNull(AValue) or (AValue=0); end; {$IFDEF REPORTBUILDER} function TFDMCommon.GetReportId(const repName: string): string; begin qReportId.Close; qReportId.ParamByName('item_name').AsString := repName; qReportId.Open; if not qReportId.IsEmpty then result := qReportIditem_id.AsString else begin MessageDlg('Stampa non configurata',mtInformation,[mbOk],0); Abort; end; end; {$ELSE} function TFDMCommon.GetReportId(const repName: string): string; begin result := repName; end; {$ENDIF} function TFDMCommon.VarToInt(const AVariant: Variant): integer; begin Result := StrToIntDef(Trim(VarToStr(AVariant)), 0); end; procedure TFDMCommon.DetailFirst(ADataSet: TDataSet; const AMasterDetailKeyFieldNames: String; const AMasterDetailKeyValues: Variant; var AReopened: Boolean); begin with (ADataSet as TgmClientDataset) do begin if Active and (ParamByName(AMasterDetailKeyFieldNames).Value = AMasterDetailKeyValues) then begin First; Exit; end; // DisableControls; --> viene già fatto in syRefresh... // try Active := False; ParamByName(AMasterDetailKeyFieldNames).Value := AMasterDetailKeyValues; Refresh; // finally // EnableControls; // end; AReopened := True; end; end; function TFDMCommon.DetailIsCurrentQuery(ADataSet: TDataSet; const AMasterDetailKeyFieldNames: String; const AMasterDetailKeyValues: Variant): Boolean; begin with (ADataSet as TgmClientDataset) do Result := Active and (ParamByName(AMasterDetailKeyFieldNames).Value = AMasterDetailKeyValues); end; procedure TFDMCommon.ApplicaDataFine(xView: TcxGridDBTableView; xColumn: TcxGridDBColumn); begin xView.DataController.Filter.BeginUpdate; with xView.DataController.Filter.Root do begin with AddItemList(fboAnd) do begin Clear; BoolOperatorKind := fboOr; AddItem(xColumn, foEqual, null, ''); AddItem(xColumn, foGreater, Date(), DateToStr(Date())); end; end; xView.DataController.Filter.Active := True; xView.DataController.Filter.EndUpdate; end; function TFDMCommon.gmStrToFloat(const S: string): Extended; begin Result := StrToFloat(StringReplace(S, FormatSettings.ThousandSeparator, '',[rfReplaceAll]), FormatSettings); end; procedure TFDMCommon.SaveDevExObjConfiguration(pDevExObj: TcxControl); var mem: TMemoryStream; pname: string; begin pname := pDevExObj.Owner.Name+'_'+pDevExObj.Name; mem := TMemoryStream.Create; try if not GetParamManager.HasParam(pname) then GetParamManager.RegisterParam(pname, null, ssUser, psRemote); if pDevExObj is TcxDBPivotGrid then TcxDBPivotGrid(pDevExObj).StoreToStream(mem); mem.Position := 0; GetParamManager.ParamByName(pname).LoadFromStream(mem); finally mem.Free; end; end; procedure TFDMCommon.RestoreDevExObjConfiguration(pDevExObj: TcxControl); var mem: TMemoryStream; pname: string; begin pname := pDevExObj.Owner.Name+'_'+pDevExObj.Name; mem := TMemoryStream.Create; try if not GetParamManager.HasParam(pName) then GetParamManager.RegisterParam(pName, null, ssUser, psRemote); GetParamManager.ParamByName(pName).SaveToStream(mem); if mem.Size>0 then begin mem.Position := 0; if pDevExObj is TcxDBPivotGrid then TcxDBPivotGrid(pDevExObj).RestoreFromStream(mem); end; finally mem.Free; end; end; procedure TFDMCommon.PivotGridExpandAll(pPivotGrid: TcxDBPivotGrid); var i: integer; begin pPivotGrid.BeginUpdate; try for i := 0 to pPivotGrid.FieldCount - 1 do pPivotGrid.Fields[i].ExpandAll; finally pPivotGrid.EndUpdate; end; end; (* ------------------------ *) function StrToWord(const Value: String): Word; inline; begin // if Length(Value) > 1 then begin {$IFDEF STRING_IS_UNICODE} Result := TwoCharToWord(Value[1], Value[2]); {$ELSE} Result := PWord(Pointer(Value))^; {$ENDIF} // end else begin // Result := 0; // end; end; {************************************************* *********** * Procedure PostKeyEx * * Parameters: * hWindow: target window to be send the keystroke * key : virtual keycode of the key to send. For printable * keys this is simply the ANSI code (Ord(character)). * shift : state of the modifier keys. This is a set, so you * can set several of these keys (shift, control, alt, * mouse buttons) in tandem. The TShiftState type is * declared in the Classes Unit. * specialkey: normally this should be False. Set it to True to * specify a key on the numeric keypad, for example. * If this parameter is true, bit 24 of the lparam for * the posted WM_KEY* messages will be set. * Description: * This procedure sets up Windows key state array to correctly * reflect the requested pattern of modifier keys and then posts * a WM_KEYDOWN/WM_KEYUP message pair to the target window. Then * Application.ProcessMessages is called to process the messages * before the keyboard state is restored. * Error Conditions: * May fail due to lack of memory for the two key state buffers. * Will raise an exception in this case. * NOTE: * Setting the keyboard state will not work across applications * running in different memory spaces on Win32 unless AttachThreadInput * is used to connect to the target thread first. *Created: 02/21/96 16:39:00 by P. Below ************************************************** **********} Procedure PostKeyEx( hWindow: HWnd; key: Word; Const shift: TShiftState; specialkey: Boolean ); Type TBuffers = Array [0..1] of TKeyboardState; Var pKeyBuffers : ^TBuffers; lparam: LongInt; Begin (* check if the target window exists *) If IsWindow(hWindow) Then Begin (* set local variables to default values *) // pKeyBuffers := Nil; lparam := MakeLong(0, MapVirtualKey(key, 0)); (* modify lparam if special key requested *) If specialkey Then lparam := lparam or $1000000; (* allocate space for the key state buffers *) New(pKeyBuffers); try (* Fill buffer 1 with current state so we can later restore it. Null out buffer 0 to get a "no key pressed" state. *) GetKeyboardState( pKeyBuffers^[1] ); FillChar(pKeyBuffers^[0], Sizeof(TKeyboardState), 0); (* set the requested modifier keys to "down" state in the buffer *) If ssShift In shift Then pKeyBuffers^[0][VK_SHIFT] := $80; If ssAlt In shift Then Begin (* Alt needs special treatment since a bit in lparam needs also be set *) pKeyBuffers^[0][VK_MENU] := $80; lparam := lparam or $20000000; End; If ssCtrl In shift Then pKeyBuffers^[0][VK_CONTROL] := $80; If ssLeft In shift Then pKeyBuffers^[0][VK_LBUTTON] := $80; If ssRight In shift Then pKeyBuffers^[0][VK_RBUTTON] := $80; If ssMiddle In shift Then pKeyBuffers^[0][VK_MBUTTON] := $80; (* make out new key state array the active key state map *) SetKeyboardState( pKeyBuffers^[0] ); (* post the key messages *) If ssAlt In Shift Then Begin PostMessage( hWindow, WM_SYSKEYDOWN, key, lparam); PostMessage( hWindow, WM_SYSKEYUP, key, lparam or $C0000000); End Else Begin PostMessage( hWindow, WM_KEYDOWN, key, lparam); PostMessage( hWindow, WM_KEYUP, key, lparam or $C0000000); End; (* process the messages *) Application.ProcessMessages; (* restore the old key state map *) SetKeyboardState( pKeyBuffers^[1] ); finally (* free the memory for the key state buffers *) If pKeyBuffers <> Nil Then Dispose( pKeyBuffers ); End; { If } End; End; { PostKeyEx } function IIfThen(AValue: Boolean; const ATrue: string; const AFalse: string = ''): string; overload; begin if AValue then Result := ATrue else Result := AFalse; end; function IIfThen(AValue: Boolean; const ATrue: integer; const AFalse: integer): integer; overload; begin if AValue then Result := ATrue else Result := AFalse; end; { TDataSetParams } function TDataSetParams.BlobField: TBlobField; begin Result := FParams.qParamDatasetDATA; end; function TDataSetParams.CompanyField: TField; begin Result := FParams.qParamDatasetCOMPANY; // Required for company scoped params end; function TDataSetParams.DataSet: TDataSet; begin Result := FParams.qParamDataset; end; function TDataSetParams.NameField: TField; begin Result := FParams.qParamDatasetNOME; end; procedure TDataSetParams.Open; begin inherited; if FParams = nil then FParams := FDMCommon; if not FParams.qParamDataset.Active then FParams.qParamDataset.Open; end; function TDataSetParams.UserField: TField; begin Result := FParams.qParamDatasetUSER_ID; //Required for company scoped params end; function TDataSetParams.ValueField: TField; begin Result := FParams.qParamDatasetVALORE; end; {JRT} function TDataSetParams.WorkstationField: TField; begin Result := FParams.qParamDatasetWorkstation; end; {} procedure ExceptionFilter(const exceptIntf : IMEException; var handled : boolean); var dove: integer; ExceptionMessage: string; vShow: integer; // -- 0= no show; 1=show locale; 2=show handler vContinue,vLog: boolean; fatto: boolean; temp: string; d: integer; errorcode: integer; begin (* exceptIntf.BeginUpdate; exceptIntf.BugReportHeader.Insert(0,'*** inizio errore ***', '***'); exceptIntf.BugReportHeader.Insert(1,'utente: ', gblNomeUtente + ' ('+IntToStr(gblCodUtente)+')'); exceptIntf.BugReportSections.Add('*** fine errore ***','***'); exceptIntf.EndUpdate; *) if (exceptIntf.ExceptType=etFrozen) then begin AutoSaveBugReport(exceptIntf.bugReport); exit; end; if (exceptIntf.exceptObject = nil) then exit; ExceptionMessage := MadException(exceptIntf.exceptObject).Message; vShow := 1; vLog := true; vContinue := true; if (exceptIntf.exceptObject is EAccessViolation) or (exceptIntf.exceptObject is EInvalidPointer) or (exceptIntf.exceptObject is EAbstractError) or (exceptIntf.exceptObject is EInvalidOperation) or (exceptIntf.exceptObject is EcxInvalidDataControllerOperation) then begin if DebugHook <> 0 then vShow := 2 // 3=reset applicazione 2=rimane dentro; else vShow := 4; // 4=chiudi applicazione 2=rimane dentro; end; if //(exceptIntf.exceptObject is EDBEditError) or (exceptIntf.exceptObject is EcxEditValidationError) then begin vLog := false; end; if (exceptIntf.exceptObject is EWinHttpClientException) then begin dove := Pos('Error: (',ExceptionMessage); temp := Copy(ExceptionMessage,dove+8,5); errorcode := StrToIntDef( temp, 0 ); (* case errorcode of ERROR_WINHTTP_TIMEOUT: ExceptionMessage := 'The request has timed out'; ERROR_WINHTTP_CANNOT_CONNECT: ExceptionMessage := 'Could not connect to server'; ERROR_WINHTTP_HEADER_NOT_FOUND: ExceptionMessage := 'The requested header cannot be located'; ERROR_WINHTTP_INVALID_SERVER_RESPONSE: ExceptionMessage := 'The server response cannot be parsed'; ERROR_WINHTTP_SECURE_FAILURE: ExceptionMessage := 'Error in Server SSL Certificate'; else ExceptionMessage := 'Ci sono problemi di comunicazione con il server.'; end; *) ExceptionMessage := format('Ci sono problemi di comunicazione con il server (%d)',[errorcode]); vShow := 1; vLog := false; end; if (exceptIntf.exceptObject is ERemoteDBClientException) then begin fatto := false; dove := Pos('The DELETE statement conflicted with the REFERENCE constraint',ExceptionMessage); if dove>0 then begin dove := Pos('table "',ExceptionMessage); temp := Copy(ExceptionMessage,dove+7); dove := Pos('"',temp); ExceptionMessage := format(RS_ErroreForeign,[Copy(temp,1,dove-1)]);; vLog := false; vShow := 1; fatto := true; end; if not fatto then begin dove := Pos('Cannot insert duplicate key row in object',ExceptionMessage); if dove>0 then begin ExceptionMessage := RS_ErroreChiaveDuplicata; vLog := false; vShow := 1; fatto := true; end; end; if not fatto then begin dove := Pos('Message:',ExceptionMessage); if dove>0 then begin // -- trovo l'ultima occorrenza di "]" d := LastDelimiter(']',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,d+1,Length(ExceptionMessage)-d+1); vLog := false; vShow := 1; // fatto := true; end; end; end; (* --- ToDo: fare gestione dipendente dal tipo di connessione e di DB if (exceptIntf.exceptObject is ESocketError) then begin vContinue := gbldebugmode; // false; ExceptionMessage := format(ExceptionMessage+' (%s %s)',[FDMCommon.AstaClientSocket.Address,FDMCommon.AstaClientSocket.Address]); end; if (Pos('List index out of bounds',ExceptionMessage)>0) then vShow := 0 {JRT 5488: eliminato else if (exceptIntf.exceptObject is RefVocException) then vShow := 0 } else if ((exceptIntf.exceptObject is EDataBaseError) or (exceptIntf.exceptObject is EAstaProtocolError)) then begin vShow := 2; dove := Pos('ORA-20001',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := false; vShow := 1; end; dove := Pos('ORA-20002',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,dove+11,Length(ExceptionMessage)-(dove+10)); dove := Pos(#10,ExceptionMessage); if dove>0 then ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vLog := true; vShow := 1; end; dove := Pos('ORA-00001',ExceptionMessage); if dove>0 then begin ExceptionMessage := RIS_ErroreUnicita; vLog := false; vShow := 1; end; dove := Pos('ORA-02292',ExceptionMessage); if dove>0 then begin dove := Pos('(',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,dove+1,Length(ExceptionMessage)-dove); dove := Pos(')',ExceptionMessage); ExceptionMessage := Copy(ExceptionMessage,1,dove-1); ExceptionMessage := format(RIS_ErroreForeign,[ExceptionMessage]); vLog := false; vShow := 1; end; dove := Pos('(SY001)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 3; end; dove := Pos('(SY002)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; dove := Pos('(SY003)',ExceptionMessage); if dove>0 then begin ExceptionMessage := Copy(ExceptionMessage,1,dove-1); vContinue := false; vShow := 4; end; if (vShow=2) and ((Pos('ORA-03114',ExceptionMessage)>0) or (Pos('Not logged on',ExceptionMessage)>0) or ((Pos('ORA-03113',ExceptionMessage)>0) and not (Pos('ORA-02050',exceptIntf.bugReport)>0)) or (Pos('ORA-12535',ExceptionMessage)>0) or (Pos('ORA-12500',ExceptionMessage)>0) or (Pos('ORA-12203',ExceptionMessage)>0) or (Pos('ORA-01089',ExceptionMessage)>0) or (Pos('ORA-01033',ExceptionMessage)>0) or (Pos('ORA-01034',ExceptionMessage)>0) or (Pos('ORA-01012',ExceptionMessage)>0) or (Pos('ORA-12570',ExceptionMessage)>0) or (Pos('ORA-12571',ExceptionMessage)>0)) then begin ExceptionMessage := RS_ServerNonDisponibile; vContinue := false; vShow := 4; end; end; *) MadException(exceptIntf.exceptObject).Message := ExceptionMessage; if DebugHook <> 0 then vShow := 5 else if vLog then begin MESettings.ExceptMsg := ExceptionMessage; AutoSendBugReport(exceptIntf.bugReport,exceptIntf.ScreenShot,MESettings); end; case vShow of 0:begin handled := true; end; 1,2:begin handled := true; if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(ExceptionMessage), 'Errore...', MB_ICONERROR) else MessageDlg(ExceptionMessage, mtError, [mbOk], 0); end; 3:begin handled := true; if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(ExceptionMessage), 'Errore...', MB_ICONERROR) else if MessageDlg(ExceptionMessage, mtError, [mbYes,mbNo], 0, mbYes)=mrNo then vShow := 4; end; 4:begin handled := true; // if not (GetCurrentThreadID = MainThreadID) then MessageBox(0, pchar(RS_AV), 'Errore...', MB_ICONERROR) // else // MsgDlg(RS_AV, '', ktError, [kbOk], dfFirst); end; 5:begin exceptIntf.AutoShowBugReport := True; handled := false; end; end; exceptIntf.canContinue := vContinue; if DebugHook <> 0 then exceptIntf.AutoClose := 1 else exceptIntf.AutoClose := 0; case vShow of 3: RestartApplication; 4: CloseApplication; end; end; initialization TParamManager.RemoteParamsClass := TDataSetParams; RegisterExceptionHandler(ExceptionFilter,stTrySyncCallAlways); {$IFDEF DDDEBUG} TDDDMadExceptHandler.Initialize; {$ENDIF} dxPSPreviewDialogManager.RegisterPreviewDialog(TdxMyPSRibbonPreviewDialogStyleInfo); finalization dxPSPreviewDialogManager.UnregisterPreviewDialog(TdxMyPSRibbonPreviewDialogStyleInfo); end.
program seis; const valorAlto = 32767; type str20 = String[20]; tPrenda = record cod_prenda : integer; descripcion : str20; colores : str20; tipo_prenda : str20; stock : integer; precio : real; end; archivo_maestro = file of tPrenda; //este archivo posee los codigos de prenda que se tienen que hay que dar de baja archivo_detalle = file of integer; procedure leerRegistroMaestro (var arc : archivo_maestro; var reg : tPrenda); begin if (not eof(arc)) then read(arc, reg) else reg.cod_prenda := valorAlto; end; //no se usa lista invertida procedure darBaja (var archivo : archivo_maestro; unCodigo : integer); var unaPrenda : tPrenda; begin reset(archivo); leerRegistroMaestro(archivo, unaPrenda); while ((unaPrenda.cod_prenda <> valorAlto) and (unaPrenda.cod_prenda <> unCodigo)) do leerRegistroMaestro(archivo, unaPrenda); //los detalle tienen info que estan en el maestro if (unaPrenda.cod_prenda = unCodigo) then begin //el stock en negativo me indica que el registro esta eliminado unaPrenda.stock := -1 * unaPrenda.stock; seek(archivo, filepos(archivo) - 1); write(archivo, unaPrenda); end; close(archivo); end; procedure recorrerDetalle (var archivo : archivo_maestro; var det : archivo_detalle); var unCodigo : integer; begin reset(det); while (not eof(det)) do begin read(det, unCodigo); darBaja(archivo, unCodigo); end; close(det); end; procedure compactarArchivo (var archivo, compacto : archivo_maestro); var unaPrenda : tPrenda; begin reset(archivo); rewrite(compacto); leerRegistroMaestro(archivo, unaPrenda); while (unaPrenda.cod_prenda <> valorAlto) do begin if (unaPrenda.stock >= 0) then write(compacto, unaPrenda); leerRegistroMaestro(archivo, unaPrenda); end; close(compacto); close(archivo); end; //preguntar por esto. . . procedure renombrarArchivos (var arc, compacto : archivo_maestro); begin reset(arc); rename(arc, 'original'); close(arc); erase(arc); rename(compacto, 'nuevo'); close(compacto); end; //Programa principal var archivo, compacto : archivo_maestro; detalle : archivo_detalle; begin assign(archivo, 'archivo_prendas'); assign(detalle, 'detalle'); assign(compacto, 'nuevas_prendas'); recorrerDetalle(archivo, detalle); compactarArchivo(archivo, compacto); renombrarArchivos(archivo, compacto); end.
(* * Copyright (c) 2008-2009, Susnea Andrei * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY 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. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.ArraySet; interface uses SysUtils, Tests.Utils, TestFramework, DeHL.Types, DeHL.Exceptions, DeHL.Arrays, DeHL.Collections.Stack, DeHL.Collections.ArraySet; type TTestArraySet = class(TDeHLTestCase) published procedure TestCreationAndDestroy(); procedure TestCreateWithDynFixArrays(); procedure TestCountClearAdd(); procedure TestContains(); procedure TestCopyTo(); procedure TestIDynamic(); procedure TestEnumerator(); procedure TestExceptions(); procedure TestObjectVariant(); procedure TestCleanup(); end; implementation { TTestArraySet } procedure TTestArraySet.TestCountClearAdd; var ArraySet : TArraySet<String>; Stack : TStack<String>; begin ArraySet := TArraySet<String>.Create(0); Stack := TStack<String>.Create(); Stack.Push('s1'); Stack.Push('s2'); Stack.Push('s3'); ArraySet.Add('1'); ArraySet.Add('2'); ArraySet.Add('3'); Check((ArraySet.Count = 3) and (ArraySet.Count = ArraySet.GetCount()), 'ArraySet count expected to be 3'); { 1 2 3 } ArraySet.Add('0'); { 1 2 3 0 } ArraySet.Add('-1'); { 1 2 3 0 -1 } ArraySet.Add('5'); Check((ArraySet.Count = 6) and (ArraySet.Count = ArraySet.GetCount()), 'ArraySet count expected to be 6'); ArraySet.Remove('1'); Check((ArraySet.Count = 5) and (ArraySet.Count = ArraySet.GetCount()), 'ArraySet count expected to be 5'); ArraySet.Remove('5'); ArraySet.Remove('3'); ArraySet.Remove('2'); ArraySet.Remove('-1'); ArraySet.Remove('0'); Check((ArraySet.Count = 0) and (ArraySet.Count = ArraySet.GetCount()), 'ArraySet count expected to be 0'); ArraySet.Free; Stack.Free; end; procedure TTestArraySet.TestCopyTo; var ArraySet : TArraySet<Integer>; IL : array of Integer; begin ArraySet := TArraySet<Integer>.Create(); { Add elements to the ArraySet } ArraySet.Add(1); ArraySet.Add(2); ArraySet.Add(3); ArraySet.Add(4); ArraySet.Add(5); { Check the copy } SetLength(IL, 5); ArraySet.CopyTo(IL); Check(IL[0] = 1, 'Element 0 in the new array is wrong!'); Check(IL[1] = 2, 'Element 1 in the new array is wrong!'); Check(IL[2] = 3, 'Element 2 in the new array is wrong!'); Check(IL[3] = 4, 'Element 3 in the new array is wrong!'); Check(IL[4] = 5, 'Element 4 in the new array is wrong!'); { Check the copy with index } SetLength(IL, 6); ArraySet.CopyTo(IL, 1); Check(IL[1] = 1, 'Element 1 in the new array is wrong!'); Check(IL[2] = 2, 'Element 2 in the new array is wrong!'); Check(IL[3] = 3, 'Element 3 in the new array is wrong!'); Check(IL[4] = 4, 'Element 4 in the new array is wrong!'); Check(IL[5] = 5, 'Element 5 in the new array is wrong!'); { Exception } SetLength(IL, 4); CheckException(EArgumentOutOfSpaceException, procedure() begin ArraySet.CopyTo(IL); end, 'EArgumentOutOfSpaceException not thrown in CopyTo (too small size).' ); SetLength(IL, 5); CheckException(EArgumentOutOfSpaceException, procedure() begin ArraySet.CopyTo(IL, 1); end, 'EArgumentOutOfSpaceException not thrown in CopyTo (too small size +1).' ); ArraySet.Free(); end; procedure TTestArraySet.TestCleanup; var ASet : TArraySet<Integer>; ElemCache: Integer; I: Integer; begin ElemCache := 0; { Create a new ASet } ASet := TArraySet<Integer>.Create( TTestType<Integer>.Create(procedure(Arg1: Integer) begin Inc(ElemCache, Arg1); end) ); { Add some elements } ASet.Add(1); ASet.Add(2); ASet.Add(4); ASet.Add(8); Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); ASet.Remove(1); ASet.Remove(2); ASet.Contains(10); ASet.Shrink(); ASet.Grow(); Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); { Simply walk the ASet } for I in ASet do if I > 0 then; Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); ASet.Clear(); Check(ElemCache = 12, 'Expected cache = 12'); ElemCache := 0; ASet.Add(1); ASet.Add(2); ASet.Add(4); ASet.Add(8); ASet.Free; Check(ElemCache = 15, 'Expected cache = 15'); end; procedure TTestArraySet.TestContains; var ArraySet : TArraySet<Integer>; begin ArraySet := TArraySet<Integer>.Create(); ArraySet.Add(1); ArraySet.Add(2); ArraySet.Add(3); ArraySet.Add(4); {-} ArraySet.Add(5); ArraySet.Add(6); ArraySet.Add(4); {-} ArraySet.Add(7); ArraySet.Add(8); ArraySet.Add(9); Check(ArraySet.Contains(1), 'Set expected to contain 1'); Check(ArraySet.Contains(2), 'Set expected to contain 2'); Check(ArraySet.Contains(3), 'Set expected to contain 3'); Check(ArraySet.Contains(4), 'Set expected to contain 4'); Check(not ArraySet.Contains(10), 'Set not expected to contain 10'); ArraySet.Free(); end; procedure TTestArraySet.TestCreateWithDynFixArrays; var DA: TDynamicArray<Integer>; FA: TFixedArray<Integer>; DAL: TArraySet<Integer>; FAL: TArraySet<Integer>; begin DA := TDynamicArray<Integer>.Create([5, 6, 2, 3, 1, 1]); FA := TFixedArray<Integer>.Create([5, 6, 2, 3, 1, 1]); DAL := TArraySet<Integer>.Create(DA); FAL := TArraySet<Integer>.Create(FA); Check(DAL.Count = 5, 'Expected DAL.Length to be 5'); Check(DAL.Contains(5), 'Expected DAL to contain 5'); Check(DAL.Contains(6), 'Expected DAL to contain 6'); Check(DAL.Contains(2), 'Expected DAL to contain 2'); Check(DAL.Contains(3), 'Expected DAL to contain 3'); Check(DAL.Contains(1), 'Expected DAL to contain 1'); Check(FAL.Count = 5, 'Expected FAL.Length to be 5'); Check(FAL.Contains(5), 'Expected FAL to contain 5'); Check(FAL.Contains(6), 'Expected FAL to contain 6'); Check(FAL.Contains(2), 'Expected FAL to contain 2'); Check(FAL.Contains(3), 'Expected FAL to contain 3'); Check(FAL.Contains(1), 'Expected FAL to contain 1'); DAL.Free; FAL.Free; end; procedure TTestArraySet.TestCreationAndDestroy; var ArraySet : TArraySet<Integer>; Stack : TStack<Integer>; IL : array of Integer; begin { With default capacity } ArraySet := TArraySet<Integer>.Create(); ArraySet.Add(10); ArraySet.Add(20); ArraySet.Add(30); ArraySet.Add(40); Check(ArraySet.Count = 4, 'ArraySet count expected to be 4'); ArraySet.Free(); { With preset capacity } ArraySet := TArraySet<Integer>.Create(0); ArraySet.Add(10); ArraySet.Add(20); ArraySet.Add(30); ArraySet.Add(40); Check(ArraySet.Count = 4, 'ArraySet count expected to be 4'); ArraySet.Free(); { With Copy } Stack := TStack<Integer>.Create(); Stack.Push(1); Stack.Push(2); Stack.Push(3); Stack.Push(4); ArraySet := TArraySet<Integer>.Create(Stack); Check(ArraySet.Count = 4, 'ArraySet count expected to be 4'); Check(ArraySet.Contains(1), 'ArraySet[1] expected to exist'); Check(ArraySet.Contains(2), 'ArraySet[2] expected to exist'); Check(ArraySet.Contains(3), 'ArraySet[3] expected to exist'); Check(ArraySet.Contains(4), 'ArraySet[4] expected to exist'); ArraySet.Free(); Stack.Free(); { Copy from array tests } SetLength(IL, 6); IL[0] := 1; IL[1] := 2; IL[2] := 3; IL[3] := 4; IL[4] := 5; IL[5] := 5; ArraySet := TArraySet<Integer>.Create(IL); Check(ArraySet.Count = 5, 'ArraySet count expected to be 5'); Check(ArraySet.Contains(1), 'ArraySet expected to contain 1'); Check(ArraySet.Contains(2), 'ArraySet expected to contain 2'); Check(ArraySet.Contains(3), 'ArraySet expected to contain 3'); Check(ArraySet.Contains(4), 'ArraySet expected to contain 4'); Check(ArraySet.Contains(5), 'ArraySet expected to contain 5'); ArraySet.Free; end; procedure TTestArraySet.TestEnumerator; var ArraySet : TArraySet<Integer>; I, X : Integer; begin ArraySet := TArraySet<Integer>.Create(); ArraySet.Add(10); ArraySet.Add(20); ArraySet.Add(30); X := 0; for I in ArraySet do begin if X = 0 then Check(I = 10, 'Enumerator failed at 0!') else if X = 1 then Check(I = 20, 'Enumerator failed at 1!') else if X = 2 then Check(I = 30, 'Enumerator failed at 2!') else Fail('Enumerator failed!'); Inc(X); end; { Test exceptions } CheckException(ECollectionChangedException, procedure() var I : Integer; begin for I in ArraySet do begin ArraySet.Remove(I); end; end, 'ECollectionChangedException not thrown in Enumerator!' ); Check(ArraySet.Count = 2, 'Enumerator failed too late'); ArraySet.Free(); end; procedure TTestArraySet.TestExceptions; var ArraySet : TArraySet<Integer>; NullArg : IType<Integer>; begin NullArg := nil; CheckException(ENilArgumentException, procedure() begin ArraySet := TArraySet<Integer>.Create(NullArg); ArraySet.Free(); end, 'ENilArgumentException not thrown in constructor (nil comparer).' ); CheckException(ENilArgumentException, procedure() begin ArraySet := TArraySet<Integer>.Create(NullArg, 10); ArraySet.Free(); end, 'ENilArgumentException not thrown in constructor (nil comparer).' ); CheckException(ENilArgumentException, procedure() begin ArraySet := TArraySet<Integer>.Create(TType<Integer>.Default, nil); ArraySet.Free(); end, 'ENilArgumentException not thrown in constructor (nil enum).' ); ArraySet.Free(); end; procedure TTestArraySet.TestIDynamic; const NrElem = 1000; var ASet: TArraySet<Integer>; I: Integer; begin { With intitial capacity } ASet := TArraySet<Integer>.Create(100); ASet.Shrink(); Check(ASet.Capacity = 0, 'Capacity expected to be 0'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Grow(); Check(ASet.Capacity > 0, 'Capacity expected to be > 0'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Shrink(); ASet.Add(10); ASet.Add(20); ASet.Add(30); Check(ASet.Capacity > ASet.Count, 'Capacity expected to be > Count'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Shrink(); Check(ASet.Capacity = ASet.Count, 'Capacity expected to be = Count'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Grow(); Check(ASet.Capacity > ASet.Count, 'Capacity expected to be > Count'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Clear(); ASet.Shrink(); Check(ASet.Capacity = 0, 'Capacity expected to be = 0'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); for I := 0 to NrElem - 1 do ASet.Add(I); for I := 0 to NrElem - 1 do ASet.Remove(I); Check(ASet.Capacity > NrElem, 'Capacity expected to be > NrElem'); Check(ASet.GetCapacity() = ASet.Capacity, 'GetCapacity() expected to be equal to Capacity'); ASet.Free; end; procedure TTestArraySet.TestObjectVariant; var ObjSet: TObjectArraySet<TTestObject>; TheObject: TTestObject; ObjectDied: Boolean; begin ObjSet := TObjectArraySet<TTestObject>.Create(); Check(not ObjSet.OwnsObjects, 'OwnsObjects must be false!'); TheObject := TTestObject.Create(@ObjectDied); ObjSet.Add(TheObject); ObjSet.Clear; Check(not ObjectDied, 'The object should not have been cleaned up!'); ObjSet.Add(TheObject); ObjSet.OwnsObjects := true; Check(ObjSet.OwnsObjects, 'OwnsObjects must be true!'); ObjSet.Clear; Check(ObjectDied, 'The object should have been cleaned up!'); ObjSet.Free; end; initialization TestFramework.RegisterTest(TTestArraySet.Suite); end.
unit TestMongoDB; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses Classes, SysUtils, TestFramework, MongoDB, MongoBson, MongoAPI; type TestTMongo = class; // Test methods for class TMongo TMongoThread = class(TThread) private FErrorStr: UTF8String; FMongoTest: TestTMongo; protected procedure Execute; override; public constructor Create(AMongoTest: TestTMongo); property ErrorStr: UTF8String read FErrorStr write FErrorStr; end; TestMongoBase = class(TTestCase) protected FMongo: TMongo; function CreateMongo: TMongo; virtual; procedure RemoveUser(const db: string; const AUser, APwd: UTF8String); procedure SetUp; override; procedure TearDown; override; public class procedure StartMongo(Authenticated: Boolean = False); published end; TestTMongo = class(TestMongoBase) private test_db_created: Boolean; procedure Create_test_db; procedure Create_test_db_andCheckCollection(AExists: Boolean); procedure FindAndCheckBson(ID: Integer; const AValue: UTF8String); procedure InsertAndCheckBson(ID: Integer; const AValue: UTF8String); procedure RemoveTest_user(const db: string); protected procedure RestartMongo(Authenticated: Boolean = False); virtual; public procedure SetUp; override; procedure TearDown; override; published procedure TestisConnected; procedure TestcheckConnection; procedure TestisMaster; procedure Testdisconnect; procedure Testreconnect; procedure TestgetErr; procedure TestsetTimeout; procedure TestgetTimeout; procedure TestgetPrimary; procedure TestgetSocket; procedure TestgetDatabases; procedure TestgetDatabaseCollections; procedure TestRename; procedure Testdrop; procedure TestdropDatabase; procedure TestInsert; procedure TestInsertArrayofBson; procedure TestUpdate; procedure Testremove; procedure TestfindOne; procedure TestfindOneWithSpecificFields; procedure Testfind; procedure TestCount; procedure TestCountWithQuery; procedure Testdistinct; procedure TestindexCreate; procedure TestindexCreateWithOptions; procedure TestindexCreateUsingBsonKey; procedure TestindexCreateUsingBsonKeyAndOptions; procedure TestaddUser; procedure TestaddUserWithDBParam; procedure Testauthenticate; procedure TestauthenticateWithSpecificDB; procedure TestauthenticateFail; procedure TestcommandWithBson; procedure TestcommandWithArgs; procedure TestFailedConnection; procedure TestFindAndModifyBasic; procedure TestFindAndModifyUsingBSONOID; procedure TestFindAndModifyExtended; procedure TestgetLastErr; procedure TestgetPrevErr; procedure TestresetErr; procedure TestgetServerErr; procedure TestgetServerErrString; procedure TestFourThreads; procedure TestgetLoginDatabaseName_Default; procedure TestgetLoginDatabaseName_Defined; virtual; procedure TestindexCreateUsingBsonKeyAndNameAndOptions; procedure TestSetAndGetOpTimeout; procedure TestUseWriteConcern; procedure TestTryToUseUnfinishedWriteConcern; end; // Test methods for class TMongoReplset TestTMongoReplset = class(TestTMongo) protected FMongoReplset: TMongoReplset; function CreateMongo: TMongo; override; procedure RestartMongo(Authenticated: Boolean = False); override; public procedure SetUp; override; procedure TearDown; override; published procedure TestFourThreads; procedure TestgetHost; procedure TestgetLoginDatabaseName_Defined; override; end; // Test methods for class IMongoCursor TestIMongoCursor = class(TTestCase) private FIMongoCursor: IMongoCursor; FMongo: TMongo; FMongoSecondary : TMongo; protected procedure DeleteSampleData; procedure SetupData; public procedure SetUp; override; procedure TearDown; override; published procedure TestGetConn; procedure TestGetFields; procedure TestGetHandle; procedure TestGetLimit; procedure TestGetOptions; procedure TestGetQuery; procedure TestGetSkip; procedure TestGetSort; procedure TestNext; procedure TestSetFields; procedure TestSetLimit; procedure TestSetOptions; procedure TestSetQuery; procedure TestSetSkip; procedure TestSetSort; procedure TestValue; end; TestMongoCustomizations = class(TTestCase) published procedure TestCustomFuzzFn; procedure TestCustomIncrFn; end; type TestWriteConcern = class(TTestCase) private fwc: IWriteConcern; protected procedure SetUp; override; procedure TearDown; override; published procedure TestSetAndGet_j; procedure TestSetAndGet_fsync; procedure TestGet_cmd; procedure TestGet_cmd_check_getlasterror; procedure TestGet_cmd_with_w_equals1; procedure TestGet_cmd_with_mode_equals_majority; procedure TestGet_cmd_with_jwfsyncwtimeout; procedure TestGet_cmd_with_w_equals2; procedure TestSetAndGet_wtimeout; procedure TestSetAndGet_mode; procedure TestSetAndGet_w; end; var MongoStarted : Boolean; FSlaveStarted : Boolean; procedure StartMongoDB(const AParams: UTF8String); procedure StartReplSet(Authenticated: Boolean = False); function MongoDBPath: string; implementation uses AppExec, uWinProcHelper, uFileManagement{$IFNDEF VER130}, Variants{$ENDIF}, Windows, FileCtrl {$IFDEF TAXPORT}, uScope, Forms, CnvStream, CnvFileUtils, JclDateTime {$ENDIF}; procedure StartMongoDB(const AParams: UTF8String); {$IFDEF TAXPORT} const MONGOD_NAME = 'mongod.exe'; SRC_MONGOD = 'X:\CE\CnvFiles\DUnit\MongoDB\' + MONGOD_NAME; var Scope : IScope; s : TCnvStream; f : TFileStream; TargetMongoDBPath, TargetMongoDFile : UTF8String; Files : TFileInfoList; {$ENDIF} begin {$IFDEF TAXPORT} Scope := NewScope; TargetMongoDBPath := MongoDBPath; TargetMongoDFile := TargetMongoDBPath + MONGOD_NAME; Files := Scope.Add(TFileInfoList.Create); TCnvStream.GetStreamList(SRC_MONGOD, Files, False, True); if (Files.Count = 0) or (not FileExists(TargetMongoDFile)) or (Files.Infos[0].ModifyDate > FileTimeToDateTime(GetFileInfo(TargetMongoDFile).FindData.ftLastWriteTime)) then begin SysUtils.DeleteFile(TargetMongoDFile); s := Scope.Add(TCnvStream.Create(SRC_MONGOD, cdbmRead)); ForceDirectories(TargetMongoDBPath); f := Scope.Add(TFileStream.Create(TargetMongoDFile, fmCreate)); f.CopyFrom(s, s.Size); FileSetDate(f.Handle, DateTimeToFileDate(s.ModifyDate)); end; Scope := nil; {$ENDIF} with TAppExec.Create(nil) do try ExeName := 'mongod.exe'; ExePath := MongoDBPath; ExeParams.CommaText := AParams; Execute; finally Free; end; ChDir(ExtractFilePath(ParamStr(0))); Sleep(1000); end; procedure WaitForReplSetToBeReady; var Ready : array [27018..27020] of Boolean; APort : Integer; OnePrimary : Boolean; buf : IBsonBuffer; b, res : IBson; v : Variant; i : integer; begin APort := 27018; for i := low(Ready) to high(Ready) do Ready[i] := False; OnePrimary := False; repeat Sleep(200); with TMongo.Create(Format('127.0.0.1:%d', [APort])) do try buf := NewBsonBuffer; buf.Append(PAnsiChar('replSetGetStatus'), 1); b := buf.finish; res := command('admin', b); if res = nil then continue; v := res.Value('myState'); finally Free; end; APort := APort + 1; if APort > 27020 then APort := 27018; if integer(v) in [1, 2] then Ready[APort] := True; if integer(v) = 1 then OnePrimary := True; until (not VarIsNull(v)) and Ready[27018] and Ready[27019] and Ready[27020] and OnePrimary; end; procedure StartReplSet(Authenticated: Boolean = False); var b : IBson; buf : IBsonBuffer; AuthStr : string; begin if not FSlaveStarted then begin if not Authenticated then begin DeleteEntireDir(MongoDBPath + '\MongoDataReplica_1'); ForceDirectories(MongoDBPath + '\MongoDataReplica_1'); DeleteEntireDir(MongoDBPath + '\MongoDataReplica_2'); ForceDirectories(MongoDBPath + '\MongoDataReplica_2'); DeleteEntireDir(MongoDBPath + '\MongoDataReplica_3'); ForceDirectories(MongoDBPath + '\MongoDataReplica_3'); AuthStr := ''; end else AuthStr := '--auth'; StartMongoDB('--dbpath ' + MongoDBPath + '\MongoDataReplica_1 --smallfiles --noprealloc --journalCommitInterval 5 --port 27018 --replSet foo ' + AuthStr); StartMongoDB('--dbpath ' + MongoDBPath + '\MongoDataReplica_2 --smallfiles --noprealloc --journalCommitInterval 5 --port 27019 --replSet foo ' + AuthStr); StartMongoDB('--dbpath ' + MongoDBPath + '\MongoDataReplica_3 --smallfiles --noprealloc --journalCommitInterval 5 --port 27020 --replSet foo ' + AuthStr); with TMongo.Create('127.0.0.1:27018') do try buf := NewBsonBuffer; buf.startObject(PAnsiChar('replSetInitiate')); buf.AppendStr(PAnsiChar('_id'), PAnsiChar('foo')); buf.startArray(PAnsiChar('members')); buf.startObject('0'); buf.Append(PAnsiChar('_id'), 0); buf.AppendStr(PAnsiChar('host'), PAnsiChar('127.0.0.1:27018')); buf.finishObject; buf.startObject('1'); buf.Append(PAnsiChar('_id'), 1); buf.AppendStr(PAnsiChar('host'), PAnsiChar('127.0.0.1:27019')); buf.finishObject; buf.startObject('2'); buf.Append(PAnsiChar('_id'), 2); buf.AppendStr(PAnsiChar('host'), PAnsiChar('127.0.0.1:27020')); buf.finishObject; buf.finishObject; buf.finishObject; b := buf.finish; command('admin', b); finally Free; end; WaitForReplSetToBeReady; FSlaveStarted := True; end; end; procedure ShutDownMongoDB; begin while KillProcess('mongod.exe') do Sleep(200); // Need to sleep between calls to give time to first KillProcess call to succeed end; function MongoDBPath: string; begin {$IFDEF TAXPORT} Result := ExtractFilePath(Application.ExeName) + 'MongoDB\'; {$ELSE} Result := ExpandFileName('..\..\..\MongoDB\'); {$ENDIF} end; { TestMongoBase } function TestMongoBase.CreateMongo: TMongo; begin Result := TMongo.Create; end; procedure TestMongoBase.RemoveUser(const db: string; const AUser, APwd: UTF8String); var usr : IBson; begin usr := BSON(['user', AUser]); FMongo.remove(db + '.system.users', usr); Check(not FMongo.authenticate(AUser, APwd), 'Call to Mongo.authenticate with removed user should return False'); end; procedure TestMongoBase.SetUp; begin inherited; StartMongo; FMongo := CreateMongo; end; class procedure TestMongoBase.StartMongo(Authenticated: Boolean = False); var AuthStr : string; begin if not MongoStarted then begin if not Authenticated then begin DeleteEntireDir(MongoDBPath + '\MongoData'); ForceDirectories(MongoDBPath + '\MongoData'); AuthStr := ''; end else AuthStr := '--auth'; StartMongoDB('--dbpath ' + MongoDBPath + '\MongoData --smallfiles --noprealloc --journalCommitInterval 5 ' + AuthStr); MongoStarted := True; end; end; procedure TestMongoBase.TearDown; begin FMongo.Free; FMongo := nil; inherited; end; { TestTMongo } procedure TestTMongo.Create_test_db; var b : IBson; begin if test_db_created then exit; b := BSON(['int_value', 0]); FMongo.Insert('test_db.test_col', b); //Sleep(50); test_db_created := True; end; procedure TestTMongo.Create_test_db_andCheckCollection(AExists: Boolean); var Cols : TStringArray; begin Create_test_db; Cols := FMongo.getDatabaseCollections('test_db'); if AExists then begin CheckEquals(1, length(Cols), 'There should be at least one collection created'); CheckEqualsString('test_db.test_col', Cols[0], 'First and only collection created should be named test_db.test_col'); end else CheckEquals(0, length(Cols), 'There should be no collection created'); end; procedure TestTMongo.FindAndCheckBson(ID: Integer; const AValue: UTF8String); var q, b : IBson; ns : UTF8String; begin ns := 'test_db.test_col'; q := BSON(['int_fld', ID]); b := FMongo.findOne(ns, q); Check(b <> nil, 'Call to findOne should have returned a Bson object'); CheckEqualsString(AValue, b.Value(PAnsiChar('val_fld')), 'Returned value should be equals to "' + AValue + '"'); end; procedure TestTMongo.InsertAndCheckBson(ID: Integer; const AValue: UTF8String); var ReturnValue: Boolean; b: IBson; ns: UTF8String; begin b := BSON(['int_fld', ID, 'val_fld', AValue]); ns := 'test_db.test_col'; ReturnValue := FMongo.Insert(ns, b); Check(ReturnValue, 'call to Mongo.insert should return true'); FindAndCheckBson(ID, AValue); end; procedure TestTMongo.RemoveTest_user(const db: string); begin RemoveUser(db, 'test_user', 'test_password'); end; procedure TestTMongo.RestartMongo(Authenticated: Boolean = False); begin FreeAndNil(FMongo); ShutDownMongoDB; MongoStarted := False; StartMongo(Authenticated); FMongo := CreateMongo; end; procedure TestTMongo.SetUp; begin test_db_created := False; inherited; end; procedure TestTMongo.TearDown; begin if FMongo <> nil then begin FMongo.drop('test_db.test_thread'); FMongo.dropDatabase('test_db'); FMongo.dropDatabase('test_database'); end; inherited; end; procedure TestTMongo.TestisConnected; var ReturnValue: Boolean; begin ReturnValue := FMongo.isConnected; Check(ReturnValue, 'isConnected should be true'); end; procedure TestTMongo.TestcheckConnection; var ReturnValue: Boolean; begin ReturnValue := FMongo.checkConnection; Check(ReturnValue, 'checkConnection should return true'); FMongo.disconnect; ReturnValue := FMongo.checkConnection; Check(not ReturnValue, 'checkConnection should return false'); end; procedure TestTMongo.TestisMaster; var ReturnValue: Boolean; begin ReturnValue := FMongo.isMaster; Check(ReturnValue, 'isMaster should be true'); end; procedure TestTMongo.Testdisconnect; begin Check(FMongo.isConnected, 'isConnected should be true before call to disconnect'); FMongo.disconnect; Check(not FMongo.isConnected, 'isConnected should be false after disconnect'); end; procedure TestTMongo.Testreconnect; begin FMongo.disconnect; Check(not FMongo.isConnected, 'isConnected should be false after call to disconnect'); FMongo.reconnect; Check(FMongo.isConnected, 'isConnected should be true after call to reconnect'); end; procedure TestTMongo.TestgetErr; var ReturnValue: Integer; begin ReturnValue := FMongo.getErr; CheckEquals(0, ReturnValue, 'getErr should return zero'); end; procedure TestTMongo.TestsetTimeout; var ReturnValue: Boolean; millis: Integer; begin millis := 1000; ReturnValue := FMongo.setTimeout(millis); Check(ReturnValue, 'setTimeout should return true'); end; procedure TestTMongo.TestgetTimeout; const millis = 1000; var ReturnValue: Integer; begin FMongo.setTimeout(millis); ReturnValue := FMongo.getTimeout; CheckEquals(millis, ReturnValue, 'getTimeout should return same value passed on previous call to setTimeout'); end; procedure TestTMongo.TestgetPrimary; var ReturnValue: UTF8String; begin ReturnValue := FMongo.getPrimary; CheckNotEqualsString('', ReturnValue); end; procedure TestTMongo.TestgetSocket; var ReturnValue: Pointer; begin ReturnValue := FMongo.getSocket; CheckNotEquals(0, Int64(ReturnValue), 'getSocket should return a non-zero value'); end; procedure TestTMongo.TestgetDatabases; var ReturnValue: TStringArray; begin ReturnValue := FMongo.getDatabases; CheckEquals(0, length(ReturnValue), 'There should be no databases yet'); Create_test_db; ReturnValue := FMongo.getDatabases; CheckNotEquals(0, length(ReturnValue), 'There should be at least one database create now'); end; procedure TestTMongo.TestgetDatabaseCollections; var ReturnValue: TStringArray; db: UTF8String; begin db := 'test_db'; ReturnValue := FMongo.getDatabaseCollections(db); CheckEquals(0, length(ReturnValue), 'There should be no collections on test_db database'); Create_test_db; ReturnValue := FMongo.getDatabaseCollections(db); CheckEquals(1, length(ReturnValue), 'There should be one collection on test_db database'); end; procedure TestTMongo.TestRename; var ReturnValue: Boolean; to_ns: UTF8String; from_ns: UTF8String; Cols : TStringArray; begin Create_test_db_andCheckCollection(True); from_ns := 'test_db.test_col'; to_ns := 'test_db.test_col_renamed'; ReturnValue := FMongo.Rename(from_ns, to_ns); Check(ReturnValue, 'Call to Mongo.Rename should return true'); Cols := FMongo.getDatabaseCollections('test_db'); CheckEquals(1, length(Cols), 'There should be at least one collection created'); CheckEqualsString('test_db.test_col_renamed', Cols[0], 'First and only collection created should be named test_db.test_col_renamed'); end; procedure TestTMongo.Testdrop; var ReturnValue: Boolean; ns: UTF8String; begin Create_test_db_andCheckCollection(True); ns := 'test_db.test_col'; ReturnValue := FMongo.drop(ns); Check(ReturnValue, 'Call to Mongo.drop should return true'); Create_test_db_andCheckCollection(False); end; procedure TestTMongo.TestdropDatabase; var ReturnValue: Boolean; db: UTF8String; dbs : TStringArray; begin Create_test_db_andCheckCollection(True); db := 'test_db'; ReturnValue := FMongo.dropDatabase(db); Check(ReturnValue, 'Call to Mongo.dropDatabase should return True'); dbs := FMongo.getDatabases; CheckEquals(0, length(dbs), 'After dropDatabase call there should be no databases created'); end; procedure TestTMongo.TestInsert; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); end; procedure TestTMongo.TestInsertArrayofBson; var ReturnValue: Boolean; bs1, bs2: IBson; ns: UTF8String; begin Create_test_db; bs1 := BSON(['int_fld', 1, 'val_fld', 'Value1']); bs2 := BSON(['int_fld', 2, 'val_fld', 'Value2']); ns := 'test_db.test_col'; ReturnValue := FMongo.Insert(ns, [bs1, bs2]); Check(ReturnValue, 'Call to Mongo.Insert should return True'); FindAndCheckBson(1, 'Value1'); FindAndCheckBson(2, 'Value2'); end; procedure TestTMongo.TestUpdate; var ReturnValue: Boolean; objNew: IBson; criteria: IBson; ns: UTF8String; begin Create_test_db; ns := 'test_db.test_col'; InsertAndCheckBson(1, 'Value1'); criteria := BSON(['int_fld', 1]); objNew := BSON(['int_fld', 5, 'val_fld', 'Value5']); ReturnValue := FMongo.Update(ns, criteria, objNew); Check(ReturnValue, 'call to Mongo.Update should return true'); FindAndCheckBson(5, 'Value5'); end; procedure TestTMongo.Testremove; var ReturnValue: Boolean; b, criteria: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; criteria := BSON(['int_fld', 1]); ReturnValue := FMongo.remove(ns, criteria); Check(ReturnValue, 'call to Mongo.remove should return true'); b := FMongo.findOne(ns, criteria); Check(b = nil, 'Call to findOne with non existing Bson object should return nil'); end; procedure TestTMongo.TestfindOne; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); // This will call findOne internally end; procedure TestTMongo.TestfindOneWithSpecificFields; var ReturnValue: IBson; fields: IBson; query: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; query := BSON(['int_fld', 1]); fields := BSON(['val_fld', 1]); ReturnValue := FMongo.findOne(ns, query, fields); CheckEqualsString('Value1', ReturnValue.Value(PAnsiChar('val_fld')), 'Call to Mongo.FindOne should have returned object with val_fld equals to "Value1"'); Check(VarIsNull(ReturnValue.Value(PAnsiChar('int_fld'))), 'int_fld should not have been returned by call to IBson.Value'); end; procedure TestTMongo.Testfind; var ReturnValue: Boolean; Cursor: IMongoCursor; ns: UTF8String; n : Integer; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); InsertAndCheckBson(2, 'Value2'); Cursor := NewMongoCursor; ns := 'test_db.test_col'; ReturnValue := FMongo.find(ns, Cursor); Check(ReturnValue, 'Call to Mongo.Find should return True'); n := 0; while Cursor.Next do inc(n); CheckEquals(3, n, 'Number of Bson objects returned by cursor should be equal to 3'); end; procedure TestTMongo.TestCount; var ReturnValue: Double; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; ReturnValue := FMongo.Count(ns); CheckEquals(2, ReturnValue, 'Value returned by Mongo.Count should be equals to 2'); end; procedure TestTMongo.TestCountWithQuery; var ReturnValue: Double; query: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(5, 'Value1'); query := BSON(['int_fld', 5]); ns := 'test_db.test_col'; ReturnValue := FMongo.Count(ns, query); CheckEquals(1, ReturnValue, 'Value returned by Mongo.Count should be equals to 1'); end; procedure TestTMongo.Testdistinct; var ReturnValue: IBson; i : IBsonIterator; key: UTF8String; ns: UTF8String; Arr : TIntegerArray; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); InsertAndCheckBson(1, 'Value1'); InsertAndCheckBson(2, 'Value2'); ns := 'test_db.test_col'; CheckEquals(4, FMongo.Count(ns), 'Total number of objects stored on test_col should be equals to 4'); key := 'int_fld'; ReturnValue := FMongo.distinct(ns, key); Check(ReturnValue <> nil, 'Call to Mongo.distinct should have returned a value <> nil'); i := ReturnValue.iterator; Arr := i.getIntegerArray; CheckEquals(2, length(Arr), 'Number of values returned by call to distinct should be equals to 2'); CheckEquals(1, Arr[0], 'First value returned should be equals to 1'); CheckEquals(2, Arr[1], 'Second value returned should be equals to 2'); end; procedure TestTMongo.TestindexCreate; var ReturnValue: IBson; key: UTF8String; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; key := 'int_fld'; ReturnValue := FMongo.indexCreate(ns, key); Check(ReturnValue = nil, 'Call to Mongo.indexCreate should return nil if successful'); end; procedure TestTMongo.TestindexCreateWithOptions; var ReturnValue: IBson; options: Integer; key: UTF8String; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; key := 'int_fld'; options := indexUnique; ReturnValue := FMongo.indexCreate(ns, key, options); Check(ReturnValue = nil, 'Call to Mongo.indexCreate should return nil if successful'); end; procedure TestTMongo.TestindexCreateUsingBsonKey; var ReturnValue: IBson; key: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; key := BSON(['int_fld', True]); ReturnValue := FMongo.indexCreate(ns, key); Check(ReturnValue = nil, 'Call to Mongo.indexCreate should return nil if successful'); end; procedure TestTMongo.TestindexCreateUsingBsonKeyAndOptions; var ReturnValue: IBson; options: Integer; key: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; key := BSON(['int_fld', True]); options := indexUnique; ReturnValue := FMongo.indexCreate(ns, key, options); Check(ReturnValue = nil, 'Call to Mongo.indexCreate should return nil if successful'); end; procedure TestTMongo.TestaddUser; var ReturnValue: Boolean; password: UTF8String; Name: UTF8String; begin Name := 'test_user'; password := 'test_password'; ReturnValue := FMongo.addUser(Name, password); Check(ReturnValue, 'Call to Mongo.addUser should return true'); RemoveTest_user('admin'); end; procedure TestTMongo.TestgetLoginDatabaseName_Default; var ReturnValue: Boolean; password: UTF8String; Name: UTF8String; begin Name := 'test_user'; password := 'test_password'; ReturnValue := FMongo.addUser(Name, password); Check(ReturnValue, 'Call to addUser should return true'); ReturnValue := FMongo.authenticate(Name, password); Check(ReturnValue, 'Call to authenticate should return true'); CheckEqualsString('admin', FMongo.getLoginDatabaseName, 'Default database name is "admin" when it is not specified'); RemoveTest_user('admin'); end; procedure TestTMongo.TestaddUserWithDBParam; var ReturnValue: Boolean; db: UTF8String; password: UTF8String; Name: UTF8String; begin Name := 'test_user'; password := 'test_password'; db := 'test_db'; ReturnValue := FMongo.addUser(Name, password, db); Check(ReturnValue, 'Call to Mongo.addUser should return true'); RemoveTest_user('test_db'); end; procedure TestTMongo.Testauthenticate; var ReturnValue: Boolean; password: UTF8String; Name: UTF8String; begin Name := 'test_user'; password := 'test_password'; ReturnValue := FMongo.addUser(Name, password); Check(ReturnValue, 'Call to Mongo.addUser should return true'); ReturnValue := FMongo.authenticate(Name, password); RemoveTest_user('admin'); Check(ReturnValue, 'Call to Mongo.authenticate with good credentials should return True'); end; procedure TestTMongo.TestauthenticateWithSpecificDB; var ReturnValue: Boolean; db: UTF8String; password: UTF8String; Name: UTF8String; begin Name := 'test_user'; password := 'test_password'; ReturnValue := FMongo.addUser(Name, password); Check(ReturnValue, 'Call to Mongo.addUser should return true'); db := 'admin'; ReturnValue := FMongo.authenticate(Name, password, db); RemoveTest_user('admin'); Check(ReturnValue, 'Call to Mongo.authenticate with good credentials and specific db should return True'); end; procedure TestTMongo.TestauthenticateFail; var ReturnValue: Boolean; password: UTF8String; Name: UTF8String; begin Name := 'Bla'; Password := 'Fake'; ReturnValue := FMongo.authenticate(Name, password); Check(not ReturnValue, 'Call to Mongo.authenticate with fake credentials should return False'); end; procedure TestTMongo.TestcommandWithBson; var ReturnValue: IBson; command: IBson; db: UTF8String; begin Create_test_db; command := BSON(['isMaster', null]); db := 'test_db'; ReturnValue := FMongo.command(db, command); Check(ReturnValue <> nil, 'Call to Mongo.command should return <> nil'); CheckEquals(True, ReturnValue.Value('ismaster'), 'ismaster should be equals to True'); end; procedure TestTMongo.TestcommandWithArgs; var ReturnValue: IBson; arg: Variant; cmdstr: UTF8String; db: UTF8String; begin Create_test_db; db := 'test_db'; cmdstr := 'isMaster'; arg := null; ReturnValue := FMongo.command(db, cmdstr, arg); Check(ReturnValue <> nil, 'Call to Mongo.command should return <> nil'); CheckEquals(True, ReturnValue.Value('ismaster'), 'ismaster should be equals to True'); end; procedure TestTMongo.TestFailedConnection; begin try TMongo.Create('127.0.0.1:9999'); Fail('Attempt to create mongo object with unexisting server should result on Exception'); except on E : EMongo do CheckEquals(E_ConnectionToMongoServerFailed, E.ErrorCode, 'Attempt to create mongo object should result in error, server doesn''t exist'); end; end; procedure TestTMongo.TestFindAndModifyBasic; var Res : IBson; ResultBson : IBsonIterator; begin Res := FMongo.findAndModify('test_db.test_col', ['key', 0], [], ['key', 11, 'str', 'string'], [], [tfamoNew, tfamoUpsert]); Check(Res <> nil, 'Result from call to findAndModify should be <> nil'); ResultBson := Res.find('value').subiterator; Check(ResultBson <> nil, 'subiterator should be <> nil'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckNotEqualsString('', ResultBson.getOID.asString); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEquals(11, ResultBson.value); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString('string', ResultBson.value); end; procedure TestTMongo.TestFindAndModifyUsingBSONOID; const Data : UTF8String = 'Hello world'; var Res : IBson; buf : IBsonBuffer; id, id2 : IBsonOID; ResultBson : IBsonIterator; begin id := NewBsonOID; buf := NewBsonBuffer; buf.append('_id', id); buf.appendStr('strattr', 'hello'); Check(FMongo.Insert('test_db.test_col', buf.finish), 'Call to FMongo.Insert should return true'); id2 := NewBsonOID(id.asString); Res := FMongo.findAndModify('test_db.test_col', ['_id', id2], [], ['strattr', 'world', 'ts', NewBsonTimestamp(Now, 0), 'bin', NewBsonBinary(PAnsiString(Data), length(Data))], [], [tfamoNew]); Check(Res <> nil, 'Result from call to findAndModify should be <> nil'); ResultBson := Res.find('value').subiterator; Check(ResultBson <> nil, 'subiterator should be <> nil'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString(id.asString, ResultBson.getOID.asString); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString('world', ResultBson.value, 'value of attribute strattr doesn''t match'); Check(ResultBson.next, 'Call to iterator.next should return True'); Check(ResultBson.getTimestamp <> nil, 'value of attribute should be a timestamp'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEquals(length(Data), ResultBson.getBinary.Len, 'value of attribute should be a binary'); Check(not ResultBson.next, 'Call to iterator.next should return False'); end; procedure TestTMongo.TestFindAndModifyExtended; var Res : IBson; ResultBson, SubIt : IBsonIterator; begin Res := FMongo.findAndModify('test_db.test_col', ['key', 0], [], ['key', 11, 'str', 'string', 'str_2', 'string_2', 'arr', Start_Array, 0, End_Array], [], [tfamoNew, tfamoUpsert]); Check(Res <> nil, 'Result from call to findAndModify should be <> nil'); Res := FMongo.findAndModify('test_db.test_col', ['key', 11], ['key', 1], ['$inc', Start_Object, 'key', 1, End_Object, '$set', Start_Object, 'str', 'newstr', 'arr', Start_Array, 1, 2, 3, End_Array, End_Object], ['key', 'str', 'arr'], [tfamoNew]); Check(Res <> nil, 'Result from call to findAndModify should be <> nil'); ResultBson := Res.find('value').subiterator; Check(ResultBson <> nil, 'subiterator should be <> nil'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckNotEqualsString('', ResultBson.getOID.asString); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString('key', ResultBson.key, 'Key of last element should be equals to key'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString('str', ResultBson.key, 'Key of last element should be equals to str'); Check(ResultBson.next, 'Call to iterator.next should return True'); CheckEqualsString('arr', ResultBson.key, 'Key of last element should be equals to arr'); SubIt := ResultBson.subiterator; Check(SubIt <> nil, 'SubIterator should bve <> nil'); Check(SubIt.next, 'SubIt.next should return true'); CheckEquals(1, SubIt.value, 'First value of sub array doesn''t match'); Check(SubIt.next, 'SubIt.next should return true'); CheckEquals(2, SubIt.value, 'Second value of sub array doesn''t match'); Check(SubIt.next, 'SubIt.next should return true'); CheckEquals(3, SubIt.value, 'Third value of sub array doesn''t match'); Check(not SubIt.next, 'Call to iterator.next should return False'); Check(not ResultBson.next, 'Call to iterator.next should return false, no more fields returned'); end; procedure TestTMongo.TestgetLastErr; var ReturnValue: IBson; db: UTF8String; begin db := 'test_db'; ReturnValue := FMongo.getLastErr(db); Check(ReturnValue = nil, 'Call to Mongo.getLastErr should return = nil'); end; procedure TestTMongo.TestgetPrevErr; var ReturnValue: IBson; db: UTF8String; begin db := 'test_db'; ReturnValue := FMongo.getPrevErr(db); Check(ReturnValue = nil, 'Call to Mongo.getLastErr should return = nil'); end; procedure TestTMongo.TestresetErr; var db: UTF8String; begin FMongo.resetErr(db); Check(True); end; procedure TestTMongo.TestgetServerErr; var ReturnValue: Integer; begin ReturnValue := FMongo.getServerErr; CheckEquals(0, ReturnValue, 'Error code should be equals to zero'); end; procedure TestTMongo.TestgetServerErrString; var ReturnValue: UTF8String; begin ReturnValue := FMongo.getServerErrString; CheckEqualsString('', ReturnValue, 'Error UTF8String should be equals to blank UTF8String'); end; procedure TestTMongo.TestFourThreads; const ThreadCount = 4; var ts : array of TMongoThread; i : integer; begin SetLength (ts, ThreadCount); for I := low(ts) to high(ts) do ts[i] := TMongoThread.Create(self); try for I := low(ts) to high(ts) do ts[i].Resume; for I := low(ts) to high(ts) do ts[i].WaitFor; for I := low(ts) to high(ts) do CheckEqualsString('', ts[i].ErrorStr, 'ErrorString should be equals to blank UTF8String'); finally for I := low(ts) to high(ts) do ts[i].Free; end; end; procedure TestTMongo.TestgetLoginDatabaseName_Defined; var ReturnValue: Boolean; password: UTF8String; Name: UTF8String; db : UTF8String; begin RestartMongo; sleep(1000); Name := 'test_user_xx'; password := 'test_password_xx'; db := 'test_db'; ReturnValue := FMongo.createUser(Name, password, db, ['dbAdmin', 'readWrite']); Check(ReturnValue, 'Call to addUser should return true'); Sleep(500); RestartMongo(True); sleep(1000); ReturnValue := FMongo.authenticate(Name, password, db); try Check(ReturnValue, 'Call to authenticate should return true'); CheckEqualsString(db, FMongo.getLoginDatabaseName); //RemoveTest_user; finally RestartMongo(False); sleep(1000); end; end; procedure TestTMongo.TestindexCreateUsingBsonKeyAndNameAndOptions; var ReturnValue: IBson; options: Integer; key: IBson; ns: UTF8String; begin Create_test_db; InsertAndCheckBson(1, 'Value1'); ns := 'test_db.test_col'; key := BSON(['int_fld', True]); options := indexUnique; ReturnValue := FMongo.indexCreate(ns, key, PAnsiChar('test_index_name'), Options); Check(ReturnValue = nil, 'Call to Mongo.indexCreate should return nil if successful'); end; procedure TestTMongo.TestSetAndGetOpTimeout; begin CheckEquals(0, FMongo.OpTimeout); FMongo.OpTimeout := 10000; CheckEquals(10000, FMongo.OpTimeout); end; procedure TestTMongo.TestUseWriteConcern; var wc : IWriteConcern; begin Create_test_db; wc := NewWriteConcern; wc.j := 1; wc.finish; FMongo.setWriteConcern(wc); InsertAndCheckBson(1, 'Value1'); FMongo.setWriteConcern(nil); InsertAndCheckBson(2, 'Value2'); end; procedure TestTMongo.TestTryToUseUnfinishedWriteConcern; var wc : IWriteConcern; begin wc := NewWriteConcern; wc.j := 1; try FMongo.setWriteConcern(wc); Fail('Should have failed with error that tried to use unfinished writeconcern'); except on E : EMongo do CheckEquals(E_CanTUseAnUnfinishedWriteConcern, E.ErrorCode, 'Exception expected should be that tried to use unfinished writeconcern'); end; end; { TestTMongoReplset } function TestTMongoReplset.CreateMongo: TMongo; begin Result := TMongoReplset.Create('foo'); with Result as TMongoReplset do begin addSeed('127.0.0.1:27018'); addSeed('127.0.0.1:27019'); addSeed('127.0.0.1:27020'); end; end; procedure TestTMongoReplset.RestartMongo(Authenticated: Boolean = False); begin FreeAndNil(FMongo); ShutDownMongoDB; MongoStarted := False; FSlaveStarted := False; StartReplSet(Authenticated); StartMongo(Authenticated); FMongo := CreateMongo; FMongoReplset := FMongo as TMongoReplset; FMongoReplset.Connect; end; procedure TestTMongoReplset.SetUp; begin inherited; StartReplSet; FMongoReplset := FMongo as TMongoReplset; FMongoReplset.Connect; end; procedure TestTMongoReplset.TearDown; begin inherited; FMongoReplset := nil; end; procedure TestTMongoReplset.TestFourThreads; begin // Let's skip this test. It's known to fail with Replicas Check(True); end; procedure TestTMongoReplset.TestgetHost; var i, n: Integer; List : TStringList; begin n := FMongoReplset.getHostCount; CheckEquals(3, n, 'Host count should be equals to 3'); List := TStringList.Create; try List.Sorted := True; for i := 0 to n - 1 do List.Add(FMongoReplset.getHost(i)); CheckEqualsString('127.0.0.1:27018', List[0], 'First host should be "127.0.0.1:27018"'); CheckEqualsString('127.0.0.1:27019', List[1], 'First host should be "127.0.0.1:27019"'); CheckEqualsString('127.0.0.1:27020', List[2], 'First host should be "127.0.0.1:27020"'); finally List.Free; end; end; procedure TestTMongoReplset.TestgetLoginDatabaseName_Defined; begin Check(true); end; { TestIMongoCursor } const SampleDataCount = 1000; SampleDataDB = 'test_db.sampledata'; procedure TestIMongoCursor.DeleteSampleData; begin FMongo.drop(PAnsiChar(SampleDataDB)); end; procedure TestIMongoCursor.SetUp; begin inherited; FIMongoCursor := NewMongoCursor; StartReplSet; FMongo := TMongoReplset.Create('foo'); with FMongo as TMongoReplset do begin addSeed('127.0.0.1:27018'); addSeed('127.0.0.1:27019'); addSeed('127.0.0.1:27020'); Connect; end; {TestMongoBase.StartMongo; FMongo := TMongo.Create;} end; procedure TestIMongoCursor.SetupData; var b : IBsonBuffer; i : integer; s : UTF8String; begin for I := 0 to SampleDataCount - 1 do begin b := NewBsonBuffer; b.Append(PAnsiChar('ID'), i); s := Format('STR_%0.4d', [SampleDataCount - i]); b.AppendStr(PAnsiChar('STRVAL'), PAnsiChar(s)); FMongo.Insert(PAnsiChar(SampleDataDB), b.finish); end; end; procedure TestIMongoCursor.TearDown; begin DeleteSampleData; FIMongoCursor := nil; FMongo.dropDatabase('test_db'); FMongo.Free; if FMongoSecondary <> nil then FreeAndNil(FMongoSecondary); inherited; end; procedure TestIMongoCursor.TestGetConn; var ReturnValue: TMongo; begin FIMongoCursor.Conn := FMongo; ReturnValue := FIMongoCursor.GetConn; Check(ReturnValue = FMongo, 'FIMongoCursor.GetConn should be equals to FMongo'); end; procedure TestIMongoCursor.TestGetFields; var AFields : IBson; ReturnValue: IBson; begin SetupData; AFields := BSON(['ID', 1]); FIMongoCursor.Fields := AFields; Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); Check(FIMongoCursor.Next, 'Call to FIMongoCursor.Next should return True'); ReturnValue := FIMongoCursor.Fields; Check(ReturnValue = AFields, 'Call to FIMongoCursor.GetFields should return a non-nil Bson object'); end; procedure TestIMongoCursor.TestGetHandle; var ReturnValue: Pointer; begin FMongo.find(SampleDataDB, FIMongoCursor); // This is needed to populate the iterator handle ReturnValue := FIMongoCursor.Handle; Check(ReturnValue <> nil, 'Call to FIMongoCursor.Handle should return a value <> nil'); end; procedure TestIMongoCursor.TestGetLimit; var ReturnValue: Integer; begin FIMongoCursor.Limit := 10; ReturnValue := FIMongoCursor.GetLimit; CheckEquals(10, ReturnValue, 'FIMongoCursor.Limit should be equals to 10'); end; procedure TestIMongoCursor.TestGetOptions; var ReturnValue: Integer; begin FIMongoCursor.Options := cursorPartial; ReturnValue := FIMongoCursor.GetOptions; CheckEquals(cursorPartial, ReturnValue, 'FIMongoCursor.Options should be equals to cursorPartial'); end; procedure TestIMongoCursor.TestGetQuery; var ReturnValue: IBson; AQuery : IBson; begin AQuery := BSON(['ID', 0]); FIMongoCursor.Query := AQuery; ReturnValue := FIMongoCursor.Query; Check(ReturnValue = AQuery, 'FIMongoCursor.Query should return value equal to AQuery'); end; procedure TestIMongoCursor.TestGetSkip; var ReturnValue: Integer; begin FIMongoCursor.Skip := 10; ReturnValue := FIMongoCursor.GetSkip; CheckEquals(10, ReturnValue, 'Call to FIMongoCursor.Skip should be equals to 10'); end; procedure TestIMongoCursor.TestGetSort; var ASort : IBson; ReturnValue: IBson; begin ASort := BSON(['ID', True]); FIMongoCursor.Sort := ASort; ReturnValue := FIMongoCursor.GetSort; Check(ReturnValue = FIMongoCursor.Sort, 'Call to FIMongoCursor.Sort should return value equals to ASort'); end; procedure TestIMongoCursor.TestNext; var ReturnValue: Boolean; begin FMongo.find(SampleDataDB, FIMongoCursor); ReturnValue := FIMongoCursor.Next; Check(not ReturnValue, 'FIMongoCursor.Next should return false when trying to get cursor to collection without data'); SetupData; FMongo.find(SampleDataDB, FIMongoCursor); ReturnValue := FIMongoCursor.Next; Check(ReturnValue, 'FIMongoCursor.Next should return true when trying to get cursor to collection with data'); end; procedure TestIMongoCursor.TestSetFields; var v : Variant; begin SetupData; FIMongoCursor.Fields := BSON(['ID', 1]); Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); Check(FIMongoCursor.Next, 'Call to FIMongoCursor.Next should return true'); v := FIMongoCursor.Value.Value('ID'); Check(not VarIsNull(v), 'Value returned by FIMongoCursor.Value.Value("ID") should be different from variant NULL'); v := FIMongoCursor.Value.Value('STRVAL'); Check(VarIsNull(v), 'Value returned by FIMongoCursor.Value.Value("STRVAL") should be variant NULL'); FIMongoCursor.Fields := BSON(['ID', 1, 'STRVAL', 1]); Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); Check(FIMongoCursor.Next, 'Call to FIMongoCursor.Next should return true'); v := FIMongoCursor.Value.Value('ID'); Check(not VarIsNull(v), 'Value returned by FIMongoCursor.Value.Value("ID") should be different from variant NULL'); v := FIMongoCursor.Value.Value('STRVAL'); Check(not VarIsNull(v), 'Value returned by FIMongoCursor.Value.Value("STRVAL") should be different from variant NULL'); end; procedure TestIMongoCursor.TestSetLimit; var n : integer; begin SetupData; FIMongoCursor.Limit := 10; Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); n := 0; while FIMongoCursor.Next do inc(n); CheckEquals(10, n, 'Number of Bson objects returned should be equals to 10'); end; procedure TestIMongoCursor.TestSetOptions; begin FMongoSecondary := TMongo.Create('127.0.0.1:27019'); SetupData; try FMongoSecondary.find(SampleDataDB, FIMongoCursor); // Call can succeed or fail, depending if we end up hitting the primary. // There where cases where 27019 was primary except on E : EMongo do Check((E.ErrorCode = E_MongoDBServerError) and (pos('not master', E.Message) > 0), 'Call should have errored our because Secondary option was not set'); end; FIMongoCursor := nil; FIMongoCursor := NewMongoCursor; FIMongoCursor.Options := cursorSlaveOk; Check(FMongoSecondary.find(SampleDataDB, FIMongoCursor), 'Call to FMongoSecondary.Find should return True'); FIMongoCursor := nil; end; procedure TestIMongoCursor.TestSetQuery; var n : integer; begin SetupData; FIMongoCursor.Query := BSON(['ID', 0]); Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); n := 0; while FIMongoCursor.Next do inc(n); CheckEquals(1, n, 'Number of objects returned should be equals to 1'); end; procedure TestIMongoCursor.TestSetSkip; var n: Integer; begin SetupData; FIMongoCursor.Skip := SampleDataCount - 50; Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return true'); n := 0; while FIMongoCursor.Next do inc(n); CheckEquals(50, n, 'Number of objects returned should be equals to 1'); end; procedure TestIMongoCursor.TestSetSort; var Prev, Value : UTF8String; n : integer; begin SetupData; Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return true'); Prev := 'STR_' + IntToStr(SampleDataCount + 1); n := 0; while FIMongoCursor.Next do begin Value := FIMongoCursor.Value.Value('STRVAL'); Check(Value < Prev, 'Value should be lesser than previous value'); Prev := Value; inc(n); end; CheckEquals(SampleDataCount, n, 'Number of objects returned should be ' + IntToStr(SampleDataCount)); FMongo.indexCreate(SampleDataDB, 'STRVAL'); FIMongoCursor := NewMongoCursor; FIMongoCursor.Sort := BSON(['STRVAL', 1]); Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return true'); Prev := 'STR_0000'; n := 0; while FIMongoCursor.Next do begin Value := FIMongoCursor.Value.Value('STRVAL'); Check(Value > Prev, 'Value should be higher than previous value'); Prev := Value; inc(n); end; CheckEquals(SampleDataCount, n, 'Number of objects returned should be ' + IntToStr(SampleDataCount)); end; procedure TestIMongoCursor.TestValue; var ReturnValue: IBson; begin SetupData; Check(FMongo.find(SampleDataDB, FIMongoCursor), 'Call to FMongo.Find should return True'); FIMongoCursor.Next; ReturnValue := FIMongoCursor.Value; Check(ReturnValue <> nil, 'Call to FIMongoCursor.Value should return a value <> nil'); end; { TMongoThread } constructor TMongoThread.Create(AMongoTest: TestTMongo); begin inherited Create(True); FMongoTest := AMongoTest; end; procedure TMongoThread.Execute; const ObjCount = 50; var AMongo : TMongo; Buf : IBsonBuffer; b, q : IBson; i : integer; OID : IBsonOID; n : Integer; Ids : array [0..ObjCount] of Integer; procedure ReCreateConnection; begin FreeAndNil(AMongo); AMongo := FMongoTest.CreateMongo; if AMongo is TMongoReplset then (AMongo as TMongoReplset).Connect; end; begin try AMongo := FMongoTest.CreateMongo; try if AMongo is TMongoReplset then (AMongo as TMongoReplset).Connect; for I := 0 to ObjCount do begin Buf := NewBsonBuffer; OID := NewBsonOID; Buf.Append(PAnsiChar('_id'), OID); n := Random(1024); Buf.Append(PAnsiChar('NUM'), n); Buf.AppendStr(PAnsiChar('STRDATA'), PAnsiChar('1234' + IntToStr(i))); b := Buf.finish; Ids[i] := n; AMongo.Insert('test_db.test_thread', b); if (Random(3) = 1) and not(AMongo is TMongoReplset) then ReCreateConnection; end; for I := 0 to ObjCount do begin q := BSON(['NUM', Ids[i]]); b := AMongo.findOne('test_db.test_thread', q); if (b = nil) or (b.Value(PAnsiChar('NUM')) <> Ids[i]) then raise Exception.CreateFmt('Object not found. Value: %d, Array index: %d', [Ids[i], i]); if (Random(3) = 1) and not(AMongo is TMongoReplset) then ReCreateConnection; end; Sleep(500); finally if AMongo <> nil then AMongo.Free; end; except on E : Exception do ErrorStr := E.Message; end; end; { TestMongoCustomizations } procedure TestMongoCustomizations.TestCustomFuzzFn; begin CheckNotEquals(0, CustomFuzzFn, 'CustomFuzzFn should return a value <> 0'); end; procedure TestMongoCustomizations.TestCustomIncrFn; begin CheckNotEquals(0, CustomIncrFn, 'CustomIncrFn should return a value <> 0'); end; procedure TestWriteConcern.SetUp; begin inherited; fwc := NewWriteConcern; end; procedure TestWriteConcern.TearDown; begin fwc := nil; inherited; end; { TestWriteConcern } procedure TestWriteConcern.TestSetAndGet_j; begin fwc.j := 101; CheckEquals(101, fwc.j); end; procedure TestWriteConcern.TestSetAndGet_fsync; begin fwc.fsync := 101; CheckEquals(101, fwc.fsync); end; procedure TestWriteConcern.TestGet_cmd; var ACmd : IBson; begin fwc.j := 101; Check(fwc.cmd = nil, 'cmd should be equals to nil'); fwc.finish; ACmd := fwc.cmd; Check(ACmd <> nil, 'cmd should be <> nil'); CheckEquals(101, ACmd.value('j')); end; procedure TestWriteConcern.TestGet_cmd_check_getlasterror; var ACmd : IBson; begin fwc.j := 101; fwc.finish; ACmd := fwc.cmd; CheckEquals(1, ACmd.value('getlasterror')); end; procedure TestWriteConcern.TestGet_cmd_with_w_equals1; var ACmd : IBson; begin fwc.w := 1; fwc.finish; ACmd := fwc.cmd; Check(ACmd.find('w') = nil, 'w value should not be included because value = 1 was passed'); end; procedure TestWriteConcern.TestGet_cmd_with_mode_equals_majority; var ACmd : IBson; begin fwc.mode := 'majority'; fwc.finish; ACmd := fwc.cmd; CheckEqualsString('majority', ACmd.value('w')); end; procedure TestWriteConcern.TestGet_cmd_with_jwfsyncwtimeout; var ACmd : IBson; begin fwc.w := 4; fwc.fsync := 2; fwc.wtimeout := 1000; fwc.j := 3; fwc.finish; ACmd := fwc.cmd; CheckEquals(4, ACmd.value('w')); CheckEquals(2, ACmd.value('fsync')); CheckEquals(1000, ACmd.value('wtimeout')); CheckEquals(3, ACmd.value('j')); end; procedure TestWriteConcern.TestGet_cmd_with_w_equals2; var ACmd : IBson; begin fwc.w := 2; fwc.finish; ACmd := fwc.cmd; CheckEquals(2, ACmd.Value('w'), 'w value should equals to 2'); end; procedure TestWriteConcern.TestSetAndGet_wtimeout; begin fwc.wtimeout := 101; CheckEquals(101, fwc.wtimeout); end; procedure TestWriteConcern.TestSetAndGet_mode; begin fwc.mode := 'Hola'; CheckEqualsString('Hola', fwc.mode); end; procedure TestWriteConcern.TestSetAndGet_w; begin fwc.w := 1; CheckEquals(1, fwc.w); fwc.w := 101; CheckEquals(101, fwc.w); end; {$IFDEF OnDemandMongoCLoad} var MongoCDLLName : UTF8String; {$ENDIF} initialization {$IFDEF OnDemandMongoCLoad} if (ParamStr(1) = '') or (CompareText(ExtractFileExt(ParamStr(1)), '.dll') <> 0) then MongoCDLLName := Default_MongoCDLL else {$IFDEF Enterprise} MongoCDLLName := Default_MongoCDLL; {$Else} MongoCDLLName := ParamStr(1); {$ENDIF} InitMongoDBLibrary(MongoCDLLName); {$ENDIF} bsonEmpty; // Call bsonEmpty on initialization to avoid reporting of memory leak when enabled // Register any test cases with the test runner RegisterTest(TestTMongo.Suite); RegisterTest(TestTMongoReplset.Suite); RegisterTest(TestIMongoCursor.Suite); RegisterTest(TestMongoCustomizations.Suite); RegisterTest(TestWriteConcern.Suite); finalization if MongoStarted then ShutDownMongoDB; end.
unit FMX.VPR.Polygons; (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Vectorial Polygon Rasterizer for FMX. * * The Initial Developer of the Original Code is * Mattias Andersson <mattias@centaurix.com> * * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) interface {$I VPR.INC} uses Winapi.Windows, System.Types, System.Classes, FMX.Types, FMX.VPR; type TJoinStyle = (jsMiter, jsBevel, jsRound); TEndStyle = (esButt, esSquare, esRound); function PolyPolylineFS(const Points: TPolyPolygon; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; function PolylineFS(const Points: TPolygon; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; function DashedPolylineFS(const Points: TPolygon; const DashArray: TDashArray; DashOffset: Single = 0; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; function BuildDashedLine(const Points: TPolygon; const DashArray: TDashArray; DashOffset: Single = 0; Scale: Single = 1): TPolyPolygon; function PolygonBounds(const Points: TPolygon): TRectF; overload; function PolygonBounds(const PP: TPolyPolygon): TRectF; overload; function ClipPolygon(const Points: TPolygon; const ClipRect: TRectF): TPolygon; function ClosePolygon(const Points: TPolygon): TPolygon; procedure TextToPath(Font: HFONT; Path: TPathData; const ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign); overload; function MeasureText(Font: HFONT; const ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign): TRectF; overload; function _Round(var X: Single): Integer; {$IFDEF CPUX86} function Round(const X: Single): Integer; {$ENDIF} function Hypot(const X, Y: Single): Single; function StackAlloc(Size: Integer): Pointer; register; procedure StackFree(P: Pointer); register; var UseHinting: Boolean = {$IFDEF NOHINTING}False{$ELSE}True{$ENDIF}; // stretching factor when calling GetGlyphOutline() const HORZSTRETCH = 16; implementation uses System.Math; function Hypot(const X, Y: Single): Single; {$IFDEF PUREPASCAL} begin Result := Sqrt(Sqr(X) + Sqr(Y)); {$ELSE} asm {$IFDEF CPUX86} FLD X FMUL ST,ST FLD Y FMUL ST,ST FADDP ST(1),ST FSQRT FWAIT {$ENDIF} {$IFDEF CPUX64} MULSS XMM0, XMM0 MULSS XMM1, XMM1 ADDSS XMM0, XMM1 SQRTSS XMM0, XMM0 {$ENDIF} {$ENDIF} end; {$IFDEF CPUX86} function _Round(var X: Single): Integer; asm fld [X] fistp dword ptr [esp-4] mov eax,[esp-4] end; function Round(const X: Single): Integer; asm fld X fistp dword ptr [esp-4] mov eax,[esp-4] end; {$ELSE} function _Round(var X: Single): Integer; begin Result := Round(X); end; {$ENDIF} const {$HINTS OFF} TWOPI = 6.283185308; {$HINTS ON} {$IFDEF CPUX86} { StackAlloc allocates a 'small' block of memory from the stack by decrementing SP. This provides the allocation speed of a local variable, but the runtime size flexibility of heap allocated memory. } function StackAlloc(Size: Integer): Pointer; register; asm POP ECX { return address } MOV EDX, ESP ADD EAX, 3 AND EAX, not 3 // round up to keep ESP dword aligned CMP EAX, 4092 JLE @@2 @@1: SUB ESP, 4092 PUSH EAX { make sure we touch guard page, to grow stack } SUB EAX, 4096 JNS @@1 ADD EAX, 4096 @@2: SUB ESP, EAX MOV EAX, ESP { function result = low memory address of block } PUSH EDX { save original SP, for cleanup } MOV EDX, ESP SUB EDX, 4 PUSH EDX { save current SP, for sanity check (sp = [sp]) } PUSH ECX { return to caller } end; { StackFree pops the memory allocated by StackAlloc off the stack. - Calling StackFree is optional - SP will be restored when the calling routine exits, but it's a good idea to free the stack allocated memory ASAP anyway. - StackFree must be called in the same stack context as StackAlloc - not in a subroutine or finally block. - Multiple StackFree calls must occur in reverse order of their corresponding StackAlloc calls. - Built-in sanity checks guarantee that an improper call to StackFree will not corrupt the stack. Worst case is that the stack block is not released until the calling routine exits. } procedure StackFree(P: Pointer); register; asm POP ECX { return address } MOV EDX, DWORD PTR [ESP] SUB EAX, 8 CMP EDX, ESP { sanity check #1 (SP = [SP]) } JNE @@1 CMP EDX, EAX { sanity check #2 (P = this stack block) } JNE @@1 MOV ESP, DWORD PTR [ESP+4] { restore previous SP } @@1: PUSH ECX { return to caller } end; {$ENDIF} {$IFDEF CPUX64} function StackAlloc(Size: Integer): Pointer; register; begin GetMem(Result, Size); end; procedure StackFree(P: Pointer); register; begin FreeMem(P); end; (* function StackAlloc(Size: Integer): Pointer; register; asm MOV RAX, RCX POP RCX { return address } MOV RDX, RSP ADD RAX, 3 AND RAX, NOT 3 // round up to keep ESP dword aligned CMP RAX, 4092 JLE @@2 @@1: SUB RSP, 4092 PUSH RAX { make sure we touch guard page, to grow stack } SUB RAX, 4096 JNS @@1 ADD RAX, 4096 @@2: SUB RSP, RAX MOV RAX, RSP { function result = low memory address of block } PUSH RDX { save original SP, for cleanup } MOV RDX, RSP SUB RDX, 8 PUSH RDX { save current SP, for sanity check (sp = [sp]) } PUSH RCX { return to caller } end; procedure StackFree(P: Pointer); register; asm MOV RAX, RCX POP RCX { return address } MOV RDX, QWORD PTR [RSP] SUB RAX, 8 CMP RDX, RSP { sanity check #1 (SP = [SP]) } JNE @@1 CMP RDX, RAX { sanity check #2 (P = this stack block) } JNE @@1 MOV RSP, QWORD PTR [RSP+8] { restore previous SP } @@1: PUSH RCX { return to caller } end; *) {$ENDIF} function ClosePolygon(const Points: TPolygon): TPolygon; var L: Integer; P1, P2: TPointF; begin L := Length(Points); Result := Points; if L <= 1 then Exit; P1 := Result[0]; P2 := Result[L - 1]; if (P1.X = P2.X) and (P1.Y = P2.Y) then Exit; SetLength(Result, L+1); Move(Result[0], Points[0], L*SizeOf(TPointF)); Result[L] := P1; end; function InterpolateX(X: Single; const P1, P2: TPointF): TPointF; var W: Single; begin W := (X - P1.X) / (P2.X - P1.X); Result.X := X; Result.Y := P1.Y + W * (P2.Y - P1.Y); end; function InterpolateY(Y: Single; const P1, P2: TPointF): TPointF; var W: Single; begin W := (Y - P1.Y) / (P2.Y - P1.Y); Result.Y := Y; Result.X := P1.X + W * (P2.X - P1.X); end; function GetCode(const P: TPointF; const R: TRectF): Integer; inline; begin Result := Ord(P.X >= R.Left) or (Ord(P.X <= R.Right) shl 1) or (Ord(P.Y >= R.Top) shl 2) or (Ord(P.Y <= R.Bottom) shl 3); end; {$IFDEF USESTACKALLOC} {$W+} {$ENDIF} function ClipPolygon(const Points: TPolygon; const ClipRect: TRectF): TPolygon; type TInterpolateProc = function(X: Single; const P1, P2: TPointF): TPointF; TByteArray = array [0..0] of Byte; PByteArray = ^TByteArray; const SAFEOVERSIZE = 5; POPCOUNT: array [0..15] of Integer = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); var I, J, K, L, N: Integer; X, Y, Z, Code, Count: Integer; Codes: PByteArray; NextIndex: PIntegerArray; Temp: PPointArray; label ExitProc; procedure AddPoint(Index: Integer; const P: TPointF); begin Temp[K] := P; Codes[K] := GetCode(P, ClipRect); Inc(K); Inc(Count); end; function ClipEdges(Mask: Integer; V: Single; Interpolate: TInterpolateProc): Boolean; var I, NextI, StopIndex: Integer; begin I := 0; while (I < K) and (Codes[I] and Mask = 0) do Inc(I); Result := I = K; if Result then { all points outside } begin ClipPolygon := nil; Result := True; Exit; end; StopIndex := I; repeat NextI := NextIndex[I]; if Codes[NextI] and Mask = 0 then { inside -> outside } begin NextIndex[I] := K; NextIndex[K] := K + 1; AddPoint(I, Interpolate(V, Temp[I], Temp[NextI])); while Codes[NextI] and Mask = 0 do begin Dec(Count); Codes[NextI] := 0; I := NextI; NextI := NextIndex[I]; end; { outside -> inside } NextIndex[K] := NextI; AddPoint(I, Interpolate(V, Temp[I], Temp[NextI])); end; I := NextI; until I = StopIndex; end; begin N := Length(Points); {$IFDEF USESTACKALLOC} Codes := StackAlloc(N * SAFEOVERSIZE); {$ELSE} GetMem(Codes, N * SAFEOVERSIZE); {$ENDIF} X := 15; Y := 0; for I := 0 to N - 1 do begin Code := GetCode(Points[I], ClipRect); Codes[I] := Code; X := X and Code; Y := Y or Code; end; if X = 15 then { all points inside } begin Result := Points; end else if Y <> 15 then { all points outside } begin Result := nil; end else begin Count := N; Z := Codes[N - 1]; for I := 0 to N - 1 do begin Code := Codes[I]; Inc(Count, POPCOUNT[Z xor Code]); Z := Code; end; {$IFDEF USESTACKALLOC} Temp := StackAlloc(Count * SizeOf(TPointF)); NextIndex := StackAlloc(Count * SizeOf(TPointF)); {$ELSE} GetMem(Temp, Count * SizeOf(TPointF)); GetMem(NextIndex, Count * SizeOf(TPointF)); {$ENDIF} Move(Points[0], Temp[0], N * SizeOf(TPointF)); for I := 0 to N - 2 do NextIndex[I] := I + 1; NextIndex[N - 1] := 0; Count := N; K := N; if X and 1 = 0 then if ClipEdges(1, ClipRect.Left, InterpolateX) then goto ExitProc; if X and 2 = 0 then if ClipEdges(2, ClipRect.Right, InterpolateX) then goto ExitProc; if X and 4 = 0 then if ClipEdges(4, ClipRect.Top, InterpolateY) then goto ExitProc; if X and 8 = 0 then if ClipEdges(8, ClipRect.Bottom, InterpolateY) then goto ExitProc; SetLength(Result, Count); { start with first point inside the clipping rectangle } I := 0; while Codes[I] = 0 do I := NextIndex[I]; J := I; L := 0; repeat Result[L] := Temp[I]; Inc(L); I := NextIndex[I]; until I = J; ExitProc: {$IFDEF USESTACKALLOC} StackFree(NextIndex); StackFree(Temp); {$ELSE} FreeMem(NextIndex); FreeMem(Temp); {$ENDIF} end; {$IFDEF USESTACKALLOC} StackFree(Codes); {$ELSE} FreeMem(Codes); {$ENDIF} end; {$IFDEF USESTACKALLOC} {$W-} {$ENDIF} function PolygonBounds(const Points: TPolygon): TRectF; var I, N: Integer; begin N := Length(Points); if N = 0 then begin Result := Default(TRectF); Exit; end; Result.Left := Points[0].X; Result.Top := Points[0].Y; Result.Right := Points[0].X; Result.Bottom := Points[0].Y; for I := 1 to N - 1 do begin Result.Left := Min(Result.Left, Points[I].X); Result.Right := Max(Result.Right, Points[I].X); Result.Top := Min(Result.Top, Points[I].Y); Result.Bottom := Max(Result.Bottom, Points[I].Y); end; end; function PolygonBounds(const PP: TPolyPolygon): TRectF; var I: Integer; begin Result := PolygonBounds(PP[0]); for I := 1 to High(PP) do begin Result := UnionRect(Result, PolygonBounds(PP[I])); end; end; function BuildArc(const P: TPointF; a1, a2, r: Single; Steps: Integer): TPolygon; overload; var I, N: Integer; a, da, dx, dy: Single; begin SetLength(Result, Steps); N := Steps - 1; da := (a2 - a1) / N; a := a1; for I := 0 to N do begin SinCos(a, dy, dx); Result[I].X := P.X + dx * r; Result[I].Y := P.Y + dy * r; a := a + da; end; end; function BuildArc(const P: TPointF; a1, a2, r: Single): TPolygon; overload; const MINSTEPS = 6; var Steps: Integer; begin Steps := Max(MINSTEPS, Round(Sqrt(Abs(r)) * Abs(a2 - a1))); Result := BuildArc(P, a1, a2, r, Steps); end; function BuildNormals(const Points: TPolygon): TPolygon; var I, Count, NextI: Integer; dx, dy, f: Single; begin Count := Length(Points); SetLength(Result, Count); I := 0; NextI := 1; while I < Count do begin if NextI >= Count then NextI := 0; dx := Points[NextI].X - Points[I].X; dy := Points[NextI].Y - Points[I].Y; if (dx <> 0) or (dy <> 0) then begin f := 1/Sqrt(Sqr(dx) + Sqr(dy));//HypotRcp(dx, dy); dx := dx * f; dy := dy * f; end; Result[I].X := dy; Result[I].Y := -dx; Inc(I); Inc(NextI); end; end; function Grow(const Points: TPolygon; const Normals: TPolygon; const Delta: Single; JoinStyle: TJoinStyle; Closed: Boolean; MiterLimit: Single): TPolygon; overload; const BUFFSIZEINCREMENT = 128; var I, L, H: Integer; ResSize, BuffSize: integer; PX, PY, D, RMin: Single; A, B: TPointF; procedure AddPoint(const LongDeltaX, LongDeltaY: Single); begin if ResSize = BuffSize then begin inc(BuffSize, BUFFSIZEINCREMENT); SetLength(Result, BuffSize); end; with Result[ResSize] do begin X := PX + LongDeltaX; Y := PY + LongDeltaY; end; inc(resSize); end; procedure AddMitered(const X1, Y1, X2, Y2: Single); var R, CX, CY: Single; begin CX := X1 + X2; CY := Y1 + Y2; R := X1 * CX + Y1 * CY; if R < RMin then begin AddPoint(D * X1, D * Y1); AddPoint(D * X2, D * Y2); end else begin R := D / R; AddPoint(CX * R, CY * R) end; end; procedure AddBevelled(const X1, Y1, X2, Y2: Single); var R: Single; begin R := X1 * Y2 - X2 * Y1; if R * D <= 0 then begin AddMitered(X1, Y1, X2, Y2); end else begin AddPoint(D * X1, D * Y1); AddPoint(D * X2, D * Y2); end; end; procedure AddRoundedJoin(const X1, Y1, X2, Y2: Single); var R, a1, a2, da: Single; Arc: TPolygon; arcLen: integer; begin R := X1 * Y2 - X2 * Y1; if R * D <= 0 then begin AddMitered(X1, Y1, X2, Y2); end else begin a1 := ArcTan2(Y1, X1); a2 := ArcTan2(Y2, X2); da := a2 - a1; if da > Pi then a2 := a2 - TWOPI else if da < -Pi then a2 := a2 + TWOPI; Arc := BuildArc(PointF(PX, PY), a1, a2, D); arcLen := length(Arc); if resSize + arcLen >= BuffSize then begin inc(BuffSize, arcLen); SetLength(Result, BuffSize); end; Move(Arc[0], Result[resSize], Length(Arc) * SizeOf(TPointF)); inc(resSize, arcLen); end; end; procedure AddJoin(const X, Y, X1, Y1, X2, Y2: Single); begin PX := X; PY := Y; case JoinStyle of jsMiter: AddMitered(A.X, A.Y, B.X, B.Y); jsBevel: AddBevelled(A.X, A.Y, B.X, B.Y); jsRound: AddRoundedJoin(A.X, A.Y, B.X, B.Y); end; end; begin Result := nil; if Length(Points) <= 1 then Exit; D := Delta; RMin := 2/Sqr(MiterLimit); H := High(Points) - Ord(not Closed); while (H >= 0) and (Normals[H].X = 0) and (Normals[H].Y = 0) do Dec(H); {** all normals zeroed => Exit } if H < 0 then Exit; L := 0; while (Normals[L].X = 0) and (Normals[L].Y = 0) do Inc(L); if Closed then A := Normals[H] else A := Normals[L]; ResSize := 0; BuffSize := BUFFSIZEINCREMENT; SetLength(Result, BuffSize); for I := L to H do begin B := Normals[I]; if (B.X = 0) and (B.Y = 0) then Continue; with Points[I] do AddJoin(X, Y, A.X, A.Y, B.X, B.Y); A := B; end; if not Closed then with Points[High(Points)] do AddJoin(X, Y, A.X, A.Y, A.X, A.Y); SetLength(Result, resSize); end; function Grow(const Points: TPolygon; const Delta: Single; JoinStyle: TJoinStyle; Closed: Boolean; MiterLimit: Single): TPolygon; overload; var Normals: TPolygon; begin Normals := BuildNormals(Points); Result := Grow(Points, Normals, Delta, JoinStyle, Closed, MiterLimit); end; function ReversePolygon(const Points: TPolygon): TPolygon; var I, L: Integer; begin L := Length(Points); SetLength(Result, L); Dec(L); for I := 0 to L do Result[I] := Points[L - I]; end; function BuildLineEnd(const P, N: TPointF; const W: Single; EndStyle: TEndStyle): TPolygon; var a1, a2: Single; begin case EndStyle of esButt: begin Result := nil; end; esSquare: begin SetLength(Result, 2); Result[0].X := P.X + (N.X - N.Y) * W; Result[0].Y := P.Y + (N.Y + N.X) * W; Result[1].X := P.X - (N.X + N.Y) * W; Result[1].Y := P.Y - (N.Y - N.X) * W; end; esRound: begin a1 := ArcTan2(N.Y, N.X); a2 := ArcTan2(-N.Y, -N.X); if a2 < a1 then a2 := a2 + TWOPI; Result := BuildArc(P, a1, a2, W); end; end; end; function BuildPolyline(const Points: TPolygon; StrokeWidth: Single; JoinStyle: TJoinStyle; EndStyle: TEndStyle; MiterLimit: Single): TPolygon; var L, H: Integer; Normals: TPolygon; P1, P2, E1, E2: TPolygon; V: Single; P: PPointF; begin V := StrokeWidth * 0.5; Normals := BuildNormals(Points); P1 := Grow(Points, Normals, V, JoinStyle, False, MiterLimit); P2 := ReversePolygon(Grow(Points, Normals, -V, JoinStyle, False, MiterLimit)); H := High(Points) - 1; while (H >= 0) and (Normals[H].X = 0) and (Normals[H].Y = 0) do Dec(H); if H < 0 then begin // only one point => any normal will do H := 0; SetLength(Normals, 1); Normals[0].X := 0; Normals[0].Y := 1; end; L := 0; while (Normals[L].X = 0) and (Normals[L].Y = 0) do Inc(L); E1 := BuildLineEnd(Points[0], Normals[L], -V, EndStyle); E2 := BuildLineEnd(Points[High(Points)], Normals[H], V, EndStyle); SetLength(Result, Length(P1) + Length(P2) + Length(E1) + Length(E2)); P := @Result[0]; Move(E1[0], P^, Length(E1) * SizeOf(TPointF)); Inc(P, Length(E1)); Move(P1[0], P^, Length(P1) * SizeOf(TPointF)); Inc(P, Length(P1)); Move(E2[0], P^, Length(E2) * SizeOf(TPointF)); Inc(P, Length(E2)); Move(P2[0], P^, Length(P2) * SizeOf(TPointF)); end; function PolyPolylineFS(const Points: TPolyPolygon; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; var I: Integer; P1, P2: TPolygon; Dst: TPolyPolygon; Normals: TPolygon; begin if Closed then begin SetLength(Dst, Length(Points)*2); for I := 0 to High(Points) do begin Normals := BuildNormals(Points[I]); P1 := Grow(Points[I], Normals, StrokeWidth * 0.5, JoinStyle, true, MiterLimit); P2 := Grow(Points[I], Normals, -StrokeWidth * 0.5, JoinStyle, true, MiterLimit); Dst[I * 2] := P1; Dst[I * 2 + 1] := ReversePolygon(P2); end; end else begin SetLength(Dst, Length(Points)); for I := 0 to High(Points) do Dst[I] := BuildPolyline(Points[I], StrokeWidth, JoinStyle, EndStyle, MiterLimit); end; Result := Dst; end; function PolylineFS(const Points: TPolygon; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; var P: TPolyPolygon; begin SetLength(P, 1); P[0] := Points; Result := PolyPolylineFS(P, Closed, StrokeWidth, JoinStyle, EndStyle, MiterLimit); end; //============================================================================// type PBezierVertex = ^TBezierVertex; TBezierVertex = record case Integer of 0: (Point: TPointF; ControlPoints: array [0..1] of TPointF); 1: (Points: array [0..2] of TPointF); end; const GGO_UNHINTED = $0100; GGODefaultFlags: array [Boolean] of Integer = (GGO_NATIVE or GGO_UNHINTED, GGO_NATIVE); const FixedOne = $10000; VertFlip_mat2: tmat2 = ( eM11: (fract: 0; Value: {$IFNDEF NOHORIZONTALHINTING}1{$ELSE}HORZSTRETCH{$ENDIF}); eM12: (fract: 0; Value: 0); eM21: (fract: 0; Value: 0); eM22: (fract: 0; Value: -1); ); function QuadToBezier(Q0, Q1, Q2: TPointF): TBezierVertex; // Q-spline to Bezier curve: // B0 = Q0 // B1 = (Q0 + 2*Q1) / 3 // B2 = (Q0 + 2*Q2) / 3 begin with Result do begin Points[0] := Q0; Points[1].X := (Q0.X + 2*Q1.X) / 3; Points[1].Y := (Q0.Y + 2*Q1.Y) / 3; Points[2].X := (Q0.X + 2*Q2.X) / 3; Points[2].Y := (Q0.Y + 2*Q2.Y) / 3; end; end; procedure OffsetVertex(var Vertex: TBezierVertex; const Dx, Dy: Single); begin Vertex.Points[0].X := Vertex.Points[0].X + Dx; Vertex.Points[0].Y := Vertex.Points[0].Y + Dy; Vertex.Points[1].X := Vertex.Points[1].X + Dx; Vertex.Points[1].Y := Vertex.Points[1].Y + Dy; Vertex.Points[2].X := Vertex.Points[2].X + Dx; Vertex.Points[2].Y := Vertex.Points[2].Y + Dy; end; function PointFXtoPointF(const Point: tagPointFX): TPointF; begin Result.X := Point.X.Value + Point.X.Fract / FixedOne; Result.Y := Point.Y.Value + Point.Y.Fract / FixedOne; end; {$IFDEF USESTACKALLOC} {$W+} {$ENDIF} procedure GlyphOutlineToPath(Handle: HDC; Path: TPathData; DstX, DstY: Single; const Glyph: Integer; out Metrics: TGlyphMetrics); var J, K, S: Integer; Res: DWORD; PGlyphMem, PBuffer: PTTPolygonHeader; PPCurve: PTTPolyCurve; P: TPointF; V: TBezierVertex; Q0, Q1, Q2: TPointF; procedure AddToBezierCurve; begin V := QuadToBezier(Q0, Q2, Q1); OffsetVertex(V, DstX, DstY); Path.CurveTo(V.Points[0], V.Points[1], V.Points[2]); end; begin Res := GetGlyphOutlineW(Handle, Glyph, GGODefaultFlags[UseHinting], Metrics, 0, nil, VertFlip_mat2); if not Assigned(Path) then Exit; PGlyphMem := StackAlloc(Res); PBuffer := PGlyphMem; Res := GetGlyphOutlineW(Handle, Glyph, GGODefaultFlags[UseHinting], Metrics, Res, PBuffer, VertFlip_mat2); if (Res = GDI_ERROR) or (PBuffer^.dwType <> TT_POLYGON_TYPE) then begin StackFree(PGlyphMem); Exit; end; K := 0; while Res > 0 do begin S := PBuffer.cb - SizeOf(TTTPolygonHeader); NativeInt(PPCurve) := NativeInt(PBuffer) + SizeOf(TTTPolygonHeader); Q0 := PointFXtoPointF(PBuffer.pfxStart); Q2 := Q0; Path.MoveTo(PointF(Q0.X + DstX, Q0.Y + DstY)); while S > 0 do begin case PPCurve.wType of TT_PRIM_LINE: begin Q1 := Q0; AddToBezierCurve; P := Q0; P.X := P.X + DstX; P.Y := P.Y + DstY; for J := 0 to PPCurve.cpfx - 1 do begin P := PointFXtoPointF(PPCurve.apfx[J]); P.X := P.X + DstX; P.Y := P.Y + DstY; Path.LineTo(P); end; Q0 := PointFXtoPointF(PPCurve.apfx[PPCurve.cpfx - 1]); Q2 := Q0; end; TT_PRIM_QSPLINE: begin for J := 0 to PPCurve.cpfx - 2 do begin Q1 := PointFXtoPointF(PPCurve.apfx[J]); AddToBezierCurve; if J < PPCurve.cpfx - 2 then with PointFXtoPointF(PPCurve.apfx[J + 1]) do begin Q0.x := (Q1.x + x) * 0.5; Q0.y := (Q1.y + y) * 0.5; end else Q0 := PointFXtoPointF(PPCurve.apfx[J + 1]); Q2 := Q1; end; end; end; K := (PPCurve.cpfx - 1) * SizeOf(TPointFX) + SizeOf(TTPolyCurve); Dec(S, K); Inc(NativeInt(PPCurve), K); end; Dec(NativeInt(PPCurve), K); if PPCurve.wType = TT_PRIM_QSPLINE then begin Q1 := PointFXtoPointF(PPCurve.apfx[PPCurve.cpfx - 1]); AddToBezierCurve; end; Path.ClosePath; Dec(Res, PBuffer.cb); Inc(NativeInt(PBuffer), PBuffer.cb); end; StackFree(PGlyphMem); end; {$IFDEF USESTACKALLOC} {$W-} {$ENDIF} procedure TextToPath(DC: HDC; Path: TPathData; var ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign); overload; const CHAR_CR = 10; CHAR_NL = 13; CHAR_SP = 32; var GlyphMetrics: TGlyphMetrics; TextMetric: TTextMetric; I, J, TextLen: Integer; CharValue: Integer; X, Y, XMax: Single; S: WideString; procedure NewLine; begin X := ARect.Left{$IFDEF NOHORIZONTALHINTING}*HORZSTRETCH{$ENDIF}; Y := Y + TextMetric.tmHeight; end; function MeasureTextX(const S: WideString): Integer; var I: Integer; begin Result := 0; for I := 1 to Length(S) do begin CharValue := Ord(S[I]); GetGlyphOutlineW(DC, CharValue, GGODefaultFlags[UseHinting], GlyphMetrics, 0, nil, VertFlip_mat2); Inc(Result, GlyphMetrics.gmCellIncX); end; end; procedure TestNewLine(X: Single); begin if X > ARect.Right{$IFDEF NOHORIZONTALHINTING}*HORZSTRETCH{$ENDIF} then NewLine; end; begin GetTextMetrics(DC, TextMetric); TextLen := Length(Text); X := ARect.Left {$IFDEF NOHORIZONTALHINTING}*HORZSTRETCH{$ENDIF}; Y := ARect.Top + TextMetric.tmAscent; XMax := X; for I := 1 to TextLen do begin CharValue := Ord(Text[I]); if CharValue <= 32 then begin case CharValue of CHAR_CR: X := ARect.Left; CHAR_NL: Y := Y + TextMetric.tmHeight; CHAR_SP: begin GetGlyphOutlineW(DC, CharValue, GGODefaultFlags[UseHinting], GlyphMetrics, 0, nil, VertFlip_mat2); X := X + GlyphMetrics.gmCellIncX; if WordWrap then begin J := I + 1; while (J <= TextLen) and ([Ord(Text[J])] * [CHAR_CR, CHAR_NL, CHAR_SP] = []) do Inc(J); S := Copy(Text, I + 1, J - I - 1); TestNewLine(X + MeasureTextX(S)); end; end; end; end else begin TestNewLine(X); GlyphOutlineToPath(DC, Path, X, Y, CharValue, GlyphMetrics); X := X + GlyphMetrics.gmCellIncX; if X > XMax then XMax := X; end; end; Y := Y + TextMetric.tmHeight - TextMetric.tmAscent; {$IFNDEF NOHORIZONTALHINTING} ARect := RectF(ARect.Left, ARect.Top, XMax, Y); {$ELSE} ARect := RectF(ARect.Left, ARect.Top, XMax{$IFDEF NOHORIZONTALHINTING}/HORZSTRETCH{$ENDIF}, Y); if Assigned(Path) then Path.Scale(1/HORZSTRETCH, 1); {$ENDIF} end; function MeasureText(DC: HDC; const ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign): TRectF; overload; begin Result := ARect; TextToPath(DC, nil, Result, Text, WordWrap, HorzAlign, VertAlign); case HorzAlign of TTextAlign.taCenter: OffsetRect(Result, (((ARect.Left + ARect.Right) - (Result.Left + Result.Right)) * 0.5), 0); TTextAlign.taTrailing: OffsetRect(Result, ARect.Right - Result.Right, 0); end; case VertAlign of TTextAlign.taCenter: OffsetRect(Result, 0, ((ARect.Top + ARect.Bottom) - (Result.Top + Result.Bottom)) * 0.5); TTextAlign.taTrailing: OffsetRect(Result, 0, ARect.Bottom - Result.Bottom); end; Result.Left := Round(Result.Left); Result.Top := Round(Result.Top); Result.Right := Round(Result.Right); Result.Bottom := Round(Result.Bottom); end; function MeasureText(Font: HFONT; const ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign): TRectF; overload; var DC: HDC; begin DC := GetDC(0); try SelectObject(DC, Font); Result := MeasureText(DC, ARect, Text, WordWrap, HorzAlign, VertAlign); finally ReleaseDC(0, DC); end; end; procedure TextToPath(Font: HFONT; Path: TPathData; const ARect: TRectF; const Text: WideString; WordWrap: Boolean; HorzAlign, VertAlign: TTextAlign); overload; var DC: HDC; R: TRectF; begin DC := GetDC(0); try SelectObject(DC, Font); R := MeasureText(DC, ARect, Text, WordWrap, HorzAlign, VertAlign); TextToPath(DC, Path, R, Text, WordWrap, HorzAlign, VertAlign); finally ReleaseDC(0, DC); end; end; function BuildDashedLine(const Points: TPolygon; const DashArray: TDashArray; DashOffset: Single = 0; Scale: Single = 1): TPolyPolygon; var I, J, DashIndex: Integer; Offset, dx, dy, d, v: Single; procedure AddPoint(X, Y: Single); var K: Integer; begin K := Length(Result[J]); SetLength(Result[J], K + 1); Result[J][K].X := X; Result[J][K].Y := Y; end; begin DashIndex := 0; Offset := 0; DashOffset := DashArray[0] - DashOffset; v := 0; for I := 0 to High(DashArray) do v := v + DashArray[I]; while DashOffset < 0 do DashOffset := DashOffset + v; while DashOffset >= v do DashOffset := DashOffset - v; while DashOffset - DashArray[DashIndex] > 0 do begin DashOffset := DashOffset - DashArray[DashIndex]; Inc(DashIndex); end; DashOffset := DashOffset * Scale; J := 0; // N: second dimension might not be zero by default! SetLength(Result, 1, 0); if not Odd(DashIndex) then AddPoint(Points[0].X, Points[0].Y); for I := 1 to High(Points) do begin dx := Points[I].X - Points[I - 1].X; dy := Points[I].Y - Points[I - 1].Y; d := Hypot(dx, dy); if d = 0 then Continue; dx := dx / d; dy := dy / d; Offset := Offset + d; while Offset > DashOffset do begin v := Offset - DashOffset; AddPoint(Points[I].X - v * dx, Points[I].Y - v * dy); DashIndex := (DashIndex + 1) mod Length(DashArray); DashOffset := DashOffset + DashArray[DashIndex] * Scale; if Odd(DashIndex) then begin Inc(J); SetLength(Result, J + 1); end; end; if not Odd(DashIndex) then AddPoint(Points[I].X, Points[I].Y); end; if Length(Result[J]) = 0 then SetLength(Result, Length(Result) - 1); end; function DashedPolylineFS(const Points: TPolygon; const DashArray: TDashArray; DashOffset: Single = 0; Closed: Boolean = False; StrokeWidth: Single = 1.0; JoinStyle: TJoinStyle = jsMiter; EndStyle: TEndStyle = esButt; MiterLimit: Single = 4.0): TPolyPolygon; var PP: TPolyPolygon; I: Integer; begin PP := BuildDashedLine(Points, DashArray, DashOffset, StrokeWidth); SetLength(Result, Length(PP)); for I := 0 to High(PP) do Result[I] := BuildPolyline(PP[I], StrokeWidth, JoinStyle, EndStyle, MiterLimit); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.controller.abstract; interface uses ormbr.factory.interfaces, ormbr.container.objectset.interfaces, ormbr.container.dataset.interfaces; type TControllerAbstract<M: class, constructor> = class abstract protected FConnection: IDBConnection; FContainerDataSet: IContainerDataSet<M>; FContainerObjectSet: IContainerObjectSet<M>; public constructor Create(AConnection: IDBConnection; AContainerDataSet: IContainerDataSet<M>; AContainerObjectSet: IContainerObjectSet<M>); virtual; end; implementation { TControllerAbstract<M> } constructor TControllerAbstract<M>.Create(AConnection: IDBConnection; AContainerDataSet: IContainerDataSet<M>; AContainerObjectSet: IContainerObjectSet<M>); begin FConnection := AConnection; FContainerDataSet := AContainerDataSet; FContainerObjectSet := AContainerObjectSet; end; end.
(* @abstract(Contient des fonctions mathématiques optimisées. @br Des fonctions appoximatives peuvent être utilisées si désiré (utile en temps réel).) Par exemple: @br   Les fonctions 'approximatives' de Sin et Cos ont une précision moyenne de 4E-8.   Elle comprend des également des fonctions trigonométriques, calcul d'interpolations, @br   Des fonctionnalités avancées comme Bessel, BlackMan. Et aussi quelques fonctions utiles   Elle ajoute également des fonctions non définies dans l'unité Math FPC tel que : @br   ArcCsc, ArcSec, ArcCot, CscH, SecH ect ... Pour plus de fonctions mathématiques, voir les unités: @br   BZVectorMath, BZFastMath, BZRayMarchMath, BZGeoTools ------------------------------------------------------------------------------------------------------------- @created(24/02/2019) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(Creation : 24/02/2019) @item(Mise à jour : ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes :)@br Quelques liens : @unorderedList( @item(http://www.i-logic.com/utilities/trig.htm) @item(http://jacksondunstan.com/articles/1217) @item(http://mathworld.wolfram.com) ) ------------------------------------------------------------------------------------------------------------- @bold(Dependances) : BZFastMath ------------------------------------------------------------------------------------------------------------- @bold(Credits :)@br @unorderedList( @item(J.Delauney (BeanzMaster)) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL / LGPL ------------------------------------------------------------------------------------------------------------- *) Unit BZMath; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //============================================================================== {.$DEFINE USE_DOUBLE} Interface Uses Classes, SysUtils, Math; //============================================================================== {%region%-----[ Constantes et types mathématique utiles ]----------------------} Const cInfinity = 1e1000; //< Nombre infini EpsilonFuzzFactor = 1000; //< Facteur Epsilon pour précision étendue EpsilonXTResolution = 1E-19 * EpsilonFuzzFactor; //< Résolution Epsilon étendue cPI: Double = 3.1415926535897932384626433832795; //< Valeur de PI cInvPI: Double = 1.0 / 3.1415926535897932384626433832795; //< Valeur inverse de PI = 0.31830988618379067153776752674503 c2DivPI: Double = 2.0 / 3.1415926535897932384626433832795; //< 2 Diviser par PI = 0.63661977236758134307553505349006 cPIdiv180: Single = 3.1415926535897932384626433832795 / 180; //< PI diviser par 180 = 0.01745329251994329576923690768489‬ cPI180 : Single = 3.1415926535897932384626433832795 * 180; //< PI multiplier par 180 = 565.48667764616278292327580899031‬ c180divPI: Single = 180 / 3.1415926535897932384626433832795; //< 180 diviser par PI = 57.295779513082320876798154814105‬ c2PI: Single = 3.1415926535897932384626433832795*2; //< PI multiplier par 2 = 6.283185307179586476925286766559 cInv2PI : Single = 1.0 / (3.1415926535897932384626433832795*2); //< Inverse de PI multiplier par 2 = 0.15915494309189533576888376337251 c4PI : Single = 3.1415926535897932384626433832795*4; //< PI multiplier par 4 = 12.566370614359172953850573533118 cPIdiv2: Single = 3.1415926535897932384626433832795 / 2; //< PI diviser par 2 = 1.5707963267948966192313216916398 cPIdiv3: Single = 3.1415926535897932384626433832795 / 3; //< PI diviser par 3 = 1.0471975511965977461542144610932 cPIdiv4: Single = 3.1415926535897932384626433832795 / 4; //< PI diviser par 4 = 0.78539816339744830961566084581988 c3PIdiv2: Single = 3*3.1415926535897932384626433832795/2; //< 3 multiplier par PI diviser par 2 = 4.7123889803846898576939650749193 c3PIdiv4: Single = 3*3.1415926535897932384626433832795/4; //< 4 multiplier par PI diviser par 2 = 2.3561944901923449288469825374596 cInv360: Single = 1 / 360; //< Inverse de 360 = 0.00277777777777777777777777777778 c180: Single = 180; //< 180 c360: Single = 360; //< 360 cOneHalf: Single = 0.5; //< 0.5 cMinusOneHalf: Single = -0.5; //< -0.5 cZero: Single = 0.0; //< Zero cOne: Single = 1.0; //< 1.0 cLn10: Single = 2.302585093; //< Logarythme naturel de 10 cLowEpsilon : Single = 1e-4; //< Epsilon de très faible précision cEpsilon: Single = 1e-10; //< Epsilon faible précision cEpsilon40 : Single = 1E-40; //< Epsilon moyenne précision cEpsilon30 : Single = 1E-30; //< Epsilon grande précision cFullEpsilon: Double = 1e-12; //< Epsilon précision par défaut cColinearBias = 1E-8; //< Bias colinéaire cEulerNumber = 2.71828182846; //< Nombre d'Euler cInvSqrt2 = 1.0 / sqrt(2.0); //< Inverse de la racine carré de 2 = 1.4142135623730950488016887242097 cInvThree = 1.0 / 3.0; //< Inverse de 3 = 0.33333333333333333333333333333333 cInv255 = 1/255; //< Inverse de 255 = 0.0039215686274509803921568627451 cRadian = 180 / 3.1415926535897932384626433832795; //< 57.29577951; cBernstein: Single = 0.2801694990238691330364364912307; //< Constante de Bernstein cCbrt2: Single = 1.2599210498948731647672106072782; //< Racine cubique de 2 cCbrt3: Single = 1.4422495703074083823216383107801; //< Racine cubique de 3 cCbrt10: Single = 2.1544346900318837217592935665194; //< Racine cubique de 10 cCbrtPi: Single = 1.4645918875615232630201425272638; //< Racine cubique de PI // portées maximal les types de points flottants IEEE // Compatible avec Math.pas MinSingle = 1.5e-45; //< Nombre minimum Single MaxSingle = 3.4e+38; //< Nombre maximum Single MinDouble = 5.0e-324; //< Nombre minimum Double MaxDouble = 1.7e+308; //< Nombre maximum Double MinExtended = 3.4e-4932; //< Nombre minimum Extended MaxExtended = 1.1e+4932; //< Nombre maximuum Extended // Complex MinComp = -9.223372036854775807e+18; //< Nombre minimum Complex MaxComp = 9.223372036854775807e+18; //< Nombre maximum Complex Type { Types réels:     A point flottant: @br @unorderedlist(       @item(Simple (Single) 32 bits : 7-8 chiffres significatifs)       @item(Double (Double) 64 bits : 15-16 chiffres significatifs)       @item(Etendu (Extended) 80 bits : 19-20 chiffres significatifs) )     A point fixe: @br       Devise (Currency) 64 bits : 19-20 chiffres significatifs, 4 après la virgule décimale. } FloatX = Extended; PFloatX = ^FloatX; { TExtended80Rec : } TExtended80Rec = Packed Record Case Integer Of 1: (Bytes: Array[0..9] Of Byte); 2: (Float: Extended); End; type { Type utilisé pour stocker des Sinus et Cosinus } {$ifdef USE_DOUBLE} TSinCos = record sin: double; cos: double; end; PSinCos = ^TSinCos; {$else} TSinCos = record sin: single; cos: single; end; PSinCos = ^TSinCos; {$endif} TBZCubicRootSolution = Array[0..2] of Single; Type { Enumération des types d'interpolation pour l'unité BZMath : @br @unorderedlist( @item(itLinear : Interpolation Lineaire) @item(itPower : Interpolation par puissance) @item(itSin : Interpolation Sinuosidale) @item(itSinAlt : Interpolation Sinuosidale Alternative) @item(itTan : Interpolation par tangente) @item(itLn : Interpolation logarithmique) @item(itExp : Interpolation exponentielle) ) Voir : InterpolateValue } TBZInterpolationType = (itLinear, itPower, itSin, itSinAlt, itTan, itLn, itExp); {%endregion%} {%region%-----[ fonctions d'arrondissement ]-----------------------------------} { Arrondit une valeur vers son entier le plus proche } Function Round(v: Single): Integer; Overload; { Arrondit une valeur vers zero } Function Trunc(v: Single): Integer; Overload; { Arrondit une valeur vers l'infini négatif } Function Floor(v: Single): Integer; Overload; { Retourne la partie fractionnaire d'un nombre } Function Fract(v:Single):Single; { Arrondit une valeur vers l'infini positif } Function Ceil(v: Single): Integer; Overload; { Arrondit la valeur en virgule flottante à l'entier le plus proche. @br   Se comporte comme Round mais Retourne une valeur en virgule flottante. } Function RoundFloat(v: Single): Single; { arrondit une valeur vers son entier le plus proche } Function NewRound(x: Single): Integer; {%endregion%} {%region%-----[ fonctions utiles générales ]-----------------------------------} //operator mod(const a,b:Single):Single;inline;overload; { calcule le reste d'une division en virgule flottante } function fmod(const A,B:Single):Single; { Assure que valeur donnée soit dans une plage de deux valeurs entières } function Clamp(const V : Integer; Min,Max : integer) : integer; overload; { Assure que valeur donnée soit dans une plage de deux valeurs en virgule flottante } function Clamp(const V,Min,Max : Single): Single; overload; { Assure que valeur donnée soit d'un minimum du paramètre en virgule flottante "aMin" } function ClampMin(const V,aMin:Single): Single; { Assure que la valeur donnée soit dans la plage de 0..255 } function ClampByte(Const Value:Integer):Byte; { Vérifie si la valeur est proche de zéro ou zéro absolu } Function IsZero(Const A: Extended; Const Epsilon: Extended = 0.0): Boolean; { Retourne le signe de la valeur x en utilisant la convention (-1, 0, +1) } Function Sign(x: Single): Integer; { Retourne le signe strict de la valeur x en utilisant la convention (-1, +1) } Function SignStrict(x: Single): Integer; { Retourne le maximum de trois valeurs entières } Function Max(A, B, C: Integer): Integer; overload; //Function Max(Const A, B, C: Byte): Byte; overload; { Retourne le minimum de trois valeurs entières } Function Min(A, B, C: Integer): Integer; overload; //Function Min(Const A, B, C: Byte): Byte; overload; { Retourne le maximum de deux valeurs en virgule flottante } Function Max(v1, v2 : Single): Single; overload; { Retourne le minimum de deux valeurs en virgule flottante } Function Min(v1, v2 : Single): Single; overload; { Retourne le maximum de deux valeurs Byte } Function Max(v1, v2 : Byte): Byte; overload; { Retourne le minimum de deux valeurs Byte } Function Min(v1, v2 : Byte): Byte; overload; { Retourne le maximum de deux valeurs Integer } Function Max(v1, v2 : Integer): Integer; overload; { Retourne le minimum de deux valeurs Integer } Function Min(v1, v2 : Integer): Integer; overload; { Retourne le maximum de trois valeurs en virgule flottante } Function Max(v1, v2, v3: Single): Single; overload; { Retourne le minimum de trois valeurs en virgule flottante } Function Min(v1, v2, v3: Single): Single; overload; { Calcule la valeur "réciproque" (1 / x) } Function ComputeReciprocal(x: Single): Single; { Vérifie si la valeur donnée se trouve dans une plage de deux valeurs } Function IsInRange(const X, a, b: Single): Boolean; //Function IsInRange(const X, a, b: Integer): Boolean;overload; { Une fonction 'cercle vers le haut'. Renvoie y sur un cercle unitaire donné 1-x. Utile pour former des biseaux. @br x compris entre 0.0 et 1.0 } function CircleUp(x : Single) : Single; { Une fonction 'cercle vers le bas'. Renvoie 1-y sur un cercle unitaire donné x. Utile pour former des biseaux. @br x compris entre 0.0 et 1.0 } function CircleDown(x : Single) : Single; { Retourne 1.0 - x } function flip(x : Single) : Single; { Similaire à Mod et fmod mais avec le respect des nombres négatif } function Modulus(a, b : Single) : Single; overload; { Similaire à Mod et fmod mais avec le respect des nombres négatif } function Modulus(a, b : Integer) : Integer; overload; {%endregion%} {%region%-----[ Fonctions sur les angles ]-------------------------------------} { Normalise un angle en radian } Function NormalizeRadAngle(angle: Single): Single; { Normalise un angle en degree } Function NormalizeDegAngle(angle: Single): Single; { Calcul la distance entre deux angles en degrée } Function DistanceBetweenAngles(angle1, angle2: Single): Single; { Convertie un angle en degrée vers un angle en radian } Function DegToRadian(Const Degrees: Single): Single; { Convertie un angle en radian vers un angle en degrée } Function RadianToDeg(Const Radians: Single): Single; { Interpolation lineaire entre deux angles } Function InterpolateAngleLinear(start, stop, t: Single): Single; {%endregion%} {%region%-----[ Fonctions sur les puissances ]---------------------------------} { Vérifie si une valeur données est de puissance de deux } Function IsPowerOfTwo(Value: Longword): Boolean; { Retourne la puissance de deux suivante, d'une valeur donnée } Function NextPowerOfTwo(Value: Cardinal): Cardinal; { Retourne la puissance de deux précédente, d'une valeur donnée } Function PreviousPowerOfTwo(Value: Cardinal): Cardinal; { Elève la "base" à n'importe quelle puissance. Pour les exposants fractionnaires, ou | exposants | > MaxInt, la base doit être> 0. } function Pow(const Base, Exponent: Single): Single; overload; { Elève une valeur donnée en virgule flottante, par une puissance en valeur entière } function PowerInteger(Const Base: Single; Exponent: Integer): Single; overload; { Elève une valeur donnée entière, par une puissance en valeur entière } Function PowerInt(Const Base, Power: Integer): Single; { Elève une valeur donnée à la puissance 3 } Function pow3(x: Single): Single; {%endregion%} {%region%-----[ Fonctions trigonométrique ]------------------------------------} { Retourne le Sinus d'une valeur donnée } function Sin(x:Single):Single; overload; { Retourne le Cosinus d'une valeur donnée } function Cos(x:Single):Single; overload; { Retourne la tangente d'une valeur donnée } function Tan(const X : Single) : Single; overload; { Retourne le Sinus ety Cosinus d'une valeur donnée } procedure SinCos(const Theta: Single; out Sin, Cos: Single); overload; { Retourne le sinus et le cosinus d'un angle donné et d'un rayon. @br @bold(Note) : les valeurs du sinus et du cosinus calculés sont multipliés par le rayon.} procedure SinCos(const theta, radius : Single; out Sin, Cos: Single); overload; { Calcul de l'Hypotenus } Function Hypot(Const X, Y: Single): Single; //Function Hypot(Const X, Y, Z: Single): Single; { Retourne la cotangente d'un angle donné } function CoTan(const X : Single) : Single; overload; {%endregion%} {%region%-----[ Fonctions trigonométrique inverse ]----------------------------} { Retourne l' arc cosinus d'un angle donné } function ArcCos(const x : Single) : Single; overload; { Retourne l' arc sinus d'un angle donné } Function ArcSin(Const x: Single): Single; { Retourne l'arc tangente d'un angle et d'un quadrant } function ArcTan2(const Y, X : Single) : Single; overload; { Retourne l'inverse Cosecant d'une valeur donnée } Function ArcCsc(Const X: Single): Single; { Retourne l'inverse secant d'une valeur donnée } Function ArcSec(Const X: Single): Single; { Retourne l'inverse Cotangnete d'une valeur donnée } Function ArcCot(Const X: Single): Single; {%endregion%} {%region%-----[ Fonctions hyperbolique ]---------------------------------------} { Retourne le sinus hyperbolique d'une valeur donnée } function Sinh(const x : Single) : Single; overload; { Retourne le cosinus hyperbolique d'une valeur donnée } function Cosh(const x : Single) : Single; overload; { Retourne la cosecante hyperbolique d'une valeur donnée } Function CscH(Const X: Single): Single; { Retourne la secante hyperbolique d'une valeur donnée } Function SecH(Const X: Single): Single; { Retourne la cotangente hyperbolique d'une valeur donnée } Function CotH(Const X: Extended): Extended; { Retourne le sinus, cosinus hyperbolique d'une valeur donnée } Function SinCosh(Const x: Single): Single; {%endregion%} {%region%-----[ Fonctions hyperbolique inverse ]-------------------------------} { Retourne la cosecante hyperbolique inverse d'une valeur donnée } Function ArcCscH(Const X: Single): Single; { Retourne la secante hyperbolique inverse d'une valeur donnée } Function ArcSecH(Const X: Single): Single; { Retourne la cotangnente hyperbolique inverse d'une valeur donnée } Function ArcCotH(Const X: Single): Single; {%endregion%} {%region%-----[ Fonctions racine carré ]---------------------------------------} { Retourne la racine carré d'une valeur donnée } function Sqrt(const A: Single): Single; overload; { Retourne la racine carré inverse d'une valeur donnée } Function InvSqrt(v: Single): Single; {%endregion%} {%region%-----[ Fonctions logarithmique ]--------------------------------------} { Retourne le logarithme de base 2 d'une valeur donnée } Function Log2(X: Single): Single; Overload; { Retourne le logarithme de base 10 d'une valeur donnée } function Log10(X: Single): Single; { Retourne le logarithme de base N d'une valeur donnée } function LogN(Base, X: Single): Single; {%endregion%} {%region%-----[ Fonctions logarithmique naturel ]------------------------------} { Retourne le logarithme naturel d'une valeur donnée } Function Ln(X: Single): Single; overload; { Retourne ln (1 + X), précis pour X près de 0. } Function LnXP1(x: Single): Single; {%endregion%} {%region%-----[ Fonctions exponentielles ]-------------------------------------} { Retourne exponentiation naturelle d'une valeur donnée } Function Exp(Const X: Single): Single; overload; { multiplie la valeur donnée X par 2 puissance de N.} Function ldExp(x: Single; N: Integer): Single; {%endregion%} {%region%-----[ Fonctions d'interpolations ]-----------------------------------} { Calcul du facteur d'ordre un de Bessel } Function BesselOrderOne(x: Double): Double; { Calcul du facteur de Bessel } Function Bessel(x: Double): Double; { Calcul du facteur IO de Bessel } Function BesselIO(x: Double): Double; { Calcul du facteur de Blackman } Function Blackman(x: Double): Double; { Une courbe de phase déphasée peut être utile si elle commence à zéro et se termine à zéro,   pour certains comportements de rebond (suggéré par Hubert-Jan). @br Donner à "x" différentes valeurs entières pour ajuster la quantité de rebonds. Il culmine à 1.0. @br Elle peuvent prendre des valeurs négatives, mais elles peuvent rendre le calcul inutilisable dans certaines applications } Function Sinc(x: Single): Single; { Calcul d'une interpolation linéaire avec distortion } Function InterpolateValue(Const Start, Stop, Delta: Single; Const DistortionDegree: Single; Const InterpolationType: TBZInterpolationType): Single; { Calcul rapide d'une interpolation linéaire avec distortion } Function InterpolateValueFast(Const OriginalStart, OriginalStop, OriginalCurrent: Single; Const TargetStart, TargetStop: Single;Const DistortionDegree: Single; Const InterpolationType: TBZInterpolationType): Single; { Calcul d'une interpolation linéaire avec distortion avec vérification des valeurs } Function InterpolateValueSafe(Const OriginalStart, OriginalStop, OriginalCurrent: Single; Const TargetStart, TargetStop: Single;Const DistortionDegree: Single; Const InterpolationType: TBZInterpolationType): Single; { Calcul d'une interpolation bilinéaire } function InterpolateBilinear(x,y : Single; nw, ne, sw, se : Single) : Single; {%endregion%} {%region%-----[ fonctions émulées "HL/GL Shader script" ]----------------------} { Calul d'une interpolation linéraire de type Hermite entre deux valeurs } function SmoothStep(Edge0,Edge1,x: Single): Single; { Calul d'une interpolation linéraire de type Quintic entre deux valeurs } function SmoothStepQuintic(Edge0,Edge1,x: Single): Single; { Calul d'une interpolation linéraire standard entre deux valeurs } function Lerp(Edge0,Edge1,x: Single): Single; { Calul d'une interpolation Cubic } function CubicLerp(Edge0,Edge1,Edge2, Edge3, x: Single): Single; { Calul d'une interpolation Cosine entre deux valeurs } function CosineLerp(Edge0,Edge1,x: Single): Single; //function SinLerp(Edge0,Edge1,x: Single): Single; //function SinAltLerp(Edge0,Edge1,x: Single): Single; //function ExpLerp(Edge0,Edge1,x: Single): Single; //function LnLerp(Edge0,Edge1,x: Single): Single; //function TanLerp(Edge0,Edge1,x: Single): Single; //function PowerLerp(Edge0,Edge1,x: Single): Single; { Génére une fonction d'étape en comparant deux valeurs } function Step(Edge,x: Single): Single; { Retourne la longueur d'un vecteur 1D } Function Length1D(x:Single):Single; { Mixe deux valeurs en fonction du poid "a" } function Mix(x,y,a : Double) : Double; {%endregion%} {%region%-----[ Fonctions utiles pour les animations ou interpolations ]-------} { Mélange la valeur avec un seuil et lisse avec un polynôme cubique. @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function AlmostIdentity( x,m,n : single ):single; { Parfait pour déclencher des comportements ou créer des enveloppes pour la musique ou l'animation. @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } function Impulse(k,x : Single):Single; { Interpolation cubique Identique à smoothstep (c-w, c, x) -smoothstep (c, c + w, x) @br   Vous pouvez l'utiliser comme un remplacement bon marché pour une interpolation gaussienne. @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function CubicPulse(c,w,x : Single) : Single; { Calcul une atténuation naturelle @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function ExpStep(x,k,n:Single):Single; { Remappe l'intervalle 0..1 en 0..1, de sorte que les coins soient remappés à 0 et le centre à 1 @br @bold(Note) : parabola(0) = parabola(1) = 0, et parabola(1/2) = 1 @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function Parabola(x,k:Single):Single; { Remappe l'intervalle 0..1 en 0..1, de sorte que les coins soient remappés à 0. @br   Très utile pour incliner la forme d'un côté ou de l'autre afin de faire des feuilles, des yeux, et bien d'autres formes intéressantes. @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function pcurve(x,a,b:Single):Single; { Remappe l'intervalle de l'unité dans l'intervalle de l'unité en élargissant les côtés et en comprimant le centre, et en gardant 1/2 mappé à 1/2. @br   C'était une fonction courante dans les tutoriels RSL (Renderman Shading Language). @br K : k=1 est la courbe d'identité, k <1 produit la forme classique gain(), et k > 1 produit des courbes en forme de 's'. @br @bold(Note) : Les courbes sont symétriques (et inverses) pour k = a et k = 1 / a. @br Voir aussi : http://www.iquilezles.org/www/articles/functions/functions.htm } Function pGain(x,k:Single):Single; { Une variante de la fonction gamma. @br   A = le nombre auquel appliquer le gain @br B = le paramètre du gain. @ @unorderedlist(    @item(0.5 signifie pas de changement,)    @item(Des valeurs plus petites réduisent le gain,) @item(Des valeurs plus élevées augmentent le gain.)) } function vGain(a, b : Single) : Single; { Applique une polarisation (bias) à un nombre dans l'intervalle unitaire, en déplaçant les nombres vers 0 ou 1 selon le paramètre de biais. @br A = le nombre à polariser @br B = le paramètre de polarisation. @br   0.5 signifie pas de changement, des valeurs plus petites biaisent vers 0, plus grandes vers 1. } function bias(a, b : Single) : Single; { Un déphaseur de courbe sinc @br Voir aussi : http://mathworld.wolfram.com/SincFunction.html } Function pSinc(x,k:Single):Single;overload; {%endregion%} {%region%-----[ AUtres fonctions utiles ]--------------------------------------} { Convertir une valeur en pourcentage à partir de [min..max]} Function Val2Percent(min, max,val: Single): Integer; { Convertis un nombre de pixel "nbPixels" en centimètre } function PixelsToCentimeters(nbPixels : Integer) : Double; { Convertis un nombre de centimètre "nbCm" en pixels } function CentimetersToPixels(nbCm : Double) : Integer; { Convertis un nombre de pouce "nbInch" en centimètre } function InchToCentimeters(nbInch : Double) : Double; { Convertis un nombre de centimètre "nbCm" en pouce } function CentimetersToInch(nbCm : Double) : Double; { Convertis un nombre de pixel "nbPixels" en millimètre } function PixelsToMillimeters(nbPixels : Integer) : Double; { Convertis un nombre de millimètre "nbMm" en pixels } function MillimetersToPixels(nbMm : Double) : Integer; { Convertis un nombre de pouce "nbInch" en pixels } function InchToPixels(nbInch : Double) : Integer; { Convertis un nombre de Pixels "nbPixels" en pouce } function PixelsToInch(nbPixels: Integer) : Double; { @abstract(Convertis un nombre de pixel en centimètre en fonction de la résolution en DPI. @br @bold(Note) : DPI = "Dot Per Inch" (point par pouce) ) @bold(Exemple) : Vous avez une image de dimension 512x512 pixels. @br Sur un écran d'ordinateur de 72 dpi de résolution, cette image fera 18cm de côté. @br Si vous imprimez cette image avec une résolution de 300dpi, cette image fera alors 4,33cm de coté } function PixelsResolutionToCentimeters(nbPixels, DPI : Integer) : Double; { @abstract(Convertis un nombre de centimètre en fonction de la résolution en DPI en pixels @bold(Note) : DPI = "Dot Per Inch" (point par pouce) ) @bold(Exemple) : Vous désirez imprimer une image de 5cm de côté avec une imprimante ayant une résolution de 600 dpi. L'image devra alors avoir une dimension de 1181x1181 pixels } function CentimetersToPixelsResolution(nbCm : Double; DPI : Integer) : Integer; { Retourne la racine cubique de x } function CubeRoot(x : Single) : Single; { Retourne les solutions cubique pour les nombre a, b, c, d } function CubicRoot(a, b, c, d : Single) : TBZCubicRootSolution; { Calcule la valeur en x de la fonction gaussienne } function ComputeGaussian(x, Sigma : Single) : Single; { Calcule la valeur en x de la fonction gaussienne centrée } function ComputeGaussianCenter(x, Sigma : Single) : Single; { Calcule la dérivé de la valeur en x de la fonction gaussienne } function ComputeGaussianDerivative(x, Sigma : Single) : Single; { Calcul la moyenne de trois valeurs gaussiennes autour de "x" } function ComputeMeanGaussian(x, Sigma : Single) : Single; { Calcul une distribution gaussienne de sigma pour x suivant le poid weight } function ComputeGaussianDistribution(x, weight, sigma : Single) : Single; { Calcul la valeur en x du Laplacien gaussien } function ComputeLoG(x, Sigma : Single) : Single; { Calcul la valeur en x du Laplacien gaussien centré } function ComputeLoGCenter(x, Sigma : Single) : Single; { Calcul du nombre d'Euler en fonction de "weight" } function ComputeEuler(Weight : Single) : Single; { Retourne la valeur factorielle de x } function Factorial(x : Int64) : Int64; { Retourne le x ème polynome de Berstein d'ordre n+1 évalué en u (appartenant à 0..1) } function ComputeBerstein(x, n : integer; u : Single) : Single; { Normalise une valeur en virgule flotantte comprise entre l'interval [InMin, InMax] vers l'interval [OutMin, OutMax] } function RangeMap(value, InMin, InMax, OutMin, OutMax : Single) : Single; overload; { Normalise une valeur entière comprise entre l'interval [InMin, InMax] vers l'interval [OutMin, OutMax] } function RangeMap(value, InMin, InMax, OutMin, OutMax : Integer) : integer; overload; {%endregion%} //============================================================================== Implementation //============================================================================== {$IFDEF USE_FASTMATH} uses BZFastMath;{$ENDIF} //============================================================================== {%region%=====[ fonctions d'arrondissement ]===================================} Function Round(v : Single) : Integer; Begin {$HINTS OFF} Result := System.round(v); {$HINTS ON} End; Function Trunc(v : Single) : Integer; Begin {$HINTS OFF} Result := System.Trunc(v); {$HINTS ON} End; Function Fract(v : Single) : Single; begin result := v - trunc(v); //result := frac(v); //v-Int(v); end; Function RoundFloat(v : Single) : Single; Begin {$HINTS OFF} //Result := system.int Result := System.Trunc(v + cOneHalf); {$HINTS ON} End; Function NewRound(x : Single) : Integer; Var y: Integer; Begin y := 0; If (x - floor(x) < 0.5) Then y := floor(x) Else If (x - floor(x) = 0) Then y := Trunc(x) Else y := Trunc(x) + 1; Result := y; End; Function Ceil(v : Single) : Integer; Begin {$HINTS OFF} //If Fract(v) > 0 Then // Result := Trunc(v) + 1 //Else // Result := Trunc(v); Result := Trunc(v); if (v - Result) > 0 then Inc(Result); {$HINTS ON} End; Function Floor(v : Single) : Integer; Begin {$HINTS OFF} result :=0; if (v=0.0) then exit else If (v > 0) Then Result := System.Trunc(v) Else Result := System.Trunc(v-0.999999999); {$HINTS ON} End; {%endregion%} {%region%=====[ fonctions utiles générales ]===================================} //operator mod(const a,b:Single):Single; function fmod(const A, B : Single) : Single; begin result := 0; if b=0 then exit; Result := a - b * System.trunc(a / b);//a-b * Int(a/b); (a/b);//Int(a/b);// end; function Clamp(const V : Integer; Min,Max : integer) : integer; begin Result := V; if Result > Max then begin result := Max; exit; end; if Result < Min then result := Min; end; function Clamp(const V,Min,Max : Single) : Single; begin Result := V; if V > Max then result := Max else if V < Min then result := Min; end; function ClampMin(const V,aMin:Single): Single; begin if V < aMin then result := aMin else result := V; end; {$IFNDEF NO_ASM_OPTIMIZATIONS} function ClampByte(Const Value : Integer) : Byte; assembler; nostackframe; asm {$IFDEF CPU64} {$IFDEF UNIX} MOV EAX,EDI {$ELSE} // in win x64 calling convention parameters are passed in ECX, EDX, R8 & R9 MOV EAX,ECX {$ENDIF} {$ENDIF} TEST EAX,$FFFFFF00 JNZ @above RET @above: JS @below MOV EAX,$FF RET @Below: XOR EAX,EAX end; {$ELSE} function ClampByte(const Value: Integer): Byte; inline; begin Result := Value; if Value > 255 then Result := 255 else if Value < 0 then Result := 0; end; {$ENDIF} Function IsZero(Const A : Extended; Const Epsilon : Extended) : Boolean; Var e: Extended; Begin If Epsilon = 0 Then E := EpsilonXTResolution Else E := Epsilon; Result := FastAbs(A) <= E; End; Function Sign(x : Single) : Integer; Begin {$IFDEF USE_FASTMATH} Result := FastSign(x); {$ELSE} If x < 0 Then Result := -1 Else If x > 0 Then Result := 1 Else Result := 0; {$ENDIF} End; Function SignStrict(x : Single) : Integer; Begin If x < 0 Then Result := -1 Else Result := 1; End; Function Min(v1, v2 : Single) : Single; begin if v1<v2 then Result:=v1 else Result:=v2; end; Function Max(v1, v2 : Byte) : Byte; begin Result:=v1; if v1<v2 then Result:=v2; end; Function Min(v1, v2 : Byte) : Byte; begin Result:=v1; if v1>v2 then Result:=v2; end; Function Max(v1, v2 : Integer) : Integer; begin Result:=v1; if v1<v2 then Result:=v2; end; Function Min(v1, v2 : Integer) : Integer; begin Result:=v1; if v1>v2 then Result:=v2; end; Function Max(v1, v2 : Single) : Single; begin Result:=v2; if v1>v2 then Result:=v1; end; Function Min(v1, v2, v3 : Single) : Single; Var N: Single; Begin N := v3; If v1 < N Then N := v1; If v2 < N Then N := v2; Result := N; End; Function Max(v1, v2, v3 : Single) : Single; Var N: Single; Begin N := v3; If v1 > N Then N := v1; If v2 > N Then N := v2; Result := N; End; {$IFDEF USE_ASM_OPTIMIZATIONS} Function Max(A, B, C : Integer) : Integer; Assembler; asm {$IFDEF CPU64} {$IFDEF UNIX} MOV EAX, EDI CMP ESI, EAX CMOVG EAX, ESI CMP EDX, EAX CMOVG EAX, EDX {$ELSE} MOV RAX, RCX MOV RCX, R8 CMP EDX, EAX CMOVG EAX, EDX CMP ECX, EAX CMOVG EAX, ECX {$ENDIF} {$ELSE} CMP EDX, EAX CMOVG EAX, EDX CMP ECX, EAX CMOVG EAX, ECX {$ENDIF} End; {$else} function Max(A, B, C : Integer) : Integer; //Inline; Var n: Integer; Begin If A > C Then N := A Else N := C; If B > N Then N := B; Result := N; End; {$endif} {$IFDEF USE_ASM_OPTIMIZATIONS} Function Min(A, B, C : Integer) : Integer; Assembler; Asm {$IFDEF CPU64} {$IFDEF UNIX} MOV EAX, EDI CMP ESI, EAX CMOVL EAX, ESI CMP EDX, EAX CMOVL EAX, EDX {$ELSE} MOV RAX, RCX MOV RCX, R8 CMP EDX, EAX CMOVL EAX, EDX CMP ECX, EAX CMOVL EAX, ECX {$ENDIF} {$ELSE} CMP EDX, EAX CMOVL EAX, EDX CMP ECX, EAX CMOVL EAX, ECX {$ENDIF} End; {$else} function Min(A, B, C : Integer) : Integer; Inline; Var n: Integer; Begin If A < C Then N := A Else N := C; If B < N Then N := B; Result := N; End; {$endif} Function ComputeReciprocal(x : Single) : Single; Var a: Integer; Begin Result := 0; If x = 0 Then exit; a := Sign(x); If ((a * x) >= cEpsilon) Then Result := 1.0 / x Else Result := a * (1.0 / cEpsilon); End; Function IsInRange(const X, a, b : Single) : Boolean; begin if a < b then result := (a <= X) and (X <= b) else result := (b <= X) and (X <= a); end; function CircleUp(x : Single) : Single; var xx : Single; begin xx := 1-x; Result := System.sqrt(1-xx*xx); end; function CircleDown(x : Single) : Single; begin Result := 1.0-System.sqrt(1-x*x); end; function flip(x : Single) : Single; begin Result := 1 - x; end; function Modulus(a, b : Single) : Single; Var n : Integer; r : Single; begin n := System.Trunc(a/b); r := a - (b * n); if r<0 then result := r + b else result := r; end; function Modulus(a, b : Integer) : Integer; Var n : Integer; r : Integer; begin n := System.Trunc(a/b); r := a - (b * n); if r<0 then result := r + b else result := r; end; {%endregion%} {%region%=====[ Fonctions sur les angles ]=====================================} Function NormalizeRadAngle(angle : Single) : Single; Begin Result := angle - RoundFloat(angle * cInv2PI) * c2PI; If Result > cPI Then Result := Result - c2PI Else If Result < -PI Then Result := Result + c2PI; End; Function NormalizeDegAngle(angle : Single) : Single; Begin Result := angle - RoundFloat(angle * cInv360) * c360; If Result > c180 Then Result := Result - c360 Else If Result < -c180 Then Result := Result + c360; End; Function DistanceBetweenAngles(angle1, angle2 : Single) : Single; Begin angle1 := NormalizeRadAngle(angle1); angle2 := NormalizeRadAngle(angle2); Result := Abs(angle2 - angle1); If Result > cPI Then Result := c2PI - Result; End; Function DegToRadian(Const Degrees : Single) : Single; Begin Result := Degrees * cPIdiv180; End; Function RadianToDeg(Const Radians : Single) : Single; Begin Result := Radians * c180divPI; End; Function InterpolateAngleLinear(start, stop, t : Single) : Single; Var d: Single; Begin start := NormalizeRadAngle(start); stop := NormalizeRadAngle(stop); d := stop - start; If d > PI Then Begin // positive d, angle on opposite side, becomes negative i.e. changes direction d := -d - c2PI; End Else If d < -PI Then Begin // negative d, angle on opposite side, becomes positive i.e. changes direction d := d + c2PI; End; Result := start + d * t; End; {%endregion} {%region%=====[ Fonctions sur les puissances ]=================================} Function IsPowerOfTwo(Value : Longword) : Boolean; Const BitCountTable: Array[0..255] Of Byte = (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8); Function BitCount(Value: Longword): Longword; inline; Var V: Array[0..3] Of Byte absolute Value; Begin Result := BitCountTable[V[0]] + BitCountTable[V[1]] + BitCountTable[V[2]] + BitCountTable[V[3]]; End; Begin Result := BitCount(Value) = 1; End; Function PreviousPowerOfTwo(Value : Cardinal) : Cardinal; Var I, N: Cardinal; Begin Result := 0; For I := 14 Downto 2 Do Begin N := (1 Shl I); If N < Value Then Break Else Result := N; End; End; Function NextPowerOfTwo(Value : Cardinal) : Cardinal; Begin If (Value > 0) Then Begin Dec(Value); Value := Value Or (Value Shr 1); Value := Value Or (Value Shr 2); Value := Value Or (Value Shr 4); Value := Value Or (Value Shr 8); Value := Value Or (Value Shr 16); End; Result := Value + 1; End; function Pow(const Base, Exponent : Single) : Single; begin {$IFDEF USE_FASTMATH} if exponent=cZero then Result:=cOne else if (base=cZero) and (exponent>cZero) then Result:=cZero else if RoundFloat(exponent)=exponent then Result:=FastPower(base, Integer(Round(exponent))) else Result:=FastExp(exponent*FastLn(base)); {$ELSE} {$HINTS OFF} if exponent=cZero then Result:=cOne else if (base=cZero) and (exponent>cZero) then Result:=cZero else if RoundFloat(exponent)=exponent then Result:=Power(base, Integer(Round(exponent))) else Result:=Exp(exponent*Ln(base)); {$HINTS ON} {$ENDIF} end; function PowerInteger(Const Base : Single; Exponent : Integer) : Single; begin {$IFDEF USE_FASTMATH} result := FastPower(Base,Exponent); {$ELSE} {$HINTS OFF} Result:=Math.Power(Base, Exponent); {$HINTS ON} {$ENDIF} end; Function PowerInt(Const Base, Power : Integer) : Single; Var I: Integer; Temp: Double; Begin Temp := 1; For I := 0 To Pred(Power) Do Temp := Temp * Base; Result := Temp; End; Function pow3(x : Single) : Single; Begin If x = 0.0 Then Result := 0.0 Else Result := x * x * x; End; {%endregion} {%region%=====[ Fonctions trigonométrique ]====================================} function Sin(x:Single):Single;Inline; begin {$IFDEF USE_FASTMATH} result := FastSinLUT(x);//RemezSin(x); {$ELSE} result := System.Sin(x); {$ENDIF} end; function Cos(x:Single):Single; Inline; begin {$IFDEF USE_FASTMATH} result := FastCosLUT(x); //RemezCos(x); {$ELSE} result := System.Cos(x); {$ENDIF} end; function Tan(const X : Single) : Single; begin {$IFDEF USE_FASTMATH} Result := FastTan(x); {$ELSE} {$HINTS OFF} Result:=Math.Tan(x); {$HINTS ON} {$ENDIF} end; procedure SinCos(const Theta: Single; out Sin, Cos: Single); var s, c : Single; begin {$ifdef USE_FASTMATH} //C := RemezCos(Theta); //S := RemezCos(cPIdiv2-Theta); S := FastSinLUT(Theta); C := FastCosLUT(Theta); {$else} Math.SinCos(Theta, s, c); {$endif} {$HINTS OFF} Sin:=s; Cos:=c; {$HINTS ON} end; procedure SinCos(const theta, radius : Single; out Sin, Cos: Single); var s, c : Single; begin {$ifdef USE_FASTMATH} S := FastSinLUT(Theta); C := FastCosLUT(Theta); {$else} Math.SinCos(Theta, s, c); {$endif} {$HINTS OFF} // Sin:=s; Cos:=c; Sin:=s*radius; Cos:=c*radius; {$HINTS ON} end; function CoTan(const X : Single) : Single; begin {$HINTS OFF} Result:=Math.CoTan(x); {$HINTS ON} end; Function Hypot(Const X, Y : Single) : Single; Begin {$IFDEF USE_FASTMATH} Result := FastSqrt((X*X) + (Y*Y)); {$ELSE} Result := System.Sqrt(Sqr(X) + Sqr(Y)); {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions trigonométrique inverse ]============================} function ArcCos(const x : Single): Single; begin {$IFDEF USE_FASTMATH} if FastAbs(X) > 1.0 then Result := FastArcCosine(FastSign(X)) else Result:=FastArcCosine(X); {$ELSE} {$HINTS OFF} if Abs(X) > 1.0 then Result := Math.ArcCos(Sign(X)) else Result:=Math.ArcCos(X); {$HINTS ON} {$ENDIF} end; Function ArcSin(Const x : Single) : Single; begin {$IFDEF USE_FASTMATH} Result:= FastArcTan2(X, FastSqrt(1 - (x*x))) {$ELSE} Result:= Math.ArcTan2(X, System.Sqrt(1 - Sqr(X))) {$ENDIF} end; function ArcTan2(const Y, X : Single) : Single; begin {$IFDEF USE_FASTMATH} Result:= FastArcTan2(y, x) {$ELSE} Result:= Math.ArcTan2(x,y) {$ENDIF} end; Function ArcCsc(Const X : Single) : Single; Begin If IsZero(X) Then Result := cInfinity Else Result := ArcSin(1 / X); End; Function ArcSec(Const X : Single) : Single; Begin If IsZero(X) Then Result := cInfinity Else Result := ArcCos(1 / X); End; Function ArcCot(Const X : Single) : Single; Begin If IsZero(X) Then Result := cPIDiv2 Else {$IFDEF USE_FASTMATH} Result := FastArcTan(1 / X); {$ELSE} Result := ArcTan(1 / X); {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions hyperbolique ]=======================================} function Sinh(const x : Single) : Single; begin {$IFDEF USE_FASTMATH} Result:=0.5*(FastExp(x) - FastExp(-x)); {$ELSE} Result:=0.5*(Exp(x)- Exp(-x)); {$ENDIF} end; function Cosh(const x : Single) : Single; begin {$IFDEF USE_FASTMATH} Result:=0.5*(FastExp(x)+ FastExp(-x)); {$ELSE} Result:=0.5*(Exp(x)+ Exp(-x)); {$ENDIF} end; Function SinCosh(Const x : Single) : Single; Begin {$IFDEF USE_FASTMATH} Result := 0.5 * (FastExp(x) - FastExp(-x)); {$ELSE} Result := 0.5 * (Exp(x) - Exp(-x)); {$ENDIF} End; Function CscH(Const X : Single) : Single; Begin Result := 1 / SinH(X); End; Function SecH(Const X : Single) : Single; Begin Result := 1 / CosH(X); End; Function CotH(Const X : Extended) : Extended; Begin Result := 1 / TanH(X); End; {%endregion%} {%region%=====[ Fonctions hyperbolique inverse ]===============================} Function ArcCscH(Const X : Single) : Single; Begin {$IFDEF USE_FASTMATH} If IsZero(X) Then Result := cInfinity Else If X < 0 Then Result := FastLn((1 - FastInvSqrt(1 + X * X)) * X) Else Result := FastLn((1 + FastInvSqrt(1 + X * X)) * X); {$ELSE} If IsZero(X) Then Result := Infinity Else If X < 0 Then Result := System.Ln((1 - System.Sqrt(1 + X * X)) / X) Else Result := System.Ln((1 + System.Sqrt(1 + X * X)) / X); {$ENDIF} End; Function ArcSecH(Const X : Single) : Single; Begin {$IFDEF USE_FASTMATH} If IsZero(X) Then Result := cInfinity Else If SameValue(X, 1) Then Result := 0 Else Result := FastLn((FastInvSqrt(1 - X * X) + 1) * X); {$ELSE} If IsZero(X) Then Result := cInfinity Else If SameValue(X, 1) Then Result := 0 Else Result := System.Ln((System.Sqrt(1 - X * X) + 1) / X); {$ENDIF} End; Function ArcCotH(Const X : Single) : Single; Begin {$IFDEF USE_FASTMATH} If SameValue(X, 1) Then Result := cInfinity // 1.0 / 0.0 Else If SameValue(X, -1) Then Result := -cInfinity // -1.0 / 0.0 Else Result := 0.5 * FastLn((X + 1) / (X - 1)); {$ELSE} If SameValue(X, 1) Then Result := cInfinity // 1.0 / 0.0 Else If SameValue(X, -1) Then Result := -cInfinity // -1.0 / 0.0 Else Result := 0.5 * Ln((X + 1) / (X - 1)); {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions racine carré ]=======================================} function Sqrt(const A: Single): Single; Begin {$IFDEF USE_FASTMATH} {$IFDEF CPU64} Result := FastSqrt(A); {$ELSE} Result := System.Sqrt(A); {$ENDIF} {$ELSE} Result := System.Sqrt(A); {$ENDIF} End; Function InvSqrt(v : Single) : Single; {$IFNDEF USE_FASTMATH} var s : single; {$ENDIF} Begin {$IFDEF USE_FASTMATH} Result := FastInvSqrt(v); {$ELSE} s:= System.sqrt(v); //+ EpsilonXTResolution; Result := 1 / s; {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions logarithmique ]======================================} function Log10(X : Single) : Single; // Log10(X):=Log2(X) * Log10(2) Begin {$IFDEF USE_FASTMATH} Result := FastLog10(x); {$ELSE} Result := Math.Log10(X); //Result := Ln(x) * 0.4342944819; // 1/ln(10) {$ENDIF} End; Function Log2(X : Single) : Single; Begin {$IFDEF USE_FASTMATH} Result := FastLog2(x); {$ELSE} Result := Math.Log2(X); //Result := Ln(x) * 1.4426950408889634079; // 1/ln(2) {$ENDIF} End; function LogN(Base, X : Single) : Single; Begin {$IFDEF USE_FASTMATH} // LogN(X):=Log2(X) / Log2(N) Result := FastLog2(Base) / FastLog2(X); {$ELSE} Result := Math.LogN(Base, X); {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions logarithmique naturel ]==============================} Function Ln(X : Single) : Single; Var aLo, aHi, aMid, aVal: Single; Begin If (X < 0) Then Begin Result := 0; Exit; End; // use recursion to get approx range If (X < 1) Then Begin Result := -BZMath.ln(1 / X); Exit; End; If (X > cEulerNumber) Then Begin Result := BZMath.Ln(X / cEulerNumber) + 1; Exit; End; // X is now between 1 and e // Y is between 0 and 1 alo := 0.0; ahi := 1.0; While (True) Do Begin amid := (alo + ahi) / 2; aval := BZMath.exp(amid); If (aval > X) Then ahi := amid; If (aval < X) Then alo := amid; If (abs(aval - X) < 0.0001) Then //cEpsilon Begin Result := amid; Exit; End; End; End; Function LnXP1(x : Single) : Single; {$IFDEF USE_FASTMATH} Var y: Single; {$ENDIF} Begin {$IFDEF USE_FASTMATH} If (x >= 4.0) Then Result := FastLn(1.0 + x) Else Begin y := 1.0 + x; If (y = 1.0) Then Result := x Else Begin Result := FastLn(y); // lnxp1(-1) = ln(0) = -Inf If y > 0.0 Then Result := Result + (x - (y - 1.0)) / y; End; End; {$ELSE} Result := Math.LnXP1(X); {$ENDIF} End; {%endregion%} {%region%=====[ Fonctions exponentielles ]=====================================} Function Exp(Const X : Single) : Single; Var I, N: Integer; D: Double; Begin If (X = 1.0) Then Result := cEulerNumber Else If (x < 0) Then Result := 1.0 / Exp(-X) Else Begin N := 2; Result := 1.0 + X; Repeat D := X; For I := 2 To N Do Begin D := D * (X / I); End; Result := Result + D; Inc(N); Until (d <= cEpsilon); End; End; Function ldExp(x : Single; N : Integer) : Single; Var r: Single; Begin R := 1; If N > 0 Then Begin While N > 0 Do Begin R := R * 2; Dec(N); End; End Else Begin While N < 0 Do Begin R := R / 2; Inc(N); End; End; Result := x * R; End; {%endregion%} {%region%=====[ Fonctions d'interpolations ]===================================} Function BesselOrderOne(x : Double) : Double; Var p, q: Double; Function J1(x: Double): Double; Const Pone: Array[0..8] Of Double = ( 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 ); Qone: Array[0..8] Of Double = ( 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 ); Var pj, qj: Double; i: Byte; Begin pj := 0.0; qj := 0.0; pj := Pone[8]; qj := Qone[8]; For i := 7 Downto 0 Do Begin pj := pj * x * x + Pone[i]; qj := qj * x * x + Qone[i]; End; Result := (pj / qj); End; Function P1(x: Double): Double; Const Pone: Array[0..5] Of Double = ( 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 ); Qone: Array[0..5] Of Double = ( 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 ); Var xx, pp, qp: Double; i: Byte; Begin pp := 0.0; qp := 0.0; pp := Pone[5]; qp := Qone[5]; xx := 8.0 / x; xx := xx * xx; For i := 4 Downto 0 Do Begin pp := pp * xx + Pone[i]; qp := qp * xx + Qone[i]; End; Result := (pp / qp); End; Function Q1(x: Double): Double; Const Pone: Array[0..5] Of Double = ( 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 ); Qone: Array[0..5] Of Double = ( 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 ); Var xx, pq, qq: Double; i: Byte; Begin pq := 0.0; qq := 0.0; pq := Pone[5]; qq := Qone[5]; xx := 8.0 / x; xx := xx * xx; For i := 4 Downto 0 Do Begin pq := pq * xx + Pone[i]; qq := qq * xx + Qone[i]; End; Result := (pq / qq); End; Begin Result := 0.0; If x = 0.0 Then exit; p := x; If x < 0.0 Then x := -x; If x < 8.0 Then Result := p * J1(x) Else Begin q := Sqrt(2.0 / (cPI * x)) * (P1(x) * (cInvSqrt2 * (System.sin(x) - System.cos(x))) - 8.0 / x * Q1(x) * (-cInvSqrt2 * (System.sin(x) + System.cos(x)))); If p < 0.0 Then q := -q; Result := q; End; End; Function Bessel(x : Double) : Double; Begin If x = 0.0 Then Result := cPIdiv4 Else Result := BesselOrderOne(cPI * x) / (2.0 * x); End; Function BesselIO(x : Double) : Double; Var I: Integer; Sum, Y, T: Double; Begin Y := Sqr(0.5 * X); T := Y; I := 2; Sum := 0.0; While T > cFullEpsilon Do Begin Sum := Sum + T; T := T * (Y / (I * I)); Inc(I); End; Result := Sum; End; Function Blackman(x : Double) : Double; Var xpi: Double; Begin xpi := PI * x; Result := 0.42 + 0.5 * System.cos(xpi) + 0.08 * System.cos(2 * xpi); End; Function Sinc(x : Single) : Single; {$IFNDEF USE_FASTMATH} Var xx: Single; {$ENDIF} Begin result :=0.0; {$IFDEF USE_FASTMATH} If x = 0.0 Then Result := 1.0 Else FastSinC(x); {$ELSE} If x = 0.0 Then Result := 1.0 Else Begin xx := cPI * x; Result := System.Sin(xx) / (xx); End; {$ENDIF} End; Function InterpolateLinear(Const start, stop, Delta: Single): Single; Begin Result := start + (stop - start) * Delta; End; Function InterpolateLn(Const Start, Stop, Delta: Single; Const DistortionDegree: Single): Single; Begin Result := (Stop - Start) * Ln(1 + Delta * DistortionDegree) / Ln(1 + DistortionDegree) + Start; End; Function InterpolateExp(Const Start, Stop, Delta: Single; Const DistortionDegree: Single): Single; Begin Result := (Stop - Start) * Exp(-DistortionDegree * (1 - Delta)) + Start; End; Function InterpolatePower(Const Start, Stop, Delta: Single; Const DistortionDegree: Single): Single; Var i: Integer; Begin If (Round(DistortionDegree) <> DistortionDegree) And (Delta < 0) Then Begin i := Round(DistortionDegree); Result := (Stop - Start) * PowerInteger(Delta, i) + Start; End Else Result := (Stop - Start) * Power(Delta, DistortionDegree) + Start; End; Function InterpolateSinAlt(Const Start, Stop, Delta: Single): Single; Begin Result := (Stop - Start) * Delta * Sin(Delta * cPIDiv2) + Start; End; Function InterpolateSin(Const Start, Stop, Delta: Single): Single; Begin Result := (Stop - Start) * Sin(Delta * cPIDiv2) + Start; End; Function InterpolateTan(Const Start, Stop, Delta: Single): Single; Begin Result := (Stop - Start) * Tan(Delta * cPIDiv4) + Start; End; Function InterpolateValue(Const Start, Stop, Delta : Single; Const DistortionDegree : Single; Const InterpolationType : TBZInterpolationType) : Single; Begin Case InterpolationType Of itLinear: Result := InterpolateLinear(Start, Stop, Delta); itPower: Result := InterpolatePower(Start, Stop, Delta, DistortionDegree); itSin: Result := InterpolateSin(Start, Stop, Delta); itSinAlt: Result := InterpolateSinAlt(Start, Stop, Delta); itTan: Result := InterpolateTan(Start, Stop, Delta); itLn: Result := InterpolateLn(Start, Stop, Delta, DistortionDegree); itExp: Result := InterpolateExp(Start, Stop, Delta, DistortionDegree); //itHermit //itQuintic Else Begin Result := -1; End; End; End; Function InterpolateValueSafe(Const OriginalStart, OriginalStop, OriginalCurrent : Single; Const TargetStart, TargetStop : Single; Const DistortionDegree : Single; Const InterpolationType : TBZInterpolationType) : Single; Var ChangeDelta: Single; Begin If OriginalStop = OriginalStart Then Result := TargetStart Else Begin ChangeDelta := (OriginalCurrent - OriginalStart) / (OriginalStop - OriginalStart); Result := InterpolateValue(TargetStart, TargetStop, ChangeDelta, DistortionDegree, InterpolationType); End; End; Function InterpolateValueFast(Const OriginalStart, OriginalStop, OriginalCurrent : Single; Const TargetStart, TargetStop : Single; Const DistortionDegree : Single; Const InterpolationType : TBZInterpolationType) : Single; Var ChangeDelta: Single; Begin ChangeDelta := (OriginalCurrent - OriginalStart) / (OriginalStop - OriginalStart); Result := InterpolateValue(TargetStart, TargetStop, ChangeDelta, DistortionDegree, InterpolationType); End; function InterpolateBilinear(x,y : Single; nw, ne, sw, se : Single) : Single; var cx, cy, m1, m2 : Single; begin cx := 1.0 - x; cy := 1.0 - y; m1 := cx * nw + x * ne; m2 := cx * sw + x * se; Result := (cy * m1 + y * m2); end; {%endregion%} {%region%=====[ fonctions émulées "HL/GL Shader script" ]======================} function SmoothStep(Edge0,Edge1,x: Single): Single;Inline; var t:single; begin t:= Clamp((x-Edge0) / (Edge1 - Edge0),0.0,1.0); result := t * t * (3.0 - 2.0 * t); //t*t * ((t*2.0)*3.0); end; function SmoothStepQuintic(Edge0,Edge1,x: Single): Single;Inline; var t:single; begin t:= Clamp((x-Edge0) / (Edge1 - Edge0),0.0,1.0); result := t * t * t * (t * (t * 6 - 15) + 10); end; function Lerp(Edge0,Edge1,x: Single): Single; Inline; begin // Fast method = Edge0 + x * (Edge1 - Edge0); result := Edge0 * (1 - x) + (Edge1 * x); // S'assure que le resultat = Edge1 quand x = 1. end; function CubicLerp(Edge0, Edge1, Edge2, Edge3, x : Single) : Single; var P, Q, R, S: Double; begin P := (Edge3 - Edge2) - (Edge0 - Edge1); Q := (Edge0 - Edge1) - P; R := Edge2 - Edge0; S := Edge1; Result := P * x * x * x + Q * x * x + R * x + S; end; function CosineLerp(Edge0, Edge1, x : Single) : Single; var f, ft: Double; begin ft := x * cPi; f := (1.0 - cos(ft)) * 0.5; Result := Edge0 * (1 - f) + Edge1 * f; end; function Step(Edge,x: Single): Single; begin if x<Edge then result := 0.0 else result := 1.0; end; Function Length1D(x : Single) : Single; begin Result := Sqrt(x*x); end; function Mix(x, y, a : Double) : Double; begin Result := x * (1 - a) + y * a; end; {%endregion%} {%region%=====[ Fonctions utiles pour les animations ou interpolations ]=======} // Converted from http://www.iquilezles.org/www/articles/functions/functions.htm // Useful for animation Function AlmostIdentity(x, m, n : single) : single; var a,b,t : Single; begin if (x>m) then begin result:= x; exit; end; a := 2.0*n - m; b := 2.0*m - 3.0*n; t := x/m; result := (a*t + b)*t*t + n; end; function Impulse(k,x : Single):Single; Inline; var h:Single; begin h := k*x; result := h * exp(1.0-h); end; Function CubicPulse(c, w, x : Single) : Single; begin result := 0.0; x := abs(x - c); if(x>w ) then exit; x := x / w; Result := 1.0 - x * x * (3.0-2.0 * x); end; Function ExpStep(x, k, n : Single) : Single; begin result := Exp(-k * pow(x,n)); end; Function Parabola(x, k : Single) : Single; begin result := pow( 4.0*x*(1.0-x), k ); end; Function pcurve(x, a, b : Single) : Single; var k : Single; begin k := pow(a+b,a+b) / (pow(a,a) * pow(b,b)); result := k * pow(x, a) * pow(1.0-x, b); end; Function pSinc(x, k : Single) : Single; var a : Single; begin a := cPI * (k*x-1.0); Result := sin(a)/a; end; Function pGain(x, k : Single) : Single; var a : Single; begin if x<0.5 then begin a := 0.5 * Pow(2.0*x,k); Result := a; end else begin a := 0.5 * Pow(2.0*(1.0-x),k); result :=1.0-a; end; end; function vGain(a, b : Single) : Single; Var c : Single; begin c := (1.0/b-2.0) * (1.0-2.0*a); if (a < 0.5) then Result := a/(c+1.0) else Result := (c-a)/(c-1.0); end; function bias(a, b : Single) : Single; Begin Result := a /((1.0/b-2)*(1.0-a)+1); End; {%endregion%} {%region%=====[ AUtres fonctions utiles ]======================================} Function Val2Percent(min, max, val : Single) : Integer; Var S: Single; Begin If max = min Then S := 0 Else If max < min Then S := 100 * ((val - max) / (min - max)) Else S := 100 * ((val - min) / (max - min)); If S < 0 Then S := 0; If S > 100 Then S := 100; Result := round(S); End; { NOTE : 1 cm = 37.79527559055 pixels 1 pixel = 0.02645833333333416 cm } function PixelsToCentimeters(nbPixels : Integer) : Double; begin Result := (nbPixels * 0.02645833333333416) end; function CentimetersToPixels(nbCm : Double) : Integer; begin Result := Round((nbCm / 0.02645833333333416)); end; { NOTE : 1 pouce (inch) = 2,54 cm 1 cm = 0,3937 pouce (inch) } function InchToCentimeters(nbInch : Double) : Double; begin Result := nbInch / 0.3937; end; function CentimetersToInch(nbCm : Double) : Double; begin Result := nbCm * 0.3937; end; function PixelsToMillimeters(nbPixels : Integer) : Double; begin Result := PixelsToCentimeters(nbPixels) * 10; end; function MillimetersToPixels(nbMm : Double) : Integer; begin Result := CentimetersToPixels(nbMm / 10); end; function InchToPixels(nbInch : Double) : Integer; begin Result := CentimetersToPixels(InchToCentimeters(NbInch)); end; function PixelsToInch(nbPixels : Integer) : Double; begin Result := CentimetersToInch(PixelsToCentimeters(nbPixels)); end; function PixelsResolutionToCentimeters(nbPixels, DPI : Integer) : Double; begin Result := nbPixels * 2.54 / DPI; end; function CentimetersToPixelsResolution(nbCm : Double; DPI : Integer) : Integer; begin Result := Round(nbCm * DPI / 2.54); end; function CubeRoot(x : Single) : Single; begin if x<0 then Result := -Math.power(-x, 1/3.0) else Result := Math.power(x, 1/3.0) end; // https://www.particleincell.com/2013/cubic-line-intersection/ function CubicRoot(a, b, c, d : Single) : TBZCubicRootSolution; Const _Coef : Single = 1/3; _Coef2 : Single = 1.732050807568877; // Sqrt(3) var tA, tB, tC, tQ, tQ3, tR, tD, s, t, v, v1 : Single; aR : TBZCubicRootSolution; i : Byte; begin tA := b / a; tB := c / a; tC := d / a; tQ := (3.0 * tb - (tA *tA)) / 9.0; v := tA * tA * tA; tR := (9.0 * tA * tB - 27.0 * tC - (v + v)) / 54.0; tQ3 := (tQ * tQ * tQ); tD := tQ3 + (tR * tR); if (tD >= 0) then // complex or duplicate roots begin v := System.Sqrt(tD); v1 := tR + v; s := Sign(v1) * Math.Power(abs(v1), _Coef); v1 := tR - v; t := Sign(v1) * Math.Power(abs(v1), _Coef); v := -tA * _Coef; v1 := s + t; Result[0] := v + v1; v1 := v1 * 0.5; v1 := v - v1; Result[1] := v1; Result[2] := v1; // discard complex roots v1 := abs(_Coef2 * ((s - t) *0.5)); if (v1 <> 0.0) then begin Result[1] := -1.0; Result[2] := -1.0; end; end else // distinct real roots begin v := arcCos(tR / System.Sqrt(-tQ3)); v1 := tA * _Coef; t := System.Sqrt(-tQ); t := t + t; Result[0] := t * System.cos(v * _Coef)- v1; Result[1] := t * System.cos((v + c2PI) * _Coef) - v1; Result[2] := t * System.cos((v + c4PI) * _Coef) - v1; end; // discard out of spec roots for i := 0 to 2 do begin if (Result[i] < 0.0) or (Result[i] > 1.0) then Result[i] := -1.0; end; end; function ComputeGaussian(x, Sigma : Single) : Single; begin Result := System.exp(((-x * x) / ( 2 * Sigma * Sigma))); end; function ComputeGaussianCenter(x, Sigma : Single) : Single; Var u : Single; begin u:= Sqr(x / Sigma); Result := System.exp(-u * 0.5) end; function ComputeGaussianDerivative(x, Sigma : Single) : Single; begin Result := -x /(Sigma * Sigma) * ComputeGaussian(x,Sigma); end; function ComputeMeanGaussian(x, Sigma : Single) : Single; Var t : Single; begin t := (ComputeGaussian(x,Sigma) + ComputeGaussian((x + 0.5),Sigma) + ComputeGaussian((x - 0.5),Sigma)) * cInvThree; Result := t / (c2PI * Sigma * Sigma); end; function ComputeGaussianDistribution(x, weight, sigma : Single) : Single; Var d, n : Single; begin d := x - weight; n := 1.0 / (System.sqrt(cPI) * sigma); Result := System.exp(-d * d / ( 2 * sigma * sigma)) * n; end; function ComputeLoG(x, Sigma : Single) : Single; var g : Single; begin g := ComputeGaussian(x,Sigma); Result := (x * x - 2 * Sigma * Sigma) / (Math.power(Sigma,4)) * g; end; function ComputeLoGCenter(x, Sigma : Single) : Single; var g : Single; begin g := ComputeGaussianCenter(x,Sigma); Result := (x * x - 2 * Sigma * Sigma) / (Math.power(Sigma,4)) * g; end; function ComputeEuler(Weight : Single) : Single; begin Result := 1.0 / (2 * cPI * Math.Power(Weight, 2.0)); end; function Factorial(x: Int64): Int64; Var i, r : integer; begin r:= 1; for i:= 2 to x do begin r := r * i; end; result := r; end; function ComputeBerstein(x, n: integer; u: Single): Single; var f : Single; begin f := 1.0 - u; result := factorial(n) / (factorial(x) * factorial(n-x)) * power(u, x) * power(f, n-x); end; //https://stackoverflow.com/questions/5731863/mapping-a-numeric-range-onto-another function RangeMap(value, InMin, InMax, OutMin, OutMax : Single) : Single; begin Result := OutMin + (OutMax - OutMin) * ((Value - InMin) / (InMax - InMin)); end; function RangeMap(value, InMin, InMax, OutMin, OutMax : Integer) : integer; begin Result := OutMin + (OutMax - OutMin) * ((Value - InMin) div (InMax - InMin)); end; //function //function RandomRange(Mini, Maxi : Integer) : Integer; //begin // result := Random(Maxi - Mini + 1) + Mini; //end; {%endregion%} //============================================================================== initialization {$IFDEF USE_FASTMATH} _InitSinCosTanLUT; {$ENDIF} finalization {$IFDEF USE_FASTMATH} _DoneSinCosTanLUT; {$ENDIF} //============================================================================== End.
{ Subroutine PICPRG_TINFO (PR, TINFO, STAT) * * Get detailed information about the target chip the library is * configured to into TINFO. STAT is returned with an error if the * library has not been previously configured. } module picprg_tinfo; define picprg_tinfo; %include 'picprg2.ins.pas'; procedure picprg_tinfo ( {get detailed info about the target chip} in out pr: picprg_t; {state for this use of the library} out tinfo: picprg_tinfo_t; {returned detailed target chip info} out stat: sys_err_t); {completion status} val_param; var ent_p: picprg_adrent_p_t; {pointer to current address list entry} begin if picprg_nconfig (pr, stat) then return; {library not configured ?} tinfo.name.max := size_char(tinfo.name.str); tinfo.name1.max := size_char(tinfo.name1.str); string_copy (pr.name_p^.name, tinfo.name); {name of the chosen variant} string_copy (pr.id_p^.name_p^.name, tinfo.name1); {first listed name this PIC} tinfo.idspace := pr.id_p^.idspace; {name space for device ID word} tinfo.id := pr.id; {actual device ID word including rev} tinfo.rev_mask := pr.id_p^.rev_mask; {mask for revision value} tinfo.rev_shft := pr.id_p^.rev_shft; {bits to shift maked revision value right} tinfo.rev := rshft(tinfo.id & tinfo.rev_mask, tinfo.rev_shft); {revision number} tinfo.vdd := pr.name_p^.vdd; {voltage levels} tinfo.vppmin := pr.id_p^.vppmin; {allowable Vpp voltage range} tinfo.vppmax := pr.id_p^.vppmax; tinfo.wbufsz := pr.id_p^.wbufsz; {write buffer size and applicable range} tinfo.wbstrt := pr.id_p^.wbstrt; tinfo.wblen := pr.id_p^.wblen; tinfo.pins := pr.id_p^.pins; {number of pins in DIP package} tinfo.nprog := pr.id_p^.nprog; tinfo.ndat := pr.id_p^.ndat; tinfo.adrres := pr.id_p^.adrres; tinfo.maskprg := pr.id_p^.maskprg; tinfo.maskdat := pr.id_p^.maskdat; tinfo.datmap := pr.id_p^.datmap; tinfo.tprogp := pr.id_p^.tprogp; tinfo.tprogd := pr.id_p^.tprogd; tinfo.nconfig := 0; {init number of config addresses} ent_p := pr.id_p^.config_p; {init to first entry in the list} while ent_p <> nil do begin {once for each entry in the list} tinfo.nconfig := tinfo.nconfig + 1; {count one more CONFIG address} ent_p := ent_p^.next_p; {advance to next list entry} end; tinfo.config_p := pr.id_p^.config_p; {return pointer to list of CONFIG addresses} tinfo.nother := 0; {init number of other addresses} ent_p := pr.id_p^.other_p; {init to first entry in the list} while ent_p <> nil do begin {once for each entry in the list} tinfo.nother := tinfo.nother + 1; {count one more OTHER address} ent_p := ent_p^.next_p; {advance to next list entry} end; tinfo.other_p := pr.id_p^.other_p; {return pointer to list of OTHER addresses} tinfo.fam := pr.id_p^.fam; {PIC family ID} tinfo.eecon1 := pr.id_p^.eecon1; tinfo.eeadr := pr.id_p^.eeadr; tinfo.eeadrh := pr.id_p^.eeadrh; tinfo.eedata := pr.id_p^.eedata; tinfo.visi := pr.id_p^.visi; tinfo.tblpag := pr.id_p^.tblpag; tinfo.nvmcon := pr.id_p^.nvmcon; tinfo.nvmkey := pr.id_p^.nvmkey; tinfo.nvmadr := pr.id_p^.nvmadr; tinfo.nvmadru := pr.id_p^.nvmadru; tinfo.hdouble := pr.id_p^.hdouble; {HEX file addresses are doubled} tinfo.eedouble := pr.id_p^.eedouble; {EEPROM addresses double in HEX file beyond HDOUBLE} end;
unit uBigFastSearchDFM; interface uses Dialogs, Classes, SysUtils, Masks; type TFoundEvent = procedure(AFileName, AFormClass, AObjectName, APropertyName, AValue: string; ALine: Integer) of object; TSearchOption = (soWildcard, soSmartSpace, soStartingWith, soStringsItemsAsSeparateStrings); TSearchOptions = set of TSearchOption; type TScanDFMThread = class(TThread) private FFileName: string; FCode: string; FSearch: string; FCallBack: TFoundEvent; FSearchOptions: TSearchOptions; FFindSQLDump: TStrings; FFoundFormClass: string; FFoundObjectName: string; FFoundPropertyName: string; FFoundValue: string; FFoundLine: Integer; protected procedure Execute; override; procedure DoFound(AFileName, AFormClass, AObjectName, APropertyName, AValue: string; ALine: Integer); procedure HandleFound; public constructor Create(FileName: string; Code: string; Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings = nil); procedure Abandon; end; procedure ScanDFM(Code: string; AFileName: String; Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings = nil); implementation { TScanDFMThread } procedure TScanDFMThread.Abandon; begin // If a thread won't finish (usually because the search mask is too complex) // abandon the thread. Disable the events and give the thread idle priority. // The user will be able to continue and even start new searches, while this // thread continues to run in the background. FCallBack := nil; Priority := tpIdle; OnTerminate := nil; end; constructor TScanDFMThread.Create(FileName, Code, Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings); begin inherited Create(True); FFileName := FileName; FCode := Code; FSearch := Search; FCallBack := CallBack; FSearchOptions := SearchOptions; FFindSQLDump := FindSQLDump; FreeOnTerminate := True; //Resume; end; procedure TScanDFMThread.DoFound(AFileName, AFormClass, AObjectName, APropertyName, AValue: string; ALine: Integer); begin FFoundFormClass := AFormClass; FFoundObjectName := AObjectName; FFoundPropertyName := APropertyName; FFoundValue := AValue; FFoundLine := ALine; Synchronize(HandleFound); end; procedure TScanDFMThread.Execute; begin inherited; if not Terminated then try ScanDFM(FCode, FFileName, FSearch, DoFound, FSearchOptions, FFindSQLDump); except on E:EAbort do else raise; end; end; procedure TScanDFMThread.HandleFound; begin if Assigned(FCallBack) then FCallBack(FFileName, FFoundFormClass, FFoundObjectName, FFoundPropertyName, FFoundValue, FFoundLine) else Abort; end; type TExpecting = (eObject, eObjectName, eObjectClass); procedure DeSpace(var s: string); // Replace all subsequent whitespace characters with one single space var i: Integer; j: Integer; b: Boolean; begin j := 0; b := True; for i := 1 to Length(s) do begin if CharInSet(s[i], [#13,#10,#9,#32]) then begin if not b then begin Inc(j); s[j] := ' '; end; b := True; end else begin Inc(j); s[j] := s[i]; b := False; end; end; SetLength(s, j); end; procedure ScanDFM(Code: string; AFileName: String; Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings = nil); // This routine scans an entire dfm file and skips most characters. It scans // words to find object names and property names. It also triggers on <quote> // and <tab> to find strings. Numbers, binary data and operators are skipped. var i: Integer; // Code pos j: Integer; // Code pos helper Len: Integer; // Length of entire code Buffer: string; // Buffer to hold strings BufferPos: Integer; InfoString: string; // Property name TempString: string; // Property info block FormClass: string; LastObjectName: string; LastIdentifier: string; LastProperty: string; LastPropertyItem: string; LastString: string; Haystack: string; LastItem: Integer; LastCollectionItem: Integer; LastCollectionItemStr: string; CollectionName: string; PropertyName: string; Done: Boolean; // Loop terminator CharacterCode: Integer; // Code of special character Expecting: TExpecting; // What's next? FoundStringParticle: Boolean; PropertyPrinted: Boolean; // Property name printed to FindSQL export ObjectNamePrinted: Boolean; // Object name printed to FindSQL export Line: Integer; // Current line position (of i) LastPropertyLine: Integer; // Line number of last property name procedure IncI; begin if Code[i] = #13 then Inc(Line); Inc(i); end; procedure DecI; begin Dec(i); if Code[i] = #13 then Dec(Line); end; procedure SkipWhiteSpace; begin while (i <= Len) and CharInSet(Code[i], [' ', #9, #13, #10]) do IncI; end; begin Search := UpperCase(Search); // Search case-insensitive // If not 'Starting with', insert a wildcard at the beginning of the search string if (soWildcard in SearchOptions) and not (soStartingWith in SearchOptions) and (Copy(Search, 1, 1) <> '*') then Insert('*', Search, 1); Len := Length(Code); // Store to eliminate multiple function calls Line := 1; // Line number of current position LastPropertyLine := 0; // Line number of last property name i := 1; // Current character Expecting := eObject; // Expected next word LastItem := -1; // Item in stringlist property. -1 = not in stringlist LastCollectionItem := -1; // Item in collection property. -1 = not in collection // Remember if the object name and property name are output already to a // the FindSQL export. ObjectNamePrinted := False; PropertyPrinted := False; while i < Len do begin case Code[i] of 'a'..'z', 'A'..'Z', '_': // Identifier or keyword begin LastProperty := ''; repeat j := i; // Find an identifier (range of alphanumerical characters) and store it repeat IncI until not CharInSet(Code[i], ['a'..'z', 'A'..'Z', '_', '0'..'9']); LastIdentifier := Copy(Code, j, i - j); if Code[i] <> '.' then begin // No dot: Add identifier to property and break the identifier-loop LastProperty := LastProperty + LastIdentifier; DecI; Break; end else begin // Dot found. If identifier is followed by a '.' keep scanning. // Multiple identifiers make up a propery name (like SQL.Strings) LastProperty := LastProperty + LastIdentifier + '.'; IncI; end; until False; PropertyPrinted := False; LastPropertyLine := Line; // Remember line number // Check for object name and class case Expecting of eObject: begin // Found object. Next identifier is the object name if SameText(LastIdentifier, 'object') or SameText(LastIdentifier, 'inherited') then Expecting := eObjectName; end; eObjectName: begin LastObjectName := LastProperty; ObjectNamePrinted := False; SkipWhiteSpace; if Code[i] = ':' then // Skip the colon IncI; Expecting := eObjectClass; // Scan for object class end; eObjectClass: begin // The first object class we find is the form class. Store it if FormClass = '' then FormClass := LastProperty; Expecting := eObject; end; end; end; '(': LastItem := 0; // Count items for stringlist properties ')': LastItem := -1; // -1 = not in stringlist '<': begin // Count items for collection properties and remember the collection // property name LastCollectionItem := 0; CollectionName := LastProperty; SkipWhiteSpace; end; '>': begin LastCollectionItem := -1; CollectionName := ''; SkipWhiteSpace; end; '''', '#': begin LastString := ''; repeat // Scan string loop (multiple parts, separated by a '+') repeat // Scan string part loop (range of strings and special chars) FoundStringParticle := False; if Code[i] = '''' then // String, encapsuled in quotes begin j := i; FoundStringParticle := True; // Find the end quote of this string Done := False; repeat // Loop until a quote is found that is not immediately followed // by another. Two quotes will be translated to one, later. repeat IncI until (Code[i] = '''') or (i > Len); if (i > Len) or (Code[Succ(i)] <> '''') then Done := True else if Code[Succ(i)] = '''' then IncI; // Skip over this next quote. until Done; // Allocate a buffer that's large enough at least SetLength(Buffer, i - j); BufferPos := 1; // Add all characters to the buffer, skipping each first quote // This way not many relocates are necessary while j < i do begin if Code[j] = '''' then Inc(j); Buffer[BufferPos] := Code[j]; Inc(j); Inc(BufferPos); end; // Truncate the string SetLength(Buffer, BufferPos - 1); LastString := LastString + Buffer; // Move to the first character behind the string. IncI; end; while Code[i] = '#' do // Special character begin FoundStringParticle := True; j := Succ(i); // Scan for numerals repeat IncI; until not CharInSet(Code[i], ['0'..'9']); // If TryStrToInt failed, this means there are none or too many // digits following the #. This means the dfm is corrupt. Skip // the character and try to move on. if TryStrToInt(Copy(Code, j, i - j), CharacterCode) then LastString := LastString + Chr(CharacterCode); end; until not FoundStringParticle; // String ended. Search for a +, because this indicates there is // another part SkipWhiteSpace; if (Code[i] <> '+') then // No +? Then break. begin if (soStringsItemsAsSeparateStrings in SearchOptions) or // Treat all strings items as separate strings (LastItem = -1) or // Not in stringlist at all (not CharInSet(Code[i], ['''', '#'])) // String is not continued. If LastItem > -1 and this is true, the dfm is corrupt! then begin DecI; // It will be incremented after the case. Break; end else begin // Stringlist is continued LastString := LastString + #13#10; // Insert enters between stringlist items end; end else begin IncI; // Skip the plus SkipWhiteSpace; // Skip whitespace after the plus end; until False; // Perform actual search Haystack := UpperCase(LastString); if soSmartSpace in SearchOptions then DeSpace(HayStack); if ((soWildcard in SearchOptions) and MatchesMask(Haystack, Search)) or ( (not (soWildcard in SearchOptions)) and ( ((soStartingWith in SearchOptions) and (Copy(Haystack, 1, Length(Search)) = Search)) or (not (soStartingWith in SearchOptions) and (Pos(Search, Haystack) > 0)) ) ) then begin if (soStringsItemsAsSeparateStrings in SearchOptions) and (LastItem > -1) then LastPropertyItem := Format('[%d]', [LastItem]) // Show in which item the text was found else LastPropertyItem := ''; if LastCollectionItem > -1 then LastCollectionItemStr := Format('[%d]', [LastCollectionItem]) else LastCollectionItemStr := ''; if CollectionName <> '' then PropertyName := CollectionName + LastCollectionItemStr + '.' + LastProperty + LastPropertyItem else PropertyName := LastProperty + LastPropertyItem; CallBack(AFileName, FormClass, LastObjectName, PropertyName, LastString + #13#10, LastPropertyLine); end; if Assigned(FindSQLDump) then begin // Present a FindDFM 1.0-like result of these properties: if SameText(LastProperty, 'CommandText') or SameText(LastProperty, 'CommandText.Strings') or SameText(LastProperty, 'ProcedureName') or SameText(LastProperty, 'SearchQuery.Strings') or SameText(LastProperty, 'CountQuery.Strings') then begin // Print the name of this object, if not already if not ObjectNamePrinted then begin TempString := '| ' + FormClass + '.' + LastObjectName + ' |'; InfoString := '+' + StringOfChar('-', Length(TempString) - 2) + '+'; InfoString := InfoString + #13#10 + TempString + #13#10 + InfoString; FindSQLDump.Add(InfoString); ObjectNamePrinted := True; // Remember we printed it end; if not PropertyPrinted then begin // Add some information to some properties if SameText(LastProperty, 'SearchQuery.Strings') then InfoString := 'Search query:'#13#10 + LastString else if SameText(LastProperty, 'CountQuery.Strings') then InfoString := 'Count query:'#13#10 + LastString else if SameText(LastProperty, 'ProcedureName') then InfoString := 'execute ' + LastString else InfoString := LastString; FindSQLDump.Add(InfoString); // Property value PropertyPrinted := True; end; end; end; if LastItem > -1 then Inc(LastItem); if LastCollectionItem > -1 then Inc(LastCollectionItem); end; // string case else // No recognized character. Probably an operator. Ignore end; IncI; end; end; end.
unit UPersistentObject; interface uses Classes, DB, Contnrs, DBClient; type TRecordType = (rtFirst, rtLast, rtAll); TPersistentObject = class; TPersistentObjectClass = class of TPersistentObject; TInitObject = procedure(Obj: TPersistentObject) of object; // Classe base de persistência TPersistentObject = class(TInterfacedPersistent) private FNew: Boolean; FGetChildOnDemand: Boolean; FGuid: string; FOwner: TObject; FOriginalIDValues: TParams; // Método para retornar o valor de uma propriedade do objeto function GetPropertyValue(PropName: string): string; protected // Método de classe que retorna o formato da data para operações no banco class function DateFormat: string; virtual; // Método de classe para setar o valor das properties do objeto com base num dataset class procedure SetPropertiesFromDataSet(DataSet: TDataSet; PersistentObject: TPersistentObject); virtual; procedure SetPropertyFromField(Field: TField; const PropName: string); virtual; // Método que retorna se o objeto é novo ou não function GetNew: Boolean; virtual; // Método para retorna o nome do campo de status do objeto function GetStatusField: string; virtual; // Método executado no OnCreate para realizar operação de inicialização // do objeto procedure InitObject; virtual; // Método para persistir o objeto no banco function Insert: Boolean; virtual; abstract; // Método que verifica se uma determinada proprieda é nula function IsPropertyNull(const PropName: string): Boolean; virtual; // Método para definir o valor a ser considerado como nulo para campos Char function NullCharValue(const PropName: string): Char; virtual; // Método para definir o valor a ser considerado como nulo para campos Double function NullDoubleValue(const PropName: string): Double; virtual; // Método para definir o valor a ser considerado como nulo para campos Integer function NullIntegerValue(const PropName: string): Integer; virtual; // Método para definir o valor a ser considerado como nulo para campos String function NullStringValue(const PropName: string): string; virtual; // Método para definir o valor padrão para propriedade do tipo Char procedure SetDefaultCharPropertyValue(const PropName: string); virtual; // Método para definir o valor padrão para propriedade do tipo Double procedure SetDefaultDoublePropertyValue(const PropName: string); virtual; // Método para definir o valor padrão para propriedade do tipo Integer procedure SetDefaultIntegerPropertyValue(const PropName: string); virtual; // Método para definir o valor padrão para propriedade do tipo TObject procedure SetDefaultObjectPropertyValue(const PropName: string); virtual; // Método para definir o valor padrão para propriedade do tipo String procedure SetDefaultStringPropertyValue(const PropName: string); virtual; // Método para setar os valor padrão de todas as propriedades do objeto procedure SetDefaultValues; virtual; // Método para atualizar o objeto no banco function Update: Boolean; virtual; abstract; procedure SetOriginalIdFieldValue(Field: TField); property OriginalIDValues: TParams read FOriginalIDValues; public constructor Create; overload; virtual; // Construtor para já inicializar algumas propriedade do objeto constructor Create(const DefaultProperties: array of string; const DefaultValues: array of Variant); overload; virtual; constructor Create(const GetChildOnDemand: Boolean); overload; virtual; destructor Destroy; override; // Método para copiar as propriedade de outro objeto procedure Assign(Source: TPersistent); override; // Métodos para retornar a representação textual do objeto function AsString: String; virtual; // Método para localizar um objeto com base no ID único function FindById(const Id: integer): Boolean; virtual; // Método de classe para retornar o(s) campos(s) chave do objeto // class function GetIdField: TArrayStr; virtual; // Método de classe que retorna o nome da tabela class function GetTableName: string; virtual; // Método para inverter Status do objeto procedure InverteStatus; // Método de classe que retorna uma instância do objeto como base num registro // do dataset class function NewInstanceFromDataSet(DataSet: TDataSet; OnInitObject: TInitObject): TPersistentObject; virtual; class function NewInstanceFromDataSetSomeFields(DataSet: TDataSet; OnInitObject: TInitObject; aCampos: Array of String; const GetChildOnDemand: Boolean = True): TPersistentObject; virtual; // Método que preenche os atributos de um objeto com base num registro do dataset class procedure FromDataSet(DataSet: TDataSet; PersistentObject: TPersistentObject; OnInitObject: TInitObject); // Método que retorna um novo registro a partir de uma instancia de um objeto. class procedure NewRecordDataSetFromInstace(DataSet: TDataSet; PersistentObject: TPersistentObject); // Método que posiciona o cursor do dataset na posição do objeto class procedure SetDataSetCursorFromObject(DataSet: TDataSet; PersistentObject: TPersistentObject); class procedure SaveChanges(PersistentObject: TPersistentObject; DataSet: TClientDataSet); overload; class procedure SaveChanges(PersistentObject: TPersistentObject; DataSet: TClientDataSet; UpdateStatus: TUpdateStatus); overload; // Método de classe que prepara uma instrução SQL para ser executada class function SQLFilter(const Fields: array of string; const Values: array of variant): string; // Método para validar a persistencia do objeto no banco function IsDuplicated: Boolean; virtual; abstract; property Owner: TObject read FOwner write FOwner; property New: Boolean read GetNew write FNew; property PropertyValue[PropName: string]: string read GetPropertyValue; default; property GetChildOnDemand: Boolean read FGetChildOnDemand write FGetChildOnDemand; published // Método para limpar as propriedades do objeto procedure Clear; virtual; // Método para excluir o objeto do banco function Delete: Boolean; virtual; // Método para localizar o objeto com base num filtro function Find(const Filter: string; const RecordType: TRecordType = rtAll): Boolean; overload; virtual; abstract; // Método para salvar o objeto do banco function Save: Boolean; virtual; end; implementation uses UStringFunctions, TypInfo, SysUtils, UDicionario, Variants, StrUtils, UObjectFunctions, FMTBcd, USistemaException; { TPersistentObject } /// <summary> /// Método para copiar as propriedade de outro objeto /// </summary> /// <param name="Source">Objeto original</param> procedure TPersistentObject.Assign(Source: TPersistent); var obj: TPersistentObject; PropList: TPropList; c: Integer; begin if Source.ClassType = Self.ClassType then begin c := GetPropList(Self.ClassInfo, tkProperties, @PropList); for c := 0 to Pred(c) do // Copiando somente propriedades que não são somente leitura if Assigned(PropList[c].SetProc) then case PropType(Source, PropList[c].Name) of tkChar, tkString, tkLString, tkUString: SetStrProp(Self, PropList[c].Name, GetStrProp(Source, PropList[c].Name)); tkFloat: SetFloatProp(Self, PropList[c].Name, GetFloatProp(Source, PropList[c].Name)); tkInteger: SetOrdProp(Self, PropList[c].Name, GetOrdProp(Source, PropList[c].Name)); tkClass: SetObjectProp(Self, PropList[c].Name, GetObjectProp(Source, PropList[c].Name)); end; end else raise EConvertError.CreateFmt('Cannot assign a %s object to a %s object', [Source.ClassName, Self.ClassName]); end; /// <summary> /// Método para limpar as propriedades do objeto /// </summary> function TPersistentObject.AsString: String; begin end; procedure TPersistentObject.Clear; var PropList: TPropList; i, c: Integer; begin c := GetPropList(Self.ClassInfo, tkProperties, @PropList); for i := 0 to Pred(c) do // As propriedade iniciadas com _ ou que não possuem set (somente leitura) não devem ser inicializadas if (Copy(PropList[i].Name, 1, 1) <> '_') and Assigned(PropList[i].SetProc) then case PropType(Self, PropList[i].Name) of tkChar : Self.SetDefaultCharPropertyValue(PropList[i].Name); tkClass : Self.SetDefaultObjectPropertyValue(PropList[i].Name); tkFloat : Self.SetDefaultDoublePropertyValue(PropList[i].Name); tkInteger: Self.SetDefaultIntegerPropertyValue(PropList[i].Name); tkString, tkLString, tkUString : Self.SetDefaultStringPropertyValue(PropList[i].Name); end; Self.New := True; end; constructor TPersistentObject.Create(const GetChildOnDemand: Boolean); begin Self.Create; Self.GetChildOnDemand := GetChildOnDemand; end; /// <summary> /// Construtor para já inicializar algumas propriedade do objeto /// </summary> /// <param name="DefaultProperties">Propriedades a serem inicializadas</param> /// <param name="DefaultValues">Valores das propriedades</param> constructor TPersistentObject.Create(const DefaultProperties: array of string; const DefaultValues: array of Variant); var i: Integer; begin if Length(DefaultProperties) <> Length(DefaultValues) then raise EInvalidOperation.Create('The size of DefaultProperties and DefaultValues is different.'); Self.Create; Self.New := True; for i := Low(DefaultProperties) to High(DefaultProperties) do TObjectFunctions.SetPrimitiveTypeProperty(Self, DefaultProperties[i], DefaultValues[i]); end; constructor TPersistentObject.Create; begin inherited Create; Self.New := True; Self.GetChildOnDemand := True; Self.SetDefaultValues; Self.InitObject; {$IFDEF TRACE} if TraceAtivo then FGuid := TInternalLog.CriarInstancia(Self.ClassType); {$ENDIF} end; /// <summary> /// Método de classe que retorna o formato da data para operações no banco /// </summary> /// <returns>Formato da data, que pode ser usado na função FormatDateTime</returns> class function TPersistentObject.DateFormat: string; begin Result := 'YYYY-MM-DD'; end; /// <summary> /// Método para excluir o objeto do banco /// </summary> /// <returns>True se a exclusão foi feita com sucesso e False caso contrário</returns> function TPersistentObject.Delete: Boolean; begin Result := True; end; destructor TPersistentObject.Destroy; begin FOriginalIDValues.Free; {$IFDEF TRACE} if TraceAtivo then TInternalLog.DestruirInstancia(FGuid); {$ENDIF} inherited; end; /// <summary> /// Método para localizar um objeto com base no ID único /// </summary> /// <param name="Id">Identificador do objeto</param> /// <returns>True se localizou e False caso contrário</returns> function TPersistentObject.FindById(const Id: integer): Boolean; begin // Result := (Length(Self.GetIdField) = 1) and Self.Find(Format('%s = %d', [Dicionario.Valor(Self.GetIdField[0]), Id])); end; class procedure TPersistentObject.FromDataSet(DataSet: TDataSet; PersistentObject: TPersistentObject; OnInitObject: TInitObject); begin if DataSet.Active then begin if Assigned(OnInitObject) then OnInitObject(PersistentObject); SetPropertiesFromDataSet(DataSet, PersistentObject); end; end; /// <summary> /// Método de classe para retornar o(s) campos(s) chave do objeto /// </summary> /// <returns>Um array com os campos chave do objeto</returns> //class function TPersistentObject.GetIdField: TArrayStr; //begin // SetLength(Result, 1); // Result[0] := 'ID'; //end; /// <summary> /// Método que retorna se o objeto é novo, ou seja não foi persistido ainda, ou não /// </summary> /// <returns>True se o objeto é novo e False caso contrário</returns> function TPersistentObject.GetNew: Boolean; begin Result := FNew; end; /// <summary> /// Método para retornar o valor de uma propriedade do objeto /// </summary> /// <param name="PropName">Nome da propriedade</param> /// <returns>Valor da propriedade</returns> function TPersistentObject.GetPropertyValue(PropName: string): string; begin PropName := Dicionario.Significado(PropName); // Verificando se o atributo é publicado if IsPublishedProp(Self, PropName) then // Se o tipo do atributo for Classe, retorna vazio if PropType(Self, PropName) in [tkClass] then Result := '' else Result := GetPropValue(Self, PropName); end; /// <summary> /// Método para retorna o nome do campo de status do objeto /// </summary> /// <returns>Nome do campo de status</returns> function TPersistentObject.GetStatusField: string; begin end; /// <summary> /// Método de classe que retorna o nome da tabela /// </summary> /// <returns>Nome da tabela no banco</returns> class function TPersistentObject.GetTableName: string; begin Result := StringReplace(Self.ClassName, 'T', '', []); end; /// <summary> /// Método executado no OnCreate para realizar operação de inicialização /// do objeto /// </summary> procedure TPersistentObject.InitObject; begin FOriginalIDValues := TParams.Create(nil); end; /// <summary> /// Método para inverter Status do objeto /// </summary> procedure TPersistentObject.InverteStatus; var sStatus: string; begin // Verificando se o objeto possui campo de status if IsPublishedProp(Self, Self.GetStatusField) then begin sStatus := GetStrProp(Self, Self.GetStatusField); SetStrProp(Self, Self.GetStatusField, IfThen(sStatus = 'A', 'I', 'A')); end; end; /// <summary> /// Método que verifica se uma determinada proprieda é nula /// </summary> /// <param name="PropName">Nome da propriedade</param> /// <returns>True se a propriedade estiver nula e False caso contrário</returns> function TPersistentObject.IsPropertyNull(const PropName: string): Boolean; begin case PropType(Self, PropName) of tkChar: Result := GetStrProp(Self, PropName) = Self.NullCharValue(PropName); tkString, tkLString, tkUString: Result := GetStrProp(Self, PropName) = Self.NullStringValue(PropName); tkInteger: Result := GetOrdProp(Self, PropName) = Self.NullIntegerValue(PropName); tkFloat: Result := GetFloatProp(Self, PropName) = Self.NullDoubleValue(PropName); end; end; /// <summary> /// Método de classe que retorna uma instância do objeto como base num registro /// do dataset /// </summary> /// <param name="DataSet">Dataset de origem dos dados</param> /// <param name="OnInitObject">Evento de inicialização do objeto</param> /// <returns>Objeto instanciado</returns> class function TPersistentObject.NewInstanceFromDataSet( DataSet: TDataSet; OnInitObject: TInitObject): TPersistentObject; begin if DataSet.Active then begin Result := Self.Create; Result.New := DataSet.IsEmpty; Self.FromDataSet(DataSet, Result, OnInitObject); end else Result := nil; end; class function TPersistentObject.NewInstanceFromDataSetSomeFields( DataSet: TDataSet; OnInitObject: TInitObject; aCampos: array of String; const GetChildOnDemand: Boolean): TPersistentObject; var i: Integer; begin if DataSet.Active then begin Result := Self.Create(GetChildOnDemand); Result.New := False; if Assigned(OnInitObject) then OnInitObject(Result); for i := Low(aCampos) to High(aCampos) do // Verificando se a propriedade com o nome do campo é publicada para setar o valor if IsPublishedProp(Result, Dicionario.Significado(aCampos[i])) then if not DataSet.FieldByName(aCampos[i]).IsNull then SetPropValue(Result, Dicionario.Significado(DataSet.FieldByName(aCampos[i]).FieldName), DataSet.FieldByName(aCampos[i]).Value); end else Result := nil; end; class procedure TPersistentObject.NewRecordDataSetFromInstace(DataSet: TDataSet; PersistentObject: TPersistentObject); var c, i: Integer; PropList: TPropList; sFieldName: string; objField: TField; begin if PersistentObject.New then DataSet.Append else DataSet.Edit; // Obtendo lista de propriedades do objeto c := GetPropList(PersistentObject.ClassInfo, tkProperties, @PropList); for i := 0 to c - 1 do begin if Copy(PropList[i].Name, 1, 1) <> '_' then begin sFieldName := Dicionario.Valor(PropList[i].Name); objField := DataSet.FindField(sFieldName); if not Assigned(objField) then Continue; if PersistentObject.IsPropertyNull(PropList[i].Name) then begin if not objField.IsNull then objField.Clear; Continue; end; case PropType(PersistentObject, PropList[i].Name) of tkInteger: objField.AsInteger := GetOrdProp(PersistentObject, PropList[i].Name); { TODO : Verificar } tkFloat: begin if objField.DataType in [ftFMTBcd, ftBCD] then objField.AsBCD := DoubleToBcd(GetFloatProp(PersistentObject, PropList[i].Name)) else objField.AsFloat := GetFloatProp(PersistentObject, PropList[i].Name); end; tkChar, tkString, tkLString, tkUString: objField.AsString := GetStrProp(PersistentObject, PropList[i].Name); else raise ESistemaException.CreateFmt('Type %s is not supported.', [GetEnumName(TypeInfo(TTypeKind), Integer(PropType(PersistentObject, PropList[i].Name)))]); end; end; end; DataSet.Post; end; /// <summary> /// Método para definir o valor a ser considerado como nulo para campos Char /// </summary> /// <returns>Valor a ser considerado como nulo para a propriedade</returns> function TPersistentObject.NullCharValue(const PropName: string): Char; begin Result := ' '; end; /// <summary> /// Método para definir o valor a ser considerado como nulo para campos Double /// </summary> /// <returns>Valor a ser considerado como nulo para a propriedade</returns> function TPersistentObject.NullDoubleValue(const PropName: string): Double; begin Result := 0.0; end; /// <summary> /// Método para definir o valor a ser considerado como nulo para campos Integer /// </summary> /// <returns>Valor a ser considerado como nulo para a propriedade</returns> function TPersistentObject.NullIntegerValue(const PropName: string): Integer; begin Result := 0; end; /// <summary> /// Método para definir o valor a ser considerado como nulo para campos String /// </summary> /// <returns>Valor a ser considerado como nulo para a propriedade</returns> function TPersistentObject.NullStringValue(const PropName: string): string; begin Result := ''; end; /// <summary> /// Método para salvar o objeto do banco /// </summary> /// <returns></returns> function TPersistentObject.Save: Boolean; begin if Self.New then Result := Self.Insert else Result := Self.Update; end; class procedure TPersistentObject.SaveChanges( PersistentObject: TPersistentObject; DataSet: TClientDataSet; UpdateStatus: TUpdateStatus); begin DataSet.StatusFilter := [UpdateStatus]; DataSet.First; while not DataSet.EOF do begin if DataSet.UpdateStatus <> UpdateStatus then begin DataSet.Next; Continue; end; Self.FromDataSet(DataSet, PersistentObject, nil); PersistentObject.New := DataSet.UpdateStatus = usInserted; if DataSet.UpdateStatus = usDeleted then PersistentObject.Delete else PersistentObject.Save; PersistentObject.Clear; DataSet.Next; end; end; class procedure TPersistentObject.SaveChanges( PersistentObject: TPersistentObject; DataSet: TClientDataSet); begin DataSet.DisableControls; try SaveChanges(PersistentObject, DataSet, usInserted); SaveChanges(PersistentObject, DataSet, usModified); SaveChanges(PersistentObject, DataSet, usDeleted); finally DataSet.StatusFilter := []; DataSet.EnableControls; end; end; class procedure TPersistentObject.SetDataSetCursorFromObject(DataSet: TDataSet; PersistentObject: TPersistentObject); var i: Integer; // IdFields: TArrayStr; IdValues: Array of Variant; begin // IdFields := Self.GetIdField; // SetLength(IdValues, Length(IdFields)); // // for i := 0 to Length(IdFields) - 1 do // begin // if IsPublishedProp(PersistentObject, IdFields[i]) then // begin // IdValues[i] := PersistentObject.GetPropertyValue(IdFields[i]); // IdFields[i] := Dicionario.Valor(IdFields[i]); // end; // end; // // DataSet.Locate(TStringFunctions.ArrayToStr(IdFields, ';'), IdValues, []); end; /// <summary> /// Método para definir o valor padrão para propriedade do tipo Char /// </summary> /// <param name="PropName">Nome da propriedade</param> procedure TPersistentObject.SetDefaultCharPropertyValue( const PropName: string); begin SetStrProp(Self, PropName, ' '); end; /// <summary> /// Método para definir o valor padrão para propriedade do tipo Double /// </summary> /// <param name="PropName">Nome da propriedade</param> procedure TPersistentObject.SetDefaultDoublePropertyValue( const PropName: string); begin SetFloatProp(Self, PropName, 0); end; /// <summary> /// Método para definir o valor padrão para propriedade do tipo Integer /// </summary> /// <param name="PropName">Nome da propriedade</param> procedure TPersistentObject.SetDefaultIntegerPropertyValue( const PropName: string); begin SetOrdProp(Self, PropName, 0); end; /// <summary> /// Método para definir o valor padrão para propriedade do tipo Object /// </summary> /// <param name="PropName">Nome da propriedade</param> procedure TPersistentObject.SetDefaultObjectPropertyValue( const PropName: string); begin end; /// <summary> /// Método para definir o valor padrão para propriedade do tipo String /// </summary> /// <param name="PropName">Nome da propriedade</param> procedure TPersistentObject.SetDefaultStringPropertyValue( const PropName: string); begin SetStrProp(Self, PropName, ''); end; /// <summary> /// Método para setar os valor padrão de todas as propriedades do objeto /// </summary> procedure TPersistentObject.SetDefaultValues; begin end; class procedure TPersistentObject.SetPropertiesFromDataSet(DataSet: TDataSet; PersistentObject: TPersistentObject); var i: Integer; sCampo: string; begin for i := 0 to DataSet.FieldCount - 1 do begin if not DataSet.Fields[i].IsNull then begin sCampo := Dicionario.Significado(DataSet.Fields[i].FieldName); PersistentObject.SetPropertyFromField(DataSet.Fields[i], sCampo); end; end; end; procedure TPersistentObject.SetOriginalIdFieldValue(Field: TField); var objParam: TParam; begin objParam := Self.OriginalIDValues.FindParam(Field.FieldName); if not Assigned(objParam) then objParam := Self.OriginalIDValues.Add as TParam; objParam.ParamType := ptInput; objParam.AssignField(Field); end; procedure TPersistentObject.SetPropertyFromField(Field: TField; const PropName: string); begin // Verificando se a propriedade com o nome do campo é publicada para setar o valor if IsPublishedProp(Self, PropName) then begin // if TStringFunctions.Contains(PropName, Self.GetIdField, False) then Self.SetOriginalIdFieldValue(Field); SetPropValue(Self, PropName, Field.Value); end; end; /// <summary> /// Método de classe que prepara uma instrução SQL para ser executada /// </summary> /// <param name="Fields">Campos do filtro</param> /// <param name="Values">Valores</param> /// <returns>String formatada para a consulta</returns> class function TPersistentObject.SQLFilter(const Fields: array of string; const Values: array of variant): string; var i: Integer; sField : string; begin // Definindo cláusula WHERE Result := ''; for i := Low(Fields) to High(Fields) do begin // Obtendo nome do campo sField := TStringFunctions.ExtractSymbols(Fields[i]); sField := StringReplace(Fields[i], sField, Dicionario.Valor(sField), [rfReplaceAll]); Result := Format('%s AND %s ', [Result, sField]); case VarType(Values[i]) of varString, varUString : Result := Result + QuotedStr(string(Values[i])); varInteger : Result := Result + StringReplace(Values[i], '.', '', [rfReplaceAll]); varDate : Result := Result + QuotedStr(FormatDateTime(Self.DateFormat, Values[i])); varDouble : Result := Result + StringReplace(Values[i], '.', '', [rfReplaceAll]); end; end; // Ajustando cláusula if Result <> '' then System.Delete(Result, 1, 5); end; end.
{*******************************************************} { } { Turbo Pascal Runtime Library } { String Handling Unit } { } { Copyright (C) 1990,92 Borland International } { } {*******************************************************} unit Strings; {$S-} interface { StrLen returns the number of characters in Str, not counting } { the null terminator. } function StrLen(Str: PChar): Word; { StrEnd returns a pointer to the null character that } { terminates Str. } function StrEnd(Str: PChar): PChar; { StrMove copies exactly Count characters from Source to Dest } { and returns Dest. Source and Dest may overlap. } function StrMove(Dest, Source: PChar; Count: Word): PChar; { StrCopy copies Source to Dest and returns Dest. } function StrCopy(Dest, Source: PChar): PChar; { StrECopy copies Source to Dest and returns StrEnd(Dest). } function StrECopy(Dest, Source: PChar): PChar; { StrLCopy copies at most MaxLen characters from Source to Dest } { and returns Dest. } function StrLCopy(Dest, Source: PChar; MaxLen: Word): PChar; { StrPCopy copies the Pascal style string Source into Dest and } { returns Dest. } function StrPCopy(Dest: PChar; Source: String): PChar; { StrCat appends a copy of Source to the end of Dest and } { returns Dest. } function StrCat(Dest, Source: PChar): PChar; { StrLCat appends at most MaxLen - StrLen(Dest) characters from } { Source to the end of Dest, and returns Dest. } function StrLCat(Dest, Source: PChar; MaxLen: Word): PChar; { StrComp compares Str1 to Str2. The return value is less than } { 0 if Str1 < Str2, 0 if Str1 = Str2, or greater than 0 if } { Str1 > Str2. } function StrComp(Str1, Str2: PChar): Integer; { StrIComp compares Str1 to Str2, without case sensitivity. The } { return value is the same as StrComp. } function StrIComp(Str1, Str2: PChar): Integer; { StrLComp compares Str1 to Str2, for a maximum length of } { MaxLen characters. The return value is the same as StrComp. } function StrLComp(Str1, Str2: PChar; MaxLen: Word): Integer; { StrLIComp compares Str1 to Str2, for a maximum length of } { MaxLen characters, without case sensitivity. The return value } { is the same as StrComp. } function StrLIComp(Str1, Str2: PChar; MaxLen: Word): Integer; { StrScan returns a pointer to the first occurrence of Chr in } { Str. If Chr does not occur in Str, StrScan returns NIL. The } { null terminator is considered to be part of the string. } function StrScan(Str: PChar; Chr: Char): PChar; { StrRScan returns a pointer to the last occurrence of Chr in } { Str. If Chr does not occur in Str, StrRScan returns NIL. The } { null terminator is considered to be part of the string. } function StrRScan(Str: PChar; Chr: Char): PChar; { StrPos returns a pointer to the first occurrence of Str2 in } { Str1. If Str2 does not occur in Str1, StrPos returns NIL. } function StrPos(Str1, Str2: PChar): PChar; { StrUpper converts Str to upper case and returns Str. } function StrUpper(Str: PChar): PChar; { StrLower converts Str to lower case and returns Str. } function StrLower(Str: PChar): PChar; { StrPas converts Str to a Pascal style string. } function StrPas(Str: PChar): String; { StrNew allocates a copy of Str on the heap. If Str is NIL or } { points to an empty string, StrNew returns NIL and doesn't } { allocate any heap space. Otherwise, StrNew makes a duplicate } { of Str, obtaining space with a call to the GetMem standard } { procedure, and returns a pointer to the duplicated string. } { The allocated space is StrLen(Str) + 1 bytes long. } function StrNew(Str: PChar): PChar; { StrDispose disposes a string that was previously allocated } { with StrNew. If Str is NIL, StrDispose does nothing. } procedure StrDispose(Str: PChar); implementation {$W-} function StrLen(Str: PChar): Word; assembler; asm CLD LES DI,Str MOV CX,0FFFFH XOR AL,AL REPNE SCASB MOV AX,0FFFEH SUB AX,CX end; function StrEnd(Str: PChar): PChar; assembler; asm CLD LES DI,Str MOV CX,0FFFFH XOR AL,AL REPNE SCASB MOV AX,DI MOV DX,ES DEC AX end; function StrMove(Dest, Source: PChar; Count: Word): PChar; assembler; asm PUSH DS CLD LDS SI,Source LES DI,Dest MOV AX,DI MOV DX,ES MOV CX,Count CMP SI,DI JAE @@1 STD ADD SI,CX ADD DI,CX DEC SI DEC DI @@1: REP MOVSB CLD POP DS end; function StrCopy(Dest, Source: PChar): PChar; assembler; asm PUSH DS CLD LES DI,Source MOV CX,0FFFFH XOR AL,AL REPNE SCASB NOT CX LDS SI,Source LES DI,Dest MOV AX,DI MOV DX,ES REP MOVSB POP DS end; function StrECopy(Dest, Source: PChar): PChar; assembler; asm PUSH DS CLD LES DI,Source MOV CX,0FFFFH XOR AL,AL REPNE SCASB NOT CX LDS SI,Source LES DI,Dest REP MOVSB MOV AX,DI MOV DX,ES DEC AX POP DS end; function StrLCopy(Dest, Source: PChar; MaxLen: Word): PChar; assembler; asm PUSH DS CLD LES DI,Source MOV CX,MaxLen MOV BX,CX XOR AL,AL REPNE SCASB SUB BX,CX MOV CX,BX LDS SI,Source LES DI,Dest MOV BX,DI MOV DX,ES REP MOVSB STOSB XCHG AX,BX POP DS end; function StrPCopy(Dest: PChar; Source: String): PChar; assembler; asm PUSH DS CLD LDS SI,Source LES DI,Dest MOV BX,DI MOV DX,ES LODSB XOR AH,AH XCHG AX,CX REP MOVSB XOR AL,AL STOSB XCHG AX,BX POP DS end; function StrCat(Dest, Source: PChar): PChar; assembler; asm PUSH Dest.Word[2] PUSH Dest.Word[0] PUSH CS CALL NEAR PTR StrEnd PUSH DX PUSH AX PUSH Source.Word[2] PUSH Source.Word[0] PUSH CS CALL NEAR PTR StrCopy MOV AX,Dest.Word[0] MOV DX,Dest.Word[2] end; function StrLCat(Dest, Source: PChar; MaxLen: Word): PChar; assembler; asm PUSH Dest.Word[2] PUSH Dest.Word[0] PUSH CS CALL NEAR PTR StrEnd MOV CX,Dest.Word[0] ADD CX,MaxLen SUB CX,AX JBE @@1 PUSH DX PUSH AX PUSH Source.Word[2] PUSH Source.Word[0] PUSH CX PUSH CS CALL NEAR PTR StrLCopy @@1: MOV AX,Dest.Word[0] MOV DX,Dest.Word[2] end; function StrComp(Str1, Str2: PChar): Integer; assembler; asm PUSH DS CLD LES DI,Str2 MOV SI,DI MOV CX,0FFFFH XOR AX,AX CWD REPNE SCASB NOT CX MOV DI,SI LDS SI,Str1 REPE CMPSB MOV AL,DS:[SI-1] MOV DL,ES:[DI-1] SUB AX,DX POP DS end; function StrIComp(Str1, Str2: PChar): Integer; assembler; asm PUSH DS CLD LES DI,Str2 MOV SI,DI MOV CX,0FFFFH XOR AX,AX CWD REPNE SCASB NOT CX MOV DI,SI LDS SI,Str1 @@1: REPE CMPSB JE @@4 MOV AL,DS:[SI-1] CMP AL,'a' JB @@2 CMP AL,'z' JA @@2 SUB AL,20H @@2: MOV DL,ES:[DI-1] CMP DL,'a' JB @@3 CMP DL,'z' JA @@3 SUB DL,20H @@3: SUB AX,DX JE @@1 @@4: POP DS end; function StrLComp(Str1, Str2: PChar; MaxLen: Word): Integer; assembler; asm PUSH DS CLD LES DI,Str2 MOV SI,DI MOV AX,MaxLen MOV CX,AX JCXZ @@1 XCHG AX,BX XOR AX,AX CWD REPNE SCASB SUB BX,CX MOV CX,BX MOV DI,SI LDS SI,Str1 REPE CMPSB MOV AL,DS:[SI-1] MOV DL,ES:[DI-1] SUB AX,DX @@1: POP DS end; function StrLIComp(Str1, Str2: PChar; MaxLen: Word): Integer; assembler; asm PUSH DS CLD LES DI,Str2 MOV SI,DI MOV AX,MaxLen MOV CX,AX JCXZ @@4 XCHG AX,BX XOR AX,AX CWD REPNE SCASB SUB BX,CX MOV CX,BX MOV DI,SI LDS SI,Str1 @@1: REPE CMPSB JE @@4 MOV AL,DS:[SI-1] CMP AL,'a' JB @@2 CMP AL,'z' JA @@2 SUB AL,20H @@2: MOV DL,ES:[DI-1] CMP DL,'a' JB @@3 CMP DL,'z' JA @@3 SUB DL,20H @@3: SUB AX,DX JE @@1 @@4: POP DS end; function StrScan(Str: PChar; Chr: Char): PChar; assembler; asm CLD LES DI,Str MOV SI,DI MOV CX,0FFFFH XOR AL,AL REPNE SCASB NOT CX MOV DI,SI MOV AL,Chr REPNE SCASB MOV AX,0 CWD JNE @@1 MOV AX,DI MOV DX,ES DEC AX @@1: end; function StrRScan(Str: PChar; Chr: Char): PChar; assembler; asm CLD LES DI,Str MOV CX,0FFFFH XOR AL,AL REPNE SCASB NOT CX STD DEC DI MOV AL,Chr REPNE SCASB MOV AX,0 CWD JNE @@1 MOV AX,DI MOV DX,ES INC AX @@1: CLD end; function StrPos(Str1, Str2: PChar): PChar; assembler; asm PUSH DS CLD XOR AL,AL LES DI,Str2 MOV CX,0FFFFH REPNE SCASB NOT CX DEC CX JE @@2 MOV DX,CX MOV BX,ES MOV DS,BX LES DI,Str1 MOV BX,DI MOV CX,0FFFFH REPNE SCASB NOT CX SUB CX,DX JBE @@2 MOV DI,BX @@1: MOV SI,Str2.Word[0] LODSB REPNE SCASB JNE @@2 MOV AX,CX MOV BX,DI MOV CX,DX DEC CX REPE CMPSB MOV CX,AX MOV DI,BX JNE @@1 MOV AX,DI MOV DX,ES DEC AX JMP @@3 @@2: XOR AX,AX MOV DX,AX @@3: POP DS end; function StrUpper(Str: PChar): PChar; assembler; asm PUSH DS CLD LDS SI,Str MOV BX,SI MOV DX,DS @@1: LODSB OR AL,AL JE @@2 CMP AL,'a' JB @@1 CMP AL,'z' JA @@1 SUB AL,20H MOV [SI-1],AL JMP @@1 @@2: XCHG AX,BX POP DS end; function StrLower(Str: PChar): PChar; assembler; asm PUSH DS CLD LDS SI,Str MOV BX,SI MOV DX,DS @@1: LODSB OR AL,AL JE @@2 CMP AL,'A' JB @@1 CMP AL,'Z' JA @@1 ADD AL,20H MOV [SI-1],AL JMP @@1 @@2: XCHG AX,BX POP DS end; function StrPas(Str: PChar): String; assembler; asm PUSH DS CLD LES DI,Str MOV CX,0FFFFH XOR AL,AL REPNE SCASB NOT CX DEC CX LDS SI,Str LES DI,@Result MOV AL,CL STOSB REP MOVSB POP DS end; {$W+} function StrNew(Str: PChar): PChar; var L: Word; P: PChar; begin StrNew := nil; if (Str <> nil) and (Str^ <> #0) then begin L := StrLen(Str) + 1; GetMem(P, L); if P <> nil then StrNew := StrMove(P, Str, L); end; end; procedure StrDispose(Str: PChar); begin if Str <> nil then FreeMem(Str, StrLen(Str) + 1); end; end.
{------------------------------------ 功能说明:为方便调用常用接口 创建日期:2010/04/13 作者:WZW 版权:WZW -------------------------------------} unit _Sys; {$weakpackageunit on} interface uses SysUtils, Classes, SysSvc, SysInfoIntf, DialogIntf, MainFormIntf, LogIntf, DBIntf, EncdDecdIntf; type ISysSvcHelper = interface ['{B5DAC302-0608-4472-BA4E-53A9A42CA057}'] function SysInfo: ISysInfo; function Dialogs: IDialog; function Form: IFormMgr; function Log: ILog; function EncdDecd: IEncdDecd; end; TSysSvcHelper = class(TInterfacedObject, ISysSvcHelper) private public function SysInfo: ISysInfo; function Dialogs: IDialog; function Form: IFormMgr; function Log: ILog; function EncdDecd: IEncdDecd; end; function Sys: ISysSvcHelper; implementation const ERR_IntfNotFound = '找不到%s接口!'; procedure RiaseIntfNotFoundErr(IID: TGUID); begin raise Exception.CreateFmt(ERR_IntfNotFound, [GUIDToString(IID)]); end; function Sys: ISysSvcHelper; begin Result := TSysSvcHelper.Create; end; { TSysSvcHelper } function TSysSvcHelper.Dialogs: IDialog; begin if SysService.QueryInterface(IDialog, Result) <> S_OK then RiaseIntfNotFoundErr(IDialog); end; function TSysSvcHelper.EncdDecd: IEncdDecd; begin if SysService.QueryInterface(IEncdDecd, Result) <> S_OK then RiaseIntfNotFoundErr(IEncdDecd); end; function TSysSvcHelper.Form: IFormMgr; begin if SysService.QueryInterface(IFormMgr, Result) <> S_OK then RiaseIntfNotFoundErr(IFormMgr); end; function TSysSvcHelper.Log: ILog; begin if SysService.QueryInterface(ILog, Result) <> S_OK then RiaseIntfNotFoundErr(ILog); end; function TSysSvcHelper.SysInfo: ISysInfo; begin if SysService.QueryInterface(ISysInfo, Result) <> S_OK then RiaseIntfNotFoundErr(ISysInfo); end; end.
unit Unit_alunos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DB, ADODB; type TForm_alunos = class(TForm) btn_novo: TBitBtn; btn_salvar: TBitBtn; btn_alterar: TBitBtn; btn_cancelar: TBitBtn; btn_excluir: TBitBtn; btn_fechar: TBitBtn; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; edt_cod: TEdit; edt_nome: TEdit; edt_idade: TEdit; edt_telefone: TEdit; edt_sexo: TEdit; ADOQuery_aux: TADOQuery; btn_localizar: TBitBtn; procedure FormShow(Sender: TObject); procedure btn_novoClick(Sender: TObject); procedure btn_salvarClick(Sender: TObject); procedure btn_alterarClick(Sender: TObject); procedure btn_cancelarClick(Sender: TObject); procedure btn_fecharClick(Sender: TObject); procedure btn_excluirClick(Sender: TObject); procedure btn_localizarClick(Sender: TObject); private { Private declarations } public { Public declarations } operacao, pk : string; procedure desabilita_salvar(Sender: TObject); procedure habilita_salvar(Sender: TObject); procedure bloqueia_campos; procedure libera_campos; procedure limpa_campos; end; var Form_alunos: TForm_alunos; implementation uses Unit_logon, Unit_pesquisa; {$R *.dfm} { TForm_alunos } procedure TForm_alunos.bloqueia_campos; var i : integer; begin for i := 1 to Form_alunos.ComponentCount -1 do begin if Form_alunos.Components[i] is TEdit then begin (Form_alunos.Components[i] as TEdit).Enabled := False; (Form_alunos.Components[i] as TEdit).Color := clInfoBk; end; end; end; procedure TForm_alunos.desabilita_salvar(Sender: TObject); begin btn_novo.Enabled := True; btn_salvar.Enabled := False; btn_alterar.Enabled := True; btn_cancelar.Enabled := False; btn_excluir.Enabled := True; if Sender = btn_novo then operacao := 'novo' else if Sender = btn_salvar then operacao := 'salvar' else if Sender = btn_alterar then operacao := 'alterar' else if Sender = btn_cancelar then operacao := 'cancelar' else if Sender = btn_excluir then operacao := 'excluir'; end; procedure TForm_alunos.habilita_salvar(Sender: TObject); begin btn_novo.Enabled := False; btn_salvar.Enabled := True; btn_alterar.Enabled := False; btn_cancelar.Enabled := True; btn_excluir.Enabled := False; if Sender = btn_novo then operacao := 'novo' else if Sender = btn_salvar then operacao := 'salvar' else if Sender = btn_alterar then operacao := 'alterar' else if Sender = btn_cancelar then operacao := 'cancelar' else if Sender = btn_excluir then operacao := 'excluir'; end; procedure TForm_alunos.libera_campos; var i : integer; begin for i := 1 to Form_alunos.ComponentCount -1 do begin if Form_alunos.Components[i] is TEdit then begin if (Form_alunos.Components[i] as TEdit).Name <> 'edt_cod' then begin (Form_alunos.Components[i] as TEdit).Enabled := True; (Form_alunos.Components[i] as TEdit).Color := clWindow; end; end; end; end; procedure TForm_alunos.limpa_campos; var i : integer; begin for i := 1 to Form_alunos.ComponentCount -1 do begin if Form_alunos.Components[i] is TEdit then begin (Form_alunos.Components[i] as TEdit).Clear; end; end; end; procedure TForm_alunos.FormShow(Sender: TObject); begin pk := ''; operacao := ''; limpa_campos; bloqueia_campos; desabilita_salvar(sender); end; procedure TForm_alunos.btn_novoClick(Sender: TObject); begin libera_campos; limpa_campos; pk := ''; habilita_salvar(sender); end; procedure TForm_alunos.btn_salvarClick(Sender: TObject); var deuerro : boolean; begin if (edt_nome.Text='') or (edt_idade.Text='') or (edt_telefone.Text='') or (edt_sexo.Text='') then begin Showmessage('Preencha todos os campos!'); end else begin if operacao = 'novo' then adoquery_aux.SQL.Text := ' INSERT INTO ALUNOS ' + ' (NOME, IDADE, TELEFONE, SEXO) VALUES ' + '('+ QuotedStr(edt_nome.Text) + ','+ edt_idade.Text + ','+ QuotedStr(edt_telefone.Text) + ','+ QuotedStr(edt_sexo.Text) + ')' else if operacao = 'alterar' then adoquery_aux.SQL.Text := ' UPDATE ALUNOS SET '+ ' NOME ='+ QuotedStr(edt_nome.Text) + ', IDADE ='+ edt_idade.Text + ', TELEFONE ='+ QuotedStr(edt_telefone.Text) + ', SEXO ='+ QuotedStr(edt_sexo.Text) + ' WHERE COD_ALUNO = '+ pk; Form_logon.ConexaoBD.BeginTrans; try ADOQuery_aux.ExecSQL; deuerro := false; except on E : Exception do begin deuerro := true; if Form_logon.ErroBD(E.Message,'PK_Alunos') = 'Sim' then Showmessage('Aluno já cadastrado!') else if Form_logon.ErroBD(E.Message,'FK_Matriculas_Alunos') = 'Sim' then Showmessage('Existem matrículas cadastradas para este aluno!') else Showmessage('Ocorreu o seguinte erro: ' + E.Message); end; end; if deuerro = true then begin Form_logon.ConexaoBD.RollbackTrans; end else begin Form_logon.ConexaoBD.CommitTrans; if operacao = 'novo' then begin ADOQuery_aux.SQL.Text:=' SELECT COD_ALUNO FROM ALUNOS ' + ' WHERE NOME = '+ QuotedStr(edt_nome.Text) + ' AND IDADE = ' + edt_idade.Text + ' AND TELEFONE = ' + QuotedStr(edt_telefone.Text) + ' AND SEXO = ' + QuotedStr(edt_sexo.Text); ADOQuery_aux.Open; pk := ADOQuery_aux.fieldbyname('COD_ALUNO').AsString; ADOQuery_aux.Close; end; desabilita_salvar(sender); bloqueia_campos; edt_cod.Text := pk; end; end; end; procedure TForm_alunos.btn_alterarClick(Sender: TObject); begin if pk = '' then Showmessage('Impossível alterar!') else begin libera_campos; habilita_salvar(sender); end; end; procedure TForm_alunos.btn_cancelarClick(Sender: TObject); begin if operacao = 'novo' then limpa_campos; desabilita_salvar(sender); bloqueia_campos; end; procedure TForm_alunos.btn_fecharClick(Sender: TObject); begin Close; end; procedure TForm_alunos.btn_excluirClick(Sender: TObject); var deuerro : boolean; begin if pk = '' then Showmessage('Impossível excluir!') else begin adoquery_aux.SQL.Text := ' DELETE FROM ALUNOS ' + ' WHERE COD_ALUNO = ' + pk; Form_logon.ConexaoBD.BeginTrans; try ADOQuery_aux.ExecSQL; deuerro := false; except on E : Exception do begin deuerro := true; if Form_logon.ErroBD(E.Message,'FK_Matriculas_Alunos') = 'Sim' then Showmessage('Existem matrículas cadastradas para este aluno!') else Showmessage('Ocorreu o seguinte erro: ' + E.Message); end; end; if deuerro = true then begin Form_logon.ConexaoBD.RollbackTrans; end else begin Form_logon.ConexaoBD.CommitTrans; pk := ''; desabilita_salvar(sender); limpa_campos; bloqueia_campos; end; end; end; procedure TForm_alunos.btn_localizarClick(Sender: TObject); begin limpa_campos; bloqueia_campos; desabilita_salvar(sender); Form_pesquisa.sql_pesquisa:='SELECT * FROM ALUNOS '; Form_pesquisa.ShowModal; if Form_pesquisa.chave <> '' then begin pk := Form_pesquisa.chave; ADOQuery_aux.SQL.Text := ' SELECT * FROM ALUNOS '+ ' WHERE COD_ALUNO = ' + pk; ADOQuery_aux.Open; edt_cod.Text := ADOQuery_aux.fieldbyname('COD_ALUNO').AsString; edt_nome.Text := ADOQuery_aux.fieldbyname('NOME').AsString; edt_idade.Text := ADOQuery_aux.fieldbyname('IDADE').AsString; edt_telefone.Text := ADOQuery_aux.fieldbyname('TELEFONE').AsString; edt_sexo.Text := ADOQuery_aux.fieldbyname('SEXO').AsString; end; end; end.
unit USalesLineItem; interface uses UMoney, UProductDescription; type ISalesLineItem = interface function getSubTotal(): IMoney; end; TSalesLineItem = class(TInterfacedObject, ISalesLineItem) private quantity: Integer; /// <link>aggregation</link> description: IProductDescription; public function getSubTotal(): IMoney; constructor Create(desc: IProductDescription; quantity: Integer); end; implementation { SalesLineItem } constructor TSalesLineItem.Create(desc: IProductDescription; quantity: integer); begin Self.description:=desc; Self.quantity:=quantity; end; function TSalesLineItem.getSubTotal: IMoney; begin Result:=description.getPrice().times(quantity); end; end.
program testchar03(output); {test character passed byref} procedure plusone(var c:char); var i:integer; begin i := ord(c); i := i + 1; c := chr(i); end; procedure printplusone(c:char); var x:char; begin x := c; writeln('before: ', x); plusone(x); writeln('after: ', x); end; begin printplusone('0'); printplusone('a'); printplusone('%'); end.
unit RestFulServerTests; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Windows, Sysutils, Classes, IniFiles, DUnitX.TestFramework, IdHttp, IdSSLOpenSSL, DateSupport, StringSupport, FileSupport, AdvObjects, AdvGenerics, AdvStringBuilders, FHIRConstants, FHIRBase, FHIRLang, FHIRTypes, FHIRResources, FHIRSupport, FHIRUtilities, FHIRClient, SCIMObjects, SmartOnFhirUtilities, SmartOnFhirTestingLogin, FHIRServerConstants, ServerUtilities, FHIRServerContext, FHIRStorageService, FHIRUserProvider, FHIRRestServer, WebSourceProvider; Const TEST_USER_NAME = 'DunitX-test-user'; TEST_ANON_USER_NAME = 'DunitX-anon-user'; JWT = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjZjZDg1OTdhMWY2ODVjZTA2Y2NhNDJkZTBjMjVmNmY0YjA0OGQ2ODkifQ.'+ 'eyJhenAiOiI5NDAwMDYzMTAxMzguYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI5NDAwMDYzMTAxMzguYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTE5MDQ2MjAwNTMzNjQzOTIyODYiLCJlbWFpbCI6ImdyYWhhbWVnQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLC'+'JhdF9oYXNoIjoiRGltRTh0Zy1XM1U3dFY1ZkxFS2tuUSIsImlzcyI6ImFjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE1MDExMjg2NTgsImV4cCI6MTUwMTEzMjI1OH0.'+ 'DIQA4SvN66r6re8WUxcM9sa5PnVaX1t0Sh34H7ltJE1ElFrwzRAQ3Hz2u_M_gE7a4NaxmbJDFQnVGI3PvZ1TD_bT5zFcFKcq1NWe6kHNFYYn3slxSzGuj02bCdRsTRKu9LXs0YZM1uhbbimOyyajJHckT3tT2dpXYCdfZvBLVu7LUwchBigxE7Q-QnsXwJh28f9P-C1SrA-hLkVf9F7E7zBXgUtkoEyN4rI7FLI6tP7Yc_i'+'ryICAVu2rR9AZCU-hTICbN-uBC7Fuy-kMr-yuu9zdZsaS4LYJxyoAPZNIengjtNcceDVX9m-Evw-Z1iwSFTtDvVyBlC7xbf4JdxaSRw'; // token from google for Grahame Grieve type TTestStorageService = class; TTestFHIROperationEngine = class (TFHIROperationEngine) private FIsReadAllowed : boolean; FStorage : TTestStorageService; public function opAllowed(resource : string; command : TFHIRCommandType) : Boolean; procedure StartTransaction; override; procedure CommitTransaction; override; procedure RollbackTransaction; override; procedure ExecuteConformanceStmt(request: TFHIRRequest; response : TFHIRResponse); override; function ExecuteRead(request: TFHIRRequest; response : TFHIRResponse; ignoreHeaders : boolean) : boolean; override; procedure ExecuteSearch(request: TFHIRRequest; response : TFHIRResponse); override; property IsReadAllowed : boolean read FIsReadAllowed write FIsReadAllowed; end; TTestingFHIRUserProvider = class (TFHIRUserProvider) public Function loadUser(id : String; var key : integer) : TSCIMUser; override; function CheckLogin(username, password : String; var key : integer) : boolean; override; end; TTestOAuthLogin = class (TAdvObject) private client_id, name, redirect, state, scope, jwt, patient: String; public function Link : TTestOAuthLogin; overload; end; TTestStorageService = class (TFHIRStorageService) private FlastSession : TFHIRSession; FLastReadSystem : String; FLastReadUser : String; FLastUserEvidence : TFHIRUseridEvidence; FLastSystemEvidence : TFHIRSystemIdEvidence; FOAuths : TAdvMap<TTestOAuthLogin>; procedure reset; protected function GetTotalResourceCount: integer; override; public Constructor Create; override; Destructor Destroy; override; procedure RecordFhirSession(session: TFhirSession); override; procedure QueueResource(r: TFhirResource; dateTime: TDateTimeEx); override; function createOperationContext(lang : String) : TFHIROperationEngine; override; Procedure Yield(op : TFHIROperationEngine; exception : Exception); override; procedure recordOAuthLogin(id, client_id, scope, redirect_uri, state : String); override; function hasOAuthSession(id : String; status : integer) : boolean; override; function fetchOAuthDetails(key, status : integer; var client_id, name, redirect, state, scope : String) : boolean; override; procedure updateOAuthSession(id : String; state, key : integer; var client_id : String); override; procedure recordOAuthChoice(id : String; scopes, jwt, patient : String); override; procedure RegisterAuditEvent(session: TFhirSession; ip: String); override; procedure RegisterConsentRecord(session: TFhirSession); override; function getClientInfo(id : String) : TRegisteredClientInformation; override; function getClientName(id : String) : string; override; function storeClient(client : TRegisteredClientInformation; sessionKey : integer) : String; override; end; [TextFixture] TRestFulServerTests = Class (TObject) private FIni : TFHIRServerIniFile; FStore : TTestStorageService; FContext : TFHIRServerContext; FServer : TFhirWebServer; FClientXml : TFhirHTTPClient; FClientJson : TFhirHTTPClient; FClientSSL : TFhirHTTPClient; FClientSSLCert : TFhirHTTPClient; public [Setup] procedure Setup; [TearDown] procedure TearDown; [TestCase] Procedure TestLowLevelXml; [TestCase] Procedure TestLowLevelJson; [TestCase] Procedure TestCapabilityStatementXml; [TestCase] Procedure TestCapabilityStatementJson; [TestCase] Procedure TestSSL; [TestCase] Procedure TestCapabilityStatementSSL; [TestCase] Procedure TestPatientExampleJson; [TestCase] Procedure TestPatientExampleXml; [TestCase] Procedure TestPatientExampleSSL; [TestCase] Procedure TestPatientExampleOWin; [TestCase] Procedure TestPatientExampleSmartOnFhir; [TestCase] Procedure TestConformanceCertificateNone; [TestCase] Procedure TestConformanceCertificate; [TestCase] Procedure TestConformanceCertificateNotOk; [TestCase] Procedure TestConformanceCertificateSpecified; [TestCase] Procedure TestConformanceCertificateWrong; [TestCase] Procedure TestConformanceCertificateOptionalNone; [TestCase] Procedure TestConformanceCertificateOptionalRight; [TestCase] Procedure TestConformanceCertificateOptionalWrong; [TestCase] Procedure TestPatientExampleCertificate; [TestCase] Procedure TestPatientExampleCertificateJWT; [TestCase] Procedure TestPatientExampleCertificateJWTNoCert; end; implementation { TTestStorageService } destructor TTestStorageService.Destroy; begin FOAuths.Free; FlastSession.Free; inherited; end; constructor TTestStorageService.Create; begin inherited; FOAuths := TAdvMap<TTestOAuthLogin>.create; end; function TTestStorageService.createOperationContext(lang: String): TFHIROperationEngine; begin result := TTestFHIROperationEngine.create(nil, lang); TTestFHIROperationEngine(result).FIsReadAllowed := true; TTestFHIROperationEngine(result).FStorage := self; end; procedure TTestStorageService.Yield(op: TFHIROperationEngine; exception: Exception); begin op.free; end; function TTestStorageService.GetTotalResourceCount: integer; begin result := 1; end; procedure TTestStorageService.QueueResource(r: TFhirResource; dateTime: TDateTimeEx); begin end; procedure TTestStorageService.RecordFhirSession(session: TFhirSession); begin FlastSession.Free; FlastSession := session.Link; end; procedure TTestStorageService.recordOAuthChoice(id, scopes, jwt, patient: String); var l : TTestOAuthLogin; begin l := FOAuths[id]; l.scope := scopes; l.jwt := jwt; l.patient := patient; end; procedure TTestStorageService.recordOAuthLogin(id, client_id, scope, redirect_uri, state: String); var l : TTestOAuthLogin; begin l := TTestOAuthLogin.Create; try l.client_id := client_id; l.redirect := redirect_uri; l.state := state; l.scope := scope; FOAuths.Add(id, l.Link); finally l.Free; end; end; function TTestStorageService.hasOAuthSession(id: String; status: integer): boolean; begin result := FOAuths.ContainsKey(id); end; procedure TTestStorageService.updateOAuthSession(id: String; state, key: integer; var client_id : String); var l : TTestOAuthLogin; begin l := FOAuths[id]; if not FOAuths.containsKey(inttostr(key)) then FOAuths.Add(inttostr(key), l.Link); client_id := FOAuths[inttostr(key)].client_id; end; function TTestStorageService.fetchOAuthDetails(key, status: integer; var client_id, name, redirect, state, scope: String): boolean; var l : TTestOAuthLogin; begin result := FOAuths.ContainsKey(inttostr(key)); if result then begin l := FOAuths[inttostr(key)]; client_id := l.client_id; name := l.name; redirect := l.redirect; state := l.state; scope := l.scope; end; end; function TTestStorageService.getClientInfo(id: String): TRegisteredClientInformation; begin result := TRegisteredClientInformation.Create; result.name := getClientName(id); result.redirects.Add('http://localhost:961/done'); result.secret := 'this-password-is-never-used'; end; function TTestStorageService.getClientName(id: String): string; begin result := 'test server'; end; procedure TTestStorageService.RegisterAuditEvent(session: TFhirSession; ip: String); begin end; procedure TTestStorageService.RegisterConsentRecord(session: TFhirSession); begin end; procedure TTestStorageService.reset; begin FlastSession.Free; FlastSession := nil; FLastReadSystem := ''; FLastReadUser := ''; FLastUserEvidence := userNoInformation; FLastSystemEvidence := systemNoInformation; FOAuths.Clear; end; function TTestStorageService.storeClient(client: TRegisteredClientInformation; sessionKey: integer): String; begin end; { TTestingFHIRUserProvider } function TTestingFHIRUserProvider.CheckLogin(username, password: String; var key: integer): boolean; begin result := true; if (username = 'test') and (password = 'test') then key := 1 else result := false; end; function TTestingFHIRUserProvider.loadUser(id: String; var key: integer): TSCIMUser; begin result := TSCIMUser.CreateNew; if (id = 'ANONYMOUS') then result.userName := TEST_ANON_USER_NAME else result.userName := TEST_USER_NAME; result.formattedName := result.userName+'.formatted'; key := 1; end; { TTestFHIROperationEngine } procedure TTestFHIROperationEngine.CommitTransaction; begin end; procedure TTestFHIROperationEngine.ExecuteConformanceStmt(request: TFHIRRequest; response: TFHIRResponse); var oConf : TFhirCapabilityStatement; c : TFhirContactPoint; ct: TFhirContactDetail; begin FStorage.FLastReadUser := request.Session.Username; FStorage.FLastReadSystem := request.Session.SystemName; FStorage.FLastUserEvidence := request.Session.UserEvidence; FStorage.FLastSystemEvidence := request.Session.SystemEvidence; response.HTTPCode := 200; oConf := TFhirCapabilityStatement.Create; response.Resource := oConf; oConf.id := 'FhirServer'; ct := oConf.contactList.Append; c := ct.telecomList.Append; c.system := ContactPointSystemOther; c.value := 'http://healthintersections.com.au/'; oConf.version := FHIR_GENERATED_VERSION+'-'+SERVER_VERSION; // this conformance statement is versioned by both oConf.name := 'Health Intersections FHIR Server Conformance Statement'; oConf.publisher := 'Health Intersections'; // oConf.description := 'Standard Conformance Statement for the open source Reference FHIR Server provided by Health Intersections'; oConf.status := PublicationStatusActive; oConf.experimental := false; oConf.date := TDateTimeEx.makeUTC; oConf.software := TFhirCapabilityStatementSoftware.Create; oConf.software.name := 'Reference Server'; oConf.software.version := SERVER_VERSION; oConf.software.releaseDate := TDateTimeEx.fromXml(SERVER_RELEASE_DATE); end; function TTestFHIROperationEngine.ExecuteRead(request: TFHIRRequest; response: TFHIRResponse; ignoreHeaders: boolean): boolean; //var // resourceKey : integer; // field : String; // comp : TFHIRParserClass; // needsObject : boolean; var filename : String; format : TFHIRFormat; begin result := false; NotFound(request, response); filename := Path(['C:\work\org.hl7.fhir\build\publish', 'patient-'+request.Id+'.xml']); if check(response, FIsReadAllowed and (request.ResourceName = 'Patient') and FileExists(filename), 400, lang, StringFormat(GetFhirMessage('MSG_OP_NOT_ALLOWED', lang), [CODES_TFHIRCommandType[request.CommandType], request.ResourceName]), IssueTypeForbidden) then begin result := true; FStorage.FLastReadUser := request.Session.Username; FStorage.FLastReadSystem := request.Session.SystemName; FStorage.FLastUserEvidence := request.Session.UserEvidence; FStorage.FLastSystemEvidence := request.Session.SystemEvidence; response.HTTPCode := 200; response.Message := 'OK'; response.Body := ''; response.versionId := '1'; response.LastModifiedDate := FileGetModified(filename); format := ffXml; response.Resource := FileToResource(filename, format); end; end; procedure TTestFHIROperationEngine.ExecuteSearch(request: TFHIRRequest; response: TFHIRResponse); begin response.bundle := TFhirBundle.Create(BundleTypeSearchset); end; function TTestFHIROperationEngine.opAllowed(resource: string; command: TFHIRCommandType): Boolean; begin result := true; end; procedure TTestFHIROperationEngine.RollbackTransaction; begin end; procedure TTestFHIROperationEngine.StartTransaction; begin end; { TRestFulServerTests } procedure TRestFulServerTests.Setup; begin FIni := TFHIRServerIniFile.Create('C:\work\fhirserver\tests\server-tests.ini'); FStore := TTestStorageService.create(); FContext := TFHIRServerContext.Create(FStore.Link); FContext.ownername := 'Test-Server'; FServer := TFhirWebServer.Create(FIni.Link, 'Test-Server', nil, FContext.Link); // ctxt.TerminologyServer := FterminologyServer.Link; FContext.UserProvider := TTestingFHIRUserProvider.Create; FContext.userProvider.OnProcessFile := FServer.ReturnProcessedFile; FServer.AuthServer.UserProvider := FContext.userProvider.Link; FServer.OWinSecuritySecure := true; FServer.ServeMissingCertificate := true; FServer.ServeUnknownCertificate := true; FServer.Start(true); FServer.SourceProvider := TFHIRWebServerSourceFolderProvider.Create('C:\work\fhirserver\web'); FClientXml := TFhirHTTPClient.Create(FContext.ValidatorContext.Link, FServer.ClientAddress(false), false); FClientXml.UseIndy := true; FClientJson := TFhirHTTPClient.Create(FContext.ValidatorContext.Link, FServer.ClientAddress(false), true); FClientJson.UseIndy := true; FClientSSL := TFhirHTTPClient.Create(FContext.ValidatorContext.Link, FServer.ClientAddress(true), false); FClientSSL.UseIndy := true; FClientSSLCert := TFhirHTTPClient.Create(FContext.ValidatorContext.Link, FServer.ClientAddress(true), true); FClientSSLCert.UseIndy := true; end; procedure TRestFulServerTests.TearDown; begin FClientXml.Free; FClientJson.Free; FClientSSL.Free; FClientSSLCert.Free; FServer.Stop; FServer.Free; FStore.Free; FContext.Free; FIni.Free; end; procedure TRestFulServerTests.TestCapabilityStatementJson; var cs : TFhirCapabilityStatement; begin cs := FClientJson.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; end; procedure TRestFulServerTests.TestCapabilityStatementSSL; var cs : TFhirCapabilityStatement; begin FClientSSL.smartToken := nil; cs := FClientSSL.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; end; procedure TRestFulServerTests.TestCapabilityStatementXml; var cs : TFhirCapabilityStatement; begin cs := FClientXml.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; end; procedure TRestFulServerTests.TestLowLevelXml; var http : TIdHTTP; resp : TBytesStream; begin http := TIdHTTP.Create(nil); Try // ssl := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); // Try // http.IOHandler := ssl; // ssl.SSLOptions.Mode := sslmClient; // ssl.SSLOptions.Method := sslvTLSv1_2; // finally // ssl.free; // end; http.Request.Accept := 'application/fhir+xml'; resp := TBytesStream.create; try http.Get(FServer.ClientAddress(false)+'/metadata', resp); resp.position := 0; Assert.isTrue(http.ResponseCode = 200, 'response code <> 200'); Assert.isTrue(http.Response.ContentType = 'application/fhir+xml', 'response content type <> application/fhir+xml');; finally resp.free; end; finally http.free; end; end; procedure TRestFulServerTests.TestConformanceCertificate; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.ServeUnknownCertificate := true; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; cs := FClientSSL.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'client.test.fhir.org', 'SystemName should be "client.test.fhir.org" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromCertificate, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromCertificate]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateNotOk; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.ServeUnknownCertificate := false; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; try cs := FClientSSL.conformance(false); try Assert.IsFalse(true); finally cs.Free; end; except on e:exception do Assert.IsTrue(e.message.contains('SSL')); // all good - access should be refused end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateNone; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := ''; FClientSSL.certPWord := ''; try cs := FClientSSL.conformance(false); try Assert.IsFalse(true); finally cs.Free; end; except on e:exception do Assert.IsTrue(e.message.contains('handshake')); // all good - access should be refused end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateOptionalNone; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.CertificateIdList.add('B7:90:70:D1:D8:D1:1B:9D:03:86:F4:5B:B5:69:E3:C4'); FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := ''; FClientSSL.certPWord := ''; cs := FClientSSL.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'Unknown', 'SystemName should be "Unknown" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemUnknown, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemUnknown]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateOptionalRight; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.CertificateIdList.add('B7:90:70:D1:D8:D1:1B:9D:03:86:F4:5B:B5:69:E3:C4'); FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; cs := FClientSSL.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'client.test.fhir.org', 'SystemName should be "client.test.fhir.org" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromCertificate, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromCertificate]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateOptionalWrong; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.ServeUnknownCertificate := false; FServer.CertificateIdList.add('B7:90:70:D1:D8:D1:1B:9D:03:86:F4:5B:B5:69:E3:C4'); FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\local.fhir.org.cert'; FClientSSL.certPWord := 'test'; try cs := FClientSSL.conformance(false); try Assert.IsFalse(true); finally cs.Free; end; except on e:exception do Assert.IsTrue(e.message.contains('connecting')); // all good - access should be refused end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateSpecified; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.CertificateIdList.add('B7:90:70:D1:D8:D1:1B:9D:03:86:F4:5B:B5:69:E3:C4'); FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; cs := FClientSSL.conformance(false); try Assert.IsNotNull(cs); finally cs.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'client.test.fhir.org', 'SystemName should be "client.test.fhir.org" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not '+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromCertificate, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromCertificate]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestConformanceCertificateWrong; var cs : TFHIRCapabilityStatement; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.ServeUnknownCertificate := false; FServer.CertificateIdList.add('B7:90:70:D1:D8:D1:1B:9D:03:86:F4:5B:B5:69:E3:C4'); FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\local.fhir.org.cert'; FClientSSL.certPWord := 'test'; try cs := FClientSSL.conformance(false); try Assert.IsFalse(true); finally cs.Free; end; except on e:exception do Assert.IsTrue(e.message.contains('connecting')); // all good - access should be refused end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleCertificate; var res : TFhirResource; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := false; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; try res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsFalse(true, 'should not be abe to read without authorization, but got a '+res.className); finally res.free; end; except on e:EFHIRClientException do Assert.isTrue(e.issue.hasIssueList and (e.issue.issueList[0].code = IssueTypeLogin), 'Isseue type is wrong'); on e:exception do Assert.isTrue(false, e.ClassName+'; '+ e.Message); end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleCertificateJWT; var res : TFhirResource; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.Start(true); FClientSSL.certFile := 'C:\work\fhirserver\tests\client.test.fhir.org.cert'; FClientSSL.certPWord := 'test'; FClientSSL.smartToken := TSmartOnFhirAccessToken.create; FClientSSL.smartToken.accessToken := JWT; FClientSSL.smartToken.expires := now + 20 * DATETIME_MINUTE_ONE; res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.free; end; Assert.IsTrue(FStore.FLastReadSystem = 'client.test.fhir.org', 'SystemName should be "client.test.fhir.org" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = 'grahameg@gmail.com', 'Username should be "grahameg@gmail.com", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userBearerJWT, 'UserEvidence should be "'+CODES_UserIdEvidence[userBearerJWT]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromCertificate, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromCertificate]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleCertificateJWTNoCert; var res : TFhirResource; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.Start(true); FClientSSL.smartToken := TSmartOnFhirAccessToken.create; FClientSSL.smartToken.accessToken := JWT; FClientSSL.smartToken.expires := now + 20 * DATETIME_MINUTE_ONE; res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.free; end; Assert.IsTrue(FStore.FLastReadSystem = 'Unknown', 'SystemName should be "Unknown" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = 'grahameg@gmail.com', 'Username should be "grahameg@gmail.com", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userBearerJWT, 'UserEvidence should be "'+CODES_UserIdEvidence[userBearerJWT]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemUnknown, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemUnknown]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleJson; var res : TFhirResource; begin FStore.reset; res := FClientJson.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'Unknown', 'SystemName should be "Unknown" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemUnknown, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemUnknown]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleOWin; var res : TFhirResource; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := ''; FClientSSL.certPWord := ''; FClientSSL.authoriseByOWin(FClientSSL.url+'/'+OWIN_TOKEN_PATH, 'test', 'test'); res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'test', 'SystemName should be "test" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromOWin, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromOWin]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleSmartOnFhir; var res : TFhirResource; tester : TSmartOnFhirTestingLogin; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := ''; FClientSSL.certPWord := ''; tester := TSmartOnFhirTestingLogin.create; try tester.server.fhirEndPoint := FServer.AuthServer.EndPoint; tester.server.authorizeEndpoint := 'https://'+FIni.readString(voMaybeVersioned, 'web', 'host', '')+':'+FIni.readString(voMaybeVersioned, 'web', 'https', '')+FIni.readString(voMaybeVersioned, 'web', 'auth-path', '')+'/auth'; tester.server.tokenEndPoint := 'https://'+FIni.readString(voMaybeVersioned, 'web', 'host', '')+':'+FIni.readString(voMaybeVersioned, 'web', 'https', '')+FIni.readString(voMaybeVersioned, 'web', 'auth-path', '')+'/token'; tester.scopes := 'openid profile user/*.*'; tester.server.clientid := 'web'; tester.server.redirectport := 961; tester.server.clientsecret := 'this-password-is-never-used'; tester.username := 'test'; tester.password := 'test'; tester.login; FClientSSL.SmartToken := tester.token.link; finally tester.Free; end; res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'web', 'SystemName should be "web" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_USER_NAME, 'Username should be "'+TEST_USER_NAME+'", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userLogin, 'UserEvidence should be "'+CODES_UserIdEvidence[userLogin]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemFromOAuth, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemFromOAuth]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleSSL; var res : TFhirResource; begin FStore.reset; FServer.Stop; FServer.ServeMissingCertificate := true; FServer.CertificateIdList.clear; FServer.Start(true); FClientSSL.smartToken := nil; FClientSSL.certFile := ''; FClientSSL.certPWord := ''; try res := FClientSSL.readResource(frtPatient, 'example'); try Assert.IsFalse(true, 'should not be abe to read without authorization, but got a '+res.className); finally res.free; end; except on e:EFHIRClientException do Assert.isTrue(e.issue.hasIssueList and (e.issue.issueList[0].code = IssueTypeLogin), 'Isseue type is wrong'); on e:exception do Assert.isTrue(false, e.ClassName+'; '+ e.Message); end; Assert.IsTrue(FStore.FLastReadSystem = '', 'SystemName should be "" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = '', 'Username should be "", not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userNoInformation, 'UserEvidence should be "'+CODES_UserIdEvidence[userNoInformation]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemNoInformation, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemNoInformation]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestPatientExampleXml; var res : TFhirResource; begin FStore.reset; res := FClientXml.readResource(frtPatient, 'example'); try Assert.IsNotNull(res, 'no resource returned'); Assert.isTrue(res is TFHIRPatient, 'Resource should be Patient, not '+res.className); Assert.IsTrue(res.id = 'example'); finally res.Free; end; Assert.IsTrue(FStore.FLastReadSystem = 'Unknown', 'SystemName should be "Unknown" not "'+FStore.FLastReadSystem+'"'); Assert.IsTrue(FStore.FLastReadUser = TEST_ANON_USER_NAME, 'Username should be "'+TEST_ANON_USER_NAME+'" not "'+FStore.FLastReadUser+'"'); Assert.IsTrue(FStore.FLastUserEvidence = userAnonymous, 'UserEvidence should be "'+CODES_UserIdEvidence[userAnonymous]+'" not "'+CODES_UserIdEvidence[FStore.FLastUserEvidence]+'"'); Assert.IsTrue(FStore.FLastSystemEvidence = systemUnknown, 'SystemEvidence should be "'+CODES_SystemIdEvidence[systemUnknown]+'" not "'+CODES_SystemIdEvidence[FStore.FLastSystemEvidence]+'"'); end; procedure TRestFulServerTests.TestSSL; var http : TIdHTTP; resp : TBytesStream; ssl : TIdSSLIOHandlerSocketOpenSSL; begin http := TIdHTTP.Create(nil); Try ssl := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); Try http.IOHandler := ssl; ssl.SSLOptions.Mode := sslmClient; ssl.SSLOptions.Method := sslvTLSv1_2; http.Request.Accept := 'application/fhir+xml'; resp := TBytesStream.create; try http.Get(FServer.ClientAddress(true)+'/metadata', resp); resp.position := 0; Assert.isTrue(http.ResponseCode = 200, 'response code <> 200'); Assert.isTrue(http.Response.ContentType = 'application/fhir+xml', 'response content type <> application/fhir+xml');; finally resp.free; end; finally ssl.free; end; finally http.free; end; end; procedure TRestFulServerTests.TestLowLevelJson; var http : TIdHTTP; resp : TBytesStream; begin http := TIdHTTP.Create(nil); Try // ssl := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); // Try // http.IOHandler := ssl; // ssl.SSLOptions.Mode := sslmClient; // ssl.SSLOptions.Method := sslvTLSv1_2; // finally // ssl.free; // end; http.Request.Accept := 'application/fhir+json'; resp := TBytesStream.create; try http.Get(FServer.ClientAddress(false)+'/metadata', resp); resp.position := 0; Assert.isTrue(http.ResponseCode = 200, 'response code <> 200'); Assert.isTrue(http.Response.ContentType = 'application/fhir+json', 'response content type <> application/fhir+json');; finally resp.free; end; finally http.free; end; end; { TTestOAuthLogin } function TTestOAuthLogin.Link: TTestOAuthLogin; begin result := TTestOAuthLogin(inherited Link); end; initialization TDUnitX.RegisterTestFixture(TRestFulServerTests); end.
unit Server.Models.Ativo.Start; interface uses Server.Models.Cadastros.Resultados, Generics.Collections, Server.Models.Cadastros.FaseContato, Server.Models.Cadastros.ConfigMail, Server.Models.Cadastros.Operadores, Server.Models.Cadastros.MotivosPausa, Server.Models.Cadastros.FoneAreas, Server.Models.Cadastros.Grupos, Server.Models.Cadastros.Midias, Server.Models.Cadastros.Segmentos, Server.Models.Cadastros.Cargos; type TAtivoStart = class private fResultados: TObjectList<TResultados>; fFaseContato: TObjectList<TFaseContato>; fConfigMail: TObjectList<TConfigMail>; fOperadores: TObjectList<TOperadores>; fMotivosPausa: TObjectList<TMotivosPausa>; fFoneAreas: TObjectList<TFoneAreas>; fSegmentos: TObjectList<TSegmentos>; fGrupos: TObjectList<TGrupos>; fMidias: TObjectList<TMidias>; fCargos: TObjectList<TCargos>; public property Resultados: TObjectList<TResultados> read fResultados write fResultados; property FaseContato: TObjectList<TFaseContato> read fFaseContato write fFaseContato; property ConfigMail: TObjectList<TConfigMail> read fConfigMail write fConfigMail; property Operadores: TObjectList<TOperadores> read fOperadores write fOperadores; property MotivosPausa: TObjectList<TMotivosPausa> read fMotivosPausa write fMotivosPausa; property FoneAreas: TObjectList<TFoneAreas> read fFoneAreas write fFoneAreas; property Grupos: TObjectList<TGrupos> read fGrupos write fGrupos; property Midias: TObjectList<TMidias> read fMidias write fMidias; property Segmentos: TObjectList<TSegmentos> read fSegmentos write fSegmentos; property Cargos: TObjectList<TCargos> read fCargos write fCargos; constructor Create; destructor destroy; override; end; implementation { TAtivoStart } constructor TAtivoStart.Create; begin Resultados := TObjectList<TResultados>.Create; FaseContato := TObjectList<TFaseContato>.Create; ConfigMail := TObjectList<TConfigMail>.Create; Operadores := TObjectList<TOperadores>.Create; MotivosPausa := TObjectList<TMotivosPausa>.Create; FoneAreas := TObjectList<TFoneAreas>.Create; Grupos := TObjectList<TGrupos>.Create; Midias := TObjectList<TMidias>.Create; Segmentos := TObjectList<TSegmentos>.Create; Cargos := TObjectList<TCargos>.Create; end; destructor TAtivoStart.destroy; begin Resultados.Free; FaseContato.Free; ConfigMail.Free; Operadores.Free; MotivosPausa.Free; FoneAreas.Free; Grupos.Free; Midias.Free; Segmentos.Free; Cargos.Free; inherited; end; end.
unit Unit2; interface uses Graphics; Var ColBack: TColor; Type Tviz=class(TObject) x,y,r: integer; kr,kv,pe: Tcolor; Canvas: Tcanvas; Procedure Ris; virtual; abstract; Procedure Show; Procedure Hide; Procedure MoveT(x0,y0: integer); Procedure Draw(bl: boolean); end; Tkrug=class(TViz) x1,y1,x2,y2: integer; Constructor Create(x0,y0,r0:integer; Canvas0:TCanvas); Procedure Ris; override; end; implementation Procedure Tviz.Draw; begin with Canvas do begin if bl then begin kr:=clRed; kv:=clGreen; pe:=clBlack; end else begin kr:=ColBack; kv:=ColBack; pe:=ColBack; end; Ris; end; end; Procedure Tviz.Show; begin Draw(True); end; Procedure Tviz.Hide; begin Draw(False); end; Constructor Tkrug.Create; begin x:=x0; y:=y0; r:=r0; Canvas:=Canvas0; end; Procedure tkrug.Ris; begin x1:=x-r; y1:=y-r; x2:=x+r; y2:=y+r; Canvas.Pen.Color:=pe; Canvas.Brush.Color:=kv; Canvas.Rectangle(x1,y1,x2,y2); Canvas.Brush.Color:=kr; Canvas.Ellipse(x1,y1,x2,y2); end; Procedure Tviz.MoveT; begin hide; x:=x+x0; y:=y+y0; show; end; end.
unit Polynom; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/Utils // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Uses Types,ArrayBld; Type TPolynomial = record private FDegree: Integer; FCoefs: TDoubleDynArray; Procedure Allocate; overload; Procedure Allocate(Const MaxDegree: Integer); overload; Procedure SetDegree(MaxDegree: Integer); Function GetCoefs(Power: Integer): Float64; Function GetValue(x: Float64): Float64; inline; public Class Operator Implicit(const Constant: Float64): TPolynomial; Class Operator Implicit(const Coefs: array of Float64): TPolynomial; Class Operator Equal(a: TPolynomial; b: TPolynomial): Boolean; Class Operator Add(a: Float64; b: TPolynomial): TPolynomial; Class Operator Add(a: TPolynomial; b: TPolynomial): TPolynomial; Class Operator Multiply(a: Float64; b: TPolynomial): TPolynomial; Class Operator Multiply(a: TPolynomial; b: TPolynomial): TPolynomial; public Constructor Create(const Constant: Float64); overload; Constructor Create(const Coefs: array of Float64); overload; Function Null: Boolean; Procedure Differentiate; Function Derivative: TPolynomial; Procedure AntiDifferentiate(Const Constant: Float64 = 0); Function Primitive(Const Constant: Float64 = 0): TPolynomial; Function Integrate(Const a,b: Float64): Float64; public Property Degree: Integer read FDegree; Property Coefs[Power: Integer]: Float64 read GetCoefs; Property Value[x: Float64]: Float64 read GetValue; default; end; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Class Operator TPolynomial.Implicit(const Constant: Float64): TPolynomial; begin Result.FDegree := 0; Result.Allocate; Result.FCoefs[0] := Constant; end; Class Operator TPolynomial.Implicit(Const Coefs: array of Float64): TPolynomial; begin Result.FCoefs := TFloatArrayBuilder.Create(Coefs); Result.SetDegree(Length(Coefs)-1); end; Class Operator TPolynomial.Equal(a: TPolynomial; b: TPolynomial): Boolean; begin if a.FDegree = b.FDegree then begin Result := true; for var Coef := 0 to a.FDegree do if a.FCoefs[Coef] <> b.FCoefs[Coef] then begin Result := false; Break; end; end else Result := false; end; Class Operator TPolynomial.Add(a: Float64; b: TPolynomial): TPolynomial; begin Result.FDegree := b.FDegree; Result.Allocate; for var Coef := 0 to b.FDegree do Result.FCoefs[Coef] := b.FCoefs[Coef]; Result.FCoefs[0] := Result.FCoefs[0] + a; end; Class Operator TPolynomial.Add(a: TPolynomial; b: TPolynomial): TPolynomial; Var Coef: Integer; begin if a.FDegree = b.FDegree then begin Result.Allocate(a.FDegree); for Coef := 0 to a.FDegree do Result.FCoefs[Coef] := a.FCoefs[Coef] + b.FCoefs[Coef]; Result.SetDegree(a.FDegree); end else if a.FDegree < b.FDegree then begin Result.FDegree := b.FDegree; Result.Allocate; for Coef := 0 to a.FDegree do Result.FCoefs[Coef] := a.FCoefs[Coef] + b.FCoefs[Coef]; for Coef := a.FDegree+1 to b.FDegree do Result.FCoefs[Coef] := b.FCoefs[Coef]; end else begin Result.FDegree := a.FDegree; Result.Allocate; for Coef := 0 to b.FDegree do Result.FCoefs[Coef] := a.FCoefs[Coef] + b.FCoefs[Coef]; for Coef := b.FDegree+1 to a.FDegree do Result.FCoefs[Coef] := a.FCoefs[Coef]; end; end; Class Operator TPolynomial.Multiply(a: Float64; b: TPolynomial): TPolynomial; begin if a = 0 then Result := 0 else for var Coef := 0 to b.FDegree do Result.FCoefs[Coef] := a*b.FCoefs[Coef]; end; Class Operator TPolynomial.Multiply(a: TPolynomial; b: TPolynomial): TPolynomial; begin if a.Null or b.Null then Result := 0 else begin Result.FDegree := a.FDegree+b.FDegree; Result.Allocate; for var aCoef := 0 to a.FDegree do for var bCoef := 0 to b.FDegree do Result.FCoefs[aCoef+bCoef] := Result.FCoefs[aCoef+bCoef] + a.FCoefs[aCoef]*b.FCoefs[bCoef]; end; end; Constructor TPolynomial.Create(const Constant: Float64); begin FDegree := 0; Allocate; FCoefs[0] := Constant; end; Constructor TPolynomial.Create(const Coefs: array of Float64); begin FCoefs := TFloatArrayBuilder.Create(Coefs); SetDegree(Length(Coefs)-1); end; Procedure TPolynomial.Allocate; begin FCoefs := nil; SetLength(FCoefs,FDegree+8); end; Procedure TPolynomial.Allocate(Const MaxDegree: Integer); begin SetLength(FCoefs,MaxDegree+8); end; Procedure TPolynomial.SetDegree(MaxDegree: Integer); begin FDegree := 0; for var Power := MaxDegree downto 0 do if FCoefs[Power] <> 0 then begin FDegree := Power; Break; end; end; Function TPolynomial.GetCoefs(Power: Integer): Float64; begin Result := FCoefs[Power]; end; Function TPolynomial.GetValue(x: Float64): Float64; begin Result := FCoefs[FDegree]; for var Power := FDegree-1 downto 0 do Result := x*Result + FCoefs[Power]; end; Function TPolynomial.Null: Boolean; begin Result := (FDegree = 0) and (FCoefs[0] = 0); end; Procedure TPolynomial.Differentiate; begin if FDegree = 0 then FCoefs[0] := 0 else begin FDegree := FDegree-1; for var Coef := 0 to FDegree do FCoefs[Coef] := (Coef+1)*FCoefs[Coef+1] end; end; Function TPolynomial.Derivative: TPolynomial; begin if FDegree = 0 then Result := 0 else begin Result.FDegree := FDegree-1; Result.Allocate; for var Coef := 0 to FDegree-1 do Result.FCoefs[Coef] := (Coef+1)*FCoefs[Coef+1] end; end; Procedure TPolynomial.AntiDifferentiate(Const Constant: Float64 = 0); begin FDegree := FDegree+1; if Length(FCoefs) <= FDegree then SetLength(FCoefs,FDegree+8); for var Coef := FDegree downto 1 do FCoefs[Coef] := FCoefs[Coef-1]/Coef; FCoefs[0] := Constant; end; Function TPolynomial.Primitive(Const Constant: Float64 = 0): TPolynomial; begin if Null then Result := Constant else begin Result.FDegree := FDegree+1; Result.Allocate; for var Coef := FDegree+1 downto 1 do Result.FCoefs[Coef] := FCoefs[Coef-1]/Coef; Result.FCoefs[0] := Constant; end; end; Function TPolynomial.Integrate(Const a,b: Float64): Float64; begin var Coef := FCoefs[FDegree]/(FDegree+1); var Primitive_a := a*Coef; var Primitive_b := b*Coef; for var Power := FDegree-1 downto 0 do begin Coef := FCoefs[Power]/(Power+1); Primitive_a := a*(Primitive_a + Coef); Primitive_b := b*(Primitive_b + Coef); end; Result := Primitive_b - Primitive_a; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.metadata.postgresql; interface uses SysUtils, Variants, DB, Generics.Collections, dbcbr.metadata.register, dbcbr.metadata.extract, dbcbr.database.mapping, dbebr.factory.interfaces; type TCatalogMetadataPostgreSQL = class(TCatalogMetadataAbstract) protected function GetSelectTables: string; override; function GetSelectTableColumns(ATableName: string): string; override; function GetSelectPrimaryKey(ATableName: string): string; override; function GetSelectPrimaryKeyColumns(APrimaryKeyName: string): string; override; function GetSelectForeignKey(ATableName: string): string; override; function GetSelectForeignKeyColumns(AForeignKeyName: string): string; overload; function GetSelectIndexe(ATableName: string): string; override; function GetSelectIndexeColumns(AIndexeName: string): string; override; function GetSelectTriggers(ATableName: string): string; override; function GetSelectViews: string; override; function GetSelectChecks(ATableName: string): string; override; function GetSelectSequences: string; override; function Execute: IDBResultSet; public procedure CreateFieldTypeList; override; procedure GetCatalogs; override; procedure GetSchemas; override; procedure GetTables; override; procedure GetColumns(ATable: TTableMIK); override; procedure GetPrimaryKey(ATable: TTableMIK); override; procedure GetIndexeKeys(ATable: TTableMIK); override; procedure GetForeignKeys(ATable: TTableMIK); override; procedure GetTriggers(ATable: TTableMIK); override; procedure GetChecks(ATable: TTableMIK); override; procedure GetSequences; override; procedure GetProcedures; override; procedure GetFunctions; override; procedure GetViews; override; procedure GetDatabaseMetadata; override; end; implementation { TSchemaExtractSQLite } procedure TCatalogMetadataPostgreSQL.CreateFieldTypeList; begin if Assigned(FFieldType) then begin FFieldType.Clear; FFieldType.Add('VARCHAR', ftString); FFieldType.Add('REAL', ftFloat); FFieldType.Add('DOUBLE PRECISION', ftExtended); FFieldType.Add('CHAR', ftFixedChar); FFieldType.Add('DECIMAL', ftBCD); FFieldType.Add('NUMERIC', ftFloat); FFieldType.Add('TEXT', ftWideMemo); FFieldType.Add('SMALLINT', ftSmallint); FFieldType.Add('INT', ftInteger); FFieldType.Add('BIGINT', ftLargeint); FFieldType.Add('INT4', ftInteger); FFieldType.Add('INT8', ftLargeint); FFieldType.Add('BYTEA', ftBlob); FFieldType.Add('BOOL', ftBoolean); FFieldType.Add('TIMESTAMP', ftTimeStamp); FFieldType.Add('DATE', ftDate); FFieldType.Add('TIME', ftTime); end; end; function TCatalogMetadataPostgreSQL.Execute: IDBResultSet; var LSQLQuery: IDBQuery; begin inherited; LSQLQuery := FConnection.CreateQuery; try LSQLQuery.CommandText := FSQLText; Exit(LSQLQuery.ExecuteQuery); except raise end; end; procedure TCatalogMetadataPostgreSQL.GetDatabaseMetadata; begin inherited; GetCatalogs; end; procedure TCatalogMetadataPostgreSQL.GetCatalogs; begin inherited; FCatalogMetadata.Name := ''; GetSchemas; end; procedure TCatalogMetadataPostgreSQL.GetChecks(ATable: TTableMIK); var LDBResultSet: IDBResultSet; LCheck: TCheckMIK; begin inherited; FSQLText := GetSelectChecks(ATable.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LCheck := TCheckMIK.Create(ATable); LCheck.Name := VarToStr(LDBResultSet.GetFieldValue('name')); LCheck.Description := ''; LCheck.Condition := VarToStr(LDBResultSet.GetFieldValue('condition')); ATable.Checks.Add(UpperCase(LCheck.Name), LCheck); end; end; procedure TCatalogMetadataPostgreSQL.GetSchemas; begin inherited; FCatalogMetadata.Schema := 'public'; GetSequences; GetTables; end; procedure TCatalogMetadataPostgreSQL.GetTables; var LDBResultSet: IDBResultSet; LTable: TTableMIK; begin inherited; FSQLText := GetSelectTables; LDBResultSet := Execute; while LDBResultSet.NotEof do begin LTable := TTableMIK.Create(FCatalogMetadata); LTable.Name := VarToStr(LDBResultSet.GetFieldValue('table_name')); LTable.Description := VarToStr(LDBResultSet.GetFieldValue('table_description')); /// <summary> /// Extrair colunas da tabela /// </summary> GetColumns(LTable); /// <summary> /// Extrair Primary Key da tabela /// </summary> GetPrimaryKey(LTable); /// <summary> /// Extrair Foreign Keys da tabela /// </summary> GetForeignKeys(LTable); /// <summary> /// Extrair Indexes da tabela /// </summary> GetIndexeKeys(LTable); /// <summary> /// Extrair Checks da tabela /// </summary> GetChecks(LTable); /// <summary> /// Adiciona na lista de tabelas extraidas /// </summary> FCatalogMetadata.Tables.Add(UpperCase(LTable.Name), LTable); end; end; procedure TCatalogMetadataPostgreSQL.GetColumns(ATable: TTableMIK); var LDBResultSet: IDBResultSet; LColumn: TColumnMIK; function ExtractDefaultValue(ADefaultValue: Variant): string; begin Result := ''; if ADefaultValue <> Null then Result := ADefaultValue; if Result = '0.000' then Result := '0'; end; function ResolveIntegerNullValue(AValue: Variant): Integer; begin Result := 0; if AValue <> Null then Result := VarAsType(AValue, varInteger); end; begin inherited; FSQLText := GetSelectTableColumns(ATable.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LColumn := TColumnMIK.Create(ATable); LColumn.Name := VarToStr(LDBResultSet.GetFieldValue('column_name')); LColumn.Position := VarAsType(LDBResultSet.GetFieldValue('column_position'), varInteger) -1; LColumn.Size := ResolveIntegerNullValue(LDBResultSet.GetFieldValue('column_size')); LColumn.Precision := ResolveIntegerNullValue(LDBResultSet.GetFieldValue('column_precision')); LColumn.Scale := ResolveIntegerNullValue(LDBResultSet.GetFieldValue('column_scale')); LColumn.NotNull := VarToStr(LDBResultSet.GetFieldValue('column_nullable')) = 'NO'; LColumn.DefaultValue := ExtractDefaultValue(VarToStr(LDBResultSet.GetFieldValue('column_defaultvalue'))); LColumn.Description := VarToStr(LDBResultSet.GetFieldValue('column_description')); LColumn.TypeName := VarToStr(LDBResultSet.GetFieldValue('column_typename')); SetFieldType(LColumn); /// <summary> /// Resolve Field Type /// </summary> GetFieldTypeDefinition(LColumn); ATable.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); end; end; procedure TCatalogMetadataPostgreSQL.GetPrimaryKey(ATable: TTableMIK); var LDBResultSet: IDBResultSet; procedure GetPrimaryKeyColumns(APrimaryKey: TPrimaryKeyMIK); var LDBResultSet: IDBResultSet; LColumn: TColumnMIK; begin FSQLText := GetSelectPrimaryKeyColumns(APrimaryKey.Table.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LColumn := TColumnMIK.Create(ATable); LColumn.Name := VarToStr(LDBResultSet.GetFieldValue('column_name')); LColumn.Position := VarAsType(LDBResultSet.GetFieldValue('column_position'), varInteger) -1; LColumn.NotNull := True; APrimaryKey.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); end; end; begin inherited; FSQLText := GetSelectPrimaryKey(ATable.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin ATable.PrimaryKey.Name := Format('PK_%s', [ATable.Name]); ATable.PrimaryKey.Description := VarToStr(LDBResultSet.GetFieldValue('pk_description')); /// <summary> /// Extrai as columnas da primary key /// </summary> GetPrimaryKeyColumns(ATable.PrimaryKey); end; end; procedure TCatalogMetadataPostgreSQL.GetForeignKeys(ATable: TTableMIK); procedure GetForeignKeyColumns(AForeignKey: TForeignKeyMIK); var LDBResultSet: IDBResultSet; LFromField: TColumnMIK; LToField: TColumnMIK; begin // FSQLText := GetSelectForeignKeyColumns(AForeignKey.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin /// <summary> /// Coluna tabela source /// </summary> LFromField := TColumnMIK.Create(ATable); LFromField.Name := VarToStr(LDBResultSet.GetFieldValue('column_name')); LFromField.Position := VarAsType(LDBResultSet.GetFieldValue('column_position'), varInteger) -1; AForeignKey.FromFields.Add(FormatFloat('000000', LFromField.Position), LFromField); /// <summary> /// Coluna tabela referencia /// </summary> LToField := TColumnMIK.Create(ATable); LToField.Name := VarToStr(LDBResultSet.GetFieldValue('column_reference')); LToField.Position := VarAsType(LDBResultSet.GetFieldValue('column_referenceposition'), varInteger) -1; AForeignKey.ToFields.Add(FormatFloat('000000', LToField.Position), LToField); end; end; var LDBResultSet: IDBResultSet; LForeignKey: TForeignKeyMIK; LFromField: TColumnMIK; LToField: TColumnMIK; begin inherited; FSQLText := GetSelectForeignKey(ATable.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LForeignKey := TForeignKeyMIK.Create(ATable); // LForeignKey.Name := Format('FK_%s_%s', [VarToStr(LDBResultSet.GetFieldValue('table_reference')), // VarToStr(LDBResultSet.GetFieldValue('column_name'))]); LForeignKey.Name := VarToStr(LDBResultSet.GetFieldValue('fk_name')); LForeignKey.FromTable := VarToStr(LDBResultSet.GetFieldValue('table_reference')); // LForeignKey.OnUpdate := GetRuleAction(VarAsType(LDBResultSet.GetFieldValue('fk_updateaction'), varInteger)); // LForeignKey.OnDelete := GetRuleAction(VarAsType(LDBResultSet.GetFieldValue('fk_deleteaction'), varInteger)); LForeignKey.OnUpdate := GetRuleAction(VarToStr(LDBResultSet.GetFieldValue('fk_updateaction'))); LForeignKey.OnDelete := GetRuleAction(VarToStr(LDBResultSet.GetFieldValue('fk_deleteaction'))); LForeignKey.Description := VarToStr(LDBResultSet.GetFieldValue('fk_description')); ATable.ForeignKeys.Add(LForeignKey.Name, LForeignKey); // Coluna tabela master LFromField := TColumnMIK.Create(ATable); LFromField.Name := VarToStr(LDBResultSet.GetFieldValue('column_name')); LForeignKey.FromFields.Add(LFromField.Name, LFromField); // Coluna tabela referencia LToField := TColumnMIK.Create(ATable); LToField.Name := VarToStr(LDBResultSet.GetFieldValue('column_reference')); LForeignKey.ToFields.Add(LToField.Name, LToField); // Gera a lista de campos do foreignkey // GetForeignKeyColumns(LForeignKey); end; end; procedure TCatalogMetadataPostgreSQL.GetFunctions; begin inherited; end; procedure TCatalogMetadataPostgreSQL.GetProcedures; begin inherited; end; procedure TCatalogMetadataPostgreSQL.GetSequences; var LDBResultSet: IDBResultSet; LSequence: TSequenceMIK; begin inherited; FSQLText := GetSelectSequences; LDBResultSet := Execute; while LDBResultSet.NotEof do begin LSequence := TSequenceMIK.Create(FCatalogMetadata); LSequence.Name := VarToStr(LDBResultSet.GetFieldValue('name')); LSequence.Description := VarToStr(LDBResultSet.GetFieldValue('description'));; FCatalogMetadata.Sequences.Add(UpperCase(LSequence.Name), LSequence); end; end; procedure TCatalogMetadataPostgreSQL.GetTriggers(ATable: TTableMIK); var LDBResultSet: IDBResultSet; LTrigger: TTriggerMIK; begin inherited; FSQLText := ''; LDBResultSet := Execute; while LDBResultSet.NotEof do begin LTrigger := TTriggerMIK.Create(ATable); LTrigger.Name := VarToStr(LDBResultSet.GetFieldValue('name')); LTrigger.Description := ''; LTrigger.Script := VarToStr(LDBResultSet.GetFieldValue('sql')); ATable.Triggers.Add(UpperCase(LTrigger.Name), LTrigger); end; end; procedure TCatalogMetadataPostgreSQL.GetIndexeKeys(ATable: TTableMIK); var LDBResultSet: IDBResultSet; LIndexeKey: TIndexeKeyMIK; procedure GetIndexeKeyColumns(AIndexeKey: TIndexeKeyMIK); var LDBResultSet: IDBResultSet; LColumn: TColumnMIK; iColumn: Integer; begin FSQLText := GetSelectIndexeColumns(AIndexeKey.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LColumn := TColumnMIK.Create(ATable); LColumn.Name := VarToStr(LDBResultSet.GetFieldValue('column_name')); LColumn.Position := LColumn.Position + 1; // VarAsType(LDBResultSet.GetFieldValue('column_position'), varInteger); AIndexeKey.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); end; end; begin inherited; FSQLText := GetSelectIndexe(ATable.Name); LDBResultSet := Execute; while LDBResultSet.NotEof do begin LIndexeKey := TIndexeKeyMIK.Create(ATable); LIndexeKey.Name := VarToStr(LDBResultSet.GetFieldValue('indexe_name')); LIndexeKey.Unique := VarAsType(LDBResultSet.GetFieldValue('indexe_unique'), varBoolean); ATable.IndexeKeys.Add(UpperCase(LIndexeKey.Name), LIndexeKey); /// <summary> /// Gera a lista de campos do indexe /// </summary> GetIndexeKeyColumns(LIndexeKey); end; end; procedure TCatalogMetadataPostgreSQL.GetViews; var LDBResultSet: IDBResultSet; LView: TViewMIK; begin inherited; FSQLText := GetSelectViews; LDBResultSet := Execute; while LDBResultSet.NotEof do begin LView := TViewMIK.Create(FCatalogMetadata); LView.Name := VarToStr(LDBResultSet.GetFieldValue('view_name')); LView.Script := VarToStr(LDBResultSet.GetFieldValue('view_script')); LView.Description := VarToStr(LDBResultSet.GetFieldValue('view_description')); FCatalogMetadata.Views.Add(UpperCase(LView.Name), LView); end; end; function TCatalogMetadataPostgreSQL.GetSelectPrimaryKey(ATableName: string): string; begin Result := ' select rc.constraint_name as pk_name, ' + ' '''' as pk_description ' + ' from information_schema.table_constraints rc ' + ' where rc.constraint_type = ''PRIMARY KEY'' ' + ' and rc.table_schema not in (''pg_catalog'', ''information_schema'') ' + ' and rc.table_name in (' + QuotedStr(ATableName) + ') ' + ' order by rc.constraint_name '; end; function TCatalogMetadataPostgreSQL.GetSelectPrimaryKeyColumns(APrimaryKeyName: string): string; begin Result := ' select c.column_name as column_name, ' + ' c.ordinal_position as column_position ' + ' from information_schema.key_column_usage c ' + ' inner join information_schema.table_constraints t on c.table_name = t.table_name ' + ' and t.constraint_name = c.constraint_name ' + ' and t.constraint_type = ''PRIMARY KEY'' ' + ' where t.table_name = ' + QuotedStr(APrimaryKeyName) + ' and c.table_schema not in (''pg_catalog'', ''information_schema'') ' + ' order by t.table_name, ' + ' t.constraint_name, ' + ' c.ordinal_position '; end; function TCatalogMetadataPostgreSQL.GetSelectSequences: string; begin Result := ' select relname as name, ' + ' '''' as description ' + ' from pg_class ' + ' where relkind in (' + QuotedStr('S') + ')'; end; function TCatalogMetadataPostgreSQL.GetSelectTableColumns(ATableName: string): string; begin Result := ' select column_name as column_name, ' + ' ordinal_position as column_position, ' + ' character_maximum_length as column_size, ' + ' numeric_precision as column_precision, ' + ' numeric_scale as column_scale, ' + ' collation_name as column_collation, ' + ' is_nullable as column_nullable, ' + ' column_default as column_defaultvalue, ' + ' '''' as column_description, ' + ' upper(udt_name) as column_typename, ' + ' character_set_name as column_charset ' + ' from information_schema.columns ' + ' where table_name in (' + QuotedStr(ATableName) + ') ' + ' order by ordinal_position' ; end; function TCatalogMetadataPostgreSQL.GetSelectTables: string; begin Result := ' select table_name as table_name, ' + ' '''' as table_description ' + ' from information_schema.tables ' + ' where table_type = ''BASE TABLE'' ' + ' and table_schema not in (''pg_catalog'', ''information_schema'') ' + ' order by table_name'; end; function TCatalogMetadataPostgreSQL.GetSelectTriggers(ATableName: string): string; begin Result := ''; end; function TCatalogMetadataPostgreSQL.GetSelectForeignKey(ATableName: string): string; begin Result := ' select kc.constraint_name as fk_name, ' + ' kc.column_name as column_name, ' + ' kc.ordinal_position as column_position, ' + ' ku.table_name as table_reference, ' + ' ku.column_name as column_reference, ' + ' kc.position_in_unique_constraint as column_referenceposition, ' + ' rc.update_rule as fk_updateaction, ' + ' rc.delete_rule as fk_deleteaction, ' + ' '''' as fk_description ' + ' from information_schema.key_column_usage kc ' + ' inner join information_schema.referential_constraints rc on kc.constraint_name = rc.constraint_name ' + ' inner join information_schema.key_column_usage ku on rc.unique_constraint_name = ku.constraint_name ' + ' where kc.table_name in(' + QuotedStr(ATableName) + ') ' + ' and kc.table_schema not in (''pg_catalog'', ''information_schema'') ' + ' order by kc.constraint_name, kc.position_in_unique_constraint'; end; function TCatalogMetadataPostgreSQL.GetSelectForeignKeyColumns(AForeignKeyName: string): string; begin Result := 'Falta Implementar'; end; function TCatalogMetadataPostgreSQL.GetSelectChecks(ATableName: string): string; begin Result := ' select conname as name, ' + ' pg_get_constraintdef(c.oid) as condition ' + ' from pg_constraint c ' + ' inner join pg_namespace n on n.oid = c.connamespace ' + ' where conrelid::regclass = ' + QuotedStr(ATableName) + '::regclass' + ' and contype in (' + QuotedStr('c') + ')'; end; function TCatalogMetadataPostgreSQL.GetSelectViews: string; begin Result := ' select v.table_name as view_name, ' + ' v.view_definition as view_script, ' + ' '''' as view_description ' + ' from information_schema.views v ' + ' where table_schema not in (''pg_catalog'', ''information_schema'') ' + ' and table_name !~ ''^pg_'' '; end; function TCatalogMetadataPostgreSQL.GetSelectIndexe(ATableName: string): string; begin Result := ' select c.relname as indexe_name, ' + ' b.indisunique as indexe_unique, ' + ' '''' as indexe_description ' + ' from pg_class as a ' + ' join pg_index as b on (a.oid = b.indrelid) ' + ' join pg_class as c on (c.oid = b.indexrelid) ' + ' where a.relname in(' + QuotedStr(ATableName) + ') ' + ' and b.indisprimary != ''t'' ' + ' order by c.relname'; end; function TCatalogMetadataPostgreSQL.GetSelectIndexeColumns(AIndexeName: string): string; begin Result := ' select a.attname as column_name, ' + ' a.attnum as column_position, ' + ' '''' as column_description, ' + ' cast(c.indkey as varchar(20)) as column_ordem ' + ' from pg_index c ' + ' left join pg_class t on c.indrelid = t.oid ' + ' left join pg_class i on c.indexrelid = i.oid ' + ' left join pg_attribute a on a.attrelid = t.oid and a.attnum = any(indkey) ' + ' where i.relname in(' + QuotedStr(AIndexeName) + ') ' + ' order by i.relname, a.attnum'; end; initialization TMetadataRegister.GetInstance.RegisterMetadata(dnPostgreSQL, TCatalogMetadataPostgreSQL.Create); end.
unit ClientDocSqlManager; interface uses SysUtils, Classes, rtcFunction, rtcDataCli, rtcCliModule, rtcInfo, rtcConn, rtcHttpCli, rtcLog, rtcDB, DB, MemTableDataEh, MemTableEh, variants, DataDriverEh, vkvariable, Dialogs, System.Generics.Collections, System.Contnrs; type // TOnFillFieldNameList = procedure(Sender:TObject); TAdditionalSqlManager = class private FTableName: String; FFieldList: TStringList; FObjectList: TObjectList; public constructor Create; destructor Destroy; override; property TableName: String read FTableName write FTableName; property FieldList: TStringList read FFieldList; property ObjectList: TObjectList read FObjectList; end; TClientDocSQLManager = class(TObject) private FTableName: String; FKeyFields: String; FKeyFieldsList: TStringList; FGenId: String; FSelectSQL: TStringList; FParams: TParams; // FUpdateSQL: TStringList; // FInsertSQL: TStringList; // FDeleteSQL: TStringList; // FLockSQL: TStringList; FDocVariableList: TVkVariableCollection; FFieldNameList: TStringList; // FOnFillFieldNameList: TNotifyEvent; // FAdditionalList: TList<TAdditionalSqlManager>; procedure SetTableName(const Value: String); function GetKeyFieldsList: TStringList; function GetKeyFields: String; protected // procedure FillFieldNameList; virtual; public constructor Create; destructor Destroy; override; procedure CalcVariablesOnDs(DataSet: TDataSet; AVarList: TVkVariableCollection); function GetKeyValues(ADataSet: TDataSet): Variant; overload; function GetKeyValues(AVarList: TVkVariableCollection): Variant; overload; // procedure GenerateDinamicSQLInsert; // procedure GenerateDinamicSQLUpdate(var bChanged: Boolean); // procedure GenerateDinamicSQLDelete; // procedure GenerateDinamicSQLLock; // function GenerateSQLInsert(AParams: TVkVariableCollection):String; // function GenerateSQLUpdate(AParams: TVkVariableCollection):String; // function GenerateSQLDelete(AParams: TVkVariableCollection):String; // function GetReturningOnKeyFields: String; // function GetWhereOnKeyFields: String; procedure InitCommonParamsDT(const ATableName: String = ''; const AGenId: String = ''); procedure SaveVariablesInDataSet(ADataSet: TDataSet; AVarList: TVkVariableCollection); procedure UpdateVariablesOnDeltaDs(DataSet: TDataSet; AVarList: TVkVariableCollection); // function IndexOfInAdditionalFields(const AName: String): Integer; // property AdditionalList: TList<TAdditionalSqlManager> read FAdditionalList; property DocVariableList: TVkVariableCollection read FDocVariableList; property TableName: String read FTableName write SetTableName; // property GenId: String read FGenId write FGenId; property SelectSQL: TStringList read FSelectSQL; // property UpdateSQL: TStringList read FUpdateSQL; // property InsertSQL: TStringList read FInsertSQL; // property DeleteSQL: TStringList read FDeleteSQL; // property LockSQL: TStringList read FLockSQL; property KeyFields: String read GetKeyFields; property KeyFieldsList: TStringList read GetKeyFieldsList; // property OnFillFieldNameList: TNotifyEvent read FOnFillFieldNameList // write FOnFillFieldNameList; property FieldNameList: TStringList read FFieldNameList; property Params: TParams read FParams; end; implementation { TDocSqlManager } procedure TClientDocSQLManager.CalcVariablesOnDs(DataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; ind: Integer; begin with DataSet do begin if True then for i := 0 to FieldCount - 1 do begin ind := AVarList.IndexOf(Fields[i].FieldName); if ind > -1 then begin case Fields[i].DataType of ftFMTBcd: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsFloat; ftBcd: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsLargeInt; ftBlob: AVarList[Fields[i].FieldName].InitValue := Fields[i].AsString; else try AVarList.Items[ind].InitValue := Fields[i].Value; XLog(Fields[i].FieldName + ' = ' + Fields[i].AsString); except XLog(Fields[i].FieldName + ' = ' + Fields[i].AsString); ShowMessage((' error in InitVariable i = ' + IntToStr(i))); Raise; end; end; end; end; end; end; constructor TClientDocSQLManager.Create; begin FSelectSQL := TStringList.Create; //FUpdateSQL := TStringList.Create; //FInsertSQL := TStringList.Create; //FDeleteSQL := TStringList.Create; //FLockSQL := TStringList.Create; FFieldNameList := TStringList.Create; FDocVariableList := TVkVariableCollection.Create(nil); FKeyFieldsList := TStringList.Create; //FAdditionalList := TList<TAdditionalSqlManager>.Create; FParams := TParams.Create(nil); end; destructor TClientDocSQLManager.Destroy; begin FSelectSQL.Free; //FUpdateSQL.Free; //FInsertSQL.Free; //FDeleteSQL.Free; //FLockSQL.Free; FDocVariableList.Free; FKeyFieldsList.Free; FFieldNameList.Free; //FAdditionalList.Free; FParams.Free; inherited; end; {procedure TClientDocSQLManager.FillFieldNameList; begin if Assigned(FOnFillFieldNameList) then FOnFillFieldNameList(Self); // else // raise Exception.Create('Error - OnFillFieldNameList - is not defined'); end;} {procedure TClientDocSQLManager.GenerateDinamicSQLDelete; begin FDeleteSQL.Clear; FDeleteSQL.Add(' DELETE FROM ' + FTableName); FDeleteSQL.Add(GetWhereOnKeyFields); end; procedure TClientDocSQLManager.GenerateDinamicSQLInsert; var i: Integer; bFirst: Boolean; begin with FInsertSQL do begin Clear; Add(' INSERT INTO ' + FTableName); Add('('); bFirst := true; for i := 0 to FDocVariableList.Count - 1 do begin if (FFieldNameList.IndexOf(FDocVariableList.Items[i].Name) > -1) and (IndexOfInAdditionalFields(FDocVariableList.Items[i].Name) = -1) then begin if not bFirst then Add(','); Add(FDocVariableList.Items[i].Name); bFirst := False; // if i<FDocVariableList.Count-1 then // Add(','); end; end; Add(')'); Add(' VALUES ('); bFirst := true; for i := 0 to FDocVariableList.Count - 1 do begin if (FFieldNameList.IndexOf(FDocVariableList.Items[i].Name) > -1) and (IndexOfInAdditionalFields(FDocVariableList.Items[i].Name) = -1) then begin if not bFirst then Add(','); Add(':' + FDocVariableList.Items[i].Name); bFirst := False; end; end; Add(')'); Add(GetReturningOnKeyFields); end; end; procedure TClientDocSQLManager.GenerateDinamicSQLLock; begin with FLockSQL do begin Clear; Add(' SELECT * FROM ' + FTableName); Add(GetWhereOnKeyFields); Add(' WITH LOCK '); end; end; procedure TClientDocSQLManager.GenerateDinamicSQLUpdate; var i: Integer; _UpdateList: TStringList; bFirst: Boolean; begin _UpdateList := TStringList.Create; bFirst := true; try FDocVariableList.GetChangedList(_UpdateList); bChanged := False; // _UpdateList.Count > 0; with FUpdateSQL do begin Clear; Add(' UPDATE ' + FTableName); Add(' SET'); for i := 0 to _UpdateList.Count - 1 do begin if (FFieldNameList.IndexOf(_UpdateList[i]) > -1) and (IndexOfInAdditionalFields(_UpdateList[i]) = -1) then begin if not bFirst then Add(',') else begin bFirst := False; bChanged := true; end; if FDocVariableList.VarByName(_UpdateList[i]).IsDelta then Add(_UpdateList[i] + ' = ' + _UpdateList[i] + '+:' + _UpdateList[i]) else Add(_UpdateList[i] + ' = :' + _UpdateList[i]); end; end; Add(GetWhereOnKeyFields); end; finally FreeandNil(_UpdateList); end; end; function TClientDocSQLManager.GenerateSQLDelete(AParams: TVkVariableCollection): String; begin GenerateDinamicSQLLock; Result := FDeleteSQL.Text; end; function TClientDocSQLManager.GenerateSQLInsert(AParams: TVkVariableCollection):String; var bFirst: Boolean; i: Integer; begin with FInsertSQL do begin Clear; Add(' INSERT INTO ' + FTableName); Add('('); bFirst := true; for i := 0 to AParams.Count - 1 do begin if (FFieldNameList.IndexOf(AParams.Items[i].Name) > -1) and (IndexOfInAdditionalFields(AParams.Items[i].Name) = -1) then begin if not bFirst then Add(','); Add(AParams.Items[i].Name); bFirst := False; end; end; Add(')'); Add(' VALUES ('); bFirst := true; for i := 0 to AParams.Count - 1 do begin if (FFieldNameList.IndexOf(AParams.Items[i].Name) > -1) and (IndexOfInAdditionalFields(AParams.Items[i].Name) = -1) then begin if not bFirst then Add(','); Add(':' + AParams.Items[i].Name); bFirst := False; end; end; Add(')'); end; Result := FInsertSQL.Text; end; function TClientDocSQLManager.GenerateSQLUpdate(AParams: TVkVariableCollection): String; var i: Integer; _UpdateList: TStringList; bFirst: Boolean; begin _UpdateList := TStringList.Create; bFirst := true; try AParams.GetChangedList(_UpdateList); // bChanged := False; // _UpdateList.Count > 0; with FUpdateSQL do begin Clear; Add(' UPDATE ' + FTableName); Add(' SET'); for i := 0 to _UpdateList.Count - 1 do begin if (FFieldNameList.IndexOf(_UpdateList[i]) > -1) and (IndexOfInAdditionalFields(_UpdateList[i]) = -1) then begin if not bFirst then Add(',') else begin bFirst := False; //bChanged := true; end; if FDocVariableList.VarByName(_UpdateList[i]).IsDelta then Add(_UpdateList[i] + ' = ' + _UpdateList[i] + '+:' + _UpdateList[i]) else Add(_UpdateList[i] + ' = :' + _UpdateList[i]); end; end; Add(GetWhereOnKeyFields); end; finally FreeandNil(_UpdateList); end; end;} function TClientDocSQLManager.GetKeyFields: String; var sb: TStringBuilder; i: Integer; begin sb := TStringBuilder.Create; for i:=0 to FKeyFieldsList.Count-1 do begin sb.Append(FKeyFieldsList[i]); if (i< FKeyFieldsList.Count-1) then sb.Append(';'); end; Result := sb.ToString() end; function TClientDocSQLManager.GetKeyFieldsList: TStringList; begin // FKeyFieldsList.Clear; // FKeyFieldsList.Delimiter := ';'; // FKeyFieldsList.DelimitedText := FKeyFields; Result := FKeyFieldsList; end; function TClientDocSQLManager.GetKeyValues (AVarList: TVkVariableCollection): Variant; var i: Integer; function getVarValue(const name: String):Variant; var v: TVkVariable; begin v := AVarList.VarByName(name); if Assigned(v) then Result := v.Value else raise Exception.Create(Format(' %s is not defined', [name])); end; begin if AVarList.Count = 0 then begin Result := null; Exit; end; if KeyFieldsList.Count = 0 then Result := null else if KeyFieldsList.Count = 1 then Result := getVarValue(KeyFieldsList[0]) else begin Result := VarArrayCreate([0, KeyFieldsList.Count - 1], varvariant); for i := 0 to KeyFieldsList.Count - 1 do begin Result[i] := getVarValue(KeyFieldsList[i]); end; end; end; {function TClientDocSQLManager.GetReturningOnKeyFields: String; var i: Integer; sb: TStringBuilder; begin sb := tStringBuilder.Create; try if KeyFieldsList.Count = 0 then sb.append('') else if KeyFieldsList.Count = 1 then sb.append(' RETURNING ').append( KeyFieldsList[0]).append(' INTO :').Append( KeyFieldsList[0]) else begin Result := ' RETURNING '; for i := 0 to KeyFieldsList.Count - 1 do begin sb.append(KeyFieldsList[i]); if i < KeyFieldsList.Count - 1 then sb.append(', '); end; sb.append(' INTO '); for i := 0 to KeyFieldsList.Count - 1 do begin sb.append(':'+KeyFieldsList[i]); if i < KeyFieldsList.Count - 1 then sb.append(', '); end; end; Result := sb.toString(); finally sb.free; end; end;} function TClientDocSQLManager.GetKeyValues(ADataSet: TDataSet): Variant; var i: Integer; begin if ADataSet.isEmpty then begin Result := null; Exit; end; if KeyFieldsList.Count = 0 then Result := null else if KeyFieldsList.Count = 1 then Result := ADataSet.FieldByName(KeyFieldsList[0]).Value else begin Result := VarArrayCreate([0, KeyFieldsList.Count - 1], varvariant); for i := 0 to KeyFieldsList.Count - 1 do Result[i] := ADataSet.FieldByName(KeyFieldsList[i]).Value; end; end; {function TClientDocSQLManager.GetWhereOnKeyFields: String; var i: Integer; sb: TStringBuilder; begin sb := TStringBuilder.Create; try if KeyFieldsList.Count = 0 then sb.Append('') else if KeyFieldsList.Count = 1 then sb.Append(' WHERE ').Append( KeyFieldsList[0]).Append(' = :').Append( KeyFieldsList[0]) else begin sb.Append(' WHERE '); for i := 0 to KeyFieldsList.Count - 1 do begin sb.Append( KeyFieldsList[i]).Append(' = :').Append(KeyFieldsList[i]); if i < KeyFieldsList.Count - 1 then sb.Append(' AND '); end; end; Result := sb.toString(); finally sb.free; end; end;} {function TClientDocSQLManager.IndexOfInAdditionalFields (const AName: String): Integer; var _Item: TAdditionalSqlManager; begin Result := -1; for _Item in AdditionalList do begin Result := _Item.FieldList.IndexOf(AName); if Result > -1 then Break; end; Result := -1; end;} procedure TClientDocSQLManager.InitCommonParamsDT(const ATableName, AGenId: String); begin if ATableName <> '' then FTableName := UpperCase(ATableName); // if AKeyFields <> '' then // FKeyFields := UpperCase(AKeyFields); if AGenId <> '' then FGenId := UpperCase(AGenId); //FillFieldNameList; { GenerateDinamicSQLInsert; GenerateDinamicSQLUpdate; GenerateDinamicSQLDelete; GenerateDinamicSQLLock; } end; procedure TClientDocSQLManager.SaveVariablesInDataSet(ADataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; _Field: TField; _ReadOnly: Boolean; begin for i := 0 to AVarList.Count - 1 do begin _Field := ADataSet.FindField(AVarList.Items[i].Name); if Assigned(_Field) then begin _ReadOnly := _Field.ReadOnly; try if _ReadOnly then _Field.ReadOnly := False; if AVarList.Items[i].Value = unassigned then _Field.Value := null else _Field.Value := AVarList.Items[i].Value; finally _Field.ReadOnly := _ReadOnly; end; end; end; end; procedure TClientDocSQLManager.SetTableName(const Value: String); begin FTableName := UpperCase(Value); //FillFieldNameList; end; procedure TClientDocSQLManager.UpdateVariablesOnDeltaDs(DataSet: TDataSet; AVarList: TVkVariableCollection); var i: Integer; ind: Integer; begin with DataSet do begin for i := 0 to FieldCount - 1 do begin if Fields[i].NewValue <> unassigned then begin ind := AVarList.IndexOf(Fields[i].FieldName); if ind > -1 then try AVarList.Items[ind].Value := Fields[i].Value; except ShowMessage('Name ' + Fields[i].FieldName + ', Index - ' + IntToStr(ind)); Raise; end; end; end; end; end; { TAdditionalSqlManager } constructor TAdditionalSqlManager.Create; begin FFieldList := TStringList.Create; FObjectList := TObjectList.Create; FObjectList.OwnsObjects := true; end; destructor TAdditionalSqlManager.Destroy; begin FFieldList.Free; FObjectList.Free; inherited; end; end.
unit mp3stream2; interface uses SysUtils, Windows, Classes, MMSystem, msacm, DSoutput, httpstream, main, utils; // BEGIN OF ACM MP3 STUFF // type PMPEGLAYER3WAVEFORMAT = ^TMPEGLAYER3WAVEFORMAT; TMPEGLAYER3WAVEFORMAT = packed record wfx: tWAVEFORMATEX; wID: WORD; fdwFlags: DWORD; nBlockSize: WORD; nFramesPerBlock: WORD; nCodecDelay: WORD; end; const WAVE_FORMAT_MPEG = $50; WAVE_FORMAT_MPEGLAYER3 = $55; ACM_MPEG_LAYER1 = 1; ACM_MPEG_LAYER2 = 2; ACM_MPEG_LAYER3 = 4; ACM_MPEG_STEREO = 1; ACM_MPEG_JOINTSTEREO = 2; ACM_MPEG_DUALCHANNEL = 4; ACM_MPEG_SINGLECHANNEL = 8; ACM_MPEG_ID_MPEG1 = $10; MPEGLAYER3_ID_MPEG = 1; MPEGLAYER3_FLAG_PADDING_ON = 1; MPEGLAYER3_FLAG_PADDING_OFF = 2; // END OF ACM MP3 STUFF // const inBufferlen = BUFFPACKET * 2; outBufferlen = 32 * 1024; // NOT SAFE, BUT ENOUGH type TMP3 = class(TRadioPlayer) private fHandle: HACMSTREAM; fStreamHeader: TACMSTREAMHEADER; inBuffer: array[0..inBufferlen - 1] of Byte; inPos, inFilled: Cardinal; outBuffer: array[0..outBufferlen - 1] of Byte; outPos, outFilled: Cardinal; fStream: THTTPSTREAM; protected function FillinFormat(var inFormat: TMPEGLAYER3WAVEFORMAT): LongBool; procedure updatebuffer(const offset: Cardinal); override; procedure initbuffer; function prebuffer(): LongBool; override; public function GetProgress(): Integer; override; //function GetTrack(): string; override; procedure GetInfo(out Atitle, Aquality: string); override; function Open(const url: string): LongBool; override; constructor Create(); destructor Destroy; override; end; implementation { TMP3 } function TMP3.GetProgress(): Integer; begin Result := fStream.BuffFilled; end; procedure TMP3.GetInfo(out Atitle, Aquality: string); begin fStream.GetMetaInfo(Atitle, Aquality); Aquality := Aquality + 'k mp3'; end; destructor TMP3.Destroy; begin inherited; fStreamHeader.cbSrcLength := inBufferlen; acmStreamUnprepareHeader(fHandle, fStreamHeader, 0); acmStreamClose(fHandle, 0); fStream.Free; end; {function swap32(n: Cardinal): Cardinal; assembler; asm bswap eax; end;} function check(n: LongInt): LongBool; begin Result := False; if (n and $FFE00000) <> $FFE00000 then Exit; if ((n shr 10) and $3) = $3 then Exit; if ((n shr 12) and $F) = $F then Exit; if ((n shr 12) and $F) = $0 then Exit; if (4 - ((n shr 17) and 3)) <> 3 then Exit; // only layer 3, nothing else Result := True end; function TMP3.FillinFormat(var inFormat: TMPEGLAYER3WAVEFORMAT): LongBool; const SamplingFreq: array[0..8] of Integer = (44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000); BitRates: array[0..15] of integer = (0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0); var i: Integer; frame: Cardinal; buf: PByteArray; begin frame := 0; Result := False; while (fStream.BuffFilled > 0) and (not Result) do begin buf := PByteArray(fStream.GetBuffer()); FStream.NextBuffer(); for i := 0 to BUFFPACKET - 1 - 4 do begin //frame := swap32(PDWORD(LongInt(buf) + i)^); frame := PDWORD(LongInt(buf) + i)^; asm bswap esi end; if check(frame) then begin Result := True; Break; end; end; end; if not Result then Exit; // NOT FOUND A VALID FRAME with inFormat do begin with wfx do begin wFormatTag := WAVE_FORMAT_MPEGLAYER3; cbSize := SizeOf(TMPEGLAYER3WAVEFORMAT) - SizeOf(TWAVEFORMATEX); //3 means mono, else it is stereo if (frame shr 6) and 3 = 3 then nChannels := 1 else nChannels := 2; if (frame and (1 shl 20)) <> 0 then begin if (frame and (1 shl 19)) = 0 then nSamplesPerSec := SamplingFreq[(frame shr 10) and 3 + 3] else nSamplesPerSec := SamplingFreq[(frame shr 10) and 3]; end else nSamplesPerSec := SamplingFreq[(frame shr 10) and 3 + 6]; nAvgBytesPerSec := (BitRates[(frame shr 12) and $F] * 1000) shr 3; nBlockAlign := 1; wBitsPerSample := 0; if nSamplesPerSec >= 32000 then nBlockSize := 1152 * nAvgBytesPerSec div nSamplesPerSec else nBlockSize := 576 * nAvgBytesPerSec div nSamplesPerSec; end; wID := MPEGLAYER3_ID_MPEG; nCodecDelay := 0;//$0571; nFramesPerBlock := 1; if ((frame shr 9) and 1) <> 0 then fdwFlags := MPEGLAYER3_FLAG_PADDING_ON else fdwFlags := MPEGLAYER3_FLAG_PADDING_OFF; end; end; procedure TMP3.initbuffer; var inFormat: TMPEGLAYER3WAVEFORMAT; outFormat: TWaveFormatEx; r: Cardinal; begin fStreamHeader.cbSrcLength := inBufferlen; acmStreamUnprepareHeader(fHandle, fStreamHeader, 0); acmStreamClose(fHandle, 0); if not FillinFormat(inFormat) then RaiseError('lol'); with outFormat do begin wFormatTag := WAVE_FORMAT_PCM; nChannels := inFormat.wfx.nChannels; wBitsPerSample := 16; nSamplesPerSec := inFormat.wfx.nSamplesPerSec; nBlockAlign := nChannels * 2; nAvgBytesPerSec := nSamplesPerSec * nBlockAlign; cbSize := 0; end; r := acmStreamOpen(@fHandle, 0, inFormat.wfx, outFormat, nil, 0, 0, 0); if r <> 0 then RaiseError(IntToStr(r)); with fStreamHeader do begin cbStruct := SizeOf(TACMSTREAMHEADER); pbSrc := @inBuffer; cbSrcLength := inBufferlen; pbDst := @outBuffer; cbDstLength := outBufferlen; end; acmStreamPrepareHeader(fHandle, fStreamHeader, 0); if r <> 0 then RaiseError(IntToStr(r)); {acmStreamSize(fHandle,inBufferlen,r, ACM_STREAMSIZEF_SOURCE); Writeln(r);} Fhalfbuffersize := fDS.InitializeBuffer(outFormat.nSamplesPerSec, outFormat.nChannels); end; function TMP3.Open(const url: string): LongBool; begin Result := fStream.open(url); if not Result then begin Terminate; Resume; end; end; function TMP3.prebuffer(): LongBool; begin Result := False; // WAIT TO PREBUFFER! repeat Sleep(64); if Terminated then Exit; until FStream.BuffFilled > BUFFPRE; initbuffer(); Result := True; end; procedure TMP3.updatebuffer(const offset: Cardinal); var dsbuf: PByteArray; r, done, dssize, Decoded: Cardinal; begin DSERROR(fDS.SoundBuffer.Lock(offset, Fhalfbuffersize, @dsbuf, @dssize, nil, nil, 0), 'locking buffer'); r := 0; Decoded := 0; if outFilled <> 0 then begin {if outFilled < dssize then begin} Move(outBuffer[outPos], dsbuf[Decoded], outFilled); Inc(Decoded, outFilled); outPos := 0; outFilled := 0; {end else begin Move(outBuffer[outPos], dsbuf[Decoded], dssize); Inc(Decoded, dssize); Inc(outPos, dssize); Dec(outFilled, dssize); end;} end; //while decoded < dssize do //begin repeat if Terminated then Exit; // Repeat code that fills the DS buffer if (FStream.BuffFilled > 0) then begin if inFilled <> 0 then // buffer have some data, we have to put it at the begin begin Move(inBuffer[inPos], inBuffer, inFilled); inPos := 0; end; //while (inBufferLen - inFilled >= BUFFPACKET) and (fStream.BuffFilled <> 0) do // buffer needs more data if inFilled < BUFFPACKET then begin Move(fStream.GetBuffer()^, inBuffer[inFilled], BUFFPACKET); FStream.NextBuffer(); Inc(inFilled, BUFFPACKET); end; fStreamHeader.cbSrcLength := inFilled; r := acmStreamConvert(fHandle, fStreamHeader, ACM_STREAMCONVERTF_BLOCKALIGN); if r <> 0 then Break; Dec(inFilled, fStreamHeader.cbSrcLengthUsed); done := fStreamHeader.cbDstLengthUsed; if Decoded + done > dssize then done := dssize - Decoded; Move(outBuffer, dsbuf[Decoded], done); Inc(Decoded, done); outFilled := fStreamHeader.cbDstLengthUsed - done; outPos := done; end else begin NotifyForm(NOTIFY_BUFFER, BUFFER_RECOVERING); fDS.Stop; repeat Sleep(64); if Terminated then Exit; until FStream.BuffFilled > BUFFRESTORE; fDS.Play; NotifyForm(NOTIFY_BUFFER, BUFFER_OK); end; //end; until (Decoded >= dssize); if (r = 0) then fDS.SoundBuffer.Unlock(dsbuf, dssize, nil, 0) else begin fDS.Stop; initbuffer(); fDS.Play; end; end; constructor TMP3.Create(); begin inherited; fStream := THTTPSTREAM.Create('audio/mpeg'); end; end.
Program prEscolaridade; uses crt; Type Tperson = record age : integer; schooling : integer; end; TPeopleList = array[1..100] of Tperson; // funcao para identificar nome das escolaridades function nameofSchooling(i : integer) : string; var nameSchooling : string; begin case (i) of 1 : nameSchooling := 'Ensino Basico'; 2 : nameSchooling := 'Ensino Medio'; 3 : nameSchooling := 'Ensino Superior'; 4 : nameSchooling := 'Pos Graduacao'; 5 : nameSchooling := 'Mestrado'; 6 : nameSchooling := 'Doutorado'; end; nameofSchooling := nameSchooling; end; // funcao para obter idade function getAge: integer; var age : integer; begin writeln('IDADE [ou Digite 0 para encerrar e voltar ao MENU]'); write('>> '); readln(age); getAge := age; end; // funcao para obter escolaridade function getSchooling : integer; var schooling : integer; begin repeat writeln('ESCOLARIDADE'); writeln('[1]: ', nameofSchooling(1)); writeln('[2]: ', nameofSchooling(2)); writeln('[3]: ', nameofSchooling(3)); writeln('[4]: ', nameofSchooling(4)); writeln('[5]: ', nameofSchooling(5)); writeln('[6]: ', nameofSchooling(6)); write('>> '); readln(schooling); writeln('-------------------------'); until (schooling >= 1) and (schooling <= 6); getSchooling := schooling; end; // funcao para armazenar as pessoas function getPeople(var i : integer) : TPeopleList; var people : TPeopleList; begin repeat inc(i); writeln('-------------------------'); writeln('PESSOA NUMERO ', i); people[i].age := getAge; if (people[i].age <> 0) then people[i].schooling := getSchooling until (people[i].age = 0); dec(i); getPeople := people; end; // funcao para obter numero de pessoas por escolaridade e limite de idade function getPeoplePerSchooling(age, schooling, n : integer; people : TPeopleList) : integer; var i, number : integer; begin number := 0; for i := 1 to n do begin if (people[i].schooling = schooling) and (people[i].age < age) then begin inc(number); end; end; getPeoplePerSchooling := number; end; // procedimento para imprimir Pessoas por Escolaridade procedure printPeoplePerSchooling (n : integer; people : TPeopleList); var schooling : array[1..6] of integer; i : integer; begin writeln('-------------------------'); for i := 1 to 6 do begin schooling[i] := getPeoplePerSchooling(200, i, n, people); writeln(nameofSchooling(i), ': ', schooling[i], ' pessoas (', schooling[i] / n * 100 :2:2, '%).'); end; end; // funcao para imprimir maior e menor grau de escolaridade procedure printMajorAndMinorNumberSchooling(n : integer; people : TPeopleList); var i, major, minor, i_major, i_minor : integer; begin writeln('-------------------------'); major := getPeoplePerSchooling(200, 1, n, people); minor := getPeoplePerSchooling(200, 1, n, people); for i := 1 to 6 do begin if (getPeoplePerSchooling(200, i, n, people) >= major) then begin major := getPeoplePerSchooling(200, i, n, people); i_major := i; end; if (getPeoplePerSchooling(200, i, n, people) <= minor) then begin minor := getPeoplePerSchooling(200, i, n, people); i_minor := i; end; end; writeln(nameofSchooling(i_major), ' tem o maior numero de pessoas (', major, ' pessoas).'); writeln(nameofSchooling(i_minor), ' tem o menor numero de pessoas (', minor, ' pessoas).'); end; // procedure printMedia(schooling, n : integer; people : TPeopleList); var age, number, i : integer; begin age := 0; number := 0; for i := 1 to n do begin if (people[i].schooling = schooling) then begin age := age + people[i].age; inc(number); end; end; writeln('Media de idade das pessoas que concluiram o ', nameofSchooling(schooling), ' = ', age / number, 'anos.'); end; procedure printMinorAge(schooling, n : integer; people : TPeopleList); var minor_age, i : integer; begin for i := 1 to n do begin if (people[i].schooling = schooling) then begin minor_age := people[i].age; break; end end; for i := 1 to n do begin if (people[i].schooling = schooling) and (people[i].age < minor_age) then begin minor_age := people[i].age; end; end; writeln('A pessoa com menor idade com ', nameofSchooling(schooling), ' concluido tem ', minor_age, ' anos.'); end; procedure menu; Var people : TPeopleList; n : integer; op : integer; begin n := 0; repeat writeln('-------------------------'); writeln(' MENU'); writeln('-------------------------'); writeln('1 - Armazenar pessoas.'); writeln('2 - Imprimir numero de pessoas por escolaridade.'); writeln('3 - Imprimir escolaridade com maior e menor numero de pessoas.'); writeln('4 - Imprimir percentual de pessoas que concluiram o ', nameofSchooling(3), ' antes dos 24 anos.'); writeln('5 - Imprimir media de idade da pessoas que concluiram o ', nameofSchooling(5), '.'); writeln('6 - Imprimir menor idade da pessoa com ', nameofSchooling(6), '.'); writeln('0 - SAIR'); write('>> '); readln(op); case (op) of 1: people := getPeople(n); 2: printPeoplePerSchooling(n, people); 3: printMajorAndMinorNumberSchooling(n, people); 4: writeln(getPeoplePerSchooling(24, 3, n, people) / n * 100 :2:2, '% das pessoas concluiram o ', nameofSchooling(3), ' antes dos 24 anos'); 5: printMedia(5, n, people); 6: printMinorAge(6, n, people); end; until (op = 0); end; Begin menu; End.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Menus, ActnList, StdActns; type { TForm1 } TForm1 = class(TForm) Action1: TAction; ActionList1: TActionList; ColorSelect1: TColorSelect; EditCopy1: TEditCopy; EditDelete1: TEditDelete; EditPaste1: TEditPaste; EditSelectAll1: TEditSelectAll; FileOpen1: TFileOpen; FontEdit1: TFontEdit; MainMenu1: TMainMenu; Memo1: TMemo; MenuItem1: TMenuItem; MenuItem10: TMenuItem; MenuItem11: TMenuItem; MenuItem12: TMenuItem; MenuItem13: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; TOpenDialog1: TOpenDialog; procedure Action1Execute(Sender: TObject); procedure ColorSelect1Accept(Sender: TObject); procedure FileOpen1Accept(Sender: TObject); procedure FontEdit1Accept(Sender: TObject); procedure MenuItem12Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.FileOpen1Accept(Sender: TObject); begin Memo1.Clear; Memo1.Lines.LoadFromFile(FileOpen1.Dialog.FileName); Form1.Caption:=FileOpen1.Dialog.FileName; end; procedure TForm1.ColorSelect1Accept(Sender: TObject); begin Memo1.Font.Color := ColorSelect1.Dialog.Color; end; procedure TForm1.Action1Execute(Sender: TObject); begin ShowMessage('Welcome to My text Editor'); end; procedure TForm1.FontEdit1Accept(Sender: TObject); begin Memo1.Font := FontEdit1.Dialog.Font; end; procedure TForm1.MenuItem12Click(Sender: TObject); var saveDialog: TSaveDialog; begin saveDialog := TSaveDialog.Create(self); saveDialog.Title := 'Save your text as text file'; saveDialog.Filter := 'Text file|*.txt'; if saveDialog.Execute then begin with TStringList.Create do try Add(Memo1.Lines.Text); SaveToFile(saveDialog.FileName); finally Free; end; end; saveDialog.Free; end; end.
unit RoutesController; interface uses Routes, BusLine, BusStop,Generics.Collections, Aurelius.Engine.ObjectManager, ControllerInterfaces, Aurelius.Criteria.Linq, Aurelius.Criteria.Projections; type TRouteController = class(TInterfacedObject, IController<TRoute>) private FManager: TObjectManager; public constructor Create; destructor Destroy; procedure Delete(Route: TRoute); function GetAll: TList<TRoute>; function GetRoute(ID: integer): TRoute; function PriorStopExists(BusStop: TBusStop): Boolean; function NextStopExists(BusStop: TBusStop): Boolean; procedure Save(Route: TRoute); procedure Update(Route:TRoute); procedure Merge(Route: TRoute); function GetRouteIfExists(PriorBusStop, NextBusStop: TBusStop; BusLine: TBusLine): TRoute; overload; function GetRouteIfExists(PriorBusStop, NextBusStop: TBusStop): TRoute; overload; function Refresh(Route: TRoute):TRoute; function getLinesByBusStop(BusStop: TBusStop): TList<TBusLine>; end; implementation uses DBConnection; { TRouteController } constructor TRouteController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TRouteController.Delete(Route: TRoute); begin if not FManager.IsAttached(Route) then Route := FManager.Find<TRoute>(Route.Id); FManager.Remove(Route); end; destructor TRouteController.Destroy; begin FManager.Free; inherited; end; function TRouteController.GetAll: TList<TRoute>; begin FManager.Clear; Result := FManager.FindAll<TRoute>; end; function TRouteController.getLinesByBusStop(BusStop: TBusStop): TList<TBusLine>; var RouteList: TList<TRoute>; Route: TRoute; begin RouteList := FManager.Find<TRoute>. CreateAlias('PriorStop', 'p'). CreateAlias('NextStop', 'n'). Where( Linq.Sql<Integer, Integer>('{p.ID} = (?) or {n.ID} = (?)', BusStop.ID, BusStop.ID) ).List; Result := TList<TBusLine>.Create; for Route in RouteList do begin if not Result.Contains(Route.BusLine) then Result.Add(Route.BusLine); end; end; function TRouteController.GetRoute(ID: integer): TRoute; begin Result := FManager.Find<TRoute>(ID); end; function TRouteController.GetRouteIfExists(PriorBusStop, NextBusStop: TBusStop; BusLine: TBusLine): TRoute; var Route: TRoute; Routes: TList<TRoute>; Found: Boolean; begin Found := False; Routes := Self.GetAll; for Route in Routes do begin if (BusLine.ID = Route.BusLine.ID) then begin if (PriorBusStop.ID = Route.PriorStop.ID) then begin if (NextBusStop.ID = Route.NextStop.ID) then begin Result := Route; Found := True; end; end; end; end; if not Found then Result := nil; end; function TRouteController.GetRouteIfExists(PriorBusStop, NextBusStop: TBusStop): TRoute; var Route: TRoute; Routes: TList<TRoute>; Found: Boolean; begin Found := False; Routes := Self.GetAll; for Route in Routes do begin if (PriorBusStop.ID = Route.PriorStop.ID) then begin if (NextBusStop.ID = Route.NextStop.ID) then begin Result := Route; Found := True; end; end; end; if not Found then Result := nil; end; function TRouteController.NextStopExists(BusStop: TBusStop): Boolean; var Routes: TList<TRoute>; Route: TRoute; begin Routes := FManager.FindAll<TRoute>; Result := False; for Route in Routes do begin if Route.NextStop.ID = BusStop.ID then Result := True; end; end; function TRouteController.PriorStopExists(BusStop: TBusStop): Boolean; begin end; function TRouteController.Refresh(Route: TRoute): TRoute; begin FManager.Refresh(Route); result := Route; end; procedure TRouteController.Save(Route: TRoute); begin FManager.Save(Route); end; procedure TRouteController.Merge(Route: TRoute); begin FManager.Replicate<TRoute>(Route); // FManager.Flush; end; procedure TRouteController.Update(Route: TRoute); begin FManager.Update(Route); FManager.Flush; end; end.
unit uClasseConta; interface uses uConn, Data.SqlExpr, Data.DB,System.classes,StrUtils; Type TConta = class private // A varialve Conex�o receber a class da Unit uConn Conexao: TConn; // propriendades do usuario FId : String; FNome : string; FIdGru : String; FTpCon : String; FDtOpe : string; FInativo : String; FQry: TSQLQuery; FDs: TDataSource; FDsPesquisa: TDataSource; FQryPesquisa: TSQLQuery; procedure SetDs(const Value: TDataSource); procedure SetDsPesquisa(const Value: TDataSource); procedure SetQry(const Value: TSQLQuery); procedure SetQryPesquisa(const Value: TSQLQuery); procedure SetDtOpe(const Value: String); procedure SetId(const Value: String); procedure SetIdGru(const Value: String); procedure SetInativo(const Value: String); procedure SetNome(const Value: String); procedure SetTpCon(const Value: String); public constructor Create(Conn : TConn); // Propriedades property Id : String read FId write SetId; property Nome : String read FNome write SetNome; property DtOpe: String read FDtOpe write SetDtOpe; property Inativo: String read FInativo write SetInativo; property TpCon: String read FTpCon write SetTpCon; property IdGru: String read FIdGru write SetIdGru; // Componentes property Qry : TSQLQuery read FQry write SetQry; property QryPesquisa : TSQLQuery read FQryPesquisa write SetQryPesquisa; property Ds : TDataSource read FDs write SetDs; property DsPesquisa : TDataSource read FDsPesquisa write SetDsPesquisa; // Metodos function Inserir : Boolean; function UltimoRegistro : Integer; function Alterar : Boolean; function Status( Id : String ) : String; function TipoContaAlter ( Id : String ) : Integer; function ListaConta( TpConta : String ) : TStrings; function Tipo( ID : String ): Integer; function IDCon( NOme : String ): String; function VerificaConta : Boolean; function Deletar( Id : String ) : Boolean; function VerificaMov( Id: String ): Boolean; function TipoContaValidar ( Id : String ): String; end; implementation uses System.SysUtils, uBancoDados, Vcl.Forms, Winapi.Windows; { TConta } constructor TConta.Create(Conn: TConn); begin Conexao := Conn; Qry := TSQLQuery.Create(nil); Ds := TDataSource.Create(nil); QryPesquisa := TSQLQuery.Create(nil); DsPesquisa := TDataSource.Create(nil); // Conecta a Query no TSQLconnection Qry.SQLConnection := Conexao.ConexaoBanco; QryPesquisa.SQLConnection := Conexao.ConexaoBanco; Ds.DataSet := Qry; DsPesquisa.DataSet := QryPesquisa; end; function TConta.Inserir : Boolean; begin with Qry do begin Close; SQL.Text := ' insert into ficon ( nmcon, cdgru, tpcon, dtope ) ' + ' values ( :NMCON, :CDGRU, :TPCON, :DTOPE ) '; Params.ParamByName('NMCON').Value := FNome; Params.ParamByName('CDGRU').Value := FIdGru; Params.ParamByName('TPCON').Value := FTpCon; Params.ParamByName('DTOPE').Value := Date; try ExecSQL(); DM.cdsConta.Refresh; Result := True; // Retorna True se Executa sem erro except Result := False; // Retorna False se Executa com erro end; end; end; function TConta.UltimoRegistro: Integer; begin with QryPesquisa do begin Close; SQL.Text := ' select max(cdcon) from ficon '; try Open; Result := FieldByName('MAX').AsInteger + 1; // Retorna o registro do banco except Result := 0; end; end; end; function TConta.Alterar: Boolean; begin if (FInativo = 'S') and ( VerificaMov( FId ) ) then begin Application.MessageBox(' Conta possuir movimento, impossivel inativa ','Atenção',MB_OK); end else if ( VerificaMov( FId ) ) and ( FTpCon <> TipoContaValidar( FId ) ) then begin Application.MessageBox(' Conta possuir movimento, impossivel alterar tipo de conta ','Atenção',MB_OK); end else begin with Qry do begin Close; SQL.Text := ' update ficon set nmcon = :NMCON, inativo = :INTV, tpcon = :TPCON, cdgru = :CDGRU ' + ' where cdcon = :CDCON '; Params.ParamByName('NMCON').Value:= FNome; Params.ParamByName('INTV').Value:= FInativo; Params.ParamByName('TPCON').Value:= FTpCon; Params.ParamByName('CDGRU').Value := StrToInt(FIdGru); Params.ParamByName('CDCON').Value := StrToInt(FId); try ExecSQL(); DM.cdsConta.Refresh; Result := True; // Retorna True se Executa sem erro except Application.MessageBox('O registro não foi alterado!','Atenção',MB_OK); end; end; end; end; function TConta.Status(Id: String): String; begin with QryPesquisa do begin Close; SQL.Text := ' select inativo from ficon where cdcon = '+Id; try Open; Result := FieldByName('inativo').AsString; // Retorna o registro do banco except Result := '0'; end; end; end; function TConta.TipoContaAlter ( Id : String ) : Integer; var tp : String; begin with QryPesquisa do begin Close; SQL.Text := ' select tpcon from ficon where cdcon = '+Id; try Open; tp := FieldByName('tpcon').AsString; // Retorna o registro do banco finally case AnsiIndexStr(tp,['R','D','N']) of 0 : Result := 0; 1 : Result := 1; 2 : Result := 2; end; end; end; end; function TConta.ListaConta( TpConta : String ): TStrings; begin Result := TStringList.Create; Result.Clear; Result.BeginUpdate; with QryPesquisa do begin Close; SQL.Text := ' select nmcon from ficon where tpcon = :TPCON '; Params.ParamByName('TPCON').Value := TpConta; try Open; finally First; while not Eof do begin Result.Add(FieldByName('nmcon').AsString); Next; end; end; end; Result.EndUpdate; end; function TConta.Tipo( ID: String): Integer; begin if ID <> EmptyStr then begin with QryPesquisa do begin Close; SQL.Text := ' select tpcon from ficon where CDCON = :CDCON'; Params.ParamByName('CDCON').Value := ID; try Open; if FieldByName('tpcon').AsString = 'R' then Result := 0 else if FieldByName('tpcon').AsString = 'D' then Result := 1 else if FieldByName('tpcon').AsString = 'N' then Result := 2 else Result := -1; except Result := 0; end; end; end; end; function TConta.IDCon( Nome : String ): String; begin with QryPesquisa do begin Close; SQL.Text := ' select cdcon from ficon where nmcon = :NMCON'; Params.ParamByName('NMCON').Value := Nome; try Open; Result := FieldByName('cdcon').AsString; except Result := '0'; end; end; end; function TConta.VerificaConta : Boolean; var count : Integer; begin with QryPesquisa do begin Close; SQL.Text := ' select count(cdcon) from ficon where nmcon = :NMCON '; Params.ParamByName('NMCON').Value := FNome; try Open; count := FieldByName('count').AsInteger; // Retorna o registro do banco finally if count > 0 then Result := True else Result := False; end; end; end; function TConta.Deletar( Id: String ): Boolean; begin with Qry do begin Close; SQL.Text := ' delete from ficon where cdcon = :CDCON ' ; Params.ParamByName('CDCON').Value := StrToInt(Id); try ExecSQL(); DM.cdsConta.Refresh; Result := True; // Retorna True se Executa sem erro except Result := False; // Retorna False se Executa com erro end; end; end; function TConta.VerificaMov( Id: String ): Boolean; begin with Qry do begin Close; SQL.Text := ' select count(cdcon) from fimov where cdcon = :CDCON ' ; Params.ParamByName('CDCON').Value := StrToInt(Id); try Open; if FieldByName('count').AsInteger > 0 then Result := True else Result := False; except Result := False; end; end; end; function TConta.TipoContaValidar( Id : String ): String; begin with QryPesquisa do begin Close; SQL.Text := ' select tpcon from ficon where cdcon = '+Id; try Open; finally Result := FieldByName('tpcon').AsString; end; end; end; procedure TConta.SetDs(const Value: TDataSource); begin FDs := Value; end; procedure TConta.SetDsPesquisa(const Value: TDataSource); begin FDsPesquisa := Value; end; procedure TConta.SetDtOpe(const Value: String); begin FDtOpe := Value; end; procedure TConta.SetId(const Value: String); begin FId := Value; end; procedure TConta.SetIdGru(const Value: String); begin if Value= EmptyStr then raise Exception.Create('Empreencha o Campo Grupo') else FIdGru := Value; end; procedure TConta.SetInativo(const Value: String); begin FInativo := Value; end; procedure TConta.SetNome(const Value: String); begin if Value= EmptyStr then raise Exception.Create('Empreencha o Campo Nome da Conta') else FNome := Value; end; procedure TConta.SetQry(const Value: TSQLQuery); begin FQry := Value; end; procedure TConta.SetQryPesquisa(const Value: TSQLQuery); begin FQryPesquisa := Value; end; procedure TConta.SetTpCon(const Value: String); begin FTpCon := Value; end; end.
unit VectorOperatorsTestCase; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type { TVectorOperatorsTestCase } TVectorOperatorsTestCase = class(TVectorBaseTestCase) published procedure TestCompare; // these two test ensure we have data to play procedure TestCompareFalse; // with and tests the compare function. procedure TestAddVector; procedure TestAddSingle; procedure TestSubVector; procedure TestSubSingle; procedure TestMulVector; procedure TestMulSingle; procedure TestDivVector; procedure TestDivSingle; procedure TestEqualVector; procedure TestSomeEqualVector; procedure TestUnEqualVector; procedure TestLTorEqualVector; procedure TestLTorEqualOneGreaterVector; procedure TestGTorEqualVector; procedure TestGTorEqualOneLessVector; procedure TestLTVector; procedure TestLTOneGreaterVector; procedure TestGTVector; procedure TestGTOneLessVector; end; implementation {%region%====[ TVectorOperatorsTestCase ]======================================} {Test IsEqual and we have same values for each class ttpe} procedure TVectorOperatorsTestCase.TestCompare; begin AssertTrue('Test Values do not match'+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOperatorsTestCase.TestCompareFalse; begin AssertFalse('Test Values should not match'+nt1.ToString+' --> '+vt2.ToString, Compare(nt1,vt2)); end; procedure TVectorOperatorsTestCase.TestAddVector; begin nt3 := nt2 + nt1; vt3 := vt1 + vt2; AssertTrue('Vector + Vector no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestAddSingle; begin nt3 := nt1 + fs1; vt3 := vt1 + fs1; AssertTrue('Vector + Single no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestSubVector; begin nt3 := nt2 - nt1; vt3 := vt2 - vt1; AssertTrue('Vector - Vector no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestSubSingle; begin nt3 := nt1 - fs1; vt3 := vt1 - fs1; AssertTrue('Vector - Single no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestMulVector; begin nt3 := nt2 * nt1; vt3 := vt2 * vt1; AssertTrue('Vector x Vector no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestMulSingle; begin nt3 := nt1 * fs1; vt3 := vt1 * fs1; AssertTrue('Vector x Single no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestDivVector; begin nt3 := nt2 / nt1; vt3 := vt2 / vt1; AssertTrue('Vector / Vector no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestDivSingle; begin nt3 := nt1 / fs1; vt3 := vt1 / fs1; AssertTrue('Vector / Single no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3)); end; procedure TVectorOperatorsTestCase.TestEqualVector; begin nb := nt1 = nt1; vb := vt1 = vt1; AssertTrue('Vectors should be equal'+nt1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestSomeEqualVector; begin at1.V := vt1.V; at1.X := at1.X +1; at1.Z := at1.Z - 1; ant1.V := at1.V; nb := nt1 = ant1; vb := vt1 = at1; AssertTrue('Vectors should not be equal'+vt1.ToString+' --> '+at1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestUnEqualVector; begin nb := nt1 = nt2; vb := vt1 = vt2; AssertTrue('Vectors should be equal'+vt1.ToString+' --> '+vt2.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestLTorEqualVector; begin at1 := vt1 - 1; ant1.V := at1.V; nb := at1 <= vt1; vb := ant1 <= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestLTorEqualOneGreaterVector; begin at1 := vt1 - 1; at1.Y := vt1.Y + 1; ant1.V := at1.V; nb := at1 <= vt1; vb := ant1 <= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestGTorEqualVector; begin at1 := vt1 + 1; ant1.V := at1.V; nb := at1 >= vt1; vb := ant1 >= nt1; AssertTrue('Vectors should be gt equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestGTorEqualOneLessVector; begin at1 := vt1 + 1; at1.Y := vt1.Y - 1; ant1.V := at1.V; nb := at1 >= vt1; vb := ant1 >= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestLTVector; begin at1 := vt1 - 1; ant1.V := at1.V; nb := at1 <= vt1; vb := ant1 <= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestLTOneGreaterVector; begin at1 := vt1 - 1; at1.Y := vt1.Y + 1; ant1.V := at1.V; nb := at1 <= vt1; vb := ant1 <= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestGTVector; begin at1 := vt1 + 1; ant1.V := at1.V; nb := at1 >= vt1; vb := ant1 >= nt1; AssertTrue('Vectors should be gt equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; procedure TVectorOperatorsTestCase.TestGTOneLessVector; begin at1 := vt1 + 1; at1.Y := vt1.Y - 1; ant1.V := at1.V; nb := at1 >= vt1; vb := ant1 >= nt1; AssertTrue('Vectors should be equal'+at1.ToString+' --> '+vt1.ToString, not(nb xor vb)); end; {%endregion%} initialization RegisterTest(REPORT_GROUP_VECTOR4F, TVectorOperatorsTestCase); end.
unit Atm.Tests.Fixtures.Machine; interface uses System.SysUtils, DUnitX.TestFramework, Atm.Services.CardReader, Atm.Services.Communicator, Atm.Services.Machine; type [TestFixture] TAtmMachineTests = class(TObject) public [Test] procedure Create_NoOp_CheckWithdrawalDisabled; [Test] procedure StartSession_WithRightPin_CheckWithdrawalEnabled; [Test] procedure StartSession_WithWrongPin_CheckWithdrawalDisabled; [Test] procedure EndSession_WithRightPin_CheckWithdrawalDisabled; [Test] procedure StartSession_WithRightPin_NoWarning; [Test] procedure StartSession_WithWrongPin_WarningSent; [Test] procedure StartSession_WithWrongPin_WarningTextMatch; end; implementation uses Atm.Tests.Globals, Atm.Tests.Mocks.Communicator, Atm.Tests.Stubs.CardReader, Atm.Tests.Stubs.Communicator; procedure TAtmMachineTests.Create_NoOp_CheckWithdrawalDisabled; var LMachine: TAtmMachine; begin LMachine := TAtmMachine.Create(CreateCardReaderStub, CreateCommunicatorStub); try Assert.IsFalse(LMachine.WithdrawalEnabled); finally LMachine.Free; end; end; procedure TAtmMachineTests.EndSession_WithRightPin_CheckWithdrawalDisabled; var LMachine: TAtmMachine; begin LMachine := TAtmMachine.Create(CreateCardReaderStub, CreateCommunicatorStub); try LMachine.StartSession(PinRightValue); LMachine.EndSession; Assert.IsFalse(LMachine.WithdrawalEnabled); finally LMachine.Free; end; end; procedure TAtmMachineTests.StartSession_WithRightPin_CheckWithdrawalEnabled; var LMachine: TAtmMachine; begin LMachine := TAtmMachine.Create(CreateCardReaderStub, CreateCommunicatorStub); try LMachine.StartSession(PinRightValue); Assert.IsTrue(LMachine.WithdrawalEnabled); finally LMachine.Free; end; end; procedure TAtmMachineTests.StartSession_WithWrongPin_CheckWithdrawalDisabled; var LMachine: TAtmMachine; begin LMachine := TAtmMachine.Create(CreateCardReaderStub, CreateCommunicatorStub); try LMachine.StartSession(PinWrongValue); Assert.IsFalse(LMachine.WithdrawalEnabled); finally LMachine.Free; end; end; procedure TAtmMachineTests.StartSession_WithRightPin_NoWarning; var LMock: IAtmCommunicatorMock; LMachine: TAtmMachine; begin LMock := CreateCommunicatorMock; LMachine := TAtmMachine.Create(CreateCardReaderStub, LMock); try LMachine.StartSession(PinRightValue); Assert.IsFalse(LMock.WarningSent); finally FreeAndNil(LMachine); end; end; procedure TAtmMachineTests.StartSession_WithWrongPin_WarningSent; var LMock: IAtmCommunicatorMock; LMachine: TAtmMachine; begin LMock := CreateCommunicatorMock; LMachine := TAtmMachine.Create(CreateCardReaderStub, LMock); try LMachine.StartSession(PinWrongValue); Assert.IsTrue(LMock.WarningSent); finally FreeAndNil(LMachine); end; end; procedure TAtmMachineTests.StartSession_WithWrongPin_WarningTextMatch; var LMock: IAtmCommunicatorMock; LMachine: TAtmMachine; begin LMock := CreateCommunicatorMock; LMachine := TAtmMachine.Create(CreateCardReaderStub, LMock); try LMachine.StartSession(PinWrongValue); Assert.AreEqual('Wrong PIN alert', LMock.WarningText); finally FreeAndNil(LMachine); end; end; initialization TDUnitX.RegisterTestFixture(TAtmMachineTests); end.