text
stringlengths
14
6.51M
{ MIT License Copyright (c) 2017-2019 Marcos Douglas B. Santos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit JamesBase64Adapters; {$i James.inc} interface uses Classes, SysUtils, SynCommons, JamesDataBase, JamesDataCore; type /// Base64 coded action TBase64Action = (baEncode, baDecode); /// object to adapt a Base64 text into other types TBase64Adapter = {$ifdef UNICODE}record{$else}object{$endif} private fAction: TBase64Action; fText: RawByteString; function AsCoded: RawByteString; public /// initialize the instance // - the action will determinate if the origin will be encoded or decoded for in adapter methods procedure Init(aAction: TBase64Action; const aText: RawByteString); /// return as RawByteString function AsRawByteString: RawByteString; /// return as DataStream function AsDataStream: IDataStream; end; implementation { TBase64Adapter } function TBase64Adapter.AsCoded: RawByteString; begin case fAction of baEncode: result := BinToBase64(fText); baDecode: result := Base64ToBin(fText); else result := ''; end; end; procedure TBase64Adapter.Init(aAction: TBase64Action; const aText: RawByteString); begin fAction := aAction; fText := aText; end; function TBase64Adapter.AsRawByteString: RawByteString; begin result := AsCoded; end; function TBase64Adapter.AsDataStream: IDataStream; var m: TStream; begin m := RawByteStringToStream(AsCoded); try result := TDataStream.Create(m); finally m.Free; end; end; end.
unit FMXGR32DemoMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls, System.Math.Vectors, GR32_Transforms, GR32, System.Math, FMX.Layouts, TypInfo, FMX.Platform, FMX.ListBox, GR32_Resamplers; type TFMXGR32DemoMainFrom = class(TForm) Image1: TImage; Layout2: TLayout; Image2: TImage; Rectangle3: TRectangle; Label13: TLabel; Rectangle1: TRectangle; Label1: TLabel; CmbResamplerClassNames: TComboBox; procedure FormCreate(Sender: TObject); procedure Layout2Resize(Sender: TObject); procedure CmbResamplerClassNamesChange(Sender: TObject); private const DESIRE_FORMAT: TPixelFormat = {$IFDEF ANDROID} TPixelFormat.RGBA {$ELSE} TPixelFormat.BGRA {$ENDIF} ; private { Private declarations } Transformation: TProjectiveTransformation; FScaleFactor: Single; Vertices: array [0..3] of TPointF; procedure DoPointChanged(Sender: TObject; var X, Y: Single); procedure DoTransform; public { Public declarations } end; var FMXGR32DemoMainFrom: TFMXGR32DemoMainFrom; implementation {$R *.fmx} procedure TFMXGR32DemoMainFrom.CmbResamplerClassNamesChange(Sender: TObject); begin DoTransform; end; procedure TFMXGR32DemoMainFrom.DoPointChanged(Sender: TObject; var X, Y: Single); var idx: Integer; begin idx := (Sender as TComponent).Tag; Vertices[idx].X := X; Vertices[idx].Y := Y; DoTransform; end; procedure TFMXGR32DemoMainFrom.DoTransform; var src, dst: TBitmap32; maxx,maxy: Single; I: Integer; s: string; dstBitmap, tmp: TBitmap; begin if image1.Bitmap.PixelFormat <> DESIRE_FORMAT then begin s := TypInfo.GetEnumName(TypeInfo(TPixelFormat), Integer(image1.Bitmap.PixelFormat)); ShowMessage('wrong with ' + s); Exit; end; maxx := 0; maxy := 0; for I := 0 to 3 do begin maxx := max(maxx, Vertices[I].X); maxy := max(maxy, Vertices[I].Y); end; Transformation.X0 := Vertices[0].X; Transformation.Y0 := Vertices[0].Y; Transformation.X1 := Vertices[1].X; Transformation.Y1 := Vertices[1].Y; Transformation.X2 := Vertices[2].X; Transformation.Y2 := Vertices[2].Y; Transformation.X3 := Vertices[3].X; Transformation.Y3 := Vertices[3].Y; Transformation.SrcRect := FloatRect(0,0,200,200); src := TBitmap32.Create(); dst := TBitmap32.Create(); dstBitmap := TBitmap.Create; try src.Assign(Image1.Bitmap); with CmbResamplerClassNames do if ItemIndex >= 0 then Src.ResamplerClassName := Items[ ItemIndex ]; dst.SetSize(ceil(maxx), ceil(maxy)); Dst.Clear($00000000); Transform(Dst, Src, Transformation); dstBitmap.Assign(dst); if FScaleFactor = 1 then Image2.Bitmap := dstBitmap else begin tmp := TBitmap.Create; try tmp.SetSize(Round(dstBitmap.Width * FScaleFactor), Round(dstBitmap.Height * FScaleFactor)); tmp.Canvas.BeginScene; tmp.Clear(0); tmp.Canvas.DrawBitmap(dstBitmap, dstBitmap.Bounds, tmp.Bounds, 1); tmp.Canvas.EndScene; Image2.Bitmap := tmp; finally tmp.Free; end; end; finally dstBitmap.Free; dst.Free; src.Free; end; end; procedure TFMXGR32DemoMainFrom.FormCreate(Sender: TObject); var I: Integer; Shape: TSelectionPoint; ScreenSrv: IFMXScreenService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, ScreenSrv) then FScaleFactor := ScreenSrv.GetScreenScale else FScaleFactor := 1; Transformation := TProjectiveTransformation.Create; Vertices[0] := Point(0,0); Vertices[1] := Point(200,0); Vertices[2] := Point(200,200); Vertices[3] := Point(0,200); for I := 0 to 3 do begin Shape := TSelectionPoint.Create(Self); Shape.Parent := Image2; Shape.GripSize := 9; Shape.Position.X := Vertices[i].X; Shape.Position.Y := Vertices[i].Y; Shape.OnTrack := DoPointChanged; Shape.Tag := i; end; ResamplerList.GetClassNames(CmbResamplerClassNames.Items); CmbResamplerClassNames.ItemIndex := 0; end; procedure TFMXGR32DemoMainFrom.Layout2Resize(Sender: TObject); begin Image1.Position.Point := TPoint.Zero; if Layout2.Width > Layout2.Height then begin Image1.Size.Size := TSizeF.Create(Layout2.Width / 2, Layout2.Height); Image2.Position.Point := PointF(Layout2.Width/2, 0); Image2.Size.Size := TSizeF.Create(Layout2.Width / 2, Layout2.Height); end else begin Image1.Size.Size := TSizeF.Create(Layout2.Width, Layout2.Height/2); Image2.Position.Point := PointF(0, Layout2.Height/2); Image2.Size.Size := TSizeF.Create(Layout2.Width, Layout2.Height/2); end; end; end.
(* Challenge 120 TASK #2 - Clock Angle Submitted by: Mohammad S Anwar You are given time $T in the format hh:mm. Write a script to find the smaller angle formed by the hands of an analog clock at a given time. HINT: A analog clock is divided up into 12 sectors. One sector represents 30 degree (360/12 = 30). Example Input: $T = '03:10' Output: 35 degree The distance between the 2 and the 3 on the clock is 30 degree. For the 10 minutes i.e. 1/6 of an hour that have passed. The hour hand has also moved 1/6 of the distance between the 3 and the 4, which adds 5 degree (1/6 of 30). The total measure of the angle is 35 degree. Input: $T = '04:00' Output: 120 degree *) program ch2(input, output); uses sysutils, strutils; function parseTime(hhmm: String): Integer; var p, hh, mm: Integer; begin p := PosEx(':', hhmm); hh := StrToInt(LeftStr(hhmm, p-1)); mm := StrToInt(MidStr(hhmm, p+1, length(hhmm))); parseTime := hh*100+mm; end; function clockAngle(hhmm: Integer): Integer; var hh, mm, hh_angle, mm_angle, angle: Integer; begin hh := hhmm div 100; mm := hhmm mod 100; mm_angle := mm*360 div 60; hh_angle := (hh mod 12)*360 div 12 + mm_angle div 12; angle := abs(hh_angle - mm_angle); if angle > 180 then angle := 360 - angle; clockAngle := angle; end; var angle: Integer; begin angle := clockAngle(parseTime(paramStr(1))); WriteLn(angle); end.
unit fmuEJSession; interface uses // VCL Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, // This untPages, untDriver, Spin; type TfmEJSession = class(TPage) Memo: TMemo; btnGetEKLZJournal: TBitBtn; btnStop: TBitBtn; lblSessionNumber: TLabel; btnGetEKLZSessionTotal: TBitBtn; btnEKLZJournalOnSessionNumber: TBitBtn; btnReadEKLZJournal: TBitBtn; seSessionNumber: TSpinEdit; procedure btnGetEKLZJournalClick(Sender: TObject); procedure btnGetEKLZSessionTotalClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnEKLZJournalOnSessionNumberClick(Sender: TObject); procedure btnReadEKLZJournalClick(Sender: TObject); private FStopFlag: Boolean; procedure GetEKLZData; procedure Check2(ResultCode: Integer); end; implementation {$R *.DFM} /////////////////////////////////////////////////////////////////////////////// // Некоторый эксперт написал что неправильно выдавать ошибку // Хорошо, ошибка будет просто очищаться в драйвере procedure TfmEJSession.Check2(ResultCode: Integer); begin if ResultCode <> 0 then begin if ResultCode = $A9 then Driver.ClearResult; Abort; end; end; procedure TfmEJSession.GetEKLZData; begin Memo.Lines.Add(''); Memo.Lines.Add(' Тип ККМ: ' + Driver.UDescription); Memo.Lines.Add(''); repeat Check2(Driver.GetEKLZData); Memo.Lines.Add(' ' + Driver.EKLZData); Application.ProcessMessages; until FStopFlag; Driver.EKLZInterrupt; end; procedure TfmEJSession.btnGetEKLZJournalClick(Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.SessionNumber := seSessionNumber.Value; Check(Driver.GetEKLZJournal); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmEJSession.btnGetEKLZSessionTotalClick(Sender: TObject); begin FStopFlag := False; EnableButtons(False); btnStop.Enabled := True; try Memo.Clear; Driver.SessionNumber := seSessionNumber.Value; Check(Driver.GetEKLZSessionTotal); GetEKLZData; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmEJSession.btnStopClick(Sender: TObject); begin FStopFlag := True; end; procedure TfmEJSession.btnEKLZJournalOnSessionNumberClick( Sender: TObject); begin EnableButtons(False); try Driver.SessionNumber := seSessionNumber.Value; Driver.ReadEKLZSessionTotal; finally EnableButtons(True); end; end; procedure TfmEJSession.btnReadEKLZJournalClick(Sender: TObject); begin EnableButtons(False); try Driver.SessionNumber := seSessionNumber.Value; Driver.EKLZJournalOnSessionNumber; finally EnableButtons(True); end; end; end.
unit DBISAMTableAU; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBISAMTb, ffsutils, dbisamen; const PrimaryKey = ''; resourcestring comma = ', '; TableNoExist = 'Table does not exist'; DefNoExist = 'Definition does not exist'; NoTableName = 'Table name is missing'; FieldCntMis = 'Field count mismatch'; FieldDefMis = 'Field definition mismatch'; IndexCntMis = 'Index count mismatch'; IndexDefMis = 'Index definition mismatch'; type TDefField = record FieldName : string[30]; FieldType : string[10]; FieldLen : integer; Req : boolean; Desc : string[50]; end; TDefIndex = record IdxName : string[30]; IdxFields : string[200]; IdxOpts : TIndexOptions; end; EAUTable = class(Exception); TDBISAMTableAU = class(TDBISAMTable) private FModCount: integer; FAutoRepair: boolean; procedure SetModCount(const Value: integer); procedure SetAutoRepair(const Value: boolean); // validation & creation variables protected procedure LoadFieldDefs(AStringList:TStringList);virtual; procedure LoadIndexDefs(AStringList:TStringList);virtual; private FDefName: string; FSavedKey: string; SavedIndexName:string; FAutoModCount: boolean; function FindTheRecord(dsFrom: TDataSet): boolean; function FindByCSV(csv:string):boolean; procedure SetDefName(const Value: string); procedure CopyFromCSV(csv: string); procedure CopyFromCSVWMemo(csv: string); procedure SaveKeyCSV; procedure CopyKeyFromCSV(csv: string); procedure RestoreState; procedure SaveState; function PrimaryFieldsCSV: string; procedure SetAutoModCount(const Value: boolean); property ModCount:integer read FModCount write SetModCount; protected { Protected declarations } SuppressBackup:boolean; procedure DoBeforeDelete;override; procedure DoAfterDelete;override; public { Public declarations } constructor create(AOwner:TComponent);overload;override; constructor create(AOwner:TComponent;ADatabase:TDbisamDatabase;ATableName:string);reintroduce;overload; procedure post;override; procedure DoBeforeEdit;override; procedure DoBeforePost;override; function GetCSV(const KeyValues: TStrings):string;overload; function GetCSV(const KeyValues: string):string;overload; function GetCSVWMemo: String; function GetMemoField(FieldName:string):string; procedure GetTableAsCSV(var sl: TStringList; OptionalList:string = ''); procedure SetMemoField(KeyFields, FieldName, AMemo:string); procedure RecordCopy(dsFrom: TDataSet); procedure RangeCopy(dsFrom: TDataSet); procedure UpdateFrom(dsFrom: TDataSet); procedure DeleteFrom(dsFrom: TDataSet); procedure UpdateFromCSV(csv:string); procedure AppendFromCSV(csv:string); procedure AppendFromCSVWMemo(csv:string); procedure VerifyStructure; procedure MakeTable(OverWrite:boolean = false); procedure DeleteByKeyCSV(csv: string); property SavedKey:string read FSavedKey; procedure UpgradeStructure(force:boolean=false); procedure OpenUp; procedure TransferRecord(dsFrom: TDataSet); published { Published declarations } property DefName:string read FDefName write SetDefName; property AutoModCount:boolean read FAutoModCount write SetAutoModCount; property AutoRepair:boolean read FAutoRepair write SetAutoRepair; end; TDBISAMQueryAU = class(TDBISAMQuery) private FModCount: integer; procedure SetModCount(const Value: integer); // validation & creation variables private FAutoModCount: boolean; procedure SetAutoModCount(const Value: boolean); property ModCount:integer read FModCount write SetModCount; protected { Protected declarations } SuppressBackup:boolean; procedure DoBeforeDelete;override; procedure DoAfterDelete;override; public { Public declarations } constructor create(AOwner:TComponent);overload;override; constructor create(AOwner:TComponent;ADatabase:TDbisamDatabase;ATableName:string);reintroduce;overload; procedure post;override; procedure DoBeforeEdit;override; procedure DoBeforePost;override; function GetCSV(const KeyValues: TStrings):string;overload; function GetCSV(const KeyValues: string):string;overload; procedure GetTableAsCSV(var sl: TStringList; OptionalList:string = ''); published { Published declarations } property AutoModCount:boolean read FAutoModCount write SetAutoModCount; end; procedure Register; function StringToDataType(s: string): TFieldType; function StringToDefField(s: string): TDefField; function StringToDefIndex(s: string): TDefIndex; function DataTypeToString(ft: TFieldType): string; function DataTypeToStringField(ft: TFieldType):string; implementation { TDBISAMTableAU } function StringToDataType(s: string): TFieldType; begin s := uppercase(s); result := ftUnknown; // the default if s = 'STRING' then result := ftString; if s = 'SMALLINT' then result := ftSmallInt; if s = 'INTEGER' then result := ftInteger; if s = 'WORD' then result := ftWord; if s = 'BOOLEAN' then result := ftBoolean; if s = 'FLOAT' then result := ftFloat; if s = 'CURRENCY' then result := ftCurrency; if s = 'BCD' then result := ftBCD; if s = 'TDATE' then result := ftDate; if s = 'TTIME' then result := ftTime; if s = 'TDATETIME' then result := ftDateTime; if s = 'BYTES' then result := ftBytes; if s = 'VARBYTES' then result := ftVarBytes; if s = 'AUTOINC' then result := ftAutoInc; if s = 'BLOB' then result := ftBlob; if s = 'MEMO' then result := ftMemo; if s = 'GRAPHIC' then result := ftGraphic; if s = 'FMTMEMO' then result := ftFmtMemo; end; function DataTypeToString(ft: TFieldType): string; begin result := 'Unknown'; case ft of ftString : result := 'String'; ftSmallInt : result := 'SmallInt'; ftInteger : result := 'Integer'; ftWord : result := 'Word'; ftBoolean : result := 'Boolean'; ftFloat : result := 'Float'; ftCurrency : result := 'Currency'; ftBCD : result := 'BCD'; ftDate : result := 'TDate'; ftTime : result := 'TTime'; ftDateTime : result := 'TDateTime'; ftAutoInc : result := 'AutoInc'; ftBlob : result := 'Blob'; ftMemo : result := 'Memo'; ftGraphic : result := 'Graphic'; ftFmtMemo : result := 'FmtMemo'; end; end; function DataTypeToStringField(ft: TFieldType):string; begin if ft in [ftBlob, ftMemo, ftGraphic, ftFmtMemo] then result := 'Blob' else result := DataTypeToString(ft); end; function StringToDefField(s: string):TDefField; const msgstr = 'AUTable Invalid Field Definition'; var p : integer; oknum : integer; fdef : TDefField; req : string; begin fillchar(fdef, sizeof(fdef),0); // name p := pos(',',s); if p > 0 then fdef.FieldName := trim(copy(s,1,p-1)) else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // type p := pos(',',s); if p > 0 then fdef.FieldType := trim(copy(s,1,p-1)) else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // length p := pos(',',s); if p > 0 then val(trim(copy(s,1,p-1)), fdef.FieldLen, Oknum) else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // required p := pos(',',s); if p > 0 then req := trim(copy(s,1,p-1)) else req := s; fdef.Req := req = 'Y'; s := trim(copy(s,p+1,length(s)-p)); // description fdef.Desc := trim(s); // any remainder result := fdef; end; function StringToDefIndex(s: string): TDefIndex; const msgstr = 'AUTable Invalid Index Definition'; var p : integer; fdef : TDefIndex; fiIdxPrimary, fiIdxUnique, fiIdxCaseIns, fiIdxDescend : boolean; begin fillchar(fdef, sizeof(fdef),0); try // name p := pos(',',s); if p > 0 then fdef.IdxName := trim(copy(s,1,p-1)) else raise EAuTable.create(msgstr); if uppercase(fdef.IdxName) = 'PRIMARYKEY' then fdef.IdxName := ''; s := trim(copy(s,p+1,length(s)-p)); // fields p := pos(',',s); if p > 0 then fdef.IdxFields := trim(copy(s,1,p-1)) else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // opt Primary p := pos(',',s); if p > 0 then fiIdxPrimary := uppercase(trim(copy(s,1,p-1))) = 'Y' else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // opt Unique p := pos(',',s); if p > 0 then fiIdxUnique := uppercase(trim(copy(s,1,p-1))) = 'Y' else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // opt CaseIns p := pos(',',s); if p > 0 then fiIdxCaseIns := uppercase(trim(copy(s,1,p-1))) = 'Y' else raise EAuTable.create(msgstr); s := trim(copy(s,p+1,length(s)-p)); // opt Descend fiIdxDescend := uppercase(trim(copy(s,1,p-1))) = 'Y'; // convert to set FDef.IdxOpts := []; if fiIdxPrimary then FDef.IdxOpts := FDef.IdxOpts + [ixPrimary]; if fiIdxUnique then FDef.IdxOpts := FDef.IdxOpts + [ixUnique]; if fiIdxCaseIns then FDef.IdxOpts := FDef.IdxOpts + [ixCaseInsensitive]; if fiIdxDescend then FDef.IdxOpts := FDef.IdxOpts + [ixDescending]; finally result := fdef; end; end; constructor TDBISAMTableAU.create(AOwner: TComponent); begin inherited; SuppressBackup := false; end; procedure TDBISAMTableAU.post; begin if AutoModCount then begin end; inherited; end; procedure Register; begin RegisterComponents( 'Data Access', [ TDBISAMTableAU ] ); end; { Register } procedure TDBISAMTableAU.GetTableAsCSV(var sl:TStringList; OptionalList:string); begin sl.Clear; try First; while not EOF do begin sl.Add(GetCSV(OptionalList)); Next; end; except sl.Clear; end; end; function TDBISAMTableAU.GetCSV(const KeyValues: TStrings): string; var x : integer; n : integer; s : string; fld : TField; begin result := ''; n := keyValues.count - 1; if n >= 0 then begin for x := 0 to n do begin fld := FieldByName(KeyValues[x]); if fld <> nil then begin if fld.FieldKind = fkData then begin try s := ''; case fld.DataType of ftBoolean : case fld.AsBoolean of true : s := 'True'; false : s := 'False'; end; ftInteger : s := IntToStr(fld.AsInteger); ftFloat : s := FloatToStr(fld.AsFloat); ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftBytes, ftVarBytes, ftTypedBinary, ftCursor : s := ''; else s := fld.AsString; end; result := result + csvquote(s); except result := result + csvquote(' '); // do nothing if the field is bad end; if x < n then result := result + ','; end; end; end; end else begin n := FieldCount - 1; for x := 0 to n do begin fld := Fields[x]; if fld.FieldKind = fkData then begin try s := ''; case fld.DataType of ftBoolean : case fld.AsBoolean of true : s := s + 'True'; false : s := s + 'False'; end; else s := fld.AsString; end; result := result + csvquote(s); except result := result + csvquote(' '); end; if x < n then result := result + ','; end; end; end; end; function TDBISAMTableAU.GetCSVWMemo: string; var x : integer; n : integer; s : string; fld : TField; begin result := ''; n := FieldCount - 1; for x := 0 to n do begin fld := Fields[x]; if fld.FieldKind = fkData then begin try s := ''; case fld.DataType of ftBoolean : case fld.AsBoolean of true : s := s + 'True'; false : s := s + 'False'; end; ftMemo, ftFmtMemo : s := trimright(fld.AsString); else s := fld.AsString; end; result := result + csvquote(s); except result := result + csvquote(' '); end; if x < n then result := result + ','; end; end; end; procedure TDBISAMTableAU.TransferRecord(dsFrom:TDataSet); var x : integer; fname : string; fromfld : TField; i : integer; begin for x := 0 to FieldCount - 1 do begin fname := fields[x].FieldName; i := dsFrom.FieldList.IndexOf(fname); if i > -1 then begin try fromfld := dsFrom.FieldByName(fname); except fromfld := nil; end; if fromfld <> nil then begin if fields[x].DataType = fromfld.DataType then fields[x].Value := fromFld.Value else fields[x].AsString := fromfld.AsString; end; end; end; end; procedure TDBISAMTableAU.RecordCopy(dsFrom:TDataSet); begin if (dsfrom.RecordCount = 0) then exit; append; TransferRecord(dsFrom); try post; except cancel; UpdateFrom(dsFrom); end; end; procedure TDBISAMTableAU.RangeCopy(dsFrom:TDataSet); begin if dsFrom.RecordCount = 0 then exit; dsFrom.First; while not dsfrom.eof do begin try RecordCopy(dsFrom); except UpdateFrom(dsFrom); end; dsFrom.Next; end; end; function TDBISAMTableAU.FindTheRecord(dsFrom: TDataset):boolean; var fname : string; x : integer; begin SaveState; indexname := PrimaryKey; // set to primary key try SetKey; for x := 0 to IndexFieldCount - 1 do begin fname := IndexFields[x].FieldName; fieldbyname(fname).Value := dsFrom.FieldByName(fname).value; end; result := GoToKey; finally RestoreState; // put it back end; end; procedure TDBISAMTableAU.UpdateFrom(dsFrom: TDataset); begin if FindTheRecord(dsFrom) then begin Edit; TransferRecord(dsFrom); Post; end; end; procedure TDBISAMTableAU.DeleteFrom(dsFrom: TDataset); begin if FindTheRecord(dsFrom) then Delete; end; procedure TDBISAMTableAU.SetDefName(const Value: string); begin FDefName := Value; end; constructor TDBISAMTableAU.create(AOwner:TComponent;ADatabase: TDbisamDatabase; ATableName: string); begin inherited create(AOwner); Databasename := ADatabase.DatabaseName; SessionName := ADatabase.SessionName; TableName := ATableName; SuppressBackup := false; end; procedure TDBISAMTableAU.LoadFieldDefs(AStringList:TStringList); begin AStringList.Clear; end; procedure TDBISAMTableAU.LoadIndexDefs(AStringList:TStringList); begin AStringList.Clear; end; procedure TDBISAMTableAU.VerifyStructure; var x,y : integer; temp : TField; IsAMatch : boolean; tempTable : TDbIsamTable; found : integer; dfield : TDefField; dindex : TDefIndex; DefFields : TStringList; DefIndexs : TStringList; begin // there are several things to consider // 1. The actual table doesn't exist // 2. The actual table has fields that the def doesn't // 3. The actual table is missing fields from the def // 4. The actual table's field defs don't match the definition // start with table being there if not exists then raise EAuTable.create(Tablename+':'+TableNoExist); // does the table exist? // We check out each field in the def & try to match it with the table, first failure quits // Read the table info DefFields := TStringList.Create; DefIndexs := TStringList.Create; tempTable := TDbIsamtable.Create(nil); tempTable.SessionName := SessionName; tempTable.DatabaseName := DatabaseName; tempTable.Tablename := Tablename; tempTable.Active := true; try // now read the definition LoadFieldDefs(DefFields); LoadIndexDefs(DefIndexs); if (tempTable.fields.Count) <> DefFields.Count then raise EAuTable.Create('Table: '+TableName+'-'+FieldCntMis); // now check field by field for x := 0 to DefFields.Count - 1 do begin dfield := StringToDefField(DefFields[x]); temp := tempTable.FindField(dfield.FieldName); if temp <> nil then begin IsAMatch := temp.DataType = StringToDataType(dfield.FieldType); if IsAMatch then IsAMatch := temp.Size = dfield.FieldLen; if IsAMatch then IsAMatch := temp.Required = dfield.Req; end else IsAMatch := false; if not IsAMatch then raise EAuTable.Create('Table: '+TableName+'-'+FieldDefMis); // something about the fields didn't match end; // now check the indexes tempTable.IndexDefs.Update; // make sure they are read ( not done by default) if (tempTable.IndexDefs.Count) <> DefIndexs.Count then raise EAuTable.Create('Table: '+TableName+'-'+IndexCntMis); // check the defs for x := 0 to DefIndexs.Count - 1 do begin found := -1; dindex := StringToDefIndex(DefIndexs[x]); for y := 0 to TempTable.IndexDefs.Count - 1 do begin if uppercase(TempTable.IndexDefs.Items[y].Name) = uppercase(dindex.IdxName) then begin found := y; break; end; end; if found > -1 then begin IsAMatch := uppercase(TempTable.IndexDefs.Items[found].Fields) = uppercase(dindex.IdxFields); if IsAMatch then IsAMatch := (dindex.IdxOpts = TempTable.IndexDefs.Items[y].Options); end else IsAMatch := false; if not IsAMatch then raise EAuTable.Create('Table: '+TableName+'-'+IndexDefMis); // something about the indices didn't match end; // If you get to this point then nothing knocked it out finally tempTable.Active := false; tempTable.Free; DefFields.Free; DefIndexs.Free; end; end; procedure TDBISAMTableAU.MakeTable(OverWrite: boolean); var dfield : TDefField; dindex : TDefIndex; DefFields : TStringList; DefIndexs : TStringList; TempTable : TDbIsamTable; makethetable : boolean; x : integer; begin // Is there a table name? if trim(TableName) = '' then raise EAUTable.Create(NoTableName); if exists then MakeTheTable := Overwrite else MakeTheTable := true; if MakeTheTable then begin // now read the definition DefFields := TStringList.create; DefIndexs := TStringList.Create; TempTable := TDbIsamTable.Create(nil); TempTable.DatabaseName := Databasename; TempTable.SessionName := SessionName; TempTable.TableName := TableName; TempTable.InMemory := Inmemory; try LoadFieldDefs(DefFields); LoadIndexDefs(DefIndexs); for x := 0 to DefFields.Count - 1 do begin dfield := StringToDefField(DefFields[x]); with dField do TempTable.FieldDefs.Add(Fieldname,StringToDataType(FieldType),FieldLen,Req); end; for x := 0 to DefIndexs.count - 1 do begin dindex := stringtoDefIndex(DefIndexs[x]); with dindex do TempTable.IndexDefs.add(IdxName, IdxFields, IdxOpts); end; if exists then DeleteTable; tempTable.CreateTable; finally TempTable.Free; DefFields.Free; DefIndexs.Free; end; SuppressBackup := true; UpgradeStructure(true); SuppressBackup := false; end; end; function TDBISAMTableAU.GetCSV(const KeyValues: string): string; var sl : TStringList; p : integer; s : string; begin sl := TStringList.create; s := Keyvalues; p := pos(';',s); while p > 0 do begin sl.add(copy(s,1,p-1)); s := copy(s,p+1,length(s)); p := pos(';',s); end; if s > '' then sl.add(s); try result := GetCSV(sl); finally sl.free; end; end; procedure TDBISAMTableAU.CopyFromCSV(csv:string); var n, x : integer; sl : TStringList; fld : TField; begin sl := TStringList.create; try sl.CommaText := csv; if sl.Count < FieldCount then exit; n := FieldCount - 1; for x := 0 to n do begin fld := Fields[x]; try case fld.DataType of ftBoolean : if sl[x] = '' then fld.AsBoolean := false else fld.asstring := sl[x]; ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftDate, ftBCD, ftTime, ftDateTime : if sl[x] = '' then fld.AsInteger := 0 else fld.AsString := sl[x]; ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftBytes, ftVarBytes, ftTypedBinary, ftCursor : begin end; // do nothing else fld.asstring := sl[x]; end; except end; end; finally sl.free; end; end; procedure TDBISAMTableAU.CopyFromCSVWMemo(csv:string); var n, x : integer; sl : TStringList; fld : TField; begin sl := TStringList.create; try sl.CommaText := csv; if sl.Count < FieldCount then exit; n := FieldCount - 1; for x := 0 to n do begin fld := Fields[x]; try case fld.DataType of ftBoolean : if sl[x] = '' then fld.AsBoolean := false else fld.asstring := sl[x]; ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftDate, ftBCD, ftTime, ftDateTime : if sl[x] = '' then fld.AsInteger := 0 else fld.AsString := sl[x]; ftBlob, ftGraphic, ftBytes, ftVarBytes, ftTypedBinary, ftCursor : begin end; // do nothing ftMemo,ftFmtMemo : begin if trim(sl[x]) <> '' then fld.AsString := sl[x]; end; else fld.asstring := sl[x]; end; except end; end; finally sl.free; end; end; procedure TDBISAMTableAU.CopyKeyFromCSV(csv:string); var x : integer; sl : TStringList; kf : TStringList; begin sl := TStringList.create; kf := TStringList.create; try kf.commatext := PrimaryFieldsCSV; sl.CommaText := csv; for x := 0 to kf.Count - 1 do FieldByName(kf[x]).AsString := sl[x]; finally kf.free; sl.free; end; end; procedure TDBISAMTableAU.AppendFromCSV(csv: string); begin if not FindByCSV(csv) then begin Append; CopyFromCSV(csv); try post; except cancel; raise; end; end; RestoreState; end; procedure TDBISAMTableAU.AppendFromCSVWMemo(csv: string); begin if not FindByCSV(csv) then begin Append; CopyFromCSVWMemo(csv); try post; except cancel; raise; end; end; RestoreState; end; procedure TDbISAMTableAU.SaveState; begin SavedIndexName := IndexName; end; procedure TDbIsamTableAU.RestoreState; begin IndexName := SavedIndexName; end; procedure TDBISAMTableAU.UpdateFromCSV(csv: string); begin try if FindByCSV(csv) then begin Edit; CopyFromCSV(csv); try post; except cancel; raise; end; end; finally RestoreState; end; end; function TDBISAMTableAU.PrimaryFieldsCSV:string; var s : string; p : integer; begin indexdefs.Update; s := indexdefs[0].Fields; p := pos(';',s); while p > 0 do begin system.delete(s,p,1); system.insert(',',s,p); p := pos(';',s); end; result := s; end; procedure TDBISAMTableAU.SaveKeyCSV; begin try FSavedKey := GetCSV(indexdefs[0].Fields); except FSavedKey := ''; end; end; procedure TDBISAMTableAU.DeleteByKeyCSV(csv:string); begin try if FindByCSV(csv) then Delete; finally RestoreState; end; end; function TDBISAMTableAU.FindByCSV(csv: string): boolean; begin SaveState; IndexName := PrimaryKey; IndexDefs.Update; SetKey; CopyKeyFromCSV(csv); Result := GotoKey; end; procedure TDBISAMTableAU.DoBeforeDelete; begin inherited; end; procedure TDBISAMTableAU.DoAfterDelete; begin inherited; end; procedure TDBISAMTableAU.UpgradeStructure(force:boolean=false); var x,y : integer; dfield : TDefField; dindex : TDefIndex; DefFields : TStringList; DefIndexs : TStringList; MakeTheTable : boolean; fldnum : integer; foundfield : boolean; begin // Is there a table name? if trim(TableName) = '' then raise EAUTable.Create(NoTableName); if not exists then exit; if not force then begin try VerifyStructure; MakeTheTable := False; except MakeTheTable := True; end; end else MakeTheTable := true; if MakeTheTable then begin // now read the definition DefFields := TStringList.create; DefIndexs := TStringList.Create; try LoadFieldDefs(DefFields); LoadIndexDefs(DefIndexs); RestructureFieldDefs.Update; // get the current definition for x := 0 to DefFields.Count - 1 do begin dfield := StringToDefField(DefFields[x]); fldnum := restructurefielddefs.IndexOf(dfield.FieldName); if fldnum >= 0 then begin// the current field was found RestructureFieldDefs.Items[fldnum].DataType := StringToDataType(dfield.FieldType); RestructureFieldDefs.Items[fldnum].Name := dfield.fieldname; RestructureFieldDefs.Items[fldnum].Required := dfield.Req; RestructureFieldDefs.Items[fldnum].Size := dfield.FieldLen; end else with dField do RestructureFieldDefs.Add(FieldName, StringToDataType(FieldType), FieldLen, Req, '', '', '', '', fcNoChange, RestructureFieldDefs.Count + 1); end; // we've done the adds & updates, now we need to delete fields x := 0; while x < RestructureFieldDefs.Count do begin foundfield := false; for y := 0 to DefFields.Count - 1 do begin dfield := StringToDefField(DefFields[y]); if uppercase(dfield.FieldName) = uppercase(RestructureFieldDefs.Items[x].Name) then foundfield := true; if foundfield then break; end; if not foundfield then RestructureFieldDefs.Delete(x) else inc(x); end; // indexes RestructureIndexDefs.Clear; for x := 0 to DefIndexs.count - 1 do begin dindex := stringtoDefIndex(DefIndexs[x]); with dindex do RestructureIndexDefs.add(IdxName, IdxFields, IdxOpts, icDuplicateByte); end; RestructureTable(0,0,1,0,false,'','',1024,-1,SuppressBackup); finally DefFields.Free; DefIndexs.Free; end; end; end; function TDBISAMTableAU.GetMemoField(FieldName: string): string; var fld : TField; begin fld := fieldbyname(FieldName); if fld = nil then result := '' else begin if fld.DataType in [ftMemo, ftFmtMemo] then result := fld.AsString else result := ''; end; end; procedure TDBISAMTableAU.SetMemoField(KeyFields, FieldName, AMemo: string); var fld : TField; begin fld := fieldbyname(FieldName); if fld = nil then exit; try if FindByCSV(KeyFields) then begin Edit; fld.AsString := AMemo; try post; except cancel; raise; end; end; finally RestoreState; end; end; procedure TDBISAMTableAU.OpenUp; begin if not exists then MakeTable(false); (* try Active := true; except Active := false; end; *) // Bill took away. DBISAM2 doesn't throw an exception when opening and the index formats differ if not active then begin try // this will fail if its a memory table... #John if not InMemory then VerifyStructure; Active := true; except on E : Exception do begin if (E is EDBISAMEngineError) then begin case EDBISAMEngineError(E).Errors[0].ErrorCode of DBISAM_ENDOFBLOB, DBISAM_HEADERCORRUPT, DBISAM_FILECORRUPT, DBISAM_MEMOCORRUPT, DBISAM_INDEXCORRUPT, DBISAM_READERR, DBISAM_WRITEERR, DBISAM_INVALIDBLOBOFFSET, DBISAM_INVALIDIDXDESC, DBISAM_INVALIDBLOBLEN: if AutoRepair then RepairTable; end; end else if (E is EAUTable) then UpgradeStructure; end; end; Active := true; end; end; procedure TDBISAMTableAU.SetAutoModCount(const Value: boolean); begin FAutoModCount := Value; end; procedure TDBISAMTableAU.DoBeforeEdit; begin inherited; if AutoModCount and (recordcount > 0) then begin try ModCount := fieldbyname('MODCOUNT').AsInteger; except ModCount := 0; end; end; end; procedure TDBISAMTableAU.SetModCount(const Value: integer); begin FModCount := Value; end; procedure TDBISAMTableAU.DoBeforePost; var MCount : integer; begin if AutoModCount and (State = dsEdit) then begin try MCount := fieldByName('ModCount').asInteger; except MCount := 0; end; if ModCount <> MCount then raise exception.Create('Record has been changed by another user.') else begin ModCount := ModCount + 1; fieldbyname('ModCount').asinteger := ModCount; end; end; inherited; end; procedure TDBISAMTableAU.SetAutoRepair(const Value: boolean); begin FAutoRepair := Value; end; { TDBISAMQueryAU } constructor TDBISAMQueryAU.create(AOwner: TComponent); begin inherited; SuppressBackup := false; RequestLive := true; end; constructor TDBISAMQueryAU.create(AOwner: TComponent; ADatabase: TDbisamDatabase; ATableName: string); begin inherited create(AOwner); Databasename := ADatabase.DatabaseName; SessionName := ADatabase.SessionName; SuppressBackup := false; RequestLive := true; end; procedure TDBISAMQueryAU.DoAfterDelete; begin inherited; end; procedure TDBISAMQueryAU.DoBeforeDelete; begin inherited; end; procedure TDBISAMQueryAU.DoBeforeEdit; begin inherited; if AutoModCount and (recordcount > 0) then begin try ModCount := fieldbyname('MODCOUNT').AsInteger; except ModCount := 0; end; end; end; procedure TDBISAMQueryAU.DoBeforePost; var MCount : integer; begin if AutoModCount and (State = dsEdit) then begin try MCount := fieldByName('ModCount').asInteger; except MCount := 0; end; if ModCount <> MCount then raise exception.Create('Record has been changed by another user.') else begin ModCount := ModCount + 1; fieldbyname('ModCount').asinteger := ModCount; end; end; inherited; end; function TDBISAMQueryAU.GetCSV(const KeyValues: string): string; var sl : TStringList; p : integer; s : string; begin sl := TStringList.create; s := Keyvalues; p := pos(';',s); while p > 0 do begin sl.add(copy(s,1,p-1)); s := copy(s,p+1,length(s)); p := pos(';',s); end; if s > '' then sl.add(s); try result := GetCSV(sl); finally sl.free; end; end; function TDBISAMQueryAU.GetCSV(const KeyValues: TStrings): string; var x : integer; n : integer; s : string; fld : TField; begin result := ''; n := keyValues.count - 1; if n >= 0 then begin for x := 0 to n do begin fld := FieldByName(KeyValues[x]); if fld <> nil then begin if fld.FieldKind = fkData then begin try s := ''; case fld.DataType of ftBoolean : case fld.AsBoolean of true : s := 'True'; false : s := 'False'; end; ftInteger : s := IntToStr(fld.AsInteger); ftFloat : s := FloatToStr(fld.AsFloat); ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftBytes, ftVarBytes, ftTypedBinary, ftCursor : s := ''; else s := fld.AsString; end; result := result + csvquote(s); except result := result + csvquote(' '); // do nothing if the field is bad end; if x < n then result := result + ','; end; end; end; end else begin n := FieldCount - 1; for x := 0 to n do begin fld := Fields[x]; if fld.FieldKind = fkData then begin try s := ''; case fld.DataType of ftBoolean : case fld.AsBoolean of true : s := s + 'True'; false : s := s + 'False'; end; else s := fld.AsString; end; result := result + csvquote(s); except result := result + csvquote(' '); end; if x < n then result := result + ','; end; end; end; end; procedure TDBISAMQueryAU.GetTableAsCSV(var sl: TStringList; OptionalList: string); begin sl.Clear; try First; while not EOF do begin sl.Add(GetCSV(OptionalList)); Next; end; except sl.Clear; end; end; procedure TDBISAMQueryAU.post; begin inherited; end; procedure TDBISAMQueryAU.SetAutoModCount(const Value: boolean); begin FAutoModCount := Value; end; procedure TDBISAMQueryAU.SetModCount(const Value: integer); begin FModCount := Value; end; end.
unit Base.LoadConfig; interface Uses System.Classes, System.SysUtils, Vcl.Forms, System.JSON, Base.System.JSON.Helper, Base.System.JsonFiles, Vcl.ComCtrls, JSON.Conection, JSON.LangDB, JSON.Status, Log.DB, Base.Def, Base.Color; Type TLoadConfig = Class Private // Private Classes function LoadConection(Log: TRichEdit): Boolean; function LoadLangDB(Log: TRichEdit): Boolean; function LoadBaseStatus(Log: TRichEdit): Boolean; Public // Public Classes Constructor Create; // declaração do metodo construtor procedure LoadFiles(Log: TRichEdit); Destructor Destroy; Override; // declaração do metodo destrutor End; Var BaseClass: Array [0 .. 4] of TJsonStatus; implementation Uses Base.Struct; constructor TLoadConfig.Create; Var I: Integer; begin JsonConection := TjsonConect.Create; JsonLangDB := tJsonLangDB.Create; LogDB := Tlog.Create; for I := 0 to cBase do begin BaseClass[I] := TJsonStatus.Create; end; end; function TLoadConfig.LoadConection(Log: TRichEdit): Boolean; begin cFile := JsonConection.FolderGame + FileConexao; jFile := TJsonFile.Create(cFile); try JsonConection.DB := jFile.ReadString('MYSQL', 'DB', ''); JsonConection.USER := jFile.ReadString('MYSQL', 'USER', ''); JsonConection.SENHA := jFile.ReadString('MYSQL', 'SENHA', ''); JsonConection.PORTA_MYSQL := jFile.ReadInteger('MYSQL', 'PORT', 0); JsonConection.IP := jFile.ReadString('MYSQL', 'IP', ''); JsonConection.MAXCHANNEL := jFile.ReadInteger('CHANNEL', 'MAXCHANNEL', 0); JsonConection.PORTA_CHANNEL1 := jFile.ReadInteger('CHANNEL', 'PORT1', 0); JsonConection.IP_CHANNEL1 := jFile.ReadString('CHANNEL', 'IP1', ''); JsonConection.PORTA_CHANNEL2 := jFile.ReadInteger('CHANNEL', 'PORT2', 0); JsonConection.IP_CHANNEL2 := jFile.ReadString('CHANNEL', 'IP2', ''); JsonConection.PORTA_CHANNEL3 := jFile.ReadInteger('CHANNEL', 'PORT3', 0); JsonConection.IP_CHANNEL3 := jFile.ReadString('CHANNEL', 'IP3', ''); JsonConection.PORTA_CHANNEL4 := jFile.ReadInteger('CHANNEL', 'PORT4', 0); JsonConection.IP_CHANNEL4 := jFile.ReadString('CHANNEL', 'IP4', ''); JsonConection.PORTA_CHANNEL5 := jFile.ReadInteger('CHANNEL', 'PORT5', 0); JsonConection.IP_CHANNEL5 := jFile.ReadString('CHANNEL', 'IP5', ''); Log.Clear; Log.SelAttributes.Color := Laranja; Log.Lines.Add ('############################### SERVER EMULATOR ###############################'); Log.Lines.Add('Banco de Dados: Mysql'); jFile.ReadSectionValues('MYSQL', Log.Lines); LogDB.DBLog(Log, FileConexao + ':', 0); LogDB.DBLog(Log, '.......................................................................' + '............................................................OK!!!', 0); Result := True; except on E: Exception do begin LogDB.DBLog(Log, E.Message, 1); LogDB.DBLog(Log, FileConexao + '...........................................................Falha.', 1); Result := False; end; end; jFile.Free; end; function TLoadConfig.LoadLangDB(Log: TRichEdit): Boolean; begin cFile := JsonConection.FolderGame + FileLangDB; jFile := TJsonFile.Create(cFile); try JsonLangDB.NotAccount := jFile.ReadString('LangDB', 'NotAccount', ''); JsonLangDB.NumericError := jFile.ReadString('LangDB', 'NumericError', ''); JsonLangDB.LoggedIn := jFile.ReadString('LangDB', 'LoggedIn', ''); JsonLangDB.Blocked := jFile.ReadString('LangDB', 'Blocked', ''); JsonLangDB.Baned := jFile.ReadString('LangDB', 'Baned', ''); JsonLangDB.ResetPass := jFile.ReadString('LangDB', 'ResetPass', ''); JsonLangDB.NotFound := jFile.ReadString('LangDB', 'NotFound', ''); JsonLangDB.CharExists := jFile.ReadString('LangDB', 'CharExists', ''); JsonLangDB.followingError := jFile.ReadString('LangDB', 'FollowingError', ''); LogDB.DBLog(Log, FileLangDB + ':', 0); LogDB.DBLog(Log, '.......................................................................' + '............................................................OK!!!', 0); Result := True; except on E: Exception do begin Result := False; LogDB.DBLog(Log, E.Message, 1); LogDB.DBLog(Log, FileLangDB + '...........................................................Falha.', 1); end; end; jFile.Free; end; function TLoadConfig.LoadBaseStatus(Log: TRichEdit): Boolean; begin cFile := JsonConection.FolderGame + FileBaseStatus; jFile := TJsonFile.Create(cFile); Try // Carrega TK BASE BaseClass[TK]._Str := jFile.ReadInteger('TK', 'STR', 0); BaseClass[TK].INT := jFile.ReadInteger('TK', 'INT', 0); BaseClass[TK].DEX := jFile.ReadInteger('TK', 'DEX', 0); BaseClass[TK].CON := jFile.ReadInteger('TK', 'CON', 0); // Carrega FM BASE BaseClass[FM]._Str := jFile.ReadInteger('FM', 'STR', 0); BaseClass[FM].INT := jFile.ReadInteger('FM', 'INT', 0); BaseClass[FM].DEX := jFile.ReadInteger('FM', 'DEX', 0); BaseClass[FM].CON := jFile.ReadInteger('FM', 'CON', 0); // Carrega BM BASE BaseClass[BM]._Str := jFile.ReadInteger('BM', 'STR', 0); BaseClass[BM].INT := jFile.ReadInteger('BM', 'INT', 0); BaseClass[BM].DEX := jFile.ReadInteger('BM', 'DEX', 0); BaseClass[BM].CON := jFile.ReadInteger('BM', 'CON', 0); // Carrega HT BASE BaseClass[HT]._Str := jFile.ReadInteger('HT', 'STR', 0); BaseClass[HT].INT := jFile.ReadInteger('HT', 'INT', 0); BaseClass[HT].DEX := jFile.ReadInteger('HT', 'DEX', 0); BaseClass[HT].CON := jFile.ReadInteger('HT', 'CON', 0); // BASE BaseClass[cBase].HP := jFile.ReadInteger('BASE', 'HP', 0); BaseClass[cBase].MP := jFile.ReadInteger('BASE', 'MP', 0); BaseClass[cBase].PosX := jFile.ReadInteger('BASE', 'PosX', 0); BaseClass[cBase].PosY := jFile.ReadInteger('BASE', 'PosY', 0); BaseClass[cBase].GemX := jFile.ReadInteger('BASE', 'GemX', 0); BaseClass[cBase].GemY := jFile.ReadInteger('BASE', 'GemY', 0); LogDB.DBLog(Log, FileBaseStatus + ':', 0); LogDB.DBLog(Log, '.......................................................................' + '............................................................OK!!!', 0); Result := True; except on E: Exception do begin LogDB.DBLog(Log, E.Message, 1); LogDB.DBLog(Log, FileBaseStatus + '...........................................................Falha.', 1); Result := False; end; end; jFile.Free; end; procedure TLoadConfig.LoadFiles(Log: TRichEdit); begin LoadConection(Log); LoadLangDB(Log); LoadBaseStatus(Log); end; destructor TLoadConfig.Destroy; Var I: Integer; begin JsonConection.Free; JsonLangDB.Free; LogDB.Free; for I := 0 to cBase do begin BaseClass[I].Free; end; inherited; end; end.
{ Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Runtime datatype representations } unit xpr.str; {$I express.inc} interface {$I objh.inc} uses SysUtils, xpr.express, xpr.objbase; type TStringObject = class(TEpObject) value: epString; constructor Create(AValue:epString); function Copy(gcGen:Byte=0): TEpObject; override; function DeepCopy: TEpObject; override; function AsChar: epChar; override; function AsString: epString; override; function AsBool: Boolean; override; function AsInt: epInt; override; procedure ASGN(other:TEpObject; var dest:TEpObject); override; procedure INPLACE_ADD(other:TEpObject); override; procedure ADD(other:TEpObject; var dest:TEpObject); override; procedure GET_ITEM(constref index:TEpObject; var dest:TEpObject); override; procedure SET_ITEM(constref index:TEpObject; constref other:TEpObject); override; end; procedure SetStringDest(var dest:TEpObject; constref value:epString); inline; implementation uses xpr.utils, xpr.errors, xpr.mmgr, xpr.bool, xpr.int, xpr.char; procedure SetStringDest(var dest:TEpObject; constref value:epString); var GC:TGarbageCollector; begin assert(dest <> nil, 'dest is nil'); if dest.ClassType = TStringObject then TStringObject(dest).value := value else begin GC := TGarbageCollector(dest.gc); GC.Release(dest); dest := GC.AllocString(value); end; end; constructor TStringObject.Create(AValue:epString); begin self.Value := AValue; end; function TStringObject.Copy(gcGen:Byte=0): TEpObject; begin Result := TGarbageCollector(GC).AllocString(self.value, gcGen); end; function TStringObject.DeepCopy: TEpObject; begin Result := TGarbageCollector(GC).AllocString(self.value); end; function TStringObject.AsChar: epChar; begin if Length(self.value) = 1 then Result := self.Value[1] else inherited; end; function TStringObject.AsString: epString; begin Result := self.value; end; function TStringObject.AsBool: Boolean; begin Result := Length(self.value) > 0; end; function TStringObject.AsInt: epInt; begin raise E_NOT_IMPLEMENTED; end; procedure TStringObject.ASGN(other:TEpObject; var dest:TEpObject); begin if other.ClassType = TStringObject then self.value := TStringObject(other).value else inherited; end; procedure TStringObject.INPLACE_ADD(other:TEpObject); var l:Int32; begin L := Length(self.value); if (other.ClassType = TStringObject) then begin if (Length(TStringObject(other).value) > 0) and (Length(self.value) > 0) then begin SetLength(self.value, L+Length(TStringObject(other).value)); Move( TStringObject(other).value[1], self.value[1+L], Length(TStringObject(other).value)*SizeOf(epChar) ); end else self.value += TStringObject(other).value end else if (other.ClassType = TCharObject) then begin SetLength(self.value, L+1); self.value[1+L] := TCharObject(other).value end else raise E_NOT_IMPLEMENTED; end; procedure TStringObject.ADD(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TStringObject) then SetStringDest(dest, self.value + TStringObject(other).value) else if (other.ClassType = TCharObject) then SetStringDest(dest, self.value + TCharObject(other).value) else inherited; end; procedure TStringObject.GET_ITEM(constref index:TEpObject; var dest:TEpObject); begin if index.ClassType = TIntObject then SetCharDest(dest, self.value[1+TIntObject(index).value]) else SetCharDest(dest, self.value[1+index.AsInt]); end; procedure TStringObject.SET_ITEM(constref index:TEpObject; constref other:TEpObject); begin self.value[1+index.AsInt] := TCharObject(other).AsChar; end; end.
{ @abstract(@name contains the main form of Help Generator and a class for saving and restoring project settings.) @author(Richard B. Winston <rbwinst@usgs.gov>) @created(2004-11-28) @lastmod(2005-5-16) @name contains the main form of Help Generator. It also defines @link(THelpGeneratorProjectOptions) which is used to save project options to a file and restore them again. This file is made available by the U.S. Geological Survey (USGS) to be used in the public interest and the advancement of science. You may, without any fee or cost, use, copy, modify, or distribute this file, and any derivative works thereof, and its supporting documentation, subject to the following restrictions and understandings. If you distribute copies or modifications of this file and related material, make sure the recipients receive a copy of this notice and receive or can get a copy of the original distribution. If the software and (or) related material are modified and distributed, it must be made clear that the recipients do not have the original and are informed of the extent of the modifications. For example, modified files must include a prominent notice stating the modifications, author, and date. This restriction is necessary to guard against problems introduced in the software by others, reflecting negatively on the reputation of the USGS. This file is public property. You may charge fees for distribution, warranties, and services provided in connection with this file or derivative works thereof. The name USGS can be used in any advertising or publicity to endorse or promote any products or commercial entity using this software if specific written permission is obtained from the USGS. The user agrees to appropriately acknowledge the authors and the USGS in publications that result from the use of this file or in products that include this file in whole or in part. Because the software and related material is free (other than nominal materials and handling fees) and provided "as is", the authors, USGS, or the United States Government have made no warranty, expressed or implied, as to the accuracy or completeness and are not obligated to provide the user with any support, consulting, training or assistance of any kind with regard to the use, operation, and performance of this software nor to provide the user with any updates, revisions, new versions or "bug fixes". The user assumes all risk for any damages whatsoever resulting from loss of use, data, or profits arising in connection with the access, use, quality, or performance of this software. } unit frmHelpGeneratorUnit; interface uses {$IFDEF LINUX} Libc, {$ENDIF} {$IFDEF MSWINDOWS} Windows, ShellAPI, Qt, {$ENDIF} WebUtils, SysUtils, Types, Classes, Variants, QTypes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QMenus, QCheckLst, QButtons, QExtCtrls, {PasDoc_Gen, PasDoc_GenHtml, PasDoc_Base, PasDoc_Types, PasDoc_Languages, PasDoc_GenHtmlHelp, PasDoc_GenLatex,} {CustomProjectOptions,} ConsolProjectOptionsUnit, QFileCtrls, Contnrs; type // @abstract(TfrmHelpGenerator is the class of the main form of Help // Generator.) Its published fields are mainly components that are used to // save the project settings. TfrmHelpGenerator = class(TForm) OpenDialog1: TOpenDialog; pcMain: TPageControl; tabGenerate: TTabSheet; // memoMessages displays compiler warnings. See also @link(seVerbosity); memoMessages: TMemo; tabOptions: TTabSheet; // @name controls whether of private, protected, public, published and // automated properties, methods, events, and fields will be included in // generated output. clbMethodVisibility: TCheckListBox; Label1: TLabel; // @name is used to set the language in which the web page will // be written. Of course, this only affects tha language for the text // generated by the program, not the comments about the program. comboLanguages: TComboBox; Label2: TLabel; tabSourceFiles: TTabSheet; // @name holds the complete paths of all the source files // in the project. memoFiles: TMemo; Panel3: TPanel; // Click @name to select one or more sorce files for the // project. btnBrowseSourceFiles: TButton; // @name has the path of the directory where the web files will // be created. edOutput: TEdit; Label3: TLabel; Panel1: TPanel; btnGenerate: TButton; tabIncludeDirectories: TTabSheet; // The lines in @name are the paths of the files that // may have include files that are part of the project. memoIncludeDirectories: TMemo; Panel2: TPanel; // Click @name to select a directory that may // have include directories. btnBrowseIncludeDirectory: TButton; // Click @name to select the directory in whick the // output files will be created. btnBrowseOutputDirectory: TButton; Label6: TLabel; // @name is used to set the name of the project. edProjectName: TEdit; SaveDialog1: TSaveDialog; OpenDialog2: TOpenDialog; MainMenu1: TMainMenu; miFile: TMenuItem; Open1: TMenuItem; Save1: TMenuItem; Exit1: TMenuItem; Panel4: TPanel; // @name controls the severity of the messages that are displayed. seVerbosity: TSpinEdit; Label7: TLabel; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; Label10: TLabel; // @name determines what sort of files will be created comboGenerateFormat: TComboBox; Label11: TLabel; New1: TMenuItem; tabDefines: TTabSheet; memoDefines: TMemo; About1: TMenuItem; edIntroduction: TEdit; Label13: TLabel; btnIntroduction: TButton; edConclusion: TEdit; Label14: TLabel; btnConclusion: TButton; odExtraFiles: TOpenDialog; tabMoreOptions: TTabSheet; cbUseGraphVizClasses: TCheckBox; cbUseGraphVizUses: TCheckBox; edGraphVizDotLocation: TEdit; btnGraphViz: TButton; Label15: TLabel; odDotLocation: TOpenDialog; memoHyphenatedWords: TMemo; Label16: TLabel; rgLineBreakQuality: TRadioGroup; Label4: TLabel; Label5: TLabel; Label17: TLabel; edTitle: TEdit; miHelp: TMenuItem; Help2: TMenuItem; Label18: TLabel; comboLatexGraphics: TComboBox; Label12: TLabel; edBrowser: TEdit; btnBrower: TButton; ProgramDialog: TOpenDialog; Label19: TLabel; edPasDocConsole: TEdit; btnPasDocConsole: TButton; Label20: TLabel; lbNavigator: TListBox; Splitter1: TSplitter; tabWebOptions: TTabSheet; tabLatexOptions: TTabSheet; tabLocations: TTabSheet; Panel8: TPanel; memoFooter: TMemo; Label9: TLabel; Panel9: TPanel; memoHeader: TMemo; Label8: TLabel; Splitter2: TSplitter; Label21: TLabel; edHtmlHelpContents: TEdit; btnHtmlHelpConents: TButton; Label22: TLabel; clbSort: TCheckListBox; tabSpellChecking: TTabSheet; Panel10: TPanel; cbCheckSpelling: TCheckBox; comboSpellLanguages: TComboBox; Label23: TLabel; Label24: TLabel; memoCheckSpellingIgnoreWords: TMemo; edSpellUrl: TEdit; Label25: TLabel; Label26: TLabel; edGraphVizUrl: TEdit; {procedure PasDoc1Warning(const MessageType: TMessageType; const AMessage: string; const AVerbosity: Cardinal); } procedure btnBrowseSourceFilesClick(Sender: TObject); procedure clbMethodVisibilityClickCheck(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnGenerateClick(Sender: TObject); procedure btnBrowseIncludeDirectoryClick(Sender: TObject); procedure btnBrowseOutputDirectoryClick(Sender: TObject); procedure Open1Click(Sender: TObject); procedure Save1Click(Sender: TObject); procedure Exit1Click(Sender: TObject); procedure edProjectNameChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure New1Click(Sender: TObject); procedure comboGenerateFormatChange(Sender: TObject); procedure About1Click(Sender: TObject); procedure btnIntroductionClick(Sender: TObject); procedure btnConclusionClick(Sender: TObject); procedure btnGraphVizClick(Sender: TObject); procedure cbUseGraphVizClick(Sender: TObject); procedure edGraphVizDotLocationChange(Sender: TObject); procedure Help2Click(Sender: TObject); procedure pcMainChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure pcMainChanging(Sender: TObject; var AllowChange: Boolean); procedure pcMainPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); procedure seVerbosityChanged(Sender: TObject; NewValue: Integer); procedure btnBrowerClick(Sender: TObject); procedure edPasDocConsoleChange(Sender: TObject); procedure lbNavigatorClick(Sender: TObject); procedure edHtmlHelpContentsChange(Sender: TObject); procedure btnHtmlHelpConentsClick(Sender: TObject); procedure comboLanguagesChange(Sender: TObject); procedure cbCheckSpellingClick(Sender: TObject); procedure comboSpellLanguagesChange(Sender: TObject); procedure memoCheckSpellingIgnoreWordsChange(Sender: TObject); private // @name is @true when the user has changed the project settings. // Otherwise it is @false. Changed: boolean; DefaultDirectives: TStringList; NavigateList: TObjectList; MisspelledWords: TStringList; procedure SaveChanges(var Action: TCloseAction); procedure SetDefaults; procedure SetEdVizGraphDotLocationColor; function SaveIt: boolean; procedure ShowPasDocMessage(const Text: string); procedure GenerateNavigateList; procedure OpenAFile(const FileName: string); { Private declarations } public { Public declarations } end; TNavigateItem = class(TObject) PageIndex: integer; end; {@abstract(@classname is used to store and retrieve the settings of a project.) Each published property reads or writes a property of @link(frmHelpGenerator). It also inherits methods for running the TPasDoc component.} THelpGeneratorProjectOptions = class(TConsolHelpProjectOptions) private protected function GetChanged: boolean; override; function GetConclusion: string; override; function GetDirectives: TSTrings; override; function GetFooter: TStrings; override; function GetGraphVizDotLocation: string; override; function GetHeader: TStrings; override; function GetHtmlHelpContents: string; override; {function GetHtmlDocGeneratorComponent: THtmlDocGenerator; override; function GetHTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator; override; } function GetHyphenatedWords: TStrings; override; function GetIncludeAutomated: boolean; override; function GetIncludeDirectories: TStrings; override; function GetIncludeImplicit: boolean; override; function GetIncludeStrictPrivate: boolean; override; function GetIncludePrivate: boolean; override; function GetIncludeStrictProtected: boolean; override; function GetIncludeProtected: boolean; override; function GetIncludePublic: boolean; override; function GetIncludePublished: boolean; override; function GetIntroduction: string; override; //function GetLanguage: TLanguageID; override; function GetLanguageString: string; override; function GetLatexGraphicsPackage: TLatexGraphicsPackage; override; function GetLineBreakQuality: TLineBreakQuality; override; function GetOutputDirectory: string; override; function GetOutputType: TOutputType; override; //function GetPasDocComponent: TPasDoc; override; function GetProjectName: string; override; function GetSortOptions: TSortOptions; override; function GetSourceFiles: TStrings; override; function GetSpellChecking: boolean; override; function GetSpellCheckIgnoreWords: TStrings; override; function GetSpellCheckLanguage: string; override; function GetSpellCheckLanguageCode: string; override; //function GetTexDocGeneratorComponent: TTexDocGenerator; override; function GetTitle: string; override; function GetUseGraphVizClasses: boolean; override; function GetUseGraphVizUses: boolean; override; function GetVerbosity: integer; override; procedure SetChanged(const Value: boolean); override; procedure SetConclusion(const Value: string); override; procedure SetDefaultActivePage; override; procedure SetDirectives(const Value: TSTrings); override; procedure SetFooter(const Value: TStrings); override; procedure SetGraphVizDotLocation(const Value: string); override; procedure SetHeader(const Value: TStrings); override; procedure SetHtmlHelpContents(const AValue: string); override; procedure SetHyphenatedWords(const Value: TStrings); override; procedure SetIncludeAutomated(const Value: boolean); override; procedure SetIncludeDirectories(const Value: TStrings); override; procedure SetIncludeImplicit(const Value: boolean); override; procedure SetIncludeStrictPrivate(const Value: boolean); override; procedure SetIncludePrivate(const Value: boolean); override; procedure SetIncludeStrictProtected(const Value: boolean); override; procedure SetIncludeProtected(const Value: boolean); override; procedure SetIncludePublic(const Value: boolean); override; procedure SetIncludePublished(const Value: boolean); override; procedure SetIntroduction(const Value: string); override; procedure SetLanguageString(const Value: string); override; //procedure SetLanguage(const Value: TLanguageID); override; procedure SetLatexGraphicsPackage(const Value: TLatexGraphicsPackage); override; procedure SetLineBreakQuality(const Value: TLineBreakQuality); override; procedure SetOutputDirectory(const Value: string); override; procedure SetOutputType(const Value: TOutputType); override; procedure SetProjectName(const Value: string); override; procedure SetSortOptions(Const Value: TSortOptions); override; procedure SetSourceFiles(const Value: TStrings); override; procedure SetSpellChecking(const Value: boolean); override; procedure SetSpellCheckIgnoreWords(const Value: TStrings); override; procedure SetSpellCheckLanguage(const Value: string); override; procedure SetTitle(const Value: string); override; procedure SetUseGraphVizClasses(const Value: boolean); override; procedure SetUseGraphVizUses(const Value: boolean); override; procedure SetVerbosity(const Value: integer); override; function GetPasDocConsoleLocation: string; override; end; // @name saves the location of the VizGraph dot program. T_ConsoleCLX_Ini = class(TCustomIniFile) protected function GetGraphVizDotLocation: string; override; procedure SetGraphVizDotLocation(const Value: string); override; function GetBrowserLocation: string; override; procedure SetBrowserLocation(const Value: string); override; function GetPasDocConsoleLocation: string; override; procedure SetPasDocConsoleLocation(const Value: string); override; end; var // @name is the main form of Help Generator frmHelpGenerator: TfrmHelpGenerator; implementation {$R *.xfm} uses {PasDoc_Items,} ASpellLanguages, frmAboutUnit; {procedure TfrmHelpGenerator.PasDoc1Warning(const MessageType: TMessageType; const AMessage: string; const AVerbosity: Cardinal); begin memoMessages.Lines.Add(AMessage); Application.ProcessMessages; end; } procedure TfrmHelpGenerator.btnBrowseSourceFilesClick(Sender: TObject); var Directory: string; FileIndex: integer; Files: TStringList; begin if OpenDialog1.Execute then begin Files := TStringList.Create; try if edOutput.Text = '' then begin edOutput.Text := ExtractFileDir(OpenDialog1.FileName); end; Files.Sorted := True; Files.Duplicates := dupIgnore; Files.AddStrings(memoFiles.Lines); Files.AddStrings(OpenDialog1.Files); memoFiles.Lines := Files; for FileIndex := 0 to OpenDialog1.Files.Count - 1 do begin Directory := ExtractFileDir(OpenDialog1.Files[FileIndex]); if memoIncludeDirectories.Lines.IndexOf(Directory) < 0 then begin memoIncludeDirectories.Lines.Add(Directory); end; end; finally Files.Free; end; end; end; procedure TfrmHelpGenerator.clbMethodVisibilityClickCheck(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.SetDefaults; var ProjectOptions: THelpGeneratorProjectOptions; begin ProjectOptions := THelpGeneratorProjectOptions.Create(nil); try ProjectOptions.SetDefaults; finally ProjectOptions.Free; end; end; procedure TfrmHelpGenerator.GenerateNavigateList; var Index: integer; Item: TNavigateItem; begin lbNavigator.Items.Clear; NavigateList.Clear; for Index := 0 to pcMain.PageCount -1 do begin if pcMain.Pages[Index].Enabled then begin lbNavigator.Items.Add(pcMain.Pages[Index].Caption); Item := TNavigateItem.Create; Item.PageIndex := Index; NavigateList.Add(Item); end; end; end; procedure TfrmHelpGenerator.FormCreate(Sender: TObject); var LanguageIndex: integer; Index: integer; FileName: string; begin MisspelledWords:= TStringList.Create; MisspelledWords.Sorted := True; MisspelledWords.Duplicates := dupIgnore; NavigateList:= TObjectList.Create; GenerateNavigateList; comboSpellLanguages.Items := LanguageMap; for Index := 0 to pcMain.PageCount -1 do begin pcMain.Pages[Index].TabVisible := False; end; edPasDocConsoleChange(nil); ReadIniFile(T_ConsoleCLX_Ini); {$IFDEF LINUX} odDotLocation.Filter := '(dot)|dot'; ProgramDialog.Filter := ''; {$ENDIF} THelpGeneratorProjectOptions.DefaultDefines(memoDefines.Lines); comboLanguages.Items.Capacity := MaxLanguages + 1; for LanguageIndex := 0 to MaxLanguages do begin comboLanguages.Items.Add(Languages[LanguageIndex].Name); end; GetVisibilityNames(clbMethodVisibility.Items); Constraints.MinWidth := Width; Constraints.MinHeight := Height; DefaultDirectives := TStringList.Create; DefaultDirectives.Assign(memoDefines.Lines); SetDefaults; if ParamCount >= 1 then begin FileName := ParamStr(1); If FileExists(FileName) then begin OpenDialog2.FileName := FileName; OpenAFile(OpenDialog2.FileName); end; end; end; procedure TfrmHelpGenerator.btnGenerateClick(Sender: TObject); var URL: string; BrowserPath: string; Settings: THelpGeneratorProjectOptions; begin if not FileExists(edPasDocConsole.Text) then begin pcMain.ActivePage := tabLocations; MessageDlg('The location of PasDoc consol has not been specified correctly.', mtError, [mbOK], 0); Exit; end; {$IFDEF MSWINDOWS} if (cbUseGraphVizUses.Checked or cbUseGraphVizClasses.Checked) and not FileExists(edGraphVizDotLocation.Text) then begin if MessageDlg('The location of the VizGraph "dot" program was not' + ' found. Do you want to continue?', QDialogs.mtWarning, [mbYes, mbNo], 0) <> mrYes then begin Exit; end; end; {$ENDIF} Screen.Cursor := crHourGlass; btnGenerate.Enabled := False; miFile.Enabled := False; miHelp.Enabled := False; lbNavigator.Enabled := False; try memoMessages.Clear; MisspelledWords.Clear; Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.RunPasDocConsol(ShowPasDocMessage); Settings.RunVizGraph(ShowPasDocMessage); finally Settings.Free; end; if cbCheckSpelling.Checked and (MisspelledWords.Count > 0) then begin MemoMessages.Lines.Add(''); MemoMessages.Lines.Add('misspelled words'); MemoMessages.Lines.AddStrings(MisspelledWords); Application.ProcessMessages; end; if comboGenerateFormat.ItemIndex in [0, 1] then begin MemoMessages.Lines.Add(''); MemoMessages.Lines.Add('Starting web browser'); Application.ProcessMessages; URL := FileToURL(edOutput.Text + PathDelim + 'index.html'); BrowserPath := edBrowser.Text; LaunchURL(BrowserPath, URL); end; finally Screen.Cursor := crDefault; btnGenerate.Enabled := True; miFile.Enabled := True; miHelp.Enabled := True; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.btnBrowseIncludeDirectoryClick( Sender: TObject); var directory: WideString; begin // directory is an out variable so it doesn't need to be // specified before calling SelectDirectory. if SelectDirectory('Include directory', '', directory) then begin if memoIncludeDirectories.Lines.IndexOf(directory) < 0 then begin memoIncludeDirectories.Lines.Add(directory); end else begin MessageDlg('The directory you selected, (' + directory + ') is already included.', QDialogs.mtInformation, [mbOK], 0); end; end; end; procedure TfrmHelpGenerator.btnBrowseOutputDirectoryClick(Sender: TObject); var directory: WideString; begin // directory is an out variable so it doesn't need to be // specified before calling SelectDirectory. if SelectDirectory('Output directory', '', directory) then begin edOutput.Text := directory; Changed := True; end; end; procedure TfrmHelpGenerator.OpenAFile(const FileName: string); var Settings: THelpGeneratorProjectOptions; begin SaveDialog1.FileName := FileName; Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.ReadFromComponentFile(FileName); Caption := ExtractFileName(FileName) + ': Help Generator'; finally Settings.Free; end; Changed := False; end; procedure TfrmHelpGenerator.Open1Click(Sender: TObject); var Action: TCloseAction; begin lbNavigator.Enabled := False; try if Changed then begin Action := caFree; SaveChanges(Action); if Action = caNone then begin Exit; end; end; if OpenDialog2.Execute then begin OpenAFile(OpenDialog2.FileName); end; finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; function TfrmHelpGenerator.SaveIt: boolean; var Settings: THelpGeneratorProjectOptions; begin result := SaveDialog1.Execute; if result then begin Settings := THelpGeneratorProjectOptions.Create(nil); try Settings.SaveToComponentFile(SaveDialog1.FileName); finally Settings.Free; end; Changed := False; end; end; procedure TfrmHelpGenerator.Exit1Click(Sender: TObject); begin lbNavigator.Enabled := False; try Close finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.edProjectNameChange(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.SaveChanges(var Action: TCloseAction); var MessageResult: integer; begin if Changed then begin MessageResult := MessageDlg( 'Do you want to save the settings for this project?', QDialogs.mtInformation, [mbYes, mbNo, mbCancel], 0); case MessageResult of mrYes: begin if not SaveIt then begin Action := caNone; end; end; mrNo: begin // do nothing. end; else begin Action := caNone; end; end; end; end; procedure TfrmHelpGenerator.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveChanges(Action); if Action <> caNone then begin DefaultDirectives.Free; end; end; procedure TfrmHelpGenerator.New1Click(Sender: TObject); var Action: TCloseAction; begin lbNavigator.Enabled := False; try Action := caHide; if Changed then begin SaveChanges(Action); if Action = caNone then Exit; end; SetDefaults; edProjectName.Text := ''; edTitle.Text := ''; edOutput.Text := ''; seVerbosity.Value := 2; comboGenerateFormat.ItemIndex := 0; memoFiles.Clear; memoIncludeDirectories.Clear; memoMessages.Clear; rgLineBreakQuality.ItemIndex := 0; cbCheckSpelling.Checked := False; memoCheckSpellingIgnoreWords.Lines.Clear; MisspelledWords.Clear; memoDefines.Lines.Assign(DefaultDirectives); SaveDialog1.FileName := ''; Changed := False; finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.seVerbosityChanged(Sender: TObject; NewValue: Integer); begin Changed := True; end; procedure TfrmHelpGenerator.btnIntroductionClick(Sender: TObject); begin if edIntroduction.Text <> '' then begin odExtraFiles.FileName := edIntroduction.Text; end; if odExtraFiles.Execute then begin edIntroduction.Text := odExtraFiles.FileName; Changed := True; end; end; procedure TfrmHelpGenerator.btnConclusionClick(Sender: TObject); begin if edConclusion.Text <> '' then begin odExtraFiles.FileName := edConclusion.Text; end; if odExtraFiles.Execute then begin edConclusion.Text := odExtraFiles.FileName; Changed := True; end; end; procedure TfrmHelpGenerator.cbUseGraphVizClick(Sender: TObject); begin Changed := True; edGraphVizDotLocation.Enabled := cbUseGraphVizUses.Checked or cbUseGraphVizClasses.Checked; btnGraphViz.Enabled := edGraphVizDotLocation.Enabled; SetEdVizGraphDotLocationColor; end; procedure TfrmHelpGenerator.btnGraphVizClick(Sender: TObject); begin if edGraphVizDotLocation.Text <> '' then begin odDotLocation.FileName := edGraphVizDotLocation.Text; end; if odDotLocation.Execute then begin edGraphVizDotLocation.Text := odDotLocation.FileName; Changed := True; SetEdVizGraphDotLocationColor; end; end; procedure TfrmHelpGenerator.pcMainPageChanging(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean); begin HelpKeyword := NewPage.HelpKeyword; end; procedure TfrmHelpGenerator.About1Click(Sender: TObject); begin lbNavigator.Enabled := False; try frmAbout.ShowModal; finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.Help2Click(Sender: TObject); begin lbNavigator.Enabled := False; try Application.KeywordHelp(HelpKeyWord); finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.pcMainChanging(Sender: TObject; var AllowChange: Boolean); begin AllowChange := btnGenerate.Enabled; end; procedure TfrmHelpGenerator.comboGenerateFormatChange(Sender: TObject); begin Changed := True; tabWebOptions.Enabled := (comboGenerateFormat.ItemIndex in [0, 1]); edHtmlHelpContents.Enabled := comboGenerateFormat.ItemIndex = 1; btnHtmlHelpConents.Enabled := edHtmlHelpContents.Enabled; if edHtmlHelpContents.Enabled then begin edHtmlHelpContents.Color := clBase; end else begin edHtmlHelpContents.Color := clButton; end; { memoHeader.Enabled := (comboGenerateFormat.ItemIndex in [0, 1]); memoFooter.Enabled := memoHeader.Enabled; if memoHeader.Enabled then begin memoHeader.Color := clBase; memoFooter.Color := clBase; end else begin memoHeader.Color := clButton; memoFooter.Color := clButton; end; } tabLatexOptions.Enabled := (comboGenerateFormat.ItemIndex in [2, 3]); comboLatexGraphics.Enabled := tabLatexOptions.Enabled; { rgLineBreakQuality.Enabled := (comboGenerateFormat.ItemIndex in [2, 3]); memoHyphenatedWords.Enabled := rgLineBreakQuality.Enabled; // This also sets the color of comboLatexGraphics comboLatexGraphics.Enabled := rgLineBreakQuality.Enabled; if memoHyphenatedWords.Enabled then begin memoHyphenatedWords.Color := clBase; end else begin memoHyphenatedWords.Color := clButton; end; } self.GenerateNavigateList; end; procedure TfrmHelpGenerator.FormDestroy(Sender: TObject); begin { $ IFDEF MSWINDOWS} WriteIniFile(T_ConsoleCLX_Ini); { $ENDIF} NavigateList.Free; MisspelledWords.Free; end; procedure TfrmHelpGenerator.SetEdVizGraphDotLocationColor; begin if edGraphVizDotLocation.Enabled then begin if FileExists(edGraphVizDotLocation.Text) then begin edGraphVizDotLocation.Color := clBase; end else begin edGraphVizDotLocation.Color := clRed; end; end else begin edGraphVizDotLocation.Color := clBtnFace; end; end; procedure TfrmHelpGenerator.edGraphVizDotLocationChange(Sender: TObject); begin Changed := True; SetEdVizGraphDotLocationColor; end; procedure TfrmHelpGenerator.Save1Click(Sender: TObject); begin lbNavigator.Enabled := False; try SaveIt; finally Application.ProcessMessages; lbNavigator.Enabled := True; end; end; procedure TfrmHelpGenerator.pcMainChange(Sender: TObject); begin HelpKeyword := pcMain.ActivePage.HelpKeyword; end; { THelpGeneratorProjectOptions } function THelpGeneratorProjectOptions.GetChanged: boolean; begin result := frmHelpGenerator.Changed; end; function THelpGeneratorProjectOptions.GetConclusion: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edConclusion.Text); end else begin result := frmHelpGenerator.edConclusion.Text; end; end; function THelpGeneratorProjectOptions.GetDirectives: TSTrings; begin result := frmHelpGenerator.memoDefines.Lines; end; function THelpGeneratorProjectOptions.GetFooter: TStrings; begin result := frmHelpGenerator.memoFooter.Lines; end; function THelpGeneratorProjectOptions.GetGraphVizDotLocation: string; begin result := frmHelpGenerator.edGraphVizDotLocation.Text; end; function THelpGeneratorProjectOptions.GetHeader: TStrings; begin result := frmHelpGenerator.memoFooter.Lines; end; {function THelpGeneratorProjectOptions.GetHtmlDocGeneratorComponent: THtmlDocGenerator; begin result := nil;//frmHelpGenerator.HtmlDocGenerator; end; function THelpGeneratorProjectOptions.GetHTMLHelpDocGeneratorComponent: THTMLHelpDocGenerator; begin result := nil;//frmHelpGenerator.HTMLHelpDocGenerator; end; } function THelpGeneratorProjectOptions.GetHtmlHelpContents: string; begin result := frmHelpGenerator.edHtmlHelpContents.Text; end; function THelpGeneratorProjectOptions.GetHyphenatedWords: TStrings; begin result := frmHelpGenerator.memoHyphenatedWords.Lines; end; function THelpGeneratorProjectOptions.GetIncludeAutomated: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kAutomated); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeDirectories: TStrings; var Index: integer; begin if csWriting in ComponentState then begin FSourceFiles.Assign(frmHelpGenerator.memoIncludeDirectories.Lines); for Index := 0 to FSourceFiles.Count - 1 do begin FSourceFiles[Index] := RelativeFileName(FSourceFiles[Index]); end; result := FSourceFiles; end else begin result := frmHelpGenerator.memoIncludeDirectories.Lines; end; end; function THelpGeneratorProjectOptions.GetIncludeImplicit: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kImplicit); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePrivate: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPrivate); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeProtected: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kProtected); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePublic: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublic); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludePublished: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublished); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeStrictPrivate: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictPrivate); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIncludeStrictProtected: boolean; var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictProtected); result := frmHelpGenerator.clbMethodVisibility.Checked[Index]; end; function THelpGeneratorProjectOptions.GetIntroduction: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edIntroduction.Text); end else begin result := frmHelpGenerator.edIntroduction.Text; end; end; {function THelpGeneratorProjectOptions.GetLanguage: TLanguageID; begin result := TLanguageID(frmHelpGenerator.comboLanguages.ItemIndex); end; } function THelpGeneratorProjectOptions.GetLanguageString: string; begin result := frmHelpGenerator.comboLanguages.Items[frmHelpGenerator.comboLanguages.ItemIndex]; end; function THelpGeneratorProjectOptions.GetLatexGraphicsPackage: TLatexGraphicsPackage; begin result := TLatexGraphicsPackage(frmHelpGenerator.comboLatexGraphics.ItemIndex); end; function THelpGeneratorProjectOptions.GetLineBreakQuality: TLineBreakQuality; begin result := TLineBreakQuality(frmHelpGenerator.rgLineBreakQuality.ItemIndex); end; function THelpGeneratorProjectOptions.GetOutputDirectory: string; begin if csWriting in ComponentState then begin result := RelativeFileName(frmHelpGenerator.edOutput.Text); end else begin result := frmHelpGenerator.edOutput.Text; end; end; function THelpGeneratorProjectOptions.GetOutputType: TOutputType; begin result := TOutputType(frmHelpGenerator.comboGenerateFormat.ItemIndex); end; {function THelpGeneratorProjectOptions.GetPasDocComponent: TPasDoc; begin result := nil;//frmHelpGenerator.PasDoc1; end; } function THelpGeneratorProjectOptions.GetPasDocConsoleLocation: string; begin result := frmHelpGenerator.edPasDocConsole.Text; end; function THelpGeneratorProjectOptions.GetProjectName: string; begin result := frmHelpGenerator.edProjectName.Text; end; function THelpGeneratorProjectOptions.GetSortOptions: TSortOptions; var index: TSortOption; begin result := []; for index := Low(TSortOption) to High(TSortOption) do begin if frmHelpGenerator.clbSort.Checked[Ord(index)] then begin include(result, Index); end; end; end; function THelpGeneratorProjectOptions.GetSourceFiles: TStrings; var Index: integer; begin if csWriting in ComponentState then begin FSourceFiles.Assign(frmHelpGenerator.memoFiles.Lines); for Index := 0 to FSourceFiles.Count - 1 do begin FSourceFiles[Index] := RelativeFileName(FSourceFiles[Index]); end; result := FSourceFiles; end else begin result := frmHelpGenerator.memoFiles.Lines; end; end; {function THelpGeneratorProjectOptions.GetTexDocGeneratorComponent: TTexDocGenerator; begin result := nil;//frmHelpGenerator.TexDocGenerator; end; } function THelpGeneratorProjectOptions.GetSpellCheckIgnoreWords: TStrings; begin result := frmHelpGenerator.memoCheckSpellingIgnoreWords.Lines; end; function THelpGeneratorProjectOptions.GetSpellChecking: boolean; begin result := frmHelpGenerator.cbCheckSpelling.Checked; end; function THelpGeneratorProjectOptions.GetSpellCheckLanguage: string; begin result := frmHelpGenerator.comboLanguages.Text; end; function THelpGeneratorProjectOptions.GetSpellCheckLanguageCode: string; var Item: TASpellLangMap; begin if frmHelpGenerator.comboSpellLanguages.ItemIndex >= 0 then begin Item := frmHelpGenerator.comboSpellLanguages.Items.Objects[ frmHelpGenerator.comboSpellLanguages.ItemIndex] as TASpellLangMap; result := Item.Code; end else begin result := ''; end; end; function THelpGeneratorProjectOptions.GetTitle: string; begin result := frmHelpGenerator.edTitle.Text; end; function THelpGeneratorProjectOptions.GetUseGraphVizClasses: boolean; begin result := frmHelpGenerator.cbUseGraphVizClasses.Checked; end; function THelpGeneratorProjectOptions.GetUseGraphVizUses: boolean; begin result := frmHelpGenerator.cbUseGraphVizUses.Checked; end; function THelpGeneratorProjectOptions.GetVerbosity: integer; begin result := frmHelpGenerator.seVerbosity.Value; end; procedure THelpGeneratorProjectOptions.SetChanged(const Value: boolean); begin frmHelpGenerator.Changed := Value; end; procedure THelpGeneratorProjectOptions.SetConclusion(const Value: string); begin frmHelpGenerator.edConclusion.Text := Value; end; procedure THelpGeneratorProjectOptions.SetDefaultActivePage; begin frmHelpGenerator.pcMain.ActivePageIndex := 0; end; procedure THelpGeneratorProjectOptions.SetDirectives( const Value: TSTrings); begin frmHelpGenerator.memoDefines.Lines.Assign(Value); end; procedure THelpGeneratorProjectOptions.SetFooter(const Value: TStrings); begin frmHelpGenerator.memoFooter.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetGraphVizDotLocation( const Value: string); begin if Value <> '' then begin frmHelpGenerator.edGraphVizDotLocation.Text := Value; end; end; procedure THelpGeneratorProjectOptions.SetHeader(const Value: TStrings); begin frmHelpGenerator.memoHeader.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetHtmlHelpContents( const AValue: string); begin frmHelpGenerator.edHtmlHelpContents.Text := AValue; end; procedure THelpGeneratorProjectOptions.SetHyphenatedWords( const Value: TStrings); begin frmHelpGenerator.memoHyphenatedWords.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetIncludeAutomated( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kAutomated); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeDirectories( const Value: TStrings); begin frmHelpGenerator.memoIncludeDirectories.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetIncludeImplicit( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kImplicit); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePrivate( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPrivate); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeProtected( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kProtected); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePublic( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublic); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludePublished( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kPublished); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeStrictPrivate( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictPrivate); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIncludeStrictProtected( const Value: boolean); var Index: integer; begin Index := frmHelpGenerator.clbMethodVisibility.Items.IndexOf(kStrictProtected); frmHelpGenerator.clbMethodVisibility.Checked[Index] := Value; frmHelpGenerator.clbMethodVisibilityClickCheck(nil); end; procedure THelpGeneratorProjectOptions.SetIntroduction( const Value: string); begin frmHelpGenerator.edIntroduction.Text := Value; end; {procedure THelpGeneratorProjectOptions.SetLanguage( const Value: TLanguageID); begin frmHelpGenerator.comboLanguages.ItemIndex := Ord(Value); frmHelpGenerator.comboLanguagesChange(nil); end; } procedure THelpGeneratorProjectOptions.SetLanguageString( const Value: string); begin frmHelpGenerator.comboLanguages.ItemIndex := frmHelpGenerator.comboLanguages.Items.IndexOf(Value); frmHelpGenerator.comboLanguagesChange(nil); end; procedure THelpGeneratorProjectOptions.SetLatexGraphicsPackage( const Value: TLatexGraphicsPackage); begin frmHelpGenerator.comboLatexGraphics.ItemIndex := Ord(Value); end; procedure THelpGeneratorProjectOptions.SetLineBreakQuality( const Value: TLineBreakQuality); begin frmHelpGenerator.rgLineBreakQuality.ItemIndex := Ord(Value); end; procedure THelpGeneratorProjectOptions.SetOutputDirectory( const Value: string); begin frmHelpGenerator.edOutput.Text := Value; end; procedure THelpGeneratorProjectOptions.SetOutputType(const Value: TOutputType); begin frmHelpGenerator.comboGenerateFormat.ItemIndex := Ord(Value); frmHelpGenerator.comboGenerateFormat.OnChange(nil); end; procedure THelpGeneratorProjectOptions.SetProjectName(const Value: string); begin frmHelpGenerator.edProjectName.Text := Value; end; procedure THelpGeneratorProjectOptions.SetSortOptions( const Value: TSortOptions); var index: TSortOption; begin for index := Low(TSortOption) to High(TSortOption) do begin frmHelpGenerator.clbSort.Checked[Ord(index)] := Index in Value; end; end; procedure THelpGeneratorProjectOptions.SetSourceFiles( const Value: TStrings); begin frmHelpGenerator.memoFiles.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetSpellCheckIgnoreWords( const Value: TStrings); begin frmHelpGenerator.memoCheckSpellingIgnoreWords.Lines := Value; end; procedure THelpGeneratorProjectOptions.SetSpellChecking( const Value: boolean); begin frmHelpGenerator.cbCheckSpelling.Checked := Value; end; procedure THelpGeneratorProjectOptions.SetSpellCheckLanguage( const Value: string); var Index: integer; begin Index := frmHelpGenerator.comboSpellLanguages.Items.IndexOf(Value); frmHelpGenerator.comboSpellLanguages.ItemIndex := Index; end; procedure THelpGeneratorProjectOptions.SetTitle(const Value: string); begin frmHelpGenerator.edTitle.Text := Value; end; procedure THelpGeneratorProjectOptions.SetUseGraphVizClasses( const Value: boolean); begin frmHelpGenerator.cbUseGraphVizClasses.Checked := Value; end; procedure THelpGeneratorProjectOptions.SetUseGraphVizUses( const Value: boolean); begin frmHelpGenerator.cbUseGraphVizUses.Checked := Value; end; procedure THelpGeneratorProjectOptions.SetVerbosity(const Value: integer); begin frmHelpGenerator.seVerbosity.Value := Value; end; { T_ConsoleCLX_Ini } function T_ConsoleCLX_Ini.GetBrowserLocation: string; begin result := frmHelpGenerator.edBrowser.Text; end; function T_ConsoleCLX_Ini.GetGraphVizDotLocation: string; begin result := frmHelpGenerator.edGraphVizDotLocation.Text; end; function T_ConsoleCLX_Ini.GetPasDocConsoleLocation: string; begin result := frmHelpGenerator.edPasDocConsole.Text; end; procedure T_ConsoleCLX_Ini.SetBrowserLocation(const Value: string); begin frmHelpGenerator.edBrowser.Text := Value; end; procedure T_ConsoleCLX_Ini.SetGraphVizDotLocation(const Value: string); begin frmHelpGenerator.edGraphVizDotLocation.Text := Value; end; procedure TfrmHelpGenerator.btnBrowerClick(Sender: TObject); var ed: TEdit; begin ed := nil; if Sender = btnBrower then begin ed := edBrowser; end else if Sender = btnPasDocConsole then begin ed := edPasDocConsole; end else begin Assert(False); end; ProgramDialog.FileName := ed.Text; if ProgramDialog.Execute then begin ed.Text := ProgramDialog.FileName; end; end; procedure T_ConsoleCLX_Ini.SetPasDocConsoleLocation(const Value: string); begin frmHelpGenerator.edPasDocConsole.Text := Value; frmHelpGenerator.edPasDocConsoleChange(nil); end; procedure TfrmHelpGenerator.ShowPasDocMessage(const Text: string); const Misspell = 'Warning[2]: Word misspelled "'; var MisspellLength : integer; WrongWord: string; begin MisspellLength := Length(Misspell); memoMessages.Lines.Add(Text); if Pos(Misspell, Text) = 1 then begin WrongWord := Copy(Text, MisspellLength+1, MAXINT); if Length(WrongWord) > 0 then begin SetLength(WrongWord, Length(WrongWord)-1); MisspelledWords.Add(WrongWord); end; end; Application.ProcessMessages; end; procedure TfrmHelpGenerator.edPasDocConsoleChange(Sender: TObject); begin if FileExists(edPasDocConsole.Text) then begin edPasDocConsole.Color := clBase; end else begin edPasDocConsole.Color := clRed; end; end; procedure TfrmHelpGenerator.lbNavigatorClick(Sender: TObject); var Item: TNavigateItem; begin if lbNavigator.ItemIndex >= 0 then begin Item := NavigateList[lbNavigator.ItemIndex] as TNavigateItem; pcMain.ActivePageIndex := Item.PageIndex; end; end; procedure TfrmHelpGenerator.edHtmlHelpContentsChange(Sender: TObject); begin Changed := True; if edHtmlHelpContents.Enabled then begin if FileExists(edHtmlHelpContents.Text) then begin edHtmlHelpContents.Color := clBase; end else begin edHtmlHelpContents.Color := clRed; end; end; end; procedure TfrmHelpGenerator.btnHtmlHelpConentsClick(Sender: TObject); begin odExtraFiles.FileName := edHtmlHelpContents.Text; if odExtraFiles.Execute then begin edHtmlHelpContents.Text := odExtraFiles.FileName; edHtmlHelpContentsChange(nil); end; end; procedure TfrmHelpGenerator.comboLanguagesChange(Sender: TObject); var Lang: string; SpacePos: integer; LangPos: integer; begin Changed := True; Lang := comboLanguages.Text; SpacePos := Pos(' ', Lang); if SpacePos > 0 then begin Lang := Copy(Lang, 1, SpacePos-1); end; if Lang = 'Brasilian' then begin Lang := 'Portuguese'; end else if Lang = 'Catalan' then begin Lang := 'Catalan / Valencian'; end; LangPos := comboSpellLanguages.Items.IndexOf(Lang); if LangPos >= 0 then begin comboSpellLanguages.ItemIndex := LangPos end; end; procedure TfrmHelpGenerator.cbCheckSpellingClick(Sender: TObject); begin Changed := True; comboSpellLanguages.Enabled := cbCheckSpelling.Checked; memoCheckSpellingIgnoreWords.Enabled := cbCheckSpelling.Checked; if comboSpellLanguages.Enabled then begin comboSpellLanguages.Color := clBase; memoCheckSpellingIgnoreWords.Color := clBase; end else begin comboSpellLanguages.Color := clButton; memoCheckSpellingIgnoreWords.Color := clButton; end; end; procedure TfrmHelpGenerator.comboSpellLanguagesChange(Sender: TObject); begin Changed := True; end; procedure TfrmHelpGenerator.memoCheckSpellingIgnoreWordsChange( Sender: TObject); begin Changed := True; end; initialization Classes.RegisterClass(THelpGeneratorProjectOptions); Classes.RegisterClass(T_ConsoleCLX_Ini); end.
unit fvm.Strings; interface function RetrieveNextValueFrom(var s: string; Separator: char): string; implementation uses SysUtils; function RetrieveNextValueFrom(var s: string; Separator: char): string; var p: integer; begin p := Pos(Separator, s); if p = 0 then begin Result := Trim(s); s := ''; end else begin Result := Trim(Copy(s, 1, p-1)); s := Trim(Copy(s, p+1, MaxInt)); end; end; end.
unit uGame3D; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms3D, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Effects, FMX.Objects, FMX.Filter.Effects, FMX.StdCtrls, FMX.Ani, FMX.Layouts, FMX.Controls3D, FMX.Layers3D, FMX.Platform, System.IOUtils, System.IniFiles, Math, System.Math.Vectors; type TGameForm3D = class(TForm3D) BackGroundImage: TImage; BigPipe: TLayout; TopPipe: TRectangle; TopPipeCap: TRectangle; BirdSprite: TImage; FMonkeyA: TImage; FMonkeyB: TImage; GameLoop: TTimer; GameOverLayout: TLayout; GameOverLBL: TLabel; GOFloat: TFloatAnimation; Rectangle3: TRectangle; Label2: TLabel; Label4: TLabel; GOScoreLBL: TLabel; BestScoreLBL: TLabel; Layout1: TLayout; OKBTN: TButton; ReplayBTN: TButton; GetReadyLayout: TLayout; Image2: TImage; MonochromeEffect1: TMonochromeEffect; Rectangle1: TRectangle; Label1: TLabel; Arc1: TArc; Arc2: TArc; Rectangle2: TRectangle; Pie1: TPie; GetReadyLBL: TLabel; FloatAnimation1: TFloatAnimation; GlowEffect3: TGlowEffect; Ground: TRectangle; GroundA: TImage; GroundB: TImage; GroundBar: TImage; ScoreLBL: TLabel; GlowEffect1: TGlowEffect; Layer3D: TLayer3D; procedure GameLoopTimer(Sender: TObject); procedure Form3DDestroy(Sender: TObject); procedure Form3DMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure GetReadyLayoutClick(Sender: TObject); procedure ReplayBTNClick(Sender: TObject); procedure OKBTNClick(Sender: TObject); procedure Form3DCreate(Sender: TObject); procedure Form3DHide(Sender: TObject); procedure Form3DShow(Sender: TObject); private { Private declarations } public { Public declarations } EnemyList: TStringList; GameTick: Integer; Score: Integer; GameLoopActive: Boolean; IsGameOver: Boolean; MonkeyAni: Boolean; GroundAni: Boolean; IniFileName: String; BestScore: Integer; JustOnce: Boolean; BG_WRatio: Integer; BG_HRatio: Integer; procedure ResetGame; procedure SetScore(I: Integer); procedure GameOver; function CheckBoundryCollision( R1, R2 : TRect; OffSetY : LongInt = 4; OffSetX : LongInt = 4): Boolean; {overload;} function GetScreenScale: Single; end; const BG_WIDTH=384; BG_HEIGHT=576; var GameForm3D: TGameForm3D; implementation {$R *.fmx} uses uMenu; function TGameForm3D.GetScreenScale: Single; var ScreenSvc: IFMXScreenService; begin Result := 1; if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(ScreenSvc)) then begin Result := ScreenSvc.GetScreenScale; end; end; procedure TGameForm3D.Form3DCreate(Sender: TObject); begin EnemyList := TStringList.Create; GOFloat.StopValue := 0; GOFloat.StartValue := GameForm3D.Height; GameOverLayout.Position.Y := GameForm3D.Height; IniFileName := System.IOUtils.TPath.GetDocumentsPath + System.SysUtils.PathDelim + 'Scores.dat'; end; procedure TGameForm3D.Form3DDestroy(Sender: TObject); begin EnemyList.Free; end; procedure TGameForm3D.Form3DHide(Sender: TObject); begin GameLoop.Enabled := False; MenuForm.Show; end; procedure TGameForm3D.Form3DMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if GameLoopActive=True then begin if BirdSprite.Position.Y<75 then begin BirdSprite.Position.Y := 0; end else begin BirdSprite.Position.Y := BirdSprite.Position.Y-75; end; BirdSprite.RotationAngle := 0; end; end; procedure TGameForm3D.Form3DShow(Sender: TObject); var IniFile: TMemIniFile; begin if JustOnce=False then begin try IniFile := TMemIniFile.Create(IniFileName); BestScore := IniFile.ReadInteger('Settings','Best',0); IniFile.Free; BestScoreLBL.Text := IntToStr(BestScore); except on E: Exception do begin //E.Message; end; end; JustOnce := True; end; end; procedure TGameForm3D.ReplayBTNClick(Sender: TObject); begin GameOverLayout.Position.Y := GameForm3D.Height; GameForm3D.ResetGame; end; procedure TGameForm3D.ResetGame; var I: Integer; R: TLayout; begin IsGameOver := False; MonkeyAni := False; GameOverLayout.Visible := False; BirdSprite.Position.X := 96; BirdSprite.Position.Y := 248; BirdSprite.RotationAngle := 0; GetReadyLayout.Visible := True; SetScore(0); for I := EnemyList.Count-1 downto 0 do begin if Assigned(EnemyList.Objects[I]) then begin R := TLayout(EnemyList.Objects[I]); R.DisposeOf; EnemyList.Delete(I); end; end; Application.ProcessMessages; GameLoop.Enabled := True; end; procedure TGameForm3D.GameOver; var IniFile: TMemIniFile; begin IsGameOver := True; GameLoopActive := False; GameOverLayout.BringToFront; GameOverLayout.Visible := True; ScoreLBL.Visible := False; //GOFloat.Enabled := True; GOScoreLBL.Text := IntToStr(Score); if Score>BestScore then begin BestScore := Score; BestScoreLBL.Text := IntToStr(Score); try IniFile := TMemIniFile.Create(IniFileName); IniFile.WriteInteger('Settings','Best',BestScore); IniFile.Free; except on E: Exception do begin //E.Message; end; end; end; end; procedure TGameForm3D.GetReadyLayoutClick(Sender: TObject); var FormScale: Single; begin FormScale := GetScreenScale; BG_WRatio := Trunc(FormScale); BG_HRatio := Trunc(FormScale); GetReadyLayout.Visible := False; ScoreLBL.Visible := True; GameLoopActive := True; end; procedure TGameForm3D.OKBTNClick(Sender: TObject); begin if IsGameOver=True then begin GameOverLayout.Position.Y := GameForm3D.Height; GameOverLayout.Visible := False; GameForm3D.Close; MenuForm.Show; end; end; procedure TGameForm3D.SetScore(I: Integer); begin Score := I; ScoreLBL.Text := IntToStr(Score); end; procedure TGameForm3D.GameLoopTimer(Sender: TObject); const SpawnTime = 1.5; var R: TLayout; I: Integer; POffset,WOffset: Integer; R1, R2: TRect; GameOverCheck: Boolean; begin //GameForm3D.BeginUpdate; if GameLoopActive=True then begin GameOverCheck := False; if (BirdSprite.Position.Y+BirdSprite.Height)>Ground.Position.Y then begin GameOverCheck := True; end; if GameTick=0 then begin if (Random<0.5) then begin WOffset := (200*BG_HRatio); end else begin WOffset := (250*BG_HRatio); end; if (Random<0.5) then begin POffset := (-125*BG_HRatio); end else begin POffset := (-25*BG_HRatio); end; R := TLayout(BigPipe.Clone(Self)); EnemyList.AddObject('',R); R.Parent := Layer3D;//GameForm3D; R.Visible := True; R.Position.X := GameForm3D.Width+R.Width; R.Position.Y := (0-WOffset)+POffset; R.Tag := 1; R := TLayout(BigPipe.Clone(Self)); EnemyList.AddObject('',R); R.Parent := Layer3D;//GameForm3D; R.Visible := True; R.Position.X := GameForm3D.Width+R.Width; R.Position.Y := (GameForm3D.Height-R.Height+WOffset)+POffset; R.RotationAngle := 180; R.Tag := 2; end; if GameTick>(SpawnTime*30) then begin GameTick := 0; end else begin Inc(GameTick); end; R1 := Rect(Trunc(BirdSprite.Position.X),Trunc(BirdSprite.Position.Y),Trunc(BirdSprite.Position.X+BirdSprite.Width),Trunc(BirdSprite.Position.Y+BirdSprite.Height)); for I := EnemyList.Count-1 downto 0 do begin if Assigned(EnemyList.Objects[I]) then begin R := TLayout(EnemyList.Objects[I]); R.Position.X := R.Position.X-5; R2 := Rect(Trunc(R.Position.X),Trunc(R.Position.Y),Trunc(R.Position.X+R.Width),Trunc(R.Position.Y+R.Height)); if CheckBoundryCollision(R1,R2)=True then begin GameOverCheck := True; end else begin if (((R.Position.X+(R.Width/2))<BirdSprite.Position.X) AND (R.Tag=1) AND (R.TagFloat=0)) then begin R.TagFloat := 1; SetScore(Score+1); end; end; if (R.Position.X<((R.Width*-1)-10)) then begin R.DisposeOf; EnemyList.Delete(I); end; end; end; if BirdSprite.RotationAngle<90 then BirdSprite.RotationAngle := BirdSprite.RotationAngle+5; BirdSprite.Position.Y := BirdSprite.Position.Y+(Max(BirdSprite.RotationAngle,1)/5); if MonkeyAni=False then begin BirdSprite.Bitmap.Assign(FMonkeyB.Bitmap); MonkeyAni := True; end else begin BirdSprite.Bitmap.Assign(FMonkeyA.Bitmap); MonkeyAni := False; end; if GameOverCheck=True then GameOver; end; Ground.BringToFront; ScoreLBL.BringToFront; if GroundAni=True then begin GroundBar.Bitmap.Assign(GroundB.Bitmap); GroundAni := False; GroundBar.BringToFront; end else begin GroundBar.Bitmap.Assign(GroundA.Bitmap); GroundAni := True; GroundBar.BringToFront; end; if IsGameOver then GameOverLayout.BringToFront; // GameForm3D.EndUpdate; end; {function CheckCollision(x1, y1, x2, y2, enemy_height, enemy_width: Integer): Boolean; const OFFSET_X = 4; OFFSET_Y = 4; begin Result := True; } { if (( (y1 + PLAYER_HEIGHT - (OFFSET_Y * 2) < (y1 + OFFSET_Y and y2 + ENEMY_HEIGHT - (OFFSET_Y * 2) ) or ( (x1 + PLAYER_WIDTH - (OFFSET_X * 2) and (x1 + OFFSET_X and x2 + ENEMY_WIDTH - (OFFSET_X * 2) )) then Result := False;} //end; function TGameForm3D.CheckBoundryCollision( R1, R2 : TRect; OffSetY : LongInt = 4; OffSetX : LongInt = 4): Boolean; // Simple collision test based on rectangles. begin // Rectangle R1 can be the rectangle of the character (player) // Rectangle R2 can be the rectangle of the enemy // Simple collision test based on rectangles. We can also use the // API function IntersectRect() but i believe this is much faster. Result:=( NOT ((R1.Bottom - (OffSetY * 2) < R2.Top + OffSetY) or(R1.Top + OffSetY > R2.Bottom - (OffSetY * 2)) or( R1.Right - (OffSetX * 2) < R2.Left + OffSetX) or( R1.Left + OffSetX > R2.Right - (OffSetX * 2)))); end; end.
unit Control.CadastroFinanceiro; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Control.Sistema, Model.CadastroFinanceiro; type TCadastroFinanceiroControl = class private FFinanceiro : TCadastroFinanceiro; public constructor Create; destructor Destroy; override; property Financeiro: TCadastroFinanceiro read FFinanceiro write FFinanceiro; function GetID(iID: Integer; iTipo: Integer): Integer; function Localizar(aParam: array of variant): boolean; function Gravar(): Boolean; function SaveBatch(memTable: TFDMemTable): Boolean; function SetupClass(FDQuery: TFDQuery): boolean; function ClearClass(): boolean; end; implementation { TFinanceiroEmpresaControl } uses Common.ENum; function TCadastroFinanceiroControl.ClearClass: boolean; begin Result := FFinanceiro.ClearClass; end; constructor TCadastroFinanceiroControl.Create; begin FFinanceiro := TCadastroFinanceiro.Create; end; destructor TCadastroFinanceiroControl.Destroy; begin FFinanceiro.Free; inherited; end; function TCadastroFinanceiroControl.GetID(iID: Integer; iTipo: Integer): Integer; begin Result := FFinanceiro.GetID(iID); end; function TCadastroFinanceiroControl.Gravar: Boolean; begin Result := FFinanceiro.Gravar; end; function TCadastroFinanceiroControl.Localizar(aParam: array of variant): Boolean; begin Result := FFinanceiro.Localizar(aParam); end; function TCadastroFinanceiroControl.SaveBatch(memTable: TFDMemTable): Boolean; begin Result := FFinanceiro.SaveBatch(memTable); end; function TCadastroFinanceiroControl.SetupClass(FDQuery: TFDQuery): boolean; begin Result := FFinanceiro.SetupClass(FDQuery); end; end.
{$I DFS.INC} { Standard defines for all Delphi Free Stuff components } {------------------------------------------------------------------------------} { TdfsStatusBar v1.24 } {------------------------------------------------------------------------------} { A status bar that provides many common specialized panels and owning of } { other components by the status bar. } { } { Copyright 2000, Brad Stowers. All Rights Reserved. } { } { Copyright: } { All Delphi Free Stuff (hereafter "DFS") source code is copyrighted by } { Bradley D. Stowers (hereafter "author"), and shall remain the exclusive } { property of the author. } { } { Distribution Rights: } { You are granted a non-exlusive, royalty-free right to produce and distribute } { compiled binary files (executables, DLLs, etc.) that are built with any of } { the DFS source code unless specifically stated otherwise. } { You are further granted permission to redistribute any of the DFS source } { code in source code form, provided that the original archive as found on the } { DFS web site (http://www.delphifreestuff.com) is distributed unmodified. For } { example, if you create a descendant of TdfsColorButton, you must include in } { the distribution package the colorbtn.zip file in the exact form that you } { downloaded it from http://www.delphifreestuff.com/mine/files/colorbtn.zip. } { } { Restrictions: } { Without the express written consent of the author, you may not: } { * Distribute modified versions of any DFS source code by itself. You must } { include the original archive as you found it at the DFS site. } { * Sell or lease any portion of DFS source code. You are, of course, free } { to sell any of your own original code that works with, enhances, etc. } { DFS source code. } { * Distribute DFS source code for profit. } { } { Warranty: } { There is absolutely no warranty of any kind whatsoever with any of the DFS } { source code (hereafter "software"). The software is provided to you "AS-IS", } { and all risks and losses associated with it's use are assumed by you. In no } { event shall the author of the softare, Bradley D. Stowers, be held } { accountable for any damages or losses that may occur from use or misuse of } { the software. } { } { Support: } { Support is provided via the DFS Support Forum, which is a web-based message } { system. You can find it at http://www.delphifreestuff.com/discus/ } { All DFS source code is provided free of charge. As such, I can not guarantee } { any support whatsoever. While I do try to answer all questions that I } { receive, and address all problems that are reported to me, you must } { understand that I simply can not guarantee that this will always be so. } { } { Clarifications: } { If you need any further information, please feel free to contact me directly.} { This agreement can be found online at my site in the "Miscellaneous" section.} {------------------------------------------------------------------------------} { The lateset version of my components are always available on the web at: } { http://www.delphifreestuff.com/ } { See DFSStatusBar.txt for notes, known issues, and revision history. } {------------------------------------------------------------------------------} { Date last modified: June 27, 2001 } {------------------------------------------------------------------------------} unit dfsStatusBar; interface uses {$IFDEF DFS_DEBUG} DFSDebug, {$ENDIF} Windows, Classes, Messages, Controls, ComCtrls, Graphics, Forms, ExtCtrls; const WM_REFRESHLOCKINDICATORS = WM_APP + 230; { This shuts up C++Builder 3 about the redefiniton being different. There seems to be no equivalent in C1. Sorry. } {$IFDEF DFS_CPPB_3_UP} {$EXTERNALSYM DFS_COMPONENT_VERSION} {$ENDIF} DFS_COMPONENT_VERSION = 'TdfsStatusBar v1.24'; type TdfsStatusPanelType = ( sptNormal, // Nothing special, same as a regular TStatusPanel sptCapsLock, // Caps lock indicator. Normal color if on, gray if // off sptNumLock, // Num lock indicator. Normal color if on, gray if // off sptScrollLock, // Scroll lock indicator. Normal color if on, gray // if off sptDate, // Current date. Uses DateFormat property for format sptTime, // Current time. Uses TimeFormat property for format sptDateTime, // Current date and time. Uses DateFormat and // TimeFormat properties for format sptTimeDate, // Current time and date. Uses DateFormat and // TimeFormat properties for format sptEllipsisText, // Shorten text at the end with '...' when won't fit. sptEllipsisPath, // Shorten by removing path info with '...' when // won't fit. sptGlyph, // Displays a TPicture object in the panel. sptGauge, // A progress meter. Use GaugeAttrs to customize it. sptOwnerDraw // Same as the old TStatusPanel.Style = psOwnerDraw. ); TPercent = 0..100; TdfsGaugeStyle = ( gsPercent, // Your basic progress meeter. gsIndeterminate, // A progress indicator where the min/max are not // known. That is, you want to show something // going on, but don't know how long it will take. // It's a little ball that "bounces" back and forth. gsIndeterminate2 // Same as above, but looks more Netscape-ish. ); TdfsGaugeStyles = set of TdfsGaugeStyle; TdfsStatusBar = class; // forward declaration TdfsStatusPanel = class; // forward declaration TdfsDrawPanelEvent = procedure(StatusBar: TdfsStatusBar; Panel: TdfsStatusPanel; const Rect: TRect) of object; TdfsPanelHintTextEvent = procedure (StatusBar: TdfsStatusBar; Panel: TdfsStatusPanel; var Hint: string) of object; TdfsGaugeAttrs = class(TPersistent) private FStyle: TdfsGaugeStyle; FOwner: TdfsStatusPanel; FPosition: TPercent; FSpeed: integer; FColor: TColor; FTextColor: TColor; procedure SetPosition(const Value: TPercent); procedure SetStyle(const Value: TdfsGaugeStyle); procedure SetSpeed(const Value: integer); procedure SetColor(const Value: TColor); procedure SetTextColor(const Value: TColor); public constructor Create(AOwner: TdfsStatusPanel); procedure Assign(Source: TPersistent); override; property Owner: TdfsStatusPanel read FOwner; published property Style: TdfsGaugeStyle read FStyle write SetStyle default gsPercent; property Position: TPercent read FPosition write SetPosition default 0; property Speed: integer read FSpeed write SetSpeed default 4; property Color: TColor read FColor write SetColor default clHighlight; property TextColor: TColor read FTextColor write SetTextColor default clHighlightText; end; TdfsStatusPanel = class(TCollectionItem) private FKeyOn: boolean; FPanelType: TdfsStatusPanelType; FAutoFit: boolean; FEnabled: boolean; FTimeFormat: string; FDateFormat: string; FText: string; FGlyph: TPicture; FGaugeLastPos: integer; FGaugeDirection: integer; FOnDrawPanel: TdfsDrawPanelEvent; FHint: string; FOnHintText: TdfsPanelHintTextEvent; FOnClick: TNotifyEvent; FGaugeAttrs: TdfsGaugeAttrs; FGaugeBitmap: TBitmap; FBorderWidth: TBorderWidth; procedure SetPanelType(const Val: TdfsStatusPanelType); function GetAlignment: TAlignment; function GetBevel: TStatusPanelBevel; {$IFDEF DFS_COMPILER_4_UP} function IsBiDiModeStored: Boolean; function GetBiDiMode: TBiDiMode; function GetParentBiDiMode: Boolean; {$ENDIF} function GetWidth: Integer; procedure SetAlignment(const Value: TAlignment); procedure SetBevel(const Value: TStatusPanelBevel); {$IFDEF DFS_COMPILER_4_UP} procedure SetBiDiMode(const Value: TBiDiMode); procedure SetParentBiDiMode(const Value: Boolean); {$ENDIF} procedure SetText(const Value: string); procedure SetWidth(const Value: Integer); procedure SetAutoFit(const Value: boolean); procedure SetDateFormat(const Value: string); procedure SetEnabled(const Value: boolean); procedure SetGlyph(const Value: TPicture); procedure SetTimeFormat(const Value: string); function GetStatusBar: TdfsStatusBar; function GetEnabled: boolean; function GetHint: string; procedure SetGaugeAttrs(const Value: TdfsGaugeAttrs); function GetLinkedPanel: TStatusPanel; function GetGaugeBitmap: TBitmap; procedure SetBorderWidth(const Value: TBorderWidth); function IsTextStored: Boolean; protected procedure SetIndex(Value: integer); override; function GetDisplayName: string; override; procedure TimerNotification; procedure UpdateAutoFitWidth; dynamic; procedure UpdateDateTime; dynamic; procedure GlyphChanged(Sender: TObject); dynamic; procedure DrawPanel(Rect: TRect); dynamic; procedure EnabledChanged; dynamic; procedure DoHintText(var HintText: string); dynamic; procedure Redraw(Canvas: TCanvas; Dest: TRect); dynamic; procedure DrawKeyLock(Canvas: TCanvas; R: TRect); dynamic; procedure DrawTextBased(Canvas: TCanvas; R: TRect); dynamic; procedure DrawGlyph(Canvas: TCanvas; R: TRect); dynamic; procedure DrawGauge(Canvas: TCanvas; R: TRect); dynamic; procedure DrawIndeterminateGauge(Canvas: TCanvas; R: TRect); dynamic; function InitGaugeBitmap: TBitmap; dynamic; procedure Click; dynamic; procedure UpdateKeyboardHook; property LinkedPanel: TStatusPanel read GetLinkedPanel; property GaugeBitmap: TBitmap read GetGaugeBitmap; public constructor Create(AOwner: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Invalidate; property StatusBar: TdfsStatusBar read GetStatusBar; published property GaugeAttrs: TdfsGaugeAttrs read FGaugeAttrs write SetGaugeAttrs; property Alignment: TAlignment read GetAlignment write SetAlignment default taLeftJustify; property Bevel: TStatusPanelBevel read GetBevel write SetBevel default pbLowered; property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0; {$IFDEF DFS_COMPILER_4_UP} property BiDiMode: TBiDiMode read GetBiDiMode write SetBiDiMode stored IsBiDiModeStored; property ParentBiDiMode: Boolean read GetParentBiDiMode write SetParentBiDiMode default True; {$ENDIF} // PanelType must come before most of the other properties because it would // stomp on some of their values as they are streamed. Some of the other // properties have to be ordered a certain way, too, so don't mess with // the declaration order. property PanelType: TdfsStatusPanelType read FPanelType write SetPanelType default sptNormal; property Glyph: TPicture read FGlyph write SetGlyph; property Text: string read FText write SetText stored IsTextStored; property DateFormat: string read FDateFormat write SetDateFormat; property TimeFormat: string read FTimeFormat write SetTimeFormat; property Enabled: boolean read GetEnabled write SetEnabled; property Width: Integer read GetWidth write SetWidth; property AutoFit: boolean read FAutoFit write SetAutoFit; property Hint: string read GetHint write FHint; property OnDrawPanel: TdfsDrawPanelEvent read FOnDrawPanel write FOnDrawPanel; property OnHintText: TdfsPanelHintTextEvent read FOnHintText write FOnHintText; property OnClick: TNotifyEvent read FOnClick write FOnClick; end; TdfsStatusPanels = class(TCollection) private FTimer: TTimer; FTimerClients: TList; FLastDate: TDateTime; FStatusBar: TdfsStatusBar; FLinkedPanels: TStatusPanels; function GetItem(Index: Integer): TdfsStatusPanel; procedure SetItem(Index: Integer; Value: TdfsStatusPanel); protected procedure Update(Item: TCollectionItem); override; function GetOwner: TPersistent; override; procedure RegisterTimer(Client: TdfsStatusPanel); procedure DeregisterTimer(Client: TdfsStatusPanel); procedure TimerEvent(Sender: TObject); public constructor Create(StatusBar: TdfsStatusBar; LinkedPanels: TStatusPanels); destructor Destroy; override; function Add: TdfsStatusPanel; property Items[Index: Integer]: TdfsStatusPanel read GetItem write SetItem; default; end; TdfsStatusBar = class(TStatusBar) private FPanels: TdfsStatusPanels; FMainWinHookClients: TList; FExtentCanvas: HDC; FExtentFont: HFONT; FExtentFontOld: HFONT; FUseMonitorDLL: boolean; FDLLClientCount: integer; FKeyHookMsg: UINT; procedure SetPanels(const Value: TdfsStatusPanels); function AppWinHook(var Message: TMessage): boolean; procedure WMRefreshLockIndicators(var Msg: TMessage); message WM_REFRESHLOCKINDICATORS; procedure CMFontChanged(var Msg: TMessage); message CM_FONTCHANGED; procedure CMEnabledChanged(var Msg: TMessage); message CM_ENABLEDCHANGED; procedure CMHintShow(var Msg: TMessage); message CM_HINTSHOW; procedure SetOnDrawPanel(const Value: TdfsDrawPanelEvent); function GetOnDrawPanel: TdfsDrawPanelEvent; function GetVersion: string; procedure SetVersion(const Val: string); procedure UpdateExtentFont; procedure SetUseMonitorDLL(const Value: boolean); procedure UpdateKeyboardHooks; procedure WMDestroy(var Msg: TWMDestroy); message WM_DESTROY; procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; protected procedure DrawPanel(Panel: TStatusPanel; const Rect: TRect); override; procedure Loaded; override; procedure CreateWnd; override; procedure WndProc(var Msg: TMessage); override; function GetPanelRect(Index: integer): TRect; function FindLinkedPanel(Panel: TStatusPanel): TdfsStatusPanel; procedure RegisterMainWinHook(Client: TdfsStatusPanel); procedure DeregisterMainWinHook(Client: TdfsStatusPanel); procedure RegisterSystemHook; procedure DeregisterSystemHook; function TextExtent(const Text: string): TSize; procedure Click; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InvalidatePanel(Index: integer); {$IFDEF DFS_COMPILER_4_UP} function ExecuteAction(Action: TBasicAction): Boolean; override; {$ENDIF} published property UseMonitorDLL: boolean read FUseMonitorDLL write SetUseMonitorDLL default FALSE; property Panels: TdfsStatusPanels read FPanels write SetPanels; property Version: string read GetVersion write SetVersion stored FALSE; property OnDrawPanel: TdfsDrawPanelEvent read GetOnDrawPanel write SetOnDrawPanel; end; // You may want to change this value if you don't like the speed of the // indeterminate gauge const INDETERMINATE_GAUGE_UPDATE_INTERVAL: integer = 50; // in milliseconds {$IFDEF DFS_COMPILER_3_UP} resourcestring {$ELSE} const {$ENDIF} SCapsLock = ' CAPS '; SNumLock = ' NUM '; SScrollLock = ' SCROLL '; const IndeterminateGuages: TdfsGaugeStyles = [gsIndeterminate, gsIndeterminate2]; implementation uses {$IFDEF DFS_COMPILER_6_UP} RTLConsts, {$ELSE} Consts, {$ENDIF} CommCtrl, TypInfo, SysUtils, DFSKb; const KEY_CODE: array[sptCapsLock..sptScrollLock] of integer = ( VK_CAPITAL, VK_NUMLOCK, VK_SCROLL ); var KeyboardHookHandle: HHOOK; KeyHookClients: TList; RegisteredTimers: integer; MayNeedRefresh: boolean; // Keyboard hook callback function KeyboardHookCallBack(Code: integer; KeyCode: WPARAM; KeyInfo: LPARAM): LRESULT; stdcall; var x: integer; begin if Code >= 0 then begin if MayNeedRefresh then begin for x := 0 to KeyHookClients.Count-1 do TdfsStatusPanel(KeyHookClients[x]).Invalidate; MayNeedRefresh := FALSE; end else // Is it one of the indicator keys, and is it not a repeat if ((KeyCode = VK_CAPITAL) or (KeyCode = VK_NUMLOCK) or (KeyCode = VK_SCROLL)) and // This checks to see if the key is being pressed (bit 31) and if it was // up before (bit 30). We don't care about key releases or keys that // were already down. That just makes us flicker... (((KeyInfo SHR 31) and 1) = 0) and (((KeyInfo SHR 30) and 1) = 0) then begin for x := 0 to KeyHookClients.Count-1 do begin case TdfsStatusPanel(KeyHookClients[x]).PanelType of sptCapsLock: begin if KeyCode = VK_CAPITAL then TdfsStatusPanel(KeyHookClients[x]).Invalidate; end; sptNumLock: begin if KeyCode = VK_NUMLOCK then TdfsStatusPanel(KeyHookClients[x]).Invalidate; end; sptScrollLock: begin if KeyCode = VK_SCROLL then TdfsStatusPanel(KeyHookClients[x]).Invalidate; end; end; end; end; end; Result := CallNextHookEx(KeyboardHookHandle, Code, KeyCode, KeyInfo); end; // Utility routins for installing the windows hook for keypresses procedure RegisterTaskKeyboardHook(Client: TdfsStatusPanel); begin if KeyboardHookHandle = 0 then KeyboardHookHandle := SetWindowsHookEx(WH_KEYBOARD, KeyboardHookCallBack, 0, GetCurrentThreadID); KeyHookClients.Add(Client); end; procedure DeregisterTaskKeyboardHook(Client: TdfsStatusPanel); begin KeyHookClients.Remove(Client); if KeyHookClients.Count < 1 then begin UnhookWindowsHookEx(KeyboardHookHandle); KeyboardHookHandle := 0; end; end; // Utility function for making a copy of a font handle function CopyHFont(Font: HFONT): HFONT; var LF: TLogFont; begin if Font <> 0 then begin GetObject(Font, SizeOf(LF), @LF); Result := CreateFontIndirect(LF); end else Result := 0; end; { TdfsGaugeAttrs } procedure TdfsGaugeAttrs.Assign(Source: TPersistent); var SrcAttrs: TdfsGaugeAttrs absolute Source; begin if Source is TdfsGaugeAttrs then begin FOwner := SrcAttrs.Owner; Position := SrcAttrs.Position; Style := SrcAttrs.Style; end else inherited Assign(Source); end; constructor TdfsGaugeAttrs.Create(AOwner: TdfsStatusPanel); begin inherited Create; FOwner := AOwner; FStyle := gsPercent; FPosition := 0; FSpeed := 4; FColor := clHighlight; FTextColor := clHighlightText; end; procedure TdfsGaugeAttrs.SetColor(const Value: TColor); begin if FColor <> Value then begin FColor := Value; FOwner.FGaugeBitmap.Free; FOwner.FGaugeBitmap := NIL; FOwner.Invalidate; end; end; procedure TdfsGaugeAttrs.SetPosition(const Value: TPercent); begin if FPosition <> Value then begin FPosition := Value; FOwner.Invalidate; end; end; procedure TdfsGaugeAttrs.SetSpeed(const Value: integer); begin if (FSpeed <> Value) and (FSpeed > 0) then FSpeed := Value; if Owner.FGaugeDirection < 0 then Owner.FGaugeDirection := -FSpeed else Owner.FGaugeDirection := FSpeed; end; procedure TdfsGaugeAttrs.SetStyle(const Value: TdfsGaugeStyle); begin if FStyle <> Value then begin if (Owner.PanelType = sptGauge) and (FStyle in IndeterminateGuages) and Owner.Enabled then TdfsStatusPanels(Owner.Collection).DeregisterTimer(Owner); FStyle := Value; FOwner.Invalidate; if (Owner.PanelType = sptGauge) and (FStyle in IndeterminateGuages) and Owner.Enabled then TdfsStatusPanels(Owner.Collection).RegisterTimer(Owner); end; end; procedure TdfsGaugeAttrs.SetTextColor(const Value: TColor); begin if Value <> FTextColor then begin FTextColor := Value; Owner.Invalidate; end; end; { TdfsStatusPanel } procedure TdfsStatusPanel.Assign(Source: TPersistent); var SrcPanel: TdfsStatusPanel absolute Source; begin if Source is TdfsStatusPanel then begin { if LinkedPanel <> NIL then LinkedPanel.Free; LinkedPanel := SrcPanel.FLinkedPanel;} GaugeAttrs.Assign(SrcPanel.GaugeAttrs); Alignment := SrcPanel.Alignment; Bevel := SrcPanel.Bevel; {$IFDEF DFS_COMPILER_4_UP} BiDiMode := SrcPanel.BiDiMode; ParentBiDiMode := SrcPanel.ParentBiDiMode; {$ENDIF} Glyph.Assign(SrcPanel.Glyph); Text := SrcPanel.Text; DateFormat := SrcPanel.DateFormat; TimeFormat := SrcPanel.TimeFormat; Enabled := SrcPanel.Enabled; Width := SrcPanel.Width; AutoFit := SrcPanel.AutoFit; Hint := SrcPanel.Hint; OnDrawPanel := SrcPanel.OnDrawPanel; OnHintText := SrcPanel.OnHintText; // Do last! PanelType := SrcPanel.PanelType; end else inherited Assign(Source); end; constructor TdfsStatusPanel.Create(AOwner: TCollection); begin inherited Create(AOwner); if AOwner is TdfsStatusPanels then begin TdfsStatusPanels(AOwner).FLinkedPanels.Add; LinkedPanel.Style := psOwnerDraw; end else raise Exception.Create('TdfsStatusPanel owner must be TdfsStatusPanesls'); FKeyOn := FALSE; FGaugeLastPos := 0; FGaugeDirection := 1; FPanelType := sptNormal; FAutoFit := FALSE; FEnabled := TRUE; FTimeFormat := ''; FDateFormat := ''; FGaugeAttrs := TdfsGaugeAttrs.Create(Self); FGlyph := TPicture.Create; FGlyph.OnChange := GlyphChanged; end; destructor TdfsStatusPanel.Destroy; begin if Enabled then case FPanelType of sptCapsLock, sptNumLock, sptScrollLock: begin if StatusBar.UseMonitorDLL then StatusBar.DeregisterSystemHook else begin DeregisterTaskKeyboardHook(Self); StatusBar.DeregisterMainWinHook(Self); end; end; sptDate, sptTime, sptDateTime, sptTimeDate: TdfsStatusPanels(Collection).DeregisterTimer(Self); sptGauge: if GaugeAttrs.Style in IndeterminateGuages then TdfsStatusPanels(Collection).DeregisterTimer(Self); end; FGlyph.Free; FGaugeAttrs.Free; FGaugeBitmap.Free; TdfsStatusPanels(Collection).FLinkedPanels[Index].Free; inherited Destroy; end; function TdfsStatusPanel.GetAlignment: TAlignment; begin Result := LinkedPanel.Alignment end; function TdfsStatusPanel.GetBevel: TStatusPanelBevel; begin Result := LinkedPanel.Bevel end; {$IFDEF DFS_COMPILER_4_UP} function TdfsStatusPanel.GetBiDiMode: TBiDiMode; begin Result := LinkedPanel.BiDiMode end; function TdfsStatusPanel.GetParentBiDiMode: Boolean; begin Result := LinkedPanel.ParentBiDiMode end; {$ENDIF} function TdfsStatusPanel.GetStatusBar: TdfsStatusBar; begin Result := TdfsStatusPanels(Collection).FStatusBar; end; function TdfsStatusPanel.GetWidth: Integer; begin Result := LinkedPanel.Width end; procedure TdfsStatusPanel.Invalidate; begin if StatusBar <> NIL then StatusBar.InvalidatePanel(Index); end; {$IFDEF DFS_COMPILER_4_UP} function TdfsStatusPanel.IsBiDiModeStored: Boolean; begin Result := not ParentBiDiMode; end; {$ENDIF} procedure TdfsStatusPanel.Redraw(Canvas: TCanvas; Dest: TRect); var Buffer: TBitmap; R: TRect; begin if (not StatusBar.HandleAllocated) or (IsRectEmpty(Dest))then exit; InflateRect(Dest, -1, -1); // Don't paint over the shadows. R := Dest; OffsetRect(R, -Dest.Left, -Dest.Top); Buffer := TBitmap.Create; try Buffer.Width := R.Right; Buffer.Height := R.Bottom; Buffer.Canvas.Font.Handle := CopyHFont(Canvas.Font.Handle); Buffer.Canvas.Brush.Color := StatusBar.Color; Buffer.Canvas.FillRect(R); if BorderWidth > 0 then InflateRect(R, -BorderWidth, -BorderWidth); if Enabled then begin case PanelType of sptCapsLock, sptNumLock, sptScrollLock: DrawKeyLock(Buffer.Canvas, R); sptNormal, sptDate, sptTime, sptDateTime, sptTimeDate, sptEllipsisText, sptEllipsisPath, sptOwnerDraw: begin if (PanelType = sptOwnerDraw) and not (csDesigning in StatusBar.ComponentState) then exit; DrawTextBased(Buffer.Canvas, R); end; sptGlyph: DrawGlyph(Buffer.Canvas, R); sptGauge: if GaugeAttrs.Style in IndeterminateGuages then DrawIndeterminateGauge(Buffer.Canvas, R) else DrawGauge(Buffer.Canvas, R); end; end; Canvas.Draw(Dest.Left, Dest.Top, Buffer); finally Buffer.Free; end; end; procedure TdfsStatusPanel.DrawGauge(Canvas: TCanvas; R: TRect); var R1, R2: TRect; R1Rgn, R2Rgn, OldRgn: HRGN; Pct: string; OldColor: TColorRef; DTFlags: UINT; begin R1 := R; R2 := R; R1.Right := R1.Left + MulDiv(R.Right-R.Left, FGaugeAttrs.Position, 100); with Canvas do begin Brush.Color := GaugeAttrs.Color; FillRect(R1); R2.Left := R1.Right; Brush.Color := StatusBar.Color; FillRect(R2); { This could probably be simplified with ExtTextOut and SetTextAlign now things are being properly buffered off-screen. But, this is working and doesn't seem slow, so.... "If it ain't broke, don't fix it." :) } if Text = '' then Pct := IntToStr(FGaugeAttrs.Position) + '%' else Pct := Text; // Use what's in the panel's text property. // don't change background color behind text! Brush.Style := bsClear; OldColor := GetTextColor(Handle); R1Rgn := CreateRectRgnIndirect(R1); R2Rgn := CreateRectRgnIndirect(R2); OldRgn := CreateRectRgn(0, 0, 1, 1); try GetClipRgn(Handle, OldRgn); DTFlags := DT_VCENTER or DT_NOPREFIX or DT_SINGLELINE; case Alignment of taCenter: DTFlags := DTFlags or DT_CENTER; taRightJustify: DTFlags := DTFlags or DT_RIGHT; end; // Draw the text in the "filled" area with text color if (R1Rgn<>0) and (SelectClipRgn(Handle, R1Rgn) <> ERROR) then try SetTextColor(Handle, ColorToRGB(GaugeAttrs.TextColor)); DrawText(Handle, PChar(Pct), -1, R, DTFlags); finally SelectClipRgn(Handle, OldRgn); end; // Draw the text in the "empty" area with normal color if (R2Rgn<>0) and (SelectClipRgn(Handle, R2Rgn) <> ERROR) then try // SetTextColor(Handle, OldColor); SetTextColor(Handle, ColorToRGB(StatusBar.Font.Color)); DrawText(Handle, PChar(Pct), -1, R, DTFlags); finally SelectClipRgn(Handle, OldRgn); end; finally SetTextColor(Handle, OldColor); DeleteObject(R1Rgn); DeleteObject(R2Rgn); DeleteObject(OldRgn); end; end; end; procedure TdfsStatusPanel.DrawGlyph(Canvas: TCanvas; R: TRect); const TEXT_SPACE = 2; var TW: integer; GR: TRect; begin GR := R; if Text <> '' then TW := Canvas.TextWidth(Text) + TEXT_SPACE else TW := 0; if (Alignment = taCenter) or AutoFit then with GR do Left := Left + ((Right - Left - Glyph.Width - TW) div 2) else if Alignment = taRightJustify then GR.Left := GR.Right - Glyph.Width; GR.Top := GR.Top + (GR.Bottom - GR.Top - Glyph.Height) div 2; if Glyph.Graphic is TBitmap then begin // Draw it transparently Canvas.BrushCopy(Bounds(GR.Left, GR.Top, Glyph.Width, Glyph.Height), Glyph.Bitmap, Rect(0, 0, Glyph.Width, Glyph.Height), Glyph.Bitmap.Canvas.Pixels[0, Glyph.Height-1]); end else Canvas.Draw(GR.Left, GR.Top, Glyph.Graphic); if Text <> '' then begin SetTextColor(Canvas.Handle, ColorToRGB(StatusBar.Font.Color)); case Alignment of taLeftJustify, taCenter: begin GR.Left := GR.Left + Glyph.Width + TEXT_SPACE; GR.Top := R.Top; GR.Bottom := R.Bottom; DrawText(Canvas.Handle, PChar(Text), -1, GR, DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER); end; taRightJustify: begin GR.Left := GR.Left - TW - TEXT_SPACE; GR.Top := R.Top; GR.Bottom := R.Bottom; DrawText(Canvas.Handle, PChar(Text), -1, GR, DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER); end; end; end; end; function TdfsStatusPanel.InitGaugeBitmap: TBitmap; var r1, b1, g1, r2, b2, g2: byte; c1, c2: Longint; i: integer; divi: integer; mul: extended; begin c1 := ColorToRGB(StatusBar.Color); c2 := ColorToRGB(GaugeAttrs.Color); r1 := GetRValue(c1); b1 := GetBValue(c1); g1 := GetGValue(c1); r2 := GetRValue(c2); b2 := GetBValue(c2); g2 := GetGValue(c2); Result := TBitmap.Create; with Result do begin Height := StatusBar.Height; Width := 100; divi := Width-1; Canvas.Brush.Color := clRed; Canvas.FillRect(Rect(0, 0, Width, Height)); for i := 0 to divi do begin mul := (i/divi); Canvas.Pen.Color := RGB(trunc(r1 + (r2 - r1) * mul), trunc(g1 + (g2 - g1) *mul), trunc(b1 + (b2 - b1) * mul)); Canvas.MoveTo(i, 0); Canvas.LineTo(i, Height); end; end; end; procedure TdfsStatusPanel.DrawIndeterminateGauge(Canvas: TCanvas; R: TRect); var gb:TBitmap; gbr:TRect; x: integer; begin inc(FGaugeLastPos, FGaugeDirection); case GaugeAttrs.Style of gsIndeterminate: begin with Canvas do begin Brush.Color := GaugeAttrs.Color; Pen.Color := GaugeAttrs.Color; gbr := R; InflateRect(R, 0, -((R.Bottom - R.Top) div 3)); x := R.Bottom - R.Top; if (FGaugeDirection > 0) and ((FGaugeLastPos + X + 1) >= (R.Right - R.Left)) then begin FGaugeDirection := -GaugeAttrs.Speed; end else if (FGaugeDirection < 0) and (FGaugeLastPos <= 1) then begin FGaugeDirection := GaugeAttrs.Speed; end; Inc(R.Left, FGaugeLastPos); R.Right := R.Left + X; // Make it a wee bit bigger InflateRect(R, 1, 1); with R do Ellipse(Left, Top, Right, Bottom); end; end; gsIndeterminate2: begin with Canvas do begin gb := GaugeBitmap; if (FGaugeDirection > 0) and ((FGaugeLastPos+ 1) >= (R.Right - R.Left)) then FGaugeDirection := -FGaugeAttrs.Speed else if (FGaugeDirection < 0) and (FGaugeLastPos <= -gb.Width) then FGaugeDirection := FGaugeAttrs.Speed; Inc(R.Left, FGaugeLastPos); gbr := Rect(0, 0, gb.Width, gb.Height); if (r.right - r.left) > gb.width then r.right := r.left + gb.Width else if (r.right - r.left) < gb.width then begin if FGaugeDirection > 0 then gbr.Right := r.right - r.Left else gbr.Left := gbr.right - (r.right - r.left); end; if FGaugeDirection > 0 then CopyRect(r, gb.Canvas, gbr) else CopyRect(r, gb.Canvas, Rect(gbr.right-1, gbr.Bottom-1, gbr.left-1, gbr.top-1)) end; end; end; end; procedure TdfsStatusPanel.DrawKeyLock(Canvas: TCanvas; R: TRect); var DTFlags: UINT; OldColor: TColorRef; begin OldColor := GetTextColor(Canvas.Handle); if StatusBar.UseMonitorDLL then begin if not FKeyOn then SetTextColor(Canvas.Handle, ColorToRGB(clGrayText)) // might need to be a property else SetTextColor(Canvas.Handle, ColorToRGB(StatusBar.Font.Color)); end else begin if not Odd(GetKeyState(KEY_CODE[FPanelType])) then SetTextColor(Canvas.Handle, ColorToRGB(clGrayText)) // might need to be a property else SetTextColor(Canvas.Handle, ColorToRGB(StatusBar.Font.Color)); end; DTFlags := DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER; if AutoFit then DTFLags := DTFlags or DT_CENTER else case Alignment of taCenter: DTFlags := DTFlags or DT_CENTER; taRightJustify: DTFlags := DTFlags or DT_RIGHT; end; DrawText(Canvas.Handle, PChar(Text), -1, R, DTFlags); SetTextColor(Canvas.Handle, OldColor); end; procedure TdfsStatusPanel.DrawTextBased(Canvas: TCanvas; R: TRect); var DTFlags: UINT; begin DTFlags := DT_SINGLELINE or DT_NOPREFIX or DT_VCENTER; if AutoFit then DTFLags := DTFlags or DT_CENTER else case Alignment of taCenter: DTFlags := DTFlags or DT_CENTER; taRightJustify: begin dec(R.Right); DTFlags := DTFlags or DT_RIGHT; end; end; case PanelType of sptEllipsisPath: DTFlags := DTFlags or DT_PATH_ELLIPSIS; sptEllipsisText: DTFlags := DTFlags or DT_END_ELLIPSIS; end; SetTextColor(Canvas.Handle, ColorToRGB(StatusBar.Font.Color)); if PanelType = sptOwnerDraw then // This only happens when in design mode, see Redraw method. DrawText(Canvas.Handle, ' *OD* ', -1, R, DTFlags) else DrawText(Canvas.Handle, PChar(Text), -1, R, DTFlags); end; procedure TdfsStatusPanel.SetAlignment(const Value: TAlignment); begin if LinkedPanel.Alignment <> Value then begin LinkedPanel.Alignment := Value; Invalidate; end; end; procedure TdfsStatusPanel.SetAutoFit(const Value: boolean); begin if FAutoFit <> Value then begin FAutoFit := Value; UpdateAutoFitWidth; end; end; procedure TdfsStatusPanel.SetBevel(const Value: TStatusPanelBevel); begin if LinkedPanel.Bevel <> Value then LinkedPanel.Bevel := Value; end; {$IFDEF DFS_COMPILER_4_UP} procedure TdfsStatusPanel.SetBiDiMode(const Value: TBiDiMode); begin if LinkedPanel.BiDiMode <> Value then LinkedPanel.BiDiMode := Value; end; procedure TdfsStatusPanel.SetParentBiDiMode(const Value: Boolean); begin if LinkedPanel.ParentBiDiMode <> Value then LinkedPanel.ParentBiDiMode := Value; end; {$ENDIF} procedure TdfsStatusPanel.SetDateFormat(const Value: string); begin if FDateFormat <> Value then begin FDateFormat := Value; UpdateDateTime; end; end; procedure TdfsStatusPanel.SetEnabled(const Value: boolean); begin if FEnabled <> Value then begin FEnabled := Value; EnabledChanged; end; end; procedure TdfsStatusPanel.SetGlyph(const Value: TPicture); begin FGlyph.Assign(Value); // GlyphChanged method will take care of updating display. end; procedure TdfsStatusPanel.SetPanelType(const Val: TdfsStatusPanelType); const LOCK_TEXT: array[sptCapsLock..sptScrollLock] of string = ( SCapsLock, SNumLock, SScrollLock ); begin if Val <> FPanelType then begin if Enabled then case FPanelType of sptCapsLock, sptNumLock, sptScrollLock: begin if StatusBar.UseMonitorDLL then StatusBar.DeregisterSystemHook else begin DeregisterTaskKeyboardHook(Self); StatusBar.DeregisterMainWinHook(Self); end; end; sptDate, sptTime, sptDateTime, sptTimeDate: TdfsStatusPanels(Collection).DeregisterTimer(Self); sptGauge: if GaugeAttrs.Style in IndeterminateGuages then TdfsStatusPanels(Collection).DeregisterTimer(Self); end; FPanelType := Val; case FPanelType of sptCapsLock, sptNumLock, sptScrollLock: begin Text := LOCK_TEXT[FPanelType]; AutoFit := TRUE; if Enabled then begin if StatusBar.UseMonitorDLL then begin StatusBar.RegisterSystemHook; FKeyOn := Odd(GetKeyState(KEY_CODE[FPanelType])); end else begin RegisterTaskKeyboardHook(Self); StatusBar.RegisterMainWinHook(Self); end; end; end; sptDate, sptTime, sptDateTime, sptTimeDate: begin AutoFit := FALSE; if Enabled then TdfsStatusPanels(Collection).RegisterTimer(Self); UpdateDateTime; end; sptEllipsisText, sptEllipsisPath: begin AutoFit := FALSE; if Hint = '' then Hint := '...'; end; sptGlyph: begin AutoFit := TRUE; end; sptGauge: begin AutoFit := FALSE; Alignment := taCenter; if GaugeAttrs.Style in IndeterminateGuages then begin Enabled := FALSE; // Enabled is false, so don't need to register FGaugeLastPos := 0; FGaugeDirection := GaugeAttrs.Speed; end; end; else AutoFit := FALSE; end; Invalidate; end; end; procedure TdfsStatusPanel.SetText(const Value: string); begin //outputdebugstring(Pchar(value)); if FText <> Value then begin //outputdebugstring(Pchar(ftext)); FText := Value; //outputdebugstring(Pchar(ftext)); Invalidate; UpdateAutoFitWidth; end; end; procedure TdfsStatusPanel.SetTimeFormat(const Value: string); begin if FTimeFormat <> Value then begin FTimeFormat := Value; UpdateDateTime; end; end; procedure TdfsStatusPanel.SetWidth(const Value: Integer); begin if ((not FAutoFit) or (csLoading in StatusBar.ComponentState)) and (LinkedPanel.Width <> Value) then LinkedPanel.Width := Value; if (PanelType = sptGauge) and (GaugeAttrs.Style in IndeterminateGuages) then begin FGaugeLastPos := 0; FGaugeDirection := GaugeAttrs.Speed; Invalidate; end; end; procedure TdfsStatusPanel.TimerNotification; begin if PanelType in [sptDate, sptTime, sptDateTime, sptTimeDate] then UpdateDateTime else if (PanelType = sptGauge) and (GaugeAttrs.Style in IndeterminateGuages) then // Call Redraw directly. It will take care of erasing the old part. If we // used Invalidate, the background would get erased, too, and it would // flicker a lot. Redraw(StatusBar.Canvas, StatusBar.GetPanelRect(Index)); end; procedure TdfsStatusPanel.UpdateAutoFitWidth; begin if FAutoFit and (StatusBar <> NIL) and (StatusBar.HandleAllocated) then begin if PanelType = sptGlyph then begin if Text = '' then LinkedPanel.Width := BorderWidth + Glyph.Width + 4 else LinkedPanel.Width := StatusBar.TextExtent(Text).cx + 2 + (BorderWidth * 2) + Glyph.Width + 4; end else LinkedPanel.Width := StatusBar.TextExtent(Text).cx + 6 + BorderWidth; end; Invalidate; end; procedure TdfsStatusPanel.UpdateDateTime; var Fmt: string; Txt: string; begin case PanelType of sptDate: if DateFormat = '' then Fmt := ShortDateFormat else Fmt := DateFormat; sptTime: if TimeFormat = '' then Fmt := LongTimeFormat else Fmt := TimeFormat; sptDateTime: begin if DateFormat = '' then Fmt := ShortDateFormat else Fmt := DateFormat; if TimeFormat = '' then Fmt := Fmt + ' ' + LongTimeFormat else Fmt := Fmt + ' ' + TimeFormat; end; sptTimeDate: begin if TimeFormat = '' then Fmt := LongTimeFormat else Fmt := TimeFormat; if DateFormat = '' then Fmt := Fmt + ' ' + ShortDateFormat else Fmt := Fmt + ' ' + DateFormat; end; end; Txt := FormatDateTime(Fmt, Now); if Txt <> Text then begin Text := Txt; // Invalidate(TRUE); Redraw(Statusbar.Canvas, StatusBar.GetPanelRect(Index)); end; end; procedure TdfsStatusPanel.GlyphChanged(Sender: TObject); begin if PanelType = sptGlyph then begin Invalidate; UpdateAutoFitWidth; end; end; procedure TdfsStatusPanel.DrawPanel(Rect: TRect); begin if (csDesigning in StatusBar.ComponentState) or (Addr(OnDrawPanel) = NIL) or (PanelType <> sptOwnerDraw) then Redraw(StatusBar.Canvas, StatusBar.GetPanelRect(Index)) else if assigned(FOnDrawPanel) then FOnDrawPanel(StatusBar, Self, Rect); end; function TdfsStatusPanel.GetEnabled: boolean; begin if csWriting in StatusBar.ComponentState then Result := FEnabled else Result := FEnabled and StatusBar.Enabled; end; procedure TdfsStatusPanel.EnabledChanged; begin // Enabled property (self or parent) changed, update register/deregister calls if Enabled then begin case FPanelType of sptCapsLock, sptNumLock, sptScrollLock: begin if StatusBar.UseMonitorDLL then begin StatusBar.RegisterSystemHook; FKeyOn := Odd(GetKeyState(KEY_CODE[FPanelType])); end else begin RegisterTaskKeyboardHook(Self); StatusBar.RegisterMainWinHook(Self); end; end; sptDate, sptTime, sptDateTime, sptTimeDate: TdfsStatusPanels(Collection).RegisterTimer(Self); sptGauge: if GaugeAttrs.Style in IndeterminateGuages then TdfsStatusPanels(Collection).RegisterTimer(Self); end; end else begin case FPanelType of sptCapsLock, sptNumLock, sptScrollLock: begin if StatusBar.UseMonitorDLL then StatusBar.DeregisterSystemHook else begin DeregisterTaskKeyboardHook(Self); StatusBar.DeregisterMainWinHook(Self); end; end; sptDate, sptTime, sptDateTime, sptTimeDate: TdfsStatusPanels(Collection).DeregisterTimer(Self); sptGauge: if GaugeAttrs.Style in IndeterminateGuages then TdfsStatusPanels(Collection).DeregisterTimer(Self); end; end; Invalidate; if not Enabled then begin FGaugeLastPos := 0; FGaugeDirection := GaugeAttrs.Speed; end; end; function TdfsStatusPanel.GetHint: string; begin if (not (csDesigning in StatusBar.ComponentState)) and (PanelType in [sptEllipsisText, sptEllipsisPath]) and (FHint = '...') then Result := Text else Result := FHint; DoHintText(Result); end; procedure TdfsStatusPanel.DoHintText(var HintText: string); begin if assigned(FOnHintText) then FOnHintText(StatusBar, Self, HintText); end; procedure TdfsStatusPanel.SetGaugeAttrs(const Value: TdfsGaugeAttrs); begin FGaugeAttrs := Value; end; function TdfsStatusPanel.GetDisplayName: string; begin case PanelType of sptNormal, sptEllipsisText, sptEllipsisPath: Result := Text; else Result := GetEnumName(TypeInfo(TdfsStatusPanelType), ord(PanelType)); end; if Result = '' then Result := inherited GetDisplayName; end; procedure TdfsStatusPanel.SetIndex(Value: integer); var CurIndex: Integer; begin CurIndex := Index; if (CurIndex >= 0) and (CurIndex <> Value) then begin TdfsStatusPanels(Collection).FLinkedPanels[CurIndex].Index := Value; inherited SetIndex(Value); end; end; function TdfsStatusPanel.GetLinkedPanel: TStatusPanel; begin Result := TdfsStatusPanels(Collection).FLinkedPanels[Index]; end; procedure TdfsStatusPanel.UpdateKeyboardHook; begin if PanelType in [sptCapsLock, sptNumLock, sptScrollLock] then begin if StatusBar.UseMonitorDLL and Enabled then begin DeregisterTaskKeyboardHook(Self); StatusBar.DeregisterMainWinHook(Self); StatusBar.RegisterSystemHook; FKeyOn := Odd(GetKeyState(KEY_CODE[FPanelType])); end else if (not StatusBar.UseMonitorDLL) and Enabled then begin StatusBar.DeregisterSystemHook; RegisterTaskKeyboardHook(Self); StatusBar.RegisterMainWinHook(Self); end; end; end; procedure TdfsStatusPanel.Click; begin if assigned(FOnClick) then FOnClick(Self); end; function TdfsStatusPanel.GetGaugeBitmap: TBitmap; begin if FGaugeBitmap = NIL then FGaugeBitmap := InitGaugeBitmap; Result := FGaugeBitmap; end; procedure TdfsStatusPanel.SetBorderWidth(const Value: TBorderWidth); begin if FBorderWidth <> Value then begin FBorderWidth := Value; UpdateAutoFitWidth; Invalidate; end; end; function TdfsStatusPanel.IsTextStored: Boolean; begin Result := not (PanelType in [sptDate, sptTime, sptDateTime, sptTimeDate]); end; { TdfsStatusPanels } function TdfsStatusPanels.Add: TdfsStatusPanel; begin Result := TdfsStatusPanel(inherited Add); end; constructor TdfsStatusPanels.Create(StatusBar: TdfsStatusBar; LinkedPanels: TStatusPanels); begin FStatusBar := StatusBar; FLinkedPanels := LinkedPanels; FTimer := NIL; FTimerClients := TList.Create; inherited Create(TdfsStatusPanel); end; procedure TdfsStatusPanels.DeregisterTimer(Client: TdfsStatusPanel); var x: integer; NewTimerRes: integer; begin if FTimerClients.Remove(Client) <> -1 then dec(RegisteredTimers); if FTimerClients.Count < 1 then begin FTimer.Free; FTimer := NIL; end else begin NewTimerRes := 60000; // Least impact we can manage easily for x := 0 to FTimerClients.Count-1 do case TdfsStatusPanel(FTimerClients[x]).PanelType of sptTime, sptDateTime, sptTimeDate: NewTimerRes := 1000; sptGauge: if TdfsStatusPanel(FTimerClients[x]).GaugeAttrs.Style in IndeterminateGuages then begin NewTimerRes := INDETERMINATE_GAUGE_UPDATE_INTERVAL; break; end; end; FTimer.Interval := NewTimerRes; end; end; destructor TdfsStatusPanels.Destroy; begin // Call inherited first because it causes children to be destroyed, and that // might cause FTimerClients to be needed. inherited Destroy; FTimer.Free; FTimer := NIL; FTimerClients.Free; FTimerClients := NIL; // Yes, there is a reason for this! end; function TdfsStatusPanels.GetItem(Index: Integer): TdfsStatusPanel; begin Result := TdfsStatusPanel(inherited GetItem(Index)); end; function TdfsStatusPanels.GetOwner: TPersistent; begin Result := FStatusBar; end; procedure TdfsStatusPanels.RegisterTimer(Client: TdfsStatusPanel); var FirstClient: boolean; begin if FTimer = NIL then begin FTimer := TTimer.Create(FStatusBar); FLastDate := Date; FTimer.OnTimer := TimerEvent; end; if FTimerClients.IndexOf(Client) >= 0 then exit; // We're already in the list! FTimerClients.Add(Client); inc(RegisteredTimers); FirstClient := FTimerClients.Count = 1; case Client.PanelType of sptDate: if FirstClient then FTimer.Interval := 60000; // Least impact we can manage easily sptTime, sptDateTime, sptTimeDate: if FirstClient or (FTimer.Interval > 1000) then FTimer.Interval := 1000; sptGauge: if Client.GaugeAttrs.Style in IndeterminateGuages then FTimer.Interval := INDETERMINATE_GAUGE_UPDATE_INTERVAL; end; FTimer.Enabled := TRUE; end; procedure TdfsStatusPanels.SetItem(Index: Integer; Value: TdfsStatusPanel); begin // I have no idea if this will work or not.... inherited SetItem(Index, Value); FLinkedPanels[Index] := Value.LinkedPanel; end; procedure TdfsStatusPanels.TimerEvent(Sender: TObject); var x: integer; DateUpdate: boolean; Panel: TdfsStatusPanel; begin if FLastDate <> Date then begin DateUpdate := TRUE; FLastDate := Date; end else DateUpdate := FALSE; for x := 0 to FTimerClients.Count-1 do begin Panel := TdfsStatusPanel(FTimerClients[x]); // shorthand if (Panel.PanelType in [sptTime, sptDateTime, sptTimeDate]) or (DateUpdate and (Panel.PanelType = sptDate)) or ((Panel.PanelType = sptGauge) and (Panel.GaugeAttrs.Style in IndeterminateGuages)) then TdfsStatusPanel(FTimerClients[x]).TimerNotification; end; end; procedure TdfsStatusPanels.Update(Item: TCollectionItem); begin if Item is TdfsStatusPanel then TdfsStatusPanel(Item).Invalidate else FStatusBar.Invalidate; end; { TdfsStatusBar } constructor TdfsStatusBar.Create(AOwner: TComponent); begin FExtentCanvas := CreateCompatibleDC(0); FExtentFont := 0; FExtentFontOld := 0; FUseMonitorDLL := FALSE; FDLLClientCount := 0; FMainWinHookClients := TList.Create; inherited Create(AOwner); // Allow it to accept controls dropped onto it. ControlStyle:= ControlStyle + [csAcceptsControls]; FPanels := TdfsStatusPanels.Create(Self, inherited Panels); end; procedure TdfsStatusBar.InvalidatePanel(Index: integer); var PanelRect: TRect; begin if (Index >= 0) and (Index < Panels.Count) then begin PanelRect := GetPanelRect(Index); if not IsRectEmpty(PanelRect) then Panels[Index].Redraw(Canvas, PanelRect) end else begin {$IFDEF DFS_COMPILER_6_UP} TList.Error(@SListIndexError, Index); {$ELSE} {$IFDEF DFS_COMPILER_3_UP} raise EListError.Create(SListIndexError); {$ELSE} raise EListError.CreateRes(SListIndexError); {$ENDIF} {$ENDIF} end; end; function TdfsStatusBar.GetPanelRect(Index: integer): TRect; begin SetRectEmpty(Result); if HandleAllocated then if Perform(SB_GETRECT, Index, LPARAM(@Result)) = 0 then SetRectEmpty(Result); // SB_GETRECT failed, probably not visible end; procedure TdfsStatusBar.SetPanels(const Value: TdfsStatusPanels); begin FPanels.Assign(Value); // what about linked panels???? end; destructor TdfsStatusBar.Destroy; begin FPanels.Free; SelectObject(FExtentCanvas, FExtentFontOld); if FExtentFont <> 0 then begin DeleteObject(FExtentFont); FExtentFont := 0; end; if FExtentCanvas <> 0 then begin DeleteDC(FExtentCanvas); FExtentCanvas := 0; end; Assert(FMainWinHookClients.Count = 0, 'Unbalanced MainWinHook registrations'); inherited Destroy; FMainWinHookClients.Free; end; procedure TdfsStatusBar.DrawPanel(Panel: TStatusPanel; const Rect: TRect); var DFSPanel: TdfsStatusPanel; OldFont: HFONT; begin // Panel is the REAL TStatusPanel, we need to find our special one. DFSPanel := FindLinkedPanel(Panel); Assert(DFSPanel <> NIL, 'Panel links corrupted'); // Stupid VCL status bar doesn't always have the right font in Canvas. OldFont := SelectObject(Canvas.Handle, FExtentFont); try if Addr(OnDrawPanel) <> NIL then inherited DrawPanel(TStatusPanel(DFSPanel), Rect); DFSPanel.DrawPanel(Rect); finally SelectObject(Canvas.Handle, OldFont); end; end; function TdfsStatusBar.FindLinkedPanel(Panel: TStatusPanel): TdfsStatusPanel; var x: integer; begin Result := NIL; for x := 0 to Panels.Count-1 do if Panels[x].LinkedPanel = Panel then begin Result := Panels[x]; break; end; end; function TdfsStatusBar.AppWinHook(var Message: TMessage): boolean; begin if Message.Msg = WM_ACTIVATEAPP then begin if UseMonitorDLL then begin { if Message.wParam = 1 then PostMessage(Handle, WM_REFRESHLOCKINDICATORS, 0, 0);} end else begin // We're being deactivated, someone may change an indicator and that will // screw up the GetKeyState API call. if Message.wParam = 0 then MayNeedRefresh := TRUE; // Won't work in some situations if we call it directly. PostMessage(Handle, WM_REFRESHLOCKINDICATORS, 0, 0); end; end; Result := FALSE; end; procedure TdfsStatusBar.WMRefreshLockIndicators(var Msg: TMessage); var x: integer; begin Panels.BeginUpdate; try for x := 0 to Panels.Count-1 do if Panels[x].PanelType in [sptCapsLock, sptNumLock, sptScrollLock] then InvalidatePanel(Panels[x].Index); finally Panels.EndUpdate; end; end; procedure TdfsStatusBar.CMFontChanged(var Msg: TMessage); var x: integer; begin inherited; UpdateExtentFont; if Panels = NIL then exit; Panels.BeginUpdate; try for x := 0 to Panels.Count-1 do if Panels[x].AutoFit then Panels[x].UpdateAutoFitWidth; finally Panels.EndUpdate; end; end; procedure TdfsStatusBar.SetOnDrawPanel(const Value: TdfsDrawPanelEvent); begin inherited OnDrawPanel := TDrawPanelEvent(Value); end; function TdfsStatusBar.GetOnDrawPanel: TdfsDrawPanelEvent; begin TDrawPanelEvent(Result) := inherited OnDrawPanel; end; function TdfsStatusBar.GetVersion: string; begin Result := DFS_COMPONENT_VERSION; end; procedure TdfsStatusBar.SetVersion(const Val: string); begin { empty write method, just needed to get it to show up in Object Inspector } end; procedure TdfsStatusBar.CMEnabledChanged(var Msg: TMessage); var x: integer; begin inherited; Invalidate; for x := 0 to Panels.Count-1 do Panels[x].EnabledChanged; end; procedure TdfsStatusBar.CMHintShow(var Msg: TMessage); function FindClosestBefore(x: integer): TdfsStatusPanel; var y: integer; begin Result := NIL; for y := 0 to Panels.Count-1 do begin if GetPanelRect(y).Left < x then Result := Panels[y] else break; end; (* If I do it this way, it screws up. Optimizaer bug, maybe? for y := Panels.Count-1 downto 0 do begin if GetPanelRect(y).Left < x then begin Result := Panels[y]; break; end; end;*) end; function FindClosestAfter(x: integer): TdfsStatusPanel; var y: integer; begin Result := NIL; for y := 0 to Panels.Count-1 do begin if GetPanelRect(y).Right > x then begin Result := Panels[y]; break; end; end; end; var x: integer; Panel: TdfsStatusPanel; R: TRect; begin inherited; with TCMHintShow(Msg) do begin begin Panel := NIL; for x := 0 to Panels.Count-1 do begin if PtInRect(GetPanelRect(x), HintInfo.CursorPos) then begin Panel := Panels[x]; break; end; end; if (Panel = NIL) or (Panel.Hint = '') then begin // Hit a border, or a panel without a hint. What we have to do here is // tell the hint info how big of a rectangle the hint applies to. So, // we must find the first panel before this point with a hint, and the // first panel after this point with a hint and set CursorRect equal to // the area between those two panels. CursorRect already has the area // of the status bar, so if we don't find a panel, it's ok. // Find first valid panel before hint position and set CursorRect.Left Panel := FindClosestBefore(HintInfo.CursorPos.x); while (Panel <> NIL) do begin R := GetPanelRect(Panel.Index); if Panel.Hint <> '' then begin HintInfo.CursorRect.Left := R.Right; Panel := NIL; end else Panel := FindClosestBefore(R.Left); end; // Find first valid panel after hint position and set CursorRect.Right Panel := FindClosestAfter(HintInfo.CursorPos.x); while (Panel <> NIL) do begin R := GetPanelRect(Panel.Index); if Panel.Hint <> '' then begin HintInfo.CursorRect.Right := R.Left; Panel := NIL; end else Panel := FindClosestAfter(R.Right); end; end else begin // Give it the hint of the panel HintInfo.HintStr := Panel.Hint; // Tell the hint mechanism that it needs to check the hint when the // cursor leaves the panel rectangle. HintInfo.CursorRect := GetPanelRect(Panel.Index); end; end; end; end; procedure TdfsStatusBar.DeregisterMainWinHook(Client: TdfsStatusPanel); begin FMainWinHookClients.Remove(Client); Assert(FMainWinHookClients.Count >= 0, 'Unbalanced MainWinHook registrations'); if FMainWinHookClients.Count < 1 then Application.UnhookMainWindow(AppWinHook); end; procedure TdfsStatusBar.RegisterMainWinHook(Client: TdfsStatusPanel); begin FMainWinHookClients.Add(Client); if FMainWinHookClients.Count = 1 then Application.HookMainWindow(AppWinHook); end; procedure TdfsStatusBar.Loaded; var x: integer; begin inherited Loaded; UpdateExtentFont; for x := 0 to Panels.Count-1 do if Panels[x].AutoFit then Panels[x].UpdateAutoFitWidth; end; procedure TdfsStatusBar.CreateWnd; var x: integer; begin inherited CreateWnd; if not (csLoading in ComponentState) then begin UpdateExtentFont; for x := 0 to Panels.Count-1 do if Panels[x].AutoFit then Panels[x].UpdateAutoFitWidth; end; if FDLLClientCount > 0 then FKeyHookMsg := DLLRegisterKeyboardHook(Handle); end; procedure TdfsStatusBar.WMDestroy(var Msg: TWMDestroy); begin if FUseMonitorDLL and (FDLLClientCount > 0) then DLLDeregisterKeyboardHook(Handle); inherited; end; function TdfsStatusBar.TextExtent(const Text: string): TSize; begin if not GetTextExtentPoint32(FExtentCanvas, PChar(Text), Length(Text), Result) then begin Result.cx := -1; Result.cy := -1; end; end; procedure TdfsStatusBar.UpdateExtentFont; begin if FExtentFont <> 0 then begin SelectObject(FExtentCanvas, FExtentFontOld); DeleteObject(FExtentFont); end; // In D4, the font handle might be different than what TFont describes! FExtentFont := CopyHFont(Font.Handle); FExtentFontOld := SelectObject(FExtentCanvas, FExtentFont); end; procedure TdfsStatusBar.SetUseMonitorDLL(const Value: boolean); begin if FUseMonitorDLL <> Value then begin FUseMonitorDLL := Value; UpdateKeyboardHooks; if FUseMonitorDLL and (not DFSKbDLL_Loaded) {and not (csDesigning in ComponentState)} then begin UseMonitorDLL := FALSE; if csDesigning in ComponentState then raise Exception.Create('Could not load ' + DFSKbDLLName); end; end; end; procedure TdfsStatusBar.UpdateKeyboardHooks; var x: integer; begin for x := 0 to Panels.Count-1 do Panels[x].UpdateKeyboardHook; end; procedure TdfsStatusBar.DeregisterSystemHook; begin dec(FDLLClientCount); if FDLLClientCount < 1 then begin if DFSKbDLL_Loaded and HandleAllocated then DLLDeregisterKeyboardHook(Handle); FDLLClientCount := 0; if DFSKbDLL_Loaded then UnloadDFSKbDLL; end; end; procedure TdfsStatusBar.RegisterSystemHook; begin inc(FDLLClientCount); if (FDLLClientCount = 1) {and not (csDesigning in ComponentState)} then begin if not DFSKbDLL_Loaded then IniTdfsKbDLL; if HandleAllocated and DFSKbDLL_Loaded then FKeyHookMsg := DLLRegisterKeyboardHook(Handle); end; end; procedure TdfsStatusBar.WndProc(var Msg: TMessage); function VKToPanelType(VKCode: byte): TdfsStatusPanelType; begin case VKCode of VK_NUMLOCK: Result := sptNumLock; VK_SCROLL: Result := sptScrollLock; else Result := sptCapsLock; end; end; var x: integer; begin if Msg.Msg = FKeyHookMsg then begin for x := 0 to Panels.Count-1 do if VKToPanelType(Msg.wParam) = Panels[x].PanelType then begin Panels[x].FKeyOn := Odd(Msg.lParam); Panels[x].Invalidate; end; end else inherited WndProc(Msg); end; procedure TdfsStatusBar.Click; var x: integer; CursorPos: TPoint; begin GetCursorPos(CursorPos); CursorPos := ScreenToClient(CursorPos); for x := 0 to Panels.Count-1 do begin if PtInRect(GetPanelRect(x), CursorPos) then begin Panels[x].Click; break; end; end; inherited Click; end; procedure TdfsStatusBar.WMPaint(var Msg: TWMPaint); procedure DrawSizeGrip(R: TRect); begin OffsetRect(R, -1, -1); with Canvas do begin Brush.Color := Color; Pen.Width := 1; FillRect(R); Pen.Color := clBtnHighlight; MoveTo(R.Right - 2, R.Bottom); LineTo(R.Right, R.Bottom - 2); MoveTo(R.Right - 13, R.Bottom); LineTo(R.Right, R.Bottom - 13); MoveTo(R.Right - 9, R.Bottom); LineTo(R.Right, R.Bottom - 9); MoveTo(R.Right - 5, R.Bottom); LineTo(R.Right, R.Bottom - 5); MoveTo(R.Right - 1, R.Bottom); LineTo(R.Right, R.Bottom); Pen.Color := clBtnShadow; MoveTo(R.Right - 11, R.Bottom); LineTo(R.Right, R.Bottom - 11); MoveTo(R.Right - 7, R.Bottom); LineTo(R.Right, R.Bottom - 7); MoveTo(R.Right - 3, R.Bottom); LineTo(R.Right, R.Bottom - 3); Brush.Color := clBtnFace; Pen.Color := clBtnShadow; MoveTo(R.Left, R.Top); LineTo(R.Right, R.Top); end; end; var R: TRect; DC: HDC; PS: tagPaintStruct; begin if Mouse.IsDragging then begin DC := BeginPaint(Handle, PS); EndPaint(Handle, PS); exit; end; inherited; if Color <> clBtnFace then begin R := ClientRect; R.Left := R.Right - 15; Inc(R.Top, 3); dec(R.Bottom); DrawSizeGrip(R); end; end; {$IFDEF DFS_COMPILER_4_UP} function TdfsStatusBar.ExecuteAction(Action: TBasicAction): Boolean; begin // outputdebugstring(Pchar(panels[0].ftext)); Result := inherited ExecuteAction(Action); // outputdebugstring(Pchar(panels[0].ftext)); Invalidate; // outputdebugstring(Pchar(panels[0].ftext)); end; {$ENDIF} initialization {$IFDEF DFS_DEBUG} DFSDebug.Log('dfsStatusBar: init begin', TRUE); {$ENDIF} MayNeedRefresh := FALSE; KeyboardHookHandle := 0; KeyHookClients := TList.Create; RegisteredTimers := 0; {$IFDEF DFS_DEBUG} DFSDebug.Log('dfsStatusBar: init end.', TRUE); {$ENDIF} finalization {$IFDEF DFS_DEBUG} DFSDebug.Log('dfsStatusBar: finalization begin.', TRUE); {$ENDIF} // remove hook just in case it somehow got left installed if KeyboardHookHandle <> 0 then begin UnhookWindowsHookEx(KeyboardHookHandle); KeyboardHookHandle := 0; Assert(FALSE, 'TdfsStatusBar: Keyboard hook still installed'); end; Assert(RegisteredTimers = 0, 'TdfsStatusBar: Unbalanced timer registrations'); KeyHookClients.Free; KeyHookClients := NIL; if DFSKb.DFSKbDLL_Loaded then UnloadDFSKbDLL; {$IFDEF DFS_DEBUG} DFSDebug.Log('dfsStatusBar: finalization end.', TRUE); {$ENDIF} end.
unit Rotas.Bancos; interface uses Horse; procedure Bancos_Get(Req: THorseRequest; Res: THorseResponse; Next: TProc); implementation uses System.SysUtils, uDM, System.JSON, Horse.Commons, DataSet.Serialize, uFuncoes; procedure Bancos_Get(Req: THorseRequest; Res: THorseResponse; Next: TProc); var ADM: TDM; sID: String; begin Req.Params.TryGetValue('id', sID); ADM := TDM.Create(nil); try ADM.qrBancos.Close; if not sID.IsEmpty then begin ADM.qrBancos.SQL.Add('where id = :id'); ADM.qrBancos.Params[0].AsString := sID; end; ADM.qrBancos.Open; if ADM.qrBancos.RecordCount = 0 then GerarErro(Res, 'Nenhuma informação localizada.'); if sID.IsEmpty then Res.Send<TJSONArray>(ADM.qrBancos.ToJSONArray()) else Res.Send<TJSONObject>(ADM.qrBancos.ToJSONObject()); finally ADM.Free; end; end; end.
unit IdAboutVCL; interface {$I IdCompilerDefines.inc} uses {$IFDEF WIDGET_KYLIX} QStdCtrls, QForms, QExtCtrls, QControls, QComCtrls, QGraphics, Qt, {$ENDIF} {$IFDEF WIDGET_VCL_LIKE} StdCtrls, Buttons, ExtCtrls, Graphics, Controls, ComCtrls, Forms, {$ENDIF} {$IFDEF HAS_UNIT_Types} Types, {$ENDIF} {$IFDEF WIDGET_LCL} LResources, {$ENDIF} Classes, SysUtils; type TfrmAbout = class(TForm) protected FimLogo : TImage; FlblCopyRight : TLabel; FlblName : TLabel; FlblVersion : TLabel; FlblPleaseVisitUs : TLabel; FlblURL : TLabel; //for LCL, we use a TBitBtn to be consistant with some GUI interfaces //and the Lazarus IDE. {$IFDEF USE_TBitBtn} FbbtnOk : TBitBtn; {$ELSE} FbbtnOk : TButton; {$ENDIF} procedure lblURLClick(Sender: TObject); function GetProductName: String; procedure SetProductName(const AValue: String); function GetVersion: String; procedure SetVersion(const AValue: String); public class procedure ShowDlg; class procedure ShowAboutBox(const AProductName, AProductVersion: String); constructor Create(AOwner : TComponent); overload; override; constructor Create; reintroduce; overload; property ProductName : String read GetProductName write SetProductName; property Version : String read GetVersion write SetVersion; end; implementation {$IFNDEF WIDGET_LCL} {$IFDEF WIN32} {$R IdAboutVCL.RES} {$ENDIF} {$IFDEF KYLIX} {$R IdAboutVCL.RES} {$ENDIF} {$ENDIF} uses {$IFDEF WIN32}ShellApi, {$ENDIF} {$IFNDEF WIDGET_LCL} //done this way because we reference HInstance in Delphi for loading //resources. Lazarus does something different. {$IFDEF WIN32} Windows, {$ENDIF} {$ENDIF} IdDsnCoreResourceStrings, IdGlobal; { TfrmAbout } constructor TfrmAbout.Create(AOwner: TComponent); begin inherited CreateNew(AOwner,0); FimLogo := TImage.Create(Self); FlblCopyRight := TLabel.Create(Self); FlblName := TLabel.Create(Self); FlblVersion := TLabel.Create(Self); FlblPleaseVisitUs := TLabel.Create(Self); FlblURL := TLabel.Create(Self); {$IFDEF USE_TBitBtn} FbbtnOk := TBitBtn.Create(Self); {$ELSE} FbbtnOk := TButton.Create(Self); {$ENDIF} Name := 'formAbout'; Left := 0; Top := 0; Anchors := [];//[akLeft, akTop, akRight,akBottom]; BorderIcons := [biSystemMenu]; BorderStyle := bsDialog; Caption := RSAAboutFormCaption; ClientHeight := 336; ClientWidth := 554; Color := clBtnFace; Font.Color := clBtnText; Font.Height := -11; Font.Name := 'Tahoma'; Font.Style := []; Position := poScreenCenter; {$IFDEF WIDGET_VCL} Scaled := True; {$ENDIF} Self.Constraints.MinHeight := Height; Self.Constraints.MinWidth := Width; // PixelsPerInch := 96; with FimLogo do begin Name := 'imLogo'; Parent := Self; Left := 0; Top := 0; Width := 388; Height := 240; {$IFDEF WIDGET_LCL} Picture.Bitmap.LoadFromLazarusResource('IndyCar');//this is XPM format {$ENDIF} {$IFDEF WIDGET_VCL_LIKE_OR_KYLIX} Picture.Bitmap.LoadFromResourceName(HInstance, 'INDYCAR'); {Do not Localize} Transparent := True; {$ENDIF} end; with FlblName do begin Name := 'lblName'; Parent := Self; Left := 390; Top := 8; Width := 160; Height := 104; Alignment := taCenter; AutoSize := False; Anchors := [akLeft, akTop, akRight]; {$IFDEF WIDGET_VCL} Font.Charset := DEFAULT_CHARSET; Transparent := True; {$ENDIF} Font.Color := clBtnText; Font.Height := -16; Font.Name := 'Verdana'; Font.Style := [fsBold]; ParentFont := False; WordWrap := True; end; with FlblVersion do begin Name := 'lblVersion'; Parent := Self; Left := 390; Top := 72; Width := 160; Height := 40; Alignment := taCenter; AutoSize := False; {$IFDEF WIDGET_VCL} Font.Charset := DEFAULT_CHARSET; Transparent := True; {$ENDIF} Font.Color := clBtnText; Font.Height := -15; Font.Name := 'Verdana'; Font.Style := [fsBold]; ParentFont := False; Anchors := [akLeft, akTop, akRight]; end; with FlblCopyRight do begin Name := 'lblCopyRight'; Parent := Self; Left := 390; Top := 128; Width := 160; Height := 112; Alignment := taCenter; Anchors := [akLeft, akTop, akRight]; AutoSize := False; Caption := RSAAboutBoxCopyright; {$IFDEF WIDGET_VCL} Font.Charset := DEFAULT_CHARSET; Transparent := True; {$ENDIF} Font.Color := clBtnText; Font.Height := -13; Font.Name := 'Verdana'; Font.Style := [fsBold]; ParentFont := False; WordWrap := True; end; with FlblPleaseVisitUs do begin Name := 'lblPleaseVisitUs'; Parent := Self; Left := 8; Top := 244; Width := 540; Height := 23; Alignment := taCenter; AutoSize := False; {$IFDEF WIDGET_VCL} Font.Charset := DEFAULT_CHARSET; Transparent := True; {$ENDIF} Font.Height := -13; Font.Name := 'Verdana'; Caption := RSAAboutBoxPleaseVisit; Anchors := [akLeft, akTop, akRight]; end; with FlblURL do begin Name := 'lblURL'; Left := 8; Top := 260; Width := 540; Height := 23; Cursor := crHandPoint; Alignment := taCenter; AutoSize := False; {$IFDEF WIDGET_VCL} Font.Charset := DEFAULT_CHARSET; Transparent := True; {$ENDIF} Font.Color := clBlue; Font.Height := -13; Font.Name := 'Verdana'; Font.Style := [fsUnderline]; ParentFont := False; OnClick := lblURLClick; Caption := RSAAboutBoxIndyWebsite; Anchors := [akLeft, akTop, akRight]; Parent := Self; end; with FbbtnOk do begin Name := 'bbtnOk'; Left := 475; {$IFDEF USE_TBitBtn} Top := 297; {$ELSE} Top := 302; Height := 25; {$ENDIF} Width := 75; Anchors := [akRight, akBottom]; {$IFDEF USE_TBitBtn} Kind := bkOk; {$ELSE} Cancel := True; Default := True; ModalResult := 1; Caption := RSOk; {$ENDIF} TabOrder := 0; Anchors := [akLeft, akTop, akRight]; Parent := Self; end; end; function TfrmAbout.GetVersion: String; begin Result := FlblVersion.Caption; end; function TfrmAbout.GetProductName: String; begin Result := FlblName.Caption; end; procedure TfrmAbout.lblURLClick(Sender: TObject); begin {$IFDEF WIN32} ShellAPI.shellExecute(Handle,PChar('open'),PChar(FlblURL.Caption),nil,nil, 0); {Do not Localize} FlblURL.Font.Color := clPurple; {$ENDIF} end; procedure TfrmAbout.SetVersion(const AValue: String); begin FlblVersion.Caption := AValue; end; procedure TfrmAbout.SetProductName(const AValue: String); begin FlblName.Caption := AValue; end; class procedure TfrmAbout.ShowAboutBox(const AProductName, AProductVersion: String); begin with TfrmAbout.Create do try Version := IndyFormat(RSAAboutBoxVersion, [AProductVersion]); ProductName := AProductName; ShowModal; finally Free; end; end; class procedure TfrmAbout.ShowDlg; begin ShowAboutBox(RSAAboutBoxCompName, gsIdVersion); end; constructor TfrmAbout.Create; begin Create(nil); end; {$IFDEF WIDGET_LCL} initialization {$i IdAboutVCL.lrs} {$ENDIF} end.
unit About; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Dialogs; type TAboutBox = class(TForm) Panel1: TPanel; OKButton: TButton; Memo1: TMemo; ProgramIcon: TImage; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var AboutBox: TAboutBox; implementation {$R *.DFM} procedure TAboutBox.FormCreate(Sender: TObject); const InfoNum = 10; InfoStr: array[ 1..InfoNum ] of string = ( 'CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright', 'LegalTradeMarks', 'OriginalFileName', 'ProductName', 'ProductVersion', 'Comments' ); InfoTrans: array[ 1..InfoNum ] of string = ( 'Compaņia ', 'Archivo ', 'Version ', 'Nombre Interno ', 'Copyright ', 'TradeMark:', 'Original ', 'Producto:', 'Version Producto ', 'Comentarios ' ); type TTranslationPair = packed record Lang, CharSet: word; end; PTranslationIDList = ^TTranslationIDList; TTranslationIDList = array[0..MAXINT div SizeOf(TTranslationPair)-1] of TTranslationPair; var lpArch: PChar; Handle, Len: Cardinal; Buf: PChar; Value: Pointer; i: integer; StringFile: array[ 0..49 ] of char; tempo: string; IDs: PTranslationIDList; begin try GetMem( lpArch, 126 ); Handle := 0; StrPCopy( lpArch, Application.Exename ); Len := GetFileVersionInfoSize( lpArch, Handle ); if Len <= 0 then exit; Buf := AllocMem( Len ); GetFileVersionInfo( lpArch, Handle, Len, Buf ); if not VerQueryValue( Buf, PChar( 'VarFileInfo\Translation\' ), Pointer( IDs ), len ) then exit; Tempo := Format( '%.4x%.4x', [ IDs^[0].Lang, IDs^[0].CharSet ] ); for i:=1 to 10 do begin StrPCopy( StringFile, '\StringFileInfo\' + Tempo + '\' + InfoStr[i] ); if VerQueryValue( Buf, StringFile, Value, len ) then Memo1.Lines.Add( InfoTrans[i] + ' = ' + StrPas( PAnsiChar(Value ))); end; finally freeMem( lpArch, 126 ); freeMem( Buf, Len ); end; end; end.
unit SProc; interface uses Windows; procedure SReplace(var s: WideString; const sfrom, sto: WideString); function SFormatS(const Msg: WideString; Params: array of WideString): WideString; function ToOEM(const s: string): string; function ToANSI(const s: string): string; function SExtractFileDir(const FileName: WideString): WideString; function SExtractFilePath(const FileName: WideString): WideString; function SExtractFileExt(const FileName: WideString): WideString; function SFindString(const F, S: string; fWholeWords, fCaseSens: boolean): integer; function Min(n1, n2: integer): integer; function Max(n1, n2: integer): integer; implementation procedure SReplace(var s: WideString; const sfrom, sto: WideString); var i: integer; begin i:= Pos(sfrom, s); if i>0 then begin Delete(s, i, Length(sfrom)); Insert(sto, s, i); end; end; function SFormatS(const Msg: WideString; Params: array of WideString): WideString; var i: integer; begin Result:= Msg; for i:= Low(Params) to High(Params) do SReplace(Result, '%s', Params[i]); end; function ToOEM(const s: string): string; begin SetLength(Result, Length(s)); CharToOemBuff(PChar(s), PChar(Result), Length(s)); end; function ToANSI(const s: string): string; begin SetLength(Result, Length(s)); OemToCharBuff(PChar(s), PChar(Result), Length(s)); end; function LastDelimiter(const Delimiters, S: WideString): Integer; var i: integer; begin for i:= Length(S) downto 1 do if Pos(S[i], Delimiters)>0 then begin Result:= i; Exit end; Result:= 0; end; function SExtractFileDir(const FileName: WideString): WideString; var I: Integer; begin I := LastDelimiter('\:', FileName); if (I > 1) and (FileName[I] = '\') and (not (char(FileName[I - 1]) in ['\', ':'])) then Dec(I); Result := Copy(FileName, 1, I); end; function SExtractFilePath(const FileName: WideString): WideString; var I: Integer; begin I := LastDelimiter('\:', FileName); Result := Copy(FileName, 1, I); end; function SExtractFileExt(const FileName: WideString): WideString; var I: Integer; begin I := LastDelimiter('.\:', FileName); if (I > 0) and (FileName[I] = '.') then Result := Copy(FileName, I, MaxInt) else Result := ''; end; function SLower(const S: string): string; begin Result:= S; if Result<>'' then begin UniqueString(Result); CharLowerBuff(@Result[1], Length(Result)); end; end; function SDelimiters: string; const Chars = ' !"#$%&''()*+,-./:;<=>?'+'@[\]^'+'`{|}~'; var i: integer; begin Result:= ''; for i:= 0 to 31 do Result:= Result+Chr(i); Result:= Result+Chars; end; function SFindString(const F, S: string; fWholeWords, fCaseSens: boolean): integer; var SBuf, FBuf: string; Delimiters: string; Match: boolean; i, j: integer; begin Result:= 0; Delimiters:= SDelimiters; SBuf:= S; FBuf:= F; if not fCaseSens then begin SBuf:= SLower(SBuf); FBuf:= SLower(FBuf); end; for i:= 1 to Length(S)-Length(F)+1 do begin //Match:= FBuf=Copy(SBuf, i, Length(FBuf)); //Slow Match:= true; for j:= 1 to Length(FBuf) do if FBuf[j]<>SBuf[i+j-1] then begin Match:= false; Break end; if fWholeWords then Match:= Match and ((i=1) or (Pos(S[i-1], Delimiters)>0)) and (i<Length(S)-Length(F)+1) and ({(i>=Length(S)-Length(F)+1) or} (Pos(S[i+Length(F)], Delimiters)>0)); if Match then begin Result:= i; Break end; end; end; function Min(n1, n2: integer): integer; begin if n1<n2 then Result:= n1 else Result:= n2; end; function Max(n1, n2: integer): integer; begin if n1>n2 then Result:= n1 else Result:= n2; end; end.
unit ZMCenDir19; (* ZMCenDir19.pas - handles external interface to directory entries TZipMaster19 VCL by Chris Vleghert and Eric W. Engler v1.9 Copyright (C) 2009 Russell Peters This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License (licence.txt) for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA contact: problems AT delphizip DOT org updates: http://www.delphizip.org modified 2010-06-20 ---------------------------------------------------------------------------*) interface uses Classes, ZipMstr19, ZMStructs19, ZMCompat19, ZMZipFile19, ZMIRec19, ZMCore19; type TZCentralValues = (zcvDirty, zcvEmpty, zcvError, zcvBadStruct, zcvBusy); TZCentralStatus = set of TZCentralValues; type TZMCenDir = class; // class to handle external directory access requests TZMCentralEntry = class(TZMDirEntry) private fCheck: Cardinal; fDir: TZMCenDir; fIdx: Cardinal; protected function Fetch(var rec: TZMIRec): Boolean; function GetCompressedSize: Int64; override; function GetCompressionMethod: Word; override; function GetCRC32: Cardinal; override; function GetDateTime: Cardinal; override; function GetEncoded: TZMEncodingOpts; override; function GetEncrypted: Boolean; override; function GetExtFileAttrib: Longword; override; function GetExtraData(Tag: Word): TZMRawBytes; override; function GetExtraField: TZMRawBytes; override; function GetExtraFieldLength: Word; override; function GetFileComment: TZMString; override; function GetFileCommentLen: Word; override; function GetFileName: TZMString; override; function GetFileNameLength: Word; override; function GetFlag: Word; override; function GetHeaderName: TZMRawBytes; override; function GetIntFileAttrib: Word; override; function GetRelOffLocalHdr: Int64; override; function GetStartOnDisk: Word; override; function GetStatusBits: Cardinal; override; function GetUncompressedSize: Int64; override; function GetVersionMadeBy: Word; override; function GetVersionNeeded: Word; override; property Check: Cardinal Read fCheck Write fCheck; property Idx: Cardinal Read fIdx Write fIdx; public constructor Create(Dir: TZMCenDir; idx: Integer; Check: Cardinal); end; TZMCenDir = class private fCount: Integer; fCurrent: TZMZipFile; fDirOnlyCount: Integer; fEntries: TList; fIgnoreDirOnly: Boolean; fLoadNo: Integer; fStatus: TZCentralStatus; fVerbose: Boolean; fWorker: TZMCore; procedure ClearEntries; //virtual; function GetCurrent: TZMZipFile; function GetEOCOffset: Int64; function GetMultiDisk: Boolean; function GetSFXOffset: Cardinal; function GetSOCOffset: Int64; function GetTotalDisks: Integer; function GetZipComment: Ansistring; function GetZipFileSize: Int64; procedure SetCurrent(const Value: TZMZipFile); procedure SetIgnoreDirOnly(Value: Boolean); procedure SetStatus(const Value: TZCentralStatus); procedure SetZipComment(const Value: Ansistring); protected function AddRecord(idx: Integer): Boolean; function GetDirEntry(Idx: Integer): TZMCentralEntry; procedure Invalidate; function Map: Integer; procedure SetCapacity(MaxEntries: Integer); property Worker: TZMCore Read fWorker; public constructor Create(Core: TZMCore); destructor Destroy; override; procedure Clear; // returns pointer to internal record function Entry(chk, idx: Cardinal): TZMIRec; function Find(const fspec: TZMString; var idx: Integer): TZMCentralEntry; function IndexOf(const FName: TZMString): Integer; function ReleaseZip: TZMZipFile; procedure ZipChange(Sender: TObject; idx: Integer; chng: TZCChanges); property Count: Integer Read fCount Write fCount; property Current: TZMZipFile Read GetCurrent Write SetCurrent; // DirEntry uses 'external' filtered index property DirEntry[Idx: Integer]: TZMCentralEntry read GetDirEntry; default; property DirOnlyCount: Integer Read fDirOnlyCount Write fDirOnlyCount; property EOCOffset: Int64 Read GetEOCOffset; property IgnoreDirOnly: Boolean Read fIgnoreDirOnly Write SetIgnoreDirOnly; property LoadNo: Integer Read fLoadNo Write fLoadNo; property MultiDisk: Boolean Read GetMultiDisk; property SFXOffset: Cardinal Read GetSFXOffset; property SOCOffset: Int64 Read GetSOCOffset; property Status: TZCentralStatus Read fStatus Write SetStatus; property TotalDisks: Integer Read GetTotalDisks; property Verbose: Boolean Read fVerbose Write fVerbose; property ZipComment: Ansistring Read GetZipComment Write SetZipComment; property ZipFileSize: Int64 Read GetZipFileSize; end; implementation uses SysUtils, ZMMatch19; { type TZCChanges = (zccNone, zccBegin, zccCount, zccAdd, zccEdit, zccDelete, zccEnd); TZCChangeEvent = procedure(Sender: TObject; idx: integer; change: TZCChanges) of object; } {TZMCenDir} constructor TZMCenDir.Create(Core: TZMCore); begin inherited Create; fWorker := Core; fEntries := TList.Create; fCount := 0; fLoadNo := 0; fDirOnlyCount := 0; end; destructor TZMCenDir.Destroy; begin ClearEntries; FreeAndNil(fEntries); FreeAndNil(fCurrent); inherited Destroy; end; function TZMCenDir.AddRecord(idx: Integer): Boolean; var rec: TZMIRec; x: TZMCentralEntry; begin Result := False; rec := fCurrent.Items[idx]; if IgnoreDirOnly and rec.TestStatusBit(zsbDirOnly) then Inc(fDirOnlyCount) else begin x := fEntries.Items[fCount]; x.Idx := idx; x.Check := fCurrent.CheckNo; Inc(fCount); Result := True; end; end; procedure TZMCenDir.Clear; begin ClearEntries; FreeAndNil(fCurrent); end; procedure TZMCenDir.ClearEntries; var i: Integer; tmp: TObject; begin fCount := 0; fDirOnlyCount := 0; for i := 0 to pred(fEntries.Count) do begin tmp := fEntries.Items[i]; if tmp <> nil then begin fEntries.Items[i] := nil; tmp.Free; end; end; fEntries.Clear; end; // return a pointer to an internal Entry function TZMCenDir.Entry(chk, idx: Cardinal): TZMIRec; begin if assigned(Current) then Result := fCurrent.Entry(chk, idx) else Result := nil; end; (*? TZMCentralDir.Find Find specified external filespec after idx (<0 - from beginning) returns pointer to Directory entry (nil - not found) sets idx to index of found entry (-1 not found) *) function TZMCenDir.Find(const fspec: TZMString; var idx: Integer): TZMCentralEntry; var c: Integer; begin if idx < 0 then idx := -1; c := pred(Count); while idx < c do begin Inc(idx); Result := DirEntry[idx]; if Worker.FNMatch(fspec, Result.FileName) then exit; end; idx := -1; Result := nil; end; function TZMCenDir.GetCurrent: TZMZipFile; begin if assigned(fCurrent) then begin if (fCurrent.info and zfi_Invalid) <> 0 then Current := TZMZipFile.Create(Worker); // force reload end else Current := TZMZipFile.Create(Worker); Result := fCurrent; end; function TZMCenDir.GetDirEntry(Idx: Integer): TZMCentralEntry; begin if (Idx >= 0) and (Idx < Count) then Result := TZMCentralEntry(fEntries.Items[Idx]) else Result := nil; end; function TZMCenDir.GetEOCOffset: Int64; begin if assigned(Current) then Result := fCurrent.EOCOffset else Result := 0; end; function TZMCenDir.GetMultiDisk: Boolean; begin if assigned(Current) then Result := fCurrent.MultiDisk else Result := False; end; function TZMCenDir.GetSFXOffset: Cardinal; begin if assigned(Current) then Result := fCurrent.SFXOfs else Result := 0; end; function TZMCenDir.GetSOCOffset: Int64; begin if assigned(Current) then Result := fCurrent.CentralOffset else Result := 0; end; function TZMCenDir.GetTotalDisks: Integer; begin Result := 0; if assigned(Current) then Result := Current.TotalDisks; end; function TZMCenDir.GetZipComment: Ansistring; begin if assigned(Current) then Result := fCurrent.ZipComment else Result := ''; end; function TZMCenDir.GetZipFileSize: Int64; begin Result := 0; if assigned(Current) then Result := Current.File_Size; end; (*? TZMCentralDir.IndexOf Find specified external filespec returns index of Directory entry (-1 - not found) Only checks unfiltered entries *) function TZMCenDir.IndexOf(const FName: TZMString): Integer; begin for Result := 0 to pred(Count) do if Worker.FNMatch(FName, DirEntry[Result].FileName) then exit; Result := -1; end; procedure TZMCenDir.Invalidate; var i: Integer; x: TZMCentralEntry; begin fLoadNo := Worker.NextCheckNo; for i := 0 to fEntries.Count - 1 do begin x := fEntries.Items[i]; x.Idx := i; x.Check := fLoadNo; end; fCount := 0; end; function TZMCenDir.Map: Integer; var i: Integer; x: TZMCentralEntry; zc: Integer; begin fDirOnlyCount := 0; if assigned(fCurrent) then zc := Current.Count else zc := 0; SetCapacity(zc); fCount := 0; if IgnoreDirOnly then begin for i := 0 to pred(zc) do AddRecord(i); end else begin for i := 0 to pred(zc) do begin x := fEntries.Items[i]; x.Idx := i; x.Check := fLoadNo; end; fCount := zc; end; Result := 0; end; function TZMCenDir.ReleaseZip: TZMZipFile; begin Result := fCurrent; fCurrent := nil; Worker.OnDirUpdate; end; procedure TZMCenDir.SetCapacity(MaxEntries: Integer); var i: Integer; begin if MaxEntries > fEntries.Count then begin fEntries.Capacity := MaxEntries; // populate the list for i := fEntries.Count to MaxEntries - 1 do fEntries.Add(TZMCentralEntry.Create(self, i, fLoadNo)); end; Invalidate; end; procedure TZMCenDir.SetCurrent(const Value: TZMZipFile); var cnt: Integer; i: Integer; begin if fCurrent <> Value then begin Invalidate; // don't free old - just mark useless FreeAndNil(fCurrent); fCurrent := Value; if assigned(Value) then begin fCurrent.OnChange := ZipChange; fLoadNo := fCurrent.CheckNo; cnt := fCurrent.Count; if cnt > 0 then begin // load entries SetCapacity(cnt); // will set remap fCount := 0; for i := 0 to cnt - 1 do if AddRecord(i) then Worker.OnNewName(pred(fCount)); end; end; Worker.OnDirUpdate; end; end; procedure TZMCenDir.SetIgnoreDirOnly(Value: Boolean); begin if Value <> IgnoreDirOnly then begin fIgnoreDirOnly := Value; Map; end; end; procedure TZMCenDir.SetStatus(const Value: TZCentralStatus); begin fStatus := Value; end; procedure TZMCenDir.SetZipComment(const Value: Ansistring); begin // end; procedure TZMCenDir.ZipChange(Sender: TObject; idx: Integer; chng: TZCChanges); begin case chng of // zccNone: ; zccBegin: ClearEntries; zccCount: SetCapacity(idx); zccAdd: if AddRecord(idx) then Worker.OnNewName(pred(fCount)); // zccEdit: ; // zccDelete: ; zccEnd: Worker.OnDirUpdate; zccCheckNo: // CheckNo changed because entries changed Invalidate; end; end; { TZMCentralEntry } constructor TZMCentralEntry.Create(Dir: TZMCenDir; idx: Integer; Check: Cardinal); begin inherited Create; fDir := Dir; fIdx := idx; fCheck := Check; end; // return pointer to internal data function TZMCentralEntry.Fetch(var rec: TZMIRec): Boolean; begin Result := False; if assigned(fDir) then begin rec := fDir.Entry(Check, Idx); Result := assigned(rec); end; end; function TZMCentralEntry.GetCompressedSize: Int64; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.CompressedSize; end; function TZMCentralEntry.GetCompressionMethod: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.ComprMethod; end; function TZMCentralEntry.GetCRC32: Cardinal; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.CRC32; end; function TZMCentralEntry.GetDateTime: Cardinal; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.ModifDateTime; end; function TZMCentralEntry.GetEncoded: TZMEncodingOpts; var r: TZMIRec; begin Result := zeoOEM; if Fetch(r) then Result := r.IsEncoded; end; function TZMCentralEntry.GetEncrypted: Boolean; var r: TZMIRec; begin Result := False; if Fetch(r) then Result := r.Encrypted; end; function TZMCentralEntry.GetExtFileAttrib: Longword; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.ExtFileAttrib; end; function TZMCentralEntry.GetExtraData(Tag: Word): TZMRawBytes; var r: TZMIRec; begin Result := ''; if Fetch(r) then Result := r.ExtraData[Tag]; end; function TZMCentralEntry.GetExtraField: TZMRawBytes; var r: TZMIRec; begin Result := ''; if Fetch(r) then Result := r.ExtraField; end; function TZMCentralEntry.GetExtraFieldLength: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.ExtraFieldLength; end; function TZMCentralEntry.GetFileComment: TZMString; var r: TZMIRec; begin Result := ''; if Fetch(r) then Result := r.FileComment; end; function TZMCentralEntry.GetFileCommentLen: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.FileCommentLen; end; function TZMCentralEntry.GetFileName: TZMString; var r: TZMIRec; begin Result := ''; if Fetch(r) then Result := r.FileName; end; function TZMCentralEntry.GetFileNameLength: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.FileNameLength; end; function TZMCentralEntry.GetFlag: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.Flag; end; function TZMCentralEntry.GetHeaderName: TZMRawBytes; var r: TZMIRec; begin Result := ''; if Fetch(r) then Result := r.HeaderName; end; function TZMCentralEntry.GetIntFileAttrib: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.IntFileAttrib; end; function TZMCentralEntry.GetRelOffLocalHdr: Int64; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.RelOffLocal; end; function TZMCentralEntry.GetStartOnDisk: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.DiskStart; end; function TZMCentralEntry.GetStatusBits: Cardinal; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.StatusBits; end; function TZMCentralEntry.GetUncompressedSize: Int64; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.UncompressedSize; end; function TZMCentralEntry.GetVersionMadeBy: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.VersionMadeBy; end; function TZMCentralEntry.GetVersionNeeded: Word; var r: TZMIRec; begin Result := 0; if Fetch(r) then Result := r.VersionNeeded; end; end.
unit Unit35; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type IInterfaceBase = interface ['{BE1B71E0-44C0-4D04-82B5-C9A00ACEF840}'] function GetText:string; procedure SetText( const AText:String ); property Text:string read GetText write SetText; end; TMinhaClasse = class(TInterfacedObject, IInterfaceBase) strict private FText:string; function GetText:string; procedure SetText( const AText:String ); property Text:string read GetText write SetText; end; TLetreiro = class(TInterfacedObject, IInterfaceBase) end; TForm35 = class(TForm,IInterfaceBase) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } FMinhaClasse : IInterfaceBase; F1:TMinhaClasse; function GetText:string; procedure SetText( const AText:String ); public { Public declarations } end; var Form35: TForm35; implementation {$R *.dfm} { TMinhaClasse } function TMinhaClasse.GetText: string; begin result := FText; end; procedure TMinhaClasse.SetText(const AText: String); begin FText := AText; end; { TForm35 } procedure TForm35.Button1Click(Sender: TObject); begin // exemplo 1 FMinhaClasse := TMinhaClasse.Create as IInterfaceBase; // ou // exemplo 2 FMinhaClasse := TLetreiro.Create as IInterfaceBase; FMinhaClasse.Text := 'a'; showMessage( FMinhaClasse.Text ); // nao requer // FMinhaClasse.free; FMinhaClasse.disposeOf; // F2.text := 'a'; F1:=TMinhaClasse.create; try finally F1.Free; end; end; function TForm35.GetText: string; begin end; procedure TForm35.SetText(const AText: String); begin end; end.
unit ChromeLikeFormCaptionData; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeFormCaptionData.pas" // Стереотип: "SimpleClass" // Элемент модели: "TChromeLikeFormCaptionData" MUID: (533D343C02FF) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses , l3ProtoObject , Types , Windows ; const cWindowCaptionButtonPadding = 2; type TChromeLikeFormCaptionButtonKind = ( cbkMinimize , cbkMaximizeRestore , cbkClose );//TChromeLikeFormCaptionButtonKind TChromeLikeFormCaptionData = class(Tl3ProtoObject) private f_CloseButtonRect: TRect; {* Прямоугольник кнопки "Закрыть" в координатах от правого верхнего угла окна } f_MaximizeButtonRect: TRect; {* Прямоугольник кнопки "Развернуть" / "Восстановить" в координатах от правого верхнего угла окна } f_MinimizeButtonRect: TRect; {* Прямоугольник кнопки "Свернуть" в координатах от правого верхнего угла окна } f_WasPopulatedThemed: Boolean; {* Признак того, что данные получены с учетом темы Windows } private function MakeRelativeRect(const aWndRect: TRect; const aButtonRect: TRect): TRect; procedure InitTitleBarInfo; protected procedure InitFields; override; public procedure UpdateTitleBarInfo(aHwnd: hWnd); function MakeButtonRect(aRight: Integer; aButtonKind: TChromeLikeFormCaptionButtonKind): TRect; end;//TChromeLikeFormCaptionData {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses , ChromeLikeWinUtils , l3Base , ChromeLikeTypes //#UC START# *533D343C02FFimpl_uses* //#UC END# *533D343C02FFimpl_uses* ; function TChromeLikeFormCaptionData.MakeRelativeRect(const aWndRect: TRect; const aButtonRect: TRect): TRect; //#UC START# *533D3553015B_533D343C02FF_var* //#UC END# *533D3553015B_533D343C02FF_var* begin //#UC START# *533D3553015B_533D343C02FF_impl* with Result do begin Right := aWndRect.Right - aButtonRect.Right; Top := aButtonRect.Top; Left := aWndRect.Right - aButtonRect.Left; Bottom := aButtonRect.Bottom; end; //#UC END# *533D3553015B_533D343C02FF_impl* end;//TChromeLikeFormCaptionData.MakeRelativeRect procedure TChromeLikeFormCaptionData.InitTitleBarInfo; //#UC START# *533D358C033A_533D343C02FF_var* const cBugFixButtonSizeDecrease = 3; // - величина уменьшения размера кнопок var l_ButtonWidth: Integer; l_ButtonHeight: Integer; function lp_MakeButtonRect(aRight: Integer; aTop: Integer): TRect; begin with Result do begin Right := aRight + cWindowCaptionButtonPadding; Top := aTop + cWindowCaptionButtonPadding; Bottom := Top + l_ButtonHeight - cBugFixButtonSizeDecrease; Left := Right + l_ButtonWidth - cBugFixButtonSizeDecrease; end;//with Result end;//lp_MakeButtonRect var l_BorderHeight: Integer; l_BorderWidth: Integer; //#UC END# *533D358C033A_533D343C02FF_var* begin //#UC START# *533D358C033A_533D343C02FF_impl* // Заполним размеры умолчательными из GetSystemMetrics. Они вряд ли соответствуют // текущей теме, но так хотя бы покажутся кнопки l_ButtonWidth := GetSystemMetrics(SM_CXSIZE); l_ButtonHeight := GetSystemMetrics(SM_CYSIZE); l_BorderWidth := GetSystemMetrics(SM_CXSIZEFRAME); l_BorderHeight := GetSystemMetrics(SM_CYSIZEFRAME); // Очередная бага: на XP после WM_THEMECHANGED, пока пользователь не сменит тему // оформления еще раз приходят неправильные SM_CXSIZE (cx = 18; cy = 25 вместо // (cx = 25; cy = 25), поэтому приравняем ширину к высоте if (IsWindowsXP and (l_ButtonWidth <> l_ButtonHeight)) then l_ButtonWidth := l_ButtonHeight; // Прямоугольники кнопок считаем относительно правого верхнего угла окна f_CloseButtonRect := lp_MakeButtonRect(l_BorderWidth, l_BorderHeight); f_MaximizeButtonRect := lp_MakeButtonRect(f_CloseButtonRect.Left, l_BorderHeight); f_MinimizeButtonRect := lp_MakeButtonRect(f_MaximizeButtonRect.Left, l_BorderHeight); // Если ОС - ниже Висты, оставляем эти значения и не будем их пересчитывать. // Если Vista и новее - пересчитаем позже f_WasPopulatedThemed := not IsWindowsVistaOrLater; //#UC END# *533D358C033A_533D343C02FF_impl* end;//TChromeLikeFormCaptionData.InitTitleBarInfo procedure TChromeLikeFormCaptionData.UpdateTitleBarInfo(aHwnd: hWnd); //#UC START# *533D35BB0292_533D343C02FF_var* var l_Info: TTitleBarInfoEx; l_WndRect: TRect; l_VistaMetrics: TVistaWindowCaptionMetrics; //#UC END# *533D35BB0292_533D343C02FF_var* begin //#UC START# *533D35BB0292_533D343C02FF_impl* // Все это нужно потому, что по-другому невозможно на W7 узнать размеры кнопок. // GetSystemMetrics возвращает левые значения, а посылать себе WM_GETTITLEBARINFOEX // нет смысла - настоящие кнопки отключены и W7 отдает мусорные цифры. if f_WasPopulatedThemed then Exit; l_VistaMetrics := GetVistaWindowCaptionMetrics(aHwnd); l_Info := l_VistaMetrics.rTitleBarInfo; l_WndRect := l_VistaMetrics.rWindowRect; with l_Info do begin // Здесь делаем прямоугольники кнопок, посчитаные относительно // правого верхнего угла окна. f_CloseButtonRect := MakeRelativeRect(l_WndRect, rgrect[5]); f_MaximizeButtonRect := MakeRelativeRect(l_WndRect, rgrect[3]); f_MinimizeButtonRect := MakeRelativeRect(l_WndRect, rgrect[2]); end; f_WasPopulatedThemed := True; //#UC END# *533D35BB0292_533D343C02FF_impl* end;//TChromeLikeFormCaptionData.UpdateTitleBarInfo function TChromeLikeFormCaptionData.MakeButtonRect(aRight: Integer; aButtonKind: TChromeLikeFormCaptionButtonKind): TRect; //#UC START# *533D3681003B_533D343C02FF_var* var l_RelativeRect: TRect; //#UC END# *533D3681003B_533D343C02FF_var* begin //#UC START# *533D3681003B_533D343C02FF_impl* l3FillChar(Result, SizeOf(Result), 0); case aButtonKind of cbkMinimize: l_RelativeRect := f_MinimizeButtonRect; cbkMaximizeRestore: l_RelativeRect := f_MaximizeButtonRect; cbkClose: l_RelativeRect := f_CloseButtonRect; end; // Из сохраненного "относительного" прямоугольника с учетом координаты // правого края окна делаем "настоящие" прямоугольники кнопки with Result do begin Right := aRight - l_RelativeRect.Right; Top := l_RelativeRect.Top; Bottom := l_RelativeRect.Bottom; Left := aRight - l_RelativeRect.Left; end;//with Result //#UC END# *533D3681003B_533D343C02FF_impl* end;//TChromeLikeFormCaptionData.MakeButtonRect procedure TChromeLikeFormCaptionData.InitFields; //#UC START# *47A042E100E2_533D343C02FF_var* //#UC END# *47A042E100E2_533D343C02FF_var* begin //#UC START# *47A042E100E2_533D343C02FF_impl* l3FillChar(f_CloseButtonRect, SizeOf(f_CloseButtonRect), 0); l3FillChar(f_MaximizeButtonRect, SizeOf(f_MaximizeButtonRect), 0); l3FillChar(f_MinimizeButtonRect, SizeOf(f_MinimizeButtonRect), 0); f_WasPopulatedThemed := False; InitTitleBarInfo; //#UC END# *47A042E100E2_533D343C02FF_impl* end;//TChromeLikeFormCaptionData.InitFields {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
unit sMessages; {$I sDefs.inc} interface uses Windows, Controls {$IFDEF FPC}, LMessages{$ENDIF}; type TacSectionInfo = record siName: string; siSkinIndex: integer; siRepaintNeeded: boolean; end; PacSectionInfo = ^TacSectionInfo; const SM_ALPHACMD = $A100; AC_SETNEWSKIN = 1; AC_REMOVESKIN = 2; AC_REFRESH = 3; // if WParamLo = 1 then message will not be broadcasted to children AC_GETPROVIDER = 4; AC_GETCACHE = 5; AC_ENDPARENTUPDATE = 6; AC_CTRLHANDLED = 7; AC_UPDATING = 8; AC_GETDEFINDEX = 9; // Get skin index if SkinSection is empty (incremented to 1) AC_PREPARING = 10; AC_GETHALFVISIBLE = 11; AC_GETLISTSW = 12; AC_UPDATESECTION = 13; AC_DROPPEDDOWN = 14; AC_SETSECTION = 15; AC_STOPFADING = 16; AC_SETBGCHANGED = 17; AC_INVALIDATE = 18; AC_CHILDCHANGED = 19; // If WParamLo = 1 then Kill effects at child AC_SETCHANGEDIFNECESSARY = 20; // Defines BgChanged to True if required, with repainting if WParamLo = 1 AC_GETCONTROLCOLOR = 21; // Returns control BG color AC_SETHALFVISIBLE = 22; AC_PREPARECACHE = 23; AC_DRAWANIMAGE = 24; AC_CONTROLLOADED = 25; AC_GETSKININDEX = 26; AC_GETSERVICEINT = 27; AC_UPDATECHILDREN = 28; AC_MOUSEENTER = 29; AC_MOUSELEAVE = 30; AC_BEGINUPDATE = 31; AC_ENDUPDATE = 32; AC_CLEARCACHE = 33; AC_GETBG = 34; AC_GETDISKIND = 35; // Init a look of disabled control AC_FONTSCHANGED = 36; // Updates default font in application (default font is Application.MainForm.Font.Name) AC_GETSKINDATA = 37; AC_PRINTING = 38; AC_UPDATELIGHT = 39; // Update light animation in the control, if WPARAMLO = 1 then immediate output AC_PAINTOUTER = 40; // Paint a Shadow or other effect, LParam is PBGInfo, if WParamLo is 1 - use cached BG if exists AC_FLUENTHANDLE = 41; // Register/unregister fluent control AC_SETGLASSMODE = 42; // Enable/disable support of GlassPaint in the control (LParamHi: TranspMode, if LParamLo = 1 then broadcast to child), // Message.Result := MakeLResult(Message.LParamLo, TranspMode); AC_BUFFEREDPRINTCLIENT = 43; AC_FORCEOPAQUE = 44; // Full repaint of ctrl if ForceOpaque (or if parent is ForceOpaque (if WParamLo = 1)) AC_BEFORESCROLL = 51; AC_AFTERSCROLL = 52; AC_REINITSCROLLS = 53; AC_GETCOLORTONE = 54; AC_LINKOBJ = 55; AC_GETAPPLICATION = 60; AC_PARENTCLOFFSET = 61; AC_NCPAINT = 62; AC_SETPOSCHANGING = 63; AC_GETPOSCHANGING = 64; AC_SETALPHA = 65; AC_GETFONTINDEX = 66; AC_GETBORDERWIDTH = 67; AC_SETSCALE = 68; AC_GETSCALE = 69; AC_GETOUTRGN = 70; AC_COPYDATA = 71; AC_POPUPCLOSED = 72; AC_UPDATESHADOW = 73; AC_SKINCHANGED = 74; AC_SKINLISTCHANGED = 75; AC_PAINTFLOATITEMS = 76; AC_UPDATEFLOATITEMS = 77; AC_UPDATEITEMSALPHA = 78; AC_UPDATEPAGEBTN = AC_UPDATEITEMSALPHA; AC_GETTOPWND = 79; AC_SETFLOATZORDER = 80; AC_UPDATEFLOATBITMAPS = 81; AC_KILLTIMERS = 82; AC_SETNCSKINNED = 83; // LPARAM = 0 or 1 AC_REFLECTLAYOUT = 84; AC_ISOPAQUE = 85; AC_GETCOMMONSKINDATA = 86; AC_ANIMSCALE = 87; // WParamLo: new PPI AC_GETDEFSECTION = 88; // Get index of default SkinSection in the sStyleSimply.acDefSections array AC_GETMOUSEAREA = 89; // Returns rect on screen active for animation (PRect returned in LPARAM) AC_GETTEXTRECT = 90; AC_DOSKIPCLICK = 91; AC_STATUSBAR = 92; // WParamLo: 1 - ctrl is alive, 0 - destroying, LParam - TStatusBar ctrl AC_ANIMPAINT = 93; // Sent after each anim iteration AC_GETBG_HI = WPARAM(AC_GETBG shl 16); AC_REFRESH_HI = WPARAM(AC_REFRESH shl 16); AC_UPDATING_HI = WPARAM(AC_UPDATING shl 16); AC_SETNEWSKIN_HI = WPARAM(AC_SETNEWSKIN shl 16); AC_GETSERVICEINT_HI = WPARAM(AC_GETSERVICEINT shl 16); AC_REMOVESKIN_HI = WPARAM(AC_REMOVESKIN shl 16); AC_PREPARECACHE_HI = WPARAM(AC_PREPARECACHE shl 16); AC_BEGINUPDATE_HI = WPARAM(AC_BEGINUPDATE shl 16); AC_ENDUPDATE_HI = WPARAM(AC_ENDUPDATE shl 16); AC_PAINTOUTER_HI = WPARAM(AC_PAINTOUTER shl 16); AC_SETBGCHANGED_HI = WPARAM(AC_SETBGCHANGED shl 16); AC_GETCONTROLCOLOR_HI = WPARAM(AC_GETCONTROLCOLOR shl 16); AC_GETDEFINDEX_HI = WPARAM(AC_GETDEFINDEX shl 16); AC_CLEARCACHE_HI = WPARAM(AC_CLEARCACHE shl 16); AC_SETSCALE_HI = WPARAM(AC_SETSCALE shl 16); AC_GETSKINDATA_HI = WPARAM(AC_GETSKINDATA shl 16); AC_MOUSELEAVE_HI = WPARAM(AC_MOUSELEAVE shl 16); AC_GETPROVIDER_HI = WPARAM(AC_GETPROVIDER shl 16); AC_ENDPARENTUPDATE_HI = WPARAM(AC_ENDPARENTUPDATE shl 16); AC_CTRLHANDLED_HI = WPARAM(AC_CTRLHANDLED shl 16); AC_GETFONTINDEX_HI = WPARAM(AC_GETFONTINDEX shl 16); AC_STOPFADING_HI = WPARAM(AC_STOPFADING shl 16); WM_DRAWMENUBORDER = CN_NOTIFY + 101; WM_DRAWMENUBORDER2 = CN_NOTIFY + 102; {$IFNDEF D2010} {$EXTERNALSYM WM_DWMSENDICONICTHUMBNAIL} WM_DWMSENDICONICTHUMBNAIL = $0323; {$EXTERNALSYM WM_DWMSENDICONICLIVEPREVIEWBITMAP} WM_DWMSENDICONICLIVEPREVIEWBITMAP = $0326; {$ENDIF} implementation end.
unit uCadastroEmpresa; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils; type TEmpresa = class private ConexaoDB:TZConnection; F_clienteId:Integer; //Int F_nome:String; //VarChar F_endereco: string; F_cidade:String; F_bairro: String; F_estado: string; F_cep: String; F_telefone1: string; F_email: string; F_telefone2: string; F_CNPJ: string; F_IM: string; F_IE: string; F_RazaoSocial: string; F_Fantasia: string; F_CodEmpresa: Integer; F_Numero :Integer; F_Contato :string; public constructor Create(aConexao:TZConnection); destructor Destroy; override; function Inserir:Boolean; function Atualizar:Boolean; function Apagar:Boolean; function Selecionar(id:Integer):Boolean; published property CodEmpresa :Integer read F_CodEmpresa write F_CodEmpresa; property CNPJ :string read F_CNPJ write F_CNPJ; property RazaoSocial :string read F_RazaoSocial write F_RazaoSocial; property Fantasia :string read F_Fantasia write F_Fantasia; property endereco :string read F_endereco write F_endereco; property cidade :string read F_cidade write F_cidade; property bairro :string read F_bairro write F_bairro; property estado :string read F_estado write F_Estado; property cep :string read F_cep write F_Cep; property telefone1 :string read F_telefone1 write F_telefone1; property telefone2 :string read F_telefone2 write F_telefone2; property email :string read F_email write F_email; property IE :string read F_IE write F_IE; property IM :string read F_IM write F_IM; property Numero :Integer read F_Numero write F_Numero; property Contato :string read F_COntato write F_Contato; end; implementation { TCategoria } {$region 'Constructor and Destructor'} constructor TEmpresa.Create(aConexao:TZConnection); begin ConexaoDB:=aConexao; end; destructor TEmpresa.Destroy; begin inherited; end; {$endRegion} {$region 'CRUD'} function TEmpresa.Apagar: Boolean; var Qry:TZQuery; begin if MessageDlg('Apagar o Registro: '+#13+#13+ 'Código: '+IntToStr(F_CodEmpresa)+#13+ 'Descrição: '+F_nome,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin Result:=false; abort; end; try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM Empresa '+ ' WHERE Emp_cod=:Emp_Cod '); Qry.ParamByName('Emp_Cod').AsInteger :=CodEmpresa; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TEmpresa.Atualizar: Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE EMPRESA '+ ' SET EMP_RAZAOSOCIAL =:RAZAO '+ ' ,EMP_FANTASIA =:FANTASIA '+ ' ,EMP_ENDERECO =:endereco '+ ' ,EMP_Cidade =:cidade '+ ' ,EMP_Bairro =:bairro '+ ' ,EMP_UF =:estado '+ ' ,EMP_Cep =:cep '+ ' ,EMP_Telefone1 =:telefone1 '+ ' ,EMP_Telefone2 =:telefone2 '+ ' ,EMP_Email =:email '+ ' ,EMP_IE =:IE '+ ' ,EMP_IM =:IM '+ ' ,Emp_Numero =:Numero '+ ' ,Emp_Contato =:Contato '+ ' ,EMP_CNPJ =:CNPJ '+ ' WHERE EMP_Cod=:EMP_Cod '); Qry.ParamByName('EMP_COD').AsInteger :=Self.F_CodEmpresa; Qry.ParamByName('RAZAO').AsString :=Self.F_RazaoSocial; Qry.ParamByName('FANTASIA').AsString :=Self.Fantasia; Qry.ParamByName('endereco').AsString :=Self.F_endereco; Qry.ParamByName('cidade').AsString :=Self.F_cidade; Qry.ParamByName('bairro').AsString :=Self.F_bairro; Qry.ParamByName('estado').AsString :=Self.F_estado; Qry.ParamByName('cep').AsString :=Self.F_cep; Qry.ParamByName('telefone1').AsString :=Self.F_telefone1; Qry.ParamByName('telefone2').AsString :=Self.F_telefone2; Qry.ParamByName('email').AsString :=Self.F_email; Qry.ParamByName('IE').AsString :=Self.F_IE; Qry.ParamByName('IM').AsString :=Self.F_IM; Qry.ParamByName('numero').AsInteger :=Self.F_Numero; Qry.ParamByName('Contato').AsString :=Self.Contato; Qry.ParamByName('CNPJ').AsString :=Self.CNPJ; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TEmpresa.Inserir: Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO EMPRESA ( '+ ' EMP_RAZAOSOCIAL '+ ' ,EMP_FANTASIA '+ ' ,EMP_ENDERECO '+ ' ,EMP_Cidade '+ ' ,EMP_Bairro '+ ' ,EMP_UF '+ ' ,EMP_Cep '+ ' ,EMP_Telefone1 '+ ' ,EMP_Telefone2 '+ ' ,EMP_Email '+ ' ,EMP_IE '+ ' ,EMP_NUMERO '+ ' ,EMP_IM '+ ' ,EMP_CONTATO '+ ' ,EMP_CNPJ) '+ 'values( '+ ' :RAZAO, '+ ' :FANTASIA, '+ ' :endereco, '+ ' :cidade, '+ ' :bairro, '+ ' :estado, '+ ' :cep, '+ ' :telefone1, '+ ' :telefone2, '+ ' :email, '+ ' :IE, '+ ' :numero, '+ ' :IM, '+ ' :CONTATO,' + ' :CNPJ)'); Qry.ParamByName('Razao').AsString :=Self.F_RazaoSocial; Qry.ParamByName('Fantasia').AsString :=Self.F_Fantasia; Qry.ParamByName('endereco').AsString :=Self.F_endereco; Qry.ParamByName('cidade').AsString :=Self.F_cidade; Qry.ParamByName('bairro').AsString :=Self.F_bairro; Qry.ParamByName('estado').AsString :=Self.F_estado; Qry.ParamByName('cep').AsString :=Self.F_cep; Qry.ParamByName('telefone1').AsString :=Self.F_telefone1; Qry.ParamByName('Telefone2').AsString := Self.F_telefone2; Qry.ParamByName('email').AsString :=Self.F_email; Qry.ParamByName('IE').AsString :=Self.F_IE; Qry.ParamByName('Numero').AsInteger :=Self.F_Numero; Qry.ParamByName('IM').AsString :=Self.F_IM; Qry.ParamByName('Contato').AsString :=Self.Contato; Qry.ParamByName('CNPJ').AsString :=Self.CNPJ; Try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; Except ConexaoDB.Rollback; Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; function TEmpresa.Selecionar(id: Integer): Boolean; var Qry:TZQuery; begin try Result:=true; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT EMP_Cod,'+ ' EMP_RAZAOSOCIAL, '+ ' EMP_FANTASIA, '+ ' EMP_endereco, '+ ' EMP_Cidade, '+ ' EMP_Bairro, '+ ' EMP_UF, '+ ' EMP_Cep, '+ ' EMP_Telefone1, '+ ' EMP_Telefone2, '+ ' EMP_Email, '+ ' EMP_IE, '+ ' EMP_IM, '+ ' EMP_Numero,'+ ' EMP_Contato,'+ ' EMP_CNPJ'+ ' FROM EMPRESA '+ ' WHERE EMP_Cod=:EMP_Cod'); Qry.ParamByName('EMP_Cod').AsInteger:=id; Try Qry.Open; Self.F_CodEmpresa := Qry.FieldByName('EMP_Cod').AsInteger; Self.F_RazaoSocial := Qry.FieldByName('EMP_RAZAOSOCIAL').AsString; Self.F_Fantasia := Qry.FieldByName('EMP_FANTASIA').AsString; Self.F_endereco := Qry.FieldByName('EMP_ENDERECO').AsString; Self.F_cidade := Qry.FieldByName('EMP_Cidade').AsString; Self.F_bairro := Qry.FieldByName('EMP_Bairro').AsString; Self.F_estado := Qry.FieldByName('EMP_UF').AsString; Self.F_cep := Qry.FieldByName('EMP_Cep').AsString; Self.F_telefone1 := Qry.FieldByName('EMP_Telefone1').AsString; Self.F_telefone2 := Qry.FieldByName('EMP_Telefone2').AsString; Self.F_email := Qry.FieldByName('EMP_Email').AsString; Self.F_IE := Qry.FieldByName('EMP_IE').AsString; Self.F_IM := Qry.FieldByName('EMP_IM').AsString; Self.F_Numero := Qry.FieldByName('EMP_Numero').AsInteger; Self.Contato := Qry.FieldByName('EMP_Contato').AsString; Self.CNPJ := Qry.FieldByName('EMP_CNPJ').AsString; Except Result:=false; End; finally if Assigned(Qry) then FreeAndNil(Qry); end; end; {$endregion} end.
program ex; uses Room; Type TVRoom=object(TRoom) height:real; {поле для хранения высоты} function V:real; {метод определения объема} procedure NewInit(l,w,h:real); {инициализирующий метод} end; Procedure TVRoom.NewInit; begin Init(l,w); {инициализируем наследуемые поля класса} height:=h; {инициализируем собственное поле класса} end; Function TVRoom.V; begin V:=Square*height; {обращаемся к методу базового класса} end; var A:TVRoom; begin A.NewInit(3,4,5.1,2.8); writeln('Plotshad komnati = ',A.Square:6:2); writeln('Obyom komnati = ',A.V:6:2); readln; end.
unit TTSELTAG3Table; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSELTAG3Record = record PSeparateby: String[10]; PGroupBy: String[10]; PTrackCode: String[8]; PDescription: String[30]; PD91: Integer; PD90: Integer; PD60: Integer; PD30: Integer; End; TTTSELTAG3Buffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSELTAG3Record; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSELTAG3 = (TTSELTAG3PrimaryKey, TTSELTAG3ByCategory); TTTSELTAG3Table = class( TDBISAMTableAU ) private FDFSeparateby: TStringField; FDFGroupBy: TStringField; FDFTrackCode: TStringField; FDFDescription: TStringField; FDFD91: TIntegerField; FDFD90: TIntegerField; FDFD60: TIntegerField; FDFD30: TIntegerField; procedure SetPSeparateby(const Value: String); function GetPSeparateby:String; procedure SetPGroupBy(const Value: String); function GetPGroupBy:String; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPD91(const Value: Integer); function GetPD91:Integer; procedure SetPD90(const Value: Integer); function GetPD90:Integer; procedure SetPD60(const Value: Integer); function GetPD60:Integer; procedure SetPD30(const Value: Integer); function GetPD30:Integer; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSELTAG3); function GetEnumIndex: TEITTSELTAG3; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSELTAG3Record; procedure StoreDataBuffer(ABuffer:TTTSELTAG3Record); property DFSeparateby: TStringField read FDFSeparateby; property DFGroupBy: TStringField read FDFGroupBy; property DFTrackCode: TStringField read FDFTrackCode; property DFDescription: TStringField read FDFDescription; property DFD91: TIntegerField read FDFD91; property DFD90: TIntegerField read FDFD90; property DFD60: TIntegerField read FDFD60; property DFD30: TIntegerField read FDFD30; property PSeparateby: String read GetPSeparateby write SetPSeparateby; property PGroupBy: String read GetPGroupBy write SetPGroupBy; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PDescription: String read GetPDescription write SetPDescription; property PD91: Integer read GetPD91 write SetPD91; property PD90: Integer read GetPD90 write SetPD90; property PD60: Integer read GetPD60 write SetPD60; property PD30: Integer read GetPD30 write SetPD30; published property Active write SetActive; property EnumIndex: TEITTSELTAG3 read GetEnumIndex write SetEnumIndex; end; { TTTSELTAG3Table } procedure Register; implementation function TTTSELTAG3Table.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSELTAG3Table.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSELTAG3Table.GenerateNewFieldName } function TTTSELTAG3Table.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSELTAG3Table.CreateField } procedure TTTSELTAG3Table.CreateFields; begin FDFSeparateby := CreateField( 'Separateby' ) as TStringField; FDFGroupBy := CreateField( 'GroupBy' ) as TStringField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFD91 := CreateField( 'D91' ) as TIntegerField; FDFD90 := CreateField( 'D90' ) as TIntegerField; FDFD60 := CreateField( 'D60' ) as TIntegerField; FDFD30 := CreateField( 'D30' ) as TIntegerField; end; { TTTSELTAG3Table.CreateFields } procedure TTTSELTAG3Table.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSELTAG3Table.SetActive } procedure TTTSELTAG3Table.SetPSeparateby(const Value: String); begin DFSeparateby.Value := Value; end; function TTTSELTAG3Table.GetPSeparateby:String; begin result := DFSeparateby.Value; end; procedure TTTSELTAG3Table.SetPGroupBy(const Value: String); begin DFGroupBy.Value := Value; end; function TTTSELTAG3Table.GetPGroupBy:String; begin result := DFGroupBy.Value; end; procedure TTTSELTAG3Table.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSELTAG3Table.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSELTAG3Table.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSELTAG3Table.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSELTAG3Table.SetPD91(const Value: Integer); begin DFD91.Value := Value; end; function TTTSELTAG3Table.GetPD91:Integer; begin result := DFD91.Value; end; procedure TTTSELTAG3Table.SetPD90(const Value: Integer); begin DFD90.Value := Value; end; function TTTSELTAG3Table.GetPD90:Integer; begin result := DFD90.Value; end; procedure TTTSELTAG3Table.SetPD60(const Value: Integer); begin DFD60.Value := Value; end; function TTTSELTAG3Table.GetPD60:Integer; begin result := DFD60.Value; end; procedure TTTSELTAG3Table.SetPD30(const Value: Integer); begin DFD30.Value := Value; end; function TTTSELTAG3Table.GetPD30:Integer; begin result := DFD30.Value; end; procedure TTTSELTAG3Table.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Separateby, String, 10, N'); Add('GroupBy, String, 10, N'); Add('TrackCode, String, 8, N'); Add('Description, String, 30, N'); Add('D91, Integer, 0, N'); Add('D90, Integer, 0, N'); Add('D60, Integer, 0, N'); Add('D30, Integer, 0, N'); end; end; procedure TTTSELTAG3Table.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Separateby;GroupBy;TrackCode, Y, Y, N, N'); Add('ByCategory, TrackCode, N, N, N, N'); end; end; procedure TTTSELTAG3Table.SetEnumIndex(Value: TEITTSELTAG3); begin case Value of TTSELTAG3PrimaryKey : IndexName := ''; TTSELTAG3ByCategory : IndexName := 'ByCategory'; end; end; function TTTSELTAG3Table.GetDataBuffer:TTTSELTAG3Record; var buf: TTTSELTAG3Record; begin fillchar(buf, sizeof(buf), 0); buf.PSeparateby := DFSeparateby.Value; buf.PGroupBy := DFGroupBy.Value; buf.PTrackCode := DFTrackCode.Value; buf.PDescription := DFDescription.Value; buf.PD91 := DFD91.Value; buf.PD90 := DFD90.Value; buf.PD60 := DFD60.Value; buf.PD30 := DFD30.Value; result := buf; end; procedure TTTSELTAG3Table.StoreDataBuffer(ABuffer:TTTSELTAG3Record); begin DFSeparateby.Value := ABuffer.PSeparateby; DFGroupBy.Value := ABuffer.PGroupBy; DFTrackCode.Value := ABuffer.PTrackCode; DFDescription.Value := ABuffer.PDescription; DFD91.Value := ABuffer.PD91; DFD90.Value := ABuffer.PD90; DFD60.Value := ABuffer.PD60; DFD30.Value := ABuffer.PD30; end; function TTTSELTAG3Table.GetEnumIndex: TEITTSELTAG3; var iname : string; begin result := TTSELTAG3PrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSELTAG3PrimaryKey; if iname = 'BYCATEGORY' then result := TTSELTAG3ByCategory; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSELTAG3Table, TTTSELTAG3Buffer ] ); end; { Register } function TTTSELTAG3Buffer.FieldNameToIndex(s:string):integer; const flist:array[1..8] of string = ('SEPARATEBY','GROUPBY','TRACKCODE','DESCRIPTION','D91','D90' ,'D60','D30' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 8) and (flist[x] <> s) do inc(x); if x <= 8 then result := x else result := 0; end; function TTTSELTAG3Buffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftInteger; 6 : result := ftInteger; 7 : result := ftInteger; 8 : result := ftInteger; end; end; function TTTSELTAG3Buffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PSeparateby; 2 : result := @Data.PGroupBy; 3 : result := @Data.PTrackCode; 4 : result := @Data.PDescription; 5 : result := @Data.PD91; 6 : result := @Data.PD90; 7 : result := @Data.PD60; 8 : result := @Data.PD30; end; end; end.
unit enet_list; (** @file list.c @brief ENet linked list functions freepascal 1.3.6 *) (** @defgroup list ENet linked list utility functions @ingroup private @{ *) interface uses enet_consts; function enet_list_begin(list:pointer):pENetListNode; function enet_list_end(list:pointer):pENetListNode; function enet_list_empty(list:pointer):boolean; function enet_list_next(iterator:pENetListNode):pENetListNode; function enet_list_previous(iterator:pENetListNode):pENetListNode; function enet_list_front(list:pointer):pENetListNode; function enet_list_back(list:pointer):pENetListNode; procedure enet_list_clear (list : pointer); function enet_list_insert (position : ENetListIterator; data : pointer):ENetListIterator; function enet_list_remove (position : ENetListIterator):pENetListNode; function enet_list_move (position : ENetListIterator; dataFirst, dataLast : Pointer):ENetListIterator; function enet_list_size (list : pENetList):enet_size_t; implementation function enet_list_begin(list:pointer):pENetListNode; begin result := pENetlist(list)^.sentinel.next; end; function enet_list_end(list:pointer):pENetListNode; begin result := @(pEnetList(list)^.sentinel); end; function enet_list_empty(list:pointer):boolean; begin result := enet_list_begin (list) = enet_list_end (list); end; function enet_list_next(iterator:pENetListNode):pENetListNode; begin result := iterator ^. next; end; function enet_list_previous(iterator:pENetListNode):pENetListNode; begin result := iterator ^. previous; end; function enet_list_front(list:pointer):pENetListNode; begin result := pENetList(list)^.sentinel.next; end; function enet_list_back(list:pointer):pENetListNode; begin result := pENetList (list) ^. sentinel.previous; end; procedure enet_list_clear (list : pointer); begin pENetList(list)^.sentinel.next := @(pENetList(list)^. sentinel); pEnetList(list)^.sentinel.previous := @(pENetList(list)^. sentinel); end; function enet_list_insert (position : ENetListIterator; data : pointer):ENetListIterator; begin result := ENetListIterator(data); result ^. previous := position ^. previous; result ^. next := pENetListNode(position); result ^. previous ^. next := pENetListNode(result); position ^. previous := pENetListNode(result); end; function enet_list_remove (position : ENetListIterator):pENetListNode; begin position ^. previous ^. next := position ^. next; position ^. next ^. previous := position ^. previous; result := pENetListNode(position); end; function enet_list_move (position : ENetListIterator; dataFirst, dataLast : Pointer):ENetListIterator; var first, last : ENetListIterator; begin first := ENetListIterator(dataFirst); last := ENetListIterator(dataLast); first^. previous^. next := last^. next; last^. next^. previous := first^. previous; first^. previous := position^. previous; last^. next := position; first^. previous^. next := first; position^. previous := last; result := first; end; function enet_list_size (list : pENetList):enet_size_t; var position : pENetListNode; // ENetListIterator begin result :=0; position := enet_list_begin(list); while position <> enet_list_end(list) do begin inc(result); position := enet_list_next(position); end; end; (** @} *) end.
unit ATxPanel; interface uses Classes, Controls, StdCtrls, ExtCtrls; type TATTextPanel = class(TPanel) private lab: TLabel; procedure SetClick(Value: TNotifyEvent); function GetLab: string; procedure SetLab(Value: string); public constructor Create(Owner: TComponent); override; property OnLabClick: TNotifyEvent write SetClick; property LabCaption: string read GetLab write SetLab; protected procedure Paint; override; end; implementation uses Graphics; procedure TATTextPanel.Paint; begin Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); end; constructor TATTextPanel.Create; begin inherited; lab := TLabel.Create(Self); with lab do begin Parent := Self; Align := alTop; Alignment := taCenter; LabCaption := 'Format not known'; end; end; procedure TATTextPanel.SetClick; begin lab.OnClick := Value; end; procedure TATTextPanel.SetLab(Value: string); begin lab.Caption := Value; Height := lab.Height + 4; end; function TATTextPanel.GetLab: string; begin Result:= lab.Caption; end; end.
unit SctFloat; { ---------------------------------------------------------------- Ace Reporter Copyright 1995-2004 SCT Associates, Inc. Written by Kevin Maher, Steve Tyrakowski ---------------------------------------------------------------- } interface {$I ace.inc} uses classes, sctdata, sctcalc; type { TSctFloat } TSctFloat = class(TSctData) private FCalc: TSctCalc; FTotalType: TSctTotalType; protected function GetValueFloat: Double; virtual; procedure SetValueFloat(Value: Double); virtual; function GetAsString: String; override; function GetAsInteger: LongInt; override; function GetAsFloat: Double; override; function GetAsBoolean: Boolean; override; procedure SetAsString(Value: String); override; procedure SetAsInteger(Value: LongInt); override; procedure SetAsFloat(Value: Double); override; procedure SetAsBoolean(Value: Boolean); override; public constructor Create; override; destructor Destroy; override; procedure Reset; override; procedure SetValue( var Value); override; procedure SetData( data: TSctData ); override; property ValueFloat: Double read GetValueFloat write SetValueFloat; property Calc: TSctCalc read FCalc write FCalc; property TotalType: TSctTotalType read FTotalType write FTotalType; end; implementation uses sysutils; { TSctFloat } constructor TSctFloat.Create; begin inherited Create; DataType := dtypeFloat; TotalType := ttValue; FCalc := TSctCalc.Create; end; destructor TSctFloat.destroy; begin FCalc.Free; inherited destroy; end; procedure TSctFloat.Reset; begin if Calc <> nil Then Calc.reset; FIsNull := False; end; procedure TSctFloat.SetValue( var Value ); begin Calc.Value := Double(Value); end; procedure TSctFloat.SetData( data: TSctData ); begin Calc.Value := TSctFloat(data).Calc.Value; Calc.Sum := TSctFloat(data).Calc.Sum; Calc.Count := TSctFloat(data).Calc.Count; Calc.Min := TSctFloat(data).Calc.Min; Calc.Max := TSctFloat(data).Calc.Max; FIsNull := data.IsNull; end; function TSctFloat.getValuefloat: Double; begin case TotalType of ttSum: Result := Calc.Sum; ttCount: Result := Calc.Count; ttMax: Result := Calc.Max; ttMin: Result := Calc.Min; ttAverage: Result := Calc.Average; ttValue: Result := Calc.Value else Result := 0; end; end; procedure TSctFloat.SetValueFloat(Value: Double); begin Calc.Value := Value; end; function TSctFloat.GetAsString: String; begin result := FloatToStr(ValueFloat); end; function TSctFloat.GetAsInteger: LongInt; begin result := Trunc(ValueFloat); end; function TSctFloat.GetAsFloat: Double; begin result := ValueFloat; end; function TSctFloat.GetAsBoolean: Boolean; begin result := ValueFloat <> 0; end; procedure TSctFloat.SetAsString(Value: String); begin ValueFloat := StrToFloat(Value); end; procedure TSctFloat.SetAsInteger(Value: LongInt); begin ValueFloat := Value; end; procedure TSctFloat.SetAsFloat(Value: Double); begin ValueFloat := Value; end; procedure TSctFloat.SetAsBoolean(Value: Boolean); begin if Value then ValueFloat := 1.0 else ValueFloat := 0; end; end.
unit LisIVA; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Mask, DateUtils, Dialogs, Db, DBTables, JvToolEdit, JvSpin, JvExMask, DBClient, EnPngGr; type TListado = function( FIni, FFin: TDateTime; nPag: integer ):boolean; StdCall; TLisIVADlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; Label2: TLabel; Label3: TLabel; FecIni: TJvDateEdit; FecFin: TJvDateEdit; rxNum: TJvSpinEdit; Cds: TClientDataSet; CdsTASA: TFloatField; CdsExpr1000: TCurrencyField; btnInfo: TButton; Image1: TImage; btnRes: TButton; bGrilla: TButton; btnRet: TButton; grabarDlg: TSaveDialog; btnPer: TButton; procedure FormCreate(Sender: TObject); procedure OKBtnClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure btnInfoClick(Sender: TObject); procedure btnResClick(Sender: TObject); procedure bGrillaClick(Sender: TObject); procedure btnRetClick(Sender: TObject); procedure btnPerClick(Sender: TObject); private { Private declarations } FArchivo: TextFile; public { Public declarations } end; var LisIVADlg: TLisIVADlg; implementation uses main, FuncsRb, Informes, DM, consiva; {$R *.DFM} procedure TLisIVADlg.FormCreate(Sender: TObject); begin DMod.TDatos.Open; FecFin.date := StartOfTheMonth( date)-1; FecIni.date := StartofTheMonth( FecFin.date ); end; procedure TLisIVADlg.OKBtnClick(Sender: TObject); begin Screen.Cursor := crHourGlass; with DMod do try TDatos.Open; QConsIVA.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QConsIVA.Parameters.ParamByName( 'FECF' ).value := FecFin.date; QConsIVA.open; QResIVANue.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QResIVANue.Parameters.ParamByName( 'FECF' ).value := FecFin.date; QResIVANue.open; SetNumeroRb( Round( rxNum.value )); VerInforme( 'IVACompras.rtm', QConsIVA, QResIVANue ); finally QConsIVA.Close; QResIVANue.Close; TDatos.Close; end; Screen.Cursor := crDefault; end; procedure TLisIVADlg.btnInfoClick(Sender: TObject); begin Screen.Cursor := crHourGlass; with DMod do try TDatos.Open; QConsIVA.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QConsIVA.Parameters.ParamByName( 'FECF' ).value := FecFin.date; QConsIVA.open; QResIVANue.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QResIVANue.Parameters.ParamByName( 'FECF' ).value := FecFin.date; QResIVANue.open; QDetImpIVA.open; SetNumeroRb( Round( rxNum.value )); VerInforme( 'InfoIVACompras.rtm', QConsIVA, QResIVANue ,QDetImpIVA ); finally QConsIVA.Close; QDetImpIVA.Close; QResIVANue.close; TDatos.Close; end; Screen.Cursor := crDefault; end; procedure TLisIVADlg.btnPerClick(Sender: TObject); var FCadena: string; begin grabarDlg.FileName := 'Percepciones_IVA_' + FormatDateTime( 'mm-yyyy', fecfin.Date ) + '.txt'; if ( grabarDlg.Execute ) then try screen.Cursor := crHourGlass; AssignFile( FArchivo, grabarDlg.FileName ); Rewrite( FArchivo ); dmod.get_Percepcion.Parameters.ParamByName('fecini').Value := fecini.Date; dmod.get_Percepcion.Parameters.ParamByName('fecfin').Value := fecfin.Date; dmod.get_Percepcion.Open; while not (dmod.get_Percepcion.eof ) do begin FCadena := format( '%3d%13s%10s%8s%8s%16f', [ dmod.get_Percepcioncodigo.value, dmod.get_Percepcioncuit.value, dmod.get_Percepcionfecha.DisplayText, dmod.get_Percepcionfactura1.value, dmod.get_Percepcionfactura2.value, dmod.get_Percepcionmonto.value ]); Writeln(FArchivo, FCadena ); dmod.get_Percepcion.Next; end; ShowMessage('exportacion realizada con exito' ); finally CloseFile( FArchivo ); dmod.get_Percepcion.Close; Screen.Cursor := crDefault; end; end; procedure TLisIVADlg.btnResClick(Sender: TObject); begin with DMod do begin // QResCompras.Parameters.ParamByName( 'FECI' ).value := FecIni.date; // QResCompras.Parameters.ParamByName( 'FECF' ).value := FecFin.date; // setCadenaRb( 'del ' + DateToStr(FecIni.date) + ' al ' + DateToStr( FecFin.Date )); QDetCompras.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QDetCompras.Parameters.ParamByName( 'FECF' ).value := FecFin.date; setCadenaRb( 'del ' + DateToStr(FecIni.date) + ' al ' + DateToStr( FecFin.Date )); VerInforme( 'ResCompras.rtm', QDetCompras ); end; end; procedure TLisIVADlg.btnRetClick(Sender: TObject); var FCadena: string; begin grabarDlg.FileName := 'Retenciones_IVA_' + FormatDateTime( 'mm-yyyy', fecfin.Date ) + '.txt'; if ( grabarDlg.Execute ) then try screen.Cursor := crHourGlass; AssignFile( FArchivo, grabarDlg.FileName ); Rewrite( FArchivo ); dmod.get_Retencion.Parameters.ParamByName('fecini').Value := fecini.Date; dmod.get_Retencion.Parameters.ParamByName('fecfin').Value := fecfin.Date; dmod.get_Retencion.Open; while not (dmod.get_Retencion.eof ) do begin FCadena := format( '%3d%13s%10s%16s%16f', [ dmod.get_Retencioncodigo.value, dmod.get_Retencioncuit.value, dmod.get_Retencionfecha.DisplayText, dmod.get_Retencioncertificado.value, dmod.get_Retencionmonto.value ]); Writeln(FArchivo, FCadena ); dmod.get_Retencion.Next; end; ShowMessage('exportacion realizada con exito' ); finally CloseFile( FArchivo ); Screen.Cursor := crDefault; end; end; procedure TLisIVADlg.FormActivate(Sender: TObject); begin Screen.Cursor := crDefault; end; procedure TLisIVADlg.bGrillaClick(Sender: TObject); begin Screen.Cursor := crHourGlass; with DMod do try QConsIVA.Parameters.ParamByName( 'FECI' ).value := FecIni.date; QConsIVA.Parameters.ParamByName( 'FECF' ).value := FecFin.date; FConsIVA := TFConsIVA.create( self ); FConsIVA.FIni := FecIni.date; FConsIVA.FFin := FecFin.Date; FConsIVA.showmodal; finally FConsIVA.Free; Screen.Cursor := crDefault; end; end; end.
unit WorkJournalInterfaces; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/WorkJournalInterfaces.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Interfaces::Category>> F1 Core::Base Operations::View::WorkJournalInterfaces // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses DocumentUnit, SearchUnit, l3TreeInterfaces, UserJournalUnit, PrimWorkJournalInterfaces ; type IbsWorkJournal = interface(IUnknown) ['{2E30D6B8-6A4D-42B6-8441-14BF7C617DBC}'] function MakeTree: Il3SimpleTree; procedure Clear; procedure AddQuery(const aQuery: IQuery); procedure AddBookMark(const aBookMark: IJournalBookmark); function MakeQueryHistory(aQueryType: TQueryType; aMaxCount: Cardinal): IQueryList; function MakeBookMarkHistory(ForInpharm: Boolean; aMaxCount: Cardinal): IJournalBookmarkList; procedure Delete(const aNode: Il3SimpleNode); procedure RegisterListener(const aListener: InsWorkJournalListener); procedure UnRegisterListener(const aListener: InsWorkJournalListener); procedure NotifyJournalShrinked; end;//IbsWorkJournal {$IfEnd} //not Admin AND not Monitorings implementation end.
unit GX_EditorFormServices; {$I GX_CondDefine.inc} {$WARN SYMBOL_PLATFORM OFF} interface uses Forms, Controls; type { Interface to a component that GExperts places on each and every single editor form the IDE creates. This "proxy" provides access services to the various controls present on the form. Among these controls are, for instance, the editor control itself, tab controls, and docking panels. Do not hold an interface for any prolonged period of time, as the user may close editor forms any time, thus invalidating the proxy. } IGxEditFormProxy = interface(IUnknown) ['{5A31EA50-D292-11D3-A948-22D821000000}'] function GetEditorForm: TCustomForm; function GetEditControl: TWinControl; function GetIsSourceEditor: Boolean; // Return the actual IDE's editor form. property EditorForm: TCustomForm read GetEditorForm; // Return the editor control. property EditControl: TWinControl read GetEditControl; // Return if the edit proxy is for a source editor or another type, such as the welcome page property IsSourceEditor: Boolean read GetIsSourceEditor; end; type TEditFormEventCode = (efAfterCreate, efBeforeActivate); TEditFormNotifier = procedure(EventCode: TEditFormEventCode; EditFormProxy: IGxEditFormProxy) of object; { Allow listeners to attach to interesting events that may happen with the editor form. Currently handled are * efAfterCreate The editor form has just been created and the GExperts edit form proxy has just been installed. * efBeforeActivate The editor form is being activated. Additionally, access to all editor form proxies, representing all editor forms in the IDE is provided. } IGxEditorFormServices = interface(IUnknown) ['{38F24310-D1D9-11D3-A944-DA3A65000000}'] procedure AddListener(Listener: TEditFormNotifier); procedure RemoveListener(Listener: TEditFormNotifier); function GetCurrentProxy: IGxEditFormProxy; function GetEditorFormProxyCount: Integer; function GetEditorFormProxy(Index: Integer): IGxEditFormProxy; // Proxy on form that is currently active or was last active // if the current IDE form is not an editor form. // Returns nil if no editor form is open. property CurrentProxy: IGxEditFormProxy read GetCurrentProxy; // Retrieve number of proxies installed (one per form, strictly) // and allow to retrieve the proxy itself. property EditorFormProxyCount: Integer read GetEditorFormProxyCount; property EditorFormProxies[Index: Integer]: IGxEditFormProxy read GetEditorFormProxy; end; function GxEditorFormServices: IGxEditorFormServices; implementation uses {$IFOPT D+} GX_DbugIntf, TypInfo, {$ENDIF} Windows, SysUtils, Classes, Contnrs, GX_GenericUtils, GX_IdeUtils, GX_GenericClasses; type TListenerRecord = record ListenerMethod: TEditFormNotifier; end; PListenerRecord = ^TListenerRecord; type TGxEditorFormHostComponent = class(TComponent, IGxEditFormProxy) private FRefCount: Integer; FEditControl: TWinControl; protected // Overriden IUnknown implementations to implement life-time // management in a non-TInterfacedObject descendant. function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; protected // IGxEditFormProxy function GetEditorForm: TCustomForm; function GetEditControl: TWinControl; function GetIsSourceEditor: Boolean; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; type // Implementation of IGxEditorFormServices. // We need to descend from TComponent as this implementation // registers itself via Notification with editor forms to // learn of proxies being destroyed. TGxEditorFormServices = class(TComponent, IGxEditorFormServices) private FCurrentProxyHost: Integer; FHostComponents: TObjectList; FListeners: TList; procedure ClearListeners; procedure ClearHostComponents; procedure BeforeSetFocusEditorForm(const WindowHandle: THandle); procedure FireEvent(const EventCode: TEditFormEventCode; const EditFormProxy: TGxEditorFormHostComponent); procedure InitializeExistingForms; procedure InvalidateCurrentProxyHost; procedure UpdateCurrentProxyHost(const EditFormProxy: TGxEditorFormHostComponent); procedure FindAndAssignCurrentProxyHost; function IsInvalidCurrentProxyHost: Boolean; function InjectEditorFormHostComponent(const EditForm: TCustomForm): TGxEditorFormHostComponent; protected // Overriden IUnknown implementations for // singleton life-time management function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; protected // IGxEditorFormServices procedure AddListener(Listener: TEditFormNotifier); procedure RemoveListener(Listener: TEditFormNotifier); function GetCurrentProxy: IGxEditFormProxy; function GetEditorFormProxyCount: Integer; function GetEditorFormProxy(Index: Integer): IGxEditFormProxy; protected // Keeps track of editor form proxies as they are // removed by virtue of their containing editor // form being destroyed. procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; const InvalidCurrentProxyHost = -1; var PrivateGxEditorFormServices: TGxEditorFormServices; function GxEditorFormServices: IGxEditorFormServices; begin if not Assigned(PrivateGxEditorFormServices) then PrivateGxEditorFormServices := TGxEditorFormServices.Create(nil); Result := PrivateGxEditorFormServices; end; procedure FreeEditorFormServices; begin FreeAndNil(PrivateGxEditorFormServices); end; { TGxEditorFormHostComponent } constructor TGxEditorFormHostComponent.Create(AOwner: TComponent); begin Assert(AOwner is TCustomForm); Assert(AOwner.ClassNameIs(EditorFormClassName)); inherited Create(AOwner); // Since FindComponent searches by name, our marker component // needs a name. For simplicity, we simply take the ClassName. // Note that this will cause exceptions to be thrown if two // components with the same name are owned by the same owner; // incidentally, this is just what we want for improved // runtime program correctness verification. Name := ClassName; // Cache control information from the form: FEditControl := AOwner.FindComponent('Editor') as TWinControl; if Assigned(FEditControl) then Assert(FEditControl.ClassNameIs(EditorControlClassName)); end; destructor TGxEditorFormHostComponent.Destroy; begin // We don't want anyone to retain references // when we are going away. {$IFOPT D+} SendDebug('Inside TGxEditorFormHostComponent.Destroy'); {$ENDIF} Assert(FRefCount = 0); FRefCount := -1; // Trigger for assert upon double free, for instance. inherited Destroy; end; var CBTHook: HHOOK; function CBTHookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var ClassName: string; begin if nCode < 0 then begin Result := CallNextHookEx(CBTHook, nCode, wParam, lParam); Exit; end; try case nCode of HCBT_SETFOCUS: // A control with a window handle was focused if wParam > 0 then // wParam is 0 if an Exception happens in HCBT_Setfocus begin ClassName := GetWindowClassName(wParam); {$IFOPT D+} SendDebug('SetFocus hook found: ' + ClassName); {$ENDIF} if SameText(ClassName, EditorControlClassName) then begin {$IFOPT D+} SendDebug('SetFocus hook found an editor control'); {$ENDIF} Assert(Assigned(PrivateGxEditorFormServices)); PrivateGxEditorFormServices.BeforeSetFocusEditorForm(wParam); end; end; (* This may be useful later to replace the Screen.OnActiveFormChanged hook HCBT_ACTIVATE: // A top-level window was focused if wParam > 0 then // wParam is 0 if an Exception happens in HCBT_ACTIVATE? begin ApiResult := GetClassName(wParam, ClassNameBuffer, SizeOf(ClassNameBuffer)); Win32Check(ApiResult <> 0); Assert(ApiResult < ClassNameBufferSize, 'Found class name larger than fixed buffer size'); {$IFOPT D+} SendDebug('Window hook found: ' + StrPas(ClassNameBuffer)); {$ENDIF} ComparisonResult := StrLIComp(ClassNameBuffer, 'TDefaultEnvironmentDialog', ClassNameBufferSize); if ComparisonResult = 0 then begin {$IFOPT D+} SendDebug('SetFocus hook found a form to resize'); {$ENDIF} Assert(Assigned(PrivateGxEditorFormServices)); //PrivateGxEditorFormServices.BeforeSetFocusEditorForm(wParam); end; end; *) else //FI:W506 // Nothing. end; except on E: Exception do begin {$IFOPT D+} SendDebugError('CBTHookProc Exception: '+ E.Message); {$ENDIF D+} GxLogException(E); // Swallow exception. end; end; Result := CallNextHookEx(CBTHook, nCode, wParam, lParam); end; function TGxEditorFormHostComponent.GetEditControl: TWinControl; begin Result := FEditControl; end; function TGxEditorFormHostComponent.GetEditorForm: TCustomForm; begin Result := Owner as TCustomForm; Assert(Assigned(Result)); Assert(Result.ClassNameIs(EditorFormClassName)); end; function TGxEditorFormHostComponent.GetIsSourceEditor: Boolean; begin Result := Assigned(FEditControl); end; procedure TGxEditorFormHostComponent.Notification(AComponent: TComponent; Operation: TOperation); begin //{$IFOPT D+} if Assigned(AComponent) then SendDebugFmt('TGxEditorFormHostComponent.Notification: %s for "%s" of class %s',[GetEnumName(TypeInfo(TOperation), Integer(Operation)), AComponent.Name, AComponent.ClassName]); {$ENDIF} Assert((Operation = opRemove) or (Operation = opInsert)); if Operation = opRemove then if AComponent = FEditControl then FEditControl := nil; inherited Notification(AComponent, Operation); end; function TGxEditorFormHostComponent._AddRef: Integer; begin Result := InterlockedIncrement(FRefCount); end; function TGxEditorFormHostComponent._Release: Integer; begin Result := InterlockedDecrement(FRefCount); end; { TGxEditorFormServices } procedure TGxEditorFormServices.AddListener(Listener: TEditFormNotifier); var AListenerRecord: PListenerRecord; begin Assert(Assigned(FListeners)); Assert(Assigned(Listener)); New(AListenerRecord); FListeners.Add(AListenerRecord); AListenerRecord^.ListenerMethod := Listener; end; procedure TGxEditorFormServices.BeforeSetFocusEditorForm(const WindowHandle: THandle); var i: Integer; AForm: TCustomForm; HostComponent: TComponent; NewHostComponentCreated: Boolean; AComp: TComponent; begin // Find the EditWindow that owns the Editor Control pointed to by WindowHandle AForm := nil; i := Screen.FormCount -1; while i >= 0 do begin AForm := Screen.Forms[i]; Assert(Assigned(AForm)); if IsIdeEditorForm(AForm) then begin {$IFOPT D+}SendDebug('Editor form found - '+ AForm.Name);{$ENDIF} AComp := AForm.FindComponent('Editor'); if Assigned(AComp) and (AComp is TWinControl) then begin if TWinControl(AComp).Handle = WindowHandle then Break; end; end; Dec(i); end; Assert(i >= 0); Assert(Assigned(AForm)); if csDesigning in AForm.ComponentState then Exit; HostComponent := AForm.FindComponent(TGxEditorFormHostComponent.ClassName); if not Assigned(HostComponent) then begin //if not ComponentOwnsClass(AForm, EditorControlName) then // Exit; HostComponent := InjectEditorFormHostComponent(AForm); NewHostComponentCreated := True; end else NewHostComponentCreated := False; UpdateCurrentProxyHost(HostComponent as TGxEditorFormHostComponent); if NewHostComponentCreated then FireEvent(efAfterCreate, HostComponent as TGxEditorFormHostComponent); FireEvent(efBeforeActivate, HostComponent as TGxEditorFormHostComponent); end; procedure TGxEditorFormServices.ClearHostComponents; var HostComponent: TComponent; HostOwner: TComponent; begin if Assigned(FHostComponents) then begin {$IFOPT D+} if FHostComponents.Count > 0 then begin MessageBox(0, PChar(Format('EditorFormServices has %d dangling host components', [FHostComponents.Count])), 'Warning', MB_OK or MB_ICONHAND); end; {$ENDIF D+} // We now remove our installed host components from // the form - this is particularly necessary if // GExperts is used in a package and unloaded // dynamically. while FHostComponents.Count > 0 do begin HostComponent := FHostComponents[0] as TComponent; // Remove the host component from the owner's component // list; this will trigger TGxEditorFormServices.Notification // with opRemove which in turn will remove HostComponent from // FHostComponents list. Assert(Assigned(HostComponent)); HostOwner := HostComponent.Owner; Assert(Assigned(HostOwner)); HostOwner.RemoveComponent(HostComponent); // Now that no one refers to the component any longer, // destroy it. HostComponent.Destroy; end; InvalidateCurrentProxyHost; Assert(FHostComponents.Count = 0); end; end; procedure TGxEditorFormServices.ClearListeners; var i: Integer; AListenerRecord: PListenerRecord; begin if Assigned(FListeners) then begin {$IFOPT D+} if FListeners.Count > 0 then begin MessageBox(0, PChar(Format('EditorFormServices has %d dangling listeners', [FListeners.Count])), 'Warning', MB_OK or MB_ICONHAND); end; {$ENDIF D+} for i := 0 to FListeners.Count-1 do begin AListenerRecord := FListeners[i]; Dispose(AListenerRecord); end; FListeners.Clear; end; end; constructor TGxEditorFormServices.Create(AOwner: TComponent); const OwnsObjects = True; begin Assert(AOwner = nil); inherited Create(AOwner); FListeners := TList.Create; FHostComponents := TObjectList.Create(not OwnsObjects); InvalidateCurrentProxyHost; CBTHook := SetWindowsHookEx(WH_CBT, CBTHookProc, 0, GetCurrentThreadID); Win32Check(CBTHook <> 0); InitializeExistingForms; end; destructor TGxEditorFormServices.Destroy; begin if CBTHook <> 0 then begin Win32Check(UnhookWindowsHookEx(CBTHook)); CBTHook := 0; end; ClearHostComponents; FreeAndNil(FHostComponents); ClearListeners; FreeAndNil(FListeners); inherited Destroy; end; function CustomFormIsInFrontOf(const QueriedForm, BaseForm: TCustomForm): Boolean; var i: Integer; ScreenCustomForm: TCustomForm; begin if not Assigned(QueriedForm) then begin Result := False; Exit; end; if not Assigned(BaseForm) {and Assigned(QueriedForm)} then begin Result := True; Exit; end; Result := False; for i := 0 to Screen.CustomFormCount do begin ScreenCustomForm := Screen.CustomForms[i]; Result := (ScreenCustomForm = QueriedForm); if Result then Break; if ScreenCustomForm = BaseForm then Break; end; end; procedure TGxEditorFormServices.FindAndAssignCurrentProxyHost; var i: Integer; TopMostHostComponent: TGxEditorFormHostComponent; AHostComponent: TGxEditorFormHostComponent; begin Assert(Assigned(FHostComponents)); // We do have a number of host components installed. // Iterate over these and find the one which is associated // with the top-most editor form. This is then the // current proxy host. // Optimization: No proxy, nothing current. Do nothing. if FHostComponents.Count = 0 then Exit; FCurrentProxyHost := 0; // First item/proxy (index) // Optimization: If we only have one proxy, we know // that this is the one and only current (first) one. if FHostComponents.Count = 1 then Exit; TopMostHostComponent := FHostComponents[FCurrentProxyHost] as TGxEditorFormHostComponent; for i := 1 to FHostComponents.Count-1 do begin AHostComponent := FHostComponents[i] as TGxEditorFormHostComponent; if CustomFormIsInFrontOf(AHostComponent.GetEditorForm, TopMostHostComponent.GetEditorForm) then begin FCurrentProxyHost := i; TopMostHostComponent := AHostComponent; end; end; end; procedure TGxEditorFormServices.FireEvent(const EventCode: TEditFormEventCode; const EditFormProxy: TGxEditorFormHostComponent); var i: Integer; AListenerRecord: PListenerRecord; begin {$IFOPT D+} SendDebug(Format('Firing form event %s', [GetEnumName(TypeInfo(TEditFormEventCode), Integer(EventCode))])); {$ENDIF} Assert(Assigned(FListeners)); Assert(Assigned(EditFormProxy)); for i := 0 to FListeners.Count-1 do begin AListenerRecord := FListeners[i]; Assert(Assigned(AListenerRecord)); try {$IFOPT D+} SendDebug(Format('Firing to editor form listener %d', [i])); {$ENDIF} AListenerRecord^.ListenerMethod(EventCode, EditFormProxy); except on E: Exception do begin GxLogException(E); // Swallow exception. end; end; end; end; function TGxEditorFormServices.GetCurrentProxy: IGxEditFormProxy; begin Assert(Assigned(FHostComponents)); // No editor forms have been created (yet - or all // available ones have been destroyed). if FHostComponents.Count = 0 then begin Result := nil; Exit; end; if IsInvalidCurrentProxyHost then begin // We do not have a valid current proxy host // (and hence editor form) yet. This may be // due to editor form removal or it may happen // if we just installed ourselves into the // existing editor forms after a request // for editor services. // (Note that editor form services are only // created upon first usage, not up-front on // installation.) FindAndAssignCurrentProxyHost; // If after an attempt to find the current proxy / editor // form we still don't have one, give up and return nothing. // This really should not happen. if IsInvalidCurrentProxyHost then begin Result := nil; Assert(False, 'No current editor form proxy was found although one was requested'); Exit; end; end; Assert(FCurrentProxyHost >= 0); Assert(FCurrentProxyHost < FHostComponents.Count); Result := FHostComponents[FCurrentProxyHost] as TGxEditorFormHostComponent; end; function TGxEditorFormServices.GetEditorFormProxy(Index: Integer): IGxEditFormProxy; begin Assert(Assigned(FHostComponents)); Result := FHostComponents[Index] as TGxEditorFormHostComponent; end; function TGxEditorFormServices.GetEditorFormProxyCount: Integer; begin Assert(Assigned(FHostComponents)); Result := FHostComponents.Count; end; procedure TGxEditorFormServices.InitializeExistingForms; var i: Integer; AForm: TCustomForm; begin {$IFOPT D+} SendDebug('Begin injecting host components into existing forms'); {$ENDIF} for i := 0 to Screen.FormCount-1 do begin AForm := Screen.Forms[i]; if IsIdeEditorForm(AForm) then InjectEditorFormHostComponent(AForm); end; end; function TGxEditorFormServices.InjectEditorFormHostComponent( const EditForm: TCustomForm): TGxEditorFormHostComponent; var AHostComponent: TGxEditorFormHostComponent; begin Assert(Assigned(EditForm)); AHostComponent := TGxEditorFormHostComponent.Create(EditForm); FHostComponents.Add(AHostComponent); AHostComponent.FreeNotification(Self); {$IFOPT D+} SendDebug('Injected host component into ' + EditForm.Name); {$ENDIF} Result := AHostComponent; end; procedure TGxEditorFormServices.InvalidateCurrentProxyHost; begin FCurrentProxyHost := InvalidCurrentProxyHost; end; function TGxEditorFormServices.IsInvalidCurrentProxyHost: Boolean; begin Result := (FCurrentProxyHost = InvalidCurrentProxyHost); end; procedure TGxEditorFormServices.Notification(AComponent: TComponent; Operation: TOperation); var Index: Integer; begin if Operation = opRemove then begin Assert(Assigned(FHostComponents)); Index := FHostComponents.IndexOf(AComponent); if Index >= 0 then begin FHostComponents.Delete(Index); InvalidateCurrentProxyHost; end; end; inherited Notification(AComponent, Operation); end; procedure TGxEditorFormServices.RemoveListener(Listener: TEditFormNotifier); var i: Integer; AListenerRecord: PListenerRecord; begin Assert(Assigned(FListeners)); Assert(Assigned(Listener)); for i := 0 to FListeners.Count-1 do begin AListenerRecord := FListeners[i]; if @AListenerRecord^.ListenerMethod = @Listener then begin Dispose(AListenerRecord); FListeners.Delete(i); Break; end; end; end; procedure TGxEditorFormServices.UpdateCurrentProxyHost( const EditFormProxy: TGxEditorFormHostComponent); begin Assert(Assigned(EditFormProxy)); FCurrentProxyHost := FHostComponents.IndexOf(EditFormProxy); Assert(FCurrentProxyHost >= 0); end; function TGxEditorFormServices._AddRef: Integer; begin Result := 1; end; function TGxEditorFormServices._Release: Integer; begin Result := 1; end; initialization finalization FreeEditorFormServices; end.
{$IFDEF LAPE} (*=============================================================================| Object oriented wrapper for Simba Bitmaps |=============================================================================*) {!DOCTOPIC}{ TRafBitmap module } {!DOCREF} { @method: type TRafBitmap = record ... end; @desc: Object oriented wrapper for Simba Bitmaps, with some extra stuff.. Definition: [code=pascal] TRafBitmap = record Bitmap: Integer; Width, Height: Integer; Loaded:Boolean; end; [/code] } type TRafBitmap = record Bitmap: Integer; Width, Height: Integer; Loaded:Boolean; end; (*=============================================================================| Regular intilaization |=============================================================================*) {!DOCREF} { @method: procedure TRafBitmap.Create(W,H: Integer); @desc: Creates a bitmap of the given size. } procedure TRafBitmap.Create(W,H: Integer); begin if Self.Loaded then Self.Free(); Self.Bitmap := CreateBitmap(W,H); Self.Loaded := True; Self.Width := W; Self.Height := H; end; {!DOCREF} { @method: procedure TRafBitmap.Create(W,H: Integer; Str:String); overload; @desc: Creates a bitmap from a string. } procedure TRafBitmap.Create(W, H: Integer; Str:String); overload; begin if Self.Loaded then Self.Free(); Self.Bitmap := BitmapFromString(W,H,Str); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); Self.Loaded := True; end; {!DOCREF} { @method: procedure TRafBitmap.Create(SimbaBitmap:Integer); overload; @desc: Create a TRafBitmap-instance from a Simba-bitmap. } procedure TRafBitmap.Create(SimbaBitmap:Integer); overload; begin if Self.Loaded then Self.Free(); Self.Bitmap := SimbaBitmap; GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); Self.Loaded := True; end; {!DOCREF} { @method: procedure TRafBitmap.Open(ImgPath:String); @desc: Open a image file from anywhere on your computer } procedure TRafBitmap.Open(ImgPath:String); begin if Self.Loaded then Self.Free(); try Self.Bitmap := LoadBitmap(ImgPath); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); Self.Loaded := True; except if not(FileExists(ImgPath)) then RaiseWarning('File "'+ImgPath+'" does not exist.', ERR_WARNING) else RaiseWarning('Unexpected error in "TRafBitmap.Open()".', ERR_WARNING); end; end; {!DOCREF} { @method: procedure TRafBitmap.FromClient(); @desc: Loads the whole client bitmap in to this image. If this image is already in use it will be freed first. } procedure TRafBitmap.FromClient(); var W,H:Integer; begin if Self.Loaded then Self.Free(); GetClientDimensions(W,H); Self.Bitmap := BitmapFromClient(0,0,W-1,H-1); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); Self.Loaded := True; end; {!DOCREF} { @method: procedure TRafBitmap.FromClient(X1,Y1,X2,Y2:Int32); overload; @desc: Loads the client bitmap in to this image. If this image is already in use it will be freed first. Allows you to target a box of the client. } procedure TRafBitmap.FromClient(X1,Y1,X2,Y2:Int32); overload; var W,H:Integer; begin if Self.Loaded then Self.Free(); GetClientDimensions(W,H); if (X2 >= W) or (X2 <= -1) then X2 := W-1; if (Y2 >= H) or (Y2 <= -1) then Y2 := H-1; if (X1 > X2) or (Y1 > Y2) then Exit; Self.Bitmap := BitmapFromClient(X1,Y1,X2,Y2); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); Self.Loaded := True; end; (*=============================================================================| Saving bitmap |=============================================================================*) {!DOCREF} { @method: function TRafBitmap.Save(ImgPath:String): TRafBitmap; @desc: ... } function TRafBitmap.Save(ImgPath:String): TRafBitmap; begin if not(Self.IsLoaded('TRafBitmap.Save()')) then Exit; SaveBitmap(Self.Bitmap, ImgPath); end; (*=============================================================================| General functinality |=============================================================================*) {!DOCREF} { @method: procedure TRafBitmap.SetSize(NewWidth,NewHeight:Int32); @desc: Will increse, or decrease the size of the image, it the size is increased, the image will be extended with a black background. } procedure TRafBitmap.SetSize(NewWidth,NewHeight:Int32); begin if not(Self.IsLoaded('TRafBitmap.SetSize()')) then Exit; SetBitmapSize(Self.Bitmap, NewWidth, NewHeight); Self.Width := NewWidth; Self.Height := NewHeight; end; {!DOCREF} { @method: procedure TRafBitmap.Clear(Color:Int32); @desc: Clears the image and paints over with the given color. } procedure TRafBitmap.Clear(Color:Int32); begin if not(Self.IsLoaded('TRafBitmap.Clear()')) then Exit; FastDrawClear(Self.Bitmap, Color); end; {!DOCREF} { @method: function TRafBitmap.Clone(): TRafBitmap; @desc: Returns a copy of the image } function TRafBitmap.Clone(): TRafBitmap; begin if not(Self.IsLoaded('TRafBitmap.Clone()')) then Exit; Result.Bitmap := CopyBitmap(Self.Bitmap); Result.Width := Self.Width; Result.Height := Self.Height; Result.Loaded := True; end; {!DOCREF} { @method: function TRafBitmap.Crop(X1,Y1,X2,Y2:Int32): TRafBitmap; @desc: Crops the image down to the given bounds. } function TRafBitmap.Crop(X1,Y1,X2,Y2:Int32): TRafBitmap; var m:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.Crop()')) then Exit; M := Self.ToMatrix().Area(x1,y1,x2,y2); Result.FromMatrix(M); end; {!DOCREF} { @method: procedure TRafBitmap.LazyCrop(X1,Y1,X2,Y2:Int32); @desc: Crops the image down to the given bounds. [note]Modifies the image, does not make a copy[/note] } procedure TRafBitmap.LazyCrop(X1,Y1,X2,Y2:Int32); begin if not(Self.IsLoaded('TRafBitmap.LazyCrop()')) then Exit; CropBitmap(Self.Bitmap, X1,Y1,X2,Y2); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); end; {!DOCREF} { @method: function TRafBitmap.GetPixels(TPA:TPointArray): TIntegerArray; @desc: Returns all the pixels in the `TPA` from the image } function TRafBitmap.GetPixels(TPA:TPointArray): TIntegerArray; begin if not(Self.IsLoaded('TRafBitmap.GetPixels()')) then Exit; Result := FastGetPixels(Self.Bitmap, TPA); end; {!DOCREF} { @method: function TRafBitmap.Pixel(x,y:Integer): Integer; @desc: Gets the color at the given pixel } function TRafBitmap.Pixel(x,y:Integer): Integer; begin if not(Self.IsLoaded('TRafBitmap.Pixel()')) then Exit; Result := FastGetPixel(Self.Bitmap, x,y); end; {!DOCREF} { @method: procedure TRafBitmap.Pixel(x,y, color:Integer); overload; @desc: Sets the given pixels value to the value `color` } procedure TRafBitmap.Pixel(x,y, color:Integer); overload; begin if not(Self.IsLoaded('TRafBitmap.Pixel()')) then Exit; FastSetPixel(Self.Bitmap, x,y, color); end; {!DOCREF} { @method: procedure TRafBitmap.SetPixels(TPA:TPointArray; Color:Int32); @desc: Sets all the given pixels to value `color` } procedure TRafBitmap.SetPixels(TPA:TPointArray; Color:Int32); var i,x,y, Hi: Integer; begin if not(Self.IsLoaded('TRafBitmap.SetPixels()')) then Exit; Hi := High(TPA); if (Hi < -1) then Exit; for i := 0 to Hi do begin x := TPA[i].X; y := TPA[i].Y; if ((x >= 0) and (y >= 0) and (x < Self.Width) and (y < Self.Height)) then Self.Pixel(x,y, color); end; //DrawTPABitmap(Self.Bitmap, TPA, color); end; {!DOCREF} { @method: procedure TRafBitmap.SetPixels(TPA:TPointArray; Colors:TIntArray); overload; @desc: Sets all the given pixels `TPA` to values in `colors` } procedure TRafBitmap.SetPixels(TPA:TPointArray; Colors:TIntArray); overload; begin if not(Self.IsLoaded('TRafBitmap.SetPixels()')) then Exit; FastSetPixels(Self.Bitmap, TPA, Colors); end; {!DOCREF} { @method: procedure TRafBitmap.ReplaceColor(OldColor, NewColor: Int32); @desc: Replaces all the occurances of `OldColor` with `NewColor` } procedure TRafBitmap.ReplaceColor(OldColor, NewColor: Int32); begin if not(Self.IsLoaded('TRafBitmap.ReplaceColor()')) then Exit; FastReplaceColor(Self.Bitmap, OldColor, NewColor); end; {!DOCREF} { @method: function TRafBitmap.ToMatrix(): TIntMatrix; @desc: Returns a 2D matrix-representation of the image } function TRafBitmap.ToMatrix(): TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.ToMatrix()')) then Exit; Result := BitmapToMatrix(Self.Bitmap); end; {!DOCREF} { @method: procedure TRafBitmap.FromMatrix(Matrix: TIntMatrix); @desc: Copys the data from the 2D matrix and writes it to the image } procedure TRafBitmap.FromMatrix(Matrix: TIntMatrix); begin if Self.Loaded then begin try DrawMatrixBitmap(Self.Bitmap, Matrix); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); except RaiseWarning('TRafBitmap.FromMatrix: Matrix is not initalized', ERR_WARNING); end; end else begin Self.Create(1,1); DrawMatrixBitmap(Self.Bitmap, Matrix); GetBitmapSize(Self.Bitmap, Self.Width, Self.Height); end; end; {!DOCREF} { @method: function TRafBitmap.FindColorTol(var TPA:TPointArray; Color:Integer; Area:TBox; Tolerance:Integer): Boolean; @desc: Searches for the given `color` in the bitmap. [note]method is using a deprecated function. That means params might change in the future[/note] } function TRafBitmap.FindColorTol(var TPA:TPointArray; Color:Integer; Area:TBox; Tolerance:Integer): Boolean; var Matrix: TIntMatrix; begin Result := False; if not(Self.IsLoaded('TRafBitmap.FindColorTol()')) then Exit; if (Area.X2 >= Self.Width) then Area.X2 := Self.Width - 1 else if (Area.X2 <= -1) then Area.X2 := Self.Width - Area.x2; if (Area.Y2 >= Self.Height) then Area.Y2 := Self.Height - 1 else if (Area.Y2 <= -1) then Area.Y2 := Self.Height - Area.y2; if (Area.X1 > Area.X2) or (Area.Y1 > Area.Y2) then Exit; Matrix := Self.ToMatrix(); Matrix := Matrix.Area(Area.x1,Area.y1,Area.x2,Area.y2); Result := exp_ImFindColorTolEx(Matrix, TPA, Color, Tolerance); SetLength(Matrix, 0); if not(Result) then Exit; if (Area.X1=0) and (Area.Y1 = 0) then Exit; OffsetTPA(TPA, Point(Area.X1, Area.Y1)); end; {!DOCREF} { @method: function TRafBitmap.FindColor(var TPA:TPointArray; Color:Integer; Area:TBox): Boolean; @desc: Searches for the given 'color' in the bitmap. [note]method is using a deprecated function. That means params might change in the future[/note] } function TRafBitmap.FindColor(var TPA:TPointArray; Color:Integer; Area:TBox): Boolean; begin Result := Self.FindColorTol(TPA, Color, Area, 0); end; {!DOCREF} { @method: function TRafBitmap.FindColor(var TPA:TPointArray; Color:Integer): Boolean; overload; @desc: Searches for the given 'color' in the bitmap. [note]method is using a deprecated function. That means params might change in the future[/note] } function TRafBitmap.FindColor(var TPA:TPointArray; Color:Integer): Boolean; overload; begin Result := Self.FindColorTol(TPA, Color, IntToBox(0,0,self.width,self.height), 0); end; (*=============================================================================| Transformations |=============================================================================*) {!DOCREF} { @method: procedure TRafBitmap.Resize(NewWidth, NewHeight:Integer); @desc: Simple and quick bitmap resizing using nearest neighbor. } procedure TRafBitmap.Resize(NewWidth, NewHeight:Integer); begin if not(Self.IsLoaded('TRafBitmap.Resize()')) then Exit; ResizeBitmapEx(Self.Bitmap, RM_Bilinear, NewWidth, NewHeight); Self.Width := NewWidth; Self.Height := NewHeight; end; {!DOCREF} { @method: procedure TRafBitmap.ResizeEx(NewWidth, NewHeight:Integer; Resampler:TResizeAlgo=RA_BILINEAR); @desc: Allows you to resize the bitmap by not just using nearest neighbor, but also BICUBIC, and BILINEAR interpolation } procedure TRafBitmap.ResizeEx(NewWidth, NewHeight:Integer; Resampler:TResizeAlgo=RA_BILINEAR); var Matrix:T2DIntegerArray; begin if not(Self.IsLoaded('TRafBitmap.ResizeEx()')) then Exit; Matrix := Self.ToMatrix(); exp_ImResize(Matrix, NewWidth, NewHeight, Resampler); Self.FromMatrix(Matrix); end; {!DOCREF} { @method: function TRafBitmap.Rotate(Angle:Extended; Expand:Boolean; Smooth:Boolean=True): TRafBitmap; @desc: Rotates a copy of the bitmap by the given angle. [params] [b]Algle:[/b] The amount to rotate the bitmap, defined in radians [b]Expand:[/b] `True` means that the result is expanded to fit the rotated image. `False` keeps original size. [b]Smooth:[/b] `True` will use bilinear interpolation, while `False` will use nearest neighbor. [/params] } function TRafBitmap.Rotate(Angle:Extended; Expand:Boolean; Smooth:Boolean=True): TRafBitmap; var Mat:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.RotateCopy()')) then Exit; Mat := exp_ImRotate(Self.ToMatrix(), Angle, Expand, Smooth); Result.FromMatrix(Mat); end; {!DOCREF} { @method: procedure TRafBitmap.LazyRotate(Angle:Extended; Expand:Boolean; Smooth:Boolean=True); @desc: Rotates a copy of the bitmap by the given angle. [params] [b]Algle:[/b] The amount to rotate the bitmap, defined in radians [b]Expand:[/b] `True` means that the result is expanded to fit the rotated image. `False` keeps original size. [b]Smooth:[/b] `True` will use bilinear interpolation, while `False` will use nearest neighbor. [/params] } procedure TRafBitmap.LazyRotate(Angle:Extended; Expand:Boolean; Smooth:Boolean=True); var Mat:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.RotateCopy()')) then Exit; Mat := exp_ImRotate(Self.ToMatrix(), Angle, Expand, Smooth); Self.FromMatrix(Mat); end; {!DOCREF} { @method: function TRafBitmap.Flip(Horizontal:Boolean): TRafBitmap; @desc: Flips the bitmap Left->Right `Horizontal=True` or Top->Down `Horizontal=False` } function TRafBitmap.Flip(Horizontal:Boolean): TRafBitmap; var method: TBmpMirrorStyle; begin if not(Self.IsLoaded('TRafBitmap.Flip()')) then Exit; case Horizontal of True: method := MirrorWidth; False:method := MirrorHeight; end; Result.Bitmap := CreateMirroredBitmapEx(Self.Bitmap, method); GetBitmapSize(Result.Bitmap, Result.Width, Result.Height); Result.Loaded := True; end; {!DOCREF} { @method: procedure TRafBitmap.Invert(); @desc: Inverts the colors in the bitmap } procedure TRafBitmap.Invert(); begin if not(Self.IsLoaded('TRafBitmap.Invert()')) then Exit; InvertBitmap(Self.Bitmap); end; {!DOCREF} { @method: procedure TRafBitmap.Blur(Radius: Integer; Iter:Integer=0); @desc: Allows you to blur the bitmap `Iter` times, with a radius of the size `Radius` } procedure TRafBitmap.Blur(Radius: Integer; Iter:Integer=0); var i:Int32; Matrix:TIntMatrix; function BlurMore(Mat:TIntMatrix; Box:Int32):TIntMatrix; begin Result := exp_ImBlur(Mat, Box); end; begin if not(Self.IsLoaded('TRafBitmap.Blur()')) then Exit; Matrix := Self.ToMatrix(); for i:=0 to Iter do Matrix := BlurMore(Matrix, Radius); Self.FromMatrix(Matrix); end; {!DOCREF} { @method: procedure TRafBitmap.MedianBlur(Radius: Integer); @desc: Computes the median of the neighborhood of radius `Radius` for each pixel in the image and sets the result pixel to that value. } procedure TRafBitmap.Median(Radius: Integer); var Matrix:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.Median()')) then Exit; Matrix := exp_ImMedianBlur(Self.ToMatrix(), Radius); Self.FromMatrix(Matrix); end; {!DOCREF} { @method: procedure TRafBitmap.GaussianBlur(Radius: Integer; Sigma:Single=1.5); @desc: Appends a gaussion blur to the bitmap, with a radius of the size `Radius`. Sigma is a modifier, higher sigma = less focus on center. } procedure TRafBitmap.GaussianBlur(Radius: Integer; Sigma:Single=1.5); var i:Int32; Matrix:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.GaussianBlur()')) then Exit(); SetLength(Matrix, Self.Height,Self.Width); exp_ImGaussBlur(Self.ToMatrix(), Matrix, Radius, sigma); Self.FromMatrix(Matrix); end; {!DOCREF} { @method: procedure TRafBitmap.Brightness(Amount:Extended; Legacy:Boolean); @desc: Allows you to modify the brightness of the bitmap. This function is still slightly bugged if `Legacy=False`. } procedure TRafBitmap.Brightness(Amount:Extended; Legacy:Boolean=True); var Matrix:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.Brightness()')) then Exit; Matrix := Self.ToMatrix(); Matrix := exp_ImBrighten(Matrix, Amount, Legacy); Self.FromMatrix(Matrix); end; {!DOCREF} { @method: function TRafBitmap.Blend(Other:TRafBitmap; Alpha:Single): TRafBitmap; @desc: Belnds the two images in to one. Alpha must be in range of `0.0-1.0`. Both images must also be the exact same size. } function TRafBitmap.Blend(Other:TRafBitmap; Alpha:Single): TRafBitmap; var Matrix:TIntMatrix; begin if not(Self.IsLoaded('TRafBitmap.Blend()')) then Exit; if not(Other.Loaded) then RaiseException(erException, '"Other" bitmap is not loaded.'); if not(Other.Width=Self.Width) or not(Other.Height=Self.Height) then RaiseException(erException, 'Bitmaps must have the same size'); Matrix := exp_ImBlend(Self.ToMatrix(), Other.ToMatrix(), Alpha); Result.FromMatrix(Matrix); end; {!DOCREF} { @method: function TRafBitmap.Draw(Other:TRafBitmap; Pos:TPoint; AutoResize:Boolean=False): TRafBitmap; @desc: Draws the `other` image to the current image-instance at the given position `Pos`. If `AutoResize` is `True`, it will resize the current image-instance automaticly if needed. } function TRafBitmap.Draw(Other:TRafBitmap; Pos:TPoint; AutoResize:Boolean=False): TRafBitmap; var nw,nh:Int32; begin if not(Self.IsLoaded('TRafBitmap.Blend()')) then Exit; if AutoResize then begin NW := Self.Width; NH := Self.Height; if Pos.x+Other.Width >= Self.Width then NW := Pos.x+Other.Width; if Pos.y+Other.Height >= Self.Height then NH := Pos.y+Other.Height; if (NH > Self.Height) or (NW > Self.Width) then Self.SetSize(NW, NH); end; FastDrawTransparent(Pos.x, Pos.y, other.bitmap, self.bitmap); end; (*=============================================================================| Other functinality |=============================================================================*) {!DOCREF} { @method: procedure TRafBitmap.Debug(); @desc: Debugs the bitmap } procedure TRafBitmap.Debug(); begin if not(Self.IsLoaded('TRafBitmap.Debug()')) then Exit; DisplayDebugImgWindow(Self.Width,Self.Height); DrawBitmapDebugImg(Self.Bitmap); end; {!DOCREF} { @method: function TRafBitmap.ToString(): String; @desc: Converts the bitmap in to an encoded string format. This format can then be used with `TRafBitmap.Create(W,H:Int32; Str:String);` to recreate the bitmap. } function TRafBitmap.ToString(): String; begin if not(Self.IsLoaded('TRafBitmap.ToString()')) then Exit; Result := CreateBitmapString(Self.Bitmap); end; {!DOCREF} { @method: procedure TRafBitmap.Free(); @desc: Releases the bitmap } procedure TRafBitmap.Free(); begin if not(Self.IsLoaded('TRafBitmap.Free()')) then Exit; FreeBitmap(Self.Bitmap); Self.Width := 0; Self.Height := 0; Self.Loaded := False; end; function TRafBitmap.IsLoaded(CallFrom:String; RaiseErr:Boolean=True): Boolean; begin Result := Self.Loaded; if not(Result) then begin RaiseWarning(CallFrom+': Bitmap is not initalized', ERR_WARNING); end; end; {$ENDIF}
inherited dmOrdemServico: TdmOrdemServico OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETOS' ' (FIL_ORIG, NR_OS, DT_EMISSAO, DT_BAIXA, STATUS, OS_VEICULO, OS' + '_SOLICITANTE, TIPO_FRETE, CGC_REMET, CGC_DEST, REDESPACHANTE, CO' + 'NSIGNATARIO, RESPONSAVEL, VEICULO, MOTORISTA, VLR_MERC, PESO, VO' + 'LUME, OBSERVACAO, FRT_COMBINADO, ADIANTAMENTO, CTO_DOCUMENTO, CT' + 'O_FILIAL, FIL_ORDPGTO, NR_ORDPGTO, DT_ORDPGTO, CTO_NUMERO, DT_AL' + 'TERACAO, OPERADOR, ISS_ORDPGTO, NR_PEDIDO, M3, CARRETA, DT_ATRAC' + 'AGEM, DT_DEMURRAGE, DT_DEADLINE, DT_VCTOARM, TP_ORDEM)' 'VALUES' ' (:FIL_ORIG, :NR_OS, :DT_EMISSAO, :DT_BAIXA, :STATUS, :OS_VEICU' + 'LO, :OS_SOLICITANTE, :TIPO_FRETE, :CGC_REMET, :CGC_DEST, :REDESP' + 'ACHANTE, :CONSIGNATARIO, :RESPONSAVEL, :VEICULO, :MOTORISTA, :VL' + 'R_MERC, :PESO, :VOLUME, :OBSERVACAO, :FRT_COMBINADO, :ADIANTAMEN' + 'TO, :CTO_DOCUMENTO, :CTO_FILIAL, :FIL_ORDPGTO, :NR_ORDPGTO, :DT_' + 'ORDPGTO, :CTO_NUMERO, :DT_ALTERACAO, :OPERADOR, :ISS_ORDPGTO, :N' + 'R_PEDIDO, :M3, :CARRETA, :DT_ATRACAGEM, :DT_DEMURRAGE, :DT_DEADL' + 'INE, :DT_VCTOARM, :TP_ORDEM)') SQLDelete.Strings = ( 'DELETE FROM STWOPETOS' 'WHERE' ' FIL_ORIG = :Old_FIL_ORIG AND NR_OS = :Old_NR_OS') SQLUpdate.Strings = ( 'UPDATE STWOPETOS' 'SET' ' FIL_ORIG = :FIL_ORIG, NR_OS = :NR_OS, DT_EMISSAO = :DT_EMISSAO' + ', DT_BAIXA = :DT_BAIXA, STATUS = :STATUS, OS_VEICULO = :OS_VEICU' + 'LO, OS_SOLICITANTE = :OS_SOLICITANTE, TIPO_FRETE = :TIPO_FRETE, ' + 'CGC_REMET = :CGC_REMET, CGC_DEST = :CGC_DEST, REDESPACHANTE = :R' + 'EDESPACHANTE, CONSIGNATARIO = :CONSIGNATARIO, RESPONSAVEL = :RES' + 'PONSAVEL, VEICULO = :VEICULO, MOTORISTA = :MOTORISTA, VLR_MERC =' + ' :VLR_MERC, PESO = :PESO, VOLUME = :VOLUME, OBSERVACAO = :OBSERV' + 'ACAO, FRT_COMBINADO = :FRT_COMBINADO, ADIANTAMENTO = :ADIANTAMEN' + 'TO, CTO_DOCUMENTO = :CTO_DOCUMENTO, CTO_FILIAL = :CTO_FILIAL, FI' + 'L_ORDPGTO = :FIL_ORDPGTO, NR_ORDPGTO = :NR_ORDPGTO, DT_ORDPGTO =' + ' :DT_ORDPGTO, CTO_NUMERO = :CTO_NUMERO, DT_ALTERACAO = :DT_ALTER' + 'ACAO, OPERADOR = :OPERADOR, ISS_ORDPGTO = :ISS_ORDPGTO, NR_PEDID' + 'O = :NR_PEDIDO, M3 = :M3, CARRETA = :CARRETA, DT_ATRACAGEM = :DT' + '_ATRACAGEM, DT_DEMURRAGE = :DT_DEMURRAGE, DT_DEADLINE = :DT_DEAD' + 'LINE, DT_VCTOARM = :DT_VCTOARM, TP_ORDEM = :TP_ORDEM' 'WHERE' ' FIL_ORIG = :Old_FIL_ORIG AND NR_OS = :Old_NR_OS') SQLRefresh.Strings = ( 'SELECT FIL_ORIG, NR_OS, DT_EMISSAO, DT_BAIXA, STATUS, OS_VEICULO' + ', OS_SOLICITANTE, TIPO_FRETE, CGC_REMET, CGC_DEST, REDESPACHANTE' + ', CONSIGNATARIO, RESPONSAVEL, VEICULO, MOTORISTA, VLR_MERC, PESO' + ', VOLUME, OBSERVACAO, FRT_COMBINADO, ADIANTAMENTO, CTO_DOCUMENTO' + ', CTO_FILIAL, FIL_ORDPGTO, NR_ORDPGTO, DT_ORDPGTO, CTO_NUMERO, D' + 'T_ALTERACAO, OPERADOR, ISS_ORDPGTO, NR_PEDIDO, M3, CARRETA, DT_A' + 'TRACAGEM, DT_DEMURRAGE, DT_DEADLINE, DT_VCTOARM, TP_ORDEM FROM S' + 'TWOPETOS' 'WHERE' ' FIL_ORIG = :Old_FIL_ORIG AND NR_OS = :Old_NR_OS') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETOS' 'WHERE' 'FIL_ORIG = :Old_FIL_ORIG AND NR_OS = :Old_NR_OS' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT' ' OS.*,' ' RM.NOME NM_REMETENTE,' ' RM.CIDADE ORIG_CIDADE,' ' RM.ESTADO ORIG_ESTADO,' ' DEST.NOME NM_DESTINATARIO,' ' DEST.CIDADE DEST_CIDADE,' ' DEST.ESTADO DEST_ESTADO,' ' REDESP.NOME NM_REDESPACHANTE,' ' REDESP.CIDADE REDESP_CIDADE,' ' REDESP.ESTADO REDESP_ESTADO,' ' CONSIG.NOME NM_CONSIGNATARIO,' ' CONSIG.CIDADE CONSIG_CIDADE,' ' CONSIG.ESTADO CONSIG_ESTADO,' ' RESP.NOME NM_RESPONSAVEL,' ' RESP.FILIAL FIL_RESPONSAVEL,' ' MOT.NOME NM_MOTORISTA,' ' TPVEIC.DESCRICAO NM_OSVEICULO,' ' NOTA.CONTEUDO,' ' (RM.ENDERECO || '#39', '#39' || RM.END_NRO) END_REMETENTE,' ' (DEST.ENDERECO || '#39', '#39' || DEST.END_NRO) END_DESTINATARIO,' ' VEI.PLACA PLC_VEICULO,' ' VEI.MODELO MOD_VEICULO' 'FROM STWOPETOS OS' 'LEFT JOIN STWOPETCLI RM ON OS.CGC_REMET = RM.CGC' 'LEFT JOIN STWOPETCLI DEST ON OS.CGC_DEST = DEST.CGC' 'LEFT JOIN STWOPETCLI REDESP ON OS.REDESPACHANTE = REDESP.CGC' 'LEFT JOIN STWOPETCLI CONSIG ON OS.CONSIGNATARIO = CONSIG.CGC' 'LEFT JOIN STWOPETCLI RESP ON OS.RESPONSAVEL = RESP.CGC' 'LEFT JOIN STWOPETMOT MOT ON OS.MOTORISTA = MOT.CPF' 'LEFT JOIN STWOPETVEI VEI ON OS.OS_VEICULO = VEI.FROTA' 'LEFT JOIN STWOPETTPVE TPVEIC ON OS.OS_VEICULO = TPVEIC.CODIGO' 'LEFT JOIN STWOPETNOTA NOTA ON OS.FIL_ORIG = NOTA.FIL_ORIG AND OS' + '.NR_OS = NOTA.NR_CTO AND NOTA.DOCUMENTO = '#39'OS'#39) object qryManutencaoFIL_ORIG: TStringField FieldName = 'FIL_ORIG' Required = True Size = 3 end object qryManutencaoNR_OS: TIntegerField FieldName = 'NR_OS' Required = True end object qryManutencaoDT_EMISSAO: TDateTimeField FieldName = 'DT_EMISSAO' end object qryManutencaoDT_BAIXA: TDateTimeField FieldName = 'DT_BAIXA' end object qryManutencaoSTATUS: TStringField FieldName = 'STATUS' Size = 2 end object qryManutencaoOS_VEICULO: TIntegerField FieldName = 'OS_VEICULO' end object qryManutencaoOS_SOLICITANTE: TStringField FieldName = 'OS_SOLICITANTE' end object qryManutencaoTIPO_FRETE: TStringField FieldName = 'TIPO_FRETE' Size = 1 end object qryManutencaoCGC_REMET: TStringField FieldName = 'CGC_REMET' Size = 18 end object qryManutencaoCGC_DEST: TStringField FieldName = 'CGC_DEST' Size = 18 end object qryManutencaoREDESPACHANTE: TStringField FieldName = 'REDESPACHANTE' Size = 18 end object qryManutencaoCONSIGNATARIO: TStringField FieldName = 'CONSIGNATARIO' Size = 18 end object qryManutencaoRESPONSAVEL: TStringField FieldName = 'RESPONSAVEL' Size = 18 end object qryManutencaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryManutencaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryManutencaoVLR_MERC: TFloatField FieldName = 'VLR_MERC' end object qryManutencaoPESO: TFloatField FieldName = 'PESO' end object qryManutencaoVOLUME: TFloatField FieldName = 'VOLUME' end object qryManutencaoOBSERVACAO: TStringField FieldName = 'OBSERVACAO' Size = 200 end object qryManutencaoFRT_COMBINADO: TFloatField FieldName = 'FRT_COMBINADO' end object qryManutencaoADIANTAMENTO: TFloatField FieldName = 'ADIANTAMENTO' end object qryManutencaoCTO_DOCUMENTO: TStringField FieldName = 'CTO_DOCUMENTO' Size = 2 end object qryManutencaoCTO_FILIAL: TStringField FieldName = 'CTO_FILIAL' Size = 3 end object qryManutencaoFIL_ORDPGTO: TStringField FieldName = 'FIL_ORDPGTO' Size = 3 end object qryManutencaoNR_ORDPGTO: TFloatField FieldName = 'NR_ORDPGTO' end object qryManutencaoDT_ORDPGTO: TDateTimeField FieldName = 'DT_ORDPGTO' end object qryManutencaoCTO_NUMERO: TFloatField FieldName = 'CTO_NUMERO' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryManutencaoISS_ORDPGTO: TFloatField FieldName = 'ISS_ORDPGTO' end object qryManutencaoNR_PEDIDO: TFloatField FieldName = 'NR_PEDIDO' end object qryManutencaoM3: TFloatField FieldName = 'M3' end object qryManutencaoCARRETA: TStringField FieldName = 'CARRETA' Size = 8 end object qryManutencaoNM_REMETENTE: TStringField FieldName = 'NM_REMETENTE' ProviderFlags = [] Size = 40 end object qryManutencaoORIG_CIDADE: TStringField FieldName = 'ORIG_CIDADE' ProviderFlags = [] Size = 30 end object qryManutencaoORIG_ESTADO: TStringField FieldName = 'ORIG_ESTADO' ProviderFlags = [] Size = 2 end object qryManutencaoNM_DESTINATARIO: TStringField FieldName = 'NM_DESTINATARIO' ProviderFlags = [] Size = 40 end object qryManutencaoDEST_CIDADE: TStringField FieldName = 'DEST_CIDADE' ProviderFlags = [] Size = 30 end object qryManutencaoDEST_ESTADO: TStringField FieldName = 'DEST_ESTADO' ProviderFlags = [] Size = 2 end object qryManutencaoNM_REDESPACHANTE: TStringField FieldName = 'NM_REDESPACHANTE' ProviderFlags = [] Size = 40 end object qryManutencaoREDESP_CIDADE: TStringField FieldName = 'REDESP_CIDADE' ProviderFlags = [] Size = 30 end object qryManutencaoREDESP_ESTADO: TStringField FieldName = 'REDESP_ESTADO' ProviderFlags = [] Size = 2 end object qryManutencaoNM_CONSIGNATARIO: TStringField FieldName = 'NM_CONSIGNATARIO' ProviderFlags = [] Size = 40 end object qryManutencaoCONSIG_CIDADE: TStringField FieldName = 'CONSIG_CIDADE' ProviderFlags = [] Size = 30 end object qryManutencaoCONSIG_ESTADO: TStringField FieldName = 'CONSIG_ESTADO' ProviderFlags = [] Size = 2 end object qryManutencaoNM_RESPONSAVEL: TStringField FieldName = 'NM_RESPONSAVEL' ProviderFlags = [] Size = 40 end object qryManutencaoFIL_RESPONSAVEL: TStringField FieldName = 'FIL_RESPONSAVEL' ProviderFlags = [] Size = 3 end object qryManutencaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ProviderFlags = [] Size = 40 end object qryManutencaoNM_OSVEICULO: TStringField FieldName = 'NM_OSVEICULO' ProviderFlags = [] end object qryManutencaoCONTEUDO: TStringField FieldName = 'CONTEUDO' ProviderFlags = [] end object qryManutencaoEND_REMETENTE: TStringField FieldName = 'END_REMETENTE' ProviderFlags = [] Size = 122 end object qryManutencaoEND_DESTINATARIO: TStringField FieldName = 'END_DESTINATARIO' ProviderFlags = [] Size = 122 end object qryManutencaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ProviderFlags = [] Size = 8 end object qryManutencaoMOD_VEICULO: TStringField FieldName = 'MOD_VEICULO' ProviderFlags = [] Size = 15 end object qryManutencaoDT_ATRACAGEM: TDateTimeField FieldName = 'DT_ATRACAGEM' end object qryManutencaoDT_DEMURRAGE: TDateTimeField FieldName = 'DT_DEMURRAGE' end object qryManutencaoDT_DEADLINE: TDateTimeField FieldName = 'DT_DEADLINE' end object qryManutencaoDT_VCTOARM: TDateTimeField FieldName = 'DT_VCTOARM' end object qryManutencaoTP_ORDEM: TStringField FieldName = 'TP_ORDEM' end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT' ' OS.*,' ' RM.NOME NM_REMETENTE,' ' RM.CIDADE ORIG_CIDADE,' ' RM.ESTADO ORIG_ESTADO,' ' DEST.NOME NM_DESTINATARIO,' ' DEST.CIDADE DEST_CIDADE,' ' DEST.ESTADO DEST_ESTADO,' ' REDESP.NOME NM_REDESPACHANTE,' ' REDESP.CIDADE REDESP_CIDADE,' ' REDESP.ESTADO REDESP_ESTADO,' ' CONSIG.NOME NM_CONSIGNATARIO,' ' CONSIG.CIDADE CONSIG_CIDADE,' ' CONSIG.ESTADO CONSIG_ESTADO,' ' RESP.NOME NM_RESPONSAVEL,' ' RESP.FILIAL FIL_RESPONSAVEL,' ' MOT.NOME NM_MOTORISTA,' ' TPVEIC.DESCRICAO NM_OSVEICULO,' ' NOTA.CONTEUDO,' ' (RM.ENDERECO || '#39', '#39' || RM.END_NRO) END_REMETENTE,' ' (DEST.ENDERECO || '#39', '#39' || DEST.END_NRO) END_DESTINATARIO,' ' VEI.PLACA PLC_VEICULO,' ' VEI.MODELO MOD_VEICULO' 'FROM STWOPETOS OS' 'LEFT JOIN STWOPETCLI RM ON OS.CGC_REMET = RM.CGC' 'LEFT JOIN STWOPETCLI DEST ON OS.CGC_DEST = DEST.CGC' 'LEFT JOIN STWOPETCLI REDESP ON OS.REDESPACHANTE = REDESP.CGC' 'LEFT JOIN STWOPETCLI CONSIG ON OS.CONSIGNATARIO = CONSIG.CGC' 'LEFT JOIN STWOPETCLI RESP ON OS.RESPONSAVEL = RESP.CGC' 'LEFT JOIN STWOPETMOT MOT ON OS.MOTORISTA = MOT.CPF' 'LEFT JOIN STWOPETVEI VEI ON OS.OS_VEICULO = VEI.FROTA' 'LEFT JOIN STWOPETTPVE TPVEIC ON OS.OS_VEICULO = TPVEIC.CODIGO' 'LEFT JOIN STWOPETNOTA NOTA ON OS.FIL_ORIG = NOTA.FIL_ORIG AND OS' + '.NR_OS = NOTA.NR_CTO AND NOTA.DOCUMENTO = '#39'OS'#39) object qryLocalizacaoFIL_ORIG: TStringField FieldName = 'FIL_ORIG' Required = True Size = 3 end object qryLocalizacaoNR_OS: TIntegerField FieldName = 'NR_OS' Required = True end object qryLocalizacaoDT_EMISSAO: TDateTimeField FieldName = 'DT_EMISSAO' end object qryLocalizacaoDT_BAIXA: TDateTimeField FieldName = 'DT_BAIXA' end object qryLocalizacaoSTATUS: TStringField FieldName = 'STATUS' Size = 2 end object qryLocalizacaoOS_VEICULO: TIntegerField FieldName = 'OS_VEICULO' end object qryLocalizacaoOS_SOLICITANTE: TStringField FieldName = 'OS_SOLICITANTE' end object qryLocalizacaoTIPO_FRETE: TStringField FieldName = 'TIPO_FRETE' Size = 1 end object qryLocalizacaoCGC_REMET: TStringField FieldName = 'CGC_REMET' Size = 18 end object qryLocalizacaoCGC_DEST: TStringField FieldName = 'CGC_DEST' Size = 18 end object qryLocalizacaoREDESPACHANTE: TStringField FieldName = 'REDESPACHANTE' Size = 18 end object qryLocalizacaoCONSIGNATARIO: TStringField FieldName = 'CONSIGNATARIO' Size = 18 end object qryLocalizacaoRESPONSAVEL: TStringField FieldName = 'RESPONSAVEL' Size = 18 end object qryLocalizacaoVEICULO: TStringField FieldName = 'VEICULO' Size = 8 end object qryLocalizacaoMOTORISTA: TStringField FieldName = 'MOTORISTA' Size = 18 end object qryLocalizacaoVLR_MERC: TFloatField FieldName = 'VLR_MERC' end object qryLocalizacaoPESO: TFloatField FieldName = 'PESO' end object qryLocalizacaoVOLUME: TFloatField FieldName = 'VOLUME' end object qryLocalizacaoOBSERVACAO: TStringField FieldName = 'OBSERVACAO' Size = 200 end object qryLocalizacaoFRT_COMBINADO: TFloatField FieldName = 'FRT_COMBINADO' end object qryLocalizacaoADIANTAMENTO: TFloatField FieldName = 'ADIANTAMENTO' end object qryLocalizacaoCTO_DOCUMENTO: TStringField FieldName = 'CTO_DOCUMENTO' Size = 2 end object qryLocalizacaoCTO_FILIAL: TStringField FieldName = 'CTO_FILIAL' Size = 3 end object qryLocalizacaoFIL_ORDPGTO: TStringField FieldName = 'FIL_ORDPGTO' Size = 3 end object qryLocalizacaoNR_ORDPGTO: TFloatField FieldName = 'NR_ORDPGTO' end object qryLocalizacaoDT_ORDPGTO: TDateTimeField FieldName = 'DT_ORDPGTO' end object qryLocalizacaoCTO_NUMERO: TFloatField FieldName = 'CTO_NUMERO' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end object qryLocalizacaoISS_ORDPGTO: TFloatField FieldName = 'ISS_ORDPGTO' end object qryLocalizacaoNR_PEDIDO: TFloatField FieldName = 'NR_PEDIDO' end object qryLocalizacaoM3: TFloatField FieldName = 'M3' end object qryLocalizacaoCARRETA: TStringField FieldName = 'CARRETA' Size = 8 end object qryLocalizacaoNM_REMETENTE: TStringField FieldName = 'NM_REMETENTE' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoORIG_CIDADE: TStringField FieldName = 'ORIG_CIDADE' ProviderFlags = [] ReadOnly = True Size = 30 end object qryLocalizacaoORIG_ESTADO: TStringField FieldName = 'ORIG_ESTADO' ProviderFlags = [] ReadOnly = True Size = 2 end object qryLocalizacaoNM_DESTINATARIO: TStringField FieldName = 'NM_DESTINATARIO' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoDEST_CIDADE: TStringField FieldName = 'DEST_CIDADE' ProviderFlags = [] ReadOnly = True Size = 30 end object qryLocalizacaoDEST_ESTADO: TStringField FieldName = 'DEST_ESTADO' ProviderFlags = [] ReadOnly = True Size = 2 end object qryLocalizacaoNM_REDESPACHANTE: TStringField FieldName = 'NM_REDESPACHANTE' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoREDESP_CIDADE: TStringField FieldName = 'REDESP_CIDADE' ProviderFlags = [] ReadOnly = True Size = 30 end object qryLocalizacaoREDESP_ESTADO: TStringField FieldName = 'REDESP_ESTADO' ProviderFlags = [] ReadOnly = True Size = 2 end object qryLocalizacaoNM_CONSIGNATARIO: TStringField FieldName = 'NM_CONSIGNATARIO' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoCONSIG_CIDADE: TStringField FieldName = 'CONSIG_CIDADE' ProviderFlags = [] ReadOnly = True Size = 30 end object qryLocalizacaoCONSIG_ESTADO: TStringField FieldName = 'CONSIG_ESTADO' ProviderFlags = [] ReadOnly = True Size = 2 end object qryLocalizacaoNM_RESPONSAVEL: TStringField FieldName = 'NM_RESPONSAVEL' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoFIL_RESPONSAVEL: TStringField FieldName = 'FIL_RESPONSAVEL' ProviderFlags = [] ReadOnly = True Size = 3 end object qryLocalizacaoNM_MOTORISTA: TStringField FieldName = 'NM_MOTORISTA' ProviderFlags = [] ReadOnly = True Size = 40 end object qryLocalizacaoNM_OSVEICULO: TStringField FieldName = 'NM_OSVEICULO' ProviderFlags = [] ReadOnly = True end object qryLocalizacaoCONTEUDO: TStringField FieldName = 'CONTEUDO' ProviderFlags = [] ReadOnly = True end object qryLocalizacaoEND_REMETENTE: TStringField FieldName = 'END_REMETENTE' ReadOnly = True Size = 122 end object qryLocalizacaoEND_DESTINATARIO: TStringField FieldName = 'END_DESTINATARIO' ReadOnly = True Size = 122 end object qryLocalizacaoPLC_VEICULO: TStringField FieldName = 'PLC_VEICULO' ReadOnly = True Size = 8 end object qryLocalizacaoMOD_VEICULO: TStringField FieldName = 'MOD_VEICULO' ReadOnly = True Size = 15 end object qryLocalizacaoDT_ATRACAGEM: TDateTimeField FieldName = 'DT_ATRACAGEM' end object qryLocalizacaoDT_DEMURRAGE: TDateTimeField FieldName = 'DT_DEMURRAGE' end object qryLocalizacaoDT_DEADLINE: TDateTimeField FieldName = 'DT_DEADLINE' end object qryLocalizacaoDT_VCTOARM: TDateTimeField FieldName = 'DT_VCTOARM' end object qryLocalizacaoTP_ORDEM: TStringField FieldName = 'TP_ORDEM' end end end
unit udmRcboParceiros; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmRcboParceiros = class(TdmPadrao) qryLocalizacaoFIL_RECIBO: TStringField; qryLocalizacaoNRO_RECIBO: TFloatField; qryLocalizacaoEMISSAO: TDateTimeField; qryLocalizacaoREFERENCIA_I: TDateTimeField; qryLocalizacaoREFERENCIA_F: TDateTimeField; qryLocalizacaoUNIDADE: TStringField; qryLocalizacaoVLR_COMISSOES: TFloatField; qryLocalizacaoVLR_CREDITOS: TFloatField; qryLocalizacaoVLR_DESCONTOS: TFloatField; qryLocalizacaoVLR_LIQUIDO: TFloatField; qryLocalizacaoOBS: TBlobField; qryLocalizacaoSTATUS: TStringField; qryLocalizacaoFIL_ORIGEM: TStringField; qryLocalizacaoAUTORIZACAO: TFloatField; qryLocalizacaoPARCELA: TIntegerField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoNM_UNIDADE: TStringField; qryManutencaoFIL_RECIBO: TStringField; qryManutencaoNRO_RECIBO: TFloatField; qryManutencaoEMISSAO: TDateTimeField; qryManutencaoREFERENCIA_I: TDateTimeField; qryManutencaoREFERENCIA_F: TDateTimeField; qryManutencaoUNIDADE: TStringField; qryManutencaoVLR_COMISSOES: TFloatField; qryManutencaoVLR_CREDITOS: TFloatField; qryManutencaoVLR_DESCONTOS: TFloatField; qryManutencaoVLR_LIQUIDO: TFloatField; qryManutencaoOBS: TBlobField; qryManutencaoSTATUS: TStringField; qryManutencaoFIL_ORIGEM: TStringField; qryManutencaoAUTORIZACAO: TFloatField; qryManutencaoPARCELA: TIntegerField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryManutencaoNM_UNIDADE: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FNro_Recibo: Real; FEmissora: string; function GetSQL_DEFAULT: string; public property Emissora: string read FEmissora write FEmissora; property Nro_Recibo: Real read FNro_Recibo write FNro_Recibo; property SQLPadrao: string read GetSQL_DEFAULT; end; const SQL_DEFAULT = ' SELECT ' + ' RECP.FIL_RECIBO, ' + ' RECP.NRO_RECIBO, ' + ' RECP.EMISSAO, ' + ' RECP.REFERENCIA_I, ' + ' RECP.REFERENCIA_F, ' + ' RECP.UNIDADE, ' + ' RECP.VLR_COMISSOES, ' + ' RECP.VLR_CREDITOS, ' + ' RECP.VLR_DESCONTOS, ' + ' RECP.VLR_LIQUIDO, ' + ' RECP.OBS, ' + ' RECP.STATUS, ' + ' RECP.FIL_ORIGEM, ' + ' RECP.AUTORIZACAO, ' + ' RECP.PARCELA, ' + ' RECP.DT_ALTERACAO, ' + ' RECP.OPERADOR, ' + ' FIL.NOME NM_UNIDADE ' + ' FROM STWACRTRECT RECP ' + ' LEFT JOIN STWOPETFIL FIL ON FIL.FILIAL = RECP.UNIDADE '; var dmRcboParceiros: TdmRcboParceiros; implementation {$R *.dfm} { TdmRcboParceiros } function TdmRcboParceiros.GetSQL_DEFAULT: string; begin Result := SQL_DEFAULT; end; procedure TdmRcboParceiros.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE RECP.FIL_RECIBO = :FIL_RECIBO'); SQL.Add(' AND RECP.NRO_RECIBO = :NRO_RECIBO'); SQL.Add('ORDER BY RECP.FIL_RECIBO, RECP.NRO_RECIBO'); Params[0].AsString := FEmissora; Params[1].AsFloat := FNro_Recibo; end; end; procedure TdmRcboParceiros.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY RECP.FIL_RECIBO, RECP.NRO_RECIBO'); end; end; end.
unit l3LineArray; {* Информация о нарезке на строки. } { Библиотека "Эверест" } { Автор: Люлин А.В. } { Модуль: l3LineArray - описание массива форматированных строк} { Начат: 13.12.96 } { $Id: l3LineArray.pas,v 1.12 2012/11/01 07:09:29 lulin Exp $ } // $Log: l3LineArray.pas,v $ // Revision 1.12 2012/11/01 07:09:29 lulin // - вычищаем мусор. // // Revision 1.11 2011/06/09 17:06:18 lulin // {RequestLink:269060903}. // // Revision 1.10 2009/07/20 11:22:19 lulin // - заставляем работать F1 после - {RequestLink:141264340}. №7, 32, 33. // // Revision 1.9 2008/04/23 18:27:44 lulin // - <K>: 89106529. // // Revision 1.8 2008/02/20 18:35:00 lulin // - упрощаем наследование. // // Revision 1.7 2008/01/28 14:41:34 lulin // - объединил списки и динамические массивы. // // Revision 1.6 2007/09/25 07:41:56 lulin // - убрано ненужное значение параметра по-умолчанию. // // Revision 1.5 2007/01/30 15:24:24 lulin // - текст ноды - теперь более простого типа. // // Revision 1.4 2006/11/03 11:00:47 lulin // - объединил с веткой 6.4. // // Revision 1.3.24.3 2006/10/26 12:50:45 lulin // - используем полиморфизм, вместо выяснения класса объекта. // // Revision 1.3.24.2 2006/10/26 10:48:53 lulin // - избавляемся от преобразования карты форматирования к тегу. // // Revision 1.3.24.1 2006/10/26 09:02:31 lulin // - добавлен интерфейс - список форматированных строк. // // Revision 1.3 2005/11/01 15:49:23 lulin // - bug fix: бывало обращение к несуществующей строке параграфа в результате которого не рисовался документ (CQ OIT5-17516). // // Revision 1.2 2005/05/24 13:53:33 lulin // - rename unit: evFormattedLines -> l3FormattedLines. // // Revision 1.1 2005/05/24 13:43:34 lulin // - rename unit: evLineAr -> l3LineArray. // // Revision 1.20 2004/05/31 17:15:30 law // - cleanup. // // Revision 1.19 2004/05/27 14:31:56 law // - new methods: _Tl3_CBase.IsCacheable, _NeedStoreInPool. // // Revision 1.18 2004/04/20 14:53:39 law // - new method: Tl3PCharLen.InitPart. // - remove proc: ev_plAssign. // // Revision 1.17 2003/09/23 08:37:56 law // - new prop: IevHyperlink.Hint. // - rename proc: ev_plAssignNil -> l3AssignNil. // // Revision 1.16 2003/05/12 09:20:23 law // - rename proc: ev_plIsNil -> l3IsNil. // // Revision 1.15 2002/07/18 16:28:11 law // - new method: GetLine. // // Revision 1.14 2002/07/18 11:47:58 law // - new class: _TevBaseLineArray. // // Revision 1.13 2002/07/18 10:42:10 law // - comments. // // Revision 1.12 2002/07/09 12:02:20 law // - rename unit: evUnits -> l3Units. // // Revision 1.11 2002/02/06 11:36:42 law // - bug fix: не всегда учитывалась кодировка исходной строки. // // Revision 1.10 2001/06/22 09:07:38 law // - bug fix: подавление EListError при получении параметров несуществующей строки (что спорно, но пока сделано так). // // Revision 1.9 2001/06/19 09:29:50 law // - new behavior: TevLineArray теперь сделан на основе "динамического" массива. // // Revision 1.8 2001/02/26 09:06:49 law // - сделана обработка переноса слов по слогам. // // Revision 1.7 2000/12/15 15:10:36 law // - вставлены директивы Log. // {$I l3Define.inc } interface uses Classes, l3Interfaces, l3Types, l3Base, l3String, l3DynamicArray, l3Units ; type TevBaseLineInfo = packed object {* Информация о нарезке на строки. } public // public fields B : Long; {* - правая граница строки. } LE : Tl3Point; {* - размеры строки. } end;//TevBaseLineInfo TevLineInfo = packed object(TevBaseLineInfo) {* Информация о нарезке на строки и их оформлении. } public // public fields FI : Tl3FontIndexes; {* - набор индексов шрифта. } WC : Long; {* - количество слов (пробелов) в строке. } AddHyphen : Bool; {*- добавлять ли знак переноса. } end;{TevLineInfo} PevLineInfo = ^TevLineInfo; PevBaseLineInfo = ^TevBaseLineInfo; PPevLineInfo = ^PevLineInfo; TevBaseLineArray = class(Tl3DynamicArray) {* Массив нарезок на строки. } protected // property methods function GetLineWidth(i: Long): Long; procedure SetLineWidth(i: Long; Value: Long); {-} function GetLineHeight(i: Long): Long; {-} protected // internal methods function pm_GetItemSize: Long; override; {-} public // public methods procedure Add(B: Long; const LineExtent: Tl3_Point); reintroduce; {* - добавить информацию о строке. } class function IsCacheable: Bool; override; {-} procedure GetLineBorders(const aText: Tl3PCharLen; L: Long; var B1,B2: Long); {* - получить информацию о границах строки. } function GetLine(S: Tl3CustomString; i: Long): Tl3PCharLen; overload; {* - получить i-ю строку. } function GetLine(const S: Tl3PCharLenPrim; i: Long): Tl3PCharLen; overload; {* - получить i-ю строку. } public // public properties property LineWidth[i: Long]: Long read GetLineWidth write SetLineWidth; {* - ширина строки. } property LineHeight[i: Long]: Long read GetLineHeight; {* - высота строки. } property Items; {* - элементы массива. } end;//TevBaseLineArray TevLineArray = class(TevBaseLineArray, Il3Lines) {* Массив нарезок на строки. } protected // property methods function GetLineWordCount(i: Long): Long; procedure SetLineWordCount(i: Long; Value: Long); {-} protected // internal methods function AsObject: TObject; {-} function Get_Count: Integer; {-} function pm_GetItemSize: Long; override; {-} public // public methods procedure Add(aB : Long; var aLineExtent : Tl3_Point; aFI : Tl3FontIndexes; anAddHyphen : Bool); reintroduce; overload; {* - добавить информацию о строке. } procedure Add(B: Long; const LineExtent: Tl3_Point); overload; {* - добавить информацию о строке. } procedure ShiftLines(TL: Long; Len: Long); {* - сдвинуть информацию о нарезке. } public // public properties property LineWordCount[i: Long]: Long read GetLineWordCount write SetLineWordCount; {* - количество слов в строке. } end;//TevLineArray implementation uses l3Const, l3Chars ; // start class TevLineArray procedure TevLineArray.Add(aB : Long; var aLineExtent : Tl3_Point; aFI : Tl3FontIndexes; anAddHyphen : Bool); {overload;} begin if (l3_fiSub in aFI) then Inc(aLineExtent.P.Y, l3FontIndexDelta); if (l3_fiSuper in aFI) then Inc(aLineExtent.P.Y, l3FontIndexDelta); inherited Add(aB, aLineExtent); if (aFI = [l3_fiNone]) then aFI := []; with PevLineInfo(Items[Pred(Count)])^ do begin WC := -1; FI := aFI; AddHyphen := anAddHyphen; end;//PevLineInfo(Items[Pred(Count)])^ end; procedure TevLineArray.Add(B: Long; const LineExtent: Tl3_Point); {overload;} {-} var LE : Tl3_Point; begin LE := LineExtent; Add(B, LE, [], false); end; function TevLineArray.GetLineWordCount(i: Long): Long; begin try Result := PevLineInfo(Items[Pred(i)])^.WC; except on EListError do Result := 0; end;//try..except end; procedure TevLineArray.SetLineWordCount(i: Long; Value: Long); begin PevLineInfo(Items[Pred(i)])^.WC := Value; end; function TevLineArray.AsObject: TObject; {-} begin Result := Self; end; function TevLineArray.Get_Count: Integer; {-} begin Result := Count; end; function TevLineArray.pm_GetItemSize: Long; //override; {-} begin Result := SizeOf(TevLineInfo); end; procedure TevLineArray.ShiftLines(TL: Long; Len: Long); {-} var LI : PevBaseLineInfo; LID : Long; begin if (TL <= Count) then begin for LID := TL to Count do begin LI := Items[Pred(LID)]; LI^.B := LI^.B + Len; end;{for LID..} end;{TL <= Count} end; // start class TevBaseLineArray function TevBaseLineArray.GetLineWidth(i: Long): Long; begin try Result := PevBaseLineInfo(Items[Pred(i)])^.LE.X; except on EListError do Result := 0; end;//try..except end; procedure TevBaseLineArray.SetLineWidth(i: Long; Value: Long); begin PevBaseLineInfo(Items[Pred(i)])^.LE.X := Value; end; function TevBaseLineArray.GetLineHeight(i: Long): Long; begin try Result := PevBaseLineInfo(Items[Pred(i)])^.LE.Y; except on EListError do Result := 0; end;//try..except end; function TevBaseLineArray.pm_GetItemSize: Long; //override; {-} begin Result := SizeOf(TevBaseLineInfo); end; class function TevBaseLineArray.IsCacheable: Bool; {override;} {-} begin Result := true; end; procedure TevBaseLineArray.GetLineBorders(const aText: Tl3PCharLen; L: Long; var B1, B2: Long); begin B1 := 0; B2 := 0; if not l3IsNil(aText) then begin Dec(L); if (L = 0) then B1 := 0 else B1 := PevBaseLineInfo(Items[Pred(L)])^.B; if (Count = 0) OR (L = Count) then B2 := aText.SLen else B2 := PevBaseLineInfo(Items[L])^.B; end; end; function TevBaseLineArray.GetLine(S: Tl3CustomString; i: Long): Tl3PCharLen; begin if S.Empty then l3AssignNil(Result) else Result := GetLine(S.AsPCharLen, i); end; function TevBaseLineArray.GetLine(const S: Tl3PCharLenPrim; i: Long): Tl3PCharLen; //overload; {* - получить i-ю строку. } var O1, O2 : Long; begin if l3IsNil(S) then l3AssignNil(Result) else begin Dec(i); if (i = 0) then O1 := 0 else O1 := PevBaseLineInfo(Items[Pred(i)])^.B; if (Count = 0) OR (i = Count) then O2 := S.SLen else O2 := PevBaseLineInfo(Items[i])^.B; Result.InitPart(S.S, O1, O2, S.SCodePage); end;//l3IsNil(S) end; procedure TevBaseLineArray.Add(B: Long; const LineExtent: Tl3_Point); {overload;} {-} var LI : TevBaseLineInfo; begin LI.B := B; LI.LE := Tl3Point(LineExtent); inherited Add(LI); end; end.
unit i2cmem; interface uses {$IFDEF WINDOWS}windows,{$ELSE}main_engine,{$ENDIF} file_engine; type i2cmem_chip=class constructor create(tipo:byte); destructor free; public function read_sda:byte; procedure write_scl(valor:byte); procedure write_sda(valor:byte); procedure reset; procedure load_data(ptemp:pbyte); procedure write_data(file_name:string); function save_snapshot(data_dest:pbyte):word; procedure load_snapshot(data_dest:pbyte); private page:array[0..15] of byte; data:array[0..$7fff] of byte; wc,devsel_address_low:boolean; byteaddr,data_size,address_mask:word; page_written_size,page_offset,addresshigh,write_page_size,slave_address, devsel,scl,sdaw,shift,bits,state,sdar,e0,e1,e2,read_page_size:byte; function select_device:boolean; end; const STATE_IDLE=0; STATE_DEVSEL=1; STATE_ADDRESSHIGH=2; STATE_ADDRESSLOW=3; STATE_DATAIN=4; STATE_READSELACK=5; STATE_DATAOUT=6; STATE_RESET=7; I2CMEM_SLAVE_ADDRESS=$a0; I2CMEM_SLAVE_ADDRESS_ALT=$b0; DEVSEL_RW=1; DEVSEL_ADDRESS=$fe; I2C_24C02=6; I2C_24C08=10; I2C_24C256=14; var i2cmem_0:i2cmem_chip; implementation constructor i2cmem_chip.create(tipo:byte); begin case tipo of I2C_24C02:begin self.read_page_size:=0; self.write_page_size:=8; self.data_size:=$100; end; I2C_24C08:begin self.read_page_size:=0; self.write_page_size:=16; self.data_size:=$400; end; I2C_24C256:begin self.read_page_size:=0; self.write_page_size:=64; self.data_size:=$8000; end; end; self.address_mask:=self.data_size-1; fillchar(self.data[0],$8000,$ff); end; destructor i2cmem_chip.free; begin end; procedure i2cmem_chip.reset; begin self.scl:=0; self.sdaw:=0; self.e0:=0; self.e1:=0; self.e2:=0; self.wc:=false; self.sdar:=1; self.state:=STATE_IDLE; self.bits:=0; self.shift:=0; self.devsel:=0; self.addresshigh:=0; self.byteaddr:=0; self.page_offset:=0; self.page_written_size:=0; self.devsel_address_low:=false; self.slave_address:=I2CMEM_SLAVE_ADDRESS; end; procedure i2cmem_chip.load_data(ptemp:pbyte); begin copymemory(@self.data,ptemp,self.data_size); end; procedure i2cmem_chip.write_data(file_name:string); begin write_file(file_name,@self.data,self.data_size); end; function i2cmem_chip.select_device:boolean; var device:byte; mask:word; begin if self.devsel_address_low then begin // Due to a full address and read/write flag fitting in one 8-bit packet, the Xicor X24C01 replies on all addresses. select_device:=true; exit; end; device:=(self.slave_address and $f0) or (self.e2 shl 3) or (self.e1 shl 2) or (self.e0 shl 1); if (self.data_size<=$800) then mask:=DEVSEL_ADDRESS and not(self.address_mask shr 7) else mask:=DEVSEL_ADDRESS and $ffff; if ((self.devsel and mask)=(device and mask)) then begin select_device:=true; exit; end; select_device:=false; end; function i2cmem_chip.read_sda:byte; begin read_sda:=self.sdar and 1; end; procedure i2cmem_chip.write_scl(valor:byte); var offset:integer; begin if (self.scl<>valor) then begin self.scl:=valor; case self.state of STATE_DEVSEL, STATE_ADDRESSHIGH, STATE_ADDRESSLOW, STATE_DATAIN:begin if (self.bits<8) then begin if (self.scl<>0) then begin self.shift:=((self.shift shl 1) or self.sdaw) and $ff; self.bits:=self.bits+1; end; end else begin if (self.scl<>0) then begin self.bits:=self.bits+1; end else begin if (self.bits=8) then begin case self.state of STATE_DEVSEL:begin self.devsel:=self.shift; if ((self.devsel=0) and not(self.devsel_address_low)) then begin // TODO: Atmel datasheets document 2-wire software reset, but doesn't mention it will lower sda only that it will release it. // ltv_naru however requires it to be lowered, but we don't currently know the manufacturer of the chip used. self.state:=STATE_RESET; end else if not(self.select_device) then begin self.state:=STATE_IDLE; end else if ((self.devsel and DEVSEL_RW)=0) then begin if (self.devsel_address_low) then begin self.byteaddr:=(self.devsel and DEVSEL_ADDRESS) shr 1; self.page_offset:=0; self.page_written_size:=0; self.state:=STATE_DATAIN; end else begin if (self.data_size<=$800) then self.state:=STATE_ADDRESSLOW else self.state:=STATE_ADDRESSHIGH; end; end else begin if (self.devsel_address_low) then self.byteaddr:=(self.devsel and DEVSEL_ADDRESS) shr 1; self.state:=STATE_READSELACK; end; end; STATE_ADDRESSHIGH:begin self.addresshigh:=self.shift; self.state:=STATE_ADDRESSLOW; end; STATE_ADDRESSLOW:begin if (self.data_size<=$800) then self.byteaddr:=self.shift or ((self.devsel and DEVSEL_ADDRESS) shl 7) and self.address_mask else self.byteaddr:=self.shift or (self.addresshigh shl 8); self.page_offset:=0; self.page_written_size:=0; self.state:=STATE_DATAIN; end; STATE_DATAIN:begin if self.wc then begin self.state:=STATE_IDLE; end else if (self.write_page_size>0) then begin self.page[self.page_offset]:=self.shift; self.page_offset:=self.page_offset+1; if (self.page_offset=self.write_page_size) then self.page_offset:=0; self.page_written_size:=self.page_written_size+1; if (self.page_written_size>self.write_page_size) then self.page_written_size:=self.write_page_size; end else begin offset:=self.byteaddr and self.address_mask; self.data[offset]:=self.shift; self.byteaddr:=self.byteaddr+1; end end; end; //del segundo case if (self.state<>STATE_IDLE) then self.sdar:=0; end else begin //del if bits=8 self.bits:=0; self.sdar:=1; end; end; end; //del else del prime if end; STATE_READSELACK:begin self.bits:=0; self.state:=STATE_DATAOUT; end; STATE_DATAOUT:begin if (self.bits<8) then begin if (self.scl<>0) then begin self.bits:=self.bits+1; end else begin if (self.bits=0) then begin offset:=self.byteaddr and self.address_mask; self.shift:=self.data[offset]; self.byteaddr:=(self.byteaddr and not(self.read_page_size-1)) or ((self.byteaddr+1) and (self.read_page_size-1)); end; self.sdar:=(self.shift shr 7) and 1; self.shift:=(self.shift shl 1) and $ff; end; end else begin if (self.scl<>0) then begin if (self.sdaw<>0) then self.state:=STATE_IDLE; self.bits:=0; end else self.sdar:=1; end; end; STATE_RESET:begin if (self.scl<>0) then begin if (self.bits>8) then begin self.state:=STATE_IDLE; self.sdar:=1; end; self.bits:=self.bits+1; end; end; end; //del case end; //del if end; procedure i2cmem_chip.write_sda(valor:byte); var base,root,f:integer; begin valor:=valor and 1; if (self.sdaw<>valor) then begin self.sdaw:=valor; if (self.scl<>0) then begin if (self.sdaw<>0) then begin if (self.page_written_size>0) then begin base:=self.byteaddr and self.address_mask; root:=base and not(self.write_page_size-1); for f:=0 to (self.page_written_size-1) do self.data[root or ((base+f) and (self.write_page_size-1))]:=self.page[f]; self.page_written_size:=0; end; self.state:=STATE_IDLE; end else begin self.state:=STATE_DEVSEL; self.bits:=0; end; self.sdar:=1; end; end; end; function i2cmem_chip.save_snapshot(data_dest:pbyte):word; var temp:pbyte; buffer:array[0..23] of byte; begin temp:=data_dest; copymemory(temp,@page,16); inc(temp,16); copymemory(temp,@data,$8000); inc(temp,$8000); buffer[0]:=byte(wc); buffer[1]:=byte(devsel_address_low); copymemory(@buffer[2],@byteaddr,2); copymemory(@buffer[4],@data_size,2); copymemory(@buffer[6],@address_mask,2); buffer[8]:=page_written_size; buffer[9]:=page_offset; buffer[10]:=addresshigh; buffer[11]:=write_page_size; buffer[12]:=slave_address; buffer[13]:=devsel; buffer[14]:=scl; buffer[15]:=sdaw; buffer[16]:=shift; buffer[17]:=bits; buffer[18]:=state; buffer[19]:=sdar; buffer[20]:=e0; buffer[21]:=e1; buffer[22]:=e2; buffer[23]:=read_page_size; copymemory(temp,@buffer[0],24); save_snapshot:=16+$8000+24; end; procedure i2cmem_chip.load_snapshot(data_dest:pbyte); var temp:pbyte; buffer:array[0..23] of byte; begin temp:=data_dest; copymemory(@page,temp,16); inc(temp,16); copymemory(@data,temp,$8000); inc(temp,$8000); copymemory(@buffer,temp,24); wc:=buffer[0]<>0; devsel_address_low:=buffer[1]<>0; copymemory(@byteaddr,@buffer[2],2); copymemory(@data_size,@buffer[4],2); copymemory(@address_mask,@buffer[6],2); page_written_size:=buffer[8]; page_offset:=buffer[9]; addresshigh:=buffer[10]; write_page_size:=buffer[11]; slave_address:=buffer[12]; devsel:=buffer[13]; scl:=buffer[14]; sdaw:=buffer[15]; shift:=buffer[16]; bits:=buffer[17]; state:=buffer[18]; sdar:=buffer[19]; e0:=buffer[20]; e1:=buffer[21]; e2:=buffer[22]; read_page_size:=buffer[23]; end; end.
unit ProvMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, dxTL, dxDBCtrl, DB, DBClient, dxCntner, dxDBTL, ExtCtrls, ComCtrls, xmldom, Provider, Xmlxform, Grids, DBGrids, dxBar, ActnList, Menus, ActnMan, ToolWin, ActnCtrls, ActnMenus, XPStyleActnCtrls, ssActionMainMenuBar, SConnect, ssSocketConnection, ssClientDataSet, dxExEdtr, dxInspct, dxInspRw, StdCtrls, cxLookAndFeelPainters, cxButtons { RXSplit, mwCustomEdit, mwHighlighter, wmSQLSyn, Placemnt, ssFormStorage, ActnPopupCtrl, } ; type TxServers = class private FList: TList; FIndex: integer; public constructor Create; Destructor Destroy; override; function Add(const AHost: string): TssSocketConnection; procedure Delete(const AHost: string); function ServerByName(const AHost: string): TssSocketConnection; end; TfrmProvMain = class(TForm) //edProv: TmwCustomEdit; { btnApply: TdxBarButton; btnDelDB: TdxBarButton; btnDelete: TdxBarButton; btnNewDB: TdxBarButton; btnNewGroup: TdxBarButton; btnProvNew: TdxBarButton; btnRefresh: TdxBarButton; btnUndo: TdxBarButton; btnUp: TdxBarButton; BarManager: TdxBarManager; } panLeft: TPanel; panRight: TPanel; srcGroups: TDataSource; Images: TImageList; //wmSQLSyn1: TwmSQLSyn; tlMain: TTreeView; ActionList1: TActionList; aDelete: TAction; Panel1: TPanel; pcMain: TPageControl; tsProvText: TTabSheet; tsView: TTabSheet; lvMain: TListView; LargeImages: TImageList; cdsText: TClientDataSet; aUp: TAction; aRefresh: TAction; pmView: TPopupMenu; mnuLargeIcons: TMenuItem; mnuSmallIcons: TMenuItem; mnuList: TMenuItem; mnuTable: TMenuItem; cdsGroups: TClientDataSet; amMain: TActionManager; aExit: TAction; splMain: TSplitter; barMainMenu: TssActionMainMenuBar; aScan: TAction; aConnect: TAction; aDisconnect: TAction; tsDBInfo: TTabSheet; inspDB: TdxInspector; irDB: TdxInspectorTextRow; irParams: TdxInspectorTextRow; irPath: TdxInspectorTextButtonRow; aNewDB: TAction; sbMain: TStatusBar; aUndo: TAction; aApply: TAction; irDef: TdxInspectorTextPickRow; cdsDB: TClientDataSet; aDelDB: TAction; pmTree: TPopupMenu; mnuNewDB: TMenuItem; mnuDelDB: TMenuItem; sepDB: TMenuItem; mnuScan: TMenuItem; mnuConnect: TMenuItem; mnuDisconnect: TMenuItem; test1: TMenuItem; test2: TMenuItem; sepProv: TMenuItem; aNewGroup: TAction; aNewProv: TAction; aDelProv: TAction; mnuDelProv: TMenuItem; edProv: TMemo; FindDialog1: TFindDialog; aFind: TAction; aFindNext: TAction; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure tlMainExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure tlMainCollapsed(Sender: TObject; Node: TTreeNode); procedure tlMainExpanded(Sender: TObject; Node: TTreeNode); procedure tlMainEdited(Sender: TObject; Node: TTreeNode; var S: String); procedure aNewProvExecute(Sender: TObject); procedure aNewGroupExecute(Sender: TObject); procedure cdsGroupsAfterOpen(DataSet: TDataSet); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure tlMainChange(Sender: TObject; Node: TTreeNode); procedure lvMainDblClick(Sender: TObject); procedure aApplyExecute(Sender: TObject); procedure edProvChange(Sender: TObject); procedure aUpExecute(Sender: TObject); procedure aRefreshExecute(Sender: TObject); procedure tlMainChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure mnuLargeIconsClick(Sender: TObject); procedure mnuSmallIconsClick(Sender: TObject); procedure mnuListClick(Sender: TObject); procedure mnuTableClick(Sender: TObject); procedure cdsTextAfterOpen(DataSet: TDataSet); { procedure FormStorageStoredValues0Save(Sender: TStoredValue; var Value: Variant); procedure FormStorageStoredValues0Restore(Sender: TStoredValue; var Value: Variant); } procedure tlMainEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean); procedure aExitExecute(Sender: TObject); procedure aScanExecute(Sender: TObject); procedure tlMainMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pmTreePopup(Sender: TObject); procedure aConnectExecute(Sender: TObject); procedure aDisconnectExecute(Sender: TObject); procedure cdsGroupsBeforeOpen(DataSet: TDataSet); procedure irDBDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); procedure inspDBDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); procedure tsDBInfoShow(Sender: TObject); procedure FormResize(Sender: TObject); procedure irParamsDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); procedure irDBChange(Sender: TObject); procedure irPathChange(Sender: TObject); procedure irPathButtonClick(Sender: TObject; AbsoluteIndex: Integer); procedure amMainUpdate(Action: TBasicAction; var Handled: Boolean); procedure aNewDBExecute(Sender: TObject); procedure aUndoExecute(Sender: TObject); procedure tlMainGetImageIndex(Sender: TObject; Node: TTreeNode); procedure aDelDBExecute(Sender: TObject); procedure aDelProvExecute(Sender: TObject); procedure mnuDelProvClick(Sender: TObject); procedure mnuConnectClick(Sender: TObject); procedure mnuDisconnectClick(Sender: TObject); procedure aFindExecute(Sender: TObject); procedure FindDialog1Find(Sender: TObject); private CurrText: string; FHostsList: TStringList; NeedToScan: boolean; PopupNode: TTreeNode; FServers: TxServers; FServerNode: TTreeNode; FDBNameModified, FNewDBAdded, FDBParamsModified, FSQLModified: boolean; FDeleting: boolean; FNewNode, FLastFoundNode: TTreeNode; FChangeNode_: boolean; procedure RefreshTree(const AID: integer); procedure RefreshDBInfo; function AddNewDB: boolean; procedure TreeLocate(const AID: integer); procedure GetLevel(ANode: TTreeNode); procedure ReloadView(ANode: TTreeNode); procedure LoadProvText(const AID: integer); procedure SortByObj(AList: TStringList); procedure SaveProvText; procedure SaveDBName; procedure SaveDBParams; function GetDBParams: string; function TestConn(const AHost: string): boolean; procedure LoadHostsFromRegistry; procedure SaveHostsToRegistry; procedure CheckRegistry; procedure ScanNetwork; function ConnectToServer(const AHost: string): boolean; procedure DisconnectFromServer(const AHost: string); function GetServerNode(ANode: TTreeNode): TTreeNode; procedure EraseStateIndexes; procedure SelectPopupNode; function DoFind(Anode: TTreeNode): Boolean; end; var frmProvMain: TfrmProvMain; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses xFun, xNetUtils, xStrUtils, ActiveX, ssServer_TLB, MConnect, ComObj, Registry, ssaConst, strUtils; {$R *.dfm} //============================================================================================== procedure TfrmProvMain.FormCreate(Sender: TObject); begin //FormStorage.Active := True; FServers := TxServers.Create; FHostsList := TStringList.Create; CheckRegistry; LoadHostsFromRegistry; //cdsGroups.Open; //DSRefresh(cdsGroups, 'id', 0); RefreshTree(0); FSQLModified := False; FDBParamsModified := False; end; //============================================================================================== procedure TfrmProvMain.FormDestroy(Sender: TObject); begin cdsGroups.Close; FServers.Free; FHostsList.Free; end; //============================================================================================== procedure TfrmProvMain.RefreshTree(const AID: integer); begin GetLevel(nil); //TreeLocate(AID); end; //============================================================================================== procedure TfrmProvMain.GetLevel(ANode: TTreeNode); var FNode: TTreeNode; BM: TBookmark; FPType: integer; i: integer; begin if ANode <> nil then FServerNode := GetServerNode(ANode); BM := cdsGroups.GetBookmark; try if ANode <> nil then ANode.DeleteChildren else tlMain.Items.Clear; if ANode = nil then begin FNode := tlMain.Items.AddObject(nil, 'Сервера', pointer(-1)); tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 17; FNode.SelectedIndex := 17; FNode.StateIndex := 0; end else begin FPType := Integer(ANode.Data); case FPType of -1: begin if NeedToScan then ScanNetwork; for i := 0 to FHostsList.Count - 1 do begin FNode := tlMain.Items.AddChildObject(ANode, DelChars(FHostsList[i], '\'), pointer(-2)); tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 16; FNode.SelectedIndex := 16; end; end; -2: begin if not ConnectToServer(ANode.Text) then begin MessageDlg('Error connecting to server ' + ANode.Text + '!', mtError, [mbOk], 0); Exit; end; ANode.SelectedIndex := 15; ANode.ImageIndex := 15; FNode := tlMain.Items.AddChildObject(ANode, 'Базы данных', pointer(-3)); tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 20; FNode.SelectedIndex := 20; FNode := tlMain.Items.AddChildObject(ANode, 'Провайдеры', pointer(-4)); tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 23; FNode.SelectedIndex := 23; FNode := tlMain.Items.AddChildObject(ANode, 'Пользователи', pointer(-5)); tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 21; FNode.SelectedIndex := 21; end; -4: begin // providers if cdsGroups.Active = False then begin cdsGroups.Open; DSRefresh(cdsGroups, 'id', 0); end; cdsGroups.First; while not cdsGroups.Eof do begin if (Integer(ANode.Data) = -4) and (cdsGroups.fieldbyname('id').AsInteger = cdsGroups.FieldByName('pid').AsInteger) then begin FNode := tlMain.Items.AddChildObject(ANode, cdsGroups.fieldbyname('name').AsString, pointer(cdsGroups.fieldbyname('id').AsInteger)); if cdsGroups.fieldbyname('isgroup').AsInteger = 1 then begin tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 12; FNode.SelectedIndex := 12; end else FNode.ImageIndex := 0; end; cdsGroups.Next; end; end; // -4 - providers -3: begin // databases if cdsDB.Active then cdsDB.Close; cdsDB.RemoteServer := FServers.ServerByName(FServerNode.Text); cdsDB.Open; while not cdsDB.Eof do begin FNode := tlMain.Items.AddChildObject(ANode, cdsDB.fieldbyname('desc').AsString, pointer(cdsDB.fieldbyname('dbid').AsInteger)); if cdsDB.FieldByName('def').AsInteger = 0 then begin FNode.ImageIndex := 24; FNode.SelectedIndex := 24; end else begin FNode.ImageIndex := 27; FNode.SelectedIndex := 27; end; cdsDb.Next; end; cdsDb.Close; end // case -3 - databases else begin// case if (Integer(ANode.Data) > 0) then begin cdsGroups.First; while not cdsGroups.Eof do begin if (Integer(ANode.Data) > 0) and (cdsGroups.fieldbyname('id').AsInteger <> Integer(ANode.Data)) and (cdsGroups.fieldbyname('pid').AsInteger = Integer(ANode.Data)) then begin FNode := tlMain.Items.AddChildObject(ANode, cdsGroups.fieldbyname('name').AsString, pointer(cdsGroups.fieldbyname('id').AsInteger)); if cdsGroups.fieldbyname('isgroup').AsInteger = 1 then begin tlMain.Items.AddChild(FNode, ''); FNode.ImageIndex := 12; FNode.SelectedIndex := 12; end else FNode.ImageIndex := 0; end; cdsGroups.Next; end; // while not cdsGroups.Eof end; // if (Integer(ANode.Data)>0) end; // case else end; // case FPType of end; // if ANode = nil else cdsGroups.GotoBookmark(BM); finally cdsGroups.FreeBookmark(BM); end; end; //============================================================================================== procedure TfrmProvMain.tlMainExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); begin if Node.Item[0].Text = '' then GetLevel(Node); tlMain.AlphaSort(True); tlMain.SortType := stText; if tlMain.Selected = FServerNode then tlMainChange(tlMain, FServerNode); end; //============================================================================================== procedure TfrmProvMain.tlMainCollapsed(Sender: TObject; Node: TTreeNode); begin //Node.ImageIndex := 12; //Node.SelectedIndex := 12; end; //============================================================================================== procedure TfrmProvMain.tlMainExpanded(Sender: TObject; Node: TTreeNode); begin //Node.ImageIndex := 13; //Node.SelectedIndex := 13; end; //============================================================================================== procedure TfrmProvMain.tlMainEdited(Sender: TObject; Node: TTreeNode; var S: String); var pid, res: integer; begin Node.Text := S; if Integer(Node.Parent.Data) = -3 then begin if mrYes <> MessageDlg('Переименовать базу данных <' + CurrText + '> в <' + S + '>?', mtConfirmation, [mbYes, mbNo], 0) then begin S := CurrText; Exit; end else begin irDB.EditText := S; FDBNameModified := True; aApply.Execute; end; end else if (Integer(Node.Parent.Data) = -4) or (Integer(Node.Parent.Data) > 0) then begin if Integer(Node.Parent.Data) = -4 then pid := Integer(Node.Data) else pid := Integer(Node.Parent.Data); res := FServers.ServerByName(FServerNode.Text).AppServer.AddProvider(Integer(Node.Data), S, pid, -1, 0); case res of -1: MessageDlg('Could not modify provider or group!', mtError, [mbOk], 0); -2: MessageDlg('Provider with this name already exist!', mtError, [mbOk], 0); 0: DSRefresh(cdsGroups, 'id', 0); end; if res < 0 then S := CurrText; end; end; //============================================================================================== procedure TfrmProvMain.aNewProvExecute(Sender: TObject); var maxx, pid, res: integer; FNode: TTreeNode; begin maxx := FServers.ServerByName(FServerNode.Text).AppServer.GetMaxProvID+1; if Integer(PopupNode.Data) = -4 then pid := maxx else if (PopupNode.ImageIndex = 0) then if Integer(PopupNode.Parent.Data) <> -4 then pid := Integer(PopupNode.Parent.Data) else pid := maxx; res := FServers.ServerByName(FServerNode.Text).AppServer.AddProvider(maxx, 'New Provider', pid, 0, 1); if res < 0 then begin case res of -1:MessageDlg('Could not add provider!', mtError, [mbOk], 0); -2:MessageDlg('Provider with this name already exist!', mtError, [mbOk], 0); end; end else begin if Integer(PopupNode.Data) = -4 then FNode := tlMain.Items.AddChildObject(PopupNode, 'New Provider', pointer(maxx)) else if PopupNode.ImageIndex = 0 then FNode := tlMain.Items.AddChildObject(PopupNode.Parent, 'New Provider', pointer(maxx)) else FNode := tlMain.Items.AddChildObject(PopupNode, 'New Provider', pointer(maxx)); FNode.ImageIndex := 0; FNode.SelectedIndex := 0; DSRefresh(cdsGroups, 'id', 0); tlMain.Selected := FNode; FNode.EditText; end; end; //============================================================================================== procedure TfrmProvMain.aNewGroupExecute(Sender: TObject); var FNode: TTreeNode; maxx, pid: integer; begin maxx := FServers.ServerByName(FServerNode.Text).AppServer.GetMaxProvID+1; if Integer(PopupNode.Data)<0 then pid := maxx else if (PopupNode.ImageIndex=0) then if Integer(PopupNode.Parent.Data)<>-4 then pid := Integer(PopupNode.Parent.Data) else pid := maxx; if FServers.ServerByName(FServerNode.Text).AppServer.AddProvider(maxx, 'New Group', pid, 1, 1)<0 then begin MessageDlg('Could not add group!', mtError, [mbOk], 0); end else begin if Integer(PopupNode.Data)=-4 then FNode := tlMain.Items.AddChildObject(PopupNode, 'New Group', pointer(maxx)) else if tlMain.Selected.ImageIndex=0 then FNode := tlMain.Items.AddChildObject(PopupNode.Parent, 'New Group', pointer(maxx)) else FNode := tlMain.Items.AddChildObject(PopupNode, 'New Group', pointer(maxx)); FNode.ImageIndex := 12; FNode.SelectedIndex := 13; DSRefresh(cdsGroups, 'id', 0); tlMain.Items.AddChild(FNode, ''); tlMain.Selected := FNode; FNode.EditText; end; end; //============================================================================================== procedure TfrmProvMain.cdsGroupsAfterOpen(DataSet: TDataSet); begin cdsGroups.LogChanges := False; if cdsText.Active then cdsText.Close; cdsText.Open; end; //============================================================================================== procedure TfrmProvMain.ActionList1Update(Action: TBasicAction; var Handled: Boolean); var id_: integer; begin if tlMain.Selected <> nil then id_ := Integer(tlMain.Selected.Data) else id_ := 0; aNewProv.Enabled := True; aNewGroup.Enabled := aNewProv.Enabled; aUp.Enabled := (tlMain.Selected<>nil) and (tlMain.Selected.Level<>0); end; //============================================================================================== procedure TfrmProvMain.tlMainChange(Sender: TObject; Node: TTreeNode); var id_: integer; begin id_ := Integer(Node.Data); if (Integer(Node.Data) <> -1) and (Integer(Node.Data) <> -2) and (Node.Count = 1) and (Node.Item[0].Text = '') then GetLevel(Node); case id_ of -1: begin FServerNode := nil; pcMain.ActivePage := tsView; ReloadView(Node); end; -2: begin FServerNode := GetServerNode(Node); pcMain.ActivePage := tsView; ReloadView(Node); end; -3, -4: begin FServerNode := GetServerNode(Node); pcMain.ActivePage := tsView; ReloadView(Node); end else begin if (Integer(Node.Data) > 0) and (Integer(Node.Parent.Data) = -3) then begin FServerNode := GetServerNode(Node); pcMain.ActivePage := tsDBInfo; RefreshDBInfo; end else if Integer(Node.Data) > 0 then begin if cdsGroups.Locate('id', id_, []) then begin if cdsGroups.FieldByName('isgroup').AsInteger = 1 then begin pcMain.ActivePage := tsView; ReloadView(Node); end else begin pcMain.ActivePage := tsProvText; LoadProvText(id_); end; end; end; // if (Integer(Node.Data)>0) and (Integer(Node.Parent.Data)=-3) end; // case else end; // case tlMain.AlphaSort(True); end; //============================================================================================== procedure TfrmProvMain.ReloadView(ANode: TTreeNode); var i: integer; li: TListItem; begin lvMain.Clear; if (ANode.Level = 0) and (ANode.Count > 0) and (ANode.Item[0].Text = '') and (FHostsList.Count > 0) then GetLevel(ANode); if (ANode = FServerNode) and (ANode.Item[0].Text = '') then begin li := lvMain.Items.Add; li.Caption := aConnect.Caption; li.ImageIndex := aConnect.ImageIndex; end else with lvMain do begin if (ANode.Count = 1) and (ANode.Item[0].Text = '') then Exit; for i := 0 to ANode.Count - 1 do begin li := Items.Add; li.Caption := ANode.Item[i].Text; li.ImageIndex := ANode.Item[i].ImageIndex; li.Data := ANode.Item[i]; end; end; end; //============================================================================================== procedure TfrmProvMain.lvMainDblClick(Sender: TObject); begin if (lvMain.Selected <> nil) then begin if lvMain.Selected.ImageIndex = aConnect.ImageIndex then begin GetLevel(FServerNode); FServerNode.Expand(False); tlMainChange(tlMain, FServerNode); end else begin tlMain.Selected := lvMain.Selected.Data; tlMain.Selected.Expand(False); end; end; end; //============================================================================================== procedure TfrmProvMain.LoadProvText(const AID: integer); begin edProv.Text := FServers.ServerByName(FServerNode.Text).AppServer.GetProvText(AID); FSQLModified := False; end; //============================================================================================== procedure TfrmProvMain.SortByObj(AList: TStringList); var i: integer; f: boolean; begin f := true; while f do begin f := false; for i := 0 to AList.Count-2 do if Integer(AList.Objects[i]) > Integer(AList.Objects[i+1]) then begin f := True; AList.Exchange(i, i+1); end; end; end; //============================================================================================== procedure TfrmProvMain.aApplyExecute(Sender: TObject); begin inspDB.Perform(CM_EXIT, 0, 0); if FSQLModified then begin SaveProvText; FSQLModified := False; end; if FNewDBAdded then begin if AddNewDB then FNewDBAdded := False else Exit; end else begin if FDBNameModified then begin SaveDBName; FDBNameModified := False; end; if FDBParamsModified then begin SaveDBParams; FDBParamsModified := False; end; end; EraseStateIndexes; end; //============================================================================================== procedure TfrmProvMain.edProvChange(Sender: TObject); begin FSQLModified := True; end; //============================================================================================== procedure TfrmProvMain.aUpExecute(Sender: TObject); begin if tlMain.Selected.Level <> 0 then tlMain.Selected := tlMain.Selected.Parent; end; //============================================================================================== procedure TfrmProvMain.aRefreshExecute(Sender: TObject); begin DSRefresh(cdsGroups, 'id', 0); if tlMain.Selected<>nil then RefreshTree(Integer(tlMain.Selected.Data)) else RefreshTree(0); end; //============================================================================================== procedure TfrmProvMain.tlMainChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin if aApply.Enabled and not FDeleting then begin if FSQLModified and (MessageDlg('Текст провайдера был изменён! Сохранить?', mtWarning, [mbYes, mbNo], 0)=mrYes) then aApply.Execute; if FNewDBAdded then if (MessageDlg('Была добавлена новая база данных! Сохранить?', mtWarning, [mbYes, mbNo], 0)<>mrYes) then aUndo.Execute else aApply.Execute; if FDBNameModified or FDBParamsModified then if (MessageDlg('Параметры базы данных были изменены! Сохранить?', mtWarning, [mbYes, mbNo], 0)<>mrYes) then aUndo.Execute else aApply.Execute; end; end; //============================================================================================== procedure TfrmProvMain.SaveProvText; begin if -1 = FServers.ServerByName(FServerNode.Text).AppServer.ModifyProvText(Integer(tlMain.Selected.Data), edProv.Text) then MessageDlg('Could not modify provider text!', mtError, [mbOk], 0); end; //============================================================================================== procedure TfrmProvMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var a: boolean; begin tlMainChanging(tlMain, tlMain.Selected, a); end; //============================================================================================== procedure TfrmProvMain.mnuLargeIconsClick(Sender: TObject); begin lvMain.ViewStyle := vsIcon; mnuLargeIcons.Checked := True; end; //============================================================================================== procedure TfrmProvMain.mnuSmallIconsClick(Sender: TObject); begin lvMain.ViewStyle := vsSmallIcon; mnuSmallIcons.Checked := True; end; //============================================================================================== procedure TfrmProvMain.mnuListClick(Sender: TObject); begin lvMain.ViewStyle := vsList; mnuList.Checked := True; end; //============================================================================================== procedure TfrmProvMain.mnuTableClick(Sender: TObject); begin lvMain.ViewStyle := vsReport; mnuTable.Checked := True; end; //============================================================================================== procedure TfrmProvMain.TreeLocate(const AID: integer); var i: integer; function TreeChildLocate(ANode: TTreeNode; const AID: integer): boolean; var i: integer; begin Result := False; for i := 0 to ANode.Count-1 do if Integer(ANode.Item[i].Data)=AID then begin ANode.Expand(False); Result := True; Exit; end else if TreeChildLocate(ANode.Item[i], AID) then Exit; ANode.Collapse(False); end; begin for i := 0 to tlMain.Items.Count - 1 do begin if 0 = tlMain.Items.Item[i].Level then begin if AID = Integer(tlMain.Items.Item[i].Data) then begin tlMain.Selected := tlMain.Items.Item[i]; Exit; end else if TreeChildLocate(tlMain.Items[i], AID) then Exit;//tlMain.Items[i].Expand(False); end; end; end; //============================================================================================== procedure TfrmProvMain.cdsTextAfterOpen(DataSet: TDataSet); begin cdsText.LogChanges := False; end; //============================================================================================== {procedure TfrmProvMain.FormStorageStoredValues0Save(Sender: TStoredValue; var Value: Variant); begin case lvMain.ViewStyle of vsSmallIcon: Value := 0; vsIcon : Value := 1; vsList : Value := 2; vsReport : Value := 3; end; end; //============================================================================================== procedure TfrmProvMain.FormStorageStoredValues0Restore(Sender: TStoredValue; var Value: Variant); begin if Value <> EmptyStr then case Value of 0:begin lvMain.ViewStyle := vsSmallIcon; mnuSmallIcons.Checked := True; end; 1:begin lvMain.ViewStyle := vsIcon; mnuLargeIcons.Checked := True; end; 2:begin lvMain.ViewStyle := vsList; mnuList.Checked := True; end; 3:begin lvMain.ViewStyle := vsReport; mnuTable.Checked := True; end; end; end; } //============================================================================================== procedure TfrmProvMain.tlMainEditing(Sender: TObject; Node: TTreeNode; var AllowEdit: Boolean); begin AllowEdit := Integer(Node.Data)>0; if not AllowEdit then Exit; CurrText := Node.Text; end; //============================================================================================== procedure TfrmProvMain.aExitExecute(Sender: TObject); begin Close; end; //============================================================================================== function TfrmProvMain.TestConn(const AHost: string): boolean; begin Result := False; with TssSocketConnection.Create(nil) do try try Host := DelChars(AHost, '\'); LoginPrompt := False; DBID := -1; ServerGUID := GUIDToString(CLASS_ssSrv); Open; Close; Result := True; finally Free; end; except end; end; //============================================================================================== procedure TfrmProvMain.LoadHostsFromRegistry; var h: string; begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if OpenKey(RegKey, False) then begin h := ReadString('Hosts'); CloseKey; if h <> '' then StrToList(h, FHostsList, [';']) else NeedToScan := True; end; finally Free; end; end; //============================================================================================== procedure TfrmProvMain.CheckRegistry; begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if not KeyExists(RegKey) then CreateKey(RegKey); finally Free; end; end; //============================================================================================== procedure TfrmProvMain.ScanNetwork; var FHosts: TStringList; i: integer; begin Screen.Cursor := crHourGlass; FHostsList.Clear; FHosts := GetNetHosts; try for i := 0 to FHosts.Count-1 do if TestConn(FHosts[i]) then FHostsList.Add(FHosts[i]); SaveHostsToRegistry; NeedToScan := False; tlMainChange(tlMain, FServerNode); finally Screen.Cursor := crDefault; FHosts.Free; end; end; //============================================================================================== procedure TfrmProvMain.SaveHostsToRegistry; var h: string; begin with TRegistry.Create do try RootKey := HKEY_CURRENT_USER; if OpenKey(RegKey, False) then begin h := ListToStr(FHostsList, ';'); WriteString('Hosts', h); CloseKey; end else CreateKey(RegKey); finally Free; end; end; //============================================================================================== procedure TfrmProvMain.aScanExecute(Sender: TObject); begin if PopupNode<>nil then tlMain.Selected := PopupNode; ScanNetwork; tlMain.Selected.Expand(False); //GetLevel(tlMain.Selected); end; //============================================================================================== procedure TfrmProvMain.tlMainMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var FPos: TPoint; begin if Button=mbRight then begin PopupNode := tlMain.GetNodeAt(X, Y); FPos := tlMain.ClientToScreen(Point(X, Y)); pmTree.Popup(FPos.X, FPos.Y); end; end; //============================================================================================== procedure TfrmProvMain.pmTreePopup(Sender: TObject); var FNode: TTreeNode; h: boolean; begin mnuScan.Visible := (PopupNode<>nil) and (Integer(PopupNode.Data)=-1); if (PopupNode <> nil) then FNode := GetServerNode(PopupNode) else FNode := nil; mnuConnect.Visible := (PopupNode<>nil) and (FNode<>nil) and (FNode.ImageIndex=16); mnuDisconnect.Visible := (PopupNode<>nil) and (FNode<>nil) and (FNode.ImageIndex=15); amMainUpdate(aDelDB, h); end; //============================================================================================== procedure TfrmProvMain.aConnectExecute(Sender: TObject); begin with FServerNode do begin ConnectToServer(Text); ImageIndex := 15; SelectedIndex := 15; Expand(False); tlMainChange(tlMain, FServerNode); end; end; //============================================================================================== procedure TfrmProvMain.aDisconnectExecute(Sender: TObject); begin DisconnectFromServer(FServerNode.Text); tlMainChange(tlMain, FServerNode); end; //============================================================================================== function TfrmProvMain.ConnectToServer(const AHost: string): boolean; var Conn: TssSocketConnection; begin Screen.Cursor := crHourGlass; try Result := False; Conn := FServers.ServerByName(AHost); if Conn = nil then Conn := FServers.Add(AHost); if Conn <> nil then begin if Conn.Connected then Conn.Connected := False; try Conn.Connected := True; Result := True; except Exit; end; end; finally Screen.Cursor := crDefault; end; end; { TServers } //============================================================================================== function TxServers.Add(const AHost: string): TssSocketConnection; var Conn: TssSocketConnection; begin Result := nil; if ServerByName(AHost)=nil then begin Conn := TssSocketConnection.Create(nil); with Conn do begin Host := AHost; DBConnectAtOnce := False; ServerGUID := GUIDToString(CLASS_ssSrv); LoginPrompt := False; end; FList.Add(Conn); Result := Conn; end; end; //============================================================================================== constructor TxServers.Create; begin inherited; FList := TList.Create; end; //============================================================================================== procedure TxServers.Delete(const AHost: string); var Conn: TssSocketConnection; begin Conn := ServerByName(AHost); if Conn <> nil then begin if Conn.Connected then Conn.Connected := False; Conn.Free; FList.Delete(FIndex); end; end; //============================================================================================== destructor TxServers.Destroy; var i: integer; begin for i := 0 to FList.Count-1 do with TssSocketConnection(FList[i]) do begin if Connected then Connected := False; Free; end; FList.Free; inherited; end; //============================================================================================== function TxServers.ServerByName(const AHost: string): TssSocketConnection; var i: integer; begin Result := nil; for i := 0 to FList.Count-1 do with TssSocketConnection(FList[i]) do begin if Host = AHost then begin FIndex := i; Result := TssSocketConnection(FList[i]); Exit; end; end; end; //============================================================================================== procedure TfrmProvMain.DisconnectFromServer(const AHost: string); var Conn: TssSocketConnection; begin Conn := FServers.ServerByName(AHost); if (Conn <> nil) and Conn.Connected then Conn.Connected := False; FServerNode.SelectedIndex := 16; FServerNode.ImageIndex := 16; FServerNode.DeleteChildren; tlMain.Items.AddChild(FServerNode, ''); end; //============================================================================================== function TfrmProvMain.GetServerNode(ANode: TTreeNode): TTreeNode; begin Result := nil; if ANode.Parent = nil then Exit; if Integer(ANode.Data) = -2 then Result := ANode else Result := GetServerNode(ANode.Parent); end; //============================================================================================== procedure TfrmProvMain.cdsGroupsBeforeOpen(DataSet: TDataSet); begin cdsGroups.RemoteServer := FServers.ServerByName(FServerNode.Text); end; //============================================================================================== procedure TfrmProvMain.irDBDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); begin AFont.Style := [fsBold]; end; //============================================================================================== procedure TfrmProvMain.inspDBDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); begin AColor := clWindow; AFont.Color := clWindowText; end; //============================================================================================== procedure TfrmProvMain.tsDBInfoShow(Sender: TObject); begin //ins end; //============================================================================================== procedure TfrmProvMain.FormResize(Sender: TObject); begin if inspDB.DividerPos <> 190 then inspDB.DividerPos := 190; end; //============================================================================================== procedure TfrmProvMain.RefreshDBInfo; var FParams, FParam: string; i, j: integer; FRow: TdxInspectorRowNode; begin irDB.Text := tlMain.Selected.Text; irPath.Text := ''; if tlMain.Selected.ImageIndex = 27 then irDef.Text := 'True' else irDef.Text := 'False'; irParams.Node.DeleteChildren; FParams := FServers.ServerByName(FServerNode.Text).AppServer.GetDBParams(Integer(tlMain.Selected.Data)); for i := 1 to WordCount(FParams, [';']) do begin FParam := ExtractWord(i, FParams, [';']); if FParam <> '' then begin if LowerCase(ExtractWord(1, FParam, ['='])) = 'data source' then irPath.Text := ExtractWord(2, FParam, ['=']) else begin FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := ExtractWord(1, FParam, ['=']); TdxInspectorTextRow(FRow.Row).Text := ExtractWord(2, FParam, ['=']); FRow.Row.OnChange := irPath.OnChange; end; end; irParams.Node.Expand(False); end; FDBParamsModified := False; FDBNameModified := False; end; //============================================================================================== procedure TfrmProvMain.irParamsDrawCaption(Sender: TdxInspectorRow; ACanvas: TCanvas; ARect: TRect; var AText: String; AFont: TFont; var AColor: TColor; var ADone: Boolean); begin AFont.Style := []; end; //============================================================================================== procedure TfrmProvMain.irDBChange(Sender: TObject); begin if not FNewDBAdded then begin FDBNameModified := True; tlMain.Selected.StateIndex := 26; FServerNode.StateIndex := 26; end; end; //============================================================================================== procedure TfrmProvMain.SaveDBName; var res: integer; FDef: integer; begin if irDef.EditText = 'True' then FDef := 1 else FDef := 0; res := FServers.ServerByName(FServerNode.Text).AppServer.AddDB(Integer(tlMain.Selected.Data), irDB.EditText, FDef, 0); case res of -1: MessageDlg('Could not modify database name!', mtError, [mbOk], 0); //0: RefreshDBInfo; end; if res < 0 then begin irDB.Text := tlMain.Selected.Text; if tlMain.Selected.ImageIndex = 27 then irDef.Text := 'True' else irDef.Text := 'False'; end else begin tlMain.Selected.Text := irDB.EditText; if irDef.Text='True' then begin tlMain.Selected.ImageIndex := 27; tlMain.Selected.SelectedIndex := 27; end else begin tlMain.Selected.ImageIndex := 24; tlMain.Selected.SelectedIndex := 24; end; end; end; //============================================================================================== procedure TfrmProvMain.SaveDBParams; var DBParams: string; res: integer; begin DBParams := GetDBParams; res := FServers.ServerByName(FServerNode.Text).AppServer.AddDBParams(Integer(tlMain.Selected.Data), DBParams, 0); if res < 0 then ShowMessage('error'); FDBParamsModified := False; end; //============================================================================================== procedure TfrmProvMain.irPathChange(Sender: TObject); begin if not FNewDBAdded then begin FDBParamsModified := True; tlMain.Selected.StateIndex := 26; FServerNode.StateIndex := 26; end; end; //============================================================================================== procedure TfrmProvMain.irPathButtonClick(Sender: TObject; AbsoluteIndex: Integer); begin with TOpenDialog.Create(nil) do try DefaultExt := 'gdb'; Filter := 'Interbase Database (*.gdb)|*.gdb,*.fdb'; if Execute then begin irPath.Text := FileName; FDBParamsModified := True; end; finally Free; end; end; //============================================================================================== procedure TfrmProvMain.amMainUpdate(Action: TBasicAction; var Handled: Boolean); var FNode: TTreeNode; begin if (PopupNode<>nil) then FNode := GetServerNode(PopupNode) else FNode := nil; aApply.Enabled := FDBNameModified or FDBParamsModified or FSQLModified or FNewDBAdded; aUndo.Enabled := aApply.Enabled; aNewDB.Enabled := (PopupNode<>nil) and (FNode<>nil) and ((Integer(PopupNode.Data)=-3) or (Integer(PopupNode.Parent.Data)=-3)); mnuNewDB.Visible := aNewDB.Enabled; aDelDB.Enabled := (PopupNode<>nil) and (FNode<>nil) and (PopupNode.Parent<>nil) and (Integer(PopupNode.Parent.Data)=-3); mnuDelDB.Visible := aDelDB.Enabled; sepDB.Visible := mnuNewDB.Visible or mnuDelDB.Visible; aScan.Visible := (PopupNode<>nil) and (Integer(PopupNode.Data)=-1); aNewGroup.Visible := (PopupNode<>nil) and (FNode<>nil) and (PopupNode.Parent<>nil) and ((Integer(PopupNode.Parent.Data)=-4) or (Integer(PopupNode.Data)=-4) or (Integer(PopupNode.Parent.Data)>0)); aNewProv.Visible := aNewGroup.Visible; aDelProv.Enabled := (PopupNode<>nil) and (FNode<>nil) and (Integer(PopupNode.Parent.Data)<>-3) and ((Integer(PopupNode.Parent.Data)=-4) or (Integer(PopupNode.Data)>0)); mnuDelProv.Visible := aDelProv.Enabled; sepProv.Visible := aNewGroup.Visible or aNewProv.Visible or mnuDelProv.Visible; end; //============================================================================================== procedure TfrmProvMain.aNewDBExecute(Sender: TObject); var FNode, FDBNode: TTreeNode; FRow: TdxInspectorRowNode; begin FDBNode := PopupNode; if Integer(FDBNode.Data) <> -3 then FDBNode := FDBNode.Parent; if not FDBNode.Expanded then FDBNode.Expand(False); FNode := tlMain.Items.AddChild(FDBNode, 'New Database'); FNewNode := FNode; FNode.ImageIndex := 24; FNode.SelectedIndex := 24; FNode.StateIndex := 26; FServerNode.StateIndex := 26; pcMain.ActivePage := tsDBInfo; irDB.Text := 'New Database'; irPath.Text := ''; irDef.Text := 'False'; irParams.Node.DeleteChildren; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'PROVIDER'; TdxInspectorTextRow(FRow.Row).Text := 'LCPI.IBProvider.1'; FRow.Row.OnChange := irPath.OnChange; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'User ID'; TdxInspectorTextRow(FRow.Row).Text := 'SYSDBA'; FRow.Row.OnChange := irPath.OnChange; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'Password'; TdxInspectorTextRow(FRow.Row).Text := 'masterkey'; FRow.Row.OnChange := irPath.OnChange; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'Persist Security Info'; TdxInspectorTextRow(FRow.Row).Text := 'True'; FRow.Row.OnChange := irPath.OnChange; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'ctype'; TdxInspectorTextRow(FRow.Row).Text := 'WIN1251'; FRow.Row.OnChange := irPath.OnChange; FRow := irParams.Node.AddChildEx(TdxInspectorTextRow); FRow.Row.Caption := 'auto_commit'; TdxInspectorTextRow(FRow.Row).Text := 'True'; FRow.Row.OnChange := irPath.OnChange; irParams.Node.Expand(False); inspDB.SetFocus; inspDB.FocusedNumber := 1; inspDB.FocusedNumber := 0; tlMain.Selected := FNode; FNewDbAdded := True; //FChangeNode_ := True; end; //============================================================================================== procedure TfrmProvMain.aUndoExecute(Sender: TObject); var FNode: TTreeNode; begin FDeleting := True; if FDBNameModified then begin irDB.Text := tlMain.Selected.Text; FDBNameModified := False; end; if FNewDBAdded then begin FNode := tlMain.Selected; tlMain.Selected := tlMain.FindNextToSelect; FNode.Free; FNewDBAdded := False; end; EraseStateIndexes; FDeleting := False; end; //============================================================================================== procedure TfrmProvMain.tlMainGetImageIndex(Sender: TObject; Node: TTreeNode); begin {if FDBNameModified or FDBParamsModified then begin if (Node=FServerNode) or ((Node.Parent<>nil) and (Integer(Node.Parent.Data)=-3)) then Node.StateIndex := 26; end else Node.StateIndex := -1; } end; //============================================================================================== procedure TfrmProvMain.EraseStateIndexes; var i: integer; begin for i := 0 to tlMain.Items.Count-1 do tlMain.Items[i].StateIndex := -1; end; //============================================================================================== function TfrmProvMain.AddNewDB: boolean; var Res: integer; FDef: integer; a: boolean; begin Result := False; if irDef.Text = 'True' then FDef := 1 else FDef := 0; Application.ProcessMessages; Screen.Cursor := crHourGlass; try a := FServers.ServerByName(FServerNode.Text).AppServer.NewDB(irPath.EditText, GetDBParams); finally Screen.Cursor := crDefault; end; if not a then begin MessageDlg('Ошибка при создании файла базы данных!', mtError, [mbOk], 0); Exit; end; Res := FServers.ServerByName(FServerNode.Text).AppServer.AddDB(Integer(tlMain.Selected.Data), irDB.EditText, FDef, 1); case res of -1: MessageDlg('Невозможно создать базу данных!', mtError, [mbOk], 0); //0: RefreshDBInfo; else begin tlMain.Selected.Data := pointer(Res); SaveDBParams; tlMain.Selected.Text := irDB.Text; Result := True; end; end; end; //============================================================================================== procedure TfrmProvMain.aDelDBExecute(Sender: TObject); var Res: integer; FNode: TTreeNode; begin Res := FServers.ServerByName(FServerNode.Text).AppServer.DropDB(Integer(tlMain.Selected.Data)); case res of -1: MessageDlg('Database execution timeout!', mtError, [mbOk], 0); -2: MessageDlg('Error dropping database!', mtError, [mbOk], 0); 0: begin FNode := tlMain.Selected; tlMain.Selected := FNode.GetNext; if FNode = PopupNode then PopupNode := nil; FNode.Free; end; end; end; //============================================================================================== procedure TfrmProvMain.aDelProvExecute(Sender: TObject); begin if MessageDlg('Вы уверены?', mtWarning, [mbYes, mbNo], 0) = mrYes then begin if tlMain.Selected.Count > 0 then begin MessageDlg('Сначала удалите подчинённые провайдеры и группы!', mtError, [mbOk], 0); Exit; end; if FServers.ServerByName(FServerNode.Text).AppServer.DropProvider(Integer(tlMain.Selected.Data))=-1 then begin MessageDlg('Could not drop provider or group!', mtError, [mbOk], 0); end else begin tlMain.Items.Delete(tlMain.Selected); PopupNode := tlMain.Selected; DSRefresh(cdsGroups, 'id', 0); end; end; end; //============================================================================================== procedure TfrmProvMain.mnuDelProvClick(Sender: TObject); begin SelectPopupNode; aDelProv.Execute; end; //============================================================================================== procedure TfrmProvMain.SelectPopupNode; begin if tlMain.Selected<>PopupNode then tlMain.Selected := PopupNode; end; //============================================================================================== procedure TfrmProvMain.mnuConnectClick(Sender: TObject); begin SelectPopupNode; aConnect.Execute; end; //============================================================================================== procedure TfrmProvMain.mnuDisconnectClick(Sender: TObject); begin SelectPopupNode; aDisconnect.Execute; end; //============================================================================================== function TfrmProvMain.GetDBParams: string; var i: integer; begin Result := 'Data Source=' + irPath.EditText + ';'; for i := 0 to irParams.Node.Count - 1 do begin Result := Result + TdxInspectorTextRow(TdxInspectorRowNode(irParams.Node.Items[i]).Row).Caption + '=' + TdxInspectorTextRow(TdxInspectorRowNode(irParams.Node.Items[i]).Row).EditText+';'; end; if Result <> '' then System.Delete(Result, Length(Result), 1); end; //============================================================================================== procedure TfrmProvMain.aFindExecute(Sender: TObject); begin FindDialog1.Execute; end; //============================================================================================== function TfrmProvMain.DoFind(Anode: TTreeNode): Boolean; var n: TTreeNode; begin Result := False; if Anode = nil then exit; if Anode = FLastFoundNode then begin // finding next Result := DoFind(Anode.GetNext); Exit; end; // looking if topmost parent is provider's sub-tree root n := Anode; while n.Data <> pointer(-4) do begin n := n.Parent; if n = nil then Exit; end; n := Anode; while n <> nil do begin if not n.Expanded then n.Expand(False);// this should automatically load missing sub-providers if AnsiContainsText(n.Text, FindDialog1.FindText) then begin n.Selected := True; FLastFoundNode := n; Result := True; Exit; end; n := n.GetNext; end; Anode.Collapse(True); // nothing found here - cleaning up end; //============================================================================================== procedure TfrmProvMain.FindDialog1Find(Sender: TObject); begin DoFind(tlMain.Selected); end; end.
{ Date Created: 5/22/00 11:17:33 AM } unit InfoSRCHTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoSRCHRecord = record PLoanNumber: String[18]; PModCount: SmallInt; Pcollateralindex: String[1]; PcollateralYear: String[2]; Pdescription: String[12]; PserialNumber: String[5]; Pvin: String[17]; PShortName: String[15]; PAddress: String[30]; PPolicyString: String[15]; PCompanyAgent: String[20]; PExpirationDate: String[10]; PMatchFlags: Integer; End; TInfoSRCHBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoSRCHRecord end; TEIInfoSRCH = (InfoSRCHPrimaryKey, InfoSRCHLoanNumber, InfoSRCHDescription, InfoSRCHSerialNumPolicy, InfoSRCHPolicy, InfoSRCHByName, InfoSRCHByAddress); TInfoSRCHTable = class( TDBISAMTableAU ) private FDFLoanNumber: TStringField; FDFModCount: TSmallIntField; FDFcollateralindex: TStringField; FDFcollateralYear: TStringField; FDFdescription: TStringField; FDFserialNumber: TStringField; FDFvin: TStringField; FDFShortName: TStringField; FDFAddress: TStringField; FDFPolicyString: TStringField; FDFCompanyAgent: TStringField; FDFExpirationDate: TStringField; FDFMatchFlags: TIntegerField; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPcollateralindex(const Value: String); function GetPcollateralindex:String; procedure SetPcollateralYear(const Value: String); function GetPcollateralYear:String; procedure SetPdescription(const Value: String); function GetPdescription:String; procedure SetPserialNumber(const Value: String); function GetPserialNumber:String; procedure SetPvin(const Value: String); function GetPvin:String; procedure SetPShortName(const Value: String); function GetPShortName:String; procedure SetPAddress(const Value: String); function GetPAddress:String; procedure SetPPolicyString(const Value: String); function GetPPolicyString:String; procedure SetPCompanyAgent(const Value: String); function GetPCompanyAgent:String; procedure SetPExpirationDate(const Value: String); function GetPExpirationDate:String; procedure SetPMatchFlags(const Value: Integer); function GetPMatchFlags:Integer; procedure SetEnumIndex(Value: TEIInfoSRCH); function GetEnumIndex: TEIInfoSRCH; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoSRCHRecord; procedure StoreDataBuffer(ABuffer:TInfoSRCHRecord); property DFLoanNumber: TStringField read FDFLoanNumber; property DFModCount: TSmallIntField read FDFModCount; property DFcollateralindex: TStringField read FDFcollateralindex; property DFcollateralYear: TStringField read FDFcollateralYear; property DFdescription: TStringField read FDFdescription; property DFserialNumber: TStringField read FDFserialNumber; property DFvin: TStringField read FDFvin; property DFShortName: TStringField read FDFShortName; property DFAddress: TStringField read FDFAddress; property DFPolicyString: TStringField read FDFPolicyString; property DFCompanyAgent: TStringField read FDFCompanyAgent; property DFExpirationDate: TStringField read FDFExpirationDate; property DFMatchFlags: TIntegerField read FDFMatchFlags; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; property PModCount: SmallInt read GetPModCount write SetPModCount; property Pcollateralindex: String read GetPcollateralindex write SetPcollateralindex; property PcollateralYear: String read GetPcollateralYear write SetPcollateralYear; property Pdescription: String read GetPdescription write SetPdescription; property PserialNumber: String read GetPserialNumber write SetPserialNumber; property Pvin: String read GetPvin write SetPvin; property PShortName: String read GetPShortName write SetPShortName; property PAddress: String read GetPAddress write SetPAddress; property PPolicyString: String read GetPPolicyString write SetPPolicyString; property PCompanyAgent: String read GetPCompanyAgent write SetPCompanyAgent; property PExpirationDate: String read GetPExpirationDate write SetPExpirationDate; property PMatchFlags: Integer read GetPMatchFlags write SetPMatchFlags; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoSRCH read GetEnumIndex write SetEnumIndex; end; { TInfoSRCHTable } procedure Register; implementation procedure TInfoSRCHTable.CreateFields; begin FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFcollateralindex := CreateField( 'collateralindex' ) as TStringField; FDFcollateralYear := CreateField( 'collateralYear' ) as TStringField; FDFdescription := CreateField( 'description' ) as TStringField; FDFserialNumber := CreateField( 'serialNumber' ) as TStringField; FDFvin := CreateField( 'vin' ) as TStringField; FDFShortName := CreateField( 'ShortName' ) as TStringField; FDFAddress := CreateField( 'Address' ) as TStringField; FDFPolicyString := CreateField( 'PolicyString' ) as TStringField; FDFCompanyAgent := CreateField( 'CompanyAgent' ) as TStringField; FDFExpirationDate := CreateField( 'ExpirationDate' ) as TStringField; FDFMatchFlags := CreateField( 'MatchFlags' ) as TIntegerField; end; { TInfoSRCHTable.CreateFields } procedure TInfoSRCHTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoSRCHTable.SetActive } procedure TInfoSRCHTable.Validate; begin { Enter Validation Code Here } end; { TInfoSRCHTable.Validate } procedure TInfoSRCHTable.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TInfoSRCHTable.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TInfoSRCHTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoSRCHTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoSRCHTable.SetPcollateralindex(const Value: String); begin DFcollateralindex.Value := Value; end; function TInfoSRCHTable.GetPcollateralindex:String; begin result := DFcollateralindex.Value; end; procedure TInfoSRCHTable.SetPcollateralYear(const Value: String); begin DFcollateralYear.Value := Value; end; function TInfoSRCHTable.GetPcollateralYear:String; begin result := DFcollateralYear.Value; end; procedure TInfoSRCHTable.SetPdescription(const Value: String); begin DFdescription.Value := Value; end; function TInfoSRCHTable.GetPdescription:String; begin result := DFdescription.Value; end; procedure TInfoSRCHTable.SetPserialNumber(const Value: String); begin DFserialNumber.Value := Value; end; function TInfoSRCHTable.GetPserialNumber:String; begin result := DFserialNumber.Value; end; procedure TInfoSRCHTable.SetPvin(const Value: String); begin DFvin.Value := Value; end; function TInfoSRCHTable.GetPvin:String; begin result := DFvin.Value; end; procedure TInfoSRCHTable.SetPShortName(const Value: String); begin DFShortName.Value := Value; end; function TInfoSRCHTable.GetPShortName:String; begin result := DFShortName.Value; end; procedure TInfoSRCHTable.SetPAddress(const Value: String); begin DFAddress.Value := Value; end; function TInfoSRCHTable.GetPAddress:String; begin result := DFAddress.Value; end; procedure TInfoSRCHTable.SetPPolicyString(const Value: String); begin DFPolicyString.Value := Value; end; function TInfoSRCHTable.GetPPolicyString:String; begin result := DFPolicyString.Value; end; procedure TInfoSRCHTable.SetPCompanyAgent(const Value: String); begin DFCompanyAgent.Value := Value; end; function TInfoSRCHTable.GetPCompanyAgent:String; begin result := DFCompanyAgent.Value; end; procedure TInfoSRCHTable.SetPExpirationDate(const Value: String); begin DFExpirationDate.Value := Value; end; function TInfoSRCHTable.GetPExpirationDate:String; begin result := DFExpirationDate.Value; end; procedure TInfoSRCHTable.SetPMatchFlags(const Value: Integer); begin DFMatchFlags.Value := Value; end; function TInfoSRCHTable.GetPMatchFlags:Integer; begin result := DFMatchFlags.Value; end; procedure TInfoSRCHTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LoanNumber, String, 18, N'); Add('ModCount, SmallInt, 0, N'); Add('collateralindex, String, 1, N'); Add('collateralYear, String, 2, N'); Add('description, String, 12, N'); Add('serialNumber, String, 5, N'); Add('vin, String, 17, N'); Add('ShortName, String, 15, N'); Add('Address, String, 30, N'); Add('PolicyString, String, 15, N'); Add('CompanyAgent, String, 20, N'); Add('ExpirationDate, String, 10, N'); Add('MatchFlags, Integer, 0, N'); end; end; procedure TInfoSRCHTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LoanNumber;collateralindex, Y, Y, N, N'); Add('LoanNumber, LoanNumber;collateralindex, N, N, N, N'); Add('Description, description;collateralYear;serialNumber, N, N, Y, N'); Add('SerialNumPolicy, serialNumber;description;collateralindex, N, N, Y, N'); Add('Policy, collateralindex;PolicyString;LoanNumber, N, N, Y, N'); Add('ByName, ShortName;collateralindex, N, N, Y, N'); Add('ByAddress, Address, N, N, Y, N'); end; end; procedure TInfoSRCHTable.SetEnumIndex(Value: TEIInfoSRCH); begin case Value of InfoSRCHPrimaryKey : IndexName := ''; InfoSRCHLoanNumber : IndexName := 'LoanNumber'; InfoSRCHDescription : IndexName := 'Description'; InfoSRCHSerialNumPolicy : IndexName := 'SerialNumPolicy'; InfoSRCHPolicy : IndexName := 'Policy'; InfoSRCHByName : IndexName := 'ByName'; InfoSRCHByAddress : IndexName := 'ByAddress'; end; end; function TInfoSRCHTable.GetDataBuffer:TInfoSRCHRecord; var buf: TInfoSRCHRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLoanNumber := DFLoanNumber.Value; buf.PModCount := DFModCount.Value; buf.Pcollateralindex := DFcollateralindex.Value; buf.PcollateralYear := DFcollateralYear.Value; buf.Pdescription := DFdescription.Value; buf.PserialNumber := DFserialNumber.Value; buf.Pvin := DFvin.Value; buf.PShortName := DFShortName.Value; buf.PAddress := DFAddress.Value; buf.PPolicyString := DFPolicyString.Value; buf.PCompanyAgent := DFCompanyAgent.Value; buf.PExpirationDate := DFExpirationDate.Value; buf.PMatchFlags := DFMatchFlags.Value; result := buf; end; procedure TInfoSRCHTable.StoreDataBuffer(ABuffer:TInfoSRCHRecord); begin DFLoanNumber.Value := ABuffer.PLoanNumber; DFModCount.Value := ABuffer.PModCount; DFcollateralindex.Value := ABuffer.Pcollateralindex; DFcollateralYear.Value := ABuffer.PcollateralYear; DFdescription.Value := ABuffer.Pdescription; DFserialNumber.Value := ABuffer.PserialNumber; DFvin.Value := ABuffer.Pvin; DFShortName.Value := ABuffer.PShortName; DFAddress.Value := ABuffer.PAddress; DFPolicyString.Value := ABuffer.PPolicyString; DFCompanyAgent.Value := ABuffer.PCompanyAgent; DFExpirationDate.Value := ABuffer.PExpirationDate; DFMatchFlags.Value := ABuffer.PMatchFlags; end; function TInfoSRCHTable.GetEnumIndex: TEIInfoSRCH; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoSRCHPrimaryKey; if iname = 'LOANNUMBER' then result := InfoSRCHLoanNumber; if iname = 'DESCRIPTION' then result := InfoSRCHDescription; if iname = 'SERIALNUMPOLICY' then result := InfoSRCHSerialNumPolicy; if iname = 'POLICY' then result := InfoSRCHPolicy; if iname = 'BYNAME' then result := InfoSRCHByName; if iname = 'BYADDRESS' then result := InfoSRCHByAddress; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoSRCHTable, TInfoSRCHBuffer ] ); end; { Register } function TInfoSRCHBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLoanNumber; 2 : result := @Data.PModCount; 3 : result := @Data.Pcollateralindex; 4 : result := @Data.PcollateralYear; 5 : result := @Data.Pdescription; 6 : result := @Data.PserialNumber; 7 : result := @Data.Pvin; 8 : result := @Data.PShortName; 9 : result := @Data.PAddress; 10 : result := @Data.PPolicyString; 11 : result := @Data.PCompanyAgent; 12 : result := @Data.PExpirationDate; 13 : result := @Data.PMatchFlags; end; end; end. { InfoSRCHTable }
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.RegEx.Utils Description : Common string validations Author : Kike Pérez Version : 2.0 Created : 07/04/2021 Modified : 07/04/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.RegEx.Utils; {$i QuickLib.inc} interface uses System.SysUtils, System.RegularExpressions; type TRegExUtils = class /// <summary> Validates if value is Integer or Float number </summary> class function IsNumber(const aValue : string) : Boolean; /// <summary> Validates if value is Integer number </summary> class function IsInteger(const aValue : string) : Boolean; /// <summary> Validates if value is Float number </summary> class function IsFloat(const aValue : string) : Boolean; /// <summary> Validates if value is alphanumeric with optional space char as valid char </summary> class function IsAlphanumeric(const aValue : string; aSpaceCharAsValid : Boolean = True) : Boolean; /// <summary> Validates email address </summary> class function IsValidEmail(const aEmail : string) : Boolean; /// <summary> Validates password complexity (Should have 1 lowercase letter, 1 uppercase letter, 1 number, /// 1 special character and be at least 8 characters long) </summary> class function IsPasswordComplex(const aPassword : string) : Boolean; /// <summary> Validate username (may include _ and – with min and max length restriction) </summary> class function IsValidUsername(const aUsername: string; aMinLength : Integer = 3; aMaxLength : Integer = 18): Boolean; // <summary> Validates Url with optional protocol </summary> class function IsValidUrl(const aUrl: string; aProtocolOptional : Boolean): Boolean; // <summary> Validates Ip v4 </summary> class function IsValidIpv4(const aIp : string) : Boolean; // <summary> Validates Ip v6 </summary> class function IsValidIpv6(const aIp : string) : Boolean; // <summary> Validates date format YYYMMdd with - or . or / </summary> class function IsValidDate_YYYYMMdd(const aDate : string) : Boolean; // <summary> Validates date format ddMMYYYY with - or . or / </summary> class function IsValidDate_ddMMYYY(const aDate : string) : Boolean; // <summary> Validates Httml tag </summary> class function IsValidHtmlTag(const aValue : string) : Boolean; // <summary> Validates for duplicates in a string </summary> class function HasDuplicates(const aValue : string) : Boolean; /// <summary> Validates international number with optional country code/extension </summary> class function IsValidPhoneNumber(const aPhoneNumber : string) : Boolean; /// <summary> Validates Path, filename and extension </summary> class function IsValidFilePath(const aFilePath : string) : Boolean; /// <summary> Validates Visa card number </summary> class function IsValidVisaCard(const aCardNumber : string) : Boolean; /// <summary> Validates Master Card number </summary> class function IsValidMasterCard(const aCardNumber : string) : Boolean; /// <summary> Validates American Express card number /summary> class function IsValidAmericanExpressCard(const aCardNumber : string) : Boolean; /// <summary> Validates Passport number</summary> class function IsValidPassport(const aPassport : string) : Boolean; /// <summary> Validates Spanish Documento Nacional de Identidad </summary> class function IsValidDNI_ES(const aDNI : string) : Boolean; /// <summary> Validates USA Social Security Number document </summary> class function IsValidSSN_US(const aSSN : string) : Boolean; end; implementation { TRegExUtils } class function TRegExUtils.IsNumber(const aValue: string): Boolean; begin Result := TRegEx.IsMatch(aValue,'^(-|)\d*(\.\d+)?$'); end; class function TRegExUtils.IsFloat(const aValue: string): Boolean; begin Result := TRegEx.IsMatch(aValue,'^(-|)\d*\.\d+$'); end; class function TRegExUtils.IsInteger(const aValue: string): Boolean; begin Result := TRegEx.IsMatch(aValue,'^\d+$'); end; class function TRegExUtils.IsAlphanumeric(const aValue : string; aSpaceCharAsValid : Boolean) : Boolean; begin if aSpaceCharAsValid then Result := TRegEx.IsMatch(aValue,'^[a-zA-Z0-9 ]*$') else Result := TRegEx.IsMatch(aValue,'^[a-zA-Z0-9]*$'); end; class function TRegExUtils.IsPasswordComplex(const aPassword : string) : Boolean; begin Result := TRegEx.IsMatch(aPassword,'(?=(.*[0-9]))(?=.*[\!@#$%^&*()\\[\]{}\-_+=~`|:;"''<>,./?])(?=.*[a-z])(?=(.*[A-Z]))(?=(.*)).{8,}'); end; class function TRegExUtils.IsValidEmail(const aEmail: string): Boolean; begin Result := TRegEx.IsMatch(aEmail,'^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$'); end; class function TRegExUtils.IsValidFilePath(const aFilePath: string): Boolean; begin Result := TRegEx.IsMatch(aFilePath,'((\/|\\|\/\/|https?:\\\\|https?:\/\/)[a-z0-9_@\-^!#$%&+={}.\/\\\[\]]+)+\.[a-z]+$'); end; class function TRegExUtils.IsValidUsername(const aUsername: string; aMinLength : Integer; aMaxLength : Integer): Boolean; begin Result := TRegEx.IsMatch(aUsername,Format('^[A-Za-z0-9_-]{%d,%d}$',[aMinLength,aMaxLength])); end; class function TRegExUtils.IsValidUrl(const aUrl: string; aProtocolOptional : Boolean): Boolean; begin if aProtocolOptional then Result := TRegEx.IsMatch(aUrl,'(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)') else Result := TRegEx.IsMatch(aUrl,'https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#()?&//=]*)'); end; class function TRegExUtils.IsValidIpv4(const aIp: string): Boolean; begin Result := TRegEx.IsMatch(aIp,'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'); end; class function TRegExUtils.IsValidIpv6(const aIp: string): Boolean; begin Result := TRegEx.IsMatch(aIp,'(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]' +'{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|' +'([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}' +'(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}' +'|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)' +'|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}' +'((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9])' +'{0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.)' +'{3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))'); end; class function TRegExUtils.IsValidDate_ddMMYYY(const aDate: string): Boolean; begin Result := TRegEx.IsMatch(aDate,'^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)' + '(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-' +'|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|' +'(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)' +'(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$'); end; class function TRegExUtils.IsValidDate_YYYYMMdd(const aDate: string): Boolean; begin Result := TRegEx.IsMatch(aDate,'([12]\d{3}(\/|-|\.)(0[1-9]|1[0-2])(\/|-|\.)(0[1-9]|[12]\d|3[01]))'); end; class function TRegExUtils.IsValidHtmlTag(const aValue: string): Boolean; begin Result := TRegEx.IsMatch(aValue,'<\/?[\w\s]*>|<.+[\W]>'); end; class function TRegExUtils.HasDuplicates(const aValue: string): Boolean; begin Result := TRegEx.IsMatch(aValue,'(\b\w+\b)(?=.*\b\1\b)'); end; class function TRegExUtils.IsValidPhoneNumber(const aPhoneNumber: string): Boolean; begin Result := TRegEx.IsMatch(aPhoneNumber,'^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$'); end; class function TRegExUtils.IsValidVisaCard(const aCardNumber: string): Boolean; begin Result := TRegEx.IsMatch(aCardNumber,'^4[0-9]{12}(?:[0-9]{3})?$'); end; class function TRegExUtils.IsValidMasterCard(const aCardNumber: string): Boolean; begin Result := TRegEx.IsMatch(aCardNumber,'^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$'); end; class function TRegExUtils.IsValidAmericanExpressCard(const aCardNumber: string): Boolean; begin Result := TRegEx.IsMatch(aCardNumber,'^3[47][0-9]{13}$'); end; class function TRegExUtils.IsValidPassport(const aPassport: string): Boolean; begin Result := TRegEx.IsMatch(aPassport,'^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$'); end; class function TRegExUtils.IsValidDNI_ES(const aDNI: string): Boolean; begin Result := TRegEx.IsMatch(aDNI,'((([X-Z])|([LM])){1}([-]?)((\d){7})([-]?)([A-Z]{1}))|((\d{8})([-]?)([A-Z]))'); end; class function TRegExUtils.IsValidSSN_US(const aSSN: string): Boolean; begin Result := TRegEx.IsMatch(aSSN,'^((?!219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4})|((?!219 09 9999|078 05 1120)(?!666|000|9\d{2})\d{3} (?!00)\d{2} (?!0{4})\d{4})|((?!219099999|078051120)(?!666|000|9\d{2})\d{3}(?!00)\d{2}(?!0{4})\d{4})$'); end; end.
unit Mat.Export; interface uses Vcl.DBGrids, System.Classes, System.SysUtils; type // Class helps to export to Excel. TExportHelper = class public procedure ExportToCsv(FileName: String; SourceGrid: TDBGrid); end; var ExportHelper: TExportHelper; implementation { TExcelExportHelper } uses Mat.Constants; procedure TExportHelper.ExportToCsv(FileName: String; SourceGrid: TDBGrid); var Stream: TFileStream; i: Integer; OutLine: String; sTemp, s: String; begin Stream := TFileStream.Create(FileName, fmCreate); try s := String(SourceGrid.Fields[0].FieldName); for i := 1 to SourceGrid.FieldCount - 1 do begin s := s + ',' + string(SourceGrid.Fields[I].FieldName); end; s:= s + CRLF; Stream.Write(s[1], Length(s) * SizeOf(Char)); while not SourceGrid.DataSource.DataSet.Eof do begin // You'll need to add your special handling here where OutLine is built s := ''; OutLine := ''; for i := 0 to SourceGrid.FieldCount - 1 do begin sTemp := SourceGrid.Fields[i].AsString; // Special handling to sTemp here OutLine := OutLine + sTemp +','; end; // Remove final unnecessary ',' SetLength(OutLine, Length(OutLine) - 1); // Write line to file Stream .Write(OutLine[1], Length(OutLine) * SizeOf(Char)); // Write line ending Stream.Write(sLineBreak, Length(sLineBreak)); SourceGrid.DataSource.DataSet.Next; end; finally Stream.Free; // Saves the file end; //showmessage('Records Successfully Exported.') ; end; initialization ExportHelper := TExportHelper.Create; finalization FreeAndNil(ExportHelper); end.
unit Model.ItensManutencao; interface type TItensManutencao = class private var FID: Integer; FDescricao: String; FInsumo: Integer; FLog: String; public property ID: Integer read FID write FID; property Descricao: String read FDescricao write FDescricao; property Insumo: Integer read FInsumo write FInsumo; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFID: Integer; pFDescricao: String; pFInsumo: Integer; pFLog: String); overload; end; implementation constructor TItensManutencao.Create; begin inherited Create; end; constructor TItensManutencao.Create(pFID: Integer; pFDescricao: String; pFInsumo: Integer; pFLog: String); begin FID := pFID; FDescricao := pFDescricao; FInsumo := pFInsumo; FLog := pFLog; end; end.
unit UFrmMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DzTalkApp, Vcl.StdCtrls; type TFrmMain = class(TForm) TA: TDzTalkApp; BtnSendCmd: TButton; EdID: TEdit; Label1: TLabel; BtnSendInteger: TButton; Label2: TLabel; EdInteger: TEdit; BtnSendString: TButton; Label3: TLabel; EdString: TEdit; BtnSendDouble: TButton; Label4: TLabel; EdDouble: TEdit; BtnSendRecord: TButton; Label5: TLabel; EdRecNumber: TEdit; Label6: TLabel; EdRecText: TEdit; CkRecFlag: TCheckBox; BtnSendStream: TButton; Label7: TLabel; LbResult: TLabel; procedure BtnSendCmdClick(Sender: TObject); procedure BtnSendIntegerClick(Sender: TObject); procedure BtnSendStringClick(Sender: TObject); procedure BtnSendDoubleClick(Sender: TObject); procedure BtnSendRecordClick(Sender: TObject); procedure BtnSendStreamClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} type TRecordData = packed record Number: Integer; Text: ShortString; Flag: Boolean; end; procedure TFrmMain.BtnSendCmdClick(Sender: TObject); var ID: Word; begin ID := StrToInt(EdID.Text); if ID>1000 then raise Exception.Create('ID bigger than 1000 not allowed on this demo app'); TA.Send(ID); end; procedure TFrmMain.BtnSendIntegerClick(Sender: TObject); begin TA.Send(1001, StrToInt( EdInteger.Text ) ); end; procedure TFrmMain.BtnSendStringClick(Sender: TObject); begin TA.Send(1002, EdString.Text); end; procedure TFrmMain.BtnSendDoubleClick(Sender: TObject); var D: Double; begin D := StrToFloat(EdDouble.Text); TA.Send(1003, @D, SizeOf(D)); end; procedure TFrmMain.BtnSendRecordClick(Sender: TObject); var R: TRecordData; begin R.Number := StrToInt(EdRecNumber.Text); R.Text := ShortString(EdRecText.Text); R.Flag := CkRecFlag.Checked; TA.Send(1004, @R, SizeOf(R)); end; procedure TFrmMain.BtnSendStreamClick(Sender: TObject); procedure GetPrintScreen(var B: Vcl.Graphics.TBitmap); var DC: HDC; R: TRect; begin DC := GetDC(0); try Winapi.Windows.GetClientRect(WindowFromDC(DC), R); B.SetSize(R.Width, R.Height); BitBlt(B.Canvas.Handle, 0, 0, B.Width, B.Height, DC, 0, 0, SRCCOPY); finally ReleaseDC(0, DC); end; end; var M: TMemoryStream; B: Vcl.Graphics.TBitmap; begin M := TMemoryStream.Create; try B := TBitmap.Create; try GetPrintScreen(B); B.SaveToStream(M); finally B.Free; end; TA.Send(1005, M); finally M.Free; end; LbResult.Caption := IntToStr(TA.GetResult); end; end.
unit RSDefLod; { *********************************************************************** } { Copyright (c) Sergey Rozhenko } { http://sites.google.com/site/sergroj/ } { sergroj@mail.ru } { *********************************************************************** } {$I RSPak.inc} interface uses Windows, Classes, Messages, SysUtils, RSQ, Graphics, RSSysUtils, RSGraphics; function RSMakePalette(HeroesPal:pointer):HPalette; function RSMakeLogPalette(HeroesPal:pointer):PLogPalette; procedure RSWritePalette(HeroesPal:pointer; Pal:HPALETTE); implementation type TLogPal = packed record palVersion: word; palNumEntries: word; palPalEntry: packed array[0..255] of TPaletteEntry; end; THeroesPalEntry = packed record Red:byte; Green:byte; Blue:byte; end; THeroesPal = packed array[0..255] of THeroesPalEntry; PHeroesPal = ^THeroesPal; function RSMakePalette(HeroesPal:pointer):HPalette; var Pal:PLogPalette; begin Pal:=RSMakeLogPalette(HeroesPal); result:=RSWin32Check(CreatePalette(Pal^)); FreeMem(Pal, 4 + 256*4); end; function RSMakeLogPalette(HeroesPal:pointer):PLogPalette; var HerPal: PHeroesPal; i: int; begin GetMem(result, 4 + 256*4); HerPal:=HeroesPal; result.palVersion:=$300; result.palNumEntries:=256; for i:=0 to 255 do begin result.palPalEntry[i].peRed:= HerPal[i].Red; result.palPalEntry[i].peGreen:= HerPal[i].Green; result.palPalEntry[i].peBlue:= HerPal[i].Blue; result.palPalEntry[i].peFlags:= 0; end; end; procedure RSWritePalette(HeroesPal:pointer; Pal:HPALETTE); var HerPal: PHeroesPal; LogPal: TLogPal; i: int; begin HerPal:=HeroesPal; GetPaletteEntries(Pal, 0, 256, LogPal.palPalEntry[0]); for i:=0 to 255 do begin HerPal[i].Red:= LogPal.palPalEntry[i].peRed; HerPal[i].Green:= LogPal.palPalEntry[i].peGreen; HerPal[i].Blue:= LogPal.palPalEntry[i].peBlue; end; end; end.
unit Model.UsuariosBaseEntregador; interface uses Common.ENum, FireDAC.Comp.Client, Forms, Windows; type TUsuariosBaseEntregador = class private FAcao: TAcao; FID: Integer; FEntregador: Integer; FAgente: Integer; FUsuario: Integer; public property ID: Integer read FID write FID; property Usuario: Integer read FUsuario write FUsuario; property Agente: Integer read FAgente write FAgente; property Entregador: Integer read FEntregador write FEntregador; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; end; implementation { TUsuariosBaseEntregador } uses DAO.UsuariosBaseEntregador; function TUsuariosBaseEntregador.Gravar: Boolean; var usuarioDAO : TUsuariosBaseEntregadorDAO; begin try Result := False; usuarioDAO := TUsuariosBaseEntregadorDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := usuarioDAO.Inserir(Self); Common.ENum.tacAlterar: Result := usuarioDAO.Alterar(Self); Common.ENum.tacExcluir: Result := usuarioDAO.Excluir(Self); end; finally usuarioDAO.Free; end;end; function TUsuariosBaseEntregador.Localizar(aParam: array of variant): TFDQuery; var usuarioDAO: TUsuariosBaseEntregadorDAO; begin try usuarioDAO := TUsuariosBaseEntregadorDAO.Create(); Result := usuarioDAO.Pesquisar(aParam); finally usuarioDAO.Free; end; end; end.
unit vcmTabsHistoryService; // Модуль: "w:\common\components\gui\Garant\VCM\implementation\Visual\ChromeLike\vcmTabsHistoryService.pas" // Стереотип: "UtilityPack" // Элемент модели: "vcmTabsHistoryService" MUID: (559BA3CE0056) {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} uses l3IntfUses , l3ProtoObject , vcmHistoryService , vcmInterfaces ; type TvcmTabsHistoryService = {final} class(Tl3ProtoObject, IvcmHistoryService) private f_OrgContainer: Pointer; f_CloneContainer: Pointer; public function GetFormHistory(const aForm: IvcmEntityForm): IvcmHistory; procedure SaveFormState(const aForm: IvcmEntityForm); function GetContainerHistory(const aContainer: IvcmContainer): IvcmHistory; function IsInBF(const aForm: IvcmEntityForm): Boolean; function Back(const aForm: IvcmEntityForm): Boolean; procedure MakingCloneStarted(const aContainer: IvcmContainer); procedure ContainerForCloneMade(const aOrgContainer: IvcmContainer; const aCloneContainer: IvcmContainer); procedure MakingCloneFinished(const aContainer: IvcmContainer); function IsClone(const aContainer: IvcmContainer): Boolean; class function Instance: TvcmTabsHistoryService; {* Метод получения экземпляра синглетона TvcmTabsHistoryService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TvcmTabsHistoryService {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs)} uses l3ImplUses , l3TabbedContainersDispatcher {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , SysUtils , vcmBase , vcmFormSetHistory , l3Base //#UC START# *559BA3CE0056impl_uses* , vcmDispatcher //#UC END# *559BA3CE0056impl_uses* ; var g_TvcmTabsHistoryService: TvcmTabsHistoryService = nil; {* Экземпляр синглетона TvcmTabsHistoryService } procedure TvcmTabsHistoryServiceFree; {* Метод освобождения экземпляра синглетона TvcmTabsHistoryService } begin l3Free(g_TvcmTabsHistoryService); end;//TvcmTabsHistoryServiceFree function TvcmTabsHistoryService.GetFormHistory(const aForm: IvcmEntityForm): IvcmHistory; //#UC START# *559BA1B80327_559BA3E6014C_var* var l_Form: TForm; l_Tab: Il3FormTab; l_History: IvcmHistory; l_ContainedForm: IvcmContainedForm; //#UC END# *559BA1B80327_559BA3E6014C_var* begin //#UC START# *559BA1B80327_559BA3E6014C_impl* Result := nil; if Tl3TabbedContainersDispatcher.Instance.NeedUseTabs then begin l_Form := TForm(aForm.VCLWinControl); l_Tab := Tl3TabbedContainersDispatcher.Instance.GetFormTab(l_Form); if (l_Tab <> nil) and Supports(l_Tab.TabbedForm, IvcmContainedForm, l_ContainedForm) then Result := l_ContainedForm.ContainedFormHistory; end; if (Result = nil) then Result := TvcmDispatcher.Instance.History; //#UC END# *559BA1B80327_559BA3E6014C_impl* end;//TvcmTabsHistoryService.GetFormHistory procedure TvcmTabsHistoryService.SaveFormState(const aForm: IvcmEntityForm); //#UC START# *559BA3270003_559BA3E6014C_var* var l_History: IvcmHistory; //#UC END# *559BA3270003_559BA3E6014C_var* begin //#UC START# *559BA3270003_559BA3E6014C_impl* l_History := GetFormHistory(aForm); Assert(l_History <> nil); l_History.ForceSaveState(aForm); //#UC END# *559BA3270003_559BA3E6014C_impl* end;//TvcmTabsHistoryService.SaveFormState function TvcmTabsHistoryService.GetContainerHistory(const aContainer: IvcmContainer): IvcmHistory; //#UC START# *559CAE8C0067_559BA3E6014C_var* //#UC END# *559CAE8C0067_559BA3E6014C_var* begin //#UC START# *559CAE8C0067_559BA3E6014C_impl* if Tl3TabbedContainersDispatcher.Instance.NeedUseTabs then Result := GetFormHistory(aContainer.AsForm) else Result := TvcmDispatcher.Instance.History; //#UC END# *559CAE8C0067_559BA3E6014C_impl* end;//TvcmTabsHistoryService.GetContainerHistory function TvcmTabsHistoryService.IsInBF(const aForm: IvcmEntityForm): Boolean; //#UC START# *55B8A6460123_559BA3E6014C_var* //#UC END# *55B8A6460123_559BA3E6014C_var* begin //#UC START# *55B8A6460123_559BA3E6014C_impl* Result := Tl3TabbedContainersDispatcher.Instance.IsInBF(aForm.VCLWinControl as TForm); //#UC END# *55B8A6460123_559BA3E6014C_impl* end;//TvcmTabsHistoryService.IsInBF function TvcmTabsHistoryService.Back(const aForm: IvcmEntityForm): Boolean; //#UC START# *569E01920150_559BA3E6014C_var* var l_Tab: Il3FormTab; l_TabHistory: IvcmHistory; //#UC END# *569E01920150_559BA3E6014C_var* begin //#UC START# *569E01920150_559BA3E6014C_impl* if Tl3TabbedContainersDispatcher.Instance.NeedUseTabs then begin // Если возвращаться некуда - закрываем вкладке l_Tab := Tl3TabbedContainersDispatcher.Instance.GetFormTab(TForm(aForm.VCLWinControl)); Assert(l_Tab <> nil); l_TabHistory := GetFormHistory(aForm); Assert(l_TabHistory <> nil); if l_TabHistory.CanBack then l_TabHistory.Back else Tl3TabbedContainersDispatcher.Instance.GetActiveTabbedContainer.CloseTab(l_Tab); end else Result := TvcmDispatcher.Instance.History.Back; //#UC END# *569E01920150_559BA3E6014C_impl* end;//TvcmTabsHistoryService.Back procedure TvcmTabsHistoryService.MakingCloneStarted(const aContainer: IvcmContainer); //#UC START# *57AD88650343_559BA3E6014C_var* //#UC END# *57AD88650343_559BA3E6014C_var* begin //#UC START# *57AD88650343_559BA3E6014C_impl* f_OrgContainer := Pointer(aContainer); f_CloneContainer := nil; //#UC END# *57AD88650343_559BA3E6014C_impl* end;//TvcmTabsHistoryService.MakingCloneStarted procedure TvcmTabsHistoryService.ContainerForCloneMade(const aOrgContainer: IvcmContainer; const aCloneContainer: IvcmContainer); //#UC START# *57AD88AF012D_559BA3E6014C_var* //#UC END# *57AD88AF012D_559BA3E6014C_var* begin //#UC START# *57AD88AF012D_559BA3E6014C_impl* f_CloneContainer := Pointer(aCloneContainer); //#UC END# *57AD88AF012D_559BA3E6014C_impl* end;//TvcmTabsHistoryService.ContainerForCloneMade procedure TvcmTabsHistoryService.MakingCloneFinished(const aContainer: IvcmContainer); //#UC START# *57AD88D00074_559BA3E6014C_var* //#UC END# *57AD88D00074_559BA3E6014C_var* begin //#UC START# *57AD88D00074_559BA3E6014C_impl* f_OrgContainer := Pointer(aContainer); f_CloneContainer := nil; //#UC END# *57AD88D00074_559BA3E6014C_impl* end;//TvcmTabsHistoryService.MakingCloneFinished function TvcmTabsHistoryService.IsClone(const aContainer: IvcmContainer): Boolean; //#UC START# *57AD88DC01F7_559BA3E6014C_var* //#UC END# *57AD88DC01F7_559BA3E6014C_var* begin //#UC START# *57AD88DC01F7_559BA3E6014C_impl* Result := f_CloneContainer = Pointer(aContainer); //#UC END# *57AD88DC01F7_559BA3E6014C_impl* end;//TvcmTabsHistoryService.IsClone class function TvcmTabsHistoryService.Instance: TvcmTabsHistoryService; {* Метод получения экземпляра синглетона TvcmTabsHistoryService } begin if (g_TvcmTabsHistoryService = nil) then begin l3System.AddExitProc(TvcmTabsHistoryServiceFree); g_TvcmTabsHistoryService := Create; end; Result := g_TvcmTabsHistoryService; end;//TvcmTabsHistoryService.Instance class function TvcmTabsHistoryService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TvcmTabsHistoryService <> nil; end;//TvcmTabsHistoryService.Exists initialization TvcmHistoryService.Instance.Alien := TvcmTabsHistoryService.Instance; {* Регистрация TvcmTabsHistoryService } {$IfEnd} // NOT Defined(NoVCM) AND NOT Defined(NoVGScene) AND NOT Defined(NoTabs) end.
unit register_rxctrl; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, LazarusPackageIntf, DBPropEdits, PropEdits, DB, ComponentEditors; type { TRxCollumsSortFieldsProperty } TRxCollumsSortFieldsProperty = class(TDBGridFieldProperty) public function GetAttributes: TPropertyAttributes; override; procedure Edit; override; procedure FillValues(const Values: TStringList); override; end; { TPopUpColumnFieldProperty } TPopUpColumnFieldProperty = class(TFieldProperty) public procedure FillValues(const Values: TStringList); override; end; type { THistoryButtonProperty } THistoryButtonProperty = class(TStringPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; type { TRxLoginDialogEditor } TRxLoginDialogEditor = class(TComponentEditor) public DefaultEditor: TBaseComponentEditor; constructor Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); override; destructor Destroy; override; function GetVerbCount:integer;override; function GetVerb(Index:integer):string;override; procedure ExecuteVerb(Index:integer);override; end; { TRxAppIcon } TRxAppIconEditor = class(TComponentEditor) public DefaultEditor: TBaseComponentEditor; constructor Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); override; destructor Destroy; override; function GetVerbCount:integer;override; function GetVerb(Index:integer):string;override; procedure ExecuteVerb(Index:integer);override; end; procedure Register; implementation uses RxLogin, RxAppIcon, Dialogs, rxconst, RxHistoryNavigator, rxpopupunit, rxceEditLookupFields, rxdbgrid, rxdconst, duallist, rxstrutils, Forms; resourcestring sTestTRxLoginDialog = 'Test TRxLoginDialog'; sLoadIcon = 'Load icon'; { TRxLoginDialogEditor } constructor TRxLoginDialogEditor.Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); var CompClass: TClass; begin inherited Create(AComponent, ADesigner); CompClass := PClass(Acomponent)^; try PClass(AComponent)^ := TComponent; DefaultEditor := GetComponentEditor(AComponent, ADesigner); finally PClass(AComponent)^ := CompClass; end; end; destructor TRxLoginDialogEditor.Destroy; begin DefaultEditor.Free; inherited Destroy; end; function TRxLoginDialogEditor.GetVerbCount: integer; begin Result:=DefaultEditor.GetVerbCount + 1; end; function TRxLoginDialogEditor.GetVerb(Index: integer): string; begin if Index < DefaultEditor.GetVerbCount then Result := DefaultEditor.GetVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:Result:=sTestTRxLoginDialog; end; end; end; procedure TRxLoginDialogEditor.ExecuteVerb(Index: integer); begin if Index < DefaultEditor.GetVerbCount then DefaultEditor.ExecuteVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:(Component as TRxLoginDialog).Login; end; end; end; { TRxAppIcon } type PClass = ^TClass; constructor TRxAppIconEditor.Create(AComponent: TComponent; ADesigner: TComponentEditorDesigner); var CompClass: TClass; begin inherited Create(AComponent, ADesigner); CompClass := PClass(Acomponent)^; try PClass(AComponent)^ := TComponent; DefaultEditor := GetComponentEditor(AComponent, ADesigner); finally PClass(AComponent)^ := CompClass; end; end; destructor TRxAppIconEditor.Destroy; begin DefaultEditor.Free; inherited Destroy; end; function TRxAppIconEditor.GetVerbCount: integer; begin Result:=DefaultEditor.GetVerbCount + 1; end; function TRxAppIconEditor.GetVerb(Index: integer): string; begin if Index < DefaultEditor.GetVerbCount then Result := DefaultEditor.GetVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:Result:=sLoadIcon; end; end; end; procedure TRxAppIconEditor.ExecuteVerb(Index: integer); var OpenDialog1: TOpenDialog; begin if Index < DefaultEditor.GetVerbCount then DefaultEditor.ExecuteVerb(Index) else begin case Index - DefaultEditor.GetVerbCount of 0:begin OpenDialog1:=TOpenDialog.Create(nil); OpenDialog1.Filter:=sWindowsIcoFiles; try if OpenDialog1.Execute then (Component as TRxAppIcon).LoadFromFile(OpenDialog1.FileName); finally OpenDialog1.Free; end; Modified; end; end; end; end; { THistoryButtonProperty } function THistoryButtonProperty.GetAttributes: TPropertyAttributes; begin Result:= [paValueList, paSortList, paMultiSelect]; end; procedure THistoryButtonProperty.GetValues(Proc: TGetStrProc); var I: Integer; Navigator:TRxHistoryNavigator; begin Navigator:=TRxHistoryNavigator(GetComponent(0)); if Assigned(Navigator) then begin if Assigned(Navigator.ToolPanel) then begin for i:=0 to Navigator.ToolPanel.Items.Count - 1 do begin if Assigned(Navigator.ToolPanel.Items[i].Action) then Proc(Navigator.ToolPanel.Items[i].Action.Name); end; end; end; end; { TPopUpColumnFieldProperty } procedure TPopUpColumnFieldProperty.FillValues(const Values: TStringList); var Column: TPopUpColumn; DataSource: TDataSource; begin Column:=TPopUpColumn(GetComponent(0)); if not (Column is TPopUpColumn) then exit; DataSource := TPopUpFormColumns(Column.Collection).PopUpFormOptions.DataSource; if Assigned(DataSource) and Assigned(DataSource.DataSet) then DataSource.DataSet.GetFieldNames(Values); end; { TRxCollumsSortFieldsProperty } function TRxCollumsSortFieldsProperty.GetAttributes: TPropertyAttributes; begin Result:= [paValueList, paSortList, paMultiSelect, paDialog]; end; procedure TRxCollumsSortFieldsProperty.Edit; var DualListDialog1: TDualListDialog; FCol:TRxColumn; /// FGrid:TRxDBGrid; procedure DoInitFill; var i,j:integer; LookupDisplay:string; begin LookupDisplay:=FCol.SortFields; if LookupDisplay<>'' then begin StrToStrings(LookupDisplay, DualListDialog1.List2, ';'); for i:=DualListDialog1.List1.Count-1 downto 0 do begin j:=DualListDialog1.List2.IndexOf(DualListDialog1.List1[i]); if j>=0 then DualListDialog1.List1.Delete(i); end; end; end; function DoFillDone:string; var i:integer; begin for i:=0 to DualListDialog1.List2.Count-1 do Result:=Result + DualListDialog1.List2[i]+';'; if Result<>'' then Result:=Copy(Result, 1, Length(Result)-1); end; procedure DoSetCaptions; begin DualListDialog1.Label1Caption:=sRxAllFields; DualListDialog1.Label2Caption:=sRxSortFieldsDisplay; DualListDialog1.Title:=sRxFillSortFieldsDisp; end; begin FCol:=nil; if GetComponent(0) is TRxColumn then FCol:=TRxColumn(GetComponent(0)) else exit; DualListDialog1:=TDualListDialog.Create(Application); try DoSetCaptions; FillValues(DualListDialog1.List1 as TStringList); DoInitFill; if DualListDialog1.Execute then FCol.SortFields:=DoFillDone; finally FreeAndNil(DualListDialog1); end; end; procedure TRxCollumsSortFieldsProperty.FillValues(const Values: TStringList); var Column: TRxColumn; Grid: TRxDBGrid; DataSource: TDataSource; begin Column:=TRxColumn(GetComponent(0)); if not (Column is TRxColumn) then exit; Grid:=TRxDBGrid(Column.Grid); if not (Grid is TRxDBGrid) then exit; // LoadDataSourceFields(Grid.DataSource, Values); DataSource := Grid.DataSource; if (DataSource is TDataSource) and Assigned(DataSource.DataSet) then DataSource.DataSet.GetFieldNames(Values); end; procedure Register; begin // RegisterComponentEditor(TRxLoginDialog, TRxLoginDialogEditor); RegisterComponentEditor(TRxAppIcon, TRxAppIconEditor); // RegisterPropertyEditor(TypeInfo(string), TPopUpColumn, 'FieldName', TPopUpColumnFieldProperty); RegisterPropertyEditor(TypeInfo(string), TRxHistoryNavigator, 'BackBtn', THistoryButtonProperty); RegisterPropertyEditor(TypeInfo(string), TRxHistoryNavigator, 'ForwardBtn', THistoryButtonProperty); RegisterPropertyEditor(TypeInfo(string), TRxColumn, 'SortFields', TRxCollumsSortFieldsProperty); RegisterCEEditLookupFields; // end; end.
unit RegDLL; { Inno Setup Copyright (C) 1997-2012 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Registers 32-bit/64-bit DLL-based OLE servers in a child process (regsvr32.exe) } interface uses Windows; procedure RegisterServer(const AUnregister: Boolean; const AIs64Bit: Boolean; const Filename: String; const AFailCriticalErrors: Boolean); implementation uses SysUtils, Forms, PathFunc, CmnFunc, CmnFunc2, InstFunc, Msgs, MsgIDs, Logging, RedirFunc, Main; function WaitForAndCloseProcessHandle(var AProcessHandle: THandle): DWORD; var WaitResult: DWORD; begin try repeat { Process any pending messages first because MsgWaitForMultipleObjects (called below) only returns when *new* messages arrive } Application.ProcessMessages; WaitResult := MsgWaitForMultipleObjects(1, AProcessHandle, False, INFINITE, QS_ALLINPUT); until WaitResult <> WAIT_OBJECT_0+1; if WaitResult = WAIT_FAILED then Win32ErrorMsg('MsgWaitForMultipleObjects'); if not GetExitCodeProcess(AProcessHandle, Result) then Win32ErrorMsg('GetExitCodeProcess'); finally CloseHandle(AProcessHandle); end; end; procedure RegisterServerUsingRegSvr32(const AUnregister: Boolean; const AIs64Bit: Boolean; const Filename: String); var SysDir, CmdLine: String; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; ExitCode: DWORD; begin SysDir := GetSystemDir; CmdLine := '"' + AddBackslash(SysDir) + 'regsvr32.exe"'; if AUnregister then CmdLine := CmdLine + ' /u'; CmdLine := CmdLine + ' /s "' + Filename + '"'; if AIs64Bit then Log('Spawning 64-bit RegSvr32: ' + CmdLine) else Log('Spawning 32-bit RegSvr32: ' + CmdLine); FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); if not CreateProcessRedir(AIs64Bit, nil, PChar(CmdLine), nil, nil, False, CREATE_DEFAULT_ERROR_MODE, nil, PChar(SysDir), StartupInfo, ProcessInfo) then Win32ErrorMsg('CreateProcess'); CloseHandle(ProcessInfo.hThread); ExitCode := WaitForAndCloseProcessHandle(ProcessInfo.hProcess); if ExitCode <> 0 then raise Exception.Create(FmtSetupMessage1(msgErrorRegSvr32Failed, Format('0x%x', [ExitCode]))); end; procedure RegisterServer(const AUnregister: Boolean; const AIs64Bit: Boolean; const Filename: String; const AFailCriticalErrors: Boolean); var WindowDisabler: TWindowDisabler; begin if AIs64Bit and not IsWin64 then InternalError('Cannot register 64-bit DLLs on this version of Windows'); { Disable windows so the user can't utilize our UI while the child process is running } WindowDisabler := TWindowDisabler.Create; try { On Windows Vista, to get the "WRP Mitigation" compatibility hack which a lot of DLLs a require, we must use regsvr32.exe to handle the (un)registration. On Windows 2000/XP/2003, use regsvr32.exe as well for behavioral & error message consistency. } RegisterServerUsingRegSvr32(AUnregister, AIs64Bit, Filename); finally WindowDisabler.Free; end; end; end.
unit FileUtils_UH; interface uses SysUtils, Classes; procedure createDirectory_ALL(dir: string); function GetDirFileList(dir: String; list: TStrings; mask: string = '*.*'): boolean; implementation procedure createDirectory_ALL(dir: string); begin dir := ExtractFileDir(dir); if not DirectoryExists(dir) then begin createDirectory_ALL(dir); //recursion!! CreateDir(dir); end; end; function GetDirFileList(dir: String; list: TStrings; mask: string = '*.*'): boolean; var f: TSearchRec; ende: Boolean; begin list.Clear; Result := FindFirst(dir + mask, faAnyFile, f) = 0; ende := not Result; while not ende do begin list.Add(f.Name); ende := FindNext(f) <> 0; end; FindClose(f); end; end.
{ Private include file used by the base translator routines. Routines that * are specific to reading or writing a particular language do not include * this file. } %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'syo.ins.pas'; %include 'sst.ins.pas'; const sst_mem_pool_size = 4096; {size of memory pools allocated at a time} sst_mem_pool_chunk = 256; {max size chunk allowed to use from pool} { * Declare common block where current translator state is kept. } var (sst2) mem_p: util_mem_context_p_t; {points to top level SST memory context} max_symbol_len: sys_int_machine_t; {max allowed input symbol name} { * Private entry point declarations. } procedure sst_out_allow_break; {allow line break at current position} extern; procedure sst_out_append ( {append characters for current statement} in str: univ string_var_arg_t); {the characters to append} extern; procedure sst_out_appendn ( {append N characters to current output line} in chars: univ string; {the characters to append} in n_chars: string_index_t); {the number of characters to append} extern; procedure sst_out_appends ( {append string to current output line} in s: string); {string to append, trailing blanks ignored} extern; procedure sst_out_append_sym_name ( {append symbol output name to curr position} in sym: sst_symbol_t); {symbol descriptor to write name of} extern; procedure sst_out_blank_line; {make sure preceeding line is blank} extern; procedure sst_out_break; {break line at current position} extern; procedure sst_out_comment_end; {write end of comment string} extern; procedure sst_out_comment_set ( {set comment to correspond to next char} in s: univ string_var_arg_t); {body of comment string} extern; procedure sst_out_comment_start; {write start of comment string} extern; procedure sst_out_config; {set target machine configuration data} extern; procedure sst_out_delimit; {write delim or break line before next output} extern; procedure sst_out_indent; {increase indentation by one level} extern; procedure sst_out_line_close; {close current line} extern; procedure sst_out_line_insert; {raw insert new line at current position} extern; procedure sst_out_line_new; {set up so next char goes on next line} extern; procedure sst_out_line_new_cont; {set up for next line is continuation line} extern; procedure sst_out_name ( {make output symbol name from input name} in name_in: univ string; {input symbol name characters} in name_in_len: string_index_t; {number of characters in NAME_IN} in ext: univ string; {output name suffix, if any} in ext_len: string_index_t; {number of characters in EXT} in rename: sst_rename_k_t; {what kind of re-naming is allowed} in out name_out: univ string_var_arg_t; {resulting output source symbol name} out pos: string_hash_pos_t); {pos handle where name goes in symbol table} extern; procedure sst_out_name_sym ( {set output name for an existing symbol} in out sym: sst_symbol_t); {NOP if symbol already has output name} extern; procedure sst_out_notify_src_range ( {declare source chars range for new output} in str_h: syo_string_t); {new out chars related to these in chars} extern; procedure sst_out_tab_indent; {tab to current indentation level} extern; procedure sst_out_undent; {decrease indentation by one level} extern; procedure sst_out_undent_all; {reset to no indentation level} extern; procedure sst_out_write ( {write output lines from memory to file} in out conn: file_conn_t; {connection handle to output file} out stat: sys_err_t); {completion status code} extern;
unit ADC.ScriptBtn; interface uses System.SysUtils, System.Classes, System.RegularExpressions, Winapi.ActiveX, Winapi.Windows, MSXML2_TLB, ADC.Types, ADC.ADObject, Dialogs; type PADScriptButton = ^TADScriptButton; TADScriptButton = record Title: string; Description: string; Path: string; Parameters: string; private function IsWow64: Boolean; function DisableWow64FsRedirection(OldValue: LongBool): Boolean; function RevertWow64FsRedirection(OldValue: LongBool): Boolean; public procedure Execute(AObj: TADObject; AWow64FsRedirection: Boolean = True); end; TADScriptButtonList = class(TList) private FOwnsObjects: Boolean; procedure Notify(Ptr: Pointer; Action: TListNotification); override; function Get(Index: Integer): PADScriptButton; public constructor Create(AOwnsObjects: Boolean = True); reintroduce; destructor Destroy; override; function Add(Value: PADScriptButton): Integer; procedure Clear; override; procedure LoadFromFile(AFileName: TFileName); procedure SaveToFile(AFileName: TFileName); property Items[Index: Integer]: PADScriptButton read Get; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; type TCreateScriptButtonProc = procedure (Sender: TObject; AButton: TADScriptButton) of object; TChangeScriptButtonProc = procedure (Sender: TObject; AButton: PADScriptButton) of object; implementation { TADScriptButton } function TADScriptButton.DisableWow64FsRedirection(OldValue: LongBool): Boolean; type TWow64DisableWow64FsRedirection = function(var Wow64FsEnableRedirection: LongBool): LongBool; stdcall; var hHandle: THandle; Wow64DisableWow64FsRedirection: TWow64DisableWow64FsRedirection; begin Result := True; if not IsWow64 then Exit; try hHandle := GetModuleHandle('kernel32.dll'); @Wow64DisableWow64FsRedirection := GetProcAddress(hHandle, 'Wow64DisableWow64FsRedirection'); if ((hHandle <> 0) and (@Wow64DisableWow64FsRedirection <> nil)) then Wow64DisableWow64FsRedirection(OldValue); except Result := False; end; end; procedure TADScriptButton.Execute(AObj: TADObject; AWow64FsRedirection: Boolean); var regEx: TRegEx; StartInfo: TStartupInfo; ProcInfo: TProcessInformation; SA: SECURITY_ATTRIBUTES; sbParams: string; sbCmdLine: string; OldValue: LongBool; fSuccess: Boolean; begin if AObj = nil then Exit; sbParams := Format(' %s ', [Self.Parameters]); sbParams := regEx.Replace( sbParams, '(?<=\s)-hn(?=\s)', Format('"%s"', [AObj.DomainHostName]) ); sbParams := regEx.Replace( sbParams, '(?<=\s)-an(?=\s)', Format('"%s"', [AObj.sAMAccountName]) ); sbParams := regEx.Replace( sbParams, '(?<=\s)-dn(?=\s)', Format('"%s"', [AObj.distinguishedName]) ); sbCmdLine := 'wscript "' + Self.Path + '" ' + sbParams; with SA do begin nLength := SizeOf(SECURITY_ATTRIBUTES); bInheritHandle := True; lpSecurityDescriptor := nil; end; FillChar(StartInfo, SizeOf(StartInfo), #0); FillChar(ProcInfo, SizeOf(StartInfo), #0); with StartInfo do begin cb := SizeOf(StartInfo); dwFlags := STARTF_USESHOWWINDOW; wShowWindow := SW_HIDE; end; if not AWow64FsRedirection then DisableWow64FsRedirection(OldValue); fSuccess := CreateProcess( nil, PChar(sbCmdLine), @SA, @SA, False, 0, nil, nil, StartInfo, ProcInfo ); if not AWow64FsRedirection then RevertWow64FsRedirection(OldValue); if fSuccess then begin //// WaitForSingleObject(ProcInfo.hProcess, INFINITE); // case WaitForSingleObject(ProcInfo.hProcess, 15000) of // WAIT_TIMEOUT : ; // WAIT_FAILED : ; // else ; // end; CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end else begin raise Exception.Create(SysErrorMessage(GetLastError)); end; end; function TADScriptButton.IsWow64: Boolean; type LPFN_ISWOW64PROCESS = function(hProcess: THandle; var Wow64Process: BOOL): BOOL; stdcall; var fnIsWow64Process: LPFN_ISWOW64PROCESS; bIsWow64: BOOL; begin Result := False; fnIsWow64Process := LPFN_ISWOW64PROCESS(GetProcAddress(GetModuleHandle('kernel32'), 'IsWow64Process')); if Assigned(fnIsWow64Process) then begin bIsWow64 := False; if fnIsWow64Process(GetCurrentProcess(), bIsWow64) then Result := bIsWow64; end; end; function TADScriptButton.RevertWow64FsRedirection(OldValue: LongBool): Boolean; type TWow64RevertWow64FsRedirection = function(var Wow64RevertWow64FsRedirection: LongBool): LongBool; stdcall; var hHandle: THandle; Wow64RevertWow64FsRedirection: TWow64RevertWow64FsRedirection; begin Result := true; if not IsWow64 then Exit; try hHandle := GetModuleHandle('kernel32.dll'); @Wow64RevertWow64FsRedirection := GetProcAddress(hHandle, 'Wow64RevertWow64FsRedirection'); if ((hHandle <> 0) and (@Wow64RevertWow64FsRedirection <> nil)) then Wow64RevertWow64FsRedirection(OldValue); except Result := False; end; end; { TADScriptButtonList } function TADScriptButtonList.Add(Value: PADScriptButton): Integer; begin Result := inherited Add(Value); end; procedure TADScriptButtonList.Clear; var i: Integer; begin for i := Self.Count - 1 downto 0 do Self.Delete(i); inherited Clear; end; constructor TADScriptButtonList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; destructor TADScriptButtonList.Destroy; begin inherited; end; function TADScriptButtonList.Get(Index: Integer): PADScriptButton; begin Result := PADScriptButton(inherited Get(Index)); end; procedure TADScriptButtonList.LoadFromFile(AFileName: TFileName); var xmlFileName: TFileName; XMLStream: TStringStream; XMLDoc: IXMLDOMDocument; XMLNodeList: IXMLDOMNodeList; XMLNode: IXMLDOMNode; i: Integer; s: PADScriptButton; eventString: string; begin Self.Clear; xmlFileName := AFileName; if not FileExists(AFileName) then Exit; XMLStream := TStringStream.Create; try XMLStream.LoadFromFile(xmlFileName); XMLDoc := CoDOMDocument60.Create; XMLDoc.async := False; XMLDoc.load(TStreamAdapter.Create(XMLStream) as IStream); if XMLDoc.parseError.errorCode = 0 then begin XMLNodeList := XMLDoc.documentElement.selectNodes('script'); for i := 0 to XMLNodeList.length - 1 do begin New(s); XMLNode := XMLNodeList.item[i].selectSingleNode('title'); s^.Title := XMLNode.text; XMLNode := XMLNodeList.item[i].selectSingleNode('description'); s^.Description := XMLNode.text; XMLNode := XMLNodeList.item[i].selectSingleNode('path'); s^.Path := XMLNode.text; XMLNode := XMLNodeList.item[i].selectSingleNode('parameters'); s^.Parameters := XMLNode.text; Self.Add(s); end; end; finally XMLStream.Free; end; end; procedure TADScriptButtonList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; case Action of lnAdded: begin end; lnExtracted: begin end; lnDeleted: begin if FOwnsObjects then Dispose(PADScriptButton(Ptr)) end; end; end; procedure TADScriptButtonList.SaveToFile(AFileName: TFileName); var xmlFileName: TFileName; xmlBin: TXMLByteArray; xmlStream: TStringStream; xmlDoc: IXMLDOMDocument; xmlRoot: IXMLDOMNode; xmlEvent: IXMLDOMNode; xmlNode: IXMLDOMNode; s: PADScriptButton; begin xmlFileName := AFileName; XMLStream := TStringStream.Create; XMLDoc := CoDOMDocument60.Create; try XMLDoc.async := True; XMLDoc.loadXML('<SCRIPT_BUTTONS></SCRIPT_BUTTONS>'); for s in Self do begin XMLEvent := XMLDoc.createNode(NODE_ELEMENT, 'script', ''); XMLNode := XMLDoc.createNode(NODE_ELEMENT, 'title', ''); XMLNode.text := s^.Title; XMLEvent.appendChild(XMLNode); XMLNode := XMLDoc.createNode(NODE_ELEMENT, 'description', ''); XMLNode.text := s^.Description; XMLEvent.appendChild(XMLNode); XMLNode := XMLDoc.createNode(NODE_ELEMENT, 'path', ''); XMLNode.text := s^.Path; XMLEvent.appendChild(XMLNode); XMLNode := XMLDoc.createNode(NODE_ELEMENT, 'parameters', ''); XMLNode.text := s^.Parameters; XMLEvent.appendChild(XMLNode); XMLRoot := XMLDoc.documentElement; XMLRoot.appendChild(XMLEvent); end; XMLDoc.save(xmlFileName); finally XMLStream.Free; XMLDoc := nil; end; end; end.
unit CameraConfigurationUtils; interface uses System.Classes, System.SysUtils, System.Types, System.Generics.Collections, System.Generics.Defaults, System.Math, Fmx.Forms, Fmx.Dialogs, Androidapi.JNIBridge, Androidapi.JNI.Hardware, Androidapi.JNI.JavaTypes, Androidapi.Helpers, Androidapi.Log; type TCameraConfigurationUtils = class sealed private const MIN_PREVIEW_PIXELS: Integer = 480 * 320; MAX_EXPOSURE_COMPENSATION: Single = 1.5; MIN_EXPOSURE_COMPENSATION: Single = 0.0; MAX_ASPECT_DISTORTION: double = 0.15; MIN_FPS: Integer = 10; MAX_FPS: Integer = 20; AREA_PER_1000: Integer = 400; TAG = 'CameraConfiguration'; private class var Tms: TMarshaller; class function findSettableValue(name: string; const supportedValues: JList; desiredValues: TArray<JString>): JString; public class procedure setBestPreviewFPS(parameters: JCamera_Parameters); overload; class procedure setBestPreviewFPS(parameters: JCamera_Parameters; minFPS, maxFPS: Integer); overload; class procedure setFocus(parameters: JCamera_Parameters; autoFocus, disableContinuous, safeMode: Boolean); static; class procedure setInvertColor(parameters: JCamera_Parameters); static; class procedure setVideoStabilization(parameters : JCamera_Parameters); static; class procedure setBarcodeSceneMode(parameters: JCamera_Parameters); static; class function findBestPreviewSizeValue(parameters: JCamera_Parameters; screenResolution: TSize): TSize; static; end; implementation { TCameraConfigurationUtils } type TJCamera_SizeComparer = class(TComparer<TSize>) public function Compare(const a, b: TSize): Integer; override; end; class function TCameraConfigurationUtils.findBestPreviewSizeValue (parameters: JCamera_Parameters; screenResolution: TSize): TSize; var rawSupportedSizes: JList; supportedPreviewSizes: TList<TSize>; defaultSize, defaultPreview, camera_size: JCamera_Size; supportedPreviewSize, largestPreview: TSize; I, realWidth, realHeight: Integer; screenAspectRatio, aspectRatio, distortion: double; isCandidatePortrait: Boolean; maybeFlippedWidth, maybeFlippedHeight: Integer; exactPoint, largestSize, _defaultSize: TSize; begin rawSupportedSizes := parameters.getSupportedPreviewSizes(); if (rawSupportedSizes = nil) then begin // Log.w(TAG, "Device returned no supported preview sizes; using default"); defaultSize := parameters.getPreviewSize(); if (defaultSize = nil) then begin raise Exception.Create('Parameters contained no preview size!'); end; Result := TSize.Create(defaultSize.width, defaultSize.height); end; // Sort by size, descending supportedPreviewSizes := TList<TSize>.Create; for I := 0 to rawSupportedSizes.size - 1 do begin camera_size := TJCamera_Size.Wrap(rawSupportedSizes.get(I)); supportedPreviewSizes.Add(TSize.Create(camera_size.width, camera_size.height)); end; supportedPreviewSizes.Sort(TJCamera_SizeComparer.Create); // if (Log.isLoggable(TAG, Log.INFO)) { // StringBuilder previewSizesString = new StringBuilder(); // for (Camera.Size supportedPreviewSize : supportedPreviewSizes) { // previewSizesString.append(supportedPreviewSize.width).append('x') // .append(supportedPreviewSize.height).append(' '); // } // Log.i(TAG, "Supported preview sizes: " + previewSizesString); // } if screenResolution.width > screenResolution.height then screenAspectRatio := screenResolution.width / screenResolution.height else screenAspectRatio := screenResolution.height / screenResolution.width; // Remove sizes that are unsuitable for I := supportedPreviewSizes.Count - 1 downto 0 do begin supportedPreviewSize := supportedPreviewSizes[I]; realWidth := supportedPreviewSize.width; realHeight := supportedPreviewSize.height; if (realWidth * realHeight < MIN_PREVIEW_PIXELS) then begin supportedPreviewSizes.Remove(supportedPreviewSize); continue; end; isCandidatePortrait := realWidth < realHeight; if isCandidatePortrait then maybeFlippedWidth := realHeight else maybeFlippedWidth := realWidth; if isCandidatePortrait then maybeFlippedHeight := realWidth else maybeFlippedHeight := realHeight; aspectRatio := maybeFlippedWidth / maybeFlippedHeight; distortion := Abs(aspectRatio - screenAspectRatio); if (distortion > MAX_ASPECT_DISTORTION) then begin supportedPreviewSizes.Remove(supportedPreviewSize); continue; end; if (maybeFlippedWidth = screenResolution.width) and (maybeFlippedHeight = screenResolution.height) then begin exactPoint := TSize.Create(realWidth, realHeight); // Log.i(TAG, "Found preview size exactly matching screen size: " + exactPoint); Exit(exactPoint); end; end; // If no exact match, use largest preview size. This was not a great idea on older devices because // of the additional computation needed. We're likely to get here on newer Android 4+ devices, where // the CPU is much more powerful. if (supportedPreviewSizes.Count > 0) then begin largestPreview := supportedPreviewSizes.Last; // largestPreview := supportedPreviewSizes[0]; largestSize := TSize.Create(largestPreview.width, largestPreview.height); // Log.i(TAG, "Using largest suitable preview size: " + largestSize); Exit(largestSize); end; // If there is nothing at all suitable, return current preview size defaultPreview := parameters.getPreviewSize(); if (defaultPreview = nil) then begin raise Exception.Create('Parameters contained no preview size!'); end; _defaultSize := TSize.Create(defaultPreview.width, defaultPreview.height); // Log.i(TAG, "No suitable preview sizes, using default: " + defaultSize); Result := _defaultSize; end; class function TCameraConfigurationUtils.findSettableValue(name: string; const supportedValues: JList; desiredValues: TArray<JString>): JString; var desiredValue: JString; s: string; I: Integer; begin if supportedValues <> nil then begin for desiredValue in desiredValues do begin if supportedValues.contains(desiredValue) then Exit(desiredValue); end; end; Result := nil; end; class procedure TCameraConfigurationUtils.setBarcodeSceneMode (parameters: JCamera_Parameters); var sceneMode: JString; begin if SameText(JStringToString(parameters.getSceneMode), JStringToString(TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE)) then begin // Log.i(TAG, "Barcode scene mode already set"); Exit; end; sceneMode := findSettableValue('scene mode', parameters.getSupportedSceneModes(), [TJCamera_Parameters.JavaClass.SCENE_MODE_BARCODE]); if (sceneMode <> nil) then parameters.setSceneMode(sceneMode); end; class procedure TCameraConfigurationUtils.setBestPreviewFPS (parameters: JCamera_Parameters; minFPS, maxFPS: Integer); var supportedPreviewFpsRanges: JList; currentFpsRange, suitableFPSRange: TJavaArray<Integer>; fpsRange, currentFpsRanges: TJavaArray<Integer>; I, thisMin, thisMax, MinIdx, MaxIdx: Integer; JO: JObject; LP: Pointer; begin supportedPreviewFpsRanges := parameters.getSupportedPreviewFpsRange(); // Log.i(TAG, "Supported FPS ranges: " + toString(supportedPreviewFpsRanges)); if (supportedPreviewFpsRanges <> nil) and (not supportedPreviewFpsRanges.isEmpty) then begin suitableFPSRange := nil; MinIdx := TJCamera_Parameters.JavaClass.PREVIEW_FPS_MIN_INDEX; MaxIdx := TJCamera_Parameters.JavaClass.PREVIEW_FPS_MAX_INDEX; for I := 0 to supportedPreviewFpsRanges.size - 1 do begin JO := supportedPreviewFpsRanges.get(I); LP := (JO as ILocalObject).GetObjectID; fpsRange := TJavaArray<Integer> (WrapJNIArray(LP, TypeInfo(TJavaArray<Integer>))); thisMin := fpsRange.Items[MinIdx]; thisMax := fpsRange.Items[MaxIdx]; if (thisMin >= minFPS * 1000) and (thisMax <= maxFPS * 1000) then begin suitableFPSRange := fpsRange; break; end; end; if not Assigned(suitableFPSRange) then begin // Log.i(TAG, "No suitable FPS range?"); end else begin currentFpsRange := TJavaArray<Integer>.Create(2); parameters.getPreviewFpsRange(currentFpsRange); if (currentFpsRange.Items[0] = suitableFPSRange.Items[0]) and (currentFpsRange.Items[1] = suitableFPSRange.Items[1]) then begin // Log.i(TAG, "FPS range already set to " + Arrays.toString(suitableFPSRange)); end else begin // Log.i(TAG, "Setting FPS range to " + Arrays.toString(suitableFPSRange)); parameters.setPreviewFpsRange(suitableFPSRange.Items[MinIdx], suitableFPSRange.Items[MaxIdx]); end; end; end; end; class procedure TCameraConfigurationUtils.setBestPreviewFPS (parameters: JCamera_Parameters); begin setBestPreviewFPS(parameters, MIN_FPS, MAX_FPS); end; class procedure TCameraConfigurationUtils.setFocus (parameters: JCamera_Parameters; autoFocus, disableContinuous, safeMode: Boolean); var supportedFocusModes: JList; focusMode: JString; begin supportedFocusModes := parameters.getSupportedFocusModes(); focusMode := nil; if (autoFocus) then begin if (safeMode or disableContinuous) then begin focusMode := findSettableValue('focus mode', supportedFocusModes, [TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO]); end else begin focusMode := findSettableValue('focus mode', supportedFocusModes, [TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_PICTURE, TJCamera_Parameters.JavaClass.FOCUS_MODE_CONTINUOUS_VIDEO, TJCamera_Parameters.JavaClass.FOCUS_MODE_AUTO]); end; end; // Maybe selected auto-focus but not available, so fall through here: if (not safeMode) and (focusMode = nil) then begin focusMode := findSettableValue('focus mode', supportedFocusModes, [TJCamera_Parameters.JavaClass.FOCUS_MODE_MACRO, TJCamera_Parameters.JavaClass.FOCUS_MODE_EDOF]); end; if (focusMode <> nil) then begin if (focusMode.equals(parameters.getFocusMode())) then begin Logi(Tms.asAnsi('Focus mode already set to ' + JStringToString(focusMode)) .ToPointer); end else begin parameters.setFocusMode(focusMode); end; end; end; class procedure TCameraConfigurationUtils.setInvertColor (parameters: JCamera_Parameters); var p: TJCamera_Parameters; colorMode: JString; begin if (TJCamera_Parameters.JavaClass.EFFECT_NEGATIVE.equals (parameters.getColorEffect())) then begin // Log.i(TAG, "Negative effect already set"); Exit; end; colorMode := findSettableValue(' color effect ', parameters.getSupportedColorEffects(), [TJCamera_Parameters.JavaClass.EFFECT_NEGATIVE]); if (colorMode <> nil) then begin parameters.setColorEffect(colorMode); end; end; class procedure TCameraConfigurationUtils.setVideoStabilization (parameters: JCamera_Parameters); begin if (parameters.isVideoStabilizationSupported()) then begin if (parameters.getVideoStabilization()) then begin // Log.i(TAG, "Video stabilization already enabled"); end else begin // Log.i(TAG, "Enabling video stabilization..."); parameters.setVideoStabilization(true); end; end else begin // Log.i(TAG, "This device does not support video stabilization"); end; end; { JCamera_SizeComparer } function TJCamera_SizeComparer.Compare(const a, b: TSize): Integer; var leftPixels, rightPixels: Integer; begin leftPixels := a.height * a.width; rightPixels := b.height * b.width; if (rightPixels < leftPixels) then Result := -1 else if (rightPixels > leftPixels) then Result := 1 else Result := 0; end; end.
unit uConsultasCliente; interface uses Vcl.Forms, dmPrincipal, System.SysUtils, FireDAC.Comp.Client; function adicionarNovoSerial(serial: String): Boolean; function buscarSerialCliente(): string; function buscarCodigoUsuario(nomeUsuario: string): string; function buscarCNPJCliente(): string; function getSenhaUsuario(nomeUsuario: string): string; function verificarSerialHDCliente(serialCliente, serialHD: string): Boolean; function proximoCliente(): String; function getNomeCliente(): String; implementation uses uConstantes, uConsulta; function proximoCliente(): String; begin Result := IntToStr(StrToInt(ultimoCodigo(conexaoSistema, 'RADIUS_CLIENTE', 'ID_CLIENTE')) + 1); end; function buscarSerialCliente(): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT FIRST 1 ' + ' R.SERIAL ' + ' FROM RADIUS_CLIENTE R ';; dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('SERIAL').AsString; finally FreeAndNil(dsConsulta) end; end; function adicionarNovoSerial(serial: String): Boolean; begin dmPrincipal.frmDmPrincipal.FDConnexao.ExecSQL ('UPDATE RADIUS_CLIENTE SET SERIAL = ' + QuotedStr(serial) + ' WHERE (ID_CLIENTE = 1);') end; function buscarCodigoUsuario(nomeUsuario: string): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT ' + #13 + ' U.ID_USUARIO ' + #13 + ' FROM RADIUS_USUARIO U ' + #13 + ' WHERE ' + #13 + ' U.NOME = ' + QuotedStr(nomeUsuario); dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('ID_USUARIO').AsString; finally FreeAndNil(dsConsulta) end; end; function getSenhaUsuario(nomeUsuario: string): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT ' + #13 + ' U.SENHA ' + #13 + ' FROM RADIUS_USUARIO U ' + #13 + ' WHERE ' + #13 + ' U.NOME = ' + QuotedStr(nomeUsuario); dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('SENHA').AsString; finally FreeAndNil(dsConsulta) end; end; function verificarSerialHDCliente(serialCliente, serialHD: string): Boolean; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT ' + #13 + ' M.SERIAL_HD ' + #13 + ' FROM RADIUS_CLIENTE U ' + #13 + ' INNER JOIN RADIUS_MAQUINAS_CLIENTE M ON (M.ID_CLIENTE = U.ID_CLIENTE) ' + #13 + ' WHERE ' + #13 + ' U.SERIAL = ' + QuotedStr(serialCliente) + #13 + ' AND M.SERIAL_HD = ' + QuotedStr(serialHD); dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('SERIAL_HD').AsString = serialHD; finally FreeAndNil(dsConsulta) end; end; function buscarCNPJCliente(): string; var dsConsulta: TFDQuery; strSQLConsulta: string; begin strSQLConsulta := 'SELECT' + #13#10 + 'C.CNPJ' + #13#10 + 'FROM RADIUS_CLIENTE C' + #13#10 + 'WHERE C.ID_CLIENTE = 1'; dsConsulta := TFDQuery.Create(dmPrincipal.frmDmPrincipal.FDConnexao); dsConsulta.Connection := dmPrincipal.frmDmPrincipal.FDConnexao; dsConsulta.SQL.Text := strSQLConsulta; dsConsulta.Active := True; try Result := dsConsulta.FieldByName('CNPJ').AsString; finally FreeAndNil(dsConsulta) end; end; function getNomeCliente(): String; begin Result := buscarDado(conexaoSistema, 'RADIUS_CLIENTE', 'ID_CLIENTE', 'NOME_CLIENTE', '1'); end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2017 * } { *********************************************************** } unit tfCiphers; interface {$I TFL.inc} uses SysUtils, Classes, tfTypes, tfArrays, tfConsts, tfExceptions, {$IFDEF TFL_DLL} tfImport {$ELSE} tfAESCiphers, tfDES, tfRC4, tfRC5, tfSalsa20, tfCipherServ, // tfKeyStreams, tfEvpAES, tfOpenSSL {$ENDIF}; const ALG_AES = TF_ALG_AES; ALG_DES = TF_ALG_DES; ALG_RC5 = TF_ALG_RC5; ALG_3DES = TF_ALG_3DES; ALG_RC4 = TF_ALG_RC4; ALG_SALSA20 = TF_ALG_SALSA20; ALG_CHACHA20 = TF_ALG_CHACHA20; MODE_ECB = TF_KEYMODE_ECB; MODE_CBC = TF_KEYMODE_CBC; MODE_CFB = TF_KEYMODE_CFB; MODE_OFB = TF_KEYMODE_OFB; MODE_CTR = TF_KEYMODE_CTR; MODE_GCM = TF_KEYMODE_GCM; PADDING_DEFAULT = TF_PADDING_DEFAULT; PADDING_NONE = TF_PADDING_NONE; PADDING_ZERO = TF_PADDING_ZERO; PADDING_ANSI = TF_PADDING_ANSI; PADDING_PKCS = TF_PADDING_PKCS; PADDING_ISO = TF_PADDING_ISO; ECB_ENCRYPT = TF_KEYDIR_ENCRYPT or TF_KEYMODE_ECB; ECB_DECRYPT = TF_KEYDIR_DECRYPT or TF_KEYMODE_ECB; CBC_ENCRYPT = TF_KEYDIR_ENCRYPT or TF_KEYMODE_CBC; CBC_DECRYPT = TF_KEYDIR_DECRYPT or TF_KEYMODE_CBC; CTR_ENCRYPT = TF_KEYDIR_ENCRYPT or TF_KEYMODE_CTR; CTR_DECRYPT = TF_KEYDIR_DECRYPT or TF_KEYMODE_CTR; AES_ECB = ALG_AES or MODE_ECB; AES_ECB_ENCRYPT = ALG_AES or ECB_ENCRYPT; AES_ECB_DECRYPT = ALG_AES or ECB_DECRYPT; AES_CBC = ALG_AES or MODE_CBC; AES_CBC_ENCRYPT = ALG_AES or CBC_ENCRYPT; AES_CBC_DECRYPT = ALG_AES or CBC_DECRYPT; AES_CTR = ALG_AES or MODE_CTR; AES_CTR_ENCRYPT = ALG_AES or CTR_ENCRYPT; AES_CTR_DECRYPT = ALG_AES or CTR_DECRYPT; // current DES implementation require direction for key expansion, DES_ECB = ALG_DES or MODE_ECB; DES_ECB_ENCRYPT = ALG_DES or ECB_ENCRYPT; DES_ECB_DECRYPT = ALG_DES or ECB_DECRYPT; DES_CBC = ALG_DES or MODE_CBC; DES_CBC_ENCRYPT = ALG_DES or CBC_ENCRYPT; DES_CBC_DECRYPT = ALG_DES or CBC_DECRYPT; DES_CTR = ALG_DES or MODE_CTR; DES_CTR_ENCRYPT = ALG_DES or CTR_ENCRYPT; DES_CTR_DECRYPT = ALG_DES or CTR_DECRYPT; DES3_ECB = ALG_3DES or MODE_ECB; DES3_ECB_ENCRYPT = ALG_3DES or ECB_ENCRYPT; DES3_ECB_DECRYPT = ALG_3DES or ECB_DECRYPT; DES3_CBC = ALG_3DES or MODE_CBC; DES3_CBC_ENCRYPT = ALG_3DES or CBC_ENCRYPT; DES3_CBC_DECRYPT = ALG_3DES or CBC_DECRYPT; DES3_CTR = ALG_3DES or MODE_CTR; DES3_CTR_ENCRYPT = ALG_3DES or CTR_ENCRYPT; DES3_CTR_DECRYPT = ALG_3DES or CTR_DECRYPT; RC5_ECB = ALG_RC5 or MODE_ECB; RC5_ECB_ENCRYPT = ALG_RC5 or ECB_ENCRYPT; RC5_ECB_DECRYPT = ALG_RC5 or ECB_DECRYPT; RC5_CBC = ALG_RC5 or MODE_CBC; RC5_CBC_ENCRYPT = ALG_RC5 or CBC_ENCRYPT; RC5_CBC_DECRYPT = ALG_RC5 or CBC_DECRYPT; RC5_CTR = ALG_RC5 or MODE_CTR; RC5_CTR_ENCRYPT = ALG_RC5 or CTR_ENCRYPT; RC5_CTR_DECRYPT = ALG_RC5 or CTR_DECRYPT; ENGINE_OSSL = TF_ENGINE_OSSL; type TCipher = record private FInstance: ICipher; public procedure Free; function IsAssigned: Boolean; procedure Burn; function Clone: TCipher; function IsBlockCipher: Boolean; function GetBlockSize: Cardinal; function GetNonce: UInt64; procedure SetNonce(const Value: UInt64); procedure SetIV(AIV: Pointer; AIVLen: Cardinal); overload; procedure SetIV(const AIV: ByteArray); overload; procedure GetIV(AIV: Pointer; AIVLen: Cardinal); overload; function GetIV(AIVLen: Cardinal): ByteArray; overload; function Init(AKey: PByte; AKeyLen: Cardinal): TCipher; overload; function Init(const AKey: ByteArray): TCipher; overload; function Init(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; overload; function Init(const AKey: ByteArray; const AIV: ByteArray): TCipher; overload; function Init(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; overload; function Init(const AKey: ByteArray; const ANonce: UInt64): TCipher; overload; function EncryptInit(AKey: PByte; AKeyLen: Cardinal): TCipher; overload; function EncryptInit(const AKey: ByteArray): TCipher; overload; function EncryptInit(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; overload; function EncryptInit(const AKey: ByteArray; const AIV: ByteArray): TCipher; overload; function EncryptInit(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; overload; function EncryptInit(const AKey: ByteArray; const ANonce: UInt64): TCipher; overload; function DecryptInit(AKey: PByte; AKeyLen: Cardinal): TCipher; overload; function DecryptInit(const AKey: ByteArray): TCipher; overload; function DecryptInit(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; overload; function DecryptInit(const AKey: ByteArray; const AIV: ByteArray): TCipher; overload; function DecryptInit(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; overload; function DecryptInit(const AKey: ByteArray; const ANonce: UInt64): TCipher; overload; { // key + IV function ExpandKey(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; overload; function ExpandKey(const AKey: ByteArray; const AIV: ByteArray): TCipher; overload; // key + Nonce function ExpandKey(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; overload; function ExpandKey(const AKey: ByteArray; const ANonce: UInt64): TCipher; overload; // key only (zeroed IV) function ExpandKey(AKey: PByte; AKeyLen: Cardinal): TCipher; overload; function ExpandKey(const AKey: ByteArray): TCipher; overload; } procedure EncryptUpdate(InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean); procedure DecryptUpdate(InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean); procedure Encrypt(Data, OutData: Pointer; DataSize: Cardinal); procedure Decrypt(Data, OutData: Pointer; DataSize: Cardinal); procedure GetKeyStream(var Data; DataSize: Cardinal; Last: Boolean = False); function KeyStream(DataSize: Cardinal; Last: Boolean = False): ByteArray; class function EncryptBlock(AlgID: TAlgID; const Data, Key: ByteArray): ByteArray; static; class function DecryptBlock(AlgID: TAlgID; const Data, Key: ByteArray): ByteArray; static; function EncryptByteArray(const Data: ByteArray): ByteArray; function DecryptByteArray(const Data: ByteArray): ByteArray; procedure EncryptStream(InStream, OutStream: TStream; BufSize: Cardinal = 0); procedure DecryptStream(InStream, OutStream: TStream; BufSize: Cardinal = 0); procedure EncryptFile(const InName, OutName: string; BufSize: Cardinal = 0); procedure DecryptFile(const InName, OutName: string; BufSize: Cardinal = 0); // function Skip(Value: UInt32): TCipher; overload; function Skip(Value: Int64): TCipher; overload; class function GetInstance(AlgID: TAlgID): TCipher; static; // class function AES(AFlags: UInt32): TCipher; static; // class function DES(AFlags: UInt32): TCipher; static; // class function TripleDES(AFlags: UInt32): TCipher; static; // class function RC5(AFlags: UInt32): TCipher; overload; static; class function GetRC5(AAlgID: TAlgID; BlockSize, Rounds: Cardinal): TCipher; static; // class function RC4: TCipher; static; // class function Salsa20: TCipher; overload; static; class function GetSalsa(Rounds: Cardinal): TCipher; static; // class function ChaCha20: TCipher; overload; static; class function GetChaCha(Rounds: Cardinal): TCipher; static; // class operator Explicit(const Name: string): TCipher; // class operator Explicit(AlgID: Integer): TCipher; // class function GetCount: Integer; static; // class function GetID(Index: Cardinal): TAlgID; static; // class function GetName(Index: Cardinal): string; static; // class function GetIDByName(const Name: string): TAlgID; static; // class function GetNameByID(AlgID: TAlgID): string; static; class function Supports(AlgID: TAlgID): Boolean; static; end; TStreamCipher = record private FInstance: IStreamCipher; public procedure Free; function IsAssigned: Boolean; procedure Burn; function Clone: TStreamCipher; function ExpandKey(const AKey: ByteArray; ANonce: UInt64 = 0): TStreamCipher; overload; function ExpandKey(AKey: PByte; AKeyLen: Cardinal; ANonce: UInt64): TStreamCipher; overload; function GetNonce: UInt64; procedure SetNonce(const Nonce: UInt64); function Skip(const AValue: Int64): TStreamCipher; procedure GetKeyStream(var Data; DataSize: Cardinal); function KeyStream(ASize: Cardinal): ByteArray; procedure Apply(var Data; DataLen: Cardinal); procedure ApplyTo(const InData; var OutData; DataLen: Cardinal); function ApplyToByteArray(const Data: ByteArray): ByteArray; procedure ApplyToStream(InStream, OutStream: TStream; BufSize: Cardinal = 0); procedure ApplyToFile(const InName, OutName: string; BufSize: Cardinal = 0); { class function GetInstance(AlgID: TAlgID): TStreamCipher; static; // class function GetInstance(const Name: string): TStreamCipher; static; class function AES: TStreamCipher; static; class function DES: TStreamCipher; static; class function TripleDES: TStreamCipher; static; class function RC5: TStreamCipher; overload; static; class function RC5(BlockSize, Rounds: Cardinal): TStreamCipher; overload; static; class function RC4: TStreamCipher; static; class function Salsa20: TStreamCipher; overload; static; class function Salsa20(Rounds: Cardinal): TStreamCipher; overload; static; class function ChaCha20: TStreamCipher; overload; static; class function ChaCha20(Rounds: Cardinal): TStreamCipher; overload; static; } // class operator Explicit(const Name: string): TStreamCipher; // property Nonce: UInt64 read GetNonce write SetNonceProc; end; type ECipherError = class(EForgeError); implementation procedure CipherError(ACode: TF_RESULT; const Msg: string = ''); begin raise ECipherError.Create(ACode, Msg); end; procedure HResCheck(Value: TF_RESULT); inline; begin if Value <> TF_S_OK then CipherError(Value); end; // FServer is a singleton, no memory leak because of global intf ref var FServer: ICipherServer; function GetServer: ICipherServer; begin if FServer = nil then HResCheck(GetCipherServerInstance(FServer)); Result:= FServer; end; { TCipher } (* class function TCipher.Create(const Alg: ICipherAlgorithm): TCipher; begin Result.FInstance:= Alg; end; *) procedure TCipher.Free; begin FInstance:= nil; end; function TCipher.GetBlockSize: Cardinal; begin Result:= FInstance.GetBlockSize; end; procedure TCipher.GetKeyStream(var Data; DataSize: Cardinal; Last: Boolean); begin HResCheck(FInstance.GetKeyStream(@Data, DataSize, Last)); end; function TCipher.GetNonce: UInt64; {var DataLen: Cardinal; begin DataLen:= SizeOf(UInt64); HResCheck(FInstance.GetKeyParam(TF_KP_NONCE, @Result, DataLen));} begin HResCheck(FInstance.GetNonce(Result)); end; procedure TCipher.GetIV(AIV: Pointer; AIVLen: Cardinal); begin HResCheck(FInstance.GetIV(AIV, AIVLen)); end; function TCipher.GetIV(AIVLen: Cardinal): ByteArray; var Tmp: ByteArray; begin Tmp:= ByteArray.Allocate(AIVLen); HResCheck(FInstance.GetIV(Tmp.RawData, AIVLen)); Result:= Tmp; end; function TCipher.KeyStream(DataSize: Cardinal; Last: Boolean): ByteArray; var Tmp: ByteArray; begin Tmp:= ByteArray.Allocate(DataSize); GetKeyStream(Tmp.RawData^, DataSize, Last); Result:= Tmp; end; function TCipher.Init(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; begin HResCheck(FInstance.ExpandKeyIV(AKey, AKeyLen, AIV, AIVLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Init(const AKey: ByteArray): TCipher; begin HResCheck(FInstance.ExpandKey(AKey.RawData, AKey.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Init(AKey: PByte; AKeyLen: Cardinal): TCipher; begin HResCheck(FInstance.ExpandKey(AKey, AKeyLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Init(const AKey: ByteArray; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.ExpandKeyNonce(AKey.RawData, AKey.Len, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Init(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.ExpandKeyNonce(AKey, AKeyLen, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Init(const AKey, AIV: ByteArray): TCipher; begin HResCheck(FInstance.ExpandKeyIV(AKey.RawData, AKey.Len, AIV.RawData, AIV.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.IsAssigned: Boolean; begin Result:= FInstance <> nil; end; function TCipher.IsBlockCipher: Boolean; begin Result:= FInstance.GetIsBlockCipher; end; { class function TCipher.GetInstance(const Name: string): TCipher; begin HResCheck(FServer.GetByName(Pointer(Name), SizeOf(Char), Result.FInstance)); end; } class function TCipher.GetInstance(AlgID: TAlgID): TCipher; begin HResCheck(GetCipherInstance(AlgID, Result.FInstance)); end; (* class function TCipher.AES(AFlags: UInt32): TCipher; begin Result:= GetInstance(AFlags or TF_ALG_AES); end; class function TCipher.DES(AFlags: UInt32): TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_DES, Result.FInstance)); HResCheck(GetDESInstance(PDESInstance(Result.FInstance), AFlags)); end; class function TCipher.TripleDES(AFlags: UInt32): TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_3DES, Result.FInstance)); HResCheck(Get3DESInstance(P3DESInstance(Result.FInstance), AFlags)); end; class function TCipher.RC4: TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_RC4, Result.FInstance)); HResCheck(GetRC4Instance(PRC4Instance(Result.FInstance))); end; class function TCipher.RC5(AFlags: UInt32): TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_RC5, Result.FInstance)); HResCheck(GetRC5Instance(PRC5Instance(Result.FInstance), AFlags)); end; *) class function TCipher.GetRC5(AAlgID: TAlgID; BlockSize, Rounds: Cardinal): TCipher; begin // HResCheck(FServer.GetRC5(BlockSize, Rounds, Result.FInstance)); HResCheck(GetRC5InstanceEx(PRC5Instance(Result.FInstance), AAlgID, BlockSize, Rounds)); end; (* class function TCipher.Salsa20: TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_SALSA20, Result.FInstance)); HResCheck(GetSalsa20Instance(PSalsa20Instance(Result.FInstance))); end; *) class function TCipher.GetSalsa(Rounds: Cardinal): TCipher; begin // HResCheck(FServer.GetSalsa20(Rounds, Result.FInstance)); HResCheck(GetSalsa20InstanceEx(PSalsa20Instance(Result.FInstance), Rounds)); end; (* class function TCipher.ChaCha20: TCipher; begin // HResCheck(FServer.GetByAlgID(TF_ALG_CHACHA20, Result.FInstance)); HResCheck(GetChaCha20Instance(PSalsa20Instance(Result.FInstance))); end; *) class function TCipher.GetChaCha(Rounds: Cardinal): TCipher; begin // HResCheck(FServer.GetChaCha20(Rounds, Result.FInstance)); HResCheck(GetChaCha20InstanceEx(PSalsa20Instance(Result.FInstance), Rounds)); end; { function TCipher.ExpandKey(AKey: PByte; AKeyLen: Cardinal): TCipher; begin // HResCheck(FInstance.ExpandKeyIV(AKey, AKeyLen, nil, 0)); HResCheck(FInstance.ExpandKey(AKey, AKeyLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.ExpandKey(const AKey: ByteArray): TCipher; begin // HResCheck(FInstance.ExpandKeyIV(AKey.RawData, AKey.Len, nil, 0)); HResCheck(FInstance.ExpandKey(AKey.RawData, AKey.Len)); // Result:= Self; Result.FInstance:= FInstance; end; (* function TCipher.ExpandKey(AKey: PByte; AKeyLen: Cardinal): TCipher; begin HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @AFlags, SizeOf(AFlags))); HResCheck(FInstance.ExpandKey(AKey, AKeyLen)); Result:= Self; end; *) function TCipher.ExpandKey(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; begin // HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @AFlags, SizeOf(AFlags))); // HResCheck(FInstance.SetKeyParam(TF_KP_IV, AIV, AIVLen)); HResCheck(FInstance.ExpandKeyIV(AKey, AKeyLen, AIV, AIVLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.ExpandKey(const AKey: ByteArray; const AIV: ByteArray): TCipher; begin // HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @AFlags, SizeOf(AFlags))); // HResCheck(FInstance.SetKeyParam(TF_KP_IV, AIV.RawData, AIV.Len)); HResCheck(FInstance.ExpandKeyIV(AKey.RawData, AKey.Len, AIV.RawData, AIV.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.ExpandKey(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; (* var LBlockSize: Cardinal; LBlock: array[0..TF_MAX_CIPHER_BLOCK_SIZE - 1] of Byte; begin LBlockSize:= GetBlockSize; if LBlockSize < SizeOf(ANonce) then begin if ANonce = 0 then Result:= ExpandKey(AKey, AKeyLen, nil, 0) else CipherError(TF_E_INVALIDARG); end else if LBlockSize = SizeOf(ANonce) then begin Result:= ExpandKey(AKey, AKeyLen, @ANonce, SizeOf(ANonce)); end else if LBlockSize <= TF_MAX_CIPHER_BLOCK_SIZE then begin FillChar(LBlock, LBlockSize, 0); Move(ANonce, LBlock, SizeOf(ANonce)); Result:= ExpandKey(AKey, AKeyLen, @LBlock, LBlockSize); FillChar(LBlock, LBlockSize, 0); end else CipherError(TF_E_UNEXPECTED); // HResCheck(FInstance.ExpandKey(AKey.RawData, AKey.Len)); *) begin HResCheck(FInstance.ExpandKeyNonce(AKey, AKeyLen, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.ExpandKey(const AKey: ByteArray; const ANonce: UInt64): TCipher; begin // HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @AFlags, SizeOf(AFlags))); // HResCheck(FInstance.SetKeyParam(TF_KP_NONCE, @ANonce, SizeOf(ANonce))); HResCheck(FInstance.ExpandKeyNonce(AKey.RawData, AKey.Len, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; } procedure TCipher.Burn; begin FInstance.Burn; end; procedure TCipher.EncryptUpdate(InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean); begin HResCheck(FInstance.EncryptUpdate(InBuffer, OutBuffer, DataSize, OutBufSize, Last)); end; procedure TCipher.DecryptUpdate(InBuffer, OutBuffer: PByte; var DataSize: Cardinal; OutBufSize: Cardinal; Last: Boolean); begin HResCheck(FInstance.DecryptUpdate(InBuffer, OutBuffer, DataSize, OutBufSize, Last)); end; procedure TCipher.Encrypt(Data, OutData: Pointer; DataSize: Cardinal); begin HResCheck(FInstance.Encrypt(Data, OutData, DataSize)); end; procedure TCipher.Decrypt(Data, OutData: Pointer; DataSize: Cardinal); begin HResCheck(FInstance.Decrypt(Data, OutData, DataSize)); end; class function TCipher.EncryptBlock(AlgID: TAlgID; const Data, Key: ByteArray): ByteArray; var Cipher: TCipher; BlockSize: Integer; begin AlgID:= AlgID and TF_ALGID_MASK; Cipher:= TCipher.GetInstance(AlgID or ECB_ENCRYPT).Init(Key); BlockSize:= Cipher.GetBlockSize; if (BlockSize = 0) or (BlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then CipherError(TF_E_UNEXPECTED); if (BlockSize <> Data.GetLen) then CipherError(TF_E_INVALIDARG); Result:= Data.Copy(); Cipher.FInstance.EncryptBlock(Result.GetRawData); end; class function TCipher.DecryptBlock(AlgID: TAlgID; const Data, Key: ByteArray): ByteArray; var Cipher: TCipher; BlockSize: Integer; begin AlgID:= AlgID and TF_ALGID_MASK; Cipher:= TCipher.GetInstance(AlgID or ECB_DECRYPT).Init(Key); BlockSize:= Cipher.GetBlockSize; if (BlockSize = 0) or (BlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then CipherError(TF_E_UNEXPECTED); if (BlockSize <> Data.GetLen) then CipherError(TF_E_INVALIDARG); Result:= Data.Copy(); Cipher.FInstance.DecryptBlock(Result.GetRawData); end; function TCipher.EncryptByteArray(const Data: ByteArray): ByteArray; var L0, L1: Cardinal; LBlockSize: Cardinal; OutBuffer, InBuffer: PByte; // It is possible that TCipher instance containes some cached data // before EncryptByteArray call; this is user code error // (prev encryption was not finalized), // but I must handle this case correctly; // since I wouldn't reset cache for an external engine, // I simply dump the cache to the output. begin LBlockSize:= GetBlockSize; {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin CipherError(TF_E_UNEXPECTED, 'BlockSize = ' + IntToStr(LBlockSize)); end; {$ENDIF} L0:= Data.GetLen; // one LBlockSize for cache dump, another for pad block L1:= L0 + 2 * LBlockSize; GetMem(OutBuffer, L1); try InBuffer:= OutBuffer + LBlockSize; Move(Data.RawData^, InBuffer^, L0); HResCheck(FInstance.EncryptUpdate(InBuffer, OutBuffer, L0, L1, True)); Result:= ByteArray.FromMem(OutBuffer, L0); finally FillChar(OutBuffer^, L1, 0); FreeMem(OutBuffer); end; end; function TCipher.DecryptByteArray(const Data: ByteArray): ByteArray; var L0, L1: Cardinal; LBlockSize: Cardinal; OutBuffer, InBuffer: PByte; begin LBlockSize:= GetBlockSize; {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin CipherError(TF_E_UNEXPECTED, 'BlockSize = ' + IntToStr(LBlockSize)); end; {$ENDIF} L0:= Data.GetLen; // LBlockSize for cache dump L1:= L0 + LBlockSize; GetMem(OutBuffer, L1); try InBuffer:= OutBuffer + LBlockSize; Move(Data.RawData^, InBuffer^, L0); HResCheck(FInstance.DecryptUpdate(InBuffer, OutBuffer, L0, L1, True)); Result:= ByteArray.FromMem(OutBuffer, L0); finally FillChar(OutBuffer^, L1, 0); FreeMem(OutBuffer); end; end; procedure TCipher.EncryptFile(const InName, OutName: string; BufSize: Cardinal); var InStream, OutStream: TStream; begin InStream:= TFileStream.Create(InName, fmOpenRead or fmShareDenyWrite); OutStream:= TFileStream.Create(OutName, fmCreate); try EncryptStream(InStream, OutStream, BufSize); finally InStream.Free; OutStream.Free; end; end; function TCipher.EncryptInit(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKeyIV(AKey, AKeyLen, AIV, AIVLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.EncryptInit(const AKey: ByteArray): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKey(AKey.RawData, AKey.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.EncryptInit(AKey: PByte; AKeyLen: Cardinal): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKey(AKey, AKeyLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.EncryptInit(const AKey: ByteArray; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKeyNonce(AKey.RawData, AKey.Len, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.EncryptInit(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKeyNonce(AKey, AKeyLen, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.EncryptInit(const AKey, AIV: ByteArray): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_ENCRYPT)); HResCheck(FInstance.ExpandKeyIV(AKey.RawData, AKey.Len, AIV.RawData, AIV.Len)); // Result:= Self; Result.FInstance:= FInstance; end; procedure TCipher.EncryptStream(InStream, OutStream: TStream; BufSize: Cardinal); const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; // PAD_BUFSIZE = TF_MAX_CIPHER_BLOCK_SIZE; var LBlockSize: Cardinal; DataSize, OutBufSize: Cardinal; InBuffer, OutBuffer: PByte; PInBuffer: PByte; N: Integer; Cnt: Cardinal; Last: Boolean; begin LBlockSize:= GetBlockSize; {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin CipherError(TF_E_UNEXPECTED, 'BlockSize = ' + IntToStr(LBlockSize)); end; {$ENDIF} if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE else BufSize:= (BufSize + LBlockSize - 1) and not (LBlockSize - 1); OutBufSize:= BufSize + 2 * LBlockSize; GetMem(OutBuffer, OutBufSize); InBuffer:= OutBuffer + LBlockSize; try repeat Cnt:= BufSize; PInBuffer:= InBuffer; repeat N:= InStream.Read(PInBuffer^, Cnt); if N <= 0 then Break; Inc(PInBuffer, N); Dec(Cnt, N); until (Cnt = 0); Last:= Cnt > 0; DataSize:= BufSize - Cnt; EncryptUpdate(InBuffer, OutBuffer, DataSize, OutBufSize, Last); if DataSize > 0 then OutStream.WriteBuffer(OutBuffer^, DataSize); until Last; finally FreeMem(OutBuffer); end; end; procedure TCipher.DecryptStream(InStream, OutStream: TStream; BufSize: Cardinal); const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; // PAD_BUFSIZE = TF_MAX_CIPHER_BLOCK_SIZE; var LBlockSize: Cardinal; DataSize, OutBufSize: Cardinal; InBuffer, OutBuffer, PInBuffer: PByte; N: Integer; Cnt: Cardinal; Last: Boolean; begin LBlockSize:= GetBlockSize; {$IFDEF DEBUG} if (LBlockSize <= 0) or (LBlockSize > TF_MAX_CIPHER_BLOCK_SIZE) then begin CipherError(TF_E_UNEXPECTED, 'BlockSize = ' + IntToStr(LBlockSize)); end; {$ENDIF} if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE else BufSize:= (BufSize + LBlockSize - 1) and not (LBlockSize - 1); OutBufSize:= BufSize + LBlockSize; GetMem(OutBuffer, OutBufSize); InBuffer:= OutBuffer + LBlockSize; try repeat Cnt:= BufSize; PInBuffer:= InBuffer; repeat N:= InStream.Read(PInBuffer^, Cnt); if N <= 0 then Break; Inc(PInBuffer, N); Dec(Cnt, N); until (Cnt = 0); Last:= Cnt > 0; DataSize:= BufSize - Cnt; DecryptUpdate(InBuffer, OutBuffer, DataSize, OutBufSize, Last); if DataSize > 0 then OutStream.WriteBuffer(OutBuffer^, DataSize); until Last; finally FreeMem(OutBuffer); end; end; (* procedure TCipher.DecryptStream(InStream, OutStream: TStream; BufSize: Cardinal); const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; PAD_BUFSIZE = TF_MAX_CIPHER_BLOCK_SIZE; var Pad: array[0..TF_MAX_CIPHER_BLOCK_SIZE - 1] of Byte; ReadBufSize, OutDataSize, DataSize, LDataSize, Offset: Cardinal; OutData, InData, Data, PData: PByte; N: Integer; Cnt: Cardinal; Last: Boolean; begin if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE else BufSize:= (BufSize + PAD_BUFSIZE - 1) and not (PAD_BUFSIZE - 1); OutDataSize:= BufSize + PAD_BUFSIZE; ReadBufSize:= BufSize + PAD_BUFSIZE; // allocate 2 pad blocks at the Buffer end // we don't use the 2nd pad block but OSSL can use it // then we decrypt the 1st block (Last = True) GetMem(Data, ReadBufSize + PAD_BUFSIZE); try OutData:= Data; InData:= Data; PData:= InData; Offset:= 0; repeat Cnt:= ReadBufSize; repeat N:= InStream.Read(PData^, Cnt); if N <= 0 then Break; Inc(PData, N); Dec(Cnt, N); until (Cnt = 0); Last:= Cnt > 0; if Last then begin DataSize:= OutDataSize - Cnt; end else begin DataSize:= BufSize - Offset; // Move((InData + BufSize - Offset)^, Pad, PAD_BUFSIZE); Move((Data + BufSize)^, Pad, PAD_BUFSIZE); end; LDataSize:= DataSize; Decrypt(InData, DataSize, OutData, DataSize, Last); if DataSize > 0 then OutStream.WriteBuffer(OutData^, DataSize); // OutStream.WriteBuffer(Data^, BufSize); if Last then Break else begin // Move((Data + OutBufSize - PAD_BUFSIZE)^, Data^, PAD_BUFSIZE); if LDataSize > DataSize then begin Inc(Offset, LDataSize - DataSize); Inc(InData, LDataSize - DataSize); end; Move(Pad, InData^, PAD_BUFSIZE); PData:= InData + PAD_BUFSIZE; ReadBufSize:= BufSize - Offset; OutDataSize:= ReadBufSize + PAD_BUFSIZE; end; until False; finally FreeMem(Data); end; end; *) procedure TCipher.DecryptFile(const InName, OutName: string; BufSize: Cardinal); var InStream, OutStream: TStream; begin InStream:= TFileStream.Create(InName, fmOpenRead or fmShareDenyWrite); OutStream:= TFileStream.Create(OutName, fmCreate); try DecryptStream(InStream, OutStream, BufSize); finally InStream.Free; OutStream.Free; end; end; function TCipher.DecryptInit(AKey: PByte; AKeyLen: Cardinal; AIV: Pointer; AIVLen: Cardinal): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKeyIV(AKey, AKeyLen, AIV, AIVLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.DecryptInit(const AKey: ByteArray): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKey(AKey.RawData, AKey.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.DecryptInit(AKey: PByte; AKeyLen: Cardinal): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKey(AKey, AKeyLen)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.DecryptInit(const AKey: ByteArray; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKeyNonce(AKey.RawData, AKey.Len, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.DecryptInit(AKey: PByte; AKeyLen: Cardinal; const ANonce: UInt64): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKeyNonce(AKey, AKeyLen, ANonce)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.DecryptInit(const AKey, AIV: ByteArray): TCipher; begin HResCheck(FInstance.SetKeyDir(TF_KEYDIR_DECRYPT)); HResCheck(FInstance.ExpandKeyIV(AKey.RawData, AKey.Len, AIV.RawData, AIV.Len)); // Result:= Self; Result.FInstance:= FInstance; end; function TCipher.Clone: TCipher; begin HResCheck(FInstance.Clone(Result.FInstance)); end; { class function TCipher.GetCount: Integer; begin // Result:= FServer.GetCount; Result:= GetServer.GetCount; end; } { function TCipher.Decrypt(const Data: ByteArray): ByteArray; var L: LongWord; begin L:= Data.Len; Result:= ByteArray.Copy(Data); Decrypt(Result.RawData^, L, True); Result.Len:= L; end; } { class function TCipher.GetID(Index: Cardinal): TAlgID; begin HResCheck(GetServer.GetID(Index, Result)); end; class function TCipher.GetName(Index: Cardinal): string; var // Bytes: IBytes; // I, L: Integer; // P: PByte; P: Pointer; // S: string; begin (* HResCheck(FServer.GetName(Index, Bytes)); L:= Bytes.GetLen; P:= Bytes.GetRawData; SetLength(Result, L); for I:= 1 to L do begin Result[I]:= Char(P^); Inc(P); end;*) HResCheck(GetServer.GetName(Index, P)); // S:= UTF8String(PAnsiChar(P)); // Result:= S; Result:= string(UTF8String(PAnsiChar(P))); end; class function TCipher.GetIDByName(const Name: string): TAlgID; begin HResCheck(GetServer.GetIDByName(Pointer(Name), SizeOf(Char), Result)); end; class function TCipher.GetNameByID(AlgID: TAlgID): string; var P: Pointer; begin HResCheck(GetServer.GetNameByID(AlgID and TF_ALGID_MASK, P)); Result:= string(PUTF8String(P)^); end; } (* function TCipher.SetFlags(AFlags: UInt32): TCipher; begin HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @AFlags, SizeOf(AFlags))); Result:= Self; end; procedure TCipher.SetFlagsProc(const Value: UInt32); begin HResCheck(FInstance.SetKeyParam(TF_KP_FLAGS, @Value, SizeOf(Value))); end; *) procedure TCipher.SetIV(AIV: Pointer; AIVLen: Cardinal); begin // HResCheck(FInstance.SetKeyParam(TF_KP_IV, AIV, AIVLen)); HResCheck(FInstance.SetIV(AIV, AIVLen)); end; procedure TCipher.SetIV(const AIV: ByteArray); begin // HResCheck(FInstance.SetKeyParam(TF_KP_IV, AIV.RawData, AIV.Len)); HResCheck(FInstance.SetIV(AIV.RawData, AIV.Len)); end; (* procedure TCipher.SetIVProc(const Value: ByteArray); begin HResCheck(FInstance.SetKeyParam(TF_KP_IV, Value.RawData, Value.Len)); end; *) (* function TCipher.SetNonce(const Value: ByteArray): TCipher; begin HResCheck(FInstance.SetKeyParam(TF_KP_NONCE, Value.RawData, Value.Len)); Result:= Self; end; function TCipher.SetNonce(const Value: UInt64): TCipher; begin HResCheck(FInstance.SetKeyParam(TF_KP_NONCE, @Value, SizeOf(Value))); Result:= Self; end; *) procedure TCipher.SetNonce(const Value: UInt64); begin // HResCheck(FInstance.SetKeyParam(TF_KP_NONCE, @Value, SizeOf(Value))); HResCheck(FInstance.SetNonce(Value)); end; { function TCipher.SetBlockNo(const Value: ByteArray): TCipher; begin HResCheck(FAlgorithm.SetKeyParam(TF_KP_BLOCKNO, Value.RawData, Value.Len)); Result:= Self; end; function TCipher.SetBlockNo(const Value: UInt64): TCipher; begin HResCheck(FAlgorithm.SetKeyParam(TF_KP_BLOCKNO_LE, @Value, SizeOf(Value))); Result:= Self; end; } (* function TCipher.Skip(Value: UInt32): TCipher; begin HResCheck(FInstance.SetKeyParam(TF_KP_INCNO{_LE}, @Value, SizeOf(Value))); Result:= Self; end; *) function TCipher.Skip(Value: Int64): TCipher; begin // HResCheck(FInstance.SetKeyParam(TF_KP_INCNO{_LE}, @Value, SizeOf(Value))); HResCheck(FInstance.Skip(Value)); Result:= Self; end; function SupportsOSSL(AlgID: TAlgID): Boolean; var Alg, Mode, Padding: TAlgID; begin Alg:= AlgID and TF_ALGID_MASK; Mode:= AlgID and TF_KEYMODE_MASK; Padding:= AlgID and TF_PADDING_MASK; if (Padding <> TF_PADDING_DEFAULT) and (Padding <> TF_PADDING_NONE) and (Padding <> TF_PADDING_PKCS) then begin Result:= False; Exit; end; if Alg = TF_ALG_AES then begin if (Mode = TF_KEYMODE_ECB) then begin Result:= Assigned(EVP_aes_128_ecb); Exit; end; if (Mode = TF_KEYMODE_CBC) then begin Result:= Assigned(EVP_aes_128_cbc); Exit; end; if (Mode = TF_KEYMODE_CTR) then begin Result:= Assigned(EVP_aes_128_ctr) and (Padding = TF_PADDING_DEFAULT); Exit; end; Result:= False; Exit; end else Result:= False; end; function SupportsStd(AlgID: TAlgID): Boolean; var A, Alg, Mode, Padding: TAlgID; IsBlock, IsStream: Boolean; ValidMode, ValidPadding: Boolean; const BlockAlgs: array[0..3] of TAlgID = ( TF_ALG_AES, TF_ALG_DES, TF_ALG_RC5, TF_ALG_3DES ); StreamAlgs: array[0..2] of TAlgID = ( TF_ALG_RC4, TF_ALG_SALSA20, TF_ALG_CHACHA20 ); Modes: array[0..2] of TAlgID = ( TF_KEYMODE_ECB, TF_KEYMODE_CBC, TF_KEYMODE_CTR ); Paddings: array[0..5] of TAlgID = ( TF_PADDING_DEFAULT, TF_PADDING_NONE, TF_PADDING_ZERO, TF_PADDING_ANSI, TF_PADDING_PKCS, TF_PADDING_ISO ); begin Alg:= AlgID and TF_ALGID_MASK; IsBlock:= False; IsStream:= False; for A in BlockAlgs do begin if A = Alg then begin IsBlock:= True; Break; end; end; if not IsBlock then begin for A in StreamAlgs do begin if A = Alg then begin IsStream:= True; Break; end; end; end; if not IsBlock and not IsStream then begin Result:= False; Exit; end; Mode:= AlgID and TF_KEYMODE_MASK; // a block cipher algorithm in CTR mode is a stream cipher if IsBlock and (Mode = TF_KEYMODE_CTR) then begin // IsBlock:= False; IsStream:= True; end; ValidMode:= False; for A in Modes do begin if A = Mode then begin ValidMode:= True; Break; end; end; if not ValidMode then begin Result:= False; Exit; end; Padding:= AlgID and TF_PADDING_MASK; // stream ciphers do not use padding if IsStream and (Padding <> TF_PADDING_DEFAULT) then begin Result:= False; Exit; end; ValidPadding:= False; for A in Paddings do begin if A = Mode then begin ValidPadding:= True; Break; end; end; Result:= ValidPadding; end; class function TCipher.Supports(AlgID: TAlgID): Boolean; begin case AlgID and TF_ENGINE_MASK of TF_ENGINE_STD: Result:= SupportsStd(AlgID); TF_ENGINE_OSSL: Result:= SupportsOSSL(AlgID); else Result:= False; end; end; { function TCipher.Skip(Value: ByteArray): TCipher; begin HResCheck(FAlgorithm.SetKeyParam(TF_KP_INCNO, @Value, SizeOf(Value))); Result:= Self; end; class operator TCipher.Explicit(AlgID: Integer): TCipher; begin // HResCheck(FServer.GetByAlgID(AlgID, Result.FInstance)); HResCheck(GetServer.GetByAlgID(AlgID, Result.FInstance)); end; class operator TCipher.Explicit(const Name: string): TCipher; begin // HResCheck(FServer.GetByName(Pointer(Name), SizeOf(Char), Result.FInstance)); HResCheck(GetServer.GetByName(Pointer(Name), SizeOf(Char), Result.FInstance)); end; } { TKeyStream } procedure TStreamCipher.Free; begin FInstance:= nil; end; function TStreamCipher.IsAssigned: Boolean; begin Result:= FInstance <> nil; end; function TStreamCipher.KeyStream(ASize: Cardinal): ByteArray; begin Result:= ByteArray.Allocate(ASize); HResCheck(FInstance.GetKeyStream(Result.GetRawData, ASize)); end; procedure TStreamCipher.Burn; begin FInstance.Burn; end; function TStreamCipher.ExpandKey(AKey: PByte; AKeyLen: Cardinal; ANonce: UInt64): TStreamCipher; begin HResCheck(FInstance.ExpandKey(AKey, AKeyLen, ANonce)); Result:= Self; end; function TStreamCipher.ExpandKey(const AKey: ByteArray; ANonce: UInt64): TStreamCipher; begin HResCheck(FInstance.ExpandKey(AKey.GetRawData, AKey.GetLen, ANonce)); Result:= Self; end; (* function TStreamCipher.ExpandKey(const AKey: ByteArray): TStreamCipher; begin HResCheck(FInstance.ExpandKey(AKey.GetRawData, AKey.GetLen, 0)); Result:= Self; end; *) (* class operator TStreamCipher.Explicit(const Name: string): TStreamCipher; begin // HResCheck(FServer.GetKSByName(Pointer(Name), SizeOf(Char), Result.FInstance)); HResCheck(GetServer.GetKSByName(Pointer(Name), SizeOf(Char), Result.FInstance)); end; *) (* don't want to expose class operator TStreamCipher.Explicit(AlgID: Integer): TStreamCipher; begin HResCheck(FServer.GetKSByAlgID(AlgID, Result.FInstance)); end; *) function TStreamCipher.Skip(const AValue: Int64): TStreamCipher; begin HResCheck(FInstance.Skip(AValue)); Result:= Self; end; function TStreamCipher.Clone: TStreamCipher; begin HResCheck(FInstance.Duplicate(Result.FInstance)); end; (* class function TStreamCipher.AES: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_AES, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_AES, Result.FInstance)); HResCheck(GetAESStreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.DES: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_DES, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_DES, Result.FInstance)); HResCheck(GetDESStreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.TripleDES: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_3DES, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_3DES, Result.FInstance)); HResCheck(Get3DESStreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.Salsa20: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_SALSA20, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_SALSA20, Result.FInstance)); HResCheck(GetSalsa20StreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.Salsa20(Rounds: Cardinal): TStreamCipher; begin // HResCheck(FServer.GetKSSalsa20(Rounds, Result.FInstance)); // HResCheck(GetServer.GetKSSalsa20(Rounds, Result.FInstance)); HResCheck(GetSalsa20StreamCipherInstanceEx(Result.FInstance, Rounds)); end; class function TStreamCipher.GetInstance(AlgID: TAlgID): TStreamCipher; begin HResCheck(GetStreamCipherInstance(AlgID, Result.FInstance)); end; *) (* class function TStreamCipher.GetInstance(const Name: string): TStreamCipher; begin // HResCheck(FServer.GetKSByName(Pointer(Name), SizeOf(Char), Result.FInstance)); HResCheck(GetServer.GetKSByName(Pointer(Name), SizeOf(Char), Result.FInstance)); end; *) function TStreamCipher.GetNonce: UInt64; begin HResCheck(FInstance.GetNonce(Result)); end; procedure TStreamCipher.SetNonce(const Nonce: UInt64); begin HResCheck(FInstance.SetNonce(Nonce)); end; (* class function TStreamCipher.ChaCha20: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_CHACHA20, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_CHACHA20, Result.FInstance)); // HResCheck(GetStreamCipherInstance(TF_ALG_CHACHA20, Result.FInstance)); HResCheck(GetChacha20StreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.ChaCha20(Rounds: Cardinal): TStreamCipher; begin // HResCheck(FServer.GetKSChaCha20(Rounds, Result.FInstance)); // HResCheck(GetServer.GetKSChaCha20(Rounds, Result.FInstance)); HResCheck(GetChacha20StreamCipherInstanceEx(Result.FInstance, Rounds)); end; class function TStreamCipher.RC4: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_RC4, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_RC4, Result.FInstance)); HResCheck(GetRC4StreamCipherInstance(Result.FInstance)); end; class function TStreamCipher.RC5(BlockSize, Rounds: Cardinal): TStreamCipher; begin // HResCheck(FServer.GetKSRC5(BlockSize, Rounds, Result.FInstance)); // HResCheck(GetServer.GetKSRC5(BlockSize, Rounds, Result.FInstance)); HResCheck(GetRC5StreamCipherInstanceEx(Result.FInstance, BlockSize, Rounds)); end; class function TStreamCipher.RC5: TStreamCipher; begin // HResCheck(FServer.GetKSByAlgID(TF_ALG_RC5, Result.FInstance)); // HResCheck(GetServer.GetKSByAlgID(TF_ALG_RC5, Result.FInstance)); HResCheck(GetRC5StreamCipherInstance(Result.FInstance)); end; *) procedure TStreamCipher.GetKeyStream(var Data; DataSize: Cardinal); begin HResCheck(FInstance.GetKeyStream(@Data, DataSize)); end; procedure TStreamCipher.Apply(var Data; DataLen: Cardinal); begin HResCheck(FInstance.Apply(@Data, DataLen)); end; procedure TStreamCipher.ApplyTo(const InData; var OutData; DataLen: Cardinal); var HRes: TF_RESULT; begin Move(InData, OutData, DataLen); HRes:= FInstance.Apply(@OutData, DataLen); if HRes <> TF_S_OK then begin FillChar(OutData, DataLen, 0); CipherError(HRes); end; end; function TStreamCipher.ApplyToByteArray(const Data: ByteArray): ByteArray; var L: Cardinal; HRes: TF_RESULT; begin L:= Data.GetLen; Result:= Data; Result.ReAllocate(L); HRes:= FInstance.Apply(Result.RawData, L); if HRes <> TF_S_OK then begin FillChar(Result.RawData^, L, 0); CipherError(HRes); end; end; procedure TStreamCipher.ApplyToFile(const InName, OutName: string; BufSize: Cardinal); var InStream, OutStream: TStream; begin InStream:= TFileStream.Create(InName, fmOpenRead or fmShareDenyWrite); try OutStream:= TFileStream.Create(OutName, fmCreate); try ApplyToStream(InStream, OutStream, BufSize); finally OutStream.Free; end; finally InStream.Free; end; end; procedure TStreamCipher.ApplyToStream(InStream, OutStream: TStream; BufSize: Cardinal); const MIN_BUFSIZE = 4 * 1024; MAX_BUFSIZE = 4 * 1024 * 1024; DEFAULT_BUFSIZE = 16 * 1024; PAD_BUFSIZE = TF_MAX_CIPHER_BLOCK_SIZE; var DataSize: Cardinal; Data, PData: PByte; N: Integer; Cnt: Cardinal; begin if (BufSize < MIN_BUFSIZE) or (BufSize > MAX_BUFSIZE) then BufSize:= DEFAULT_BUFSIZE else BufSize:= (BufSize + PAD_BUFSIZE - 1) and not (PAD_BUFSIZE - 1); GetMem(Data, BufSize); try repeat Cnt:= BufSize; PData:= Data; repeat N:= InStream.Read(PData^, Cnt); if N <= 0 then Break; Inc(PData, N); Dec(Cnt, N); until (Cnt = 0); DataSize:= BufSize - Cnt; if DataSize > 0 then begin Apply(Data^, DataSize); OutStream.WriteBuffer(Data^, DataSize); FillChar(Data^, DataSize, 0); end; until Cnt > 0; finally FreeMem(Data); end; end; (* {$IFNDEF TFL_DLL} initialization GetCipherServerInstance(FServer); {$ENDIF} *) end.
unit atListHelper; // Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atListHelper.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatListHelper" MUID: (4A4CDD01023F) interface uses l3IntfUses , BaseTypesUnit , DynamicDocListUnit , DynamicTreeUnit , l3_Base ; const SON_ASCENDING = 'по возрастанию'; SON_DESCENDING = 'по убыванию'; STN_CREATE_DATE = 'по дате издания'; STN_LAST_EDIT_DATE = 'по дате последнего изменения'; STN_PRIORITY = 'по юридической силе'; STN_RELEVANCE = 'по релевантности'; STN_NOT_SORTED = 'не сортирован'; type _EntityInterface_ = IDynList; {$Include w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atEntityWithName.imp.pas} TatList = class(_atEntityWithName_) private f_Root: INodeBase; protected function pm_GetHistory: AnsiString; function pm_GetRoot: INodeBase; function pm_GetFirstElement: INodeBase; procedure ClearFields; override; public property History: AnsiString read pm_GetHistory; property Root: INodeBase read pm_GetRoot; property FirstElement: INodeBase read pm_GetFirstElement; end;//TatList TatListHelper = class public class function ST2Str(const aSortType: TSortType): AnsiString; virtual; class function Str2ST(const aStr: AnsiString; out theSortType: TSortType): Boolean; virtual; class function SO2Str(const aSortOrder: TSortOrder): AnsiString; virtual; class function Str2SO(const aStr: AnsiString; out theSortOrder: TSortOrder): Boolean; virtual; class function IsCanBeSortedBy(const aList: IDynList; const aSortType: TSortType): Boolean; virtual; class procedure LoadList(const aList: IDynList; const aNodesCount: Integer); virtual; end;//TatListHelper implementation uses l3ImplUses , SysUtils , atNodeHelper , atStringHelper , StrUtils , IOUnit //#UC START# *4A4CDD01023Fimpl_uses* //#UC END# *4A4CDD01023Fimpl_uses* ; {$Include w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atEntityWithName.imp.pas} function TatList.pm_GetHistory: AnsiString; //#UC START# *5051E5520315_4FD24A98029Fget_var* const SUBSTR = '_title">'; var l_Str : IString; i : Integer; //#UC END# *5051E5520315_4FD24A98029Fget_var* begin //#UC START# *5051E5520315_4FD24A98029Fget_impl* Entity.GetHistory(l_Str); Result := TatStringHelper.AStr2DStr(l_Str); // Result := AnsiReplaceText(Result, '</pre>', ''); Result := AnsiReplaceText(Result, '<pre class="rqname">', ''); Result := AnsiReplaceText(Result, '</span>', ''); Result := AnsiReplaceText(Result, '</space>', ''); Result := AnsiReplaceText(Result, '<pre class="space">', ''); Result := AnsiReplaceText(Result, '<pre class="rqval">', #9); i := Pos(SUBSTR, Result); if i <> 0 then Delete(Result, 1, i - 1 + Length(SUBSTR)); Result := Trim(Result); //#UC END# *5051E5520315_4FD24A98029Fget_impl* end;//TatList.pm_GetHistory function TatList.pm_GetRoot: INodeBase; //#UC START# *5051E87C0078_4FD24A98029Fget_var* //#UC END# *5051E87C0078_4FD24A98029Fget_var* begin //#UC START# *5051E87C0078_4FD24A98029Fget_impl* if NOT Assigned(f_Root) then Entity.GetRoot(f_Root); Result := f_Root; //#UC END# *5051E87C0078_4FD24A98029Fget_impl* end;//TatList.pm_GetRoot function TatList.pm_GetFirstElement: INodeBase; //#UC START# *5051E8E7028C_4FD24A98029Fget_var* //#UC END# *5051E8E7028C_4FD24A98029Fget_var* begin //#UC START# *5051E8E7028C_4FD24A98029Fget_impl* Root.GetFirstChild(Result); //#UC END# *5051E8E7028C_4FD24A98029Fget_impl* end;//TatList.pm_GetFirstElement procedure TatList.ClearFields; begin f_Root := nil; inherited; end;//TatList.ClearFields class function TatListHelper.ST2Str(const aSortType: TSortType): AnsiString; //#UC START# *4A4CDE0A001A_4A4CDD01023F_var* //#UC END# *4A4CDE0A001A_4A4CDD01023F_var* begin //#UC START# *4A4CDE0A001A_4A4CDD01023F_impl* case aSortType of ST_PRIORITY : Result := STN_PRIORITY; ST_CREATE_DATE : Result := STN_CREATE_DATE; ST_LAST_EDIT_DATE : Result := STN_LAST_EDIT_DATE; ST_NOT_SORTED : Result := STN_NOT_SORTED; ST_RELEVANCE : Result := STN_RELEVANCE; end; //#UC END# *4A4CDE0A001A_4A4CDD01023F_impl* end;//TatListHelper.ST2Str class function TatListHelper.Str2ST(const aStr: AnsiString; out theSortType: TSortType): Boolean; //#UC START# *4A4CDE1F03C0_4A4CDD01023F_var* //#UC END# *4A4CDE1F03C0_4A4CDD01023F_var* begin //#UC START# *4A4CDE1F03C0_4A4CDD01023F_impl* Result := true; if AnsiSameText(aStr, STN_CREATE_DATE) then theSortType := ST_CREATE_DATE else if AnsiSameText(aStr, STN_LAST_EDIT_DATE) then theSortType := ST_LAST_EDIT_DATE else if AnsiSameText(aStr, STN_PRIORITY) then theSortType := ST_PRIORITY else if AnsiSameText(aStr, STN_RELEVANCE) then theSortType := ST_RELEVANCE else if AnsiSameText(aStr, STN_NOT_SORTED) then theSortType := ST_NOT_SORTED else Result := false; //#UC END# *4A4CDE1F03C0_4A4CDD01023F_impl* end;//TatListHelper.Str2ST class function TatListHelper.SO2Str(const aSortOrder: TSortOrder): AnsiString; //#UC START# *4A4CDE34010F_4A4CDD01023F_var* //#UC END# *4A4CDE34010F_4A4CDD01023F_var* begin //#UC START# *4A4CDE34010F_4A4CDD01023F_impl* case aSortOrder of SO_ASCENDING : Result := SON_ASCENDING; SO_DESCENDING : Result := SON_DESCENDING; end; //#UC END# *4A4CDE34010F_4A4CDD01023F_impl* end;//TatListHelper.SO2Str class function TatListHelper.Str2SO(const aStr: AnsiString; out theSortOrder: TSortOrder): Boolean; //#UC START# *4A4CDE4B033B_4A4CDD01023F_var* //#UC END# *4A4CDE4B033B_4A4CDD01023F_var* begin //#UC START# *4A4CDE4B033B_4A4CDD01023F_impl* Result := true; if AnsiSameText(aStr, SON_ASCENDING) then theSortOrder := SO_ASCENDING else if AnsiSameText(aStr, SON_DESCENDING) then theSortOrder := SO_DESCENDING else Result := false; //#UC END# *4A4CDE4B033B_4A4CDD01023F_impl* end;//TatListHelper.Str2SO class function TatListHelper.IsCanBeSortedBy(const aList: IDynList; const aSortType: TSortType): Boolean; //#UC START# *4A4CDEEE00C0_4A4CDD01023F_var* var l_SortTypes : ISortTypes; i : integer; //#UC END# *4A4CDEEE00C0_4A4CDD01023F_var* begin //#UC START# *4A4CDEEE00C0_4A4CDD01023F_impl* Result := false; aList.GetAvailableSortTypes(l_SortTypes); Assert(l_SortTypes <> nil, 'l_SortTypes <> nil'); i := 0; while ((i < l_SortTypes.Count) AND (NOT Result)) do begin Result := l_SortTypes.Items[i] = aSortType; Inc(i); end; //#UC END# *4A4CDEEE00C0_4A4CDD01023F_impl* end;//TatListHelper.IsCanBeSortedBy class procedure TatListHelper.LoadList(const aList: IDynList; const aNodesCount: Integer); //#UC START# *4A4DE6530114_4A4CDD01023F_var* var l_Root : INodeBase; //#UC END# *4A4DE6530114_4A4CDD01023F_var* begin //#UC START# *4A4DE6530114_4A4CDD01023F_impl* aList.GetRoot(l_Root); TatNodeHelper.LoadNodes(l_Root, 0, aNodesCount, TatNodeCallbacks.CallNodeCaption); //#UC END# *4A4DE6530114_4A4CDD01023F_impl* end;//TatListHelper.LoadList end.
unit UCoreUtils; { Copyright (c) 2018 by PascalCoin Project Contains common types for Core module. Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. Acknowledgements: Herman Schoenfeld <herman@sphere10.com>: unit creator Ugochukwu Mmaduekwe - added TOperationsManager class } {$mode delphi} interface uses Classes, SysUtils, UCrypto, UAccounts, UBlockChain, UOpTransaction, UNode, UCommon, UNetProtocol, Generics.Collections, Generics.Defaults, UCoreObjects, Forms, Dialogs, LCLType, UCellRenderers; type { TAccountComparer } TAccountComparer = class(TComparer<TAccount>) function Compare(constref ALeft, ARight: T): integer; override; class function DoCompare(constref ALeft, ARight: TAccount): integer; inline; end; { TAccountEqualityComparer } TAccountEqualityComparer = class(TEqualityComparer<TAccount>) public function Equals(constref ALeft, ARight: TAccount): boolean; override; function GetHashCode(constref AValue: TAccount): UInt32; override; class function AreEqual(constref ALeft, ARight: TAccount): boolean; class function CalcHashCode(constref AValue: TAccount): UInt32; end; { TAccountKeyComparer } TAccountKeyComparer = class(TComparer<TAccountKey>) function Compare(constref ALeft, ARight: T): integer; override; class function DoCompare(constref ALeft, ARight: TAccountKey): integer; inline; end; { TAccountKeyEqualityComparer } TAccountKeyEqualityComparer = class(TEqualityComparer<TAccountKey>) public function Equals(constref ALeft, ARight: TAccountKey): boolean; override; function GetHashCode(constref AValue: TAccountKey): UInt32; override; class function AreEqual(constref ALeft, ARight: TAccountKey): boolean; class function CalcHashCode(constref AValue: TAccountKey): UInt32; end; { TCoreTool } TCoreTool = class public class function GetSignerCandidates(ANumOps: integer; ASingleOperationFee: int64; const ACandidates: array of TAccount): TArray<TAccount>; static; end; { TOperationsManager } TOperationsManager = class private class function UpdatePayload(const ASenderPublicKey, ADestinationPublicKey: TAccountKey; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent: string; var AEncodedPayloadBytes: TRawBytes; const APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; class function SendPASCFinalizeAndDisplayMessage(const AOperationsTxt, AOperationToString: string; ANoOfOperations: integer; ATotalAmount, ATotalFee: int64; AOperationsHashTree: TOperationsHashTree; var AErrorMessage: string): boolean; static; class function OthersFinalizeAndDisplayMessage(const AOperationsTxt, AOperationToString: string; ANoOfOperations: integer; ATotalFee: int64; AOperationsHashTree: TOperationsHashTree; var AErrorMessage: string): boolean; static; public class function GetOperationShortText(const OpType, OpSubType: DWord): ansistring; static; inline; class function ExecuteOperations(const ANewOps: TExecuteOperationsModel; AHandler: TExecuteOperationsModel.TOperationExecuteResultHandler; var errors: ansistring): boolean; static; class function ExecuteSendPASC(const ASelectedAccounts: TArray<TAccount>; const ADestinationAccount, ASignerAccount: TAccount; AAmount, AFee: int64; const ASendPASCMode: TExecuteOperationsModel.TSendPASCMode; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; static; class function ExecuteChangeKey(const ASelectedAccounts: TArray<TAccount>; const ASignerAccount: TAccount; APublicKey: TAccountKey; AFee: int64; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; static; class function ExecuteEnlistAccountForSale(const ASelectedAccounts: TArray<TAccount>; const ASignerAccount, ASellerAccount: TAccount; const APublicKey: TAccountKey; AFee, ASalePrice: int64; ALockedUntilBlock: UInt32; const AAccountSaleMode: TExecuteOperationsModel.TAccountSaleMode; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; static; end; { TOrderedAccountKeysListHelper } TOrderedAccountKeysListHelper = class helper for TOrderedAccountKeysList public function GetBalance(IncludePending: boolean = False): TBalanceSummary; function GetAccounts(IncludePending: boolean = False): TArray<TAccount>; function GetAccountNumbers: TArray<cardinal>; end; { TSafeBoxHelper } TSafeBoxHelper = class helper for TPCSafeBox private function GetBalanceInternal(const AKeys: array of TAccountKey; IncludePending: boolean = False): TBalanceSummary; public function GetModifiedAccounts(const AAccounts: array of TAccount): TArray<TAccount>; function GetBalance(const AKey: TAccountKey; IncludePending: boolean = False): TBalanceSummary; overload; function GetBalance(const AKeys: array of TAccountKey; IncludePending: boolean = False): TBalanceSummary; overload; end; { TNodeHelper } TNodeHelper = class helper for TNode function HasBestKnownBlockchainTip: boolean; end; { TAccountHelper } TAccountHelper = record helper for TAccount function GetAccountString : AnsiString; function GetDisplayString : AnsiString; function GetInfoText(const ABank : TPCBank) : utf8string; property AccountString : AnsiString read GetAccountString; property DisplayString : AnsiString read GetDisplayString; end; { TOperationResumeHelper } TOperationResumeHelper = record helper for TOperationResume function GetPrintableOPHASH : AnsiString; function GetInfoText(const ABank : TPCBank) : utf8string; end; { TTimeSpanHelper } TTimeSpanHelper = record helper for TTimeSpan function TotalBlockCount : Integer; end; implementation uses UMemory, UConst, UWallet, UECIES, UAES; { TOperationsManager } class function TOperationsManager.SendPASCFinalizeAndDisplayMessage(const AOperationsTxt, AOperationToString: string; ANoOfOperations: integer; ATotalAmount, ATotalFee: int64; AOperationsHashTree: TOperationsHashTree; var AErrorMessage: string): boolean; var LAuxs, LOperationsTxt: string; i: integer; begin LOperationsTxt := AOperationsTxt; if (ANoOfOperations > 1) then begin LAuxs := 'Total amount that dest will receive: ' + TAccountComp.FormatMoney( ATotalAmount) + #10; if Application.MessageBox( PChar('Execute ' + IntToStr(ANoOfOperations) + ' operations?' + #10 + 'Operation: ' + LOperationsTxt + #10 + LAuxs + 'Total fee: ' + TAccountComp.FormatMoney(ATotalFee) + #10 + #10 + 'Note: This operation will be transmitted to the network!'), PChar(Application.Title), MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2) <> idYes then Exit; end else if Application.MessageBox(PChar('Execute this operation:' + #10 + #10 + AOperationToString + #10 + #10 + 'Note: This operation will be transmitted to the network!'), PChar(Application.Title), MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2) <> idYes then Exit; Result := True; i := TNode.Node.AddOperations(nil, AOperationsHashTree, nil, AErrorMessage); if (i = AOperationsHashTree.OperationsCount) then begin LOperationsTxt := 'Successfully executed ' + IntToStr(i) + ' operations!' + #10 + #10 + AOperationToString; if i > 1 then ShowMessage(LOperationsTxt) else begin Application.MessageBox( PChar('Successfully executed ' + IntToStr(i) + ' operations!' + #10 + #10 + AOperationToString), PChar(Application.Title), MB_OK + MB_ICONINFORMATION); end; end else if (i > 0) then begin LOperationsTxt := 'One or more of your operations has not been executed:' + #10 + 'Errors:' + #10 + AErrorMessage + #10 + #10 + 'Total successfully executed operations: ' + IntToStr(i); ShowMessage(LOperationsTxt); end else Result := False; end; class function TOperationsManager.UpdatePayload(const ASenderPublicKey, ADestinationPublicKey: TAccountKey; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent: string; var AEncodedPayloadBytes: TRawBytes; const APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; var LValid: boolean; begin if (APayloadContent = '') then Exit(True); LValid := False; AErrorMessage := 'An Error Occured During Payload Encryption.'; try case APayloadEncryptionMode of akaEncryptWithSender: begin // Use sender public key AEncodedPayloadBytes := ECIESEncrypt(ASenderPublicKey, APayloadContent); LValid := AEncodedPayloadBytes <> ''; end; akaEncryptWithReceiver: begin // With destination public key AEncodedPayloadBytes := ECIESEncrypt(ADestinationPublicKey, APayloadContent); LValid := AEncodedPayloadBytes <> ''; end; akaEncryptWithPassword: begin // With defined password if APayloadEncryptionPassword = '' then begin AErrorMessage := 'Payload Encryption Password Cannot Be Empty With The Chosen Option : "Encrypt With Password."'; Exit(False); end; AEncodedPayloadBytes := TAESComp.EVP_Encrypt_AES256( APayloadContent, APayloadEncryptionPassword); LValid := AEncodedPayloadBytes <> ''; end; akaNotEncrypt: begin // no encryption AEncodedPayloadBytes := APayloadContent; LValid := True; end else begin AErrorMessage := 'Unknown Encryption Selected'; Exit(False); end; end; finally if LValid then if Length(AEncodedPayloadBytes) > CT_MaxPayloadSize then begin LValid := False; AErrorMessage := Format('Payload Size Is %d Which Is Bigger Than %d', [Length(AEncodedPayloadBytes), CT_MaxPayloadSize]); end; Result := LValid; end; end; class function TOperationsManager.OthersFinalizeAndDisplayMessage(const AOperationsTxt, AOperationToString: string; ANoOfOperations: integer; ATotalFee: int64; AOperationsHashTree: TOperationsHashTree; var AErrorMessage: string): boolean; var LAuxs, LOperationsTxt: string; i: integer; begin LOperationsTxt := AOperationsTxt; if (ANoOfOperations > 1) then begin LAuxs := ''; if Application.MessageBox( PChar('Execute ' + IntToStr(ANoOfOperations) + ' operations?' + #10 + 'Operation: ' + LOperationsTxt + #10 + LAuxs + 'Total fee: ' + TAccountComp.FormatMoney(ATotalFee) + #10 + #10 + 'Note: This operation will be transmitted to the network!'), PChar(Application.Title), MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2) <> idYes then Exit; end else if Application.MessageBox(PChar('Execute this operation:' + #10 + #10 + AOperationToString + #10 + #10 + 'Note: This operation will be transmitted to the network!'), PChar(Application.Title), MB_YESNO + MB_ICONINFORMATION + MB_DEFBUTTON2) <> idYes then Exit; Result := True; i := TNode.Node.AddOperations(nil, AOperationsHashTree, nil, AErrorMessage); if (i = AOperationsHashTree.OperationsCount) then begin LOperationsTxt := 'Successfully executed ' + IntToStr(i) + ' operations!' + #10 + #10 + AOperationToString; if i > 1 then ShowMessage(LOperationsTxt) else begin Application.MessageBox( PChar('Successfully executed ' + IntToStr(i) + ' operations!' + #10 + #10 + AOperationToString), PChar(Application.Title), MB_OK + MB_ICONINFORMATION); end; end else if (i > 0) then begin LOperationsTxt := 'One or more of your operations has not been executed:' + #10 + 'Errors:' + #10 + AErrorMessage + #10 + #10 + 'Total successfully executed operations: ' + IntToStr(i); ShowMessage(LOperationsTxt); end else Result := False; end; class function TOperationsManager.ExecuteOperations(const ANewOps: TExecuteOperationsModel; AHandler: TExecuteOperationsModel.TOperationExecuteResultHandler; var errors: ansistring): boolean; begin end; class function TOperationsManager.GetOperationShortText(const OpType, OpSubType: DWord): ansistring; begin case OpType of CT_PseudoOp_Reward: case OpSubType of 0, CT_PseudoOpSubtype_Miner : result := 'Miner Reward'; CT_PseudoOpSubtype_Developer : result := 'Developer Reward'; else result := 'Unknown'; end; CT_Op_Transaction: case OpSubType of CT_OpSubtype_TransactionSender: Result := 'Send'; CT_OpSubtype_TransactionReceiver: Result := 'Receive'; CT_OpSubtype_BuyTransactionBuyer: result := 'Buy Account Direct'; CT_OpSubtype_BuyTransactionTarget: result := 'Purchased Account Direct'; CT_OpSubtype_BuyTransactionSeller: result := 'Sold Account Direct'; else result := 'Unknown'; end; CT_Op_Changekey: Result := 'Change Key (legacy)'; CT_Op_Recover: Result := 'Recover'; CT_Op_ListAccountForSale: case OpSubType of CT_OpSubtype_ListAccountForPublicSale: result := 'For Sale'; CT_OpSubtype_ListAccountForPrivateSale: result := 'Exclusive Sale'; else result := 'Unknown'; end; CT_Op_DelistAccount: result := 'Remove Sale'; CT_Op_BuyAccount: case OpSubType of CT_OpSubtype_BuyAccountBuyer: result := 'Buy Account'; CT_OpSubtype_BuyAccountTarget: result := 'Purchased Account'; CT_OpSubtype_BuyAccountSeller: result := 'Sold Account'; else result := 'Unknown'; end; CT_Op_ChangeKeySigned: result := 'Change Key'; CT_Op_ChangeAccountInfo: result := 'Change Info'; CT_Op_MultiOperation: case OpSubType of CT_OpSubtype_MultiOperation_Global: Result := 'Mixed-Transfer'; CT_OpSubtype_MultiOperation_AccountInfo: Result := 'Mixed-Change'; end; else result := 'Unknown'; end; end; class function TOperationsManager.ExecuteSendPASC(const ASelectedAccounts: TArray<TAccount>; const ADestinationAccount, ASignerAccount: TAccount; AAmount, AFee: int64; const ASendPASCMode: TExecuteOperationsModel.TSendPASCMode; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; var LWalletKey: TWalletKey; LWalletKeys: TWalletKeys; LNode: TNode; LPCOperation: TPCOperation; LOperationsHashTree: TOperationsHashTree; LTotalAmount, LTotalSignerFee, LAmount, LFee: int64; LDoOperation: boolean; LOperationsTxt, LOperationToString: string; LIdx, LAccountIdx, LNoOfOperations: integer; LCurrentAccount: TAccount; LPayloadEncodedBytes: TRawBytes; begin if Length(ASelectedAccounts) = 0 then begin AErrorMessage := 'No Selected Account Found'; Exit(False); end; LWalletKeys := TWallet.Keys; LNode := TNode.Node; if not Assigned(LWalletKeys) then begin AErrorMessage := 'No Wallet Keys Found'; Exit(False); end; if not Assigned(LNode) then begin AErrorMessage := 'No Node Found'; Exit(False); end; LOperationsHashTree := TOperationsHashTree.Create; try LTotalAmount := 0; LTotalSignerFee := 0; LNoOfOperations := 0; LOperationsTxt := ''; LOperationToString := ''; for LAccountIdx := Low(ASelectedAccounts) to High(ASelectedAccounts) do begin LPCOperation := nil; // reset LPCOperation to Nil LCurrentAccount := ASelectedAccounts[LAccountIdx]; if LCurrentAccount.account = ADestinationAccount.account then begin AErrorMessage := Format('Sender "%s" And Destination "%s" Accounts Are The Same', [LCurrentAccount.AccountString, ADestinationAccount.AccountString]); Exit(False); end; if not UpdatePayload(LCurrentAccount.accountInfo.accountKey, ADestinationAccount.accountInfo.accountKey, APayloadEncryptionMode, APayloadContent, LPayloadEncodedBytes, APayloadEncryptionPassword, AErrorMessage) then begin AErrorMessage := Format('Error Encoding Payload Of Selected Account "%s. ", Specific Error Is "%s"', [LCurrentAccount.AccountString, AErrorMessage]); Exit(False); end; LIdx := LWalletKeys.IndexOfAccountKey(LCurrentAccount.accountInfo.accountKey); if LIdx < 0 then begin AErrorMessage := Format('Selected Account "%s" Private Key Not Found In Wallet', [LCurrentAccount.AccountString]); Exit(False); end; LWalletKey := LWalletKeys.Key[LIdx]; if not Assigned(LWalletKey.PrivateKey) then begin if LWalletKey.HasPrivateKey then AErrorMessage := 'Wallet is Password Protected. Please Unlock Before You Proceed.' else AErrorMessage := Format('Only Public Key of Account %s Was Found in Wallet. You Cannot Operate This Account', [LCurrentAccount.AccountString]); Exit(False); end; LDoOperation := True; if LCurrentAccount.balance > 0 then case ASendPASCMode of akaAllBalance: begin LAmount := LCurrentAccount.balance - AFee; LFee := AFee; end; akaSpecifiedAmount: if LCurrentAccount.balance >= UInt64(AAmount + AFee) then begin LAmount := AAmount; LFee := AFee; end else begin AErrorMessage := Format('Insufficient Funds In "%s". %s < (%s + %s = %s)', [LCurrentAccount.AccountString, TAccountComp.FormatMoney(LCurrentAccount.balance), TAccountComp.FormatMoney(AAmount), TAccountComp.FormatMoney(AFee), TAccountComp.FormatMoney(AAmount + AFee)]); Exit(False); end; end else LDoOperation := False; if LDoOperation then begin LPCOperation := TOpTransaction.CreateTransaction( LCurrentAccount.account, LCurrentAccount.n_operation + 1, ADestinationAccount.account, LWalletKey.PrivateKey, LAmount, LFee, LPayloadEncodedBytes); try LOperationsTxt := Format('Transaction To "%s"', [ADestinationAccount.AccountString]); if Assigned(LPCOperation) then begin LOperationsHashTree.AddOperationToHashTree(LPCOperation); Inc(LTotalAmount, LAmount); Inc(LTotalSignerFee, LFee); Inc(LNoOfOperations); if LOperationToString <> '' then LOperationToString := LOperationToString + #10; LOperationToString := LOperationToString + LPCOperation.ToString; end; finally FreeAndNil(LPCOperation); end; end; end; if (LOperationsHashTree.OperationsCount = 0) then begin AErrorMessage := 'No Valid Operation To Execute'; Exit(False); end; Exit(TOperationsManager.SendPASCFinalizeAndDisplayMessage(LOperationsTxt, LOperationToString, LNoOfOperations, LTotalAmount, LTotalSignerFee, LOperationsHashTree, AErrorMessage)); finally LOperationsHashTree.Free; end; end; class function TOperationsManager.ExecuteChangeKey(const ASelectedAccounts: TArray<TAccount>; const ASignerAccount: TAccount; APublicKey: TAccountKey; AFee: int64; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; var LWalletKey: TWalletKey; LWalletKeys: TWalletKeys; LNode: TNode; LPCOperation: TPCOperation; LOperationsHashTree: TOperationsHashTree; LTotalSignerFee, LFee: int64; LIsV2: boolean; LOperationsTxt, LOperationToString: string; LIdx, LAccountIdx, LNoOfOperations: integer; LCurrentAccount, LSignerAccount: TAccount; LPayloadEncodedBytes: TRawBytes; label loop_start; begin if Length(ASelectedAccounts) = 0 then begin AErrorMessage := 'No Selected Account Found'; Exit(False); end; LWalletKeys := TWallet.Keys; LNode := TNode.Node; if not Assigned(LWalletKeys) then begin AErrorMessage := 'No Wallet Keys Found'; Exit(False); end; if not Assigned(LNode) then begin AErrorMessage := 'No Node Found'; Exit(False); end; LOperationsHashTree := TOperationsHashTree.Create; try LIsV2 := LNode.Bank.SafeBox.CurrentProtocol >= CT_PROTOCOL_2; LTotalSignerFee := 0; LNoOfOperations := 0; LOperationsTxt := ''; LOperationToString := ''; for LAccountIdx := Low(ASelectedAccounts) to High(ASelectedAccounts) do begin loop_start: LPCOperation := nil; // reset LPCOperation to Nil LCurrentAccount := ASelectedAccounts[LAccountIdx]; if (TAccountComp.EqualAccountKeys(LCurrentAccount.accountInfo.accountKey, APublicKey)) then begin AErrorMessage := 'New Key Is Same As Current Key'; Exit(False); end; if LNode.Bank.SafeBox.CurrentProtocol >= 1 then begin // Signer: LSignerAccount := ASignerAccount; if (TAccountComp.IsAccountLocked(LSignerAccount.accountInfo, LNode.Bank.BlocksCount)) then begin AErrorMessage := Format('Signer Account "%s" Is Locked Until Block %u', [LSignerAccount.AccountString, LSignerAccount.accountInfo.locked_until_block]); Exit(False); end; if (not TAccountComp.EqualAccountKeys( LSignerAccount.accountInfo.accountKey, LCurrentAccount.accountInfo.accountKey)) then begin AErrorMessage := Format('Signer Account %s Is Not The Owner Of Account %s', [LSignerAccount.AccountString, LCurrentAccount.AccountString]); Exit(False); end; end else LSignerAccount := LCurrentAccount; if not UpdatePayload(LCurrentAccount.accountInfo.accountKey, APublicKey, APayloadEncryptionMode, APayloadContent, LPayloadEncodedBytes, APayloadEncryptionPassword, AErrorMessage) then begin AErrorMessage := Format('Error Encoding Payload Of Selected Account "%s. ", Specific Error Is "%s"', [LCurrentAccount.AccountString, AErrorMessage]); Exit(False); end; LIdx := LWalletKeys.IndexOfAccountKey(LCurrentAccount.accountInfo.accountKey); if LIdx < 0 then begin AErrorMessage := Format('Selected Account "%s" Private Key Not Found In Wallet', [LCurrentAccount.AccountString]); Exit(False); end; LWalletKey := LWalletKeys.Key[LIdx]; if not Assigned(LWalletKey.PrivateKey) then begin if LWalletKey.HasPrivateKey then AErrorMessage := 'Wallet Is Password Protected. Please Unlock Before You Proceed.' else AErrorMessage := Format('Only Public Key of Account %s Was Found In Wallet. You Cannot Operate This Account', [LCurrentAccount.AccountString]); Exit(False); end; if LIsV2 then begin // must ensure is Signer account last if included in sender accounts (not necessarily ordered enumeration) if (LAccountIdx < Length(ASelectedAccounts) - 1) and (LCurrentAccount.account = LSignerAccount.account) then begin TArrayTool<TAccount>.Swap(ASelectedAccounts, LAccountIdx, Length(ASelectedAccounts) - 1); // ensure signer account processed last goto loop_start; // TODO: remove ugly hack with refactoring! end; // Maintain correct signer fee distribution if Uint64(LTotalSignerFee) >= LSignerAccount.balance then LFee := 0 else if LSignerAccount.balance - uint64(LTotalSignerFee) > UInt64(AFee) then LFee := AFee else LFee := LSignerAccount.balance - UInt64(LTotalSignerFee); LPCOperation := TOpChangeKeySigned.Create(LSignerAccount.account, LSignerAccount.n_operation + LNoOfOperations + 1, LCurrentAccount.account, LWalletKey.PrivateKey, APublicKey, LFee, LPayloadEncodedBytes); end else LPCOperation := TOpChangeKey.Create(LCurrentAccount.account, LCurrentAccount.n_operation + 1, LCurrentAccount.account, LWalletKey.PrivateKey, APublicKey, LFee, LPayloadEncodedBytes); try LOperationsTxt := Format('Change Key To "%s"', [TAccountComp.GetECInfoTxt(APublicKey.EC_OpenSSL_NID)]); if Assigned(LPCOperation) then begin LOperationsHashTree.AddOperationToHashTree(LPCOperation); Inc(LNoOfOperations); Inc(LTotalSignerFee, LFee); if LOperationToString <> '' then LOperationToString := LOperationToString + #10; LOperationToString := LOperationToString + LPCOperation.ToString; end; finally FreeAndNil(LPCOperation); end; end; if (LOperationsHashTree.OperationsCount = 0) then begin AErrorMessage := 'No Valid Operation to Execute'; Exit(False); end; Exit(TOperationsManager.OthersFinalizeAndDisplayMessage(LOperationsTxt, LOperationToString, LNoOfOperations, LTotalSignerFee, LOperationsHashTree, AErrorMessage)); finally LOperationsHashTree.Free; end; end; class function TOperationsManager.ExecuteEnlistAccountForSale(const ASelectedAccounts: TArray<TAccount>; const ASignerAccount, ASellerAccount: TAccount; const APublicKey: TAccountKey; AFee, ASalePrice: int64; ALockedUntilBlock: UInt32; const AAccountSaleMode: TExecuteOperationsModel.TAccountSaleMode; const APayloadEncryptionMode: TExecuteOperationsModel.TPayloadEncryptionMode; const APayloadContent, APayloadEncryptionPassword: string; var AErrorMessage: string): boolean; var LWalletKey: TWalletKey; LWalletKeys: TWalletKeys; LNode: TNode; LPCOperation: TPCOperation; LOperationsHashTree: TOperationsHashTree; LTotalSignerFee, LFee: int64; LOperationsTxt, LOperationToString: string; LIdx, LAccountIdx, LNoOfOperations: integer; LCurrentAccount, LSignerAccount: TAccount; LPayloadEncodedBytes: TRawBytes; begin if Length(ASelectedAccounts) = 0 then begin AErrorMessage := 'No Selected Account Found'; Exit(False); end; LWalletKeys := TWallet.Keys; LNode := TNode.Node; if not Assigned(LWalletKeys) then begin AErrorMessage := 'No Wallet Keys Found'; Exit(False); end; if not Assigned(LNode) then begin AErrorMessage := 'No Node Found'; Exit(False); end; LOperationsHashTree := TOperationsHashTree.Create; try LTotalSignerFee := 0; LNoOfOperations := 0; LOperationsTxt := ''; LOperationToString := ''; for LAccountIdx := Low(ASelectedAccounts) to High(ASelectedAccounts) do begin LPCOperation := nil; // reset LPCOperation to Nil LCurrentAccount := ASelectedAccounts[LAccountIdx]; if TAccountComp.IsAccountForSale(LCurrentAccount.accountInfo) then begin AErrorMessage := Format('Account "%s" Is Already Enlisted For Sale', [LCurrentAccount.AccountString]); Exit(False); end; if (ASellerAccount.account = LCurrentAccount.account) then begin AErrorMessage := 'Seller Account Cannot Be Same As Account To Be Sold.'; Exit(False); end; if (LNode.Node.Bank.SafeBox.CurrentProtocol = CT_PROTOCOL_1) then begin AErrorMessage := 'This Operation Needs PROTOCOL 2 Active'; Exit(False); end; if AAccountSaleMode = akaPrivateSale then begin if TAccountComp.EqualAccountKeys(APublicKey, LCurrentAccount.accountInfo.accountKey) then begin AErrorMessage := 'You Cannot Sell To An Account That You Want To Enlist For Sale.'; Exit(False); end; if ALockedUntilBlock = 0 then begin AErrorMessage := 'You Didn''t Insert a Locking Block.'; Exit(False); end; end; if not UpdatePayload(LCurrentAccount.accountInfo.accountKey, APublicKey, APayloadEncryptionMode, APayloadContent, LPayloadEncodedBytes, APayloadEncryptionPassword, AErrorMessage) then begin AErrorMessage := Format('Error Encoding Payload Of Selected Account "%s. ", Specific Error Is "%s"', [LCurrentAccount.AccountString, AErrorMessage]); Exit(False); end; LIdx := LWalletKeys.IndexOfAccountKey(LCurrentAccount.accountInfo.accountKey); if LIdx < 0 then begin AErrorMessage := Format('Selected Account "%s" Private Key Not Found In Wallet', [LCurrentAccount.AccountString]); Exit(False); end; LWalletKey := LWalletKeys.Key[LIdx]; if not Assigned(LWalletKey.PrivateKey) then begin if LWalletKey.HasPrivateKey then AErrorMessage := 'Wallet Is Password Protected. Please Unlock Before You Proceed.' else AErrorMessage := Format('Only Public Key Of Account %s Was Found In Wallet. You Cannot Operate This Account', [LCurrentAccount.AccountString]); Exit(False); end; if ASignerAccount.balance > AFee then LFee := AFee else LFee := ASignerAccount.balance; case AAccountSaleMode of akaPublicSale: LPCOperation := TOpListAccountForSale.CreateListAccountForSale( ASignerAccount.account, ASignerAccount.n_operation + 1 + LAccountIdx, LCurrentAccount.account, ASalePrice, LFee, ASellerAccount.account, APublicKey, 0, LWalletKey.PrivateKey, LPayloadEncodedBytes); akaPrivateSale: LPCOperation := TOpListAccountForSale.CreateListAccountForSale( ASignerAccount.account, ASignerAccount.n_operation + 1 + LAccountIdx, LCurrentAccount.account, ASalePrice, LFee, ASellerAccount.account, APublicKey, ALockedUntilBlock, LWalletKey.PrivateKey, LPayloadEncodedBytes) else raise Exception.Create('Invalid Account Sale Type') end; try LOperationsTxt := Format('Enlist Account For Sale At a Price Of "%s" PASC', [TAccountComp.FormatMoney(ASalePrice)]); if Assigned(LPCOperation) then begin LOperationsHashTree.AddOperationToHashTree(LPCOperation); Inc(LNoOfOperations); Inc(LTotalSignerFee, LFee); if LOperationToString <> '' then LOperationToString := LOperationToString + #10; LOperationToString := LOperationToString + LPCOperation.ToString; end; finally FreeAndNil(LPCOperation); end; end; if (LOperationsHashTree.OperationsCount = 0) then begin AErrorMessage := 'No Valid Operation to Execute'; Exit(False); end; Exit(TOperationsManager.OthersFinalizeAndDisplayMessage(LOperationsTxt, LOperationToString, LNoOfOperations, LTotalSignerFee, LOperationsHashTree, AErrorMessage)); finally LOperationsHashTree.Free; end; end; { TCoreTool } class function TCoreTool.GetSignerCandidates(ANumOps: integer; ASingleOperationFee: int64; const ACandidates: array of TAccount): TArray<TAccount>; var i, PoorSenderCount: integer; Fee, maxSignerFee, minSignerFee: int64; acc: TAccount; begin //make deep copy of accounts!!! Very Important Result := TArrayTool<TAccount>.Copy(ACandidates); Fee := ASingleOperationFee; PoorSenderCount := 0; for i := Low(Result) to High(Result) do begin acc := Result[i]; if (acc.Balance < Fee) then Inc(PoorSenderCount); end; maxSignerFee := ANumOps * Fee; minSignerFee := maxSignerFee - (PoorSenderCount * Fee); for i := High(Result) downto Low(Result) do begin acc := Result[i]; if not (acc.Balance >= maxSignerFee) then TArrayTool<TAccount>.RemoveAt(Result, i); end; end; { TNodeHelper } function TNodeHelper.HasBestKnownBlockchainTip: boolean; var LReady: boolean; LMsg: ansistring; begin LReady := Self.Bank.IsReady(LMsg); if LReady and TNetData.NetData.IsGettingNewBlockChainFromClient then Result := Self.Bank.BlocksCount = TNetData.NetData.MaxRemoteOperationBlock.block; end; { TOrderedAccountKeysListHelper } function TOrderedAccountKeysListHelper.GetBalance(IncludePending: boolean = False): TBalanceSummary; var i: integer; LAccs: TArray<TAccount>; begin Result := CT_BalanceSummary_Nil; LAccs := Self.GetAccounts(IncludePending); for i := Low(LAccs) to High(LAccs) do begin Inc(Result.TotalPASA); Inc(Result.TotalPASC, LAccs[i].Balance); end; end; function TOrderedAccountKeysListHelper.GetAccounts(IncludePending: boolean = False): TArray<TAccount>; var i, j: integer; LAccs: TList<TAccount>; LAcc: TAccount; LList: TOrderedCardinalList; Disposables: TDisposables; begin LAccs := Disposables.AddObject(TList<TAccount>.Create) as TList<TAccount>; for i := 0 to Self.Count - 1 do begin LList := Self.AccountKeyList[i]; for j := 0 to LList.Count - 1 do begin if IncludePending then LAcc := TNode.Node.Operations.SafeBoxTransaction.Account(j) else LAcc := TNode.Node.Bank.SafeBox.Account(LList.Get(j)); LAccs.Add(LAcc); end; end; Result := LAccs.ToArray; end; function TOrderedAccountKeysListHelper.GetAccountNumbers: TArray<cardinal>; var i, j: integer; LAccs: TList<cardinal>; LList: TOrderedCardinalList; Disposables: TDisposables; begin LAccs := Disposables.AddObject(TList<cardinal>.Create) as TList<cardinal>; for i := 0 to Self.Count - 1 do begin LList := Self.AccountKeyList[i]; for j := 0 to LList.Count - 1 do LAccs.Add(j); end; Result := LAccs.ToArray; end; { TSafeBoxHelper } function TSafeBoxHelper.GetModifiedAccounts(const AAccounts: array of TAccount): TArray<TAccount>; var i: integer; LChanged: TList<TAccount>; LAcc: TAccount; GC: TDisposables; begin LChanged := GC.AddObject(TList<TAccount>.Create) as TList<TAccount>; for i := Low(AAccounts) to High(AAccounts) do begin LAcc := Self.Account(AAccounts[i].account); if (LAcc.n_Operation <> AAccounts[i].n_operation) or (LAcc.Balance <> AAccounts[i].balance) then LChanged.Add(LAcc); end; Result := LChanged.ToArray; end; function TSafeBoxHelper.GetBalance(const AKey: TAccountKey; IncludePending: boolean = False): TBalanceSummary; begin Result := GetBalance([AKey], IncludePending); end; function TSafeBoxHelper.GetBalance(const AKeys: array of TAccountKey; IncludePending: boolean = False): TBalanceSummary; begin Result := GetBalanceInternal(AKeys, IncludePending); end; function TSafeBoxHelper.GetBalanceInternal(const AKeys: array of TAccountKey; IncludePending: boolean = False): TBalanceSummary; var i: integer; LAcc: TAccount; LAccs: THashSet<TAccount>; LKeys: THashSet<TAccountKey>; GC: TDisposables; begin // Setup local collections LAccs := GC.AddObject(THashSet<TAccount>.Create(TAccountEqualityComparer.Create)) as THashSet<TAccount>; LKeys := GC.AddObject(THashSet<TAccountKey>.Create(TAccountKeyEqualityComparer.Create)) as THashSet<TAccountKey>; // Gather all keys into hashset for i := Low(AKeys) to High(AKeys) do LKeys.Add(AKeys[i]); // Gather all referenced accounts for i := 0 to Self.AccountsCount - 1 do begin LAcc := Self.Account(i); if LKeys.Contains(LAcc.accountInfo.accountKey) then LAccs.Add(LAcc); end; // Build the results Result := CT_BalanceSummary_Nil; for LAcc in LAccs do begin Inc(Result.TotalPASA); Inc(Result.TotalPASC, LAcc.Balance); end; end; { TAccountComparer } function TAccountComparer.Compare(constref ALeft, ARight: TAccount): integer; begin Result := TAccountComparer.DoCompare(ALeft, ARight); end; class function TAccountComparer.DoCompare(constref ALeft, ARight: TAccount): integer; begin Result := TCompare.UInt64(ALeft.account, ARight.account); end; { TAccountEqualityComparer } function TAccountEqualityComparer.Equals(constref ALeft, ARight: TAccount): boolean; begin Result := TAccountEqualityComparer.AreEqual(ALeft, ARight); end; function TAccountEqualityComparer.GetHashCode(constref AValue: TAccount): UInt32; begin Result := TAccountEqualityComparer.CalcHashCode(AValue); end; class function TAccountEqualityComparer.AreEqual(constref ALeft, ARight: TAccount): boolean; begin Result := (ALeft.account = ARight.account) and (ALeft.balance = ARight.balance) and (ALeft.updated_block = ARight.updated_block) and (ALeft.n_operation = ARight.n_operation) and TAccountKeyEqualityComparer.AreEqual(ALeft.accountInfo.accountKey, ARight.accountInfo.accountKey); end; class function TAccountEqualityComparer.CalcHashCode(constref AValue: TAccount): UInt32; begin Result := AValue.account; end; { TAccountKeyComparer } function TAccountKeyComparer.Compare(constref ALeft, ARight: T): integer; begin Result := TAccountKeyComparer.DoCompare(ALeft, ARight); end; class function TAccountKeyComparer.DoCompare(constref ALeft, ARight: TAccountKey): integer; begin Result := BinStrComp(ALeft.x, ARight.x); if Result = 0 then Result := BinStrComp(ALeft.y, ARight.y); end; { TAccountKeyEqualityComparer } function TAccountKeyEqualityComparer.Equals(constref ALeft, ARight: TAccountKey): boolean; begin Result := TAccountKeyEqualityComparer.AreEqual(ALeft, ARight); end; function TAccountKeyEqualityComparer.GetHashCode(constref AValue: TAccountKey): UInt32; begin Result := TAccountKeyEqualityComparer.CalcHashCode(AValue); end; class function TAccountKeyEqualityComparer.AreEqual(constref ALeft, ARight: TAccountKey): boolean; begin Result := TAccountKeyComparer.DoCompare(ALeft, ARight) = 0; end; class function TAccountKeyEqualityComparer.CalcHashCode(constref AValue: TAccountKey): UInt32; begin Result := TEqualityComparer<ansistring>.Default.GetHashCode(IntToStr(AValue.EC_OpenSSL_NID) + AValue.x + AValue.y); end; { TAccountHelper } function TAccountHelper.GetAccountString: ansistring; begin Result := TAccountComp.AccountNumberToAccountTxtNumber(Self.account); end; function TAccountHelper.GetDisplayString: ansistring; begin Result := GetAccountString; if Self.Name <> '' then Result := Result + ': ' + Self.Name; end; function TAccountHelper.GetInfoText(const ABank: TPCBank): utf8string; var builder: TStrings; GC: TDisposables; begin builder := GC.AddObject(TStringList.Create) as TStrings; builder.Append(Format('Account: %s %s Type:%d', [TAccountComp.AccountNumberToAccountTxtNumber(self.account), IIF(Self.Name <> '', 'Name: ' + Self.Name, ''), Self.account_type])); builder.Append(''); builder.Append(Format('Current balance: %s', [TAccountComp.FormatMoney(Self.balance)])); builder.Append(''); builder.Append(Format('Updated on block: %d (%d blocks ago)', [Self.updated_block, ABank.BlocksCount - Self.updated_block])); builder.Append(Format('Public key type: %s', [TAccountComp.GetECInfoTxt(Self.accountInfo.accountKey.EC_OpenSSL_NID)])); builder.Append(Format('Base58 Public key: %s', [TAccountComp.AccountPublicKeyExport(Self.accountInfo.accountKey)])); if TAccountComp.IsAccountForSale(Self.accountInfo) then begin builder.Append(''); builder.Append('** Account is for sale: **'); builder.Append(Format('Price: %s', [TAccountComp.FormatMoney(Self.accountInfo.price)])); builder.Append(Format('Seller account (where to pay): %s', [TAccountComp.AccountNumberToAccountTxtNumber(Self.accountInfo.account_to_pay)])); if TAccountComp.IsAccountForSaleAcceptingTransactions(Self.accountInfo) then begin builder.Append(''); builder.Append('** Private sale **'); builder.Append(Format('New Base58 Public key: %s', [TAccountComp.AccountPublicKeyExport(Self.accountInfo.new_publicKey)])); builder.Append(''); if TAccountComp.IsAccountLocked(Self.accountInfo, ABank.BlocksCount) then builder.Append(Format('PURCHASE IS SECURE UNTIL BLOCK %d (current %d, remains %d)', [Self.accountInfo.locked_until_block, ABank.BlocksCount, Self.accountInfo.locked_until_block - ABank.BlocksCount])) else builder.Append(Format('PURCHASE IS NOT SECURE (Expired on block %d, current %d)', [Self.accountInfo.locked_until_block, ABank.BlocksCount])); end; end; Result := builder.Text; end; { TOperationResumeHelper } function TOperationResumeHelper.GetPrintableOPHASH: ansistring; begin Result := TCrypto.ToHexaString(Self.OperationHash); end; function TOperationResumeHelper.GetInfoText(const ABank: TPCBank): utf8string; var builder: TStrings; GC: TDisposables; begin if (not Self.valid) then exit; builder := GC.AddObject(TStringList.Create) as TStrings; if Self.Block < ABank.BlocksCount then if (Self.NOpInsideBlock >= 0) then builder.Add(Format('Block: %d/%d', [Self.Block, Self.NOpInsideBlock])) else begin builder.Add(Format('Block: %d', [Self.Block])); end else builder.Add('** Pending operation not included on blockchain **'); builder.Add(Format('%s', [Self.OperationTxt])); builder.Add(Format('OpType:%d Subtype:%d', [Self.OpType, Self.OpSubtype])); builder.Add(Format('Operation Hash (ophash): %s', [TCrypto.ToHexaString(Self.OperationHash)])); if (Self.OperationHash_OLD <> '') then builder.Add(Format('Old Operation Hash (old_ophash): %s', [TCrypto.ToHexaString(Self.OperationHash_OLD)])); if (Self.OriginalPayload <> '') then begin builder.Add(Format('Payload length:%d', [length(Self.OriginalPayload)])); if Self.PrintablePayload <> '' then builder.Add(Format('Payload (human): %s', [Self.PrintablePayload])); builder.Add(Format('Payload (Hexadecimal): %s', [TCrypto.ToHexaString(Self.OriginalPayload)])); end; if Self.Balance >= 0 then builder.Add(Format('Final balance: %s', [TAccountComp.FormatMoney(Self.Balance)])); Result := builder.Text; end; { TTimeSpanHelper } function TTimeSpanHelper.TotalBlockCount: integer; begin Result := Round(Self.TotalSeconds / CT_NewLineSecondsAvg); end; end.
unit SofRebuild0to3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm2 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure GetFileList(const Path: String; List: TStrings); var Rec: TSearchRec; begin if FindFirst(Path + '\*.sof', faAnyFile, Rec) = 0 then repeat if (Rec.Name = '.') or (Rec.Name = '..') then Continue; if (Rec.Attr and faDirectory) = 0 then List.Add(Rec.Name); until FindNext(Rec) <> 0; FindClose(Rec); end; procedure TForm2.Button1Click(Sender: TObject); var InFile,OutFile: File; ic: integer; InfName: TStringList; OutFName: string; tempbyte: byte; SOFVersion: byte; begin try InfName:=TStringList.Create; getFileList(ExtractFilePath(Application.ExeName),InfName); for ic := 0 to Infname.Count-1 do begin Memo1.Lines.Add('input: '+ExtractFilePath(Application.ExeName)+'\'+infName.Strings[ic]); Memo1.Lines.Add('output: '+ExtractFilePath(Application.ExeName)+'\3version_'+infName.Strings[ic]); try AssignFile(OutFile,ExtractFilePath(Application.ExeName)+'\3version_'+ infname.Strings[ic]); Rewrite(OutFile,1); AssignFile(InFile,ExtractFilePath(Application.ExeName)+'\'+infName.Strings[ic]); Reset(InFile,1); SOFVErsion:=2; BlockWrite(OutFile,SOFVersion,1); while not EOF(InFile) do begin BlockRead(inFile,tempbyte,1); BlockWrite(OutFile,tempbyte,1); end; except Memo1.Lines.Add('..failed!'); end; end; finally InfName.Free; end; end; end.
// -------------------------------------------------------------------------- // Archivo del Proyecto Ventas // Página del proyecto: http://sourceforge.net/projects/ventas // -------------------------------------------------------------------------- // Este archivo puede ser distribuido y/o modificado bajo lo terminos de la // Licencia Pública General versión 2 como es publicada por la Free Software // Fundation, Inc. // -------------------------------------------------------------------------- unit ReportesVentas; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QButtons, QExtCtrls, IniFiles, rpcompobase, rpclxreport, QcurrEdit, QMenus, QTypes; type TfrmReportesVentas = class(TForm) rgpOrden: TRadioGroup; grpDeptos: TGroupBox; lblDesde: TLabel; lblHasta: TLabel; pnlCateg: TPanel; cmbCategIni: TComboBox; cmbCategFin: TComboBox; pnlCodigo: TPanel; txtCodigoIni: TEdit; txtCodigoFin: TEdit; pnlProveedor: TPanel; txtProvIni: TEdit; txtProvFin: TEdit; pnlDescrip: TPanel; txtDescripIni: TEdit; txtDescripFin: TEdit; pnlDepto: TPanel; cmbDeptoIni: TComboBox; cmbDeptoFin: TComboBox; rdoTodo: TRadioButton; rdoRango: TRadioButton; grpFechas: TGroupBox; Label2: TLabel; Label11: TLabel; txtDiaIni: TEdit; Label30: TLabel; txtMesIni: TEdit; Label31: TLabel; txtAnioIni: TEdit; txtDiaFin: TEdit; Label1: TLabel; txtMesFin: TEdit; Label3: TLabel; txtAnioFin: TEdit; btnImprimir: TBitBtn; rptReportes: TCLXReport; btnCancelar: TBitBtn; pnlAreas: TPanel; pnlCaja: TPanel; pnlCliente: TPanel; txtClienteIni: TEdit; txtClienteFin: TEdit; pnlUsuario: TPanel; txtUsuarioIni: TEdit; txtUsuarioFin: TEdit; chkPreliminar: TCheckBox; txtCajaIni: TcurrEdit; txtCajaFin: TcurrEdit; cmbAreaIni: TComboBox; cmbAreaFin: TComboBox; cbfiscal: TCheckBox; PopupMenu1: TPopupMenu; f11: TMenuItem; p2: TLabel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure rgpOrdenClick(Sender: TObject); procedure rdoTodoClick(Sender: TObject); procedure cmbDeptoIniSelect(Sender: TObject); procedure Numero (Sender: TObject; var Key: Char); procedure btnCancelarClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure chkPreliminarClick(Sender: TObject); procedure Salta(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCreate(Sender: TObject); procedure txtAnioIniExit(Sender: TObject); procedure txtAnioFinExit(Sender: TObject); procedure txtDiaIniExit(Sender: TObject); procedure f11Click(Sender: TObject); private sFechaIni, sFechaFin : string; procedure RecuperaConfig; procedure CargaCombos; function VerificaDatos : boolean; function VerificaFechas(sFecha : string):boolean; function VerificaRangos : boolean; procedure ImprimeVentasPorArea; procedure ImprimeVentasPorCaja; procedure ImprimeVentasPorCategoria; procedure ImprimeVentasPorCliente; procedure ImprimeVentasPorCodigo; procedure ImprimeVentasPorDepartamento; procedure ImprimeVentasPorUsuario; procedure ImprimeVentasPorDescripcion; procedure ImprimeVentasPorProveedor; procedure ImprimeVentasPorVendedor; procedure Rellena(Sender: TObject); public end; var frmReportesVentas: TfrmReportesVentas; implementation uses dm; {$R *.xfm} procedure TfrmReportesVentas.FormShow(Sender: TObject); begin CargaCombos; rgpOrdenClick(Sender); rdoTodoClick(Sender); end; procedure TfrmReportesVentas.CargaCombos; begin cmbAreaIni.Items.Clear; cmbAreaFin.Items.Clear; cmbCategIni.Clear; cmbCategFin.Clear; cmbDeptoIni.Clear; cmbDeptoFin.Clear; with dmDatos.qryConsulta do begin Close; SQL.Clear; SQL.Add('SELECT nombre FROM areasventa ORDER BY nombre'); Open; while(not EOF) do begin cmbAreaIni.Items.Add(FieldByName('nombre').AsString); cmbAreaFin.Items.Add(FieldByName('nombre').AsString); Next; end; Close; SQL.Clear; SQL.Add('SELECT nombre FROM categorias WHERE tipo =''A'' ORDER BY nombre'); Open; while(not EOF) do begin cmbCategIni.Items.Add(FieldByName('nombre').AsString); cmbCategFin.Items.Add(FieldByName('nombre').AsString); Next; end; Close; SQL.Clear; SQL.Add('SELECT nombre FROM departamentos ORDER BY nombre'); Open; while(not EOF) do begin cmbDeptoIni.Items.Add(FieldByName('nombre').AsString); cmbDeptoFin.Items.Add(FieldByName('nombre').AsString); Next; end; Close; end; cmbAreaIni.ItemIndex := 0; cmbAreaFin.ItemIndex := 0; cmbCategIni.ItemIndex := 0; cmbCategFin.ItemIndex := 0; cmbDeptoIni.ItemIndex := 0; cmbDeptoFin.ItemIndex := 0; end; procedure TfrmReportesVentas.RecuperaConfig; var iniArchivo : TIniFile; sIzq, sArriba, sValor : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin //Recupera la posición Y de la ventana sArriba := ReadString('RepVentas', 'Posy', ''); //Recupera la posición X de la ventana sIzq := ReadString('RepVentas', 'Posx', ''); if (Length(sIzq) > 0) and (Length(sArriba) > 0) then begin Left := StrToInt(sIzq); Top := StrToInt(sArriba); end; //Recupera la posición de los botones de radio sValor := ReadString('RepVentas', 'Tipo', ''); if (Length(sValor) > 0) then rgpOrden.ItemIndex := StrToInt(sValor); //Recupera la fecha inicial sValor := ReadString('RepVentas', 'FechaIni', ''); if (Length(sValor) > 0) then begin txtDiaIni.Text := Copy(sValor,1,2); txtMesIni.Text := Copy(sValor,4,2); txtAnioIni.Text := Copy(sValor,7,4); end; //Recupera la fecha final sValor := ReadString('RepVentas', 'FechaFin', ''); if (Length(sValor) > 0) then begin txtDiaFin.Text := Copy(sValor,1,2); txtMesFin.Text := Copy(sValor,4,2); txtAnioFin.Text := Copy(sValor,7,4); end; Free; end; end; procedure TfrmReportesVentas.FormClose(Sender: TObject; var Action: TCloseAction); var iniArchivo : TIniFile; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); with iniArchivo do begin // Registra la posición y de la ventana WriteString('RepVentas', 'Posy', IntToStr(Top)); // Registra la posición X de la ventana WriteString('RepVentas', 'Posx', IntToStr(Left)); // Registra la posición de los botones de radio WriteString('RepVentas', 'Tipo', IntToStr(rgpOrden.ItemIndex)); // Registra la fecha inicial WriteString('RepVentas', 'FechaIni', txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text); // Registra la fecha final WriteString('RepVentas', 'FechaFin', txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text); Free; end; end; procedure TfrmReportesVentas.rgpOrdenClick(Sender: TObject); begin pnlAreas.Visible := false; pnlCaja.Visible := false; pnlCateg.Visible := false; pnlCliente.Visible := false; pnlCodigo.Visible := false; pnlDepto.Visible := false; pnlDescrip.Visible := false; pnlProveedor.Visible := false; pnlUsuario.Visible := false; case rgpOrden.ItemIndex of 0: Begin pnlAreas.Visible := true; cbfiscal.Enabled:=false; end; 1: Begin pnlCaja.Visible := true; cbfiscal.Enabled:=false; end; 2: Begin pnlCateg.Visible := true; cbfiscal.Enabled:=false; end; 3: Begin pnlCliente.Visible := true; cbfiscal.Enabled:=false; end; 4: Begin pnlCodigo.Visible := true; cbfiscal.Enabled:=true; end; 5: Begin pnlDepto.Visible := true; cbfiscal.Enabled:=false; end; 6: Begin pnlDescrip.Visible := true; cbfiscal.Enabled:=false; end; 7: Begin pnlProveedor.Visible := true; cbfiscal.Enabled:=false; end; 8: Begin pnlUsuario.Visible := true; cbfiscal.Enabled:=false; end; end; end; procedure TfrmReportesVentas.rdoTodoClick(Sender: TObject); begin if(rdoTodo.Checked) then begin lblDesde.Enabled := false; lblHasta.Enabled := false; cmbAreaIni.Enabled := false; cmbAreaFin.Enabled := false; txtCajaIni.Enabled := false; txtCajaFin.Enabled := false; txtClienteIni.Enabled := false; txtClienteFin.Enabled := false; txtUsuarioIni.Enabled := false; txtUsuarioFin.Enabled := false; txtCodigoIni.Enabled := false; txtCodigoFin.Enabled := false; cmbCategIni.Enabled := false; cmbCategFin.Enabled := false; cmbDeptoIni.Enabled := false; cmbDeptoFin.Enabled := false; txtDescripIni.Enabled := false; txtDescripFin.Enabled := false; txtProvIni.Enabled := false; txtProvFin.Enabled := false; end else begin lblDesde.Enabled := true; lblHasta.Enabled := true; cmbAreaIni.Enabled := true; cmbAreaFin.Enabled := true; txtCajaIni.Enabled := true; txtCajaFin.Enabled := true; txtClienteIni.Enabled := true; txtClienteFin.Enabled := true; txtUsuarioIni.Enabled := true; txtUsuarioFin.Enabled := true; txtCodigoIni.Enabled := true; txtCodigoFin.Enabled := true; cmbCategIni.Enabled := true; cmbCategFin.Enabled := true; cmbDeptoIni.Enabled := true; cmbDeptoFin.Enabled := true; txtDescripIni.Enabled := true; txtDescripFin.Enabled := true; txtProvIni.Enabled := true; txtProvFin.Enabled := true; end; end; procedure TfrmReportesVentas.cmbDeptoIniSelect(Sender: TObject); begin if(cmbDeptoFin.ItemIndex < cmbDeptoIni.ItemIndex) then cmbDeptoFin.ItemIndex := cmbDeptoIni.ItemIndex; end; procedure TfrmReportesVentas.Numero(Sender: TObject; var Key: Char); begin if not (Key in ['0'..'9',#8]) then Key := #0; end; procedure TfrmReportesVentas.btnCancelarClick(Sender: TObject); begin Close; end; procedure TfrmReportesVentas.chkPreliminarClick(Sender: TObject); begin rptReportes.Preview := chkPreliminar.Checked; end; procedure TfrmReportesVentas.btnImprimirClick(Sender: TObject); begin if VerificaDatos then case rgpOrden.ItemIndex of 0: ImprimeVentasPorArea; 1: ImprimeVentasPorCaja; 2: ImprimeVentasPorCategoria; 3: ImprimeVentasPorCliente; 4: ImprimeVentasPorCodigo; 5: ImprimeVentasPorDepartamento; 6: ImprimeVentasPorDescripcion; 7: ImprimeVentasPorProveedor; 8: ImprimeVentasPorUsuario; 9: ImprimeVentasPorVendedor; end; end; function TfrmReportesVentas.VerificaDatos : boolean; begin Result:= true; sFechaIni := txtMesIni.Text + '/' + txtDiaIni.Text + '/' + txtAnioIni.Text; sFechaFin := txtMesFin.Text + '/' + txtDiaFin.Text + '/' + txtAnioFin.Text; if(not VerificaFechas(txtDiaIni.Text + '/' + txtMesIni.Text + '/' + txtAnioIni.Text)) then begin Application.MessageBox('Introduce una fecha válida','Error',[smbOK],smsCritical); txtDiaIni.SetFocus; Result := false; end else if(not VerificaFechas(txtDiaFin.Text + '/' + txtMesFin.Text + '/' + txtAnioFin.Text)) then begin Application.MessageBox('Introduce una fecha válida','Error',[smbOK],smsCritical); txtDiaFin.SetFocus; Result := false; end else if not VerificaRangos then Result := false; end; function TfrmReportesVentas.VerificaFechas(sFecha : string):boolean; var dteFecha : TDateTime; begin Result:=true; if(not TryStrToDate(sFecha,dteFecha)) then Result:=false; end; function TfrmReportesVentas.VerificaRangos : boolean; var bResult : boolean; begin bResult:= true; if rdoRango.Checked then case rgpOrden.ItemIndex of 0 : if (Length(cmbAreaIni.Text)=0) or (Length(cmbAreaFin.Text)=0) then bResult := false; 1 : if (Length(txtCajaIni.Text)=0) or (Length(txtCajaFin.Text)=0) then bResult := false; 2 : if (Length(cmbCategIni.Text)=0) or (Length(cmbCategFin.Text)=0) then bResult := false; 3 : if (Length(txtClienteIni.Text)=0) or (Length(txtClienteFin.Text)=0) then bResult := false; 4 : if (Length(txtCodigoIni.Text)=0) or (Length(txtCodigoFin.Text)=0) then bResult := false; 5 : if (Length(cmbDeptoIni.Text)=0) or (Length(cmbDeptoFin.Text)=0) then bResult := false; 6 : if (Length(txtDescripIni.Text)=0) or (Length(txtDescripFin.Text)=0) then bResult := false; 7 : if (Length(txtProvIni.Text)=0) or (Length(txtProvFin.Text)=0) then bResult := false; 8 : if (Length(txtUsuarioIni.Text)=0) or (Length(txtUsuarioFin.Text)=0) then bResult := false; end; if not bResult then Application.MessageBox('Introduce un rango válido','Error',[smbOK],smsCritical); Result := bResult end; procedure TfrmReportesVentas.ImprimeVentasPorArea; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasArea', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('AREAINI').AsString := ''; rptReportes.Report.Params.ParamByName('AREAFIN').AsString := 'ZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('AREAINI').AsString := cmbAreaIni.Text; rptReportes.Report.Params.ParamByName('AREAFIN').AsString := cmbAreaFin.Text; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorCaja; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasCaja', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('CAJAINI').AsString := '1'; rptReportes.Report.Params.ParamByName('CAJAFIN').AsString := '999'; end else begin rptReportes.Report.Params.ParamByName('CAJAINI').AsString := FloatToStr(txtCajaIni.Value); rptReportes.Report.Params.ParamByName('CAJAFIN').AsString := FloatToStr(txtCajaFin.Value); end; if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorCategoria; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasCategoria', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('CATEGINI').AsString := ''; rptReportes.Report.Params.ParamByName('CATEGFIN').AsString := 'ZZZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('CATEGINI').AsString := cmbCategIni.Text; rptReportes.Report.Params.ParamByName('CATEGFIN').AsString := cmbCategFin.Text; end; {if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1' else rptReportes.Report.Params.ParamByName('FISCALES').AsString :='0'; } if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorCliente; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasCliente', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('CLIENTEINI').AsString := ''; rptReportes.Report.Params.ParamByName('CLIENTEFIN').AsString := 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('CLIENTEINI').AsString := txtClienteIni.Text; rptReportes.Report.Params.ParamByName('CLIENTEFIN').AsString := txtClienteFin.Text; end; if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorCodigo; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; if cbfiscal.Checked then sArchivo := iniArchivo.ReadString('Reportes', 'VentasCodigoFiscal', '') else sArchivo := iniArchivo.ReadString('Reportes', 'VentasCodigo', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('CODIGOINI').AsString := ''; rptReportes.Report.Params.ParamByName('CODIGOFIN').AsString := 'ZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('CODIGOINI').AsString := txtCodigoIni.Text; rptReportes.Report.Params.ParamByName('CODIGOFIN').AsString := txtCodigoFin.Text; end; if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1'; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorDepartamento; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasDepartamento', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('DEPTOINI').AsString := ''; rptReportes.Report.Params.ParamByName('DEPTOFIN').AsString := 'ZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('DEPTOINI').AsString := cmbDeptoIni.Text; rptReportes.Report.Params.ParamByName('DEPTOFIN').AsString := cmbDeptoFin.Text; end; if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; {if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1' else rptReportes.Report.Params.ParamByName('FISCALES').AsString :='0'; } rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorDescripcion; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasDescripcion', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('DESCRIPINI').AsString := ''; rptReportes.Report.Params.ParamByName('DESCRIPFIN').AsString := 'ZZZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('DESCRIPINI').AsString := txtDescripIni.Text; rptReportes.Report.Params.ParamByName('DESCRIPFIN').AsString := txtDescripFin.Text; end; { if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1' else rptReportes.Report.Params.ParamByName('FISCALES').AsString :='0'; } if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorProveedor; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasProveedor', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('PROVINI').AsString := '1'; rptReportes.Report.Params.ParamByName('PROVFIN').AsString := '9999'; end else begin rptReportes.Report.Params.ParamByName('PROVINI').AsString := txtProvIni.Text; rptReportes.Report.Params.ParamByName('PROVFIN').AsString := txtProvFin.Text; end; {if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1' else rptReportes.Report.Params.ParamByName('FISCALES').AsString :='0';} if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorVendedor; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; // sArchivo := iniArchivo.ReadString('Reportes', 'VentasProveedor', ''); sArchivo := 'Ventasporvendedor.rep'; if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if (cbfiscal.Checked = true) then begin rptReportes.Report.Params.ParamByName('P2').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('P2').AsString := 'T'; end; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('PROVINI').AsString := '1'; rptReportes.Report.Params.ParamByName('PROVFIN').AsString := '9999'; end else begin rptReportes.Report.Params.ParamByName('PROVINI').AsString := txtProvIni.Text; rptReportes.Report.Params.ParamByName('PROVFIN').AsString := txtProvFin.Text; end; {if cbfiscal.Checked then rptReportes.Report.Params.ParamByName('FISCALES').AsString := '1' else rptReportes.Report.Params.ParamByName('FISCALES').AsString :='0';} rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.ImprimeVentasPorUsuario; var iniArchivo : TIniFile; sArchivo : String; sDirReportes : String; begin iniArchivo := TIniFile.Create(ExtractFilePath(Application.ExeName) +'config.ini'); sDirReportes := iniArchivo.ReadString('Reportes', 'DirReportes', ''); if not (Length(sDirReportes) > 0) then sDirReportes:= ExtractFilePath(Application.ExeName)+'Reportes\'; sArchivo := iniArchivo.ReadString('Reportes', 'VentasUsuario', ''); if (Length(sArchivo) > 0) then begin rptReportes.FileName := sDirReportes + sArchivo; rptReportes.Report.DatabaseInfo.Items[0].SQLConnection := dmDatos.sqlBase.DataSets[0].SQLConnection; rptReportes.Report.Params.ParamByName('FECHAINI').AsString := sFechaIni; rptReportes.Report.Params.ParamByName('FECHAFIN').AsString := sFechaFin; if(rdoTodo.Checked) then begin rptReportes.Report.Params.ParamByName('USUARIOINI').AsString := ''; rptReportes.Report.Params.ParamByName('USUARIOFIN').AsString := 'ZZZZZZZZZZZ'; end else begin rptReportes.Report.Params.ParamByName('USUARIOINI').AsString := txtUsuarioIni.Text; rptReportes.Report.Params.ParamByName('USUARIOFIN').AsString := txtUsuarioFin.Text; end; if cbfiscal.Checked then begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'P'; end else begin rptReportes.Report.Params.ParamByName('FISCALES').AsString := 'T'; end; rptReportes.Execute; end else Application.MessageBox('El archivo ' + sArchivo + ' no existe','Error',[smbOK],smsCritical); end; procedure TfrmReportesVentas.Salta(Sender: TObject; var Key: Word; Shift: TShiftState); begin {Inicio (36), Fin (35), Izquierda (37), derecha (39), arriba (38), abajo (40)} if(Key >= 30) and (Key <= 122) and (Key <> 35) and (Key <> 36) and not ((Key >= 37) and (Key <= 40)) then if( Length((Sender as TEdit).Text) = (Sender as TEdit).MaxLength) then SelectNext(Sender as TWidgetControl, true, true); end; procedure TfrmReportesVentas.FormCreate(Sender: TObject); begin RecuperaConfig; end; procedure TfrmReportesVentas.txtAnioIniExit(Sender: TObject); begin txtAnioIni.Text := Trim(txtAnioIni.Text); if(Length(txtAnioIni.Text) < 4) and (Length(txtAnioIni.Text) > 0) then txtAnioIni.Text := IntToStr(StrToInt(txtAnioIni.Text) + 2000); end; procedure TfrmReportesVentas.txtAnioFinExit(Sender: TObject); begin txtAnioFin.Text := Trim(txtAnioFin.Text); if(Length(txtAnioFin.Text) < 4) and (Length(txtAnioFin.Text) > 0) then txtAnioFin.Text := IntToStr(StrToInt(txtAnioFin.Text) + 2000); end; procedure TfrmReportesVentas.Rellena(Sender: TObject); var i : integer; begin for i := Length((Sender as TEdit).Text) to (Sender as TEdit).MaxLength - 1 do (Sender as TEdit).Text := '0' + (Sender as TEdit).Text; end; procedure TfrmReportesVentas.txtDiaIniExit(Sender: TObject); begin Rellena(Sender); end; procedure TfrmReportesVentas.f11Click(Sender: TObject); begin if (cbfiscal.Checked = true) then begin p2.Visible:=false; cbfiscal.Checked := false; end else begin p2.Visible:=true; cbfiscal.Checked := true; end; end; end.
unit mariobros_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,gfx_engine,samples,rom_engine, pal_engine,sound_engine,qsnapshot; function iniciar_mario:boolean; implementation const mario_rom:array[0..3] of tipo_roms=( (n:'tma1-c-7f_f.7f';l:$2000;p:0;crc:$c0c6e014),(n:'tma1-c-7e_f.7e';l:$2000;p:$2000;crc:$94fb60d6), (n:'tma1-c-7d_f.7d';l:$2000;p:$4000;crc:$dcceb6c1),(n:'tma1-c-7c_f.7c';l:$1000;p:$f000;crc:$4a63d96b)); mario_pal:tipo_roms=(n:'tma1-c-4p_1.4p';l:$200;p:0;crc:$8187d286); mario_char:array[0..1] of tipo_roms=( (n:'tma1-v-3f.3f';l:$1000;p:0;crc:$28b0c42c),(n:'tma1-v-3j.3j';l:$1000;p:$1000;crc:$0c8cc04d)); mario_sprites:array[0..5] of tipo_roms=( (n:'tma1-v-7m.7m';l:$1000;p:0;crc:$22b7372e),(n:'tma1-v-7n.7n';l:$1000;p:$1000;crc:$4f3a1f47), (n:'tma1-v-7p.7p';l:$1000;p:$2000;crc:$56be6ccd),(n:'tma1-v-7s.7s';l:$1000;p:$3000;crc:$56f1d613), (n:'tma1-v-7t.7t';l:$1000;p:$4000;crc:$641f0008),(n:'tma1-v-7u.7u';l:$1000;p:$5000;crc:$7baf5309)); mario_samples:array[0..28] of tipo_nombre_samples=( (nombre:'mario_run.wav';restart:true),(nombre:'luigi_run.wav';restart:true),(nombre:'skid.wav';restart:true),(nombre:'bite_death.wav'),(nombre:'death.wav'), (nombre:'tune1.wav';restart:true),(nombre:'tune2.wav';restart:true),(nombre:'tune3.wav';restart:true),(nombre:'tune4.wav';restart:true),(nombre:'tune5.wav';restart:true),(nombre:'tune6.wav';restart:true), (nombre:'tune7.wav'),(nombre:'tune8.wav';restart:true),(nombre:'tune9.wav';restart:true),(nombre:'tune10.wav';restart:true),(nombre:'tune11.wav';restart:true),(nombre:'tune12.wav';restart:true), (nombre:'tune13.wav';restart:true),(nombre:'tune14.wav';restart:true),(nombre:'tune15.wav';restart:true),(nombre:'tune16.wav';restart:true),(nombre:'tune17.wav'),(nombre:'tune18.wav'),(nombre:'tune19.wav'), (nombre:'coin.wav'),(nombre:'insert_coin.wav'),(nombre:'turtle.wav'),(nombre:'crab.wav'),(nombre:'fly.wav')); //Dip mario_dip_a:array [0..4] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'3'),(dip_val:$1;dip_name:'4'),(dip_val:$2;dip_name:'5'),(dip_val:$3;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Coinage';number:4;dip:((dip_val:$4;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(dip_val:$8;dip_name:'1C 2C'),(dip_val:$c;dip_name:'1C 3C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$0;dip_name:'20K'),(dip_val:$10;dip_name:'30K'),(dip_val:$20;dip_name:'40K'),(dip_val:$30;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Difficulty';number:4;dip:((dip_val:$0;dip_name:'Easy'),(dip_val:$80;dip_name:'Medium'),(dip_val:$40;dip_name:'Hard'),(dip_val:$c0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())),()); var haz_nmi:boolean; gfx_bank,palette_bank,scroll_y,death_val,skid_val:byte; procedure update_video_mario; var atrib:byte; f,x,y,color,nchar:word; begin //Poner chars for f:=$3ff downto 0 do begin if gfx[0].buffer[f] then begin x:=31-(f mod 32); y:=31-(f div 32); atrib:=memoria[$7400+f]; nchar:=atrib+(gfx_bank shl 8); color:=((atrib shr 2) and $38) or $40 or (palette_bank shl 7); put_gfx(x*8,y*8,nchar,color,1,0); gfx[0].buffer[f]:=false; end; end; scroll__y(1,2,scroll_y); for f:=0 to $7f do begin if memoria[$7000+(f*4)]=0 then continue; nchar:=memoria[$7002+(f*4)]; atrib:=memoria[$7001+(f*4)]; color:=((atrib and $0f)+16*palette_bank) shl 3; x:=240-(memoria[$7003+(f*4)]-8); y:=memoria[$7000+(f*4)]+$f9; put_gfx_sprite(nchar,color,(atrib and $80)=0,(atrib and $40)=0,1); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(0,16,256,224,2); end; procedure eventos_mario; begin if main_vars.service1 then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.but0[0] then marcade.in0:=marcade.in0 or $10 else marcade.in0:=(marcade.in0 and $ef); if arcade_input.start[0] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.start[1] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); //P2 if arcade_input.right[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.left[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.but0[1] then marcade.in1:=marcade.in1 or $10 else marcade.in1:=(marcade.in1 and $ef); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); if arcade_input.coin[0] then marcade.in1:=(marcade.in1 or $40) else marcade.in1:=(marcade.in1 and $bf); end; end; procedure mario_principal; var frame:single; f:word; begin init_controls(false,false,false,true); frame:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin z80_0.run(frame); frame:=frame+z80_0.tframes-z80_0.contador; if f=239 then begin if haz_nmi then z80_0.change_nmi(PULSE_LINE); update_video_mario; end; end; eventos_mario; video_sync; end; end; function mario_getbyte(direccion:word):byte; begin case direccion of $0..$77ff,$f000..$ffff:mario_getbyte:=memoria[direccion]; $7c00:mario_getbyte:=marcade.in0; $7c80:mario_getbyte:=marcade.in1; $7f80:mario_getbyte:=marcade.dswa; end; end; procedure mario_putbyte(direccion:word;valor:byte); begin case direccion of 0..$5fff,$f000..$ffff:; //ROM $6000..$73ff:memoria[direccion]:=valor; $7400..$77ff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $7c00:start_sample(0); $7c80:start_sample(1); $7d00:scroll_y:=valor+17; $7d80,$7e87:; //?? $7e00:begin case (valor and $f) of 1:start_sample(5); //pow 2:start_sample(6); //tune sale vida 3:start_sample(7); //salto mario 4:start_sample(8); //tirar al agua un bicho 5:start_sample(9); //tortuga boca abajo 6:start_sample(10); //sonido agua del bicho 7:start_sample(11); //vida extra 8:start_sample(12); //tune presentacion cangrejos 9:start_sample(13); //tune comenzar la partida 10:start_sample(14); //tune presentacion tortugas 11:start_sample(15); //tune game over 12:start_sample(16); //tune bonus perfecto 13:start_sample(17); //lanzar el ultimo bicho 14:start_sample(18); //tune en bonus 15:start_sample(19); //tune coin cogido en bonus end; case (valor shr 4) of 1:start_sample(20); 2,3:start_sample(21); 4..7:start_sample(22); 8..$f:start_sample(23); end; end; $7e80:if gfx_bank<>(valor and 1) then begin gfx_bank:=valor and 1; fillchar(gfx[0].buffer[0],$400,1); end; $7e82:main_screen.flip_main_screen:=(valor and 1)=0; $7e83:if palette_bank<>(valor and 1) then begin palette_bank:=valor and 1; fillchar(gfx[0].buffer[0],$400,1); end; $7e84:haz_nmi:=(valor and 1)<>0; $7e85:if (valor and 1)<>0 then copymemory(@memoria[$7000],@memoria[$6900],$400); $7f00..$7f07:case (direccion and 7) of 0:begin //cuando pasa de 0 a 1 mordisco, cuando pasa de 1 a 0 muerte if ((death_val=0) and ((valor and 1)=1)) then start_sample(3); if ((death_val=1) and ((valor and 1)=0)) then start_sample(4); death_val:=valor and 1; end; 1:if valor<>0 then start_sample(25); //get coin 2:; //NADA 3:if valor<>0 then start_sample(27);//crab sale 4:if valor<>0 then start_sample(26);//turtle sale 5:if valor<>0 then start_sample(28);//fly sale 6:if valor<>0 then start_sample(24); //coin sale 7:begin //skid cuando pasa de 1 a 0 if ((skid_val=1) and ((valor and 1)=0)) then start_sample(2); skid_val:=valor and 1; end; end; end; end; procedure mario_sound_update; begin samples_update; end; //Main procedure reset_mario; begin z80_0.reset; reset_samples; reset_audio; marcade.in0:=0; marcade.in1:=0; haz_nmi:=false; gfx_bank:=0; palette_bank:=0; scroll_y:=0; death_val:=0; skid_val:=0; end; procedure mario_qsave(nombre:string); var data:pbyte; buffer:array[0..5] of byte; size:word; begin open_qsnapshot_save('mario'+nombre); getmem(data,20000); //CPU size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND //MEM savedata_com_qsnapshot(@memoria[$6000],$1800); //MISC buffer[0]:=byte(haz_nmi); buffer[1]:=gfx_bank; buffer[2]:=palette_bank; buffer[3]:=scroll_y; buffer[4]:=death_val; buffer[5]:=skid_val; savedata_qsnapshot(@buffer[0],6); freemem(data); close_qsnapshot; end; procedure mario_qload(nombre:string); var data:pbyte; buffer:array[0..5] of byte; begin if not(open_qsnapshot_load('mario'+nombre)) then exit; getmem(data,20000); //CPU loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND //MEM loaddata_qsnapshot(@memoria[$6000]); //MISC loaddata_qsnapshot(@buffer); haz_nmi:=buffer[0]<>0; gfx_bank:=buffer[1]; palette_bank:=buffer[2]; scroll_y:=buffer[3]; death_val:=buffer[4]; skid_val:=buffer[5]; freemem(data); close_qsnapshot; fillchar(gfx[0].buffer[0],$400,1); end; function iniciar_mario:boolean; var colores:tpaleta; f:word; bit0,bit1,bit2:byte; memoria_temp:array[0..$5fff] of byte; const pc_x:array[0..7] of dword=(7, 6, 5, 4, 3, 2, 1, 0); pc_y:array[0..7] of dword=(7*8, 6*8, 5*8, 4*8, 3*8, 2*8, 1*8, 0*8); ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 256*16*8+0, 256*16*8+1, 256*16*8+2, 256*16*8+3, 256*16*8+4, 256*16*8+5, 256*16*8+6, 256*16*8+7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); begin llamadas_maquina.bucle_general:=mario_principal; llamadas_maquina.reset:=reset_mario; llamadas_maquina.save_qsnap:=mario_qsave; llamadas_maquina.load_qsnap:=mario_qload; llamadas_maquina.fps_max:=59.185606; iniciar_mario:=false; iniciar_audio(false); screen_init(1,256,256); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,false,true); iniciar_video(256,224); //Main CPU z80_0:=cpu_z80.create(4000000,264); z80_0.change_ram_calls(mario_getbyte,mario_putbyte); //cargar roms if not(roms_load(@memoria,mario_rom)) then exit; //samples if load_samples(mario_samples) then z80_0.init_sound(mario_sound_update); //convertir chars if not(roms_load(@memoria_temp,mario_char)) then exit; init_gfx(0,8,8,512); gfx_set_desc_data(2,0,8*8,512*8*8,0); convert_gfx(0,0,@memoria_temp,@pc_x,@pc_y,false,false); //convertir sprites if not(roms_load(@memoria_temp,mario_sprites)) then exit; init_gfx(1,16,16,256); gfx[1].trans[0]:=true; gfx_set_desc_data(3,0,16*8,2*256*16*16,256*16*16,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //poner la paleta if not(roms_load(@memoria_temp,mario_pal)) then exit; for f:=0 to $1ff do begin bit0:=(memoria_temp[f] shr 5) and 1; bit1:=(memoria_temp[f] shr 6) and 1; bit2:=(memoria_temp[f] shr 7) and 1; colores[f].r:=not($21*bit0+$47*bit1+$97*bit2); bit0:=(memoria_temp[f] shr 2) and 1; bit1:=(memoria_temp[f] shr 3) and 1; bit2:=(memoria_temp[f] shr 4) and 1; colores[f].g:=not($21*bit0+$47*bit1+$97*bit2); bit0:=(memoria_temp[f] shr 0) and 1; bit1:=(memoria_temp[f] shr 1) and 1; colores[f].b:=not($55*bit0+$aa*bit1); end; set_pal(colores,$200); //DIP marcade.dswa:=0; marcade.dswa_val:=@mario_dip_a; //final reset_mario; iniciar_mario:=true; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.7 10/26/2004 11:08:10 PM JPMugaas Updated refs. Rev 1.6 28.09.2004 21:35:28 Andreas Hausladen Added TIdObjectList.Assign method for missing Delphi 5 TList.Assign Rev 1.5 1/4/2004 12:09:00 AM BGooijen Commented out Notify, this doesn't exist in DotNet, and doesn't do anything anyways Rev 1.4 3/13/2003 11:10:52 AM JPMugaas Fixed warning message. Rev 1.3 2/8/2003 04:33:34 AM JPMugaas Commented out a free statement in the TIdObjectList.Notify method because it was causing instability in some new IdFTPList code I was working on. Added a TStringList descendent object that implements a buble sort. That should require less memory than a QuickSort. This also replaces the TStrings.CustomSort because that is not supported in D4. Rev 1.2 2/7/2003 10:33:48 AM JPMugaas Added BoubleSort to TIdObjectList to facilitate some work. Rev 1.1 12/2/2002 04:32:30 AM JPMugaas Fixed minor compile errors. Rev 1.0 11/14/2002 02:16:14 PM JPMugaas Revision 1.0 2001-02-20 02:02:09-05 dsiders Initial revision } {********************************************************************} {* IdContainers.pas *} {* *} {* Provides compatibility with the Contnr.pas unit from *} {* Delphi 5 not found in Delphi 4. *} {* *} {* Based on ideas from the Borland VCL Contnr.pas interface. *} {* *} {********************************************************************} unit IdContainers; interface {$i IdCompilerDefines.inc} uses Classes; type TIdSortCompare = function(AItem1, AItem2 : TObject): Integer; {TIdObjectList} TIdObjectList = class(TList) private FOwnsObjects: Boolean; protected function GetItem(AIndex: Integer): TObject; procedure SetItem(AIndex: Integer; AObject: TObject); {$IFNDEF DOTNET} procedure Notify(AItemPtr: Pointer; AAction: TListNotification); override; {$ENDIF} public constructor Create; overload; constructor Create(AOwnsObjects: Boolean); overload; procedure BubbleSort(ACompare : TIdSortCompare); function Add(AObject: TObject): Integer; function FindInstanceOf(AClassRef: TClass; AMatchExact: Boolean = True; AStartPos: Integer = 0): Integer; function IndexOf(AObject: TObject): Integer; function Remove(AObject: TObject): Integer; procedure Insert(AIndex: Integer; AObject: TObject); procedure Assign(Source: TIdObjectList); property Items[AIndex: Integer]: TObject read GetItem write SetItem; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; TIdStringListSortCompare = function(List: TStringList; Index1, Index2: Integer): Integer; TIdBubbleSortStringList = class(TStringList) public procedure BubbleSort(ACompare: TIdStringListSortCompare); virtual; end; implementation {$IFDEF VCL_XE3_OR_ABOVE} uses System.Types; {$ENDIF} { TIdObjectList } constructor TIdObjectList.Create; begin inherited Create; FOwnsObjects := True; end; constructor TIdObjectList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; function TIdObjectList.Add(AObject: TObject): Integer; begin Result := inherited Add(AObject); end; procedure TIdObjectList.BubbleSort(ACompare: TIdSortCompare); var i, j : Integer; begin for I := Count -1 downto 0 do begin for J := 0 to Count - 1 - 1 do begin if ACompare(Items[J] , Items[J + 1])< 0 then begin Exchange(J, J + 1); end; end; end; end; function TIdObjectList.FindInstanceOf(AClassRef: TClass; AMatchExact: Boolean = True; AStartPos: Integer = 0): Integer; var iPos: Integer; bIsAMatch: Boolean; begin Result := -1; // indicates item is not in object list for iPos := AStartPos to Count - 1 do begin bIsAMatch := ((not AMatchExact) and Items[iPos].InheritsFrom(AClassRef)) or (AMatchExact and (Items[iPos].ClassType = AClassRef)); if bIsAMatch then begin Result := iPos; Break; end; end; end; function TIdObjectList.GetItem(AIndex: Integer): TObject; begin Result := inherited Items[AIndex]; end; function TIdObjectList.IndexOf(AObject: TObject): Integer; begin Result := inherited IndexOf(AObject); end; procedure TIdObjectList.Insert(AIndex: Integer; AObject: TObject); begin inherited Insert(AIndex, AObject); end; procedure TIdObjectList.Assign(Source: TIdObjectList); var I: Integer; begin // Delphi 5 does not have TList.Assign. // This is a simplyfied Assign method that does only support the copy operation. Clear; Capacity := Source.Capacity; for I := 0 to Source.Count - 1 do begin Add(Source[I]); end; end; {$IFNDEF DOTNET} procedure TIdObjectList.Notify(AItemPtr: Pointer; AAction: TListNotification); begin if OwnsObjects and (AAction = lnDeleted) then begin TObject(AItemPtr).Free; end; inherited Notify(AItemPtr, AAction); end; {$ENDIF} function TIdObjectList.Remove(AObject: TObject): Integer; begin Result := inherited Remove(AObject); end; procedure TIdObjectList.SetItem(AIndex: Integer; AObject: TObject); begin inherited Items[AIndex] := AObject; end; { TIdBubbleSortStringList } procedure TIdBubbleSortStringList.BubbleSort(ACompare: TIdStringListSortCompare); var i, j: Integer; LTemp: String; LTmpObj: TObject; begin for i := Count - 1 downto 0 do begin for j := 0 to Count - 1 - 1 do begin if ACompare(Self, J, J + 1) < 0 then begin LTemp := Strings[j]; LTmpObj := Objects[j]; Strings[j] := Strings[j + 1]; Objects[j] := Objects[j + 1]; Strings[j + 1] := LTemp; Objects[j + 1] := LTmpObj; end; end; end; end; end.
unit uTriggersBase; interface uses ZDataset, ZSqlProcessor, udmPrincipal; function TriggerExiste(aNomeTrigger: string): Boolean; procedure TrgContagemEstoqueAftIns(var ScriptSQL: TZSQLProcessor); procedure TrgContagemEstoqueAftDel(var ScriptSQL: TZSQLProcessor); procedure TrgTabelaConversaoAftDel(var ScriptSQL: TZSQLProcessor); procedure TrgTabelaPrecosAftDel(var ScriptSQL: TZSQLProcessor); implementation function TriggerExiste(aNomeTrigger: string): Boolean; begin with TZReadOnlyQuery.Create(nil) do begin Connection := dmPrincipal.Database; try SQL.Text := 'select count(*) from information_schema.triggers where trigger_schema=:pDatabase and trigger_name=:pNomeTrigger'; ParamByName('pDatabase').AsString := dmPrincipal.Database.Database; ParamByName('pNomeTrigger').AsString := aNomeTrigger; Open; Result := Fields[0].AsInteger > 0; finally Close; Free; end; end; end; procedure TrgContagemEstoqueAftIns(var ScriptSQL: TZSQLProcessor); begin if not TriggerExiste('trg_contagem_estoque_aft_ins') then begin ScriptSQL.Script.Clear; ScriptSQL.Script.Add('CREATE TRIGGER trg_contagem_estoque_aft_ins'); ScriptSQL.Script.Add('AFTER INSERT ON contagem_estoque'); ScriptSQL.Script.Add('FOR EACH ROW'); ScriptSQL.Script.Add('BEGIN'); ScriptSQL.Script.Add(' If (NOT EXISTS(SELECT data FROM contagem_estoque_data WHERE data = NEW.data and empresa_codigo = NEW.empresa_codigo)) THEN'); ScriptSQL.Script.Add(' INSERT INTO contagem_estoque_data VALUES('); ScriptSQL.Script.Add(' NEW.empresa_codigo,NEW.data'); ScriptSQL.Script.Add(' );'); ScriptSQL.Script.Add(' END IF;'); ScriptSQL.Script.Add('END $$'); ScriptSQL.Execute; end; end; procedure TrgContagemEstoqueAftDel(var ScriptSQL: TZSQLProcessor); begin if not TriggerExiste('trg_contagem_estoque_aft_delete') then begin ScriptSQL.Script.Clear; ScriptSQL.Script.Add('DROP TRIGGER IF EXISTS trg_contagem_estoque_aft_del $$'); ScriptSQL.Script.Add(''); ScriptSQL.Script.Add('CREATE TRIGGER trg_contagem_estoque_aft_delete'); ScriptSQL.Script.Add('AFTER DELETE ON contagem_estoque'); ScriptSQL.Script.Add('FOR EACH ROW'); ScriptSQL.Script.Add('BEGIN'); ScriptSQL.Script.Add(' DELETE FROM contagem_estoque_data WHERE not exists('); ScriptSQL.Script.Add(' select * from contagem_estoque where data=OLD.data and empresa_codigo=OLD.empresa_codigo) and data=OLD.data;'); ScriptSQL.Script.Add('END $$'); ScriptSQL.Execute; end; end; procedure TrgTabelaConversaoAftDel(var ScriptSQL: TZSQLProcessor); begin if not TriggerExiste('trg_tabela_conversao_aft_del') then begin ScriptSQL.Script.Clear; ScriptSQL.Script.Add('CREATE TRIGGER trg_tabela_conversao_aft_del'); ScriptSQL.Script.Add('AFTER DELETE ON tabela_conversao'); ScriptSQL.Script.Add('FOR EACH ROW'); ScriptSQL.Script.Add('BEGIN'); ScriptSQL.Script.Add(' DELETE FROM tabela_conversao_itens WHERE id_tabela=OLD.id;'); ScriptSQL.Script.Add('END $$'); ScriptSQL.Execute; end; end; procedure TrgTabelaPrecosAftDel(var ScriptSQL: TZSQLProcessor); begin if not TriggerExiste('trg_tabela_precos_aft_del') then begin ScriptSQL.Script.Clear; ScriptSQL.Script.Add('CREATE TRIGGER trg_tabela_precos_aft_del'); ScriptSQL.Script.Add('AFTER DELETE ON tabela_precos'); ScriptSQL.Script.Add('FOR EACH ROW'); ScriptSQL.Script.Add('BEGIN'); ScriptSQL.Script.Add(' DELETE FROM tabela_precos_itens WHERE id_periodo=OLD.id;'); ScriptSQL.Script.Add('END $$'); ScriptSQL.Execute; end; end; end.
unit StockDataTestAppAgent; interface uses Forms, Sysutils, Windows, Classes, BaseApp, BaseForm, define_dealItem, define_stockapp, define_StockDataApp, win.process; type PDownloadTask = ^TDownloadTask; TDownloadTask = record DownloadProcess : TOwnedProcess; TaskID : Integer; TaskDataSrc : Integer; TaskDealItemCode : Integer; TaskDataType : Integer; DealItemIndex: Integer; DealItem: PRT_DealItem; end; PConsoleAppData = ^TConsoleAppData; TConsoleAppData = record ConsoleForm: BaseForm.TfrmBase; TaskList: TList; //RequestDownloadTask: TDownloadTask; end; TStockDataTestAppAgent = class(BaseApp.TBaseAppAgent) protected fConsoleAppData: TConsoleAppData; public constructor Create(AHostApp: TBaseApp); override; destructor Destroy; override; function Initialize: Boolean; override; procedure Run; override; procedure ClearTask; function GetDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; function NewDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; function CheckOutDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; function GetDownloadTaskByProcessID(AProcessId: integer): PDownloadTask; function CreateAppCommandWindow: Boolean; function Console_GetNextDownloadDealItem(ADownloadTask: PDownloadTask): PRT_DealItem; procedure Console_NotifyDownloadData(ADownloadTask: PDownloadTask); function Console_CheckDownloaderProcess(ADownloadTask: PDownloadTask): Boolean; procedure Console_NotifyDownloaderShutdown(ADownloadTask: PDownloadTask); end; implementation uses windef_msg, BaseStockApp, SDDataTestForm, UtilsLog; var G_StockDataConsoleApp: TStockDataTestAppAgent = nil; function AppCommandWndProcA(AWnd: HWND; AMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; var tmpStockCode: integer; tmpDataSrc: integer; tmpDownloadTask: PDownloadTask; tmpDealItem: PRT_DealItem; begin Result := 0; case AMsg of WM_AppStart: begin end; WM_AppRequestEnd: begin if nil <> GlobalBaseStockApp then begin GlobalBaseStockApp.Terminate; end; end; WM_AppNotifyShutdownMachine: begin end; WM_Console_Command_Download: begin if nil <> GlobalBaseStockApp then begin //GlobalBaseStockApp.RunStart; if nil <> G_StockDataConsoleApp then begin tmpDataSrc := lParam; tmpStockCode := wParam; tmpDownloadTask := G_StockDataConsoleApp.GetDownloadTask(tmpDataSrc, tmpStockCode); if nil = tmpDownloadTask then begin tmpDownloadTask := G_StockDataConsoleApp.NewDownloadTask(tmpDataSrc, tmpStockCode); end; if G_StockDataConsoleApp.Console_CheckDownloaderProcess(tmpDownloadTask) then begin G_StockDataConsoleApp.Console_NotifyDownloadData(tmpDownloadTask); end; end; end; exit; end; WM_Downloader2Console_Command_DownloadResult: begin tmpDownloadTask := G_StockDataConsoleApp.GetDownloadTaskByProcessID(wParam); if nil <> tmpDownloadTask then begin if 0 = lParam then begin // 下载成功 tmpDealItem := G_StockDataConsoleApp.Console_GetNextDownloadDealItem(tmpDownloadTask); if nil <> tmpDealItem then begin tmpDownloadTask.DealItem := tmpDealItem; PostMessage(AWnd, WM_Console_Command_Download, tmpDownloadTask.TaskDealItemCode, tmpDownloadTask.TaskDataSrc); end else begin // 都下载完了 ??? G_StockDataConsoleApp.Console_NotifyDownloaderShutdown(tmpDownloadTask); //PostMessage(AWnd, WM_AppRequestEnd, 0, 0); end; end else begin // 下载失败 PostMessage(AWnd, WM_Console_Command_Download, 0, 0); end; end; end; end; Result := DefWindowProcA(AWnd, AMsg, wParam, lParam); end; { TStockDataConsoleApp } constructor TStockDataTestAppAgent.Create(AHostApp: TBaseApp); begin inherited; G_StockDataConsoleApp := Self; FillChar(fConsoleAppData, SizeOf(fConsoleAppData), 0); fConsoleAppData.TaskList := TList.Create; end; destructor TStockDataTestAppAgent.Destroy; begin if G_StockDataConsoleApp = Self then begin G_StockDataConsoleApp := nil; end; ClearTask; FreeAndNil(fConsoleAppData.TaskList); inherited; end; function TStockDataTestAppAgent.Initialize: Boolean; begin Result := inherited Initialize; if Result then begin Application.Initialize; Result := CreateAppCommandWindow; end; end; procedure TStockDataTestAppAgent.Run; begin Application.CreateForm(TfrmSDDataTest, fConsoleAppData.ConsoleForm); fConsoleAppData.ConsoleForm.Initialize(fBaseAppAgentData.HostApp); Application.Run; end; procedure TStockDataTestAppAgent.ClearTask; var i: Integer; tmpTask: PDownloadTask; begin if nil <> fConsoleAppData.TaskList then begin for i := fConsoleAppData.TaskList.Count - 1 downto 0 do begin tmpTask := fConsoleAppData.TaskList.Items[i]; FreeMem(tmpTask); end; fConsoleAppData.TaskList.Clear; end; end; function TStockDataTestAppAgent.GetDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; var i: Integer; tmpTask: PDownloadTask; begin Result := nil; if nil <> fConsoleAppData.TaskList then begin for i := fConsoleAppData.TaskList.Count - 1 downto 0 do begin tmpTask := fConsoleAppData.TaskList.Items[i]; if (tmpTask.TaskDataSrc = ATaskDataSrc) and ((tmpTask.TaskDealItemCode = ATaskDealItemCode)) then begin Result := tmpTask; Break; end; end; end; end; function TStockDataTestAppAgent.GetDownloadTaskByProcessID(AProcessId: integer): PDownloadTask; var i: Integer; tmpTask: PDownloadTask; begin Result := nil; if nil <> fConsoleAppData.TaskList then begin for i := fConsoleAppData.TaskList.Count - 1 downto 0 do begin tmpTask := fConsoleAppData.TaskList.Items[i]; if tmpTask.DownloadProcess.Core.ProcessId = AProcessId then begin Result := tmpTask; Break; end; end; end; end; function TStockDataTestAppAgent.NewDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; begin Result := System.New(PDownloadTask); FillChar(Result^, SizeOf(TDownloadTask), 0); Result.TaskDataSrc := ATaskDataSrc; Result.TaskDealItemCode := ATaskDealItemCode; fConsoleAppData.TaskList.Add(Result); end; function TStockDataTestAppAgent.CheckOutDownloadTask(ATaskDataSrc, ATaskDealItemCode: integer): PDownloadTask; begin Result := GetDownloadTask(ATaskDataSrc, ATaskDealItemCode); if nil = Result then Result := NewDownloadTask(ATaskDataSrc, ATaskDealItemCode); end; function TStockDataTestAppAgent.CreateAppCommandWindow: Boolean; var tmpRegWinClass: TWndClassA; tmpGetWinClass: TWndClassA; tmpIsReged: Boolean; begin Result := false; FillChar(tmpRegWinClass, SizeOf(tmpRegWinClass), 0); tmpRegWinClass.hInstance := HInstance; tmpRegWinClass.lpfnWndProc := @AppCommandWndProcA; tmpRegWinClass.lpszClassName := AppCmdWndClassName_StockDataDownloader_Console; tmpIsReged := GetClassInfoA(HInstance, tmpRegWinClass.lpszClassName, tmpGetWinClass); if tmpIsReged then begin if (tmpGetWinClass.lpfnWndProc <> tmpRegWinClass.lpfnWndProc) then begin UnregisterClassA(tmpRegWinClass.lpszClassName, HInstance); tmpIsReged := false; end; end; if not tmpIsReged then begin if 0 = RegisterClassA(tmpRegWinClass) then exit; end; TBaseStockApp(fBaseAppAgentData.HostApp).AppWindow := CreateWindowExA( WS_EX_TOOLWINDOW //or WS_EX_APPWINDOW //or WS_EX_TOPMOST , tmpRegWinClass.lpszClassName, '', WS_POPUP {+ 0}, 0, 0, 0, 0, HWND_MESSAGE, 0, HInstance, nil); Result := Windows.IsWindow(TBaseStockApp(fBaseAppAgentData.HostApp).AppWindow); end; procedure TStockDataTestAppAgent.Console_NotifyDownloadData(ADownloadTask: PDownloadTask); begin if nil = ADownloadTask then exit; if nil = ADownloadTask.DealItem then ADownloadTask.DealItem := Console_GetNextDownloadDealItem(ADownloadTask); if nil = ADownloadTask.DealItem then begin PostMessage(ADownloadTask.DownloadProcess.Core.AppCmdWnd, WM_AppRequestEnd, 0, 0); exit; end; if Console_CheckDownloaderProcess(ADownloadTask) then begin PostMessage(ADownloadTask.DownloadProcess.Core.AppCmdWnd, WM_Console2Downloader_Command_Download, ADownloadTask.DealItem.iCode, ADownloadTask.TaskDataSrc); end; end; function TStockDataTestAppAgent.Console_GetNextDownloadDealItem(ADownloadTask: PDownloadTask): PRT_DealItem; var tmpDealItem: PRT_DealItem; begin Result := nil; if 1 > TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.RecordCount then exit; if 0 > ADownloadTask.DealItemIndex then ADownloadTask.DealItemIndex := 0; if TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.RecordCount <= ADownloadTask.DealItemIndex then exit; if 0 <> ADownloadTask.TaskDealItemCode then begin if nil = ADownloadTask.DealItem then begin ADownloadTask.DealItem := TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.FindItem(IntToStr(ADownloadTask.TaskDealItemCode)); Result := ADownloadTask.DealItem; end; if nil <> ADownloadTask.DealItem then begin if ADownloadTask.DealItem.iCode = ADownloadTask.TaskDealItemCode then begin end; end; exit; end; if nil = ADownloadTask.DealItem then begin ADownloadTask.DealItemIndex := 0; end; if nil = ADownloadTask.DealItem then begin Result := TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.Items[ADownloadTask.DealItemIndex]; ADownloadTask.DealItem := Result; end else begin tmpDealItem := TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.Items[ADownloadTask.DealItemIndex]; if ADownloadTask.DealItem.iCode = tmpDealItem.iCode then begin while nil = Result do begin Inc(ADownloadTask.DealItemIndex); if TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.RecordCount > ADownloadTask.DealItemIndex then begin tmpDealItem := TBaseStockApp(fBaseAppAgentData.HostApp).StockItemDB.Items[ADownloadTask.DealItemIndex]; if 0 = tmpDealItem.EndDealDate then begin Result := tmpDealItem; ADownloadTask.DealItem := Result; end; end else begin Break; end; end; end; end; end; function TStockDataTestAppAgent.Console_CheckDownloaderProcess(ADownloadTask: PDownloadTask): Boolean; var i: integer; tmpRetCode: DWORD; begin Result := false; if nil = ADownloadTask then exit; Result := IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd); if not Result then begin if 0 <> ADownloadTask.DownloadProcess.Core.ProcessHandle then begin if Windows.GetExitCodeProcess(ADownloadTask.DownloadProcess.Core.ProcessHandle, tmpRetCode) then begin if Windows.STILL_ACTIVE <> tmpRetCode then ADownloadTask.DownloadProcess.Core.ProcessId := 0; end; end else begin ADownloadTask.DownloadProcess.Core.ProcessId := 0; end; if 0 = ADownloadTask.DownloadProcess.Core.ProcessId then RunProcessA(@ADownloadTask.DownloadProcess, ParamStr(0)); if (0 = ADownloadTask.DownloadProcess.Core.ProcessHandle) or (INVALID_HANDLE_VALUE = ADownloadTask.DownloadProcess.Core.ProcessHandle) then exit; for i := 0 to 100 do begin if IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd) then Break; ADownloadTask.DownloadProcess.Core.AppCmdWnd := Windows.FindWindowA(AppCmdWndClassName_StockDataDownloader, nil); Sleep(10); end; end; Result := IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd); end; procedure TStockDataTestAppAgent.Console_NotifyDownloaderShutdown(ADownloadTask: PDownloadTask); begin if IsWindow(ADownloadTask.DownloadProcess.Core.AppCmdWnd) then begin PostMessage(ADownloadTask.DownloadProcess.Core.AppCmdWnd, WM_AppRequestEnd, 0, 0); end; end; end.
unit GX_UsesManager; // Add to, remove from, and query the uses clauses of Object Pascal units // Orginal Author: Krzysztof Jez - krzysztofj@bms.com.pl // Modified by Erik Berry to remove external dependencies and cleanup // These routines do not support C++ source // note: Even though TUsesManager.Create takes a parameter specifying the unit to work on // this is only used in the parser. Any of the methodes manipulating the uses list // always work on the current source editor. interface uses Classes, Contnrs, ToolsAPI, mPasLex; type TUsesItem = class(TObject) Name: string; BeginPos: Longint; EndPos: Longint; // Position at the end of the unit name CommaBeforePos: Longint; // Position of ',' before unit name CommaAfterPos: Longint; // Position of ',' after unit name SpaceAfter: Boolean; end; TUsesList = class(TObjectList) private function GetItem(AIndex: Integer): TUsesItem; procedure SetItem(AIndex: Integer; const Value: TUsesItem); public function Add: TUsesItem; function IndexOf(const AUnitName: string): Integer; property Items[AIndex: Integer]: TUsesItem read GetItem write SetItem; end; TUsesStatus = (usNonExisting, usInterface, usImplementation, usInsideUnit); TPosInUsesList = (puInterface, puImplementation, puNo); TUsesManager = class(TObject) private FFileContent: string; FInterfUses: TUsesList; FImplemUses: TUsesList; FImplPosition: Integer; // Position of the last char of the "implementation" keyword FIntfPosition: Integer; // Position of the last char of the "interface" keyword FBegOfIntfUses: Integer; // Position of first char of interface "uses" keyword FEndOfIntfUses: Integer; // Position of the semicolon which ends interface uses clause FBegOfImplUses: Integer; // Position of first char of implementation "uses" keyword FEndOfImplUses: Integer; // Position of the semicolon which ends implementation uses clause FFileName: string; procedure BuildUsesList; function GetCurrentUnitName: string; function UsesLineWouldBeTooLong(InsertPos, InsertLength: Integer): Boolean; procedure InternalInit; procedure InternalReplaceInUses(UsesList: TUsesList; const AOldUnitName, ANewUnitName: string); function InternalAddToUsesSection(const AUnitName: string; ToInterface: Boolean): Boolean; procedure InternalRemoveFromUses(InInterface: Boolean; const AUnitName: string); public constructor Create(const SourceEditor: IOTASourceEditor); overload; constructor Create(const FileName: string); overload; destructor Destroy; override; function GetUsesStatus(const AUnitName: string): TUsesStatus; function AddToImpSection(const AUnitName: string): Boolean; function AddToIntSection(const AUnitName: string): Boolean; function IsPositionBeforeImplementation(Pos: Integer): Boolean; function IsPositionInUsesList(Pos: integer): TPosInUsesList; procedure AddUnits(AUnits: TStrings; AToImplementation: Boolean = True); procedure RemoveFromImplUses(const AUnitName: string); procedure RemoveImplementationUses; procedure RemoveFromIntfUses(const AUnitName: string); procedure RemoveInterfaceUses; procedure ReplaceInImplUses(const AOldUnitName, ANewUnitName: string); procedure ReplaceInIntUses(const AOldUnitName, ANewUnitName: string); property ImplementationUses: TUsesList read FImplemUses; property InterfaceUses: TUsesList read FInterfUses; end; // These act on the current source editor function UseUnitInImplementation(const AUnitName: string): Boolean; function UseUnitInInterface(const AUnitName: string): Boolean; function GetUsesStatus(const AUnitName: string): TUsesStatus; procedure GetImplementationUnits(Units: TStrings); procedure GetInterfaceUnits(Units: TStrings); procedure RemoveUnitFromImplementation(const AUnitName: string); procedure RemoveUnitFromInterface(const AUnitName: string); procedure ReplaceUnitInImplementation(const AOldUnitName, ANewUnitName: string); procedure ReplaceUnitInInterface(const AOldUnitName, ANewUnitName: string); implementation uses SysUtils, GX_OtaUtils, GX_GenericUtils; function UseUnitInImplementation(const AUnitName: string): Boolean; begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try Result := AddToImpSection(AUnitName); finally Free; end; end; function UseUnitInInterface(const AUnitName: string): Boolean; begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try Result := AddToIntSection(AUnitName); finally Free; end; end; function GetUsesStatus(const AUnitName: string): TUsesStatus; begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try Result := GetUsesStatus(AUnitName); finally Free; end; end; procedure InternalGetUnits(Units: TStrings; FromIntf: Boolean); var i: Integer; UsesList: TUsesList; begin Assert(Assigned(Units)); Units.Clear; with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try if FromIntf then UsesList := FInterfUses else UsesList := FImplemUses; for i := 0 to UsesList.Count - 1 do Units.Add(UsesList.Items[i].Name); finally Free; end; end; procedure GetImplementationUnits(Units: TStrings); begin InternalGetUnits(Units, False); end; procedure GetInterfaceUnits(Units: TStrings); begin InternalGetUnits(Units, True); end; procedure RemoveUnitFromImplementation(const AUnitName: string); begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try RemoveFromImplUses(AUnitName); finally Free; end; end; procedure RemoveUnitFromInterface(const AUnitName: string); begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try RemoveFromIntfUses(AUnitName); finally Free; end; end; procedure ReplaceUnitInImplementation(const AOldUnitName, ANewUnitName: string); begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try ReplaceInImplUses(AOldUnitName, ANewUnitName); finally Free; end; end; procedure ReplaceUnitInInterface(const AOldUnitName, ANewUnitName: string); begin with TUsesManager.Create(GxOtaGetCurrentSourceEditor) do try ReplaceInIntUses(AOldUnitName, ANewUnitName); finally Free; end; end; constructor TUsesManager.Create(const SourceEditor: IOTASourceEditor); begin inherited Create; Assert(Assigned(SourceEditor)); FFileName := SourceEditor.FileName; FFileContent := GxOtaReadEditorTextToString(SourceEditor.CreateReader); InternalInit; end; constructor TUsesManager.Create(const FileName: string); var sl: TStringList; begin inherited Create; FFileName := FileName; sl := TStringList.Create; try sl.LoadFromFile(FFileName); FFileContent := sl.Text; finally FreeAndNil(sl); end; InternalInit; end; procedure TUsesManager.InternalInit; begin FInterfUses := TUsesList.Create; FImplemUses := TUsesList.Create; BuildUsesList; end; destructor TUsesManager.Destroy; begin FreeAndNil(FInterfUses); FreeAndNil(FImplemUses); inherited Destroy; end; function TUsesManager.AddToImpSection(const AUnitName: string): Boolean; begin Result := InternalAddToUsesSection(AUnitName, False); end; function TUsesManager.AddToIntSection(const AUnitName: string): Boolean; begin Result := InternalAddToUsesSection(AUnitName, True); end; // Add a unit to a uses clause (may require removing it from the other clause) function TUsesManager.InternalAddToUsesSection(const AUnitName: string; ToInterface: Boolean): Boolean; var InsertPosition: Integer; LastUses: TUsesItem; InsertString: string; Status: TUsesStatus; UsesItems: TUsesList; UsesPos: Integer; begin Result := False; Status := GetUsesStatus(AUnitName); if Status = usInsideUnit then Exit; if ToInterface then begin if Status = usImplementation then RemoveFromImplUses(AUnitName) else if Status = usInterface then Exit; UsesPos := FIntfPosition; UsesItems := FInterfUses; end else begin // Add to implementation if Status in [usInterface, usImplementation] then Exit; UsesPos := FImplPosition; UsesItems := FImplemUses; end; if UsesPos = 0 then Exit; // If a uses item exists if UsesItems.Count > 0 then begin // Retrieve the position after the last uses item LastUses := UsesItems.Items[UsesItems.Count - 1]; InsertPosition := LastUses.EndPos; InsertString := ', ' + AUnitName; if UsesLineWouldBeTooLong(InsertPosition, Length(InsertString)) then InsertString := ',' + sLineBreak + ' ' + AUnitName; // Insert the new unit name into the uses clause GxOtaInsertTextIntoEditorAtCharPos(InsertString, InsertPosition); end else // The uses clause does not exist begin InsertString := sLineBreak + sLineBreak +'uses'+ sLineBreak +' '+ AUnitName +';'; GxOtaInsertTextIntoEditorAtCharPos(InsertString, UsesPos); end; // This needs to be done last since it changes the implementation offsets if not ToInterface then begin if Status = usInterface then RemoveFromIntfUses(AUnitName); end; Result := True; end; procedure TUsesManager.AddUnits(AUnits: TStrings; AToImplementation: Boolean); var UnitName: string; i: Integer; begin for i := 0 to AUnits.Count - 1 do begin UnitName := AUnits.Strings[i]; if AToImplementation then AddToImpSection(UnitName) else AddToIntSection(UnitName); end; end; procedure TUsesManager.BuildUsesList; var Section: (sImplementation, sInterface); InUses: Boolean; UsesItem: TUsesItem; LastCommaPos: Integer; Parser: TmwPasLex; begin Parser := TmwPasLex.Create; try Parser.Origin := @FFileContent[1]; Section := sInterface; InUses := False; Parser.RunPos := 0; FBegOfImplUses := 0; FImplPosition := 0; FIntfPosition := 0; FEndOfIntfUses := 0; FBegOfIntfUses := 0; UsesItem := nil; LastCommaPos := 0; Parser.NextNoJunk; while Parser.TokenID <> tkNull do begin case Parser.TokenID of tkInterface: begin Section := sInterface; FIntfPosition := Parser.RunPos; InUses := False; LastCommaPos := 0; end; tkImplementation: begin Section := sImplementation; FImplPosition := Parser.RunPos; InUses := False; LastCommaPos := 0; end; tkUses: begin InUses := True; if Section = sImplementation then FBegOfImplUses := Parser.RunPos - Length('uses'); if Section = sInterface then FBegOfIntfUses := Parser.RunPos - Length('uses'); LastCommaPos := 0; end; else // If it is after the unit identifier if InUses and not (Parser.TokenID in [tkCompDirect, tkIn, tkString]) then begin if Parser.TokenID = tkIdentifier then begin if Section = sInterface then UsesItem := FInterfUses.Add else // Section = sImplementation UsesItem := FImplemUses.Add; {$IFOPT D+} Assert(UsesItem <> nil); {$ENDIF} UsesItem.Name := Parser.GetDottedIdentifierAtPos(True); UsesItem.EndPos := Parser.RunPos; UsesItem.BeginPos := UsesItem.EndPos - Length(UsesItem.Name); if LastCommaPos <> 0 then UsesItem.CommaBeforePos := LastCommaPos - 1; UsesItem.CommaAfterPos := 0; end // tkIdentifier else if Parser.TokenID = tkComma then begin LastCommaPos := Parser.RunPos; if UsesItem <> nil then begin UsesItem.CommaAfterPos := LastCommaPos - 1; if Parser.NextChar = ' ' then UsesItem.SpaceAfter := True; end; end else // FParser.TokenID <> tkComma begin InUses := False; if Section = sImplementation then begin FEndOfImplUses := Parser.RunPos; Break; // End of parsing end; if Section = sInterface then FEndOfIntfUses := Parser.RunPos; end; // Not comma end; // UsesFlag end; Parser.NextNoJunk; end; finally FreeAndNil(Parser); end; end; function TUsesManager.GetCurrentUnitName: string; begin Result := Trim(ExtractPureFileName(FFileName)); end; function TUsesManager.GetUsesStatus(const AUnitName: string): TUsesStatus; begin if SameFileName(GetCurrentUnitName, Trim(AUnitName)) then Result := usInsideUnit else if FInterfUses.IndexOf(AUnitName) > -1 then Result := usInterface else if FImplemUses.IndexOf(AUnitName) > -1 then Result := usImplementation else Result := usNonExisting; end; { Remove a unit from a uses clause Algorithm to remove Unit1: If the unit at the start of the uses clause: uses Unit1; // Only unit in the uses clause -> Remove the whole uses clause uses Unit1, Unit2; // There is a unit after Unit1 -> Remove the unit name and trailing comma If the unit is the last one in the uses clause: uses Unit2, Unit1; -> Remove the unit name and comma before it If the unit the middle of the uses clause: uses Unit2, Unit1, Unit3; // Comma directly after the unit name -> The Unit name and trailing comma are deleted uses Unit2 ,Unit1 ,Unit3; // Comma not directly after the unit name -> The Unit name and preceeding comma are deleted } procedure TUsesManager.InternalRemoveFromUses(InInterface: Boolean; const AUnitName: string); var DeletedUnit: TUsesItem; UnitIndex: Integer; BegPos, EndPos: Integer; UsesList: TUsesList; begin if InInterface then UsesList := FInterfUses else UsesList := FImplemUses; UnitIndex := UsesList.IndexOf(AUnitName); if UnitIndex > -1 then begin // If this is the only uses unit, we delete the whole clause if UsesList.Count = 1 then begin if InInterface then RemoveInterfaceUses else RemoveImplementationUses; end else begin DeletedUnit := UsesList.Items[UnitIndex]; if UnitIndex = 0 then // First in the uses clause begin if DeletedUnit.CommaAfterPos <> 0 then EndPos := DeletedUnit.CommaAfterPos + 1 else EndPos := DeletedUnit.EndPos; BegPos := DeletedUnit.BeginPos; end else if UnitIndex = UsesList.Count-1 then // Last in the uses clause begin EndPos := DeletedUnit.EndPos; if DeletedUnit.CommaBeforePos <> 0 then BegPos := DeletedUnit.CommaBeforePos else BegPos := DeletedUnit.BeginPos; end else // In the middle of the uses clause begin if DeletedUnit.CommaAfterPos = DeletedUnit.EndPos then begin // Comma directly after unit BegPos := DeletedUnit.BeginPos; EndPos := DeletedUnit.CommaAfterPos + 1; end else // Comma before unit begin if DeletedUnit.CommaBeforePos <> 0 then BegPos := DeletedUnit.CommaBeforePos else BegPos := DeletedUnit.BeginPos; EndPos := DeletedUnit.EndPos; end; end; if DeletedUnit.SpaceAfter then Inc(EndPos); GxOtaDeleteTextFromPos(BegPos, EndPos - BegPos); end; end; end; // Remove the whole implementation uses clause procedure TUsesManager.RemoveImplementationUses; var BegIndex, Count: Integer; begin if (FBegOfImplUses = 0) or (FEndOfImplUses = 0) then raise Exception.Create('RemoveImplementationUses: Begin or End of uses clause is not available!'); BegIndex := FBegOfImplUses; Count := FEndOfImplUses - BegIndex; GxOtaDeleteTextFromPos(BegIndex, Count); end; procedure TUsesManager.RemoveFromImplUses(const AUnitName: string); begin InternalRemoveFromUses(False, AUnitName); end; procedure TUsesManager.RemoveFromIntfUses(const AUnitName: string); begin InternalRemoveFromUses(True, AUnitName); end; // Remove the whole interface uses clause procedure TUsesManager.RemoveInterfaceUses; var BegIndex, Count: Integer; begin if (FBegOfIntfUses = 0) or (FEndOfIntfUses = 0) then raise Exception.Create('RemoveInterfaceUses: Begin or End of uses clause is not available!'); BegIndex := FBegOfIntfUses; Count := FEndOfIntfUses - BegIndex; GxOtaDeleteTextFromPos(BegIndex, Count); end; procedure TUsesManager.InternalReplaceInUses(UsesList: TUsesList; const AOldUnitName, ANewUnitName: string); var ReplaceUnit: TUsesItem; UnitIndex: Integer; BegPos, EndPos: Integer; SourceEditor: IOTASourceEditor; begin UnitIndex := UsesList.IndexOf(AOldUnitName); if UnitIndex = -1 then exit; ReplaceUnit := UsesList.Items[UnitIndex]; SourceEditor := GxOtaGetCurrentSourceEditor; EndPos := ReplaceUnit.EndPos; BegPos := ReplaceUnit.BeginPos; GxOtaDeleteTextFromPos(BegPos, EndPos - BegPos, SourceEditor); GxOtaInsertTextIntoEditorAtCharPos(ANewUnitName, BegPos, SourceEditor); end; procedure TUsesManager.ReplaceInImplUses(const AOldUnitName, ANewUnitName: string); begin InternalReplaceInUses(FImplemUses, AOldUnitName, ANewUnitName); end; procedure TUsesManager.ReplaceInIntUses(const AOldUnitName, ANewUnitName: string); begin InternalReplaceInUses(FInterfUses, AOldUnitName, ANewUnitName); end; function TUsesList.Add: TUsesItem; begin Result := TUsesItem.Create; inherited Add(Result); end; function TUsesList.IndexOf(const AUnitName: string): Integer; begin Result := Count - 1; while Result >= 0 do begin if SameText(Items[Result].Name, AUnitName) then Break; Dec(Result); end; end; function TUsesList.GetItem(AIndex: Integer): TUsesItem; begin Result := TUsesItem(Get(AIndex)); end; procedure TUsesList.SetItem(AIndex: Integer; const Value: TUsesItem); begin Put(AIndex, Value); end; function TUsesManager.UsesLineWouldBeTooLong(InsertPos, InsertLength: Integer): Boolean; var EditView: IOTAEditView; InsertCharPos: TOTACharPos; InsertEditPos: TOTAEditPos; begin EditView := GxOtaGetTopMostEditView; Assert(Assigned(EditView)); InsertCharPos := GxOtaGetCharPosFromPos(InsertPos, EditView); EditView.ConvertPos(False, InsertEditPos, InsertCharPos); Result := (InsertEditPos.Col + InsertLength) > 80; end; function TUsesManager.IsPositionBeforeImplementation(Pos: Integer): Boolean; begin Result := FImplPosition > Pos; end; function TUsesManager.IsPositionInUsesList(Pos: Integer): TPosInUsesList; begin if (FBegOfIntfUses + Length('uses') < Pos) and (Pos < FEndOfIntfUses) then Result := puInterface else if (FBegOfImplUses + Length('uses') < Pos) and (Pos < FEndOfImplUses) then Result := puImplementation else Result := puNo; end; end.
unit arDeliveryList; interface uses Classes, l3ProtoObject, csDataPipe, daTypes ; type TarDeliveryList = class(Tl3ProtoObject) private f_List: TStrings; f_UserID: TdaUserID; function pm_GetCount: Integer; function pm_GetTaskID(anIndex: Integer): String; protected procedure Cleanup; override; public constructor Create(aUserID: TdaUserID); procedure Communicate(aPipe: TCsDataPipe); property Count: Integer read pm_GetCount; property TaskID[anIndex: Integer]: String read pm_GetTaskID; default; end; implementation uses SysUtils ; { TarDeliveryList } procedure TarDeliveryList.Cleanup; begin FreeAndNil(f_List); inherited Cleanup; end; procedure TarDeliveryList.Communicate(aPipe: TCsDataPipe); var l_Count: Integer; begin aPipe.WriteCardinal(f_UserID); l_Count := aPipe.ReadInteger; f_List.Clear; while l_Count > 0 do begin f_List.Add(aPipe.ReadLn); Dec(l_Count); end; end; constructor TarDeliveryList.Create(aUserID: TdaUserID); begin inherited Create; f_UserID := aUserID; f_List := TStringList.Create; end; function TarDeliveryList.pm_GetCount: Integer; begin Result := f_List.Count; end; function TarDeliveryList.pm_GetTaskID(anIndex: Integer): String; begin Result := f_List[anIndex]; end; end.
{ String manipulation routines. Copyright (C) 2006, 2007, 2008 Aleg Azarousky. } {$include version.inc} unit uStringUtils; interface uses Windows, classes; const ListDivider = #13; // Used in DelphiToStringEx defHumanizeDivider = '\'; // Used in StringToHumanized UnicodeLabel = #$EF#$BB#$BF; // Split a string by a given divider // Return in El - left part, in s - rest of a string procedure SplitBy(var s: string; const divider: string; var el: string); procedure WideSplitBy(var s: WideString; const divider: WideString; var el: WideString); // ANSI string <--> Wide string consider Code page of ANSI string procedure AnsiToWideString(const s: AnsiString; var ws: WideString; AnsiCodepage: LongWord); procedure WideToAnsiString(const ws: WideString; var s: AnsiString; AnsiCodepage: LongWord); // Escaped string to string (based on the JEDI Code Library (JCL)) function StrEscapedToString(const S: WideString): WideString; // Encode string to lng file string // DividerCR - substitution for #13 // DividerCRLF - substitution for #13#10 function StringToLng(const s: WideString; Humanize: boolean; const DividerCR, DividerCRLF: WideString): WideString; // Decode lng file string to string // DividerCR - substitution for #13 // DividerCRLF - substitution for #13#10 // DefaultLineBreak - used when DividerCR = DividerCRLF function LngToString(const s: WideString; Humanize: boolean; const DividerCR, DividerCRLF, DefaultLineBreak: WideString): WideString; //Replace the Load language file elements with replace strings procedure ReplaceNew(var ws:WideString; var s:string); implementation uses SysUtils, {$ifdef D7} uLegacyCode {$else} WideStrUtils {$endif}; {$ifndef D7}{$region 'Delphi string conversions'}{$endif} procedure SplitBy(var s: string; const divider: string; var el: string); var i: integer; begin i := pos(divider, s); if i <= 0 then begin el := s; s := ''; end else begin el := copy(s, 1, i-1); delete(s, 1, i+length(divider)-1); end; end; procedure WideSplitBy(var s: WideString; const divider: WideString; var el: WideString); var i: integer; begin i := pos(divider, s); if i <= 0 then begin el := s; s := ''; end else begin el := copy(s, 1, i-1); delete(s, 1, i+length(divider)-1); end; end; procedure ReplaceNew(var ws:WideString; var s:string); var sl : TStringList; tstr: String; i : integer; val: String; begin try sl := TStringList.Create; sl.Text := s; // tstr := sl.Values[ws]; for i:=0 to sl.Count-1 do begin if pos(sl.Names[i],ws) > 0 then begin val := sl.Values[Sl.Names[i]]; tstr := StringReplace(ws, sl.Names[i], val, [rfReplaceAll, rfIgnoreCase]); ws := tstr; end; end; if tstr <> '' then ws := tstr; finally sl.free; end; end; procedure AnsiToWideString(const s: AnsiString; var ws: WideString; AnsiCodepage: LongWord); begin {$ifdef D6} My_WStrFromStr(s, ws, AnsiCodepage); {$else} SetMultiByteConversionCodePage(AnsiCodepage); ws := s; SetMultiByteConversionCodePage(CP_THREAD_ACP); {$endif} end; procedure WideToAnsiString(const ws: WideString; var s: AnsiString; AnsiCodepage: LongWord); begin SetMultiByteConversionCodePage(AnsiCodepage); s := ws; SetMultiByteConversionCodePage(CP_THREAD_ACP); end; // Encode string to delphi style string function StringToDelphi(const s: WideString): WideString; var i: integer; StrOpened: boolean; res: WideString; ch: WideChar; procedure SwitchStr; // '...' begin StrOpened := not StrOpened; res := res + ''''; end; begin StrOpened := false; if s = '' then res := '''''' else begin for i := 1 to length(s) do begin ch := s[i]; case ch of '''': begin if StrOpened then res := res + '''''' else begin res := res + ''''''''; StrOpened := true; end; end; #0..#31: begin if StrOpened then SwitchStr; res := res + '#' + IntToStr(ord(ch)); end; else begin if not StrOpened then SwitchStr; res := res + ch; end; end; end; end; if StrOpened then SwitchStr; result := res; end; type EDelphiToStringError = Class(Exception) iBadChar: integer; // Bad character position end; // Decode delphi style string to string function DelphiToString(const s: WideString): WideString; label Err; var i, iOpened: integer; res: WideString; StrOpened, CodeOpened: boolean; ch: WideChar; procedure OpenStr; // '... begin StrOpened := true; iOpened := i; end; procedure OpenCode; // #13 begin CodeOpened := true; iOpened := i; end; function CloseCode: boolean; begin try res := res + WideChar(StrToInt(copy(s, iOpened+1, i-iOpened-1))); result := true; CodeOpened := false; except result := false; end; end; var Ex: EDelphiToStringError; begin res := ''; StrOpened := false; CodeOpened := false; // 'Method ''%s'' not supported by automation object' // 'Exception %s in module %s at %p.'#13#10'%s%s'#13#10 // '''hallo' -- 'hallo''' // 'hal'''#13#10'lo' -- 'hallo''hallo' for i := 1 to length(s) do begin ch := s[i]; if StrOpened then begin // Str opened, code closed if ch = '''' then StrOpened := false else res := res + ch; end else begin if CodeOpened then begin // Str closed, code opened case ch of '''': begin if not CloseCode then goto Err; OpenStr; end; '#': begin if not CloseCode then goto Err; OpenCode; end; '0'..'9':; else goto Err; end; end else begin // Str closed, code closed case ch of '''': begin if (i > 1) and (s[i-1] = '''') then res := res + ''''; OpenStr; end; '#': OpenCode; else begin result := res; Ex := EDelphiToStringError.Create('Bad decoded string: "' + s + '"'); Ex.iBadChar := i; raise Ex; end; end; end; end; end; if StrOpened then begin Err: raise Exception.Create('Bad decoded string: "' + s + '"'); end; if CodeOpened then CloseCode; result := res; end; // Decode delphi style string and stringlist to string // Stringlist elements delimited by #13 function DelphiToStringEx(s: WideString): WideString; var res, s1: WideString; procedure AddResS1; begin if res <> '' then res := res + ListDivider; res := res + S1; end; var Ok: boolean; begin res := ''; repeat Ok := true; try s1 := DelphiToString(s); except on E: EDelphiToStringError do begin AddResS1; s := Trim(copy(s, E.iBadChar+1, MaxInt)); Ok := false; end; end; until Ok; AddResS1; result := res; end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'Escaped string conversions'}{$endif} function StrEscapedToString(const S: WideString): WideString; var I, Len, N, Val: Integer; procedure HandleHexEscapeSeq; const HexDigits = WideString('0123456789abcdefABCDEF'); begin N := Pos(S[I + 1], HexDigits) - 1; if N < 0 then // '\x' without hex digit following is not escape sequence Result := Result + '\x' else begin Inc(I); // Jump over x if N >= 16 then N := N - 6; Val := N; // Same for second digit if I < Len then begin N := Pos(S[I + 1], HexDigits) - 1; if N >= 0 then begin Inc(I); // Jump over first digit if N >= 16 then N := N - 6; Val := Val * 16 + N; end; end; if val > 255 then raise Exception.Create('Numeric constant too large'); Result := Result + WideChar(Val); end; end; procedure HandleOctEscapeSeq; const OctDigits = WideString('01234567'); begin // first digit Val := Pos(S[I], OctDigits) - 1; if I < Len then begin N := Pos(S[I + 1], OctDigits) - 1; if N >= 0 then begin Inc(I); Val := Val * 8 + N; end; if I < Len then begin N := Pos(S[I + 1], OctDigits) - 1; if N >= 0 then begin Inc(I); Val := Val * 8 + N; end; end; end; if val > 255 then raise Exception.Create('Numeric constant too large'); Result := Result + WideChar(Val); end; begin Result := ''; I := 1; Len := Length(S); while I <= Len do begin if not ((S[I] = '\') and (I < Len)) then Result := Result + S[I] else begin Inc(I); // Jump over escape character case S[I] of 'a': Result := Result + #7; 'b': Result := Result + #8; 'f': Result := Result + #12; 'n': Result := Result + #10; 'r': Result := Result + #13; 't': Result := Result + #9; 'v': Result := Result + #11; '\', '"', '''', '?': Result := Result + S[I]; 'x': if I < Len then // Start of hex escape sequence HandleHexEscapeSeq else // '\x' at end of string is not escape sequence Result := Result + '\x'; '0'..'7': // start of octal escape sequence HandleOctEscapeSeq; else // no escape sequence Result := Result + '\' + S[I]; end; end; Inc(I); end; end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'Humanized string conversions'}{$endif} // Encode string to "humanized" style string // DividerCR - substitution for #13 // DividerCRLF - substitution for #13#10 function StringToHumanized(const s: WideString; const DividerCR, DividerCRLF: WideString): WideString; begin if (pos(DividerCR, s) > 0) or (pos(DividerCRLF, s) > 0) then raise Exception.CreateFmt( 'String "%s" contains a humanize divider "%s" or "%s" and can''t be converted properly.'#13#10 + 'Try set a different string as the divider for this application.', [s, DividerCR, DividerCRLF]); result := WideStringReplace( WideStringReplace(s, sLineBreak, DividerCRLF, [rfReplaceAll]), #13, DividerCR, [rfReplaceAll]); end; // Decode "humanized" style string to string // DividerCR - substitution for #13 // DividerCRLF - substitution for #13#10 // DefaultLineBreak - used when DividerCR = DividerCRLF function HumanizedToString(const s: WideString; const DividerCR, DividerCRLF, DefaultLineBreak: WideString): WideString; begin if DividerCR = DividerCRLF then result := WideStringReplace(s, DividerCR, DefaultLineBreak, [rfReplaceAll]) else begin result := WideStringReplace(s, DividerCR, #13, [rfReplaceAll]); result := WideStringReplace(result, DividerCRLF, sLineBreak, [rfReplaceAll]); end; end; {$ifndef D7}{$endregion}{$endif} {$ifndef D7}{$region 'Lng file string conversions'}{$endif} function StringToLng(const s: WideString; Humanize: boolean; const DividerCR, DividerCRLF: WideString): WideString; begin if Humanize then result := StringToHumanized(s, DividerCR, DividerCRLF) else result := StringToDelphi(s); end; function LngToString(const s: WideString; Humanize: boolean; const DividerCR, DividerCRLF, DefaultLineBreak: WideString): WideString; begin if Humanize then result := HumanizedToString(s, DividerCR, DividerCRLF, DefaultLineBreak) else result := DelphiToStringEx(s); end; {$ifndef D7}{$endregion}{$endif} end.
unit channellisttests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, ChannelList, IRCViewIntf; type { TChannelListTests } TChannelListTests = class(TTestCase) private FSUT: TChannelList; FChannel1: TChannel; FChannel2: TChannel; procedure Add2ChannelsWith2UsersEach; protected procedure SetUp; override; procedure TearDown; override; published procedure AutoCompleteNickNames; procedure ChannelByName; procedure UserByNick; procedure NickNameChanged; procedure UserNickNameChanged; procedure UserQuit; procedure RemoveUserFromChannel; procedure CloseChannelWhenCurrentUserParts; procedure JoinChannel; end; implementation uses fakeview; { TChannelListTests } const StrChannel1 = '#channel1'; StrChannel2 = '#channel2'; StrUser1Channel1 = '@User1C1'; StrUser2Channel1 = '+User2C1'; StrUser1Channel2 = '@User1C2'; StrUser2Channel2 = '+User2C2'; procedure TChannelListTests.Add2ChannelsWith2UsersEach; begin FChannel1.Users.Add(TUser.Create(StrUser1Channel1)); FChannel1.Users.Add(TUser.Create(StrUser2Channel1)); FChannel2.Users.Add(TUser.Create(StrUser1Channel2)); FChannel2.Users.Add(TUser.Create(StrUser2Channel2)); end; procedure TChannelListTests.SetUp; begin inherited SetUp; FSUT := TChannelList.Create(TFakeView.Create); FChannel1 := TChannel.Create(StrChannel1); FSUT.Add(FChannel1); FChannel2 := TChannel.Create(StrChannel2); FSUT.Add(FChannel2); end; procedure TChannelListTests.TearDown; begin FreeAndNil(FSUT); inherited TearDown; end; procedure TChannelListTests.AutoCompleteNickNames; begin Add2ChannelsWith2UsersEach; CheckEquals('User1C1', FSUT.AutoComplete(StrChannel1, 'User')); CheckEquals('', FSUT.AutoComplete(StrChannel1, 'User1C2')); CheckEquals('', FSUT.AutoComplete(StrChannel1, 'User3')); end; procedure TChannelListTests.ChannelByName; const StrChannel1CamelCase = '#Channel1'; begin CheckTrue(FChannel1 = FSUT.ChannelByName(StrChannel1), 'Invalid channel'); CheckTrue(FChannel1 = FSUT.ChannelByName(StrChannel1CamelCase), 'Search should be case insensitive'); CheckFalse(Assigned(FSUT.ChannelByName('#newchannel')), 'Shouldnt be assigned'); end; procedure TChannelListTests.UserByNick; const StrUser1 = 'User1'; var UserList: TUserList; User1: TUser; begin UserList := TUserList.Create; try User1 := TUser.Create(StrUser1); UserList.Add(User1); UserList.Add(TUser.Create('User2')); CheckTrue(User1 = UserList.UserByNick(StrUser1), 'User not found'); CheckFalse(Assigned(UserList.UserByNick('NonUser')), 'User found'); finally UserList.Free; end; end; procedure TChannelListTests.NickNameChanged; begin FChannel1.Users.Add(TUser.Create('User1')); FChannel1.Users.Add(TUser.Create('User2')); FChannel2.Users.Add(TUser.Create('User3')); FChannel2.Users.Add(TUser.Create('User4')); FSUT.NickNameChanged('User2', 'User22'); FSUT.NickNameChanged('User3', 'User33'); CheckEquals('User1', FChannel1.Users.Items[0].NickName); CheckEquals('User22', FChannel1.Users.Items[1].NickName); CheckEquals('User33', FChannel2.Users.Items[0].NickName); CheckEquals('User4', FChannel2.Users.Items[1].NickName); end; procedure TChannelListTests.UserNickNameChanged; begin FSUT.NickName := 'nick'; FChannel1.Users.Add(TUser.Create('@nick')); FChannel2.Users.Add(TUser.Create('nick')); FSUT.NickNameChanged('nick', 'newnick'); CheckEquals('@newnick', FChannel1.Users[0].NickNameInChannel); CheckEquals('newnick', FChannel1.Users[0].NickName); CheckEquals('newnick', FChannel2.Users[0].NickNameInChannel); CheckEquals('newnick', FChannel2.Users[0].NickName); end; procedure TChannelListTests.UserQuit; begin FChannel1.Users.Add(TUser.Create('User1')); FChannel1.Users.Add(TUser.Create('User2')); FChannel2.Users.Add(TUser.Create('@User1')); FChannel2.Users.Add(TUser.Create('User3')); FSUT.Quit('User1', 'Leaving'); CheckEquals(1, FChannel1.Users.Count); CheckEquals('User2', FChannel1.Users.Items[0].NickName); CheckEquals(1, FChannel2.Users.Count); CheckEquals('User3', FChannel2.Users.Items[0].NickName); end; procedure TChannelListTests.RemoveUserFromChannel; begin FChannel1.Users.Add(TUser.Create('User1')); FChannel1.Users.Add(TUser.Create('@User2')); FChannel2.Users.Add(TUser.Create('User1')); FChannel2.Users.Add(TUser.Create('+User3')); FSUT.Parted('User1', '', StrChannel1, ''); FSUT.Parted('User2', '', StrChannel1, ''); FSUT.Parted('User3', '', StrChannel2, ''); CheckEquals(0, FChannel1.Users.Count); CheckEquals(1, FChannel2.Users.Count); CheckEquals('User1', FChannel2.Users.Items[0].NickName); end; procedure TChannelListTests.CloseChannelWhenCurrentUserParts; begin FSUT.NickName := 'Nick'; FChannel1.Users.Add(TUser.Create(FSUT.NickName)); FChannel2.Users.Add(TUser.Create('@Nick')); FSUT.Parted(FSUT.NickName, '', StrChannel1, ''); CheckEquals(1, FSUT.Count); CheckEquals(1, FChannel2.Users.Count); FSUT.Parted('Nick', '', StrChannel2, ''); CheckEquals(0, FSUT.Count); end; procedure TChannelListTests.JoinChannel; begin FSUT.Clear; FSUT.Joined('Nick', '', '#channel'); CheckEquals(1, FSUT.Count); CheckEquals('Nick', FSUT.Items[0].Users[0].NickName); FSUT.Joined('Nick2', '', '#channel'); CheckEquals(1, FSUT.Count); CheckEquals('Nick2', FSUT.Items[0].Users[1].NickName); FSUT.Joined('Nick', '', '#channel2'); CheckEquals(2, FSUT.Count); end; initialization RegisterTest(TChannelListTests); end.
unit uService; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, System.JSON, FireDAc.Comp.Client, FireDAc.Dapt; type {$METHODINFO ON} Service = class(TComponent) private { Private declarations } public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; function Ping: String; function fncRetornaItensPedido(poChavePedive: String): TJSONObject; function fncRetornaVencimentoPedido(poChavePedive: String): TJSONObject; function fncRetornaDadosPedido(poChavePedive: String): TJsonArray; end; {$METHODINFO OFF} implementation uses System.StrUtils, uDmPrincipal, Vcl.Dialogs, uDashBoard; function Service.EchoString(Value: string): string; begin Result := Value; end; function Service.fncRetornaDadosPedido(poChavePedive: String): TJsonArray; var vlJsonObject : TJSONObject; vlsEmpresa, vlsPedido : TJSONString; ja:TJsonArray; begin vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(poChavePedive), 0) as TJSONObject; vlsEmpresa := vlJsonObject.GetValue('Pedv_Empresa') as TJSONString; vlsPedido := vlJsonObject.GetValue('Pedv_Numero') as TJSONString; FDashBoard.pcdMensagemMemo('Requisição Enviada com parâmetro: Empresa: ' + vlsEmpresa.Value + ' Pedido: ' + vlsPedido.Value + ' na função fncRetornaDadosPedido'); DMPrincipal.FDCabecalhoPedido.Close; DMPrincipal.FDCabecalhoPedido.ParamByName('EMPRESA').AsString := vlsEmpresa.Value; DMPrincipal.FDCabecalhoPedido.ParamByName('NUMERO').AsString := vlsPedido.Value; DMPrincipal.FDCabecalhoPedido.Open(); ja := TJsonArray.Create; vlJsonObject := TJSONObject.Create; vlJsonObject.AddPair('Empresa', DMPrincipal.FDCabecalhoPedido.FieldByName('Empresa').AsString); vlJsonObject.AddPair('Pedido', DMPrincipal.FDCabecalhoPedido.FieldByName('Pedido').AsString); vlJsonObject.AddPair('Cliente', DMPrincipal.FDCabecalhoPedido.FieldByName('Cliente').AsString); vlJsonObject.AddPair('DataPedido', DMPrincipal.FDCabecalhoPedido.FieldByName('DataPedido').AsString); vlJsonObject.AddPair('Negociacao', DMPrincipal.FDCabecalhoPedido.FieldByName('Negociacao').AsString); vlJsonObject.AddPair('Status', DMPrincipal.FDCabecalhoPedido.FieldByName('Status').AsString); ja.AddElement(vlJsonObject); FDashBoard.pcdMensagemMemo('Requisição Entregue com o parâmetro: ' + vlJsonObject.ToString + ' da função fncRetornaDadosPedido'); Result := ja; end; function Service.fncRetornaItensPedido(poChavePedive: String): TJSONObject; var vlJsonObject, vlPropertyJson : TJSONObject; vlsEmpresa, vlsPedido : TJSONString; vlJsonList:TJsonArray; vlI: Integer; // SSArquivoStream: TStringStream; begin vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(poChavePedive), 0) as TJSONObject; vlsEmpresa := vlJsonObject.GetValue('Pedv_Empresa') as TJSONString; vlsPedido := vlJsonObject.GetValue('Pedv_Numero') as TJSONString; FDashBoard.pcdMensagemMemo('Requisição Enviada com parâmetro: Empresa: ' + vlsEmpresa.Value + ' Pedido: ' + vlsPedido.Value + ' na função fncRetornaItensPedido'); DMPrincipal.FDItensPedido.Close; DMPrincipal.FDItensPedido.ParamByName('EMPRESA').AsString := vlsEmpresa.Value; DMPrincipal.FDItensPedido.ParamByName('NUMERO').AsString := vlsPedido.Value; DMPrincipal.FDItensPedido.Open(); vlJsonList := TJsonArray.Create; vlJsonObject := TJSONObject.Create; DMPrincipal.FDItensPedido.First; DMPrincipal.FDItensPedido.FetchAll; //for I := 0 to DMPrincipal.FDItensPedido.RecordCount - 1 do while not DMPrincipal.FDItensPedido.Eof do begin vlPropertyJson := TJSONObject.Create; vlPropertyJson.AddPair('Produto', DMPrincipal.FDItensPedido.FieldByName('Produto').AsString); vlPropertyJson.AddPair('Qtde', StringReplace(DMPrincipal.FDItensPedido.FieldByName('Qtde').AsString,',', '.',[rfReplaceAll])); vlPropertyJson.AddPair('Unitario', StringReplace(DMPrincipal.FDItensPedido.FieldByName('Unitario').AsString,',', '.',[rfReplaceAll])); vlPropertyJson.AddPair('Total', StringReplace(DMPrincipal.FDItensPedido.FieldByName('Total').AsString,',', '.',[rfReplaceAll])); vlJsonList.AddElement(vlPropertyJson); DMPrincipal.FDItensPedido.Next; end; vlJsonObject.AddPair('Itens', vlJsonList); //SSArquivoStream := TStringStream.Create(vlJsonObject.ToString); //SSArquivoStream.SaveToFile('C:\JSON.txt'); FDashBoard.pcdMensagemMemo('Requisição Entregue com o parâmetro: ' + vlJsonObject.ToString + ' da função fncRetornaItensPedido'); Result := vlJsonObject; end; function Service.fncRetornaVencimentoPedido(poChavePedive: String): TJSONObject; var vlJsonObject, vlPropertyJson : TJSONObject; vlsEmpresa, vlsPedido : TJSONString; vlJsonList:TJsonArray; I: Integer; // SSArquivoStream: TStringStream; begin vlJsonObject := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(poChavePedive), 0) as TJSONObject; vlsEmpresa := vlJsonObject.GetValue('Pedv_Empresa') as TJSONString; vlsPedido := vlJsonObject.GetValue('Pedv_Numero') as TJSONString; FDashBoard.pcdMensagemMemo('Requisição Enviada com parâmetro: Empresa: ' + vlsEmpresa.Value + ' Pedido: ' + vlsPedido.Value + ' na função fncRetornaVencimentoPedido'); DMPrincipal.FDVencimentosPedido.Close; DMPrincipal.FDVencimentosPedido.ParamByName('EMPRESA').AsString := vlsEmpresa.Value; DMPrincipal.FDVencimentosPedido.ParamByName('NUMERO').AsString := vlsPedido.Value; DMPrincipal.FDVencimentosPedido.Open(); vlJsonList := TJsonArray.Create; vlJsonObject := TJSONObject.Create; DMPrincipal.FDVencimentosPedido.First; DMPrincipal.FDVencimentosPedido.FetchAll; //for I := 0 to DMPrincipal.FDVencimentosPedido.RecordCount - 1 do while not DMPrincipal.FDVencimentosPedido.Eof do begin vlPropertyJson := TJSONObject.Create; vlPropertyJson.AddPair('DataVenc', DMPrincipal.FDVencimentosPedido.FieldByName('DataVenc').AsString); vlPropertyJson.AddPair('Docto', DMPrincipal.FDVencimentosPedido.FieldByName('Docto').AsString); vlPropertyJson.AddPair('Status', DMPrincipal.FDVencimentosPedido.FieldByName('Status').AsString); vlPropertyJson.AddPair('Cobranca', DMPrincipal.FDVencimentosPedido.FieldByName('Cobranca').AsString); vlJsonList.Add(vlPropertyJson); DMPrincipal.FDVencimentosPedido.Next; end; vlJsonObject.AddPair('Vencimentos', vlJsonList); //SSArquivoStream := TStringStream.Create(vlJsonObject.ToString); //SSArquivoStream.SaveToFile('C:\JSON.txt'); FDashBoard.pcdMensagemMemo('Requisição Entregue com o parâmetro: ' + vlJsonObject.ToString + ' da função fncRetornaVencimentoPedido'); Result := vlJsonObject; end; function Service.Ping: String; begin FDashBoard.pcdMensagemMemo('Teste de Conexão na função Ping'); Result := 'Ok'; end; function Service.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
unit App.Intf; interface uses DEX.Types; type IUI = interface procedure ShowMessage(const AMessage: string); procedure ShowException(const AMessage: string); procedure WaitLock; procedure WaitCancel; procedure WaitUnlock; end; IAppCore = interface procedure DoCloudLogin; procedure DoCloudRequestBalance(const Symbol: string); procedure DoCloudBalance(const Address: string; Amount: Extended; const Symbol: string); procedure DoCloudRequestTransfer(const Symbol,Address: string; Amount: Extended); procedure DoCloudRequestRatio; procedure DoCloudRatio(RatioBTC,RatioLTC,RatioETH: Extended); procedure DoForging(Owner,Buyer,Token: Int64; Amount,Commission1,Commission2: Extended); procedure DoCloudRequestForging(const TokenSymbol,CryptoSymbol: string; TokenAmount,CryptoAmount,CryptoRatio,Commission: Extended); procedure DoCloudForgingResult(const Tx: string); procedure DoCloudRequestCreateOffer(Direction: Integer; const Symbol1,Symbol2: string; Amount,Ratio: Extended; EndDate: TDateTime); procedure DoCloudCreateOffer(OfferID: Int64); procedure DoCloudRequestOffers(const Symbol1,Symbol2: string); procedure DoCloudOffers(const Offers: TOffers); procedure DoOfferTransfer(Direction: Integer; const Symbol1,Symbol2: string; OfferAccount: Int64; Amount,Ratio: Extended); procedure DoTransferToken2(const TokenSymbol,ToAccount: string; Amount: Extended); function GetSymbolBalance(const Symbol: string): Extended; procedure DoCloudRequestKillOffers(const Offers: TArray<Int64>); procedure DoCloudKillOffers(const Offers: TArray<Int64>); procedure DoCloudActiveOffers(const Offers: TOffers); procedure DoCloudClosedOffers(const Offers: TOffers); procedure DoCloudHistoryOffers(const Offers: TOffers); procedure DoCloudPairsSummary(const Pairs: TPairs); procedure DoCloudRequestCandles(const Symbol1,Symbol2: string; BeginDate: TDateTime; IntervalType: Integer); procedure DoCloudCandles(const Symbol1,Symbol2: string; IntervalCode: Integer; const Candles: TDataCandles); procedure DoCloudRequestSetNotifications(Enabled: Boolean); procedure DoCloudSetNotifications(Enabled: Boolean); procedure DoCloudNotifyEvent(const Symbol1,Symbol2: string; EventCode: Integer); procedure DoCloudRequestTradingHistory(const Symbol1,Symbol2: string; Count: Integer); procedure DoCloudTradingHistory(const Symbol1,Symbol2: string; const Trades: TDataTrades); end; var UI: IUI; AppCore: IAppCore; implementation end.
// Set component properties progress/status form // Original Quthor: Robert Wachtel (rwachtel@gmx.de) unit GX_SetComponentPropsStatus; interface uses Forms, StdCtrls, ExtCtrls, Classes, Controls, GX_BaseForm; type TfmSetComponentPropsStatus = class(TfmBaseForm) grpbxStatus: TGroupBox; pnlProcessedFile: TPanel; procedure FormClose(Sender: TObject; var Action: TCloseAction); private procedure SetProcessedFile(const Value: string); public class function GetInstance: TfmSetComponentPropsStatus; class procedure ReleaseMe; property ProcessedFile: string write SetProcessedFile; end; implementation {$R *.dfm} var myfmSetComponentPropsStatus: TfmSetComponentPropsStatus = nil; // Hide the form when closing it procedure TfmSetComponentPropsStatus.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; // Class function to get a form singleton class function TfmSetComponentPropsStatus.GetInstance: TfmSetComponentPropsStatus; begin if not Assigned(myfmSetComponentPropsStatus) then begin try myfmSetComponentPropsStatus := TfmSetComponentPropsStatus.Create(nil); except myfmSetComponentPropsStatus := nil; end; end; Result := myfmSetComponentPropsStatus; end; // Class function to release the form singleton class procedure TfmSetComponentPropsStatus.ReleaseMe; begin if Assigned(myfmSetComponentPropsStatus) then begin myfmSetComponentPropsStatus.Release; myfmSetComponentPropsStatus := nil; end; end; // Show the file being processed on the form procedure TfmSetComponentPropsStatus.SetProcessedFile(const Value: string); begin pnlProcessedFile.Caption := Value; Application.ProcessMessages; end; end.
unit uApuracao; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask, uGeraApuracao, uCRUDDespesas, uCRUDFaturamento, uCRUDConfiguracao, uImpressao, FireDAC.Comp.Client; type TFApuracao = class(TForm) pgcApuracao: TPageControl; ts_ApuracaoAnual: TTabSheet; ts_ApuracaoFechadas: TTabSheet; GroupBox1: TGroupBox; Label1: TLabel; edtAno: TMaskEdit; btnApuracao: TBitBtn; GroupBox2: TGroupBox; Label2: TLabel; btnImprimir: TBitBtn; cbAno: TComboBox; btnFechar2: TBitBtn; btnFechar: TBitBtn; procedure FormShow(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnApuracaoClick(Sender: TObject); procedure btnImprimirClick(Sender: TObject); procedure cbAnoExit(Sender: TObject); private vloGeraApuracao : TGeraApuracao; vloFaturamento : TCrudFaturamento; vloDespesas : TCrudDespesas; vloConfiguracoes : TCRUDConfiguracao; vloRelatorio : TImpressao; procedure HabilitaPaletas(vPaleta: TTabSheet); procedure pcdImpressaoApuracao(psAno: String); { Private declarations } public vPaleta: String; { Public declarations } end; var FApuracao: TFApuracao; implementation {$R *.dfm} uses uDMPrincipal, uPrincipal; procedure TFApuracao.btnApuracaoClick(Sender: TObject); var vlsAPUR_ANO, vlsMensagem : String; vldAPUR_RECEITABRUTA, vldAPUR_DESPESAS, vldAPUR_LUCROEVIDENCIADO, vldAPUR_PORCENTAGEMISENTA, vldAPUR_VALORISENTO, vldAPUR_VALORTRIBUTADO, vldAPUR_VALORDECLARARIR : Double; vlbAPUR_DECLARA : Boolean; begin vldAPUR_RECEITABRUTA := 0; vldAPUR_DESPESAS := 0; vldAPUR_LUCROEVIDENCIADO := 0; vldAPUR_PORCENTAGEMISENTA := 0; vldAPUR_VALORISENTO := 0; vldAPUR_VALORTRIBUTADO := 0; vldAPUR_VALORDECLARARIR := 0; vlsAPUR_ANO := ''; vlbAPUR_DECLARA := False; vlsMensagem := ''; if Trim(edtAno.Text) = '' then begin Fprincipal.pcdMensagem('Ano obrigatório'); edtAno.SetFocus; Abort; end else begin if not Fprincipal.fncValidaAno(edtAno.Text) then begin edtAno.SetFocus; Abort; end; end; if MessageDlg('Deseja gerar a apuração do ano ' + edtAno.Text + '?', mtInformation, [mbYes, mbNo], 0) = mrYes then begin vlsAPUR_ANO := edtAno.Text; vldAPUR_DESPESAS := vloDespesas.fncRetornaValorTotalANO(edtAno.Text); if vldAPUR_DESPESAS = 0 then vlsMensagem := '- Valor das despesas do ano: '+edtAno.Text+ ' não foram lançadas, acessar o menu: Lançamentos\Despesas e realizar os lançamentos.' + sLineBreak; vldAPUR_RECEITABRUTA := vloFaturamento.fncRetornaValorFaturadoANO(edtAno.Text); if vldAPUR_RECEITABRUTA = 0 then vlsMensagem := vlsMensagem + '- Valor das receitas do ano: '+edtAno.Text+ ' não foram lançadas, acessar o menu: Lançamentos\Faturamento e realizar os lançamentos.' + sLineBreak; vloConfiguracoes.pcdRetornaValorFaturadoANO(edtAno.Text); vldAPUR_PORCENTAGEMISENTA := vloConfiguracoes.poRetornoConfig.CONFIG_PORCENTAGEMISENTO; if vldAPUR_PORCENTAGEMISENTA = 0 then vlsMensagem := vlsMensagem + '- Valor da porcentagem de isenção do ano: '+edtAno.Text+ ' não foi lançada, acessar o menu: Configurações e realizar o lançamento.' + sLineBreak; vldAPUR_VALORDECLARARIR := vloConfiguracoes.poRetornoConfig.CONFIG_VALORDECLARARIR; if vldAPUR_VALORDECLARARIR = 0 then vlsMensagem := vlsMensagem + '- Valor limite para Imposto de Renda do ano: '+edtAno.Text+ ' não foi lançado, acessar o menu: Configurações e realizar o lançamento.'; if Trim(vlsMensagem) <> '' then begin Fprincipal.pcdMensagem('Existem inconsistências na apuração, corrija para continuar: ' + sLineBreak + vlsMensagem); edtAno.SetFocus; Abort; end; vldAPUR_LUCROEVIDENCIADO := (vldAPUR_RECEITABRUTA - vldAPUR_DESPESAS); vldAPUR_VALORISENTO := (vldAPUR_RECEITABRUTA * (vldAPUR_PORCENTAGEMISENTA / 100)); vldAPUR_VALORTRIBUTADO := (vldAPUR_LUCROEVIDENCIADO - vldAPUR_VALORISENTO); vlbAPUR_DECLARA := vldAPUR_VALORTRIBUTADO > vldAPUR_VALORDECLARARIR; vloGeraApuracao.APUR_RECEITABRUTA := vldAPUR_RECEITABRUTA; vloGeraApuracao.APUR_DESPESAS := vldAPUR_DESPESAS; vloGeraApuracao.APUR_LUCROEVIDENCIADO := vldAPUR_LUCROEVIDENCIADO; vloGeraApuracao.APUR_PORCENTAGEMISENTA := vldAPUR_PORCENTAGEMISENTA; vloGeraApuracao.APUR_VALORISENTO := vldAPUR_VALORISENTO; vloGeraApuracao.APUR_VALORTRIBUTADO := vldAPUR_VALORTRIBUTADO; vloGeraApuracao.APUR_VALORDECLARARIR := vldAPUR_VALORDECLARARIR; vloGeraApuracao.APUR_ANO := vlsAPUR_ANO; if vlbAPUR_DECLARA then vloGeraApuracao.APUR_DECLARA := 'True' else vloGeraApuracao.APUR_DECLARA := 'False'; vloGeraApuracao.pcdGravaApuracao; end; end; procedure TFApuracao.btnFecharClick(Sender: TObject); begin Close; end; procedure TFApuracao.btnImprimirClick(Sender: TObject); begin pcdImpressaoApuracao(cbAno.Text); end; procedure TFApuracao.cbAnoExit(Sender: TObject); begin if not Fprincipal.fncValidaAno(cbAno.Text) then begin cbAno.SetFocus; Abort; end; end; procedure TFApuracao.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(vloGeraApuracao) then FreeAndNil(vloGeraApuracao); if Assigned(vloDespesas) then FreeAndNil(vloDespesas); if Assigned(vloFaturamento) then FreeAndNil(vloFaturamento); if Assigned(vloConfiguracoes) then FreeAndNil(vloConfiguracoes); if Assigned(vloRelatorio) then FreeAndNil(vloRelatorio); end; procedure TFApuracao.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Perform(WM_NEXTDLGCTL, 0, 0); Key := #0; end; end; procedure TFApuracao.FormShow(Sender: TObject); var poQuery : TFDQuery; begin vloGeraApuracao := TGeraApuracao.Create(DMPrincipal.poConexao); vloDespesas := TCrudDespesas.Create(DMPrincipal.poConexao); vloFaturamento := TCRUDFaturamento.Create(DMPrincipal.poConexao); vloConfiguracoes := TCRUDConfiguracao.Create(DMPrincipal.poConexao); vloRelatorio := TImpressao.Create(DMPrincipal.poConexao); if Trim(vPaleta) = 'Apuração' then begin HabilitaPaletas(ts_ApuracaoAnual); if edtAno.CanFocus then edtAno.SetFocus; end else if Trim(vPaleta) = 'Fechadas' then begin HabilitaPaletas(ts_ApuracaoFechadas); poQuery := vloGeraApuracao.fncRetornaQtdeAnosApurados; poQuery.First; cbAno.Items.Clear; while not poQuery.Eof do begin cbAno.Items.Add(poQuery.FieldByName('APUR_ANO').AsString); poQuery.Next; end; if cbAno.CanFocus then cbAno.SetFocus; end; end; procedure TFApuracao.HabilitaPaletas(vPaleta: TTabSheet); begin ts_ApuracaoAnual.TabVisible := vPaleta = ts_ApuracaoAnual; ts_ApuracaoFechadas.TabVisible := vPaleta = ts_ApuracaoFechadas; end; procedure TFApuracao.pcdImpressaoApuracao(psAno: String); begin vloRelatorio.Imp_Ano := psAno; vloRelatorio.pcdImpressaoApuracao; end; end.
unit WpcScriptCommons; {$mode objfpc}{$H+} interface uses Classes, SysUtils, WpcExceptions; type TWpcStatemetId = ( WPC_WAIT_STATEMENT_ID, WPC_WALLPAPER_STATEMENT_ID, WPC_STOP_STATEMENT_ID, WPC_SWITCH_BRANCH_STATEMENT_ID, WPC_USE_BRANCH_STATEMENT_ID, WPC_WALLPAPER_CHOOSER_STATEMENT_ID, WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID, WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID, WPC_BRANCH_STATEMENT_ID, WPC_END_OF_BLOCK_STATEMENT, WPC_UNKNOWN_STATEMENT ); TWpcStatementPropertyId = ( WPC_DELAY_STATEMENT_PROPERY_ID, WPC_TIMES_STATEMENT_PROPERY_ID, WPC_PROBABILITY_STATEMENT_PROPERY_ID, WPC_WALLPAPER_STYLE_PROPERTY_ID, WPC_UNKNOWN_STATEMENT_PROPERTY ); function StatementIdToStr(StatementId : TWpcStatemetId) : String; function StatementPropertyIdToStr(StatementPropertyId : TWpcStatementPropertyId) : String; implementation function StatementIdToStr(StatementId: TWpcStatemetId): String; begin case (StatementId) of WPC_WAIT_STATEMENT_ID: Result := 'WAIT'; WPC_WALLPAPER_STATEMENT_ID: Result := 'SET WALLPAPER'; WPC_STOP_STATEMENT_ID: Result := 'STOP'; WPC_SWITCH_BRANCH_STATEMENT_ID: Result := 'SWITCH BRANCH'; WPC_USE_BRANCH_STATEMENT_ID: Result := 'USE BRANCH'; WPC_WALLPAPER_CHOOSER_STATEMENT_ID: Result := 'WALLPAPER CHOOSER'; WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID: Result := 'BRANCH TO USE CHOOSER'; WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID: Result := 'BRANCH TO SWITCH CHOOSER'; WPC_BRANCH_STATEMENT_ID: Result := 'BRANCH'; WPC_END_OF_BLOCK_STATEMENT: Result := 'END'; WPC_UNKNOWN_STATEMENT: Result := '_UNKNOWN_' else // Should never happen raise TWpcException.Create('Unknown statement id.'); end; end; function StatementPropertyIdToStr(StatementPropertyId: TWpcStatementPropertyId): String; begin case (StatementPropertyId) of WPC_DELAY_STATEMENT_PROPERY_ID: Result := 'DELAY PROPERTY'; WPC_TIMES_STATEMENT_PROPERY_ID: Result := 'TIMES PROPERTY'; WPC_PROBABILITY_STATEMENT_PROPERY_ID: Result := 'PROBABILITY PROPRTY'; WPC_WALLPAPER_STYLE_PROPERTY_ID: Result := 'STYLE PROPERTY'; WPC_UNKNOWN_STATEMENT_PROPERTY: Result := 'UNKNOWN PROPERTY'; else // Should never happen raise TWpcException.Create('Unknown statement id.'); end; end; end.
unit MyMsgForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { Tmy_msgform } Tmy_msgform = class(TForm) Image1: TImage; background: TImage; ImageList1: TImageList; Label1: TLabel; Timer1: TTimer; procedure backgroundClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure Timer1StopTimer(Sender: TObject); private { private declarations } public { public declarations } end; var my_msgform: Tmy_msgform; procedure showAlertForm (const ss:string; imgidx:integer; timeout:integer); implementation {$R *.lfm} { Tmy_msgform } {Процедура принимает текст уведомления, индекс картинки из ImageList и время на показ уведомления (в милисекундах)} procedure ShowAlertForm (const ss:string; imgidx:integer; timeout:integer); begin with my_msgform do begin ImageList1.GetBitmap(imgidx,Image1.Picture.Bitmap); Label1.Caption:=ss; Timer1.Interval:=timeout*1000; ShowModal; end; end; procedure Tmy_msgform.FormShow(Sender: TObject); begin timer1.Enabled:=true; end; procedure Tmy_msgform.Timer1StopTimer(Sender: TObject); begin Timer1.Enabled:=false; my_msgform.Close; end; end.
{******************************************************************************* 作者: dmzn@163.com 2020-08-14 描述: 系统业务处理 *******************************************************************************} unit USysBusiness; {$I Link.inc} interface uses Windows, DB, Classes, Controls, SysUtils, UDataModule, UDataReport, UFormBase, ULibFun, UFormCtrl, USysConst, USysDB, USysLoger; type TBookStatus = (bsNone, bsNew, bsEdit, bsDel); //图书状态 PBookItem = ^TBookItem; TBookItem = record FEnabled : Boolean; //记录有效 FRecord : string; //记录标识 FBookID : string; //档案标识 FBookName : string; //档案名称 FDetailID : string; //图书编号 FAuthor : string; //作者 FLang : string; //语种 FClass : string; //分类 FISBN : string; //isdn FName : string; //图书名称 FPublisher : string; //出版商 FProvider : string; //供应商 FPubPrice : Double; //定价 FGetPrice : Double; //采购价 FSalePrice : Double; //销售价 FNumAll : Integer; //库存 FNumIn : Integer; //在库 FNumOut : Integer; //借出 FNumSale : Integer; //销售 FNumNow : Integer; FNumAfter : Integer; FValid : Boolean; //允许借阅 FBookValid : Boolean; //允许借阅总开关 FStatus : TBookStatus;//编辑状态 FBorrowID : string; //借阅记录 FBorrowDate : TDateTime; //借阅时间 FBorrowNum : Integer; //借阅量 FReturnDate : TDateTime; //归还时间 FReturnNum : Integer; //归还量 FSaleID : string; //销售记录 FSaleNum : Integer; //销售量 FSaleReturn : Integer; //销售退回 FMemo : string; end; TBooks = array of TBookItem; PMemberItem = ^TMemberItem; TMemberItem = record FRecord : string; //记录标识 FMID : string; //会员编号 FName : string; //会员名称 FSex : string; //性别 FCard : string; //会员卡号 FPhone : string; //手机号码 FLevel : string; //会员等级 FValidDate : TDateTime; //有效期 FBorrowNum : Integer; //借阅次数 FBorrowBooks : Integer; //借阅本数 FBuyNum : Integer; //购买次数 FBuyBooks : Integer; //购买本书 FMonCH : Integer; //每月可借: 中文 FMonEN : Integer; //每月可借: 英文 FMonth : string; //计数月份 FMonCHHas : Integer; //当月已借: 中文 FMonENHas : Integer; //当月已借: 英文 FPlayArea : Integer; //游玩区次数 FHasBorrow : Integer; //已借未归还本数 FNoReturnAllowed: Integer; //允许借出未还本数 end; TMembers = array of TMemberItem; TGoodsItem = record FEnabled : Boolean; //记录有效 FID : string; //商品编号 FName : string; //商品名称 FNum : Integer; //数量 FPrice : Double; //价格 FMoney : Double; //金额 end; TGoods = array of TGoodsItem; function GetCurrentMonth: string; {*当前月份*} function EncodePhone(const nPhone: string): string; {*手机号隐私处理*} function GetSerailID(var nID: string; const nGroup,nObject: string; const nUserDate: Boolean = True): Boolean; {*获取串号*} function LoadBaseDataList(const nList: TStrings; const nGroup: string; const nDefault: PBaseDataItem = nil): Boolean; function LoadBaseDataItem(const nGroup,nItem: string; var nValue: TBaseDataItem): Boolean; function LoadBaseDataDefault(const nGroup: string; var nValue: TBaseDataItem): Boolean; procedure SaveBaseDataItem(const nValue: PBaseDataItem; const nOverride: Boolean = False); procedure SaveBaseDataItemNoExists(const nGroup,nText: string); {*基础档案业务*} procedure SyncBookNumber(const nBookID: string); {*同步图书库存量*} function LoadBooks(const nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string = ''): Boolean; function LoadBooksBorrow(const nMID,nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string = ''): Boolean; function LoadBooksSale(const nMID,nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string = ''): Boolean; {*加载图书列表*} function LoadMembers(const nMID: string; var nMembers: TMembers; var nHint: string; nWhere: string = ''): Boolean; {*加载会员列表*} function GetMemberHasBorrow(const nMID: string): Integer; {*会员未归还本数*} implementation //Desc: 记录日志 procedure WriteLog(const nEvent: string); begin gSysLoger.AddLog(nEvent); end; //Date: 2020-08-24 //Desc: 当前月份字符串 function GetCurrentMonth: string; begin Result := Copy(DateTime2Str(Now), 1, 7); end; function EncodePhone(const nPhone: string): string; var nEnd: string; nLen: Integer; begin Result := nPhone; nLen := Length(Result); if nLen <= 4 then Exit; nEnd := Copy(Result, nLen - 3, 4); Result := Copy(Result, 1, nLen - 4); nLen := Length(Result); if nLen > 3 then Result := Copy(Result, 1, nLen - 3) + 'xxx'; Result := Result + nEnd; end; //Date: 2020-08-14 //Parm: 分组;对象; //Desc: 按规则生成序列编号 function GetSerailID(var nID: string; const nGroup,nObject: string; const nUserDate: Boolean): Boolean; var nInt: Integer; nInTrans: Boolean; nStr,nP,nB: string; begin nInTrans := FDM.ADOConn.InTransaction; if not nInTrans then FDM.ADOConn.BeginTrans; try Result := False; nStr := 'Update %s Set B_Base=B_Base+1 ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sTable_SerialBase, nGroup, nObject]); FDM.ExecuteSQL(nStr); nStr := 'Select B_Prefix,B_IDLen,B_Base,B_Date,%s as B_Now From %s ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sField_SQLServer_Now, sTable_SerialBase, nGroup, nObject]); //xxxxx with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin nID := '没有[ %s.%s ]的编码配置.'; nID := Format(nID, [nGroup, nObject]); FDM.ADOConn.RollbackTrans; Exit; end; nP := FieldByName('B_Prefix').AsString; nB := FieldByName('B_Base').AsString; nInt := FieldByName('B_IDLen').AsInteger; if nUserDate then //按日期编码 begin nStr := Date2Str(FieldByName('B_Date').AsDateTime, False); //old date if (nStr <> Date2Str(FieldByName('B_Now').AsDateTime, False)) and (FieldByName('B_Now').AsDateTime > FieldByName('B_Date').AsDateTime) then begin nStr := 'Update %s Set B_Base=1,B_Date=%s ' + 'Where B_Group=''%s'' And B_Object=''%s'''; nStr := Format(nStr, [sTable_SerialBase, sField_SQLServer_Now, nGroup, nObject]); FDM.ExecuteSQL(nStr); nB := '1'; nStr := Date2Str(FieldByName('B_Now').AsDateTime, False); //now date end; System.Delete(nStr, 1, 2); //yymmdd nInt := nInt - Length(nP) - Length(nStr) - Length(nB); nID := nP + nStr + StringOfChar('0', nInt) + nB; end else begin nInt := nInt - Length(nP) - Length(nB); nStr := StringOfChar('0', nInt); nID := nP + nStr + nB; end; end; if not nInTrans then FDM.ADOConn.CommitTrans; Result := True; except if not nInTrans then FDM.ADOConn.RollbackTrans; raise; end; end; //Date: 2020-08-27 //Parm: 数据集;值 //Desc: 将nDS的当前记录填充到nVal中 procedure LoadBaseDataFormDataset(const nDS: TDataSet; const nVal: PBaseDataItem); begin with nDS, nVal^ do begin FRecord := FieldByName('B_ID').AsString; FGroup := FieldByName('B_Group').AsString; FGroupName := FieldByName('B_GroupName').AsString; FName := FieldByName('B_Text').AsString; FParamA := FieldByName('B_ParamA').AsString; FParamB := FieldByName('B_ParamB').AsString; FMemo := FieldByName('B_Memo').AsString; FDefault := FieldByName('B_Default').AsString = sFlag_Yes; end; end; //Date: 2020-08-17 //Parm: 列表;档案分组;默认值 //Desc: 读取nGroup的档案清单,存入nList function LoadBaseDataList(const nList: TStrings; const nGroup: string; const nDefault: PBaseDataItem): Boolean; var nStr: string; begin nStr := 'Select * From %s Where B_Group=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, nGroup]); with FDM.QueryTemp(nStr) do begin Result := RecordCount > 0; if not Result then Exit; First; while not Eof do begin nStr := FieldByName('B_Text').AsString; nList.Add(nStr); if Assigned(nDefault) and (FieldByName('B_Default').AsString = sFlag_Yes) then LoadBaseDataFormDataset(FDM.SQLTemp, nDefault); //xxxxx Next; end; end; end; //Date: 2020-08-22 //Parm: 档案分组;档案项;取值 //Desc: 读取nGroup.nItem的内容 function LoadBaseDataItem(const nGroup,nItem: string; var nValue: TBaseDataItem): Boolean; var nStr: string; begin nStr := 'Select * From %s Where B_Group=''%s'' And B_Text=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, nGroup, nItem]); with FDM.QueryTemp(nStr) do begin Result := RecordCount > 0; if Result then LoadBaseDataFormDataset(FDM.SqlTemp, @nValue); //xxxxx end; end; //Date: 2020-08-27 //Parm: 档案分组 //Desc: 读取nGroup的默认项 function LoadBaseDataDefault(const nGroup: string; var nValue: TBaseDataItem): Boolean; var nStr: string; begin nStr := 'Select * From %s Where B_Group=''%s'' And B_Default=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, nGroup, sFlag_Yes]); with FDM.QueryTemp(nStr) do begin Result := RecordCount > 0; if Result then LoadBaseDataFormDataset(FDM.SqlTemp, @nValue); //xxxxx end; end; //Date: 2020-08-23 //Parm: 档案值;是否覆盖 //Desc: 保存nGroup.nItem的值nValue procedure SaveBaseDataItem(const nValue: PBaseDataItem; const nOverride: Boolean); var nStr: string; nIdx: Integer; nVal: TBaseDataItem; nLocalTrans: Boolean; begin if (nValue.FGroup = '') or (nValue.FName = '') then Exit; //invalid data if (nValue.FRecord = '') and LoadBaseDataItem(nValue.FGroup, nValue.FName, nVal) then begin nValue.FRecord := nVal.FRecord; if nValue.FGroupName = '' then nValue.FGroupName := nVal.FGroupName; //xxxxx end; if (nValue.FRecord <> '') and (not nOverride) then Exit; //has exists if nValue.FGroupName = '' then begin for nIdx:=Low(cBaseData) to High(cBaseData) do if CompareText(cBaseData[nIdx].FName, nValue.FGroup) = 0 then begin nValue.FGroupName := cBaseData[nIdx].FDesc; Break; end; end; nLocalTrans := not FDM.ADOConn.InTransaction; if nLocalTrans then FDM.ADOConn.BeginTrans; try nStr := MakeSQLByStr([ SF('B_Group', nValue.FGroup), SF('B_GroupName', nValue.FGroupName), SF('B_Text', nValue.FName), SF('B_Py', GetPinYinOfStr(nValue.FName)), SF('B_ParamA', nValue.FParamA), SF('B_ParamB', nValue.FParamB), SF_IF([SF('B_Default', sFlag_Yes), SF('B_Default', '')], nValue.FDefault), SF('B_Memo', nValue.FMemo) ], sTable_BaseInfo, SF('B_ID', nValue.FRecord), nValue.FRecord = ''); FDM.ExecuteSQL(nStr); if nValue.FDefault then begin nStr := 'Update %s Set B_Default=''%s'' ' + 'Where B_Group=''%s'' And B_Text<>''%s'''; nStr := Format(nStr, [sTable_BaseInfo, '', nValue.FGroup, nValue.FName]); FDM.ExecuteSQL(nStr); //关闭其它默认项 end; if nLocalTrans then FDM.ADOConn.CommitTrans; //xxxxx except if nLocalTrans then FDM.ADOConn.RollbackTrans; raise; end; end; //Date: 2020-08-24 //Parm: 分组标识;内容 //Desc: 如果不存在,则保存基础档案nGroup.nText procedure SaveBaseDataItemNoExists(const nGroup,nText: string); var nVal: TBaseDataItem; begin FillChar(nVal, SizeOf(nVal), #0); with nVal do begin FGroup := nGroup; FName := nText; FDefault := False; end; SaveBaseDataItem(@nVal, False); end; //Date: 2020-08-19 //Parm: 图书档案标识 //Desc: 更新nBookID的当前库存 procedure SyncBookNumber(const nBookID: string); var nStr: string; begin nStr := 'Update %s Set B_NumAll=NumAll,B_NumIn=NumIn,B_NumOut=NumOut,' + 'B_NumSale=NumSale From (' + ' Select D_Book,Sum(D_NumAll) as NumAll,Sum(D_NumIn) as NumIn,' + ' Sum(D_NumOut) as NumOut,Sum(D_NumSale) as NumSale From %s ' + ' Where D_Book=''%s'' Group By D_Book' + ') t Where B_ID=D_Book'; nStr := Format(nStr, [sTable_Books, sTable_BookDetail, nBookID]); FDM.ExecuteSQL(nStr); end; //Date: 2020-08-24 //Parm: isdn;图书清单;提示信息 //Desc: 读取isdn的书单,存入nBooks function LoadBooks(const nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string): Boolean; var nStr: string; nIdx: Integer; nDef: TBookItem; begin Result := False; SetLength(nBooks, 0); //init default if nWhere = '' then nWhere := Format('D_ISBN=''%s''', [nISDN]); //default nStr := 'Select dt.*,B_Name,B_Author,B_Lang,B_Class,B_Valid From %s dt ' + ' Left Join %s On B_ID=D_Book ' + 'Where %s'; nStr := Format(nStr, [sTable_BookDetail, sTable_Books, nWhere]); with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin nHint := '该条码没有图书档案'; Exit; end; FillChar(nDef, SizeOf(TBooks), #0); SetLength(nBooks, RecordCount); nIdx := 0; First; while not Eof do begin nBooks[nIdx] := nDef; //default value with nBooks[nIdx] do begin FEnabled := True; FRecord := FieldByName('R_ID').AsString; FBookID := FieldByName('D_Book').AsString; FBookName := FieldByName('B_Name').AsString; FLang := FieldByName('B_Lang').AsString; FClass := FieldByName('B_Class').AsString; FDetailID := FieldByName('D_ID').AsString; FISBN := FieldByName('D_ISBN').AsString; FName := FieldByName('D_Name').AsString; FAuthor := FieldByName('D_Author').AsString; FPublisher := FieldByName('D_Publisher').AsString; FProvider := FieldByName('D_Provider').AsString; FPubPrice := FieldByName('D_PubPrice').AsFloat; FGetPrice := FieldByName('D_GetPrice').AsFloat; FSalePrice := FieldByName('D_SalePrice').AsFloat; FNumAll := FieldByName('D_NumAll').AsInteger; FNumIn := FieldByName('D_NumIn').AsInteger; FNumOut := FieldByName('D_NumOut').AsInteger; FNumSale := FieldByName('D_NumSale').AsInteger; FMemo := FieldByName('D_Memo').AsString; FValid := FieldByName('D_Valid').AsString = sFlag_Yes; FBookValid := FieldByName('B_Valid').AsString = sFlag_Yes; end; Inc(nIdx); Next; end; end; Result := True; end; //Date: 2020-08-28 //Parm: 会员编号;isdn;图书清单;提示细腻 //Desc: 加载nMID借阅的nISDN书单 function LoadBooksBorrow(const nMID,nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string): Boolean; var nStr: string; nIdx: Integer; nDef: TBookItem; begin Result := False; SetLength(nBooks, 0); //init default if nWhere = '' then begin nWhere := 'B_NumBorrow > B_NumReturn And B_Member=''%s'' And D_ISBN=''%s'''; nWhere := Format(nWhere, [nMID, nISDN]); end; nStr := 'Select br.*,dt.*,B_Name,B_Author,B_Lang,B_Class,B_Valid,' + 'br.R_ID as BorrowID,dt.R_ID as DetailID From %s br ' + ' Left Join %s bk on bk.B_ID=br.B_Book ' + ' Left Join %s dt on dt.D_ID=br.B_BookDtl ' + 'Where %s'; nStr := Format(nStr, [sTable_BookBorrow, sTable_Books, sTable_BookDetail, nWhere]); with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin nHint := '该条码没有需要归还的图书'; Exit; end; FillChar(nDef, SizeOf(TBooks), #0); SetLength(nBooks, RecordCount); nIdx := 0; First; while not Eof do begin nBooks[nIdx] := nDef; //default value with nBooks[nIdx] do begin FEnabled := True; FRecord := FieldByName('DetailID').AsString; FBookID := FieldByName('D_Book').AsString; FBookName := FieldByName('B_Name').AsString; FLang := FieldByName('B_Lang').AsString; FClass := FieldByName('B_Class').AsString; FDetailID := FieldByName('D_ID').AsString; FISBN := FieldByName('D_ISBN').AsString; FName := FieldByName('D_Name').AsString; FAuthor := FieldByName('D_Author').AsString; FPublisher := FieldByName('D_Publisher').AsString; FProvider := FieldByName('D_Provider').AsString; FPubPrice := FieldByName('D_PubPrice').AsFloat; FGetPrice := FieldByName('D_GetPrice').AsFloat; FSalePrice := FieldByName('D_SalePrice').AsFloat; FNumAll := FieldByName('D_NumAll').AsInteger; FNumIn := FieldByName('D_NumIn').AsInteger; FNumOut := FieldByName('D_NumOut').AsInteger; FNumSale := FieldByName('D_NumSale').AsInteger; FMemo := FieldByName('D_Memo').AsString; FValid := FieldByName('D_Valid').AsString = sFlag_Yes; FBookValid := FieldByName('B_Valid').AsString = sFlag_Yes; FBorrowID := FieldByName('BorrowID').AsString; FBorrowDate := FieldByName('B_DateBorrow').AsDateTime; FBorrowNum := FieldByName('B_NumBorrow').AsInteger; FReturnDate := FieldByName('B_DateReturn').AsDateTime; FReturnNum := FieldByName('B_NumReturn').AsInteger; end; Inc(nIdx); Next; end; end; Result := True; end; //Date: 2020-08-28 //Parm: 会员编号;isdn;图书清单;提示细腻 //Desc: 加载nMID借阅的nISDN书单 function LoadBooksSale(const nMID,nISDN: string; var nBooks: TBooks; var nHint: string; nWhere: string): Boolean; var nStr: string; nIdx: Integer; nDef: TBookItem; begin Result := False; SetLength(nBooks, 0); //init default if nWhere = '' then begin nWhere := 'S_Member=''%s'' And D_ISBN=''%s'' And ' + 'S_Type=''%s'' And S_Num > S_Return'; nWhere := Format(nWhere, [nMID, nISDN, sFlag_Out]); //售出可退回 end; nStr := 'Select bs.*,dt.*,B_Name,B_Author,B_Lang,B_Class,B_Valid,' + 'bs.R_ID as SaleID,dt.R_ID as DetailID From %s bs ' + ' Left Join %s bk on bk.B_ID=bs.S_Book ' + ' Left Join %s dt on dt.D_ID=bs.S_BookDtl ' + 'Where %s'; nStr := Format(nStr, [sTable_BookSale, sTable_Books, sTable_BookDetail, nWhere]); with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin nHint := '该条码没有可以退回的图书'; Exit; end; FillChar(nDef, SizeOf(TBooks), #0); SetLength(nBooks, RecordCount); nIdx := 0; First; while not Eof do begin nBooks[nIdx] := nDef; //default value with nBooks[nIdx] do begin FEnabled := True; FRecord := FieldByName('DetailID').AsString; FBookID := FieldByName('D_Book').AsString; FBookName := FieldByName('B_Name').AsString; FLang := FieldByName('B_Lang').AsString; FClass := FieldByName('B_Class').AsString; FDetailID := FieldByName('D_ID').AsString; FISBN := FieldByName('D_ISBN').AsString; FName := FieldByName('D_Name').AsString; FAuthor := FieldByName('D_Author').AsString; FPublisher := FieldByName('D_Publisher').AsString; FProvider := FieldByName('D_Provider').AsString; FPubPrice := FieldByName('D_PubPrice').AsFloat; FGetPrice := FieldByName('D_GetPrice').AsFloat; FSalePrice := FieldByName('D_SalePrice').AsFloat; FNumAll := FieldByName('D_NumAll').AsInteger; FNumIn := FieldByName('D_NumIn').AsInteger; FNumOut := FieldByName('D_NumOut').AsInteger; FNumSale := FieldByName('D_NumSale').AsInteger; FMemo := FieldByName('D_Memo').AsString; FValid := FieldByName('D_Valid').AsString = sFlag_Yes; FBookValid := FieldByName('B_Valid').AsString = sFlag_Yes; FSaleID := FieldByName('SaleID').AsString; FSaleNum := FieldByName('S_Num').AsInteger; FSaleReturn := FieldByName('S_Return').AsInteger; end; Inc(nIdx); Next; end; end; Result := True; end; //Date: 2020-08-26 //Parm: 会员编号;会员列表;提示信息 //Desc: 读取nMID会员的信息 function LoadMembers(const nMID: string; var nMembers: TMembers; var nHint: string; nWhere: string): Boolean; var nStr: string; nIdx: Integer; begin Result := False; SetLength(nMembers, 0); //init default if nWhere = '' then nWhere := Format('M_ID=''%s''', [nMID]); //default nStr := 'Select * From %s Where %s'; nStr := Format(nStr, [sTable_Members, nWhere]); with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin nHint := '会员档案已丢失'; Exit; end; SetLength(nMembers, RecordCount); nIdx := 0; First; while not Eof do begin with nMembers[nIdx] do begin FRecord := FieldByName('R_ID').AsString; FMID := FieldByName('M_ID').AsString; FName := FieldByName('M_Name').AsString; FSex := FieldByName('M_Sex').AsString; FCard := FieldByName('M_Card').AsString; FPhone := FieldByName('M_Phone').AsString; FLevel := FieldByName('M_Level').AsString; FValidDate := FieldByName('M_ValidDate').AsDateTime; FBorrowNum := FieldByName('M_BorrowNum').AsInteger; FBorrowBooks := FieldByName('M_BorrowBooks').AsInteger; FBuyNum := FieldByName('M_BuyNum').AsInteger; FBuyBooks := FieldByName('M_BuyBooks').AsInteger; FNoReturnAllowed := FieldByName('M_NoReturnAllowed').AsInteger; FMonCH := FieldByName('M_MonCH').AsInteger; FMonEN := FieldByName('M_MonEN').AsInteger; FMonth := FieldByName('M_Month').AsString; FMonCHHas := FieldByName('M_MonCHHas').AsInteger; FMonENHas := FieldByName('M_MonENHas').AsInteger; if FMonth <> GetCurrentMonth then //每月第一次清零计数 begin nStr := 'Update %s Set M_Month=''%s'',M_MonCHHas=0,M_MonENHas=0 ' + 'Where R_ID=%s'; nStr := Format(nStr, [sTable_Members, GetCurrentMonth, FRecord]); FDM.ExecuteSQL(nStr); FMonth := GetCurrentMonth; FMonCHHas := 0; FMonENHas := 0; end; FPlayArea := FieldByName('M_PlayArea').AsInteger; end; Inc(nIdx); Next; end; end; Result := True; end; //Date: 2021-07-08 //Parm: 会员编号 //Desc: 获取nMID未归还的本数 function GetMemberHasBorrow(const nMID: string): Integer; var nStr: string; begin Result := 0; nStr := 'Select Sum(B_NumBorrow-B_NumReturn) From %s Where B_Member=''%s'''; nStr := Format(nStr, [sTable_BookBorrow, nMID]); with FDM.QueryTemp(nStr) do begin if RecordCount > 0 then Result := Fields[0].AsInteger; //xxxxx end; end; end.
{ //************************************************************// } { // // } { // Código gerado pelo assistente // } { // // } { // Projeto MVCBr // } { // tireideletra.com.br / amarildo lacerda // } { //************************************************************// } { // Data: 10/03/2017 21:21:54 // } { //************************************************************// } Unit RestODataApp.ViewModel; interface { .$I ..\inc\mvcbr.inc } uses MVCBr.Interf, MVCBr.ViewModel, RestODataApp.ViewModel.Interf; Type /// Object Factory para o ViewModel TRestODataAppViewModel = class(TViewModelFactory, IRestODataAppViewModel, IViewModelAs<IRestODataAppViewModel>) public function ViewModelAs: IRestODataAppViewModel; class function new(): IRestODataAppViewModel; overload; class function new(const AController: IController) : IRestODataAppViewModel; overload; procedure AfterInit; override; end; implementation function TRestODataAppViewModel.ViewModelAs: IRestODataAppViewModel; begin result := self; end; class function TRestODataAppViewModel.new(): IRestODataAppViewModel; begin result := new(nil); end; /// <summary> /// New cria uma nova instância para o ViewModel /// </summary> /// <param name="AController"> /// AController é o controller ao qual o ViewModel esta /// ligado /// </param> class function TRestODataAppViewModel.new(const AController: IController) : IRestODataAppViewModel; begin result := TRestODataAppViewModel.create; result.controller(AController); end; procedure TRestODataAppViewModel.AfterInit; begin // evento disparado apos a definicao do Controller; end; end.
unit MainForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.DBGrids, Vcl.ExtCtrls, uCliente, Vcl.StdCtrls, System.Generics.Collections, uPessoa, uJSONPessoa, MidasLib, Data.DB, Datasnap.DBClient; type TfrmMain = class(TForm) pnlBotoes: TPanel; dbgrdPessoa: TDBGrid; btnIncluir: TButton; btnAlterar: TButton; btnExcluir: TButton; btnListar: TButton; dsPessoa: TDataSource; cdsPessoa: TClientDataSet; cdsPessoaid: TIntegerField; cdsPessoanome: TStringField; cdsPessoaprofissao: TStringField; cdsPessoanaturalidade: TStringField; procedure btnListarClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnExcluirClick(Sender: TObject); procedure btnAlterarClick(Sender: TObject); procedure btnIncluirClick(Sender: TObject); private JSONPessoa: TJSONPessoa; Cliente: TCliente<TPessoa>; procedure CarregaCDS(APessoas: TPessoas); procedure Listar; function RegistroSelecionado: Boolean; function GetPessoaSelecionada: TPessoa; property PessoaSelecionada: TPessoa read GetPessoaSelecionada; public { Public declarations } end; var frmMain: TfrmMain; implementation {$R *.dfm} uses uConfig, uProtocolo, uMessageBox, uMJD.Messages, CadastroPessoaForm; procedure TfrmMain.btnAlterarClick(Sender: TObject); begin if (RegistroSelecionado()) then begin Application.CreateForm(TfrmCadastroPessoaForm, frmCadastroPessoaForm); frmCadastroPessoaForm.CarregaDados(PessoaSelecionada); if frmCadastroPessoaForm.ShowModal() = mrOk then Listar(); end; end; procedure TfrmMain.btnExcluirClick(Sender: TObject); Var Resposta: TProtocoloResposta; begin if (RegistroSelecionado() AND MessageBox.MessageYesNo(rsConfirmaExclusao)) then begin try Resposta := Cliente.ExecuteExcluir(JSONPessoa.ObjectToJson(PessoaSelecionada)); if (Resposta.Status = spOk) then Listar() else MessageBox.MessageError(Resposta.Mensagem, TStatusProtocoloString[Resposta.Status]); except on E: Exception do MessageBox.MessageError(E.Message); end; end; end; procedure TfrmMain.btnIncluirClick(Sender: TObject); begin Application.CreateForm(TfrmCadastroPessoaForm, frmCadastroPessoaForm); if frmCadastroPessoaForm.ShowModal() = mrOk then Listar(); end; procedure TfrmMain.btnListarClick(Sender: TObject); begin Listar(); end; procedure TfrmMain.CarregaCDS(APessoas: TPessoas); var Pessoa: TPessoa; begin cdsPessoa.EmptyDataSet(); for Pessoa in APessoas do begin cdsPessoa.Append(); cdsPessoaid.AsInteger := Pessoa.Id; cdsPessoanome.AsString := Pessoa.Nome; cdsPessoaprofissao.AsString := Pessoa.Profissao; cdsPessoanaturalidade.AsString := Pessoa.Naturalidade; cdsPessoa.Post(); end; end; procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Cliente.Free(); JSONPessoa.Free; Action := caFree; end; procedure TfrmMain.FormCreate(Sender: TObject); begin Cliente := TCliente<TPessoa>.Create(Config.Host, Config.Porta); JSONPessoa := TJSONPessoa.Create; Listar(); end; function TfrmMain.GetPessoaSelecionada: TPessoa; begin Result := TPessoa.Create(); Result.Id := cdsPessoaid.AsInteger; Result.Nome := cdsPessoanome.AsString; Result.Profissao := cdsPessoaprofissao.AsString; Result.Naturalidade := cdsPessoanaturalidade.AsString; end; procedure TfrmMain.Listar; Var Resposta: TProtocoloResposta; begin try Resposta := Cliente.ExecuteListar(''); if (Resposta.Status = spOk) then CarregaCDS(JSONPessoa.JsonToObjectList(Resposta.Mensagem).Pessoas) else MessageBox.MessageError(Resposta.Mensagem, TStatusProtocoloString[Resposta.Status]); except on E: Exception do MessageBox.MessageError(E.Message); end; end; function TfrmMain.RegistroSelecionado: Boolean; begin Result := not cdsPessoa.IsEmpty; if not Result then MessageBox.MessageOk(rsSelecioneRegistro); end; end.
unit Sample.App; {$INCLUDE 'Sample.inc'} interface uses System.Classes, System.UITypes; type { Abstract base class for sample applications. Note that the sample applications do NOT use the VCL or FireMonkey frameworks. So you can also use these samples to learn how to make a cross-platform without FireMonkey. See the Sample.Platform.* units for details. } TApplication = class abstract {$REGION 'Internal Declarations'} private FWidth: Integer; FHeight: Integer; FTitle: String; {$ENDREGION 'Internal Declarations'} public { Creates the sample application. Parameters: AWidth: width of the client area of the window. AHeight: height of the client area of the window. ATitle: title of the application. These parameters are ignored on mobile platforms (which is always full screen) } constructor Create(const AWidth, AHeight: Integer; const ATitle: String); virtual; { Must be overridden to initialize the application. For example, you can load resources such as buffers, textures, shaders etc. here } procedure Initialize; virtual; abstract; { Is called once every frame to render the frame. Parameters: ADeltaTimeSec: time since last Render call in seconds. ATotalTimeSec: time since the app started, in seconds Must be overridden. } procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); virtual; abstract; { Must be overridden to clean up the app. Is called when the application terminates. Any resources created in the Initialize method should be released here. } procedure Shutdown; virtual; abstract; { Is called when a mouse button is pressed (or screen touch is started). Parameters: AButton: the mouse button that is pressed (touch events are translated to the mbLeft button). AShift: shift state (whether Shift and/or Control are down) AX: X-position AY: Y-position This method does nothing by default but can be overridden to handle a mouse press or touch event. } procedure MouseDown(const AButton: TMouseButton; const AShift: TShiftState; const AX, AY: Single); virtual; { Is called when the mouse is moved (or the finger on the touch screen is moved). Parameters: AShift: shift state (whether Shift and/or Control are down) AX: X-position AY: Y-position This method does nothing by default but can be overridden to handle a mouse move or touch event. } procedure MouseMove(const AShift: TShiftState; const AX, AY: Single); virtual; { Is called when a mouse button is released (or screen touch is ended). Parameters: AButton: the mouse button that is released (touch events are translated to the mbLeft button). AShift: shift state (whether Shift and/or Control are down) AX: X-position AY: Y-position This method does nothing by default but can be overridden to handle a mouse release or touch event. } procedure MouseUp(const AButton: TMouseButton; const AShift: TShiftState; const AX, AY: Single); virtual; { Is called when the mouse wheel is moved. Parameters: AShift: shift state (whether Shift and/or Control are down) AWheelDelta: number of notches the wheel is moved. This method does nothing by default but can be overridden to handle a mouse wheel event. } procedure MouseWheel(const AShift: TShiftState; const AWheelDelta: Integer); virtual; { Is called when a key is depressed. Parameters: AKey: virtual key code (one of the vk* constants in the System.UITypes unit) AShift: shift state (whether Shift, Control and or Alt are down) This method does nothing by default but can be overridden to handle a key press. } procedure KeyDown(const AKey: Integer; const AShift: TShiftState); virtual; { Is called when a key is released. Parameters: AKey: virtual key code (one of the vk* constants in the System.UITypes unit) AShift: shift state (whether Shift, Control and or Alt are down) This method does nothing by default but can be overridden to handle a key release. } procedure KeyUp(const AKey: Integer; const AShift: TShiftState); virtual; { Is called when the framebuffer has resized. For example, when the user rotates a mobile device. Parameters: AWidth: new width of the framebuffer AHeight: new height of the framebuffer. } procedure Resize(const AWidth, AHeight: Integer); virtual; { If the application needs a stencil buffer, then you must override this method and return True. Returns False by default. } function NeedStencilBuffer: Boolean; virtual; { Call this method to manually terminate the app. } procedure Terminate; { Framebuffer width } property Width: Integer read FWidth; { Framebuffer height } property Height: Integer read FHeight; { Application title } property Title: String read FTitle; end; TApplicationClass = class of TApplication; { Main entry point of the application. Call this procedure to run the app. Parameters: AAppClass: class of the application to run. This should the class you derived from TApplication. AWidth: width of the client area of the window. AHeight: height of the client area of the window. ATitle: title of the application. } procedure RunApp(const AAppClass: TApplicationClass; const AWidth, AHeight: Integer; const ATitle: String); implementation uses System.SysUtils, Sample.Platform; procedure RunApp(const AAppClass: TApplicationClass; const AWidth, AHeight: Integer; const ATitle: String); var App: TApplication; begin ReportMemoryLeaksOnShutdown := True; try App := AAppClass.Create(AWidth, AHeight, ATitle); try TPlatform.Run(App); finally App.Free; end; except on E: Exception do ShowException(E, ExceptAddr); end; end; { TApplication } constructor TApplication.Create(const AWidth, AHeight: Integer; const ATitle: String); begin inherited Create; FWidth := AWidth; FHeight := AHeight; FTitle := ATitle; end; procedure TApplication.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { No default implementation } end; procedure TApplication.KeyUp(const AKey: Integer; const AShift: TShiftState); begin { No default implementation } end; procedure TApplication.MouseDown(const AButton: TMouseButton; const AShift: TShiftState; const AX, AY: Single); begin { No default implementation } end; procedure TApplication.MouseMove(const AShift: TShiftState; const AX, AY: Single); begin { No default implementation } end; procedure TApplication.MouseUp(const AButton: TMouseButton; const AShift: TShiftState; const AX, AY: Single); begin { No default implementation } end; procedure TApplication.MouseWheel(const AShift: TShiftState; const AWheelDelta: Integer); begin { No default implementation } end; function TApplication.NeedStencilBuffer: Boolean; begin Result := False; end; procedure TApplication.Resize(const AWidth, AHeight: Integer); begin FWidth := AWidth; FHeight := AHeight; end; procedure TApplication.Terminate; begin TPlatform.Terminate; end; end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike P�rez Unit : Quick.Commons Description : Common functions Author : Kike P�rez Version : 2.0 Created : 14/07/2017 Modified : 19/01/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Commons; {$i QuickLib.inc} interface uses Classes, SysUtils, Types, {$IFDEF MSWINDOWS} Windows, ActiveX, ShlObj, {$ENDIF MSWINDOWS} {$IFDEF FPC} Quick.Files, {$IFDEF LINUX} FileInfo, {$ENDIF} {$ELSE} IOUtils, {$ENDIF} {$IFDEF ANDROID} Androidapi.JNI.Os, Androidapi.Helpers, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText, {$IFDEF DELPHIRX103_UP} Androidapi.JNI.App, {$ENDIF} {$ENDIF} {$IFDEF IOS} iOSapi.UIKit, Posix.SysSysctl, Posix.StdDef, iOSapi.Foundation, Macapi.ObjectiveC, Macapi.Helpers, {$ENDIF} {$IFDEF OSX} Macapi.Foundation, Macapi.Helpers, FMX.Helpers.Mac, Macapi.ObjectiveC, {$ENDIF} {$IFDEF POSIX} Posix.Unistd, {$ENDIF} DateUtils; type TLogEventType = (etInfo, etSuccess, etWarning, etError, etDebug, etDone, etTrace, etCritical, etException); TLogVerbose = set of TLogEventType; const LOG_ONLYERRORS = [etInfo,etError]; LOG_ERRORSANDWARNINGS = [etInfo,etWarning,etError]; LOG_TRACE = [etInfo,etError,etWarning,etTrace]; LOG_ALL = [etInfo, etSuccess, etWarning, etError, etDebug, etDone, etTrace, etCritical, etException]; LOG_DEBUG = [etInfo,etSuccess,etWarning,etError,etDebug]; {$IFDEF DELPHIXE7_UP} EventStr : array of string = ['INFO','SUCC','WARN','ERROR','DEBUG','DONE','TRACE','CRITICAL','EXCEPTION']; {$ELSE} EventStr : array[0..8] of string = ('INFO','SUCC','WARN','ERROR','DEBUG','DONE','TRACE','CRITICAL','EXCEPTION'); {$ENDIF} CRLF = #13#10; type TPasswordComplexity = set of (pfIncludeNumbers,pfIncludeSigns); TEnvironmentPath = record EXEPATH : string; {$IFDEF MSWINDOWS} WINDOWS : string; SYSTEM : string; PROGRAMFILES : string; COMMONFILES : string; HOMEDRIVE : string; TEMP : string; USERPROFILE : string; INSTDRIVE : string; DESKTOP : string; STARTMENU : string; DESKTOP_ALLUSERS : string; STARTMENU_ALLUSERS : string; STARTUP : string; APPDATA : String; PROGRAMDATA : string; ALLUSERSPROFILE : string; {$ENDIF MSWINDOWS} end; {$IFNDEF FPC} TFileHelper = record helper for TFile {$IF DEFINED(MSWINDOWS) OR DEFINED(DELPHILINUX)} class function IsInUse(const FileName : string) : Boolean; static; {$ENDIF} class function GetSize(const FileName: String): Int64; static; end; TDirectoryHelper = record helper for TDirectory class function GetSize(const Path: String): Int64; static; end; {$ENDIF} {$IFDEF FPC} {$IFDEF LINUX} UINT = cardinal; {$ENDIF} PLASTINPUTINFO = ^LASTINPUTINFO; tagLASTINPUTINFO = record cbSize: UINT; dwTime: DWORD; end; LASTINPUTINFO = tagLASTINPUTINFO; TLastInputInfo = LASTINPUTINFO; type TCmdLineSwitchType = (clstValueNextParam, clstValueAppended); TCmdLineSwitchTypes = set of TCmdLineSwitchType; {$ENDIF} TCounter = record private fMaxValue : Integer; fCurrentValue : Integer; public property MaxValue : Integer read fMaxValue; procedure Init(aMaxValue : Integer); function Count : Integer; function CountIs(aValue : Integer) : Boolean; function Check : Boolean; procedure Reset; end; TTimeCounter = record private fCurrentTime : TDateTime; fDoneEvery : Integer; public property DoneEvery : Integer read fDoneEvery; procedure Init(MillisecondsToReach : Integer); function Check : Boolean; procedure Reset; end; {$IFNDEF FPC} {$IFNDEF DELPHIXE7_UP} TArrayUtil<T> = class class procedure Delete(var aArray : TArray<T>; aIndex : Integer); end; {$ENDIF} TArrayOfStringHelper = record helper for TArray<string> public function Any : Boolean; overload; function Any(const aValue : string) : Boolean; overload; function Add(const aValue : string) : Integer; function AddIfNotExists(const aValue : string; aCaseSense : Boolean = False) : Integer; function Remove(const aValue : string) : Boolean; function Exists(const aValue : string) : Boolean; function Count : Integer; end; TDelegate<T> = reference to procedure(Value : T); {$ENDIF} TPairItem = record Name : string; Value : string; constructor Create(const aName, aValue : string); end; TPairList = class type TPairEnumerator = class private fArray : ^TArray<TPairItem>; fIndex : Integer; function GetCurrent: TPairItem; public constructor Create(var aArray: TArray<TPairItem>); property Current : TPairItem read GetCurrent; function MoveNext: Boolean; end; private fItems : TArray<TPairItem>; public function GetEnumerator : TPairEnumerator; function GetValue(const aName : string) : string; function GetPair(const aName : string) : TPairItem; function Add(aPair : TPairItem) : Integer; overload; function Add(const aName, aValue : string) : Integer; overload; procedure AddOrUpdate(const aName, aValue : string); function Exists(const aName : string) : Boolean; function Remove(const aName : string) : Boolean; function Count : Integer; property Items[const aName : string] : string read GetValue write AddOrUpdate; function ToArray : TArray<TPairItem>; procedure FromArray(aValue : TArray<TPairItem>); procedure Clear; end; {$IFDEF DELPHIXE7_UP} TDateTimeHelper = record helper for TDateTime public function ToSQLString : string; procedure FromNow; procedure FromUTC(const aUTCTime : TDateTime); function IncDay(const aValue : Cardinal = 1) : TDateTime; function DecDay(const aValue : Cardinal = 1) : TDateTime; function IncMonth(const aValue : Cardinal = 1) : TDateTime; function DecMonth(const aValue : Cardinal = 1) : TDateTime; function IncYear(const aValue : Cardinal = 1) : TDateTime; function DecYear(const aValue : Cardinal = 1) : TDateTime; function IsEqualTo(const aDateTime : TDateTime) : Boolean; function IsAfter(const aDateTime : TDateTime) : Boolean; function IsBefore(const aDateTime : TDateTime) : Boolean; function IsSameDay(const aDateTime : TDateTime) : Boolean; function IsSameTime(const aTime : TTime) : Boolean; function DayOfTheWeek : Word; function ToJsonFormat : string; function ToGMTFormat: string; function ToTimeStamp : TTimeStamp; function ToUTC : TDateTime; function ToMilliseconds : Int64; function ToString : string; function Date : TDate; function Time : TTime; function IsAM : Boolean; function IsPM : Boolean; end; TDateHelper = record helper for TDate public function ToString : string; end; TTimeHelper = record helper for TTime public function ToString : string; end; {$ENDIF} EEnvironmentPath = class(Exception); EShellError = class(Exception); //generates a random password with complexity options function RandomPassword(const PasswordLength : Integer; Complexity : TPasswordComplexity = [pfIncludeNumbers,pfIncludeSigns]) : string; //generates a random string function RandomString(const aLength: Integer) : string; //extracts file extension from a filename function ExtractFileNameWithoutExt(const FileName: string): string; //converts a Unix path to Windows path function UnixToWindowsPath(const UnixPath: string): string; //converts a Windows path to Unix path function WindowsToUnixPath(const WindowsPath: string): string; //corrects malformed urls function CorrectURLPath(const cUrl : string) : string; //get url parts function UrlGetProtocol(const aUrl : string) : string; function UrlGetHost(const aUrl : string) : string; function UrlGetPath(const aUrl : string) : string; function UrlGetQuery(const aUrl : string) : string; function UrlRemoveProtocol(const aUrl : string) : string; function UrlRemoveQuery(const aUrl : string) : string; function UrlSimpleEncode(const aUrl : string) : string; //get typical environment paths as temp, desktop, etc procedure GetEnvironmentPaths; {$IFDEF MSWINDOWS} function GetSpecialFolderPath(folderID : Integer) : string; //checks if running on a 64bit OS function Is64bitOS : Boolean; //checks if is a console app function IsConsole : Boolean; function HasConsoleOutput : Boolean; //checks if compiled in debug mode {$ENDIF} function IsDebug : Boolean; {$IFDEF MSWINDOWS} //checks if running as a service function IsService : Boolean; //gets number of seconds without user interaction (mouse, keyboard) function SecondsIdle: DWord; //frees process memory not needed procedure FreeUnusedMem; //changes screen resolution function SetScreenResolution(Width, Height: integer): Longint; {$ENDIF MSWINDOWS} //returns last day of current month function LastDayCurrentMonth: TDateTime; {$IFDEF FPC} function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime; aInclusive: Boolean = True): Boolean; {$ENDIF} //checks if two datetimes are in same day function IsSameDay(cBefore, cNow : TDateTime) : Boolean; //change Time of a DateTime function ChangeTimeOfADay(aDate : TDateTime; aHour, aMinute, aSecond : Word; aMilliSecond : Word = 0) : TDateTime; //change Date of a DateTime function ChangeDateOfADay(aDate : TDateTime; aYear, aMonth, aDay : Word) : TDateTime; //returns n times a char function FillStr(const C : Char; const Count : Integer) : string; function FillStrEx(const value : string; const Count : Integer) : string; //checks if string exists in array of string function StrInArray(const aValue : string; const aInArray : array of string; aCaseSensitive : Boolean = True) : Boolean; //checks if integer exists in array of integer function IntInArray(const aValue : Integer; const aInArray : array of Integer) : Boolean; //check if array is empty function IsEmptyArray(aArray : TArray<string>) : Boolean; overload; function IsEmptyArray(aArray : TArray<Integer>) : Boolean; overload; //returns a number leading zero function Zeroes(const Number, Len : Int64) : string; //converts a number to thousand delimeter string function NumberToStr(const Number : Int64) : string; //returns n spaces function Spaces(const Count : Integer) : string; //returns current date as a string function NowStr : string; //returns a new GUID as string function NewGuidStr : string; //compare a string with a wildcard pattern (? or *) function IsLike(cText, Pattern: string) : Boolean; //Upper case for first letter function Capitalize(s: string): string; function CapitalizeWords(s: string): string; //returns current logged user function GetLoggedUserName : string; //returns computer name function GetComputerName : string; //check if remote desktop session {$IFDEF MSWINDOWS} function IsRemoteSession : Boolean; {$ENDIF} //extract domain and user name from user login function ExtractDomainAndUser(const aUser : string; out oDomain, oUser : string) : Boolean; //Changes incorrect delims in path function NormalizePathDelim(const cPath : string; const Delim : Char) : string; //combine paths normalized with delim function CombinePaths(const aFirstPath, aSecondPath: string; aDelim : Char): string; //Removes firs segment of a path function RemoveFirstPathSegment(const cdir : string) : string; //Removes last segment of a path function RemoveLastPathSegment(const cDir : string) : string; //returns path delimiter if found function GetPathDelimiter(const aPath : string) : string; //returns first segment of a path function GetFirstPathSegment(const aPath : string) : string; //returns last segment of a path function GetLastPathSegment(const aPath : string) : string; //finds swith in commandline params function ParamFindSwitch(const Switch : string) : Boolean; //gets value for a switch if exists function ParamGetSwitch(const Switch : string; var cvalue : string) : Boolean; //returns app name (filename based) function GetAppName : string; //returns app version (major & minor) function GetAppVersionStr: string; //returns app version full (major, minor, release & compiled) function GetAppVersionFullStr: string; //convert UTC DateTime to Local DateTime function UTCToLocalTime(GMTTime: TDateTime): TDateTime; //convert Local DateTime to UTC DateTime function LocalTimeToUTC(LocalTime : TDateTime): TDateTime; //convert DateTime to GTM Time string function DateTimeToGMT(aDate : TDateTime) : string; //convert GMT Time string to DateTime function GMTToDateTime(aDate : string) : TDateTime; //convert DateTime to Json Date format function DateTimeToJsonDate(aDateTime : TDateTime) : string; //convert Json Date format to DateTime function JsonDateToDateTime(const aJsonDate : string) : TDateTime; //count number of digits of a Integer function CountDigits(anInt: Cardinal): Cardinal; inline; //count times a string is present in other string function CountStr(const aFindStr, aSourceStr : string) : Integer; //save stream to file procedure SaveStreamToFile(aStream : TStream; const aFilename : string); //save stream to string function StreamToString(const aStream: TStream; const aEncoding: TEncoding): string; function StreamToStringEx(aStream : TStream) : string; //save string to stream procedure StringToStream(const aStr : string; aStream : TStream; const aEncoding: TEncoding); procedure StringToStreamEx(const aStr : string; aStream : TStream); //returns a real comma separated text from stringlist function CommaText(aList : TStringList) : string; overload; //returns a real comma separated text from array of string function CommaText(aArray : TArray<string>) : string; overload; //returns a string CRLF separated from array of string function ArrayToString(aArray : TArray<string>) : string; overload; //returns a string with separator from array of string function ArrayToString(aArray : TArray<string>; aSeparator : string) : string; overload; //converts TStrings to array function StringsToArray(aStrings : TStrings) : TArray<string>; overload; //converts string comma or semicolon separated to array function StringsToArray(const aString : string) : TArray<string>; overload; {$IFDEF MSWINDOWS} //process messages on console applications procedure ProcessMessages; //get last error message function GetLastOSError : String; {$ENDIF} {$IF DEFINED(FPC) AND DEFINED(MSWINDOWS)} function GetLastInputInfo(var plii: TLastInputInfo): BOOL;stdcall; external 'user32' name 'GetLastInputInfo'; {$ENDIF} function RemoveLastChar(const aText : string) : string; function DateTimeToSQL(aDateTime : TDateTime) : string; function IsInteger(const aValue : string) : Boolean; function IsFloat(const aValue : string) : Boolean; function IsBoolean(const aValue : string) : Boolean; //extract a substring and deletes from source string function ExtractStr(var vSource : string; aIndex : Integer; aCount : Integer) : string; //get first string between string delimiters function GetSubString(const aSource, aFirstDelimiter, aLastDelimiter : string) : string; //get double quoted or dequoted string function DbQuotedStr(const str : string): string; function UnDbQuotedStr(const str: string) : string; //get simple quoted or dequoted string function SpQuotedStr(const str : string): string; function UnSpQuotedStr(const str : string): string; function UnQuotedStr(const str : string; const aQuote : Char) : string; //ternary operator function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : string) : string; overload; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Integer) : Integer; overload; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Extended) : Extended; overload; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : TObject) : TObject; overload; var path : TEnvironmentPath; //Enabled if QuickService is defined IsQuickServiceApp : Boolean; implementation {TFileHelper} {$IFNDEF FPC} {$IFDEF MSWINDOWS} class function TFileHelper.IsInUse(const FileName : string) : Boolean; var HFileRes: HFILE; begin Result := False; if not FileExists(FileName) then Exit; try HFileRes := CreateFile(PChar(FileName) ,GENERIC_READ or GENERIC_WRITE ,0 ,nil ,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL ,0); Result := (HFileRes = INVALID_HANDLE_VALUE); if not(Result) then begin CloseHandle(HFileRes); end; except Result := True; end; end; {$ENDIF} {$IFDEF DELPHILINUX} class function TFileHelper.IsInUse(const FileName : string) : Boolean; var fs : TFileStream; begin try fs := TFileStream.Create(FileName, fmOpenReadWrite, fmShareExclusive); Result := True; fs.Free; except Result := False; end; end; {$ENDIF} {$IFDEF MSWINDOWS} class function TFileHelper.GetSize(const FileName: String): Int64; var info: TWin32FileAttributeData; begin Result := -1; if not GetFileAttributesEx(PWideChar(FileName), GetFileExInfoStandard, @info) then Exit; Result := Int64(info.nFileSizeLow) or Int64(info.nFileSizeHigh shl 32); end; {$ELSE} class function TFileHelper.GetSize(const FileName: String): Int64; var sr : TSearchRec; begin if FindFirst(fileName, faAnyFile, sr ) = 0 then Result := sr.Size else Result := -1; end; {$ENDIF} {TDirectoryHelper} class function TDirectoryHelper.GetSize(const Path: String): Int64; var filename : string; begin Result := -1; for filename in TDirectory.GetFiles(Path) do begin Result := Result + TFile.GetSize(filename); end; end; {$ENDIF} {other functions} function RandomPassword(const PasswordLength : Integer; Complexity : TPasswordComplexity = [pfIncludeNumbers,pfIncludeSigns]) : string; const PassAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; PassSigns = '@!&$'; PassNumbers = '1234567890'; var MinNumbers, MinSigns : Integer; NumNumbers, NumSigns : Integer; begin Result := ''; Randomize; //fill all alfa repeat Result := Result + PassAlpha[Random(Length(PassAlpha))+1]; until (Length(Result) = PasswordLength); //checks if need include numbers if pfIncludeNumbers in Complexity then begin MinNumbers := Round(PasswordLength / 10 * 2); NumNumbers := 0; if MinNumbers = 0 then MinNumbers := 1; repeat Result[Random(PasswordLength)+1] := PassNumbers[Random(Length(PassNumbers))+1]; Inc(NumNumbers); until NumNumbers = MinNumbers; end; //checks if need include signs if pfIncludeSigns in Complexity then begin MinSigns := Round(PasswordLength / 10 * 1); NumSigns := 0; if MinSigns = 0 then MinSigns := 1; repeat Result[Random(PasswordLength)+1] := PassSigns[Random(Length(PassSigns))+1]; Inc(NumSigns); until NumSigns = MinSigns; end; end; function RandomString(const aLength: Integer) : string; const chars : string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; var i : Integer; clong : Integer; begin clong := High(chars); SetLength(Result, aLength); for i := 1 to aLength do begin Result[i] := chars[Random(clong) + 1]; end; end; function ExtractFileNameWithoutExt(const FileName: string): string; begin Result := TPath.GetFileNameWithoutExtension(FileName); end; function UnixToWindowsPath(const UnixPath: string): string; begin Result := StringReplace(UnixPath, '/', '\',[rfReplaceAll, rfIgnoreCase]); end; function WindowsToUnixPath(const WindowsPath: string): string; begin Result := StringReplace(WindowsPath, '\', '/',[rfReplaceAll, rfIgnoreCase]); end; function CorrectURLPath(const cUrl : string) : string; var nurl : string; begin nurl := WindowsToUnixPath(cUrl); nurl := StringReplace(nurl,'//','/',[rfReplaceAll]); Result := StringReplace(nurl,' ','%20',[rfReplaceAll]); //TNetEncoding.Url.Encode() end; function UrlGetProtocol(const aUrl : string) : string; begin Result := aUrl.SubString(0,aUrl.IndexOf('://')); end; function UrlGetHost(const aUrl : string) : string; var url : string; len : Integer; begin url := UrlRemoveProtocol(aUrl); if url.Contains('/') then len := url.IndexOf('/') else len := url.Length; Result := url.SubString(0,len); end; function UrlGetPath(const aUrl : string) : string; var url : string; len : Integer; begin url := UrlRemoveProtocol(aUrl); if not url.Contains('/') then Exit(''); len := url.IndexOf('?'); if len < 0 then len := url.Length else len := url.IndexOf('?') - url.IndexOf('/'); Result := url.Substring(url.IndexOf('/'),len); end; function UrlGetQuery(const aUrl : string) : string; begin if not aUrl.Contains('?') then Exit(''); Result := aUrl.Substring(aUrl.IndexOf('?')+1); end; function UrlRemoveProtocol(const aUrl : string) : string; var pos : Integer; begin pos := aUrl.IndexOf('://'); if pos < 0 then pos := 0 else pos := pos + 3; Result := aUrl.SubString(pos, aUrl.Length); end; function UrlRemoveQuery(const aUrl : string) : string; begin if not aUrl.Contains('?') then Exit(aUrl); Result := aUrl.Substring(0,aUrl.IndexOf('?')); end; function UrlSimpleEncode(const aUrl : string) : string; begin Result := StringReplace(aUrl,' ','%20',[rfReplaceAll]); end; procedure GetEnvironmentPaths; begin //gets path path.EXEPATH := TPath.GetDirectoryName(ParamStr(0)); {$IFDEF MSWINDOWS} path.WINDOWS := SysUtils.GetEnvironmentVariable('windir'); path.PROGRAMFILES := SysUtils.GetEnvironmentVariable('ProgramFiles'); path.COMMONFILES := SysUtils.GetEnvironmentVariable('CommonProgramFiles(x86)'); path.HOMEDRIVE := SysUtils.GetEnvironmentVariable('SystemDrive'); path.USERPROFILE := SysUtils.GetEnvironmentVariable('USERPROFILE'); path.PROGRAMDATA := SysUtils.GetEnvironmentVariable('ProgramData'); path.ALLUSERSPROFILE := SysUtils.GetEnvironmentVariable('AllUsersProfile'); path.INSTDRIVE := path.HOMEDRIVE; path.TEMP := SysUtils.GetEnvironmentVariable('TEMP'); //these paths fail if user is SYSTEM try path.SYSTEM := GetSpecialFolderPath(CSIDL_SYSTEM); path.APPDATA := GetSpecialFolderPath(CSIDL_APPDATA); path.DESKTOP := GetSpecialFolderPath(CSIDL_DESKTOP); path.DESKTOP_ALLUSERS := GetSpecialFolderPath(CSIDL_COMMON_DESKTOPDIRECTORY); path.STARTMENU:=GetSpecialFolderPath(CSIDL_PROGRAMS); path.STARTMENU_ALLUSERS:=GetSpecialFolderPath(CSIDL_COMMON_PROGRAMS); path.STARTMENU_ALLUSERS := path.STARTMENU; path.STARTUP:=GetSpecialFolderPath(CSIDL_STARTUP); except // end; {$ENDIF} end; {$IFDEF MSWINDOWS} function GetSpecialFolderPath(folderID : Integer) : string; var shellMalloc: IMalloc; ppidl: PItemIdList; begin ppidl := nil; try if SHGetMalloc(shellMalloc) = NOERROR then begin SHGetSpecialFolderLocation(0, folderID, ppidl); SetLength(Result, MAX_PATH); if not SHGetPathFromIDList(ppidl,{$IFDEF FPC}PAnsiChar(Result){$ELSE}PChar(Result){$ENDIF}) then begin raise EShellError.create(Format('GetSpecialFolderPath: Invalid PIPL (%d)',[folderID])); end; SetLength(Result, lStrLen({$IFDEF FPC}PAnsiChar(Result){$ELSE}PChar(Result){$ENDIF})); end; finally if ppidl <> nil then shellMalloc.Free(ppidl); end; end; function Is64bitOS : Boolean; begin {$IFDEF WIN64} Result := True; {$ELSE} Result := False; {$ENDIF WIN64} end; function IsConsole: Boolean; begin {$IFDEF CONSOLE} Result := True; {$ELSE} Result := False; {$ENDIF CONSOLE} end; {$ENDIF} function HasConsoleOutput : Boolean; {$IFDEF MSWINDOWS} var stout : THandle; begin try stout := GetStdHandle(Std_Output_Handle); {$WARN SYMBOL_PLATFORM OFF} //Allready checked that we are on a windows platform Win32Check(stout <> Invalid_Handle_Value); {$WARN SYMBOL_PLATFORM ON} Result := stout <> 0; except Result := False; end; end; {$ELSE} begin Result := IsConsole; end; {$ENDIF} function IsDebug: Boolean; begin {$IFDEF DEBUG} Result := True; {$ELSE} Result := False; {$ENDIF DEBUG} end; {$IFDEF MSWINDOWS} function IsService : Boolean; begin //only working with my Quick.AppService unit try Result := (IsConsole) and (not HasConsoleOutput); except Result := False; end; end; function SecondsIdle: DWord; var liInfo: TLastInputInfo; begin liInfo.cbSize := SizeOf(TLastInputInfo) ; GetLastInputInfo(liInfo) ; Result := (GetTickCount - liInfo.dwTime) DIV 1000; end; procedure FreeUnusedMem; begin if Win32Platform = VER_PLATFORM_WIN32_NT then SetProcessWorkingSetSize(GetCurrentProcess, $FFFFFFFF, $FFFFFFFF); end; function SetScreenResolution(Width, Height: integer): Longint; var DeviceMode: TDeviceMode; begin with DeviceMode do begin dmSize := SizeOf(TDeviceMode); dmPelsWidth := Width; dmPelsHeight := Height; dmFields := DM_PELSWIDTH or DM_PELSHEIGHT; end; Result := ChangeDisplaySettings(DeviceMode, CDS_UPDATEREGISTRY); end; {$ENDIF MSWINDOWS} function LastDayCurrentMonth: TDateTime; begin Result := EncodeDate(YearOf(Now),MonthOf(Now), DaysInMonth(Now)); end; {$IFDEF FPC} function DateTimeInRange(ADateTime: TDateTime; AStartDateTime, AEndDateTime: TDateTime; aInclusive: Boolean = True): Boolean; begin if aInclusive then Result := (AStartDateTime <= ADateTime) and (ADateTime <= AEndDateTime) else Result := (AStartDateTime < ADateTime) and (ADateTime < AEndDateTime); end; {$ENDIF} function IsSameDay(cBefore, cNow : TDateTime) : Boolean; begin //Test: Result := MinutesBetween(cBefore,cNow) < 1; Result := DateTimeInRange(cNow,StartOfTheDay(cBefore),EndOfTheDay(cBefore),True); end; function ChangeTimeOfADay(aDate : TDateTime; aHour, aMinute, aSecond : Word; aMilliSecond : Word = 0) : TDateTime; var y, m, d : Word; begin DecodeDate(aDate,y,m,d); Result := EncodeDateTime(y,m,d,aHour,aMinute,aSecond,aMilliSecond); end; function ChangeDateOfADay(aDate : TDateTime; aYear, aMonth, aDay : Word) : TDateTime; var h, m, s, ms : Word; begin DecodeTime(aDate,h,m,s,ms); Result := EncodeDateTime(aYear,aMonth,aDay,h,m,s,0); end; function FillStr(const C : Char; const Count : Integer) : string; var i : Integer; begin Result := ''; for i := 1 to Count do Result := Result + C; end; function FillStrEx(const value : string; const Count : Integer) : string; var i : Integer; begin Result := ''; for i := 1 to Count do Result := Result + value; end; function StrInArray(const aValue : string; const aInArray : array of string; aCaseSensitive : Boolean = True) : Boolean; var s : string; begin for s in aInArray do begin if aCaseSensitive then begin if s = aValue then Exit(True); end else begin if CompareText(aValue,s) = 0 then Exit(True); end; end; Result := False; end; function IntInArray(const aValue : Integer; const aInArray : array of Integer) : Boolean; var i : Integer; begin for i in aInArray do begin if i = aValue then Exit(True); end; Result := False; end; function IsEmptyArray(aArray : TArray<string>) : Boolean; begin Result := Length(aArray) = 0; end; function IsEmptyArray(aArray : TArray<Integer>) : Boolean; begin Result := Length(aArray) = 0; end; function Zeroes(const Number, Len : Int64) : string; begin if Len > Length(IntToStr(Number)) then Result := FillStr('0',Len - Length(IntToStr(Number))) + IntToStr(Number) else Result := IntToStr(Number); end; function NumberToStr(const Number : Int64) : string; begin try Result := FormatFloat('0,',Number); except Result := '#Error'; end; end; function Spaces(const Count : Integer) : string; begin Result := FillStr(' ',Count); end; function NowStr : string; begin Result := DateTimeToStr(Now()); end; function NewGuidStr : string; {$IFNDEF DELPHIRX10_UP} var guid : TGUID; {$ENDIF} begin {$IFDEF DELPHIRX10_UP} Result := TGUID.NewGuid.ToString; {$ELSE} guid.NewGuid; Result := guid.ToString {$ENDIF} end; function IsLike(cText, Pattern: string) : Boolean; var i, n : Integer; match : Boolean; wildcard : Boolean; CurrentPattern : Char; begin Result := False; wildcard := False; cText := LowerCase(cText); Pattern := LowerCase(Pattern); match := False; if (Pattern.Length > cText.Length) or (Pattern = '') then Exit; if Pattern = '*' then begin Result := True; Exit; end; for i := 1 to cText.Length do begin CurrentPattern := Pattern[i]; if CurrentPattern = '*' then wildcard := True; if wildcard then begin n := Pos(Copy(Pattern,i+1,Pattern.Length),cText); if (n > i) or (Pattern.Length = i) then begin Result := True; Exit; end; end else begin if (cText[i] = CurrentPattern) or (CurrentPattern = '?') then match := True else match := False; end; end; Result := match; end; function Capitalize(s: string): string; begin Result := ''; if s.Length = 0 then Exit; s := LowerCase(s,loUserLocale); Result := UpperCase(s[1],loUserLocale) + Trim(Copy(s, 2, s.Length)); end; function CapitalizeWords(s: string): string; var cword : string; begin Result := ''; if s.Length = 0 then Exit; s := LowerCase(s,loUserLocale); for cword in s.Split([' ']) do begin if Result = '' then Result := Capitalize(cword) else Result := Result + ' ' + Capitalize(cword); end; end; function GetLoggedUserName : string; {$IFDEF MSWINDOWS} const cnMaxUserNameLen = 254; var sUserName : string; dwUserNameLen : DWord; begin dwUserNameLen := cnMaxUserNameLen-1; SetLength( sUserName, cnMaxUserNameLen ); GetUserName(PChar( sUserName ),dwUserNameLen ); SetLength( sUserName, dwUserNameLen ); Result := sUserName; end; {$ELSE} {$IF DEFINED(FPC) AND DEFINED(LINUX)} begin Result := GetEnvironmentVariable('USERNAME'); end; {$ELSE} var {$IFNDEF NEXTGEN} plogin : PAnsiChar; {$ELSE} plogin : MarshaledAString; {$ENDIF} begin {$IFDEF POSIX} try plogin := getlogin; {$IFDEF NEXTGEN} Result := string(plogin); {$ELSE} Result := Copy(plogin,1,Length(Trim(plogin))); {$ENDIF} except Result := 'N/A'; end; {$ELSE} Result := 'N/A'; {$ENDIF} //raise ENotImplemented.Create('Not Android GetLoggedUserName implemented!'); end; {$ENDIF} {$ENDIF} {$IFDEF IOS} function GetDeviceModel : String; var size : size_t; buffer : array of Byte; begin sysctlbyname('hw.machine',nil,@size,nil,0); if size > 0 then begin SetLength(buffer, size); sysctlbyname('hw.machine',@buffer[0],@size,nil,0); Result := UTF8ToString(MarshaledAString(buffer)); end else Result := EmptyStr; end; {$ENDIF} function GetComputerName : string; {$IFDEF MSWINDOWS} var dwLength: dword; begin dwLength := 253; SetLength(Result, dwLength+1); if not Windows.GetComputerName(pchar(result), dwLength) then Result := 'Not detected!'; Result := pchar(result); end; {$ELSE} {$IF DEFINED(FPC) AND DEFINED(LINUX)} begin Result := GetEnvironmentVariable('COMPUTERNAME'); end; {$ELSE} //Android gets model name {$IFDEF NEXTGEN} begin {$IFDEF ANDROID} Result := JStringToString(TJBuild.JavaClass.MODEL); {$ELSE} //IOS Result := GetDeviceModel; {$ENDIF} end; {$ELSE} {$IFDEF DELPHILINUX} var phost : PAnsiChar; begin try phost := AllocMem(256); try if gethostname(phost,_SC_HOST_NAME_MAX) = 0 then begin {$IFDEF DEBUG} Result := Copy(Trim(phost),1,Length(Trim(phost))); {$ELSE} Result := Copy(phost,1,Length(phost)); {$ENDIF} end else Result := 'N/A.'; finally FreeMem(phost); end; except Result := 'N/A'; end; end; {$ELSE} //OSX begin Result := NSStrToStr(TNSHost.Wrap(TNSHost.OCClass.currentHost).localizedName); end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF MSWINDOWS} function IsRemoteSession : Boolean; const SM_REMOTECONTROL = $2001; SM_REMOTESESSION = $1000; begin Result := (GetSystemMetrics(SM_REMOTESESSION) <> 0) or (GetSystemMetrics(SM_REMOTECONTROL) <> 0); end; {$ENDIF} function ExtractDomainAndUser(const aUser : string; out oDomain, oUser : string) : Boolean; begin //check if domain specified into username if aUser.Contains('\') then begin oDomain := Copy(aUser,Low(aUser),Pos('\',aUser)-1); oUser := Copy(aUser,Pos('\',aUser)+1,aUser.Length); Exit(True); end else if aUser.Contains('@') then begin oDomain := Copy(aUser,Pos('@',aUser)+1,aUser.Length); oUser := Copy(aUser,Low(aUser),Pos('@',aUser)-1); Exit(True); end; oDomain := ''; oUser := aUser; Result := False; end; function NormalizePathDelim(const cPath : string; const Delim : Char) : string; begin if Delim = '\' then Result := StringReplace(cPath,'/',Delim,[rfReplaceAll]) else Result := StringReplace(cPath,'\',Delim,[rfReplaceAll]); end; function CombinePaths(const aFirstPath, aSecondPath: string; aDelim : Char): string; var path1 : string; path2 : string; begin path1 := NormalizePathDelim(aFirstPath,aDelim); path2 := NormalizePathDelim(aSecondPath,aDelim); if path1.EndsWith(aDelim) then begin if path2.StartsWith(aDelim) then Result := path1 + path2.Substring(1) else Result := path1 + path2; end else begin if path2.StartsWith(aDelim) then Result := path1 + path2 else result := path1 + aDelim + path2; end; end; function RemoveFirstPathSegment(const cdir : string) : string; var posi : Integer; delim : Char; dir : string; StartsWithDelim : Boolean; begin if cDir.Contains('\') then delim := '\' else if cDir.Contains('/') then delim := '/' else begin Exit(''); end; dir := NormalizePathDelim(cDir,delim); if dir.StartsWith(delim) then begin dir := Copy(dir,2,dir.Length); StartsWithDelim := True; end else StartsWithDelim := False; if dir.CountChar(delim) = 0 then Exit('') else posi := Pos(delim,dir)+1; Result := Copy(dir,posi,dir.Length); if (not Result.IsEmpty) and (StartsWithDelim) then Result := delim + Result; end; function RemoveLastPathSegment(const cDir : string) : string; var posi : Integer; delim : Char; dir : string; EndsWithDelim : Boolean; begin if cDir.Contains('\') then delim := '\' else if cDir.Contains('/') then delim := '/' else begin Exit(''); end; dir := NormalizePathDelim(cDir,delim); if dir.EndsWith(delim) then begin dir := Copy(dir,1,dir.Length-1); EndsWithDelim := True; end else EndsWithDelim := False; if dir.CountChar(delim) > 1 then posi := dir.LastDelimiter(delim) else posi := Pos(delim,dir)-1; if posi = dir.Length then posi := 0; Result := Copy(dir,1,posi); if (not Result.IsEmpty) and (EndsWithDelim) then Result := Result + delim; end; function GetPathDelimiter(const aPath : string) : string; begin if aPath.Contains('/') then Result := '/' else if aPath.Contains('\') then Result := '\' else Result := ''; end; function GetFirstPathSegment(const aPath : string) : string; var delimiter : string; spath : string; begin delimiter := GetPathDelimiter(aPath); if delimiter.IsEmpty then Exit(aPath); if aPath.StartsWith(delimiter) then spath := Copy(aPath,2,aPath.Length) else spath := aPath; if spath.Contains(delimiter) then Result := Copy(spath,0,spath.IndexOf(delimiter)) else Result := spath; end; function GetLastPathSegment(const aPath : string) : string; var delimiter : string; spath : string; begin delimiter := GetPathDelimiter(aPath); if delimiter.IsEmpty then Exit(aPath); if aPath.EndsWith(delimiter) then spath := Copy(aPath,0,aPath.Length - 1) else spath := aPath; Result := spath.Substring(spath.LastDelimiter(delimiter)+1); end; function ParamFindSwitch(const Switch : string) : Boolean; begin Result := FindCmdLineSwitch(Switch,['-', '/'],True); end; {$IFDEF FPC} function FindCmdLineSwitch(const Switch: string; var Value: string; IgnoreCase: Boolean = True; const SwitchTypes: TCmdLineSwitchTypes = [clstValueNextParam, clstValueAppended]): Boolean; overload; type TCompareProc = function(const S1, S2: string): Boolean; var Param: string; I, ValueOfs, SwitchLen, ParamLen: Integer; SameSwitch: TCompareProc; begin Result := False; Value := ''; if IgnoreCase then SameSwitch := SameText else SameSwitch := SameStr; SwitchLen := Switch.Length; for I := 1 to ParamCount do begin Param := ParamStr(I); if CharInSet(Param.Chars[0], SwitchChars) and SameSwitch(Param.SubString(1,SwitchLen), Switch) then begin ParamLen := Param.Length; // Look for an appended value if the param is longer than the switch if (ParamLen > SwitchLen + 1) then begin // If not looking for appended value switches then this is not a matching switch if not (clstValueAppended in SwitchTypes) then Continue; ValueOfs := SwitchLen + 1; if Param.Chars[ValueOfs] = ':' then Inc(ValueOfs); Value := Param.SubString(ValueOfs, MaxInt); end // If the next param is not a switch, then treat it as the value else if (clstValueNextParam in SwitchTypes) and (I < ParamCount) and not CharInSet(ParamStr(I+1).Chars[0], SwitchChars) then Value := ParamStr(I+1); Result := True; Break; end; end; end; {$ENDIF} function ParamGetSwitch(const Switch : string; var cvalue : string) : Boolean; begin Result := FindCmdLineSwitch(Switch,cvalue,True,[clstValueAppended]); end; function GetAppName : string; begin Result := ExtractFilenameWithoutExt(ParamStr(0)); end; function GetAppVersionStr: string; {$IFDEF MSWINDOWS} var Rec: LongRec; ver : Cardinal; begin ver := GetFileVersion(ParamStr(0)); if ver <> Cardinal(-1) then begin Rec := LongRec(ver); Result := Format('%d.%d', [Rec.Hi, Rec.Lo]); end else Result := ''; end; {$ELSE} {$IF DEFINED(FPC) AND DEFINED(LINUX)} var version : TProgramVersion; begin if GetProgramVersion(version) then Result := Format('%d.%d', [version.Major, version.Minor]) else Result := ''; end; {$ELSE} {$IFDEF NEXTGEN} {$IFDEF ANDROID} var PkgInfo : JPackageInfo; begin {$IFDEF DELPHIRX103_UP} PkgInfo := TAndroidHelper.Activity.getPackageManager.getPackageInfo(TAndroidHelper.Activity.getPackageName,0); {$ELSE} PkgInfo := SharedActivity.getPackageManager.getPackageInfo(SharedActivity.getPackageName,0); {$ENDIF} Result := IntToStr(PkgInfo.VersionCode); end; {$ELSE} //IOS var AppKey: Pointer; AppBundle: NSBundle; BuildStr : NSString; begin try AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID; AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey)); Result := UTF8ToString(BuildStr.UTF8String); except Result := ''; end; end; {$ENDIF} {$ELSE} //OSX {$IFDEF OSX} var AppKey: Pointer; AppBundle: NSBundle; BuildStr : NSString; begin try AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID; AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey)); Result := UTF8ToString(BuildStr.UTF8String); except Result := ''; end; end; {$ELSE} begin Result := ''; end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} function GetAppVersionFullStr: string; {$IFDEF MSWINDOWS} var Exe: string; Size, Handle: DWORD; Buffer: TBytes; FixedPtr: PVSFixedFileInfo; begin Result := ''; Exe := ParamStr(0); Size := GetFileVersionInfoSize(PChar(Exe), Handle); if Size = 0 then begin //RaiseLastOSError; //no version info in file Exit; end; SetLength(Buffer, Size); if not GetFileVersionInfo(PChar(Exe), Handle, Size, Buffer) then RaiseLastOSError; if not VerQueryValue(Buffer, '\', Pointer(FixedPtr), Size) then RaiseLastOSError; if (LongRec(FixedPtr.dwFileVersionLS).Hi = 0) and (LongRec(FixedPtr.dwFileVersionLS).Lo = 0) then begin Result := Format('%d.%d', [LongRec(FixedPtr.dwFileVersionMS).Hi, //major LongRec(FixedPtr.dwFileVersionMS).Lo]); //minor end else if (LongRec(FixedPtr.dwFileVersionLS).Lo = 0) then begin Result := Format('%d.%d.%d', [LongRec(FixedPtr.dwFileVersionMS).Hi, //major LongRec(FixedPtr.dwFileVersionMS).Lo, //minor LongRec(FixedPtr.dwFileVersionLS).Hi]); //release end else begin Result := Format('%d.%d.%d.%d', [LongRec(FixedPtr.dwFileVersionMS).Hi, //major LongRec(FixedPtr.dwFileVersionMS).Lo, //minor LongRec(FixedPtr.dwFileVersionLS).Hi, //release LongRec(FixedPtr.dwFileVersionLS).Lo]); //build end; end; {$ELSE} {$IF DEFINED(FPC) AND DEFINED(LINUX)} var version : TProgramVersion; begin if GetProgramVersion(version) then Result := Format('%d.%d.%d.%d', [version.Major, version.Minor, version.Revision, version.Build]) else Result := ''; end; {$ELSE} {$IFDEF NEXTGEN} {$IFDEF ANDROID} var PkgInfo : JPackageInfo; begin {$IFDEF DELPHIRX103_UP} PkgInfo := TAndroidHelper.Activity.getPackageManager.getPackageInfo(TAndroidHelper.Activity.getPackageName,0); {$ELSE} PkgInfo := SharedActivity.getPackageManager.getPackageInfo(SharedActivity.getPackageName,0); {$ENDIF} Result := JStringToString(PkgInfo.versionName); end; {$ELSE} //IOS var AppKey: Pointer; AppBundle: NSBundle; BuildStr : NSString; begin AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID; AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey)); Result := UTF8ToString(BuildStr.UTF8String); end; {$ENDIF} {$ELSE} {$IFDEF OSX} var AppKey: Pointer; AppBundle: NSBundle; BuildStr : NSString; begin AppKey := (StrToNSStr('CFBundleVersion') as ILocalObject).GetObjectID; AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); BuildStr := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppKey)); Result := UTF8ToString(BuildStr.UTF8String); end; {$ELSE} begin Result := ''; end; {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} function UTCToLocalTime(GMTTime: TDateTime): TDateTime; begin {$IFDEF FPC} Result := LocalTimeToUniversal(GMTTime); {$ELSE} Result := TTimeZone.Local.ToLocalTime(GMTTime); {$ENDIF} end; function LocalTimeToUTC(LocalTime : TDateTime): TDateTime; begin {$IFDEF FPC} Result := UniversalTimeToLocal(Localtime); {$ELSE} Result := TTimeZone.Local.ToUniversalTime(LocalTime); {$ENDIF} end; function DateTimeToGMT(aDate : TDateTime) : string; var FmtSettings : TFormatSettings; begin FmtSettings.DateSeparator := '-'; FmtSettings.TimeSeparator := ':'; FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ" GMT"'; Result := DateTimeToStr(aDate,FmtSettings).Trim; end; function GMTToDateTime(aDate : string) : TDateTime; var FmtSettings : TFormatSettings; begin FmtSettings.DateSeparator := '-'; FmtSettings.TimeSeparator := ':'; FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ" GMT"'; Result := StrToDateTime(aDate,FmtSettings); end; function DateTimeToJsonDate(aDateTime : TDateTime) : string; {$IFNDEF DELPHIXE7_UP} var FmtSettings : TFormatSettings; {$ENDIF} begin {$IFDEF DELPHIXE7_UP} Result := DateToISO8601(aDateTime); {$ELSE} FmtSettings.DateSeparator := '-'; FmtSettings.TimeSeparator := ':'; FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ"Z"'; Result := DateTimeToStr(aDateTime,FmtSettings).Trim; {$ENDIF} end; function JsonDateToDateTime(const aJsonDate : string) : TDateTime; {$IFNDEF DELPHIXE7_UP} var FmtSettings : TFormatSettings; {$ENDIF} {$IFDEF FPC} var jdate : string; {$ENDIF} begin {$IFDEF DELPHIXE7_UP} Result := ISO8601ToDate(aJsonDate); {$ELSE} FmtSettings.DateSeparator := '-'; FmtSettings.TimeSeparator := ':'; FmtSettings.ShortDateFormat := 'YYYY-MM-DD"T"HH:NN:SS.ZZZ"Z"'; {$IFDEF FPC} jdate := StringReplace(aJsondate,'T',' ',[rfIgnoreCase]); jdate := Copy(jdate,1,Pos('.',jdate)-1); Result := StrToDateTime(jdate,FmtSettings); {$ELSE} Result := StrToDateTime(aJsonDate,FmtSettings); {$ENDIF} {$ENDIF} end; function CountDigits(anInt: Cardinal): Cardinal; inline; var cmp: Cardinal; begin cmp := 10; Result := 1; while (Result < 10) and (cmp <= anInt) do begin cmp := cmp*10; Inc(Result); end; end; function CountStr(const aFindStr, aSourceStr : string) : Integer; var i : Integer; found : Integer; findstr : string; mainstr : string; begin findstr := aFindStr.ToLower; mainstr := aSourceStr.ToLower; Result := 0; i := 0; while i < mainstr.Length do begin found := Pos(findstr,mainstr,i); if found > 0 then begin i := found; Inc(Result); end else Break; end; end; procedure SaveStreamToFile(aStream : TStream; const aFileName : string); var fs : TFileStream; begin fs := TFileStream.Create(aFileName,fmCreate); try aStream.Seek(0,soBeginning); fs.CopyFrom(aStream,aStream.Size); finally fs.Free; end; end; function StreamToString(const aStream: TStream; const aEncoding: TEncoding): string; var sbytes: TBytes; begin aStream.Position := 0; SetLength(sbytes, aStream.Size); aStream.ReadBuffer(sbytes,aStream.Size); Result := aEncoding.GetString(sbytes); end; function StreamToStringEx(aStream : TStream) : string; var ss : TStringStream; begin aStream.Position := 0; if aStream = nil then Exit; if aStream is TMemoryStream then begin SetString(Result, PChar(TMemoryStream(aStream).Memory), TMemoryStream(aStream).Size div SizeOf(Char)); end else if aStream is TStringStream then begin Result := TStringStream(aStream).DataString; end else begin ss := TStringStream.Create; try aStream.Seek(0,soBeginning); ss.CopyFrom(aStream,aStream.Size); Result := ss.DataString; finally ss.Free; end; end; end; procedure StringToStream(const aStr : string; aStream : TStream; const aEncoding: TEncoding); var stream : TStringStream; begin stream := TStringStream.Create(aStr,aEncoding); try aStream.CopyFrom(stream,stream.Size); finally stream.Free; end; end; procedure StringToStreamEx(const aStr : string; aStream : TStream); begin aStream.Seek(0,soBeginning); aStream.WriteBuffer(Pointer(aStr)^,aStr.Length * SizeOf(Char)); end; function CommaText(aList : TStringList) : string; var value : string; sb : TStringBuilder; begin if aList.Text = '' then Exit; sb := TStringBuilder.Create; try for value in aList do begin sb.Append(value); sb.Append(','); end; if sb.Length > 1 then Result := sb.ToString(0, sb.Length - 1); finally sb.Free; end; end; function CommaText(aArray : TArray<string>) : string; var value : string; sb : TStringBuilder; begin if High(aArray) < 0 then Exit; sb := TStringBuilder.Create; try for value in aArray do begin sb.Append(value); sb.Append(','); end; if sb.Length > 1 then Result := sb.ToString(0, sb.Length - 1); finally sb.Free; end; end; function ArrayToString(aArray : TArray<string>) : string; var value : string; sb : TStringBuilder; begin Result := ''; if High(aArray) < 0 then Exit; sb := TStringBuilder.Create; try for value in aArray do begin sb.Append(value); sb.Append(CRLF); end; Result := sb.ToString; finally sb.Free; end; end; function ArrayToString(aArray : TArray<string>; aSeparator : string) : string; var value : string; sb : TStringBuilder; isfirst : Boolean; begin Result := ''; if High(aArray) < 0 then Exit; isfirst := True; sb := TStringBuilder.Create; try for value in aArray do begin if isfirst then isfirst := False else sb.Append(aSeparator); sb.Append(value); end; Result := sb.ToString; finally sb.Free; end; end; function StringsToArray(aStrings : TStrings) : TArray<string>; var i : Integer; begin if aStrings.Count = 0 then Exit; SetLength(Result,aStrings.Count); for i := 0 to aStrings.Count - 1 do begin Result[i] := aStrings[i]; end; end; function StringsToArray(const aString : string) : TArray<string>; var item : string; begin for item in aString.Split([';',',']) do Result := Result + [item.Trim]; end; { TCounter } procedure TCounter.Init(aMaxValue : Integer); begin fMaxValue := aMaxValue; fCurrentValue := 0; end; function TCounter.Count : Integer; begin Result := fCurrentValue; end; function TCounter.CountIs(aValue : Integer) : Boolean; begin Result := fCurrentValue = aValue; end; function TCounter.Check : Boolean; begin if fCurrentValue = fMaxValue then begin Result := True; Reset; end else begin Result := False; Inc(fCurrentValue); end; end; procedure TCounter.Reset; begin fCurrentValue := fMaxValue; end; { TimeCounter } procedure TTimeCounter.Init(MillisecondsToReach : Integer); begin fDoneEvery := MillisecondsToReach; end; function TTimeCounter.Check : Boolean; begin if MilliSecondsBetween(fCurrentTime,Now) > fDoneEvery then begin fCurrentTime := Now(); Result := True; end else Result := False; end; procedure TTimeCounter.Reset; begin fCurrentTime := Now(); end; { TArrayOfStringHelper} {$IFNDEF FPC} function TArrayOfStringHelper.Any : Boolean; begin Result := High(Self) >= 0; end; function TArrayOfStringHelper.Any(const aValue : string) : Boolean; begin Result := Exists(aValue); end; function TArrayOfStringHelper.Add(const aValue : string) : Integer; begin SetLength(Self,Length(Self)+1); Self[High(Self)] := aValue; Result := High(Self); end; function TArrayOfStringHelper.AddIfNotExists(const aValue : string; aCaseSense : Boolean = False) : Integer; var i : Integer; begin for i := Low(Self) to High(Self) do begin if aCaseSense then begin if Self[i] = aValue then Exit(i); end else begin if CompareText(Self[i],aValue) = 0 then Exit(i) end; end; //if not exists add it Result := Self.Add(aValue); end; function TArrayOfStringHelper.Remove(const aValue : string) : Boolean; var i : Integer; begin for i := Low(Self) to High(Self) do begin if CompareText(Self[i],aValue) = 0 then begin {$IFDEF DELPHIXE7_UP} System.Delete(Self,i,1); {$ELSE} TArrayUtil<string>.Delete(Self,i); {$ENDIF} Exit(True); end; end; Result := False; end; function TArrayOfStringHelper.Exists(const aValue : string) : Boolean; var value : string; begin Result := False; for value in Self do begin if CompareText(value,aValue) = 0 then Exit(True) end; end; function TArrayOfStringHelper.Count : Integer; begin Result := High(Self) + 1; end; {$ENDIF} { TPairItem } constructor TPairItem.Create(const aName, aValue: string); begin Name := aName; Value := aValue; end; { TPairList } function TPairList.GetEnumerator : TPairEnumerator; begin Result := TPairEnumerator.Create(fItems); end; function TPairList.Add(aPair: TPairItem): Integer; begin SetLength(fItems,Length(fItems)+1); fItems[High(fItems)] := aPair; Result := High(fItems); end; function TPairList.Add(const aName, aValue: string): Integer; begin SetLength(fItems,Length(fItems)+1); fItems[High(fItems)].Name := aName; fItems[High(fItems)].Value := aValue; Result := High(fItems); end; procedure TPairList.AddOrUpdate(const aName, aValue: string); var i : Integer; begin for i := Low(fItems) to High(fItems) do begin if CompareText(fItems[i].Name,aName) = 0 then begin fItems[i].Value := aValue; Exit; end; end; //if not exists add it Self.Add(aName,aValue); end; function TPairList.Count: Integer; begin Result := High(fItems) + 1; end; function TPairList.Exists(const aName: string): Boolean; var i : Integer; begin Result := False; for i := Low(fItems) to High(fItems) do begin if CompareText(fItems[i].Name,aName) = 0 then Exit(True) end; end; function TPairList.GetPair(const aName: string): TPairItem; var i : Integer; begin for i := Low(fItems) to High(fItems) do begin if CompareText(fItems[i].Name,aName) = 0 then Exit(fItems[i]); end; end; function TPairList.GetValue(const aName: string): string; var i : Integer; begin Result := ''; for i := Low(fItems) to High(fItems) do begin if CompareText(fItems[i].Name,aName) = 0 then Exit(fItems[i].Value); end; end; function TPairList.Remove(const aName: string): Boolean; var i : Integer; begin for i := Low(fItems) to High(fItems) do begin if CompareText(fItems[i].Name,aName) = 0 then begin {$IF Defined(DELPHIXE7_UP) OR Defined(FPC)} System.Delete(fItems,i,1); {$ELSE} TArrayUtil<TPairItem>.Delete(fItems,i); {$ENDIF} Exit(True); end; end; Result := False; end; function TPairList.ToArray : TArray<TPairItem>; begin Result := fItems; end; procedure TPairList.FromArray(aValue : TArray<TPairItem>); begin fItems := aValue; end; procedure TPairList.Clear; begin SetLength(fItems,0); end; { TPairList.TPairEnumerator} constructor TPairList.TPairEnumerator.Create(var aArray: TArray<TPairItem>); begin fIndex := -1; fArray := @aArray; end; function TPairList.TPairEnumerator.GetCurrent : TPairItem; begin Result := TArray<TPairItem>(fArray^)[fIndex]; end; function TPairList.TPairEnumerator.MoveNext: Boolean; begin Inc(fIndex); Result := fIndex < High(TArray<TPairItem>(fArray^))+1; end; {$IFDEF MSWINDOWS} procedure ProcessMessages; var Msg: TMsg; begin while integer(PeekMessage(Msg, 0, 0, 0, PM_REMOVE)) <> 0 do begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; function GetLastOSError: String; begin Result := SysErrorMessage(Windows.GetLastError); end; {$ENDIF} function RemoveLastChar(const aText : string) : string; begin Result := aText.Remove(aText.Length - 1); end; function DateTimeToSQL(aDateTime : TDateTime) : string; begin Result := FormatDateTime('YYYY-MM-DD hh:mm:ss',aDateTime); end; function IsInteger(const aValue : string) : Boolean; var i : Integer; begin Result := TryStrToInt(aValue,i); end; function IsFloat(const aValue : string) : Boolean; var e : Extended; begin Result := TryStrToFloat(aValue,e); end; function IsBoolean(const aValue : string) : Boolean; var b : Boolean; begin Result := TryStrToBool(aValue,b); end; function ExtractStr(var vSource : string; aIndex : Integer; aCount : Integer) : string; begin if aIndex > vSource.Length then Exit(''); Result := Copy(vSource,aIndex,aCount); Delete(vSource,aIndex,aCount); end; function GetSubString(const aSource, aFirstDelimiter, aLastDelimiter : string) : string; var i : Integer; begin i := Pos(aFirstDelimiter,aSource); if i > -1 then Result := Copy(aSource, i + aFirstDelimiter.Length, Pos(aLastDelimiter, aSource, i + aFirstDelimiter.Length) - i - aFirstDelimiter.Length) else Result := ''; end; function DbQuotedStr(const str : string): string; var i : Integer; begin Result := str; for i := Result.Length - 1 downto 0 do begin if Result.Chars[i] = '"' then Result := Result.Insert(i, '"'); end; Result := '"' + Result + '"'; end; function UnDbQuotedStr(const str: string) : string; begin Result := Trim(str); if not Result.IsEmpty then begin if Result.StartsWith('"') then Result := Copy(Result, 2, Result.Length - 2); end; end; function SpQuotedStr(const str : string): string; begin Result := '''' + str + ''''; end; function UnSpQuotedStr(const str: string) : string; begin Result := Trim(str); if not Result.IsEmpty then begin if Result.StartsWith('''') then Result := Copy(Result, 2, Result.Length - 2); end; end; function UnQuotedStr(const str : string; const aQuote : Char) : string; begin if (str.Length > 0) and (str[Low(str)] = aQuote) and (str[High(str)] = aQuote) then Result := Copy(str, Low(str)+1, High(str) - 2) else Result := str; end; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : string) : string; begin if aCondition then Result := aIfIsTrue else Result := aIfIsFalse; end; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Integer) : Integer; begin if aCondition then Result := aIfIsTrue else Result := aIfIsFalse; end; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : Extended) : Extended; begin if aCondition then Result := aIfIsTrue else Result := aIfIsFalse; end; function Ifx(aCondition : Boolean; const aIfIsTrue, aIfIsFalse : TObject) : TObject; begin if aCondition then Result := aIfIsTrue else Result := aIfIsFalse; end; {$IFNDEF FPC} {$IFNDEF DELPHIXE7_UP} class procedure TArrayUtil<T>.Delete(var aArray : TArray<T>; aIndex : Integer); var n : Integer; len : Integer; begin len := Length(aArray); if (len > 0) and (aIndex < len) then begin for n := aIndex + 1 to len - 1 do aArray[n - 1] := aArray[n]; SetLength(aArray, len - 1); end; end; {$ENDIF} {$ENDIF} { TDateTimeHelper } {$IFDEF DELPHIXE7_UP} function TDateTimeHelper.ToSQLString : string; begin Result := DateTimeToSQL(Self); end; procedure TDateTimeHelper.FromNow; begin Self := Now; end; procedure TDateTimeHelper.FromUTC(const aUTCTime: TDateTime); begin Self := UTCToLocalTime(aUTCTime); end; function TDateTimeHelper.IncDay(const aValue : Cardinal = 1) : TDateTime; begin Result := System.DateUtils.IncDay(Self,aValue); end; function TDateTimeHelper.DecDay(const aValue : Cardinal = 1) : TDateTime; begin Result := System.DateUtils.IncDay(Self,-aValue); end; function TDateTimeHelper.IncMonth(const aValue : Cardinal = 1) : TDateTime; begin Result := SysUtils.IncMonth(Self,aValue); end; function TDateTimeHelper.DecMonth(const aValue : Cardinal = 1) : TDateTime; begin Result := SysUtils.IncMonth(Self,-aValue); end; function TDateTimeHelper.IncYear(const aValue : Cardinal = 1) : TDateTime; begin Result := System.DateUtils.IncYear(Self,aValue); end; function TDateTimeHelper.DecYear(const aValue : Cardinal = 1) : TDateTime; begin Result := System.DateUtils.IncYear(Self,-aValue); end; function TDateTimeHelper.IsEqualTo(const aDateTime : TDateTime) : Boolean; begin Result := Self = aDateTime; end; function TDateTimeHelper.IsAfter(const aDateTime : TDateTime) : Boolean; begin Result := Self > aDateTime; end; function TDateTimeHelper.IsBefore(const aDateTime : TDateTime) : Boolean; begin Result := Self < aDateTime; end; function TDateTimeHelper.IsSameDay(const aDateTime : TDateTime) : Boolean; begin Result := System.DateUtils.SameDate(Self,aDateTime); end; function TDateTimeHelper.IsSameTime(const aTime : TTime) : Boolean; begin Result := System.DateUtils.SameTime(Self,aTime); end; function TDateTimeHelper.DayOfTheWeek : Word; begin Result := System.DateUtils.NthDayOfWeek(Self); end; function TDateTimeHelper.ToJsonFormat : string; begin Result := DateTimeToJsonDate(Self); end; function TDateTimeHelper.ToGMTFormat : string; begin Result := DateTimeToGMT(Self); end; function TDateTimeHelper.ToTimeStamp : TTimeStamp; begin Result := DateTimeToTimeStamp(Self); end; function TDateTimeHelper.ToUTC : TDateTime; begin Result := LocalTimeToUTC(Self); end; function TDateTimeHelper.ToMilliseconds : Int64; begin {$IFDEF DELPHIRX104_ANDUP} Result := System.DateUtils.DateTimeToMilliseconds(Self); {$ELSE} Result := System.DateUtils.MilliSecondOf(Self); {$ENDIF} end; function TDateTimeHelper.ToString : string; begin Result := DateTimeToStr(Self); end; function TDateTimeHelper.Date : TDate; begin Result := System.DateUtils.DateOf(Self); end; function TDateTimeHelper.Time : TTime; begin Result := System.DateUtils.TimeOf(Self); end; function TDateTimeHelper.IsAM : Boolean; begin Result := System.DateUtils.IsAM(Self); end; function TDateTimeHelper.IsPM : Boolean; begin Result := System.DateUtils.IsPM(Self); end; { TDateHelper } function TDateHelper.ToString : string; begin Result := DateToStr(Self); end; { TTimeHelper } function TTimeHelper.ToString : string; begin Result := TimeToStr(Self); end; {$ENDIF} {$IFNDEF NEXTGEN} initialization try GetEnvironmentPaths; except {$IFDEF SHOW_ENVIRONMENTPATH_ERRORS} on E : Exception do begin if not IsService then begin if HasConsoleOutput then Writeln(Format('[WARN] GetEnvironmentPaths: %s',[E.Message])) else MessageBox(0,PWideChar(Format('Get environment path error: %s',[E.Message])),'GetEnvironmentPaths',MB_ICONEXCLAMATION); end; end; {$ENDIF} end; {$ENDIF} end.
unit fuChangeLogStatus; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvGlowButton, Vcl.ComCtrls, Vcl.StdCtrls; type TUpdateLogStatusValidation = (clSuccess,clNoChangedBy,clNoChangedDate); type TfrmChangeLogStatus = class(TForm) cbStatus: TComboBox; Label1: TLabel; eChangedBy: TEdit; Label2: TLabel; dtpChangedOn: TDateTimePicker; Label3: TLabel; AdvGlowButton1: TAdvGlowButton; procedure FormCreate(Sender: TObject); function ValidateChangeLogDataEntry : TUpdateLogStatusValidation; procedure AdvGlowButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmChangeLogStatus: TfrmChangeLogStatus; implementation {$R *.dfm} procedure TfrmChangeLogStatus.AdvGlowButton1Click(Sender: TObject); begin if ValidateChangeLogDataEntry = clSuccess then ModalResult:= mrOK else MessageDlg('Please complete all fields before submitting the changes to the log status.',mtInformation,[mbOK],0); end; procedure TfrmChangeLogStatus.FormCreate(Sender: TObject); begin dtpCHangedOn.DateTime:= Now; end; function TfrmChangeLogStatus.ValidateChangeLogDataEntry : TUpdateLogStatusValidation; begin Result:= clSuccess; if (Result = clSuccess) and (eChangedBy.Text = '') then Result:= clNoChangedBy; end; end.
unit setStringEx; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, setForm, Vcl.StdCtrls, parser, Vcl.Imaging.pngimage, Vcl.ExtCtrls; type TfrmStringEx = class(TfrmSetSimple) edtMin: TEdit; lbl4: TLabel; edtMax: TEdit; lbl5: TLabel; procedure btnSaveClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure Init (S : TSimpleObject; OnCheckName : TOnCheckName; OnOk, OnCancel : TNotifyEvent); override; end; var frmStringEx: TfrmStringEx; implementation {$R *.dfm} procedure TfrmStringEx.btnSaveClick(Sender: TObject); var i : integer; eMin, eMax : Integer; begin inherited; // Проверка на валидность eMin := StrToIntDef (edtMin.Text, 0); edtMin.Text := IntToStr(eMin); eMax := StrToIntDef (edtMax.Text, 100); edtMax.Text := IntToStr(eMax); if eMin >= eMax then begin Application.MessageBox('Граничные значения указаны не верно. Min >= Max', PChar(Application.Title), MB_OK + MB_ICONSTOP); edtMax.Clear; edtMax.SetFocus; Exit; end; FS.Arguments[1] := edtMin.Text; FS.Arguments[2] := edtMax.Text; end; procedure TfrmStringEx.Init(S: TSimpleObject; OnCheckName: TOnCheckName; OnOk, OnCancel: TNotifyEvent); begin inherited; edtMin.Text := FS.Arguments[1]; edtMax.Text := FS.Arguments[2]; end; end.
unit centroCostos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, Provider, DBClient, ImgList, ActnList, StdCtrls, Grids, Wwdbigrd, Wwdbgrid, Buttons, JvFooter, ExtCtrls, JvExExtCtrls, JvExtComponent, JvCaptionPanel, wwdblook; type TFCentroCostos = class(TForm) pnl: TJvCaptionPanel; JvFooter1: TJvFooter; btnOK: TBitBtn; btnAnu: TBitBtn; btnNue: TBitBtn; grilla: TwwDBGrid; Label1: TLabel; lblTotal: TLabel; ac: TActionList; ImageList1: TImageList; cds: TClientDataSet; ds: TDataSource; cdsCUENTA: TStringField; cdsOT: TIntegerField; cdsIMPORTE: TFloatField; cdsOBSERVACION: TStringField; LookOT: TwwDBLookupCombo; dsOT: TDataSource; acOK: TAction; acAnular: TAction; acNuevo: TAction; cdsTOTAL: TAggregateField; procedure FormCreate(Sender: TObject); procedure acOKExecute(Sender: TObject); procedure acAnularExecute(Sender: TObject); procedure acNuevoExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cdsNewRecord(DataSet: TDataSet); procedure cdsBeforePost(DataSet: TDataSet); private { Private declarations } FTotal: Double; FVieCuenta, FVieObserva: string; permitirInsertar: Boolean; function verificarTotal: Boolean; public { Public declarations } procedure setTotal( importe: double ); end; var FCentroCostos: TFCentroCostos; implementation uses DM; {$R *.dfm} procedure TFCentroCostos.acAnularExecute(Sender: TObject); begin if MessageDlg( 'Confirma anulacion de imputaciones?', mtWarning, mbYesNo, 0 ) <> mrYes then SysUtils.Abort; ModalResult := mrCancel; end; procedure TFCentroCostos.acNuevoExecute(Sender: TObject); begin ShowMessage('Por favor, ingrese la OT desde el módulo de gestión de presupuestos y pedidos' ); end; procedure TFCentroCostos.acOKExecute(Sender: TObject); begin if (MessageDlg( 'Confirma apropiacion de costos?', mtConfirmation, mbYesNo, 0 ) <> mrYes) then Abort else if (VerificarTotal) then ModalResult := mrOk else raise Exception.Create('Importe total imputado no corresponde con valor de comprobante'); end; procedure TFCentroCostos.cdsBeforePost(DataSet: TDataSet); begin FVieCuenta := cdsCUENTA.Value; FVieObserva := cdsOBSERVACION.Value; if (cdsOT.Value = 0) and (ActiveControl=grilla) then ShowMessage('Atencion! Imputado a centro generico de costos' ); end; procedure TFCentroCostos.cdsNewRecord(DataSet: TDataSet); begin // if not PermitirInsertar then // raise Exception.Create('No se puede ingresar nueva cuenta'); cdsCUENTA.Value := FVieCuenta; cdsOBSERVACION.Value := FVieObserva; end; procedure TFCentroCostos.FormClose(Sender: TObject; var Action: TCloseAction); begin DMod.qselOT.Close; end; procedure TFCentroCostos.FormCreate(Sender: TObject); begin cds.CreateDataSet; DMod.qselOT.Open; end; procedure TFCentroCostos.setTotal(importe: double); begin FTotal := Round( importe*100 )/100; lblTotal.Caption := Format( '%14.2f', [ FTotal ]); end; function TFCentroCostos.verificarTotal: Boolean; var total, origen: integer; begin try Result := True; total := Round(cdsTOTAL.Value*100); origen := Round(FTotal*100); if ( total <> Origen ) then Result := False; except Result := False; end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DdhAppX, Menus, IniFiles, Misc, ShellAPI, ExtCtrls; type TProgramController=class; TFrmMain = class(TForm) AppExt: TDdhAppExt; TrayPopupMenu: TPopupMenu; pmiDDSClose: TMenuItem; pmiLine1: TMenuItem; Timer: TTimer; pmiReboot: TMenuItem; pmiShutdown: TMenuItem; procedure pmiCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure pmiProgramClick(Sender: TObject); procedure AppExtLBtnDown(Sender: TObject); procedure CloseProgs; procedure pmiShutdownClick(Sender: TObject); procedure pmiRebootClick(Sender: TObject); procedure pmiLogoffClick(Sender: TObject); private function Get_Progs(i: Integer): TProgramController; public { Public declarations } Ini:TIniFile; FProgs:TList; property Progs[i:Integer]:TProgramController read Get_Progs; end; TProgramController=class(TObject) mi:TMenuItem; AppName,CmdLine,CurDir:String; CreationFlags:Cardinal; SI:TStartupInfo; PI:TProcessInformation; Valid:Boolean; constructor CreateFromIniSection(Ini:TIniFile; const Section:String); procedure SupportProcessActivity; function StartProcess:Boolean; procedure CloseHandles; procedure QuitProcess; procedure RestoreMainWindow; function ProcessStillActive:Boolean; destructor Destroy;override; end; var FrmMain: TFrmMain; implementation {$R *.DFM} function enumShowWindows(hwnd:THandle; CmdShow:Cardinal):Boolean;stdcall; begin if IsWindow(hwnd) and IsWindowVisible(hwnd) then begin ShowWindowAsync(hwnd,CmdShow); SetActiveWindow(hwnd); Result:=False; end else Result:=True; end; procedure ShowThdWindows(ThdId:Cardinal; CmdShow:Cardinal); begin EnumThreadWindows(ThdId,@enumShowWindows,CmdShow); end; procedure TFrmMain.pmiCloseClick(Sender: TObject); begin Close; end; procedure TFrmMain.FormCreate(Sender: TObject); const Config='Config'; TPSize=16384; type PDWORD=^DWORD; PTokenPrivileges=^_TOKEN_PRIVILEGES; var SL:TStringList; i:Integer; PC:TProgramController; FName:String; PTH:THandle; TP:^_TOKEN_PRIVILEGES; j:Cardinal; begin { if ParamCount=0 then FName:=GetModuleFullName+'.ini' else FName:=ExpandFileName(ParamStr(1)); } FName:=GetModuleFullName+'.ini'; Ini:=TIniFile.Create(FName); FProgs:=TList.Create; SL:=TStringList.Create; try Ini.ReadSections(SL); for i:=0 to SL.Count-1 do begin PC:=TProgramController.CreateFromIniSection(Ini,SL[i]); if PC.Valid then begin FProgs.Add(PC); PC.mi.OnClick:=pmiProgramClick; TrayPopupMenu.Items.Insert(0,PC.mi); end else PC.Free; end; except Halt(1); end; SL.Free; GetMem(TP,TPSize); try FillChar(TP^,TPSize,0); if not OpenProcessToken(GetCurrentProcess,TOKEN_ALL_ACCESS,PTH) then// LastErrorMsg(FALSE) else begin TP^.PrivilegeCount:=1; if not LookupPrivilegeValue('','SeShutdownPrivilege',TP^.Privileges[0].Luid) then// LastErrorMsg(FALSE) else begin TP^.Privileges[0].Attributes:=SE_PRIVILEGE_ENABLED; if not AdjustTokenPrivileges(PTH,False,TP^,0,PTokenPrivileges(nil)^,PDWORD(nil)^) then// LastErrorMsg(FALSE) else begin FillChar(TP^,TPSize,0); if not GetTokenInformation(PTH,TokenPrivileges,TP,TPSize,j) then// LastErrorMsg(FALSE); end; end; end; finally FreeMem(TP,TPSize); end; end; function TFrmMain.Get_Progs(i: Integer): TProgramController; begin Result:=FProgs[i]; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin CloseProgs; end; procedure TFrmMain.TimerTimer(Sender: TObject); var i:Integer; begin if FProgs=nil then exit; for i:=0 to FProgs.Count-1 do Progs[i].SupportProcessActivity; end; procedure TFrmMain.pmiProgramClick(Sender: TObject); var i:Integer; begin for i:=0 to FProgs.Count-1 do begin if Progs[i].mi=Sender then begin Progs[i].RestoreMainWindow; break; end; end; end; procedure TFrmMain.AppExtLBtnDown(Sender: TObject); var P:TPoint; begin GetCursorPos(P); TrayPopupMenu.Popup(P.x,P.y); end; procedure TFrmMain.CloseProgs; var i:Integer; begin for i:=0 to FProgs.Count-1 do Progs[i].Free; FProgs.Count:=0; end; { TProgramController } procedure TProgramController.CloseHandles; begin CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; constructor TProgramController.CreateFromIniSection(Ini: TIniFile; const Section: String); function GetShowCmd(SCStr:String):Cardinal; begin SCStr:=UpperCase(Trim(SCStr)); if SCStr='MAX' then Result:=SW_SHOWMAXIMIZED else if SCStr='MIN' then Result:=SW_SHOWMINNOACTIVE else Result:=SW_SHOWNORMAL; end; function GetPriority(PrStr:String):Cardinal; begin PrStr:=UpperCase(Trim(PrStr)); if PrStr='IDLE' then Result:=IDLE_PRIORITY_CLASS else if PrStr='HIGH' then Result:=HIGH_PRIORITY_CLASS else if PrStr='REALTIME' then Result:=REALTIME_PRIORITY_CLASS else Result:=NORMAL_PRIORITY_CLASS; // if PrStr='NORMAL' end; var Icon:TIcon; IconFile:String; begin inherited Create; FillChar(SI,SizeOf(SI),0); SI.cb:=SizeOf(SI); SI.dwFlags:=STARTF_USESHOWWINDOW; SI.wShowWindow:=GetShowCmd(Ini.ReadString(Section,'ShowCmd','')); AppName:=ExpandFileName(Ini.ReadString(Section,'AppName','')); CmdLine:=Ini.ReadString(Section,'CmdLine',''); CurDir:=ExpandFileName(Ini.ReadString(Section,'CurDir','')); CreationFlags:=GetPriority(Ini.ReadString(Section,'Priority','')); if StartProcess then begin mi:=TMenuItem.Create(nil); mi.Caption:=Ini.ReadString(Section,'Caption','empty caption'); mi.Bitmap.PixelFormat:=pf8bit; mi.Bitmap.Width:=32; mi.Bitmap.Height:=32; Icon:=TIcon.Create; try try IconFile:=ExpandFileName(Ini.ReadString(Section,'IconFile',AppName)); Icon.Handle:=ExtractIcon(HInstance,PChar(Iconfile),0); mi.Bitmap.Canvas.Draw(0,0,Icon); finally Icon.Free; end; except end; Valid:=True; end else Valid:=False; end; destructor TProgramController.Destroy; begin QuitProcess; CloseHandles; mi.Free; inherited; end; procedure TProgramController.SupportProcessActivity; begin if ProcessStillActive then exit; CloseHandles; StartProcess; end; function TProgramController.ProcessStillActive: Boolean; var ExitCode:Cardinal; begin ExitCode:=0; GetExitCodeProcess(PI.hProcess,ExitCode); Result:=(ExitCode=STILL_ACTIVE); end; procedure TProgramController.QuitProcess; begin PostThreadMessage(PI.dwThreadId,WM_QUIT,0,0); end; function TProgramController.StartProcess: Boolean; begin Result:=CreateProcess( PChar(AppName),PChar(CmdLine),nil,nil,False,CreationFlags,nil,PChar(CurDir),SI,PI ); end; procedure TProgramController.RestoreMainWindow; begin // ShowThdWindows(PI.dwThreadId,SW_SHOWNORMAL); PostThreadMessage(PI.dwThreadId,WM_ACTIVATEAPP,Cardinal(True),PI.dwThreadId); end; procedure TFrmMain.pmiShutdownClick(Sender: TObject); begin CloseProgs; ExitWindowsEx(EWX_SHUTDOWN,0); Close; end; procedure TFrmMain.pmiRebootClick(Sender: TObject); begin CloseProgs; ExitWindowsEx(EWX_REBOOT,0); Close; end; procedure TFrmMain.pmiLogoffClick(Sender: TObject); begin CloseProgs; ExitWindowsEx(EWX_LOGOFF,0); Close; end; end.
unit PackStrings; interface function IsPacked(const str : WideString) : boolean; function PackStr(const str : string) : WideString; function UnpackStr(const str : WideString) : string; implementation function IsPacked(const str : WideString) : boolean; begin result := (length(str) > 0) and (pchar(str)[1] <> #0); end; function PackStr(const str : string) : WideString; var aux : pchar absolute result; len : integer; i : integer; begin len := length(str); if len <> 0 then begin if len and 1 <> 0 then SetLength(result, len div 2 + 1) else SetLength(result, len div 2); for i := 0 to pred(length(str)) do aux[i] := pchar(str)[i]; aux[length(str)] := #0; end else result := ''; end; function UnpackStr(const str : WideString) : string; begin result := pchar(str); end; end.
unit TableCreator; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBISAMTb, TableManDbIsam, TTSRptRunTable, DBISAMTableAU, TTSLNOTTable, TTSLENDTable, TTSNMSRTable, TTSACOLTable, TTSLOANTable, TTSGUARTable, comctrls, stdCtrls, DaapiTypes, FFSUtils, TicklerTypes; type TBaseList = (blNone, blTrak, blColl, blOfcr, blBrch, blDivi); TdmTableCreator = class(TDataModule) wintick: TDBISAMDatabase; WinTickReport: TDBISAMDatabase; GenTag: TDBISAMTable; TickReports: TDBISAMDatabase; procedure dmTableCreatorCreate(Sender: TObject); procedure dmTableCreatorDestroy(Sender: TObject); private mpbar : TProgressbar; msbar : TLabel; procedure StatusOff; procedure StatusOn(pbar: TProgressbar; sbar: TLabel); procedure StatusUpdate(position: integer; lbl: string); private { Private declarations } public { Public declarations } // report tables procedure InitializeDatabase; function GetLTName(index: TLenderTables;ALenderNumber:string): string; function LongDateText(s:string):string; function RptFileName(rtype:TTicklerReport;RptID:integer):string; procedure RemoveTagTables(RptID:integer); end; procedure OpenDS(tbl:TDBIsamTable;lt:TLenderTables;ALenderNumber:string); procedure OpenRS(tbl:TDbISamTableAU;rt:TReportTables;RptID:integer); procedure CloseRS(tbl:TDbIsamTableAU); procedure CloseDS(tbl:TDbIsamTable); function FormatZip(z:string):string; function LendOpt(s:string;i:integer):boolean; const onetwo : array[boolean] of integer = (2,1); tabColors : array[boolean] of TColor = (clBlack,clBlue); TTickRptTitle : array[TTicklerReport] of string = ('NONE','MONITORED LOAN REPORT', //tickNone, tickMonitor 'CUSTOMER LABELS','EXCEPTION REPORT', //tickCustLabel, tickException, 'NOTICE PRINT','PURGED LOANS', //tickNoticePrint, tickPurge, 'EXPORTED LOANS','EXCEPTION RECAP', //tickExport, tickELRecap, 'EXCEPTION DATA','TRANSACTION SUMMARY', //tickELData, tickTranSum, 'LOAN INFORMATION','REPORT COVER PAGE'); //tickLoanData, tickCover LColor : array[boolean] of TColor = (clRed, clNavy); LLabel : array[boolean] of string = ('ALL','SET'); HLColor : array[boolean] of TColor = (clBlack,clBlue); HLSize : array[boolean] of integer = (8,10); poColor : array[boolean] of TColor = (clBlack,clRed); poBkgnd : array[boolean] of TColor = (clBlack,clWindow); resourcestring // constants for date field values other than a date sdtCont = 'CONT.'; sdtWaived = 'WAIVED'; sdtHistory = 'HISTORY'; sdtNA = 'N/A'; sdtSatisfied = 'SATISF''D'; // constants for List selections conUnlist = ' <UNLISTED>'; conBlank = ' <BLANK>'; // conBySelected = 'BySelected'; // message box captions mbcInformation = 'Information'; mbcConfirmation = 'Confirmation'; mbcIncomplete = 'Incomplete Entry'; var dmTableCreator: TdmTableCreator; implementation uses WinTickReg, filectrl, NoticeUp, DataCentral, TTSDirectDaapi, TicklerGlobals; {$R *.DFM} { TdmTableCreator } function LendOpt(s:string;i:integer):boolean; begin if length(s) >= i then result := s[i] = 'Y' else result := false; end; procedure OpenDS(tbl:TDBIsamTable;lt:TLenderTables;ALenderNumber:string); begin tbl.TableName := dmTableCreator.GetLTName(lt, ALenderNumber); tbl.Active := true; end; procedure CloseDS(tbl:TDbIsamTable); begin if tbl.Active then tbl.Active := false; end; procedure OpenRS(tbl:TDbISamTableAU;rt:TReportTables;RptID:integer); var s : string; begin s := IntToBase26(RptID); tbl.TableName := RtNameList[rt] + s; if not tbl.Exists then tbl.MakeTable(true); tbl.Active := true; end; procedure CloseRS(tbl:TDbIsamTableAU); begin tbl.active := false; end; procedure TdmTableCreator.RemoveTagTables(RptID:integer); var rt : TReportTables; begin for rt := low(TReportTables) to high(TReportTables) do begin if rt <> rtNoticeTag then begin GenTag.TableName := RTNameList[rt] + intToBase26(RptID); if GenTag.Exists then GenTag.DeleteTable; end; end; end; procedure TdmTableCreator.InitializeDatabase; var s : array[0..255] of char; p : string; begin getTempPath(255,s); p := strpas(s); if copy(p,length(p),1) <> '\' then p := p + '\'; // primary data wintick.connected := false; wintick.Directory := dmWinTickReg.Specs.DirData; wintick.connected := true; // reports winTickReport.connected := false; winTickReport.Directory := p; wintickReport.connected := true; TickReports.Connected := false; TickReports.Directory := dmWinTickReg.Specs.DirReports; TickReports.Connected := true; // create the Daapi if assigned(Daapi) then begin Daapi.Free; Daapi := nil; end; Daapi := TTTSDirectDaapi.create(nil, dmWinTickReg.Specs.DirData); end; procedure TdmTableCreator.dmTableCreatorCreate(Sender: TObject); begin GlobalZoom := 2; // 25% end; function TdmTableCreator.GetLTName(index: TLenderTables;ALenderNumber:string): string; begin result := LTNameList[index] + ALenderNumber; end; function TdmTableCreator.LongDateText(s: string): string; begin result := s; if s > '' then begin case s[1] of 'S' : result := sdtSatisfied; 'W' : result := sdtWaived; 'C' : result := sdtCont; 'N' : result := sdtNA; 'H' : result := sdtHistory; end; end; end; function TdmTableCreator.RptFileName(rtype: TTicklerReport;RptID:integer): string; var s : string; begin s := IntToBase26(RptID); result := dmWintickReg.Specs.DirReports + s + '.' + TTickRptCat[rtype]; end; procedure TdmTableCreator.dmTableCreatorDestroy(Sender: TObject); begin Daapi.Free; end; function FormatZip(z:string):string; var s : string; p : integer; begin s := z; if length(s) > 5 then begin if length(s) = 6 then s := copy(s,1,5) else begin p := pos('-',s); if (p > 0) and (p <> 6) then delete(s,p,1); p := pos('-',s); if p = 0 then insert('-',s,6); end; end; result := s; end; procedure TdmTableCreator.StatusOn(pbar:TProgressbar;sbar:TLabel); begin mpbar := pbar; if mpbar <> nil then begin mpbar.Position := 0; mpbar.visible := true; mpbar.update; end; msbar := sbar; if msbar <> nil then begin msbar.caption := ''; msbar.visible := true; msbar.update; end; end; procedure TdmTableCreator.StatusUpdate(position:integer;lbl:string); begin if (mpbar <> nil) and (position >= 0) then begin mpbar.position := position; mpbar.update; end; if (msbar <> nil) and (lbl > '') then begin msbar.caption := lbl; msbar.update; end; end; procedure TdmTableCreator.StatusOff; begin if mpbar <> nil then begin mpbar.visible := false; mpbar.update; end; if msbar <> nil then begin msbar.visible := false; msbar.update; end; end; end.
unit TcpDealAgent; interface uses Windows, BaseWinProcess, define_ctp_deal; type TTcpAgentDealConsoleData = record IsDealConnected: Boolean; IsDealLogined: Boolean; IsSettlementConfirmed: Boolean; SrvWND: HWND; TCPAgentDealProcess: TOwnProcess; //====================================== Index: Integer; DealArray: array[0..300 - 1] of TDeal; LastRequestDeal: PDeal; //====================================== TradingAccount: TTradingAccount; InvestorPositionCache: TInvestorPositionCache; // ------------------------------- InputOrderCache: TInputOrderCache; InputOrderActionCache: TInputOrderActionCache; OrderCache: TOrderCache; TradeCache: TTradeCache; end; TDealConsole = class protected fTcpAgentDealConsoleData: TTcpAgentDealConsoleData; public constructor Create; virtual; destructor Destroy; override; //====================================== function FindSrvWindow: Boolean; procedure StartAgentProcess; //====================================== // 初始化过程 procedure InitDeal; procedure ConnectDeal(Addr: AnsiString); procedure LoginDeal(ABrokerId, Account, APassword: AnsiString); procedure ChangeDealPwd(AOldPwd, ANewPwd: AnsiString); procedure ConfirmSettlementInfo; procedure QueryMoney; procedure QueryUserHold(AInstrumentId: AnsiString); //================================ function CheckOutDeal: PDeal; procedure RunDeal(ADeal: PDeal); procedure CancelDeal(ADeal: PDeal); function CheckOutOrderRequest(ADeal: PDeal): PDealOrderRequest; function CheckOutOrderResponse(ADeal: PDeal): PDealOrderResponse; function CheckOutOrderDeal(ADeal: PDeal): PDealResponse; //================================ function FindDealByRequestId(ARequestId: Integer): PDeal; function FindDealByOrderSysId(AOrderSysId: AnsiString): PDeal; function FindDealByBrokerOrderSeq(ABrokerOrderSeq: Integer): PDeal; //================================ function GetOrderItem(AIndex: integer): POrder; function GetInputOrderItem(AIndex: integer): PInputOrder; function GetInputOrderActionItem(AIndex: integer): PInputOrderAction; function GetTradeItem(AIndex: Integer): PTrade; public function CheckOutOrder: POrder; property OrderCount: integer read fTcpAgentDealConsoleData.OrderCache.Count; property OrderItem[AIndex: integer]: POrder read GetOrderItem; //----------------------------------------------- public function CheckOutInputOrder: PInputOrder; property InputOrderItem[AIndex: integer]: PInputOrder read GetInputOrderItem; //----------------------------------------------- public function CheckOutInputOrderAction: PInputOrderAction; property InputOrderActionItem[AIndex: integer]: PInputOrderAction read GetInputOrderActionItem; //----------------------------------------------- public function CheckOutTrade: PTrade; property TradeItem[AIndex: Integer]: PTrade read GetTradeItem; //----------------------------------------------- public function CheckOutInvestorPosition(AInstrumentId: AnsiString): PInvestorPosition; public property TradingAccount: TTradingAccount read fTcpAgentDealConsoleData.TradingAccount write fTcpAgentDealConsoleData.TradingAccount; property SrvWND: HWND read fTcpAgentDealConsoleData.SrvWND; property IsDealConnected: Boolean read fTcpAgentDealConsoleData.IsDealConnected write fTcpAgentDealConsoleData.IsDealConnected; property IsDealLogined: Boolean read fTcpAgentDealConsoleData.IsDealLogined write fTcpAgentDealConsoleData.IsDealLogined; property IsSettlementConfirmed: Boolean read fTcpAgentDealConsoleData.IsSettlementConfirmed write fTcpAgentDealConsoleData.IsSettlementConfirmed; end; implementation uses Messages, Sysutils, UtilsApplication, TcpAgentConsole, define_app_msg; { TDealConsole } constructor TDealConsole.Create; begin FillChar(fTcpAgentDealConsoleData, SizeOf(fTcpAgentDealConsoleData), 0); end; destructor TDealConsole.Destroy; begin inherited; end; function TDealConsole.FindSrvWindow: Boolean; begin if 0 <> fTcpAgentDealConsoleData.SrvWND then begin if not IsWindow(fTcpAgentDealConsoleData.SrvWND) then begin fTcpAgentDealConsoleData.SrvWND := 0; end else begin Result := true; exit; end; end; fTcpAgentDealConsoleData.SrvWND := FindWindow('Tftdc_api_srv', 'tcpagent'); Result := (fTcpAgentDealConsoleData.SrvWND <> 0) and (fTcpAgentDealConsoleData.SrvWND <> INVALID_HANDLE_VALUE); end; procedure TDealConsole.StartAgentProcess; var tmpProcessFileUrl: AnsiString; begin if not FindSrvWindow then begin //CloseExProcess(@fTcpAgentConsoleData.TCPAgentProcess); //fTcpAgentConsoleData.TCPAgentProcess.FilePath := ExtractFilePath(ParamStr(0)); //fTcpAgentConsoleData.TCPAgentProcess.FileUrl := fTcpAgentConsoleData.TCPAgentProcess.FilePath + 'tcpagent.exe'; tmpProcessFileUrl := ExtractFilePath(ParamStr(0)) + 'tcpagent.exe'; if FileExists(tmpProcessFileUrl) then begin RunProcessA(@fTcpAgentDealConsoleData.TCPAgentDealProcess, tmpProcessFileUrl, nil); end; //RunExProcess(@fTcpAgentConsoleData.TCPAgentProcess); end; SleepWait(200); end; procedure TDealConsole.InitDeal; begin if not FindSrvWindow then begin StartAgentProcess(); SleepWait(200); end; if FindSrvWindow then begin SleepWait(50); PostMessage(fTcpAgentDealConsoleData.SrvWND, WM_C2S_Deal_RequestInitialize, 0, 0); end; end; procedure TDealConsole.ConnectDeal(Addr: AnsiString); var tmpCopyData: TCopyDataCommand; begin if FindSrvWindow then begin //PostMessage(SrvWND, WM_C2S_RequestConnectFront, 0, 0); FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_Deal_RequestConnectFront; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @Addr[1], Length(Addr)); SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; procedure TDealConsole.LoginDeal(ABrokerId, Account, APassword: AnsiString); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if FindSrvWindow then begin //PostMessage(SrvWND, WM_C2S_RequestUserLogin, 0, 0); FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_Deal_RequestUserLogin; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; tmpAnsi := ABrokerId; //G_BrokerId := tmpAnsi; CopyMemory(@tmpCopyData.CommonCommand.scmd3[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := Account; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := APassword; CopyMemory(@tmpCopyData.CommonCommand.scmd2[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.CommonCommand.icmd1 := GTcpAgentConsole.CheckOutRequestId; SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); SleepWait(500); end; end; procedure TDealConsole.ConfirmSettlementInfo; begin if FindSrvWindow then begin SendMessage(SrvWND, WM_C2S_RequestSettlementInfoConfirm, GTcpAgentConsole.CheckOutRequestId, 0); end; end; procedure TDealConsole.ChangeDealPwd(AOldPwd, ANewPwd: AnsiString); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if FindSrvWindow then begin FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_Deal_RequestChangeDealPwd; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; tmpAnsi := AOldPwd; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := ANewPwd; CopyMemory(@tmpCopyData.CommonCommand.scmd2[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.CommonCommand.icmd1 := GTcpAgentConsole.CheckOutRequestId; SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; procedure TDealConsole.QueryUserHold(AInstrumentId: AnsiString); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if AInstrumentId = '' then exit; if FindSrvWindow then begin FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.Base.dwData := WM_C2S_RequestQueryHold; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; tmpAnsi := AInstrumentId; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.CommonCommand.icmd1 := GTcpAgentConsole.CheckOutRequestId; SendMessage(SrvWND, WM_COPYDATA,0, LongWord(@tmpCopyData)); end; end; procedure TDealConsole.QueryMoney; begin if FindSrvWindow then begin SendMessage(SrvWND, WM_C2S_RequestQueryMoney, GTcpAgentConsole.CheckOutRequestId, 0); end; end; function TDealConsole.CheckOutDeal: PDeal; begin // Result := System.New(PDeal); // FillChar(Result^, SizeOf(TDeal), 0); Result := @fTcpAgentDealConsoleData.DealArray[fTcpAgentDealConsoleData.Index]; Inc(fTcpAgentDealConsoleData.Index); end; procedure TDealConsole.RunDeal(ADeal: PDeal); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if ADeal = nil then exit; if ADeal.Status = deal_Invalid then ADeal.Status := deal_Open; fTcpAgentDealConsoleData.LastRequestDeal := ADeal; ADeal.OrderRequest.RequestId := GTcpAgentConsole.CheckOutRequestId; if ADeal.OrderRequest.Price > 0 then begin if ADeal.OrderRequest.Num > 0 then begin FillChar(tmpCopyData, SizeOf(tmpCopyData), 0); tmpCopyData.CommonCommand.fcmd1 := ADeal.OrderRequest.Price;// StrToFloatDef(edtPrice.text, 0); tmpCopyData.CommonCommand.icmd2 := ADeal.OrderRequest.Num;//StrToIntDef(edtNum.text, 0); if ADeal.OrderRequest.Direction = directionBuy then tmpCopyData.CommonCommand.icmd1 := 0;//StrToInt(THOST_FTDC_D_Buy); // 买 if ADeal.OrderRequest.Direction = directionSale then tmpCopyData.CommonCommand.icmd1 := 1;// StrToInt(THOST_FTDC_D_Sell); // 卖 if ADeal.OrderRequest.Mode = modeOpen then tmpCopyData.CommonCommand.icmd3 := 0;//StrToInt(THOST_FTDC_OF_Open); // 开仓 if ADeal.OrderRequest.Mode = modeCloseOut then tmpCopyData.CommonCommand.icmd3 := 1;//StrToInt(THOST_FTDC_OF_Close); // 平仓 if ADeal.OrderRequest.Mode = modeCloseNow then tmpCopyData.CommonCommand.icmd3 := 3;//StrToInt(THOST_FTDC_OF_CloseToday); // 平仓 tmpCopyData.CommonCommand.icmd4 := ADeal.OrderRequest.RequestId; //tmpAnsi := G_BrokerId; //CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := Trim(ADeal.OrderRequest.InstrumentID); CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.Base.dwData := WM_C2S_RequestOrder; tmpCopyData.Base.cbData := SizeOf(tmpCopyData.CommonCommand); tmpCopyData.Base.lpData := @tmpCopyData.CommonCommand; SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; end; procedure TDealConsole.CancelDeal(ADeal: PDeal); var tmpCopyData: TCopyDataCommand; tmpAnsi: AnsiString; begin if ADeal.CancelRequest = nil then begin ADeal.CancelRequest := System.New(PDealCancelRequest); FillChar(ADeal.CancelRequest^, SizeOf(TDealCancelRequest), 0); tmpCopyData.CommonCommand.icmd1 := ADeal.BrokerOrderSeq; tmpCopyData.CommonCommand.icmd2 := GTcpAgentConsole.CheckOutRequestId; tmpAnsi := ADeal.ExchangeID; CopyMemory(@tmpCopyData.CommonCommand.scmd1[0], @tmpAnsi[1], Length(tmpAnsi)); tmpAnsi := ADeal.OrderSysID; CopyMemory(@tmpCopyData.CommonCommand.scmd2[0], @tmpAnsi[1], Length(tmpAnsi)); tmpCopyData.Base.dwData := WM_C2S_RequestCancelOrder; SendMessage(SrvWND, WM_COPYDATA, 0, LongWord(@tmpCopyData)); end; end; function TDealConsole.CheckOutOrderRequest(ADeal: PDeal): PDealOrderRequest; begin Result := @ADeal.OrderRequest; end; function TDealConsole.CheckOutOrderResponse(ADeal: PDeal): PDealOrderResponse; begin Result := ADeal.OrderResponse; if Result = nil then begin Result := System.New(PDealOrderResponse); FillChar(Result^, SizeOf(TDealOrderResponse), 0); ADeal.OrderResponse := Result; end; end; function TDealConsole.CheckOutOrderDeal(ADeal: PDeal): PDealResponse; begin Result := ADeal.Deal; if Result = nil then begin Result := System.New(PDealResponse); FillChar(Result^, SizeOf(TDealResponse), 0); ADeal.Deal := Result; end; end; function TDealConsole.FindDealByOrderSysId(AOrderSysId: AnsiString): PDeal; var i: integer; begin Result := nil; for i := 0 to fTcpAgentDealConsoleData.Index - 1 do begin if fTcpAgentDealConsoleData.DealArray[i].Status <> deal_Invalid then begin if fTcpAgentDealConsoleData.DealArray[i].OrderSysID = AOrderSysId then begin Result := @fTcpAgentDealConsoleData.DealArray[i]; Break; end; end; end; end; function TDealConsole.FindDealByBrokerOrderSeq(ABrokerOrderSeq: Integer): PDeal; var i: integer; begin Result := nil; if ABrokerOrderSeq = 0 then exit; for i := fTcpAgentDealConsoleData.Index - 1 downto 0 do begin if fTcpAgentDealConsoleData.DealArray[i].Status <> deal_Invalid then begin if fTcpAgentDealConsoleData.DealArray[i].BrokerOrderSeq = ABrokerOrderSeq then begin Result := @fTcpAgentDealConsoleData.DealArray[i]; Break; end; end; end; end; function TDealConsole.FindDealByRequestId(ARequestId: Integer): PDeal; var i: integer; begin Result := nil; if ARequestId = 0 then exit; for i := 0 to fTcpAgentDealConsoleData.Index - 1 do begin if fTcpAgentDealConsoleData.DealArray[i].Status <> deal_Invalid then begin if fTcpAgentDealConsoleData.DealArray[i].OrderRequest.RequestId = ARequestId then begin Result := @fTcpAgentDealConsoleData.DealArray[i]; Break; end; end; end; end; function TDealConsole.CheckOutOrder: POrder; begin Result := nil; if fTcpAgentDealConsoleData.OrderCache.OrderArray[fTcpAgentDealConsoleData.OrderCache.Count] = nil then begin Result := System.New(POrder); FillChar(Result^, SizeOf(TOrder), 0); fTcpAgentDealConsoleData.OrderCache.OrderArray[fTcpAgentDealConsoleData.OrderCache.Count] := Result; Inc(fTcpAgentDealConsoleData.OrderCache.Count); end; end; function TDealConsole.GetOrderItem(AIndex: integer): POrder; begin Result := fTcpAgentDealConsoleData.OrderCache.OrderArray[AIndex]; end; function TDealConsole.CheckOutInputOrder: PInputOrder; begin Result := nil; if fTcpAgentDealConsoleData.InputOrderCache.InputOrderArray[fTcpAgentDealConsoleData.InputOrderCache.Count] = nil then begin Result := System.New(PInputOrder); FillChar(Result^, SizeOf(TInputOrder), 0); fTcpAgentDealConsoleData.InputOrderCache.InputOrderArray[fTcpAgentDealConsoleData.InputOrderCache.Count] := Result; Inc(fTcpAgentDealConsoleData.InputOrderCache.Count); end; end; function TDealConsole.GetInputOrderItem(AIndex: integer): PInputOrder; begin Result := fTcpAgentDealConsoleData.InputOrderCache.InputOrderArray[AIndex]; end; function TDealConsole.CheckOutInputOrderAction: PInputOrderAction; begin Result := nil; if fTcpAgentDealConsoleData.InputOrderActionCache.InputOrderActionArray[fTcpAgentDealConsoleData.InputOrderActionCache.Count] = nil then begin Result := System.New(PInputOrderAction); FillChar(Result^, SizeOf(TInputOrderAction), 0); fTcpAgentDealConsoleData.InputOrderActionCache.InputOrderActionArray[fTcpAgentDealConsoleData.InputOrderActionCache.Count] := Result; Inc(fTcpAgentDealConsoleData.InputOrderActionCache.Count); end; end; function TDealConsole.GetInputOrderActionItem(AIndex: integer): PInputOrderAction; begin Result := fTcpAgentDealConsoleData.InputOrderActionCache.InputOrderActionArray[AIndex]; end; function TDealConsole.CheckOutTrade: PTrade; begin Result := nil; if fTcpAgentDealConsoleData.TradeCache.TradeArray[fTcpAgentDealConsoleData.TradeCache.Count] = nil then begin Result := System.New(PTrade); FillChar(Result^, SizeOf(TTrade), 0); fTcpAgentDealConsoleData.TradeCache.TradeArray[fTcpAgentDealConsoleData.TradeCache.Count] := Result; Inc(fTcpAgentDealConsoleData.TradeCache.Count); end; end; function TDealConsole.GetTradeItem(AIndex: Integer): PTrade; begin Result := fTcpAgentDealConsoleData.TradeCache.TradeArray[AIndex]; end; function TDealConsole.CheckOutInvestorPosition(AInstrumentId: AnsiString): PInvestorPosition; var i: integer; begin Result := nil; if AInstrumentId = '' then exit; for i := 0 to fTcpAgentDealConsoleData.InvestorPositionCache.Count - 1 do begin if fTcpAgentDealConsoleData.InvestorPositionCache.InvestorPositionArray[i] = nil then Break; if SameText(fTcpAgentDealConsoleData.InvestorPositionCache.InvestorPositionArray[i].InstrumentId, AInstrumentId) then begin result := fTcpAgentDealConsoleData.InvestorPositionCache.InvestorPositionArray[i]; Break; end; end; if Result = nil then begin if fTcpAgentDealConsoleData.InvestorPositionCache.InvestorPositionArray[fTcpAgentDealConsoleData.InvestorPositionCache.Count] = nil then begin Result := System.New(PInvestorPosition); FillChar(Result^, SizeOf(TInvestorPosition), 0); Result.InstrumentId := AInstrumentId; fTcpAgentDealConsoleData.InvestorPositionCache.InvestorPositionArray[fTcpAgentDealConsoleData.InvestorPositionCache.Count] := Result; Inc(fTcpAgentDealConsoleData.InvestorPositionCache.Count); end; end; end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC 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 CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** Version 0.1 2015.07.13 - First release This is ChromaPrint for Pascal. Look for more details at https://acoustid.org/chromaprint For FPC, use the included DaMath Librarie for DOUBLE Precision calculation. FPC has some bugs with mathematic operations like double division by integer. Delphi is working with the standard Math-Lib. Use the ffMPEG libaries if you want to use the avlibcodec.dll. You can use the build in Lomont FFT and the build in Audio resampler (which is itself translated form the ffmpeg-source / chromaprint-source ) to have no dependencies. Compiler-switch in CP.FFT: USE_FFT_LOMONT This switch is turned on in FPC right now, cause ffmpeg headers are not checked if working with FPC. ************************************************************************** } {$ENDREGION} unit CP.ChromaPrint; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, {$IFDEF FPC} XMLRead, XMLWrite, DOM, {$ENDIF} CP.FingerprinterConfiguration, CP.Resampler, CP.IntegralImage, CP.FFT, CP.Classifier, CP.FeatureVectorConsumer, CP.SilenceRemover, CP.AudioConsumer, CP.AudioProcessor, CP.Chroma, CP.Fingerprint, CP.Image, CP.Def; type TChromaprintContext = record Algorithm: integer; Fingerprinter: TFingerprinter; Fingerprint: TUINT32Array; end; TAcoustIDResult = record Score: single; ID: ansistring; MusicBrainzRecordingID: array of ansistring; end; TAcoustIDResponse = record Status: integer; Results: array of TAcoustIDResult; end; { TChromaPrint } IChromaPrint = interface ['{9C602390-DEBC-431B-BFFB-DE0372AD6102}'] function Version: PWideChar; stdcall; function New(Algorithm: integer): HResult; stdcall; function GetAlgorithm: integer; stdcall; function SetOption(const Name: PWideChar; Value: integer): HResult; stdcall; function Start(Sample_Rate: integer; NumChannels: integer): HResult; stdcall; function Feed(Data: TSmallintArray; length: integer): HResult; stdcall; function Finish: HResult; stdcall; function GetFingerprint(out Fingerprint: ansistring): HResult; stdcall; function GetRawFingerprint(out Fingerprint: TUINT32Array; out Size: integer): HResult; stdcall; function EnocdeFingerprint(RawFP: TUINT32Array; Algorithm: integer; Out EncodedFP: ansistring; out EncodedSize: integer; Base64: boolean): HResult; stdcall; function DecodeFingerprint(encoded: string; uncompressed: TUINT32Array; out Algorithm: integer; Base64: boolean): HResult; stdcall; end; IAcoustID = interface function SearchAcoustID(Fingerprint: ansistring; Duration: integer): HResult; stdcall; function GetSearchCount: integer; stdcall; function GetMusicBrainzInfo(SearchNr: integer; var AcoustIDInfo: TAcoustIDResult): HResult; stdcall; function SetAPIKey(Key: ansistring): HResult; stdcall; end; TChromaPrint = class(TInterfacedObject, IChromaPrint, IAcoustID) private // IChromaPrint ctx: TChromaprintContext; // IAcoustID FSearchCount: integer; FResponse: TAcoustIDResponse; FAcoustIDAPIKey: ansistring; {$IFDEF FPC} function ReadXMLAcoustIDSearchResult(AXMLDocument: TXMLDocument): HResult; {$ENDIF} public // IChromaPrint function Version: PWideChar; stdcall; function New(Algorithm: integer): HResult; stdcall; function GetAlgorithm: integer; stdcall; function SetOption(const Name: PWideChar; Value: integer): HResult; stdcall; function Start(Sample_Rate: integer; NumChannels: integer): integer; stdcall; function Feed(Data: TSmallintArray; length: integer): HResult; stdcall; function Finish: HResult; stdcall; function GetFingerprint(out Fingerprint: ansistring): HResult; stdcall; function GetRawFingerprint(out Fingerprint: TUINT32Array; out Size: integer): HResult; stdcall; function EnocdeFingerprint(RawFP: TUINT32Array; Algorithm: integer; Out EncodedFP: ansistring; out EncodedSize: integer; Base64: boolean): HResult; stdcall; function DecodeFingerprint(encoded: string; uncompressed: TUINT32Array; out Algorithm: integer; Base64: boolean): HResult; stdcall; // IAcoustID function SearchAcoustID(Fingerprint: ansistring; Duration: integer): HResult; stdcall; function GetSearchCount: integer; stdcall; function GetMusicBrainzInfo(SearchNr: integer; var AcoustIDInfo: TAcoustIDResult): HResult; stdcall; function SetAPIKey(Key: ansistring): HResult; stdcall; public constructor Create; destructor Destroy; override; end; implementation uses Windows, CP.Utils, CP.Base64, CP.FingerprintCompressor {$IFDEF FPC} , DaMath, httpsend {$ELSE} , Math {$ENDIF}; { TChromaPrint } {$IFDEF FPC} function TChromaPrint.ReadXMLAcoustIDSearchResult(AXMLDocument: TXMLDocument): HResult; var i, m, j, k, lRecordingIndex: integer; ts: ansistring; lChildNode, lChildNode2, lRecordingNode: TDOMNode; lRecordingCount: integer; lScore: ansistring; lValue: single; lFormatSettings: TFormatSettings; begin lFormatSettings.DecimalSeparator := '.'; SetLength(FResponse.Results, 0); FResponse.Status := 0; // = Status Error m := AXMLDocument.DocumentElement.ChildNodes.Count; with AXMLDocument.DocumentElement.ChildNodes do begin for i := 0 to (m - 1) do begin ts := Item[i].NodeName; if ts = 'status' then begin end else if ts = 'results' then begin SetLength(FResponse.Results, Item[i].ChildNodes.Count); for j := 0 to Item[i].ChildNodes.Count - 1 do begin lChildNode := Item[i].ChildNodes.Item[j]; ts := lChildNode.NodeName; if ts = 'result' then begin // we are now looking for results for k := 0 to lChildNode.ChildNodes.Count - 1 do begin lChildNode2 := lChildNode.ChildNodes.Item[k]; ts := lChildNode2.NodeName; if ts = 'recordings' then begin lRecordingCount := lChildNode2.ChildNodes.Count; SetLength(FResponse.Results[j].MusicBrainzRecordingID, lRecordingCount); for lRecordingIndex := 0 to lRecordingCount - 1 do begin lRecordingNode := lChildNode2.ChildNodes.Item[lRecordingIndex]; ts := lRecordingNode.NodeName; if ts = 'recording' then FResponse.Results[j].MusicBrainzRecordingID[lRecordingIndex] := lRecordingNode.FirstChild.FirstChild.NodeValue; end; end else if ts = 'score' then begin lScore := ansistring(lChildNode2.FirstChild.NodeValue); lValue := 0; if lScore <> '' then lValue := StrToFloat(lScore, lFormatSettings); FResponse.Results[j].Score := lValue; end else if ts = 'id' then begin FResponse.Results[j].ID := lChildNode2.FirstChild.NodeValue; end; end; end; OutputDebugString(PChar(ts)); end; end; end; end; end; {$ENDIF} function TChromaPrint.Version: PWideChar; stdcall; begin Result := PWideChar(IntToStr(CHROMAPRINT_VERSION_MAJOR) + '.' + IntToStr(CHROMAPRINT_VERSION_MINOR) + '.' + IntToStr(CHROMAPRINT_VERSION_PATCH)); end; function TChromaPrint.New(Algorithm: integer): HResult; stdcall; begin SetLength(ctx.Fingerprint, 0); ctx.Algorithm := Algorithm; if ctx.Fingerprinter <> nil then ctx.Fingerprinter.Free; ctx.Fingerprinter := TFingerprinter.Create(CreateFingerprinterConfiguration(ctx.Algorithm)); if ctx.Fingerprinter <> nil then Result := S_OK else Result := S_FALSE; end; function TChromaPrint.GetAlgorithm: integer; stdcall; begin Result := ctx.Algorithm; end; function TChromaPrint.SetOption(const Name: PWideChar; Value: integer): HResult; stdcall; begin if ctx.Fingerprinter.SetOption(Name, Value) then Result := S_OK else Result := S_FALSE; end; function TChromaPrint.Start(Sample_Rate: integer; NumChannels: integer): integer; stdcall; begin if ctx.Fingerprinter.Start(Sample_Rate, NumChannels) then Result := S_OK else Result := S_FALSE; end; function TChromaPrint.Feed(Data: TSmallintArray; length: integer): HResult; stdcall; begin // data: raw audio data, should point to an array of 16-bit signed integers in native byte-order ctx.Fingerprinter.Consume(Data, 0, length); Result := S_OK; end; function TChromaPrint.Finish: HResult; stdcall; begin ctx.Fingerprint := ctx.Fingerprinter.Finish; Result := S_OK; end; function TChromaPrint.GetFingerprint(out Fingerprint: ansistring): HResult; stdcall; begin Fingerprint := Base64Encode(CompressFingerprint(ctx.Fingerprint, Ord(ctx.Algorithm))); Result := S_OK; end; function TChromaPrint.GetRawFingerprint(out Fingerprint: TUINT32Array; out Size: integer): HResult; stdcall; begin Fingerprint := ctx.Fingerprint; Size := length(ctx.Fingerprint); Result := S_OK; end; function TChromaPrint.EnocdeFingerprint(RawFP: TUINT32Array; Algorithm: integer; out EncodedFP: ansistring; out EncodedSize: integer; Base64: boolean): HResult; stdcall; var compressed: string; begin compressed := CompressFingerprint(RawFP, Algorithm); if not Base64 then begin EncodedFP := compressed; EncodedSize := length(EncodedFP); Result := S_OK; end else begin EncodedFP := Base64Encode(compressed); EncodedSize := length(EncodedFP); Result := S_OK; end; end; constructor TChromaPrint.Create; begin end; function TChromaPrint.DecodeFingerprint(encoded: string; uncompressed: TUINT32Array; out Algorithm: integer; Base64: boolean): HResult; stdcall; var lCompressed: string; begin if Base64 then lCompressed := Base64Decode(encoded) else lCompressed := encoded; uncompressed := DecompressFingerprint(lCompressed, Algorithm); end; function TChromaPrint.SearchAcoustID(Fingerprint: ansistring; Duration: integer): HResult; stdcall; {$IFDEF FPC} var HTTP: THTTPSend; FURLXML: ansistring; XMLDocument: TXMLDocument; {$ENDIF} begin {$IFDEF FPC} FURLXML := 'http://api.acoustid.org/v2/lookup?client=' + FAcoustIDAPIKey + '&format=xml&duration=' + IntToStr(Duration) + '&meta=recordingids&fingerprint=' + Fingerprint; HTTP := THTTPSend.Create; try if HTTP.HTTPMethod('GET', FURLXML) then begin ReadXMLFile(XMLDocument, HTTP.Document); ReadXMLAcoustIDSearchResult(XMLDocument); end; finally HTTP.Free; end; {$ENDIF} end; function TChromaPrint.GetSearchCount: integer; stdcall; begin Result := length(FResponse.Results); end; function TChromaPrint.GetMusicBrainzInfo(SearchNr: integer; var AcoustIDInfo: TAcoustIDResult): HResult; stdcall; begin AcoustIDInfo.Score := FResponse.Results[SearchNr].Score; AcoustIDInfo.ID := FResponse.Results[SearchNr].ID; Move(FResponse.Results[SearchNr].MusicBrainzRecordingID, AcoustIDInfo.MusicBrainzRecordingID, SizeOf(FResponse.Results[SearchNr].MusicBrainzRecordingID)); end; function TChromaPrint.SetAPIKey(Key: ansistring): HResult; stdcall; begin FAcoustIDAPIKey := Key; end; destructor TChromaPrint.Destroy; begin SetLength(ctx.Fingerprint, 0); if ctx.Fingerprinter <> nil then ctx.Fingerprinter.Free; inherited Destroy; end; end.
program Lab12_Var9; type Node = record value :Integer; right :^Node; end; type List = record start :^Node; marker :^Node; end; type ListFile = File of Integer; procedure initlist(var l :List); begin l.start := nil; l.marker := nil; end; procedure moveright(var l :List); begin if l.marker <> nil then begin l.marker := l.marker^.right; end; end; procedure appendright(var l :List; value :Integer); var newn, prevn :^Node; begin new(newn); newn^.value := value; writeln('DEBUG append: New element created. Value: ', value); if l.start = nil then { List is empty } begin l.start := newn; l.start^.right := newn; l.marker := newn; writeln('DEBUG append: List was empty'); end else begin prevn := l.marker^.right; l.marker^.right := newn; newn^.right := prevn; end; end; procedure removeright(var l :List); var right :^Node; begin if l.start = nil then { List is empty } begin exit; end; right := l.marker^.right; if right = l.marker then { List is empty now } begin initlist(l); writeln('DEBUG remove: List will be empty now'); end else l.marker^.right := right^.right; if right = l.start then { Change start position } begin l.start := l.marker; writeln('DEBUG remove: Change the start'); end; dispose(right); writeln('DEBUG remove: Element disposed'); end; procedure removemarker(var l :List); var cur :^Node; begin cur := l.start; if cur = nil then { List is empty. } begin exit; end; while cur^.right <> l.marker do begin cur := cur^.right; end; l.marker := cur; removeright(l); end; procedure destroylist(var l :List); begin while l.start <> nil do begin removeright(l); end; end; procedure printlist(var l :List); var cur :^Node; begin cur := l.start; if cur = nil then begin writeln('<EMPTY>'); exit; end; write('[ '); repeat begin if cur = l.marker then begin write('*'); end; write(cur^.value, ', '); cur := cur^.right; end; until cur = l.start; writeln(']'); end; procedure readlist(var l :List; var infile :ListFile); var value :Integer; begin while not eof(infile) do begin read(infile, value); writeln('DEBUG read: Read value ', value); appendright(l, value); l.marker := l.marker^.right; end; end; procedure writelist(var l :List; var outfile :ListFile); var cur :^Node; begin cur := l.start; if cur = nil then { List is empty } begin exit; end; repeat begin write(outfile, cur^.value); writeln('DEBUG write: Write value ', cur^.value); cur := cur^.right; end; until cur = l.start; end; procedure printmenu(); begin writeln('1) Move right.'); writeln('2) Append right.'); writeln('3) Remove the marker.'); writeln('4) Write to file.'); writeln('5) Read from file.'); writeln('0) Create a new list.'); writeln('^C to exit.'); end; function openfile(var filename :String; var fd :ListFile; toread :Boolean) :Boolean; begin assign(fd, filename); if toread then begin reset(fd); end else rewrite(fd); openfile := (ioresult() = 0); end; var choice :Char; l :List; value :Integer; filename :String; fd :ListFile; begin initlist(l); while true do begin writeln('Menu:'); printmenu(); writeln('List:'); printlist(l); write('Choice: '); readln(choice); case choice of '1': moveright(l); '2': begin write('Write your value: '); readln(value); appendright(l, value); end; '3': removemarker(l); '4': begin write('Write your file: '); readln(filename); if not openfile(filename, fd, false) then begin writeln('Cant open file!'); end else begin writelist(l, fd); close(fd); end; end; '5': begin write('Write your file to read: '); readln(filename); if not openfile(filename, fd, true) then begin writeln('Cant open file!'); end else begin destroylist(l); readlist(l, fd); l.marker := l.start; close(fd); end; end; '0': destroylist(l); end; end; end.
unit Unit1; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ImgList, Grids, StdCtrls, ExtCtrls; type TForm1 = class(TForm) DrawGrid1: TDrawGrid; ImageList1: TImageList; Timer1: TTimer; Panel1: TPanel; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; Button1: TButton; procedure DrawGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure Button1Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure DrawGrid1DblClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure CheckBox3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private-Deklarationen } FFrames : Integer; public { Public-Deklarationen } end; var Form1: TForm1; const COL_COUNT = 8; ROW_COUNT = 8; type TChessField = array[1..COL_COUNT, 1..ROW_COUNT] of Smallint; var chessField : TChessField; implementation {$R *.DFM} // dieser Eventhandler zeichnet auf dem Drwagrid procedure TForm1.DrawGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var figur : Smallint; bkcolor : TColor; begin if ACol = 0 then begin // Beschriftung vertikal if ARow <> 0 then DrawGrid1.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2, IntToStr(ARow)); end else if ARow = 0 then begin // Beschriftung horizontal DrawGrid1.Canvas.TextRect(Rect, Rect.Left+2, Rect.Top+2, chr(Ord('A')+ACol-1)); end else begin // "eigentliches" Schachbrett // Hintergrund Farbe ermitteln if Odd(ACol+ARow) then bkcolor := clLime else bkcolor := clWhite; // Hintergrund zeichnen DrawGrid1.Canvas.brush.Color := bkcolor; DrawGrid1.Canvas.FillRect(rect); // Spielfigur zeichen figur := chessField[ACol, ARow]; // figur = 0 zählt als leeres Feld if figur > 0 then ImageList1.Draw(DrawGrid1.Canvas, Rect.Left, Rect.Top, figur-1); end; end; procedure TForm1.Button1Click(Sender: TObject); var x ,y : Integer; begin // irgenwelche Figuren setzen x := 1 + random(COL_COUNT); y := 1 + random(ROW_COUNT); chessField[x,y] := random(ImageList1.Count); // Neuzeichnen erzwingen DrawGrid1.Invalidate; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin with Sender as TCheckBox do begin if Checked then DrawGrid1.Options := DrawGrid1.Options + [goVertLine] else DrawGrid1.Options := DrawGrid1.Options - [goVertLine]; end; end; procedure TForm1.CheckBox2Click(Sender: TObject); begin with Sender as TCheckBox do begin if Checked then DrawGrid1.Options := DrawGrid1.Options + [goHorzLine] else DrawGrid1.Options := DrawGrid1.Options - [goHorzLine]; end; end; procedure TForm1.DrawGrid1DblClick(Sender: TObject); var x , y : Integer; figur : Smallint; begin x := DrawGrid1.Col; y := DrawGrid1.Row; // alte Figur holen figur := chessField[x,y]; // nächste Figur wählen Inc(figur); // auspassen, damit wir nicht ausserhalb der Imageliste kommen if figur > ImageList1.Count then figur := 0; chessField[x,y] := figur; // neue Figur setzen DrawGrid1.Invalidate; end; procedure TForm1.Timer1Timer(Sender: TObject); var x ,y : Integer; begin x := 1 + random(COL_COUNT); y := 1 + random(ROW_COUNT); // alte Figur holen chessField[x,y] := random(ImageList1.Count); DrawGrid1.Invalidate; Inc(FFrames); Caption := IntToStr(FFrames); end; procedure TForm1.CheckBox3Click(Sender: TObject); begin Timer1.Enabled := CheckBox3.Checked; FFrames := 0; end; procedure TForm1.FormCreate(Sender: TObject); begin DrawGrid1.RowCount := ROW_COUNT; DrawGrid1.ColCount := COL_COUNT; end; end.
unit nsExecuteProgressIndicator; interface {$If not defined(Admin) AND not defined(Monitorings)} uses Windows, Messages, l3Interfaces, vcmInterfaces, BaseTypesUnit, DynamicDocListUnit, ProgressIndicatorSupportUnit, SearchProgressIndicatorUnit, SearchUnit, nsThreadNotifier, SearchInterfaces ; type TnsExecuteProgressIndicator = class (TnsThreadNotifier, IProgressIndicatorForSearch, InsProgressIndicator) private f_MaxCount: Longint; f_ProgressIndicator: IvcmEntity; f_Result: ISearchEntity; f_Cancelled: Boolean; protected f_CancelLongProcess: ICancelLongProcess; protected procedure DoStartProcess; virtual; abstract; {-} function DataValid: Boolean; virtual; abstract; {-} public constructor Create; reintroduce; {-} procedure Cleanup; override; {-} //InsProgressIndicator function Execute(const aCaption: Il3CString; out aSearchEntity: ISearchEntity): Boolean; {-} procedure StartProcess(const aProgressIndicator: IvcmEntity); {-} procedure StopProcess; {-} //IProgressIndicatorForSearch function GetMaxCount: Longint; stdcall; {-} procedure SetCurrent(aCurCount: Longint; aArg: Longint); stdcall; {-} procedure FinishProcess(const aSearchEntity: ISearchEntity); stdcall; {-} end; {$IfEnd} //not Admin implementation {$If not defined(Admin) AND not defined(Monitorings)} uses l3Base, vcmBase, StdRes, ProgressIndicator_Form, PrimProgressIndicator_Form , Common_F1CommonServices_Contracts ; function TnsExecuteProgressIndicator.Execute(const aCaption: Il3CString; out aSearchEntity: ISearchEntity): Boolean; var l_ProgressIndicator : InsProgressIndicator; begin Result := False; if DataValid then begin l_ProgressIndicator := Self; try TCommonService.Instance.MakeProgressIndicator(l_ProgressIndicator, aCaption, GetMaxCount); aSearchEntity := f_Result; Result := not f_Cancelled; finally l_ProgressIndicator := nil; end;//try..finally end;//DataValid end; constructor TnsExecuteProgressIndicator.Create; begin inherited Create; // f_MaxCount := 100; end; procedure TnsExecuteProgressIndicator.Cleanup; begin f_CancelLongProcess := nil; f_ProgressIndicator := nil; f_Result := nil; f_Cancelled := False; inherited Cleanup; end; function TnsExecuteProgressIndicator.GetMaxCount: Longint; begin Result := f_MaxCount; end; procedure TnsExecuteProgressIndicator.StartProcess(const aProgressIndicator: IvcmEntity); begin f_ProgressIndicator := aProgressIndicator; DoStartProcess; end; procedure TnsExecuteProgressIndicator.StopProcess; begin if Assigned(f_CancelLongProcess) then begin f_CancelLongProcess.CancelProcess(); f_Cancelled := True; end; end; procedure TnsExecuteProgressIndicator.SetCurrent(aCurCount: Longint; aArg: Longint); begin if Assigned(f_ProgressIndicator) then PostMessage((f_ProgressIndicator as IvcmEntityForm).VCLWinControl.Handle, WM_USER_SET_CURRENT, aCurCount, aArg); end; procedure TnsExecuteProgressIndicator.FinishProcess(const aSearchEntity: ISearchEntity); begin f_Result := aSearchEntity; if Assigned(f_ProgressIndicator) then PostMessage((f_ProgressIndicator as IvcmEntityForm).VCLWinControl.Handle, WM_USER_FINISH_PROCESS, 0, 0); f_CancelLongProcess := nil; f_ProgressIndicator := nil; end; {$IfEnd} //not Admin end.
unit Control.UsuariosBaseEntregador; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.UsuariosBaseEntregador; type TUsuariosBaseEntregadorControl = class private FUsuarios: TUsuariosBaseEntregador; public constructor Create; destructor Destroy; override; property Usuarios: TUsuariosBaseEntregador read FUsuarios write FUsuarios; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function ValidaCampos(): Boolean; end; implementation { TUsuariosBaseEntregador } constructor TUsuariosBaseEntregadorControl.Create; begin FUsuarios := TUsuariosBaseEntregador.Create; end; destructor TUsuariosBaseEntregadorControl.Destroy; begin FUsuarios.Free; inherited; end; function TUsuariosBaseEntregadorControl.Gravar: Boolean; begin Result := False; if not ValidaCampos() then Exit; Result := FUsuarios.Gravar; end; function TUsuariosBaseEntregadorControl.Localizar(aParam: array of variant): TFDQuery; begin Result := FUsuarios.Localizar(aParam); end; function TUsuariosBaseEntregadorControl.ValidaCampos: Boolean; begin Result := False; if FUsuarios.Usuario = 0 then begin Application.MessageBox('Informe o usuário!', 'Atenção', MB_OK + MB_ICONERROR); Exit; end; if FUsuarios.Agente = 0 then begin Application.MessageBox('Informe o Agente!', 'Atenção', MB_OK + MB_ICONERROR); Exit; end; Result := True; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.0 8/24/2003 06:47:42 PM JPMugaas { FTPContext base class so that the ThreadClass may be shared with the { FileSystem classes. } unit IdFTPServerContextBase; interface uses IdContext; {This is for a basic thread class that can be shared with the FTP File System component and any other file system class so they can share more information than just the Username} type TIdFTPUserType = (utNone, utAnonymousUser, utNormalUser); TIdFTPServerContextBase = class(TIdContext) protected FUserType: TIdFTPUserType; FAuthenticated: Boolean; FALLOSize: Integer; FCurrentDir: string; FHomeDir: string; FUsername: string; FPassword: string; FRESTPos: Integer; FRNFR: string; procedure ReInitialize; virtual; public property Authenticated: Boolean read FAuthenticated write FAuthenticated; property ALLOSize: Integer read FALLOSize write FALLOSize; property CurrentDir: string read FCurrentDir write FCurrentDir; property HomeDir: string read FHomeDir write FHomeDir; property Password: string read FPassword write FPassword; property Username: string read FUsername write FUsername; property UserType: TIdFTPUserType read FUserType write FUserType; property RESTPos: Integer read FRESTPos write FRESTPos; property RNFR: string read FRNFR write FRNFR; end; implementation { TIdFTPServerContextBase } procedure TIdFTPServerContextBase.ReInitialize; begin UserType := utNone; FAuthenticated := False; FALLOSize := 0; FCurrentDir := '/'; {Do not Localize} FHomeDir := ''; {Do not Localize} FUsername := ''; {Do not Localize} FPassword := ''; {Do not Localize} FRESTPos := 0; FRNFR := ''; {Do not Localize} end; end.
(* ***** 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 TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StExport.pas 4.04 *} {*********************************************************} {* SysTools: DB Exporter Classes *} {*********************************************************} {$include StDefine.inc} unit StExport; interface uses Windows, SysUtils, Classes, DB, DbConsts, StBase, StTxtDat; const DefaultDateFmt = 'mm/dd/yyyy'; DefaultTimeFmt = 'hh:mm:ss'; DefaultDateTimeFmt = 'mm/dd/yyyy hh:mm:ss'; type TStExportProgressEvent = procedure (Sender : TObject; Index : Integer; var Abort : Boolean) of object; TStDBtoCSVExport = class private FDataSet: TDataSet; FFieldDelimiter: Char; FIncludeHeader: Boolean; FLineTermChar : AnsiChar; FLineTerminator : TStLineTerminator; FQuoteAlways: Boolean; FQuoteDelimiter: Char; FQuoteIfSpaces: Boolean; FDateFmt: string; FTimeFmt, FDateTimeFmt : string; FOnExportProgress : TStExportProgressEvent; FOnQuoteField : TStOnQuoteFieldEvent; protected {private} function BuildCSVHeader: string; function BuildCSVRec : string; procedure SetDataSet(const Value: TDataSet); procedure SetFieldDelimiter(const Value: Char); procedure SetIncludeHeader(const Value: Boolean); procedure SetQuoteAlways(const Value: Boolean); procedure SetQuoteDelimiter(const Value: Char); procedure SetQuoteIfSpaces(const Value: Boolean); public constructor Create; { Access and Update Methods } procedure DoQuote(var Value: String); virtual; { Persistence and streaming methods } procedure ExportToStream(AStream : TStream); procedure ExportToFile(AFile : TFileName); { properties } property DataSet : TDataSet read FDataSet write SetDataSet; property FieldDelimiter : Char read FFieldDelimiter write SetFieldDelimiter default StDefaultDelim; property IncludeHeader : Boolean read FIncludeHeader write SetIncludeHeader default False; property LineTermChar : AnsiChar read FLineTermChar write FLineTermChar default #0; property LineTerminator : TStLineTerminator read FLineTerminator write FLineTerminator default ltCRLF; property QuoteAlways : Boolean read FQuoteAlways write SetQuoteAlways default False; property QuoteDelimiter : Char read FQuoteDelimiter write SetQuoteDelimiter default StDefaultQuote; property QuoteIfSpaces : Boolean read FQuoteIfSpaces write SetQuoteIfSpaces default False; property DateFmt : string read FDateFmt write FDateFmt; property TimeFmt : string read FTimeFmt write FTimeFmt; property DateTimeFmt : string read FDateTimeFmt write FDateTimeFmt; { events } property OnQuoteField : TStOnQuoteFieldEvent read FOnQuoteField write FOnQuoteField; property OnExportProgress : TStExportProgressEvent read FOnExportProgress write FOnExportProgress; end; TStDbSchemaGenerator = class private FDataSet : TDataSet; FSchema : TStTextDataSchema; protected {private} function GetFieldDelimiter: Char; function GetQuoteDelimiter: Char; function GetSchemaName: string; procedure SetDataSet(const Value: TDataSet); procedure SetFieldDelimiter(const Value: Char); procedure SetQuoteDelimiter(const Value: Char); procedure SetSchemaName(const Value: string); public constructor Create; destructor Destroy; override; { Persistence and streaming methods } procedure ExportToStream(AStream : TStream); procedure ExportToFile(AFile : TFileName); { properties } property DataSet : TDataSet read FDataSet write SetDataSet; property FieldDelimiter : Char read GetFieldDelimiter write SetFieldDelimiter default StDefaultDelim; property QuoteDelimiter : Char read GetQuoteDelimiter write SetQuoteDelimiter default StDefaultQuote; property SchemaName : string read GetSchemaName write SetSchemaName; end; implementation uses StStrms; { TFieldType = (ftUnknown, ftString, ftSmallint, ftInteger, ftWord, ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, ftWideString, ftLargeint, ftADT, ftArray, ftReference, ftDataSet, ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch, ftGuid); } const { see DB unit for full set of field types } DBValidFields = [ftString, ftSmallInt, ftInteger, ftAutoInc, ftWord, ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime]; DBFloatFields = [ftFloat, ftCurrency, ftBCD]; { TStDBtoCSVExport } constructor TStDBtoCSVExport.Create; begin inherited Create; FFieldDelimiter := StDefaultDelim; FQuoteDelimiter := StDefaultQuote; FLineTermChar := #0; FLineTerminator := ltCRLF; FQuoteAlways := False; FQuoteIfSpaces := False; FDateFmt := DefaultDateFmt; FTimeFmt := DefaultTimeFmt; FDateTimeFmt := DefaultDateTimeFmt; end; function TStDBtoCSVExport.BuildCSVHeader: string; { generate CSV header from Data Set field data } var i : Integer; Name : string; TheField : TField; begin Result := ''; for i := 0 to Pred(FDataSet.FieldCount) do begin TheField := FDataSet.Fields[i]; { is field is among supported types? } if (TheField.FieldKind = fkData) and (TheField.DataType in DBValidFields) then begin { get name of current field } Name := TheField.FieldName; if i = 0 then { no field delimiter before first field } Result := Result + Name else Result := Result + FFieldDelimiter + Name; end; end; end; function TStDBtoCSVExport.BuildCSVRec: string; { generate record of CSV data from Data Set field data } var i : Integer; FieldStr : String; TheField : TField; begin Result := ''; for i := 0 to Pred(FDataSet.FieldCount) do begin TheField := FDataSet.Fields[i]; { is field is among supported types? } if (TheField.FieldKind = fkData) and (TheField.DataType in DBValidFields) then begin { get value of current field as a string } case TheField.DataType of ftDate : FieldStr := FormatDateTime(FDateFmt, TheField.AsDateTime); ftTime : FieldStr := FormatDateTime(FTimeFmt, TheField.AsDateTime); ftDateTime : FieldStr := FormatDateTime(FDateTimeFmt, TheField.AsDateTime); else FieldStr := TheField.AsString; end; { quote if needed } DoQuote(FieldStr); if i = 0 then { no field delimiter before first field } Result := Result + FieldStr else Result := Result + FFieldDelimiter + FieldStr; end; end; end; procedure TStDBtoCSVExport.DoQuote(var Value : String); { quote field string if needed or desired } var QuoteIt : Boolean; begin { fire event if available } if Assigned(FOnQuoteField) then begin FOnQuoteField(self, Value); end else begin { use default quoting policy } QuoteIt := False; if FQuoteAlways then QuoteIt := True else if ((Pos(' ', Value) > 0) and FQuoteIfSpaces) or (Pos(FFieldDelimiter, Value) > 0) or (Pos(FQuoteDelimiter, Value) > 0) then QuoteIt := True; if QuoteIt then Value := FQuoteDelimiter + Value + FQuoteDelimiter; end; end; procedure TStDBtoCSVExport.ExportToFile(AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmCreate); try ExportToStream(FS); finally FS.Free; end; end; procedure TStDBtoCSVExport.ExportToStream(AStream: TStream); var TS : TStAnsiTextStream; Abort : Boolean; Count : Integer; begin { table must be open and active } if not FDataSet.Active then DatabaseError(SDataSetClosed, FDataSet); TS := TStAnsiTextStream.Create(AStream); TS.LineTerminator := FLineTerminator; TS.LineTermChar := FLineTermChar; try { generate header line if desired } if FIncludeHeader then TS.WriteLine(BuildCSVHeader); { iterate table } FDataSet.First; Count := 0; Abort := False; while not FDataSet.Eof and not Abort do begin { write CSV formatted data for current record } TS.WriteLine(BuildCSVRec); Inc(Count); if Assigned(FOnExportProgress) then FOnExportProgress(self, Count, Abort); { next record } FDataSet.Next; end; finally TS.Free; end; end; procedure TStDBtoCSVExport.SetDataSet(const Value: TDataSet); begin FDataSet := Value; end; procedure TStDBtoCSVExport.SetFieldDelimiter(const Value: Char); begin FFieldDelimiter := Value; end; procedure TStDBtoCSVExport.SetIncludeHeader(const Value: Boolean); begin FIncludeHeader := Value; end; procedure TStDBtoCSVExport.SetQuoteAlways(const Value: Boolean); begin FQuoteAlways := Value; end; procedure TStDBtoCSVExport.SetQuoteIfSpaces(const Value: Boolean); begin FQuoteIfSpaces := Value; end; procedure TStDBtoCSVExport.SetQuoteDelimiter(const Value: Char); begin FQuoteDelimiter := Value; end; { TStSchemaFieldType = (sftUnknown, sftChar, sftFloat, sftNumber, sftBool, sftLongInt, sftDate, sftTime, sftTimeStamp); } function ConvertFieldType(DBFieldType : TFieldType) : TStSchemaFieldType; { convert table field type to schema field type } begin case DBFieldType of ftString : Result := sftChar; ftSmallInt : Result := sftNumber; ftInteger : Result := sftLongInt; ftAutoInc : Result := sftLongInt; ftWord : Result := sftNumber; ftBoolean : Result := sftBool; ftFloat : Result := sftFloat; ftCurrency : Result := sftFloat; ftBCD : Result := sftFloat; ftDate : Result := sftDate; ftTime : Result := sftTime; ftDateTime : Result := sftTimeStamp; else Result := sftUnknown; end; end; function GetDecimals(const DataStr : string): Integer; { determine decimal places for float formatted string } begin Result := Length(DataStr) - Pos(FormatSettings.DecimalSeparator, DataStr); try StrToFloat(DataStr); except Result := 0; end; end; { TStDbSchemaGenerator } constructor TStDbSchemaGenerator.Create; begin inherited Create; FSchema := TStTextDataSchema.Create; { set defaults for compatible schema } FSchema.LayoutType := ltVarying; FSchema.FieldDelimiter := StDefaultDelim; FSchema.QuoteDelimiter := StDefaultQuote; FSchema.CommentDelimiter := StDefaultComment; end; destructor TStDbSchemaGenerator.Destroy; begin FSchema.Free; inherited Destroy; end; procedure TStDbSchemaGenerator.ExportToFile(AFile: TFileName); var FS : TFileStream; begin FS := TFileStream.Create(AFile, fmCreate); try ExportToStream(FS); finally FS.Free; end; end; procedure TStDbSchemaGenerator.ExportToStream(AStream: TStream); var i, Width, Decimals : Integer; TheField : TField; begin { table must be open and active } if not FDataSet.Active then DatabaseError(SDataSetClosed, FDataSet); { build field definitions } for i := 0 to Pred(FDataSet.FieldCount) do begin TheField := FDataSet.Fields[i]; { is field is among supported types? } if (TheField.FieldKind = fkData) and (TheField.DataType in DBValidFields) then begin Width := TheField.DisplayWidth; { if it's a floating point type field, need decimals } if (FDataSet.Fields[i].DataType in DBFloatFields) then Decimals := GetDecimals(TheField.AsString) else Decimals := 0; { add field definition to Schema } FSchema.AddField(TheField.FieldName, ConvertFieldType(TheField.DataType), Width, Decimals); end; end; { save the schema } FSchema.SaveToStream(AStream); end; function TStDbSchemaGenerator.GetFieldDelimiter: Char; begin Result := FSchema.FieldDelimiter; end; function TStDbSchemaGenerator.GetQuoteDelimiter: Char; begin Result := FSchema.QuoteDelimiter; end; function TStDbSchemaGenerator.GetSchemaName: string; begin Result := FSchema.SchemaName; end; procedure TStDbSchemaGenerator.SetDataSet(const Value: TDataSet); begin FDataSet := Value; end; procedure TStDbSchemaGenerator.SetFieldDelimiter(const Value: Char); begin FSchema.FieldDelimiter := Value; end; procedure TStDbSchemaGenerator.SetQuoteDelimiter(const Value: Char); begin FSchema.QuoteDelimiter := Value; end; procedure TStDbSchemaGenerator.SetSchemaName(const Value: string); begin FSchema.SchemaName:= Value; end; end.
unit INFOLENDERMASTERCODETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TINFOLENDERMASTERCODERecord = record PRecID: Word; PComponentNumber: Word; PCodeNumber: Word; PCode: String[6]; PDescription: String[30]; PActive: Boolean; PComponentIndex: Word; End; TINFOLENDERMASTERCODEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TINFOLENDERMASTERCODERecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIINFOLENDERMASTERCODE = (INFOLENDERMASTERCODEPrimaryKey, INFOLENDERMASTERCODEDataCode, INFOLENDERMASTERCODEComponentCode); TINFOLENDERMASTERCODETable = class( TDBISAMTableAU ) private FDFRecID: TWordField; FDFComponentNumber: TWordField; FDFCodeNumber: TWordField; FDFCode: TStringField; FDFDescription: TStringField; FDFActive: TBooleanField; FDFComponentIndex: TWordField; procedure SetPRecID(const Value: Word); function GetPRecID:Word; procedure SetPComponentNumber(const Value: Word); function GetPComponentNumber:Word; procedure SetPCodeNumber(const Value: Word); function GetPCodeNumber:Word; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; procedure SetPComponentIndex(const Value: Word); function GetPComponentIndex:Word; procedure SetEnumIndex(Value: TEIINFOLENDERMASTERCODE); function GetEnumIndex: TEIINFOLENDERMASTERCODE; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TINFOLENDERMASTERCODERecord; procedure StoreDataBuffer(ABuffer:TINFOLENDERMASTERCODERecord); property DFRecID: TWordField read FDFRecID; property DFComponentNumber: TWordField read FDFComponentNumber; property DFCodeNumber: TWordField read FDFCodeNumber; property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFActive: TBooleanField read FDFActive; property DFComponentIndex: TWordField read FDFComponentIndex; property PRecID: Word read GetPRecID write SetPRecID; property PComponentNumber: Word read GetPComponentNumber write SetPComponentNumber; property PCodeNumber: Word read GetPCodeNumber write SetPCodeNumber; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PActive: Boolean read GetPActive write SetPActive; property PComponentIndex: Word read GetPComponentIndex write SetPComponentIndex; published property Active write SetActive; property EnumIndex: TEIINFOLENDERMASTERCODE read GetEnumIndex write SetEnumIndex; end; { TINFOLENDERMASTERCODETable } procedure Register; implementation procedure TINFOLENDERMASTERCODETable.CreateFields; begin FDFRecID := CreateField( 'RecID' ) as TWordField; FDFComponentNumber := CreateField( 'ComponentNumber' ) as TWordField; FDFCodeNumber := CreateField( 'CodeNumber' ) as TWordField; FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFActive := CreateField( 'Active' ) as TBooleanField; FDFComponentIndex := CreateField( 'ComponentIndex' ) as TWordField; end; { TINFOLENDERMASTERCODETable.CreateFields } procedure TINFOLENDERMASTERCODETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TINFOLENDERMASTERCODETable.SetActive } procedure TINFOLENDERMASTERCODETable.SetPRecID(const Value: Word); begin DFRecID.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPRecID:Word; begin result := DFRecID.Value; end; procedure TINFOLENDERMASTERCODETable.SetPComponentNumber(const Value: Word); begin DFComponentNumber.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPComponentNumber:Word; begin result := DFComponentNumber.Value; end; procedure TINFOLENDERMASTERCODETable.SetPCodeNumber(const Value: Word); begin DFCodeNumber.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPCodeNumber:Word; begin result := DFCodeNumber.Value; end; procedure TINFOLENDERMASTERCODETable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPCode:String; begin result := DFCode.Value; end; procedure TINFOLENDERMASTERCODETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TINFOLENDERMASTERCODETable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TINFOLENDERMASTERCODETable.SetPComponentIndex(const Value: Word); begin DFComponentIndex.Value := Value; end; function TINFOLENDERMASTERCODETable.GetPComponentIndex:Word; begin result := DFComponentIndex.Value; end; procedure TINFOLENDERMASTERCODETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('RecID, Word, 0, N'); Add('ComponentNumber, Word, 0, N'); Add('CodeNumber, Word, 0, N'); Add('Code, String, 6, N'); Add('Description, String, 30, N'); Add('Active, Boolean, 0, N'); Add('ComponentIndex, Word, 0, N'); end; end; procedure TINFOLENDERMASTERCODETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, RecID, Y, Y, N, N'); Add('DataCode, ComponentNumber;Code, N, Y, N, N'); Add('ComponentCode, ComponentNumber;CodeNumber, N, Y, N, N'); end; end; procedure TINFOLENDERMASTERCODETable.SetEnumIndex(Value: TEIINFOLENDERMASTERCODE); begin case Value of INFOLENDERMASTERCODEPrimaryKey : IndexName := ''; INFOLENDERMASTERCODEDataCode : IndexName := 'DataCode'; INFOLENDERMASTERCODEComponentCode : IndexName := 'ComponentCode'; end; end; function TINFOLENDERMASTERCODETable.GetDataBuffer:TINFOLENDERMASTERCODERecord; var buf: TINFOLENDERMASTERCODERecord; begin fillchar(buf, sizeof(buf), 0); buf.PRecID := DFRecID.Value; buf.PComponentNumber := DFComponentNumber.Value; buf.PCodeNumber := DFCodeNumber.Value; buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PActive := DFActive.Value; buf.PComponentIndex := DFComponentIndex.Value; result := buf; end; procedure TINFOLENDERMASTERCODETable.StoreDataBuffer(ABuffer:TINFOLENDERMASTERCODERecord); begin DFRecID.Value := ABuffer.PRecID; DFComponentNumber.Value := ABuffer.PComponentNumber; DFCodeNumber.Value := ABuffer.PCodeNumber; DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFActive.Value := ABuffer.PActive; DFComponentIndex.Value := ABuffer.PComponentIndex; end; function TINFOLENDERMASTERCODETable.GetEnumIndex: TEIINFOLENDERMASTERCODE; var iname : string; begin result := INFOLENDERMASTERCODEPrimaryKey; iname := uppercase(indexname); if iname = '' then result := INFOLENDERMASTERCODEPrimaryKey; if iname = 'DATACODE' then result := INFOLENDERMASTERCODEDataCode; if iname = 'COMPONENTCODE' then result := INFOLENDERMASTERCODEComponentCode; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TINFOLENDERMASTERCODETable, TINFOLENDERMASTERCODEBuffer ] ); end; { Register } function TINFOLENDERMASTERCODEBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..7] of string = ('RECID','COMPONENTNUMBER','CODENUMBER','CODE','DESCRIPTION','ACTIVE' ,'COMPONENTINDEX' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 7) and (flist[x] <> s) do inc(x); if x <= 7 then result := x else result := 0; end; function TINFOLENDERMASTERCODEBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftWord; 2 : result := ftWord; 3 : result := ftWord; 4 : result := ftString; 5 : result := ftString; 6 : result := ftBoolean; 7 : result := ftWord; end; end; function TINFOLENDERMASTERCODEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PRecID; 2 : result := @Data.PComponentNumber; 3 : result := @Data.PCodeNumber; 4 : result := @Data.PCode; 5 : result := @Data.PDescription; 6 : result := @Data.PActive; 7 : result := @Data.PComponentIndex; end; end; end.
unit UDataDetailFrame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.Memo, FMX.Objects, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Response.Adapter, REST.Client, FMX.ScrollBox, FMX.Controls.Presentation; type TDataDetailFrame = class(TFrame) TextEPGDateTimeLabel: TLabel; TextEPGInfoBottomRectangle: TRectangle; TextEPGInfoLabel: TLabel; TextEPGInfoMemo: TMemo; TextEPGInfoRecordButton: TButton; TextEPGInfoToolBar: TToolBar; TextEPGTitleLabel: TLabel; TextEPGBackButton: TButton; DataAniIndicator: TAniIndicator; procedure TextEPGInfoRecordButtonClick(Sender: TObject); private { Private declarations } fDataSet: TDataSet; fRESTRequestAddTimer: TRESTRequest; fRESTResponseAddTimer: TRESTResponse; fDetailDataSetConfigList: TStringList; procedure startSpinner; procedure stopSpinner; public { Public declarations } procedure init(lDetailDataSet: TDataSet; lDetailRESTRequestAddTimer: TRESTRequest; lDetailRESTResponseAddTimer: TRESTResponse; lDetailDataSetConfigList: TStringList); end; implementation {$R *.fmx} procedure TDataDetailFrame.init(lDetailDataSet: TDataSet; lDetailRESTRequestAddTimer: TRESTRequest; lDetailRESTResponseAddTimer: TRESTResponse; lDetailDataSetConfigList: TStringList); begin fDataSet := lDetailDataSet; fRESTRequestAddTimer := lDetailRESTRequestAddTimer; fRESTResponseAddTimer := lDetailRESTResponseAddTimer; fDetailDataSetConfigList := lDetailDataSetConfigList; TextEPGTitleLabel.Text := fDataSet.FieldByName(lDetailDataSetConfigList[0] ).AsString; TextEPGInfoLabel.Text := fDataSet.FieldByName(lDetailDataSetConfigList[1] ).AsString; if lDetailDataSetConfigList[4] = 'filesize' then begin TextEPGDateTimeLabel.Text := fDataSet.FieldByName (lDetailDataSetConfigList[2]).AsString + ' - ' + fDataSet.FieldByName(lDetailDataSetConfigList[3]).AsString + ' min:s' + ' - ' + FloatToStr (RoundTo(StrToInt64(fDataSet.FieldByName(lDetailDataSetConfigList[4]) .AsString) / 1024 / 1024 / 1024, -2)) + ' GB'; end else begin TextEPGDateTimeLabel.Text := fDataSet.FieldByName (lDetailDataSetConfigList[2]).AsString + ': ' + fDataSet.FieldByName(lDetailDataSetConfigList[3]).AsString + ' - ' + fDataSet.FieldByName(lDetailDataSetConfigList[4]).AsString end; TextEPGInfoMemo.Text := fDataSet.FieldByName(lDetailDataSetConfigList[5] ).AsString; end; procedure TDataDetailFrame.startSpinner; begin // spinner on DataAniIndicator.Visible := True; DataAniIndicator.Enabled := True; Application.ProcessMessages; end; procedure TDataDetailFrame.stopSpinner; begin // spinner on DataAniIndicator.Visible := False; DataAniIndicator.Enabled := False; end; procedure TDataDetailFrame.TextEPGInfoRecordButtonClick(Sender: TObject); begin // start the spinner startSpinner; fRESTRequestAddTimer.Params[0].Value := fDataSet.FieldByName('sref').AsString; fRESTRequestAddTimer.Params[1].Value := fDataSet.FieldByName('id').AsString; try fRESTRequestAddTimer.Execute; except // spinner off stopSpinner; MessageDlg('Can''t find your decoder! Please check your settings!', System.UITypes.TMsgDlgType.mtError, [System.UITypes.TMsgDlgBtn.mbOK], 0); end; if fRESTResponseAddTimer.StatusCode = 200 then begin // spinner off stopSpinner; MessageDlg('Timer successfully scheduled!', System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbOK], 0); end else begin // spinner off stopSpinner; MessageDlg('The following error occurred: ' + fRESTResponseAddTimer.StatusText, System.UITypes.TMsgDlgType.mtError, [System.UITypes.TMsgDlgBtn.mbOK], 0); end; end; end.
unit Surfaces; interface uses Classes, Windows, Collection, SysUtils, BackupInterfaces, SyncObjs, Matrix, LargeMatrix; const tidClassFamily_SurfacePools = 'SurfacePools'; tidSurfacePool_Surfaces = 'Surfaces'; tidSurfacePool_Integrators = 'Integrators'; type TSurfaceId = string; TSurfaceValue = single; type IAreaAgent = interface function getAgentArea : TRect; end; type // Classes defined: TSurfacePool = class; TSurface = class; TSurfaceModifier = class; TSurfaceIntegrator = class; TIntegratorPool = class; CSurfacePool = class of TSurfacePool; CSurface = class of TSurface; CSurfaceModifier = class of TSurfaceModifier; CSurfaceIntegrator = class of TSurfaceIntegrator; CIntegratorPool = class of TIntegratorPool; TSurfacePool = class public constructor Create; destructor Destroy; override; private fSurfaces : TLockableCollection; private function GetSurface( id : TSurfaceId ) : TSurface; public property Surface[id : TSurfaceId] : TSurface read GetSurface; default; property Surfaces : TLockableCollection read fSurfaces; public procedure AddSurface( Surface : TSurface ); procedure Update; end; TSurface = class( TObject, IMatrix ) public constructor Create( anId : TSurfaceId; aName : string ); destructor Destroy; override; private fId : TSurfaceId; fName : string; public property Id : TSurfaceId read fId; property Name : string read fName; private fModifiers : TLockableCollection; fMatrix : TSingleLargeMatrix; public procedure AddModifier( Modifier : TSurfaceModifier ); procedure DelModifier( Modifier : TSurfaceModifier ); procedure SetSize( xSize, ySize : integer ); private procedure Update; protected function GetValue( x, y : integer ) : TSurfaceValue; virtual; function GetAreaModifiers( Area : TRect ) : TLockableCollection; virtual; protected property AreaModifiers[Area : TRect] : TLockableCollection read GetAreaModifiers; property Value[x, y : integer] : TSurfaceValue read GetValue; default; // IMatrix private function getCols : integer; function getRows : integer; procedure setDimensions( n, m : integer ); function getElement ( i, j : integer ) : single; procedure setElement ( i, j : integer; value : single ); // IUnknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; end; TSurfaceModifier = class( TObject, IAreaAgent ) public constructor Create( aSurfaceId : TSurfaceId; anOrigin : TPoint; aValue, aStrength : TSurfaceValue ); virtual; destructor Destroy; override; private fOrigin : TPoint; fValue : TSurfaceValue; fNewValue : TSurfaceValue; fStrength : TSurfaceValue; fSurface : TSurface; fFixedArea : boolean; protected function GetValueAt( x, y : integer ) : TSurfaceValue; virtual; abstract; function GetArea : TRect; virtual; abstract; procedure SetArea( anArea : TRect ); virtual; abstract; procedure Update; virtual; abstract; private function GetIntersects( anArea : TRect ) : boolean; function GetModified : boolean; procedure SetValue( aValue : TSurfaceValue ); procedure SetStrength( aStrength : TSurfaceValue ); public property Origin : TPoint read fOrigin write fOrigin; property Value : TSurfaceValue read fValue write SetValue; property Modified : boolean read GetModified; property Area : TRect read GetArea write SetArea; property Strength : TSurfaceValue read fStrength write SetStrength; property FixedArea : boolean read fFixedArea write fFixedArea; property ValueAt[x, y : integer] : TSurfaceValue read GetValueAt; default; property Intersects[Area : TRect] : boolean read GetIntersects; public function GetClone : TSurfaceModifier; procedure Delete; private procedure Render; public procedure LoadFromBackup( Reader : IBackupReader ); virtual; procedure StoreToBackup ( Writer : IBackupWriter ); virtual; private fToBeDeleted : boolean; // IAreaAgent private function getAgentArea : TRect; // IUnknown private function QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; function _AddRef : integer; stdcall; function _Release : integer; stdcall; end; TSurfaceIntegrator = class public constructor Create( aSurfaceId : TSurfaceId; anArea : TRect ); overload; constructor Create( aSurfaceId : TSurfaceId; aReference : IAreaAgent ); overload; destructor Destroy; override; private fSurface : TSurface; fArea : TRect; fValueLock : TCriticalSection; fValue : TSurfaceValue; fReference : IAreaAgent; private function GetValue : TSurfaceValue; function GetMedia : TSurfaceValue; public property Value : TSurfaceValue read GetValue; property Media : TSurfaceValue read GetMedia; public procedure Integrate; procedure Delete; public procedure LoadFromBackup( Reader : IBackupReader ); virtual; procedure StoreToBackup ( Writer : IBackupWriter ); virtual; end; TIntegratorPool = class public constructor Create; destructor Destroy; override; private fIntegrators : TLockableCollection; fNewMeat : TLockableCollection; fDeadMeat : TLockableCollection; public procedure IntegrateAll; end; type EIntegratorException = class( Exception ); procedure InitSurfaces; procedure RegisterBackup; implementation uses ClassStorage, MathUtils, Logs; const tidLog_Survival = 'Survival'; // TSurfacePool constructor TSurfacePool.Create; begin inherited Create; fSurfaces := TLockableCollection.Create( 0, rkBelonguer ); end; destructor TSurfacePool.Destroy; begin fSurfaces.Free; inherited; end; function TSurfacePool.GetSurface( id : TSurfaceId ) : TSurface; var i : integer; begin fSurfaces.Lock; try i := 0; while (i < fSurfaces.Count) and (TSurface(fSurfaces[i]).Id <> id) do inc( i ); if i < fSurfaces.Count then result := TSurface(fSurfaces[i]) else result := nil; finally fSurfaces.Unlock; end; end; procedure TSurfacePool.AddSurface( Surface : TSurface ); begin fSurfaces.Insert( Surface ); end; procedure TSurfacePool.Update; var i : integer; begin for i := 0 to pred(fSurfaces.Count) do TSurface(fSurfaces[i]).Update; end; // TSurface constructor TSurface.Create( anId : TSurfaceId; aName : string ); var SurfacePool : TSurfacePool; begin inherited Create; fId := anId; fName := aName; fModifiers := TLockableCollection.Create( 0, rkBelonguer ); SurfacePool := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces]); SurfacePool.AddSurface( self ); end; destructor TSurface.Destroy; begin fModifiers.Free; if fMatrix <> nil then fMatrix.Free; inherited; end; procedure TSurface.AddModifier( Modifier : TSurfaceModifier ); begin if fModifiers.IndexOf(Modifier) = noIndex then fModifiers.Insert( Modifier ) else Logs.Log('Modifiers', DateTimeToStr(Now) + Format(' Mofifier repeated position %d, %d.', [Modifier.Origin.x, Modifier.Origin.y])); end; procedure TSurface.DelModifier( Modifier : TSurfaceModifier ); begin //Logs.Log('Modifiers', DateTimeToStr(Now) + ' >> ' + Modifier.ClassName + ' ' + IntToStr(integer(Modifier))); fModifiers.Extract(Modifier); //fModifiers.Delete( Modifier ); // >> Otherwise kaboom!!! end; function TSurface.GetValue( x, y : integer ) : TSurfaceValue; var Modifiers : TCollection; i : integer; begin if fMatrix <> nil then result := fMatrix[y, x] else begin Modifiers := AreaModifiers[Rect(x, y, x + 1, y + 1)]; result := 0; for i := 0 to pred(Modifiers.Count) do result := result + TSurfaceModifier(Modifiers[i])[x, y]; Modifiers.Free; end; end; procedure TSurface.SetSize( xSize, ySize : integer ); begin fMatrix := TSingleLargeMatrix.Create( ySize, xSize, 16 ); end; procedure TSurface.Update; var i : integer; SM : TSurfaceModifier; Area : integer; begin try Area := 0; Logs.LogMemReport(tidLog_Survival); Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' <SURF ' + Name ); fModifiers.Lock; try for i := pred(fModifiers.Count) downto 0 do try SM := TSurfaceModifier(fModifiers[i]); SM.Render; if SM.fToBeDeleted then DelModifier( SM ) else with SM.Area do inc(Area, (Right - Left)*(Bottom - Top)); except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' SURF ERROR ' + E.Message + ' at Modifier ' + IntToStr(i) ); end; finally fModifiers.Unlock; end; Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' SURF ' + Name + '> Area: ' + IntToStr(Area)); Logs.LogMemReport(tidLog_Survival); except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' SURF ERROR: ' + E.Message ); end; end; function TSurface.GetAreaModifiers( Area : TRect ) : TLockableCollection; var i : integer; begin result := TLockableCollection.Create( 0, rkBelonguer ); try fModifiers.Lock; try for i := 0 to pred(fModifiers.Count) do try if TSurfaceModifier(fModifiers[i]).Intersects[Area] then result.Insert( TSurfaceModifier(fModifiers[i]).GetClone ); except end finally fModifiers.Unlock; end; except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' GetAreaModifiers ERROR: ' + E.Message ); end; end; function TSurface.getCols : integer; begin if fMatrix <> nil then result := fMatrix.Cols else result := 0; end; function TSurface.getRows : integer; begin if fMatrix <> nil then result := fMatrix.Rows else result := 0; end; procedure TSurface.setDimensions( n, m : integer ); begin end; function TSurface.getElement( i, j : integer ) : single; begin result := GetValue( j, i ); end; procedure TSurface.setElement( i, j : integer; value : single ); begin end; function TSurface.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TSurface._AddRef : integer; stdcall; begin result := 1; end; function TSurface._Release : integer; stdcall; begin result := 1; end; // TSurfaceModifier constructor TSurfaceModifier.Create( aSurfaceId : TSurfaceId; anOrigin : TPoint; aValue, aStrength : TSurfaceValue ); begin inherited Create; fOrigin := anOrigin; fNewValue := aValue; fStrength := aStrength; if aSurfaceId <> '' then begin fSurface := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces])[aSurfaceId]; fSurface.AddModifier( self ); end; end; destructor TSurfaceModifier.Destroy; begin inherited; end; function TSurfaceModifier.GetIntersects( anArea : TRect ) : boolean; var useless : TRect; begin result := IntersectRect( useless, Area, anArea ); end; function TSurfaceModifier.GetModified : boolean; begin result := abs(fValue - fNewValue) > 0.5; //fValue <> fNewValue; end; procedure TSurfaceModifier.SetValue( aValue : TSurfaceValue ); begin fNewValue := aValue; end; procedure TSurfaceModifier.SetStrength( aStrength : TSurfaceValue ); begin fStrength := aStrength; end; function TSurfaceModifier.GetClone : TSurfaceModifier; begin result := CSurfaceModifier(ClassType).Create( '', Origin, Value, Strength ); end; procedure TSurfaceModifier.Delete; begin Value := 0; fToBeDeleted := true; { if fSurface <> nil then fSurface.DelModifier( self ); } end; procedure TSurfaceModifier.Render; var x, y : integer; R : TRect; begin if (fSurface.fMatrix <> nil) and Modified then begin R := Area; // Remove old values for x := R.Left to min(R.Right - 1, fSurface.fMatrix.Cols) do for y := R.Top to min(R.Bottom - 1, fSurface.fMatrix.Rows) do fSurface.fMatrix.IncElement( y, x, -ValueAt[x, y] ); // fSurface.fMatrix[y, x] := fSurface.fMatrix[y, x] - ValueAt[x, y]; // Set new values fValue := fNewValue; Update; R := Area; for x := R.Left to min(R.Right - 1, fSurface.fMatrix.Cols) do for y := R.Top to min(R.Bottom - 1, fSurface.fMatrix.Rows) do fSurface.fMatrix.IncElement( y, x, ValueAt[x, y] ); // fSurface.fMatrix[y, x] := fSurface.fMatrix[y, x] + ValueAt[x, y]; end; end; procedure TSurfaceModifier.LoadFromBackup( Reader : IBackupReader ); var Name : string; begin fOrigin.x := Reader.ReadInteger( 'Origin.x', 0 ); fOrigin.y := Reader.ReadInteger( 'Origin.y', 0 ); fNewValue := Reader.ReadSingle( 'Value', 0 ); fStrength := Reader.ReadSingle( 'Strength', 0 ); Name := Reader.ReadString( 'Surface', '' ); if Name <> '' then fSurface := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces])[Name]; end; procedure TSurfaceModifier.StoreToBackup( Writer : IBackupWriter ); begin Writer.WriteInteger( 'Origin.x', fOrigin.x ); Writer.WriteInteger( 'Origin.y', fOrigin.y ); Writer.WriteSingle( 'Value', fNewValue ); Writer.WriteSingle( 'Strength', fStrength ); if fSurface <> nil then Writer.WriteString( 'Surface', fSurface.Id ) else Writer.WriteString( 'Surface', '' ) end; function TSurfaceModifier.getAgentArea : TRect; begin result := Area; end; function TSurfaceModifier.QueryInterface(const IID: TGUID; out Obj): hresult; stdcall; begin pointer(Obj) := nil; result := E_FAIL; end; function TSurfaceModifier._AddRef : integer; stdcall; begin result := 1; end; function TSurfaceModifier._Release : integer; stdcall; begin result := 1; end; // TSurfaceIntegrator constructor TSurfaceIntegrator.Create( aSurfaceId : TSurfaceId; anArea : TRect ); var SurfacePool : TSurfacePool; IntegratorPool : TIntegratorPool; begin inherited Create; fValueLock := TCriticalSection.Create; SurfacePool := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces]); fSurface := SurfacePool[aSurfaceId]; if fSurface <> nil then begin fArea := anArea; IntegratorPool := TIntegratorPool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Integrators]); IntegratorPool.fNewMeat.Insert( self ); end else raise EIntegratorException.Create( 'Cannot find surface "' + aSurfaceId + '"' ); end; constructor TSurfaceIntegrator.Create( aSurfaceId : TSurfaceId; aReference : IAreaAgent ); begin Create( aSurfaceId, aReference.getAgentArea ); fReference := aReference; end; destructor TSurfaceIntegrator.Destroy; begin fValueLock.Free; inherited; end; function TSurfaceIntegrator.GetValue : TSurfaceValue; begin fValueLock.Enter; try result := fValue; finally fValueLock.Leave; end; end; function TSurfaceIntegrator.GetMedia : TSurfaceValue; begin fValueLock.Enter; try try result := Value/abs((fArea.Left - fArea.Right)*(fArea.Top - fArea.Bottom)); except result := 0; end; finally fValueLock.Leave; end; end; procedure TSurfaceIntegrator.Integrate; var x, y : integer; Sum : TSurfaceValue; tmpArea : TRect; begin fValueLock.Enter; try if fReference <> nil then try tmpArea := fReference.getAgentArea except on E : Exception do begin fReference := nil; tmpArea := fArea; Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' ERROR getting reference area in integrator: ' + E.Message ); end; end else tmpArea := fArea; finally fValueLock.Leave; end; tmpArea.Top := max( 0, tmpArea.Top ); tmpArea.Left := max( 0, tmpArea.Left ); tmpArea.Bottom := min( fSurface.getRows, tmpArea.Bottom ); tmpArea.Right := min( fSurface.getCols, tmpArea.Right ); Sum := 0; for y := tmpArea.Top to tmpArea.Bottom do for x := tmpArea.Left to tmpArea.Right do Sum := Sum + fSurface.Value[x, y]; fValueLock.Enter; try fValue := Sum; finally fValueLock.Leave; end; end; procedure TSurfaceIntegrator.Delete; var IntegratorPool : TIntegratorPool; begin IntegratorPool := TIntegratorPool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Integrators]); IntegratorPool.fDeadMeat.Insert( self ); end; procedure TSurfaceIntegrator.LoadFromBackup( Reader : IBackupReader ); var SurfacePool : TSurfacePool; IntegratorPool : TIntegratorPool; SurfaceId : string; begin fValueLock := TCriticalSection.Create; SurfacePool := TSurfacePool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Surfaces]); SurfaceId := Reader.ReadString( 'Surface', '' ); fSurface := SurfacePool[SurfaceId]; if fSurface <> nil then begin fArea.Left := Reader.ReadInteger( 'Area.Left', 0 ); fArea.Top := Reader.ReadInteger( 'Area.Top', 0 ); fArea.Right := Reader.ReadInteger( 'Area.Right', 0 ); fArea.Bottom := Reader.ReadInteger( 'Area.Bottom', 0 ); IntegratorPool := TIntegratorPool(TheClassStorage.ClassById[tidClassFamily_SurfacePools, tidSurfacePool_Integrators]); IntegratorPool.fNewMeat.Insert( self ); end else raise EIntegratorException.Create( 'Cannot find surface."' ); end; procedure TSurfaceIntegrator.StoreToBackup( Writer : IBackupWriter ); begin Writer.WriteString( 'Surface', fSurface.Id ); Writer.WriteInteger( 'Area.Left', fArea.Left ); Writer.WriteInteger( 'Area.Top', fArea.Top ); Writer.WriteInteger( 'Area.Right', fArea.Right ); Writer.WriteInteger( 'Area.Bottom', fArea.Bottom ); end; // TIntegratorPool constructor TIntegratorPool.Create; begin inherited Create; fIntegrators := TLockableCollection.Create( 0, rkBelonguer ); fNewMeat := TLockableCollection.Create( 0, rkBelonguer ); fDeadMeat := TLockableCollection.Create( 0, rkBelonguer ); end; destructor TIntegratorPool.Destroy; begin fIntegrators.Free; fNewMeat.Free; fDeadMeat.Free; inherited; end; procedure TIntegratorPool.IntegrateAll; procedure ReleaseMeat; begin fNewMeat.Lock; try while fNewMeat.Count > 0 do begin fIntegrators.Insert( fNewMeat[0] ); fNewMeat.AtExtract( 0 ); end; finally fNewMeat.Unlock; end; fDeadMeat.Lock; try while fDeadMeat.Count > 0 do begin fIntegrators.Extract( fDeadMeat[0] ); // fDeadMeat.AtDelete( 0 ); >> Garbage Collection fDeadMeat.AtExtract( 0 ); end; finally fDeadMeat.Unlock; end; end; var i : integer; begin fIntegrators.Lock; try try ReleaseMeat; except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' Integrator Release Meat ERROR: ' + E.Message ); end; for i := pred(fIntegrators.Count) downto 0 do with TSurfaceIntegrator(fIntegrators[i]) do try Integrate; except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' Integrator No. ' + IntToStr(i) + ' ERROR: ' + E.Message ); end; finally fIntegrators.Unlock; end; end; // TSurfaceModifierBackupAgent type TSurfaceModifierBackupAgent = class(TBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; class procedure TSurfaceModifierBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); begin TSurfaceModifier(Obj).StoreToBackup(Stream); end; class procedure TSurfaceModifierBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin TSurfaceModifier(Obj).LoadFromBackup(Stream); if TSurfaceModifier(Obj).fSurface <> nil then TSurfaceModifier(Obj).fSurface.AddModifier( TSurfaceModifier(Obj) ); end; // TSurfaceIntegratorBackupAgent type TSurfaceIntegratorBackupAgent = class(TBackupAgent) protected class procedure Write(Stream : IBackupWriter; Obj : TObject); override; class procedure Read (Stream : IBackupReader; Obj : TObject); override; end; class procedure TSurfaceIntegratorBackupAgent.Write(Stream : IBackupWriter; Obj : TObject); begin TSurfaceIntegrator(Obj).StoreToBackup(Stream); end; class procedure TSurfaceIntegratorBackupAgent.Read(Stream : IBackupReader; Obj : TObject); begin TSurfaceIntegrator(Obj).LoadFromBackup(Stream); end; // RegisterBackup procedure RegisterBackup; begin TSurfaceModifierBackupAgent.Register( [TSurfaceModifier] ); TSurfaceIntegratorBackupAgent.Register( [TSurfaceIntegrator] ); end; // InitSurfaces procedure InitSurfaces; begin TheClassStorage.RegisterClass( tidClassFamily_SurfacePools, tidSurfacePool_Surfaces, TSurfacePool.Create ); TheClassStorage.RegisterClass( tidClassFamily_SurfacePools, tidSurfacePool_Integrators, TIntegratorPool.Create ); end; end.
unit MainFm; interface uses PXT.Types, Windows, System.Classes, System.SysUtils, Vcl.Forms, Vcl.Controls, Vcl.Graphics, Vcl.Dialogs, PXT.Graphics, PXT.Controls, PXT.Canvas, Vcl.StdCtrls, Generics.Collections, PXT.Sprites; type TEnemyKind = (Ship, SquareShip, AnimShip, Mine); TMapRec = record X, Y, Z: Integer; ImageName: string[50]; end; TBullet = class(TAnimatedSprite) private DestAngle: Single; FMoveSpeed: Integer; FCounter: Integer; public constructor Create(const AParent: TSprite); override; procedure DoMove(const MoveCount: Single); override; property MoveSpeed: Integer read FMoveSpeed write FMoveSpeed; end; TPlayerBullet = class(TAnimatedSprite) private FDestX, FDestY: Integer; FCounter: Integer; FMoveSpeed: Integer; public procedure DoMove(const MoveCount: Single); override; procedure DoCollision(const Sprite: TSprite); override; property DestX: Integer read FDestX write FDestX; property DestY: Integer read FDestY write FDestY; property MoveSpeed: Integer read FMoveSpeed write FMoveSpeed; end; TEnemy = class(TAnimatedSprite) private FMoveSpeed: Single; FTempMoveSpeed: Single; FRotateSpeed: Single; FDestX, FDestY: Integer; FDestAngle: Integer; FLookAt: Boolean; FKind: TEnemyKind; FLife: Integer; FBullet: TBullet; public function InOffScreen: Boolean; procedure DoMove(const MoveCount: Single); override; property Kind: TEnemyKind read FKind write FKind; property MoveSpeed: Single read FMoveSpeed write FMoveSpeed; property TempMoveSpeed: Single read FTempMoveSpeed write FTempMoveSpeed; property RotateSpeed: Single read FRotateSpeed write FRotateSpeed; property DestX: Integer read FDestX write FDestX; property DestY: Integer read FDestY write FDestY; property DestAngle: Integer read FDestAngle write FDestAngle; property LookAt: Boolean read FLookAt write FLookAt; property Life: Integer read FLife write FLife; property Bullet: TBullet read FBullet write FBullet; end; TAsteroids = class(TAnimatedSprite) private FStep: Single; FMoveSpeed: Single; FRange: Single; FSeed: Integer; FPosX: Integer; FPosY: Integer; FLife: Integer; public procedure DoMove(const MoveCount: Single); override; property MoveSpeed: Single read FMoveSpeed write FMoveSpeed; property Step: Single read FStep write FStep; property Seed: Integer read FSeed write FSeed; property Range: Single read FRange write FRange; property PosX: Integer read FPosX write FPosX; property PosY: Integer read FPosY write FPosY; property Life: Integer read FLife write FLife; end; TFort = class(TAnimatedSprite) private FLife: Integer; FBullet: TBullet; public procedure DoMove(const MoveCount: Single); override; property Bullet: TBullet read FBullet write FBullet; property Life: Integer read FLife write FLife; end; TPlayerShip = class(TPlayerSprite) private FDoAccelerate: Boolean; FDoDeccelerate: Boolean; FLife: Single; FBullet: TPlayerBullet; FReady: Boolean; FReadyTime: Integer; public procedure DoMove(const MoveCount: Single); override; procedure DoCollision(const Sprite: TSprite); override; property DoAccelerate: Boolean read FDoAccelerate write FDoAccelerate; property DoDeccelerate: Boolean read FDoDeccelerate write FDoDeccelerate; property Bullet: TPlayerBullet read FBullet write FBullet; property Life: Single read FLife write FLife; end; TTail = class(TPlayerSprite) private FCounter: Integer; public procedure DoMove(const MoveCount: Single); override; property Counter: Integer read FCounter write FCounter; end; TExplosion = class(TPlayerSprite) public procedure DoMove(const MoveCount: Single); override; end; TSpark = class(TPlayerSprite) public procedure DoMove(const MoveCount: Single); override; end; TBonus = class(TAnimatedSprite) private FPX, FPY: Single; FStep: Single; FMoveSpeed: Single; public procedure DoMove(const MoveCount: Single); override; property PX: Single read FPX write FPX; property PY: Single read FPY write FPY; property Step: Single read FStep write FStep; property MoveSpeed: Single read FMoveSpeed write FMoveSpeed; end; TMainForm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FDisplaySize: TPoint2i; FDisplayScale: Single; FDevice: TDevice; FCanvas: TCanvas; FTextRenderer: TTextRenderer; DrawableTexture: TTexture; SourceTexture: TTexture; CursorX, CursorY: Integer; SpaceLayer, MistLayer1, MistLayer2: TSpriteEngine; SpriteEngine: TSpriteEngine; PlayerShip: TPlayerShip; FileSize: Integer; MapData: array of TMapRec; Score: Integer; DisplaySize: TPoint2i; GameFont: TTextRenderer; GameCanvas: TGameCanvas; procedure LoadTexture(FileName: string); procedure TimerEvent(Sender: TObject); procedure RenderEvent; procedure LoadMap(FileName: string); procedure CreateMap(OffsetX, OffsetY: Integer); procedure CreateSpark(PosX, PosY: Single); procedure CreateBonus(BonusName: string; PosX, PosY: Single); public end; var MainForm: TMainForm; implementation uses PXT.Headers, AsphyreTimer, System.Types, PXT.TypesEx, StrUtils, MMsystem, Bass; {$R *.dfm} var GameImages: TDictionary<string, TTexture>; hs: HSTREAM; procedure PlaySound(FileName: AnsiString); begin hs := BASS_StreamCreateFile(False, PAnsiChar('Sounds/' + FileName), 0, 0, 0); BASS_ChannelPlay(hs, False); end; procedure TMainForm.LoadTexture(FileName: string); begin var Texture := TextureInit(MainForm.FDevice, FileName, PXT.Types.TPixelFormat.RGBA8); GameImages.Add(ChangeFileExt(ExtractFileName(FileName), ''), Texture); end; procedure TMainForm.FormCreate(Sender: TObject); var LParameters: TTextureParameters; const RandNumber: array[0..1] of string = ('-0.15', '0.15'); begin GameImages := TDictionary<string, TTexture>.Create; FDisplaySize := Point2i(ClientWidth, ClientHeight); FDevice := DeviceInit(TDeviceBackend.Default, Handle, Point2i(1024, 768), PXT.Types.TPixelFormat.BGRA8, PXT.Types.TPixelFormat.Unknown, 0, DeviceAttributes([TDeviceAttribute.VSync])); FDevice.Resize(Point2i(1024, 768)); if not FDevice.Initialized then begin MessageDlg('Could not create rendering device.', mtError, [mbOK], 0); Application.Terminate; Exit; end; GameCanvas.Create(FDevice); FTextRenderer := TextRendererInit(GameCanvas, Point2i(512, 512)); if not FTextRenderer.Initialized then begin MessageDlg('Could not create text renderer.', mtError, [mbOK], 0); Application.Terminate; Exit; end; SpriteEngine := TSpriteEngine.Create(nil); SpriteEngine.Canvas := GameCanvas; SpriteEngine.VisibleWidth := 1800; SpriteEngine.VisibleHeight := 1600; // SpaceLayer := TSpriteEngine.Create(nil); SpaceLayer.Canvas := GameCanvas; SpaceLayer.VisibleWidth := 1800; SpaceLayer.VisibleHeight := 1600; // MistLayer1 := TSpriteEngine.Create(nil); MistLayer1.Canvas := GameCanvas; MistLayer1.VisibleWidth := 1800; MistLayer1.VisibleHeight := 1600; // MistLayer2 := TSpriteEngine.Create(nil); MistLayer2.Canvas := GameCanvas; MistLayer2.VisibleWidth := 1800; MistLayer2.VisibleHeight := 1600; var FileSearchRec: TSearchRec; if FindFirst(ExtractFilePath(ParamStr(0)) + 'Gfx\' + '*.png', faAnyfile, FileSearchRec) = 0 then repeat LoadTexture('Gfx\' + FileSearchRec.Name); until FindNext(FileSearchRec) <> 0; LoadTexture('Gfx\Space.jpg'); // create enemys for var I := 0 to 400 do begin with TEnemy.Create(SpriteEngine) do begin ImageLib := GameImages; Kind := TEnemyKind(Random(4)); DrawMode := 1; X := Random(8000) - 2500; Y := Random(8000) - 2500; Z := 10000; Collisioned := True; MoveSpeed := 1 + (Random(4) * 0.5); RotateSpeed := 0.5 + (Random(4) * 0.4); Life := 4; case Kind of Ship: begin ImageName := 'Ship' + IntToStr(Random(2)); SetPattern(128, 128); CollideRadius := 40; ScaleX := 0.7; ScaleY := 0.8; end; SquareShip: begin ImageName := 'SquareShip' + IntToStr(Random(2)); CollideRadius := 30; LookAt := True; if ImageName = 'SquareShip0' then SetPattern(60, 62) else SetPattern(72, 62); end; AnimShip: begin ImageName := 'AnimShip' + IntToStr(Random(2)); CollideRadius := 25; // ScaleX := 1.1; // ScaleY := 1.1; if ImageName = 'AnimShip1' then begin SetPattern(64, 64); SetAnim(ImageName, 0, 8, 0.2, True, False, True); end; if ImageName = 'AnimShip0' then begin SetPattern(48, 62); SetAnim(ImageName, 0, 4, 0.08, True, False, True); end; end; Mine: begin ImageName := 'Mine0'; SetPattern(64, 64); CollideRadius := 16; RotateSpeed := 0.04; end; end; TempMoveSpeed := MoveSpeed; Width := PatternWidth; Height := PatternHeight; end; end; // create asteroids for var I := 0 to 500 do with TAsteroids.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := 'Roids' + IntToStr(Random(3)); PosX := Random(8000) - 2500; PosY := Random(8000) - 2500; Z := 4800; DrawMode := 1; DoCenter := True; if ImageName = 'Roids0' then begin SetPattern(64, 64); AnimSpeed := 0.2; end; if ImageName = 'Roids1' then begin SetPattern(96, 96); AnimSpeed := 0.16; end; if ImageName = 'Roids2' then begin SetPattern(128, 128); AnimSpeed := 0.25; end; SetAnim(ImageName, 0, PatternCount, 0.15, True, False, True); MoveSpeed := RandomFrom(RandNumber).ToSingle; Range := 150 + Random(200); Step := (Random(1512)); Seed := 50 + Random(100); Life := 6; ScaleX := 1; ScaleY := 1; Collisioned := True; if ImageName = 'Roids0' then CollideRadius := 32; if ImageName = 'Roids1' then CollideRadius := 48; if ImageName = 'Roids2' then CollideRadius := 50; Width := PatternWidth; Height := PatternHeight; end; // create player's ship PlayerShip := TPlayerShip.Create(SpriteEngine); with PlayerShip do begin ImageLib := GameImages; ImageName := 'PlayerShip'; SetPattern(64, 64); Width := PatternWidth; Height := PatternHeight; ScaleX := 1.2; ScaleY := 1.2; DoCenter := True; DrawMode := 1; Acceleration := 0.02; Decceleration := 0.02; MinSpeed := 0; Maxspeed := 4.5; Z := 5000; Collisioned := True; CollideRadius := 25; end; LoadMap('Level1.map'); CreateMap(500, 500); // create planet for var I := 0 to 100 do begin with TSpriteEx.Create(SpaceLayer) do begin ImageLib := GameImages; ImageName := 'planet' + IntToStr(Random(4)); Width := ImageWidth; Height := ImageHeight; X := (Random(25) * 300) - 2500; Y := (Random(25) * 300) - 2500; Z := 100; Moved := False; end; end; // create a huge endless space with TBackgroundSprite.Create(SpaceLayer) do begin ImageLib := GameImages; ImageName := 'Space'; SetPattern(512, 512); Width := PatternWidth; Height := PatternHeight; SetMapSize(1, 1); Tiled := True; TileMode := tmFull; Moved := False; end; // create mist layer1 with TBackgroundSprite.Create(MistLayer1) do begin ImageLib := GameImages; ImageName := 'Mist'; SetPattern(1024, 1024); Width := PatternWidth; Height := PatternHeight; BlendingEffect := TBlendingEffect.Add; SetMapSize(1, 1); Tiled := True; TileMode := tmFull; Moved := False; end; // create mist layer2 with TBackgroundSprite.Create(MistLayer2) do begin ImageLib := GameImages; ImageName := 'Mist'; SetPattern(1024, 1024); X := 200; Y := 200; Width := PatternWidth; Height := PatternHeight; BlendingEffect := TBlendingEffect.Add; SetMapSize(1, 1); Tiled := True; TileMode := tmFull; Moved := False; end; Screen.Cursor := crNone; Timer.OnTimer := TimerEvent; Timer.Speed := 60.0; Timer.MaxFPS := 4000; Timer.Enabled := True; if not BASS_Init(-1, 44100, 0, 0, nil) then ShowMessage('ªì©l¤Æ¿ù»~'); MCISendString(PChar('play ' + 'Sounds\music1.mid'), nil, 0, 0); end; function Timex: Real; {$J+} const Start: Int64 = 0; frequency: Int64 = 0; {$J-} var Counter: Int64; begin if Start = 0 then begin QueryPerformanceCounter(Start); QueryPerformanceFrequency(frequency); Result := 0; end; Counter := 0; QueryPerformanceCounter(Counter); Result := (Counter - Start) / frequency; end; var CurrentTime: Double; Accumulator: Double; NewTime, DeltaTime: Double; Counter: Integer; procedure TMainForm.TimerEvent(Sender: TObject); const dt = 1 / 60; begin NewTime := Timex; DeltaTime := NewTime - CurrentTime; if DeltaTime > 0.016666 then DeltaTime := 0.016666; CurrentTime := NewTime; Accumulator := Accumulator + DeltaTime; while (Accumulator >= dt) do begin SpriteEngine.Dead; SpriteEngine.Move(1); SpaceLayer.WorldX := SpriteEngine.WorldX * 0.71; SpaceLayer.WorldY := SpriteEngine.WorldY * 0.71; MistLayer1.WorldX := SpriteEngine.WorldX * 1.1; MistLayer1.WorldY := SpriteEngine.WorldY * 1.1; MistLayer2.WorldX := SpriteEngine.WorldX * 1.3; MistLayer2.WorldY := SpriteEngine.WorldY * 1.3; Inc(Counter); if (Counter mod 4) = 0 then if PlayerShip.ImageName = 'PlayerShip' then begin with TTail.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := 'tail'; SetPattern(64, 64); Width := PatternWidth; Height := PatternHeight; BlendingEffect := TBlendingEffect.Add; DrawMode := 1; ScaleX := 0.1; ScaleY := 0.1; X := 510 + Engine.WorldX; Y := 382 + Engine.WorldY; Z := 4000; Acceleration := 2.51; MinSpeed := 1; if PlayerShip.Speed < 1 then Maxspeed := 2 else Maxspeed := 0.5; Direction := -128 + PlayerShip.Direction; end; end; Accumulator := Accumulator - dt; end; FDevice.BeginScene; FDevice.Clear([TClearLayer.Color], FloatColor($FFFFC800)); GameCanvas.BeginScene; RenderEvent; GameCanvas.EndScene; FDevice.EndScene; end; procedure TMainForm.RenderEvent; begin SpaceLayer.Draw; MistLayer1.Draw; MistLayer2.Draw; SpriteEngine.Draw; var Angle := Angle256(Trunc(CursorX) - 512, Trunc(CursorY) - 384) * 0.025; GameCanvas.DrawRotate(GameImages['cursor'], CursorX, CursorY, 15, 35, Angle, 1, $FFFFFFFF, TBlendingEffect.Add); GameCanvas.DrawPattern(GameImages['Shield'], 20, 640, -Trunc(PlayerShip.Life), 111, 105, False, $FFFFFFFF); var LFontSettings := TFontSettings.Create('Tahoma', 28.0, TFontWeight.Bold); LFontSettings.Effect.ShadowBrightness := 0.5; LFontSettings.Effect.ShadowOpacity := 1.0; LFontSettings.Effect.BorderType := TFontBorder.SemiHeavy; FTextRenderer.FontSettings := LFontSettings; FTextRenderer.DrawCentered(Point2f(500, 20), Score.ToString, ColorPair($FF0000FF, $FF00FFFF)); end; procedure TMainForm.FormDestroy(Sender: TObject); begin SpriteEngine.Free; SpaceLayer.Free; MistLayer1.Free; MistLayer2.Free; GameImages.Free; FTextRenderer.Free; FCanvas.Free; FDevice.Free; end; procedure TMainForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbRight then begin CursorX := X; CursorY := Y; PlayerShip.DoAccelerate := True; PlayerShip.DoDeccelerate := False; end; if (Button = mbLeft) and (PlayerShip.ImageName = 'PlayerShip') then begin PlaySound('Shoot.wav'); PlayerShip.Bullet := TPlayerBullet.Create(SpriteEngine); with PlayerShip.Bullet do begin ImageLib := GameImages; ImageName := 'bb'; SetPattern(24, 36); Width := PatternWidth; Height := PatternHeight; ScaleX := 1; ScaleY := 1; DrawMode := 1; BlendingEffect := TBlendingEffect.Add; DoCenter := True; MoveSpeed := 9; Angle := PlayerShip.Angle + 0.05; X := PlayerShip.X; Y := PlayerShip.Y; Z := 11000; Collisioned := True; CollideRadius := 10; end; end; end; procedure TMainForm.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin CursorX := X; CursorY := Y; end; procedure TMainForm.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbRight then begin PlayerShip.DoAccelerate := False; PlayerShip.DoDeccelerate := True; end; end; procedure TMainForm.LoadMap(FileName: string); var Fs: TFileStream; begin Fs := TFileStream.Create(ExtractFilePath(Application.ExeName) + FileName, fmOpenRead); Fs.ReadBuffer(FileSize, SizeOf(FileSize)); SetLength(MapData, FileSize); Fs.ReadBuffer(MapData[0], SizeOf(TMapRec) * FileSize); Fs.Destroy; end; procedure TMainForm.CreateMap(OffsetX, OffsetY: Integer); var I: Integer; begin for I := 0 to FileSize - 1 do begin if LeftStr(MapData[I].ImageName, 4) = 'Tile' then begin with TSprite.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := LowerCase(MapData[I].ImageName); Width := ImageWidth; Height := ImageHeight; X := MapData[I].X + OffsetX - 2500; Y := MapData[I].Y + OffsetY - 2500; Z := MapData[I].Z; Moved := False; end; end; // if LeftStr(MapData[I].ImageName, 4) = 'Fort' then begin with TFort.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := LowerCase(MapData[I].ImageName); SetPattern(44, 77); DrawMode := 1; DoCenter := True; Width := PatternWidth; Height := PatternHeight; X := MapData[I].X + OffsetX - 2500 + 22; Y := MapData[I].Y + OffsetY - 2500 + 40; Z := MapData[I].Z; Collisioned := True; CollideRadius := 24; Life := 5; end; end; end; end; procedure TMainForm.CreateSpark(PosX, PosY: Single); var I, Pattern: Integer; const RandNumber: array[0..1] of string = ('5', '9'); begin Pattern := RandomFrom(RandNumber).ToInteger; for I := 0 to 128 do begin with TSpark.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := 'Particles'; SetPattern(32, 32); Width := PatternWidth; Height := PatternHeight; BlendingEffect := TBlendingEffect.Add; X := PosX + -Random(30); Y := PosY + Random(30); Z := 12000; PatternIndex := Pattern; ScaleX := 1.2; ScaleY := 1.2; Red := Random(250); Green := Random(250); Blue := Random(250); Acceleration := 0.02; MinSpeed := 0.8; Maxspeed := -(0.4 + Random(2)); Direction := I * 2; end; end; end; procedure TMainForm.CreateBonus(BonusName: string; PosX, PosY: Single); begin if (Random(3) = 1) or (Random(3) = 2) then begin with TBonus.Create(SpriteEngine) do begin ImageLib := GameImages; ImageName := BonusName; SetPattern(32, 32); Width := PatternWidth; Height := PatternHeight; MoveSpeed := 0.251; PX := PosX - 50; PY := PosY - 100; Z := 12000; ScaleX := 1.5; ScaleY := 1.5; DoCenter := True; Collisioned := True; CollideRadius := 24; SetAnim(ImageName, 0, PatternCount, 0.25, True, False, True); end; end; end; procedure TEnemy.DoMove(const MoveCount: Single); begin if (Life >= 1) and (ImageName <> 'Explosion2') then BlendingEffect := TBlendingEffect.Normal; if (InOffScreen) and (ImageName <> 'Explosion2') then MoveSpeed := TempMoveSpeed; if (Life <= 0) or (not InOffScreen) then MoveSpeed := 0; if Trunc(AnimPos) >= 15 then Dead; if (Trunc(AnimPos) >= 1) and (ImageName = 'Explosion2') then Collisioned := False; case Kind of Ship: begin CollidePos := Point(Round(X) + 64, Round(Y) + 64); case Random(100) of 40..43: begin DestAngle := Random(255); end; 51..52: begin DestAngle := Trunc(Angle256(Trunc(MainForm.PlayerShip.X) - Trunc(Self.X), Trunc(MainForm.PlayerShip.Y) - Trunc(Self.Y))); end; end; RotateToAngle(DestAngle, RotateSpeed, MoveSpeed); end; SquareShip: begin CollidePos := Point(Round(X) + 30, Round(Y) + 30); case Random(100) of 40..45: begin DestX := Random(8000); DestY := Random(6000) end; 51..52: begin DestX := Trunc(MainForm.PlayerShip.X); DestY := Trunc(MainForm.PlayerShip.Y); end; end; CircleToPos(DestX, DestY, Trunc(MainForm.PlayerShip.X), Trunc(MainForm.PlayerShip.Y), RotateSpeed, MoveSpeed, LookAt); end; AnimShip: begin CollidePos := Point(Round(X) + 20, Round(Y) + 20); case Random(100) of 40..45: begin DestX := Random(8000); DestY := Random(6000) end; 51..54: begin DestX := Trunc(MainForm.PlayerShip.X); DestY := Trunc(MainForm.PlayerShip.Y); end; end; RotateToPos(DestX, DestY, RotateSpeed, MoveSpeed); end; Mine: begin CollidePos := Point(Round(X) + 32, Round(Y) + 32); case Random(300) of 150: begin DestX := Trunc(MainForm.PlayerShip.X); DestY := Trunc(MainForm.PlayerShip.Y); end; 200..202: begin DestX := Random(8000); DestY := Random(8000); end; end; Angle := Angle + RotateSpeed; TowardToPos(DestX, DestY, MoveSpeed, False); end; end; // enemy shoot bullet if (Kind = Ship) or (Kind = SquareShip) then begin if InOffScreen then begin if Random(100) = 50 then begin Bullet := TBullet.Create(MainForm.SpriteEngine); Bullet.ImageName := 'bulletr'; Bullet.MoveSpeed := 5; Bullet.X := Self.X + 1; Bullet.Y := Self.Y; Bullet.DestAngle := Angle * 40; end; end; end; inherited; end; function TEnemy.InOffScreen: Boolean; begin if (X > Engine.WorldX - 50) and (Y > Engine.WorldY - 50) and (X < Engine.WorldX + 1124) and (Y < Engine.WorldY + 778) then Result := True else Result := False; end; constructor TBullet.Create(const AParent: TSprite); begin inherited; ImageLib := GameImages; SetPattern(40, 40); BlendingEffect := TBlendingEffect.Add; Z := 4000; FCounter := 0; DrawMode := 1; Collisioned := True; if ImageName = 'bulletr' then CollideRadius := 15; if ImageName = 'BulletS' then CollideRadius := 12; end; procedure TBullet.DoMove; begin inherited; CollidePos := Point(Round(X) + 20, Round(Y) + 20); TowardToAngle(Trunc(DestAngle), MoveSpeed, True); Inc(FCounter); if (Trunc(AnimPos) >= 15) and (ImageName = 'Explosion3') then Dead; if FCounter > 250 then Dead; end; procedure TPlayerBullet.DoMove; begin inherited; TowardToAngle(Trunc(Angle * 40), MoveSpeed, True); CollidePos := Point(Round(X) + 24, Round(Y) + 38); Inc(FCounter); if FCounter > 180 then Dead; if Trunc(AnimPos) >= 11 then Dead; Collision; end; procedure TPlayerBullet.DoCollision(const Sprite: TSprite); var I: Integer; begin if Sprite is TAsteroids then begin PlaySound('Hit.wav'); Collisioned := False; MoveSpeed := 0; SetPattern(64, 64); SetAnim('Explosions', 0, 12, 0.3, False, False, True); if Trunc(AnimPos) < 1 then TAsteroids(Sprite).BlendingEffect := TBlendingEffect.Shadow; TAsteroids(Sprite).Life := TAsteroids(Sprite).Life - 1; if (TAsteroids(Sprite).Life <= 0) then begin PlaySound('Explode.wav'); TAsteroids(Sprite).MoveSpeed := 0; for I := 0 to 128 do with TExplosion.Create(MainForm.SpriteEngine) do begin ImageLib := GameImages; ImageName := 'Particles'; SetPattern(32, 32); Width := PatternWidth; Height := PatternHeight; BlendingEffect := TBlendingEffect.Add; X := TAsteroids(Sprite).X + -Random(60); Y := TAsteroids(Sprite).Y - Random(60); Z := 4850; PatternIndex := 7; ScaleX := 3; ScaleY := 3; Red := 255; Green := 100; Blue := 101; Acceleration := 0.0252; MinSpeed := 1; Maxspeed := -(0.31 + Random(2)); Direction := I * 2; end; MainForm.CreateBonus('Money', TAsteroids(Sprite).X, TAsteroids(Sprite).Y); TAsteroids(Sprite).Dead; end; end; // if Sprite is TEnemy then begin PlaySound('Hit.wav'); Collisioned := False; MoveSpeed := 0; SetPattern(64, 64); SetAnim('Explosion3', 0, 12, 0.3, False, False, True); if Trunc(AnimPos) < 1 then TEnemy(Sprite).BlendingEffect := TBlendingEffect.Add; TEnemy(Sprite).Life := TEnemy(Sprite).Life - 1; if TEnemy(Sprite).Life <= 0 then begin TEnemy(Sprite).MoveSpeed := 0; TEnemy(Sprite).RotateSpeed := 0; TEnemy(Sprite).DestAngle := 0; TEnemy(Sprite).LookAt := False; TEnemy(Sprite).BlendingEffect := TBlendingEffect.Add; TEnemy(Sprite).ScaleX := 3; TEnemy(Sprite).ScaleY := 3; TEnemy(Sprite).SetPattern(64, 64); TEnemy(Sprite).SetAnim('Explosion2', 0, 16, 0.15, False, False, True); MainForm.CreateBonus('Bonus' + IntToStr(Random(3)), X, Y); end; end; // if Sprite is TFort then begin PlaySound('Hit.wav'); Collisioned := False; MoveSpeed := 0; SetPattern(64, 64); SetAnim('Explosion3', 0, 12, 0.3, False, False, True); if Trunc(AnimPos) < 3 then TFort(Sprite).SetColor(255, 0, 0); TFort(Sprite).Life := TFort(Sprite).Life - 1; if TFort(Sprite).Life <= 0 then begin TFort(Sprite).BlendingEffect := TBlendingEffect.Add; TFort(Sprite).ScaleX := 3; TFort(Sprite).ScaleY := 3; TFort(Sprite).SetPattern(64, 64); TFort(Sprite).SetAnim('Explosion2', 0, 16, 0.15, False, False, True); end; end; end; procedure TAsteroids.DoMove(const MoveCount: Single); begin inherited; X := PosX + Cos(Step / (30)) * Range - (Sin(Step / (20)) * Range); Y := PosY + Sin(Step / (30 + Seed)) * Range + (Cos(Step / (20)) * Range); Step := Step + MoveSpeed; if ImageName = 'Roids2' then Angle := Angle + 0.02; if ImageName = 'Roids0' then CollidePos := Point(Round(X) + 32, Round(Y) + 32); if ImageName = 'Roids1' then CollidePos := Point(Round(X) + 30, Round(Y) + 30); if ImageName = 'Roids2' then CollidePos := Point(Round(X) + 34, Round(Y) + 34); BlendingEffect := TBlendingEffect.Normal; end; procedure TFort.DoMove(const MoveCount: Single); begin inherited; SetColor(255, 255, 255); if ImageName = 'fort' then LookAt(Trunc(MainForm.PlayerShip.X), Trunc(MainForm.PlayerShip.Y)); CollidePos := Point(Round(X) + 22, Round(Y) + 36); if Trunc(AnimPos) >= 15 then Dead; if (Trunc(AnimPos) >= 1) and (ImageName = 'Explosion2') then Collisioned := False; if Random(150) = 50 then begin if (X > Engine.WorldX + 0) and (Y > Engine.WorldY + 0) and (X < Engine.WorldX + 800) and (Y < Engine.WorldY + 600) then begin Bullet := TBullet.Create(MainForm.SpriteEngine); Bullet.ImageName := 'BulletS'; Bullet.Width := 40; Bullet.Height := 40; Bullet.BlendingEffect := TBlendingEffect.Add; Bullet.MoveSpeed := 4; Bullet.Z := 4000; Bullet.FCounter := 0; Bullet.X := Self.X + 5; Bullet.Y := Self.Y; Bullet.DrawMode := 1; Bullet.DestAngle := Angle * 40; end; end; end; procedure TPlayerShip.DoMove(const MoveCount: Single); begin inherited; SetColor(255, 255, 255); CollidePos := Point(Round(X) + 20, Round(Y) + 20); Collision; if DoAccelerate then Accelerate; if DoDeccelerate then Deccelerate; if ImageName = 'PlayerShip' then begin UpdatePos(1); // LookAt(CursorX, CursorY); Angle := Angle256(Trunc(MainForm.CursorX) - 512, Trunc(MainForm.CursorY) - 384) * 0.025; Direction := Trunc(Angle256(MainForm.CursorX - 512, MainForm.CursorY - 384)); end; if (Trunc(AnimPos) >= 32) and (ImageName = 'Explode') then begin ImageName := 'PlayerShip'; BlendingEffect := TBlendingEffect.Normal; ScaleX := 1.2; ScaleY := 1.2; end; if FReady then Inc(FReadyTime); if FReadyTime = 350 then begin FReady := False; Collisioned := True; end; Engine.WorldX := X - 512; Engine.WorldY := Y - 384; end; procedure TPlayerShip.DoCollision(const Sprite: TSprite); var I: Integer; begin if Sprite is TBonus then begin PlaySound('GetBonus.wav'); if TBonus(Sprite).ImageName = 'Bonus0' then Inc(MainForm.Score, 100); if TBonus(Sprite).ImageName = 'Bonus1' then Inc(MainForm.Score, 200); if TBonus(Sprite).ImageName = 'Bonus2' then Inc(MainForm.Score, 300); if TBonus(Sprite).ImageName = 'Money' then Inc(MainForm.Score, 500); MainForm.CreateSpark(TBonus(Sprite).X, TBonus(Sprite).Y); TBonus(Sprite).Dead; end; if Sprite is TBullet then begin PlaySound('Hit.wav'); MainForm.PlayerShip.Life := MainForm.PlayerShip.Life - 0.25; Self.SetColor(255, 0, 0); TBullet(Sprite).Collisioned := False; TBullet(Sprite).MoveSpeed := 0; TBullet(Sprite).SetPattern(64, 64); TBullet(Sprite).SetAnim('Explosion3', 0, 12, 0.3, False, False, True); TBullet(Sprite).Z := 10000; end; if (Sprite is TAsteroids) or (Sprite is TEnemy) then begin PlaySound('Hit.wav'); FReady := True; FReadyTime := 0; MainForm.PlayerShip.Life := MainForm.PlayerShip.Life - 0.25; AnimPos := 0; SetPattern(64, 64); SetAnim('Explode', 0, 40, 0.25, False, False, True); Collisioned := False; BlendingEffect := TBlendingEffect.Add; ScaleX := 1.5; ScaleY := 1.5; end; end; procedure TTail.DoMove(const MoveCount: Single); begin inherited; Alpha := Alpha - 6; if MainForm.PlayerShip.Speed < 1.1 then begin ScaleX := ScaleX + 0.01; ScaleY := ScaleY + 0.01; end else begin ScaleX := ScaleX + 0.025; ScaleY := ScaleY + 0.025; end; Angle := Angle + 0.125; UpdatePos(1); Accelerate; Inc(FCounter); if FCounter > 25 then Dead; end; procedure TExplosion.DoMove(const MoveCount: Single); begin inherited; Accelerate; UpdatePos(1); Alpha := Alpha - 1; if Alpha < 1 then Dead; end; procedure TSpark.DoMove(const MoveCount: Single); begin inherited; Accelerate; UpdatePos(1); Alpha := Alpha - 1; if Alpha < 1 then Dead; end; procedure TBonus.DoMove(const MoveCount: Single); begin inherited; CollidePos := Point(Round(X) + 24, Round(Y) + 24); X := PX + Cos(Step / (30)) * 60 - (Sin(Step / (20)) * 150); Y := PY + Sin(Step / (90)) * 130 + (Cos(Step / (20)) * 110); Step := Step + MoveSpeed; end; end.
unit uCadObservacoes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uModelo, StdCtrls, DB, ActnList, Grids, DBGrids, RPDBGrid, ComCtrls, DBCtrls, Buttons, ExtCtrls, Mask, ZAbstractDataset, ZDataset, ZAbstractRODataset; type TfrmCadObservacoes = class(TfrmModelo) GroupBox1: TGroupBox; Label1: TLabel; DBEdit1: TDBEdit; Label2: TLabel; DBMemo1: TDBMemo; qrObsNFGrid: TZReadOnlyQuery; qrObsNFGridcodigo: TStringField; qrObsNFGriddescricao: TBlobField; qrObsNFGriduser_inclusao: TStringField; qrObsNFGriddata_inclusao: TDateField; qrObsNFGriduser_alteracao: TStringField; qrObsNFGriddata_alteracao: TDateField; qrObsNFFicha: TZQuery; qrObsNFFichacodigo: TStringField; qrObsNFFichadescricao: TBlobField; qrObsNFFichauser_inclusao: TStringField; qrObsNFFichadata_inclusao: TDateField; qrObsNFFichauser_alteracao: TStringField; qrObsNFFichadata_alteracao: TDateField; procedure FormCreate(Sender: TObject); procedure actGravaExecute(Sender: TObject); procedure dsFichaDataChange(Sender: TObject; Field: TField); procedure qrObsNFGriddescricaoGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure DBMemo1KeyPress(Sender: TObject; var Key: Char); procedure DBEdit1KeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var frmCadObservacoes: TfrmCadObservacoes; implementation uses udmCadastros, udmPrincipal, funcoes; {$R *.dfm} procedure TfrmCadObservacoes.FormCreate(Sender: TObject); begin dsGrid.DataSet := qrObsNFGrid; dsFicha.DataSet := qrObsNFFicha; qrObsNFFicha.DataSource := dsGrid; qrObsNFGrid.Open; qrObsNFFicha.Open; inherited; ReturnToGridAfterEdit := True; end; procedure TfrmCadObservacoes.actGravaExecute(Sender: TObject); var codigo: string; begin ActiveControl := nil; if qrObsNFFichacodigo.AsString = '' then begin MessageBox(handle, 'Código não pode ser nulo!', 'Consistência', mb_ok + mb_IconError); if DBEdit1.CanFocus then DBEdit1.SetFocus; Exit; end; if qrObsNFFichadescricao.AsString = '' then begin MessageBox(handle, 'Descrição não pode ser nula!', 'Consistência', mb_ok + mb_IconError); if DBMemo1.CanFocus then DBMemo1.SetFocus; Exit; end; codigo := dsFicha.DataSet['codigo']; with dmCadastros do begin if funcao = 'incluir' then begin qrObsNFFicha['user_inclusao'] := dmPrincipal.usuario; qrObsNFFicha['data_inclusao'] := dmPrincipal.SoData; end else if funcao = 'alterar' then begin qrObsNFFicha['user_alteracao'] := dmPrincipal.usuario; qrObsNFFicha['data_alteracao'] := dmPrincipal.SoData; end; end; inherited; dsGrid.DataSet.Refresh; dsGrid.DataSet.Locate('codigo', codigo, []); end; procedure TfrmCadObservacoes.dsFichaDataChange(Sender: TObject; Field: TField); begin inherited; (***** Barra de Status *****) if StringEmBranco(qrObsNFFichauser_inclusao.AsString) then StatusBar1.Panels[1].Text := '' else StatusBar1.Panels[1].Text := 'Inclusão: ' + qrObsNFFichauser_inclusao.AsString + ' - ' + qrObsNFFichadata_inclusao.AsString; if StringEmBranco(qrObsNFFichauser_alteracao.AsString) then StatusBar1.Panels[2].Text := '' else StatusBar1.Panels[2].Text := 'Alteração: ' + qrObsNFFichauser_alteracao.AsString + ' - ' + qrObsNFFichadata_alteracao.AsString; end; procedure TfrmCadObservacoes.qrObsNFGriddescricaoGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin inherited; Text := Sender.AsString; end; procedure TfrmCadObservacoes.DBMemo1KeyPress(Sender: TObject; var Key: Char); begin inherited; Key := Upcase(Key); end; procedure TfrmCadObservacoes.DBEdit1KeyPress(Sender: TObject; var Key: Char); begin inherited; if not (Key in ['0'..'9', Chr(8)]) then Key := #0; end; end.
unit ce_txtsyn; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SynEditHighlighter, SynEditTypes, ce_dlangutils; type TTokenKind = (tkSym, tkTxt, tkWhi); TSynTxtSyn = class(TSynCustomHighlighter) private fSymAttribs: TSynHighlighterAttributes; fTxtAttribs: TSynHighlighterAttributes; fWhiAttribs: TSynHighlighterAttributes; fTokToAttri: array[TTokenKind] of TSynHighlighterAttributes; fToken: TTokenKind; fTokStart, fTokStop: Integer; fLineBuf: string; fCurrIdent: string; procedure setSymAttribs(aValue: TSynHighlighterAttributes); procedure setTxtAttribs(aValue: TSynHighlighterAttributes); procedure setWhiAttribs(aValue: TSynHighlighterAttributes); procedure setCurrIdent(const aValue: string); published property symbAttributes: TSynHighlighterAttributes read fSymAttribs write setSymAttribs; property textAttributes: TSynHighlighterAttributes read fTxtAttribs write setTxtAttribs; property whitAttributes: TSynHighlighterAttributes read fWhiAttribs write setWhiAttribs; public constructor Create(aOwner: TComponent); override; // procedure setLine(const NewValue: String; LineNumber: Integer); override; procedure Next; override; procedure GetTokenEx(out TokenStart: PChar; out TokenLength: integer); override; function GetTokenAttribute: TSynHighlighterAttributes; override; function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override; function GetToken: string; override; function GetTokenKind: integer; override; function GetTokenPos: Integer; override; function GetEol: Boolean; override; // property CurrIdent: string read fCurrIdent write setCurrIdent; end; const txtSym: TCharSet = [ '&', '~', '#', '"', #39, '(', '-', ')', '=', '{', '[', '|', '`', '\', '^', '@', ']', '}', '+', '$', '*', '%', '<', '>', ',', '?', ';', '.', ':', '/', '!']; implementation uses Graphics; constructor TSynTxtSyn.Create(aOwner: TComponent); begin inherited; SetSubComponent(True); // fSymAttribs := TSynHighlighterAttributes.Create('Symbols', 'Symbols'); fTxtAttribs := TSynHighlighterAttributes.Create('Text', 'Text'); fWhiAttribs := TSynHighlighterAttributes.Create('White', 'White'); // fSymAttribs.Foreground := clBlack; fSymAttribs.Style := [fsBold]; fTxtAttribs.Foreground := clNavy; fWhiAttribs.Foreground := clNone; // AddAttribute(fSymAttribs); AddAttribute(fTxtAttribs); AddAttribute(fWhiAttribs); // fTokToAttri[tkSym] := fSymAttribs; fTokToAttri[tkTxt] := fTxtAttribs; fTokToAttri[tkWhi] := fWhiAttribs; // fTokStop := 1; Next; end; procedure TSynTxtSyn.setSymAttribs(aValue: TSynHighlighterAttributes); begin fSymAttribs.Assign(aValue); end; procedure TSynTxtSyn.setTxtAttribs(aValue: TSynHighlighterAttributes); begin fTxtAttribs.Assign(aValue); end; procedure TSynTxtSyn.setWhiAttribs(aValue: TSynHighlighterAttributes); begin fWhiAttribs.Assign(aValue); end; procedure TSynTxtSyn.setCurrIdent(const aValue: string); begin if fCurrIdent = aValue then Exit; fCurrIdent := aValue; BeginUpdate; fUpdateChange := True; EndUpdate; end; procedure TSynTxtSyn.setLine(const NewValue: String; LineNumber: Integer); begin inherited; fLineBuf := NewValue + #10; fTokStop := 1; Next; end; procedure TSynTxtSyn.Next; begin fTokStart := fTokStop; fTokStop := fTokStart; // EOL if fTokStop > length(fLineBuf) then exit; // spaces if (isWhite(fLineBuf[fTokStop])) then begin fToken := tkWhi; while isWhite(fLineBuf[fTokStop]) do begin Inc(fTokStop); if fTokStop > length(fLineBuf) then exit; end; exit; end; // symbs if (fLineBuf[fTokStop] in txtSym) then begin fToken := tkSym; while (fLineBuf[fTokStop] in txtSym) do begin Inc(fTokStop); if fLineBuf[fTokStop] = #10 then exit; end; exit; end; // text fToken := tkTxt; while not ((fLineBuf[fTokStop] in txtSym) or isWhite(fLineBuf[fTokStop])) do begin Inc(fTokStop); if fLineBuf[fTokStop] = #10 then exit; end; if fLineBuf[fTokStop] = #10 then exit; end; function TSynTxtSyn.GetEol: Boolean; begin Result := fTokStop > length(fLineBuf); end; function TSynTxtSyn.GetTokenAttribute: TSynHighlighterAttributes; begin Result := fTokToAttri[fToken]; Result.FrameEdges := sfeNone; if fCurrIdent <> '' then if GetToken = fCurrIdent then begin Result.FrameColor := Result.Foreground; Result.FrameStyle := slsSolid; Result.FrameEdges := sfeAround; end; end; function TSynTxtSyn.GetTokenPos: Integer; begin Result := fTokStart - 1; end; function TSynTxtSyn.GetToken: string; begin Result := copy(fLineBuf, FTokStart, fTokStop - FTokStart); end; procedure TSynTxtSyn.GetTokenEx(out TokenStart: PChar; out TokenLength: integer); begin TokenStart := @fLineBuf[FTokStart]; TokenLength := fTokStop - FTokStart; end; function TSynTxtSyn.GetTokenKind: integer; var a: TSynHighlighterAttributes; begin Result := SYN_ATTR_IDENTIFIER; a := GetTokenAttribute; if a = fTxtAttribs then Result := SYN_ATTR_IDENTIFIER else if a = fWhiAttribs then Result := SYN_ATTR_WHITESPACE else if a = fSymAttribs then Result := SYN_ATTR_SYMBOL; end; function TSynTxtSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; begin case Index of SYN_ATTR_COMMENT: Result := fTxtAttribs; SYN_ATTR_IDENTIFIER: Result := fTxtAttribs; SYN_ATTR_KEYWORD: Result := fTxtAttribs; SYN_ATTR_STRING: Result := fTxtAttribs; SYN_ATTR_WHITESPACE: Result := fWhiAttribs; SYN_ATTR_SYMBOL: Result := fSymAttribs; else Result := fTxtAttribs; end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls; type TForm1 = class(TForm) Label1: TLabel; Label2: TLabel; eQuantity: TEdit; ePrice: TEdit; leSum: TLabeledEdit; btnOk: TBitBtn; BitBtn2: TBitBtn; procedure FormCreate(Sender: TObject); procedure eQuantityChange(Sender: TObject); procedure eQuantityKeyPress(Sender: TObject; var Key: Char); procedure ePriceChange(Sender: TObject); procedure leSumChange(Sender: TObject); private { Private declarations } procedure CheckOk; public { Public declarations } end; var Form1: TForm1; implementation uses common; {$R *.dfm} procedure TForm1.CheckOk; begin btnOk.Enabled := (ePrice.Text <> '') and (eQuantity.Text <> '') and (leSum.Text <> ''); end; procedure TForm1.ePriceChange(Sender: TObject); begin if ePrice.Focused and (ePrice.Text <> '') then begin if eQuantity.Text <> '' then leSum.Text := FloatToStrF( StrToFloat(ePrice.Text) * StrToFloat(eQuantity.Text), ffFixed, 15, 2) else if leSum.Text <> '' then eQuantity.Text := FloatToStrF( StrToFloat(leSum.Text) / StrToFloat(ePrice.Text), ffFixed, 15, 2) end; CheckOk; end; procedure TForm1.eQuantityChange(Sender: TObject); begin if eQuantity.Focused and (eQuantity.Text <> '') then begin if ePrice.Text <> '' then leSum.Text := FloatToStrF( StrToFloat(ePrice.Text) * StrToFloat(eQuantity.Text), ffFixed, 15, 2) else if leSum.Text <> '' then ePrice.Text := FloatToStrF( StrToFloat(leSum.Text) / StrToFloat(eQuantity.Text), ffFixed, 15, 2) end; CheckOk; end; procedure TForm1.eQuantityKeyPress(Sender: TObject; var Key: Char); var s: string; k: integer; begin if key = #8 then exit; // #8 = backspace if (key = '.') or (key = ',') then key := FormatSettings.DecimalSeparator; s := (Sender as TCustomEdit).Text; k := (Sender as TCustomEdit).SelStart; // местоположение курсора s := copy(s, 1, k) + key + copy(s, k+1, length(s)); if (key = 'e') or (key = 'E') or not CheckStrToFloat(s) then key := #0; end; procedure TForm1.FormCreate(Sender: TObject); begin eQuantity.Clear; ePrice.Clear; end; procedure TForm1.leSumChange(Sender: TObject); begin if leSum.Focused and (leSum.Text <> '') then begin if eQuantity.Text <> '' then ePrice.Text := FloatToStrF( StrToFloat(leSum.Text) / StrToFloat(eQuantity.Text), ffFixed, 15, 2) else if ePrice.Text <> '' then eQuantity.Text := FloatToStrF( StrToFloat(leSum.Text) / StrToFloat(ePrice.Text), ffFixed, 15, 2) end; CheckOk; end; end.
unit TTSMLTAGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSMLTAGRecord = record PSeparateby: String[10]; PGroupBy: String[10]; PSortby: String[120]; PLoanNum: String[20]; PCifFlag: String[1]; PAutoInc: Integer; PLoanCifNum: String[25]; PNetDollar: Currency; PName1: String[40]; PName2: String[40]; PName3: String[40]; PName4: String[40]; PName5: String[40]; POfficer: String[8]; PBalance: Currency; PIndirect: Currency; PBranch: String[8]; PDivision: String[8]; PCustCollCode: String[20]; PCollDesc1: String[60]; PCollDesc2: String[60]; PCollDesc3: String[60]; PCollDesc4: String[60]; PLoanDates: String[30]; PPaidout: String[25]; PPhone: String[40]; PValue1: Currency; PValue2: Currency; PCustCollCodeDesc: String[30]; PDepartment: String[8]; End; TTTSMLTAGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSMLTAGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSMLTAG = (TTSMLTAGPrimaryKey, TTSMLTAGBySort, TTSMLTAGbyLoanNum, TTSMLTAGByException); TTTSMLTAGTable = class( TDBISAMTableAU ) private FDFSeparateby: TStringField; FDFGroupBy: TStringField; FDFSortby: TStringField; FDFLoanNum: TStringField; FDFCifFlag: TStringField; FDFAutoInc: TAutoIncField; FDFLoanCifNum: TStringField; FDFNetDollar: TCurrencyField; FDFName1: TStringField; FDFName2: TStringField; FDFName3: TStringField; FDFName4: TStringField; FDFName5: TStringField; FDFOfficer: TStringField; FDFBalance: TCurrencyField; FDFIndirect: TCurrencyField; FDFBranch: TStringField; FDFDivision: TStringField; FDFCustCollCode: TStringField; FDFCollDesc1: TStringField; FDFCollDesc2: TStringField; FDFCollDesc3: TStringField; FDFCollDesc4: TStringField; FDFLoanDates: TStringField; FDFPaidout: TStringField; FDFPhone: TStringField; FDFValue1: TCurrencyField; FDFValue2: TCurrencyField; FDFCustCollCodeDesc: TStringField; FDFNotes: TBlobField; FDFDepartment: TStringField; procedure SetPSeparateby(const Value: String); function GetPSeparateby:String; procedure SetPGroupBy(const Value: String); function GetPGroupBy:String; procedure SetPSortby(const Value: String); function GetPSortby:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanCifNum(const Value: String); function GetPLoanCifNum:String; procedure SetPNetDollar(const Value: Currency); function GetPNetDollar:Currency; procedure SetPName1(const Value: String); function GetPName1:String; procedure SetPName2(const Value: String); function GetPName2:String; procedure SetPName3(const Value: String); function GetPName3:String; procedure SetPName4(const Value: String); function GetPName4:String; procedure SetPName5(const Value: String); function GetPName5:String; procedure SetPOfficer(const Value: String); function GetPOfficer:String; procedure SetPBalance(const Value: Currency); function GetPBalance:Currency; procedure SetPIndirect(const Value: Currency); function GetPIndirect:Currency; procedure SetPBranch(const Value: String); function GetPBranch:String; procedure SetPDivision(const Value: String); function GetPDivision:String; procedure SetPCustCollCode(const Value: String); function GetPCustCollCode:String; procedure SetPCollDesc1(const Value: String); function GetPCollDesc1:String; procedure SetPCollDesc2(const Value: String); function GetPCollDesc2:String; procedure SetPCollDesc3(const Value: String); function GetPCollDesc3:String; procedure SetPCollDesc4(const Value: String); function GetPCollDesc4:String; procedure SetPLoanDates(const Value: String); function GetPLoanDates:String; procedure SetPPaidout(const Value: String); function GetPPaidout:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPValue1(const Value: Currency); function GetPValue1:Currency; procedure SetPValue2(const Value: Currency); function GetPValue2:Currency; procedure SetPCustCollCodeDesc(const Value: String); function GetPCustCollCodeDesc:String; procedure SetPDepartment(const Value: String); function GetPDepartment:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSMLTAG); function GetEnumIndex: TEITTSMLTAG; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSMLTAGRecord; procedure StoreDataBuffer(ABuffer:TTTSMLTAGRecord); property DFSeparateby: TStringField read FDFSeparateby; property DFGroupBy: TStringField read FDFGroupBy; property DFSortby: TStringField read FDFSortby; property DFLoanNum: TStringField read FDFLoanNum; property DFCifFlag: TStringField read FDFCifFlag; property DFAutoInc: TAutoIncField read FDFAutoInc; property DFLoanCifNum: TStringField read FDFLoanCifNum; property DFNetDollar: TCurrencyField read FDFNetDollar; property DFName1: TStringField read FDFName1; property DFName2: TStringField read FDFName2; property DFName3: TStringField read FDFName3; property DFName4: TStringField read FDFName4; property DFName5: TStringField read FDFName5; property DFOfficer: TStringField read FDFOfficer; property DFBalance: TCurrencyField read FDFBalance; property DFIndirect: TCurrencyField read FDFIndirect; property DFBranch: TStringField read FDFBranch; property DFDivision: TStringField read FDFDivision; property DFCustCollCode: TStringField read FDFCustCollCode; property DFCollDesc1: TStringField read FDFCollDesc1; property DFCollDesc2: TStringField read FDFCollDesc2; property DFCollDesc3: TStringField read FDFCollDesc3; property DFCollDesc4: TStringField read FDFCollDesc4; property DFLoanDates: TStringField read FDFLoanDates; property DFPaidout: TStringField read FDFPaidout; property DFPhone: TStringField read FDFPhone; property DFValue1: TCurrencyField read FDFValue1; property DFValue2: TCurrencyField read FDFValue2; property DFCustCollCodeDesc: TStringField read FDFCustCollCodeDesc; property DFNotes: TBlobField read FDFNotes; property DFDepartment: TStringField read FDFDepartment; property PSeparateby: String read GetPSeparateby write SetPSeparateby; property PGroupBy: String read GetPGroupBy write SetPGroupBy; property PSortby: String read GetPSortby write SetPSortby; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanCifNum: String read GetPLoanCifNum write SetPLoanCifNum; property PNetDollar: Currency read GetPNetDollar write SetPNetDollar; property PName1: String read GetPName1 write SetPName1; property PName2: String read GetPName2 write SetPName2; property PName3: String read GetPName3 write SetPName3; property PName4: String read GetPName4 write SetPName4; property PName5: String read GetPName5 write SetPName5; property POfficer: String read GetPOfficer write SetPOfficer; property PBalance: Currency read GetPBalance write SetPBalance; property PIndirect: Currency read GetPIndirect write SetPIndirect; property PBranch: String read GetPBranch write SetPBranch; property PDivision: String read GetPDivision write SetPDivision; property PCustCollCode: String read GetPCustCollCode write SetPCustCollCode; property PCollDesc1: String read GetPCollDesc1 write SetPCollDesc1; property PCollDesc2: String read GetPCollDesc2 write SetPCollDesc2; property PCollDesc3: String read GetPCollDesc3 write SetPCollDesc3; property PCollDesc4: String read GetPCollDesc4 write SetPCollDesc4; property PLoanDates: String read GetPLoanDates write SetPLoanDates; property PPaidout: String read GetPPaidout write SetPPaidout; property PPhone: String read GetPPhone write SetPPhone; property PValue1: Currency read GetPValue1 write SetPValue1; property PValue2: Currency read GetPValue2 write SetPValue2; property PCustCollCodeDesc: String read GetPCustCollCodeDesc write SetPCustCollCodeDesc; property PDepartment: String read GetPDepartment write SetPDepartment; published property Active write SetActive; property EnumIndex: TEITTSMLTAG read GetEnumIndex write SetEnumIndex; end; { TTTSMLTAGTable } procedure Register; implementation function TTTSMLTAGTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSMLTAGTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSMLTAGTable.GenerateNewFieldName } function TTTSMLTAGTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSMLTAGTable.CreateField } procedure TTTSMLTAGTable.CreateFields; begin FDFSeparateby := CreateField( 'Separateby' ) as TStringField; FDFGroupBy := CreateField( 'GroupBy' ) as TStringField; FDFSortby := CreateField( 'Sortby' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFAutoInc := CreateField( 'AutoInc' ) as TAutoIncField; FDFLoanCifNum := CreateField( 'LoanCifNum' ) as TStringField; FDFNetDollar := CreateField( 'NetDollar' ) as TCurrencyField; FDFName1 := CreateField( 'Name1' ) as TStringField; FDFName2 := CreateField( 'Name2' ) as TStringField; FDFName3 := CreateField( 'Name3' ) as TStringField; FDFName4 := CreateField( 'Name4' ) as TStringField; FDFName5 := CreateField( 'Name5' ) as TStringField; FDFOfficer := CreateField( 'Officer' ) as TStringField; FDFBalance := CreateField( 'Balance' ) as TCurrencyField; FDFIndirect := CreateField( 'Indirect' ) as TCurrencyField; FDFBranch := CreateField( 'Branch' ) as TStringField; FDFDivision := CreateField( 'Division' ) as TStringField; FDFCustCollCode := CreateField( 'CustCollCode' ) as TStringField; FDFCollDesc1 := CreateField( 'CollDesc1' ) as TStringField; FDFCollDesc2 := CreateField( 'CollDesc2' ) as TStringField; FDFCollDesc3 := CreateField( 'CollDesc3' ) as TStringField; FDFCollDesc4 := CreateField( 'CollDesc4' ) as TStringField; FDFLoanDates := CreateField( 'LoanDates' ) as TStringField; FDFPaidout := CreateField( 'Paidout' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFValue1 := CreateField( 'Value1' ) as TCurrencyField; FDFValue2 := CreateField( 'Value2' ) as TCurrencyField; FDFCustCollCodeDesc := CreateField( 'CustCollCodeDesc' ) as TStringField; FDFNotes := CreateField( 'Notes' ) as TBlobField; FDFDepartment := CreateField( 'Department' ) as TStringField; end; { TTTSMLTAGTable.CreateFields } procedure TTTSMLTAGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSMLTAGTable.SetActive } procedure TTTSMLTAGTable.SetPSeparateby(const Value: String); begin DFSeparateby.Value := Value; end; function TTTSMLTAGTable.GetPSeparateby:String; begin result := DFSeparateby.Value; end; procedure TTTSMLTAGTable.SetPGroupBy(const Value: String); begin DFGroupBy.Value := Value; end; function TTTSMLTAGTable.GetPGroupBy:String; begin result := DFGroupBy.Value; end; procedure TTTSMLTAGTable.SetPSortby(const Value: String); begin DFSortby.Value := Value; end; function TTTSMLTAGTable.GetPSortby:String; begin result := DFSortby.Value; end; procedure TTTSMLTAGTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSMLTAGTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSMLTAGTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSMLTAGTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSMLTAGTable.SetPLoanCifNum(const Value: String); begin DFLoanCifNum.Value := Value; end; function TTTSMLTAGTable.GetPLoanCifNum:String; begin result := DFLoanCifNum.Value; end; procedure TTTSMLTAGTable.SetPNetDollar(const Value: Currency); begin DFNetDollar.Value := Value; end; function TTTSMLTAGTable.GetPNetDollar:Currency; begin result := DFNetDollar.Value; end; procedure TTTSMLTAGTable.SetPName1(const Value: String); begin DFName1.Value := Value; end; function TTTSMLTAGTable.GetPName1:String; begin result := DFName1.Value; end; procedure TTTSMLTAGTable.SetPName2(const Value: String); begin DFName2.Value := Value; end; function TTTSMLTAGTable.GetPName2:String; begin result := DFName2.Value; end; procedure TTTSMLTAGTable.SetPName3(const Value: String); begin DFName3.Value := Value; end; function TTTSMLTAGTable.GetPName3:String; begin result := DFName3.Value; end; procedure TTTSMLTAGTable.SetPName4(const Value: String); begin DFName4.Value := Value; end; function TTTSMLTAGTable.GetPName4:String; begin result := DFName4.Value; end; procedure TTTSMLTAGTable.SetPName5(const Value: String); begin DFName5.Value := Value; end; function TTTSMLTAGTable.GetPName5:String; begin result := DFName5.Value; end; procedure TTTSMLTAGTable.SetPOfficer(const Value: String); begin DFOfficer.Value := Value; end; function TTTSMLTAGTable.GetPOfficer:String; begin result := DFOfficer.Value; end; procedure TTTSMLTAGTable.SetPBalance(const Value: Currency); begin DFBalance.Value := Value; end; function TTTSMLTAGTable.GetPBalance:Currency; begin result := DFBalance.Value; end; procedure TTTSMLTAGTable.SetPIndirect(const Value: Currency); begin DFIndirect.Value := Value; end; function TTTSMLTAGTable.GetPIndirect:Currency; begin result := DFIndirect.Value; end; procedure TTTSMLTAGTable.SetPBranch(const Value: String); begin DFBranch.Value := Value; end; function TTTSMLTAGTable.GetPBranch:String; begin result := DFBranch.Value; end; procedure TTTSMLTAGTable.SetPDivision(const Value: String); begin DFDivision.Value := Value; end; function TTTSMLTAGTable.GetPDivision:String; begin result := DFDivision.Value; end; procedure TTTSMLTAGTable.SetPCustCollCode(const Value: String); begin DFCustCollCode.Value := Value; end; function TTTSMLTAGTable.GetPCustCollCode:String; begin result := DFCustCollCode.Value; end; procedure TTTSMLTAGTable.SetPCollDesc1(const Value: String); begin DFCollDesc1.Value := Value; end; function TTTSMLTAGTable.GetPCollDesc1:String; begin result := DFCollDesc1.Value; end; procedure TTTSMLTAGTable.SetPCollDesc2(const Value: String); begin DFCollDesc2.Value := Value; end; function TTTSMLTAGTable.GetPCollDesc2:String; begin result := DFCollDesc2.Value; end; procedure TTTSMLTAGTable.SetPCollDesc3(const Value: String); begin DFCollDesc3.Value := Value; end; function TTTSMLTAGTable.GetPCollDesc3:String; begin result := DFCollDesc3.Value; end; procedure TTTSMLTAGTable.SetPCollDesc4(const Value: String); begin DFCollDesc4.Value := Value; end; function TTTSMLTAGTable.GetPCollDesc4:String; begin result := DFCollDesc4.Value; end; procedure TTTSMLTAGTable.SetPLoanDates(const Value: String); begin DFLoanDates.Value := Value; end; function TTTSMLTAGTable.GetPLoanDates:String; begin result := DFLoanDates.Value; end; procedure TTTSMLTAGTable.SetPPaidout(const Value: String); begin DFPaidout.Value := Value; end; function TTTSMLTAGTable.GetPPaidout:String; begin result := DFPaidout.Value; end; procedure TTTSMLTAGTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TTTSMLTAGTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TTTSMLTAGTable.SetPValue1(const Value: Currency); begin DFValue1.Value := Value; end; function TTTSMLTAGTable.GetPValue1:Currency; begin result := DFValue1.Value; end; procedure TTTSMLTAGTable.SetPValue2(const Value: Currency); begin DFValue2.Value := Value; end; function TTTSMLTAGTable.GetPValue2:Currency; begin result := DFValue2.Value; end; procedure TTTSMLTAGTable.SetPCustCollCodeDesc(const Value: String); begin DFCustCollCodeDesc.Value := Value; end; function TTTSMLTAGTable.GetPCustCollCodeDesc:String; begin result := DFCustCollCodeDesc.Value; end; procedure TTTSMLTAGTable.SetPDepartment(const Value: String); begin DFDepartment.Value := Value; end; function TTTSMLTAGTable.GetPDepartment:String; begin result := DFDepartment.Value; end; procedure TTTSMLTAGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Separateby, String, 10, N'); Add('GroupBy, String, 10, N'); Add('Sortby, String, 120, N'); Add('LoanNum, String, 20, N'); Add('CifFlag, String, 1, N'); Add('AutoInc, AutoInc, 0, N'); Add('LoanCifNum, String, 25, N'); Add('NetDollar, Currency, 0, N'); Add('Name1, String, 40, N'); Add('Name2, String, 40, N'); Add('Name3, String, 40, N'); Add('Name4, String, 40, N'); Add('Name5, String, 40, N'); Add('Officer, String, 8, N'); Add('Balance, Currency, 0, N'); Add('Indirect, Currency, 0, N'); Add('Branch, String, 8, N'); Add('Division, String, 8, N'); Add('CustCollCode, String, 20, N'); Add('CollDesc1, String, 60, N'); Add('CollDesc2, String, 60, N'); Add('CollDesc3, String, 60, N'); Add('CollDesc4, String, 60, N'); Add('LoanDates, String, 30, N'); Add('Paidout, String, 25, N'); Add('Phone, String, 40, N'); Add('Value1, Currency, 0, N'); Add('Value2, Currency, 0, N'); Add('CustCollCodeDesc, String, 30, N'); Add('Notes, Memo, 0, N'); Add('Department, String, 8, N'); end; end; procedure TTTSMLTAGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, AutoInc, Y, Y, N, N'); Add('BySort, Separateby;GroupBy;Sortby, N, N, Y, N'); Add('byLoanNum, CifFlag;LoanNum, N, N, Y, N'); Add('ByException, Separateby;GroupBy;CifFlag;LoanNum, N, Y, Y, N'); end; end; procedure TTTSMLTAGTable.SetEnumIndex(Value: TEITTSMLTAG); begin case Value of TTSMLTAGPrimaryKey : IndexName := ''; TTSMLTAGBySort : IndexName := 'BySort'; TTSMLTAGbyLoanNum : IndexName := 'byLoanNum'; TTSMLTAGByException : IndexName := 'ByException'; end; end; function TTTSMLTAGTable.GetDataBuffer:TTTSMLTAGRecord; var buf: TTTSMLTAGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PSeparateby := DFSeparateby.Value; buf.PGroupBy := DFGroupBy.Value; buf.PSortby := DFSortby.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCifFlag := DFCifFlag.Value; buf.PAutoInc := DFAutoInc.Value; buf.PLoanCifNum := DFLoanCifNum.Value; buf.PNetDollar := DFNetDollar.Value; buf.PName1 := DFName1.Value; buf.PName2 := DFName2.Value; buf.PName3 := DFName3.Value; buf.PName4 := DFName4.Value; buf.PName5 := DFName5.Value; buf.POfficer := DFOfficer.Value; buf.PBalance := DFBalance.Value; buf.PIndirect := DFIndirect.Value; buf.PBranch := DFBranch.Value; buf.PDivision := DFDivision.Value; buf.PCustCollCode := DFCustCollCode.Value; buf.PCollDesc1 := DFCollDesc1.Value; buf.PCollDesc2 := DFCollDesc2.Value; buf.PCollDesc3 := DFCollDesc3.Value; buf.PCollDesc4 := DFCollDesc4.Value; buf.PLoanDates := DFLoanDates.Value; buf.PPaidout := DFPaidout.Value; buf.PPhone := DFPhone.Value; buf.PValue1 := DFValue1.Value; buf.PValue2 := DFValue2.Value; buf.PCustCollCodeDesc := DFCustCollCodeDesc.Value; buf.PDepartment := DFDepartment.Value; result := buf; end; procedure TTTSMLTAGTable.StoreDataBuffer(ABuffer:TTTSMLTAGRecord); begin DFSeparateby.Value := ABuffer.PSeparateby; DFGroupBy.Value := ABuffer.PGroupBy; DFSortby.Value := ABuffer.PSortby; DFLoanNum.Value := ABuffer.PLoanNum; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanCifNum.Value := ABuffer.PLoanCifNum; DFNetDollar.Value := ABuffer.PNetDollar; DFName1.Value := ABuffer.PName1; DFName2.Value := ABuffer.PName2; DFName3.Value := ABuffer.PName3; DFName4.Value := ABuffer.PName4; DFName5.Value := ABuffer.PName5; DFOfficer.Value := ABuffer.POfficer; DFBalance.Value := ABuffer.PBalance; DFIndirect.Value := ABuffer.PIndirect; DFBranch.Value := ABuffer.PBranch; DFDivision.Value := ABuffer.PDivision; DFCustCollCode.Value := ABuffer.PCustCollCode; DFCollDesc1.Value := ABuffer.PCollDesc1; DFCollDesc2.Value := ABuffer.PCollDesc2; DFCollDesc3.Value := ABuffer.PCollDesc3; DFCollDesc4.Value := ABuffer.PCollDesc4; DFLoanDates.Value := ABuffer.PLoanDates; DFPaidout.Value := ABuffer.PPaidout; DFPhone.Value := ABuffer.PPhone; DFValue1.Value := ABuffer.PValue1; DFValue2.Value := ABuffer.PValue2; DFCustCollCodeDesc.Value := ABuffer.PCustCollCodeDesc; DFDepartment.Value := ABuffer.PDepartment; end; function TTTSMLTAGTable.GetEnumIndex: TEITTSMLTAG; var iname : string; begin result := TTSMLTAGPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSMLTAGPrimaryKey; if iname = 'BYSORT' then result := TTSMLTAGBySort; if iname = 'BYLOANNUM' then result := TTSMLTAGbyLoanNum; if iname = 'BYEXCEPTION' then result := TTSMLTAGByException; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSMLTAGTable, TTTSMLTAGBuffer ] ); end; { Register } function TTTSMLTAGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..30] of string = ('SEPARATEBY','GROUPBY','SORTBY','LOANNUM','CIFFLAG','AUTOINC' ,'LOANCIFNUM','NETDOLLAR','NAME1','NAME2','NAME3' ,'NAME4','NAME5','OFFICER','BALANCE','INDIRECT' ,'BRANCH','DIVISION','CUSTCOLLCODE','COLLDESC1','COLLDESC2' ,'COLLDESC3','COLLDESC4','LOANDATES','PAIDOUT','PHONE' ,'VALUE1','VALUE2','CUSTCOLLCODEDESC','DEPARTMENT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 30) and (flist[x] <> s) do inc(x); if x <= 30 then result := x else result := 0; end; function TTTSMLTAGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftAutoInc; 7 : result := ftString; 8 : result := ftCurrency; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftString; 14 : result := ftString; 15 : result := ftCurrency; 16 : result := ftCurrency; 17 : result := ftString; 18 : result := ftString; 19 : result := ftString; 20 : result := ftString; 21 : result := ftString; 22 : result := ftString; 23 : result := ftString; 24 : result := ftString; 25 : result := ftString; 26 : result := ftString; 27 : result := ftCurrency; 28 : result := ftCurrency; 29 : result := ftString; 30 : result := ftString; end; end; function TTTSMLTAGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PSeparateby; 2 : result := @Data.PGroupBy; 3 : result := @Data.PSortby; 4 : result := @Data.PLoanNum; 5 : result := @Data.PCifFlag; 6 : result := @Data.PAutoInc; 7 : result := @Data.PLoanCifNum; 8 : result := @Data.PNetDollar; 9 : result := @Data.PName1; 10 : result := @Data.PName2; 11 : result := @Data.PName3; 12 : result := @Data.PName4; 13 : result := @Data.PName5; 14 : result := @Data.POfficer; 15 : result := @Data.PBalance; 16 : result := @Data.PIndirect; 17 : result := @Data.PBranch; 18 : result := @Data.PDivision; 19 : result := @Data.PCustCollCode; 20 : result := @Data.PCollDesc1; 21 : result := @Data.PCollDesc2; 22 : result := @Data.PCollDesc3; 23 : result := @Data.PCollDesc4; 24 : result := @Data.PLoanDates; 25 : result := @Data.PPaidout; 26 : result := @Data.PPhone; 27 : result := @Data.PValue1; 28 : result := @Data.PValue2; 29 : result := @Data.PCustCollCodeDesc; 30 : result := @Data.PDepartment; end; end; end.
unit Classes; interface type //Classe TOpenWeatherCidade TOpenWeatherCidade = class(TObject) private Nome: String; public property cidade: String read Nome; end; //Classe TOpenWeatherSys TOpenWeatherSys = class(TObject) private Fcountry: string; Fsunrise: Integer; Fsunset: Integer; public property country: string read Fcountry; property sunrise: Integer read Fsunrise; property sunset: Integer read Fsunset; end; //Classe TOpenWeatherWeatherItem TOpenWeatherWeatherItem = class(TObject) private Fid: Integer; Fmain: string; Fdescription: string; Ficon: string; public property id: Integer read Fid; property main: string read Fmain; property description: string read Fdescription; property icon: string read Ficon; end; //Classe TOpenWeatherWeather TOpenWeatherWeather = array of TOpenWeatherWeatherItem; //Classe TOpenWeatherMain TOpenWeatherMain = class(TObject) private Ftemp: Double; Fhumidity: Double; Fpressure: Double; Ftemp_min: Double; Ftemp_max: Double; public property temp: Double read Ftemp; property humidity: Double read Fhumidity; property pressure: Double read Fpressure; property temp_min: Double read Ftemp_min; property temp_max: Double read Ftemp_max; end; //Classe TOpenWeatherWind TOpenWeatherWind = class(TObject) private Fspeed: Double; Fdegrees: Double; public property speed: Double read Fspeed; property degrees: Double read Fdegrees; end; //Classe TOpenWeatherClouds TOpenWeatherClouds = class(TObject) private Fall: Double; public property all: Double read Fall; end; //Classe TOpenWeatherRain TOpenWeatherRain = class(TObject) private F3h: Double; public property vol3h: Double read F3h; end; //Classe TOpenWeatherPorCidade TOpenWeatherPorCidade = class(TObject) private Fcidade: TOpenWeatherCidade; Fsys: TOpenWeatherSys; Fweather: TOpenWeatherWeather; Fmain: TOpenWeatherMain; Fwind: TOpenWeatherWind; Frain: TOpenWeatherRain; Fclouds: TOpenWeatherClouds; Fdt: Integer; Fid: Integer; Fname: string; Fcod: Integer; public property cidade: TOpenWeatherCidade read Fcidade; property sys: TOpenWeatherSys read Fsys; property weather: TOpenWeatherWeather read Fweather; property main: TOpenWeatherMain read Fmain; property wind: TOpenWeatherWind read Fwind; property rain: TOpenWeatherRain read Frain; property clouds: TOpenWeatherClouds read Fclouds; property dt: Integer read Fdt; property id: Integer read Fid; property name: string read Fname; property cod: Integer read Fcod; end; implementation end.
unit MFichas.Controller.Venda; interface uses MFichas.Controller.Caixa.Interfaces, MFichas.Controller.Venda.Interfaces, MFichas.Controller.Venda.Metodos, MFichas.Model.Venda.Interfaces, MFichas.Model.Venda, MFichas.Model.Caixa; type TControllerVenda = class(TInterfacedObject, iControllerVenda) private [weak] FParent : iControllerCaixa; FMetodos: iControllerVendaMetodos; FModel : iModelVenda; class var FInstance: iControllerVenda; constructor Create(AParent: iControllerCaixa); public destructor Destroy; override; class function New(AParent: iControllerCaixa): iControllerVenda; function Metodos: iControllerVendaMetodos; end; implementation { TControllerVenda } constructor TControllerVenda.Create(AParent: iControllerCaixa); begin FParent := AParent; if not Assigned(FModel) then FModel := TModelVenda.New(TModelCaixa.New); FMetodos := TControllerVendaMetodos.New(Self, FModel); end; destructor TControllerVenda.Destroy; begin inherited; end; function TControllerVenda.Metodos: iControllerVendaMetodos; begin Result := FMetodos; end; class function TControllerVenda.New(AParent: iControllerCaixa): iControllerVenda; begin if not Assigned(FInstance) then FInstance := Self.Create(AParent); Result := FInstance; end; end.
unit sdlinput; { $Id: sdlinput.pas,v 1.9 2007/08/22 21:18:43 savage Exp $ } {******************************************************************************} { } { JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer } { SDL Input Wrapper } { } { } { The initial developer of this Pascal code was : } { Dominique Louis <Dominique@SavageSoftware.com.au> } { } { Portions created by Dominique Louis are } { Copyright (C) 2003 - 2100 Dominique Louis. } { } { } { Contributor(s) } { -------------- } { Dominique Louis <Dominique@SavageSoftware.com.au> } { } { Obtained through: } { Joint Endeavour of Delphi Innovators ( Project JEDI ) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } { Description } { ----------- } { SDL Mouse, Keyboard and Joystick wrapper } { } { } { Requires } { -------- } { SDL.dll on Windows platforms } { libSDL-1.1.so.0 on Linux platform } { } { Programming Notes } { ----------------- } { } { } { } { } { Revision History } { ---------------- } { March 12 2003 - DL : Initial creation } { } { February 02 2004 - DL : Added Custom Cursor Support to the Mouse class } { $Log: sdlinput.pas,v $ Revision 1.9 2007/08/22 21:18:43 savage Thanks to Dean for his MouseDelta patch. Revision 1.8 2005/08/03 18:57:32 savage Various updates and additions. Mainly to handle OpenGL 3D Window support and better cursor support for the mouse class Revision 1.7 2004/09/30 22:32:04 savage Updated with slightly different header comments Revision 1.6 2004/09/12 21:52:58 savage Slight changes to fix some issues with the sdl classes. Revision 1.5 2004/05/10 21:11:49 savage changes required to help get SoAoS off the ground. Revision 1.4 2004/05/03 22:38:40 savage Added the ability to enable or disable certain inputs @ runtime. Basically it just does not call UpdateInput if Enabled = false. Can also disable and enable input devices via the InputManager. Revision 1.3 2004/04/28 21:27:01 savage Updated Joystick code and event handlers. Needs testing... Revision 1.2 2004/02/14 22:36:29 savage Fixed inconsistencies of using LoadLibrary and LoadModule. Now all units make use of LoadModule rather than LoadLibrary and other dynamic proc procedures. Revision 1.1 2004/02/05 00:08:20 savage Module 1.0 release } {******************************************************************************} interface {$i jedi-sdl.inc} uses Classes, sdl; type TSDLInputType = ( itJoystick , itKeyBoard, itMouse ); TSDLInputTypes = set of TSDLInputType; TSDLCustomInput = class( TObject ) private FEnabled: Boolean; public constructor Create; function UpdateInput( event: TSDL_EVENT ) : Boolean; virtual; abstract; property Enabled : Boolean read FEnabled write FEnabled; end; TSDLJoyAxisMoveEvent = procedure ( Which: UInt8; Axis: UInt8; Value: SInt16 ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLJoyBallMoveEvent = procedure ( Which: UInt8; Ball: UInt8; RelativePos: TPoint ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLJoyHatMoveEvent = procedure ( Which: UInt8; Hat: UInt8; Value: SInt16 ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLJoyButtonEvent = procedure ( Which: UInt8; Button: UInt8; State: SInt16 ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLJoyStick = class( TSDLCustomInput ) private FJoystick : PSDL_Joystick; FJoystickIndex : Integer; FJoyAxisMoveEvent : TSDLJoyAxisMoveEvent; FJoyBallMoveEvent : TSDLJoyBallMoveEvent; FJoyHatMoveEvent : TSDLJoyHatMoveEvent; FJoyButtonDownEvent : TSDLJoyButtonEvent; FJoyButtonUpEvent : TSDLJoyButtonEvent; procedure DoAxisMove( Event : TSDL_Event ); procedure DoBallMove( Event : TSDL_Event ); procedure DoHatMove( Event : TSDL_Event ); procedure DoButtonDown( Event : TSDL_Event ); procedure DoButtonUp( Event : TSDL_Event ); function GetName: PChar; function GetNumAxes: integer; function GetNumBalls: integer; function GetNumButtons: integer; function GetNumHats: integer; public constructor Create( Index : Integer ); destructor Destroy; override; procedure Open; procedure Close; function UpdateInput( Event: TSDL_EVENT ) : Boolean; override; property Name : PChar read GetName; property NumAxes : integer read GetNumAxes; property NumBalls : integer read GetNumBalls; property NumButtons : integer read GetNumButtons; property NumHats : integer read GetNumHats; property OnAxisMove : TSDLJoyAxisMoveEvent read FJoyAxisMoveEvent write FJoyAxisMoveEvent; property OnBallMove : TSDLJoyBallMoveEvent read FJoyBallMoveEvent write FJoyBallMoveEvent; property OnHatMove : TSDLJoyHatMoveEvent read FJoyHatMoveEvent write FJoyHatMoveEvent; property OnButtonDown : TSDLJoyButtonEvent read FJoyButtonDownEvent write FJoyButtonDownEvent; property OnButtonUp : TSDLJoyButtonEvent read FJoyButtonUpEvent write FJoyButtonUpEvent; end; TSDLJoySticks = class( TObject ) private FNumOfJoySticks: Integer; FJoyStickList : TList; function GetJoyStick(Index: integer): TSDLJoyStick; procedure SetJoyStick(Index: integer; const Value: TSDLJoyStick); public constructor Create; destructor Destroy; override; function UpdateInput( event: TSDL_EVENT ) : Boolean; property NumOfJoySticks : Integer read FNumOfJoySticks write FNumOfJoySticks; property JoySticks[ Index : integer ] : TSDLJoyStick read GetJoyStick write SetJoyStick; end; TSDLKeyBoardEvent = procedure ( var Key: TSDLKey; Shift: TSDLMod; unicode : UInt16 ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLKeyBoard = class( TSDLCustomInput ) private FKeys : PKeyStateArr; FOnKeyUp: TSDLKeyBoardEvent; FOnKeyDown: TSDLKeyBoardEvent; procedure DoKeyDown( keysym : PSDL_keysym ); procedure DoKeyUp( keysym : PSDL_keysym ); public function IsKeyDown( Key : TSDLKey ) : Boolean; function IsKeyUp( Key : TSDLKey ) : Boolean; function UpdateInput( event: TSDL_EVENT ) : Boolean; override; property Keys : PKeyStateArr read FKeys write FKeys; property OnKeyDown : TSDLKeyBoardEvent read FOnKeyDown write FOnKeyDown; property OnKeyUp : TSDLKeyBoardEvent read FOnKeyUp write FOnKeyUp; end; TSDLMouseButtonEvent = procedure ( Button : Integer; Shift: TSDLMod; MousePos : TPoint ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLMouseMoveEvent = procedure ( Shift: TSDLMod; CurrentPos : TPoint; RelativePos : TPoint ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLMouseWheelEvent = procedure ( WheelDelta : Integer; Shift: TSDLMod; MousePos : TPoint ) {$IFNDEF NOT_OO}of object{$ENDIF}; TSDLCustomCursor = class( TObject ) private FFileName : string; FHotPoint: TPoint; procedure SetFileName(const aValue: string ); function ScanForChar( str : string; ch : Char; startPos : Integer; lookFor : Boolean ) : Integer; public constructor Create( const aFileName : string; aHotPoint: TPoint ); procedure LoadFromFile( const aFileName : string ); virtual; abstract; procedure LoadFromStream( aStream : TStream ); virtual; abstract; procedure Show; virtual; abstract; property FileName : string read FFileName write SetFileName; property HotPoint : TPoint read FHotPoint write FHotPoint; end; TSDLXPMCursor = class( TSDLCustomCursor ) private FCursor : PSDL_Cursor; procedure FreeCursor; public destructor Destroy; override; procedure LoadFromFile( const aFileName : string ); override; procedure LoadFromStream( aStream : TStream ); override; procedure Show; override; end; TSDLCursorList = class( TStringList ) protected function GetObject( aIndex : Integer ): TSDLCustomCursor; reintroduce; procedure PutObject( aIndex : Integer; AObject : TSDLCustomCursor); reintroduce; public constructor Create; function AddCursor(const aName : string; aObject : TSDLCustomCursor): Integer; virtual; end; TSDLMouse = class( TSDLCustomInput ) private FDragging : Boolean; FMousePos : TPoint; FOnMouseUp: TSDLMouseButtonEvent; FOnMouseDown: TSDLMouseButtonEvent; FOnMouseMove: TSDLMouseMoveEvent; FOnMouseWheel: TSDLMouseWheelEvent; FCursorList : TSDLCursorList; // Cursor Pointer procedure DoMouseMove( Event: TSDL_Event ); procedure DoMouseDown( Event: TSDL_Event ); procedure DoMouseUp( Event: TSDL_Event ); procedure DoMouseWheelScroll( Event: TSDL_Event ); function GetMousePosition: TPoint; procedure SetMousePosition(const Value: TPoint); function GetMouseDelta: TPoint; public destructor Destroy; override; function UpdateInput( event: TSDL_EVENT ) : Boolean; override; function MouseIsDown( Button : Integer ) : Boolean; function MouseIsUp( Button : Integer ) : Boolean; procedure ShowCursor; procedure HideCursor; property OnMouseDown : TSDLMouseButtonEvent read FOnMouseDown write FOnMouseDown; property OnMouseUp : TSDLMouseButtonEvent read FOnMouseUp write FOnMouseUp; property OnMouseMove : TSDLMouseMoveEvent read FOnMouseMove write FOnMouseMove; property OnMouseWheel : TSDLMouseWheelEvent read FOnMouseWheel write FOnMouseWheel; property MousePosition : TPoint read GetMousePosition write SetMousePosition; property MouseDelta: TPoint read GetMouseDelta; property Cursors : TSDLCursorList read FCursorList write FCursorList; end; TSDLInputManager = class( TObject ) private FKeyBoard : TSDLKeyBoard; FMouse : TSDLMouse; FJoystick : TSDLJoysticks; public constructor Create( InitInputs : TSDLInputTypes ); destructor Destroy; override; procedure Disable( InitInputs : TSDLInputTypes; JoyStickNumber : Integer = 0 ); procedure Enable( InitInputs : TSDLInputTypes; JoyStickNumber : Integer = 0 ); function UpdateInputs( event: TSDL_EVENT ) : Boolean; property KeyBoard : TSDLKeyBoard read FKeyBoard write FKeyBoard; property Mouse : TSDLMouse read FMouse write FMouse; property JoyStick : TSDLJoysticks read FJoyStick write FJoyStick; end; implementation uses SysUtils; { TSDLCustomInput } constructor TSDLCustomInput.Create; begin inherited; FEnabled := true; end; { TSDLJoysticks } constructor TSDLJoysticks.Create; var i : integer; begin inherited; if ( SDL_WasInit( SDL_INIT_JOYSTICK ) = 0 ) then SDL_InitSubSystem( SDL_INIT_JOYSTICK ); FNumOfJoySticks := SDL_NumJoysticks; FJoyStickList := TList.Create; for i := 0 to FNumOfJoySticks - 1 do begin FJoyStickList.Add( TSDLJoyStick.Create( i ) ); end; end; destructor TSDLJoysticks.Destroy; var i : integer; begin if FJoyStickList.Count > 0 then begin for i := 0 to FJoyStickList.Count - 1 do begin TSDLJoyStick( FJoyStickList.Items[i] ).Free; end; end; SDL_QuitSubSystem( SDL_INIT_JOYSTICK ); inherited; end; function TSDLJoySticks.GetJoyStick(Index: integer): TSDLJoyStick; begin Result := TSDLJoyStick( FJoyStickList[ Index ] ); end; procedure TSDLJoySticks.SetJoyStick(Index: integer; const Value: TSDLJoyStick); begin FJoyStickList[ Index ] := @Value; end; function TSDLJoysticks.UpdateInput(event: TSDL_EVENT): Boolean; var i : integer; begin result := false; if FJoyStickList.Count > 0 then begin for i := 0 to FJoyStickList.Count - 1 do begin TSDLJoyStick( FJoyStickList.Items[i] ).UpdateInput( event ); end; end; end; { TSDLKeyBoard } procedure TSDLKeyBoard.DoKeyDown(keysym: PSDL_keysym); begin if Assigned( FOnKeyDown ) then FOnKeyDown( keysym.sym , keysym.modifier, keysym.unicode ); end; procedure TSDLKeyBoard.DoKeyUp(keysym: PSDL_keysym); begin if Assigned( FOnKeyUp ) then FOnKeyUp( keysym.sym , keysym.modifier, keysym.unicode ); end; function TSDLKeyBoard.IsKeyDown( Key: TSDLKey ): Boolean; begin SDL_PumpEvents; // Populate Keys array FKeys := PKeyStateArr( SDL_GetKeyState( nil ) ); Result := ( FKeys[Key] = SDL_PRESSED ); end; function TSDLKeyBoard.IsKeyUp( Key: TSDLKey ): Boolean; begin SDL_PumpEvents; // Populate Keys array FKeys := PKeyStateArr( SDL_GetKeyState( nil ) ); Result := ( FKeys[Key] = SDL_RELEASED ); end; function TSDLKeyBoard.UpdateInput(event: TSDL_EVENT): Boolean; begin result := false; if ( FEnabled ) then begin case event.type_ of SDL_KEYDOWN : begin // handle key presses DoKeyDown( @event.key.keysym ); result := true; end; SDL_KEYUP : begin // handle key releases DoKeyUp( @event.key.keysym ); result := true; end; end; end; end; { TSDLMouse } destructor TSDLMouse.Destroy; begin inherited; end; procedure TSDLMouse.DoMouseDown( Event: TSDL_Event ); var CurrentPos : TPoint; begin FDragging := true; if Assigned( FOnMouseDown ) then begin CurrentPos.x := event.button.x; CurrentPos.y := event.button.y; FOnMouseDown( event.button.button, SDL_GetModState, CurrentPos ); end; end; procedure TSDLMouse.DoMouseMove( Event: TSDL_Event ); var CurrentPos, RelativePos : TPoint; begin if Assigned( FOnMouseMove ) then begin CurrentPos.x := event.motion.x; CurrentPos.y := event.motion.y; RelativePos.x := event.motion.xrel; RelativePos.y := event.motion.yrel; FOnMouseMove( SDL_GetModState, CurrentPos, RelativePos ); end; end; procedure TSDLMouse.DoMouseUp( event: TSDL_EVENT ); var Point : TPoint; begin FDragging := false; if Assigned( FOnMouseUp ) then begin Point.x := event.button.x; Point.y := event.button.y; FOnMouseUp( event.button.button, SDL_GetModState, Point ); end; end; procedure TSDLMouse.DoMouseWheelScroll( event: TSDL_EVENT ); var Point : TPoint; begin if Assigned( FOnMouseWheel ) then begin Point.x := event.button.x; Point.y := event.button.y; if ( event.button.button = SDL_BUTTON_WHEELUP ) then FOnMouseWheel( SDL_BUTTON_WHEELUP, SDL_GetModState, Point ) else FOnMouseWheel( SDL_BUTTON_WHEELDOWN, SDL_GetModState, Point ); end; end; function TSDLMouse.GetMouseDelta: TPoint; begin SDL_PumpEvents; SDL_GetRelativeMouseState( Result.X, Result.Y ); end; function TSDLMouse.GetMousePosition: TPoint; begin SDL_PumpEvents; SDL_GetMouseState( FMousePos.X, FMousePos.Y ); Result := FMousePos; end; procedure TSDLMouse.HideCursor; begin SDL_ShowCursor( SDL_DISABLE ); end; function TSDLMouse.MouseIsDown(Button: Integer): Boolean; begin SDL_PumpEvents; Result := ( SDL_GetMouseState( FMousePos.X, FMousePos.Y ) and SDL_BUTTON( Button ) = 0 ); end; function TSDLMouse.MouseIsUp(Button: Integer): Boolean; begin SDL_PumpEvents; Result := not ( SDL_GetMouseState( FMousePos.X, FMousePos.Y ) and SDL_BUTTON( Button ) = 0 ); end; procedure TSDLMouse.SetMousePosition(const Value: TPoint); begin SDL_WarpMouse( Value.x, Value.y ); end; procedure TSDLMouse.ShowCursor; begin SDL_ShowCursor( SDL_ENABLE ); end; function TSDLMouse.UpdateInput(event: TSDL_EVENT): Boolean; begin result := false; if ( FEnabled ) then begin case event.type_ of SDL_MOUSEMOTION : begin // handle Mouse Move DoMouseMove( event ); end; SDL_MOUSEBUTTONDOWN : begin // handle Mouse Down if ( event.button.button = SDL_BUTTON_WHEELUP ) or ( event.button.button = SDL_BUTTON_WHEELDOWN ) then DoMouseWheelScroll( event ) else DoMouseDown( event ); end; SDL_MOUSEBUTTONUP : begin // handle Mouse Up if ( event.button.button = SDL_BUTTON_WHEELUP ) or ( event.button.button = SDL_BUTTON_WHEELDOWN ) then DoMouseWheelScroll( event ) else DoMouseUp( event ); end; end; end; end; { TSDLInputManager } constructor TSDLInputManager.Create(InitInputs: TSDLInputTypes); begin inherited Create; if itJoystick in InitInputs then FJoystick := TSDLJoysticks.Create; if itKeyBoard in InitInputs then FKeyBoard := TSDLKeyBoard.Create; if itMouse in InitInputs then FMouse := TSDLMouse.Create; end; destructor TSDLInputManager.Destroy; begin if FJoystick <> nil then FreeAndNil( FJoystick ); if FKeyBoard <> nil then FreeAndNil( FKeyBoard ); if FMouse <> nil then FreeAndNil( FMouse ); inherited; end; procedure TSDLInputManager.Disable( InitInputs : TSDLInputTypes; JoyStickNumber : Integer ); begin if itJoystick in InitInputs then FJoystick.JoySticks[ JoyStickNumber ].Enabled := false; if itKeyBoard in InitInputs then FKeyBoard.Enabled := false; if itMouse in InitInputs then FMouse.Enabled := false; end; procedure TSDLInputManager.Enable( InitInputs: TSDLInputTypes; JoyStickNumber: Integer ); begin if itJoystick in InitInputs then FJoystick.JoySticks[ JoyStickNumber ].Enabled := true; if itKeyBoard in InitInputs then FKeyBoard.Enabled := true; if itMouse in InitInputs then FMouse.Enabled := true; end; function TSDLInputManager.UpdateInputs( event: TSDL_EVENT ): Boolean; begin Result := false; if ( FJoystick <> nil ) then Result := FJoystick.UpdateInput( event ); if ( FKeyBoard <> nil ) then Result := FKeyBoard.UpdateInput( event ); if ( FMouse <> nil ) then Result := FMouse.UpdateInput( event ); end; { TSDLJoyStick } procedure TSDLJoyStick.Close; begin SDL_JoystickClose( @FJoystick ); end; constructor TSDLJoyStick.Create( Index : Integer ); begin inherited Create; FJoystick := nil; FJoystickIndex := Index; end; destructor TSDLJoyStick.Destroy; begin if FJoystick <> nil then Close; inherited; end; procedure TSDLJoyStick.DoAxisMove(Event: TSDL_Event); begin if Assigned( FJoyAxisMoveEvent ) then begin FJoyAxisMoveEvent( Event.jaxis.which, Event.jaxis.axis, Event.jaxis.value ); end end; procedure TSDLJoyStick.DoBallMove(Event: TSDL_Event); var BallPoint : TPoint; begin if Assigned( FJoyBallMoveEvent ) then begin BallPoint.x := Event.jball.xrel; BallPoint.y := Event.jball.yrel; FJoyBallMoveEvent( Event.jball.which, Event.jball.ball, BallPoint ); end; end; procedure TSDLJoyStick.DoButtonDown(Event: TSDL_Event); begin if Assigned( FJoyButtonDownEvent ) then begin if ( Event.jbutton.state = SDL_PRESSED ) then FJoyButtonDownEvent( Event.jbutton.which, Event.jbutton.button, Event.jbutton.state ); end; end; procedure TSDLJoyStick.DoButtonUp(Event: TSDL_Event); begin if Assigned( FJoyButtonUpEvent ) then begin if ( Event.jbutton.state = SDL_RELEASED ) then FJoyButtonUpEvent( Event.jbutton.which, Event.jbutton.button, Event.jbutton.state ); end end; procedure TSDLJoyStick.DoHatMove(Event: TSDL_Event); begin if Assigned( FJoyHatMoveEvent ) then begin FJoyHatMoveEvent( Event.jhat.which, Event.jhat.hat, Event.jhat.value ); end; end; function TSDLJoyStick.GetName: PChar; begin result := FJoystick.name; end; function TSDLJoyStick.GetNumAxes: integer; begin result := FJoystick.naxes; end; function TSDLJoyStick.GetNumBalls: integer; begin result := FJoystick.nballs; end; function TSDLJoyStick.GetNumButtons: integer; begin result := FJoystick.nbuttons; end; function TSDLJoyStick.GetNumHats: integer; begin result := FJoystick.nhats; end; procedure TSDLJoyStick.Open; begin FJoystick := SDL_JoyStickOpen( FJoystickIndex ); end; function TSDLJoyStick.UpdateInput(Event: TSDL_EVENT): Boolean; begin Result := false; if ( FEnabled ) then begin case event.type_ of SDL_JOYAXISMOTION : begin DoAxisMove( Event ); end; SDL_JOYBALLMOTION : begin DoBallMove( Event ); end; SDL_JOYHATMOTION : begin DoHatMove( Event ); end; SDL_JOYBUTTONDOWN : begin DoButtonDown( Event ); end; SDL_JOYBUTTONUP : begin DoButtonUp( Event ); end; end; end; end; { TSDLCustomCursor } constructor TSDLCustomCursor.Create(const aFileName: string; aHotPoint: TPoint); begin inherited Create; FHotPoint := aHotPoint; LoadFromFile( aFileName ); end; function TSDLCustomCursor.ScanForChar(str: string; ch: Char; startPos: Integer; lookFor: Boolean): Integer; begin Result := -1; while ( ( ( str[ startPos ] = ch ) <> lookFor ) and ( startPos < Length( str ) ) ) do inc( startPos ); if startPos <> Length( str ) then Result := startPos; end; procedure TSDLCustomCursor.SetFileName(const aValue: string); begin LoadFromFile( aValue ); end; { TSDLXPMCursor } destructor TSDLXPMCursor.Destroy; begin FreeCursor; inherited; end; procedure TSDLXPMCursor.FreeCursor; begin if FCursor <> nil then begin SDL_FreeCursor( FCursor ); FFileName := ''; end; end; procedure TSDLXPMCursor.LoadFromFile(const aFileName: string); var xpmFile : Textfile; step : Integer; holdPos : Integer; counter : Integer; dimensions : array[ 1..3 ] of Integer; clr, clrNone, clrBlack, clrWhite : Char; data, mask : array of UInt8; i, col : Integer; LineString : string; begin FreeCursor; AssignFile( xpmFile, aFileName ); Reset( xpmFile ); step := 0; i := -1; clrBlack := 'X'; clrWhite := ','; clrNone := ' '; counter := 0; while not ( eof( xpmFile ) ) do begin Readln( xpmFile, LineString ); // scan for strings if LineString[ 1 ] = '"' then begin case step of 0 : // Get dimensions (should be width height number-of-colors ???) begin HoldPos := 2; counter := ScanForChar( LineString, ' ', HoldPos, False ); counter := ScanForChar( LineString, ' ', counter, True ); dimensions[ 1 ] := StrToInt( Copy( LineString, HoldPos, counter - HoldPos ) ); counter := ScanForChar( LineString, ' ', counter, False ); holdPos := counter; counter := ScanForChar( LineString, ' ', counter, True ); dimensions[ 2 ] := StrToInt( Copy( LineString, holdPos, counter - HoldPos ) ); counter := ScanForChar( LineString, ' ', counter, False ); holdPos := counter; counter := ScanForChar( LineString, ' ', counter, True ); dimensions[ 3 ] := StrToInt( Copy( LineString, holdPos, counter - HoldPos ) ); step := 1; SetLength( data, ( dimensions[ 1 ] * dimensions[ 2 ] ) div 8 ); SetLength( mask, ( dimensions[ 1 ] * dimensions[ 2 ] ) div 8 ); //Log.LogStatus( 'Length = ' + IntToStr( ( dimensions[ 1 ] * dimensions[ 2 ] ) div 8 ), 'LoadCursorFromFile' ); end; 1 : // get the symbols for transparent, black and white begin // get the symbol for the color clr := LineString[ 2 ]; // look for the 'c' symbol counter := ScanForChar( LineString, 'c', 3, True ); inc( counter ); counter := ScanForChar( LineString, ' ', counter, False ); if LowerCase( Copy( LineString, counter, 4 ) ) = 'none' then begin clrNone := clr; end; if LowerCase( Copy( LineString, counter, 7 ) ) = '#ffffff' then begin clrWhite := clr; end; if LowerCase( Copy( LineString, counter, 7 ) ) = '#000000' then begin clrBlack := clr; end; dec( dimensions[ 3 ] ); if dimensions[ 3 ] = 0 then begin step := 2; counter := 0; end; end; 2 : // get cursor information -- modified from the SDL // documentation of SDL_CreateCursor. begin for col := 1 to dimensions[1] do begin if ( ( col mod 8 ) <> 1 ) then begin data[ i ] := data[ i ] shl 1; mask[ i ] := mask[ i ] shl 1; end else begin inc( i ); data[ i ] := 0; mask[ i ] := 0; end; if LineString[ col ] = clrWhite then begin mask[ i ] := mask[ i ] or $01; end else if LineString[ col ] = clrBlack then begin data[ i ] := data[ i ] or $01; mask[ i ] := mask[ i ] or $01; end else if LineString[ col + 1 ] = clrNone then begin // end; end; inc(counter); if counter = dimensions[2] then step := 4; end; end; end; end; CloseFile( xpmFile ); FCursor := SDL_CreateCursor( PUInt8( data ), PUInt8( mask ), dimensions[ 1 ], dimensions[ 2 ], FHotPoint.x, FHotPoint.y ); end; procedure TSDLXPMCursor.LoadFromStream(aStream: TStream); begin inherited; end; procedure TSDLXPMCursor.Show; begin inherited; SDL_SetCursor( FCursor ); end; { TSDLCursorList } function TSDLCursorList.AddCursor(const aName : string; aObject : TSDLCustomCursor): Integer; begin result := inherited AddObject( aName, aObject ); end; constructor TSDLCursorList.Create; begin inherited; Duplicates := dupIgnore; end; function TSDLCursorList.GetObject(aIndex: Integer): TSDLCustomCursor; begin result := TSDLCustomCursor( inherited GetObject( aIndex ) ); end; procedure TSDLCursorList.PutObject(aIndex: Integer; aObject: TSDLCustomCursor); begin inherited PutObject( aIndex, aObject ); end; end.
{$include lem_directives.inc} unit LemMetaPiece; interface uses Classes; type TMetaPiece = class private protected fWidth : Integer; fHeight : Integer; procedure Error(const S: string); virtual; public procedure LoadFromStream(S: TStream); virtual; published property Width : Integer read fWidth write fWidth; property Height : Integer read fHeight write fHeight; end; implementation uses Lemstrings, LemMisc; { TMetaPiece } procedure TMetaPiece.Error(const S: string); begin raise ELemmixError.Create(S); end; procedure TMetaPiece.LoadFromStream(S: TStream); begin Error(SMetaPieceLoadError); end; end.